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