blob: 85269bcc8372c623021d278942e1cc3461cbeb95 [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);
1050
1051 if (ret)
1052 return ret;
1053
1054 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) |
1055 GT_NOA_ENABLE));
1056
1057 /* PRM:
1058 *
1059 * OA unit is using “crclk” for its functionality. When trunk
1060 * level clock gating takes place, OA clock would be gated,
1061 * unable to count the events from non-render clock domain.
1062 * Render clock gating must be disabled when OA is enabled to
1063 * count the events from non-render domain. Unit level clock
1064 * gating for RCS should also be disabled.
1065 */
1066 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
1067 ~GEN7_DOP_CLOCK_GATE_ENABLE));
1068 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
1069 GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1070
1071 config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs,
1072 dev_priv->perf.oa.mux_regs_len);
1073
1074 /* It apparently takes a fairly long time for a new MUX
1075 * configuration to be be applied after these register writes.
1076 * This delay duration was derived empirically based on the
1077 * render_basic config but hopefully it covers the maximum
1078 * configuration latency.
1079 *
1080 * As a fallback, the checks in _append_oa_reports() to skip
1081 * invalid OA reports do also seem to work to discard reports
1082 * generated before this config has completed - albeit not
1083 * silently.
1084 *
1085 * Unfortunately this is essentially a magic number, since we
1086 * don't currently know of a reliable mechanism for predicting
1087 * how long the MUX config will take to apply and besides
1088 * seeing invalid reports we don't know of a reliable way to
1089 * explicitly check that the MUX config has landed.
1090 *
1091 * It's even possible we've miss characterized the underlying
1092 * problem - it just seems like the simplest explanation why
1093 * a delay at this location would mitigate any invalid reports.
1094 */
1095 usleep_range(15000, 20000);
1096
1097 config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
1098 dev_priv->perf.oa.b_counter_regs_len);
1099
1100 return 0;
1101}
1102
1103static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
1104{
1105 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
1106 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
1107 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
1108 GEN7_DOP_CLOCK_GATE_ENABLE));
1109
1110 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
1111 ~GT_NOA_ENABLE));
1112}
1113
1114static void gen7_update_oacontrol_locked(struct drm_i915_private *dev_priv)
1115{
Chris Wilson67520412017-03-02 13:28:01 +00001116 lockdep_assert_held(&dev_priv->perf.hook_lock);
Robert Braggd7965152016-11-07 19:49:52 +00001117
1118 if (dev_priv->perf.oa.exclusive_stream->enabled) {
1119 struct i915_gem_context *ctx =
1120 dev_priv->perf.oa.exclusive_stream->ctx;
1121 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
1122
1123 bool periodic = dev_priv->perf.oa.periodic;
1124 u32 period_exponent = dev_priv->perf.oa.period_exponent;
1125 u32 report_format = dev_priv->perf.oa.oa_buffer.format;
1126
1127 I915_WRITE(GEN7_OACONTROL,
1128 (ctx_id & GEN7_OACONTROL_CTX_MASK) |
1129 (period_exponent <<
1130 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
1131 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
1132 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
1133 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
1134 GEN7_OACONTROL_ENABLE);
1135 } else
1136 I915_WRITE(GEN7_OACONTROL, 0);
1137}
1138
1139static void gen7_oa_enable(struct drm_i915_private *dev_priv)
1140{
1141 unsigned long flags;
1142
1143 /* Reset buf pointers so we don't forward reports from before now.
1144 *
1145 * Think carefully if considering trying to avoid this, since it
1146 * also ensures status flags and the buffer itself are cleared
1147 * in error paths, and we have checks for invalid reports based
1148 * on the assumption that certain fields are written to zeroed
1149 * memory which this helps maintains.
1150 */
1151 gen7_init_oa_buffer(dev_priv);
1152
1153 spin_lock_irqsave(&dev_priv->perf.hook_lock, flags);
1154 gen7_update_oacontrol_locked(dev_priv);
1155 spin_unlock_irqrestore(&dev_priv->perf.hook_lock, flags);
1156}
1157
Robert Bragg16d98b32016-12-07 21:40:33 +00001158/**
1159 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
1160 * @stream: An i915 perf stream opened for OA metrics
1161 *
1162 * [Re]enables hardware periodic sampling according to the period configured
1163 * when opening the stream. This also starts a hrtimer that will periodically
1164 * check for data in the circular OA buffer for notifying userspace (e.g.
1165 * during a read() or poll()).
1166 */
Robert Braggd7965152016-11-07 19:49:52 +00001167static void i915_oa_stream_enable(struct i915_perf_stream *stream)
1168{
1169 struct drm_i915_private *dev_priv = stream->dev_priv;
1170
1171 dev_priv->perf.oa.ops.oa_enable(dev_priv);
1172
1173 if (dev_priv->perf.oa.periodic)
1174 hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
1175 ns_to_ktime(POLL_PERIOD),
1176 HRTIMER_MODE_REL_PINNED);
1177}
1178
1179static void gen7_oa_disable(struct drm_i915_private *dev_priv)
1180{
1181 I915_WRITE(GEN7_OACONTROL, 0);
1182}
1183
Robert Bragg16d98b32016-12-07 21:40:33 +00001184/**
1185 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
1186 * @stream: An i915 perf stream opened for OA metrics
1187 *
1188 * Stops the OA unit from periodically writing counter reports into the
1189 * circular OA buffer. This also stops the hrtimer that periodically checks for
1190 * data in the circular OA buffer, for notifying userspace.
1191 */
Robert Braggd7965152016-11-07 19:49:52 +00001192static void i915_oa_stream_disable(struct i915_perf_stream *stream)
1193{
1194 struct drm_i915_private *dev_priv = stream->dev_priv;
1195
1196 dev_priv->perf.oa.ops.oa_disable(dev_priv);
1197
1198 if (dev_priv->perf.oa.periodic)
1199 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
1200}
1201
Robert Braggd7965152016-11-07 19:49:52 +00001202static const struct i915_perf_stream_ops i915_oa_stream_ops = {
1203 .destroy = i915_oa_stream_destroy,
1204 .enable = i915_oa_stream_enable,
1205 .disable = i915_oa_stream_disable,
1206 .wait_unlocked = i915_oa_wait_unlocked,
1207 .poll_wait = i915_oa_poll_wait,
1208 .read = i915_oa_read,
1209};
1210
Robert Bragg16d98b32016-12-07 21:40:33 +00001211/**
1212 * i915_oa_stream_init - validate combined props for OA stream and init
1213 * @stream: An i915 perf stream
1214 * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
1215 * @props: The property state that configures stream (individually validated)
1216 *
1217 * While read_properties_unlocked() validates properties in isolation it
1218 * doesn't ensure that the combination necessarily makes sense.
1219 *
1220 * At this point it has been determined that userspace wants a stream of
1221 * OA metrics, but still we need to further validate the combined
1222 * properties are OK.
1223 *
1224 * If the configuration makes sense then we can allocate memory for
1225 * a circular OA buffer and apply the requested metric set configuration.
1226 *
1227 * Returns: zero on success or a negative error code.
1228 */
Robert Braggd7965152016-11-07 19:49:52 +00001229static int i915_oa_stream_init(struct i915_perf_stream *stream,
1230 struct drm_i915_perf_open_param *param,
1231 struct perf_open_properties *props)
1232{
1233 struct drm_i915_private *dev_priv = stream->dev_priv;
1234 int format_size;
1235 int ret;
1236
Robert Bragg442b8c02016-11-07 19:49:53 +00001237 /* If the sysfs metrics/ directory wasn't registered for some
1238 * reason then don't let userspace try their luck with config
1239 * IDs
1240 */
1241 if (!dev_priv->perf.metrics_kobj) {
Robert Bragg77085502016-12-01 17:21:52 +00001242 DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
Robert Bragg442b8c02016-11-07 19:49:53 +00001243 return -EINVAL;
1244 }
1245
Robert Braggd7965152016-11-07 19:49:52 +00001246 if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
Robert Bragg77085502016-12-01 17:21:52 +00001247 DRM_DEBUG("Only OA report sampling supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001248 return -EINVAL;
1249 }
1250
1251 if (!dev_priv->perf.oa.ops.init_oa_buffer) {
Robert Bragg77085502016-12-01 17:21:52 +00001252 DRM_DEBUG("OA unit not supported\n");
Robert Braggd7965152016-11-07 19:49:52 +00001253 return -ENODEV;
1254 }
1255
1256 /* To avoid the complexity of having to accurately filter
1257 * counter reports and marshal to the appropriate client
1258 * we currently only allow exclusive access
1259 */
1260 if (dev_priv->perf.oa.exclusive_stream) {
Robert Bragg77085502016-12-01 17:21:52 +00001261 DRM_DEBUG("OA unit already in use\n");
Robert Braggd7965152016-11-07 19:49:52 +00001262 return -EBUSY;
1263 }
1264
1265 if (!props->metrics_set) {
Robert Bragg77085502016-12-01 17:21:52 +00001266 DRM_DEBUG("OA metric set not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001267 return -EINVAL;
1268 }
1269
1270 if (!props->oa_format) {
Robert Bragg77085502016-12-01 17:21:52 +00001271 DRM_DEBUG("OA report format not specified\n");
Robert Braggd7965152016-11-07 19:49:52 +00001272 return -EINVAL;
1273 }
1274
Robert Bragg712122e2017-05-11 16:43:31 +01001275 /* We set up some ratelimit state to potentially throttle any _NOTES
1276 * about spurious, invalid OA reports which we don't forward to
1277 * userspace.
1278 *
1279 * The initialization is associated with opening the stream (not driver
1280 * init) considering we print a _NOTE about any throttling when closing
1281 * the stream instead of waiting until driver _fini which no one would
1282 * ever see.
1283 *
1284 * Using the same limiting factors as printk_ratelimit()
1285 */
1286 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
1287 5 * HZ, 10);
1288 /* Since we use a DRM_NOTE for spurious reports it would be
1289 * inconsistent to let __ratelimit() automatically print a warning for
1290 * throttling.
1291 */
1292 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
1293 RATELIMIT_MSG_ON_RELEASE);
1294
Robert Braggd7965152016-11-07 19:49:52 +00001295 stream->sample_size = sizeof(struct drm_i915_perf_record_header);
1296
1297 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
1298
1299 stream->sample_flags |= SAMPLE_OA_REPORT;
1300 stream->sample_size += format_size;
1301
1302 dev_priv->perf.oa.oa_buffer.format_size = format_size;
1303 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
1304 return -EINVAL;
1305
1306 dev_priv->perf.oa.oa_buffer.format =
1307 dev_priv->perf.oa.oa_formats[props->oa_format].format;
1308
1309 dev_priv->perf.oa.metrics_set = props->metrics_set;
1310
1311 dev_priv->perf.oa.periodic = props->oa_periodic;
Robert Bragg0dd860c2017-05-11 16:43:28 +01001312 if (dev_priv->perf.oa.periodic)
Robert Braggd7965152016-11-07 19:49:52 +00001313 dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
1314
Robert Braggd7965152016-11-07 19:49:52 +00001315 if (stream->ctx) {
1316 ret = oa_get_render_ctx_id(stream);
1317 if (ret)
1318 return ret;
1319 }
1320
1321 ret = alloc_oa_buffer(dev_priv);
1322 if (ret)
1323 goto err_oa_buf_alloc;
1324
1325 /* PRM - observability performance counters:
1326 *
1327 * OACONTROL, performance counter enable, note:
1328 *
1329 * "When this bit is set, in order to have coherent counts,
1330 * RC6 power state and trunk clock gating must be disabled.
1331 * This can be achieved by programming MMIO registers as
1332 * 0xA094=0 and 0xA090[31]=1"
1333 *
1334 * In our case we are expecting that taking pm + FORCEWAKE
1335 * references will effectively disable RC6.
1336 */
1337 intel_runtime_pm_get(dev_priv);
1338 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
1339
1340 ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv);
1341 if (ret)
1342 goto err_enable;
1343
1344 stream->ops = &i915_oa_stream_ops;
1345
1346 dev_priv->perf.oa.exclusive_stream = stream;
1347
1348 return 0;
1349
1350err_enable:
1351 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
1352 intel_runtime_pm_put(dev_priv);
1353 free_oa_buffer(dev_priv);
1354
1355err_oa_buf_alloc:
1356 if (stream->ctx)
1357 oa_put_render_ctx_id(stream);
1358
1359 return ret;
1360}
1361
Robert Bragg16d98b32016-12-07 21:40:33 +00001362/**
1363 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
1364 * @stream: An i915 perf stream
1365 * @file: An i915 perf stream file
1366 * @buf: destination buffer given by userspace
1367 * @count: the number of bytes userspace wants to read
1368 * @ppos: (inout) file seek position (unused)
1369 *
1370 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
1371 * ensure that if we've successfully copied any data then reporting that takes
1372 * precedence over any internal error status, so the data isn't lost.
1373 *
1374 * For example ret will be -ENOSPC whenever there is more buffered data than
1375 * can be copied to userspace, but that's only interesting if we weren't able
1376 * to copy some data because it implies the userspace buffer is too small to
1377 * receive a single record (and we never split records).
1378 *
1379 * Another case with ret == -EFAULT is more of a grey area since it would seem
1380 * like bad form for userspace to ask us to overrun its buffer, but the user
1381 * knows best:
1382 *
1383 * http://yarchive.net/comp/linux/partial_reads_writes.html
1384 *
1385 * Returns: The number of bytes copied or a negative error code on failure.
1386 */
Robert Braggeec688e2016-11-07 19:49:47 +00001387static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
1388 struct file *file,
1389 char __user *buf,
1390 size_t count,
1391 loff_t *ppos)
1392{
1393 /* Note we keep the offset (aka bytes read) separate from any
1394 * error status so that the final check for whether we return
1395 * the bytes read with a higher precedence than any error (see
1396 * comment below) doesn't need to be handled/duplicated in
1397 * stream->ops->read() implementations.
1398 */
1399 size_t offset = 0;
1400 int ret = stream->ops->read(stream, buf, count, &offset);
1401
Robert Braggeec688e2016-11-07 19:49:47 +00001402 return offset ?: (ret ?: -EAGAIN);
1403}
1404
Robert Bragg16d98b32016-12-07 21:40:33 +00001405/**
1406 * i915_perf_read - handles read() FOP for i915 perf stream FDs
1407 * @file: An i915 perf stream file
1408 * @buf: destination buffer given by userspace
1409 * @count: the number of bytes userspace wants to read
1410 * @ppos: (inout) file seek position (unused)
1411 *
1412 * The entry point for handling a read() on a stream file descriptor from
1413 * userspace. Most of the work is left to the i915_perf_read_locked() and
1414 * &i915_perf_stream_ops->read but to save having stream implementations (of
1415 * which we might have multiple later) we handle blocking read here.
1416 *
1417 * We can also consistently treat trying to read from a disabled stream
1418 * as an IO error so implementations can assume the stream is enabled
1419 * while reading.
1420 *
1421 * Returns: The number of bytes copied or a negative error code on failure.
1422 */
Robert Braggeec688e2016-11-07 19:49:47 +00001423static ssize_t i915_perf_read(struct file *file,
1424 char __user *buf,
1425 size_t count,
1426 loff_t *ppos)
1427{
1428 struct i915_perf_stream *stream = file->private_data;
1429 struct drm_i915_private *dev_priv = stream->dev_priv;
1430 ssize_t ret;
1431
Robert Braggd7965152016-11-07 19:49:52 +00001432 /* To ensure it's handled consistently we simply treat all reads of a
1433 * disabled stream as an error. In particular it might otherwise lead
1434 * to a deadlock for blocking file descriptors...
1435 */
1436 if (!stream->enabled)
1437 return -EIO;
1438
Robert Braggeec688e2016-11-07 19:49:47 +00001439 if (!(file->f_flags & O_NONBLOCK)) {
Robert Braggd7965152016-11-07 19:49:52 +00001440 /* There's the small chance of false positives from
1441 * stream->ops->wait_unlocked.
1442 *
1443 * E.g. with single context filtering since we only wait until
1444 * oabuffer has >= 1 report we don't immediately know whether
1445 * any reports really belong to the current context
Robert Braggeec688e2016-11-07 19:49:47 +00001446 */
1447 do {
1448 ret = stream->ops->wait_unlocked(stream);
1449 if (ret)
1450 return ret;
1451
1452 mutex_lock(&dev_priv->perf.lock);
1453 ret = i915_perf_read_locked(stream, file,
1454 buf, count, ppos);
1455 mutex_unlock(&dev_priv->perf.lock);
1456 } while (ret == -EAGAIN);
1457 } else {
1458 mutex_lock(&dev_priv->perf.lock);
1459 ret = i915_perf_read_locked(stream, file, buf, count, ppos);
1460 mutex_unlock(&dev_priv->perf.lock);
1461 }
1462
Robert Bragg26ebd9c2017-05-11 16:43:25 +01001463 /* We allow the poll checking to sometimes report false positive POLLIN
1464 * events where we might actually report EAGAIN on read() if there's
1465 * not really any data available. In this situation though we don't
1466 * want to enter a busy loop between poll() reporting a POLLIN event
1467 * and read() returning -EAGAIN. Clearing the oa.pollin state here
1468 * effectively ensures we back off until the next hrtimer callback
1469 * before reporting another POLLIN event.
1470 */
1471 if (ret >= 0 || ret == -EAGAIN) {
Robert Braggd7965152016-11-07 19:49:52 +00001472 /* Maybe make ->pollin per-stream state if we support multiple
1473 * concurrent streams in the future.
1474 */
1475 dev_priv->perf.oa.pollin = false;
1476 }
1477
Robert Braggeec688e2016-11-07 19:49:47 +00001478 return ret;
1479}
1480
Robert Braggd7965152016-11-07 19:49:52 +00001481static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
1482{
1483 struct drm_i915_private *dev_priv =
1484 container_of(hrtimer, typeof(*dev_priv),
1485 perf.oa.poll_check_timer);
1486
Robert Bragg0dd860c2017-05-11 16:43:28 +01001487 if (dev_priv->perf.oa.ops.oa_buffer_check(dev_priv)) {
Robert Braggd7965152016-11-07 19:49:52 +00001488 dev_priv->perf.oa.pollin = true;
1489 wake_up(&dev_priv->perf.oa.poll_wq);
1490 }
1491
1492 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
1493
1494 return HRTIMER_RESTART;
1495}
1496
Robert Bragg16d98b32016-12-07 21:40:33 +00001497/**
1498 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
1499 * @dev_priv: i915 device instance
1500 * @stream: An i915 perf stream
1501 * @file: An i915 perf stream file
1502 * @wait: poll() state table
1503 *
1504 * For handling userspace polling on an i915 perf stream, this calls through to
1505 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
1506 * will be woken for new stream data.
1507 *
1508 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1509 * with any non-file-operation driver hooks.
1510 *
1511 * Returns: any poll events that are ready without sleeping
1512 */
Robert Braggd7965152016-11-07 19:49:52 +00001513static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
1514 struct i915_perf_stream *stream,
Robert Braggeec688e2016-11-07 19:49:47 +00001515 struct file *file,
1516 poll_table *wait)
1517{
Robert Braggd7965152016-11-07 19:49:52 +00001518 unsigned int events = 0;
Robert Braggeec688e2016-11-07 19:49:47 +00001519
1520 stream->ops->poll_wait(stream, file, wait);
1521
Robert Braggd7965152016-11-07 19:49:52 +00001522 /* Note: we don't explicitly check whether there's something to read
1523 * here since this path may be very hot depending on what else
1524 * userspace is polling, or on the timeout in use. We rely solely on
1525 * the hrtimer/oa_poll_check_timer_cb to notify us when there are
1526 * samples to read.
1527 */
1528 if (dev_priv->perf.oa.pollin)
1529 events |= POLLIN;
Robert Braggeec688e2016-11-07 19:49:47 +00001530
Robert Braggd7965152016-11-07 19:49:52 +00001531 return events;
Robert Braggeec688e2016-11-07 19:49:47 +00001532}
1533
Robert Bragg16d98b32016-12-07 21:40:33 +00001534/**
1535 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
1536 * @file: An i915 perf stream file
1537 * @wait: poll() state table
1538 *
1539 * For handling userspace polling on an i915 perf stream, this ensures
1540 * poll_wait() gets called with a wait queue that will be woken for new stream
1541 * data.
1542 *
1543 * Note: Implementation deferred to i915_perf_poll_locked()
1544 *
1545 * Returns: any poll events that are ready without sleeping
1546 */
Robert Braggeec688e2016-11-07 19:49:47 +00001547static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
1548{
1549 struct i915_perf_stream *stream = file->private_data;
1550 struct drm_i915_private *dev_priv = stream->dev_priv;
1551 int ret;
1552
1553 mutex_lock(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00001554 ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
Robert Braggeec688e2016-11-07 19:49:47 +00001555 mutex_unlock(&dev_priv->perf.lock);
1556
1557 return ret;
1558}
1559
Robert Bragg16d98b32016-12-07 21:40:33 +00001560/**
1561 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
1562 * @stream: A disabled i915 perf stream
1563 *
1564 * [Re]enables the associated capture of data for this stream.
1565 *
1566 * If a stream was previously enabled then there's currently no intention
1567 * to provide userspace any guarantee about the preservation of previously
1568 * buffered data.
1569 */
Robert Braggeec688e2016-11-07 19:49:47 +00001570static void i915_perf_enable_locked(struct i915_perf_stream *stream)
1571{
1572 if (stream->enabled)
1573 return;
1574
1575 /* Allow stream->ops->enable() to refer to this */
1576 stream->enabled = true;
1577
1578 if (stream->ops->enable)
1579 stream->ops->enable(stream);
1580}
1581
Robert Bragg16d98b32016-12-07 21:40:33 +00001582/**
1583 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
1584 * @stream: An enabled i915 perf stream
1585 *
1586 * Disables the associated capture of data for this stream.
1587 *
1588 * The intention is that disabling an re-enabling a stream will ideally be
1589 * cheaper than destroying and re-opening a stream with the same configuration,
1590 * though there are no formal guarantees about what state or buffered data
1591 * must be retained between disabling and re-enabling a stream.
1592 *
1593 * Note: while a stream is disabled it's considered an error for userspace
1594 * to attempt to read from the stream (-EIO).
1595 */
Robert Braggeec688e2016-11-07 19:49:47 +00001596static void i915_perf_disable_locked(struct i915_perf_stream *stream)
1597{
1598 if (!stream->enabled)
1599 return;
1600
1601 /* Allow stream->ops->disable() to refer to this */
1602 stream->enabled = false;
1603
1604 if (stream->ops->disable)
1605 stream->ops->disable(stream);
1606}
1607
Robert Bragg16d98b32016-12-07 21:40:33 +00001608/**
1609 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1610 * @stream: An i915 perf stream
1611 * @cmd: the ioctl request
1612 * @arg: the ioctl data
1613 *
1614 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1615 * with any non-file-operation driver hooks.
1616 *
1617 * Returns: zero on success or a negative error code. Returns -EINVAL for
1618 * an unknown ioctl request.
1619 */
Robert Braggeec688e2016-11-07 19:49:47 +00001620static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
1621 unsigned int cmd,
1622 unsigned long arg)
1623{
1624 switch (cmd) {
1625 case I915_PERF_IOCTL_ENABLE:
1626 i915_perf_enable_locked(stream);
1627 return 0;
1628 case I915_PERF_IOCTL_DISABLE:
1629 i915_perf_disable_locked(stream);
1630 return 0;
1631 }
1632
1633 return -EINVAL;
1634}
1635
Robert Bragg16d98b32016-12-07 21:40:33 +00001636/**
1637 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
1638 * @file: An i915 perf stream file
1639 * @cmd: the ioctl request
1640 * @arg: the ioctl data
1641 *
1642 * Implementation deferred to i915_perf_ioctl_locked().
1643 *
1644 * Returns: zero on success or a negative error code. Returns -EINVAL for
1645 * an unknown ioctl request.
1646 */
Robert Braggeec688e2016-11-07 19:49:47 +00001647static long i915_perf_ioctl(struct file *file,
1648 unsigned int cmd,
1649 unsigned long arg)
1650{
1651 struct i915_perf_stream *stream = file->private_data;
1652 struct drm_i915_private *dev_priv = stream->dev_priv;
1653 long ret;
1654
1655 mutex_lock(&dev_priv->perf.lock);
1656 ret = i915_perf_ioctl_locked(stream, cmd, arg);
1657 mutex_unlock(&dev_priv->perf.lock);
1658
1659 return ret;
1660}
1661
Robert Bragg16d98b32016-12-07 21:40:33 +00001662/**
1663 * i915_perf_destroy_locked - destroy an i915 perf stream
1664 * @stream: An i915 perf stream
1665 *
1666 * Frees all resources associated with the given i915 perf @stream, disabling
1667 * any associated data capture in the process.
1668 *
1669 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
1670 * with any non-file-operation driver hooks.
1671 */
Robert Braggeec688e2016-11-07 19:49:47 +00001672static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
1673{
Robert Braggeec688e2016-11-07 19:49:47 +00001674 if (stream->enabled)
1675 i915_perf_disable_locked(stream);
1676
1677 if (stream->ops->destroy)
1678 stream->ops->destroy(stream);
1679
1680 list_del(&stream->link);
1681
Chris Wilson69df05e2016-12-18 15:37:21 +00001682 if (stream->ctx)
1683 i915_gem_context_put_unlocked(stream->ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001684
1685 kfree(stream);
1686}
1687
Robert Bragg16d98b32016-12-07 21:40:33 +00001688/**
1689 * i915_perf_release - handles userspace close() of a stream file
1690 * @inode: anonymous inode associated with file
1691 * @file: An i915 perf stream file
1692 *
1693 * Cleans up any resources associated with an open i915 perf stream file.
1694 *
1695 * NB: close() can't really fail from the userspace point of view.
1696 *
1697 * Returns: zero on success or a negative error code.
1698 */
Robert Braggeec688e2016-11-07 19:49:47 +00001699static int i915_perf_release(struct inode *inode, struct file *file)
1700{
1701 struct i915_perf_stream *stream = file->private_data;
1702 struct drm_i915_private *dev_priv = stream->dev_priv;
1703
1704 mutex_lock(&dev_priv->perf.lock);
1705 i915_perf_destroy_locked(stream);
1706 mutex_unlock(&dev_priv->perf.lock);
1707
1708 return 0;
1709}
1710
1711
1712static const struct file_operations fops = {
1713 .owner = THIS_MODULE,
1714 .llseek = no_llseek,
1715 .release = i915_perf_release,
1716 .poll = i915_perf_poll,
1717 .read = i915_perf_read,
1718 .unlocked_ioctl = i915_perf_ioctl,
1719};
1720
1721
1722static struct i915_gem_context *
1723lookup_context(struct drm_i915_private *dev_priv,
1724 struct drm_i915_file_private *file_priv,
1725 u32 ctx_user_handle)
1726{
1727 struct i915_gem_context *ctx;
1728 int ret;
1729
1730 ret = i915_mutex_lock_interruptible(&dev_priv->drm);
1731 if (ret)
1732 return ERR_PTR(ret);
1733
1734 ctx = i915_gem_context_lookup(file_priv, ctx_user_handle);
1735 if (!IS_ERR(ctx))
1736 i915_gem_context_get(ctx);
1737
1738 mutex_unlock(&dev_priv->drm.struct_mutex);
1739
1740 return ctx;
1741}
1742
Robert Bragg16d98b32016-12-07 21:40:33 +00001743/**
1744 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
1745 * @dev_priv: i915 device instance
1746 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
1747 * @props: individually validated u64 property value pairs
1748 * @file: drm file
1749 *
1750 * See i915_perf_ioctl_open() for interface details.
1751 *
1752 * Implements further stream config validation and stream initialization on
1753 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
1754 * taken to serialize with any non-file-operation driver hooks.
1755 *
1756 * Note: at this point the @props have only been validated in isolation and
1757 * it's still necessary to validate that the combination of properties makes
1758 * sense.
1759 *
1760 * In the case where userspace is interested in OA unit metrics then further
1761 * config validation and stream initialization details will be handled by
1762 * i915_oa_stream_init(). The code here should only validate config state that
1763 * will be relevant to all stream types / backends.
1764 *
1765 * Returns: zero on success or a negative error code.
1766 */
Robert Braggeec688e2016-11-07 19:49:47 +00001767static int
1768i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
1769 struct drm_i915_perf_open_param *param,
1770 struct perf_open_properties *props,
1771 struct drm_file *file)
1772{
1773 struct i915_gem_context *specific_ctx = NULL;
1774 struct i915_perf_stream *stream = NULL;
1775 unsigned long f_flags = 0;
1776 int stream_fd;
1777 int ret;
1778
1779 if (props->single_context) {
1780 u32 ctx_handle = props->ctx_handle;
1781 struct drm_i915_file_private *file_priv = file->driver_priv;
1782
1783 specific_ctx = lookup_context(dev_priv, file_priv, ctx_handle);
1784 if (IS_ERR(specific_ctx)) {
1785 ret = PTR_ERR(specific_ctx);
1786 if (ret != -EINTR)
Robert Bragg77085502016-12-01 17:21:52 +00001787 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
Robert Braggeec688e2016-11-07 19:49:47 +00001788 ctx_handle);
1789 goto err;
1790 }
1791 }
1792
Robert Braggccdf6342016-11-07 19:49:54 +00001793 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
1794 * we check a dev.i915.perf_stream_paranoid sysctl option
1795 * to determine if it's ok to access system wide OA counters
1796 * without CAP_SYS_ADMIN privileges.
1797 */
1798 if (!specific_ctx &&
1799 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001800 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001801 ret = -EACCES;
1802 goto err_ctx;
1803 }
1804
1805 stream = kzalloc(sizeof(*stream), GFP_KERNEL);
1806 if (!stream) {
1807 ret = -ENOMEM;
1808 goto err_ctx;
1809 }
1810
Robert Braggeec688e2016-11-07 19:49:47 +00001811 stream->dev_priv = dev_priv;
1812 stream->ctx = specific_ctx;
1813
Robert Braggd7965152016-11-07 19:49:52 +00001814 ret = i915_oa_stream_init(stream, param, props);
1815 if (ret)
1816 goto err_alloc;
1817
1818 /* we avoid simply assigning stream->sample_flags = props->sample_flags
1819 * to have _stream_init check the combination of sample flags more
1820 * thoroughly, but still this is the expected result at this point.
Robert Braggeec688e2016-11-07 19:49:47 +00001821 */
Robert Braggd7965152016-11-07 19:49:52 +00001822 if (WARN_ON(stream->sample_flags != props->sample_flags)) {
1823 ret = -ENODEV;
Matthew Auld22f880c2017-03-27 21:34:59 +01001824 goto err_flags;
Robert Braggd7965152016-11-07 19:49:52 +00001825 }
Robert Braggeec688e2016-11-07 19:49:47 +00001826
1827 list_add(&stream->link, &dev_priv->perf.streams);
1828
1829 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
1830 f_flags |= O_CLOEXEC;
1831 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
1832 f_flags |= O_NONBLOCK;
1833
1834 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
1835 if (stream_fd < 0) {
1836 ret = stream_fd;
1837 goto err_open;
1838 }
1839
1840 if (!(param->flags & I915_PERF_FLAG_DISABLED))
1841 i915_perf_enable_locked(stream);
1842
1843 return stream_fd;
1844
1845err_open:
1846 list_del(&stream->link);
Matthew Auld22f880c2017-03-27 21:34:59 +01001847err_flags:
Robert Braggeec688e2016-11-07 19:49:47 +00001848 if (stream->ops->destroy)
1849 stream->ops->destroy(stream);
1850err_alloc:
1851 kfree(stream);
1852err_ctx:
Chris Wilson69df05e2016-12-18 15:37:21 +00001853 if (specific_ctx)
1854 i915_gem_context_put_unlocked(specific_ctx);
Robert Braggeec688e2016-11-07 19:49:47 +00001855err:
1856 return ret;
1857}
1858
Robert Bragg16d98b32016-12-07 21:40:33 +00001859/**
1860 * read_properties_unlocked - validate + copy userspace stream open properties
1861 * @dev_priv: i915 device instance
1862 * @uprops: The array of u64 key value pairs given by userspace
1863 * @n_props: The number of key value pairs expected in @uprops
1864 * @props: The stream configuration built up while validating properties
Robert Braggeec688e2016-11-07 19:49:47 +00001865 *
1866 * Note this function only validates properties in isolation it doesn't
1867 * validate that the combination of properties makes sense or that all
1868 * properties necessary for a particular kind of stream have been set.
Robert Bragg16d98b32016-12-07 21:40:33 +00001869 *
1870 * Note that there currently aren't any ordering requirements for properties so
1871 * we shouldn't validate or assume anything about ordering here. This doesn't
1872 * rule out defining new properties with ordering requirements in the future.
Robert Braggeec688e2016-11-07 19:49:47 +00001873 */
1874static int read_properties_unlocked(struct drm_i915_private *dev_priv,
1875 u64 __user *uprops,
1876 u32 n_props,
1877 struct perf_open_properties *props)
1878{
1879 u64 __user *uprop = uprops;
1880 int i;
1881
1882 memset(props, 0, sizeof(struct perf_open_properties));
1883
1884 if (!n_props) {
Robert Bragg77085502016-12-01 17:21:52 +00001885 DRM_DEBUG("No i915 perf properties given\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001886 return -EINVAL;
1887 }
1888
1889 /* Considering that ID = 0 is reserved and assuming that we don't
1890 * (currently) expect any configurations to ever specify duplicate
1891 * values for a particular property ID then the last _PROP_MAX value is
1892 * one greater than the maximum number of properties we expect to get
1893 * from userspace.
1894 */
1895 if (n_props >= DRM_I915_PERF_PROP_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001896 DRM_DEBUG("More i915 perf properties specified than exist\n");
Robert Braggeec688e2016-11-07 19:49:47 +00001897 return -EINVAL;
1898 }
1899
1900 for (i = 0; i < n_props; i++) {
Robert Bragg00319ba2016-11-07 19:49:55 +00001901 u64 oa_period, oa_freq_hz;
Robert Braggeec688e2016-11-07 19:49:47 +00001902 u64 id, value;
1903 int ret;
1904
1905 ret = get_user(id, uprop);
1906 if (ret)
1907 return ret;
1908
1909 ret = get_user(value, uprop + 1);
1910 if (ret)
1911 return ret;
1912
Matthew Auld0a309f92017-03-27 21:32:36 +01001913 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
1914 DRM_DEBUG("Unknown i915 perf property ID\n");
1915 return -EINVAL;
1916 }
1917
Robert Braggeec688e2016-11-07 19:49:47 +00001918 switch ((enum drm_i915_perf_property_id)id) {
1919 case DRM_I915_PERF_PROP_CTX_HANDLE:
1920 props->single_context = 1;
1921 props->ctx_handle = value;
1922 break;
Robert Braggd7965152016-11-07 19:49:52 +00001923 case DRM_I915_PERF_PROP_SAMPLE_OA:
1924 props->sample_flags |= SAMPLE_OA_REPORT;
1925 break;
1926 case DRM_I915_PERF_PROP_OA_METRICS_SET:
1927 if (value == 0 ||
1928 value > dev_priv->perf.oa.n_builtin_sets) {
Robert Bragg77085502016-12-01 17:21:52 +00001929 DRM_DEBUG("Unknown OA metric set ID\n");
Robert Braggd7965152016-11-07 19:49:52 +00001930 return -EINVAL;
1931 }
1932 props->metrics_set = value;
1933 break;
1934 case DRM_I915_PERF_PROP_OA_FORMAT:
1935 if (value == 0 || value >= I915_OA_FORMAT_MAX) {
Robert Bragg52c57c22017-05-11 16:43:29 +01001936 DRM_DEBUG("Out-of-range OA report format %llu\n",
1937 value);
Robert Braggd7965152016-11-07 19:49:52 +00001938 return -EINVAL;
1939 }
1940 if (!dev_priv->perf.oa.oa_formats[value].size) {
Robert Bragg52c57c22017-05-11 16:43:29 +01001941 DRM_DEBUG("Unsupported OA report format %llu\n",
1942 value);
Robert Braggd7965152016-11-07 19:49:52 +00001943 return -EINVAL;
1944 }
1945 props->oa_format = value;
1946 break;
1947 case DRM_I915_PERF_PROP_OA_EXPONENT:
1948 if (value > OA_EXPONENT_MAX) {
Robert Bragg77085502016-12-01 17:21:52 +00001949 DRM_DEBUG("OA timer exponent too high (> %u)\n",
1950 OA_EXPONENT_MAX);
Robert Braggd7965152016-11-07 19:49:52 +00001951 return -EINVAL;
1952 }
1953
Robert Bragg00319ba2016-11-07 19:49:55 +00001954 /* Theoretically we can program the OA unit to sample
Robert Braggd7965152016-11-07 19:49:52 +00001955 * every 160ns but don't allow that by default unless
1956 * root.
1957 *
Robert Bragg00319ba2016-11-07 19:49:55 +00001958 * On Haswell the period is derived from the exponent
1959 * as:
1960 *
1961 * period = 80ns * 2^(exponent + 1)
Robert Braggd7965152016-11-07 19:49:52 +00001962 */
Robert Bragg00319ba2016-11-07 19:49:55 +00001963 BUILD_BUG_ON(sizeof(oa_period) != 8);
1964 oa_period = 80ull * (2ull << value);
1965
1966 /* This check is primarily to ensure that oa_period <=
1967 * UINT32_MAX (before passing to do_div which only
1968 * accepts a u32 denominator), but we can also skip
1969 * checking anything < 1Hz which implicitly can't be
1970 * limited via an integer oa_max_sample_rate.
1971 */
1972 if (oa_period <= NSEC_PER_SEC) {
1973 u64 tmp = NSEC_PER_SEC;
1974 do_div(tmp, oa_period);
1975 oa_freq_hz = tmp;
1976 } else
1977 oa_freq_hz = 0;
1978
1979 if (oa_freq_hz > i915_oa_max_sample_rate &&
1980 !capable(CAP_SYS_ADMIN)) {
Robert Bragg77085502016-12-01 17:21:52 +00001981 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 +00001982 i915_oa_max_sample_rate);
Robert Braggd7965152016-11-07 19:49:52 +00001983 return -EACCES;
1984 }
1985
1986 props->oa_periodic = true;
1987 props->oa_period_exponent = value;
1988 break;
Matthew Auld0a309f92017-03-27 21:32:36 +01001989 case DRM_I915_PERF_PROP_MAX:
Robert Braggeec688e2016-11-07 19:49:47 +00001990 MISSING_CASE(id);
Robert Braggeec688e2016-11-07 19:49:47 +00001991 return -EINVAL;
1992 }
1993
1994 uprop += 2;
1995 }
1996
1997 return 0;
1998}
1999
Robert Bragg16d98b32016-12-07 21:40:33 +00002000/**
2001 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
2002 * @dev: drm device
2003 * @data: ioctl data copied from userspace (unvalidated)
2004 * @file: drm file
2005 *
2006 * Validates the stream open parameters given by userspace including flags
2007 * and an array of u64 key, value pair properties.
2008 *
2009 * Very little is assumed up front about the nature of the stream being
2010 * opened (for instance we don't assume it's for periodic OA unit metrics). An
2011 * i915-perf stream is expected to be a suitable interface for other forms of
2012 * buffered data written by the GPU besides periodic OA metrics.
2013 *
2014 * Note we copy the properties from userspace outside of the i915 perf
2015 * mutex to avoid an awkward lockdep with mmap_sem.
2016 *
2017 * Most of the implementation details are handled by
2018 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
2019 * mutex for serializing with any non-file-operation driver hooks.
2020 *
2021 * Return: A newly opened i915 Perf stream file descriptor or negative
2022 * error code on failure.
2023 */
Robert Braggeec688e2016-11-07 19:49:47 +00002024int i915_perf_open_ioctl(struct drm_device *dev, void *data,
2025 struct drm_file *file)
2026{
2027 struct drm_i915_private *dev_priv = dev->dev_private;
2028 struct drm_i915_perf_open_param *param = data;
2029 struct perf_open_properties props;
2030 u32 known_open_flags;
2031 int ret;
2032
2033 if (!dev_priv->perf.initialized) {
Robert Bragg77085502016-12-01 17:21:52 +00002034 DRM_DEBUG("i915 perf interface not available for this system\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002035 return -ENOTSUPP;
2036 }
2037
2038 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
2039 I915_PERF_FLAG_FD_NONBLOCK |
2040 I915_PERF_FLAG_DISABLED;
2041 if (param->flags & ~known_open_flags) {
Robert Bragg77085502016-12-01 17:21:52 +00002042 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
Robert Braggeec688e2016-11-07 19:49:47 +00002043 return -EINVAL;
2044 }
2045
2046 ret = read_properties_unlocked(dev_priv,
2047 u64_to_user_ptr(param->properties_ptr),
2048 param->num_properties,
2049 &props);
2050 if (ret)
2051 return ret;
2052
2053 mutex_lock(&dev_priv->perf.lock);
2054 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
2055 mutex_unlock(&dev_priv->perf.lock);
2056
2057 return ret;
2058}
2059
Robert Bragg16d98b32016-12-07 21:40:33 +00002060/**
2061 * i915_perf_register - exposes i915-perf to userspace
2062 * @dev_priv: i915 device instance
2063 *
2064 * In particular OA metric sets are advertised under a sysfs metrics/
2065 * directory allowing userspace to enumerate valid IDs that can be
2066 * used to open an i915-perf stream.
2067 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002068void i915_perf_register(struct drm_i915_private *dev_priv)
2069{
2070 if (!IS_HASWELL(dev_priv))
2071 return;
2072
2073 if (!dev_priv->perf.initialized)
2074 return;
2075
2076 /* To be sure we're synchronized with an attempted
2077 * i915_perf_open_ioctl(); considering that we register after
2078 * being exposed to userspace.
2079 */
2080 mutex_lock(&dev_priv->perf.lock);
2081
2082 dev_priv->perf.metrics_kobj =
2083 kobject_create_and_add("metrics",
2084 &dev_priv->drm.primary->kdev->kobj);
2085 if (!dev_priv->perf.metrics_kobj)
2086 goto exit;
2087
2088 if (i915_perf_register_sysfs_hsw(dev_priv)) {
2089 kobject_put(dev_priv->perf.metrics_kobj);
2090 dev_priv->perf.metrics_kobj = NULL;
2091 }
2092
2093exit:
2094 mutex_unlock(&dev_priv->perf.lock);
2095}
2096
Robert Bragg16d98b32016-12-07 21:40:33 +00002097/**
2098 * i915_perf_unregister - hide i915-perf from userspace
2099 * @dev_priv: i915 device instance
2100 *
2101 * i915-perf state cleanup is split up into an 'unregister' and
2102 * 'deinit' phase where the interface is first hidden from
2103 * userspace by i915_perf_unregister() before cleaning up
2104 * remaining state in i915_perf_fini().
2105 */
Robert Bragg442b8c02016-11-07 19:49:53 +00002106void i915_perf_unregister(struct drm_i915_private *dev_priv)
2107{
2108 if (!IS_HASWELL(dev_priv))
2109 return;
2110
2111 if (!dev_priv->perf.metrics_kobj)
2112 return;
2113
2114 i915_perf_unregister_sysfs_hsw(dev_priv);
2115
2116 kobject_put(dev_priv->perf.metrics_kobj);
2117 dev_priv->perf.metrics_kobj = NULL;
2118}
2119
Robert Braggccdf6342016-11-07 19:49:54 +00002120static struct ctl_table oa_table[] = {
2121 {
2122 .procname = "perf_stream_paranoid",
2123 .data = &i915_perf_stream_paranoid,
2124 .maxlen = sizeof(i915_perf_stream_paranoid),
2125 .mode = 0644,
2126 .proc_handler = proc_dointvec_minmax,
2127 .extra1 = &zero,
2128 .extra2 = &one,
2129 },
Robert Bragg00319ba2016-11-07 19:49:55 +00002130 {
2131 .procname = "oa_max_sample_rate",
2132 .data = &i915_oa_max_sample_rate,
2133 .maxlen = sizeof(i915_oa_max_sample_rate),
2134 .mode = 0644,
2135 .proc_handler = proc_dointvec_minmax,
2136 .extra1 = &zero,
2137 .extra2 = &oa_sample_rate_hard_limit,
2138 },
Robert Braggccdf6342016-11-07 19:49:54 +00002139 {}
2140};
2141
2142static struct ctl_table i915_root[] = {
2143 {
2144 .procname = "i915",
2145 .maxlen = 0,
2146 .mode = 0555,
2147 .child = oa_table,
2148 },
2149 {}
2150};
2151
2152static struct ctl_table dev_root[] = {
2153 {
2154 .procname = "dev",
2155 .maxlen = 0,
2156 .mode = 0555,
2157 .child = i915_root,
2158 },
2159 {}
2160};
2161
Robert Bragg16d98b32016-12-07 21:40:33 +00002162/**
2163 * i915_perf_init - initialize i915-perf state on module load
2164 * @dev_priv: i915 device instance
2165 *
2166 * Initializes i915-perf state without exposing anything to userspace.
2167 *
2168 * Note: i915-perf initialization is split into an 'init' and 'register'
2169 * phase with the i915_perf_register() exposing state to userspace.
2170 */
Robert Braggeec688e2016-11-07 19:49:47 +00002171void i915_perf_init(struct drm_i915_private *dev_priv)
2172{
Robert Braggd7965152016-11-07 19:49:52 +00002173 if (!IS_HASWELL(dev_priv))
2174 return;
2175
2176 hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
2177 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
2178 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
2179 init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
2180
Robert Braggeec688e2016-11-07 19:49:47 +00002181 INIT_LIST_HEAD(&dev_priv->perf.streams);
2182 mutex_init(&dev_priv->perf.lock);
Robert Braggd7965152016-11-07 19:49:52 +00002183 spin_lock_init(&dev_priv->perf.hook_lock);
Robert Bragg0dd860c2017-05-11 16:43:28 +01002184 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
Robert Braggd7965152016-11-07 19:49:52 +00002185
2186 dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
2187 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
2188 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
2189 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
2190 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
2191 dev_priv->perf.oa.ops.read = gen7_oa_read;
Robert Bragg0dd860c2017-05-11 16:43:28 +01002192 dev_priv->perf.oa.ops.oa_buffer_check =
2193 gen7_oa_buffer_check_unlocked;
Robert Braggd7965152016-11-07 19:49:52 +00002194
2195 dev_priv->perf.oa.oa_formats = hsw_oa_formats;
2196
2197 dev_priv->perf.oa.n_builtin_sets =
2198 i915_oa_n_builtin_metric_sets_hsw;
Robert Braggeec688e2016-11-07 19:49:47 +00002199
Robert Braggccdf6342016-11-07 19:49:54 +00002200 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
2201
Robert Braggeec688e2016-11-07 19:49:47 +00002202 dev_priv->perf.initialized = true;
2203}
2204
Robert Bragg16d98b32016-12-07 21:40:33 +00002205/**
2206 * i915_perf_fini - Counter part to i915_perf_init()
2207 * @dev_priv: i915 device instance
2208 */
Robert Braggeec688e2016-11-07 19:49:47 +00002209void i915_perf_fini(struct drm_i915_private *dev_priv)
2210{
2211 if (!dev_priv->perf.initialized)
2212 return;
2213
Robert Braggccdf6342016-11-07 19:49:54 +00002214 unregister_sysctl_table(dev_priv->perf.sysctl_header);
2215
Robert Braggd7965152016-11-07 19:49:52 +00002216 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
Robert Braggeec688e2016-11-07 19:49:47 +00002217 dev_priv->perf.initialized = false;
2218}