xref: /openbmc/linux/drivers/gpu/drm/i915/i915_pmu.c (revision 9a6b55ac)
1 /*
2  * SPDX-License-Identifier: MIT
3  *
4  * Copyright © 2017-2018 Intel Corporation
5  */
6 
7 #include <linux/irq.h>
8 #include <linux/pm_runtime.h>
9 
10 #include "gt/intel_engine.h"
11 #include "gt/intel_engine_pm.h"
12 #include "gt/intel_engine_user.h"
13 #include "gt/intel_gt_pm.h"
14 #include "gt/intel_rc6.h"
15 #include "gt/intel_rps.h"
16 
17 #include "i915_drv.h"
18 #include "i915_pmu.h"
19 #include "intel_pm.h"
20 
21 /* Frequency for the sampling timer for events which need it. */
22 #define FREQUENCY 200
23 #define PERIOD max_t(u64, 10000, NSEC_PER_SEC / FREQUENCY)
24 
25 #define ENGINE_SAMPLE_MASK \
26 	(BIT(I915_SAMPLE_BUSY) | \
27 	 BIT(I915_SAMPLE_WAIT) | \
28 	 BIT(I915_SAMPLE_SEMA))
29 
30 #define ENGINE_SAMPLE_BITS (1 << I915_PMU_SAMPLE_BITS)
31 
32 static cpumask_t i915_pmu_cpumask;
33 
34 static u8 engine_config_sample(u64 config)
35 {
36 	return config & I915_PMU_SAMPLE_MASK;
37 }
38 
39 static u8 engine_event_sample(struct perf_event *event)
40 {
41 	return engine_config_sample(event->attr.config);
42 }
43 
44 static u8 engine_event_class(struct perf_event *event)
45 {
46 	return (event->attr.config >> I915_PMU_CLASS_SHIFT) & 0xff;
47 }
48 
49 static u8 engine_event_instance(struct perf_event *event)
50 {
51 	return (event->attr.config >> I915_PMU_SAMPLE_BITS) & 0xff;
52 }
53 
54 static bool is_engine_config(u64 config)
55 {
56 	return config < __I915_PMU_OTHER(0);
57 }
58 
59 static unsigned int config_enabled_bit(u64 config)
60 {
61 	if (is_engine_config(config))
62 		return engine_config_sample(config);
63 	else
64 		return ENGINE_SAMPLE_BITS + (config - __I915_PMU_OTHER(0));
65 }
66 
67 static u64 config_enabled_mask(u64 config)
68 {
69 	return BIT_ULL(config_enabled_bit(config));
70 }
71 
72 static bool is_engine_event(struct perf_event *event)
73 {
74 	return is_engine_config(event->attr.config);
75 }
76 
77 static unsigned int event_enabled_bit(struct perf_event *event)
78 {
79 	return config_enabled_bit(event->attr.config);
80 }
81 
82 static bool pmu_needs_timer(struct i915_pmu *pmu, bool gpu_active)
83 {
84 	struct drm_i915_private *i915 = container_of(pmu, typeof(*i915), pmu);
85 	u64 enable;
86 
87 	/*
88 	 * Only some counters need the sampling timer.
89 	 *
90 	 * We start with a bitmask of all currently enabled events.
91 	 */
92 	enable = pmu->enable;
93 
94 	/*
95 	 * Mask out all the ones which do not need the timer, or in
96 	 * other words keep all the ones that could need the timer.
97 	 */
98 	enable &= config_enabled_mask(I915_PMU_ACTUAL_FREQUENCY) |
99 		  config_enabled_mask(I915_PMU_REQUESTED_FREQUENCY) |
100 		  ENGINE_SAMPLE_MASK;
101 
102 	/*
103 	 * When the GPU is idle per-engine counters do not need to be
104 	 * running so clear those bits out.
105 	 */
106 	if (!gpu_active)
107 		enable &= ~ENGINE_SAMPLE_MASK;
108 	/*
109 	 * Also there is software busyness tracking available we do not
110 	 * need the timer for I915_SAMPLE_BUSY counter.
111 	 */
112 	else if (i915->caps.scheduler & I915_SCHEDULER_CAP_ENGINE_BUSY_STATS)
113 		enable &= ~BIT(I915_SAMPLE_BUSY);
114 
115 	/*
116 	 * If some bits remain it means we need the sampling timer running.
117 	 */
118 	return enable;
119 }
120 
121 static u64 __get_rc6(struct intel_gt *gt)
122 {
123 	struct drm_i915_private *i915 = gt->i915;
124 	u64 val;
125 
126 	val = intel_rc6_residency_ns(&gt->rc6,
127 				     IS_VALLEYVIEW(i915) ?
128 				     VLV_GT_RENDER_RC6 :
129 				     GEN6_GT_GFX_RC6);
130 
131 	if (HAS_RC6p(i915))
132 		val += intel_rc6_residency_ns(&gt->rc6, GEN6_GT_GFX_RC6p);
133 
134 	if (HAS_RC6pp(i915))
135 		val += intel_rc6_residency_ns(&gt->rc6, GEN6_GT_GFX_RC6pp);
136 
137 	return val;
138 }
139 
140 #if IS_ENABLED(CONFIG_PM)
141 
142 static inline s64 ktime_since(const ktime_t kt)
143 {
144 	return ktime_to_ns(ktime_sub(ktime_get(), kt));
145 }
146 
147 static u64 get_rc6(struct intel_gt *gt)
148 {
149 	struct drm_i915_private *i915 = gt->i915;
150 	struct i915_pmu *pmu = &i915->pmu;
151 	unsigned long flags;
152 	bool awake = false;
153 	u64 val;
154 
155 	if (intel_gt_pm_get_if_awake(gt)) {
156 		val = __get_rc6(gt);
157 		intel_gt_pm_put_async(gt);
158 		awake = true;
159 	}
160 
161 	spin_lock_irqsave(&pmu->lock, flags);
162 
163 	if (awake) {
164 		pmu->sample[__I915_SAMPLE_RC6].cur = val;
165 	} else {
166 		/*
167 		 * We think we are runtime suspended.
168 		 *
169 		 * Report the delta from when the device was suspended to now,
170 		 * on top of the last known real value, as the approximated RC6
171 		 * counter value.
172 		 */
173 		val = ktime_since(pmu->sleep_last);
174 		val += pmu->sample[__I915_SAMPLE_RC6].cur;
175 	}
176 
177 	if (val < pmu->sample[__I915_SAMPLE_RC6_LAST_REPORTED].cur)
178 		val = pmu->sample[__I915_SAMPLE_RC6_LAST_REPORTED].cur;
179 	else
180 		pmu->sample[__I915_SAMPLE_RC6_LAST_REPORTED].cur = val;
181 
182 	spin_unlock_irqrestore(&pmu->lock, flags);
183 
184 	return val;
185 }
186 
187 static void park_rc6(struct drm_i915_private *i915)
188 {
189 	struct i915_pmu *pmu = &i915->pmu;
190 
191 	if (pmu->enable & config_enabled_mask(I915_PMU_RC6_RESIDENCY))
192 		pmu->sample[__I915_SAMPLE_RC6].cur = __get_rc6(&i915->gt);
193 
194 	pmu->sleep_last = ktime_get();
195 }
196 
197 #else
198 
199 static u64 get_rc6(struct intel_gt *gt)
200 {
201 	return __get_rc6(gt);
202 }
203 
204 static void park_rc6(struct drm_i915_private *i915) {}
205 
206 #endif
207 
208 static void __i915_pmu_maybe_start_timer(struct i915_pmu *pmu)
209 {
210 	if (!pmu->timer_enabled && pmu_needs_timer(pmu, true)) {
211 		pmu->timer_enabled = true;
212 		pmu->timer_last = ktime_get();
213 		hrtimer_start_range_ns(&pmu->timer,
214 				       ns_to_ktime(PERIOD), 0,
215 				       HRTIMER_MODE_REL_PINNED);
216 	}
217 }
218 
219 void i915_pmu_gt_parked(struct drm_i915_private *i915)
220 {
221 	struct i915_pmu *pmu = &i915->pmu;
222 
223 	if (!pmu->base.event_init)
224 		return;
225 
226 	spin_lock_irq(&pmu->lock);
227 
228 	park_rc6(i915);
229 
230 	/*
231 	 * Signal sampling timer to stop if only engine events are enabled and
232 	 * GPU went idle.
233 	 */
234 	pmu->timer_enabled = pmu_needs_timer(pmu, false);
235 
236 	spin_unlock_irq(&pmu->lock);
237 }
238 
239 void i915_pmu_gt_unparked(struct drm_i915_private *i915)
240 {
241 	struct i915_pmu *pmu = &i915->pmu;
242 
243 	if (!pmu->base.event_init)
244 		return;
245 
246 	spin_lock_irq(&pmu->lock);
247 
248 	/*
249 	 * Re-enable sampling timer when GPU goes active.
250 	 */
251 	__i915_pmu_maybe_start_timer(pmu);
252 
253 	spin_unlock_irq(&pmu->lock);
254 }
255 
256 static void
257 add_sample(struct i915_pmu_sample *sample, u32 val)
258 {
259 	sample->cur += val;
260 }
261 
262 static void
263 engines_sample(struct intel_gt *gt, unsigned int period_ns)
264 {
265 	struct drm_i915_private *i915 = gt->i915;
266 	struct intel_engine_cs *engine;
267 	enum intel_engine_id id;
268 
269 	if ((i915->pmu.enable & ENGINE_SAMPLE_MASK) == 0)
270 		return;
271 
272 	for_each_engine(engine, gt, id) {
273 		struct intel_engine_pmu *pmu = &engine->pmu;
274 		unsigned long flags;
275 		bool busy;
276 		u32 val;
277 
278 		if (!intel_engine_pm_get_if_awake(engine))
279 			continue;
280 
281 		spin_lock_irqsave(&engine->uncore->lock, flags);
282 
283 		val = ENGINE_READ_FW(engine, RING_CTL);
284 		if (val == 0) /* powerwell off => engine idle */
285 			goto skip;
286 
287 		if (val & RING_WAIT)
288 			add_sample(&pmu->sample[I915_SAMPLE_WAIT], period_ns);
289 		if (val & RING_WAIT_SEMAPHORE)
290 			add_sample(&pmu->sample[I915_SAMPLE_SEMA], period_ns);
291 
292 		/* No need to sample when busy stats are supported. */
293 		if (intel_engine_supports_stats(engine))
294 			goto skip;
295 
296 		/*
297 		 * While waiting on a semaphore or event, MI_MODE reports the
298 		 * ring as idle. However, previously using the seqno, and with
299 		 * execlists sampling, we account for the ring waiting as the
300 		 * engine being busy. Therefore, we record the sample as being
301 		 * busy if either waiting or !idle.
302 		 */
303 		busy = val & (RING_WAIT_SEMAPHORE | RING_WAIT);
304 		if (!busy) {
305 			val = ENGINE_READ_FW(engine, RING_MI_MODE);
306 			busy = !(val & MODE_IDLE);
307 		}
308 		if (busy)
309 			add_sample(&pmu->sample[I915_SAMPLE_BUSY], period_ns);
310 
311 skip:
312 		spin_unlock_irqrestore(&engine->uncore->lock, flags);
313 		intel_engine_pm_put_async(engine);
314 	}
315 }
316 
317 static void
318 add_sample_mult(struct i915_pmu_sample *sample, u32 val, u32 mul)
319 {
320 	sample->cur += mul_u32_u32(val, mul);
321 }
322 
323 static void
324 frequency_sample(struct intel_gt *gt, unsigned int period_ns)
325 {
326 	struct drm_i915_private *i915 = gt->i915;
327 	struct intel_uncore *uncore = gt->uncore;
328 	struct i915_pmu *pmu = &i915->pmu;
329 	struct intel_rps *rps = &gt->rps;
330 
331 	if (pmu->enable & config_enabled_mask(I915_PMU_ACTUAL_FREQUENCY)) {
332 		u32 val;
333 
334 		val = rps->cur_freq;
335 		if (intel_gt_pm_get_if_awake(gt)) {
336 			val = intel_uncore_read_notrace(uncore, GEN6_RPSTAT1);
337 			val = intel_get_cagf(rps, val);
338 			intel_gt_pm_put_async(gt);
339 		}
340 
341 		add_sample_mult(&pmu->sample[__I915_SAMPLE_FREQ_ACT],
342 				intel_gpu_freq(rps, val),
343 				period_ns / 1000);
344 	}
345 
346 	if (pmu->enable & config_enabled_mask(I915_PMU_REQUESTED_FREQUENCY)) {
347 		add_sample_mult(&pmu->sample[__I915_SAMPLE_FREQ_REQ],
348 				intel_gpu_freq(rps, rps->cur_freq),
349 				period_ns / 1000);
350 	}
351 }
352 
353 static enum hrtimer_restart i915_sample(struct hrtimer *hrtimer)
354 {
355 	struct drm_i915_private *i915 =
356 		container_of(hrtimer, struct drm_i915_private, pmu.timer);
357 	struct i915_pmu *pmu = &i915->pmu;
358 	struct intel_gt *gt = &i915->gt;
359 	unsigned int period_ns;
360 	ktime_t now;
361 
362 	if (!READ_ONCE(pmu->timer_enabled))
363 		return HRTIMER_NORESTART;
364 
365 	now = ktime_get();
366 	period_ns = ktime_to_ns(ktime_sub(now, pmu->timer_last));
367 	pmu->timer_last = now;
368 
369 	/*
370 	 * Strictly speaking the passed in period may not be 100% accurate for
371 	 * all internal calculation, since some amount of time can be spent on
372 	 * grabbing the forcewake. However the potential error from timer call-
373 	 * back delay greatly dominates this so we keep it simple.
374 	 */
375 	engines_sample(gt, period_ns);
376 	frequency_sample(gt, period_ns);
377 
378 	hrtimer_forward(hrtimer, now, ns_to_ktime(PERIOD));
379 
380 	return HRTIMER_RESTART;
381 }
382 
383 static u64 count_interrupts(struct drm_i915_private *i915)
384 {
385 	/* open-coded kstat_irqs() */
386 	struct irq_desc *desc = irq_to_desc(i915->drm.pdev->irq);
387 	u64 sum = 0;
388 	int cpu;
389 
390 	if (!desc || !desc->kstat_irqs)
391 		return 0;
392 
393 	for_each_possible_cpu(cpu)
394 		sum += *per_cpu_ptr(desc->kstat_irqs, cpu);
395 
396 	return sum;
397 }
398 
399 static void engine_event_destroy(struct perf_event *event)
400 {
401 	struct drm_i915_private *i915 =
402 		container_of(event->pmu, typeof(*i915), pmu.base);
403 	struct intel_engine_cs *engine;
404 
405 	engine = intel_engine_lookup_user(i915,
406 					  engine_event_class(event),
407 					  engine_event_instance(event));
408 	if (WARN_ON_ONCE(!engine))
409 		return;
410 
411 	if (engine_event_sample(event) == I915_SAMPLE_BUSY &&
412 	    intel_engine_supports_stats(engine))
413 		intel_disable_engine_stats(engine);
414 }
415 
416 static void i915_pmu_event_destroy(struct perf_event *event)
417 {
418 	WARN_ON(event->parent);
419 
420 	if (is_engine_event(event))
421 		engine_event_destroy(event);
422 }
423 
424 static int
425 engine_event_status(struct intel_engine_cs *engine,
426 		    enum drm_i915_pmu_engine_sample sample)
427 {
428 	switch (sample) {
429 	case I915_SAMPLE_BUSY:
430 	case I915_SAMPLE_WAIT:
431 		break;
432 	case I915_SAMPLE_SEMA:
433 		if (INTEL_GEN(engine->i915) < 6)
434 			return -ENODEV;
435 		break;
436 	default:
437 		return -ENOENT;
438 	}
439 
440 	return 0;
441 }
442 
443 static int
444 config_status(struct drm_i915_private *i915, u64 config)
445 {
446 	switch (config) {
447 	case I915_PMU_ACTUAL_FREQUENCY:
448 		if (IS_VALLEYVIEW(i915) || IS_CHERRYVIEW(i915))
449 			/* Requires a mutex for sampling! */
450 			return -ENODEV;
451 		/* Fall-through. */
452 	case I915_PMU_REQUESTED_FREQUENCY:
453 		if (INTEL_GEN(i915) < 6)
454 			return -ENODEV;
455 		break;
456 	case I915_PMU_INTERRUPTS:
457 		break;
458 	case I915_PMU_RC6_RESIDENCY:
459 		if (!HAS_RC6(i915))
460 			return -ENODEV;
461 		break;
462 	default:
463 		return -ENOENT;
464 	}
465 
466 	return 0;
467 }
468 
469 static int engine_event_init(struct perf_event *event)
470 {
471 	struct drm_i915_private *i915 =
472 		container_of(event->pmu, typeof(*i915), pmu.base);
473 	struct intel_engine_cs *engine;
474 	u8 sample;
475 	int ret;
476 
477 	engine = intel_engine_lookup_user(i915, engine_event_class(event),
478 					  engine_event_instance(event));
479 	if (!engine)
480 		return -ENODEV;
481 
482 	sample = engine_event_sample(event);
483 	ret = engine_event_status(engine, sample);
484 	if (ret)
485 		return ret;
486 
487 	if (sample == I915_SAMPLE_BUSY && intel_engine_supports_stats(engine))
488 		ret = intel_enable_engine_stats(engine);
489 
490 	return ret;
491 }
492 
493 static int i915_pmu_event_init(struct perf_event *event)
494 {
495 	struct drm_i915_private *i915 =
496 		container_of(event->pmu, typeof(*i915), pmu.base);
497 	int ret;
498 
499 	if (event->attr.type != event->pmu->type)
500 		return -ENOENT;
501 
502 	/* unsupported modes and filters */
503 	if (event->attr.sample_period) /* no sampling */
504 		return -EINVAL;
505 
506 	if (has_branch_stack(event))
507 		return -EOPNOTSUPP;
508 
509 	if (event->cpu < 0)
510 		return -EINVAL;
511 
512 	/* only allow running on one cpu at a time */
513 	if (!cpumask_test_cpu(event->cpu, &i915_pmu_cpumask))
514 		return -EINVAL;
515 
516 	if (is_engine_event(event))
517 		ret = engine_event_init(event);
518 	else
519 		ret = config_status(i915, event->attr.config);
520 	if (ret)
521 		return ret;
522 
523 	if (!event->parent)
524 		event->destroy = i915_pmu_event_destroy;
525 
526 	return 0;
527 }
528 
529 static u64 __i915_pmu_event_read(struct perf_event *event)
530 {
531 	struct drm_i915_private *i915 =
532 		container_of(event->pmu, typeof(*i915), pmu.base);
533 	struct i915_pmu *pmu = &i915->pmu;
534 	u64 val = 0;
535 
536 	if (is_engine_event(event)) {
537 		u8 sample = engine_event_sample(event);
538 		struct intel_engine_cs *engine;
539 
540 		engine = intel_engine_lookup_user(i915,
541 						  engine_event_class(event),
542 						  engine_event_instance(event));
543 
544 		if (WARN_ON_ONCE(!engine)) {
545 			/* Do nothing */
546 		} else if (sample == I915_SAMPLE_BUSY &&
547 			   intel_engine_supports_stats(engine)) {
548 			val = ktime_to_ns(intel_engine_get_busy_time(engine));
549 		} else {
550 			val = engine->pmu.sample[sample].cur;
551 		}
552 	} else {
553 		switch (event->attr.config) {
554 		case I915_PMU_ACTUAL_FREQUENCY:
555 			val =
556 			   div_u64(pmu->sample[__I915_SAMPLE_FREQ_ACT].cur,
557 				   USEC_PER_SEC /* to MHz */);
558 			break;
559 		case I915_PMU_REQUESTED_FREQUENCY:
560 			val =
561 			   div_u64(pmu->sample[__I915_SAMPLE_FREQ_REQ].cur,
562 				   USEC_PER_SEC /* to MHz */);
563 			break;
564 		case I915_PMU_INTERRUPTS:
565 			val = count_interrupts(i915);
566 			break;
567 		case I915_PMU_RC6_RESIDENCY:
568 			val = get_rc6(&i915->gt);
569 			break;
570 		}
571 	}
572 
573 	return val;
574 }
575 
576 static void i915_pmu_event_read(struct perf_event *event)
577 {
578 	struct hw_perf_event *hwc = &event->hw;
579 	u64 prev, new;
580 
581 again:
582 	prev = local64_read(&hwc->prev_count);
583 	new = __i915_pmu_event_read(event);
584 
585 	if (local64_cmpxchg(&hwc->prev_count, prev, new) != prev)
586 		goto again;
587 
588 	local64_add(new - prev, &event->count);
589 }
590 
591 static void i915_pmu_enable(struct perf_event *event)
592 {
593 	struct drm_i915_private *i915 =
594 		container_of(event->pmu, typeof(*i915), pmu.base);
595 	unsigned int bit = event_enabled_bit(event);
596 	struct i915_pmu *pmu = &i915->pmu;
597 	unsigned long flags;
598 
599 	spin_lock_irqsave(&pmu->lock, flags);
600 
601 	/*
602 	 * Update the bitmask of enabled events and increment
603 	 * the event reference counter.
604 	 */
605 	BUILD_BUG_ON(ARRAY_SIZE(pmu->enable_count) != I915_PMU_MASK_BITS);
606 	GEM_BUG_ON(bit >= ARRAY_SIZE(pmu->enable_count));
607 	GEM_BUG_ON(pmu->enable_count[bit] == ~0);
608 	pmu->enable |= BIT_ULL(bit);
609 	pmu->enable_count[bit]++;
610 
611 	/*
612 	 * Start the sampling timer if needed and not already enabled.
613 	 */
614 	__i915_pmu_maybe_start_timer(pmu);
615 
616 	/*
617 	 * For per-engine events the bitmask and reference counting
618 	 * is stored per engine.
619 	 */
620 	if (is_engine_event(event)) {
621 		u8 sample = engine_event_sample(event);
622 		struct intel_engine_cs *engine;
623 
624 		engine = intel_engine_lookup_user(i915,
625 						  engine_event_class(event),
626 						  engine_event_instance(event));
627 
628 		BUILD_BUG_ON(ARRAY_SIZE(engine->pmu.enable_count) !=
629 			     I915_ENGINE_SAMPLE_COUNT);
630 		BUILD_BUG_ON(ARRAY_SIZE(engine->pmu.sample) !=
631 			     I915_ENGINE_SAMPLE_COUNT);
632 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.enable_count));
633 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.sample));
634 		GEM_BUG_ON(engine->pmu.enable_count[sample] == ~0);
635 
636 		engine->pmu.enable |= BIT(sample);
637 		engine->pmu.enable_count[sample]++;
638 	}
639 
640 	spin_unlock_irqrestore(&pmu->lock, flags);
641 
642 	/*
643 	 * Store the current counter value so we can report the correct delta
644 	 * for all listeners. Even when the event was already enabled and has
645 	 * an existing non-zero value.
646 	 */
647 	local64_set(&event->hw.prev_count, __i915_pmu_event_read(event));
648 }
649 
650 static void i915_pmu_disable(struct perf_event *event)
651 {
652 	struct drm_i915_private *i915 =
653 		container_of(event->pmu, typeof(*i915), pmu.base);
654 	unsigned int bit = event_enabled_bit(event);
655 	struct i915_pmu *pmu = &i915->pmu;
656 	unsigned long flags;
657 
658 	spin_lock_irqsave(&pmu->lock, flags);
659 
660 	if (is_engine_event(event)) {
661 		u8 sample = engine_event_sample(event);
662 		struct intel_engine_cs *engine;
663 
664 		engine = intel_engine_lookup_user(i915,
665 						  engine_event_class(event),
666 						  engine_event_instance(event));
667 
668 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.enable_count));
669 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.sample));
670 		GEM_BUG_ON(engine->pmu.enable_count[sample] == 0);
671 
672 		/*
673 		 * Decrement the reference count and clear the enabled
674 		 * bitmask when the last listener on an event goes away.
675 		 */
676 		if (--engine->pmu.enable_count[sample] == 0)
677 			engine->pmu.enable &= ~BIT(sample);
678 	}
679 
680 	GEM_BUG_ON(bit >= ARRAY_SIZE(pmu->enable_count));
681 	GEM_BUG_ON(pmu->enable_count[bit] == 0);
682 	/*
683 	 * Decrement the reference count and clear the enabled
684 	 * bitmask when the last listener on an event goes away.
685 	 */
686 	if (--pmu->enable_count[bit] == 0) {
687 		pmu->enable &= ~BIT_ULL(bit);
688 		pmu->timer_enabled &= pmu_needs_timer(pmu, true);
689 	}
690 
691 	spin_unlock_irqrestore(&pmu->lock, flags);
692 }
693 
694 static void i915_pmu_event_start(struct perf_event *event, int flags)
695 {
696 	i915_pmu_enable(event);
697 	event->hw.state = 0;
698 }
699 
700 static void i915_pmu_event_stop(struct perf_event *event, int flags)
701 {
702 	if (flags & PERF_EF_UPDATE)
703 		i915_pmu_event_read(event);
704 	i915_pmu_disable(event);
705 	event->hw.state = PERF_HES_STOPPED;
706 }
707 
708 static int i915_pmu_event_add(struct perf_event *event, int flags)
709 {
710 	if (flags & PERF_EF_START)
711 		i915_pmu_event_start(event, flags);
712 
713 	return 0;
714 }
715 
716 static void i915_pmu_event_del(struct perf_event *event, int flags)
717 {
718 	i915_pmu_event_stop(event, PERF_EF_UPDATE);
719 }
720 
721 static int i915_pmu_event_event_idx(struct perf_event *event)
722 {
723 	return 0;
724 }
725 
726 struct i915_str_attribute {
727 	struct device_attribute attr;
728 	const char *str;
729 };
730 
731 static ssize_t i915_pmu_format_show(struct device *dev,
732 				    struct device_attribute *attr, char *buf)
733 {
734 	struct i915_str_attribute *eattr;
735 
736 	eattr = container_of(attr, struct i915_str_attribute, attr);
737 	return sprintf(buf, "%s\n", eattr->str);
738 }
739 
740 #define I915_PMU_FORMAT_ATTR(_name, _config) \
741 	(&((struct i915_str_attribute[]) { \
742 		{ .attr = __ATTR(_name, 0444, i915_pmu_format_show, NULL), \
743 		  .str = _config, } \
744 	})[0].attr.attr)
745 
746 static struct attribute *i915_pmu_format_attrs[] = {
747 	I915_PMU_FORMAT_ATTR(i915_eventid, "config:0-20"),
748 	NULL,
749 };
750 
751 static const struct attribute_group i915_pmu_format_attr_group = {
752 	.name = "format",
753 	.attrs = i915_pmu_format_attrs,
754 };
755 
756 struct i915_ext_attribute {
757 	struct device_attribute attr;
758 	unsigned long val;
759 };
760 
761 static ssize_t i915_pmu_event_show(struct device *dev,
762 				   struct device_attribute *attr, char *buf)
763 {
764 	struct i915_ext_attribute *eattr;
765 
766 	eattr = container_of(attr, struct i915_ext_attribute, attr);
767 	return sprintf(buf, "config=0x%lx\n", eattr->val);
768 }
769 
770 static struct attribute_group i915_pmu_events_attr_group = {
771 	.name = "events",
772 	/* Patch in attrs at runtime. */
773 };
774 
775 static ssize_t
776 i915_pmu_get_attr_cpumask(struct device *dev,
777 			  struct device_attribute *attr,
778 			  char *buf)
779 {
780 	return cpumap_print_to_pagebuf(true, buf, &i915_pmu_cpumask);
781 }
782 
783 static DEVICE_ATTR(cpumask, 0444, i915_pmu_get_attr_cpumask, NULL);
784 
785 static struct attribute *i915_cpumask_attrs[] = {
786 	&dev_attr_cpumask.attr,
787 	NULL,
788 };
789 
790 static const struct attribute_group i915_pmu_cpumask_attr_group = {
791 	.attrs = i915_cpumask_attrs,
792 };
793 
794 static const struct attribute_group *i915_pmu_attr_groups[] = {
795 	&i915_pmu_format_attr_group,
796 	&i915_pmu_events_attr_group,
797 	&i915_pmu_cpumask_attr_group,
798 	NULL
799 };
800 
801 #define __event(__config, __name, __unit) \
802 { \
803 	.config = (__config), \
804 	.name = (__name), \
805 	.unit = (__unit), \
806 }
807 
808 #define __engine_event(__sample, __name) \
809 { \
810 	.sample = (__sample), \
811 	.name = (__name), \
812 }
813 
814 static struct i915_ext_attribute *
815 add_i915_attr(struct i915_ext_attribute *attr, const char *name, u64 config)
816 {
817 	sysfs_attr_init(&attr->attr.attr);
818 	attr->attr.attr.name = name;
819 	attr->attr.attr.mode = 0444;
820 	attr->attr.show = i915_pmu_event_show;
821 	attr->val = config;
822 
823 	return ++attr;
824 }
825 
826 static struct perf_pmu_events_attr *
827 add_pmu_attr(struct perf_pmu_events_attr *attr, const char *name,
828 	     const char *str)
829 {
830 	sysfs_attr_init(&attr->attr.attr);
831 	attr->attr.attr.name = name;
832 	attr->attr.attr.mode = 0444;
833 	attr->attr.show = perf_event_sysfs_show;
834 	attr->event_str = str;
835 
836 	return ++attr;
837 }
838 
839 static struct attribute **
840 create_event_attributes(struct i915_pmu *pmu)
841 {
842 	struct drm_i915_private *i915 = container_of(pmu, typeof(*i915), pmu);
843 	static const struct {
844 		u64 config;
845 		const char *name;
846 		const char *unit;
847 	} events[] = {
848 		__event(I915_PMU_ACTUAL_FREQUENCY, "actual-frequency", "M"),
849 		__event(I915_PMU_REQUESTED_FREQUENCY, "requested-frequency", "M"),
850 		__event(I915_PMU_INTERRUPTS, "interrupts", NULL),
851 		__event(I915_PMU_RC6_RESIDENCY, "rc6-residency", "ns"),
852 	};
853 	static const struct {
854 		enum drm_i915_pmu_engine_sample sample;
855 		char *name;
856 	} engine_events[] = {
857 		__engine_event(I915_SAMPLE_BUSY, "busy"),
858 		__engine_event(I915_SAMPLE_SEMA, "sema"),
859 		__engine_event(I915_SAMPLE_WAIT, "wait"),
860 	};
861 	unsigned int count = 0;
862 	struct perf_pmu_events_attr *pmu_attr = NULL, *pmu_iter;
863 	struct i915_ext_attribute *i915_attr = NULL, *i915_iter;
864 	struct attribute **attr = NULL, **attr_iter;
865 	struct intel_engine_cs *engine;
866 	unsigned int i;
867 
868 	/* Count how many counters we will be exposing. */
869 	for (i = 0; i < ARRAY_SIZE(events); i++) {
870 		if (!config_status(i915, events[i].config))
871 			count++;
872 	}
873 
874 	for_each_uabi_engine(engine, i915) {
875 		for (i = 0; i < ARRAY_SIZE(engine_events); i++) {
876 			if (!engine_event_status(engine,
877 						 engine_events[i].sample))
878 				count++;
879 		}
880 	}
881 
882 	/* Allocate attribute objects and table. */
883 	i915_attr = kcalloc(count, sizeof(*i915_attr), GFP_KERNEL);
884 	if (!i915_attr)
885 		goto err_alloc;
886 
887 	pmu_attr = kcalloc(count, sizeof(*pmu_attr), GFP_KERNEL);
888 	if (!pmu_attr)
889 		goto err_alloc;
890 
891 	/* Max one pointer of each attribute type plus a termination entry. */
892 	attr = kcalloc(count * 2 + 1, sizeof(*attr), GFP_KERNEL);
893 	if (!attr)
894 		goto err_alloc;
895 
896 	i915_iter = i915_attr;
897 	pmu_iter = pmu_attr;
898 	attr_iter = attr;
899 
900 	/* Initialize supported non-engine counters. */
901 	for (i = 0; i < ARRAY_SIZE(events); i++) {
902 		char *str;
903 
904 		if (config_status(i915, events[i].config))
905 			continue;
906 
907 		str = kstrdup(events[i].name, GFP_KERNEL);
908 		if (!str)
909 			goto err;
910 
911 		*attr_iter++ = &i915_iter->attr.attr;
912 		i915_iter = add_i915_attr(i915_iter, str, events[i].config);
913 
914 		if (events[i].unit) {
915 			str = kasprintf(GFP_KERNEL, "%s.unit", events[i].name);
916 			if (!str)
917 				goto err;
918 
919 			*attr_iter++ = &pmu_iter->attr.attr;
920 			pmu_iter = add_pmu_attr(pmu_iter, str, events[i].unit);
921 		}
922 	}
923 
924 	/* Initialize supported engine counters. */
925 	for_each_uabi_engine(engine, i915) {
926 		for (i = 0; i < ARRAY_SIZE(engine_events); i++) {
927 			char *str;
928 
929 			if (engine_event_status(engine,
930 						engine_events[i].sample))
931 				continue;
932 
933 			str = kasprintf(GFP_KERNEL, "%s-%s",
934 					engine->name, engine_events[i].name);
935 			if (!str)
936 				goto err;
937 
938 			*attr_iter++ = &i915_iter->attr.attr;
939 			i915_iter =
940 				add_i915_attr(i915_iter, str,
941 					      __I915_PMU_ENGINE(engine->uabi_class,
942 								engine->uabi_instance,
943 								engine_events[i].sample));
944 
945 			str = kasprintf(GFP_KERNEL, "%s-%s.unit",
946 					engine->name, engine_events[i].name);
947 			if (!str)
948 				goto err;
949 
950 			*attr_iter++ = &pmu_iter->attr.attr;
951 			pmu_iter = add_pmu_attr(pmu_iter, str, "ns");
952 		}
953 	}
954 
955 	pmu->i915_attr = i915_attr;
956 	pmu->pmu_attr = pmu_attr;
957 
958 	return attr;
959 
960 err:;
961 	for (attr_iter = attr; *attr_iter; attr_iter++)
962 		kfree((*attr_iter)->name);
963 
964 err_alloc:
965 	kfree(attr);
966 	kfree(i915_attr);
967 	kfree(pmu_attr);
968 
969 	return NULL;
970 }
971 
972 static void free_event_attributes(struct i915_pmu *pmu)
973 {
974 	struct attribute **attr_iter = i915_pmu_events_attr_group.attrs;
975 
976 	for (; *attr_iter; attr_iter++)
977 		kfree((*attr_iter)->name);
978 
979 	kfree(i915_pmu_events_attr_group.attrs);
980 	kfree(pmu->i915_attr);
981 	kfree(pmu->pmu_attr);
982 
983 	i915_pmu_events_attr_group.attrs = NULL;
984 	pmu->i915_attr = NULL;
985 	pmu->pmu_attr = NULL;
986 }
987 
988 static int i915_pmu_cpu_online(unsigned int cpu, struct hlist_node *node)
989 {
990 	struct i915_pmu *pmu = hlist_entry_safe(node, typeof(*pmu), node);
991 
992 	GEM_BUG_ON(!pmu->base.event_init);
993 
994 	/* Select the first online CPU as a designated reader. */
995 	if (!cpumask_weight(&i915_pmu_cpumask))
996 		cpumask_set_cpu(cpu, &i915_pmu_cpumask);
997 
998 	return 0;
999 }
1000 
1001 static int i915_pmu_cpu_offline(unsigned int cpu, struct hlist_node *node)
1002 {
1003 	struct i915_pmu *pmu = hlist_entry_safe(node, typeof(*pmu), node);
1004 	unsigned int target;
1005 
1006 	GEM_BUG_ON(!pmu->base.event_init);
1007 
1008 	if (cpumask_test_and_clear_cpu(cpu, &i915_pmu_cpumask)) {
1009 		target = cpumask_any_but(topology_sibling_cpumask(cpu), cpu);
1010 		/* Migrate events if there is a valid target */
1011 		if (target < nr_cpu_ids) {
1012 			cpumask_set_cpu(target, &i915_pmu_cpumask);
1013 			perf_pmu_migrate_context(&pmu->base, cpu, target);
1014 		}
1015 	}
1016 
1017 	return 0;
1018 }
1019 
1020 static enum cpuhp_state cpuhp_slot = CPUHP_INVALID;
1021 
1022 static int i915_pmu_register_cpuhp_state(struct i915_pmu *pmu)
1023 {
1024 	enum cpuhp_state slot;
1025 	int ret;
1026 
1027 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
1028 				      "perf/x86/intel/i915:online",
1029 				      i915_pmu_cpu_online,
1030 				      i915_pmu_cpu_offline);
1031 	if (ret < 0)
1032 		return ret;
1033 
1034 	slot = ret;
1035 	ret = cpuhp_state_add_instance(slot, &pmu->node);
1036 	if (ret) {
1037 		cpuhp_remove_multi_state(slot);
1038 		return ret;
1039 	}
1040 
1041 	cpuhp_slot = slot;
1042 	return 0;
1043 }
1044 
1045 static void i915_pmu_unregister_cpuhp_state(struct i915_pmu *pmu)
1046 {
1047 	WARN_ON(cpuhp_slot == CPUHP_INVALID);
1048 	WARN_ON(cpuhp_state_remove_instance(cpuhp_slot, &pmu->node));
1049 	cpuhp_remove_multi_state(cpuhp_slot);
1050 }
1051 
1052 static bool is_igp(struct drm_i915_private *i915)
1053 {
1054 	struct pci_dev *pdev = i915->drm.pdev;
1055 
1056 	/* IGP is 0000:00:02.0 */
1057 	return pci_domain_nr(pdev->bus) == 0 &&
1058 	       pdev->bus->number == 0 &&
1059 	       PCI_SLOT(pdev->devfn) == 2 &&
1060 	       PCI_FUNC(pdev->devfn) == 0;
1061 }
1062 
1063 void i915_pmu_register(struct drm_i915_private *i915)
1064 {
1065 	struct i915_pmu *pmu = &i915->pmu;
1066 	int ret = -ENOMEM;
1067 
1068 	if (INTEL_GEN(i915) <= 2) {
1069 		dev_info(i915->drm.dev, "PMU not supported for this GPU.");
1070 		return;
1071 	}
1072 
1073 	spin_lock_init(&pmu->lock);
1074 	hrtimer_init(&pmu->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1075 	pmu->timer.function = i915_sample;
1076 
1077 	if (!is_igp(i915))
1078 		pmu->name = kasprintf(GFP_KERNEL,
1079 				      "i915-%s",
1080 				      dev_name(i915->drm.dev));
1081 	else
1082 		pmu->name = "i915";
1083 	if (!pmu->name)
1084 		goto err;
1085 
1086 	i915_pmu_events_attr_group.attrs = create_event_attributes(pmu);
1087 	if (!i915_pmu_events_attr_group.attrs)
1088 		goto err_name;
1089 
1090 	pmu->base.attr_groups	= i915_pmu_attr_groups;
1091 	pmu->base.task_ctx_nr	= perf_invalid_context;
1092 	pmu->base.event_init	= i915_pmu_event_init;
1093 	pmu->base.add		= i915_pmu_event_add;
1094 	pmu->base.del		= i915_pmu_event_del;
1095 	pmu->base.start		= i915_pmu_event_start;
1096 	pmu->base.stop		= i915_pmu_event_stop;
1097 	pmu->base.read		= i915_pmu_event_read;
1098 	pmu->base.event_idx	= i915_pmu_event_event_idx;
1099 
1100 	ret = perf_pmu_register(&pmu->base, pmu->name, -1);
1101 	if (ret)
1102 		goto err_attr;
1103 
1104 	ret = i915_pmu_register_cpuhp_state(pmu);
1105 	if (ret)
1106 		goto err_unreg;
1107 
1108 	return;
1109 
1110 err_unreg:
1111 	perf_pmu_unregister(&pmu->base);
1112 err_attr:
1113 	pmu->base.event_init = NULL;
1114 	free_event_attributes(pmu);
1115 err_name:
1116 	if (!is_igp(i915))
1117 		kfree(pmu->name);
1118 err:
1119 	dev_notice(i915->drm.dev, "Failed to register PMU!\n");
1120 }
1121 
1122 void i915_pmu_unregister(struct drm_i915_private *i915)
1123 {
1124 	struct i915_pmu *pmu = &i915->pmu;
1125 
1126 	if (!pmu->base.event_init)
1127 		return;
1128 
1129 	WARN_ON(pmu->enable);
1130 
1131 	hrtimer_cancel(&pmu->timer);
1132 
1133 	i915_pmu_unregister_cpuhp_state(pmu);
1134 
1135 	perf_pmu_unregister(&pmu->base);
1136 	pmu->base.event_init = NULL;
1137 	if (!is_igp(i915))
1138 		kfree(pmu->name);
1139 	free_event_attributes(pmu);
1140 }
1141