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