1 /* 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 27 28 /** 29 * DOC: i915 Perf Overview 30 * 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 * 48 */ 49 50 /** 51 * DOC: i915 Perf History and Comparison with Core Perf 52 * 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 * 82 * Issues hit with first prototype based on Core Perf 83 * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 84 * 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 * 142 * - As a side note on perf's grouping feature; there was also some concern 143 * 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 194 #include <linux/anon_inodes.h> 195 #include <linux/sizes.h> 196 #include <linux/uuid.h> 197 198 #include "i915_drv.h" 199 #include "i915_oa_hsw.h" 200 #include "i915_oa_bdw.h" 201 #include "i915_oa_chv.h" 202 #include "i915_oa_sklgt2.h" 203 #include "i915_oa_sklgt3.h" 204 #include "i915_oa_sklgt4.h" 205 #include "i915_oa_bxt.h" 206 #include "i915_oa_kblgt2.h" 207 #include "i915_oa_kblgt3.h" 208 #include "i915_oa_glk.h" 209 #include "i915_oa_cflgt2.h" 210 #include "i915_oa_cflgt3.h" 211 #include "i915_oa_cnl.h" 212 #include "i915_oa_icl.h" 213 #include "intel_lrc_reg.h" 214 215 #define OA_TAKEN(tail, head) (((tail) - (head)) & (dev_priv->perf.oa.oa_buffer.vma->size - 1)) 216 217 /** 218 * DOC: OA Tail Pointer Race 219 * 220 * There's a HW race condition between OA unit tail pointer register updates and 221 * writes to memory whereby the tail pointer can sometimes get ahead of what's 222 * been written out to the OA buffer so far (in terms of what's visible to the 223 * CPU). 224 * 225 * Although this can be observed explicitly while copying reports to userspace 226 * by checking for a zeroed report-id field in tail reports, we want to account 227 * for this earlier, as part of the oa_buffer_check to avoid lots of redundant 228 * read() attempts. 229 * 230 * In effect we define a tail pointer for reading that lags the real tail 231 * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough 232 * time for the corresponding reports to become visible to the CPU. 233 * 234 * To manage this we actually track two tail pointers: 235 * 1) An 'aging' tail with an associated timestamp that is tracked until we 236 * can trust the corresponding data is visible to the CPU; at which point 237 * it is considered 'aged'. 238 * 2) An 'aged' tail that can be used for read()ing. 239 * 240 * The two separate pointers let us decouple read()s from tail pointer aging. 241 * 242 * The tail pointers are checked and updated at a limited rate within a hrtimer 243 * callback (the same callback that is used for delivering EPOLLIN events) 244 * 245 * Initially the tails are marked invalid with %INVALID_TAIL_PTR which 246 * indicates that an updated tail pointer is needed. 247 * 248 * Most of the implementation details for this workaround are in 249 * oa_buffer_check_unlocked() and _append_oa_reports() 250 * 251 * Note for posterity: previously the driver used to define an effective tail 252 * pointer that lagged the real pointer by a 'tail margin' measured in bytes 253 * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency. 254 * This was flawed considering that the OA unit may also automatically generate 255 * non-periodic reports (such as on context switch) or the OA unit may be 256 * enabled without any periodic sampling. 257 */ 258 #define OA_TAIL_MARGIN_NSEC 100000ULL 259 #define INVALID_TAIL_PTR 0xffffffff 260 261 /* frequency for checking whether the OA unit has written new reports to the 262 * circular OA buffer... 263 */ 264 #define POLL_FREQUENCY 200 265 #define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY) 266 267 /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */ 268 static int zero; 269 static int one = 1; 270 static u32 i915_perf_stream_paranoid = true; 271 272 /* The maximum exponent the hardware accepts is 63 (essentially it selects one 273 * of the 64bit timestamp bits to trigger reports from) but there's currently 274 * no known use case for sampling as infrequently as once per 47 thousand years. 275 * 276 * Since the timestamps included in OA reports are only 32bits it seems 277 * reasonable to limit the OA exponent where it's still possible to account for 278 * overflow in OA report timestamps. 279 */ 280 #define OA_EXPONENT_MAX 31 281 282 #define INVALID_CTX_ID 0xffffffff 283 284 /* On Gen8+ automatically triggered OA reports include a 'reason' field... */ 285 #define OAREPORT_REASON_MASK 0x3f 286 #define OAREPORT_REASON_SHIFT 19 287 #define OAREPORT_REASON_TIMER (1<<0) 288 #define OAREPORT_REASON_CTX_SWITCH (1<<3) 289 #define OAREPORT_REASON_CLK_RATIO (1<<5) 290 291 292 /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate 293 * 294 * The highest sampling frequency we can theoretically program the OA unit 295 * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell. 296 * 297 * Initialized just before we register the sysctl parameter. 298 */ 299 static int oa_sample_rate_hard_limit; 300 301 /* Theoretically we can program the OA unit to sample every 160ns but don't 302 * allow that by default unless root... 303 * 304 * The default threshold of 100000Hz is based on perf's similar 305 * kernel.perf_event_max_sample_rate sysctl parameter. 306 */ 307 static u32 i915_oa_max_sample_rate = 100000; 308 309 /* XXX: beware if future OA HW adds new report formats that the current 310 * code assumes all reports have a power-of-two size and ~(size - 1) can 311 * be used as a mask to align the OA tail pointer. 312 */ 313 static const struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = { 314 [I915_OA_FORMAT_A13] = { 0, 64 }, 315 [I915_OA_FORMAT_A29] = { 1, 128 }, 316 [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 }, 317 /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */ 318 [I915_OA_FORMAT_B4_C8] = { 4, 64 }, 319 [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 }, 320 [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 }, 321 [I915_OA_FORMAT_C4_B8] = { 7, 64 }, 322 }; 323 324 static const struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = { 325 [I915_OA_FORMAT_A12] = { 0, 64 }, 326 [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 }, 327 [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 }, 328 [I915_OA_FORMAT_C4_B8] = { 7, 64 }, 329 }; 330 331 #define SAMPLE_OA_REPORT (1<<0) 332 333 /** 334 * struct perf_open_properties - for validated properties given to open a stream 335 * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags 336 * @single_context: Whether a single or all gpu contexts should be monitored 337 * @ctx_handle: A gem ctx handle for use with @single_context 338 * @metrics_set: An ID for an OA unit metric set advertised via sysfs 339 * @oa_format: An OA unit HW report format 340 * @oa_periodic: Whether to enable periodic OA unit sampling 341 * @oa_period_exponent: The OA unit sampling period is derived from this 342 * @oa_buffer_size_exponent: The OA buffer size is derived from this 343 * 344 * As read_properties_unlocked() enumerates and validates the properties given 345 * to open a stream of metrics the configuration is built up in the structure 346 * which starts out zero initialized. 347 */ 348 struct perf_open_properties { 349 u32 sample_flags; 350 351 u64 single_context:1; 352 u64 ctx_handle; 353 354 /* OA sampling state */ 355 int metrics_set; 356 int oa_format; 357 bool oa_periodic; 358 int oa_period_exponent; 359 u32 oa_buffer_size_exponent; 360 }; 361 362 static void free_oa_config(struct drm_i915_private *dev_priv, 363 struct i915_oa_config *oa_config) 364 { 365 if (!PTR_ERR(oa_config->flex_regs)) 366 kfree(oa_config->flex_regs); 367 if (!PTR_ERR(oa_config->b_counter_regs)) 368 kfree(oa_config->b_counter_regs); 369 if (!PTR_ERR(oa_config->mux_regs)) 370 kfree(oa_config->mux_regs); 371 kfree(oa_config); 372 } 373 374 static void put_oa_config(struct drm_i915_private *dev_priv, 375 struct i915_oa_config *oa_config) 376 { 377 if (!atomic_dec_and_test(&oa_config->ref_count)) 378 return; 379 380 free_oa_config(dev_priv, oa_config); 381 } 382 383 static int get_oa_config(struct drm_i915_private *dev_priv, 384 int metrics_set, 385 struct i915_oa_config **out_config) 386 { 387 int ret; 388 389 if (metrics_set == 1) { 390 *out_config = &dev_priv->perf.oa.test_config; 391 atomic_inc(&dev_priv->perf.oa.test_config.ref_count); 392 return 0; 393 } 394 395 ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock); 396 if (ret) 397 return ret; 398 399 *out_config = idr_find(&dev_priv->perf.metrics_idr, metrics_set); 400 if (!*out_config) 401 ret = -EINVAL; 402 else 403 atomic_inc(&(*out_config)->ref_count); 404 405 mutex_unlock(&dev_priv->perf.metrics_lock); 406 407 return ret; 408 } 409 410 static u32 gen8_oa_hw_tail_read(struct drm_i915_private *dev_priv) 411 { 412 return I915_READ(GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK; 413 } 414 415 static u32 gen7_oa_hw_tail_read(struct drm_i915_private *dev_priv) 416 { 417 u32 oastatus1 = I915_READ(GEN7_OASTATUS1); 418 419 return oastatus1 & GEN7_OASTATUS1_TAIL_MASK; 420 } 421 422 /** 423 * oa_buffer_check_unlocked - check for data and update tail ptr state 424 * @dev_priv: i915 device instance 425 * 426 * This is either called via fops (for blocking reads in user ctx) or the poll 427 * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check 428 * if there is data available for userspace to read. 429 * 430 * This function is central to providing a workaround for the OA unit tail 431 * pointer having a race with respect to what data is visible to the CPU. 432 * It is responsible for reading tail pointers from the hardware and giving 433 * the pointers time to 'age' before they are made available for reading. 434 * (See description of OA_TAIL_MARGIN_NSEC above for further details.) 435 * 436 * Besides returning true when there is data available to read() this function 437 * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp 438 * and .aged_tail_idx state used for reading. 439 * 440 * Note: It's safe to read OA config state here unlocked, assuming that this is 441 * only called while the stream is enabled, while the global OA configuration 442 * can't be modified. 443 * 444 * Returns: %true if the OA buffer contains data, else %false 445 */ 446 static bool oa_buffer_check_unlocked(struct drm_i915_private *dev_priv) 447 { 448 int report_size = dev_priv->perf.oa.oa_buffer.format_size; 449 unsigned long flags; 450 unsigned int aged_idx; 451 u32 head, hw_tail, aged_tail, aging_tail; 452 u64 now; 453 454 /* We have to consider the (unlikely) possibility that read() errors 455 * could result in an OA buffer reset which might reset the head, 456 * tails[] and aged_tail state. 457 */ 458 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 459 460 /* NB: The head we observe here might effectively be a little out of 461 * date (between head and tails[aged_idx].offset if there is currently 462 * a read() in progress. 463 */ 464 head = dev_priv->perf.oa.oa_buffer.head; 465 466 aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx; 467 aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset; 468 aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset; 469 470 hw_tail = dev_priv->perf.oa.ops.oa_hw_tail_read(dev_priv); 471 472 /* The tail pointer increases in 64 byte increments, 473 * not in report_size steps... 474 */ 475 hw_tail &= ~(report_size - 1); 476 477 now = ktime_get_mono_fast_ns(); 478 479 /* Update the aged tail 480 * 481 * Flip the tail pointer available for read()s once the aging tail is 482 * old enough to trust that the corresponding data will be visible to 483 * the CPU... 484 * 485 * Do this before updating the aging pointer in case we may be able to 486 * immediately start aging a new pointer too (if new data has become 487 * available) without needing to wait for a later hrtimer callback. 488 */ 489 if (aging_tail != INVALID_TAIL_PTR && 490 ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) > 491 OA_TAIL_MARGIN_NSEC)) { 492 493 aged_idx ^= 1; 494 dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx; 495 496 aged_tail = aging_tail; 497 498 /* Mark that we need a new pointer to start aging... */ 499 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR; 500 aging_tail = INVALID_TAIL_PTR; 501 } 502 503 /* Update the aging tail 504 * 505 * We throttle aging tail updates until we have a new tail that 506 * represents >= one report more data than is already available for 507 * reading. This ensures there will be enough data for a successful 508 * read once this new pointer has aged and ensures we will give the new 509 * pointer time to age. 510 */ 511 if (aging_tail == INVALID_TAIL_PTR && 512 (aged_tail == INVALID_TAIL_PTR || 513 OA_TAKEN(hw_tail, aged_tail) >= report_size)) { 514 struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma; 515 u32 gtt_offset = i915_ggtt_offset(vma); 516 517 /* Be paranoid and do a bounds check on the pointer read back 518 * from hardware, just in case some spurious hardware condition 519 * could put the tail out of bounds... 520 */ 521 if (hw_tail >= gtt_offset && 522 hw_tail < (gtt_offset + dev_priv->perf.oa.oa_buffer.vma->size)) { 523 dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = 524 aging_tail = hw_tail; 525 dev_priv->perf.oa.oa_buffer.aging_timestamp = now; 526 } else { 527 DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n", 528 hw_tail); 529 } 530 } 531 532 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 533 534 return aged_tail == INVALID_TAIL_PTR ? 535 false : OA_TAKEN(aged_tail, head) >= report_size; 536 } 537 538 /** 539 * append_oa_status - Appends a status record to a userspace read() buffer. 540 * @stream: An i915-perf stream opened for OA metrics 541 * @buf: destination buffer given by userspace 542 * @count: the number of bytes userspace wants to read 543 * @offset: (inout): the current position for writing into @buf 544 * @type: The kind of status to report to userspace 545 * 546 * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`) 547 * into the userspace read() buffer. 548 * 549 * The @buf @offset will only be updated on success. 550 * 551 * Returns: 0 on success, negative error code on failure. 552 */ 553 static int append_oa_status(struct i915_perf_stream *stream, 554 char __user *buf, 555 size_t count, 556 size_t *offset, 557 enum drm_i915_perf_record_type type) 558 { 559 struct drm_i915_perf_record_header header = { type, 0, sizeof(header) }; 560 561 if ((count - *offset) < header.size) 562 return -ENOSPC; 563 564 if (copy_to_user(buf + *offset, &header, sizeof(header))) 565 return -EFAULT; 566 567 (*offset) += header.size; 568 569 return 0; 570 } 571 572 /** 573 * append_oa_sample - Copies single OA report into userspace read() buffer. 574 * @stream: An i915-perf stream opened for OA metrics 575 * @buf: destination buffer given by userspace 576 * @count: the number of bytes userspace wants to read 577 * @offset: (inout): the current position for writing into @buf 578 * @report: A single OA report to (optionally) include as part of the sample 579 * 580 * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*` 581 * properties when opening a stream, tracked as `stream->sample_flags`. This 582 * function copies the requested components of a single sample to the given 583 * read() @buf. 584 * 585 * The @buf @offset will only be updated on success. 586 * 587 * Returns: 0 on success, negative error code on failure. 588 */ 589 static int append_oa_sample(struct i915_perf_stream *stream, 590 char __user *buf, 591 size_t count, 592 size_t *offset, 593 const u8 *report) 594 { 595 struct drm_i915_private *dev_priv = stream->dev_priv; 596 int report_size = dev_priv->perf.oa.oa_buffer.format_size; 597 struct drm_i915_perf_record_header header; 598 u32 sample_flags = stream->sample_flags; 599 600 header.type = DRM_I915_PERF_RECORD_SAMPLE; 601 header.pad = 0; 602 header.size = stream->sample_size; 603 604 if ((count - *offset) < header.size) 605 return -ENOSPC; 606 607 buf += *offset; 608 if (copy_to_user(buf, &header, sizeof(header))) 609 return -EFAULT; 610 buf += sizeof(header); 611 612 if (sample_flags & SAMPLE_OA_REPORT) { 613 if (copy_to_user(buf, report, report_size)) 614 return -EFAULT; 615 } 616 617 (*offset) += header.size; 618 619 return 0; 620 } 621 622 /** 623 * Copies all buffered OA reports into userspace read() buffer. 624 * @stream: An i915-perf stream opened for OA metrics 625 * @buf: destination buffer given by userspace 626 * @count: the number of bytes userspace wants to read 627 * @offset: (inout): the current position for writing into @buf 628 * 629 * Notably any error condition resulting in a short read (-%ENOSPC or 630 * -%EFAULT) will be returned even though one or more records may 631 * have been successfully copied. In this case it's up to the caller 632 * to decide if the error should be squashed before returning to 633 * userspace. 634 * 635 * Note: reports are consumed from the head, and appended to the 636 * tail, so the tail chases the head?... If you think that's mad 637 * and back-to-front you're not alone, but this follows the 638 * Gen PRM naming convention. 639 * 640 * Returns: 0 on success, negative error code on failure. 641 */ 642 static int gen8_append_oa_reports(struct i915_perf_stream *stream, 643 char __user *buf, 644 size_t count, 645 size_t *offset) 646 { 647 struct drm_i915_private *dev_priv = stream->dev_priv; 648 int report_size = dev_priv->perf.oa.oa_buffer.format_size; 649 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr; 650 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma); 651 u32 mask = (dev_priv->perf.oa.oa_buffer.vma->size - 1); 652 size_t start_offset = *offset; 653 unsigned long flags; 654 unsigned int aged_tail_idx; 655 u32 head, tail; 656 u32 taken; 657 int ret = 0; 658 659 if (WARN_ON(!stream->enabled)) 660 return -EIO; 661 662 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 663 664 head = dev_priv->perf.oa.oa_buffer.head; 665 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx; 666 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset; 667 668 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 669 670 /* 671 * An invalid tail pointer here means we're still waiting for the poll 672 * hrtimer callback to give us a pointer 673 */ 674 if (tail == INVALID_TAIL_PTR) 675 return -EAGAIN; 676 677 /* 678 * NB: oa_buffer.head/tail include the gtt_offset which we don't want 679 * while indexing relative to oa_buf_base. 680 */ 681 head -= gtt_offset; 682 tail -= gtt_offset; 683 684 /* 685 * An out of bounds or misaligned head or tail pointer implies a driver 686 * bug since we validate + align the tail pointers we read from the 687 * hardware and we are in full control of the head pointer which should 688 * only be incremented by multiples of the report size (notably also 689 * all a power of two). 690 */ 691 if (WARN_ONCE(head > dev_priv->perf.oa.oa_buffer.vma->size || head % report_size || 692 tail > dev_priv->perf.oa.oa_buffer.vma->size || tail % report_size, 693 "Inconsistent OA buffer pointers: head = %u, tail = %u\n", 694 head, tail)) 695 return -EIO; 696 697 698 for (/* none */; 699 (taken = OA_TAKEN(tail, head)); 700 head = (head + report_size) & mask) { 701 u8 *report = oa_buf_base + head; 702 u32 *report32 = (void *)report; 703 u32 ctx_id; 704 u32 reason; 705 706 /* 707 * All the report sizes factor neatly into the buffer 708 * size so we never expect to see a report split 709 * between the beginning and end of the buffer. 710 * 711 * Given the initial alignment check a misalignment 712 * here would imply a driver bug that would result 713 * in an overrun. 714 */ 715 if (WARN_ON((dev_priv->perf.oa.oa_buffer.vma->size - head) < report_size)) { 716 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n"); 717 break; 718 } 719 720 /* 721 * The reason field includes flags identifying what 722 * triggered this specific report (mostly timer 723 * triggered or e.g. due to a context switch). 724 * 725 * This field is never expected to be zero so we can 726 * check that the report isn't invalid before copying 727 * it to userspace... 728 */ 729 reason = ((report32[0] >> OAREPORT_REASON_SHIFT) & 730 OAREPORT_REASON_MASK); 731 if (reason == 0) { 732 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs)) 733 DRM_NOTE("Skipping spurious, invalid OA report\n"); 734 continue; 735 } 736 737 ctx_id = report32[2] & dev_priv->perf.oa.specific_ctx_id_mask; 738 739 /* 740 * Squash whatever is in the CTX_ID field if it's marked as 741 * invalid to be sure we avoid false-positive, single-context 742 * filtering below... 743 * 744 * Note: that we don't clear the valid_ctx_bit so userspace can 745 * understand that the ID has been squashed by the kernel. 746 */ 747 if (!(report32[0] & dev_priv->perf.oa.gen8_valid_ctx_bit)) 748 ctx_id = report32[2] = INVALID_CTX_ID; 749 750 /* 751 * NB: For Gen 8 the OA unit no longer supports clock gating 752 * off for a specific context and the kernel can't securely 753 * stop the counters from updating as system-wide / global 754 * values. 755 * 756 * Automatic reports now include a context ID so reports can be 757 * filtered on the cpu but it's not worth trying to 758 * automatically subtract/hide counter progress for other 759 * contexts while filtering since we can't stop userspace 760 * issuing MI_REPORT_PERF_COUNT commands which would still 761 * provide a side-band view of the real values. 762 * 763 * To allow userspace (such as Mesa/GL_INTEL_performance_query) 764 * to normalize counters for a single filtered context then it 765 * needs be forwarded bookend context-switch reports so that it 766 * can track switches in between MI_REPORT_PERF_COUNT commands 767 * and can itself subtract/ignore the progress of counters 768 * associated with other contexts. Note that the hardware 769 * automatically triggers reports when switching to a new 770 * context which are tagged with the ID of the newly active 771 * context. To avoid the complexity (and likely fragility) of 772 * reading ahead while parsing reports to try and minimize 773 * forwarding redundant context switch reports (i.e. between 774 * other, unrelated contexts) we simply elect to forward them 775 * all. 776 * 777 * We don't rely solely on the reason field to identify context 778 * switches since it's not-uncommon for periodic samples to 779 * identify a switch before any 'context switch' report. 780 */ 781 if (!dev_priv->perf.oa.exclusive_stream->ctx || 782 dev_priv->perf.oa.specific_ctx_id == ctx_id || 783 (dev_priv->perf.oa.oa_buffer.last_ctx_id == 784 dev_priv->perf.oa.specific_ctx_id) || 785 reason & OAREPORT_REASON_CTX_SWITCH) { 786 787 /* 788 * While filtering for a single context we avoid 789 * leaking the IDs of other contexts. 790 */ 791 if (dev_priv->perf.oa.exclusive_stream->ctx && 792 dev_priv->perf.oa.specific_ctx_id != ctx_id) { 793 report32[2] = INVALID_CTX_ID; 794 } 795 796 ret = append_oa_sample(stream, buf, count, offset, 797 report); 798 if (ret) 799 break; 800 801 dev_priv->perf.oa.oa_buffer.last_ctx_id = ctx_id; 802 } 803 804 /* 805 * The above reason field sanity check is based on 806 * the assumption that the OA buffer is initially 807 * zeroed and we reset the field after copying so the 808 * check is still meaningful once old reports start 809 * being overwritten. 810 */ 811 report32[0] = 0; 812 } 813 814 if (start_offset != *offset) { 815 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 816 817 /* 818 * We removed the gtt_offset for the copy loop above, indexing 819 * relative to oa_buf_base so put back here... 820 */ 821 head += gtt_offset; 822 823 I915_WRITE(GEN8_OAHEADPTR, head & GEN8_OAHEADPTR_MASK); 824 dev_priv->perf.oa.oa_buffer.head = head; 825 826 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 827 } 828 829 return ret; 830 } 831 832 /** 833 * gen8_oa_read - copy status records then buffered OA reports 834 * @stream: An i915-perf stream opened for OA metrics 835 * @buf: destination buffer given by userspace 836 * @count: the number of bytes userspace wants to read 837 * @offset: (inout): the current position for writing into @buf 838 * 839 * Checks OA unit status registers and if necessary appends corresponding 840 * status records for userspace (such as for a buffer full condition) and then 841 * initiate appending any buffered OA reports. 842 * 843 * Updates @offset according to the number of bytes successfully copied into 844 * the userspace buffer. 845 * 846 * NB: some data may be successfully copied to the userspace buffer 847 * even if an error is returned, and this is reflected in the 848 * updated @offset. 849 * 850 * Returns: zero on success or a negative error code 851 */ 852 static int gen8_oa_read(struct i915_perf_stream *stream, 853 char __user *buf, 854 size_t count, 855 size_t *offset) 856 { 857 struct drm_i915_private *dev_priv = stream->dev_priv; 858 u32 oastatus; 859 int ret; 860 861 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr)) 862 return -EIO; 863 864 oastatus = I915_READ(GEN8_OASTATUS); 865 866 /* 867 * We treat OABUFFER_OVERFLOW as a significant error: 868 * 869 * Although theoretically we could handle this more gracefully 870 * sometimes, some Gens don't correctly suppress certain 871 * automatically triggered reports in this condition and so we 872 * have to assume that old reports are now being trampled 873 * over. 874 */ 875 if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) { 876 ret = append_oa_status(stream, buf, count, offset, 877 DRM_I915_PERF_RECORD_OA_BUFFER_LOST); 878 if (ret) 879 return ret; 880 881 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n", 882 dev_priv->perf.oa.period_exponent); 883 884 dev_priv->perf.oa.ops.oa_disable(stream); 885 dev_priv->perf.oa.ops.oa_enable(stream); 886 887 /* 888 * Note: .oa_enable() is expected to re-init the oabuffer and 889 * reset GEN8_OASTATUS for us 890 */ 891 oastatus = I915_READ(GEN8_OASTATUS); 892 } 893 894 if (oastatus & GEN8_OASTATUS_REPORT_LOST) { 895 ret = append_oa_status(stream, buf, count, offset, 896 DRM_I915_PERF_RECORD_OA_REPORT_LOST); 897 if (ret) 898 return ret; 899 I915_WRITE(GEN8_OASTATUS, 900 oastatus & ~GEN8_OASTATUS_REPORT_LOST); 901 } 902 903 return gen8_append_oa_reports(stream, buf, count, offset); 904 } 905 906 /** 907 * Copies all buffered OA reports into userspace read() buffer. 908 * @stream: An i915-perf stream opened for OA metrics 909 * @buf: destination buffer given by userspace 910 * @count: the number of bytes userspace wants to read 911 * @offset: (inout): the current position for writing into @buf 912 * 913 * Notably any error condition resulting in a short read (-%ENOSPC or 914 * -%EFAULT) will be returned even though one or more records may 915 * have been successfully copied. In this case it's up to the caller 916 * to decide if the error should be squashed before returning to 917 * userspace. 918 * 919 * Note: reports are consumed from the head, and appended to the 920 * tail, so the tail chases the head?... If you think that's mad 921 * and back-to-front you're not alone, but this follows the 922 * Gen PRM naming convention. 923 * 924 * Returns: 0 on success, negative error code on failure. 925 */ 926 static int gen7_append_oa_reports(struct i915_perf_stream *stream, 927 char __user *buf, 928 size_t count, 929 size_t *offset) 930 { 931 struct drm_i915_private *dev_priv = stream->dev_priv; 932 int report_size = dev_priv->perf.oa.oa_buffer.format_size; 933 u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr; 934 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma); 935 u32 mask = (dev_priv->perf.oa.oa_buffer.vma->size - 1); 936 size_t start_offset = *offset; 937 unsigned long flags; 938 unsigned int aged_tail_idx; 939 u32 head, tail; 940 u32 taken; 941 int ret = 0; 942 943 if (WARN_ON(!stream->enabled)) 944 return -EIO; 945 946 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 947 948 head = dev_priv->perf.oa.oa_buffer.head; 949 aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx; 950 tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset; 951 952 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 953 954 /* An invalid tail pointer here means we're still waiting for the poll 955 * hrtimer callback to give us a pointer 956 */ 957 if (tail == INVALID_TAIL_PTR) 958 return -EAGAIN; 959 960 /* NB: oa_buffer.head/tail include the gtt_offset which we don't want 961 * while indexing relative to oa_buf_base. 962 */ 963 head -= gtt_offset; 964 tail -= gtt_offset; 965 966 /* An out of bounds or misaligned head or tail pointer implies a driver 967 * bug since we validate + align the tail pointers we read from the 968 * hardware and we are in full control of the head pointer which should 969 * only be incremented by multiples of the report size (notably also 970 * all a power of two). 971 */ 972 if (WARN_ONCE(head > dev_priv->perf.oa.oa_buffer.vma->size || head % report_size || 973 tail > dev_priv->perf.oa.oa_buffer.vma->size || tail % report_size, 974 "Inconsistent OA buffer pointers: head = %u, tail = %u\n", 975 head, tail)) 976 return -EIO; 977 978 979 for (/* none */; 980 (taken = OA_TAKEN(tail, head)); 981 head = (head + report_size) & mask) { 982 u8 *report = oa_buf_base + head; 983 u32 *report32 = (void *)report; 984 985 /* All the report sizes factor neatly into the buffer 986 * size so we never expect to see a report split 987 * between the beginning and end of the buffer. 988 * 989 * Given the initial alignment check a misalignment 990 * here would imply a driver bug that would result 991 * in an overrun. 992 */ 993 if (WARN_ON((dev_priv->perf.oa.oa_buffer.vma->size - head) < report_size)) { 994 DRM_ERROR("Spurious OA head ptr: non-integral report offset\n"); 995 break; 996 } 997 998 /* The report-ID field for periodic samples includes 999 * some undocumented flags related to what triggered 1000 * the report and is never expected to be zero so we 1001 * can check that the report isn't invalid before 1002 * copying it to userspace... 1003 */ 1004 if (report32[0] == 0) { 1005 if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs)) 1006 DRM_NOTE("Skipping spurious, invalid OA report\n"); 1007 continue; 1008 } 1009 1010 ret = append_oa_sample(stream, buf, count, offset, report); 1011 if (ret) 1012 break; 1013 1014 /* The above report-id field sanity check is based on 1015 * the assumption that the OA buffer is initially 1016 * zeroed and we reset the field after copying so the 1017 * check is still meaningful once old reports start 1018 * being overwritten. 1019 */ 1020 report32[0] = 0; 1021 } 1022 1023 if (start_offset != *offset) { 1024 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 1025 1026 /* We removed the gtt_offset for the copy loop above, indexing 1027 * relative to oa_buf_base so put back here... 1028 */ 1029 head += gtt_offset; 1030 1031 I915_WRITE(GEN7_OASTATUS2, 1032 ((head & GEN7_OASTATUS2_HEAD_MASK) | 1033 GEN7_OASTATUS2_MEM_SELECT_GGTT)); 1034 dev_priv->perf.oa.oa_buffer.head = head; 1035 1036 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 1037 } 1038 1039 return ret; 1040 } 1041 1042 /** 1043 * gen7_oa_read - copy status records then buffered OA reports 1044 * @stream: An i915-perf stream opened for OA metrics 1045 * @buf: destination buffer given by userspace 1046 * @count: the number of bytes userspace wants to read 1047 * @offset: (inout): the current position for writing into @buf 1048 * 1049 * Checks Gen 7 specific OA unit status registers and if necessary appends 1050 * corresponding status records for userspace (such as for a buffer full 1051 * condition) and then initiate appending any buffered OA reports. 1052 * 1053 * Updates @offset according to the number of bytes successfully copied into 1054 * the userspace buffer. 1055 * 1056 * Returns: zero on success or a negative error code 1057 */ 1058 static int gen7_oa_read(struct i915_perf_stream *stream, 1059 char __user *buf, 1060 size_t count, 1061 size_t *offset) 1062 { 1063 struct drm_i915_private *dev_priv = stream->dev_priv; 1064 u32 oastatus1; 1065 int ret; 1066 1067 if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr)) 1068 return -EIO; 1069 1070 oastatus1 = I915_READ(GEN7_OASTATUS1); 1071 1072 /* XXX: On Haswell we don't have a safe way to clear oastatus1 1073 * bits while the OA unit is enabled (while the tail pointer 1074 * may be updated asynchronously) so we ignore status bits 1075 * that have already been reported to userspace. 1076 */ 1077 oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1; 1078 1079 /* We treat OABUFFER_OVERFLOW as a significant error: 1080 * 1081 * - The status can be interpreted to mean that the buffer is 1082 * currently full (with a higher precedence than OA_TAKEN() 1083 * which will start to report a near-empty buffer after an 1084 * overflow) but it's awkward that we can't clear the status 1085 * on Haswell, so without a reset we won't be able to catch 1086 * the state again. 1087 * 1088 * - Since it also implies the HW has started overwriting old 1089 * reports it may also affect our sanity checks for invalid 1090 * reports when copying to userspace that assume new reports 1091 * are being written to cleared memory. 1092 * 1093 * - In the future we may want to introduce a flight recorder 1094 * mode where the driver will automatically maintain a safe 1095 * guard band between head/tail, avoiding this overflow 1096 * condition, but we avoid the added driver complexity for 1097 * now. 1098 */ 1099 if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) { 1100 ret = append_oa_status(stream, buf, count, offset, 1101 DRM_I915_PERF_RECORD_OA_BUFFER_LOST); 1102 if (ret) 1103 return ret; 1104 1105 DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n", 1106 dev_priv->perf.oa.period_exponent); 1107 1108 dev_priv->perf.oa.ops.oa_disable(stream); 1109 dev_priv->perf.oa.ops.oa_enable(stream); 1110 1111 oastatus1 = I915_READ(GEN7_OASTATUS1); 1112 } 1113 1114 if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) { 1115 ret = append_oa_status(stream, buf, count, offset, 1116 DRM_I915_PERF_RECORD_OA_REPORT_LOST); 1117 if (ret) 1118 return ret; 1119 dev_priv->perf.oa.gen7_latched_oastatus1 |= 1120 GEN7_OASTATUS1_REPORT_LOST; 1121 } 1122 1123 return gen7_append_oa_reports(stream, buf, count, offset); 1124 } 1125 1126 /** 1127 * i915_oa_wait_unlocked - handles blocking IO until OA data available 1128 * @stream: An i915-perf stream opened for OA metrics 1129 * 1130 * Called when userspace tries to read() from a blocking stream FD opened 1131 * for OA metrics. It waits until the hrtimer callback finds a non-empty 1132 * OA buffer and wakes us. 1133 * 1134 * Note: it's acceptable to have this return with some false positives 1135 * since any subsequent read handling will return -EAGAIN if there isn't 1136 * really data ready for userspace yet. 1137 * 1138 * Returns: zero on success or a negative error code 1139 */ 1140 static int i915_oa_wait_unlocked(struct i915_perf_stream *stream) 1141 { 1142 struct drm_i915_private *dev_priv = stream->dev_priv; 1143 1144 /* We would wait indefinitely if periodic sampling is not enabled */ 1145 if (!dev_priv->perf.oa.periodic) 1146 return -EIO; 1147 1148 return wait_event_interruptible(dev_priv->perf.oa.poll_wq, 1149 oa_buffer_check_unlocked(dev_priv)); 1150 } 1151 1152 /** 1153 * i915_oa_poll_wait - call poll_wait() for an OA stream poll() 1154 * @stream: An i915-perf stream opened for OA metrics 1155 * @file: An i915 perf stream file 1156 * @wait: poll() state table 1157 * 1158 * For handling userspace polling on an i915 perf stream opened for OA metrics, 1159 * this starts a poll_wait with the wait queue that our hrtimer callback wakes 1160 * when it sees data ready to read in the circular OA buffer. 1161 */ 1162 static void i915_oa_poll_wait(struct i915_perf_stream *stream, 1163 struct file *file, 1164 poll_table *wait) 1165 { 1166 struct drm_i915_private *dev_priv = stream->dev_priv; 1167 1168 poll_wait(file, &dev_priv->perf.oa.poll_wq, wait); 1169 } 1170 1171 /** 1172 * i915_oa_read - just calls through to &i915_oa_ops->read 1173 * @stream: An i915-perf stream opened for OA metrics 1174 * @buf: destination buffer given by userspace 1175 * @count: the number of bytes userspace wants to read 1176 * @offset: (inout): the current position for writing into @buf 1177 * 1178 * Updates @offset according to the number of bytes successfully copied into 1179 * the userspace buffer. 1180 * 1181 * Returns: zero on success or a negative error code 1182 */ 1183 static int i915_oa_read(struct i915_perf_stream *stream, 1184 char __user *buf, 1185 size_t count, 1186 size_t *offset) 1187 { 1188 struct drm_i915_private *dev_priv = stream->dev_priv; 1189 1190 return dev_priv->perf.oa.ops.read(stream, buf, count, offset); 1191 } 1192 1193 static struct intel_context *oa_pin_context(struct drm_i915_private *i915, 1194 struct i915_gem_context *ctx) 1195 { 1196 struct intel_engine_cs *engine = i915->engine[RCS]; 1197 struct intel_context *ce; 1198 int ret; 1199 1200 ret = i915_mutex_lock_interruptible(&i915->drm); 1201 if (ret) 1202 return ERR_PTR(ret); 1203 1204 /* 1205 * As the ID is the gtt offset of the context's vma we 1206 * pin the vma to ensure the ID remains fixed. 1207 * 1208 * NB: implied RCS engine... 1209 */ 1210 ce = intel_context_pin(ctx, engine); 1211 mutex_unlock(&i915->drm.struct_mutex); 1212 if (IS_ERR(ce)) 1213 return ce; 1214 1215 i915->perf.oa.pinned_ctx = ce; 1216 1217 return ce; 1218 } 1219 1220 /** 1221 * oa_get_render_ctx_id - determine and hold ctx hw id 1222 * @stream: An i915-perf stream opened for OA metrics 1223 * 1224 * Determine the render context hw id, and ensure it remains fixed for the 1225 * lifetime of the stream. This ensures that we don't have to worry about 1226 * updating the context ID in OACONTROL on the fly. 1227 * 1228 * Returns: zero on success or a negative error code 1229 */ 1230 static int oa_get_render_ctx_id(struct i915_perf_stream *stream) 1231 { 1232 struct drm_i915_private *i915 = stream->dev_priv; 1233 struct intel_context *ce; 1234 1235 ce = oa_pin_context(i915, stream->ctx); 1236 if (IS_ERR(ce)) 1237 return PTR_ERR(ce); 1238 1239 switch (INTEL_GEN(i915)) { 1240 case 7: { 1241 /* 1242 * On Haswell we don't do any post processing of the reports 1243 * and don't need to use the mask. 1244 */ 1245 i915->perf.oa.specific_ctx_id = i915_ggtt_offset(ce->state); 1246 i915->perf.oa.specific_ctx_id_mask = 0; 1247 break; 1248 } 1249 1250 case 8: 1251 case 9: 1252 case 10: 1253 if (USES_GUC_SUBMISSION(i915)) { 1254 /* 1255 * When using GuC, the context descriptor we write in 1256 * i915 is read by GuC and rewritten before it's 1257 * actually written into the hardware. The LRCA is 1258 * what is put into the context id field of the 1259 * context descriptor by GuC. Because it's aligned to 1260 * a page, the lower 12bits are always at 0 and 1261 * dropped by GuC. They won't be part of the context 1262 * ID in the OA reports, so squash those lower bits. 1263 */ 1264 i915->perf.oa.specific_ctx_id = 1265 lower_32_bits(ce->lrc_desc) >> 12; 1266 1267 /* 1268 * GuC uses the top bit to signal proxy submission, so 1269 * ignore that bit. 1270 */ 1271 i915->perf.oa.specific_ctx_id_mask = 1272 (1U << (GEN8_CTX_ID_WIDTH - 1)) - 1; 1273 } else { 1274 i915->perf.oa.specific_ctx_id_mask = 1275 (1U << GEN8_CTX_ID_WIDTH) - 1; 1276 i915->perf.oa.specific_ctx_id = 1277 upper_32_bits(ce->lrc_desc); 1278 i915->perf.oa.specific_ctx_id &= 1279 i915->perf.oa.specific_ctx_id_mask; 1280 } 1281 break; 1282 1283 case 11: { 1284 i915->perf.oa.specific_ctx_id_mask = 1285 ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) << (GEN11_SW_CTX_ID_SHIFT - 32) | 1286 ((1U << GEN11_ENGINE_INSTANCE_WIDTH) - 1) << (GEN11_ENGINE_INSTANCE_SHIFT - 32) | 1287 ((1 << GEN11_ENGINE_CLASS_WIDTH) - 1) << (GEN11_ENGINE_CLASS_SHIFT - 32); 1288 i915->perf.oa.specific_ctx_id = upper_32_bits(ce->lrc_desc); 1289 i915->perf.oa.specific_ctx_id &= 1290 i915->perf.oa.specific_ctx_id_mask; 1291 break; 1292 } 1293 1294 default: 1295 MISSING_CASE(INTEL_GEN(i915)); 1296 } 1297 1298 DRM_DEBUG_DRIVER("filtering on ctx_id=0x%x ctx_id_mask=0x%x\n", 1299 i915->perf.oa.specific_ctx_id, 1300 i915->perf.oa.specific_ctx_id_mask); 1301 1302 return 0; 1303 } 1304 1305 /** 1306 * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold 1307 * @stream: An i915-perf stream opened for OA metrics 1308 * 1309 * In case anything needed doing to ensure the context HW ID would remain valid 1310 * for the lifetime of the stream, then that can be undone here. 1311 */ 1312 static void oa_put_render_ctx_id(struct i915_perf_stream *stream) 1313 { 1314 struct drm_i915_private *dev_priv = stream->dev_priv; 1315 struct intel_context *ce; 1316 1317 dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID; 1318 dev_priv->perf.oa.specific_ctx_id_mask = 0; 1319 1320 ce = fetch_and_zero(&dev_priv->perf.oa.pinned_ctx); 1321 if (ce) { 1322 mutex_lock(&dev_priv->drm.struct_mutex); 1323 intel_context_unpin(ce); 1324 mutex_unlock(&dev_priv->drm.struct_mutex); 1325 } 1326 } 1327 1328 static void 1329 free_oa_buffer(struct drm_i915_private *i915) 1330 { 1331 mutex_lock(&i915->drm.struct_mutex); 1332 1333 i915_vma_unpin_and_release(&i915->perf.oa.oa_buffer.vma, 1334 I915_VMA_RELEASE_MAP); 1335 1336 mutex_unlock(&i915->drm.struct_mutex); 1337 1338 i915->perf.oa.oa_buffer.vaddr = NULL; 1339 } 1340 1341 static void i915_oa_stream_destroy(struct i915_perf_stream *stream) 1342 { 1343 struct drm_i915_private *dev_priv = stream->dev_priv; 1344 1345 BUG_ON(stream != dev_priv->perf.oa.exclusive_stream); 1346 1347 /* 1348 * Unset exclusive_stream first, it will be checked while disabling 1349 * the metric set on gen8+. 1350 */ 1351 mutex_lock(&dev_priv->drm.struct_mutex); 1352 dev_priv->perf.oa.exclusive_stream = NULL; 1353 dev_priv->perf.oa.ops.disable_metric_set(dev_priv); 1354 mutex_unlock(&dev_priv->drm.struct_mutex); 1355 1356 free_oa_buffer(dev_priv); 1357 1358 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL); 1359 intel_runtime_pm_put(dev_priv); 1360 1361 if (stream->ctx) 1362 oa_put_render_ctx_id(stream); 1363 1364 put_oa_config(dev_priv, stream->oa_config); 1365 1366 if (dev_priv->perf.oa.spurious_report_rs.missed) { 1367 DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n", 1368 dev_priv->perf.oa.spurious_report_rs.missed); 1369 } 1370 } 1371 1372 static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv) 1373 { 1374 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma); 1375 unsigned long flags; 1376 1377 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 1378 1379 /* Pre-DevBDW: OABUFFER must be set with counters off, 1380 * before OASTATUS1, but after OASTATUS2 1381 */ 1382 I915_WRITE(GEN7_OASTATUS2, 1383 gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT); /* head */ 1384 dev_priv->perf.oa.oa_buffer.head = gtt_offset; 1385 1386 I915_WRITE(GEN7_OABUFFER, gtt_offset); 1387 1388 I915_WRITE(GEN7_OASTATUS1, gtt_offset | 1389 ((dev_priv->perf.oa.oa_buffer.size_exponent - 17) << 1390 GEN7_OASTATUS1_BUFFER_SIZE_SHIFT)); /* tail */ 1391 1392 /* Mark that we need updated tail pointers to read from... */ 1393 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR; 1394 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR; 1395 1396 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 1397 1398 /* On Haswell we have to track which OASTATUS1 flags we've 1399 * already seen since they can't be cleared while periodic 1400 * sampling is enabled. 1401 */ 1402 dev_priv->perf.oa.gen7_latched_oastatus1 = 0; 1403 1404 /* NB: although the OA buffer will initially be allocated 1405 * zeroed via shmfs (and so this memset is redundant when 1406 * first allocating), we may re-init the OA buffer, either 1407 * when re-enabling a stream or in error/reset paths. 1408 * 1409 * The reason we clear the buffer for each re-init is for the 1410 * sanity check in gen7_append_oa_reports() that looks at the 1411 * report-id field to make sure it's non-zero which relies on 1412 * the assumption that new reports are being written to zeroed 1413 * memory... 1414 */ 1415 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, 1416 dev_priv->perf.oa.oa_buffer.vma->size); 1417 1418 /* Maybe make ->pollin per-stream state if we support multiple 1419 * concurrent streams in the future. 1420 */ 1421 dev_priv->perf.oa.pollin = false; 1422 } 1423 1424 static void gen8_init_oa_buffer(struct drm_i915_private *dev_priv) 1425 { 1426 u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma); 1427 unsigned long flags; 1428 1429 spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 1430 1431 I915_WRITE(GEN8_OASTATUS, 0); 1432 I915_WRITE(GEN8_OAHEADPTR, gtt_offset); 1433 dev_priv->perf.oa.oa_buffer.head = gtt_offset; 1434 1435 I915_WRITE(GEN8_OABUFFER_UDW, 0); 1436 1437 /* 1438 * PRM says: 1439 * 1440 * "This MMIO must be set before the OATAILPTR 1441 * register and after the OAHEADPTR register. This is 1442 * to enable proper functionality of the overflow 1443 * bit." 1444 */ 1445 I915_WRITE(GEN8_OABUFFER, gtt_offset | 1446 ((dev_priv->perf.oa.oa_buffer.size_exponent - 17) << 1447 GEN8_OABUFFER_BUFFER_SIZE_SHIFT) | 1448 GEN8_OABUFFER_MEM_SELECT_GGTT); 1449 I915_WRITE(GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK); 1450 1451 /* Mark that we need updated tail pointers to read from... */ 1452 dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR; 1453 dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR; 1454 1455 /* 1456 * Reset state used to recognise context switches, affecting which 1457 * reports we will forward to userspace while filtering for a single 1458 * context. 1459 */ 1460 dev_priv->perf.oa.oa_buffer.last_ctx_id = INVALID_CTX_ID; 1461 1462 spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags); 1463 1464 /* 1465 * NB: although the OA buffer will initially be allocated 1466 * zeroed via shmfs (and so this memset is redundant when 1467 * first allocating), we may re-init the OA buffer, either 1468 * when re-enabling a stream or in error/reset paths. 1469 * 1470 * The reason we clear the buffer for each re-init is for the 1471 * sanity check in gen8_append_oa_reports() that looks at the 1472 * reason field to make sure it's non-zero which relies on 1473 * the assumption that new reports are being written to zeroed 1474 * memory... 1475 */ 1476 memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, 1477 dev_priv->perf.oa.oa_buffer.vma->size); 1478 1479 /* 1480 * Maybe make ->pollin per-stream state if we support multiple 1481 * concurrent streams in the future. 1482 */ 1483 dev_priv->perf.oa.pollin = false; 1484 } 1485 1486 static int alloc_oa_buffer(struct drm_i915_private *dev_priv, int size_exponent) 1487 { 1488 struct drm_i915_gem_object *bo; 1489 struct i915_vma *vma; 1490 size_t size = 1U << size_exponent; 1491 int ret; 1492 1493 if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma)) 1494 return -ENODEV; 1495 1496 if (WARN_ON(size < SZ_128K || size > SZ_16M)) 1497 return -EINVAL; 1498 1499 ret = i915_mutex_lock_interruptible(&dev_priv->drm); 1500 if (ret) 1501 return ret; 1502 1503 bo = i915_gem_object_create(dev_priv, size); 1504 if (IS_ERR(bo)) { 1505 DRM_ERROR("Failed to allocate OA buffer\n"); 1506 ret = PTR_ERR(bo); 1507 goto unlock; 1508 } 1509 1510 ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC); 1511 if (ret) 1512 goto err_unref; 1513 1514 /* PreHSW required 512K alignment, HSW requires 16M */ 1515 vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0); 1516 if (IS_ERR(vma)) { 1517 ret = PTR_ERR(vma); 1518 goto err_unref; 1519 } 1520 dev_priv->perf.oa.oa_buffer.vma = vma; 1521 dev_priv->perf.oa.oa_buffer.size_exponent = size_exponent; 1522 1523 dev_priv->perf.oa.oa_buffer.vaddr = 1524 i915_gem_object_pin_map(bo, I915_MAP_WB); 1525 if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) { 1526 ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr); 1527 goto err_unpin; 1528 } 1529 1530 DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p, size = %llu\n", 1531 i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma), 1532 dev_priv->perf.oa.oa_buffer.vaddr, 1533 dev_priv->perf.oa.oa_buffer.vma->size); 1534 1535 goto unlock; 1536 1537 err_unpin: 1538 __i915_vma_unpin(vma); 1539 1540 err_unref: 1541 i915_gem_object_put(bo); 1542 1543 dev_priv->perf.oa.oa_buffer.vaddr = NULL; 1544 dev_priv->perf.oa.oa_buffer.vma = NULL; 1545 1546 unlock: 1547 mutex_unlock(&dev_priv->drm.struct_mutex); 1548 return ret; 1549 } 1550 1551 static void config_oa_regs(struct drm_i915_private *dev_priv, 1552 const struct i915_oa_reg *regs, 1553 u32 n_regs) 1554 { 1555 u32 i; 1556 1557 for (i = 0; i < n_regs; i++) { 1558 const struct i915_oa_reg *reg = regs + i; 1559 1560 I915_WRITE(reg->addr, reg->value); 1561 } 1562 } 1563 1564 static int hsw_enable_metric_set(struct i915_perf_stream *stream) 1565 { 1566 struct drm_i915_private *dev_priv = stream->dev_priv; 1567 const struct i915_oa_config *oa_config = stream->oa_config; 1568 1569 /* PRM: 1570 * 1571 * OA unit is using “crclk” for its functionality. When trunk 1572 * level clock gating takes place, OA clock would be gated, 1573 * unable to count the events from non-render clock domain. 1574 * Render clock gating must be disabled when OA is enabled to 1575 * count the events from non-render domain. Unit level clock 1576 * gating for RCS should also be disabled. 1577 */ 1578 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) & 1579 ~GEN7_DOP_CLOCK_GATE_ENABLE)); 1580 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) | 1581 GEN6_CSUNIT_CLOCK_GATE_DISABLE)); 1582 1583 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len); 1584 1585 /* It apparently takes a fairly long time for a new MUX 1586 * configuration to be be applied after these register writes. 1587 * This delay duration was derived empirically based on the 1588 * render_basic config but hopefully it covers the maximum 1589 * configuration latency. 1590 * 1591 * As a fallback, the checks in _append_oa_reports() to skip 1592 * invalid OA reports do also seem to work to discard reports 1593 * generated before this config has completed - albeit not 1594 * silently. 1595 * 1596 * Unfortunately this is essentially a magic number, since we 1597 * don't currently know of a reliable mechanism for predicting 1598 * how long the MUX config will take to apply and besides 1599 * seeing invalid reports we don't know of a reliable way to 1600 * explicitly check that the MUX config has landed. 1601 * 1602 * It's even possible we've miss characterized the underlying 1603 * problem - it just seems like the simplest explanation why 1604 * a delay at this location would mitigate any invalid reports. 1605 */ 1606 usleep_range(15000, 20000); 1607 1608 config_oa_regs(dev_priv, oa_config->b_counter_regs, 1609 oa_config->b_counter_regs_len); 1610 1611 return 0; 1612 } 1613 1614 static void hsw_disable_metric_set(struct drm_i915_private *dev_priv) 1615 { 1616 I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) & 1617 ~GEN6_CSUNIT_CLOCK_GATE_DISABLE)); 1618 I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) | 1619 GEN7_DOP_CLOCK_GATE_ENABLE)); 1620 1621 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) & 1622 ~GT_NOA_ENABLE)); 1623 } 1624 1625 /* 1626 * NB: It must always remain pointer safe to run this even if the OA unit 1627 * has been disabled. 1628 * 1629 * It's fine to put out-of-date values into these per-context registers 1630 * in the case that the OA unit has been disabled. 1631 */ 1632 static void gen8_update_reg_state_unlocked(struct i915_gem_context *ctx, 1633 u32 *reg_state, 1634 const struct i915_oa_config *oa_config) 1635 { 1636 struct drm_i915_private *dev_priv = ctx->i915; 1637 u32 ctx_oactxctrl = dev_priv->perf.oa.ctx_oactxctrl_offset; 1638 u32 ctx_flexeu0 = dev_priv->perf.oa.ctx_flexeu0_offset; 1639 /* The MMIO offsets for Flex EU registers aren't contiguous */ 1640 i915_reg_t flex_regs[] = { 1641 EU_PERF_CNTL0, 1642 EU_PERF_CNTL1, 1643 EU_PERF_CNTL2, 1644 EU_PERF_CNTL3, 1645 EU_PERF_CNTL4, 1646 EU_PERF_CNTL5, 1647 EU_PERF_CNTL6, 1648 }; 1649 int i; 1650 1651 CTX_REG(reg_state, ctx_oactxctrl, GEN8_OACTXCONTROL, 1652 (dev_priv->perf.oa.period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) | 1653 (dev_priv->perf.oa.periodic ? GEN8_OA_TIMER_ENABLE : 0) | 1654 GEN8_OA_COUNTER_RESUME); 1655 1656 for (i = 0; i < ARRAY_SIZE(flex_regs); i++) { 1657 u32 state_offset = ctx_flexeu0 + i * 2; 1658 u32 mmio = i915_mmio_reg_offset(flex_regs[i]); 1659 1660 /* 1661 * This arbitrary default will select the 'EU FPU0 Pipeline 1662 * Active' event. In the future it's anticipated that there 1663 * will be an explicit 'No Event' we can select, but not yet... 1664 */ 1665 u32 value = 0; 1666 1667 if (oa_config) { 1668 u32 j; 1669 1670 for (j = 0; j < oa_config->flex_regs_len; j++) { 1671 if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) { 1672 value = oa_config->flex_regs[j].value; 1673 break; 1674 } 1675 } 1676 } 1677 1678 CTX_REG(reg_state, state_offset, flex_regs[i], value); 1679 } 1680 } 1681 1682 /* 1683 * Manages updating the per-context aspects of the OA stream 1684 * configuration across all contexts. 1685 * 1686 * The awkward consideration here is that OACTXCONTROL controls the 1687 * exponent for periodic sampling which is primarily used for system 1688 * wide profiling where we'd like a consistent sampling period even in 1689 * the face of context switches. 1690 * 1691 * Our approach of updating the register state context (as opposed to 1692 * say using a workaround batch buffer) ensures that the hardware 1693 * won't automatically reload an out-of-date timer exponent even 1694 * transiently before a WA BB could be parsed. 1695 * 1696 * This function needs to: 1697 * - Ensure the currently running context's per-context OA state is 1698 * updated 1699 * - Ensure that all existing contexts will have the correct per-context 1700 * OA state if they are scheduled for use. 1701 * - Ensure any new contexts will be initialized with the correct 1702 * per-context OA state. 1703 * 1704 * Note: it's only the RCS/Render context that has any OA state. 1705 */ 1706 static int gen8_configure_all_contexts(struct drm_i915_private *dev_priv, 1707 const struct i915_oa_config *oa_config) 1708 { 1709 struct intel_engine_cs *engine = dev_priv->engine[RCS]; 1710 unsigned int map_type = i915_coherent_map_type(dev_priv); 1711 struct i915_gem_context *ctx; 1712 struct i915_request *rq; 1713 int ret; 1714 1715 lockdep_assert_held(&dev_priv->drm.struct_mutex); 1716 1717 /* 1718 * The OA register config is setup through the context image. This image 1719 * might be written to by the GPU on context switch (in particular on 1720 * lite-restore). This means we can't safely update a context's image, 1721 * if this context is scheduled/submitted to run on the GPU. 1722 * 1723 * We could emit the OA register config through the batch buffer but 1724 * this might leave small interval of time where the OA unit is 1725 * configured at an invalid sampling period. 1726 * 1727 * So far the best way to work around this issue seems to be draining 1728 * the GPU from any submitted work. 1729 */ 1730 ret = i915_gem_wait_for_idle(dev_priv, 1731 I915_WAIT_LOCKED, 1732 MAX_SCHEDULE_TIMEOUT); 1733 if (ret) 1734 return ret; 1735 1736 /* Update all contexts now that we've stalled the submission. */ 1737 list_for_each_entry(ctx, &dev_priv->contexts.list, link) { 1738 struct intel_context *ce = to_intel_context(ctx, engine); 1739 u32 *regs; 1740 1741 /* OA settings will be set upon first use */ 1742 if (!ce->state) 1743 continue; 1744 1745 regs = i915_gem_object_pin_map(ce->state->obj, map_type); 1746 if (IS_ERR(regs)) 1747 return PTR_ERR(regs); 1748 1749 ce->state->obj->mm.dirty = true; 1750 regs += LRC_STATE_PN * PAGE_SIZE / sizeof(*regs); 1751 1752 gen8_update_reg_state_unlocked(ctx, regs, oa_config); 1753 1754 i915_gem_object_unpin_map(ce->state->obj); 1755 } 1756 1757 /* 1758 * Apply the configuration by doing one context restore of the edited 1759 * context image. 1760 */ 1761 rq = i915_request_alloc(engine, dev_priv->kernel_context); 1762 if (IS_ERR(rq)) 1763 return PTR_ERR(rq); 1764 1765 i915_request_add(rq); 1766 1767 return 0; 1768 } 1769 1770 static int gen8_enable_metric_set(struct i915_perf_stream *stream) 1771 { 1772 struct drm_i915_private *dev_priv = stream->dev_priv; 1773 const struct i915_oa_config *oa_config = stream->oa_config; 1774 int ret; 1775 1776 /* 1777 * We disable slice/unslice clock ratio change reports on SKL since 1778 * they are too noisy. The HW generates a lot of redundant reports 1779 * where the ratio hasn't really changed causing a lot of redundant 1780 * work to processes and increasing the chances we'll hit buffer 1781 * overruns. 1782 * 1783 * Although we don't currently use the 'disable overrun' OABUFFER 1784 * feature it's worth noting that clock ratio reports have to be 1785 * disabled before considering to use that feature since the HW doesn't 1786 * correctly block these reports. 1787 * 1788 * Currently none of the high-level metrics we have depend on knowing 1789 * this ratio to normalize. 1790 * 1791 * Note: This register is not power context saved and restored, but 1792 * that's OK considering that we disable RC6 while the OA unit is 1793 * enabled. 1794 * 1795 * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to 1796 * be read back from automatically triggered reports, as part of the 1797 * RPT_ID field. 1798 */ 1799 if (IS_GEN(dev_priv, 9, 11)) { 1800 I915_WRITE(GEN8_OA_DEBUG, 1801 _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS | 1802 GEN9_OA_DEBUG_INCLUDE_CLK_RATIO)); 1803 } 1804 1805 /* 1806 * Update all contexts prior writing the mux configurations as we need 1807 * to make sure all slices/subslices are ON before writing to NOA 1808 * registers. 1809 */ 1810 ret = gen8_configure_all_contexts(dev_priv, oa_config); 1811 if (ret) 1812 return ret; 1813 1814 config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len); 1815 1816 config_oa_regs(dev_priv, oa_config->b_counter_regs, 1817 oa_config->b_counter_regs_len); 1818 1819 return 0; 1820 } 1821 1822 static void gen8_disable_metric_set(struct drm_i915_private *dev_priv) 1823 { 1824 /* Reset all contexts' slices/subslices configurations. */ 1825 gen8_configure_all_contexts(dev_priv, NULL); 1826 1827 I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) & 1828 ~GT_NOA_ENABLE)); 1829 } 1830 1831 static void gen10_disable_metric_set(struct drm_i915_private *dev_priv) 1832 { 1833 /* Reset all contexts' slices/subslices configurations. */ 1834 gen8_configure_all_contexts(dev_priv, NULL); 1835 1836 /* Make sure we disable noa to save power. */ 1837 I915_WRITE(RPM_CONFIG1, 1838 I915_READ(RPM_CONFIG1) & ~GEN10_GT_NOA_ENABLE); 1839 } 1840 1841 static void gen7_oa_enable(struct i915_perf_stream *stream) 1842 { 1843 struct drm_i915_private *dev_priv = stream->dev_priv; 1844 struct i915_gem_context *ctx = stream->ctx; 1845 u32 ctx_id = dev_priv->perf.oa.specific_ctx_id; 1846 bool periodic = dev_priv->perf.oa.periodic; 1847 u32 period_exponent = dev_priv->perf.oa.period_exponent; 1848 u32 report_format = dev_priv->perf.oa.oa_buffer.format; 1849 1850 /* 1851 * Reset buf pointers so we don't forward reports from before now. 1852 * 1853 * Think carefully if considering trying to avoid this, since it 1854 * also ensures status flags and the buffer itself are cleared 1855 * in error paths, and we have checks for invalid reports based 1856 * on the assumption that certain fields are written to zeroed 1857 * memory which this helps maintains. 1858 */ 1859 gen7_init_oa_buffer(dev_priv); 1860 1861 I915_WRITE(GEN7_OACONTROL, 1862 (ctx_id & GEN7_OACONTROL_CTX_MASK) | 1863 (period_exponent << 1864 GEN7_OACONTROL_TIMER_PERIOD_SHIFT) | 1865 (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) | 1866 (report_format << GEN7_OACONTROL_FORMAT_SHIFT) | 1867 (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) | 1868 GEN7_OACONTROL_ENABLE); 1869 } 1870 1871 static void gen8_oa_enable(struct i915_perf_stream *stream) 1872 { 1873 struct drm_i915_private *dev_priv = stream->dev_priv; 1874 u32 report_format = dev_priv->perf.oa.oa_buffer.format; 1875 1876 /* 1877 * Reset buf pointers so we don't forward reports from before now. 1878 * 1879 * Think carefully if considering trying to avoid this, since it 1880 * also ensures status flags and the buffer itself are cleared 1881 * in error paths, and we have checks for invalid reports based 1882 * on the assumption that certain fields are written to zeroed 1883 * memory which this helps maintains. 1884 */ 1885 gen8_init_oa_buffer(dev_priv); 1886 1887 /* 1888 * Note: we don't rely on the hardware to perform single context 1889 * filtering and instead filter on the cpu based on the context-id 1890 * field of reports 1891 */ 1892 I915_WRITE(GEN8_OACONTROL, (report_format << 1893 GEN8_OA_REPORT_FORMAT_SHIFT) | 1894 GEN8_OA_COUNTER_ENABLE); 1895 } 1896 1897 /** 1898 * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream 1899 * @stream: An i915 perf stream opened for OA metrics 1900 * 1901 * [Re]enables hardware periodic sampling according to the period configured 1902 * when opening the stream. This also starts a hrtimer that will periodically 1903 * check for data in the circular OA buffer for notifying userspace (e.g. 1904 * during a read() or poll()). 1905 */ 1906 static void i915_oa_stream_enable(struct i915_perf_stream *stream) 1907 { 1908 struct drm_i915_private *dev_priv = stream->dev_priv; 1909 1910 dev_priv->perf.oa.ops.oa_enable(stream); 1911 1912 if (dev_priv->perf.oa.periodic) 1913 hrtimer_start(&dev_priv->perf.oa.poll_check_timer, 1914 ns_to_ktime(POLL_PERIOD), 1915 HRTIMER_MODE_REL_PINNED); 1916 } 1917 1918 static void gen7_oa_disable(struct i915_perf_stream *stream) 1919 { 1920 struct drm_i915_private *dev_priv = stream->dev_priv; 1921 1922 I915_WRITE(GEN7_OACONTROL, 0); 1923 if (intel_wait_for_register(dev_priv, 1924 GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0, 1925 50)) 1926 DRM_ERROR("wait for OA to be disabled timed out\n"); 1927 } 1928 1929 static void gen8_oa_disable(struct i915_perf_stream *stream) 1930 { 1931 struct drm_i915_private *dev_priv = stream->dev_priv; 1932 1933 I915_WRITE(GEN8_OACONTROL, 0); 1934 if (intel_wait_for_register(dev_priv, 1935 GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0, 1936 50)) 1937 DRM_ERROR("wait for OA to be disabled timed out\n"); 1938 } 1939 1940 /** 1941 * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream 1942 * @stream: An i915 perf stream opened for OA metrics 1943 * 1944 * Stops the OA unit from periodically writing counter reports into the 1945 * circular OA buffer. This also stops the hrtimer that periodically checks for 1946 * data in the circular OA buffer, for notifying userspace. 1947 */ 1948 static void i915_oa_stream_disable(struct i915_perf_stream *stream) 1949 { 1950 struct drm_i915_private *dev_priv = stream->dev_priv; 1951 1952 dev_priv->perf.oa.ops.oa_disable(stream); 1953 1954 if (dev_priv->perf.oa.periodic) 1955 hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer); 1956 } 1957 1958 static const struct i915_perf_stream_ops i915_oa_stream_ops = { 1959 .destroy = i915_oa_stream_destroy, 1960 .enable = i915_oa_stream_enable, 1961 .disable = i915_oa_stream_disable, 1962 .wait_unlocked = i915_oa_wait_unlocked, 1963 .poll_wait = i915_oa_poll_wait, 1964 .read = i915_oa_read, 1965 }; 1966 1967 /** 1968 * i915_oa_stream_init - validate combined props for OA stream and init 1969 * @stream: An i915 perf stream 1970 * @param: The open parameters passed to `DRM_I915_PERF_OPEN` 1971 * @props: The property state that configures stream (individually validated) 1972 * 1973 * While read_properties_unlocked() validates properties in isolation it 1974 * doesn't ensure that the combination necessarily makes sense. 1975 * 1976 * At this point it has been determined that userspace wants a stream of 1977 * OA metrics, but still we need to further validate the combined 1978 * properties are OK. 1979 * 1980 * If the configuration makes sense then we can allocate memory for 1981 * a circular OA buffer and apply the requested metric set configuration. 1982 * 1983 * Returns: zero on success or a negative error code. 1984 */ 1985 static int i915_oa_stream_init(struct i915_perf_stream *stream, 1986 struct drm_i915_perf_open_param *param, 1987 struct perf_open_properties *props) 1988 { 1989 struct drm_i915_private *dev_priv = stream->dev_priv; 1990 int format_size; 1991 int ret; 1992 1993 /* If the sysfs metrics/ directory wasn't registered for some 1994 * reason then don't let userspace try their luck with config 1995 * IDs 1996 */ 1997 if (!dev_priv->perf.metrics_kobj) { 1998 DRM_DEBUG("OA metrics weren't advertised via sysfs\n"); 1999 return -EINVAL; 2000 } 2001 2002 if (!(props->sample_flags & SAMPLE_OA_REPORT)) { 2003 DRM_DEBUG("Only OA report sampling supported\n"); 2004 return -EINVAL; 2005 } 2006 2007 if (!dev_priv->perf.oa.ops.enable_metric_set) { 2008 DRM_DEBUG("OA unit not supported\n"); 2009 return -ENODEV; 2010 } 2011 2012 /* To avoid the complexity of having to accurately filter 2013 * counter reports and marshal to the appropriate client 2014 * we currently only allow exclusive access 2015 */ 2016 if (dev_priv->perf.oa.exclusive_stream) { 2017 DRM_DEBUG("OA unit already in use\n"); 2018 return -EBUSY; 2019 } 2020 2021 if (!props->oa_format) { 2022 DRM_DEBUG("OA report format not specified\n"); 2023 return -EINVAL; 2024 } 2025 2026 /* We set up some ratelimit state to potentially throttle any _NOTES 2027 * about spurious, invalid OA reports which we don't forward to 2028 * userspace. 2029 * 2030 * The initialization is associated with opening the stream (not driver 2031 * init) considering we print a _NOTE about any throttling when closing 2032 * the stream instead of waiting until driver _fini which no one would 2033 * ever see. 2034 * 2035 * Using the same limiting factors as printk_ratelimit() 2036 */ 2037 ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs, 2038 5 * HZ, 10); 2039 /* Since we use a DRM_NOTE for spurious reports it would be 2040 * inconsistent to let __ratelimit() automatically print a warning for 2041 * throttling. 2042 */ 2043 ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs, 2044 RATELIMIT_MSG_ON_RELEASE); 2045 2046 stream->sample_size = sizeof(struct drm_i915_perf_record_header); 2047 2048 format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size; 2049 2050 stream->sample_flags |= SAMPLE_OA_REPORT; 2051 stream->sample_size += format_size; 2052 2053 dev_priv->perf.oa.oa_buffer.format_size = format_size; 2054 if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0)) 2055 return -EINVAL; 2056 2057 dev_priv->perf.oa.oa_buffer.format = 2058 dev_priv->perf.oa.oa_formats[props->oa_format].format; 2059 2060 dev_priv->perf.oa.periodic = props->oa_periodic; 2061 if (dev_priv->perf.oa.periodic) 2062 dev_priv->perf.oa.period_exponent = props->oa_period_exponent; 2063 2064 if (stream->ctx) { 2065 ret = oa_get_render_ctx_id(stream); 2066 if (ret) { 2067 DRM_DEBUG("Invalid context id to filter with\n"); 2068 return ret; 2069 } 2070 } 2071 2072 ret = get_oa_config(dev_priv, props->metrics_set, &stream->oa_config); 2073 if (ret) { 2074 DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set); 2075 goto err_config; 2076 } 2077 2078 /* PRM - observability performance counters: 2079 * 2080 * OACONTROL, performance counter enable, note: 2081 * 2082 * "When this bit is set, in order to have coherent counts, 2083 * RC6 power state and trunk clock gating must be disabled. 2084 * This can be achieved by programming MMIO registers as 2085 * 0xA094=0 and 0xA090[31]=1" 2086 * 2087 * In our case we are expecting that taking pm + FORCEWAKE 2088 * references will effectively disable RC6. 2089 */ 2090 intel_runtime_pm_get(dev_priv); 2091 intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL); 2092 2093 ret = alloc_oa_buffer(dev_priv, props->oa_buffer_size_exponent); 2094 if (ret) 2095 goto err_oa_buf_alloc; 2096 2097 ret = i915_mutex_lock_interruptible(&dev_priv->drm); 2098 if (ret) 2099 goto err_lock; 2100 2101 ret = dev_priv->perf.oa.ops.enable_metric_set(stream); 2102 if (ret) { 2103 DRM_DEBUG("Unable to enable metric set\n"); 2104 goto err_enable; 2105 } 2106 2107 stream->ops = &i915_oa_stream_ops; 2108 2109 dev_priv->perf.oa.exclusive_stream = stream; 2110 2111 mutex_unlock(&dev_priv->drm.struct_mutex); 2112 2113 return 0; 2114 2115 err_enable: 2116 dev_priv->perf.oa.ops.disable_metric_set(dev_priv); 2117 mutex_unlock(&dev_priv->drm.struct_mutex); 2118 2119 err_lock: 2120 free_oa_buffer(dev_priv); 2121 2122 err_oa_buf_alloc: 2123 put_oa_config(dev_priv, stream->oa_config); 2124 2125 intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL); 2126 intel_runtime_pm_put(dev_priv); 2127 2128 err_config: 2129 if (stream->ctx) 2130 oa_put_render_ctx_id(stream); 2131 2132 return ret; 2133 } 2134 2135 void i915_oa_init_reg_state(struct intel_engine_cs *engine, 2136 struct i915_gem_context *ctx, 2137 u32 *reg_state) 2138 { 2139 struct i915_perf_stream *stream; 2140 2141 if (engine->id != RCS) 2142 return; 2143 2144 stream = engine->i915->perf.oa.exclusive_stream; 2145 if (stream) 2146 gen8_update_reg_state_unlocked(ctx, reg_state, stream->oa_config); 2147 } 2148 2149 /** 2150 * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation 2151 * @stream: An i915 perf stream 2152 * @file: An i915 perf stream file 2153 * @buf: destination buffer given by userspace 2154 * @count: the number of bytes userspace wants to read 2155 * @ppos: (inout) file seek position (unused) 2156 * 2157 * Besides wrapping &i915_perf_stream_ops->read this provides a common place to 2158 * ensure that if we've successfully copied any data then reporting that takes 2159 * precedence over any internal error status, so the data isn't lost. 2160 * 2161 * For example ret will be -ENOSPC whenever there is more buffered data than 2162 * can be copied to userspace, but that's only interesting if we weren't able 2163 * to copy some data because it implies the userspace buffer is too small to 2164 * receive a single record (and we never split records). 2165 * 2166 * Another case with ret == -EFAULT is more of a grey area since it would seem 2167 * like bad form for userspace to ask us to overrun its buffer, but the user 2168 * knows best: 2169 * 2170 * http://yarchive.net/comp/linux/partial_reads_writes.html 2171 * 2172 * Returns: The number of bytes copied or a negative error code on failure. 2173 */ 2174 static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream, 2175 struct file *file, 2176 char __user *buf, 2177 size_t count, 2178 loff_t *ppos) 2179 { 2180 /* Note we keep the offset (aka bytes read) separate from any 2181 * error status so that the final check for whether we return 2182 * the bytes read with a higher precedence than any error (see 2183 * comment below) doesn't need to be handled/duplicated in 2184 * stream->ops->read() implementations. 2185 */ 2186 size_t offset = 0; 2187 int ret = stream->ops->read(stream, buf, count, &offset); 2188 2189 return offset ?: (ret ?: -EAGAIN); 2190 } 2191 2192 /** 2193 * i915_perf_read - handles read() FOP for i915 perf stream FDs 2194 * @file: An i915 perf stream file 2195 * @buf: destination buffer given by userspace 2196 * @count: the number of bytes userspace wants to read 2197 * @ppos: (inout) file seek position (unused) 2198 * 2199 * The entry point for handling a read() on a stream file descriptor from 2200 * userspace. Most of the work is left to the i915_perf_read_locked() and 2201 * &i915_perf_stream_ops->read but to save having stream implementations (of 2202 * which we might have multiple later) we handle blocking read here. 2203 * 2204 * We can also consistently treat trying to read from a disabled stream 2205 * as an IO error so implementations can assume the stream is enabled 2206 * while reading. 2207 * 2208 * Returns: The number of bytes copied or a negative error code on failure. 2209 */ 2210 static ssize_t i915_perf_read(struct file *file, 2211 char __user *buf, 2212 size_t count, 2213 loff_t *ppos) 2214 { 2215 struct i915_perf_stream *stream = file->private_data; 2216 struct drm_i915_private *dev_priv = stream->dev_priv; 2217 ssize_t ret; 2218 2219 /* To ensure it's handled consistently we simply treat all reads of a 2220 * disabled stream as an error. In particular it might otherwise lead 2221 * to a deadlock for blocking file descriptors... 2222 */ 2223 if (!stream->enabled) 2224 return -EIO; 2225 2226 if (!(file->f_flags & O_NONBLOCK)) { 2227 /* There's the small chance of false positives from 2228 * stream->ops->wait_unlocked. 2229 * 2230 * E.g. with single context filtering since we only wait until 2231 * oabuffer has >= 1 report we don't immediately know whether 2232 * any reports really belong to the current context 2233 */ 2234 do { 2235 ret = stream->ops->wait_unlocked(stream); 2236 if (ret) 2237 return ret; 2238 2239 mutex_lock(&dev_priv->perf.lock); 2240 ret = i915_perf_read_locked(stream, file, 2241 buf, count, ppos); 2242 mutex_unlock(&dev_priv->perf.lock); 2243 } while (ret == -EAGAIN); 2244 } else { 2245 mutex_lock(&dev_priv->perf.lock); 2246 ret = i915_perf_read_locked(stream, file, buf, count, ppos); 2247 mutex_unlock(&dev_priv->perf.lock); 2248 } 2249 2250 /* We allow the poll checking to sometimes report false positive EPOLLIN 2251 * events where we might actually report EAGAIN on read() if there's 2252 * not really any data available. In this situation though we don't 2253 * want to enter a busy loop between poll() reporting a EPOLLIN event 2254 * and read() returning -EAGAIN. Clearing the oa.pollin state here 2255 * effectively ensures we back off until the next hrtimer callback 2256 * before reporting another EPOLLIN event. 2257 */ 2258 if (ret >= 0 || ret == -EAGAIN) { 2259 /* Maybe make ->pollin per-stream state if we support multiple 2260 * concurrent streams in the future. 2261 */ 2262 dev_priv->perf.oa.pollin = false; 2263 } 2264 2265 return ret; 2266 } 2267 2268 static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer) 2269 { 2270 struct drm_i915_private *dev_priv = 2271 container_of(hrtimer, typeof(*dev_priv), 2272 perf.oa.poll_check_timer); 2273 2274 if (oa_buffer_check_unlocked(dev_priv)) { 2275 dev_priv->perf.oa.pollin = true; 2276 wake_up(&dev_priv->perf.oa.poll_wq); 2277 } 2278 2279 hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD)); 2280 2281 return HRTIMER_RESTART; 2282 } 2283 2284 /** 2285 * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream 2286 * @dev_priv: i915 device instance 2287 * @stream: An i915 perf stream 2288 * @file: An i915 perf stream file 2289 * @wait: poll() state table 2290 * 2291 * For handling userspace polling on an i915 perf stream, this calls through to 2292 * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that 2293 * will be woken for new stream data. 2294 * 2295 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize 2296 * with any non-file-operation driver hooks. 2297 * 2298 * Returns: any poll events that are ready without sleeping 2299 */ 2300 static __poll_t i915_perf_poll_locked(struct drm_i915_private *dev_priv, 2301 struct i915_perf_stream *stream, 2302 struct file *file, 2303 poll_table *wait) 2304 { 2305 __poll_t events = 0; 2306 2307 stream->ops->poll_wait(stream, file, wait); 2308 2309 /* Note: we don't explicitly check whether there's something to read 2310 * here since this path may be very hot depending on what else 2311 * userspace is polling, or on the timeout in use. We rely solely on 2312 * the hrtimer/oa_poll_check_timer_cb to notify us when there are 2313 * samples to read. 2314 */ 2315 if (dev_priv->perf.oa.pollin) 2316 events |= EPOLLIN; 2317 2318 return events; 2319 } 2320 2321 /** 2322 * i915_perf_poll - call poll_wait() with a suitable wait queue for stream 2323 * @file: An i915 perf stream file 2324 * @wait: poll() state table 2325 * 2326 * For handling userspace polling on an i915 perf stream, this ensures 2327 * poll_wait() gets called with a wait queue that will be woken for new stream 2328 * data. 2329 * 2330 * Note: Implementation deferred to i915_perf_poll_locked() 2331 * 2332 * Returns: any poll events that are ready without sleeping 2333 */ 2334 static __poll_t i915_perf_poll(struct file *file, poll_table *wait) 2335 { 2336 struct i915_perf_stream *stream = file->private_data; 2337 struct drm_i915_private *dev_priv = stream->dev_priv; 2338 __poll_t ret; 2339 2340 mutex_lock(&dev_priv->perf.lock); 2341 ret = i915_perf_poll_locked(dev_priv, stream, file, wait); 2342 mutex_unlock(&dev_priv->perf.lock); 2343 2344 return ret; 2345 } 2346 2347 /** 2348 * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl 2349 * @stream: A disabled i915 perf stream 2350 * 2351 * [Re]enables the associated capture of data for this stream. 2352 * 2353 * If a stream was previously enabled then there's currently no intention 2354 * to provide userspace any guarantee about the preservation of previously 2355 * buffered data. 2356 */ 2357 static void i915_perf_enable_locked(struct i915_perf_stream *stream) 2358 { 2359 if (stream->enabled) 2360 return; 2361 2362 /* Allow stream->ops->enable() to refer to this */ 2363 stream->enabled = true; 2364 2365 if (stream->ops->enable) 2366 stream->ops->enable(stream); 2367 } 2368 2369 /** 2370 * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl 2371 * @stream: An enabled i915 perf stream 2372 * 2373 * Disables the associated capture of data for this stream. 2374 * 2375 * The intention is that disabling an re-enabling a stream will ideally be 2376 * cheaper than destroying and re-opening a stream with the same configuration, 2377 * though there are no formal guarantees about what state or buffered data 2378 * must be retained between disabling and re-enabling a stream. 2379 * 2380 * Note: while a stream is disabled it's considered an error for userspace 2381 * to attempt to read from the stream (-EIO). 2382 */ 2383 static void i915_perf_disable_locked(struct i915_perf_stream *stream) 2384 { 2385 if (!stream->enabled) 2386 return; 2387 2388 /* Allow stream->ops->disable() to refer to this */ 2389 stream->enabled = false; 2390 2391 if (stream->ops->disable) 2392 stream->ops->disable(stream); 2393 } 2394 2395 /** 2396 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs 2397 * @stream: An i915 perf stream 2398 * @cmd: the ioctl request 2399 * @arg: the ioctl data 2400 * 2401 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize 2402 * with any non-file-operation driver hooks. 2403 * 2404 * Returns: zero on success or a negative error code. Returns -EINVAL for 2405 * an unknown ioctl request. 2406 */ 2407 static long i915_perf_ioctl_locked(struct i915_perf_stream *stream, 2408 unsigned int cmd, 2409 unsigned long arg) 2410 { 2411 switch (cmd) { 2412 case I915_PERF_IOCTL_ENABLE: 2413 i915_perf_enable_locked(stream); 2414 return 0; 2415 case I915_PERF_IOCTL_DISABLE: 2416 i915_perf_disable_locked(stream); 2417 return 0; 2418 } 2419 2420 return -EINVAL; 2421 } 2422 2423 /** 2424 * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs 2425 * @file: An i915 perf stream file 2426 * @cmd: the ioctl request 2427 * @arg: the ioctl data 2428 * 2429 * Implementation deferred to i915_perf_ioctl_locked(). 2430 * 2431 * Returns: zero on success or a negative error code. Returns -EINVAL for 2432 * an unknown ioctl request. 2433 */ 2434 static long i915_perf_ioctl(struct file *file, 2435 unsigned int cmd, 2436 unsigned long arg) 2437 { 2438 struct i915_perf_stream *stream = file->private_data; 2439 struct drm_i915_private *dev_priv = stream->dev_priv; 2440 long ret; 2441 2442 mutex_lock(&dev_priv->perf.lock); 2443 ret = i915_perf_ioctl_locked(stream, cmd, arg); 2444 mutex_unlock(&dev_priv->perf.lock); 2445 2446 return ret; 2447 } 2448 2449 /** 2450 * i915_perf_destroy_locked - destroy an i915 perf stream 2451 * @stream: An i915 perf stream 2452 * 2453 * Frees all resources associated with the given i915 perf @stream, disabling 2454 * any associated data capture in the process. 2455 * 2456 * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize 2457 * with any non-file-operation driver hooks. 2458 */ 2459 static void i915_perf_destroy_locked(struct i915_perf_stream *stream) 2460 { 2461 if (stream->enabled) 2462 i915_perf_disable_locked(stream); 2463 2464 if (stream->ops->destroy) 2465 stream->ops->destroy(stream); 2466 2467 list_del(&stream->link); 2468 2469 if (stream->ctx) 2470 i915_gem_context_put(stream->ctx); 2471 2472 kfree(stream); 2473 } 2474 2475 /** 2476 * i915_perf_release - handles userspace close() of a stream file 2477 * @inode: anonymous inode associated with file 2478 * @file: An i915 perf stream file 2479 * 2480 * Cleans up any resources associated with an open i915 perf stream file. 2481 * 2482 * NB: close() can't really fail from the userspace point of view. 2483 * 2484 * Returns: zero on success or a negative error code. 2485 */ 2486 static int i915_perf_release(struct inode *inode, struct file *file) 2487 { 2488 struct i915_perf_stream *stream = file->private_data; 2489 struct drm_i915_private *dev_priv = stream->dev_priv; 2490 2491 mutex_lock(&dev_priv->perf.lock); 2492 i915_perf_destroy_locked(stream); 2493 mutex_unlock(&dev_priv->perf.lock); 2494 2495 return 0; 2496 } 2497 2498 2499 static const struct file_operations fops = { 2500 .owner = THIS_MODULE, 2501 .llseek = no_llseek, 2502 .release = i915_perf_release, 2503 .poll = i915_perf_poll, 2504 .read = i915_perf_read, 2505 .unlocked_ioctl = i915_perf_ioctl, 2506 /* Our ioctl have no arguments, so it's safe to use the same function 2507 * to handle 32bits compatibility. 2508 */ 2509 .compat_ioctl = i915_perf_ioctl, 2510 }; 2511 2512 2513 /** 2514 * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD 2515 * @dev_priv: i915 device instance 2516 * @param: The open parameters passed to 'DRM_I915_PERF_OPEN` 2517 * @props: individually validated u64 property value pairs 2518 * @file: drm file 2519 * 2520 * See i915_perf_ioctl_open() for interface details. 2521 * 2522 * Implements further stream config validation and stream initialization on 2523 * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex 2524 * taken to serialize with any non-file-operation driver hooks. 2525 * 2526 * Note: at this point the @props have only been validated in isolation and 2527 * it's still necessary to validate that the combination of properties makes 2528 * sense. 2529 * 2530 * In the case where userspace is interested in OA unit metrics then further 2531 * config validation and stream initialization details will be handled by 2532 * i915_oa_stream_init(). The code here should only validate config state that 2533 * will be relevant to all stream types / backends. 2534 * 2535 * Returns: zero on success or a negative error code. 2536 */ 2537 static int 2538 i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv, 2539 struct drm_i915_perf_open_param *param, 2540 struct perf_open_properties *props, 2541 struct drm_file *file) 2542 { 2543 struct i915_gem_context *specific_ctx = NULL; 2544 struct i915_perf_stream *stream = NULL; 2545 unsigned long f_flags = 0; 2546 bool privileged_op = true; 2547 int stream_fd; 2548 int ret; 2549 2550 if (props->single_context) { 2551 u32 ctx_handle = props->ctx_handle; 2552 struct drm_i915_file_private *file_priv = file->driver_priv; 2553 2554 specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle); 2555 if (!specific_ctx) { 2556 DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n", 2557 ctx_handle); 2558 ret = -ENOENT; 2559 goto err; 2560 } 2561 } 2562 2563 /* 2564 * On Haswell the OA unit supports clock gating off for a specific 2565 * context and in this mode there's no visibility of metrics for the 2566 * rest of the system, which we consider acceptable for a 2567 * non-privileged client. 2568 * 2569 * For Gen8+ the OA unit no longer supports clock gating off for a 2570 * specific context and the kernel can't securely stop the counters 2571 * from updating as system-wide / global values. Even though we can 2572 * filter reports based on the included context ID we can't block 2573 * clients from seeing the raw / global counter values via 2574 * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to 2575 * enable the OA unit by default. 2576 */ 2577 if (IS_HASWELL(dev_priv) && specific_ctx) 2578 privileged_op = false; 2579 2580 /* Similar to perf's kernel.perf_paranoid_cpu sysctl option 2581 * we check a dev.i915.perf_stream_paranoid sysctl option 2582 * to determine if it's ok to access system wide OA counters 2583 * without CAP_SYS_ADMIN privileges. 2584 */ 2585 if (privileged_op && 2586 i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) { 2587 DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n"); 2588 ret = -EACCES; 2589 goto err_ctx; 2590 } 2591 2592 stream = kzalloc(sizeof(*stream), GFP_KERNEL); 2593 if (!stream) { 2594 ret = -ENOMEM; 2595 goto err_ctx; 2596 } 2597 2598 stream->dev_priv = dev_priv; 2599 stream->ctx = specific_ctx; 2600 2601 ret = i915_oa_stream_init(stream, param, props); 2602 if (ret) 2603 goto err_alloc; 2604 2605 /* we avoid simply assigning stream->sample_flags = props->sample_flags 2606 * to have _stream_init check the combination of sample flags more 2607 * thoroughly, but still this is the expected result at this point. 2608 */ 2609 if (WARN_ON(stream->sample_flags != props->sample_flags)) { 2610 ret = -ENODEV; 2611 goto err_flags; 2612 } 2613 2614 list_add(&stream->link, &dev_priv->perf.streams); 2615 2616 if (param->flags & I915_PERF_FLAG_FD_CLOEXEC) 2617 f_flags |= O_CLOEXEC; 2618 if (param->flags & I915_PERF_FLAG_FD_NONBLOCK) 2619 f_flags |= O_NONBLOCK; 2620 2621 stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags); 2622 if (stream_fd < 0) { 2623 ret = stream_fd; 2624 goto err_open; 2625 } 2626 2627 if (!(param->flags & I915_PERF_FLAG_DISABLED)) 2628 i915_perf_enable_locked(stream); 2629 2630 return stream_fd; 2631 2632 err_open: 2633 list_del(&stream->link); 2634 err_flags: 2635 if (stream->ops->destroy) 2636 stream->ops->destroy(stream); 2637 err_alloc: 2638 kfree(stream); 2639 err_ctx: 2640 if (specific_ctx) 2641 i915_gem_context_put(specific_ctx); 2642 err: 2643 return ret; 2644 } 2645 2646 static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent) 2647 { 2648 return div64_u64(1000000000ULL * (2ULL << exponent), 2649 1000ULL * INTEL_INFO(dev_priv)->cs_timestamp_frequency_khz); 2650 } 2651 2652 static int 2653 select_oa_buffer_exponent(struct drm_i915_private *i915, 2654 u64 requested_size) 2655 { 2656 int order; 2657 2658 /* 2659 * When no size is specified, use the largest size supported by all 2660 * generations. 2661 */ 2662 if (!requested_size) 2663 return order_base_2(SZ_16M); 2664 2665 order = order_base_2(clamp_t(u64, requested_size, SZ_128K, SZ_16M)); 2666 if (requested_size != (1UL << order)) 2667 return -EINVAL; 2668 2669 return order; 2670 } 2671 2672 /** 2673 * read_properties_unlocked - validate + copy userspace stream open properties 2674 * @dev_priv: i915 device instance 2675 * @uprops: The array of u64 key value pairs given by userspace 2676 * @n_props: The number of key value pairs expected in @uprops 2677 * @props: The stream configuration built up while validating properties 2678 * 2679 * Note this function only validates properties in isolation it doesn't 2680 * validate that the combination of properties makes sense or that all 2681 * properties necessary for a particular kind of stream have been set. 2682 * 2683 * Note that there currently aren't any ordering requirements for properties so 2684 * we shouldn't validate or assume anything about ordering here. This doesn't 2685 * rule out defining new properties with ordering requirements in the future. 2686 */ 2687 static int read_properties_unlocked(struct drm_i915_private *dev_priv, 2688 u64 __user *uprops, 2689 u32 n_props, 2690 struct perf_open_properties *props) 2691 { 2692 u64 __user *uprop = uprops; 2693 u32 i; 2694 2695 memset(props, 0, sizeof(struct perf_open_properties)); 2696 2697 if (!n_props) { 2698 DRM_DEBUG("No i915 perf properties given\n"); 2699 return -EINVAL; 2700 } 2701 2702 /* Considering that ID = 0 is reserved and assuming that we don't 2703 * (currently) expect any configurations to ever specify duplicate 2704 * values for a particular property ID then the last _PROP_MAX value is 2705 * one greater than the maximum number of properties we expect to get 2706 * from userspace. 2707 */ 2708 if (n_props >= DRM_I915_PERF_PROP_MAX) { 2709 DRM_DEBUG("More i915 perf properties specified than exist\n"); 2710 return -EINVAL; 2711 } 2712 2713 for (i = 0; i < n_props; i++) { 2714 u64 oa_period, oa_freq_hz; 2715 u64 id, value; 2716 int ret; 2717 2718 ret = get_user(id, uprop); 2719 if (ret) 2720 return ret; 2721 2722 ret = get_user(value, uprop + 1); 2723 if (ret) 2724 return ret; 2725 2726 if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) { 2727 DRM_DEBUG("Unknown i915 perf property ID\n"); 2728 return -EINVAL; 2729 } 2730 2731 switch ((enum drm_i915_perf_property_id)id) { 2732 case DRM_I915_PERF_PROP_CTX_HANDLE: 2733 props->single_context = 1; 2734 props->ctx_handle = value; 2735 break; 2736 case DRM_I915_PERF_PROP_SAMPLE_OA: 2737 if (value) 2738 props->sample_flags |= SAMPLE_OA_REPORT; 2739 break; 2740 case DRM_I915_PERF_PROP_OA_METRICS_SET: 2741 if (value == 0) { 2742 DRM_DEBUG("Unknown OA metric set ID\n"); 2743 return -EINVAL; 2744 } 2745 props->metrics_set = value; 2746 break; 2747 case DRM_I915_PERF_PROP_OA_FORMAT: 2748 if (value == 0 || value >= I915_OA_FORMAT_MAX) { 2749 DRM_DEBUG("Out-of-range OA report format %llu\n", 2750 value); 2751 return -EINVAL; 2752 } 2753 if (!dev_priv->perf.oa.oa_formats[value].size) { 2754 DRM_DEBUG("Unsupported OA report format %llu\n", 2755 value); 2756 return -EINVAL; 2757 } 2758 props->oa_format = value; 2759 break; 2760 case DRM_I915_PERF_PROP_OA_EXPONENT: 2761 if (value > OA_EXPONENT_MAX) { 2762 DRM_DEBUG("OA timer exponent too high (> %u)\n", 2763 OA_EXPONENT_MAX); 2764 return -EINVAL; 2765 } 2766 2767 /* Theoretically we can program the OA unit to sample 2768 * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns 2769 * for BXT. We don't allow such high sampling 2770 * frequencies by default unless root. 2771 */ 2772 2773 BUILD_BUG_ON(sizeof(oa_period) != 8); 2774 oa_period = oa_exponent_to_ns(dev_priv, value); 2775 2776 /* This check is primarily to ensure that oa_period <= 2777 * UINT32_MAX (before passing to do_div which only 2778 * accepts a u32 denominator), but we can also skip 2779 * checking anything < 1Hz which implicitly can't be 2780 * limited via an integer oa_max_sample_rate. 2781 */ 2782 if (oa_period <= NSEC_PER_SEC) { 2783 u64 tmp = NSEC_PER_SEC; 2784 do_div(tmp, oa_period); 2785 oa_freq_hz = tmp; 2786 } else 2787 oa_freq_hz = 0; 2788 2789 if (oa_freq_hz > i915_oa_max_sample_rate && 2790 !capable(CAP_SYS_ADMIN)) { 2791 DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n", 2792 i915_oa_max_sample_rate); 2793 return -EACCES; 2794 } 2795 2796 props->oa_periodic = true; 2797 props->oa_period_exponent = value; 2798 break; 2799 case DRM_I915_PERF_PROP_OA_BUFFER_SIZE: 2800 ret = select_oa_buffer_exponent(dev_priv, value); 2801 if (ret < 0) { 2802 DRM_DEBUG("OA buffer size invalid %llu\n", value); 2803 return ret; 2804 } 2805 props->oa_buffer_size_exponent = ret; 2806 break; 2807 case DRM_I915_PERF_PROP_MAX: 2808 MISSING_CASE(id); 2809 return -EINVAL; 2810 } 2811 2812 uprop += 2; 2813 } 2814 2815 /* If no buffer size was requested, select the default one. */ 2816 if (!props->oa_buffer_size_exponent) { 2817 props->oa_buffer_size_exponent = 2818 select_oa_buffer_exponent(dev_priv, 0); 2819 } 2820 2821 return 0; 2822 } 2823 2824 /** 2825 * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD 2826 * @dev: drm device 2827 * @data: ioctl data copied from userspace (unvalidated) 2828 * @file: drm file 2829 * 2830 * Validates the stream open parameters given by userspace including flags 2831 * and an array of u64 key, value pair properties. 2832 * 2833 * Very little is assumed up front about the nature of the stream being 2834 * opened (for instance we don't assume it's for periodic OA unit metrics). An 2835 * i915-perf stream is expected to be a suitable interface for other forms of 2836 * buffered data written by the GPU besides periodic OA metrics. 2837 * 2838 * Note we copy the properties from userspace outside of the i915 perf 2839 * mutex to avoid an awkward lockdep with mmap_sem. 2840 * 2841 * Most of the implementation details are handled by 2842 * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock 2843 * mutex for serializing with any non-file-operation driver hooks. 2844 * 2845 * Return: A newly opened i915 Perf stream file descriptor or negative 2846 * error code on failure. 2847 */ 2848 int i915_perf_open_ioctl(struct drm_device *dev, void *data, 2849 struct drm_file *file) 2850 { 2851 struct drm_i915_private *dev_priv = dev->dev_private; 2852 struct drm_i915_perf_open_param *param = data; 2853 struct perf_open_properties props; 2854 u32 known_open_flags; 2855 int ret; 2856 2857 if (!dev_priv->perf.initialized) { 2858 DRM_DEBUG("i915 perf interface not available for this system\n"); 2859 return -ENOTSUPP; 2860 } 2861 2862 known_open_flags = I915_PERF_FLAG_FD_CLOEXEC | 2863 I915_PERF_FLAG_FD_NONBLOCK | 2864 I915_PERF_FLAG_DISABLED; 2865 if (param->flags & ~known_open_flags) { 2866 DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n"); 2867 return -EINVAL; 2868 } 2869 2870 ret = read_properties_unlocked(dev_priv, 2871 u64_to_user_ptr(param->properties_ptr), 2872 param->num_properties, 2873 &props); 2874 if (ret) 2875 return ret; 2876 2877 mutex_lock(&dev_priv->perf.lock); 2878 ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file); 2879 mutex_unlock(&dev_priv->perf.lock); 2880 2881 return ret; 2882 } 2883 2884 /** 2885 * i915_perf_register - exposes i915-perf to userspace 2886 * @dev_priv: i915 device instance 2887 * 2888 * In particular OA metric sets are advertised under a sysfs metrics/ 2889 * directory allowing userspace to enumerate valid IDs that can be 2890 * used to open an i915-perf stream. 2891 */ 2892 void i915_perf_register(struct drm_i915_private *dev_priv) 2893 { 2894 int ret; 2895 2896 if (!dev_priv->perf.initialized) 2897 return; 2898 2899 /* To be sure we're synchronized with an attempted 2900 * i915_perf_open_ioctl(); considering that we register after 2901 * being exposed to userspace. 2902 */ 2903 mutex_lock(&dev_priv->perf.lock); 2904 2905 dev_priv->perf.metrics_kobj = 2906 kobject_create_and_add("metrics", 2907 &dev_priv->drm.primary->kdev->kobj); 2908 if (!dev_priv->perf.metrics_kobj) 2909 goto exit; 2910 2911 sysfs_attr_init(&dev_priv->perf.oa.test_config.sysfs_metric_id.attr); 2912 2913 if (IS_HASWELL(dev_priv)) { 2914 i915_perf_load_test_config_hsw(dev_priv); 2915 } else if (IS_BROADWELL(dev_priv)) { 2916 i915_perf_load_test_config_bdw(dev_priv); 2917 } else if (IS_CHERRYVIEW(dev_priv)) { 2918 i915_perf_load_test_config_chv(dev_priv); 2919 } else if (IS_SKYLAKE(dev_priv)) { 2920 if (IS_SKL_GT2(dev_priv)) 2921 i915_perf_load_test_config_sklgt2(dev_priv); 2922 else if (IS_SKL_GT3(dev_priv)) 2923 i915_perf_load_test_config_sklgt3(dev_priv); 2924 else if (IS_SKL_GT4(dev_priv)) 2925 i915_perf_load_test_config_sklgt4(dev_priv); 2926 } else if (IS_BROXTON(dev_priv)) { 2927 i915_perf_load_test_config_bxt(dev_priv); 2928 } else if (IS_KABYLAKE(dev_priv)) { 2929 if (IS_KBL_GT2(dev_priv)) 2930 i915_perf_load_test_config_kblgt2(dev_priv); 2931 else if (IS_KBL_GT3(dev_priv)) 2932 i915_perf_load_test_config_kblgt3(dev_priv); 2933 } else if (IS_GEMINILAKE(dev_priv)) { 2934 i915_perf_load_test_config_glk(dev_priv); 2935 } else if (IS_COFFEELAKE(dev_priv)) { 2936 if (IS_CFL_GT2(dev_priv)) 2937 i915_perf_load_test_config_cflgt2(dev_priv); 2938 if (IS_CFL_GT3(dev_priv)) 2939 i915_perf_load_test_config_cflgt3(dev_priv); 2940 } else if (IS_CANNONLAKE(dev_priv)) { 2941 i915_perf_load_test_config_cnl(dev_priv); 2942 } else if (IS_ICELAKE(dev_priv)) { 2943 i915_perf_load_test_config_icl(dev_priv); 2944 } 2945 2946 if (dev_priv->perf.oa.test_config.id == 0) 2947 goto sysfs_error; 2948 2949 ret = sysfs_create_group(dev_priv->perf.metrics_kobj, 2950 &dev_priv->perf.oa.test_config.sysfs_metric); 2951 if (ret) 2952 goto sysfs_error; 2953 2954 atomic_set(&dev_priv->perf.oa.test_config.ref_count, 1); 2955 2956 goto exit; 2957 2958 sysfs_error: 2959 kobject_put(dev_priv->perf.metrics_kobj); 2960 dev_priv->perf.metrics_kobj = NULL; 2961 2962 exit: 2963 mutex_unlock(&dev_priv->perf.lock); 2964 } 2965 2966 /** 2967 * i915_perf_unregister - hide i915-perf from userspace 2968 * @dev_priv: i915 device instance 2969 * 2970 * i915-perf state cleanup is split up into an 'unregister' and 2971 * 'deinit' phase where the interface is first hidden from 2972 * userspace by i915_perf_unregister() before cleaning up 2973 * remaining state in i915_perf_fini(). 2974 */ 2975 void i915_perf_unregister(struct drm_i915_private *dev_priv) 2976 { 2977 if (!dev_priv->perf.metrics_kobj) 2978 return; 2979 2980 sysfs_remove_group(dev_priv->perf.metrics_kobj, 2981 &dev_priv->perf.oa.test_config.sysfs_metric); 2982 2983 kobject_put(dev_priv->perf.metrics_kobj); 2984 dev_priv->perf.metrics_kobj = NULL; 2985 } 2986 2987 static bool gen8_is_valid_flex_addr(struct drm_i915_private *dev_priv, u32 addr) 2988 { 2989 static const i915_reg_t flex_eu_regs[] = { 2990 EU_PERF_CNTL0, 2991 EU_PERF_CNTL1, 2992 EU_PERF_CNTL2, 2993 EU_PERF_CNTL3, 2994 EU_PERF_CNTL4, 2995 EU_PERF_CNTL5, 2996 EU_PERF_CNTL6, 2997 }; 2998 int i; 2999 3000 for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) { 3001 if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr) 3002 return true; 3003 } 3004 return false; 3005 } 3006 3007 static bool gen7_is_valid_b_counter_addr(struct drm_i915_private *dev_priv, u32 addr) 3008 { 3009 return (addr >= i915_mmio_reg_offset(OASTARTTRIG1) && 3010 addr <= i915_mmio_reg_offset(OASTARTTRIG8)) || 3011 (addr >= i915_mmio_reg_offset(OAREPORTTRIG1) && 3012 addr <= i915_mmio_reg_offset(OAREPORTTRIG8)) || 3013 (addr >= i915_mmio_reg_offset(OACEC0_0) && 3014 addr <= i915_mmio_reg_offset(OACEC7_1)); 3015 } 3016 3017 static bool gen7_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr) 3018 { 3019 return addr == i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) || 3020 (addr >= i915_mmio_reg_offset(MICRO_BP0_0) && 3021 addr <= i915_mmio_reg_offset(NOA_WRITE)) || 3022 (addr >= i915_mmio_reg_offset(OA_PERFCNT1_LO) && 3023 addr <= i915_mmio_reg_offset(OA_PERFCNT2_HI)) || 3024 (addr >= i915_mmio_reg_offset(OA_PERFMATRIX_LO) && 3025 addr <= i915_mmio_reg_offset(OA_PERFMATRIX_HI)); 3026 } 3027 3028 static bool gen8_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr) 3029 { 3030 return gen7_is_valid_mux_addr(dev_priv, addr) || 3031 addr == i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) || 3032 (addr >= i915_mmio_reg_offset(RPM_CONFIG0) && 3033 addr <= i915_mmio_reg_offset(NOA_CONFIG(8))); 3034 } 3035 3036 static bool gen10_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr) 3037 { 3038 return gen8_is_valid_mux_addr(dev_priv, addr) || 3039 (addr >= i915_mmio_reg_offset(OA_PERFCNT3_LO) && 3040 addr <= i915_mmio_reg_offset(OA_PERFCNT4_HI)); 3041 } 3042 3043 static bool hsw_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr) 3044 { 3045 return gen7_is_valid_mux_addr(dev_priv, addr) || 3046 (addr >= 0x25100 && addr <= 0x2FF90) || 3047 (addr >= i915_mmio_reg_offset(HSW_MBVID2_NOA0) && 3048 addr <= i915_mmio_reg_offset(HSW_MBVID2_NOA9)) || 3049 addr == i915_mmio_reg_offset(HSW_MBVID2_MISR0); 3050 } 3051 3052 static bool chv_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr) 3053 { 3054 return gen7_is_valid_mux_addr(dev_priv, addr) || 3055 (addr >= 0x182300 && addr <= 0x1823A4); 3056 } 3057 3058 static uint32_t mask_reg_value(u32 reg, u32 val) 3059 { 3060 /* HALF_SLICE_CHICKEN2 is programmed with a the 3061 * WaDisableSTUnitPowerOptimization workaround. Make sure the value 3062 * programmed by userspace doesn't change this. 3063 */ 3064 if (i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) == reg) 3065 val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE); 3066 3067 /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function 3068 * indicated by its name and a bunch of selection fields used by OA 3069 * configs. 3070 */ 3071 if (i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) == reg) 3072 val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE); 3073 3074 return val; 3075 } 3076 3077 static struct i915_oa_reg *alloc_oa_regs(struct drm_i915_private *dev_priv, 3078 bool (*is_valid)(struct drm_i915_private *dev_priv, u32 addr), 3079 u32 __user *regs, 3080 u32 n_regs) 3081 { 3082 struct i915_oa_reg *oa_regs; 3083 int err; 3084 u32 i; 3085 3086 if (!n_regs) 3087 return NULL; 3088 3089 if (!access_ok(VERIFY_READ, regs, n_regs * sizeof(u32) * 2)) 3090 return ERR_PTR(-EFAULT); 3091 3092 /* No is_valid function means we're not allowing any register to be programmed. */ 3093 GEM_BUG_ON(!is_valid); 3094 if (!is_valid) 3095 return ERR_PTR(-EINVAL); 3096 3097 oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL); 3098 if (!oa_regs) 3099 return ERR_PTR(-ENOMEM); 3100 3101 for (i = 0; i < n_regs; i++) { 3102 u32 addr, value; 3103 3104 err = get_user(addr, regs); 3105 if (err) 3106 goto addr_err; 3107 3108 if (!is_valid(dev_priv, addr)) { 3109 DRM_DEBUG("Invalid oa_reg address: %X\n", addr); 3110 err = -EINVAL; 3111 goto addr_err; 3112 } 3113 3114 err = get_user(value, regs + 1); 3115 if (err) 3116 goto addr_err; 3117 3118 oa_regs[i].addr = _MMIO(addr); 3119 oa_regs[i].value = mask_reg_value(addr, value); 3120 3121 regs += 2; 3122 } 3123 3124 return oa_regs; 3125 3126 addr_err: 3127 kfree(oa_regs); 3128 return ERR_PTR(err); 3129 } 3130 3131 static ssize_t show_dynamic_id(struct device *dev, 3132 struct device_attribute *attr, 3133 char *buf) 3134 { 3135 struct i915_oa_config *oa_config = 3136 container_of(attr, typeof(*oa_config), sysfs_metric_id); 3137 3138 return sprintf(buf, "%d\n", oa_config->id); 3139 } 3140 3141 static int create_dynamic_oa_sysfs_entry(struct drm_i915_private *dev_priv, 3142 struct i915_oa_config *oa_config) 3143 { 3144 sysfs_attr_init(&oa_config->sysfs_metric_id.attr); 3145 oa_config->sysfs_metric_id.attr.name = "id"; 3146 oa_config->sysfs_metric_id.attr.mode = S_IRUGO; 3147 oa_config->sysfs_metric_id.show = show_dynamic_id; 3148 oa_config->sysfs_metric_id.store = NULL; 3149 3150 oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr; 3151 oa_config->attrs[1] = NULL; 3152 3153 oa_config->sysfs_metric.name = oa_config->uuid; 3154 oa_config->sysfs_metric.attrs = oa_config->attrs; 3155 3156 return sysfs_create_group(dev_priv->perf.metrics_kobj, 3157 &oa_config->sysfs_metric); 3158 } 3159 3160 /** 3161 * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config 3162 * @dev: drm device 3163 * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from 3164 * userspace (unvalidated) 3165 * @file: drm file 3166 * 3167 * Validates the submitted OA register to be saved into a new OA config that 3168 * can then be used for programming the OA unit and its NOA network. 3169 * 3170 * Returns: A new allocated config number to be used with the perf open ioctl 3171 * or a negative error code on failure. 3172 */ 3173 int i915_perf_add_config_ioctl(struct drm_device *dev, void *data, 3174 struct drm_file *file) 3175 { 3176 struct drm_i915_private *dev_priv = dev->dev_private; 3177 struct drm_i915_perf_oa_config *args = data; 3178 struct i915_oa_config *oa_config, *tmp; 3179 int err, id; 3180 3181 if (!dev_priv->perf.initialized) { 3182 DRM_DEBUG("i915 perf interface not available for this system\n"); 3183 return -ENOTSUPP; 3184 } 3185 3186 if (!dev_priv->perf.metrics_kobj) { 3187 DRM_DEBUG("OA metrics weren't advertised via sysfs\n"); 3188 return -EINVAL; 3189 } 3190 3191 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) { 3192 DRM_DEBUG("Insufficient privileges to add i915 OA config\n"); 3193 return -EACCES; 3194 } 3195 3196 if ((!args->mux_regs_ptr || !args->n_mux_regs) && 3197 (!args->boolean_regs_ptr || !args->n_boolean_regs) && 3198 (!args->flex_regs_ptr || !args->n_flex_regs)) { 3199 DRM_DEBUG("No OA registers given\n"); 3200 return -EINVAL; 3201 } 3202 3203 oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL); 3204 if (!oa_config) { 3205 DRM_DEBUG("Failed to allocate memory for the OA config\n"); 3206 return -ENOMEM; 3207 } 3208 3209 atomic_set(&oa_config->ref_count, 1); 3210 3211 if (!uuid_is_valid(args->uuid)) { 3212 DRM_DEBUG("Invalid uuid format for OA config\n"); 3213 err = -EINVAL; 3214 goto reg_err; 3215 } 3216 3217 /* Last character in oa_config->uuid will be 0 because oa_config is 3218 * kzalloc. 3219 */ 3220 memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid)); 3221 3222 oa_config->mux_regs_len = args->n_mux_regs; 3223 oa_config->mux_regs = 3224 alloc_oa_regs(dev_priv, 3225 dev_priv->perf.oa.ops.is_valid_mux_reg, 3226 u64_to_user_ptr(args->mux_regs_ptr), 3227 args->n_mux_regs); 3228 3229 if (IS_ERR(oa_config->mux_regs)) { 3230 DRM_DEBUG("Failed to create OA config for mux_regs\n"); 3231 err = PTR_ERR(oa_config->mux_regs); 3232 goto reg_err; 3233 } 3234 3235 oa_config->b_counter_regs_len = args->n_boolean_regs; 3236 oa_config->b_counter_regs = 3237 alloc_oa_regs(dev_priv, 3238 dev_priv->perf.oa.ops.is_valid_b_counter_reg, 3239 u64_to_user_ptr(args->boolean_regs_ptr), 3240 args->n_boolean_regs); 3241 3242 if (IS_ERR(oa_config->b_counter_regs)) { 3243 DRM_DEBUG("Failed to create OA config for b_counter_regs\n"); 3244 err = PTR_ERR(oa_config->b_counter_regs); 3245 goto reg_err; 3246 } 3247 3248 if (INTEL_GEN(dev_priv) < 8) { 3249 if (args->n_flex_regs != 0) { 3250 err = -EINVAL; 3251 goto reg_err; 3252 } 3253 } else { 3254 oa_config->flex_regs_len = args->n_flex_regs; 3255 oa_config->flex_regs = 3256 alloc_oa_regs(dev_priv, 3257 dev_priv->perf.oa.ops.is_valid_flex_reg, 3258 u64_to_user_ptr(args->flex_regs_ptr), 3259 args->n_flex_regs); 3260 3261 if (IS_ERR(oa_config->flex_regs)) { 3262 DRM_DEBUG("Failed to create OA config for flex_regs\n"); 3263 err = PTR_ERR(oa_config->flex_regs); 3264 goto reg_err; 3265 } 3266 } 3267 3268 err = mutex_lock_interruptible(&dev_priv->perf.metrics_lock); 3269 if (err) 3270 goto reg_err; 3271 3272 /* We shouldn't have too many configs, so this iteration shouldn't be 3273 * too costly. 3274 */ 3275 idr_for_each_entry(&dev_priv->perf.metrics_idr, tmp, id) { 3276 if (!strcmp(tmp->uuid, oa_config->uuid)) { 3277 DRM_DEBUG("OA config already exists with this uuid\n"); 3278 err = -EADDRINUSE; 3279 goto sysfs_err; 3280 } 3281 } 3282 3283 err = create_dynamic_oa_sysfs_entry(dev_priv, oa_config); 3284 if (err) { 3285 DRM_DEBUG("Failed to create sysfs entry for OA config\n"); 3286 goto sysfs_err; 3287 } 3288 3289 /* Config id 0 is invalid, id 1 for kernel stored test config. */ 3290 oa_config->id = idr_alloc(&dev_priv->perf.metrics_idr, 3291 oa_config, 2, 3292 0, GFP_KERNEL); 3293 if (oa_config->id < 0) { 3294 DRM_DEBUG("Failed to create sysfs entry for OA config\n"); 3295 err = oa_config->id; 3296 goto sysfs_err; 3297 } 3298 3299 mutex_unlock(&dev_priv->perf.metrics_lock); 3300 3301 DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id); 3302 3303 return oa_config->id; 3304 3305 sysfs_err: 3306 mutex_unlock(&dev_priv->perf.metrics_lock); 3307 reg_err: 3308 put_oa_config(dev_priv, oa_config); 3309 DRM_DEBUG("Failed to add new OA config\n"); 3310 return err; 3311 } 3312 3313 /** 3314 * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config 3315 * @dev: drm device 3316 * @data: ioctl data (pointer to u64 integer) copied from userspace 3317 * @file: drm file 3318 * 3319 * Configs can be removed while being used, the will stop appearing in sysfs 3320 * and their content will be freed when the stream using the config is closed. 3321 * 3322 * Returns: 0 on success or a negative error code on failure. 3323 */ 3324 int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data, 3325 struct drm_file *file) 3326 { 3327 struct drm_i915_private *dev_priv = dev->dev_private; 3328 u64 *arg = data; 3329 struct i915_oa_config *oa_config; 3330 int ret; 3331 3332 if (!dev_priv->perf.initialized) { 3333 DRM_DEBUG("i915 perf interface not available for this system\n"); 3334 return -ENOTSUPP; 3335 } 3336 3337 if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) { 3338 DRM_DEBUG("Insufficient privileges to remove i915 OA config\n"); 3339 return -EACCES; 3340 } 3341 3342 ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock); 3343 if (ret) 3344 goto lock_err; 3345 3346 oa_config = idr_find(&dev_priv->perf.metrics_idr, *arg); 3347 if (!oa_config) { 3348 DRM_DEBUG("Failed to remove unknown OA config\n"); 3349 ret = -ENOENT; 3350 goto config_err; 3351 } 3352 3353 GEM_BUG_ON(*arg != oa_config->id); 3354 3355 sysfs_remove_group(dev_priv->perf.metrics_kobj, 3356 &oa_config->sysfs_metric); 3357 3358 idr_remove(&dev_priv->perf.metrics_idr, *arg); 3359 3360 DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id); 3361 3362 put_oa_config(dev_priv, oa_config); 3363 3364 config_err: 3365 mutex_unlock(&dev_priv->perf.metrics_lock); 3366 lock_err: 3367 return ret; 3368 } 3369 3370 static struct ctl_table oa_table[] = { 3371 { 3372 .procname = "perf_stream_paranoid", 3373 .data = &i915_perf_stream_paranoid, 3374 .maxlen = sizeof(i915_perf_stream_paranoid), 3375 .mode = 0644, 3376 .proc_handler = proc_dointvec_minmax, 3377 .extra1 = &zero, 3378 .extra2 = &one, 3379 }, 3380 { 3381 .procname = "oa_max_sample_rate", 3382 .data = &i915_oa_max_sample_rate, 3383 .maxlen = sizeof(i915_oa_max_sample_rate), 3384 .mode = 0644, 3385 .proc_handler = proc_dointvec_minmax, 3386 .extra1 = &zero, 3387 .extra2 = &oa_sample_rate_hard_limit, 3388 }, 3389 {} 3390 }; 3391 3392 static struct ctl_table i915_root[] = { 3393 { 3394 .procname = "i915", 3395 .maxlen = 0, 3396 .mode = 0555, 3397 .child = oa_table, 3398 }, 3399 {} 3400 }; 3401 3402 static struct ctl_table dev_root[] = { 3403 { 3404 .procname = "dev", 3405 .maxlen = 0, 3406 .mode = 0555, 3407 .child = i915_root, 3408 }, 3409 {} 3410 }; 3411 3412 /** 3413 * i915_perf_init - initialize i915-perf state on module load 3414 * @dev_priv: i915 device instance 3415 * 3416 * Initializes i915-perf state without exposing anything to userspace. 3417 * 3418 * Note: i915-perf initialization is split into an 'init' and 'register' 3419 * phase with the i915_perf_register() exposing state to userspace. 3420 */ 3421 void i915_perf_init(struct drm_i915_private *dev_priv) 3422 { 3423 if (IS_HASWELL(dev_priv)) { 3424 dev_priv->perf.oa.ops.is_valid_b_counter_reg = 3425 gen7_is_valid_b_counter_addr; 3426 dev_priv->perf.oa.ops.is_valid_mux_reg = 3427 hsw_is_valid_mux_addr; 3428 dev_priv->perf.oa.ops.is_valid_flex_reg = NULL; 3429 dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set; 3430 dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set; 3431 dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable; 3432 dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable; 3433 dev_priv->perf.oa.ops.read = gen7_oa_read; 3434 dev_priv->perf.oa.ops.oa_hw_tail_read = 3435 gen7_oa_hw_tail_read; 3436 3437 dev_priv->perf.oa.oa_formats = hsw_oa_formats; 3438 } else if (HAS_LOGICAL_RING_CONTEXTS(dev_priv)) { 3439 /* Note: that although we could theoretically also support the 3440 * legacy ringbuffer mode on BDW (and earlier iterations of 3441 * this driver, before upstreaming did this) it didn't seem 3442 * worth the complexity to maintain now that BDW+ enable 3443 * execlist mode by default. 3444 */ 3445 dev_priv->perf.oa.oa_formats = gen8_plus_oa_formats; 3446 3447 dev_priv->perf.oa.ops.oa_enable = gen8_oa_enable; 3448 dev_priv->perf.oa.ops.oa_disable = gen8_oa_disable; 3449 dev_priv->perf.oa.ops.read = gen8_oa_read; 3450 dev_priv->perf.oa.ops.oa_hw_tail_read = gen8_oa_hw_tail_read; 3451 3452 if (IS_GEN8(dev_priv) || IS_GEN9(dev_priv)) { 3453 dev_priv->perf.oa.ops.is_valid_b_counter_reg = 3454 gen7_is_valid_b_counter_addr; 3455 dev_priv->perf.oa.ops.is_valid_mux_reg = 3456 gen8_is_valid_mux_addr; 3457 dev_priv->perf.oa.ops.is_valid_flex_reg = 3458 gen8_is_valid_flex_addr; 3459 3460 if (IS_CHERRYVIEW(dev_priv)) { 3461 dev_priv->perf.oa.ops.is_valid_mux_reg = 3462 chv_is_valid_mux_addr; 3463 } 3464 3465 dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set; 3466 dev_priv->perf.oa.ops.disable_metric_set = gen8_disable_metric_set; 3467 3468 if (IS_GEN8(dev_priv)) { 3469 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x120; 3470 dev_priv->perf.oa.ctx_flexeu0_offset = 0x2ce; 3471 3472 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<25); 3473 } else { 3474 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128; 3475 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de; 3476 3477 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16); 3478 } 3479 } else if (IS_GEN(dev_priv, 10, 11)) { 3480 dev_priv->perf.oa.ops.is_valid_b_counter_reg = 3481 gen7_is_valid_b_counter_addr; 3482 dev_priv->perf.oa.ops.is_valid_mux_reg = 3483 gen10_is_valid_mux_addr; 3484 dev_priv->perf.oa.ops.is_valid_flex_reg = 3485 gen8_is_valid_flex_addr; 3486 3487 dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set; 3488 dev_priv->perf.oa.ops.disable_metric_set = gen10_disable_metric_set; 3489 3490 dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128; 3491 dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de; 3492 3493 dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16); 3494 } 3495 } 3496 3497 if (dev_priv->perf.oa.ops.enable_metric_set) { 3498 hrtimer_init(&dev_priv->perf.oa.poll_check_timer, 3499 CLOCK_MONOTONIC, HRTIMER_MODE_REL); 3500 dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb; 3501 init_waitqueue_head(&dev_priv->perf.oa.poll_wq); 3502 3503 INIT_LIST_HEAD(&dev_priv->perf.streams); 3504 mutex_init(&dev_priv->perf.lock); 3505 spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock); 3506 3507 oa_sample_rate_hard_limit = 1000 * 3508 (INTEL_INFO(dev_priv)->cs_timestamp_frequency_khz / 2); 3509 dev_priv->perf.sysctl_header = register_sysctl_table(dev_root); 3510 3511 mutex_init(&dev_priv->perf.metrics_lock); 3512 idr_init(&dev_priv->perf.metrics_idr); 3513 3514 dev_priv->perf.initialized = true; 3515 } 3516 } 3517 3518 static int destroy_config(int id, void *p, void *data) 3519 { 3520 struct drm_i915_private *dev_priv = data; 3521 struct i915_oa_config *oa_config = p; 3522 3523 put_oa_config(dev_priv, oa_config); 3524 3525 return 0; 3526 } 3527 3528 /** 3529 * i915_perf_fini - Counter part to i915_perf_init() 3530 * @dev_priv: i915 device instance 3531 */ 3532 void i915_perf_fini(struct drm_i915_private *dev_priv) 3533 { 3534 if (!dev_priv->perf.initialized) 3535 return; 3536 3537 idr_for_each(&dev_priv->perf.metrics_idr, destroy_config, dev_priv); 3538 idr_destroy(&dev_priv->perf.metrics_idr); 3539 3540 unregister_sysctl_table(dev_priv->perf.sysctl_header); 3541 3542 memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops)); 3543 3544 dev_priv->perf.initialized = false; 3545 } 3546