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