2 * Copyright © 2015-2016 Intel Corporation
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:
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
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
24 * Robert Bragg <robert@sixbynine.org>
29 * DOC: i915 Perf Overview
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
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.
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.
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
51 * DOC: i915 Perf History and Comparison with Core Perf
53 * The interface was initially inspired by the core Perf infrastructure but
54 * some notable differences are:
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.
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.
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.
82 * Issues hit with first prototype based on Core Perf
83 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
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.
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.
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.
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
106 * - The perf based OA PMU driver broke some significant design assumptions:
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.
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.
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.
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.
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.
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.
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.
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.
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
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.
178 * - It felt like our perf based PMU was making some technical compromises
179 * just for the sake of using perf:
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.
194 #include <linux/anon_inodes.h>
195 #include <linux/sizes.h>
196 #include <linux/uuid.h>
198 #include "gem/i915_gem_context.h"
199 #include "gt/intel_engine_pm.h"
200 #include "gt/intel_engine_user.h"
201 #include "gt/intel_gt.h"
202 #include "gt/intel_lrc_reg.h"
203 #include "gt/intel_ring.h"
205 #include "i915_drv.h"
206 #include "i915_perf.h"
207 #include "oa/i915_oa_hsw.h"
208 #include "oa/i915_oa_bdw.h"
209 #include "oa/i915_oa_chv.h"
210 #include "oa/i915_oa_sklgt2.h"
211 #include "oa/i915_oa_sklgt3.h"
212 #include "oa/i915_oa_sklgt4.h"
213 #include "oa/i915_oa_bxt.h"
214 #include "oa/i915_oa_kblgt2.h"
215 #include "oa/i915_oa_kblgt3.h"
216 #include "oa/i915_oa_glk.h"
217 #include "oa/i915_oa_cflgt2.h"
218 #include "oa/i915_oa_cflgt3.h"
219 #include "oa/i915_oa_cnl.h"
220 #include "oa/i915_oa_icl.h"
221 #include "oa/i915_oa_tgl.h"
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.
227 #define OA_BUFFER_SIZE SZ_16M
229 #define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
232 * DOC: OA Tail Pointer Race
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
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 to avoid lots of redundant
244 * In effect we define a tail pointer for reading that lags the real tail
245 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
246 * time for the corresponding reports to become visible to the CPU.
248 * To manage this we actually track two tail pointers:
249 * 1) An 'aging' tail with an associated timestamp that is tracked until we
250 * can trust the corresponding data is visible to the CPU; at which point
251 * it is considered 'aged'.
252 * 2) An 'aged' tail that can be used for read()ing.
254 * The two separate pointers let us decouple read()s from tail pointer aging.
256 * The tail pointers are checked and updated at a limited rate within a hrtimer
257 * callback (the same callback that is used for delivering EPOLLIN events)
259 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
260 * indicates that an updated tail pointer is needed.
262 * Most of the implementation details for this workaround are in
263 * oa_buffer_check_unlocked() and _append_oa_reports()
265 * Note for posterity: previously the driver used to define an effective tail
266 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
267 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
268 * This was flawed considering that the OA unit may also automatically generate
269 * non-periodic reports (such as on context switch) or the OA unit may be
270 * enabled without any periodic sampling.
272 #define OA_TAIL_MARGIN_NSEC 100000ULL
273 #define INVALID_TAIL_PTR 0xffffffff
275 /* frequency for checking whether the OA unit has written new reports to the
276 * circular OA buffer...
278 #define POLL_FREQUENCY 200
279 #define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
281 /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
282 static u32 i915_perf_stream_paranoid = true;
284 /* The maximum exponent the hardware accepts is 63 (essentially it selects one
285 * of the 64bit timestamp bits to trigger reports from) but there's currently
286 * no known use case for sampling as infrequently as once per 47 thousand years.
288 * Since the timestamps included in OA reports are only 32bits it seems
289 * reasonable to limit the OA exponent where it's still possible to account for
290 * overflow in OA report timestamps.
292 #define OA_EXPONENT_MAX 31
294 #define INVALID_CTX_ID 0xffffffff
296 /* On Gen8+ automatically triggered OA reports include a 'reason' field... */
297 #define OAREPORT_REASON_MASK 0x3f
298 #define OAREPORT_REASON_MASK_EXTENDED 0x7f
299 #define OAREPORT_REASON_SHIFT 19
300 #define OAREPORT_REASON_TIMER (1<<0)
301 #define OAREPORT_REASON_CTX_SWITCH (1<<3)
302 #define OAREPORT_REASON_CLK_RATIO (1<<5)
305 /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
307 * The highest sampling frequency we can theoretically program the OA unit
308 * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
310 * Initialized just before we register the sysctl parameter.
312 static int oa_sample_rate_hard_limit;
314 /* Theoretically we can program the OA unit to sample every 160ns but don't
315 * allow that by default unless root...
317 * The default threshold of 100000Hz is based on perf's similar
318 * kernel.perf_event_max_sample_rate sysctl parameter.
320 static u32 i915_oa_max_sample_rate = 100000;
322 /* XXX: beware if future OA HW adds new report formats that the current
323 * code assumes all reports have a power-of-two size and ~(size - 1) can
324 * be used as a mask to align the OA tail pointer.
326 static const struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
327 [I915_OA_FORMAT_A13] = { 0, 64 },
328 [I915_OA_FORMAT_A29] = { 1, 128 },
329 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
330 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
331 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
332 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
333 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
334 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
337 static const struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
338 [I915_OA_FORMAT_A12] = { 0, 64 },
339 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
340 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
341 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
344 static const struct i915_oa_format gen12_oa_formats[I915_OA_FORMAT_MAX] = {
345 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
348 #define SAMPLE_OA_REPORT (1<<0)
351 * struct perf_open_properties - for validated properties given to open a stream
352 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
353 * @single_context: Whether a single or all gpu contexts should be monitored
354 * @hold_preemption: Whether the preemption is disabled for the filtered
356 * @ctx_handle: A gem ctx handle for use with @single_context
357 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
358 * @oa_format: An OA unit HW report format
359 * @oa_periodic: Whether to enable periodic OA unit sampling
360 * @oa_period_exponent: The OA unit sampling period is derived from this
361 * @engine: The engine (typically rcs0) being monitored by the OA unit
363 * As read_properties_unlocked() enumerates and validates the properties given
364 * to open a stream of metrics the configuration is built up in the structure
365 * which starts out zero initialized.
367 struct perf_open_properties {
370 u64 single_context:1;
371 u64 hold_preemption:1;
374 /* OA sampling state */
378 int oa_period_exponent;
380 struct intel_engine_cs *engine;
383 struct i915_oa_config_bo {
384 struct llist_node node;
386 struct i915_oa_config *oa_config;
387 struct i915_vma *vma;
390 static struct ctl_table_header *sysctl_header;
392 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer);
394 void i915_oa_config_release(struct kref *ref)
396 struct i915_oa_config *oa_config =
397 container_of(ref, typeof(*oa_config), ref);
399 kfree(oa_config->flex_regs);
400 kfree(oa_config->b_counter_regs);
401 kfree(oa_config->mux_regs);
403 kfree_rcu(oa_config, rcu);
406 struct i915_oa_config *
407 i915_perf_get_oa_config(struct i915_perf *perf, int metrics_set)
409 struct i915_oa_config *oa_config;
412 if (metrics_set == 1)
413 oa_config = &perf->test_config;
415 oa_config = idr_find(&perf->metrics_idr, metrics_set);
417 oa_config = i915_oa_config_get(oa_config);
423 static void free_oa_config_bo(struct i915_oa_config_bo *oa_bo)
425 i915_oa_config_put(oa_bo->oa_config);
426 i915_vma_put(oa_bo->vma);
430 static u32 gen12_oa_hw_tail_read(struct i915_perf_stream *stream)
432 struct intel_uncore *uncore = stream->uncore;
434 return intel_uncore_read(uncore, GEN12_OAG_OATAILPTR) &
435 GEN12_OAG_OATAILPTR_MASK;
438 static u32 gen8_oa_hw_tail_read(struct i915_perf_stream *stream)
440 struct intel_uncore *uncore = stream->uncore;
442 return intel_uncore_read(uncore, GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
445 static u32 gen7_oa_hw_tail_read(struct i915_perf_stream *stream)
447 struct intel_uncore *uncore = stream->uncore;
448 u32 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
450 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
454 * oa_buffer_check_unlocked - check for data and update tail ptr state
455 * @stream: i915 stream instance
457 * This is either called via fops (for blocking reads in user ctx) or the poll
458 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
459 * if there is data available for userspace to read.
461 * This function is central to providing a workaround for the OA unit tail
462 * pointer having a race with respect to what data is visible to the CPU.
463 * It is responsible for reading tail pointers from the hardware and giving
464 * the pointers time to 'age' before they are made available for reading.
465 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
467 * Besides returning true when there is data available to read() this function
468 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
469 * and .aged_tail_idx state used for reading.
471 * Note: It's safe to read OA config state here unlocked, assuming that this is
472 * only called while the stream is enabled, while the global OA configuration
475 * Returns: %true if the OA buffer contains data, else %false
477 static bool oa_buffer_check_unlocked(struct i915_perf_stream *stream)
479 int report_size = stream->oa_buffer.format_size;
481 unsigned int aged_idx;
482 u32 head, hw_tail, aged_tail, aging_tail;
485 /* We have to consider the (unlikely) possibility that read() errors
486 * could result in an OA buffer reset which might reset the head,
487 * tails[] and aged_tail state.
489 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
491 /* NB: The head we observe here might effectively be a little out of
492 * date (between head and tails[aged_idx].offset if there is currently
493 * a read() in progress.
495 head = stream->oa_buffer.head;
497 aged_idx = stream->oa_buffer.aged_tail_idx;
498 aged_tail = stream->oa_buffer.tails[aged_idx].offset;
499 aging_tail = stream->oa_buffer.tails[!aged_idx].offset;
501 hw_tail = stream->perf->ops.oa_hw_tail_read(stream);
503 /* The tail pointer increases in 64 byte increments,
504 * not in report_size steps...
506 hw_tail &= ~(report_size - 1);
508 now = ktime_get_mono_fast_ns();
510 /* Update the aged tail
512 * Flip the tail pointer available for read()s once the aging tail is
513 * old enough to trust that the corresponding data will be visible to
516 * Do this before updating the aging pointer in case we may be able to
517 * immediately start aging a new pointer too (if new data has become
518 * available) without needing to wait for a later hrtimer callback.
520 if (aging_tail != INVALID_TAIL_PTR &&
521 ((now - stream->oa_buffer.aging_timestamp) >
522 OA_TAIL_MARGIN_NSEC)) {
525 stream->oa_buffer.aged_tail_idx = aged_idx;
527 aged_tail = aging_tail;
529 /* Mark that we need a new pointer to start aging... */
530 stream->oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
531 aging_tail = INVALID_TAIL_PTR;
534 /* Update the aging tail
536 * We throttle aging tail updates until we have a new tail that
537 * represents >= one report more data than is already available for
538 * reading. This ensures there will be enough data for a successful
539 * read once this new pointer has aged and ensures we will give the new
540 * pointer time to age.
542 if (aging_tail == INVALID_TAIL_PTR &&
543 (aged_tail == INVALID_TAIL_PTR ||
544 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
545 struct i915_vma *vma = stream->oa_buffer.vma;
546 u32 gtt_offset = i915_ggtt_offset(vma);
548 /* Be paranoid and do a bounds check on the pointer read back
549 * from hardware, just in case some spurious hardware condition
550 * could put the tail out of bounds...
552 if (hw_tail >= gtt_offset &&
553 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
554 stream->oa_buffer.tails[!aged_idx].offset =
555 aging_tail = hw_tail;
556 stream->oa_buffer.aging_timestamp = now;
558 drm_err(&stream->perf->i915->drm,
559 "Ignoring spurious out of range OA buffer tail pointer = %x\n",
564 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
566 return aged_tail == INVALID_TAIL_PTR ?
567 false : OA_TAKEN(aged_tail, head) >= report_size;
571 * append_oa_status - Appends a status record to a userspace read() buffer.
572 * @stream: An i915-perf stream opened for OA metrics
573 * @buf: destination buffer given by userspace
574 * @count: the number of bytes userspace wants to read
575 * @offset: (inout): the current position for writing into @buf
576 * @type: The kind of status to report to userspace
578 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
579 * into the userspace read() buffer.
581 * The @buf @offset will only be updated on success.
583 * Returns: 0 on success, negative error code on failure.
585 static int append_oa_status(struct i915_perf_stream *stream,
589 enum drm_i915_perf_record_type type)
591 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
593 if ((count - *offset) < header.size)
596 if (copy_to_user(buf + *offset, &header, sizeof(header)))
599 (*offset) += header.size;
605 * append_oa_sample - Copies single OA report into userspace read() buffer.
606 * @stream: An i915-perf stream opened for OA metrics
607 * @buf: destination buffer given by userspace
608 * @count: the number of bytes userspace wants to read
609 * @offset: (inout): the current position for writing into @buf
610 * @report: A single OA report to (optionally) include as part of the sample
612 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
613 * properties when opening a stream, tracked as `stream->sample_flags`. This
614 * function copies the requested components of a single sample to the given
617 * The @buf @offset will only be updated on success.
619 * Returns: 0 on success, negative error code on failure.
621 static int append_oa_sample(struct i915_perf_stream *stream,
627 int report_size = stream->oa_buffer.format_size;
628 struct drm_i915_perf_record_header header;
629 u32 sample_flags = stream->sample_flags;
631 header.type = DRM_I915_PERF_RECORD_SAMPLE;
633 header.size = stream->sample_size;
635 if ((count - *offset) < header.size)
639 if (copy_to_user(buf, &header, sizeof(header)))
641 buf += sizeof(header);
643 if (sample_flags & SAMPLE_OA_REPORT) {
644 if (copy_to_user(buf, report, report_size))
648 (*offset) += header.size;
654 * Copies all buffered OA reports into userspace read() buffer.
655 * @stream: An i915-perf stream opened for OA metrics
656 * @buf: destination buffer given by userspace
657 * @count: the number of bytes userspace wants to read
658 * @offset: (inout): the current position for writing into @buf
660 * Notably any error condition resulting in a short read (-%ENOSPC or
661 * -%EFAULT) will be returned even though one or more records may
662 * have been successfully copied. In this case it's up to the caller
663 * to decide if the error should be squashed before returning to
666 * Note: reports are consumed from the head, and appended to the
667 * tail, so the tail chases the head?... If you think that's mad
668 * and back-to-front you're not alone, but this follows the
669 * Gen PRM naming convention.
671 * Returns: 0 on success, negative error code on failure.
673 static int gen8_append_oa_reports(struct i915_perf_stream *stream,
678 struct intel_uncore *uncore = stream->uncore;
679 int report_size = stream->oa_buffer.format_size;
680 u8 *oa_buf_base = stream->oa_buffer.vaddr;
681 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
682 u32 mask = (OA_BUFFER_SIZE - 1);
683 size_t start_offset = *offset;
685 unsigned int aged_tail_idx;
690 if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
693 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
695 head = stream->oa_buffer.head;
696 aged_tail_idx = stream->oa_buffer.aged_tail_idx;
697 tail = stream->oa_buffer.tails[aged_tail_idx].offset;
699 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
702 * An invalid tail pointer here means we're still waiting for the poll
703 * hrtimer callback to give us a pointer
705 if (tail == INVALID_TAIL_PTR)
709 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
710 * while indexing relative to oa_buf_base.
716 * An out of bounds or misaligned head or tail pointer implies a driver
717 * bug since we validate + align the tail pointers we read from the
718 * hardware and we are in full control of the head pointer which should
719 * only be incremented by multiples of the report size (notably also
720 * all a power of two).
722 if (drm_WARN_ONCE(&uncore->i915->drm,
723 head > OA_BUFFER_SIZE || head % report_size ||
724 tail > OA_BUFFER_SIZE || tail % report_size,
725 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
731 (taken = OA_TAKEN(tail, head));
732 head = (head + report_size) & mask) {
733 u8 *report = oa_buf_base + head;
734 u32 *report32 = (void *)report;
739 * All the report sizes factor neatly into the buffer
740 * size so we never expect to see a report split
741 * between the beginning and end of the buffer.
743 * Given the initial alignment check a misalignment
744 * here would imply a driver bug that would result
747 if (drm_WARN_ON(&uncore->i915->drm,
748 (OA_BUFFER_SIZE - head) < report_size)) {
749 drm_err(&uncore->i915->drm,
750 "Spurious OA head ptr: non-integral report offset\n");
755 * The reason field includes flags identifying what
756 * triggered this specific report (mostly timer
757 * triggered or e.g. due to a context switch).
759 * This field is never expected to be zero so we can
760 * check that the report isn't invalid before copying
763 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
764 (IS_GEN(stream->perf->i915, 12) ?
765 OAREPORT_REASON_MASK_EXTENDED :
766 OAREPORT_REASON_MASK));
768 if (__ratelimit(&stream->perf->spurious_report_rs))
769 DRM_NOTE("Skipping spurious, invalid OA report\n");
773 ctx_id = report32[2] & stream->specific_ctx_id_mask;
776 * Squash whatever is in the CTX_ID field if it's marked as
777 * invalid to be sure we avoid false-positive, single-context
780 * Note: that we don't clear the valid_ctx_bit so userspace can
781 * understand that the ID has been squashed by the kernel.
783 if (!(report32[0] & stream->perf->gen8_valid_ctx_bit) &&
784 INTEL_GEN(stream->perf->i915) <= 11)
785 ctx_id = report32[2] = INVALID_CTX_ID;
788 * NB: For Gen 8 the OA unit no longer supports clock gating
789 * off for a specific context and the kernel can't securely
790 * stop the counters from updating as system-wide / global
793 * Automatic reports now include a context ID so reports can be
794 * filtered on the cpu but it's not worth trying to
795 * automatically subtract/hide counter progress for other
796 * contexts while filtering since we can't stop userspace
797 * issuing MI_REPORT_PERF_COUNT commands which would still
798 * provide a side-band view of the real values.
800 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
801 * to normalize counters for a single filtered context then it
802 * needs be forwarded bookend context-switch reports so that it
803 * can track switches in between MI_REPORT_PERF_COUNT commands
804 * and can itself subtract/ignore the progress of counters
805 * associated with other contexts. Note that the hardware
806 * automatically triggers reports when switching to a new
807 * context which are tagged with the ID of the newly active
808 * context. To avoid the complexity (and likely fragility) of
809 * reading ahead while parsing reports to try and minimize
810 * forwarding redundant context switch reports (i.e. between
811 * other, unrelated contexts) we simply elect to forward them
814 * We don't rely solely on the reason field to identify context
815 * switches since it's not-uncommon for periodic samples to
816 * identify a switch before any 'context switch' report.
818 if (!stream->perf->exclusive_stream->ctx ||
819 stream->specific_ctx_id == ctx_id ||
820 stream->oa_buffer.last_ctx_id == stream->specific_ctx_id ||
821 reason & OAREPORT_REASON_CTX_SWITCH) {
824 * While filtering for a single context we avoid
825 * leaking the IDs of other contexts.
827 if (stream->perf->exclusive_stream->ctx &&
828 stream->specific_ctx_id != ctx_id) {
829 report32[2] = INVALID_CTX_ID;
832 ret = append_oa_sample(stream, buf, count, offset,
837 stream->oa_buffer.last_ctx_id = ctx_id;
841 * The above reason field sanity check is based on
842 * the assumption that the OA buffer is initially
843 * zeroed and we reset the field after copying so the
844 * check is still meaningful once old reports start
850 if (start_offset != *offset) {
851 i915_reg_t oaheadptr;
853 oaheadptr = IS_GEN(stream->perf->i915, 12) ?
854 GEN12_OAG_OAHEADPTR : GEN8_OAHEADPTR;
856 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
859 * We removed the gtt_offset for the copy loop above, indexing
860 * relative to oa_buf_base so put back here...
863 intel_uncore_write(uncore, oaheadptr,
864 head & GEN12_OAG_OAHEADPTR_MASK);
865 stream->oa_buffer.head = head;
867 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
874 * gen8_oa_read - copy status records then buffered OA reports
875 * @stream: An i915-perf stream opened for OA metrics
876 * @buf: destination buffer given by userspace
877 * @count: the number of bytes userspace wants to read
878 * @offset: (inout): the current position for writing into @buf
880 * Checks OA unit status registers and if necessary appends corresponding
881 * status records for userspace (such as for a buffer full condition) and then
882 * initiate appending any buffered OA reports.
884 * Updates @offset according to the number of bytes successfully copied into
885 * the userspace buffer.
887 * NB: some data may be successfully copied to the userspace buffer
888 * even if an error is returned, and this is reflected in the
891 * Returns: zero on success or a negative error code
893 static int gen8_oa_read(struct i915_perf_stream *stream,
898 struct intel_uncore *uncore = stream->uncore;
900 i915_reg_t oastatus_reg;
903 if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
906 oastatus_reg = IS_GEN(stream->perf->i915, 12) ?
907 GEN12_OAG_OASTATUS : GEN8_OASTATUS;
909 oastatus = intel_uncore_read(uncore, oastatus_reg);
912 * We treat OABUFFER_OVERFLOW as a significant error:
914 * Although theoretically we could handle this more gracefully
915 * sometimes, some Gens don't correctly suppress certain
916 * automatically triggered reports in this condition and so we
917 * have to assume that old reports are now being trampled
920 * Considering how we don't currently give userspace control
921 * over the OA buffer size and always configure a large 16MB
922 * buffer, then a buffer overflow does anyway likely indicate
923 * that something has gone quite badly wrong.
925 if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
926 ret = append_oa_status(stream, buf, count, offset,
927 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
931 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
932 stream->period_exponent);
934 stream->perf->ops.oa_disable(stream);
935 stream->perf->ops.oa_enable(stream);
938 * Note: .oa_enable() is expected to re-init the oabuffer and
939 * reset GEN8_OASTATUS for us
941 oastatus = intel_uncore_read(uncore, oastatus_reg);
944 if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
945 ret = append_oa_status(stream, buf, count, offset,
946 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
949 intel_uncore_write(uncore, oastatus_reg,
950 oastatus & ~GEN8_OASTATUS_REPORT_LOST);
953 return gen8_append_oa_reports(stream, buf, count, offset);
957 * Copies all buffered OA reports into userspace read() buffer.
958 * @stream: An i915-perf stream opened for OA metrics
959 * @buf: destination buffer given by userspace
960 * @count: the number of bytes userspace wants to read
961 * @offset: (inout): the current position for writing into @buf
963 * Notably any error condition resulting in a short read (-%ENOSPC or
964 * -%EFAULT) will be returned even though one or more records may
965 * have been successfully copied. In this case it's up to the caller
966 * to decide if the error should be squashed before returning to
969 * Note: reports are consumed from the head, and appended to the
970 * tail, so the tail chases the head?... If you think that's mad
971 * and back-to-front you're not alone, but this follows the
972 * Gen PRM naming convention.
974 * Returns: 0 on success, negative error code on failure.
976 static int gen7_append_oa_reports(struct i915_perf_stream *stream,
981 struct intel_uncore *uncore = stream->uncore;
982 int report_size = stream->oa_buffer.format_size;
983 u8 *oa_buf_base = stream->oa_buffer.vaddr;
984 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
985 u32 mask = (OA_BUFFER_SIZE - 1);
986 size_t start_offset = *offset;
988 unsigned int aged_tail_idx;
993 if (drm_WARN_ON(&uncore->i915->drm, !stream->enabled))
996 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
998 head = stream->oa_buffer.head;
999 aged_tail_idx = stream->oa_buffer.aged_tail_idx;
1000 tail = stream->oa_buffer.tails[aged_tail_idx].offset;
1002 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1004 /* An invalid tail pointer here means we're still waiting for the poll
1005 * hrtimer callback to give us a pointer
1007 if (tail == INVALID_TAIL_PTR)
1010 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
1011 * while indexing relative to oa_buf_base.
1016 /* An out of bounds or misaligned head or tail pointer implies a driver
1017 * bug since we validate + align the tail pointers we read from the
1018 * hardware and we are in full control of the head pointer which should
1019 * only be incremented by multiples of the report size (notably also
1020 * all a power of two).
1022 if (drm_WARN_ONCE(&uncore->i915->drm,
1023 head > OA_BUFFER_SIZE || head % report_size ||
1024 tail > OA_BUFFER_SIZE || tail % report_size,
1025 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
1031 (taken = OA_TAKEN(tail, head));
1032 head = (head + report_size) & mask) {
1033 u8 *report = oa_buf_base + head;
1034 u32 *report32 = (void *)report;
1036 /* All the report sizes factor neatly into the buffer
1037 * size so we never expect to see a report split
1038 * between the beginning and end of the buffer.
1040 * Given the initial alignment check a misalignment
1041 * here would imply a driver bug that would result
1044 if (drm_WARN_ON(&uncore->i915->drm,
1045 (OA_BUFFER_SIZE - head) < report_size)) {
1046 drm_err(&uncore->i915->drm,
1047 "Spurious OA head ptr: non-integral report offset\n");
1051 /* The report-ID field for periodic samples includes
1052 * some undocumented flags related to what triggered
1053 * the report and is never expected to be zero so we
1054 * can check that the report isn't invalid before
1055 * copying it to userspace...
1057 if (report32[0] == 0) {
1058 if (__ratelimit(&stream->perf->spurious_report_rs))
1059 DRM_NOTE("Skipping spurious, invalid OA report\n");
1063 ret = append_oa_sample(stream, buf, count, offset, report);
1067 /* The above report-id field sanity check is based on
1068 * the assumption that the OA buffer is initially
1069 * zeroed and we reset the field after copying so the
1070 * check is still meaningful once old reports start
1071 * being overwritten.
1076 if (start_offset != *offset) {
1077 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1079 /* We removed the gtt_offset for the copy loop above, indexing
1080 * relative to oa_buf_base so put back here...
1084 intel_uncore_write(uncore, GEN7_OASTATUS2,
1085 (head & GEN7_OASTATUS2_HEAD_MASK) |
1086 GEN7_OASTATUS2_MEM_SELECT_GGTT);
1087 stream->oa_buffer.head = head;
1089 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1096 * gen7_oa_read - copy status records then buffered OA reports
1097 * @stream: An i915-perf stream opened for OA metrics
1098 * @buf: destination buffer given by userspace
1099 * @count: the number of bytes userspace wants to read
1100 * @offset: (inout): the current position for writing into @buf
1102 * Checks Gen 7 specific OA unit status registers and if necessary appends
1103 * corresponding status records for userspace (such as for a buffer full
1104 * condition) and then initiate appending any buffered OA reports.
1106 * Updates @offset according to the number of bytes successfully copied into
1107 * the userspace buffer.
1109 * Returns: zero on success or a negative error code
1111 static int gen7_oa_read(struct i915_perf_stream *stream,
1116 struct intel_uncore *uncore = stream->uncore;
1120 if (drm_WARN_ON(&uncore->i915->drm, !stream->oa_buffer.vaddr))
1123 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1125 /* XXX: On Haswell we don't have a safe way to clear oastatus1
1126 * bits while the OA unit is enabled (while the tail pointer
1127 * may be updated asynchronously) so we ignore status bits
1128 * that have already been reported to userspace.
1130 oastatus1 &= ~stream->perf->gen7_latched_oastatus1;
1132 /* We treat OABUFFER_OVERFLOW as a significant error:
1134 * - The status can be interpreted to mean that the buffer is
1135 * currently full (with a higher precedence than OA_TAKEN()
1136 * which will start to report a near-empty buffer after an
1137 * overflow) but it's awkward that we can't clear the status
1138 * on Haswell, so without a reset we won't be able to catch
1141 * - Since it also implies the HW has started overwriting old
1142 * reports it may also affect our sanity checks for invalid
1143 * reports when copying to userspace that assume new reports
1144 * are being written to cleared memory.
1146 * - In the future we may want to introduce a flight recorder
1147 * mode where the driver will automatically maintain a safe
1148 * guard band between head/tail, avoiding this overflow
1149 * condition, but we avoid the added driver complexity for
1152 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1153 ret = append_oa_status(stream, buf, count, offset,
1154 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1158 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
1159 stream->period_exponent);
1161 stream->perf->ops.oa_disable(stream);
1162 stream->perf->ops.oa_enable(stream);
1164 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1167 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1168 ret = append_oa_status(stream, buf, count, offset,
1169 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1172 stream->perf->gen7_latched_oastatus1 |=
1173 GEN7_OASTATUS1_REPORT_LOST;
1176 return gen7_append_oa_reports(stream, buf, count, offset);
1180 * i915_oa_wait_unlocked - handles blocking IO until OA data available
1181 * @stream: An i915-perf stream opened for OA metrics
1183 * Called when userspace tries to read() from a blocking stream FD opened
1184 * for OA metrics. It waits until the hrtimer callback finds a non-empty
1185 * OA buffer and wakes us.
1187 * Note: it's acceptable to have this return with some false positives
1188 * since any subsequent read handling will return -EAGAIN if there isn't
1189 * really data ready for userspace yet.
1191 * Returns: zero on success or a negative error code
1193 static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1195 /* We would wait indefinitely if periodic sampling is not enabled */
1196 if (!stream->periodic)
1199 return wait_event_interruptible(stream->poll_wq,
1200 oa_buffer_check_unlocked(stream));
1204 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1205 * @stream: An i915-perf stream opened for OA metrics
1206 * @file: An i915 perf stream file
1207 * @wait: poll() state table
1209 * For handling userspace polling on an i915 perf stream opened for OA metrics,
1210 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1211 * when it sees data ready to read in the circular OA buffer.
1213 static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1217 poll_wait(file, &stream->poll_wq, wait);
1221 * i915_oa_read - just calls through to &i915_oa_ops->read
1222 * @stream: An i915-perf stream opened for OA metrics
1223 * @buf: destination buffer given by userspace
1224 * @count: the number of bytes userspace wants to read
1225 * @offset: (inout): the current position for writing into @buf
1227 * Updates @offset according to the number of bytes successfully copied into
1228 * the userspace buffer.
1230 * Returns: zero on success or a negative error code
1232 static int i915_oa_read(struct i915_perf_stream *stream,
1237 return stream->perf->ops.read(stream, buf, count, offset);
1240 static struct intel_context *oa_pin_context(struct i915_perf_stream *stream)
1242 struct i915_gem_engines_iter it;
1243 struct i915_gem_context *ctx = stream->ctx;
1244 struct intel_context *ce;
1247 for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
1248 if (ce->engine != stream->engine) /* first match! */
1252 * As the ID is the gtt offset of the context's vma we
1253 * pin the vma to ensure the ID remains fixed.
1255 err = intel_context_pin(ce);
1257 stream->pinned_ctx = ce;
1261 i915_gem_context_unlock_engines(ctx);
1263 return stream->pinned_ctx;
1267 * oa_get_render_ctx_id - determine and hold ctx hw id
1268 * @stream: An i915-perf stream opened for OA metrics
1270 * Determine the render context hw id, and ensure it remains fixed for the
1271 * lifetime of the stream. This ensures that we don't have to worry about
1272 * updating the context ID in OACONTROL on the fly.
1274 * Returns: zero on success or a negative error code
1276 static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1278 struct intel_context *ce;
1280 ce = oa_pin_context(stream);
1284 switch (INTEL_GEN(ce->engine->i915)) {
1287 * On Haswell we don't do any post processing of the reports
1288 * and don't need to use the mask.
1290 stream->specific_ctx_id = i915_ggtt_offset(ce->state);
1291 stream->specific_ctx_id_mask = 0;
1298 if (intel_engine_in_execlists_submission_mode(ce->engine)) {
1299 stream->specific_ctx_id_mask =
1300 (1U << GEN8_CTX_ID_WIDTH) - 1;
1301 stream->specific_ctx_id = stream->specific_ctx_id_mask;
1304 * When using GuC, the context descriptor we write in
1305 * i915 is read by GuC and rewritten before it's
1306 * actually written into the hardware. The LRCA is
1307 * what is put into the context id field of the
1308 * context descriptor by GuC. Because it's aligned to
1309 * a page, the lower 12bits are always at 0 and
1310 * dropped by GuC. They won't be part of the context
1311 * ID in the OA reports, so squash those lower bits.
1313 stream->specific_ctx_id =
1314 lower_32_bits(ce->lrc_desc) >> 12;
1317 * GuC uses the top bit to signal proxy submission, so
1320 stream->specific_ctx_id_mask =
1321 (1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
1327 stream->specific_ctx_id_mask =
1328 ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) << (GEN11_SW_CTX_ID_SHIFT - 32);
1330 * Pick an unused context id
1331 * 0 - (NUM_CONTEXT_TAG - 1) are used by other contexts
1332 * GEN12_MAX_CONTEXT_HW_ID (0x7ff) is used by idle context
1334 stream->specific_ctx_id = (GEN12_MAX_CONTEXT_HW_ID - 1) << (GEN11_SW_CTX_ID_SHIFT - 32);
1335 BUILD_BUG_ON((GEN12_MAX_CONTEXT_HW_ID - 1) < NUM_CONTEXT_TAG);
1340 MISSING_CASE(INTEL_GEN(ce->engine->i915));
1343 ce->tag = stream->specific_ctx_id;
1345 drm_dbg(&stream->perf->i915->drm,
1346 "filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
1347 stream->specific_ctx_id,
1348 stream->specific_ctx_id_mask);
1354 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1355 * @stream: An i915-perf stream opened for OA metrics
1357 * In case anything needed doing to ensure the context HW ID would remain valid
1358 * for the lifetime of the stream, then that can be undone here.
1360 static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1362 struct intel_context *ce;
1364 ce = fetch_and_zero(&stream->pinned_ctx);
1366 ce->tag = 0; /* recomputed on next submission after parking */
1367 intel_context_unpin(ce);
1370 stream->specific_ctx_id = INVALID_CTX_ID;
1371 stream->specific_ctx_id_mask = 0;
1375 free_oa_buffer(struct i915_perf_stream *stream)
1377 i915_vma_unpin_and_release(&stream->oa_buffer.vma,
1378 I915_VMA_RELEASE_MAP);
1380 stream->oa_buffer.vaddr = NULL;
1384 free_oa_configs(struct i915_perf_stream *stream)
1386 struct i915_oa_config_bo *oa_bo, *tmp;
1388 i915_oa_config_put(stream->oa_config);
1389 llist_for_each_entry_safe(oa_bo, tmp, stream->oa_config_bos.first, node)
1390 free_oa_config_bo(oa_bo);
1394 free_noa_wait(struct i915_perf_stream *stream)
1396 i915_vma_unpin_and_release(&stream->noa_wait, 0);
1399 static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1401 struct i915_perf *perf = stream->perf;
1403 BUG_ON(stream != perf->exclusive_stream);
1406 * Unset exclusive_stream first, it will be checked while disabling
1407 * the metric set on gen8+.
1409 * See i915_oa_init_reg_state() and lrc_configure_all_contexts()
1411 WRITE_ONCE(perf->exclusive_stream, NULL);
1412 perf->ops.disable_metric_set(stream);
1414 free_oa_buffer(stream);
1416 intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
1417 intel_engine_pm_put(stream->engine);
1420 oa_put_render_ctx_id(stream);
1422 free_oa_configs(stream);
1423 free_noa_wait(stream);
1425 if (perf->spurious_report_rs.missed) {
1426 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1427 perf->spurious_report_rs.missed);
1431 static void gen7_init_oa_buffer(struct i915_perf_stream *stream)
1433 struct intel_uncore *uncore = stream->uncore;
1434 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1435 unsigned long flags;
1437 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1439 /* Pre-DevBDW: OABUFFER must be set with counters off,
1440 * before OASTATUS1, but after OASTATUS2
1442 intel_uncore_write(uncore, GEN7_OASTATUS2, /* head */
1443 gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT);
1444 stream->oa_buffer.head = gtt_offset;
1446 intel_uncore_write(uncore, GEN7_OABUFFER, gtt_offset);
1448 intel_uncore_write(uncore, GEN7_OASTATUS1, /* tail */
1449 gtt_offset | OABUFFER_SIZE_16M);
1451 /* Mark that we need updated tail pointers to read from... */
1452 stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1453 stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1455 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1457 /* On Haswell we have to track which OASTATUS1 flags we've
1458 * already seen since they can't be cleared while periodic
1459 * sampling is enabled.
1461 stream->perf->gen7_latched_oastatus1 = 0;
1463 /* NB: although the OA buffer will initially be allocated
1464 * zeroed via shmfs (and so this memset is redundant when
1465 * first allocating), we may re-init the OA buffer, either
1466 * when re-enabling a stream or in error/reset paths.
1468 * The reason we clear the buffer for each re-init is for the
1469 * sanity check in gen7_append_oa_reports() that looks at the
1470 * report-id field to make sure it's non-zero which relies on
1471 * the assumption that new reports are being written to zeroed
1474 memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1476 stream->pollin = false;
1479 static void gen8_init_oa_buffer(struct i915_perf_stream *stream)
1481 struct intel_uncore *uncore = stream->uncore;
1482 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1483 unsigned long flags;
1485 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1487 intel_uncore_write(uncore, GEN8_OASTATUS, 0);
1488 intel_uncore_write(uncore, GEN8_OAHEADPTR, gtt_offset);
1489 stream->oa_buffer.head = gtt_offset;
1491 intel_uncore_write(uncore, GEN8_OABUFFER_UDW, 0);
1496 * "This MMIO must be set before the OATAILPTR
1497 * register and after the OAHEADPTR register. This is
1498 * to enable proper functionality of the overflow
1501 intel_uncore_write(uncore, GEN8_OABUFFER, gtt_offset |
1502 OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1503 intel_uncore_write(uncore, GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1505 /* Mark that we need updated tail pointers to read from... */
1506 stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1507 stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1510 * Reset state used to recognise context switches, affecting which
1511 * reports we will forward to userspace while filtering for a single
1514 stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1516 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1519 * NB: although the OA buffer will initially be allocated
1520 * zeroed via shmfs (and so this memset is redundant when
1521 * first allocating), we may re-init the OA buffer, either
1522 * when re-enabling a stream or in error/reset paths.
1524 * The reason we clear the buffer for each re-init is for the
1525 * sanity check in gen8_append_oa_reports() that looks at the
1526 * reason field to make sure it's non-zero which relies on
1527 * the assumption that new reports are being written to zeroed
1530 memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1532 stream->pollin = false;
1535 static void gen12_init_oa_buffer(struct i915_perf_stream *stream)
1537 struct intel_uncore *uncore = stream->uncore;
1538 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1539 unsigned long flags;
1541 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1543 intel_uncore_write(uncore, GEN12_OAG_OASTATUS, 0);
1544 intel_uncore_write(uncore, GEN12_OAG_OAHEADPTR,
1545 gtt_offset & GEN12_OAG_OAHEADPTR_MASK);
1546 stream->oa_buffer.head = gtt_offset;
1551 * "This MMIO must be set before the OATAILPTR
1552 * register and after the OAHEADPTR register. This is
1553 * to enable proper functionality of the overflow
1556 intel_uncore_write(uncore, GEN12_OAG_OABUFFER, gtt_offset |
1557 OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1558 intel_uncore_write(uncore, GEN12_OAG_OATAILPTR,
1559 gtt_offset & GEN12_OAG_OATAILPTR_MASK);
1561 /* Mark that we need updated tail pointers to read from... */
1562 stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1563 stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1566 * Reset state used to recognise context switches, affecting which
1567 * reports we will forward to userspace while filtering for a single
1570 stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1572 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1575 * NB: although the OA buffer will initially be allocated
1576 * zeroed via shmfs (and so this memset is redundant when
1577 * first allocating), we may re-init the OA buffer, either
1578 * when re-enabling a stream or in error/reset paths.
1580 * The reason we clear the buffer for each re-init is for the
1581 * sanity check in gen8_append_oa_reports() that looks at the
1582 * reason field to make sure it's non-zero which relies on
1583 * the assumption that new reports are being written to zeroed
1586 memset(stream->oa_buffer.vaddr, 0,
1587 stream->oa_buffer.vma->size);
1589 stream->pollin = false;
1592 static int alloc_oa_buffer(struct i915_perf_stream *stream)
1594 struct drm_i915_private *i915 = stream->perf->i915;
1595 struct drm_i915_gem_object *bo;
1596 struct i915_vma *vma;
1599 if (drm_WARN_ON(&i915->drm, stream->oa_buffer.vma))
1602 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1603 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1605 bo = i915_gem_object_create_shmem(stream->perf->i915, OA_BUFFER_SIZE);
1607 drm_err(&i915->drm, "Failed to allocate OA buffer\n");
1611 i915_gem_object_set_cache_coherency(bo, I915_CACHE_LLC);
1613 /* PreHSW required 512K alignment, HSW requires 16M */
1614 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1619 stream->oa_buffer.vma = vma;
1621 stream->oa_buffer.vaddr =
1622 i915_gem_object_pin_map(bo, I915_MAP_WB);
1623 if (IS_ERR(stream->oa_buffer.vaddr)) {
1624 ret = PTR_ERR(stream->oa_buffer.vaddr);
1631 __i915_vma_unpin(vma);
1634 i915_gem_object_put(bo);
1636 stream->oa_buffer.vaddr = NULL;
1637 stream->oa_buffer.vma = NULL;
1642 static u32 *save_restore_register(struct i915_perf_stream *stream, u32 *cs,
1643 bool save, i915_reg_t reg, u32 offset,
1649 cmd = save ? MI_STORE_REGISTER_MEM : MI_LOAD_REGISTER_MEM;
1650 if (INTEL_GEN(stream->perf->i915) >= 8)
1653 for (d = 0; d < dword_count; d++) {
1655 *cs++ = i915_mmio_reg_offset(reg) + 4 * d;
1656 *cs++ = intel_gt_scratch_offset(stream->engine->gt,
1664 static int alloc_noa_wait(struct i915_perf_stream *stream)
1666 struct drm_i915_private *i915 = stream->perf->i915;
1667 struct drm_i915_gem_object *bo;
1668 struct i915_vma *vma;
1669 const u64 delay_ticks = 0xffffffffffffffff -
1671 atomic64_read(&stream->perf->noa_programming_delay) *
1672 RUNTIME_INFO(i915)->cs_timestamp_frequency_khz,
1674 const u32 base = stream->engine->mmio_base;
1675 #define CS_GPR(x) GEN8_RING_CS_GPR(base, x)
1676 u32 *batch, *ts0, *cs, *jump;
1687 bo = i915_gem_object_create_internal(i915, 4096);
1690 "Failed to allocate NOA wait batchbuffer\n");
1695 * We pin in GGTT because we jump into this buffer now because
1696 * multiple OA config BOs will have a jump to this address and it
1697 * needs to be fixed during the lifetime of the i915/perf stream.
1699 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, 0, PIN_HIGH);
1705 batch = cs = i915_gem_object_pin_map(bo, I915_MAP_WB);
1706 if (IS_ERR(batch)) {
1707 ret = PTR_ERR(batch);
1711 /* Save registers. */
1712 for (i = 0; i < N_CS_GPR; i++)
1713 cs = save_restore_register(
1714 stream, cs, true /* save */, CS_GPR(i),
1715 INTEL_GT_SCRATCH_FIELD_PERF_CS_GPR + 8 * i, 2);
1716 cs = save_restore_register(
1717 stream, cs, true /* save */, MI_PREDICATE_RESULT_1,
1718 INTEL_GT_SCRATCH_FIELD_PERF_PREDICATE_RESULT_1, 1);
1720 /* First timestamp snapshot location. */
1724 * Initial snapshot of the timestamp register to implement the wait.
1725 * We work with 32b values, so clear out the top 32b bits of the
1726 * register because the ALU works 64bits.
1728 *cs++ = MI_LOAD_REGISTER_IMM(1);
1729 *cs++ = i915_mmio_reg_offset(CS_GPR(START_TS)) + 4;
1731 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1732 *cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
1733 *cs++ = i915_mmio_reg_offset(CS_GPR(START_TS));
1736 * This is the location we're going to jump back into until the
1737 * required amount of time has passed.
1742 * Take another snapshot of the timestamp register. Take care to clear
1743 * up the top 32bits of CS_GPR(1) as we're using it for other
1746 *cs++ = MI_LOAD_REGISTER_IMM(1);
1747 *cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS)) + 4;
1749 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1750 *cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
1751 *cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS));
1754 * Do a diff between the 2 timestamps and store the result back into
1758 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(NOW_TS));
1759 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(START_TS));
1760 *cs++ = MI_MATH_SUB;
1761 *cs++ = MI_MATH_STORE(MI_MATH_REG(DELTA_TS), MI_MATH_REG_ACCU);
1762 *cs++ = MI_MATH_STORE(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
1765 * Transfer the carry flag (set to 1 if ts1 < ts0, meaning the
1766 * timestamp have rolled over the 32bits) into the predicate register
1767 * to be used for the predicated jump.
1769 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1770 *cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
1771 *cs++ = i915_mmio_reg_offset(MI_PREDICATE_RESULT_1);
1773 /* Restart from the beginning if we had timestamps roll over. */
1774 *cs++ = (INTEL_GEN(i915) < 8 ?
1775 MI_BATCH_BUFFER_START :
1776 MI_BATCH_BUFFER_START_GEN8) |
1778 *cs++ = i915_ggtt_offset(vma) + (ts0 - batch) * 4;
1782 * Now add the diff between to previous timestamps and add it to :
1783 * (((1 * << 64) - 1) - delay_ns)
1785 * When the Carry Flag contains 1 this means the elapsed time is
1786 * longer than the expected delay, and we can exit the wait loop.
1788 *cs++ = MI_LOAD_REGISTER_IMM(2);
1789 *cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET));
1790 *cs++ = lower_32_bits(delay_ticks);
1791 *cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET)) + 4;
1792 *cs++ = upper_32_bits(delay_ticks);
1795 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(DELTA_TS));
1796 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(DELTA_TARGET));
1797 *cs++ = MI_MATH_ADD;
1798 *cs++ = MI_MATH_STOREINV(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
1800 *cs++ = MI_ARB_CHECK;
1803 * Transfer the result into the predicate register to be used for the
1806 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1807 *cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
1808 *cs++ = i915_mmio_reg_offset(MI_PREDICATE_RESULT_1);
1810 /* Predicate the jump. */
1811 *cs++ = (INTEL_GEN(i915) < 8 ?
1812 MI_BATCH_BUFFER_START :
1813 MI_BATCH_BUFFER_START_GEN8) |
1815 *cs++ = i915_ggtt_offset(vma) + (jump - batch) * 4;
1818 /* Restore registers. */
1819 for (i = 0; i < N_CS_GPR; i++)
1820 cs = save_restore_register(
1821 stream, cs, false /* restore */, CS_GPR(i),
1822 INTEL_GT_SCRATCH_FIELD_PERF_CS_GPR + 8 * i, 2);
1823 cs = save_restore_register(
1824 stream, cs, false /* restore */, MI_PREDICATE_RESULT_1,
1825 INTEL_GT_SCRATCH_FIELD_PERF_PREDICATE_RESULT_1, 1);
1827 /* And return to the ring. */
1828 *cs++ = MI_BATCH_BUFFER_END;
1830 GEM_BUG_ON(cs - batch > PAGE_SIZE / sizeof(*batch));
1832 i915_gem_object_flush_map(bo);
1833 i915_gem_object_unpin_map(bo);
1835 stream->noa_wait = vma;
1839 i915_vma_unpin_and_release(&vma, 0);
1841 i915_gem_object_put(bo);
1845 static u32 *write_cs_mi_lri(u32 *cs,
1846 const struct i915_oa_reg *reg_data,
1851 for (i = 0; i < n_regs; i++) {
1852 if ((i % MI_LOAD_REGISTER_IMM_MAX_REGS) == 0) {
1853 u32 n_lri = min_t(u32,
1855 MI_LOAD_REGISTER_IMM_MAX_REGS);
1857 *cs++ = MI_LOAD_REGISTER_IMM(n_lri);
1859 *cs++ = i915_mmio_reg_offset(reg_data[i].addr);
1860 *cs++ = reg_data[i].value;
1866 static int num_lri_dwords(int num_regs)
1871 count += DIV_ROUND_UP(num_regs, MI_LOAD_REGISTER_IMM_MAX_REGS);
1872 count += num_regs * 2;
1878 static struct i915_oa_config_bo *
1879 alloc_oa_config_buffer(struct i915_perf_stream *stream,
1880 struct i915_oa_config *oa_config)
1882 struct drm_i915_gem_object *obj;
1883 struct i915_oa_config_bo *oa_bo;
1884 size_t config_length = 0;
1888 oa_bo = kzalloc(sizeof(*oa_bo), GFP_KERNEL);
1890 return ERR_PTR(-ENOMEM);
1892 config_length += num_lri_dwords(oa_config->mux_regs_len);
1893 config_length += num_lri_dwords(oa_config->b_counter_regs_len);
1894 config_length += num_lri_dwords(oa_config->flex_regs_len);
1895 config_length += 3; /* MI_BATCH_BUFFER_START */
1896 config_length = ALIGN(sizeof(u32) * config_length, I915_GTT_PAGE_SIZE);
1898 obj = i915_gem_object_create_shmem(stream->perf->i915, config_length);
1904 cs = i915_gem_object_pin_map(obj, I915_MAP_WB);
1910 cs = write_cs_mi_lri(cs,
1911 oa_config->mux_regs,
1912 oa_config->mux_regs_len);
1913 cs = write_cs_mi_lri(cs,
1914 oa_config->b_counter_regs,
1915 oa_config->b_counter_regs_len);
1916 cs = write_cs_mi_lri(cs,
1917 oa_config->flex_regs,
1918 oa_config->flex_regs_len);
1920 /* Jump into the active wait. */
1921 *cs++ = (INTEL_GEN(stream->perf->i915) < 8 ?
1922 MI_BATCH_BUFFER_START :
1923 MI_BATCH_BUFFER_START_GEN8);
1924 *cs++ = i915_ggtt_offset(stream->noa_wait);
1927 i915_gem_object_flush_map(obj);
1928 i915_gem_object_unpin_map(obj);
1930 oa_bo->vma = i915_vma_instance(obj,
1931 &stream->engine->gt->ggtt->vm,
1933 if (IS_ERR(oa_bo->vma)) {
1934 err = PTR_ERR(oa_bo->vma);
1938 oa_bo->oa_config = i915_oa_config_get(oa_config);
1939 llist_add(&oa_bo->node, &stream->oa_config_bos);
1944 i915_gem_object_put(obj);
1947 return ERR_PTR(err);
1950 static struct i915_vma *
1951 get_oa_vma(struct i915_perf_stream *stream, struct i915_oa_config *oa_config)
1953 struct i915_oa_config_bo *oa_bo;
1956 * Look for the buffer in the already allocated BOs attached
1959 llist_for_each_entry(oa_bo, stream->oa_config_bos.first, node) {
1960 if (oa_bo->oa_config == oa_config &&
1961 memcmp(oa_bo->oa_config->uuid,
1963 sizeof(oa_config->uuid)) == 0)
1967 oa_bo = alloc_oa_config_buffer(stream, oa_config);
1969 return ERR_CAST(oa_bo);
1972 return i915_vma_get(oa_bo->vma);
1975 static struct i915_request *
1976 emit_oa_config(struct i915_perf_stream *stream,
1977 struct i915_oa_config *oa_config,
1978 struct intel_context *ce)
1980 struct i915_request *rq;
1981 struct i915_vma *vma;
1984 vma = get_oa_vma(stream, oa_config);
1986 return ERR_CAST(vma);
1988 err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
1992 intel_engine_pm_get(ce->engine);
1993 rq = i915_request_create(ce);
1994 intel_engine_pm_put(ce->engine);
2001 err = i915_request_await_object(rq, vma->obj, 0);
2003 err = i915_vma_move_to_active(vma, rq, 0);
2004 i915_vma_unlock(vma);
2006 goto err_add_request;
2008 err = rq->engine->emit_bb_start(rq,
2010 I915_DISPATCH_SECURE);
2012 goto err_add_request;
2014 i915_request_get(rq);
2016 i915_request_add(rq);
2018 i915_vma_unpin(vma);
2021 return err ? ERR_PTR(err) : rq;
2024 static struct intel_context *oa_context(struct i915_perf_stream *stream)
2026 return stream->pinned_ctx ?: stream->engine->kernel_context;
2029 static struct i915_request *
2030 hsw_enable_metric_set(struct i915_perf_stream *stream)
2032 struct intel_uncore *uncore = stream->uncore;
2037 * OA unit is using “crclk” for its functionality. When trunk
2038 * level clock gating takes place, OA clock would be gated,
2039 * unable to count the events from non-render clock domain.
2040 * Render clock gating must be disabled when OA is enabled to
2041 * count the events from non-render domain. Unit level clock
2042 * gating for RCS should also be disabled.
2044 intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
2045 GEN7_DOP_CLOCK_GATE_ENABLE, 0);
2046 intel_uncore_rmw(uncore, GEN6_UCGCTL1,
2047 0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
2049 return emit_oa_config(stream, stream->oa_config, oa_context(stream));
2052 static void hsw_disable_metric_set(struct i915_perf_stream *stream)
2054 struct intel_uncore *uncore = stream->uncore;
2056 intel_uncore_rmw(uncore, GEN6_UCGCTL1,
2057 GEN6_CSUNIT_CLOCK_GATE_DISABLE, 0);
2058 intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
2059 0, GEN7_DOP_CLOCK_GATE_ENABLE);
2061 intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2064 static u32 oa_config_flex_reg(const struct i915_oa_config *oa_config,
2067 u32 mmio = i915_mmio_reg_offset(reg);
2071 * This arbitrary default will select the 'EU FPU0 Pipeline
2072 * Active' event. In the future it's anticipated that there
2073 * will be an explicit 'No Event' we can select, but not yet...
2078 for (i = 0; i < oa_config->flex_regs_len; i++) {
2079 if (i915_mmio_reg_offset(oa_config->flex_regs[i].addr) == mmio)
2080 return oa_config->flex_regs[i].value;
2086 * NB: It must always remain pointer safe to run this even if the OA unit
2087 * has been disabled.
2089 * It's fine to put out-of-date values into these per-context registers
2090 * in the case that the OA unit has been disabled.
2093 gen8_update_reg_state_unlocked(const struct intel_context *ce,
2094 const struct i915_perf_stream *stream)
2096 u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
2097 u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2098 /* The MMIO offsets for Flex EU registers aren't contiguous */
2099 i915_reg_t flex_regs[] = {
2108 u32 *reg_state = ce->lrc_reg_state;
2111 reg_state[ctx_oactxctrl + 1] =
2112 (stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2113 (stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2114 GEN8_OA_COUNTER_RESUME;
2116 for (i = 0; i < ARRAY_SIZE(flex_regs); i++)
2117 reg_state[ctx_flexeu0 + i * 2 + 1] =
2118 oa_config_flex_reg(stream->oa_config, flex_regs[i]);
2120 reg_state[CTX_R_PWR_CLK_STATE] =
2121 intel_sseu_make_rpcs(ce->engine->i915, &ce->sseu);
2131 gen8_store_flex(struct i915_request *rq,
2132 struct intel_context *ce,
2133 const struct flex *flex, unsigned int count)
2138 cs = intel_ring_begin(rq, 4 * count);
2142 offset = i915_ggtt_offset(ce->state) + LRC_STATE_PN * PAGE_SIZE;
2144 *cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
2145 *cs++ = offset + flex->offset * sizeof(u32);
2147 *cs++ = flex->value;
2148 } while (flex++, --count);
2150 intel_ring_advance(rq, cs);
2156 gen8_load_flex(struct i915_request *rq,
2157 struct intel_context *ce,
2158 const struct flex *flex, unsigned int count)
2162 GEM_BUG_ON(!count || count > 63);
2164 cs = intel_ring_begin(rq, 2 * count + 2);
2168 *cs++ = MI_LOAD_REGISTER_IMM(count);
2170 *cs++ = i915_mmio_reg_offset(flex->reg);
2171 *cs++ = flex->value;
2172 } while (flex++, --count);
2175 intel_ring_advance(rq, cs);
2180 static int gen8_modify_context(struct intel_context *ce,
2181 const struct flex *flex, unsigned int count)
2183 struct i915_request *rq;
2186 rq = intel_engine_create_kernel_request(ce->engine);
2190 /* Serialise with the remote context */
2191 err = intel_context_prepare_remote_request(ce, rq);
2193 err = gen8_store_flex(rq, ce, flex, count);
2195 i915_request_add(rq);
2199 static int gen8_modify_self(struct intel_context *ce,
2200 const struct flex *flex, unsigned int count)
2202 struct i915_request *rq;
2205 intel_engine_pm_get(ce->engine);
2206 rq = i915_request_create(ce);
2207 intel_engine_pm_put(ce->engine);
2211 err = gen8_load_flex(rq, ce, flex, count);
2213 i915_request_add(rq);
2217 static int gen8_configure_context(struct i915_gem_context *ctx,
2218 struct flex *flex, unsigned int count)
2220 struct i915_gem_engines_iter it;
2221 struct intel_context *ce;
2224 for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
2225 GEM_BUG_ON(ce == ce->engine->kernel_context);
2227 if (ce->engine->class != RENDER_CLASS)
2230 /* Otherwise OA settings will be set upon first use */
2231 if (!intel_context_pin_if_active(ce))
2234 flex->value = intel_sseu_make_rpcs(ctx->i915, &ce->sseu);
2235 err = gen8_modify_context(ce, flex, count);
2237 intel_context_unpin(ce);
2241 i915_gem_context_unlock_engines(ctx);
2246 static int gen12_configure_oar_context(struct i915_perf_stream *stream, bool enable)
2249 struct intel_context *ce = stream->pinned_ctx;
2250 u32 format = stream->oa_buffer.format;
2251 struct flex regs_context[] = {
2254 stream->perf->ctx_oactxctrl_offset + 1,
2255 enable ? GEN8_OA_COUNTER_RESUME : 0,
2258 /* Offsets in regs_lri are not used since this configuration is only
2259 * applied using LRI. Initialize the correct offsets for posterity.
2261 #define GEN12_OAR_OACONTROL_OFFSET 0x5B0
2262 struct flex regs_lri[] = {
2264 GEN12_OAR_OACONTROL,
2265 GEN12_OAR_OACONTROL_OFFSET + 1,
2266 (format << GEN12_OAR_OACONTROL_COUNTER_FORMAT_SHIFT) |
2267 (enable ? GEN12_OAR_OACONTROL_COUNTER_ENABLE : 0)
2270 RING_CONTEXT_CONTROL(ce->engine->mmio_base),
2271 CTX_CONTEXT_CONTROL,
2272 _MASKED_FIELD(GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE,
2274 GEN12_CTX_CTRL_OAR_CONTEXT_ENABLE :
2279 /* Modify the context image of pinned context with regs_context*/
2280 err = intel_context_lock_pinned(ce);
2284 err = gen8_modify_context(ce, regs_context, ARRAY_SIZE(regs_context));
2285 intel_context_unlock_pinned(ce);
2289 /* Apply regs_lri using LRI with pinned context */
2290 return gen8_modify_self(ce, regs_lri, ARRAY_SIZE(regs_lri));
2294 * Manages updating the per-context aspects of the OA stream
2295 * configuration across all contexts.
2297 * The awkward consideration here is that OACTXCONTROL controls the
2298 * exponent for periodic sampling which is primarily used for system
2299 * wide profiling where we'd like a consistent sampling period even in
2300 * the face of context switches.
2302 * Our approach of updating the register state context (as opposed to
2303 * say using a workaround batch buffer) ensures that the hardware
2304 * won't automatically reload an out-of-date timer exponent even
2305 * transiently before a WA BB could be parsed.
2307 * This function needs to:
2308 * - Ensure the currently running context's per-context OA state is
2310 * - Ensure that all existing contexts will have the correct per-context
2311 * OA state if they are scheduled for use.
2312 * - Ensure any new contexts will be initialized with the correct
2313 * per-context OA state.
2315 * Note: it's only the RCS/Render context that has any OA state.
2316 * Note: the first flex register passed must always be R_PWR_CLK_STATE
2318 static int oa_configure_all_contexts(struct i915_perf_stream *stream,
2322 struct drm_i915_private *i915 = stream->perf->i915;
2323 struct intel_engine_cs *engine;
2324 struct i915_gem_context *ctx, *cn;
2327 lockdep_assert_held(&stream->perf->lock);
2330 * The OA register config is setup through the context image. This image
2331 * might be written to by the GPU on context switch (in particular on
2332 * lite-restore). This means we can't safely update a context's image,
2333 * if this context is scheduled/submitted to run on the GPU.
2335 * We could emit the OA register config through the batch buffer but
2336 * this might leave small interval of time where the OA unit is
2337 * configured at an invalid sampling period.
2339 * Note that since we emit all requests from a single ring, there
2340 * is still an implicit global barrier here that may cause a high
2341 * priority context to wait for an otherwise independent low priority
2342 * context. Contexts idle at the time of reconfiguration are not
2343 * trapped behind the barrier.
2345 spin_lock(&i915->gem.contexts.lock);
2346 list_for_each_entry_safe(ctx, cn, &i915->gem.contexts.list, link) {
2347 if (!kref_get_unless_zero(&ctx->ref))
2350 spin_unlock(&i915->gem.contexts.lock);
2352 err = gen8_configure_context(ctx, regs, num_regs);
2354 i915_gem_context_put(ctx);
2358 spin_lock(&i915->gem.contexts.lock);
2359 list_safe_reset_next(ctx, cn, link);
2360 i915_gem_context_put(ctx);
2362 spin_unlock(&i915->gem.contexts.lock);
2365 * After updating all other contexts, we need to modify ourselves.
2366 * If we don't modify the kernel_context, we do not get events while
2369 for_each_uabi_engine(engine, i915) {
2370 struct intel_context *ce = engine->kernel_context;
2372 if (engine->class != RENDER_CLASS)
2375 regs[0].value = intel_sseu_make_rpcs(i915, &ce->sseu);
2377 err = gen8_modify_self(ce, regs, num_regs);
2385 static int gen12_configure_all_contexts(struct i915_perf_stream *stream,
2386 const struct i915_oa_config *oa_config)
2388 struct flex regs[] = {
2390 GEN8_R_PWR_CLK_STATE,
2391 CTX_R_PWR_CLK_STATE,
2395 return oa_configure_all_contexts(stream, regs, ARRAY_SIZE(regs));
2398 static int lrc_configure_all_contexts(struct i915_perf_stream *stream,
2399 const struct i915_oa_config *oa_config)
2401 /* The MMIO offsets for Flex EU registers aren't contiguous */
2402 const u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2403 #define ctx_flexeuN(N) (ctx_flexeu0 + 2 * (N) + 1)
2404 struct flex regs[] = {
2406 GEN8_R_PWR_CLK_STATE,
2407 CTX_R_PWR_CLK_STATE,
2411 stream->perf->ctx_oactxctrl_offset + 1,
2413 { EU_PERF_CNTL0, ctx_flexeuN(0) },
2414 { EU_PERF_CNTL1, ctx_flexeuN(1) },
2415 { EU_PERF_CNTL2, ctx_flexeuN(2) },
2416 { EU_PERF_CNTL3, ctx_flexeuN(3) },
2417 { EU_PERF_CNTL4, ctx_flexeuN(4) },
2418 { EU_PERF_CNTL5, ctx_flexeuN(5) },
2419 { EU_PERF_CNTL6, ctx_flexeuN(6) },
2425 (stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2426 (stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2427 GEN8_OA_COUNTER_RESUME;
2429 for (i = 2; i < ARRAY_SIZE(regs); i++)
2430 regs[i].value = oa_config_flex_reg(oa_config, regs[i].reg);
2432 return oa_configure_all_contexts(stream, regs, ARRAY_SIZE(regs));
2435 static struct i915_request *
2436 gen8_enable_metric_set(struct i915_perf_stream *stream)
2438 struct intel_uncore *uncore = stream->uncore;
2439 struct i915_oa_config *oa_config = stream->oa_config;
2443 * We disable slice/unslice clock ratio change reports on SKL since
2444 * they are too noisy. The HW generates a lot of redundant reports
2445 * where the ratio hasn't really changed causing a lot of redundant
2446 * work to processes and increasing the chances we'll hit buffer
2449 * Although we don't currently use the 'disable overrun' OABUFFER
2450 * feature it's worth noting that clock ratio reports have to be
2451 * disabled before considering to use that feature since the HW doesn't
2452 * correctly block these reports.
2454 * Currently none of the high-level metrics we have depend on knowing
2455 * this ratio to normalize.
2457 * Note: This register is not power context saved and restored, but
2458 * that's OK considering that we disable RC6 while the OA unit is
2461 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
2462 * be read back from automatically triggered reports, as part of the
2465 if (IS_GEN_RANGE(stream->perf->i915, 9, 11)) {
2466 intel_uncore_write(uncore, GEN8_OA_DEBUG,
2467 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2468 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
2472 * Update all contexts prior writing the mux configurations as we need
2473 * to make sure all slices/subslices are ON before writing to NOA
2476 ret = lrc_configure_all_contexts(stream, oa_config);
2478 return ERR_PTR(ret);
2480 return emit_oa_config(stream, oa_config, oa_context(stream));
2483 static u32 oag_report_ctx_switches(const struct i915_perf_stream *stream)
2485 return _MASKED_FIELD(GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS,
2486 (stream->sample_flags & SAMPLE_OA_REPORT) ?
2487 0 : GEN12_OAG_OA_DEBUG_DISABLE_CTX_SWITCH_REPORTS);
2490 static struct i915_request *
2491 gen12_enable_metric_set(struct i915_perf_stream *stream)
2493 struct intel_uncore *uncore = stream->uncore;
2494 struct i915_oa_config *oa_config = stream->oa_config;
2495 bool periodic = stream->periodic;
2496 u32 period_exponent = stream->period_exponent;
2499 intel_uncore_write(uncore, GEN12_OAG_OA_DEBUG,
2500 /* Disable clk ratio reports, like previous Gens. */
2501 _MASKED_BIT_ENABLE(GEN12_OAG_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2502 GEN12_OAG_OA_DEBUG_INCLUDE_CLK_RATIO) |
2504 * If the user didn't require OA reports, instruct
2505 * the hardware not to emit ctx switch reports.
2507 oag_report_ctx_switches(stream));
2509 intel_uncore_write(uncore, GEN12_OAG_OAGLBCTXCTRL, periodic ?
2510 (GEN12_OAG_OAGLBCTXCTRL_COUNTER_RESUME |
2511 GEN12_OAG_OAGLBCTXCTRL_TIMER_ENABLE |
2512 (period_exponent << GEN12_OAG_OAGLBCTXCTRL_TIMER_PERIOD_SHIFT))
2516 * Update all contexts prior writing the mux configurations as we need
2517 * to make sure all slices/subslices are ON before writing to NOA
2520 ret = gen12_configure_all_contexts(stream, oa_config);
2522 return ERR_PTR(ret);
2525 * For Gen12, performance counters are context
2526 * saved/restored. Only enable it for the context that
2530 ret = gen12_configure_oar_context(stream, true);
2532 return ERR_PTR(ret);
2535 return emit_oa_config(stream, oa_config, oa_context(stream));
2538 static void gen8_disable_metric_set(struct i915_perf_stream *stream)
2540 struct intel_uncore *uncore = stream->uncore;
2542 /* Reset all contexts' slices/subslices configurations. */
2543 lrc_configure_all_contexts(stream, NULL);
2545 intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2548 static void gen10_disable_metric_set(struct i915_perf_stream *stream)
2550 struct intel_uncore *uncore = stream->uncore;
2552 /* Reset all contexts' slices/subslices configurations. */
2553 lrc_configure_all_contexts(stream, NULL);
2555 /* Make sure we disable noa to save power. */
2556 intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
2559 static void gen12_disable_metric_set(struct i915_perf_stream *stream)
2561 struct intel_uncore *uncore = stream->uncore;
2563 /* Reset all contexts' slices/subslices configurations. */
2564 gen12_configure_all_contexts(stream, NULL);
2566 /* disable the context save/restore or OAR counters */
2568 gen12_configure_oar_context(stream, false);
2570 /* Make sure we disable noa to save power. */
2571 intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
2574 static void gen7_oa_enable(struct i915_perf_stream *stream)
2576 struct intel_uncore *uncore = stream->uncore;
2577 struct i915_gem_context *ctx = stream->ctx;
2578 u32 ctx_id = stream->specific_ctx_id;
2579 bool periodic = stream->periodic;
2580 u32 period_exponent = stream->period_exponent;
2581 u32 report_format = stream->oa_buffer.format;
2584 * Reset buf pointers so we don't forward reports from before now.
2586 * Think carefully if considering trying to avoid this, since it
2587 * also ensures status flags and the buffer itself are cleared
2588 * in error paths, and we have checks for invalid reports based
2589 * on the assumption that certain fields are written to zeroed
2590 * memory which this helps maintains.
2592 gen7_init_oa_buffer(stream);
2594 intel_uncore_write(uncore, GEN7_OACONTROL,
2595 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
2597 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
2598 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
2599 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
2600 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
2601 GEN7_OACONTROL_ENABLE);
2604 static void gen8_oa_enable(struct i915_perf_stream *stream)
2606 struct intel_uncore *uncore = stream->uncore;
2607 u32 report_format = stream->oa_buffer.format;
2610 * Reset buf pointers so we don't forward reports from before now.
2612 * Think carefully if considering trying to avoid this, since it
2613 * also ensures status flags and the buffer itself are cleared
2614 * in error paths, and we have checks for invalid reports based
2615 * on the assumption that certain fields are written to zeroed
2616 * memory which this helps maintains.
2618 gen8_init_oa_buffer(stream);
2621 * Note: we don't rely on the hardware to perform single context
2622 * filtering and instead filter on the cpu based on the context-id
2625 intel_uncore_write(uncore, GEN8_OACONTROL,
2626 (report_format << GEN8_OA_REPORT_FORMAT_SHIFT) |
2627 GEN8_OA_COUNTER_ENABLE);
2630 static void gen12_oa_enable(struct i915_perf_stream *stream)
2632 struct intel_uncore *uncore = stream->uncore;
2633 u32 report_format = stream->oa_buffer.format;
2636 * If we don't want OA reports from the OA buffer, then we don't even
2637 * need to program the OAG unit.
2639 if (!(stream->sample_flags & SAMPLE_OA_REPORT))
2642 gen12_init_oa_buffer(stream);
2644 intel_uncore_write(uncore, GEN12_OAG_OACONTROL,
2645 (report_format << GEN12_OAG_OACONTROL_OA_COUNTER_FORMAT_SHIFT) |
2646 GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE);
2650 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
2651 * @stream: An i915 perf stream opened for OA metrics
2653 * [Re]enables hardware periodic sampling according to the period configured
2654 * when opening the stream. This also starts a hrtimer that will periodically
2655 * check for data in the circular OA buffer for notifying userspace (e.g.
2656 * during a read() or poll()).
2658 static void i915_oa_stream_enable(struct i915_perf_stream *stream)
2660 stream->perf->ops.oa_enable(stream);
2662 if (stream->periodic)
2663 hrtimer_start(&stream->poll_check_timer,
2664 ns_to_ktime(POLL_PERIOD),
2665 HRTIMER_MODE_REL_PINNED);
2668 static void gen7_oa_disable(struct i915_perf_stream *stream)
2670 struct intel_uncore *uncore = stream->uncore;
2672 intel_uncore_write(uncore, GEN7_OACONTROL, 0);
2673 if (intel_wait_for_register(uncore,
2674 GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
2676 drm_err(&stream->perf->i915->drm,
2677 "wait for OA to be disabled timed out\n");
2680 static void gen8_oa_disable(struct i915_perf_stream *stream)
2682 struct intel_uncore *uncore = stream->uncore;
2684 intel_uncore_write(uncore, GEN8_OACONTROL, 0);
2685 if (intel_wait_for_register(uncore,
2686 GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
2688 drm_err(&stream->perf->i915->drm,
2689 "wait for OA to be disabled timed out\n");
2692 static void gen12_oa_disable(struct i915_perf_stream *stream)
2694 struct intel_uncore *uncore = stream->uncore;
2696 intel_uncore_write(uncore, GEN12_OAG_OACONTROL, 0);
2697 if (intel_wait_for_register(uncore,
2698 GEN12_OAG_OACONTROL,
2699 GEN12_OAG_OACONTROL_OA_COUNTER_ENABLE, 0,
2701 drm_err(&stream->perf->i915->drm,
2702 "wait for OA to be disabled timed out\n");
2704 intel_uncore_write(uncore, GEN12_OA_TLB_INV_CR, 1);
2705 if (intel_wait_for_register(uncore,
2706 GEN12_OA_TLB_INV_CR,
2709 drm_err(&stream->perf->i915->drm,
2710 "wait for OA tlb invalidate timed out\n");
2714 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
2715 * @stream: An i915 perf stream opened for OA metrics
2717 * Stops the OA unit from periodically writing counter reports into the
2718 * circular OA buffer. This also stops the hrtimer that periodically checks for
2719 * data in the circular OA buffer, for notifying userspace.
2721 static void i915_oa_stream_disable(struct i915_perf_stream *stream)
2723 stream->perf->ops.oa_disable(stream);
2725 if (stream->periodic)
2726 hrtimer_cancel(&stream->poll_check_timer);
2729 static const struct i915_perf_stream_ops i915_oa_stream_ops = {
2730 .destroy = i915_oa_stream_destroy,
2731 .enable = i915_oa_stream_enable,
2732 .disable = i915_oa_stream_disable,
2733 .wait_unlocked = i915_oa_wait_unlocked,
2734 .poll_wait = i915_oa_poll_wait,
2735 .read = i915_oa_read,
2738 static int i915_perf_stream_enable_sync(struct i915_perf_stream *stream)
2740 struct i915_request *rq;
2742 rq = stream->perf->ops.enable_metric_set(stream);
2746 i915_request_wait(rq, 0, MAX_SCHEDULE_TIMEOUT);
2747 i915_request_put(rq);
2753 * i915_oa_stream_init - validate combined props for OA stream and init
2754 * @stream: An i915 perf stream
2755 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
2756 * @props: The property state that configures stream (individually validated)
2758 * While read_properties_unlocked() validates properties in isolation it
2759 * doesn't ensure that the combination necessarily makes sense.
2761 * At this point it has been determined that userspace wants a stream of
2762 * OA metrics, but still we need to further validate the combined
2763 * properties are OK.
2765 * If the configuration makes sense then we can allocate memory for
2766 * a circular OA buffer and apply the requested metric set configuration.
2768 * Returns: zero on success or a negative error code.
2770 static int i915_oa_stream_init(struct i915_perf_stream *stream,
2771 struct drm_i915_perf_open_param *param,
2772 struct perf_open_properties *props)
2774 struct drm_i915_private *i915 = stream->perf->i915;
2775 struct i915_perf *perf = stream->perf;
2779 if (!props->engine) {
2780 DRM_DEBUG("OA engine not specified\n");
2785 * If the sysfs metrics/ directory wasn't registered for some
2786 * reason then don't let userspace try their luck with config
2789 if (!perf->metrics_kobj) {
2790 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
2794 if (!(props->sample_flags & SAMPLE_OA_REPORT) &&
2795 (INTEL_GEN(perf->i915) < 12 || !stream->ctx)) {
2796 DRM_DEBUG("Only OA report sampling supported\n");
2800 if (!perf->ops.enable_metric_set) {
2801 DRM_DEBUG("OA unit not supported\n");
2806 * To avoid the complexity of having to accurately filter
2807 * counter reports and marshal to the appropriate client
2808 * we currently only allow exclusive access
2810 if (perf->exclusive_stream) {
2811 DRM_DEBUG("OA unit already in use\n");
2815 if (!props->oa_format) {
2816 DRM_DEBUG("OA report format not specified\n");
2820 stream->engine = props->engine;
2821 stream->uncore = stream->engine->gt->uncore;
2823 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2825 format_size = perf->oa_formats[props->oa_format].size;
2827 stream->sample_flags = props->sample_flags;
2828 stream->sample_size += format_size;
2830 stream->oa_buffer.format_size = format_size;
2831 if (drm_WARN_ON(&i915->drm, stream->oa_buffer.format_size == 0))
2834 stream->hold_preemption = props->hold_preemption;
2836 stream->oa_buffer.format =
2837 perf->oa_formats[props->oa_format].format;
2839 stream->periodic = props->oa_periodic;
2840 if (stream->periodic)
2841 stream->period_exponent = props->oa_period_exponent;
2844 ret = oa_get_render_ctx_id(stream);
2846 DRM_DEBUG("Invalid context id to filter with\n");
2851 ret = alloc_noa_wait(stream);
2853 DRM_DEBUG("Unable to allocate NOA wait batch buffer\n");
2854 goto err_noa_wait_alloc;
2857 stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
2858 if (!stream->oa_config) {
2859 DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set);
2864 /* PRM - observability performance counters:
2866 * OACONTROL, performance counter enable, note:
2868 * "When this bit is set, in order to have coherent counts,
2869 * RC6 power state and trunk clock gating must be disabled.
2870 * This can be achieved by programming MMIO registers as
2871 * 0xA094=0 and 0xA090[31]=1"
2873 * In our case we are expecting that taking pm + FORCEWAKE
2874 * references will effectively disable RC6.
2876 intel_engine_pm_get(stream->engine);
2877 intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
2879 ret = alloc_oa_buffer(stream);
2881 goto err_oa_buf_alloc;
2883 stream->ops = &i915_oa_stream_ops;
2884 WRITE_ONCE(perf->exclusive_stream, stream);
2886 ret = i915_perf_stream_enable_sync(stream);
2888 DRM_DEBUG("Unable to enable metric set\n");
2892 DRM_DEBUG("opening stream oa config uuid=%s\n",
2893 stream->oa_config->uuid);
2895 hrtimer_init(&stream->poll_check_timer,
2896 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2897 stream->poll_check_timer.function = oa_poll_check_timer_cb;
2898 init_waitqueue_head(&stream->poll_wq);
2899 spin_lock_init(&stream->oa_buffer.ptr_lock);
2904 WRITE_ONCE(perf->exclusive_stream, NULL);
2905 perf->ops.disable_metric_set(stream);
2907 free_oa_buffer(stream);
2910 free_oa_configs(stream);
2912 intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
2913 intel_engine_pm_put(stream->engine);
2916 free_noa_wait(stream);
2920 oa_put_render_ctx_id(stream);
2925 void i915_oa_init_reg_state(const struct intel_context *ce,
2926 const struct intel_engine_cs *engine)
2928 struct i915_perf_stream *stream;
2930 if (engine->class != RENDER_CLASS)
2933 /* perf.exclusive_stream serialised by lrc_configure_all_contexts() */
2934 stream = READ_ONCE(engine->i915->perf.exclusive_stream);
2936 * For gen12, only CTX_R_PWR_CLK_STATE needs update, but the caller
2937 * is already doing that, so nothing to be done for gen12 here.
2939 if (stream && INTEL_GEN(stream->perf->i915) < 12)
2940 gen8_update_reg_state_unlocked(ce, stream);
2944 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2945 * @stream: An i915 perf stream
2946 * @file: An i915 perf stream file
2947 * @buf: destination buffer given by userspace
2948 * @count: the number of bytes userspace wants to read
2949 * @ppos: (inout) file seek position (unused)
2951 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2952 * ensure that if we've successfully copied any data then reporting that takes
2953 * precedence over any internal error status, so the data isn't lost.
2955 * For example ret will be -ENOSPC whenever there is more buffered data than
2956 * can be copied to userspace, but that's only interesting if we weren't able
2957 * to copy some data because it implies the userspace buffer is too small to
2958 * receive a single record (and we never split records).
2960 * Another case with ret == -EFAULT is more of a grey area since it would seem
2961 * like bad form for userspace to ask us to overrun its buffer, but the user
2964 * http://yarchive.net/comp/linux/partial_reads_writes.html
2966 * Returns: The number of bytes copied or a negative error code on failure.
2968 static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2974 /* Note we keep the offset (aka bytes read) separate from any
2975 * error status so that the final check for whether we return
2976 * the bytes read with a higher precedence than any error (see
2977 * comment below) doesn't need to be handled/duplicated in
2978 * stream->ops->read() implementations.
2981 int ret = stream->ops->read(stream, buf, count, &offset);
2983 return offset ?: (ret ?: -EAGAIN);
2987 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2988 * @file: An i915 perf stream file
2989 * @buf: destination buffer given by userspace
2990 * @count: the number of bytes userspace wants to read
2991 * @ppos: (inout) file seek position (unused)
2993 * The entry point for handling a read() on a stream file descriptor from
2994 * userspace. Most of the work is left to the i915_perf_read_locked() and
2995 * &i915_perf_stream_ops->read but to save having stream implementations (of
2996 * which we might have multiple later) we handle blocking read here.
2998 * We can also consistently treat trying to read from a disabled stream
2999 * as an IO error so implementations can assume the stream is enabled
3002 * Returns: The number of bytes copied or a negative error code on failure.
3004 static ssize_t i915_perf_read(struct file *file,
3009 struct i915_perf_stream *stream = file->private_data;
3010 struct i915_perf *perf = stream->perf;
3013 /* To ensure it's handled consistently we simply treat all reads of a
3014 * disabled stream as an error. In particular it might otherwise lead
3015 * to a deadlock for blocking file descriptors...
3017 if (!stream->enabled)
3020 if (!(file->f_flags & O_NONBLOCK)) {
3021 /* There's the small chance of false positives from
3022 * stream->ops->wait_unlocked.
3024 * E.g. with single context filtering since we only wait until
3025 * oabuffer has >= 1 report we don't immediately know whether
3026 * any reports really belong to the current context
3029 ret = stream->ops->wait_unlocked(stream);
3033 mutex_lock(&perf->lock);
3034 ret = i915_perf_read_locked(stream, file,
3036 mutex_unlock(&perf->lock);
3037 } while (ret == -EAGAIN);
3039 mutex_lock(&perf->lock);
3040 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
3041 mutex_unlock(&perf->lock);
3044 /* We allow the poll checking to sometimes report false positive EPOLLIN
3045 * events where we might actually report EAGAIN on read() if there's
3046 * not really any data available. In this situation though we don't
3047 * want to enter a busy loop between poll() reporting a EPOLLIN event
3048 * and read() returning -EAGAIN. Clearing the oa.pollin state here
3049 * effectively ensures we back off until the next hrtimer callback
3050 * before reporting another EPOLLIN event.
3052 if (ret >= 0 || ret == -EAGAIN) {
3053 /* Maybe make ->pollin per-stream state if we support multiple
3054 * concurrent streams in the future.
3056 stream->pollin = false;
3062 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
3064 struct i915_perf_stream *stream =
3065 container_of(hrtimer, typeof(*stream), poll_check_timer);
3067 if (oa_buffer_check_unlocked(stream)) {
3068 stream->pollin = true;
3069 wake_up(&stream->poll_wq);
3072 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
3074 return HRTIMER_RESTART;
3078 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
3079 * @stream: An i915 perf stream
3080 * @file: An i915 perf stream file
3081 * @wait: poll() state table
3083 * For handling userspace polling on an i915 perf stream, this calls through to
3084 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
3085 * will be woken for new stream data.
3087 * Note: The &perf->lock mutex has been taken to serialize
3088 * with any non-file-operation driver hooks.
3090 * Returns: any poll events that are ready without sleeping
3092 static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
3096 __poll_t events = 0;
3098 stream->ops->poll_wait(stream, file, wait);
3100 /* Note: we don't explicitly check whether there's something to read
3101 * here since this path may be very hot depending on what else
3102 * userspace is polling, or on the timeout in use. We rely solely on
3103 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
3113 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
3114 * @file: An i915 perf stream file
3115 * @wait: poll() state table
3117 * For handling userspace polling on an i915 perf stream, this ensures
3118 * poll_wait() gets called with a wait queue that will be woken for new stream
3121 * Note: Implementation deferred to i915_perf_poll_locked()
3123 * Returns: any poll events that are ready without sleeping
3125 static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
3127 struct i915_perf_stream *stream = file->private_data;
3128 struct i915_perf *perf = stream->perf;
3131 mutex_lock(&perf->lock);
3132 ret = i915_perf_poll_locked(stream, file, wait);
3133 mutex_unlock(&perf->lock);
3139 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
3140 * @stream: A disabled i915 perf stream
3142 * [Re]enables the associated capture of data for this stream.
3144 * If a stream was previously enabled then there's currently no intention
3145 * to provide userspace any guarantee about the preservation of previously
3148 static void i915_perf_enable_locked(struct i915_perf_stream *stream)
3150 if (stream->enabled)
3153 /* Allow stream->ops->enable() to refer to this */
3154 stream->enabled = true;
3156 if (stream->ops->enable)
3157 stream->ops->enable(stream);
3159 if (stream->hold_preemption)
3160 intel_context_set_nopreempt(stream->pinned_ctx);
3164 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
3165 * @stream: An enabled i915 perf stream
3167 * Disables the associated capture of data for this stream.
3169 * The intention is that disabling an re-enabling a stream will ideally be
3170 * cheaper than destroying and re-opening a stream with the same configuration,
3171 * though there are no formal guarantees about what state or buffered data
3172 * must be retained between disabling and re-enabling a stream.
3174 * Note: while a stream is disabled it's considered an error for userspace
3175 * to attempt to read from the stream (-EIO).
3177 static void i915_perf_disable_locked(struct i915_perf_stream *stream)
3179 if (!stream->enabled)
3182 /* Allow stream->ops->disable() to refer to this */
3183 stream->enabled = false;
3185 if (stream->hold_preemption)
3186 intel_context_clear_nopreempt(stream->pinned_ctx);
3188 if (stream->ops->disable)
3189 stream->ops->disable(stream);
3192 static long i915_perf_config_locked(struct i915_perf_stream *stream,
3193 unsigned long metrics_set)
3195 struct i915_oa_config *config;
3196 long ret = stream->oa_config->id;
3198 config = i915_perf_get_oa_config(stream->perf, metrics_set);
3202 if (config != stream->oa_config) {
3203 struct i915_request *rq;
3206 * If OA is bound to a specific context, emit the
3207 * reconfiguration inline from that context. The update
3208 * will then be ordered with respect to submission on that
3211 * When set globally, we use a low priority kernel context,
3212 * so it will effectively take effect when idle.
3214 rq = emit_oa_config(stream, config, oa_context(stream));
3216 config = xchg(&stream->oa_config, config);
3217 i915_request_put(rq);
3223 i915_oa_config_put(config);
3229 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
3230 * @stream: An i915 perf stream
3231 * @cmd: the ioctl request
3232 * @arg: the ioctl data
3234 * Note: The &perf->lock mutex has been taken to serialize
3235 * with any non-file-operation driver hooks.
3237 * Returns: zero on success or a negative error code. Returns -EINVAL for
3238 * an unknown ioctl request.
3240 static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
3245 case I915_PERF_IOCTL_ENABLE:
3246 i915_perf_enable_locked(stream);
3248 case I915_PERF_IOCTL_DISABLE:
3249 i915_perf_disable_locked(stream);
3251 case I915_PERF_IOCTL_CONFIG:
3252 return i915_perf_config_locked(stream, arg);
3259 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
3260 * @file: An i915 perf stream file
3261 * @cmd: the ioctl request
3262 * @arg: the ioctl data
3264 * Implementation deferred to i915_perf_ioctl_locked().
3266 * Returns: zero on success or a negative error code. Returns -EINVAL for
3267 * an unknown ioctl request.
3269 static long i915_perf_ioctl(struct file *file,
3273 struct i915_perf_stream *stream = file->private_data;
3274 struct i915_perf *perf = stream->perf;
3277 mutex_lock(&perf->lock);
3278 ret = i915_perf_ioctl_locked(stream, cmd, arg);
3279 mutex_unlock(&perf->lock);
3285 * i915_perf_destroy_locked - destroy an i915 perf stream
3286 * @stream: An i915 perf stream
3288 * Frees all resources associated with the given i915 perf @stream, disabling
3289 * any associated data capture in the process.
3291 * Note: The &perf->lock mutex has been taken to serialize
3292 * with any non-file-operation driver hooks.
3294 static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
3296 if (stream->enabled)
3297 i915_perf_disable_locked(stream);
3299 if (stream->ops->destroy)
3300 stream->ops->destroy(stream);
3303 i915_gem_context_put(stream->ctx);
3309 * i915_perf_release - handles userspace close() of a stream file
3310 * @inode: anonymous inode associated with file
3311 * @file: An i915 perf stream file
3313 * Cleans up any resources associated with an open i915 perf stream file.
3315 * NB: close() can't really fail from the userspace point of view.
3317 * Returns: zero on success or a negative error code.
3319 static int i915_perf_release(struct inode *inode, struct file *file)
3321 struct i915_perf_stream *stream = file->private_data;
3322 struct i915_perf *perf = stream->perf;
3324 mutex_lock(&perf->lock);
3325 i915_perf_destroy_locked(stream);
3326 mutex_unlock(&perf->lock);
3328 /* Release the reference the perf stream kept on the driver. */
3329 drm_dev_put(&perf->i915->drm);
3335 static const struct file_operations fops = {
3336 .owner = THIS_MODULE,
3337 .llseek = no_llseek,
3338 .release = i915_perf_release,
3339 .poll = i915_perf_poll,
3340 .read = i915_perf_read,
3341 .unlocked_ioctl = i915_perf_ioctl,
3342 /* Our ioctl have no arguments, so it's safe to use the same function
3343 * to handle 32bits compatibility.
3345 .compat_ioctl = i915_perf_ioctl,
3350 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
3351 * @perf: i915 perf instance
3352 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
3353 * @props: individually validated u64 property value pairs
3356 * See i915_perf_ioctl_open() for interface details.
3358 * Implements further stream config validation and stream initialization on
3359 * behalf of i915_perf_open_ioctl() with the &perf->lock mutex
3360 * taken to serialize with any non-file-operation driver hooks.
3362 * Note: at this point the @props have only been validated in isolation and
3363 * it's still necessary to validate that the combination of properties makes
3366 * In the case where userspace is interested in OA unit metrics then further
3367 * config validation and stream initialization details will be handled by
3368 * i915_oa_stream_init(). The code here should only validate config state that
3369 * will be relevant to all stream types / backends.
3371 * Returns: zero on success or a negative error code.
3374 i915_perf_open_ioctl_locked(struct i915_perf *perf,
3375 struct drm_i915_perf_open_param *param,
3376 struct perf_open_properties *props,
3377 struct drm_file *file)
3379 struct i915_gem_context *specific_ctx = NULL;
3380 struct i915_perf_stream *stream = NULL;
3381 unsigned long f_flags = 0;
3382 bool privileged_op = true;
3386 if (props->single_context) {
3387 u32 ctx_handle = props->ctx_handle;
3388 struct drm_i915_file_private *file_priv = file->driver_priv;
3390 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
3391 if (!specific_ctx) {
3392 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
3400 * On Haswell the OA unit supports clock gating off for a specific
3401 * context and in this mode there's no visibility of metrics for the
3402 * rest of the system, which we consider acceptable for a
3403 * non-privileged client.
3405 * For Gen8->11 the OA unit no longer supports clock gating off for a
3406 * specific context and the kernel can't securely stop the counters
3407 * from updating as system-wide / global values. Even though we can
3408 * filter reports based on the included context ID we can't block
3409 * clients from seeing the raw / global counter values via
3410 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
3411 * enable the OA unit by default.
3413 * For Gen12+ we gain a new OAR unit that only monitors the RCS on a
3414 * per context basis. So we can relax requirements there if the user
3415 * doesn't request global stream access (i.e. query based sampling
3416 * using MI_RECORD_PERF_COUNT.
3418 if (IS_HASWELL(perf->i915) && specific_ctx)
3419 privileged_op = false;
3420 else if (IS_GEN(perf->i915, 12) && specific_ctx &&
3421 (props->sample_flags & SAMPLE_OA_REPORT) == 0)
3422 privileged_op = false;
3424 if (props->hold_preemption) {
3425 if (!props->single_context) {
3426 DRM_DEBUG("preemption disable with no context\n");
3430 privileged_op = true;
3433 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
3434 * we check a dev.i915.perf_stream_paranoid sysctl option
3435 * to determine if it's ok to access system wide OA counters
3436 * without CAP_SYS_ADMIN privileges.
3438 if (privileged_op &&
3439 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3440 DRM_DEBUG("Insufficient privileges to open i915 perf stream\n");
3445 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
3451 stream->perf = perf;
3452 stream->ctx = specific_ctx;
3454 ret = i915_oa_stream_init(stream, param, props);
3458 /* we avoid simply assigning stream->sample_flags = props->sample_flags
3459 * to have _stream_init check the combination of sample flags more
3460 * thoroughly, but still this is the expected result at this point.
3462 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
3467 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
3468 f_flags |= O_CLOEXEC;
3469 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
3470 f_flags |= O_NONBLOCK;
3472 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
3473 if (stream_fd < 0) {
3478 if (!(param->flags & I915_PERF_FLAG_DISABLED))
3479 i915_perf_enable_locked(stream);
3481 /* Take a reference on the driver that will be kept with stream_fd
3482 * until its release.
3484 drm_dev_get(&perf->i915->drm);
3489 if (stream->ops->destroy)
3490 stream->ops->destroy(stream);
3495 i915_gem_context_put(specific_ctx);
3500 static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
3502 return div64_u64(1000000000ULL * (2ULL << exponent),
3503 1000ULL * RUNTIME_INFO(perf->i915)->cs_timestamp_frequency_khz);
3507 * read_properties_unlocked - validate + copy userspace stream open properties
3508 * @perf: i915 perf instance
3509 * @uprops: The array of u64 key value pairs given by userspace
3510 * @n_props: The number of key value pairs expected in @uprops
3511 * @props: The stream configuration built up while validating properties
3513 * Note this function only validates properties in isolation it doesn't
3514 * validate that the combination of properties makes sense or that all
3515 * properties necessary for a particular kind of stream have been set.
3517 * Note that there currently aren't any ordering requirements for properties so
3518 * we shouldn't validate or assume anything about ordering here. This doesn't
3519 * rule out defining new properties with ordering requirements in the future.
3521 static int read_properties_unlocked(struct i915_perf *perf,
3524 struct perf_open_properties *props)
3526 u64 __user *uprop = uprops;
3529 memset(props, 0, sizeof(struct perf_open_properties));
3532 DRM_DEBUG("No i915 perf properties given\n");
3536 /* At the moment we only support using i915-perf on the RCS. */
3537 props->engine = intel_engine_lookup_user(perf->i915,
3538 I915_ENGINE_CLASS_RENDER,
3540 if (!props->engine) {
3541 DRM_DEBUG("No RENDER-capable engines\n");
3545 /* Considering that ID = 0 is reserved and assuming that we don't
3546 * (currently) expect any configurations to ever specify duplicate
3547 * values for a particular property ID then the last _PROP_MAX value is
3548 * one greater than the maximum number of properties we expect to get
3551 if (n_props >= DRM_I915_PERF_PROP_MAX) {
3552 DRM_DEBUG("More i915 perf properties specified than exist\n");
3556 for (i = 0; i < n_props; i++) {
3557 u64 oa_period, oa_freq_hz;
3561 ret = get_user(id, uprop);
3565 ret = get_user(value, uprop + 1);
3569 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
3570 DRM_DEBUG("Unknown i915 perf property ID\n");
3574 switch ((enum drm_i915_perf_property_id)id) {
3575 case DRM_I915_PERF_PROP_CTX_HANDLE:
3576 props->single_context = 1;
3577 props->ctx_handle = value;
3579 case DRM_I915_PERF_PROP_SAMPLE_OA:
3581 props->sample_flags |= SAMPLE_OA_REPORT;
3583 case DRM_I915_PERF_PROP_OA_METRICS_SET:
3585 DRM_DEBUG("Unknown OA metric set ID\n");
3588 props->metrics_set = value;
3590 case DRM_I915_PERF_PROP_OA_FORMAT:
3591 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
3592 DRM_DEBUG("Out-of-range OA report format %llu\n",
3596 if (!perf->oa_formats[value].size) {
3597 DRM_DEBUG("Unsupported OA report format %llu\n",
3601 props->oa_format = value;
3603 case DRM_I915_PERF_PROP_OA_EXPONENT:
3604 if (value > OA_EXPONENT_MAX) {
3605 DRM_DEBUG("OA timer exponent too high (> %u)\n",
3610 /* Theoretically we can program the OA unit to sample
3611 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
3612 * for BXT. We don't allow such high sampling
3613 * frequencies by default unless root.
3616 BUILD_BUG_ON(sizeof(oa_period) != 8);
3617 oa_period = oa_exponent_to_ns(perf, value);
3619 /* This check is primarily to ensure that oa_period <=
3620 * UINT32_MAX (before passing to do_div which only
3621 * accepts a u32 denominator), but we can also skip
3622 * checking anything < 1Hz which implicitly can't be
3623 * limited via an integer oa_max_sample_rate.
3625 if (oa_period <= NSEC_PER_SEC) {
3626 u64 tmp = NSEC_PER_SEC;
3627 do_div(tmp, oa_period);
3632 if (oa_freq_hz > i915_oa_max_sample_rate &&
3633 !capable(CAP_SYS_ADMIN)) {
3634 DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
3635 i915_oa_max_sample_rate);
3639 props->oa_periodic = true;
3640 props->oa_period_exponent = value;
3642 case DRM_I915_PERF_PROP_HOLD_PREEMPTION:
3643 props->hold_preemption = !!value;
3645 case DRM_I915_PERF_PROP_MAX:
3657 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
3659 * @data: ioctl data copied from userspace (unvalidated)
3662 * Validates the stream open parameters given by userspace including flags
3663 * and an array of u64 key, value pair properties.
3665 * Very little is assumed up front about the nature of the stream being
3666 * opened (for instance we don't assume it's for periodic OA unit metrics). An
3667 * i915-perf stream is expected to be a suitable interface for other forms of
3668 * buffered data written by the GPU besides periodic OA metrics.
3670 * Note we copy the properties from userspace outside of the i915 perf
3671 * mutex to avoid an awkward lockdep with mmap_sem.
3673 * Most of the implementation details are handled by
3674 * i915_perf_open_ioctl_locked() after taking the &perf->lock
3675 * mutex for serializing with any non-file-operation driver hooks.
3677 * Return: A newly opened i915 Perf stream file descriptor or negative
3678 * error code on failure.
3680 int i915_perf_open_ioctl(struct drm_device *dev, void *data,
3681 struct drm_file *file)
3683 struct i915_perf *perf = &to_i915(dev)->perf;
3684 struct drm_i915_perf_open_param *param = data;
3685 struct perf_open_properties props;
3686 u32 known_open_flags;
3690 DRM_DEBUG("i915 perf interface not available for this system\n");
3694 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
3695 I915_PERF_FLAG_FD_NONBLOCK |
3696 I915_PERF_FLAG_DISABLED;
3697 if (param->flags & ~known_open_flags) {
3698 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
3702 ret = read_properties_unlocked(perf,
3703 u64_to_user_ptr(param->properties_ptr),
3704 param->num_properties,
3709 mutex_lock(&perf->lock);
3710 ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
3711 mutex_unlock(&perf->lock);
3717 * i915_perf_register - exposes i915-perf to userspace
3718 * @i915: i915 device instance
3720 * In particular OA metric sets are advertised under a sysfs metrics/
3721 * directory allowing userspace to enumerate valid IDs that can be
3722 * used to open an i915-perf stream.
3724 void i915_perf_register(struct drm_i915_private *i915)
3726 struct i915_perf *perf = &i915->perf;
3732 /* To be sure we're synchronized with an attempted
3733 * i915_perf_open_ioctl(); considering that we register after
3734 * being exposed to userspace.
3736 mutex_lock(&perf->lock);
3738 perf->metrics_kobj =
3739 kobject_create_and_add("metrics",
3740 &i915->drm.primary->kdev->kobj);
3741 if (!perf->metrics_kobj)
3744 sysfs_attr_init(&perf->test_config.sysfs_metric_id.attr);
3746 if (IS_TIGERLAKE(i915)) {
3747 i915_perf_load_test_config_tgl(i915);
3748 } else if (INTEL_GEN(i915) >= 11) {
3749 i915_perf_load_test_config_icl(i915);
3750 } else if (IS_CANNONLAKE(i915)) {
3751 i915_perf_load_test_config_cnl(i915);
3752 } else if (IS_COFFEELAKE(i915)) {
3753 if (IS_CFL_GT2(i915))
3754 i915_perf_load_test_config_cflgt2(i915);
3755 if (IS_CFL_GT3(i915))
3756 i915_perf_load_test_config_cflgt3(i915);
3757 } else if (IS_GEMINILAKE(i915)) {
3758 i915_perf_load_test_config_glk(i915);
3759 } else if (IS_KABYLAKE(i915)) {
3760 if (IS_KBL_GT2(i915))
3761 i915_perf_load_test_config_kblgt2(i915);
3762 else if (IS_KBL_GT3(i915))
3763 i915_perf_load_test_config_kblgt3(i915);
3764 } else if (IS_BROXTON(i915)) {
3765 i915_perf_load_test_config_bxt(i915);
3766 } else if (IS_SKYLAKE(i915)) {
3767 if (IS_SKL_GT2(i915))
3768 i915_perf_load_test_config_sklgt2(i915);
3769 else if (IS_SKL_GT3(i915))
3770 i915_perf_load_test_config_sklgt3(i915);
3771 else if (IS_SKL_GT4(i915))
3772 i915_perf_load_test_config_sklgt4(i915);
3773 } else if (IS_CHERRYVIEW(i915)) {
3774 i915_perf_load_test_config_chv(i915);
3775 } else if (IS_BROADWELL(i915)) {
3776 i915_perf_load_test_config_bdw(i915);
3777 } else if (IS_HASWELL(i915)) {
3778 i915_perf_load_test_config_hsw(i915);
3781 if (perf->test_config.id == 0)
3784 ret = sysfs_create_group(perf->metrics_kobj,
3785 &perf->test_config.sysfs_metric);
3789 perf->test_config.perf = perf;
3790 kref_init(&perf->test_config.ref);
3795 kobject_put(perf->metrics_kobj);
3796 perf->metrics_kobj = NULL;
3799 mutex_unlock(&perf->lock);
3803 * i915_perf_unregister - hide i915-perf from userspace
3804 * @i915: i915 device instance
3806 * i915-perf state cleanup is split up into an 'unregister' and
3807 * 'deinit' phase where the interface is first hidden from
3808 * userspace by i915_perf_unregister() before cleaning up
3809 * remaining state in i915_perf_fini().
3811 void i915_perf_unregister(struct drm_i915_private *i915)
3813 struct i915_perf *perf = &i915->perf;
3815 if (!perf->metrics_kobj)
3818 sysfs_remove_group(perf->metrics_kobj,
3819 &perf->test_config.sysfs_metric);
3821 kobject_put(perf->metrics_kobj);
3822 perf->metrics_kobj = NULL;
3825 static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
3827 static const i915_reg_t flex_eu_regs[] = {
3838 for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
3839 if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
3845 #define ADDR_IN_RANGE(addr, start, end) \
3846 ((addr) >= (start) && \
3849 #define REG_IN_RANGE(addr, start, end) \
3850 ((addr) >= i915_mmio_reg_offset(start) && \
3851 (addr) <= i915_mmio_reg_offset(end))
3853 #define REG_EQUAL(addr, mmio) \
3854 ((addr) == i915_mmio_reg_offset(mmio))
3856 static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
3858 return REG_IN_RANGE(addr, OASTARTTRIG1, OASTARTTRIG8) ||
3859 REG_IN_RANGE(addr, OAREPORTTRIG1, OAREPORTTRIG8) ||
3860 REG_IN_RANGE(addr, OACEC0_0, OACEC7_1);
3863 static bool gen7_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3865 return REG_EQUAL(addr, HALF_SLICE_CHICKEN2) ||
3866 REG_IN_RANGE(addr, MICRO_BP0_0, NOA_WRITE) ||
3867 REG_IN_RANGE(addr, OA_PERFCNT1_LO, OA_PERFCNT2_HI) ||
3868 REG_IN_RANGE(addr, OA_PERFMATRIX_LO, OA_PERFMATRIX_HI);
3871 static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3873 return gen7_is_valid_mux_addr(perf, addr) ||
3874 REG_EQUAL(addr, WAIT_FOR_RC6_EXIT) ||
3875 REG_IN_RANGE(addr, RPM_CONFIG0, NOA_CONFIG(8));
3878 static bool gen10_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3880 return gen8_is_valid_mux_addr(perf, addr) ||
3881 REG_EQUAL(addr, GEN10_NOA_WRITE_HIGH) ||
3882 REG_IN_RANGE(addr, OA_PERFCNT3_LO, OA_PERFCNT4_HI);
3885 static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3887 return gen7_is_valid_mux_addr(perf, addr) ||
3888 ADDR_IN_RANGE(addr, 0x25100, 0x2FF90) ||
3889 REG_IN_RANGE(addr, HSW_MBVID2_NOA0, HSW_MBVID2_NOA9) ||
3890 REG_EQUAL(addr, HSW_MBVID2_MISR0);
3893 static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3895 return gen7_is_valid_mux_addr(perf, addr) ||
3896 ADDR_IN_RANGE(addr, 0x182300, 0x1823A4);
3899 static bool gen12_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
3901 return REG_IN_RANGE(addr, GEN12_OAG_OASTARTTRIG1, GEN12_OAG_OASTARTTRIG8) ||
3902 REG_IN_RANGE(addr, GEN12_OAG_OAREPORTTRIG1, GEN12_OAG_OAREPORTTRIG8) ||
3903 REG_IN_RANGE(addr, GEN12_OAG_CEC0_0, GEN12_OAG_CEC7_1) ||
3904 REG_IN_RANGE(addr, GEN12_OAG_SCEC0_0, GEN12_OAG_SCEC7_1) ||
3905 REG_EQUAL(addr, GEN12_OAA_DBG_REG) ||
3906 REG_EQUAL(addr, GEN12_OAG_OA_PESS) ||
3907 REG_EQUAL(addr, GEN12_OAG_SPCTR_CNF);
3910 static bool gen12_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3912 return REG_EQUAL(addr, NOA_WRITE) ||
3913 REG_EQUAL(addr, GEN10_NOA_WRITE_HIGH) ||
3914 REG_EQUAL(addr, GDT_CHICKEN_BITS) ||
3915 REG_EQUAL(addr, WAIT_FOR_RC6_EXIT) ||
3916 REG_EQUAL(addr, RPM_CONFIG0) ||
3917 REG_EQUAL(addr, RPM_CONFIG1) ||
3918 REG_IN_RANGE(addr, NOA_CONFIG(0), NOA_CONFIG(8));
3921 static u32 mask_reg_value(u32 reg, u32 val)
3923 /* HALF_SLICE_CHICKEN2 is programmed with a the
3924 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
3925 * programmed by userspace doesn't change this.
3927 if (REG_EQUAL(reg, HALF_SLICE_CHICKEN2))
3928 val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
3930 /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
3931 * indicated by its name and a bunch of selection fields used by OA
3934 if (REG_EQUAL(reg, WAIT_FOR_RC6_EXIT))
3935 val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
3940 static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
3941 bool (*is_valid)(struct i915_perf *perf, u32 addr),
3945 struct i915_oa_reg *oa_regs;
3952 if (!access_ok(regs, n_regs * sizeof(u32) * 2))
3953 return ERR_PTR(-EFAULT);
3955 /* No is_valid function means we're not allowing any register to be programmed. */
3956 GEM_BUG_ON(!is_valid);
3958 return ERR_PTR(-EINVAL);
3960 oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
3962 return ERR_PTR(-ENOMEM);
3964 for (i = 0; i < n_regs; i++) {
3967 err = get_user(addr, regs);
3971 if (!is_valid(perf, addr)) {
3972 DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
3977 err = get_user(value, regs + 1);
3981 oa_regs[i].addr = _MMIO(addr);
3982 oa_regs[i].value = mask_reg_value(addr, value);
3991 return ERR_PTR(err);
3994 static ssize_t show_dynamic_id(struct device *dev,
3995 struct device_attribute *attr,
3998 struct i915_oa_config *oa_config =
3999 container_of(attr, typeof(*oa_config), sysfs_metric_id);
4001 return sprintf(buf, "%d\n", oa_config->id);
4004 static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
4005 struct i915_oa_config *oa_config)
4007 sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
4008 oa_config->sysfs_metric_id.attr.name = "id";
4009 oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
4010 oa_config->sysfs_metric_id.show = show_dynamic_id;
4011 oa_config->sysfs_metric_id.store = NULL;
4013 oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
4014 oa_config->attrs[1] = NULL;
4016 oa_config->sysfs_metric.name = oa_config->uuid;
4017 oa_config->sysfs_metric.attrs = oa_config->attrs;
4019 return sysfs_create_group(perf->metrics_kobj,
4020 &oa_config->sysfs_metric);
4024 * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
4026 * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
4027 * userspace (unvalidated)
4030 * Validates the submitted OA register to be saved into a new OA config that
4031 * can then be used for programming the OA unit and its NOA network.
4033 * Returns: A new allocated config number to be used with the perf open ioctl
4034 * or a negative error code on failure.
4036 int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
4037 struct drm_file *file)
4039 struct i915_perf *perf = &to_i915(dev)->perf;
4040 struct drm_i915_perf_oa_config *args = data;
4041 struct i915_oa_config *oa_config, *tmp;
4042 struct i915_oa_reg *regs;
4046 DRM_DEBUG("i915 perf interface not available for this system\n");
4050 if (!perf->metrics_kobj) {
4051 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
4055 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
4056 DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
4060 if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
4061 (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
4062 (!args->flex_regs_ptr || !args->n_flex_regs)) {
4063 DRM_DEBUG("No OA registers given\n");
4067 oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
4069 DRM_DEBUG("Failed to allocate memory for the OA config\n");
4073 oa_config->perf = perf;
4074 kref_init(&oa_config->ref);
4076 if (!uuid_is_valid(args->uuid)) {
4077 DRM_DEBUG("Invalid uuid format for OA config\n");
4082 /* Last character in oa_config->uuid will be 0 because oa_config is
4085 memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
4087 oa_config->mux_regs_len = args->n_mux_regs;
4088 regs = alloc_oa_regs(perf,
4089 perf->ops.is_valid_mux_reg,
4090 u64_to_user_ptr(args->mux_regs_ptr),
4094 DRM_DEBUG("Failed to create OA config for mux_regs\n");
4095 err = PTR_ERR(regs);
4098 oa_config->mux_regs = regs;
4100 oa_config->b_counter_regs_len = args->n_boolean_regs;
4101 regs = alloc_oa_regs(perf,
4102 perf->ops.is_valid_b_counter_reg,
4103 u64_to_user_ptr(args->boolean_regs_ptr),
4104 args->n_boolean_regs);
4107 DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
4108 err = PTR_ERR(regs);
4111 oa_config->b_counter_regs = regs;
4113 if (INTEL_GEN(perf->i915) < 8) {
4114 if (args->n_flex_regs != 0) {
4119 oa_config->flex_regs_len = args->n_flex_regs;
4120 regs = alloc_oa_regs(perf,
4121 perf->ops.is_valid_flex_reg,
4122 u64_to_user_ptr(args->flex_regs_ptr),
4126 DRM_DEBUG("Failed to create OA config for flex_regs\n");
4127 err = PTR_ERR(regs);
4130 oa_config->flex_regs = regs;
4133 err = mutex_lock_interruptible(&perf->metrics_lock);
4137 /* We shouldn't have too many configs, so this iteration shouldn't be
4140 idr_for_each_entry(&perf->metrics_idr, tmp, id) {
4141 if (!strcmp(tmp->uuid, oa_config->uuid)) {
4142 DRM_DEBUG("OA config already exists with this uuid\n");
4148 err = create_dynamic_oa_sysfs_entry(perf, oa_config);
4150 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
4154 /* Config id 0 is invalid, id 1 for kernel stored test config. */
4155 oa_config->id = idr_alloc(&perf->metrics_idr,
4158 if (oa_config->id < 0) {
4159 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
4160 err = oa_config->id;
4164 mutex_unlock(&perf->metrics_lock);
4166 DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id);
4168 return oa_config->id;
4171 mutex_unlock(&perf->metrics_lock);
4173 i915_oa_config_put(oa_config);
4174 DRM_DEBUG("Failed to add new OA config\n");
4179 * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
4181 * @data: ioctl data (pointer to u64 integer) copied from userspace
4184 * Configs can be removed while being used, the will stop appearing in sysfs
4185 * and their content will be freed when the stream using the config is closed.
4187 * Returns: 0 on success or a negative error code on failure.
4189 int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
4190 struct drm_file *file)
4192 struct i915_perf *perf = &to_i915(dev)->perf;
4194 struct i915_oa_config *oa_config;
4198 DRM_DEBUG("i915 perf interface not available for this system\n");
4202 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
4203 DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
4207 ret = mutex_lock_interruptible(&perf->metrics_lock);
4211 oa_config = idr_find(&perf->metrics_idr, *arg);
4213 DRM_DEBUG("Failed to remove unknown OA config\n");
4218 GEM_BUG_ON(*arg != oa_config->id);
4220 sysfs_remove_group(perf->metrics_kobj, &oa_config->sysfs_metric);
4222 idr_remove(&perf->metrics_idr, *arg);
4224 mutex_unlock(&perf->metrics_lock);
4226 DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
4228 i915_oa_config_put(oa_config);
4233 mutex_unlock(&perf->metrics_lock);
4237 static struct ctl_table oa_table[] = {
4239 .procname = "perf_stream_paranoid",
4240 .data = &i915_perf_stream_paranoid,
4241 .maxlen = sizeof(i915_perf_stream_paranoid),
4243 .proc_handler = proc_dointvec_minmax,
4244 .extra1 = SYSCTL_ZERO,
4245 .extra2 = SYSCTL_ONE,
4248 .procname = "oa_max_sample_rate",
4249 .data = &i915_oa_max_sample_rate,
4250 .maxlen = sizeof(i915_oa_max_sample_rate),
4252 .proc_handler = proc_dointvec_minmax,
4253 .extra1 = SYSCTL_ZERO,
4254 .extra2 = &oa_sample_rate_hard_limit,
4259 static struct ctl_table i915_root[] = {
4269 static struct ctl_table dev_root[] = {
4280 * i915_perf_init - initialize i915-perf state on module bind
4281 * @i915: i915 device instance
4283 * Initializes i915-perf state without exposing anything to userspace.
4285 * Note: i915-perf initialization is split into an 'init' and 'register'
4286 * phase with the i915_perf_register() exposing state to userspace.
4288 void i915_perf_init(struct drm_i915_private *i915)
4290 struct i915_perf *perf = &i915->perf;
4292 /* XXX const struct i915_perf_ops! */
4294 if (IS_HASWELL(i915)) {
4295 perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
4296 perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
4297 perf->ops.is_valid_flex_reg = NULL;
4298 perf->ops.enable_metric_set = hsw_enable_metric_set;
4299 perf->ops.disable_metric_set = hsw_disable_metric_set;
4300 perf->ops.oa_enable = gen7_oa_enable;
4301 perf->ops.oa_disable = gen7_oa_disable;
4302 perf->ops.read = gen7_oa_read;
4303 perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
4305 perf->oa_formats = hsw_oa_formats;
4306 } else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
4307 /* Note: that although we could theoretically also support the
4308 * legacy ringbuffer mode on BDW (and earlier iterations of
4309 * this driver, before upstreaming did this) it didn't seem
4310 * worth the complexity to maintain now that BDW+ enable
4311 * execlist mode by default.
4313 perf->ops.read = gen8_oa_read;
4315 if (IS_GEN_RANGE(i915, 8, 9)) {
4316 perf->oa_formats = gen8_plus_oa_formats;
4318 perf->ops.is_valid_b_counter_reg =
4319 gen7_is_valid_b_counter_addr;
4320 perf->ops.is_valid_mux_reg =
4321 gen8_is_valid_mux_addr;
4322 perf->ops.is_valid_flex_reg =
4323 gen8_is_valid_flex_addr;
4325 if (IS_CHERRYVIEW(i915)) {
4326 perf->ops.is_valid_mux_reg =
4327 chv_is_valid_mux_addr;
4330 perf->ops.oa_enable = gen8_oa_enable;
4331 perf->ops.oa_disable = gen8_oa_disable;
4332 perf->ops.enable_metric_set = gen8_enable_metric_set;
4333 perf->ops.disable_metric_set = gen8_disable_metric_set;
4334 perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
4336 if (IS_GEN(i915, 8)) {
4337 perf->ctx_oactxctrl_offset = 0x120;
4338 perf->ctx_flexeu0_offset = 0x2ce;
4340 perf->gen8_valid_ctx_bit = BIT(25);
4342 perf->ctx_oactxctrl_offset = 0x128;
4343 perf->ctx_flexeu0_offset = 0x3de;
4345 perf->gen8_valid_ctx_bit = BIT(16);
4347 } else if (IS_GEN_RANGE(i915, 10, 11)) {
4348 perf->oa_formats = gen8_plus_oa_formats;
4350 perf->ops.is_valid_b_counter_reg =
4351 gen7_is_valid_b_counter_addr;
4352 perf->ops.is_valid_mux_reg =
4353 gen10_is_valid_mux_addr;
4354 perf->ops.is_valid_flex_reg =
4355 gen8_is_valid_flex_addr;
4357 perf->ops.oa_enable = gen8_oa_enable;
4358 perf->ops.oa_disable = gen8_oa_disable;
4359 perf->ops.enable_metric_set = gen8_enable_metric_set;
4360 perf->ops.disable_metric_set = gen10_disable_metric_set;
4361 perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
4363 if (IS_GEN(i915, 10)) {
4364 perf->ctx_oactxctrl_offset = 0x128;
4365 perf->ctx_flexeu0_offset = 0x3de;
4367 perf->ctx_oactxctrl_offset = 0x124;
4368 perf->ctx_flexeu0_offset = 0x78e;
4370 perf->gen8_valid_ctx_bit = BIT(16);
4371 } else if (IS_GEN(i915, 12)) {
4372 perf->oa_formats = gen12_oa_formats;
4374 perf->ops.is_valid_b_counter_reg =
4375 gen12_is_valid_b_counter_addr;
4376 perf->ops.is_valid_mux_reg =
4377 gen12_is_valid_mux_addr;
4378 perf->ops.is_valid_flex_reg =
4379 gen8_is_valid_flex_addr;
4381 perf->ops.oa_enable = gen12_oa_enable;
4382 perf->ops.oa_disable = gen12_oa_disable;
4383 perf->ops.enable_metric_set = gen12_enable_metric_set;
4384 perf->ops.disable_metric_set = gen12_disable_metric_set;
4385 perf->ops.oa_hw_tail_read = gen12_oa_hw_tail_read;
4387 perf->ctx_flexeu0_offset = 0;
4388 perf->ctx_oactxctrl_offset = 0x144;
4392 if (perf->ops.enable_metric_set) {
4393 mutex_init(&perf->lock);
4395 oa_sample_rate_hard_limit = 1000 *
4396 (RUNTIME_INFO(i915)->cs_timestamp_frequency_khz / 2);
4398 mutex_init(&perf->metrics_lock);
4399 idr_init(&perf->metrics_idr);
4401 /* We set up some ratelimit state to potentially throttle any
4402 * _NOTES about spurious, invalid OA reports which we don't
4403 * forward to userspace.
4405 * We print a _NOTE about any throttling when closing the
4406 * stream instead of waiting until driver _fini which no one
4409 * Using the same limiting factors as printk_ratelimit()
4411 ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
4412 /* Since we use a DRM_NOTE for spurious reports it would be
4413 * inconsistent to let __ratelimit() automatically print a
4414 * warning for throttling.
4416 ratelimit_set_flags(&perf->spurious_report_rs,
4417 RATELIMIT_MSG_ON_RELEASE);
4419 atomic64_set(&perf->noa_programming_delay,
4420 500 * 1000 /* 500us */);
4426 static int destroy_config(int id, void *p, void *data)
4428 i915_oa_config_put(p);
4432 void i915_perf_sysctl_register(void)
4434 sysctl_header = register_sysctl_table(dev_root);
4437 void i915_perf_sysctl_unregister(void)
4439 unregister_sysctl_table(sysctl_header);
4443 * i915_perf_fini - Counter part to i915_perf_init()
4444 * @i915: i915 device instance
4446 void i915_perf_fini(struct drm_i915_private *i915)
4448 struct i915_perf *perf = &i915->perf;
4453 idr_for_each(&perf->metrics_idr, destroy_config, perf);
4454 idr_destroy(&perf->metrics_idr);
4456 memset(&perf->ops, 0, sizeof(perf->ops));
4461 * i915_perf_ioctl_version - Version of the i915-perf subsystem
4463 * This version number is used by userspace to detect available features.
4465 int i915_perf_ioctl_version(void)
4468 * 1: Initial version
4469 * I915_PERF_IOCTL_ENABLE
4470 * I915_PERF_IOCTL_DISABLE
4472 * 2: Added runtime modification of OA config.
4473 * I915_PERF_IOCTL_CONFIG
4475 * 3: Add DRM_I915_PERF_PROP_HOLD_PREEMPTION parameter to hold
4476 * preemption on a particular context so that performance data is
4477 * accessible from a delta of MI_RPC reports without looking at the
4483 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
4484 #include "selftests/i915_perf.c"