xref: /openbmc/linux/drivers/gpu/drm/i915/i915_pmu.c (revision c4a54f70)
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 bool exclusive_mmio_access(const struct drm_i915_private *i915)
263 {
264 	/*
265 	 * We have to avoid concurrent mmio cache line access on gen7 or
266 	 * risk a machine hang. For a fun history lesson dig out the old
267 	 * userspace intel_gpu_top and run it on Ivybridge or Haswell!
268 	 */
269 	return IS_GEN(i915, 7);
270 }
271 
272 static void engine_sample(struct intel_engine_cs *engine, unsigned int period_ns)
273 {
274 	struct intel_engine_pmu *pmu = &engine->pmu;
275 	bool busy;
276 	u32 val;
277 
278 	val = ENGINE_READ_FW(engine, RING_CTL);
279 	if (val == 0) /* powerwell off => engine idle */
280 		return;
281 
282 	if (val & RING_WAIT)
283 		add_sample(&pmu->sample[I915_SAMPLE_WAIT], period_ns);
284 	if (val & RING_WAIT_SEMAPHORE)
285 		add_sample(&pmu->sample[I915_SAMPLE_SEMA], period_ns);
286 
287 	/* No need to sample when busy stats are supported. */
288 	if (intel_engine_supports_stats(engine))
289 		return;
290 
291 	/*
292 	 * While waiting on a semaphore or event, MI_MODE reports the
293 	 * ring as idle. However, previously using the seqno, and with
294 	 * execlists sampling, we account for the ring waiting as the
295 	 * engine being busy. Therefore, we record the sample as being
296 	 * busy if either waiting or !idle.
297 	 */
298 	busy = val & (RING_WAIT_SEMAPHORE | RING_WAIT);
299 	if (!busy) {
300 		val = ENGINE_READ_FW(engine, RING_MI_MODE);
301 		busy = !(val & MODE_IDLE);
302 	}
303 	if (busy)
304 		add_sample(&pmu->sample[I915_SAMPLE_BUSY], period_ns);
305 }
306 
307 static void
308 engines_sample(struct intel_gt *gt, unsigned int period_ns)
309 {
310 	struct drm_i915_private *i915 = gt->i915;
311 	struct intel_engine_cs *engine;
312 	enum intel_engine_id id;
313 	unsigned long flags;
314 
315 	if ((i915->pmu.enable & ENGINE_SAMPLE_MASK) == 0)
316 		return;
317 
318 	if (!intel_gt_pm_is_awake(gt))
319 		return;
320 
321 	for_each_engine(engine, gt, id) {
322 		if (!intel_engine_pm_get_if_awake(engine))
323 			continue;
324 
325 		if (exclusive_mmio_access(i915)) {
326 			spin_lock_irqsave(&engine->uncore->lock, flags);
327 			engine_sample(engine, period_ns);
328 			spin_unlock_irqrestore(&engine->uncore->lock, flags);
329 		} else {
330 			engine_sample(engine, period_ns);
331 		}
332 
333 		intel_engine_pm_put_async(engine);
334 	}
335 }
336 
337 static void
338 add_sample_mult(struct i915_pmu_sample *sample, u32 val, u32 mul)
339 {
340 	sample->cur += mul_u32_u32(val, mul);
341 }
342 
343 static bool frequency_sampling_enabled(struct i915_pmu *pmu)
344 {
345 	return pmu->enable &
346 	       (config_enabled_mask(I915_PMU_ACTUAL_FREQUENCY) |
347 		config_enabled_mask(I915_PMU_REQUESTED_FREQUENCY));
348 }
349 
350 static void
351 frequency_sample(struct intel_gt *gt, unsigned int period_ns)
352 {
353 	struct drm_i915_private *i915 = gt->i915;
354 	struct intel_uncore *uncore = gt->uncore;
355 	struct i915_pmu *pmu = &i915->pmu;
356 	struct intel_rps *rps = &gt->rps;
357 
358 	if (!frequency_sampling_enabled(pmu))
359 		return;
360 
361 	/* Report 0/0 (actual/requested) frequency while parked. */
362 	if (!intel_gt_pm_get_if_awake(gt))
363 		return;
364 
365 	if (pmu->enable & config_enabled_mask(I915_PMU_ACTUAL_FREQUENCY)) {
366 		u32 val;
367 
368 		/*
369 		 * We take a quick peek here without using forcewake
370 		 * so that we don't perturb the system under observation
371 		 * (forcewake => !rc6 => increased power use). We expect
372 		 * that if the read fails because it is outside of the
373 		 * mmio power well, then it will return 0 -- in which
374 		 * case we assume the system is running at the intended
375 		 * frequency. Fortunately, the read should rarely fail!
376 		 */
377 		val = intel_uncore_read_fw(uncore, GEN6_RPSTAT1);
378 		if (val)
379 			val = intel_rps_get_cagf(rps, val);
380 		else
381 			val = rps->cur_freq;
382 
383 		add_sample_mult(&pmu->sample[__I915_SAMPLE_FREQ_ACT],
384 				intel_gpu_freq(rps, val), period_ns / 1000);
385 	}
386 
387 	if (pmu->enable & config_enabled_mask(I915_PMU_REQUESTED_FREQUENCY)) {
388 		add_sample_mult(&pmu->sample[__I915_SAMPLE_FREQ_REQ],
389 				intel_gpu_freq(rps, rps->cur_freq),
390 				period_ns / 1000);
391 	}
392 
393 	intel_gt_pm_put_async(gt);
394 }
395 
396 static enum hrtimer_restart i915_sample(struct hrtimer *hrtimer)
397 {
398 	struct drm_i915_private *i915 =
399 		container_of(hrtimer, struct drm_i915_private, pmu.timer);
400 	struct i915_pmu *pmu = &i915->pmu;
401 	struct intel_gt *gt = &i915->gt;
402 	unsigned int period_ns;
403 	ktime_t now;
404 
405 	if (!READ_ONCE(pmu->timer_enabled))
406 		return HRTIMER_NORESTART;
407 
408 	now = ktime_get();
409 	period_ns = ktime_to_ns(ktime_sub(now, pmu->timer_last));
410 	pmu->timer_last = now;
411 
412 	/*
413 	 * Strictly speaking the passed in period may not be 100% accurate for
414 	 * all internal calculation, since some amount of time can be spent on
415 	 * grabbing the forcewake. However the potential error from timer call-
416 	 * back delay greatly dominates this so we keep it simple.
417 	 */
418 	engines_sample(gt, period_ns);
419 	frequency_sample(gt, period_ns);
420 
421 	hrtimer_forward(hrtimer, now, ns_to_ktime(PERIOD));
422 
423 	return HRTIMER_RESTART;
424 }
425 
426 static u64 count_interrupts(struct drm_i915_private *i915)
427 {
428 	/* open-coded kstat_irqs() */
429 	struct irq_desc *desc = irq_to_desc(i915->drm.pdev->irq);
430 	u64 sum = 0;
431 	int cpu;
432 
433 	if (!desc || !desc->kstat_irqs)
434 		return 0;
435 
436 	for_each_possible_cpu(cpu)
437 		sum += *per_cpu_ptr(desc->kstat_irqs, cpu);
438 
439 	return sum;
440 }
441 
442 static void i915_pmu_event_destroy(struct perf_event *event)
443 {
444 	WARN_ON(event->parent);
445 	module_put(THIS_MODULE);
446 }
447 
448 static int
449 engine_event_status(struct intel_engine_cs *engine,
450 		    enum drm_i915_pmu_engine_sample sample)
451 {
452 	switch (sample) {
453 	case I915_SAMPLE_BUSY:
454 	case I915_SAMPLE_WAIT:
455 		break;
456 	case I915_SAMPLE_SEMA:
457 		if (INTEL_GEN(engine->i915) < 6)
458 			return -ENODEV;
459 		break;
460 	default:
461 		return -ENOENT;
462 	}
463 
464 	return 0;
465 }
466 
467 static int
468 config_status(struct drm_i915_private *i915, u64 config)
469 {
470 	switch (config) {
471 	case I915_PMU_ACTUAL_FREQUENCY:
472 		if (IS_VALLEYVIEW(i915) || IS_CHERRYVIEW(i915))
473 			/* Requires a mutex for sampling! */
474 			return -ENODEV;
475 		/* Fall-through. */
476 	case I915_PMU_REQUESTED_FREQUENCY:
477 		if (INTEL_GEN(i915) < 6)
478 			return -ENODEV;
479 		break;
480 	case I915_PMU_INTERRUPTS:
481 		break;
482 	case I915_PMU_RC6_RESIDENCY:
483 		if (!HAS_RC6(i915))
484 			return -ENODEV;
485 		break;
486 	default:
487 		return -ENOENT;
488 	}
489 
490 	return 0;
491 }
492 
493 static int engine_event_init(struct perf_event *event)
494 {
495 	struct drm_i915_private *i915 =
496 		container_of(event->pmu, typeof(*i915), pmu.base);
497 	struct intel_engine_cs *engine;
498 
499 	engine = intel_engine_lookup_user(i915, engine_event_class(event),
500 					  engine_event_instance(event));
501 	if (!engine)
502 		return -ENODEV;
503 
504 	return engine_event_status(engine, engine_event_sample(event));
505 }
506 
507 static int i915_pmu_event_init(struct perf_event *event)
508 {
509 	struct drm_i915_private *i915 =
510 		container_of(event->pmu, typeof(*i915), pmu.base);
511 	int ret;
512 
513 	if (event->attr.type != event->pmu->type)
514 		return -ENOENT;
515 
516 	/* unsupported modes and filters */
517 	if (event->attr.sample_period) /* no sampling */
518 		return -EINVAL;
519 
520 	if (has_branch_stack(event))
521 		return -EOPNOTSUPP;
522 
523 	if (event->cpu < 0)
524 		return -EINVAL;
525 
526 	/* only allow running on one cpu at a time */
527 	if (!cpumask_test_cpu(event->cpu, &i915_pmu_cpumask))
528 		return -EINVAL;
529 
530 	if (is_engine_event(event))
531 		ret = engine_event_init(event);
532 	else
533 		ret = config_status(i915, event->attr.config);
534 	if (ret)
535 		return ret;
536 
537 	if (!event->parent) {
538 		__module_get(THIS_MODULE);
539 		event->destroy = i915_pmu_event_destroy;
540 	}
541 
542 	return 0;
543 }
544 
545 static u64 __i915_pmu_event_read(struct perf_event *event)
546 {
547 	struct drm_i915_private *i915 =
548 		container_of(event->pmu, typeof(*i915), pmu.base);
549 	struct i915_pmu *pmu = &i915->pmu;
550 	u64 val = 0;
551 
552 	if (is_engine_event(event)) {
553 		u8 sample = engine_event_sample(event);
554 		struct intel_engine_cs *engine;
555 
556 		engine = intel_engine_lookup_user(i915,
557 						  engine_event_class(event),
558 						  engine_event_instance(event));
559 
560 		if (drm_WARN_ON_ONCE(&i915->drm, !engine)) {
561 			/* Do nothing */
562 		} else if (sample == I915_SAMPLE_BUSY &&
563 			   intel_engine_supports_stats(engine)) {
564 			val = ktime_to_ns(intel_engine_get_busy_time(engine));
565 		} else {
566 			val = engine->pmu.sample[sample].cur;
567 		}
568 	} else {
569 		switch (event->attr.config) {
570 		case I915_PMU_ACTUAL_FREQUENCY:
571 			val =
572 			   div_u64(pmu->sample[__I915_SAMPLE_FREQ_ACT].cur,
573 				   USEC_PER_SEC /* to MHz */);
574 			break;
575 		case I915_PMU_REQUESTED_FREQUENCY:
576 			val =
577 			   div_u64(pmu->sample[__I915_SAMPLE_FREQ_REQ].cur,
578 				   USEC_PER_SEC /* to MHz */);
579 			break;
580 		case I915_PMU_INTERRUPTS:
581 			val = count_interrupts(i915);
582 			break;
583 		case I915_PMU_RC6_RESIDENCY:
584 			val = get_rc6(&i915->gt);
585 			break;
586 		}
587 	}
588 
589 	return val;
590 }
591 
592 static void i915_pmu_event_read(struct perf_event *event)
593 {
594 	struct hw_perf_event *hwc = &event->hw;
595 	u64 prev, new;
596 
597 again:
598 	prev = local64_read(&hwc->prev_count);
599 	new = __i915_pmu_event_read(event);
600 
601 	if (local64_cmpxchg(&hwc->prev_count, prev, new) != prev)
602 		goto again;
603 
604 	local64_add(new - prev, &event->count);
605 }
606 
607 static void i915_pmu_enable(struct perf_event *event)
608 {
609 	struct drm_i915_private *i915 =
610 		container_of(event->pmu, typeof(*i915), pmu.base);
611 	unsigned int bit = event_enabled_bit(event);
612 	struct i915_pmu *pmu = &i915->pmu;
613 	intel_wakeref_t wakeref;
614 	unsigned long flags;
615 
616 	wakeref = intel_runtime_pm_get(&i915->runtime_pm);
617 	spin_lock_irqsave(&pmu->lock, flags);
618 
619 	/*
620 	 * Update the bitmask of enabled events and increment
621 	 * the event reference counter.
622 	 */
623 	BUILD_BUG_ON(ARRAY_SIZE(pmu->enable_count) != I915_PMU_MASK_BITS);
624 	GEM_BUG_ON(bit >= ARRAY_SIZE(pmu->enable_count));
625 	GEM_BUG_ON(pmu->enable_count[bit] == ~0);
626 
627 	if (pmu->enable_count[bit] == 0 &&
628 	    config_enabled_mask(I915_PMU_RC6_RESIDENCY) & BIT_ULL(bit)) {
629 		pmu->sample[__I915_SAMPLE_RC6_LAST_REPORTED].cur = 0;
630 		pmu->sample[__I915_SAMPLE_RC6].cur = __get_rc6(&i915->gt);
631 		pmu->sleep_last = ktime_get();
632 	}
633 
634 	pmu->enable |= BIT_ULL(bit);
635 	pmu->enable_count[bit]++;
636 
637 	/*
638 	 * Start the sampling timer if needed and not already enabled.
639 	 */
640 	__i915_pmu_maybe_start_timer(pmu);
641 
642 	/*
643 	 * For per-engine events the bitmask and reference counting
644 	 * is stored per engine.
645 	 */
646 	if (is_engine_event(event)) {
647 		u8 sample = engine_event_sample(event);
648 		struct intel_engine_cs *engine;
649 
650 		engine = intel_engine_lookup_user(i915,
651 						  engine_event_class(event),
652 						  engine_event_instance(event));
653 
654 		BUILD_BUG_ON(ARRAY_SIZE(engine->pmu.enable_count) !=
655 			     I915_ENGINE_SAMPLE_COUNT);
656 		BUILD_BUG_ON(ARRAY_SIZE(engine->pmu.sample) !=
657 			     I915_ENGINE_SAMPLE_COUNT);
658 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.enable_count));
659 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.sample));
660 		GEM_BUG_ON(engine->pmu.enable_count[sample] == ~0);
661 
662 		engine->pmu.enable |= BIT(sample);
663 		engine->pmu.enable_count[sample]++;
664 	}
665 
666 	spin_unlock_irqrestore(&pmu->lock, flags);
667 
668 	/*
669 	 * Store the current counter value so we can report the correct delta
670 	 * for all listeners. Even when the event was already enabled and has
671 	 * an existing non-zero value.
672 	 */
673 	local64_set(&event->hw.prev_count, __i915_pmu_event_read(event));
674 
675 	intel_runtime_pm_put(&i915->runtime_pm, wakeref);
676 }
677 
678 static void i915_pmu_disable(struct perf_event *event)
679 {
680 	struct drm_i915_private *i915 =
681 		container_of(event->pmu, typeof(*i915), pmu.base);
682 	unsigned int bit = event_enabled_bit(event);
683 	struct i915_pmu *pmu = &i915->pmu;
684 	unsigned long flags;
685 
686 	spin_lock_irqsave(&pmu->lock, flags);
687 
688 	if (is_engine_event(event)) {
689 		u8 sample = engine_event_sample(event);
690 		struct intel_engine_cs *engine;
691 
692 		engine = intel_engine_lookup_user(i915,
693 						  engine_event_class(event),
694 						  engine_event_instance(event));
695 
696 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.enable_count));
697 		GEM_BUG_ON(sample >= ARRAY_SIZE(engine->pmu.sample));
698 		GEM_BUG_ON(engine->pmu.enable_count[sample] == 0);
699 
700 		/*
701 		 * Decrement the reference count and clear the enabled
702 		 * bitmask when the last listener on an event goes away.
703 		 */
704 		if (--engine->pmu.enable_count[sample] == 0)
705 			engine->pmu.enable &= ~BIT(sample);
706 	}
707 
708 	GEM_BUG_ON(bit >= ARRAY_SIZE(pmu->enable_count));
709 	GEM_BUG_ON(pmu->enable_count[bit] == 0);
710 	/*
711 	 * Decrement the reference count and clear the enabled
712 	 * bitmask when the last listener on an event goes away.
713 	 */
714 	if (--pmu->enable_count[bit] == 0) {
715 		pmu->enable &= ~BIT_ULL(bit);
716 		pmu->timer_enabled &= pmu_needs_timer(pmu, true);
717 	}
718 
719 	spin_unlock_irqrestore(&pmu->lock, flags);
720 }
721 
722 static void i915_pmu_event_start(struct perf_event *event, int flags)
723 {
724 	i915_pmu_enable(event);
725 	event->hw.state = 0;
726 }
727 
728 static void i915_pmu_event_stop(struct perf_event *event, int flags)
729 {
730 	if (flags & PERF_EF_UPDATE)
731 		i915_pmu_event_read(event);
732 	i915_pmu_disable(event);
733 	event->hw.state = PERF_HES_STOPPED;
734 }
735 
736 static int i915_pmu_event_add(struct perf_event *event, int flags)
737 {
738 	if (flags & PERF_EF_START)
739 		i915_pmu_event_start(event, flags);
740 
741 	return 0;
742 }
743 
744 static void i915_pmu_event_del(struct perf_event *event, int flags)
745 {
746 	i915_pmu_event_stop(event, PERF_EF_UPDATE);
747 }
748 
749 static int i915_pmu_event_event_idx(struct perf_event *event)
750 {
751 	return 0;
752 }
753 
754 struct i915_str_attribute {
755 	struct device_attribute attr;
756 	const char *str;
757 };
758 
759 static ssize_t i915_pmu_format_show(struct device *dev,
760 				    struct device_attribute *attr, char *buf)
761 {
762 	struct i915_str_attribute *eattr;
763 
764 	eattr = container_of(attr, struct i915_str_attribute, attr);
765 	return sprintf(buf, "%s\n", eattr->str);
766 }
767 
768 #define I915_PMU_FORMAT_ATTR(_name, _config) \
769 	(&((struct i915_str_attribute[]) { \
770 		{ .attr = __ATTR(_name, 0444, i915_pmu_format_show, NULL), \
771 		  .str = _config, } \
772 	})[0].attr.attr)
773 
774 static struct attribute *i915_pmu_format_attrs[] = {
775 	I915_PMU_FORMAT_ATTR(i915_eventid, "config:0-20"),
776 	NULL,
777 };
778 
779 static const struct attribute_group i915_pmu_format_attr_group = {
780 	.name = "format",
781 	.attrs = i915_pmu_format_attrs,
782 };
783 
784 struct i915_ext_attribute {
785 	struct device_attribute attr;
786 	unsigned long val;
787 };
788 
789 static ssize_t i915_pmu_event_show(struct device *dev,
790 				   struct device_attribute *attr, char *buf)
791 {
792 	struct i915_ext_attribute *eattr;
793 
794 	eattr = container_of(attr, struct i915_ext_attribute, attr);
795 	return sprintf(buf, "config=0x%lx\n", eattr->val);
796 }
797 
798 static ssize_t
799 i915_pmu_get_attr_cpumask(struct device *dev,
800 			  struct device_attribute *attr,
801 			  char *buf)
802 {
803 	return cpumap_print_to_pagebuf(true, buf, &i915_pmu_cpumask);
804 }
805 
806 static DEVICE_ATTR(cpumask, 0444, i915_pmu_get_attr_cpumask, NULL);
807 
808 static struct attribute *i915_cpumask_attrs[] = {
809 	&dev_attr_cpumask.attr,
810 	NULL,
811 };
812 
813 static const struct attribute_group i915_pmu_cpumask_attr_group = {
814 	.attrs = i915_cpumask_attrs,
815 };
816 
817 #define __event(__config, __name, __unit) \
818 { \
819 	.config = (__config), \
820 	.name = (__name), \
821 	.unit = (__unit), \
822 }
823 
824 #define __engine_event(__sample, __name) \
825 { \
826 	.sample = (__sample), \
827 	.name = (__name), \
828 }
829 
830 static struct i915_ext_attribute *
831 add_i915_attr(struct i915_ext_attribute *attr, const char *name, u64 config)
832 {
833 	sysfs_attr_init(&attr->attr.attr);
834 	attr->attr.attr.name = name;
835 	attr->attr.attr.mode = 0444;
836 	attr->attr.show = i915_pmu_event_show;
837 	attr->val = config;
838 
839 	return ++attr;
840 }
841 
842 static struct perf_pmu_events_attr *
843 add_pmu_attr(struct perf_pmu_events_attr *attr, const char *name,
844 	     const char *str)
845 {
846 	sysfs_attr_init(&attr->attr.attr);
847 	attr->attr.attr.name = name;
848 	attr->attr.attr.mode = 0444;
849 	attr->attr.show = perf_event_sysfs_show;
850 	attr->event_str = str;
851 
852 	return ++attr;
853 }
854 
855 static struct attribute **
856 create_event_attributes(struct i915_pmu *pmu)
857 {
858 	struct drm_i915_private *i915 = container_of(pmu, typeof(*i915), pmu);
859 	static const struct {
860 		u64 config;
861 		const char *name;
862 		const char *unit;
863 	} events[] = {
864 		__event(I915_PMU_ACTUAL_FREQUENCY, "actual-frequency", "M"),
865 		__event(I915_PMU_REQUESTED_FREQUENCY, "requested-frequency", "M"),
866 		__event(I915_PMU_INTERRUPTS, "interrupts", NULL),
867 		__event(I915_PMU_RC6_RESIDENCY, "rc6-residency", "ns"),
868 	};
869 	static const struct {
870 		enum drm_i915_pmu_engine_sample sample;
871 		char *name;
872 	} engine_events[] = {
873 		__engine_event(I915_SAMPLE_BUSY, "busy"),
874 		__engine_event(I915_SAMPLE_SEMA, "sema"),
875 		__engine_event(I915_SAMPLE_WAIT, "wait"),
876 	};
877 	unsigned int count = 0;
878 	struct perf_pmu_events_attr *pmu_attr = NULL, *pmu_iter;
879 	struct i915_ext_attribute *i915_attr = NULL, *i915_iter;
880 	struct attribute **attr = NULL, **attr_iter;
881 	struct intel_engine_cs *engine;
882 	unsigned int i;
883 
884 	/* Count how many counters we will be exposing. */
885 	for (i = 0; i < ARRAY_SIZE(events); i++) {
886 		if (!config_status(i915, events[i].config))
887 			count++;
888 	}
889 
890 	for_each_uabi_engine(engine, i915) {
891 		for (i = 0; i < ARRAY_SIZE(engine_events); i++) {
892 			if (!engine_event_status(engine,
893 						 engine_events[i].sample))
894 				count++;
895 		}
896 	}
897 
898 	/* Allocate attribute objects and table. */
899 	i915_attr = kcalloc(count, sizeof(*i915_attr), GFP_KERNEL);
900 	if (!i915_attr)
901 		goto err_alloc;
902 
903 	pmu_attr = kcalloc(count, sizeof(*pmu_attr), GFP_KERNEL);
904 	if (!pmu_attr)
905 		goto err_alloc;
906 
907 	/* Max one pointer of each attribute type plus a termination entry. */
908 	attr = kcalloc(count * 2 + 1, sizeof(*attr), GFP_KERNEL);
909 	if (!attr)
910 		goto err_alloc;
911 
912 	i915_iter = i915_attr;
913 	pmu_iter = pmu_attr;
914 	attr_iter = attr;
915 
916 	/* Initialize supported non-engine counters. */
917 	for (i = 0; i < ARRAY_SIZE(events); i++) {
918 		char *str;
919 
920 		if (config_status(i915, events[i].config))
921 			continue;
922 
923 		str = kstrdup(events[i].name, GFP_KERNEL);
924 		if (!str)
925 			goto err;
926 
927 		*attr_iter++ = &i915_iter->attr.attr;
928 		i915_iter = add_i915_attr(i915_iter, str, events[i].config);
929 
930 		if (events[i].unit) {
931 			str = kasprintf(GFP_KERNEL, "%s.unit", events[i].name);
932 			if (!str)
933 				goto err;
934 
935 			*attr_iter++ = &pmu_iter->attr.attr;
936 			pmu_iter = add_pmu_attr(pmu_iter, str, events[i].unit);
937 		}
938 	}
939 
940 	/* Initialize supported engine counters. */
941 	for_each_uabi_engine(engine, i915) {
942 		for (i = 0; i < ARRAY_SIZE(engine_events); i++) {
943 			char *str;
944 
945 			if (engine_event_status(engine,
946 						engine_events[i].sample))
947 				continue;
948 
949 			str = kasprintf(GFP_KERNEL, "%s-%s",
950 					engine->name, engine_events[i].name);
951 			if (!str)
952 				goto err;
953 
954 			*attr_iter++ = &i915_iter->attr.attr;
955 			i915_iter =
956 				add_i915_attr(i915_iter, str,
957 					      __I915_PMU_ENGINE(engine->uabi_class,
958 								engine->uabi_instance,
959 								engine_events[i].sample));
960 
961 			str = kasprintf(GFP_KERNEL, "%s-%s.unit",
962 					engine->name, engine_events[i].name);
963 			if (!str)
964 				goto err;
965 
966 			*attr_iter++ = &pmu_iter->attr.attr;
967 			pmu_iter = add_pmu_attr(pmu_iter, str, "ns");
968 		}
969 	}
970 
971 	pmu->i915_attr = i915_attr;
972 	pmu->pmu_attr = pmu_attr;
973 
974 	return attr;
975 
976 err:;
977 	for (attr_iter = attr; *attr_iter; attr_iter++)
978 		kfree((*attr_iter)->name);
979 
980 err_alloc:
981 	kfree(attr);
982 	kfree(i915_attr);
983 	kfree(pmu_attr);
984 
985 	return NULL;
986 }
987 
988 static void free_event_attributes(struct i915_pmu *pmu)
989 {
990 	struct attribute **attr_iter = pmu->events_attr_group.attrs;
991 
992 	for (; *attr_iter; attr_iter++)
993 		kfree((*attr_iter)->name);
994 
995 	kfree(pmu->events_attr_group.attrs);
996 	kfree(pmu->i915_attr);
997 	kfree(pmu->pmu_attr);
998 
999 	pmu->events_attr_group.attrs = NULL;
1000 	pmu->i915_attr = NULL;
1001 	pmu->pmu_attr = NULL;
1002 }
1003 
1004 static int i915_pmu_cpu_online(unsigned int cpu, struct hlist_node *node)
1005 {
1006 	struct i915_pmu *pmu = hlist_entry_safe(node, typeof(*pmu), cpuhp.node);
1007 
1008 	GEM_BUG_ON(!pmu->base.event_init);
1009 
1010 	/* Select the first online CPU as a designated reader. */
1011 	if (!cpumask_weight(&i915_pmu_cpumask))
1012 		cpumask_set_cpu(cpu, &i915_pmu_cpumask);
1013 
1014 	return 0;
1015 }
1016 
1017 static int i915_pmu_cpu_offline(unsigned int cpu, struct hlist_node *node)
1018 {
1019 	struct i915_pmu *pmu = hlist_entry_safe(node, typeof(*pmu), cpuhp.node);
1020 	unsigned int target;
1021 
1022 	GEM_BUG_ON(!pmu->base.event_init);
1023 
1024 	if (cpumask_test_and_clear_cpu(cpu, &i915_pmu_cpumask)) {
1025 		target = cpumask_any_but(topology_sibling_cpumask(cpu), cpu);
1026 		/* Migrate events if there is a valid target */
1027 		if (target < nr_cpu_ids) {
1028 			cpumask_set_cpu(target, &i915_pmu_cpumask);
1029 			perf_pmu_migrate_context(&pmu->base, cpu, target);
1030 		}
1031 	}
1032 
1033 	return 0;
1034 }
1035 
1036 static int i915_pmu_register_cpuhp_state(struct i915_pmu *pmu)
1037 {
1038 	enum cpuhp_state slot;
1039 	int ret;
1040 
1041 	ret = cpuhp_setup_state_multi(CPUHP_AP_ONLINE_DYN,
1042 				      "perf/x86/intel/i915:online",
1043 				      i915_pmu_cpu_online,
1044 				      i915_pmu_cpu_offline);
1045 	if (ret < 0)
1046 		return ret;
1047 
1048 	slot = ret;
1049 	ret = cpuhp_state_add_instance(slot, &pmu->cpuhp.node);
1050 	if (ret) {
1051 		cpuhp_remove_multi_state(slot);
1052 		return ret;
1053 	}
1054 
1055 	pmu->cpuhp.slot = slot;
1056 	return 0;
1057 }
1058 
1059 static void i915_pmu_unregister_cpuhp_state(struct i915_pmu *pmu)
1060 {
1061 	WARN_ON(pmu->cpuhp.slot == CPUHP_INVALID);
1062 	WARN_ON(cpuhp_state_remove_instance(pmu->cpuhp.slot, &pmu->cpuhp.node));
1063 	cpuhp_remove_multi_state(pmu->cpuhp.slot);
1064 	pmu->cpuhp.slot = CPUHP_INVALID;
1065 }
1066 
1067 static bool is_igp(struct drm_i915_private *i915)
1068 {
1069 	struct pci_dev *pdev = i915->drm.pdev;
1070 
1071 	/* IGP is 0000:00:02.0 */
1072 	return pci_domain_nr(pdev->bus) == 0 &&
1073 	       pdev->bus->number == 0 &&
1074 	       PCI_SLOT(pdev->devfn) == 2 &&
1075 	       PCI_FUNC(pdev->devfn) == 0;
1076 }
1077 
1078 void i915_pmu_register(struct drm_i915_private *i915)
1079 {
1080 	struct i915_pmu *pmu = &i915->pmu;
1081 	const struct attribute_group *attr_groups[] = {
1082 		&i915_pmu_format_attr_group,
1083 		&pmu->events_attr_group,
1084 		&i915_pmu_cpumask_attr_group,
1085 		NULL
1086 	};
1087 
1088 	int ret = -ENOMEM;
1089 
1090 	if (INTEL_GEN(i915) <= 2) {
1091 		drm_info(&i915->drm, "PMU not supported for this GPU.");
1092 		return;
1093 	}
1094 
1095 	spin_lock_init(&pmu->lock);
1096 	hrtimer_init(&pmu->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1097 	pmu->timer.function = i915_sample;
1098 	pmu->cpuhp.slot = CPUHP_INVALID;
1099 
1100 	if (!is_igp(i915)) {
1101 		pmu->name = kasprintf(GFP_KERNEL,
1102 				      "i915_%s",
1103 				      dev_name(i915->drm.dev));
1104 		if (pmu->name) {
1105 			/* tools/perf reserves colons as special. */
1106 			strreplace((char *)pmu->name, ':', '_');
1107 		}
1108 	} else {
1109 		pmu->name = "i915";
1110 	}
1111 	if (!pmu->name)
1112 		goto err;
1113 
1114 	pmu->events_attr_group.name = "events";
1115 	pmu->events_attr_group.attrs = create_event_attributes(pmu);
1116 	if (!pmu->events_attr_group.attrs)
1117 		goto err_name;
1118 
1119 	pmu->base.attr_groups = kmemdup(attr_groups, sizeof(attr_groups),
1120 					GFP_KERNEL);
1121 	if (!pmu->base.attr_groups)
1122 		goto err_attr;
1123 
1124 	pmu->base.task_ctx_nr	= perf_invalid_context;
1125 	pmu->base.event_init	= i915_pmu_event_init;
1126 	pmu->base.add		= i915_pmu_event_add;
1127 	pmu->base.del		= i915_pmu_event_del;
1128 	pmu->base.start		= i915_pmu_event_start;
1129 	pmu->base.stop		= i915_pmu_event_stop;
1130 	pmu->base.read		= i915_pmu_event_read;
1131 	pmu->base.event_idx	= i915_pmu_event_event_idx;
1132 
1133 	ret = perf_pmu_register(&pmu->base, pmu->name, -1);
1134 	if (ret)
1135 		goto err_groups;
1136 
1137 	ret = i915_pmu_register_cpuhp_state(pmu);
1138 	if (ret)
1139 		goto err_unreg;
1140 
1141 	return;
1142 
1143 err_unreg:
1144 	perf_pmu_unregister(&pmu->base);
1145 err_groups:
1146 	kfree(pmu->base.attr_groups);
1147 err_attr:
1148 	pmu->base.event_init = NULL;
1149 	free_event_attributes(pmu);
1150 err_name:
1151 	if (!is_igp(i915))
1152 		kfree(pmu->name);
1153 err:
1154 	drm_notice(&i915->drm, "Failed to register PMU!\n");
1155 }
1156 
1157 void i915_pmu_unregister(struct drm_i915_private *i915)
1158 {
1159 	struct i915_pmu *pmu = &i915->pmu;
1160 
1161 	if (!pmu->base.event_init)
1162 		return;
1163 
1164 	drm_WARN_ON(&i915->drm, pmu->enable);
1165 
1166 	hrtimer_cancel(&pmu->timer);
1167 
1168 	i915_pmu_unregister_cpuhp_state(pmu);
1169 
1170 	perf_pmu_unregister(&pmu->base);
1171 	pmu->base.event_init = NULL;
1172 	kfree(pmu->base.attr_groups);
1173 	if (!is_igp(i915))
1174 		kfree(pmu->name);
1175 	free_event_attributes(pmu);
1176 }
1177