drm/i915/perf: implement active wait for noa configurations
[linux-2.6-block.git] / drivers / gpu / drm / i915 / i915_perf.c
CommitLineData
eec688e1
RB
1/*
2 * Copyright © 2015-2016 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Robert Bragg <robert@sixbynine.org>
25 */
26
7abbd8d6
RB
27
28/**
16d98b31 29 * DOC: i915 Perf Overview
7abbd8d6
RB
30 *
31 * Gen graphics supports a large number of performance counters that can help
32 * driver and application developers understand and optimize their use of the
33 * GPU.
34 *
35 * This i915 perf interface enables userspace to configure and open a file
36 * descriptor representing a stream of GPU metrics which can then be read() as
37 * a stream of sample records.
38 *
39 * The interface is particularly suited to exposing buffered metrics that are
40 * captured by DMA from the GPU, unsynchronized with and unrelated to the CPU.
41 *
42 * Streams representing a single context are accessible to applications with a
43 * corresponding drm file descriptor, such that OpenGL can use the interface
44 * without special privileges. Access to system-wide metrics requires root
45 * privileges by default, unless changed via the dev.i915.perf_event_paranoid
46 * sysctl option.
47 *
16d98b31
RB
48 */
49
50/**
51 * DOC: i915 Perf History and Comparison with Core Perf
7abbd8d6
RB
52 *
53 * The interface was initially inspired by the core Perf infrastructure but
54 * some notable differences are:
55 *
56 * i915 perf file descriptors represent a "stream" instead of an "event"; where
57 * a perf event primarily corresponds to a single 64bit value, while a stream
58 * might sample sets of tightly-coupled counters, depending on the
59 * configuration. For example the Gen OA unit isn't designed to support
60 * orthogonal configurations of individual counters; it's configured for a set
61 * of related counters. Samples for an i915 perf stream capturing OA metrics
62 * will include a set of counter values packed in a compact HW specific format.
63 * The OA unit supports a number of different packing formats which can be
64 * selected by the user opening the stream. Perf has support for grouping
65 * events, but each event in the group is configured, validated and
66 * authenticated individually with separate system calls.
67 *
68 * i915 perf stream configurations are provided as an array of u64 (key,value)
69 * pairs, instead of a fixed struct with multiple miscellaneous config members,
70 * interleaved with event-type specific members.
71 *
72 * i915 perf doesn't support exposing metrics via an mmap'd circular buffer.
73 * The supported metrics are being written to memory by the GPU unsynchronized
74 * with the CPU, using HW specific packing formats for counter sets. Sometimes
75 * the constraints on HW configuration require reports to be filtered before it
76 * would be acceptable to expose them to unprivileged applications - to hide
77 * the metrics of other processes/contexts. For these use cases a read() based
78 * interface is a good fit, and provides an opportunity to filter data as it
79 * gets copied from the GPU mapped buffers to userspace buffers.
80 *
81 *
16d98b31
RB
82 * Issues hit with first prototype based on Core Perf
83 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
7abbd8d6
RB
84 *
85 * The first prototype of this driver was based on the core perf
86 * infrastructure, and while we did make that mostly work, with some changes to
87 * perf, we found we were breaking or working around too many assumptions baked
88 * into perf's currently cpu centric design.
89 *
90 * In the end we didn't see a clear benefit to making perf's implementation and
91 * interface more complex by changing design assumptions while we knew we still
92 * wouldn't be able to use any existing perf based userspace tools.
93 *
94 * Also considering the Gen specific nature of the Observability hardware and
95 * how userspace will sometimes need to combine i915 perf OA metrics with
96 * side-band OA data captured via MI_REPORT_PERF_COUNT commands; we're
97 * expecting the interface to be used by a platform specific userspace such as
98 * OpenGL or tools. This is to say; we aren't inherently missing out on having
99 * a standard vendor/architecture agnostic interface by not using perf.
100 *
101 *
102 * For posterity, in case we might re-visit trying to adapt core perf to be
103 * better suited to exposing i915 metrics these were the main pain points we
104 * hit:
105 *
106 * - The perf based OA PMU driver broke some significant design assumptions:
107 *
108 * Existing perf pmus are used for profiling work on a cpu and we were
109 * introducing the idea of _IS_DEVICE pmus with different security
110 * implications, the need to fake cpu-related data (such as user/kernel
111 * registers) to fit with perf's current design, and adding _DEVICE records
112 * as a way to forward device-specific status records.
113 *
114 * The OA unit writes reports of counters into a circular buffer, without
115 * involvement from the CPU, making our PMU driver the first of a kind.
116 *
117 * Given the way we were periodically forward data from the GPU-mapped, OA
118 * buffer to perf's buffer, those bursts of sample writes looked to perf like
119 * we were sampling too fast and so we had to subvert its throttling checks.
120 *
121 * Perf supports groups of counters and allows those to be read via
122 * transactions internally but transactions currently seem designed to be
123 * explicitly initiated from the cpu (say in response to a userspace read())
124 * and while we could pull a report out of the OA buffer we can't
125 * trigger a report from the cpu on demand.
126 *
127 * Related to being report based; the OA counters are configured in HW as a
128 * set while perf generally expects counter configurations to be orthogonal.
129 * Although counters can be associated with a group leader as they are
130 * opened, there's no clear precedent for being able to provide group-wide
131 * configuration attributes (for example we want to let userspace choose the
132 * OA unit report format used to capture all counters in a set, or specify a
133 * GPU context to filter metrics on). We avoided using perf's grouping
134 * feature and forwarded OA reports to userspace via perf's 'raw' sample
135 * field. This suited our userspace well considering how coupled the counters
136 * are when dealing with normalizing. It would be inconvenient to split
137 * counters up into separate events, only to require userspace to recombine
138 * them. For Mesa it's also convenient to be forwarded raw, periodic reports
139 * for combining with the side-band raw reports it captures using
140 * MI_REPORT_PERF_COUNT commands.
141 *
16d98b31 142 * - As a side note on perf's grouping feature; there was also some concern
7abbd8d6
RB
143 * that using PERF_FORMAT_GROUP as a way to pack together counter values
144 * would quite drastically inflate our sample sizes, which would likely
145 * lower the effective sampling resolutions we could use when the available
146 * memory bandwidth is limited.
147 *
148 * With the OA unit's report formats, counters are packed together as 32
149 * or 40bit values, with the largest report size being 256 bytes.
150 *
151 * PERF_FORMAT_GROUP values are 64bit, but there doesn't appear to be a
152 * documented ordering to the values, implying PERF_FORMAT_ID must also be
153 * used to add a 64bit ID before each value; giving 16 bytes per counter.
154 *
155 * Related to counter orthogonality; we can't time share the OA unit, while
156 * event scheduling is a central design idea within perf for allowing
157 * userspace to open + enable more events than can be configured in HW at any
158 * one time. The OA unit is not designed to allow re-configuration while in
159 * use. We can't reconfigure the OA unit without losing internal OA unit
160 * state which we can't access explicitly to save and restore. Reconfiguring
161 * the OA unit is also relatively slow, involving ~100 register writes. From
162 * userspace Mesa also depends on a stable OA configuration when emitting
163 * MI_REPORT_PERF_COUNT commands and importantly the OA unit can't be
164 * disabled while there are outstanding MI_RPC commands lest we hang the
165 * command streamer.
166 *
167 * The contents of sample records aren't extensible by device drivers (i.e.
168 * the sample_type bits). As an example; Sourab Gupta had been looking to
169 * attach GPU timestamps to our OA samples. We were shoehorning OA reports
170 * into sample records by using the 'raw' field, but it's tricky to pack more
171 * than one thing into this field because events/core.c currently only lets a
172 * pmu give a single raw data pointer plus len which will be copied into the
173 * ring buffer. To include more than the OA report we'd have to copy the
174 * report into an intermediate larger buffer. I'd been considering allowing a
175 * vector of data+len values to be specified for copying the raw data, but
176 * it felt like a kludge to being using the raw field for this purpose.
177 *
178 * - It felt like our perf based PMU was making some technical compromises
179 * just for the sake of using perf:
180 *
181 * perf_event_open() requires events to either relate to a pid or a specific
182 * cpu core, while our device pmu related to neither. Events opened with a
183 * pid will be automatically enabled/disabled according to the scheduling of
184 * that process - so not appropriate for us. When an event is related to a
185 * cpu id, perf ensures pmu methods will be invoked via an inter process
186 * interrupt on that core. To avoid invasive changes our userspace opened OA
187 * perf events for a specific cpu. This was workable but it meant the
188 * majority of the OA driver ran in atomic context, including all OA report
189 * forwarding, which wasn't really necessary in our case and seems to make
190 * our locking requirements somewhat complex as we handled the interaction
191 * with the rest of the i915 driver.
192 */
193
eec688e1 194#include <linux/anon_inodes.h>
d7965152 195#include <linux/sizes.h>
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
347 * @ctx_handle: A gem ctx handle for use with @single_context
348 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
349 * @oa_format: An OA unit HW report format
350 * @oa_periodic: Whether to enable periodic OA unit sampling
351 * @oa_period_exponent: The OA unit sampling period is derived from this
9a61363a 352 * @engine: The engine (typically rcs0) being monitored by the OA unit
16d98b31
RB
353 *
354 * As read_properties_unlocked() enumerates and validates the properties given
355 * to open a stream of metrics the configuration is built up in the structure
356 * which starts out zero initialized.
357 */
eec688e1
RB
358struct perf_open_properties {
359 u32 sample_flags;
360
361 u64 single_context:1;
362 u64 ctx_handle;
d7965152
RB
363
364 /* OA sampling state */
365 int metrics_set;
366 int oa_format;
367 bool oa_periodic;
368 int oa_period_exponent;
9a61363a
LL
369
370 struct intel_engine_cs *engine;
d7965152
RB
371};
372
6a45008a
LL
373struct i915_oa_config_bo {
374 struct llist_node node;
375
376 struct i915_oa_config *oa_config;
377 struct i915_vma *vma;
378};
379
a37f08a8
UNR
380static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer);
381
6a45008a 382void i915_oa_config_release(struct kref *ref)
f89823c2 383{
6a45008a
LL
384 struct i915_oa_config *oa_config =
385 container_of(ref, typeof(*oa_config), ref);
386
f89823c2
LL
387 if (!PTR_ERR(oa_config->flex_regs))
388 kfree(oa_config->flex_regs);
389 if (!PTR_ERR(oa_config->b_counter_regs))
390 kfree(oa_config->b_counter_regs);
391 if (!PTR_ERR(oa_config->mux_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:
1734 __i915_vma_unpin(vma);
1735err_unref:
1736 i915_gem_object_put(bo);
1737 return ret;
1738}
1739
8f8b1171 1740static void config_oa_regs(struct intel_uncore *uncore,
d7965152 1741 const struct i915_oa_reg *regs,
701f8231 1742 u32 n_regs)
d7965152 1743{
701f8231 1744 u32 i;
d7965152
RB
1745
1746 for (i = 0; i < n_regs; i++) {
1747 const struct i915_oa_reg *reg = regs + i;
1748
8f8b1171 1749 intel_uncore_write(uncore, reg->addr, reg->value);
d7965152
RB
1750 }
1751}
1752
14bfcd3e 1753static void delay_after_mux(void)
d7965152 1754{
14bfcd3e
LL
1755 /*
1756 * It apparently takes a fairly long time for a new MUX
d7965152
RB
1757 * configuration to be be applied after these register writes.
1758 * This delay duration was derived empirically based on the
1759 * render_basic config but hopefully it covers the maximum
1760 * configuration latency.
1761 *
1762 * As a fallback, the checks in _append_oa_reports() to skip
1763 * invalid OA reports do also seem to work to discard reports
1764 * generated before this config has completed - albeit not
1765 * silently.
1766 *
1767 * Unfortunately this is essentially a magic number, since we
1768 * don't currently know of a reliable mechanism for predicting
1769 * how long the MUX config will take to apply and besides
1770 * seeing invalid reports we don't know of a reliable way to
1771 * explicitly check that the MUX config has landed.
1772 *
1773 * It's even possible we've miss characterized the underlying
1774 * problem - it just seems like the simplest explanation why
1775 * a delay at this location would mitigate any invalid reports.
1776 */
1777 usleep_range(15000, 20000);
14bfcd3e
LL
1778}
1779
1780static int hsw_enable_metric_set(struct i915_perf_stream *stream)
1781{
52111c46 1782 struct intel_uncore *uncore = stream->uncore;
14bfcd3e
LL
1783 const struct i915_oa_config *oa_config = stream->oa_config;
1784
1785 /*
1786 * PRM:
1787 *
1788 * OA unit is using “crclk” for its functionality. When trunk
1789 * level clock gating takes place, OA clock would be gated,
1790 * unable to count the events from non-render clock domain.
1791 * Render clock gating must be disabled when OA is enabled to
1792 * count the events from non-render domain. Unit level clock
1793 * gating for RCS should also be disabled.
1794 */
8f8b1171
CW
1795 intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
1796 GEN7_DOP_CLOCK_GATE_ENABLE, 0);
1797 intel_uncore_rmw(uncore, GEN6_UCGCTL1,
1798 0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
14bfcd3e 1799
8f8b1171 1800 config_oa_regs(uncore, oa_config->mux_regs, oa_config->mux_regs_len);
14bfcd3e 1801 delay_after_mux();
d7965152 1802
8f8b1171 1803 config_oa_regs(uncore, oa_config->b_counter_regs,
701f8231 1804 oa_config->b_counter_regs_len);
d7965152
RB
1805
1806 return 0;
1807}
1808
a37f08a8 1809static void hsw_disable_metric_set(struct i915_perf_stream *stream)
d7965152 1810{
52111c46 1811 struct intel_uncore *uncore = stream->uncore;
a37f08a8 1812
8f8b1171
CW
1813 intel_uncore_rmw(uncore, GEN6_UCGCTL1,
1814 GEN6_CSUNIT_CLOCK_GATE_DISABLE, 0);
1815 intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
1816 0, GEN7_DOP_CLOCK_GATE_ENABLE);
d7965152 1817
8f8b1171 1818 intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
d7965152
RB
1819}
1820
a9877da2
CW
1821static u32 oa_config_flex_reg(const struct i915_oa_config *oa_config,
1822 i915_reg_t reg)
1823{
1824 u32 mmio = i915_mmio_reg_offset(reg);
1825 int i;
1826
1827 /*
1828 * This arbitrary default will select the 'EU FPU0 Pipeline
1829 * Active' event. In the future it's anticipated that there
1830 * will be an explicit 'No Event' we can select, but not yet...
1831 */
1832 if (!oa_config)
1833 return 0;
1834
1835 for (i = 0; i < oa_config->flex_regs_len; i++) {
1836 if (i915_mmio_reg_offset(oa_config->flex_regs[i].addr) == mmio)
1837 return oa_config->flex_regs[i].value;
1838 }
1839
1840 return 0;
1841}
19f81df2
RB
1842/*
1843 * NB: It must always remain pointer safe to run this even if the OA unit
1844 * has been disabled.
1845 *
1846 * It's fine to put out-of-date values into these per-context registers
1847 * in the case that the OA unit has been disabled.
1848 */
b146e5ef 1849static void
7dc56af5
CW
1850gen8_update_reg_state_unlocked(const struct intel_context *ce,
1851 const struct i915_perf_stream *stream)
19f81df2 1852{
8f8b1171
CW
1853 u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
1854 u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
19f81df2 1855 /* The MMIO offsets for Flex EU registers aren't contiguous */
35ab4fd2
LL
1856 i915_reg_t flex_regs[] = {
1857 EU_PERF_CNTL0,
1858 EU_PERF_CNTL1,
1859 EU_PERF_CNTL2,
1860 EU_PERF_CNTL3,
1861 EU_PERF_CNTL4,
1862 EU_PERF_CNTL5,
1863 EU_PERF_CNTL6,
19f81df2 1864 };
7dc56af5 1865 u32 *reg_state = ce->lrc_reg_state;
19f81df2
RB
1866 int i;
1867
7dc56af5 1868 reg_state[ctx_oactxctrl + 1] =
a37f08a8
UNR
1869 (stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
1870 (stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
7dc56af5 1871 GEN8_OA_COUNTER_RESUME;
19f81df2 1872
7dc56af5
CW
1873 for (i = 0; i < ARRAY_SIZE(flex_regs); i++)
1874 reg_state[ctx_flexeu0 + i * 2 + 1] =
1875 oa_config_flex_reg(stream->oa_config, flex_regs[i]);
ec431eae 1876
8f8b1171
CW
1877 reg_state[CTX_R_PWR_CLK_STATE] =
1878 intel_sseu_make_rpcs(ce->engine->i915, &ce->sseu);
19f81df2
RB
1879}
1880
a9877da2
CW
1881struct flex {
1882 i915_reg_t reg;
1883 u32 offset;
1884 u32 value;
1885};
1886
1887static int
1888gen8_store_flex(struct i915_request *rq,
1889 struct intel_context *ce,
1890 const struct flex *flex, unsigned int count)
1891{
1892 u32 offset;
1893 u32 *cs;
1894
1895 cs = intel_ring_begin(rq, 4 * count);
1896 if (IS_ERR(cs))
1897 return PTR_ERR(cs);
1898
1899 offset = i915_ggtt_offset(ce->state) + LRC_STATE_PN * PAGE_SIZE;
1900 do {
1901 *cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
7dc56af5 1902 *cs++ = offset + flex->offset * sizeof(u32);
a9877da2
CW
1903 *cs++ = 0;
1904 *cs++ = flex->value;
1905 } while (flex++, --count);
1906
1907 intel_ring_advance(rq, cs);
1908
1909 return 0;
1910}
1911
1912static int
1913gen8_load_flex(struct i915_request *rq,
1914 struct intel_context *ce,
1915 const struct flex *flex, unsigned int count)
1916{
1917 u32 *cs;
1918
1919 GEM_BUG_ON(!count || count > 63);
1920
1921 cs = intel_ring_begin(rq, 2 * count + 2);
1922 if (IS_ERR(cs))
1923 return PTR_ERR(cs);
1924
1925 *cs++ = MI_LOAD_REGISTER_IMM(count);
1926 do {
1927 *cs++ = i915_mmio_reg_offset(flex->reg);
1928 *cs++ = flex->value;
1929 } while (flex++, --count);
1930 *cs++ = MI_NOOP;
1931
1932 intel_ring_advance(rq, cs);
1933
1934 return 0;
1935}
1936
1937static int gen8_modify_context(struct intel_context *ce,
1938 const struct flex *flex, unsigned int count)
1939{
1940 struct i915_request *rq;
1941 int err;
1942
1943 lockdep_assert_held(&ce->pin_mutex);
1944
1945 rq = i915_request_create(ce->engine->kernel_context);
1946 if (IS_ERR(rq))
1947 return PTR_ERR(rq);
1948
1949 /* Serialise with the remote context */
1950 err = intel_context_prepare_remote_request(ce, rq);
1951 if (err == 0)
1952 err = gen8_store_flex(rq, ce, flex, count);
1953
1954 i915_request_add(rq);
1955 return err;
1956}
1957
1958static int gen8_modify_self(struct intel_context *ce,
1959 const struct flex *flex, unsigned int count)
1960{
1961 struct i915_request *rq;
1962 int err;
1963
1964 rq = i915_request_create(ce);
1965 if (IS_ERR(rq))
1966 return PTR_ERR(rq);
1967
1968 err = gen8_load_flex(rq, ce, flex, count);
1969
1970 i915_request_add(rq);
1971 return err;
1972}
1973
5cca5038
CW
1974static int gen8_configure_context(struct i915_gem_context *ctx,
1975 struct flex *flex, unsigned int count)
1976{
1977 struct i915_gem_engines_iter it;
1978 struct intel_context *ce;
1979 int err = 0;
1980
1981 for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
1982 GEM_BUG_ON(ce == ce->engine->kernel_context);
1983
1984 if (ce->engine->class != RENDER_CLASS)
1985 continue;
1986
1987 err = intel_context_lock_pinned(ce);
1988 if (err)
1989 break;
1990
1991 flex->value = intel_sseu_make_rpcs(ctx->i915, &ce->sseu);
1992
1993 /* Otherwise OA settings will be set upon first use */
1994 if (intel_context_is_pinned(ce))
1995 err = gen8_modify_context(ce, flex, count);
1996
1997 intel_context_unlock_pinned(ce);
1998 if (err)
1999 break;
2000 }
2001 i915_gem_context_unlock_engines(ctx);
2002
2003 return err;
2004}
2005
19f81df2
RB
2006/*
2007 * Manages updating the per-context aspects of the OA stream
2008 * configuration across all contexts.
2009 *
2010 * The awkward consideration here is that OACTXCONTROL controls the
2011 * exponent for periodic sampling which is primarily used for system
2012 * wide profiling where we'd like a consistent sampling period even in
2013 * the face of context switches.
2014 *
2015 * Our approach of updating the register state context (as opposed to
2016 * say using a workaround batch buffer) ensures that the hardware
2017 * won't automatically reload an out-of-date timer exponent even
2018 * transiently before a WA BB could be parsed.
2019 *
2020 * This function needs to:
2021 * - Ensure the currently running context's per-context OA state is
2022 * updated
2023 * - Ensure that all existing contexts will have the correct per-context
2024 * OA state if they are scheduled for use.
2025 * - Ensure any new contexts will be initialized with the correct
2026 * per-context OA state.
2027 *
2028 * Note: it's only the RCS/Render context that has any OA state.
2029 */
a37f08a8 2030static int gen8_configure_all_contexts(struct i915_perf_stream *stream,
41d3fdcd 2031 const struct i915_oa_config *oa_config)
19f81df2 2032{
8f8b1171 2033 struct drm_i915_private *i915 = stream->perf->i915;
a9877da2 2034 /* The MMIO offsets for Flex EU registers aren't contiguous */
8f8b1171 2035 const u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
7dc56af5 2036#define ctx_flexeuN(N) (ctx_flexeu0 + 2 * (N) + 1)
a9877da2
CW
2037 struct flex regs[] = {
2038 {
2039 GEN8_R_PWR_CLK_STATE,
2040 CTX_R_PWR_CLK_STATE,
2041 },
2042 {
2043 GEN8_OACTXCONTROL,
8f8b1171 2044 stream->perf->ctx_oactxctrl_offset + 1,
a37f08a8
UNR
2045 ((stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2046 (stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
a9877da2
CW
2047 GEN8_OA_COUNTER_RESUME)
2048 },
2049 { EU_PERF_CNTL0, ctx_flexeuN(0) },
2050 { EU_PERF_CNTL1, ctx_flexeuN(1) },
2051 { EU_PERF_CNTL2, ctx_flexeuN(2) },
2052 { EU_PERF_CNTL3, ctx_flexeuN(3) },
2053 { EU_PERF_CNTL4, ctx_flexeuN(4) },
2054 { EU_PERF_CNTL5, ctx_flexeuN(5) },
2055 { EU_PERF_CNTL6, ctx_flexeuN(6) },
2056 };
2057#undef ctx_flexeuN
2058 struct intel_engine_cs *engine;
a4e7ccda
CW
2059 struct i915_gem_context *ctx, *cn;
2060 int i, err;
19f81df2 2061
a9877da2
CW
2062 for (i = 2; i < ARRAY_SIZE(regs); i++)
2063 regs[i].value = oa_config_flex_reg(oa_config, regs[i].reg);
2064
a4c969d1 2065 lockdep_assert_held(&stream->perf->lock);
19f81df2 2066
19f81df2
RB
2067 /*
2068 * The OA register config is setup through the context image. This image
2069 * might be written to by the GPU on context switch (in particular on
2070 * lite-restore). This means we can't safely update a context's image,
2071 * if this context is scheduled/submitted to run on the GPU.
2072 *
2073 * We could emit the OA register config through the batch buffer but
2074 * this might leave small interval of time where the OA unit is
2075 * configured at an invalid sampling period.
2076 *
a9877da2
CW
2077 * Note that since we emit all requests from a single ring, there
2078 * is still an implicit global barrier here that may cause a high
2079 * priority context to wait for an otherwise independent low priority
2080 * context. Contexts idle at the time of reconfiguration are not
2081 * trapped behind the barrier.
19f81df2 2082 */
a4e7ccda
CW
2083 spin_lock(&i915->gem.contexts.lock);
2084 list_for_each_entry_safe(ctx, cn, &i915->gem.contexts.list, link) {
a9877da2
CW
2085 if (ctx == i915->kernel_context)
2086 continue;
2087
a4e7ccda
CW
2088 if (!kref_get_unless_zero(&ctx->ref))
2089 continue;
2090
2091 spin_unlock(&i915->gem.contexts.lock);
2092
5cca5038 2093 err = gen8_configure_context(ctx, regs, ARRAY_SIZE(regs));
a4e7ccda
CW
2094 if (err) {
2095 i915_gem_context_put(ctx);
a9877da2 2096 return err;
a4e7ccda
CW
2097 }
2098
2099 spin_lock(&i915->gem.contexts.lock);
2100 list_safe_reset_next(ctx, cn, link);
2101 i915_gem_context_put(ctx);
19f81df2 2102 }
a4e7ccda 2103 spin_unlock(&i915->gem.contexts.lock);
19f81df2 2104
722f3de3 2105 /*
a9877da2
CW
2106 * After updating all other contexts, we need to modify ourselves.
2107 * If we don't modify the kernel_context, we do not get events while
2108 * idle.
722f3de3 2109 */
750e76b4 2110 for_each_uabi_engine(engine, i915) {
a9877da2 2111 struct intel_context *ce = engine->kernel_context;
722f3de3 2112
a9877da2
CW
2113 if (engine->class != RENDER_CLASS)
2114 continue;
2115
2116 regs[0].value = intel_sseu_make_rpcs(i915, &ce->sseu);
2117
2118 err = gen8_modify_self(ce, regs, ARRAY_SIZE(regs));
2119 if (err)
2120 return err;
2121 }
722f3de3
TU
2122
2123 return 0;
19f81df2
RB
2124}
2125
5728de2f 2126static int gen8_enable_metric_set(struct i915_perf_stream *stream)
19f81df2 2127{
52111c46 2128 struct intel_uncore *uncore = stream->uncore;
5728de2f 2129 const struct i915_oa_config *oa_config = stream->oa_config;
701f8231 2130 int ret;
19f81df2
RB
2131
2132 /*
2133 * We disable slice/unslice clock ratio change reports on SKL since
2134 * they are too noisy. The HW generates a lot of redundant reports
2135 * where the ratio hasn't really changed causing a lot of redundant
2136 * work to processes and increasing the chances we'll hit buffer
2137 * overruns.
2138 *
2139 * Although we don't currently use the 'disable overrun' OABUFFER
2140 * feature it's worth noting that clock ratio reports have to be
2141 * disabled before considering to use that feature since the HW doesn't
2142 * correctly block these reports.
2143 *
2144 * Currently none of the high-level metrics we have depend on knowing
2145 * this ratio to normalize.
2146 *
2147 * Note: This register is not power context saved and restored, but
2148 * that's OK considering that we disable RC6 while the OA unit is
2149 * enabled.
2150 *
2151 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
2152 * be read back from automatically triggered reports, as part of the
2153 * RPT_ID field.
2154 */
8f8b1171
CW
2155 if (IS_GEN_RANGE(stream->perf->i915, 9, 11)) {
2156 intel_uncore_write(uncore, GEN8_OA_DEBUG,
2157 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2158 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
19f81df2
RB
2159 }
2160
2161 /*
2162 * Update all contexts prior writing the mux configurations as we need
2163 * to make sure all slices/subslices are ON before writing to NOA
2164 * registers.
2165 */
a37f08a8 2166 ret = gen8_configure_all_contexts(stream, oa_config);
19f81df2
RB
2167 if (ret)
2168 return ret;
2169
8f8b1171 2170 config_oa_regs(uncore, oa_config->mux_regs, oa_config->mux_regs_len);
14bfcd3e 2171 delay_after_mux();
701f8231 2172
8f8b1171 2173 config_oa_regs(uncore, oa_config->b_counter_regs,
701f8231 2174 oa_config->b_counter_regs_len);
19f81df2
RB
2175
2176 return 0;
2177}
2178
a37f08a8 2179static void gen8_disable_metric_set(struct i915_perf_stream *stream)
19f81df2 2180{
52111c46 2181 struct intel_uncore *uncore = stream->uncore;
a37f08a8 2182
19f81df2 2183 /* Reset all contexts' slices/subslices configurations. */
a37f08a8 2184 gen8_configure_all_contexts(stream, NULL);
28964cf2 2185
8f8b1171 2186 intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
19f81df2
RB
2187}
2188
a37f08a8 2189static void gen10_disable_metric_set(struct i915_perf_stream *stream)
95690a02 2190{
52111c46 2191 struct intel_uncore *uncore = stream->uncore;
a37f08a8 2192
95690a02 2193 /* Reset all contexts' slices/subslices configurations. */
a37f08a8 2194 gen8_configure_all_contexts(stream, NULL);
95690a02
LL
2195
2196 /* Make sure we disable noa to save power. */
8f8b1171 2197 intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
95690a02
LL
2198}
2199
5728de2f 2200static void gen7_oa_enable(struct i915_perf_stream *stream)
d7965152 2201{
52111c46 2202 struct intel_uncore *uncore = stream->uncore;
5728de2f 2203 struct i915_gem_context *ctx = stream->ctx;
a37f08a8
UNR
2204 u32 ctx_id = stream->specific_ctx_id;
2205 bool periodic = stream->periodic;
2206 u32 period_exponent = stream->period_exponent;
2207 u32 report_format = stream->oa_buffer.format;
11051303 2208
1bef3409
RB
2209 /*
2210 * Reset buf pointers so we don't forward reports from before now.
2211 *
2212 * Think carefully if considering trying to avoid this, since it
2213 * also ensures status flags and the buffer itself are cleared
2214 * in error paths, and we have checks for invalid reports based
2215 * on the assumption that certain fields are written to zeroed
2216 * memory which this helps maintains.
2217 */
a37f08a8 2218 gen7_init_oa_buffer(stream);
d7965152 2219
8f8b1171
CW
2220 intel_uncore_write(uncore, GEN7_OACONTROL,
2221 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
2222 (period_exponent <<
2223 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
2224 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
2225 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
2226 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
2227 GEN7_OACONTROL_ENABLE);
d7965152
RB
2228}
2229
5728de2f 2230static void gen8_oa_enable(struct i915_perf_stream *stream)
19f81df2 2231{
52111c46 2232 struct intel_uncore *uncore = stream->uncore;
a37f08a8 2233 u32 report_format = stream->oa_buffer.format;
19f81df2
RB
2234
2235 /*
2236 * Reset buf pointers so we don't forward reports from before now.
2237 *
2238 * Think carefully if considering trying to avoid this, since it
2239 * also ensures status flags and the buffer itself are cleared
2240 * in error paths, and we have checks for invalid reports based
2241 * on the assumption that certain fields are written to zeroed
2242 * memory which this helps maintains.
2243 */
a37f08a8 2244 gen8_init_oa_buffer(stream);
19f81df2
RB
2245
2246 /*
2247 * Note: we don't rely on the hardware to perform single context
2248 * filtering and instead filter on the cpu based on the context-id
2249 * field of reports
2250 */
8f8b1171
CW
2251 intel_uncore_write(uncore, GEN8_OACONTROL,
2252 (report_format << GEN8_OA_REPORT_FORMAT_SHIFT) |
2253 GEN8_OA_COUNTER_ENABLE);
19f81df2
RB
2254}
2255
16d98b31
RB
2256/**
2257 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
2258 * @stream: An i915 perf stream opened for OA metrics
2259 *
2260 * [Re]enables hardware periodic sampling according to the period configured
2261 * when opening the stream. This also starts a hrtimer that will periodically
2262 * check for data in the circular OA buffer for notifying userspace (e.g.
2263 * during a read() or poll()).
2264 */
d7965152
RB
2265static void i915_oa_stream_enable(struct i915_perf_stream *stream)
2266{
8f8b1171 2267 stream->perf->ops.oa_enable(stream);
d7965152 2268
a37f08a8
UNR
2269 if (stream->periodic)
2270 hrtimer_start(&stream->poll_check_timer,
d7965152
RB
2271 ns_to_ktime(POLL_PERIOD),
2272 HRTIMER_MODE_REL_PINNED);
2273}
2274
5728de2f 2275static void gen7_oa_disable(struct i915_perf_stream *stream)
d7965152 2276{
52111c46 2277 struct intel_uncore *uncore = stream->uncore;
5728de2f 2278
97a04e0d
DCS
2279 intel_uncore_write(uncore, GEN7_OACONTROL, 0);
2280 if (intel_wait_for_register(uncore,
e896d29a
CW
2281 GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
2282 50))
2283 DRM_ERROR("wait for OA to be disabled timed out\n");
d7965152
RB
2284}
2285
5728de2f 2286static void gen8_oa_disable(struct i915_perf_stream *stream)
19f81df2 2287{
52111c46 2288 struct intel_uncore *uncore = stream->uncore;
5728de2f 2289
97a04e0d
DCS
2290 intel_uncore_write(uncore, GEN8_OACONTROL, 0);
2291 if (intel_wait_for_register(uncore,
e896d29a
CW
2292 GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
2293 50))
2294 DRM_ERROR("wait for OA to be disabled timed out\n");
19f81df2
RB
2295}
2296
16d98b31
RB
2297/**
2298 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
2299 * @stream: An i915 perf stream opened for OA metrics
2300 *
2301 * Stops the OA unit from periodically writing counter reports into the
2302 * circular OA buffer. This also stops the hrtimer that periodically checks for
2303 * data in the circular OA buffer, for notifying userspace.
2304 */
d7965152
RB
2305static void i915_oa_stream_disable(struct i915_perf_stream *stream)
2306{
8f8b1171 2307 stream->perf->ops.oa_disable(stream);
d7965152 2308
a37f08a8
UNR
2309 if (stream->periodic)
2310 hrtimer_cancel(&stream->poll_check_timer);
d7965152
RB
2311}
2312
d7965152
RB
2313static const struct i915_perf_stream_ops i915_oa_stream_ops = {
2314 .destroy = i915_oa_stream_destroy,
2315 .enable = i915_oa_stream_enable,
2316 .disable = i915_oa_stream_disable,
2317 .wait_unlocked = i915_oa_wait_unlocked,
2318 .poll_wait = i915_oa_poll_wait,
2319 .read = i915_oa_read,
eec688e1
RB
2320};
2321
16d98b31
RB
2322/**
2323 * i915_oa_stream_init - validate combined props for OA stream and init
2324 * @stream: An i915 perf stream
2325 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
2326 * @props: The property state that configures stream (individually validated)
2327 *
2328 * While read_properties_unlocked() validates properties in isolation it
2329 * doesn't ensure that the combination necessarily makes sense.
2330 *
2331 * At this point it has been determined that userspace wants a stream of
2332 * OA metrics, but still we need to further validate the combined
2333 * properties are OK.
2334 *
2335 * If the configuration makes sense then we can allocate memory for
2336 * a circular OA buffer and apply the requested metric set configuration.
2337 *
2338 * Returns: zero on success or a negative error code.
2339 */
d7965152
RB
2340static int i915_oa_stream_init(struct i915_perf_stream *stream,
2341 struct drm_i915_perf_open_param *param,
2342 struct perf_open_properties *props)
2343{
8f8b1171 2344 struct i915_perf *perf = stream->perf;
d7965152
RB
2345 int format_size;
2346 int ret;
2347
9a61363a
LL
2348 if (!props->engine) {
2349 DRM_DEBUG("OA engine not specified\n");
2350 return -EINVAL;
2351 }
2352
2353 /*
2354 * If the sysfs metrics/ directory wasn't registered for some
442b8c06
RB
2355 * reason then don't let userspace try their luck with config
2356 * IDs
2357 */
8f8b1171 2358 if (!perf->metrics_kobj) {
7708550c 2359 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
442b8c06
RB
2360 return -EINVAL;
2361 }
2362
d7965152 2363 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
7708550c 2364 DRM_DEBUG("Only OA report sampling supported\n");
d7965152
RB
2365 return -EINVAL;
2366 }
2367
8f8b1171 2368 if (!perf->ops.enable_metric_set) {
7708550c 2369 DRM_DEBUG("OA unit not supported\n");
d7965152
RB
2370 return -ENODEV;
2371 }
2372
9a61363a
LL
2373 /*
2374 * To avoid the complexity of having to accurately filter
d7965152
RB
2375 * counter reports and marshal to the appropriate client
2376 * we currently only allow exclusive access
2377 */
8f8b1171 2378 if (perf->exclusive_stream) {
7708550c 2379 DRM_DEBUG("OA unit already in use\n");
d7965152
RB
2380 return -EBUSY;
2381 }
2382
d7965152 2383 if (!props->oa_format) {
7708550c 2384 DRM_DEBUG("OA report format not specified\n");
d7965152
RB
2385 return -EINVAL;
2386 }
2387
9a61363a 2388 stream->engine = props->engine;
52111c46 2389 stream->uncore = stream->engine->gt->uncore;
9a61363a 2390
d7965152
RB
2391 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2392
8f8b1171 2393 format_size = perf->oa_formats[props->oa_format].size;
d7965152
RB
2394
2395 stream->sample_flags |= SAMPLE_OA_REPORT;
2396 stream->sample_size += format_size;
2397
a37f08a8
UNR
2398 stream->oa_buffer.format_size = format_size;
2399 if (WARN_ON(stream->oa_buffer.format_size == 0))
d7965152
RB
2400 return -EINVAL;
2401
a37f08a8 2402 stream->oa_buffer.format =
8f8b1171 2403 perf->oa_formats[props->oa_format].format;
d7965152 2404
a37f08a8
UNR
2405 stream->periodic = props->oa_periodic;
2406 if (stream->periodic)
2407 stream->period_exponent = props->oa_period_exponent;
d7965152 2408
d7965152
RB
2409 if (stream->ctx) {
2410 ret = oa_get_render_ctx_id(stream);
9bd9be66
LL
2411 if (ret) {
2412 DRM_DEBUG("Invalid context id to filter with\n");
d7965152 2413 return ret;
9bd9be66 2414 }
d7965152
RB
2415 }
2416
daed3e44
LL
2417 ret = alloc_noa_wait(stream);
2418 if (ret) {
2419 DRM_DEBUG("Unable to allocate NOA wait batch buffer\n");
2420 goto err_noa_wait_alloc;
2421 }
2422
6a45008a
LL
2423 stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
2424 if (!stream->oa_config) {
9bd9be66 2425 DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set);
6a45008a 2426 ret = -EINVAL;
f89823c2 2427 goto err_config;
9bd9be66 2428 }
701f8231 2429
d7965152
RB
2430 /* PRM - observability performance counters:
2431 *
2432 * OACONTROL, performance counter enable, note:
2433 *
2434 * "When this bit is set, in order to have coherent counts,
2435 * RC6 power state and trunk clock gating must be disabled.
2436 * This can be achieved by programming MMIO registers as
2437 * 0xA094=0 and 0xA090[31]=1"
2438 *
2439 * In our case we are expecting that taking pm + FORCEWAKE
2440 * references will effectively disable RC6.
2441 */
a5efcde6 2442 intel_engine_pm_get(stream->engine);
52111c46 2443 intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
d7965152 2444
a37f08a8 2445 ret = alloc_oa_buffer(stream);
987f8c44 2446 if (ret)
2447 goto err_oa_buf_alloc;
2448
ec431eae 2449 stream->ops = &i915_oa_stream_ops;
8f8b1171 2450 perf->exclusive_stream = stream;
ec431eae 2451
8f8b1171 2452 ret = perf->ops.enable_metric_set(stream);
9bd9be66
LL
2453 if (ret) {
2454 DRM_DEBUG("Unable to enable metric set\n");
d7965152 2455 goto err_enable;
9bd9be66 2456 }
d7965152 2457
6a45008a
LL
2458 DRM_DEBUG("opening stream oa config uuid=%s\n",
2459 stream->oa_config->uuid);
2460
a37f08a8
UNR
2461 hrtimer_init(&stream->poll_check_timer,
2462 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2463 stream->poll_check_timer.function = oa_poll_check_timer_cb;
2464 init_waitqueue_head(&stream->poll_wq);
2465 spin_lock_init(&stream->oa_buffer.ptr_lock);
2466
d7965152
RB
2467 return 0;
2468
41d3fdcd 2469err_enable:
8f8b1171
CW
2470 perf->exclusive_stream = NULL;
2471 perf->ops.disable_metric_set(stream);
701f8231 2472
a37f08a8 2473 free_oa_buffer(stream);
d7965152
RB
2474
2475err_oa_buf_alloc:
6a45008a 2476 free_oa_configs(stream);
f89823c2 2477
52111c46 2478 intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
a5efcde6 2479 intel_engine_pm_put(stream->engine);
f89823c2
LL
2480
2481err_config:
daed3e44
LL
2482 free_noa_wait(stream);
2483
2484err_noa_wait_alloc:
d7965152
RB
2485 if (stream->ctx)
2486 oa_put_render_ctx_id(stream);
2487
2488 return ret;
2489}
2490
7dc56af5
CW
2491void i915_oa_init_reg_state(const struct intel_context *ce,
2492 const struct intel_engine_cs *engine)
19f81df2 2493{
28b6cb08 2494 struct i915_perf_stream *stream;
19f81df2 2495
dffa8feb
CW
2496 /* perf.exclusive_stream serialised by gen8_configure_all_contexts() */
2497 lockdep_assert_held(&ce->pin_mutex);
2498
8a68d464 2499 if (engine->class != RENDER_CLASS)
19f81df2
RB
2500 return;
2501
a37f08a8 2502 stream = engine->i915->perf.exclusive_stream;
701f8231 2503 if (stream)
7dc56af5 2504 gen8_update_reg_state_unlocked(ce, stream);
19f81df2
RB
2505}
2506
16d98b31
RB
2507/**
2508 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2509 * @stream: An i915 perf stream
2510 * @file: An i915 perf stream file
2511 * @buf: destination buffer given by userspace
2512 * @count: the number of bytes userspace wants to read
2513 * @ppos: (inout) file seek position (unused)
2514 *
2515 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2516 * ensure that if we've successfully copied any data then reporting that takes
2517 * precedence over any internal error status, so the data isn't lost.
2518 *
2519 * For example ret will be -ENOSPC whenever there is more buffered data than
2520 * can be copied to userspace, but that's only interesting if we weren't able
2521 * to copy some data because it implies the userspace buffer is too small to
2522 * receive a single record (and we never split records).
2523 *
2524 * Another case with ret == -EFAULT is more of a grey area since it would seem
2525 * like bad form for userspace to ask us to overrun its buffer, but the user
2526 * knows best:
2527 *
2528 * http://yarchive.net/comp/linux/partial_reads_writes.html
2529 *
2530 * Returns: The number of bytes copied or a negative error code on failure.
2531 */
eec688e1
RB
2532static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2533 struct file *file,
2534 char __user *buf,
2535 size_t count,
2536 loff_t *ppos)
2537{
2538 /* Note we keep the offset (aka bytes read) separate from any
2539 * error status so that the final check for whether we return
2540 * the bytes read with a higher precedence than any error (see
2541 * comment below) doesn't need to be handled/duplicated in
2542 * stream->ops->read() implementations.
2543 */
2544 size_t offset = 0;
2545 int ret = stream->ops->read(stream, buf, count, &offset);
2546
eec688e1
RB
2547 return offset ?: (ret ?: -EAGAIN);
2548}
2549
16d98b31
RB
2550/**
2551 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2552 * @file: An i915 perf stream file
2553 * @buf: destination buffer given by userspace
2554 * @count: the number of bytes userspace wants to read
2555 * @ppos: (inout) file seek position (unused)
2556 *
2557 * The entry point for handling a read() on a stream file descriptor from
2558 * userspace. Most of the work is left to the i915_perf_read_locked() and
2559 * &i915_perf_stream_ops->read but to save having stream implementations (of
2560 * which we might have multiple later) we handle blocking read here.
2561 *
2562 * We can also consistently treat trying to read from a disabled stream
2563 * as an IO error so implementations can assume the stream is enabled
2564 * while reading.
2565 *
2566 * Returns: The number of bytes copied or a negative error code on failure.
2567 */
eec688e1
RB
2568static ssize_t i915_perf_read(struct file *file,
2569 char __user *buf,
2570 size_t count,
2571 loff_t *ppos)
2572{
2573 struct i915_perf_stream *stream = file->private_data;
8f8b1171 2574 struct i915_perf *perf = stream->perf;
eec688e1
RB
2575 ssize_t ret;
2576
d7965152
RB
2577 /* To ensure it's handled consistently we simply treat all reads of a
2578 * disabled stream as an error. In particular it might otherwise lead
2579 * to a deadlock for blocking file descriptors...
2580 */
2581 if (!stream->enabled)
2582 return -EIO;
2583
eec688e1 2584 if (!(file->f_flags & O_NONBLOCK)) {
d7965152
RB
2585 /* There's the small chance of false positives from
2586 * stream->ops->wait_unlocked.
2587 *
2588 * E.g. with single context filtering since we only wait until
2589 * oabuffer has >= 1 report we don't immediately know whether
2590 * any reports really belong to the current context
eec688e1
RB
2591 */
2592 do {
2593 ret = stream->ops->wait_unlocked(stream);
2594 if (ret)
2595 return ret;
2596
8f8b1171 2597 mutex_lock(&perf->lock);
eec688e1
RB
2598 ret = i915_perf_read_locked(stream, file,
2599 buf, count, ppos);
8f8b1171 2600 mutex_unlock(&perf->lock);
eec688e1
RB
2601 } while (ret == -EAGAIN);
2602 } else {
8f8b1171 2603 mutex_lock(&perf->lock);
eec688e1 2604 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
8f8b1171 2605 mutex_unlock(&perf->lock);
eec688e1
RB
2606 }
2607
a9a08845 2608 /* We allow the poll checking to sometimes report false positive EPOLLIN
26ebd9c7
RB
2609 * events where we might actually report EAGAIN on read() if there's
2610 * not really any data available. In this situation though we don't
a9a08845 2611 * want to enter a busy loop between poll() reporting a EPOLLIN event
26ebd9c7
RB
2612 * and read() returning -EAGAIN. Clearing the oa.pollin state here
2613 * effectively ensures we back off until the next hrtimer callback
a9a08845 2614 * before reporting another EPOLLIN event.
26ebd9c7
RB
2615 */
2616 if (ret >= 0 || ret == -EAGAIN) {
d7965152
RB
2617 /* Maybe make ->pollin per-stream state if we support multiple
2618 * concurrent streams in the future.
2619 */
a37f08a8 2620 stream->pollin = false;
d7965152
RB
2621 }
2622
eec688e1
RB
2623 return ret;
2624}
2625
d7965152
RB
2626static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
2627{
a37f08a8
UNR
2628 struct i915_perf_stream *stream =
2629 container_of(hrtimer, typeof(*stream), poll_check_timer);
d7965152 2630
a37f08a8
UNR
2631 if (oa_buffer_check_unlocked(stream)) {
2632 stream->pollin = true;
2633 wake_up(&stream->poll_wq);
d7965152
RB
2634 }
2635
2636 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
2637
2638 return HRTIMER_RESTART;
2639}
2640
16d98b31
RB
2641/**
2642 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
16d98b31
RB
2643 * @stream: An i915 perf stream
2644 * @file: An i915 perf stream file
2645 * @wait: poll() state table
2646 *
2647 * For handling userspace polling on an i915 perf stream, this calls through to
2648 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
2649 * will be woken for new stream data.
2650 *
8f8b1171 2651 * Note: The &perf->lock mutex has been taken to serialize
16d98b31
RB
2652 * with any non-file-operation driver hooks.
2653 *
2654 * Returns: any poll events that are ready without sleeping
2655 */
8f8b1171
CW
2656static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
2657 struct file *file,
2658 poll_table *wait)
eec688e1 2659{
afc9a42b 2660 __poll_t events = 0;
eec688e1
RB
2661
2662 stream->ops->poll_wait(stream, file, wait);
2663
d7965152
RB
2664 /* Note: we don't explicitly check whether there's something to read
2665 * here since this path may be very hot depending on what else
2666 * userspace is polling, or on the timeout in use. We rely solely on
2667 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
2668 * samples to read.
2669 */
a37f08a8 2670 if (stream->pollin)
a9a08845 2671 events |= EPOLLIN;
eec688e1 2672
d7965152 2673 return events;
eec688e1
RB
2674}
2675
16d98b31
RB
2676/**
2677 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
2678 * @file: An i915 perf stream file
2679 * @wait: poll() state table
2680 *
2681 * For handling userspace polling on an i915 perf stream, this ensures
2682 * poll_wait() gets called with a wait queue that will be woken for new stream
2683 * data.
2684 *
2685 * Note: Implementation deferred to i915_perf_poll_locked()
2686 *
2687 * Returns: any poll events that are ready without sleeping
2688 */
afc9a42b 2689static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
eec688e1
RB
2690{
2691 struct i915_perf_stream *stream = file->private_data;
8f8b1171 2692 struct i915_perf *perf = stream->perf;
afc9a42b 2693 __poll_t ret;
eec688e1 2694
8f8b1171
CW
2695 mutex_lock(&perf->lock);
2696 ret = i915_perf_poll_locked(stream, file, wait);
2697 mutex_unlock(&perf->lock);
eec688e1
RB
2698
2699 return ret;
2700}
2701
16d98b31
RB
2702/**
2703 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
2704 * @stream: A disabled i915 perf stream
2705 *
2706 * [Re]enables the associated capture of data for this stream.
2707 *
2708 * If a stream was previously enabled then there's currently no intention
2709 * to provide userspace any guarantee about the preservation of previously
2710 * buffered data.
2711 */
eec688e1
RB
2712static void i915_perf_enable_locked(struct i915_perf_stream *stream)
2713{
2714 if (stream->enabled)
2715 return;
2716
2717 /* Allow stream->ops->enable() to refer to this */
2718 stream->enabled = true;
2719
2720 if (stream->ops->enable)
2721 stream->ops->enable(stream);
2722}
2723
16d98b31
RB
2724/**
2725 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
2726 * @stream: An enabled i915 perf stream
2727 *
2728 * Disables the associated capture of data for this stream.
2729 *
2730 * The intention is that disabling an re-enabling a stream will ideally be
2731 * cheaper than destroying and re-opening a stream with the same configuration,
2732 * though there are no formal guarantees about what state or buffered data
2733 * must be retained between disabling and re-enabling a stream.
2734 *
2735 * Note: while a stream is disabled it's considered an error for userspace
2736 * to attempt to read from the stream (-EIO).
2737 */
eec688e1
RB
2738static void i915_perf_disable_locked(struct i915_perf_stream *stream)
2739{
2740 if (!stream->enabled)
2741 return;
2742
2743 /* Allow stream->ops->disable() to refer to this */
2744 stream->enabled = false;
2745
2746 if (stream->ops->disable)
2747 stream->ops->disable(stream);
2748}
2749
16d98b31
RB
2750/**
2751 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2752 * @stream: An i915 perf stream
2753 * @cmd: the ioctl request
2754 * @arg: the ioctl data
2755 *
8f8b1171 2756 * Note: The &perf->lock mutex has been taken to serialize
16d98b31
RB
2757 * with any non-file-operation driver hooks.
2758 *
2759 * Returns: zero on success or a negative error code. Returns -EINVAL for
2760 * an unknown ioctl request.
2761 */
eec688e1
RB
2762static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
2763 unsigned int cmd,
2764 unsigned long arg)
2765{
2766 switch (cmd) {
2767 case I915_PERF_IOCTL_ENABLE:
2768 i915_perf_enable_locked(stream);
2769 return 0;
2770 case I915_PERF_IOCTL_DISABLE:
2771 i915_perf_disable_locked(stream);
2772 return 0;
2773 }
2774
2775 return -EINVAL;
2776}
2777
16d98b31
RB
2778/**
2779 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2780 * @file: An i915 perf stream file
2781 * @cmd: the ioctl request
2782 * @arg: the ioctl data
2783 *
2784 * Implementation deferred to i915_perf_ioctl_locked().
2785 *
2786 * Returns: zero on success or a negative error code. Returns -EINVAL for
2787 * an unknown ioctl request.
2788 */
eec688e1
RB
2789static long i915_perf_ioctl(struct file *file,
2790 unsigned int cmd,
2791 unsigned long arg)
2792{
2793 struct i915_perf_stream *stream = file->private_data;
8f8b1171 2794 struct i915_perf *perf = stream->perf;
eec688e1
RB
2795 long ret;
2796
8f8b1171 2797 mutex_lock(&perf->lock);
eec688e1 2798 ret = i915_perf_ioctl_locked(stream, cmd, arg);
8f8b1171 2799 mutex_unlock(&perf->lock);
eec688e1
RB
2800
2801 return ret;
2802}
2803
16d98b31
RB
2804/**
2805 * i915_perf_destroy_locked - destroy an i915 perf stream
2806 * @stream: An i915 perf stream
2807 *
2808 * Frees all resources associated with the given i915 perf @stream, disabling
2809 * any associated data capture in the process.
2810 *
8f8b1171 2811 * Note: The &perf->lock mutex has been taken to serialize
16d98b31
RB
2812 * with any non-file-operation driver hooks.
2813 */
eec688e1
RB
2814static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
2815{
eec688e1
RB
2816 if (stream->enabled)
2817 i915_perf_disable_locked(stream);
2818
2819 if (stream->ops->destroy)
2820 stream->ops->destroy(stream);
2821
69df05e1 2822 if (stream->ctx)
5f09a9c8 2823 i915_gem_context_put(stream->ctx);
eec688e1
RB
2824
2825 kfree(stream);
2826}
2827
16d98b31
RB
2828/**
2829 * i915_perf_release - handles userspace close() of a stream file
2830 * @inode: anonymous inode associated with file
2831 * @file: An i915 perf stream file
2832 *
2833 * Cleans up any resources associated with an open i915 perf stream file.
2834 *
2835 * NB: close() can't really fail from the userspace point of view.
2836 *
2837 * Returns: zero on success or a negative error code.
2838 */
eec688e1
RB
2839static int i915_perf_release(struct inode *inode, struct file *file)
2840{
2841 struct i915_perf_stream *stream = file->private_data;
8f8b1171 2842 struct i915_perf *perf = stream->perf;
eec688e1 2843
8f8b1171 2844 mutex_lock(&perf->lock);
eec688e1 2845 i915_perf_destroy_locked(stream);
8f8b1171 2846 mutex_unlock(&perf->lock);
eec688e1 2847
a5af1df7 2848 /* Release the reference the perf stream kept on the driver. */
8f8b1171 2849 drm_dev_put(&perf->i915->drm);
a5af1df7 2850
eec688e1
RB
2851 return 0;
2852}
2853
2854
2855static const struct file_operations fops = {
2856 .owner = THIS_MODULE,
2857 .llseek = no_llseek,
2858 .release = i915_perf_release,
2859 .poll = i915_perf_poll,
2860 .read = i915_perf_read,
2861 .unlocked_ioctl = i915_perf_ioctl,
191f8960
LL
2862 /* Our ioctl have no arguments, so it's safe to use the same function
2863 * to handle 32bits compatibility.
2864 */
2865 .compat_ioctl = i915_perf_ioctl,
eec688e1
RB
2866};
2867
2868
16d98b31
RB
2869/**
2870 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
8f8b1171 2871 * @perf: i915 perf instance
16d98b31
RB
2872 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
2873 * @props: individually validated u64 property value pairs
2874 * @file: drm file
2875 *
2876 * See i915_perf_ioctl_open() for interface details.
2877 *
2878 * Implements further stream config validation and stream initialization on
8f8b1171 2879 * behalf of i915_perf_open_ioctl() with the &perf->lock mutex
16d98b31
RB
2880 * taken to serialize with any non-file-operation driver hooks.
2881 *
2882 * Note: at this point the @props have only been validated in isolation and
2883 * it's still necessary to validate that the combination of properties makes
2884 * sense.
2885 *
2886 * In the case where userspace is interested in OA unit metrics then further
2887 * config validation and stream initialization details will be handled by
2888 * i915_oa_stream_init(). The code here should only validate config state that
2889 * will be relevant to all stream types / backends.
2890 *
2891 * Returns: zero on success or a negative error code.
2892 */
eec688e1 2893static int
8f8b1171 2894i915_perf_open_ioctl_locked(struct i915_perf *perf,
eec688e1
RB
2895 struct drm_i915_perf_open_param *param,
2896 struct perf_open_properties *props,
2897 struct drm_file *file)
2898{
2899 struct i915_gem_context *specific_ctx = NULL;
2900 struct i915_perf_stream *stream = NULL;
2901 unsigned long f_flags = 0;
19f81df2 2902 bool privileged_op = true;
eec688e1
RB
2903 int stream_fd;
2904 int ret;
2905
2906 if (props->single_context) {
2907 u32 ctx_handle = props->ctx_handle;
2908 struct drm_i915_file_private *file_priv = file->driver_priv;
2909
635f56c3
ID
2910 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
2911 if (!specific_ctx) {
2912 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
2913 ctx_handle);
2914 ret = -ENOENT;
eec688e1
RB
2915 goto err;
2916 }
2917 }
2918
19f81df2
RB
2919 /*
2920 * On Haswell the OA unit supports clock gating off for a specific
2921 * context and in this mode there's no visibility of metrics for the
2922 * rest of the system, which we consider acceptable for a
2923 * non-privileged client.
2924 *
2925 * For Gen8+ the OA unit no longer supports clock gating off for a
2926 * specific context and the kernel can't securely stop the counters
2927 * from updating as system-wide / global values. Even though we can
2928 * filter reports based on the included context ID we can't block
2929 * clients from seeing the raw / global counter values via
2930 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
2931 * enable the OA unit by default.
2932 */
8f8b1171 2933 if (IS_HASWELL(perf->i915) && specific_ctx)
19f81df2
RB
2934 privileged_op = false;
2935
ccdf6341
RB
2936 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
2937 * we check a dev.i915.perf_stream_paranoid sysctl option
2938 * to determine if it's ok to access system wide OA counters
2939 * without CAP_SYS_ADMIN privileges.
2940 */
19f81df2 2941 if (privileged_op &&
ccdf6341 2942 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
7708550c 2943 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
eec688e1
RB
2944 ret = -EACCES;
2945 goto err_ctx;
2946 }
2947
2948 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
2949 if (!stream) {
2950 ret = -ENOMEM;
2951 goto err_ctx;
2952 }
2953
8f8b1171 2954 stream->perf = perf;
eec688e1
RB
2955 stream->ctx = specific_ctx;
2956
d7965152
RB
2957 ret = i915_oa_stream_init(stream, param, props);
2958 if (ret)
2959 goto err_alloc;
2960
2961 /* we avoid simply assigning stream->sample_flags = props->sample_flags
2962 * to have _stream_init check the combination of sample flags more
2963 * thoroughly, but still this is the expected result at this point.
eec688e1 2964 */
d7965152
RB
2965 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
2966 ret = -ENODEV;
22f880ca 2967 goto err_flags;
d7965152 2968 }
eec688e1 2969
eec688e1
RB
2970 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
2971 f_flags |= O_CLOEXEC;
2972 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
2973 f_flags |= O_NONBLOCK;
2974
2975 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
2976 if (stream_fd < 0) {
2977 ret = stream_fd;
23b9e41a 2978 goto err_flags;
eec688e1
RB
2979 }
2980
2981 if (!(param->flags & I915_PERF_FLAG_DISABLED))
2982 i915_perf_enable_locked(stream);
2983
a5af1df7
LL
2984 /* Take a reference on the driver that will be kept with stream_fd
2985 * until its release.
2986 */
8f8b1171 2987 drm_dev_get(&perf->i915->drm);
a5af1df7 2988
eec688e1
RB
2989 return stream_fd;
2990
22f880ca 2991err_flags:
eec688e1
RB
2992 if (stream->ops->destroy)
2993 stream->ops->destroy(stream);
2994err_alloc:
2995 kfree(stream);
2996err_ctx:
69df05e1 2997 if (specific_ctx)
5f09a9c8 2998 i915_gem_context_put(specific_ctx);
eec688e1
RB
2999err:
3000 return ret;
3001}
3002
8f8b1171 3003static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
155e941f 3004{
9f9b2792 3005 return div64_u64(1000000000ULL * (2ULL << exponent),
8f8b1171 3006 1000ULL * RUNTIME_INFO(perf->i915)->cs_timestamp_frequency_khz);
155e941f
RB
3007}
3008
16d98b31
RB
3009/**
3010 * read_properties_unlocked - validate + copy userspace stream open properties
8f8b1171 3011 * @perf: i915 perf instance
16d98b31
RB
3012 * @uprops: The array of u64 key value pairs given by userspace
3013 * @n_props: The number of key value pairs expected in @uprops
3014 * @props: The stream configuration built up while validating properties
eec688e1
RB
3015 *
3016 * Note this function only validates properties in isolation it doesn't
3017 * validate that the combination of properties makes sense or that all
3018 * properties necessary for a particular kind of stream have been set.
16d98b31
RB
3019 *
3020 * Note that there currently aren't any ordering requirements for properties so
3021 * we shouldn't validate or assume anything about ordering here. This doesn't
3022 * rule out defining new properties with ordering requirements in the future.
eec688e1 3023 */
8f8b1171 3024static int read_properties_unlocked(struct i915_perf *perf,
eec688e1
RB
3025 u64 __user *uprops,
3026 u32 n_props,
3027 struct perf_open_properties *props)
3028{
3029 u64 __user *uprop = uprops;
701f8231 3030 u32 i;
eec688e1
RB
3031
3032 memset(props, 0, sizeof(struct perf_open_properties));
3033
3034 if (!n_props) {
7708550c 3035 DRM_DEBUG("No i915 perf properties given\n");
eec688e1
RB
3036 return -EINVAL;
3037 }
3038
9a61363a
LL
3039 /* At the moment we only support using i915-perf on the RCS. */
3040 props->engine = intel_engine_lookup_user(perf->i915,
3041 I915_ENGINE_CLASS_RENDER,
3042 0);
3043 if (!props->engine) {
3044 DRM_DEBUG("No RENDER-capable engines\n");
3045 return -EINVAL;
3046 }
3047
eec688e1
RB
3048 /* Considering that ID = 0 is reserved and assuming that we don't
3049 * (currently) expect any configurations to ever specify duplicate
3050 * values for a particular property ID then the last _PROP_MAX value is
3051 * one greater than the maximum number of properties we expect to get
3052 * from userspace.
3053 */
3054 if (n_props >= DRM_I915_PERF_PROP_MAX) {
7708550c 3055 DRM_DEBUG("More i915 perf properties specified than exist\n");
eec688e1
RB
3056 return -EINVAL;
3057 }
3058
3059 for (i = 0; i < n_props; i++) {
00319ba0 3060 u64 oa_period, oa_freq_hz;
eec688e1
RB
3061 u64 id, value;
3062 int ret;
3063
3064 ret = get_user(id, uprop);
3065 if (ret)
3066 return ret;
3067
3068 ret = get_user(value, uprop + 1);
3069 if (ret)
3070 return ret;
3071
0a309f9e
MA
3072 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
3073 DRM_DEBUG("Unknown i915 perf property ID\n");
3074 return -EINVAL;
3075 }
3076
eec688e1
RB
3077 switch ((enum drm_i915_perf_property_id)id) {
3078 case DRM_I915_PERF_PROP_CTX_HANDLE:
3079 props->single_context = 1;
3080 props->ctx_handle = value;
3081 break;
d7965152 3082 case DRM_I915_PERF_PROP_SAMPLE_OA:
b6dd47b9
LL
3083 if (value)
3084 props->sample_flags |= SAMPLE_OA_REPORT;
d7965152
RB
3085 break;
3086 case DRM_I915_PERF_PROP_OA_METRICS_SET:
701f8231 3087 if (value == 0) {
7708550c 3088 DRM_DEBUG("Unknown OA metric set ID\n");
d7965152
RB
3089 return -EINVAL;
3090 }
3091 props->metrics_set = value;
3092 break;
3093 case DRM_I915_PERF_PROP_OA_FORMAT:
3094 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
52c57c26
RB
3095 DRM_DEBUG("Out-of-range OA report format %llu\n",
3096 value);
d7965152
RB
3097 return -EINVAL;
3098 }
8f8b1171 3099 if (!perf->oa_formats[value].size) {
52c57c26
RB
3100 DRM_DEBUG("Unsupported OA report format %llu\n",
3101 value);
d7965152
RB
3102 return -EINVAL;
3103 }
3104 props->oa_format = value;
3105 break;
3106 case DRM_I915_PERF_PROP_OA_EXPONENT:
3107 if (value > OA_EXPONENT_MAX) {
7708550c
RB
3108 DRM_DEBUG("OA timer exponent too high (> %u)\n",
3109 OA_EXPONENT_MAX);
d7965152
RB
3110 return -EINVAL;
3111 }
3112
00319ba0 3113 /* Theoretically we can program the OA unit to sample
155e941f
RB
3114 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
3115 * for BXT. We don't allow such high sampling
3116 * frequencies by default unless root.
00319ba0 3117 */
155e941f 3118
00319ba0 3119 BUILD_BUG_ON(sizeof(oa_period) != 8);
8f8b1171 3120 oa_period = oa_exponent_to_ns(perf, value);
00319ba0
RB
3121
3122 /* This check is primarily to ensure that oa_period <=
3123 * UINT32_MAX (before passing to do_div which only
3124 * accepts a u32 denominator), but we can also skip
3125 * checking anything < 1Hz which implicitly can't be
3126 * limited via an integer oa_max_sample_rate.
d7965152 3127 */
00319ba0
RB
3128 if (oa_period <= NSEC_PER_SEC) {
3129 u64 tmp = NSEC_PER_SEC;
3130 do_div(tmp, oa_period);
3131 oa_freq_hz = tmp;
3132 } else
3133 oa_freq_hz = 0;
3134
3135 if (oa_freq_hz > i915_oa_max_sample_rate &&
3136 !capable(CAP_SYS_ADMIN)) {
7708550c 3137 DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
00319ba0 3138 i915_oa_max_sample_rate);
d7965152
RB
3139 return -EACCES;
3140 }
3141
3142 props->oa_periodic = true;
3143 props->oa_period_exponent = value;
3144 break;
0a309f9e 3145 case DRM_I915_PERF_PROP_MAX:
eec688e1 3146 MISSING_CASE(id);
eec688e1
RB
3147 return -EINVAL;
3148 }
3149
3150 uprop += 2;
3151 }
3152
3153 return 0;
3154}
3155
16d98b31
RB
3156/**
3157 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
3158 * @dev: drm device
3159 * @data: ioctl data copied from userspace (unvalidated)
3160 * @file: drm file
3161 *
3162 * Validates the stream open parameters given by userspace including flags
3163 * and an array of u64 key, value pair properties.
3164 *
3165 * Very little is assumed up front about the nature of the stream being
3166 * opened (for instance we don't assume it's for periodic OA unit metrics). An
3167 * i915-perf stream is expected to be a suitable interface for other forms of
3168 * buffered data written by the GPU besides periodic OA metrics.
3169 *
3170 * Note we copy the properties from userspace outside of the i915 perf
3171 * mutex to avoid an awkward lockdep with mmap_sem.
3172 *
3173 * Most of the implementation details are handled by
8f8b1171 3174 * i915_perf_open_ioctl_locked() after taking the &perf->lock
16d98b31
RB
3175 * mutex for serializing with any non-file-operation driver hooks.
3176 *
3177 * Return: A newly opened i915 Perf stream file descriptor or negative
3178 * error code on failure.
3179 */
eec688e1
RB
3180int i915_perf_open_ioctl(struct drm_device *dev, void *data,
3181 struct drm_file *file)
3182{
8f8b1171 3183 struct i915_perf *perf = &to_i915(dev)->perf;
eec688e1
RB
3184 struct drm_i915_perf_open_param *param = data;
3185 struct perf_open_properties props;
3186 u32 known_open_flags;
3187 int ret;
3188
8f8b1171 3189 if (!perf->i915) {
7708550c 3190 DRM_DEBUG("i915 perf interface not available for this system\n");
eec688e1
RB
3191 return -ENOTSUPP;
3192 }
3193
3194 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
3195 I915_PERF_FLAG_FD_NONBLOCK |
3196 I915_PERF_FLAG_DISABLED;
3197 if (param->flags & ~known_open_flags) {
7708550c 3198 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
eec688e1
RB
3199 return -EINVAL;
3200 }
3201
8f8b1171 3202 ret = read_properties_unlocked(perf,
eec688e1
RB
3203 u64_to_user_ptr(param->properties_ptr),
3204 param->num_properties,
3205 &props);
3206 if (ret)
3207 return ret;
3208
8f8b1171
CW
3209 mutex_lock(&perf->lock);
3210 ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
3211 mutex_unlock(&perf->lock);
eec688e1
RB
3212
3213 return ret;
3214}
3215
16d98b31
RB
3216/**
3217 * i915_perf_register - exposes i915-perf to userspace
8f8b1171 3218 * @i915: i915 device instance
16d98b31
RB
3219 *
3220 * In particular OA metric sets are advertised under a sysfs metrics/
3221 * directory allowing userspace to enumerate valid IDs that can be
3222 * used to open an i915-perf stream.
3223 */
8f8b1171 3224void i915_perf_register(struct drm_i915_private *i915)
442b8c06 3225{
8f8b1171 3226 struct i915_perf *perf = &i915->perf;
701f8231
LL
3227 int ret;
3228
8f8b1171 3229 if (!perf->i915)
442b8c06
RB
3230 return;
3231
3232 /* To be sure we're synchronized with an attempted
3233 * i915_perf_open_ioctl(); considering that we register after
3234 * being exposed to userspace.
3235 */
8f8b1171 3236 mutex_lock(&perf->lock);
442b8c06 3237
8f8b1171 3238 perf->metrics_kobj =
442b8c06 3239 kobject_create_and_add("metrics",
8f8b1171
CW
3240 &i915->drm.primary->kdev->kobj);
3241 if (!perf->metrics_kobj)
442b8c06
RB
3242 goto exit;
3243
8f8b1171
CW
3244 sysfs_attr_init(&perf->test_config.sysfs_metric_id.attr);
3245
3246 if (INTEL_GEN(i915) >= 11) {
3247 i915_perf_load_test_config_icl(i915);
3248 } else if (IS_CANNONLAKE(i915)) {
3249 i915_perf_load_test_config_cnl(i915);
3250 } else if (IS_COFFEELAKE(i915)) {
3251 if (IS_CFL_GT2(i915))
3252 i915_perf_load_test_config_cflgt2(i915);
3253 if (IS_CFL_GT3(i915))
3254 i915_perf_load_test_config_cflgt3(i915);
3255 } else if (IS_GEMINILAKE(i915)) {
3256 i915_perf_load_test_config_glk(i915);
3257 } else if (IS_KABYLAKE(i915)) {
3258 if (IS_KBL_GT2(i915))
3259 i915_perf_load_test_config_kblgt2(i915);
3260 else if (IS_KBL_GT3(i915))
3261 i915_perf_load_test_config_kblgt3(i915);
3262 } else if (IS_BROXTON(i915)) {
3263 i915_perf_load_test_config_bxt(i915);
3264 } else if (IS_SKYLAKE(i915)) {
3265 if (IS_SKL_GT2(i915))
3266 i915_perf_load_test_config_sklgt2(i915);
3267 else if (IS_SKL_GT3(i915))
3268 i915_perf_load_test_config_sklgt3(i915);
3269 else if (IS_SKL_GT4(i915))
3270 i915_perf_load_test_config_sklgt4(i915);
3271 } else if (IS_CHERRYVIEW(i915)) {
3272 i915_perf_load_test_config_chv(i915);
3273 } else if (IS_BROADWELL(i915)) {
3274 i915_perf_load_test_config_bdw(i915);
3275 } else if (IS_HASWELL(i915)) {
3276 i915_perf_load_test_config_hsw(i915);
3277 }
3278
3279 if (perf->test_config.id == 0)
701f8231
LL
3280 goto sysfs_error;
3281
8f8b1171
CW
3282 ret = sysfs_create_group(perf->metrics_kobj,
3283 &perf->test_config.sysfs_metric);
701f8231
LL
3284 if (ret)
3285 goto sysfs_error;
f89823c2 3286
6a45008a
LL
3287 perf->test_config.perf = perf;
3288 kref_init(&perf->test_config.ref);
f89823c2 3289
19f81df2
RB
3290 goto exit;
3291
3292sysfs_error:
8f8b1171
CW
3293 kobject_put(perf->metrics_kobj);
3294 perf->metrics_kobj = NULL;
19f81df2 3295
442b8c06 3296exit:
8f8b1171 3297 mutex_unlock(&perf->lock);
442b8c06
RB
3298}
3299
16d98b31
RB
3300/**
3301 * i915_perf_unregister - hide i915-perf from userspace
8f8b1171 3302 * @i915: i915 device instance
16d98b31
RB
3303 *
3304 * i915-perf state cleanup is split up into an 'unregister' and
3305 * 'deinit' phase where the interface is first hidden from
3306 * userspace by i915_perf_unregister() before cleaning up
3307 * remaining state in i915_perf_fini().
3308 */
8f8b1171 3309void i915_perf_unregister(struct drm_i915_private *i915)
442b8c06 3310{
8f8b1171
CW
3311 struct i915_perf *perf = &i915->perf;
3312
3313 if (!perf->metrics_kobj)
442b8c06
RB
3314 return;
3315
8f8b1171
CW
3316 sysfs_remove_group(perf->metrics_kobj,
3317 &perf->test_config.sysfs_metric);
442b8c06 3318
8f8b1171
CW
3319 kobject_put(perf->metrics_kobj);
3320 perf->metrics_kobj = NULL;
442b8c06
RB
3321}
3322
8f8b1171 3323static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
f89823c2
LL
3324{
3325 static const i915_reg_t flex_eu_regs[] = {
3326 EU_PERF_CNTL0,
3327 EU_PERF_CNTL1,
3328 EU_PERF_CNTL2,
3329 EU_PERF_CNTL3,
3330 EU_PERF_CNTL4,
3331 EU_PERF_CNTL5,
3332 EU_PERF_CNTL6,
3333 };
3334 int i;
3335
3336 for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
7c52a221 3337 if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
f89823c2
LL
3338 return true;
3339 }
3340 return false;
3341}
3342
8f8b1171 3343static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
f89823c2 3344{
7c52a221
LL
3345 return (addr >= i915_mmio_reg_offset(OASTARTTRIG1) &&
3346 addr <= i915_mmio_reg_offset(OASTARTTRIG8)) ||
3347 (addr >= i915_mmio_reg_offset(OAREPORTTRIG1) &&
3348 addr <= i915_mmio_reg_offset(OAREPORTTRIG8)) ||
3349 (addr >= i915_mmio_reg_offset(OACEC0_0) &&
3350 addr <= i915_mmio_reg_offset(OACEC7_1));
f89823c2
LL
3351}
3352
8f8b1171 3353static bool gen7_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
f89823c2 3354{
7c52a221
LL
3355 return addr == i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) ||
3356 (addr >= i915_mmio_reg_offset(MICRO_BP0_0) &&
3357 addr <= i915_mmio_reg_offset(NOA_WRITE)) ||
3358 (addr >= i915_mmio_reg_offset(OA_PERFCNT1_LO) &&
3359 addr <= i915_mmio_reg_offset(OA_PERFCNT2_HI)) ||
3360 (addr >= i915_mmio_reg_offset(OA_PERFMATRIX_LO) &&
3361 addr <= i915_mmio_reg_offset(OA_PERFMATRIX_HI));
f89823c2
LL
3362}
3363
8f8b1171 3364static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
f89823c2 3365{
8f8b1171 3366 return gen7_is_valid_mux_addr(perf, addr) ||
7c52a221
LL
3367 addr == i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) ||
3368 (addr >= i915_mmio_reg_offset(RPM_CONFIG0) &&
3369 addr <= i915_mmio_reg_offset(NOA_CONFIG(8)));
f89823c2
LL
3370}
3371
8f8b1171 3372static bool gen10_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
95690a02 3373{
8f8b1171 3374 return gen8_is_valid_mux_addr(perf, addr) ||
bf210f6c 3375 addr == i915_mmio_reg_offset(GEN10_NOA_WRITE_HIGH) ||
7c52a221
LL
3376 (addr >= i915_mmio_reg_offset(OA_PERFCNT3_LO) &&
3377 addr <= i915_mmio_reg_offset(OA_PERFCNT4_HI));
95690a02
LL
3378}
3379
8f8b1171 3380static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
f89823c2 3381{
8f8b1171 3382 return gen7_is_valid_mux_addr(perf, addr) ||
f89823c2 3383 (addr >= 0x25100 && addr <= 0x2FF90) ||
7c52a221
LL
3384 (addr >= i915_mmio_reg_offset(HSW_MBVID2_NOA0) &&
3385 addr <= i915_mmio_reg_offset(HSW_MBVID2_NOA9)) ||
3386 addr == i915_mmio_reg_offset(HSW_MBVID2_MISR0);
f89823c2
LL
3387}
3388
8f8b1171 3389static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
f89823c2 3390{
8f8b1171 3391 return gen7_is_valid_mux_addr(perf, addr) ||
f89823c2
LL
3392 (addr >= 0x182300 && addr <= 0x1823A4);
3393}
3394
739f3abd 3395static u32 mask_reg_value(u32 reg, u32 val)
f89823c2
LL
3396{
3397 /* HALF_SLICE_CHICKEN2 is programmed with a the
3398 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
3399 * programmed by userspace doesn't change this.
3400 */
7c52a221 3401 if (i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) == reg)
f89823c2
LL
3402 val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
3403
3404 /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
3405 * indicated by its name and a bunch of selection fields used by OA
3406 * configs.
3407 */
7c52a221 3408 if (i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) == reg)
f89823c2
LL
3409 val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
3410
3411 return val;
3412}
3413
8f8b1171
CW
3414static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
3415 bool (*is_valid)(struct i915_perf *perf, u32 addr),
f89823c2
LL
3416 u32 __user *regs,
3417 u32 n_regs)
3418{
3419 struct i915_oa_reg *oa_regs;
3420 int err;
3421 u32 i;
3422
3423 if (!n_regs)
3424 return NULL;
3425
96d4f267 3426 if (!access_ok(regs, n_regs * sizeof(u32) * 2))
f89823c2
LL
3427 return ERR_PTR(-EFAULT);
3428
3429 /* No is_valid function means we're not allowing any register to be programmed. */
3430 GEM_BUG_ON(!is_valid);
3431 if (!is_valid)
3432 return ERR_PTR(-EINVAL);
3433
3434 oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
3435 if (!oa_regs)
3436 return ERR_PTR(-ENOMEM);
3437
3438 for (i = 0; i < n_regs; i++) {
3439 u32 addr, value;
3440
3441 err = get_user(addr, regs);
3442 if (err)
3443 goto addr_err;
3444
8f8b1171 3445 if (!is_valid(perf, addr)) {
f89823c2
LL
3446 DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
3447 err = -EINVAL;
3448 goto addr_err;
3449 }
3450
3451 err = get_user(value, regs + 1);
3452 if (err)
3453 goto addr_err;
3454
3455 oa_regs[i].addr = _MMIO(addr);
3456 oa_regs[i].value = mask_reg_value(addr, value);
3457
3458 regs += 2;
3459 }
3460
3461 return oa_regs;
3462
3463addr_err:
3464 kfree(oa_regs);
3465 return ERR_PTR(err);
3466}
3467
3468static ssize_t show_dynamic_id(struct device *dev,
3469 struct device_attribute *attr,
3470 char *buf)
3471{
3472 struct i915_oa_config *oa_config =
3473 container_of(attr, typeof(*oa_config), sysfs_metric_id);
3474
3475 return sprintf(buf, "%d\n", oa_config->id);
3476}
3477
8f8b1171 3478static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
f89823c2
LL
3479 struct i915_oa_config *oa_config)
3480{
28152a23 3481 sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
f89823c2
LL
3482 oa_config->sysfs_metric_id.attr.name = "id";
3483 oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
3484 oa_config->sysfs_metric_id.show = show_dynamic_id;
3485 oa_config->sysfs_metric_id.store = NULL;
3486
3487 oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
3488 oa_config->attrs[1] = NULL;
3489
3490 oa_config->sysfs_metric.name = oa_config->uuid;
3491 oa_config->sysfs_metric.attrs = oa_config->attrs;
3492
8f8b1171 3493 return sysfs_create_group(perf->metrics_kobj,
f89823c2
LL
3494 &oa_config->sysfs_metric);
3495}
3496
3497/**
3498 * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
3499 * @dev: drm device
3500 * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
3501 * userspace (unvalidated)
3502 * @file: drm file
3503 *
3504 * Validates the submitted OA register to be saved into a new OA config that
3505 * can then be used for programming the OA unit and its NOA network.
3506 *
3507 * Returns: A new allocated config number to be used with the perf open ioctl
3508 * or a negative error code on failure.
3509 */
3510int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
3511 struct drm_file *file)
3512{
8f8b1171 3513 struct i915_perf *perf = &to_i915(dev)->perf;
f89823c2
LL
3514 struct drm_i915_perf_oa_config *args = data;
3515 struct i915_oa_config *oa_config, *tmp;
3516 int err, id;
3517
8f8b1171 3518 if (!perf->i915) {
f89823c2
LL
3519 DRM_DEBUG("i915 perf interface not available for this system\n");
3520 return -ENOTSUPP;
3521 }
3522
8f8b1171 3523 if (!perf->metrics_kobj) {
f89823c2
LL
3524 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
3525 return -EINVAL;
3526 }
3527
3528 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3529 DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
3530 return -EACCES;
3531 }
3532
3533 if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
3534 (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
3535 (!args->flex_regs_ptr || !args->n_flex_regs)) {
3536 DRM_DEBUG("No OA registers given\n");
3537 return -EINVAL;
3538 }
3539
3540 oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
3541 if (!oa_config) {
3542 DRM_DEBUG("Failed to allocate memory for the OA config\n");
3543 return -ENOMEM;
3544 }
3545
6a45008a
LL
3546 oa_config->perf = perf;
3547 kref_init(&oa_config->ref);
f89823c2
LL
3548
3549 if (!uuid_is_valid(args->uuid)) {
3550 DRM_DEBUG("Invalid uuid format for OA config\n");
3551 err = -EINVAL;
3552 goto reg_err;
3553 }
3554
3555 /* Last character in oa_config->uuid will be 0 because oa_config is
3556 * kzalloc.
3557 */
3558 memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
3559
3560 oa_config->mux_regs_len = args->n_mux_regs;
3561 oa_config->mux_regs =
8f8b1171
CW
3562 alloc_oa_regs(perf,
3563 perf->ops.is_valid_mux_reg,
f89823c2
LL
3564 u64_to_user_ptr(args->mux_regs_ptr),
3565 args->n_mux_regs);
3566
3567 if (IS_ERR(oa_config->mux_regs)) {
3568 DRM_DEBUG("Failed to create OA config for mux_regs\n");
3569 err = PTR_ERR(oa_config->mux_regs);
3570 goto reg_err;
3571 }
3572
3573 oa_config->b_counter_regs_len = args->n_boolean_regs;
3574 oa_config->b_counter_regs =
8f8b1171
CW
3575 alloc_oa_regs(perf,
3576 perf->ops.is_valid_b_counter_reg,
f89823c2
LL
3577 u64_to_user_ptr(args->boolean_regs_ptr),
3578 args->n_boolean_regs);
3579
3580 if (IS_ERR(oa_config->b_counter_regs)) {
3581 DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
3582 err = PTR_ERR(oa_config->b_counter_regs);
3583 goto reg_err;
3584 }
3585
8f8b1171 3586 if (INTEL_GEN(perf->i915) < 8) {
f89823c2
LL
3587 if (args->n_flex_regs != 0) {
3588 err = -EINVAL;
3589 goto reg_err;
3590 }
3591 } else {
3592 oa_config->flex_regs_len = args->n_flex_regs;
3593 oa_config->flex_regs =
8f8b1171
CW
3594 alloc_oa_regs(perf,
3595 perf->ops.is_valid_flex_reg,
f89823c2
LL
3596 u64_to_user_ptr(args->flex_regs_ptr),
3597 args->n_flex_regs);
3598
3599 if (IS_ERR(oa_config->flex_regs)) {
3600 DRM_DEBUG("Failed to create OA config for flex_regs\n");
3601 err = PTR_ERR(oa_config->flex_regs);
3602 goto reg_err;
3603 }
3604 }
3605
8f8b1171 3606 err = mutex_lock_interruptible(&perf->metrics_lock);
f89823c2
LL
3607 if (err)
3608 goto reg_err;
3609
3610 /* We shouldn't have too many configs, so this iteration shouldn't be
3611 * too costly.
3612 */
8f8b1171 3613 idr_for_each_entry(&perf->metrics_idr, tmp, id) {
f89823c2
LL
3614 if (!strcmp(tmp->uuid, oa_config->uuid)) {
3615 DRM_DEBUG("OA config already exists with this uuid\n");
3616 err = -EADDRINUSE;
3617 goto sysfs_err;
3618 }
3619 }
3620
8f8b1171 3621 err = create_dynamic_oa_sysfs_entry(perf, oa_config);
f89823c2
LL
3622 if (err) {
3623 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3624 goto sysfs_err;
3625 }
3626
3627 /* Config id 0 is invalid, id 1 for kernel stored test config. */
8f8b1171 3628 oa_config->id = idr_alloc(&perf->metrics_idr,
f89823c2
LL
3629 oa_config, 2,
3630 0, GFP_KERNEL);
3631 if (oa_config->id < 0) {
3632 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3633 err = oa_config->id;
3634 goto sysfs_err;
3635 }
3636
8f8b1171 3637 mutex_unlock(&perf->metrics_lock);
f89823c2 3638
9bd9be66
LL
3639 DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id);
3640
f89823c2
LL
3641 return oa_config->id;
3642
3643sysfs_err:
8f8b1171 3644 mutex_unlock(&perf->metrics_lock);
f89823c2 3645reg_err:
6a45008a 3646 i915_oa_config_put(oa_config);
f89823c2
LL
3647 DRM_DEBUG("Failed to add new OA config\n");
3648 return err;
3649}
3650
3651/**
3652 * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
3653 * @dev: drm device
3654 * @data: ioctl data (pointer to u64 integer) copied from userspace
3655 * @file: drm file
3656 *
3657 * Configs can be removed while being used, the will stop appearing in sysfs
3658 * and their content will be freed when the stream using the config is closed.
3659 *
3660 * Returns: 0 on success or a negative error code on failure.
3661 */
3662int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
3663 struct drm_file *file)
3664{
8f8b1171 3665 struct i915_perf *perf = &to_i915(dev)->perf;
f89823c2
LL
3666 u64 *arg = data;
3667 struct i915_oa_config *oa_config;
3668 int ret;
3669
8f8b1171 3670 if (!perf->i915) {
f89823c2
LL
3671 DRM_DEBUG("i915 perf interface not available for this system\n");
3672 return -ENOTSUPP;
3673 }
3674
3675 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3676 DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
3677 return -EACCES;
3678 }
3679
8f8b1171 3680 ret = mutex_lock_interruptible(&perf->metrics_lock);
f89823c2 3681 if (ret)
6a45008a 3682 return ret;
f89823c2 3683
8f8b1171 3684 oa_config = idr_find(&perf->metrics_idr, *arg);
f89823c2
LL
3685 if (!oa_config) {
3686 DRM_DEBUG("Failed to remove unknown OA config\n");
3687 ret = -ENOENT;
6a45008a 3688 goto err_unlock;
f89823c2
LL
3689 }
3690
3691 GEM_BUG_ON(*arg != oa_config->id);
3692
8f8b1171 3693 sysfs_remove_group(perf->metrics_kobj,
f89823c2
LL
3694 &oa_config->sysfs_metric);
3695
8f8b1171 3696 idr_remove(&perf->metrics_idr, *arg);
9bd9be66 3697
6a45008a
LL
3698 mutex_unlock(&perf->metrics_lock);
3699
9bd9be66
LL
3700 DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
3701
6a45008a
LL
3702 i915_oa_config_put(oa_config);
3703
3704 return 0;
f89823c2 3705
6a45008a 3706err_unlock:
8f8b1171 3707 mutex_unlock(&perf->metrics_lock);
f89823c2
LL
3708 return ret;
3709}
3710
ccdf6341
RB
3711static struct ctl_table oa_table[] = {
3712 {
3713 .procname = "perf_stream_paranoid",
3714 .data = &i915_perf_stream_paranoid,
3715 .maxlen = sizeof(i915_perf_stream_paranoid),
3716 .mode = 0644,
3717 .proc_handler = proc_dointvec_minmax,
eec4844f
MC
3718 .extra1 = SYSCTL_ZERO,
3719 .extra2 = SYSCTL_ONE,
ccdf6341 3720 },
00319ba0
RB
3721 {
3722 .procname = "oa_max_sample_rate",
3723 .data = &i915_oa_max_sample_rate,
3724 .maxlen = sizeof(i915_oa_max_sample_rate),
3725 .mode = 0644,
3726 .proc_handler = proc_dointvec_minmax,
eec4844f 3727 .extra1 = SYSCTL_ZERO,
00319ba0
RB
3728 .extra2 = &oa_sample_rate_hard_limit,
3729 },
ccdf6341
RB
3730 {}
3731};
3732
3733static struct ctl_table i915_root[] = {
3734 {
3735 .procname = "i915",
3736 .maxlen = 0,
3737 .mode = 0555,
3738 .child = oa_table,
3739 },
3740 {}
3741};
3742
3743static struct ctl_table dev_root[] = {
3744 {
3745 .procname = "dev",
3746 .maxlen = 0,
3747 .mode = 0555,
3748 .child = i915_root,
3749 },
3750 {}
3751};
3752
16d98b31
RB
3753/**
3754 * i915_perf_init - initialize i915-perf state on module load
8f8b1171 3755 * @i915: i915 device instance
16d98b31
RB
3756 *
3757 * Initializes i915-perf state without exposing anything to userspace.
3758 *
3759 * Note: i915-perf initialization is split into an 'init' and 'register'
3760 * phase with the i915_perf_register() exposing state to userspace.
3761 */
8f8b1171
CW
3762void i915_perf_init(struct drm_i915_private *i915)
3763{
3764 struct i915_perf *perf = &i915->perf;
3765
3766 /* XXX const struct i915_perf_ops! */
3767
3768 if (IS_HASWELL(i915)) {
3769 perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
3770 perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
3771 perf->ops.is_valid_flex_reg = NULL;
3772 perf->ops.enable_metric_set = hsw_enable_metric_set;
3773 perf->ops.disable_metric_set = hsw_disable_metric_set;
3774 perf->ops.oa_enable = gen7_oa_enable;
3775 perf->ops.oa_disable = gen7_oa_disable;
3776 perf->ops.read = gen7_oa_read;
3777 perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
3778
3779 perf->oa_formats = hsw_oa_formats;
3780 } else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
19f81df2
RB
3781 /* Note: that although we could theoretically also support the
3782 * legacy ringbuffer mode on BDW (and earlier iterations of
3783 * this driver, before upstreaming did this) it didn't seem
3784 * worth the complexity to maintain now that BDW+ enable
3785 * execlist mode by default.
3786 */
8f8b1171 3787 perf->oa_formats = gen8_plus_oa_formats;
d7965152 3788
8f8b1171
CW
3789 perf->ops.oa_enable = gen8_oa_enable;
3790 perf->ops.oa_disable = gen8_oa_disable;
3791 perf->ops.read = gen8_oa_read;
3792 perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
701f8231 3793
8f8b1171
CW
3794 if (IS_GEN_RANGE(i915, 8, 9)) {
3795 perf->ops.is_valid_b_counter_reg =
ba6b7c1a 3796 gen7_is_valid_b_counter_addr;
8f8b1171 3797 perf->ops.is_valid_mux_reg =
ba6b7c1a 3798 gen8_is_valid_mux_addr;
8f8b1171 3799 perf->ops.is_valid_flex_reg =
ba6b7c1a 3800 gen8_is_valid_flex_addr;
155e941f 3801
8f8b1171
CW
3802 if (IS_CHERRYVIEW(i915)) {
3803 perf->ops.is_valid_mux_reg =
f89823c2
LL
3804 chv_is_valid_mux_addr;
3805 }
155e941f 3806
8f8b1171
CW
3807 perf->ops.enable_metric_set = gen8_enable_metric_set;
3808 perf->ops.disable_metric_set = gen8_disable_metric_set;
ba6b7c1a 3809
8f8b1171
CW
3810 if (IS_GEN(i915, 8)) {
3811 perf->ctx_oactxctrl_offset = 0x120;
3812 perf->ctx_flexeu0_offset = 0x2ce;
ba6b7c1a 3813
8f8b1171 3814 perf->gen8_valid_ctx_bit = BIT(25);
ba6b7c1a 3815 } else {
8f8b1171
CW
3816 perf->ctx_oactxctrl_offset = 0x128;
3817 perf->ctx_flexeu0_offset = 0x3de;
ba6b7c1a 3818
8f8b1171 3819 perf->gen8_valid_ctx_bit = BIT(16);
ba6b7c1a 3820 }
8f8b1171
CW
3821 } else if (IS_GEN_RANGE(i915, 10, 11)) {
3822 perf->ops.is_valid_b_counter_reg =
95690a02 3823 gen7_is_valid_b_counter_addr;
8f8b1171 3824 perf->ops.is_valid_mux_reg =
95690a02 3825 gen10_is_valid_mux_addr;
8f8b1171 3826 perf->ops.is_valid_flex_reg =
95690a02
LL
3827 gen8_is_valid_flex_addr;
3828
8f8b1171
CW
3829 perf->ops.enable_metric_set = gen8_enable_metric_set;
3830 perf->ops.disable_metric_set = gen10_disable_metric_set;
95690a02 3831
8f8b1171
CW
3832 if (IS_GEN(i915, 10)) {
3833 perf->ctx_oactxctrl_offset = 0x128;
3834 perf->ctx_flexeu0_offset = 0x3de;
8dcfdfb4 3835 } else {
8f8b1171
CW
3836 perf->ctx_oactxctrl_offset = 0x124;
3837 perf->ctx_flexeu0_offset = 0x78e;
8dcfdfb4 3838 }
8f8b1171 3839 perf->gen8_valid_ctx_bit = BIT(16);
19f81df2 3840 }
19f81df2 3841 }
d7965152 3842
8f8b1171 3843 if (perf->ops.enable_metric_set) {
8f8b1171 3844 mutex_init(&perf->lock);
eec688e1 3845
9f9b2792 3846 oa_sample_rate_hard_limit = 1000 *
8f8b1171
CW
3847 (RUNTIME_INFO(i915)->cs_timestamp_frequency_khz / 2);
3848 perf->sysctl_header = register_sysctl_table(dev_root);
ccdf6341 3849
8f8b1171
CW
3850 mutex_init(&perf->metrics_lock);
3851 idr_init(&perf->metrics_idr);
f89823c2 3852
a37f08a8
UNR
3853 /* We set up some ratelimit state to potentially throttle any
3854 * _NOTES about spurious, invalid OA reports which we don't
3855 * forward to userspace.
3856 *
3857 * We print a _NOTE about any throttling when closing the
3858 * stream instead of waiting until driver _fini which no one
3859 * would ever see.
3860 *
3861 * Using the same limiting factors as printk_ratelimit()
3862 */
8f8b1171 3863 ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
a37f08a8
UNR
3864 /* Since we use a DRM_NOTE for spurious reports it would be
3865 * inconsistent to let __ratelimit() automatically print a
3866 * warning for throttling.
3867 */
8f8b1171 3868 ratelimit_set_flags(&perf->spurious_report_rs,
a37f08a8
UNR
3869 RATELIMIT_MSG_ON_RELEASE);
3870
daed3e44
LL
3871 atomic64_set(&perf->noa_programming_delay,
3872 500 * 1000 /* 500us */);
3873
8f8b1171 3874 perf->i915 = i915;
19f81df2 3875 }
eec688e1
RB
3876}
3877
f89823c2
LL
3878static int destroy_config(int id, void *p, void *data)
3879{
6a45008a 3880 i915_oa_config_put(p);
f89823c2
LL
3881 return 0;
3882}
3883
16d98b31
RB
3884/**
3885 * i915_perf_fini - Counter part to i915_perf_init()
8f8b1171 3886 * @i915: i915 device instance
16d98b31 3887 */
8f8b1171 3888void i915_perf_fini(struct drm_i915_private *i915)
eec688e1 3889{
8f8b1171 3890 struct i915_perf *perf = &i915->perf;
eec688e1 3891
8f8b1171
CW
3892 if (!perf->i915)
3893 return;
f89823c2 3894
8f8b1171
CW
3895 idr_for_each(&perf->metrics_idr, destroy_config, perf);
3896 idr_destroy(&perf->metrics_idr);
ccdf6341 3897
8f8b1171 3898 unregister_sysctl_table(perf->sysctl_header);
19f81df2 3899
8f8b1171
CW
3900 memset(&perf->ops, 0, sizeof(perf->ops));
3901 perf->i915 = NULL;
eec688e1 3902}
daed3e44
LL
3903
3904#if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
3905#include "selftests/i915_perf.c"
3906#endif