1 /*
2  * Copyright © 2015-2016 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  *
23  * Authors:
24  *   Robert Bragg <robert@sixbynine.org>
25  */
26 
27 
28 /**
29  * DOC: i915 Perf Overview
30  *
31  * Gen graphics supports a large number of performance counters that can help
32  * driver and application developers understand and optimize their use of the
33  * GPU.
34  *
35  * This i915 perf interface enables userspace to configure and open a file
36  * descriptor representing a stream of GPU metrics which can then be read() as
37  * a stream of sample records.
38  *
39  * The interface is particularly suited to exposing buffered metrics that are
40  * captured by DMA from the GPU, unsynchronized with and unrelated to the CPU.
41  *
42  * Streams representing a single context are accessible to applications with a
43  * corresponding drm file descriptor, such that OpenGL can use the interface
44  * without special privileges. Access to system-wide metrics requires root
45  * privileges by default, unless changed via the dev.i915.perf_event_paranoid
46  * sysctl option.
47  *
48  */
49 
50 /**
51  * DOC: i915 Perf History and Comparison with Core Perf
52  *
53  * The interface was initially inspired by the core Perf infrastructure but
54  * some notable differences are:
55  *
56  * i915 perf file descriptors represent a "stream" instead of an "event"; where
57  * a perf event primarily corresponds to a single 64bit value, while a stream
58  * might sample sets of tightly-coupled counters, depending on the
59  * configuration.  For example the Gen OA unit isn't designed to support
60  * orthogonal configurations of individual counters; it's configured for a set
61  * of related counters. Samples for an i915 perf stream capturing OA metrics
62  * will include a set of counter values packed in a compact HW specific format.
63  * The OA unit supports a number of different packing formats which can be
64  * selected by the user opening the stream. Perf has support for grouping
65  * events, but each event in the group is configured, validated and
66  * authenticated individually with separate system calls.
67  *
68  * i915 perf stream configurations are provided as an array of u64 (key,value)
69  * pairs, instead of a fixed struct with multiple miscellaneous config members,
70  * interleaved with event-type specific members.
71  *
72  * i915 perf doesn't support exposing metrics via an mmap'd circular buffer.
73  * The supported metrics are being written to memory by the GPU unsynchronized
74  * with the CPU, using HW specific packing formats for counter sets. Sometimes
75  * the constraints on HW configuration require reports to be filtered before it
76  * would be acceptable to expose them to unprivileged applications - to hide
77  * the metrics of other processes/contexts. For these use cases a read() based
78  * interface is a good fit, and provides an opportunity to filter data as it
79  * gets copied from the GPU mapped buffers to userspace buffers.
80  *
81  *
82  * Issues hit with first prototype based on Core Perf
83  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
84  *
85  * The first prototype of this driver was based on the core perf
86  * infrastructure, and while we did make that mostly work, with some changes to
87  * perf, we found we were breaking or working around too many assumptions baked
88  * into perf's currently cpu centric design.
89  *
90  * In the end we didn't see a clear benefit to making perf's implementation and
91  * interface more complex by changing design assumptions while we knew we still
92  * wouldn't be able to use any existing perf based userspace tools.
93  *
94  * Also considering the Gen specific nature of the Observability hardware and
95  * how userspace will sometimes need to combine i915 perf OA metrics with
96  * side-band OA data captured via MI_REPORT_PERF_COUNT commands; we're
97  * expecting the interface to be used by a platform specific userspace such as
98  * OpenGL or tools. This is to say; we aren't inherently missing out on having
99  * a standard vendor/architecture agnostic interface by not using perf.
100  *
101  *
102  * For posterity, in case we might re-visit trying to adapt core perf to be
103  * better suited to exposing i915 metrics these were the main pain points we
104  * hit:
105  *
106  * - The perf based OA PMU driver broke some significant design assumptions:
107  *
108  *   Existing perf pmus are used for profiling work on a cpu and we were
109  *   introducing the idea of _IS_DEVICE pmus with different security
110  *   implications, the need to fake cpu-related data (such as user/kernel
111  *   registers) to fit with perf's current design, and adding _DEVICE records
112  *   as a way to forward device-specific status records.
113  *
114  *   The OA unit writes reports of counters into a circular buffer, without
115  *   involvement from the CPU, making our PMU driver the first of a kind.
116  *
117  *   Given the way we were periodically forward data from the GPU-mapped, OA
118  *   buffer to perf's buffer, those bursts of sample writes looked to perf like
119  *   we were sampling too fast and so we had to subvert its throttling checks.
120  *
121  *   Perf supports groups of counters and allows those to be read via
122  *   transactions internally but transactions currently seem designed to be
123  *   explicitly initiated from the cpu (say in response to a userspace read())
124  *   and while we could pull a report out of the OA buffer we can't
125  *   trigger a report from the cpu on demand.
126  *
127  *   Related to being report based; the OA counters are configured in HW as a
128  *   set while perf generally expects counter configurations to be orthogonal.
129  *   Although counters can be associated with a group leader as they are
130  *   opened, there's no clear precedent for being able to provide group-wide
131  *   configuration attributes (for example we want to let userspace choose the
132  *   OA unit report format used to capture all counters in a set, or specify a
133  *   GPU context to filter metrics on). We avoided using perf's grouping
134  *   feature and forwarded OA reports to userspace via perf's 'raw' sample
135  *   field. This suited our userspace well considering how coupled the counters
136  *   are when dealing with normalizing. It would be inconvenient to split
137  *   counters up into separate events, only to require userspace to recombine
138  *   them. For Mesa it's also convenient to be forwarded raw, periodic reports
139  *   for combining with the side-band raw reports it captures using
140  *   MI_REPORT_PERF_COUNT commands.
141  *
142  *   - As a side note on perf's grouping feature; there was also some concern
143  *     that using PERF_FORMAT_GROUP as a way to pack together counter values
144  *     would quite drastically inflate our sample sizes, which would likely
145  *     lower the effective sampling resolutions we could use when the available
146  *     memory bandwidth is limited.
147  *
148  *     With the OA unit's report formats, counters are packed together as 32
149  *     or 40bit values, with the largest report size being 256 bytes.
150  *
151  *     PERF_FORMAT_GROUP values are 64bit, but there doesn't appear to be a
152  *     documented ordering to the values, implying PERF_FORMAT_ID must also be
153  *     used to add a 64bit ID before each value; giving 16 bytes per counter.
154  *
155  *   Related to counter orthogonality; we can't time share the OA unit, while
156  *   event scheduling is a central design idea within perf for allowing
157  *   userspace to open + enable more events than can be configured in HW at any
158  *   one time.  The OA unit is not designed to allow re-configuration while in
159  *   use. We can't reconfigure the OA unit without losing internal OA unit
160  *   state which we can't access explicitly to save and restore. Reconfiguring
161  *   the OA unit is also relatively slow, involving ~100 register writes. From
162  *   userspace Mesa also depends on a stable OA configuration when emitting
163  *   MI_REPORT_PERF_COUNT commands and importantly the OA unit can't be
164  *   disabled while there are outstanding MI_RPC commands lest we hang the
165  *   command streamer.
166  *
167  *   The contents of sample records aren't extensible by device drivers (i.e.
168  *   the sample_type bits). As an example; Sourab Gupta had been looking to
169  *   attach GPU timestamps to our OA samples. We were shoehorning OA reports
170  *   into sample records by using the 'raw' field, but it's tricky to pack more
171  *   than one thing into this field because events/core.c currently only lets a
172  *   pmu give a single raw data pointer plus len which will be copied into the
173  *   ring buffer. To include more than the OA report we'd have to copy the
174  *   report into an intermediate larger buffer. I'd been considering allowing a
175  *   vector of data+len values to be specified for copying the raw data, but
176  *   it felt like a kludge to being using the raw field for this purpose.
177  *
178  * - It felt like our perf based PMU was making some technical compromises
179  *   just for the sake of using perf:
180  *
181  *   perf_event_open() requires events to either relate to a pid or a specific
182  *   cpu core, while our device pmu related to neither.  Events opened with a
183  *   pid will be automatically enabled/disabled according to the scheduling of
184  *   that process - so not appropriate for us. When an event is related to a
185  *   cpu id, perf ensures pmu methods will be invoked via an inter process
186  *   interrupt on that core. To avoid invasive changes our userspace opened OA
187  *   perf events for a specific cpu. This was workable but it meant the
188  *   majority of the OA driver ran in atomic context, including all OA report
189  *   forwarding, which wasn't really necessary in our case and seems to make
190  *   our locking requirements somewhat complex as we handled the interaction
191  *   with the rest of the i915 driver.
192  */
193 
194 #include <linux/anon_inodes.h>
195 #include <linux/nospec.h>
196 #include <linux/sizes.h>
197 #include <linux/uuid.h>
198 
199 #include "gem/i915_gem_context.h"
200 #include "gem/i915_gem_internal.h"
201 #include "gt/intel_engine_pm.h"
202 #include "gt/intel_engine_regs.h"
203 #include "gt/intel_engine_user.h"
204 #include "gt/intel_execlists_submission.h"
205 #include "gt/intel_gpu_commands.h"
206 #include "gt/intel_gt.h"
207 #include "gt/intel_gt_clock_utils.h"
208 #include "gt/intel_gt_mcr.h"
209 #include "gt/intel_gt_regs.h"
210 #include "gt/intel_lrc.h"
211 #include "gt/intel_lrc_reg.h"
212 #include "gt/intel_rc6.h"
213 #include "gt/intel_ring.h"
214 #include "gt/uc/intel_guc_slpc.h"
215 
216 #include "i915_drv.h"
217 #include "i915_file_private.h"
218 #include "i915_perf.h"
219 #include "i915_perf_oa_regs.h"
220 #include "i915_reg.h"
221 
222 /* HW requires this to be a power of two, between 128k and 16M, though driver
223  * is currently generally designed assuming the largest 16M size is used such
224  * that the overflow cases are unlikely in normal operation.
225  */
226 #define OA_BUFFER_SIZE		SZ_16M
227 
228 #define OA_TAKEN(tail, head)	((tail - head) & (OA_BUFFER_SIZE - 1))
229 
230 /**
231  * DOC: OA Tail Pointer Race
232  *
233  * There's a HW race condition between OA unit tail pointer register updates and
234  * writes to memory whereby the tail pointer can sometimes get ahead of what's
235  * been written out to the OA buffer so far (in terms of what's visible to the
236  * CPU).
237  *
238  * Although this can be observed explicitly while copying reports to userspace
239  * by checking for a zeroed report-id field in tail reports, we want to account
240  * for this earlier, as part of the oa_buffer_check_unlocked to avoid lots of
241  * redundant read() attempts.
242  *
243  * We workaround this issue in oa_buffer_check_unlocked() by reading the reports
244  * in the OA buffer, starting from the tail reported by the HW until we find a
245  * report with its first 2 dwords not 0 meaning its previous report is
246  * completely in memory and ready to be read. Those dwords are also set to 0
247  * once read and the whole buffer is cleared upon OA buffer initialization. The
248  * first dword is the reason for this report while the second is the timestamp,
249  * making the chances of having those 2 fields at 0 fairly unlikely. A more
250  * detailed explanation is available in oa_buffer_check_unlocked().
251  *
252  * Most of the implementation details for this workaround are in
253  * oa_buffer_check_unlocked() and _append_oa_reports()
254  *
255  * Note for posterity: previously the driver used to define an effective tail
256  * pointer that lagged the real pointer by a 'tail margin' measured in bytes
257  * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
258  * This was flawed considering that the OA unit may also automatically generate
259  * non-periodic reports (such as on context switch) or the OA unit may be
260  * enabled without any periodic sampling.
261  */
262 #define OA_TAIL_MARGIN_NSEC	100000ULL
263 #define INVALID_TAIL_PTR	0xffffffff
264 
265 /* The default frequency for checking whether the OA unit has written new
266  * reports to the circular OA buffer...
267  */
268 #define DEFAULT_POLL_FREQUENCY_HZ 200
269 #define DEFAULT_POLL_PERIOD_NS (NSEC_PER_SEC / DEFAULT_POLL_FREQUENCY_HZ)
270 
271 /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
272 static u32 i915_perf_stream_paranoid = true;
273 
274 /* The maximum exponent the hardware accepts is 63 (essentially it selects one
275  * of the 64bit timestamp bits to trigger reports from) but there's currently
276  * no known use case for sampling as infrequently as once per 47 thousand years.
277  *
278  * Since the timestamps included in OA reports are only 32bits it seems
279  * reasonable to limit the OA exponent where it's still possible to account for
280  * overflow in OA report timestamps.
281  */
282 #define OA_EXPONENT_MAX 31
283 
284 #define INVALID_CTX_ID 0xffffffff
285 
286 /* On Gen8+ automatically triggered OA reports include a 'reason' field... */
287 #define OAREPORT_REASON_MASK           0x3f
288 #define OAREPORT_REASON_MASK_EXTENDED  0x7f
289 #define OAREPORT_REASON_SHIFT          19
290 #define OAREPORT_REASON_TIMER          (1<<0)
291 #define OAREPORT_REASON_CTX_SWITCH     (1<<3)
292 #define OAREPORT_REASON_CLK_RATIO      (1<<5)
293 
294 #define HAS_MI_SET_PREDICATE(i915) (GRAPHICS_VER_FULL(i915) >= IP_VER(12, 50))
295 
296 /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
297  *
298  * The highest sampling frequency we can theoretically program the OA unit
299  * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
300  *
301  * Initialized just before we register the sysctl parameter.
302  */
303 static int oa_sample_rate_hard_limit;
304 
305 /* Theoretically we can program the OA unit to sample every 160ns but don't
306  * allow that by default unless root...
307  *
308  * The default threshold of 100000Hz is based on perf's similar
309  * kernel.perf_event_max_sample_rate sysctl parameter.
310  */
311 static u32 i915_oa_max_sample_rate = 100000;
312 
313 /* XXX: beware if future OA HW adds new report formats that the current
314  * code assumes all reports have a power-of-two size and ~(size - 1) can
315  * be used as a mask to align the OA tail pointer.
316  */
317 static const struct i915_oa_format oa_formats[I915_OA_FORMAT_MAX] = {
318 	[I915_OA_FORMAT_A13]	    = { 0, 64 },
319 	[I915_OA_FORMAT_A29]	    = { 1, 128 },
320 	[I915_OA_FORMAT_A13_B8_C8]  = { 2, 128 },
321 	/* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
322 	[I915_OA_FORMAT_B4_C8]	    = { 4, 64 },
323 	[I915_OA_FORMAT_A45_B8_C8]  = { 5, 256 },
324 	[I915_OA_FORMAT_B4_C8_A16]  = { 6, 128 },
325 	[I915_OA_FORMAT_C4_B8]	    = { 7, 64 },
326 	[I915_OA_FORMAT_A12]		    = { 0, 64 },
327 	[I915_OA_FORMAT_A12_B8_C8]	    = { 2, 128 },
328 	[I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
329 	[I915_OAR_FORMAT_A32u40_A4u32_B8_C8]    = { 5, 256 },
330 	[I915_OA_FORMAT_A24u40_A14u32_B8_C8]    = { 5, 256 },
331 	[I915_OAM_FORMAT_MPEC8u64_B8_C8]	= { 1, 192, TYPE_OAM, HDR_64_BIT },
332 	[I915_OAM_FORMAT_MPEC8u32_B8_C8]	= { 2, 128, TYPE_OAM, HDR_64_BIT },
333 };
334 
335 static const u32 mtl_oa_base[] = {
336 	[PERF_GROUP_OAM_SAMEDIA_0] = 0x393000,
337 };
338 
339 #define SAMPLE_OA_REPORT      (1<<0)
340 
341 /**
342  * struct perf_open_properties - for validated properties given to open a stream
343  * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
344  * @single_context: Whether a single or all gpu contexts should be monitored
345  * @hold_preemption: Whether the preemption is disabled for the filtered
346  *                   context
347  * @ctx_handle: A gem ctx handle for use with @single_context
348  * @metrics_set: An ID for an OA unit metric set advertised via sysfs
349  * @oa_format: An OA unit HW report format
350  * @oa_periodic: Whether to enable periodic OA unit sampling
351  * @oa_period_exponent: The OA unit sampling period is derived from this
352  * @engine: The engine (typically rcs0) being monitored by the OA unit
353  * @has_sseu: Whether @sseu was specified by userspace
354  * @sseu: internal SSEU configuration computed either from the userspace
355  *        specified configuration in the opening parameters or a default value
356  *        (see get_default_sseu_config())
357  * @poll_oa_period: The period in nanoseconds at which the CPU will check for OA
358  * data availability
359  *
360  * As read_properties_unlocked() enumerates and validates the properties given
361  * to open a stream of metrics the configuration is built up in the structure
362  * which starts out zero initialized.
363  */
364 struct perf_open_properties {
365 	u32 sample_flags;
366 
367 	u64 single_context:1;
368 	u64 hold_preemption:1;
369 	u64 ctx_handle;
370 
371 	/* OA sampling state */
372 	int metrics_set;
373 	int oa_format;
374 	bool oa_periodic;
375 	int oa_period_exponent;
376 
377 	struct intel_engine_cs *engine;
378 
379 	bool has_sseu;
380 	struct intel_sseu sseu;
381 
382 	u64 poll_oa_period;
383 };
384 
385 struct i915_oa_config_bo {
386 	struct llist_node node;
387 
388 	struct i915_oa_config *oa_config;
389 	struct i915_vma *vma;
390 };
391 
392 static struct ctl_table_header *sysctl_header;
393 
394 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer);
395 
i915_oa_config_release(struct kref * ref)396 void i915_oa_config_release(struct kref *ref)
397 {
398 	struct i915_oa_config *oa_config =
399 		container_of(ref, typeof(*oa_config), ref);
400 
401 	kfree(oa_config->flex_regs);
402 	kfree(oa_config->b_counter_regs);
403 	kfree(oa_config->mux_regs);
404 
405 	kfree_rcu(oa_config, rcu);
406 }
407 
408 struct i915_oa_config *
i915_perf_get_oa_config(struct i915_perf * perf,int metrics_set)409 i915_perf_get_oa_config(struct i915_perf *perf, int metrics_set)
410 {
411 	struct i915_oa_config *oa_config;
412 
413 	rcu_read_lock();
414 	oa_config = idr_find(&perf->metrics_idr, metrics_set);
415 	if (oa_config)
416 		oa_config = i915_oa_config_get(oa_config);
417 	rcu_read_unlock();
418 
419 	return oa_config;
420 }
421 
free_oa_config_bo(struct i915_oa_config_bo * oa_bo)422 static void free_oa_config_bo(struct i915_oa_config_bo *oa_bo)
423 {
424 	i915_oa_config_put(oa_bo->oa_config);
425 	i915_vma_put(oa_bo->vma);
426 	kfree(oa_bo);
427 }
428 
429 static inline const
__oa_regs(struct i915_perf_stream * stream)430 struct i915_perf_regs *__oa_regs(struct i915_perf_stream *stream)
431 {
432 	return &stream->engine->oa_group->regs;
433 }
434 
gen12_oa_hw_tail_read(struct i915_perf_stream * stream)435 static u32 gen12_oa_hw_tail_read(struct i915_perf_stream *stream)
436 {
437 	struct intel_uncore *uncore = stream->uncore;
438 
439 	return intel_uncore_read(uncore, __oa_regs(stream)->oa_tail_ptr) &
440 	       GEN12_OAG_OATAILPTR_MASK;
441 }
442 
gen8_oa_hw_tail_read(struct i915_perf_stream * stream)443 static u32 gen8_oa_hw_tail_read(struct i915_perf_stream *stream)
444 {
445 	struct intel_uncore *uncore = stream->uncore;
446 
447 	return intel_uncore_read(uncore, GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
448 }
449 
gen7_oa_hw_tail_read(struct i915_perf_stream * stream)450 static u32 gen7_oa_hw_tail_read(struct i915_perf_stream *stream)
451 {
452 	struct intel_uncore *uncore = stream->uncore;
453 	u32 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
454 
455 	return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
456 }
457 
458 #define oa_report_header_64bit(__s) \
459 	((__s)->oa_buffer.format->header == HDR_64_BIT)
460 
oa_report_id(struct i915_perf_stream * stream,void * report)461 static u64 oa_report_id(struct i915_perf_stream *stream, void *report)
462 {
463 	return oa_report_header_64bit(stream) ? *(u64 *)report : *(u32 *)report;
464 }
465 
oa_report_reason(struct i915_perf_stream * stream,void * report)466 static u64 oa_report_reason(struct i915_perf_stream *stream, void *report)
467 {
468 	return (oa_report_id(stream, report) >> OAREPORT_REASON_SHIFT) &
469 	       (GRAPHICS_VER(stream->perf->i915) == 12 ?
470 		OAREPORT_REASON_MASK_EXTENDED :
471 		OAREPORT_REASON_MASK);
472 }
473 
oa_report_id_clear(struct i915_perf_stream * stream,u32 * report)474 static void oa_report_id_clear(struct i915_perf_stream *stream, u32 *report)
475 {
476 	if (oa_report_header_64bit(stream))
477 		*(u64 *)report = 0;
478 	else
479 		*report = 0;
480 }
481 
oa_report_ctx_invalid(struct i915_perf_stream * stream,void * report)482 static bool oa_report_ctx_invalid(struct i915_perf_stream *stream, void *report)
483 {
484 	return !(oa_report_id(stream, report) &
485 	       stream->perf->gen8_valid_ctx_bit);
486 }
487 
oa_timestamp(struct i915_perf_stream * stream,void * report)488 static u64 oa_timestamp(struct i915_perf_stream *stream, void *report)
489 {
490 	return oa_report_header_64bit(stream) ?
491 		*((u64 *)report + 1) :
492 		*((u32 *)report + 1);
493 }
494 
oa_timestamp_clear(struct i915_perf_stream * stream,u32 * report)495 static void oa_timestamp_clear(struct i915_perf_stream *stream, u32 *report)
496 {
497 	if (oa_report_header_64bit(stream))
498 		*(u64 *)&report[2] = 0;
499 	else
500 		report[1] = 0;
501 }
502 
oa_context_id(struct i915_perf_stream * stream,u32 * report)503 static u32 oa_context_id(struct i915_perf_stream *stream, u32 *report)
504 {
505 	u32 ctx_id = oa_report_header_64bit(stream) ? report[4] : report[2];
506 
507 	return ctx_id & stream->specific_ctx_id_mask;
508 }
509 
oa_context_id_squash(struct i915_perf_stream * stream,u32 * report)510 static void oa_context_id_squash(struct i915_perf_stream *stream, u32 *report)
511 {
512 	if (oa_report_header_64bit(stream))
513 		report[4] = INVALID_CTX_ID;
514 	else
515 		report[2] = INVALID_CTX_ID;
516 }
517 
518 /**
519  * oa_buffer_check_unlocked - check for data and update tail ptr state
520  * @stream: i915 stream instance
521  *
522  * This is either called via fops (for blocking reads in user ctx) or the poll
523  * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
524  * if there is data available for userspace to read.
525  *
526  * This function is central to providing a workaround for the OA unit tail
527  * pointer having a race with respect to what data is visible to the CPU.
528  * It is responsible for reading tail pointers from the hardware and giving
529  * the pointers time to 'age' before they are made available for reading.
530  * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
531  *
532  * Besides returning true when there is data available to read() this function
533  * also updates the tail in the oa_buffer object.
534  *
535  * Note: It's safe to read OA config state here unlocked, assuming that this is
536  * only called while the stream is enabled, while the global OA configuration
537  * can't be modified.
538  *
539  * Returns: %true if the OA buffer contains data, else %false
540  */
oa_buffer_check_unlocked(struct i915_perf_stream * stream)541 static bool oa_buffer_check_unlocked(struct i915_perf_stream *stream)
542 {
543 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
544 	int report_size = stream->oa_buffer.format->size;
545 	u32 head, tail, read_tail;
546 	unsigned long flags;
547 	bool pollin;
548 	u32 hw_tail;
549 	u32 partial_report_size;
550 
551 	/* We have to consider the (unlikely) possibility that read() errors
552 	 * could result in an OA buffer reset which might reset the head and
553 	 * tail state.
554 	 */
555 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
556 
557 	hw_tail = stream->perf->ops.oa_hw_tail_read(stream);
558 
559 	/* The tail pointer increases in 64 byte increments, not in report_size
560 	 * steps. Also the report size may not be a power of 2. Compute
561 	 * potentially partially landed report in the OA buffer
562 	 */
563 	partial_report_size = OA_TAKEN(hw_tail, stream->oa_buffer.tail);
564 	partial_report_size %= report_size;
565 
566 	/* Subtract partial amount off the tail */
567 	hw_tail = OA_TAKEN(hw_tail, partial_report_size);
568 
569 	/* NB: The head we observe here might effectively be a little
570 	 * out of date. If a read() is in progress, the head could be
571 	 * anywhere between this head and stream->oa_buffer.tail.
572 	 */
573 	head = stream->oa_buffer.head - gtt_offset;
574 	read_tail = stream->oa_buffer.tail - gtt_offset;
575 
576 	tail = hw_tail;
577 
578 	/* Walk the stream backward until we find a report with report
579 	 * id and timestmap not at 0. Since the circular buffer pointers
580 	 * progress by increments of 64 bytes and that reports can be up
581 	 * to 256 bytes long, we can't tell whether a report has fully
582 	 * landed in memory before the report id and timestamp of the
583 	 * following report have effectively landed.
584 	 *
585 	 * This is assuming that the writes of the OA unit land in
586 	 * memory in the order they were written to.
587 	 * If not : (╯°□°)╯︵ ┻━┻
588 	 */
589 	while (OA_TAKEN(tail, read_tail) >= report_size) {
590 		void *report = stream->oa_buffer.vaddr + tail;
591 
592 		if (oa_report_id(stream, report) ||
593 		    oa_timestamp(stream, report))
594 			break;
595 
596 		tail = (tail - report_size) & (OA_BUFFER_SIZE - 1);
597 	}
598 
599 	if (OA_TAKEN(hw_tail, tail) > report_size &&
600 	    __ratelimit(&stream->perf->tail_pointer_race))
601 		drm_notice(&stream->uncore->i915->drm,
602 			   "unlanded report(s) head=0x%x tail=0x%x hw_tail=0x%x\n",
603 		 head, tail, hw_tail);
604 
605 	stream->oa_buffer.tail = gtt_offset + tail;
606 
607 	pollin = OA_TAKEN(stream->oa_buffer.tail,
608 			  stream->oa_buffer.head) >= report_size;
609 
610 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
611 
612 	return pollin;
613 }
614 
615 /**
616  * append_oa_status - Appends a status record to a userspace read() buffer.
617  * @stream: An i915-perf stream opened for OA metrics
618  * @buf: destination buffer given by userspace
619  * @count: the number of bytes userspace wants to read
620  * @offset: (inout): the current position for writing into @buf
621  * @type: The kind of status to report to userspace
622  *
623  * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
624  * into the userspace read() buffer.
625  *
626  * The @buf @offset will only be updated on success.
627  *
628  * Returns: 0 on success, negative error code on failure.
629  */
append_oa_status(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset,enum drm_i915_perf_record_type type)630 static int append_oa_status(struct i915_perf_stream *stream,
631 			    char __user *buf,
632 			    size_t count,
633 			    size_t *offset,
634 			    enum drm_i915_perf_record_type type)
635 {
636 	struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
637 
638 	if ((count - *offset) < header.size)
639 		return -ENOSPC;
640 
641 	if (copy_to_user(buf + *offset, &header, sizeof(header)))
642 		return -EFAULT;
643 
644 	(*offset) += header.size;
645 
646 	return 0;
647 }
648 
649 /**
650  * append_oa_sample - Copies single OA report into userspace read() buffer.
651  * @stream: An i915-perf stream opened for OA metrics
652  * @buf: destination buffer given by userspace
653  * @count: the number of bytes userspace wants to read
654  * @offset: (inout): the current position for writing into @buf
655  * @report: A single OA report to (optionally) include as part of the sample
656  *
657  * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
658  * properties when opening a stream, tracked as `stream->sample_flags`. This
659  * function copies the requested components of a single sample to the given
660  * read() @buf.
661  *
662  * The @buf @offset will only be updated on success.
663  *
664  * Returns: 0 on success, negative error code on failure.
665  */
append_oa_sample(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset,const u8 * report)666 static int append_oa_sample(struct i915_perf_stream *stream,
667 			    char __user *buf,
668 			    size_t count,
669 			    size_t *offset,
670 			    const u8 *report)
671 {
672 	int report_size = stream->oa_buffer.format->size;
673 	struct drm_i915_perf_record_header header;
674 	int report_size_partial;
675 	u8 *oa_buf_end;
676 
677 	header.type = DRM_I915_PERF_RECORD_SAMPLE;
678 	header.pad = 0;
679 	header.size = stream->sample_size;
680 
681 	if ((count - *offset) < header.size)
682 		return -ENOSPC;
683 
684 	buf += *offset;
685 	if (copy_to_user(buf, &header, sizeof(header)))
686 		return -EFAULT;
687 	buf += sizeof(header);
688 
689 	oa_buf_end = stream->oa_buffer.vaddr + OA_BUFFER_SIZE;
690 	report_size_partial = oa_buf_end - report;
691 
692 	if (report_size_partial < report_size) {
693 		if (copy_to_user(buf, report, report_size_partial))
694 			return -EFAULT;
695 		buf += report_size_partial;
696 
697 		if (copy_to_user(buf, stream->oa_buffer.vaddr,
698 				 report_size - report_size_partial))
699 			return -EFAULT;
700 	} else if (copy_to_user(buf, report, report_size)) {
701 		return -EFAULT;
702 	}
703 
704 	(*offset) += header.size;
705 
706 	return 0;
707 }
708 
709 /**
710  * gen8_append_oa_reports - Copies all buffered OA reports into
711  *			    userspace read() buffer.
712  * @stream: An i915-perf stream opened for OA metrics
713  * @buf: destination buffer given by userspace
714  * @count: the number of bytes userspace wants to read
715  * @offset: (inout): the current position for writing into @buf
716  *
717  * Notably any error condition resulting in a short read (-%ENOSPC or
718  * -%EFAULT) will be returned even though one or more records may
719  * have been successfully copied. In this case it's up to the caller
720  * to decide if the error should be squashed before returning to
721  * userspace.
722  *
723  * Note: reports are consumed from the head, and appended to the
724  * tail, so the tail chases the head?... If you think that's mad
725  * and back-to-front you're not alone, but this follows the
726  * Gen PRM naming convention.
727  *
728  * Returns: 0 on success, negative error code on failure.
729  */
gen8_append_oa_reports(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset)730 static int gen8_append_oa_reports(struct i915_perf_stream *stream,
731 				  char __user *buf,
732 				  size_t count,
733 				  size_t *offset)
734 {
735 	struct intel_uncore *uncore = stream->uncore;
736 	int report_size = stream->oa_buffer.format->size;
737 	u8 *oa_buf_base = stream->oa_buffer.vaddr;
738 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
739 	u32 mask = (OA_BUFFER_SIZE - 1);
740 	size_t start_offset = *offset;
741 	unsigned long flags;
742 	u32 head, tail;
743 	int ret = 0;
744 
745 	if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
746 		return -EIO;
747 
748 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
749 
750 	head = stream->oa_buffer.head;
751 	tail = stream->oa_buffer.tail;
752 
753 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
754 
755 	/*
756 	 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
757 	 * while indexing relative to oa_buf_base.
758 	 */
759 	head -= gtt_offset;
760 	tail -= gtt_offset;
761 
762 	/*
763 	 * An out of bounds or misaligned head or tail pointer implies a driver
764 	 * bug since we validate + align the tail pointers we read from the
765 	 * hardware and we are in full control of the head pointer which should
766 	 * only be incremented by multiples of the report size.
767 	 */
768 	if (drm_WARN_ONCE(&uncore->i915->drm,
769 			  head > OA_BUFFER_SIZE ||
770 			  tail > OA_BUFFER_SIZE,
771 			  "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
772 			  head, tail))
773 		return -EIO;
774 
775 
776 	for (/* none */;
777 	     OA_TAKEN(tail, head);
778 	     head = (head + report_size) & mask) {
779 		u8 *report = oa_buf_base + head;
780 		u32 *report32 = (void *)report;
781 		u32 ctx_id;
782 		u64 reason;
783 
784 		/*
785 		 * The reason field includes flags identifying what
786 		 * triggered this specific report (mostly timer
787 		 * triggered or e.g. due to a context switch).
788 		 */
789 		reason = oa_report_reason(stream, report);
790 		ctx_id = oa_context_id(stream, report32);
791 
792 		/*
793 		 * Squash whatever is in the CTX_ID field if it's marked as
794 		 * invalid to be sure we avoid false-positive, single-context
795 		 * filtering below...
796 		 *
797 		 * Note: that we don't clear the valid_ctx_bit so userspace can
798 		 * understand that the ID has been squashed by the kernel.
799 		 *
800 		 * Update:
801 		 *
802 		 * On XEHP platforms the behavior of context id valid bit has
803 		 * changed compared to prior platforms. To describe this, we
804 		 * define a few terms:
805 		 *
806 		 * context-switch-report: This is a report with the reason type
807 		 * being context-switch. It is generated when a context switches
808 		 * out.
809 		 *
810 		 * context-valid-bit: A bit that is set in the report ID field
811 		 * to indicate that a valid context has been loaded.
812 		 *
813 		 * gpu-idle: A condition characterized by a
814 		 * context-switch-report with context-valid-bit set to 0.
815 		 *
816 		 * On prior platforms, context-id-valid bit is set to 0 only
817 		 * when GPU goes idle. In all other reports, it is set to 1.
818 		 *
819 		 * On XEHP platforms, context-valid-bit is set to 1 in a context
820 		 * switch report if a new context switched in. For all other
821 		 * reports it is set to 0.
822 		 *
823 		 * This change in behavior causes an issue with MMIO triggered
824 		 * reports. MMIO triggered reports have the markers in the
825 		 * context ID field and the context-valid-bit is 0. The logic
826 		 * below to squash the context ID would render the report
827 		 * useless since the user will not be able to find it in the OA
828 		 * buffer. Since MMIO triggered reports exist only on XEHP,
829 		 * we should avoid squashing these for XEHP platforms.
830 		 */
831 
832 		if (oa_report_ctx_invalid(stream, report) &&
833 		    GRAPHICS_VER_FULL(stream->engine->i915) < IP_VER(12, 50)) {
834 			ctx_id = INVALID_CTX_ID;
835 			oa_context_id_squash(stream, report32);
836 		}
837 
838 		/*
839 		 * NB: For Gen 8 the OA unit no longer supports clock gating
840 		 * off for a specific context and the kernel can't securely
841 		 * stop the counters from updating as system-wide / global
842 		 * values.
843 		 *
844 		 * Automatic reports now include a context ID so reports can be
845 		 * filtered on the cpu but it's not worth trying to
846 		 * automatically subtract/hide counter progress for other
847 		 * contexts while filtering since we can't stop userspace
848 		 * issuing MI_REPORT_PERF_COUNT commands which would still
849 		 * provide a side-band view of the real values.
850 		 *
851 		 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
852 		 * to normalize counters for a single filtered context then it
853 		 * needs be forwarded bookend context-switch reports so that it
854 		 * can track switches in between MI_REPORT_PERF_COUNT commands
855 		 * and can itself subtract/ignore the progress of counters
856 		 * associated with other contexts. Note that the hardware
857 		 * automatically triggers reports when switching to a new
858 		 * context which are tagged with the ID of the newly active
859 		 * context. To avoid the complexity (and likely fragility) of
860 		 * reading ahead while parsing reports to try and minimize
861 		 * forwarding redundant context switch reports (i.e. between
862 		 * other, unrelated contexts) we simply elect to forward them
863 		 * all.
864 		 *
865 		 * We don't rely solely on the reason field to identify context
866 		 * switches since it's not-uncommon for periodic samples to
867 		 * identify a switch before any 'context switch' report.
868 		 */
869 		if (!stream->ctx ||
870 		    stream->specific_ctx_id == ctx_id ||
871 		    stream->oa_buffer.last_ctx_id == stream->specific_ctx_id ||
872 		    reason & OAREPORT_REASON_CTX_SWITCH) {
873 
874 			/*
875 			 * While filtering for a single context we avoid
876 			 * leaking the IDs of other contexts.
877 			 */
878 			if (stream->ctx &&
879 			    stream->specific_ctx_id != ctx_id) {
880 				oa_context_id_squash(stream, report32);
881 			}
882 
883 			ret = append_oa_sample(stream, buf, count, offset,
884 					       report);
885 			if (ret)
886 				break;
887 
888 			stream->oa_buffer.last_ctx_id = ctx_id;
889 		}
890 
891 		if (is_power_of_2(report_size)) {
892 			/*
893 			 * Clear out the report id and timestamp as a means
894 			 * to detect unlanded reports.
895 			 */
896 			oa_report_id_clear(stream, report32);
897 			oa_timestamp_clear(stream, report32);
898 		} else {
899 			u8 *oa_buf_end = stream->oa_buffer.vaddr +
900 					 OA_BUFFER_SIZE;
901 			u32 part = oa_buf_end - (u8 *)report32;
902 
903 			/* Zero out the entire report */
904 			if (report_size <= part) {
905 				memset(report32, 0, report_size);
906 			} else {
907 				memset(report32, 0, part);
908 				memset(oa_buf_base, 0, report_size - part);
909 			}
910 		}
911 	}
912 
913 	if (start_offset != *offset) {
914 		i915_reg_t oaheadptr;
915 
916 		oaheadptr = GRAPHICS_VER(stream->perf->i915) == 12 ?
917 			    __oa_regs(stream)->oa_head_ptr :
918 			    GEN8_OAHEADPTR;
919 
920 		spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
921 
922 		/*
923 		 * We removed the gtt_offset for the copy loop above, indexing
924 		 * relative to oa_buf_base so put back here...
925 		 */
926 		head += gtt_offset;
927 		intel_uncore_write(uncore, oaheadptr,
928 				   head & GEN12_OAG_OAHEADPTR_MASK);
929 		stream->oa_buffer.head = head;
930 
931 		spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
932 	}
933 
934 	return ret;
935 }
936 
937 /**
938  * gen8_oa_read - copy status records then buffered OA reports
939  * @stream: An i915-perf stream opened for OA metrics
940  * @buf: destination buffer given by userspace
941  * @count: the number of bytes userspace wants to read
942  * @offset: (inout): the current position for writing into @buf
943  *
944  * Checks OA unit status registers and if necessary appends corresponding
945  * status records for userspace (such as for a buffer full condition) and then
946  * initiate appending any buffered OA reports.
947  *
948  * Updates @offset according to the number of bytes successfully copied into
949  * the userspace buffer.
950  *
951  * NB: some data may be successfully copied to the userspace buffer
952  * even if an error is returned, and this is reflected in the
953  * updated @offset.
954  *
955  * Returns: zero on success or a negative error code
956  */
gen8_oa_read(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset)957 static int gen8_oa_read(struct i915_perf_stream *stream,
958 			char __user *buf,
959 			size_t count,
960 			size_t *offset)
961 {
962 	struct intel_uncore *uncore = stream->uncore;
963 	u32 oastatus;
964 	i915_reg_t oastatus_reg;
965 	int ret;
966 
967 	if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
968 		return -EIO;
969 
970 	oastatus_reg = GRAPHICS_VER(stream->perf->i915) == 12 ?
971 		       __oa_regs(stream)->oa_status :
972 		       GEN8_OASTATUS;
973 
974 	oastatus = intel_uncore_read(uncore, oastatus_reg);
975 
976 	/*
977 	 * We treat OABUFFER_OVERFLOW as a significant error:
978 	 *
979 	 * Although theoretically we could handle this more gracefully
980 	 * sometimes, some Gens don't correctly suppress certain
981 	 * automatically triggered reports in this condition and so we
982 	 * have to assume that old reports are now being trampled
983 	 * over.
984 	 *
985 	 * Considering how we don't currently give userspace control
986 	 * over the OA buffer size and always configure a large 16MB
987 	 * buffer, then a buffer overflow does anyway likely indicate
988 	 * that something has gone quite badly wrong.
989 	 */
990 	if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
991 		ret = append_oa_status(stream, buf, count, offset,
992 				       DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
993 		if (ret)
994 			return ret;
995 
996 		drm_dbg(&stream->perf->i915->drm,
997 			"OA buffer overflow (exponent = %d): force restart\n",
998 			stream->period_exponent);
999 
1000 		stream->perf->ops.oa_disable(stream);
1001 		stream->perf->ops.oa_enable(stream);
1002 
1003 		/*
1004 		 * Note: .oa_enable() is expected to re-init the oabuffer and
1005 		 * reset GEN8_OASTATUS for us
1006 		 */
1007 		oastatus = intel_uncore_read(uncore, oastatus_reg);
1008 	}
1009 
1010 	if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
1011 		ret = append_oa_status(stream, buf, count, offset,
1012 				       DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1013 		if (ret)
1014 			return ret;
1015 
1016 		intel_uncore_rmw(uncore, oastatus_reg,
1017 				 GEN8_OASTATUS_COUNTER_OVERFLOW |
1018 				 GEN8_OASTATUS_REPORT_LOST,
1019 				 IS_GRAPHICS_VER(uncore->i915, 8, 11) ?
1020 				 (GEN8_OASTATUS_HEAD_POINTER_WRAP |
1021 				  GEN8_OASTATUS_TAIL_POINTER_WRAP) : 0);
1022 	}
1023 
1024 	return gen8_append_oa_reports(stream, buf, count, offset);
1025 }
1026 
1027 /**
1028  * gen7_append_oa_reports - Copies all buffered OA reports into
1029  *			    userspace read() buffer.
1030  * @stream: An i915-perf stream opened for OA metrics
1031  * @buf: destination buffer given by userspace
1032  * @count: the number of bytes userspace wants to read
1033  * @offset: (inout): the current position for writing into @buf
1034  *
1035  * Notably any error condition resulting in a short read (-%ENOSPC or
1036  * -%EFAULT) will be returned even though one or more records may
1037  * have been successfully copied. In this case it's up to the caller
1038  * to decide if the error should be squashed before returning to
1039  * userspace.
1040  *
1041  * Note: reports are consumed from the head, and appended to the
1042  * tail, so the tail chases the head?... If you think that's mad
1043  * and back-to-front you're not alone, but this follows the
1044  * Gen PRM naming convention.
1045  *
1046  * Returns: 0 on success, negative error code on failure.
1047  */
gen7_append_oa_reports(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset)1048 static int gen7_append_oa_reports(struct i915_perf_stream *stream,
1049 				  char __user *buf,
1050 				  size_t count,
1051 				  size_t *offset)
1052 {
1053 	struct intel_uncore *uncore = stream->uncore;
1054 	int report_size = stream->oa_buffer.format->size;
1055 	u8 *oa_buf_base = stream->oa_buffer.vaddr;
1056 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1057 	u32 mask = (OA_BUFFER_SIZE - 1);
1058 	size_t start_offset = *offset;
1059 	unsigned long flags;
1060 	u32 head, tail;
1061 	int ret = 0;
1062 
1063 	if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
1064 		return -EIO;
1065 
1066 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1067 
1068 	head = stream->oa_buffer.head;
1069 	tail = stream->oa_buffer.tail;
1070 
1071 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1072 
1073 	/* NB: oa_buffer.head/tail include the gtt_offset which we don't want
1074 	 * while indexing relative to oa_buf_base.
1075 	 */
1076 	head -= gtt_offset;
1077 	tail -= gtt_offset;
1078 
1079 	/* An out of bounds or misaligned head or tail pointer implies a driver
1080 	 * bug since we validate + align the tail pointers we read from the
1081 	 * hardware and we are in full control of the head pointer which should
1082 	 * only be incremented by multiples of the report size (notably also
1083 	 * all a power of two).
1084 	 */
1085 	if (drm_WARN_ONCE(&uncore->i915->drm,
1086 			  head > OA_BUFFER_SIZE || head % report_size ||
1087 			  tail > OA_BUFFER_SIZE || tail % report_size,
1088 			  "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
1089 			  head, tail))
1090 		return -EIO;
1091 
1092 
1093 	for (/* none */;
1094 	     OA_TAKEN(tail, head);
1095 	     head = (head + report_size) & mask) {
1096 		u8 *report = oa_buf_base + head;
1097 		u32 *report32 = (void *)report;
1098 
1099 		/* All the report sizes factor neatly into the buffer
1100 		 * size so we never expect to see a report split
1101 		 * between the beginning and end of the buffer.
1102 		 *
1103 		 * Given the initial alignment check a misalignment
1104 		 * here would imply a driver bug that would result
1105 		 * in an overrun.
1106 		 */
1107 		if (drm_WARN_ON(&uncore->i915->drm,
1108 				(OA_BUFFER_SIZE - head) < report_size)) {
1109 			drm_err(&uncore->i915->drm,
1110 				"Spurious OA head ptr: non-integral report offset\n");
1111 			break;
1112 		}
1113 
1114 		/* The report-ID field for periodic samples includes
1115 		 * some undocumented flags related to what triggered
1116 		 * the report and is never expected to be zero so we
1117 		 * can check that the report isn't invalid before
1118 		 * copying it to userspace...
1119 		 */
1120 		if (report32[0] == 0) {
1121 			if (__ratelimit(&stream->perf->spurious_report_rs))
1122 				drm_notice(&uncore->i915->drm,
1123 					   "Skipping spurious, invalid OA report\n");
1124 			continue;
1125 		}
1126 
1127 		ret = append_oa_sample(stream, buf, count, offset, report);
1128 		if (ret)
1129 			break;
1130 
1131 		/* Clear out the first 2 dwords as a mean to detect unlanded
1132 		 * reports.
1133 		 */
1134 		report32[0] = 0;
1135 		report32[1] = 0;
1136 	}
1137 
1138 	if (start_offset != *offset) {
1139 		spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1140 
1141 		/* We removed the gtt_offset for the copy loop above, indexing
1142 		 * relative to oa_buf_base so put back here...
1143 		 */
1144 		head += gtt_offset;
1145 
1146 		intel_uncore_write(uncore, GEN7_OASTATUS2,
1147 				   (head & GEN7_OASTATUS2_HEAD_MASK) |
1148 				   GEN7_OASTATUS2_MEM_SELECT_GGTT);
1149 		stream->oa_buffer.head = head;
1150 
1151 		spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1152 	}
1153 
1154 	return ret;
1155 }
1156 
1157 /**
1158  * gen7_oa_read - copy status records then buffered OA reports
1159  * @stream: An i915-perf stream opened for OA metrics
1160  * @buf: destination buffer given by userspace
1161  * @count: the number of bytes userspace wants to read
1162  * @offset: (inout): the current position for writing into @buf
1163  *
1164  * Checks Gen 7 specific OA unit status registers and if necessary appends
1165  * corresponding status records for userspace (such as for a buffer full
1166  * condition) and then initiate appending any buffered OA reports.
1167  *
1168  * Updates @offset according to the number of bytes successfully copied into
1169  * the userspace buffer.
1170  *
1171  * Returns: zero on success or a negative error code
1172  */
gen7_oa_read(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset)1173 static int gen7_oa_read(struct i915_perf_stream *stream,
1174 			char __user *buf,
1175 			size_t count,
1176 			size_t *offset)
1177 {
1178 	struct intel_uncore *uncore = stream->uncore;
1179 	u32 oastatus1;
1180 	int ret;
1181 
1182 	if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
1183 		return -EIO;
1184 
1185 	oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1186 
1187 	/* XXX: On Haswell we don't have a safe way to clear oastatus1
1188 	 * bits while the OA unit is enabled (while the tail pointer
1189 	 * may be updated asynchronously) so we ignore status bits
1190 	 * that have already been reported to userspace.
1191 	 */
1192 	oastatus1 &= ~stream->perf->gen7_latched_oastatus1;
1193 
1194 	/* We treat OABUFFER_OVERFLOW as a significant error:
1195 	 *
1196 	 * - The status can be interpreted to mean that the buffer is
1197 	 *   currently full (with a higher precedence than OA_TAKEN()
1198 	 *   which will start to report a near-empty buffer after an
1199 	 *   overflow) but it's awkward that we can't clear the status
1200 	 *   on Haswell, so without a reset we won't be able to catch
1201 	 *   the state again.
1202 	 *
1203 	 * - Since it also implies the HW has started overwriting old
1204 	 *   reports it may also affect our sanity checks for invalid
1205 	 *   reports when copying to userspace that assume new reports
1206 	 *   are being written to cleared memory.
1207 	 *
1208 	 * - In the future we may want to introduce a flight recorder
1209 	 *   mode where the driver will automatically maintain a safe
1210 	 *   guard band between head/tail, avoiding this overflow
1211 	 *   condition, but we avoid the added driver complexity for
1212 	 *   now.
1213 	 */
1214 	if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1215 		ret = append_oa_status(stream, buf, count, offset,
1216 				       DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1217 		if (ret)
1218 			return ret;
1219 
1220 		drm_dbg(&stream->perf->i915->drm,
1221 			"OA buffer overflow (exponent = %d): force restart\n",
1222 			stream->period_exponent);
1223 
1224 		stream->perf->ops.oa_disable(stream);
1225 		stream->perf->ops.oa_enable(stream);
1226 
1227 		oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1228 	}
1229 
1230 	if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1231 		ret = append_oa_status(stream, buf, count, offset,
1232 				       DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1233 		if (ret)
1234 			return ret;
1235 		stream->perf->gen7_latched_oastatus1 |=
1236 			GEN7_OASTATUS1_REPORT_LOST;
1237 	}
1238 
1239 	return gen7_append_oa_reports(stream, buf, count, offset);
1240 }
1241 
1242 /**
1243  * i915_oa_wait_unlocked - handles blocking IO until OA data available
1244  * @stream: An i915-perf stream opened for OA metrics
1245  *
1246  * Called when userspace tries to read() from a blocking stream FD opened
1247  * for OA metrics. It waits until the hrtimer callback finds a non-empty
1248  * OA buffer and wakes us.
1249  *
1250  * Note: it's acceptable to have this return with some false positives
1251  * since any subsequent read handling will return -EAGAIN if there isn't
1252  * really data ready for userspace yet.
1253  *
1254  * Returns: zero on success or a negative error code
1255  */
i915_oa_wait_unlocked(struct i915_perf_stream * stream)1256 static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1257 {
1258 	/* We would wait indefinitely if periodic sampling is not enabled */
1259 	if (!stream->periodic)
1260 		return -EIO;
1261 
1262 	return wait_event_interruptible(stream->poll_wq,
1263 					oa_buffer_check_unlocked(stream));
1264 }
1265 
1266 /**
1267  * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1268  * @stream: An i915-perf stream opened for OA metrics
1269  * @file: An i915 perf stream file
1270  * @wait: poll() state table
1271  *
1272  * For handling userspace polling on an i915 perf stream opened for OA metrics,
1273  * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1274  * when it sees data ready to read in the circular OA buffer.
1275  */
i915_oa_poll_wait(struct i915_perf_stream * stream,struct file * file,poll_table * wait)1276 static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1277 			      struct file *file,
1278 			      poll_table *wait)
1279 {
1280 	poll_wait(file, &stream->poll_wq, wait);
1281 }
1282 
1283 /**
1284  * i915_oa_read - just calls through to &i915_oa_ops->read
1285  * @stream: An i915-perf stream opened for OA metrics
1286  * @buf: destination buffer given by userspace
1287  * @count: the number of bytes userspace wants to read
1288  * @offset: (inout): the current position for writing into @buf
1289  *
1290  * Updates @offset according to the number of bytes successfully copied into
1291  * the userspace buffer.
1292  *
1293  * Returns: zero on success or a negative error code
1294  */
i915_oa_read(struct i915_perf_stream * stream,char __user * buf,size_t count,size_t * offset)1295 static int i915_oa_read(struct i915_perf_stream *stream,
1296 			char __user *buf,
1297 			size_t count,
1298 			size_t *offset)
1299 {
1300 	return stream->perf->ops.read(stream, buf, count, offset);
1301 }
1302 
oa_pin_context(struct i915_perf_stream * stream)1303 static struct intel_context *oa_pin_context(struct i915_perf_stream *stream)
1304 {
1305 	struct i915_gem_engines_iter it;
1306 	struct i915_gem_context *ctx = stream->ctx;
1307 	struct intel_context *ce;
1308 	struct i915_gem_ww_ctx ww;
1309 	int err = -ENODEV;
1310 
1311 	for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
1312 		if (ce->engine != stream->engine) /* first match! */
1313 			continue;
1314 
1315 		err = 0;
1316 		break;
1317 	}
1318 	i915_gem_context_unlock_engines(ctx);
1319 
1320 	if (err)
1321 		return ERR_PTR(err);
1322 
1323 	i915_gem_ww_ctx_init(&ww, true);
1324 retry:
1325 	/*
1326 	 * As the ID is the gtt offset of the context's vma we
1327 	 * pin the vma to ensure the ID remains fixed.
1328 	 */
1329 	err = intel_context_pin_ww(ce, &ww);
1330 	if (err == -EDEADLK) {
1331 		err = i915_gem_ww_ctx_backoff(&ww);
1332 		if (!err)
1333 			goto retry;
1334 	}
1335 	i915_gem_ww_ctx_fini(&ww);
1336 
1337 	if (err)
1338 		return ERR_PTR(err);
1339 
1340 	stream->pinned_ctx = ce;
1341 	return stream->pinned_ctx;
1342 }
1343 
1344 static int
__store_reg_to_mem(struct i915_request * rq,i915_reg_t reg,u32 ggtt_offset)1345 __store_reg_to_mem(struct i915_request *rq, i915_reg_t reg, u32 ggtt_offset)
1346 {
1347 	u32 *cs, cmd;
1348 
1349 	cmd = MI_STORE_REGISTER_MEM | MI_SRM_LRM_GLOBAL_GTT;
1350 	if (GRAPHICS_VER(rq->i915) >= 8)
1351 		cmd++;
1352 
1353 	cs = intel_ring_begin(rq, 4);
1354 	if (IS_ERR(cs))
1355 		return PTR_ERR(cs);
1356 
1357 	*cs++ = cmd;
1358 	*cs++ = i915_mmio_reg_offset(reg);
1359 	*cs++ = ggtt_offset;
1360 	*cs++ = 0;
1361 
1362 	intel_ring_advance(rq, cs);
1363 
1364 	return 0;
1365 }
1366 
1367 static int
__read_reg(struct intel_context * ce,i915_reg_t reg,u32 ggtt_offset)1368 __read_reg(struct intel_context *ce, i915_reg_t reg, u32 ggtt_offset)
1369 {
1370 	struct i915_request *rq;
1371 	int err;
1372 
1373 	rq = i915_request_create(ce);
1374 	if (IS_ERR(rq))
1375 		return PTR_ERR(rq);
1376 
1377 	i915_request_get(rq);
1378 
1379 	err = __store_reg_to_mem(rq, reg, ggtt_offset);
1380 
1381 	i915_request_add(rq);
1382 	if (!err && i915_request_wait(rq, 0, HZ / 2) < 0)
1383 		err = -ETIME;
1384 
1385 	i915_request_put(rq);
1386 
1387 	return err;
1388 }
1389 
1390 static int
gen12_guc_sw_ctx_id(struct intel_context * ce,u32 * ctx_id)1391 gen12_guc_sw_ctx_id(struct intel_context *ce, u32 *ctx_id)
1392 {
1393 	struct i915_vma *scratch;
1394 	u32 *val;
1395 	int err;
1396 
1397 	scratch = __vm_create_scratch_for_read_pinned(&ce->engine->gt->ggtt->vm, 4);
1398 	if (IS_ERR(scratch))
1399 		return PTR_ERR(scratch);
1400 
1401 	err = i915_vma_sync(scratch);
1402 	if (err)
1403 		goto err_scratch;
1404 
1405 	err = __read_reg(ce, RING_EXECLIST_STATUS_HI(ce->engine->mmio_base),
1406 			 i915_ggtt_offset(scratch));
1407 	if (err)
1408 		goto err_scratch;
1409 
1410 	val = i915_gem_object_pin_map_unlocked(scratch->obj, I915_MAP_WB);
1411 	if (IS_ERR(val)) {
1412 		err = PTR_ERR(val);
1413 		goto err_scratch;
1414 	}
1415 
1416 	*ctx_id = *val;
1417 	i915_gem_object_unpin_map(scratch->obj);
1418 
1419 err_scratch:
1420 	i915_vma_unpin_and_release(&scratch, 0);
1421 	return err;
1422 }
1423 
1424 /*
1425  * For execlist mode of submission, pick an unused context id
1426  * 0 - (NUM_CONTEXT_TAG -1) are used by other contexts
1427  * XXX_MAX_CONTEXT_HW_ID is used by idle context
1428  *
1429  * For GuC mode of submission read context id from the upper dword of the
1430  * EXECLIST_STATUS register. Note that we read this value only once and expect
1431  * that the value stays fixed for the entire OA use case. There are cases where
1432  * GuC KMD implementation may deregister a context to reuse it's context id, but
1433  * we prevent that from happening to the OA context by pinning it.
1434  */
gen12_get_render_context_id(struct i915_perf_stream * stream)1435 static int gen12_get_render_context_id(struct i915_perf_stream *stream)
1436 {
1437 	u32 ctx_id, mask;
1438 	int ret;
1439 
1440 	if (intel_engine_uses_guc(stream->engine)) {
1441 		ret = gen12_guc_sw_ctx_id(stream->pinned_ctx, &ctx_id);
1442 		if (ret)
1443 			return ret;
1444 
1445 		mask = ((1U << GEN12_GUC_SW_CTX_ID_WIDTH) - 1) <<
1446 			(GEN12_GUC_SW_CTX_ID_SHIFT - 32);
1447 	} else if (GRAPHICS_VER_FULL(stream->engine->i915) >= IP_VER(12, 50)) {
1448 		ctx_id = (XEHP_MAX_CONTEXT_HW_ID - 1) <<
1449 			(XEHP_SW_CTX_ID_SHIFT - 32);
1450 
1451 		mask = ((1U << XEHP_SW_CTX_ID_WIDTH) - 1) <<
1452 			(XEHP_SW_CTX_ID_SHIFT - 32);
1453 	} else {
1454 		ctx_id = (GEN12_MAX_CONTEXT_HW_ID - 1) <<
1455 			 (GEN11_SW_CTX_ID_SHIFT - 32);
1456 
1457 		mask = ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) <<
1458 			(GEN11_SW_CTX_ID_SHIFT - 32);
1459 	}
1460 	stream->specific_ctx_id = ctx_id & mask;
1461 	stream->specific_ctx_id_mask = mask;
1462 
1463 	return 0;
1464 }
1465 
oa_find_reg_in_lri(u32 * state,u32 reg,u32 * offset,u32 end)1466 static bool oa_find_reg_in_lri(u32 *state, u32 reg, u32 *offset, u32 end)
1467 {
1468 	u32 idx = *offset;
1469 	u32 len = min(MI_LRI_LEN(state[idx]) + idx, end);
1470 	bool found = false;
1471 
1472 	idx++;
1473 	for (; idx < len; idx += 2) {
1474 		if (state[idx] == reg) {
1475 			found = true;
1476 			break;
1477 		}
1478 	}
1479 
1480 	*offset = idx;
1481 	return found;
1482 }
1483 
oa_context_image_offset(struct intel_context * ce,u32 reg)1484 static u32 oa_context_image_offset(struct intel_context *ce, u32 reg)
1485 {
1486 	u32 offset, len = (ce->engine->context_size - PAGE_SIZE) / 4;
1487 	u32 *state = ce->lrc_reg_state;
1488 
1489 	if (drm_WARN_ON(&ce->engine->i915->drm, !state))
1490 		return U32_MAX;
1491 
1492 	for (offset = 0; offset < len; ) {
1493 		if (IS_MI_LRI_CMD(state[offset])) {
1494 			/*
1495 			 * We expect reg-value pairs in MI_LRI command, so
1496 			 * MI_LRI_LEN() should be even, if not, issue a warning.
1497 			 */
1498 			drm_WARN_ON(&ce->engine->i915->drm,
1499 				    MI_LRI_LEN(state[offset]) & 0x1);
1500 
1501 			if (oa_find_reg_in_lri(state, reg, &offset, len))
1502 				break;
1503 		} else {
1504 			offset++;
1505 		}
1506 	}
1507 
1508 	return offset < len ? offset : U32_MAX;
1509 }
1510 
set_oa_ctx_ctrl_offset(struct intel_context * ce)1511 static int set_oa_ctx_ctrl_offset(struct intel_context *ce)
1512 {
1513 	i915_reg_t reg = GEN12_OACTXCONTROL(ce->engine->mmio_base);
1514 	struct i915_perf *perf = &ce->engine->i915->perf;
1515 	u32 offset = perf->ctx_oactxctrl_offset;
1516 
1517 	/* Do this only once. Failure is stored as offset of U32_MAX */
1518 	if (offset)
1519 		goto exit;
1520 
1521 	offset = oa_context_image_offset(ce, i915_mmio_reg_offset(reg));
1522 	perf->ctx_oactxctrl_offset = offset;
1523 
1524 	drm_dbg(&ce->engine->i915->drm,
1525 		"%s oa ctx control at 0x%08x dword offset\n",
1526 		ce->engine->name, offset);
1527 
1528 exit:
1529 	return offset && offset != U32_MAX ? 0 : -ENODEV;
1530 }
1531 
engine_supports_mi_query(struct intel_engine_cs * engine)1532 static bool engine_supports_mi_query(struct intel_engine_cs *engine)
1533 {
1534 	return engine->class == RENDER_CLASS;
1535 }
1536 
1537 /**
1538  * oa_get_render_ctx_id - determine and hold ctx hw id
1539  * @stream: An i915-perf stream opened for OA metrics
1540  *
1541  * Determine the render context hw id, and ensure it remains fixed for the
1542  * lifetime of the stream. This ensures that we don't have to worry about
1543  * updating the context ID in OACONTROL on the fly.
1544  *
1545  * Returns: zero on success or a negative error code
1546  */
oa_get_render_ctx_id(struct i915_perf_stream * stream)1547 static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1548 {
1549 	struct intel_context *ce;
1550 	int ret = 0;
1551 
1552 	ce = oa_pin_context(stream);
1553 	if (IS_ERR(ce))
1554 		return PTR_ERR(ce);
1555 
1556 	if (engine_supports_mi_query(stream->engine) &&
1557 	    HAS_LOGICAL_RING_CONTEXTS(stream->perf->i915)) {
1558 		/*
1559 		 * We are enabling perf query here. If we don't find the context
1560 		 * offset here, just return an error.
1561 		 */
1562 		ret = set_oa_ctx_ctrl_offset(ce);
1563 		if (ret) {
1564 			intel_context_unpin(ce);
1565 			drm_err(&stream->perf->i915->drm,
1566 				"Enabling perf query failed for %s\n",
1567 				stream->engine->name);
1568 			return ret;
1569 		}
1570 	}
1571 
1572 	switch (GRAPHICS_VER(ce->engine->i915)) {
1573 	case 7: {
1574 		/*
1575 		 * On Haswell we don't do any post processing of the reports
1576 		 * and don't need to use the mask.
1577 		 */
1578 		stream->specific_ctx_id = i915_ggtt_offset(ce->state);
1579 		stream->specific_ctx_id_mask = 0;
1580 		break;
1581 	}
1582 
1583 	case 8:
1584 	case 9:
1585 		if (intel_engine_uses_guc(ce->engine)) {
1586 			/*
1587 			 * When using GuC, the context descriptor we write in
1588 			 * i915 is read by GuC and rewritten before it's
1589 			 * actually written into the hardware. The LRCA is
1590 			 * what is put into the context id field of the
1591 			 * context descriptor by GuC. Because it's aligned to
1592 			 * a page, the lower 12bits are always at 0 and
1593 			 * dropped by GuC. They won't be part of the context
1594 			 * ID in the OA reports, so squash those lower bits.
1595 			 */
1596 			stream->specific_ctx_id = ce->lrc.lrca >> 12;
1597 
1598 			/*
1599 			 * GuC uses the top bit to signal proxy submission, so
1600 			 * ignore that bit.
1601 			 */
1602 			stream->specific_ctx_id_mask =
1603 				(1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
1604 		} else {
1605 			stream->specific_ctx_id_mask =
1606 				(1U << GEN8_CTX_ID_WIDTH) - 1;
1607 			stream->specific_ctx_id = stream->specific_ctx_id_mask;
1608 		}
1609 		break;
1610 
1611 	case 11:
1612 	case 12:
1613 		ret = gen12_get_render_context_id(stream);
1614 		break;
1615 
1616 	default:
1617 		MISSING_CASE(GRAPHICS_VER(ce->engine->i915));
1618 	}
1619 
1620 	ce->tag = stream->specific_ctx_id;
1621 
1622 	drm_dbg(&stream->perf->i915->drm,
1623 		"filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
1624 		stream->specific_ctx_id,
1625 		stream->specific_ctx_id_mask);
1626 
1627 	return ret;
1628 }
1629 
1630 /**
1631  * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1632  * @stream: An i915-perf stream opened for OA metrics
1633  *
1634  * In case anything needed doing to ensure the context HW ID would remain valid
1635  * for the lifetime of the stream, then that can be undone here.
1636  */
oa_put_render_ctx_id(struct i915_perf_stream * stream)1637 static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1638 {
1639 	struct intel_context *ce;
1640 
1641 	ce = fetch_and_zero(&stream->pinned_ctx);
1642 	if (ce) {
1643 		ce->tag = 0; /* recomputed on next submission after parking */
1644 		intel_context_unpin(ce);
1645 	}
1646 
1647 	stream->specific_ctx_id = INVALID_CTX_ID;
1648 	stream->specific_ctx_id_mask = 0;
1649 }
1650 
1651 static void
free_oa_buffer(struct i915_perf_stream * stream)1652 free_oa_buffer(struct i915_perf_stream *stream)
1653 {
1654 	i915_vma_unpin_and_release(&stream->oa_buffer.vma,
1655 				   I915_VMA_RELEASE_MAP);
1656 
1657 	stream->oa_buffer.vaddr = NULL;
1658 }
1659 
1660 static void
free_oa_configs(struct i915_perf_stream * stream)1661 free_oa_configs(struct i915_perf_stream *stream)
1662 {
1663 	struct i915_oa_config_bo *oa_bo, *tmp;
1664 
1665 	i915_oa_config_put(stream->oa_config);
1666 	llist_for_each_entry_safe(oa_bo, tmp, stream->oa_config_bos.first, node)
1667 		free_oa_config_bo(oa_bo);
1668 }
1669 
1670 static void
free_noa_wait(struct i915_perf_stream * stream)1671 free_noa_wait(struct i915_perf_stream *stream)
1672 {
1673 	i915_vma_unpin_and_release(&stream->noa_wait, 0);
1674 }
1675 
engine_supports_oa(const struct intel_engine_cs * engine)1676 static bool engine_supports_oa(const struct intel_engine_cs *engine)
1677 {
1678 	return engine->oa_group;
1679 }
1680 
engine_supports_oa_format(struct intel_engine_cs * engine,int type)1681 static bool engine_supports_oa_format(struct intel_engine_cs *engine, int type)
1682 {
1683 	return engine->oa_group && engine->oa_group->type == type;
1684 }
1685 
i915_oa_stream_destroy(struct i915_perf_stream * stream)1686 static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1687 {
1688 	struct i915_perf *perf = stream->perf;
1689 	struct intel_gt *gt = stream->engine->gt;
1690 	struct i915_perf_group *g = stream->engine->oa_group;
1691 
1692 	if (WARN_ON(stream != g->exclusive_stream))
1693 		return;
1694 
1695 	/*
1696 	 * Unset exclusive_stream first, it will be checked while disabling
1697 	 * the metric set on gen8+.
1698 	 *
1699 	 * See i915_oa_init_reg_state() and lrc_configure_all_contexts()
1700 	 */
1701 	WRITE_ONCE(g->exclusive_stream, NULL);
1702 	perf->ops.disable_metric_set(stream);
1703 
1704 	free_oa_buffer(stream);
1705 
1706 	/*
1707 	 * Wa_16011777198:dg2: Unset the override of GUCRC mode to enable rc6.
1708 	 */
1709 	if (stream->override_gucrc)
1710 		drm_WARN_ON(&gt->i915->drm,
1711 			    intel_guc_slpc_unset_gucrc_mode(&gt->uc.guc.slpc));
1712 
1713 	intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
1714 	intel_engine_pm_put(stream->engine);
1715 
1716 	if (stream->ctx)
1717 		oa_put_render_ctx_id(stream);
1718 
1719 	free_oa_configs(stream);
1720 	free_noa_wait(stream);
1721 
1722 	if (perf->spurious_report_rs.missed) {
1723 		drm_notice(&gt->i915->drm,
1724 			   "%d spurious OA report notices suppressed due to ratelimiting\n",
1725 			   perf->spurious_report_rs.missed);
1726 	}
1727 }
1728 
gen7_init_oa_buffer(struct i915_perf_stream * stream)1729 static void gen7_init_oa_buffer(struct i915_perf_stream *stream)
1730 {
1731 	struct intel_uncore *uncore = stream->uncore;
1732 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1733 	unsigned long flags;
1734 
1735 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1736 
1737 	/* Pre-DevBDW: OABUFFER must be set with counters off,
1738 	 * before OASTATUS1, but after OASTATUS2
1739 	 */
1740 	intel_uncore_write(uncore, GEN7_OASTATUS2, /* head */
1741 			   gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT);
1742 	stream->oa_buffer.head = gtt_offset;
1743 
1744 	intel_uncore_write(uncore, GEN7_OABUFFER, gtt_offset);
1745 
1746 	intel_uncore_write(uncore, GEN7_OASTATUS1, /* tail */
1747 			   gtt_offset | OABUFFER_SIZE_16M);
1748 
1749 	/* Mark that we need updated tail pointers to read from... */
1750 	stream->oa_buffer.tail = gtt_offset;
1751 
1752 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1753 
1754 	/* On Haswell we have to track which OASTATUS1 flags we've
1755 	 * already seen since they can't be cleared while periodic
1756 	 * sampling is enabled.
1757 	 */
1758 	stream->perf->gen7_latched_oastatus1 = 0;
1759 
1760 	/* NB: although the OA buffer will initially be allocated
1761 	 * zeroed via shmfs (and so this memset is redundant when
1762 	 * first allocating), we may re-init the OA buffer, either
1763 	 * when re-enabling a stream or in error/reset paths.
1764 	 *
1765 	 * The reason we clear the buffer for each re-init is for the
1766 	 * sanity check in gen7_append_oa_reports() that looks at the
1767 	 * report-id field to make sure it's non-zero which relies on
1768 	 * the assumption that new reports are being written to zeroed
1769 	 * memory...
1770 	 */
1771 	memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1772 }
1773 
gen8_init_oa_buffer(struct i915_perf_stream * stream)1774 static void gen8_init_oa_buffer(struct i915_perf_stream *stream)
1775 {
1776 	struct intel_uncore *uncore = stream->uncore;
1777 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1778 	unsigned long flags;
1779 
1780 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1781 
1782 	intel_uncore_write(uncore, GEN8_OASTATUS, 0);
1783 	intel_uncore_write(uncore, GEN8_OAHEADPTR, gtt_offset);
1784 	stream->oa_buffer.head = gtt_offset;
1785 
1786 	intel_uncore_write(uncore, GEN8_OABUFFER_UDW, 0);
1787 
1788 	/*
1789 	 * PRM says:
1790 	 *
1791 	 *  "This MMIO must be set before the OATAILPTR
1792 	 *  register and after the OAHEADPTR register. This is
1793 	 *  to enable proper functionality of the overflow
1794 	 *  bit."
1795 	 */
1796 	intel_uncore_write(uncore, GEN8_OABUFFER, gtt_offset |
1797 		   OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1798 	intel_uncore_write(uncore, GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1799 
1800 	/* Mark that we need updated tail pointers to read from... */
1801 	stream->oa_buffer.tail = gtt_offset;
1802 
1803 	/*
1804 	 * Reset state used to recognise context switches, affecting which
1805 	 * reports we will forward to userspace while filtering for a single
1806 	 * context.
1807 	 */
1808 	stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1809 
1810 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1811 
1812 	/*
1813 	 * NB: although the OA buffer will initially be allocated
1814 	 * zeroed via shmfs (and so this memset is redundant when
1815 	 * first allocating), we may re-init the OA buffer, either
1816 	 * when re-enabling a stream or in error/reset paths.
1817 	 *
1818 	 * The reason we clear the buffer for each re-init is for the
1819 	 * sanity check in gen8_append_oa_reports() that looks at the
1820 	 * reason field to make sure it's non-zero which relies on
1821 	 * the assumption that new reports are being written to zeroed
1822 	 * memory...
1823 	 */
1824 	memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1825 }
1826 
gen12_init_oa_buffer(struct i915_perf_stream * stream)1827 static void gen12_init_oa_buffer(struct i915_perf_stream *stream)
1828 {
1829 	struct intel_uncore *uncore = stream->uncore;
1830 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1831 	unsigned long flags;
1832 
1833 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1834 
1835 	intel_uncore_write(uncore, __oa_regs(stream)->oa_status, 0);
1836 	intel_uncore_write(uncore, __oa_regs(stream)->oa_head_ptr,
1837 			   gtt_offset & GEN12_OAG_OAHEADPTR_MASK);
1838 	stream->oa_buffer.head = gtt_offset;
1839 
1840 	/*
1841 	 * PRM says:
1842 	 *
1843 	 *  "This MMIO must be set before the OATAILPTR
1844 	 *  register and after the OAHEADPTR register. This is
1845 	 *  to enable proper functionality of the overflow
1846 	 *  bit."
1847 	 */
1848 	intel_uncore_write(uncore, __oa_regs(stream)->oa_buffer, gtt_offset |
1849 			   OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1850 	intel_uncore_write(uncore, __oa_regs(stream)->oa_tail_ptr,
1851 			   gtt_offset & GEN12_OAG_OATAILPTR_MASK);
1852 
1853 	/* Mark that we need updated tail pointers to read from... */
1854 	stream->oa_buffer.tail = gtt_offset;
1855 
1856 	/*
1857 	 * Reset state used to recognise context switches, affecting which
1858 	 * reports we will forward to userspace while filtering for a single
1859 	 * context.
1860 	 */
1861 	stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1862 
1863 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1864 
1865 	/*
1866 	 * NB: although the OA buffer will initially be allocated
1867 	 * zeroed via shmfs (and so this memset is redundant when
1868 	 * first allocating), we may re-init the OA buffer, either
1869 	 * when re-enabling a stream or in error/reset paths.
1870 	 *
1871 	 * The reason we clear the buffer for each re-init is for the
1872 	 * sanity check in gen8_append_oa_reports() that looks at the
1873 	 * reason field to make sure it's non-zero which relies on
1874 	 * the assumption that new reports are being written to zeroed
1875 	 * memory...
1876 	 */
1877 	memset(stream->oa_buffer.vaddr, 0,
1878 	       stream->oa_buffer.vma->size);
1879 }
1880 
alloc_oa_buffer(struct i915_perf_stream * stream)1881 static int alloc_oa_buffer(struct i915_perf_stream *stream)
1882 {
1883 	struct drm_i915_private *i915 = stream->perf->i915;
1884 	struct intel_gt *gt = stream->engine->gt;
1885 	struct drm_i915_gem_object *bo;
1886 	struct i915_vma *vma;
1887 	int ret;
1888 
1889 	if (drm_WARN_ON(&i915->drm, stream->oa_buffer.vma))
1890 		return -ENODEV;
1891 
1892 	BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1893 	BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1894 
1895 	bo = i915_gem_object_create_shmem(stream->perf->i915, OA_BUFFER_SIZE);
1896 	if (IS_ERR(bo)) {
1897 		drm_err(&i915->drm, "Failed to allocate OA buffer\n");
1898 		return PTR_ERR(bo);
1899 	}
1900 
1901 	i915_gem_object_set_cache_coherency(bo, I915_CACHE_LLC);
1902 
1903 	/* PreHSW required 512K alignment, HSW requires 16M */
1904 	vma = i915_vma_instance(bo, &gt->ggtt->vm, NULL);
1905 	if (IS_ERR(vma)) {
1906 		ret = PTR_ERR(vma);
1907 		goto err_unref;
1908 	}
1909 
1910 	/*
1911 	 * PreHSW required 512K alignment.
1912 	 * HSW and onwards, align to requested size of OA buffer.
1913 	 */
1914 	ret = i915_vma_pin(vma, 0, SZ_16M, PIN_GLOBAL | PIN_HIGH);
1915 	if (ret) {
1916 		drm_err(&gt->i915->drm, "Failed to pin OA buffer %d\n", ret);
1917 		goto err_unref;
1918 	}
1919 
1920 	stream->oa_buffer.vma = vma;
1921 
1922 	stream->oa_buffer.vaddr =
1923 		i915_gem_object_pin_map_unlocked(bo, I915_MAP_WB);
1924 	if (IS_ERR(stream->oa_buffer.vaddr)) {
1925 		ret = PTR_ERR(stream->oa_buffer.vaddr);
1926 		goto err_unpin;
1927 	}
1928 
1929 	return 0;
1930 
1931 err_unpin:
1932 	__i915_vma_unpin(vma);
1933 
1934 err_unref:
1935 	i915_gem_object_put(bo);
1936 
1937 	stream->oa_buffer.vaddr = NULL;
1938 	stream->oa_buffer.vma = NULL;
1939 
1940 	return ret;
1941 }
1942 
save_restore_register(struct i915_perf_stream * stream,u32 * cs,bool save,i915_reg_t reg,u32 offset,u32 dword_count)1943 static u32 *save_restore_register(struct i915_perf_stream *stream, u32 *cs,
1944 				  bool save, i915_reg_t reg, u32 offset,
1945 				  u32 dword_count)
1946 {
1947 	u32 cmd;
1948 	u32 d;
1949 
1950 	cmd = save ? MI_STORE_REGISTER_MEM : MI_LOAD_REGISTER_MEM;
1951 	cmd |= MI_SRM_LRM_GLOBAL_GTT;
1952 	if (GRAPHICS_VER(stream->perf->i915) >= 8)
1953 		cmd++;
1954 
1955 	for (d = 0; d < dword_count; d++) {
1956 		*cs++ = cmd;
1957 		*cs++ = i915_mmio_reg_offset(reg) + 4 * d;
1958 		*cs++ = i915_ggtt_offset(stream->noa_wait) + offset + 4 * d;
1959 		*cs++ = 0;
1960 	}
1961 
1962 	return cs;
1963 }
1964 
alloc_noa_wait(struct i915_perf_stream * stream)1965 static int alloc_noa_wait(struct i915_perf_stream *stream)
1966 {
1967 	struct drm_i915_private *i915 = stream->perf->i915;
1968 	struct intel_gt *gt = stream->engine->gt;
1969 	struct drm_i915_gem_object *bo;
1970 	struct i915_vma *vma;
1971 	const u64 delay_ticks = 0xffffffffffffffff -
1972 		intel_gt_ns_to_clock_interval(to_gt(stream->perf->i915),
1973 		atomic64_read(&stream->perf->noa_programming_delay));
1974 	const u32 base = stream->engine->mmio_base;
1975 #define CS_GPR(x) GEN8_RING_CS_GPR(base, x)
1976 	u32 *batch, *ts0, *cs, *jump;
1977 	struct i915_gem_ww_ctx ww;
1978 	int ret, i;
1979 	enum {
1980 		START_TS,
1981 		NOW_TS,
1982 		DELTA_TS,
1983 		JUMP_PREDICATE,
1984 		DELTA_TARGET,
1985 		N_CS_GPR
1986 	};
1987 	i915_reg_t mi_predicate_result = HAS_MI_SET_PREDICATE(i915) ?
1988 					  MI_PREDICATE_RESULT_2_ENGINE(base) :
1989 					  MI_PREDICATE_RESULT_1(RENDER_RING_BASE);
1990 
1991 	/*
1992 	 * gt->scratch was being used to save/restore the GPR registers, but on
1993 	 * MTL the scratch uses stolen lmem. An MI_SRM to this memory region
1994 	 * causes an engine hang. Instead allocate an additional page here to
1995 	 * save/restore GPR registers
1996 	 */
1997 	bo = i915_gem_object_create_internal(i915, 8192);
1998 	if (IS_ERR(bo)) {
1999 		drm_err(&i915->drm,
2000 			"Failed to allocate NOA wait batchbuffer\n");
2001 		return PTR_ERR(bo);
2002 	}
2003 
2004 	i915_gem_ww_ctx_init(&ww, true);
2005 retry:
2006 	ret = i915_gem_object_lock(bo, &ww);
2007 	if (ret)
2008 		goto out_ww;
2009 
2010 	/*
2011 	 * We pin in GGTT because we jump into this buffer now because
2012 	 * multiple OA config BOs will have a jump to this address and it
2013 	 * needs to be fixed during the lifetime of the i915/perf stream.
2014 	 */
2015 	vma = i915_vma_instance(bo, &gt->ggtt->vm, NULL);
2016 	if (IS_ERR(vma)) {
2017 		ret = PTR_ERR(vma);
2018 		goto out_ww;
2019 	}
2020 
2021 	ret = i915_vma_pin_ww(vma, &ww, 0, 0, PIN_GLOBAL | PIN_HIGH);
2022 	if (ret)
2023 		goto out_ww;
2024 
2025 	batch = cs = i915_gem_object_pin_map(bo, I915_MAP_WB);
2026 	if (IS_ERR(batch)) {
2027 		ret = PTR_ERR(batch);
2028 		goto err_unpin;
2029 	}
2030 
2031 	stream->noa_wait = vma;
2032 
2033 #define GPR_SAVE_OFFSET 4096
2034 #define PREDICATE_SAVE_OFFSET 4160
2035 
2036 	/* Save registers. */
2037 	for (i = 0; i < N_CS_GPR; i++)
2038 		cs = save_restore_register(
2039 			stream, cs, true /* save */, CS_GPR(i),
2040 			GPR_SAVE_OFFSET + 8 * i, 2);
2041 	cs = save_restore_register(
2042 		stream, cs, true /* save */, mi_predicate_result,
2043 		PREDICATE_SAVE_OFFSET, 1);
2044 
2045 	/* First timestamp snapshot location. */
2046 	ts0 = cs;
2047 
2048 	/*
2049 	 * Initial snapshot of the timestamp register to implement the wait.
2050 	 * We work with 32b values, so clear out the top 32b bits of the
2051 	 * register because the ALU works 64bits.
2052 	 */
2053 	*cs++ = MI_LOAD_REGISTER_IMM(1);
2054 	*cs++ = i915_mmio_reg_offset(CS_GPR(START_TS)) + 4;
2055 	*cs++ = 0;
2056 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
2057 	*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
2058 	*cs++ = i915_mmio_reg_offset(CS_GPR(START_TS));
2059 
2060 	/*
2061 	 * This is the location we're going to jump back into until the
2062 	 * required amount of time has passed.
2063 	 */
2064 	jump = cs;
2065 
2066 	/*
2067 	 * Take another snapshot of the timestamp register. Take care to clear
2068 	 * up the top 32bits of CS_GPR(1) as we're using it for other
2069 	 * operations below.
2070 	 */
2071 	*cs++ = MI_LOAD_REGISTER_IMM(1);
2072 	*cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS)) + 4;
2073 	*cs++ = 0;
2074 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
2075 	*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
2076 	*cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS));
2077 
2078 	/*
2079 	 * Do a diff between the 2 timestamps and store the result back into
2080 	 * CS_GPR(1).
2081 	 */
2082 	*cs++ = MI_MATH(5);
2083 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(NOW_TS));
2084 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(START_TS));
2085 	*cs++ = MI_MATH_SUB;
2086 	*cs++ = MI_MATH_STORE(MI_MATH_REG(DELTA_TS), MI_MATH_REG_ACCU);
2087 	*cs++ = MI_MATH_STORE(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
2088 
2089 	/*
2090 	 * Transfer the carry flag (set to 1 if ts1 < ts0, meaning the
2091 	 * timestamp have rolled over the 32bits) into the predicate register
2092 	 * to be used for the predicated jump.
2093 	 */
2094 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
2095 	*cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
2096 	*cs++ = i915_mmio_reg_offset(mi_predicate_result);
2097 
2098 	if (HAS_MI_SET_PREDICATE(i915))
2099 		*cs++ = MI_SET_PREDICATE | 1;
2100 
2101 	/* Restart from the beginning if we had timestamps roll over. */
2102 	*cs++ = (GRAPHICS_VER(i915) < 8 ?
2103 		 MI_BATCH_BUFFER_START :
2104 		 MI_BATCH_BUFFER_START_GEN8) |
2105 		MI_BATCH_PREDICATE;
2106 	*cs++ = i915_ggtt_offset(vma) + (ts0 - batch) * 4;
2107 	*cs++ = 0;
2108 
2109 	if (HAS_MI_SET_PREDICATE(i915))
2110 		*cs++ = MI_SET_PREDICATE;
2111 
2112 	/*
2113 	 * Now add the diff between to previous timestamps and add it to :
2114 	 *      (((1 * << 64) - 1) - delay_ns)
2115 	 *
2116 	 * When the Carry Flag contains 1 this means the elapsed time is
2117 	 * longer than the expected delay, and we can exit the wait loop.
2118 	 */
2119 	*cs++ = MI_LOAD_REGISTER_IMM(2);
2120 	*cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET));
2121 	*cs++ = lower_32_bits(delay_ticks);
2122 	*cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET)) + 4;
2123 	*cs++ = upper_32_bits(delay_ticks);
2124 
2125 	*cs++ = MI_MATH(4);
2126 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(DELTA_TS));
2127 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(DELTA_TARGET));
2128 	*cs++ = MI_MATH_ADD;
2129 	*cs++ = MI_MATH_STOREINV(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
2130 
2131 	*cs++ = MI_ARB_CHECK;
2132 
2133 	/*
2134 	 * Transfer the result into the predicate register to be used for the
2135 	 * predicated jump.
2136 	 */
2137 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
2138 	*cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
2139 	*cs++ = i915_mmio_reg_offset(mi_predicate_result);
2140 
2141 	if (HAS_MI_SET_PREDICATE(i915))
2142 		*cs++ = MI_SET_PREDICATE | 1;
2143 
2144 	/* Predicate the jump.  */
2145 	*cs++ = (GRAPHICS_VER(i915) < 8 ?
2146 		 MI_BATCH_BUFFER_START :
2147 		 MI_BATCH_BUFFER_START_GEN8) |
2148 		MI_BATCH_PREDICATE;
2149 	*cs++ = i915_ggtt_offset(vma) + (jump - batch) * 4;
2150 	*cs++ = 0;
2151 
2152 	if (HAS_MI_SET_PREDICATE(i915))
2153 		*cs++ = MI_SET_PREDICATE;
2154 
2155 	/* Restore registers. */
2156 	for (i = 0; i < N_CS_GPR; i++)
2157 		cs = save_restore_register(
2158 			stream, cs, false /* restore */, CS_GPR(i),
2159 			GPR_SAVE_OFFSET + 8 * i, 2);
2160 	cs = save_restore_register(
2161 		stream, cs, false /* restore */, mi_predicate_result,
2162 		PREDICATE_SAVE_OFFSET, 1);
2163 
2164 	/* And return to the ring. */
2165 	*cs++ = MI_BATCH_BUFFER_END;
2166 
2167 	GEM_BUG_ON(cs - batch > PAGE_SIZE / sizeof(*batch));
2168 
2169 	i915_gem_object_flush_map(bo);
2170 	__i915_gem_object_release_map(bo);
2171 
2172 	goto out_ww;
2173 
2174 err_unpin:
2175 	i915_vma_unpin_and_release(&vma, 0);
2176 out_ww:
2177 	if (ret == -EDEADLK) {
2178 		ret = i915_gem_ww_ctx_backoff(&ww);
2179 		if (!ret)
2180 			goto retry;
2181 	}
2182 	i915_gem_ww_ctx_fini(&ww);
2183 	if (ret)
2184 		i915_gem_object_put(bo);
2185 	return ret;
2186 }
2187 
write_cs_mi_lri(u32 * cs,const struct i915_oa_reg * reg_data,u32 n_regs)2188 static u32 *write_cs_mi_lri(u32 *cs,
2189 			    const struct i915_oa_reg *reg_data,
2190 			    u32 n_regs)
2191 {
2192 	u32 i;
2193 
2194 	for (i = 0; i < n_regs; i++) {
2195 		if ((i % MI_LOAD_REGISTER_IMM_MAX_REGS) == 0) {
2196 			u32 n_lri = min_t(u32,
2197 					  n_regs - i,
2198 					  MI_LOAD_REGISTER_IMM_MAX_REGS);
2199 
2200 			*cs++ = MI_LOAD_REGISTER_IMM(n_lri);
2201 		}
2202 		*cs++ = i915_mmio_reg_offset(reg_data[i].addr);
2203 		*cs++ = reg_data[i].value;
2204 	}
2205 
2206 	return cs;
2207 }
2208 
num_lri_dwords(int num_regs)2209 static int num_lri_dwords(int num_regs)
2210 {
2211 	int count = 0;
2212 
2213 	if (num_regs > 0) {
2214 		count += DIV_ROUND_UP(num_regs, MI_LOAD_REGISTER_IMM_MAX_REGS);
2215 		count += num_regs * 2;
2216 	}
2217 
2218 	return count;
2219 }
2220 
2221 static struct i915_oa_config_bo *
alloc_oa_config_buffer(struct i915_perf_stream * stream,struct i915_oa_config * oa_config)2222 alloc_oa_config_buffer(struct i915_perf_stream *stream,
2223 		       struct i915_oa_config *oa_config)
2224 {
2225 	struct drm_i915_gem_object *obj;
2226 	struct i915_oa_config_bo *oa_bo;
2227 	struct i915_gem_ww_ctx ww;
2228 	size_t config_length = 0;
2229 	u32 *cs;
2230 	int err;
2231 
2232 	oa_bo = kzalloc(sizeof(*oa_bo), GFP_KERNEL);
2233 	if (!oa_bo)
2234 		return ERR_PTR(-ENOMEM);
2235 
2236 	config_length += num_lri_dwords(oa_config->mux_regs_len);
2237 	config_length += num_lri_dwords(oa_config->b_counter_regs_len);
2238 	config_length += num_lri_dwords(oa_config->flex_regs_len);
2239 	config_length += 3; /* MI_BATCH_BUFFER_START */
2240 	config_length = ALIGN(sizeof(u32) * config_length, I915_GTT_PAGE_SIZE);
2241 
2242 	obj = i915_gem_object_create_shmem(stream->perf->i915, config_length);
2243 	if (IS_ERR(obj)) {
2244 		err = PTR_ERR(obj);
2245 		goto err_free;
2246 	}
2247 
2248 	i915_gem_ww_ctx_init(&ww, true);
2249 retry:
2250 	err = i915_gem_object_lock(obj, &ww);
2251 	if (err)
2252 		goto out_ww;
2253 
2254 	cs = i915_gem_object_pin_map(obj, I915_MAP_WB);
2255 	if (IS_ERR(cs)) {
2256 		err = PTR_ERR(cs);
2257 		goto out_ww;
2258 	}
2259 
2260 	cs = write_cs_mi_lri(cs,
2261 			     oa_config->mux_regs,
2262 			     oa_config->mux_regs_len);
2263 	cs = write_cs_mi_lri(cs,
2264 			     oa_config->b_counter_regs,
2265 			     oa_config->b_counter_regs_len);
2266 	cs = write_cs_mi_lri(cs,
2267 			     oa_config->flex_regs,
2268 			     oa_config->flex_regs_len);
2269 
2270 	/* Jump into the active wait. */
2271 	*cs++ = (GRAPHICS_VER(stream->perf->i915) < 8 ?
2272 		 MI_BATCH_BUFFER_START :
2273 		 MI_BATCH_BUFFER_START_GEN8);
2274 	*cs++ = i915_ggtt_offset(stream->noa_wait);
2275 	*cs++ = 0;
2276 
2277 	i915_gem_object_flush_map(obj);
2278 	__i915_gem_object_release_map(obj);
2279 
2280 	oa_bo->vma = i915_vma_instance(obj,
2281 				       &stream->engine->gt->ggtt->vm,
2282 				       NULL);
2283 	if (IS_ERR(oa_bo->vma)) {
2284 		err = PTR_ERR(oa_bo->vma);
2285 		goto out_ww;
2286 	}
2287 
2288 	oa_bo->oa_config = i915_oa_config_get(oa_config);
2289 	llist_add(&oa_bo->node, &stream->oa_config_bos);
2290 
2291 out_ww:
2292 	if (err == -EDEADLK) {
2293 		err = i915_gem_ww_ctx_backoff(&ww);
2294 		if (!err)
2295 			goto retry;
2296 	}
2297 	i915_gem_ww_ctx_fini(&ww);
2298 
2299 	if (err)
2300 		i915_gem_object_put(obj);
2301 err_free:
2302 	if (err) {
2303 		kfree(oa_bo);
2304 		return ERR_PTR(err);
2305 	}
2306 	return oa_bo;
2307 }
2308 
2309 static struct i915_vma *
get_oa_vma(struct i915_perf_stream * stream,struct i915_oa_config * oa_config)2310 get_oa_vma(struct i915_perf_stream *stream, struct i915_oa_config *oa_config)
2311 {
2312 	struct i915_oa_config_bo *oa_bo;
2313 
2314 	/*
2315 	 * Look for the buffer in the already allocated BOs attached
2316 	 * to the stream.
2317 	 */
2318 	llist_for_each_entry(oa_bo, stream->oa_config_bos.first, node) {
2319 		if (oa_bo->oa_config == oa_config &&
2320 		    memcmp(oa_bo->oa_config->uuid,
2321 			   oa_config->uuid,
2322 			   sizeof(oa_config->uuid)) == 0)
2323 			goto out;
2324 	}
2325 
2326 	oa_bo = alloc_oa_config_buffer(stream, oa_config);
2327 	if (IS_ERR(oa_bo))
2328 		return ERR_CAST(oa_bo);
2329 
2330 out:
2331 	return i915_vma_get(oa_bo->vma);
2332 }
2333 
2334 static int
emit_oa_config(struct i915_perf_stream * stream,struct i915_oa_config * oa_config,struct intel_context * ce,struct i915_active * active)2335 emit_oa_config(struct i915_perf_stream *stream,
2336 	       struct i915_oa_config *oa_config,
2337 	       struct intel_context *ce,
2338 	       struct i915_active *active)
2339 {
2340 	struct i915_request *rq;
2341 	struct i915_vma *vma;
2342 	struct i915_gem_ww_ctx ww;
2343 	int err;
2344 
2345 	vma = get_oa_vma(stream, oa_config);
2346 	if (IS_ERR(vma))
2347 		return PTR_ERR(vma);
2348 
2349 	i915_gem_ww_ctx_init(&ww, true);
2350 retry:
2351 	err = i915_gem_object_lock(vma->obj, &ww);
2352 	if (err)
2353 		goto err;
2354 
2355 	err = i915_vma_pin_ww(vma, &ww, 0, 0, PIN_GLOBAL | PIN_HIGH);
2356 	if (err)
2357 		goto err;
2358 
2359 	intel_engine_pm_get(ce->engine);
2360 	rq = i915_request_create(ce);
2361 	intel_engine_pm_put(ce->engine);
2362 	if (IS_ERR(rq)) {
2363 		err = PTR_ERR(rq);
2364 		goto err_vma_unpin;
2365 	}
2366 
2367 	if (!IS_ERR_OR_NULL(active)) {
2368 		/* After all individual context modifications */
2369 		err = i915_request_await_active(rq, active,
2370 						I915_ACTIVE_AWAIT_ACTIVE);
2371 		if (err)
2372 			goto err_add_request;
2373 
2374 		err = i915_active_add_request(active, rq);
2375 		if (err)
2376 			goto err_add_request;
2377 	}
2378 
2379 	err = i915_vma_move_to_active(vma, rq, 0);
2380 	if (err)
2381 		goto err_add_request;
2382 
2383 	err = rq->engine->emit_bb_start(rq,
2384 					i915_vma_offset(vma), 0,
2385 					I915_DISPATCH_SECURE);
2386 	if (err)
2387 		goto err_add_request;
2388 
2389 err_add_request:
2390 	i915_request_add(rq);
2391 err_vma_unpin:
2392 	i915_vma_unpin(vma);
2393 err:
2394 	if (err == -EDEADLK) {
2395 		err = i915_gem_ww_ctx_backoff(&ww);
2396 		if (!err)
2397 			goto retry;
2398 	}
2399 
2400 	i915_gem_ww_ctx_fini(&ww);
2401 	i915_vma_put(vma);
2402 	return err;
2403 }
2404 
oa_context(struct i915_perf_stream * stream)2405 static struct intel_context *oa_context(struct i915_perf_stream *stream)
2406 {
2407 	return stream->pinned_ctx ?: stream->engine->kernel_context;
2408 }
2409 
2410 static int
hsw_enable_metric_set(struct i915_perf_stream * stream,struct i915_active * active)2411 hsw_enable_metric_set(struct i915_perf_stream *stream,
2412 		      struct i915_active *active)
2413 {
2414 	struct intel_uncore *uncore = stream->uncore;
2415 
2416 	/*
2417 	 * PRM:
2418 	 *
2419 	 * OA unit is using “crclk” for its functionality. When trunk
2420 	 * level clock gating takes place, OA clock would be gated,
2421 	 * unable to count the events from non-render clock domain.
2422 	 * Render clock gating must be disabled when OA is enabled to
2423 	 * count the events from non-render domain. Unit level clock
2424 	 * gating for RCS should also be disabled.
2425 	 */
2426 	intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
2427 			 GEN7_DOP_CLOCK_GATE_ENABLE, 0);
2428 	intel_uncore_rmw(uncore, GEN6_UCGCTL1,
2429 			 0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
2430 
2431 	return emit_oa_config(stream,
2432 			      stream->oa_config, oa_context(stream),
2433 			      active);
2434 }
2435 
hsw_disable_metric_set(struct i915_perf_stream * stream)2436 static void hsw_disable_metric_set(struct i915_perf_stream *stream)
2437 {
2438 	struct intel_uncore *uncore = stream->uncore;
2439 
2440 	intel_uncore_rmw(uncore, GEN6_UCGCTL1,
2441 			 GEN6_CSUNIT_CLOCK_GATE_DISABLE, 0);
2442 	intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
2443 			 0, GEN7_DOP_CLOCK_GATE_ENABLE);
2444 
2445 	intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2446 }
2447 
oa_config_flex_reg(const struct i915_oa_config * oa_config,i915_reg_t reg)2448 static u32 oa_config_flex_reg(const struct i915_oa_config *oa_config,
2449 			      i915_reg_t reg)
2450 {
2451 	u32 mmio = i915_mmio_reg_offset(reg);
2452 	int i;
2453 
2454 	/*
2455 	 * This arbitrary default will select the 'EU FPU0 Pipeline
2456 	 * Active' event. In the future it's anticipated that there
2457 	 * will be an explicit 'No Event' we can select, but not yet...
2458 	 */
2459 	if (!oa_config)
2460 		return 0;
2461 
2462 	for (i = 0; i < oa_config->flex_regs_len; i++) {
2463 		if (i915_mmio_reg_offset(oa_config->flex_regs[i].addr) == mmio)
2464 			return oa_config->flex_regs[i].value;
2465 	}
2466 
2467 	return 0;
2468 }
2469 /*
2470  * NB: It must always remain pointer safe to run this even if the OA unit
2471  * has been disabled.
2472  *
2473  * It's fine to put out-of-date values into these per-context registers
2474  * in the case that the OA unit has been disabled.
2475  */
2476 static void
gen8_update_reg_state_unlocked(const struct intel_context * ce,const struct i915_perf_stream * stream)2477 gen8_update_reg_state_unlocked(const struct intel_context *ce,
2478 			       const struct i915_perf_stream *stream)
2479 {
2480 	u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
2481 	u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2482 	/* The MMIO offsets for Flex EU registers aren't contiguous */
2483 	static const i915_reg_t flex_regs[] = {
2484 		EU_PERF_CNTL0,
2485 		EU_PERF_CNTL1,
2486 		EU_PERF_CNTL2,
2487 		EU_PERF_CNTL3,
2488 		EU_PERF_CNTL4,
2489 		EU_PERF_CNTL5,
2490 		EU_PERF_CNTL6,
2491 	};
2492 	u32 *reg_state = ce->lrc_reg_state;
2493 	int i;
2494 
2495 	reg_state[ctx_oactxctrl + 1] =
2496 		(stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2497 		(stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2498 		GEN8_OA_COUNTER_RESUME;
2499 
2500 	for (i = 0; i < ARRAY_SIZE(flex_regs); i++)
2501 		reg_state[ctx_flexeu0 + i * 2 + 1] =
2502 			oa_config_flex_reg(stream->oa_config, flex_regs[i]);
2503 }
2504 
2505 struct flex {
2506 	i915_reg_t reg;
2507 	u32 offset;
2508 	u32 value;
2509 };
2510 
2511 static int
gen8_store_flex(struct i915_request * rq,struct intel_context * ce,const struct flex * flex,unsigned int count)2512 gen8_store_flex(struct i915_request *rq,
2513 		struct intel_context *ce,
2514 		const struct flex *flex, unsigned int count)
2515 {
2516 	u32 offset;
2517 	u32 *cs;
2518 
2519 	cs = intel_ring_begin(rq, 4 * count);
2520 	if (IS_ERR(cs))
2521 		return PTR_ERR(cs);
2522 
2523 	offset = i915_ggtt_offset(ce->state) + LRC_STATE_OFFSET;
2524 	do {
2525 		*cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
2526 		*cs++ = offset + flex->offset * sizeof(u32);
2527 		*cs++ = 0;
2528 		*cs++ = flex->value;
2529 	} while (flex++, --count);
2530 
2531 	intel_ring_advance(rq, cs);
2532 
2533 	return 0;
2534 }
2535 
2536 static int
gen8_load_flex(struct i915_request * rq,struct intel_context * ce,const struct flex * flex,unsigned int count)2537 gen8_load_flex(struct i915_request *rq,
2538 	       struct intel_context *ce,
2539 	       const struct flex *flex, unsigned int count)
2540 {
2541 	u32 *cs;
2542 
2543 	GEM_BUG_ON(!count || count > 63);
2544 
2545 	cs = intel_ring_begin(rq, 2 * count + 2);
2546 	if (IS_ERR(cs))
2547 		return PTR_ERR(cs);
2548 
2549 	*cs++ = MI_LOAD_REGISTER_IMM(count);
2550 	do {
2551 		*cs++ = i915_mmio_reg_offset(flex->reg);
2552 		*cs++ = flex->value;
2553 	} while (flex++, --count);
2554 	*cs++ = MI_NOOP;
2555 
2556 	intel_ring_advance(rq, cs);
2557 
2558 	return 0;
2559 }
2560 
gen8_modify_context(struct intel_context * ce,const struct flex * flex,unsigned int count)2561 static int gen8_modify_context(struct intel_context *ce,
2562 			       const struct flex *flex, unsigned int count)
2563 {
2564 	struct i915_request *rq;
2565 	int err;
2566 
2567 	rq = intel_engine_create_kernel_request(ce->engine);
2568 	if (IS_ERR(rq))
2569 		return PTR_ERR(rq);
2570 
2571 	/* Serialise with the remote context */
2572 	err = intel_context_prepare_remote_request(ce, rq);
2573 	if (err == 0)
2574 		err = gen8_store_flex(rq, ce, flex, count);
2575 
2576 	i915_request_add(rq);
2577 	return err;
2578 }
2579 
2580 static int
gen8_modify_self(struct intel_context * ce,const struct flex * flex,unsigned int count,struct i915_active * active)2581 gen8_modify_self(struct intel_context *ce,
2582 		 const struct flex *flex, unsigned int count,
2583 		 struct i915_active *active)
2584 {
2585 	struct i915_request *rq;
2586 	int err;
2587 
2588 	intel_engine_pm_get(ce->engine);
2589 	rq = i915_request_create(ce);
2590 	intel_engine_pm_put(ce->engine);
2591 	if (IS_ERR(rq))
2592 		return PTR_ERR(rq);
2593 
2594 	if (!IS_ERR_OR_NULL(active)) {
2595 		err = i915_active_add_request(active, rq);
2596 		if (err)
2597 			goto err_add_request;
2598 	}
2599 
2600 	err = gen8_load_flex(rq, ce, flex, count);
2601 	if (err)
2602 		goto err_add_request;
2603 
2604 err_add_request:
2605 	i915_request_add(rq);
2606 	return err;
2607 }
2608 
gen8_configure_context(struct i915_perf_stream * stream,struct i915_gem_context * ctx,struct flex * flex,unsigned int count)2609 static int gen8_configure_context(struct i915_perf_stream *stream,
2610 				  struct i915_gem_context *ctx,
2611 				  struct flex *flex, unsigned int count)
2612 {
2613 	struct i915_gem_engines_iter it;
2614 	struct intel_context *ce;
2615 	int err = 0;
2616 
2617 	for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
2618 		GEM_BUG_ON(ce == ce->engine->kernel_context);
2619 
2620 		if (ce->engine->class != RENDER_CLASS)
2621 			continue;
2622 
2623 		/* Otherwise OA settings will be set upon first use */
2624 		if (!intel_context_pin_if_active(ce))
2625 			continue;
2626 
2627 		flex->value = intel_sseu_make_rpcs(ce->engine->gt, &ce->sseu);
2628 		err = gen8_modify_context(ce, flex, count);
2629 
2630 		intel_context_unpin(ce);
2631 		if (err)
2632 			break;
2633 	}
2634 	i915_gem_context_unlock_engines(ctx);
2635 
2636 	return err;
2637 }
2638 
gen12_configure_oar_context(struct i915_perf_stream * stream,struct i915_active * active)2639 static int gen12_configure_oar_context(struct i915_perf_stream *stream,
2640 				       struct i915_active *active)
2641 {
2642 	int err;
2643 	struct intel_context *ce = stream->pinned_ctx;
2644 	u32 format = stream->oa_buffer.format->format;
2645 	u32 offset = stream->perf->ctx_oactxctrl_offset;
2646 	struct flex regs_context[] = {
2647 		{
2648 			GEN8_OACTXCONTROL,
2649 			offset + 1,
2650 			active ? GEN8_OA_COUNTER_RESUME : 0,
2651 		},
2652 	};
2653 	/* Offsets in regs_lri are not used since this configuration is only
2654 	 * applied using LRI. Initialize the correct offsets for posterity.
2655 	 */
2656 #define GEN12_OAR_OACONTROL_OFFSET 0x5B0
2657 	struct flex regs_lri[] = {
2658 		{
2659 			GEN12_OAR_OACONTROL,
2660 			GEN12_OAR_OACONTROL_OFFSET + 1,
2661 			(format << GEN12_OAR_OACONTROL_COUNTER_FORMAT_SHIFT) |
2662 			(active ? GEN12_OAR_OACONTROL_COUNTER_ENABLE : 0)
2663 		},
2664 		{
2665 			RING_CONTEXT_CONTROL(ce->engine->mmio_base),
2666 			CTX_CONTEXT_CONTROL,
2667 			_MASKED_FIELD(GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE,
2668 				      active ?
2669 				      GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE :
2670 				      0)
2671 		},
2672 	};
2673 
2674 	/* Modify the context image of pinned context with regs_context */
2675 	err = intel_context_lock_pinned(ce);
2676 	if (err)
2677 		return err;
2678 
2679 	err = gen8_modify_context(ce, regs_context,
2680 				  ARRAY_SIZE(regs_context));
2681 	intel_context_unlock_pinned(ce);
2682 	if (err)
2683 		return err;
2684 
2685 	/* Apply regs_lri using LRI with pinned context */
2686 	return gen8_modify_self(ce, regs_lri, ARRAY_SIZE(regs_lri), active);
2687 }
2688 
2689 /*
2690  * Manages updating the per-context aspects of the OA stream
2691  * configuration across all contexts.
2692  *
2693  * The awkward consideration here is that OACTXCONTROL controls the
2694  * exponent for periodic sampling which is primarily used for system
2695  * wide profiling where we'd like a consistent sampling period even in
2696  * the face of context switches.
2697  *
2698  * Our approach of updating the register state context (as opposed to
2699  * say using a workaround batch buffer) ensures that the hardware
2700  * won't automatically reload an out-of-date timer exponent even
2701  * transiently before a WA BB could be parsed.
2702  *
2703  * This function needs to:
2704  * - Ensure the currently running context's per-context OA state is
2705  *   updated
2706  * - Ensure that all existing contexts will have the correct per-context
2707  *   OA state if they are scheduled for use.
2708  * - Ensure any new contexts will be initialized with the correct
2709  *   per-context OA state.
2710  *
2711  * Note: it's only the RCS/Render context that has any OA state.
2712  * Note: the first flex register passed must always be R_PWR_CLK_STATE
2713  */
2714 static int
oa_configure_all_contexts(struct i915_perf_stream * stream,struct flex * regs,size_t num_regs,struct i915_active * active)2715 oa_configure_all_contexts(struct i915_perf_stream *stream,
2716 			  struct flex *regs,
2717 			  size_t num_regs,
2718 			  struct i915_active *active)
2719 {
2720 	struct drm_i915_private *i915 = stream->perf->i915;
2721 	struct intel_engine_cs *engine;
2722 	struct intel_gt *gt = stream->engine->gt;
2723 	struct i915_gem_context *ctx, *cn;
2724 	int err;
2725 
2726 	lockdep_assert_held(&gt->perf.lock);
2727 
2728 	/*
2729 	 * The OA register config is setup through the context image. This image
2730 	 * might be written to by the GPU on context switch (in particular on
2731 	 * lite-restore). This means we can't safely update a context's image,
2732 	 * if this context is scheduled/submitted to run on the GPU.
2733 	 *
2734 	 * We could emit the OA register config through the batch buffer but
2735 	 * this might leave small interval of time where the OA unit is
2736 	 * configured at an invalid sampling period.
2737 	 *
2738 	 * Note that since we emit all requests from a single ring, there
2739 	 * is still an implicit global barrier here that may cause a high
2740 	 * priority context to wait for an otherwise independent low priority
2741 	 * context. Contexts idle at the time of reconfiguration are not
2742 	 * trapped behind the barrier.
2743 	 */
2744 	spin_lock(&i915->gem.contexts.lock);
2745 	list_for_each_entry_safe(ctx, cn, &i915->gem.contexts.list, link) {
2746 		if (!kref_get_unless_zero(&ctx->ref))
2747 			continue;
2748 
2749 		spin_unlock(&i915->gem.contexts.lock);
2750 
2751 		err = gen8_configure_context(stream, ctx, regs, num_regs);
2752 		if (err) {
2753 			i915_gem_context_put(ctx);
2754 			return err;
2755 		}
2756 
2757 		spin_lock(&i915->gem.contexts.lock);
2758 		list_safe_reset_next(ctx, cn, link);
2759 		i915_gem_context_put(ctx);
2760 	}
2761 	spin_unlock(&i915->gem.contexts.lock);
2762 
2763 	/*
2764 	 * After updating all other contexts, we need to modify ourselves.
2765 	 * If we don't modify the kernel_context, we do not get events while
2766 	 * idle.
2767 	 */
2768 	for_each_uabi_engine(engine, i915) {
2769 		struct intel_context *ce = engine->kernel_context;
2770 
2771 		if (engine->class != RENDER_CLASS)
2772 			continue;
2773 
2774 		regs[0].value = intel_sseu_make_rpcs(engine->gt, &ce->sseu);
2775 
2776 		err = gen8_modify_self(ce, regs, num_regs, active);
2777 		if (err)
2778 			return err;
2779 	}
2780 
2781 	return 0;
2782 }
2783 
2784 static int
gen12_configure_all_contexts(struct i915_perf_stream * stream,const struct i915_oa_config * oa_config,struct i915_active * active)2785 gen12_configure_all_contexts(struct i915_perf_stream *stream,
2786 			     const struct i915_oa_config *oa_config,
2787 			     struct i915_active *active)
2788 {
2789 	struct flex regs[] = {
2790 		{
2791 			GEN8_R_PWR_CLK_STATE(RENDER_RING_BASE),
2792 			CTX_R_PWR_CLK_STATE,
2793 		},
2794 	};
2795 
2796 	if (stream->engine->class != RENDER_CLASS)
2797 		return 0;
2798 
2799 	return oa_configure_all_contexts(stream,
2800 					 regs, ARRAY_SIZE(regs),
2801 					 active);
2802 }
2803 
2804 static int
lrc_configure_all_contexts(struct i915_perf_stream * stream,const struct i915_oa_config * oa_config,struct i915_active * active)2805 lrc_configure_all_contexts(struct i915_perf_stream *stream,
2806 			   const struct i915_oa_config *oa_config,
2807 			   struct i915_active *active)
2808 {
2809 	u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
2810 	/* The MMIO offsets for Flex EU registers aren't contiguous */
2811 	const u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2812 #define ctx_flexeuN(N) (ctx_flexeu0 + 2 * (N) + 1)
2813 	struct flex regs[] = {
2814 		{
2815 			GEN8_R_PWR_CLK_STATE(RENDER_RING_BASE),
2816 			CTX_R_PWR_CLK_STATE,
2817 		},
2818 		{
2819 			GEN8_OACTXCONTROL,
2820 			ctx_oactxctrl + 1,
2821 		},
2822 		{ EU_PERF_CNTL0, ctx_flexeuN(0) },
2823 		{ EU_PERF_CNTL1, ctx_flexeuN(1) },
2824 		{ EU_PERF_CNTL2, ctx_flexeuN(2) },
2825 		{ EU_PERF_CNTL3, ctx_flexeuN(3) },
2826 		{ EU_PERF_CNTL4, ctx_flexeuN(4) },
2827 		{ EU_PERF_CNTL5, ctx_flexeuN(5) },
2828 		{ EU_PERF_CNTL6, ctx_flexeuN(6) },
2829 	};
2830 #undef ctx_flexeuN
2831 	int i;
2832 
2833 	regs[1].value =
2834 		(stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2835 		(stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2836 		GEN8_OA_COUNTER_RESUME;
2837 
2838 	for (i = 2; i < ARRAY_SIZE(regs); i++)
2839 		regs[i].value = oa_config_flex_reg(oa_config, regs[i].reg);
2840 
2841 	return oa_configure_all_contexts(stream,
2842 					 regs, ARRAY_SIZE(regs),
2843 					 active);
2844 }
2845 
2846 static int
gen8_enable_metric_set(struct i915_perf_stream * stream,struct i915_active * active)2847 gen8_enable_metric_set(struct i915_perf_stream *stream,
2848 		       struct i915_active *active)
2849 {
2850 	struct intel_uncore *uncore = stream->uncore;
2851 	struct i915_oa_config *oa_config = stream->oa_config;
2852 	int ret;
2853 
2854 	/*
2855 	 * We disable slice/unslice clock ratio change reports on SKL since
2856 	 * they are too noisy. The HW generates a lot of redundant reports
2857 	 * where the ratio hasn't really changed causing a lot of redundant
2858 	 * work to processes and increasing the chances we'll hit buffer
2859 	 * overruns.
2860 	 *
2861 	 * Although we don't currently use the 'disable overrun' OABUFFER
2862 	 * feature it's worth noting that clock ratio reports have to be
2863 	 * disabled before considering to use that feature since the HW doesn't
2864 	 * correctly block these reports.
2865 	 *
2866 	 * Currently none of the high-level metrics we have depend on knowing
2867 	 * this ratio to normalize.
2868 	 *
2869 	 * Note: This register is not power context saved and restored, but
2870 	 * that's OK considering that we disable RC6 while the OA unit is
2871 	 * enabled.
2872 	 *
2873 	 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
2874 	 * be read back from automatically triggered reports, as part of the
2875 	 * RPT_ID field.
2876 	 */
2877 	if (IS_GRAPHICS_VER(stream->perf->i915, 9, 11)) {
2878 		intel_uncore_write(uncore, GEN8_OA_DEBUG,
2879 				   _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2880 						      GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
2881 	}
2882 
2883 	/*
2884 	 * Update all contexts prior writing the mux configurations as we need
2885 	 * to make sure all slices/subslices are ON before writing to NOA
2886 	 * registers.
2887 	 */
2888 	ret = lrc_configure_all_contexts(stream, oa_config, active);
2889 	if (ret)
2890 		return ret;
2891 
2892 	return emit_oa_config(stream,
2893 			      stream->oa_config, oa_context(stream),
2894 			      active);
2895 }
2896 
oag_report_ctx_switches(const struct i915_perf_stream * stream)2897 static u32 oag_report_ctx_switches(const struct i915_perf_stream *stream)
2898 {
2899 	return _MASKED_FIELD(GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS,
2900 			     (stream->sample_flags & SAMPLE_OA_REPORT) ?
2901 			     0 : GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS);
2902 }
2903 
2904 static int
gen12_enable_metric_set(struct i915_perf_stream * stream,struct i915_active * active)2905 gen12_enable_metric_set(struct i915_perf_stream *stream,
2906 			struct i915_active *active)
2907 {
2908 	struct drm_i915_private *i915 = stream->perf->i915;
2909 	struct intel_uncore *uncore = stream->uncore;
2910 	struct i915_oa_config *oa_config = stream->oa_config;
2911 	bool periodic = stream->periodic;
2912 	u32 period_exponent = stream->period_exponent;
2913 	u32 sqcnt1;
2914 	int ret;
2915 
2916 	/*
2917 	 * Wa_1508761755:xehpsdv, dg2
2918 	 * EU NOA signals behave incorrectly if EU clock gating is enabled.
2919 	 * Disable thread stall DOP gating and EU DOP gating.
2920 	 */
2921 	if (IS_XEHPSDV(i915) || IS_DG2(i915)) {
2922 		intel_gt_mcr_multicast_write(uncore->gt, GEN8_ROW_CHICKEN,
2923 					     _MASKED_BIT_ENABLE(STALL_DOP_GATING_DISABLE));
2924 		intel_uncore_write(uncore, GEN7_ROW_CHICKEN2,
2925 				   _MASKED_BIT_ENABLE(GEN12_DISABLE_DOP_GATING));
2926 	}
2927 
2928 	intel_uncore_write(uncore, __oa_regs(stream)->oa_debug,
2929 			   /* Disable clk ratio reports, like previous Gens. */
2930 			   _MASKED_BIT_ENABLE(GEN12_OAG_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2931 					      GEN12_OAG_OA_DEBUG_INCLUDE_CLK_RATIO) |
2932 			   /*
2933 			    * If the user didn't require OA reports, instruct
2934 			    * the hardware not to emit ctx switch reports.
2935 			    */
2936 			   oag_report_ctx_switches(stream));
2937 
2938 	intel_uncore_write(uncore, __oa_regs(stream)->oa_ctx_ctrl, periodic ?
2939 			   (GEN12_OAG_OAGLBCTXCTRL_COUNTER_RESUME |
2940 			    GEN12_OAG_OAGLBCTXCTRL_TIMER_ENABLE |
2941 			    (period_exponent << GEN12_OAG_OAGLBCTXCTRL_TIMER_PERIOD_SHIFT))
2942 			    : 0);
2943 
2944 	/*
2945 	 * Initialize Super Queue Internal Cnt Register
2946 	 * Set PMON Enable in order to collect valid metrics.
2947 	 * Enable byets per clock reporting in OA for XEHPSDV onward.
2948 	 */
2949 	sqcnt1 = GEN12_SQCNT1_PMON_ENABLE |
2950 		 (HAS_OA_BPC_REPORTING(i915) ? GEN12_SQCNT1_OABPC : 0);
2951 
2952 	intel_uncore_rmw(uncore, GEN12_SQCNT1, 0, sqcnt1);
2953 
2954 	/*
2955 	 * Update all contexts prior writing the mux configurations as we need
2956 	 * to make sure all slices/subslices are ON before writing to NOA
2957 	 * registers.
2958 	 */
2959 	ret = gen12_configure_all_contexts(stream, oa_config, active);
2960 	if (ret)
2961 		return ret;
2962 
2963 	/*
2964 	 * For Gen12, performance counters are context
2965 	 * saved/restored. Only enable it for the context that
2966 	 * requested this.
2967 	 */
2968 	if (stream->ctx) {
2969 		ret = gen12_configure_oar_context(stream, active);
2970 		if (ret)
2971 			return ret;
2972 	}
2973 
2974 	return emit_oa_config(stream,
2975 			      stream->oa_config, oa_context(stream),
2976 			      active);
2977 }
2978 
gen8_disable_metric_set(struct i915_perf_stream * stream)2979 static void gen8_disable_metric_set(struct i915_perf_stream *stream)
2980 {
2981 	struct intel_uncore *uncore = stream->uncore;
2982 
2983 	/* Reset all contexts' slices/subslices configurations. */
2984 	lrc_configure_all_contexts(stream, NULL, NULL);
2985 
2986 	intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2987 }
2988 
gen11_disable_metric_set(struct i915_perf_stream * stream)2989 static void gen11_disable_metric_set(struct i915_perf_stream *stream)
2990 {
2991 	struct intel_uncore *uncore = stream->uncore;
2992 
2993 	/* Reset all contexts' slices/subslices configurations. */
2994 	lrc_configure_all_contexts(stream, NULL, NULL);
2995 
2996 	/* Make sure we disable noa to save power. */
2997 	intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
2998 }
2999 
gen12_disable_metric_set(struct i915_perf_stream * stream)3000 static void gen12_disable_metric_set(struct i915_perf_stream *stream)
3001 {
3002 	struct intel_uncore *uncore = stream->uncore;
3003 	struct drm_i915_private *i915 = stream->perf->i915;
3004 	u32 sqcnt1;
3005 
3006 	/*
3007 	 * Wa_1508761755:xehpsdv, dg2
3008 	 * Enable thread stall DOP gating and EU DOP gating.
3009 	 */
3010 	if (IS_XEHPSDV(i915) || IS_DG2(i915)) {
3011 		intel_gt_mcr_multicast_write(uncore->gt, GEN8_ROW_CHICKEN,
3012 					     _MASKED_BIT_DISABLE(STALL_DOP_GATING_DISABLE));
3013 		intel_uncore_write(uncore, GEN7_ROW_CHICKEN2,
3014 				   _MASKED_BIT_DISABLE(GEN12_DISABLE_DOP_GATING));
3015 	}
3016 
3017 	/* Reset all contexts' slices/subslices configurations. */
3018 	gen12_configure_all_contexts(stream, NULL, NULL);
3019 
3020 	/* disable the context save/restore or OAR counters */
3021 	if (stream->ctx)
3022 		gen12_configure_oar_context(stream, NULL);
3023 
3024 	/* Make sure we disable noa to save power. */
3025 	intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
3026 
3027 	sqcnt1 = GEN12_SQCNT1_PMON_ENABLE |
3028 		 (HAS_OA_BPC_REPORTING(i915) ? GEN12_SQCNT1_OABPC : 0);
3029 
3030 	/* Reset PMON Enable to save power. */
3031 	intel_uncore_rmw(uncore, GEN12_SQCNT1, sqcnt1, 0);
3032 }
3033 
gen7_oa_enable(struct i915_perf_stream * stream)3034 static void gen7_oa_enable(struct i915_perf_stream *stream)
3035 {
3036 	struct intel_uncore *uncore = stream->uncore;
3037 	struct i915_gem_context *ctx = stream->ctx;
3038 	u32 ctx_id = stream->specific_ctx_id;
3039 	bool periodic = stream->periodic;
3040 	u32 period_exponent = stream->period_exponent;
3041 	u32 report_format = stream->oa_buffer.format->format;
3042 
3043 	/*
3044 	 * Reset buf pointers so we don't forward reports from before now.
3045 	 *
3046 	 * Think carefully if considering trying to avoid this, since it
3047 	 * also ensures status flags and the buffer itself are cleared
3048 	 * in error paths, and we have checks for invalid reports based
3049 	 * on the assumption that certain fields are written to zeroed
3050 	 * memory which this helps maintains.
3051 	 */
3052 	gen7_init_oa_buffer(stream);
3053 
3054 	intel_uncore_write(uncore, GEN7_OACONTROL,
3055 			   (ctx_id & GEN7_OACONTROL_CTX_MASK) |
3056 			   (period_exponent <<
3057 			    GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
3058 			   (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
3059 			   (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
3060 			   (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
3061 			   GEN7_OACONTROL_ENABLE);
3062 }
3063 
gen8_oa_enable(struct i915_perf_stream * stream)3064 static void gen8_oa_enable(struct i915_perf_stream *stream)
3065 {
3066 	struct intel_uncore *uncore = stream->uncore;
3067 	u32 report_format = stream->oa_buffer.format->format;
3068 
3069 	/*
3070 	 * Reset buf pointers so we don't forward reports from before now.
3071 	 *
3072 	 * Think carefully if considering trying to avoid this, since it
3073 	 * also ensures status flags and the buffer itself are cleared
3074 	 * in error paths, and we have checks for invalid reports based
3075 	 * on the assumption that certain fields are written to zeroed
3076 	 * memory which this helps maintains.
3077 	 */
3078 	gen8_init_oa_buffer(stream);
3079 
3080 	/*
3081 	 * Note: we don't rely on the hardware to perform single context
3082 	 * filtering and instead filter on the cpu based on the context-id
3083 	 * field of reports
3084 	 */
3085 	intel_uncore_write(uncore, GEN8_OACONTROL,
3086 			   (report_format << GEN8_OA_REPORT_FORMAT_SHIFT) |
3087 			   GEN8_OA_COUNTER_ENABLE);
3088 }
3089 
gen12_oa_enable(struct i915_perf_stream * stream)3090 static void gen12_oa_enable(struct i915_perf_stream *stream)
3091 {
3092 	const struct i915_perf_regs *regs;
3093 	u32 val;
3094 
3095 	/*
3096 	 * If we don't want OA reports from the OA buffer, then we don't even
3097 	 * need to program the OAG unit.
3098 	 */
3099 	if (!(stream->sample_flags & SAMPLE_OA_REPORT))
3100 		return;
3101 
3102 	gen12_init_oa_buffer(stream);
3103 
3104 	regs = __oa_regs(stream);
3105 	val = (stream->oa_buffer.format->format << regs->oa_ctrl_counter_format_shift) |
3106 	      GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE;
3107 
3108 	intel_uncore_write(stream->uncore, regs->oa_ctrl, val);
3109 }
3110 
3111 /**
3112  * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
3113  * @stream: An i915 perf stream opened for OA metrics
3114  *
3115  * [Re]enables hardware periodic sampling according to the period configured
3116  * when opening the stream. This also starts a hrtimer that will periodically
3117  * check for data in the circular OA buffer for notifying userspace (e.g.
3118  * during a read() or poll()).
3119  */
i915_oa_stream_enable(struct i915_perf_stream * stream)3120 static void i915_oa_stream_enable(struct i915_perf_stream *stream)
3121 {
3122 	stream->pollin = false;
3123 
3124 	stream->perf->ops.oa_enable(stream);
3125 
3126 	if (stream->sample_flags & SAMPLE_OA_REPORT)
3127 		hrtimer_start(&stream->poll_check_timer,
3128 			      ns_to_ktime(stream->poll_oa_period),
3129 			      HRTIMER_MODE_REL_PINNED);
3130 }
3131 
gen7_oa_disable(struct i915_perf_stream * stream)3132 static void gen7_oa_disable(struct i915_perf_stream *stream)
3133 {
3134 	struct intel_uncore *uncore = stream->uncore;
3135 
3136 	intel_uncore_write(uncore, GEN7_OACONTROL, 0);
3137 	if (intel_wait_for_register(uncore,
3138 				    GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
3139 				    50))
3140 		drm_err(&stream->perf->i915->drm,
3141 			"wait for OA to be disabled timed out\n");
3142 }
3143 
gen8_oa_disable(struct i915_perf_stream * stream)3144 static void gen8_oa_disable(struct i915_perf_stream *stream)
3145 {
3146 	struct intel_uncore *uncore = stream->uncore;
3147 
3148 	intel_uncore_write(uncore, GEN8_OACONTROL, 0);
3149 	if (intel_wait_for_register(uncore,
3150 				    GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
3151 				    50))
3152 		drm_err(&stream->perf->i915->drm,
3153 			"wait for OA to be disabled timed out\n");
3154 }
3155 
gen12_oa_disable(struct i915_perf_stream * stream)3156 static void gen12_oa_disable(struct i915_perf_stream *stream)
3157 {
3158 	struct intel_uncore *uncore = stream->uncore;
3159 
3160 	intel_uncore_write(uncore, __oa_regs(stream)->oa_ctrl, 0);
3161 	if (intel_wait_for_register(uncore,
3162 				    __oa_regs(stream)->oa_ctrl,
3163 				    GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE, 0,
3164 				    50))
3165 		drm_err(&stream->perf->i915->drm,
3166 			"wait for OA to be disabled timed out\n");
3167 
3168 	intel_uncore_write(uncore, GEN12_OA_TLB_INV_CR, 1);
3169 	if (intel_wait_for_register(uncore,
3170 				    GEN12_OA_TLB_INV_CR,
3171 				    1, 0,
3172 				    50))
3173 		drm_err(&stream->perf->i915->drm,
3174 			"wait for OA tlb invalidate timed out\n");
3175 }
3176 
3177 /**
3178  * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
3179  * @stream: An i915 perf stream opened for OA metrics
3180  *
3181  * Stops the OA unit from periodically writing counter reports into the
3182  * circular OA buffer. This also stops the hrtimer that periodically checks for
3183  * data in the circular OA buffer, for notifying userspace.
3184  */
i915_oa_stream_disable(struct i915_perf_stream * stream)3185 static void i915_oa_stream_disable(struct i915_perf_stream *stream)
3186 {
3187 	stream->perf->ops.oa_disable(stream);
3188 
3189 	if (stream->sample_flags & SAMPLE_OA_REPORT)
3190 		hrtimer_cancel(&stream->poll_check_timer);
3191 }
3192 
3193 static const struct i915_perf_stream_ops i915_oa_stream_ops = {
3194 	.destroy = i915_oa_stream_destroy,
3195 	.enable = i915_oa_stream_enable,
3196 	.disable = i915_oa_stream_disable,
3197 	.wait_unlocked = i915_oa_wait_unlocked,
3198 	.poll_wait = i915_oa_poll_wait,
3199 	.read = i915_oa_read,
3200 };
3201 
i915_perf_stream_enable_sync(struct i915_perf_stream * stream)3202 static int i915_perf_stream_enable_sync(struct i915_perf_stream *stream)
3203 {
3204 	struct i915_active *active;
3205 	int err;
3206 
3207 	active = i915_active_create();
3208 	if (!active)
3209 		return -ENOMEM;
3210 
3211 	err = stream->perf->ops.enable_metric_set(stream, active);
3212 	if (err == 0)
3213 		__i915_active_wait(active, TASK_UNINTERRUPTIBLE);
3214 
3215 	i915_active_put(active);
3216 	return err;
3217 }
3218 
3219 static void
get_default_sseu_config(struct intel_sseu * out_sseu,struct intel_engine_cs * engine)3220 get_default_sseu_config(struct intel_sseu *out_sseu,
3221 			struct intel_engine_cs *engine)
3222 {
3223 	const struct sseu_dev_info *devinfo_sseu = &engine->gt->info.sseu;
3224 
3225 	*out_sseu = intel_sseu_from_device_info(devinfo_sseu);
3226 
3227 	if (GRAPHICS_VER(engine->i915) == 11) {
3228 		/*
3229 		 * We only need subslice count so it doesn't matter which ones
3230 		 * we select - just turn off low bits in the amount of half of
3231 		 * all available subslices per slice.
3232 		 */
3233 		out_sseu->subslice_mask =
3234 			~(~0 << (hweight8(out_sseu->subslice_mask) / 2));
3235 		out_sseu->slice_mask = 0x1;
3236 	}
3237 }
3238 
3239 static int
get_sseu_config(struct intel_sseu * out_sseu,struct intel_engine_cs * engine,const struct drm_i915_gem_context_param_sseu * drm_sseu)3240 get_sseu_config(struct intel_sseu *out_sseu,
3241 		struct intel_engine_cs *engine,
3242 		const struct drm_i915_gem_context_param_sseu *drm_sseu)
3243 {
3244 	if (drm_sseu->engine.engine_class != engine->uabi_class ||
3245 	    drm_sseu->engine.engine_instance != engine->uabi_instance)
3246 		return -EINVAL;
3247 
3248 	return i915_gem_user_to_context_sseu(engine->gt, drm_sseu, out_sseu);
3249 }
3250 
3251 /*
3252  * OA timestamp frequency = CS timestamp frequency in most platforms. On some
3253  * platforms OA unit ignores the CTC_SHIFT and the 2 timestamps differ. In such
3254  * cases, return the adjusted CS timestamp frequency to the user.
3255  */
i915_perf_oa_timestamp_frequency(struct drm_i915_private * i915)3256 u32 i915_perf_oa_timestamp_frequency(struct drm_i915_private *i915)
3257 {
3258 	/*
3259 	 * Wa_18013179988:dg2
3260 	 * Wa_14015846243:mtl
3261 	 */
3262 	if (IS_DG2(i915) || IS_METEORLAKE(i915)) {
3263 		intel_wakeref_t wakeref;
3264 		u32 reg, shift;
3265 
3266 		with_intel_runtime_pm(to_gt(i915)->uncore->rpm, wakeref)
3267 			reg = intel_uncore_read(to_gt(i915)->uncore, RPM_CONFIG0);
3268 
3269 		shift = REG_FIELD_GET(GEN10_RPM_CONFIG0_CTC_SHIFT_PARAMETER_MASK,
3270 				      reg);
3271 
3272 		return to_gt(i915)->clock_frequency << (3 - shift);
3273 	}
3274 
3275 	return to_gt(i915)->clock_frequency;
3276 }
3277 
3278 /**
3279  * i915_oa_stream_init - validate combined props for OA stream and init
3280  * @stream: An i915 perf stream
3281  * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
3282  * @props: The property state that configures stream (individually validated)
3283  *
3284  * While read_properties_unlocked() validates properties in isolation it
3285  * doesn't ensure that the combination necessarily makes sense.
3286  *
3287  * At this point it has been determined that userspace wants a stream of
3288  * OA metrics, but still we need to further validate the combined
3289  * properties are OK.
3290  *
3291  * If the configuration makes sense then we can allocate memory for
3292  * a circular OA buffer and apply the requested metric set configuration.
3293  *
3294  * Returns: zero on success or a negative error code.
3295  */
i915_oa_stream_init(struct i915_perf_stream * stream,struct drm_i915_perf_open_param * param,struct perf_open_properties * props)3296 static int i915_oa_stream_init(struct i915_perf_stream *stream,
3297 			       struct drm_i915_perf_open_param *param,
3298 			       struct perf_open_properties *props)
3299 {
3300 	struct drm_i915_private *i915 = stream->perf->i915;
3301 	struct i915_perf *perf = stream->perf;
3302 	struct i915_perf_group *g;
3303 	struct intel_gt *gt;
3304 	int ret;
3305 
3306 	if (!props->engine) {
3307 		drm_dbg(&stream->perf->i915->drm,
3308 			"OA engine not specified\n");
3309 		return -EINVAL;
3310 	}
3311 	gt = props->engine->gt;
3312 	g = props->engine->oa_group;
3313 
3314 	/*
3315 	 * If the sysfs metrics/ directory wasn't registered for some
3316 	 * reason then don't let userspace try their luck with config
3317 	 * IDs
3318 	 */
3319 	if (!perf->metrics_kobj) {
3320 		drm_dbg(&stream->perf->i915->drm,
3321 			"OA metrics weren't advertised via sysfs\n");
3322 		return -EINVAL;
3323 	}
3324 
3325 	if (!(props->sample_flags & SAMPLE_OA_REPORT) &&
3326 	    (GRAPHICS_VER(perf->i915) < 12 || !stream->ctx)) {
3327 		drm_dbg(&stream->perf->i915->drm,
3328 			"Only OA report sampling supported\n");
3329 		return -EINVAL;
3330 	}
3331 
3332 	if (!perf->ops.enable_metric_set) {
3333 		drm_dbg(&stream->perf->i915->drm,
3334 			"OA unit not supported\n");
3335 		return -ENODEV;
3336 	}
3337 
3338 	/*
3339 	 * To avoid the complexity of having to accurately filter
3340 	 * counter reports and marshal to the appropriate client
3341 	 * we currently only allow exclusive access
3342 	 */
3343 	if (g->exclusive_stream) {
3344 		drm_dbg(&stream->perf->i915->drm,
3345 			"OA unit already in use\n");
3346 		return -EBUSY;
3347 	}
3348 
3349 	if (!props->oa_format) {
3350 		drm_dbg(&stream->perf->i915->drm,
3351 			"OA report format not specified\n");
3352 		return -EINVAL;
3353 	}
3354 
3355 	stream->engine = props->engine;
3356 	stream->uncore = stream->engine->gt->uncore;
3357 
3358 	stream->sample_size = sizeof(struct drm_i915_perf_record_header);
3359 
3360 	stream->oa_buffer.format = &perf->oa_formats[props->oa_format];
3361 	if (drm_WARN_ON(&i915->drm, stream->oa_buffer.format->size == 0))
3362 		return -EINVAL;
3363 
3364 	stream->sample_flags = props->sample_flags;
3365 	stream->sample_size += stream->oa_buffer.format->size;
3366 
3367 	stream->hold_preemption = props->hold_preemption;
3368 
3369 	stream->periodic = props->oa_periodic;
3370 	if (stream->periodic)
3371 		stream->period_exponent = props->oa_period_exponent;
3372 
3373 	if (stream->ctx) {
3374 		ret = oa_get_render_ctx_id(stream);
3375 		if (ret) {
3376 			drm_dbg(&stream->perf->i915->drm,
3377 				"Invalid context id to filter with\n");
3378 			return ret;
3379 		}
3380 	}
3381 
3382 	ret = alloc_noa_wait(stream);
3383 	if (ret) {
3384 		drm_dbg(&stream->perf->i915->drm,
3385 			"Unable to allocate NOA wait batch buffer\n");
3386 		goto err_noa_wait_alloc;
3387 	}
3388 
3389 	stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
3390 	if (!stream->oa_config) {
3391 		drm_dbg(&stream->perf->i915->drm,
3392 			"Invalid OA config id=%i\n", props->metrics_set);
3393 		ret = -EINVAL;
3394 		goto err_config;
3395 	}
3396 
3397 	/* PRM - observability performance counters:
3398 	 *
3399 	 *   OACONTROL, performance counter enable, note:
3400 	 *
3401 	 *   "When this bit is set, in order to have coherent counts,
3402 	 *   RC6 power state and trunk clock gating must be disabled.
3403 	 *   This can be achieved by programming MMIO registers as
3404 	 *   0xA094=0 and 0xA090[31]=1"
3405 	 *
3406 	 *   In our case we are expecting that taking pm + FORCEWAKE
3407 	 *   references will effectively disable RC6.
3408 	 */
3409 	intel_engine_pm_get(stream->engine);
3410 	intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
3411 
3412 	/*
3413 	 * Wa_16011777198:dg2: GuC resets render as part of the Wa. This causes
3414 	 * OA to lose the configuration state. Prevent this by overriding GUCRC
3415 	 * mode.
3416 	 */
3417 	if (intel_uc_uses_guc_rc(&gt->uc) &&
3418 	    (IS_DG2_GRAPHICS_STEP(gt->i915, G10, STEP_A0, STEP_C0) ||
3419 	     IS_DG2_GRAPHICS_STEP(gt->i915, G11, STEP_A0, STEP_B0))) {
3420 		ret = intel_guc_slpc_override_gucrc_mode(&gt->uc.guc.slpc,
3421 							 SLPC_GUCRC_MODE_GUCRC_NO_RC6);
3422 		if (ret) {
3423 			drm_dbg(&stream->perf->i915->drm,
3424 				"Unable to override gucrc mode\n");
3425 			goto err_gucrc;
3426 		}
3427 
3428 		stream->override_gucrc = true;
3429 	}
3430 
3431 	ret = alloc_oa_buffer(stream);
3432 	if (ret)
3433 		goto err_oa_buf_alloc;
3434 
3435 	stream->ops = &i915_oa_stream_ops;
3436 
3437 	stream->engine->gt->perf.sseu = props->sseu;
3438 	WRITE_ONCE(g->exclusive_stream, stream);
3439 
3440 	ret = i915_perf_stream_enable_sync(stream);
3441 	if (ret) {
3442 		drm_dbg(&stream->perf->i915->drm,
3443 			"Unable to enable metric set\n");
3444 		goto err_enable;
3445 	}
3446 
3447 	drm_dbg(&stream->perf->i915->drm,
3448 		"opening stream oa config uuid=%s\n",
3449 		  stream->oa_config->uuid);
3450 
3451 	hrtimer_init(&stream->poll_check_timer,
3452 		     CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3453 	stream->poll_check_timer.function = oa_poll_check_timer_cb;
3454 	init_waitqueue_head(&stream->poll_wq);
3455 	spin_lock_init(&stream->oa_buffer.ptr_lock);
3456 	mutex_init(&stream->lock);
3457 
3458 	return 0;
3459 
3460 err_enable:
3461 	WRITE_ONCE(g->exclusive_stream, NULL);
3462 	perf->ops.disable_metric_set(stream);
3463 
3464 	free_oa_buffer(stream);
3465 
3466 err_oa_buf_alloc:
3467 	if (stream->override_gucrc)
3468 		intel_guc_slpc_unset_gucrc_mode(&gt->uc.guc.slpc);
3469 
3470 err_gucrc:
3471 	intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
3472 	intel_engine_pm_put(stream->engine);
3473 
3474 	free_oa_configs(stream);
3475 
3476 err_config:
3477 	free_noa_wait(stream);
3478 
3479 err_noa_wait_alloc:
3480 	if (stream->ctx)
3481 		oa_put_render_ctx_id(stream);
3482 
3483 	return ret;
3484 }
3485 
i915_oa_init_reg_state(const struct intel_context * ce,const struct intel_engine_cs * engine)3486 void i915_oa_init_reg_state(const struct intel_context *ce,
3487 			    const struct intel_engine_cs *engine)
3488 {
3489 	struct i915_perf_stream *stream;
3490 
3491 	if (engine->class != RENDER_CLASS)
3492 		return;
3493 
3494 	/* perf.exclusive_stream serialised by lrc_configure_all_contexts() */
3495 	stream = READ_ONCE(engine->oa_group->exclusive_stream);
3496 	if (stream && GRAPHICS_VER(stream->perf->i915) < 12)
3497 		gen8_update_reg_state_unlocked(ce, stream);
3498 }
3499 
3500 /**
3501  * i915_perf_read - handles read() FOP for i915 perf stream FDs
3502  * @file: An i915 perf stream file
3503  * @buf: destination buffer given by userspace
3504  * @count: the number of bytes userspace wants to read
3505  * @ppos: (inout) file seek position (unused)
3506  *
3507  * The entry point for handling a read() on a stream file descriptor from
3508  * userspace. Most of the work is left to the i915_perf_read_locked() and
3509  * &i915_perf_stream_ops->read but to save having stream implementations (of
3510  * which we might have multiple later) we handle blocking read here.
3511  *
3512  * We can also consistently treat trying to read from a disabled stream
3513  * as an IO error so implementations can assume the stream is enabled
3514  * while reading.
3515  *
3516  * Returns: The number of bytes copied or a negative error code on failure.
3517  */
i915_perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)3518 static ssize_t i915_perf_read(struct file *file,
3519 			      char __user *buf,
3520 			      size_t count,
3521 			      loff_t *ppos)
3522 {
3523 	struct i915_perf_stream *stream = file->private_data;
3524 	size_t offset = 0;
3525 	int ret;
3526 
3527 	/* To ensure it's handled consistently we simply treat all reads of a
3528 	 * disabled stream as an error. In particular it might otherwise lead
3529 	 * to a deadlock for blocking file descriptors...
3530 	 */
3531 	if (!stream->enabled || !(stream->sample_flags & SAMPLE_OA_REPORT))
3532 		return -EIO;
3533 
3534 	if (!(file->f_flags & O_NONBLOCK)) {
3535 		/* There's the small chance of false positives from
3536 		 * stream->ops->wait_unlocked.
3537 		 *
3538 		 * E.g. with single context filtering since we only wait until
3539 		 * oabuffer has >= 1 report we don't immediately know whether
3540 		 * any reports really belong to the current context
3541 		 */
3542 		do {
3543 			ret = stream->ops->wait_unlocked(stream);
3544 			if (ret)
3545 				return ret;
3546 
3547 			mutex_lock(&stream->lock);
3548 			ret = stream->ops->read(stream, buf, count, &offset);
3549 			mutex_unlock(&stream->lock);
3550 		} while (!offset && !ret);
3551 	} else {
3552 		mutex_lock(&stream->lock);
3553 		ret = stream->ops->read(stream, buf, count, &offset);
3554 		mutex_unlock(&stream->lock);
3555 	}
3556 
3557 	/* We allow the poll checking to sometimes report false positive EPOLLIN
3558 	 * events where we might actually report EAGAIN on read() if there's
3559 	 * not really any data available. In this situation though we don't
3560 	 * want to enter a busy loop between poll() reporting a EPOLLIN event
3561 	 * and read() returning -EAGAIN. Clearing the oa.pollin state here
3562 	 * effectively ensures we back off until the next hrtimer callback
3563 	 * before reporting another EPOLLIN event.
3564 	 * The exception to this is if ops->read() returned -ENOSPC which means
3565 	 * that more OA data is available than could fit in the user provided
3566 	 * buffer. In this case we want the next poll() call to not block.
3567 	 */
3568 	if (ret != -ENOSPC)
3569 		stream->pollin = false;
3570 
3571 	/* Possible values for ret are 0, -EFAULT, -ENOSPC, -EIO, ... */
3572 	return offset ?: (ret ?: -EAGAIN);
3573 }
3574 
oa_poll_check_timer_cb(struct hrtimer * hrtimer)3575 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
3576 {
3577 	struct i915_perf_stream *stream =
3578 		container_of(hrtimer, typeof(*stream), poll_check_timer);
3579 
3580 	if (oa_buffer_check_unlocked(stream)) {
3581 		stream->pollin = true;
3582 		wake_up(&stream->poll_wq);
3583 	}
3584 
3585 	hrtimer_forward_now(hrtimer,
3586 			    ns_to_ktime(stream->poll_oa_period));
3587 
3588 	return HRTIMER_RESTART;
3589 }
3590 
3591 /**
3592  * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
3593  * @stream: An i915 perf stream
3594  * @file: An i915 perf stream file
3595  * @wait: poll() state table
3596  *
3597  * For handling userspace polling on an i915 perf stream, this calls through to
3598  * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
3599  * will be woken for new stream data.
3600  *
3601  * Returns: any poll events that are ready without sleeping
3602  */
i915_perf_poll_locked(struct i915_perf_stream * stream,struct file * file,poll_table * wait)3603 static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
3604 				      struct file *file,
3605 				      poll_table *wait)
3606 {
3607 	__poll_t events = 0;
3608 
3609 	stream->ops->poll_wait(stream, file, wait);
3610 
3611 	/* Note: we don't explicitly check whether there's something to read
3612 	 * here since this path may be very hot depending on what else
3613 	 * userspace is polling, or on the timeout in use. We rely solely on
3614 	 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
3615 	 * samples to read.
3616 	 */
3617 	if (stream->pollin)
3618 		events |= EPOLLIN;
3619 
3620 	return events;
3621 }
3622 
3623 /**
3624  * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
3625  * @file: An i915 perf stream file
3626  * @wait: poll() state table
3627  *
3628  * For handling userspace polling on an i915 perf stream, this ensures
3629  * poll_wait() gets called with a wait queue that will be woken for new stream
3630  * data.
3631  *
3632  * Note: Implementation deferred to i915_perf_poll_locked()
3633  *
3634  * Returns: any poll events that are ready without sleeping
3635  */
i915_perf_poll(struct file * file,poll_table * wait)3636 static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
3637 {
3638 	struct i915_perf_stream *stream = file->private_data;
3639 	__poll_t ret;
3640 
3641 	mutex_lock(&stream->lock);
3642 	ret = i915_perf_poll_locked(stream, file, wait);
3643 	mutex_unlock(&stream->lock);
3644 
3645 	return ret;
3646 }
3647 
3648 /**
3649  * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
3650  * @stream: A disabled i915 perf stream
3651  *
3652  * [Re]enables the associated capture of data for this stream.
3653  *
3654  * If a stream was previously enabled then there's currently no intention
3655  * to provide userspace any guarantee about the preservation of previously
3656  * buffered data.
3657  */
i915_perf_enable_locked(struct i915_perf_stream * stream)3658 static void i915_perf_enable_locked(struct i915_perf_stream *stream)
3659 {
3660 	if (stream->enabled)
3661 		return;
3662 
3663 	/* Allow stream->ops->enable() to refer to this */
3664 	stream->enabled = true;
3665 
3666 	if (stream->ops->enable)
3667 		stream->ops->enable(stream);
3668 
3669 	if (stream->hold_preemption)
3670 		intel_context_set_nopreempt(stream->pinned_ctx);
3671 }
3672 
3673 /**
3674  * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
3675  * @stream: An enabled i915 perf stream
3676  *
3677  * Disables the associated capture of data for this stream.
3678  *
3679  * The intention is that disabling an re-enabling a stream will ideally be
3680  * cheaper than destroying and re-opening a stream with the same configuration,
3681  * though there are no formal guarantees about what state or buffered data
3682  * must be retained between disabling and re-enabling a stream.
3683  *
3684  * Note: while a stream is disabled it's considered an error for userspace
3685  * to attempt to read from the stream (-EIO).
3686  */
i915_perf_disable_locked(struct i915_perf_stream * stream)3687 static void i915_perf_disable_locked(struct i915_perf_stream *stream)
3688 {
3689 	if (!stream->enabled)
3690 		return;
3691 
3692 	/* Allow stream->ops->disable() to refer to this */
3693 	stream->enabled = false;
3694 
3695 	if (stream->hold_preemption)
3696 		intel_context_clear_nopreempt(stream->pinned_ctx);
3697 
3698 	if (stream->ops->disable)
3699 		stream->ops->disable(stream);
3700 }
3701 
i915_perf_config_locked(struct i915_perf_stream * stream,unsigned long metrics_set)3702 static long i915_perf_config_locked(struct i915_perf_stream *stream,
3703 				    unsigned long metrics_set)
3704 {
3705 	struct i915_oa_config *config;
3706 	long ret = stream->oa_config->id;
3707 
3708 	config = i915_perf_get_oa_config(stream->perf, metrics_set);
3709 	if (!config)
3710 		return -EINVAL;
3711 
3712 	if (config != stream->oa_config) {
3713 		int err;
3714 
3715 		/*
3716 		 * If OA is bound to a specific context, emit the
3717 		 * reconfiguration inline from that context. The update
3718 		 * will then be ordered with respect to submission on that
3719 		 * context.
3720 		 *
3721 		 * When set globally, we use a low priority kernel context,
3722 		 * so it will effectively take effect when idle.
3723 		 */
3724 		err = emit_oa_config(stream, config, oa_context(stream), NULL);
3725 		if (!err)
3726 			config = xchg(&stream->oa_config, config);
3727 		else
3728 			ret = err;
3729 	}
3730 
3731 	i915_oa_config_put(config);
3732 
3733 	return ret;
3734 }
3735 
3736 /**
3737  * i915_perf_ioctl_locked - support ioctl() usage with i915 perf stream FDs
3738  * @stream: An i915 perf stream
3739  * @cmd: the ioctl request
3740  * @arg: the ioctl data
3741  *
3742  * Returns: zero on success or a negative error code. Returns -EINVAL for
3743  * an unknown ioctl request.
3744  */
i915_perf_ioctl_locked(struct i915_perf_stream * stream,unsigned int cmd,unsigned long arg)3745 static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
3746 				   unsigned int cmd,
3747 				   unsigned long arg)
3748 {
3749 	switch (cmd) {
3750 	case I915_PERF_IOCTL_ENABLE:
3751 		i915_perf_enable_locked(stream);
3752 		return 0;
3753 	case I915_PERF_IOCTL_DISABLE:
3754 		i915_perf_disable_locked(stream);
3755 		return 0;
3756 	case I915_PERF_IOCTL_CONFIG:
3757 		return i915_perf_config_locked(stream, arg);
3758 	}
3759 
3760 	return -EINVAL;
3761 }
3762 
3763 /**
3764  * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
3765  * @file: An i915 perf stream file
3766  * @cmd: the ioctl request
3767  * @arg: the ioctl data
3768  *
3769  * Implementation deferred to i915_perf_ioctl_locked().
3770  *
3771  * Returns: zero on success or a negative error code. Returns -EINVAL for
3772  * an unknown ioctl request.
3773  */
i915_perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)3774 static long i915_perf_ioctl(struct file *file,
3775 			    unsigned int cmd,
3776 			    unsigned long arg)
3777 {
3778 	struct i915_perf_stream *stream = file->private_data;
3779 	long ret;
3780 
3781 	mutex_lock(&stream->lock);
3782 	ret = i915_perf_ioctl_locked(stream, cmd, arg);
3783 	mutex_unlock(&stream->lock);
3784 
3785 	return ret;
3786 }
3787 
3788 /**
3789  * i915_perf_destroy_locked - destroy an i915 perf stream
3790  * @stream: An i915 perf stream
3791  *
3792  * Frees all resources associated with the given i915 perf @stream, disabling
3793  * any associated data capture in the process.
3794  *
3795  * Note: The &gt->perf.lock mutex has been taken to serialize
3796  * with any non-file-operation driver hooks.
3797  */
i915_perf_destroy_locked(struct i915_perf_stream * stream)3798 static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
3799 {
3800 	if (stream->enabled)
3801 		i915_perf_disable_locked(stream);
3802 
3803 	if (stream->ops->destroy)
3804 		stream->ops->destroy(stream);
3805 
3806 	if (stream->ctx)
3807 		i915_gem_context_put(stream->ctx);
3808 
3809 	kfree(stream);
3810 }
3811 
3812 /**
3813  * i915_perf_release - handles userspace close() of a stream file
3814  * @inode: anonymous inode associated with file
3815  * @file: An i915 perf stream file
3816  *
3817  * Cleans up any resources associated with an open i915 perf stream file.
3818  *
3819  * NB: close() can't really fail from the userspace point of view.
3820  *
3821  * Returns: zero on success or a negative error code.
3822  */
i915_perf_release(struct inode * inode,struct file * file)3823 static int i915_perf_release(struct inode *inode, struct file *file)
3824 {
3825 	struct i915_perf_stream *stream = file->private_data;
3826 	struct i915_perf *perf = stream->perf;
3827 	struct intel_gt *gt = stream->engine->gt;
3828 
3829 	/*
3830 	 * Within this call, we know that the fd is being closed and we have no
3831 	 * other user of stream->lock. Use the perf lock to destroy the stream
3832 	 * here.
3833 	 */
3834 	mutex_lock(&gt->perf.lock);
3835 	i915_perf_destroy_locked(stream);
3836 	mutex_unlock(&gt->perf.lock);
3837 
3838 	/* Release the reference the perf stream kept on the driver. */
3839 	drm_dev_put(&perf->i915->drm);
3840 
3841 	return 0;
3842 }
3843 
3844 
3845 static const struct file_operations fops = {
3846 	.owner		= THIS_MODULE,
3847 	.llseek		= no_llseek,
3848 	.release	= i915_perf_release,
3849 	.poll		= i915_perf_poll,
3850 	.read		= i915_perf_read,
3851 	.unlocked_ioctl	= i915_perf_ioctl,
3852 	/* Our ioctl have no arguments, so it's safe to use the same function
3853 	 * to handle 32bits compatibility.
3854 	 */
3855 	.compat_ioctl   = i915_perf_ioctl,
3856 };
3857 
3858 
3859 /**
3860  * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
3861  * @perf: i915 perf instance
3862  * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
3863  * @props: individually validated u64 property value pairs
3864  * @file: drm file
3865  *
3866  * See i915_perf_ioctl_open() for interface details.
3867  *
3868  * Implements further stream config validation and stream initialization on
3869  * behalf of i915_perf_open_ioctl() with the &gt->perf.lock mutex
3870  * taken to serialize with any non-file-operation driver hooks.
3871  *
3872  * Note: at this point the @props have only been validated in isolation and
3873  * it's still necessary to validate that the combination of properties makes
3874  * sense.
3875  *
3876  * In the case where userspace is interested in OA unit metrics then further
3877  * config validation and stream initialization details will be handled by
3878  * i915_oa_stream_init(). The code here should only validate config state that
3879  * will be relevant to all stream types / backends.
3880  *
3881  * Returns: zero on success or a negative error code.
3882  */
3883 static int
i915_perf_open_ioctl_locked(struct i915_perf * perf,struct drm_i915_perf_open_param * param,struct perf_open_properties * props,struct drm_file * file)3884 i915_perf_open_ioctl_locked(struct i915_perf *perf,
3885 			    struct drm_i915_perf_open_param *param,
3886 			    struct perf_open_properties *props,
3887 			    struct drm_file *file)
3888 {
3889 	struct i915_gem_context *specific_ctx = NULL;
3890 	struct i915_perf_stream *stream = NULL;
3891 	unsigned long f_flags = 0;
3892 	bool privileged_op = true;
3893 	int stream_fd;
3894 	int ret;
3895 
3896 	if (props->single_context) {
3897 		u32 ctx_handle = props->ctx_handle;
3898 		struct drm_i915_file_private *file_priv = file->driver_priv;
3899 
3900 		specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
3901 		if (IS_ERR(specific_ctx)) {
3902 			drm_dbg(&perf->i915->drm,
3903 				"Failed to look up context with ID %u for opening perf stream\n",
3904 				  ctx_handle);
3905 			ret = PTR_ERR(specific_ctx);
3906 			goto err;
3907 		}
3908 	}
3909 
3910 	/*
3911 	 * On Haswell the OA unit supports clock gating off for a specific
3912 	 * context and in this mode there's no visibility of metrics for the
3913 	 * rest of the system, which we consider acceptable for a
3914 	 * non-privileged client.
3915 	 *
3916 	 * For Gen8->11 the OA unit no longer supports clock gating off for a
3917 	 * specific context and the kernel can't securely stop the counters
3918 	 * from updating as system-wide / global values. Even though we can
3919 	 * filter reports based on the included context ID we can't block
3920 	 * clients from seeing the raw / global counter values via
3921 	 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
3922 	 * enable the OA unit by default.
3923 	 *
3924 	 * For Gen12+ we gain a new OAR unit that only monitors the RCS on a
3925 	 * per context basis. So we can relax requirements there if the user
3926 	 * doesn't request global stream access (i.e. query based sampling
3927 	 * using MI_RECORD_PERF_COUNT.
3928 	 */
3929 	if (IS_HASWELL(perf->i915) && specific_ctx)
3930 		privileged_op = false;
3931 	else if (GRAPHICS_VER(perf->i915) == 12 && specific_ctx &&
3932 		 (props->sample_flags & SAMPLE_OA_REPORT) == 0)
3933 		privileged_op = false;
3934 
3935 	if (props->hold_preemption) {
3936 		if (!props->single_context) {
3937 			drm_dbg(&perf->i915->drm,
3938 				"preemption disable with no context\n");
3939 			ret = -EINVAL;
3940 			goto err;
3941 		}
3942 		privileged_op = true;
3943 	}
3944 
3945 	/*
3946 	 * Asking for SSEU configuration is a priviliged operation.
3947 	 */
3948 	if (props->has_sseu)
3949 		privileged_op = true;
3950 	else
3951 		get_default_sseu_config(&props->sseu, props->engine);
3952 
3953 	/* Similar to perf's kernel.perf_paranoid_cpu sysctl option
3954 	 * we check a dev.i915.perf_stream_paranoid sysctl option
3955 	 * to determine if it's ok to access system wide OA counters
3956 	 * without CAP_PERFMON or CAP_SYS_ADMIN privileges.
3957 	 */
3958 	if (privileged_op &&
3959 	    i915_perf_stream_paranoid && !perfmon_capable()) {
3960 		drm_dbg(&perf->i915->drm,
3961 			"Insufficient privileges to open i915 perf stream\n");
3962 		ret = -EACCES;
3963 		goto err_ctx;
3964 	}
3965 
3966 	stream = kzalloc(sizeof(*stream), GFP_KERNEL);
3967 	if (!stream) {
3968 		ret = -ENOMEM;
3969 		goto err_ctx;
3970 	}
3971 
3972 	stream->perf = perf;
3973 	stream->ctx = specific_ctx;
3974 	stream->poll_oa_period = props->poll_oa_period;
3975 
3976 	ret = i915_oa_stream_init(stream, param, props);
3977 	if (ret)
3978 		goto err_alloc;
3979 
3980 	/* we avoid simply assigning stream->sample_flags = props->sample_flags
3981 	 * to have _stream_init check the combination of sample flags more
3982 	 * thoroughly, but still this is the expected result at this point.
3983 	 */
3984 	if (WARN_ON(stream->sample_flags != props->sample_flags)) {
3985 		ret = -ENODEV;
3986 		goto err_flags;
3987 	}
3988 
3989 	if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
3990 		f_flags |= O_CLOEXEC;
3991 	if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
3992 		f_flags |= O_NONBLOCK;
3993 
3994 	stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
3995 	if (stream_fd < 0) {
3996 		ret = stream_fd;
3997 		goto err_flags;
3998 	}
3999 
4000 	if (!(param->flags & I915_PERF_FLAG_DISABLED))
4001 		i915_perf_enable_locked(stream);
4002 
4003 	/* Take a reference on the driver that will be kept with stream_fd
4004 	 * until its release.
4005 	 */
4006 	drm_dev_get(&perf->i915->drm);
4007 
4008 	return stream_fd;
4009 
4010 err_flags:
4011 	if (stream->ops->destroy)
4012 		stream->ops->destroy(stream);
4013 err_alloc:
4014 	kfree(stream);
4015 err_ctx:
4016 	if (specific_ctx)
4017 		i915_gem_context_put(specific_ctx);
4018 err:
4019 	return ret;
4020 }
4021 
oa_exponent_to_ns(struct i915_perf * perf,int exponent)4022 static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
4023 {
4024 	u64 nom = (2ULL << exponent) * NSEC_PER_SEC;
4025 	u32 den = i915_perf_oa_timestamp_frequency(perf->i915);
4026 
4027 	return div_u64(nom + den - 1, den);
4028 }
4029 
4030 static __always_inline bool
oa_format_valid(struct i915_perf * perf,enum drm_i915_oa_format format)4031 oa_format_valid(struct i915_perf *perf, enum drm_i915_oa_format format)
4032 {
4033 	return test_bit(format, perf->format_mask);
4034 }
4035 
4036 static __always_inline void
oa_format_add(struct i915_perf * perf,enum drm_i915_oa_format format)4037 oa_format_add(struct i915_perf *perf, enum drm_i915_oa_format format)
4038 {
4039 	__set_bit(format, perf->format_mask);
4040 }
4041 
4042 /**
4043  * read_properties_unlocked - validate + copy userspace stream open properties
4044  * @perf: i915 perf instance
4045  * @uprops: The array of u64 key value pairs given by userspace
4046  * @n_props: The number of key value pairs expected in @uprops
4047  * @props: The stream configuration built up while validating properties
4048  *
4049  * Note this function only validates properties in isolation it doesn't
4050  * validate that the combination of properties makes sense or that all
4051  * properties necessary for a particular kind of stream have been set.
4052  *
4053  * Note that there currently aren't any ordering requirements for properties so
4054  * we shouldn't validate or assume anything about ordering here. This doesn't
4055  * rule out defining new properties with ordering requirements in the future.
4056  */
read_properties_unlocked(struct i915_perf * perf,u64 __user * uprops,u32 n_props,struct perf_open_properties * props)4057 static int read_properties_unlocked(struct i915_perf *perf,
4058 				    u64 __user *uprops,
4059 				    u32 n_props,
4060 				    struct perf_open_properties *props)
4061 {
4062 	struct drm_i915_gem_context_param_sseu user_sseu;
4063 	const struct i915_oa_format *f;
4064 	u64 __user *uprop = uprops;
4065 	bool config_instance = false;
4066 	bool config_class = false;
4067 	bool config_sseu = false;
4068 	u8 class, instance;
4069 	u32 i;
4070 	int ret;
4071 
4072 	memset(props, 0, sizeof(struct perf_open_properties));
4073 	props->poll_oa_period = DEFAULT_POLL_PERIOD_NS;
4074 
4075 	/* Considering that ID = 0 is reserved and assuming that we don't
4076 	 * (currently) expect any configurations to ever specify duplicate
4077 	 * values for a particular property ID then the last _PROP_MAX value is
4078 	 * one greater than the maximum number of properties we expect to get
4079 	 * from userspace.
4080 	 */
4081 	if (!n_props || n_props >= DRM_I915_PERF_PROP_MAX) {
4082 		drm_dbg(&perf->i915->drm,
4083 			"Invalid number of i915 perf properties given\n");
4084 		return -EINVAL;
4085 	}
4086 
4087 	/* Defaults when class:instance is not passed */
4088 	class = I915_ENGINE_CLASS_RENDER;
4089 	instance = 0;
4090 
4091 	for (i = 0; i < n_props; i++) {
4092 		u64 oa_period, oa_freq_hz;
4093 		u64 id, value;
4094 
4095 		ret = get_user(id, uprop);
4096 		if (ret)
4097 			return ret;
4098 
4099 		ret = get_user(value, uprop + 1);
4100 		if (ret)
4101 			return ret;
4102 
4103 		if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
4104 			drm_dbg(&perf->i915->drm,
4105 				"Unknown i915 perf property ID\n");
4106 			return -EINVAL;
4107 		}
4108 
4109 		switch ((enum drm_i915_perf_property_id)id) {
4110 		case DRM_I915_PERF_PROP_CTX_HANDLE:
4111 			props->single_context = 1;
4112 			props->ctx_handle = value;
4113 			break;
4114 		case DRM_I915_PERF_PROP_SAMPLE_OA:
4115 			if (value)
4116 				props->sample_flags |= SAMPLE_OA_REPORT;
4117 			break;
4118 		case DRM_I915_PERF_PROP_OA_METRICS_SET:
4119 			if (value == 0) {
4120 				drm_dbg(&perf->i915->drm,
4121 					"Unknown OA metric set ID\n");
4122 				return -EINVAL;
4123 			}
4124 			props->metrics_set = value;
4125 			break;
4126 		case DRM_I915_PERF_PROP_OA_FORMAT:
4127 			if (value == 0 || value >= I915_OA_FORMAT_MAX) {
4128 				drm_dbg(&perf->i915->drm,
4129 					"Out-of-range OA report format %llu\n",
4130 					  value);
4131 				return -EINVAL;
4132 			}
4133 			if (!oa_format_valid(perf, value)) {
4134 				drm_dbg(&perf->i915->drm,
4135 					"Unsupported OA report format %llu\n",
4136 					  value);
4137 				return -EINVAL;
4138 			}
4139 			props->oa_format = value;
4140 			break;
4141 		case DRM_I915_PERF_PROP_OA_EXPONENT:
4142 			if (value > OA_EXPONENT_MAX) {
4143 				drm_dbg(&perf->i915->drm,
4144 					"OA timer exponent too high (> %u)\n",
4145 					 OA_EXPONENT_MAX);
4146 				return -EINVAL;
4147 			}
4148 
4149 			/* Theoretically we can program the OA unit to sample
4150 			 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
4151 			 * for BXT. We don't allow such high sampling
4152 			 * frequencies by default unless root.
4153 			 */
4154 
4155 			BUILD_BUG_ON(sizeof(oa_period) != 8);
4156 			oa_period = oa_exponent_to_ns(perf, value);
4157 
4158 			/* This check is primarily to ensure that oa_period <=
4159 			 * UINT32_MAX (before passing to do_div which only
4160 			 * accepts a u32 denominator), but we can also skip
4161 			 * checking anything < 1Hz which implicitly can't be
4162 			 * limited via an integer oa_max_sample_rate.
4163 			 */
4164 			if (oa_period <= NSEC_PER_SEC) {
4165 				u64 tmp = NSEC_PER_SEC;
4166 				do_div(tmp, oa_period);
4167 				oa_freq_hz = tmp;
4168 			} else
4169 				oa_freq_hz = 0;
4170 
4171 			if (oa_freq_hz > i915_oa_max_sample_rate && !perfmon_capable()) {
4172 				drm_dbg(&perf->i915->drm,
4173 					"OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without CAP_PERFMON or CAP_SYS_ADMIN privileges\n",
4174 					  i915_oa_max_sample_rate);
4175 				return -EACCES;
4176 			}
4177 
4178 			props->oa_periodic = true;
4179 			props->oa_period_exponent = value;
4180 			break;
4181 		case DRM_I915_PERF_PROP_HOLD_PREEMPTION:
4182 			props->hold_preemption = !!value;
4183 			break;
4184 		case DRM_I915_PERF_PROP_GLOBAL_SSEU: {
4185 			if (GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 50)) {
4186 				drm_dbg(&perf->i915->drm,
4187 					"SSEU config not supported on gfx %x\n",
4188 					GRAPHICS_VER_FULL(perf->i915));
4189 				return -ENODEV;
4190 			}
4191 
4192 			if (copy_from_user(&user_sseu,
4193 					   u64_to_user_ptr(value),
4194 					   sizeof(user_sseu))) {
4195 				drm_dbg(&perf->i915->drm,
4196 					"Unable to copy global sseu parameter\n");
4197 				return -EFAULT;
4198 			}
4199 			config_sseu = true;
4200 			break;
4201 		}
4202 		case DRM_I915_PERF_PROP_POLL_OA_PERIOD:
4203 			if (value < 100000 /* 100us */) {
4204 				drm_dbg(&perf->i915->drm,
4205 					"OA availability timer too small (%lluns < 100us)\n",
4206 					  value);
4207 				return -EINVAL;
4208 			}
4209 			props->poll_oa_period = value;
4210 			break;
4211 		case DRM_I915_PERF_PROP_OA_ENGINE_CLASS:
4212 			class = (u8)value;
4213 			config_class = true;
4214 			break;
4215 		case DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE:
4216 			instance = (u8)value;
4217 			config_instance = true;
4218 			break;
4219 		default:
4220 			MISSING_CASE(id);
4221 			return -EINVAL;
4222 		}
4223 
4224 		uprop += 2;
4225 	}
4226 
4227 	if ((config_class && !config_instance) ||
4228 	    (config_instance && !config_class)) {
4229 		drm_dbg(&perf->i915->drm,
4230 			"OA engine-class and engine-instance parameters must be passed together\n");
4231 		return -EINVAL;
4232 	}
4233 
4234 	props->engine = intel_engine_lookup_user(perf->i915, class, instance);
4235 	if (!props->engine) {
4236 		drm_dbg(&perf->i915->drm,
4237 			"OA engine class and instance invalid %d:%d\n",
4238 			class, instance);
4239 		return -EINVAL;
4240 	}
4241 
4242 	if (!engine_supports_oa(props->engine)) {
4243 		drm_dbg(&perf->i915->drm,
4244 			"Engine not supported by OA %d:%d\n",
4245 			class, instance);
4246 		return -EINVAL;
4247 	}
4248 
4249 	/*
4250 	 * Wa_14017512683: mtl[a0..c0): Use of OAM must be preceded with Media
4251 	 * C6 disable in BIOS. Fail if Media C6 is enabled on steppings where OAM
4252 	 * does not work as expected.
4253 	 */
4254 	if (IS_MTL_MEDIA_STEP(props->engine->i915, STEP_A0, STEP_C0) &&
4255 	    props->engine->oa_group->type == TYPE_OAM &&
4256 	    intel_check_bios_c6_setup(&props->engine->gt->rc6)) {
4257 		drm_dbg(&perf->i915->drm,
4258 			"OAM requires media C6 to be disabled in BIOS\n");
4259 		return -EINVAL;
4260 	}
4261 
4262 	i = array_index_nospec(props->oa_format, I915_OA_FORMAT_MAX);
4263 	f = &perf->oa_formats[i];
4264 	if (!engine_supports_oa_format(props->engine, f->type)) {
4265 		drm_dbg(&perf->i915->drm,
4266 			"Invalid OA format %d for class %d\n",
4267 			f->type, props->engine->class);
4268 		return -EINVAL;
4269 	}
4270 
4271 	if (config_sseu) {
4272 		ret = get_sseu_config(&props->sseu, props->engine, &user_sseu);
4273 		if (ret) {
4274 			drm_dbg(&perf->i915->drm,
4275 				"Invalid SSEU configuration\n");
4276 			return ret;
4277 		}
4278 		props->has_sseu = true;
4279 	}
4280 
4281 	return 0;
4282 }
4283 
4284 /**
4285  * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
4286  * @dev: drm device
4287  * @data: ioctl data copied from userspace (unvalidated)
4288  * @file: drm file
4289  *
4290  * Validates the stream open parameters given by userspace including flags
4291  * and an array of u64 key, value pair properties.
4292  *
4293  * Very little is assumed up front about the nature of the stream being
4294  * opened (for instance we don't assume it's for periodic OA unit metrics). An
4295  * i915-perf stream is expected to be a suitable interface for other forms of
4296  * buffered data written by the GPU besides periodic OA metrics.
4297  *
4298  * Note we copy the properties from userspace outside of the i915 perf
4299  * mutex to avoid an awkward lockdep with mmap_lock.
4300  *
4301  * Most of the implementation details are handled by
4302  * i915_perf_open_ioctl_locked() after taking the &gt->perf.lock
4303  * mutex for serializing with any non-file-operation driver hooks.
4304  *
4305  * Return: A newly opened i915 Perf stream file descriptor or negative
4306  * error code on failure.
4307  */
i915_perf_open_ioctl(struct drm_device * dev,void * data,struct drm_file * file)4308 int i915_perf_open_ioctl(struct drm_device *dev, void *data,
4309 			 struct drm_file *file)
4310 {
4311 	struct i915_perf *perf = &to_i915(dev)->perf;
4312 	struct drm_i915_perf_open_param *param = data;
4313 	struct intel_gt *gt;
4314 	struct perf_open_properties props;
4315 	u32 known_open_flags;
4316 	int ret;
4317 
4318 	if (!perf->i915)
4319 		return -ENOTSUPP;
4320 
4321 	known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
4322 			   I915_PERF_FLAG_FD_NONBLOCK |
4323 			   I915_PERF_FLAG_DISABLED;
4324 	if (param->flags & ~known_open_flags) {
4325 		drm_dbg(&perf->i915->drm,
4326 			"Unknown drm_i915_perf_open_param flag\n");
4327 		return -EINVAL;
4328 	}
4329 
4330 	ret = read_properties_unlocked(perf,
4331 				       u64_to_user_ptr(param->properties_ptr),
4332 				       param->num_properties,
4333 				       &props);
4334 	if (ret)
4335 		return ret;
4336 
4337 	gt = props.engine->gt;
4338 
4339 	mutex_lock(&gt->perf.lock);
4340 	ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
4341 	mutex_unlock(&gt->perf.lock);
4342 
4343 	return ret;
4344 }
4345 
4346 /**
4347  * i915_perf_register - exposes i915-perf to userspace
4348  * @i915: i915 device instance
4349  *
4350  * In particular OA metric sets are advertised under a sysfs metrics/
4351  * directory allowing userspace to enumerate valid IDs that can be
4352  * used to open an i915-perf stream.
4353  */
i915_perf_register(struct drm_i915_private * i915)4354 void i915_perf_register(struct drm_i915_private *i915)
4355 {
4356 	struct i915_perf *perf = &i915->perf;
4357 	struct intel_gt *gt = to_gt(i915);
4358 
4359 	if (!perf->i915)
4360 		return;
4361 
4362 	/* To be sure we're synchronized with an attempted
4363 	 * i915_perf_open_ioctl(); considering that we register after
4364 	 * being exposed to userspace.
4365 	 */
4366 	mutex_lock(&gt->perf.lock);
4367 
4368 	perf->metrics_kobj =
4369 		kobject_create_and_add("metrics",
4370 				       &i915->drm.primary->kdev->kobj);
4371 
4372 	mutex_unlock(&gt->perf.lock);
4373 }
4374 
4375 /**
4376  * i915_perf_unregister - hide i915-perf from userspace
4377  * @i915: i915 device instance
4378  *
4379  * i915-perf state cleanup is split up into an 'unregister' and
4380  * 'deinit' phase where the interface is first hidden from
4381  * userspace by i915_perf_unregister() before cleaning up
4382  * remaining state in i915_perf_fini().
4383  */
i915_perf_unregister(struct drm_i915_private * i915)4384 void i915_perf_unregister(struct drm_i915_private *i915)
4385 {
4386 	struct i915_perf *perf = &i915->perf;
4387 
4388 	if (!perf->metrics_kobj)
4389 		return;
4390 
4391 	kobject_put(perf->metrics_kobj);
4392 	perf->metrics_kobj = NULL;
4393 }
4394 
gen8_is_valid_flex_addr(struct i915_perf * perf,u32 addr)4395 static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
4396 {
4397 	static const i915_reg_t flex_eu_regs[] = {
4398 		EU_PERF_CNTL0,
4399 		EU_PERF_CNTL1,
4400 		EU_PERF_CNTL2,
4401 		EU_PERF_CNTL3,
4402 		EU_PERF_CNTL4,
4403 		EU_PERF_CNTL5,
4404 		EU_PERF_CNTL6,
4405 	};
4406 	int i;
4407 
4408 	for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
4409 		if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
4410 			return true;
4411 	}
4412 	return false;
4413 }
4414 
reg_in_range_table(u32 addr,const struct i915_range * table)4415 static bool reg_in_range_table(u32 addr, const struct i915_range *table)
4416 {
4417 	while (table->start || table->end) {
4418 		if (addr >= table->start && addr <= table->end)
4419 			return true;
4420 
4421 		table++;
4422 	}
4423 
4424 	return false;
4425 }
4426 
4427 #define REG_EQUAL(addr, mmio) \
4428 	((addr) == i915_mmio_reg_offset(mmio))
4429 
4430 static const struct i915_range gen7_oa_b_counters[] = {
4431 	{ .start = 0x2710, .end = 0x272c },	/* OASTARTTRIG[1-8] */
4432 	{ .start = 0x2740, .end = 0x275c },	/* OAREPORTTRIG[1-8] */
4433 	{ .start = 0x2770, .end = 0x27ac },	/* OACEC[0-7][0-1] */
4434 	{}
4435 };
4436 
4437 static const struct i915_range gen12_oa_b_counters[] = {
4438 	{ .start = 0x2b2c, .end = 0x2b2c },	/* GEN12_OAG_OA_PESS */
4439 	{ .start = 0xd900, .end = 0xd91c },	/* GEN12_OAG_OASTARTTRIG[1-8] */
4440 	{ .start = 0xd920, .end = 0xd93c },	/* GEN12_OAG_OAREPORTTRIG1[1-8] */
4441 	{ .start = 0xd940, .end = 0xd97c },	/* GEN12_OAG_CEC[0-7][0-1] */
4442 	{ .start = 0xdc00, .end = 0xdc3c },	/* GEN12_OAG_SCEC[0-7][0-1] */
4443 	{ .start = 0xdc40, .end = 0xdc40 },	/* GEN12_OAG_SPCTR_CNF */
4444 	{ .start = 0xdc44, .end = 0xdc44 },	/* GEN12_OAA_DBG_REG */
4445 	{}
4446 };
4447 
4448 static const struct i915_range mtl_oam_b_counters[] = {
4449 	{ .start = 0x393000, .end = 0x39301c },	/* GEN12_OAM_STARTTRIG1[1-8] */
4450 	{ .start = 0x393020, .end = 0x39303c },	/* GEN12_OAM_REPORTTRIG1[1-8] */
4451 	{ .start = 0x393040, .end = 0x39307c },	/* GEN12_OAM_CEC[0-7][0-1] */
4452 	{ .start = 0x393200, .end = 0x39323C },	/* MPES[0-7] */
4453 	{}
4454 };
4455 
4456 static const struct i915_range xehp_oa_b_counters[] = {
4457 	{ .start = 0xdc48, .end = 0xdc48 },	/* OAA_ENABLE_REG */
4458 	{ .start = 0xdd00, .end = 0xdd48 },	/* OAG_LCE0_0 - OAA_LENABLE_REG */
4459 	{}
4460 };
4461 
4462 static const struct i915_range gen7_oa_mux_regs[] = {
4463 	{ .start = 0x91b8, .end = 0x91cc },	/* OA_PERFCNT[1-2], OA_PERFMATRIX */
4464 	{ .start = 0x9800, .end = 0x9888 },	/* MICRO_BP0_0 - NOA_WRITE */
4465 	{ .start = 0xe180, .end = 0xe180 },	/* HALF_SLICE_CHICKEN2 */
4466 	{}
4467 };
4468 
4469 static const struct i915_range hsw_oa_mux_regs[] = {
4470 	{ .start = 0x09e80, .end = 0x09ea4 }, /* HSW_MBVID2_NOA[0-9] */
4471 	{ .start = 0x09ec0, .end = 0x09ec0 }, /* HSW_MBVID2_MISR0 */
4472 	{ .start = 0x25100, .end = 0x2ff90 },
4473 	{}
4474 };
4475 
4476 static const struct i915_range chv_oa_mux_regs[] = {
4477 	{ .start = 0x182300, .end = 0x1823a4 },
4478 	{}
4479 };
4480 
4481 static const struct i915_range gen8_oa_mux_regs[] = {
4482 	{ .start = 0x0d00, .end = 0x0d2c },	/* RPM_CONFIG[0-1], NOA_CONFIG[0-8] */
4483 	{ .start = 0x20cc, .end = 0x20cc },	/* WAIT_FOR_RC6_EXIT */
4484 	{}
4485 };
4486 
4487 static const struct i915_range gen11_oa_mux_regs[] = {
4488 	{ .start = 0x91c8, .end = 0x91dc },	/* OA_PERFCNT[3-4] */
4489 	{}
4490 };
4491 
4492 static const struct i915_range gen12_oa_mux_regs[] = {
4493 	{ .start = 0x0d00, .end = 0x0d04 },     /* RPM_CONFIG[0-1] */
4494 	{ .start = 0x0d0c, .end = 0x0d2c },     /* NOA_CONFIG[0-8] */
4495 	{ .start = 0x9840, .end = 0x9840 },	/* GDT_CHICKEN_BITS */
4496 	{ .start = 0x9884, .end = 0x9888 },	/* NOA_WRITE */
4497 	{ .start = 0x20cc, .end = 0x20cc },	/* WAIT_FOR_RC6_EXIT */
4498 	{}
4499 };
4500 
4501 /*
4502  * Ref: 14010536224:
4503  * 0x20cc is repurposed on MTL, so use a separate array for MTL.
4504  */
4505 static const struct i915_range mtl_oa_mux_regs[] = {
4506 	{ .start = 0x0d00, .end = 0x0d04 },	/* RPM_CONFIG[0-1] */
4507 	{ .start = 0x0d0c, .end = 0x0d2c },	/* NOA_CONFIG[0-8] */
4508 	{ .start = 0x9840, .end = 0x9840 },	/* GDT_CHICKEN_BITS */
4509 	{ .start = 0x9884, .end = 0x9888 },	/* NOA_WRITE */
4510 	{ .start = 0x38d100, .end = 0x38d114},	/* VISACTL */
4511 	{}
4512 };
4513 
gen7_is_valid_b_counter_addr(struct i915_perf * perf,u32 addr)4514 static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
4515 {
4516 	return reg_in_range_table(addr, gen7_oa_b_counters);
4517 }
4518 
gen8_is_valid_mux_addr(struct i915_perf * perf,u32 addr)4519 static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4520 {
4521 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4522 		reg_in_range_table(addr, gen8_oa_mux_regs);
4523 }
4524 
gen11_is_valid_mux_addr(struct i915_perf * perf,u32 addr)4525 static bool gen11_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4526 {
4527 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4528 		reg_in_range_table(addr, gen8_oa_mux_regs) ||
4529 		reg_in_range_table(addr, gen11_oa_mux_regs);
4530 }
4531 
hsw_is_valid_mux_addr(struct i915_perf * perf,u32 addr)4532 static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4533 {
4534 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4535 		reg_in_range_table(addr, hsw_oa_mux_regs);
4536 }
4537 
chv_is_valid_mux_addr(struct i915_perf * perf,u32 addr)4538 static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4539 {
4540 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4541 		reg_in_range_table(addr, chv_oa_mux_regs);
4542 }
4543 
gen12_is_valid_b_counter_addr(struct i915_perf * perf,u32 addr)4544 static bool gen12_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
4545 {
4546 	return reg_in_range_table(addr, gen12_oa_b_counters);
4547 }
4548 
mtl_is_valid_oam_b_counter_addr(struct i915_perf * perf,u32 addr)4549 static bool mtl_is_valid_oam_b_counter_addr(struct i915_perf *perf, u32 addr)
4550 {
4551 	if (HAS_OAM(perf->i915) &&
4552 	    GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 70))
4553 		return reg_in_range_table(addr, mtl_oam_b_counters);
4554 
4555 	return false;
4556 }
4557 
xehp_is_valid_b_counter_addr(struct i915_perf * perf,u32 addr)4558 static bool xehp_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
4559 {
4560 	return reg_in_range_table(addr, xehp_oa_b_counters) ||
4561 		reg_in_range_table(addr, gen12_oa_b_counters) ||
4562 		mtl_is_valid_oam_b_counter_addr(perf, addr);
4563 }
4564 
gen12_is_valid_mux_addr(struct i915_perf * perf,u32 addr)4565 static bool gen12_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4566 {
4567 	if (IS_METEORLAKE(perf->i915))
4568 		return reg_in_range_table(addr, mtl_oa_mux_regs);
4569 	else
4570 		return reg_in_range_table(addr, gen12_oa_mux_regs);
4571 }
4572 
mask_reg_value(u32 reg,u32 val)4573 static u32 mask_reg_value(u32 reg, u32 val)
4574 {
4575 	/* HALF_SLICE_CHICKEN2 is programmed with a the
4576 	 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
4577 	 * programmed by userspace doesn't change this.
4578 	 */
4579 	if (REG_EQUAL(reg, HALF_SLICE_CHICKEN2))
4580 		val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
4581 
4582 	/* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
4583 	 * indicated by its name and a bunch of selection fields used by OA
4584 	 * configs.
4585 	 */
4586 	if (REG_EQUAL(reg, WAIT_FOR_RC6_EXIT))
4587 		val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
4588 
4589 	return val;
4590 }
4591 
alloc_oa_regs(struct i915_perf * perf,bool (* is_valid)(struct i915_perf * perf,u32 addr),u32 __user * regs,u32 n_regs)4592 static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
4593 					 bool (*is_valid)(struct i915_perf *perf, u32 addr),
4594 					 u32 __user *regs,
4595 					 u32 n_regs)
4596 {
4597 	struct i915_oa_reg *oa_regs;
4598 	int err;
4599 	u32 i;
4600 
4601 	if (!n_regs)
4602 		return NULL;
4603 
4604 	/* No is_valid function means we're not allowing any register to be programmed. */
4605 	GEM_BUG_ON(!is_valid);
4606 	if (!is_valid)
4607 		return ERR_PTR(-EINVAL);
4608 
4609 	oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
4610 	if (!oa_regs)
4611 		return ERR_PTR(-ENOMEM);
4612 
4613 	for (i = 0; i < n_regs; i++) {
4614 		u32 addr, value;
4615 
4616 		err = get_user(addr, regs);
4617 		if (err)
4618 			goto addr_err;
4619 
4620 		if (!is_valid(perf, addr)) {
4621 			drm_dbg(&perf->i915->drm,
4622 				"Invalid oa_reg address: %X\n", addr);
4623 			err = -EINVAL;
4624 			goto addr_err;
4625 		}
4626 
4627 		err = get_user(value, regs + 1);
4628 		if (err)
4629 			goto addr_err;
4630 
4631 		oa_regs[i].addr = _MMIO(addr);
4632 		oa_regs[i].value = mask_reg_value(addr, value);
4633 
4634 		regs += 2;
4635 	}
4636 
4637 	return oa_regs;
4638 
4639 addr_err:
4640 	kfree(oa_regs);
4641 	return ERR_PTR(err);
4642 }
4643 
show_dynamic_id(struct kobject * kobj,struct kobj_attribute * attr,char * buf)4644 static ssize_t show_dynamic_id(struct kobject *kobj,
4645 			       struct kobj_attribute *attr,
4646 			       char *buf)
4647 {
4648 	struct i915_oa_config *oa_config =
4649 		container_of(attr, typeof(*oa_config), sysfs_metric_id);
4650 
4651 	return sprintf(buf, "%d\n", oa_config->id);
4652 }
4653 
create_dynamic_oa_sysfs_entry(struct i915_perf * perf,struct i915_oa_config * oa_config)4654 static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
4655 					 struct i915_oa_config *oa_config)
4656 {
4657 	sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
4658 	oa_config->sysfs_metric_id.attr.name = "id";
4659 	oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
4660 	oa_config->sysfs_metric_id.show = show_dynamic_id;
4661 	oa_config->sysfs_metric_id.store = NULL;
4662 
4663 	oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
4664 	oa_config->attrs[1] = NULL;
4665 
4666 	oa_config->sysfs_metric.name = oa_config->uuid;
4667 	oa_config->sysfs_metric.attrs = oa_config->attrs;
4668 
4669 	return sysfs_create_group(perf->metrics_kobj,
4670 				  &oa_config->sysfs_metric);
4671 }
4672 
4673 /**
4674  * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
4675  * @dev: drm device
4676  * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
4677  *        userspace (unvalidated)
4678  * @file: drm file
4679  *
4680  * Validates the submitted OA register to be saved into a new OA config that
4681  * can then be used for programming the OA unit and its NOA network.
4682  *
4683  * Returns: A new allocated config number to be used with the perf open ioctl
4684  * or a negative error code on failure.
4685  */
i915_perf_add_config_ioctl(struct drm_device * dev,void * data,struct drm_file * file)4686 int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
4687 			       struct drm_file *file)
4688 {
4689 	struct i915_perf *perf = &to_i915(dev)->perf;
4690 	struct drm_i915_perf_oa_config *args = data;
4691 	struct i915_oa_config *oa_config, *tmp;
4692 	struct i915_oa_reg *regs;
4693 	int err, id;
4694 
4695 	if (!perf->i915)
4696 		return -ENOTSUPP;
4697 
4698 	if (!perf->metrics_kobj) {
4699 		drm_dbg(&perf->i915->drm,
4700 			"OA metrics weren't advertised via sysfs\n");
4701 		return -EINVAL;
4702 	}
4703 
4704 	if (i915_perf_stream_paranoid && !perfmon_capable()) {
4705 		drm_dbg(&perf->i915->drm,
4706 			"Insufficient privileges to add i915 OA config\n");
4707 		return -EACCES;
4708 	}
4709 
4710 	if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
4711 	    (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
4712 	    (!args->flex_regs_ptr || !args->n_flex_regs)) {
4713 		drm_dbg(&perf->i915->drm,
4714 			"No OA registers given\n");
4715 		return -EINVAL;
4716 	}
4717 
4718 	oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
4719 	if (!oa_config) {
4720 		drm_dbg(&perf->i915->drm,
4721 			"Failed to allocate memory for the OA config\n");
4722 		return -ENOMEM;
4723 	}
4724 
4725 	oa_config->perf = perf;
4726 	kref_init(&oa_config->ref);
4727 
4728 	if (!uuid_is_valid(args->uuid)) {
4729 		drm_dbg(&perf->i915->drm,
4730 			"Invalid uuid format for OA config\n");
4731 		err = -EINVAL;
4732 		goto reg_err;
4733 	}
4734 
4735 	/* Last character in oa_config->uuid will be 0 because oa_config is
4736 	 * kzalloc.
4737 	 */
4738 	memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
4739 
4740 	oa_config->mux_regs_len = args->n_mux_regs;
4741 	regs = alloc_oa_regs(perf,
4742 			     perf->ops.is_valid_mux_reg,
4743 			     u64_to_user_ptr(args->mux_regs_ptr),
4744 			     args->n_mux_regs);
4745 
4746 	if (IS_ERR(regs)) {
4747 		drm_dbg(&perf->i915->drm,
4748 			"Failed to create OA config for mux_regs\n");
4749 		err = PTR_ERR(regs);
4750 		goto reg_err;
4751 	}
4752 	oa_config->mux_regs = regs;
4753 
4754 	oa_config->b_counter_regs_len = args->n_boolean_regs;
4755 	regs = alloc_oa_regs(perf,
4756 			     perf->ops.is_valid_b_counter_reg,
4757 			     u64_to_user_ptr(args->boolean_regs_ptr),
4758 			     args->n_boolean_regs);
4759 
4760 	if (IS_ERR(regs)) {
4761 		drm_dbg(&perf->i915->drm,
4762 			"Failed to create OA config for b_counter_regs\n");
4763 		err = PTR_ERR(regs);
4764 		goto reg_err;
4765 	}
4766 	oa_config->b_counter_regs = regs;
4767 
4768 	if (GRAPHICS_VER(perf->i915) < 8) {
4769 		if (args->n_flex_regs != 0) {
4770 			err = -EINVAL;
4771 			goto reg_err;
4772 		}
4773 	} else {
4774 		oa_config->flex_regs_len = args->n_flex_regs;
4775 		regs = alloc_oa_regs(perf,
4776 				     perf->ops.is_valid_flex_reg,
4777 				     u64_to_user_ptr(args->flex_regs_ptr),
4778 				     args->n_flex_regs);
4779 
4780 		if (IS_ERR(regs)) {
4781 			drm_dbg(&perf->i915->drm,
4782 				"Failed to create OA config for flex_regs\n");
4783 			err = PTR_ERR(regs);
4784 			goto reg_err;
4785 		}
4786 		oa_config->flex_regs = regs;
4787 	}
4788 
4789 	err = mutex_lock_interruptible(&perf->metrics_lock);
4790 	if (err)
4791 		goto reg_err;
4792 
4793 	/* We shouldn't have too many configs, so this iteration shouldn't be
4794 	 * too costly.
4795 	 */
4796 	idr_for_each_entry(&perf->metrics_idr, tmp, id) {
4797 		if (!strcmp(tmp->uuid, oa_config->uuid)) {
4798 			drm_dbg(&perf->i915->drm,
4799 				"OA config already exists with this uuid\n");
4800 			err = -EADDRINUSE;
4801 			goto sysfs_err;
4802 		}
4803 	}
4804 
4805 	err = create_dynamic_oa_sysfs_entry(perf, oa_config);
4806 	if (err) {
4807 		drm_dbg(&perf->i915->drm,
4808 			"Failed to create sysfs entry for OA config\n");
4809 		goto sysfs_err;
4810 	}
4811 
4812 	/* Config id 0 is invalid, id 1 for kernel stored test config. */
4813 	oa_config->id = idr_alloc(&perf->metrics_idr,
4814 				  oa_config, 2,
4815 				  0, GFP_KERNEL);
4816 	if (oa_config->id < 0) {
4817 		drm_dbg(&perf->i915->drm,
4818 			"Failed to create sysfs entry for OA config\n");
4819 		err = oa_config->id;
4820 		goto sysfs_err;
4821 	}
4822 	id = oa_config->id;
4823 
4824 	drm_dbg(&perf->i915->drm,
4825 		"Added config %s id=%i\n", oa_config->uuid, oa_config->id);
4826 	mutex_unlock(&perf->metrics_lock);
4827 
4828 	return id;
4829 
4830 sysfs_err:
4831 	mutex_unlock(&perf->metrics_lock);
4832 reg_err:
4833 	i915_oa_config_put(oa_config);
4834 	drm_dbg(&perf->i915->drm,
4835 		"Failed to add new OA config\n");
4836 	return err;
4837 }
4838 
4839 /**
4840  * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
4841  * @dev: drm device
4842  * @data: ioctl data (pointer to u64 integer) copied from userspace
4843  * @file: drm file
4844  *
4845  * Configs can be removed while being used, the will stop appearing in sysfs
4846  * and their content will be freed when the stream using the config is closed.
4847  *
4848  * Returns: 0 on success or a negative error code on failure.
4849  */
i915_perf_remove_config_ioctl(struct drm_device * dev,void * data,struct drm_file * file)4850 int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
4851 				  struct drm_file *file)
4852 {
4853 	struct i915_perf *perf = &to_i915(dev)->perf;
4854 	u64 *arg = data;
4855 	struct i915_oa_config *oa_config;
4856 	int ret;
4857 
4858 	if (!perf->i915)
4859 		return -ENOTSUPP;
4860 
4861 	if (i915_perf_stream_paranoid && !perfmon_capable()) {
4862 		drm_dbg(&perf->i915->drm,
4863 			"Insufficient privileges to remove i915 OA config\n");
4864 		return -EACCES;
4865 	}
4866 
4867 	ret = mutex_lock_interruptible(&perf->metrics_lock);
4868 	if (ret)
4869 		return ret;
4870 
4871 	oa_config = idr_find(&perf->metrics_idr, *arg);
4872 	if (!oa_config) {
4873 		drm_dbg(&perf->i915->drm,
4874 			"Failed to remove unknown OA config\n");
4875 		ret = -ENOENT;
4876 		goto err_unlock;
4877 	}
4878 
4879 	GEM_BUG_ON(*arg != oa_config->id);
4880 
4881 	sysfs_remove_group(perf->metrics_kobj, &oa_config->sysfs_metric);
4882 
4883 	idr_remove(&perf->metrics_idr, *arg);
4884 
4885 	mutex_unlock(&perf->metrics_lock);
4886 
4887 	drm_dbg(&perf->i915->drm,
4888 		"Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
4889 
4890 	i915_oa_config_put(oa_config);
4891 
4892 	return 0;
4893 
4894 err_unlock:
4895 	mutex_unlock(&perf->metrics_lock);
4896 	return ret;
4897 }
4898 
4899 static struct ctl_table oa_table[] = {
4900 	{
4901 	 .procname = "perf_stream_paranoid",
4902 	 .data = &i915_perf_stream_paranoid,
4903 	 .maxlen = sizeof(i915_perf_stream_paranoid),
4904 	 .mode = 0644,
4905 	 .proc_handler = proc_dointvec_minmax,
4906 	 .extra1 = SYSCTL_ZERO,
4907 	 .extra2 = SYSCTL_ONE,
4908 	 },
4909 	{
4910 	 .procname = "oa_max_sample_rate",
4911 	 .data = &i915_oa_max_sample_rate,
4912 	 .maxlen = sizeof(i915_oa_max_sample_rate),
4913 	 .mode = 0644,
4914 	 .proc_handler = proc_dointvec_minmax,
4915 	 .extra1 = SYSCTL_ZERO,
4916 	 .extra2 = &oa_sample_rate_hard_limit,
4917 	 },
4918 	{}
4919 };
4920 
num_perf_groups_per_gt(struct intel_gt * gt)4921 static u32 num_perf_groups_per_gt(struct intel_gt *gt)
4922 {
4923 	return 1;
4924 }
4925 
__oam_engine_group(struct intel_engine_cs * engine)4926 static u32 __oam_engine_group(struct intel_engine_cs *engine)
4927 {
4928 	if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 70)) {
4929 		/*
4930 		 * There's 1 SAMEDIA gt and 1 OAM per SAMEDIA gt. All media slices
4931 		 * within the gt use the same OAM. All MTL SKUs list 1 SA MEDIA.
4932 		 */
4933 		drm_WARN_ON(&engine->i915->drm,
4934 			    engine->gt->type != GT_MEDIA);
4935 
4936 		return PERF_GROUP_OAM_SAMEDIA_0;
4937 	}
4938 
4939 	return PERF_GROUP_INVALID;
4940 }
4941 
__oa_engine_group(struct intel_engine_cs * engine)4942 static u32 __oa_engine_group(struct intel_engine_cs *engine)
4943 {
4944 	switch (engine->class) {
4945 	case RENDER_CLASS:
4946 		return PERF_GROUP_OAG;
4947 
4948 	case VIDEO_DECODE_CLASS:
4949 	case VIDEO_ENHANCEMENT_CLASS:
4950 		return __oam_engine_group(engine);
4951 
4952 	default:
4953 		return PERF_GROUP_INVALID;
4954 	}
4955 }
4956 
__oam_regs(u32 base)4957 static struct i915_perf_regs __oam_regs(u32 base)
4958 {
4959 	return (struct i915_perf_regs) {
4960 		base,
4961 		GEN12_OAM_HEAD_POINTER(base),
4962 		GEN12_OAM_TAIL_POINTER(base),
4963 		GEN12_OAM_BUFFER(base),
4964 		GEN12_OAM_CONTEXT_CONTROL(base),
4965 		GEN12_OAM_CONTROL(base),
4966 		GEN12_OAM_DEBUG(base),
4967 		GEN12_OAM_STATUS(base),
4968 		GEN12_OAM_CONTROL_COUNTER_FORMAT_SHIFT,
4969 	};
4970 }
4971 
__oag_regs(void)4972 static struct i915_perf_regs __oag_regs(void)
4973 {
4974 	return (struct i915_perf_regs) {
4975 		0,
4976 		GEN12_OAG_OAHEADPTR,
4977 		GEN12_OAG_OATAILPTR,
4978 		GEN12_OAG_OABUFFER,
4979 		GEN12_OAG_OAGLBCTXCTRL,
4980 		GEN12_OAG_OACONTROL,
4981 		GEN12_OAG_OA_DEBUG,
4982 		GEN12_OAG_OASTATUS,
4983 		GEN12_OAG_OACONTROL_OA_COUNTER_FORMAT_SHIFT,
4984 	};
4985 }
4986 
oa_init_groups(struct intel_gt * gt)4987 static void oa_init_groups(struct intel_gt *gt)
4988 {
4989 	int i, num_groups = gt->perf.num_perf_groups;
4990 
4991 	for (i = 0; i < num_groups; i++) {
4992 		struct i915_perf_group *g = &gt->perf.group[i];
4993 
4994 		/* Fused off engines can result in a group with num_engines == 0 */
4995 		if (g->num_engines == 0)
4996 			continue;
4997 
4998 		if (i == PERF_GROUP_OAG && gt->type != GT_MEDIA) {
4999 			g->regs = __oag_regs();
5000 			g->type = TYPE_OAG;
5001 		} else if (GRAPHICS_VER_FULL(gt->i915) >= IP_VER(12, 70)) {
5002 			g->regs = __oam_regs(mtl_oa_base[i]);
5003 			g->type = TYPE_OAM;
5004 		}
5005 	}
5006 }
5007 
oa_init_gt(struct intel_gt * gt)5008 static int oa_init_gt(struct intel_gt *gt)
5009 {
5010 	u32 num_groups = num_perf_groups_per_gt(gt);
5011 	struct intel_engine_cs *engine;
5012 	struct i915_perf_group *g;
5013 	intel_engine_mask_t tmp;
5014 
5015 	g = kcalloc(num_groups, sizeof(*g), GFP_KERNEL);
5016 	if (!g)
5017 		return -ENOMEM;
5018 
5019 	for_each_engine_masked(engine, gt, ALL_ENGINES, tmp) {
5020 		u32 index = __oa_engine_group(engine);
5021 
5022 		engine->oa_group = NULL;
5023 		if (index < num_groups) {
5024 			g[index].num_engines++;
5025 			engine->oa_group = &g[index];
5026 		}
5027 	}
5028 
5029 	gt->perf.num_perf_groups = num_groups;
5030 	gt->perf.group = g;
5031 
5032 	oa_init_groups(gt);
5033 
5034 	return 0;
5035 }
5036 
oa_init_engine_groups(struct i915_perf * perf)5037 static int oa_init_engine_groups(struct i915_perf *perf)
5038 {
5039 	struct intel_gt *gt;
5040 	int i, ret;
5041 
5042 	for_each_gt(gt, perf->i915, i) {
5043 		ret = oa_init_gt(gt);
5044 		if (ret)
5045 			return ret;
5046 	}
5047 
5048 	return 0;
5049 }
5050 
oa_init_supported_formats(struct i915_perf * perf)5051 static void oa_init_supported_formats(struct i915_perf *perf)
5052 {
5053 	struct drm_i915_private *i915 = perf->i915;
5054 	enum intel_platform platform = INTEL_INFO(i915)->platform;
5055 
5056 	switch (platform) {
5057 	case INTEL_HASWELL:
5058 		oa_format_add(perf, I915_OA_FORMAT_A13);
5059 		oa_format_add(perf, I915_OA_FORMAT_A13);
5060 		oa_format_add(perf, I915_OA_FORMAT_A29);
5061 		oa_format_add(perf, I915_OA_FORMAT_A13_B8_C8);
5062 		oa_format_add(perf, I915_OA_FORMAT_B4_C8);
5063 		oa_format_add(perf, I915_OA_FORMAT_A45_B8_C8);
5064 		oa_format_add(perf, I915_OA_FORMAT_B4_C8_A16);
5065 		oa_format_add(perf, I915_OA_FORMAT_C4_B8);
5066 		break;
5067 
5068 	case INTEL_BROADWELL:
5069 	case INTEL_CHERRYVIEW:
5070 	case INTEL_SKYLAKE:
5071 	case INTEL_BROXTON:
5072 	case INTEL_KABYLAKE:
5073 	case INTEL_GEMINILAKE:
5074 	case INTEL_COFFEELAKE:
5075 	case INTEL_COMETLAKE:
5076 	case INTEL_ICELAKE:
5077 	case INTEL_ELKHARTLAKE:
5078 	case INTEL_JASPERLAKE:
5079 	case INTEL_TIGERLAKE:
5080 	case INTEL_ROCKETLAKE:
5081 	case INTEL_DG1:
5082 	case INTEL_ALDERLAKE_S:
5083 	case INTEL_ALDERLAKE_P:
5084 		oa_format_add(perf, I915_OA_FORMAT_A12);
5085 		oa_format_add(perf, I915_OA_FORMAT_A12_B8_C8);
5086 		oa_format_add(perf, I915_OA_FORMAT_A32u40_A4u32_B8_C8);
5087 		oa_format_add(perf, I915_OA_FORMAT_C4_B8);
5088 		break;
5089 
5090 	case INTEL_DG2:
5091 		oa_format_add(perf, I915_OAR_FORMAT_A32u40_A4u32_B8_C8);
5092 		oa_format_add(perf, I915_OA_FORMAT_A24u40_A14u32_B8_C8);
5093 		break;
5094 
5095 	case INTEL_METEORLAKE:
5096 		oa_format_add(perf, I915_OAR_FORMAT_A32u40_A4u32_B8_C8);
5097 		oa_format_add(perf, I915_OA_FORMAT_A24u40_A14u32_B8_C8);
5098 		oa_format_add(perf, I915_OAM_FORMAT_MPEC8u64_B8_C8);
5099 		oa_format_add(perf, I915_OAM_FORMAT_MPEC8u32_B8_C8);
5100 		break;
5101 
5102 	default:
5103 		MISSING_CASE(platform);
5104 	}
5105 }
5106 
i915_perf_init_info(struct drm_i915_private * i915)5107 static void i915_perf_init_info(struct drm_i915_private *i915)
5108 {
5109 	struct i915_perf *perf = &i915->perf;
5110 
5111 	switch (GRAPHICS_VER(i915)) {
5112 	case 8:
5113 		perf->ctx_oactxctrl_offset = 0x120;
5114 		perf->ctx_flexeu0_offset = 0x2ce;
5115 		perf->gen8_valid_ctx_bit = BIT(25);
5116 		break;
5117 	case 9:
5118 		perf->ctx_oactxctrl_offset = 0x128;
5119 		perf->ctx_flexeu0_offset = 0x3de;
5120 		perf->gen8_valid_ctx_bit = BIT(16);
5121 		break;
5122 	case 11:
5123 		perf->ctx_oactxctrl_offset = 0x124;
5124 		perf->ctx_flexeu0_offset = 0x78e;
5125 		perf->gen8_valid_ctx_bit = BIT(16);
5126 		break;
5127 	case 12:
5128 		perf->gen8_valid_ctx_bit = BIT(16);
5129 		/*
5130 		 * Calculate offset at runtime in oa_pin_context for gen12 and
5131 		 * cache the value in perf->ctx_oactxctrl_offset.
5132 		 */
5133 		break;
5134 	default:
5135 		MISSING_CASE(GRAPHICS_VER(i915));
5136 	}
5137 }
5138 
5139 /**
5140  * i915_perf_init - initialize i915-perf state on module bind
5141  * @i915: i915 device instance
5142  *
5143  * Initializes i915-perf state without exposing anything to userspace.
5144  *
5145  * Note: i915-perf initialization is split into an 'init' and 'register'
5146  * phase with the i915_perf_register() exposing state to userspace.
5147  */
i915_perf_init(struct drm_i915_private * i915)5148 int i915_perf_init(struct drm_i915_private *i915)
5149 {
5150 	struct i915_perf *perf = &i915->perf;
5151 
5152 	perf->oa_formats = oa_formats;
5153 	if (IS_HASWELL(i915)) {
5154 		perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
5155 		perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
5156 		perf->ops.is_valid_flex_reg = NULL;
5157 		perf->ops.enable_metric_set = hsw_enable_metric_set;
5158 		perf->ops.disable_metric_set = hsw_disable_metric_set;
5159 		perf->ops.oa_enable = gen7_oa_enable;
5160 		perf->ops.oa_disable = gen7_oa_disable;
5161 		perf->ops.read = gen7_oa_read;
5162 		perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
5163 	} else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
5164 		/* Note: that although we could theoretically also support the
5165 		 * legacy ringbuffer mode on BDW (and earlier iterations of
5166 		 * this driver, before upstreaming did this) it didn't seem
5167 		 * worth the complexity to maintain now that BDW+ enable
5168 		 * execlist mode by default.
5169 		 */
5170 		perf->ops.read = gen8_oa_read;
5171 		i915_perf_init_info(i915);
5172 
5173 		if (IS_GRAPHICS_VER(i915, 8, 9)) {
5174 			perf->ops.is_valid_b_counter_reg =
5175 				gen7_is_valid_b_counter_addr;
5176 			perf->ops.is_valid_mux_reg =
5177 				gen8_is_valid_mux_addr;
5178 			perf->ops.is_valid_flex_reg =
5179 				gen8_is_valid_flex_addr;
5180 
5181 			if (IS_CHERRYVIEW(i915)) {
5182 				perf->ops.is_valid_mux_reg =
5183 					chv_is_valid_mux_addr;
5184 			}
5185 
5186 			perf->ops.oa_enable = gen8_oa_enable;
5187 			perf->ops.oa_disable = gen8_oa_disable;
5188 			perf->ops.enable_metric_set = gen8_enable_metric_set;
5189 			perf->ops.disable_metric_set = gen8_disable_metric_set;
5190 			perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
5191 		} else if (GRAPHICS_VER(i915) == 11) {
5192 			perf->ops.is_valid_b_counter_reg =
5193 				gen7_is_valid_b_counter_addr;
5194 			perf->ops.is_valid_mux_reg =
5195 				gen11_is_valid_mux_addr;
5196 			perf->ops.is_valid_flex_reg =
5197 				gen8_is_valid_flex_addr;
5198 
5199 			perf->ops.oa_enable = gen8_oa_enable;
5200 			perf->ops.oa_disable = gen8_oa_disable;
5201 			perf->ops.enable_metric_set = gen8_enable_metric_set;
5202 			perf->ops.disable_metric_set = gen11_disable_metric_set;
5203 			perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
5204 		} else if (GRAPHICS_VER(i915) == 12) {
5205 			perf->ops.is_valid_b_counter_reg =
5206 				HAS_OA_SLICE_CONTRIB_LIMITS(i915) ?
5207 				xehp_is_valid_b_counter_addr :
5208 				gen12_is_valid_b_counter_addr;
5209 			perf->ops.is_valid_mux_reg =
5210 				gen12_is_valid_mux_addr;
5211 			perf->ops.is_valid_flex_reg =
5212 				gen8_is_valid_flex_addr;
5213 
5214 			perf->ops.oa_enable = gen12_oa_enable;
5215 			perf->ops.oa_disable = gen12_oa_disable;
5216 			perf->ops.enable_metric_set = gen12_enable_metric_set;
5217 			perf->ops.disable_metric_set = gen12_disable_metric_set;
5218 			perf->ops.oa_hw_tail_read = gen12_oa_hw_tail_read;
5219 		}
5220 	}
5221 
5222 	if (perf->ops.enable_metric_set) {
5223 		struct intel_gt *gt;
5224 		int i, ret;
5225 
5226 		for_each_gt(gt, i915, i)
5227 			mutex_init(&gt->perf.lock);
5228 
5229 		/* Choose a representative limit */
5230 		oa_sample_rate_hard_limit = to_gt(i915)->clock_frequency / 2;
5231 
5232 		mutex_init(&perf->metrics_lock);
5233 		idr_init_base(&perf->metrics_idr, 1);
5234 
5235 		/* We set up some ratelimit state to potentially throttle any
5236 		 * _NOTES about spurious, invalid OA reports which we don't
5237 		 * forward to userspace.
5238 		 *
5239 		 * We print a _NOTE about any throttling when closing the
5240 		 * stream instead of waiting until driver _fini which no one
5241 		 * would ever see.
5242 		 *
5243 		 * Using the same limiting factors as printk_ratelimit()
5244 		 */
5245 		ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
5246 		/* Since we use a DRM_NOTE for spurious reports it would be
5247 		 * inconsistent to let __ratelimit() automatically print a
5248 		 * warning for throttling.
5249 		 */
5250 		ratelimit_set_flags(&perf->spurious_report_rs,
5251 				    RATELIMIT_MSG_ON_RELEASE);
5252 
5253 		ratelimit_state_init(&perf->tail_pointer_race,
5254 				     5 * HZ, 10);
5255 		ratelimit_set_flags(&perf->tail_pointer_race,
5256 				    RATELIMIT_MSG_ON_RELEASE);
5257 
5258 		atomic64_set(&perf->noa_programming_delay,
5259 			     500 * 1000 /* 500us */);
5260 
5261 		perf->i915 = i915;
5262 
5263 		ret = oa_init_engine_groups(perf);
5264 		if (ret) {
5265 			drm_err(&i915->drm,
5266 				"OA initialization failed %d\n", ret);
5267 			return ret;
5268 		}
5269 
5270 		oa_init_supported_formats(perf);
5271 	}
5272 
5273 	return 0;
5274 }
5275 
destroy_config(int id,void * p,void * data)5276 static int destroy_config(int id, void *p, void *data)
5277 {
5278 	i915_oa_config_put(p);
5279 	return 0;
5280 }
5281 
i915_perf_sysctl_register(void)5282 int i915_perf_sysctl_register(void)
5283 {
5284 	sysctl_header = register_sysctl("dev/i915", oa_table);
5285 	return 0;
5286 }
5287 
i915_perf_sysctl_unregister(void)5288 void i915_perf_sysctl_unregister(void)
5289 {
5290 	unregister_sysctl_table(sysctl_header);
5291 }
5292 
5293 /**
5294  * i915_perf_fini - Counter part to i915_perf_init()
5295  * @i915: i915 device instance
5296  */
i915_perf_fini(struct drm_i915_private * i915)5297 void i915_perf_fini(struct drm_i915_private *i915)
5298 {
5299 	struct i915_perf *perf = &i915->perf;
5300 	struct intel_gt *gt;
5301 	int i;
5302 
5303 	if (!perf->i915)
5304 		return;
5305 
5306 	for_each_gt(gt, perf->i915, i)
5307 		kfree(gt->perf.group);
5308 
5309 	idr_for_each(&perf->metrics_idr, destroy_config, perf);
5310 	idr_destroy(&perf->metrics_idr);
5311 
5312 	memset(&perf->ops, 0, sizeof(perf->ops));
5313 	perf->i915 = NULL;
5314 }
5315 
5316 /**
5317  * i915_perf_ioctl_version - Version of the i915-perf subsystem
5318  * @i915: The i915 device
5319  *
5320  * This version number is used by userspace to detect available features.
5321  */
i915_perf_ioctl_version(struct drm_i915_private * i915)5322 int i915_perf_ioctl_version(struct drm_i915_private *i915)
5323 {
5324 	/*
5325 	 * 1: Initial version
5326 	 *   I915_PERF_IOCTL_ENABLE
5327 	 *   I915_PERF_IOCTL_DISABLE
5328 	 *
5329 	 * 2: Added runtime modification of OA config.
5330 	 *   I915_PERF_IOCTL_CONFIG
5331 	 *
5332 	 * 3: Add DRM_I915_PERF_PROP_HOLD_PREEMPTION parameter to hold
5333 	 *    preemption on a particular context so that performance data is
5334 	 *    accessible from a delta of MI_RPC reports without looking at the
5335 	 *    OA buffer.
5336 	 *
5337 	 * 4: Add DRM_I915_PERF_PROP_ALLOWED_SSEU to limit what contexts can
5338 	 *    be run for the duration of the performance recording based on
5339 	 *    their SSEU configuration.
5340 	 *
5341 	 * 5: Add DRM_I915_PERF_PROP_POLL_OA_PERIOD parameter that controls the
5342 	 *    interval for the hrtimer used to check for OA data.
5343 	 *
5344 	 * 6: Add DRM_I915_PERF_PROP_OA_ENGINE_CLASS and
5345 	 *    DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE
5346 	 *
5347 	 * 7: Add support for video decode and enhancement classes.
5348 	 */
5349 
5350 	/*
5351 	 * Wa_14017512683: mtl[a0..c0): Use of OAM must be preceded with Media
5352 	 * C6 disable in BIOS. If Media C6 is enabled in BIOS, return version 6
5353 	 * to indicate that OA media is not supported.
5354 	 */
5355 	if (IS_MTL_MEDIA_STEP(i915, STEP_A0, STEP_C0)) {
5356 		struct intel_gt *gt;
5357 		int i;
5358 
5359 		for_each_gt(gt, i915, i) {
5360 			if (gt->type == GT_MEDIA &&
5361 			    intel_check_bios_c6_setup(&gt->rc6))
5362 				return 6;
5363 		}
5364 	}
5365 
5366 	return 7;
5367 }
5368 
5369 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5370 #include "selftests/i915_perf.c"
5371 #endif
5372