blob: a6af4d7dc4d6af9b0dfe4a830daaa85951bba318 [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>
Robert Braggeec688e2016-11-07 19:49:47 +0000196
197#include "i915_drv.h"
Robert Braggd7965152016-11-07 19:49:52 +0000198#include "i915_oa_hsw.h"
Robert Bragg19f81df2017-06-13 12:23:03 +0100199#include "i915_oa_bdw.h"
200#include "i915_oa_chv.h"
201#include "i915_oa_sklgt2.h"
202#include "i915_oa_sklgt3.h"
203#include "i915_oa_sklgt4.h"
204#include "i915_oa_bxt.h"
Robert Braggd7965152016-11-07 19:49:52 +0000205
206/* HW requires this to be a power of two, between 128k and 16M, though driver
207 * is currently generally designed assuming the largest 16M size is used such
208 * that the overflow cases are unlikely in normal operation.
209 */
210#define OA_BUFFER_SIZE SZ_16M
211
212#define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
213
Robert Bragg0dd860c2017-05-11 16:43:28 +0100214/**
215 * DOC: OA Tail Pointer Race
216 *
217 * There's a HW race condition between OA unit tail pointer register updates and
Robert Braggd7965152016-11-07 19:49:52 +0000218 * writes to memory whereby the tail pointer can sometimes get ahead of what's
Robert Bragg0dd860c2017-05-11 16:43:28 +0100219 * been written out to the OA buffer so far (in terms of what's visible to the
220 * CPU).
Robert Braggd7965152016-11-07 19:49:52 +0000221 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100222 * Although this can be observed explicitly while copying reports to userspace
223 * by checking for a zeroed report-id field in tail reports, we want to account
Robert Bragg19f81df2017-06-13 12:23:03 +0100224 * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
Robert Bragg0dd860c2017-05-11 16:43:28 +0100225 * read() attempts.
Robert Braggd7965152016-11-07 19:49:52 +0000226 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100227 * In effect we define a tail pointer for reading that lags the real tail
228 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
229 * time for the corresponding reports to become visible to the CPU.
Robert Braggd7965152016-11-07 19:49:52 +0000230 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100231 * To manage this we actually track two tail pointers:
232 * 1) An 'aging' tail with an associated timestamp that is tracked until we
233 * can trust the corresponding data is visible to the CPU; at which point
234 * it is considered 'aged'.
235 * 2) An 'aged' tail that can be used for read()ing.
236 *
237 * The two separate pointers let us decouple read()s from tail pointer aging.
238 *
239 * The tail pointers are checked and updated at a limited rate within a hrtimer
240 * callback (the same callback that is used for delivering POLLIN events)
241 *
242 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
243 * indicates that an updated tail pointer is needed.
244 *
245 * Most of the implementation details for this workaround are in
Robert Bragg19f81df2017-06-13 12:23:03 +0100246 * oa_buffer_check_unlocked() and _append_oa_reports()
Robert Bragg0dd860c2017-05-11 16:43:28 +0100247 *
248 * Note for posterity: previously the driver used to define an effective tail
249 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
250 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
251 * This was flawed considering that the OA unit may also automatically generate
252 * non-periodic reports (such as on context switch) or the OA unit may be
253 * enabled without any periodic sampling.
Robert Braggd7965152016-11-07 19:49:52 +0000254 */
255#define OA_TAIL_MARGIN_NSEC 100000ULL
Robert Bragg0dd860c2017-05-11 16:43:28 +0100256#define INVALID_TAIL_PTR 0xffffffff
Robert Braggd7965152016-11-07 19:49:52 +0000257
258/* frequency for checking whether the OA unit has written new reports to the
259 * circular OA buffer...
260 */
261#define POLL_FREQUENCY 200
262#define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
263
Robert Braggccdf6342016-11-07 19:49:54 +0000264/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
265static int zero;
266static int one = 1;
267static u32 i915_perf_stream_paranoid = true;
268
Robert Braggd7965152016-11-07 19:49:52 +0000269/* The maximum exponent the hardware accepts is 63 (essentially it selects one
270 * of the 64bit timestamp bits to trigger reports from) but there's currently
271 * no known use case for sampling as infrequently as once per 47 thousand years.
272 *
273 * Since the timestamps included in OA reports are only 32bits it seems
274 * reasonable to limit the OA exponent where it's still possible to account for
275 * overflow in OA report timestamps.
276 */
277#define OA_EXPONENT_MAX 31
278
279#define INVALID_CTX_ID 0xffffffff
280
Robert Bragg19f81df2017-06-13 12:23:03 +0100281/* On Gen8+ automatically triggered OA reports include a 'reason' field... */
282#define OAREPORT_REASON_MASK 0x3f
283#define OAREPORT_REASON_SHIFT 19
284#define OAREPORT_REASON_TIMER (1<<0)
285#define OAREPORT_REASON_CTX_SWITCH (1<<3)
286#define OAREPORT_REASON_CLK_RATIO (1<<5)
287
Robert Braggd7965152016-11-07 19:49:52 +0000288
Robert Bragg00319ba2016-11-07 19:49:55 +0000289/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
290 *
291 * 160ns is the smallest sampling period we can theoretically program the OA
292 * unit with on Haswell, corresponding to 6.25MHz.
293 */
294static int oa_sample_rate_hard_limit = 6250000;
295
296/* Theoretically we can program the OA unit to sample every 160ns but don't
297 * allow that by default unless root...
298 *
299 * The default threshold of 100000Hz is based on perf's similar
300 * kernel.perf_event_max_sample_rate sysctl parameter.
301 */
302static u32 i915_oa_max_sample_rate = 100000;
303
Robert Braggd7965152016-11-07 19:49:52 +0000304/* XXX: beware if future OA HW adds new report formats that the current
305 * code assumes all reports have a power-of-two size and ~(size - 1) can
306 * be used as a mask to align the OA tail pointer.
307 */
308static struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
309 [I915_OA_FORMAT_A13] = { 0, 64 },
310 [I915_OA_FORMAT_A29] = { 1, 128 },
311 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
312 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
313 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
314 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
315 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
316 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
317};
318
Robert Bragg19f81df2017-06-13 12:23:03 +0100319static struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
320 [I915_OA_FORMAT_A12] = { 0, 64 },
321 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
322 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
323 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
324};
325
Robert Braggd7965152016-11-07 19:49:52 +0000326#define SAMPLE_OA_REPORT (1<<0)
Robert Braggeec688e2016-11-07 19:49:47 +0000327
Robert Bragg16d98b32016-12-07 21:40:33 +0000328/**
329 * struct perf_open_properties - for validated properties given to open a stream
330 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
331 * @single_context: Whether a single or all gpu contexts should be monitored
332 * @ctx_handle: A gem ctx handle for use with @single_context
333 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
334 * @oa_format: An OA unit HW report format
335 * @oa_periodic: Whether to enable periodic OA unit sampling
336 * @oa_period_exponent: The OA unit sampling period is derived from this
337 *
338 * As read_properties_unlocked() enumerates and validates the properties given
339 * to open a stream of metrics the configuration is built up in the structure
340 * which starts out zero initialized.
341 */
Robert Braggeec688e2016-11-07 19:49:47 +0000342struct perf_open_properties {
343 u32 sample_flags;
344
345 u64 single_context:1;
346 u64 ctx_handle;
Robert Braggd7965152016-11-07 19:49:52 +0000347
348 /* OA sampling state */
349 int metrics_set;
350 int oa_format;
351 bool oa_periodic;
352 int oa_period_exponent;
Robert Braggeec688e2016-11-07 19:49:47 +0000353};
354
Robert Bragg19f81df2017-06-13 12:23:03 +0100355static u32 gen8_oa_hw_tail_read(struct drm_i915_private *dev_priv)
356{
357 return I915_READ(GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
358}
359
360static u32 gen7_oa_hw_tail_read(struct drm_i915_private *dev_priv)
361{
362 u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
363
364 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
365}
366
Robert Bragg0dd860c2017-05-11 16:43:28 +0100367/**
Robert Bragg19f81df2017-06-13 12:23:03 +0100368 * oa_buffer_check_unlocked - check for data and update tail ptr state
Robert Bragg0dd860c2017-05-11 16:43:28 +0100369 * @dev_priv: i915 device instance
Robert Braggd7965152016-11-07 19:49:52 +0000370 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100371 * This is either called via fops (for blocking reads in user ctx) or the poll
372 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
373 * if there is data available for userspace to read.
Robert Braggd7965152016-11-07 19:49:52 +0000374 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100375 * This function is central to providing a workaround for the OA unit tail
376 * pointer having a race with respect to what data is visible to the CPU.
377 * It is responsible for reading tail pointers from the hardware and giving
378 * the pointers time to 'age' before they are made available for reading.
379 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
380 *
381 * Besides returning true when there is data available to read() this function
382 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
383 * and .aged_tail_idx state used for reading.
384 *
385 * Note: It's safe to read OA config state here unlocked, assuming that this is
386 * only called while the stream is enabled, while the global OA configuration
387 * can't be modified.
388 *
389 * Returns: %true if the OA buffer contains data, else %false
Robert Braggd7965152016-11-07 19:49:52 +0000390 */
Robert Bragg19f81df2017-06-13 12:23:03 +0100391static bool oa_buffer_check_unlocked(struct drm_i915_private *dev_priv)
Robert Braggd7965152016-11-07 19:49:52 +0000392{
393 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100394 unsigned long flags;
395 unsigned int aged_idx;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100396 u32 head, hw_tail, aged_tail, aging_tail;
397 u64 now;
Robert Braggd7965152016-11-07 19:49:52 +0000398
Robert Bragg0dd860c2017-05-11 16:43:28 +0100399 /* We have to consider the (unlikely) possibility that read() errors
400 * could result in an OA buffer reset which might reset the head,
401 * tails[] and aged_tail state.
402 */
403 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
404
405 /* NB: The head we observe here might effectively be a little out of
406 * date (between head and tails[aged_idx].offset if there is currently
407 * a read() in progress.
408 */
409 head = dev_priv->perf.oa.oa_buffer.head;
410
411 aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
412 aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset;
413 aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset;
414
Robert Bragg19f81df2017-06-13 12:23:03 +0100415 hw_tail = dev_priv->perf.oa.ops.oa_hw_tail_read(dev_priv);
Robert Bragg0dd860c2017-05-11 16:43:28 +0100416
417 /* The tail pointer increases in 64 byte increments,
418 * not in report_size steps...
419 */
420 hw_tail &= ~(report_size - 1);
421
422 now = ktime_get_mono_fast_ns();
423
Robert Bragg4117ebc2017-05-11 16:43:30 +0100424 /* Update the aged tail
425 *
426 * Flip the tail pointer available for read()s once the aging tail is
427 * old enough to trust that the corresponding data will be visible to
428 * the CPU...
429 *
430 * Do this before updating the aging pointer in case we may be able to
431 * immediately start aging a new pointer too (if new data has become
432 * available) without needing to wait for a later hrtimer callback.
433 */
434 if (aging_tail != INVALID_TAIL_PTR &&
435 ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) >
436 OA_TAIL_MARGIN_NSEC)) {
Robert Bragg19f81df2017-06-13 12:23:03 +0100437
Robert Bragg4117ebc2017-05-11 16:43:30 +0100438 aged_idx ^= 1;
439 dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx;
440
441 aged_tail = aging_tail;
442
443 /* Mark that we need a new pointer to start aging... */
444 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
445 aging_tail = INVALID_TAIL_PTR;
446 }
447
Robert Bragg0dd860c2017-05-11 16:43:28 +0100448 /* Update the aging tail
449 *
450 * We throttle aging tail updates until we have a new tail that
451 * represents >= one report more data than is already available for
452 * reading. This ensures there will be enough data for a successful
453 * read once this new pointer has aged and ensures we will give the new
454 * pointer time to age.
455 */
456 if (aging_tail == INVALID_TAIL_PTR &&
457 (aged_tail == INVALID_TAIL_PTR ||
458 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
459 struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma;
460 u32 gtt_offset = i915_ggtt_offset(vma);
461
462 /* Be paranoid and do a bounds check on the pointer read back
463 * from hardware, just in case some spurious hardware condition
464 * could put the tail out of bounds...
465 */
466 if (hw_tail >= gtt_offset &&
467 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
468 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset =
469 aging_tail = hw_tail;
470 dev_priv->perf.oa.oa_buffer.aging_timestamp = now;
471 } else {
472 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
473 hw_tail);
474 }
475 }
476
Robert Bragg0dd860c2017-05-11 16:43:28 +0100477 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
478
479 return aged_tail == INVALID_TAIL_PTR ?
480 false : OA_TAKEN(aged_tail, head) >= report_size;
Robert Braggd7965152016-11-07 19:49:52 +0000481}
482
483/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000484 * append_oa_status - Appends a status record to a userspace read() buffer.
485 * @stream: An i915-perf stream opened for OA metrics
486 * @buf: destination buffer given by userspace
487 * @count: the number of bytes userspace wants to read
488 * @offset: (inout): the current position for writing into @buf
489 * @type: The kind of status to report to userspace
490 *
491 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
492 * into the userspace read() buffer.
493 *
494 * The @buf @offset will only be updated on success.
495 *
496 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000497 */
498static int append_oa_status(struct i915_perf_stream *stream,
499 char __user *buf,
500 size_t count,
501 size_t *offset,
502 enum drm_i915_perf_record_type type)
503{
504 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
505
506 if ((count - *offset) < header.size)
507 return -ENOSPC;
508
509 if (copy_to_user(buf + *offset, &header, sizeof(header)))
510 return -EFAULT;
511
512 (*offset) += header.size;
513
514 return 0;
515}
516
517/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000518 * append_oa_sample - Copies single OA report into userspace read() buffer.
519 * @stream: An i915-perf stream opened for OA metrics
520 * @buf: destination buffer given by userspace
521 * @count: the number of bytes userspace wants to read
522 * @offset: (inout): the current position for writing into @buf
523 * @report: A single OA report to (optionally) include as part of the sample
524 *
525 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
526 * properties when opening a stream, tracked as `stream->sample_flags`. This
527 * function copies the requested components of a single sample to the given
528 * read() @buf.
529 *
530 * The @buf @offset will only be updated on success.
531 *
532 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000533 */
534static int append_oa_sample(struct i915_perf_stream *stream,
535 char __user *buf,
536 size_t count,
537 size_t *offset,
538 const u8 *report)
539{
540 struct drm_i915_private *dev_priv = stream->dev_priv;
541 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
542 struct drm_i915_perf_record_header header;
543 u32 sample_flags = stream->sample_flags;
544
545 header.type = DRM_I915_PERF_RECORD_SAMPLE;
546 header.pad = 0;
547 header.size = stream->sample_size;
548
549 if ((count - *offset) < header.size)
550 return -ENOSPC;
551
552 buf += *offset;
553 if (copy_to_user(buf, &header, sizeof(header)))
554 return -EFAULT;
555 buf += sizeof(header);
556
557 if (sample_flags & SAMPLE_OA_REPORT) {
558 if (copy_to_user(buf, report, report_size))
559 return -EFAULT;
560 }
561
562 (*offset) += header.size;
563
564 return 0;
565}
566
567/**
568 * Copies all buffered OA reports into userspace read() buffer.
569 * @stream: An i915-perf stream opened for OA metrics
570 * @buf: destination buffer given by userspace
571 * @count: the number of bytes userspace wants to read
572 * @offset: (inout): the current position for writing into @buf
Robert Braggd7965152016-11-07 19:49:52 +0000573 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000574 * Notably any error condition resulting in a short read (-%ENOSPC or
575 * -%EFAULT) will be returned even though one or more records may
Robert Braggd7965152016-11-07 19:49:52 +0000576 * have been successfully copied. In this case it's up to the caller
577 * to decide if the error should be squashed before returning to
578 * userspace.
579 *
580 * Note: reports are consumed from the head, and appended to the
Robert Bragge81b3a52017-05-11 16:43:24 +0100581 * tail, so the tail chases the head?... If you think that's mad
Robert Braggd7965152016-11-07 19:49:52 +0000582 * and back-to-front you're not alone, but this follows the
583 * Gen PRM naming convention.
Robert Bragg16d98b32016-12-07 21:40:33 +0000584 *
585 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000586 */
Robert Bragg19f81df2017-06-13 12:23:03 +0100587static int gen8_append_oa_reports(struct i915_perf_stream *stream,
588 char __user *buf,
589 size_t count,
590 size_t *offset)
591{
592 struct drm_i915_private *dev_priv = stream->dev_priv;
593 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
594 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
595 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
596 u32 mask = (OA_BUFFER_SIZE - 1);
597 size_t start_offset = *offset;
598 unsigned long flags;
599 unsigned int aged_tail_idx;
600 u32 head, tail;
601 u32 taken;
602 int ret = 0;
603
604 if (WARN_ON(!stream->enabled))
605 return -EIO;
606
607 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
608
609 head = dev_priv->perf.oa.oa_buffer.head;
610 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
611 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
612
613 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
614
615 /*
616 * An invalid tail pointer here means we're still waiting for the poll
617 * hrtimer callback to give us a pointer
618 */
619 if (tail == INVALID_TAIL_PTR)
620 return -EAGAIN;
621
622 /*
623 * NB: oa_buffer.head/tail include the gtt_offset which we don't want
624 * while indexing relative to oa_buf_base.
625 */
626 head -= gtt_offset;
627 tail -= gtt_offset;
628
629 /*
630 * An out of bounds or misaligned head or tail pointer implies a driver
631 * bug since we validate + align the tail pointers we read from the
632 * hardware and we are in full control of the head pointer which should
633 * only be incremented by multiples of the report size (notably also
634 * all a power of two).
635 */
636 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
637 tail > OA_BUFFER_SIZE || tail % report_size,
638 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
639 head, tail))
640 return -EIO;
641
642
643 for (/* none */;
644 (taken = OA_TAKEN(tail, head));
645 head = (head + report_size) & mask) {
646 u8 *report = oa_buf_base + head;
647 u32 *report32 = (void *)report;
648 u32 ctx_id;
649 u32 reason;
650
651 /*
652 * All the report sizes factor neatly into the buffer
653 * size so we never expect to see a report split
654 * between the beginning and end of the buffer.
655 *
656 * Given the initial alignment check a misalignment
657 * here would imply a driver bug that would result
658 * in an overrun.
659 */
660 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
661 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
662 break;
663 }
664
665 /*
666 * The reason field includes flags identifying what
667 * triggered this specific report (mostly timer
668 * triggered or e.g. due to a context switch).
669 *
670 * This field is never expected to be zero so we can
671 * check that the report isn't invalid before copying
672 * it to userspace...
673 */
674 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
675 OAREPORT_REASON_MASK);
676 if (reason == 0) {
677 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
678 DRM_NOTE("Skipping spurious, invalid OA report\n");
679 continue;
680 }
681
682 /*
683 * XXX: Just keep the lower 21 bits for now since I'm not
684 * entirely sure if the HW touches any of the higher bits in
685 * this field
686 */
687 ctx_id = report32[2] & 0x1fffff;
688
689 /*
690 * Squash whatever is in the CTX_ID field if it's marked as
691 * invalid to be sure we avoid false-positive, single-context
692 * filtering below...
693 *
694 * Note: that we don't clear the valid_ctx_bit so userspace can
695 * understand that the ID has been squashed by the kernel.
696 */
697 if (!(report32[0] & dev_priv->perf.oa.gen8_valid_ctx_bit))
698 ctx_id = report32[2] = INVALID_CTX_ID;
699
700 /*
701 * NB: For Gen 8 the OA unit no longer supports clock gating
702 * off for a specific context and the kernel can't securely
703 * stop the counters from updating as system-wide / global
704 * values.
705 *
706 * Automatic reports now include a context ID so reports can be
707 * filtered on the cpu but it's not worth trying to
708 * automatically subtract/hide counter progress for other
709 * contexts while filtering since we can't stop userspace
710 * issuing MI_REPORT_PERF_COUNT commands which would still
711 * provide a side-band view of the real values.
712 *
713 * To allow userspace (such as Mesa/GL_INTEL_performance_query)
714 * to normalize counters for a single filtered context then it
715 * needs be forwarded bookend context-switch reports so that it
716 * can track switches in between MI_REPORT_PERF_COUNT commands
717 * and can itself subtract/ignore the progress of counters
718 * associated with other contexts. Note that the hardware
719 * automatically triggers reports when switching to a new
720 * context which are tagged with the ID of the newly active
721 * context. To avoid the complexity (and likely fragility) of
722 * reading ahead while parsing reports to try and minimize
723 * forwarding redundant context switch reports (i.e. between
724 * other, unrelated contexts) we simply elect to forward them
725 * all.
726 *
727 * We don't rely solely on the reason field to identify context
728 * switches since it's not-uncommon for periodic samples to
729 * identify a switch before any 'context switch' report.
730 */
731 if (!dev_priv->perf.oa.exclusive_stream->ctx ||
732 dev_priv->perf.oa.specific_ctx_id == ctx_id ||
733 (dev_priv->perf.oa.oa_buffer.last_ctx_id ==
734 dev_priv->perf.oa.specific_ctx_id) ||
735 reason & OAREPORT_REASON_CTX_SWITCH) {
736
737 /*
738 * While filtering for a single context we avoid
739 * leaking the IDs of other contexts.
740 */
741 if (dev_priv->perf.oa.exclusive_stream->ctx &&
742 dev_priv->perf.oa.specific_ctx_id != ctx_id) {
743 report32[2] = INVALID_CTX_ID;
744 }
745
746 ret = append_oa_sample(stream, buf, count, offset,
747 report);
748 if (ret)
749 break;
750
751 dev_priv->perf.oa.oa_buffer.last_ctx_id = ctx_id;
752 }
753
754 /*
755 * The above reason field sanity check is based on
756 * the assumption that the OA buffer is initially
757 * zeroed and we reset the field after copying so the
758 * check is still meaningful once old reports start
759 * being overwritten.
760 */
761 report32[0] = 0;
762 }
763
764 if (start_offset != *offset) {
765 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
766
767 /*
768 * We removed the gtt_offset for the copy loop above, indexing
769 * relative to oa_buf_base so put back here...
770 */
771 head += gtt_offset;
772
773 I915_WRITE(GEN8_OAHEADPTR, head & GEN8_OAHEADPTR_MASK);
774 dev_priv->perf.oa.oa_buffer.head = head;
775
776 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
777 }
778
779 return ret;
780}
781
782/**
783 * gen8_oa_read - copy status records then buffered OA reports
784 * @stream: An i915-perf stream opened for OA metrics
785 * @buf: destination buffer given by userspace
786 * @count: the number of bytes userspace wants to read
787 * @offset: (inout): the current position for writing into @buf
788 *
789 * Checks OA unit status registers and if necessary appends corresponding
790 * status records for userspace (such as for a buffer full condition) and then
791 * initiate appending any buffered OA reports.
792 *
793 * Updates @offset according to the number of bytes successfully copied into
794 * the userspace buffer.
795 *
796 * NB: some data may be successfully copied to the userspace buffer
797 * even if an error is returned, and this is reflected in the
798 * updated @offset.
799 *
800 * Returns: zero on success or a negative error code
801 */
802static int gen8_oa_read(struct i915_perf_stream *stream,
803 char __user *buf,
804 size_t count,
805 size_t *offset)
806{
807 struct drm_i915_private *dev_priv = stream->dev_priv;
808 u32 oastatus;
809 int ret;
810
811 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
812 return -EIO;
813
814 oastatus = I915_READ(GEN8_OASTATUS);
815
816 /*
817 * We treat OABUFFER_OVERFLOW as a significant error:
818 *
819 * Although theoretically we could handle this more gracefully
820 * sometimes, some Gens don't correctly suppress certain
821 * automatically triggered reports in this condition and so we
822 * have to assume that old reports are now being trampled
823 * over.
824 *
825 * Considering how we don't currently give userspace control
826 * over the OA buffer size and always configure a large 16MB
827 * buffer, then a buffer overflow does anyway likely indicate
828 * that something has gone quite badly wrong.
829 */
830 if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
831 ret = append_oa_status(stream, buf, count, offset,
832 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
833 if (ret)
834 return ret;
835
836 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
837 dev_priv->perf.oa.period_exponent);
838
839 dev_priv->perf.oa.ops.oa_disable(dev_priv);
840 dev_priv->perf.oa.ops.oa_enable(dev_priv);
841
842 /*
843 * Note: .oa_enable() is expected to re-init the oabuffer and
844 * reset GEN8_OASTATUS for us
845 */
846 oastatus = I915_READ(GEN8_OASTATUS);
847 }
848
849 if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
850 ret = append_oa_status(stream, buf, count, offset,
851 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
852 if (ret)
853 return ret;
854 I915_WRITE(GEN8_OASTATUS,
855 oastatus & ~GEN8_OASTATUS_REPORT_LOST);
856 }
857
858 return gen8_append_oa_reports(stream, buf, count, offset);
859}
860
861/**
862 * Copies all buffered OA reports into userspace read() buffer.
863 * @stream: An i915-perf stream opened for OA metrics
864 * @buf: destination buffer given by userspace
865 * @count: the number of bytes userspace wants to read
866 * @offset: (inout): the current position for writing into @buf
867 *
868 * Notably any error condition resulting in a short read (-%ENOSPC or
869 * -%EFAULT) will be returned even though one or more records may
870 * have been successfully copied. In this case it's up to the caller
871 * to decide if the error should be squashed before returning to
872 * userspace.
873 *
874 * Note: reports are consumed from the head, and appended to the
875 * tail, so the tail chases the head?... If you think that's mad
876 * and back-to-front you're not alone, but this follows the
877 * Gen PRM naming convention.
878 *
879 * Returns: 0 on success, negative error code on failure.
880 */
Robert Braggd7965152016-11-07 19:49:52 +0000881static int gen7_append_oa_reports(struct i915_perf_stream *stream,
882 char __user *buf,
883 size_t count,
Robert Bragg3bb335c2017-05-11 16:43:27 +0100884 size_t *offset)
Robert Braggd7965152016-11-07 19:49:52 +0000885{
886 struct drm_i915_private *dev_priv = stream->dev_priv;
887 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
888 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
Robert Braggd7965152016-11-07 19:49:52 +0000889 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
890 u32 mask = (OA_BUFFER_SIZE - 1);
Robert Bragg3bb335c2017-05-11 16:43:27 +0100891 size_t start_offset = *offset;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100892 unsigned long flags;
893 unsigned int aged_tail_idx;
894 u32 head, tail;
Robert Braggd7965152016-11-07 19:49:52 +0000895 u32 taken;
896 int ret = 0;
897
898 if (WARN_ON(!stream->enabled))
899 return -EIO;
900
Robert Bragg0dd860c2017-05-11 16:43:28 +0100901 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggf2790202017-05-11 16:43:26 +0100902
Robert Bragg0dd860c2017-05-11 16:43:28 +0100903 head = dev_priv->perf.oa.oa_buffer.head;
904 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
905 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
906
907 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
908
909 /* An invalid tail pointer here means we're still waiting for the poll
910 * hrtimer callback to give us a pointer
Robert Braggf2790202017-05-11 16:43:26 +0100911 */
Robert Bragg0dd860c2017-05-11 16:43:28 +0100912 if (tail == INVALID_TAIL_PTR)
Robert Braggd7965152016-11-07 19:49:52 +0000913 return -EAGAIN;
914
Robert Bragg0dd860c2017-05-11 16:43:28 +0100915 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
916 * while indexing relative to oa_buf_base.
917 */
918 head -= gtt_offset;
919 tail -= gtt_offset;
920
921 /* An out of bounds or misaligned head or tail pointer implies a driver
922 * bug since we validate + align the tail pointers we read from the
923 * hardware and we are in full control of the head pointer which should
924 * only be incremented by multiples of the report size (notably also
925 * all a power of two).
926 */
927 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
928 tail > OA_BUFFER_SIZE || tail % report_size,
929 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
930 head, tail))
931 return -EIO;
932
Robert Braggd7965152016-11-07 19:49:52 +0000933
934 for (/* none */;
935 (taken = OA_TAKEN(tail, head));
936 head = (head + report_size) & mask) {
937 u8 *report = oa_buf_base + head;
938 u32 *report32 = (void *)report;
939
940 /* All the report sizes factor neatly into the buffer
941 * size so we never expect to see a report split
942 * between the beginning and end of the buffer.
943 *
944 * Given the initial alignment check a misalignment
945 * here would imply a driver bug that would result
946 * in an overrun.
947 */
948 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
949 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
950 break;
951 }
952
953 /* The report-ID field for periodic samples includes
954 * some undocumented flags related to what triggered
955 * the report and is never expected to be zero so we
956 * can check that the report isn't invalid before
957 * copying it to userspace...
958 */
959 if (report32[0] == 0) {
Robert Bragg712122e2017-05-11 16:43:31 +0100960 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
961 DRM_NOTE("Skipping spurious, invalid OA report\n");
Robert Braggd7965152016-11-07 19:49:52 +0000962 continue;
963 }
964
965 ret = append_oa_sample(stream, buf, count, offset, report);
966 if (ret)
967 break;
968
969 /* The above report-id field sanity check is based on
970 * the assumption that the OA buffer is initially
971 * zeroed and we reset the field after copying so the
972 * check is still meaningful once old reports start
973 * being overwritten.
974 */
975 report32[0] = 0;
976 }
977
Robert Bragg3bb335c2017-05-11 16:43:27 +0100978 if (start_offset != *offset) {
Robert Bragg0dd860c2017-05-11 16:43:28 +0100979 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
980
Robert Bragg3bb335c2017-05-11 16:43:27 +0100981 /* We removed the gtt_offset for the copy loop above, indexing
982 * relative to oa_buf_base so put back here...
983 */
984 head += gtt_offset;
985
986 I915_WRITE(GEN7_OASTATUS2,
987 ((head & GEN7_OASTATUS2_HEAD_MASK) |
988 OA_MEM_SELECT_GGTT));
989 dev_priv->perf.oa.oa_buffer.head = head;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100990
991 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Bragg3bb335c2017-05-11 16:43:27 +0100992 }
Robert Braggd7965152016-11-07 19:49:52 +0000993
994 return ret;
995}
996
Robert Bragg16d98b32016-12-07 21:40:33 +0000997/**
998 * gen7_oa_read - copy status records then buffered OA reports
999 * @stream: An i915-perf stream opened for OA metrics
1000 * @buf: destination buffer given by userspace
1001 * @count: the number of bytes userspace wants to read
1002 * @offset: (inout): the current position for writing into @buf
1003 *
1004 * Checks Gen 7 specific OA unit status registers and if necessary appends
1005 * corresponding status records for userspace (such as for a buffer full
1006 * condition) and then initiate appending any buffered OA reports.
1007 *
1008 * Updates @offset according to the number of bytes successfully copied into
1009 * the userspace buffer.
1010 *
1011 * Returns: zero on success or a negative error code
1012 */
Robert Braggd7965152016-11-07 19:49:52 +00001013static int gen7_oa_read(struct i915_perf_stream *stream,
1014 char __user *buf,
1015 size_t count,
1016 size_t *offset)
1017{
1018 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +00001019 u32 oastatus1;
Robert Braggd7965152016-11-07 19:49:52 +00001020 int ret;
1021
1022 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
1023 return -EIO;
1024
Robert Braggd7965152016-11-07 19:49:52 +00001025 oastatus1 = I915_READ(GEN7_OASTATUS1);
1026
Robert Braggd7965152016-11-07 19:49:52 +00001027 /* XXX: On Haswell we don't have a safe way to clear oastatus1
1028 * bits while the OA unit is enabled (while the tail pointer
1029 * may be updated asynchronously) so we ignore status bits
1030 * that have already been reported to userspace.
1031 */
1032 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
1033
1034 /* We treat OABUFFER_OVERFLOW as a significant error:
1035 *
1036 * - The status can be interpreted to mean that the buffer is
1037 * currently full (with a higher precedence than OA_TAKEN()
1038 * which will start to report a near-empty buffer after an
1039 * overflow) but it's awkward that we can't clear the status
1040 * on Haswell, so without a reset we won't be able to catch
1041 * the state again.
1042 *
1043 * - Since it also implies the HW has started overwriting old
1044 * reports it may also affect our sanity checks for invalid
1045 * reports when copying to userspace that assume new reports
1046 * are being written to cleared memory.
1047 *
1048 * - In the future we may want to introduce a flight recorder
1049 * mode where the driver will automatically maintain a safe
1050 * guard band between head/tail, avoiding this overflow
1051 * condition, but we avoid the added driver complexity for
1052 * now.
1053 */
1054 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
1055 ret = append_oa_status(stream, buf, count, offset,
1056 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
1057 if (ret)
1058 return ret;
1059
Robert Bragg19f81df2017-06-13 12:23:03 +01001060 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
1061 dev_priv->perf.oa.period_exponent);
Robert Braggd7965152016-11-07 19:49:52 +00001062
1063 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1064 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1065
Robert Braggd7965152016-11-07 19:49:52 +00001066 oastatus1 = I915_READ(GEN7_OASTATUS1);
Robert Braggd7965152016-11-07 19:49:52 +00001067 }
1068
1069 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
1070 ret = append_oa_status(stream, buf, count, offset,
1071 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
1072 if (ret)
1073 return ret;
1074 dev_priv->perf.oa.gen7_latched_oastatus1 |=
1075 GEN7_OASTATUS1_REPORT_LOST;
1076 }
1077
Robert Bragg3bb335c2017-05-11 16:43:27 +01001078 return gen7_append_oa_reports(stream, buf, count, offset);
Robert Braggd7965152016-11-07 19:49:52 +00001079}
1080
Robert Bragg16d98b32016-12-07 21:40:33 +00001081/**
1082 * i915_oa_wait_unlocked - handles blocking IO until OA data available
1083 * @stream: An i915-perf stream opened for OA metrics
1084 *
1085 * Called when userspace tries to read() from a blocking stream FD opened
1086 * for OA metrics. It waits until the hrtimer callback finds a non-empty
1087 * OA buffer and wakes us.
1088 *
1089 * Note: it's acceptable to have this return with some false positives
1090 * since any subsequent read handling will return -EAGAIN if there isn't
1091 * really data ready for userspace yet.
1092 *
1093 * Returns: zero on success or a negative error code
1094 */
Robert Braggd7965152016-11-07 19:49:52 +00001095static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
1096{
1097 struct drm_i915_private *dev_priv = stream->dev_priv;
1098
1099 /* We would wait indefinitely if periodic sampling is not enabled */
1100 if (!dev_priv->perf.oa.periodic)
1101 return -EIO;
1102
Robert Braggd7965152016-11-07 19:49:52 +00001103 return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
Robert Bragg19f81df2017-06-13 12:23:03 +01001104 oa_buffer_check_unlocked(dev_priv));
Robert Braggd7965152016-11-07 19:49:52 +00001105}
1106
Robert Bragg16d98b32016-12-07 21:40:33 +00001107/**
1108 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
1109 * @stream: An i915-perf stream opened for OA metrics
1110 * @file: An i915 perf stream file
1111 * @wait: poll() state table
1112 *
1113 * For handling userspace polling on an i915 perf stream opened for OA metrics,
1114 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
1115 * when it sees data ready to read in the circular OA buffer.
1116 */
Robert Braggd7965152016-11-07 19:49:52 +00001117static void i915_oa_poll_wait(struct i915_perf_stream *stream,
1118 struct file *file,
1119 poll_table *wait)
1120{
1121 struct drm_i915_private *dev_priv = stream->dev_priv;
1122
1123 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
1124}
1125
Robert Bragg16d98b32016-12-07 21:40:33 +00001126/**
1127 * i915_oa_read - just calls through to &i915_oa_ops->read
1128 * @stream: An i915-perf stream opened for OA metrics
1129 * @buf: destination buffer given by userspace
1130 * @count: the number of bytes userspace wants to read
1131 * @offset: (inout): the current position for writing into @buf
1132 *
1133 * Updates @offset according to the number of bytes successfully copied into
1134 * the userspace buffer.
1135 *
1136 * Returns: zero on success or a negative error code
1137 */
Robert Braggd7965152016-11-07 19:49:52 +00001138static int i915_oa_read(struct i915_perf_stream *stream,
1139 char __user *buf,
1140 size_t count,
1141 size_t *offset)
1142{
1143 struct drm_i915_private *dev_priv = stream->dev_priv;
1144
1145 return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
1146}
1147
Robert Bragg16d98b32016-12-07 21:40:33 +00001148/**
1149 * oa_get_render_ctx_id - determine and hold ctx hw id
1150 * @stream: An i915-perf stream opened for OA metrics
1151 *
1152 * Determine the render context hw id, and ensure it remains fixed for the
Robert Braggd7965152016-11-07 19:49:52 +00001153 * lifetime of the stream. This ensures that we don't have to worry about
1154 * updating the context ID in OACONTROL on the fly.
Robert Bragg16d98b32016-12-07 21:40:33 +00001155 *
1156 * Returns: zero on success or a negative error code
Robert Braggd7965152016-11-07 19:49:52 +00001157 */
1158static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
1159{
1160 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +00001161
Robert Bragg19f81df2017-06-13 12:23:03 +01001162 if (i915.enable_execlists)
1163 dev_priv->perf.oa.specific_ctx_id = stream->ctx->hw_id;
1164 else {
1165 struct intel_engine_cs *engine = dev_priv->engine[RCS];
1166 struct intel_ring *ring;
1167 int ret;
Robert Braggd7965152016-11-07 19:49:52 +00001168
Robert Bragg19f81df2017-06-13 12:23:03 +01001169 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1170 if (ret)
1171 return ret;
Robert Braggd7965152016-11-07 19:49:52 +00001172
Robert Bragg19f81df2017-06-13 12:23:03 +01001173 /*
1174 * As the ID is the gtt offset of the context's vma we
1175 * pin the vma to ensure the ID remains fixed.
1176 *
1177 * NB: implied RCS engine...
1178 */
1179 ring = engine->context_pin(engine, stream->ctx);
1180 mutex_unlock(&dev_priv->drm.struct_mutex);
1181 if (IS_ERR(ring))
1182 return PTR_ERR(ring);
1183
1184
1185 /*
1186 * Explicitly track the ID (instead of calling
1187 * i915_ggtt_offset() on the fly) considering the difference
1188 * with gen8+ and execlists
1189 */
1190 dev_priv->perf.oa.specific_ctx_id =
1191 i915_ggtt_offset(stream->ctx->engine[engine->id].state);
1192 }
Robert Braggd7965152016-11-07 19:49:52 +00001193
Chris Wilson266a2402017-05-04 10:33:08 +01001194 return 0;
Robert Braggd7965152016-11-07 19:49:52 +00001195}
1196
Robert Bragg16d98b32016-12-07 21:40:33 +00001197/**
1198 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
1199 * @stream: An i915-perf stream opened for OA metrics
1200 *
1201 * In case anything needed doing to ensure the context HW ID would remain valid
1202 * for the lifetime of the stream, then that can be undone here.
1203 */
Robert Braggd7965152016-11-07 19:49:52 +00001204static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
1205{
1206 struct drm_i915_private *dev_priv = stream->dev_priv;
1207
Robert Bragg19f81df2017-06-13 12:23:03 +01001208 if (i915.enable_execlists) {
1209 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
1210 } else {
1211 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Robert Braggd7965152016-11-07 19:49:52 +00001212
Robert Bragg19f81df2017-06-13 12:23:03 +01001213 mutex_lock(&dev_priv->drm.struct_mutex);
Robert Braggd7965152016-11-07 19:49:52 +00001214
Robert Bragg19f81df2017-06-13 12:23:03 +01001215 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
1216 engine->context_unpin(engine, stream->ctx);
1217
1218 mutex_unlock(&dev_priv->drm.struct_mutex);
1219 }
Robert Braggd7965152016-11-07 19:49:52 +00001220}
1221
1222static void
1223free_oa_buffer(struct drm_i915_private *i915)
1224{
1225 mutex_lock(&i915->drm.struct_mutex);
1226
1227 i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
1228 i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
1229 i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
1230
1231 i915->perf.oa.oa_buffer.vma = NULL;
1232 i915->perf.oa.oa_buffer.vaddr = NULL;
1233
1234 mutex_unlock(&i915->drm.struct_mutex);
1235}
1236
1237static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
1238{
1239 struct drm_i915_private *dev_priv = stream->dev_priv;
1240
1241 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
1242
Robert Bragg19f81df2017-06-13 12:23:03 +01001243 /*
1244 * Unset exclusive_stream first, it might be checked while
1245 * disabling the metric set on gen8+.
1246 */
1247 dev_priv->perf.oa.exclusive_stream = NULL;
1248
Robert Braggd7965152016-11-07 19:49:52 +00001249 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
1250
1251 free_oa_buffer(dev_priv);
1252
1253 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1254 intel_runtime_pm_put(dev_priv);
1255
1256 if (stream->ctx)
1257 oa_put_render_ctx_id(stream);
1258
Robert Bragg712122e2017-05-11 16:43:31 +01001259 if (dev_priv->perf.oa.spurious_report_rs.missed) {
1260 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
1261 dev_priv->perf.oa.spurious_report_rs.missed);
1262 }
Robert Braggd7965152016-11-07 19:49:52 +00001263}
1264
1265static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
1266{
1267 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
Robert Bragg0dd860c2017-05-11 16:43:28 +01001268 unsigned long flags;
1269
1270 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggd7965152016-11-07 19:49:52 +00001271
1272 /* Pre-DevBDW: OABUFFER must be set with counters off,
1273 * before OASTATUS1, but after OASTATUS2
1274 */
1275 I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
Robert Braggf2790202017-05-11 16:43:26 +01001276 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1277
Robert Braggd7965152016-11-07 19:49:52 +00001278 I915_WRITE(GEN7_OABUFFER, gtt_offset);
Robert Braggf2790202017-05-11 16:43:26 +01001279
Robert Braggd7965152016-11-07 19:49:52 +00001280 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
1281
Robert Bragg0dd860c2017-05-11 16:43:28 +01001282 /* Mark that we need updated tail pointers to read from... */
1283 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1284 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1285
1286 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1287
Robert Braggd7965152016-11-07 19:49:52 +00001288 /* On Haswell we have to track which OASTATUS1 flags we've
1289 * already seen since they can't be cleared while periodic
1290 * sampling is enabled.
1291 */
1292 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
1293
1294 /* NB: although the OA buffer will initially be allocated
1295 * zeroed via shmfs (and so this memset is redundant when
1296 * first allocating), we may re-init the OA buffer, either
1297 * when re-enabling a stream or in error/reset paths.
1298 *
1299 * The reason we clear the buffer for each re-init is for the
1300 * sanity check in gen7_append_oa_reports() that looks at the
1301 * report-id field to make sure it's non-zero which relies on
1302 * the assumption that new reports are being written to zeroed
1303 * memory...
1304 */
1305 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1306
1307 /* Maybe make ->pollin per-stream state if we support multiple
1308 * concurrent streams in the future.
1309 */
1310 dev_priv->perf.oa.pollin = false;
1311}
1312
Robert Bragg19f81df2017-06-13 12:23:03 +01001313static void gen8_init_oa_buffer(struct drm_i915_private *dev_priv)
1314{
1315 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
1316 unsigned long flags;
1317
1318 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1319
1320 I915_WRITE(GEN8_OASTATUS, 0);
1321 I915_WRITE(GEN8_OAHEADPTR, gtt_offset);
1322 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
1323
1324 I915_WRITE(GEN8_OABUFFER_UDW, 0);
1325
1326 /*
1327 * PRM says:
1328 *
1329 * "This MMIO must be set before the OATAILPTR
1330 * register and after the OAHEADPTR register. This is
1331 * to enable proper functionality of the overflow
1332 * bit."
1333 */
1334 I915_WRITE(GEN8_OABUFFER, gtt_offset |
1335 OABUFFER_SIZE_16M | OA_MEM_SELECT_GGTT);
1336 I915_WRITE(GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
1337
1338 /* Mark that we need updated tail pointers to read from... */
1339 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
1340 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
1341
1342 /*
1343 * Reset state used to recognise context switches, affecting which
1344 * reports we will forward to userspace while filtering for a single
1345 * context.
1346 */
1347 dev_priv->perf.oa.oa_buffer.last_ctx_id = INVALID_CTX_ID;
1348
1349 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
1350
1351 /*
1352 * NB: although the OA buffer will initially be allocated
1353 * zeroed via shmfs (and so this memset is redundant when
1354 * first allocating), we may re-init the OA buffer, either
1355 * when re-enabling a stream or in error/reset paths.
1356 *
1357 * The reason we clear the buffer for each re-init is for the
1358 * sanity check in gen8_append_oa_reports() that looks at the
1359 * reason field to make sure it's non-zero which relies on
1360 * the assumption that new reports are being written to zeroed
1361 * memory...
1362 */
1363 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
1364
1365 /*
1366 * Maybe make ->pollin per-stream state if we support multiple
1367 * concurrent streams in the future.
1368 */
1369 dev_priv->perf.oa.pollin = false;
1370}
1371
Robert Braggd7965152016-11-07 19:49:52 +00001372static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
1373{
1374 struct drm_i915_gem_object *bo;
1375 struct i915_vma *vma;
1376 int ret;
1377
1378 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
1379 return -ENODEV;
1380
1381 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1382 if (ret)
1383 return ret;
1384
1385 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
1386 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
1387
Tvrtko Ursulin12d79d72016-12-01 14:16:37 +00001388 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +00001389 if (IS_ERR(bo)) {
1390 DRM_ERROR("Failed to allocate OA buffer\n");
1391 ret = PTR_ERR(bo);
1392 goto unlock;
1393 }
1394
1395 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
1396 if (ret)
1397 goto err_unref;
1398
1399 /* PreHSW required 512K alignment, HSW requires 16M */
1400 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
1401 if (IS_ERR(vma)) {
1402 ret = PTR_ERR(vma);
1403 goto err_unref;
1404 }
1405 dev_priv->perf.oa.oa_buffer.vma = vma;
1406
1407 dev_priv->perf.oa.oa_buffer.vaddr =
1408 i915_gem_object_pin_map(bo, I915_MAP_WB);
1409 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
1410 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
1411 goto err_unpin;
1412 }
1413
1414 dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
1415
1416 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
1417 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
1418 dev_priv->perf.oa.oa_buffer.vaddr);
1419
1420 goto unlock;
1421
1422err_unpin:
1423 __i915_vma_unpin(vma);
1424
1425err_unref:
1426 i915_gem_object_put(bo);
1427
1428 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
1429 dev_priv->perf.oa.oa_buffer.vma = NULL;
1430
1431unlock:
1432 mutex_unlock(&dev_priv->drm.struct_mutex);
1433 return ret;
1434}
1435
1436static void config_oa_regs(struct drm_i915_private *dev_priv,
1437 const struct i915_oa_reg *regs,
1438 int n_regs)
1439{
1440 int i;
1441
1442 for (i = 0; i < n_regs; i++) {
1443 const struct i915_oa_reg *reg = regs + i;
1444
1445 I915_WRITE(reg->addr, reg->value);
1446 }
1447}
1448
1449static int hsw_enable_metric_set(struct drm_i915_private *dev_priv)
1450{
1451 int ret = i915_oa_select_metric_set_hsw(dev_priv);
Lionel Landwerlin3f488d92017-06-13 12:23:01 +01001452 int i;
Robert Braggd7965152016-11-07 19:49:52 +00001453
1454 if (ret)
1455 return ret;
1456
1457 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) |
1458 GT_NOA_ENABLE));
1459
1460 /* PRM:
1461 *
1462 * OA unit is using “crclk” for its functionality. When trunk
1463 * level clock gating takes place, OA clock would be gated,
1464 * unable to count the events from non-render clock domain.
1465 * Render clock gating must be disabled when OA is enabled to
1466 * count the events from non-render domain. Unit level clock
1467 * gating for RCS should also be disabled.
1468 */
1469 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1470 ~GEN7_DOP_CLOCK_GATE_ENABLE));
1471 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
1472 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1473
Lionel Landwerlin3f488d92017-06-13 12:23:01 +01001474 for (i = 0; i < dev_priv->perf.oa.n_mux_configs; i++) {
1475 config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs[i],
1476 dev_priv->perf.oa.mux_regs_lens[i]);
1477 }
Robert Braggd7965152016-11-07 19:49:52 +00001478
1479 /* It apparently takes a fairly long time for a new MUX
1480 * configuration to be be applied after these register writes.
1481 * This delay duration was derived empirically based on the
1482 * render_basic config but hopefully it covers the maximum
1483 * configuration latency.
1484 *
1485 * As a fallback, the checks in _append_oa_reports() to skip
1486 * invalid OA reports do also seem to work to discard reports
1487 * generated before this config has completed - albeit not
1488 * silently.
1489 *
1490 * Unfortunately this is essentially a magic number, since we
1491 * don't currently know of a reliable mechanism for predicting
1492 * how long the MUX config will take to apply and besides
1493 * seeing invalid reports we don't know of a reliable way to
1494 * explicitly check that the MUX config has landed.
1495 *
1496 * It's even possible we've miss characterized the underlying
1497 * problem - it just seems like the simplest explanation why
1498 * a delay at this location would mitigate any invalid reports.
1499 */
1500 usleep_range(15000, 20000);
1501
1502 config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
1503 dev_priv->perf.oa.b_counter_regs_len);
1504
1505 return 0;
1506}
1507
1508static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
1509{
1510 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
1511 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1512 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
1513 GEN7_DOP_CLOCK_GATE_ENABLE));
1514
1515 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1516 ~GT_NOA_ENABLE));
1517}
1518
Robert Bragg19f81df2017-06-13 12:23:03 +01001519/*
1520 * NB: It must always remain pointer safe to run this even if the OA unit
1521 * has been disabled.
1522 *
1523 * It's fine to put out-of-date values into these per-context registers
1524 * in the case that the OA unit has been disabled.
1525 */
1526static void gen8_update_reg_state_unlocked(struct i915_gem_context *ctx,
1527 u32 *reg_state)
1528{
1529 struct drm_i915_private *dev_priv = ctx->i915;
1530 const struct i915_oa_reg *flex_regs = dev_priv->perf.oa.flex_regs;
1531 int n_flex_regs = dev_priv->perf.oa.flex_regs_len;
1532 u32 ctx_oactxctrl = dev_priv->perf.oa.ctx_oactxctrl_offset;
1533 u32 ctx_flexeu0 = dev_priv->perf.oa.ctx_flexeu0_offset;
1534 /* The MMIO offsets for Flex EU registers aren't contiguous */
1535 u32 flex_mmio[] = {
1536 i915_mmio_reg_offset(EU_PERF_CNTL0),
1537 i915_mmio_reg_offset(EU_PERF_CNTL1),
1538 i915_mmio_reg_offset(EU_PERF_CNTL2),
1539 i915_mmio_reg_offset(EU_PERF_CNTL3),
1540 i915_mmio_reg_offset(EU_PERF_CNTL4),
1541 i915_mmio_reg_offset(EU_PERF_CNTL5),
1542 i915_mmio_reg_offset(EU_PERF_CNTL6),
1543 };
1544 int i;
1545
1546 reg_state[ctx_oactxctrl] = i915_mmio_reg_offset(GEN8_OACTXCONTROL);
1547 reg_state[ctx_oactxctrl+1] = (dev_priv->perf.oa.period_exponent <<
1548 GEN8_OA_TIMER_PERIOD_SHIFT) |
1549 (dev_priv->perf.oa.periodic ?
1550 GEN8_OA_TIMER_ENABLE : 0) |
1551 GEN8_OA_COUNTER_RESUME;
1552
1553 for (i = 0; i < ARRAY_SIZE(flex_mmio); i++) {
1554 u32 state_offset = ctx_flexeu0 + i * 2;
1555 u32 mmio = flex_mmio[i];
1556
1557 /*
1558 * This arbitrary default will select the 'EU FPU0 Pipeline
1559 * Active' event. In the future it's anticipated that there
1560 * will be an explicit 'No Event' we can select, but not yet...
1561 */
1562 u32 value = 0;
1563 int j;
1564
1565 for (j = 0; j < n_flex_regs; j++) {
1566 if (i915_mmio_reg_offset(flex_regs[j].addr) == mmio) {
1567 value = flex_regs[j].value;
1568 break;
1569 }
1570 }
1571
1572 reg_state[state_offset] = mmio;
1573 reg_state[state_offset+1] = value;
1574 }
1575}
1576
1577/*
1578 * Same as gen8_update_reg_state_unlocked only through the batchbuffer. This
1579 * is only used by the kernel context.
1580 */
1581static int gen8_emit_oa_config(struct drm_i915_gem_request *req)
1582{
1583 struct drm_i915_private *dev_priv = req->i915;
1584 const struct i915_oa_reg *flex_regs = dev_priv->perf.oa.flex_regs;
1585 int n_flex_regs = dev_priv->perf.oa.flex_regs_len;
1586 /* The MMIO offsets for Flex EU registers aren't contiguous */
1587 u32 flex_mmio[] = {
1588 i915_mmio_reg_offset(EU_PERF_CNTL0),
1589 i915_mmio_reg_offset(EU_PERF_CNTL1),
1590 i915_mmio_reg_offset(EU_PERF_CNTL2),
1591 i915_mmio_reg_offset(EU_PERF_CNTL3),
1592 i915_mmio_reg_offset(EU_PERF_CNTL4),
1593 i915_mmio_reg_offset(EU_PERF_CNTL5),
1594 i915_mmio_reg_offset(EU_PERF_CNTL6),
1595 };
1596 u32 *cs;
1597 int i;
1598
1599 cs = intel_ring_begin(req, n_flex_regs * 2 + 4);
1600 if (IS_ERR(cs))
1601 return PTR_ERR(cs);
1602
1603 *cs++ = MI_LOAD_REGISTER_IMM(n_flex_regs + 1);
1604
1605 *cs++ = i915_mmio_reg_offset(GEN8_OACTXCONTROL);
1606 *cs++ = (dev_priv->perf.oa.period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
1607 (dev_priv->perf.oa.periodic ? GEN8_OA_TIMER_ENABLE : 0) |
1608 GEN8_OA_COUNTER_RESUME;
1609
1610 for (i = 0; i < ARRAY_SIZE(flex_mmio); i++) {
1611 u32 mmio = flex_mmio[i];
1612
1613 /*
1614 * This arbitrary default will select the 'EU FPU0 Pipeline
1615 * Active' event. In the future it's anticipated that there
1616 * will be an explicit 'No Event' we can select, but not
1617 * yet...
1618 */
1619 u32 value = 0;
1620 int j;
1621
1622 for (j = 0; j < n_flex_regs; j++) {
1623 if (i915_mmio_reg_offset(flex_regs[j].addr) == mmio) {
1624 value = flex_regs[j].value;
1625 break;
1626 }
1627 }
1628
1629 *cs++ = mmio;
1630 *cs++ = value;
1631 }
1632
1633 *cs++ = MI_NOOP;
1634 intel_ring_advance(req, cs);
1635
1636 return 0;
1637}
1638
1639static int gen8_switch_to_updated_kernel_context(struct drm_i915_private *dev_priv)
1640{
1641 struct intel_engine_cs *engine = dev_priv->engine[RCS];
1642 struct i915_gem_timeline *timeline;
1643 struct drm_i915_gem_request *req;
1644 int ret;
1645
1646 lockdep_assert_held(&dev_priv->drm.struct_mutex);
1647
1648 i915_gem_retire_requests(dev_priv);
1649
1650 req = i915_gem_request_alloc(engine, dev_priv->kernel_context);
1651 if (IS_ERR(req))
1652 return PTR_ERR(req);
1653
1654 ret = gen8_emit_oa_config(req);
1655 if (ret) {
1656 i915_add_request(req);
1657 return ret;
1658 }
1659
1660 /* Queue this switch after all other activity */
1661 list_for_each_entry(timeline, &dev_priv->gt.timelines, link) {
1662 struct drm_i915_gem_request *prev;
1663 struct intel_timeline *tl;
1664
1665 tl = &timeline->engine[engine->id];
1666 prev = i915_gem_active_raw(&tl->last_request,
1667 &dev_priv->drm.struct_mutex);
1668 if (prev)
1669 i915_sw_fence_await_sw_fence_gfp(&req->submit,
1670 &prev->submit,
1671 GFP_KERNEL);
1672 }
1673
1674 ret = i915_switch_context(req);
1675 i915_add_request(req);
1676
1677 return ret;
1678}
1679
1680/*
1681 * Manages updating the per-context aspects of the OA stream
1682 * configuration across all contexts.
1683 *
1684 * The awkward consideration here is that OACTXCONTROL controls the
1685 * exponent for periodic sampling which is primarily used for system
1686 * wide profiling where we'd like a consistent sampling period even in
1687 * the face of context switches.
1688 *
1689 * Our approach of updating the register state context (as opposed to
1690 * say using a workaround batch buffer) ensures that the hardware
1691 * won't automatically reload an out-of-date timer exponent even
1692 * transiently before a WA BB could be parsed.
1693 *
1694 * This function needs to:
1695 * - Ensure the currently running context's per-context OA state is
1696 * updated
1697 * - Ensure that all existing contexts will have the correct per-context
1698 * OA state if they are scheduled for use.
1699 * - Ensure any new contexts will be initialized with the correct
1700 * per-context OA state.
1701 *
1702 * Note: it's only the RCS/Render context that has any OA state.
1703 */
1704static int gen8_configure_all_contexts(struct drm_i915_private *dev_priv,
1705 bool interruptible)
1706{
1707 struct i915_gem_context *ctx;
1708 int ret;
1709 unsigned int wait_flags = I915_WAIT_LOCKED;
1710
1711 if (interruptible) {
1712 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1713 if (ret)
1714 return ret;
1715
1716 wait_flags |= I915_WAIT_INTERRUPTIBLE;
1717 } else {
1718 mutex_lock(&dev_priv->drm.struct_mutex);
1719 }
1720
1721 /* Switch away from any user context. */
1722 ret = gen8_switch_to_updated_kernel_context(dev_priv);
1723 if (ret)
1724 goto out;
1725
1726 /*
1727 * The OA register config is setup through the context image. This image
1728 * might be written to by the GPU on context switch (in particular on
1729 * lite-restore). This means we can't safely update a context's image,
1730 * if this context is scheduled/submitted to run on the GPU.
1731 *
1732 * We could emit the OA register config through the batch buffer but
1733 * this might leave small interval of time where the OA unit is
1734 * configured at an invalid sampling period.
1735 *
1736 * So far the best way to work around this issue seems to be draining
1737 * the GPU from any submitted work.
1738 */
1739 ret = i915_gem_wait_for_idle(dev_priv, wait_flags);
1740 if (ret)
1741 goto out;
1742
1743 /* Update all contexts now that we've stalled the submission. */
1744 list_for_each_entry(ctx, &dev_priv->context_list, link) {
1745 struct intel_context *ce = &ctx->engine[RCS];
1746 u32 *regs;
1747
1748 /* OA settings will be set upon first use */
1749 if (!ce->state)
1750 continue;
1751
1752 regs = i915_gem_object_pin_map(ce->state->obj, I915_MAP_WB);
1753 if (IS_ERR(regs)) {
1754 ret = PTR_ERR(regs);
1755 goto out;
1756 }
1757
1758 ce->state->obj->mm.dirty = true;
1759 regs += LRC_STATE_PN * PAGE_SIZE / sizeof(*regs);
1760
1761 gen8_update_reg_state_unlocked(ctx, regs);
1762
1763 i915_gem_object_unpin_map(ce->state->obj);
1764 }
1765
1766 out:
1767 mutex_unlock(&dev_priv->drm.struct_mutex);
1768
1769 return ret;
1770}
1771
1772static int gen8_enable_metric_set(struct drm_i915_private *dev_priv)
1773{
1774 int ret = dev_priv->perf.oa.ops.select_metric_set(dev_priv);
1775 int i;
1776
1777 if (ret)
1778 return ret;
1779
1780 /*
1781 * We disable slice/unslice clock ratio change reports on SKL since
1782 * they are too noisy. The HW generates a lot of redundant reports
1783 * where the ratio hasn't really changed causing a lot of redundant
1784 * work to processes and increasing the chances we'll hit buffer
1785 * overruns.
1786 *
1787 * Although we don't currently use the 'disable overrun' OABUFFER
1788 * feature it's worth noting that clock ratio reports have to be
1789 * disabled before considering to use that feature since the HW doesn't
1790 * correctly block these reports.
1791 *
1792 * Currently none of the high-level metrics we have depend on knowing
1793 * this ratio to normalize.
1794 *
1795 * Note: This register is not power context saved and restored, but
1796 * that's OK considering that we disable RC6 while the OA unit is
1797 * enabled.
1798 *
1799 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
1800 * be read back from automatically triggered reports, as part of the
1801 * RPT_ID field.
1802 */
1803 if (IS_SKYLAKE(dev_priv) || IS_BROXTON(dev_priv)) {
1804 I915_WRITE(GEN8_OA_DEBUG,
1805 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
1806 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
1807 }
1808
1809 /*
1810 * Update all contexts prior writing the mux configurations as we need
1811 * to make sure all slices/subslices are ON before writing to NOA
1812 * registers.
1813 */
1814 ret = gen8_configure_all_contexts(dev_priv, true);
1815 if (ret)
1816 return ret;
1817
1818 I915_WRITE(GDT_CHICKEN_BITS, 0xA0);
1819 for (i = 0; i < dev_priv->perf.oa.n_mux_configs; i++) {
1820 config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs[i],
1821 dev_priv->perf.oa.mux_regs_lens[i]);
1822 }
1823 I915_WRITE(GDT_CHICKEN_BITS, 0x80);
1824
1825 config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
1826 dev_priv->perf.oa.b_counter_regs_len);
1827
1828 return 0;
1829}
1830
1831static void gen8_disable_metric_set(struct drm_i915_private *dev_priv)
1832{
1833 /* Reset all contexts' slices/subslices configurations. */
1834 gen8_configure_all_contexts(dev_priv, false);
1835}
1836
Robert Braggd7965152016-11-07 19:49:52 +00001837static void gen7_update_oacontrol_locked(struct drm_i915_private *dev_priv)
1838{
Chris Wilson67520412017-03-02 13:28:01 +00001839 lockdep_assert_held(&dev_priv->perf.hook_lock);
Robert Braggd7965152016-11-07 19:49:52 +00001840
1841 if (dev_priv->perf.oa.exclusive_stream->enabled) {
1842 struct i915_gem_context *ctx =
1843 dev_priv->perf.oa.exclusive_stream->ctx;
1844 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1845
1846 bool periodic = dev_priv->perf.oa.periodic;
1847 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1848 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1849
1850 I915_WRITE(GEN7_OACONTROL,
1851 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1852 (period_exponent <<
1853 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1854 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1855 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1856 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1857 GEN7_OACONTROL_ENABLE);
1858 } else
1859 I915_WRITE(GEN7_OACONTROL, 0);
1860}
1861
1862static void gen7_oa_enable(struct drm_i915_private *dev_priv)
1863{
1864 unsigned long flags;
1865
1866 /* Reset buf pointers so we don't forward reports from before now.
1867 *
1868 * Think carefully if considering trying to avoid this, since it
1869 * also ensures status flags and the buffer itself are cleared
1870 * in error paths, and we have checks for invalid reports based
1871 * on the assumption that certain fields are written to zeroed
1872 * memory which this helps maintains.
1873 */
1874 gen7_init_oa_buffer(dev_priv);
1875
1876 spin_lock_irqsave(&dev_priv->perf.hook_lock, flags);
1877 gen7_update_oacontrol_locked(dev_priv);
1878 spin_unlock_irqrestore(&dev_priv->perf.hook_lock, flags);
1879}
1880
Robert Bragg19f81df2017-06-13 12:23:03 +01001881static void gen8_oa_enable(struct drm_i915_private *dev_priv)
1882{
1883 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1884
1885 /*
1886 * Reset buf pointers so we don't forward reports from before now.
1887 *
1888 * Think carefully if considering trying to avoid this, since it
1889 * also ensures status flags and the buffer itself are cleared
1890 * in error paths, and we have checks for invalid reports based
1891 * on the assumption that certain fields are written to zeroed
1892 * memory which this helps maintains.
1893 */
1894 gen8_init_oa_buffer(dev_priv);
1895
1896 /*
1897 * Note: we don't rely on the hardware to perform single context
1898 * filtering and instead filter on the cpu based on the context-id
1899 * field of reports
1900 */
1901 I915_WRITE(GEN8_OACONTROL, (report_format <<
1902 GEN8_OA_REPORT_FORMAT_SHIFT) |
1903 GEN8_OA_COUNTER_ENABLE);
1904}
1905
Robert Bragg16d98b32016-12-07 21:40:33 +00001906/**
1907 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1908 * @stream: An i915 perf stream opened for OA metrics
1909 *
1910 * [Re]enables hardware periodic sampling according to the period configured
1911 * when opening the stream. This also starts a hrtimer that will periodically
1912 * check for data in the circular OA buffer for notifying userspace (e.g.
1913 * during a read() or poll()).
1914 */
Robert Braggd7965152016-11-07 19:49:52 +00001915static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1916{
1917 struct drm_i915_private *dev_priv = stream->dev_priv;
1918
1919 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1920
1921 if (dev_priv->perf.oa.periodic)
1922 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1923 ns_to_ktime(POLL_PERIOD),
1924 HRTIMER_MODE_REL_PINNED);
1925}
1926
1927static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1928{
1929 I915_WRITE(GEN7_OACONTROL, 0);
1930}
1931
Robert Bragg19f81df2017-06-13 12:23:03 +01001932static void gen8_oa_disable(struct drm_i915_private *dev_priv)
1933{
1934 I915_WRITE(GEN8_OACONTROL, 0);
1935}
1936
Robert Bragg16d98b32016-12-07 21:40:33 +00001937/**
1938 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1939 * @stream: An i915 perf stream opened for OA metrics
1940 *
1941 * Stops the OA unit from periodically writing counter reports into the
1942 * circular OA buffer. This also stops the hrtimer that periodically checks for
1943 * data in the circular OA buffer, for notifying userspace.
1944 */
Robert Braggd7965152016-11-07 19:49:52 +00001945static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1946{
1947 struct drm_i915_private *dev_priv = stream->dev_priv;
1948
1949 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1950
1951 if (dev_priv->perf.oa.periodic)
1952 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1953}
1954
Robert Braggd7965152016-11-07 19:49:52 +00001955static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1956 .destroy = i915_oa_stream_destroy,
1957 .enable = i915_oa_stream_enable,
1958 .disable = i915_oa_stream_disable,
1959 .wait_unlocked = i915_oa_wait_unlocked,
1960 .poll_wait = i915_oa_poll_wait,
1961 .read = i915_oa_read,
1962};
1963
Robert Bragg16d98b32016-12-07 21:40:33 +00001964/**
1965 * i915_oa_stream_init - validate combined props for OA stream and init
1966 * @stream: An i915 perf stream
1967 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1968 * @props: The property state that configures stream (individually validated)
1969 *
1970 * While read_properties_unlocked() validates properties in isolation it
1971 * doesn't ensure that the combination necessarily makes sense.
1972 *
1973 * At this point it has been determined that userspace wants a stream of
1974 * OA metrics, but still we need to further validate the combined
1975 * properties are OK.
1976 *
1977 * If the configuration makes sense then we can allocate memory for
1978 * a circular OA buffer and apply the requested metric set configuration.
1979 *
1980 * Returns: zero on success or a negative error code.
1981 */
Robert Braggd7965152016-11-07 19:49:52 +00001982static int i915_oa_stream_init(struct i915_perf_stream *stream,
1983 struct drm_i915_perf_open_param *param,
1984 struct perf_open_properties *props)
1985{
1986 struct drm_i915_private *dev_priv = stream->dev_priv;
1987 int format_size;
1988 int ret;
1989
Robert Bragg442b8c02016-11-07 19:49:53 +00001990 /* If the sysfs metrics/ directory wasn't registered for some
1991 * reason then don't let userspace try their luck with config
1992 * IDs
1993 */
1994 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00001995 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00001996 return -EINVAL;
1997 }
1998
Robert Braggd7965152016-11-07 19:49:52 +00001999 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00002000 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00002001 return -EINVAL;
2002 }
2003
2004 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
Robert Bragg77085502016-12-01 17:21:52 +00002005 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00002006 return -ENODEV;
2007 }
2008
2009 /* To avoid the complexity of having to accurately filter
2010 * counter reports and marshal to the appropriate client
2011 * we currently only allow exclusive access
2012 */
2013 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00002014 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00002015 return -EBUSY;
2016 }
2017
2018 if (!props->metrics_set) {
Robert Bragg77085502016-12-01 17:21:52 +00002019 DRM_DEBUG("OA metric set not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00002020 return -EINVAL;
2021 }
2022
2023 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00002024 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00002025 return -EINVAL;
2026 }
2027
Robert Bragg712122e2017-05-11 16:43:31 +01002028 /* We set up some ratelimit state to potentially throttle any _NOTES
2029 * about spurious, invalid OA reports which we don't forward to
2030 * userspace.
2031 *
2032 * The initialization is associated with opening the stream (not driver
2033 * init) considering we print a _NOTE about any throttling when closing
2034 * the stream instead of waiting until driver _fini which no one would
2035 * ever see.
2036 *
2037 * Using the same limiting factors as printk_ratelimit()
2038 */
2039 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
2040 5 * HZ, 10);
2041 /* Since we use a DRM_NOTE for spurious reports it would be
2042 * inconsistent to let __ratelimit() automatically print a warning for
2043 * throttling.
2044 */
2045 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
2046 RATELIMIT_MSG_ON_RELEASE);
2047
Robert Braggd7965152016-11-07 19:49:52 +00002048 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
2049
2050 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
2051
2052 stream->sample_flags |= SAMPLE_OA_REPORT;
2053 stream->sample_size += format_size;
2054
2055 dev_priv->perf.oa.oa_buffer.format_size = format_size;
2056 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
2057 return -EINVAL;
2058
2059 dev_priv->perf.oa.oa_buffer.format =
2060 dev_priv->perf.oa.oa_formats[props->oa_format].format;
2061
2062 dev_priv->perf.oa.metrics_set = props->metrics_set;
2063
2064 dev_priv->perf.oa.periodic = props->oa_periodic;
Robert Bragg0dd860c2017-05-11 16:43:28 +01002065 if (dev_priv->perf.oa.periodic)
Robert Braggd7965152016-11-07 19:49:52 +00002066 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
2067
Robert Braggd7965152016-11-07 19:49:52 +00002068 if (stream->ctx) {
2069 ret = oa_get_render_ctx_id(stream);
2070 if (ret)
2071 return ret;
2072 }
2073
2074 ret = alloc_oa_buffer(dev_priv);
2075 if (ret)
2076 goto err_oa_buf_alloc;
2077
2078 /* PRM - observability performance counters:
2079 *
2080 * OACONTROL, performance counter enable, note:
2081 *
2082 * "When this bit is set, in order to have coherent counts,
2083 * RC6 power state and trunk clock gating must be disabled.
2084 * This can be achieved by programming MMIO registers as
2085 * 0xA094=0 and 0xA090[31]=1"
2086 *
2087 * In our case we are expecting that taking pm + FORCEWAKE
2088 * references will effectively disable RC6.
2089 */
2090 intel_runtime_pm_get(dev_priv);
2091 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
2092
2093 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv);
2094 if (ret)
2095 goto err_enable;
2096
2097 stream->ops = &i915_oa_stream_ops;
2098
2099 dev_priv->perf.oa.exclusive_stream = stream;
2100
2101 return 0;
2102
2103err_enable:
2104 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
2105 intel_runtime_pm_put(dev_priv);
2106 free_oa_buffer(dev_priv);
2107
2108err_oa_buf_alloc:
2109 if (stream->ctx)
2110 oa_put_render_ctx_id(stream);
2111
2112 return ret;
2113}
2114
Robert Bragg19f81df2017-06-13 12:23:03 +01002115void i915_oa_init_reg_state(struct intel_engine_cs *engine,
2116 struct i915_gem_context *ctx,
2117 u32 *reg_state)
2118{
2119 struct drm_i915_private *dev_priv = engine->i915;
2120
2121 if (engine->id != RCS)
2122 return;
2123
2124 if (!dev_priv->perf.initialized)
2125 return;
2126
2127 gen8_update_reg_state_unlocked(ctx, reg_state);
2128}
2129
Robert Bragg16d98b32016-12-07 21:40:33 +00002130/**
2131 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
2132 * @stream: An i915 perf stream
2133 * @file: An i915 perf stream file
2134 * @buf: destination buffer given by userspace
2135 * @count: the number of bytes userspace wants to read
2136 * @ppos: (inout) file seek position (unused)
2137 *
2138 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
2139 * ensure that if we've successfully copied any data then reporting that takes
2140 * precedence over any internal error status, so the data isn't lost.
2141 *
2142 * For example ret will be -ENOSPC whenever there is more buffered data than
2143 * can be copied to userspace, but that's only interesting if we weren't able
2144 * to copy some data because it implies the userspace buffer is too small to
2145 * receive a single record (and we never split records).
2146 *
2147 * Another case with ret == -EFAULT is more of a grey area since it would seem
2148 * like bad form for userspace to ask us to overrun its buffer, but the user
2149 * knows best:
2150 *
2151 * http://yarchive.net/comp/linux/partial_reads_writes.html
2152 *
2153 * Returns: The number of bytes copied or a negative error code on failure.
2154 */
Robert Braggeec688e2016-11-07 19:49:47 +00002155static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
2156 struct file *file,
2157 char __user *buf,
2158 size_t count,
2159 loff_t *ppos)
2160{
2161 /* Note we keep the offset (aka bytes read) separate from any
2162 * error status so that the final check for whether we return
2163 * the bytes read with a higher precedence than any error (see
2164 * comment below) doesn't need to be handled/duplicated in
2165 * stream->ops->read() implementations.
2166 */
2167 size_t offset = 0;
2168 int ret = stream->ops->read(stream, buf, count, &offset);
2169
Robert Braggeec688e2016-11-07 19:49:47 +00002170 return offset ?: (ret ?: -EAGAIN);
2171}
2172
Robert Bragg16d98b32016-12-07 21:40:33 +00002173/**
2174 * i915_perf_read - handles read() FOP for i915 perf stream FDs
2175 * @file: An i915 perf stream file
2176 * @buf: destination buffer given by userspace
2177 * @count: the number of bytes userspace wants to read
2178 * @ppos: (inout) file seek position (unused)
2179 *
2180 * The entry point for handling a read() on a stream file descriptor from
2181 * userspace. Most of the work is left to the i915_perf_read_locked() and
2182 * &i915_perf_stream_ops->read but to save having stream implementations (of
2183 * which we might have multiple later) we handle blocking read here.
2184 *
2185 * We can also consistently treat trying to read from a disabled stream
2186 * as an IO error so implementations can assume the stream is enabled
2187 * while reading.
2188 *
2189 * Returns: The number of bytes copied or a negative error code on failure.
2190 */
Robert Braggeec688e2016-11-07 19:49:47 +00002191static ssize_t i915_perf_read(struct file *file,
2192 char __user *buf,
2193 size_t count,
2194 loff_t *ppos)
2195{
2196 struct i915_perf_stream *stream = file->private_data;
2197 struct drm_i915_private *dev_priv = stream->dev_priv;
2198 ssize_t ret;
2199
Robert Braggd7965152016-11-07 19:49:52 +00002200 /* To ensure it's handled consistently we simply treat all reads of a
2201 * disabled stream as an error. In particular it might otherwise lead
2202 * to a deadlock for blocking file descriptors...
2203 */
2204 if (!stream->enabled)
2205 return -EIO;
2206
Robert Braggeec688e2016-11-07 19:49:47 +00002207 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00002208 /* There's the small chance of false positives from
2209 * stream->ops->wait_unlocked.
2210 *
2211 * E.g. with single context filtering since we only wait until
2212 * oabuffer has >= 1 report we don't immediately know whether
2213 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00002214 */
2215 do {
2216 ret = stream->ops->wait_unlocked(stream);
2217 if (ret)
2218 return ret;
2219
2220 mutex_lock(&dev_priv->perf.lock);
2221 ret = i915_perf_read_locked(stream, file,
2222 buf, count, ppos);
2223 mutex_unlock(&dev_priv->perf.lock);
2224 } while (ret == -EAGAIN);
2225 } else {
2226 mutex_lock(&dev_priv->perf.lock);
2227 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
2228 mutex_unlock(&dev_priv->perf.lock);
2229 }
2230
Robert Bragg26ebd9c2017-05-11 16:43:25 +01002231 /* We allow the poll checking to sometimes report false positive POLLIN
2232 * events where we might actually report EAGAIN on read() if there's
2233 * not really any data available. In this situation though we don't
2234 * want to enter a busy loop between poll() reporting a POLLIN event
2235 * and read() returning -EAGAIN. Clearing the oa.pollin state here
2236 * effectively ensures we back off until the next hrtimer callback
2237 * before reporting another POLLIN event.
2238 */
2239 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00002240 /* Maybe make ->pollin per-stream state if we support multiple
2241 * concurrent streams in the future.
2242 */
2243 dev_priv->perf.oa.pollin = false;
2244 }
2245
Robert Braggeec688e2016-11-07 19:49:47 +00002246 return ret;
2247}
2248
Robert Braggd7965152016-11-07 19:49:52 +00002249static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
2250{
2251 struct drm_i915_private *dev_priv =
2252 container_of(hrtimer, typeof(*dev_priv),
2253 perf.oa.poll_check_timer);
2254
Robert Bragg19f81df2017-06-13 12:23:03 +01002255 if (oa_buffer_check_unlocked(dev_priv)) {
Robert Braggd7965152016-11-07 19:49:52 +00002256 dev_priv->perf.oa.pollin = true;
2257 wake_up(&dev_priv->perf.oa.poll_wq);
2258 }
2259
2260 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
2261
2262 return HRTIMER_RESTART;
2263}
2264
Robert Bragg16d98b32016-12-07 21:40:33 +00002265/**
2266 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
2267 * @dev_priv: i915 device instance
2268 * @stream: An i915 perf stream
2269 * @file: An i915 perf stream file
2270 * @wait: poll() state table
2271 *
2272 * For handling userspace polling on an i915 perf stream, this calls through to
2273 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
2274 * will be woken for new stream data.
2275 *
2276 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2277 * with any non-file-operation driver hooks.
2278 *
2279 * Returns: any poll events that are ready without sleeping
2280 */
Robert Braggd7965152016-11-07 19:49:52 +00002281static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
2282 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00002283 struct file *file,
2284 poll_table *wait)
2285{
Robert Braggd7965152016-11-07 19:49:52 +00002286 unsigned int events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00002287
2288 stream->ops->poll_wait(stream, file, wait);
2289
Robert Braggd7965152016-11-07 19:49:52 +00002290 /* Note: we don't explicitly check whether there's something to read
2291 * here since this path may be very hot depending on what else
2292 * userspace is polling, or on the timeout in use. We rely solely on
2293 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
2294 * samples to read.
2295 */
2296 if (dev_priv->perf.oa.pollin)
2297 events |= POLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00002298
Robert Braggd7965152016-11-07 19:49:52 +00002299 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00002300}
2301
Robert Bragg16d98b32016-12-07 21:40:33 +00002302/**
2303 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
2304 * @file: An i915 perf stream file
2305 * @wait: poll() state table
2306 *
2307 * For handling userspace polling on an i915 perf stream, this ensures
2308 * poll_wait() gets called with a wait queue that will be woken for new stream
2309 * data.
2310 *
2311 * Note: Implementation deferred to i915_perf_poll_locked()
2312 *
2313 * Returns: any poll events that are ready without sleeping
2314 */
Robert Braggeec688e2016-11-07 19:49:47 +00002315static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
2316{
2317 struct i915_perf_stream *stream = file->private_data;
2318 struct drm_i915_private *dev_priv = stream->dev_priv;
2319 int ret;
2320
2321 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002322 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00002323 mutex_unlock(&dev_priv->perf.lock);
2324
2325 return ret;
2326}
2327
Robert Bragg16d98b32016-12-07 21:40:33 +00002328/**
2329 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
2330 * @stream: A disabled i915 perf stream
2331 *
2332 * [Re]enables the associated capture of data for this stream.
2333 *
2334 * If a stream was previously enabled then there's currently no intention
2335 * to provide userspace any guarantee about the preservation of previously
2336 * buffered data.
2337 */
Robert Braggeec688e2016-11-07 19:49:47 +00002338static void i915_perf_enable_locked(struct i915_perf_stream *stream)
2339{
2340 if (stream->enabled)
2341 return;
2342
2343 /* Allow stream->ops->enable() to refer to this */
2344 stream->enabled = true;
2345
2346 if (stream->ops->enable)
2347 stream->ops->enable(stream);
2348}
2349
Robert Bragg16d98b32016-12-07 21:40:33 +00002350/**
2351 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
2352 * @stream: An enabled i915 perf stream
2353 *
2354 * Disables the associated capture of data for this stream.
2355 *
2356 * The intention is that disabling an re-enabling a stream will ideally be
2357 * cheaper than destroying and re-opening a stream with the same configuration,
2358 * though there are no formal guarantees about what state or buffered data
2359 * must be retained between disabling and re-enabling a stream.
2360 *
2361 * Note: while a stream is disabled it's considered an error for userspace
2362 * to attempt to read from the stream (-EIO).
2363 */
Robert Braggeec688e2016-11-07 19:49:47 +00002364static void i915_perf_disable_locked(struct i915_perf_stream *stream)
2365{
2366 if (!stream->enabled)
2367 return;
2368
2369 /* Allow stream->ops->disable() to refer to this */
2370 stream->enabled = false;
2371
2372 if (stream->ops->disable)
2373 stream->ops->disable(stream);
2374}
2375
Robert Bragg16d98b32016-12-07 21:40:33 +00002376/**
2377 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2378 * @stream: An i915 perf stream
2379 * @cmd: the ioctl request
2380 * @arg: the ioctl data
2381 *
2382 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2383 * with any non-file-operation driver hooks.
2384 *
2385 * Returns: zero on success or a negative error code. Returns -EINVAL for
2386 * an unknown ioctl request.
2387 */
Robert Braggeec688e2016-11-07 19:49:47 +00002388static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
2389 unsigned int cmd,
2390 unsigned long arg)
2391{
2392 switch (cmd) {
2393 case I915_PERF_IOCTL_ENABLE:
2394 i915_perf_enable_locked(stream);
2395 return 0;
2396 case I915_PERF_IOCTL_DISABLE:
2397 i915_perf_disable_locked(stream);
2398 return 0;
2399 }
2400
2401 return -EINVAL;
2402}
2403
Robert Bragg16d98b32016-12-07 21:40:33 +00002404/**
2405 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
2406 * @file: An i915 perf stream file
2407 * @cmd: the ioctl request
2408 * @arg: the ioctl data
2409 *
2410 * Implementation deferred to i915_perf_ioctl_locked().
2411 *
2412 * Returns: zero on success or a negative error code. Returns -EINVAL for
2413 * an unknown ioctl request.
2414 */
Robert Braggeec688e2016-11-07 19:49:47 +00002415static long i915_perf_ioctl(struct file *file,
2416 unsigned int cmd,
2417 unsigned long arg)
2418{
2419 struct i915_perf_stream *stream = file->private_data;
2420 struct drm_i915_private *dev_priv = stream->dev_priv;
2421 long ret;
2422
2423 mutex_lock(&dev_priv->perf.lock);
2424 ret = i915_perf_ioctl_locked(stream, cmd, arg);
2425 mutex_unlock(&dev_priv->perf.lock);
2426
2427 return ret;
2428}
2429
Robert Bragg16d98b32016-12-07 21:40:33 +00002430/**
2431 * i915_perf_destroy_locked - destroy an i915 perf stream
2432 * @stream: An i915 perf stream
2433 *
2434 * Frees all resources associated with the given i915 perf @stream, disabling
2435 * any associated data capture in the process.
2436 *
2437 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
2438 * with any non-file-operation driver hooks.
2439 */
Robert Braggeec688e2016-11-07 19:49:47 +00002440static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
2441{
Robert Braggeec688e2016-11-07 19:49:47 +00002442 if (stream->enabled)
2443 i915_perf_disable_locked(stream);
2444
2445 if (stream->ops->destroy)
2446 stream->ops->destroy(stream);
2447
2448 list_del(&stream->link);
2449
Chris Wilson69df05e2016-12-18 15:37:21 +00002450 if (stream->ctx)
2451 i915_gem_context_put_unlocked(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00002452
2453 kfree(stream);
2454}
2455
Robert Bragg16d98b32016-12-07 21:40:33 +00002456/**
2457 * i915_perf_release - handles userspace close() of a stream file
2458 * @inode: anonymous inode associated with file
2459 * @file: An i915 perf stream file
2460 *
2461 * Cleans up any resources associated with an open i915 perf stream file.
2462 *
2463 * NB: close() can't really fail from the userspace point of view.
2464 *
2465 * Returns: zero on success or a negative error code.
2466 */
Robert Braggeec688e2016-11-07 19:49:47 +00002467static int i915_perf_release(struct inode *inode, struct file *file)
2468{
2469 struct i915_perf_stream *stream = file->private_data;
2470 struct drm_i915_private *dev_priv = stream->dev_priv;
2471
2472 mutex_lock(&dev_priv->perf.lock);
2473 i915_perf_destroy_locked(stream);
2474 mutex_unlock(&dev_priv->perf.lock);
2475
2476 return 0;
2477}
2478
2479
2480static const struct file_operations fops = {
2481 .owner = THIS_MODULE,
2482 .llseek = no_llseek,
2483 .release = i915_perf_release,
2484 .poll = i915_perf_poll,
2485 .read = i915_perf_read,
2486 .unlocked_ioctl = i915_perf_ioctl,
2487};
2488
2489
2490static struct i915_gem_context *
2491lookup_context(struct drm_i915_private *dev_priv,
2492 struct drm_i915_file_private *file_priv,
2493 u32 ctx_user_handle)
2494{
2495 struct i915_gem_context *ctx;
2496 int ret;
2497
2498 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
2499 if (ret)
2500 return ERR_PTR(ret);
2501
2502 ctx = i915_gem_context_lookup(file_priv, ctx_user_handle);
2503 if (!IS_ERR(ctx))
2504 i915_gem_context_get(ctx);
2505
2506 mutex_unlock(&dev_priv->drm.struct_mutex);
2507
2508 return ctx;
2509}
2510
Robert Bragg16d98b32016-12-07 21:40:33 +00002511/**
2512 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
2513 * @dev_priv: i915 device instance
2514 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
2515 * @props: individually validated u64 property value pairs
2516 * @file: drm file
2517 *
2518 * See i915_perf_ioctl_open() for interface details.
2519 *
2520 * Implements further stream config validation and stream initialization on
2521 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
2522 * taken to serialize with any non-file-operation driver hooks.
2523 *
2524 * Note: at this point the @props have only been validated in isolation and
2525 * it's still necessary to validate that the combination of properties makes
2526 * sense.
2527 *
2528 * In the case where userspace is interested in OA unit metrics then further
2529 * config validation and stream initialization details will be handled by
2530 * i915_oa_stream_init(). The code here should only validate config state that
2531 * will be relevant to all stream types / backends.
2532 *
2533 * Returns: zero on success or a negative error code.
2534 */
Robert Braggeec688e2016-11-07 19:49:47 +00002535static int
2536i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
2537 struct drm_i915_perf_open_param *param,
2538 struct perf_open_properties *props,
2539 struct drm_file *file)
2540{
2541 struct i915_gem_context *specific_ctx = NULL;
2542 struct i915_perf_stream *stream = NULL;
2543 unsigned long f_flags = 0;
Robert Bragg19f81df2017-06-13 12:23:03 +01002544 bool privileged_op = true;
Robert Braggeec688e2016-11-07 19:49:47 +00002545 int stream_fd;
2546 int ret;
2547
2548 if (props->single_context) {
2549 u32 ctx_handle = props->ctx_handle;
2550 struct drm_i915_file_private *file_priv = file->driver_priv;
2551
2552 specific_ctx = lookup_context(dev_priv, file_priv, ctx_handle);
2553 if (IS_ERR(specific_ctx)) {
2554 ret = PTR_ERR(specific_ctx);
2555 if (ret != -EINTR)
Robert Bragg77085502016-12-01 17:21:52 +00002556 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
Robert Braggeec688e2016-11-07 19:49:47 +00002557 ctx_handle);
2558 goto err;
2559 }
2560 }
2561
Robert Bragg19f81df2017-06-13 12:23:03 +01002562 /*
2563 * On Haswell the OA unit supports clock gating off for a specific
2564 * context and in this mode there's no visibility of metrics for the
2565 * rest of the system, which we consider acceptable for a
2566 * non-privileged client.
2567 *
2568 * For Gen8+ the OA unit no longer supports clock gating off for a
2569 * specific context and the kernel can't securely stop the counters
2570 * from updating as system-wide / global values. Even though we can
2571 * filter reports based on the included context ID we can't block
2572 * clients from seeing the raw / global counter values via
2573 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
2574 * enable the OA unit by default.
2575 */
2576 if (IS_HASWELL(dev_priv) && specific_ctx)
2577 privileged_op = false;
2578
Robert Braggccdf6342016-11-07 19:49:54 +00002579 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
2580 * we check a dev.i915.perf_stream_paranoid sysctl option
2581 * to determine if it's ok to access system wide OA counters
2582 * without CAP_SYS_ADMIN privileges.
2583 */
Robert Bragg19f81df2017-06-13 12:23:03 +01002584 if (privileged_op &&
Robert Braggccdf6342016-11-07 19:49:54 +00002585 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00002586 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002587 ret = -EACCES;
2588 goto err_ctx;
2589 }
2590
2591 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
2592 if (!stream) {
2593 ret = -ENOMEM;
2594 goto err_ctx;
2595 }
2596
Robert Braggeec688e2016-11-07 19:49:47 +00002597 stream->dev_priv = dev_priv;
2598 stream->ctx = specific_ctx;
2599
Robert Braggd7965152016-11-07 19:49:52 +00002600 ret = i915_oa_stream_init(stream, param, props);
2601 if (ret)
2602 goto err_alloc;
2603
2604 /* we avoid simply assigning stream->sample_flags = props->sample_flags
2605 * to have _stream_init check the combination of sample flags more
2606 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00002607 */
Robert Braggd7965152016-11-07 19:49:52 +00002608 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
2609 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01002610 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00002611 }
Robert Braggeec688e2016-11-07 19:49:47 +00002612
2613 list_add(&stream->link, &dev_priv->perf.streams);
2614
2615 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
2616 f_flags |= O_CLOEXEC;
2617 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
2618 f_flags |= O_NONBLOCK;
2619
2620 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
2621 if (stream_fd < 0) {
2622 ret = stream_fd;
2623 goto err_open;
2624 }
2625
2626 if (!(param->flags & I915_PERF_FLAG_DISABLED))
2627 i915_perf_enable_locked(stream);
2628
2629 return stream_fd;
2630
2631err_open:
2632 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01002633err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00002634 if (stream->ops->destroy)
2635 stream->ops->destroy(stream);
2636err_alloc:
2637 kfree(stream);
2638err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00002639 if (specific_ctx)
2640 i915_gem_context_put_unlocked(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00002641err:
2642 return ret;
2643}
2644
Robert Bragg16d98b32016-12-07 21:40:33 +00002645/**
2646 * read_properties_unlocked - validate + copy userspace stream open properties
2647 * @dev_priv: i915 device instance
2648 * @uprops: The array of u64 key value pairs given by userspace
2649 * @n_props: The number of key value pairs expected in @uprops
2650 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00002651 *
2652 * Note this function only validates properties in isolation it doesn't
2653 * validate that the combination of properties makes sense or that all
2654 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00002655 *
2656 * Note that there currently aren't any ordering requirements for properties so
2657 * we shouldn't validate or assume anything about ordering here. This doesn't
2658 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00002659 */
2660static int read_properties_unlocked(struct drm_i915_private *dev_priv,
2661 u64 __user *uprops,
2662 u32 n_props,
2663 struct perf_open_properties *props)
2664{
2665 u64 __user *uprop = uprops;
2666 int i;
2667
2668 memset(props, 0, sizeof(struct perf_open_properties));
2669
2670 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00002671 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002672 return -EINVAL;
2673 }
2674
2675 /* Considering that ID = 0 is reserved and assuming that we don't
2676 * (currently) expect any configurations to ever specify duplicate
2677 * values for a particular property ID then the last _PROP_MAX value is
2678 * one greater than the maximum number of properties we expect to get
2679 * from userspace.
2680 */
2681 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00002682 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002683 return -EINVAL;
2684 }
2685
2686 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00002687 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00002688 u64 id, value;
2689 int ret;
2690
2691 ret = get_user(id, uprop);
2692 if (ret)
2693 return ret;
2694
2695 ret = get_user(value, uprop + 1);
2696 if (ret)
2697 return ret;
2698
Matthew Auld0a309f92017-03-27 21:32:36 +01002699 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
2700 DRM_DEBUG("Unknown i915 perf property ID\n");
2701 return -EINVAL;
2702 }
2703
Robert Braggeec688e2016-11-07 19:49:47 +00002704 switch ((enum drm_i915_perf_property_id)id) {
2705 case DRM_I915_PERF_PROP_CTX_HANDLE:
2706 props->single_context = 1;
2707 props->ctx_handle = value;
2708 break;
Robert Braggd7965152016-11-07 19:49:52 +00002709 case DRM_I915_PERF_PROP_SAMPLE_OA:
2710 props->sample_flags |= SAMPLE_OA_REPORT;
2711 break;
2712 case DRM_I915_PERF_PROP_OA_METRICS_SET:
2713 if (value == 0 ||
2714 value > dev_priv->perf.oa.n_builtin_sets) {
Robert Bragg77085502016-12-01 17:21:52 +00002715 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00002716 return -EINVAL;
2717 }
2718 props->metrics_set = value;
2719 break;
2720 case DRM_I915_PERF_PROP_OA_FORMAT:
2721 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg52c57c22017-05-11 16:43:29 +01002722 DRM_DEBUG("Out-of-range OA report format %llu\n",
2723 value);
Robert Braggd7965152016-11-07 19:49:52 +00002724 return -EINVAL;
2725 }
2726 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg52c57c22017-05-11 16:43:29 +01002727 DRM_DEBUG("Unsupported OA report format %llu\n",
2728 value);
Robert Braggd7965152016-11-07 19:49:52 +00002729 return -EINVAL;
2730 }
2731 props->oa_format = value;
2732 break;
2733 case DRM_I915_PERF_PROP_OA_EXPONENT:
2734 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00002735 DRM_DEBUG("OA timer exponent too high (> %u)\n",
2736 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00002737 return -EINVAL;
2738 }
2739
Robert Bragg00319ba2016-11-07 19:49:55 +00002740 /* Theoretically we can program the OA unit to sample
Robert Braggd7965152016-11-07 19:49:52 +00002741 * every 160ns but don't allow that by default unless
2742 * root.
2743 *
Robert Bragg00319ba2016-11-07 19:49:55 +00002744 * On Haswell the period is derived from the exponent
2745 * as:
2746 *
2747 * period = 80ns * 2^(exponent + 1)
Robert Braggd7965152016-11-07 19:49:52 +00002748 */
Robert Bragg00319ba2016-11-07 19:49:55 +00002749 BUILD_BUG_ON(sizeof(oa_period) != 8);
2750 oa_period = 80ull * (2ull << value);
2751
2752 /* This check is primarily to ensure that oa_period <=
2753 * UINT32_MAX (before passing to do_div which only
2754 * accepts a u32 denominator), but we can also skip
2755 * checking anything < 1Hz which implicitly can't be
2756 * limited via an integer oa_max_sample_rate.
2757 */
2758 if (oa_period <= NSEC_PER_SEC) {
2759 u64 tmp = NSEC_PER_SEC;
2760 do_div(tmp, oa_period);
2761 oa_freq_hz = tmp;
2762 } else
2763 oa_freq_hz = 0;
2764
2765 if (oa_freq_hz > i915_oa_max_sample_rate &&
2766 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00002767 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 +00002768 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00002769 return -EACCES;
2770 }
2771
2772 props->oa_periodic = true;
2773 props->oa_period_exponent = value;
2774 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01002775 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00002776 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00002777 return -EINVAL;
2778 }
2779
2780 uprop += 2;
2781 }
2782
2783 return 0;
2784}
2785
Robert Bragg16d98b32016-12-07 21:40:33 +00002786/**
2787 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
2788 * @dev: drm device
2789 * @data: ioctl data copied from userspace (unvalidated)
2790 * @file: drm file
2791 *
2792 * Validates the stream open parameters given by userspace including flags
2793 * and an array of u64 key, value pair properties.
2794 *
2795 * Very little is assumed up front about the nature of the stream being
2796 * opened (for instance we don't assume it's for periodic OA unit metrics). An
2797 * i915-perf stream is expected to be a suitable interface for other forms of
2798 * buffered data written by the GPU besides periodic OA metrics.
2799 *
2800 * Note we copy the properties from userspace outside of the i915 perf
2801 * mutex to avoid an awkward lockdep with mmap_sem.
2802 *
2803 * Most of the implementation details are handled by
2804 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
2805 * mutex for serializing with any non-file-operation driver hooks.
2806 *
2807 * Return: A newly opened i915 Perf stream file descriptor or negative
2808 * error code on failure.
2809 */
Robert Braggeec688e2016-11-07 19:49:47 +00002810int i915_perf_open_ioctl(struct drm_device *dev, void *data,
2811 struct drm_file *file)
2812{
2813 struct drm_i915_private *dev_priv = dev->dev_private;
2814 struct drm_i915_perf_open_param *param = data;
2815 struct perf_open_properties props;
2816 u32 known_open_flags;
2817 int ret;
2818
2819 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00002820 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002821 return -ENOTSUPP;
2822 }
2823
2824 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
2825 I915_PERF_FLAG_FD_NONBLOCK |
2826 I915_PERF_FLAG_DISABLED;
2827 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00002828 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002829 return -EINVAL;
2830 }
2831
2832 ret = read_properties_unlocked(dev_priv,
2833 u64_to_user_ptr(param->properties_ptr),
2834 param->num_properties,
2835 &props);
2836 if (ret)
2837 return ret;
2838
2839 mutex_lock(&dev_priv->perf.lock);
2840 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
2841 mutex_unlock(&dev_priv->perf.lock);
2842
2843 return ret;
2844}
2845
Robert Bragg16d98b32016-12-07 21:40:33 +00002846/**
2847 * i915_perf_register - exposes i915-perf to userspace
2848 * @dev_priv: i915 device instance
2849 *
2850 * In particular OA metric sets are advertised under a sysfs metrics/
2851 * directory allowing userspace to enumerate valid IDs that can be
2852 * used to open an i915-perf stream.
2853 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002854void i915_perf_register(struct drm_i915_private *dev_priv)
2855{
Robert Bragg442b8c02016-11-07 19:49:53 +00002856 if (!dev_priv->perf.initialized)
2857 return;
2858
2859 /* To be sure we're synchronized with an attempted
2860 * i915_perf_open_ioctl(); considering that we register after
2861 * being exposed to userspace.
2862 */
2863 mutex_lock(&dev_priv->perf.lock);
2864
2865 dev_priv->perf.metrics_kobj =
2866 kobject_create_and_add("metrics",
2867 &dev_priv->drm.primary->kdev->kobj);
2868 if (!dev_priv->perf.metrics_kobj)
2869 goto exit;
2870
Robert Bragg19f81df2017-06-13 12:23:03 +01002871 if (IS_HASWELL(dev_priv)) {
2872 if (i915_perf_register_sysfs_hsw(dev_priv))
2873 goto sysfs_error;
2874 } else if (IS_BROADWELL(dev_priv)) {
2875 if (i915_perf_register_sysfs_bdw(dev_priv))
2876 goto sysfs_error;
2877 } else if (IS_CHERRYVIEW(dev_priv)) {
2878 if (i915_perf_register_sysfs_chv(dev_priv))
2879 goto sysfs_error;
2880 } else if (IS_SKYLAKE(dev_priv)) {
2881 if (IS_SKL_GT2(dev_priv)) {
2882 if (i915_perf_register_sysfs_sklgt2(dev_priv))
2883 goto sysfs_error;
2884 } else if (IS_SKL_GT3(dev_priv)) {
2885 if (i915_perf_register_sysfs_sklgt3(dev_priv))
2886 goto sysfs_error;
2887 } else if (IS_SKL_GT4(dev_priv)) {
2888 if (i915_perf_register_sysfs_sklgt4(dev_priv))
2889 goto sysfs_error;
2890 } else
2891 goto sysfs_error;
2892 } else if (IS_BROXTON(dev_priv)) {
2893 if (i915_perf_register_sysfs_bxt(dev_priv))
2894 goto sysfs_error;
Robert Bragg442b8c02016-11-07 19:49:53 +00002895 }
2896
Robert Bragg19f81df2017-06-13 12:23:03 +01002897 goto exit;
2898
2899sysfs_error:
2900 kobject_put(dev_priv->perf.metrics_kobj);
2901 dev_priv->perf.metrics_kobj = NULL;
2902
Robert Bragg442b8c02016-11-07 19:49:53 +00002903exit:
2904 mutex_unlock(&dev_priv->perf.lock);
2905}
2906
Robert Bragg16d98b32016-12-07 21:40:33 +00002907/**
2908 * i915_perf_unregister - hide i915-perf from userspace
2909 * @dev_priv: i915 device instance
2910 *
2911 * i915-perf state cleanup is split up into an 'unregister' and
2912 * 'deinit' phase where the interface is first hidden from
2913 * userspace by i915_perf_unregister() before cleaning up
2914 * remaining state in i915_perf_fini().
2915 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002916void i915_perf_unregister(struct drm_i915_private *dev_priv)
2917{
Robert Bragg442b8c02016-11-07 19:49:53 +00002918 if (!dev_priv->perf.metrics_kobj)
2919 return;
2920
Robert Bragg19f81df2017-06-13 12:23:03 +01002921 if (IS_HASWELL(dev_priv))
2922 i915_perf_unregister_sysfs_hsw(dev_priv);
2923 else if (IS_BROADWELL(dev_priv))
2924 i915_perf_unregister_sysfs_bdw(dev_priv);
2925 else if (IS_CHERRYVIEW(dev_priv))
2926 i915_perf_unregister_sysfs_chv(dev_priv);
2927 else if (IS_SKYLAKE(dev_priv)) {
2928 if (IS_SKL_GT2(dev_priv))
2929 i915_perf_unregister_sysfs_sklgt2(dev_priv);
2930 else if (IS_SKL_GT3(dev_priv))
2931 i915_perf_unregister_sysfs_sklgt3(dev_priv);
2932 else if (IS_SKL_GT4(dev_priv))
2933 i915_perf_unregister_sysfs_sklgt4(dev_priv);
2934 } else if (IS_BROXTON(dev_priv))
2935 i915_perf_unregister_sysfs_bxt(dev_priv);
Robert Bragg442b8c02016-11-07 19:49:53 +00002936
2937 kobject_put(dev_priv->perf.metrics_kobj);
2938 dev_priv->perf.metrics_kobj = NULL;
2939}
2940
Robert Braggccdf6342016-11-07 19:49:54 +00002941static struct ctl_table oa_table[] = {
2942 {
2943 .procname = "perf_stream_paranoid",
2944 .data = &i915_perf_stream_paranoid,
2945 .maxlen = sizeof(i915_perf_stream_paranoid),
2946 .mode = 0644,
2947 .proc_handler = proc_dointvec_minmax,
2948 .extra1 = &zero,
2949 .extra2 = &one,
2950 },
Robert Bragg00319ba2016-11-07 19:49:55 +00002951 {
2952 .procname = "oa_max_sample_rate",
2953 .data = &i915_oa_max_sample_rate,
2954 .maxlen = sizeof(i915_oa_max_sample_rate),
2955 .mode = 0644,
2956 .proc_handler = proc_dointvec_minmax,
2957 .extra1 = &zero,
2958 .extra2 = &oa_sample_rate_hard_limit,
2959 },
Robert Braggccdf6342016-11-07 19:49:54 +00002960 {}
2961};
2962
2963static struct ctl_table i915_root[] = {
2964 {
2965 .procname = "i915",
2966 .maxlen = 0,
2967 .mode = 0555,
2968 .child = oa_table,
2969 },
2970 {}
2971};
2972
2973static struct ctl_table dev_root[] = {
2974 {
2975 .procname = "dev",
2976 .maxlen = 0,
2977 .mode = 0555,
2978 .child = i915_root,
2979 },
2980 {}
2981};
2982
Robert Bragg16d98b32016-12-07 21:40:33 +00002983/**
2984 * i915_perf_init - initialize i915-perf state on module load
2985 * @dev_priv: i915 device instance
2986 *
2987 * Initializes i915-perf state without exposing anything to userspace.
2988 *
2989 * Note: i915-perf initialization is split into an 'init' and 'register'
2990 * phase with the i915_perf_register() exposing state to userspace.
2991 */
Robert Braggeec688e2016-11-07 19:49:47 +00002992void i915_perf_init(struct drm_i915_private *dev_priv)
2993{
Robert Bragg19f81df2017-06-13 12:23:03 +01002994 dev_priv->perf.oa.n_builtin_sets = 0;
Robert Braggd7965152016-11-07 19:49:52 +00002995
Robert Bragg19f81df2017-06-13 12:23:03 +01002996 if (IS_HASWELL(dev_priv)) {
2997 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
2998 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
2999 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
3000 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
3001 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
3002 dev_priv->perf.oa.ops.read = gen7_oa_read;
3003 dev_priv->perf.oa.ops.oa_hw_tail_read =
3004 gen7_oa_hw_tail_read;
Robert Braggd7965152016-11-07 19:49:52 +00003005
Robert Bragg19f81df2017-06-13 12:23:03 +01003006 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
Robert Braggd7965152016-11-07 19:49:52 +00003007
Robert Bragg19f81df2017-06-13 12:23:03 +01003008 dev_priv->perf.oa.n_builtin_sets =
3009 i915_oa_n_builtin_metric_sets_hsw;
3010 } else if (i915.enable_execlists) {
3011 /* Note: that although we could theoretically also support the
3012 * legacy ringbuffer mode on BDW (and earlier iterations of
3013 * this driver, before upstreaming did this) it didn't seem
3014 * worth the complexity to maintain now that BDW+ enable
3015 * execlist mode by default.
3016 */
Robert Braggd7965152016-11-07 19:49:52 +00003017
Robert Bragg19f81df2017-06-13 12:23:03 +01003018 if (IS_GEN8(dev_priv)) {
3019 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x120;
3020 dev_priv->perf.oa.ctx_flexeu0_offset = 0x2ce;
3021 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<25);
Robert Braggd7965152016-11-07 19:49:52 +00003022
Robert Bragg19f81df2017-06-13 12:23:03 +01003023 if (IS_BROADWELL(dev_priv)) {
3024 dev_priv->perf.oa.n_builtin_sets =
3025 i915_oa_n_builtin_metric_sets_bdw;
3026 dev_priv->perf.oa.ops.select_metric_set =
3027 i915_oa_select_metric_set_bdw;
3028 } else if (IS_CHERRYVIEW(dev_priv)) {
3029 dev_priv->perf.oa.n_builtin_sets =
3030 i915_oa_n_builtin_metric_sets_chv;
3031 dev_priv->perf.oa.ops.select_metric_set =
3032 i915_oa_select_metric_set_chv;
3033 }
3034 } else if (IS_GEN9(dev_priv)) {
3035 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
3036 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
3037 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
Robert Braggeec688e2016-11-07 19:49:47 +00003038
Robert Bragg19f81df2017-06-13 12:23:03 +01003039 if (IS_SKL_GT2(dev_priv)) {
3040 dev_priv->perf.oa.n_builtin_sets =
3041 i915_oa_n_builtin_metric_sets_sklgt2;
3042 dev_priv->perf.oa.ops.select_metric_set =
3043 i915_oa_select_metric_set_sklgt2;
3044 } else if (IS_SKL_GT3(dev_priv)) {
3045 dev_priv->perf.oa.n_builtin_sets =
3046 i915_oa_n_builtin_metric_sets_sklgt3;
3047 dev_priv->perf.oa.ops.select_metric_set =
3048 i915_oa_select_metric_set_sklgt3;
3049 } else if (IS_SKL_GT4(dev_priv)) {
3050 dev_priv->perf.oa.n_builtin_sets =
3051 i915_oa_n_builtin_metric_sets_sklgt4;
3052 dev_priv->perf.oa.ops.select_metric_set =
3053 i915_oa_select_metric_set_sklgt4;
3054 } else if (IS_BROXTON(dev_priv)) {
3055 dev_priv->perf.oa.n_builtin_sets =
3056 i915_oa_n_builtin_metric_sets_bxt;
3057 dev_priv->perf.oa.ops.select_metric_set =
3058 i915_oa_select_metric_set_bxt;
3059 }
3060 }
Robert Braggccdf6342016-11-07 19:49:54 +00003061
Robert Bragg19f81df2017-06-13 12:23:03 +01003062 if (dev_priv->perf.oa.n_builtin_sets) {
3063 dev_priv->perf.oa.ops.init_oa_buffer = gen8_init_oa_buffer;
3064 dev_priv->perf.oa.ops.enable_metric_set =
3065 gen8_enable_metric_set;
3066 dev_priv->perf.oa.ops.disable_metric_set =
3067 gen8_disable_metric_set;
3068 dev_priv->perf.oa.ops.oa_enable = gen8_oa_enable;
3069 dev_priv->perf.oa.ops.oa_disable = gen8_oa_disable;
3070 dev_priv->perf.oa.ops.read = gen8_oa_read;
3071 dev_priv->perf.oa.ops.oa_hw_tail_read =
3072 gen8_oa_hw_tail_read;
3073
3074 dev_priv->perf.oa.oa_formats = gen8_plus_oa_formats;
3075 }
3076 }
3077
3078 if (dev_priv->perf.oa.n_builtin_sets) {
3079 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
3080 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3081 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
3082 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
3083
3084 INIT_LIST_HEAD(&dev_priv->perf.streams);
3085 mutex_init(&dev_priv->perf.lock);
3086 spin_lock_init(&dev_priv->perf.hook_lock);
3087 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
3088
3089 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
3090
3091 dev_priv->perf.initialized = true;
3092 }
Robert Braggeec688e2016-11-07 19:49:47 +00003093}
3094
Robert Bragg16d98b32016-12-07 21:40:33 +00003095/**
3096 * i915_perf_fini - Counter part to i915_perf_init()
3097 * @dev_priv: i915 device instance
3098 */
Robert Braggeec688e2016-11-07 19:49:47 +00003099void i915_perf_fini(struct drm_i915_private *dev_priv)
3100{
3101 if (!dev_priv->perf.initialized)
3102 return;
3103
Robert Braggccdf6342016-11-07 19:49:54 +00003104 unregister_sysctl_table(dev_priv->perf.sysctl_header);
3105
Robert Braggd7965152016-11-07 19:49:52 +00003106 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Bragg19f81df2017-06-13 12:23:03 +01003107
Robert Braggeec688e2016-11-07 19:49:47 +00003108 dev_priv->perf.initialized = false;
3109}