xref: /openbmc/linux/drivers/gpu/drm/i915/i915_perf.c (revision 15a1fbdcfb519c2bd291ed01c6c94e0b89537a77)
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/sizes.h>
196 #include <linux/uuid.h>
197 
198 #include "gem/i915_gem_context.h"
199 #include "gt/intel_engine_pm.h"
200 #include "gt/intel_engine_user.h"
201 #include "gt/intel_gt.h"
202 #include "gt/intel_lrc_reg.h"
203 #include "gt/intel_ring.h"
204 
205 #include "i915_drv.h"
206 #include "i915_perf.h"
207 #include "oa/i915_oa_hsw.h"
208 #include "oa/i915_oa_bdw.h"
209 #include "oa/i915_oa_chv.h"
210 #include "oa/i915_oa_sklgt2.h"
211 #include "oa/i915_oa_sklgt3.h"
212 #include "oa/i915_oa_sklgt4.h"
213 #include "oa/i915_oa_bxt.h"
214 #include "oa/i915_oa_kblgt2.h"
215 #include "oa/i915_oa_kblgt3.h"
216 #include "oa/i915_oa_glk.h"
217 #include "oa/i915_oa_cflgt2.h"
218 #include "oa/i915_oa_cflgt3.h"
219 #include "oa/i915_oa_cnl.h"
220 #include "oa/i915_oa_icl.h"
221 #include "oa/i915_oa_tgl.h"
222 
223 /* HW requires this to be a power of two, between 128k and 16M, though driver
224  * is currently generally designed assuming the largest 16M size is used such
225  * that the overflow cases are unlikely in normal operation.
226  */
227 #define OA_BUFFER_SIZE		SZ_16M
228 
229 #define OA_TAKEN(tail, head)	((tail - head) & (OA_BUFFER_SIZE - 1))
230 
231 /**
232  * DOC: OA Tail Pointer Race
233  *
234  * There's a HW race condition between OA unit tail pointer register updates and
235  * writes to memory whereby the tail pointer can sometimes get ahead of what's
236  * been written out to the OA buffer so far (in terms of what's visible to the
237  * CPU).
238  *
239  * Although this can be observed explicitly while copying reports to userspace
240  * by checking for a zeroed report-id field in tail reports, we want to account
241  * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
242  * read() attempts.
243  *
244  * In effect we define a tail pointer for reading that lags the real tail
245  * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
246  * time for the corresponding reports to become visible to the CPU.
247  *
248  * To manage this we actually track two tail pointers:
249  *  1) An 'aging' tail with an associated timestamp that is tracked until we
250  *     can trust the corresponding data is visible to the CPU; at which point
251  *     it is considered 'aged'.
252  *  2) An 'aged' tail that can be used for read()ing.
253  *
254  * The two separate pointers let us decouple read()s from tail pointer aging.
255  *
256  * The tail pointers are checked and updated at a limited rate within a hrtimer
257  * callback (the same callback that is used for delivering EPOLLIN events)
258  *
259  * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
260  * indicates that an updated tail pointer is needed.
261  *
262  * Most of the implementation details for this workaround are in
263  * oa_buffer_check_unlocked() and _append_oa_reports()
264  *
265  * Note for posterity: previously the driver used to define an effective tail
266  * pointer that lagged the real pointer by a 'tail margin' measured in bytes
267  * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
268  * This was flawed considering that the OA unit may also automatically generate
269  * non-periodic reports (such as on context switch) or the OA unit may be
270  * enabled without any periodic sampling.
271  */
272 #define OA_TAIL_MARGIN_NSEC	100000ULL
273 #define INVALID_TAIL_PTR	0xffffffff
274 
275 /* frequency for checking whether the OA unit has written new reports to the
276  * circular OA buffer...
277  */
278 #define POLL_FREQUENCY 200
279 #define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
280 
281 /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
282 static u32 i915_perf_stream_paranoid = true;
283 
284 /* The maximum exponent the hardware accepts is 63 (essentially it selects one
285  * of the 64bit timestamp bits to trigger reports from) but there's currently
286  * no known use case for sampling as infrequently as once per 47 thousand years.
287  *
288  * Since the timestamps included in OA reports are only 32bits it seems
289  * reasonable to limit the OA exponent where it's still possible to account for
290  * overflow in OA report timestamps.
291  */
292 #define OA_EXPONENT_MAX 31
293 
294 #define INVALID_CTX_ID 0xffffffff
295 
296 /* On Gen8+ automatically triggered OA reports include a 'reason' field... */
297 #define OAREPORT_REASON_MASK           0x3f
298 #define OAREPORT_REASON_MASK_EXTENDED  0x7f
299 #define OAREPORT_REASON_SHIFT          19
300 #define OAREPORT_REASON_TIMER          (1<<0)
301 #define OAREPORT_REASON_CTX_SWITCH     (1<<3)
302 #define OAREPORT_REASON_CLK_RATIO      (1<<5)
303 
304 
305 /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
306  *
307  * The highest sampling frequency we can theoretically program the OA unit
308  * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
309  *
310  * Initialized just before we register the sysctl parameter.
311  */
312 static int oa_sample_rate_hard_limit;
313 
314 /* Theoretically we can program the OA unit to sample every 160ns but don't
315  * allow that by default unless root...
316  *
317  * The default threshold of 100000Hz is based on perf's similar
318  * kernel.perf_event_max_sample_rate sysctl parameter.
319  */
320 static u32 i915_oa_max_sample_rate = 100000;
321 
322 /* XXX: beware if future OA HW adds new report formats that the current
323  * code assumes all reports have a power-of-two size and ~(size - 1) can
324  * be used as a mask to align the OA tail pointer.
325  */
326 static const struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
327 	[I915_OA_FORMAT_A13]	    = { 0, 64 },
328 	[I915_OA_FORMAT_A29]	    = { 1, 128 },
329 	[I915_OA_FORMAT_A13_B8_C8]  = { 2, 128 },
330 	/* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
331 	[I915_OA_FORMAT_B4_C8]	    = { 4, 64 },
332 	[I915_OA_FORMAT_A45_B8_C8]  = { 5, 256 },
333 	[I915_OA_FORMAT_B4_C8_A16]  = { 6, 128 },
334 	[I915_OA_FORMAT_C4_B8]	    = { 7, 64 },
335 };
336 
337 static const struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
338 	[I915_OA_FORMAT_A12]		    = { 0, 64 },
339 	[I915_OA_FORMAT_A12_B8_C8]	    = { 2, 128 },
340 	[I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
341 	[I915_OA_FORMAT_C4_B8]		    = { 7, 64 },
342 };
343 
344 static const struct i915_oa_format gen12_oa_formats[I915_OA_FORMAT_MAX] = {
345 	[I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
346 };
347 
348 #define SAMPLE_OA_REPORT      (1<<0)
349 
350 /**
351  * struct perf_open_properties - for validated properties given to open a stream
352  * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
353  * @single_context: Whether a single or all gpu contexts should be monitored
354  * @hold_preemption: Whether the preemption is disabled for the filtered
355  *                   context
356  * @ctx_handle: A gem ctx handle for use with @single_context
357  * @metrics_set: An ID for an OA unit metric set advertised via sysfs
358  * @oa_format: An OA unit HW report format
359  * @oa_periodic: Whether to enable periodic OA unit sampling
360  * @oa_period_exponent: The OA unit sampling period is derived from this
361  * @engine: The engine (typically rcs0) being monitored by the OA unit
362  *
363  * As read_properties_unlocked() enumerates and validates the properties given
364  * to open a stream of metrics the configuration is built up in the structure
365  * which starts out zero initialized.
366  */
367 struct perf_open_properties {
368 	u32 sample_flags;
369 
370 	u64 single_context:1;
371 	u64 hold_preemption:1;
372 	u64 ctx_handle;
373 
374 	/* OA sampling state */
375 	int metrics_set;
376 	int oa_format;
377 	bool oa_periodic;
378 	int oa_period_exponent;
379 
380 	struct intel_engine_cs *engine;
381 };
382 
383 struct i915_oa_config_bo {
384 	struct llist_node node;
385 
386 	struct i915_oa_config *oa_config;
387 	struct i915_vma *vma;
388 };
389 
390 static struct ctl_table_header *sysctl_header;
391 
392 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer);
393 
394 void i915_oa_config_release(struct kref *ref)
395 {
396 	struct i915_oa_config *oa_config =
397 		container_of(ref, typeof(*oa_config), ref);
398 
399 	kfree(oa_config->flex_regs);
400 	kfree(oa_config->b_counter_regs);
401 	kfree(oa_config->mux_regs);
402 
403 	kfree_rcu(oa_config, rcu);
404 }
405 
406 struct i915_oa_config *
407 i915_perf_get_oa_config(struct i915_perf *perf, int metrics_set)
408 {
409 	struct i915_oa_config *oa_config;
410 
411 	rcu_read_lock();
412 	if (metrics_set == 1)
413 		oa_config = &perf->test_config;
414 	else
415 		oa_config = idr_find(&perf->metrics_idr, metrics_set);
416 	if (oa_config)
417 		oa_config = i915_oa_config_get(oa_config);
418 	rcu_read_unlock();
419 
420 	return oa_config;
421 }
422 
423 static void free_oa_config_bo(struct i915_oa_config_bo *oa_bo)
424 {
425 	i915_oa_config_put(oa_bo->oa_config);
426 	i915_vma_put(oa_bo->vma);
427 	kfree(oa_bo);
428 }
429 
430 static u32 gen12_oa_hw_tail_read(struct i915_perf_stream *stream)
431 {
432 	struct intel_uncore *uncore = stream->uncore;
433 
434 	return intel_uncore_read(uncore, GEN12_OAG_OATAILPTR) &
435 	       GEN12_OAG_OATAILPTR_MASK;
436 }
437 
438 static u32 gen8_oa_hw_tail_read(struct i915_perf_stream *stream)
439 {
440 	struct intel_uncore *uncore = stream->uncore;
441 
442 	return intel_uncore_read(uncore, GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
443 }
444 
445 static u32 gen7_oa_hw_tail_read(struct i915_perf_stream *stream)
446 {
447 	struct intel_uncore *uncore = stream->uncore;
448 	u32 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
449 
450 	return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
451 }
452 
453 /**
454  * oa_buffer_check_unlocked - check for data and update tail ptr state
455  * @stream: i915 stream instance
456  *
457  * This is either called via fops (for blocking reads in user ctx) or the poll
458  * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
459  * if there is data available for userspace to read.
460  *
461  * This function is central to providing a workaround for the OA unit tail
462  * pointer having a race with respect to what data is visible to the CPU.
463  * It is responsible for reading tail pointers from the hardware and giving
464  * the pointers time to 'age' before they are made available for reading.
465  * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
466  *
467  * Besides returning true when there is data available to read() this function
468  * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
469  * and .aged_tail_idx state used for reading.
470  *
471  * Note: It's safe to read OA config state here unlocked, assuming that this is
472  * only called while the stream is enabled, while the global OA configuration
473  * can't be modified.
474  *
475  * Returns: %true if the OA buffer contains data, else %false
476  */
477 static bool oa_buffer_check_unlocked(struct i915_perf_stream *stream)
478 {
479 	int report_size = stream->oa_buffer.format_size;
480 	unsigned long flags;
481 	unsigned int aged_idx;
482 	u32 head, hw_tail, aged_tail, aging_tail;
483 	u64 now;
484 
485 	/* We have to consider the (unlikely) possibility that read() errors
486 	 * could result in an OA buffer reset which might reset the head,
487 	 * tails[] and aged_tail state.
488 	 */
489 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
490 
491 	/* NB: The head we observe here might effectively be a little out of
492 	 * date (between head and tails[aged_idx].offset if there is currently
493 	 * a read() in progress.
494 	 */
495 	head = stream->oa_buffer.head;
496 
497 	aged_idx = stream->oa_buffer.aged_tail_idx;
498 	aged_tail = stream->oa_buffer.tails[aged_idx].offset;
499 	aging_tail = stream->oa_buffer.tails[!aged_idx].offset;
500 
501 	hw_tail = stream->perf->ops.oa_hw_tail_read(stream);
502 
503 	/* The tail pointer increases in 64 byte increments,
504 	 * not in report_size steps...
505 	 */
506 	hw_tail &= ~(report_size - 1);
507 
508 	now = ktime_get_mono_fast_ns();
509 
510 	/* Update the aged tail
511 	 *
512 	 * Flip the tail pointer available for read()s once the aging tail is
513 	 * old enough to trust that the corresponding data will be visible to
514 	 * the CPU...
515 	 *
516 	 * Do this before updating the aging pointer in case we may be able to
517 	 * immediately start aging a new pointer too (if new data has become
518 	 * available) without needing to wait for a later hrtimer callback.
519 	 */
520 	if (aging_tail != INVALID_TAIL_PTR &&
521 	    ((now - stream->oa_buffer.aging_timestamp) >
522 	     OA_TAIL_MARGIN_NSEC)) {
523 
524 		aged_idx ^= 1;
525 		stream->oa_buffer.aged_tail_idx = aged_idx;
526 
527 		aged_tail = aging_tail;
528 
529 		/* Mark that we need a new pointer to start aging... */
530 		stream->oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
531 		aging_tail = INVALID_TAIL_PTR;
532 	}
533 
534 	/* Update the aging tail
535 	 *
536 	 * We throttle aging tail updates until we have a new tail that
537 	 * represents >= one report more data than is already available for
538 	 * reading. This ensures there will be enough data for a successful
539 	 * read once this new pointer has aged and ensures we will give the new
540 	 * pointer time to age.
541 	 */
542 	if (aging_tail == INVALID_TAIL_PTR &&
543 	    (aged_tail == INVALID_TAIL_PTR ||
544 	     OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
545 		struct i915_vma *vma = stream->oa_buffer.vma;
546 		u32 gtt_offset = i915_ggtt_offset(vma);
547 
548 		/* Be paranoid and do a bounds check on the pointer read back
549 		 * from hardware, just in case some spurious hardware condition
550 		 * could put the tail out of bounds...
551 		 */
552 		if (hw_tail >= gtt_offset &&
553 		    hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
554 			stream->oa_buffer.tails[!aged_idx].offset =
555 				aging_tail = hw_tail;
556 			stream->oa_buffer.aging_timestamp = now;
557 		} else {
558 			drm_err(&stream->perf->i915->drm,
559 				"Ignoring spurious out of range OA buffer tail pointer = %x\n",
560 				hw_tail);
561 		}
562 	}
563 
564 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
565 
566 	return aged_tail == INVALID_TAIL_PTR ?
567 		false : OA_TAKEN(aged_tail, head) >= report_size;
568 }
569 
570 /**
571  * append_oa_status - Appends a status record to a userspace read() buffer.
572  * @stream: An i915-perf stream opened for OA metrics
573  * @buf: destination buffer given by userspace
574  * @count: the number of bytes userspace wants to read
575  * @offset: (inout): the current position for writing into @buf
576  * @type: The kind of status to report to userspace
577  *
578  * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
579  * into the userspace read() buffer.
580  *
581  * The @buf @offset will only be updated on success.
582  *
583  * Returns: 0 on success, negative error code on failure.
584  */
585 static int append_oa_status(struct i915_perf_stream *stream,
586 			    char __user *buf,
587 			    size_t count,
588 			    size_t *offset,
589 			    enum drm_i915_perf_record_type type)
590 {
591 	struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
592 
593 	if ((count - *offset) < header.size)
594 		return -ENOSPC;
595 
596 	if (copy_to_user(buf + *offset, &header, sizeof(header)))
597 		return -EFAULT;
598 
599 	(*offset) += header.size;
600 
601 	return 0;
602 }
603 
604 /**
605  * append_oa_sample - Copies single OA report into userspace read() buffer.
606  * @stream: An i915-perf stream opened for OA metrics
607  * @buf: destination buffer given by userspace
608  * @count: the number of bytes userspace wants to read
609  * @offset: (inout): the current position for writing into @buf
610  * @report: A single OA report to (optionally) include as part of the sample
611  *
612  * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
613  * properties when opening a stream, tracked as `stream->sample_flags`. This
614  * function copies the requested components of a single sample to the given
615  * read() @buf.
616  *
617  * The @buf @offset will only be updated on success.
618  *
619  * Returns: 0 on success, negative error code on failure.
620  */
621 static int append_oa_sample(struct i915_perf_stream *stream,
622 			    char __user *buf,
623 			    size_t count,
624 			    size_t *offset,
625 			    const u8 *report)
626 {
627 	int report_size = stream->oa_buffer.format_size;
628 	struct drm_i915_perf_record_header header;
629 	u32 sample_flags = stream->sample_flags;
630 
631 	header.type = DRM_I915_PERF_RECORD_SAMPLE;
632 	header.pad = 0;
633 	header.size = stream->sample_size;
634 
635 	if ((count - *offset) < header.size)
636 		return -ENOSPC;
637 
638 	buf += *offset;
639 	if (copy_to_user(buf, &header, sizeof(header)))
640 		return -EFAULT;
641 	buf += sizeof(header);
642 
643 	if (sample_flags & SAMPLE_OA_REPORT) {
644 		if (copy_to_user(buf, report, report_size))
645 			return -EFAULT;
646 	}
647 
648 	(*offset) += header.size;
649 
650 	return 0;
651 }
652 
653 /**
654  * Copies all buffered OA reports into userspace read() buffer.
655  * @stream: An i915-perf stream opened for OA metrics
656  * @buf: destination buffer given by userspace
657  * @count: the number of bytes userspace wants to read
658  * @offset: (inout): the current position for writing into @buf
659  *
660  * Notably any error condition resulting in a short read (-%ENOSPC or
661  * -%EFAULT) will be returned even though one or more records may
662  * have been successfully copied. In this case it's up to the caller
663  * to decide if the error should be squashed before returning to
664  * userspace.
665  *
666  * Note: reports are consumed from the head, and appended to the
667  * tail, so the tail chases the head?... If you think that's mad
668  * and back-to-front you're not alone, but this follows the
669  * Gen PRM naming convention.
670  *
671  * Returns: 0 on success, negative error code on failure.
672  */
673 static int gen8_append_oa_reports(struct i915_perf_stream *stream,
674 				  char __user *buf,
675 				  size_t count,
676 				  size_t *offset)
677 {
678 	struct intel_uncore *uncore = stream->uncore;
679 	int report_size = stream->oa_buffer.format_size;
680 	u8 *oa_buf_base = stream->oa_buffer.vaddr;
681 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
682 	u32 mask = (OA_BUFFER_SIZE - 1);
683 	size_t start_offset = *offset;
684 	unsigned long flags;
685 	unsigned int aged_tail_idx;
686 	u32 head, tail;
687 	u32 taken;
688 	int ret = 0;
689 
690 	if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
691 		return -EIO;
692 
693 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
694 
695 	head = stream->oa_buffer.head;
696 	aged_tail_idx = stream->oa_buffer.aged_tail_idx;
697 	tail = stream->oa_buffer.tails[aged_tail_idx].offset;
698 
699 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
700 
701 	/*
702 	 * An invalid tail pointer here means we're still waiting for the poll
703 	 * hrtimer callback to give us a pointer
704 	 */
705 	if (tail == INVALID_TAIL_PTR)
706 		return -EAGAIN;
707 
708 	/*
709 	 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
710 	 * while indexing relative to oa_buf_base.
711 	 */
712 	head -= gtt_offset;
713 	tail -= gtt_offset;
714 
715 	/*
716 	 * An out of bounds or misaligned head or tail pointer implies a driver
717 	 * bug since we validate + align the tail pointers we read from the
718 	 * hardware and we are in full control of the head pointer which should
719 	 * only be incremented by multiples of the report size (notably also
720 	 * all a power of two).
721 	 */
722 	if (drm_WARN_ONCE(&uncore->i915->drm,
723 			  head > OA_BUFFER_SIZE || head % report_size ||
724 			  tail > OA_BUFFER_SIZE || tail % report_size,
725 			  "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
726 			  head, tail))
727 		return -EIO;
728 
729 
730 	for (/* none */;
731 	     (taken = OA_TAKEN(tail, head));
732 	     head = (head + report_size) & mask) {
733 		u8 *report = oa_buf_base + head;
734 		u32 *report32 = (void *)report;
735 		u32 ctx_id;
736 		u32 reason;
737 
738 		/*
739 		 * All the report sizes factor neatly into the buffer
740 		 * size so we never expect to see a report split
741 		 * between the beginning and end of the buffer.
742 		 *
743 		 * Given the initial alignment check a misalignment
744 		 * here would imply a driver bug that would result
745 		 * in an overrun.
746 		 */
747 		if (drm_WARN_ON(&uncore->i915->drm,
748 				(OA_BUFFER_SIZE - head) < report_size)) {
749 			drm_err(&uncore->i915->drm,
750 				"Spurious OA head ptr: non-integral report offset\n");
751 			break;
752 		}
753 
754 		/*
755 		 * The reason field includes flags identifying what
756 		 * triggered this specific report (mostly timer
757 		 * triggered or e.g. due to a context switch).
758 		 *
759 		 * This field is never expected to be zero so we can
760 		 * check that the report isn't invalid before copying
761 		 * it to userspace...
762 		 */
763 		reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
764 			  (IS_GEN(stream->perf->i915, 12) ?
765 			   OAREPORT_REASON_MASK_EXTENDED :
766 			   OAREPORT_REASON_MASK));
767 		if (reason == 0) {
768 			if (__ratelimit(&stream->perf->spurious_report_rs))
769 				DRM_NOTE("Skipping spurious, invalid OA report\n");
770 			continue;
771 		}
772 
773 		ctx_id = report32[2] & stream->specific_ctx_id_mask;
774 
775 		/*
776 		 * Squash whatever is in the CTX_ID field if it's marked as
777 		 * invalid to be sure we avoid false-positive, single-context
778 		 * filtering below...
779 		 *
780 		 * Note: that we don't clear the valid_ctx_bit so userspace can
781 		 * understand that the ID has been squashed by the kernel.
782 		 */
783 		if (!(report32[0] & stream->perf->gen8_valid_ctx_bit) &&
784 		    INTEL_GEN(stream->perf->i915) <= 11)
785 			ctx_id = report32[2] = INVALID_CTX_ID;
786 
787 		/*
788 		 * NB: For Gen 8 the OA unit no longer supports clock gating
789 		 * off for a specific context and the kernel can't securely
790 		 * stop the counters from updating as system-wide / global
791 		 * values.
792 		 *
793 		 * Automatic reports now include a context ID so reports can be
794 		 * filtered on the cpu but it's not worth trying to
795 		 * automatically subtract/hide counter progress for other
796 		 * contexts while filtering since we can't stop userspace
797 		 * issuing MI_REPORT_PERF_COUNT commands which would still
798 		 * provide a side-band view of the real values.
799 		 *
800 		 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
801 		 * to normalize counters for a single filtered context then it
802 		 * needs be forwarded bookend context-switch reports so that it
803 		 * can track switches in between MI_REPORT_PERF_COUNT commands
804 		 * and can itself subtract/ignore the progress of counters
805 		 * associated with other contexts. Note that the hardware
806 		 * automatically triggers reports when switching to a new
807 		 * context which are tagged with the ID of the newly active
808 		 * context. To avoid the complexity (and likely fragility) of
809 		 * reading ahead while parsing reports to try and minimize
810 		 * forwarding redundant context switch reports (i.e. between
811 		 * other, unrelated contexts) we simply elect to forward them
812 		 * all.
813 		 *
814 		 * We don't rely solely on the reason field to identify context
815 		 * switches since it's not-uncommon for periodic samples to
816 		 * identify a switch before any 'context switch' report.
817 		 */
818 		if (!stream->perf->exclusive_stream->ctx ||
819 		    stream->specific_ctx_id == ctx_id ||
820 		    stream->oa_buffer.last_ctx_id == stream->specific_ctx_id ||
821 		    reason & OAREPORT_REASON_CTX_SWITCH) {
822 
823 			/*
824 			 * While filtering for a single context we avoid
825 			 * leaking the IDs of other contexts.
826 			 */
827 			if (stream->perf->exclusive_stream->ctx &&
828 			    stream->specific_ctx_id != ctx_id) {
829 				report32[2] = INVALID_CTX_ID;
830 			}
831 
832 			ret = append_oa_sample(stream, buf, count, offset,
833 					       report);
834 			if (ret)
835 				break;
836 
837 			stream->oa_buffer.last_ctx_id = ctx_id;
838 		}
839 
840 		/*
841 		 * The above reason field sanity check is based on
842 		 * the assumption that the OA buffer is initially
843 		 * zeroed and we reset the field after copying so the
844 		 * check is still meaningful once old reports start
845 		 * being overwritten.
846 		 */
847 		report32[0] = 0;
848 	}
849 
850 	if (start_offset != *offset) {
851 		i915_reg_t oaheadptr;
852 
853 		oaheadptr = IS_GEN(stream->perf->i915, 12) ?
854 			    GEN12_OAG_OAHEADPTR : GEN8_OAHEADPTR;
855 
856 		spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
857 
858 		/*
859 		 * We removed the gtt_offset for the copy loop above, indexing
860 		 * relative to oa_buf_base so put back here...
861 		 */
862 		head += gtt_offset;
863 		intel_uncore_write(uncore, oaheadptr,
864 				   head & GEN12_OAG_OAHEADPTR_MASK);
865 		stream->oa_buffer.head = head;
866 
867 		spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
868 	}
869 
870 	return ret;
871 }
872 
873 /**
874  * gen8_oa_read - copy status records then buffered OA reports
875  * @stream: An i915-perf stream opened for OA metrics
876  * @buf: destination buffer given by userspace
877  * @count: the number of bytes userspace wants to read
878  * @offset: (inout): the current position for writing into @buf
879  *
880  * Checks OA unit status registers and if necessary appends corresponding
881  * status records for userspace (such as for a buffer full condition) and then
882  * initiate appending any buffered OA reports.
883  *
884  * Updates @offset according to the number of bytes successfully copied into
885  * the userspace buffer.
886  *
887  * NB: some data may be successfully copied to the userspace buffer
888  * even if an error is returned, and this is reflected in the
889  * updated @offset.
890  *
891  * Returns: zero on success or a negative error code
892  */
893 static int gen8_oa_read(struct i915_perf_stream *stream,
894 			char __user *buf,
895 			size_t count,
896 			size_t *offset)
897 {
898 	struct intel_uncore *uncore = stream->uncore;
899 	u32 oastatus;
900 	i915_reg_t oastatus_reg;
901 	int ret;
902 
903 	if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
904 		return -EIO;
905 
906 	oastatus_reg = IS_GEN(stream->perf->i915, 12) ?
907 		       GEN12_OAG_OASTATUS : GEN8_OASTATUS;
908 
909 	oastatus = intel_uncore_read(uncore, oastatus_reg);
910 
911 	/*
912 	 * We treat OABUFFER_OVERFLOW as a significant error:
913 	 *
914 	 * Although theoretically we could handle this more gracefully
915 	 * sometimes, some Gens don't correctly suppress certain
916 	 * automatically triggered reports in this condition and so we
917 	 * have to assume that old reports are now being trampled
918 	 * over.
919 	 *
920 	 * Considering how we don't currently give userspace control
921 	 * over the OA buffer size and always configure a large 16MB
922 	 * buffer, then a buffer overflow does anyway likely indicate
923 	 * that something has gone quite badly wrong.
924 	 */
925 	if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
926 		ret = append_oa_status(stream, buf, count, offset,
927 				       DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
928 		if (ret)
929 			return ret;
930 
931 		DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
932 			  stream->period_exponent);
933 
934 		stream->perf->ops.oa_disable(stream);
935 		stream->perf->ops.oa_enable(stream);
936 
937 		/*
938 		 * Note: .oa_enable() is expected to re-init the oabuffer and
939 		 * reset GEN8_OASTATUS for us
940 		 */
941 		oastatus = intel_uncore_read(uncore, oastatus_reg);
942 	}
943 
944 	if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
945 		ret = append_oa_status(stream, buf, count, offset,
946 				       DRM_I915_PERF_RECORD_OA_REPORT_LOST);
947 		if (ret)
948 			return ret;
949 		intel_uncore_write(uncore, oastatus_reg,
950 				   oastatus & ~GEN8_OASTATUS_REPORT_LOST);
951 	}
952 
953 	return gen8_append_oa_reports(stream, buf, count, offset);
954 }
955 
956 /**
957  * Copies all buffered OA reports into userspace read() buffer.
958  * @stream: An i915-perf stream opened for OA metrics
959  * @buf: destination buffer given by userspace
960  * @count: the number of bytes userspace wants to read
961  * @offset: (inout): the current position for writing into @buf
962  *
963  * Notably any error condition resulting in a short read (-%ENOSPC or
964  * -%EFAULT) will be returned even though one or more records may
965  * have been successfully copied. In this case it's up to the caller
966  * to decide if the error should be squashed before returning to
967  * userspace.
968  *
969  * Note: reports are consumed from the head, and appended to the
970  * tail, so the tail chases the head?... If you think that's mad
971  * and back-to-front you're not alone, but this follows the
972  * Gen PRM naming convention.
973  *
974  * Returns: 0 on success, negative error code on failure.
975  */
976 static int gen7_append_oa_reports(struct i915_perf_stream *stream,
977 				  char __user *buf,
978 				  size_t count,
979 				  size_t *offset)
980 {
981 	struct intel_uncore *uncore = stream->uncore;
982 	int report_size = stream->oa_buffer.format_size;
983 	u8 *oa_buf_base = stream->oa_buffer.vaddr;
984 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
985 	u32 mask = (OA_BUFFER_SIZE - 1);
986 	size_t start_offset = *offset;
987 	unsigned long flags;
988 	unsigned int aged_tail_idx;
989 	u32 head, tail;
990 	u32 taken;
991 	int ret = 0;
992 
993 	if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
994 		return -EIO;
995 
996 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
997 
998 	head = stream->oa_buffer.head;
999 	aged_tail_idx = stream->oa_buffer.aged_tail_idx;
1000 	tail = stream->oa_buffer.tails[aged_tail_idx].offset;
1001 
1002 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1003 
1004 	/* An invalid tail pointer here means we're still waiting for the poll
1005 	 * hrtimer callback to give us a pointer
1006 	 */
1007 	if (tail == INVALID_TAIL_PTR)
1008 		return -EAGAIN;
1009 
1010 	/* NB: oa_buffer.head/tail include the gtt_offset which we don't want
1011 	 * while indexing relative to oa_buf_base.
1012 	 */
1013 	head -= gtt_offset;
1014 	tail -= gtt_offset;
1015 
1016 	/* An out of bounds or misaligned head or tail pointer implies a driver
1017 	 * bug since we validate + align the tail pointers we read from the
1018 	 * hardware and we are in full control of the head pointer which should
1019 	 * only be incremented by multiples of the report size (notably also
1020 	 * all a power of two).
1021 	 */
1022 	if (drm_WARN_ONCE(&uncore->i915->drm,
1023 			  head > OA_BUFFER_SIZE || head % report_size ||
1024 			  tail > OA_BUFFER_SIZE || tail % report_size,
1025 			  "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
1026 			  head, tail))
1027 		return -EIO;
1028 
1029 
1030 	for (/* none */;
1031 	     (taken = OA_TAKEN(tail, head));
1032 	     head = (head + report_size) & mask) {
1033 		u8 *report = oa_buf_base + head;
1034 		u32 *report32 = (void *)report;
1035 
1036 		/* All the report sizes factor neatly into the buffer
1037 		 * size so we never expect to see a report split
1038 		 * between the beginning and end of the buffer.
1039 		 *
1040 		 * Given the initial alignment check a misalignment
1041 		 * here would imply a driver bug that would result
1042 		 * in an overrun.
1043 		 */
1044 		if (drm_WARN_ON(&uncore->i915->drm,
1045 				(OA_BUFFER_SIZE - head) < report_size)) {
1046 			drm_err(&uncore->i915->drm,
1047 				"Spurious OA head ptr: non-integral report offset\n");
1048 			break;
1049 		}
1050 
1051 		/* The report-ID field for periodic samples includes
1052 		 * some undocumented flags related to what triggered
1053 		 * the report and is never expected to be zero so we
1054 		 * can check that the report isn't invalid before
1055 		 * copying it to userspace...
1056 		 */
1057 		if (report32[0] == 0) {
1058 			if (__ratelimit(&stream->perf->spurious_report_rs))
1059 				DRM_NOTE("Skipping spurious, invalid OA report\n");
1060 			continue;
1061 		}
1062 
1063 		ret = append_oa_sample(stream, buf, count, offset, report);
1064 		if (ret)
1065 			break;
1066 
1067 		/* The above report-id field sanity check is based on
1068 		 * the assumption that the OA buffer is initially
1069 		 * zeroed and we reset the field after copying so the
1070 		 * check is still meaningful once old reports start
1071 		 * being overwritten.
1072 		 */
1073 		report32[0] = 0;
1074 	}
1075 
1076 	if (start_offset != *offset) {
1077 		spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1078 
1079 		/* We removed the gtt_offset for the copy loop above, indexing
1080 		 * relative to oa_buf_base so put back here...
1081 		 */
1082 		head += gtt_offset;
1083 
1084 		intel_uncore_write(uncore, GEN7_OASTATUS2,
1085 				   (head & GEN7_OASTATUS2_HEAD_MASK) |
1086 				   GEN7_OASTATUS2_MEM_SELECT_GGTT);
1087 		stream->oa_buffer.head = head;
1088 
1089 		spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1090 	}
1091 
1092 	return ret;
1093 }
1094 
1095 /**
1096  * gen7_oa_read - copy status records then buffered OA reports
1097  * @stream: An i915-perf stream opened for OA metrics
1098  * @buf: destination buffer given by userspace
1099  * @count: the number of bytes userspace wants to read
1100  * @offset: (inout): the current position for writing into @buf
1101  *
1102  * Checks Gen 7 specific OA unit status registers and if necessary appends
1103  * corresponding status records for userspace (such as for a buffer full
1104  * condition) and then initiate appending any buffered OA reports.
1105  *
1106  * Updates @offset according to the number of bytes successfully copied into
1107  * the userspace buffer.
1108  *
1109  * Returns: zero on success or a negative error code
1110  */
1111 static int gen7_oa_read(struct i915_perf_stream *stream,
1112 			char __user *buf,
1113 			size_t count,
1114 			size_t *offset)
1115 {
1116 	struct intel_uncore *uncore = stream->uncore;
1117 	u32 oastatus1;
1118 	int ret;
1119 
1120 	if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
1121 		return -EIO;
1122 
1123 	oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1124 
1125 	/* XXX: On Haswell we don't have a safe way to clear oastatus1
1126 	 * bits while the OA unit is enabled (while the tail pointer
1127 	 * may be updated asynchronously) so we ignore status bits
1128 	 * that have already been reported to userspace.
1129 	 */
1130 	oastatus1 &= ~stream->perf->gen7_latched_oastatus1;
1131 
1132 	/* We treat OABUFFER_OVERFLOW as a significant error:
1133 	 *
1134 	 * - The status can be interpreted to mean that the buffer is
1135 	 *   currently full (with a higher precedence than OA_TAKEN()
1136 	 *   which will start to report a near-empty buffer after an
1137 	 *   overflow) but it's awkward that we can't clear the status
1138 	 *   on Haswell, so without a reset we won't be able to catch
1139 	 *   the state again.
1140 	 *
1141 	 * - Since it also implies the HW has started overwriting old
1142 	 *   reports it may also affect our sanity checks for invalid
1143 	 *   reports when copying to userspace that assume new reports
1144 	 *   are being written to cleared memory.
1145 	 *
1146 	 * - In the future we may want to introduce a flight recorder
1147 	 *   mode where the driver will automatically maintain a safe
1148 	 *   guard band between head/tail, avoiding this overflow
1149 	 *   condition, but we avoid the added driver complexity for
1150 	 *   now.
1151 	 */
1152 	if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1153 		ret = append_oa_status(stream, buf, count, offset,
1154 				       DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1155 		if (ret)
1156 			return ret;
1157 
1158 		DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
1159 			  stream->period_exponent);
1160 
1161 		stream->perf->ops.oa_disable(stream);
1162 		stream->perf->ops.oa_enable(stream);
1163 
1164 		oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1165 	}
1166 
1167 	if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1168 		ret = append_oa_status(stream, buf, count, offset,
1169 				       DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1170 		if (ret)
1171 			return ret;
1172 		stream->perf->gen7_latched_oastatus1 |=
1173 			GEN7_OASTATUS1_REPORT_LOST;
1174 	}
1175 
1176 	return gen7_append_oa_reports(stream, buf, count, offset);
1177 }
1178 
1179 /**
1180  * i915_oa_wait_unlocked - handles blocking IO until OA data available
1181  * @stream: An i915-perf stream opened for OA metrics
1182  *
1183  * Called when userspace tries to read() from a blocking stream FD opened
1184  * for OA metrics. It waits until the hrtimer callback finds a non-empty
1185  * OA buffer and wakes us.
1186  *
1187  * Note: it's acceptable to have this return with some false positives
1188  * since any subsequent read handling will return -EAGAIN if there isn't
1189  * really data ready for userspace yet.
1190  *
1191  * Returns: zero on success or a negative error code
1192  */
1193 static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1194 {
1195 	/* We would wait indefinitely if periodic sampling is not enabled */
1196 	if (!stream->periodic)
1197 		return -EIO;
1198 
1199 	return wait_event_interruptible(stream->poll_wq,
1200 					oa_buffer_check_unlocked(stream));
1201 }
1202 
1203 /**
1204  * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1205  * @stream: An i915-perf stream opened for OA metrics
1206  * @file: An i915 perf stream file
1207  * @wait: poll() state table
1208  *
1209  * For handling userspace polling on an i915 perf stream opened for OA metrics,
1210  * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1211  * when it sees data ready to read in the circular OA buffer.
1212  */
1213 static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1214 			      struct file *file,
1215 			      poll_table *wait)
1216 {
1217 	poll_wait(file, &stream->poll_wq, wait);
1218 }
1219 
1220 /**
1221  * i915_oa_read - just calls through to &i915_oa_ops->read
1222  * @stream: An i915-perf stream opened for OA metrics
1223  * @buf: destination buffer given by userspace
1224  * @count: the number of bytes userspace wants to read
1225  * @offset: (inout): the current position for writing into @buf
1226  *
1227  * Updates @offset according to the number of bytes successfully copied into
1228  * the userspace buffer.
1229  *
1230  * Returns: zero on success or a negative error code
1231  */
1232 static int i915_oa_read(struct i915_perf_stream *stream,
1233 			char __user *buf,
1234 			size_t count,
1235 			size_t *offset)
1236 {
1237 	return stream->perf->ops.read(stream, buf, count, offset);
1238 }
1239 
1240 static struct intel_context *oa_pin_context(struct i915_perf_stream *stream)
1241 {
1242 	struct i915_gem_engines_iter it;
1243 	struct i915_gem_context *ctx = stream->ctx;
1244 	struct intel_context *ce;
1245 	int err;
1246 
1247 	for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
1248 		if (ce->engine != stream->engine) /* first match! */
1249 			continue;
1250 
1251 		/*
1252 		 * As the ID is the gtt offset of the context's vma we
1253 		 * pin the vma to ensure the ID remains fixed.
1254 		 */
1255 		err = intel_context_pin(ce);
1256 		if (err == 0) {
1257 			stream->pinned_ctx = ce;
1258 			break;
1259 		}
1260 	}
1261 	i915_gem_context_unlock_engines(ctx);
1262 
1263 	return stream->pinned_ctx;
1264 }
1265 
1266 /**
1267  * oa_get_render_ctx_id - determine and hold ctx hw id
1268  * @stream: An i915-perf stream opened for OA metrics
1269  *
1270  * Determine the render context hw id, and ensure it remains fixed for the
1271  * lifetime of the stream. This ensures that we don't have to worry about
1272  * updating the context ID in OACONTROL on the fly.
1273  *
1274  * Returns: zero on success or a negative error code
1275  */
1276 static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1277 {
1278 	struct intel_context *ce;
1279 
1280 	ce = oa_pin_context(stream);
1281 	if (IS_ERR(ce))
1282 		return PTR_ERR(ce);
1283 
1284 	switch (INTEL_GEN(ce->engine->i915)) {
1285 	case 7: {
1286 		/*
1287 		 * On Haswell we don't do any post processing of the reports
1288 		 * and don't need to use the mask.
1289 		 */
1290 		stream->specific_ctx_id = i915_ggtt_offset(ce->state);
1291 		stream->specific_ctx_id_mask = 0;
1292 		break;
1293 	}
1294 
1295 	case 8:
1296 	case 9:
1297 	case 10:
1298 		if (intel_engine_in_execlists_submission_mode(ce->engine)) {
1299 			stream->specific_ctx_id_mask =
1300 				(1U << GEN8_CTX_ID_WIDTH) - 1;
1301 			stream->specific_ctx_id = stream->specific_ctx_id_mask;
1302 		} else {
1303 			/*
1304 			 * When using GuC, the context descriptor we write in
1305 			 * i915 is read by GuC and rewritten before it's
1306 			 * actually written into the hardware. The LRCA is
1307 			 * what is put into the context id field of the
1308 			 * context descriptor by GuC. Because it's aligned to
1309 			 * a page, the lower 12bits are always at 0 and
1310 			 * dropped by GuC. They won't be part of the context
1311 			 * ID in the OA reports, so squash those lower bits.
1312 			 */
1313 			stream->specific_ctx_id =
1314 				lower_32_bits(ce->lrc_desc) >> 12;
1315 
1316 			/*
1317 			 * GuC uses the top bit to signal proxy submission, so
1318 			 * ignore that bit.
1319 			 */
1320 			stream->specific_ctx_id_mask =
1321 				(1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
1322 		}
1323 		break;
1324 
1325 	case 11:
1326 	case 12: {
1327 		stream->specific_ctx_id_mask =
1328 			((1U << GEN11_SW_CTX_ID_WIDTH) - 1) << (GEN11_SW_CTX_ID_SHIFT - 32);
1329 		/*
1330 		 * Pick an unused context id
1331 		 * 0 - (NUM_CONTEXT_TAG - 1) are used by other contexts
1332 		 * GEN12_MAX_CONTEXT_HW_ID (0x7ff) is used by idle context
1333 		 */
1334 		stream->specific_ctx_id = (GEN12_MAX_CONTEXT_HW_ID - 1) << (GEN11_SW_CTX_ID_SHIFT - 32);
1335 		BUILD_BUG_ON((GEN12_MAX_CONTEXT_HW_ID - 1) < NUM_CONTEXT_TAG);
1336 		break;
1337 	}
1338 
1339 	default:
1340 		MISSING_CASE(INTEL_GEN(ce->engine->i915));
1341 	}
1342 
1343 	ce->tag = stream->specific_ctx_id;
1344 
1345 	drm_dbg(&stream->perf->i915->drm,
1346 		"filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
1347 		stream->specific_ctx_id,
1348 		stream->specific_ctx_id_mask);
1349 
1350 	return 0;
1351 }
1352 
1353 /**
1354  * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1355  * @stream: An i915-perf stream opened for OA metrics
1356  *
1357  * In case anything needed doing to ensure the context HW ID would remain valid
1358  * for the lifetime of the stream, then that can be undone here.
1359  */
1360 static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1361 {
1362 	struct intel_context *ce;
1363 
1364 	ce = fetch_and_zero(&stream->pinned_ctx);
1365 	if (ce) {
1366 		ce->tag = 0; /* recomputed on next submission after parking */
1367 		intel_context_unpin(ce);
1368 	}
1369 
1370 	stream->specific_ctx_id = INVALID_CTX_ID;
1371 	stream->specific_ctx_id_mask = 0;
1372 }
1373 
1374 static void
1375 free_oa_buffer(struct i915_perf_stream *stream)
1376 {
1377 	i915_vma_unpin_and_release(&stream->oa_buffer.vma,
1378 				   I915_VMA_RELEASE_MAP);
1379 
1380 	stream->oa_buffer.vaddr = NULL;
1381 }
1382 
1383 static void
1384 free_oa_configs(struct i915_perf_stream *stream)
1385 {
1386 	struct i915_oa_config_bo *oa_bo, *tmp;
1387 
1388 	i915_oa_config_put(stream->oa_config);
1389 	llist_for_each_entry_safe(oa_bo, tmp, stream->oa_config_bos.first, node)
1390 		free_oa_config_bo(oa_bo);
1391 }
1392 
1393 static void
1394 free_noa_wait(struct i915_perf_stream *stream)
1395 {
1396 	i915_vma_unpin_and_release(&stream->noa_wait, 0);
1397 }
1398 
1399 static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1400 {
1401 	struct i915_perf *perf = stream->perf;
1402 
1403 	BUG_ON(stream != perf->exclusive_stream);
1404 
1405 	/*
1406 	 * Unset exclusive_stream first, it will be checked while disabling
1407 	 * the metric set on gen8+.
1408 	 */
1409 	perf->exclusive_stream = NULL;
1410 	perf->ops.disable_metric_set(stream);
1411 
1412 	free_oa_buffer(stream);
1413 
1414 	intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
1415 	intel_engine_pm_put(stream->engine);
1416 
1417 	if (stream->ctx)
1418 		oa_put_render_ctx_id(stream);
1419 
1420 	free_oa_configs(stream);
1421 	free_noa_wait(stream);
1422 
1423 	if (perf->spurious_report_rs.missed) {
1424 		DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1425 			 perf->spurious_report_rs.missed);
1426 	}
1427 }
1428 
1429 static void gen7_init_oa_buffer(struct i915_perf_stream *stream)
1430 {
1431 	struct intel_uncore *uncore = stream->uncore;
1432 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1433 	unsigned long flags;
1434 
1435 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1436 
1437 	/* Pre-DevBDW: OABUFFER must be set with counters off,
1438 	 * before OASTATUS1, but after OASTATUS2
1439 	 */
1440 	intel_uncore_write(uncore, GEN7_OASTATUS2, /* head */
1441 			   gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT);
1442 	stream->oa_buffer.head = gtt_offset;
1443 
1444 	intel_uncore_write(uncore, GEN7_OABUFFER, gtt_offset);
1445 
1446 	intel_uncore_write(uncore, GEN7_OASTATUS1, /* tail */
1447 			   gtt_offset | OABUFFER_SIZE_16M);
1448 
1449 	/* Mark that we need updated tail pointers to read from... */
1450 	stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1451 	stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1452 
1453 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1454 
1455 	/* On Haswell we have to track which OASTATUS1 flags we've
1456 	 * already seen since they can't be cleared while periodic
1457 	 * sampling is enabled.
1458 	 */
1459 	stream->perf->gen7_latched_oastatus1 = 0;
1460 
1461 	/* NB: although the OA buffer will initially be allocated
1462 	 * zeroed via shmfs (and so this memset is redundant when
1463 	 * first allocating), we may re-init the OA buffer, either
1464 	 * when re-enabling a stream or in error/reset paths.
1465 	 *
1466 	 * The reason we clear the buffer for each re-init is for the
1467 	 * sanity check in gen7_append_oa_reports() that looks at the
1468 	 * report-id field to make sure it's non-zero which relies on
1469 	 * the assumption that new reports are being written to zeroed
1470 	 * memory...
1471 	 */
1472 	memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1473 
1474 	stream->pollin = false;
1475 }
1476 
1477 static void gen8_init_oa_buffer(struct i915_perf_stream *stream)
1478 {
1479 	struct intel_uncore *uncore = stream->uncore;
1480 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1481 	unsigned long flags;
1482 
1483 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1484 
1485 	intel_uncore_write(uncore, GEN8_OASTATUS, 0);
1486 	intel_uncore_write(uncore, GEN8_OAHEADPTR, gtt_offset);
1487 	stream->oa_buffer.head = gtt_offset;
1488 
1489 	intel_uncore_write(uncore, GEN8_OABUFFER_UDW, 0);
1490 
1491 	/*
1492 	 * PRM says:
1493 	 *
1494 	 *  "This MMIO must be set before the OATAILPTR
1495 	 *  register and after the OAHEADPTR register. This is
1496 	 *  to enable proper functionality of the overflow
1497 	 *  bit."
1498 	 */
1499 	intel_uncore_write(uncore, GEN8_OABUFFER, gtt_offset |
1500 		   OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1501 	intel_uncore_write(uncore, GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1502 
1503 	/* Mark that we need updated tail pointers to read from... */
1504 	stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1505 	stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1506 
1507 	/*
1508 	 * Reset state used to recognise context switches, affecting which
1509 	 * reports we will forward to userspace while filtering for a single
1510 	 * context.
1511 	 */
1512 	stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1513 
1514 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1515 
1516 	/*
1517 	 * NB: although the OA buffer will initially be allocated
1518 	 * zeroed via shmfs (and so this memset is redundant when
1519 	 * first allocating), we may re-init the OA buffer, either
1520 	 * when re-enabling a stream or in error/reset paths.
1521 	 *
1522 	 * The reason we clear the buffer for each re-init is for the
1523 	 * sanity check in gen8_append_oa_reports() that looks at the
1524 	 * reason field to make sure it's non-zero which relies on
1525 	 * the assumption that new reports are being written to zeroed
1526 	 * memory...
1527 	 */
1528 	memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1529 
1530 	stream->pollin = false;
1531 }
1532 
1533 static void gen12_init_oa_buffer(struct i915_perf_stream *stream)
1534 {
1535 	struct intel_uncore *uncore = stream->uncore;
1536 	u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1537 	unsigned long flags;
1538 
1539 	spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1540 
1541 	intel_uncore_write(uncore, GEN12_OAG_OASTATUS, 0);
1542 	intel_uncore_write(uncore, GEN12_OAG_OAHEADPTR,
1543 			   gtt_offset & GEN12_OAG_OAHEADPTR_MASK);
1544 	stream->oa_buffer.head = gtt_offset;
1545 
1546 	/*
1547 	 * PRM says:
1548 	 *
1549 	 *  "This MMIO must be set before the OATAILPTR
1550 	 *  register and after the OAHEADPTR register. This is
1551 	 *  to enable proper functionality of the overflow
1552 	 *  bit."
1553 	 */
1554 	intel_uncore_write(uncore, GEN12_OAG_OABUFFER, gtt_offset |
1555 			   OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1556 	intel_uncore_write(uncore, GEN12_OAG_OATAILPTR,
1557 			   gtt_offset & GEN12_OAG_OATAILPTR_MASK);
1558 
1559 	/* Mark that we need updated tail pointers to read from... */
1560 	stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1561 	stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1562 
1563 	/*
1564 	 * Reset state used to recognise context switches, affecting which
1565 	 * reports we will forward to userspace while filtering for a single
1566 	 * context.
1567 	 */
1568 	stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1569 
1570 	spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1571 
1572 	/*
1573 	 * NB: although the OA buffer will initially be allocated
1574 	 * zeroed via shmfs (and so this memset is redundant when
1575 	 * first allocating), we may re-init the OA buffer, either
1576 	 * when re-enabling a stream or in error/reset paths.
1577 	 *
1578 	 * The reason we clear the buffer for each re-init is for the
1579 	 * sanity check in gen8_append_oa_reports() that looks at the
1580 	 * reason field to make sure it's non-zero which relies on
1581 	 * the assumption that new reports are being written to zeroed
1582 	 * memory...
1583 	 */
1584 	memset(stream->oa_buffer.vaddr, 0,
1585 	       stream->oa_buffer.vma->size);
1586 
1587 	stream->pollin = false;
1588 }
1589 
1590 static int alloc_oa_buffer(struct i915_perf_stream *stream)
1591 {
1592 	struct drm_i915_private *i915 = stream->perf->i915;
1593 	struct drm_i915_gem_object *bo;
1594 	struct i915_vma *vma;
1595 	int ret;
1596 
1597 	if (drm_WARN_ON(&i915->drm, stream->oa_buffer.vma))
1598 		return -ENODEV;
1599 
1600 	BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1601 	BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1602 
1603 	bo = i915_gem_object_create_shmem(stream->perf->i915, OA_BUFFER_SIZE);
1604 	if (IS_ERR(bo)) {
1605 		drm_err(&i915->drm, "Failed to allocate OA buffer\n");
1606 		return PTR_ERR(bo);
1607 	}
1608 
1609 	i915_gem_object_set_cache_coherency(bo, I915_CACHE_LLC);
1610 
1611 	/* PreHSW required 512K alignment, HSW requires 16M */
1612 	vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1613 	if (IS_ERR(vma)) {
1614 		ret = PTR_ERR(vma);
1615 		goto err_unref;
1616 	}
1617 	stream->oa_buffer.vma = vma;
1618 
1619 	stream->oa_buffer.vaddr =
1620 		i915_gem_object_pin_map(bo, I915_MAP_WB);
1621 	if (IS_ERR(stream->oa_buffer.vaddr)) {
1622 		ret = PTR_ERR(stream->oa_buffer.vaddr);
1623 		goto err_unpin;
1624 	}
1625 
1626 	return 0;
1627 
1628 err_unpin:
1629 	__i915_vma_unpin(vma);
1630 
1631 err_unref:
1632 	i915_gem_object_put(bo);
1633 
1634 	stream->oa_buffer.vaddr = NULL;
1635 	stream->oa_buffer.vma = NULL;
1636 
1637 	return ret;
1638 }
1639 
1640 static u32 *save_restore_register(struct i915_perf_stream *stream, u32 *cs,
1641 				  bool save, i915_reg_t reg, u32 offset,
1642 				  u32 dword_count)
1643 {
1644 	u32 cmd;
1645 	u32 d;
1646 
1647 	cmd = save ? MI_STORE_REGISTER_MEM : MI_LOAD_REGISTER_MEM;
1648 	if (INTEL_GEN(stream->perf->i915) >= 8)
1649 		cmd++;
1650 
1651 	for (d = 0; d < dword_count; d++) {
1652 		*cs++ = cmd;
1653 		*cs++ = i915_mmio_reg_offset(reg) + 4 * d;
1654 		*cs++ = intel_gt_scratch_offset(stream->engine->gt,
1655 						offset) + 4 * d;
1656 		*cs++ = 0;
1657 	}
1658 
1659 	return cs;
1660 }
1661 
1662 static int alloc_noa_wait(struct i915_perf_stream *stream)
1663 {
1664 	struct drm_i915_private *i915 = stream->perf->i915;
1665 	struct drm_i915_gem_object *bo;
1666 	struct i915_vma *vma;
1667 	const u64 delay_ticks = 0xffffffffffffffff -
1668 		DIV64_U64_ROUND_UP(
1669 			atomic64_read(&stream->perf->noa_programming_delay) *
1670 			RUNTIME_INFO(i915)->cs_timestamp_frequency_khz,
1671 			1000000ull);
1672 	const u32 base = stream->engine->mmio_base;
1673 #define CS_GPR(x) GEN8_RING_CS_GPR(base, x)
1674 	u32 *batch, *ts0, *cs, *jump;
1675 	int ret, i;
1676 	enum {
1677 		START_TS,
1678 		NOW_TS,
1679 		DELTA_TS,
1680 		JUMP_PREDICATE,
1681 		DELTA_TARGET,
1682 		N_CS_GPR
1683 	};
1684 
1685 	bo = i915_gem_object_create_internal(i915, 4096);
1686 	if (IS_ERR(bo)) {
1687 		drm_err(&i915->drm,
1688 			"Failed to allocate NOA wait batchbuffer\n");
1689 		return PTR_ERR(bo);
1690 	}
1691 
1692 	/*
1693 	 * We pin in GGTT because we jump into this buffer now because
1694 	 * multiple OA config BOs will have a jump to this address and it
1695 	 * needs to be fixed during the lifetime of the i915/perf stream.
1696 	 */
1697 	vma = i915_gem_object_ggtt_pin(bo, NULL, 0, 0, PIN_HIGH);
1698 	if (IS_ERR(vma)) {
1699 		ret = PTR_ERR(vma);
1700 		goto err_unref;
1701 	}
1702 
1703 	batch = cs = i915_gem_object_pin_map(bo, I915_MAP_WB);
1704 	if (IS_ERR(batch)) {
1705 		ret = PTR_ERR(batch);
1706 		goto err_unpin;
1707 	}
1708 
1709 	/* Save registers. */
1710 	for (i = 0; i < N_CS_GPR; i++)
1711 		cs = save_restore_register(
1712 			stream, cs, true /* save */, CS_GPR(i),
1713 			INTEL_GT_SCRATCH_FIELD_PERF_CS_GPR + 8 * i, 2);
1714 	cs = save_restore_register(
1715 		stream, cs, true /* save */, MI_PREDICATE_RESULT_1,
1716 		INTEL_GT_SCRATCH_FIELD_PERF_PREDICATE_RESULT_1, 1);
1717 
1718 	/* First timestamp snapshot location. */
1719 	ts0 = cs;
1720 
1721 	/*
1722 	 * Initial snapshot of the timestamp register to implement the wait.
1723 	 * We work with 32b values, so clear out the top 32b bits of the
1724 	 * register because the ALU works 64bits.
1725 	 */
1726 	*cs++ = MI_LOAD_REGISTER_IMM(1);
1727 	*cs++ = i915_mmio_reg_offset(CS_GPR(START_TS)) + 4;
1728 	*cs++ = 0;
1729 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1730 	*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
1731 	*cs++ = i915_mmio_reg_offset(CS_GPR(START_TS));
1732 
1733 	/*
1734 	 * This is the location we're going to jump back into until the
1735 	 * required amount of time has passed.
1736 	 */
1737 	jump = cs;
1738 
1739 	/*
1740 	 * Take another snapshot of the timestamp register. Take care to clear
1741 	 * up the top 32bits of CS_GPR(1) as we're using it for other
1742 	 * operations below.
1743 	 */
1744 	*cs++ = MI_LOAD_REGISTER_IMM(1);
1745 	*cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS)) + 4;
1746 	*cs++ = 0;
1747 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1748 	*cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
1749 	*cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS));
1750 
1751 	/*
1752 	 * Do a diff between the 2 timestamps and store the result back into
1753 	 * CS_GPR(1).
1754 	 */
1755 	*cs++ = MI_MATH(5);
1756 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(NOW_TS));
1757 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(START_TS));
1758 	*cs++ = MI_MATH_SUB;
1759 	*cs++ = MI_MATH_STORE(MI_MATH_REG(DELTA_TS), MI_MATH_REG_ACCU);
1760 	*cs++ = MI_MATH_STORE(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
1761 
1762 	/*
1763 	 * Transfer the carry flag (set to 1 if ts1 < ts0, meaning the
1764 	 * timestamp have rolled over the 32bits) into the predicate register
1765 	 * to be used for the predicated jump.
1766 	 */
1767 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1768 	*cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
1769 	*cs++ = i915_mmio_reg_offset(MI_PREDICATE_RESULT_1);
1770 
1771 	/* Restart from the beginning if we had timestamps roll over. */
1772 	*cs++ = (INTEL_GEN(i915) < 8 ?
1773 		 MI_BATCH_BUFFER_START :
1774 		 MI_BATCH_BUFFER_START_GEN8) |
1775 		MI_BATCH_PREDICATE;
1776 	*cs++ = i915_ggtt_offset(vma) + (ts0 - batch) * 4;
1777 	*cs++ = 0;
1778 
1779 	/*
1780 	 * Now add the diff between to previous timestamps and add it to :
1781 	 *      (((1 * << 64) - 1) - delay_ns)
1782 	 *
1783 	 * When the Carry Flag contains 1 this means the elapsed time is
1784 	 * longer than the expected delay, and we can exit the wait loop.
1785 	 */
1786 	*cs++ = MI_LOAD_REGISTER_IMM(2);
1787 	*cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET));
1788 	*cs++ = lower_32_bits(delay_ticks);
1789 	*cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET)) + 4;
1790 	*cs++ = upper_32_bits(delay_ticks);
1791 
1792 	*cs++ = MI_MATH(4);
1793 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(DELTA_TS));
1794 	*cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(DELTA_TARGET));
1795 	*cs++ = MI_MATH_ADD;
1796 	*cs++ = MI_MATH_STOREINV(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
1797 
1798 	*cs++ = MI_ARB_CHECK;
1799 
1800 	/*
1801 	 * Transfer the result into the predicate register to be used for the
1802 	 * predicated jump.
1803 	 */
1804 	*cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1805 	*cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
1806 	*cs++ = i915_mmio_reg_offset(MI_PREDICATE_RESULT_1);
1807 
1808 	/* Predicate the jump.  */
1809 	*cs++ = (INTEL_GEN(i915) < 8 ?
1810 		 MI_BATCH_BUFFER_START :
1811 		 MI_BATCH_BUFFER_START_GEN8) |
1812 		MI_BATCH_PREDICATE;
1813 	*cs++ = i915_ggtt_offset(vma) + (jump - batch) * 4;
1814 	*cs++ = 0;
1815 
1816 	/* Restore registers. */
1817 	for (i = 0; i < N_CS_GPR; i++)
1818 		cs = save_restore_register(
1819 			stream, cs, false /* restore */, CS_GPR(i),
1820 			INTEL_GT_SCRATCH_FIELD_PERF_CS_GPR + 8 * i, 2);
1821 	cs = save_restore_register(
1822 		stream, cs, false /* restore */, MI_PREDICATE_RESULT_1,
1823 		INTEL_GT_SCRATCH_FIELD_PERF_PREDICATE_RESULT_1, 1);
1824 
1825 	/* And return to the ring. */
1826 	*cs++ = MI_BATCH_BUFFER_END;
1827 
1828 	GEM_BUG_ON(cs - batch > PAGE_SIZE / sizeof(*batch));
1829 
1830 	i915_gem_object_flush_map(bo);
1831 	i915_gem_object_unpin_map(bo);
1832 
1833 	stream->noa_wait = vma;
1834 	return 0;
1835 
1836 err_unpin:
1837 	i915_vma_unpin_and_release(&vma, 0);
1838 err_unref:
1839 	i915_gem_object_put(bo);
1840 	return ret;
1841 }
1842 
1843 static u32 *write_cs_mi_lri(u32 *cs,
1844 			    const struct i915_oa_reg *reg_data,
1845 			    u32 n_regs)
1846 {
1847 	u32 i;
1848 
1849 	for (i = 0; i < n_regs; i++) {
1850 		if ((i % MI_LOAD_REGISTER_IMM_MAX_REGS) == 0) {
1851 			u32 n_lri = min_t(u32,
1852 					  n_regs - i,
1853 					  MI_LOAD_REGISTER_IMM_MAX_REGS);
1854 
1855 			*cs++ = MI_LOAD_REGISTER_IMM(n_lri);
1856 		}
1857 		*cs++ = i915_mmio_reg_offset(reg_data[i].addr);
1858 		*cs++ = reg_data[i].value;
1859 	}
1860 
1861 	return cs;
1862 }
1863 
1864 static int num_lri_dwords(int num_regs)
1865 {
1866 	int count = 0;
1867 
1868 	if (num_regs > 0) {
1869 		count += DIV_ROUND_UP(num_regs, MI_LOAD_REGISTER_IMM_MAX_REGS);
1870 		count += num_regs * 2;
1871 	}
1872 
1873 	return count;
1874 }
1875 
1876 static struct i915_oa_config_bo *
1877 alloc_oa_config_buffer(struct i915_perf_stream *stream,
1878 		       struct i915_oa_config *oa_config)
1879 {
1880 	struct drm_i915_gem_object *obj;
1881 	struct i915_oa_config_bo *oa_bo;
1882 	size_t config_length = 0;
1883 	u32 *cs;
1884 	int err;
1885 
1886 	oa_bo = kzalloc(sizeof(*oa_bo), GFP_KERNEL);
1887 	if (!oa_bo)
1888 		return ERR_PTR(-ENOMEM);
1889 
1890 	config_length += num_lri_dwords(oa_config->mux_regs_len);
1891 	config_length += num_lri_dwords(oa_config->b_counter_regs_len);
1892 	config_length += num_lri_dwords(oa_config->flex_regs_len);
1893 	config_length += 3; /* MI_BATCH_BUFFER_START */
1894 	config_length = ALIGN(sizeof(u32) * config_length, I915_GTT_PAGE_SIZE);
1895 
1896 	obj = i915_gem_object_create_shmem(stream->perf->i915, config_length);
1897 	if (IS_ERR(obj)) {
1898 		err = PTR_ERR(obj);
1899 		goto err_free;
1900 	}
1901 
1902 	cs = i915_gem_object_pin_map(obj, I915_MAP_WB);
1903 	if (IS_ERR(cs)) {
1904 		err = PTR_ERR(cs);
1905 		goto err_oa_bo;
1906 	}
1907 
1908 	cs = write_cs_mi_lri(cs,
1909 			     oa_config->mux_regs,
1910 			     oa_config->mux_regs_len);
1911 	cs = write_cs_mi_lri(cs,
1912 			     oa_config->b_counter_regs,
1913 			     oa_config->b_counter_regs_len);
1914 	cs = write_cs_mi_lri(cs,
1915 			     oa_config->flex_regs,
1916 			     oa_config->flex_regs_len);
1917 
1918 	/* Jump into the active wait. */
1919 	*cs++ = (INTEL_GEN(stream->perf->i915) < 8 ?
1920 		 MI_BATCH_BUFFER_START :
1921 		 MI_BATCH_BUFFER_START_GEN8);
1922 	*cs++ = i915_ggtt_offset(stream->noa_wait);
1923 	*cs++ = 0;
1924 
1925 	i915_gem_object_flush_map(obj);
1926 	i915_gem_object_unpin_map(obj);
1927 
1928 	oa_bo->vma = i915_vma_instance(obj,
1929 				       &stream->engine->gt->ggtt->vm,
1930 				       NULL);
1931 	if (IS_ERR(oa_bo->vma)) {
1932 		err = PTR_ERR(oa_bo->vma);
1933 		goto err_oa_bo;
1934 	}
1935 
1936 	oa_bo->oa_config = i915_oa_config_get(oa_config);
1937 	llist_add(&oa_bo->node, &stream->oa_config_bos);
1938 
1939 	return oa_bo;
1940 
1941 err_oa_bo:
1942 	i915_gem_object_put(obj);
1943 err_free:
1944 	kfree(oa_bo);
1945 	return ERR_PTR(err);
1946 }
1947 
1948 static struct i915_vma *
1949 get_oa_vma(struct i915_perf_stream *stream, struct i915_oa_config *oa_config)
1950 {
1951 	struct i915_oa_config_bo *oa_bo;
1952 
1953 	/*
1954 	 * Look for the buffer in the already allocated BOs attached
1955 	 * to the stream.
1956 	 */
1957 	llist_for_each_entry(oa_bo, stream->oa_config_bos.first, node) {
1958 		if (oa_bo->oa_config == oa_config &&
1959 		    memcmp(oa_bo->oa_config->uuid,
1960 			   oa_config->uuid,
1961 			   sizeof(oa_config->uuid)) == 0)
1962 			goto out;
1963 	}
1964 
1965 	oa_bo = alloc_oa_config_buffer(stream, oa_config);
1966 	if (IS_ERR(oa_bo))
1967 		return ERR_CAST(oa_bo);
1968 
1969 out:
1970 	return i915_vma_get(oa_bo->vma);
1971 }
1972 
1973 static int emit_oa_config(struct i915_perf_stream *stream,
1974 			  struct i915_oa_config *oa_config,
1975 			  struct intel_context *ce)
1976 {
1977 	struct i915_request *rq;
1978 	struct i915_vma *vma;
1979 	int err;
1980 
1981 	vma = get_oa_vma(stream, oa_config);
1982 	if (IS_ERR(vma))
1983 		return PTR_ERR(vma);
1984 
1985 	err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
1986 	if (err)
1987 		goto err_vma_put;
1988 
1989 	intel_engine_pm_get(ce->engine);
1990 	rq = i915_request_create(ce);
1991 	intel_engine_pm_put(ce->engine);
1992 	if (IS_ERR(rq)) {
1993 		err = PTR_ERR(rq);
1994 		goto err_vma_unpin;
1995 	}
1996 
1997 	i915_vma_lock(vma);
1998 	err = i915_request_await_object(rq, vma->obj, 0);
1999 	if (!err)
2000 		err = i915_vma_move_to_active(vma, rq, 0);
2001 	i915_vma_unlock(vma);
2002 	if (err)
2003 		goto err_add_request;
2004 
2005 	err = rq->engine->emit_bb_start(rq,
2006 					vma->node.start, 0,
2007 					I915_DISPATCH_SECURE);
2008 err_add_request:
2009 	i915_request_add(rq);
2010 err_vma_unpin:
2011 	i915_vma_unpin(vma);
2012 err_vma_put:
2013 	i915_vma_put(vma);
2014 	return err;
2015 }
2016 
2017 static struct intel_context *oa_context(struct i915_perf_stream *stream)
2018 {
2019 	return stream->pinned_ctx ?: stream->engine->kernel_context;
2020 }
2021 
2022 static int hsw_enable_metric_set(struct i915_perf_stream *stream)
2023 {
2024 	struct intel_uncore *uncore = stream->uncore;
2025 
2026 	/*
2027 	 * PRM:
2028 	 *
2029 	 * OA unit is using “crclk” for its functionality. When trunk
2030 	 * level clock gating takes place, OA clock would be gated,
2031 	 * unable to count the events from non-render clock domain.
2032 	 * Render clock gating must be disabled when OA is enabled to
2033 	 * count the events from non-render domain. Unit level clock
2034 	 * gating for RCS should also be disabled.
2035 	 */
2036 	intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
2037 			 GEN7_DOP_CLOCK_GATE_ENABLE, 0);
2038 	intel_uncore_rmw(uncore, GEN6_UCGCTL1,
2039 			 0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
2040 
2041 	return emit_oa_config(stream, stream->oa_config, oa_context(stream));
2042 }
2043 
2044 static void hsw_disable_metric_set(struct i915_perf_stream *stream)
2045 {
2046 	struct intel_uncore *uncore = stream->uncore;
2047 
2048 	intel_uncore_rmw(uncore, GEN6_UCGCTL1,
2049 			 GEN6_CSUNIT_CLOCK_GATE_DISABLE, 0);
2050 	intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
2051 			 0, GEN7_DOP_CLOCK_GATE_ENABLE);
2052 
2053 	intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2054 }
2055 
2056 static u32 oa_config_flex_reg(const struct i915_oa_config *oa_config,
2057 			      i915_reg_t reg)
2058 {
2059 	u32 mmio = i915_mmio_reg_offset(reg);
2060 	int i;
2061 
2062 	/*
2063 	 * This arbitrary default will select the 'EU FPU0 Pipeline
2064 	 * Active' event. In the future it's anticipated that there
2065 	 * will be an explicit 'No Event' we can select, but not yet...
2066 	 */
2067 	if (!oa_config)
2068 		return 0;
2069 
2070 	for (i = 0; i < oa_config->flex_regs_len; i++) {
2071 		if (i915_mmio_reg_offset(oa_config->flex_regs[i].addr) == mmio)
2072 			return oa_config->flex_regs[i].value;
2073 	}
2074 
2075 	return 0;
2076 }
2077 /*
2078  * NB: It must always remain pointer safe to run this even if the OA unit
2079  * has been disabled.
2080  *
2081  * It's fine to put out-of-date values into these per-context registers
2082  * in the case that the OA unit has been disabled.
2083  */
2084 static void
2085 gen8_update_reg_state_unlocked(const struct intel_context *ce,
2086 			       const struct i915_perf_stream *stream)
2087 {
2088 	u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
2089 	u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2090 	/* The MMIO offsets for Flex EU registers aren't contiguous */
2091 	i915_reg_t flex_regs[] = {
2092 		EU_PERF_CNTL0,
2093 		EU_PERF_CNTL1,
2094 		EU_PERF_CNTL2,
2095 		EU_PERF_CNTL3,
2096 		EU_PERF_CNTL4,
2097 		EU_PERF_CNTL5,
2098 		EU_PERF_CNTL6,
2099 	};
2100 	u32 *reg_state = ce->lrc_reg_state;
2101 	int i;
2102 
2103 	reg_state[ctx_oactxctrl + 1] =
2104 		(stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2105 		(stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2106 		GEN8_OA_COUNTER_RESUME;
2107 
2108 	for (i = 0; i < ARRAY_SIZE(flex_regs); i++)
2109 		reg_state[ctx_flexeu0 + i * 2 + 1] =
2110 			oa_config_flex_reg(stream->oa_config, flex_regs[i]);
2111 
2112 	reg_state[CTX_R_PWR_CLK_STATE] =
2113 		intel_sseu_make_rpcs(ce->engine->i915, &ce->sseu);
2114 }
2115 
2116 struct flex {
2117 	i915_reg_t reg;
2118 	u32 offset;
2119 	u32 value;
2120 };
2121 
2122 static int
2123 gen8_store_flex(struct i915_request *rq,
2124 		struct intel_context *ce,
2125 		const struct flex *flex, unsigned int count)
2126 {
2127 	u32 offset;
2128 	u32 *cs;
2129 
2130 	cs = intel_ring_begin(rq, 4 * count);
2131 	if (IS_ERR(cs))
2132 		return PTR_ERR(cs);
2133 
2134 	offset = i915_ggtt_offset(ce->state) + LRC_STATE_PN * PAGE_SIZE;
2135 	do {
2136 		*cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
2137 		*cs++ = offset + flex->offset * sizeof(u32);
2138 		*cs++ = 0;
2139 		*cs++ = flex->value;
2140 	} while (flex++, --count);
2141 
2142 	intel_ring_advance(rq, cs);
2143 
2144 	return 0;
2145 }
2146 
2147 static int
2148 gen8_load_flex(struct i915_request *rq,
2149 	       struct intel_context *ce,
2150 	       const struct flex *flex, unsigned int count)
2151 {
2152 	u32 *cs;
2153 
2154 	GEM_BUG_ON(!count || count > 63);
2155 
2156 	cs = intel_ring_begin(rq, 2 * count + 2);
2157 	if (IS_ERR(cs))
2158 		return PTR_ERR(cs);
2159 
2160 	*cs++ = MI_LOAD_REGISTER_IMM(count);
2161 	do {
2162 		*cs++ = i915_mmio_reg_offset(flex->reg);
2163 		*cs++ = flex->value;
2164 	} while (flex++, --count);
2165 	*cs++ = MI_NOOP;
2166 
2167 	intel_ring_advance(rq, cs);
2168 
2169 	return 0;
2170 }
2171 
2172 static int gen8_modify_context(struct intel_context *ce,
2173 			       const struct flex *flex, unsigned int count)
2174 {
2175 	struct i915_request *rq;
2176 	int err;
2177 
2178 	rq = intel_engine_create_kernel_request(ce->engine);
2179 	if (IS_ERR(rq))
2180 		return PTR_ERR(rq);
2181 
2182 	/* Serialise with the remote context */
2183 	err = intel_context_prepare_remote_request(ce, rq);
2184 	if (err == 0)
2185 		err = gen8_store_flex(rq, ce, flex, count);
2186 
2187 	i915_request_add(rq);
2188 	return err;
2189 }
2190 
2191 static int gen8_modify_self(struct intel_context *ce,
2192 			    const struct flex *flex, unsigned int count)
2193 {
2194 	struct i915_request *rq;
2195 	int err;
2196 
2197 	rq = i915_request_create(ce);
2198 	if (IS_ERR(rq))
2199 		return PTR_ERR(rq);
2200 
2201 	err = gen8_load_flex(rq, ce, flex, count);
2202 
2203 	i915_request_add(rq);
2204 	return err;
2205 }
2206 
2207 static int gen8_configure_context(struct i915_gem_context *ctx,
2208 				  struct flex *flex, unsigned int count)
2209 {
2210 	struct i915_gem_engines_iter it;
2211 	struct intel_context *ce;
2212 	int err = 0;
2213 
2214 	for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
2215 		GEM_BUG_ON(ce == ce->engine->kernel_context);
2216 
2217 		if (ce->engine->class != RENDER_CLASS)
2218 			continue;
2219 
2220 		/* Otherwise OA settings will be set upon first use */
2221 		if (!intel_context_pin_if_active(ce))
2222 			continue;
2223 
2224 		flex->value = intel_sseu_make_rpcs(ctx->i915, &ce->sseu);
2225 		err = gen8_modify_context(ce, flex, count);
2226 
2227 		intel_context_unpin(ce);
2228 		if (err)
2229 			break;
2230 	}
2231 	i915_gem_context_unlock_engines(ctx);
2232 
2233 	return err;
2234 }
2235 
2236 static int gen12_configure_oar_context(struct i915_perf_stream *stream, bool enable)
2237 {
2238 	int err;
2239 	struct intel_context *ce = stream->pinned_ctx;
2240 	u32 format = stream->oa_buffer.format;
2241 	struct flex regs_context[] = {
2242 		{
2243 			GEN8_OACTXCONTROL,
2244 			stream->perf->ctx_oactxctrl_offset + 1,
2245 			enable ? GEN8_OA_COUNTER_RESUME : 0,
2246 		},
2247 	};
2248 	/* Offsets in regs_lri are not used since this configuration is only
2249 	 * applied using LRI. Initialize the correct offsets for posterity.
2250 	 */
2251 #define GEN12_OAR_OACONTROL_OFFSET 0x5B0
2252 	struct flex regs_lri[] = {
2253 		{
2254 			GEN12_OAR_OACONTROL,
2255 			GEN12_OAR_OACONTROL_OFFSET + 1,
2256 			(format << GEN12_OAR_OACONTROL_COUNTER_FORMAT_SHIFT) |
2257 			(enable ? GEN12_OAR_OACONTROL_COUNTER_ENABLE : 0)
2258 		},
2259 		{
2260 			RING_CONTEXT_CONTROL(ce->engine->mmio_base),
2261 			CTX_CONTEXT_CONTROL,
2262 			_MASKED_FIELD(GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE,
2263 				      enable ?
2264 				      GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE :
2265 				      0)
2266 		},
2267 	};
2268 
2269 	/* Modify the context image of pinned context with regs_context*/
2270 	err = intel_context_lock_pinned(ce);
2271 	if (err)
2272 		return err;
2273 
2274 	err = gen8_modify_context(ce, regs_context, ARRAY_SIZE(regs_context));
2275 	intel_context_unlock_pinned(ce);
2276 	if (err)
2277 		return err;
2278 
2279 	/* Apply regs_lri using LRI with pinned context */
2280 	return gen8_modify_self(ce, regs_lri, ARRAY_SIZE(regs_lri));
2281 }
2282 
2283 /*
2284  * Manages updating the per-context aspects of the OA stream
2285  * configuration across all contexts.
2286  *
2287  * The awkward consideration here is that OACTXCONTROL controls the
2288  * exponent for periodic sampling which is primarily used for system
2289  * wide profiling where we'd like a consistent sampling period even in
2290  * the face of context switches.
2291  *
2292  * Our approach of updating the register state context (as opposed to
2293  * say using a workaround batch buffer) ensures that the hardware
2294  * won't automatically reload an out-of-date timer exponent even
2295  * transiently before a WA BB could be parsed.
2296  *
2297  * This function needs to:
2298  * - Ensure the currently running context's per-context OA state is
2299  *   updated
2300  * - Ensure that all existing contexts will have the correct per-context
2301  *   OA state if they are scheduled for use.
2302  * - Ensure any new contexts will be initialized with the correct
2303  *   per-context OA state.
2304  *
2305  * Note: it's only the RCS/Render context that has any OA state.
2306  * Note: the first flex register passed must always be R_PWR_CLK_STATE
2307  */
2308 static int oa_configure_all_contexts(struct i915_perf_stream *stream,
2309 				     struct flex *regs,
2310 				     size_t num_regs)
2311 {
2312 	struct drm_i915_private *i915 = stream->perf->i915;
2313 	struct intel_engine_cs *engine;
2314 	struct i915_gem_context *ctx, *cn;
2315 	int err;
2316 
2317 	lockdep_assert_held(&stream->perf->lock);
2318 
2319 	/*
2320 	 * The OA register config is setup through the context image. This image
2321 	 * might be written to by the GPU on context switch (in particular on
2322 	 * lite-restore). This means we can't safely update a context's image,
2323 	 * if this context is scheduled/submitted to run on the GPU.
2324 	 *
2325 	 * We could emit the OA register config through the batch buffer but
2326 	 * this might leave small interval of time where the OA unit is
2327 	 * configured at an invalid sampling period.
2328 	 *
2329 	 * Note that since we emit all requests from a single ring, there
2330 	 * is still an implicit global barrier here that may cause a high
2331 	 * priority context to wait for an otherwise independent low priority
2332 	 * context. Contexts idle at the time of reconfiguration are not
2333 	 * trapped behind the barrier.
2334 	 */
2335 	spin_lock(&i915->gem.contexts.lock);
2336 	list_for_each_entry_safe(ctx, cn, &i915->gem.contexts.list, link) {
2337 		if (!kref_get_unless_zero(&ctx->ref))
2338 			continue;
2339 
2340 		spin_unlock(&i915->gem.contexts.lock);
2341 
2342 		err = gen8_configure_context(ctx, regs, num_regs);
2343 		if (err) {
2344 			i915_gem_context_put(ctx);
2345 			return err;
2346 		}
2347 
2348 		spin_lock(&i915->gem.contexts.lock);
2349 		list_safe_reset_next(ctx, cn, link);
2350 		i915_gem_context_put(ctx);
2351 	}
2352 	spin_unlock(&i915->gem.contexts.lock);
2353 
2354 	/*
2355 	 * After updating all other contexts, we need to modify ourselves.
2356 	 * If we don't modify the kernel_context, we do not get events while
2357 	 * idle.
2358 	 */
2359 	for_each_uabi_engine(engine, i915) {
2360 		struct intel_context *ce = engine->kernel_context;
2361 
2362 		if (engine->class != RENDER_CLASS)
2363 			continue;
2364 
2365 		regs[0].value = intel_sseu_make_rpcs(i915, &ce->sseu);
2366 
2367 		err = gen8_modify_self(ce, regs, num_regs);
2368 		if (err)
2369 			return err;
2370 	}
2371 
2372 	return 0;
2373 }
2374 
2375 static int gen12_configure_all_contexts(struct i915_perf_stream *stream,
2376 					const struct i915_oa_config *oa_config)
2377 {
2378 	struct flex regs[] = {
2379 		{
2380 			GEN8_R_PWR_CLK_STATE,
2381 			CTX_R_PWR_CLK_STATE,
2382 		},
2383 	};
2384 
2385 	return oa_configure_all_contexts(stream, regs, ARRAY_SIZE(regs));
2386 }
2387 
2388 static int lrc_configure_all_contexts(struct i915_perf_stream *stream,
2389 				      const struct i915_oa_config *oa_config)
2390 {
2391 	/* The MMIO offsets for Flex EU registers aren't contiguous */
2392 	const u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2393 #define ctx_flexeuN(N) (ctx_flexeu0 + 2 * (N) + 1)
2394 	struct flex regs[] = {
2395 		{
2396 			GEN8_R_PWR_CLK_STATE,
2397 			CTX_R_PWR_CLK_STATE,
2398 		},
2399 		{
2400 			GEN8_OACTXCONTROL,
2401 			stream->perf->ctx_oactxctrl_offset + 1,
2402 		},
2403 		{ EU_PERF_CNTL0, ctx_flexeuN(0) },
2404 		{ EU_PERF_CNTL1, ctx_flexeuN(1) },
2405 		{ EU_PERF_CNTL2, ctx_flexeuN(2) },
2406 		{ EU_PERF_CNTL3, ctx_flexeuN(3) },
2407 		{ EU_PERF_CNTL4, ctx_flexeuN(4) },
2408 		{ EU_PERF_CNTL5, ctx_flexeuN(5) },
2409 		{ EU_PERF_CNTL6, ctx_flexeuN(6) },
2410 	};
2411 #undef ctx_flexeuN
2412 	int i;
2413 
2414 	regs[1].value =
2415 		(stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2416 		(stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2417 		GEN8_OA_COUNTER_RESUME;
2418 
2419 	for (i = 2; i < ARRAY_SIZE(regs); i++)
2420 		regs[i].value = oa_config_flex_reg(oa_config, regs[i].reg);
2421 
2422 	return oa_configure_all_contexts(stream, regs, ARRAY_SIZE(regs));
2423 }
2424 
2425 static int gen8_enable_metric_set(struct i915_perf_stream *stream)
2426 {
2427 	struct intel_uncore *uncore = stream->uncore;
2428 	struct i915_oa_config *oa_config = stream->oa_config;
2429 	int ret;
2430 
2431 	/*
2432 	 * We disable slice/unslice clock ratio change reports on SKL since
2433 	 * they are too noisy. The HW generates a lot of redundant reports
2434 	 * where the ratio hasn't really changed causing a lot of redundant
2435 	 * work to processes and increasing the chances we'll hit buffer
2436 	 * overruns.
2437 	 *
2438 	 * Although we don't currently use the 'disable overrun' OABUFFER
2439 	 * feature it's worth noting that clock ratio reports have to be
2440 	 * disabled before considering to use that feature since the HW doesn't
2441 	 * correctly block these reports.
2442 	 *
2443 	 * Currently none of the high-level metrics we have depend on knowing
2444 	 * this ratio to normalize.
2445 	 *
2446 	 * Note: This register is not power context saved and restored, but
2447 	 * that's OK considering that we disable RC6 while the OA unit is
2448 	 * enabled.
2449 	 *
2450 	 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
2451 	 * be read back from automatically triggered reports, as part of the
2452 	 * RPT_ID field.
2453 	 */
2454 	if (IS_GEN_RANGE(stream->perf->i915, 9, 11)) {
2455 		intel_uncore_write(uncore, GEN8_OA_DEBUG,
2456 				   _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2457 						      GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
2458 	}
2459 
2460 	/*
2461 	 * Update all contexts prior writing the mux configurations as we need
2462 	 * to make sure all slices/subslices are ON before writing to NOA
2463 	 * registers.
2464 	 */
2465 	ret = lrc_configure_all_contexts(stream, oa_config);
2466 	if (ret)
2467 		return ret;
2468 
2469 	return emit_oa_config(stream, oa_config, oa_context(stream));
2470 }
2471 
2472 static u32 oag_report_ctx_switches(const struct i915_perf_stream *stream)
2473 {
2474 	return _MASKED_FIELD(GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS,
2475 			     (stream->sample_flags & SAMPLE_OA_REPORT) ?
2476 			     0 : GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS);
2477 }
2478 
2479 static int gen12_enable_metric_set(struct i915_perf_stream *stream)
2480 {
2481 	struct intel_uncore *uncore = stream->uncore;
2482 	struct i915_oa_config *oa_config = stream->oa_config;
2483 	bool periodic = stream->periodic;
2484 	u32 period_exponent = stream->period_exponent;
2485 	int ret;
2486 
2487 	intel_uncore_write(uncore, GEN12_OAG_OA_DEBUG,
2488 			   /* Disable clk ratio reports, like previous Gens. */
2489 			   _MASKED_BIT_ENABLE(GEN12_OAG_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2490 					      GEN12_OAG_OA_DEBUG_INCLUDE_CLK_RATIO) |
2491 			   /*
2492 			    * If the user didn't require OA reports, instruct
2493 			    * the hardware not to emit ctx switch reports.
2494 			    */
2495 			   oag_report_ctx_switches(stream));
2496 
2497 	intel_uncore_write(uncore, GEN12_OAG_OAGLBCTXCTRL, periodic ?
2498 			   (GEN12_OAG_OAGLBCTXCTRL_COUNTER_RESUME |
2499 			    GEN12_OAG_OAGLBCTXCTRL_TIMER_ENABLE |
2500 			    (period_exponent << GEN12_OAG_OAGLBCTXCTRL_TIMER_PERIOD_SHIFT))
2501 			    : 0);
2502 
2503 	/*
2504 	 * Update all contexts prior writing the mux configurations as we need
2505 	 * to make sure all slices/subslices are ON before writing to NOA
2506 	 * registers.
2507 	 */
2508 	ret = gen12_configure_all_contexts(stream, oa_config);
2509 	if (ret)
2510 		return ret;
2511 
2512 	/*
2513 	 * For Gen12, performance counters are context
2514 	 * saved/restored. Only enable it for the context that
2515 	 * requested this.
2516 	 */
2517 	if (stream->ctx) {
2518 		ret = gen12_configure_oar_context(stream, true);
2519 		if (ret)
2520 			return ret;
2521 	}
2522 
2523 	return emit_oa_config(stream, oa_config, oa_context(stream));
2524 }
2525 
2526 static void gen8_disable_metric_set(struct i915_perf_stream *stream)
2527 {
2528 	struct intel_uncore *uncore = stream->uncore;
2529 
2530 	/* Reset all contexts' slices/subslices configurations. */
2531 	lrc_configure_all_contexts(stream, NULL);
2532 
2533 	intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2534 }
2535 
2536 static void gen10_disable_metric_set(struct i915_perf_stream *stream)
2537 {
2538 	struct intel_uncore *uncore = stream->uncore;
2539 
2540 	/* Reset all contexts' slices/subslices configurations. */
2541 	lrc_configure_all_contexts(stream, NULL);
2542 
2543 	/* Make sure we disable noa to save power. */
2544 	intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
2545 }
2546 
2547 static void gen12_disable_metric_set(struct i915_perf_stream *stream)
2548 {
2549 	struct intel_uncore *uncore = stream->uncore;
2550 
2551 	/* Reset all contexts' slices/subslices configurations. */
2552 	gen12_configure_all_contexts(stream, NULL);
2553 
2554 	/* disable the context save/restore or OAR counters */
2555 	if (stream->ctx)
2556 		gen12_configure_oar_context(stream, false);
2557 
2558 	/* Make sure we disable noa to save power. */
2559 	intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
2560 }
2561 
2562 static void gen7_oa_enable(struct i915_perf_stream *stream)
2563 {
2564 	struct intel_uncore *uncore = stream->uncore;
2565 	struct i915_gem_context *ctx = stream->ctx;
2566 	u32 ctx_id = stream->specific_ctx_id;
2567 	bool periodic = stream->periodic;
2568 	u32 period_exponent = stream->period_exponent;
2569 	u32 report_format = stream->oa_buffer.format;
2570 
2571 	/*
2572 	 * Reset buf pointers so we don't forward reports from before now.
2573 	 *
2574 	 * Think carefully if considering trying to avoid this, since it
2575 	 * also ensures status flags and the buffer itself are cleared
2576 	 * in error paths, and we have checks for invalid reports based
2577 	 * on the assumption that certain fields are written to zeroed
2578 	 * memory which this helps maintains.
2579 	 */
2580 	gen7_init_oa_buffer(stream);
2581 
2582 	intel_uncore_write(uncore, GEN7_OACONTROL,
2583 			   (ctx_id & GEN7_OACONTROL_CTX_MASK) |
2584 			   (period_exponent <<
2585 			    GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
2586 			   (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
2587 			   (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
2588 			   (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
2589 			   GEN7_OACONTROL_ENABLE);
2590 }
2591 
2592 static void gen8_oa_enable(struct i915_perf_stream *stream)
2593 {
2594 	struct intel_uncore *uncore = stream->uncore;
2595 	u32 report_format = stream->oa_buffer.format;
2596 
2597 	/*
2598 	 * Reset buf pointers so we don't forward reports from before now.
2599 	 *
2600 	 * Think carefully if considering trying to avoid this, since it
2601 	 * also ensures status flags and the buffer itself are cleared
2602 	 * in error paths, and we have checks for invalid reports based
2603 	 * on the assumption that certain fields are written to zeroed
2604 	 * memory which this helps maintains.
2605 	 */
2606 	gen8_init_oa_buffer(stream);
2607 
2608 	/*
2609 	 * Note: we don't rely on the hardware to perform single context
2610 	 * filtering and instead filter on the cpu based on the context-id
2611 	 * field of reports
2612 	 */
2613 	intel_uncore_write(uncore, GEN8_OACONTROL,
2614 			   (report_format << GEN8_OA_REPORT_FORMAT_SHIFT) |
2615 			   GEN8_OA_COUNTER_ENABLE);
2616 }
2617 
2618 static void gen12_oa_enable(struct i915_perf_stream *stream)
2619 {
2620 	struct intel_uncore *uncore = stream->uncore;
2621 	u32 report_format = stream->oa_buffer.format;
2622 
2623 	/*
2624 	 * If we don't want OA reports from the OA buffer, then we don't even
2625 	 * need to program the OAG unit.
2626 	 */
2627 	if (!(stream->sample_flags & SAMPLE_OA_REPORT))
2628 		return;
2629 
2630 	gen12_init_oa_buffer(stream);
2631 
2632 	intel_uncore_write(uncore, GEN12_OAG_OACONTROL,
2633 			   (report_format << GEN12_OAG_OACONTROL_OA_COUNTER_FORMAT_SHIFT) |
2634 			   GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE);
2635 }
2636 
2637 /**
2638  * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
2639  * @stream: An i915 perf stream opened for OA metrics
2640  *
2641  * [Re]enables hardware periodic sampling according to the period configured
2642  * when opening the stream. This also starts a hrtimer that will periodically
2643  * check for data in the circular OA buffer for notifying userspace (e.g.
2644  * during a read() or poll()).
2645  */
2646 static void i915_oa_stream_enable(struct i915_perf_stream *stream)
2647 {
2648 	stream->perf->ops.oa_enable(stream);
2649 
2650 	if (stream->periodic)
2651 		hrtimer_start(&stream->poll_check_timer,
2652 			      ns_to_ktime(POLL_PERIOD),
2653 			      HRTIMER_MODE_REL_PINNED);
2654 }
2655 
2656 static void gen7_oa_disable(struct i915_perf_stream *stream)
2657 {
2658 	struct intel_uncore *uncore = stream->uncore;
2659 
2660 	intel_uncore_write(uncore, GEN7_OACONTROL, 0);
2661 	if (intel_wait_for_register(uncore,
2662 				    GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
2663 				    50))
2664 		drm_err(&stream->perf->i915->drm,
2665 			"wait for OA to be disabled timed out\n");
2666 }
2667 
2668 static void gen8_oa_disable(struct i915_perf_stream *stream)
2669 {
2670 	struct intel_uncore *uncore = stream->uncore;
2671 
2672 	intel_uncore_write(uncore, GEN8_OACONTROL, 0);
2673 	if (intel_wait_for_register(uncore,
2674 				    GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
2675 				    50))
2676 		drm_err(&stream->perf->i915->drm,
2677 			"wait for OA to be disabled timed out\n");
2678 }
2679 
2680 static void gen12_oa_disable(struct i915_perf_stream *stream)
2681 {
2682 	struct intel_uncore *uncore = stream->uncore;
2683 
2684 	intel_uncore_write(uncore, GEN12_OAG_OACONTROL, 0);
2685 	if (intel_wait_for_register(uncore,
2686 				    GEN12_OAG_OACONTROL,
2687 				    GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE, 0,
2688 				    50))
2689 		drm_err(&stream->perf->i915->drm,
2690 			"wait for OA to be disabled timed out\n");
2691 }
2692 
2693 /**
2694  * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
2695  * @stream: An i915 perf stream opened for OA metrics
2696  *
2697  * Stops the OA unit from periodically writing counter reports into the
2698  * circular OA buffer. This also stops the hrtimer that periodically checks for
2699  * data in the circular OA buffer, for notifying userspace.
2700  */
2701 static void i915_oa_stream_disable(struct i915_perf_stream *stream)
2702 {
2703 	stream->perf->ops.oa_disable(stream);
2704 
2705 	if (stream->periodic)
2706 		hrtimer_cancel(&stream->poll_check_timer);
2707 }
2708 
2709 static const struct i915_perf_stream_ops i915_oa_stream_ops = {
2710 	.destroy = i915_oa_stream_destroy,
2711 	.enable = i915_oa_stream_enable,
2712 	.disable = i915_oa_stream_disable,
2713 	.wait_unlocked = i915_oa_wait_unlocked,
2714 	.poll_wait = i915_oa_poll_wait,
2715 	.read = i915_oa_read,
2716 };
2717 
2718 /**
2719  * i915_oa_stream_init - validate combined props for OA stream and init
2720  * @stream: An i915 perf stream
2721  * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
2722  * @props: The property state that configures stream (individually validated)
2723  *
2724  * While read_properties_unlocked() validates properties in isolation it
2725  * doesn't ensure that the combination necessarily makes sense.
2726  *
2727  * At this point it has been determined that userspace wants a stream of
2728  * OA metrics, but still we need to further validate the combined
2729  * properties are OK.
2730  *
2731  * If the configuration makes sense then we can allocate memory for
2732  * a circular OA buffer and apply the requested metric set configuration.
2733  *
2734  * Returns: zero on success or a negative error code.
2735  */
2736 static int i915_oa_stream_init(struct i915_perf_stream *stream,
2737 			       struct drm_i915_perf_open_param *param,
2738 			       struct perf_open_properties *props)
2739 {
2740 	struct drm_i915_private *i915 = stream->perf->i915;
2741 	struct i915_perf *perf = stream->perf;
2742 	int format_size;
2743 	int ret;
2744 
2745 	if (!props->engine) {
2746 		DRM_DEBUG("OA engine not specified\n");
2747 		return -EINVAL;
2748 	}
2749 
2750 	/*
2751 	 * If the sysfs metrics/ directory wasn't registered for some
2752 	 * reason then don't let userspace try their luck with config
2753 	 * IDs
2754 	 */
2755 	if (!perf->metrics_kobj) {
2756 		DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
2757 		return -EINVAL;
2758 	}
2759 
2760 	if (!(props->sample_flags & SAMPLE_OA_REPORT) &&
2761 	    (INTEL_GEN(perf->i915) < 12 || !stream->ctx)) {
2762 		DRM_DEBUG("Only OA report sampling supported\n");
2763 		return -EINVAL;
2764 	}
2765 
2766 	if (!perf->ops.enable_metric_set) {
2767 		DRM_DEBUG("OA unit not supported\n");
2768 		return -ENODEV;
2769 	}
2770 
2771 	/*
2772 	 * To avoid the complexity of having to accurately filter
2773 	 * counter reports and marshal to the appropriate client
2774 	 * we currently only allow exclusive access
2775 	 */
2776 	if (perf->exclusive_stream) {
2777 		DRM_DEBUG("OA unit already in use\n");
2778 		return -EBUSY;
2779 	}
2780 
2781 	if (!props->oa_format) {
2782 		DRM_DEBUG("OA report format not specified\n");
2783 		return -EINVAL;
2784 	}
2785 
2786 	stream->engine = props->engine;
2787 	stream->uncore = stream->engine->gt->uncore;
2788 
2789 	stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2790 
2791 	format_size = perf->oa_formats[props->oa_format].size;
2792 
2793 	stream->sample_flags = props->sample_flags;
2794 	stream->sample_size += format_size;
2795 
2796 	stream->oa_buffer.format_size = format_size;
2797 	if (drm_WARN_ON(&i915->drm, stream->oa_buffer.format_size == 0))
2798 		return -EINVAL;
2799 
2800 	stream->hold_preemption = props->hold_preemption;
2801 
2802 	stream->oa_buffer.format =
2803 		perf->oa_formats[props->oa_format].format;
2804 
2805 	stream->periodic = props->oa_periodic;
2806 	if (stream->periodic)
2807 		stream->period_exponent = props->oa_period_exponent;
2808 
2809 	if (stream->ctx) {
2810 		ret = oa_get_render_ctx_id(stream);
2811 		if (ret) {
2812 			DRM_DEBUG("Invalid context id to filter with\n");
2813 			return ret;
2814 		}
2815 	}
2816 
2817 	ret = alloc_noa_wait(stream);
2818 	if (ret) {
2819 		DRM_DEBUG("Unable to allocate NOA wait batch buffer\n");
2820 		goto err_noa_wait_alloc;
2821 	}
2822 
2823 	stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
2824 	if (!stream->oa_config) {
2825 		DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set);
2826 		ret = -EINVAL;
2827 		goto err_config;
2828 	}
2829 
2830 	/* PRM - observability performance counters:
2831 	 *
2832 	 *   OACONTROL, performance counter enable, note:
2833 	 *
2834 	 *   "When this bit is set, in order to have coherent counts,
2835 	 *   RC6 power state and trunk clock gating must be disabled.
2836 	 *   This can be achieved by programming MMIO registers as
2837 	 *   0xA094=0 and 0xA090[31]=1"
2838 	 *
2839 	 *   In our case we are expecting that taking pm + FORCEWAKE
2840 	 *   references will effectively disable RC6.
2841 	 */
2842 	intel_engine_pm_get(stream->engine);
2843 	intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
2844 
2845 	ret = alloc_oa_buffer(stream);
2846 	if (ret)
2847 		goto err_oa_buf_alloc;
2848 
2849 	stream->ops = &i915_oa_stream_ops;
2850 	perf->exclusive_stream = stream;
2851 
2852 	ret = perf->ops.enable_metric_set(stream);
2853 	if (ret) {
2854 		DRM_DEBUG("Unable to enable metric set\n");
2855 		goto err_enable;
2856 	}
2857 
2858 	DRM_DEBUG("opening stream oa config uuid=%s\n",
2859 		  stream->oa_config->uuid);
2860 
2861 	hrtimer_init(&stream->poll_check_timer,
2862 		     CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2863 	stream->poll_check_timer.function = oa_poll_check_timer_cb;
2864 	init_waitqueue_head(&stream->poll_wq);
2865 	spin_lock_init(&stream->oa_buffer.ptr_lock);
2866 
2867 	return 0;
2868 
2869 err_enable:
2870 	perf->exclusive_stream = NULL;
2871 	perf->ops.disable_metric_set(stream);
2872 
2873 	free_oa_buffer(stream);
2874 
2875 err_oa_buf_alloc:
2876 	free_oa_configs(stream);
2877 
2878 	intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
2879 	intel_engine_pm_put(stream->engine);
2880 
2881 err_config:
2882 	free_noa_wait(stream);
2883 
2884 err_noa_wait_alloc:
2885 	if (stream->ctx)
2886 		oa_put_render_ctx_id(stream);
2887 
2888 	return ret;
2889 }
2890 
2891 void i915_oa_init_reg_state(const struct intel_context *ce,
2892 			    const struct intel_engine_cs *engine)
2893 {
2894 	struct i915_perf_stream *stream;
2895 
2896 	/* perf.exclusive_stream serialised by lrc_configure_all_contexts() */
2897 
2898 	if (engine->class != RENDER_CLASS)
2899 		return;
2900 
2901 	stream = engine->i915->perf.exclusive_stream;
2902 	/*
2903 	 * For gen12, only CTX_R_PWR_CLK_STATE needs update, but the caller
2904 	 * is already doing that, so nothing to be done for gen12 here.
2905 	 */
2906 	if (stream && INTEL_GEN(stream->perf->i915) < 12)
2907 		gen8_update_reg_state_unlocked(ce, stream);
2908 }
2909 
2910 /**
2911  * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2912  * @stream: An i915 perf stream
2913  * @file: An i915 perf stream file
2914  * @buf: destination buffer given by userspace
2915  * @count: the number of bytes userspace wants to read
2916  * @ppos: (inout) file seek position (unused)
2917  *
2918  * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2919  * ensure that if we've successfully copied any data then reporting that takes
2920  * precedence over any internal error status, so the data isn't lost.
2921  *
2922  * For example ret will be -ENOSPC whenever there is more buffered data than
2923  * can be copied to userspace, but that's only interesting if we weren't able
2924  * to copy some data because it implies the userspace buffer is too small to
2925  * receive a single record (and we never split records).
2926  *
2927  * Another case with ret == -EFAULT is more of a grey area since it would seem
2928  * like bad form for userspace to ask us to overrun its buffer, but the user
2929  * knows best:
2930  *
2931  *   http://yarchive.net/comp/linux/partial_reads_writes.html
2932  *
2933  * Returns: The number of bytes copied or a negative error code on failure.
2934  */
2935 static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2936 				     struct file *file,
2937 				     char __user *buf,
2938 				     size_t count,
2939 				     loff_t *ppos)
2940 {
2941 	/* Note we keep the offset (aka bytes read) separate from any
2942 	 * error status so that the final check for whether we return
2943 	 * the bytes read with a higher precedence than any error (see
2944 	 * comment below) doesn't need to be handled/duplicated in
2945 	 * stream->ops->read() implementations.
2946 	 */
2947 	size_t offset = 0;
2948 	int ret = stream->ops->read(stream, buf, count, &offset);
2949 
2950 	return offset ?: (ret ?: -EAGAIN);
2951 }
2952 
2953 /**
2954  * i915_perf_read - handles read() FOP for i915 perf stream FDs
2955  * @file: An i915 perf stream file
2956  * @buf: destination buffer given by userspace
2957  * @count: the number of bytes userspace wants to read
2958  * @ppos: (inout) file seek position (unused)
2959  *
2960  * The entry point for handling a read() on a stream file descriptor from
2961  * userspace. Most of the work is left to the i915_perf_read_locked() and
2962  * &i915_perf_stream_ops->read but to save having stream implementations (of
2963  * which we might have multiple later) we handle blocking read here.
2964  *
2965  * We can also consistently treat trying to read from a disabled stream
2966  * as an IO error so implementations can assume the stream is enabled
2967  * while reading.
2968  *
2969  * Returns: The number of bytes copied or a negative error code on failure.
2970  */
2971 static ssize_t i915_perf_read(struct file *file,
2972 			      char __user *buf,
2973 			      size_t count,
2974 			      loff_t *ppos)
2975 {
2976 	struct i915_perf_stream *stream = file->private_data;
2977 	struct i915_perf *perf = stream->perf;
2978 	ssize_t ret;
2979 
2980 	/* To ensure it's handled consistently we simply treat all reads of a
2981 	 * disabled stream as an error. In particular it might otherwise lead
2982 	 * to a deadlock for blocking file descriptors...
2983 	 */
2984 	if (!stream->enabled)
2985 		return -EIO;
2986 
2987 	if (!(file->f_flags & O_NONBLOCK)) {
2988 		/* There's the small chance of false positives from
2989 		 * stream->ops->wait_unlocked.
2990 		 *
2991 		 * E.g. with single context filtering since we only wait until
2992 		 * oabuffer has >= 1 report we don't immediately know whether
2993 		 * any reports really belong to the current context
2994 		 */
2995 		do {
2996 			ret = stream->ops->wait_unlocked(stream);
2997 			if (ret)
2998 				return ret;
2999 
3000 			mutex_lock(&perf->lock);
3001 			ret = i915_perf_read_locked(stream, file,
3002 						    buf, count, ppos);
3003 			mutex_unlock(&perf->lock);
3004 		} while (ret == -EAGAIN);
3005 	} else {
3006 		mutex_lock(&perf->lock);
3007 		ret = i915_perf_read_locked(stream, file, buf, count, ppos);
3008 		mutex_unlock(&perf->lock);
3009 	}
3010 
3011 	/* We allow the poll checking to sometimes report false positive EPOLLIN
3012 	 * events where we might actually report EAGAIN on read() if there's
3013 	 * not really any data available. In this situation though we don't
3014 	 * want to enter a busy loop between poll() reporting a EPOLLIN event
3015 	 * and read() returning -EAGAIN. Clearing the oa.pollin state here
3016 	 * effectively ensures we back off until the next hrtimer callback
3017 	 * before reporting another EPOLLIN event.
3018 	 */
3019 	if (ret >= 0 || ret == -EAGAIN) {
3020 		/* Maybe make ->pollin per-stream state if we support multiple
3021 		 * concurrent streams in the future.
3022 		 */
3023 		stream->pollin = false;
3024 	}
3025 
3026 	return ret;
3027 }
3028 
3029 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
3030 {
3031 	struct i915_perf_stream *stream =
3032 		container_of(hrtimer, typeof(*stream), poll_check_timer);
3033 
3034 	if (oa_buffer_check_unlocked(stream)) {
3035 		stream->pollin = true;
3036 		wake_up(&stream->poll_wq);
3037 	}
3038 
3039 	hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
3040 
3041 	return HRTIMER_RESTART;
3042 }
3043 
3044 /**
3045  * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
3046  * @stream: An i915 perf stream
3047  * @file: An i915 perf stream file
3048  * @wait: poll() state table
3049  *
3050  * For handling userspace polling on an i915 perf stream, this calls through to
3051  * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
3052  * will be woken for new stream data.
3053  *
3054  * Note: The &perf->lock mutex has been taken to serialize
3055  * with any non-file-operation driver hooks.
3056  *
3057  * Returns: any poll events that are ready without sleeping
3058  */
3059 static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
3060 				      struct file *file,
3061 				      poll_table *wait)
3062 {
3063 	__poll_t events = 0;
3064 
3065 	stream->ops->poll_wait(stream, file, wait);
3066 
3067 	/* Note: we don't explicitly check whether there's something to read
3068 	 * here since this path may be very hot depending on what else
3069 	 * userspace is polling, or on the timeout in use. We rely solely on
3070 	 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
3071 	 * samples to read.
3072 	 */
3073 	if (stream->pollin)
3074 		events |= EPOLLIN;
3075 
3076 	return events;
3077 }
3078 
3079 /**
3080  * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
3081  * @file: An i915 perf stream file
3082  * @wait: poll() state table
3083  *
3084  * For handling userspace polling on an i915 perf stream, this ensures
3085  * poll_wait() gets called with a wait queue that will be woken for new stream
3086  * data.
3087  *
3088  * Note: Implementation deferred to i915_perf_poll_locked()
3089  *
3090  * Returns: any poll events that are ready without sleeping
3091  */
3092 static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
3093 {
3094 	struct i915_perf_stream *stream = file->private_data;
3095 	struct i915_perf *perf = stream->perf;
3096 	__poll_t ret;
3097 
3098 	mutex_lock(&perf->lock);
3099 	ret = i915_perf_poll_locked(stream, file, wait);
3100 	mutex_unlock(&perf->lock);
3101 
3102 	return ret;
3103 }
3104 
3105 /**
3106  * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
3107  * @stream: A disabled i915 perf stream
3108  *
3109  * [Re]enables the associated capture of data for this stream.
3110  *
3111  * If a stream was previously enabled then there's currently no intention
3112  * to provide userspace any guarantee about the preservation of previously
3113  * buffered data.
3114  */
3115 static void i915_perf_enable_locked(struct i915_perf_stream *stream)
3116 {
3117 	if (stream->enabled)
3118 		return;
3119 
3120 	/* Allow stream->ops->enable() to refer to this */
3121 	stream->enabled = true;
3122 
3123 	if (stream->ops->enable)
3124 		stream->ops->enable(stream);
3125 
3126 	if (stream->hold_preemption)
3127 		intel_context_set_nopreempt(stream->pinned_ctx);
3128 }
3129 
3130 /**
3131  * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
3132  * @stream: An enabled i915 perf stream
3133  *
3134  * Disables the associated capture of data for this stream.
3135  *
3136  * The intention is that disabling an re-enabling a stream will ideally be
3137  * cheaper than destroying and re-opening a stream with the same configuration,
3138  * though there are no formal guarantees about what state or buffered data
3139  * must be retained between disabling and re-enabling a stream.
3140  *
3141  * Note: while a stream is disabled it's considered an error for userspace
3142  * to attempt to read from the stream (-EIO).
3143  */
3144 static void i915_perf_disable_locked(struct i915_perf_stream *stream)
3145 {
3146 	if (!stream->enabled)
3147 		return;
3148 
3149 	/* Allow stream->ops->disable() to refer to this */
3150 	stream->enabled = false;
3151 
3152 	if (stream->hold_preemption)
3153 		intel_context_clear_nopreempt(stream->pinned_ctx);
3154 
3155 	if (stream->ops->disable)
3156 		stream->ops->disable(stream);
3157 }
3158 
3159 static long i915_perf_config_locked(struct i915_perf_stream *stream,
3160 				    unsigned long metrics_set)
3161 {
3162 	struct i915_oa_config *config;
3163 	long ret = stream->oa_config->id;
3164 
3165 	config = i915_perf_get_oa_config(stream->perf, metrics_set);
3166 	if (!config)
3167 		return -EINVAL;
3168 
3169 	if (config != stream->oa_config) {
3170 		int err;
3171 
3172 		/*
3173 		 * If OA is bound to a specific context, emit the
3174 		 * reconfiguration inline from that context. The update
3175 		 * will then be ordered with respect to submission on that
3176 		 * context.
3177 		 *
3178 		 * When set globally, we use a low priority kernel context,
3179 		 * so it will effectively take effect when idle.
3180 		 */
3181 		err = emit_oa_config(stream, config, oa_context(stream));
3182 		if (err == 0)
3183 			config = xchg(&stream->oa_config, config);
3184 		else
3185 			ret = err;
3186 	}
3187 
3188 	i915_oa_config_put(config);
3189 
3190 	return ret;
3191 }
3192 
3193 /**
3194  * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
3195  * @stream: An i915 perf stream
3196  * @cmd: the ioctl request
3197  * @arg: the ioctl data
3198  *
3199  * Note: The &perf->lock mutex has been taken to serialize
3200  * with any non-file-operation driver hooks.
3201  *
3202  * Returns: zero on success or a negative error code. Returns -EINVAL for
3203  * an unknown ioctl request.
3204  */
3205 static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
3206 				   unsigned int cmd,
3207 				   unsigned long arg)
3208 {
3209 	switch (cmd) {
3210 	case I915_PERF_IOCTL_ENABLE:
3211 		i915_perf_enable_locked(stream);
3212 		return 0;
3213 	case I915_PERF_IOCTL_DISABLE:
3214 		i915_perf_disable_locked(stream);
3215 		return 0;
3216 	case I915_PERF_IOCTL_CONFIG:
3217 		return i915_perf_config_locked(stream, arg);
3218 	}
3219 
3220 	return -EINVAL;
3221 }
3222 
3223 /**
3224  * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
3225  * @file: An i915 perf stream file
3226  * @cmd: the ioctl request
3227  * @arg: the ioctl data
3228  *
3229  * Implementation deferred to i915_perf_ioctl_locked().
3230  *
3231  * Returns: zero on success or a negative error code. Returns -EINVAL for
3232  * an unknown ioctl request.
3233  */
3234 static long i915_perf_ioctl(struct file *file,
3235 			    unsigned int cmd,
3236 			    unsigned long arg)
3237 {
3238 	struct i915_perf_stream *stream = file->private_data;
3239 	struct i915_perf *perf = stream->perf;
3240 	long ret;
3241 
3242 	mutex_lock(&perf->lock);
3243 	ret = i915_perf_ioctl_locked(stream, cmd, arg);
3244 	mutex_unlock(&perf->lock);
3245 
3246 	return ret;
3247 }
3248 
3249 /**
3250  * i915_perf_destroy_locked - destroy an i915 perf stream
3251  * @stream: An i915 perf stream
3252  *
3253  * Frees all resources associated with the given i915 perf @stream, disabling
3254  * any associated data capture in the process.
3255  *
3256  * Note: The &perf->lock mutex has been taken to serialize
3257  * with any non-file-operation driver hooks.
3258  */
3259 static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
3260 {
3261 	if (stream->enabled)
3262 		i915_perf_disable_locked(stream);
3263 
3264 	if (stream->ops->destroy)
3265 		stream->ops->destroy(stream);
3266 
3267 	if (stream->ctx)
3268 		i915_gem_context_put(stream->ctx);
3269 
3270 	kfree(stream);
3271 }
3272 
3273 /**
3274  * i915_perf_release - handles userspace close() of a stream file
3275  * @inode: anonymous inode associated with file
3276  * @file: An i915 perf stream file
3277  *
3278  * Cleans up any resources associated with an open i915 perf stream file.
3279  *
3280  * NB: close() can't really fail from the userspace point of view.
3281  *
3282  * Returns: zero on success or a negative error code.
3283  */
3284 static int i915_perf_release(struct inode *inode, struct file *file)
3285 {
3286 	struct i915_perf_stream *stream = file->private_data;
3287 	struct i915_perf *perf = stream->perf;
3288 
3289 	mutex_lock(&perf->lock);
3290 	i915_perf_destroy_locked(stream);
3291 	mutex_unlock(&perf->lock);
3292 
3293 	/* Release the reference the perf stream kept on the driver. */
3294 	drm_dev_put(&perf->i915->drm);
3295 
3296 	return 0;
3297 }
3298 
3299 
3300 static const struct file_operations fops = {
3301 	.owner		= THIS_MODULE,
3302 	.llseek		= no_llseek,
3303 	.release	= i915_perf_release,
3304 	.poll		= i915_perf_poll,
3305 	.read		= i915_perf_read,
3306 	.unlocked_ioctl	= i915_perf_ioctl,
3307 	/* Our ioctl have no arguments, so it's safe to use the same function
3308 	 * to handle 32bits compatibility.
3309 	 */
3310 	.compat_ioctl   = i915_perf_ioctl,
3311 };
3312 
3313 
3314 /**
3315  * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
3316  * @perf: i915 perf instance
3317  * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
3318  * @props: individually validated u64 property value pairs
3319  * @file: drm file
3320  *
3321  * See i915_perf_ioctl_open() for interface details.
3322  *
3323  * Implements further stream config validation and stream initialization on
3324  * behalf of i915_perf_open_ioctl() with the &perf->lock mutex
3325  * taken to serialize with any non-file-operation driver hooks.
3326  *
3327  * Note: at this point the @props have only been validated in isolation and
3328  * it's still necessary to validate that the combination of properties makes
3329  * sense.
3330  *
3331  * In the case where userspace is interested in OA unit metrics then further
3332  * config validation and stream initialization details will be handled by
3333  * i915_oa_stream_init(). The code here should only validate config state that
3334  * will be relevant to all stream types / backends.
3335  *
3336  * Returns: zero on success or a negative error code.
3337  */
3338 static int
3339 i915_perf_open_ioctl_locked(struct i915_perf *perf,
3340 			    struct drm_i915_perf_open_param *param,
3341 			    struct perf_open_properties *props,
3342 			    struct drm_file *file)
3343 {
3344 	struct i915_gem_context *specific_ctx = NULL;
3345 	struct i915_perf_stream *stream = NULL;
3346 	unsigned long f_flags = 0;
3347 	bool privileged_op = true;
3348 	int stream_fd;
3349 	int ret;
3350 
3351 	if (props->single_context) {
3352 		u32 ctx_handle = props->ctx_handle;
3353 		struct drm_i915_file_private *file_priv = file->driver_priv;
3354 
3355 		specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
3356 		if (!specific_ctx) {
3357 			DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
3358 				  ctx_handle);
3359 			ret = -ENOENT;
3360 			goto err;
3361 		}
3362 	}
3363 
3364 	/*
3365 	 * On Haswell the OA unit supports clock gating off for a specific
3366 	 * context and in this mode there's no visibility of metrics for the
3367 	 * rest of the system, which we consider acceptable for a
3368 	 * non-privileged client.
3369 	 *
3370 	 * For Gen8->11 the OA unit no longer supports clock gating off for a
3371 	 * specific context and the kernel can't securely stop the counters
3372 	 * from updating as system-wide / global values. Even though we can
3373 	 * filter reports based on the included context ID we can't block
3374 	 * clients from seeing the raw / global counter values via
3375 	 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
3376 	 * enable the OA unit by default.
3377 	 *
3378 	 * For Gen12+ we gain a new OAR unit that only monitors the RCS on a
3379 	 * per context basis. So we can relax requirements there if the user
3380 	 * doesn't request global stream access (i.e. query based sampling
3381 	 * using MI_RECORD_PERF_COUNT.
3382 	 */
3383 	if (IS_HASWELL(perf->i915) && specific_ctx)
3384 		privileged_op = false;
3385 	else if (IS_GEN(perf->i915, 12) && specific_ctx &&
3386 		 (props->sample_flags & SAMPLE_OA_REPORT) == 0)
3387 		privileged_op = false;
3388 
3389 	if (props->hold_preemption) {
3390 		if (!props->single_context) {
3391 			DRM_DEBUG("preemption disable with no context\n");
3392 			ret = -EINVAL;
3393 			goto err;
3394 		}
3395 		privileged_op = true;
3396 	}
3397 
3398 	/* Similar to perf's kernel.perf_paranoid_cpu sysctl option
3399 	 * we check a dev.i915.perf_stream_paranoid sysctl option
3400 	 * to determine if it's ok to access system wide OA counters
3401 	 * without CAP_SYS_ADMIN privileges.
3402 	 */
3403 	if (privileged_op &&
3404 	    i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3405 		DRM_DEBUG("Insufficient privileges to open i915 perf stream\n");
3406 		ret = -EACCES;
3407 		goto err_ctx;
3408 	}
3409 
3410 	stream = kzalloc(sizeof(*stream), GFP_KERNEL);
3411 	if (!stream) {
3412 		ret = -ENOMEM;
3413 		goto err_ctx;
3414 	}
3415 
3416 	stream->perf = perf;
3417 	stream->ctx = specific_ctx;
3418 
3419 	ret = i915_oa_stream_init(stream, param, props);
3420 	if (ret)
3421 		goto err_alloc;
3422 
3423 	/* we avoid simply assigning stream->sample_flags = props->sample_flags
3424 	 * to have _stream_init check the combination of sample flags more
3425 	 * thoroughly, but still this is the expected result at this point.
3426 	 */
3427 	if (WARN_ON(stream->sample_flags != props->sample_flags)) {
3428 		ret = -ENODEV;
3429 		goto err_flags;
3430 	}
3431 
3432 	if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
3433 		f_flags |= O_CLOEXEC;
3434 	if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
3435 		f_flags |= O_NONBLOCK;
3436 
3437 	stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
3438 	if (stream_fd < 0) {
3439 		ret = stream_fd;
3440 		goto err_flags;
3441 	}
3442 
3443 	if (!(param->flags & I915_PERF_FLAG_DISABLED))
3444 		i915_perf_enable_locked(stream);
3445 
3446 	/* Take a reference on the driver that will be kept with stream_fd
3447 	 * until its release.
3448 	 */
3449 	drm_dev_get(&perf->i915->drm);
3450 
3451 	return stream_fd;
3452 
3453 err_flags:
3454 	if (stream->ops->destroy)
3455 		stream->ops->destroy(stream);
3456 err_alloc:
3457 	kfree(stream);
3458 err_ctx:
3459 	if (specific_ctx)
3460 		i915_gem_context_put(specific_ctx);
3461 err:
3462 	return ret;
3463 }
3464 
3465 static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
3466 {
3467 	return div64_u64(1000000000ULL * (2ULL << exponent),
3468 			 1000ULL * RUNTIME_INFO(perf->i915)->cs_timestamp_frequency_khz);
3469 }
3470 
3471 /**
3472  * read_properties_unlocked - validate + copy userspace stream open properties
3473  * @perf: i915 perf instance
3474  * @uprops: The array of u64 key value pairs given by userspace
3475  * @n_props: The number of key value pairs expected in @uprops
3476  * @props: The stream configuration built up while validating properties
3477  *
3478  * Note this function only validates properties in isolation it doesn't
3479  * validate that the combination of properties makes sense or that all
3480  * properties necessary for a particular kind of stream have been set.
3481  *
3482  * Note that there currently aren't any ordering requirements for properties so
3483  * we shouldn't validate or assume anything about ordering here. This doesn't
3484  * rule out defining new properties with ordering requirements in the future.
3485  */
3486 static int read_properties_unlocked(struct i915_perf *perf,
3487 				    u64 __user *uprops,
3488 				    u32 n_props,
3489 				    struct perf_open_properties *props)
3490 {
3491 	u64 __user *uprop = uprops;
3492 	u32 i;
3493 
3494 	memset(props, 0, sizeof(struct perf_open_properties));
3495 
3496 	if (!n_props) {
3497 		DRM_DEBUG("No i915 perf properties given\n");
3498 		return -EINVAL;
3499 	}
3500 
3501 	/* At the moment we only support using i915-perf on the RCS. */
3502 	props->engine = intel_engine_lookup_user(perf->i915,
3503 						 I915_ENGINE_CLASS_RENDER,
3504 						 0);
3505 	if (!props->engine) {
3506 		DRM_DEBUG("No RENDER-capable engines\n");
3507 		return -EINVAL;
3508 	}
3509 
3510 	/* Considering that ID = 0 is reserved and assuming that we don't
3511 	 * (currently) expect any configurations to ever specify duplicate
3512 	 * values for a particular property ID then the last _PROP_MAX value is
3513 	 * one greater than the maximum number of properties we expect to get
3514 	 * from userspace.
3515 	 */
3516 	if (n_props >= DRM_I915_PERF_PROP_MAX) {
3517 		DRM_DEBUG("More i915 perf properties specified than exist\n");
3518 		return -EINVAL;
3519 	}
3520 
3521 	for (i = 0; i < n_props; i++) {
3522 		u64 oa_period, oa_freq_hz;
3523 		u64 id, value;
3524 		int ret;
3525 
3526 		ret = get_user(id, uprop);
3527 		if (ret)
3528 			return ret;
3529 
3530 		ret = get_user(value, uprop + 1);
3531 		if (ret)
3532 			return ret;
3533 
3534 		if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
3535 			DRM_DEBUG("Unknown i915 perf property ID\n");
3536 			return -EINVAL;
3537 		}
3538 
3539 		switch ((enum drm_i915_perf_property_id)id) {
3540 		case DRM_I915_PERF_PROP_CTX_HANDLE:
3541 			props->single_context = 1;
3542 			props->ctx_handle = value;
3543 			break;
3544 		case DRM_I915_PERF_PROP_SAMPLE_OA:
3545 			if (value)
3546 				props->sample_flags |= SAMPLE_OA_REPORT;
3547 			break;
3548 		case DRM_I915_PERF_PROP_OA_METRICS_SET:
3549 			if (value == 0) {
3550 				DRM_DEBUG("Unknown OA metric set ID\n");
3551 				return -EINVAL;
3552 			}
3553 			props->metrics_set = value;
3554 			break;
3555 		case DRM_I915_PERF_PROP_OA_FORMAT:
3556 			if (value == 0 || value >= I915_OA_FORMAT_MAX) {
3557 				DRM_DEBUG("Out-of-range OA report format %llu\n",
3558 					  value);
3559 				return -EINVAL;
3560 			}
3561 			if (!perf->oa_formats[value].size) {
3562 				DRM_DEBUG("Unsupported OA report format %llu\n",
3563 					  value);
3564 				return -EINVAL;
3565 			}
3566 			props->oa_format = value;
3567 			break;
3568 		case DRM_I915_PERF_PROP_OA_EXPONENT:
3569 			if (value > OA_EXPONENT_MAX) {
3570 				DRM_DEBUG("OA timer exponent too high (> %u)\n",
3571 					 OA_EXPONENT_MAX);
3572 				return -EINVAL;
3573 			}
3574 
3575 			/* Theoretically we can program the OA unit to sample
3576 			 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
3577 			 * for BXT. We don't allow such high sampling
3578 			 * frequencies by default unless root.
3579 			 */
3580 
3581 			BUILD_BUG_ON(sizeof(oa_period) != 8);
3582 			oa_period = oa_exponent_to_ns(perf, value);
3583 
3584 			/* This check is primarily to ensure that oa_period <=
3585 			 * UINT32_MAX (before passing to do_div which only
3586 			 * accepts a u32 denominator), but we can also skip
3587 			 * checking anything < 1Hz which implicitly can't be
3588 			 * limited via an integer oa_max_sample_rate.
3589 			 */
3590 			if (oa_period <= NSEC_PER_SEC) {
3591 				u64 tmp = NSEC_PER_SEC;
3592 				do_div(tmp, oa_period);
3593 				oa_freq_hz = tmp;
3594 			} else
3595 				oa_freq_hz = 0;
3596 
3597 			if (oa_freq_hz > i915_oa_max_sample_rate &&
3598 			    !capable(CAP_SYS_ADMIN)) {
3599 				DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
3600 					  i915_oa_max_sample_rate);
3601 				return -EACCES;
3602 			}
3603 
3604 			props->oa_periodic = true;
3605 			props->oa_period_exponent = value;
3606 			break;
3607 		case DRM_I915_PERF_PROP_HOLD_PREEMPTION:
3608 			props->hold_preemption = !!value;
3609 			break;
3610 		case DRM_I915_PERF_PROP_MAX:
3611 			MISSING_CASE(id);
3612 			return -EINVAL;
3613 		}
3614 
3615 		uprop += 2;
3616 	}
3617 
3618 	return 0;
3619 }
3620 
3621 /**
3622  * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
3623  * @dev: drm device
3624  * @data: ioctl data copied from userspace (unvalidated)
3625  * @file: drm file
3626  *
3627  * Validates the stream open parameters given by userspace including flags
3628  * and an array of u64 key, value pair properties.
3629  *
3630  * Very little is assumed up front about the nature of the stream being
3631  * opened (for instance we don't assume it's for periodic OA unit metrics). An
3632  * i915-perf stream is expected to be a suitable interface for other forms of
3633  * buffered data written by the GPU besides periodic OA metrics.
3634  *
3635  * Note we copy the properties from userspace outside of the i915 perf
3636  * mutex to avoid an awkward lockdep with mmap_sem.
3637  *
3638  * Most of the implementation details are handled by
3639  * i915_perf_open_ioctl_locked() after taking the &perf->lock
3640  * mutex for serializing with any non-file-operation driver hooks.
3641  *
3642  * Return: A newly opened i915 Perf stream file descriptor or negative
3643  * error code on failure.
3644  */
3645 int i915_perf_open_ioctl(struct drm_device *dev, void *data,
3646 			 struct drm_file *file)
3647 {
3648 	struct i915_perf *perf = &to_i915(dev)->perf;
3649 	struct drm_i915_perf_open_param *param = data;
3650 	struct perf_open_properties props;
3651 	u32 known_open_flags;
3652 	int ret;
3653 
3654 	if (!perf->i915) {
3655 		DRM_DEBUG("i915 perf interface not available for this system\n");
3656 		return -ENOTSUPP;
3657 	}
3658 
3659 	known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
3660 			   I915_PERF_FLAG_FD_NONBLOCK |
3661 			   I915_PERF_FLAG_DISABLED;
3662 	if (param->flags & ~known_open_flags) {
3663 		DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
3664 		return -EINVAL;
3665 	}
3666 
3667 	ret = read_properties_unlocked(perf,
3668 				       u64_to_user_ptr(param->properties_ptr),
3669 				       param->num_properties,
3670 				       &props);
3671 	if (ret)
3672 		return ret;
3673 
3674 	mutex_lock(&perf->lock);
3675 	ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
3676 	mutex_unlock(&perf->lock);
3677 
3678 	return ret;
3679 }
3680 
3681 /**
3682  * i915_perf_register - exposes i915-perf to userspace
3683  * @i915: i915 device instance
3684  *
3685  * In particular OA metric sets are advertised under a sysfs metrics/
3686  * directory allowing userspace to enumerate valid IDs that can be
3687  * used to open an i915-perf stream.
3688  */
3689 void i915_perf_register(struct drm_i915_private *i915)
3690 {
3691 	struct i915_perf *perf = &i915->perf;
3692 	int ret;
3693 
3694 	if (!perf->i915)
3695 		return;
3696 
3697 	/* To be sure we're synchronized with an attempted
3698 	 * i915_perf_open_ioctl(); considering that we register after
3699 	 * being exposed to userspace.
3700 	 */
3701 	mutex_lock(&perf->lock);
3702 
3703 	perf->metrics_kobj =
3704 		kobject_create_and_add("metrics",
3705 				       &i915->drm.primary->kdev->kobj);
3706 	if (!perf->metrics_kobj)
3707 		goto exit;
3708 
3709 	sysfs_attr_init(&perf->test_config.sysfs_metric_id.attr);
3710 
3711 	if (IS_TIGERLAKE(i915)) {
3712 		i915_perf_load_test_config_tgl(i915);
3713 	} else if (INTEL_GEN(i915) >= 11) {
3714 		i915_perf_load_test_config_icl(i915);
3715 	} else if (IS_CANNONLAKE(i915)) {
3716 		i915_perf_load_test_config_cnl(i915);
3717 	} else if (IS_COFFEELAKE(i915)) {
3718 		if (IS_CFL_GT2(i915))
3719 			i915_perf_load_test_config_cflgt2(i915);
3720 		if (IS_CFL_GT3(i915))
3721 			i915_perf_load_test_config_cflgt3(i915);
3722 	} else if (IS_GEMINILAKE(i915)) {
3723 		i915_perf_load_test_config_glk(i915);
3724 	} else if (IS_KABYLAKE(i915)) {
3725 		if (IS_KBL_GT2(i915))
3726 			i915_perf_load_test_config_kblgt2(i915);
3727 		else if (IS_KBL_GT3(i915))
3728 			i915_perf_load_test_config_kblgt3(i915);
3729 	} else if (IS_BROXTON(i915)) {
3730 		i915_perf_load_test_config_bxt(i915);
3731 	} else if (IS_SKYLAKE(i915)) {
3732 		if (IS_SKL_GT2(i915))
3733 			i915_perf_load_test_config_sklgt2(i915);
3734 		else if (IS_SKL_GT3(i915))
3735 			i915_perf_load_test_config_sklgt3(i915);
3736 		else if (IS_SKL_GT4(i915))
3737 			i915_perf_load_test_config_sklgt4(i915);
3738 	} else if (IS_CHERRYVIEW(i915)) {
3739 		i915_perf_load_test_config_chv(i915);
3740 	} else if (IS_BROADWELL(i915)) {
3741 		i915_perf_load_test_config_bdw(i915);
3742 	} else if (IS_HASWELL(i915)) {
3743 		i915_perf_load_test_config_hsw(i915);
3744 	}
3745 
3746 	if (perf->test_config.id == 0)
3747 		goto sysfs_error;
3748 
3749 	ret = sysfs_create_group(perf->metrics_kobj,
3750 				 &perf->test_config.sysfs_metric);
3751 	if (ret)
3752 		goto sysfs_error;
3753 
3754 	perf->test_config.perf = perf;
3755 	kref_init(&perf->test_config.ref);
3756 
3757 	goto exit;
3758 
3759 sysfs_error:
3760 	kobject_put(perf->metrics_kobj);
3761 	perf->metrics_kobj = NULL;
3762 
3763 exit:
3764 	mutex_unlock(&perf->lock);
3765 }
3766 
3767 /**
3768  * i915_perf_unregister - hide i915-perf from userspace
3769  * @i915: i915 device instance
3770  *
3771  * i915-perf state cleanup is split up into an 'unregister' and
3772  * 'deinit' phase where the interface is first hidden from
3773  * userspace by i915_perf_unregister() before cleaning up
3774  * remaining state in i915_perf_fini().
3775  */
3776 void i915_perf_unregister(struct drm_i915_private *i915)
3777 {
3778 	struct i915_perf *perf = &i915->perf;
3779 
3780 	if (!perf->metrics_kobj)
3781 		return;
3782 
3783 	sysfs_remove_group(perf->metrics_kobj,
3784 			   &perf->test_config.sysfs_metric);
3785 
3786 	kobject_put(perf->metrics_kobj);
3787 	perf->metrics_kobj = NULL;
3788 }
3789 
3790 static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
3791 {
3792 	static const i915_reg_t flex_eu_regs[] = {
3793 		EU_PERF_CNTL0,
3794 		EU_PERF_CNTL1,
3795 		EU_PERF_CNTL2,
3796 		EU_PERF_CNTL3,
3797 		EU_PERF_CNTL4,
3798 		EU_PERF_CNTL5,
3799 		EU_PERF_CNTL6,
3800 	};
3801 	int i;
3802 
3803 	for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
3804 		if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
3805 			return true;
3806 	}
3807 	return false;
3808 }
3809 
3810 #define ADDR_IN_RANGE(addr, start, end) \
3811 	((addr) >= (start) && \
3812 	 (addr) <= (end))
3813 
3814 #define REG_IN_RANGE(addr, start, end) \
3815 	((addr) >= i915_mmio_reg_offset(start) && \
3816 	 (addr) <= i915_mmio_reg_offset(end))
3817 
3818 #define REG_EQUAL(addr, mmio) \
3819 	((addr) == i915_mmio_reg_offset(mmio))
3820 
3821 static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
3822 {
3823 	return REG_IN_RANGE(addr, OASTARTTRIG1, OASTARTTRIG8) ||
3824 	       REG_IN_RANGE(addr, OAREPORTTRIG1, OAREPORTTRIG8) ||
3825 	       REG_IN_RANGE(addr, OACEC0_0, OACEC7_1);
3826 }
3827 
3828 static bool gen7_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3829 {
3830 	return REG_EQUAL(addr, HALF_SLICE_CHICKEN2) ||
3831 	       REG_IN_RANGE(addr, MICRO_BP0_0, NOA_WRITE) ||
3832 	       REG_IN_RANGE(addr, OA_PERFCNT1_LO, OA_PERFCNT2_HI) ||
3833 	       REG_IN_RANGE(addr, OA_PERFMATRIX_LO, OA_PERFMATRIX_HI);
3834 }
3835 
3836 static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3837 {
3838 	return gen7_is_valid_mux_addr(perf, addr) ||
3839 	       REG_EQUAL(addr, WAIT_FOR_RC6_EXIT) ||
3840 	       REG_IN_RANGE(addr, RPM_CONFIG0, NOA_CONFIG(8));
3841 }
3842 
3843 static bool gen10_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3844 {
3845 	return gen8_is_valid_mux_addr(perf, addr) ||
3846 	       REG_EQUAL(addr, GEN10_NOA_WRITE_HIGH) ||
3847 	       REG_IN_RANGE(addr, OA_PERFCNT3_LO, OA_PERFCNT4_HI);
3848 }
3849 
3850 static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3851 {
3852 	return gen7_is_valid_mux_addr(perf, addr) ||
3853 	       ADDR_IN_RANGE(addr, 0x25100, 0x2FF90) ||
3854 	       REG_IN_RANGE(addr, HSW_MBVID2_NOA0, HSW_MBVID2_NOA9) ||
3855 	       REG_EQUAL(addr, HSW_MBVID2_MISR0);
3856 }
3857 
3858 static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3859 {
3860 	return gen7_is_valid_mux_addr(perf, addr) ||
3861 	       ADDR_IN_RANGE(addr, 0x182300, 0x1823A4);
3862 }
3863 
3864 static bool gen12_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
3865 {
3866 	return REG_IN_RANGE(addr, GEN12_OAG_OASTARTTRIG1, GEN12_OAG_OASTARTTRIG8) ||
3867 	       REG_IN_RANGE(addr, GEN12_OAG_OAREPORTTRIG1, GEN12_OAG_OAREPORTTRIG8) ||
3868 	       REG_IN_RANGE(addr, GEN12_OAG_CEC0_0, GEN12_OAG_CEC7_1) ||
3869 	       REG_IN_RANGE(addr, GEN12_OAG_SCEC0_0, GEN12_OAG_SCEC7_1) ||
3870 	       REG_EQUAL(addr, GEN12_OAA_DBG_REG) ||
3871 	       REG_EQUAL(addr, GEN12_OAG_OA_PESS) ||
3872 	       REG_EQUAL(addr, GEN12_OAG_SPCTR_CNF);
3873 }
3874 
3875 static bool gen12_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3876 {
3877 	return REG_EQUAL(addr, NOA_WRITE) ||
3878 	       REG_EQUAL(addr, GEN10_NOA_WRITE_HIGH) ||
3879 	       REG_EQUAL(addr, GDT_CHICKEN_BITS) ||
3880 	       REG_EQUAL(addr, WAIT_FOR_RC6_EXIT) ||
3881 	       REG_EQUAL(addr, RPM_CONFIG0) ||
3882 	       REG_EQUAL(addr, RPM_CONFIG1) ||
3883 	       REG_IN_RANGE(addr, NOA_CONFIG(0), NOA_CONFIG(8));
3884 }
3885 
3886 static u32 mask_reg_value(u32 reg, u32 val)
3887 {
3888 	/* HALF_SLICE_CHICKEN2 is programmed with a the
3889 	 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
3890 	 * programmed by userspace doesn't change this.
3891 	 */
3892 	if (REG_EQUAL(reg, HALF_SLICE_CHICKEN2))
3893 		val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
3894 
3895 	/* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
3896 	 * indicated by its name and a bunch of selection fields used by OA
3897 	 * configs.
3898 	 */
3899 	if (REG_EQUAL(reg, WAIT_FOR_RC6_EXIT))
3900 		val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
3901 
3902 	return val;
3903 }
3904 
3905 static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
3906 					 bool (*is_valid)(struct i915_perf *perf, u32 addr),
3907 					 u32 __user *regs,
3908 					 u32 n_regs)
3909 {
3910 	struct i915_oa_reg *oa_regs;
3911 	int err;
3912 	u32 i;
3913 
3914 	if (!n_regs)
3915 		return NULL;
3916 
3917 	if (!access_ok(regs, n_regs * sizeof(u32) * 2))
3918 		return ERR_PTR(-EFAULT);
3919 
3920 	/* No is_valid function means we're not allowing any register to be programmed. */
3921 	GEM_BUG_ON(!is_valid);
3922 	if (!is_valid)
3923 		return ERR_PTR(-EINVAL);
3924 
3925 	oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
3926 	if (!oa_regs)
3927 		return ERR_PTR(-ENOMEM);
3928 
3929 	for (i = 0; i < n_regs; i++) {
3930 		u32 addr, value;
3931 
3932 		err = get_user(addr, regs);
3933 		if (err)
3934 			goto addr_err;
3935 
3936 		if (!is_valid(perf, addr)) {
3937 			DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
3938 			err = -EINVAL;
3939 			goto addr_err;
3940 		}
3941 
3942 		err = get_user(value, regs + 1);
3943 		if (err)
3944 			goto addr_err;
3945 
3946 		oa_regs[i].addr = _MMIO(addr);
3947 		oa_regs[i].value = mask_reg_value(addr, value);
3948 
3949 		regs += 2;
3950 	}
3951 
3952 	return oa_regs;
3953 
3954 addr_err:
3955 	kfree(oa_regs);
3956 	return ERR_PTR(err);
3957 }
3958 
3959 static ssize_t show_dynamic_id(struct device *dev,
3960 			       struct device_attribute *attr,
3961 			       char *buf)
3962 {
3963 	struct i915_oa_config *oa_config =
3964 		container_of(attr, typeof(*oa_config), sysfs_metric_id);
3965 
3966 	return sprintf(buf, "%d\n", oa_config->id);
3967 }
3968 
3969 static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
3970 					 struct i915_oa_config *oa_config)
3971 {
3972 	sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
3973 	oa_config->sysfs_metric_id.attr.name = "id";
3974 	oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
3975 	oa_config->sysfs_metric_id.show = show_dynamic_id;
3976 	oa_config->sysfs_metric_id.store = NULL;
3977 
3978 	oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
3979 	oa_config->attrs[1] = NULL;
3980 
3981 	oa_config->sysfs_metric.name = oa_config->uuid;
3982 	oa_config->sysfs_metric.attrs = oa_config->attrs;
3983 
3984 	return sysfs_create_group(perf->metrics_kobj,
3985 				  &oa_config->sysfs_metric);
3986 }
3987 
3988 /**
3989  * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
3990  * @dev: drm device
3991  * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
3992  *        userspace (unvalidated)
3993  * @file: drm file
3994  *
3995  * Validates the submitted OA register to be saved into a new OA config that
3996  * can then be used for programming the OA unit and its NOA network.
3997  *
3998  * Returns: A new allocated config number to be used with the perf open ioctl
3999  * or a negative error code on failure.
4000  */
4001 int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
4002 			       struct drm_file *file)
4003 {
4004 	struct i915_perf *perf = &to_i915(dev)->perf;
4005 	struct drm_i915_perf_oa_config *args = data;
4006 	struct i915_oa_config *oa_config, *tmp;
4007 	struct i915_oa_reg *regs;
4008 	int err, id;
4009 
4010 	if (!perf->i915) {
4011 		DRM_DEBUG("i915 perf interface not available for this system\n");
4012 		return -ENOTSUPP;
4013 	}
4014 
4015 	if (!perf->metrics_kobj) {
4016 		DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
4017 		return -EINVAL;
4018 	}
4019 
4020 	if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
4021 		DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
4022 		return -EACCES;
4023 	}
4024 
4025 	if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
4026 	    (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
4027 	    (!args->flex_regs_ptr || !args->n_flex_regs)) {
4028 		DRM_DEBUG("No OA registers given\n");
4029 		return -EINVAL;
4030 	}
4031 
4032 	oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
4033 	if (!oa_config) {
4034 		DRM_DEBUG("Failed to allocate memory for the OA config\n");
4035 		return -ENOMEM;
4036 	}
4037 
4038 	oa_config->perf = perf;
4039 	kref_init(&oa_config->ref);
4040 
4041 	if (!uuid_is_valid(args->uuid)) {
4042 		DRM_DEBUG("Invalid uuid format for OA config\n");
4043 		err = -EINVAL;
4044 		goto reg_err;
4045 	}
4046 
4047 	/* Last character in oa_config->uuid will be 0 because oa_config is
4048 	 * kzalloc.
4049 	 */
4050 	memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
4051 
4052 	oa_config->mux_regs_len = args->n_mux_regs;
4053 	regs = alloc_oa_regs(perf,
4054 			     perf->ops.is_valid_mux_reg,
4055 			     u64_to_user_ptr(args->mux_regs_ptr),
4056 			     args->n_mux_regs);
4057 
4058 	if (IS_ERR(regs)) {
4059 		DRM_DEBUG("Failed to create OA config for mux_regs\n");
4060 		err = PTR_ERR(regs);
4061 		goto reg_err;
4062 	}
4063 	oa_config->mux_regs = regs;
4064 
4065 	oa_config->b_counter_regs_len = args->n_boolean_regs;
4066 	regs = alloc_oa_regs(perf,
4067 			     perf->ops.is_valid_b_counter_reg,
4068 			     u64_to_user_ptr(args->boolean_regs_ptr),
4069 			     args->n_boolean_regs);
4070 
4071 	if (IS_ERR(regs)) {
4072 		DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
4073 		err = PTR_ERR(regs);
4074 		goto reg_err;
4075 	}
4076 	oa_config->b_counter_regs = regs;
4077 
4078 	if (INTEL_GEN(perf->i915) < 8) {
4079 		if (args->n_flex_regs != 0) {
4080 			err = -EINVAL;
4081 			goto reg_err;
4082 		}
4083 	} else {
4084 		oa_config->flex_regs_len = args->n_flex_regs;
4085 		regs = alloc_oa_regs(perf,
4086 				     perf->ops.is_valid_flex_reg,
4087 				     u64_to_user_ptr(args->flex_regs_ptr),
4088 				     args->n_flex_regs);
4089 
4090 		if (IS_ERR(regs)) {
4091 			DRM_DEBUG("Failed to create OA config for flex_regs\n");
4092 			err = PTR_ERR(regs);
4093 			goto reg_err;
4094 		}
4095 		oa_config->flex_regs = regs;
4096 	}
4097 
4098 	err = mutex_lock_interruptible(&perf->metrics_lock);
4099 	if (err)
4100 		goto reg_err;
4101 
4102 	/* We shouldn't have too many configs, so this iteration shouldn't be
4103 	 * too costly.
4104 	 */
4105 	idr_for_each_entry(&perf->metrics_idr, tmp, id) {
4106 		if (!strcmp(tmp->uuid, oa_config->uuid)) {
4107 			DRM_DEBUG("OA config already exists with this uuid\n");
4108 			err = -EADDRINUSE;
4109 			goto sysfs_err;
4110 		}
4111 	}
4112 
4113 	err = create_dynamic_oa_sysfs_entry(perf, oa_config);
4114 	if (err) {
4115 		DRM_DEBUG("Failed to create sysfs entry for OA config\n");
4116 		goto sysfs_err;
4117 	}
4118 
4119 	/* Config id 0 is invalid, id 1 for kernel stored test config. */
4120 	oa_config->id = idr_alloc(&perf->metrics_idr,
4121 				  oa_config, 2,
4122 				  0, GFP_KERNEL);
4123 	if (oa_config->id < 0) {
4124 		DRM_DEBUG("Failed to create sysfs entry for OA config\n");
4125 		err = oa_config->id;
4126 		goto sysfs_err;
4127 	}
4128 
4129 	mutex_unlock(&perf->metrics_lock);
4130 
4131 	DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id);
4132 
4133 	return oa_config->id;
4134 
4135 sysfs_err:
4136 	mutex_unlock(&perf->metrics_lock);
4137 reg_err:
4138 	i915_oa_config_put(oa_config);
4139 	DRM_DEBUG("Failed to add new OA config\n");
4140 	return err;
4141 }
4142 
4143 /**
4144  * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
4145  * @dev: drm device
4146  * @data: ioctl data (pointer to u64 integer) copied from userspace
4147  * @file: drm file
4148  *
4149  * Configs can be removed while being used, the will stop appearing in sysfs
4150  * and their content will be freed when the stream using the config is closed.
4151  *
4152  * Returns: 0 on success or a negative error code on failure.
4153  */
4154 int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
4155 				  struct drm_file *file)
4156 {
4157 	struct i915_perf *perf = &to_i915(dev)->perf;
4158 	u64 *arg = data;
4159 	struct i915_oa_config *oa_config;
4160 	int ret;
4161 
4162 	if (!perf->i915) {
4163 		DRM_DEBUG("i915 perf interface not available for this system\n");
4164 		return -ENOTSUPP;
4165 	}
4166 
4167 	if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
4168 		DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
4169 		return -EACCES;
4170 	}
4171 
4172 	ret = mutex_lock_interruptible(&perf->metrics_lock);
4173 	if (ret)
4174 		return ret;
4175 
4176 	oa_config = idr_find(&perf->metrics_idr, *arg);
4177 	if (!oa_config) {
4178 		DRM_DEBUG("Failed to remove unknown OA config\n");
4179 		ret = -ENOENT;
4180 		goto err_unlock;
4181 	}
4182 
4183 	GEM_BUG_ON(*arg != oa_config->id);
4184 
4185 	sysfs_remove_group(perf->metrics_kobj, &oa_config->sysfs_metric);
4186 
4187 	idr_remove(&perf->metrics_idr, *arg);
4188 
4189 	mutex_unlock(&perf->metrics_lock);
4190 
4191 	DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
4192 
4193 	i915_oa_config_put(oa_config);
4194 
4195 	return 0;
4196 
4197 err_unlock:
4198 	mutex_unlock(&perf->metrics_lock);
4199 	return ret;
4200 }
4201 
4202 static struct ctl_table oa_table[] = {
4203 	{
4204 	 .procname = "perf_stream_paranoid",
4205 	 .data = &i915_perf_stream_paranoid,
4206 	 .maxlen = sizeof(i915_perf_stream_paranoid),
4207 	 .mode = 0644,
4208 	 .proc_handler = proc_dointvec_minmax,
4209 	 .extra1 = SYSCTL_ZERO,
4210 	 .extra2 = SYSCTL_ONE,
4211 	 },
4212 	{
4213 	 .procname = "oa_max_sample_rate",
4214 	 .data = &i915_oa_max_sample_rate,
4215 	 .maxlen = sizeof(i915_oa_max_sample_rate),
4216 	 .mode = 0644,
4217 	 .proc_handler = proc_dointvec_minmax,
4218 	 .extra1 = SYSCTL_ZERO,
4219 	 .extra2 = &oa_sample_rate_hard_limit,
4220 	 },
4221 	{}
4222 };
4223 
4224 static struct ctl_table i915_root[] = {
4225 	{
4226 	 .procname = "i915",
4227 	 .maxlen = 0,
4228 	 .mode = 0555,
4229 	 .child = oa_table,
4230 	 },
4231 	{}
4232 };
4233 
4234 static struct ctl_table dev_root[] = {
4235 	{
4236 	 .procname = "dev",
4237 	 .maxlen = 0,
4238 	 .mode = 0555,
4239 	 .child = i915_root,
4240 	 },
4241 	{}
4242 };
4243 
4244 /**
4245  * i915_perf_init - initialize i915-perf state on module bind
4246  * @i915: i915 device instance
4247  *
4248  * Initializes i915-perf state without exposing anything to userspace.
4249  *
4250  * Note: i915-perf initialization is split into an 'init' and 'register'
4251  * phase with the i915_perf_register() exposing state to userspace.
4252  */
4253 void i915_perf_init(struct drm_i915_private *i915)
4254 {
4255 	struct i915_perf *perf = &i915->perf;
4256 
4257 	/* XXX const struct i915_perf_ops! */
4258 
4259 	if (IS_HASWELL(i915)) {
4260 		perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
4261 		perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
4262 		perf->ops.is_valid_flex_reg = NULL;
4263 		perf->ops.enable_metric_set = hsw_enable_metric_set;
4264 		perf->ops.disable_metric_set = hsw_disable_metric_set;
4265 		perf->ops.oa_enable = gen7_oa_enable;
4266 		perf->ops.oa_disable = gen7_oa_disable;
4267 		perf->ops.read = gen7_oa_read;
4268 		perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
4269 
4270 		perf->oa_formats = hsw_oa_formats;
4271 	} else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
4272 		/* Note: that although we could theoretically also support the
4273 		 * legacy ringbuffer mode on BDW (and earlier iterations of
4274 		 * this driver, before upstreaming did this) it didn't seem
4275 		 * worth the complexity to maintain now that BDW+ enable
4276 		 * execlist mode by default.
4277 		 */
4278 		perf->ops.read = gen8_oa_read;
4279 
4280 		if (IS_GEN_RANGE(i915, 8, 9)) {
4281 			perf->oa_formats = gen8_plus_oa_formats;
4282 
4283 			perf->ops.is_valid_b_counter_reg =
4284 				gen7_is_valid_b_counter_addr;
4285 			perf->ops.is_valid_mux_reg =
4286 				gen8_is_valid_mux_addr;
4287 			perf->ops.is_valid_flex_reg =
4288 				gen8_is_valid_flex_addr;
4289 
4290 			if (IS_CHERRYVIEW(i915)) {
4291 				perf->ops.is_valid_mux_reg =
4292 					chv_is_valid_mux_addr;
4293 			}
4294 
4295 			perf->ops.oa_enable = gen8_oa_enable;
4296 			perf->ops.oa_disable = gen8_oa_disable;
4297 			perf->ops.enable_metric_set = gen8_enable_metric_set;
4298 			perf->ops.disable_metric_set = gen8_disable_metric_set;
4299 			perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
4300 
4301 			if (IS_GEN(i915, 8)) {
4302 				perf->ctx_oactxctrl_offset = 0x120;
4303 				perf->ctx_flexeu0_offset = 0x2ce;
4304 
4305 				perf->gen8_valid_ctx_bit = BIT(25);
4306 			} else {
4307 				perf->ctx_oactxctrl_offset = 0x128;
4308 				perf->ctx_flexeu0_offset = 0x3de;
4309 
4310 				perf->gen8_valid_ctx_bit = BIT(16);
4311 			}
4312 		} else if (IS_GEN_RANGE(i915, 10, 11)) {
4313 			perf->oa_formats = gen8_plus_oa_formats;
4314 
4315 			perf->ops.is_valid_b_counter_reg =
4316 				gen7_is_valid_b_counter_addr;
4317 			perf->ops.is_valid_mux_reg =
4318 				gen10_is_valid_mux_addr;
4319 			perf->ops.is_valid_flex_reg =
4320 				gen8_is_valid_flex_addr;
4321 
4322 			perf->ops.oa_enable = gen8_oa_enable;
4323 			perf->ops.oa_disable = gen8_oa_disable;
4324 			perf->ops.enable_metric_set = gen8_enable_metric_set;
4325 			perf->ops.disable_metric_set = gen10_disable_metric_set;
4326 			perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
4327 
4328 			if (IS_GEN(i915, 10)) {
4329 				perf->ctx_oactxctrl_offset = 0x128;
4330 				perf->ctx_flexeu0_offset = 0x3de;
4331 			} else {
4332 				perf->ctx_oactxctrl_offset = 0x124;
4333 				perf->ctx_flexeu0_offset = 0x78e;
4334 			}
4335 			perf->gen8_valid_ctx_bit = BIT(16);
4336 		} else if (IS_GEN(i915, 12)) {
4337 			perf->oa_formats = gen12_oa_formats;
4338 
4339 			perf->ops.is_valid_b_counter_reg =
4340 				gen12_is_valid_b_counter_addr;
4341 			perf->ops.is_valid_mux_reg =
4342 				gen12_is_valid_mux_addr;
4343 			perf->ops.is_valid_flex_reg =
4344 				gen8_is_valid_flex_addr;
4345 
4346 			perf->ops.oa_enable = gen12_oa_enable;
4347 			perf->ops.oa_disable = gen12_oa_disable;
4348 			perf->ops.enable_metric_set = gen12_enable_metric_set;
4349 			perf->ops.disable_metric_set = gen12_disable_metric_set;
4350 			perf->ops.oa_hw_tail_read = gen12_oa_hw_tail_read;
4351 
4352 			perf->ctx_flexeu0_offset = 0;
4353 			perf->ctx_oactxctrl_offset = 0x144;
4354 		}
4355 	}
4356 
4357 	if (perf->ops.enable_metric_set) {
4358 		mutex_init(&perf->lock);
4359 
4360 		oa_sample_rate_hard_limit = 1000 *
4361 			(RUNTIME_INFO(i915)->cs_timestamp_frequency_khz / 2);
4362 
4363 		mutex_init(&perf->metrics_lock);
4364 		idr_init(&perf->metrics_idr);
4365 
4366 		/* We set up some ratelimit state to potentially throttle any
4367 		 * _NOTES about spurious, invalid OA reports which we don't
4368 		 * forward to userspace.
4369 		 *
4370 		 * We print a _NOTE about any throttling when closing the
4371 		 * stream instead of waiting until driver _fini which no one
4372 		 * would ever see.
4373 		 *
4374 		 * Using the same limiting factors as printk_ratelimit()
4375 		 */
4376 		ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
4377 		/* Since we use a DRM_NOTE for spurious reports it would be
4378 		 * inconsistent to let __ratelimit() automatically print a
4379 		 * warning for throttling.
4380 		 */
4381 		ratelimit_set_flags(&perf->spurious_report_rs,
4382 				    RATELIMIT_MSG_ON_RELEASE);
4383 
4384 		atomic64_set(&perf->noa_programming_delay,
4385 			     500 * 1000 /* 500us */);
4386 
4387 		perf->i915 = i915;
4388 	}
4389 }
4390 
4391 static int destroy_config(int id, void *p, void *data)
4392 {
4393 	i915_oa_config_put(p);
4394 	return 0;
4395 }
4396 
4397 void i915_perf_sysctl_register(void)
4398 {
4399 	sysctl_header = register_sysctl_table(dev_root);
4400 }
4401 
4402 void i915_perf_sysctl_unregister(void)
4403 {
4404 	unregister_sysctl_table(sysctl_header);
4405 }
4406 
4407 /**
4408  * i915_perf_fini - Counter part to i915_perf_init()
4409  * @i915: i915 device instance
4410  */
4411 void i915_perf_fini(struct drm_i915_private *i915)
4412 {
4413 	struct i915_perf *perf = &i915->perf;
4414 
4415 	if (!perf->i915)
4416 		return;
4417 
4418 	idr_for_each(&perf->metrics_idr, destroy_config, perf);
4419 	idr_destroy(&perf->metrics_idr);
4420 
4421 	memset(&perf->ops, 0, sizeof(perf->ops));
4422 	perf->i915 = NULL;
4423 }
4424 
4425 /**
4426  * i915_perf_ioctl_version - Version of the i915-perf subsystem
4427  *
4428  * This version number is used by userspace to detect available features.
4429  */
4430 int i915_perf_ioctl_version(void)
4431 {
4432 	/*
4433 	 * 1: Initial version
4434 	 *   I915_PERF_IOCTL_ENABLE
4435 	 *   I915_PERF_IOCTL_DISABLE
4436 	 *
4437 	 * 2: Added runtime modification of OA config.
4438 	 *   I915_PERF_IOCTL_CONFIG
4439 	 *
4440 	 * 3: Add DRM_I915_PERF_PROP_HOLD_PREEMPTION parameter to hold
4441 	 *    preemption on a particular context so that performance data is
4442 	 *    accessible from a delta of MI_RPC reports without looking at the
4443 	 *    OA buffer.
4444 	 */
4445 	return 3;
4446 }
4447 
4448 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
4449 #include "selftests/i915_perf.c"
4450 #endif
4451