xref: /openbmc/linux/drivers/gpu/drm/i915/i915_perf.c (revision 49c23519)
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 
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 *
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 
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
430 struct i915_perf_regs *__oa_regs(struct i915_perf_stream *stream)
431 {
432 	return &stream->engine->oa_group->regs;
433 }
434 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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  */
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  */
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  */
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  */
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  */
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  */
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  */
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  */
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  */
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  */
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 
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
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
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
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  */
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 
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 
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 
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 
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  */
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  */
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
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
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
1671 free_noa_wait(struct i915_perf_stream *stream)
1672 {
1673 	i915_vma_unpin_and_release(&stream->noa_wait, 0);
1674 }
1675 
1676 static bool engine_supports_oa(const struct intel_engine_cs *engine)
1677 {
1678 	return engine->oa_group;
1679 }
1680 
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 
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 
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 
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 
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 
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 
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 
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 
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 
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 *
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 *
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
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 
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
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 
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 
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
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
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
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 
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
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 
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 
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
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
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
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
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 
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
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 
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 
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 
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 
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 
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 
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  */
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 
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 
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 
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  */
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 
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
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
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  */
3256 u32 i915_perf_oa_timestamp_frequency(struct drm_i915_private *i915)
3257 {
3258 	struct intel_gt *gt = to_gt(i915);
3259 
3260 	/* Wa_18013179988 */
3261 	if (IS_DG2(i915) || IS_GFX_GT_IP_RANGE(gt, IP_VER(12, 70), IP_VER(12, 74))) {
3262 		intel_wakeref_t wakeref;
3263 		u32 reg, shift;
3264 
3265 		with_intel_runtime_pm(to_gt(i915)->uncore->rpm, wakeref)
3266 			reg = intel_uncore_read(to_gt(i915)->uncore, RPM_CONFIG0);
3267 
3268 		shift = REG_FIELD_GET(GEN10_RPM_CONFIG0_CTC_SHIFT_PARAMETER_MASK,
3269 				      reg);
3270 
3271 		return to_gt(i915)->clock_frequency << (3 - shift);
3272 	}
3273 
3274 	return to_gt(i915)->clock_frequency;
3275 }
3276 
3277 /**
3278  * i915_oa_stream_init - validate combined props for OA stream and init
3279  * @stream: An i915 perf stream
3280  * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
3281  * @props: The property state that configures stream (individually validated)
3282  *
3283  * While read_properties_unlocked() validates properties in isolation it
3284  * doesn't ensure that the combination necessarily makes sense.
3285  *
3286  * At this point it has been determined that userspace wants a stream of
3287  * OA metrics, but still we need to further validate the combined
3288  * properties are OK.
3289  *
3290  * If the configuration makes sense then we can allocate memory for
3291  * a circular OA buffer and apply the requested metric set configuration.
3292  *
3293  * Returns: zero on success or a negative error code.
3294  */
3295 static int i915_oa_stream_init(struct i915_perf_stream *stream,
3296 			       struct drm_i915_perf_open_param *param,
3297 			       struct perf_open_properties *props)
3298 {
3299 	struct drm_i915_private *i915 = stream->perf->i915;
3300 	struct i915_perf *perf = stream->perf;
3301 	struct i915_perf_group *g;
3302 	struct intel_gt *gt;
3303 	int ret;
3304 
3305 	if (!props->engine) {
3306 		drm_dbg(&stream->perf->i915->drm,
3307 			"OA engine not specified\n");
3308 		return -EINVAL;
3309 	}
3310 	gt = props->engine->gt;
3311 	g = props->engine->oa_group;
3312 
3313 	/*
3314 	 * If the sysfs metrics/ directory wasn't registered for some
3315 	 * reason then don't let userspace try their luck with config
3316 	 * IDs
3317 	 */
3318 	if (!perf->metrics_kobj) {
3319 		drm_dbg(&stream->perf->i915->drm,
3320 			"OA metrics weren't advertised via sysfs\n");
3321 		return -EINVAL;
3322 	}
3323 
3324 	if (!(props->sample_flags & SAMPLE_OA_REPORT) &&
3325 	    (GRAPHICS_VER(perf->i915) < 12 || !stream->ctx)) {
3326 		drm_dbg(&stream->perf->i915->drm,
3327 			"Only OA report sampling supported\n");
3328 		return -EINVAL;
3329 	}
3330 
3331 	if (!perf->ops.enable_metric_set) {
3332 		drm_dbg(&stream->perf->i915->drm,
3333 			"OA unit not supported\n");
3334 		return -ENODEV;
3335 	}
3336 
3337 	/*
3338 	 * To avoid the complexity of having to accurately filter
3339 	 * counter reports and marshal to the appropriate client
3340 	 * we currently only allow exclusive access
3341 	 */
3342 	if (g->exclusive_stream) {
3343 		drm_dbg(&stream->perf->i915->drm,
3344 			"OA unit already in use\n");
3345 		return -EBUSY;
3346 	}
3347 
3348 	if (!props->oa_format) {
3349 		drm_dbg(&stream->perf->i915->drm,
3350 			"OA report format not specified\n");
3351 		return -EINVAL;
3352 	}
3353 
3354 	stream->engine = props->engine;
3355 	stream->uncore = stream->engine->gt->uncore;
3356 
3357 	stream->sample_size = sizeof(struct drm_i915_perf_record_header);
3358 
3359 	stream->oa_buffer.format = &perf->oa_formats[props->oa_format];
3360 	if (drm_WARN_ON(&i915->drm, stream->oa_buffer.format->size == 0))
3361 		return -EINVAL;
3362 
3363 	stream->sample_flags = props->sample_flags;
3364 	stream->sample_size += stream->oa_buffer.format->size;
3365 
3366 	stream->hold_preemption = props->hold_preemption;
3367 
3368 	stream->periodic = props->oa_periodic;
3369 	if (stream->periodic)
3370 		stream->period_exponent = props->oa_period_exponent;
3371 
3372 	if (stream->ctx) {
3373 		ret = oa_get_render_ctx_id(stream);
3374 		if (ret) {
3375 			drm_dbg(&stream->perf->i915->drm,
3376 				"Invalid context id to filter with\n");
3377 			return ret;
3378 		}
3379 	}
3380 
3381 	ret = alloc_noa_wait(stream);
3382 	if (ret) {
3383 		drm_dbg(&stream->perf->i915->drm,
3384 			"Unable to allocate NOA wait batch buffer\n");
3385 		goto err_noa_wait_alloc;
3386 	}
3387 
3388 	stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
3389 	if (!stream->oa_config) {
3390 		drm_dbg(&stream->perf->i915->drm,
3391 			"Invalid OA config id=%i\n", props->metrics_set);
3392 		ret = -EINVAL;
3393 		goto err_config;
3394 	}
3395 
3396 	/* PRM - observability performance counters:
3397 	 *
3398 	 *   OACONTROL, performance counter enable, note:
3399 	 *
3400 	 *   "When this bit is set, in order to have coherent counts,
3401 	 *   RC6 power state and trunk clock gating must be disabled.
3402 	 *   This can be achieved by programming MMIO registers as
3403 	 *   0xA094=0 and 0xA090[31]=1"
3404 	 *
3405 	 *   In our case we are expecting that taking pm + FORCEWAKE
3406 	 *   references will effectively disable RC6.
3407 	 */
3408 	intel_engine_pm_get(stream->engine);
3409 	intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
3410 
3411 	/*
3412 	 * Wa_16011777198:dg2: GuC resets render as part of the Wa. This causes
3413 	 * OA to lose the configuration state. Prevent this by overriding GUCRC
3414 	 * mode.
3415 	 */
3416 	if (intel_uc_uses_guc_rc(&gt->uc) &&
3417 	    (IS_DG2_GRAPHICS_STEP(gt->i915, G10, STEP_A0, STEP_C0) ||
3418 	     IS_DG2_GRAPHICS_STEP(gt->i915, G11, STEP_A0, STEP_B0))) {
3419 		ret = intel_guc_slpc_override_gucrc_mode(&gt->uc.guc.slpc,
3420 							 SLPC_GUCRC_MODE_GUCRC_NO_RC6);
3421 		if (ret) {
3422 			drm_dbg(&stream->perf->i915->drm,
3423 				"Unable to override gucrc mode\n");
3424 			goto err_gucrc;
3425 		}
3426 
3427 		stream->override_gucrc = true;
3428 	}
3429 
3430 	ret = alloc_oa_buffer(stream);
3431 	if (ret)
3432 		goto err_oa_buf_alloc;
3433 
3434 	stream->ops = &i915_oa_stream_ops;
3435 
3436 	stream->engine->gt->perf.sseu = props->sseu;
3437 	WRITE_ONCE(g->exclusive_stream, stream);
3438 
3439 	ret = i915_perf_stream_enable_sync(stream);
3440 	if (ret) {
3441 		drm_dbg(&stream->perf->i915->drm,
3442 			"Unable to enable metric set\n");
3443 		goto err_enable;
3444 	}
3445 
3446 	drm_dbg(&stream->perf->i915->drm,
3447 		"opening stream oa config uuid=%s\n",
3448 		  stream->oa_config->uuid);
3449 
3450 	hrtimer_init(&stream->poll_check_timer,
3451 		     CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3452 	stream->poll_check_timer.function = oa_poll_check_timer_cb;
3453 	init_waitqueue_head(&stream->poll_wq);
3454 	spin_lock_init(&stream->oa_buffer.ptr_lock);
3455 	mutex_init(&stream->lock);
3456 
3457 	return 0;
3458 
3459 err_enable:
3460 	WRITE_ONCE(g->exclusive_stream, NULL);
3461 	perf->ops.disable_metric_set(stream);
3462 
3463 	free_oa_buffer(stream);
3464 
3465 err_oa_buf_alloc:
3466 	if (stream->override_gucrc)
3467 		intel_guc_slpc_unset_gucrc_mode(&gt->uc.guc.slpc);
3468 
3469 err_gucrc:
3470 	intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
3471 	intel_engine_pm_put(stream->engine);
3472 
3473 	free_oa_configs(stream);
3474 
3475 err_config:
3476 	free_noa_wait(stream);
3477 
3478 err_noa_wait_alloc:
3479 	if (stream->ctx)
3480 		oa_put_render_ctx_id(stream);
3481 
3482 	return ret;
3483 }
3484 
3485 void i915_oa_init_reg_state(const struct intel_context *ce,
3486 			    const struct intel_engine_cs *engine)
3487 {
3488 	struct i915_perf_stream *stream;
3489 
3490 	if (engine->class != RENDER_CLASS)
3491 		return;
3492 
3493 	/* perf.exclusive_stream serialised by lrc_configure_all_contexts() */
3494 	stream = READ_ONCE(engine->oa_group->exclusive_stream);
3495 	if (stream && GRAPHICS_VER(stream->perf->i915) < 12)
3496 		gen8_update_reg_state_unlocked(ce, stream);
3497 }
3498 
3499 /**
3500  * i915_perf_read - handles read() FOP for i915 perf stream FDs
3501  * @file: An i915 perf stream file
3502  * @buf: destination buffer given by userspace
3503  * @count: the number of bytes userspace wants to read
3504  * @ppos: (inout) file seek position (unused)
3505  *
3506  * The entry point for handling a read() on a stream file descriptor from
3507  * userspace. Most of the work is left to the i915_perf_read_locked() and
3508  * &i915_perf_stream_ops->read but to save having stream implementations (of
3509  * which we might have multiple later) we handle blocking read here.
3510  *
3511  * We can also consistently treat trying to read from a disabled stream
3512  * as an IO error so implementations can assume the stream is enabled
3513  * while reading.
3514  *
3515  * Returns: The number of bytes copied or a negative error code on failure.
3516  */
3517 static ssize_t i915_perf_read(struct file *file,
3518 			      char __user *buf,
3519 			      size_t count,
3520 			      loff_t *ppos)
3521 {
3522 	struct i915_perf_stream *stream = file->private_data;
3523 	size_t offset = 0;
3524 	int ret;
3525 
3526 	/* To ensure it's handled consistently we simply treat all reads of a
3527 	 * disabled stream as an error. In particular it might otherwise lead
3528 	 * to a deadlock for blocking file descriptors...
3529 	 */
3530 	if (!stream->enabled || !(stream->sample_flags & SAMPLE_OA_REPORT))
3531 		return -EIO;
3532 
3533 	if (!(file->f_flags & O_NONBLOCK)) {
3534 		/* There's the small chance of false positives from
3535 		 * stream->ops->wait_unlocked.
3536 		 *
3537 		 * E.g. with single context filtering since we only wait until
3538 		 * oabuffer has >= 1 report we don't immediately know whether
3539 		 * any reports really belong to the current context
3540 		 */
3541 		do {
3542 			ret = stream->ops->wait_unlocked(stream);
3543 			if (ret)
3544 				return ret;
3545 
3546 			mutex_lock(&stream->lock);
3547 			ret = stream->ops->read(stream, buf, count, &offset);
3548 			mutex_unlock(&stream->lock);
3549 		} while (!offset && !ret);
3550 	} else {
3551 		mutex_lock(&stream->lock);
3552 		ret = stream->ops->read(stream, buf, count, &offset);
3553 		mutex_unlock(&stream->lock);
3554 	}
3555 
3556 	/* We allow the poll checking to sometimes report false positive EPOLLIN
3557 	 * events where we might actually report EAGAIN on read() if there's
3558 	 * not really any data available. In this situation though we don't
3559 	 * want to enter a busy loop between poll() reporting a EPOLLIN event
3560 	 * and read() returning -EAGAIN. Clearing the oa.pollin state here
3561 	 * effectively ensures we back off until the next hrtimer callback
3562 	 * before reporting another EPOLLIN event.
3563 	 * The exception to this is if ops->read() returned -ENOSPC which means
3564 	 * that more OA data is available than could fit in the user provided
3565 	 * buffer. In this case we want the next poll() call to not block.
3566 	 */
3567 	if (ret != -ENOSPC)
3568 		stream->pollin = false;
3569 
3570 	/* Possible values for ret are 0, -EFAULT, -ENOSPC, -EIO, ... */
3571 	return offset ?: (ret ?: -EAGAIN);
3572 }
3573 
3574 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
3575 {
3576 	struct i915_perf_stream *stream =
3577 		container_of(hrtimer, typeof(*stream), poll_check_timer);
3578 
3579 	if (oa_buffer_check_unlocked(stream)) {
3580 		stream->pollin = true;
3581 		wake_up(&stream->poll_wq);
3582 	}
3583 
3584 	hrtimer_forward_now(hrtimer,
3585 			    ns_to_ktime(stream->poll_oa_period));
3586 
3587 	return HRTIMER_RESTART;
3588 }
3589 
3590 /**
3591  * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
3592  * @stream: An i915 perf stream
3593  * @file: An i915 perf stream file
3594  * @wait: poll() state table
3595  *
3596  * For handling userspace polling on an i915 perf stream, this calls through to
3597  * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
3598  * will be woken for new stream data.
3599  *
3600  * Returns: any poll events that are ready without sleeping
3601  */
3602 static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
3603 				      struct file *file,
3604 				      poll_table *wait)
3605 {
3606 	__poll_t events = 0;
3607 
3608 	stream->ops->poll_wait(stream, file, wait);
3609 
3610 	/* Note: we don't explicitly check whether there's something to read
3611 	 * here since this path may be very hot depending on what else
3612 	 * userspace is polling, or on the timeout in use. We rely solely on
3613 	 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
3614 	 * samples to read.
3615 	 */
3616 	if (stream->pollin)
3617 		events |= EPOLLIN;
3618 
3619 	return events;
3620 }
3621 
3622 /**
3623  * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
3624  * @file: An i915 perf stream file
3625  * @wait: poll() state table
3626  *
3627  * For handling userspace polling on an i915 perf stream, this ensures
3628  * poll_wait() gets called with a wait queue that will be woken for new stream
3629  * data.
3630  *
3631  * Note: Implementation deferred to i915_perf_poll_locked()
3632  *
3633  * Returns: any poll events that are ready without sleeping
3634  */
3635 static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
3636 {
3637 	struct i915_perf_stream *stream = file->private_data;
3638 	__poll_t ret;
3639 
3640 	mutex_lock(&stream->lock);
3641 	ret = i915_perf_poll_locked(stream, file, wait);
3642 	mutex_unlock(&stream->lock);
3643 
3644 	return ret;
3645 }
3646 
3647 /**
3648  * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
3649  * @stream: A disabled i915 perf stream
3650  *
3651  * [Re]enables the associated capture of data for this stream.
3652  *
3653  * If a stream was previously enabled then there's currently no intention
3654  * to provide userspace any guarantee about the preservation of previously
3655  * buffered data.
3656  */
3657 static void i915_perf_enable_locked(struct i915_perf_stream *stream)
3658 {
3659 	if (stream->enabled)
3660 		return;
3661 
3662 	/* Allow stream->ops->enable() to refer to this */
3663 	stream->enabled = true;
3664 
3665 	if (stream->ops->enable)
3666 		stream->ops->enable(stream);
3667 
3668 	if (stream->hold_preemption)
3669 		intel_context_set_nopreempt(stream->pinned_ctx);
3670 }
3671 
3672 /**
3673  * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
3674  * @stream: An enabled i915 perf stream
3675  *
3676  * Disables the associated capture of data for this stream.
3677  *
3678  * The intention is that disabling an re-enabling a stream will ideally be
3679  * cheaper than destroying and re-opening a stream with the same configuration,
3680  * though there are no formal guarantees about what state or buffered data
3681  * must be retained between disabling and re-enabling a stream.
3682  *
3683  * Note: while a stream is disabled it's considered an error for userspace
3684  * to attempt to read from the stream (-EIO).
3685  */
3686 static void i915_perf_disable_locked(struct i915_perf_stream *stream)
3687 {
3688 	if (!stream->enabled)
3689 		return;
3690 
3691 	/* Allow stream->ops->disable() to refer to this */
3692 	stream->enabled = false;
3693 
3694 	if (stream->hold_preemption)
3695 		intel_context_clear_nopreempt(stream->pinned_ctx);
3696 
3697 	if (stream->ops->disable)
3698 		stream->ops->disable(stream);
3699 }
3700 
3701 static long i915_perf_config_locked(struct i915_perf_stream *stream,
3702 				    unsigned long metrics_set)
3703 {
3704 	struct i915_oa_config *config;
3705 	long ret = stream->oa_config->id;
3706 
3707 	config = i915_perf_get_oa_config(stream->perf, metrics_set);
3708 	if (!config)
3709 		return -EINVAL;
3710 
3711 	if (config != stream->oa_config) {
3712 		int err;
3713 
3714 		/*
3715 		 * If OA is bound to a specific context, emit the
3716 		 * reconfiguration inline from that context. The update
3717 		 * will then be ordered with respect to submission on that
3718 		 * context.
3719 		 *
3720 		 * When set globally, we use a low priority kernel context,
3721 		 * so it will effectively take effect when idle.
3722 		 */
3723 		err = emit_oa_config(stream, config, oa_context(stream), NULL);
3724 		if (!err)
3725 			config = xchg(&stream->oa_config, config);
3726 		else
3727 			ret = err;
3728 	}
3729 
3730 	i915_oa_config_put(config);
3731 
3732 	return ret;
3733 }
3734 
3735 /**
3736  * i915_perf_ioctl_locked - support ioctl() usage with i915 perf stream FDs
3737  * @stream: An i915 perf stream
3738  * @cmd: the ioctl request
3739  * @arg: the ioctl data
3740  *
3741  * Returns: zero on success or a negative error code. Returns -EINVAL for
3742  * an unknown ioctl request.
3743  */
3744 static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
3745 				   unsigned int cmd,
3746 				   unsigned long arg)
3747 {
3748 	switch (cmd) {
3749 	case I915_PERF_IOCTL_ENABLE:
3750 		i915_perf_enable_locked(stream);
3751 		return 0;
3752 	case I915_PERF_IOCTL_DISABLE:
3753 		i915_perf_disable_locked(stream);
3754 		return 0;
3755 	case I915_PERF_IOCTL_CONFIG:
3756 		return i915_perf_config_locked(stream, arg);
3757 	}
3758 
3759 	return -EINVAL;
3760 }
3761 
3762 /**
3763  * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
3764  * @file: An i915 perf stream file
3765  * @cmd: the ioctl request
3766  * @arg: the ioctl data
3767  *
3768  * Implementation deferred to i915_perf_ioctl_locked().
3769  *
3770  * Returns: zero on success or a negative error code. Returns -EINVAL for
3771  * an unknown ioctl request.
3772  */
3773 static long i915_perf_ioctl(struct file *file,
3774 			    unsigned int cmd,
3775 			    unsigned long arg)
3776 {
3777 	struct i915_perf_stream *stream = file->private_data;
3778 	long ret;
3779 
3780 	mutex_lock(&stream->lock);
3781 	ret = i915_perf_ioctl_locked(stream, cmd, arg);
3782 	mutex_unlock(&stream->lock);
3783 
3784 	return ret;
3785 }
3786 
3787 /**
3788  * i915_perf_destroy_locked - destroy an i915 perf stream
3789  * @stream: An i915 perf stream
3790  *
3791  * Frees all resources associated with the given i915 perf @stream, disabling
3792  * any associated data capture in the process.
3793  *
3794  * Note: The &gt->perf.lock mutex has been taken to serialize
3795  * with any non-file-operation driver hooks.
3796  */
3797 static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
3798 {
3799 	if (stream->enabled)
3800 		i915_perf_disable_locked(stream);
3801 
3802 	if (stream->ops->destroy)
3803 		stream->ops->destroy(stream);
3804 
3805 	if (stream->ctx)
3806 		i915_gem_context_put(stream->ctx);
3807 
3808 	kfree(stream);
3809 }
3810 
3811 /**
3812  * i915_perf_release - handles userspace close() of a stream file
3813  * @inode: anonymous inode associated with file
3814  * @file: An i915 perf stream file
3815  *
3816  * Cleans up any resources associated with an open i915 perf stream file.
3817  *
3818  * NB: close() can't really fail from the userspace point of view.
3819  *
3820  * Returns: zero on success or a negative error code.
3821  */
3822 static int i915_perf_release(struct inode *inode, struct file *file)
3823 {
3824 	struct i915_perf_stream *stream = file->private_data;
3825 	struct i915_perf *perf = stream->perf;
3826 	struct intel_gt *gt = stream->engine->gt;
3827 
3828 	/*
3829 	 * Within this call, we know that the fd is being closed and we have no
3830 	 * other user of stream->lock. Use the perf lock to destroy the stream
3831 	 * here.
3832 	 */
3833 	mutex_lock(&gt->perf.lock);
3834 	i915_perf_destroy_locked(stream);
3835 	mutex_unlock(&gt->perf.lock);
3836 
3837 	/* Release the reference the perf stream kept on the driver. */
3838 	drm_dev_put(&perf->i915->drm);
3839 
3840 	return 0;
3841 }
3842 
3843 
3844 static const struct file_operations fops = {
3845 	.owner		= THIS_MODULE,
3846 	.llseek		= no_llseek,
3847 	.release	= i915_perf_release,
3848 	.poll		= i915_perf_poll,
3849 	.read		= i915_perf_read,
3850 	.unlocked_ioctl	= i915_perf_ioctl,
3851 	/* Our ioctl have no arguments, so it's safe to use the same function
3852 	 * to handle 32bits compatibility.
3853 	 */
3854 	.compat_ioctl   = i915_perf_ioctl,
3855 };
3856 
3857 
3858 /**
3859  * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
3860  * @perf: i915 perf instance
3861  * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
3862  * @props: individually validated u64 property value pairs
3863  * @file: drm file
3864  *
3865  * See i915_perf_ioctl_open() for interface details.
3866  *
3867  * Implements further stream config validation and stream initialization on
3868  * behalf of i915_perf_open_ioctl() with the &gt->perf.lock mutex
3869  * taken to serialize with any non-file-operation driver hooks.
3870  *
3871  * Note: at this point the @props have only been validated in isolation and
3872  * it's still necessary to validate that the combination of properties makes
3873  * sense.
3874  *
3875  * In the case where userspace is interested in OA unit metrics then further
3876  * config validation and stream initialization details will be handled by
3877  * i915_oa_stream_init(). The code here should only validate config state that
3878  * will be relevant to all stream types / backends.
3879  *
3880  * Returns: zero on success or a negative error code.
3881  */
3882 static int
3883 i915_perf_open_ioctl_locked(struct i915_perf *perf,
3884 			    struct drm_i915_perf_open_param *param,
3885 			    struct perf_open_properties *props,
3886 			    struct drm_file *file)
3887 {
3888 	struct i915_gem_context *specific_ctx = NULL;
3889 	struct i915_perf_stream *stream = NULL;
3890 	unsigned long f_flags = 0;
3891 	bool privileged_op = true;
3892 	int stream_fd;
3893 	int ret;
3894 
3895 	if (props->single_context) {
3896 		u32 ctx_handle = props->ctx_handle;
3897 		struct drm_i915_file_private *file_priv = file->driver_priv;
3898 
3899 		specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
3900 		if (IS_ERR(specific_ctx)) {
3901 			drm_dbg(&perf->i915->drm,
3902 				"Failed to look up context with ID %u for opening perf stream\n",
3903 				  ctx_handle);
3904 			ret = PTR_ERR(specific_ctx);
3905 			goto err;
3906 		}
3907 	}
3908 
3909 	/*
3910 	 * On Haswell the OA unit supports clock gating off for a specific
3911 	 * context and in this mode there's no visibility of metrics for the
3912 	 * rest of the system, which we consider acceptable for a
3913 	 * non-privileged client.
3914 	 *
3915 	 * For Gen8->11 the OA unit no longer supports clock gating off for a
3916 	 * specific context and the kernel can't securely stop the counters
3917 	 * from updating as system-wide / global values. Even though we can
3918 	 * filter reports based on the included context ID we can't block
3919 	 * clients from seeing the raw / global counter values via
3920 	 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
3921 	 * enable the OA unit by default.
3922 	 *
3923 	 * For Gen12+ we gain a new OAR unit that only monitors the RCS on a
3924 	 * per context basis. So we can relax requirements there if the user
3925 	 * doesn't request global stream access (i.e. query based sampling
3926 	 * using MI_RECORD_PERF_COUNT.
3927 	 */
3928 	if (IS_HASWELL(perf->i915) && specific_ctx)
3929 		privileged_op = false;
3930 	else if (GRAPHICS_VER(perf->i915) == 12 && specific_ctx &&
3931 		 (props->sample_flags & SAMPLE_OA_REPORT) == 0)
3932 		privileged_op = false;
3933 
3934 	if (props->hold_preemption) {
3935 		if (!props->single_context) {
3936 			drm_dbg(&perf->i915->drm,
3937 				"preemption disable with no context\n");
3938 			ret = -EINVAL;
3939 			goto err;
3940 		}
3941 		privileged_op = true;
3942 	}
3943 
3944 	/*
3945 	 * Asking for SSEU configuration is a priviliged operation.
3946 	 */
3947 	if (props->has_sseu)
3948 		privileged_op = true;
3949 	else
3950 		get_default_sseu_config(&props->sseu, props->engine);
3951 
3952 	/* Similar to perf's kernel.perf_paranoid_cpu sysctl option
3953 	 * we check a dev.i915.perf_stream_paranoid sysctl option
3954 	 * to determine if it's ok to access system wide OA counters
3955 	 * without CAP_PERFMON or CAP_SYS_ADMIN privileges.
3956 	 */
3957 	if (privileged_op &&
3958 	    i915_perf_stream_paranoid && !perfmon_capable()) {
3959 		drm_dbg(&perf->i915->drm,
3960 			"Insufficient privileges to open i915 perf stream\n");
3961 		ret = -EACCES;
3962 		goto err_ctx;
3963 	}
3964 
3965 	stream = kzalloc(sizeof(*stream), GFP_KERNEL);
3966 	if (!stream) {
3967 		ret = -ENOMEM;
3968 		goto err_ctx;
3969 	}
3970 
3971 	stream->perf = perf;
3972 	stream->ctx = specific_ctx;
3973 	stream->poll_oa_period = props->poll_oa_period;
3974 
3975 	ret = i915_oa_stream_init(stream, param, props);
3976 	if (ret)
3977 		goto err_alloc;
3978 
3979 	/* we avoid simply assigning stream->sample_flags = props->sample_flags
3980 	 * to have _stream_init check the combination of sample flags more
3981 	 * thoroughly, but still this is the expected result at this point.
3982 	 */
3983 	if (WARN_ON(stream->sample_flags != props->sample_flags)) {
3984 		ret = -ENODEV;
3985 		goto err_flags;
3986 	}
3987 
3988 	if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
3989 		f_flags |= O_CLOEXEC;
3990 	if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
3991 		f_flags |= O_NONBLOCK;
3992 
3993 	stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
3994 	if (stream_fd < 0) {
3995 		ret = stream_fd;
3996 		goto err_flags;
3997 	}
3998 
3999 	if (!(param->flags & I915_PERF_FLAG_DISABLED))
4000 		i915_perf_enable_locked(stream);
4001 
4002 	/* Take a reference on the driver that will be kept with stream_fd
4003 	 * until its release.
4004 	 */
4005 	drm_dev_get(&perf->i915->drm);
4006 
4007 	return stream_fd;
4008 
4009 err_flags:
4010 	if (stream->ops->destroy)
4011 		stream->ops->destroy(stream);
4012 err_alloc:
4013 	kfree(stream);
4014 err_ctx:
4015 	if (specific_ctx)
4016 		i915_gem_context_put(specific_ctx);
4017 err:
4018 	return ret;
4019 }
4020 
4021 static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
4022 {
4023 	u64 nom = (2ULL << exponent) * NSEC_PER_SEC;
4024 	u32 den = i915_perf_oa_timestamp_frequency(perf->i915);
4025 
4026 	return div_u64(nom + den - 1, den);
4027 }
4028 
4029 static __always_inline bool
4030 oa_format_valid(struct i915_perf *perf, enum drm_i915_oa_format format)
4031 {
4032 	return test_bit(format, perf->format_mask);
4033 }
4034 
4035 static __always_inline void
4036 oa_format_add(struct i915_perf *perf, enum drm_i915_oa_format format)
4037 {
4038 	__set_bit(format, perf->format_mask);
4039 }
4040 
4041 /**
4042  * read_properties_unlocked - validate + copy userspace stream open properties
4043  * @perf: i915 perf instance
4044  * @uprops: The array of u64 key value pairs given by userspace
4045  * @n_props: The number of key value pairs expected in @uprops
4046  * @props: The stream configuration built up while validating properties
4047  *
4048  * Note this function only validates properties in isolation it doesn't
4049  * validate that the combination of properties makes sense or that all
4050  * properties necessary for a particular kind of stream have been set.
4051  *
4052  * Note that there currently aren't any ordering requirements for properties so
4053  * we shouldn't validate or assume anything about ordering here. This doesn't
4054  * rule out defining new properties with ordering requirements in the future.
4055  */
4056 static int read_properties_unlocked(struct i915_perf *perf,
4057 				    u64 __user *uprops,
4058 				    u32 n_props,
4059 				    struct perf_open_properties *props)
4060 {
4061 	struct drm_i915_gem_context_param_sseu user_sseu;
4062 	const struct i915_oa_format *f;
4063 	u64 __user *uprop = uprops;
4064 	bool config_instance = false;
4065 	bool config_class = false;
4066 	bool config_sseu = false;
4067 	u8 class, instance;
4068 	u32 i;
4069 	int ret;
4070 
4071 	memset(props, 0, sizeof(struct perf_open_properties));
4072 	props->poll_oa_period = DEFAULT_POLL_PERIOD_NS;
4073 
4074 	/* Considering that ID = 0 is reserved and assuming that we don't
4075 	 * (currently) expect any configurations to ever specify duplicate
4076 	 * values for a particular property ID then the last _PROP_MAX value is
4077 	 * one greater than the maximum number of properties we expect to get
4078 	 * from userspace.
4079 	 */
4080 	if (!n_props || n_props >= DRM_I915_PERF_PROP_MAX) {
4081 		drm_dbg(&perf->i915->drm,
4082 			"Invalid number of i915 perf properties given\n");
4083 		return -EINVAL;
4084 	}
4085 
4086 	/* Defaults when class:instance is not passed */
4087 	class = I915_ENGINE_CLASS_RENDER;
4088 	instance = 0;
4089 
4090 	for (i = 0; i < n_props; i++) {
4091 		u64 oa_period, oa_freq_hz;
4092 		u64 id, value;
4093 
4094 		ret = get_user(id, uprop);
4095 		if (ret)
4096 			return ret;
4097 
4098 		ret = get_user(value, uprop + 1);
4099 		if (ret)
4100 			return ret;
4101 
4102 		if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
4103 			drm_dbg(&perf->i915->drm,
4104 				"Unknown i915 perf property ID\n");
4105 			return -EINVAL;
4106 		}
4107 
4108 		switch ((enum drm_i915_perf_property_id)id) {
4109 		case DRM_I915_PERF_PROP_CTX_HANDLE:
4110 			props->single_context = 1;
4111 			props->ctx_handle = value;
4112 			break;
4113 		case DRM_I915_PERF_PROP_SAMPLE_OA:
4114 			if (value)
4115 				props->sample_flags |= SAMPLE_OA_REPORT;
4116 			break;
4117 		case DRM_I915_PERF_PROP_OA_METRICS_SET:
4118 			if (value == 0) {
4119 				drm_dbg(&perf->i915->drm,
4120 					"Unknown OA metric set ID\n");
4121 				return -EINVAL;
4122 			}
4123 			props->metrics_set = value;
4124 			break;
4125 		case DRM_I915_PERF_PROP_OA_FORMAT:
4126 			if (value == 0 || value >= I915_OA_FORMAT_MAX) {
4127 				drm_dbg(&perf->i915->drm,
4128 					"Out-of-range OA report format %llu\n",
4129 					  value);
4130 				return -EINVAL;
4131 			}
4132 			if (!oa_format_valid(perf, value)) {
4133 				drm_dbg(&perf->i915->drm,
4134 					"Unsupported OA report format %llu\n",
4135 					  value);
4136 				return -EINVAL;
4137 			}
4138 			props->oa_format = value;
4139 			break;
4140 		case DRM_I915_PERF_PROP_OA_EXPONENT:
4141 			if (value > OA_EXPONENT_MAX) {
4142 				drm_dbg(&perf->i915->drm,
4143 					"OA timer exponent too high (> %u)\n",
4144 					 OA_EXPONENT_MAX);
4145 				return -EINVAL;
4146 			}
4147 
4148 			/* Theoretically we can program the OA unit to sample
4149 			 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
4150 			 * for BXT. We don't allow such high sampling
4151 			 * frequencies by default unless root.
4152 			 */
4153 
4154 			BUILD_BUG_ON(sizeof(oa_period) != 8);
4155 			oa_period = oa_exponent_to_ns(perf, value);
4156 
4157 			/* This check is primarily to ensure that oa_period <=
4158 			 * UINT32_MAX (before passing to do_div which only
4159 			 * accepts a u32 denominator), but we can also skip
4160 			 * checking anything < 1Hz which implicitly can't be
4161 			 * limited via an integer oa_max_sample_rate.
4162 			 */
4163 			if (oa_period <= NSEC_PER_SEC) {
4164 				u64 tmp = NSEC_PER_SEC;
4165 				do_div(tmp, oa_period);
4166 				oa_freq_hz = tmp;
4167 			} else
4168 				oa_freq_hz = 0;
4169 
4170 			if (oa_freq_hz > i915_oa_max_sample_rate && !perfmon_capable()) {
4171 				drm_dbg(&perf->i915->drm,
4172 					"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",
4173 					  i915_oa_max_sample_rate);
4174 				return -EACCES;
4175 			}
4176 
4177 			props->oa_periodic = true;
4178 			props->oa_period_exponent = value;
4179 			break;
4180 		case DRM_I915_PERF_PROP_HOLD_PREEMPTION:
4181 			props->hold_preemption = !!value;
4182 			break;
4183 		case DRM_I915_PERF_PROP_GLOBAL_SSEU: {
4184 			if (GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 50)) {
4185 				drm_dbg(&perf->i915->drm,
4186 					"SSEU config not supported on gfx %x\n",
4187 					GRAPHICS_VER_FULL(perf->i915));
4188 				return -ENODEV;
4189 			}
4190 
4191 			if (copy_from_user(&user_sseu,
4192 					   u64_to_user_ptr(value),
4193 					   sizeof(user_sseu))) {
4194 				drm_dbg(&perf->i915->drm,
4195 					"Unable to copy global sseu parameter\n");
4196 				return -EFAULT;
4197 			}
4198 			config_sseu = true;
4199 			break;
4200 		}
4201 		case DRM_I915_PERF_PROP_POLL_OA_PERIOD:
4202 			if (value < 100000 /* 100us */) {
4203 				drm_dbg(&perf->i915->drm,
4204 					"OA availability timer too small (%lluns < 100us)\n",
4205 					  value);
4206 				return -EINVAL;
4207 			}
4208 			props->poll_oa_period = value;
4209 			break;
4210 		case DRM_I915_PERF_PROP_OA_ENGINE_CLASS:
4211 			class = (u8)value;
4212 			config_class = true;
4213 			break;
4214 		case DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE:
4215 			instance = (u8)value;
4216 			config_instance = true;
4217 			break;
4218 		default:
4219 			MISSING_CASE(id);
4220 			return -EINVAL;
4221 		}
4222 
4223 		uprop += 2;
4224 	}
4225 
4226 	if ((config_class && !config_instance) ||
4227 	    (config_instance && !config_class)) {
4228 		drm_dbg(&perf->i915->drm,
4229 			"OA engine-class and engine-instance parameters must be passed together\n");
4230 		return -EINVAL;
4231 	}
4232 
4233 	props->engine = intel_engine_lookup_user(perf->i915, class, instance);
4234 	if (!props->engine) {
4235 		drm_dbg(&perf->i915->drm,
4236 			"OA engine class and instance invalid %d:%d\n",
4237 			class, instance);
4238 		return -EINVAL;
4239 	}
4240 
4241 	if (!engine_supports_oa(props->engine)) {
4242 		drm_dbg(&perf->i915->drm,
4243 			"Engine not supported by OA %d:%d\n",
4244 			class, instance);
4245 		return -EINVAL;
4246 	}
4247 
4248 	/*
4249 	 * Wa_14017512683: mtl[a0..c0): Use of OAM must be preceded with Media
4250 	 * C6 disable in BIOS. Fail if Media C6 is enabled on steppings where OAM
4251 	 * does not work as expected.
4252 	 */
4253 	if (IS_MTL_MEDIA_STEP(props->engine->i915, STEP_A0, STEP_C0) &&
4254 	    props->engine->oa_group->type == TYPE_OAM &&
4255 	    intel_check_bios_c6_setup(&props->engine->gt->rc6)) {
4256 		drm_dbg(&perf->i915->drm,
4257 			"OAM requires media C6 to be disabled in BIOS\n");
4258 		return -EINVAL;
4259 	}
4260 
4261 	i = array_index_nospec(props->oa_format, I915_OA_FORMAT_MAX);
4262 	f = &perf->oa_formats[i];
4263 	if (!engine_supports_oa_format(props->engine, f->type)) {
4264 		drm_dbg(&perf->i915->drm,
4265 			"Invalid OA format %d for class %d\n",
4266 			f->type, props->engine->class);
4267 		return -EINVAL;
4268 	}
4269 
4270 	if (config_sseu) {
4271 		ret = get_sseu_config(&props->sseu, props->engine, &user_sseu);
4272 		if (ret) {
4273 			drm_dbg(&perf->i915->drm,
4274 				"Invalid SSEU configuration\n");
4275 			return ret;
4276 		}
4277 		props->has_sseu = true;
4278 	}
4279 
4280 	return 0;
4281 }
4282 
4283 /**
4284  * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
4285  * @dev: drm device
4286  * @data: ioctl data copied from userspace (unvalidated)
4287  * @file: drm file
4288  *
4289  * Validates the stream open parameters given by userspace including flags
4290  * and an array of u64 key, value pair properties.
4291  *
4292  * Very little is assumed up front about the nature of the stream being
4293  * opened (for instance we don't assume it's for periodic OA unit metrics). An
4294  * i915-perf stream is expected to be a suitable interface for other forms of
4295  * buffered data written by the GPU besides periodic OA metrics.
4296  *
4297  * Note we copy the properties from userspace outside of the i915 perf
4298  * mutex to avoid an awkward lockdep with mmap_lock.
4299  *
4300  * Most of the implementation details are handled by
4301  * i915_perf_open_ioctl_locked() after taking the &gt->perf.lock
4302  * mutex for serializing with any non-file-operation driver hooks.
4303  *
4304  * Return: A newly opened i915 Perf stream file descriptor or negative
4305  * error code on failure.
4306  */
4307 int i915_perf_open_ioctl(struct drm_device *dev, void *data,
4308 			 struct drm_file *file)
4309 {
4310 	struct i915_perf *perf = &to_i915(dev)->perf;
4311 	struct drm_i915_perf_open_param *param = data;
4312 	struct intel_gt *gt;
4313 	struct perf_open_properties props;
4314 	u32 known_open_flags;
4315 	int ret;
4316 
4317 	if (!perf->i915)
4318 		return -ENOTSUPP;
4319 
4320 	known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
4321 			   I915_PERF_FLAG_FD_NONBLOCK |
4322 			   I915_PERF_FLAG_DISABLED;
4323 	if (param->flags & ~known_open_flags) {
4324 		drm_dbg(&perf->i915->drm,
4325 			"Unknown drm_i915_perf_open_param flag\n");
4326 		return -EINVAL;
4327 	}
4328 
4329 	ret = read_properties_unlocked(perf,
4330 				       u64_to_user_ptr(param->properties_ptr),
4331 				       param->num_properties,
4332 				       &props);
4333 	if (ret)
4334 		return ret;
4335 
4336 	gt = props.engine->gt;
4337 
4338 	mutex_lock(&gt->perf.lock);
4339 	ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
4340 	mutex_unlock(&gt->perf.lock);
4341 
4342 	return ret;
4343 }
4344 
4345 /**
4346  * i915_perf_register - exposes i915-perf to userspace
4347  * @i915: i915 device instance
4348  *
4349  * In particular OA metric sets are advertised under a sysfs metrics/
4350  * directory allowing userspace to enumerate valid IDs that can be
4351  * used to open an i915-perf stream.
4352  */
4353 void i915_perf_register(struct drm_i915_private *i915)
4354 {
4355 	struct i915_perf *perf = &i915->perf;
4356 	struct intel_gt *gt = to_gt(i915);
4357 
4358 	if (!perf->i915)
4359 		return;
4360 
4361 	/* To be sure we're synchronized with an attempted
4362 	 * i915_perf_open_ioctl(); considering that we register after
4363 	 * being exposed to userspace.
4364 	 */
4365 	mutex_lock(&gt->perf.lock);
4366 
4367 	perf->metrics_kobj =
4368 		kobject_create_and_add("metrics",
4369 				       &i915->drm.primary->kdev->kobj);
4370 
4371 	mutex_unlock(&gt->perf.lock);
4372 }
4373 
4374 /**
4375  * i915_perf_unregister - hide i915-perf from userspace
4376  * @i915: i915 device instance
4377  *
4378  * i915-perf state cleanup is split up into an 'unregister' and
4379  * 'deinit' phase where the interface is first hidden from
4380  * userspace by i915_perf_unregister() before cleaning up
4381  * remaining state in i915_perf_fini().
4382  */
4383 void i915_perf_unregister(struct drm_i915_private *i915)
4384 {
4385 	struct i915_perf *perf = &i915->perf;
4386 
4387 	if (!perf->metrics_kobj)
4388 		return;
4389 
4390 	kobject_put(perf->metrics_kobj);
4391 	perf->metrics_kobj = NULL;
4392 }
4393 
4394 static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
4395 {
4396 	static const i915_reg_t flex_eu_regs[] = {
4397 		EU_PERF_CNTL0,
4398 		EU_PERF_CNTL1,
4399 		EU_PERF_CNTL2,
4400 		EU_PERF_CNTL3,
4401 		EU_PERF_CNTL4,
4402 		EU_PERF_CNTL5,
4403 		EU_PERF_CNTL6,
4404 	};
4405 	int i;
4406 
4407 	for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
4408 		if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
4409 			return true;
4410 	}
4411 	return false;
4412 }
4413 
4414 static bool reg_in_range_table(u32 addr, const struct i915_range *table)
4415 {
4416 	while (table->start || table->end) {
4417 		if (addr >= table->start && addr <= table->end)
4418 			return true;
4419 
4420 		table++;
4421 	}
4422 
4423 	return false;
4424 }
4425 
4426 #define REG_EQUAL(addr, mmio) \
4427 	((addr) == i915_mmio_reg_offset(mmio))
4428 
4429 static const struct i915_range gen7_oa_b_counters[] = {
4430 	{ .start = 0x2710, .end = 0x272c },	/* OASTARTTRIG[1-8] */
4431 	{ .start = 0x2740, .end = 0x275c },	/* OAREPORTTRIG[1-8] */
4432 	{ .start = 0x2770, .end = 0x27ac },	/* OACEC[0-7][0-1] */
4433 	{}
4434 };
4435 
4436 static const struct i915_range gen12_oa_b_counters[] = {
4437 	{ .start = 0x2b2c, .end = 0x2b2c },	/* GEN12_OAG_OA_PESS */
4438 	{ .start = 0xd900, .end = 0xd91c },	/* GEN12_OAG_OASTARTTRIG[1-8] */
4439 	{ .start = 0xd920, .end = 0xd93c },	/* GEN12_OAG_OAREPORTTRIG1[1-8] */
4440 	{ .start = 0xd940, .end = 0xd97c },	/* GEN12_OAG_CEC[0-7][0-1] */
4441 	{ .start = 0xdc00, .end = 0xdc3c },	/* GEN12_OAG_SCEC[0-7][0-1] */
4442 	{ .start = 0xdc40, .end = 0xdc40 },	/* GEN12_OAG_SPCTR_CNF */
4443 	{ .start = 0xdc44, .end = 0xdc44 },	/* GEN12_OAA_DBG_REG */
4444 	{}
4445 };
4446 
4447 static const struct i915_range mtl_oam_b_counters[] = {
4448 	{ .start = 0x393000, .end = 0x39301c },	/* GEN12_OAM_STARTTRIG1[1-8] */
4449 	{ .start = 0x393020, .end = 0x39303c },	/* GEN12_OAM_REPORTTRIG1[1-8] */
4450 	{ .start = 0x393040, .end = 0x39307c },	/* GEN12_OAM_CEC[0-7][0-1] */
4451 	{ .start = 0x393200, .end = 0x39323C },	/* MPES[0-7] */
4452 	{}
4453 };
4454 
4455 static const struct i915_range xehp_oa_b_counters[] = {
4456 	{ .start = 0xdc48, .end = 0xdc48 },	/* OAA_ENABLE_REG */
4457 	{ .start = 0xdd00, .end = 0xdd48 },	/* OAG_LCE0_0 - OAA_LENABLE_REG */
4458 	{}
4459 };
4460 
4461 static const struct i915_range gen7_oa_mux_regs[] = {
4462 	{ .start = 0x91b8, .end = 0x91cc },	/* OA_PERFCNT[1-2], OA_PERFMATRIX */
4463 	{ .start = 0x9800, .end = 0x9888 },	/* MICRO_BP0_0 - NOA_WRITE */
4464 	{ .start = 0xe180, .end = 0xe180 },	/* HALF_SLICE_CHICKEN2 */
4465 	{}
4466 };
4467 
4468 static const struct i915_range hsw_oa_mux_regs[] = {
4469 	{ .start = 0x09e80, .end = 0x09ea4 }, /* HSW_MBVID2_NOA[0-9] */
4470 	{ .start = 0x09ec0, .end = 0x09ec0 }, /* HSW_MBVID2_MISR0 */
4471 	{ .start = 0x25100, .end = 0x2ff90 },
4472 	{}
4473 };
4474 
4475 static const struct i915_range chv_oa_mux_regs[] = {
4476 	{ .start = 0x182300, .end = 0x1823a4 },
4477 	{}
4478 };
4479 
4480 static const struct i915_range gen8_oa_mux_regs[] = {
4481 	{ .start = 0x0d00, .end = 0x0d2c },	/* RPM_CONFIG[0-1], NOA_CONFIG[0-8] */
4482 	{ .start = 0x20cc, .end = 0x20cc },	/* WAIT_FOR_RC6_EXIT */
4483 	{}
4484 };
4485 
4486 static const struct i915_range gen11_oa_mux_regs[] = {
4487 	{ .start = 0x91c8, .end = 0x91dc },	/* OA_PERFCNT[3-4] */
4488 	{}
4489 };
4490 
4491 static const struct i915_range gen12_oa_mux_regs[] = {
4492 	{ .start = 0x0d00, .end = 0x0d04 },     /* RPM_CONFIG[0-1] */
4493 	{ .start = 0x0d0c, .end = 0x0d2c },     /* NOA_CONFIG[0-8] */
4494 	{ .start = 0x9840, .end = 0x9840 },	/* GDT_CHICKEN_BITS */
4495 	{ .start = 0x9884, .end = 0x9888 },	/* NOA_WRITE */
4496 	{ .start = 0x20cc, .end = 0x20cc },	/* WAIT_FOR_RC6_EXIT */
4497 	{}
4498 };
4499 
4500 /*
4501  * Ref: 14010536224:
4502  * 0x20cc is repurposed on MTL, so use a separate array for MTL.
4503  */
4504 static const struct i915_range mtl_oa_mux_regs[] = {
4505 	{ .start = 0x0d00, .end = 0x0d04 },	/* RPM_CONFIG[0-1] */
4506 	{ .start = 0x0d0c, .end = 0x0d2c },	/* NOA_CONFIG[0-8] */
4507 	{ .start = 0x9840, .end = 0x9840 },	/* GDT_CHICKEN_BITS */
4508 	{ .start = 0x9884, .end = 0x9888 },	/* NOA_WRITE */
4509 	{ .start = 0x38d100, .end = 0x38d114},	/* VISACTL */
4510 	{}
4511 };
4512 
4513 static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
4514 {
4515 	return reg_in_range_table(addr, gen7_oa_b_counters);
4516 }
4517 
4518 static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4519 {
4520 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4521 		reg_in_range_table(addr, gen8_oa_mux_regs);
4522 }
4523 
4524 static bool gen11_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4525 {
4526 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4527 		reg_in_range_table(addr, gen8_oa_mux_regs) ||
4528 		reg_in_range_table(addr, gen11_oa_mux_regs);
4529 }
4530 
4531 static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4532 {
4533 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4534 		reg_in_range_table(addr, hsw_oa_mux_regs);
4535 }
4536 
4537 static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4538 {
4539 	return reg_in_range_table(addr, gen7_oa_mux_regs) ||
4540 		reg_in_range_table(addr, chv_oa_mux_regs);
4541 }
4542 
4543 static bool gen12_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
4544 {
4545 	return reg_in_range_table(addr, gen12_oa_b_counters);
4546 }
4547 
4548 static bool mtl_is_valid_oam_b_counter_addr(struct i915_perf *perf, u32 addr)
4549 {
4550 	if (HAS_OAM(perf->i915) &&
4551 	    GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 70))
4552 		return reg_in_range_table(addr, mtl_oam_b_counters);
4553 
4554 	return false;
4555 }
4556 
4557 static bool xehp_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
4558 {
4559 	return reg_in_range_table(addr, xehp_oa_b_counters) ||
4560 		reg_in_range_table(addr, gen12_oa_b_counters) ||
4561 		mtl_is_valid_oam_b_counter_addr(perf, addr);
4562 }
4563 
4564 static bool gen12_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
4565 {
4566 	if (GRAPHICS_VER_FULL(perf->i915) >= IP_VER(12, 70))
4567 		return reg_in_range_table(addr, mtl_oa_mux_regs);
4568 	else
4569 		return reg_in_range_table(addr, gen12_oa_mux_regs);
4570 }
4571 
4572 static u32 mask_reg_value(u32 reg, u32 val)
4573 {
4574 	/* HALF_SLICE_CHICKEN2 is programmed with a the
4575 	 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
4576 	 * programmed by userspace doesn't change this.
4577 	 */
4578 	if (REG_EQUAL(reg, HALF_SLICE_CHICKEN2))
4579 		val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
4580 
4581 	/* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
4582 	 * indicated by its name and a bunch of selection fields used by OA
4583 	 * configs.
4584 	 */
4585 	if (REG_EQUAL(reg, WAIT_FOR_RC6_EXIT))
4586 		val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
4587 
4588 	return val;
4589 }
4590 
4591 static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
4592 					 bool (*is_valid)(struct i915_perf *perf, u32 addr),
4593 					 u32 __user *regs,
4594 					 u32 n_regs)
4595 {
4596 	struct i915_oa_reg *oa_regs;
4597 	int err;
4598 	u32 i;
4599 
4600 	if (!n_regs)
4601 		return NULL;
4602 
4603 	/* No is_valid function means we're not allowing any register to be programmed. */
4604 	GEM_BUG_ON(!is_valid);
4605 	if (!is_valid)
4606 		return ERR_PTR(-EINVAL);
4607 
4608 	oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
4609 	if (!oa_regs)
4610 		return ERR_PTR(-ENOMEM);
4611 
4612 	for (i = 0; i < n_regs; i++) {
4613 		u32 addr, value;
4614 
4615 		err = get_user(addr, regs);
4616 		if (err)
4617 			goto addr_err;
4618 
4619 		if (!is_valid(perf, addr)) {
4620 			drm_dbg(&perf->i915->drm,
4621 				"Invalid oa_reg address: %X\n", addr);
4622 			err = -EINVAL;
4623 			goto addr_err;
4624 		}
4625 
4626 		err = get_user(value, regs + 1);
4627 		if (err)
4628 			goto addr_err;
4629 
4630 		oa_regs[i].addr = _MMIO(addr);
4631 		oa_regs[i].value = mask_reg_value(addr, value);
4632 
4633 		regs += 2;
4634 	}
4635 
4636 	return oa_regs;
4637 
4638 addr_err:
4639 	kfree(oa_regs);
4640 	return ERR_PTR(err);
4641 }
4642 
4643 static ssize_t show_dynamic_id(struct kobject *kobj,
4644 			       struct kobj_attribute *attr,
4645 			       char *buf)
4646 {
4647 	struct i915_oa_config *oa_config =
4648 		container_of(attr, typeof(*oa_config), sysfs_metric_id);
4649 
4650 	return sprintf(buf, "%d\n", oa_config->id);
4651 }
4652 
4653 static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
4654 					 struct i915_oa_config *oa_config)
4655 {
4656 	sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
4657 	oa_config->sysfs_metric_id.attr.name = "id";
4658 	oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
4659 	oa_config->sysfs_metric_id.show = show_dynamic_id;
4660 	oa_config->sysfs_metric_id.store = NULL;
4661 
4662 	oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
4663 	oa_config->attrs[1] = NULL;
4664 
4665 	oa_config->sysfs_metric.name = oa_config->uuid;
4666 	oa_config->sysfs_metric.attrs = oa_config->attrs;
4667 
4668 	return sysfs_create_group(perf->metrics_kobj,
4669 				  &oa_config->sysfs_metric);
4670 }
4671 
4672 /**
4673  * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
4674  * @dev: drm device
4675  * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
4676  *        userspace (unvalidated)
4677  * @file: drm file
4678  *
4679  * Validates the submitted OA register to be saved into a new OA config that
4680  * can then be used for programming the OA unit and its NOA network.
4681  *
4682  * Returns: A new allocated config number to be used with the perf open ioctl
4683  * or a negative error code on failure.
4684  */
4685 int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
4686 			       struct drm_file *file)
4687 {
4688 	struct i915_perf *perf = &to_i915(dev)->perf;
4689 	struct drm_i915_perf_oa_config *args = data;
4690 	struct i915_oa_config *oa_config, *tmp;
4691 	struct i915_oa_reg *regs;
4692 	int err, id;
4693 
4694 	if (!perf->i915)
4695 		return -ENOTSUPP;
4696 
4697 	if (!perf->metrics_kobj) {
4698 		drm_dbg(&perf->i915->drm,
4699 			"OA metrics weren't advertised via sysfs\n");
4700 		return -EINVAL;
4701 	}
4702 
4703 	if (i915_perf_stream_paranoid && !perfmon_capable()) {
4704 		drm_dbg(&perf->i915->drm,
4705 			"Insufficient privileges to add i915 OA config\n");
4706 		return -EACCES;
4707 	}
4708 
4709 	if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
4710 	    (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
4711 	    (!args->flex_regs_ptr || !args->n_flex_regs)) {
4712 		drm_dbg(&perf->i915->drm,
4713 			"No OA registers given\n");
4714 		return -EINVAL;
4715 	}
4716 
4717 	oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
4718 	if (!oa_config) {
4719 		drm_dbg(&perf->i915->drm,
4720 			"Failed to allocate memory for the OA config\n");
4721 		return -ENOMEM;
4722 	}
4723 
4724 	oa_config->perf = perf;
4725 	kref_init(&oa_config->ref);
4726 
4727 	if (!uuid_is_valid(args->uuid)) {
4728 		drm_dbg(&perf->i915->drm,
4729 			"Invalid uuid format for OA config\n");
4730 		err = -EINVAL;
4731 		goto reg_err;
4732 	}
4733 
4734 	/* Last character in oa_config->uuid will be 0 because oa_config is
4735 	 * kzalloc.
4736 	 */
4737 	memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
4738 
4739 	oa_config->mux_regs_len = args->n_mux_regs;
4740 	regs = alloc_oa_regs(perf,
4741 			     perf->ops.is_valid_mux_reg,
4742 			     u64_to_user_ptr(args->mux_regs_ptr),
4743 			     args->n_mux_regs);
4744 
4745 	if (IS_ERR(regs)) {
4746 		drm_dbg(&perf->i915->drm,
4747 			"Failed to create OA config for mux_regs\n");
4748 		err = PTR_ERR(regs);
4749 		goto reg_err;
4750 	}
4751 	oa_config->mux_regs = regs;
4752 
4753 	oa_config->b_counter_regs_len = args->n_boolean_regs;
4754 	regs = alloc_oa_regs(perf,
4755 			     perf->ops.is_valid_b_counter_reg,
4756 			     u64_to_user_ptr(args->boolean_regs_ptr),
4757 			     args->n_boolean_regs);
4758 
4759 	if (IS_ERR(regs)) {
4760 		drm_dbg(&perf->i915->drm,
4761 			"Failed to create OA config for b_counter_regs\n");
4762 		err = PTR_ERR(regs);
4763 		goto reg_err;
4764 	}
4765 	oa_config->b_counter_regs = regs;
4766 
4767 	if (GRAPHICS_VER(perf->i915) < 8) {
4768 		if (args->n_flex_regs != 0) {
4769 			err = -EINVAL;
4770 			goto reg_err;
4771 		}
4772 	} else {
4773 		oa_config->flex_regs_len = args->n_flex_regs;
4774 		regs = alloc_oa_regs(perf,
4775 				     perf->ops.is_valid_flex_reg,
4776 				     u64_to_user_ptr(args->flex_regs_ptr),
4777 				     args->n_flex_regs);
4778 
4779 		if (IS_ERR(regs)) {
4780 			drm_dbg(&perf->i915->drm,
4781 				"Failed to create OA config for flex_regs\n");
4782 			err = PTR_ERR(regs);
4783 			goto reg_err;
4784 		}
4785 		oa_config->flex_regs = regs;
4786 	}
4787 
4788 	err = mutex_lock_interruptible(&perf->metrics_lock);
4789 	if (err)
4790 		goto reg_err;
4791 
4792 	/* We shouldn't have too many configs, so this iteration shouldn't be
4793 	 * too costly.
4794 	 */
4795 	idr_for_each_entry(&perf->metrics_idr, tmp, id) {
4796 		if (!strcmp(tmp->uuid, oa_config->uuid)) {
4797 			drm_dbg(&perf->i915->drm,
4798 				"OA config already exists with this uuid\n");
4799 			err = -EADDRINUSE;
4800 			goto sysfs_err;
4801 		}
4802 	}
4803 
4804 	err = create_dynamic_oa_sysfs_entry(perf, oa_config);
4805 	if (err) {
4806 		drm_dbg(&perf->i915->drm,
4807 			"Failed to create sysfs entry for OA config\n");
4808 		goto sysfs_err;
4809 	}
4810 
4811 	/* Config id 0 is invalid, id 1 for kernel stored test config. */
4812 	oa_config->id = idr_alloc(&perf->metrics_idr,
4813 				  oa_config, 2,
4814 				  0, GFP_KERNEL);
4815 	if (oa_config->id < 0) {
4816 		drm_dbg(&perf->i915->drm,
4817 			"Failed to create sysfs entry for OA config\n");
4818 		err = oa_config->id;
4819 		goto sysfs_err;
4820 	}
4821 	id = oa_config->id;
4822 
4823 	drm_dbg(&perf->i915->drm,
4824 		"Added config %s id=%i\n", oa_config->uuid, oa_config->id);
4825 	mutex_unlock(&perf->metrics_lock);
4826 
4827 	return id;
4828 
4829 sysfs_err:
4830 	mutex_unlock(&perf->metrics_lock);
4831 reg_err:
4832 	i915_oa_config_put(oa_config);
4833 	drm_dbg(&perf->i915->drm,
4834 		"Failed to add new OA config\n");
4835 	return err;
4836 }
4837 
4838 /**
4839  * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
4840  * @dev: drm device
4841  * @data: ioctl data (pointer to u64 integer) copied from userspace
4842  * @file: drm file
4843  *
4844  * Configs can be removed while being used, the will stop appearing in sysfs
4845  * and their content will be freed when the stream using the config is closed.
4846  *
4847  * Returns: 0 on success or a negative error code on failure.
4848  */
4849 int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
4850 				  struct drm_file *file)
4851 {
4852 	struct i915_perf *perf = &to_i915(dev)->perf;
4853 	u64 *arg = data;
4854 	struct i915_oa_config *oa_config;
4855 	int ret;
4856 
4857 	if (!perf->i915)
4858 		return -ENOTSUPP;
4859 
4860 	if (i915_perf_stream_paranoid && !perfmon_capable()) {
4861 		drm_dbg(&perf->i915->drm,
4862 			"Insufficient privileges to remove i915 OA config\n");
4863 		return -EACCES;
4864 	}
4865 
4866 	ret = mutex_lock_interruptible(&perf->metrics_lock);
4867 	if (ret)
4868 		return ret;
4869 
4870 	oa_config = idr_find(&perf->metrics_idr, *arg);
4871 	if (!oa_config) {
4872 		drm_dbg(&perf->i915->drm,
4873 			"Failed to remove unknown OA config\n");
4874 		ret = -ENOENT;
4875 		goto err_unlock;
4876 	}
4877 
4878 	GEM_BUG_ON(*arg != oa_config->id);
4879 
4880 	sysfs_remove_group(perf->metrics_kobj, &oa_config->sysfs_metric);
4881 
4882 	idr_remove(&perf->metrics_idr, *arg);
4883 
4884 	mutex_unlock(&perf->metrics_lock);
4885 
4886 	drm_dbg(&perf->i915->drm,
4887 		"Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
4888 
4889 	i915_oa_config_put(oa_config);
4890 
4891 	return 0;
4892 
4893 err_unlock:
4894 	mutex_unlock(&perf->metrics_lock);
4895 	return ret;
4896 }
4897 
4898 static struct ctl_table oa_table[] = {
4899 	{
4900 	 .procname = "perf_stream_paranoid",
4901 	 .data = &i915_perf_stream_paranoid,
4902 	 .maxlen = sizeof(i915_perf_stream_paranoid),
4903 	 .mode = 0644,
4904 	 .proc_handler = proc_dointvec_minmax,
4905 	 .extra1 = SYSCTL_ZERO,
4906 	 .extra2 = SYSCTL_ONE,
4907 	 },
4908 	{
4909 	 .procname = "oa_max_sample_rate",
4910 	 .data = &i915_oa_max_sample_rate,
4911 	 .maxlen = sizeof(i915_oa_max_sample_rate),
4912 	 .mode = 0644,
4913 	 .proc_handler = proc_dointvec_minmax,
4914 	 .extra1 = SYSCTL_ZERO,
4915 	 .extra2 = &oa_sample_rate_hard_limit,
4916 	 },
4917 	{}
4918 };
4919 
4920 static u32 num_perf_groups_per_gt(struct intel_gt *gt)
4921 {
4922 	return 1;
4923 }
4924 
4925 static u32 __oam_engine_group(struct intel_engine_cs *engine)
4926 {
4927 	if (GRAPHICS_VER_FULL(engine->i915) >= IP_VER(12, 70)) {
4928 		/*
4929 		 * There's 1 SAMEDIA gt and 1 OAM per SAMEDIA gt. All media slices
4930 		 * within the gt use the same OAM. All MTL SKUs list 1 SA MEDIA.
4931 		 */
4932 		drm_WARN_ON(&engine->i915->drm,
4933 			    engine->gt->type != GT_MEDIA);
4934 
4935 		return PERF_GROUP_OAM_SAMEDIA_0;
4936 	}
4937 
4938 	return PERF_GROUP_INVALID;
4939 }
4940 
4941 static u32 __oa_engine_group(struct intel_engine_cs *engine)
4942 {
4943 	switch (engine->class) {
4944 	case RENDER_CLASS:
4945 		return PERF_GROUP_OAG;
4946 
4947 	case VIDEO_DECODE_CLASS:
4948 	case VIDEO_ENHANCEMENT_CLASS:
4949 		return __oam_engine_group(engine);
4950 
4951 	default:
4952 		return PERF_GROUP_INVALID;
4953 	}
4954 }
4955 
4956 static struct i915_perf_regs __oam_regs(u32 base)
4957 {
4958 	return (struct i915_perf_regs) {
4959 		base,
4960 		GEN12_OAM_HEAD_POINTER(base),
4961 		GEN12_OAM_TAIL_POINTER(base),
4962 		GEN12_OAM_BUFFER(base),
4963 		GEN12_OAM_CONTEXT_CONTROL(base),
4964 		GEN12_OAM_CONTROL(base),
4965 		GEN12_OAM_DEBUG(base),
4966 		GEN12_OAM_STATUS(base),
4967 		GEN12_OAM_CONTROL_COUNTER_FORMAT_SHIFT,
4968 	};
4969 }
4970 
4971 static struct i915_perf_regs __oag_regs(void)
4972 {
4973 	return (struct i915_perf_regs) {
4974 		0,
4975 		GEN12_OAG_OAHEADPTR,
4976 		GEN12_OAG_OATAILPTR,
4977 		GEN12_OAG_OABUFFER,
4978 		GEN12_OAG_OAGLBCTXCTRL,
4979 		GEN12_OAG_OACONTROL,
4980 		GEN12_OAG_OA_DEBUG,
4981 		GEN12_OAG_OASTATUS,
4982 		GEN12_OAG_OACONTROL_OA_COUNTER_FORMAT_SHIFT,
4983 	};
4984 }
4985 
4986 static void oa_init_groups(struct intel_gt *gt)
4987 {
4988 	int i, num_groups = gt->perf.num_perf_groups;
4989 
4990 	for (i = 0; i < num_groups; i++) {
4991 		struct i915_perf_group *g = &gt->perf.group[i];
4992 
4993 		/* Fused off engines can result in a group with num_engines == 0 */
4994 		if (g->num_engines == 0)
4995 			continue;
4996 
4997 		if (i == PERF_GROUP_OAG && gt->type != GT_MEDIA) {
4998 			g->regs = __oag_regs();
4999 			g->type = TYPE_OAG;
5000 		} else if (GRAPHICS_VER_FULL(gt->i915) >= IP_VER(12, 70)) {
5001 			g->regs = __oam_regs(mtl_oa_base[i]);
5002 			g->type = TYPE_OAM;
5003 		}
5004 	}
5005 }
5006 
5007 static int oa_init_gt(struct intel_gt *gt)
5008 {
5009 	u32 num_groups = num_perf_groups_per_gt(gt);
5010 	struct intel_engine_cs *engine;
5011 	struct i915_perf_group *g;
5012 	intel_engine_mask_t tmp;
5013 
5014 	g = kcalloc(num_groups, sizeof(*g), GFP_KERNEL);
5015 	if (!g)
5016 		return -ENOMEM;
5017 
5018 	for_each_engine_masked(engine, gt, ALL_ENGINES, tmp) {
5019 		u32 index = __oa_engine_group(engine);
5020 
5021 		engine->oa_group = NULL;
5022 		if (index < num_groups) {
5023 			g[index].num_engines++;
5024 			engine->oa_group = &g[index];
5025 		}
5026 	}
5027 
5028 	gt->perf.num_perf_groups = num_groups;
5029 	gt->perf.group = g;
5030 
5031 	oa_init_groups(gt);
5032 
5033 	return 0;
5034 }
5035 
5036 static int oa_init_engine_groups(struct i915_perf *perf)
5037 {
5038 	struct intel_gt *gt;
5039 	int i, ret;
5040 
5041 	for_each_gt(gt, perf->i915, i) {
5042 		ret = oa_init_gt(gt);
5043 		if (ret)
5044 			return ret;
5045 	}
5046 
5047 	return 0;
5048 }
5049 
5050 static void oa_init_supported_formats(struct i915_perf *perf)
5051 {
5052 	struct drm_i915_private *i915 = perf->i915;
5053 	enum intel_platform platform = INTEL_INFO(i915)->platform;
5054 
5055 	switch (platform) {
5056 	case INTEL_HASWELL:
5057 		oa_format_add(perf, I915_OA_FORMAT_A13);
5058 		oa_format_add(perf, I915_OA_FORMAT_A13);
5059 		oa_format_add(perf, I915_OA_FORMAT_A29);
5060 		oa_format_add(perf, I915_OA_FORMAT_A13_B8_C8);
5061 		oa_format_add(perf, I915_OA_FORMAT_B4_C8);
5062 		oa_format_add(perf, I915_OA_FORMAT_A45_B8_C8);
5063 		oa_format_add(perf, I915_OA_FORMAT_B4_C8_A16);
5064 		oa_format_add(perf, I915_OA_FORMAT_C4_B8);
5065 		break;
5066 
5067 	case INTEL_BROADWELL:
5068 	case INTEL_CHERRYVIEW:
5069 	case INTEL_SKYLAKE:
5070 	case INTEL_BROXTON:
5071 	case INTEL_KABYLAKE:
5072 	case INTEL_GEMINILAKE:
5073 	case INTEL_COFFEELAKE:
5074 	case INTEL_COMETLAKE:
5075 	case INTEL_ICELAKE:
5076 	case INTEL_ELKHARTLAKE:
5077 	case INTEL_JASPERLAKE:
5078 	case INTEL_TIGERLAKE:
5079 	case INTEL_ROCKETLAKE:
5080 	case INTEL_DG1:
5081 	case INTEL_ALDERLAKE_S:
5082 	case INTEL_ALDERLAKE_P:
5083 		oa_format_add(perf, I915_OA_FORMAT_A12);
5084 		oa_format_add(perf, I915_OA_FORMAT_A12_B8_C8);
5085 		oa_format_add(perf, I915_OA_FORMAT_A32u40_A4u32_B8_C8);
5086 		oa_format_add(perf, I915_OA_FORMAT_C4_B8);
5087 		break;
5088 
5089 	case INTEL_DG2:
5090 		oa_format_add(perf, I915_OAR_FORMAT_A32u40_A4u32_B8_C8);
5091 		oa_format_add(perf, I915_OA_FORMAT_A24u40_A14u32_B8_C8);
5092 		break;
5093 
5094 	case INTEL_METEORLAKE:
5095 		oa_format_add(perf, I915_OAR_FORMAT_A32u40_A4u32_B8_C8);
5096 		oa_format_add(perf, I915_OA_FORMAT_A24u40_A14u32_B8_C8);
5097 		oa_format_add(perf, I915_OAM_FORMAT_MPEC8u64_B8_C8);
5098 		oa_format_add(perf, I915_OAM_FORMAT_MPEC8u32_B8_C8);
5099 		break;
5100 
5101 	default:
5102 		MISSING_CASE(platform);
5103 	}
5104 }
5105 
5106 static void i915_perf_init_info(struct drm_i915_private *i915)
5107 {
5108 	struct i915_perf *perf = &i915->perf;
5109 
5110 	switch (GRAPHICS_VER(i915)) {
5111 	case 8:
5112 		perf->ctx_oactxctrl_offset = 0x120;
5113 		perf->ctx_flexeu0_offset = 0x2ce;
5114 		perf->gen8_valid_ctx_bit = BIT(25);
5115 		break;
5116 	case 9:
5117 		perf->ctx_oactxctrl_offset = 0x128;
5118 		perf->ctx_flexeu0_offset = 0x3de;
5119 		perf->gen8_valid_ctx_bit = BIT(16);
5120 		break;
5121 	case 11:
5122 		perf->ctx_oactxctrl_offset = 0x124;
5123 		perf->ctx_flexeu0_offset = 0x78e;
5124 		perf->gen8_valid_ctx_bit = BIT(16);
5125 		break;
5126 	case 12:
5127 		perf->gen8_valid_ctx_bit = BIT(16);
5128 		/*
5129 		 * Calculate offset at runtime in oa_pin_context for gen12 and
5130 		 * cache the value in perf->ctx_oactxctrl_offset.
5131 		 */
5132 		break;
5133 	default:
5134 		MISSING_CASE(GRAPHICS_VER(i915));
5135 	}
5136 }
5137 
5138 /**
5139  * i915_perf_init - initialize i915-perf state on module bind
5140  * @i915: i915 device instance
5141  *
5142  * Initializes i915-perf state without exposing anything to userspace.
5143  *
5144  * Note: i915-perf initialization is split into an 'init' and 'register'
5145  * phase with the i915_perf_register() exposing state to userspace.
5146  */
5147 int i915_perf_init(struct drm_i915_private *i915)
5148 {
5149 	struct i915_perf *perf = &i915->perf;
5150 
5151 	perf->oa_formats = oa_formats;
5152 	if (IS_HASWELL(i915)) {
5153 		perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
5154 		perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
5155 		perf->ops.is_valid_flex_reg = NULL;
5156 		perf->ops.enable_metric_set = hsw_enable_metric_set;
5157 		perf->ops.disable_metric_set = hsw_disable_metric_set;
5158 		perf->ops.oa_enable = gen7_oa_enable;
5159 		perf->ops.oa_disable = gen7_oa_disable;
5160 		perf->ops.read = gen7_oa_read;
5161 		perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
5162 	} else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
5163 		/* Note: that although we could theoretically also support the
5164 		 * legacy ringbuffer mode on BDW (and earlier iterations of
5165 		 * this driver, before upstreaming did this) it didn't seem
5166 		 * worth the complexity to maintain now that BDW+ enable
5167 		 * execlist mode by default.
5168 		 */
5169 		perf->ops.read = gen8_oa_read;
5170 		i915_perf_init_info(i915);
5171 
5172 		if (IS_GRAPHICS_VER(i915, 8, 9)) {
5173 			perf->ops.is_valid_b_counter_reg =
5174 				gen7_is_valid_b_counter_addr;
5175 			perf->ops.is_valid_mux_reg =
5176 				gen8_is_valid_mux_addr;
5177 			perf->ops.is_valid_flex_reg =
5178 				gen8_is_valid_flex_addr;
5179 
5180 			if (IS_CHERRYVIEW(i915)) {
5181 				perf->ops.is_valid_mux_reg =
5182 					chv_is_valid_mux_addr;
5183 			}
5184 
5185 			perf->ops.oa_enable = gen8_oa_enable;
5186 			perf->ops.oa_disable = gen8_oa_disable;
5187 			perf->ops.enable_metric_set = gen8_enable_metric_set;
5188 			perf->ops.disable_metric_set = gen8_disable_metric_set;
5189 			perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
5190 		} else if (GRAPHICS_VER(i915) == 11) {
5191 			perf->ops.is_valid_b_counter_reg =
5192 				gen7_is_valid_b_counter_addr;
5193 			perf->ops.is_valid_mux_reg =
5194 				gen11_is_valid_mux_addr;
5195 			perf->ops.is_valid_flex_reg =
5196 				gen8_is_valid_flex_addr;
5197 
5198 			perf->ops.oa_enable = gen8_oa_enable;
5199 			perf->ops.oa_disable = gen8_oa_disable;
5200 			perf->ops.enable_metric_set = gen8_enable_metric_set;
5201 			perf->ops.disable_metric_set = gen11_disable_metric_set;
5202 			perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
5203 		} else if (GRAPHICS_VER(i915) == 12) {
5204 			perf->ops.is_valid_b_counter_reg =
5205 				HAS_OA_SLICE_CONTRIB_LIMITS(i915) ?
5206 				xehp_is_valid_b_counter_addr :
5207 				gen12_is_valid_b_counter_addr;
5208 			perf->ops.is_valid_mux_reg =
5209 				gen12_is_valid_mux_addr;
5210 			perf->ops.is_valid_flex_reg =
5211 				gen8_is_valid_flex_addr;
5212 
5213 			perf->ops.oa_enable = gen12_oa_enable;
5214 			perf->ops.oa_disable = gen12_oa_disable;
5215 			perf->ops.enable_metric_set = gen12_enable_metric_set;
5216 			perf->ops.disable_metric_set = gen12_disable_metric_set;
5217 			perf->ops.oa_hw_tail_read = gen12_oa_hw_tail_read;
5218 		}
5219 	}
5220 
5221 	if (perf->ops.enable_metric_set) {
5222 		struct intel_gt *gt;
5223 		int i, ret;
5224 
5225 		for_each_gt(gt, i915, i)
5226 			mutex_init(&gt->perf.lock);
5227 
5228 		/* Choose a representative limit */
5229 		oa_sample_rate_hard_limit = to_gt(i915)->clock_frequency / 2;
5230 
5231 		mutex_init(&perf->metrics_lock);
5232 		idr_init_base(&perf->metrics_idr, 1);
5233 
5234 		/* We set up some ratelimit state to potentially throttle any
5235 		 * _NOTES about spurious, invalid OA reports which we don't
5236 		 * forward to userspace.
5237 		 *
5238 		 * We print a _NOTE about any throttling when closing the
5239 		 * stream instead of waiting until driver _fini which no one
5240 		 * would ever see.
5241 		 *
5242 		 * Using the same limiting factors as printk_ratelimit()
5243 		 */
5244 		ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
5245 		/* Since we use a DRM_NOTE for spurious reports it would be
5246 		 * inconsistent to let __ratelimit() automatically print a
5247 		 * warning for throttling.
5248 		 */
5249 		ratelimit_set_flags(&perf->spurious_report_rs,
5250 				    RATELIMIT_MSG_ON_RELEASE);
5251 
5252 		ratelimit_state_init(&perf->tail_pointer_race,
5253 				     5 * HZ, 10);
5254 		ratelimit_set_flags(&perf->tail_pointer_race,
5255 				    RATELIMIT_MSG_ON_RELEASE);
5256 
5257 		atomic64_set(&perf->noa_programming_delay,
5258 			     500 * 1000 /* 500us */);
5259 
5260 		perf->i915 = i915;
5261 
5262 		ret = oa_init_engine_groups(perf);
5263 		if (ret) {
5264 			drm_err(&i915->drm,
5265 				"OA initialization failed %d\n", ret);
5266 			return ret;
5267 		}
5268 
5269 		oa_init_supported_formats(perf);
5270 	}
5271 
5272 	return 0;
5273 }
5274 
5275 static int destroy_config(int id, void *p, void *data)
5276 {
5277 	i915_oa_config_put(p);
5278 	return 0;
5279 }
5280 
5281 int i915_perf_sysctl_register(void)
5282 {
5283 	sysctl_header = register_sysctl("dev/i915", oa_table);
5284 	return 0;
5285 }
5286 
5287 void i915_perf_sysctl_unregister(void)
5288 {
5289 	unregister_sysctl_table(sysctl_header);
5290 }
5291 
5292 /**
5293  * i915_perf_fini - Counter part to i915_perf_init()
5294  * @i915: i915 device instance
5295  */
5296 void i915_perf_fini(struct drm_i915_private *i915)
5297 {
5298 	struct i915_perf *perf = &i915->perf;
5299 	struct intel_gt *gt;
5300 	int i;
5301 
5302 	if (!perf->i915)
5303 		return;
5304 
5305 	for_each_gt(gt, perf->i915, i)
5306 		kfree(gt->perf.group);
5307 
5308 	idr_for_each(&perf->metrics_idr, destroy_config, perf);
5309 	idr_destroy(&perf->metrics_idr);
5310 
5311 	memset(&perf->ops, 0, sizeof(perf->ops));
5312 	perf->i915 = NULL;
5313 }
5314 
5315 /**
5316  * i915_perf_ioctl_version - Version of the i915-perf subsystem
5317  * @i915: The i915 device
5318  *
5319  * This version number is used by userspace to detect available features.
5320  */
5321 int i915_perf_ioctl_version(struct drm_i915_private *i915)
5322 {
5323 	/*
5324 	 * 1: Initial version
5325 	 *   I915_PERF_IOCTL_ENABLE
5326 	 *   I915_PERF_IOCTL_DISABLE
5327 	 *
5328 	 * 2: Added runtime modification of OA config.
5329 	 *   I915_PERF_IOCTL_CONFIG
5330 	 *
5331 	 * 3: Add DRM_I915_PERF_PROP_HOLD_PREEMPTION parameter to hold
5332 	 *    preemption on a particular context so that performance data is
5333 	 *    accessible from a delta of MI_RPC reports without looking at the
5334 	 *    OA buffer.
5335 	 *
5336 	 * 4: Add DRM_I915_PERF_PROP_ALLOWED_SSEU to limit what contexts can
5337 	 *    be run for the duration of the performance recording based on
5338 	 *    their SSEU configuration.
5339 	 *
5340 	 * 5: Add DRM_I915_PERF_PROP_POLL_OA_PERIOD parameter that controls the
5341 	 *    interval for the hrtimer used to check for OA data.
5342 	 *
5343 	 * 6: Add DRM_I915_PERF_PROP_OA_ENGINE_CLASS and
5344 	 *    DRM_I915_PERF_PROP_OA_ENGINE_INSTANCE
5345 	 *
5346 	 * 7: Add support for video decode and enhancement classes.
5347 	 */
5348 
5349 	/*
5350 	 * Wa_14017512683: mtl[a0..c0): Use of OAM must be preceded with Media
5351 	 * C6 disable in BIOS. If Media C6 is enabled in BIOS, return version 6
5352 	 * to indicate that OA media is not supported.
5353 	 */
5354 	if (IS_MTL_MEDIA_STEP(i915, STEP_A0, STEP_C0)) {
5355 		struct intel_gt *gt;
5356 		int i;
5357 
5358 		for_each_gt(gt, i915, i) {
5359 			if (gt->type == GT_MEDIA &&
5360 			    intel_check_bios_c6_setup(&gt->rc6))
5361 				return 6;
5362 		}
5363 	}
5364 
5365 	return 7;
5366 }
5367 
5368 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
5369 #include "selftests/i915_perf.c"
5370 #endif
5371