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