blob: 1b40ac6d140044c5de4a637d98d8635efffc271d [file] [log] [blame]
Robert Braggeec688e2016-11-07 19:49:47 +00001/*
2 * Copyright © 2015-2016 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Robert Bragg <robert@sixbynine.org>
25 */
26
Robert Bragg7abbd8d2016-11-07 19:49:57 +000027
28/**
Robert Bragg16d98b32016-12-07 21:40:33 +000029 * DOC: i915 Perf Overview
Robert Bragg7abbd8d2016-11-07 19:49:57 +000030 *
31 * Gen graphics supports a large number of performance counters that can help
32 * driver and application developers understand and optimize their use of the
33 * GPU.
34 *
35 * This i915 perf interface enables userspace to configure and open a file
36 * descriptor representing a stream of GPU metrics which can then be read() as
37 * a stream of sample records.
38 *
39 * The interface is particularly suited to exposing buffered metrics that are
40 * captured by DMA from the GPU, unsynchronized with and unrelated to the CPU.
41 *
42 * Streams representing a single context are accessible to applications with a
43 * corresponding drm file descriptor, such that OpenGL can use the interface
44 * without special privileges. Access to system-wide metrics requires root
45 * privileges by default, unless changed via the dev.i915.perf_event_paranoid
46 * sysctl option.
47 *
Robert Bragg16d98b32016-12-07 21:40:33 +000048 */
49
50/**
51 * DOC: i915 Perf History and Comparison with Core Perf
Robert Bragg7abbd8d2016-11-07 19:49:57 +000052 *
53 * The interface was initially inspired by the core Perf infrastructure but
54 * some notable differences are:
55 *
56 * i915 perf file descriptors represent a "stream" instead of an "event"; where
57 * a perf event primarily corresponds to a single 64bit value, while a stream
58 * might sample sets of tightly-coupled counters, depending on the
59 * configuration. For example the Gen OA unit isn't designed to support
60 * orthogonal configurations of individual counters; it's configured for a set
61 * of related counters. Samples for an i915 perf stream capturing OA metrics
62 * will include a set of counter values packed in a compact HW specific format.
63 * The OA unit supports a number of different packing formats which can be
64 * selected by the user opening the stream. Perf has support for grouping
65 * events, but each event in the group is configured, validated and
66 * authenticated individually with separate system calls.
67 *
68 * i915 perf stream configurations are provided as an array of u64 (key,value)
69 * pairs, instead of a fixed struct with multiple miscellaneous config members,
70 * interleaved with event-type specific members.
71 *
72 * i915 perf doesn't support exposing metrics via an mmap'd circular buffer.
73 * The supported metrics are being written to memory by the GPU unsynchronized
74 * with the CPU, using HW specific packing formats for counter sets. Sometimes
75 * the constraints on HW configuration require reports to be filtered before it
76 * would be acceptable to expose them to unprivileged applications - to hide
77 * the metrics of other processes/contexts. For these use cases a read() based
78 * interface is a good fit, and provides an opportunity to filter data as it
79 * gets copied from the GPU mapped buffers to userspace buffers.
80 *
81 *
Robert Bragg16d98b32016-12-07 21:40:33 +000082 * Issues hit with first prototype based on Core Perf
83 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Robert Bragg7abbd8d2016-11-07 19:49:57 +000084 *
85 * The first prototype of this driver was based on the core perf
86 * infrastructure, and while we did make that mostly work, with some changes to
87 * perf, we found we were breaking or working around too many assumptions baked
88 * into perf's currently cpu centric design.
89 *
90 * In the end we didn't see a clear benefit to making perf's implementation and
91 * interface more complex by changing design assumptions while we knew we still
92 * wouldn't be able to use any existing perf based userspace tools.
93 *
94 * Also considering the Gen specific nature of the Observability hardware and
95 * how userspace will sometimes need to combine i915 perf OA metrics with
96 * side-band OA data captured via MI_REPORT_PERF_COUNT commands; we're
97 * expecting the interface to be used by a platform specific userspace such as
98 * OpenGL or tools. This is to say; we aren't inherently missing out on having
99 * a standard vendor/architecture agnostic interface by not using perf.
100 *
101 *
102 * For posterity, in case we might re-visit trying to adapt core perf to be
103 * better suited to exposing i915 metrics these were the main pain points we
104 * hit:
105 *
106 * - The perf based OA PMU driver broke some significant design assumptions:
107 *
108 * Existing perf pmus are used for profiling work on a cpu and we were
109 * introducing the idea of _IS_DEVICE pmus with different security
110 * implications, the need to fake cpu-related data (such as user/kernel
111 * registers) to fit with perf's current design, and adding _DEVICE records
112 * as a way to forward device-specific status records.
113 *
114 * The OA unit writes reports of counters into a circular buffer, without
115 * involvement from the CPU, making our PMU driver the first of a kind.
116 *
117 * Given the way we were periodically forward data from the GPU-mapped, OA
118 * buffer to perf's buffer, those bursts of sample writes looked to perf like
119 * we were sampling too fast and so we had to subvert its throttling checks.
120 *
121 * Perf supports groups of counters and allows those to be read via
122 * transactions internally but transactions currently seem designed to be
123 * explicitly initiated from the cpu (say in response to a userspace read())
124 * and while we could pull a report out of the OA buffer we can't
125 * trigger a report from the cpu on demand.
126 *
127 * Related to being report based; the OA counters are configured in HW as a
128 * set while perf generally expects counter configurations to be orthogonal.
129 * Although counters can be associated with a group leader as they are
130 * opened, there's no clear precedent for being able to provide group-wide
131 * configuration attributes (for example we want to let userspace choose the
132 * OA unit report format used to capture all counters in a set, or specify a
133 * GPU context to filter metrics on). We avoided using perf's grouping
134 * feature and forwarded OA reports to userspace via perf's 'raw' sample
135 * field. This suited our userspace well considering how coupled the counters
136 * are when dealing with normalizing. It would be inconvenient to split
137 * counters up into separate events, only to require userspace to recombine
138 * them. For Mesa it's also convenient to be forwarded raw, periodic reports
139 * for combining with the side-band raw reports it captures using
140 * MI_REPORT_PERF_COUNT commands.
141 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000142 * - As a side note on perf's grouping feature; there was also some concern
Robert Bragg7abbd8d2016-11-07 19:49:57 +0000143 * that using PERF_FORMAT_GROUP as a way to pack together counter values
144 * would quite drastically inflate our sample sizes, which would likely
145 * lower the effective sampling resolutions we could use when the available
146 * memory bandwidth is limited.
147 *
148 * With the OA unit's report formats, counters are packed together as 32
149 * or 40bit values, with the largest report size being 256 bytes.
150 *
151 * PERF_FORMAT_GROUP values are 64bit, but there doesn't appear to be a
152 * documented ordering to the values, implying PERF_FORMAT_ID must also be
153 * used to add a 64bit ID before each value; giving 16 bytes per counter.
154 *
155 * Related to counter orthogonality; we can't time share the OA unit, while
156 * event scheduling is a central design idea within perf for allowing
157 * userspace to open + enable more events than can be configured in HW at any
158 * one time. The OA unit is not designed to allow re-configuration while in
159 * use. We can't reconfigure the OA unit without losing internal OA unit
160 * state which we can't access explicitly to save and restore. Reconfiguring
161 * the OA unit is also relatively slow, involving ~100 register writes. From
162 * userspace Mesa also depends on a stable OA configuration when emitting
163 * MI_REPORT_PERF_COUNT commands and importantly the OA unit can't be
164 * disabled while there are outstanding MI_RPC commands lest we hang the
165 * command streamer.
166 *
167 * The contents of sample records aren't extensible by device drivers (i.e.
168 * the sample_type bits). As an example; Sourab Gupta had been looking to
169 * attach GPU timestamps to our OA samples. We were shoehorning OA reports
170 * into sample records by using the 'raw' field, but it's tricky to pack more
171 * than one thing into this field because events/core.c currently only lets a
172 * pmu give a single raw data pointer plus len which will be copied into the
173 * ring buffer. To include more than the OA report we'd have to copy the
174 * report into an intermediate larger buffer. I'd been considering allowing a
175 * vector of data+len values to be specified for copying the raw data, but
176 * it felt like a kludge to being using the raw field for this purpose.
177 *
178 * - It felt like our perf based PMU was making some technical compromises
179 * just for the sake of using perf:
180 *
181 * perf_event_open() requires events to either relate to a pid or a specific
182 * cpu core, while our device pmu related to neither. Events opened with a
183 * pid will be automatically enabled/disabled according to the scheduling of
184 * that process - so not appropriate for us. When an event is related to a
185 * cpu id, perf ensures pmu methods will be invoked via an inter process
186 * interrupt on that core. To avoid invasive changes our userspace opened OA
187 * perf events for a specific cpu. This was workable but it meant the
188 * majority of the OA driver ran in atomic context, including all OA report
189 * forwarding, which wasn't really necessary in our case and seems to make
190 * our locking requirements somewhat complex as we handled the interaction
191 * with the rest of the i915 driver.
192 */
193
Robert Braggeec688e2016-11-07 19:49:47 +0000194#include <linux/anon_inodes.h>
Robert Braggd7965152016-11-07 19:49:52 +0000195#include <linux/sizes.h>
Lionel Landwerlinf89823c2017-08-03 18:05:50 +0100196#include <linux/uuid.h>
Robert Braggeec688e2016-11-07 19:49:47 +0000197
198#include "i915_drv.h"
Robert Braggd7965152016-11-07 19:49:52 +0000199#include "i915_oa_hsw.h"
Robert Bragg19f81df2017-06-13 12:23:03 +0100200#include "i915_oa_bdw.h"
201#include "i915_oa_chv.h"
202#include "i915_oa_sklgt2.h"
203#include "i915_oa_sklgt3.h"
204#include "i915_oa_sklgt4.h"
205#include "i915_oa_bxt.h"
Lionel Landwerlin6c5c1d82017-06-13 12:23:08 +0100206#include "i915_oa_kblgt2.h"
207#include "i915_oa_kblgt3.h"
Lionel Landwerlin28c7ef92017-06-13 12:23:09 +0100208#include "i915_oa_glk.h"
Robert Braggd7965152016-11-07 19:49:52 +0000209
210/* HW requires this to be a power of two, between 128k and 16M, though driver
211 * is currently generally designed assuming the largest 16M size is used such
212 * that the overflow cases are unlikely in normal operation.
213 */
214#define OA_BUFFER_SIZE SZ_16M
215
216#define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
217
Robert Bragg0dd860c2017-05-11 16:43:28 +0100218/**
219 * DOC: OA Tail Pointer Race
220 *
221 * There's a HW race condition between OA unit tail pointer register updates and
Robert Braggd7965152016-11-07 19:49:52 +0000222 * writes to memory whereby the tail pointer can sometimes get ahead of what's
Robert Bragg0dd860c2017-05-11 16:43:28 +0100223 * been written out to the OA buffer so far (in terms of what's visible to the
224 * CPU).
Robert Braggd7965152016-11-07 19:49:52 +0000225 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100226 * Although this can be observed explicitly while copying reports to userspace
227 * by checking for a zeroed report-id field in tail reports, we want to account
Robert Bragg19f81df2017-06-13 12:23:03 +0100228 * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
Robert Bragg0dd860c2017-05-11 16:43:28 +0100229 * read() attempts.
Robert Braggd7965152016-11-07 19:49:52 +0000230 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100231 * In effect we define a tail pointer for reading that lags the real tail
232 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
233 * time for the corresponding reports to become visible to the CPU.
Robert Braggd7965152016-11-07 19:49:52 +0000234 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100235 * To manage this we actually track two tail pointers:
236 * 1) An 'aging' tail with an associated timestamp that is tracked until we
237 * can trust the corresponding data is visible to the CPU; at which point
238 * it is considered 'aged'.
239 * 2) An 'aged' tail that can be used for read()ing.
240 *
241 * The two separate pointers let us decouple read()s from tail pointer aging.
242 *
243 * The tail pointers are checked and updated at a limited rate within a hrtimer
244 * callback (the same callback that is used for delivering POLLIN events)
245 *
246 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
247 * indicates that an updated tail pointer is needed.
248 *
249 * Most of the implementation details for this workaround are in
Robert Bragg19f81df2017-06-13 12:23:03 +0100250 * oa_buffer_check_unlocked() and _append_oa_reports()
Robert Bragg0dd860c2017-05-11 16:43:28 +0100251 *
252 * Note for posterity: previously the driver used to define an effective tail
253 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
254 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
255 * This was flawed considering that the OA unit may also automatically generate
256 * non-periodic reports (such as on context switch) or the OA unit may be
257 * enabled without any periodic sampling.
Robert Braggd7965152016-11-07 19:49:52 +0000258 */
259#define OA_TAIL_MARGIN_NSEC 100000ULL
Robert Bragg0dd860c2017-05-11 16:43:28 +0100260#define INVALID_TAIL_PTR 0xffffffff
Robert Braggd7965152016-11-07 19:49:52 +0000261
262/* frequency for checking whether the OA unit has written new reports to the
263 * circular OA buffer...
264 */
265#define POLL_FREQUENCY 200
266#define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
267
Robert Braggccdf6342016-11-07 19:49:54 +0000268/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
269static int zero;
270static int one = 1;
271static u32 i915_perf_stream_paranoid = true;
272
Robert Braggd7965152016-11-07 19:49:52 +0000273/* The maximum exponent the hardware accepts is 63 (essentially it selects one
274 * of the 64bit timestamp bits to trigger reports from) but there's currently
275 * no known use case for sampling as infrequently as once per 47 thousand years.
276 *
277 * Since the timestamps included in OA reports are only 32bits it seems
278 * reasonable to limit the OA exponent where it's still possible to account for
279 * overflow in OA report timestamps.
280 */
281#define OA_EXPONENT_MAX 31
282
283#define INVALID_CTX_ID 0xffffffff
284
Robert Bragg19f81df2017-06-13 12:23:03 +0100285/* On Gen8+ automatically triggered OA reports include a 'reason' field... */
286#define OAREPORT_REASON_MASK 0x3f
287#define OAREPORT_REASON_SHIFT 19
288#define OAREPORT_REASON_TIMER (1<<0)
289#define OAREPORT_REASON_CTX_SWITCH (1<<3)
290#define OAREPORT_REASON_CLK_RATIO (1<<5)
291
Robert Braggd7965152016-11-07 19:49:52 +0000292
Robert Bragg00319ba2016-11-07 19:49:55 +0000293/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
294 *
Robert Bragg155e9412017-06-13 12:23:05 +0100295 * The highest sampling frequency we can theoretically program the OA unit
296 * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
297 *
298 * Initialized just before we register the sysctl parameter.
Robert Bragg00319ba2016-11-07 19:49:55 +0000299 */
Robert Bragg155e9412017-06-13 12:23:05 +0100300static int oa_sample_rate_hard_limit;
Robert Bragg00319ba2016-11-07 19:49:55 +0000301
302/* Theoretically we can program the OA unit to sample every 160ns but don't
303 * allow that by default unless root...
304 *
305 * The default threshold of 100000Hz is based on perf's similar
306 * kernel.perf_event_max_sample_rate sysctl parameter.
307 */
308static u32 i915_oa_max_sample_rate = 100000;
309
Robert Braggd7965152016-11-07 19:49:52 +0000310/* XXX: beware if future OA HW adds new report formats that the current
311 * code assumes all reports have a power-of-two size and ~(size - 1) can
312 * be used as a mask to align the OA tail pointer.
313 */
314static struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
315 [I915_OA_FORMAT_A13] = { 0, 64 },
316 [I915_OA_FORMAT_A29] = { 1, 128 },
317 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
318 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
319 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
320 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
321 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
322 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
323};
324
Robert Bragg19f81df2017-06-13 12:23:03 +0100325static struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
326 [I915_OA_FORMAT_A12] = { 0, 64 },
327 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
328 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
329 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
330};
331
Robert Braggd7965152016-11-07 19:49:52 +0000332#define SAMPLE_OA_REPORT (1<<0)
Robert Braggeec688e2016-11-07 19:49:47 +0000333
Robert Bragg16d98b32016-12-07 21:40:33 +0000334/**
335 * struct perf_open_properties - for validated properties given to open a stream
336 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
337 * @single_context: Whether a single or all gpu contexts should be monitored
338 * @ctx_handle: A gem ctx handle for use with @single_context
339 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
340 * @oa_format: An OA unit HW report format
341 * @oa_periodic: Whether to enable periodic OA unit sampling
342 * @oa_period_exponent: The OA unit sampling period is derived from this
343 *
344 * As read_properties_unlocked() enumerates and validates the properties given
345 * to open a stream of metrics the configuration is built up in the structure
346 * which starts out zero initialized.
347 */
Robert Braggeec688e2016-11-07 19:49:47 +0000348struct perf_open_properties {
349 u32 sample_flags;
350
351 u64 single_context:1;
352 u64 ctx_handle;
Robert Braggd7965152016-11-07 19:49:52 +0000353
354 /* OA sampling state */
355 int metrics_set;
356 int oa_format;
357 bool oa_periodic;
358 int oa_period_exponent;
Robert Braggeec688e2016-11-07 19:49:47 +0000359};
360
Lionel Landwerlinf89823c2017-08-03 18:05:50 +0100361static void free_oa_config(struct drm_i915_private *dev_priv,
362 struct i915_oa_config *oa_config)
363{
364 if (!PTR_ERR(oa_config->flex_regs))
365 kfree(oa_config->flex_regs);
366 if (!PTR_ERR(oa_config->b_counter_regs))
367 kfree(oa_config->b_counter_regs);
368 if (!PTR_ERR(oa_config->mux_regs))
369 kfree(oa_config->mux_regs);
370 kfree(oa_config);
371}
372
373static void put_oa_config(struct drm_i915_private *dev_priv,
374 struct i915_oa_config *oa_config)
375{
376 if (!atomic_dec_and_test(&oa_config->ref_count))
377 return;
378
379 free_oa_config(dev_priv, oa_config);
380}
381
382static int get_oa_config(struct drm_i915_private *dev_priv,
383 int metrics_set,
384 struct i915_oa_config **out_config)
385{
386 int ret;
387
388 if (metrics_set == 1) {
389 *out_config = &dev_priv->perf.oa.test_config;
390 atomic_inc(&dev_priv->perf.oa.test_config.ref_count);
391 return 0;
392 }
393
394 ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
395 if (ret)
396 return ret;
397
398 *out_config = idr_find(&dev_priv->perf.metrics_idr, metrics_set);
399 if (!*out_config)
400 ret = -EINVAL;
401 else
402 atomic_inc(&(*out_config)->ref_count);
403
404 mutex_unlock(&dev_priv->perf.metrics_lock);
405
406 return ret;
407}
408
Robert Bragg19f81df2017-06-13 12:23:03 +0100409static u32 gen8_oa_hw_tail_read(struct drm_i915_private *dev_priv)
410{
411 return I915_READ(GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
412}
413
414static u32 gen7_oa_hw_tail_read(struct drm_i915_private *dev_priv)
415{
416 u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
417
418 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
419}
420
Robert Bragg0dd860c2017-05-11 16:43:28 +0100421/**
Robert Bragg19f81df2017-06-13 12:23:03 +0100422 * oa_buffer_check_unlocked - check for data and update tail ptr state
Robert Bragg0dd860c2017-05-11 16:43:28 +0100423 * @dev_priv: i915 device instance
Robert Braggd7965152016-11-07 19:49:52 +0000424 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100425 * This is either called via fops (for blocking reads in user ctx) or the poll
426 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
427 * if there is data available for userspace to read.
Robert Braggd7965152016-11-07 19:49:52 +0000428 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100429 * This function is central to providing a workaround for the OA unit tail
430 * pointer having a race with respect to what data is visible to the CPU.
431 * It is responsible for reading tail pointers from the hardware and giving
432 * the pointers time to 'age' before they are made available for reading.
433 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
434 *
435 * Besides returning true when there is data available to read() this function
436 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
437 * and .aged_tail_idx state used for reading.
438 *
439 * Note: It's safe to read OA config state here unlocked, assuming that this is
440 * only called while the stream is enabled, while the global OA configuration
441 * can't be modified.
442 *
443 * Returns: %true if the OA buffer contains data, else %false
Robert Braggd7965152016-11-07 19:49:52 +0000444 */
Robert Bragg19f81df2017-06-13 12:23:03 +0100445static bool oa_buffer_check_unlocked(struct drm_i915_private *dev_priv)
Robert Braggd7965152016-11-07 19:49:52 +0000446{
447 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100448 unsigned long flags;
449 unsigned int aged_idx;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100450 u32 head, hw_tail, aged_tail, aging_tail;
451 u64 now;
Robert Braggd7965152016-11-07 19:49:52 +0000452
Robert Bragg0dd860c2017-05-11 16:43:28 +0100453 /* We have to consider the (unlikely) possibility that read() errors
454 * could result in an OA buffer reset which might reset the head,
455 * tails[] and aged_tail state.
456 */
457 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
458
459 /* NB: The head we observe here might effectively be a little out of
460 * date (between head and tails[aged_idx].offset if there is currently
461 * a read() in progress.
462 */
463 head = dev_priv->perf.oa.oa_buffer.head;
464
465 aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
466 aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset;
467 aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset;
468
Robert Bragg19f81df2017-06-13 12:23:03 +0100469 hw_tail = dev_priv->perf.oa.ops.oa_hw_tail_read(dev_priv);
Robert Bragg0dd860c2017-05-11 16:43:28 +0100470
471 /* The tail pointer increases in 64 byte increments,
472 * not in report_size steps...
473 */
474 hw_tail &= ~(report_size - 1);
475
476 now = ktime_get_mono_fast_ns();
477
Robert Bragg4117ebc2017-05-11 16:43:30 +0100478 /* Update the aged tail
479 *
480 * Flip the tail pointer available for read()s once the aging tail is
481 * old enough to trust that the corresponding data will be visible to
482 * the CPU...
483 *
484 * Do this before updating the aging pointer in case we may be able to
485 * immediately start aging a new pointer too (if new data has become
486 * available) without needing to wait for a later hrtimer callback.
487 */
488 if (aging_tail != INVALID_TAIL_PTR &&
489 ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) >
490 OA_TAIL_MARGIN_NSEC)) {
Robert Bragg19f81df2017-06-13 12:23:03 +0100491
Robert Bragg4117ebc2017-05-11 16:43:30 +0100492 aged_idx ^= 1;
493 dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx;
494
495 aged_tail = aging_tail;
496
497 /* Mark that we need a new pointer to start aging... */
498 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
499 aging_tail = INVALID_TAIL_PTR;
500 }
501
Robert Bragg0dd860c2017-05-11 16:43:28 +0100502 /* Update the aging tail
503 *
504 * We throttle aging tail updates until we have a new tail that
505 * represents >= one report more data than is already available for
506 * reading. This ensures there will be enough data for a successful
507 * read once this new pointer has aged and ensures we will give the new
508 * pointer time to age.
509 */
510 if (aging_tail == INVALID_TAIL_PTR &&
511 (aged_tail == INVALID_TAIL_PTR ||
512 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
513 struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma;
514 u32 gtt_offset = i915_ggtt_offset(vma);
515
516 /* Be paranoid and do a bounds check on the pointer read back
517 * from hardware, just in case some spurious hardware condition
518 * could put the tail out of bounds...
519 */
520 if (hw_tail >= gtt_offset &&
521 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
522 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset =
523 aging_tail = hw_tail;
524 dev_priv->perf.oa.oa_buffer.aging_timestamp = now;
525 } else {
526 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
527 hw_tail);
528 }
529 }
530
Robert Bragg0dd860c2017-05-11 16:43:28 +0100531 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
532
533 return aged_tail == INVALID_TAIL_PTR ?
534 false : OA_TAKEN(aged_tail, head) >= report_size;
Robert Braggd7965152016-11-07 19:49:52 +0000535}
536
537/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000538 * append_oa_status - Appends a status record to a userspace read() buffer.
539 * @stream: An i915-perf stream opened for OA metrics
540 * @buf: destination buffer given by userspace
541 * @count: the number of bytes userspace wants to read
542 * @offset: (inout): the current position for writing into @buf
543 * @type: The kind of status to report to userspace
544 *
545 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
546 * into the userspace read() buffer.
547 *
548 * The @buf @offset will only be updated on success.
549 *
550 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000551 */
552static int append_oa_status(struct i915_perf_stream *stream,
553 char __user *buf,
554 size_t count,
555 size_t *offset,
556 enum drm_i915_perf_record_type type)
557{
558 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
559
560 if ((count - *offset) < header.size)
561 return -ENOSPC;
562
563 if (copy_to_user(buf + *offset, &header, sizeof(header)))
564 return -EFAULT;
565
566 (*offset) += header.size;
567
568 return 0;
569}
570
571/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000572 * append_oa_sample - Copies single OA report into userspace read() buffer.
573 * @stream: An i915-perf stream opened for OA metrics
574 * @buf: destination buffer given by userspace
575 * @count: the number of bytes userspace wants to read
576 * @offset: (inout): the current position for writing into @buf
577 * @report: A single OA report to (optionally) include as part of the sample
578 *
579 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
580 * properties when opening a stream, tracked as `stream->sample_flags`. This
581 * function copies the requested components of a single sample to the given
582 * read() @buf.
583 *
584 * The @buf @offset will only be updated on success.
585 *
586 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000587 */
588static int append_oa_sample(struct i915_perf_stream *stream,
589 char __user *buf,
590 size_t count,
591 size_t *offset,
592 const u8 *report)
593{
594 struct drm_i915_private *dev_priv = stream->dev_priv;
595 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
596 struct drm_i915_perf_record_header header;
597 u32 sample_flags = stream->sample_flags;
598
599 header.type = DRM_I915_PERF_RECORD_SAMPLE;
600 header.pad = 0;
601 header.size = stream->sample_size;
602
603 if ((count - *offset) < header.size)
604 return -ENOSPC;
605
606 buf += *offset;
607 if (copy_to_user(buf, &header, sizeof(header)))
608 return -EFAULT;
609 buf += sizeof(header);
610
611 if (sample_flags & SAMPLE_OA_REPORT) {
612 if (copy_to_user(buf, report, report_size))
613 return -EFAULT;
614 }
615
616 (*offset) += header.size;
617
618 return 0;
619}
620
621/**
622 * Copies all buffered OA reports into userspace read() buffer.
623 * @stream: An i915-perf stream opened for OA metrics
624 * @buf: destination buffer given by userspace
625 * @count: the number of bytes userspace wants to read
626 * @offset: (inout): the current position for writing into @buf
Robert Braggd7965152016-11-07 19:49:52 +0000627 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000628 * Notably any error condition resulting in a short read (-%ENOSPC or
629 * -%EFAULT) will be returned even though one or more records may
Robert Braggd7965152016-11-07 19:49:52 +0000630 * have been successfully copied. In this case it's up to the caller
631 * to decide if the error should be squashed before returning to
632 * userspace.
633 *
634 * Note: reports are consumed from the head, and appended to the
Robert Bragge81b3a52017-05-11 16:43:24 +0100635 * tail, so the tail chases the head?... If you think that's mad
Robert Braggd7965152016-11-07 19:49:52 +0000636 * and back-to-front you're not alone, but this follows the
637 * Gen PRM naming convention.
Robert Bragg16d98b32016-12-07 21:40:33 +0000638 *
639 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000640 */
Robert Bragg19f81df2017-06-13 12:23:03 +0100641static int gen8_append_oa_reports(struct i915_perf_stream *stream,
642 char __user *buf,
643 size_t count,
644 size_t *offset)
645{
646 struct drm_i915_private *dev_priv = stream->dev_priv;
647 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
648 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
649 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
650 u32 mask = (OA_BUFFER_SIZE - 1);
651 size_t start_offset = *offset;
652 unsigned long flags;
653 unsigned int aged_tail_idx;
654 u32 head, tail;
655 u32 taken;
656 int ret = 0;
657
658 if (WARN_ON(!stream->enabled))
659 return -EIO;
660
661 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
662
663 head = dev_priv->perf.oa.oa_buffer.head;
664 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
665 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
666
667 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
668
669 /*
670 * An invalid tail pointer here means we're still waiting for the poll
671 * hrtimer callback to give us a pointer
672 */
673 if (tail == INVALID_TAIL_PTR)
674 return -EAGAIN;
675
676 /*
677 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
678 * while indexing relative to oa_buf_base.
679 */
680 head -= gtt_offset;
681 tail -= gtt_offset;
682
683 /*
684 * An out of bounds or misaligned head or tail pointer implies a driver
685 * bug since we validate + align the tail pointers we read from the
686 * hardware and we are in full control of the head pointer which should
687 * only be incremented by multiples of the report size (notably also
688 * all a power of two).
689 */
690 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
691 tail > OA_BUFFER_SIZE || tail % report_size,
692 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
693 head, tail))
694 return -EIO;
695
696
697 for (/* none */;
698 (taken = OA_TAKEN(tail, head));
699 head = (head + report_size) & mask) {
700 u8 *report = oa_buf_base + head;
701 u32 *report32 = (void *)report;
702 u32 ctx_id;
703 u32 reason;
704
705 /*
706 * All the report sizes factor neatly into the buffer
707 * size so we never expect to see a report split
708 * between the beginning and end of the buffer.
709 *
710 * Given the initial alignment check a misalignment
711 * here would imply a driver bug that would result
712 * in an overrun.
713 */
714 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
715 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
716 break;
717 }
718
719 /*
720 * The reason field includes flags identifying what
721 * triggered this specific report (mostly timer
722 * triggered or e.g. due to a context switch).
723 *
724 * This field is never expected to be zero so we can
725 * check that the report isn't invalid before copying
726 * it to userspace...
727 */
728 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
729 OAREPORT_REASON_MASK);
730 if (reason == 0) {
731 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
732 DRM_NOTE("Skipping spurious, invalid OA report\n");
733 continue;
734 }
735
736 /*
737 * XXX: Just keep the lower 21 bits for now since I'm not
738 * entirely sure if the HW touches any of the higher bits in
739 * this field
740 */
741 ctx_id = report32[2] & 0x1fffff;
742
743 /*
744 * Squash whatever is in the CTX_ID field if it's marked as
745 * invalid to be sure we avoid false-positive, single-context
746 * filtering below...
747 *
748 * Note: that we don't clear the valid_ctx_bit so userspace can
749 * understand that the ID has been squashed by the kernel.
750 */
751 if (!(report32[0] & dev_priv->perf.oa.gen8_valid_ctx_bit))
752 ctx_id = report32[2] = INVALID_CTX_ID;
753
754 /*
755 * NB: For Gen 8 the OA unit no longer supports clock gating
756 * off for a specific context and the kernel can't securely
757 * stop the counters from updating as system-wide / global
758 * values.
759 *
760 * Automatic reports now include a context ID so reports can be
761 * filtered on the cpu but it's not worth trying to
762 * automatically subtract/hide counter progress for other
763 * contexts while filtering since we can't stop userspace
764 * issuing MI_REPORT_PERF_COUNT commands which would still
765 * provide a side-band view of the real values.
766 *
767 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
768 * to normalize counters for a single filtered context then it
769 * needs be forwarded bookend context-switch reports so that it
770 * can track switches in between MI_REPORT_PERF_COUNT commands
771 * and can itself subtract/ignore the progress of counters
772 * associated with other contexts. Note that the hardware
773 * automatically triggers reports when switching to a new
774 * context which are tagged with the ID of the newly active
775 * context. To avoid the complexity (and likely fragility) of
776 * reading ahead while parsing reports to try and minimize
777 * forwarding redundant context switch reports (i.e. between
778 * other, unrelated contexts) we simply elect to forward them
779 * all.
780 *
781 * We don't rely solely on the reason field to identify context
782 * switches since it's not-uncommon for periodic samples to
783 * identify a switch before any 'context switch' report.
784 */
785 if (!dev_priv->perf.oa.exclusive_stream->ctx ||
786 dev_priv->perf.oa.specific_ctx_id == ctx_id ||
787 (dev_priv->perf.oa.oa_buffer.last_ctx_id ==
788 dev_priv->perf.oa.specific_ctx_id) ||
789 reason & OAREPORT_REASON_CTX_SWITCH) {
790
791 /*
792 * While filtering for a single context we avoid
793 * leaking the IDs of other contexts.
794 */
795 if (dev_priv->perf.oa.exclusive_stream->ctx &&
796 dev_priv->perf.oa.specific_ctx_id != ctx_id) {
797 report32[2] = INVALID_CTX_ID;
798 }
799
800 ret = append_oa_sample(stream, buf, count, offset,
801 report);
802 if (ret)
803 break;
804
805 dev_priv->perf.oa.oa_buffer.last_ctx_id = ctx_id;
806 }
807
808 /*
809 * The above reason field sanity check is based on
810 * the assumption that the OA buffer is initially
811 * zeroed and we reset the field after copying so the
812 * check is still meaningful once old reports start
813 * being overwritten.
814 */
815 report32[0] = 0;
816 }
817
818 if (start_offset != *offset) {
819 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
820
821 /*
822 * We removed the gtt_offset for the copy loop above, indexing
823 * relative to oa_buf_base so put back here...
824 */
825 head += gtt_offset;
826
827 I915_WRITE(GEN8_OAHEADPTR, head & GEN8_OAHEADPTR_MASK);
828 dev_priv->perf.oa.oa_buffer.head = head;
829
830 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
831 }
832
833 return ret;
834}
835
836/**
837 * gen8_oa_read - copy status records then buffered OA reports
838 * @stream: An i915-perf stream opened for OA metrics
839 * @buf: destination buffer given by userspace
840 * @count: the number of bytes userspace wants to read
841 * @offset: (inout): the current position for writing into @buf
842 *
843 * Checks OA unit status registers and if necessary appends corresponding
844 * status records for userspace (such as for a buffer full condition) and then
845 * initiate appending any buffered OA reports.
846 *
847 * Updates @offset according to the number of bytes successfully copied into
848 * the userspace buffer.
849 *
850 * NB: some data may be successfully copied to the userspace buffer
851 * even if an error is returned, and this is reflected in the
852 * updated @offset.
853 *
854 * Returns: zero on success or a negative error code
855 */
856static int gen8_oa_read(struct i915_perf_stream *stream,
857 char __user *buf,
858 size_t count,
859 size_t *offset)
860{
861 struct drm_i915_private *dev_priv = stream->dev_priv;
862 u32 oastatus;
863 int ret;
864
865 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
866 return -EIO;
867
868 oastatus = I915_READ(GEN8_OASTATUS);
869
870 /*
871 * We treat OABUFFER_OVERFLOW as a significant error:
872 *
873 * Although theoretically we could handle this more gracefully
874 * sometimes, some Gens don't correctly suppress certain
875 * automatically triggered reports in this condition and so we
876 * have to assume that old reports are now being trampled
877 * over.
878 *
879 * Considering how we don't currently give userspace control
880 * over the OA buffer size and always configure a large 16MB
881 * buffer, then a buffer overflow does anyway likely indicate
882 * that something has gone quite badly wrong.
883 */
884 if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
885 ret = append_oa_status(stream, buf, count, offset,
886 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
887 if (ret)
888 return ret;
889
890 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
891 dev_priv->perf.oa.period_exponent);
892
893 dev_priv->perf.oa.ops.oa_disable(dev_priv);
894 dev_priv->perf.oa.ops.oa_enable(dev_priv);
895
896 /*
897 * Note: .oa_enable() is expected to re-init the oabuffer and
898 * reset GEN8_OASTATUS for us
899 */
900 oastatus = I915_READ(GEN8_OASTATUS);
901 }
902
903 if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
904 ret = append_oa_status(stream, buf, count, offset,
905 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
906 if (ret)
907 return ret;
908 I915_WRITE(GEN8_OASTATUS,
909 oastatus & ~GEN8_OASTATUS_REPORT_LOST);
910 }
911
912 return gen8_append_oa_reports(stream, buf, count, offset);
913}
914
915/**
916 * Copies all buffered OA reports into userspace read() buffer.
917 * @stream: An i915-perf stream opened for OA metrics
918 * @buf: destination buffer given by userspace
919 * @count: the number of bytes userspace wants to read
920 * @offset: (inout): the current position for writing into @buf
921 *
922 * Notably any error condition resulting in a short read (-%ENOSPC or
923 * -%EFAULT) will be returned even though one or more records may
924 * have been successfully copied. In this case it's up to the caller
925 * to decide if the error should be squashed before returning to
926 * userspace.
927 *
928 * Note: reports are consumed from the head, and appended to the
929 * tail, so the tail chases the head?... If you think that's mad
930 * and back-to-front you're not alone, but this follows the
931 * Gen PRM naming convention.
932 *
933 * Returns: 0 on success, negative error code on failure.
934 */
Robert Braggd7965152016-11-07 19:49:52 +0000935static int gen7_append_oa_reports(struct i915_perf_stream *stream,
936 char __user *buf,
937 size_t count,
Robert Bragg3bb335c2017-05-11 16:43:27 +0100938 size_t *offset)
Robert Braggd7965152016-11-07 19:49:52 +0000939{
940 struct drm_i915_private *dev_priv = stream->dev_priv;
941 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
942 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
Robert Braggd7965152016-11-07 19:49:52 +0000943 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
944 u32 mask = (OA_BUFFER_SIZE - 1);
Robert Bragg3bb335c2017-05-11 16:43:27 +0100945 size_t start_offset = *offset;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100946 unsigned long flags;
947 unsigned int aged_tail_idx;
948 u32 head, tail;
Robert Braggd7965152016-11-07 19:49:52 +0000949 u32 taken;
950 int ret = 0;
951
952 if (WARN_ON(!stream->enabled))
953 return -EIO;
954
Robert Bragg0dd860c2017-05-11 16:43:28 +0100955 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggf2790202017-05-11 16:43:26 +0100956
Robert Bragg0dd860c2017-05-11 16:43:28 +0100957 head = dev_priv->perf.oa.oa_buffer.head;
958 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
959 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
960
961 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
962
963 /* An invalid tail pointer here means we're still waiting for the poll
964 * hrtimer callback to give us a pointer
Robert Braggf2790202017-05-11 16:43:26 +0100965 */
Robert Bragg0dd860c2017-05-11 16:43:28 +0100966 if (tail == INVALID_TAIL_PTR)
Robert Braggd7965152016-11-07 19:49:52 +0000967 return -EAGAIN;
968
Robert Bragg0dd860c2017-05-11 16:43:28 +0100969 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
970 * while indexing relative to oa_buf_base.
971 */
972 head -= gtt_offset;
973 tail -= gtt_offset;
974
975 /* An out of bounds or misaligned head or tail pointer implies a driver
976 * bug since we validate + align the tail pointers we read from the
977 * hardware and we are in full control of the head pointer which should
978 * only be incremented by multiples of the report size (notably also
979 * all a power of two).
980 */
981 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
982 tail > OA_BUFFER_SIZE || tail % report_size,
983 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
984 head, tail))
985 return -EIO;
986
Robert Braggd7965152016-11-07 19:49:52 +0000987
988 for (/* none */;
989 (taken = OA_TAKEN(tail, head));
990 head = (head + report_size) & mask) {
991 u8 *report = oa_buf_base + head;
992 u32 *report32 = (void *)report;
993
994 /* All the report sizes factor neatly into the buffer
995 * size so we never expect to see a report split
996 * between the beginning and end of the buffer.
997 *
998 * Given the initial alignment check a misalignment
999 * here would imply a driver bug that would result
1000 * in an overrun.
1001 */
1002 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
1003 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
1004 break;
1005 }
1006
1007 /* The report-ID field for periodic samples includes
1008 * some undocumented flags related to what triggered
1009 * the report and is never expected to be zero so we
1010 * can check that the report isn't invalid before
1011 * copying it to userspace...
1012 */
1013 if (report32[0] == 0) {
Robert Bragg712122e2017-05-11 16:43:31 +01001014 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
1015 DRM_NOTE("Skipping spurious, invalid OA report\n");
Robert Braggd7965152016-11-07 19:49:52 +00001016 continue;
1017 }
1018
1019 ret = append_oa_sample(stream, buf, count, offset, report);
1020 if (ret)
1021 break;
1022
1023 /* The above report-id field sanity check is based on
1024 * the assumption that the OA buffer is initially
1025 * zeroed and we reset the field after copying so the
1026 * check is still meaningful once old reports start
1027 * being overwritten.
1028 */
1029 report32[0] = 0;
1030 }
1031
Robert Bragg3bb335c2017-05-11 16:43:27 +01001032 if (start_offset != *offset) {
Robert Bragg0dd860c2017-05-11 16:43:28 +01001033 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1034
Robert Bragg3bb335c2017-05-11 16:43:27 +01001035 /* We removed the gtt_offset for the copy loop above, indexing
1036 * relative to oa_buf_base so put back here...
1037 */
1038 head += gtt_offset;
1039
1040 I915_WRITE(GEN7_OASTATUS2,
1041 ((head & GEN7_OASTATUS2_HEAD_MASK) |
1042 OA_MEM_SELECT_GGTT));
1043 dev_priv->perf.oa.oa_buffer.head = head;
Robert Bragg0dd860c2017-05-11 16:43:28 +01001044
1045 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Bragg3bb335c2017-05-11 16:43:27 +01001046 }
Robert Braggd7965152016-11-07 19:49:52 +00001047
1048 return ret;
1049}
1050
Robert Bragg16d98b32016-12-07 21:40:33 +00001051/**
1052 * gen7_oa_read - copy status records then buffered OA reports
1053 * @stream: An i915-perf stream opened for OA metrics
1054 * @buf: destination buffer given by userspace
1055 * @count: the number of bytes userspace wants to read
1056 * @offset: (inout): the current position for writing into @buf
1057 *
1058 * Checks Gen 7 specific OA unit status registers and if necessary appends
1059 * corresponding status records for userspace (such as for a buffer full
1060 * condition) and then initiate appending any buffered OA reports.
1061 *
1062 * Updates @offset according to the number of bytes successfully copied into
1063 * the userspace buffer.
1064 *
1065 * Returns: zero on success or a negative error code
1066 */
Robert Braggd7965152016-11-07 19:49:52 +00001067static int gen7_oa_read(struct i915_perf_stream *stream,
1068 char __user *buf,
1069 size_t count,
1070 size_t *offset)
1071{
1072 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +00001073 u32 oastatus1;
Robert Braggd7965152016-11-07 19:49:52 +00001074 int ret;
1075
1076 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
1077 return -EIO;
1078
Robert Braggd7965152016-11-07 19:49:52 +00001079 oastatus1 = I915_READ(GEN7_OASTATUS1);
1080
Robert Braggd7965152016-11-07 19:49:52 +00001081 /* XXX: On Haswell we don't have a safe way to clear oastatus1
1082 * bits while the OA unit is enabled (while the tail pointer
1083 * may be updated asynchronously) so we ignore status bits
1084 * that have already been reported to userspace.
1085 */
1086 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
1087
1088 /* We treat OABUFFER_OVERFLOW as a significant error:
1089 *
1090 * - The status can be interpreted to mean that the buffer is
1091 * currently full (with a higher precedence than OA_TAKEN()
1092 * which will start to report a near-empty buffer after an
1093 * overflow) but it's awkward that we can't clear the status
1094 * on Haswell, so without a reset we won't be able to catch
1095 * the state again.
1096 *
1097 * - Since it also implies the HW has started overwriting old
1098 * reports it may also affect our sanity checks for invalid
1099 * reports when copying to userspace that assume new reports
1100 * are being written to cleared memory.
1101 *
1102 * - In the future we may want to introduce a flight recorder
1103 * mode where the driver will automatically maintain a safe
1104 * guard band between head/tail, avoiding this overflow
1105 * condition, but we avoid the added driver complexity for
1106 * now.
1107 */
1108 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1109 ret = append_oa_status(stream, buf, count, offset,
1110 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1111 if (ret)
1112 return ret;
1113
Robert Bragg19f81df2017-06-13 12:23:03 +01001114 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
1115 dev_priv->perf.oa.period_exponent);
Robert Braggd7965152016-11-07 19:49:52 +00001116
1117 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1118 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1119
Robert Braggd7965152016-11-07 19:49:52 +00001120 oastatus1 = I915_READ(GEN7_OASTATUS1);
Robert Braggd7965152016-11-07 19:49:52 +00001121 }
1122
1123 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1124 ret = append_oa_status(stream, buf, count, offset,
1125 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1126 if (ret)
1127 return ret;
1128 dev_priv->perf.oa.gen7_latched_oastatus1 |=
1129 GEN7_OASTATUS1_REPORT_LOST;
1130 }
1131
Robert Bragg3bb335c2017-05-11 16:43:27 +01001132 return gen7_append_oa_reports(stream, buf, count, offset);
Robert Braggd7965152016-11-07 19:49:52 +00001133}
1134
Robert Bragg16d98b32016-12-07 21:40:33 +00001135/**
1136 * i915_oa_wait_unlocked - handles blocking IO until OA data available
1137 * @stream: An i915-perf stream opened for OA metrics
1138 *
1139 * Called when userspace tries to read() from a blocking stream FD opened
1140 * for OA metrics. It waits until the hrtimer callback finds a non-empty
1141 * OA buffer and wakes us.
1142 *
1143 * Note: it's acceptable to have this return with some false positives
1144 * since any subsequent read handling will return -EAGAIN if there isn't
1145 * really data ready for userspace yet.
1146 *
1147 * Returns: zero on success or a negative error code
1148 */
Robert Braggd7965152016-11-07 19:49:52 +00001149static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1150{
1151 struct drm_i915_private *dev_priv = stream->dev_priv;
1152
1153 /* We would wait indefinitely if periodic sampling is not enabled */
1154 if (!dev_priv->perf.oa.periodic)
1155 return -EIO;
1156
Robert Braggd7965152016-11-07 19:49:52 +00001157 return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
Robert Bragg19f81df2017-06-13 12:23:03 +01001158 oa_buffer_check_unlocked(dev_priv));
Robert Braggd7965152016-11-07 19:49:52 +00001159}
1160
Robert Bragg16d98b32016-12-07 21:40:33 +00001161/**
1162 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1163 * @stream: An i915-perf stream opened for OA metrics
1164 * @file: An i915 perf stream file
1165 * @wait: poll() state table
1166 *
1167 * For handling userspace polling on an i915 perf stream opened for OA metrics,
1168 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1169 * when it sees data ready to read in the circular OA buffer.
1170 */
Robert Braggd7965152016-11-07 19:49:52 +00001171static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1172 struct file *file,
1173 poll_table *wait)
1174{
1175 struct drm_i915_private *dev_priv = stream->dev_priv;
1176
1177 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
1178}
1179
Robert Bragg16d98b32016-12-07 21:40:33 +00001180/**
1181 * i915_oa_read - just calls through to &i915_oa_ops->read
1182 * @stream: An i915-perf stream opened for OA metrics
1183 * @buf: destination buffer given by userspace
1184 * @count: the number of bytes userspace wants to read
1185 * @offset: (inout): the current position for writing into @buf
1186 *
1187 * Updates @offset according to the number of bytes successfully copied into
1188 * the userspace buffer.
1189 *
1190 * Returns: zero on success or a negative error code
1191 */
Robert Braggd7965152016-11-07 19:49:52 +00001192static int i915_oa_read(struct i915_perf_stream *stream,
1193 char __user *buf,
1194 size_t count,
1195 size_t *offset)
1196{
1197 struct drm_i915_private *dev_priv = stream->dev_priv;
1198
1199 return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
1200}
1201
Robert Bragg16d98b32016-12-07 21:40:33 +00001202/**
1203 * oa_get_render_ctx_id - determine and hold ctx hw id
1204 * @stream: An i915-perf stream opened for OA metrics
1205 *
1206 * Determine the render context hw id, and ensure it remains fixed for the
Robert Braggd7965152016-11-07 19:49:52 +00001207 * lifetime of the stream. This ensures that we don't have to worry about
1208 * updating the context ID in OACONTROL on the fly.
Robert Bragg16d98b32016-12-07 21:40:33 +00001209 *
1210 * Returns: zero on success or a negative error code
Robert Braggd7965152016-11-07 19:49:52 +00001211 */
1212static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1213{
1214 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +00001215
Robert Bragg19f81df2017-06-13 12:23:03 +01001216 if (i915.enable_execlists)
1217 dev_priv->perf.oa.specific_ctx_id = stream->ctx->hw_id;
1218 else {
1219 struct intel_engine_cs *engine = dev_priv->engine[RCS];
1220 struct intel_ring *ring;
1221 int ret;
Robert Braggd7965152016-11-07 19:49:52 +00001222
Robert Bragg19f81df2017-06-13 12:23:03 +01001223 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1224 if (ret)
1225 return ret;
Robert Braggd7965152016-11-07 19:49:52 +00001226
Robert Bragg19f81df2017-06-13 12:23:03 +01001227 /*
1228 * As the ID is the gtt offset of the context's vma we
1229 * pin the vma to ensure the ID remains fixed.
1230 *
1231 * NB: implied RCS engine...
1232 */
1233 ring = engine->context_pin(engine, stream->ctx);
1234 mutex_unlock(&dev_priv->drm.struct_mutex);
1235 if (IS_ERR(ring))
1236 return PTR_ERR(ring);
1237
1238
1239 /*
1240 * Explicitly track the ID (instead of calling
1241 * i915_ggtt_offset() on the fly) considering the difference
1242 * with gen8+ and execlists
1243 */
1244 dev_priv->perf.oa.specific_ctx_id =
1245 i915_ggtt_offset(stream->ctx->engine[engine->id].state);
1246 }
Robert Braggd7965152016-11-07 19:49:52 +00001247
Chris Wilson266a2402017-05-04 10:33:08 +01001248 return 0;
Robert Braggd7965152016-11-07 19:49:52 +00001249}
1250
Robert Bragg16d98b32016-12-07 21:40:33 +00001251/**
1252 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1253 * @stream: An i915-perf stream opened for OA metrics
1254 *
1255 * In case anything needed doing to ensure the context HW ID would remain valid
1256 * for the lifetime of the stream, then that can be undone here.
1257 */
Robert Braggd7965152016-11-07 19:49:52 +00001258static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1259{
1260 struct drm_i915_private *dev_priv = stream->dev_priv;
1261
Robert Bragg19f81df2017-06-13 12:23:03 +01001262 if (i915.enable_execlists) {
1263 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
1264 } else {
1265 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Robert Braggd7965152016-11-07 19:49:52 +00001266
Robert Bragg19f81df2017-06-13 12:23:03 +01001267 mutex_lock(&dev_priv->drm.struct_mutex);
Robert Braggd7965152016-11-07 19:49:52 +00001268
Robert Bragg19f81df2017-06-13 12:23:03 +01001269 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
1270 engine->context_unpin(engine, stream->ctx);
1271
1272 mutex_unlock(&dev_priv->drm.struct_mutex);
1273 }
Robert Braggd7965152016-11-07 19:49:52 +00001274}
1275
1276static void
1277free_oa_buffer(struct drm_i915_private *i915)
1278{
1279 mutex_lock(&i915->drm.struct_mutex);
1280
1281 i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
1282 i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
1283 i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
1284
1285 i915->perf.oa.oa_buffer.vma = NULL;
1286 i915->perf.oa.oa_buffer.vaddr = NULL;
1287
1288 mutex_unlock(&i915->drm.struct_mutex);
1289}
1290
1291static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1292{
1293 struct drm_i915_private *dev_priv = stream->dev_priv;
1294
1295 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
1296
Robert Bragg19f81df2017-06-13 12:23:03 +01001297 /*
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01001298 * Unset exclusive_stream first, it will be checked while disabling
1299 * the metric set on gen8+.
Robert Bragg19f81df2017-06-13 12:23:03 +01001300 */
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001301 mutex_lock(&dev_priv->drm.struct_mutex);
Robert Bragg19f81df2017-06-13 12:23:03 +01001302 dev_priv->perf.oa.exclusive_stream = NULL;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001303 mutex_unlock(&dev_priv->drm.struct_mutex);
Robert Bragg19f81df2017-06-13 12:23:03 +01001304
Robert Braggd7965152016-11-07 19:49:52 +00001305 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
1306
1307 free_oa_buffer(dev_priv);
1308
1309 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1310 intel_runtime_pm_put(dev_priv);
1311
1312 if (stream->ctx)
1313 oa_put_render_ctx_id(stream);
1314
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01001315 put_oa_config(dev_priv, stream->oa_config);
1316
Robert Bragg712122e2017-05-11 16:43:31 +01001317 if (dev_priv->perf.oa.spurious_report_rs.missed) {
1318 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1319 dev_priv->perf.oa.spurious_report_rs.missed);
1320 }
Robert Braggd7965152016-11-07 19:49:52 +00001321}
1322
1323static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
1324{
1325 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
Robert Bragg0dd860c2017-05-11 16:43:28 +01001326 unsigned long flags;
1327
1328 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggd7965152016-11-07 19:49:52 +00001329
1330 /* Pre-DevBDW: OABUFFER must be set with counters off,
1331 * before OASTATUS1, but after OASTATUS2
1332 */
1333 I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
Robert Braggf2790202017-05-11 16:43:26 +01001334 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1335
Robert Braggd7965152016-11-07 19:49:52 +00001336 I915_WRITE(GEN7_OABUFFER, gtt_offset);
Robert Braggf2790202017-05-11 16:43:26 +01001337
Robert Braggd7965152016-11-07 19:49:52 +00001338 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
1339
Robert Bragg0dd860c2017-05-11 16:43:28 +01001340 /* Mark that we need updated tail pointers to read from... */
1341 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1342 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1343
1344 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1345
Robert Braggd7965152016-11-07 19:49:52 +00001346 /* On Haswell we have to track which OASTATUS1 flags we've
1347 * already seen since they can't be cleared while periodic
1348 * sampling is enabled.
1349 */
1350 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
1351
1352 /* NB: although the OA buffer will initially be allocated
1353 * zeroed via shmfs (and so this memset is redundant when
1354 * first allocating), we may re-init the OA buffer, either
1355 * when re-enabling a stream or in error/reset paths.
1356 *
1357 * The reason we clear the buffer for each re-init is for the
1358 * sanity check in gen7_append_oa_reports() that looks at the
1359 * report-id field to make sure it's non-zero which relies on
1360 * the assumption that new reports are being written to zeroed
1361 * memory...
1362 */
1363 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1364
1365 /* Maybe make ->pollin per-stream state if we support multiple
1366 * concurrent streams in the future.
1367 */
1368 dev_priv->perf.oa.pollin = false;
1369}
1370
Robert Bragg19f81df2017-06-13 12:23:03 +01001371static void gen8_init_oa_buffer(struct drm_i915_private *dev_priv)
1372{
1373 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
1374 unsigned long flags;
1375
1376 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1377
1378 I915_WRITE(GEN8_OASTATUS, 0);
1379 I915_WRITE(GEN8_OAHEADPTR, gtt_offset);
1380 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1381
1382 I915_WRITE(GEN8_OABUFFER_UDW, 0);
1383
1384 /*
1385 * PRM says:
1386 *
1387 * "This MMIO must be set before the OATAILPTR
1388 * register and after the OAHEADPTR register. This is
1389 * to enable proper functionality of the overflow
1390 * bit."
1391 */
1392 I915_WRITE(GEN8_OABUFFER, gtt_offset |
1393 OABUFFER_SIZE_16M | OA_MEM_SELECT_GGTT);
1394 I915_WRITE(GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1395
1396 /* Mark that we need updated tail pointers to read from... */
1397 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1398 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1399
1400 /*
1401 * Reset state used to recognise context switches, affecting which
1402 * reports we will forward to userspace while filtering for a single
1403 * context.
1404 */
1405 dev_priv->perf.oa.oa_buffer.last_ctx_id = INVALID_CTX_ID;
1406
1407 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1408
1409 /*
1410 * NB: although the OA buffer will initially be allocated
1411 * zeroed via shmfs (and so this memset is redundant when
1412 * first allocating), we may re-init the OA buffer, either
1413 * when re-enabling a stream or in error/reset paths.
1414 *
1415 * The reason we clear the buffer for each re-init is for the
1416 * sanity check in gen8_append_oa_reports() that looks at the
1417 * reason field to make sure it's non-zero which relies on
1418 * the assumption that new reports are being written to zeroed
1419 * memory...
1420 */
1421 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1422
1423 /*
1424 * Maybe make ->pollin per-stream state if we support multiple
1425 * concurrent streams in the future.
1426 */
1427 dev_priv->perf.oa.pollin = false;
1428}
1429
Robert Braggd7965152016-11-07 19:49:52 +00001430static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
1431{
1432 struct drm_i915_gem_object *bo;
1433 struct i915_vma *vma;
1434 int ret;
1435
1436 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
1437 return -ENODEV;
1438
1439 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1440 if (ret)
1441 return ret;
1442
1443 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1444 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1445
Tvrtko Ursulin12d79d72016-12-01 14:16:37 +00001446 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +00001447 if (IS_ERR(bo)) {
1448 DRM_ERROR("Failed to allocate OA buffer\n");
1449 ret = PTR_ERR(bo);
1450 goto unlock;
1451 }
1452
1453 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
1454 if (ret)
1455 goto err_unref;
1456
1457 /* PreHSW required 512K alignment, HSW requires 16M */
1458 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1459 if (IS_ERR(vma)) {
1460 ret = PTR_ERR(vma);
1461 goto err_unref;
1462 }
1463 dev_priv->perf.oa.oa_buffer.vma = vma;
1464
1465 dev_priv->perf.oa.oa_buffer.vaddr =
1466 i915_gem_object_pin_map(bo, I915_MAP_WB);
1467 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
1468 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
1469 goto err_unpin;
1470 }
1471
1472 dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
1473
1474 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
1475 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
1476 dev_priv->perf.oa.oa_buffer.vaddr);
1477
1478 goto unlock;
1479
1480err_unpin:
1481 __i915_vma_unpin(vma);
1482
1483err_unref:
1484 i915_gem_object_put(bo);
1485
1486 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
1487 dev_priv->perf.oa.oa_buffer.vma = NULL;
1488
1489unlock:
1490 mutex_unlock(&dev_priv->drm.struct_mutex);
1491 return ret;
1492}
1493
1494static void config_oa_regs(struct drm_i915_private *dev_priv,
1495 const struct i915_oa_reg *regs,
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001496 u32 n_regs)
Robert Braggd7965152016-11-07 19:49:52 +00001497{
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001498 u32 i;
Robert Braggd7965152016-11-07 19:49:52 +00001499
1500 for (i = 0; i < n_regs; i++) {
1501 const struct i915_oa_reg *reg = regs + i;
1502
1503 I915_WRITE(reg->addr, reg->value);
1504 }
1505}
1506
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001507static int hsw_enable_metric_set(struct drm_i915_private *dev_priv,
1508 const struct i915_oa_config *oa_config)
Robert Braggd7965152016-11-07 19:49:52 +00001509{
Robert Braggd7965152016-11-07 19:49:52 +00001510 /* PRM:
1511 *
1512 * OA unit is using “crclk” for its functionality. When trunk
1513 * level clock gating takes place, OA clock would be gated,
1514 * unable to count the events from non-render clock domain.
1515 * Render clock gating must be disabled when OA is enabled to
1516 * count the events from non-render domain. Unit level clock
1517 * gating for RCS should also be disabled.
1518 */
1519 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1520 ~GEN7_DOP_CLOCK_GATE_ENABLE));
1521 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
1522 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1523
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001524 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
Robert Braggd7965152016-11-07 19:49:52 +00001525
1526 /* It apparently takes a fairly long time for a new MUX
1527 * configuration to be be applied after these register writes.
1528 * This delay duration was derived empirically based on the
1529 * render_basic config but hopefully it covers the maximum
1530 * configuration latency.
1531 *
1532 * As a fallback, the checks in _append_oa_reports() to skip
1533 * invalid OA reports do also seem to work to discard reports
1534 * generated before this config has completed - albeit not
1535 * silently.
1536 *
1537 * Unfortunately this is essentially a magic number, since we
1538 * don't currently know of a reliable mechanism for predicting
1539 * how long the MUX config will take to apply and besides
1540 * seeing invalid reports we don't know of a reliable way to
1541 * explicitly check that the MUX config has landed.
1542 *
1543 * It's even possible we've miss characterized the underlying
1544 * problem - it just seems like the simplest explanation why
1545 * a delay at this location would mitigate any invalid reports.
1546 */
1547 usleep_range(15000, 20000);
1548
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001549 config_oa_regs(dev_priv, oa_config->b_counter_regs,
1550 oa_config->b_counter_regs_len);
Robert Braggd7965152016-11-07 19:49:52 +00001551
1552 return 0;
1553}
1554
1555static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
1556{
1557 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
1558 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1559 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
1560 GEN7_DOP_CLOCK_GATE_ENABLE));
1561
1562 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1563 ~GT_NOA_ENABLE));
1564}
1565
Robert Bragg19f81df2017-06-13 12:23:03 +01001566/*
1567 * NB: It must always remain pointer safe to run this even if the OA unit
1568 * has been disabled.
1569 *
1570 * It's fine to put out-of-date values into these per-context registers
1571 * in the case that the OA unit has been disabled.
1572 */
1573static void gen8_update_reg_state_unlocked(struct i915_gem_context *ctx,
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001574 u32 *reg_state,
1575 const struct i915_oa_config *oa_config)
Robert Bragg19f81df2017-06-13 12:23:03 +01001576{
1577 struct drm_i915_private *dev_priv = ctx->i915;
Robert Bragg19f81df2017-06-13 12:23:03 +01001578 u32 ctx_oactxctrl = dev_priv->perf.oa.ctx_oactxctrl_offset;
1579 u32 ctx_flexeu0 = dev_priv->perf.oa.ctx_flexeu0_offset;
1580 /* The MMIO offsets for Flex EU registers aren't contiguous */
1581 u32 flex_mmio[] = {
1582 i915_mmio_reg_offset(EU_PERF_CNTL0),
1583 i915_mmio_reg_offset(EU_PERF_CNTL1),
1584 i915_mmio_reg_offset(EU_PERF_CNTL2),
1585 i915_mmio_reg_offset(EU_PERF_CNTL3),
1586 i915_mmio_reg_offset(EU_PERF_CNTL4),
1587 i915_mmio_reg_offset(EU_PERF_CNTL5),
1588 i915_mmio_reg_offset(EU_PERF_CNTL6),
1589 };
1590 int i;
1591
1592 reg_state[ctx_oactxctrl] = i915_mmio_reg_offset(GEN8_OACTXCONTROL);
1593 reg_state[ctx_oactxctrl+1] = (dev_priv->perf.oa.period_exponent <<
1594 GEN8_OA_TIMER_PERIOD_SHIFT) |
1595 (dev_priv->perf.oa.periodic ?
1596 GEN8_OA_TIMER_ENABLE : 0) |
1597 GEN8_OA_COUNTER_RESUME;
1598
1599 for (i = 0; i < ARRAY_SIZE(flex_mmio); i++) {
1600 u32 state_offset = ctx_flexeu0 + i * 2;
1601 u32 mmio = flex_mmio[i];
1602
1603 /*
1604 * This arbitrary default will select the 'EU FPU0 Pipeline
1605 * Active' event. In the future it's anticipated that there
1606 * will be an explicit 'No Event' we can select, but not yet...
1607 */
1608 u32 value = 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01001609
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001610 if (oa_config) {
1611 u32 j;
1612
1613 for (j = 0; j < oa_config->flex_regs_len; j++) {
1614 if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) {
1615 value = oa_config->flex_regs[j].value;
1616 break;
1617 }
Robert Bragg19f81df2017-06-13 12:23:03 +01001618 }
1619 }
1620
1621 reg_state[state_offset] = mmio;
1622 reg_state[state_offset+1] = value;
1623 }
1624}
1625
1626/*
1627 * Same as gen8_update_reg_state_unlocked only through the batchbuffer. This
1628 * is only used by the kernel context.
1629 */
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001630static int gen8_emit_oa_config(struct drm_i915_gem_request *req,
1631 const struct i915_oa_config *oa_config)
Robert Bragg19f81df2017-06-13 12:23:03 +01001632{
1633 struct drm_i915_private *dev_priv = req->i915;
Robert Bragg19f81df2017-06-13 12:23:03 +01001634 /* The MMIO offsets for Flex EU registers aren't contiguous */
1635 u32 flex_mmio[] = {
1636 i915_mmio_reg_offset(EU_PERF_CNTL0),
1637 i915_mmio_reg_offset(EU_PERF_CNTL1),
1638 i915_mmio_reg_offset(EU_PERF_CNTL2),
1639 i915_mmio_reg_offset(EU_PERF_CNTL3),
1640 i915_mmio_reg_offset(EU_PERF_CNTL4),
1641 i915_mmio_reg_offset(EU_PERF_CNTL5),
1642 i915_mmio_reg_offset(EU_PERF_CNTL6),
1643 };
1644 u32 *cs;
1645 int i;
1646
Lionel Landwerlin01d928e2017-08-03 17:58:07 +01001647 cs = intel_ring_begin(req, ARRAY_SIZE(flex_mmio) * 2 + 4);
Robert Bragg19f81df2017-06-13 12:23:03 +01001648 if (IS_ERR(cs))
1649 return PTR_ERR(cs);
1650
Lionel Landwerlin01d928e2017-08-03 17:58:07 +01001651 *cs++ = MI_LOAD_REGISTER_IMM(ARRAY_SIZE(flex_mmio) + 1);
Robert Bragg19f81df2017-06-13 12:23:03 +01001652
1653 *cs++ = i915_mmio_reg_offset(GEN8_OACTXCONTROL);
1654 *cs++ = (dev_priv->perf.oa.period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
1655 (dev_priv->perf.oa.periodic ? GEN8_OA_TIMER_ENABLE : 0) |
1656 GEN8_OA_COUNTER_RESUME;
1657
1658 for (i = 0; i < ARRAY_SIZE(flex_mmio); i++) {
1659 u32 mmio = flex_mmio[i];
1660
1661 /*
1662 * This arbitrary default will select the 'EU FPU0 Pipeline
1663 * Active' event. In the future it's anticipated that there
1664 * will be an explicit 'No Event' we can select, but not
1665 * yet...
1666 */
1667 u32 value = 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01001668
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001669 if (oa_config) {
1670 u32 j;
1671
1672 for (j = 0; j < oa_config->flex_regs_len; j++) {
1673 if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) {
1674 value = oa_config->flex_regs[j].value;
1675 break;
1676 }
Robert Bragg19f81df2017-06-13 12:23:03 +01001677 }
1678 }
1679
1680 *cs++ = mmio;
1681 *cs++ = value;
1682 }
1683
1684 *cs++ = MI_NOOP;
1685 intel_ring_advance(req, cs);
1686
1687 return 0;
1688}
1689
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001690static int gen8_switch_to_updated_kernel_context(struct drm_i915_private *dev_priv,
1691 const struct i915_oa_config *oa_config)
Robert Bragg19f81df2017-06-13 12:23:03 +01001692{
1693 struct intel_engine_cs *engine = dev_priv->engine[RCS];
1694 struct i915_gem_timeline *timeline;
1695 struct drm_i915_gem_request *req;
1696 int ret;
1697
1698 lockdep_assert_held(&dev_priv->drm.struct_mutex);
1699
1700 i915_gem_retire_requests(dev_priv);
1701
1702 req = i915_gem_request_alloc(engine, dev_priv->kernel_context);
1703 if (IS_ERR(req))
1704 return PTR_ERR(req);
1705
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001706 ret = gen8_emit_oa_config(req, oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01001707 if (ret) {
1708 i915_add_request(req);
1709 return ret;
1710 }
1711
1712 /* Queue this switch after all other activity */
1713 list_for_each_entry(timeline, &dev_priv->gt.timelines, link) {
1714 struct drm_i915_gem_request *prev;
1715 struct intel_timeline *tl;
1716
1717 tl = &timeline->engine[engine->id];
1718 prev = i915_gem_active_raw(&tl->last_request,
1719 &dev_priv->drm.struct_mutex);
1720 if (prev)
1721 i915_sw_fence_await_sw_fence_gfp(&req->submit,
1722 &prev->submit,
1723 GFP_KERNEL);
1724 }
1725
1726 ret = i915_switch_context(req);
1727 i915_add_request(req);
1728
1729 return ret;
1730}
1731
1732/*
1733 * Manages updating the per-context aspects of the OA stream
1734 * configuration across all contexts.
1735 *
1736 * The awkward consideration here is that OACTXCONTROL controls the
1737 * exponent for periodic sampling which is primarily used for system
1738 * wide profiling where we'd like a consistent sampling period even in
1739 * the face of context switches.
1740 *
1741 * Our approach of updating the register state context (as opposed to
1742 * say using a workaround batch buffer) ensures that the hardware
1743 * won't automatically reload an out-of-date timer exponent even
1744 * transiently before a WA BB could be parsed.
1745 *
1746 * This function needs to:
1747 * - Ensure the currently running context's per-context OA state is
1748 * updated
1749 * - Ensure that all existing contexts will have the correct per-context
1750 * OA state if they are scheduled for use.
1751 * - Ensure any new contexts will be initialized with the correct
1752 * per-context OA state.
1753 *
1754 * Note: it's only the RCS/Render context that has any OA state.
1755 */
1756static int gen8_configure_all_contexts(struct drm_i915_private *dev_priv,
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001757 const struct i915_oa_config *oa_config,
Robert Bragg19f81df2017-06-13 12:23:03 +01001758 bool interruptible)
1759{
1760 struct i915_gem_context *ctx;
1761 int ret;
1762 unsigned int wait_flags = I915_WAIT_LOCKED;
1763
1764 if (interruptible) {
1765 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1766 if (ret)
1767 return ret;
1768
1769 wait_flags |= I915_WAIT_INTERRUPTIBLE;
1770 } else {
1771 mutex_lock(&dev_priv->drm.struct_mutex);
1772 }
1773
1774 /* Switch away from any user context. */
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001775 ret = gen8_switch_to_updated_kernel_context(dev_priv, oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01001776 if (ret)
1777 goto out;
1778
1779 /*
1780 * The OA register config is setup through the context image. This image
1781 * might be written to by the GPU on context switch (in particular on
1782 * lite-restore). This means we can't safely update a context's image,
1783 * if this context is scheduled/submitted to run on the GPU.
1784 *
1785 * We could emit the OA register config through the batch buffer but
1786 * this might leave small interval of time where the OA unit is
1787 * configured at an invalid sampling period.
1788 *
1789 * So far the best way to work around this issue seems to be draining
1790 * the GPU from any submitted work.
1791 */
1792 ret = i915_gem_wait_for_idle(dev_priv, wait_flags);
1793 if (ret)
1794 goto out;
1795
1796 /* Update all contexts now that we've stalled the submission. */
Chris Wilson829a0af2017-06-20 12:05:45 +01001797 list_for_each_entry(ctx, &dev_priv->contexts.list, link) {
Robert Bragg19f81df2017-06-13 12:23:03 +01001798 struct intel_context *ce = &ctx->engine[RCS];
1799 u32 *regs;
1800
1801 /* OA settings will be set upon first use */
1802 if (!ce->state)
1803 continue;
1804
1805 regs = i915_gem_object_pin_map(ce->state->obj, I915_MAP_WB);
1806 if (IS_ERR(regs)) {
1807 ret = PTR_ERR(regs);
1808 goto out;
1809 }
1810
1811 ce->state->obj->mm.dirty = true;
1812 regs += LRC_STATE_PN * PAGE_SIZE / sizeof(*regs);
1813
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001814 gen8_update_reg_state_unlocked(ctx, regs, oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01001815
1816 i915_gem_object_unpin_map(ce->state->obj);
1817 }
1818
1819 out:
1820 mutex_unlock(&dev_priv->drm.struct_mutex);
1821
1822 return ret;
1823}
1824
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001825static int gen8_enable_metric_set(struct drm_i915_private *dev_priv,
1826 const struct i915_oa_config *oa_config)
Robert Bragg19f81df2017-06-13 12:23:03 +01001827{
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001828 int ret;
Robert Bragg19f81df2017-06-13 12:23:03 +01001829
1830 /*
1831 * We disable slice/unslice clock ratio change reports on SKL since
1832 * they are too noisy. The HW generates a lot of redundant reports
1833 * where the ratio hasn't really changed causing a lot of redundant
1834 * work to processes and increasing the chances we'll hit buffer
1835 * overruns.
1836 *
1837 * Although we don't currently use the 'disable overrun' OABUFFER
1838 * feature it's worth noting that clock ratio reports have to be
1839 * disabled before considering to use that feature since the HW doesn't
1840 * correctly block these reports.
1841 *
1842 * Currently none of the high-level metrics we have depend on knowing
1843 * this ratio to normalize.
1844 *
1845 * Note: This register is not power context saved and restored, but
1846 * that's OK considering that we disable RC6 while the OA unit is
1847 * enabled.
1848 *
1849 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
1850 * be read back from automatically triggered reports, as part of the
1851 * RPT_ID field.
1852 */
Lionel Landwerlin342a2c82017-09-18 12:21:23 +01001853 if (IS_GEN9(dev_priv)) {
Robert Bragg19f81df2017-06-13 12:23:03 +01001854 I915_WRITE(GEN8_OA_DEBUG,
1855 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
1856 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
1857 }
1858
1859 /*
1860 * Update all contexts prior writing the mux configurations as we need
1861 * to make sure all slices/subslices are ON before writing to NOA
1862 * registers.
1863 */
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001864 ret = gen8_configure_all_contexts(dev_priv, oa_config, true);
Robert Bragg19f81df2017-06-13 12:23:03 +01001865 if (ret)
1866 return ret;
1867
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001868 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
1869
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001870 config_oa_regs(dev_priv, oa_config->b_counter_regs,
1871 oa_config->b_counter_regs_len);
Robert Bragg19f81df2017-06-13 12:23:03 +01001872
1873 return 0;
1874}
1875
1876static void gen8_disable_metric_set(struct drm_i915_private *dev_priv)
1877{
1878 /* Reset all contexts' slices/subslices configurations. */
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001879 gen8_configure_all_contexts(dev_priv, NULL, false);
Lionel Landwerlin28964cf2017-08-03 17:58:10 +01001880
1881 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1882 ~GT_NOA_ENABLE));
1883
Robert Bragg19f81df2017-06-13 12:23:03 +01001884}
1885
Robert Bragg1bef3402017-06-13 12:23:06 +01001886static void gen7_oa_enable(struct drm_i915_private *dev_priv)
Robert Braggd7965152016-11-07 19:49:52 +00001887{
Robert Bragg1bef3402017-06-13 12:23:06 +01001888 /*
1889 * Reset buf pointers so we don't forward reports from before now.
1890 *
1891 * Think carefully if considering trying to avoid this, since it
1892 * also ensures status flags and the buffer itself are cleared
1893 * in error paths, and we have checks for invalid reports based
1894 * on the assumption that certain fields are written to zeroed
1895 * memory which this helps maintains.
1896 */
1897 gen7_init_oa_buffer(dev_priv);
Robert Braggd7965152016-11-07 19:49:52 +00001898
1899 if (dev_priv->perf.oa.exclusive_stream->enabled) {
1900 struct i915_gem_context *ctx =
1901 dev_priv->perf.oa.exclusive_stream->ctx;
1902 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1903
1904 bool periodic = dev_priv->perf.oa.periodic;
1905 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1906 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1907
1908 I915_WRITE(GEN7_OACONTROL,
1909 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1910 (period_exponent <<
1911 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1912 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1913 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1914 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1915 GEN7_OACONTROL_ENABLE);
1916 } else
1917 I915_WRITE(GEN7_OACONTROL, 0);
1918}
1919
Robert Bragg19f81df2017-06-13 12:23:03 +01001920static void gen8_oa_enable(struct drm_i915_private *dev_priv)
1921{
1922 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1923
1924 /*
1925 * Reset buf pointers so we don't forward reports from before now.
1926 *
1927 * Think carefully if considering trying to avoid this, since it
1928 * also ensures status flags and the buffer itself are cleared
1929 * in error paths, and we have checks for invalid reports based
1930 * on the assumption that certain fields are written to zeroed
1931 * memory which this helps maintains.
1932 */
1933 gen8_init_oa_buffer(dev_priv);
1934
1935 /*
1936 * Note: we don't rely on the hardware to perform single context
1937 * filtering and instead filter on the cpu based on the context-id
1938 * field of reports
1939 */
1940 I915_WRITE(GEN8_OACONTROL, (report_format <<
1941 GEN8_OA_REPORT_FORMAT_SHIFT) |
1942 GEN8_OA_COUNTER_ENABLE);
1943}
1944
Robert Bragg16d98b32016-12-07 21:40:33 +00001945/**
1946 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1947 * @stream: An i915 perf stream opened for OA metrics
1948 *
1949 * [Re]enables hardware periodic sampling according to the period configured
1950 * when opening the stream. This also starts a hrtimer that will periodically
1951 * check for data in the circular OA buffer for notifying userspace (e.g.
1952 * during a read() or poll()).
1953 */
Robert Braggd7965152016-11-07 19:49:52 +00001954static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1955{
1956 struct drm_i915_private *dev_priv = stream->dev_priv;
1957
1958 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1959
1960 if (dev_priv->perf.oa.periodic)
1961 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1962 ns_to_ktime(POLL_PERIOD),
1963 HRTIMER_MODE_REL_PINNED);
1964}
1965
1966static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1967{
1968 I915_WRITE(GEN7_OACONTROL, 0);
1969}
1970
Robert Bragg19f81df2017-06-13 12:23:03 +01001971static void gen8_oa_disable(struct drm_i915_private *dev_priv)
1972{
1973 I915_WRITE(GEN8_OACONTROL, 0);
1974}
1975
Robert Bragg16d98b32016-12-07 21:40:33 +00001976/**
1977 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1978 * @stream: An i915 perf stream opened for OA metrics
1979 *
1980 * Stops the OA unit from periodically writing counter reports into the
1981 * circular OA buffer. This also stops the hrtimer that periodically checks for
1982 * data in the circular OA buffer, for notifying userspace.
1983 */
Robert Braggd7965152016-11-07 19:49:52 +00001984static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1985{
1986 struct drm_i915_private *dev_priv = stream->dev_priv;
1987
1988 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1989
1990 if (dev_priv->perf.oa.periodic)
1991 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1992}
1993
Robert Braggd7965152016-11-07 19:49:52 +00001994static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1995 .destroy = i915_oa_stream_destroy,
1996 .enable = i915_oa_stream_enable,
1997 .disable = i915_oa_stream_disable,
1998 .wait_unlocked = i915_oa_wait_unlocked,
1999 .poll_wait = i915_oa_poll_wait,
2000 .read = i915_oa_read,
2001};
2002
Robert Bragg16d98b32016-12-07 21:40:33 +00002003/**
2004 * i915_oa_stream_init - validate combined props for OA stream and init
2005 * @stream: An i915 perf stream
2006 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
2007 * @props: The property state that configures stream (individually validated)
2008 *
2009 * While read_properties_unlocked() validates properties in isolation it
2010 * doesn't ensure that the combination necessarily makes sense.
2011 *
2012 * At this point it has been determined that userspace wants a stream of
2013 * OA metrics, but still we need to further validate the combined
2014 * properties are OK.
2015 *
2016 * If the configuration makes sense then we can allocate memory for
2017 * a circular OA buffer and apply the requested metric set configuration.
2018 *
2019 * Returns: zero on success or a negative error code.
2020 */
Robert Braggd7965152016-11-07 19:49:52 +00002021static int i915_oa_stream_init(struct i915_perf_stream *stream,
2022 struct drm_i915_perf_open_param *param,
2023 struct perf_open_properties *props)
2024{
2025 struct drm_i915_private *dev_priv = stream->dev_priv;
2026 int format_size;
2027 int ret;
2028
Robert Bragg442b8c02016-11-07 19:49:53 +00002029 /* If the sysfs metrics/ directory wasn't registered for some
2030 * reason then don't let userspace try their luck with config
2031 * IDs
2032 */
2033 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00002034 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00002035 return -EINVAL;
2036 }
2037
Robert Braggd7965152016-11-07 19:49:52 +00002038 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00002039 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00002040 return -EINVAL;
2041 }
2042
2043 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
Robert Bragg77085502016-12-01 17:21:52 +00002044 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00002045 return -ENODEV;
2046 }
2047
2048 /* To avoid the complexity of having to accurately filter
2049 * counter reports and marshal to the appropriate client
2050 * we currently only allow exclusive access
2051 */
2052 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00002053 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00002054 return -EBUSY;
2055 }
2056
Robert Braggd7965152016-11-07 19:49:52 +00002057 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00002058 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00002059 return -EINVAL;
2060 }
2061
Robert Bragg712122e2017-05-11 16:43:31 +01002062 /* We set up some ratelimit state to potentially throttle any _NOTES
2063 * about spurious, invalid OA reports which we don't forward to
2064 * userspace.
2065 *
2066 * The initialization is associated with opening the stream (not driver
2067 * init) considering we print a _NOTE about any throttling when closing
2068 * the stream instead of waiting until driver _fini which no one would
2069 * ever see.
2070 *
2071 * Using the same limiting factors as printk_ratelimit()
2072 */
2073 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
2074 5 * HZ, 10);
2075 /* Since we use a DRM_NOTE for spurious reports it would be
2076 * inconsistent to let __ratelimit() automatically print a warning for
2077 * throttling.
2078 */
2079 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
2080 RATELIMIT_MSG_ON_RELEASE);
2081
Robert Braggd7965152016-11-07 19:49:52 +00002082 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2083
2084 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
2085
2086 stream->sample_flags |= SAMPLE_OA_REPORT;
2087 stream->sample_size += format_size;
2088
2089 dev_priv->perf.oa.oa_buffer.format_size = format_size;
2090 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
2091 return -EINVAL;
2092
2093 dev_priv->perf.oa.oa_buffer.format =
2094 dev_priv->perf.oa.oa_formats[props->oa_format].format;
2095
Robert Braggd7965152016-11-07 19:49:52 +00002096 dev_priv->perf.oa.periodic = props->oa_periodic;
Robert Bragg0dd860c2017-05-11 16:43:28 +01002097 if (dev_priv->perf.oa.periodic)
Robert Braggd7965152016-11-07 19:49:52 +00002098 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
2099
Robert Braggd7965152016-11-07 19:49:52 +00002100 if (stream->ctx) {
2101 ret = oa_get_render_ctx_id(stream);
2102 if (ret)
2103 return ret;
2104 }
2105
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002106 ret = get_oa_config(dev_priv, props->metrics_set, &stream->oa_config);
2107 if (ret)
2108 goto err_config;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002109
Robert Braggd7965152016-11-07 19:49:52 +00002110 /* PRM - observability performance counters:
2111 *
2112 * OACONTROL, performance counter enable, note:
2113 *
2114 * "When this bit is set, in order to have coherent counts,
2115 * RC6 power state and trunk clock gating must be disabled.
2116 * This can be achieved by programming MMIO registers as
2117 * 0xA094=0 and 0xA090[31]=1"
2118 *
2119 * In our case we are expecting that taking pm + FORCEWAKE
2120 * references will effectively disable RC6.
2121 */
2122 intel_runtime_pm_get(dev_priv);
2123 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
2124
sagar.a.kamble@intel.com987f8c42017-06-27 23:09:41 +05302125 ret = alloc_oa_buffer(dev_priv);
2126 if (ret)
2127 goto err_oa_buf_alloc;
2128
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002129 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv,
2130 stream->oa_config);
Robert Braggd7965152016-11-07 19:49:52 +00002131 if (ret)
2132 goto err_enable;
2133
2134 stream->ops = &i915_oa_stream_ops;
2135
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002136 /* Lock device for exclusive_stream access late because
2137 * enable_metric_set() might lock as well on gen8+.
2138 */
2139 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
2140 if (ret)
2141 goto err_lock;
2142
Robert Braggd7965152016-11-07 19:49:52 +00002143 dev_priv->perf.oa.exclusive_stream = stream;
2144
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002145 mutex_unlock(&dev_priv->drm.struct_mutex);
2146
Robert Braggd7965152016-11-07 19:49:52 +00002147 return 0;
2148
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002149err_lock:
2150 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
2151
Robert Braggd7965152016-11-07 19:49:52 +00002152err_enable:
Robert Braggd7965152016-11-07 19:49:52 +00002153 free_oa_buffer(dev_priv);
2154
2155err_oa_buf_alloc:
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002156 put_oa_config(dev_priv, stream->oa_config);
2157
sagar.a.kamble@intel.com987f8c42017-06-27 23:09:41 +05302158 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2159 intel_runtime_pm_put(dev_priv);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002160
2161err_config:
Robert Braggd7965152016-11-07 19:49:52 +00002162 if (stream->ctx)
2163 oa_put_render_ctx_id(stream);
2164
2165 return ret;
2166}
2167
Robert Bragg19f81df2017-06-13 12:23:03 +01002168void i915_oa_init_reg_state(struct intel_engine_cs *engine,
2169 struct i915_gem_context *ctx,
2170 u32 *reg_state)
2171{
Chris Wilson28b6cb02017-08-10 18:57:43 +01002172 struct i915_perf_stream *stream;
Robert Bragg19f81df2017-06-13 12:23:03 +01002173
2174 if (engine->id != RCS)
2175 return;
2176
Chris Wilson28b6cb02017-08-10 18:57:43 +01002177 stream = engine->i915->perf.oa.exclusive_stream;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002178 if (stream)
2179 gen8_update_reg_state_unlocked(ctx, reg_state, stream->oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01002180}
2181
Robert Bragg16d98b32016-12-07 21:40:33 +00002182/**
2183 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2184 * @stream: An i915 perf stream
2185 * @file: An i915 perf stream file
2186 * @buf: destination buffer given by userspace
2187 * @count: the number of bytes userspace wants to read
2188 * @ppos: (inout) file seek position (unused)
2189 *
2190 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2191 * ensure that if we've successfully copied any data then reporting that takes
2192 * precedence over any internal error status, so the data isn't lost.
2193 *
2194 * For example ret will be -ENOSPC whenever there is more buffered data than
2195 * can be copied to userspace, but that's only interesting if we weren't able
2196 * to copy some data because it implies the userspace buffer is too small to
2197 * receive a single record (and we never split records).
2198 *
2199 * Another case with ret == -EFAULT is more of a grey area since it would seem
2200 * like bad form for userspace to ask us to overrun its buffer, but the user
2201 * knows best:
2202 *
2203 * http://yarchive.net/comp/linux/partial_reads_writes.html
2204 *
2205 * Returns: The number of bytes copied or a negative error code on failure.
2206 */
Robert Braggeec688e2016-11-07 19:49:47 +00002207static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2208 struct file *file,
2209 char __user *buf,
2210 size_t count,
2211 loff_t *ppos)
2212{
2213 /* Note we keep the offset (aka bytes read) separate from any
2214 * error status so that the final check for whether we return
2215 * the bytes read with a higher precedence than any error (see
2216 * comment below) doesn't need to be handled/duplicated in
2217 * stream->ops->read() implementations.
2218 */
2219 size_t offset = 0;
2220 int ret = stream->ops->read(stream, buf, count, &offset);
2221
Robert Braggeec688e2016-11-07 19:49:47 +00002222 return offset ?: (ret ?: -EAGAIN);
2223}
2224
Robert Bragg16d98b32016-12-07 21:40:33 +00002225/**
2226 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2227 * @file: An i915 perf stream file
2228 * @buf: destination buffer given by userspace
2229 * @count: the number of bytes userspace wants to read
2230 * @ppos: (inout) file seek position (unused)
2231 *
2232 * The entry point for handling a read() on a stream file descriptor from
2233 * userspace. Most of the work is left to the i915_perf_read_locked() and
2234 * &i915_perf_stream_ops->read but to save having stream implementations (of
2235 * which we might have multiple later) we handle blocking read here.
2236 *
2237 * We can also consistently treat trying to read from a disabled stream
2238 * as an IO error so implementations can assume the stream is enabled
2239 * while reading.
2240 *
2241 * Returns: The number of bytes copied or a negative error code on failure.
2242 */
Robert Braggeec688e2016-11-07 19:49:47 +00002243static ssize_t i915_perf_read(struct file *file,
2244 char __user *buf,
2245 size_t count,
2246 loff_t *ppos)
2247{
2248 struct i915_perf_stream *stream = file->private_data;
2249 struct drm_i915_private *dev_priv = stream->dev_priv;
2250 ssize_t ret;
2251
Robert Braggd7965152016-11-07 19:49:52 +00002252 /* To ensure it's handled consistently we simply treat all reads of a
2253 * disabled stream as an error. In particular it might otherwise lead
2254 * to a deadlock for blocking file descriptors...
2255 */
2256 if (!stream->enabled)
2257 return -EIO;
2258
Robert Braggeec688e2016-11-07 19:49:47 +00002259 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00002260 /* There's the small chance of false positives from
2261 * stream->ops->wait_unlocked.
2262 *
2263 * E.g. with single context filtering since we only wait until
2264 * oabuffer has >= 1 report we don't immediately know whether
2265 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00002266 */
2267 do {
2268 ret = stream->ops->wait_unlocked(stream);
2269 if (ret)
2270 return ret;
2271
2272 mutex_lock(&dev_priv->perf.lock);
2273 ret = i915_perf_read_locked(stream, file,
2274 buf, count, ppos);
2275 mutex_unlock(&dev_priv->perf.lock);
2276 } while (ret == -EAGAIN);
2277 } else {
2278 mutex_lock(&dev_priv->perf.lock);
2279 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
2280 mutex_unlock(&dev_priv->perf.lock);
2281 }
2282
Robert Bragg26ebd9c2017-05-11 16:43:25 +01002283 /* We allow the poll checking to sometimes report false positive POLLIN
2284 * events where we might actually report EAGAIN on read() if there's
2285 * not really any data available. In this situation though we don't
2286 * want to enter a busy loop between poll() reporting a POLLIN event
2287 * and read() returning -EAGAIN. Clearing the oa.pollin state here
2288 * effectively ensures we back off until the next hrtimer callback
2289 * before reporting another POLLIN event.
2290 */
2291 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00002292 /* Maybe make ->pollin per-stream state if we support multiple
2293 * concurrent streams in the future.
2294 */
2295 dev_priv->perf.oa.pollin = false;
2296 }
2297
Robert Braggeec688e2016-11-07 19:49:47 +00002298 return ret;
2299}
2300
Robert Braggd7965152016-11-07 19:49:52 +00002301static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
2302{
2303 struct drm_i915_private *dev_priv =
2304 container_of(hrtimer, typeof(*dev_priv),
2305 perf.oa.poll_check_timer);
2306
Robert Bragg19f81df2017-06-13 12:23:03 +01002307 if (oa_buffer_check_unlocked(dev_priv)) {
Robert Braggd7965152016-11-07 19:49:52 +00002308 dev_priv->perf.oa.pollin = true;
2309 wake_up(&dev_priv->perf.oa.poll_wq);
2310 }
2311
2312 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
2313
2314 return HRTIMER_RESTART;
2315}
2316
Robert Bragg16d98b32016-12-07 21:40:33 +00002317/**
2318 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
2319 * @dev_priv: i915 device instance
2320 * @stream: An i915 perf stream
2321 * @file: An i915 perf stream file
2322 * @wait: poll() state table
2323 *
2324 * For handling userspace polling on an i915 perf stream, this calls through to
2325 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
2326 * will be woken for new stream data.
2327 *
2328 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2329 * with any non-file-operation driver hooks.
2330 *
2331 * Returns: any poll events that are ready without sleeping
2332 */
Robert Braggd7965152016-11-07 19:49:52 +00002333static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
2334 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00002335 struct file *file,
2336 poll_table *wait)
2337{
Robert Braggd7965152016-11-07 19:49:52 +00002338 unsigned int events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00002339
2340 stream->ops->poll_wait(stream, file, wait);
2341
Robert Braggd7965152016-11-07 19:49:52 +00002342 /* Note: we don't explicitly check whether there's something to read
2343 * here since this path may be very hot depending on what else
2344 * userspace is polling, or on the timeout in use. We rely solely on
2345 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
2346 * samples to read.
2347 */
2348 if (dev_priv->perf.oa.pollin)
2349 events |= POLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00002350
Robert Braggd7965152016-11-07 19:49:52 +00002351 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00002352}
2353
Robert Bragg16d98b32016-12-07 21:40:33 +00002354/**
2355 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
2356 * @file: An i915 perf stream file
2357 * @wait: poll() state table
2358 *
2359 * For handling userspace polling on an i915 perf stream, this ensures
2360 * poll_wait() gets called with a wait queue that will be woken for new stream
2361 * data.
2362 *
2363 * Note: Implementation deferred to i915_perf_poll_locked()
2364 *
2365 * Returns: any poll events that are ready without sleeping
2366 */
Robert Braggeec688e2016-11-07 19:49:47 +00002367static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
2368{
2369 struct i915_perf_stream *stream = file->private_data;
2370 struct drm_i915_private *dev_priv = stream->dev_priv;
2371 int ret;
2372
2373 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002374 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00002375 mutex_unlock(&dev_priv->perf.lock);
2376
2377 return ret;
2378}
2379
Robert Bragg16d98b32016-12-07 21:40:33 +00002380/**
2381 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
2382 * @stream: A disabled i915 perf stream
2383 *
2384 * [Re]enables the associated capture of data for this stream.
2385 *
2386 * If a stream was previously enabled then there's currently no intention
2387 * to provide userspace any guarantee about the preservation of previously
2388 * buffered data.
2389 */
Robert Braggeec688e2016-11-07 19:49:47 +00002390static void i915_perf_enable_locked(struct i915_perf_stream *stream)
2391{
2392 if (stream->enabled)
2393 return;
2394
2395 /* Allow stream->ops->enable() to refer to this */
2396 stream->enabled = true;
2397
2398 if (stream->ops->enable)
2399 stream->ops->enable(stream);
2400}
2401
Robert Bragg16d98b32016-12-07 21:40:33 +00002402/**
2403 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
2404 * @stream: An enabled i915 perf stream
2405 *
2406 * Disables the associated capture of data for this stream.
2407 *
2408 * The intention is that disabling an re-enabling a stream will ideally be
2409 * cheaper than destroying and re-opening a stream with the same configuration,
2410 * though there are no formal guarantees about what state or buffered data
2411 * must be retained between disabling and re-enabling a stream.
2412 *
2413 * Note: while a stream is disabled it's considered an error for userspace
2414 * to attempt to read from the stream (-EIO).
2415 */
Robert Braggeec688e2016-11-07 19:49:47 +00002416static void i915_perf_disable_locked(struct i915_perf_stream *stream)
2417{
2418 if (!stream->enabled)
2419 return;
2420
2421 /* Allow stream->ops->disable() to refer to this */
2422 stream->enabled = false;
2423
2424 if (stream->ops->disable)
2425 stream->ops->disable(stream);
2426}
2427
Robert Bragg16d98b32016-12-07 21:40:33 +00002428/**
2429 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2430 * @stream: An i915 perf stream
2431 * @cmd: the ioctl request
2432 * @arg: the ioctl data
2433 *
2434 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2435 * with any non-file-operation driver hooks.
2436 *
2437 * Returns: zero on success or a negative error code. Returns -EINVAL for
2438 * an unknown ioctl request.
2439 */
Robert Braggeec688e2016-11-07 19:49:47 +00002440static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
2441 unsigned int cmd,
2442 unsigned long arg)
2443{
2444 switch (cmd) {
2445 case I915_PERF_IOCTL_ENABLE:
2446 i915_perf_enable_locked(stream);
2447 return 0;
2448 case I915_PERF_IOCTL_DISABLE:
2449 i915_perf_disable_locked(stream);
2450 return 0;
2451 }
2452
2453 return -EINVAL;
2454}
2455
Robert Bragg16d98b32016-12-07 21:40:33 +00002456/**
2457 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2458 * @file: An i915 perf stream file
2459 * @cmd: the ioctl request
2460 * @arg: the ioctl data
2461 *
2462 * Implementation deferred to i915_perf_ioctl_locked().
2463 *
2464 * Returns: zero on success or a negative error code. Returns -EINVAL for
2465 * an unknown ioctl request.
2466 */
Robert Braggeec688e2016-11-07 19:49:47 +00002467static long i915_perf_ioctl(struct file *file,
2468 unsigned int cmd,
2469 unsigned long arg)
2470{
2471 struct i915_perf_stream *stream = file->private_data;
2472 struct drm_i915_private *dev_priv = stream->dev_priv;
2473 long ret;
2474
2475 mutex_lock(&dev_priv->perf.lock);
2476 ret = i915_perf_ioctl_locked(stream, cmd, arg);
2477 mutex_unlock(&dev_priv->perf.lock);
2478
2479 return ret;
2480}
2481
Robert Bragg16d98b32016-12-07 21:40:33 +00002482/**
2483 * i915_perf_destroy_locked - destroy an i915 perf stream
2484 * @stream: An i915 perf stream
2485 *
2486 * Frees all resources associated with the given i915 perf @stream, disabling
2487 * any associated data capture in the process.
2488 *
2489 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2490 * with any non-file-operation driver hooks.
2491 */
Robert Braggeec688e2016-11-07 19:49:47 +00002492static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
2493{
Robert Braggeec688e2016-11-07 19:49:47 +00002494 if (stream->enabled)
2495 i915_perf_disable_locked(stream);
2496
2497 if (stream->ops->destroy)
2498 stream->ops->destroy(stream);
2499
2500 list_del(&stream->link);
2501
Chris Wilson69df05e2016-12-18 15:37:21 +00002502 if (stream->ctx)
Chris Wilson5f09a9c2017-06-20 12:05:46 +01002503 i915_gem_context_put(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00002504
2505 kfree(stream);
2506}
2507
Robert Bragg16d98b32016-12-07 21:40:33 +00002508/**
2509 * i915_perf_release - handles userspace close() of a stream file
2510 * @inode: anonymous inode associated with file
2511 * @file: An i915 perf stream file
2512 *
2513 * Cleans up any resources associated with an open i915 perf stream file.
2514 *
2515 * NB: close() can't really fail from the userspace point of view.
2516 *
2517 * Returns: zero on success or a negative error code.
2518 */
Robert Braggeec688e2016-11-07 19:49:47 +00002519static int i915_perf_release(struct inode *inode, struct file *file)
2520{
2521 struct i915_perf_stream *stream = file->private_data;
2522 struct drm_i915_private *dev_priv = stream->dev_priv;
2523
2524 mutex_lock(&dev_priv->perf.lock);
2525 i915_perf_destroy_locked(stream);
2526 mutex_unlock(&dev_priv->perf.lock);
2527
2528 return 0;
2529}
2530
2531
2532static const struct file_operations fops = {
2533 .owner = THIS_MODULE,
2534 .llseek = no_llseek,
2535 .release = i915_perf_release,
2536 .poll = i915_perf_poll,
2537 .read = i915_perf_read,
2538 .unlocked_ioctl = i915_perf_ioctl,
2539};
2540
2541
Robert Bragg16d98b32016-12-07 21:40:33 +00002542/**
2543 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
2544 * @dev_priv: i915 device instance
2545 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
2546 * @props: individually validated u64 property value pairs
2547 * @file: drm file
2548 *
2549 * See i915_perf_ioctl_open() for interface details.
2550 *
2551 * Implements further stream config validation and stream initialization on
2552 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
2553 * taken to serialize with any non-file-operation driver hooks.
2554 *
2555 * Note: at this point the @props have only been validated in isolation and
2556 * it's still necessary to validate that the combination of properties makes
2557 * sense.
2558 *
2559 * In the case where userspace is interested in OA unit metrics then further
2560 * config validation and stream initialization details will be handled by
2561 * i915_oa_stream_init(). The code here should only validate config state that
2562 * will be relevant to all stream types / backends.
2563 *
2564 * Returns: zero on success or a negative error code.
2565 */
Robert Braggeec688e2016-11-07 19:49:47 +00002566static int
2567i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
2568 struct drm_i915_perf_open_param *param,
2569 struct perf_open_properties *props,
2570 struct drm_file *file)
2571{
2572 struct i915_gem_context *specific_ctx = NULL;
2573 struct i915_perf_stream *stream = NULL;
2574 unsigned long f_flags = 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01002575 bool privileged_op = true;
Robert Braggeec688e2016-11-07 19:49:47 +00002576 int stream_fd;
2577 int ret;
2578
2579 if (props->single_context) {
2580 u32 ctx_handle = props->ctx_handle;
2581 struct drm_i915_file_private *file_priv = file->driver_priv;
2582
Imre Deak635f56c2017-07-14 18:12:41 +03002583 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
2584 if (!specific_ctx) {
2585 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
2586 ctx_handle);
2587 ret = -ENOENT;
Robert Braggeec688e2016-11-07 19:49:47 +00002588 goto err;
2589 }
2590 }
2591
Robert Bragg19f81df2017-06-13 12:23:03 +01002592 /*
2593 * On Haswell the OA unit supports clock gating off for a specific
2594 * context and in this mode there's no visibility of metrics for the
2595 * rest of the system, which we consider acceptable for a
2596 * non-privileged client.
2597 *
2598 * For Gen8+ the OA unit no longer supports clock gating off for a
2599 * specific context and the kernel can't securely stop the counters
2600 * from updating as system-wide / global values. Even though we can
2601 * filter reports based on the included context ID we can't block
2602 * clients from seeing the raw / global counter values via
2603 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
2604 * enable the OA unit by default.
2605 */
2606 if (IS_HASWELL(dev_priv) && specific_ctx)
2607 privileged_op = false;
2608
Robert Braggccdf6342016-11-07 19:49:54 +00002609 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
2610 * we check a dev.i915.perf_stream_paranoid sysctl option
2611 * to determine if it's ok to access system wide OA counters
2612 * without CAP_SYS_ADMIN privileges.
2613 */
Robert Bragg19f81df2017-06-13 12:23:03 +01002614 if (privileged_op &&
Robert Braggccdf6342016-11-07 19:49:54 +00002615 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00002616 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002617 ret = -EACCES;
2618 goto err_ctx;
2619 }
2620
2621 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
2622 if (!stream) {
2623 ret = -ENOMEM;
2624 goto err_ctx;
2625 }
2626
Robert Braggeec688e2016-11-07 19:49:47 +00002627 stream->dev_priv = dev_priv;
2628 stream->ctx = specific_ctx;
2629
Robert Braggd7965152016-11-07 19:49:52 +00002630 ret = i915_oa_stream_init(stream, param, props);
2631 if (ret)
2632 goto err_alloc;
2633
2634 /* we avoid simply assigning stream->sample_flags = props->sample_flags
2635 * to have _stream_init check the combination of sample flags more
2636 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00002637 */
Robert Braggd7965152016-11-07 19:49:52 +00002638 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
2639 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01002640 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00002641 }
Robert Braggeec688e2016-11-07 19:49:47 +00002642
2643 list_add(&stream->link, &dev_priv->perf.streams);
2644
2645 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
2646 f_flags |= O_CLOEXEC;
2647 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
2648 f_flags |= O_NONBLOCK;
2649
2650 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
2651 if (stream_fd < 0) {
2652 ret = stream_fd;
2653 goto err_open;
2654 }
2655
2656 if (!(param->flags & I915_PERF_FLAG_DISABLED))
2657 i915_perf_enable_locked(stream);
2658
2659 return stream_fd;
2660
2661err_open:
2662 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01002663err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00002664 if (stream->ops->destroy)
2665 stream->ops->destroy(stream);
2666err_alloc:
2667 kfree(stream);
2668err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00002669 if (specific_ctx)
Chris Wilson5f09a9c2017-06-20 12:05:46 +01002670 i915_gem_context_put(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00002671err:
2672 return ret;
2673}
2674
Robert Bragg155e9412017-06-13 12:23:05 +01002675static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
2676{
2677 return div_u64(1000000000ULL * (2ULL << exponent),
2678 dev_priv->perf.oa.timestamp_frequency);
2679}
2680
Robert Bragg16d98b32016-12-07 21:40:33 +00002681/**
2682 * read_properties_unlocked - validate + copy userspace stream open properties
2683 * @dev_priv: i915 device instance
2684 * @uprops: The array of u64 key value pairs given by userspace
2685 * @n_props: The number of key value pairs expected in @uprops
2686 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00002687 *
2688 * Note this function only validates properties in isolation it doesn't
2689 * validate that the combination of properties makes sense or that all
2690 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00002691 *
2692 * Note that there currently aren't any ordering requirements for properties so
2693 * we shouldn't validate or assume anything about ordering here. This doesn't
2694 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00002695 */
2696static int read_properties_unlocked(struct drm_i915_private *dev_priv,
2697 u64 __user *uprops,
2698 u32 n_props,
2699 struct perf_open_properties *props)
2700{
2701 u64 __user *uprop = uprops;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002702 u32 i;
Robert Braggeec688e2016-11-07 19:49:47 +00002703
2704 memset(props, 0, sizeof(struct perf_open_properties));
2705
2706 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00002707 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002708 return -EINVAL;
2709 }
2710
2711 /* Considering that ID = 0 is reserved and assuming that we don't
2712 * (currently) expect any configurations to ever specify duplicate
2713 * values for a particular property ID then the last _PROP_MAX value is
2714 * one greater than the maximum number of properties we expect to get
2715 * from userspace.
2716 */
2717 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00002718 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002719 return -EINVAL;
2720 }
2721
2722 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00002723 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00002724 u64 id, value;
2725 int ret;
2726
2727 ret = get_user(id, uprop);
2728 if (ret)
2729 return ret;
2730
2731 ret = get_user(value, uprop + 1);
2732 if (ret)
2733 return ret;
2734
Matthew Auld0a309f92017-03-27 21:32:36 +01002735 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
2736 DRM_DEBUG("Unknown i915 perf property ID\n");
2737 return -EINVAL;
2738 }
2739
Robert Braggeec688e2016-11-07 19:49:47 +00002740 switch ((enum drm_i915_perf_property_id)id) {
2741 case DRM_I915_PERF_PROP_CTX_HANDLE:
2742 props->single_context = 1;
2743 props->ctx_handle = value;
2744 break;
Robert Braggd7965152016-11-07 19:49:52 +00002745 case DRM_I915_PERF_PROP_SAMPLE_OA:
2746 props->sample_flags |= SAMPLE_OA_REPORT;
2747 break;
2748 case DRM_I915_PERF_PROP_OA_METRICS_SET:
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002749 if (value == 0) {
Robert Bragg77085502016-12-01 17:21:52 +00002750 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00002751 return -EINVAL;
2752 }
2753 props->metrics_set = value;
2754 break;
2755 case DRM_I915_PERF_PROP_OA_FORMAT:
2756 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg52c57c22017-05-11 16:43:29 +01002757 DRM_DEBUG("Out-of-range OA report format %llu\n",
2758 value);
Robert Braggd7965152016-11-07 19:49:52 +00002759 return -EINVAL;
2760 }
2761 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg52c57c22017-05-11 16:43:29 +01002762 DRM_DEBUG("Unsupported OA report format %llu\n",
2763 value);
Robert Braggd7965152016-11-07 19:49:52 +00002764 return -EINVAL;
2765 }
2766 props->oa_format = value;
2767 break;
2768 case DRM_I915_PERF_PROP_OA_EXPONENT:
2769 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00002770 DRM_DEBUG("OA timer exponent too high (> %u)\n",
2771 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00002772 return -EINVAL;
2773 }
2774
Robert Bragg00319ba2016-11-07 19:49:55 +00002775 /* Theoretically we can program the OA unit to sample
Robert Bragg155e9412017-06-13 12:23:05 +01002776 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
2777 * for BXT. We don't allow such high sampling
2778 * frequencies by default unless root.
Robert Braggd7965152016-11-07 19:49:52 +00002779 */
Robert Bragg155e9412017-06-13 12:23:05 +01002780
Robert Bragg00319ba2016-11-07 19:49:55 +00002781 BUILD_BUG_ON(sizeof(oa_period) != 8);
Robert Bragg155e9412017-06-13 12:23:05 +01002782 oa_period = oa_exponent_to_ns(dev_priv, value);
Robert Bragg00319ba2016-11-07 19:49:55 +00002783
2784 /* This check is primarily to ensure that oa_period <=
2785 * UINT32_MAX (before passing to do_div which only
2786 * accepts a u32 denominator), but we can also skip
2787 * checking anything < 1Hz which implicitly can't be
2788 * limited via an integer oa_max_sample_rate.
2789 */
2790 if (oa_period <= NSEC_PER_SEC) {
2791 u64 tmp = NSEC_PER_SEC;
2792 do_div(tmp, oa_period);
2793 oa_freq_hz = tmp;
2794 } else
2795 oa_freq_hz = 0;
2796
2797 if (oa_freq_hz > i915_oa_max_sample_rate &&
2798 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00002799 DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
Robert Bragg00319ba2016-11-07 19:49:55 +00002800 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00002801 return -EACCES;
2802 }
2803
2804 props->oa_periodic = true;
2805 props->oa_period_exponent = value;
2806 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01002807 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00002808 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00002809 return -EINVAL;
2810 }
2811
2812 uprop += 2;
2813 }
2814
2815 return 0;
2816}
2817
Robert Bragg16d98b32016-12-07 21:40:33 +00002818/**
2819 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
2820 * @dev: drm device
2821 * @data: ioctl data copied from userspace (unvalidated)
2822 * @file: drm file
2823 *
2824 * Validates the stream open parameters given by userspace including flags
2825 * and an array of u64 key, value pair properties.
2826 *
2827 * Very little is assumed up front about the nature of the stream being
2828 * opened (for instance we don't assume it's for periodic OA unit metrics). An
2829 * i915-perf stream is expected to be a suitable interface for other forms of
2830 * buffered data written by the GPU besides periodic OA metrics.
2831 *
2832 * Note we copy the properties from userspace outside of the i915 perf
2833 * mutex to avoid an awkward lockdep with mmap_sem.
2834 *
2835 * Most of the implementation details are handled by
2836 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
2837 * mutex for serializing with any non-file-operation driver hooks.
2838 *
2839 * Return: A newly opened i915 Perf stream file descriptor or negative
2840 * error code on failure.
2841 */
Robert Braggeec688e2016-11-07 19:49:47 +00002842int i915_perf_open_ioctl(struct drm_device *dev, void *data,
2843 struct drm_file *file)
2844{
2845 struct drm_i915_private *dev_priv = dev->dev_private;
2846 struct drm_i915_perf_open_param *param = data;
2847 struct perf_open_properties props;
2848 u32 known_open_flags;
2849 int ret;
2850
2851 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00002852 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002853 return -ENOTSUPP;
2854 }
2855
2856 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
2857 I915_PERF_FLAG_FD_NONBLOCK |
2858 I915_PERF_FLAG_DISABLED;
2859 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00002860 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002861 return -EINVAL;
2862 }
2863
2864 ret = read_properties_unlocked(dev_priv,
2865 u64_to_user_ptr(param->properties_ptr),
2866 param->num_properties,
2867 &props);
2868 if (ret)
2869 return ret;
2870
2871 mutex_lock(&dev_priv->perf.lock);
2872 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
2873 mutex_unlock(&dev_priv->perf.lock);
2874
2875 return ret;
2876}
2877
Robert Bragg16d98b32016-12-07 21:40:33 +00002878/**
2879 * i915_perf_register - exposes i915-perf to userspace
2880 * @dev_priv: i915 device instance
2881 *
2882 * In particular OA metric sets are advertised under a sysfs metrics/
2883 * directory allowing userspace to enumerate valid IDs that can be
2884 * used to open an i915-perf stream.
2885 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002886void i915_perf_register(struct drm_i915_private *dev_priv)
2887{
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002888 int ret;
2889
Robert Bragg442b8c02016-11-07 19:49:53 +00002890 if (!dev_priv->perf.initialized)
2891 return;
2892
2893 /* To be sure we're synchronized with an attempted
2894 * i915_perf_open_ioctl(); considering that we register after
2895 * being exposed to userspace.
2896 */
2897 mutex_lock(&dev_priv->perf.lock);
2898
2899 dev_priv->perf.metrics_kobj =
2900 kobject_create_and_add("metrics",
2901 &dev_priv->drm.primary->kdev->kobj);
2902 if (!dev_priv->perf.metrics_kobj)
2903 goto exit;
2904
Chris Wilson40f75ea2017-08-10 18:57:41 +01002905 sysfs_attr_init(&dev_priv->perf.oa.test_config.sysfs_metric_id.attr);
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002906
Robert Bragg19f81df2017-06-13 12:23:03 +01002907 if (IS_HASWELL(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002908 i915_perf_load_test_config_hsw(dev_priv);
Robert Bragg19f81df2017-06-13 12:23:03 +01002909 } else if (IS_BROADWELL(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002910 i915_perf_load_test_config_bdw(dev_priv);
Robert Bragg19f81df2017-06-13 12:23:03 +01002911 } else if (IS_CHERRYVIEW(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002912 i915_perf_load_test_config_chv(dev_priv);
Robert Bragg19f81df2017-06-13 12:23:03 +01002913 } else if (IS_SKYLAKE(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002914 if (IS_SKL_GT2(dev_priv))
2915 i915_perf_load_test_config_sklgt2(dev_priv);
2916 else if (IS_SKL_GT3(dev_priv))
2917 i915_perf_load_test_config_sklgt3(dev_priv);
2918 else if (IS_SKL_GT4(dev_priv))
2919 i915_perf_load_test_config_sklgt4(dev_priv);
Robert Bragg19f81df2017-06-13 12:23:03 +01002920 } else if (IS_BROXTON(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002921 i915_perf_load_test_config_bxt(dev_priv);
Lionel Landwerlin6c5c1d82017-06-13 12:23:08 +01002922 } else if (IS_KABYLAKE(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002923 if (IS_KBL_GT2(dev_priv))
2924 i915_perf_load_test_config_kblgt2(dev_priv);
2925 else if (IS_KBL_GT3(dev_priv))
2926 i915_perf_load_test_config_kblgt3(dev_priv);
Lionel Landwerlin28c7ef92017-06-13 12:23:09 +01002927 } else if (IS_GEMINILAKE(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002928 i915_perf_load_test_config_glk(dev_priv);
Robert Bragg442b8c02016-11-07 19:49:53 +00002929 }
2930
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002931 if (dev_priv->perf.oa.test_config.id == 0)
2932 goto sysfs_error;
2933
2934 ret = sysfs_create_group(dev_priv->perf.metrics_kobj,
2935 &dev_priv->perf.oa.test_config.sysfs_metric);
2936 if (ret)
2937 goto sysfs_error;
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002938
2939 atomic_set(&dev_priv->perf.oa.test_config.ref_count, 1);
2940
Robert Bragg19f81df2017-06-13 12:23:03 +01002941 goto exit;
2942
2943sysfs_error:
2944 kobject_put(dev_priv->perf.metrics_kobj);
2945 dev_priv->perf.metrics_kobj = NULL;
2946
Robert Bragg442b8c02016-11-07 19:49:53 +00002947exit:
2948 mutex_unlock(&dev_priv->perf.lock);
2949}
2950
Robert Bragg16d98b32016-12-07 21:40:33 +00002951/**
2952 * i915_perf_unregister - hide i915-perf from userspace
2953 * @dev_priv: i915 device instance
2954 *
2955 * i915-perf state cleanup is split up into an 'unregister' and
2956 * 'deinit' phase where the interface is first hidden from
2957 * userspace by i915_perf_unregister() before cleaning up
2958 * remaining state in i915_perf_fini().
2959 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002960void i915_perf_unregister(struct drm_i915_private *dev_priv)
2961{
Robert Bragg442b8c02016-11-07 19:49:53 +00002962 if (!dev_priv->perf.metrics_kobj)
2963 return;
2964
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002965 sysfs_remove_group(dev_priv->perf.metrics_kobj,
2966 &dev_priv->perf.oa.test_config.sysfs_metric);
Robert Bragg442b8c02016-11-07 19:49:53 +00002967
2968 kobject_put(dev_priv->perf.metrics_kobj);
2969 dev_priv->perf.metrics_kobj = NULL;
2970}
2971
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002972static bool gen8_is_valid_flex_addr(struct drm_i915_private *dev_priv, u32 addr)
2973{
2974 static const i915_reg_t flex_eu_regs[] = {
2975 EU_PERF_CNTL0,
2976 EU_PERF_CNTL1,
2977 EU_PERF_CNTL2,
2978 EU_PERF_CNTL3,
2979 EU_PERF_CNTL4,
2980 EU_PERF_CNTL5,
2981 EU_PERF_CNTL6,
2982 };
2983 int i;
2984
2985 for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
2986 if (flex_eu_regs[i].reg == addr)
2987 return true;
2988 }
2989 return false;
2990}
2991
2992static bool gen7_is_valid_b_counter_addr(struct drm_i915_private *dev_priv, u32 addr)
2993{
2994 return (addr >= OASTARTTRIG1.reg && addr <= OASTARTTRIG8.reg) ||
2995 (addr >= OAREPORTTRIG1.reg && addr <= OAREPORTTRIG8.reg) ||
2996 (addr >= OACEC0_0.reg && addr <= OACEC7_1.reg);
2997}
2998
2999static bool gen7_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3000{
3001 return addr == HALF_SLICE_CHICKEN2.reg ||
3002 (addr >= MICRO_BP0_0.reg && addr <= NOA_WRITE.reg) ||
3003 (addr >= OA_PERFCNT1_LO.reg && addr <= OA_PERFCNT2_HI.reg) ||
3004 (addr >= OA_PERFMATRIX_LO.reg && addr <= OA_PERFMATRIX_HI.reg);
3005}
3006
3007static bool gen8_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3008{
3009 return gen7_is_valid_mux_addr(dev_priv, addr) ||
3010 addr == WAIT_FOR_RC6_EXIT.reg ||
3011 (addr >= RPM_CONFIG0.reg && addr <= NOA_CONFIG(8).reg);
3012}
3013
3014static bool hsw_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3015{
3016 return gen7_is_valid_mux_addr(dev_priv, addr) ||
3017 (addr >= 0x25100 && addr <= 0x2FF90) ||
3018 addr == 0x9ec0;
3019}
3020
3021static bool chv_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3022{
3023 return gen7_is_valid_mux_addr(dev_priv, addr) ||
3024 (addr >= 0x182300 && addr <= 0x1823A4);
3025}
3026
3027static uint32_t mask_reg_value(u32 reg, u32 val)
3028{
3029 /* HALF_SLICE_CHICKEN2 is programmed with a the
3030 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
3031 * programmed by userspace doesn't change this.
3032 */
3033 if (HALF_SLICE_CHICKEN2.reg == reg)
3034 val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
3035
3036 /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
3037 * indicated by its name and a bunch of selection fields used by OA
3038 * configs.
3039 */
3040 if (WAIT_FOR_RC6_EXIT.reg == reg)
3041 val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
3042
3043 return val;
3044}
3045
3046static struct i915_oa_reg *alloc_oa_regs(struct drm_i915_private *dev_priv,
3047 bool (*is_valid)(struct drm_i915_private *dev_priv, u32 addr),
3048 u32 __user *regs,
3049 u32 n_regs)
3050{
3051 struct i915_oa_reg *oa_regs;
3052 int err;
3053 u32 i;
3054
3055 if (!n_regs)
3056 return NULL;
3057
3058 if (!access_ok(VERIFY_READ, regs, n_regs * sizeof(u32) * 2))
3059 return ERR_PTR(-EFAULT);
3060
3061 /* No is_valid function means we're not allowing any register to be programmed. */
3062 GEM_BUG_ON(!is_valid);
3063 if (!is_valid)
3064 return ERR_PTR(-EINVAL);
3065
3066 oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
3067 if (!oa_regs)
3068 return ERR_PTR(-ENOMEM);
3069
3070 for (i = 0; i < n_regs; i++) {
3071 u32 addr, value;
3072
3073 err = get_user(addr, regs);
3074 if (err)
3075 goto addr_err;
3076
3077 if (!is_valid(dev_priv, addr)) {
3078 DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
3079 err = -EINVAL;
3080 goto addr_err;
3081 }
3082
3083 err = get_user(value, regs + 1);
3084 if (err)
3085 goto addr_err;
3086
3087 oa_regs[i].addr = _MMIO(addr);
3088 oa_regs[i].value = mask_reg_value(addr, value);
3089
3090 regs += 2;
3091 }
3092
3093 return oa_regs;
3094
3095addr_err:
3096 kfree(oa_regs);
3097 return ERR_PTR(err);
3098}
3099
3100static ssize_t show_dynamic_id(struct device *dev,
3101 struct device_attribute *attr,
3102 char *buf)
3103{
3104 struct i915_oa_config *oa_config =
3105 container_of(attr, typeof(*oa_config), sysfs_metric_id);
3106
3107 return sprintf(buf, "%d\n", oa_config->id);
3108}
3109
3110static int create_dynamic_oa_sysfs_entry(struct drm_i915_private *dev_priv,
3111 struct i915_oa_config *oa_config)
3112{
Chris Wilson28152a22017-08-03 23:37:00 +01003113 sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003114 oa_config->sysfs_metric_id.attr.name = "id";
3115 oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
3116 oa_config->sysfs_metric_id.show = show_dynamic_id;
3117 oa_config->sysfs_metric_id.store = NULL;
3118
3119 oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
3120 oa_config->attrs[1] = NULL;
3121
3122 oa_config->sysfs_metric.name = oa_config->uuid;
3123 oa_config->sysfs_metric.attrs = oa_config->attrs;
3124
3125 return sysfs_create_group(dev_priv->perf.metrics_kobj,
3126 &oa_config->sysfs_metric);
3127}
3128
3129/**
3130 * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
3131 * @dev: drm device
3132 * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
3133 * userspace (unvalidated)
3134 * @file: drm file
3135 *
3136 * Validates the submitted OA register to be saved into a new OA config that
3137 * can then be used for programming the OA unit and its NOA network.
3138 *
3139 * Returns: A new allocated config number to be used with the perf open ioctl
3140 * or a negative error code on failure.
3141 */
3142int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
3143 struct drm_file *file)
3144{
3145 struct drm_i915_private *dev_priv = dev->dev_private;
3146 struct drm_i915_perf_oa_config *args = data;
3147 struct i915_oa_config *oa_config, *tmp;
3148 int err, id;
3149
3150 if (!dev_priv->perf.initialized) {
3151 DRM_DEBUG("i915 perf interface not available for this system\n");
3152 return -ENOTSUPP;
3153 }
3154
3155 if (!dev_priv->perf.metrics_kobj) {
3156 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
3157 return -EINVAL;
3158 }
3159
3160 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3161 DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
3162 return -EACCES;
3163 }
3164
3165 if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
3166 (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
3167 (!args->flex_regs_ptr || !args->n_flex_regs)) {
3168 DRM_DEBUG("No OA registers given\n");
3169 return -EINVAL;
3170 }
3171
3172 oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
3173 if (!oa_config) {
3174 DRM_DEBUG("Failed to allocate memory for the OA config\n");
3175 return -ENOMEM;
3176 }
3177
3178 atomic_set(&oa_config->ref_count, 1);
3179
3180 if (!uuid_is_valid(args->uuid)) {
3181 DRM_DEBUG("Invalid uuid format for OA config\n");
3182 err = -EINVAL;
3183 goto reg_err;
3184 }
3185
3186 /* Last character in oa_config->uuid will be 0 because oa_config is
3187 * kzalloc.
3188 */
3189 memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
3190
3191 oa_config->mux_regs_len = args->n_mux_regs;
3192 oa_config->mux_regs =
3193 alloc_oa_regs(dev_priv,
3194 dev_priv->perf.oa.ops.is_valid_mux_reg,
3195 u64_to_user_ptr(args->mux_regs_ptr),
3196 args->n_mux_regs);
3197
3198 if (IS_ERR(oa_config->mux_regs)) {
3199 DRM_DEBUG("Failed to create OA config for mux_regs\n");
3200 err = PTR_ERR(oa_config->mux_regs);
3201 goto reg_err;
3202 }
3203
3204 oa_config->b_counter_regs_len = args->n_boolean_regs;
3205 oa_config->b_counter_regs =
3206 alloc_oa_regs(dev_priv,
3207 dev_priv->perf.oa.ops.is_valid_b_counter_reg,
3208 u64_to_user_ptr(args->boolean_regs_ptr),
3209 args->n_boolean_regs);
3210
3211 if (IS_ERR(oa_config->b_counter_regs)) {
3212 DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
3213 err = PTR_ERR(oa_config->b_counter_regs);
3214 goto reg_err;
3215 }
3216
3217 if (INTEL_GEN(dev_priv) < 8) {
3218 if (args->n_flex_regs != 0) {
3219 err = -EINVAL;
3220 goto reg_err;
3221 }
3222 } else {
3223 oa_config->flex_regs_len = args->n_flex_regs;
3224 oa_config->flex_regs =
3225 alloc_oa_regs(dev_priv,
3226 dev_priv->perf.oa.ops.is_valid_flex_reg,
3227 u64_to_user_ptr(args->flex_regs_ptr),
3228 args->n_flex_regs);
3229
3230 if (IS_ERR(oa_config->flex_regs)) {
3231 DRM_DEBUG("Failed to create OA config for flex_regs\n");
3232 err = PTR_ERR(oa_config->flex_regs);
3233 goto reg_err;
3234 }
3235 }
3236
3237 err = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
3238 if (err)
3239 goto reg_err;
3240
3241 /* We shouldn't have too many configs, so this iteration shouldn't be
3242 * too costly.
3243 */
3244 idr_for_each_entry(&dev_priv->perf.metrics_idr, tmp, id) {
3245 if (!strcmp(tmp->uuid, oa_config->uuid)) {
3246 DRM_DEBUG("OA config already exists with this uuid\n");
3247 err = -EADDRINUSE;
3248 goto sysfs_err;
3249 }
3250 }
3251
3252 err = create_dynamic_oa_sysfs_entry(dev_priv, oa_config);
3253 if (err) {
3254 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3255 goto sysfs_err;
3256 }
3257
3258 /* Config id 0 is invalid, id 1 for kernel stored test config. */
3259 oa_config->id = idr_alloc(&dev_priv->perf.metrics_idr,
3260 oa_config, 2,
3261 0, GFP_KERNEL);
3262 if (oa_config->id < 0) {
3263 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3264 err = oa_config->id;
3265 goto sysfs_err;
3266 }
3267
3268 mutex_unlock(&dev_priv->perf.metrics_lock);
3269
3270 return oa_config->id;
3271
3272sysfs_err:
3273 mutex_unlock(&dev_priv->perf.metrics_lock);
3274reg_err:
3275 put_oa_config(dev_priv, oa_config);
3276 DRM_DEBUG("Failed to add new OA config\n");
3277 return err;
3278}
3279
3280/**
3281 * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
3282 * @dev: drm device
3283 * @data: ioctl data (pointer to u64 integer) copied from userspace
3284 * @file: drm file
3285 *
3286 * Configs can be removed while being used, the will stop appearing in sysfs
3287 * and their content will be freed when the stream using the config is closed.
3288 *
3289 * Returns: 0 on success or a negative error code on failure.
3290 */
3291int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
3292 struct drm_file *file)
3293{
3294 struct drm_i915_private *dev_priv = dev->dev_private;
3295 u64 *arg = data;
3296 struct i915_oa_config *oa_config;
3297 int ret;
3298
3299 if (!dev_priv->perf.initialized) {
3300 DRM_DEBUG("i915 perf interface not available for this system\n");
3301 return -ENOTSUPP;
3302 }
3303
3304 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3305 DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
3306 return -EACCES;
3307 }
3308
3309 ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
3310 if (ret)
3311 goto lock_err;
3312
3313 oa_config = idr_find(&dev_priv->perf.metrics_idr, *arg);
3314 if (!oa_config) {
3315 DRM_DEBUG("Failed to remove unknown OA config\n");
3316 ret = -ENOENT;
3317 goto config_err;
3318 }
3319
3320 GEM_BUG_ON(*arg != oa_config->id);
3321
3322 sysfs_remove_group(dev_priv->perf.metrics_kobj,
3323 &oa_config->sysfs_metric);
3324
3325 idr_remove(&dev_priv->perf.metrics_idr, *arg);
3326 put_oa_config(dev_priv, oa_config);
3327
3328config_err:
3329 mutex_unlock(&dev_priv->perf.metrics_lock);
3330lock_err:
3331 return ret;
3332}
3333
Robert Braggccdf6342016-11-07 19:49:54 +00003334static struct ctl_table oa_table[] = {
3335 {
3336 .procname = "perf_stream_paranoid",
3337 .data = &i915_perf_stream_paranoid,
3338 .maxlen = sizeof(i915_perf_stream_paranoid),
3339 .mode = 0644,
3340 .proc_handler = proc_dointvec_minmax,
3341 .extra1 = &zero,
3342 .extra2 = &one,
3343 },
Robert Bragg00319ba2016-11-07 19:49:55 +00003344 {
3345 .procname = "oa_max_sample_rate",
3346 .data = &i915_oa_max_sample_rate,
3347 .maxlen = sizeof(i915_oa_max_sample_rate),
3348 .mode = 0644,
3349 .proc_handler = proc_dointvec_minmax,
3350 .extra1 = &zero,
3351 .extra2 = &oa_sample_rate_hard_limit,
3352 },
Robert Braggccdf6342016-11-07 19:49:54 +00003353 {}
3354};
3355
3356static struct ctl_table i915_root[] = {
3357 {
3358 .procname = "i915",
3359 .maxlen = 0,
3360 .mode = 0555,
3361 .child = oa_table,
3362 },
3363 {}
3364};
3365
3366static struct ctl_table dev_root[] = {
3367 {
3368 .procname = "dev",
3369 .maxlen = 0,
3370 .mode = 0555,
3371 .child = i915_root,
3372 },
3373 {}
3374};
3375
Robert Bragg16d98b32016-12-07 21:40:33 +00003376/**
3377 * i915_perf_init - initialize i915-perf state on module load
3378 * @dev_priv: i915 device instance
3379 *
3380 * Initializes i915-perf state without exposing anything to userspace.
3381 *
3382 * Note: i915-perf initialization is split into an 'init' and 'register'
3383 * phase with the i915_perf_register() exposing state to userspace.
3384 */
Robert Braggeec688e2016-11-07 19:49:47 +00003385void i915_perf_init(struct drm_i915_private *dev_priv)
3386{
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003387 dev_priv->perf.oa.timestamp_frequency = 0;
Robert Braggd7965152016-11-07 19:49:52 +00003388
Robert Bragg19f81df2017-06-13 12:23:03 +01003389 if (IS_HASWELL(dev_priv)) {
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003390 dev_priv->perf.oa.ops.is_valid_b_counter_reg =
3391 gen7_is_valid_b_counter_addr;
3392 dev_priv->perf.oa.ops.is_valid_mux_reg =
3393 hsw_is_valid_mux_addr;
3394 dev_priv->perf.oa.ops.is_valid_flex_reg = NULL;
Robert Bragg19f81df2017-06-13 12:23:03 +01003395 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
3396 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
3397 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
3398 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
3399 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
3400 dev_priv->perf.oa.ops.read = gen7_oa_read;
3401 dev_priv->perf.oa.ops.oa_hw_tail_read =
3402 gen7_oa_hw_tail_read;
Robert Braggd7965152016-11-07 19:49:52 +00003403
Robert Bragg155e9412017-06-13 12:23:05 +01003404 dev_priv->perf.oa.timestamp_frequency = 12500000;
3405
Robert Bragg19f81df2017-06-13 12:23:03 +01003406 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
Robert Bragg19f81df2017-06-13 12:23:03 +01003407 } else if (i915.enable_execlists) {
3408 /* Note: that although we could theoretically also support the
3409 * legacy ringbuffer mode on BDW (and earlier iterations of
3410 * this driver, before upstreaming did this) it didn't seem
3411 * worth the complexity to maintain now that BDW+ enable
3412 * execlist mode by default.
3413 */
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003414 dev_priv->perf.oa.ops.is_valid_b_counter_reg =
3415 gen7_is_valid_b_counter_addr;
3416 dev_priv->perf.oa.ops.is_valid_mux_reg =
3417 gen8_is_valid_mux_addr;
3418 dev_priv->perf.oa.ops.is_valid_flex_reg =
3419 gen8_is_valid_flex_addr;
Robert Braggd7965152016-11-07 19:49:52 +00003420
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003421 dev_priv->perf.oa.ops.init_oa_buffer = gen8_init_oa_buffer;
3422 dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set;
3423 dev_priv->perf.oa.ops.disable_metric_set = gen8_disable_metric_set;
3424 dev_priv->perf.oa.ops.oa_enable = gen8_oa_enable;
3425 dev_priv->perf.oa.ops.oa_disable = gen8_oa_disable;
3426 dev_priv->perf.oa.ops.read = gen8_oa_read;
3427 dev_priv->perf.oa.ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
3428
3429 dev_priv->perf.oa.oa_formats = gen8_plus_oa_formats;
3430
Robert Bragg19f81df2017-06-13 12:23:03 +01003431 if (IS_GEN8(dev_priv)) {
3432 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x120;
3433 dev_priv->perf.oa.ctx_flexeu0_offset = 0x2ce;
Robert Bragg155e9412017-06-13 12:23:05 +01003434
3435 dev_priv->perf.oa.timestamp_frequency = 12500000;
3436
Robert Bragg19f81df2017-06-13 12:23:03 +01003437 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<25);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003438 if (IS_CHERRYVIEW(dev_priv)) {
3439 dev_priv->perf.oa.ops.is_valid_mux_reg =
3440 chv_is_valid_mux_addr;
3441 }
Robert Bragg19f81df2017-06-13 12:23:03 +01003442 } else if (IS_GEN9(dev_priv)) {
3443 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
3444 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
Robert Bragg155e9412017-06-13 12:23:05 +01003445
Robert Bragg19f81df2017-06-13 12:23:03 +01003446 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
Robert Braggeec688e2016-11-07 19:49:47 +00003447
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003448 switch (dev_priv->info.platform) {
3449 case INTEL_BROXTON:
3450 case INTEL_GEMINILAKE:
Robert Bragg155e9412017-06-13 12:23:05 +01003451 dev_priv->perf.oa.timestamp_frequency = 19200000;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003452 break;
3453 case INTEL_SKYLAKE:
3454 case INTEL_KABYLAKE:
3455 dev_priv->perf.oa.timestamp_frequency = 12000000;
3456 break;
3457 default:
3458 /* Leave timestamp_frequency to 0 so we can
3459 * detect unsupported platforms.
3460 */
3461 break;
Robert Bragg19f81df2017-06-13 12:23:03 +01003462 }
3463 }
Robert Bragg19f81df2017-06-13 12:23:03 +01003464 }
3465
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003466 if (dev_priv->perf.oa.timestamp_frequency) {
Robert Bragg19f81df2017-06-13 12:23:03 +01003467 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
3468 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3469 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
3470 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
3471
3472 INIT_LIST_HEAD(&dev_priv->perf.streams);
3473 mutex_init(&dev_priv->perf.lock);
Robert Bragg19f81df2017-06-13 12:23:03 +01003474 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
3475
Robert Bragg155e9412017-06-13 12:23:05 +01003476 oa_sample_rate_hard_limit =
3477 dev_priv->perf.oa.timestamp_frequency / 2;
Robert Bragg19f81df2017-06-13 12:23:03 +01003478 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
3479
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003480 mutex_init(&dev_priv->perf.metrics_lock);
3481 idr_init(&dev_priv->perf.metrics_idr);
3482
Robert Bragg19f81df2017-06-13 12:23:03 +01003483 dev_priv->perf.initialized = true;
3484 }
Robert Braggeec688e2016-11-07 19:49:47 +00003485}
3486
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003487static int destroy_config(int id, void *p, void *data)
3488{
3489 struct drm_i915_private *dev_priv = data;
3490 struct i915_oa_config *oa_config = p;
3491
3492 put_oa_config(dev_priv, oa_config);
3493
3494 return 0;
3495}
3496
Robert Bragg16d98b32016-12-07 21:40:33 +00003497/**
3498 * i915_perf_fini - Counter part to i915_perf_init()
3499 * @dev_priv: i915 device instance
3500 */
Robert Braggeec688e2016-11-07 19:49:47 +00003501void i915_perf_fini(struct drm_i915_private *dev_priv)
3502{
3503 if (!dev_priv->perf.initialized)
3504 return;
3505
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003506 idr_for_each(&dev_priv->perf.metrics_idr, destroy_config, dev_priv);
3507 idr_destroy(&dev_priv->perf.metrics_idr);
3508
Robert Braggccdf6342016-11-07 19:49:54 +00003509 unregister_sysctl_table(dev_priv->perf.sysctl_header);
3510
Robert Braggd7965152016-11-07 19:49:52 +00003511 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Bragg19f81df2017-06-13 12:23:03 +01003512
Robert Braggeec688e2016-11-07 19:49:47 +00003513 dev_priv->perf.initialized = false;
3514}