blob: e0fcb982a14f31e1a1ab933a1d18e75473921ed5 [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"
Lionel Landwerlin22ea4f32017-09-18 12:21:24 +0100209#include "i915_oa_cflgt2.h"
Lionel Landwerlin4407eaa2017-11-10 19:08:40 +0000210#include "i915_oa_cflgt3.h"
Lionel Landwerlin95690a02017-11-10 19:08:43 +0000211#include "i915_oa_cnl.h"
Lionel Landwerlin1de401c2018-03-26 14:39:48 +0100212#include "i915_oa_icl.h"
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +0100213#include "intel_lrc_reg.h"
Robert Braggd7965152016-11-07 19:49:52 +0000214
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200215/* HW requires this to be a power of two, between 128k and 16M, though driver
216 * is currently generally designed assuming the largest 16M size is used such
217 * that the overflow cases are unlikely in normal operation.
218 */
219#define OA_BUFFER_SIZE SZ_16M
220
221#define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
Robert Braggd7965152016-11-07 19:49:52 +0000222
Robert Bragg0dd860c2017-05-11 16:43:28 +0100223/**
224 * DOC: OA Tail Pointer Race
225 *
226 * There's a HW race condition between OA unit tail pointer register updates and
Robert Braggd7965152016-11-07 19:49:52 +0000227 * writes to memory whereby the tail pointer can sometimes get ahead of what's
Robert Bragg0dd860c2017-05-11 16:43:28 +0100228 * been written out to the OA buffer so far (in terms of what's visible to the
229 * CPU).
Robert Braggd7965152016-11-07 19:49:52 +0000230 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100231 * Although this can be observed explicitly while copying reports to userspace
232 * by checking for a zeroed report-id field in tail reports, we want to account
Robert Bragg19f81df2017-06-13 12:23:03 +0100233 * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
Robert Bragg0dd860c2017-05-11 16:43:28 +0100234 * read() attempts.
Robert Braggd7965152016-11-07 19:49:52 +0000235 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100236 * In effect we define a tail pointer for reading that lags the real tail
237 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
238 * time for the corresponding reports to become visible to the CPU.
Robert Braggd7965152016-11-07 19:49:52 +0000239 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100240 * To manage this we actually track two tail pointers:
241 * 1) An 'aging' tail with an associated timestamp that is tracked until we
242 * can trust the corresponding data is visible to the CPU; at which point
243 * it is considered 'aged'.
244 * 2) An 'aged' tail that can be used for read()ing.
245 *
246 * The two separate pointers let us decouple read()s from tail pointer aging.
247 *
248 * The tail pointers are checked and updated at a limited rate within a hrtimer
Linus Torvaldsa9a08842018-02-11 14:34:03 -0800249 * callback (the same callback that is used for delivering EPOLLIN events)
Robert Bragg0dd860c2017-05-11 16:43:28 +0100250 *
251 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
252 * indicates that an updated tail pointer is needed.
253 *
254 * Most of the implementation details for this workaround are in
Robert Bragg19f81df2017-06-13 12:23:03 +0100255 * oa_buffer_check_unlocked() and _append_oa_reports()
Robert Bragg0dd860c2017-05-11 16:43:28 +0100256 *
257 * Note for posterity: previously the driver used to define an effective tail
258 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
259 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
260 * This was flawed considering that the OA unit may also automatically generate
261 * non-periodic reports (such as on context switch) or the OA unit may be
262 * enabled without any periodic sampling.
Robert Braggd7965152016-11-07 19:49:52 +0000263 */
264#define OA_TAIL_MARGIN_NSEC 100000ULL
Robert Bragg0dd860c2017-05-11 16:43:28 +0100265#define INVALID_TAIL_PTR 0xffffffff
Robert Braggd7965152016-11-07 19:49:52 +0000266
267/* frequency for checking whether the OA unit has written new reports to the
268 * circular OA buffer...
269 */
270#define POLL_FREQUENCY 200
271#define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
272
Robert Braggccdf6342016-11-07 19:49:54 +0000273/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
274static int zero;
275static int one = 1;
276static u32 i915_perf_stream_paranoid = true;
277
Robert Braggd7965152016-11-07 19:49:52 +0000278/* The maximum exponent the hardware accepts is 63 (essentially it selects one
279 * of the 64bit timestamp bits to trigger reports from) but there's currently
280 * no known use case for sampling as infrequently as once per 47 thousand years.
281 *
282 * Since the timestamps included in OA reports are only 32bits it seems
283 * reasonable to limit the OA exponent where it's still possible to account for
284 * overflow in OA report timestamps.
285 */
286#define OA_EXPONENT_MAX 31
287
288#define INVALID_CTX_ID 0xffffffff
289
Robert Bragg19f81df2017-06-13 12:23:03 +0100290/* On Gen8+ automatically triggered OA reports include a 'reason' field... */
291#define OAREPORT_REASON_MASK 0x3f
292#define OAREPORT_REASON_SHIFT 19
293#define OAREPORT_REASON_TIMER (1<<0)
294#define OAREPORT_REASON_CTX_SWITCH (1<<3)
295#define OAREPORT_REASON_CLK_RATIO (1<<5)
296
Robert Braggd7965152016-11-07 19:49:52 +0000297
Robert Bragg00319ba2016-11-07 19:49:55 +0000298/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
299 *
Robert Bragg155e9412017-06-13 12:23:05 +0100300 * The highest sampling frequency we can theoretically program the OA unit
301 * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
302 *
303 * Initialized just before we register the sysctl parameter.
Robert Bragg00319ba2016-11-07 19:49:55 +0000304 */
Robert Bragg155e9412017-06-13 12:23:05 +0100305static int oa_sample_rate_hard_limit;
Robert Bragg00319ba2016-11-07 19:49:55 +0000306
307/* Theoretically we can program the OA unit to sample every 160ns but don't
308 * allow that by default unless root...
309 *
310 * The default threshold of 100000Hz is based on perf's similar
311 * kernel.perf_event_max_sample_rate sysctl parameter.
312 */
313static u32 i915_oa_max_sample_rate = 100000;
314
Robert Braggd7965152016-11-07 19:49:52 +0000315/* XXX: beware if future OA HW adds new report formats that the current
316 * code assumes all reports have a power-of-two size and ~(size - 1) can
317 * be used as a mask to align the OA tail pointer.
318 */
Jani Nikula6ebb6d82018-06-13 14:49:29 +0300319static const struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
Robert Braggd7965152016-11-07 19:49:52 +0000320 [I915_OA_FORMAT_A13] = { 0, 64 },
321 [I915_OA_FORMAT_A29] = { 1, 128 },
322 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
323 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
324 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
325 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
326 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
327 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
328};
329
Jani Nikula6ebb6d82018-06-13 14:49:29 +0300330static const struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
Robert Bragg19f81df2017-06-13 12:23:03 +0100331 [I915_OA_FORMAT_A12] = { 0, 64 },
332 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
333 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
334 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
335};
336
Robert Braggd7965152016-11-07 19:49:52 +0000337#define SAMPLE_OA_REPORT (1<<0)
Robert Braggeec688e2016-11-07 19:49:47 +0000338
Robert Bragg16d98b32016-12-07 21:40:33 +0000339/**
340 * struct perf_open_properties - for validated properties given to open a stream
341 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
342 * @single_context: Whether a single or all gpu contexts should be monitored
343 * @ctx_handle: A gem ctx handle for use with @single_context
344 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
345 * @oa_format: An OA unit HW report format
346 * @oa_periodic: Whether to enable periodic OA unit sampling
347 * @oa_period_exponent: The OA unit sampling period is derived from this
348 *
349 * As read_properties_unlocked() enumerates and validates the properties given
350 * to open a stream of metrics the configuration is built up in the structure
351 * which starts out zero initialized.
352 */
Robert Braggeec688e2016-11-07 19:49:47 +0000353struct perf_open_properties {
354 u32 sample_flags;
355
356 u64 single_context:1;
357 u64 ctx_handle;
Robert Braggd7965152016-11-07 19:49:52 +0000358
359 /* OA sampling state */
360 int metrics_set;
361 int oa_format;
362 bool oa_periodic;
363 int oa_period_exponent;
Robert Braggeec688e2016-11-07 19:49:47 +0000364};
365
Lionel Landwerlinf89823c2017-08-03 18:05:50 +0100366static void free_oa_config(struct drm_i915_private *dev_priv,
367 struct i915_oa_config *oa_config)
368{
369 if (!PTR_ERR(oa_config->flex_regs))
370 kfree(oa_config->flex_regs);
371 if (!PTR_ERR(oa_config->b_counter_regs))
372 kfree(oa_config->b_counter_regs);
373 if (!PTR_ERR(oa_config->mux_regs))
374 kfree(oa_config->mux_regs);
375 kfree(oa_config);
376}
377
378static void put_oa_config(struct drm_i915_private *dev_priv,
379 struct i915_oa_config *oa_config)
380{
381 if (!atomic_dec_and_test(&oa_config->ref_count))
382 return;
383
384 free_oa_config(dev_priv, oa_config);
385}
386
387static int get_oa_config(struct drm_i915_private *dev_priv,
388 int metrics_set,
389 struct i915_oa_config **out_config)
390{
391 int ret;
392
393 if (metrics_set == 1) {
394 *out_config = &dev_priv->perf.oa.test_config;
395 atomic_inc(&dev_priv->perf.oa.test_config.ref_count);
396 return 0;
397 }
398
399 ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
400 if (ret)
401 return ret;
402
403 *out_config = idr_find(&dev_priv->perf.metrics_idr, metrics_set);
404 if (!*out_config)
405 ret = -EINVAL;
406 else
407 atomic_inc(&(*out_config)->ref_count);
408
409 mutex_unlock(&dev_priv->perf.metrics_lock);
410
411 return ret;
412}
413
Robert Bragg19f81df2017-06-13 12:23:03 +0100414static u32 gen8_oa_hw_tail_read(struct drm_i915_private *dev_priv)
415{
416 return I915_READ(GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
417}
418
419static u32 gen7_oa_hw_tail_read(struct drm_i915_private *dev_priv)
420{
421 u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
422
423 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
424}
425
Robert Bragg0dd860c2017-05-11 16:43:28 +0100426/**
Robert Bragg19f81df2017-06-13 12:23:03 +0100427 * oa_buffer_check_unlocked - check for data and update tail ptr state
Robert Bragg0dd860c2017-05-11 16:43:28 +0100428 * @dev_priv: i915 device instance
Robert Braggd7965152016-11-07 19:49:52 +0000429 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100430 * This is either called via fops (for blocking reads in user ctx) or the poll
431 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
432 * if there is data available for userspace to read.
Robert Braggd7965152016-11-07 19:49:52 +0000433 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100434 * This function is central to providing a workaround for the OA unit tail
435 * pointer having a race with respect to what data is visible to the CPU.
436 * It is responsible for reading tail pointers from the hardware and giving
437 * the pointers time to 'age' before they are made available for reading.
438 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
439 *
440 * Besides returning true when there is data available to read() this function
441 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
442 * and .aged_tail_idx state used for reading.
443 *
444 * Note: It's safe to read OA config state here unlocked, assuming that this is
445 * only called while the stream is enabled, while the global OA configuration
446 * can't be modified.
447 *
448 * Returns: %true if the OA buffer contains data, else %false
Robert Braggd7965152016-11-07 19:49:52 +0000449 */
Robert Bragg19f81df2017-06-13 12:23:03 +0100450static bool oa_buffer_check_unlocked(struct drm_i915_private *dev_priv)
Robert Braggd7965152016-11-07 19:49:52 +0000451{
452 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100453 unsigned long flags;
454 unsigned int aged_idx;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100455 u32 head, hw_tail, aged_tail, aging_tail;
456 u64 now;
Robert Braggd7965152016-11-07 19:49:52 +0000457
Robert Bragg0dd860c2017-05-11 16:43:28 +0100458 /* We have to consider the (unlikely) possibility that read() errors
459 * could result in an OA buffer reset which might reset the head,
460 * tails[] and aged_tail state.
461 */
462 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
463
464 /* NB: The head we observe here might effectively be a little out of
465 * date (between head and tails[aged_idx].offset if there is currently
466 * a read() in progress.
467 */
468 head = dev_priv->perf.oa.oa_buffer.head;
469
470 aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
471 aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset;
472 aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset;
473
Robert Bragg19f81df2017-06-13 12:23:03 +0100474 hw_tail = dev_priv->perf.oa.ops.oa_hw_tail_read(dev_priv);
Robert Bragg0dd860c2017-05-11 16:43:28 +0100475
476 /* The tail pointer increases in 64 byte increments,
477 * not in report_size steps...
478 */
479 hw_tail &= ~(report_size - 1);
480
481 now = ktime_get_mono_fast_ns();
482
Robert Bragg4117ebc2017-05-11 16:43:30 +0100483 /* Update the aged tail
484 *
485 * Flip the tail pointer available for read()s once the aging tail is
486 * old enough to trust that the corresponding data will be visible to
487 * the CPU...
488 *
489 * Do this before updating the aging pointer in case we may be able to
490 * immediately start aging a new pointer too (if new data has become
491 * available) without needing to wait for a later hrtimer callback.
492 */
493 if (aging_tail != INVALID_TAIL_PTR &&
494 ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) >
495 OA_TAIL_MARGIN_NSEC)) {
Robert Bragg19f81df2017-06-13 12:23:03 +0100496
Robert Bragg4117ebc2017-05-11 16:43:30 +0100497 aged_idx ^= 1;
498 dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx;
499
500 aged_tail = aging_tail;
501
502 /* Mark that we need a new pointer to start aging... */
503 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
504 aging_tail = INVALID_TAIL_PTR;
505 }
506
Robert Bragg0dd860c2017-05-11 16:43:28 +0100507 /* Update the aging tail
508 *
509 * We throttle aging tail updates until we have a new tail that
510 * represents >= one report more data than is already available for
511 * reading. This ensures there will be enough data for a successful
512 * read once this new pointer has aged and ensures we will give the new
513 * pointer time to age.
514 */
515 if (aging_tail == INVALID_TAIL_PTR &&
516 (aged_tail == INVALID_TAIL_PTR ||
517 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
518 struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma;
519 u32 gtt_offset = i915_ggtt_offset(vma);
520
521 /* Be paranoid and do a bounds check on the pointer read back
522 * from hardware, just in case some spurious hardware condition
523 * could put the tail out of bounds...
524 */
525 if (hw_tail >= gtt_offset &&
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200526 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
Robert Bragg0dd860c2017-05-11 16:43:28 +0100527 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset =
528 aging_tail = hw_tail;
529 dev_priv->perf.oa.oa_buffer.aging_timestamp = now;
530 } else {
531 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
532 hw_tail);
533 }
534 }
535
Robert Bragg0dd860c2017-05-11 16:43:28 +0100536 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
537
538 return aged_tail == INVALID_TAIL_PTR ?
539 false : OA_TAKEN(aged_tail, head) >= report_size;
Robert Braggd7965152016-11-07 19:49:52 +0000540}
541
542/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000543 * append_oa_status - Appends a status record to a userspace read() buffer.
544 * @stream: An i915-perf stream opened for OA metrics
545 * @buf: destination buffer given by userspace
546 * @count: the number of bytes userspace wants to read
547 * @offset: (inout): the current position for writing into @buf
548 * @type: The kind of status to report to userspace
549 *
550 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
551 * into the userspace read() buffer.
552 *
553 * The @buf @offset will only be updated on success.
554 *
555 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000556 */
557static int append_oa_status(struct i915_perf_stream *stream,
558 char __user *buf,
559 size_t count,
560 size_t *offset,
561 enum drm_i915_perf_record_type type)
562{
563 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
564
565 if ((count - *offset) < header.size)
566 return -ENOSPC;
567
568 if (copy_to_user(buf + *offset, &header, sizeof(header)))
569 return -EFAULT;
570
571 (*offset) += header.size;
572
573 return 0;
574}
575
576/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000577 * append_oa_sample - Copies single OA report into userspace read() buffer.
578 * @stream: An i915-perf stream opened for OA metrics
579 * @buf: destination buffer given by userspace
580 * @count: the number of bytes userspace wants to read
581 * @offset: (inout): the current position for writing into @buf
582 * @report: A single OA report to (optionally) include as part of the sample
583 *
584 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
585 * properties when opening a stream, tracked as `stream->sample_flags`. This
586 * function copies the requested components of a single sample to the given
587 * read() @buf.
588 *
589 * The @buf @offset will only be updated on success.
590 *
591 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000592 */
593static int append_oa_sample(struct i915_perf_stream *stream,
594 char __user *buf,
595 size_t count,
596 size_t *offset,
597 const u8 *report)
598{
599 struct drm_i915_private *dev_priv = stream->dev_priv;
600 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
601 struct drm_i915_perf_record_header header;
602 u32 sample_flags = stream->sample_flags;
603
604 header.type = DRM_I915_PERF_RECORD_SAMPLE;
605 header.pad = 0;
606 header.size = stream->sample_size;
607
608 if ((count - *offset) < header.size)
609 return -ENOSPC;
610
611 buf += *offset;
612 if (copy_to_user(buf, &header, sizeof(header)))
613 return -EFAULT;
614 buf += sizeof(header);
615
616 if (sample_flags & SAMPLE_OA_REPORT) {
617 if (copy_to_user(buf, report, report_size))
618 return -EFAULT;
619 }
620
621 (*offset) += header.size;
622
623 return 0;
624}
625
626/**
627 * Copies all buffered OA reports into userspace read() buffer.
628 * @stream: An i915-perf stream opened for OA metrics
629 * @buf: destination buffer given by userspace
630 * @count: the number of bytes userspace wants to read
631 * @offset: (inout): the current position for writing into @buf
Robert Braggd7965152016-11-07 19:49:52 +0000632 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000633 * Notably any error condition resulting in a short read (-%ENOSPC or
634 * -%EFAULT) will be returned even though one or more records may
Robert Braggd7965152016-11-07 19:49:52 +0000635 * have been successfully copied. In this case it's up to the caller
636 * to decide if the error should be squashed before returning to
637 * userspace.
638 *
639 * Note: reports are consumed from the head, and appended to the
Robert Bragge81b3a52017-05-11 16:43:24 +0100640 * tail, so the tail chases the head?... If you think that's mad
Robert Braggd7965152016-11-07 19:49:52 +0000641 * and back-to-front you're not alone, but this follows the
642 * Gen PRM naming convention.
Robert Bragg16d98b32016-12-07 21:40:33 +0000643 *
644 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000645 */
Robert Bragg19f81df2017-06-13 12:23:03 +0100646static int gen8_append_oa_reports(struct i915_perf_stream *stream,
647 char __user *buf,
648 size_t count,
649 size_t *offset)
650{
651 struct drm_i915_private *dev_priv = stream->dev_priv;
652 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
653 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
654 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200655 u32 mask = (OA_BUFFER_SIZE - 1);
Robert Bragg19f81df2017-06-13 12:23:03 +0100656 size_t start_offset = *offset;
657 unsigned long flags;
658 unsigned int aged_tail_idx;
659 u32 head, tail;
660 u32 taken;
661 int ret = 0;
662
663 if (WARN_ON(!stream->enabled))
664 return -EIO;
665
666 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
667
668 head = dev_priv->perf.oa.oa_buffer.head;
669 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
670 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
671
672 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
673
674 /*
675 * An invalid tail pointer here means we're still waiting for the poll
676 * hrtimer callback to give us a pointer
677 */
678 if (tail == INVALID_TAIL_PTR)
679 return -EAGAIN;
680
681 /*
682 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
683 * while indexing relative to oa_buf_base.
684 */
685 head -= gtt_offset;
686 tail -= gtt_offset;
687
688 /*
689 * An out of bounds or misaligned head or tail pointer implies a driver
690 * bug since we validate + align the tail pointers we read from the
691 * hardware and we are in full control of the head pointer which should
692 * only be incremented by multiples of the report size (notably also
693 * all a power of two).
694 */
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200695 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
696 tail > OA_BUFFER_SIZE || tail % report_size,
Robert Bragg19f81df2017-06-13 12:23:03 +0100697 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
698 head, tail))
699 return -EIO;
700
701
702 for (/* none */;
703 (taken = OA_TAKEN(tail, head));
704 head = (head + report_size) & mask) {
705 u8 *report = oa_buf_base + head;
706 u32 *report32 = (void *)report;
707 u32 ctx_id;
708 u32 reason;
709
710 /*
711 * All the report sizes factor neatly into the buffer
712 * size so we never expect to see a report split
713 * between the beginning and end of the buffer.
714 *
715 * Given the initial alignment check a misalignment
716 * here would imply a driver bug that would result
717 * in an overrun.
718 */
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200719 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
Robert Bragg19f81df2017-06-13 12:23:03 +0100720 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
721 break;
722 }
723
724 /*
725 * The reason field includes flags identifying what
726 * triggered this specific report (mostly timer
727 * triggered or e.g. due to a context switch).
728 *
729 * This field is never expected to be zero so we can
730 * check that the report isn't invalid before copying
731 * it to userspace...
732 */
733 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
734 OAREPORT_REASON_MASK);
735 if (reason == 0) {
736 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
737 DRM_NOTE("Skipping spurious, invalid OA report\n");
738 continue;
739 }
740
Lionel Landwerlin61d56762018-06-02 12:29:46 +0100741 ctx_id = report32[2] & dev_priv->perf.oa.specific_ctx_id_mask;
Robert Bragg19f81df2017-06-13 12:23:03 +0100742
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.
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200878 *
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.
Robert Bragg19f81df2017-06-13 12:23:03 +0100883 */
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
Lionel Landwerlin5728de22018-10-23 11:07:06 +0100893 dev_priv->perf.oa.ops.oa_disable(stream);
894 dev_priv->perf.oa.ops.oa_enable(stream);
Robert Bragg19f81df2017-06-13 12:23:03 +0100895
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);
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200944 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 */
Joonas Lahtinenfe841682018-11-16 15:55:09 +0200981 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
982 tail > OA_BUFFER_SIZE || tail % report_size,
Robert Bragg0dd860c2017-05-11 16:43:28 +0100983 "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 */
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001002 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
Robert Braggd7965152016-11-07 19:49:52 +00001003 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) |
Lionel Landwerlinb82ed432018-03-26 10:08:26 +01001042 GEN7_OASTATUS2_MEM_SELECT_GGTT));
Robert Bragg3bb335c2017-05-11 16:43:27 +01001043 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
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001117 dev_priv->perf.oa.ops.oa_disable(stream);
1118 dev_priv->perf.oa.ops.oa_enable(stream);
Robert Braggd7965152016-11-07 19:49:52 +00001119
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
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001202static struct intel_context *oa_pin_context(struct drm_i915_private *i915,
1203 struct i915_gem_context *ctx)
1204{
Chris Wilson8a68d462019-03-05 18:03:30 +00001205 struct intel_engine_cs *engine = i915->engine[RCS0];
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001206 struct intel_context *ce;
1207 int ret;
1208
1209 ret = i915_mutex_lock_interruptible(&i915->drm);
1210 if (ret)
1211 return ERR_PTR(ret);
1212
1213 /*
1214 * As the ID is the gtt offset of the context's vma we
1215 * pin the vma to ensure the ID remains fixed.
1216 *
1217 * NB: implied RCS engine...
1218 */
1219 ce = intel_context_pin(ctx, engine);
1220 mutex_unlock(&i915->drm.struct_mutex);
1221 if (IS_ERR(ce))
1222 return ce;
1223
1224 i915->perf.oa.pinned_ctx = ce;
1225
1226 return ce;
1227}
1228
Robert Bragg16d98b32016-12-07 21:40:33 +00001229/**
1230 * oa_get_render_ctx_id - determine and hold ctx hw id
1231 * @stream: An i915-perf stream opened for OA metrics
1232 *
1233 * Determine the render context hw id, and ensure it remains fixed for the
Robert Braggd7965152016-11-07 19:49:52 +00001234 * lifetime of the stream. This ensures that we don't have to worry about
1235 * updating the context ID in OACONTROL on the fly.
Robert Bragg16d98b32016-12-07 21:40:33 +00001236 *
1237 * Returns: zero on success or a negative error code
Robert Braggd7965152016-11-07 19:49:52 +00001238 */
1239static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1240{
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001241 struct drm_i915_private *i915 = stream->dev_priv;
1242 struct intel_context *ce;
Robert Braggd7965152016-11-07 19:49:52 +00001243
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001244 ce = oa_pin_context(i915, stream->ctx);
1245 if (IS_ERR(ce))
1246 return PTR_ERR(ce);
Robert Braggd7965152016-11-07 19:49:52 +00001247
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001248 switch (INTEL_GEN(i915)) {
1249 case 7: {
Robert Bragg19f81df2017-06-13 12:23:03 +01001250 /*
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001251 * On Haswell we don't do any post processing of the reports
1252 * and don't need to use the mask.
Robert Bragg19f81df2017-06-13 12:23:03 +01001253 */
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001254 i915->perf.oa.specific_ctx_id = i915_ggtt_offset(ce->state);
1255 i915->perf.oa.specific_ctx_id_mask = 0;
1256 break;
Robert Bragg19f81df2017-06-13 12:23:03 +01001257 }
Robert Braggd7965152016-11-07 19:49:52 +00001258
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001259 case 8:
1260 case 9:
1261 case 10:
1262 if (USES_GUC_SUBMISSION(i915)) {
1263 /*
1264 * When using GuC, the context descriptor we write in
1265 * i915 is read by GuC and rewritten before it's
1266 * actually written into the hardware. The LRCA is
1267 * what is put into the context id field of the
1268 * context descriptor by GuC. Because it's aligned to
1269 * a page, the lower 12bits are always at 0 and
1270 * dropped by GuC. They won't be part of the context
1271 * ID in the OA reports, so squash those lower bits.
1272 */
1273 i915->perf.oa.specific_ctx_id =
1274 lower_32_bits(ce->lrc_desc) >> 12;
1275
1276 /*
1277 * GuC uses the top bit to signal proxy submission, so
1278 * ignore that bit.
1279 */
1280 i915->perf.oa.specific_ctx_id_mask =
1281 (1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
1282 } else {
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001283 i915->perf.oa.specific_ctx_id_mask =
1284 (1U << GEN8_CTX_ID_WIDTH) - 1;
Michel Thierry9904b1562018-06-04 16:32:49 -07001285 i915->perf.oa.specific_ctx_id =
1286 upper_32_bits(ce->lrc_desc);
1287 i915->perf.oa.specific_ctx_id &=
1288 i915->perf.oa.specific_ctx_id_mask;
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001289 }
1290 break;
1291
1292 case 11: {
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001293 i915->perf.oa.specific_ctx_id_mask =
1294 ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) << (GEN11_SW_CTX_ID_SHIFT - 32) |
1295 ((1U << GEN11_ENGINE_INSTANCE_WIDTH) - 1) << (GEN11_ENGINE_INSTANCE_SHIFT - 32) |
1296 ((1 << GEN11_ENGINE_CLASS_WIDTH) - 1) << (GEN11_ENGINE_CLASS_SHIFT - 32);
Michel Thierry2b9a8202018-06-04 16:32:50 -07001297 i915->perf.oa.specific_ctx_id = upper_32_bits(ce->lrc_desc);
1298 i915->perf.oa.specific_ctx_id &=
1299 i915->perf.oa.specific_ctx_id_mask;
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001300 break;
1301 }
1302
1303 default:
1304 MISSING_CASE(INTEL_GEN(i915));
1305 }
1306
1307 DRM_DEBUG_DRIVER("filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
1308 i915->perf.oa.specific_ctx_id,
1309 i915->perf.oa.specific_ctx_id_mask);
1310
Chris Wilson266a2402017-05-04 10:33:08 +01001311 return 0;
Robert Braggd7965152016-11-07 19:49:52 +00001312}
1313
Robert Bragg16d98b32016-12-07 21:40:33 +00001314/**
1315 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1316 * @stream: An i915-perf stream opened for OA metrics
1317 *
1318 * In case anything needed doing to ensure the context HW ID would remain valid
1319 * for the lifetime of the stream, then that can be undone here.
1320 */
Robert Braggd7965152016-11-07 19:49:52 +00001321static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1322{
1323 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilson1fc44d92018-05-17 22:26:32 +01001324 struct intel_context *ce;
Robert Braggd7965152016-11-07 19:49:52 +00001325
Chris Wilson1fc44d92018-05-17 22:26:32 +01001326 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
Lionel Landwerlin61d56762018-06-02 12:29:46 +01001327 dev_priv->perf.oa.specific_ctx_id_mask = 0;
Robert Braggd7965152016-11-07 19:49:52 +00001328
Chris Wilson1fc44d92018-05-17 22:26:32 +01001329 ce = fetch_and_zero(&dev_priv->perf.oa.pinned_ctx);
1330 if (ce) {
Robert Bragg19f81df2017-06-13 12:23:03 +01001331 mutex_lock(&dev_priv->drm.struct_mutex);
Chris Wilson1fc44d92018-05-17 22:26:32 +01001332 intel_context_unpin(ce);
Robert Bragg19f81df2017-06-13 12:23:03 +01001333 mutex_unlock(&dev_priv->drm.struct_mutex);
1334 }
Robert Braggd7965152016-11-07 19:49:52 +00001335}
1336
1337static void
1338free_oa_buffer(struct drm_i915_private *i915)
1339{
1340 mutex_lock(&i915->drm.struct_mutex);
1341
Chris Wilson6a2f59e2018-07-21 13:50:37 +01001342 i915_vma_unpin_and_release(&i915->perf.oa.oa_buffer.vma,
1343 I915_VMA_RELEASE_MAP);
Robert Braggd7965152016-11-07 19:49:52 +00001344
1345 mutex_unlock(&i915->drm.struct_mutex);
Chris Wilson6a2f59e2018-07-21 13:50:37 +01001346
1347 i915->perf.oa.oa_buffer.vaddr = NULL;
Robert Braggd7965152016-11-07 19:49:52 +00001348}
1349
1350static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1351{
1352 struct drm_i915_private *dev_priv = stream->dev_priv;
1353
1354 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
1355
Robert Bragg19f81df2017-06-13 12:23:03 +01001356 /*
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01001357 * Unset exclusive_stream first, it will be checked while disabling
1358 * the metric set on gen8+.
Robert Bragg19f81df2017-06-13 12:23:03 +01001359 */
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001360 mutex_lock(&dev_priv->drm.struct_mutex);
Robert Bragg19f81df2017-06-13 12:23:03 +01001361 dev_priv->perf.oa.exclusive_stream = NULL;
Robert Braggd7965152016-11-07 19:49:52 +00001362 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00001363 mutex_unlock(&dev_priv->drm.struct_mutex);
Robert Braggd7965152016-11-07 19:49:52 +00001364
1365 free_oa_buffer(dev_priv);
1366
Daniele Ceraolo Spurio3ceea6a2019-03-19 11:35:36 -07001367 intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
Chris Wilson6619c002019-01-14 14:21:15 +00001368 intel_runtime_pm_put(dev_priv, stream->wakeref);
Robert Braggd7965152016-11-07 19:49:52 +00001369
1370 if (stream->ctx)
1371 oa_put_render_ctx_id(stream);
1372
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01001373 put_oa_config(dev_priv, stream->oa_config);
1374
Robert Bragg712122e2017-05-11 16:43:31 +01001375 if (dev_priv->perf.oa.spurious_report_rs.missed) {
1376 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1377 dev_priv->perf.oa.spurious_report_rs.missed);
1378 }
Robert Braggd7965152016-11-07 19:49:52 +00001379}
1380
1381static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
1382{
1383 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
Robert Bragg0dd860c2017-05-11 16:43:28 +01001384 unsigned long flags;
1385
1386 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggd7965152016-11-07 19:49:52 +00001387
1388 /* Pre-DevBDW: OABUFFER must be set with counters off,
1389 * before OASTATUS1, but after OASTATUS2
1390 */
Lionel Landwerlinb82ed432018-03-26 10:08:26 +01001391 I915_WRITE(GEN7_OASTATUS2,
1392 gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT); /* head */
Robert Braggf2790202017-05-11 16:43:26 +01001393 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1394
Robert Braggd7965152016-11-07 19:49:52 +00001395 I915_WRITE(GEN7_OABUFFER, gtt_offset);
Robert Braggf2790202017-05-11 16:43:26 +01001396
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001397 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
Robert Braggd7965152016-11-07 19:49:52 +00001398
Robert Bragg0dd860c2017-05-11 16:43:28 +01001399 /* Mark that we need updated tail pointers to read from... */
1400 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1401 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1402
1403 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1404
Robert Braggd7965152016-11-07 19:49:52 +00001405 /* On Haswell we have to track which OASTATUS1 flags we've
1406 * already seen since they can't be cleared while periodic
1407 * sampling is enabled.
1408 */
1409 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
1410
1411 /* NB: although the OA buffer will initially be allocated
1412 * zeroed via shmfs (and so this memset is redundant when
1413 * first allocating), we may re-init the OA buffer, either
1414 * when re-enabling a stream or in error/reset paths.
1415 *
1416 * The reason we clear the buffer for each re-init is for the
1417 * sanity check in gen7_append_oa_reports() that looks at the
1418 * report-id field to make sure it's non-zero which relies on
1419 * the assumption that new reports are being written to zeroed
1420 * memory...
1421 */
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001422 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +00001423
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 Bragg19f81df2017-06-13 12:23:03 +01001430static void gen8_init_oa_buffer(struct drm_i915_private *dev_priv)
1431{
1432 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
1433 unsigned long flags;
1434
1435 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1436
1437 I915_WRITE(GEN8_OASTATUS, 0);
1438 I915_WRITE(GEN8_OAHEADPTR, gtt_offset);
1439 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1440
1441 I915_WRITE(GEN8_OABUFFER_UDW, 0);
1442
1443 /*
1444 * PRM says:
1445 *
1446 * "This MMIO must be set before the OATAILPTR
1447 * register and after the OAHEADPTR register. This is
1448 * to enable proper functionality of the overflow
1449 * bit."
1450 */
1451 I915_WRITE(GEN8_OABUFFER, gtt_offset |
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001452 OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
Robert Bragg19f81df2017-06-13 12:23:03 +01001453 I915_WRITE(GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1454
1455 /* Mark that we need updated tail pointers to read from... */
1456 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1457 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1458
1459 /*
1460 * Reset state used to recognise context switches, affecting which
1461 * reports we will forward to userspace while filtering for a single
1462 * context.
1463 */
1464 dev_priv->perf.oa.oa_buffer.last_ctx_id = INVALID_CTX_ID;
1465
1466 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1467
1468 /*
1469 * NB: although the OA buffer will initially be allocated
1470 * zeroed via shmfs (and so this memset is redundant when
1471 * first allocating), we may re-init the OA buffer, either
1472 * when re-enabling a stream or in error/reset paths.
1473 *
1474 * The reason we clear the buffer for each re-init is for the
1475 * sanity check in gen8_append_oa_reports() that looks at the
1476 * reason field to make sure it's non-zero which relies on
1477 * the assumption that new reports are being written to zeroed
1478 * memory...
1479 */
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001480 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
Robert Bragg19f81df2017-06-13 12:23:03 +01001481
1482 /*
1483 * Maybe make ->pollin per-stream state if we support multiple
1484 * concurrent streams in the future.
1485 */
1486 dev_priv->perf.oa.pollin = false;
1487}
1488
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001489static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
Robert Braggd7965152016-11-07 19:49:52 +00001490{
1491 struct drm_i915_gem_object *bo;
1492 struct i915_vma *vma;
1493 int ret;
1494
1495 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
1496 return -ENODEV;
1497
1498 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1499 if (ret)
1500 return ret;
1501
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001502 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1503 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1504
1505 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +00001506 if (IS_ERR(bo)) {
1507 DRM_ERROR("Failed to allocate OA buffer\n");
1508 ret = PTR_ERR(bo);
1509 goto unlock;
1510 }
1511
1512 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
1513 if (ret)
1514 goto err_unref;
1515
1516 /* PreHSW required 512K alignment, HSW requires 16M */
1517 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1518 if (IS_ERR(vma)) {
1519 ret = PTR_ERR(vma);
1520 goto err_unref;
1521 }
1522 dev_priv->perf.oa.oa_buffer.vma = vma;
1523
1524 dev_priv->perf.oa.oa_buffer.vaddr =
1525 i915_gem_object_pin_map(bo, I915_MAP_WB);
1526 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
1527 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
1528 goto err_unpin;
1529 }
1530
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001531 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
Robert Braggd7965152016-11-07 19:49:52 +00001532 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
Joonas Lahtinenfe841682018-11-16 15:55:09 +02001533 dev_priv->perf.oa.oa_buffer.vaddr);
Robert Braggd7965152016-11-07 19:49:52 +00001534
1535 goto unlock;
1536
1537err_unpin:
1538 __i915_vma_unpin(vma);
1539
1540err_unref:
1541 i915_gem_object_put(bo);
1542
1543 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
1544 dev_priv->perf.oa.oa_buffer.vma = NULL;
1545
1546unlock:
1547 mutex_unlock(&dev_priv->drm.struct_mutex);
1548 return ret;
1549}
1550
1551static void config_oa_regs(struct drm_i915_private *dev_priv,
1552 const struct i915_oa_reg *regs,
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001553 u32 n_regs)
Robert Braggd7965152016-11-07 19:49:52 +00001554{
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001555 u32 i;
Robert Braggd7965152016-11-07 19:49:52 +00001556
1557 for (i = 0; i < n_regs; i++) {
1558 const struct i915_oa_reg *reg = regs + i;
1559
1560 I915_WRITE(reg->addr, reg->value);
1561 }
1562}
1563
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001564static int hsw_enable_metric_set(struct i915_perf_stream *stream)
Robert Braggd7965152016-11-07 19:49:52 +00001565{
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001566 struct drm_i915_private *dev_priv = stream->dev_priv;
1567 const struct i915_oa_config *oa_config = stream->oa_config;
1568
Robert Braggd7965152016-11-07 19:49:52 +00001569 /* PRM:
1570 *
1571 * OA unit is using “crclk” for its functionality. When trunk
1572 * level clock gating takes place, OA clock would be gated,
1573 * unable to count the events from non-render clock domain.
1574 * Render clock gating must be disabled when OA is enabled to
1575 * count the events from non-render domain. Unit level clock
1576 * gating for RCS should also be disabled.
1577 */
1578 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1579 ~GEN7_DOP_CLOCK_GATE_ENABLE));
1580 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
1581 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1582
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001583 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
Robert Braggd7965152016-11-07 19:49:52 +00001584
1585 /* It apparently takes a fairly long time for a new MUX
1586 * configuration to be be applied after these register writes.
1587 * This delay duration was derived empirically based on the
1588 * render_basic config but hopefully it covers the maximum
1589 * configuration latency.
1590 *
1591 * As a fallback, the checks in _append_oa_reports() to skip
1592 * invalid OA reports do also seem to work to discard reports
1593 * generated before this config has completed - albeit not
1594 * silently.
1595 *
1596 * Unfortunately this is essentially a magic number, since we
1597 * don't currently know of a reliable mechanism for predicting
1598 * how long the MUX config will take to apply and besides
1599 * seeing invalid reports we don't know of a reliable way to
1600 * explicitly check that the MUX config has landed.
1601 *
1602 * It's even possible we've miss characterized the underlying
1603 * problem - it just seems like the simplest explanation why
1604 * a delay at this location would mitigate any invalid reports.
1605 */
1606 usleep_range(15000, 20000);
1607
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001608 config_oa_regs(dev_priv, oa_config->b_counter_regs,
1609 oa_config->b_counter_regs_len);
Robert Braggd7965152016-11-07 19:49:52 +00001610
1611 return 0;
1612}
1613
1614static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
1615{
1616 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
1617 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1618 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
1619 GEN7_DOP_CLOCK_GATE_ENABLE));
1620
1621 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1622 ~GT_NOA_ENABLE));
1623}
1624
Robert Bragg19f81df2017-06-13 12:23:03 +01001625/*
1626 * NB: It must always remain pointer safe to run this even if the OA unit
1627 * has been disabled.
1628 *
1629 * It's fine to put out-of-date values into these per-context registers
1630 * in the case that the OA unit has been disabled.
1631 */
Chris Wilsonb146e5e2019-03-06 08:47:04 +00001632static void
1633gen8_update_reg_state_unlocked(struct intel_context *ce,
1634 u32 *reg_state,
1635 const struct i915_oa_config *oa_config)
Robert Bragg19f81df2017-06-13 12:23:03 +01001636{
Chris Wilsonb146e5e2019-03-06 08:47:04 +00001637 struct drm_i915_private *i915 = ce->gem_context->i915;
1638 u32 ctx_oactxctrl = i915->perf.oa.ctx_oactxctrl_offset;
1639 u32 ctx_flexeu0 = i915->perf.oa.ctx_flexeu0_offset;
Robert Bragg19f81df2017-06-13 12:23:03 +01001640 /* The MMIO offsets for Flex EU registers aren't contiguous */
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +01001641 i915_reg_t flex_regs[] = {
1642 EU_PERF_CNTL0,
1643 EU_PERF_CNTL1,
1644 EU_PERF_CNTL2,
1645 EU_PERF_CNTL3,
1646 EU_PERF_CNTL4,
1647 EU_PERF_CNTL5,
1648 EU_PERF_CNTL6,
Robert Bragg19f81df2017-06-13 12:23:03 +01001649 };
1650 int i;
1651
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +01001652 CTX_REG(reg_state, ctx_oactxctrl, GEN8_OACTXCONTROL,
Chris Wilsonb146e5e2019-03-06 08:47:04 +00001653 (i915->perf.oa.period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
1654 (i915->perf.oa.periodic ? GEN8_OA_TIMER_ENABLE : 0) |
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +01001655 GEN8_OA_COUNTER_RESUME);
Robert Bragg19f81df2017-06-13 12:23:03 +01001656
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +01001657 for (i = 0; i < ARRAY_SIZE(flex_regs); i++) {
Robert Bragg19f81df2017-06-13 12:23:03 +01001658 u32 state_offset = ctx_flexeu0 + i * 2;
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +01001659 u32 mmio = i915_mmio_reg_offset(flex_regs[i]);
Robert Bragg19f81df2017-06-13 12:23:03 +01001660
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 yet...
1665 */
1666 u32 value = 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01001667
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001668 if (oa_config) {
1669 u32 j;
1670
1671 for (j = 0; j < oa_config->flex_regs_len; j++) {
1672 if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) {
1673 value = oa_config->flex_regs[j].value;
1674 break;
1675 }
Robert Bragg19f81df2017-06-13 12:23:03 +01001676 }
1677 }
1678
Lionel Landwerlin35ab4fd2018-08-13 09:02:18 +01001679 CTX_REG(reg_state, state_offset, flex_regs[i], value);
Robert Bragg19f81df2017-06-13 12:23:03 +01001680 }
Lionel Landwerlinec431ea2019-02-05 09:50:29 +00001681
Chris Wilsonb146e5e2019-03-06 08:47:04 +00001682 CTX_REG(reg_state,
1683 CTX_R_PWR_CLK_STATE, GEN8_R_PWR_CLK_STATE,
1684 gen8_make_rpcs(i915, &ce->sseu));
Robert Bragg19f81df2017-06-13 12:23:03 +01001685}
1686
1687/*
Robert Bragg19f81df2017-06-13 12:23:03 +01001688 * Manages updating the per-context aspects of the OA stream
1689 * configuration across all contexts.
1690 *
1691 * The awkward consideration here is that OACTXCONTROL controls the
1692 * exponent for periodic sampling which is primarily used for system
1693 * wide profiling where we'd like a consistent sampling period even in
1694 * the face of context switches.
1695 *
1696 * Our approach of updating the register state context (as opposed to
1697 * say using a workaround batch buffer) ensures that the hardware
1698 * won't automatically reload an out-of-date timer exponent even
1699 * transiently before a WA BB could be parsed.
1700 *
1701 * This function needs to:
1702 * - Ensure the currently running context's per-context OA state is
1703 * updated
1704 * - Ensure that all existing contexts will have the correct per-context
1705 * OA state if they are scheduled for use.
1706 * - Ensure any new contexts will be initialized with the correct
1707 * per-context OA state.
1708 *
1709 * Note: it's only the RCS/Render context that has any OA state.
1710 */
1711static int gen8_configure_all_contexts(struct drm_i915_private *dev_priv,
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00001712 const struct i915_oa_config *oa_config)
Robert Bragg19f81df2017-06-13 12:23:03 +01001713{
Chris Wilson8a68d462019-03-05 18:03:30 +00001714 struct intel_engine_cs *engine = dev_priv->engine[RCS0];
Chris Wilson666424a2018-09-14 13:35:04 +01001715 unsigned int map_type = i915_coherent_map_type(dev_priv);
Robert Bragg19f81df2017-06-13 12:23:03 +01001716 struct i915_gem_context *ctx;
Tvrtko Ursulin722f3de2018-09-12 16:29:30 +01001717 struct i915_request *rq;
Robert Bragg19f81df2017-06-13 12:23:03 +01001718 int ret;
Robert Bragg19f81df2017-06-13 12:23:03 +01001719
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00001720 lockdep_assert_held(&dev_priv->drm.struct_mutex);
Robert Bragg19f81df2017-06-13 12:23:03 +01001721
Robert Bragg19f81df2017-06-13 12:23:03 +01001722 /*
1723 * The OA register config is setup through the context image. This image
1724 * might be written to by the GPU on context switch (in particular on
1725 * lite-restore). This means we can't safely update a context's image,
1726 * if this context is scheduled/submitted to run on the GPU.
1727 *
1728 * We could emit the OA register config through the batch buffer but
1729 * this might leave small interval of time where the OA unit is
1730 * configured at an invalid sampling period.
1731 *
1732 * So far the best way to work around this issue seems to be draining
1733 * the GPU from any submitted work.
1734 */
Chris Wilsonec625fb2018-07-09 13:20:42 +01001735 ret = i915_gem_wait_for_idle(dev_priv,
Tvrtko Ursulin722f3de2018-09-12 16:29:30 +01001736 I915_WAIT_LOCKED,
Chris Wilsonec625fb2018-07-09 13:20:42 +01001737 MAX_SCHEDULE_TIMEOUT);
Robert Bragg19f81df2017-06-13 12:23:03 +01001738 if (ret)
Lionel Landwerlin1c71bc52018-08-13 09:02:17 +01001739 return ret;
Robert Bragg19f81df2017-06-13 12:23:03 +01001740
1741 /* Update all contexts now that we've stalled the submission. */
Chris Wilson829a0af2017-06-20 12:05:45 +01001742 list_for_each_entry(ctx, &dev_priv->contexts.list, link) {
Chris Wilsonc4d52fe2019-03-08 13:25:19 +00001743 struct intel_context *ce = intel_context_lookup(ctx, engine);
Robert Bragg19f81df2017-06-13 12:23:03 +01001744 u32 *regs;
1745
1746 /* OA settings will be set upon first use */
Chris Wilsonc4d52fe2019-03-08 13:25:19 +00001747 if (!ce || !ce->state)
Robert Bragg19f81df2017-06-13 12:23:03 +01001748 continue;
1749
Chris Wilson666424a2018-09-14 13:35:04 +01001750 regs = i915_gem_object_pin_map(ce->state->obj, map_type);
Lionel Landwerlin1c71bc52018-08-13 09:02:17 +01001751 if (IS_ERR(regs))
1752 return PTR_ERR(regs);
Robert Bragg19f81df2017-06-13 12:23:03 +01001753
1754 ce->state->obj->mm.dirty = true;
1755 regs += LRC_STATE_PN * PAGE_SIZE / sizeof(*regs);
1756
Chris Wilsonb146e5e2019-03-06 08:47:04 +00001757 gen8_update_reg_state_unlocked(ce, regs, oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01001758
1759 i915_gem_object_unpin_map(ce->state->obj);
1760 }
1761
Tvrtko Ursulin722f3de2018-09-12 16:29:30 +01001762 /*
1763 * Apply the configuration by doing one context restore of the edited
1764 * context image.
1765 */
1766 rq = i915_request_alloc(engine, dev_priv->kernel_context);
1767 if (IS_ERR(rq))
1768 return PTR_ERR(rq);
1769
1770 i915_request_add(rq);
1771
1772 return 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01001773}
1774
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001775static int gen8_enable_metric_set(struct i915_perf_stream *stream)
Robert Bragg19f81df2017-06-13 12:23:03 +01001776{
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001777 struct drm_i915_private *dev_priv = stream->dev_priv;
1778 const struct i915_oa_config *oa_config = stream->oa_config;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001779 int ret;
Robert Bragg19f81df2017-06-13 12:23:03 +01001780
1781 /*
1782 * We disable slice/unslice clock ratio change reports on SKL since
1783 * they are too noisy. The HW generates a lot of redundant reports
1784 * where the ratio hasn't really changed causing a lot of redundant
1785 * work to processes and increasing the chances we'll hit buffer
1786 * overruns.
1787 *
1788 * Although we don't currently use the 'disable overrun' OABUFFER
1789 * feature it's worth noting that clock ratio reports have to be
1790 * disabled before considering to use that feature since the HW doesn't
1791 * correctly block these reports.
1792 *
1793 * Currently none of the high-level metrics we have depend on knowing
1794 * this ratio to normalize.
1795 *
1796 * Note: This register is not power context saved and restored, but
1797 * that's OK considering that we disable RC6 while the OA unit is
1798 * enabled.
1799 *
1800 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
1801 * be read back from automatically triggered reports, as part of the
1802 * RPT_ID field.
1803 */
Lucas De Marchi00690002018-12-12 10:10:42 -08001804 if (IS_GEN_RANGE(dev_priv, 9, 11)) {
Robert Bragg19f81df2017-06-13 12:23:03 +01001805 I915_WRITE(GEN8_OA_DEBUG,
1806 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
1807 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
1808 }
1809
1810 /*
1811 * Update all contexts prior writing the mux configurations as we need
1812 * to make sure all slices/subslices are ON before writing to NOA
1813 * registers.
1814 */
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00001815 ret = gen8_configure_all_contexts(dev_priv, oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01001816 if (ret)
1817 return ret;
1818
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001819 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
1820
Lionel Landwerlin701f8232017-08-03 17:58:08 +01001821 config_oa_regs(dev_priv, oa_config->b_counter_regs,
1822 oa_config->b_counter_regs_len);
Robert Bragg19f81df2017-06-13 12:23:03 +01001823
1824 return 0;
1825}
1826
1827static void gen8_disable_metric_set(struct drm_i915_private *dev_priv)
1828{
1829 /* Reset all contexts' slices/subslices configurations. */
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00001830 gen8_configure_all_contexts(dev_priv, NULL);
Lionel Landwerlin28964cf2017-08-03 17:58:10 +01001831
1832 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1833 ~GT_NOA_ENABLE));
Robert Bragg19f81df2017-06-13 12:23:03 +01001834}
1835
Lionel Landwerlin95690a02017-11-10 19:08:43 +00001836static void gen10_disable_metric_set(struct drm_i915_private *dev_priv)
1837{
1838 /* Reset all contexts' slices/subslices configurations. */
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00001839 gen8_configure_all_contexts(dev_priv, NULL);
Lionel Landwerlin95690a02017-11-10 19:08:43 +00001840
1841 /* Make sure we disable noa to save power. */
1842 I915_WRITE(RPM_CONFIG1,
1843 I915_READ(RPM_CONFIG1) & ~GEN10_GT_NOA_ENABLE);
1844}
1845
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001846static void gen7_oa_enable(struct i915_perf_stream *stream)
Robert Braggd7965152016-11-07 19:49:52 +00001847{
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001848 struct drm_i915_private *dev_priv = stream->dev_priv;
1849 struct i915_gem_context *ctx = stream->ctx;
Lionel Landwerlin11051302018-03-26 10:08:23 +01001850 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1851 bool periodic = dev_priv->perf.oa.periodic;
1852 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1853 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1854
Robert Bragg1bef3402017-06-13 12:23:06 +01001855 /*
1856 * Reset buf pointers so we don't forward reports from before now.
1857 *
1858 * Think carefully if considering trying to avoid this, since it
1859 * also ensures status flags and the buffer itself are cleared
1860 * in error paths, and we have checks for invalid reports based
1861 * on the assumption that certain fields are written to zeroed
1862 * memory which this helps maintains.
1863 */
1864 gen7_init_oa_buffer(dev_priv);
Robert Braggd7965152016-11-07 19:49:52 +00001865
Lionel Landwerlin11051302018-03-26 10:08:23 +01001866 I915_WRITE(GEN7_OACONTROL,
1867 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1868 (period_exponent <<
1869 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1870 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1871 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1872 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1873 GEN7_OACONTROL_ENABLE);
Robert Braggd7965152016-11-07 19:49:52 +00001874}
1875
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001876static void gen8_oa_enable(struct i915_perf_stream *stream)
Robert Bragg19f81df2017-06-13 12:23:03 +01001877{
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001878 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Bragg19f81df2017-06-13 12:23:03 +01001879 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1880
1881 /*
1882 * Reset buf pointers so we don't forward reports from before now.
1883 *
1884 * Think carefully if considering trying to avoid this, since it
1885 * also ensures status flags and the buffer itself are cleared
1886 * in error paths, and we have checks for invalid reports based
1887 * on the assumption that certain fields are written to zeroed
1888 * memory which this helps maintains.
1889 */
1890 gen8_init_oa_buffer(dev_priv);
1891
1892 /*
1893 * Note: we don't rely on the hardware to perform single context
1894 * filtering and instead filter on the cpu based on the context-id
1895 * field of reports
1896 */
1897 I915_WRITE(GEN8_OACONTROL, (report_format <<
1898 GEN8_OA_REPORT_FORMAT_SHIFT) |
1899 GEN8_OA_COUNTER_ENABLE);
1900}
1901
Robert Bragg16d98b32016-12-07 21:40:33 +00001902/**
1903 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1904 * @stream: An i915 perf stream opened for OA metrics
1905 *
1906 * [Re]enables hardware periodic sampling according to the period configured
1907 * when opening the stream. This also starts a hrtimer that will periodically
1908 * check for data in the circular OA buffer for notifying userspace (e.g.
1909 * during a read() or poll()).
1910 */
Robert Braggd7965152016-11-07 19:49:52 +00001911static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1912{
1913 struct drm_i915_private *dev_priv = stream->dev_priv;
1914
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001915 dev_priv->perf.oa.ops.oa_enable(stream);
Robert Braggd7965152016-11-07 19:49:52 +00001916
1917 if (dev_priv->perf.oa.periodic)
1918 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1919 ns_to_ktime(POLL_PERIOD),
1920 HRTIMER_MODE_REL_PINNED);
1921}
1922
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001923static void gen7_oa_disable(struct i915_perf_stream *stream)
Robert Braggd7965152016-11-07 19:49:52 +00001924{
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001925 struct drm_i915_private *dev_priv = stream->dev_priv;
1926
Robert Braggd7965152016-11-07 19:49:52 +00001927 I915_WRITE(GEN7_OACONTROL, 0);
Chris Wilsone896d292018-05-11 14:52:07 +01001928 if (intel_wait_for_register(dev_priv,
1929 GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
1930 50))
1931 DRM_ERROR("wait for OA to be disabled timed out\n");
Robert Braggd7965152016-11-07 19:49:52 +00001932}
1933
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001934static void gen8_oa_disable(struct i915_perf_stream *stream)
Robert Bragg19f81df2017-06-13 12:23:03 +01001935{
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001936 struct drm_i915_private *dev_priv = stream->dev_priv;
1937
Robert Bragg19f81df2017-06-13 12:23:03 +01001938 I915_WRITE(GEN8_OACONTROL, 0);
Chris Wilsone896d292018-05-11 14:52:07 +01001939 if (intel_wait_for_register(dev_priv,
1940 GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
1941 50))
1942 DRM_ERROR("wait for OA to be disabled timed out\n");
Robert Bragg19f81df2017-06-13 12:23:03 +01001943}
1944
Robert Bragg16d98b32016-12-07 21:40:33 +00001945/**
1946 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1947 * @stream: An i915 perf stream opened for OA metrics
1948 *
1949 * Stops the OA unit from periodically writing counter reports into the
1950 * circular OA buffer. This also stops the hrtimer that periodically checks for
1951 * data in the circular OA buffer, for notifying userspace.
1952 */
Robert Braggd7965152016-11-07 19:49:52 +00001953static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1954{
1955 struct drm_i915_private *dev_priv = stream->dev_priv;
1956
Lionel Landwerlin5728de22018-10-23 11:07:06 +01001957 dev_priv->perf.oa.ops.oa_disable(stream);
Robert Braggd7965152016-11-07 19:49:52 +00001958
1959 if (dev_priv->perf.oa.periodic)
1960 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1961}
1962
Robert Braggd7965152016-11-07 19:49:52 +00001963static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1964 .destroy = i915_oa_stream_destroy,
1965 .enable = i915_oa_stream_enable,
1966 .disable = i915_oa_stream_disable,
1967 .wait_unlocked = i915_oa_wait_unlocked,
1968 .poll_wait = i915_oa_poll_wait,
1969 .read = i915_oa_read,
1970};
1971
Robert Bragg16d98b32016-12-07 21:40:33 +00001972/**
1973 * i915_oa_stream_init - validate combined props for OA stream and init
1974 * @stream: An i915 perf stream
1975 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1976 * @props: The property state that configures stream (individually validated)
1977 *
1978 * While read_properties_unlocked() validates properties in isolation it
1979 * doesn't ensure that the combination necessarily makes sense.
1980 *
1981 * At this point it has been determined that userspace wants a stream of
1982 * OA metrics, but still we need to further validate the combined
1983 * properties are OK.
1984 *
1985 * If the configuration makes sense then we can allocate memory for
1986 * a circular OA buffer and apply the requested metric set configuration.
1987 *
1988 * Returns: zero on success or a negative error code.
1989 */
Robert Braggd7965152016-11-07 19:49:52 +00001990static int i915_oa_stream_init(struct i915_perf_stream *stream,
1991 struct drm_i915_perf_open_param *param,
1992 struct perf_open_properties *props)
1993{
1994 struct drm_i915_private *dev_priv = stream->dev_priv;
1995 int format_size;
1996 int ret;
1997
Robert Bragg442b8c02016-11-07 19:49:53 +00001998 /* If the sysfs metrics/ directory wasn't registered for some
1999 * reason then don't let userspace try their luck with config
2000 * IDs
2001 */
2002 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00002003 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00002004 return -EINVAL;
2005 }
2006
Robert Braggd7965152016-11-07 19:49:52 +00002007 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00002008 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00002009 return -EINVAL;
2010 }
2011
Lionel Landwerlin784b1a82018-10-23 11:07:05 +01002012 if (!dev_priv->perf.oa.ops.enable_metric_set) {
Robert Bragg77085502016-12-01 17:21:52 +00002013 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00002014 return -ENODEV;
2015 }
2016
2017 /* To avoid the complexity of having to accurately filter
2018 * counter reports and marshal to the appropriate client
2019 * we currently only allow exclusive access
2020 */
2021 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00002022 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00002023 return -EBUSY;
2024 }
2025
Robert Braggd7965152016-11-07 19:49:52 +00002026 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00002027 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00002028 return -EINVAL;
2029 }
2030
Robert Bragg712122e2017-05-11 16:43:31 +01002031 /* We set up some ratelimit state to potentially throttle any _NOTES
2032 * about spurious, invalid OA reports which we don't forward to
2033 * userspace.
2034 *
2035 * The initialization is associated with opening the stream (not driver
2036 * init) considering we print a _NOTE about any throttling when closing
2037 * the stream instead of waiting until driver _fini which no one would
2038 * ever see.
2039 *
2040 * Using the same limiting factors as printk_ratelimit()
2041 */
2042 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
2043 5 * HZ, 10);
2044 /* Since we use a DRM_NOTE for spurious reports it would be
2045 * inconsistent to let __ratelimit() automatically print a warning for
2046 * throttling.
2047 */
2048 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
2049 RATELIMIT_MSG_ON_RELEASE);
2050
Robert Braggd7965152016-11-07 19:49:52 +00002051 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2052
2053 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
2054
2055 stream->sample_flags |= SAMPLE_OA_REPORT;
2056 stream->sample_size += format_size;
2057
2058 dev_priv->perf.oa.oa_buffer.format_size = format_size;
2059 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
2060 return -EINVAL;
2061
2062 dev_priv->perf.oa.oa_buffer.format =
2063 dev_priv->perf.oa.oa_formats[props->oa_format].format;
2064
Robert Braggd7965152016-11-07 19:49:52 +00002065 dev_priv->perf.oa.periodic = props->oa_periodic;
Robert Bragg0dd860c2017-05-11 16:43:28 +01002066 if (dev_priv->perf.oa.periodic)
Robert Braggd7965152016-11-07 19:49:52 +00002067 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
2068
Robert Braggd7965152016-11-07 19:49:52 +00002069 if (stream->ctx) {
2070 ret = oa_get_render_ctx_id(stream);
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01002071 if (ret) {
2072 DRM_DEBUG("Invalid context id to filter with\n");
Robert Braggd7965152016-11-07 19:49:52 +00002073 return ret;
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01002074 }
Robert Braggd7965152016-11-07 19:49:52 +00002075 }
2076
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002077 ret = get_oa_config(dev_priv, props->metrics_set, &stream->oa_config);
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01002078 if (ret) {
2079 DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002080 goto err_config;
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01002081 }
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002082
Robert Braggd7965152016-11-07 19:49:52 +00002083 /* PRM - observability performance counters:
2084 *
2085 * OACONTROL, performance counter enable, note:
2086 *
2087 * "When this bit is set, in order to have coherent counts,
2088 * RC6 power state and trunk clock gating must be disabled.
2089 * This can be achieved by programming MMIO registers as
2090 * 0xA094=0 and 0xA090[31]=1"
2091 *
2092 * In our case we are expecting that taking pm + FORCEWAKE
2093 * references will effectively disable RC6.
2094 */
Chris Wilson6619c002019-01-14 14:21:15 +00002095 stream->wakeref = intel_runtime_pm_get(dev_priv);
Daniele Ceraolo Spurio3ceea6a2019-03-19 11:35:36 -07002096 intel_uncore_forcewake_get(&dev_priv->uncore, FORCEWAKE_ALL);
Robert Braggd7965152016-11-07 19:49:52 +00002097
Joonas Lahtinenfe841682018-11-16 15:55:09 +02002098 ret = alloc_oa_buffer(dev_priv);
sagar.a.kamble@intel.com987f8c42017-06-27 23:09:41 +05302099 if (ret)
2100 goto err_oa_buf_alloc;
2101
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00002102 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
2103 if (ret)
2104 goto err_lock;
2105
Lionel Landwerlinec431ea2019-02-05 09:50:29 +00002106 stream->ops = &i915_oa_stream_ops;
2107 dev_priv->perf.oa.exclusive_stream = stream;
2108
Lionel Landwerlin5728de22018-10-23 11:07:06 +01002109 ret = dev_priv->perf.oa.ops.enable_metric_set(stream);
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01002110 if (ret) {
2111 DRM_DEBUG("Unable to enable metric set\n");
Robert Braggd7965152016-11-07 19:49:52 +00002112 goto err_enable;
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01002113 }
Robert Braggd7965152016-11-07 19:49:52 +00002114
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002115 mutex_unlock(&dev_priv->drm.struct_mutex);
2116
Robert Braggd7965152016-11-07 19:49:52 +00002117 return 0;
2118
2119err_enable:
Lionel Landwerlinec431ea2019-02-05 09:50:29 +00002120 dev_priv->perf.oa.exclusive_stream = NULL;
Lionel Landwerlin41d3fdc2018-03-01 11:06:13 +00002121 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
2122 mutex_unlock(&dev_priv->drm.struct_mutex);
2123
2124err_lock:
Robert Braggd7965152016-11-07 19:49:52 +00002125 free_oa_buffer(dev_priv);
2126
2127err_oa_buf_alloc:
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002128 put_oa_config(dev_priv, stream->oa_config);
2129
Daniele Ceraolo Spurio3ceea6a2019-03-19 11:35:36 -07002130 intel_uncore_forcewake_put(&dev_priv->uncore, FORCEWAKE_ALL);
Chris Wilson6619c002019-01-14 14:21:15 +00002131 intel_runtime_pm_put(dev_priv, stream->wakeref);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002132
2133err_config:
Robert Braggd7965152016-11-07 19:49:52 +00002134 if (stream->ctx)
2135 oa_put_render_ctx_id(stream);
2136
2137 return ret;
2138}
2139
Robert Bragg19f81df2017-06-13 12:23:03 +01002140void i915_oa_init_reg_state(struct intel_engine_cs *engine,
Chris Wilsonb146e5e2019-03-06 08:47:04 +00002141 struct intel_context *ce,
2142 u32 *regs)
Robert Bragg19f81df2017-06-13 12:23:03 +01002143{
Chris Wilson28b6cb02017-08-10 18:57:43 +01002144 struct i915_perf_stream *stream;
Robert Bragg19f81df2017-06-13 12:23:03 +01002145
Chris Wilson8a68d462019-03-05 18:03:30 +00002146 if (engine->class != RENDER_CLASS)
Robert Bragg19f81df2017-06-13 12:23:03 +01002147 return;
2148
Chris Wilson28b6cb02017-08-10 18:57:43 +01002149 stream = engine->i915->perf.oa.exclusive_stream;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002150 if (stream)
Chris Wilsonb146e5e2019-03-06 08:47:04 +00002151 gen8_update_reg_state_unlocked(ce, regs, stream->oa_config);
Robert Bragg19f81df2017-06-13 12:23:03 +01002152}
2153
Robert Bragg16d98b32016-12-07 21:40:33 +00002154/**
2155 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2156 * @stream: An i915 perf stream
2157 * @file: An i915 perf stream file
2158 * @buf: destination buffer given by userspace
2159 * @count: the number of bytes userspace wants to read
2160 * @ppos: (inout) file seek position (unused)
2161 *
2162 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2163 * ensure that if we've successfully copied any data then reporting that takes
2164 * precedence over any internal error status, so the data isn't lost.
2165 *
2166 * For example ret will be -ENOSPC whenever there is more buffered data than
2167 * can be copied to userspace, but that's only interesting if we weren't able
2168 * to copy some data because it implies the userspace buffer is too small to
2169 * receive a single record (and we never split records).
2170 *
2171 * Another case with ret == -EFAULT is more of a grey area since it would seem
2172 * like bad form for userspace to ask us to overrun its buffer, but the user
2173 * knows best:
2174 *
2175 * http://yarchive.net/comp/linux/partial_reads_writes.html
2176 *
2177 * Returns: The number of bytes copied or a negative error code on failure.
2178 */
Robert Braggeec688e2016-11-07 19:49:47 +00002179static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2180 struct file *file,
2181 char __user *buf,
2182 size_t count,
2183 loff_t *ppos)
2184{
2185 /* Note we keep the offset (aka bytes read) separate from any
2186 * error status so that the final check for whether we return
2187 * the bytes read with a higher precedence than any error (see
2188 * comment below) doesn't need to be handled/duplicated in
2189 * stream->ops->read() implementations.
2190 */
2191 size_t offset = 0;
2192 int ret = stream->ops->read(stream, buf, count, &offset);
2193
Robert Braggeec688e2016-11-07 19:49:47 +00002194 return offset ?: (ret ?: -EAGAIN);
2195}
2196
Robert Bragg16d98b32016-12-07 21:40:33 +00002197/**
2198 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2199 * @file: An i915 perf stream file
2200 * @buf: destination buffer given by userspace
2201 * @count: the number of bytes userspace wants to read
2202 * @ppos: (inout) file seek position (unused)
2203 *
2204 * The entry point for handling a read() on a stream file descriptor from
2205 * userspace. Most of the work is left to the i915_perf_read_locked() and
2206 * &i915_perf_stream_ops->read but to save having stream implementations (of
2207 * which we might have multiple later) we handle blocking read here.
2208 *
2209 * We can also consistently treat trying to read from a disabled stream
2210 * as an IO error so implementations can assume the stream is enabled
2211 * while reading.
2212 *
2213 * Returns: The number of bytes copied or a negative error code on failure.
2214 */
Robert Braggeec688e2016-11-07 19:49:47 +00002215static ssize_t i915_perf_read(struct file *file,
2216 char __user *buf,
2217 size_t count,
2218 loff_t *ppos)
2219{
2220 struct i915_perf_stream *stream = file->private_data;
2221 struct drm_i915_private *dev_priv = stream->dev_priv;
2222 ssize_t ret;
2223
Robert Braggd7965152016-11-07 19:49:52 +00002224 /* To ensure it's handled consistently we simply treat all reads of a
2225 * disabled stream as an error. In particular it might otherwise lead
2226 * to a deadlock for blocking file descriptors...
2227 */
2228 if (!stream->enabled)
2229 return -EIO;
2230
Robert Braggeec688e2016-11-07 19:49:47 +00002231 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00002232 /* There's the small chance of false positives from
2233 * stream->ops->wait_unlocked.
2234 *
2235 * E.g. with single context filtering since we only wait until
2236 * oabuffer has >= 1 report we don't immediately know whether
2237 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00002238 */
2239 do {
2240 ret = stream->ops->wait_unlocked(stream);
2241 if (ret)
2242 return ret;
2243
2244 mutex_lock(&dev_priv->perf.lock);
2245 ret = i915_perf_read_locked(stream, file,
2246 buf, count, ppos);
2247 mutex_unlock(&dev_priv->perf.lock);
2248 } while (ret == -EAGAIN);
2249 } else {
2250 mutex_lock(&dev_priv->perf.lock);
2251 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
2252 mutex_unlock(&dev_priv->perf.lock);
2253 }
2254
Linus Torvaldsa9a08842018-02-11 14:34:03 -08002255 /* We allow the poll checking to sometimes report false positive EPOLLIN
Robert Bragg26ebd9c2017-05-11 16:43:25 +01002256 * events where we might actually report EAGAIN on read() if there's
2257 * not really any data available. In this situation though we don't
Linus Torvaldsa9a08842018-02-11 14:34:03 -08002258 * want to enter a busy loop between poll() reporting a EPOLLIN event
Robert Bragg26ebd9c2017-05-11 16:43:25 +01002259 * and read() returning -EAGAIN. Clearing the oa.pollin state here
2260 * effectively ensures we back off until the next hrtimer callback
Linus Torvaldsa9a08842018-02-11 14:34:03 -08002261 * before reporting another EPOLLIN event.
Robert Bragg26ebd9c2017-05-11 16:43:25 +01002262 */
2263 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00002264 /* Maybe make ->pollin per-stream state if we support multiple
2265 * concurrent streams in the future.
2266 */
2267 dev_priv->perf.oa.pollin = false;
2268 }
2269
Robert Braggeec688e2016-11-07 19:49:47 +00002270 return ret;
2271}
2272
Robert Braggd7965152016-11-07 19:49:52 +00002273static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
2274{
2275 struct drm_i915_private *dev_priv =
2276 container_of(hrtimer, typeof(*dev_priv),
2277 perf.oa.poll_check_timer);
2278
Robert Bragg19f81df2017-06-13 12:23:03 +01002279 if (oa_buffer_check_unlocked(dev_priv)) {
Robert Braggd7965152016-11-07 19:49:52 +00002280 dev_priv->perf.oa.pollin = true;
2281 wake_up(&dev_priv->perf.oa.poll_wq);
2282 }
2283
2284 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
2285
2286 return HRTIMER_RESTART;
2287}
2288
Robert Bragg16d98b32016-12-07 21:40:33 +00002289/**
2290 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
2291 * @dev_priv: i915 device instance
2292 * @stream: An i915 perf stream
2293 * @file: An i915 perf stream file
2294 * @wait: poll() state table
2295 *
2296 * For handling userspace polling on an i915 perf stream, this calls through to
2297 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
2298 * will be woken for new stream data.
2299 *
2300 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2301 * with any non-file-operation driver hooks.
2302 *
2303 * Returns: any poll events that are ready without sleeping
2304 */
Al Viroafc9a422017-07-03 06:39:46 -04002305static __poll_t i915_perf_poll_locked(struct drm_i915_private *dev_priv,
Robert Braggd7965152016-11-07 19:49:52 +00002306 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00002307 struct file *file,
2308 poll_table *wait)
2309{
Al Viroafc9a422017-07-03 06:39:46 -04002310 __poll_t events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00002311
2312 stream->ops->poll_wait(stream, file, wait);
2313
Robert Braggd7965152016-11-07 19:49:52 +00002314 /* Note: we don't explicitly check whether there's something to read
2315 * here since this path may be very hot depending on what else
2316 * userspace is polling, or on the timeout in use. We rely solely on
2317 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
2318 * samples to read.
2319 */
2320 if (dev_priv->perf.oa.pollin)
Linus Torvaldsa9a08842018-02-11 14:34:03 -08002321 events |= EPOLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00002322
Robert Braggd7965152016-11-07 19:49:52 +00002323 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00002324}
2325
Robert Bragg16d98b32016-12-07 21:40:33 +00002326/**
2327 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
2328 * @file: An i915 perf stream file
2329 * @wait: poll() state table
2330 *
2331 * For handling userspace polling on an i915 perf stream, this ensures
2332 * poll_wait() gets called with a wait queue that will be woken for new stream
2333 * data.
2334 *
2335 * Note: Implementation deferred to i915_perf_poll_locked()
2336 *
2337 * Returns: any poll events that are ready without sleeping
2338 */
Al Viroafc9a422017-07-03 06:39:46 -04002339static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
Robert Braggeec688e2016-11-07 19:49:47 +00002340{
2341 struct i915_perf_stream *stream = file->private_data;
2342 struct drm_i915_private *dev_priv = stream->dev_priv;
Al Viroafc9a422017-07-03 06:39:46 -04002343 __poll_t ret;
Robert Braggeec688e2016-11-07 19:49:47 +00002344
2345 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002346 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00002347 mutex_unlock(&dev_priv->perf.lock);
2348
2349 return ret;
2350}
2351
Robert Bragg16d98b32016-12-07 21:40:33 +00002352/**
2353 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
2354 * @stream: A disabled i915 perf stream
2355 *
2356 * [Re]enables the associated capture of data for this stream.
2357 *
2358 * If a stream was previously enabled then there's currently no intention
2359 * to provide userspace any guarantee about the preservation of previously
2360 * buffered data.
2361 */
Robert Braggeec688e2016-11-07 19:49:47 +00002362static void i915_perf_enable_locked(struct i915_perf_stream *stream)
2363{
2364 if (stream->enabled)
2365 return;
2366
2367 /* Allow stream->ops->enable() to refer to this */
2368 stream->enabled = true;
2369
2370 if (stream->ops->enable)
2371 stream->ops->enable(stream);
2372}
2373
Robert Bragg16d98b32016-12-07 21:40:33 +00002374/**
2375 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
2376 * @stream: An enabled i915 perf stream
2377 *
2378 * Disables the associated capture of data for this stream.
2379 *
2380 * The intention is that disabling an re-enabling a stream will ideally be
2381 * cheaper than destroying and re-opening a stream with the same configuration,
2382 * though there are no formal guarantees about what state or buffered data
2383 * must be retained between disabling and re-enabling a stream.
2384 *
2385 * Note: while a stream is disabled it's considered an error for userspace
2386 * to attempt to read from the stream (-EIO).
2387 */
Robert Braggeec688e2016-11-07 19:49:47 +00002388static void i915_perf_disable_locked(struct i915_perf_stream *stream)
2389{
2390 if (!stream->enabled)
2391 return;
2392
2393 /* Allow stream->ops->disable() to refer to this */
2394 stream->enabled = false;
2395
2396 if (stream->ops->disable)
2397 stream->ops->disable(stream);
2398}
2399
Robert Bragg16d98b32016-12-07 21:40:33 +00002400/**
2401 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2402 * @stream: An i915 perf stream
2403 * @cmd: the ioctl request
2404 * @arg: the ioctl data
2405 *
2406 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2407 * with any non-file-operation driver hooks.
2408 *
2409 * Returns: zero on success or a negative error code. Returns -EINVAL for
2410 * an unknown ioctl request.
2411 */
Robert Braggeec688e2016-11-07 19:49:47 +00002412static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
2413 unsigned int cmd,
2414 unsigned long arg)
2415{
2416 switch (cmd) {
2417 case I915_PERF_IOCTL_ENABLE:
2418 i915_perf_enable_locked(stream);
2419 return 0;
2420 case I915_PERF_IOCTL_DISABLE:
2421 i915_perf_disable_locked(stream);
2422 return 0;
2423 }
2424
2425 return -EINVAL;
2426}
2427
Robert Bragg16d98b32016-12-07 21:40:33 +00002428/**
2429 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2430 * @file: An i915 perf stream file
2431 * @cmd: the ioctl request
2432 * @arg: the ioctl data
2433 *
2434 * Implementation deferred to i915_perf_ioctl_locked().
2435 *
2436 * Returns: zero on success or a negative error code. Returns -EINVAL for
2437 * an unknown ioctl request.
2438 */
Robert Braggeec688e2016-11-07 19:49:47 +00002439static long i915_perf_ioctl(struct file *file,
2440 unsigned int cmd,
2441 unsigned long arg)
2442{
2443 struct i915_perf_stream *stream = file->private_data;
2444 struct drm_i915_private *dev_priv = stream->dev_priv;
2445 long ret;
2446
2447 mutex_lock(&dev_priv->perf.lock);
2448 ret = i915_perf_ioctl_locked(stream, cmd, arg);
2449 mutex_unlock(&dev_priv->perf.lock);
2450
2451 return ret;
2452}
2453
Robert Bragg16d98b32016-12-07 21:40:33 +00002454/**
2455 * i915_perf_destroy_locked - destroy an i915 perf stream
2456 * @stream: An i915 perf stream
2457 *
2458 * Frees all resources associated with the given i915 perf @stream, disabling
2459 * any associated data capture in the process.
2460 *
2461 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2462 * with any non-file-operation driver hooks.
2463 */
Robert Braggeec688e2016-11-07 19:49:47 +00002464static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
2465{
Robert Braggeec688e2016-11-07 19:49:47 +00002466 if (stream->enabled)
2467 i915_perf_disable_locked(stream);
2468
2469 if (stream->ops->destroy)
2470 stream->ops->destroy(stream);
2471
2472 list_del(&stream->link);
2473
Chris Wilson69df05e2016-12-18 15:37:21 +00002474 if (stream->ctx)
Chris Wilson5f09a9c2017-06-20 12:05:46 +01002475 i915_gem_context_put(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00002476
2477 kfree(stream);
2478}
2479
Robert Bragg16d98b32016-12-07 21:40:33 +00002480/**
2481 * i915_perf_release - handles userspace close() of a stream file
2482 * @inode: anonymous inode associated with file
2483 * @file: An i915 perf stream file
2484 *
2485 * Cleans up any resources associated with an open i915 perf stream file.
2486 *
2487 * NB: close() can't really fail from the userspace point of view.
2488 *
2489 * Returns: zero on success or a negative error code.
2490 */
Robert Braggeec688e2016-11-07 19:49:47 +00002491static int i915_perf_release(struct inode *inode, struct file *file)
2492{
2493 struct i915_perf_stream *stream = file->private_data;
2494 struct drm_i915_private *dev_priv = stream->dev_priv;
2495
2496 mutex_lock(&dev_priv->perf.lock);
2497 i915_perf_destroy_locked(stream);
2498 mutex_unlock(&dev_priv->perf.lock);
2499
2500 return 0;
2501}
2502
2503
2504static const struct file_operations fops = {
2505 .owner = THIS_MODULE,
2506 .llseek = no_llseek,
2507 .release = i915_perf_release,
2508 .poll = i915_perf_poll,
2509 .read = i915_perf_read,
2510 .unlocked_ioctl = i915_perf_ioctl,
Lionel Landwerlin191f8962017-10-24 16:27:28 +01002511 /* Our ioctl have no arguments, so it's safe to use the same function
2512 * to handle 32bits compatibility.
2513 */
2514 .compat_ioctl = i915_perf_ioctl,
Robert Braggeec688e2016-11-07 19:49:47 +00002515};
2516
2517
Robert Bragg16d98b32016-12-07 21:40:33 +00002518/**
2519 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
2520 * @dev_priv: i915 device instance
2521 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
2522 * @props: individually validated u64 property value pairs
2523 * @file: drm file
2524 *
2525 * See i915_perf_ioctl_open() for interface details.
2526 *
2527 * Implements further stream config validation and stream initialization on
2528 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
2529 * taken to serialize with any non-file-operation driver hooks.
2530 *
2531 * Note: at this point the @props have only been validated in isolation and
2532 * it's still necessary to validate that the combination of properties makes
2533 * sense.
2534 *
2535 * In the case where userspace is interested in OA unit metrics then further
2536 * config validation and stream initialization details will be handled by
2537 * i915_oa_stream_init(). The code here should only validate config state that
2538 * will be relevant to all stream types / backends.
2539 *
2540 * Returns: zero on success or a negative error code.
2541 */
Robert Braggeec688e2016-11-07 19:49:47 +00002542static int
2543i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
2544 struct drm_i915_perf_open_param *param,
2545 struct perf_open_properties *props,
2546 struct drm_file *file)
2547{
2548 struct i915_gem_context *specific_ctx = NULL;
2549 struct i915_perf_stream *stream = NULL;
2550 unsigned long f_flags = 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01002551 bool privileged_op = true;
Robert Braggeec688e2016-11-07 19:49:47 +00002552 int stream_fd;
2553 int ret;
2554
2555 if (props->single_context) {
2556 u32 ctx_handle = props->ctx_handle;
2557 struct drm_i915_file_private *file_priv = file->driver_priv;
2558
Imre Deak635f56c2017-07-14 18:12:41 +03002559 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
2560 if (!specific_ctx) {
2561 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
2562 ctx_handle);
2563 ret = -ENOENT;
Robert Braggeec688e2016-11-07 19:49:47 +00002564 goto err;
2565 }
2566 }
2567
Robert Bragg19f81df2017-06-13 12:23:03 +01002568 /*
2569 * On Haswell the OA unit supports clock gating off for a specific
2570 * context and in this mode there's no visibility of metrics for the
2571 * rest of the system, which we consider acceptable for a
2572 * non-privileged client.
2573 *
2574 * For Gen8+ the OA unit no longer supports clock gating off for a
2575 * specific context and the kernel can't securely stop the counters
2576 * from updating as system-wide / global values. Even though we can
2577 * filter reports based on the included context ID we can't block
2578 * clients from seeing the raw / global counter values via
2579 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
2580 * enable the OA unit by default.
2581 */
2582 if (IS_HASWELL(dev_priv) && specific_ctx)
2583 privileged_op = false;
2584
Robert Braggccdf6342016-11-07 19:49:54 +00002585 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
2586 * we check a dev.i915.perf_stream_paranoid sysctl option
2587 * to determine if it's ok to access system wide OA counters
2588 * without CAP_SYS_ADMIN privileges.
2589 */
Robert Bragg19f81df2017-06-13 12:23:03 +01002590 if (privileged_op &&
Robert Braggccdf6342016-11-07 19:49:54 +00002591 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00002592 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002593 ret = -EACCES;
2594 goto err_ctx;
2595 }
2596
2597 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
2598 if (!stream) {
2599 ret = -ENOMEM;
2600 goto err_ctx;
2601 }
2602
Robert Braggeec688e2016-11-07 19:49:47 +00002603 stream->dev_priv = dev_priv;
2604 stream->ctx = specific_ctx;
2605
Robert Braggd7965152016-11-07 19:49:52 +00002606 ret = i915_oa_stream_init(stream, param, props);
2607 if (ret)
2608 goto err_alloc;
2609
2610 /* we avoid simply assigning stream->sample_flags = props->sample_flags
2611 * to have _stream_init check the combination of sample flags more
2612 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00002613 */
Robert Braggd7965152016-11-07 19:49:52 +00002614 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
2615 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01002616 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00002617 }
Robert Braggeec688e2016-11-07 19:49:47 +00002618
2619 list_add(&stream->link, &dev_priv->perf.streams);
2620
2621 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
2622 f_flags |= O_CLOEXEC;
2623 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
2624 f_flags |= O_NONBLOCK;
2625
2626 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
2627 if (stream_fd < 0) {
2628 ret = stream_fd;
2629 goto err_open;
2630 }
2631
2632 if (!(param->flags & I915_PERF_FLAG_DISABLED))
2633 i915_perf_enable_locked(stream);
2634
2635 return stream_fd;
2636
2637err_open:
2638 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01002639err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00002640 if (stream->ops->destroy)
2641 stream->ops->destroy(stream);
2642err_alloc:
2643 kfree(stream);
2644err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00002645 if (specific_ctx)
Chris Wilson5f09a9c2017-06-20 12:05:46 +01002646 i915_gem_context_put(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00002647err:
2648 return ret;
2649}
2650
Robert Bragg155e9412017-06-13 12:23:05 +01002651static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
2652{
Lionel Landwerlin9f9b2792017-10-27 15:59:31 +01002653 return div64_u64(1000000000ULL * (2ULL << exponent),
Jani Nikula02584042018-12-31 16:56:41 +02002654 1000ULL * RUNTIME_INFO(dev_priv)->cs_timestamp_frequency_khz);
Robert Bragg155e9412017-06-13 12:23:05 +01002655}
2656
Robert Bragg16d98b32016-12-07 21:40:33 +00002657/**
2658 * read_properties_unlocked - validate + copy userspace stream open properties
2659 * @dev_priv: i915 device instance
2660 * @uprops: The array of u64 key value pairs given by userspace
2661 * @n_props: The number of key value pairs expected in @uprops
2662 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00002663 *
2664 * Note this function only validates properties in isolation it doesn't
2665 * validate that the combination of properties makes sense or that all
2666 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00002667 *
2668 * Note that there currently aren't any ordering requirements for properties so
2669 * we shouldn't validate or assume anything about ordering here. This doesn't
2670 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00002671 */
2672static int read_properties_unlocked(struct drm_i915_private *dev_priv,
2673 u64 __user *uprops,
2674 u32 n_props,
2675 struct perf_open_properties *props)
2676{
2677 u64 __user *uprop = uprops;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002678 u32 i;
Robert Braggeec688e2016-11-07 19:49:47 +00002679
2680 memset(props, 0, sizeof(struct perf_open_properties));
2681
2682 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00002683 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002684 return -EINVAL;
2685 }
2686
2687 /* Considering that ID = 0 is reserved and assuming that we don't
2688 * (currently) expect any configurations to ever specify duplicate
2689 * values for a particular property ID then the last _PROP_MAX value is
2690 * one greater than the maximum number of properties we expect to get
2691 * from userspace.
2692 */
2693 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00002694 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002695 return -EINVAL;
2696 }
2697
2698 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00002699 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00002700 u64 id, value;
2701 int ret;
2702
2703 ret = get_user(id, uprop);
2704 if (ret)
2705 return ret;
2706
2707 ret = get_user(value, uprop + 1);
2708 if (ret)
2709 return ret;
2710
Matthew Auld0a309f92017-03-27 21:32:36 +01002711 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
2712 DRM_DEBUG("Unknown i915 perf property ID\n");
2713 return -EINVAL;
2714 }
2715
Robert Braggeec688e2016-11-07 19:49:47 +00002716 switch ((enum drm_i915_perf_property_id)id) {
2717 case DRM_I915_PERF_PROP_CTX_HANDLE:
2718 props->single_context = 1;
2719 props->ctx_handle = value;
2720 break;
Robert Braggd7965152016-11-07 19:49:52 +00002721 case DRM_I915_PERF_PROP_SAMPLE_OA:
Lionel Landwerlinb6dd47b2018-03-26 10:08:22 +01002722 if (value)
2723 props->sample_flags |= SAMPLE_OA_REPORT;
Robert Braggd7965152016-11-07 19:49:52 +00002724 break;
2725 case DRM_I915_PERF_PROP_OA_METRICS_SET:
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002726 if (value == 0) {
Robert Bragg77085502016-12-01 17:21:52 +00002727 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00002728 return -EINVAL;
2729 }
2730 props->metrics_set = value;
2731 break;
2732 case DRM_I915_PERF_PROP_OA_FORMAT:
2733 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg52c57c22017-05-11 16:43:29 +01002734 DRM_DEBUG("Out-of-range OA report format %llu\n",
2735 value);
Robert Braggd7965152016-11-07 19:49:52 +00002736 return -EINVAL;
2737 }
2738 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg52c57c22017-05-11 16:43:29 +01002739 DRM_DEBUG("Unsupported OA report format %llu\n",
2740 value);
Robert Braggd7965152016-11-07 19:49:52 +00002741 return -EINVAL;
2742 }
2743 props->oa_format = value;
2744 break;
2745 case DRM_I915_PERF_PROP_OA_EXPONENT:
2746 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00002747 DRM_DEBUG("OA timer exponent too high (> %u)\n",
2748 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00002749 return -EINVAL;
2750 }
2751
Robert Bragg00319ba2016-11-07 19:49:55 +00002752 /* Theoretically we can program the OA unit to sample
Robert Bragg155e9412017-06-13 12:23:05 +01002753 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
2754 * for BXT. We don't allow such high sampling
2755 * frequencies by default unless root.
Robert Braggd7965152016-11-07 19:49:52 +00002756 */
Robert Bragg155e9412017-06-13 12:23:05 +01002757
Robert Bragg00319ba2016-11-07 19:49:55 +00002758 BUILD_BUG_ON(sizeof(oa_period) != 8);
Robert Bragg155e9412017-06-13 12:23:05 +01002759 oa_period = oa_exponent_to_ns(dev_priv, value);
Robert Bragg00319ba2016-11-07 19:49:55 +00002760
2761 /* This check is primarily to ensure that oa_period <=
2762 * UINT32_MAX (before passing to do_div which only
2763 * accepts a u32 denominator), but we can also skip
2764 * checking anything < 1Hz which implicitly can't be
2765 * limited via an integer oa_max_sample_rate.
2766 */
2767 if (oa_period <= NSEC_PER_SEC) {
2768 u64 tmp = NSEC_PER_SEC;
2769 do_div(tmp, oa_period);
2770 oa_freq_hz = tmp;
2771 } else
2772 oa_freq_hz = 0;
2773
2774 if (oa_freq_hz > i915_oa_max_sample_rate &&
2775 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00002776 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 +00002777 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00002778 return -EACCES;
2779 }
2780
2781 props->oa_periodic = true;
2782 props->oa_period_exponent = value;
2783 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01002784 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00002785 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00002786 return -EINVAL;
2787 }
2788
2789 uprop += 2;
2790 }
2791
2792 return 0;
2793}
2794
Robert Bragg16d98b32016-12-07 21:40:33 +00002795/**
2796 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
2797 * @dev: drm device
2798 * @data: ioctl data copied from userspace (unvalidated)
2799 * @file: drm file
2800 *
2801 * Validates the stream open parameters given by userspace including flags
2802 * and an array of u64 key, value pair properties.
2803 *
2804 * Very little is assumed up front about the nature of the stream being
2805 * opened (for instance we don't assume it's for periodic OA unit metrics). An
2806 * i915-perf stream is expected to be a suitable interface for other forms of
2807 * buffered data written by the GPU besides periodic OA metrics.
2808 *
2809 * Note we copy the properties from userspace outside of the i915 perf
2810 * mutex to avoid an awkward lockdep with mmap_sem.
2811 *
2812 * Most of the implementation details are handled by
2813 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
2814 * mutex for serializing with any non-file-operation driver hooks.
2815 *
2816 * Return: A newly opened i915 Perf stream file descriptor or negative
2817 * error code on failure.
2818 */
Robert Braggeec688e2016-11-07 19:49:47 +00002819int i915_perf_open_ioctl(struct drm_device *dev, void *data,
2820 struct drm_file *file)
2821{
2822 struct drm_i915_private *dev_priv = dev->dev_private;
2823 struct drm_i915_perf_open_param *param = data;
2824 struct perf_open_properties props;
2825 u32 known_open_flags;
2826 int ret;
2827
2828 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00002829 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002830 return -ENOTSUPP;
2831 }
2832
2833 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
2834 I915_PERF_FLAG_FD_NONBLOCK |
2835 I915_PERF_FLAG_DISABLED;
2836 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00002837 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002838 return -EINVAL;
2839 }
2840
2841 ret = read_properties_unlocked(dev_priv,
2842 u64_to_user_ptr(param->properties_ptr),
2843 param->num_properties,
2844 &props);
2845 if (ret)
2846 return ret;
2847
2848 mutex_lock(&dev_priv->perf.lock);
2849 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
2850 mutex_unlock(&dev_priv->perf.lock);
2851
2852 return ret;
2853}
2854
Robert Bragg16d98b32016-12-07 21:40:33 +00002855/**
2856 * i915_perf_register - exposes i915-perf to userspace
2857 * @dev_priv: i915 device instance
2858 *
2859 * In particular OA metric sets are advertised under a sysfs metrics/
2860 * directory allowing userspace to enumerate valid IDs that can be
2861 * used to open an i915-perf stream.
2862 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002863void i915_perf_register(struct drm_i915_private *dev_priv)
2864{
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002865 int ret;
2866
Robert Bragg442b8c02016-11-07 19:49:53 +00002867 if (!dev_priv->perf.initialized)
2868 return;
2869
2870 /* To be sure we're synchronized with an attempted
2871 * i915_perf_open_ioctl(); considering that we register after
2872 * being exposed to userspace.
2873 */
2874 mutex_lock(&dev_priv->perf.lock);
2875
2876 dev_priv->perf.metrics_kobj =
2877 kobject_create_and_add("metrics",
2878 &dev_priv->drm.primary->kdev->kobj);
2879 if (!dev_priv->perf.metrics_kobj)
2880 goto exit;
2881
Chris Wilson40f75ea2017-08-10 18:57:41 +01002882 sysfs_attr_init(&dev_priv->perf.oa.test_config.sysfs_metric_id.attr);
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002883
Rodrigo Vivi2dd24a92019-03-08 13:42:58 -08002884 if (INTEL_GEN(dev_priv) >= 11) {
Rodrigo Vivi993298a2019-03-01 09:27:03 -08002885 i915_perf_load_test_config_icl(dev_priv);
2886 } else if (IS_CANNONLAKE(dev_priv)) {
2887 i915_perf_load_test_config_cnl(dev_priv);
2888 } else if (IS_COFFEELAKE(dev_priv)) {
2889 if (IS_CFL_GT2(dev_priv))
2890 i915_perf_load_test_config_cflgt2(dev_priv);
2891 if (IS_CFL_GT3(dev_priv))
2892 i915_perf_load_test_config_cflgt3(dev_priv);
2893 } else if (IS_GEMINILAKE(dev_priv)) {
2894 i915_perf_load_test_config_glk(dev_priv);
2895 } else if (IS_KABYLAKE(dev_priv)) {
2896 if (IS_KBL_GT2(dev_priv))
2897 i915_perf_load_test_config_kblgt2(dev_priv);
2898 else if (IS_KBL_GT3(dev_priv))
2899 i915_perf_load_test_config_kblgt3(dev_priv);
2900 } else if (IS_BROXTON(dev_priv)) {
2901 i915_perf_load_test_config_bxt(dev_priv);
Robert Bragg19f81df2017-06-13 12:23:03 +01002902 } else if (IS_SKYLAKE(dev_priv)) {
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002903 if (IS_SKL_GT2(dev_priv))
2904 i915_perf_load_test_config_sklgt2(dev_priv);
2905 else if (IS_SKL_GT3(dev_priv))
2906 i915_perf_load_test_config_sklgt3(dev_priv);
2907 else if (IS_SKL_GT4(dev_priv))
2908 i915_perf_load_test_config_sklgt4(dev_priv);
Rodrigo Vivi993298a2019-03-01 09:27:03 -08002909 } else if (IS_CHERRYVIEW(dev_priv)) {
2910 i915_perf_load_test_config_chv(dev_priv);
2911 } else if (IS_BROADWELL(dev_priv)) {
2912 i915_perf_load_test_config_bdw(dev_priv);
2913 } else if (IS_HASWELL(dev_priv)) {
2914 i915_perf_load_test_config_hsw(dev_priv);
2915}
Robert Bragg442b8c02016-11-07 19:49:53 +00002916
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002917 if (dev_priv->perf.oa.test_config.id == 0)
2918 goto sysfs_error;
2919
2920 ret = sysfs_create_group(dev_priv->perf.metrics_kobj,
2921 &dev_priv->perf.oa.test_config.sysfs_metric);
2922 if (ret)
2923 goto sysfs_error;
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002924
2925 atomic_set(&dev_priv->perf.oa.test_config.ref_count, 1);
2926
Robert Bragg19f81df2017-06-13 12:23:03 +01002927 goto exit;
2928
2929sysfs_error:
2930 kobject_put(dev_priv->perf.metrics_kobj);
2931 dev_priv->perf.metrics_kobj = NULL;
2932
Robert Bragg442b8c02016-11-07 19:49:53 +00002933exit:
2934 mutex_unlock(&dev_priv->perf.lock);
2935}
2936
Robert Bragg16d98b32016-12-07 21:40:33 +00002937/**
2938 * i915_perf_unregister - hide i915-perf from userspace
2939 * @dev_priv: i915 device instance
2940 *
2941 * i915-perf state cleanup is split up into an 'unregister' and
2942 * 'deinit' phase where the interface is first hidden from
2943 * userspace by i915_perf_unregister() before cleaning up
2944 * remaining state in i915_perf_fini().
2945 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002946void i915_perf_unregister(struct drm_i915_private *dev_priv)
2947{
Robert Bragg442b8c02016-11-07 19:49:53 +00002948 if (!dev_priv->perf.metrics_kobj)
2949 return;
2950
Lionel Landwerlin701f8232017-08-03 17:58:08 +01002951 sysfs_remove_group(dev_priv->perf.metrics_kobj,
2952 &dev_priv->perf.oa.test_config.sysfs_metric);
Robert Bragg442b8c02016-11-07 19:49:53 +00002953
2954 kobject_put(dev_priv->perf.metrics_kobj);
2955 dev_priv->perf.metrics_kobj = NULL;
2956}
2957
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002958static bool gen8_is_valid_flex_addr(struct drm_i915_private *dev_priv, u32 addr)
2959{
2960 static const i915_reg_t flex_eu_regs[] = {
2961 EU_PERF_CNTL0,
2962 EU_PERF_CNTL1,
2963 EU_PERF_CNTL2,
2964 EU_PERF_CNTL3,
2965 EU_PERF_CNTL4,
2966 EU_PERF_CNTL5,
2967 EU_PERF_CNTL6,
2968 };
2969 int i;
2970
2971 for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00002972 if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002973 return true;
2974 }
2975 return false;
2976}
2977
2978static bool gen7_is_valid_b_counter_addr(struct drm_i915_private *dev_priv, u32 addr)
2979{
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00002980 return (addr >= i915_mmio_reg_offset(OASTARTTRIG1) &&
2981 addr <= i915_mmio_reg_offset(OASTARTTRIG8)) ||
2982 (addr >= i915_mmio_reg_offset(OAREPORTTRIG1) &&
2983 addr <= i915_mmio_reg_offset(OAREPORTTRIG8)) ||
2984 (addr >= i915_mmio_reg_offset(OACEC0_0) &&
2985 addr <= i915_mmio_reg_offset(OACEC7_1));
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002986}
2987
2988static bool gen7_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
2989{
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00002990 return addr == i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) ||
2991 (addr >= i915_mmio_reg_offset(MICRO_BP0_0) &&
2992 addr <= i915_mmio_reg_offset(NOA_WRITE)) ||
2993 (addr >= i915_mmio_reg_offset(OA_PERFCNT1_LO) &&
2994 addr <= i915_mmio_reg_offset(OA_PERFCNT2_HI)) ||
2995 (addr >= i915_mmio_reg_offset(OA_PERFMATRIX_LO) &&
2996 addr <= i915_mmio_reg_offset(OA_PERFMATRIX_HI));
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01002997}
2998
2999static bool gen8_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3000{
3001 return gen7_is_valid_mux_addr(dev_priv, addr) ||
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00003002 addr == i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) ||
3003 (addr >= i915_mmio_reg_offset(RPM_CONFIG0) &&
3004 addr <= i915_mmio_reg_offset(NOA_CONFIG(8)));
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003005}
3006
Lionel Landwerlin95690a02017-11-10 19:08:43 +00003007static bool gen10_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3008{
3009 return gen8_is_valid_mux_addr(dev_priv, addr) ||
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00003010 (addr >= i915_mmio_reg_offset(OA_PERFCNT3_LO) &&
3011 addr <= i915_mmio_reg_offset(OA_PERFCNT4_HI));
Lionel Landwerlin95690a02017-11-10 19:08:43 +00003012}
3013
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003014static 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) ||
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00003018 (addr >= i915_mmio_reg_offset(HSW_MBVID2_NOA0) &&
3019 addr <= i915_mmio_reg_offset(HSW_MBVID2_NOA9)) ||
3020 addr == i915_mmio_reg_offset(HSW_MBVID2_MISR0);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003021}
3022
3023static bool chv_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
3024{
3025 return gen7_is_valid_mux_addr(dev_priv, addr) ||
3026 (addr >= 0x182300 && addr <= 0x1823A4);
3027}
3028
Jani Nikula739f3ab2019-01-16 11:15:19 +02003029static u32 mask_reg_value(u32 reg, u32 val)
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003030{
3031 /* HALF_SLICE_CHICKEN2 is programmed with a the
3032 * WaDisableSTUnitPowerOptimization workaround. Make sure the value
3033 * programmed by userspace doesn't change this.
3034 */
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00003035 if (i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) == reg)
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003036 val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
3037
3038 /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
3039 * indicated by its name and a bunch of selection fields used by OA
3040 * configs.
3041 */
Lionel Landwerlin7c52a222017-11-13 23:34:52 +00003042 if (i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) == reg)
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003043 val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
3044
3045 return val;
3046}
3047
3048static struct i915_oa_reg *alloc_oa_regs(struct drm_i915_private *dev_priv,
3049 bool (*is_valid)(struct drm_i915_private *dev_priv, u32 addr),
3050 u32 __user *regs,
3051 u32 n_regs)
3052{
3053 struct i915_oa_reg *oa_regs;
3054 int err;
3055 u32 i;
3056
3057 if (!n_regs)
3058 return NULL;
3059
Linus Torvalds96d4f262019-01-03 18:57:57 -08003060 if (!access_ok(regs, n_regs * sizeof(u32) * 2))
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003061 return ERR_PTR(-EFAULT);
3062
3063 /* No is_valid function means we're not allowing any register to be programmed. */
3064 GEM_BUG_ON(!is_valid);
3065 if (!is_valid)
3066 return ERR_PTR(-EINVAL);
3067
3068 oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
3069 if (!oa_regs)
3070 return ERR_PTR(-ENOMEM);
3071
3072 for (i = 0; i < n_regs; i++) {
3073 u32 addr, value;
3074
3075 err = get_user(addr, regs);
3076 if (err)
3077 goto addr_err;
3078
3079 if (!is_valid(dev_priv, addr)) {
3080 DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
3081 err = -EINVAL;
3082 goto addr_err;
3083 }
3084
3085 err = get_user(value, regs + 1);
3086 if (err)
3087 goto addr_err;
3088
3089 oa_regs[i].addr = _MMIO(addr);
3090 oa_regs[i].value = mask_reg_value(addr, value);
3091
3092 regs += 2;
3093 }
3094
3095 return oa_regs;
3096
3097addr_err:
3098 kfree(oa_regs);
3099 return ERR_PTR(err);
3100}
3101
3102static ssize_t show_dynamic_id(struct device *dev,
3103 struct device_attribute *attr,
3104 char *buf)
3105{
3106 struct i915_oa_config *oa_config =
3107 container_of(attr, typeof(*oa_config), sysfs_metric_id);
3108
3109 return sprintf(buf, "%d\n", oa_config->id);
3110}
3111
3112static int create_dynamic_oa_sysfs_entry(struct drm_i915_private *dev_priv,
3113 struct i915_oa_config *oa_config)
3114{
Chris Wilson28152a22017-08-03 23:37:00 +01003115 sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003116 oa_config->sysfs_metric_id.attr.name = "id";
3117 oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
3118 oa_config->sysfs_metric_id.show = show_dynamic_id;
3119 oa_config->sysfs_metric_id.store = NULL;
3120
3121 oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
3122 oa_config->attrs[1] = NULL;
3123
3124 oa_config->sysfs_metric.name = oa_config->uuid;
3125 oa_config->sysfs_metric.attrs = oa_config->attrs;
3126
3127 return sysfs_create_group(dev_priv->perf.metrics_kobj,
3128 &oa_config->sysfs_metric);
3129}
3130
3131/**
3132 * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
3133 * @dev: drm device
3134 * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
3135 * userspace (unvalidated)
3136 * @file: drm file
3137 *
3138 * Validates the submitted OA register to be saved into a new OA config that
3139 * can then be used for programming the OA unit and its NOA network.
3140 *
3141 * Returns: A new allocated config number to be used with the perf open ioctl
3142 * or a negative error code on failure.
3143 */
3144int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
3145 struct drm_file *file)
3146{
3147 struct drm_i915_private *dev_priv = dev->dev_private;
3148 struct drm_i915_perf_oa_config *args = data;
3149 struct i915_oa_config *oa_config, *tmp;
3150 int err, id;
3151
3152 if (!dev_priv->perf.initialized) {
3153 DRM_DEBUG("i915 perf interface not available for this system\n");
3154 return -ENOTSUPP;
3155 }
3156
3157 if (!dev_priv->perf.metrics_kobj) {
3158 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
3159 return -EINVAL;
3160 }
3161
3162 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3163 DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
3164 return -EACCES;
3165 }
3166
3167 if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
3168 (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
3169 (!args->flex_regs_ptr || !args->n_flex_regs)) {
3170 DRM_DEBUG("No OA registers given\n");
3171 return -EINVAL;
3172 }
3173
3174 oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
3175 if (!oa_config) {
3176 DRM_DEBUG("Failed to allocate memory for the OA config\n");
3177 return -ENOMEM;
3178 }
3179
3180 atomic_set(&oa_config->ref_count, 1);
3181
3182 if (!uuid_is_valid(args->uuid)) {
3183 DRM_DEBUG("Invalid uuid format for OA config\n");
3184 err = -EINVAL;
3185 goto reg_err;
3186 }
3187
3188 /* Last character in oa_config->uuid will be 0 because oa_config is
3189 * kzalloc.
3190 */
3191 memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
3192
3193 oa_config->mux_regs_len = args->n_mux_regs;
3194 oa_config->mux_regs =
3195 alloc_oa_regs(dev_priv,
3196 dev_priv->perf.oa.ops.is_valid_mux_reg,
3197 u64_to_user_ptr(args->mux_regs_ptr),
3198 args->n_mux_regs);
3199
3200 if (IS_ERR(oa_config->mux_regs)) {
3201 DRM_DEBUG("Failed to create OA config for mux_regs\n");
3202 err = PTR_ERR(oa_config->mux_regs);
3203 goto reg_err;
3204 }
3205
3206 oa_config->b_counter_regs_len = args->n_boolean_regs;
3207 oa_config->b_counter_regs =
3208 alloc_oa_regs(dev_priv,
3209 dev_priv->perf.oa.ops.is_valid_b_counter_reg,
3210 u64_to_user_ptr(args->boolean_regs_ptr),
3211 args->n_boolean_regs);
3212
3213 if (IS_ERR(oa_config->b_counter_regs)) {
3214 DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
3215 err = PTR_ERR(oa_config->b_counter_regs);
3216 goto reg_err;
3217 }
3218
3219 if (INTEL_GEN(dev_priv) < 8) {
3220 if (args->n_flex_regs != 0) {
3221 err = -EINVAL;
3222 goto reg_err;
3223 }
3224 } else {
3225 oa_config->flex_regs_len = args->n_flex_regs;
3226 oa_config->flex_regs =
3227 alloc_oa_regs(dev_priv,
3228 dev_priv->perf.oa.ops.is_valid_flex_reg,
3229 u64_to_user_ptr(args->flex_regs_ptr),
3230 args->n_flex_regs);
3231
3232 if (IS_ERR(oa_config->flex_regs)) {
3233 DRM_DEBUG("Failed to create OA config for flex_regs\n");
3234 err = PTR_ERR(oa_config->flex_regs);
3235 goto reg_err;
3236 }
3237 }
3238
3239 err = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
3240 if (err)
3241 goto reg_err;
3242
3243 /* We shouldn't have too many configs, so this iteration shouldn't be
3244 * too costly.
3245 */
3246 idr_for_each_entry(&dev_priv->perf.metrics_idr, tmp, id) {
3247 if (!strcmp(tmp->uuid, oa_config->uuid)) {
3248 DRM_DEBUG("OA config already exists with this uuid\n");
3249 err = -EADDRINUSE;
3250 goto sysfs_err;
3251 }
3252 }
3253
3254 err = create_dynamic_oa_sysfs_entry(dev_priv, oa_config);
3255 if (err) {
3256 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3257 goto sysfs_err;
3258 }
3259
3260 /* Config id 0 is invalid, id 1 for kernel stored test config. */
3261 oa_config->id = idr_alloc(&dev_priv->perf.metrics_idr,
3262 oa_config, 2,
3263 0, GFP_KERNEL);
3264 if (oa_config->id < 0) {
3265 DRM_DEBUG("Failed to create sysfs entry for OA config\n");
3266 err = oa_config->id;
3267 goto sysfs_err;
3268 }
3269
3270 mutex_unlock(&dev_priv->perf.metrics_lock);
3271
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01003272 DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id);
3273
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003274 return oa_config->id;
3275
3276sysfs_err:
3277 mutex_unlock(&dev_priv->perf.metrics_lock);
3278reg_err:
3279 put_oa_config(dev_priv, oa_config);
3280 DRM_DEBUG("Failed to add new OA config\n");
3281 return err;
3282}
3283
3284/**
3285 * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
3286 * @dev: drm device
3287 * @data: ioctl data (pointer to u64 integer) copied from userspace
3288 * @file: drm file
3289 *
3290 * Configs can be removed while being used, the will stop appearing in sysfs
3291 * and their content will be freed when the stream using the config is closed.
3292 *
3293 * Returns: 0 on success or a negative error code on failure.
3294 */
3295int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
3296 struct drm_file *file)
3297{
3298 struct drm_i915_private *dev_priv = dev->dev_private;
3299 u64 *arg = data;
3300 struct i915_oa_config *oa_config;
3301 int ret;
3302
3303 if (!dev_priv->perf.initialized) {
3304 DRM_DEBUG("i915 perf interface not available for this system\n");
3305 return -ENOTSUPP;
3306 }
3307
3308 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
3309 DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
3310 return -EACCES;
3311 }
3312
3313 ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
3314 if (ret)
3315 goto lock_err;
3316
3317 oa_config = idr_find(&dev_priv->perf.metrics_idr, *arg);
3318 if (!oa_config) {
3319 DRM_DEBUG("Failed to remove unknown OA config\n");
3320 ret = -ENOENT;
3321 goto config_err;
3322 }
3323
3324 GEM_BUG_ON(*arg != oa_config->id);
3325
3326 sysfs_remove_group(dev_priv->perf.metrics_kobj,
3327 &oa_config->sysfs_metric);
3328
3329 idr_remove(&dev_priv->perf.metrics_idr, *arg);
Lionel Landwerlin9bd9be62018-03-26 10:08:28 +01003330
3331 DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
3332
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003333 put_oa_config(dev_priv, oa_config);
3334
3335config_err:
3336 mutex_unlock(&dev_priv->perf.metrics_lock);
3337lock_err:
3338 return ret;
3339}
3340
Robert Braggccdf6342016-11-07 19:49:54 +00003341static struct ctl_table oa_table[] = {
3342 {
3343 .procname = "perf_stream_paranoid",
3344 .data = &i915_perf_stream_paranoid,
3345 .maxlen = sizeof(i915_perf_stream_paranoid),
3346 .mode = 0644,
3347 .proc_handler = proc_dointvec_minmax,
3348 .extra1 = &zero,
3349 .extra2 = &one,
3350 },
Robert Bragg00319ba2016-11-07 19:49:55 +00003351 {
3352 .procname = "oa_max_sample_rate",
3353 .data = &i915_oa_max_sample_rate,
3354 .maxlen = sizeof(i915_oa_max_sample_rate),
3355 .mode = 0644,
3356 .proc_handler = proc_dointvec_minmax,
3357 .extra1 = &zero,
3358 .extra2 = &oa_sample_rate_hard_limit,
3359 },
Robert Braggccdf6342016-11-07 19:49:54 +00003360 {}
3361};
3362
3363static struct ctl_table i915_root[] = {
3364 {
3365 .procname = "i915",
3366 .maxlen = 0,
3367 .mode = 0555,
3368 .child = oa_table,
3369 },
3370 {}
3371};
3372
3373static struct ctl_table dev_root[] = {
3374 {
3375 .procname = "dev",
3376 .maxlen = 0,
3377 .mode = 0555,
3378 .child = i915_root,
3379 },
3380 {}
3381};
3382
Robert Bragg16d98b32016-12-07 21:40:33 +00003383/**
3384 * i915_perf_init - initialize i915-perf state on module load
3385 * @dev_priv: i915 device instance
3386 *
3387 * Initializes i915-perf state without exposing anything to userspace.
3388 *
3389 * Note: i915-perf initialization is split into an 'init' and 'register'
3390 * phase with the i915_perf_register() exposing state to userspace.
3391 */
Robert Braggeec688e2016-11-07 19:49:47 +00003392void i915_perf_init(struct drm_i915_private *dev_priv)
3393{
Robert Bragg19f81df2017-06-13 12:23:03 +01003394 if (IS_HASWELL(dev_priv)) {
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003395 dev_priv->perf.oa.ops.is_valid_b_counter_reg =
3396 gen7_is_valid_b_counter_addr;
3397 dev_priv->perf.oa.ops.is_valid_mux_reg =
3398 hsw_is_valid_mux_addr;
3399 dev_priv->perf.oa.ops.is_valid_flex_reg = NULL;
Robert Bragg19f81df2017-06-13 12:23:03 +01003400 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
3401 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
3402 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
3403 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
3404 dev_priv->perf.oa.ops.read = gen7_oa_read;
3405 dev_priv->perf.oa.ops.oa_hw_tail_read =
3406 gen7_oa_hw_tail_read;
Robert Braggd7965152016-11-07 19:49:52 +00003407
Robert Bragg19f81df2017-06-13 12:23:03 +01003408 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
Chris Wilsonfb5c5512017-11-20 20:55:00 +00003409 } else if (HAS_LOGICAL_RING_CONTEXTS(dev_priv)) {
Robert Bragg19f81df2017-06-13 12:23:03 +01003410 /* Note: that although we could theoretically also support the
3411 * legacy ringbuffer mode on BDW (and earlier iterations of
3412 * this driver, before upstreaming did this) it didn't seem
3413 * worth the complexity to maintain now that BDW+ enable
3414 * execlist mode by default.
3415 */
Lionel Landwerlinba6b7c12017-11-10 19:08:41 +00003416 dev_priv->perf.oa.oa_formats = gen8_plus_oa_formats;
Robert Braggd7965152016-11-07 19:49:52 +00003417
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003418 dev_priv->perf.oa.ops.oa_enable = gen8_oa_enable;
3419 dev_priv->perf.oa.ops.oa_disable = gen8_oa_disable;
3420 dev_priv->perf.oa.ops.read = gen8_oa_read;
3421 dev_priv->perf.oa.ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
3422
Lucas De Marchif3ce44a2018-12-12 10:10:44 -08003423 if (IS_GEN_RANGE(dev_priv, 8, 9)) {
Lionel Landwerlinba6b7c12017-11-10 19:08:41 +00003424 dev_priv->perf.oa.ops.is_valid_b_counter_reg =
3425 gen7_is_valid_b_counter_addr;
3426 dev_priv->perf.oa.ops.is_valid_mux_reg =
3427 gen8_is_valid_mux_addr;
3428 dev_priv->perf.oa.ops.is_valid_flex_reg =
3429 gen8_is_valid_flex_addr;
Lionel Landwerlin701f8232017-08-03 17:58:08 +01003430
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003431 if (IS_CHERRYVIEW(dev_priv)) {
3432 dev_priv->perf.oa.ops.is_valid_mux_reg =
3433 chv_is_valid_mux_addr;
3434 }
Robert Bragg155e9412017-06-13 12:23:05 +01003435
Lionel Landwerlinba6b7c12017-11-10 19:08:41 +00003436 dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set;
3437 dev_priv->perf.oa.ops.disable_metric_set = gen8_disable_metric_set;
3438
Lucas De Marchicf819ef2018-12-12 10:10:43 -08003439 if (IS_GEN(dev_priv, 8)) {
Lionel Landwerlinba6b7c12017-11-10 19:08:41 +00003440 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x120;
3441 dev_priv->perf.oa.ctx_flexeu0_offset = 0x2ce;
3442
3443 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<25);
3444 } else {
3445 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
3446 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
3447
3448 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
3449 }
Lucas De Marchi00690002018-12-12 10:10:42 -08003450 } else if (IS_GEN_RANGE(dev_priv, 10, 11)) {
Lionel Landwerlin95690a02017-11-10 19:08:43 +00003451 dev_priv->perf.oa.ops.is_valid_b_counter_reg =
3452 gen7_is_valid_b_counter_addr;
3453 dev_priv->perf.oa.ops.is_valid_mux_reg =
3454 gen10_is_valid_mux_addr;
3455 dev_priv->perf.oa.ops.is_valid_flex_reg =
3456 gen8_is_valid_flex_addr;
3457
3458 dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set;
3459 dev_priv->perf.oa.ops.disable_metric_set = gen10_disable_metric_set;
3460
3461 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
3462 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
3463
3464 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
Robert Bragg19f81df2017-06-13 12:23:03 +01003465 }
Robert Bragg19f81df2017-06-13 12:23:03 +01003466 }
3467
Lionel Landwerlin9f9b2792017-10-27 15:59:31 +01003468 if (dev_priv->perf.oa.ops.enable_metric_set) {
Robert Bragg19f81df2017-06-13 12:23:03 +01003469 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
3470 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3471 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
3472 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
3473
3474 INIT_LIST_HEAD(&dev_priv->perf.streams);
3475 mutex_init(&dev_priv->perf.lock);
Robert Bragg19f81df2017-06-13 12:23:03 +01003476 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
3477
Lionel Landwerlin9f9b2792017-10-27 15:59:31 +01003478 oa_sample_rate_hard_limit = 1000 *
Jani Nikula02584042018-12-31 16:56:41 +02003479 (RUNTIME_INFO(dev_priv)->cs_timestamp_frequency_khz / 2);
Robert Bragg19f81df2017-06-13 12:23:03 +01003480 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
3481
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003482 mutex_init(&dev_priv->perf.metrics_lock);
3483 idr_init(&dev_priv->perf.metrics_idr);
3484
Robert Bragg19f81df2017-06-13 12:23:03 +01003485 dev_priv->perf.initialized = true;
3486 }
Robert Braggeec688e2016-11-07 19:49:47 +00003487}
3488
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003489static int destroy_config(int id, void *p, void *data)
3490{
3491 struct drm_i915_private *dev_priv = data;
3492 struct i915_oa_config *oa_config = p;
3493
3494 put_oa_config(dev_priv, oa_config);
3495
3496 return 0;
3497}
3498
Robert Bragg16d98b32016-12-07 21:40:33 +00003499/**
3500 * i915_perf_fini - Counter part to i915_perf_init()
3501 * @dev_priv: i915 device instance
3502 */
Robert Braggeec688e2016-11-07 19:49:47 +00003503void i915_perf_fini(struct drm_i915_private *dev_priv)
3504{
3505 if (!dev_priv->perf.initialized)
3506 return;
3507
Lionel Landwerlinf89823c2017-08-03 18:05:50 +01003508 idr_for_each(&dev_priv->perf.metrics_idr, destroy_config, dev_priv);
3509 idr_destroy(&dev_priv->perf.metrics_idr);
3510
Robert Braggccdf6342016-11-07 19:49:54 +00003511 unregister_sysctl_table(dev_priv->perf.sysctl_header);
3512
Robert Braggd7965152016-11-07 19:49:52 +00003513 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Bragg19f81df2017-06-13 12:23:03 +01003514
Robert Braggeec688e2016-11-07 19:49:47 +00003515 dev_priv->perf.initialized = false;
3516}