drm/i915/perf: leave GDT_CHICKEN_BITS programming in configs
[linux-2.6-block.git] / drivers / gpu / drm / i915 / i915_perf.c
CommitLineData
eec688e1
RB
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
7abbd8d6
RB
27
28/**
16d98b31 29 * DOC: i915 Perf Overview
7abbd8d6
RB
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 *
16d98b31
RB
48 */
49
50/**
51 * DOC: i915 Perf History and Comparison with Core Perf
7abbd8d6
RB
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 *
16d98b31
RB
82 * Issues hit with first prototype based on Core Perf
83 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7abbd8d6
RB
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 *
16d98b31 142 * - As a side note on perf's grouping feature; there was also some concern
7abbd8d6
RB
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
eec688e1 194#include <linux/anon_inodes.h>
d7965152 195#include <linux/sizes.h>
eec688e1
RB
196
197#include "i915_drv.h"
d7965152 198#include "i915_oa_hsw.h"
19f81df2
RB
199#include "i915_oa_bdw.h"
200#include "i915_oa_chv.h"
201#include "i915_oa_sklgt2.h"
202#include "i915_oa_sklgt3.h"
203#include "i915_oa_sklgt4.h"
204#include "i915_oa_bxt.h"
6c5c1d89
LL
205#include "i915_oa_kblgt2.h"
206#include "i915_oa_kblgt3.h"
28c7ef9e 207#include "i915_oa_glk.h"
d7965152
RB
208
209/* HW requires this to be a power of two, between 128k and 16M, though driver
210 * is currently generally designed assuming the largest 16M size is used such
211 * that the overflow cases are unlikely in normal operation.
212 */
213#define OA_BUFFER_SIZE SZ_16M
214
215#define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
216
0dd860cf
RB
217/**
218 * DOC: OA Tail Pointer Race
219 *
220 * There's a HW race condition between OA unit tail pointer register updates and
d7965152 221 * writes to memory whereby the tail pointer can sometimes get ahead of what's
0dd860cf
RB
222 * been written out to the OA buffer so far (in terms of what's visible to the
223 * CPU).
224 *
225 * Although this can be observed explicitly while copying reports to userspace
226 * by checking for a zeroed report-id field in tail reports, we want to account
19f81df2 227 * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
0dd860cf
RB
228 * read() attempts.
229 *
230 * In effect we define a tail pointer for reading that lags the real tail
231 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
232 * time for the corresponding reports to become visible to the CPU.
233 *
234 * To manage this we actually track two tail pointers:
235 * 1) An 'aging' tail with an associated timestamp that is tracked until we
236 * can trust the corresponding data is visible to the CPU; at which point
237 * it is considered 'aged'.
238 * 2) An 'aged' tail that can be used for read()ing.
d7965152 239 *
0dd860cf 240 * The two separate pointers let us decouple read()s from tail pointer aging.
d7965152 241 *
0dd860cf
RB
242 * The tail pointers are checked and updated at a limited rate within a hrtimer
243 * callback (the same callback that is used for delivering POLLIN events)
d7965152 244 *
0dd860cf
RB
245 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
246 * indicates that an updated tail pointer is needed.
247 *
248 * Most of the implementation details for this workaround are in
19f81df2 249 * oa_buffer_check_unlocked() and _append_oa_reports()
0dd860cf
RB
250 *
251 * Note for posterity: previously the driver used to define an effective tail
252 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
253 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
254 * This was flawed considering that the OA unit may also automatically generate
255 * non-periodic reports (such as on context switch) or the OA unit may be
256 * enabled without any periodic sampling.
d7965152
RB
257 */
258#define OA_TAIL_MARGIN_NSEC 100000ULL
0dd860cf 259#define INVALID_TAIL_PTR 0xffffffff
d7965152
RB
260
261/* frequency for checking whether the OA unit has written new reports to the
262 * circular OA buffer...
263 */
264#define POLL_FREQUENCY 200
265#define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
266
ccdf6341
RB
267/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
268static int zero;
269static int one = 1;
270static u32 i915_perf_stream_paranoid = true;
271
d7965152
RB
272/* The maximum exponent the hardware accepts is 63 (essentially it selects one
273 * of the 64bit timestamp bits to trigger reports from) but there's currently
274 * no known use case for sampling as infrequently as once per 47 thousand years.
275 *
276 * Since the timestamps included in OA reports are only 32bits it seems
277 * reasonable to limit the OA exponent where it's still possible to account for
278 * overflow in OA report timestamps.
279 */
280#define OA_EXPONENT_MAX 31
281
282#define INVALID_CTX_ID 0xffffffff
283
19f81df2
RB
284/* On Gen8+ automatically triggered OA reports include a 'reason' field... */
285#define OAREPORT_REASON_MASK 0x3f
286#define OAREPORT_REASON_SHIFT 19
287#define OAREPORT_REASON_TIMER (1<<0)
288#define OAREPORT_REASON_CTX_SWITCH (1<<3)
289#define OAREPORT_REASON_CLK_RATIO (1<<5)
290
d7965152 291
00319ba0
RB
292/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
293 *
155e941f
RB
294 * The highest sampling frequency we can theoretically program the OA unit
295 * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
296 *
297 * Initialized just before we register the sysctl parameter.
00319ba0 298 */
155e941f 299static int oa_sample_rate_hard_limit;
00319ba0
RB
300
301/* Theoretically we can program the OA unit to sample every 160ns but don't
302 * allow that by default unless root...
303 *
304 * The default threshold of 100000Hz is based on perf's similar
305 * kernel.perf_event_max_sample_rate sysctl parameter.
306 */
307static u32 i915_oa_max_sample_rate = 100000;
308
d7965152
RB
309/* XXX: beware if future OA HW adds new report formats that the current
310 * code assumes all reports have a power-of-two size and ~(size - 1) can
311 * be used as a mask to align the OA tail pointer.
312 */
313static struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
314 [I915_OA_FORMAT_A13] = { 0, 64 },
315 [I915_OA_FORMAT_A29] = { 1, 128 },
316 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
317 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
318 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
319 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
320 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
321 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
322};
323
19f81df2
RB
324static struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
325 [I915_OA_FORMAT_A12] = { 0, 64 },
326 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
327 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
328 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
329};
330
d7965152 331#define SAMPLE_OA_REPORT (1<<0)
eec688e1 332
16d98b31
RB
333/**
334 * struct perf_open_properties - for validated properties given to open a stream
335 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
336 * @single_context: Whether a single or all gpu contexts should be monitored
337 * @ctx_handle: A gem ctx handle for use with @single_context
338 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
339 * @oa_format: An OA unit HW report format
340 * @oa_periodic: Whether to enable periodic OA unit sampling
341 * @oa_period_exponent: The OA unit sampling period is derived from this
342 *
343 * As read_properties_unlocked() enumerates and validates the properties given
344 * to open a stream of metrics the configuration is built up in the structure
345 * which starts out zero initialized.
346 */
eec688e1
RB
347struct perf_open_properties {
348 u32 sample_flags;
349
350 u64 single_context:1;
351 u64 ctx_handle;
d7965152
RB
352
353 /* OA sampling state */
354 int metrics_set;
355 int oa_format;
356 bool oa_periodic;
357 int oa_period_exponent;
358};
359
19f81df2
RB
360static u32 gen8_oa_hw_tail_read(struct drm_i915_private *dev_priv)
361{
362 return I915_READ(GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
363}
364
365static u32 gen7_oa_hw_tail_read(struct drm_i915_private *dev_priv)
366{
367 u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
368
369 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
370}
371
0dd860cf 372/**
19f81df2 373 * oa_buffer_check_unlocked - check for data and update tail ptr state
0dd860cf 374 * @dev_priv: i915 device instance
d7965152 375 *
0dd860cf
RB
376 * This is either called via fops (for blocking reads in user ctx) or the poll
377 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
378 * if there is data available for userspace to read.
d7965152 379 *
0dd860cf
RB
380 * This function is central to providing a workaround for the OA unit tail
381 * pointer having a race with respect to what data is visible to the CPU.
382 * It is responsible for reading tail pointers from the hardware and giving
383 * the pointers time to 'age' before they are made available for reading.
384 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
385 *
386 * Besides returning true when there is data available to read() this function
387 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
388 * and .aged_tail_idx state used for reading.
389 *
390 * Note: It's safe to read OA config state here unlocked, assuming that this is
391 * only called while the stream is enabled, while the global OA configuration
392 * can't be modified.
393 *
394 * Returns: %true if the OA buffer contains data, else %false
d7965152 395 */
19f81df2 396static bool oa_buffer_check_unlocked(struct drm_i915_private *dev_priv)
d7965152
RB
397{
398 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
0dd860cf
RB
399 unsigned long flags;
400 unsigned int aged_idx;
0dd860cf
RB
401 u32 head, hw_tail, aged_tail, aging_tail;
402 u64 now;
403
404 /* We have to consider the (unlikely) possibility that read() errors
405 * could result in an OA buffer reset which might reset the head,
406 * tails[] and aged_tail state.
407 */
408 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
409
410 /* NB: The head we observe here might effectively be a little out of
411 * date (between head and tails[aged_idx].offset if there is currently
412 * a read() in progress.
413 */
414 head = dev_priv->perf.oa.oa_buffer.head;
415
416 aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
417 aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset;
418 aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset;
419
19f81df2 420 hw_tail = dev_priv->perf.oa.ops.oa_hw_tail_read(dev_priv);
0dd860cf
RB
421
422 /* The tail pointer increases in 64 byte increments,
423 * not in report_size steps...
424 */
425 hw_tail &= ~(report_size - 1);
426
427 now = ktime_get_mono_fast_ns();
428
4117ebc7
RB
429 /* Update the aged tail
430 *
431 * Flip the tail pointer available for read()s once the aging tail is
432 * old enough to trust that the corresponding data will be visible to
433 * the CPU...
434 *
435 * Do this before updating the aging pointer in case we may be able to
436 * immediately start aging a new pointer too (if new data has become
437 * available) without needing to wait for a later hrtimer callback.
438 */
439 if (aging_tail != INVALID_TAIL_PTR &&
440 ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) >
441 OA_TAIL_MARGIN_NSEC)) {
19f81df2 442
4117ebc7
RB
443 aged_idx ^= 1;
444 dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx;
445
446 aged_tail = aging_tail;
447
448 /* Mark that we need a new pointer to start aging... */
449 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
450 aging_tail = INVALID_TAIL_PTR;
451 }
452
0dd860cf
RB
453 /* Update the aging tail
454 *
455 * We throttle aging tail updates until we have a new tail that
456 * represents >= one report more data than is already available for
457 * reading. This ensures there will be enough data for a successful
458 * read once this new pointer has aged and ensures we will give the new
459 * pointer time to age.
460 */
461 if (aging_tail == INVALID_TAIL_PTR &&
462 (aged_tail == INVALID_TAIL_PTR ||
463 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
464 struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma;
465 u32 gtt_offset = i915_ggtt_offset(vma);
466
467 /* Be paranoid and do a bounds check on the pointer read back
468 * from hardware, just in case some spurious hardware condition
469 * could put the tail out of bounds...
470 */
471 if (hw_tail >= gtt_offset &&
472 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
473 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset =
474 aging_tail = hw_tail;
475 dev_priv->perf.oa.oa_buffer.aging_timestamp = now;
476 } else {
477 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
478 hw_tail);
479 }
480 }
481
0dd860cf
RB
482 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
483
484 return aged_tail == INVALID_TAIL_PTR ?
485 false : OA_TAKEN(aged_tail, head) >= report_size;
d7965152
RB
486}
487
488/**
16d98b31
RB
489 * append_oa_status - Appends a status record to a userspace read() buffer.
490 * @stream: An i915-perf stream opened for OA metrics
491 * @buf: destination buffer given by userspace
492 * @count: the number of bytes userspace wants to read
493 * @offset: (inout): the current position for writing into @buf
494 * @type: The kind of status to report to userspace
495 *
496 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
497 * into the userspace read() buffer.
498 *
499 * The @buf @offset will only be updated on success.
500 *
501 * Returns: 0 on success, negative error code on failure.
d7965152
RB
502 */
503static int append_oa_status(struct i915_perf_stream *stream,
504 char __user *buf,
505 size_t count,
506 size_t *offset,
507 enum drm_i915_perf_record_type type)
508{
509 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
510
511 if ((count - *offset) < header.size)
512 return -ENOSPC;
513
514 if (copy_to_user(buf + *offset, &header, sizeof(header)))
515 return -EFAULT;
516
517 (*offset) += header.size;
518
519 return 0;
520}
521
522/**
16d98b31
RB
523 * append_oa_sample - Copies single OA report into userspace read() buffer.
524 * @stream: An i915-perf stream opened for OA metrics
525 * @buf: destination buffer given by userspace
526 * @count: the number of bytes userspace wants to read
527 * @offset: (inout): the current position for writing into @buf
528 * @report: A single OA report to (optionally) include as part of the sample
529 *
530 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
531 * properties when opening a stream, tracked as `stream->sample_flags`. This
532 * function copies the requested components of a single sample to the given
533 * read() @buf.
534 *
535 * The @buf @offset will only be updated on success.
536 *
537 * Returns: 0 on success, negative error code on failure.
d7965152
RB
538 */
539static int append_oa_sample(struct i915_perf_stream *stream,
540 char __user *buf,
541 size_t count,
542 size_t *offset,
543 const u8 *report)
544{
545 struct drm_i915_private *dev_priv = stream->dev_priv;
546 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
547 struct drm_i915_perf_record_header header;
548 u32 sample_flags = stream->sample_flags;
549
550 header.type = DRM_I915_PERF_RECORD_SAMPLE;
551 header.pad = 0;
552 header.size = stream->sample_size;
553
554 if ((count - *offset) < header.size)
555 return -ENOSPC;
556
557 buf += *offset;
558 if (copy_to_user(buf, &header, sizeof(header)))
559 return -EFAULT;
560 buf += sizeof(header);
561
562 if (sample_flags & SAMPLE_OA_REPORT) {
563 if (copy_to_user(buf, report, report_size))
564 return -EFAULT;
565 }
566
567 (*offset) += header.size;
568
569 return 0;
570}
571
19f81df2
RB
572/**
573 * Copies all buffered OA reports into userspace read() buffer.
574 * @stream: An i915-perf stream opened for OA metrics
575 * @buf: destination buffer given by userspace
576 * @count: the number of bytes userspace wants to read
577 * @offset: (inout): the current position for writing into @buf
578 *
579 * Notably any error condition resulting in a short read (-%ENOSPC or
580 * -%EFAULT) will be returned even though one or more records may
581 * have been successfully copied. In this case it's up to the caller
582 * to decide if the error should be squashed before returning to
583 * userspace.
584 *
585 * Note: reports are consumed from the head, and appended to the
586 * tail, so the tail chases the head?... If you think that's mad
587 * and back-to-front you're not alone, but this follows the
588 * Gen PRM naming convention.
589 *
590 * Returns: 0 on success, negative error code on failure.
591 */
592static int gen8_append_oa_reports(struct i915_perf_stream *stream,
593 char __user *buf,
594 size_t count,
595 size_t *offset)
596{
597 struct drm_i915_private *dev_priv = stream->dev_priv;
598 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
599 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
600 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
601 u32 mask = (OA_BUFFER_SIZE - 1);
602 size_t start_offset = *offset;
603 unsigned long flags;
604 unsigned int aged_tail_idx;
605 u32 head, tail;
606 u32 taken;
607 int ret = 0;
608
609 if (WARN_ON(!stream->enabled))
610 return -EIO;
611
612 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
613
614 head = dev_priv->perf.oa.oa_buffer.head;
615 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
616 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
617
618 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
619
620 /*
621 * An invalid tail pointer here means we're still waiting for the poll
622 * hrtimer callback to give us a pointer
623 */
624 if (tail == INVALID_TAIL_PTR)
625 return -EAGAIN;
626
627 /*
628 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
629 * while indexing relative to oa_buf_base.
630 */
631 head -= gtt_offset;
632 tail -= gtt_offset;
633
634 /*
635 * An out of bounds or misaligned head or tail pointer implies a driver
636 * bug since we validate + align the tail pointers we read from the
637 * hardware and we are in full control of the head pointer which should
638 * only be incremented by multiples of the report size (notably also
639 * all a power of two).
640 */
641 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
642 tail > OA_BUFFER_SIZE || tail % report_size,
643 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
644 head, tail))
645 return -EIO;
646
647
648 for (/* none */;
649 (taken = OA_TAKEN(tail, head));
650 head = (head + report_size) & mask) {
651 u8 *report = oa_buf_base + head;
652 u32 *report32 = (void *)report;
653 u32 ctx_id;
654 u32 reason;
655
656 /*
657 * All the report sizes factor neatly into the buffer
658 * size so we never expect to see a report split
659 * between the beginning and end of the buffer.
660 *
661 * Given the initial alignment check a misalignment
662 * here would imply a driver bug that would result
663 * in an overrun.
664 */
665 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
666 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
667 break;
668 }
669
670 /*
671 * The reason field includes flags identifying what
672 * triggered this specific report (mostly timer
673 * triggered or e.g. due to a context switch).
674 *
675 * This field is never expected to be zero so we can
676 * check that the report isn't invalid before copying
677 * it to userspace...
678 */
679 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
680 OAREPORT_REASON_MASK);
681 if (reason == 0) {
682 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
683 DRM_NOTE("Skipping spurious, invalid OA report\n");
684 continue;
685 }
686
687 /*
688 * XXX: Just keep the lower 21 bits for now since I'm not
689 * entirely sure if the HW touches any of the higher bits in
690 * this field
691 */
692 ctx_id = report32[2] & 0x1fffff;
693
694 /*
695 * Squash whatever is in the CTX_ID field if it's marked as
696 * invalid to be sure we avoid false-positive, single-context
697 * filtering below...
698 *
699 * Note: that we don't clear the valid_ctx_bit so userspace can
700 * understand that the ID has been squashed by the kernel.
701 */
702 if (!(report32[0] & dev_priv->perf.oa.gen8_valid_ctx_bit))
703 ctx_id = report32[2] = INVALID_CTX_ID;
704
705 /*
706 * NB: For Gen 8 the OA unit no longer supports clock gating
707 * off for a specific context and the kernel can't securely
708 * stop the counters from updating as system-wide / global
709 * values.
710 *
711 * Automatic reports now include a context ID so reports can be
712 * filtered on the cpu but it's not worth trying to
713 * automatically subtract/hide counter progress for other
714 * contexts while filtering since we can't stop userspace
715 * issuing MI_REPORT_PERF_COUNT commands which would still
716 * provide a side-band view of the real values.
717 *
718 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
719 * to normalize counters for a single filtered context then it
720 * needs be forwarded bookend context-switch reports so that it
721 * can track switches in between MI_REPORT_PERF_COUNT commands
722 * and can itself subtract/ignore the progress of counters
723 * associated with other contexts. Note that the hardware
724 * automatically triggers reports when switching to a new
725 * context which are tagged with the ID of the newly active
726 * context. To avoid the complexity (and likely fragility) of
727 * reading ahead while parsing reports to try and minimize
728 * forwarding redundant context switch reports (i.e. between
729 * other, unrelated contexts) we simply elect to forward them
730 * all.
731 *
732 * We don't rely solely on the reason field to identify context
733 * switches since it's not-uncommon for periodic samples to
734 * identify a switch before any 'context switch' report.
735 */
736 if (!dev_priv->perf.oa.exclusive_stream->ctx ||
737 dev_priv->perf.oa.specific_ctx_id == ctx_id ||
738 (dev_priv->perf.oa.oa_buffer.last_ctx_id ==
739 dev_priv->perf.oa.specific_ctx_id) ||
740 reason & OAREPORT_REASON_CTX_SWITCH) {
741
742 /*
743 * While filtering for a single context we avoid
744 * leaking the IDs of other contexts.
745 */
746 if (dev_priv->perf.oa.exclusive_stream->ctx &&
747 dev_priv->perf.oa.specific_ctx_id != ctx_id) {
748 report32[2] = INVALID_CTX_ID;
749 }
750
751 ret = append_oa_sample(stream, buf, count, offset,
752 report);
753 if (ret)
754 break;
755
756 dev_priv->perf.oa.oa_buffer.last_ctx_id = ctx_id;
757 }
758
759 /*
760 * The above reason field sanity check is based on
761 * the assumption that the OA buffer is initially
762 * zeroed and we reset the field after copying so the
763 * check is still meaningful once old reports start
764 * being overwritten.
765 */
766 report32[0] = 0;
767 }
768
769 if (start_offset != *offset) {
770 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
771
772 /*
773 * We removed the gtt_offset for the copy loop above, indexing
774 * relative to oa_buf_base so put back here...
775 */
776 head += gtt_offset;
777
778 I915_WRITE(GEN8_OAHEADPTR, head & GEN8_OAHEADPTR_MASK);
779 dev_priv->perf.oa.oa_buffer.head = head;
780
781 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
782 }
783
784 return ret;
785}
786
787/**
788 * gen8_oa_read - copy status records then buffered OA reports
789 * @stream: An i915-perf stream opened for OA metrics
790 * @buf: destination buffer given by userspace
791 * @count: the number of bytes userspace wants to read
792 * @offset: (inout): the current position for writing into @buf
793 *
794 * Checks OA unit status registers and if necessary appends corresponding
795 * status records for userspace (such as for a buffer full condition) and then
796 * initiate appending any buffered OA reports.
797 *
798 * Updates @offset according to the number of bytes successfully copied into
799 * the userspace buffer.
800 *
801 * NB: some data may be successfully copied to the userspace buffer
802 * even if an error is returned, and this is reflected in the
803 * updated @offset.
804 *
805 * Returns: zero on success or a negative error code
806 */
807static int gen8_oa_read(struct i915_perf_stream *stream,
808 char __user *buf,
809 size_t count,
810 size_t *offset)
811{
812 struct drm_i915_private *dev_priv = stream->dev_priv;
813 u32 oastatus;
814 int ret;
815
816 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
817 return -EIO;
818
819 oastatus = I915_READ(GEN8_OASTATUS);
820
821 /*
822 * We treat OABUFFER_OVERFLOW as a significant error:
823 *
824 * Although theoretically we could handle this more gracefully
825 * sometimes, some Gens don't correctly suppress certain
826 * automatically triggered reports in this condition and so we
827 * have to assume that old reports are now being trampled
828 * over.
829 *
830 * Considering how we don't currently give userspace control
831 * over the OA buffer size and always configure a large 16MB
832 * buffer, then a buffer overflow does anyway likely indicate
833 * that something has gone quite badly wrong.
834 */
835 if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
836 ret = append_oa_status(stream, buf, count, offset,
837 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
838 if (ret)
839 return ret;
840
841 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
842 dev_priv->perf.oa.period_exponent);
843
844 dev_priv->perf.oa.ops.oa_disable(dev_priv);
845 dev_priv->perf.oa.ops.oa_enable(dev_priv);
846
847 /*
848 * Note: .oa_enable() is expected to re-init the oabuffer and
849 * reset GEN8_OASTATUS for us
850 */
851 oastatus = I915_READ(GEN8_OASTATUS);
852 }
853
854 if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
855 ret = append_oa_status(stream, buf, count, offset,
856 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
857 if (ret)
858 return ret;
859 I915_WRITE(GEN8_OASTATUS,
860 oastatus & ~GEN8_OASTATUS_REPORT_LOST);
861 }
862
863 return gen8_append_oa_reports(stream, buf, count, offset);
864}
865
d7965152
RB
866/**
867 * Copies all buffered OA reports into userspace read() buffer.
868 * @stream: An i915-perf stream opened for OA metrics
869 * @buf: destination buffer given by userspace
870 * @count: the number of bytes userspace wants to read
871 * @offset: (inout): the current position for writing into @buf
d7965152 872 *
16d98b31
RB
873 * Notably any error condition resulting in a short read (-%ENOSPC or
874 * -%EFAULT) will be returned even though one or more records may
d7965152
RB
875 * have been successfully copied. In this case it's up to the caller
876 * to decide if the error should be squashed before returning to
877 * userspace.
878 *
879 * Note: reports are consumed from the head, and appended to the
e81b3a55 880 * tail, so the tail chases the head?... If you think that's mad
d7965152
RB
881 * and back-to-front you're not alone, but this follows the
882 * Gen PRM naming convention.
16d98b31
RB
883 *
884 * Returns: 0 on success, negative error code on failure.
d7965152
RB
885 */
886static int gen7_append_oa_reports(struct i915_perf_stream *stream,
887 char __user *buf,
888 size_t count,
3bb335c1 889 size_t *offset)
d7965152
RB
890{
891 struct drm_i915_private *dev_priv = stream->dev_priv;
892 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
893 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
d7965152
RB
894 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
895 u32 mask = (OA_BUFFER_SIZE - 1);
3bb335c1 896 size_t start_offset = *offset;
0dd860cf
RB
897 unsigned long flags;
898 unsigned int aged_tail_idx;
899 u32 head, tail;
d7965152
RB
900 u32 taken;
901 int ret = 0;
902
903 if (WARN_ON(!stream->enabled))
904 return -EIO;
905
0dd860cf 906 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
f279020a 907
0dd860cf
RB
908 head = dev_priv->perf.oa.oa_buffer.head;
909 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
910 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
f279020a 911
0dd860cf 912 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
d7965152 913
0dd860cf
RB
914 /* An invalid tail pointer here means we're still waiting for the poll
915 * hrtimer callback to give us a pointer
d7965152 916 */
0dd860cf
RB
917 if (tail == INVALID_TAIL_PTR)
918 return -EAGAIN;
d7965152 919
0dd860cf
RB
920 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
921 * while indexing relative to oa_buf_base.
d7965152 922 */
0dd860cf
RB
923 head -= gtt_offset;
924 tail -= gtt_offset;
d7965152 925
0dd860cf
RB
926 /* An out of bounds or misaligned head or tail pointer implies a driver
927 * bug since we validate + align the tail pointers we read from the
928 * hardware and we are in full control of the head pointer which should
929 * only be incremented by multiples of the report size (notably also
930 * all a power of two).
d7965152 931 */
0dd860cf
RB
932 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
933 tail > OA_BUFFER_SIZE || tail % report_size,
934 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
935 head, tail))
936 return -EIO;
d7965152 937
d7965152
RB
938
939 for (/* none */;
940 (taken = OA_TAKEN(tail, head));
941 head = (head + report_size) & mask) {
942 u8 *report = oa_buf_base + head;
943 u32 *report32 = (void *)report;
944
945 /* All the report sizes factor neatly into the buffer
946 * size so we never expect to see a report split
947 * between the beginning and end of the buffer.
948 *
949 * Given the initial alignment check a misalignment
950 * here would imply a driver bug that would result
951 * in an overrun.
952 */
953 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
954 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
955 break;
956 }
957
958 /* The report-ID field for periodic samples includes
959 * some undocumented flags related to what triggered
960 * the report and is never expected to be zero so we
961 * can check that the report isn't invalid before
962 * copying it to userspace...
963 */
964 if (report32[0] == 0) {
712122ea
RB
965 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
966 DRM_NOTE("Skipping spurious, invalid OA report\n");
d7965152
RB
967 continue;
968 }
969
970 ret = append_oa_sample(stream, buf, count, offset, report);
971 if (ret)
972 break;
973
974 /* The above report-id field sanity check is based on
975 * the assumption that the OA buffer is initially
976 * zeroed and we reset the field after copying so the
977 * check is still meaningful once old reports start
978 * being overwritten.
979 */
980 report32[0] = 0;
981 }
982
3bb335c1 983 if (start_offset != *offset) {
0dd860cf
RB
984 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
985
3bb335c1
RB
986 /* We removed the gtt_offset for the copy loop above, indexing
987 * relative to oa_buf_base so put back here...
988 */
989 head += gtt_offset;
990
991 I915_WRITE(GEN7_OASTATUS2,
992 ((head & GEN7_OASTATUS2_HEAD_MASK) |
993 OA_MEM_SELECT_GGTT));
994 dev_priv->perf.oa.oa_buffer.head = head;
0dd860cf
RB
995
996 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
3bb335c1 997 }
d7965152
RB
998
999 return ret;
1000}
1001
16d98b31
RB
1002/**
1003 * gen7_oa_read - copy status records then buffered OA reports
1004 * @stream: An i915-perf stream opened for OA metrics
1005 * @buf: destination buffer given by userspace
1006 * @count: the number of bytes userspace wants to read
1007 * @offset: (inout): the current position for writing into @buf
1008 *
1009 * Checks Gen 7 specific OA unit status registers and if necessary appends
1010 * corresponding status records for userspace (such as for a buffer full
1011 * condition) and then initiate appending any buffered OA reports.
1012 *
1013 * Updates @offset according to the number of bytes successfully copied into
1014 * the userspace buffer.
1015 *
1016 * Returns: zero on success or a negative error code
1017 */
d7965152
RB
1018static int gen7_oa_read(struct i915_perf_stream *stream,
1019 char __user *buf,
1020 size_t count,
1021 size_t *offset)
1022{
1023 struct drm_i915_private *dev_priv = stream->dev_priv;
d7965152 1024 u32 oastatus1;
d7965152
RB
1025 int ret;
1026
1027 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
1028 return -EIO;
1029
d7965152
RB
1030 oastatus1 = I915_READ(GEN7_OASTATUS1);
1031
d7965152
RB
1032 /* XXX: On Haswell we don't have a safe way to clear oastatus1
1033 * bits while the OA unit is enabled (while the tail pointer
1034 * may be updated asynchronously) so we ignore status bits
1035 * that have already been reported to userspace.
1036 */
1037 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
1038
1039 /* We treat OABUFFER_OVERFLOW as a significant error:
1040 *
1041 * - The status can be interpreted to mean that the buffer is
1042 * currently full (with a higher precedence than OA_TAKEN()
1043 * which will start to report a near-empty buffer after an
1044 * overflow) but it's awkward that we can't clear the status
1045 * on Haswell, so without a reset we won't be able to catch
1046 * the state again.
1047 *
1048 * - Since it also implies the HW has started overwriting old
1049 * reports it may also affect our sanity checks for invalid
1050 * reports when copying to userspace that assume new reports
1051 * are being written to cleared memory.
1052 *
1053 * - In the future we may want to introduce a flight recorder
1054 * mode where the driver will automatically maintain a safe
1055 * guard band between head/tail, avoiding this overflow
1056 * condition, but we avoid the added driver complexity for
1057 * now.
1058 */
1059 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1060 ret = append_oa_status(stream, buf, count, offset,
1061 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1062 if (ret)
1063 return ret;
1064
19f81df2
RB
1065 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
1066 dev_priv->perf.oa.period_exponent);
d7965152
RB
1067
1068 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1069 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1070
d7965152 1071 oastatus1 = I915_READ(GEN7_OASTATUS1);
d7965152
RB
1072 }
1073
1074 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1075 ret = append_oa_status(stream, buf, count, offset,
1076 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1077 if (ret)
1078 return ret;
1079 dev_priv->perf.oa.gen7_latched_oastatus1 |=
1080 GEN7_OASTATUS1_REPORT_LOST;
1081 }
1082
3bb335c1 1083 return gen7_append_oa_reports(stream, buf, count, offset);
d7965152
RB
1084}
1085
16d98b31
RB
1086/**
1087 * i915_oa_wait_unlocked - handles blocking IO until OA data available
1088 * @stream: An i915-perf stream opened for OA metrics
1089 *
1090 * Called when userspace tries to read() from a blocking stream FD opened
1091 * for OA metrics. It waits until the hrtimer callback finds a non-empty
1092 * OA buffer and wakes us.
1093 *
1094 * Note: it's acceptable to have this return with some false positives
1095 * since any subsequent read handling will return -EAGAIN if there isn't
1096 * really data ready for userspace yet.
1097 *
1098 * Returns: zero on success or a negative error code
1099 */
d7965152
RB
1100static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1101{
1102 struct drm_i915_private *dev_priv = stream->dev_priv;
1103
1104 /* We would wait indefinitely if periodic sampling is not enabled */
1105 if (!dev_priv->perf.oa.periodic)
1106 return -EIO;
1107
d7965152 1108 return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
19f81df2 1109 oa_buffer_check_unlocked(dev_priv));
d7965152
RB
1110}
1111
16d98b31
RB
1112/**
1113 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1114 * @stream: An i915-perf stream opened for OA metrics
1115 * @file: An i915 perf stream file
1116 * @wait: poll() state table
1117 *
1118 * For handling userspace polling on an i915 perf stream opened for OA metrics,
1119 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1120 * when it sees data ready to read in the circular OA buffer.
1121 */
d7965152
RB
1122static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1123 struct file *file,
1124 poll_table *wait)
1125{
1126 struct drm_i915_private *dev_priv = stream->dev_priv;
1127
1128 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
1129}
1130
16d98b31
RB
1131/**
1132 * i915_oa_read - just calls through to &i915_oa_ops->read
1133 * @stream: An i915-perf stream opened for OA metrics
1134 * @buf: destination buffer given by userspace
1135 * @count: the number of bytes userspace wants to read
1136 * @offset: (inout): the current position for writing into @buf
1137 *
1138 * Updates @offset according to the number of bytes successfully copied into
1139 * the userspace buffer.
1140 *
1141 * Returns: zero on success or a negative error code
1142 */
d7965152
RB
1143static int i915_oa_read(struct i915_perf_stream *stream,
1144 char __user *buf,
1145 size_t count,
1146 size_t *offset)
1147{
1148 struct drm_i915_private *dev_priv = stream->dev_priv;
1149
1150 return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
1151}
1152
16d98b31
RB
1153/**
1154 * oa_get_render_ctx_id - determine and hold ctx hw id
1155 * @stream: An i915-perf stream opened for OA metrics
1156 *
1157 * Determine the render context hw id, and ensure it remains fixed for the
d7965152
RB
1158 * lifetime of the stream. This ensures that we don't have to worry about
1159 * updating the context ID in OACONTROL on the fly.
16d98b31
RB
1160 *
1161 * Returns: zero on success or a negative error code
d7965152
RB
1162 */
1163static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1164{
1165 struct drm_i915_private *dev_priv = stream->dev_priv;
d7965152 1166
19f81df2
RB
1167 if (i915.enable_execlists)
1168 dev_priv->perf.oa.specific_ctx_id = stream->ctx->hw_id;
1169 else {
1170 struct intel_engine_cs *engine = dev_priv->engine[RCS];
1171 struct intel_ring *ring;
1172 int ret;
d7965152 1173
19f81df2
RB
1174 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1175 if (ret)
1176 return ret;
1177
1178 /*
1179 * As the ID is the gtt offset of the context's vma we
1180 * pin the vma to ensure the ID remains fixed.
1181 *
1182 * NB: implied RCS engine...
1183 */
1184 ring = engine->context_pin(engine, stream->ctx);
1185 mutex_unlock(&dev_priv->drm.struct_mutex);
1186 if (IS_ERR(ring))
1187 return PTR_ERR(ring);
d7965152 1188
19f81df2
RB
1189
1190 /*
1191 * Explicitly track the ID (instead of calling
1192 * i915_ggtt_offset() on the fly) considering the difference
1193 * with gen8+ and execlists
1194 */
1195 dev_priv->perf.oa.specific_ctx_id =
1196 i915_ggtt_offset(stream->ctx->engine[engine->id].state);
1197 }
d7965152 1198
266a240b 1199 return 0;
d7965152
RB
1200}
1201
16d98b31
RB
1202/**
1203 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1204 * @stream: An i915-perf stream opened for OA metrics
1205 *
1206 * In case anything needed doing to ensure the context HW ID would remain valid
1207 * for the lifetime of the stream, then that can be undone here.
1208 */
d7965152
RB
1209static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1210{
1211 struct drm_i915_private *dev_priv = stream->dev_priv;
1212
19f81df2
RB
1213 if (i915.enable_execlists) {
1214 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
1215 } else {
1216 struct intel_engine_cs *engine = dev_priv->engine[RCS];
d7965152 1217
19f81df2 1218 mutex_lock(&dev_priv->drm.struct_mutex);
d7965152 1219
19f81df2
RB
1220 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
1221 engine->context_unpin(engine, stream->ctx);
1222
1223 mutex_unlock(&dev_priv->drm.struct_mutex);
1224 }
d7965152
RB
1225}
1226
1227static void
1228free_oa_buffer(struct drm_i915_private *i915)
1229{
1230 mutex_lock(&i915->drm.struct_mutex);
1231
1232 i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
1233 i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
1234 i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
1235
1236 i915->perf.oa.oa_buffer.vma = NULL;
1237 i915->perf.oa.oa_buffer.vaddr = NULL;
1238
1239 mutex_unlock(&i915->drm.struct_mutex);
1240}
1241
1242static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1243{
1244 struct drm_i915_private *dev_priv = stream->dev_priv;
1245
1246 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
1247
19f81df2
RB
1248 /*
1249 * Unset exclusive_stream first, it might be checked while
1250 * disabling the metric set on gen8+.
1251 */
701f8231 1252 mutex_lock(&dev_priv->drm.struct_mutex);
19f81df2 1253 dev_priv->perf.oa.exclusive_stream = NULL;
701f8231 1254 mutex_unlock(&dev_priv->drm.struct_mutex);
19f81df2 1255
d7965152
RB
1256 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
1257
1258 free_oa_buffer(dev_priv);
1259
1260 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1261 intel_runtime_pm_put(dev_priv);
1262
1263 if (stream->ctx)
1264 oa_put_render_ctx_id(stream);
1265
712122ea
RB
1266 if (dev_priv->perf.oa.spurious_report_rs.missed) {
1267 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1268 dev_priv->perf.oa.spurious_report_rs.missed);
1269 }
d7965152
RB
1270}
1271
1272static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
1273{
1274 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
0dd860cf
RB
1275 unsigned long flags;
1276
1277 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
d7965152
RB
1278
1279 /* Pre-DevBDW: OABUFFER must be set with counters off,
1280 * before OASTATUS1, but after OASTATUS2
1281 */
1282 I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
f279020a
RB
1283 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1284
d7965152 1285 I915_WRITE(GEN7_OABUFFER, gtt_offset);
f279020a 1286
d7965152
RB
1287 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
1288
0dd860cf
RB
1289 /* Mark that we need updated tail pointers to read from... */
1290 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1291 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1292
1293 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1294
d7965152
RB
1295 /* On Haswell we have to track which OASTATUS1 flags we've
1296 * already seen since they can't be cleared while periodic
1297 * sampling is enabled.
1298 */
1299 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
1300
1301 /* NB: although the OA buffer will initially be allocated
1302 * zeroed via shmfs (and so this memset is redundant when
1303 * first allocating), we may re-init the OA buffer, either
1304 * when re-enabling a stream or in error/reset paths.
1305 *
1306 * The reason we clear the buffer for each re-init is for the
1307 * sanity check in gen7_append_oa_reports() that looks at the
1308 * report-id field to make sure it's non-zero which relies on
1309 * the assumption that new reports are being written to zeroed
1310 * memory...
1311 */
1312 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1313
1314 /* Maybe make ->pollin per-stream state if we support multiple
1315 * concurrent streams in the future.
1316 */
1317 dev_priv->perf.oa.pollin = false;
1318}
1319
19f81df2
RB
1320static void gen8_init_oa_buffer(struct drm_i915_private *dev_priv)
1321{
1322 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
1323 unsigned long flags;
1324
1325 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1326
1327 I915_WRITE(GEN8_OASTATUS, 0);
1328 I915_WRITE(GEN8_OAHEADPTR, gtt_offset);
1329 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1330
1331 I915_WRITE(GEN8_OABUFFER_UDW, 0);
1332
1333 /*
1334 * PRM says:
1335 *
1336 * "This MMIO must be set before the OATAILPTR
1337 * register and after the OAHEADPTR register. This is
1338 * to enable proper functionality of the overflow
1339 * bit."
1340 */
1341 I915_WRITE(GEN8_OABUFFER, gtt_offset |
1342 OABUFFER_SIZE_16M | OA_MEM_SELECT_GGTT);
1343 I915_WRITE(GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1344
1345 /* Mark that we need updated tail pointers to read from... */
1346 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1347 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1348
1349 /*
1350 * Reset state used to recognise context switches, affecting which
1351 * reports we will forward to userspace while filtering for a single
1352 * context.
1353 */
1354 dev_priv->perf.oa.oa_buffer.last_ctx_id = INVALID_CTX_ID;
1355
1356 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1357
1358 /*
1359 * NB: although the OA buffer will initially be allocated
1360 * zeroed via shmfs (and so this memset is redundant when
1361 * first allocating), we may re-init the OA buffer, either
1362 * when re-enabling a stream or in error/reset paths.
1363 *
1364 * The reason we clear the buffer for each re-init is for the
1365 * sanity check in gen8_append_oa_reports() that looks at the
1366 * reason field to make sure it's non-zero which relies on
1367 * the assumption that new reports are being written to zeroed
1368 * memory...
1369 */
1370 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1371
1372 /*
1373 * Maybe make ->pollin per-stream state if we support multiple
1374 * concurrent streams in the future.
1375 */
1376 dev_priv->perf.oa.pollin = false;
1377}
1378
d7965152
RB
1379static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
1380{
1381 struct drm_i915_gem_object *bo;
1382 struct i915_vma *vma;
1383 int ret;
1384
1385 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
1386 return -ENODEV;
1387
1388 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1389 if (ret)
1390 return ret;
1391
1392 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1393 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1394
12d79d78 1395 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
d7965152
RB
1396 if (IS_ERR(bo)) {
1397 DRM_ERROR("Failed to allocate OA buffer\n");
1398 ret = PTR_ERR(bo);
1399 goto unlock;
1400 }
1401
1402 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
1403 if (ret)
1404 goto err_unref;
1405
1406 /* PreHSW required 512K alignment, HSW requires 16M */
1407 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1408 if (IS_ERR(vma)) {
1409 ret = PTR_ERR(vma);
1410 goto err_unref;
1411 }
1412 dev_priv->perf.oa.oa_buffer.vma = vma;
1413
1414 dev_priv->perf.oa.oa_buffer.vaddr =
1415 i915_gem_object_pin_map(bo, I915_MAP_WB);
1416 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
1417 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
1418 goto err_unpin;
1419 }
1420
1421 dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
1422
1423 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
1424 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
1425 dev_priv->perf.oa.oa_buffer.vaddr);
1426
1427 goto unlock;
1428
1429err_unpin:
1430 __i915_vma_unpin(vma);
1431
1432err_unref:
1433 i915_gem_object_put(bo);
1434
1435 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
1436 dev_priv->perf.oa.oa_buffer.vma = NULL;
1437
1438unlock:
1439 mutex_unlock(&dev_priv->drm.struct_mutex);
1440 return ret;
1441}
1442
1443static void config_oa_regs(struct drm_i915_private *dev_priv,
1444 const struct i915_oa_reg *regs,
701f8231 1445 u32 n_regs)
d7965152 1446{
701f8231 1447 u32 i;
d7965152
RB
1448
1449 for (i = 0; i < n_regs; i++) {
1450 const struct i915_oa_reg *reg = regs + i;
1451
1452 I915_WRITE(reg->addr, reg->value);
1453 }
1454}
1455
701f8231
LL
1456static int hsw_enable_metric_set(struct drm_i915_private *dev_priv,
1457 const struct i915_oa_config *oa_config)
d7965152 1458{
d7965152
RB
1459 /* PRM:
1460 *
1461 * OA unit is using “crclk” for its functionality. When trunk
1462 * level clock gating takes place, OA clock would be gated,
1463 * unable to count the events from non-render clock domain.
1464 * Render clock gating must be disabled when OA is enabled to
1465 * count the events from non-render domain. Unit level clock
1466 * gating for RCS should also be disabled.
1467 */
1468 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1469 ~GEN7_DOP_CLOCK_GATE_ENABLE));
1470 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
1471 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1472
701f8231 1473 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
d7965152
RB
1474
1475 /* It apparently takes a fairly long time for a new MUX
1476 * configuration to be be applied after these register writes.
1477 * This delay duration was derived empirically based on the
1478 * render_basic config but hopefully it covers the maximum
1479 * configuration latency.
1480 *
1481 * As a fallback, the checks in _append_oa_reports() to skip
1482 * invalid OA reports do also seem to work to discard reports
1483 * generated before this config has completed - albeit not
1484 * silently.
1485 *
1486 * Unfortunately this is essentially a magic number, since we
1487 * don't currently know of a reliable mechanism for predicting
1488 * how long the MUX config will take to apply and besides
1489 * seeing invalid reports we don't know of a reliable way to
1490 * explicitly check that the MUX config has landed.
1491 *
1492 * It's even possible we've miss characterized the underlying
1493 * problem - it just seems like the simplest explanation why
1494 * a delay at this location would mitigate any invalid reports.
1495 */
1496 usleep_range(15000, 20000);
1497
701f8231
LL
1498 config_oa_regs(dev_priv, oa_config->b_counter_regs,
1499 oa_config->b_counter_regs_len);
d7965152
RB
1500
1501 return 0;
1502}
1503
1504static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
1505{
1506 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
1507 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1508 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
1509 GEN7_DOP_CLOCK_GATE_ENABLE));
1510
1511 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1512 ~GT_NOA_ENABLE));
1513}
1514
19f81df2
RB
1515/*
1516 * NB: It must always remain pointer safe to run this even if the OA unit
1517 * has been disabled.
1518 *
1519 * It's fine to put out-of-date values into these per-context registers
1520 * in the case that the OA unit has been disabled.
1521 */
1522static void gen8_update_reg_state_unlocked(struct i915_gem_context *ctx,
701f8231
LL
1523 u32 *reg_state,
1524 const struct i915_oa_config *oa_config)
19f81df2
RB
1525{
1526 struct drm_i915_private *dev_priv = ctx->i915;
19f81df2
RB
1527 u32 ctx_oactxctrl = dev_priv->perf.oa.ctx_oactxctrl_offset;
1528 u32 ctx_flexeu0 = dev_priv->perf.oa.ctx_flexeu0_offset;
1529 /* The MMIO offsets for Flex EU registers aren't contiguous */
1530 u32 flex_mmio[] = {
1531 i915_mmio_reg_offset(EU_PERF_CNTL0),
1532 i915_mmio_reg_offset(EU_PERF_CNTL1),
1533 i915_mmio_reg_offset(EU_PERF_CNTL2),
1534 i915_mmio_reg_offset(EU_PERF_CNTL3),
1535 i915_mmio_reg_offset(EU_PERF_CNTL4),
1536 i915_mmio_reg_offset(EU_PERF_CNTL5),
1537 i915_mmio_reg_offset(EU_PERF_CNTL6),
1538 };
1539 int i;
1540
1541 reg_state[ctx_oactxctrl] = i915_mmio_reg_offset(GEN8_OACTXCONTROL);
1542 reg_state[ctx_oactxctrl+1] = (dev_priv->perf.oa.period_exponent <<
1543 GEN8_OA_TIMER_PERIOD_SHIFT) |
1544 (dev_priv->perf.oa.periodic ?
1545 GEN8_OA_TIMER_ENABLE : 0) |
1546 GEN8_OA_COUNTER_RESUME;
1547
1548 for (i = 0; i < ARRAY_SIZE(flex_mmio); i++) {
1549 u32 state_offset = ctx_flexeu0 + i * 2;
1550 u32 mmio = flex_mmio[i];
1551
1552 /*
1553 * This arbitrary default will select the 'EU FPU0 Pipeline
1554 * Active' event. In the future it's anticipated that there
1555 * will be an explicit 'No Event' we can select, but not yet...
1556 */
1557 u32 value = 0;
19f81df2 1558
701f8231
LL
1559 if (oa_config) {
1560 u32 j;
1561
1562 for (j = 0; j < oa_config->flex_regs_len; j++) {
1563 if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) {
1564 value = oa_config->flex_regs[j].value;
1565 break;
1566 }
19f81df2
RB
1567 }
1568 }
1569
1570 reg_state[state_offset] = mmio;
1571 reg_state[state_offset+1] = value;
1572 }
1573}
1574
1575/*
1576 * Same as gen8_update_reg_state_unlocked only through the batchbuffer. This
1577 * is only used by the kernel context.
1578 */
701f8231
LL
1579static int gen8_emit_oa_config(struct drm_i915_gem_request *req,
1580 const struct i915_oa_config *oa_config)
19f81df2
RB
1581{
1582 struct drm_i915_private *dev_priv = req->i915;
19f81df2
RB
1583 /* The MMIO offsets for Flex EU registers aren't contiguous */
1584 u32 flex_mmio[] = {
1585 i915_mmio_reg_offset(EU_PERF_CNTL0),
1586 i915_mmio_reg_offset(EU_PERF_CNTL1),
1587 i915_mmio_reg_offset(EU_PERF_CNTL2),
1588 i915_mmio_reg_offset(EU_PERF_CNTL3),
1589 i915_mmio_reg_offset(EU_PERF_CNTL4),
1590 i915_mmio_reg_offset(EU_PERF_CNTL5),
1591 i915_mmio_reg_offset(EU_PERF_CNTL6),
1592 };
1593 u32 *cs;
1594 int i;
1595
01d928e9 1596 cs = intel_ring_begin(req, ARRAY_SIZE(flex_mmio) * 2 + 4);
19f81df2
RB
1597 if (IS_ERR(cs))
1598 return PTR_ERR(cs);
1599
01d928e9 1600 *cs++ = MI_LOAD_REGISTER_IMM(ARRAY_SIZE(flex_mmio) + 1);
19f81df2
RB
1601
1602 *cs++ = i915_mmio_reg_offset(GEN8_OACTXCONTROL);
1603 *cs++ = (dev_priv->perf.oa.period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
1604 (dev_priv->perf.oa.periodic ? GEN8_OA_TIMER_ENABLE : 0) |
1605 GEN8_OA_COUNTER_RESUME;
1606
1607 for (i = 0; i < ARRAY_SIZE(flex_mmio); i++) {
1608 u32 mmio = flex_mmio[i];
1609
1610 /*
1611 * This arbitrary default will select the 'EU FPU0 Pipeline
1612 * Active' event. In the future it's anticipated that there
1613 * will be an explicit 'No Event' we can select, but not
1614 * yet...
1615 */
1616 u32 value = 0;
19f81df2 1617
701f8231
LL
1618 if (oa_config) {
1619 u32 j;
1620
1621 for (j = 0; j < oa_config->flex_regs_len; j++) {
1622 if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) {
1623 value = oa_config->flex_regs[j].value;
1624 break;
1625 }
19f81df2
RB
1626 }
1627 }
1628
1629 *cs++ = mmio;
1630 *cs++ = value;
1631 }
1632
1633 *cs++ = MI_NOOP;
1634 intel_ring_advance(req, cs);
1635
1636 return 0;
1637}
1638
701f8231
LL
1639static int gen8_switch_to_updated_kernel_context(struct drm_i915_private *dev_priv,
1640 const struct i915_oa_config *oa_config)
19f81df2
RB
1641{
1642 struct intel_engine_cs *engine = dev_priv->engine[RCS];
1643 struct i915_gem_timeline *timeline;
1644 struct drm_i915_gem_request *req;
1645 int ret;
1646
1647 lockdep_assert_held(&dev_priv->drm.struct_mutex);
1648
1649 i915_gem_retire_requests(dev_priv);
1650
1651 req = i915_gem_request_alloc(engine, dev_priv->kernel_context);
1652 if (IS_ERR(req))
1653 return PTR_ERR(req);
1654
701f8231 1655 ret = gen8_emit_oa_config(req, oa_config);
19f81df2
RB
1656 if (ret) {
1657 i915_add_request(req);
1658 return ret;
1659 }
1660
1661 /* Queue this switch after all other activity */
1662 list_for_each_entry(timeline, &dev_priv->gt.timelines, link) {
1663 struct drm_i915_gem_request *prev;
1664 struct intel_timeline *tl;
1665
1666 tl = &timeline->engine[engine->id];
1667 prev = i915_gem_active_raw(&tl->last_request,
1668 &dev_priv->drm.struct_mutex);
1669 if (prev)
1670 i915_sw_fence_await_sw_fence_gfp(&req->submit,
1671 &prev->submit,
1672 GFP_KERNEL);
1673 }
1674
1675 ret = i915_switch_context(req);
1676 i915_add_request(req);
1677
1678 return ret;
1679}
1680
1681/*
1682 * Manages updating the per-context aspects of the OA stream
1683 * configuration across all contexts.
1684 *
1685 * The awkward consideration here is that OACTXCONTROL controls the
1686 * exponent for periodic sampling which is primarily used for system
1687 * wide profiling where we'd like a consistent sampling period even in
1688 * the face of context switches.
1689 *
1690 * Our approach of updating the register state context (as opposed to
1691 * say using a workaround batch buffer) ensures that the hardware
1692 * won't automatically reload an out-of-date timer exponent even
1693 * transiently before a WA BB could be parsed.
1694 *
1695 * This function needs to:
1696 * - Ensure the currently running context's per-context OA state is
1697 * updated
1698 * - Ensure that all existing contexts will have the correct per-context
1699 * OA state if they are scheduled for use.
1700 * - Ensure any new contexts will be initialized with the correct
1701 * per-context OA state.
1702 *
1703 * Note: it's only the RCS/Render context that has any OA state.
1704 */
1705static int gen8_configure_all_contexts(struct drm_i915_private *dev_priv,
701f8231 1706 const struct i915_oa_config *oa_config,
19f81df2
RB
1707 bool interruptible)
1708{
1709 struct i915_gem_context *ctx;
1710 int ret;
1711 unsigned int wait_flags = I915_WAIT_LOCKED;
1712
1713 if (interruptible) {
1714 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1715 if (ret)
1716 return ret;
1717
1718 wait_flags |= I915_WAIT_INTERRUPTIBLE;
1719 } else {
1720 mutex_lock(&dev_priv->drm.struct_mutex);
1721 }
1722
1723 /* Switch away from any user context. */
701f8231 1724 ret = gen8_switch_to_updated_kernel_context(dev_priv, oa_config);
19f81df2
RB
1725 if (ret)
1726 goto out;
1727
1728 /*
1729 * The OA register config is setup through the context image. This image
1730 * might be written to by the GPU on context switch (in particular on
1731 * lite-restore). This means we can't safely update a context's image,
1732 * if this context is scheduled/submitted to run on the GPU.
1733 *
1734 * We could emit the OA register config through the batch buffer but
1735 * this might leave small interval of time where the OA unit is
1736 * configured at an invalid sampling period.
1737 *
1738 * So far the best way to work around this issue seems to be draining
1739 * the GPU from any submitted work.
1740 */
1741 ret = i915_gem_wait_for_idle(dev_priv, wait_flags);
1742 if (ret)
1743 goto out;
1744
1745 /* Update all contexts now that we've stalled the submission. */
829a0af2 1746 list_for_each_entry(ctx, &dev_priv->contexts.list, link) {
19f81df2
RB
1747 struct intel_context *ce = &ctx->engine[RCS];
1748 u32 *regs;
1749
1750 /* OA settings will be set upon first use */
1751 if (!ce->state)
1752 continue;
1753
1754 regs = i915_gem_object_pin_map(ce->state->obj, I915_MAP_WB);
1755 if (IS_ERR(regs)) {
1756 ret = PTR_ERR(regs);
1757 goto out;
1758 }
1759
1760 ce->state->obj->mm.dirty = true;
1761 regs += LRC_STATE_PN * PAGE_SIZE / sizeof(*regs);
1762
701f8231 1763 gen8_update_reg_state_unlocked(ctx, regs, oa_config);
19f81df2
RB
1764
1765 i915_gem_object_unpin_map(ce->state->obj);
1766 }
1767
1768 out:
1769 mutex_unlock(&dev_priv->drm.struct_mutex);
1770
1771 return ret;
1772}
1773
701f8231
LL
1774static int gen8_enable_metric_set(struct drm_i915_private *dev_priv,
1775 const struct i915_oa_config *oa_config)
19f81df2 1776{
701f8231 1777 int ret;
19f81df2
RB
1778
1779 /*
1780 * We disable slice/unslice clock ratio change reports on SKL since
1781 * they are too noisy. The HW generates a lot of redundant reports
1782 * where the ratio hasn't really changed causing a lot of redundant
1783 * work to processes and increasing the chances we'll hit buffer
1784 * overruns.
1785 *
1786 * Although we don't currently use the 'disable overrun' OABUFFER
1787 * feature it's worth noting that clock ratio reports have to be
1788 * disabled before considering to use that feature since the HW doesn't
1789 * correctly block these reports.
1790 *
1791 * Currently none of the high-level metrics we have depend on knowing
1792 * this ratio to normalize.
1793 *
1794 * Note: This register is not power context saved and restored, but
1795 * that's OK considering that we disable RC6 while the OA unit is
1796 * enabled.
1797 *
1798 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
1799 * be read back from automatically triggered reports, as part of the
1800 * RPT_ID field.
1801 */
6c5c1d89 1802 if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv) ||
28c7ef9e 1803 IS_KABYLAKE(dev_priv) || IS_GEMINILAKE(dev_priv)) {
19f81df2
RB
1804 I915_WRITE(GEN8_OA_DEBUG,
1805 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
1806 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
1807 }
1808
1809 /*
1810 * Update all contexts prior writing the mux configurations as we need
1811 * to make sure all slices/subslices are ON before writing to NOA
1812 * registers.
1813 */
701f8231 1814 ret = gen8_configure_all_contexts(dev_priv, oa_config, true);
19f81df2
RB
1815 if (ret)
1816 return ret;
1817
701f8231
LL
1818 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
1819
701f8231
LL
1820 config_oa_regs(dev_priv, oa_config->b_counter_regs,
1821 oa_config->b_counter_regs_len);
19f81df2
RB
1822
1823 return 0;
1824}
1825
1826static void gen8_disable_metric_set(struct drm_i915_private *dev_priv)
1827{
1828 /* Reset all contexts' slices/subslices configurations. */
701f8231 1829 gen8_configure_all_contexts(dev_priv, NULL, false);
19f81df2
RB
1830}
1831
1bef3409 1832static void gen7_oa_enable(struct drm_i915_private *dev_priv)
d7965152 1833{
1bef3409
RB
1834 /*
1835 * Reset buf pointers so we don't forward reports from before now.
1836 *
1837 * Think carefully if considering trying to avoid this, since it
1838 * also ensures status flags and the buffer itself are cleared
1839 * in error paths, and we have checks for invalid reports based
1840 * on the assumption that certain fields are written to zeroed
1841 * memory which this helps maintains.
1842 */
1843 gen7_init_oa_buffer(dev_priv);
d7965152
RB
1844
1845 if (dev_priv->perf.oa.exclusive_stream->enabled) {
1846 struct i915_gem_context *ctx =
1847 dev_priv->perf.oa.exclusive_stream->ctx;
1848 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1849
1850 bool periodic = dev_priv->perf.oa.periodic;
1851 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1852 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1853
1854 I915_WRITE(GEN7_OACONTROL,
1855 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1856 (period_exponent <<
1857 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1858 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1859 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1860 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1861 GEN7_OACONTROL_ENABLE);
1862 } else
1863 I915_WRITE(GEN7_OACONTROL, 0);
1864}
1865
19f81df2
RB
1866static void gen8_oa_enable(struct drm_i915_private *dev_priv)
1867{
1868 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1869
1870 /*
1871 * Reset buf pointers so we don't forward reports from before now.
1872 *
1873 * Think carefully if considering trying to avoid this, since it
1874 * also ensures status flags and the buffer itself are cleared
1875 * in error paths, and we have checks for invalid reports based
1876 * on the assumption that certain fields are written to zeroed
1877 * memory which this helps maintains.
1878 */
1879 gen8_init_oa_buffer(dev_priv);
1880
1881 /*
1882 * Note: we don't rely on the hardware to perform single context
1883 * filtering and instead filter on the cpu based on the context-id
1884 * field of reports
1885 */
1886 I915_WRITE(GEN8_OACONTROL, (report_format <<
1887 GEN8_OA_REPORT_FORMAT_SHIFT) |
1888 GEN8_OA_COUNTER_ENABLE);
1889}
1890
16d98b31
RB
1891/**
1892 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1893 * @stream: An i915 perf stream opened for OA metrics
1894 *
1895 * [Re]enables hardware periodic sampling according to the period configured
1896 * when opening the stream. This also starts a hrtimer that will periodically
1897 * check for data in the circular OA buffer for notifying userspace (e.g.
1898 * during a read() or poll()).
1899 */
d7965152
RB
1900static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1901{
1902 struct drm_i915_private *dev_priv = stream->dev_priv;
1903
1904 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1905
1906 if (dev_priv->perf.oa.periodic)
1907 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1908 ns_to_ktime(POLL_PERIOD),
1909 HRTIMER_MODE_REL_PINNED);
1910}
1911
1912static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1913{
1914 I915_WRITE(GEN7_OACONTROL, 0);
1915}
1916
19f81df2
RB
1917static void gen8_oa_disable(struct drm_i915_private *dev_priv)
1918{
1919 I915_WRITE(GEN8_OACONTROL, 0);
1920}
1921
16d98b31
RB
1922/**
1923 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1924 * @stream: An i915 perf stream opened for OA metrics
1925 *
1926 * Stops the OA unit from periodically writing counter reports into the
1927 * circular OA buffer. This also stops the hrtimer that periodically checks for
1928 * data in the circular OA buffer, for notifying userspace.
1929 */
d7965152
RB
1930static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1931{
1932 struct drm_i915_private *dev_priv = stream->dev_priv;
1933
1934 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1935
1936 if (dev_priv->perf.oa.periodic)
1937 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1938}
1939
d7965152
RB
1940static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1941 .destroy = i915_oa_stream_destroy,
1942 .enable = i915_oa_stream_enable,
1943 .disable = i915_oa_stream_disable,
1944 .wait_unlocked = i915_oa_wait_unlocked,
1945 .poll_wait = i915_oa_poll_wait,
1946 .read = i915_oa_read,
eec688e1
RB
1947};
1948
701f8231
LL
1949static struct i915_oa_config *get_oa_config(struct drm_i915_private *dev_priv,
1950 int metrics_set)
1951{
1952 if (metrics_set == 1)
1953 return &dev_priv->perf.oa.test_config;
1954
1955 return NULL;
1956}
1957
16d98b31
RB
1958/**
1959 * i915_oa_stream_init - validate combined props for OA stream and init
1960 * @stream: An i915 perf stream
1961 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1962 * @props: The property state that configures stream (individually validated)
1963 *
1964 * While read_properties_unlocked() validates properties in isolation it
1965 * doesn't ensure that the combination necessarily makes sense.
1966 *
1967 * At this point it has been determined that userspace wants a stream of
1968 * OA metrics, but still we need to further validate the combined
1969 * properties are OK.
1970 *
1971 * If the configuration makes sense then we can allocate memory for
1972 * a circular OA buffer and apply the requested metric set configuration.
1973 *
1974 * Returns: zero on success or a negative error code.
1975 */
d7965152
RB
1976static int i915_oa_stream_init(struct i915_perf_stream *stream,
1977 struct drm_i915_perf_open_param *param,
1978 struct perf_open_properties *props)
1979{
1980 struct drm_i915_private *dev_priv = stream->dev_priv;
1981 int format_size;
1982 int ret;
1983
442b8c06
RB
1984 /* If the sysfs metrics/ directory wasn't registered for some
1985 * reason then don't let userspace try their luck with config
1986 * IDs
1987 */
1988 if (!dev_priv->perf.metrics_kobj) {
7708550c 1989 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
442b8c06
RB
1990 return -EINVAL;
1991 }
1992
d7965152 1993 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
7708550c 1994 DRM_DEBUG("Only OA report sampling supported\n");
d7965152
RB
1995 return -EINVAL;
1996 }
1997
1998 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
7708550c 1999 DRM_DEBUG("OA unit not supported\n");
d7965152
RB
2000 return -ENODEV;
2001 }
2002
2003 /* To avoid the complexity of having to accurately filter
2004 * counter reports and marshal to the appropriate client
2005 * we currently only allow exclusive access
2006 */
2007 if (dev_priv->perf.oa.exclusive_stream) {
7708550c 2008 DRM_DEBUG("OA unit already in use\n");
d7965152
RB
2009 return -EBUSY;
2010 }
2011
d7965152 2012 if (!props->oa_format) {
7708550c 2013 DRM_DEBUG("OA report format not specified\n");
d7965152
RB
2014 return -EINVAL;
2015 }
2016
712122ea
RB
2017 /* We set up some ratelimit state to potentially throttle any _NOTES
2018 * about spurious, invalid OA reports which we don't forward to
2019 * userspace.
2020 *
2021 * The initialization is associated with opening the stream (not driver
2022 * init) considering we print a _NOTE about any throttling when closing
2023 * the stream instead of waiting until driver _fini which no one would
2024 * ever see.
2025 *
2026 * Using the same limiting factors as printk_ratelimit()
2027 */
2028 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
2029 5 * HZ, 10);
2030 /* Since we use a DRM_NOTE for spurious reports it would be
2031 * inconsistent to let __ratelimit() automatically print a warning for
2032 * throttling.
2033 */
2034 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
2035 RATELIMIT_MSG_ON_RELEASE);
2036
d7965152
RB
2037 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2038
2039 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
2040
2041 stream->sample_flags |= SAMPLE_OA_REPORT;
2042 stream->sample_size += format_size;
2043
2044 dev_priv->perf.oa.oa_buffer.format_size = format_size;
2045 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
2046 return -EINVAL;
2047
2048 dev_priv->perf.oa.oa_buffer.format =
2049 dev_priv->perf.oa.oa_formats[props->oa_format].format;
2050
d7965152 2051 dev_priv->perf.oa.periodic = props->oa_periodic;
0dd860cf 2052 if (dev_priv->perf.oa.periodic)
d7965152
RB
2053 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
2054
d7965152
RB
2055 if (stream->ctx) {
2056 ret = oa_get_render_ctx_id(stream);
2057 if (ret)
2058 return ret;
2059 }
2060
701f8231
LL
2061 stream->oa_config = get_oa_config(dev_priv, props->metrics_set);
2062 if (!stream->oa_config)
2063 return -EINVAL;
2064
d7965152
RB
2065 /* PRM - observability performance counters:
2066 *
2067 * OACONTROL, performance counter enable, note:
2068 *
2069 * "When this bit is set, in order to have coherent counts,
2070 * RC6 power state and trunk clock gating must be disabled.
2071 * This can be achieved by programming MMIO registers as
2072 * 0xA094=0 and 0xA090[31]=1"
2073 *
2074 * In our case we are expecting that taking pm + FORCEWAKE
2075 * references will effectively disable RC6.
2076 */
2077 intel_runtime_pm_get(dev_priv);
2078 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
2079
987f8c44 2080 ret = alloc_oa_buffer(dev_priv);
2081 if (ret)
2082 goto err_oa_buf_alloc;
2083
701f8231
LL
2084 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv,
2085 stream->oa_config);
d7965152
RB
2086 if (ret)
2087 goto err_enable;
2088
2089 stream->ops = &i915_oa_stream_ops;
2090
701f8231
LL
2091 /* Lock device for exclusive_stream access late because
2092 * enable_metric_set() might lock as well on gen8+.
2093 */
2094 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
2095 if (ret)
2096 goto err_lock;
2097
d7965152
RB
2098 dev_priv->perf.oa.exclusive_stream = stream;
2099
701f8231
LL
2100 mutex_unlock(&dev_priv->drm.struct_mutex);
2101
d7965152
RB
2102 return 0;
2103
701f8231
LL
2104err_lock:
2105 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
2106
d7965152 2107err_enable:
d7965152
RB
2108 free_oa_buffer(dev_priv);
2109
2110err_oa_buf_alloc:
987f8c44 2111 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2112 intel_runtime_pm_put(dev_priv);
d7965152
RB
2113 if (stream->ctx)
2114 oa_put_render_ctx_id(stream);
2115
2116 return ret;
2117}
2118
19f81df2
RB
2119void i915_oa_init_reg_state(struct intel_engine_cs *engine,
2120 struct i915_gem_context *ctx,
2121 u32 *reg_state)
2122{
2123 struct drm_i915_private *dev_priv = engine->i915;
701f8231 2124 struct i915_perf_stream *stream = dev_priv->perf.oa.exclusive_stream;
19f81df2
RB
2125
2126 if (engine->id != RCS)
2127 return;
2128
2129 if (!dev_priv->perf.initialized)
2130 return;
2131
701f8231
LL
2132 if (stream)
2133 gen8_update_reg_state_unlocked(ctx, reg_state, stream->oa_config);
19f81df2
RB
2134}
2135
16d98b31
RB
2136/**
2137 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2138 * @stream: An i915 perf stream
2139 * @file: An i915 perf stream file
2140 * @buf: destination buffer given by userspace
2141 * @count: the number of bytes userspace wants to read
2142 * @ppos: (inout) file seek position (unused)
2143 *
2144 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2145 * ensure that if we've successfully copied any data then reporting that takes
2146 * precedence over any internal error status, so the data isn't lost.
2147 *
2148 * For example ret will be -ENOSPC whenever there is more buffered data than
2149 * can be copied to userspace, but that's only interesting if we weren't able
2150 * to copy some data because it implies the userspace buffer is too small to
2151 * receive a single record (and we never split records).
2152 *
2153 * Another case with ret == -EFAULT is more of a grey area since it would seem
2154 * like bad form for userspace to ask us to overrun its buffer, but the user
2155 * knows best:
2156 *
2157 * http://yarchive.net/comp/linux/partial_reads_writes.html
2158 *
2159 * Returns: The number of bytes copied or a negative error code on failure.
2160 */
eec688e1
RB
2161static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2162 struct file *file,
2163 char __user *buf,
2164 size_t count,
2165 loff_t *ppos)
2166{
2167 /* Note we keep the offset (aka bytes read) separate from any
2168 * error status so that the final check for whether we return
2169 * the bytes read with a higher precedence than any error (see
2170 * comment below) doesn't need to be handled/duplicated in
2171 * stream->ops->read() implementations.
2172 */
2173 size_t offset = 0;
2174 int ret = stream->ops->read(stream, buf, count, &offset);
2175
eec688e1
RB
2176 return offset ?: (ret ?: -EAGAIN);
2177}
2178
16d98b31
RB
2179/**
2180 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2181 * @file: An i915 perf stream file
2182 * @buf: destination buffer given by userspace
2183 * @count: the number of bytes userspace wants to read
2184 * @ppos: (inout) file seek position (unused)
2185 *
2186 * The entry point for handling a read() on a stream file descriptor from
2187 * userspace. Most of the work is left to the i915_perf_read_locked() and
2188 * &i915_perf_stream_ops->read but to save having stream implementations (of
2189 * which we might have multiple later) we handle blocking read here.
2190 *
2191 * We can also consistently treat trying to read from a disabled stream
2192 * as an IO error so implementations can assume the stream is enabled
2193 * while reading.
2194 *
2195 * Returns: The number of bytes copied or a negative error code on failure.
2196 */
eec688e1
RB
2197static ssize_t i915_perf_read(struct file *file,
2198 char __user *buf,
2199 size_t count,
2200 loff_t *ppos)
2201{
2202 struct i915_perf_stream *stream = file->private_data;
2203 struct drm_i915_private *dev_priv = stream->dev_priv;
2204 ssize_t ret;
2205
d7965152
RB
2206 /* To ensure it's handled consistently we simply treat all reads of a
2207 * disabled stream as an error. In particular it might otherwise lead
2208 * to a deadlock for blocking file descriptors...
2209 */
2210 if (!stream->enabled)
2211 return -EIO;
2212
eec688e1 2213 if (!(file->f_flags & O_NONBLOCK)) {
d7965152
RB
2214 /* There's the small chance of false positives from
2215 * stream->ops->wait_unlocked.
2216 *
2217 * E.g. with single context filtering since we only wait until
2218 * oabuffer has >= 1 report we don't immediately know whether
2219 * any reports really belong to the current context
eec688e1
RB
2220 */
2221 do {
2222 ret = stream->ops->wait_unlocked(stream);
2223 if (ret)
2224 return ret;
2225
2226 mutex_lock(&dev_priv->perf.lock);
2227 ret = i915_perf_read_locked(stream, file,
2228 buf, count, ppos);
2229 mutex_unlock(&dev_priv->perf.lock);
2230 } while (ret == -EAGAIN);
2231 } else {
2232 mutex_lock(&dev_priv->perf.lock);
2233 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
2234 mutex_unlock(&dev_priv->perf.lock);
2235 }
2236
26ebd9c7
RB
2237 /* We allow the poll checking to sometimes report false positive POLLIN
2238 * events where we might actually report EAGAIN on read() if there's
2239 * not really any data available. In this situation though we don't
2240 * want to enter a busy loop between poll() reporting a POLLIN event
2241 * and read() returning -EAGAIN. Clearing the oa.pollin state here
2242 * effectively ensures we back off until the next hrtimer callback
2243 * before reporting another POLLIN event.
2244 */
2245 if (ret >= 0 || ret == -EAGAIN) {
d7965152
RB
2246 /* Maybe make ->pollin per-stream state if we support multiple
2247 * concurrent streams in the future.
2248 */
2249 dev_priv->perf.oa.pollin = false;
2250 }
2251
eec688e1
RB
2252 return ret;
2253}
2254
d7965152
RB
2255static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
2256{
2257 struct drm_i915_private *dev_priv =
2258 container_of(hrtimer, typeof(*dev_priv),
2259 perf.oa.poll_check_timer);
2260
19f81df2 2261 if (oa_buffer_check_unlocked(dev_priv)) {
d7965152
RB
2262 dev_priv->perf.oa.pollin = true;
2263 wake_up(&dev_priv->perf.oa.poll_wq);
2264 }
2265
2266 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
2267
2268 return HRTIMER_RESTART;
2269}
2270
16d98b31
RB
2271/**
2272 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
2273 * @dev_priv: i915 device instance
2274 * @stream: An i915 perf stream
2275 * @file: An i915 perf stream file
2276 * @wait: poll() state table
2277 *
2278 * For handling userspace polling on an i915 perf stream, this calls through to
2279 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
2280 * will be woken for new stream data.
2281 *
2282 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2283 * with any non-file-operation driver hooks.
2284 *
2285 * Returns: any poll events that are ready without sleeping
2286 */
d7965152
RB
2287static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
2288 struct i915_perf_stream *stream,
eec688e1
RB
2289 struct file *file,
2290 poll_table *wait)
2291{
d7965152 2292 unsigned int events = 0;
eec688e1
RB
2293
2294 stream->ops->poll_wait(stream, file, wait);
2295
d7965152
RB
2296 /* Note: we don't explicitly check whether there's something to read
2297 * here since this path may be very hot depending on what else
2298 * userspace is polling, or on the timeout in use. We rely solely on
2299 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
2300 * samples to read.
2301 */
2302 if (dev_priv->perf.oa.pollin)
2303 events |= POLLIN;
eec688e1 2304
d7965152 2305 return events;
eec688e1
RB
2306}
2307
16d98b31
RB
2308/**
2309 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
2310 * @file: An i915 perf stream file
2311 * @wait: poll() state table
2312 *
2313 * For handling userspace polling on an i915 perf stream, this ensures
2314 * poll_wait() gets called with a wait queue that will be woken for new stream
2315 * data.
2316 *
2317 * Note: Implementation deferred to i915_perf_poll_locked()
2318 *
2319 * Returns: any poll events that are ready without sleeping
2320 */
eec688e1
RB
2321static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
2322{
2323 struct i915_perf_stream *stream = file->private_data;
2324 struct drm_i915_private *dev_priv = stream->dev_priv;
2325 int ret;
2326
2327 mutex_lock(&dev_priv->perf.lock);
d7965152 2328 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
eec688e1
RB
2329 mutex_unlock(&dev_priv->perf.lock);
2330
2331 return ret;
2332}
2333
16d98b31
RB
2334/**
2335 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
2336 * @stream: A disabled i915 perf stream
2337 *
2338 * [Re]enables the associated capture of data for this stream.
2339 *
2340 * If a stream was previously enabled then there's currently no intention
2341 * to provide userspace any guarantee about the preservation of previously
2342 * buffered data.
2343 */
eec688e1
RB
2344static void i915_perf_enable_locked(struct i915_perf_stream *stream)
2345{
2346 if (stream->enabled)
2347 return;
2348
2349 /* Allow stream->ops->enable() to refer to this */
2350 stream->enabled = true;
2351
2352 if (stream->ops->enable)
2353 stream->ops->enable(stream);
2354}
2355
16d98b31
RB
2356/**
2357 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
2358 * @stream: An enabled i915 perf stream
2359 *
2360 * Disables the associated capture of data for this stream.
2361 *
2362 * The intention is that disabling an re-enabling a stream will ideally be
2363 * cheaper than destroying and re-opening a stream with the same configuration,
2364 * though there are no formal guarantees about what state or buffered data
2365 * must be retained between disabling and re-enabling a stream.
2366 *
2367 * Note: while a stream is disabled it's considered an error for userspace
2368 * to attempt to read from the stream (-EIO).
2369 */
eec688e1
RB
2370static void i915_perf_disable_locked(struct i915_perf_stream *stream)
2371{
2372 if (!stream->enabled)
2373 return;
2374
2375 /* Allow stream->ops->disable() to refer to this */
2376 stream->enabled = false;
2377
2378 if (stream->ops->disable)
2379 stream->ops->disable(stream);
2380}
2381
16d98b31
RB
2382/**
2383 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2384 * @stream: An i915 perf stream
2385 * @cmd: the ioctl request
2386 * @arg: the ioctl data
2387 *
2388 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2389 * with any non-file-operation driver hooks.
2390 *
2391 * Returns: zero on success or a negative error code. Returns -EINVAL for
2392 * an unknown ioctl request.
2393 */
eec688e1
RB
2394static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
2395 unsigned int cmd,
2396 unsigned long arg)
2397{
2398 switch (cmd) {
2399 case I915_PERF_IOCTL_ENABLE:
2400 i915_perf_enable_locked(stream);
2401 return 0;
2402 case I915_PERF_IOCTL_DISABLE:
2403 i915_perf_disable_locked(stream);
2404 return 0;
2405 }
2406
2407 return -EINVAL;
2408}
2409
16d98b31
RB
2410/**
2411 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2412 * @file: An i915 perf stream file
2413 * @cmd: the ioctl request
2414 * @arg: the ioctl data
2415 *
2416 * Implementation deferred to i915_perf_ioctl_locked().
2417 *
2418 * Returns: zero on success or a negative error code. Returns -EINVAL for
2419 * an unknown ioctl request.
2420 */
eec688e1
RB
2421static long i915_perf_ioctl(struct file *file,
2422 unsigned int cmd,
2423 unsigned long arg)
2424{
2425 struct i915_perf_stream *stream = file->private_data;
2426 struct drm_i915_private *dev_priv = stream->dev_priv;
2427 long ret;
2428
2429 mutex_lock(&dev_priv->perf.lock);
2430 ret = i915_perf_ioctl_locked(stream, cmd, arg);
2431 mutex_unlock(&dev_priv->perf.lock);
2432
2433 return ret;
2434}
2435
16d98b31
RB
2436/**
2437 * i915_perf_destroy_locked - destroy an i915 perf stream
2438 * @stream: An i915 perf stream
2439 *
2440 * Frees all resources associated with the given i915 perf @stream, disabling
2441 * any associated data capture in the process.
2442 *
2443 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2444 * with any non-file-operation driver hooks.
2445 */
eec688e1
RB
2446static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
2447{
eec688e1
RB
2448 if (stream->enabled)
2449 i915_perf_disable_locked(stream);
2450
2451 if (stream->ops->destroy)
2452 stream->ops->destroy(stream);
2453
2454 list_del(&stream->link);
2455
69df05e1 2456 if (stream->ctx)
5f09a9c8 2457 i915_gem_context_put(stream->ctx);
eec688e1
RB
2458
2459 kfree(stream);
2460}
2461
16d98b31
RB
2462/**
2463 * i915_perf_release - handles userspace close() of a stream file
2464 * @inode: anonymous inode associated with file
2465 * @file: An i915 perf stream file
2466 *
2467 * Cleans up any resources associated with an open i915 perf stream file.
2468 *
2469 * NB: close() can't really fail from the userspace point of view.
2470 *
2471 * Returns: zero on success or a negative error code.
2472 */
eec688e1
RB
2473static int i915_perf_release(struct inode *inode, struct file *file)
2474{
2475 struct i915_perf_stream *stream = file->private_data;
2476 struct drm_i915_private *dev_priv = stream->dev_priv;
2477
2478 mutex_lock(&dev_priv->perf.lock);
2479 i915_perf_destroy_locked(stream);
2480 mutex_unlock(&dev_priv->perf.lock);
2481
2482 return 0;
2483}
2484
2485
2486static const struct file_operations fops = {
2487 .owner = THIS_MODULE,
2488 .llseek = no_llseek,
2489 .release = i915_perf_release,
2490 .poll = i915_perf_poll,
2491 .read = i915_perf_read,
2492 .unlocked_ioctl = i915_perf_ioctl,
2493};
2494
2495
16d98b31
RB
2496/**
2497 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
2498 * @dev_priv: i915 device instance
2499 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
2500 * @props: individually validated u64 property value pairs
2501 * @file: drm file
2502 *
2503 * See i915_perf_ioctl_open() for interface details.
2504 *
2505 * Implements further stream config validation and stream initialization on
2506 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
2507 * taken to serialize with any non-file-operation driver hooks.
2508 *
2509 * Note: at this point the @props have only been validated in isolation and
2510 * it's still necessary to validate that the combination of properties makes
2511 * sense.
2512 *
2513 * In the case where userspace is interested in OA unit metrics then further
2514 * config validation and stream initialization details will be handled by
2515 * i915_oa_stream_init(). The code here should only validate config state that
2516 * will be relevant to all stream types / backends.
2517 *
2518 * Returns: zero on success or a negative error code.
2519 */
eec688e1
RB
2520static int
2521i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
2522 struct drm_i915_perf_open_param *param,
2523 struct perf_open_properties *props,
2524 struct drm_file *file)
2525{
2526 struct i915_gem_context *specific_ctx = NULL;
2527 struct i915_perf_stream *stream = NULL;
2528 unsigned long f_flags = 0;
19f81df2 2529 bool privileged_op = true;
eec688e1
RB
2530 int stream_fd;
2531 int ret;
2532
2533 if (props->single_context) {
2534 u32 ctx_handle = props->ctx_handle;
2535 struct drm_i915_file_private *file_priv = file->driver_priv;
2536
635f56c3
ID
2537 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
2538 if (!specific_ctx) {
2539 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
2540 ctx_handle);
2541 ret = -ENOENT;
eec688e1
RB
2542 goto err;
2543 }
2544 }
2545
19f81df2
RB
2546 /*
2547 * On Haswell the OA unit supports clock gating off for a specific
2548 * context and in this mode there's no visibility of metrics for the
2549 * rest of the system, which we consider acceptable for a
2550 * non-privileged client.
2551 *
2552 * For Gen8+ the OA unit no longer supports clock gating off for a
2553 * specific context and the kernel can't securely stop the counters
2554 * from updating as system-wide / global values. Even though we can
2555 * filter reports based on the included context ID we can't block
2556 * clients from seeing the raw / global counter values via
2557 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
2558 * enable the OA unit by default.
2559 */
2560 if (IS_HASWELL(dev_priv) && specific_ctx)
2561 privileged_op = false;
2562
ccdf6341
RB
2563 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
2564 * we check a dev.i915.perf_stream_paranoid sysctl option
2565 * to determine if it's ok to access system wide OA counters
2566 * without CAP_SYS_ADMIN privileges.
2567 */
19f81df2 2568 if (privileged_op &&
ccdf6341 2569 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
7708550c 2570 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
eec688e1
RB
2571 ret = -EACCES;
2572 goto err_ctx;
2573 }
2574
2575 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
2576 if (!stream) {
2577 ret = -ENOMEM;
2578 goto err_ctx;
2579 }
2580
eec688e1
RB
2581 stream->dev_priv = dev_priv;
2582 stream->ctx = specific_ctx;
2583
d7965152
RB
2584 ret = i915_oa_stream_init(stream, param, props);
2585 if (ret)
2586 goto err_alloc;
2587
2588 /* we avoid simply assigning stream->sample_flags = props->sample_flags
2589 * to have _stream_init check the combination of sample flags more
2590 * thoroughly, but still this is the expected result at this point.
eec688e1 2591 */
d7965152
RB
2592 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
2593 ret = -ENODEV;
22f880ca 2594 goto err_flags;
d7965152 2595 }
eec688e1
RB
2596
2597 list_add(&stream->link, &dev_priv->perf.streams);
2598
2599 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
2600 f_flags |= O_CLOEXEC;
2601 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
2602 f_flags |= O_NONBLOCK;
2603
2604 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
2605 if (stream_fd < 0) {
2606 ret = stream_fd;
2607 goto err_open;
2608 }
2609
2610 if (!(param->flags & I915_PERF_FLAG_DISABLED))
2611 i915_perf_enable_locked(stream);
2612
2613 return stream_fd;
2614
2615err_open:
2616 list_del(&stream->link);
22f880ca 2617err_flags:
eec688e1
RB
2618 if (stream->ops->destroy)
2619 stream->ops->destroy(stream);
2620err_alloc:
2621 kfree(stream);
2622err_ctx:
69df05e1 2623 if (specific_ctx)
5f09a9c8 2624 i915_gem_context_put(specific_ctx);
eec688e1
RB
2625err:
2626 return ret;
2627}
2628
155e941f
RB
2629static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
2630{
2631 return div_u64(1000000000ULL * (2ULL << exponent),
2632 dev_priv->perf.oa.timestamp_frequency);
2633}
2634
16d98b31
RB
2635/**
2636 * read_properties_unlocked - validate + copy userspace stream open properties
2637 * @dev_priv: i915 device instance
2638 * @uprops: The array of u64 key value pairs given by userspace
2639 * @n_props: The number of key value pairs expected in @uprops
2640 * @props: The stream configuration built up while validating properties
eec688e1
RB
2641 *
2642 * Note this function only validates properties in isolation it doesn't
2643 * validate that the combination of properties makes sense or that all
2644 * properties necessary for a particular kind of stream have been set.
16d98b31
RB
2645 *
2646 * Note that there currently aren't any ordering requirements for properties so
2647 * we shouldn't validate or assume anything about ordering here. This doesn't
2648 * rule out defining new properties with ordering requirements in the future.
eec688e1
RB
2649 */
2650static int read_properties_unlocked(struct drm_i915_private *dev_priv,
2651 u64 __user *uprops,
2652 u32 n_props,
2653 struct perf_open_properties *props)
2654{
2655 u64 __user *uprop = uprops;
701f8231 2656 u32 i;
eec688e1
RB
2657
2658 memset(props, 0, sizeof(struct perf_open_properties));
2659
2660 if (!n_props) {
7708550c 2661 DRM_DEBUG("No i915 perf properties given\n");
eec688e1
RB
2662 return -EINVAL;
2663 }
2664
2665 /* Considering that ID = 0 is reserved and assuming that we don't
2666 * (currently) expect any configurations to ever specify duplicate
2667 * values for a particular property ID then the last _PROP_MAX value is
2668 * one greater than the maximum number of properties we expect to get
2669 * from userspace.
2670 */
2671 if (n_props >= DRM_I915_PERF_PROP_MAX) {
7708550c 2672 DRM_DEBUG("More i915 perf properties specified than exist\n");
eec688e1
RB
2673 return -EINVAL;
2674 }
2675
2676 for (i = 0; i < n_props; i++) {
00319ba0 2677 u64 oa_period, oa_freq_hz;
eec688e1
RB
2678 u64 id, value;
2679 int ret;
2680
2681 ret = get_user(id, uprop);
2682 if (ret)
2683 return ret;
2684
2685 ret = get_user(value, uprop + 1);
2686 if (ret)
2687 return ret;
2688
0a309f9e
MA
2689 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
2690 DRM_DEBUG("Unknown i915 perf property ID\n");
2691 return -EINVAL;
2692 }
2693
eec688e1
RB
2694 switch ((enum drm_i915_perf_property_id)id) {
2695 case DRM_I915_PERF_PROP_CTX_HANDLE:
2696 props->single_context = 1;
2697 props->ctx_handle = value;
2698 break;
d7965152
RB
2699 case DRM_I915_PERF_PROP_SAMPLE_OA:
2700 props->sample_flags |= SAMPLE_OA_REPORT;
2701 break;
2702 case DRM_I915_PERF_PROP_OA_METRICS_SET:
701f8231 2703 if (value == 0) {
7708550c 2704 DRM_DEBUG("Unknown OA metric set ID\n");
d7965152
RB
2705 return -EINVAL;
2706 }
2707 props->metrics_set = value;
2708 break;
2709 case DRM_I915_PERF_PROP_OA_FORMAT:
2710 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
52c57c26
RB
2711 DRM_DEBUG("Out-of-range OA report format %llu\n",
2712 value);
d7965152
RB
2713 return -EINVAL;
2714 }
2715 if (!dev_priv->perf.oa.oa_formats[value].size) {
52c57c26
RB
2716 DRM_DEBUG("Unsupported OA report format %llu\n",
2717 value);
d7965152
RB
2718 return -EINVAL;
2719 }
2720 props->oa_format = value;
2721 break;
2722 case DRM_I915_PERF_PROP_OA_EXPONENT:
2723 if (value > OA_EXPONENT_MAX) {
7708550c
RB
2724 DRM_DEBUG("OA timer exponent too high (> %u)\n",
2725 OA_EXPONENT_MAX);
d7965152
RB
2726 return -EINVAL;
2727 }
2728
00319ba0 2729 /* Theoretically we can program the OA unit to sample
155e941f
RB
2730 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
2731 * for BXT. We don't allow such high sampling
2732 * frequencies by default unless root.
00319ba0 2733 */
155e941f 2734
00319ba0 2735 BUILD_BUG_ON(sizeof(oa_period) != 8);
155e941f 2736 oa_period = oa_exponent_to_ns(dev_priv, value);
00319ba0
RB
2737
2738 /* This check is primarily to ensure that oa_period <=
2739 * UINT32_MAX (before passing to do_div which only
2740 * accepts a u32 denominator), but we can also skip
2741 * checking anything < 1Hz which implicitly can't be
2742 * limited via an integer oa_max_sample_rate.
d7965152 2743 */
00319ba0
RB
2744 if (oa_period <= NSEC_PER_SEC) {
2745 u64 tmp = NSEC_PER_SEC;
2746 do_div(tmp, oa_period);
2747 oa_freq_hz = tmp;
2748 } else
2749 oa_freq_hz = 0;
2750
2751 if (oa_freq_hz > i915_oa_max_sample_rate &&
2752 !capable(CAP_SYS_ADMIN)) {
7708550c 2753 DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
00319ba0 2754 i915_oa_max_sample_rate);
d7965152
RB
2755 return -EACCES;
2756 }
2757
2758 props->oa_periodic = true;
2759 props->oa_period_exponent = value;
2760 break;
0a309f9e 2761 case DRM_I915_PERF_PROP_MAX:
eec688e1 2762 MISSING_CASE(id);
eec688e1
RB
2763 return -EINVAL;
2764 }
2765
2766 uprop += 2;
2767 }
2768
2769 return 0;
2770}
2771
16d98b31
RB
2772/**
2773 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
2774 * @dev: drm device
2775 * @data: ioctl data copied from userspace (unvalidated)
2776 * @file: drm file
2777 *
2778 * Validates the stream open parameters given by userspace including flags
2779 * and an array of u64 key, value pair properties.
2780 *
2781 * Very little is assumed up front about the nature of the stream being
2782 * opened (for instance we don't assume it's for periodic OA unit metrics). An
2783 * i915-perf stream is expected to be a suitable interface for other forms of
2784 * buffered data written by the GPU besides periodic OA metrics.
2785 *
2786 * Note we copy the properties from userspace outside of the i915 perf
2787 * mutex to avoid an awkward lockdep with mmap_sem.
2788 *
2789 * Most of the implementation details are handled by
2790 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
2791 * mutex for serializing with any non-file-operation driver hooks.
2792 *
2793 * Return: A newly opened i915 Perf stream file descriptor or negative
2794 * error code on failure.
2795 */
eec688e1
RB
2796int i915_perf_open_ioctl(struct drm_device *dev, void *data,
2797 struct drm_file *file)
2798{
2799 struct drm_i915_private *dev_priv = dev->dev_private;
2800 struct drm_i915_perf_open_param *param = data;
2801 struct perf_open_properties props;
2802 u32 known_open_flags;
2803 int ret;
2804
2805 if (!dev_priv->perf.initialized) {
7708550c 2806 DRM_DEBUG("i915 perf interface not available for this system\n");
eec688e1
RB
2807 return -ENOTSUPP;
2808 }
2809
2810 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
2811 I915_PERF_FLAG_FD_NONBLOCK |
2812 I915_PERF_FLAG_DISABLED;
2813 if (param->flags & ~known_open_flags) {
7708550c 2814 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
eec688e1
RB
2815 return -EINVAL;
2816 }
2817
2818 ret = read_properties_unlocked(dev_priv,
2819 u64_to_user_ptr(param->properties_ptr),
2820 param->num_properties,
2821 &props);
2822 if (ret)
2823 return ret;
2824
2825 mutex_lock(&dev_priv->perf.lock);
2826 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
2827 mutex_unlock(&dev_priv->perf.lock);
2828
2829 return ret;
2830}
2831
16d98b31
RB
2832/**
2833 * i915_perf_register - exposes i915-perf to userspace
2834 * @dev_priv: i915 device instance
2835 *
2836 * In particular OA metric sets are advertised under a sysfs metrics/
2837 * directory allowing userspace to enumerate valid IDs that can be
2838 * used to open an i915-perf stream.
2839 */
442b8c06
RB
2840void i915_perf_register(struct drm_i915_private *dev_priv)
2841{
701f8231
LL
2842 int ret;
2843
442b8c06
RB
2844 if (!dev_priv->perf.initialized)
2845 return;
2846
2847 /* To be sure we're synchronized with an attempted
2848 * i915_perf_open_ioctl(); considering that we register after
2849 * being exposed to userspace.
2850 */
2851 mutex_lock(&dev_priv->perf.lock);
2852
2853 dev_priv->perf.metrics_kobj =
2854 kobject_create_and_add("metrics",
2855 &dev_priv->drm.primary->kdev->kobj);
2856 if (!dev_priv->perf.metrics_kobj)
2857 goto exit;
2858
701f8231
LL
2859 memset(&dev_priv->perf.oa.test_config, 0,
2860 sizeof(dev_priv->perf.oa.test_config));
2861
19f81df2 2862 if (IS_HASWELL(dev_priv)) {
701f8231 2863 i915_perf_load_test_config_hsw(dev_priv);
19f81df2 2864 } else if (IS_BROADWELL(dev_priv)) {
701f8231 2865 i915_perf_load_test_config_bdw(dev_priv);
19f81df2 2866 } else if (IS_CHERRYVIEW(dev_priv)) {
701f8231 2867 i915_perf_load_test_config_chv(dev_priv);
19f81df2 2868 } else if (IS_SKYLAKE(dev_priv)) {
701f8231
LL
2869 if (IS_SKL_GT2(dev_priv))
2870 i915_perf_load_test_config_sklgt2(dev_priv);
2871 else if (IS_SKL_GT3(dev_priv))
2872 i915_perf_load_test_config_sklgt3(dev_priv);
2873 else if (IS_SKL_GT4(dev_priv))
2874 i915_perf_load_test_config_sklgt4(dev_priv);
19f81df2 2875 } else if (IS_BROXTON(dev_priv)) {
701f8231 2876 i915_perf_load_test_config_bxt(dev_priv);
6c5c1d89 2877 } else if (IS_KABYLAKE(dev_priv)) {
701f8231
LL
2878 if (IS_KBL_GT2(dev_priv))
2879 i915_perf_load_test_config_kblgt2(dev_priv);
2880 else if (IS_KBL_GT3(dev_priv))
2881 i915_perf_load_test_config_kblgt3(dev_priv);
28c7ef9e 2882 } else if (IS_GEMINILAKE(dev_priv)) {
701f8231 2883 i915_perf_load_test_config_glk(dev_priv);
442b8c06
RB
2884 }
2885
701f8231
LL
2886 if (dev_priv->perf.oa.test_config.id == 0)
2887 goto sysfs_error;
2888
2889 ret = sysfs_create_group(dev_priv->perf.metrics_kobj,
2890 &dev_priv->perf.oa.test_config.sysfs_metric);
2891 if (ret)
2892 goto sysfs_error;
19f81df2
RB
2893 goto exit;
2894
2895sysfs_error:
2896 kobject_put(dev_priv->perf.metrics_kobj);
2897 dev_priv->perf.metrics_kobj = NULL;
2898
442b8c06
RB
2899exit:
2900 mutex_unlock(&dev_priv->perf.lock);
2901}
2902
16d98b31
RB
2903/**
2904 * i915_perf_unregister - hide i915-perf from userspace
2905 * @dev_priv: i915 device instance
2906 *
2907 * i915-perf state cleanup is split up into an 'unregister' and
2908 * 'deinit' phase where the interface is first hidden from
2909 * userspace by i915_perf_unregister() before cleaning up
2910 * remaining state in i915_perf_fini().
2911 */
442b8c06
RB
2912void i915_perf_unregister(struct drm_i915_private *dev_priv)
2913{
442b8c06
RB
2914 if (!dev_priv->perf.metrics_kobj)
2915 return;
2916
701f8231
LL
2917 sysfs_remove_group(dev_priv->perf.metrics_kobj,
2918 &dev_priv->perf.oa.test_config.sysfs_metric);
442b8c06
RB
2919
2920 kobject_put(dev_priv->perf.metrics_kobj);
2921 dev_priv->perf.metrics_kobj = NULL;
2922}
2923
ccdf6341
RB
2924static struct ctl_table oa_table[] = {
2925 {
2926 .procname = "perf_stream_paranoid",
2927 .data = &i915_perf_stream_paranoid,
2928 .maxlen = sizeof(i915_perf_stream_paranoid),
2929 .mode = 0644,
2930 .proc_handler = proc_dointvec_minmax,
2931 .extra1 = &zero,
2932 .extra2 = &one,
2933 },
00319ba0
RB
2934 {
2935 .procname = "oa_max_sample_rate",
2936 .data = &i915_oa_max_sample_rate,
2937 .maxlen = sizeof(i915_oa_max_sample_rate),
2938 .mode = 0644,
2939 .proc_handler = proc_dointvec_minmax,
2940 .extra1 = &zero,
2941 .extra2 = &oa_sample_rate_hard_limit,
2942 },
ccdf6341
RB
2943 {}
2944};
2945
2946static struct ctl_table i915_root[] = {
2947 {
2948 .procname = "i915",
2949 .maxlen = 0,
2950 .mode = 0555,
2951 .child = oa_table,
2952 },
2953 {}
2954};
2955
2956static struct ctl_table dev_root[] = {
2957 {
2958 .procname = "dev",
2959 .maxlen = 0,
2960 .mode = 0555,
2961 .child = i915_root,
2962 },
2963 {}
2964};
2965
16d98b31
RB
2966/**
2967 * i915_perf_init - initialize i915-perf state on module load
2968 * @dev_priv: i915 device instance
2969 *
2970 * Initializes i915-perf state without exposing anything to userspace.
2971 *
2972 * Note: i915-perf initialization is split into an 'init' and 'register'
2973 * phase with the i915_perf_register() exposing state to userspace.
2974 */
eec688e1
RB
2975void i915_perf_init(struct drm_i915_private *dev_priv)
2976{
701f8231 2977 dev_priv->perf.oa.timestamp_frequency = 0;
19f81df2
RB
2978
2979 if (IS_HASWELL(dev_priv)) {
2980 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
2981 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
2982 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
2983 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
2984 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
2985 dev_priv->perf.oa.ops.read = gen7_oa_read;
2986 dev_priv->perf.oa.ops.oa_hw_tail_read =
2987 gen7_oa_hw_tail_read;
2988
155e941f
RB
2989 dev_priv->perf.oa.timestamp_frequency = 12500000;
2990
19f81df2 2991 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
19f81df2
RB
2992 } else if (i915.enable_execlists) {
2993 /* Note: that although we could theoretically also support the
2994 * legacy ringbuffer mode on BDW (and earlier iterations of
2995 * this driver, before upstreaming did this) it didn't seem
2996 * worth the complexity to maintain now that BDW+ enable
2997 * execlist mode by default.
2998 */
d7965152 2999
701f8231
LL
3000 dev_priv->perf.oa.ops.init_oa_buffer = gen8_init_oa_buffer;
3001 dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set;
3002 dev_priv->perf.oa.ops.disable_metric_set = gen8_disable_metric_set;
3003 dev_priv->perf.oa.ops.oa_enable = gen8_oa_enable;
3004 dev_priv->perf.oa.ops.oa_disable = gen8_oa_disable;
3005 dev_priv->perf.oa.ops.read = gen8_oa_read;
3006 dev_priv->perf.oa.ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
3007
3008 dev_priv->perf.oa.oa_formats = gen8_plus_oa_formats;
3009
19f81df2
RB
3010 if (IS_GEN8(dev_priv)) {
3011 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x120;
3012 dev_priv->perf.oa.ctx_flexeu0_offset = 0x2ce;
155e941f
RB
3013
3014 dev_priv->perf.oa.timestamp_frequency = 12500000;
3015
19f81df2 3016 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<25);
19f81df2
RB
3017 } else if (IS_GEN9(dev_priv)) {
3018 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
3019 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
155e941f 3020
19f81df2
RB
3021 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
3022
701f8231
LL
3023 switch (dev_priv->info.platform) {
3024 case INTEL_BROXTON:
3025 case INTEL_GEMINILAKE:
155e941f 3026 dev_priv->perf.oa.timestamp_frequency = 19200000;
701f8231
LL
3027 break;
3028 case INTEL_SKYLAKE:
3029 case INTEL_KABYLAKE:
3030 dev_priv->perf.oa.timestamp_frequency = 12000000;
3031 break;
3032 default:
3033 /* Leave timestamp_frequency to 0 so we can
3034 * detect unsupported platforms.
3035 */
3036 break;
19f81df2
RB
3037 }
3038 }
19f81df2 3039 }
d7965152 3040
701f8231 3041 if (dev_priv->perf.oa.timestamp_frequency) {
19f81df2
RB
3042 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
3043 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3044 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
3045 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
d7965152 3046
19f81df2
RB
3047 INIT_LIST_HEAD(&dev_priv->perf.streams);
3048 mutex_init(&dev_priv->perf.lock);
19f81df2 3049 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
eec688e1 3050
155e941f
RB
3051 oa_sample_rate_hard_limit =
3052 dev_priv->perf.oa.timestamp_frequency / 2;
19f81df2 3053 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
ccdf6341 3054
19f81df2
RB
3055 dev_priv->perf.initialized = true;
3056 }
eec688e1
RB
3057}
3058
16d98b31
RB
3059/**
3060 * i915_perf_fini - Counter part to i915_perf_init()
3061 * @dev_priv: i915 device instance
3062 */
eec688e1
RB
3063void i915_perf_fini(struct drm_i915_private *dev_priv)
3064{
3065 if (!dev_priv->perf.initialized)
3066 return;
3067
ccdf6341
RB
3068 unregister_sysctl_table(dev_priv->perf.sysctl_header);
3069
d7965152 3070 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
19f81df2 3071
eec688e1
RB
3072 dev_priv->perf.initialized = false;
3073}