blob: 29cad6bb73d6be364f6059dc4c3b3aaa4689841c [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"
199
200/* HW requires this to be a power of two, between 128k and 16M, though driver
201 * is currently generally designed assuming the largest 16M size is used such
202 * that the overflow cases are unlikely in normal operation.
203 */
204#define OA_BUFFER_SIZE SZ_16M
205
206#define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
207
208/* There's a HW race condition between OA unit tail pointer register updates and
209 * writes to memory whereby the tail pointer can sometimes get ahead of what's
210 * been written out to the OA buffer so far.
211 *
212 * Although this can be observed explicitly by checking for a zeroed report-id
213 * field in tail reports, it seems preferable to account for this earlier e.g.
214 * as part of the _oa_buffer_is_empty checks to minimize -EAGAIN polling cycles
215 * in this situation.
216 *
217 * To give time for the most recent reports to land before they may be copied to
218 * userspace, the driver operates as if the tail pointer effectively lags behind
219 * the HW tail pointer by 'tail_margin' bytes. The margin in bytes is calculated
220 * based on this constant in nanoseconds, the current OA sampling exponent
221 * and current report size.
222 *
223 * There is also a fallback check while reading to simply skip over reports with
224 * a zeroed report-id.
225 */
226#define OA_TAIL_MARGIN_NSEC 100000ULL
227
228/* frequency for checking whether the OA unit has written new reports to the
229 * circular OA buffer...
230 */
231#define POLL_FREQUENCY 200
232#define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
233
Robert Braggccdf6342016-11-07 19:49:54 +0000234/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
235static int zero;
236static int one = 1;
237static u32 i915_perf_stream_paranoid = true;
238
Robert Braggd7965152016-11-07 19:49:52 +0000239/* The maximum exponent the hardware accepts is 63 (essentially it selects one
240 * of the 64bit timestamp bits to trigger reports from) but there's currently
241 * no known use case for sampling as infrequently as once per 47 thousand years.
242 *
243 * Since the timestamps included in OA reports are only 32bits it seems
244 * reasonable to limit the OA exponent where it's still possible to account for
245 * overflow in OA report timestamps.
246 */
247#define OA_EXPONENT_MAX 31
248
249#define INVALID_CTX_ID 0xffffffff
250
251
Robert Bragg00319ba2016-11-07 19:49:55 +0000252/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
253 *
254 * 160ns is the smallest sampling period we can theoretically program the OA
255 * unit with on Haswell, corresponding to 6.25MHz.
256 */
257static int oa_sample_rate_hard_limit = 6250000;
258
259/* Theoretically we can program the OA unit to sample every 160ns but don't
260 * allow that by default unless root...
261 *
262 * The default threshold of 100000Hz is based on perf's similar
263 * kernel.perf_event_max_sample_rate sysctl parameter.
264 */
265static u32 i915_oa_max_sample_rate = 100000;
266
Robert Braggd7965152016-11-07 19:49:52 +0000267/* XXX: beware if future OA HW adds new report formats that the current
268 * code assumes all reports have a power-of-two size and ~(size - 1) can
269 * be used as a mask to align the OA tail pointer.
270 */
271static struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
272 [I915_OA_FORMAT_A13] = { 0, 64 },
273 [I915_OA_FORMAT_A29] = { 1, 128 },
274 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
275 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
276 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
277 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
278 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
279 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
280};
281
282#define SAMPLE_OA_REPORT (1<<0)
Robert Braggeec688e2016-11-07 19:49:47 +0000283
Robert Bragg16d98b32016-12-07 21:40:33 +0000284/**
285 * struct perf_open_properties - for validated properties given to open a stream
286 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
287 * @single_context: Whether a single or all gpu contexts should be monitored
288 * @ctx_handle: A gem ctx handle for use with @single_context
289 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
290 * @oa_format: An OA unit HW report format
291 * @oa_periodic: Whether to enable periodic OA unit sampling
292 * @oa_period_exponent: The OA unit sampling period is derived from this
293 *
294 * As read_properties_unlocked() enumerates and validates the properties given
295 * to open a stream of metrics the configuration is built up in the structure
296 * which starts out zero initialized.
297 */
Robert Braggeec688e2016-11-07 19:49:47 +0000298struct perf_open_properties {
299 u32 sample_flags;
300
301 u64 single_context:1;
302 u64 ctx_handle;
Robert Braggd7965152016-11-07 19:49:52 +0000303
304 /* OA sampling state */
305 int metrics_set;
306 int oa_format;
307 bool oa_periodic;
308 int oa_period_exponent;
Robert Braggeec688e2016-11-07 19:49:47 +0000309};
310
Robert Braggd7965152016-11-07 19:49:52 +0000311/* NB: This is either called via fops or the poll check hrtimer (atomic ctx)
312 *
313 * It's safe to read OA config state here unlocked, assuming that this is only
314 * called while the stream is enabled, while the global OA configuration can't
315 * be modified.
316 *
317 * Note: we don't lock around the head/tail reads even though there's the slim
318 * possibility of read() fop errors forcing a re-init of the OA buffer
319 * pointers. A race here could result in a false positive !empty status which
320 * is acceptable.
321 */
322static bool gen7_oa_buffer_is_empty_fop_unlocked(struct drm_i915_private *dev_priv)
323{
324 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
Robert Braggd7965152016-11-07 19:49:52 +0000325 u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
Robert Braggf2790202017-05-11 16:43:26 +0100326 u32 head = dev_priv->perf.oa.oa_buffer.head;
Robert Braggd7965152016-11-07 19:49:52 +0000327 u32 tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
328
329 return OA_TAKEN(tail, head) <
330 dev_priv->perf.oa.tail_margin + report_size;
331}
332
333/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000334 * append_oa_status - Appends a status record to a userspace read() buffer.
335 * @stream: An i915-perf stream opened for OA metrics
336 * @buf: destination buffer given by userspace
337 * @count: the number of bytes userspace wants to read
338 * @offset: (inout): the current position for writing into @buf
339 * @type: The kind of status to report to userspace
340 *
341 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
342 * into the userspace read() buffer.
343 *
344 * The @buf @offset will only be updated on success.
345 *
346 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000347 */
348static int append_oa_status(struct i915_perf_stream *stream,
349 char __user *buf,
350 size_t count,
351 size_t *offset,
352 enum drm_i915_perf_record_type type)
353{
354 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
355
356 if ((count - *offset) < header.size)
357 return -ENOSPC;
358
359 if (copy_to_user(buf + *offset, &header, sizeof(header)))
360 return -EFAULT;
361
362 (*offset) += header.size;
363
364 return 0;
365}
366
367/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000368 * append_oa_sample - Copies single OA report into userspace read() buffer.
369 * @stream: An i915-perf stream opened for OA metrics
370 * @buf: destination buffer given by userspace
371 * @count: the number of bytes userspace wants to read
372 * @offset: (inout): the current position for writing into @buf
373 * @report: A single OA report to (optionally) include as part of the sample
374 *
375 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
376 * properties when opening a stream, tracked as `stream->sample_flags`. This
377 * function copies the requested components of a single sample to the given
378 * read() @buf.
379 *
380 * The @buf @offset will only be updated on success.
381 *
382 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000383 */
384static int append_oa_sample(struct i915_perf_stream *stream,
385 char __user *buf,
386 size_t count,
387 size_t *offset,
388 const u8 *report)
389{
390 struct drm_i915_private *dev_priv = stream->dev_priv;
391 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
392 struct drm_i915_perf_record_header header;
393 u32 sample_flags = stream->sample_flags;
394
395 header.type = DRM_I915_PERF_RECORD_SAMPLE;
396 header.pad = 0;
397 header.size = stream->sample_size;
398
399 if ((count - *offset) < header.size)
400 return -ENOSPC;
401
402 buf += *offset;
403 if (copy_to_user(buf, &header, sizeof(header)))
404 return -EFAULT;
405 buf += sizeof(header);
406
407 if (sample_flags & SAMPLE_OA_REPORT) {
408 if (copy_to_user(buf, report, report_size))
409 return -EFAULT;
410 }
411
412 (*offset) += header.size;
413
414 return 0;
415}
416
417/**
418 * Copies all buffered OA reports into userspace read() buffer.
419 * @stream: An i915-perf stream opened for OA metrics
420 * @buf: destination buffer given by userspace
421 * @count: the number of bytes userspace wants to read
422 * @offset: (inout): the current position for writing into @buf
Robert Braggd7965152016-11-07 19:49:52 +0000423 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000424 * Notably any error condition resulting in a short read (-%ENOSPC or
425 * -%EFAULT) will be returned even though one or more records may
Robert Braggd7965152016-11-07 19:49:52 +0000426 * have been successfully copied. In this case it's up to the caller
427 * to decide if the error should be squashed before returning to
428 * userspace.
429 *
430 * Note: reports are consumed from the head, and appended to the
Robert Bragge81b3a52017-05-11 16:43:24 +0100431 * tail, so the tail chases the head?... If you think that's mad
Robert Braggd7965152016-11-07 19:49:52 +0000432 * and back-to-front you're not alone, but this follows the
433 * Gen PRM naming convention.
Robert Bragg16d98b32016-12-07 21:40:33 +0000434 *
435 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000436 */
437static int gen7_append_oa_reports(struct i915_perf_stream *stream,
438 char __user *buf,
439 size_t count,
Robert Bragg3bb335c2017-05-11 16:43:27 +0100440 size_t *offset)
Robert Braggd7965152016-11-07 19:49:52 +0000441{
442 struct drm_i915_private *dev_priv = stream->dev_priv;
443 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
444 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
445 int tail_margin = dev_priv->perf.oa.tail_margin;
446 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
447 u32 mask = (OA_BUFFER_SIZE - 1);
Robert Bragg3bb335c2017-05-11 16:43:27 +0100448 size_t start_offset = *offset;
449 u32 head, oastatus1, tail;
Robert Braggd7965152016-11-07 19:49:52 +0000450 u32 taken;
451 int ret = 0;
452
453 if (WARN_ON(!stream->enabled))
454 return -EIO;
455
Robert Bragg3bb335c2017-05-11 16:43:27 +0100456 head = dev_priv->perf.oa.oa_buffer.head - gtt_offset;
Robert Braggf2790202017-05-11 16:43:26 +0100457
458 /* An out of bounds or misaligned head pointer implies a driver bug
459 * since we are in full control of head pointer which should only
460 * be incremented by multiples of the report size (notably also
461 * all a power of two).
462 */
463 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size,
464 "Inconsistent OA buffer head pointer = %u\n", head))
465 return -EIO;
466
Robert Bragg3bb335c2017-05-11 16:43:27 +0100467 oastatus1 = I915_READ(GEN7_OASTATUS1);
468 tail = (oastatus1 & GEN7_OASTATUS1_TAIL_MASK) - gtt_offset;
Robert Braggd7965152016-11-07 19:49:52 +0000469
470 /* The OA unit is expected to wrap the tail pointer according to the OA
Robert Braggf2790202017-05-11 16:43:26 +0100471 * buffer size
Robert Braggd7965152016-11-07 19:49:52 +0000472 */
Robert Braggf2790202017-05-11 16:43:26 +0100473 if (tail > OA_BUFFER_SIZE) {
474 DRM_ERROR("Inconsistent OA buffer tail pointer = %u: force restart\n",
475 tail);
Robert Braggd7965152016-11-07 19:49:52 +0000476 dev_priv->perf.oa.ops.oa_disable(dev_priv);
477 dev_priv->perf.oa.ops.oa_enable(dev_priv);
Robert Braggd7965152016-11-07 19:49:52 +0000478 return -EIO;
479 }
480
481
482 /* The tail pointer increases in 64 byte increments, not in report_size
483 * steps...
484 */
485 tail &= ~(report_size - 1);
486
487 /* Move the tail pointer back by the current tail_margin to account for
488 * the possibility that the latest reports may not have really landed
489 * in memory yet...
490 */
491
492 if (OA_TAKEN(tail, head) < report_size + tail_margin)
493 return -EAGAIN;
494
495 tail -= tail_margin;
496 tail &= mask;
497
498 for (/* none */;
499 (taken = OA_TAKEN(tail, head));
500 head = (head + report_size) & mask) {
501 u8 *report = oa_buf_base + head;
502 u32 *report32 = (void *)report;
503
504 /* All the report sizes factor neatly into the buffer
505 * size so we never expect to see a report split
506 * between the beginning and end of the buffer.
507 *
508 * Given the initial alignment check a misalignment
509 * here would imply a driver bug that would result
510 * in an overrun.
511 */
512 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
513 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
514 break;
515 }
516
517 /* The report-ID field for periodic samples includes
518 * some undocumented flags related to what triggered
519 * the report and is never expected to be zero so we
520 * can check that the report isn't invalid before
521 * copying it to userspace...
522 */
523 if (report32[0] == 0) {
Robert Bragg77085502016-12-01 17:21:52 +0000524 DRM_NOTE("Skipping spurious, invalid OA report\n");
Robert Braggd7965152016-11-07 19:49:52 +0000525 continue;
526 }
527
528 ret = append_oa_sample(stream, buf, count, offset, report);
529 if (ret)
530 break;
531
532 /* The above report-id field sanity check is based on
533 * the assumption that the OA buffer is initially
534 * zeroed and we reset the field after copying so the
535 * check is still meaningful once old reports start
536 * being overwritten.
537 */
538 report32[0] = 0;
539 }
540
Robert Bragg3bb335c2017-05-11 16:43:27 +0100541 if (start_offset != *offset) {
542 /* We removed the gtt_offset for the copy loop above, indexing
543 * relative to oa_buf_base so put back here...
544 */
545 head += gtt_offset;
546
547 I915_WRITE(GEN7_OASTATUS2,
548 ((head & GEN7_OASTATUS2_HEAD_MASK) |
549 OA_MEM_SELECT_GGTT));
550 dev_priv->perf.oa.oa_buffer.head = head;
551 }
Robert Braggd7965152016-11-07 19:49:52 +0000552
553 return ret;
554}
555
Robert Bragg16d98b32016-12-07 21:40:33 +0000556/**
557 * gen7_oa_read - copy status records then buffered OA reports
558 * @stream: An i915-perf stream opened for OA metrics
559 * @buf: destination buffer given by userspace
560 * @count: the number of bytes userspace wants to read
561 * @offset: (inout): the current position for writing into @buf
562 *
563 * Checks Gen 7 specific OA unit status registers and if necessary appends
564 * corresponding status records for userspace (such as for a buffer full
565 * condition) and then initiate appending any buffered OA reports.
566 *
567 * Updates @offset according to the number of bytes successfully copied into
568 * the userspace buffer.
569 *
570 * Returns: zero on success or a negative error code
571 */
Robert Braggd7965152016-11-07 19:49:52 +0000572static int gen7_oa_read(struct i915_perf_stream *stream,
573 char __user *buf,
574 size_t count,
575 size_t *offset)
576{
577 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +0000578 u32 oastatus1;
Robert Braggd7965152016-11-07 19:49:52 +0000579 int ret;
580
581 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
582 return -EIO;
583
Robert Braggd7965152016-11-07 19:49:52 +0000584 oastatus1 = I915_READ(GEN7_OASTATUS1);
585
Robert Braggd7965152016-11-07 19:49:52 +0000586 /* XXX: On Haswell we don't have a safe way to clear oastatus1
587 * bits while the OA unit is enabled (while the tail pointer
588 * may be updated asynchronously) so we ignore status bits
589 * that have already been reported to userspace.
590 */
591 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
592
593 /* We treat OABUFFER_OVERFLOW as a significant error:
594 *
595 * - The status can be interpreted to mean that the buffer is
596 * currently full (with a higher precedence than OA_TAKEN()
597 * which will start to report a near-empty buffer after an
598 * overflow) but it's awkward that we can't clear the status
599 * on Haswell, so without a reset we won't be able to catch
600 * the state again.
601 *
602 * - Since it also implies the HW has started overwriting old
603 * reports it may also affect our sanity checks for invalid
604 * reports when copying to userspace that assume new reports
605 * are being written to cleared memory.
606 *
607 * - In the future we may want to introduce a flight recorder
608 * mode where the driver will automatically maintain a safe
609 * guard band between head/tail, avoiding this overflow
610 * condition, but we avoid the added driver complexity for
611 * now.
612 */
613 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
614 ret = append_oa_status(stream, buf, count, offset,
615 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
616 if (ret)
617 return ret;
618
Robert Bragg77085502016-12-01 17:21:52 +0000619 DRM_DEBUG("OA buffer overflow: force restart\n");
Robert Braggd7965152016-11-07 19:49:52 +0000620
621 dev_priv->perf.oa.ops.oa_disable(dev_priv);
622 dev_priv->perf.oa.ops.oa_enable(dev_priv);
623
Robert Braggd7965152016-11-07 19:49:52 +0000624 oastatus1 = I915_READ(GEN7_OASTATUS1);
Robert Braggd7965152016-11-07 19:49:52 +0000625 }
626
627 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
628 ret = append_oa_status(stream, buf, count, offset,
629 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
630 if (ret)
631 return ret;
632 dev_priv->perf.oa.gen7_latched_oastatus1 |=
633 GEN7_OASTATUS1_REPORT_LOST;
634 }
635
Robert Bragg3bb335c2017-05-11 16:43:27 +0100636 return gen7_append_oa_reports(stream, buf, count, offset);
Robert Braggd7965152016-11-07 19:49:52 +0000637}
638
Robert Bragg16d98b32016-12-07 21:40:33 +0000639/**
640 * i915_oa_wait_unlocked - handles blocking IO until OA data available
641 * @stream: An i915-perf stream opened for OA metrics
642 *
643 * Called when userspace tries to read() from a blocking stream FD opened
644 * for OA metrics. It waits until the hrtimer callback finds a non-empty
645 * OA buffer and wakes us.
646 *
647 * Note: it's acceptable to have this return with some false positives
648 * since any subsequent read handling will return -EAGAIN if there isn't
649 * really data ready for userspace yet.
650 *
651 * Returns: zero on success or a negative error code
652 */
Robert Braggd7965152016-11-07 19:49:52 +0000653static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
654{
655 struct drm_i915_private *dev_priv = stream->dev_priv;
656
657 /* We would wait indefinitely if periodic sampling is not enabled */
658 if (!dev_priv->perf.oa.periodic)
659 return -EIO;
660
661 /* Note: the oa_buffer_is_empty() condition is ok to run unlocked as it
662 * just performs mmio reads of the OA buffer head + tail pointers and
663 * it's assumed we're handling some operation that implies the stream
664 * can't be destroyed until completion (such as a read()) that ensures
665 * the device + OA buffer can't disappear
666 */
667 return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
668 !dev_priv->perf.oa.ops.oa_buffer_is_empty(dev_priv));
669}
670
Robert Bragg16d98b32016-12-07 21:40:33 +0000671/**
672 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
673 * @stream: An i915-perf stream opened for OA metrics
674 * @file: An i915 perf stream file
675 * @wait: poll() state table
676 *
677 * For handling userspace polling on an i915 perf stream opened for OA metrics,
678 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
679 * when it sees data ready to read in the circular OA buffer.
680 */
Robert Braggd7965152016-11-07 19:49:52 +0000681static void i915_oa_poll_wait(struct i915_perf_stream *stream,
682 struct file *file,
683 poll_table *wait)
684{
685 struct drm_i915_private *dev_priv = stream->dev_priv;
686
687 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
688}
689
Robert Bragg16d98b32016-12-07 21:40:33 +0000690/**
691 * i915_oa_read - just calls through to &i915_oa_ops->read
692 * @stream: An i915-perf stream opened for OA metrics
693 * @buf: destination buffer given by userspace
694 * @count: the number of bytes userspace wants to read
695 * @offset: (inout): the current position for writing into @buf
696 *
697 * Updates @offset according to the number of bytes successfully copied into
698 * the userspace buffer.
699 *
700 * Returns: zero on success or a negative error code
701 */
Robert Braggd7965152016-11-07 19:49:52 +0000702static int i915_oa_read(struct i915_perf_stream *stream,
703 char __user *buf,
704 size_t count,
705 size_t *offset)
706{
707 struct drm_i915_private *dev_priv = stream->dev_priv;
708
709 return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
710}
711
Robert Bragg16d98b32016-12-07 21:40:33 +0000712/**
713 * oa_get_render_ctx_id - determine and hold ctx hw id
714 * @stream: An i915-perf stream opened for OA metrics
715 *
716 * Determine the render context hw id, and ensure it remains fixed for the
Robert Braggd7965152016-11-07 19:49:52 +0000717 * lifetime of the stream. This ensures that we don't have to worry about
718 * updating the context ID in OACONTROL on the fly.
Robert Bragg16d98b32016-12-07 21:40:33 +0000719 *
720 * Returns: zero on success or a negative error code
Robert Braggd7965152016-11-07 19:49:52 +0000721 */
722static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
723{
724 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000725 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Chris Wilson266a2402017-05-04 10:33:08 +0100726 struct intel_ring *ring;
Robert Braggd7965152016-11-07 19:49:52 +0000727 int ret;
728
729 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
730 if (ret)
731 return ret;
732
733 /* As the ID is the gtt offset of the context's vma we pin
734 * the vma to ensure the ID remains fixed.
735 *
736 * NB: implied RCS engine...
737 */
Chris Wilson266a2402017-05-04 10:33:08 +0100738 ring = engine->context_pin(engine, stream->ctx);
739 mutex_unlock(&dev_priv->drm.struct_mutex);
740 if (IS_ERR(ring))
741 return PTR_ERR(ring);
Robert Braggd7965152016-11-07 19:49:52 +0000742
743 /* Explicitly track the ID (instead of calling i915_ggtt_offset()
744 * on the fly) considering the difference with gen8+ and
745 * execlists
746 */
Chris Wilsone8a9c582016-12-18 15:37:20 +0000747 dev_priv->perf.oa.specific_ctx_id =
748 i915_ggtt_offset(stream->ctx->engine[engine->id].state);
Robert Braggd7965152016-11-07 19:49:52 +0000749
Chris Wilson266a2402017-05-04 10:33:08 +0100750 return 0;
Robert Braggd7965152016-11-07 19:49:52 +0000751}
752
Robert Bragg16d98b32016-12-07 21:40:33 +0000753/**
754 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
755 * @stream: An i915-perf stream opened for OA metrics
756 *
757 * In case anything needed doing to ensure the context HW ID would remain valid
758 * for the lifetime of the stream, then that can be undone here.
759 */
Robert Braggd7965152016-11-07 19:49:52 +0000760static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
761{
762 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000763 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Robert Braggd7965152016-11-07 19:49:52 +0000764
765 mutex_lock(&dev_priv->drm.struct_mutex);
766
Robert Braggd7965152016-11-07 19:49:52 +0000767 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000768 engine->context_unpin(engine, stream->ctx);
Robert Braggd7965152016-11-07 19:49:52 +0000769
770 mutex_unlock(&dev_priv->drm.struct_mutex);
771}
772
773static void
774free_oa_buffer(struct drm_i915_private *i915)
775{
776 mutex_lock(&i915->drm.struct_mutex);
777
778 i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
779 i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
780 i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
781
782 i915->perf.oa.oa_buffer.vma = NULL;
783 i915->perf.oa.oa_buffer.vaddr = NULL;
784
785 mutex_unlock(&i915->drm.struct_mutex);
786}
787
788static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
789{
790 struct drm_i915_private *dev_priv = stream->dev_priv;
791
792 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
793
794 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
795
796 free_oa_buffer(dev_priv);
797
798 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
799 intel_runtime_pm_put(dev_priv);
800
801 if (stream->ctx)
802 oa_put_render_ctx_id(stream);
803
804 dev_priv->perf.oa.exclusive_stream = NULL;
805}
806
807static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
808{
809 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
810
811 /* Pre-DevBDW: OABUFFER must be set with counters off,
812 * before OASTATUS1, but after OASTATUS2
813 */
814 I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
Robert Braggf2790202017-05-11 16:43:26 +0100815 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
816
Robert Braggd7965152016-11-07 19:49:52 +0000817 I915_WRITE(GEN7_OABUFFER, gtt_offset);
Robert Braggf2790202017-05-11 16:43:26 +0100818
Robert Braggd7965152016-11-07 19:49:52 +0000819 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
820
821 /* On Haswell we have to track which OASTATUS1 flags we've
822 * already seen since they can't be cleared while periodic
823 * sampling is enabled.
824 */
825 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
826
827 /* NB: although the OA buffer will initially be allocated
828 * zeroed via shmfs (and so this memset is redundant when
829 * first allocating), we may re-init the OA buffer, either
830 * when re-enabling a stream or in error/reset paths.
831 *
832 * The reason we clear the buffer for each re-init is for the
833 * sanity check in gen7_append_oa_reports() that looks at the
834 * report-id field to make sure it's non-zero which relies on
835 * the assumption that new reports are being written to zeroed
836 * memory...
837 */
838 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
839
840 /* Maybe make ->pollin per-stream state if we support multiple
841 * concurrent streams in the future.
842 */
843 dev_priv->perf.oa.pollin = false;
844}
845
846static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
847{
848 struct drm_i915_gem_object *bo;
849 struct i915_vma *vma;
850 int ret;
851
852 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
853 return -ENODEV;
854
855 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
856 if (ret)
857 return ret;
858
859 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
860 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
861
Tvrtko Ursulin12d79d72016-12-01 14:16:37 +0000862 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +0000863 if (IS_ERR(bo)) {
864 DRM_ERROR("Failed to allocate OA buffer\n");
865 ret = PTR_ERR(bo);
866 goto unlock;
867 }
868
869 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
870 if (ret)
871 goto err_unref;
872
873 /* PreHSW required 512K alignment, HSW requires 16M */
874 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
875 if (IS_ERR(vma)) {
876 ret = PTR_ERR(vma);
877 goto err_unref;
878 }
879 dev_priv->perf.oa.oa_buffer.vma = vma;
880
881 dev_priv->perf.oa.oa_buffer.vaddr =
882 i915_gem_object_pin_map(bo, I915_MAP_WB);
883 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
884 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
885 goto err_unpin;
886 }
887
888 dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
889
890 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
891 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
892 dev_priv->perf.oa.oa_buffer.vaddr);
893
894 goto unlock;
895
896err_unpin:
897 __i915_vma_unpin(vma);
898
899err_unref:
900 i915_gem_object_put(bo);
901
902 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
903 dev_priv->perf.oa.oa_buffer.vma = NULL;
904
905unlock:
906 mutex_unlock(&dev_priv->drm.struct_mutex);
907 return ret;
908}
909
910static void config_oa_regs(struct drm_i915_private *dev_priv,
911 const struct i915_oa_reg *regs,
912 int n_regs)
913{
914 int i;
915
916 for (i = 0; i < n_regs; i++) {
917 const struct i915_oa_reg *reg = regs + i;
918
919 I915_WRITE(reg->addr, reg->value);
920 }
921}
922
923static int hsw_enable_metric_set(struct drm_i915_private *dev_priv)
924{
925 int ret = i915_oa_select_metric_set_hsw(dev_priv);
926
927 if (ret)
928 return ret;
929
930 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) |
931 GT_NOA_ENABLE));
932
933 /* PRM:
934 *
935 * OA unit is using “crclk” for its functionality. When trunk
936 * level clock gating takes place, OA clock would be gated,
937 * unable to count the events from non-render clock domain.
938 * Render clock gating must be disabled when OA is enabled to
939 * count the events from non-render domain. Unit level clock
940 * gating for RCS should also be disabled.
941 */
942 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
943 ~GEN7_DOP_CLOCK_GATE_ENABLE));
944 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
945 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
946
947 config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs,
948 dev_priv->perf.oa.mux_regs_len);
949
950 /* It apparently takes a fairly long time for a new MUX
951 * configuration to be be applied after these register writes.
952 * This delay duration was derived empirically based on the
953 * render_basic config but hopefully it covers the maximum
954 * configuration latency.
955 *
956 * As a fallback, the checks in _append_oa_reports() to skip
957 * invalid OA reports do also seem to work to discard reports
958 * generated before this config has completed - albeit not
959 * silently.
960 *
961 * Unfortunately this is essentially a magic number, since we
962 * don't currently know of a reliable mechanism for predicting
963 * how long the MUX config will take to apply and besides
964 * seeing invalid reports we don't know of a reliable way to
965 * explicitly check that the MUX config has landed.
966 *
967 * It's even possible we've miss characterized the underlying
968 * problem - it just seems like the simplest explanation why
969 * a delay at this location would mitigate any invalid reports.
970 */
971 usleep_range(15000, 20000);
972
973 config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
974 dev_priv->perf.oa.b_counter_regs_len);
975
976 return 0;
977}
978
979static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
980{
981 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
982 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
983 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
984 GEN7_DOP_CLOCK_GATE_ENABLE));
985
986 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
987 ~GT_NOA_ENABLE));
988}
989
990static void gen7_update_oacontrol_locked(struct drm_i915_private *dev_priv)
991{
Chris Wilson67520412017-03-02 13:28:01 +0000992 lockdep_assert_held(&dev_priv->perf.hook_lock);
Robert Braggd7965152016-11-07 19:49:52 +0000993
994 if (dev_priv->perf.oa.exclusive_stream->enabled) {
995 struct i915_gem_context *ctx =
996 dev_priv->perf.oa.exclusive_stream->ctx;
997 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
998
999 bool periodic = dev_priv->perf.oa.periodic;
1000 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1001 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1002
1003 I915_WRITE(GEN7_OACONTROL,
1004 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1005 (period_exponent <<
1006 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1007 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1008 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1009 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1010 GEN7_OACONTROL_ENABLE);
1011 } else
1012 I915_WRITE(GEN7_OACONTROL, 0);
1013}
1014
1015static void gen7_oa_enable(struct drm_i915_private *dev_priv)
1016{
1017 unsigned long flags;
1018
1019 /* Reset buf pointers so we don't forward reports from before now.
1020 *
1021 * Think carefully if considering trying to avoid this, since it
1022 * also ensures status flags and the buffer itself are cleared
1023 * in error paths, and we have checks for invalid reports based
1024 * on the assumption that certain fields are written to zeroed
1025 * memory which this helps maintains.
1026 */
1027 gen7_init_oa_buffer(dev_priv);
1028
1029 spin_lock_irqsave(&dev_priv->perf.hook_lock, flags);
1030 gen7_update_oacontrol_locked(dev_priv);
1031 spin_unlock_irqrestore(&dev_priv->perf.hook_lock, flags);
1032}
1033
Robert Bragg16d98b32016-12-07 21:40:33 +00001034/**
1035 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1036 * @stream: An i915 perf stream opened for OA metrics
1037 *
1038 * [Re]enables hardware periodic sampling according to the period configured
1039 * when opening the stream. This also starts a hrtimer that will periodically
1040 * check for data in the circular OA buffer for notifying userspace (e.g.
1041 * during a read() or poll()).
1042 */
Robert Braggd7965152016-11-07 19:49:52 +00001043static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1044{
1045 struct drm_i915_private *dev_priv = stream->dev_priv;
1046
1047 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1048
1049 if (dev_priv->perf.oa.periodic)
1050 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1051 ns_to_ktime(POLL_PERIOD),
1052 HRTIMER_MODE_REL_PINNED);
1053}
1054
1055static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1056{
1057 I915_WRITE(GEN7_OACONTROL, 0);
1058}
1059
Robert Bragg16d98b32016-12-07 21:40:33 +00001060/**
1061 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1062 * @stream: An i915 perf stream opened for OA metrics
1063 *
1064 * Stops the OA unit from periodically writing counter reports into the
1065 * circular OA buffer. This also stops the hrtimer that periodically checks for
1066 * data in the circular OA buffer, for notifying userspace.
1067 */
Robert Braggd7965152016-11-07 19:49:52 +00001068static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1069{
1070 struct drm_i915_private *dev_priv = stream->dev_priv;
1071
1072 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1073
1074 if (dev_priv->perf.oa.periodic)
1075 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1076}
1077
1078static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
1079{
Chris Wilson24603932016-11-23 15:07:14 +00001080 return div_u64(1000000000ULL * (2ULL << exponent),
1081 dev_priv->perf.oa.timestamp_frequency);
Robert Braggd7965152016-11-07 19:49:52 +00001082}
1083
1084static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1085 .destroy = i915_oa_stream_destroy,
1086 .enable = i915_oa_stream_enable,
1087 .disable = i915_oa_stream_disable,
1088 .wait_unlocked = i915_oa_wait_unlocked,
1089 .poll_wait = i915_oa_poll_wait,
1090 .read = i915_oa_read,
1091};
1092
Robert Bragg16d98b32016-12-07 21:40:33 +00001093/**
1094 * i915_oa_stream_init - validate combined props for OA stream and init
1095 * @stream: An i915 perf stream
1096 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1097 * @props: The property state that configures stream (individually validated)
1098 *
1099 * While read_properties_unlocked() validates properties in isolation it
1100 * doesn't ensure that the combination necessarily makes sense.
1101 *
1102 * At this point it has been determined that userspace wants a stream of
1103 * OA metrics, but still we need to further validate the combined
1104 * properties are OK.
1105 *
1106 * If the configuration makes sense then we can allocate memory for
1107 * a circular OA buffer and apply the requested metric set configuration.
1108 *
1109 * Returns: zero on success or a negative error code.
1110 */
Robert Braggd7965152016-11-07 19:49:52 +00001111static int i915_oa_stream_init(struct i915_perf_stream *stream,
1112 struct drm_i915_perf_open_param *param,
1113 struct perf_open_properties *props)
1114{
1115 struct drm_i915_private *dev_priv = stream->dev_priv;
1116 int format_size;
1117 int ret;
1118
Robert Bragg442b8c02016-11-07 19:49:53 +00001119 /* If the sysfs metrics/ directory wasn't registered for some
1120 * reason then don't let userspace try their luck with config
1121 * IDs
1122 */
1123 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00001124 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00001125 return -EINVAL;
1126 }
1127
Robert Braggd7965152016-11-07 19:49:52 +00001128 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00001129 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001130 return -EINVAL;
1131 }
1132
1133 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
Robert Bragg77085502016-12-01 17:21:52 +00001134 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001135 return -ENODEV;
1136 }
1137
1138 /* To avoid the complexity of having to accurately filter
1139 * counter reports and marshal to the appropriate client
1140 * we currently only allow exclusive access
1141 */
1142 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00001143 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00001144 return -EBUSY;
1145 }
1146
1147 if (!props->metrics_set) {
Robert Bragg77085502016-12-01 17:21:52 +00001148 DRM_DEBUG("OA metric set not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001149 return -EINVAL;
1150 }
1151
1152 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00001153 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001154 return -EINVAL;
1155 }
1156
1157 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
1158
1159 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
1160
1161 stream->sample_flags |= SAMPLE_OA_REPORT;
1162 stream->sample_size += format_size;
1163
1164 dev_priv->perf.oa.oa_buffer.format_size = format_size;
1165 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
1166 return -EINVAL;
1167
1168 dev_priv->perf.oa.oa_buffer.format =
1169 dev_priv->perf.oa.oa_formats[props->oa_format].format;
1170
1171 dev_priv->perf.oa.metrics_set = props->metrics_set;
1172
1173 dev_priv->perf.oa.periodic = props->oa_periodic;
1174 if (dev_priv->perf.oa.periodic) {
Chris Wilson24603932016-11-23 15:07:14 +00001175 u32 tail;
Robert Braggd7965152016-11-07 19:49:52 +00001176
1177 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
1178
1179 /* See comment for OA_TAIL_MARGIN_NSEC for details
1180 * about this tail_margin...
1181 */
Chris Wilson24603932016-11-23 15:07:14 +00001182 tail = div64_u64(OA_TAIL_MARGIN_NSEC,
1183 oa_exponent_to_ns(dev_priv,
1184 props->oa_period_exponent));
1185 dev_priv->perf.oa.tail_margin = (tail + 1) * format_size;
Robert Braggd7965152016-11-07 19:49:52 +00001186 }
1187
1188 if (stream->ctx) {
1189 ret = oa_get_render_ctx_id(stream);
1190 if (ret)
1191 return ret;
1192 }
1193
1194 ret = alloc_oa_buffer(dev_priv);
1195 if (ret)
1196 goto err_oa_buf_alloc;
1197
1198 /* PRM - observability performance counters:
1199 *
1200 * OACONTROL, performance counter enable, note:
1201 *
1202 * "When this bit is set, in order to have coherent counts,
1203 * RC6 power state and trunk clock gating must be disabled.
1204 * This can be achieved by programming MMIO registers as
1205 * 0xA094=0 and 0xA090[31]=1"
1206 *
1207 * In our case we are expecting that taking pm + FORCEWAKE
1208 * references will effectively disable RC6.
1209 */
1210 intel_runtime_pm_get(dev_priv);
1211 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
1212
1213 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv);
1214 if (ret)
1215 goto err_enable;
1216
1217 stream->ops = &i915_oa_stream_ops;
1218
1219 dev_priv->perf.oa.exclusive_stream = stream;
1220
1221 return 0;
1222
1223err_enable:
1224 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1225 intel_runtime_pm_put(dev_priv);
1226 free_oa_buffer(dev_priv);
1227
1228err_oa_buf_alloc:
1229 if (stream->ctx)
1230 oa_put_render_ctx_id(stream);
1231
1232 return ret;
1233}
1234
Robert Bragg16d98b32016-12-07 21:40:33 +00001235/**
1236 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
1237 * @stream: An i915 perf stream
1238 * @file: An i915 perf stream file
1239 * @buf: destination buffer given by userspace
1240 * @count: the number of bytes userspace wants to read
1241 * @ppos: (inout) file seek position (unused)
1242 *
1243 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
1244 * ensure that if we've successfully copied any data then reporting that takes
1245 * precedence over any internal error status, so the data isn't lost.
1246 *
1247 * For example ret will be -ENOSPC whenever there is more buffered data than
1248 * can be copied to userspace, but that's only interesting if we weren't able
1249 * to copy some data because it implies the userspace buffer is too small to
1250 * receive a single record (and we never split records).
1251 *
1252 * Another case with ret == -EFAULT is more of a grey area since it would seem
1253 * like bad form for userspace to ask us to overrun its buffer, but the user
1254 * knows best:
1255 *
1256 * http://yarchive.net/comp/linux/partial_reads_writes.html
1257 *
1258 * Returns: The number of bytes copied or a negative error code on failure.
1259 */
Robert Braggeec688e2016-11-07 19:49:47 +00001260static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
1261 struct file *file,
1262 char __user *buf,
1263 size_t count,
1264 loff_t *ppos)
1265{
1266 /* Note we keep the offset (aka bytes read) separate from any
1267 * error status so that the final check for whether we return
1268 * the bytes read with a higher precedence than any error (see
1269 * comment below) doesn't need to be handled/duplicated in
1270 * stream->ops->read() implementations.
1271 */
1272 size_t offset = 0;
1273 int ret = stream->ops->read(stream, buf, count, &offset);
1274
Robert Braggeec688e2016-11-07 19:49:47 +00001275 return offset ?: (ret ?: -EAGAIN);
1276}
1277
Robert Bragg16d98b32016-12-07 21:40:33 +00001278/**
1279 * i915_perf_read - handles read() FOP for i915 perf stream FDs
1280 * @file: An i915 perf stream file
1281 * @buf: destination buffer given by userspace
1282 * @count: the number of bytes userspace wants to read
1283 * @ppos: (inout) file seek position (unused)
1284 *
1285 * The entry point for handling a read() on a stream file descriptor from
1286 * userspace. Most of the work is left to the i915_perf_read_locked() and
1287 * &i915_perf_stream_ops->read but to save having stream implementations (of
1288 * which we might have multiple later) we handle blocking read here.
1289 *
1290 * We can also consistently treat trying to read from a disabled stream
1291 * as an IO error so implementations can assume the stream is enabled
1292 * while reading.
1293 *
1294 * Returns: The number of bytes copied or a negative error code on failure.
1295 */
Robert Braggeec688e2016-11-07 19:49:47 +00001296static ssize_t i915_perf_read(struct file *file,
1297 char __user *buf,
1298 size_t count,
1299 loff_t *ppos)
1300{
1301 struct i915_perf_stream *stream = file->private_data;
1302 struct drm_i915_private *dev_priv = stream->dev_priv;
1303 ssize_t ret;
1304
Robert Braggd7965152016-11-07 19:49:52 +00001305 /* To ensure it's handled consistently we simply treat all reads of a
1306 * disabled stream as an error. In particular it might otherwise lead
1307 * to a deadlock for blocking file descriptors...
1308 */
1309 if (!stream->enabled)
1310 return -EIO;
1311
Robert Braggeec688e2016-11-07 19:49:47 +00001312 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00001313 /* There's the small chance of false positives from
1314 * stream->ops->wait_unlocked.
1315 *
1316 * E.g. with single context filtering since we only wait until
1317 * oabuffer has >= 1 report we don't immediately know whether
1318 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00001319 */
1320 do {
1321 ret = stream->ops->wait_unlocked(stream);
1322 if (ret)
1323 return ret;
1324
1325 mutex_lock(&dev_priv->perf.lock);
1326 ret = i915_perf_read_locked(stream, file,
1327 buf, count, ppos);
1328 mutex_unlock(&dev_priv->perf.lock);
1329 } while (ret == -EAGAIN);
1330 } else {
1331 mutex_lock(&dev_priv->perf.lock);
1332 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
1333 mutex_unlock(&dev_priv->perf.lock);
1334 }
1335
Robert Bragg26ebd9c2017-05-11 16:43:25 +01001336 /* We allow the poll checking to sometimes report false positive POLLIN
1337 * events where we might actually report EAGAIN on read() if there's
1338 * not really any data available. In this situation though we don't
1339 * want to enter a busy loop between poll() reporting a POLLIN event
1340 * and read() returning -EAGAIN. Clearing the oa.pollin state here
1341 * effectively ensures we back off until the next hrtimer callback
1342 * before reporting another POLLIN event.
1343 */
1344 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00001345 /* Maybe make ->pollin per-stream state if we support multiple
1346 * concurrent streams in the future.
1347 */
1348 dev_priv->perf.oa.pollin = false;
1349 }
1350
Robert Braggeec688e2016-11-07 19:49:47 +00001351 return ret;
1352}
1353
Robert Braggd7965152016-11-07 19:49:52 +00001354static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
1355{
1356 struct drm_i915_private *dev_priv =
1357 container_of(hrtimer, typeof(*dev_priv),
1358 perf.oa.poll_check_timer);
1359
1360 if (!dev_priv->perf.oa.ops.oa_buffer_is_empty(dev_priv)) {
1361 dev_priv->perf.oa.pollin = true;
1362 wake_up(&dev_priv->perf.oa.poll_wq);
1363 }
1364
1365 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
1366
1367 return HRTIMER_RESTART;
1368}
1369
Robert Bragg16d98b32016-12-07 21:40:33 +00001370/**
1371 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
1372 * @dev_priv: i915 device instance
1373 * @stream: An i915 perf stream
1374 * @file: An i915 perf stream file
1375 * @wait: poll() state table
1376 *
1377 * For handling userspace polling on an i915 perf stream, this calls through to
1378 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
1379 * will be woken for new stream data.
1380 *
1381 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1382 * with any non-file-operation driver hooks.
1383 *
1384 * Returns: any poll events that are ready without sleeping
1385 */
Robert Braggd7965152016-11-07 19:49:52 +00001386static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
1387 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00001388 struct file *file,
1389 poll_table *wait)
1390{
Robert Braggd7965152016-11-07 19:49:52 +00001391 unsigned int events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00001392
1393 stream->ops->poll_wait(stream, file, wait);
1394
Robert Braggd7965152016-11-07 19:49:52 +00001395 /* Note: we don't explicitly check whether there's something to read
1396 * here since this path may be very hot depending on what else
1397 * userspace is polling, or on the timeout in use. We rely solely on
1398 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
1399 * samples to read.
1400 */
1401 if (dev_priv->perf.oa.pollin)
1402 events |= POLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00001403
Robert Braggd7965152016-11-07 19:49:52 +00001404 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00001405}
1406
Robert Bragg16d98b32016-12-07 21:40:33 +00001407/**
1408 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
1409 * @file: An i915 perf stream file
1410 * @wait: poll() state table
1411 *
1412 * For handling userspace polling on an i915 perf stream, this ensures
1413 * poll_wait() gets called with a wait queue that will be woken for new stream
1414 * data.
1415 *
1416 * Note: Implementation deferred to i915_perf_poll_locked()
1417 *
1418 * Returns: any poll events that are ready without sleeping
1419 */
Robert Braggeec688e2016-11-07 19:49:47 +00001420static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
1421{
1422 struct i915_perf_stream *stream = file->private_data;
1423 struct drm_i915_private *dev_priv = stream->dev_priv;
1424 int ret;
1425
1426 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00001427 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00001428 mutex_unlock(&dev_priv->perf.lock);
1429
1430 return ret;
1431}
1432
Robert Bragg16d98b32016-12-07 21:40:33 +00001433/**
1434 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
1435 * @stream: A disabled i915 perf stream
1436 *
1437 * [Re]enables the associated capture of data for this stream.
1438 *
1439 * If a stream was previously enabled then there's currently no intention
1440 * to provide userspace any guarantee about the preservation of previously
1441 * buffered data.
1442 */
Robert Braggeec688e2016-11-07 19:49:47 +00001443static void i915_perf_enable_locked(struct i915_perf_stream *stream)
1444{
1445 if (stream->enabled)
1446 return;
1447
1448 /* Allow stream->ops->enable() to refer to this */
1449 stream->enabled = true;
1450
1451 if (stream->ops->enable)
1452 stream->ops->enable(stream);
1453}
1454
Robert Bragg16d98b32016-12-07 21:40:33 +00001455/**
1456 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
1457 * @stream: An enabled i915 perf stream
1458 *
1459 * Disables the associated capture of data for this stream.
1460 *
1461 * The intention is that disabling an re-enabling a stream will ideally be
1462 * cheaper than destroying and re-opening a stream with the same configuration,
1463 * though there are no formal guarantees about what state or buffered data
1464 * must be retained between disabling and re-enabling a stream.
1465 *
1466 * Note: while a stream is disabled it's considered an error for userspace
1467 * to attempt to read from the stream (-EIO).
1468 */
Robert Braggeec688e2016-11-07 19:49:47 +00001469static void i915_perf_disable_locked(struct i915_perf_stream *stream)
1470{
1471 if (!stream->enabled)
1472 return;
1473
1474 /* Allow stream->ops->disable() to refer to this */
1475 stream->enabled = false;
1476
1477 if (stream->ops->disable)
1478 stream->ops->disable(stream);
1479}
1480
Robert Bragg16d98b32016-12-07 21:40:33 +00001481/**
1482 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1483 * @stream: An i915 perf stream
1484 * @cmd: the ioctl request
1485 * @arg: the ioctl data
1486 *
1487 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1488 * with any non-file-operation driver hooks.
1489 *
1490 * Returns: zero on success or a negative error code. Returns -EINVAL for
1491 * an unknown ioctl request.
1492 */
Robert Braggeec688e2016-11-07 19:49:47 +00001493static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
1494 unsigned int cmd,
1495 unsigned long arg)
1496{
1497 switch (cmd) {
1498 case I915_PERF_IOCTL_ENABLE:
1499 i915_perf_enable_locked(stream);
1500 return 0;
1501 case I915_PERF_IOCTL_DISABLE:
1502 i915_perf_disable_locked(stream);
1503 return 0;
1504 }
1505
1506 return -EINVAL;
1507}
1508
Robert Bragg16d98b32016-12-07 21:40:33 +00001509/**
1510 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1511 * @file: An i915 perf stream file
1512 * @cmd: the ioctl request
1513 * @arg: the ioctl data
1514 *
1515 * Implementation deferred to i915_perf_ioctl_locked().
1516 *
1517 * Returns: zero on success or a negative error code. Returns -EINVAL for
1518 * an unknown ioctl request.
1519 */
Robert Braggeec688e2016-11-07 19:49:47 +00001520static long i915_perf_ioctl(struct file *file,
1521 unsigned int cmd,
1522 unsigned long arg)
1523{
1524 struct i915_perf_stream *stream = file->private_data;
1525 struct drm_i915_private *dev_priv = stream->dev_priv;
1526 long ret;
1527
1528 mutex_lock(&dev_priv->perf.lock);
1529 ret = i915_perf_ioctl_locked(stream, cmd, arg);
1530 mutex_unlock(&dev_priv->perf.lock);
1531
1532 return ret;
1533}
1534
Robert Bragg16d98b32016-12-07 21:40:33 +00001535/**
1536 * i915_perf_destroy_locked - destroy an i915 perf stream
1537 * @stream: An i915 perf stream
1538 *
1539 * Frees all resources associated with the given i915 perf @stream, disabling
1540 * any associated data capture in the process.
1541 *
1542 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1543 * with any non-file-operation driver hooks.
1544 */
Robert Braggeec688e2016-11-07 19:49:47 +00001545static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
1546{
Robert Braggeec688e2016-11-07 19:49:47 +00001547 if (stream->enabled)
1548 i915_perf_disable_locked(stream);
1549
1550 if (stream->ops->destroy)
1551 stream->ops->destroy(stream);
1552
1553 list_del(&stream->link);
1554
Chris Wilson69df05e2016-12-18 15:37:21 +00001555 if (stream->ctx)
1556 i915_gem_context_put_unlocked(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001557
1558 kfree(stream);
1559}
1560
Robert Bragg16d98b32016-12-07 21:40:33 +00001561/**
1562 * i915_perf_release - handles userspace close() of a stream file
1563 * @inode: anonymous inode associated with file
1564 * @file: An i915 perf stream file
1565 *
1566 * Cleans up any resources associated with an open i915 perf stream file.
1567 *
1568 * NB: close() can't really fail from the userspace point of view.
1569 *
1570 * Returns: zero on success or a negative error code.
1571 */
Robert Braggeec688e2016-11-07 19:49:47 +00001572static int i915_perf_release(struct inode *inode, struct file *file)
1573{
1574 struct i915_perf_stream *stream = file->private_data;
1575 struct drm_i915_private *dev_priv = stream->dev_priv;
1576
1577 mutex_lock(&dev_priv->perf.lock);
1578 i915_perf_destroy_locked(stream);
1579 mutex_unlock(&dev_priv->perf.lock);
1580
1581 return 0;
1582}
1583
1584
1585static const struct file_operations fops = {
1586 .owner = THIS_MODULE,
1587 .llseek = no_llseek,
1588 .release = i915_perf_release,
1589 .poll = i915_perf_poll,
1590 .read = i915_perf_read,
1591 .unlocked_ioctl = i915_perf_ioctl,
1592};
1593
1594
1595static struct i915_gem_context *
1596lookup_context(struct drm_i915_private *dev_priv,
1597 struct drm_i915_file_private *file_priv,
1598 u32 ctx_user_handle)
1599{
1600 struct i915_gem_context *ctx;
1601 int ret;
1602
1603 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1604 if (ret)
1605 return ERR_PTR(ret);
1606
1607 ctx = i915_gem_context_lookup(file_priv, ctx_user_handle);
1608 if (!IS_ERR(ctx))
1609 i915_gem_context_get(ctx);
1610
1611 mutex_unlock(&dev_priv->drm.struct_mutex);
1612
1613 return ctx;
1614}
1615
Robert Bragg16d98b32016-12-07 21:40:33 +00001616/**
1617 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
1618 * @dev_priv: i915 device instance
1619 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
1620 * @props: individually validated u64 property value pairs
1621 * @file: drm file
1622 *
1623 * See i915_perf_ioctl_open() for interface details.
1624 *
1625 * Implements further stream config validation and stream initialization on
1626 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
1627 * taken to serialize with any non-file-operation driver hooks.
1628 *
1629 * Note: at this point the @props have only been validated in isolation and
1630 * it's still necessary to validate that the combination of properties makes
1631 * sense.
1632 *
1633 * In the case where userspace is interested in OA unit metrics then further
1634 * config validation and stream initialization details will be handled by
1635 * i915_oa_stream_init(). The code here should only validate config state that
1636 * will be relevant to all stream types / backends.
1637 *
1638 * Returns: zero on success or a negative error code.
1639 */
Robert Braggeec688e2016-11-07 19:49:47 +00001640static int
1641i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
1642 struct drm_i915_perf_open_param *param,
1643 struct perf_open_properties *props,
1644 struct drm_file *file)
1645{
1646 struct i915_gem_context *specific_ctx = NULL;
1647 struct i915_perf_stream *stream = NULL;
1648 unsigned long f_flags = 0;
1649 int stream_fd;
1650 int ret;
1651
1652 if (props->single_context) {
1653 u32 ctx_handle = props->ctx_handle;
1654 struct drm_i915_file_private *file_priv = file->driver_priv;
1655
1656 specific_ctx = lookup_context(dev_priv, file_priv, ctx_handle);
1657 if (IS_ERR(specific_ctx)) {
1658 ret = PTR_ERR(specific_ctx);
1659 if (ret != -EINTR)
Robert Bragg77085502016-12-01 17:21:52 +00001660 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
Robert Braggeec688e2016-11-07 19:49:47 +00001661 ctx_handle);
1662 goto err;
1663 }
1664 }
1665
Robert Braggccdf6342016-11-07 19:49:54 +00001666 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
1667 * we check a dev.i915.perf_stream_paranoid sysctl option
1668 * to determine if it's ok to access system wide OA counters
1669 * without CAP_SYS_ADMIN privileges.
1670 */
1671 if (!specific_ctx &&
1672 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001673 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001674 ret = -EACCES;
1675 goto err_ctx;
1676 }
1677
1678 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
1679 if (!stream) {
1680 ret = -ENOMEM;
1681 goto err_ctx;
1682 }
1683
Robert Braggeec688e2016-11-07 19:49:47 +00001684 stream->dev_priv = dev_priv;
1685 stream->ctx = specific_ctx;
1686
Robert Braggd7965152016-11-07 19:49:52 +00001687 ret = i915_oa_stream_init(stream, param, props);
1688 if (ret)
1689 goto err_alloc;
1690
1691 /* we avoid simply assigning stream->sample_flags = props->sample_flags
1692 * to have _stream_init check the combination of sample flags more
1693 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00001694 */
Robert Braggd7965152016-11-07 19:49:52 +00001695 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
1696 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01001697 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00001698 }
Robert Braggeec688e2016-11-07 19:49:47 +00001699
1700 list_add(&stream->link, &dev_priv->perf.streams);
1701
1702 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
1703 f_flags |= O_CLOEXEC;
1704 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
1705 f_flags |= O_NONBLOCK;
1706
1707 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
1708 if (stream_fd < 0) {
1709 ret = stream_fd;
1710 goto err_open;
1711 }
1712
1713 if (!(param->flags & I915_PERF_FLAG_DISABLED))
1714 i915_perf_enable_locked(stream);
1715
1716 return stream_fd;
1717
1718err_open:
1719 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01001720err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00001721 if (stream->ops->destroy)
1722 stream->ops->destroy(stream);
1723err_alloc:
1724 kfree(stream);
1725err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00001726 if (specific_ctx)
1727 i915_gem_context_put_unlocked(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001728err:
1729 return ret;
1730}
1731
Robert Bragg16d98b32016-12-07 21:40:33 +00001732/**
1733 * read_properties_unlocked - validate + copy userspace stream open properties
1734 * @dev_priv: i915 device instance
1735 * @uprops: The array of u64 key value pairs given by userspace
1736 * @n_props: The number of key value pairs expected in @uprops
1737 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00001738 *
1739 * Note this function only validates properties in isolation it doesn't
1740 * validate that the combination of properties makes sense or that all
1741 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00001742 *
1743 * Note that there currently aren't any ordering requirements for properties so
1744 * we shouldn't validate or assume anything about ordering here. This doesn't
1745 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00001746 */
1747static int read_properties_unlocked(struct drm_i915_private *dev_priv,
1748 u64 __user *uprops,
1749 u32 n_props,
1750 struct perf_open_properties *props)
1751{
1752 u64 __user *uprop = uprops;
1753 int i;
1754
1755 memset(props, 0, sizeof(struct perf_open_properties));
1756
1757 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00001758 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001759 return -EINVAL;
1760 }
1761
1762 /* Considering that ID = 0 is reserved and assuming that we don't
1763 * (currently) expect any configurations to ever specify duplicate
1764 * values for a particular property ID then the last _PROP_MAX value is
1765 * one greater than the maximum number of properties we expect to get
1766 * from userspace.
1767 */
1768 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001769 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001770 return -EINVAL;
1771 }
1772
1773 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00001774 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00001775 u64 id, value;
1776 int ret;
1777
1778 ret = get_user(id, uprop);
1779 if (ret)
1780 return ret;
1781
1782 ret = get_user(value, uprop + 1);
1783 if (ret)
1784 return ret;
1785
Matthew Auld0a309f92017-03-27 21:32:36 +01001786 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
1787 DRM_DEBUG("Unknown i915 perf property ID\n");
1788 return -EINVAL;
1789 }
1790
Robert Braggeec688e2016-11-07 19:49:47 +00001791 switch ((enum drm_i915_perf_property_id)id) {
1792 case DRM_I915_PERF_PROP_CTX_HANDLE:
1793 props->single_context = 1;
1794 props->ctx_handle = value;
1795 break;
Robert Braggd7965152016-11-07 19:49:52 +00001796 case DRM_I915_PERF_PROP_SAMPLE_OA:
1797 props->sample_flags |= SAMPLE_OA_REPORT;
1798 break;
1799 case DRM_I915_PERF_PROP_OA_METRICS_SET:
1800 if (value == 0 ||
1801 value > dev_priv->perf.oa.n_builtin_sets) {
Robert Bragg77085502016-12-01 17:21:52 +00001802 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00001803 return -EINVAL;
1804 }
1805 props->metrics_set = value;
1806 break;
1807 case DRM_I915_PERF_PROP_OA_FORMAT:
1808 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001809 DRM_DEBUG("Invalid OA report format\n");
Robert Braggd7965152016-11-07 19:49:52 +00001810 return -EINVAL;
1811 }
1812 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg77085502016-12-01 17:21:52 +00001813 DRM_DEBUG("Invalid OA report format\n");
Robert Braggd7965152016-11-07 19:49:52 +00001814 return -EINVAL;
1815 }
1816 props->oa_format = value;
1817 break;
1818 case DRM_I915_PERF_PROP_OA_EXPONENT:
1819 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001820 DRM_DEBUG("OA timer exponent too high (> %u)\n",
1821 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00001822 return -EINVAL;
1823 }
1824
Robert Bragg00319ba2016-11-07 19:49:55 +00001825 /* Theoretically we can program the OA unit to sample
Robert Braggd7965152016-11-07 19:49:52 +00001826 * every 160ns but don't allow that by default unless
1827 * root.
1828 *
Robert Bragg00319ba2016-11-07 19:49:55 +00001829 * On Haswell the period is derived from the exponent
1830 * as:
1831 *
1832 * period = 80ns * 2^(exponent + 1)
Robert Braggd7965152016-11-07 19:49:52 +00001833 */
Robert Bragg00319ba2016-11-07 19:49:55 +00001834 BUILD_BUG_ON(sizeof(oa_period) != 8);
1835 oa_period = 80ull * (2ull << value);
1836
1837 /* This check is primarily to ensure that oa_period <=
1838 * UINT32_MAX (before passing to do_div which only
1839 * accepts a u32 denominator), but we can also skip
1840 * checking anything < 1Hz which implicitly can't be
1841 * limited via an integer oa_max_sample_rate.
1842 */
1843 if (oa_period <= NSEC_PER_SEC) {
1844 u64 tmp = NSEC_PER_SEC;
1845 do_div(tmp, oa_period);
1846 oa_freq_hz = tmp;
1847 } else
1848 oa_freq_hz = 0;
1849
1850 if (oa_freq_hz > i915_oa_max_sample_rate &&
1851 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001852 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 +00001853 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00001854 return -EACCES;
1855 }
1856
1857 props->oa_periodic = true;
1858 props->oa_period_exponent = value;
1859 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01001860 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00001861 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00001862 return -EINVAL;
1863 }
1864
1865 uprop += 2;
1866 }
1867
1868 return 0;
1869}
1870
Robert Bragg16d98b32016-12-07 21:40:33 +00001871/**
1872 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
1873 * @dev: drm device
1874 * @data: ioctl data copied from userspace (unvalidated)
1875 * @file: drm file
1876 *
1877 * Validates the stream open parameters given by userspace including flags
1878 * and an array of u64 key, value pair properties.
1879 *
1880 * Very little is assumed up front about the nature of the stream being
1881 * opened (for instance we don't assume it's for periodic OA unit metrics). An
1882 * i915-perf stream is expected to be a suitable interface for other forms of
1883 * buffered data written by the GPU besides periodic OA metrics.
1884 *
1885 * Note we copy the properties from userspace outside of the i915 perf
1886 * mutex to avoid an awkward lockdep with mmap_sem.
1887 *
1888 * Most of the implementation details are handled by
1889 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
1890 * mutex for serializing with any non-file-operation driver hooks.
1891 *
1892 * Return: A newly opened i915 Perf stream file descriptor or negative
1893 * error code on failure.
1894 */
Robert Braggeec688e2016-11-07 19:49:47 +00001895int i915_perf_open_ioctl(struct drm_device *dev, void *data,
1896 struct drm_file *file)
1897{
1898 struct drm_i915_private *dev_priv = dev->dev_private;
1899 struct drm_i915_perf_open_param *param = data;
1900 struct perf_open_properties props;
1901 u32 known_open_flags;
1902 int ret;
1903
1904 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00001905 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001906 return -ENOTSUPP;
1907 }
1908
1909 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
1910 I915_PERF_FLAG_FD_NONBLOCK |
1911 I915_PERF_FLAG_DISABLED;
1912 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00001913 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001914 return -EINVAL;
1915 }
1916
1917 ret = read_properties_unlocked(dev_priv,
1918 u64_to_user_ptr(param->properties_ptr),
1919 param->num_properties,
1920 &props);
1921 if (ret)
1922 return ret;
1923
1924 mutex_lock(&dev_priv->perf.lock);
1925 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
1926 mutex_unlock(&dev_priv->perf.lock);
1927
1928 return ret;
1929}
1930
Robert Bragg16d98b32016-12-07 21:40:33 +00001931/**
1932 * i915_perf_register - exposes i915-perf to userspace
1933 * @dev_priv: i915 device instance
1934 *
1935 * In particular OA metric sets are advertised under a sysfs metrics/
1936 * directory allowing userspace to enumerate valid IDs that can be
1937 * used to open an i915-perf stream.
1938 */
Robert Bragg442b8c02016-11-07 19:49:53 +00001939void i915_perf_register(struct drm_i915_private *dev_priv)
1940{
1941 if (!IS_HASWELL(dev_priv))
1942 return;
1943
1944 if (!dev_priv->perf.initialized)
1945 return;
1946
1947 /* To be sure we're synchronized with an attempted
1948 * i915_perf_open_ioctl(); considering that we register after
1949 * being exposed to userspace.
1950 */
1951 mutex_lock(&dev_priv->perf.lock);
1952
1953 dev_priv->perf.metrics_kobj =
1954 kobject_create_and_add("metrics",
1955 &dev_priv->drm.primary->kdev->kobj);
1956 if (!dev_priv->perf.metrics_kobj)
1957 goto exit;
1958
1959 if (i915_perf_register_sysfs_hsw(dev_priv)) {
1960 kobject_put(dev_priv->perf.metrics_kobj);
1961 dev_priv->perf.metrics_kobj = NULL;
1962 }
1963
1964exit:
1965 mutex_unlock(&dev_priv->perf.lock);
1966}
1967
Robert Bragg16d98b32016-12-07 21:40:33 +00001968/**
1969 * i915_perf_unregister - hide i915-perf from userspace
1970 * @dev_priv: i915 device instance
1971 *
1972 * i915-perf state cleanup is split up into an 'unregister' and
1973 * 'deinit' phase where the interface is first hidden from
1974 * userspace by i915_perf_unregister() before cleaning up
1975 * remaining state in i915_perf_fini().
1976 */
Robert Bragg442b8c02016-11-07 19:49:53 +00001977void i915_perf_unregister(struct drm_i915_private *dev_priv)
1978{
1979 if (!IS_HASWELL(dev_priv))
1980 return;
1981
1982 if (!dev_priv->perf.metrics_kobj)
1983 return;
1984
1985 i915_perf_unregister_sysfs_hsw(dev_priv);
1986
1987 kobject_put(dev_priv->perf.metrics_kobj);
1988 dev_priv->perf.metrics_kobj = NULL;
1989}
1990
Robert Braggccdf6342016-11-07 19:49:54 +00001991static struct ctl_table oa_table[] = {
1992 {
1993 .procname = "perf_stream_paranoid",
1994 .data = &i915_perf_stream_paranoid,
1995 .maxlen = sizeof(i915_perf_stream_paranoid),
1996 .mode = 0644,
1997 .proc_handler = proc_dointvec_minmax,
1998 .extra1 = &zero,
1999 .extra2 = &one,
2000 },
Robert Bragg00319ba2016-11-07 19:49:55 +00002001 {
2002 .procname = "oa_max_sample_rate",
2003 .data = &i915_oa_max_sample_rate,
2004 .maxlen = sizeof(i915_oa_max_sample_rate),
2005 .mode = 0644,
2006 .proc_handler = proc_dointvec_minmax,
2007 .extra1 = &zero,
2008 .extra2 = &oa_sample_rate_hard_limit,
2009 },
Robert Braggccdf6342016-11-07 19:49:54 +00002010 {}
2011};
2012
2013static struct ctl_table i915_root[] = {
2014 {
2015 .procname = "i915",
2016 .maxlen = 0,
2017 .mode = 0555,
2018 .child = oa_table,
2019 },
2020 {}
2021};
2022
2023static struct ctl_table dev_root[] = {
2024 {
2025 .procname = "dev",
2026 .maxlen = 0,
2027 .mode = 0555,
2028 .child = i915_root,
2029 },
2030 {}
2031};
2032
Robert Bragg16d98b32016-12-07 21:40:33 +00002033/**
2034 * i915_perf_init - initialize i915-perf state on module load
2035 * @dev_priv: i915 device instance
2036 *
2037 * Initializes i915-perf state without exposing anything to userspace.
2038 *
2039 * Note: i915-perf initialization is split into an 'init' and 'register'
2040 * phase with the i915_perf_register() exposing state to userspace.
2041 */
Robert Braggeec688e2016-11-07 19:49:47 +00002042void i915_perf_init(struct drm_i915_private *dev_priv)
2043{
Robert Braggd7965152016-11-07 19:49:52 +00002044 if (!IS_HASWELL(dev_priv))
2045 return;
2046
2047 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
2048 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2049 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
2050 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
2051
Robert Braggeec688e2016-11-07 19:49:47 +00002052 INIT_LIST_HEAD(&dev_priv->perf.streams);
2053 mutex_init(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002054 spin_lock_init(&dev_priv->perf.hook_lock);
2055
2056 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
2057 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
2058 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
2059 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
2060 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
2061 dev_priv->perf.oa.ops.read = gen7_oa_read;
2062 dev_priv->perf.oa.ops.oa_buffer_is_empty =
2063 gen7_oa_buffer_is_empty_fop_unlocked;
2064
2065 dev_priv->perf.oa.timestamp_frequency = 12500000;
2066
2067 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
2068
2069 dev_priv->perf.oa.n_builtin_sets =
2070 i915_oa_n_builtin_metric_sets_hsw;
Robert Braggeec688e2016-11-07 19:49:47 +00002071
Robert Braggccdf6342016-11-07 19:49:54 +00002072 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
2073
Robert Braggeec688e2016-11-07 19:49:47 +00002074 dev_priv->perf.initialized = true;
2075}
2076
Robert Bragg16d98b32016-12-07 21:40:33 +00002077/**
2078 * i915_perf_fini - Counter part to i915_perf_init()
2079 * @dev_priv: i915 device instance
2080 */
Robert Braggeec688e2016-11-07 19:49:47 +00002081void i915_perf_fini(struct drm_i915_private *dev_priv)
2082{
2083 if (!dev_priv->perf.initialized)
2084 return;
2085
Robert Braggccdf6342016-11-07 19:49:54 +00002086 unregister_sysctl_table(dev_priv->perf.sysctl_header);
2087
Robert Braggd7965152016-11-07 19:49:52 +00002088 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Braggeec688e2016-11-07 19:49:47 +00002089 dev_priv->perf.initialized = false;
2090}