blob: 838ebc03976f9fda6fe8810bd36d53c409ff48d9 [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
423 * @head_ptr: (inout): the current oa buffer cpu read position
424 * @tail: the current oa buffer gpu write position
425 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000426 * Notably any error condition resulting in a short read (-%ENOSPC or
427 * -%EFAULT) will be returned even though one or more records may
Robert Braggd7965152016-11-07 19:49:52 +0000428 * have been successfully copied. In this case it's up to the caller
429 * to decide if the error should be squashed before returning to
430 * userspace.
431 *
432 * Note: reports are consumed from the head, and appended to the
Robert Bragge81b3a52017-05-11 16:43:24 +0100433 * tail, so the tail chases the head?... If you think that's mad
Robert Braggd7965152016-11-07 19:49:52 +0000434 * and back-to-front you're not alone, but this follows the
435 * Gen PRM naming convention.
Robert Bragg16d98b32016-12-07 21:40:33 +0000436 *
437 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000438 */
439static int gen7_append_oa_reports(struct i915_perf_stream *stream,
440 char __user *buf,
441 size_t count,
442 size_t *offset,
443 u32 *head_ptr,
444 u32 tail)
445{
446 struct drm_i915_private *dev_priv = stream->dev_priv;
447 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
448 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
449 int tail_margin = dev_priv->perf.oa.tail_margin;
450 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
451 u32 mask = (OA_BUFFER_SIZE - 1);
452 u32 head;
453 u32 taken;
454 int ret = 0;
455
456 if (WARN_ON(!stream->enabled))
457 return -EIO;
458
459 head = *head_ptr - gtt_offset;
Robert Braggf2790202017-05-11 16:43:26 +0100460
461 /* An out of bounds or misaligned head pointer implies a driver bug
462 * since we are in full control of head pointer which should only
463 * be incremented by multiples of the report size (notably also
464 * all a power of two).
465 */
466 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size,
467 "Inconsistent OA buffer head pointer = %u\n", head))
468 return -EIO;
469
Robert Braggd7965152016-11-07 19:49:52 +0000470 tail -= gtt_offset;
471
472 /* The OA unit is expected to wrap the tail pointer according to the OA
Robert Braggf2790202017-05-11 16:43:26 +0100473 * buffer size
Robert Braggd7965152016-11-07 19:49:52 +0000474 */
Robert Braggf2790202017-05-11 16:43:26 +0100475 if (tail > OA_BUFFER_SIZE) {
476 DRM_ERROR("Inconsistent OA buffer tail pointer = %u: force restart\n",
477 tail);
Robert Braggd7965152016-11-07 19:49:52 +0000478 dev_priv->perf.oa.ops.oa_disable(dev_priv);
479 dev_priv->perf.oa.ops.oa_enable(dev_priv);
480 *head_ptr = I915_READ(GEN7_OASTATUS2) &
481 GEN7_OASTATUS2_HEAD_MASK;
482 return -EIO;
483 }
484
485
486 /* The tail pointer increases in 64 byte increments, not in report_size
487 * steps...
488 */
489 tail &= ~(report_size - 1);
490
491 /* Move the tail pointer back by the current tail_margin to account for
492 * the possibility that the latest reports may not have really landed
493 * in memory yet...
494 */
495
496 if (OA_TAKEN(tail, head) < report_size + tail_margin)
497 return -EAGAIN;
498
499 tail -= tail_margin;
500 tail &= mask;
501
502 for (/* none */;
503 (taken = OA_TAKEN(tail, head));
504 head = (head + report_size) & mask) {
505 u8 *report = oa_buf_base + head;
506 u32 *report32 = (void *)report;
507
508 /* All the report sizes factor neatly into the buffer
509 * size so we never expect to see a report split
510 * between the beginning and end of the buffer.
511 *
512 * Given the initial alignment check a misalignment
513 * here would imply a driver bug that would result
514 * in an overrun.
515 */
516 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
517 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
518 break;
519 }
520
521 /* The report-ID field for periodic samples includes
522 * some undocumented flags related to what triggered
523 * the report and is never expected to be zero so we
524 * can check that the report isn't invalid before
525 * copying it to userspace...
526 */
527 if (report32[0] == 0) {
Robert Bragg77085502016-12-01 17:21:52 +0000528 DRM_NOTE("Skipping spurious, invalid OA report\n");
Robert Braggd7965152016-11-07 19:49:52 +0000529 continue;
530 }
531
532 ret = append_oa_sample(stream, buf, count, offset, report);
533 if (ret)
534 break;
535
536 /* The above report-id field sanity check is based on
537 * the assumption that the OA buffer is initially
538 * zeroed and we reset the field after copying so the
539 * check is still meaningful once old reports start
540 * being overwritten.
541 */
542 report32[0] = 0;
543 }
544
545 *head_ptr = gtt_offset + head;
546
547 return ret;
548}
549
Robert Bragg16d98b32016-12-07 21:40:33 +0000550/**
551 * gen7_oa_read - copy status records then buffered OA reports
552 * @stream: An i915-perf stream opened for OA metrics
553 * @buf: destination buffer given by userspace
554 * @count: the number of bytes userspace wants to read
555 * @offset: (inout): the current position for writing into @buf
556 *
557 * Checks Gen 7 specific OA unit status registers and if necessary appends
558 * corresponding status records for userspace (such as for a buffer full
559 * condition) and then initiate appending any buffered OA reports.
560 *
561 * Updates @offset according to the number of bytes successfully copied into
562 * the userspace buffer.
563 *
564 * Returns: zero on success or a negative error code
565 */
Robert Braggd7965152016-11-07 19:49:52 +0000566static int gen7_oa_read(struct i915_perf_stream *stream,
567 char __user *buf,
568 size_t count,
569 size_t *offset)
570{
571 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +0000572 u32 oastatus1;
573 u32 head;
574 u32 tail;
575 int ret;
576
577 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
578 return -EIO;
579
Robert Braggd7965152016-11-07 19:49:52 +0000580 oastatus1 = I915_READ(GEN7_OASTATUS1);
581
Robert Braggf2790202017-05-11 16:43:26 +0100582 head = dev_priv->perf.oa.oa_buffer.head;
Robert Braggd7965152016-11-07 19:49:52 +0000583 tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
584
585 /* XXX: On Haswell we don't have a safe way to clear oastatus1
586 * bits while the OA unit is enabled (while the tail pointer
587 * may be updated asynchronously) so we ignore status bits
588 * that have already been reported to userspace.
589 */
590 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
591
592 /* We treat OABUFFER_OVERFLOW as a significant error:
593 *
594 * - The status can be interpreted to mean that the buffer is
595 * currently full (with a higher precedence than OA_TAKEN()
596 * which will start to report a near-empty buffer after an
597 * overflow) but it's awkward that we can't clear the status
598 * on Haswell, so without a reset we won't be able to catch
599 * the state again.
600 *
601 * - Since it also implies the HW has started overwriting old
602 * reports it may also affect our sanity checks for invalid
603 * reports when copying to userspace that assume new reports
604 * are being written to cleared memory.
605 *
606 * - In the future we may want to introduce a flight recorder
607 * mode where the driver will automatically maintain a safe
608 * guard band between head/tail, avoiding this overflow
609 * condition, but we avoid the added driver complexity for
610 * now.
611 */
612 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
613 ret = append_oa_status(stream, buf, count, offset,
614 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
615 if (ret)
616 return ret;
617
Robert Bragg77085502016-12-01 17:21:52 +0000618 DRM_DEBUG("OA buffer overflow: force restart\n");
Robert Braggd7965152016-11-07 19:49:52 +0000619
620 dev_priv->perf.oa.ops.oa_disable(dev_priv);
621 dev_priv->perf.oa.ops.oa_enable(dev_priv);
622
Robert Braggd7965152016-11-07 19:49:52 +0000623 oastatus1 = I915_READ(GEN7_OASTATUS1);
624
Robert Braggf2790202017-05-11 16:43:26 +0100625 head = dev_priv->perf.oa.oa_buffer.head;
Robert Braggd7965152016-11-07 19:49:52 +0000626 tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
627 }
628
629 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
630 ret = append_oa_status(stream, buf, count, offset,
631 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
632 if (ret)
633 return ret;
634 dev_priv->perf.oa.gen7_latched_oastatus1 |=
635 GEN7_OASTATUS1_REPORT_LOST;
636 }
637
638 ret = gen7_append_oa_reports(stream, buf, count, offset,
639 &head, tail);
640
Robert Braggd7965152016-11-07 19:49:52 +0000641 /* Note: we update the head pointer here even if an error
642 * was returned since the error may represent a short read
643 * where some some reports were successfully copied.
644 */
645 I915_WRITE(GEN7_OASTATUS2,
646 ((head & GEN7_OASTATUS2_HEAD_MASK) |
647 OA_MEM_SELECT_GGTT));
Robert Braggf2790202017-05-11 16:43:26 +0100648 dev_priv->perf.oa.oa_buffer.head = head;
Robert Braggd7965152016-11-07 19:49:52 +0000649
650 return ret;
651}
652
Robert Bragg16d98b32016-12-07 21:40:33 +0000653/**
654 * i915_oa_wait_unlocked - handles blocking IO until OA data available
655 * @stream: An i915-perf stream opened for OA metrics
656 *
657 * Called when userspace tries to read() from a blocking stream FD opened
658 * for OA metrics. It waits until the hrtimer callback finds a non-empty
659 * OA buffer and wakes us.
660 *
661 * Note: it's acceptable to have this return with some false positives
662 * since any subsequent read handling will return -EAGAIN if there isn't
663 * really data ready for userspace yet.
664 *
665 * Returns: zero on success or a negative error code
666 */
Robert Braggd7965152016-11-07 19:49:52 +0000667static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
668{
669 struct drm_i915_private *dev_priv = stream->dev_priv;
670
671 /* We would wait indefinitely if periodic sampling is not enabled */
672 if (!dev_priv->perf.oa.periodic)
673 return -EIO;
674
675 /* Note: the oa_buffer_is_empty() condition is ok to run unlocked as it
676 * just performs mmio reads of the OA buffer head + tail pointers and
677 * it's assumed we're handling some operation that implies the stream
678 * can't be destroyed until completion (such as a read()) that ensures
679 * the device + OA buffer can't disappear
680 */
681 return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
682 !dev_priv->perf.oa.ops.oa_buffer_is_empty(dev_priv));
683}
684
Robert Bragg16d98b32016-12-07 21:40:33 +0000685/**
686 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
687 * @stream: An i915-perf stream opened for OA metrics
688 * @file: An i915 perf stream file
689 * @wait: poll() state table
690 *
691 * For handling userspace polling on an i915 perf stream opened for OA metrics,
692 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
693 * when it sees data ready to read in the circular OA buffer.
694 */
Robert Braggd7965152016-11-07 19:49:52 +0000695static void i915_oa_poll_wait(struct i915_perf_stream *stream,
696 struct file *file,
697 poll_table *wait)
698{
699 struct drm_i915_private *dev_priv = stream->dev_priv;
700
701 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
702}
703
Robert Bragg16d98b32016-12-07 21:40:33 +0000704/**
705 * i915_oa_read - just calls through to &i915_oa_ops->read
706 * @stream: An i915-perf stream opened for OA metrics
707 * @buf: destination buffer given by userspace
708 * @count: the number of bytes userspace wants to read
709 * @offset: (inout): the current position for writing into @buf
710 *
711 * Updates @offset according to the number of bytes successfully copied into
712 * the userspace buffer.
713 *
714 * Returns: zero on success or a negative error code
715 */
Robert Braggd7965152016-11-07 19:49:52 +0000716static int i915_oa_read(struct i915_perf_stream *stream,
717 char __user *buf,
718 size_t count,
719 size_t *offset)
720{
721 struct drm_i915_private *dev_priv = stream->dev_priv;
722
723 return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
724}
725
Robert Bragg16d98b32016-12-07 21:40:33 +0000726/**
727 * oa_get_render_ctx_id - determine and hold ctx hw id
728 * @stream: An i915-perf stream opened for OA metrics
729 *
730 * Determine the render context hw id, and ensure it remains fixed for the
Robert Braggd7965152016-11-07 19:49:52 +0000731 * lifetime of the stream. This ensures that we don't have to worry about
732 * updating the context ID in OACONTROL on the fly.
Robert Bragg16d98b32016-12-07 21:40:33 +0000733 *
734 * Returns: zero on success or a negative error code
Robert Braggd7965152016-11-07 19:49:52 +0000735 */
736static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
737{
738 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000739 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Chris Wilson266a2402017-05-04 10:33:08 +0100740 struct intel_ring *ring;
Robert Braggd7965152016-11-07 19:49:52 +0000741 int ret;
742
743 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
744 if (ret)
745 return ret;
746
747 /* As the ID is the gtt offset of the context's vma we pin
748 * the vma to ensure the ID remains fixed.
749 *
750 * NB: implied RCS engine...
751 */
Chris Wilson266a2402017-05-04 10:33:08 +0100752 ring = engine->context_pin(engine, stream->ctx);
753 mutex_unlock(&dev_priv->drm.struct_mutex);
754 if (IS_ERR(ring))
755 return PTR_ERR(ring);
Robert Braggd7965152016-11-07 19:49:52 +0000756
757 /* Explicitly track the ID (instead of calling i915_ggtt_offset()
758 * on the fly) considering the difference with gen8+ and
759 * execlists
760 */
Chris Wilsone8a9c582016-12-18 15:37:20 +0000761 dev_priv->perf.oa.specific_ctx_id =
762 i915_ggtt_offset(stream->ctx->engine[engine->id].state);
Robert Braggd7965152016-11-07 19:49:52 +0000763
Chris Wilson266a2402017-05-04 10:33:08 +0100764 return 0;
Robert Braggd7965152016-11-07 19:49:52 +0000765}
766
Robert Bragg16d98b32016-12-07 21:40:33 +0000767/**
768 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
769 * @stream: An i915-perf stream opened for OA metrics
770 *
771 * In case anything needed doing to ensure the context HW ID would remain valid
772 * for the lifetime of the stream, then that can be undone here.
773 */
Robert Braggd7965152016-11-07 19:49:52 +0000774static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
775{
776 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000777 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Robert Braggd7965152016-11-07 19:49:52 +0000778
779 mutex_lock(&dev_priv->drm.struct_mutex);
780
Robert Braggd7965152016-11-07 19:49:52 +0000781 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000782 engine->context_unpin(engine, stream->ctx);
Robert Braggd7965152016-11-07 19:49:52 +0000783
784 mutex_unlock(&dev_priv->drm.struct_mutex);
785}
786
787static void
788free_oa_buffer(struct drm_i915_private *i915)
789{
790 mutex_lock(&i915->drm.struct_mutex);
791
792 i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
793 i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
794 i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
795
796 i915->perf.oa.oa_buffer.vma = NULL;
797 i915->perf.oa.oa_buffer.vaddr = NULL;
798
799 mutex_unlock(&i915->drm.struct_mutex);
800}
801
802static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
803{
804 struct drm_i915_private *dev_priv = stream->dev_priv;
805
806 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
807
808 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
809
810 free_oa_buffer(dev_priv);
811
812 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
813 intel_runtime_pm_put(dev_priv);
814
815 if (stream->ctx)
816 oa_put_render_ctx_id(stream);
817
818 dev_priv->perf.oa.exclusive_stream = NULL;
819}
820
821static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
822{
823 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
824
825 /* Pre-DevBDW: OABUFFER must be set with counters off,
826 * before OASTATUS1, but after OASTATUS2
827 */
828 I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
Robert Braggf2790202017-05-11 16:43:26 +0100829 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
830
Robert Braggd7965152016-11-07 19:49:52 +0000831 I915_WRITE(GEN7_OABUFFER, gtt_offset);
Robert Braggf2790202017-05-11 16:43:26 +0100832
Robert Braggd7965152016-11-07 19:49:52 +0000833 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
834
835 /* On Haswell we have to track which OASTATUS1 flags we've
836 * already seen since they can't be cleared while periodic
837 * sampling is enabled.
838 */
839 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
840
841 /* NB: although the OA buffer will initially be allocated
842 * zeroed via shmfs (and so this memset is redundant when
843 * first allocating), we may re-init the OA buffer, either
844 * when re-enabling a stream or in error/reset paths.
845 *
846 * The reason we clear the buffer for each re-init is for the
847 * sanity check in gen7_append_oa_reports() that looks at the
848 * report-id field to make sure it's non-zero which relies on
849 * the assumption that new reports are being written to zeroed
850 * memory...
851 */
852 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
853
854 /* Maybe make ->pollin per-stream state if we support multiple
855 * concurrent streams in the future.
856 */
857 dev_priv->perf.oa.pollin = false;
858}
859
860static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
861{
862 struct drm_i915_gem_object *bo;
863 struct i915_vma *vma;
864 int ret;
865
866 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
867 return -ENODEV;
868
869 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
870 if (ret)
871 return ret;
872
873 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
874 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
875
Tvrtko Ursulin12d79d72016-12-01 14:16:37 +0000876 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +0000877 if (IS_ERR(bo)) {
878 DRM_ERROR("Failed to allocate OA buffer\n");
879 ret = PTR_ERR(bo);
880 goto unlock;
881 }
882
883 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
884 if (ret)
885 goto err_unref;
886
887 /* PreHSW required 512K alignment, HSW requires 16M */
888 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
889 if (IS_ERR(vma)) {
890 ret = PTR_ERR(vma);
891 goto err_unref;
892 }
893 dev_priv->perf.oa.oa_buffer.vma = vma;
894
895 dev_priv->perf.oa.oa_buffer.vaddr =
896 i915_gem_object_pin_map(bo, I915_MAP_WB);
897 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
898 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
899 goto err_unpin;
900 }
901
902 dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
903
904 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
905 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
906 dev_priv->perf.oa.oa_buffer.vaddr);
907
908 goto unlock;
909
910err_unpin:
911 __i915_vma_unpin(vma);
912
913err_unref:
914 i915_gem_object_put(bo);
915
916 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
917 dev_priv->perf.oa.oa_buffer.vma = NULL;
918
919unlock:
920 mutex_unlock(&dev_priv->drm.struct_mutex);
921 return ret;
922}
923
924static void config_oa_regs(struct drm_i915_private *dev_priv,
925 const struct i915_oa_reg *regs,
926 int n_regs)
927{
928 int i;
929
930 for (i = 0; i < n_regs; i++) {
931 const struct i915_oa_reg *reg = regs + i;
932
933 I915_WRITE(reg->addr, reg->value);
934 }
935}
936
937static int hsw_enable_metric_set(struct drm_i915_private *dev_priv)
938{
939 int ret = i915_oa_select_metric_set_hsw(dev_priv);
940
941 if (ret)
942 return ret;
943
944 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) |
945 GT_NOA_ENABLE));
946
947 /* PRM:
948 *
949 * OA unit is using “crclk” for its functionality. When trunk
950 * level clock gating takes place, OA clock would be gated,
951 * unable to count the events from non-render clock domain.
952 * Render clock gating must be disabled when OA is enabled to
953 * count the events from non-render domain. Unit level clock
954 * gating for RCS should also be disabled.
955 */
956 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
957 ~GEN7_DOP_CLOCK_GATE_ENABLE));
958 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
959 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
960
961 config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs,
962 dev_priv->perf.oa.mux_regs_len);
963
964 /* It apparently takes a fairly long time for a new MUX
965 * configuration to be be applied after these register writes.
966 * This delay duration was derived empirically based on the
967 * render_basic config but hopefully it covers the maximum
968 * configuration latency.
969 *
970 * As a fallback, the checks in _append_oa_reports() to skip
971 * invalid OA reports do also seem to work to discard reports
972 * generated before this config has completed - albeit not
973 * silently.
974 *
975 * Unfortunately this is essentially a magic number, since we
976 * don't currently know of a reliable mechanism for predicting
977 * how long the MUX config will take to apply and besides
978 * seeing invalid reports we don't know of a reliable way to
979 * explicitly check that the MUX config has landed.
980 *
981 * It's even possible we've miss characterized the underlying
982 * problem - it just seems like the simplest explanation why
983 * a delay at this location would mitigate any invalid reports.
984 */
985 usleep_range(15000, 20000);
986
987 config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
988 dev_priv->perf.oa.b_counter_regs_len);
989
990 return 0;
991}
992
993static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
994{
995 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
996 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
997 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
998 GEN7_DOP_CLOCK_GATE_ENABLE));
999
1000 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1001 ~GT_NOA_ENABLE));
1002}
1003
1004static void gen7_update_oacontrol_locked(struct drm_i915_private *dev_priv)
1005{
Chris Wilson67520412017-03-02 13:28:01 +00001006 lockdep_assert_held(&dev_priv->perf.hook_lock);
Robert Braggd7965152016-11-07 19:49:52 +00001007
1008 if (dev_priv->perf.oa.exclusive_stream->enabled) {
1009 struct i915_gem_context *ctx =
1010 dev_priv->perf.oa.exclusive_stream->ctx;
1011 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1012
1013 bool periodic = dev_priv->perf.oa.periodic;
1014 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1015 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1016
1017 I915_WRITE(GEN7_OACONTROL,
1018 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1019 (period_exponent <<
1020 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1021 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1022 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1023 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1024 GEN7_OACONTROL_ENABLE);
1025 } else
1026 I915_WRITE(GEN7_OACONTROL, 0);
1027}
1028
1029static void gen7_oa_enable(struct drm_i915_private *dev_priv)
1030{
1031 unsigned long flags;
1032
1033 /* Reset buf pointers so we don't forward reports from before now.
1034 *
1035 * Think carefully if considering trying to avoid this, since it
1036 * also ensures status flags and the buffer itself are cleared
1037 * in error paths, and we have checks for invalid reports based
1038 * on the assumption that certain fields are written to zeroed
1039 * memory which this helps maintains.
1040 */
1041 gen7_init_oa_buffer(dev_priv);
1042
1043 spin_lock_irqsave(&dev_priv->perf.hook_lock, flags);
1044 gen7_update_oacontrol_locked(dev_priv);
1045 spin_unlock_irqrestore(&dev_priv->perf.hook_lock, flags);
1046}
1047
Robert Bragg16d98b32016-12-07 21:40:33 +00001048/**
1049 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1050 * @stream: An i915 perf stream opened for OA metrics
1051 *
1052 * [Re]enables hardware periodic sampling according to the period configured
1053 * when opening the stream. This also starts a hrtimer that will periodically
1054 * check for data in the circular OA buffer for notifying userspace (e.g.
1055 * during a read() or poll()).
1056 */
Robert Braggd7965152016-11-07 19:49:52 +00001057static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1058{
1059 struct drm_i915_private *dev_priv = stream->dev_priv;
1060
1061 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1062
1063 if (dev_priv->perf.oa.periodic)
1064 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1065 ns_to_ktime(POLL_PERIOD),
1066 HRTIMER_MODE_REL_PINNED);
1067}
1068
1069static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1070{
1071 I915_WRITE(GEN7_OACONTROL, 0);
1072}
1073
Robert Bragg16d98b32016-12-07 21:40:33 +00001074/**
1075 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1076 * @stream: An i915 perf stream opened for OA metrics
1077 *
1078 * Stops the OA unit from periodically writing counter reports into the
1079 * circular OA buffer. This also stops the hrtimer that periodically checks for
1080 * data in the circular OA buffer, for notifying userspace.
1081 */
Robert Braggd7965152016-11-07 19:49:52 +00001082static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1083{
1084 struct drm_i915_private *dev_priv = stream->dev_priv;
1085
1086 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1087
1088 if (dev_priv->perf.oa.periodic)
1089 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1090}
1091
1092static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
1093{
Chris Wilson24603932016-11-23 15:07:14 +00001094 return div_u64(1000000000ULL * (2ULL << exponent),
1095 dev_priv->perf.oa.timestamp_frequency);
Robert Braggd7965152016-11-07 19:49:52 +00001096}
1097
1098static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1099 .destroy = i915_oa_stream_destroy,
1100 .enable = i915_oa_stream_enable,
1101 .disable = i915_oa_stream_disable,
1102 .wait_unlocked = i915_oa_wait_unlocked,
1103 .poll_wait = i915_oa_poll_wait,
1104 .read = i915_oa_read,
1105};
1106
Robert Bragg16d98b32016-12-07 21:40:33 +00001107/**
1108 * i915_oa_stream_init - validate combined props for OA stream and init
1109 * @stream: An i915 perf stream
1110 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1111 * @props: The property state that configures stream (individually validated)
1112 *
1113 * While read_properties_unlocked() validates properties in isolation it
1114 * doesn't ensure that the combination necessarily makes sense.
1115 *
1116 * At this point it has been determined that userspace wants a stream of
1117 * OA metrics, but still we need to further validate the combined
1118 * properties are OK.
1119 *
1120 * If the configuration makes sense then we can allocate memory for
1121 * a circular OA buffer and apply the requested metric set configuration.
1122 *
1123 * Returns: zero on success or a negative error code.
1124 */
Robert Braggd7965152016-11-07 19:49:52 +00001125static int i915_oa_stream_init(struct i915_perf_stream *stream,
1126 struct drm_i915_perf_open_param *param,
1127 struct perf_open_properties *props)
1128{
1129 struct drm_i915_private *dev_priv = stream->dev_priv;
1130 int format_size;
1131 int ret;
1132
Robert Bragg442b8c02016-11-07 19:49:53 +00001133 /* If the sysfs metrics/ directory wasn't registered for some
1134 * reason then don't let userspace try their luck with config
1135 * IDs
1136 */
1137 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00001138 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00001139 return -EINVAL;
1140 }
1141
Robert Braggd7965152016-11-07 19:49:52 +00001142 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00001143 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001144 return -EINVAL;
1145 }
1146
1147 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
Robert Bragg77085502016-12-01 17:21:52 +00001148 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001149 return -ENODEV;
1150 }
1151
1152 /* To avoid the complexity of having to accurately filter
1153 * counter reports and marshal to the appropriate client
1154 * we currently only allow exclusive access
1155 */
1156 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00001157 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00001158 return -EBUSY;
1159 }
1160
1161 if (!props->metrics_set) {
Robert Bragg77085502016-12-01 17:21:52 +00001162 DRM_DEBUG("OA metric set not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001163 return -EINVAL;
1164 }
1165
1166 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00001167 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001168 return -EINVAL;
1169 }
1170
1171 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
1172
1173 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
1174
1175 stream->sample_flags |= SAMPLE_OA_REPORT;
1176 stream->sample_size += format_size;
1177
1178 dev_priv->perf.oa.oa_buffer.format_size = format_size;
1179 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
1180 return -EINVAL;
1181
1182 dev_priv->perf.oa.oa_buffer.format =
1183 dev_priv->perf.oa.oa_formats[props->oa_format].format;
1184
1185 dev_priv->perf.oa.metrics_set = props->metrics_set;
1186
1187 dev_priv->perf.oa.periodic = props->oa_periodic;
1188 if (dev_priv->perf.oa.periodic) {
Chris Wilson24603932016-11-23 15:07:14 +00001189 u32 tail;
Robert Braggd7965152016-11-07 19:49:52 +00001190
1191 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
1192
1193 /* See comment for OA_TAIL_MARGIN_NSEC for details
1194 * about this tail_margin...
1195 */
Chris Wilson24603932016-11-23 15:07:14 +00001196 tail = div64_u64(OA_TAIL_MARGIN_NSEC,
1197 oa_exponent_to_ns(dev_priv,
1198 props->oa_period_exponent));
1199 dev_priv->perf.oa.tail_margin = (tail + 1) * format_size;
Robert Braggd7965152016-11-07 19:49:52 +00001200 }
1201
1202 if (stream->ctx) {
1203 ret = oa_get_render_ctx_id(stream);
1204 if (ret)
1205 return ret;
1206 }
1207
1208 ret = alloc_oa_buffer(dev_priv);
1209 if (ret)
1210 goto err_oa_buf_alloc;
1211
1212 /* PRM - observability performance counters:
1213 *
1214 * OACONTROL, performance counter enable, note:
1215 *
1216 * "When this bit is set, in order to have coherent counts,
1217 * RC6 power state and trunk clock gating must be disabled.
1218 * This can be achieved by programming MMIO registers as
1219 * 0xA094=0 and 0xA090[31]=1"
1220 *
1221 * In our case we are expecting that taking pm + FORCEWAKE
1222 * references will effectively disable RC6.
1223 */
1224 intel_runtime_pm_get(dev_priv);
1225 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
1226
1227 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv);
1228 if (ret)
1229 goto err_enable;
1230
1231 stream->ops = &i915_oa_stream_ops;
1232
1233 dev_priv->perf.oa.exclusive_stream = stream;
1234
1235 return 0;
1236
1237err_enable:
1238 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1239 intel_runtime_pm_put(dev_priv);
1240 free_oa_buffer(dev_priv);
1241
1242err_oa_buf_alloc:
1243 if (stream->ctx)
1244 oa_put_render_ctx_id(stream);
1245
1246 return ret;
1247}
1248
Robert Bragg16d98b32016-12-07 21:40:33 +00001249/**
1250 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
1251 * @stream: An i915 perf stream
1252 * @file: An i915 perf stream file
1253 * @buf: destination buffer given by userspace
1254 * @count: the number of bytes userspace wants to read
1255 * @ppos: (inout) file seek position (unused)
1256 *
1257 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
1258 * ensure that if we've successfully copied any data then reporting that takes
1259 * precedence over any internal error status, so the data isn't lost.
1260 *
1261 * For example ret will be -ENOSPC whenever there is more buffered data than
1262 * can be copied to userspace, but that's only interesting if we weren't able
1263 * to copy some data because it implies the userspace buffer is too small to
1264 * receive a single record (and we never split records).
1265 *
1266 * Another case with ret == -EFAULT is more of a grey area since it would seem
1267 * like bad form for userspace to ask us to overrun its buffer, but the user
1268 * knows best:
1269 *
1270 * http://yarchive.net/comp/linux/partial_reads_writes.html
1271 *
1272 * Returns: The number of bytes copied or a negative error code on failure.
1273 */
Robert Braggeec688e2016-11-07 19:49:47 +00001274static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
1275 struct file *file,
1276 char __user *buf,
1277 size_t count,
1278 loff_t *ppos)
1279{
1280 /* Note we keep the offset (aka bytes read) separate from any
1281 * error status so that the final check for whether we return
1282 * the bytes read with a higher precedence than any error (see
1283 * comment below) doesn't need to be handled/duplicated in
1284 * stream->ops->read() implementations.
1285 */
1286 size_t offset = 0;
1287 int ret = stream->ops->read(stream, buf, count, &offset);
1288
Robert Braggeec688e2016-11-07 19:49:47 +00001289 return offset ?: (ret ?: -EAGAIN);
1290}
1291
Robert Bragg16d98b32016-12-07 21:40:33 +00001292/**
1293 * i915_perf_read - handles read() FOP for i915 perf stream FDs
1294 * @file: An i915 perf stream file
1295 * @buf: destination buffer given by userspace
1296 * @count: the number of bytes userspace wants to read
1297 * @ppos: (inout) file seek position (unused)
1298 *
1299 * The entry point for handling a read() on a stream file descriptor from
1300 * userspace. Most of the work is left to the i915_perf_read_locked() and
1301 * &i915_perf_stream_ops->read but to save having stream implementations (of
1302 * which we might have multiple later) we handle blocking read here.
1303 *
1304 * We can also consistently treat trying to read from a disabled stream
1305 * as an IO error so implementations can assume the stream is enabled
1306 * while reading.
1307 *
1308 * Returns: The number of bytes copied or a negative error code on failure.
1309 */
Robert Braggeec688e2016-11-07 19:49:47 +00001310static ssize_t i915_perf_read(struct file *file,
1311 char __user *buf,
1312 size_t count,
1313 loff_t *ppos)
1314{
1315 struct i915_perf_stream *stream = file->private_data;
1316 struct drm_i915_private *dev_priv = stream->dev_priv;
1317 ssize_t ret;
1318
Robert Braggd7965152016-11-07 19:49:52 +00001319 /* To ensure it's handled consistently we simply treat all reads of a
1320 * disabled stream as an error. In particular it might otherwise lead
1321 * to a deadlock for blocking file descriptors...
1322 */
1323 if (!stream->enabled)
1324 return -EIO;
1325
Robert Braggeec688e2016-11-07 19:49:47 +00001326 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00001327 /* There's the small chance of false positives from
1328 * stream->ops->wait_unlocked.
1329 *
1330 * E.g. with single context filtering since we only wait until
1331 * oabuffer has >= 1 report we don't immediately know whether
1332 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00001333 */
1334 do {
1335 ret = stream->ops->wait_unlocked(stream);
1336 if (ret)
1337 return ret;
1338
1339 mutex_lock(&dev_priv->perf.lock);
1340 ret = i915_perf_read_locked(stream, file,
1341 buf, count, ppos);
1342 mutex_unlock(&dev_priv->perf.lock);
1343 } while (ret == -EAGAIN);
1344 } else {
1345 mutex_lock(&dev_priv->perf.lock);
1346 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
1347 mutex_unlock(&dev_priv->perf.lock);
1348 }
1349
Robert Bragg26ebd9c2017-05-11 16:43:25 +01001350 /* We allow the poll checking to sometimes report false positive POLLIN
1351 * events where we might actually report EAGAIN on read() if there's
1352 * not really any data available. In this situation though we don't
1353 * want to enter a busy loop between poll() reporting a POLLIN event
1354 * and read() returning -EAGAIN. Clearing the oa.pollin state here
1355 * effectively ensures we back off until the next hrtimer callback
1356 * before reporting another POLLIN event.
1357 */
1358 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00001359 /* Maybe make ->pollin per-stream state if we support multiple
1360 * concurrent streams in the future.
1361 */
1362 dev_priv->perf.oa.pollin = false;
1363 }
1364
Robert Braggeec688e2016-11-07 19:49:47 +00001365 return ret;
1366}
1367
Robert Braggd7965152016-11-07 19:49:52 +00001368static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
1369{
1370 struct drm_i915_private *dev_priv =
1371 container_of(hrtimer, typeof(*dev_priv),
1372 perf.oa.poll_check_timer);
1373
1374 if (!dev_priv->perf.oa.ops.oa_buffer_is_empty(dev_priv)) {
1375 dev_priv->perf.oa.pollin = true;
1376 wake_up(&dev_priv->perf.oa.poll_wq);
1377 }
1378
1379 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
1380
1381 return HRTIMER_RESTART;
1382}
1383
Robert Bragg16d98b32016-12-07 21:40:33 +00001384/**
1385 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
1386 * @dev_priv: i915 device instance
1387 * @stream: An i915 perf stream
1388 * @file: An i915 perf stream file
1389 * @wait: poll() state table
1390 *
1391 * For handling userspace polling on an i915 perf stream, this calls through to
1392 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
1393 * will be woken for new stream data.
1394 *
1395 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1396 * with any non-file-operation driver hooks.
1397 *
1398 * Returns: any poll events that are ready without sleeping
1399 */
Robert Braggd7965152016-11-07 19:49:52 +00001400static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
1401 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00001402 struct file *file,
1403 poll_table *wait)
1404{
Robert Braggd7965152016-11-07 19:49:52 +00001405 unsigned int events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00001406
1407 stream->ops->poll_wait(stream, file, wait);
1408
Robert Braggd7965152016-11-07 19:49:52 +00001409 /* Note: we don't explicitly check whether there's something to read
1410 * here since this path may be very hot depending on what else
1411 * userspace is polling, or on the timeout in use. We rely solely on
1412 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
1413 * samples to read.
1414 */
1415 if (dev_priv->perf.oa.pollin)
1416 events |= POLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00001417
Robert Braggd7965152016-11-07 19:49:52 +00001418 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00001419}
1420
Robert Bragg16d98b32016-12-07 21:40:33 +00001421/**
1422 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
1423 * @file: An i915 perf stream file
1424 * @wait: poll() state table
1425 *
1426 * For handling userspace polling on an i915 perf stream, this ensures
1427 * poll_wait() gets called with a wait queue that will be woken for new stream
1428 * data.
1429 *
1430 * Note: Implementation deferred to i915_perf_poll_locked()
1431 *
1432 * Returns: any poll events that are ready without sleeping
1433 */
Robert Braggeec688e2016-11-07 19:49:47 +00001434static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
1435{
1436 struct i915_perf_stream *stream = file->private_data;
1437 struct drm_i915_private *dev_priv = stream->dev_priv;
1438 int ret;
1439
1440 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00001441 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00001442 mutex_unlock(&dev_priv->perf.lock);
1443
1444 return ret;
1445}
1446
Robert Bragg16d98b32016-12-07 21:40:33 +00001447/**
1448 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
1449 * @stream: A disabled i915 perf stream
1450 *
1451 * [Re]enables the associated capture of data for this stream.
1452 *
1453 * If a stream was previously enabled then there's currently no intention
1454 * to provide userspace any guarantee about the preservation of previously
1455 * buffered data.
1456 */
Robert Braggeec688e2016-11-07 19:49:47 +00001457static void i915_perf_enable_locked(struct i915_perf_stream *stream)
1458{
1459 if (stream->enabled)
1460 return;
1461
1462 /* Allow stream->ops->enable() to refer to this */
1463 stream->enabled = true;
1464
1465 if (stream->ops->enable)
1466 stream->ops->enable(stream);
1467}
1468
Robert Bragg16d98b32016-12-07 21:40:33 +00001469/**
1470 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
1471 * @stream: An enabled i915 perf stream
1472 *
1473 * Disables the associated capture of data for this stream.
1474 *
1475 * The intention is that disabling an re-enabling a stream will ideally be
1476 * cheaper than destroying and re-opening a stream with the same configuration,
1477 * though there are no formal guarantees about what state or buffered data
1478 * must be retained between disabling and re-enabling a stream.
1479 *
1480 * Note: while a stream is disabled it's considered an error for userspace
1481 * to attempt to read from the stream (-EIO).
1482 */
Robert Braggeec688e2016-11-07 19:49:47 +00001483static void i915_perf_disable_locked(struct i915_perf_stream *stream)
1484{
1485 if (!stream->enabled)
1486 return;
1487
1488 /* Allow stream->ops->disable() to refer to this */
1489 stream->enabled = false;
1490
1491 if (stream->ops->disable)
1492 stream->ops->disable(stream);
1493}
1494
Robert Bragg16d98b32016-12-07 21:40:33 +00001495/**
1496 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1497 * @stream: An i915 perf stream
1498 * @cmd: the ioctl request
1499 * @arg: the ioctl data
1500 *
1501 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1502 * with any non-file-operation driver hooks.
1503 *
1504 * Returns: zero on success or a negative error code. Returns -EINVAL for
1505 * an unknown ioctl request.
1506 */
Robert Braggeec688e2016-11-07 19:49:47 +00001507static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
1508 unsigned int cmd,
1509 unsigned long arg)
1510{
1511 switch (cmd) {
1512 case I915_PERF_IOCTL_ENABLE:
1513 i915_perf_enable_locked(stream);
1514 return 0;
1515 case I915_PERF_IOCTL_DISABLE:
1516 i915_perf_disable_locked(stream);
1517 return 0;
1518 }
1519
1520 return -EINVAL;
1521}
1522
Robert Bragg16d98b32016-12-07 21:40:33 +00001523/**
1524 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1525 * @file: An i915 perf stream file
1526 * @cmd: the ioctl request
1527 * @arg: the ioctl data
1528 *
1529 * Implementation deferred to i915_perf_ioctl_locked().
1530 *
1531 * Returns: zero on success or a negative error code. Returns -EINVAL for
1532 * an unknown ioctl request.
1533 */
Robert Braggeec688e2016-11-07 19:49:47 +00001534static long i915_perf_ioctl(struct file *file,
1535 unsigned int cmd,
1536 unsigned long arg)
1537{
1538 struct i915_perf_stream *stream = file->private_data;
1539 struct drm_i915_private *dev_priv = stream->dev_priv;
1540 long ret;
1541
1542 mutex_lock(&dev_priv->perf.lock);
1543 ret = i915_perf_ioctl_locked(stream, cmd, arg);
1544 mutex_unlock(&dev_priv->perf.lock);
1545
1546 return ret;
1547}
1548
Robert Bragg16d98b32016-12-07 21:40:33 +00001549/**
1550 * i915_perf_destroy_locked - destroy an i915 perf stream
1551 * @stream: An i915 perf stream
1552 *
1553 * Frees all resources associated with the given i915 perf @stream, disabling
1554 * any associated data capture in the process.
1555 *
1556 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1557 * with any non-file-operation driver hooks.
1558 */
Robert Braggeec688e2016-11-07 19:49:47 +00001559static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
1560{
Robert Braggeec688e2016-11-07 19:49:47 +00001561 if (stream->enabled)
1562 i915_perf_disable_locked(stream);
1563
1564 if (stream->ops->destroy)
1565 stream->ops->destroy(stream);
1566
1567 list_del(&stream->link);
1568
Chris Wilson69df05e2016-12-18 15:37:21 +00001569 if (stream->ctx)
1570 i915_gem_context_put_unlocked(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001571
1572 kfree(stream);
1573}
1574
Robert Bragg16d98b32016-12-07 21:40:33 +00001575/**
1576 * i915_perf_release - handles userspace close() of a stream file
1577 * @inode: anonymous inode associated with file
1578 * @file: An i915 perf stream file
1579 *
1580 * Cleans up any resources associated with an open i915 perf stream file.
1581 *
1582 * NB: close() can't really fail from the userspace point of view.
1583 *
1584 * Returns: zero on success or a negative error code.
1585 */
Robert Braggeec688e2016-11-07 19:49:47 +00001586static int i915_perf_release(struct inode *inode, struct file *file)
1587{
1588 struct i915_perf_stream *stream = file->private_data;
1589 struct drm_i915_private *dev_priv = stream->dev_priv;
1590
1591 mutex_lock(&dev_priv->perf.lock);
1592 i915_perf_destroy_locked(stream);
1593 mutex_unlock(&dev_priv->perf.lock);
1594
1595 return 0;
1596}
1597
1598
1599static const struct file_operations fops = {
1600 .owner = THIS_MODULE,
1601 .llseek = no_llseek,
1602 .release = i915_perf_release,
1603 .poll = i915_perf_poll,
1604 .read = i915_perf_read,
1605 .unlocked_ioctl = i915_perf_ioctl,
1606};
1607
1608
1609static struct i915_gem_context *
1610lookup_context(struct drm_i915_private *dev_priv,
1611 struct drm_i915_file_private *file_priv,
1612 u32 ctx_user_handle)
1613{
1614 struct i915_gem_context *ctx;
1615 int ret;
1616
1617 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1618 if (ret)
1619 return ERR_PTR(ret);
1620
1621 ctx = i915_gem_context_lookup(file_priv, ctx_user_handle);
1622 if (!IS_ERR(ctx))
1623 i915_gem_context_get(ctx);
1624
1625 mutex_unlock(&dev_priv->drm.struct_mutex);
1626
1627 return ctx;
1628}
1629
Robert Bragg16d98b32016-12-07 21:40:33 +00001630/**
1631 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
1632 * @dev_priv: i915 device instance
1633 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
1634 * @props: individually validated u64 property value pairs
1635 * @file: drm file
1636 *
1637 * See i915_perf_ioctl_open() for interface details.
1638 *
1639 * Implements further stream config validation and stream initialization on
1640 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
1641 * taken to serialize with any non-file-operation driver hooks.
1642 *
1643 * Note: at this point the @props have only been validated in isolation and
1644 * it's still necessary to validate that the combination of properties makes
1645 * sense.
1646 *
1647 * In the case where userspace is interested in OA unit metrics then further
1648 * config validation and stream initialization details will be handled by
1649 * i915_oa_stream_init(). The code here should only validate config state that
1650 * will be relevant to all stream types / backends.
1651 *
1652 * Returns: zero on success or a negative error code.
1653 */
Robert Braggeec688e2016-11-07 19:49:47 +00001654static int
1655i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
1656 struct drm_i915_perf_open_param *param,
1657 struct perf_open_properties *props,
1658 struct drm_file *file)
1659{
1660 struct i915_gem_context *specific_ctx = NULL;
1661 struct i915_perf_stream *stream = NULL;
1662 unsigned long f_flags = 0;
1663 int stream_fd;
1664 int ret;
1665
1666 if (props->single_context) {
1667 u32 ctx_handle = props->ctx_handle;
1668 struct drm_i915_file_private *file_priv = file->driver_priv;
1669
1670 specific_ctx = lookup_context(dev_priv, file_priv, ctx_handle);
1671 if (IS_ERR(specific_ctx)) {
1672 ret = PTR_ERR(specific_ctx);
1673 if (ret != -EINTR)
Robert Bragg77085502016-12-01 17:21:52 +00001674 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
Robert Braggeec688e2016-11-07 19:49:47 +00001675 ctx_handle);
1676 goto err;
1677 }
1678 }
1679
Robert Braggccdf6342016-11-07 19:49:54 +00001680 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
1681 * we check a dev.i915.perf_stream_paranoid sysctl option
1682 * to determine if it's ok to access system wide OA counters
1683 * without CAP_SYS_ADMIN privileges.
1684 */
1685 if (!specific_ctx &&
1686 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001687 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001688 ret = -EACCES;
1689 goto err_ctx;
1690 }
1691
1692 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
1693 if (!stream) {
1694 ret = -ENOMEM;
1695 goto err_ctx;
1696 }
1697
Robert Braggeec688e2016-11-07 19:49:47 +00001698 stream->dev_priv = dev_priv;
1699 stream->ctx = specific_ctx;
1700
Robert Braggd7965152016-11-07 19:49:52 +00001701 ret = i915_oa_stream_init(stream, param, props);
1702 if (ret)
1703 goto err_alloc;
1704
1705 /* we avoid simply assigning stream->sample_flags = props->sample_flags
1706 * to have _stream_init check the combination of sample flags more
1707 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00001708 */
Robert Braggd7965152016-11-07 19:49:52 +00001709 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
1710 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01001711 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00001712 }
Robert Braggeec688e2016-11-07 19:49:47 +00001713
1714 list_add(&stream->link, &dev_priv->perf.streams);
1715
1716 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
1717 f_flags |= O_CLOEXEC;
1718 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
1719 f_flags |= O_NONBLOCK;
1720
1721 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
1722 if (stream_fd < 0) {
1723 ret = stream_fd;
1724 goto err_open;
1725 }
1726
1727 if (!(param->flags & I915_PERF_FLAG_DISABLED))
1728 i915_perf_enable_locked(stream);
1729
1730 return stream_fd;
1731
1732err_open:
1733 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01001734err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00001735 if (stream->ops->destroy)
1736 stream->ops->destroy(stream);
1737err_alloc:
1738 kfree(stream);
1739err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00001740 if (specific_ctx)
1741 i915_gem_context_put_unlocked(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001742err:
1743 return ret;
1744}
1745
Robert Bragg16d98b32016-12-07 21:40:33 +00001746/**
1747 * read_properties_unlocked - validate + copy userspace stream open properties
1748 * @dev_priv: i915 device instance
1749 * @uprops: The array of u64 key value pairs given by userspace
1750 * @n_props: The number of key value pairs expected in @uprops
1751 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00001752 *
1753 * Note this function only validates properties in isolation it doesn't
1754 * validate that the combination of properties makes sense or that all
1755 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00001756 *
1757 * Note that there currently aren't any ordering requirements for properties so
1758 * we shouldn't validate or assume anything about ordering here. This doesn't
1759 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00001760 */
1761static int read_properties_unlocked(struct drm_i915_private *dev_priv,
1762 u64 __user *uprops,
1763 u32 n_props,
1764 struct perf_open_properties *props)
1765{
1766 u64 __user *uprop = uprops;
1767 int i;
1768
1769 memset(props, 0, sizeof(struct perf_open_properties));
1770
1771 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00001772 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001773 return -EINVAL;
1774 }
1775
1776 /* Considering that ID = 0 is reserved and assuming that we don't
1777 * (currently) expect any configurations to ever specify duplicate
1778 * values for a particular property ID then the last _PROP_MAX value is
1779 * one greater than the maximum number of properties we expect to get
1780 * from userspace.
1781 */
1782 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001783 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001784 return -EINVAL;
1785 }
1786
1787 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00001788 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00001789 u64 id, value;
1790 int ret;
1791
1792 ret = get_user(id, uprop);
1793 if (ret)
1794 return ret;
1795
1796 ret = get_user(value, uprop + 1);
1797 if (ret)
1798 return ret;
1799
Matthew Auld0a309f92017-03-27 21:32:36 +01001800 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
1801 DRM_DEBUG("Unknown i915 perf property ID\n");
1802 return -EINVAL;
1803 }
1804
Robert Braggeec688e2016-11-07 19:49:47 +00001805 switch ((enum drm_i915_perf_property_id)id) {
1806 case DRM_I915_PERF_PROP_CTX_HANDLE:
1807 props->single_context = 1;
1808 props->ctx_handle = value;
1809 break;
Robert Braggd7965152016-11-07 19:49:52 +00001810 case DRM_I915_PERF_PROP_SAMPLE_OA:
1811 props->sample_flags |= SAMPLE_OA_REPORT;
1812 break;
1813 case DRM_I915_PERF_PROP_OA_METRICS_SET:
1814 if (value == 0 ||
1815 value > dev_priv->perf.oa.n_builtin_sets) {
Robert Bragg77085502016-12-01 17:21:52 +00001816 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00001817 return -EINVAL;
1818 }
1819 props->metrics_set = value;
1820 break;
1821 case DRM_I915_PERF_PROP_OA_FORMAT:
1822 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001823 DRM_DEBUG("Invalid OA report format\n");
Robert Braggd7965152016-11-07 19:49:52 +00001824 return -EINVAL;
1825 }
1826 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg77085502016-12-01 17:21:52 +00001827 DRM_DEBUG("Invalid OA report format\n");
Robert Braggd7965152016-11-07 19:49:52 +00001828 return -EINVAL;
1829 }
1830 props->oa_format = value;
1831 break;
1832 case DRM_I915_PERF_PROP_OA_EXPONENT:
1833 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001834 DRM_DEBUG("OA timer exponent too high (> %u)\n",
1835 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00001836 return -EINVAL;
1837 }
1838
Robert Bragg00319ba2016-11-07 19:49:55 +00001839 /* Theoretically we can program the OA unit to sample
Robert Braggd7965152016-11-07 19:49:52 +00001840 * every 160ns but don't allow that by default unless
1841 * root.
1842 *
Robert Bragg00319ba2016-11-07 19:49:55 +00001843 * On Haswell the period is derived from the exponent
1844 * as:
1845 *
1846 * period = 80ns * 2^(exponent + 1)
Robert Braggd7965152016-11-07 19:49:52 +00001847 */
Robert Bragg00319ba2016-11-07 19:49:55 +00001848 BUILD_BUG_ON(sizeof(oa_period) != 8);
1849 oa_period = 80ull * (2ull << value);
1850
1851 /* This check is primarily to ensure that oa_period <=
1852 * UINT32_MAX (before passing to do_div which only
1853 * accepts a u32 denominator), but we can also skip
1854 * checking anything < 1Hz which implicitly can't be
1855 * limited via an integer oa_max_sample_rate.
1856 */
1857 if (oa_period <= NSEC_PER_SEC) {
1858 u64 tmp = NSEC_PER_SEC;
1859 do_div(tmp, oa_period);
1860 oa_freq_hz = tmp;
1861 } else
1862 oa_freq_hz = 0;
1863
1864 if (oa_freq_hz > i915_oa_max_sample_rate &&
1865 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001866 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 +00001867 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00001868 return -EACCES;
1869 }
1870
1871 props->oa_periodic = true;
1872 props->oa_period_exponent = value;
1873 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01001874 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00001875 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00001876 return -EINVAL;
1877 }
1878
1879 uprop += 2;
1880 }
1881
1882 return 0;
1883}
1884
Robert Bragg16d98b32016-12-07 21:40:33 +00001885/**
1886 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
1887 * @dev: drm device
1888 * @data: ioctl data copied from userspace (unvalidated)
1889 * @file: drm file
1890 *
1891 * Validates the stream open parameters given by userspace including flags
1892 * and an array of u64 key, value pair properties.
1893 *
1894 * Very little is assumed up front about the nature of the stream being
1895 * opened (for instance we don't assume it's for periodic OA unit metrics). An
1896 * i915-perf stream is expected to be a suitable interface for other forms of
1897 * buffered data written by the GPU besides periodic OA metrics.
1898 *
1899 * Note we copy the properties from userspace outside of the i915 perf
1900 * mutex to avoid an awkward lockdep with mmap_sem.
1901 *
1902 * Most of the implementation details are handled by
1903 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
1904 * mutex for serializing with any non-file-operation driver hooks.
1905 *
1906 * Return: A newly opened i915 Perf stream file descriptor or negative
1907 * error code on failure.
1908 */
Robert Braggeec688e2016-11-07 19:49:47 +00001909int i915_perf_open_ioctl(struct drm_device *dev, void *data,
1910 struct drm_file *file)
1911{
1912 struct drm_i915_private *dev_priv = dev->dev_private;
1913 struct drm_i915_perf_open_param *param = data;
1914 struct perf_open_properties props;
1915 u32 known_open_flags;
1916 int ret;
1917
1918 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00001919 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001920 return -ENOTSUPP;
1921 }
1922
1923 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
1924 I915_PERF_FLAG_FD_NONBLOCK |
1925 I915_PERF_FLAG_DISABLED;
1926 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00001927 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001928 return -EINVAL;
1929 }
1930
1931 ret = read_properties_unlocked(dev_priv,
1932 u64_to_user_ptr(param->properties_ptr),
1933 param->num_properties,
1934 &props);
1935 if (ret)
1936 return ret;
1937
1938 mutex_lock(&dev_priv->perf.lock);
1939 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
1940 mutex_unlock(&dev_priv->perf.lock);
1941
1942 return ret;
1943}
1944
Robert Bragg16d98b32016-12-07 21:40:33 +00001945/**
1946 * i915_perf_register - exposes i915-perf to userspace
1947 * @dev_priv: i915 device instance
1948 *
1949 * In particular OA metric sets are advertised under a sysfs metrics/
1950 * directory allowing userspace to enumerate valid IDs that can be
1951 * used to open an i915-perf stream.
1952 */
Robert Bragg442b8c02016-11-07 19:49:53 +00001953void i915_perf_register(struct drm_i915_private *dev_priv)
1954{
1955 if (!IS_HASWELL(dev_priv))
1956 return;
1957
1958 if (!dev_priv->perf.initialized)
1959 return;
1960
1961 /* To be sure we're synchronized with an attempted
1962 * i915_perf_open_ioctl(); considering that we register after
1963 * being exposed to userspace.
1964 */
1965 mutex_lock(&dev_priv->perf.lock);
1966
1967 dev_priv->perf.metrics_kobj =
1968 kobject_create_and_add("metrics",
1969 &dev_priv->drm.primary->kdev->kobj);
1970 if (!dev_priv->perf.metrics_kobj)
1971 goto exit;
1972
1973 if (i915_perf_register_sysfs_hsw(dev_priv)) {
1974 kobject_put(dev_priv->perf.metrics_kobj);
1975 dev_priv->perf.metrics_kobj = NULL;
1976 }
1977
1978exit:
1979 mutex_unlock(&dev_priv->perf.lock);
1980}
1981
Robert Bragg16d98b32016-12-07 21:40:33 +00001982/**
1983 * i915_perf_unregister - hide i915-perf from userspace
1984 * @dev_priv: i915 device instance
1985 *
1986 * i915-perf state cleanup is split up into an 'unregister' and
1987 * 'deinit' phase where the interface is first hidden from
1988 * userspace by i915_perf_unregister() before cleaning up
1989 * remaining state in i915_perf_fini().
1990 */
Robert Bragg442b8c02016-11-07 19:49:53 +00001991void i915_perf_unregister(struct drm_i915_private *dev_priv)
1992{
1993 if (!IS_HASWELL(dev_priv))
1994 return;
1995
1996 if (!dev_priv->perf.metrics_kobj)
1997 return;
1998
1999 i915_perf_unregister_sysfs_hsw(dev_priv);
2000
2001 kobject_put(dev_priv->perf.metrics_kobj);
2002 dev_priv->perf.metrics_kobj = NULL;
2003}
2004
Robert Braggccdf6342016-11-07 19:49:54 +00002005static struct ctl_table oa_table[] = {
2006 {
2007 .procname = "perf_stream_paranoid",
2008 .data = &i915_perf_stream_paranoid,
2009 .maxlen = sizeof(i915_perf_stream_paranoid),
2010 .mode = 0644,
2011 .proc_handler = proc_dointvec_minmax,
2012 .extra1 = &zero,
2013 .extra2 = &one,
2014 },
Robert Bragg00319ba2016-11-07 19:49:55 +00002015 {
2016 .procname = "oa_max_sample_rate",
2017 .data = &i915_oa_max_sample_rate,
2018 .maxlen = sizeof(i915_oa_max_sample_rate),
2019 .mode = 0644,
2020 .proc_handler = proc_dointvec_minmax,
2021 .extra1 = &zero,
2022 .extra2 = &oa_sample_rate_hard_limit,
2023 },
Robert Braggccdf6342016-11-07 19:49:54 +00002024 {}
2025};
2026
2027static struct ctl_table i915_root[] = {
2028 {
2029 .procname = "i915",
2030 .maxlen = 0,
2031 .mode = 0555,
2032 .child = oa_table,
2033 },
2034 {}
2035};
2036
2037static struct ctl_table dev_root[] = {
2038 {
2039 .procname = "dev",
2040 .maxlen = 0,
2041 .mode = 0555,
2042 .child = i915_root,
2043 },
2044 {}
2045};
2046
Robert Bragg16d98b32016-12-07 21:40:33 +00002047/**
2048 * i915_perf_init - initialize i915-perf state on module load
2049 * @dev_priv: i915 device instance
2050 *
2051 * Initializes i915-perf state without exposing anything to userspace.
2052 *
2053 * Note: i915-perf initialization is split into an 'init' and 'register'
2054 * phase with the i915_perf_register() exposing state to userspace.
2055 */
Robert Braggeec688e2016-11-07 19:49:47 +00002056void i915_perf_init(struct drm_i915_private *dev_priv)
2057{
Robert Braggd7965152016-11-07 19:49:52 +00002058 if (!IS_HASWELL(dev_priv))
2059 return;
2060
2061 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
2062 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2063 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
2064 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
2065
Robert Braggeec688e2016-11-07 19:49:47 +00002066 INIT_LIST_HEAD(&dev_priv->perf.streams);
2067 mutex_init(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002068 spin_lock_init(&dev_priv->perf.hook_lock);
2069
2070 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
2071 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
2072 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
2073 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
2074 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
2075 dev_priv->perf.oa.ops.read = gen7_oa_read;
2076 dev_priv->perf.oa.ops.oa_buffer_is_empty =
2077 gen7_oa_buffer_is_empty_fop_unlocked;
2078
2079 dev_priv->perf.oa.timestamp_frequency = 12500000;
2080
2081 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
2082
2083 dev_priv->perf.oa.n_builtin_sets =
2084 i915_oa_n_builtin_metric_sets_hsw;
Robert Braggeec688e2016-11-07 19:49:47 +00002085
Robert Braggccdf6342016-11-07 19:49:54 +00002086 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
2087
Robert Braggeec688e2016-11-07 19:49:47 +00002088 dev_priv->perf.initialized = true;
2089}
2090
Robert Bragg16d98b32016-12-07 21:40:33 +00002091/**
2092 * i915_perf_fini - Counter part to i915_perf_init()
2093 * @dev_priv: i915 device instance
2094 */
Robert Braggeec688e2016-11-07 19:49:47 +00002095void i915_perf_fini(struct drm_i915_private *dev_priv)
2096{
2097 if (!dev_priv->perf.initialized)
2098 return;
2099
Robert Braggccdf6342016-11-07 19:49:54 +00002100 unregister_sysctl_table(dev_priv->perf.sysctl_header);
2101
Robert Braggd7965152016-11-07 19:49:52 +00002102 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Braggeec688e2016-11-07 19:49:47 +00002103 dev_priv->perf.initialized = false;
2104}