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"
222 /* HW requires this to be a power of two, between 128k and 16M, though driver
223 * is currently generally designed assuming the largest 16M size is used such
224 * that the overflow cases are unlikely in normal operation.
226 #define OA_BUFFER_SIZE SZ_16M
228 #define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
231 * DOC: OA Tail Pointer Race
233 * There's a HW race condition between OA unit tail pointer register updates and
234 * writes to memory whereby the tail pointer can sometimes get ahead of what's
235 * been written out to the OA buffer so far (in terms of what's visible to the
238 * Although this can be observed explicitly while copying reports to userspace
239 * by checking for a zeroed report-id field in tail reports, we want to account
240 * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
243 * In effect we define a tail pointer for reading that lags the real tail
244 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
245 * time for the corresponding reports to become visible to the CPU.
247 * To manage this we actually track two tail pointers:
248 * 1) An 'aging' tail with an associated timestamp that is tracked until we
249 * can trust the corresponding data is visible to the CPU; at which point
250 * it is considered 'aged'.
251 * 2) An 'aged' tail that can be used for read()ing.
253 * The two separate pointers let us decouple read()s from tail pointer aging.
255 * The tail pointers are checked and updated at a limited rate within a hrtimer
256 * callback (the same callback that is used for delivering EPOLLIN events)
258 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
259 * indicates that an updated tail pointer is needed.
261 * Most of the implementation details for this workaround are in
262 * oa_buffer_check_unlocked() and _append_oa_reports()
264 * Note for posterity: previously the driver used to define an effective tail
265 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
266 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
267 * This was flawed considering that the OA unit may also automatically generate
268 * non-periodic reports (such as on context switch) or the OA unit may be
269 * enabled without any periodic sampling.
271 #define OA_TAIL_MARGIN_NSEC 100000ULL
272 #define INVALID_TAIL_PTR 0xffffffff
274 /* frequency for checking whether the OA unit has written new reports to the
275 * circular OA buffer...
277 #define POLL_FREQUENCY 200
278 #define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
280 /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
281 static u32 i915_perf_stream_paranoid = true;
283 /* The maximum exponent the hardware accepts is 63 (essentially it selects one
284 * of the 64bit timestamp bits to trigger reports from) but there's currently
285 * no known use case for sampling as infrequently as once per 47 thousand years.
287 * Since the timestamps included in OA reports are only 32bits it seems
288 * reasonable to limit the OA exponent where it's still possible to account for
289 * overflow in OA report timestamps.
291 #define OA_EXPONENT_MAX 31
293 #define INVALID_CTX_ID 0xffffffff
295 /* On Gen8+ automatically triggered OA reports include a 'reason' field... */
296 #define OAREPORT_REASON_MASK 0x3f
297 #define OAREPORT_REASON_SHIFT 19
298 #define OAREPORT_REASON_TIMER (1<<0)
299 #define OAREPORT_REASON_CTX_SWITCH (1<<3)
300 #define OAREPORT_REASON_CLK_RATIO (1<<5)
303 /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
305 * The highest sampling frequency we can theoretically program the OA unit
306 * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
308 * Initialized just before we register the sysctl parameter.
310 static int oa_sample_rate_hard_limit;
312 /* Theoretically we can program the OA unit to sample every 160ns but don't
313 * allow that by default unless root...
315 * The default threshold of 100000Hz is based on perf's similar
316 * kernel.perf_event_max_sample_rate sysctl parameter.
318 static u32 i915_oa_max_sample_rate = 100000;
320 /* XXX: beware if future OA HW adds new report formats that the current
321 * code assumes all reports have a power-of-two size and ~(size - 1) can
322 * be used as a mask to align the OA tail pointer.
324 static const struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
325 [I915_OA_FORMAT_A13] = { 0, 64 },
326 [I915_OA_FORMAT_A29] = { 1, 128 },
327 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
328 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
329 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
330 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
331 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
332 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
335 static const struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
336 [I915_OA_FORMAT_A12] = { 0, 64 },
337 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
338 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
339 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
342 #define SAMPLE_OA_REPORT (1<<0)
345 * struct perf_open_properties - for validated properties given to open a stream
346 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
347 * @single_context: Whether a single or all gpu contexts should be monitored
348 * @hold_preemption: Whether the preemption is disabled for the filtered
350 * @ctx_handle: A gem ctx handle for use with @single_context
351 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
352 * @oa_format: An OA unit HW report format
353 * @oa_periodic: Whether to enable periodic OA unit sampling
354 * @oa_period_exponent: The OA unit sampling period is derived from this
355 * @engine: The engine (typically rcs0) being monitored by the OA unit
357 * As read_properties_unlocked() enumerates and validates the properties given
358 * to open a stream of metrics the configuration is built up in the structure
359 * which starts out zero initialized.
361 struct perf_open_properties {
364 u64 single_context:1;
365 u64 hold_preemption:1;
368 /* OA sampling state */
372 int oa_period_exponent;
374 struct intel_engine_cs *engine;
377 struct i915_oa_config_bo {
378 struct llist_node node;
380 struct i915_oa_config *oa_config;
381 struct i915_vma *vma;
384 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer);
386 void i915_oa_config_release(struct kref *ref)
388 struct i915_oa_config *oa_config =
389 container_of(ref, typeof(*oa_config), ref);
391 kfree(oa_config->flex_regs);
392 kfree(oa_config->b_counter_regs);
393 kfree(oa_config->mux_regs);
395 kfree_rcu(oa_config, rcu);
398 struct i915_oa_config *
399 i915_perf_get_oa_config(struct i915_perf *perf, int metrics_set)
401 struct i915_oa_config *oa_config;
404 if (metrics_set == 1)
405 oa_config = &perf->test_config;
407 oa_config = idr_find(&perf->metrics_idr, metrics_set);
409 oa_config = i915_oa_config_get(oa_config);
415 static void free_oa_config_bo(struct i915_oa_config_bo *oa_bo)
417 i915_oa_config_put(oa_bo->oa_config);
418 i915_vma_put(oa_bo->vma);
422 static u32 gen8_oa_hw_tail_read(struct i915_perf_stream *stream)
424 struct intel_uncore *uncore = stream->uncore;
426 return intel_uncore_read(uncore, GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
429 static u32 gen7_oa_hw_tail_read(struct i915_perf_stream *stream)
431 struct intel_uncore *uncore = stream->uncore;
432 u32 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
434 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
438 * oa_buffer_check_unlocked - check for data and update tail ptr state
439 * @stream: i915 stream instance
441 * This is either called via fops (for blocking reads in user ctx) or the poll
442 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
443 * if there is data available for userspace to read.
445 * This function is central to providing a workaround for the OA unit tail
446 * pointer having a race with respect to what data is visible to the CPU.
447 * It is responsible for reading tail pointers from the hardware and giving
448 * the pointers time to 'age' before they are made available for reading.
449 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
451 * Besides returning true when there is data available to read() this function
452 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
453 * and .aged_tail_idx state used for reading.
455 * Note: It's safe to read OA config state here unlocked, assuming that this is
456 * only called while the stream is enabled, while the global OA configuration
459 * Returns: %true if the OA buffer contains data, else %false
461 static bool oa_buffer_check_unlocked(struct i915_perf_stream *stream)
463 int report_size = stream->oa_buffer.format_size;
465 unsigned int aged_idx;
466 u32 head, hw_tail, aged_tail, aging_tail;
469 /* We have to consider the (unlikely) possibility that read() errors
470 * could result in an OA buffer reset which might reset the head,
471 * tails[] and aged_tail state.
473 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
475 /* NB: The head we observe here might effectively be a little out of
476 * date (between head and tails[aged_idx].offset if there is currently
477 * a read() in progress.
479 head = stream->oa_buffer.head;
481 aged_idx = stream->oa_buffer.aged_tail_idx;
482 aged_tail = stream->oa_buffer.tails[aged_idx].offset;
483 aging_tail = stream->oa_buffer.tails[!aged_idx].offset;
485 hw_tail = stream->perf->ops.oa_hw_tail_read(stream);
487 /* The tail pointer increases in 64 byte increments,
488 * not in report_size steps...
490 hw_tail &= ~(report_size - 1);
492 now = ktime_get_mono_fast_ns();
494 /* Update the aged tail
496 * Flip the tail pointer available for read()s once the aging tail is
497 * old enough to trust that the corresponding data will be visible to
500 * Do this before updating the aging pointer in case we may be able to
501 * immediately start aging a new pointer too (if new data has become
502 * available) without needing to wait for a later hrtimer callback.
504 if (aging_tail != INVALID_TAIL_PTR &&
505 ((now - stream->oa_buffer.aging_timestamp) >
506 OA_TAIL_MARGIN_NSEC)) {
509 stream->oa_buffer.aged_tail_idx = aged_idx;
511 aged_tail = aging_tail;
513 /* Mark that we need a new pointer to start aging... */
514 stream->oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
515 aging_tail = INVALID_TAIL_PTR;
518 /* Update the aging tail
520 * We throttle aging tail updates until we have a new tail that
521 * represents >= one report more data than is already available for
522 * reading. This ensures there will be enough data for a successful
523 * read once this new pointer has aged and ensures we will give the new
524 * pointer time to age.
526 if (aging_tail == INVALID_TAIL_PTR &&
527 (aged_tail == INVALID_TAIL_PTR ||
528 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
529 struct i915_vma *vma = stream->oa_buffer.vma;
530 u32 gtt_offset = i915_ggtt_offset(vma);
532 /* Be paranoid and do a bounds check on the pointer read back
533 * from hardware, just in case some spurious hardware condition
534 * could put the tail out of bounds...
536 if (hw_tail >= gtt_offset &&
537 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
538 stream->oa_buffer.tails[!aged_idx].offset =
539 aging_tail = hw_tail;
540 stream->oa_buffer.aging_timestamp = now;
542 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
547 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
549 return aged_tail == INVALID_TAIL_PTR ?
550 false : OA_TAKEN(aged_tail, head) >= report_size;
554 * append_oa_status - Appends a status record to a userspace read() buffer.
555 * @stream: An i915-perf stream opened for OA metrics
556 * @buf: destination buffer given by userspace
557 * @count: the number of bytes userspace wants to read
558 * @offset: (inout): the current position for writing into @buf
559 * @type: The kind of status to report to userspace
561 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
562 * into the userspace read() buffer.
564 * The @buf @offset will only be updated on success.
566 * Returns: 0 on success, negative error code on failure.
568 static int append_oa_status(struct i915_perf_stream *stream,
572 enum drm_i915_perf_record_type type)
574 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
576 if ((count - *offset) < header.size)
579 if (copy_to_user(buf + *offset, &header, sizeof(header)))
582 (*offset) += header.size;
588 * append_oa_sample - Copies single OA report into userspace read() buffer.
589 * @stream: An i915-perf stream opened for OA metrics
590 * @buf: destination buffer given by userspace
591 * @count: the number of bytes userspace wants to read
592 * @offset: (inout): the current position for writing into @buf
593 * @report: A single OA report to (optionally) include as part of the sample
595 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
596 * properties when opening a stream, tracked as `stream->sample_flags`. This
597 * function copies the requested components of a single sample to the given
600 * The @buf @offset will only be updated on success.
602 * Returns: 0 on success, negative error code on failure.
604 static int append_oa_sample(struct i915_perf_stream *stream,
610 int report_size = stream->oa_buffer.format_size;
611 struct drm_i915_perf_record_header header;
612 u32 sample_flags = stream->sample_flags;
614 header.type = DRM_I915_PERF_RECORD_SAMPLE;
616 header.size = stream->sample_size;
618 if ((count - *offset) < header.size)
622 if (copy_to_user(buf, &header, sizeof(header)))
624 buf += sizeof(header);
626 if (sample_flags & SAMPLE_OA_REPORT) {
627 if (copy_to_user(buf, report, report_size))
631 (*offset) += header.size;
637 * Copies all buffered OA reports into userspace read() buffer.
638 * @stream: An i915-perf stream opened for OA metrics
639 * @buf: destination buffer given by userspace
640 * @count: the number of bytes userspace wants to read
641 * @offset: (inout): the current position for writing into @buf
643 * Notably any error condition resulting in a short read (-%ENOSPC or
644 * -%EFAULT) will be returned even though one or more records may
645 * have been successfully copied. In this case it's up to the caller
646 * to decide if the error should be squashed before returning to
649 * Note: reports are consumed from the head, and appended to the
650 * tail, so the tail chases the head?... If you think that's mad
651 * and back-to-front you're not alone, but this follows the
652 * Gen PRM naming convention.
654 * Returns: 0 on success, negative error code on failure.
656 static int gen8_append_oa_reports(struct i915_perf_stream *stream,
661 struct intel_uncore *uncore = stream->uncore;
662 int report_size = stream->oa_buffer.format_size;
663 u8 *oa_buf_base = stream->oa_buffer.vaddr;
664 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
665 u32 mask = (OA_BUFFER_SIZE - 1);
666 size_t start_offset = *offset;
668 unsigned int aged_tail_idx;
673 if (WARN_ON(!stream->enabled))
676 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
678 head = stream->oa_buffer.head;
679 aged_tail_idx = stream->oa_buffer.aged_tail_idx;
680 tail = stream->oa_buffer.tails[aged_tail_idx].offset;
682 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
685 * An invalid tail pointer here means we're still waiting for the poll
686 * hrtimer callback to give us a pointer
688 if (tail == INVALID_TAIL_PTR)
692 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
693 * while indexing relative to oa_buf_base.
699 * An out of bounds or misaligned head or tail pointer implies a driver
700 * bug since we validate + align the tail pointers we read from the
701 * hardware and we are in full control of the head pointer which should
702 * only be incremented by multiples of the report size (notably also
703 * all a power of two).
705 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
706 tail > OA_BUFFER_SIZE || tail % report_size,
707 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
713 (taken = OA_TAKEN(tail, head));
714 head = (head + report_size) & mask) {
715 u8 *report = oa_buf_base + head;
716 u32 *report32 = (void *)report;
721 * All the report sizes factor neatly into the buffer
722 * size so we never expect to see a report split
723 * between the beginning and end of the buffer.
725 * Given the initial alignment check a misalignment
726 * here would imply a driver bug that would result
729 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
730 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
735 * The reason field includes flags identifying what
736 * triggered this specific report (mostly timer
737 * triggered or e.g. due to a context switch).
739 * This field is never expected to be zero so we can
740 * check that the report isn't invalid before copying
743 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
744 OAREPORT_REASON_MASK);
746 if (__ratelimit(&stream->perf->spurious_report_rs))
747 DRM_NOTE("Skipping spurious, invalid OA report\n");
751 ctx_id = report32[2] & stream->specific_ctx_id_mask;
754 * Squash whatever is in the CTX_ID field if it's marked as
755 * invalid to be sure we avoid false-positive, single-context
758 * Note: that we don't clear the valid_ctx_bit so userspace can
759 * understand that the ID has been squashed by the kernel.
761 if (!(report32[0] & stream->perf->gen8_valid_ctx_bit))
762 ctx_id = report32[2] = INVALID_CTX_ID;
765 * NB: For Gen 8 the OA unit no longer supports clock gating
766 * off for a specific context and the kernel can't securely
767 * stop the counters from updating as system-wide / global
770 * Automatic reports now include a context ID so reports can be
771 * filtered on the cpu but it's not worth trying to
772 * automatically subtract/hide counter progress for other
773 * contexts while filtering since we can't stop userspace
774 * issuing MI_REPORT_PERF_COUNT commands which would still
775 * provide a side-band view of the real values.
777 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
778 * to normalize counters for a single filtered context then it
779 * needs be forwarded bookend context-switch reports so that it
780 * can track switches in between MI_REPORT_PERF_COUNT commands
781 * and can itself subtract/ignore the progress of counters
782 * associated with other contexts. Note that the hardware
783 * automatically triggers reports when switching to a new
784 * context which are tagged with the ID of the newly active
785 * context. To avoid the complexity (and likely fragility) of
786 * reading ahead while parsing reports to try and minimize
787 * forwarding redundant context switch reports (i.e. between
788 * other, unrelated contexts) we simply elect to forward them
791 * We don't rely solely on the reason field to identify context
792 * switches since it's not-uncommon for periodic samples to
793 * identify a switch before any 'context switch' report.
795 if (!stream->perf->exclusive_stream->ctx ||
796 stream->specific_ctx_id == ctx_id ||
797 stream->oa_buffer.last_ctx_id == stream->specific_ctx_id ||
798 reason & OAREPORT_REASON_CTX_SWITCH) {
801 * While filtering for a single context we avoid
802 * leaking the IDs of other contexts.
804 if (stream->perf->exclusive_stream->ctx &&
805 stream->specific_ctx_id != ctx_id) {
806 report32[2] = INVALID_CTX_ID;
809 ret = append_oa_sample(stream, buf, count, offset,
814 stream->oa_buffer.last_ctx_id = ctx_id;
818 * The above reason field sanity check is based on
819 * the assumption that the OA buffer is initially
820 * zeroed and we reset the field after copying so the
821 * check is still meaningful once old reports start
827 if (start_offset != *offset) {
828 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
831 * We removed the gtt_offset for the copy loop above, indexing
832 * relative to oa_buf_base so put back here...
836 intel_uncore_write(uncore, GEN8_OAHEADPTR,
837 head & GEN8_OAHEADPTR_MASK);
838 stream->oa_buffer.head = head;
840 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
847 * gen8_oa_read - copy status records then buffered OA reports
848 * @stream: An i915-perf stream opened for OA metrics
849 * @buf: destination buffer given by userspace
850 * @count: the number of bytes userspace wants to read
851 * @offset: (inout): the current position for writing into @buf
853 * Checks OA unit status registers and if necessary appends corresponding
854 * status records for userspace (such as for a buffer full condition) and then
855 * initiate appending any buffered OA reports.
857 * Updates @offset according to the number of bytes successfully copied into
858 * the userspace buffer.
860 * NB: some data may be successfully copied to the userspace buffer
861 * even if an error is returned, and this is reflected in the
864 * Returns: zero on success or a negative error code
866 static int gen8_oa_read(struct i915_perf_stream *stream,
871 struct intel_uncore *uncore = stream->uncore;
875 if (WARN_ON(!stream->oa_buffer.vaddr))
878 oastatus = intel_uncore_read(uncore, GEN8_OASTATUS);
881 * We treat OABUFFER_OVERFLOW as a significant error:
883 * Although theoretically we could handle this more gracefully
884 * sometimes, some Gens don't correctly suppress certain
885 * automatically triggered reports in this condition and so we
886 * have to assume that old reports are now being trampled
889 * Considering how we don't currently give userspace control
890 * over the OA buffer size and always configure a large 16MB
891 * buffer, then a buffer overflow does anyway likely indicate
892 * that something has gone quite badly wrong.
894 if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
895 ret = append_oa_status(stream, buf, count, offset,
896 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
900 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
901 stream->period_exponent);
903 stream->perf->ops.oa_disable(stream);
904 stream->perf->ops.oa_enable(stream);
907 * Note: .oa_enable() is expected to re-init the oabuffer and
908 * reset GEN8_OASTATUS for us
910 oastatus = intel_uncore_read(uncore, GEN8_OASTATUS);
913 if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
914 ret = append_oa_status(stream, buf, count, offset,
915 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
918 intel_uncore_write(uncore, GEN8_OASTATUS,
919 oastatus & ~GEN8_OASTATUS_REPORT_LOST);
922 return gen8_append_oa_reports(stream, buf, count, offset);
926 * Copies all buffered OA reports into userspace read() buffer.
927 * @stream: An i915-perf stream opened for OA metrics
928 * @buf: destination buffer given by userspace
929 * @count: the number of bytes userspace wants to read
930 * @offset: (inout): the current position for writing into @buf
932 * Notably any error condition resulting in a short read (-%ENOSPC or
933 * -%EFAULT) will be returned even though one or more records may
934 * have been successfully copied. In this case it's up to the caller
935 * to decide if the error should be squashed before returning to
938 * Note: reports are consumed from the head, and appended to the
939 * tail, so the tail chases the head?... If you think that's mad
940 * and back-to-front you're not alone, but this follows the
941 * Gen PRM naming convention.
943 * Returns: 0 on success, negative error code on failure.
945 static int gen7_append_oa_reports(struct i915_perf_stream *stream,
950 struct intel_uncore *uncore = stream->uncore;
951 int report_size = stream->oa_buffer.format_size;
952 u8 *oa_buf_base = stream->oa_buffer.vaddr;
953 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
954 u32 mask = (OA_BUFFER_SIZE - 1);
955 size_t start_offset = *offset;
957 unsigned int aged_tail_idx;
962 if (WARN_ON(!stream->enabled))
965 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
967 head = stream->oa_buffer.head;
968 aged_tail_idx = stream->oa_buffer.aged_tail_idx;
969 tail = stream->oa_buffer.tails[aged_tail_idx].offset;
971 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
973 /* An invalid tail pointer here means we're still waiting for the poll
974 * hrtimer callback to give us a pointer
976 if (tail == INVALID_TAIL_PTR)
979 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
980 * while indexing relative to oa_buf_base.
985 /* An out of bounds or misaligned head or tail pointer implies a driver
986 * bug since we validate + align the tail pointers we read from the
987 * hardware and we are in full control of the head pointer which should
988 * only be incremented by multiples of the report size (notably also
989 * all a power of two).
991 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
992 tail > OA_BUFFER_SIZE || tail % report_size,
993 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
999 (taken = OA_TAKEN(tail, head));
1000 head = (head + report_size) & mask) {
1001 u8 *report = oa_buf_base + head;
1002 u32 *report32 = (void *)report;
1004 /* All the report sizes factor neatly into the buffer
1005 * size so we never expect to see a report split
1006 * between the beginning and end of the buffer.
1008 * Given the initial alignment check a misalignment
1009 * here would imply a driver bug that would result
1012 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
1013 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
1017 /* The report-ID field for periodic samples includes
1018 * some undocumented flags related to what triggered
1019 * the report and is never expected to be zero so we
1020 * can check that the report isn't invalid before
1021 * copying it to userspace...
1023 if (report32[0] == 0) {
1024 if (__ratelimit(&stream->perf->spurious_report_rs))
1025 DRM_NOTE("Skipping spurious, invalid OA report\n");
1029 ret = append_oa_sample(stream, buf, count, offset, report);
1033 /* The above report-id field sanity check is based on
1034 * the assumption that the OA buffer is initially
1035 * zeroed and we reset the field after copying so the
1036 * check is still meaningful once old reports start
1037 * being overwritten.
1042 if (start_offset != *offset) {
1043 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1045 /* We removed the gtt_offset for the copy loop above, indexing
1046 * relative to oa_buf_base so put back here...
1050 intel_uncore_write(uncore, GEN7_OASTATUS2,
1051 (head & GEN7_OASTATUS2_HEAD_MASK) |
1052 GEN7_OASTATUS2_MEM_SELECT_GGTT);
1053 stream->oa_buffer.head = head;
1055 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1062 * gen7_oa_read - copy status records then buffered OA reports
1063 * @stream: An i915-perf stream opened for OA metrics
1064 * @buf: destination buffer given by userspace
1065 * @count: the number of bytes userspace wants to read
1066 * @offset: (inout): the current position for writing into @buf
1068 * Checks Gen 7 specific OA unit status registers and if necessary appends
1069 * corresponding status records for userspace (such as for a buffer full
1070 * condition) and then initiate appending any buffered OA reports.
1072 * Updates @offset according to the number of bytes successfully copied into
1073 * the userspace buffer.
1075 * Returns: zero on success or a negative error code
1077 static int gen7_oa_read(struct i915_perf_stream *stream,
1082 struct intel_uncore *uncore = stream->uncore;
1086 if (WARN_ON(!stream->oa_buffer.vaddr))
1089 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1091 /* XXX: On Haswell we don't have a safe way to clear oastatus1
1092 * bits while the OA unit is enabled (while the tail pointer
1093 * may be updated asynchronously) so we ignore status bits
1094 * that have already been reported to userspace.
1096 oastatus1 &= ~stream->perf->gen7_latched_oastatus1;
1098 /* We treat OABUFFER_OVERFLOW as a significant error:
1100 * - The status can be interpreted to mean that the buffer is
1101 * currently full (with a higher precedence than OA_TAKEN()
1102 * which will start to report a near-empty buffer after an
1103 * overflow) but it's awkward that we can't clear the status
1104 * on Haswell, so without a reset we won't be able to catch
1107 * - Since it also implies the HW has started overwriting old
1108 * reports it may also affect our sanity checks for invalid
1109 * reports when copying to userspace that assume new reports
1110 * are being written to cleared memory.
1112 * - In the future we may want to introduce a flight recorder
1113 * mode where the driver will automatically maintain a safe
1114 * guard band between head/tail, avoiding this overflow
1115 * condition, but we avoid the added driver complexity for
1118 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1119 ret = append_oa_status(stream, buf, count, offset,
1120 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1124 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
1125 stream->period_exponent);
1127 stream->perf->ops.oa_disable(stream);
1128 stream->perf->ops.oa_enable(stream);
1130 oastatus1 = intel_uncore_read(uncore, GEN7_OASTATUS1);
1133 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1134 ret = append_oa_status(stream, buf, count, offset,
1135 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1138 stream->perf->gen7_latched_oastatus1 |=
1139 GEN7_OASTATUS1_REPORT_LOST;
1142 return gen7_append_oa_reports(stream, buf, count, offset);
1146 * i915_oa_wait_unlocked - handles blocking IO until OA data available
1147 * @stream: An i915-perf stream opened for OA metrics
1149 * Called when userspace tries to read() from a blocking stream FD opened
1150 * for OA metrics. It waits until the hrtimer callback finds a non-empty
1151 * OA buffer and wakes us.
1153 * Note: it's acceptable to have this return with some false positives
1154 * since any subsequent read handling will return -EAGAIN if there isn't
1155 * really data ready for userspace yet.
1157 * Returns: zero on success or a negative error code
1159 static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1161 /* We would wait indefinitely if periodic sampling is not enabled */
1162 if (!stream->periodic)
1165 return wait_event_interruptible(stream->poll_wq,
1166 oa_buffer_check_unlocked(stream));
1170 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1171 * @stream: An i915-perf stream opened for OA metrics
1172 * @file: An i915 perf stream file
1173 * @wait: poll() state table
1175 * For handling userspace polling on an i915 perf stream opened for OA metrics,
1176 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1177 * when it sees data ready to read in the circular OA buffer.
1179 static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1183 poll_wait(file, &stream->poll_wq, wait);
1187 * i915_oa_read - just calls through to &i915_oa_ops->read
1188 * @stream: An i915-perf stream opened for OA metrics
1189 * @buf: destination buffer given by userspace
1190 * @count: the number of bytes userspace wants to read
1191 * @offset: (inout): the current position for writing into @buf
1193 * Updates @offset according to the number of bytes successfully copied into
1194 * the userspace buffer.
1196 * Returns: zero on success or a negative error code
1198 static int i915_oa_read(struct i915_perf_stream *stream,
1203 return stream->perf->ops.read(stream, buf, count, offset);
1206 static struct intel_context *oa_pin_context(struct i915_perf_stream *stream)
1208 struct i915_gem_engines_iter it;
1209 struct i915_gem_context *ctx = stream->ctx;
1210 struct intel_context *ce;
1213 for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
1214 if (ce->engine != stream->engine) /* first match! */
1218 * As the ID is the gtt offset of the context's vma we
1219 * pin the vma to ensure the ID remains fixed.
1221 err = intel_context_pin(ce);
1223 stream->pinned_ctx = ce;
1227 i915_gem_context_unlock_engines(ctx);
1229 return stream->pinned_ctx;
1233 * oa_get_render_ctx_id - determine and hold ctx hw id
1234 * @stream: An i915-perf stream opened for OA metrics
1236 * Determine the render context hw id, and ensure it remains fixed for the
1237 * lifetime of the stream. This ensures that we don't have to worry about
1238 * updating the context ID in OACONTROL on the fly.
1240 * Returns: zero on success or a negative error code
1242 static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1244 struct intel_context *ce;
1246 ce = oa_pin_context(stream);
1250 switch (INTEL_GEN(ce->engine->i915)) {
1253 * On Haswell we don't do any post processing of the reports
1254 * and don't need to use the mask.
1256 stream->specific_ctx_id = i915_ggtt_offset(ce->state);
1257 stream->specific_ctx_id_mask = 0;
1264 if (intel_engine_in_execlists_submission_mode(ce->engine)) {
1265 stream->specific_ctx_id_mask =
1266 (1U << GEN8_CTX_ID_WIDTH) - 1;
1267 stream->specific_ctx_id = stream->specific_ctx_id_mask;
1270 * When using GuC, the context descriptor we write in
1271 * i915 is read by GuC and rewritten before it's
1272 * actually written into the hardware. The LRCA is
1273 * what is put into the context id field of the
1274 * context descriptor by GuC. Because it's aligned to
1275 * a page, the lower 12bits are always at 0 and
1276 * dropped by GuC. They won't be part of the context
1277 * ID in the OA reports, so squash those lower bits.
1279 stream->specific_ctx_id =
1280 lower_32_bits(ce->lrc_desc) >> 12;
1283 * GuC uses the top bit to signal proxy submission, so
1286 stream->specific_ctx_id_mask =
1287 (1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
1293 stream->specific_ctx_id_mask =
1294 ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) << (GEN11_SW_CTX_ID_SHIFT - 32);
1295 stream->specific_ctx_id = stream->specific_ctx_id_mask;
1300 MISSING_CASE(INTEL_GEN(ce->engine->i915));
1303 ce->tag = stream->specific_ctx_id_mask;
1305 DRM_DEBUG_DRIVER("filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
1306 stream->specific_ctx_id,
1307 stream->specific_ctx_id_mask);
1313 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1314 * @stream: An i915-perf stream opened for OA metrics
1316 * In case anything needed doing to ensure the context HW ID would remain valid
1317 * for the lifetime of the stream, then that can be undone here.
1319 static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1321 struct intel_context *ce;
1323 ce = fetch_and_zero(&stream->pinned_ctx);
1325 ce->tag = 0; /* recomputed on next submission after parking */
1326 intel_context_unpin(ce);
1329 stream->specific_ctx_id = INVALID_CTX_ID;
1330 stream->specific_ctx_id_mask = 0;
1334 free_oa_buffer(struct i915_perf_stream *stream)
1336 i915_vma_unpin_and_release(&stream->oa_buffer.vma,
1337 I915_VMA_RELEASE_MAP);
1339 stream->oa_buffer.vaddr = NULL;
1343 free_oa_configs(struct i915_perf_stream *stream)
1345 struct i915_oa_config_bo *oa_bo, *tmp;
1347 i915_oa_config_put(stream->oa_config);
1348 llist_for_each_entry_safe(oa_bo, tmp, stream->oa_config_bos.first, node)
1349 free_oa_config_bo(oa_bo);
1353 free_noa_wait(struct i915_perf_stream *stream)
1355 i915_vma_unpin_and_release(&stream->noa_wait, 0);
1358 static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1360 struct i915_perf *perf = stream->perf;
1362 BUG_ON(stream != perf->exclusive_stream);
1365 * Unset exclusive_stream first, it will be checked while disabling
1366 * the metric set on gen8+.
1368 perf->exclusive_stream = NULL;
1369 perf->ops.disable_metric_set(stream);
1371 free_oa_buffer(stream);
1373 intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
1374 intel_engine_pm_put(stream->engine);
1377 oa_put_render_ctx_id(stream);
1379 free_oa_configs(stream);
1380 free_noa_wait(stream);
1382 if (perf->spurious_report_rs.missed) {
1383 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1384 perf->spurious_report_rs.missed);
1388 static void gen7_init_oa_buffer(struct i915_perf_stream *stream)
1390 struct intel_uncore *uncore = stream->uncore;
1391 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1392 unsigned long flags;
1394 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1396 /* Pre-DevBDW: OABUFFER must be set with counters off,
1397 * before OASTATUS1, but after OASTATUS2
1399 intel_uncore_write(uncore, GEN7_OASTATUS2, /* head */
1400 gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT);
1401 stream->oa_buffer.head = gtt_offset;
1403 intel_uncore_write(uncore, GEN7_OABUFFER, gtt_offset);
1405 intel_uncore_write(uncore, GEN7_OASTATUS1, /* tail */
1406 gtt_offset | OABUFFER_SIZE_16M);
1408 /* Mark that we need updated tail pointers to read from... */
1409 stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1410 stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1412 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1414 /* On Haswell we have to track which OASTATUS1 flags we've
1415 * already seen since they can't be cleared while periodic
1416 * sampling is enabled.
1418 stream->perf->gen7_latched_oastatus1 = 0;
1420 /* NB: although the OA buffer will initially be allocated
1421 * zeroed via shmfs (and so this memset is redundant when
1422 * first allocating), we may re-init the OA buffer, either
1423 * when re-enabling a stream or in error/reset paths.
1425 * The reason we clear the buffer for each re-init is for the
1426 * sanity check in gen7_append_oa_reports() that looks at the
1427 * report-id field to make sure it's non-zero which relies on
1428 * the assumption that new reports are being written to zeroed
1431 memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1433 stream->pollin = false;
1436 static void gen8_init_oa_buffer(struct i915_perf_stream *stream)
1438 struct intel_uncore *uncore = stream->uncore;
1439 u32 gtt_offset = i915_ggtt_offset(stream->oa_buffer.vma);
1440 unsigned long flags;
1442 spin_lock_irqsave(&stream->oa_buffer.ptr_lock, flags);
1444 intel_uncore_write(uncore, GEN8_OASTATUS, 0);
1445 intel_uncore_write(uncore, GEN8_OAHEADPTR, gtt_offset);
1446 stream->oa_buffer.head = gtt_offset;
1448 intel_uncore_write(uncore, GEN8_OABUFFER_UDW, 0);
1453 * "This MMIO must be set before the OATAILPTR
1454 * register and after the OAHEADPTR register. This is
1455 * to enable proper functionality of the overflow
1458 intel_uncore_write(uncore, GEN8_OABUFFER, gtt_offset |
1459 OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
1460 intel_uncore_write(uncore, GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1462 /* Mark that we need updated tail pointers to read from... */
1463 stream->oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1464 stream->oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1467 * Reset state used to recognise context switches, affecting which
1468 * reports we will forward to userspace while filtering for a single
1471 stream->oa_buffer.last_ctx_id = INVALID_CTX_ID;
1473 spin_unlock_irqrestore(&stream->oa_buffer.ptr_lock, flags);
1476 * NB: although the OA buffer will initially be allocated
1477 * zeroed via shmfs (and so this memset is redundant when
1478 * first allocating), we may re-init the OA buffer, either
1479 * when re-enabling a stream or in error/reset paths.
1481 * The reason we clear the buffer for each re-init is for the
1482 * sanity check in gen8_append_oa_reports() that looks at the
1483 * reason field to make sure it's non-zero which relies on
1484 * the assumption that new reports are being written to zeroed
1487 memset(stream->oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1489 stream->pollin = false;
1492 static int alloc_oa_buffer(struct i915_perf_stream *stream)
1494 struct drm_i915_gem_object *bo;
1495 struct i915_vma *vma;
1498 if (WARN_ON(stream->oa_buffer.vma))
1501 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1502 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1504 bo = i915_gem_object_create_shmem(stream->perf->i915, OA_BUFFER_SIZE);
1506 DRM_ERROR("Failed to allocate OA buffer\n");
1510 i915_gem_object_set_cache_coherency(bo, I915_CACHE_LLC);
1512 /* PreHSW required 512K alignment, HSW requires 16M */
1513 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1518 stream->oa_buffer.vma = vma;
1520 stream->oa_buffer.vaddr =
1521 i915_gem_object_pin_map(bo, I915_MAP_WB);
1522 if (IS_ERR(stream->oa_buffer.vaddr)) {
1523 ret = PTR_ERR(stream->oa_buffer.vaddr);
1530 __i915_vma_unpin(vma);
1533 i915_gem_object_put(bo);
1535 stream->oa_buffer.vaddr = NULL;
1536 stream->oa_buffer.vma = NULL;
1541 static u32 *save_restore_register(struct i915_perf_stream *stream, u32 *cs,
1542 bool save, i915_reg_t reg, u32 offset,
1548 cmd = save ? MI_STORE_REGISTER_MEM : MI_LOAD_REGISTER_MEM;
1549 if (INTEL_GEN(stream->perf->i915) >= 8)
1552 for (d = 0; d < dword_count; d++) {
1554 *cs++ = i915_mmio_reg_offset(reg) + 4 * d;
1555 *cs++ = intel_gt_scratch_offset(stream->engine->gt,
1563 static int alloc_noa_wait(struct i915_perf_stream *stream)
1565 struct drm_i915_private *i915 = stream->perf->i915;
1566 struct drm_i915_gem_object *bo;
1567 struct i915_vma *vma;
1568 const u64 delay_ticks = 0xffffffffffffffff -
1570 atomic64_read(&stream->perf->noa_programming_delay) *
1571 RUNTIME_INFO(i915)->cs_timestamp_frequency_khz,
1573 const u32 base = stream->engine->mmio_base;
1574 #define CS_GPR(x) GEN8_RING_CS_GPR(base, x)
1575 u32 *batch, *ts0, *cs, *jump;
1586 bo = i915_gem_object_create_internal(i915, 4096);
1588 DRM_ERROR("Failed to allocate NOA wait batchbuffer\n");
1593 * We pin in GGTT because we jump into this buffer now because
1594 * multiple OA config BOs will have a jump to this address and it
1595 * needs to be fixed during the lifetime of the i915/perf stream.
1597 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, 0, PIN_HIGH);
1603 batch = cs = i915_gem_object_pin_map(bo, I915_MAP_WB);
1604 if (IS_ERR(batch)) {
1605 ret = PTR_ERR(batch);
1609 /* Save registers. */
1610 for (i = 0; i < N_CS_GPR; i++)
1611 cs = save_restore_register(
1612 stream, cs, true /* save */, CS_GPR(i),
1613 INTEL_GT_SCRATCH_FIELD_PERF_CS_GPR + 8 * i, 2);
1614 cs = save_restore_register(
1615 stream, cs, true /* save */, MI_PREDICATE_RESULT_1,
1616 INTEL_GT_SCRATCH_FIELD_PERF_PREDICATE_RESULT_1, 1);
1618 /* First timestamp snapshot location. */
1622 * Initial snapshot of the timestamp register to implement the wait.
1623 * We work with 32b values, so clear out the top 32b bits of the
1624 * register because the ALU works 64bits.
1626 *cs++ = MI_LOAD_REGISTER_IMM(1);
1627 *cs++ = i915_mmio_reg_offset(CS_GPR(START_TS)) + 4;
1629 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1630 *cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
1631 *cs++ = i915_mmio_reg_offset(CS_GPR(START_TS));
1634 * This is the location we're going to jump back into until the
1635 * required amount of time has passed.
1640 * Take another snapshot of the timestamp register. Take care to clear
1641 * up the top 32bits of CS_GPR(1) as we're using it for other
1644 *cs++ = MI_LOAD_REGISTER_IMM(1);
1645 *cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS)) + 4;
1647 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1648 *cs++ = i915_mmio_reg_offset(RING_TIMESTAMP(base));
1649 *cs++ = i915_mmio_reg_offset(CS_GPR(NOW_TS));
1652 * Do a diff between the 2 timestamps and store the result back into
1656 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(NOW_TS));
1657 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(START_TS));
1658 *cs++ = MI_MATH_SUB;
1659 *cs++ = MI_MATH_STORE(MI_MATH_REG(DELTA_TS), MI_MATH_REG_ACCU);
1660 *cs++ = MI_MATH_STORE(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
1663 * Transfer the carry flag (set to 1 if ts1 < ts0, meaning the
1664 * timestamp have rolled over the 32bits) into the predicate register
1665 * to be used for the predicated jump.
1667 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1668 *cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
1669 *cs++ = i915_mmio_reg_offset(MI_PREDICATE_RESULT_1);
1671 /* Restart from the beginning if we had timestamps roll over. */
1672 *cs++ = (INTEL_GEN(i915) < 8 ?
1673 MI_BATCH_BUFFER_START :
1674 MI_BATCH_BUFFER_START_GEN8) |
1676 *cs++ = i915_ggtt_offset(vma) + (ts0 - batch) * 4;
1680 * Now add the diff between to previous timestamps and add it to :
1681 * (((1 * << 64) - 1) - delay_ns)
1683 * When the Carry Flag contains 1 this means the elapsed time is
1684 * longer than the expected delay, and we can exit the wait loop.
1686 *cs++ = MI_LOAD_REGISTER_IMM(2);
1687 *cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET));
1688 *cs++ = lower_32_bits(delay_ticks);
1689 *cs++ = i915_mmio_reg_offset(CS_GPR(DELTA_TARGET)) + 4;
1690 *cs++ = upper_32_bits(delay_ticks);
1693 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCA, MI_MATH_REG(DELTA_TS));
1694 *cs++ = MI_MATH_LOAD(MI_MATH_REG_SRCB, MI_MATH_REG(DELTA_TARGET));
1695 *cs++ = MI_MATH_ADD;
1696 *cs++ = MI_MATH_STOREINV(MI_MATH_REG(JUMP_PREDICATE), MI_MATH_REG_CF);
1699 * Transfer the result into the predicate register to be used for the
1702 *cs++ = MI_LOAD_REGISTER_REG | (3 - 2);
1703 *cs++ = i915_mmio_reg_offset(CS_GPR(JUMP_PREDICATE));
1704 *cs++ = i915_mmio_reg_offset(MI_PREDICATE_RESULT_1);
1706 /* Predicate the jump. */
1707 *cs++ = (INTEL_GEN(i915) < 8 ?
1708 MI_BATCH_BUFFER_START :
1709 MI_BATCH_BUFFER_START_GEN8) |
1711 *cs++ = i915_ggtt_offset(vma) + (jump - batch) * 4;
1714 /* Restore registers. */
1715 for (i = 0; i < N_CS_GPR; i++)
1716 cs = save_restore_register(
1717 stream, cs, false /* restore */, CS_GPR(i),
1718 INTEL_GT_SCRATCH_FIELD_PERF_CS_GPR + 8 * i, 2);
1719 cs = save_restore_register(
1720 stream, cs, false /* restore */, MI_PREDICATE_RESULT_1,
1721 INTEL_GT_SCRATCH_FIELD_PERF_PREDICATE_RESULT_1, 1);
1723 /* And return to the ring. */
1724 *cs++ = MI_BATCH_BUFFER_END;
1726 GEM_BUG_ON(cs - batch > PAGE_SIZE / sizeof(*batch));
1728 i915_gem_object_flush_map(bo);
1729 i915_gem_object_unpin_map(bo);
1731 stream->noa_wait = vma;
1735 i915_vma_unpin_and_release(&vma, 0);
1737 i915_gem_object_put(bo);
1741 static u32 *write_cs_mi_lri(u32 *cs,
1742 const struct i915_oa_reg *reg_data,
1747 for (i = 0; i < n_regs; i++) {
1748 if ((i % MI_LOAD_REGISTER_IMM_MAX_REGS) == 0) {
1749 u32 n_lri = min_t(u32,
1751 MI_LOAD_REGISTER_IMM_MAX_REGS);
1753 *cs++ = MI_LOAD_REGISTER_IMM(n_lri);
1755 *cs++ = i915_mmio_reg_offset(reg_data[i].addr);
1756 *cs++ = reg_data[i].value;
1762 static int num_lri_dwords(int num_regs)
1767 count += DIV_ROUND_UP(num_regs, MI_LOAD_REGISTER_IMM_MAX_REGS);
1768 count += num_regs * 2;
1774 static struct i915_oa_config_bo *
1775 alloc_oa_config_buffer(struct i915_perf_stream *stream,
1776 struct i915_oa_config *oa_config)
1778 struct drm_i915_gem_object *obj;
1779 struct i915_oa_config_bo *oa_bo;
1780 size_t config_length = 0;
1784 oa_bo = kzalloc(sizeof(*oa_bo), GFP_KERNEL);
1786 return ERR_PTR(-ENOMEM);
1788 config_length += num_lri_dwords(oa_config->mux_regs_len);
1789 config_length += num_lri_dwords(oa_config->b_counter_regs_len);
1790 config_length += num_lri_dwords(oa_config->flex_regs_len);
1791 config_length++; /* MI_BATCH_BUFFER_END */
1792 config_length = ALIGN(sizeof(u32) * config_length, I915_GTT_PAGE_SIZE);
1794 obj = i915_gem_object_create_shmem(stream->perf->i915, config_length);
1800 cs = i915_gem_object_pin_map(obj, I915_MAP_WB);
1806 cs = write_cs_mi_lri(cs,
1807 oa_config->mux_regs,
1808 oa_config->mux_regs_len);
1809 cs = write_cs_mi_lri(cs,
1810 oa_config->b_counter_regs,
1811 oa_config->b_counter_regs_len);
1812 cs = write_cs_mi_lri(cs,
1813 oa_config->flex_regs,
1814 oa_config->flex_regs_len);
1816 *cs++ = MI_BATCH_BUFFER_END;
1818 i915_gem_object_flush_map(obj);
1819 i915_gem_object_unpin_map(obj);
1821 oa_bo->vma = i915_vma_instance(obj,
1822 &stream->engine->gt->ggtt->vm,
1824 if (IS_ERR(oa_bo->vma)) {
1825 err = PTR_ERR(oa_bo->vma);
1829 oa_bo->oa_config = i915_oa_config_get(oa_config);
1830 llist_add(&oa_bo->node, &stream->oa_config_bos);
1835 i915_gem_object_put(obj);
1838 return ERR_PTR(err);
1841 static struct i915_vma *
1842 get_oa_vma(struct i915_perf_stream *stream, struct i915_oa_config *oa_config)
1844 struct i915_oa_config_bo *oa_bo;
1847 * Look for the buffer in the already allocated BOs attached
1850 llist_for_each_entry(oa_bo, stream->oa_config_bos.first, node) {
1851 if (oa_bo->oa_config == oa_config &&
1852 memcmp(oa_bo->oa_config->uuid,
1854 sizeof(oa_config->uuid)) == 0)
1858 oa_bo = alloc_oa_config_buffer(stream, oa_config);
1860 return ERR_CAST(oa_bo);
1863 return i915_vma_get(oa_bo->vma);
1866 static int emit_oa_config(struct i915_perf_stream *stream,
1867 struct i915_oa_config *oa_config,
1868 struct intel_context *ce)
1870 struct i915_request *rq;
1871 struct i915_vma *vma;
1874 vma = get_oa_vma(stream, oa_config);
1876 return PTR_ERR(vma);
1878 err = i915_vma_pin(vma, 0, 0, PIN_GLOBAL | PIN_HIGH);
1882 rq = i915_request_create(ce);
1889 err = i915_request_await_object(rq, vma->obj, 0);
1891 err = i915_vma_move_to_active(vma, rq, 0);
1892 i915_vma_unlock(vma);
1894 goto err_add_request;
1896 err = rq->engine->emit_bb_start(rq,
1898 I915_DISPATCH_SECURE);
1900 i915_request_add(rq);
1902 i915_vma_unpin(vma);
1908 static struct intel_context *oa_context(struct i915_perf_stream *stream)
1910 return stream->pinned_ctx ?: stream->engine->kernel_context;
1913 static int hsw_enable_metric_set(struct i915_perf_stream *stream)
1915 struct intel_uncore *uncore = stream->uncore;
1920 * OA unit is using “crclk” for its functionality. When trunk
1921 * level clock gating takes place, OA clock would be gated,
1922 * unable to count the events from non-render clock domain.
1923 * Render clock gating must be disabled when OA is enabled to
1924 * count the events from non-render domain. Unit level clock
1925 * gating for RCS should also be disabled.
1927 intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
1928 GEN7_DOP_CLOCK_GATE_ENABLE, 0);
1929 intel_uncore_rmw(uncore, GEN6_UCGCTL1,
1930 0, GEN6_CSUNIT_CLOCK_GATE_DISABLE);
1932 return emit_oa_config(stream, stream->oa_config, oa_context(stream));
1935 static void hsw_disable_metric_set(struct i915_perf_stream *stream)
1937 struct intel_uncore *uncore = stream->uncore;
1939 intel_uncore_rmw(uncore, GEN6_UCGCTL1,
1940 GEN6_CSUNIT_CLOCK_GATE_DISABLE, 0);
1941 intel_uncore_rmw(uncore, GEN7_MISCCPCTL,
1942 0, GEN7_DOP_CLOCK_GATE_ENABLE);
1944 intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
1947 static u32 oa_config_flex_reg(const struct i915_oa_config *oa_config,
1950 u32 mmio = i915_mmio_reg_offset(reg);
1954 * This arbitrary default will select the 'EU FPU0 Pipeline
1955 * Active' event. In the future it's anticipated that there
1956 * will be an explicit 'No Event' we can select, but not yet...
1961 for (i = 0; i < oa_config->flex_regs_len; i++) {
1962 if (i915_mmio_reg_offset(oa_config->flex_regs[i].addr) == mmio)
1963 return oa_config->flex_regs[i].value;
1969 * NB: It must always remain pointer safe to run this even if the OA unit
1970 * has been disabled.
1972 * It's fine to put out-of-date values into these per-context registers
1973 * in the case that the OA unit has been disabled.
1976 gen8_update_reg_state_unlocked(const struct intel_context *ce,
1977 const struct i915_perf_stream *stream)
1979 u32 ctx_oactxctrl = stream->perf->ctx_oactxctrl_offset;
1980 u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
1981 /* The MMIO offsets for Flex EU registers aren't contiguous */
1982 i915_reg_t flex_regs[] = {
1991 u32 *reg_state = ce->lrc_reg_state;
1994 reg_state[ctx_oactxctrl + 1] =
1995 (stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
1996 (stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
1997 GEN8_OA_COUNTER_RESUME;
1999 for (i = 0; i < ARRAY_SIZE(flex_regs); i++)
2000 reg_state[ctx_flexeu0 + i * 2 + 1] =
2001 oa_config_flex_reg(stream->oa_config, flex_regs[i]);
2003 reg_state[CTX_R_PWR_CLK_STATE] =
2004 intel_sseu_make_rpcs(ce->engine->i915, &ce->sseu);
2014 gen8_store_flex(struct i915_request *rq,
2015 struct intel_context *ce,
2016 const struct flex *flex, unsigned int count)
2021 cs = intel_ring_begin(rq, 4 * count);
2025 offset = i915_ggtt_offset(ce->state) + LRC_STATE_PN * PAGE_SIZE;
2027 *cs++ = MI_STORE_DWORD_IMM_GEN4 | MI_USE_GGTT;
2028 *cs++ = offset + flex->offset * sizeof(u32);
2030 *cs++ = flex->value;
2031 } while (flex++, --count);
2033 intel_ring_advance(rq, cs);
2039 gen8_load_flex(struct i915_request *rq,
2040 struct intel_context *ce,
2041 const struct flex *flex, unsigned int count)
2045 GEM_BUG_ON(!count || count > 63);
2047 cs = intel_ring_begin(rq, 2 * count + 2);
2051 *cs++ = MI_LOAD_REGISTER_IMM(count);
2053 *cs++ = i915_mmio_reg_offset(flex->reg);
2054 *cs++ = flex->value;
2055 } while (flex++, --count);
2058 intel_ring_advance(rq, cs);
2063 static int gen8_modify_context(struct intel_context *ce,
2064 const struct flex *flex, unsigned int count)
2066 struct i915_request *rq;
2069 lockdep_assert_held(&ce->pin_mutex);
2071 rq = i915_request_create(ce->engine->kernel_context);
2075 /* Serialise with the remote context */
2076 err = intel_context_prepare_remote_request(ce, rq);
2078 err = gen8_store_flex(rq, ce, flex, count);
2080 i915_request_add(rq);
2084 static int gen8_modify_self(struct intel_context *ce,
2085 const struct flex *flex, unsigned int count)
2087 struct i915_request *rq;
2090 rq = i915_request_create(ce);
2094 err = gen8_load_flex(rq, ce, flex, count);
2096 i915_request_add(rq);
2100 static int gen8_configure_context(struct i915_gem_context *ctx,
2101 struct flex *flex, unsigned int count)
2103 struct i915_gem_engines_iter it;
2104 struct intel_context *ce;
2107 for_each_gem_engine(ce, i915_gem_context_lock_engines(ctx), it) {
2108 GEM_BUG_ON(ce == ce->engine->kernel_context);
2110 if (ce->engine->class != RENDER_CLASS)
2113 err = intel_context_lock_pinned(ce);
2117 flex->value = intel_sseu_make_rpcs(ctx->i915, &ce->sseu);
2119 /* Otherwise OA settings will be set upon first use */
2120 if (intel_context_is_pinned(ce))
2121 err = gen8_modify_context(ce, flex, count);
2123 intel_context_unlock_pinned(ce);
2127 i915_gem_context_unlock_engines(ctx);
2133 * Manages updating the per-context aspects of the OA stream
2134 * configuration across all contexts.
2136 * The awkward consideration here is that OACTXCONTROL controls the
2137 * exponent for periodic sampling which is primarily used for system
2138 * wide profiling where we'd like a consistent sampling period even in
2139 * the face of context switches.
2141 * Our approach of updating the register state context (as opposed to
2142 * say using a workaround batch buffer) ensures that the hardware
2143 * won't automatically reload an out-of-date timer exponent even
2144 * transiently before a WA BB could be parsed.
2146 * This function needs to:
2147 * - Ensure the currently running context's per-context OA state is
2149 * - Ensure that all existing contexts will have the correct per-context
2150 * OA state if they are scheduled for use.
2151 * - Ensure any new contexts will be initialized with the correct
2152 * per-context OA state.
2154 * Note: it's only the RCS/Render context that has any OA state.
2156 static int gen8_configure_all_contexts(struct i915_perf_stream *stream,
2157 const struct i915_oa_config *oa_config)
2159 struct drm_i915_private *i915 = stream->perf->i915;
2160 /* The MMIO offsets for Flex EU registers aren't contiguous */
2161 const u32 ctx_flexeu0 = stream->perf->ctx_flexeu0_offset;
2162 #define ctx_flexeuN(N) (ctx_flexeu0 + 2 * (N) + 1)
2163 struct flex regs[] = {
2165 GEN8_R_PWR_CLK_STATE,
2166 CTX_R_PWR_CLK_STATE,
2170 stream->perf->ctx_oactxctrl_offset + 1,
2171 ((stream->period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
2172 (stream->periodic ? GEN8_OA_TIMER_ENABLE : 0) |
2173 GEN8_OA_COUNTER_RESUME)
2175 { EU_PERF_CNTL0, ctx_flexeuN(0) },
2176 { EU_PERF_CNTL1, ctx_flexeuN(1) },
2177 { EU_PERF_CNTL2, ctx_flexeuN(2) },
2178 { EU_PERF_CNTL3, ctx_flexeuN(3) },
2179 { EU_PERF_CNTL4, ctx_flexeuN(4) },
2180 { EU_PERF_CNTL5, ctx_flexeuN(5) },
2181 { EU_PERF_CNTL6, ctx_flexeuN(6) },
2184 struct intel_engine_cs *engine;
2185 struct i915_gem_context *ctx, *cn;
2188 for (i = 2; i < ARRAY_SIZE(regs); i++)
2189 regs[i].value = oa_config_flex_reg(oa_config, regs[i].reg);
2191 lockdep_assert_held(&stream->perf->lock);
2194 * The OA register config is setup through the context image. This image
2195 * might be written to by the GPU on context switch (in particular on
2196 * lite-restore). This means we can't safely update a context's image,
2197 * if this context is scheduled/submitted to run on the GPU.
2199 * We could emit the OA register config through the batch buffer but
2200 * this might leave small interval of time where the OA unit is
2201 * configured at an invalid sampling period.
2203 * Note that since we emit all requests from a single ring, there
2204 * is still an implicit global barrier here that may cause a high
2205 * priority context to wait for an otherwise independent low priority
2206 * context. Contexts idle at the time of reconfiguration are not
2207 * trapped behind the barrier.
2209 spin_lock(&i915->gem.contexts.lock);
2210 list_for_each_entry_safe(ctx, cn, &i915->gem.contexts.list, link) {
2211 if (ctx == i915->kernel_context)
2214 if (!kref_get_unless_zero(&ctx->ref))
2217 spin_unlock(&i915->gem.contexts.lock);
2219 err = gen8_configure_context(ctx, regs, ARRAY_SIZE(regs));
2221 i915_gem_context_put(ctx);
2225 spin_lock(&i915->gem.contexts.lock);
2226 list_safe_reset_next(ctx, cn, link);
2227 i915_gem_context_put(ctx);
2229 spin_unlock(&i915->gem.contexts.lock);
2232 * After updating all other contexts, we need to modify ourselves.
2233 * If we don't modify the kernel_context, we do not get events while
2236 for_each_uabi_engine(engine, i915) {
2237 struct intel_context *ce = engine->kernel_context;
2239 if (engine->class != RENDER_CLASS)
2242 regs[0].value = intel_sseu_make_rpcs(i915, &ce->sseu);
2244 err = gen8_modify_self(ce, regs, ARRAY_SIZE(regs));
2252 static int gen8_enable_metric_set(struct i915_perf_stream *stream)
2254 struct intel_uncore *uncore = stream->uncore;
2255 struct i915_oa_config *oa_config = stream->oa_config;
2259 * We disable slice/unslice clock ratio change reports on SKL since
2260 * they are too noisy. The HW generates a lot of redundant reports
2261 * where the ratio hasn't really changed causing a lot of redundant
2262 * work to processes and increasing the chances we'll hit buffer
2265 * Although we don't currently use the 'disable overrun' OABUFFER
2266 * feature it's worth noting that clock ratio reports have to be
2267 * disabled before considering to use that feature since the HW doesn't
2268 * correctly block these reports.
2270 * Currently none of the high-level metrics we have depend on knowing
2271 * this ratio to normalize.
2273 * Note: This register is not power context saved and restored, but
2274 * that's OK considering that we disable RC6 while the OA unit is
2277 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
2278 * be read back from automatically triggered reports, as part of the
2281 if (IS_GEN_RANGE(stream->perf->i915, 9, 11)) {
2282 intel_uncore_write(uncore, GEN8_OA_DEBUG,
2283 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
2284 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
2288 * Update all contexts prior writing the mux configurations as we need
2289 * to make sure all slices/subslices are ON before writing to NOA
2292 ret = gen8_configure_all_contexts(stream, oa_config);
2296 return emit_oa_config(stream, oa_config, oa_context(stream));
2299 static void gen8_disable_metric_set(struct i915_perf_stream *stream)
2301 struct intel_uncore *uncore = stream->uncore;
2303 /* Reset all contexts' slices/subslices configurations. */
2304 gen8_configure_all_contexts(stream, NULL);
2306 intel_uncore_rmw(uncore, GDT_CHICKEN_BITS, GT_NOA_ENABLE, 0);
2309 static void gen10_disable_metric_set(struct i915_perf_stream *stream)
2311 struct intel_uncore *uncore = stream->uncore;
2313 /* Reset all contexts' slices/subslices configurations. */
2314 gen8_configure_all_contexts(stream, NULL);
2316 /* Make sure we disable noa to save power. */
2317 intel_uncore_rmw(uncore, RPM_CONFIG1, GEN10_GT_NOA_ENABLE, 0);
2320 static void gen7_oa_enable(struct i915_perf_stream *stream)
2322 struct intel_uncore *uncore = stream->uncore;
2323 struct i915_gem_context *ctx = stream->ctx;
2324 u32 ctx_id = stream->specific_ctx_id;
2325 bool periodic = stream->periodic;
2326 u32 period_exponent = stream->period_exponent;
2327 u32 report_format = stream->oa_buffer.format;
2330 * Reset buf pointers so we don't forward reports from before now.
2332 * Think carefully if considering trying to avoid this, since it
2333 * also ensures status flags and the buffer itself are cleared
2334 * in error paths, and we have checks for invalid reports based
2335 * on the assumption that certain fields are written to zeroed
2336 * memory which this helps maintains.
2338 gen7_init_oa_buffer(stream);
2340 intel_uncore_write(uncore, GEN7_OACONTROL,
2341 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
2343 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
2344 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
2345 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
2346 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
2347 GEN7_OACONTROL_ENABLE);
2350 static void gen8_oa_enable(struct i915_perf_stream *stream)
2352 struct intel_uncore *uncore = stream->uncore;
2353 u32 report_format = stream->oa_buffer.format;
2356 * Reset buf pointers so we don't forward reports from before now.
2358 * Think carefully if considering trying to avoid this, since it
2359 * also ensures status flags and the buffer itself are cleared
2360 * in error paths, and we have checks for invalid reports based
2361 * on the assumption that certain fields are written to zeroed
2362 * memory which this helps maintains.
2364 gen8_init_oa_buffer(stream);
2367 * Note: we don't rely on the hardware to perform single context
2368 * filtering and instead filter on the cpu based on the context-id
2371 intel_uncore_write(uncore, GEN8_OACONTROL,
2372 (report_format << GEN8_OA_REPORT_FORMAT_SHIFT) |
2373 GEN8_OA_COUNTER_ENABLE);
2377 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
2378 * @stream: An i915 perf stream opened for OA metrics
2380 * [Re]enables hardware periodic sampling according to the period configured
2381 * when opening the stream. This also starts a hrtimer that will periodically
2382 * check for data in the circular OA buffer for notifying userspace (e.g.
2383 * during a read() or poll()).
2385 static void i915_oa_stream_enable(struct i915_perf_stream *stream)
2387 stream->perf->ops.oa_enable(stream);
2389 if (stream->periodic)
2390 hrtimer_start(&stream->poll_check_timer,
2391 ns_to_ktime(POLL_PERIOD),
2392 HRTIMER_MODE_REL_PINNED);
2395 static void gen7_oa_disable(struct i915_perf_stream *stream)
2397 struct intel_uncore *uncore = stream->uncore;
2399 intel_uncore_write(uncore, GEN7_OACONTROL, 0);
2400 if (intel_wait_for_register(uncore,
2401 GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
2403 DRM_ERROR("wait for OA to be disabled timed out\n");
2406 static void gen8_oa_disable(struct i915_perf_stream *stream)
2408 struct intel_uncore *uncore = stream->uncore;
2410 intel_uncore_write(uncore, GEN8_OACONTROL, 0);
2411 if (intel_wait_for_register(uncore,
2412 GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
2414 DRM_ERROR("wait for OA to be disabled timed out\n");
2418 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
2419 * @stream: An i915 perf stream opened for OA metrics
2421 * Stops the OA unit from periodically writing counter reports into the
2422 * circular OA buffer. This also stops the hrtimer that periodically checks for
2423 * data in the circular OA buffer, for notifying userspace.
2425 static void i915_oa_stream_disable(struct i915_perf_stream *stream)
2427 stream->perf->ops.oa_disable(stream);
2429 if (stream->periodic)
2430 hrtimer_cancel(&stream->poll_check_timer);
2433 static const struct i915_perf_stream_ops i915_oa_stream_ops = {
2434 .destroy = i915_oa_stream_destroy,
2435 .enable = i915_oa_stream_enable,
2436 .disable = i915_oa_stream_disable,
2437 .wait_unlocked = i915_oa_wait_unlocked,
2438 .poll_wait = i915_oa_poll_wait,
2439 .read = i915_oa_read,
2443 * i915_oa_stream_init - validate combined props for OA stream and init
2444 * @stream: An i915 perf stream
2445 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
2446 * @props: The property state that configures stream (individually validated)
2448 * While read_properties_unlocked() validates properties in isolation it
2449 * doesn't ensure that the combination necessarily makes sense.
2451 * At this point it has been determined that userspace wants a stream of
2452 * OA metrics, but still we need to further validate the combined
2453 * properties are OK.
2455 * If the configuration makes sense then we can allocate memory for
2456 * a circular OA buffer and apply the requested metric set configuration.
2458 * Returns: zero on success or a negative error code.
2460 static int i915_oa_stream_init(struct i915_perf_stream *stream,
2461 struct drm_i915_perf_open_param *param,
2462 struct perf_open_properties *props)
2464 struct i915_perf *perf = stream->perf;
2468 if (!props->engine) {
2469 DRM_DEBUG("OA engine not specified\n");
2474 * If the sysfs metrics/ directory wasn't registered for some
2475 * reason then don't let userspace try their luck with config
2478 if (!perf->metrics_kobj) {
2479 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
2483 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
2484 DRM_DEBUG("Only OA report sampling supported\n");
2488 if (!perf->ops.enable_metric_set) {
2489 DRM_DEBUG("OA unit not supported\n");
2494 * To avoid the complexity of having to accurately filter
2495 * counter reports and marshal to the appropriate client
2496 * we currently only allow exclusive access
2498 if (perf->exclusive_stream) {
2499 DRM_DEBUG("OA unit already in use\n");
2503 if (!props->oa_format) {
2504 DRM_DEBUG("OA report format not specified\n");
2508 stream->engine = props->engine;
2509 stream->uncore = stream->engine->gt->uncore;
2511 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2513 format_size = perf->oa_formats[props->oa_format].size;
2515 stream->sample_flags |= SAMPLE_OA_REPORT;
2516 stream->sample_size += format_size;
2518 stream->oa_buffer.format_size = format_size;
2519 if (WARN_ON(stream->oa_buffer.format_size == 0))
2522 stream->hold_preemption = props->hold_preemption;
2524 stream->oa_buffer.format =
2525 perf->oa_formats[props->oa_format].format;
2527 stream->periodic = props->oa_periodic;
2528 if (stream->periodic)
2529 stream->period_exponent = props->oa_period_exponent;
2532 ret = oa_get_render_ctx_id(stream);
2534 DRM_DEBUG("Invalid context id to filter with\n");
2539 ret = alloc_noa_wait(stream);
2541 DRM_DEBUG("Unable to allocate NOA wait batch buffer\n");
2542 goto err_noa_wait_alloc;
2545 stream->oa_config = i915_perf_get_oa_config(perf, props->metrics_set);
2546 if (!stream->oa_config) {
2547 DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set);
2552 /* PRM - observability performance counters:
2554 * OACONTROL, performance counter enable, note:
2556 * "When this bit is set, in order to have coherent counts,
2557 * RC6 power state and trunk clock gating must be disabled.
2558 * This can be achieved by programming MMIO registers as
2559 * 0xA094=0 and 0xA090[31]=1"
2561 * In our case we are expecting that taking pm + FORCEWAKE
2562 * references will effectively disable RC6.
2564 intel_engine_pm_get(stream->engine);
2565 intel_uncore_forcewake_get(stream->uncore, FORCEWAKE_ALL);
2567 ret = alloc_oa_buffer(stream);
2569 goto err_oa_buf_alloc;
2571 stream->ops = &i915_oa_stream_ops;
2572 perf->exclusive_stream = stream;
2574 ret = perf->ops.enable_metric_set(stream);
2576 DRM_DEBUG("Unable to enable metric set\n");
2580 DRM_DEBUG("opening stream oa config uuid=%s\n",
2581 stream->oa_config->uuid);
2583 hrtimer_init(&stream->poll_check_timer,
2584 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2585 stream->poll_check_timer.function = oa_poll_check_timer_cb;
2586 init_waitqueue_head(&stream->poll_wq);
2587 spin_lock_init(&stream->oa_buffer.ptr_lock);
2592 perf->exclusive_stream = NULL;
2593 perf->ops.disable_metric_set(stream);
2595 free_oa_buffer(stream);
2598 free_oa_configs(stream);
2600 intel_uncore_forcewake_put(stream->uncore, FORCEWAKE_ALL);
2601 intel_engine_pm_put(stream->engine);
2604 free_noa_wait(stream);
2608 oa_put_render_ctx_id(stream);
2613 void i915_oa_init_reg_state(const struct intel_context *ce,
2614 const struct intel_engine_cs *engine)
2616 struct i915_perf_stream *stream;
2618 /* perf.exclusive_stream serialised by gen8_configure_all_contexts() */
2620 if (engine->class != RENDER_CLASS)
2623 stream = engine->i915->perf.exclusive_stream;
2625 gen8_update_reg_state_unlocked(ce, stream);
2629 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2630 * @stream: An i915 perf stream
2631 * @file: An i915 perf stream file
2632 * @buf: destination buffer given by userspace
2633 * @count: the number of bytes userspace wants to read
2634 * @ppos: (inout) file seek position (unused)
2636 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2637 * ensure that if we've successfully copied any data then reporting that takes
2638 * precedence over any internal error status, so the data isn't lost.
2640 * For example ret will be -ENOSPC whenever there is more buffered data than
2641 * can be copied to userspace, but that's only interesting if we weren't able
2642 * to copy some data because it implies the userspace buffer is too small to
2643 * receive a single record (and we never split records).
2645 * Another case with ret == -EFAULT is more of a grey area since it would seem
2646 * like bad form for userspace to ask us to overrun its buffer, but the user
2649 * http://yarchive.net/comp/linux/partial_reads_writes.html
2651 * Returns: The number of bytes copied or a negative error code on failure.
2653 static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2659 /* Note we keep the offset (aka bytes read) separate from any
2660 * error status so that the final check for whether we return
2661 * the bytes read with a higher precedence than any error (see
2662 * comment below) doesn't need to be handled/duplicated in
2663 * stream->ops->read() implementations.
2666 int ret = stream->ops->read(stream, buf, count, &offset);
2668 return offset ?: (ret ?: -EAGAIN);
2672 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2673 * @file: An i915 perf stream file
2674 * @buf: destination buffer given by userspace
2675 * @count: the number of bytes userspace wants to read
2676 * @ppos: (inout) file seek position (unused)
2678 * The entry point for handling a read() on a stream file descriptor from
2679 * userspace. Most of the work is left to the i915_perf_read_locked() and
2680 * &i915_perf_stream_ops->read but to save having stream implementations (of
2681 * which we might have multiple later) we handle blocking read here.
2683 * We can also consistently treat trying to read from a disabled stream
2684 * as an IO error so implementations can assume the stream is enabled
2687 * Returns: The number of bytes copied or a negative error code on failure.
2689 static ssize_t i915_perf_read(struct file *file,
2694 struct i915_perf_stream *stream = file->private_data;
2695 struct i915_perf *perf = stream->perf;
2698 /* To ensure it's handled consistently we simply treat all reads of a
2699 * disabled stream as an error. In particular it might otherwise lead
2700 * to a deadlock for blocking file descriptors...
2702 if (!stream->enabled)
2705 if (!(file->f_flags & O_NONBLOCK)) {
2706 /* There's the small chance of false positives from
2707 * stream->ops->wait_unlocked.
2709 * E.g. with single context filtering since we only wait until
2710 * oabuffer has >= 1 report we don't immediately know whether
2711 * any reports really belong to the current context
2714 ret = stream->ops->wait_unlocked(stream);
2718 mutex_lock(&perf->lock);
2719 ret = i915_perf_read_locked(stream, file,
2721 mutex_unlock(&perf->lock);
2722 } while (ret == -EAGAIN);
2724 mutex_lock(&perf->lock);
2725 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
2726 mutex_unlock(&perf->lock);
2729 /* We allow the poll checking to sometimes report false positive EPOLLIN
2730 * events where we might actually report EAGAIN on read() if there's
2731 * not really any data available. In this situation though we don't
2732 * want to enter a busy loop between poll() reporting a EPOLLIN event
2733 * and read() returning -EAGAIN. Clearing the oa.pollin state here
2734 * effectively ensures we back off until the next hrtimer callback
2735 * before reporting another EPOLLIN event.
2737 if (ret >= 0 || ret == -EAGAIN) {
2738 /* Maybe make ->pollin per-stream state if we support multiple
2739 * concurrent streams in the future.
2741 stream->pollin = false;
2747 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
2749 struct i915_perf_stream *stream =
2750 container_of(hrtimer, typeof(*stream), poll_check_timer);
2752 if (oa_buffer_check_unlocked(stream)) {
2753 stream->pollin = true;
2754 wake_up(&stream->poll_wq);
2757 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
2759 return HRTIMER_RESTART;
2763 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
2764 * @stream: An i915 perf stream
2765 * @file: An i915 perf stream file
2766 * @wait: poll() state table
2768 * For handling userspace polling on an i915 perf stream, this calls through to
2769 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
2770 * will be woken for new stream data.
2772 * Note: The &perf->lock mutex has been taken to serialize
2773 * with any non-file-operation driver hooks.
2775 * Returns: any poll events that are ready without sleeping
2777 static __poll_t i915_perf_poll_locked(struct i915_perf_stream *stream,
2781 __poll_t events = 0;
2783 stream->ops->poll_wait(stream, file, wait);
2785 /* Note: we don't explicitly check whether there's something to read
2786 * here since this path may be very hot depending on what else
2787 * userspace is polling, or on the timeout in use. We rely solely on
2788 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
2798 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
2799 * @file: An i915 perf stream file
2800 * @wait: poll() state table
2802 * For handling userspace polling on an i915 perf stream, this ensures
2803 * poll_wait() gets called with a wait queue that will be woken for new stream
2806 * Note: Implementation deferred to i915_perf_poll_locked()
2808 * Returns: any poll events that are ready without sleeping
2810 static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
2812 struct i915_perf_stream *stream = file->private_data;
2813 struct i915_perf *perf = stream->perf;
2816 mutex_lock(&perf->lock);
2817 ret = i915_perf_poll_locked(stream, file, wait);
2818 mutex_unlock(&perf->lock);
2824 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
2825 * @stream: A disabled i915 perf stream
2827 * [Re]enables the associated capture of data for this stream.
2829 * If a stream was previously enabled then there's currently no intention
2830 * to provide userspace any guarantee about the preservation of previously
2833 static void i915_perf_enable_locked(struct i915_perf_stream *stream)
2835 if (stream->enabled)
2838 /* Allow stream->ops->enable() to refer to this */
2839 stream->enabled = true;
2841 if (stream->ops->enable)
2842 stream->ops->enable(stream);
2844 if (stream->hold_preemption)
2845 i915_gem_context_set_nopreempt(stream->ctx);
2849 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
2850 * @stream: An enabled i915 perf stream
2852 * Disables the associated capture of data for this stream.
2854 * The intention is that disabling an re-enabling a stream will ideally be
2855 * cheaper than destroying and re-opening a stream with the same configuration,
2856 * though there are no formal guarantees about what state or buffered data
2857 * must be retained between disabling and re-enabling a stream.
2859 * Note: while a stream is disabled it's considered an error for userspace
2860 * to attempt to read from the stream (-EIO).
2862 static void i915_perf_disable_locked(struct i915_perf_stream *stream)
2864 if (!stream->enabled)
2867 /* Allow stream->ops->disable() to refer to this */
2868 stream->enabled = false;
2870 if (stream->hold_preemption)
2871 i915_gem_context_clear_nopreempt(stream->ctx);
2873 if (stream->ops->disable)
2874 stream->ops->disable(stream);
2877 static long i915_perf_config_locked(struct i915_perf_stream *stream,
2878 unsigned long metrics_set)
2880 struct i915_oa_config *config;
2881 long ret = stream->oa_config->id;
2883 config = i915_perf_get_oa_config(stream->perf, metrics_set);
2887 if (config != stream->oa_config) {
2891 * If OA is bound to a specific context, emit the
2892 * reconfiguration inline from that context. The update
2893 * will then be ordered with respect to submission on that
2896 * When set globally, we use a low priority kernel context,
2897 * so it will effectively take effect when idle.
2899 err = emit_oa_config(stream, config, oa_context(stream));
2901 config = xchg(&stream->oa_config, config);
2906 i915_oa_config_put(config);
2912 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2913 * @stream: An i915 perf stream
2914 * @cmd: the ioctl request
2915 * @arg: the ioctl data
2917 * Note: The &perf->lock mutex has been taken to serialize
2918 * with any non-file-operation driver hooks.
2920 * Returns: zero on success or a negative error code. Returns -EINVAL for
2921 * an unknown ioctl request.
2923 static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
2928 case I915_PERF_IOCTL_ENABLE:
2929 i915_perf_enable_locked(stream);
2931 case I915_PERF_IOCTL_DISABLE:
2932 i915_perf_disable_locked(stream);
2934 case I915_PERF_IOCTL_CONFIG:
2935 return i915_perf_config_locked(stream, arg);
2942 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2943 * @file: An i915 perf stream file
2944 * @cmd: the ioctl request
2945 * @arg: the ioctl data
2947 * Implementation deferred to i915_perf_ioctl_locked().
2949 * Returns: zero on success or a negative error code. Returns -EINVAL for
2950 * an unknown ioctl request.
2952 static long i915_perf_ioctl(struct file *file,
2956 struct i915_perf_stream *stream = file->private_data;
2957 struct i915_perf *perf = stream->perf;
2960 mutex_lock(&perf->lock);
2961 ret = i915_perf_ioctl_locked(stream, cmd, arg);
2962 mutex_unlock(&perf->lock);
2968 * i915_perf_destroy_locked - destroy an i915 perf stream
2969 * @stream: An i915 perf stream
2971 * Frees all resources associated with the given i915 perf @stream, disabling
2972 * any associated data capture in the process.
2974 * Note: The &perf->lock mutex has been taken to serialize
2975 * with any non-file-operation driver hooks.
2977 static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
2979 if (stream->enabled)
2980 i915_perf_disable_locked(stream);
2982 if (stream->ops->destroy)
2983 stream->ops->destroy(stream);
2986 i915_gem_context_put(stream->ctx);
2992 * i915_perf_release - handles userspace close() of a stream file
2993 * @inode: anonymous inode associated with file
2994 * @file: An i915 perf stream file
2996 * Cleans up any resources associated with an open i915 perf stream file.
2998 * NB: close() can't really fail from the userspace point of view.
3000 * Returns: zero on success or a negative error code.
3002 static int i915_perf_release(struct inode *inode, struct file *file)
3004 struct i915_perf_stream *stream = file->private_data;
3005 struct i915_perf *perf = stream->perf;
3007 mutex_lock(&perf->lock);
3008 i915_perf_destroy_locked(stream);
3009 mutex_unlock(&perf->lock);
3011 /* Release the reference the perf stream kept on the driver. */
3012 drm_dev_put(&perf->i915->drm);
3018 static const struct file_operations fops = {
3019 .owner = THIS_MODULE,
3020 .llseek = no_llseek,
3021 .release = i915_perf_release,
3022 .poll = i915_perf_poll,
3023 .read = i915_perf_read,
3024 .unlocked_ioctl = i915_perf_ioctl,
3025 /* Our ioctl have no arguments, so it's safe to use the same function
3026 * to handle 32bits compatibility.
3028 .compat_ioctl = i915_perf_ioctl,
3033 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
3034 * @perf: i915 perf instance
3035 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
3036 * @props: individually validated u64 property value pairs
3039 * See i915_perf_ioctl_open() for interface details.
3041 * Implements further stream config validation and stream initialization on
3042 * behalf of i915_perf_open_ioctl() with the &perf->lock mutex
3043 * taken to serialize with any non-file-operation driver hooks.
3045 * Note: at this point the @props have only been validated in isolation and
3046 * it's still necessary to validate that the combination of properties makes
3049 * In the case where userspace is interested in OA unit metrics then further
3050 * config validation and stream initialization details will be handled by
3051 * i915_oa_stream_init(). The code here should only validate config state that
3052 * will be relevant to all stream types / backends.
3054 * Returns: zero on success or a negative error code.
3057 i915_perf_open_ioctl_locked(struct i915_perf *perf,
3058 struct drm_i915_perf_open_param *param,
3059 struct perf_open_properties *props,
3060 struct drm_file *file)
3062 struct i915_gem_context *specific_ctx = NULL;
3063 struct i915_perf_stream *stream = NULL;
3064 unsigned long f_flags = 0;
3065 bool privileged_op = true;
3069 if (props->single_context) {
3070 u32 ctx_handle = props->ctx_handle;
3071 struct drm_i915_file_private *file_priv = file->driver_priv;
3073 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
3074 if (!specific_ctx) {
3075 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
3082 if (props->hold_preemption) {
3083 if (!props->single_context) {
3084 DRM_DEBUG("preemption disable with no context\n");
3088 privileged_op = true;
3092 * On Haswell the OA unit supports clock gating off for a specific
3093 * context and in this mode there's no visibility of metrics for the
3094 * rest of the system, which we consider acceptable for a
3095 * non-privileged client.
3097 * For Gen8+ the OA unit no longer supports clock gating off for a
3098 * specific context and the kernel can't securely stop the counters
3099 * from updating as system-wide / global values. Even though we can
3100 * filter reports based on the included context ID we can't block
3101 * clients from seeing the raw / global counter values via
3102 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
3103 * enable the OA unit by default.
3105 if (IS_HASWELL(perf->i915) && specific_ctx && !props->hold_preemption)
3106 privileged_op = false;
3108 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
3109 * we check a dev.i915.perf_stream_paranoid sysctl option
3110 * to determine if it's ok to access system wide OA counters
3111 * without CAP_SYS_ADMIN privileges.
3113 if (privileged_op &&
3114 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3115 DRM_DEBUG("Insufficient privileges to open i915 perf stream\n");
3120 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
3126 stream->perf = perf;
3127 stream->ctx = specific_ctx;
3129 ret = i915_oa_stream_init(stream, param, props);
3133 /* we avoid simply assigning stream->sample_flags = props->sample_flags
3134 * to have _stream_init check the combination of sample flags more
3135 * thoroughly, but still this is the expected result at this point.
3137 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
3142 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
3143 f_flags |= O_CLOEXEC;
3144 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
3145 f_flags |= O_NONBLOCK;
3147 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
3148 if (stream_fd < 0) {
3153 if (!(param->flags & I915_PERF_FLAG_DISABLED))
3154 i915_perf_enable_locked(stream);
3156 /* Take a reference on the driver that will be kept with stream_fd
3157 * until its release.
3159 drm_dev_get(&perf->i915->drm);
3164 if (stream->ops->destroy)
3165 stream->ops->destroy(stream);
3170 i915_gem_context_put(specific_ctx);
3175 static u64 oa_exponent_to_ns(struct i915_perf *perf, int exponent)
3177 return div64_u64(1000000000ULL * (2ULL << exponent),
3178 1000ULL * RUNTIME_INFO(perf->i915)->cs_timestamp_frequency_khz);
3182 * read_properties_unlocked - validate + copy userspace stream open properties
3183 * @perf: i915 perf instance
3184 * @uprops: The array of u64 key value pairs given by userspace
3185 * @n_props: The number of key value pairs expected in @uprops
3186 * @props: The stream configuration built up while validating properties
3188 * Note this function only validates properties in isolation it doesn't
3189 * validate that the combination of properties makes sense or that all
3190 * properties necessary for a particular kind of stream have been set.
3192 * Note that there currently aren't any ordering requirements for properties so
3193 * we shouldn't validate or assume anything about ordering here. This doesn't
3194 * rule out defining new properties with ordering requirements in the future.
3196 static int read_properties_unlocked(struct i915_perf *perf,
3199 struct perf_open_properties *props)
3201 u64 __user *uprop = uprops;
3204 memset(props, 0, sizeof(struct perf_open_properties));
3207 DRM_DEBUG("No i915 perf properties given\n");
3211 /* At the moment we only support using i915-perf on the RCS. */
3212 props->engine = intel_engine_lookup_user(perf->i915,
3213 I915_ENGINE_CLASS_RENDER,
3215 if (!props->engine) {
3216 DRM_DEBUG("No RENDER-capable engines\n");
3220 /* Considering that ID = 0 is reserved and assuming that we don't
3221 * (currently) expect any configurations to ever specify duplicate
3222 * values for a particular property ID then the last _PROP_MAX value is
3223 * one greater than the maximum number of properties we expect to get
3226 if (n_props >= DRM_I915_PERF_PROP_MAX) {
3227 DRM_DEBUG("More i915 perf properties specified than exist\n");
3231 for (i = 0; i < n_props; i++) {
3232 u64 oa_period, oa_freq_hz;
3236 ret = get_user(id, uprop);
3240 ret = get_user(value, uprop + 1);
3244 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
3245 DRM_DEBUG("Unknown i915 perf property ID\n");
3249 switch ((enum drm_i915_perf_property_id)id) {
3250 case DRM_I915_PERF_PROP_CTX_HANDLE:
3251 props->single_context = 1;
3252 props->ctx_handle = value;
3254 case DRM_I915_PERF_PROP_SAMPLE_OA:
3256 props->sample_flags |= SAMPLE_OA_REPORT;
3258 case DRM_I915_PERF_PROP_OA_METRICS_SET:
3260 DRM_DEBUG("Unknown OA metric set ID\n");
3263 props->metrics_set = value;
3265 case DRM_I915_PERF_PROP_OA_FORMAT:
3266 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
3267 DRM_DEBUG("Out-of-range OA report format %llu\n",
3271 if (!perf->oa_formats[value].size) {
3272 DRM_DEBUG("Unsupported OA report format %llu\n",
3276 props->oa_format = value;
3278 case DRM_I915_PERF_PROP_OA_EXPONENT:
3279 if (value > OA_EXPONENT_MAX) {
3280 DRM_DEBUG("OA timer exponent too high (> %u)\n",
3285 /* Theoretically we can program the OA unit to sample
3286 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
3287 * for BXT. We don't allow such high sampling
3288 * frequencies by default unless root.
3291 BUILD_BUG_ON(sizeof(oa_period) != 8);
3292 oa_period = oa_exponent_to_ns(perf, value);
3294 /* This check is primarily to ensure that oa_period <=
3295 * UINT32_MAX (before passing to do_div which only
3296 * accepts a u32 denominator), but we can also skip
3297 * checking anything < 1Hz which implicitly can't be
3298 * limited via an integer oa_max_sample_rate.
3300 if (oa_period <= NSEC_PER_SEC) {
3301 u64 tmp = NSEC_PER_SEC;
3302 do_div(tmp, oa_period);
3307 if (oa_freq_hz > i915_oa_max_sample_rate &&
3308 !capable(CAP_SYS_ADMIN)) {
3309 DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
3310 i915_oa_max_sample_rate);
3314 props->oa_periodic = true;
3315 props->oa_period_exponent = value;
3317 case DRM_I915_PERF_PROP_HOLD_PREEMPTION:
3318 props->hold_preemption = !!value;
3320 case DRM_I915_PERF_PROP_MAX:
3332 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
3334 * @data: ioctl data copied from userspace (unvalidated)
3337 * Validates the stream open parameters given by userspace including flags
3338 * and an array of u64 key, value pair properties.
3340 * Very little is assumed up front about the nature of the stream being
3341 * opened (for instance we don't assume it's for periodic OA unit metrics). An
3342 * i915-perf stream is expected to be a suitable interface for other forms of
3343 * buffered data written by the GPU besides periodic OA metrics.
3345 * Note we copy the properties from userspace outside of the i915 perf
3346 * mutex to avoid an awkward lockdep with mmap_sem.
3348 * Most of the implementation details are handled by
3349 * i915_perf_open_ioctl_locked() after taking the &perf->lock
3350 * mutex for serializing with any non-file-operation driver hooks.
3352 * Return: A newly opened i915 Perf stream file descriptor or negative
3353 * error code on failure.
3355 int i915_perf_open_ioctl(struct drm_device *dev, void *data,
3356 struct drm_file *file)
3358 struct i915_perf *perf = &to_i915(dev)->perf;
3359 struct drm_i915_perf_open_param *param = data;
3360 struct perf_open_properties props;
3361 u32 known_open_flags;
3365 DRM_DEBUG("i915 perf interface not available for this system\n");
3369 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
3370 I915_PERF_FLAG_FD_NONBLOCK |
3371 I915_PERF_FLAG_DISABLED;
3372 if (param->flags & ~known_open_flags) {
3373 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
3377 ret = read_properties_unlocked(perf,
3378 u64_to_user_ptr(param->properties_ptr),
3379 param->num_properties,
3384 mutex_lock(&perf->lock);
3385 ret = i915_perf_open_ioctl_locked(perf, param, &props, file);
3386 mutex_unlock(&perf->lock);
3392 * i915_perf_register - exposes i915-perf to userspace
3393 * @i915: i915 device instance
3395 * In particular OA metric sets are advertised under a sysfs metrics/
3396 * directory allowing userspace to enumerate valid IDs that can be
3397 * used to open an i915-perf stream.
3399 void i915_perf_register(struct drm_i915_private *i915)
3401 struct i915_perf *perf = &i915->perf;
3407 /* To be sure we're synchronized with an attempted
3408 * i915_perf_open_ioctl(); considering that we register after
3409 * being exposed to userspace.
3411 mutex_lock(&perf->lock);
3413 perf->metrics_kobj =
3414 kobject_create_and_add("metrics",
3415 &i915->drm.primary->kdev->kobj);
3416 if (!perf->metrics_kobj)
3419 sysfs_attr_init(&perf->test_config.sysfs_metric_id.attr);
3421 if (INTEL_GEN(i915) >= 11) {
3422 i915_perf_load_test_config_icl(i915);
3423 } else if (IS_CANNONLAKE(i915)) {
3424 i915_perf_load_test_config_cnl(i915);
3425 } else if (IS_COFFEELAKE(i915)) {
3426 if (IS_CFL_GT2(i915))
3427 i915_perf_load_test_config_cflgt2(i915);
3428 if (IS_CFL_GT3(i915))
3429 i915_perf_load_test_config_cflgt3(i915);
3430 } else if (IS_GEMINILAKE(i915)) {
3431 i915_perf_load_test_config_glk(i915);
3432 } else if (IS_KABYLAKE(i915)) {
3433 if (IS_KBL_GT2(i915))
3434 i915_perf_load_test_config_kblgt2(i915);
3435 else if (IS_KBL_GT3(i915))
3436 i915_perf_load_test_config_kblgt3(i915);
3437 } else if (IS_BROXTON(i915)) {
3438 i915_perf_load_test_config_bxt(i915);
3439 } else if (IS_SKYLAKE(i915)) {
3440 if (IS_SKL_GT2(i915))
3441 i915_perf_load_test_config_sklgt2(i915);
3442 else if (IS_SKL_GT3(i915))
3443 i915_perf_load_test_config_sklgt3(i915);
3444 else if (IS_SKL_GT4(i915))
3445 i915_perf_load_test_config_sklgt4(i915);
3446 } else if (IS_CHERRYVIEW(i915)) {
3447 i915_perf_load_test_config_chv(i915);
3448 } else if (IS_BROADWELL(i915)) {
3449 i915_perf_load_test_config_bdw(i915);
3450 } else if (IS_HASWELL(i915)) {
3451 i915_perf_load_test_config_hsw(i915);
3454 if (perf->test_config.id == 0)
3457 ret = sysfs_create_group(perf->metrics_kobj,
3458 &perf->test_config.sysfs_metric);
3462 perf->test_config.perf = perf;
3463 kref_init(&perf->test_config.ref);
3468 kobject_put(perf->metrics_kobj);
3469 perf->metrics_kobj = NULL;
3472 mutex_unlock(&perf->lock);
3476 * i915_perf_unregister - hide i915-perf from userspace
3477 * @i915: i915 device instance
3479 * i915-perf state cleanup is split up into an 'unregister' and
3480 * 'deinit' phase where the interface is first hidden from
3481 * userspace by i915_perf_unregister() before cleaning up
3482 * remaining state in i915_perf_fini().
3484 void i915_perf_unregister(struct drm_i915_private *i915)
3486 struct i915_perf *perf = &i915->perf;
3488 if (!perf->metrics_kobj)
3491 sysfs_remove_group(perf->metrics_kobj,
3492 &perf->test_config.sysfs_metric);
3494 kobject_put(perf->metrics_kobj);
3495 perf->metrics_kobj = NULL;
3498 static bool gen8_is_valid_flex_addr(struct i915_perf *perf, u32 addr)
3500 static const i915_reg_t flex_eu_regs[] = {
3511 for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
3512 if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
3518 static bool gen7_is_valid_b_counter_addr(struct i915_perf *perf, u32 addr)
3520 return (addr >= i915_mmio_reg_offset(OASTARTTRIG1) &&
3521 addr <= i915_mmio_reg_offset(OASTARTTRIG8)) ||
3522 (addr >= i915_mmio_reg_offset(OAREPORTTRIG1) &&
3523 addr <= i915_mmio_reg_offset(OAREPORTTRIG8)) ||
3524 (addr >= i915_mmio_reg_offset(OACEC0_0) &&
3525 addr <= i915_mmio_reg_offset(OACEC7_1));
3528 static bool gen7_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3530 return addr == i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) ||
3531 (addr >= i915_mmio_reg_offset(MICRO_BP0_0) &&
3532 addr <= i915_mmio_reg_offset(NOA_WRITE)) ||
3533 (addr >= i915_mmio_reg_offset(OA_PERFCNT1_LO) &&
3534 addr <= i915_mmio_reg_offset(OA_PERFCNT2_HI)) ||
3535 (addr >= i915_mmio_reg_offset(OA_PERFMATRIX_LO) &&
3536 addr <= i915_mmio_reg_offset(OA_PERFMATRIX_HI));
3539 static bool gen8_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3541 return gen7_is_valid_mux_addr(perf, addr) ||
3542 addr == i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) ||
3543 (addr >= i915_mmio_reg_offset(RPM_CONFIG0) &&
3544 addr <= i915_mmio_reg_offset(NOA_CONFIG(8)));
3547 static bool gen10_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3549 return gen8_is_valid_mux_addr(perf, addr) ||
3550 addr == i915_mmio_reg_offset(GEN10_NOA_WRITE_HIGH) ||
3551 (addr >= i915_mmio_reg_offset(OA_PERFCNT3_LO) &&
3552 addr <= i915_mmio_reg_offset(OA_PERFCNT4_HI));
3555 static bool hsw_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3557 return gen7_is_valid_mux_addr(perf, addr) ||
3558 (addr >= 0x25100 && addr <= 0x2FF90) ||
3559 (addr >= i915_mmio_reg_offset(HSW_MBVID2_NOA0) &&
3560 addr <= i915_mmio_reg_offset(HSW_MBVID2_NOA9)) ||
3561 addr == i915_mmio_reg_offset(HSW_MBVID2_MISR0);
3564 static bool chv_is_valid_mux_addr(struct i915_perf *perf, u32 addr)
3566 return gen7_is_valid_mux_addr(perf, addr) ||
3567 (addr >= 0x182300 && addr <= 0x1823A4);
3570 static u32 mask_reg_value(u32 reg, u32 val)
3572 /* HALF_SLICE_CHICKEN2 is programmed with a the
3573 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
3574 * programmed by userspace doesn't change this.
3576 if (i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) == reg)
3577 val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
3579 /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
3580 * indicated by its name and a bunch of selection fields used by OA
3583 if (i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) == reg)
3584 val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
3589 static struct i915_oa_reg *alloc_oa_regs(struct i915_perf *perf,
3590 bool (*is_valid)(struct i915_perf *perf, u32 addr),
3594 struct i915_oa_reg *oa_regs;
3601 if (!access_ok(regs, n_regs * sizeof(u32) * 2))
3602 return ERR_PTR(-EFAULT);
3604 /* No is_valid function means we're not allowing any register to be programmed. */
3605 GEM_BUG_ON(!is_valid);
3607 return ERR_PTR(-EINVAL);
3609 oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
3611 return ERR_PTR(-ENOMEM);
3613 for (i = 0; i < n_regs; i++) {
3616 err = get_user(addr, regs);
3620 if (!is_valid(perf, addr)) {
3621 DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
3626 err = get_user(value, regs + 1);
3630 oa_regs[i].addr = _MMIO(addr);
3631 oa_regs[i].value = mask_reg_value(addr, value);
3640 return ERR_PTR(err);
3643 static ssize_t show_dynamic_id(struct device *dev,
3644 struct device_attribute *attr,
3647 struct i915_oa_config *oa_config =
3648 container_of(attr, typeof(*oa_config), sysfs_metric_id);
3650 return sprintf(buf, "%d\n", oa_config->id);
3653 static int create_dynamic_oa_sysfs_entry(struct i915_perf *perf,
3654 struct i915_oa_config *oa_config)
3656 sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
3657 oa_config->sysfs_metric_id.attr.name = "id";
3658 oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
3659 oa_config->sysfs_metric_id.show = show_dynamic_id;
3660 oa_config->sysfs_metric_id.store = NULL;
3662 oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
3663 oa_config->attrs[1] = NULL;
3665 oa_config->sysfs_metric.name = oa_config->uuid;
3666 oa_config->sysfs_metric.attrs = oa_config->attrs;
3668 return sysfs_create_group(perf->metrics_kobj,
3669 &oa_config->sysfs_metric);
3673 * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
3675 * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
3676 * userspace (unvalidated)
3679 * Validates the submitted OA register to be saved into a new OA config that
3680 * can then be used for programming the OA unit and its NOA network.
3682 * Returns: A new allocated config number to be used with the perf open ioctl
3683 * or a negative error code on failure.
3685 int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
3686 struct drm_file *file)
3688 struct i915_perf *perf = &to_i915(dev)->perf;
3689 struct drm_i915_perf_oa_config *args = data;
3690 struct i915_oa_config *oa_config, *tmp;
3691 static struct i915_oa_reg *regs;
3695 DRM_DEBUG("i915 perf interface not available for this system\n");
3699 if (!perf->metrics_kobj) {
3700 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
3704 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3705 DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
3709 if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
3710 (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
3711 (!args->flex_regs_ptr || !args->n_flex_regs)) {
3712 DRM_DEBUG("No OA registers given\n");
3716 oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
3718 DRM_DEBUG("Failed to allocate memory for the OA config\n");
3722 oa_config->perf = perf;
3723 kref_init(&oa_config->ref);
3725 if (!uuid_is_valid(args->uuid)) {
3726 DRM_DEBUG("Invalid uuid format for OA config\n");
3731 /* Last character in oa_config->uuid will be 0 because oa_config is
3734 memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
3736 oa_config->mux_regs_len = args->n_mux_regs;
3737 regs = alloc_oa_regs(perf,
3738 perf->ops.is_valid_mux_reg,
3739 u64_to_user_ptr(args->mux_regs_ptr),
3743 DRM_DEBUG("Failed to create OA config for mux_regs\n");
3744 err = PTR_ERR(regs);
3747 oa_config->mux_regs = regs;
3749 oa_config->b_counter_regs_len = args->n_boolean_regs;
3750 regs = alloc_oa_regs(perf,
3751 perf->ops.is_valid_b_counter_reg,
3752 u64_to_user_ptr(args->boolean_regs_ptr),
3753 args->n_boolean_regs);
3756 DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
3757 err = PTR_ERR(regs);
3760 oa_config->b_counter_regs = regs;
3762 if (INTEL_GEN(perf->i915) < 8) {
3763 if (args->n_flex_regs != 0) {
3768 oa_config->flex_regs_len = args->n_flex_regs;
3769 regs = alloc_oa_regs(perf,
3770 perf->ops.is_valid_flex_reg,
3771 u64_to_user_ptr(args->flex_regs_ptr),
3775 DRM_DEBUG("Failed to create OA config for flex_regs\n");
3776 err = PTR_ERR(regs);
3779 oa_config->flex_regs = regs;
3782 err = mutex_lock_interruptible(&perf->metrics_lock);
3786 /* We shouldn't have too many configs, so this iteration shouldn't be
3789 idr_for_each_entry(&perf->metrics_idr, tmp, id) {
3790 if (!strcmp(tmp->uuid, oa_config->uuid)) {
3791 DRM_DEBUG("OA config already exists with this uuid\n");
3797 err = create_dynamic_oa_sysfs_entry(perf, oa_config);
3799 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3803 /* Config id 0 is invalid, id 1 for kernel stored test config. */
3804 oa_config->id = idr_alloc(&perf->metrics_idr,
3807 if (oa_config->id < 0) {
3808 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3809 err = oa_config->id;
3813 mutex_unlock(&perf->metrics_lock);
3815 DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id);
3817 return oa_config->id;
3820 mutex_unlock(&perf->metrics_lock);
3822 i915_oa_config_put(oa_config);
3823 DRM_DEBUG("Failed to add new OA config\n");
3828 * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
3830 * @data: ioctl data (pointer to u64 integer) copied from userspace
3833 * Configs can be removed while being used, the will stop appearing in sysfs
3834 * and their content will be freed when the stream using the config is closed.
3836 * Returns: 0 on success or a negative error code on failure.
3838 int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
3839 struct drm_file *file)
3841 struct i915_perf *perf = &to_i915(dev)->perf;
3843 struct i915_oa_config *oa_config;
3847 DRM_DEBUG("i915 perf interface not available for this system\n");
3851 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3852 DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
3856 ret = mutex_lock_interruptible(&perf->metrics_lock);
3860 oa_config = idr_find(&perf->metrics_idr, *arg);
3862 DRM_DEBUG("Failed to remove unknown OA config\n");
3867 GEM_BUG_ON(*arg != oa_config->id);
3869 sysfs_remove_group(perf->metrics_kobj, &oa_config->sysfs_metric);
3871 idr_remove(&perf->metrics_idr, *arg);
3873 mutex_unlock(&perf->metrics_lock);
3875 DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
3877 i915_oa_config_put(oa_config);
3882 mutex_unlock(&perf->metrics_lock);
3886 static struct ctl_table oa_table[] = {
3888 .procname = "perf_stream_paranoid",
3889 .data = &i915_perf_stream_paranoid,
3890 .maxlen = sizeof(i915_perf_stream_paranoid),
3892 .proc_handler = proc_dointvec_minmax,
3893 .extra1 = SYSCTL_ZERO,
3894 .extra2 = SYSCTL_ONE,
3897 .procname = "oa_max_sample_rate",
3898 .data = &i915_oa_max_sample_rate,
3899 .maxlen = sizeof(i915_oa_max_sample_rate),
3901 .proc_handler = proc_dointvec_minmax,
3902 .extra1 = SYSCTL_ZERO,
3903 .extra2 = &oa_sample_rate_hard_limit,
3908 static struct ctl_table i915_root[] = {
3918 static struct ctl_table dev_root[] = {
3929 * i915_perf_init - initialize i915-perf state on module load
3930 * @i915: i915 device instance
3932 * Initializes i915-perf state without exposing anything to userspace.
3934 * Note: i915-perf initialization is split into an 'init' and 'register'
3935 * phase with the i915_perf_register() exposing state to userspace.
3937 void i915_perf_init(struct drm_i915_private *i915)
3939 struct i915_perf *perf = &i915->perf;
3941 /* XXX const struct i915_perf_ops! */
3943 if (IS_HASWELL(i915)) {
3944 perf->ops.is_valid_b_counter_reg = gen7_is_valid_b_counter_addr;
3945 perf->ops.is_valid_mux_reg = hsw_is_valid_mux_addr;
3946 perf->ops.is_valid_flex_reg = NULL;
3947 perf->ops.enable_metric_set = hsw_enable_metric_set;
3948 perf->ops.disable_metric_set = hsw_disable_metric_set;
3949 perf->ops.oa_enable = gen7_oa_enable;
3950 perf->ops.oa_disable = gen7_oa_disable;
3951 perf->ops.read = gen7_oa_read;
3952 perf->ops.oa_hw_tail_read = gen7_oa_hw_tail_read;
3954 perf->oa_formats = hsw_oa_formats;
3955 } else if (HAS_LOGICAL_RING_CONTEXTS(i915)) {
3956 /* Note: that although we could theoretically also support the
3957 * legacy ringbuffer mode on BDW (and earlier iterations of
3958 * this driver, before upstreaming did this) it didn't seem
3959 * worth the complexity to maintain now that BDW+ enable
3960 * execlist mode by default.
3962 perf->oa_formats = gen8_plus_oa_formats;
3964 perf->ops.oa_enable = gen8_oa_enable;
3965 perf->ops.oa_disable = gen8_oa_disable;
3966 perf->ops.read = gen8_oa_read;
3967 perf->ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
3969 if (IS_GEN_RANGE(i915, 8, 9)) {
3970 perf->ops.is_valid_b_counter_reg =
3971 gen7_is_valid_b_counter_addr;
3972 perf->ops.is_valid_mux_reg =
3973 gen8_is_valid_mux_addr;
3974 perf->ops.is_valid_flex_reg =
3975 gen8_is_valid_flex_addr;
3977 if (IS_CHERRYVIEW(i915)) {
3978 perf->ops.is_valid_mux_reg =
3979 chv_is_valid_mux_addr;
3982 perf->ops.enable_metric_set = gen8_enable_metric_set;
3983 perf->ops.disable_metric_set = gen8_disable_metric_set;
3985 if (IS_GEN(i915, 8)) {
3986 perf->ctx_oactxctrl_offset = 0x120;
3987 perf->ctx_flexeu0_offset = 0x2ce;
3989 perf->gen8_valid_ctx_bit = BIT(25);
3991 perf->ctx_oactxctrl_offset = 0x128;
3992 perf->ctx_flexeu0_offset = 0x3de;
3994 perf->gen8_valid_ctx_bit = BIT(16);
3996 } else if (IS_GEN_RANGE(i915, 10, 11)) {
3997 perf->ops.is_valid_b_counter_reg =
3998 gen7_is_valid_b_counter_addr;
3999 perf->ops.is_valid_mux_reg =
4000 gen10_is_valid_mux_addr;
4001 perf->ops.is_valid_flex_reg =
4002 gen8_is_valid_flex_addr;
4004 perf->ops.enable_metric_set = gen8_enable_metric_set;
4005 perf->ops.disable_metric_set = gen10_disable_metric_set;
4007 if (IS_GEN(i915, 10)) {
4008 perf->ctx_oactxctrl_offset = 0x128;
4009 perf->ctx_flexeu0_offset = 0x3de;
4011 perf->ctx_oactxctrl_offset = 0x124;
4012 perf->ctx_flexeu0_offset = 0x78e;
4014 perf->gen8_valid_ctx_bit = BIT(16);
4018 if (perf->ops.enable_metric_set) {
4019 mutex_init(&perf->lock);
4021 oa_sample_rate_hard_limit = 1000 *
4022 (RUNTIME_INFO(i915)->cs_timestamp_frequency_khz / 2);
4023 perf->sysctl_header = register_sysctl_table(dev_root);
4025 mutex_init(&perf->metrics_lock);
4026 idr_init(&perf->metrics_idr);
4028 /* We set up some ratelimit state to potentially throttle any
4029 * _NOTES about spurious, invalid OA reports which we don't
4030 * forward to userspace.
4032 * We print a _NOTE about any throttling when closing the
4033 * stream instead of waiting until driver _fini which no one
4036 * Using the same limiting factors as printk_ratelimit()
4038 ratelimit_state_init(&perf->spurious_report_rs, 5 * HZ, 10);
4039 /* Since we use a DRM_NOTE for spurious reports it would be
4040 * inconsistent to let __ratelimit() automatically print a
4041 * warning for throttling.
4043 ratelimit_set_flags(&perf->spurious_report_rs,
4044 RATELIMIT_MSG_ON_RELEASE);
4046 atomic64_set(&perf->noa_programming_delay,
4047 500 * 1000 /* 500us */);
4053 static int destroy_config(int id, void *p, void *data)
4055 i915_oa_config_put(p);
4060 * i915_perf_fini - Counter part to i915_perf_init()
4061 * @i915: i915 device instance
4063 void i915_perf_fini(struct drm_i915_private *i915)
4065 struct i915_perf *perf = &i915->perf;
4070 idr_for_each(&perf->metrics_idr, destroy_config, perf);
4071 idr_destroy(&perf->metrics_idr);
4073 unregister_sysctl_table(perf->sysctl_header);
4075 memset(&perf->ops, 0, sizeof(perf->ops));
4080 * i915_perf_ioctl_version - Version of the i915-perf subsystem
4082 * This version number is used by userspace to detect available features.
4084 int i915_perf_ioctl_version(void)
4087 * 1: Initial version
4088 * I915_PERF_IOCTL_ENABLE
4089 * I915_PERF_IOCTL_DISABLE
4091 * 2: Added runtime modification of OA config.
4092 * I915_PERF_IOCTL_CONFIG
4094 * 3: Add DRM_I915_PERF_PROP_HOLD_PREEMPTION parameter to hold
4095 * preemption on a particular context so that performance data is
4096 * accessible from a delta of MI_RPC reports without looking at the
4102 #if IS_ENABLED(CONFIG_DRM_I915_SELFTEST)
4103 #include "selftests/i915_perf.c"