intel/perf: Enable MDAPI queries for Gen12
[mesa.git] / src / intel / perf / gen_perf_query.c
1 /*
2 * Copyright © 2019 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
24 #include <unistd.h>
25
26 #include "common/gen_gem.h"
27
28 #include "dev/gen_debug.h"
29 #include "dev/gen_device_info.h"
30
31 #include "perf/gen_perf.h"
32 #include "perf/gen_perf_mdapi.h"
33 #include "perf/gen_perf_query.h"
34 #include "perf/gen_perf_regs.h"
35
36 #include "drm-uapi/i915_drm.h"
37
38 #include "util/u_math.h"
39
40 #define FILE_DEBUG_FLAG DEBUG_PERFMON
41 #define MI_RPC_BO_SIZE 4096
42 #define MI_FREQ_START_OFFSET_BYTES (3072)
43 #define MI_RPC_BO_END_OFFSET_BYTES (MI_RPC_BO_SIZE / 2)
44 #define MI_FREQ_END_OFFSET_BYTES (3076)
45
46 #define MAP_READ (1 << 0)
47 #define MAP_WRITE (1 << 1)
48
49 /**
50 * Periodic OA samples are read() into these buffer structures via the
51 * i915 perf kernel interface and appended to the
52 * perf_ctx->sample_buffers linked list. When we process the
53 * results of an OA metrics query we need to consider all the periodic
54 * samples between the Begin and End MI_REPORT_PERF_COUNT command
55 * markers.
56 *
57 * 'Periodic' is a simplification as there are other automatic reports
58 * written by the hardware also buffered here.
59 *
60 * Considering three queries, A, B and C:
61 *
62 * Time ---->
63 * ________________A_________________
64 * | |
65 * | ________B_________ _____C___________
66 * | | | | | |
67 *
68 * And an illustration of sample buffers read over this time frame:
69 * [HEAD ][ ][ ][ ][ ][ ][ ][ ][TAIL ]
70 *
71 * These nodes may hold samples for query A:
72 * [ ][ ][ A ][ A ][ A ][ A ][ A ][ ][ ]
73 *
74 * These nodes may hold samples for query B:
75 * [ ][ ][ B ][ B ][ B ][ ][ ][ ][ ]
76 *
77 * These nodes may hold samples for query C:
78 * [ ][ ][ ][ ][ ][ C ][ C ][ C ][ ]
79 *
80 * The illustration assumes we have an even distribution of periodic
81 * samples so all nodes have the same size plotted against time:
82 *
83 * Note, to simplify code, the list is never empty.
84 *
85 * With overlapping queries we can see that periodic OA reports may
86 * relate to multiple queries and care needs to be take to keep
87 * track of sample buffers until there are no queries that might
88 * depend on their contents.
89 *
90 * We use a node ref counting system where a reference ensures that a
91 * node and all following nodes can't be freed/recycled until the
92 * reference drops to zero.
93 *
94 * E.g. with a ref of one here:
95 * [ 0 ][ 0 ][ 1 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ]
96 *
97 * These nodes could be freed or recycled ("reaped"):
98 * [ 0 ][ 0 ]
99 *
100 * These must be preserved until the leading ref drops to zero:
101 * [ 1 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ]
102 *
103 * When a query starts we take a reference on the current tail of
104 * the list, knowing that no already-buffered samples can possibly
105 * relate to the newly-started query. A pointer to this node is
106 * also saved in the query object's ->oa.samples_head.
107 *
108 * E.g. starting query A while there are two nodes in .sample_buffers:
109 * ________________A________
110 * |
111 *
112 * [ 0 ][ 1 ]
113 * ^_______ Add a reference and store pointer to node in
114 * A->oa.samples_head
115 *
116 * Moving forward to when the B query starts with no new buffer nodes:
117 * (for reference, i915 perf reads() are only done when queries finish)
118 * ________________A_______
119 * | ________B___
120 * | |
121 *
122 * [ 0 ][ 2 ]
123 * ^_______ Add a reference and store pointer to
124 * node in B->oa.samples_head
125 *
126 * Once a query is finished, after an OA query has become 'Ready',
127 * once the End OA report has landed and after we we have processed
128 * all the intermediate periodic samples then we drop the
129 * ->oa.samples_head reference we took at the start.
130 *
131 * So when the B query has finished we have:
132 * ________________A________
133 * | ______B___________
134 * | | |
135 * [ 0 ][ 1 ][ 0 ][ 0 ][ 0 ]
136 * ^_______ Drop B->oa.samples_head reference
137 *
138 * We still can't free these due to the A->oa.samples_head ref:
139 * [ 1 ][ 0 ][ 0 ][ 0 ]
140 *
141 * When the A query finishes: (note there's a new ref for C's samples_head)
142 * ________________A_________________
143 * | |
144 * | _____C_________
145 * | | |
146 * [ 0 ][ 0 ][ 0 ][ 0 ][ 1 ][ 0 ][ 0 ]
147 * ^_______ Drop A->oa.samples_head reference
148 *
149 * And we can now reap these nodes up to the C->oa.samples_head:
150 * [ X ][ X ][ X ][ X ]
151 * keeping -> [ 1 ][ 0 ][ 0 ]
152 *
153 * We reap old sample buffers each time we finish processing an OA
154 * query by iterating the sample_buffers list from the head until we
155 * find a referenced node and stop.
156 *
157 * Reaped buffers move to a perfquery.free_sample_buffers list and
158 * when we come to read() we first look to recycle a buffer from the
159 * free_sample_buffers list before allocating a new buffer.
160 */
161 struct oa_sample_buf {
162 struct exec_node link;
163 int refcount;
164 int len;
165 uint8_t buf[I915_PERF_OA_SAMPLE_SIZE * 10];
166 uint32_t last_timestamp;
167 };
168
169 /**
170 * gen representation of a performance query object.
171 *
172 * NB: We want to keep this structure relatively lean considering that
173 * applications may expect to allocate enough objects to be able to
174 * query around all draw calls in a frame.
175 */
176 struct gen_perf_query_object
177 {
178 const struct gen_perf_query_info *queryinfo;
179
180 /* See query->kind to know which state below is in use... */
181 union {
182 struct {
183
184 /**
185 * BO containing OA counter snapshots at query Begin/End time.
186 */
187 void *bo;
188
189 /**
190 * Address of mapped of @bo
191 */
192 void *map;
193
194 /**
195 * The MI_REPORT_PERF_COUNT command lets us specify a unique
196 * ID that will be reflected in the resulting OA report
197 * that's written by the GPU. This is the ID we're expecting
198 * in the begin report and the the end report should be
199 * @begin_report_id + 1.
200 */
201 int begin_report_id;
202
203 /**
204 * Reference the head of the brw->perfquery.sample_buffers
205 * list at the time that the query started (so we only need
206 * to look at nodes after this point when looking for samples
207 * related to this query)
208 *
209 * (See struct brw_oa_sample_buf description for more details)
210 */
211 struct exec_node *samples_head;
212
213 /**
214 * false while in the unaccumulated_elements list, and set to
215 * true when the final, end MI_RPC snapshot has been
216 * accumulated.
217 */
218 bool results_accumulated;
219
220 /**
221 * Frequency of the GT at begin and end of the query.
222 */
223 uint64_t gt_frequency[2];
224
225 /**
226 * Accumulated OA results between begin and end of the query.
227 */
228 struct gen_perf_query_result result;
229 } oa;
230
231 struct {
232 /**
233 * BO containing starting and ending snapshots for the
234 * statistics counters.
235 */
236 void *bo;
237 } pipeline_stats;
238 };
239 };
240
241 struct gen_perf_context {
242 struct gen_perf_config *perf;
243
244 void * ctx; /* driver context (eg, brw_context) */
245 void * bufmgr;
246 const struct gen_device_info *devinfo;
247
248 uint32_t hw_ctx;
249 int drm_fd;
250
251 /* The i915 perf stream we open to setup + enable the OA counters */
252 int oa_stream_fd;
253
254 /* An i915 perf stream fd gives exclusive access to the OA unit that will
255 * report counter snapshots for a specific counter set/profile in a
256 * specific layout/format so we can only start OA queries that are
257 * compatible with the currently open fd...
258 */
259 int current_oa_metrics_set_id;
260 int current_oa_format;
261
262 /* List of buffers containing OA reports */
263 struct exec_list sample_buffers;
264
265 /* Cached list of empty sample buffers */
266 struct exec_list free_sample_buffers;
267
268 int n_active_oa_queries;
269 int n_active_pipeline_stats_queries;
270
271 /* The number of queries depending on running OA counters which
272 * extends beyond brw_end_perf_query() since we need to wait until
273 * the last MI_RPC command has parsed by the GPU.
274 *
275 * Accurate accounting is important here as emitting an
276 * MI_REPORT_PERF_COUNT command while the OA unit is disabled will
277 * effectively hang the gpu.
278 */
279 int n_oa_users;
280
281 /* To help catch an spurious problem with the hardware or perf
282 * forwarding samples, we emit each MI_REPORT_PERF_COUNT command
283 * with a unique ID that we can explicitly check for...
284 */
285 int next_query_start_report_id;
286
287 /**
288 * An array of queries whose results haven't yet been assembled
289 * based on the data in buffer objects.
290 *
291 * These may be active, or have already ended. However, the
292 * results have not been requested.
293 */
294 struct gen_perf_query_object **unaccumulated;
295 int unaccumulated_elements;
296 int unaccumulated_array_size;
297
298 /* The total number of query objects so we can relinquish
299 * our exclusive access to perf if the application deletes
300 * all of its objects. (NB: We only disable perf while
301 * there are no active queries)
302 */
303 int n_query_instances;
304 };
305
306 static bool
307 inc_n_users(struct gen_perf_context *perf_ctx)
308 {
309 if (perf_ctx->n_oa_users == 0 &&
310 gen_ioctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_ENABLE, 0) < 0)
311 {
312 return false;
313 }
314 ++perf_ctx->n_oa_users;
315
316 return true;
317 }
318
319 static void
320 dec_n_users(struct gen_perf_context *perf_ctx)
321 {
322 /* Disabling the i915 perf stream will effectively disable the OA
323 * counters. Note it's important to be sure there are no outstanding
324 * MI_RPC commands at this point since they could stall the CS
325 * indefinitely once OACONTROL is disabled.
326 */
327 --perf_ctx->n_oa_users;
328 if (perf_ctx->n_oa_users == 0 &&
329 gen_ioctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_DISABLE, 0) < 0)
330 {
331 DBG("WARNING: Error disabling gen perf stream: %m\n");
332 }
333 }
334
335 static void
336 gen_perf_close(struct gen_perf_context *perfquery,
337 const struct gen_perf_query_info *query)
338 {
339 if (perfquery->oa_stream_fd != -1) {
340 close(perfquery->oa_stream_fd);
341 perfquery->oa_stream_fd = -1;
342 }
343 if (query->kind == GEN_PERF_QUERY_TYPE_RAW) {
344 struct gen_perf_query_info *raw_query =
345 (struct gen_perf_query_info *) query;
346 raw_query->oa_metrics_set_id = 0;
347 }
348 }
349
350 static bool
351 gen_perf_open(struct gen_perf_context *perf_ctx,
352 int metrics_set_id,
353 int report_format,
354 int period_exponent,
355 int drm_fd,
356 uint32_t ctx_id)
357 {
358 uint64_t properties[] = {
359 /* Single context sampling */
360 DRM_I915_PERF_PROP_CTX_HANDLE, ctx_id,
361
362 /* Include OA reports in samples */
363 DRM_I915_PERF_PROP_SAMPLE_OA, true,
364
365 /* OA unit configuration */
366 DRM_I915_PERF_PROP_OA_METRICS_SET, metrics_set_id,
367 DRM_I915_PERF_PROP_OA_FORMAT, report_format,
368 DRM_I915_PERF_PROP_OA_EXPONENT, period_exponent,
369 };
370 struct drm_i915_perf_open_param param = {
371 .flags = I915_PERF_FLAG_FD_CLOEXEC |
372 I915_PERF_FLAG_FD_NONBLOCK |
373 I915_PERF_FLAG_DISABLED,
374 .num_properties = ARRAY_SIZE(properties) / 2,
375 .properties_ptr = (uintptr_t) properties,
376 };
377 int fd = gen_ioctl(drm_fd, DRM_IOCTL_I915_PERF_OPEN, &param);
378 if (fd == -1) {
379 DBG("Error opening gen perf OA stream: %m\n");
380 return false;
381 }
382
383 perf_ctx->oa_stream_fd = fd;
384
385 perf_ctx->current_oa_metrics_set_id = metrics_set_id;
386 perf_ctx->current_oa_format = report_format;
387
388 return true;
389 }
390
391 static uint64_t
392 get_metric_id(struct gen_perf_config *perf,
393 const struct gen_perf_query_info *query)
394 {
395 /* These queries are know not to ever change, their config ID has been
396 * loaded upon the first query creation. No need to look them up again.
397 */
398 if (query->kind == GEN_PERF_QUERY_TYPE_OA)
399 return query->oa_metrics_set_id;
400
401 assert(query->kind == GEN_PERF_QUERY_TYPE_RAW);
402
403 /* Raw queries can be reprogrammed up by an external application/library.
404 * When a raw query is used for the first time it's id is set to a value !=
405 * 0. When it stops being used the id returns to 0. No need to reload the
406 * ID when it's already loaded.
407 */
408 if (query->oa_metrics_set_id != 0) {
409 DBG("Raw query '%s' guid=%s using cached ID: %"PRIu64"\n",
410 query->name, query->guid, query->oa_metrics_set_id);
411 return query->oa_metrics_set_id;
412 }
413
414 struct gen_perf_query_info *raw_query = (struct gen_perf_query_info *)query;
415 if (!gen_perf_load_metric_id(perf, query->guid,
416 &raw_query->oa_metrics_set_id)) {
417 DBG("Unable to read query guid=%s ID, falling back to test config\n", query->guid);
418 raw_query->oa_metrics_set_id = 1ULL;
419 } else {
420 DBG("Raw query '%s'guid=%s loaded ID: %"PRIu64"\n",
421 query->name, query->guid, query->oa_metrics_set_id);
422 }
423 return query->oa_metrics_set_id;
424 }
425
426 static struct oa_sample_buf *
427 get_free_sample_buf(struct gen_perf_context *perf_ctx)
428 {
429 struct exec_node *node = exec_list_pop_head(&perf_ctx->free_sample_buffers);
430 struct oa_sample_buf *buf;
431
432 if (node)
433 buf = exec_node_data(struct oa_sample_buf, node, link);
434 else {
435 buf = ralloc_size(perf_ctx->perf, sizeof(*buf));
436
437 exec_node_init(&buf->link);
438 buf->refcount = 0;
439 }
440 buf->len = 0;
441
442 return buf;
443 }
444
445 static void
446 reap_old_sample_buffers(struct gen_perf_context *perf_ctx)
447 {
448 struct exec_node *tail_node =
449 exec_list_get_tail(&perf_ctx->sample_buffers);
450 struct oa_sample_buf *tail_buf =
451 exec_node_data(struct oa_sample_buf, tail_node, link);
452
453 /* Remove all old, unreferenced sample buffers walking forward from
454 * the head of the list, except always leave at least one node in
455 * the list so we always have a node to reference when we Begin
456 * a new query.
457 */
458 foreach_list_typed_safe(struct oa_sample_buf, buf, link,
459 &perf_ctx->sample_buffers)
460 {
461 if (buf->refcount == 0 && buf != tail_buf) {
462 exec_node_remove(&buf->link);
463 exec_list_push_head(&perf_ctx->free_sample_buffers, &buf->link);
464 } else
465 return;
466 }
467 }
468
469 static void
470 free_sample_bufs(struct gen_perf_context *perf_ctx)
471 {
472 foreach_list_typed_safe(struct oa_sample_buf, buf, link,
473 &perf_ctx->free_sample_buffers)
474 ralloc_free(buf);
475
476 exec_list_make_empty(&perf_ctx->free_sample_buffers);
477 }
478
479
480 struct gen_perf_query_object *
481 gen_perf_new_query(struct gen_perf_context *perf_ctx, unsigned query_index)
482 {
483 const struct gen_perf_query_info *query =
484 &perf_ctx->perf->queries[query_index];
485 struct gen_perf_query_object *obj =
486 calloc(1, sizeof(struct gen_perf_query_object));
487
488 if (!obj)
489 return NULL;
490
491 obj->queryinfo = query;
492
493 perf_ctx->n_query_instances++;
494 return obj;
495 }
496
497 int
498 gen_perf_active_queries(struct gen_perf_context *perf_ctx,
499 const struct gen_perf_query_info *query)
500 {
501 assert(perf_ctx->n_active_oa_queries == 0 || perf_ctx->n_active_pipeline_stats_queries == 0);
502
503 switch (query->kind) {
504 case GEN_PERF_QUERY_TYPE_OA:
505 case GEN_PERF_QUERY_TYPE_RAW:
506 return perf_ctx->n_active_oa_queries;
507 break;
508
509 case GEN_PERF_QUERY_TYPE_PIPELINE:
510 return perf_ctx->n_active_pipeline_stats_queries;
511 break;
512
513 default:
514 unreachable("Unknown query type");
515 break;
516 }
517 }
518
519 const struct gen_perf_query_info*
520 gen_perf_query_info(const struct gen_perf_query_object *query)
521 {
522 return query->queryinfo;
523 }
524
525 struct gen_perf_context *
526 gen_perf_new_context(void *parent)
527 {
528 struct gen_perf_context *ctx = rzalloc(parent, struct gen_perf_context);
529 if (! ctx)
530 fprintf(stderr, "%s: failed to alloc context\n", __func__);
531 return ctx;
532 }
533
534 struct gen_perf_config *
535 gen_perf_config(struct gen_perf_context *ctx)
536 {
537 return ctx->perf;
538 }
539
540 void
541 gen_perf_init_context(struct gen_perf_context *perf_ctx,
542 struct gen_perf_config *perf_cfg,
543 void * ctx, /* driver context (eg, brw_context) */
544 void * bufmgr, /* eg brw_bufmgr */
545 const struct gen_device_info *devinfo,
546 uint32_t hw_ctx,
547 int drm_fd)
548 {
549 perf_ctx->perf = perf_cfg;
550 perf_ctx->ctx = ctx;
551 perf_ctx->bufmgr = bufmgr;
552 perf_ctx->drm_fd = drm_fd;
553 perf_ctx->hw_ctx = hw_ctx;
554 perf_ctx->devinfo = devinfo;
555
556 perf_ctx->unaccumulated =
557 ralloc_array(ctx, struct gen_perf_query_object *, 2);
558 perf_ctx->unaccumulated_elements = 0;
559 perf_ctx->unaccumulated_array_size = 2;
560
561 exec_list_make_empty(&perf_ctx->sample_buffers);
562 exec_list_make_empty(&perf_ctx->free_sample_buffers);
563
564 /* It's convenient to guarantee that this linked list of sample
565 * buffers is never empty so we add an empty head so when we
566 * Begin an OA query we can always take a reference on a buffer
567 * in this list.
568 */
569 struct oa_sample_buf *buf = get_free_sample_buf(perf_ctx);
570 exec_list_push_head(&perf_ctx->sample_buffers, &buf->link);
571
572 perf_ctx->oa_stream_fd = -1;
573 perf_ctx->next_query_start_report_id = 1000;
574 }
575
576 /**
577 * Add a query to the global list of "unaccumulated queries."
578 *
579 * Queries are tracked here until all the associated OA reports have
580 * been accumulated via accumulate_oa_reports() after the end
581 * MI_REPORT_PERF_COUNT has landed in query->oa.bo.
582 */
583 static void
584 add_to_unaccumulated_query_list(struct gen_perf_context *perf_ctx,
585 struct gen_perf_query_object *obj)
586 {
587 if (perf_ctx->unaccumulated_elements >=
588 perf_ctx->unaccumulated_array_size)
589 {
590 perf_ctx->unaccumulated_array_size *= 1.5;
591 perf_ctx->unaccumulated =
592 reralloc(perf_ctx->ctx, perf_ctx->unaccumulated,
593 struct gen_perf_query_object *,
594 perf_ctx->unaccumulated_array_size);
595 }
596
597 perf_ctx->unaccumulated[perf_ctx->unaccumulated_elements++] = obj;
598 }
599
600 /**
601 * Emit MI_STORE_REGISTER_MEM commands to capture all of the
602 * pipeline statistics for the performance query object.
603 */
604 static void
605 snapshot_statistics_registers(struct gen_perf_context *ctx,
606 struct gen_perf_query_object *obj,
607 uint32_t offset_in_bytes)
608 {
609 struct gen_perf_config *perf = ctx->perf;
610 const struct gen_perf_query_info *query = obj->queryinfo;
611 const int n_counters = query->n_counters;
612
613 for (int i = 0; i < n_counters; i++) {
614 const struct gen_perf_query_counter *counter = &query->counters[i];
615
616 assert(counter->data_type == GEN_PERF_COUNTER_DATA_TYPE_UINT64);
617
618 perf->vtbl.store_register_mem(ctx->ctx, obj->pipeline_stats.bo,
619 counter->pipeline_stat.reg, 8,
620 offset_in_bytes + i * sizeof(uint64_t));
621 }
622 }
623
624 static void
625 snapshot_freq_register(struct gen_perf_context *ctx,
626 struct gen_perf_query_object *query,
627 uint32_t bo_offset)
628 {
629 struct gen_perf_config *perf = ctx->perf;
630 const struct gen_device_info *devinfo = ctx->devinfo;
631
632 if (devinfo->gen == 8 && !devinfo->is_cherryview)
633 perf->vtbl.store_register_mem(ctx->ctx, query->oa.bo, GEN7_RPSTAT1, 4, bo_offset);
634 else if (devinfo->gen >= 9)
635 perf->vtbl.store_register_mem(ctx->ctx, query->oa.bo, GEN9_RPSTAT0, 4, bo_offset);
636 }
637
638 bool
639 gen_perf_begin_query(struct gen_perf_context *perf_ctx,
640 struct gen_perf_query_object *query)
641 {
642 struct gen_perf_config *perf_cfg = perf_ctx->perf;
643 const struct gen_perf_query_info *queryinfo = query->queryinfo;
644
645 /* XXX: We have to consider that the command parser unit that parses batch
646 * buffer commands and is used to capture begin/end counter snapshots isn't
647 * implicitly synchronized with what's currently running across other GPU
648 * units (such as the EUs running shaders) that the performance counters are
649 * associated with.
650 *
651 * The intention of performance queries is to measure the work associated
652 * with commands between the begin/end delimiters and so for that to be the
653 * case we need to explicitly synchronize the parsing of commands to capture
654 * Begin/End counter snapshots with what's running across other parts of the
655 * GPU.
656 *
657 * When the command parser reaches a Begin marker it effectively needs to
658 * drain everything currently running on the GPU until the hardware is idle
659 * before capturing the first snapshot of counters - otherwise the results
660 * would also be measuring the effects of earlier commands.
661 *
662 * When the command parser reaches an End marker it needs to stall until
663 * everything currently running on the GPU has finished before capturing the
664 * end snapshot - otherwise the results won't be a complete representation
665 * of the work.
666 *
667 * To achieve this, we stall the pipeline at pixel scoreboard (prevent any
668 * additional work to be processed by the pipeline until all pixels of the
669 * previous draw has be completed).
670 *
671 * N.B. The final results are based on deltas of counters between (inside)
672 * Begin/End markers so even though the total wall clock time of the
673 * workload is stretched by larger pipeline bubbles the bubbles themselves
674 * are generally invisible to the query results. Whether that's a good or a
675 * bad thing depends on the use case. For a lower real-time impact while
676 * capturing metrics then periodic sampling may be a better choice than
677 * INTEL_performance_query.
678 *
679 *
680 * This is our Begin synchronization point to drain current work on the
681 * GPU before we capture our first counter snapshot...
682 */
683 perf_cfg->vtbl.emit_stall_at_pixel_scoreboard(perf_ctx->ctx);
684
685 switch (queryinfo->kind) {
686 case GEN_PERF_QUERY_TYPE_OA:
687 case GEN_PERF_QUERY_TYPE_RAW: {
688
689 /* Opening an i915 perf stream implies exclusive access to the OA unit
690 * which will generate counter reports for a specific counter set with a
691 * specific layout/format so we can't begin any OA based queries that
692 * require a different counter set or format unless we get an opportunity
693 * to close the stream and open a new one...
694 */
695 uint64_t metric_id = get_metric_id(perf_ctx->perf, queryinfo);
696
697 if (perf_ctx->oa_stream_fd != -1 &&
698 perf_ctx->current_oa_metrics_set_id != metric_id) {
699
700 if (perf_ctx->n_oa_users != 0) {
701 DBG("WARNING: Begin failed already using perf config=%i/%"PRIu64"\n",
702 perf_ctx->current_oa_metrics_set_id, metric_id);
703 return false;
704 } else
705 gen_perf_close(perf_ctx, queryinfo);
706 }
707
708 /* If the OA counters aren't already on, enable them. */
709 if (perf_ctx->oa_stream_fd == -1) {
710 const struct gen_device_info *devinfo = perf_ctx->devinfo;
711
712 /* The period_exponent gives a sampling period as follows:
713 * sample_period = timestamp_period * 2^(period_exponent + 1)
714 *
715 * The timestamps increments every 80ns (HSW), ~52ns (GEN9LP) or
716 * ~83ns (GEN8/9).
717 *
718 * The counter overflow period is derived from the EuActive counter
719 * which reads a counter that increments by the number of clock
720 * cycles multiplied by the number of EUs. It can be calculated as:
721 *
722 * 2^(number of bits in A counter) / (n_eus * max_gen_freq * 2)
723 *
724 * (E.g. 40 EUs @ 1GHz = ~53ms)
725 *
726 * We select a sampling period inferior to that overflow period to
727 * ensure we cannot see more than 1 counter overflow, otherwise we
728 * could loose information.
729 */
730
731 int a_counter_in_bits = 32;
732 if (devinfo->gen >= 8)
733 a_counter_in_bits = 40;
734
735 uint64_t overflow_period = pow(2, a_counter_in_bits) / (perf_cfg->sys_vars.n_eus *
736 /* drop 1GHz freq to have units in nanoseconds */
737 2);
738
739 DBG("A counter overflow period: %"PRIu64"ns, %"PRIu64"ms (n_eus=%"PRIu64")\n",
740 overflow_period, overflow_period / 1000000ul, perf_cfg->sys_vars.n_eus);
741
742 int period_exponent = 0;
743 uint64_t prev_sample_period, next_sample_period;
744 for (int e = 0; e < 30; e++) {
745 prev_sample_period = 1000000000ull * pow(2, e + 1) / devinfo->timestamp_frequency;
746 next_sample_period = 1000000000ull * pow(2, e + 2) / devinfo->timestamp_frequency;
747
748 /* Take the previous sampling period, lower than the overflow
749 * period.
750 */
751 if (prev_sample_period < overflow_period &&
752 next_sample_period > overflow_period)
753 period_exponent = e + 1;
754 }
755
756 if (period_exponent == 0) {
757 DBG("WARNING: enable to find a sampling exponent\n");
758 return false;
759 }
760
761 DBG("OA sampling exponent: %i ~= %"PRIu64"ms\n", period_exponent,
762 prev_sample_period / 1000000ul);
763
764 if (!gen_perf_open(perf_ctx, metric_id, queryinfo->oa_format,
765 period_exponent, perf_ctx->drm_fd,
766 perf_ctx->hw_ctx))
767 return false;
768 } else {
769 assert(perf_ctx->current_oa_metrics_set_id == metric_id &&
770 perf_ctx->current_oa_format == queryinfo->oa_format);
771 }
772
773 if (!inc_n_users(perf_ctx)) {
774 DBG("WARNING: Error enabling i915 perf stream: %m\n");
775 return false;
776 }
777
778 if (query->oa.bo) {
779 perf_cfg->vtbl.bo_unreference(query->oa.bo);
780 query->oa.bo = NULL;
781 }
782
783 query->oa.bo = perf_cfg->vtbl.bo_alloc(perf_ctx->bufmgr,
784 "perf. query OA MI_RPC bo",
785 MI_RPC_BO_SIZE);
786 #ifdef DEBUG
787 /* Pre-filling the BO helps debug whether writes landed. */
788 void *map = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->oa.bo, MAP_WRITE);
789 memset(map, 0x80, MI_RPC_BO_SIZE);
790 perf_cfg->vtbl.bo_unmap(query->oa.bo);
791 #endif
792
793 query->oa.begin_report_id = perf_ctx->next_query_start_report_id;
794 perf_ctx->next_query_start_report_id += 2;
795
796 /* Take a starting OA counter snapshot. */
797 perf_cfg->vtbl.emit_mi_report_perf_count(perf_ctx->ctx, query->oa.bo, 0,
798 query->oa.begin_report_id);
799 snapshot_freq_register(perf_ctx, query, MI_FREQ_START_OFFSET_BYTES);
800
801 ++perf_ctx->n_active_oa_queries;
802
803 /* No already-buffered samples can possibly be associated with this query
804 * so create a marker within the list of sample buffers enabling us to
805 * easily ignore earlier samples when processing this query after
806 * completion.
807 */
808 assert(!exec_list_is_empty(&perf_ctx->sample_buffers));
809 query->oa.samples_head = exec_list_get_tail(&perf_ctx->sample_buffers);
810
811 struct oa_sample_buf *buf =
812 exec_node_data(struct oa_sample_buf, query->oa.samples_head, link);
813
814 /* This reference will ensure that future/following sample
815 * buffers (that may relate to this query) can't be freed until
816 * this drops to zero.
817 */
818 buf->refcount++;
819
820 gen_perf_query_result_clear(&query->oa.result);
821 query->oa.results_accumulated = false;
822
823 add_to_unaccumulated_query_list(perf_ctx, query);
824 break;
825 }
826
827 case GEN_PERF_QUERY_TYPE_PIPELINE:
828 if (query->pipeline_stats.bo) {
829 perf_cfg->vtbl.bo_unreference(query->pipeline_stats.bo);
830 query->pipeline_stats.bo = NULL;
831 }
832
833 query->pipeline_stats.bo =
834 perf_cfg->vtbl.bo_alloc(perf_ctx->bufmgr,
835 "perf. query pipeline stats bo",
836 STATS_BO_SIZE);
837
838 /* Take starting snapshots. */
839 snapshot_statistics_registers(perf_ctx, query, 0);
840
841 ++perf_ctx->n_active_pipeline_stats_queries;
842 break;
843
844 default:
845 unreachable("Unknown query type");
846 break;
847 }
848
849 return true;
850 }
851
852 void
853 gen_perf_end_query(struct gen_perf_context *perf_ctx,
854 struct gen_perf_query_object *query)
855 {
856 struct gen_perf_config *perf_cfg = perf_ctx->perf;
857
858 /* Ensure that the work associated with the queried commands will have
859 * finished before taking our query end counter readings.
860 *
861 * For more details see comment in brw_begin_perf_query for
862 * corresponding flush.
863 */
864 perf_cfg->vtbl.emit_stall_at_pixel_scoreboard(perf_ctx->ctx);
865
866 switch (query->queryinfo->kind) {
867 case GEN_PERF_QUERY_TYPE_OA:
868 case GEN_PERF_QUERY_TYPE_RAW:
869
870 /* NB: It's possible that the query will have already been marked
871 * as 'accumulated' if an error was seen while reading samples
872 * from perf. In this case we mustn't try and emit a closing
873 * MI_RPC command in case the OA unit has already been disabled
874 */
875 if (!query->oa.results_accumulated) {
876 /* Take an ending OA counter snapshot. */
877 snapshot_freq_register(perf_ctx, query, MI_FREQ_END_OFFSET_BYTES);
878 perf_cfg->vtbl.emit_mi_report_perf_count(perf_ctx->ctx, query->oa.bo,
879 MI_RPC_BO_END_OFFSET_BYTES,
880 query->oa.begin_report_id + 1);
881 }
882
883 --perf_ctx->n_active_oa_queries;
884
885 /* NB: even though the query has now ended, it can't be accumulated
886 * until the end MI_REPORT_PERF_COUNT snapshot has been written
887 * to query->oa.bo
888 */
889 break;
890
891 case GEN_PERF_QUERY_TYPE_PIPELINE:
892 snapshot_statistics_registers(perf_ctx, query,
893 STATS_BO_END_OFFSET_BYTES);
894 --perf_ctx->n_active_pipeline_stats_queries;
895 break;
896
897 default:
898 unreachable("Unknown query type");
899 break;
900 }
901 }
902
903 enum OaReadStatus {
904 OA_READ_STATUS_ERROR,
905 OA_READ_STATUS_UNFINISHED,
906 OA_READ_STATUS_FINISHED,
907 };
908
909 static enum OaReadStatus
910 read_oa_samples_until(struct gen_perf_context *perf_ctx,
911 uint32_t start_timestamp,
912 uint32_t end_timestamp)
913 {
914 struct exec_node *tail_node =
915 exec_list_get_tail(&perf_ctx->sample_buffers);
916 struct oa_sample_buf *tail_buf =
917 exec_node_data(struct oa_sample_buf, tail_node, link);
918 uint32_t last_timestamp =
919 tail_buf->len == 0 ? start_timestamp : tail_buf->last_timestamp;
920
921 while (1) {
922 struct oa_sample_buf *buf = get_free_sample_buf(perf_ctx);
923 uint32_t offset;
924 int len;
925
926 while ((len = read(perf_ctx->oa_stream_fd, buf->buf,
927 sizeof(buf->buf))) < 0 && errno == EINTR)
928 ;
929
930 if (len <= 0) {
931 exec_list_push_tail(&perf_ctx->free_sample_buffers, &buf->link);
932
933 if (len < 0) {
934 if (errno == EAGAIN) {
935 return ((last_timestamp - start_timestamp) < INT32_MAX &&
936 (last_timestamp - start_timestamp) >=
937 (end_timestamp - start_timestamp)) ?
938 OA_READ_STATUS_FINISHED :
939 OA_READ_STATUS_UNFINISHED;
940 } else {
941 DBG("Error reading i915 perf samples: %m\n");
942 }
943 } else
944 DBG("Spurious EOF reading i915 perf samples\n");
945
946 return OA_READ_STATUS_ERROR;
947 }
948
949 buf->len = len;
950 exec_list_push_tail(&perf_ctx->sample_buffers, &buf->link);
951
952 /* Go through the reports and update the last timestamp. */
953 offset = 0;
954 while (offset < buf->len) {
955 const struct drm_i915_perf_record_header *header =
956 (const struct drm_i915_perf_record_header *) &buf->buf[offset];
957 uint32_t *report = (uint32_t *) (header + 1);
958
959 if (header->type == DRM_I915_PERF_RECORD_SAMPLE)
960 last_timestamp = report[1];
961
962 offset += header->size;
963 }
964
965 buf->last_timestamp = last_timestamp;
966 }
967
968 unreachable("not reached");
969 return OA_READ_STATUS_ERROR;
970 }
971
972 /**
973 * Try to read all the reports until either the delimiting timestamp
974 * or an error arises.
975 */
976 static bool
977 read_oa_samples_for_query(struct gen_perf_context *perf_ctx,
978 struct gen_perf_query_object *query,
979 void *current_batch)
980 {
981 uint32_t *start;
982 uint32_t *last;
983 uint32_t *end;
984 struct gen_perf_config *perf_cfg = perf_ctx->perf;
985
986 /* We need the MI_REPORT_PERF_COUNT to land before we can start
987 * accumulate. */
988 assert(!perf_cfg->vtbl.batch_references(current_batch, query->oa.bo) &&
989 !perf_cfg->vtbl.bo_busy(query->oa.bo));
990
991 /* Map the BO once here and let accumulate_oa_reports() unmap
992 * it. */
993 if (query->oa.map == NULL)
994 query->oa.map = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->oa.bo, MAP_READ);
995
996 start = last = query->oa.map;
997 end = query->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
998
999 if (start[0] != query->oa.begin_report_id) {
1000 DBG("Spurious start report id=%"PRIu32"\n", start[0]);
1001 return true;
1002 }
1003 if (end[0] != (query->oa.begin_report_id + 1)) {
1004 DBG("Spurious end report id=%"PRIu32"\n", end[0]);
1005 return true;
1006 }
1007
1008 /* Read the reports until the end timestamp. */
1009 switch (read_oa_samples_until(perf_ctx, start[1], end[1])) {
1010 case OA_READ_STATUS_ERROR:
1011 /* Fallthrough and let accumulate_oa_reports() deal with the
1012 * error. */
1013 case OA_READ_STATUS_FINISHED:
1014 return true;
1015 case OA_READ_STATUS_UNFINISHED:
1016 return false;
1017 }
1018
1019 unreachable("invalid read status");
1020 return false;
1021 }
1022
1023 void
1024 gen_perf_wait_query(struct gen_perf_context *perf_ctx,
1025 struct gen_perf_query_object *query,
1026 void *current_batch)
1027 {
1028 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1029 struct brw_bo *bo = NULL;
1030
1031 switch (query->queryinfo->kind) {
1032 case GEN_PERF_QUERY_TYPE_OA:
1033 case GEN_PERF_QUERY_TYPE_RAW:
1034 bo = query->oa.bo;
1035 break;
1036
1037 case GEN_PERF_QUERY_TYPE_PIPELINE:
1038 bo = query->pipeline_stats.bo;
1039 break;
1040
1041 default:
1042 unreachable("Unknown query type");
1043 break;
1044 }
1045
1046 if (bo == NULL)
1047 return;
1048
1049 /* If the current batch references our results bo then we need to
1050 * flush first...
1051 */
1052 if (perf_cfg->vtbl.batch_references(current_batch, bo))
1053 perf_cfg->vtbl.batchbuffer_flush(perf_ctx->ctx, __FILE__, __LINE__);
1054
1055 perf_cfg->vtbl.bo_wait_rendering(bo);
1056
1057 /* Due to a race condition between the OA unit signaling report
1058 * availability and the report actually being written into memory,
1059 * we need to wait for all the reports to come in before we can
1060 * read them.
1061 */
1062 if (query->queryinfo->kind == GEN_PERF_QUERY_TYPE_OA ||
1063 query->queryinfo->kind == GEN_PERF_QUERY_TYPE_RAW) {
1064 while (!read_oa_samples_for_query(perf_ctx, query, current_batch))
1065 ;
1066 }
1067 }
1068
1069 bool
1070 gen_perf_is_query_ready(struct gen_perf_context *perf_ctx,
1071 struct gen_perf_query_object *query,
1072 void *current_batch)
1073 {
1074 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1075
1076 switch (query->queryinfo->kind) {
1077 case GEN_PERF_QUERY_TYPE_OA:
1078 case GEN_PERF_QUERY_TYPE_RAW:
1079 return (query->oa.results_accumulated ||
1080 (query->oa.bo &&
1081 !perf_cfg->vtbl.batch_references(current_batch, query->oa.bo) &&
1082 !perf_cfg->vtbl.bo_busy(query->oa.bo) &&
1083 read_oa_samples_for_query(perf_ctx, query, current_batch)));
1084 case GEN_PERF_QUERY_TYPE_PIPELINE:
1085 return (query->pipeline_stats.bo &&
1086 !perf_cfg->vtbl.batch_references(current_batch, query->pipeline_stats.bo) &&
1087 !perf_cfg->vtbl.bo_busy(query->pipeline_stats.bo));
1088
1089 default:
1090 unreachable("Unknown query type");
1091 break;
1092 }
1093
1094 return false;
1095 }
1096
1097 /**
1098 * Remove a query from the global list of unaccumulated queries once
1099 * after successfully accumulating the OA reports associated with the
1100 * query in accumulate_oa_reports() or when discarding unwanted query
1101 * results.
1102 */
1103 static void
1104 drop_from_unaccumulated_query_list(struct gen_perf_context *perf_ctx,
1105 struct gen_perf_query_object *query)
1106 {
1107 for (int i = 0; i < perf_ctx->unaccumulated_elements; i++) {
1108 if (perf_ctx->unaccumulated[i] == query) {
1109 int last_elt = --perf_ctx->unaccumulated_elements;
1110
1111 if (i == last_elt)
1112 perf_ctx->unaccumulated[i] = NULL;
1113 else {
1114 perf_ctx->unaccumulated[i] =
1115 perf_ctx->unaccumulated[last_elt];
1116 }
1117
1118 break;
1119 }
1120 }
1121
1122 /* Drop our samples_head reference so that associated periodic
1123 * sample data buffers can potentially be reaped if they aren't
1124 * referenced by any other queries...
1125 */
1126
1127 struct oa_sample_buf *buf =
1128 exec_node_data(struct oa_sample_buf, query->oa.samples_head, link);
1129
1130 assert(buf->refcount > 0);
1131 buf->refcount--;
1132
1133 query->oa.samples_head = NULL;
1134
1135 reap_old_sample_buffers(perf_ctx);
1136 }
1137
1138 /* In general if we see anything spurious while accumulating results,
1139 * we don't try and continue accumulating the current query, hoping
1140 * for the best, we scrap anything outstanding, and then hope for the
1141 * best with new queries.
1142 */
1143 static void
1144 discard_all_queries(struct gen_perf_context *perf_ctx)
1145 {
1146 while (perf_ctx->unaccumulated_elements) {
1147 struct gen_perf_query_object *query = perf_ctx->unaccumulated[0];
1148
1149 query->oa.results_accumulated = true;
1150 drop_from_unaccumulated_query_list(perf_ctx, query);
1151
1152 dec_n_users(perf_ctx);
1153 }
1154 }
1155
1156 /* Looks for the validity bit of context ID (dword 2) of an OA report. */
1157 static bool
1158 oa_report_ctx_id_valid(const struct gen_device_info *devinfo,
1159 const uint32_t *report)
1160 {
1161 assert(devinfo->gen >= 8);
1162 if (devinfo->gen == 8)
1163 return (report[0] & (1 << 25)) != 0;
1164 return (report[0] & (1 << 16)) != 0;
1165 }
1166
1167 /**
1168 * Accumulate raw OA counter values based on deltas between pairs of
1169 * OA reports.
1170 *
1171 * Accumulation starts from the first report captured via
1172 * MI_REPORT_PERF_COUNT (MI_RPC) by brw_begin_perf_query() until the
1173 * last MI_RPC report requested by brw_end_perf_query(). Between these
1174 * two reports there may also some number of periodically sampled OA
1175 * reports collected via the i915 perf interface - depending on the
1176 * duration of the query.
1177 *
1178 * These periodic snapshots help to ensure we handle counter overflow
1179 * correctly by being frequent enough to ensure we don't miss multiple
1180 * overflows of a counter between snapshots. For Gen8+ the i915 perf
1181 * snapshots provide the extra context-switch reports that let us
1182 * subtract out the progress of counters associated with other
1183 * contexts running on the system.
1184 */
1185 static void
1186 accumulate_oa_reports(struct gen_perf_context *perf_ctx,
1187 struct gen_perf_query_object *query)
1188 {
1189 const struct gen_device_info *devinfo = perf_ctx->devinfo;
1190 uint32_t *start;
1191 uint32_t *last;
1192 uint32_t *end;
1193 struct exec_node *first_samples_node;
1194 bool last_report_ctx_match = true;
1195 int out_duration = 0;
1196
1197 assert(query->oa.map != NULL);
1198
1199 start = last = query->oa.map;
1200 end = query->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
1201
1202 if (start[0] != query->oa.begin_report_id) {
1203 DBG("Spurious start report id=%"PRIu32"\n", start[0]);
1204 goto error;
1205 }
1206 if (end[0] != (query->oa.begin_report_id + 1)) {
1207 DBG("Spurious end report id=%"PRIu32"\n", end[0]);
1208 goto error;
1209 }
1210
1211 /* On Gen12+ OA reports are sourced from per context counters, so we don't
1212 * ever have to look at the global OA buffer. Yey \o/
1213 */
1214 if (perf_ctx->devinfo->gen >= 12) {
1215 last = start;
1216 goto end;
1217 }
1218
1219 /* See if we have any periodic reports to accumulate too... */
1220
1221 /* N.B. The oa.samples_head was set when the query began and
1222 * pointed to the tail of the perf_ctx->sample_buffers list at
1223 * the time the query started. Since the buffer existed before the
1224 * first MI_REPORT_PERF_COUNT command was emitted we therefore know
1225 * that no data in this particular node's buffer can possibly be
1226 * associated with the query - so skip ahead one...
1227 */
1228 first_samples_node = query->oa.samples_head->next;
1229
1230 foreach_list_typed_from(struct oa_sample_buf, buf, link,
1231 &perf_ctx->sample_buffers,
1232 first_samples_node)
1233 {
1234 int offset = 0;
1235
1236 while (offset < buf->len) {
1237 const struct drm_i915_perf_record_header *header =
1238 (const struct drm_i915_perf_record_header *)(buf->buf + offset);
1239
1240 assert(header->size != 0);
1241 assert(header->size <= buf->len);
1242
1243 offset += header->size;
1244
1245 switch (header->type) {
1246 case DRM_I915_PERF_RECORD_SAMPLE: {
1247 uint32_t *report = (uint32_t *)(header + 1);
1248 bool report_ctx_match = true;
1249 bool add = true;
1250
1251 /* Ignore reports that come before the start marker.
1252 * (Note: takes care to allow overflow of 32bit timestamps)
1253 */
1254 if (gen_device_info_timebase_scale(devinfo,
1255 report[1] - start[1]) > 5000000000) {
1256 continue;
1257 }
1258
1259 /* Ignore reports that come after the end marker.
1260 * (Note: takes care to allow overflow of 32bit timestamps)
1261 */
1262 if (gen_device_info_timebase_scale(devinfo,
1263 report[1] - end[1]) <= 5000000000) {
1264 goto end;
1265 }
1266
1267 /* For Gen8+ since the counters continue while other
1268 * contexts are running we need to discount any unrelated
1269 * deltas. The hardware automatically generates a report
1270 * on context switch which gives us a new reference point
1271 * to continuing adding deltas from.
1272 *
1273 * For Haswell we can rely on the HW to stop the progress
1274 * of OA counters while any other context is acctive.
1275 */
1276 if (devinfo->gen >= 8) {
1277 /* Consider that the current report matches our context only if
1278 * the report says the report ID is valid.
1279 */
1280 report_ctx_match = oa_report_ctx_id_valid(devinfo, report) &&
1281 report[2] == start[2];
1282 if (report_ctx_match)
1283 out_duration = 0;
1284 else
1285 out_duration++;
1286
1287 /* Only add the delta between <last, report> if the last report
1288 * was clearly identified as our context, or if we have at most
1289 * 1 report without a matching ID.
1290 *
1291 * The OA unit will sometimes label reports with an invalid
1292 * context ID when i915 rewrites the execlist submit register
1293 * with the same context as the one currently running. This
1294 * happens when i915 wants to notify the HW of ringbuffer tail
1295 * register update. We have to consider this report as part of
1296 * our context as the 3d pipeline behind the OACS unit is still
1297 * processing the operations started at the previous execlist
1298 * submission.
1299 */
1300 add = last_report_ctx_match && out_duration < 2;
1301 }
1302
1303 if (add) {
1304 gen_perf_query_result_accumulate(&query->oa.result,
1305 query->queryinfo,
1306 last, report);
1307 } else {
1308 /* We're not adding the delta because we've identified it's not
1309 * for the context we filter for. We can consider that the
1310 * query was split.
1311 */
1312 query->oa.result.query_disjoint = true;
1313 }
1314
1315 last = report;
1316 last_report_ctx_match = report_ctx_match;
1317
1318 break;
1319 }
1320
1321 case DRM_I915_PERF_RECORD_OA_BUFFER_LOST:
1322 DBG("i915 perf: OA error: all reports lost\n");
1323 goto error;
1324 case DRM_I915_PERF_RECORD_OA_REPORT_LOST:
1325 DBG("i915 perf: OA report lost\n");
1326 break;
1327 }
1328 }
1329 }
1330
1331 end:
1332
1333 gen_perf_query_result_accumulate(&query->oa.result, query->queryinfo,
1334 last, end);
1335
1336 query->oa.results_accumulated = true;
1337 drop_from_unaccumulated_query_list(perf_ctx, query);
1338 dec_n_users(perf_ctx);
1339
1340 return;
1341
1342 error:
1343
1344 discard_all_queries(perf_ctx);
1345 }
1346
1347 void
1348 gen_perf_delete_query(struct gen_perf_context *perf_ctx,
1349 struct gen_perf_query_object *query)
1350 {
1351 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1352
1353 /* We can assume that the frontend waits for a query to complete
1354 * before ever calling into here, so we don't have to worry about
1355 * deleting an in-flight query object.
1356 */
1357 switch (query->queryinfo->kind) {
1358 case GEN_PERF_QUERY_TYPE_OA:
1359 case GEN_PERF_QUERY_TYPE_RAW:
1360 if (query->oa.bo) {
1361 if (!query->oa.results_accumulated) {
1362 drop_from_unaccumulated_query_list(perf_ctx, query);
1363 dec_n_users(perf_ctx);
1364 }
1365
1366 perf_cfg->vtbl.bo_unreference(query->oa.bo);
1367 query->oa.bo = NULL;
1368 }
1369
1370 query->oa.results_accumulated = false;
1371 break;
1372
1373 case GEN_PERF_QUERY_TYPE_PIPELINE:
1374 if (query->pipeline_stats.bo) {
1375 perf_cfg->vtbl.bo_unreference(query->pipeline_stats.bo);
1376 query->pipeline_stats.bo = NULL;
1377 }
1378 break;
1379
1380 default:
1381 unreachable("Unknown query type");
1382 break;
1383 }
1384
1385 /* As an indication that the INTEL_performance_query extension is no
1386 * longer in use, it's a good time to free our cache of sample
1387 * buffers and close any current i915-perf stream.
1388 */
1389 if (--perf_ctx->n_query_instances == 0) {
1390 free_sample_bufs(perf_ctx);
1391 gen_perf_close(perf_ctx, query->queryinfo);
1392 }
1393
1394 free(query);
1395 }
1396
1397 #define GET_FIELD(word, field) (((word) & field ## _MASK) >> field ## _SHIFT)
1398
1399 static void
1400 read_gt_frequency(struct gen_perf_context *perf_ctx,
1401 struct gen_perf_query_object *obj)
1402 {
1403 const struct gen_device_info *devinfo = perf_ctx->devinfo;
1404 uint32_t start = *((uint32_t *)(obj->oa.map + MI_FREQ_START_OFFSET_BYTES)),
1405 end = *((uint32_t *)(obj->oa.map + MI_FREQ_END_OFFSET_BYTES));
1406
1407 switch (devinfo->gen) {
1408 case 7:
1409 case 8:
1410 obj->oa.gt_frequency[0] = GET_FIELD(start, GEN7_RPSTAT1_CURR_GT_FREQ) * 50ULL;
1411 obj->oa.gt_frequency[1] = GET_FIELD(end, GEN7_RPSTAT1_CURR_GT_FREQ) * 50ULL;
1412 break;
1413 case 9:
1414 case 10:
1415 case 11:
1416 case 12:
1417 obj->oa.gt_frequency[0] = GET_FIELD(start, GEN9_RPSTAT0_CURR_GT_FREQ) * 50ULL / 3ULL;
1418 obj->oa.gt_frequency[1] = GET_FIELD(end, GEN9_RPSTAT0_CURR_GT_FREQ) * 50ULL / 3ULL;
1419 break;
1420 default:
1421 unreachable("unexpected gen");
1422 }
1423
1424 /* Put the numbers into Hz. */
1425 obj->oa.gt_frequency[0] *= 1000000ULL;
1426 obj->oa.gt_frequency[1] *= 1000000ULL;
1427 }
1428
1429 static int
1430 get_oa_counter_data(struct gen_perf_context *perf_ctx,
1431 struct gen_perf_query_object *query,
1432 size_t data_size,
1433 uint8_t *data)
1434 {
1435 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1436 const struct gen_perf_query_info *queryinfo = query->queryinfo;
1437 int n_counters = queryinfo->n_counters;
1438 int written = 0;
1439
1440 for (int i = 0; i < n_counters; i++) {
1441 const struct gen_perf_query_counter *counter = &queryinfo->counters[i];
1442 uint64_t *out_uint64;
1443 float *out_float;
1444 size_t counter_size = gen_perf_query_counter_get_size(counter);
1445
1446 if (counter_size) {
1447 switch (counter->data_type) {
1448 case GEN_PERF_COUNTER_DATA_TYPE_UINT64:
1449 out_uint64 = (uint64_t *)(data + counter->offset);
1450 *out_uint64 =
1451 counter->oa_counter_read_uint64(perf_cfg, queryinfo,
1452 query->oa.result.accumulator);
1453 break;
1454 case GEN_PERF_COUNTER_DATA_TYPE_FLOAT:
1455 out_float = (float *)(data + counter->offset);
1456 *out_float =
1457 counter->oa_counter_read_float(perf_cfg, queryinfo,
1458 query->oa.result.accumulator);
1459 break;
1460 default:
1461 /* So far we aren't using uint32, double or bool32... */
1462 unreachable("unexpected counter data type");
1463 }
1464 written = counter->offset + counter_size;
1465 }
1466 }
1467
1468 return written;
1469 }
1470
1471 static int
1472 get_pipeline_stats_data(struct gen_perf_context *perf_ctx,
1473 struct gen_perf_query_object *query,
1474 size_t data_size,
1475 uint8_t *data)
1476
1477 {
1478 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1479 const struct gen_perf_query_info *queryinfo = query->queryinfo;
1480 int n_counters = queryinfo->n_counters;
1481 uint8_t *p = data;
1482
1483 uint64_t *start = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->pipeline_stats.bo, MAP_READ);
1484 uint64_t *end = start + (STATS_BO_END_OFFSET_BYTES / sizeof(uint64_t));
1485
1486 for (int i = 0; i < n_counters; i++) {
1487 const struct gen_perf_query_counter *counter = &queryinfo->counters[i];
1488 uint64_t value = end[i] - start[i];
1489
1490 if (counter->pipeline_stat.numerator !=
1491 counter->pipeline_stat.denominator) {
1492 value *= counter->pipeline_stat.numerator;
1493 value /= counter->pipeline_stat.denominator;
1494 }
1495
1496 *((uint64_t *)p) = value;
1497 p += 8;
1498 }
1499
1500 perf_cfg->vtbl.bo_unmap(query->pipeline_stats.bo);
1501
1502 return p - data;
1503 }
1504
1505 void
1506 gen_perf_get_query_data(struct gen_perf_context *perf_ctx,
1507 struct gen_perf_query_object *query,
1508 int data_size,
1509 unsigned *data,
1510 unsigned *bytes_written)
1511 {
1512 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1513 int written = 0;
1514
1515 switch (query->queryinfo->kind) {
1516 case GEN_PERF_QUERY_TYPE_OA:
1517 case GEN_PERF_QUERY_TYPE_RAW:
1518 if (!query->oa.results_accumulated) {
1519 read_gt_frequency(perf_ctx, query);
1520 uint32_t *begin_report = query->oa.map;
1521 uint32_t *end_report = query->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
1522 gen_perf_query_result_read_frequencies(&query->oa.result,
1523 perf_ctx->devinfo,
1524 begin_report,
1525 end_report);
1526 accumulate_oa_reports(perf_ctx, query);
1527 assert(query->oa.results_accumulated);
1528
1529 perf_cfg->vtbl.bo_unmap(query->oa.bo);
1530 query->oa.map = NULL;
1531 }
1532 if (query->queryinfo->kind == GEN_PERF_QUERY_TYPE_OA) {
1533 written = get_oa_counter_data(perf_ctx, query, data_size, (uint8_t *)data);
1534 } else {
1535 const struct gen_device_info *devinfo = perf_ctx->devinfo;
1536
1537 written = gen_perf_query_result_write_mdapi((uint8_t *)data, data_size,
1538 devinfo, &query->oa.result,
1539 query->oa.gt_frequency[0],
1540 query->oa.gt_frequency[1]);
1541 }
1542 break;
1543
1544 case GEN_PERF_QUERY_TYPE_PIPELINE:
1545 written = get_pipeline_stats_data(perf_ctx, query, data_size, (uint8_t *)data);
1546 break;
1547
1548 default:
1549 unreachable("Unknown query type");
1550 break;
1551 }
1552
1553 if (bytes_written)
1554 *bytes_written = written;
1555 }
1556
1557 void
1558 gen_perf_dump_query_count(struct gen_perf_context *perf_ctx)
1559 {
1560 DBG("Queries: (Open queries = %d, OA users = %d)\n",
1561 perf_ctx->n_active_oa_queries, perf_ctx->n_oa_users);
1562 }
1563
1564 void
1565 gen_perf_dump_query(struct gen_perf_context *ctx,
1566 struct gen_perf_query_object *obj,
1567 void *current_batch)
1568 {
1569 switch (obj->queryinfo->kind) {
1570 case GEN_PERF_QUERY_TYPE_OA:
1571 case GEN_PERF_QUERY_TYPE_RAW:
1572 DBG("BO: %-4s OA data: %-10s %-15s\n",
1573 obj->oa.bo ? "yes," : "no,",
1574 gen_perf_is_query_ready(ctx, obj, current_batch) ? "ready," : "not ready,",
1575 obj->oa.results_accumulated ? "accumulated" : "not accumulated");
1576 break;
1577 case GEN_PERF_QUERY_TYPE_PIPELINE:
1578 DBG("BO: %-4s\n",
1579 obj->pipeline_stats.bo ? "yes" : "no");
1580 break;
1581 default:
1582 unreachable("Unknown query type");
1583 break;
1584 }
1585 }