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