blob: 7e56b895fd3400f5065323e872202792c67793ae [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
Robert Bragg0dd860c2017-05-11 16:43:28 +0100208/**
209 * DOC: OA Tail Pointer Race
210 *
211 * There's a HW race condition between OA unit tail pointer register updates and
Robert Braggd7965152016-11-07 19:49:52 +0000212 * writes to memory whereby the tail pointer can sometimes get ahead of what's
Robert Bragg0dd860c2017-05-11 16:43:28 +0100213 * been written out to the OA buffer so far (in terms of what's visible to the
214 * CPU).
Robert Braggd7965152016-11-07 19:49:52 +0000215 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100216 * Although this can be observed explicitly while copying reports to userspace
217 * by checking for a zeroed report-id field in tail reports, we want to account
218 * for this earlier, as part of the _oa_buffer_check to avoid lots of redundant
219 * read() attempts.
Robert Braggd7965152016-11-07 19:49:52 +0000220 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100221 * In effect we define a tail pointer for reading that lags the real tail
222 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
223 * time for the corresponding reports to become visible to the CPU.
Robert Braggd7965152016-11-07 19:49:52 +0000224 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100225 * To manage this we actually track two tail pointers:
226 * 1) An 'aging' tail with an associated timestamp that is tracked until we
227 * can trust the corresponding data is visible to the CPU; at which point
228 * it is considered 'aged'.
229 * 2) An 'aged' tail that can be used for read()ing.
230 *
231 * The two separate pointers let us decouple read()s from tail pointer aging.
232 *
233 * The tail pointers are checked and updated at a limited rate within a hrtimer
234 * callback (the same callback that is used for delivering POLLIN events)
235 *
236 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
237 * indicates that an updated tail pointer is needed.
238 *
239 * Most of the implementation details for this workaround are in
240 * gen7_oa_buffer_check_unlocked() and gen7_appand_oa_reports()
241 *
242 * Note for posterity: previously the driver used to define an effective tail
243 * pointer that lagged the real pointer by a 'tail margin' measured in bytes
244 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
245 * This was flawed considering that the OA unit may also automatically generate
246 * non-periodic reports (such as on context switch) or the OA unit may be
247 * enabled without any periodic sampling.
Robert Braggd7965152016-11-07 19:49:52 +0000248 */
249#define OA_TAIL_MARGIN_NSEC 100000ULL
Robert Bragg0dd860c2017-05-11 16:43:28 +0100250#define INVALID_TAIL_PTR 0xffffffff
Robert Braggd7965152016-11-07 19:49:52 +0000251
252/* frequency for checking whether the OA unit has written new reports to the
253 * circular OA buffer...
254 */
255#define POLL_FREQUENCY 200
256#define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
257
Robert Braggccdf6342016-11-07 19:49:54 +0000258/* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
259static int zero;
260static int one = 1;
261static u32 i915_perf_stream_paranoid = true;
262
Robert Braggd7965152016-11-07 19:49:52 +0000263/* The maximum exponent the hardware accepts is 63 (essentially it selects one
264 * of the 64bit timestamp bits to trigger reports from) but there's currently
265 * no known use case for sampling as infrequently as once per 47 thousand years.
266 *
267 * Since the timestamps included in OA reports are only 32bits it seems
268 * reasonable to limit the OA exponent where it's still possible to account for
269 * overflow in OA report timestamps.
270 */
271#define OA_EXPONENT_MAX 31
272
273#define INVALID_CTX_ID 0xffffffff
274
275
Robert Bragg00319ba2016-11-07 19:49:55 +0000276/* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
277 *
278 * 160ns is the smallest sampling period we can theoretically program the OA
279 * unit with on Haswell, corresponding to 6.25MHz.
280 */
281static int oa_sample_rate_hard_limit = 6250000;
282
283/* Theoretically we can program the OA unit to sample every 160ns but don't
284 * allow that by default unless root...
285 *
286 * The default threshold of 100000Hz is based on perf's similar
287 * kernel.perf_event_max_sample_rate sysctl parameter.
288 */
289static u32 i915_oa_max_sample_rate = 100000;
290
Robert Braggd7965152016-11-07 19:49:52 +0000291/* XXX: beware if future OA HW adds new report formats that the current
292 * code assumes all reports have a power-of-two size and ~(size - 1) can
293 * be used as a mask to align the OA tail pointer.
294 */
295static struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
296 [I915_OA_FORMAT_A13] = { 0, 64 },
297 [I915_OA_FORMAT_A29] = { 1, 128 },
298 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
299 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
300 [I915_OA_FORMAT_B4_C8] = { 4, 64 },
301 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
302 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
303 [I915_OA_FORMAT_C4_B8] = { 7, 64 },
304};
305
306#define SAMPLE_OA_REPORT (1<<0)
Robert Braggeec688e2016-11-07 19:49:47 +0000307
Robert Bragg16d98b32016-12-07 21:40:33 +0000308/**
309 * struct perf_open_properties - for validated properties given to open a stream
310 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
311 * @single_context: Whether a single or all gpu contexts should be monitored
312 * @ctx_handle: A gem ctx handle for use with @single_context
313 * @metrics_set: An ID for an OA unit metric set advertised via sysfs
314 * @oa_format: An OA unit HW report format
315 * @oa_periodic: Whether to enable periodic OA unit sampling
316 * @oa_period_exponent: The OA unit sampling period is derived from this
317 *
318 * As read_properties_unlocked() enumerates and validates the properties given
319 * to open a stream of metrics the configuration is built up in the structure
320 * which starts out zero initialized.
321 */
Robert Braggeec688e2016-11-07 19:49:47 +0000322struct perf_open_properties {
323 u32 sample_flags;
324
325 u64 single_context:1;
326 u64 ctx_handle;
Robert Braggd7965152016-11-07 19:49:52 +0000327
328 /* OA sampling state */
329 int metrics_set;
330 int oa_format;
331 bool oa_periodic;
332 int oa_period_exponent;
Robert Braggeec688e2016-11-07 19:49:47 +0000333};
334
Robert Bragg0dd860c2017-05-11 16:43:28 +0100335/**
336 * gen7_oa_buffer_check_unlocked - check for data and update tail ptr state
337 * @dev_priv: i915 device instance
Robert Braggd7965152016-11-07 19:49:52 +0000338 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100339 * This is either called via fops (for blocking reads in user ctx) or the poll
340 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
341 * if there is data available for userspace to read.
Robert Braggd7965152016-11-07 19:49:52 +0000342 *
Robert Bragg0dd860c2017-05-11 16:43:28 +0100343 * This function is central to providing a workaround for the OA unit tail
344 * pointer having a race with respect to what data is visible to the CPU.
345 * It is responsible for reading tail pointers from the hardware and giving
346 * the pointers time to 'age' before they are made available for reading.
347 * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
348 *
349 * Besides returning true when there is data available to read() this function
350 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
351 * and .aged_tail_idx state used for reading.
352 *
353 * Note: It's safe to read OA config state here unlocked, assuming that this is
354 * only called while the stream is enabled, while the global OA configuration
355 * can't be modified.
356 *
357 * Returns: %true if the OA buffer contains data, else %false
Robert Braggd7965152016-11-07 19:49:52 +0000358 */
Robert Bragg0dd860c2017-05-11 16:43:28 +0100359static bool gen7_oa_buffer_check_unlocked(struct drm_i915_private *dev_priv)
Robert Braggd7965152016-11-07 19:49:52 +0000360{
361 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100362 unsigned long flags;
363 unsigned int aged_idx;
364 u32 oastatus1;
365 u32 head, hw_tail, aged_tail, aging_tail;
366 u64 now;
Robert Braggd7965152016-11-07 19:49:52 +0000367
Robert Bragg0dd860c2017-05-11 16:43:28 +0100368 /* We have to consider the (unlikely) possibility that read() errors
369 * could result in an OA buffer reset which might reset the head,
370 * tails[] and aged_tail state.
371 */
372 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
373
374 /* NB: The head we observe here might effectively be a little out of
375 * date (between head and tails[aged_idx].offset if there is currently
376 * a read() in progress.
377 */
378 head = dev_priv->perf.oa.oa_buffer.head;
379
380 aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
381 aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset;
382 aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset;
383
384 oastatus1 = I915_READ(GEN7_OASTATUS1);
385 hw_tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
386
387 /* The tail pointer increases in 64 byte increments,
388 * not in report_size steps...
389 */
390 hw_tail &= ~(report_size - 1);
391
392 now = ktime_get_mono_fast_ns();
393
Robert Bragg4117ebc2017-05-11 16:43:30 +0100394 /* Update the aged tail
395 *
396 * Flip the tail pointer available for read()s once the aging tail is
397 * old enough to trust that the corresponding data will be visible to
398 * the CPU...
399 *
400 * Do this before updating the aging pointer in case we may be able to
401 * immediately start aging a new pointer too (if new data has become
402 * available) without needing to wait for a later hrtimer callback.
403 */
404 if (aging_tail != INVALID_TAIL_PTR &&
405 ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) >
406 OA_TAIL_MARGIN_NSEC)) {
407 aged_idx ^= 1;
408 dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx;
409
410 aged_tail = aging_tail;
411
412 /* Mark that we need a new pointer to start aging... */
413 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
414 aging_tail = INVALID_TAIL_PTR;
415 }
416
Robert Bragg0dd860c2017-05-11 16:43:28 +0100417 /* Update the aging tail
418 *
419 * We throttle aging tail updates until we have a new tail that
420 * represents >= one report more data than is already available for
421 * reading. This ensures there will be enough data for a successful
422 * read once this new pointer has aged and ensures we will give the new
423 * pointer time to age.
424 */
425 if (aging_tail == INVALID_TAIL_PTR &&
426 (aged_tail == INVALID_TAIL_PTR ||
427 OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
428 struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma;
429 u32 gtt_offset = i915_ggtt_offset(vma);
430
431 /* Be paranoid and do a bounds check on the pointer read back
432 * from hardware, just in case some spurious hardware condition
433 * could put the tail out of bounds...
434 */
435 if (hw_tail >= gtt_offset &&
436 hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
437 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset =
438 aging_tail = hw_tail;
439 dev_priv->perf.oa.oa_buffer.aging_timestamp = now;
440 } else {
441 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
442 hw_tail);
443 }
444 }
445
Robert Bragg0dd860c2017-05-11 16:43:28 +0100446 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
447
448 return aged_tail == INVALID_TAIL_PTR ?
449 false : OA_TAKEN(aged_tail, head) >= report_size;
Robert Braggd7965152016-11-07 19:49:52 +0000450}
451
452/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000453 * append_oa_status - Appends a status record to a userspace read() buffer.
454 * @stream: An i915-perf stream opened for OA metrics
455 * @buf: destination buffer given by userspace
456 * @count: the number of bytes userspace wants to read
457 * @offset: (inout): the current position for writing into @buf
458 * @type: The kind of status to report to userspace
459 *
460 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
461 * into the userspace read() buffer.
462 *
463 * The @buf @offset will only be updated on success.
464 *
465 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000466 */
467static int append_oa_status(struct i915_perf_stream *stream,
468 char __user *buf,
469 size_t count,
470 size_t *offset,
471 enum drm_i915_perf_record_type type)
472{
473 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
474
475 if ((count - *offset) < header.size)
476 return -ENOSPC;
477
478 if (copy_to_user(buf + *offset, &header, sizeof(header)))
479 return -EFAULT;
480
481 (*offset) += header.size;
482
483 return 0;
484}
485
486/**
Robert Bragg16d98b32016-12-07 21:40:33 +0000487 * append_oa_sample - Copies single OA report into userspace read() buffer.
488 * @stream: An i915-perf stream opened for OA metrics
489 * @buf: destination buffer given by userspace
490 * @count: the number of bytes userspace wants to read
491 * @offset: (inout): the current position for writing into @buf
492 * @report: A single OA report to (optionally) include as part of the sample
493 *
494 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
495 * properties when opening a stream, tracked as `stream->sample_flags`. This
496 * function copies the requested components of a single sample to the given
497 * read() @buf.
498 *
499 * The @buf @offset will only be updated on success.
500 *
501 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000502 */
503static int append_oa_sample(struct i915_perf_stream *stream,
504 char __user *buf,
505 size_t count,
506 size_t *offset,
507 const u8 *report)
508{
509 struct drm_i915_private *dev_priv = stream->dev_priv;
510 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
511 struct drm_i915_perf_record_header header;
512 u32 sample_flags = stream->sample_flags;
513
514 header.type = DRM_I915_PERF_RECORD_SAMPLE;
515 header.pad = 0;
516 header.size = stream->sample_size;
517
518 if ((count - *offset) < header.size)
519 return -ENOSPC;
520
521 buf += *offset;
522 if (copy_to_user(buf, &header, sizeof(header)))
523 return -EFAULT;
524 buf += sizeof(header);
525
526 if (sample_flags & SAMPLE_OA_REPORT) {
527 if (copy_to_user(buf, report, report_size))
528 return -EFAULT;
529 }
530
531 (*offset) += header.size;
532
533 return 0;
534}
535
536/**
537 * Copies all buffered OA reports into userspace read() buffer.
538 * @stream: An i915-perf stream opened for OA metrics
539 * @buf: destination buffer given by userspace
540 * @count: the number of bytes userspace wants to read
541 * @offset: (inout): the current position for writing into @buf
Robert Braggd7965152016-11-07 19:49:52 +0000542 *
Robert Bragg16d98b32016-12-07 21:40:33 +0000543 * Notably any error condition resulting in a short read (-%ENOSPC or
544 * -%EFAULT) will be returned even though one or more records may
Robert Braggd7965152016-11-07 19:49:52 +0000545 * have been successfully copied. In this case it's up to the caller
546 * to decide if the error should be squashed before returning to
547 * userspace.
548 *
549 * Note: reports are consumed from the head, and appended to the
Robert Bragge81b3a52017-05-11 16:43:24 +0100550 * tail, so the tail chases the head?... If you think that's mad
Robert Braggd7965152016-11-07 19:49:52 +0000551 * and back-to-front you're not alone, but this follows the
552 * Gen PRM naming convention.
Robert Bragg16d98b32016-12-07 21:40:33 +0000553 *
554 * Returns: 0 on success, negative error code on failure.
Robert Braggd7965152016-11-07 19:49:52 +0000555 */
556static int gen7_append_oa_reports(struct i915_perf_stream *stream,
557 char __user *buf,
558 size_t count,
Robert Bragg3bb335c2017-05-11 16:43:27 +0100559 size_t *offset)
Robert Braggd7965152016-11-07 19:49:52 +0000560{
561 struct drm_i915_private *dev_priv = stream->dev_priv;
562 int report_size = dev_priv->perf.oa.oa_buffer.format_size;
563 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
Robert Braggd7965152016-11-07 19:49:52 +0000564 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
565 u32 mask = (OA_BUFFER_SIZE - 1);
Robert Bragg3bb335c2017-05-11 16:43:27 +0100566 size_t start_offset = *offset;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100567 unsigned long flags;
568 unsigned int aged_tail_idx;
569 u32 head, tail;
Robert Braggd7965152016-11-07 19:49:52 +0000570 u32 taken;
571 int ret = 0;
572
573 if (WARN_ON(!stream->enabled))
574 return -EIO;
575
Robert Bragg0dd860c2017-05-11 16:43:28 +0100576 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggf2790202017-05-11 16:43:26 +0100577
Robert Bragg0dd860c2017-05-11 16:43:28 +0100578 head = dev_priv->perf.oa.oa_buffer.head;
579 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
580 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
581
582 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
583
584 /* An invalid tail pointer here means we're still waiting for the poll
585 * hrtimer callback to give us a pointer
Robert Braggf2790202017-05-11 16:43:26 +0100586 */
Robert Bragg0dd860c2017-05-11 16:43:28 +0100587 if (tail == INVALID_TAIL_PTR)
Robert Braggd7965152016-11-07 19:49:52 +0000588 return -EAGAIN;
589
Robert Bragg0dd860c2017-05-11 16:43:28 +0100590 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
591 * while indexing relative to oa_buf_base.
592 */
593 head -= gtt_offset;
594 tail -= gtt_offset;
595
596 /* An out of bounds or misaligned head or tail pointer implies a driver
597 * bug since we validate + align the tail pointers we read from the
598 * hardware and we are in full control of the head pointer which should
599 * only be incremented by multiples of the report size (notably also
600 * all a power of two).
601 */
602 if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
603 tail > OA_BUFFER_SIZE || tail % report_size,
604 "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
605 head, tail))
606 return -EIO;
607
Robert Braggd7965152016-11-07 19:49:52 +0000608
609 for (/* none */;
610 (taken = OA_TAKEN(tail, head));
611 head = (head + report_size) & mask) {
612 u8 *report = oa_buf_base + head;
613 u32 *report32 = (void *)report;
614
615 /* All the report sizes factor neatly into the buffer
616 * size so we never expect to see a report split
617 * between the beginning and end of the buffer.
618 *
619 * Given the initial alignment check a misalignment
620 * here would imply a driver bug that would result
621 * in an overrun.
622 */
623 if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
624 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
625 break;
626 }
627
628 /* The report-ID field for periodic samples includes
629 * some undocumented flags related to what triggered
630 * the report and is never expected to be zero so we
631 * can check that the report isn't invalid before
632 * copying it to userspace...
633 */
634 if (report32[0] == 0) {
Robert Bragg712122e2017-05-11 16:43:31 +0100635 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
636 DRM_NOTE("Skipping spurious, invalid OA report\n");
Robert Braggd7965152016-11-07 19:49:52 +0000637 continue;
638 }
639
640 ret = append_oa_sample(stream, buf, count, offset, report);
641 if (ret)
642 break;
643
644 /* The above report-id field sanity check is based on
645 * the assumption that the OA buffer is initially
646 * zeroed and we reset the field after copying so the
647 * check is still meaningful once old reports start
648 * being overwritten.
649 */
650 report32[0] = 0;
651 }
652
Robert Bragg3bb335c2017-05-11 16:43:27 +0100653 if (start_offset != *offset) {
Robert Bragg0dd860c2017-05-11 16:43:28 +0100654 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
655
Robert Bragg3bb335c2017-05-11 16:43:27 +0100656 /* We removed the gtt_offset for the copy loop above, indexing
657 * relative to oa_buf_base so put back here...
658 */
659 head += gtt_offset;
660
661 I915_WRITE(GEN7_OASTATUS2,
662 ((head & GEN7_OASTATUS2_HEAD_MASK) |
663 OA_MEM_SELECT_GGTT));
664 dev_priv->perf.oa.oa_buffer.head = head;
Robert Bragg0dd860c2017-05-11 16:43:28 +0100665
666 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Bragg3bb335c2017-05-11 16:43:27 +0100667 }
Robert Braggd7965152016-11-07 19:49:52 +0000668
669 return ret;
670}
671
Robert Bragg16d98b32016-12-07 21:40:33 +0000672/**
673 * gen7_oa_read - copy status records then buffered OA reports
674 * @stream: An i915-perf stream opened for OA metrics
675 * @buf: destination buffer given by userspace
676 * @count: the number of bytes userspace wants to read
677 * @offset: (inout): the current position for writing into @buf
678 *
679 * Checks Gen 7 specific OA unit status registers and if necessary appends
680 * corresponding status records for userspace (such as for a buffer full
681 * condition) and then initiate appending any buffered OA reports.
682 *
683 * Updates @offset according to the number of bytes successfully copied into
684 * the userspace buffer.
685 *
686 * Returns: zero on success or a negative error code
687 */
Robert Braggd7965152016-11-07 19:49:52 +0000688static int gen7_oa_read(struct i915_perf_stream *stream,
689 char __user *buf,
690 size_t count,
691 size_t *offset)
692{
693 struct drm_i915_private *dev_priv = stream->dev_priv;
Robert Braggd7965152016-11-07 19:49:52 +0000694 u32 oastatus1;
Robert Braggd7965152016-11-07 19:49:52 +0000695 int ret;
696
697 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
698 return -EIO;
699
Robert Braggd7965152016-11-07 19:49:52 +0000700 oastatus1 = I915_READ(GEN7_OASTATUS1);
701
Robert Braggd7965152016-11-07 19:49:52 +0000702 /* XXX: On Haswell we don't have a safe way to clear oastatus1
703 * bits while the OA unit is enabled (while the tail pointer
704 * may be updated asynchronously) so we ignore status bits
705 * that have already been reported to userspace.
706 */
707 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
708
709 /* We treat OABUFFER_OVERFLOW as a significant error:
710 *
711 * - The status can be interpreted to mean that the buffer is
712 * currently full (with a higher precedence than OA_TAKEN()
713 * which will start to report a near-empty buffer after an
714 * overflow) but it's awkward that we can't clear the status
715 * on Haswell, so without a reset we won't be able to catch
716 * the state again.
717 *
718 * - Since it also implies the HW has started overwriting old
719 * reports it may also affect our sanity checks for invalid
720 * reports when copying to userspace that assume new reports
721 * are being written to cleared memory.
722 *
723 * - In the future we may want to introduce a flight recorder
724 * mode where the driver will automatically maintain a safe
725 * guard band between head/tail, avoiding this overflow
726 * condition, but we avoid the added driver complexity for
727 * now.
728 */
729 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
730 ret = append_oa_status(stream, buf, count, offset,
731 DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
732 if (ret)
733 return ret;
734
Robert Bragg77085502016-12-01 17:21:52 +0000735 DRM_DEBUG("OA buffer overflow: force restart\n");
Robert Braggd7965152016-11-07 19:49:52 +0000736
737 dev_priv->perf.oa.ops.oa_disable(dev_priv);
738 dev_priv->perf.oa.ops.oa_enable(dev_priv);
739
Robert Braggd7965152016-11-07 19:49:52 +0000740 oastatus1 = I915_READ(GEN7_OASTATUS1);
Robert Braggd7965152016-11-07 19:49:52 +0000741 }
742
743 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
744 ret = append_oa_status(stream, buf, count, offset,
745 DRM_I915_PERF_RECORD_OA_REPORT_LOST);
746 if (ret)
747 return ret;
748 dev_priv->perf.oa.gen7_latched_oastatus1 |=
749 GEN7_OASTATUS1_REPORT_LOST;
750 }
751
Robert Bragg3bb335c2017-05-11 16:43:27 +0100752 return gen7_append_oa_reports(stream, buf, count, offset);
Robert Braggd7965152016-11-07 19:49:52 +0000753}
754
Robert Bragg16d98b32016-12-07 21:40:33 +0000755/**
756 * i915_oa_wait_unlocked - handles blocking IO until OA data available
757 * @stream: An i915-perf stream opened for OA metrics
758 *
759 * Called when userspace tries to read() from a blocking stream FD opened
760 * for OA metrics. It waits until the hrtimer callback finds a non-empty
761 * OA buffer and wakes us.
762 *
763 * Note: it's acceptable to have this return with some false positives
764 * since any subsequent read handling will return -EAGAIN if there isn't
765 * really data ready for userspace yet.
766 *
767 * Returns: zero on success or a negative error code
768 */
Robert Braggd7965152016-11-07 19:49:52 +0000769static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
770{
771 struct drm_i915_private *dev_priv = stream->dev_priv;
772
773 /* We would wait indefinitely if periodic sampling is not enabled */
774 if (!dev_priv->perf.oa.periodic)
775 return -EIO;
776
Robert Braggd7965152016-11-07 19:49:52 +0000777 return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
Robert Bragg0dd860c2017-05-11 16:43:28 +0100778 dev_priv->perf.oa.ops.oa_buffer_check(dev_priv));
Robert Braggd7965152016-11-07 19:49:52 +0000779}
780
Robert Bragg16d98b32016-12-07 21:40:33 +0000781/**
782 * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
783 * @stream: An i915-perf stream opened for OA metrics
784 * @file: An i915 perf stream file
785 * @wait: poll() state table
786 *
787 * For handling userspace polling on an i915 perf stream opened for OA metrics,
788 * this starts a poll_wait with the wait queue that our hrtimer callback wakes
789 * when it sees data ready to read in the circular OA buffer.
790 */
Robert Braggd7965152016-11-07 19:49:52 +0000791static void i915_oa_poll_wait(struct i915_perf_stream *stream,
792 struct file *file,
793 poll_table *wait)
794{
795 struct drm_i915_private *dev_priv = stream->dev_priv;
796
797 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
798}
799
Robert Bragg16d98b32016-12-07 21:40:33 +0000800/**
801 * i915_oa_read - just calls through to &i915_oa_ops->read
802 * @stream: An i915-perf stream opened for OA metrics
803 * @buf: destination buffer given by userspace
804 * @count: the number of bytes userspace wants to read
805 * @offset: (inout): the current position for writing into @buf
806 *
807 * Updates @offset according to the number of bytes successfully copied into
808 * the userspace buffer.
809 *
810 * Returns: zero on success or a negative error code
811 */
Robert Braggd7965152016-11-07 19:49:52 +0000812static int i915_oa_read(struct i915_perf_stream *stream,
813 char __user *buf,
814 size_t count,
815 size_t *offset)
816{
817 struct drm_i915_private *dev_priv = stream->dev_priv;
818
819 return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
820}
821
Robert Bragg16d98b32016-12-07 21:40:33 +0000822/**
823 * oa_get_render_ctx_id - determine and hold ctx hw id
824 * @stream: An i915-perf stream opened for OA metrics
825 *
826 * Determine the render context hw id, and ensure it remains fixed for the
Robert Braggd7965152016-11-07 19:49:52 +0000827 * lifetime of the stream. This ensures that we don't have to worry about
828 * updating the context ID in OACONTROL on the fly.
Robert Bragg16d98b32016-12-07 21:40:33 +0000829 *
830 * Returns: zero on success or a negative error code
Robert Braggd7965152016-11-07 19:49:52 +0000831 */
832static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
833{
834 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000835 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Chris Wilson266a2402017-05-04 10:33:08 +0100836 struct intel_ring *ring;
Robert Braggd7965152016-11-07 19:49:52 +0000837 int ret;
838
839 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
840 if (ret)
841 return ret;
842
843 /* As the ID is the gtt offset of the context's vma we pin
844 * the vma to ensure the ID remains fixed.
845 *
846 * NB: implied RCS engine...
847 */
Chris Wilson266a2402017-05-04 10:33:08 +0100848 ring = engine->context_pin(engine, stream->ctx);
849 mutex_unlock(&dev_priv->drm.struct_mutex);
850 if (IS_ERR(ring))
851 return PTR_ERR(ring);
Robert Braggd7965152016-11-07 19:49:52 +0000852
853 /* Explicitly track the ID (instead of calling i915_ggtt_offset()
854 * on the fly) considering the difference with gen8+ and
855 * execlists
856 */
Chris Wilsone8a9c582016-12-18 15:37:20 +0000857 dev_priv->perf.oa.specific_ctx_id =
858 i915_ggtt_offset(stream->ctx->engine[engine->id].state);
Robert Braggd7965152016-11-07 19:49:52 +0000859
Chris Wilson266a2402017-05-04 10:33:08 +0100860 return 0;
Robert Braggd7965152016-11-07 19:49:52 +0000861}
862
Robert Bragg16d98b32016-12-07 21:40:33 +0000863/**
864 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
865 * @stream: An i915-perf stream opened for OA metrics
866 *
867 * In case anything needed doing to ensure the context HW ID would remain valid
868 * for the lifetime of the stream, then that can be undone here.
869 */
Robert Braggd7965152016-11-07 19:49:52 +0000870static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
871{
872 struct drm_i915_private *dev_priv = stream->dev_priv;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000873 struct intel_engine_cs *engine = dev_priv->engine[RCS];
Robert Braggd7965152016-11-07 19:49:52 +0000874
875 mutex_lock(&dev_priv->drm.struct_mutex);
876
Robert Braggd7965152016-11-07 19:49:52 +0000877 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
Chris Wilsone8a9c582016-12-18 15:37:20 +0000878 engine->context_unpin(engine, stream->ctx);
Robert Braggd7965152016-11-07 19:49:52 +0000879
880 mutex_unlock(&dev_priv->drm.struct_mutex);
881}
882
883static void
884free_oa_buffer(struct drm_i915_private *i915)
885{
886 mutex_lock(&i915->drm.struct_mutex);
887
888 i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
889 i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
890 i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
891
892 i915->perf.oa.oa_buffer.vma = NULL;
893 i915->perf.oa.oa_buffer.vaddr = NULL;
894
895 mutex_unlock(&i915->drm.struct_mutex);
896}
897
898static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
899{
900 struct drm_i915_private *dev_priv = stream->dev_priv;
901
902 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
903
904 dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
905
906 free_oa_buffer(dev_priv);
907
908 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
909 intel_runtime_pm_put(dev_priv);
910
911 if (stream->ctx)
912 oa_put_render_ctx_id(stream);
913
914 dev_priv->perf.oa.exclusive_stream = NULL;
Robert Bragg712122e2017-05-11 16:43:31 +0100915
916 if (dev_priv->perf.oa.spurious_report_rs.missed) {
917 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
918 dev_priv->perf.oa.spurious_report_rs.missed);
919 }
Robert Braggd7965152016-11-07 19:49:52 +0000920}
921
922static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
923{
924 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
Robert Bragg0dd860c2017-05-11 16:43:28 +0100925 unsigned long flags;
926
927 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
Robert Braggd7965152016-11-07 19:49:52 +0000928
929 /* Pre-DevBDW: OABUFFER must be set with counters off,
930 * before OASTATUS1, but after OASTATUS2
931 */
932 I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
Robert Braggf2790202017-05-11 16:43:26 +0100933 dev_priv->perf.oa.oa_buffer.head = gtt_offset;
934
Robert Braggd7965152016-11-07 19:49:52 +0000935 I915_WRITE(GEN7_OABUFFER, gtt_offset);
Robert Braggf2790202017-05-11 16:43:26 +0100936
Robert Braggd7965152016-11-07 19:49:52 +0000937 I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
938
Robert Bragg0dd860c2017-05-11 16:43:28 +0100939 /* Mark that we need updated tail pointers to read from... */
940 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
941 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
942
943 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
944
Robert Braggd7965152016-11-07 19:49:52 +0000945 /* On Haswell we have to track which OASTATUS1 flags we've
946 * already seen since they can't be cleared while periodic
947 * sampling is enabled.
948 */
949 dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
950
951 /* NB: although the OA buffer will initially be allocated
952 * zeroed via shmfs (and so this memset is redundant when
953 * first allocating), we may re-init the OA buffer, either
954 * when re-enabling a stream or in error/reset paths.
955 *
956 * The reason we clear the buffer for each re-init is for the
957 * sanity check in gen7_append_oa_reports() that looks at the
958 * report-id field to make sure it's non-zero which relies on
959 * the assumption that new reports are being written to zeroed
960 * memory...
961 */
962 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
963
964 /* Maybe make ->pollin per-stream state if we support multiple
965 * concurrent streams in the future.
966 */
967 dev_priv->perf.oa.pollin = false;
968}
969
970static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
971{
972 struct drm_i915_gem_object *bo;
973 struct i915_vma *vma;
974 int ret;
975
976 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
977 return -ENODEV;
978
979 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
980 if (ret)
981 return ret;
982
983 BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
984 BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
985
Tvrtko Ursulin12d79d72016-12-01 14:16:37 +0000986 bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
Robert Braggd7965152016-11-07 19:49:52 +0000987 if (IS_ERR(bo)) {
988 DRM_ERROR("Failed to allocate OA buffer\n");
989 ret = PTR_ERR(bo);
990 goto unlock;
991 }
992
993 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
994 if (ret)
995 goto err_unref;
996
997 /* PreHSW required 512K alignment, HSW requires 16M */
998 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
999 if (IS_ERR(vma)) {
1000 ret = PTR_ERR(vma);
1001 goto err_unref;
1002 }
1003 dev_priv->perf.oa.oa_buffer.vma = vma;
1004
1005 dev_priv->perf.oa.oa_buffer.vaddr =
1006 i915_gem_object_pin_map(bo, I915_MAP_WB);
1007 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
1008 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
1009 goto err_unpin;
1010 }
1011
1012 dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
1013
1014 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
1015 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
1016 dev_priv->perf.oa.oa_buffer.vaddr);
1017
1018 goto unlock;
1019
1020err_unpin:
1021 __i915_vma_unpin(vma);
1022
1023err_unref:
1024 i915_gem_object_put(bo);
1025
1026 dev_priv->perf.oa.oa_buffer.vaddr = NULL;
1027 dev_priv->perf.oa.oa_buffer.vma = NULL;
1028
1029unlock:
1030 mutex_unlock(&dev_priv->drm.struct_mutex);
1031 return ret;
1032}
1033
1034static void config_oa_regs(struct drm_i915_private *dev_priv,
1035 const struct i915_oa_reg *regs,
1036 int n_regs)
1037{
1038 int i;
1039
1040 for (i = 0; i < n_regs; i++) {
1041 const struct i915_oa_reg *reg = regs + i;
1042
1043 I915_WRITE(reg->addr, reg->value);
1044 }
1045}
1046
1047static int hsw_enable_metric_set(struct drm_i915_private *dev_priv)
1048{
1049 int ret = i915_oa_select_metric_set_hsw(dev_priv);
Lionel Landwerlin3f488d92017-06-13 12:23:01 +01001050 int i;
Robert Braggd7965152016-11-07 19:49:52 +00001051
1052 if (ret)
1053 return ret;
1054
1055 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) |
1056 GT_NOA_ENABLE));
1057
1058 /* PRM:
1059 *
1060 * OA unit is using “crclk” for its functionality. When trunk
1061 * level clock gating takes place, OA clock would be gated,
1062 * unable to count the events from non-render clock domain.
1063 * Render clock gating must be disabled when OA is enabled to
1064 * count the events from non-render domain. Unit level clock
1065 * gating for RCS should also be disabled.
1066 */
1067 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1068 ~GEN7_DOP_CLOCK_GATE_ENABLE));
1069 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
1070 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1071
Lionel Landwerlin3f488d92017-06-13 12:23:01 +01001072 for (i = 0; i < dev_priv->perf.oa.n_mux_configs; i++) {
1073 config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs[i],
1074 dev_priv->perf.oa.mux_regs_lens[i]);
1075 }
Robert Braggd7965152016-11-07 19:49:52 +00001076
1077 /* It apparently takes a fairly long time for a new MUX
1078 * configuration to be be applied after these register writes.
1079 * This delay duration was derived empirically based on the
1080 * render_basic config but hopefully it covers the maximum
1081 * configuration latency.
1082 *
1083 * As a fallback, the checks in _append_oa_reports() to skip
1084 * invalid OA reports do also seem to work to discard reports
1085 * generated before this config has completed - albeit not
1086 * silently.
1087 *
1088 * Unfortunately this is essentially a magic number, since we
1089 * don't currently know of a reliable mechanism for predicting
1090 * how long the MUX config will take to apply and besides
1091 * seeing invalid reports we don't know of a reliable way to
1092 * explicitly check that the MUX config has landed.
1093 *
1094 * It's even possible we've miss characterized the underlying
1095 * problem - it just seems like the simplest explanation why
1096 * a delay at this location would mitigate any invalid reports.
1097 */
1098 usleep_range(15000, 20000);
1099
1100 config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
1101 dev_priv->perf.oa.b_counter_regs_len);
1102
1103 return 0;
1104}
1105
1106static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
1107{
1108 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
1109 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1110 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
1111 GEN7_DOP_CLOCK_GATE_ENABLE));
1112
1113 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1114 ~GT_NOA_ENABLE));
1115}
1116
1117static void gen7_update_oacontrol_locked(struct drm_i915_private *dev_priv)
1118{
Chris Wilson67520412017-03-02 13:28:01 +00001119 lockdep_assert_held(&dev_priv->perf.hook_lock);
Robert Braggd7965152016-11-07 19:49:52 +00001120
1121 if (dev_priv->perf.oa.exclusive_stream->enabled) {
1122 struct i915_gem_context *ctx =
1123 dev_priv->perf.oa.exclusive_stream->ctx;
1124 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1125
1126 bool periodic = dev_priv->perf.oa.periodic;
1127 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1128 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1129
1130 I915_WRITE(GEN7_OACONTROL,
1131 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1132 (period_exponent <<
1133 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1134 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1135 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1136 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1137 GEN7_OACONTROL_ENABLE);
1138 } else
1139 I915_WRITE(GEN7_OACONTROL, 0);
1140}
1141
1142static void gen7_oa_enable(struct drm_i915_private *dev_priv)
1143{
1144 unsigned long flags;
1145
1146 /* Reset buf pointers so we don't forward reports from before now.
1147 *
1148 * Think carefully if considering trying to avoid this, since it
1149 * also ensures status flags and the buffer itself are cleared
1150 * in error paths, and we have checks for invalid reports based
1151 * on the assumption that certain fields are written to zeroed
1152 * memory which this helps maintains.
1153 */
1154 gen7_init_oa_buffer(dev_priv);
1155
1156 spin_lock_irqsave(&dev_priv->perf.hook_lock, flags);
1157 gen7_update_oacontrol_locked(dev_priv);
1158 spin_unlock_irqrestore(&dev_priv->perf.hook_lock, flags);
1159}
1160
Robert Bragg16d98b32016-12-07 21:40:33 +00001161/**
1162 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1163 * @stream: An i915 perf stream opened for OA metrics
1164 *
1165 * [Re]enables hardware periodic sampling according to the period configured
1166 * when opening the stream. This also starts a hrtimer that will periodically
1167 * check for data in the circular OA buffer for notifying userspace (e.g.
1168 * during a read() or poll()).
1169 */
Robert Braggd7965152016-11-07 19:49:52 +00001170static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1171{
1172 struct drm_i915_private *dev_priv = stream->dev_priv;
1173
1174 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1175
1176 if (dev_priv->perf.oa.periodic)
1177 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1178 ns_to_ktime(POLL_PERIOD),
1179 HRTIMER_MODE_REL_PINNED);
1180}
1181
1182static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1183{
1184 I915_WRITE(GEN7_OACONTROL, 0);
1185}
1186
Robert Bragg16d98b32016-12-07 21:40:33 +00001187/**
1188 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1189 * @stream: An i915 perf stream opened for OA metrics
1190 *
1191 * Stops the OA unit from periodically writing counter reports into the
1192 * circular OA buffer. This also stops the hrtimer that periodically checks for
1193 * data in the circular OA buffer, for notifying userspace.
1194 */
Robert Braggd7965152016-11-07 19:49:52 +00001195static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1196{
1197 struct drm_i915_private *dev_priv = stream->dev_priv;
1198
1199 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1200
1201 if (dev_priv->perf.oa.periodic)
1202 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1203}
1204
Robert Braggd7965152016-11-07 19:49:52 +00001205static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1206 .destroy = i915_oa_stream_destroy,
1207 .enable = i915_oa_stream_enable,
1208 .disable = i915_oa_stream_disable,
1209 .wait_unlocked = i915_oa_wait_unlocked,
1210 .poll_wait = i915_oa_poll_wait,
1211 .read = i915_oa_read,
1212};
1213
Robert Bragg16d98b32016-12-07 21:40:33 +00001214/**
1215 * i915_oa_stream_init - validate combined props for OA stream and init
1216 * @stream: An i915 perf stream
1217 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1218 * @props: The property state that configures stream (individually validated)
1219 *
1220 * While read_properties_unlocked() validates properties in isolation it
1221 * doesn't ensure that the combination necessarily makes sense.
1222 *
1223 * At this point it has been determined that userspace wants a stream of
1224 * OA metrics, but still we need to further validate the combined
1225 * properties are OK.
1226 *
1227 * If the configuration makes sense then we can allocate memory for
1228 * a circular OA buffer and apply the requested metric set configuration.
1229 *
1230 * Returns: zero on success or a negative error code.
1231 */
Robert Braggd7965152016-11-07 19:49:52 +00001232static int i915_oa_stream_init(struct i915_perf_stream *stream,
1233 struct drm_i915_perf_open_param *param,
1234 struct perf_open_properties *props)
1235{
1236 struct drm_i915_private *dev_priv = stream->dev_priv;
1237 int format_size;
1238 int ret;
1239
Robert Bragg442b8c02016-11-07 19:49:53 +00001240 /* If the sysfs metrics/ directory wasn't registered for some
1241 * reason then don't let userspace try their luck with config
1242 * IDs
1243 */
1244 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00001245 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00001246 return -EINVAL;
1247 }
1248
Robert Braggd7965152016-11-07 19:49:52 +00001249 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00001250 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001251 return -EINVAL;
1252 }
1253
1254 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
Robert Bragg77085502016-12-01 17:21:52 +00001255 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001256 return -ENODEV;
1257 }
1258
1259 /* To avoid the complexity of having to accurately filter
1260 * counter reports and marshal to the appropriate client
1261 * we currently only allow exclusive access
1262 */
1263 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00001264 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00001265 return -EBUSY;
1266 }
1267
1268 if (!props->metrics_set) {
Robert Bragg77085502016-12-01 17:21:52 +00001269 DRM_DEBUG("OA metric set not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001270 return -EINVAL;
1271 }
1272
1273 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00001274 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001275 return -EINVAL;
1276 }
1277
Robert Bragg712122e2017-05-11 16:43:31 +01001278 /* We set up some ratelimit state to potentially throttle any _NOTES
1279 * about spurious, invalid OA reports which we don't forward to
1280 * userspace.
1281 *
1282 * The initialization is associated with opening the stream (not driver
1283 * init) considering we print a _NOTE about any throttling when closing
1284 * the stream instead of waiting until driver _fini which no one would
1285 * ever see.
1286 *
1287 * Using the same limiting factors as printk_ratelimit()
1288 */
1289 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
1290 5 * HZ, 10);
1291 /* Since we use a DRM_NOTE for spurious reports it would be
1292 * inconsistent to let __ratelimit() automatically print a warning for
1293 * throttling.
1294 */
1295 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
1296 RATELIMIT_MSG_ON_RELEASE);
1297
Robert Braggd7965152016-11-07 19:49:52 +00001298 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
1299
1300 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
1301
1302 stream->sample_flags |= SAMPLE_OA_REPORT;
1303 stream->sample_size += format_size;
1304
1305 dev_priv->perf.oa.oa_buffer.format_size = format_size;
1306 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
1307 return -EINVAL;
1308
1309 dev_priv->perf.oa.oa_buffer.format =
1310 dev_priv->perf.oa.oa_formats[props->oa_format].format;
1311
1312 dev_priv->perf.oa.metrics_set = props->metrics_set;
1313
1314 dev_priv->perf.oa.periodic = props->oa_periodic;
Robert Bragg0dd860c2017-05-11 16:43:28 +01001315 if (dev_priv->perf.oa.periodic)
Robert Braggd7965152016-11-07 19:49:52 +00001316 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
1317
Robert Braggd7965152016-11-07 19:49:52 +00001318 if (stream->ctx) {
1319 ret = oa_get_render_ctx_id(stream);
1320 if (ret)
1321 return ret;
1322 }
1323
1324 ret = alloc_oa_buffer(dev_priv);
1325 if (ret)
1326 goto err_oa_buf_alloc;
1327
1328 /* PRM - observability performance counters:
1329 *
1330 * OACONTROL, performance counter enable, note:
1331 *
1332 * "When this bit is set, in order to have coherent counts,
1333 * RC6 power state and trunk clock gating must be disabled.
1334 * This can be achieved by programming MMIO registers as
1335 * 0xA094=0 and 0xA090[31]=1"
1336 *
1337 * In our case we are expecting that taking pm + FORCEWAKE
1338 * references will effectively disable RC6.
1339 */
1340 intel_runtime_pm_get(dev_priv);
1341 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
1342
1343 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv);
1344 if (ret)
1345 goto err_enable;
1346
1347 stream->ops = &i915_oa_stream_ops;
1348
1349 dev_priv->perf.oa.exclusive_stream = stream;
1350
1351 return 0;
1352
1353err_enable:
1354 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1355 intel_runtime_pm_put(dev_priv);
1356 free_oa_buffer(dev_priv);
1357
1358err_oa_buf_alloc:
1359 if (stream->ctx)
1360 oa_put_render_ctx_id(stream);
1361
1362 return ret;
1363}
1364
Robert Bragg16d98b32016-12-07 21:40:33 +00001365/**
1366 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
1367 * @stream: An i915 perf stream
1368 * @file: An i915 perf stream file
1369 * @buf: destination buffer given by userspace
1370 * @count: the number of bytes userspace wants to read
1371 * @ppos: (inout) file seek position (unused)
1372 *
1373 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
1374 * ensure that if we've successfully copied any data then reporting that takes
1375 * precedence over any internal error status, so the data isn't lost.
1376 *
1377 * For example ret will be -ENOSPC whenever there is more buffered data than
1378 * can be copied to userspace, but that's only interesting if we weren't able
1379 * to copy some data because it implies the userspace buffer is too small to
1380 * receive a single record (and we never split records).
1381 *
1382 * Another case with ret == -EFAULT is more of a grey area since it would seem
1383 * like bad form for userspace to ask us to overrun its buffer, but the user
1384 * knows best:
1385 *
1386 * http://yarchive.net/comp/linux/partial_reads_writes.html
1387 *
1388 * Returns: The number of bytes copied or a negative error code on failure.
1389 */
Robert Braggeec688e2016-11-07 19:49:47 +00001390static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
1391 struct file *file,
1392 char __user *buf,
1393 size_t count,
1394 loff_t *ppos)
1395{
1396 /* Note we keep the offset (aka bytes read) separate from any
1397 * error status so that the final check for whether we return
1398 * the bytes read with a higher precedence than any error (see
1399 * comment below) doesn't need to be handled/duplicated in
1400 * stream->ops->read() implementations.
1401 */
1402 size_t offset = 0;
1403 int ret = stream->ops->read(stream, buf, count, &offset);
1404
Robert Braggeec688e2016-11-07 19:49:47 +00001405 return offset ?: (ret ?: -EAGAIN);
1406}
1407
Robert Bragg16d98b32016-12-07 21:40:33 +00001408/**
1409 * i915_perf_read - handles read() FOP for i915 perf stream FDs
1410 * @file: An i915 perf stream file
1411 * @buf: destination buffer given by userspace
1412 * @count: the number of bytes userspace wants to read
1413 * @ppos: (inout) file seek position (unused)
1414 *
1415 * The entry point for handling a read() on a stream file descriptor from
1416 * userspace. Most of the work is left to the i915_perf_read_locked() and
1417 * &i915_perf_stream_ops->read but to save having stream implementations (of
1418 * which we might have multiple later) we handle blocking read here.
1419 *
1420 * We can also consistently treat trying to read from a disabled stream
1421 * as an IO error so implementations can assume the stream is enabled
1422 * while reading.
1423 *
1424 * Returns: The number of bytes copied or a negative error code on failure.
1425 */
Robert Braggeec688e2016-11-07 19:49:47 +00001426static ssize_t i915_perf_read(struct file *file,
1427 char __user *buf,
1428 size_t count,
1429 loff_t *ppos)
1430{
1431 struct i915_perf_stream *stream = file->private_data;
1432 struct drm_i915_private *dev_priv = stream->dev_priv;
1433 ssize_t ret;
1434
Robert Braggd7965152016-11-07 19:49:52 +00001435 /* To ensure it's handled consistently we simply treat all reads of a
1436 * disabled stream as an error. In particular it might otherwise lead
1437 * to a deadlock for blocking file descriptors...
1438 */
1439 if (!stream->enabled)
1440 return -EIO;
1441
Robert Braggeec688e2016-11-07 19:49:47 +00001442 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00001443 /* There's the small chance of false positives from
1444 * stream->ops->wait_unlocked.
1445 *
1446 * E.g. with single context filtering since we only wait until
1447 * oabuffer has >= 1 report we don't immediately know whether
1448 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00001449 */
1450 do {
1451 ret = stream->ops->wait_unlocked(stream);
1452 if (ret)
1453 return ret;
1454
1455 mutex_lock(&dev_priv->perf.lock);
1456 ret = i915_perf_read_locked(stream, file,
1457 buf, count, ppos);
1458 mutex_unlock(&dev_priv->perf.lock);
1459 } while (ret == -EAGAIN);
1460 } else {
1461 mutex_lock(&dev_priv->perf.lock);
1462 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
1463 mutex_unlock(&dev_priv->perf.lock);
1464 }
1465
Robert Bragg26ebd9c2017-05-11 16:43:25 +01001466 /* We allow the poll checking to sometimes report false positive POLLIN
1467 * events where we might actually report EAGAIN on read() if there's
1468 * not really any data available. In this situation though we don't
1469 * want to enter a busy loop between poll() reporting a POLLIN event
1470 * and read() returning -EAGAIN. Clearing the oa.pollin state here
1471 * effectively ensures we back off until the next hrtimer callback
1472 * before reporting another POLLIN event.
1473 */
1474 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00001475 /* Maybe make ->pollin per-stream state if we support multiple
1476 * concurrent streams in the future.
1477 */
1478 dev_priv->perf.oa.pollin = false;
1479 }
1480
Robert Braggeec688e2016-11-07 19:49:47 +00001481 return ret;
1482}
1483
Robert Braggd7965152016-11-07 19:49:52 +00001484static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
1485{
1486 struct drm_i915_private *dev_priv =
1487 container_of(hrtimer, typeof(*dev_priv),
1488 perf.oa.poll_check_timer);
1489
Robert Bragg0dd860c2017-05-11 16:43:28 +01001490 if (dev_priv->perf.oa.ops.oa_buffer_check(dev_priv)) {
Robert Braggd7965152016-11-07 19:49:52 +00001491 dev_priv->perf.oa.pollin = true;
1492 wake_up(&dev_priv->perf.oa.poll_wq);
1493 }
1494
1495 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
1496
1497 return HRTIMER_RESTART;
1498}
1499
Robert Bragg16d98b32016-12-07 21:40:33 +00001500/**
1501 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
1502 * @dev_priv: i915 device instance
1503 * @stream: An i915 perf stream
1504 * @file: An i915 perf stream file
1505 * @wait: poll() state table
1506 *
1507 * For handling userspace polling on an i915 perf stream, this calls through to
1508 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
1509 * will be woken for new stream data.
1510 *
1511 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1512 * with any non-file-operation driver hooks.
1513 *
1514 * Returns: any poll events that are ready without sleeping
1515 */
Robert Braggd7965152016-11-07 19:49:52 +00001516static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
1517 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00001518 struct file *file,
1519 poll_table *wait)
1520{
Robert Braggd7965152016-11-07 19:49:52 +00001521 unsigned int events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00001522
1523 stream->ops->poll_wait(stream, file, wait);
1524
Robert Braggd7965152016-11-07 19:49:52 +00001525 /* Note: we don't explicitly check whether there's something to read
1526 * here since this path may be very hot depending on what else
1527 * userspace is polling, or on the timeout in use. We rely solely on
1528 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
1529 * samples to read.
1530 */
1531 if (dev_priv->perf.oa.pollin)
1532 events |= POLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00001533
Robert Braggd7965152016-11-07 19:49:52 +00001534 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00001535}
1536
Robert Bragg16d98b32016-12-07 21:40:33 +00001537/**
1538 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
1539 * @file: An i915 perf stream file
1540 * @wait: poll() state table
1541 *
1542 * For handling userspace polling on an i915 perf stream, this ensures
1543 * poll_wait() gets called with a wait queue that will be woken for new stream
1544 * data.
1545 *
1546 * Note: Implementation deferred to i915_perf_poll_locked()
1547 *
1548 * Returns: any poll events that are ready without sleeping
1549 */
Robert Braggeec688e2016-11-07 19:49:47 +00001550static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
1551{
1552 struct i915_perf_stream *stream = file->private_data;
1553 struct drm_i915_private *dev_priv = stream->dev_priv;
1554 int ret;
1555
1556 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00001557 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00001558 mutex_unlock(&dev_priv->perf.lock);
1559
1560 return ret;
1561}
1562
Robert Bragg16d98b32016-12-07 21:40:33 +00001563/**
1564 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
1565 * @stream: A disabled i915 perf stream
1566 *
1567 * [Re]enables the associated capture of data for this stream.
1568 *
1569 * If a stream was previously enabled then there's currently no intention
1570 * to provide userspace any guarantee about the preservation of previously
1571 * buffered data.
1572 */
Robert Braggeec688e2016-11-07 19:49:47 +00001573static void i915_perf_enable_locked(struct i915_perf_stream *stream)
1574{
1575 if (stream->enabled)
1576 return;
1577
1578 /* Allow stream->ops->enable() to refer to this */
1579 stream->enabled = true;
1580
1581 if (stream->ops->enable)
1582 stream->ops->enable(stream);
1583}
1584
Robert Bragg16d98b32016-12-07 21:40:33 +00001585/**
1586 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
1587 * @stream: An enabled i915 perf stream
1588 *
1589 * Disables the associated capture of data for this stream.
1590 *
1591 * The intention is that disabling an re-enabling a stream will ideally be
1592 * cheaper than destroying and re-opening a stream with the same configuration,
1593 * though there are no formal guarantees about what state or buffered data
1594 * must be retained between disabling and re-enabling a stream.
1595 *
1596 * Note: while a stream is disabled it's considered an error for userspace
1597 * to attempt to read from the stream (-EIO).
1598 */
Robert Braggeec688e2016-11-07 19:49:47 +00001599static void i915_perf_disable_locked(struct i915_perf_stream *stream)
1600{
1601 if (!stream->enabled)
1602 return;
1603
1604 /* Allow stream->ops->disable() to refer to this */
1605 stream->enabled = false;
1606
1607 if (stream->ops->disable)
1608 stream->ops->disable(stream);
1609}
1610
Robert Bragg16d98b32016-12-07 21:40:33 +00001611/**
1612 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1613 * @stream: An i915 perf stream
1614 * @cmd: the ioctl request
1615 * @arg: the ioctl data
1616 *
1617 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1618 * with any non-file-operation driver hooks.
1619 *
1620 * Returns: zero on success or a negative error code. Returns -EINVAL for
1621 * an unknown ioctl request.
1622 */
Robert Braggeec688e2016-11-07 19:49:47 +00001623static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
1624 unsigned int cmd,
1625 unsigned long arg)
1626{
1627 switch (cmd) {
1628 case I915_PERF_IOCTL_ENABLE:
1629 i915_perf_enable_locked(stream);
1630 return 0;
1631 case I915_PERF_IOCTL_DISABLE:
1632 i915_perf_disable_locked(stream);
1633 return 0;
1634 }
1635
1636 return -EINVAL;
1637}
1638
Robert Bragg16d98b32016-12-07 21:40:33 +00001639/**
1640 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1641 * @file: An i915 perf stream file
1642 * @cmd: the ioctl request
1643 * @arg: the ioctl data
1644 *
1645 * Implementation deferred to i915_perf_ioctl_locked().
1646 *
1647 * Returns: zero on success or a negative error code. Returns -EINVAL for
1648 * an unknown ioctl request.
1649 */
Robert Braggeec688e2016-11-07 19:49:47 +00001650static long i915_perf_ioctl(struct file *file,
1651 unsigned int cmd,
1652 unsigned long arg)
1653{
1654 struct i915_perf_stream *stream = file->private_data;
1655 struct drm_i915_private *dev_priv = stream->dev_priv;
1656 long ret;
1657
1658 mutex_lock(&dev_priv->perf.lock);
1659 ret = i915_perf_ioctl_locked(stream, cmd, arg);
1660 mutex_unlock(&dev_priv->perf.lock);
1661
1662 return ret;
1663}
1664
Robert Bragg16d98b32016-12-07 21:40:33 +00001665/**
1666 * i915_perf_destroy_locked - destroy an i915 perf stream
1667 * @stream: An i915 perf stream
1668 *
1669 * Frees all resources associated with the given i915 perf @stream, disabling
1670 * any associated data capture in the process.
1671 *
1672 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1673 * with any non-file-operation driver hooks.
1674 */
Robert Braggeec688e2016-11-07 19:49:47 +00001675static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
1676{
Robert Braggeec688e2016-11-07 19:49:47 +00001677 if (stream->enabled)
1678 i915_perf_disable_locked(stream);
1679
1680 if (stream->ops->destroy)
1681 stream->ops->destroy(stream);
1682
1683 list_del(&stream->link);
1684
Chris Wilson69df05e2016-12-18 15:37:21 +00001685 if (stream->ctx)
1686 i915_gem_context_put_unlocked(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001687
1688 kfree(stream);
1689}
1690
Robert Bragg16d98b32016-12-07 21:40:33 +00001691/**
1692 * i915_perf_release - handles userspace close() of a stream file
1693 * @inode: anonymous inode associated with file
1694 * @file: An i915 perf stream file
1695 *
1696 * Cleans up any resources associated with an open i915 perf stream file.
1697 *
1698 * NB: close() can't really fail from the userspace point of view.
1699 *
1700 * Returns: zero on success or a negative error code.
1701 */
Robert Braggeec688e2016-11-07 19:49:47 +00001702static int i915_perf_release(struct inode *inode, struct file *file)
1703{
1704 struct i915_perf_stream *stream = file->private_data;
1705 struct drm_i915_private *dev_priv = stream->dev_priv;
1706
1707 mutex_lock(&dev_priv->perf.lock);
1708 i915_perf_destroy_locked(stream);
1709 mutex_unlock(&dev_priv->perf.lock);
1710
1711 return 0;
1712}
1713
1714
1715static const struct file_operations fops = {
1716 .owner = THIS_MODULE,
1717 .llseek = no_llseek,
1718 .release = i915_perf_release,
1719 .poll = i915_perf_poll,
1720 .read = i915_perf_read,
1721 .unlocked_ioctl = i915_perf_ioctl,
1722};
1723
1724
1725static struct i915_gem_context *
1726lookup_context(struct drm_i915_private *dev_priv,
1727 struct drm_i915_file_private *file_priv,
1728 u32 ctx_user_handle)
1729{
1730 struct i915_gem_context *ctx;
1731 int ret;
1732
1733 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1734 if (ret)
1735 return ERR_PTR(ret);
1736
1737 ctx = i915_gem_context_lookup(file_priv, ctx_user_handle);
1738 if (!IS_ERR(ctx))
1739 i915_gem_context_get(ctx);
1740
1741 mutex_unlock(&dev_priv->drm.struct_mutex);
1742
1743 return ctx;
1744}
1745
Robert Bragg16d98b32016-12-07 21:40:33 +00001746/**
1747 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
1748 * @dev_priv: i915 device instance
1749 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
1750 * @props: individually validated u64 property value pairs
1751 * @file: drm file
1752 *
1753 * See i915_perf_ioctl_open() for interface details.
1754 *
1755 * Implements further stream config validation and stream initialization on
1756 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
1757 * taken to serialize with any non-file-operation driver hooks.
1758 *
1759 * Note: at this point the @props have only been validated in isolation and
1760 * it's still necessary to validate that the combination of properties makes
1761 * sense.
1762 *
1763 * In the case where userspace is interested in OA unit metrics then further
1764 * config validation and stream initialization details will be handled by
1765 * i915_oa_stream_init(). The code here should only validate config state that
1766 * will be relevant to all stream types / backends.
1767 *
1768 * Returns: zero on success or a negative error code.
1769 */
Robert Braggeec688e2016-11-07 19:49:47 +00001770static int
1771i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
1772 struct drm_i915_perf_open_param *param,
1773 struct perf_open_properties *props,
1774 struct drm_file *file)
1775{
1776 struct i915_gem_context *specific_ctx = NULL;
1777 struct i915_perf_stream *stream = NULL;
1778 unsigned long f_flags = 0;
1779 int stream_fd;
1780 int ret;
1781
1782 if (props->single_context) {
1783 u32 ctx_handle = props->ctx_handle;
1784 struct drm_i915_file_private *file_priv = file->driver_priv;
1785
1786 specific_ctx = lookup_context(dev_priv, file_priv, ctx_handle);
1787 if (IS_ERR(specific_ctx)) {
1788 ret = PTR_ERR(specific_ctx);
1789 if (ret != -EINTR)
Robert Bragg77085502016-12-01 17:21:52 +00001790 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
Robert Braggeec688e2016-11-07 19:49:47 +00001791 ctx_handle);
1792 goto err;
1793 }
1794 }
1795
Robert Braggccdf6342016-11-07 19:49:54 +00001796 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
1797 * we check a dev.i915.perf_stream_paranoid sysctl option
1798 * to determine if it's ok to access system wide OA counters
1799 * without CAP_SYS_ADMIN privileges.
1800 */
1801 if (!specific_ctx &&
1802 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001803 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001804 ret = -EACCES;
1805 goto err_ctx;
1806 }
1807
1808 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
1809 if (!stream) {
1810 ret = -ENOMEM;
1811 goto err_ctx;
1812 }
1813
Robert Braggeec688e2016-11-07 19:49:47 +00001814 stream->dev_priv = dev_priv;
1815 stream->ctx = specific_ctx;
1816
Robert Braggd7965152016-11-07 19:49:52 +00001817 ret = i915_oa_stream_init(stream, param, props);
1818 if (ret)
1819 goto err_alloc;
1820
1821 /* we avoid simply assigning stream->sample_flags = props->sample_flags
1822 * to have _stream_init check the combination of sample flags more
1823 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00001824 */
Robert Braggd7965152016-11-07 19:49:52 +00001825 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
1826 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01001827 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00001828 }
Robert Braggeec688e2016-11-07 19:49:47 +00001829
1830 list_add(&stream->link, &dev_priv->perf.streams);
1831
1832 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
1833 f_flags |= O_CLOEXEC;
1834 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
1835 f_flags |= O_NONBLOCK;
1836
1837 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
1838 if (stream_fd < 0) {
1839 ret = stream_fd;
1840 goto err_open;
1841 }
1842
1843 if (!(param->flags & I915_PERF_FLAG_DISABLED))
1844 i915_perf_enable_locked(stream);
1845
1846 return stream_fd;
1847
1848err_open:
1849 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01001850err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00001851 if (stream->ops->destroy)
1852 stream->ops->destroy(stream);
1853err_alloc:
1854 kfree(stream);
1855err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00001856 if (specific_ctx)
1857 i915_gem_context_put_unlocked(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001858err:
1859 return ret;
1860}
1861
Robert Bragg16d98b32016-12-07 21:40:33 +00001862/**
1863 * read_properties_unlocked - validate + copy userspace stream open properties
1864 * @dev_priv: i915 device instance
1865 * @uprops: The array of u64 key value pairs given by userspace
1866 * @n_props: The number of key value pairs expected in @uprops
1867 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00001868 *
1869 * Note this function only validates properties in isolation it doesn't
1870 * validate that the combination of properties makes sense or that all
1871 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00001872 *
1873 * Note that there currently aren't any ordering requirements for properties so
1874 * we shouldn't validate or assume anything about ordering here. This doesn't
1875 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00001876 */
1877static int read_properties_unlocked(struct drm_i915_private *dev_priv,
1878 u64 __user *uprops,
1879 u32 n_props,
1880 struct perf_open_properties *props)
1881{
1882 u64 __user *uprop = uprops;
1883 int i;
1884
1885 memset(props, 0, sizeof(struct perf_open_properties));
1886
1887 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00001888 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001889 return -EINVAL;
1890 }
1891
1892 /* Considering that ID = 0 is reserved and assuming that we don't
1893 * (currently) expect any configurations to ever specify duplicate
1894 * values for a particular property ID then the last _PROP_MAX value is
1895 * one greater than the maximum number of properties we expect to get
1896 * from userspace.
1897 */
1898 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001899 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001900 return -EINVAL;
1901 }
1902
1903 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00001904 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00001905 u64 id, value;
1906 int ret;
1907
1908 ret = get_user(id, uprop);
1909 if (ret)
1910 return ret;
1911
1912 ret = get_user(value, uprop + 1);
1913 if (ret)
1914 return ret;
1915
Matthew Auld0a309f92017-03-27 21:32:36 +01001916 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
1917 DRM_DEBUG("Unknown i915 perf property ID\n");
1918 return -EINVAL;
1919 }
1920
Robert Braggeec688e2016-11-07 19:49:47 +00001921 switch ((enum drm_i915_perf_property_id)id) {
1922 case DRM_I915_PERF_PROP_CTX_HANDLE:
1923 props->single_context = 1;
1924 props->ctx_handle = value;
1925 break;
Robert Braggd7965152016-11-07 19:49:52 +00001926 case DRM_I915_PERF_PROP_SAMPLE_OA:
1927 props->sample_flags |= SAMPLE_OA_REPORT;
1928 break;
1929 case DRM_I915_PERF_PROP_OA_METRICS_SET:
1930 if (value == 0 ||
1931 value > dev_priv->perf.oa.n_builtin_sets) {
Robert Bragg77085502016-12-01 17:21:52 +00001932 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00001933 return -EINVAL;
1934 }
1935 props->metrics_set = value;
1936 break;
1937 case DRM_I915_PERF_PROP_OA_FORMAT:
1938 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg52c57c22017-05-11 16:43:29 +01001939 DRM_DEBUG("Out-of-range OA report format %llu\n",
1940 value);
Robert Braggd7965152016-11-07 19:49:52 +00001941 return -EINVAL;
1942 }
1943 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg52c57c22017-05-11 16:43:29 +01001944 DRM_DEBUG("Unsupported OA report format %llu\n",
1945 value);
Robert Braggd7965152016-11-07 19:49:52 +00001946 return -EINVAL;
1947 }
1948 props->oa_format = value;
1949 break;
1950 case DRM_I915_PERF_PROP_OA_EXPONENT:
1951 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001952 DRM_DEBUG("OA timer exponent too high (> %u)\n",
1953 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00001954 return -EINVAL;
1955 }
1956
Robert Bragg00319ba2016-11-07 19:49:55 +00001957 /* Theoretically we can program the OA unit to sample
Robert Braggd7965152016-11-07 19:49:52 +00001958 * every 160ns but don't allow that by default unless
1959 * root.
1960 *
Robert Bragg00319ba2016-11-07 19:49:55 +00001961 * On Haswell the period is derived from the exponent
1962 * as:
1963 *
1964 * period = 80ns * 2^(exponent + 1)
Robert Braggd7965152016-11-07 19:49:52 +00001965 */
Robert Bragg00319ba2016-11-07 19:49:55 +00001966 BUILD_BUG_ON(sizeof(oa_period) != 8);
1967 oa_period = 80ull * (2ull << value);
1968
1969 /* This check is primarily to ensure that oa_period <=
1970 * UINT32_MAX (before passing to do_div which only
1971 * accepts a u32 denominator), but we can also skip
1972 * checking anything < 1Hz which implicitly can't be
1973 * limited via an integer oa_max_sample_rate.
1974 */
1975 if (oa_period <= NSEC_PER_SEC) {
1976 u64 tmp = NSEC_PER_SEC;
1977 do_div(tmp, oa_period);
1978 oa_freq_hz = tmp;
1979 } else
1980 oa_freq_hz = 0;
1981
1982 if (oa_freq_hz > i915_oa_max_sample_rate &&
1983 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001984 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 +00001985 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00001986 return -EACCES;
1987 }
1988
1989 props->oa_periodic = true;
1990 props->oa_period_exponent = value;
1991 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01001992 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00001993 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00001994 return -EINVAL;
1995 }
1996
1997 uprop += 2;
1998 }
1999
2000 return 0;
2001}
2002
Robert Bragg16d98b32016-12-07 21:40:33 +00002003/**
2004 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
2005 * @dev: drm device
2006 * @data: ioctl data copied from userspace (unvalidated)
2007 * @file: drm file
2008 *
2009 * Validates the stream open parameters given by userspace including flags
2010 * and an array of u64 key, value pair properties.
2011 *
2012 * Very little is assumed up front about the nature of the stream being
2013 * opened (for instance we don't assume it's for periodic OA unit metrics). An
2014 * i915-perf stream is expected to be a suitable interface for other forms of
2015 * buffered data written by the GPU besides periodic OA metrics.
2016 *
2017 * Note we copy the properties from userspace outside of the i915 perf
2018 * mutex to avoid an awkward lockdep with mmap_sem.
2019 *
2020 * Most of the implementation details are handled by
2021 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
2022 * mutex for serializing with any non-file-operation driver hooks.
2023 *
2024 * Return: A newly opened i915 Perf stream file descriptor or negative
2025 * error code on failure.
2026 */
Robert Braggeec688e2016-11-07 19:49:47 +00002027int i915_perf_open_ioctl(struct drm_device *dev, void *data,
2028 struct drm_file *file)
2029{
2030 struct drm_i915_private *dev_priv = dev->dev_private;
2031 struct drm_i915_perf_open_param *param = data;
2032 struct perf_open_properties props;
2033 u32 known_open_flags;
2034 int ret;
2035
2036 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00002037 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002038 return -ENOTSUPP;
2039 }
2040
2041 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
2042 I915_PERF_FLAG_FD_NONBLOCK |
2043 I915_PERF_FLAG_DISABLED;
2044 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00002045 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002046 return -EINVAL;
2047 }
2048
2049 ret = read_properties_unlocked(dev_priv,
2050 u64_to_user_ptr(param->properties_ptr),
2051 param->num_properties,
2052 &props);
2053 if (ret)
2054 return ret;
2055
2056 mutex_lock(&dev_priv->perf.lock);
2057 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
2058 mutex_unlock(&dev_priv->perf.lock);
2059
2060 return ret;
2061}
2062
Robert Bragg16d98b32016-12-07 21:40:33 +00002063/**
2064 * i915_perf_register - exposes i915-perf to userspace
2065 * @dev_priv: i915 device instance
2066 *
2067 * In particular OA metric sets are advertised under a sysfs metrics/
2068 * directory allowing userspace to enumerate valid IDs that can be
2069 * used to open an i915-perf stream.
2070 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002071void i915_perf_register(struct drm_i915_private *dev_priv)
2072{
2073 if (!IS_HASWELL(dev_priv))
2074 return;
2075
2076 if (!dev_priv->perf.initialized)
2077 return;
2078
2079 /* To be sure we're synchronized with an attempted
2080 * i915_perf_open_ioctl(); considering that we register after
2081 * being exposed to userspace.
2082 */
2083 mutex_lock(&dev_priv->perf.lock);
2084
2085 dev_priv->perf.metrics_kobj =
2086 kobject_create_and_add("metrics",
2087 &dev_priv->drm.primary->kdev->kobj);
2088 if (!dev_priv->perf.metrics_kobj)
2089 goto exit;
2090
2091 if (i915_perf_register_sysfs_hsw(dev_priv)) {
2092 kobject_put(dev_priv->perf.metrics_kobj);
2093 dev_priv->perf.metrics_kobj = NULL;
2094 }
2095
2096exit:
2097 mutex_unlock(&dev_priv->perf.lock);
2098}
2099
Robert Bragg16d98b32016-12-07 21:40:33 +00002100/**
2101 * i915_perf_unregister - hide i915-perf from userspace
2102 * @dev_priv: i915 device instance
2103 *
2104 * i915-perf state cleanup is split up into an 'unregister' and
2105 * 'deinit' phase where the interface is first hidden from
2106 * userspace by i915_perf_unregister() before cleaning up
2107 * remaining state in i915_perf_fini().
2108 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002109void i915_perf_unregister(struct drm_i915_private *dev_priv)
2110{
2111 if (!IS_HASWELL(dev_priv))
2112 return;
2113
2114 if (!dev_priv->perf.metrics_kobj)
2115 return;
2116
2117 i915_perf_unregister_sysfs_hsw(dev_priv);
2118
2119 kobject_put(dev_priv->perf.metrics_kobj);
2120 dev_priv->perf.metrics_kobj = NULL;
2121}
2122
Robert Braggccdf6342016-11-07 19:49:54 +00002123static struct ctl_table oa_table[] = {
2124 {
2125 .procname = "perf_stream_paranoid",
2126 .data = &i915_perf_stream_paranoid,
2127 .maxlen = sizeof(i915_perf_stream_paranoid),
2128 .mode = 0644,
2129 .proc_handler = proc_dointvec_minmax,
2130 .extra1 = &zero,
2131 .extra2 = &one,
2132 },
Robert Bragg00319ba2016-11-07 19:49:55 +00002133 {
2134 .procname = "oa_max_sample_rate",
2135 .data = &i915_oa_max_sample_rate,
2136 .maxlen = sizeof(i915_oa_max_sample_rate),
2137 .mode = 0644,
2138 .proc_handler = proc_dointvec_minmax,
2139 .extra1 = &zero,
2140 .extra2 = &oa_sample_rate_hard_limit,
2141 },
Robert Braggccdf6342016-11-07 19:49:54 +00002142 {}
2143};
2144
2145static struct ctl_table i915_root[] = {
2146 {
2147 .procname = "i915",
2148 .maxlen = 0,
2149 .mode = 0555,
2150 .child = oa_table,
2151 },
2152 {}
2153};
2154
2155static struct ctl_table dev_root[] = {
2156 {
2157 .procname = "dev",
2158 .maxlen = 0,
2159 .mode = 0555,
2160 .child = i915_root,
2161 },
2162 {}
2163};
2164
Robert Bragg16d98b32016-12-07 21:40:33 +00002165/**
2166 * i915_perf_init - initialize i915-perf state on module load
2167 * @dev_priv: i915 device instance
2168 *
2169 * Initializes i915-perf state without exposing anything to userspace.
2170 *
2171 * Note: i915-perf initialization is split into an 'init' and 'register'
2172 * phase with the i915_perf_register() exposing state to userspace.
2173 */
Robert Braggeec688e2016-11-07 19:49:47 +00002174void i915_perf_init(struct drm_i915_private *dev_priv)
2175{
Robert Braggd7965152016-11-07 19:49:52 +00002176 if (!IS_HASWELL(dev_priv))
2177 return;
2178
2179 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
2180 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2181 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
2182 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
2183
Robert Braggeec688e2016-11-07 19:49:47 +00002184 INIT_LIST_HEAD(&dev_priv->perf.streams);
2185 mutex_init(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002186 spin_lock_init(&dev_priv->perf.hook_lock);
Robert Bragg0dd860c2017-05-11 16:43:28 +01002187 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
Robert Braggd7965152016-11-07 19:49:52 +00002188
2189 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
2190 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
2191 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
2192 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
2193 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
2194 dev_priv->perf.oa.ops.read = gen7_oa_read;
Robert Bragg0dd860c2017-05-11 16:43:28 +01002195 dev_priv->perf.oa.ops.oa_buffer_check =
2196 gen7_oa_buffer_check_unlocked;
Robert Braggd7965152016-11-07 19:49:52 +00002197
2198 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
2199
2200 dev_priv->perf.oa.n_builtin_sets =
2201 i915_oa_n_builtin_metric_sets_hsw;
Robert Braggeec688e2016-11-07 19:49:47 +00002202
Robert Braggccdf6342016-11-07 19:49:54 +00002203 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
2204
Robert Braggeec688e2016-11-07 19:49:47 +00002205 dev_priv->perf.initialized = true;
2206}
2207
Robert Bragg16d98b32016-12-07 21:40:33 +00002208/**
2209 * i915_perf_fini - Counter part to i915_perf_init()
2210 * @dev_priv: i915 device instance
2211 */
Robert Braggeec688e2016-11-07 19:49:47 +00002212void i915_perf_fini(struct drm_i915_private *dev_priv)
2213{
2214 if (!dev_priv->perf.initialized)
2215 return;
2216
Robert Braggccdf6342016-11-07 19:49:54 +00002217 unregister_sysctl_table(dev_priv->perf.sysctl_header);
2218
Robert Braggd7965152016-11-07 19:49:52 +00002219 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Braggeec688e2016-11-07 19:49:47 +00002220 dev_priv->perf.initialized = false;
2221}