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