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