xref: /OK3568_Linux_fs/kernel/arch/x86/events/amd/ibs.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1 /*
2  * Performance events - AMD IBS
3  *
4  *  Copyright (C) 2011 Advanced Micro Devices, Inc., Robert Richter
5  *
6  *  For licencing details see kernel-base/COPYING
7  */
8 
9 #include <linux/perf_event.h>
10 #include <linux/init.h>
11 #include <linux/export.h>
12 #include <linux/pci.h>
13 #include <linux/ptrace.h>
14 #include <linux/syscore_ops.h>
15 #include <linux/sched/clock.h>
16 
17 #include <asm/apic.h>
18 
19 #include "../perf_event.h"
20 
21 static u32 ibs_caps;
22 
23 #if defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD)
24 
25 #include <linux/kprobes.h>
26 #include <linux/hardirq.h>
27 
28 #include <asm/nmi.h>
29 
30 #define IBS_FETCH_CONFIG_MASK	(IBS_FETCH_RAND_EN | IBS_FETCH_MAX_CNT)
31 #define IBS_OP_CONFIG_MASK	IBS_OP_MAX_CNT
32 
33 
34 /*
35  * IBS states:
36  *
37  * ENABLED; tracks the pmu::add(), pmu::del() state, when set the counter is taken
38  * and any further add()s must fail.
39  *
40  * STARTED/STOPPING/STOPPED; deal with pmu::start(), pmu::stop() state but are
41  * complicated by the fact that the IBS hardware can send late NMIs (ie. after
42  * we've cleared the EN bit).
43  *
44  * In order to consume these late NMIs we have the STOPPED state, any NMI that
45  * happens after we've cleared the EN state will clear this bit and report the
46  * NMI handled (this is fundamentally racy in the face or multiple NMI sources,
47  * someone else can consume our BIT and our NMI will go unhandled).
48  *
49  * And since we cannot set/clear this separate bit together with the EN bit,
50  * there are races; if we cleared STARTED early, an NMI could land in
51  * between clearing STARTED and clearing the EN bit (in fact multiple NMIs
52  * could happen if the period is small enough), and consume our STOPPED bit
53  * and trigger streams of unhandled NMIs.
54  *
55  * If, however, we clear STARTED late, an NMI can hit between clearing the
56  * EN bit and clearing STARTED, still see STARTED set and process the event.
57  * If this event will have the VALID bit clear, we bail properly, but this
58  * is not a given. With VALID set we can end up calling pmu::stop() again
59  * (the throttle logic) and trigger the WARNs in there.
60  *
61  * So what we do is set STOPPING before clearing EN to avoid the pmu::stop()
62  * nesting, and clear STARTED late, so that we have a well defined state over
63  * the clearing of the EN bit.
64  *
65  * XXX: we could probably be using !atomic bitops for all this.
66  */
67 
68 enum ibs_states {
69 	IBS_ENABLED	= 0,
70 	IBS_STARTED	= 1,
71 	IBS_STOPPING	= 2,
72 	IBS_STOPPED	= 3,
73 
74 	IBS_MAX_STATES,
75 };
76 
77 struct cpu_perf_ibs {
78 	struct perf_event	*event;
79 	unsigned long		state[BITS_TO_LONGS(IBS_MAX_STATES)];
80 };
81 
82 struct perf_ibs {
83 	struct pmu			pmu;
84 	unsigned int			msr;
85 	u64				config_mask;
86 	u64				cnt_mask;
87 	u64				enable_mask;
88 	u64				valid_mask;
89 	u64				max_period;
90 	unsigned long			offset_mask[1];
91 	int				offset_max;
92 	unsigned int			fetch_count_reset_broken : 1;
93 	unsigned int			fetch_ignore_if_zero_rip : 1;
94 	struct cpu_perf_ibs __percpu	*pcpu;
95 
96 	struct attribute		**format_attrs;
97 	struct attribute_group		format_group;
98 	const struct attribute_group	*attr_groups[2];
99 
100 	u64				(*get_count)(u64 config);
101 };
102 
103 struct perf_ibs_data {
104 	u32		size;
105 	union {
106 		u32	data[0];	/* data buffer starts here */
107 		u32	caps;
108 	};
109 	u64		regs[MSR_AMD64_IBS_REG_COUNT_MAX];
110 };
111 
112 static int
perf_event_set_period(struct hw_perf_event * hwc,u64 min,u64 max,u64 * hw_period)113 perf_event_set_period(struct hw_perf_event *hwc, u64 min, u64 max, u64 *hw_period)
114 {
115 	s64 left = local64_read(&hwc->period_left);
116 	s64 period = hwc->sample_period;
117 	int overflow = 0;
118 
119 	/*
120 	 * If we are way outside a reasonable range then just skip forward:
121 	 */
122 	if (unlikely(left <= -period)) {
123 		left = period;
124 		local64_set(&hwc->period_left, left);
125 		hwc->last_period = period;
126 		overflow = 1;
127 	}
128 
129 	if (unlikely(left < (s64)min)) {
130 		left += period;
131 		local64_set(&hwc->period_left, left);
132 		hwc->last_period = period;
133 		overflow = 1;
134 	}
135 
136 	/*
137 	 * If the hw period that triggers the sw overflow is too short
138 	 * we might hit the irq handler. This biases the results.
139 	 * Thus we shorten the next-to-last period and set the last
140 	 * period to the max period.
141 	 */
142 	if (left > max) {
143 		left -= max;
144 		if (left > max)
145 			left = max;
146 		else if (left < min)
147 			left = min;
148 	}
149 
150 	*hw_period = (u64)left;
151 
152 	return overflow;
153 }
154 
155 static  int
perf_event_try_update(struct perf_event * event,u64 new_raw_count,int width)156 perf_event_try_update(struct perf_event *event, u64 new_raw_count, int width)
157 {
158 	struct hw_perf_event *hwc = &event->hw;
159 	int shift = 64 - width;
160 	u64 prev_raw_count;
161 	u64 delta;
162 
163 	/*
164 	 * Careful: an NMI might modify the previous event value.
165 	 *
166 	 * Our tactic to handle this is to first atomically read and
167 	 * exchange a new raw count - then add that new-prev delta
168 	 * count to the generic event atomically:
169 	 */
170 	prev_raw_count = local64_read(&hwc->prev_count);
171 	if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
172 					new_raw_count) != prev_raw_count)
173 		return 0;
174 
175 	/*
176 	 * Now we have the new raw value and have updated the prev
177 	 * timestamp already. We can now calculate the elapsed delta
178 	 * (event-)time and add that to the generic event.
179 	 *
180 	 * Careful, not all hw sign-extends above the physical width
181 	 * of the count.
182 	 */
183 	delta = (new_raw_count << shift) - (prev_raw_count << shift);
184 	delta >>= shift;
185 
186 	local64_add(delta, &event->count);
187 	local64_sub(delta, &hwc->period_left);
188 
189 	return 1;
190 }
191 
192 static struct perf_ibs perf_ibs_fetch;
193 static struct perf_ibs perf_ibs_op;
194 
get_ibs_pmu(int type)195 static struct perf_ibs *get_ibs_pmu(int type)
196 {
197 	if (perf_ibs_fetch.pmu.type == type)
198 		return &perf_ibs_fetch;
199 	if (perf_ibs_op.pmu.type == type)
200 		return &perf_ibs_op;
201 	return NULL;
202 }
203 
204 /*
205  * Use IBS for precise event sampling:
206  *
207  *  perf record -a -e cpu-cycles:p ...    # use ibs op counting cycle count
208  *  perf record -a -e r076:p ...          # same as -e cpu-cycles:p
209  *  perf record -a -e r0C1:p ...          # use ibs op counting micro-ops
210  *
211  * IbsOpCntCtl (bit 19) of IBS Execution Control Register (IbsOpCtl,
212  * MSRC001_1033) is used to select either cycle or micro-ops counting
213  * mode.
214  *
215  * The rip of IBS samples has skid 0. Thus, IBS supports precise
216  * levels 1 and 2 and the PERF_EFLAGS_EXACT is set. In rare cases the
217  * rip is invalid when IBS was not able to record the rip correctly.
218  * We clear PERF_EFLAGS_EXACT and take the rip from pt_regs then.
219  *
220  */
perf_ibs_precise_event(struct perf_event * event,u64 * config)221 static int perf_ibs_precise_event(struct perf_event *event, u64 *config)
222 {
223 	switch (event->attr.precise_ip) {
224 	case 0:
225 		return -ENOENT;
226 	case 1:
227 	case 2:
228 		break;
229 	default:
230 		return -EOPNOTSUPP;
231 	}
232 
233 	switch (event->attr.type) {
234 	case PERF_TYPE_HARDWARE:
235 		switch (event->attr.config) {
236 		case PERF_COUNT_HW_CPU_CYCLES:
237 			*config = 0;
238 			return 0;
239 		}
240 		break;
241 	case PERF_TYPE_RAW:
242 		switch (event->attr.config) {
243 		case 0x0076:
244 			*config = 0;
245 			return 0;
246 		case 0x00C1:
247 			*config = IBS_OP_CNT_CTL;
248 			return 0;
249 		}
250 		break;
251 	default:
252 		return -ENOENT;
253 	}
254 
255 	return -EOPNOTSUPP;
256 }
257 
perf_ibs_init(struct perf_event * event)258 static int perf_ibs_init(struct perf_event *event)
259 {
260 	struct hw_perf_event *hwc = &event->hw;
261 	struct perf_ibs *perf_ibs;
262 	u64 max_cnt, config;
263 	int ret;
264 
265 	perf_ibs = get_ibs_pmu(event->attr.type);
266 	if (perf_ibs) {
267 		config = event->attr.config;
268 	} else {
269 		perf_ibs = &perf_ibs_op;
270 		ret = perf_ibs_precise_event(event, &config);
271 		if (ret)
272 			return ret;
273 	}
274 
275 	if (event->pmu != &perf_ibs->pmu)
276 		return -ENOENT;
277 
278 	if (config & ~perf_ibs->config_mask)
279 		return -EINVAL;
280 
281 	if (hwc->sample_period) {
282 		if (config & perf_ibs->cnt_mask)
283 			/* raw max_cnt may not be set */
284 			return -EINVAL;
285 		if (!event->attr.sample_freq && hwc->sample_period & 0x0f)
286 			/*
287 			 * lower 4 bits can not be set in ibs max cnt,
288 			 * but allowing it in case we adjust the
289 			 * sample period to set a frequency.
290 			 */
291 			return -EINVAL;
292 		hwc->sample_period &= ~0x0FULL;
293 		if (!hwc->sample_period)
294 			hwc->sample_period = 0x10;
295 	} else {
296 		max_cnt = config & perf_ibs->cnt_mask;
297 		config &= ~perf_ibs->cnt_mask;
298 		event->attr.sample_period = max_cnt << 4;
299 		hwc->sample_period = event->attr.sample_period;
300 	}
301 
302 	if (!hwc->sample_period)
303 		return -EINVAL;
304 
305 	/*
306 	 * If we modify hwc->sample_period, we also need to update
307 	 * hwc->last_period and hwc->period_left.
308 	 */
309 	hwc->last_period = hwc->sample_period;
310 	local64_set(&hwc->period_left, hwc->sample_period);
311 
312 	hwc->config_base = perf_ibs->msr;
313 	hwc->config = config;
314 
315 	/*
316 	 * rip recorded by IbsOpRip will not be consistent with rsp and rbp
317 	 * recorded as part of interrupt regs. Thus we need to use rip from
318 	 * interrupt regs while unwinding call stack. Setting _EARLY flag
319 	 * makes sure we unwind call-stack before perf sample rip is set to
320 	 * IbsOpRip.
321 	 */
322 	if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
323 		event->attr.sample_type |= __PERF_SAMPLE_CALLCHAIN_EARLY;
324 
325 	return 0;
326 }
327 
perf_ibs_set_period(struct perf_ibs * perf_ibs,struct hw_perf_event * hwc,u64 * period)328 static int perf_ibs_set_period(struct perf_ibs *perf_ibs,
329 			       struct hw_perf_event *hwc, u64 *period)
330 {
331 	int overflow;
332 
333 	/* ignore lower 4 bits in min count: */
334 	overflow = perf_event_set_period(hwc, 1<<4, perf_ibs->max_period, period);
335 	local64_set(&hwc->prev_count, 0);
336 
337 	return overflow;
338 }
339 
get_ibs_fetch_count(u64 config)340 static u64 get_ibs_fetch_count(u64 config)
341 {
342 	return (config & IBS_FETCH_CNT) >> 12;
343 }
344 
get_ibs_op_count(u64 config)345 static u64 get_ibs_op_count(u64 config)
346 {
347 	u64 count = 0;
348 
349 	/*
350 	 * If the internal 27-bit counter rolled over, the count is MaxCnt
351 	 * and the lower 7 bits of CurCnt are randomized.
352 	 * Otherwise CurCnt has the full 27-bit current counter value.
353 	 */
354 	if (config & IBS_OP_VAL) {
355 		count = (config & IBS_OP_MAX_CNT) << 4;
356 		if (ibs_caps & IBS_CAPS_OPCNTEXT)
357 			count += config & IBS_OP_MAX_CNT_EXT_MASK;
358 	} else if (ibs_caps & IBS_CAPS_RDWROPCNT) {
359 		count = (config & IBS_OP_CUR_CNT) >> 32;
360 	}
361 
362 	return count;
363 }
364 
365 static void
perf_ibs_event_update(struct perf_ibs * perf_ibs,struct perf_event * event,u64 * config)366 perf_ibs_event_update(struct perf_ibs *perf_ibs, struct perf_event *event,
367 		      u64 *config)
368 {
369 	u64 count = perf_ibs->get_count(*config);
370 
371 	/*
372 	 * Set width to 64 since we do not overflow on max width but
373 	 * instead on max count. In perf_ibs_set_period() we clear
374 	 * prev count manually on overflow.
375 	 */
376 	while (!perf_event_try_update(event, count, 64)) {
377 		rdmsrl(event->hw.config_base, *config);
378 		count = perf_ibs->get_count(*config);
379 	}
380 }
381 
perf_ibs_enable_event(struct perf_ibs * perf_ibs,struct hw_perf_event * hwc,u64 config)382 static inline void perf_ibs_enable_event(struct perf_ibs *perf_ibs,
383 					 struct hw_perf_event *hwc, u64 config)
384 {
385 	u64 tmp = hwc->config | config;
386 
387 	if (perf_ibs->fetch_count_reset_broken)
388 		wrmsrl(hwc->config_base, tmp & ~perf_ibs->enable_mask);
389 
390 	wrmsrl(hwc->config_base, tmp | perf_ibs->enable_mask);
391 }
392 
393 /*
394  * Erratum #420 Instruction-Based Sampling Engine May Generate
395  * Interrupt that Cannot Be Cleared:
396  *
397  * Must clear counter mask first, then clear the enable bit. See
398  * Revision Guide for AMD Family 10h Processors, Publication #41322.
399  */
perf_ibs_disable_event(struct perf_ibs * perf_ibs,struct hw_perf_event * hwc,u64 config)400 static inline void perf_ibs_disable_event(struct perf_ibs *perf_ibs,
401 					  struct hw_perf_event *hwc, u64 config)
402 {
403 	config &= ~perf_ibs->cnt_mask;
404 	if (boot_cpu_data.x86 == 0x10)
405 		wrmsrl(hwc->config_base, config);
406 	config &= ~perf_ibs->enable_mask;
407 	wrmsrl(hwc->config_base, config);
408 }
409 
410 /*
411  * We cannot restore the ibs pmu state, so we always needs to update
412  * the event while stopping it and then reset the state when starting
413  * again. Thus, ignoring PERF_EF_RELOAD and PERF_EF_UPDATE flags in
414  * perf_ibs_start()/perf_ibs_stop() and instead always do it.
415  */
perf_ibs_start(struct perf_event * event,int flags)416 static void perf_ibs_start(struct perf_event *event, int flags)
417 {
418 	struct hw_perf_event *hwc = &event->hw;
419 	struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
420 	struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
421 	u64 period, config = 0;
422 
423 	if (WARN_ON_ONCE(!(hwc->state & PERF_HES_STOPPED)))
424 		return;
425 
426 	WARN_ON_ONCE(!(hwc->state & PERF_HES_UPTODATE));
427 	hwc->state = 0;
428 
429 	perf_ibs_set_period(perf_ibs, hwc, &period);
430 	if (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_OPCNTEXT)) {
431 		config |= period & IBS_OP_MAX_CNT_EXT_MASK;
432 		period &= ~IBS_OP_MAX_CNT_EXT_MASK;
433 	}
434 	config |= period >> 4;
435 
436 	/*
437 	 * Set STARTED before enabling the hardware, such that a subsequent NMI
438 	 * must observe it.
439 	 */
440 	set_bit(IBS_STARTED,    pcpu->state);
441 	clear_bit(IBS_STOPPING, pcpu->state);
442 	perf_ibs_enable_event(perf_ibs, hwc, config);
443 
444 	perf_event_update_userpage(event);
445 }
446 
perf_ibs_stop(struct perf_event * event,int flags)447 static void perf_ibs_stop(struct perf_event *event, int flags)
448 {
449 	struct hw_perf_event *hwc = &event->hw;
450 	struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
451 	struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
452 	u64 config;
453 	int stopping;
454 
455 	if (test_and_set_bit(IBS_STOPPING, pcpu->state))
456 		return;
457 
458 	stopping = test_bit(IBS_STARTED, pcpu->state);
459 
460 	if (!stopping && (hwc->state & PERF_HES_UPTODATE))
461 		return;
462 
463 	rdmsrl(hwc->config_base, config);
464 
465 	if (stopping) {
466 		/*
467 		 * Set STOPPED before disabling the hardware, such that it
468 		 * must be visible to NMIs the moment we clear the EN bit,
469 		 * at which point we can generate an !VALID sample which
470 		 * we need to consume.
471 		 */
472 		set_bit(IBS_STOPPED, pcpu->state);
473 		perf_ibs_disable_event(perf_ibs, hwc, config);
474 		/*
475 		 * Clear STARTED after disabling the hardware; if it were
476 		 * cleared before an NMI hitting after the clear but before
477 		 * clearing the EN bit might think it a spurious NMI and not
478 		 * handle it.
479 		 *
480 		 * Clearing it after, however, creates the problem of the NMI
481 		 * handler seeing STARTED but not having a valid sample.
482 		 */
483 		clear_bit(IBS_STARTED, pcpu->state);
484 		WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
485 		hwc->state |= PERF_HES_STOPPED;
486 	}
487 
488 	if (hwc->state & PERF_HES_UPTODATE)
489 		return;
490 
491 	/*
492 	 * Clear valid bit to not count rollovers on update, rollovers
493 	 * are only updated in the irq handler.
494 	 */
495 	config &= ~perf_ibs->valid_mask;
496 
497 	perf_ibs_event_update(perf_ibs, event, &config);
498 	hwc->state |= PERF_HES_UPTODATE;
499 }
500 
perf_ibs_add(struct perf_event * event,int flags)501 static int perf_ibs_add(struct perf_event *event, int flags)
502 {
503 	struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
504 	struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
505 
506 	if (test_and_set_bit(IBS_ENABLED, pcpu->state))
507 		return -ENOSPC;
508 
509 	event->hw.state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
510 
511 	pcpu->event = event;
512 
513 	if (flags & PERF_EF_START)
514 		perf_ibs_start(event, PERF_EF_RELOAD);
515 
516 	return 0;
517 }
518 
perf_ibs_del(struct perf_event * event,int flags)519 static void perf_ibs_del(struct perf_event *event, int flags)
520 {
521 	struct perf_ibs *perf_ibs = container_of(event->pmu, struct perf_ibs, pmu);
522 	struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
523 
524 	if (!test_and_clear_bit(IBS_ENABLED, pcpu->state))
525 		return;
526 
527 	perf_ibs_stop(event, PERF_EF_UPDATE);
528 
529 	pcpu->event = NULL;
530 
531 	perf_event_update_userpage(event);
532 }
533 
perf_ibs_read(struct perf_event * event)534 static void perf_ibs_read(struct perf_event *event) { }
535 
536 PMU_FORMAT_ATTR(rand_en,	"config:57");
537 PMU_FORMAT_ATTR(cnt_ctl,	"config:19");
538 
539 static struct attribute *ibs_fetch_format_attrs[] = {
540 	&format_attr_rand_en.attr,
541 	NULL,
542 };
543 
544 static struct attribute *ibs_op_format_attrs[] = {
545 	NULL,	/* &format_attr_cnt_ctl.attr if IBS_CAPS_OPCNT */
546 	NULL,
547 };
548 
549 static struct perf_ibs perf_ibs_fetch = {
550 	.pmu = {
551 		.task_ctx_nr	= perf_invalid_context,
552 
553 		.event_init	= perf_ibs_init,
554 		.add		= perf_ibs_add,
555 		.del		= perf_ibs_del,
556 		.start		= perf_ibs_start,
557 		.stop		= perf_ibs_stop,
558 		.read		= perf_ibs_read,
559 		.capabilities	= PERF_PMU_CAP_NO_EXCLUDE,
560 	},
561 	.msr			= MSR_AMD64_IBSFETCHCTL,
562 	.config_mask		= IBS_FETCH_CONFIG_MASK,
563 	.cnt_mask		= IBS_FETCH_MAX_CNT,
564 	.enable_mask		= IBS_FETCH_ENABLE,
565 	.valid_mask		= IBS_FETCH_VAL,
566 	.max_period		= IBS_FETCH_MAX_CNT << 4,
567 	.offset_mask		= { MSR_AMD64_IBSFETCH_REG_MASK },
568 	.offset_max		= MSR_AMD64_IBSFETCH_REG_COUNT,
569 	.format_attrs		= ibs_fetch_format_attrs,
570 
571 	.get_count		= get_ibs_fetch_count,
572 };
573 
574 static struct perf_ibs perf_ibs_op = {
575 	.pmu = {
576 		.task_ctx_nr	= perf_invalid_context,
577 
578 		.event_init	= perf_ibs_init,
579 		.add		= perf_ibs_add,
580 		.del		= perf_ibs_del,
581 		.start		= perf_ibs_start,
582 		.stop		= perf_ibs_stop,
583 		.read		= perf_ibs_read,
584 		.capabilities	= PERF_PMU_CAP_NO_EXCLUDE,
585 	},
586 	.msr			= MSR_AMD64_IBSOPCTL,
587 	.config_mask		= IBS_OP_CONFIG_MASK,
588 	.cnt_mask		= IBS_OP_MAX_CNT | IBS_OP_CUR_CNT |
589 				  IBS_OP_CUR_CNT_RAND,
590 	.enable_mask		= IBS_OP_ENABLE,
591 	.valid_mask		= IBS_OP_VAL,
592 	.max_period		= IBS_OP_MAX_CNT << 4,
593 	.offset_mask		= { MSR_AMD64_IBSOP_REG_MASK },
594 	.offset_max		= MSR_AMD64_IBSOP_REG_COUNT,
595 	.format_attrs		= ibs_op_format_attrs,
596 
597 	.get_count		= get_ibs_op_count,
598 };
599 
perf_ibs_handle_irq(struct perf_ibs * perf_ibs,struct pt_regs * iregs)600 static int perf_ibs_handle_irq(struct perf_ibs *perf_ibs, struct pt_regs *iregs)
601 {
602 	struct cpu_perf_ibs *pcpu = this_cpu_ptr(perf_ibs->pcpu);
603 	struct perf_event *event = pcpu->event;
604 	struct hw_perf_event *hwc;
605 	struct perf_sample_data data;
606 	struct perf_raw_record raw;
607 	struct pt_regs regs;
608 	struct perf_ibs_data ibs_data;
609 	int offset, size, check_rip, offset_max, throttle = 0;
610 	unsigned int msr;
611 	u64 *buf, *config, period, new_config = 0;
612 
613 	if (!test_bit(IBS_STARTED, pcpu->state)) {
614 fail:
615 		/*
616 		 * Catch spurious interrupts after stopping IBS: After
617 		 * disabling IBS there could be still incoming NMIs
618 		 * with samples that even have the valid bit cleared.
619 		 * Mark all this NMIs as handled.
620 		 */
621 		if (test_and_clear_bit(IBS_STOPPED, pcpu->state))
622 			return 1;
623 
624 		return 0;
625 	}
626 
627 	if (WARN_ON_ONCE(!event))
628 		goto fail;
629 
630 	hwc = &event->hw;
631 	msr = hwc->config_base;
632 	buf = ibs_data.regs;
633 	rdmsrl(msr, *buf);
634 	if (!(*buf++ & perf_ibs->valid_mask))
635 		goto fail;
636 
637 	config = &ibs_data.regs[0];
638 	perf_ibs_event_update(perf_ibs, event, config);
639 	perf_sample_data_init(&data, 0, hwc->last_period);
640 	if (!perf_ibs_set_period(perf_ibs, hwc, &period))
641 		goto out;	/* no sw counter overflow */
642 
643 	ibs_data.caps = ibs_caps;
644 	size = 1;
645 	offset = 1;
646 	check_rip = (perf_ibs == &perf_ibs_op && (ibs_caps & IBS_CAPS_RIPINVALIDCHK));
647 	if (event->attr.sample_type & PERF_SAMPLE_RAW)
648 		offset_max = perf_ibs->offset_max;
649 	else if (check_rip)
650 		offset_max = 3;
651 	else
652 		offset_max = 1;
653 	do {
654 		rdmsrl(msr + offset, *buf++);
655 		size++;
656 		offset = find_next_bit(perf_ibs->offset_mask,
657 				       perf_ibs->offset_max,
658 				       offset + 1);
659 	} while (offset < offset_max);
660 	/*
661 	 * Read IbsBrTarget, IbsOpData4, and IbsExtdCtl separately
662 	 * depending on their availability.
663 	 * Can't add to offset_max as they are staggered
664 	 */
665 	if (event->attr.sample_type & PERF_SAMPLE_RAW) {
666 		if (perf_ibs == &perf_ibs_op) {
667 			if (ibs_caps & IBS_CAPS_BRNTRGT) {
668 				rdmsrl(MSR_AMD64_IBSBRTARGET, *buf++);
669 				size++;
670 			}
671 			if (ibs_caps & IBS_CAPS_OPDATA4) {
672 				rdmsrl(MSR_AMD64_IBSOPDATA4, *buf++);
673 				size++;
674 			}
675 		}
676 		if (perf_ibs == &perf_ibs_fetch && (ibs_caps & IBS_CAPS_FETCHCTLEXTD)) {
677 			rdmsrl(MSR_AMD64_ICIBSEXTDCTL, *buf++);
678 			size++;
679 		}
680 	}
681 	ibs_data.size = sizeof(u64) * size;
682 
683 	regs = *iregs;
684 	if (check_rip && (ibs_data.regs[2] & IBS_RIP_INVALID)) {
685 		regs.flags &= ~PERF_EFLAGS_EXACT;
686 	} else {
687 		/* Workaround for erratum #1197 */
688 		if (perf_ibs->fetch_ignore_if_zero_rip && !(ibs_data.regs[1]))
689 			goto out;
690 
691 		set_linear_ip(&regs, ibs_data.regs[1]);
692 		regs.flags |= PERF_EFLAGS_EXACT;
693 	}
694 
695 	if (event->attr.sample_type & PERF_SAMPLE_RAW) {
696 		raw = (struct perf_raw_record){
697 			.frag = {
698 				.size = sizeof(u32) + ibs_data.size,
699 				.data = ibs_data.data,
700 			},
701 		};
702 		data.raw = &raw;
703 	}
704 
705 	/*
706 	 * rip recorded by IbsOpRip will not be consistent with rsp and rbp
707 	 * recorded as part of interrupt regs. Thus we need to use rip from
708 	 * interrupt regs while unwinding call stack.
709 	 */
710 	if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
711 		data.callchain = perf_callchain(event, iregs);
712 
713 	throttle = perf_event_overflow(event, &data, &regs);
714 out:
715 	if (throttle) {
716 		perf_ibs_stop(event, 0);
717 	} else {
718 		if (perf_ibs == &perf_ibs_op) {
719 			if (ibs_caps & IBS_CAPS_OPCNTEXT) {
720 				new_config = period & IBS_OP_MAX_CNT_EXT_MASK;
721 				period &= ~IBS_OP_MAX_CNT_EXT_MASK;
722 			}
723 			if ((ibs_caps & IBS_CAPS_RDWROPCNT) && (*config & IBS_OP_CNT_CTL))
724 				new_config |= *config & IBS_OP_CUR_CNT_RAND;
725 		}
726 		new_config |= period >> 4;
727 
728 		perf_ibs_enable_event(perf_ibs, hwc, new_config);
729 	}
730 
731 	perf_event_update_userpage(event);
732 
733 	return 1;
734 }
735 
736 static int
perf_ibs_nmi_handler(unsigned int cmd,struct pt_regs * regs)737 perf_ibs_nmi_handler(unsigned int cmd, struct pt_regs *regs)
738 {
739 	u64 stamp = sched_clock();
740 	int handled = 0;
741 
742 	handled += perf_ibs_handle_irq(&perf_ibs_fetch, regs);
743 	handled += perf_ibs_handle_irq(&perf_ibs_op, regs);
744 
745 	if (handled)
746 		inc_irq_stat(apic_perf_irqs);
747 
748 	perf_sample_event_took(sched_clock() - stamp);
749 
750 	return handled;
751 }
752 NOKPROBE_SYMBOL(perf_ibs_nmi_handler);
753 
perf_ibs_pmu_init(struct perf_ibs * perf_ibs,char * name)754 static __init int perf_ibs_pmu_init(struct perf_ibs *perf_ibs, char *name)
755 {
756 	struct cpu_perf_ibs __percpu *pcpu;
757 	int ret;
758 
759 	pcpu = alloc_percpu(struct cpu_perf_ibs);
760 	if (!pcpu)
761 		return -ENOMEM;
762 
763 	perf_ibs->pcpu = pcpu;
764 
765 	/* register attributes */
766 	if (perf_ibs->format_attrs[0]) {
767 		memset(&perf_ibs->format_group, 0, sizeof(perf_ibs->format_group));
768 		perf_ibs->format_group.name	= "format";
769 		perf_ibs->format_group.attrs	= perf_ibs->format_attrs;
770 
771 		memset(&perf_ibs->attr_groups, 0, sizeof(perf_ibs->attr_groups));
772 		perf_ibs->attr_groups[0]	= &perf_ibs->format_group;
773 		perf_ibs->pmu.attr_groups	= perf_ibs->attr_groups;
774 	}
775 
776 	ret = perf_pmu_register(&perf_ibs->pmu, name, -1);
777 	if (ret) {
778 		perf_ibs->pcpu = NULL;
779 		free_percpu(pcpu);
780 	}
781 
782 	return ret;
783 }
784 
perf_event_ibs_init(void)785 static __init int perf_event_ibs_init(void)
786 {
787 	struct attribute **attr = ibs_op_format_attrs;
788 	int ret;
789 
790 	/*
791 	 * Some chips fail to reset the fetch count when it is written; instead
792 	 * they need a 0-1 transition of IbsFetchEn.
793 	 */
794 	if (boot_cpu_data.x86 >= 0x16 && boot_cpu_data.x86 <= 0x18)
795 		perf_ibs_fetch.fetch_count_reset_broken = 1;
796 
797 	if (boot_cpu_data.x86 == 0x19 && boot_cpu_data.x86_model < 0x10)
798 		perf_ibs_fetch.fetch_ignore_if_zero_rip = 1;
799 
800 	ret = perf_ibs_pmu_init(&perf_ibs_fetch, "ibs_fetch");
801 	if (ret)
802 		return ret;
803 
804 	if (ibs_caps & IBS_CAPS_OPCNT) {
805 		perf_ibs_op.config_mask |= IBS_OP_CNT_CTL;
806 		*attr++ = &format_attr_cnt_ctl.attr;
807 	}
808 
809 	if (ibs_caps & IBS_CAPS_OPCNTEXT) {
810 		perf_ibs_op.max_period  |= IBS_OP_MAX_CNT_EXT_MASK;
811 		perf_ibs_op.config_mask	|= IBS_OP_MAX_CNT_EXT_MASK;
812 		perf_ibs_op.cnt_mask    |= IBS_OP_MAX_CNT_EXT_MASK;
813 	}
814 
815 	ret = perf_ibs_pmu_init(&perf_ibs_op, "ibs_op");
816 	if (ret)
817 		goto err_op;
818 
819 	ret = register_nmi_handler(NMI_LOCAL, perf_ibs_nmi_handler, 0, "perf_ibs");
820 	if (ret)
821 		goto err_nmi;
822 
823 	pr_info("perf: AMD IBS detected (0x%08x)\n", ibs_caps);
824 	return 0;
825 
826 err_nmi:
827 	perf_pmu_unregister(&perf_ibs_op.pmu);
828 	free_percpu(perf_ibs_op.pcpu);
829 	perf_ibs_op.pcpu = NULL;
830 err_op:
831 	perf_pmu_unregister(&perf_ibs_fetch.pmu);
832 	free_percpu(perf_ibs_fetch.pcpu);
833 	perf_ibs_fetch.pcpu = NULL;
834 
835 	return ret;
836 }
837 
838 #else /* defined(CONFIG_PERF_EVENTS) && defined(CONFIG_CPU_SUP_AMD) */
839 
perf_event_ibs_init(void)840 static __init int perf_event_ibs_init(void)
841 {
842 	return 0;
843 }
844 
845 #endif
846 
847 /* IBS - apic initialization, for perf and oprofile */
848 
__get_ibs_caps(void)849 static __init u32 __get_ibs_caps(void)
850 {
851 	u32 caps;
852 	unsigned int max_level;
853 
854 	if (!boot_cpu_has(X86_FEATURE_IBS))
855 		return 0;
856 
857 	/* check IBS cpuid feature flags */
858 	max_level = cpuid_eax(0x80000000);
859 	if (max_level < IBS_CPUID_FEATURES)
860 		return IBS_CAPS_DEFAULT;
861 
862 	caps = cpuid_eax(IBS_CPUID_FEATURES);
863 	if (!(caps & IBS_CAPS_AVAIL))
864 		/* cpuid flags not valid */
865 		return IBS_CAPS_DEFAULT;
866 
867 	return caps;
868 }
869 
get_ibs_caps(void)870 u32 get_ibs_caps(void)
871 {
872 	return ibs_caps;
873 }
874 
875 EXPORT_SYMBOL(get_ibs_caps);
876 
get_eilvt(int offset)877 static inline int get_eilvt(int offset)
878 {
879 	return !setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 1);
880 }
881 
put_eilvt(int offset)882 static inline int put_eilvt(int offset)
883 {
884 	return !setup_APIC_eilvt(offset, 0, 0, 1);
885 }
886 
887 /*
888  * Check and reserve APIC extended interrupt LVT offset for IBS if available.
889  */
ibs_eilvt_valid(void)890 static inline int ibs_eilvt_valid(void)
891 {
892 	int offset;
893 	u64 val;
894 	int valid = 0;
895 
896 	preempt_disable();
897 
898 	rdmsrl(MSR_AMD64_IBSCTL, val);
899 	offset = val & IBSCTL_LVT_OFFSET_MASK;
900 
901 	if (!(val & IBSCTL_LVT_OFFSET_VALID)) {
902 		pr_err(FW_BUG "cpu %d, invalid IBS interrupt offset %d (MSR%08X=0x%016llx)\n",
903 		       smp_processor_id(), offset, MSR_AMD64_IBSCTL, val);
904 		goto out;
905 	}
906 
907 	if (!get_eilvt(offset)) {
908 		pr_err(FW_BUG "cpu %d, IBS interrupt offset %d not available (MSR%08X=0x%016llx)\n",
909 		       smp_processor_id(), offset, MSR_AMD64_IBSCTL, val);
910 		goto out;
911 	}
912 
913 	valid = 1;
914 out:
915 	preempt_enable();
916 
917 	return valid;
918 }
919 
setup_ibs_ctl(int ibs_eilvt_off)920 static int setup_ibs_ctl(int ibs_eilvt_off)
921 {
922 	struct pci_dev *cpu_cfg;
923 	int nodes;
924 	u32 value = 0;
925 
926 	nodes = 0;
927 	cpu_cfg = NULL;
928 	do {
929 		cpu_cfg = pci_get_device(PCI_VENDOR_ID_AMD,
930 					 PCI_DEVICE_ID_AMD_10H_NB_MISC,
931 					 cpu_cfg);
932 		if (!cpu_cfg)
933 			break;
934 		++nodes;
935 		pci_write_config_dword(cpu_cfg, IBSCTL, ibs_eilvt_off
936 				       | IBSCTL_LVT_OFFSET_VALID);
937 		pci_read_config_dword(cpu_cfg, IBSCTL, &value);
938 		if (value != (ibs_eilvt_off | IBSCTL_LVT_OFFSET_VALID)) {
939 			pci_dev_put(cpu_cfg);
940 			pr_debug("Failed to setup IBS LVT offset, IBSCTL = 0x%08x\n",
941 				 value);
942 			return -EINVAL;
943 		}
944 	} while (1);
945 
946 	if (!nodes) {
947 		pr_debug("No CPU node configured for IBS\n");
948 		return -ENODEV;
949 	}
950 
951 	return 0;
952 }
953 
954 /*
955  * This runs only on the current cpu. We try to find an LVT offset and
956  * setup the local APIC. For this we must disable preemption. On
957  * success we initialize all nodes with this offset. This updates then
958  * the offset in the IBS_CTL per-node msr. The per-core APIC setup of
959  * the IBS interrupt vector is handled by perf_ibs_cpu_notifier that
960  * is using the new offset.
961  */
force_ibs_eilvt_setup(void)962 static void force_ibs_eilvt_setup(void)
963 {
964 	int offset;
965 	int ret;
966 
967 	preempt_disable();
968 	/* find the next free available EILVT entry, skip offset 0 */
969 	for (offset = 1; offset < APIC_EILVT_NR_MAX; offset++) {
970 		if (get_eilvt(offset))
971 			break;
972 	}
973 	preempt_enable();
974 
975 	if (offset == APIC_EILVT_NR_MAX) {
976 		pr_debug("No EILVT entry available\n");
977 		return;
978 	}
979 
980 	ret = setup_ibs_ctl(offset);
981 	if (ret)
982 		goto out;
983 
984 	if (!ibs_eilvt_valid())
985 		goto out;
986 
987 	pr_info("LVT offset %d assigned\n", offset);
988 
989 	return;
990 out:
991 	preempt_disable();
992 	put_eilvt(offset);
993 	preempt_enable();
994 	return;
995 }
996 
ibs_eilvt_setup(void)997 static void ibs_eilvt_setup(void)
998 {
999 	/*
1000 	 * Force LVT offset assignment for family 10h: The offsets are
1001 	 * not assigned by the BIOS for this family, so the OS is
1002 	 * responsible for doing it. If the OS assignment fails, fall
1003 	 * back to BIOS settings and try to setup this.
1004 	 */
1005 	if (boot_cpu_data.x86 == 0x10)
1006 		force_ibs_eilvt_setup();
1007 }
1008 
get_ibs_lvt_offset(void)1009 static inline int get_ibs_lvt_offset(void)
1010 {
1011 	u64 val;
1012 
1013 	rdmsrl(MSR_AMD64_IBSCTL, val);
1014 	if (!(val & IBSCTL_LVT_OFFSET_VALID))
1015 		return -EINVAL;
1016 
1017 	return val & IBSCTL_LVT_OFFSET_MASK;
1018 }
1019 
setup_APIC_ibs(void)1020 static void setup_APIC_ibs(void)
1021 {
1022 	int offset;
1023 
1024 	offset = get_ibs_lvt_offset();
1025 	if (offset < 0)
1026 		goto failed;
1027 
1028 	if (!setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_NMI, 0))
1029 		return;
1030 failed:
1031 	pr_warn("perf: IBS APIC setup failed on cpu #%d\n",
1032 		smp_processor_id());
1033 }
1034 
clear_APIC_ibs(void)1035 static void clear_APIC_ibs(void)
1036 {
1037 	int offset;
1038 
1039 	offset = get_ibs_lvt_offset();
1040 	if (offset >= 0)
1041 		setup_APIC_eilvt(offset, 0, APIC_EILVT_MSG_FIX, 1);
1042 }
1043 
x86_pmu_amd_ibs_starting_cpu(unsigned int cpu)1044 static int x86_pmu_amd_ibs_starting_cpu(unsigned int cpu)
1045 {
1046 	setup_APIC_ibs();
1047 	return 0;
1048 }
1049 
1050 #ifdef CONFIG_PM
1051 
perf_ibs_suspend(void)1052 static int perf_ibs_suspend(void)
1053 {
1054 	clear_APIC_ibs();
1055 	return 0;
1056 }
1057 
perf_ibs_resume(void)1058 static void perf_ibs_resume(void)
1059 {
1060 	ibs_eilvt_setup();
1061 	setup_APIC_ibs();
1062 }
1063 
1064 static struct syscore_ops perf_ibs_syscore_ops = {
1065 	.resume		= perf_ibs_resume,
1066 	.suspend	= perf_ibs_suspend,
1067 };
1068 
perf_ibs_pm_init(void)1069 static void perf_ibs_pm_init(void)
1070 {
1071 	register_syscore_ops(&perf_ibs_syscore_ops);
1072 }
1073 
1074 #else
1075 
perf_ibs_pm_init(void)1076 static inline void perf_ibs_pm_init(void) { }
1077 
1078 #endif
1079 
x86_pmu_amd_ibs_dying_cpu(unsigned int cpu)1080 static int x86_pmu_amd_ibs_dying_cpu(unsigned int cpu)
1081 {
1082 	clear_APIC_ibs();
1083 	return 0;
1084 }
1085 
amd_ibs_init(void)1086 static __init int amd_ibs_init(void)
1087 {
1088 	u32 caps;
1089 
1090 	caps = __get_ibs_caps();
1091 	if (!caps)
1092 		return -ENODEV;	/* ibs not supported by the cpu */
1093 
1094 	ibs_eilvt_setup();
1095 
1096 	if (!ibs_eilvt_valid())
1097 		return -EINVAL;
1098 
1099 	perf_ibs_pm_init();
1100 
1101 	ibs_caps = caps;
1102 	/* make ibs_caps visible to other cpus: */
1103 	smp_mb();
1104 	/*
1105 	 * x86_pmu_amd_ibs_starting_cpu will be called from core on
1106 	 * all online cpus.
1107 	 */
1108 	cpuhp_setup_state(CPUHP_AP_PERF_X86_AMD_IBS_STARTING,
1109 			  "perf/x86/amd/ibs:starting",
1110 			  x86_pmu_amd_ibs_starting_cpu,
1111 			  x86_pmu_amd_ibs_dying_cpu);
1112 
1113 	return perf_event_ibs_init();
1114 }
1115 
1116 /* Since we need the pci subsystem to init ibs we can't do this earlier: */
1117 device_initcall(amd_ibs_init);
1118