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