1c9ddf52ea378eea7e5553030f038357e186a907
[mesa.git] / src / mesa / drivers / dri / i965 / brw_performance_query.c
1 /*
2 * Copyright © 2013 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
21 * DEALINGS IN THE SOFTWARE.
22 */
23
24 /**
25 * \file brw_performance_query.c
26 *
27 * Implementation of the GL_INTEL_performance_query extension.
28 *
29 * Currently there are two possible counter sources exposed here:
30 *
31 * On Gen6+ hardware we have numerous 64bit Pipeline Statistics Registers
32 * that we can snapshot at the beginning and end of a query.
33 *
34 * On Gen7.5+ we have Observability Architecture counters which are
35 * covered in separate document from the rest of the PRMs. It is available at:
36 * https://01.org/linuxgraphics/documentation/driver-documentation-prms
37 * => 2013 Intel Core Processor Family => Observability Performance Counters
38 * (This one volume covers Sandybridge, Ivybridge, Baytrail, and Haswell,
39 * though notably we currently only support OA counters for Haswell+)
40 */
41
42 #include <limits.h>
43 #include <dirent.h>
44
45 /* put before sys/types.h to silence glibc warnings */
46 #ifdef MAJOR_IN_MKDEV
47 #include <sys/mkdev.h>
48 #endif
49 #ifdef MAJOR_IN_SYSMACROS
50 #include <sys/sysmacros.h>
51 #endif
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <fcntl.h>
55 #include <sys/mman.h>
56 #include <sys/ioctl.h>
57
58 #include <xf86drm.h>
59 #include <i915_drm.h>
60
61 #include "main/hash.h"
62 #include "main/macros.h"
63 #include "main/mtypes.h"
64 #include "main/performance_query.h"
65
66 #include "util/bitset.h"
67 #include "util/ralloc.h"
68 #include "util/hash_table.h"
69 #include "util/list.h"
70
71 #include "brw_context.h"
72 #include "brw_defines.h"
73 #include "brw_performance_query.h"
74 #include "brw_oa_hsw.h"
75 #include "intel_batchbuffer.h"
76
77 #define FILE_DEBUG_FLAG DEBUG_PERFMON
78
79 /*
80 * The largest OA format we can use on Haswell includes:
81 * 1 timestamp, 45 A counters, 8 B counters and 8 C counters.
82 */
83 #define MAX_OA_REPORT_COUNTERS 62
84
85 #define I915_PERF_OA_SAMPLE_SIZE (8 + /* drm_i915_perf_record_header */ \
86 256) /* OA counter report */
87
88 /**
89 * Periodic OA samples are read() into these buffer structures via the
90 * i915 perf kernel interface and appended to the
91 * brw->perfquery.sample_buffers linked list. When we process the
92 * results of an OA metrics query we need to consider all the periodic
93 * samples between the Begin and End MI_REPORT_PERF_COUNT command
94 * markers.
95 *
96 * 'Periodic' is a simplification as there are other automatic reports
97 * written by the hardware also buffered here.
98 *
99 * Considering three queries, A, B and C:
100 *
101 * Time ---->
102 * ________________A_________________
103 * | |
104 * | ________B_________ _____C___________
105 * | | | | | |
106 *
107 * And an illustration of sample buffers read over this time frame:
108 * [HEAD ][ ][ ][ ][ ][ ][ ][ ][TAIL ]
109 *
110 * These nodes may hold samples for query A:
111 * [ ][ ][ A ][ A ][ A ][ A ][ A ][ ][ ]
112 *
113 * These nodes may hold samples for query B:
114 * [ ][ ][ B ][ B ][ B ][ ][ ][ ][ ]
115 *
116 * These nodes may hold samples for query C:
117 * [ ][ ][ ][ ][ ][ C ][ C ][ C ][ ]
118 *
119 * The illustration assumes we have an even distribution of periodic
120 * samples so all nodes have the same size plotted against time:
121 *
122 * Note, to simplify code, the list is never empty.
123 *
124 * With overlapping queries we can see that periodic OA reports may
125 * relate to multiple queries and care needs to be take to keep
126 * track of sample buffers until there are no queries that might
127 * depend on their contents.
128 *
129 * We use a node ref counting system where a reference ensures that a
130 * node and all following nodes can't be freed/recycled until the
131 * reference drops to zero.
132 *
133 * E.g. with a ref of one here:
134 * [ 0 ][ 0 ][ 1 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ]
135 *
136 * These nodes could be freed or recycled ("reaped"):
137 * [ 0 ][ 0 ]
138 *
139 * These must be preserved until the leading ref drops to zero:
140 * [ 1 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ]
141 *
142 * When a query starts we take a reference on the current tail of
143 * the list, knowing that no already-buffered samples can possibly
144 * relate to the newly-started query. A pointer to this node is
145 * also saved in the query object's ->oa.samples_head.
146 *
147 * E.g. starting query A while there are two nodes in .sample_buffers:
148 * ________________A________
149 * |
150 *
151 * [ 0 ][ 1 ]
152 * ^_______ Add a reference and store pointer to node in
153 * A->oa.samples_head
154 *
155 * Moving forward to when the B query starts with no new buffer nodes:
156 * (for reference, i915 perf reads() are only done when queries finish)
157 * ________________A_______
158 * | ________B___
159 * | |
160 *
161 * [ 0 ][ 2 ]
162 * ^_______ Add a reference and store pointer to
163 * node in B->oa.samples_head
164 *
165 * Once a query is finished, after an OA query has become 'Ready',
166 * once the End OA report has landed and after we we have processed
167 * all the intermediate periodic samples then we drop the
168 * ->oa.samples_head reference we took at the start.
169 *
170 * So when the B query has finished we have:
171 * ________________A________
172 * | ______B___________
173 * | | |
174 * [ 0 ][ 1 ][ 0 ][ 0 ][ 0 ]
175 * ^_______ Drop B->oa.samples_head reference
176 *
177 * We still can't free these due to the A->oa.samples_head ref:
178 * [ 1 ][ 0 ][ 0 ][ 0 ]
179 *
180 * When the A query finishes: (note there's a new ref for C's samples_head)
181 * ________________A_________________
182 * | |
183 * | _____C_________
184 * | | |
185 * [ 0 ][ 0 ][ 0 ][ 0 ][ 1 ][ 0 ][ 0 ]
186 * ^_______ Drop A->oa.samples_head reference
187 *
188 * And we can now reap these nodes up to the C->oa.samples_head:
189 * [ X ][ X ][ X ][ X ]
190 * keeping -> [ 1 ][ 0 ][ 0 ]
191 *
192 * We reap old sample buffers each time we finish processing an OA
193 * query by iterating the sample_buffers list from the head until we
194 * find a referenced node and stop.
195 *
196 * Reaped buffers move to a perfquery.free_sample_buffers list and
197 * when we come to read() we first look to recycle a buffer from the
198 * free_sample_buffers list before allocating a new buffer.
199 */
200 struct brw_oa_sample_buf {
201 struct exec_node link;
202 int refcount;
203 int len;
204 uint8_t buf[I915_PERF_OA_SAMPLE_SIZE * 10];
205 };
206
207 /**
208 * i965 representation of a performance query object.
209 *
210 * NB: We want to keep this structure relatively lean considering that
211 * applications may expect to allocate enough objects to be able to
212 * query around all draw calls in a frame.
213 */
214 struct brw_perf_query_object
215 {
216 struct gl_perf_query_object base;
217
218 const struct brw_perf_query_info *query;
219
220 /* See query->kind to know which state below is in use... */
221 union {
222 struct {
223
224 /**
225 * BO containing OA counter snapshots at query Begin/End time.
226 */
227 struct brw_bo *bo;
228
229 /**
230 * The MI_REPORT_PERF_COUNT command lets us specify a unique
231 * ID that will be reflected in the resulting OA report
232 * that's written by the GPU. This is the ID we're expecting
233 * in the begin report and the the end report should be
234 * @begin_report_id + 1.
235 */
236 int begin_report_id;
237
238 /**
239 * Reference the head of the brw->perfquery.sample_buffers
240 * list at the time that the query started (so we only need
241 * to look at nodes after this point when looking for samples
242 * related to this query)
243 *
244 * (See struct brw_oa_sample_buf description for more details)
245 */
246 struct exec_node *samples_head;
247
248 /**
249 * Storage for the final accumulated OA counters.
250 */
251 uint64_t accumulator[MAX_OA_REPORT_COUNTERS];
252
253 /**
254 * false while in the unaccumulated_elements list, and set to
255 * true when the final, end MI_RPC snapshot has been
256 * accumulated.
257 */
258 bool results_accumulated;
259
260 } oa;
261
262 struct {
263 /**
264 * BO containing starting and ending snapshots for the
265 * statistics counters.
266 */
267 struct brw_bo *bo;
268 } pipeline_stats;
269 };
270 };
271
272 /** Downcasting convenience macro. */
273 static inline struct brw_perf_query_object *
274 brw_perf_query(struct gl_perf_query_object *o)
275 {
276 return (struct brw_perf_query_object *) o;
277 }
278
279 #define STATS_BO_SIZE 4096
280 #define STATS_BO_END_OFFSET_BYTES (STATS_BO_SIZE / 2)
281 #define MAX_STAT_COUNTERS (STATS_BO_END_OFFSET_BYTES / 8)
282
283 #define MI_RPC_BO_SIZE 4096
284 #define MI_RPC_BO_END_OFFSET_BYTES (MI_RPC_BO_SIZE / 2)
285
286 /******************************************************************************/
287
288 static bool
289 brw_is_perf_query_ready(struct gl_context *ctx,
290 struct gl_perf_query_object *o);
291
292 static void
293 dump_perf_query_callback(GLuint id, void *query_void, void *brw_void)
294 {
295 struct gl_context *ctx = brw_void;
296 struct gl_perf_query_object *o = query_void;
297 struct brw_perf_query_object *obj = query_void;
298
299 switch (obj->query->kind) {
300 case OA_COUNTERS:
301 DBG("%4d: %-6s %-8s BO: %-4s OA data: %-10s %-15s\n",
302 id,
303 o->Used ? "Dirty," : "New,",
304 o->Active ? "Active," : (o->Ready ? "Ready," : "Pending,"),
305 obj->oa.bo ? "yes," : "no,",
306 brw_is_perf_query_ready(ctx, o) ? "ready," : "not ready,",
307 obj->oa.results_accumulated ? "accumulated" : "not accumulated");
308 break;
309 case PIPELINE_STATS:
310 DBG("%4d: %-6s %-8s BO: %-4s\n",
311 id,
312 o->Used ? "Dirty," : "New,",
313 o->Active ? "Active," : (o->Ready ? "Ready," : "Pending,"),
314 obj->pipeline_stats.bo ? "yes" : "no");
315 break;
316 }
317 }
318
319 static void
320 dump_perf_queries(struct brw_context *brw)
321 {
322 struct gl_context *ctx = &brw->ctx;
323 DBG("Queries: (Open queries = %d, OA users = %d)\n",
324 brw->perfquery.n_active_oa_queries, brw->perfquery.n_oa_users);
325 _mesa_HashWalk(ctx->PerfQuery.Objects, dump_perf_query_callback, brw);
326 }
327
328 /******************************************************************************/
329
330 static struct brw_oa_sample_buf *
331 get_free_sample_buf(struct brw_context *brw)
332 {
333 struct exec_node *node = exec_list_pop_head(&brw->perfquery.free_sample_buffers);
334 struct brw_oa_sample_buf *buf;
335
336 if (node)
337 buf = exec_node_data(struct brw_oa_sample_buf, node, link);
338 else {
339 buf = ralloc_size(brw, sizeof(*buf));
340
341 exec_node_init(&buf->link);
342 buf->refcount = 0;
343 buf->len = 0;
344 }
345
346 return buf;
347 }
348
349 static void
350 reap_old_sample_buffers(struct brw_context *brw)
351 {
352 struct exec_node *tail_node =
353 exec_list_get_tail(&brw->perfquery.sample_buffers);
354 struct brw_oa_sample_buf *tail_buf =
355 exec_node_data(struct brw_oa_sample_buf, tail_node, link);
356
357 /* Remove all old, unreferenced sample buffers walking forward from
358 * the head of the list, except always leave at least one node in
359 * the list so we always have a node to reference when we Begin
360 * a new query.
361 */
362 foreach_list_typed_safe(struct brw_oa_sample_buf, buf, link,
363 &brw->perfquery.sample_buffers)
364 {
365 if (buf->refcount == 0 && buf != tail_buf) {
366 exec_node_remove(&buf->link);
367 exec_list_push_head(&brw->perfquery.free_sample_buffers, &buf->link);
368 } else
369 return;
370 }
371 }
372
373 static void
374 free_sample_bufs(struct brw_context *brw)
375 {
376 foreach_list_typed_safe(struct brw_oa_sample_buf, buf, link,
377 &brw->perfquery.free_sample_buffers)
378 ralloc_free(buf);
379
380 exec_list_make_empty(&brw->perfquery.free_sample_buffers);
381 }
382
383 /******************************************************************************/
384
385 /**
386 * Driver hook for glGetPerfQueryInfoINTEL().
387 */
388 static void
389 brw_get_perf_query_info(struct gl_context *ctx,
390 unsigned query_index,
391 const char **name,
392 GLuint *data_size,
393 GLuint *n_counters,
394 GLuint *n_active)
395 {
396 struct brw_context *brw = brw_context(ctx);
397 const struct brw_perf_query_info *query =
398 &brw->perfquery.queries[query_index];
399
400 *name = query->name;
401 *data_size = query->data_size;
402 *n_counters = query->n_counters;
403
404 switch (query->kind) {
405 case OA_COUNTERS:
406 *n_active = brw->perfquery.n_active_oa_queries;
407 break;
408
409 case PIPELINE_STATS:
410 *n_active = brw->perfquery.n_active_pipeline_stats_queries;
411 break;
412 }
413 }
414
415 /**
416 * Driver hook for glGetPerfCounterInfoINTEL().
417 */
418 static void
419 brw_get_perf_counter_info(struct gl_context *ctx,
420 unsigned query_index,
421 unsigned counter_index,
422 const char **name,
423 const char **desc,
424 GLuint *offset,
425 GLuint *data_size,
426 GLuint *type_enum,
427 GLuint *data_type_enum,
428 GLuint64 *raw_max)
429 {
430 struct brw_context *brw = brw_context(ctx);
431 const struct brw_perf_query_info *query =
432 &brw->perfquery.queries[query_index];
433 const struct brw_perf_query_counter *counter =
434 &query->counters[counter_index];
435
436 *name = counter->name;
437 *desc = counter->desc;
438 *offset = counter->offset;
439 *data_size = counter->size;
440 *type_enum = counter->type;
441 *data_type_enum = counter->data_type;
442 *raw_max = counter->raw_max;
443 }
444
445 /******************************************************************************/
446
447 /**
448 * Emit MI_STORE_REGISTER_MEM commands to capture all of the
449 * pipeline statistics for the performance query object.
450 */
451 static void
452 snapshot_statistics_registers(struct brw_context *brw,
453 struct brw_perf_query_object *obj,
454 uint32_t offset_in_bytes)
455 {
456 const struct brw_perf_query_info *query = obj->query;
457 const int n_counters = query->n_counters;
458
459 for (int i = 0; i < n_counters; i++) {
460 const struct brw_perf_query_counter *counter = &query->counters[i];
461
462 assert(counter->data_type == GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL);
463
464 brw_store_register_mem64(brw, obj->pipeline_stats.bo,
465 counter->pipeline_stat.reg,
466 offset_in_bytes + i * sizeof(uint64_t));
467 }
468 }
469
470 /**
471 * Emit an MI_REPORT_PERF_COUNT command packet.
472 *
473 * This asks the GPU to write a report of the current OA counter
474 * values into @bo at the given offset and containing the given
475 * @report_id which we can cross-reference when parsing the report.
476 */
477 static void
478 emit_mi_report_perf_count(struct brw_context *brw,
479 struct brw_bo *bo,
480 uint32_t offset_in_bytes,
481 uint32_t report_id)
482 {
483 assert(offset_in_bytes % 64 == 0);
484
485 BEGIN_BATCH(3);
486 OUT_BATCH(GEN6_MI_REPORT_PERF_COUNT);
487 OUT_RELOC(bo, I915_GEM_DOMAIN_INSTRUCTION, I915_GEM_DOMAIN_INSTRUCTION,
488 offset_in_bytes);
489 OUT_BATCH(report_id);
490 ADVANCE_BATCH();
491 }
492
493 /**
494 * Add a query to the global list of "unaccumulated queries."
495 *
496 * Queries are tracked here until all the associated OA reports have
497 * been accumulated via accumulate_oa_reports() after the end
498 * MI_REPORT_PERF_COUNT has landed in query->oa.bo.
499 */
500 static void
501 add_to_unaccumulated_query_list(struct brw_context *brw,
502 struct brw_perf_query_object *obj)
503 {
504 if (brw->perfquery.unaccumulated_elements >=
505 brw->perfquery.unaccumulated_array_size)
506 {
507 brw->perfquery.unaccumulated_array_size *= 1.5;
508 brw->perfquery.unaccumulated =
509 reralloc(brw, brw->perfquery.unaccumulated,
510 struct brw_perf_query_object *,
511 brw->perfquery.unaccumulated_array_size);
512 }
513
514 brw->perfquery.unaccumulated[brw->perfquery.unaccumulated_elements++] = obj;
515 }
516
517 /**
518 * Remove a query from the global list of unaccumulated queries once
519 * after successfully accumulating the OA reports associated with the
520 * query in accumulate_oa_reports() or when discarding unwanted query
521 * results.
522 */
523 static void
524 drop_from_unaccumulated_query_list(struct brw_context *brw,
525 struct brw_perf_query_object *obj)
526 {
527 for (int i = 0; i < brw->perfquery.unaccumulated_elements; i++) {
528 if (brw->perfquery.unaccumulated[i] == obj) {
529 int last_elt = --brw->perfquery.unaccumulated_elements;
530
531 if (i == last_elt)
532 brw->perfquery.unaccumulated[i] = NULL;
533 else {
534 brw->perfquery.unaccumulated[i] =
535 brw->perfquery.unaccumulated[last_elt];
536 }
537
538 break;
539 }
540 }
541
542 /* Drop our samples_head reference so that associated periodic
543 * sample data buffers can potentially be reaped if they aren't
544 * referenced by any other queries...
545 */
546
547 struct brw_oa_sample_buf *buf =
548 exec_node_data(struct brw_oa_sample_buf, obj->oa.samples_head, link);
549
550 assert(buf->refcount > 0);
551 buf->refcount--;
552
553 obj->oa.samples_head = NULL;
554
555 reap_old_sample_buffers(brw);
556 }
557
558 static uint64_t
559 timebase_scale(struct brw_context *brw, uint32_t u32_time_delta)
560 {
561 uint64_t tmp = ((uint64_t)u32_time_delta) * 1000000000ull;
562
563 return tmp ? tmp / brw->perfquery.sys_vars.timestamp_frequency : 0;
564 }
565
566 static void
567 accumulate_uint32(const uint32_t *report0,
568 const uint32_t *report1,
569 uint64_t *accumulator)
570 {
571 *accumulator += (uint32_t)(*report1 - *report0);
572 }
573
574 /**
575 * Given pointers to starting and ending OA snapshots, add the deltas for each
576 * counter to the results.
577 */
578 static void
579 add_deltas(struct brw_context *brw,
580 struct brw_perf_query_object *obj,
581 const uint32_t *start,
582 const uint32_t *end)
583 {
584 const struct brw_perf_query_info *query = obj->query;
585 uint64_t *accumulator = obj->oa.accumulator;
586 int i;
587
588 switch (query->oa_format) {
589 case I915_OA_FORMAT_A45_B8_C8:
590 accumulate_uint32(start + 1, end + 1, accumulator); /* timestamp */
591
592 for (i = 0; i < 61; i++)
593 accumulate_uint32(start + 3 + i, end + 3 + i, accumulator + 1 + i);
594
595 break;
596 default:
597 unreachable("Can't accumulate OA counters in unknown format");
598 }
599 }
600
601 static bool
602 inc_n_oa_users(struct brw_context *brw)
603 {
604 if (brw->perfquery.n_oa_users == 0 &&
605 drmIoctl(brw->perfquery.oa_stream_fd,
606 I915_PERF_IOCTL_ENABLE, 0) < 0)
607 {
608 return false;
609 }
610 ++brw->perfquery.n_oa_users;
611
612 return true;
613 }
614
615 static void
616 dec_n_oa_users(struct brw_context *brw)
617 {
618 /* Disabling the i915 perf stream will effectively disable the OA
619 * counters. Note it's important to be sure there are no outstanding
620 * MI_RPC commands at this point since they could stall the CS
621 * indefinitely once OACONTROL is disabled.
622 */
623 --brw->perfquery.n_oa_users;
624 if (brw->perfquery.n_oa_users == 0 &&
625 drmIoctl(brw->perfquery.oa_stream_fd, I915_PERF_IOCTL_DISABLE, 0) < 0)
626 {
627 DBG("WARNING: Error disabling i915 perf stream: %m\n");
628 }
629 }
630
631 /* In general if we see anything spurious while accumulating results,
632 * we don't try and continue accumulating the current query, hoping
633 * for the best, we scrap anything outstanding, and then hope for the
634 * best with new queries.
635 */
636 static void
637 discard_all_queries(struct brw_context *brw)
638 {
639 while (brw->perfquery.unaccumulated_elements) {
640 struct brw_perf_query_object *obj = brw->perfquery.unaccumulated[0];
641
642 obj->oa.results_accumulated = true;
643 drop_from_unaccumulated_query_list(brw, brw->perfquery.unaccumulated[0]);
644
645 dec_n_oa_users(brw);
646 }
647 }
648
649 static bool
650 read_oa_samples(struct brw_context *brw)
651 {
652 while (1) {
653 struct brw_oa_sample_buf *buf = get_free_sample_buf(brw);
654 int len;
655
656 while ((len = read(brw->perfquery.oa_stream_fd, buf->buf,
657 sizeof(buf->buf))) < 0 && errno == EINTR)
658 ;
659
660 if (len <= 0) {
661 exec_list_push_tail(&brw->perfquery.free_sample_buffers, &buf->link);
662
663 if (len < 0) {
664 if (errno == EAGAIN)
665 return true;
666 else {
667 DBG("Error reading i915 perf samples: %m\n");
668 return false;
669 }
670 } else {
671 DBG("Spurious EOF reading i915 perf samples\n");
672 return false;
673 }
674 }
675
676 buf->len = len;
677 exec_list_push_tail(&brw->perfquery.sample_buffers, &buf->link);
678 }
679
680 unreachable("not reached");
681 return false;
682 }
683
684 /**
685 * Accumulate raw OA counter values based on deltas between pairs
686 * of OA reports.
687 *
688 * Accumulation starts from the first report captured via
689 * MI_REPORT_PERF_COUNT (MI_RPC) by brw_begin_perf_query() until the
690 * last MI_RPC report requested by brw_end_perf_query(). Between these
691 * two reports there may also some number of periodically sampled OA
692 * reports collected via the i915 perf interface - depending on the
693 * duration of the query.
694 *
695 * These periodic snapshots help to ensure we handle counter overflow
696 * correctly by being frequent enough to ensure we don't miss multiple
697 * overflows of a counter between snapshots.
698 */
699 static void
700 accumulate_oa_reports(struct brw_context *brw,
701 struct brw_perf_query_object *obj)
702 {
703 struct gl_perf_query_object *o = &obj->base;
704 uint32_t *query_buffer;
705 uint32_t *start;
706 uint32_t *last;
707 uint32_t *end;
708 struct exec_node *first_samples_node;
709
710 assert(o->Ready);
711
712 /* Collect the latest periodic OA reports from i915 perf */
713 if (!read_oa_samples(brw))
714 goto error;
715
716 query_buffer = brw_bo_map(brw, obj->oa.bo, MAP_READ);
717
718 start = last = query_buffer;
719 end = query_buffer + (MI_RPC_BO_END_OFFSET_BYTES / sizeof(uint32_t));
720
721 if (start[0] != obj->oa.begin_report_id) {
722 DBG("Spurious start report id=%"PRIu32"\n", start[0]);
723 goto error;
724 }
725 if (end[0] != (obj->oa.begin_report_id + 1)) {
726 DBG("Spurious end report id=%"PRIu32"\n", end[0]);
727 goto error;
728 }
729
730 /* See if we have any periodic reports to accumulate too... */
731
732 /* N.B. The oa.samples_head was set when the query began and
733 * pointed to the tail of the brw->perfquery.sample_buffers list at
734 * the time the query started. Since the buffer existed before the
735 * first MI_REPORT_PERF_COUNT command was emitted we therefore know
736 * that no data in this particular node's buffer can possibly be
737 * associated with the query - so skip ahead one...
738 */
739 first_samples_node = obj->oa.samples_head->next;
740
741 foreach_list_typed_from(struct brw_oa_sample_buf, buf, link,
742 &brw->perfquery.sample_buffers,
743 first_samples_node)
744 {
745 int offset = 0;
746
747 while (offset < buf->len) {
748 const struct drm_i915_perf_record_header *header =
749 (const struct drm_i915_perf_record_header *)(buf->buf + offset);
750
751 assert(header->size != 0);
752 assert(header->size <= buf->len);
753
754 offset += header->size;
755
756 switch (header->type) {
757 case DRM_I915_PERF_RECORD_SAMPLE: {
758 uint32_t *report = (uint32_t *)(header + 1);
759
760 /* Ignore reports that come before the start marker.
761 * (Note: takes care to allow overflow of 32bit timestamps)
762 */
763 if (timebase_scale(brw, report[1] - start[1]) > 5000000000)
764 continue;
765
766 /* Ignore reports that come after the end marker.
767 * (Note: takes care to allow overflow of 32bit timestamps)
768 */
769 if (timebase_scale(brw, report[1] - end[1]) <= 5000000000)
770 goto end;
771
772 add_deltas(brw, obj, last, report);
773
774 last = report;
775
776 break;
777 }
778
779 case DRM_I915_PERF_RECORD_OA_BUFFER_LOST:
780 DBG("i915 perf: OA error: all reports lost\n");
781 goto error;
782 case DRM_I915_PERF_RECORD_OA_REPORT_LOST:
783 DBG("i915 perf: OA report lost\n");
784 break;
785 }
786 }
787 }
788
789 end:
790
791 add_deltas(brw, obj, last, end);
792
793 DBG("Marking %d accumulated - results gathered\n", o->Id);
794
795 brw_bo_unmap(obj->oa.bo);
796 obj->oa.results_accumulated = true;
797 drop_from_unaccumulated_query_list(brw, obj);
798 dec_n_oa_users(brw);
799
800 return;
801
802 error:
803
804 brw_bo_unmap(obj->oa.bo);
805 discard_all_queries(brw);
806 }
807
808 /******************************************************************************/
809
810 static bool
811 open_i915_perf_oa_stream(struct brw_context *brw,
812 int metrics_set_id,
813 int report_format,
814 int period_exponent,
815 int drm_fd,
816 uint32_t ctx_id)
817 {
818 uint64_t properties[] = {
819 /* Single context sampling */
820 DRM_I915_PERF_PROP_CTX_HANDLE, ctx_id,
821
822 /* Include OA reports in samples */
823 DRM_I915_PERF_PROP_SAMPLE_OA, true,
824
825 /* OA unit configuration */
826 DRM_I915_PERF_PROP_OA_METRICS_SET, metrics_set_id,
827 DRM_I915_PERF_PROP_OA_FORMAT, report_format,
828 DRM_I915_PERF_PROP_OA_EXPONENT, period_exponent,
829 };
830 struct drm_i915_perf_open_param param = {
831 .flags = I915_PERF_FLAG_FD_CLOEXEC |
832 I915_PERF_FLAG_FD_NONBLOCK |
833 I915_PERF_FLAG_DISABLED,
834 .num_properties = ARRAY_SIZE(properties) / 2,
835 .properties_ptr = (uintptr_t) properties,
836 };
837 int fd = drmIoctl(drm_fd, DRM_IOCTL_I915_PERF_OPEN, &param);
838 if (fd == -1) {
839 DBG("Error opening i915 perf OA stream: %m\n");
840 return false;
841 }
842
843 brw->perfquery.oa_stream_fd = fd;
844
845 brw->perfquery.current_oa_metrics_set_id = metrics_set_id;
846 brw->perfquery.current_oa_format = report_format;
847
848 return true;
849 }
850
851 static void
852 close_perf(struct brw_context *brw)
853 {
854 if (brw->perfquery.oa_stream_fd != -1) {
855 close(brw->perfquery.oa_stream_fd);
856 brw->perfquery.oa_stream_fd = -1;
857 }
858 }
859
860 /**
861 * Driver hook for glBeginPerfQueryINTEL().
862 */
863 static bool
864 brw_begin_perf_query(struct gl_context *ctx,
865 struct gl_perf_query_object *o)
866 {
867 struct brw_context *brw = brw_context(ctx);
868 struct brw_perf_query_object *obj = brw_perf_query(o);
869 const struct brw_perf_query_info *query = obj->query;
870
871 /* We can assume the frontend hides mistaken attempts to Begin a
872 * query object multiple times before its End. Similarly if an
873 * application reuses a query object before results have arrived
874 * the frontend will wait for prior results so we don't need
875 * to support abandoning in-flight results.
876 */
877 assert(!o->Active);
878 assert(!o->Used || o->Ready); /* no in-flight query to worry about */
879
880 DBG("Begin(%d)\n", o->Id);
881
882 /* XXX: We have to consider that the command parser unit that parses batch
883 * buffer commands and is used to capture begin/end counter snapshots isn't
884 * implicitly synchronized with what's currently running across other GPU
885 * units (such as the EUs running shaders) that the performance counters are
886 * associated with.
887 *
888 * The intention of performance queries is to measure the work associated
889 * with commands between the begin/end delimiters and so for that to be the
890 * case we need to explicitly synchronize the parsing of commands to capture
891 * Begin/End counter snapshots with what's running across other parts of the
892 * GPU.
893 *
894 * When the command parser reaches a Begin marker it effectively needs to
895 * drain everything currently running on the GPU until the hardware is idle
896 * before capturing the first snapshot of counters - otherwise the results
897 * would also be measuring the effects of earlier commands.
898 *
899 * When the command parser reaches an End marker it needs to stall until
900 * everything currently running on the GPU has finished before capturing the
901 * end snapshot - otherwise the results won't be a complete representation
902 * of the work.
903 *
904 * Theoretically there could be opportunities to minimize how much of the
905 * GPU pipeline is drained, or that we stall for, when we know what specific
906 * units the performance counters being queried relate to but we don't
907 * currently attempt to be clever here.
908 *
909 * Note: with our current simple approach here then for back-to-back queries
910 * we will redundantly emit duplicate commands to synchronize the command
911 * streamer with the rest of the GPU pipeline, but we assume that in HW the
912 * second synchronization is effectively a NOOP.
913 *
914 * N.B. The final results are based on deltas of counters between (inside)
915 * Begin/End markers so even though the total wall clock time of the
916 * workload is stretched by larger pipeline bubbles the bubbles themselves
917 * are generally invisible to the query results. Whether that's a good or a
918 * bad thing depends on the use case. For a lower real-time impact while
919 * capturing metrics then periodic sampling may be a better choice than
920 * INTEL_performance_query.
921 *
922 *
923 * This is our Begin synchronization point to drain current work on the
924 * GPU before we capture our first counter snapshot...
925 */
926 brw_emit_mi_flush(brw);
927
928 switch (query->kind) {
929 case OA_COUNTERS:
930
931 /* Opening an i915 perf stream implies exclusive access to the OA unit
932 * which will generate counter reports for a specific counter set with a
933 * specific layout/format so we can't begin any OA based queries that
934 * require a different counter set or format unless we get an opportunity
935 * to close the stream and open a new one...
936 */
937 if (brw->perfquery.oa_stream_fd != -1 &&
938 brw->perfquery.current_oa_metrics_set_id !=
939 query->oa_metrics_set_id) {
940
941 if (brw->perfquery.n_oa_users != 0)
942 return false;
943 else
944 close_perf(brw);
945 }
946
947 /* If the OA counters aren't already on, enable them. */
948 if (brw->perfquery.oa_stream_fd == -1) {
949 __DRIscreen *screen = brw->screen->driScrnPriv;
950 int period_exponent;
951
952 /* The timestamp for HSW+ increments every 80ns
953 *
954 * The period_exponent gives a sampling period as follows:
955 * sample_period = 80ns * 2^(period_exponent + 1)
956 *
957 * The overflow period for Haswell can be calculated as:
958 *
959 * 2^32 / (n_eus * max_gen_freq * 2)
960 * (E.g. 40 EUs @ 1GHz = ~53ms)
961 *
962 * We currently sample every 42 milliseconds...
963 */
964 period_exponent = 18;
965
966 if (!open_i915_perf_oa_stream(brw,
967 query->oa_metrics_set_id,
968 query->oa_format,
969 period_exponent,
970 screen->fd, /* drm fd */
971 brw->hw_ctx))
972 return false;
973 } else {
974 assert(brw->perfquery.current_oa_metrics_set_id ==
975 query->oa_metrics_set_id &&
976 brw->perfquery.current_oa_format ==
977 query->oa_format);
978 }
979
980 if (!inc_n_oa_users(brw)) {
981 DBG("WARNING: Error enabling i915 perf stream: %m\n");
982 return false;
983 }
984
985 if (obj->oa.bo) {
986 brw_bo_unreference(obj->oa.bo);
987 obj->oa.bo = NULL;
988 }
989
990 obj->oa.bo =
991 brw_bo_alloc(brw->bufmgr, "perf. query OA MI_RPC bo",
992 MI_RPC_BO_SIZE, 64);
993 #ifdef DEBUG
994 /* Pre-filling the BO helps debug whether writes landed. */
995 void *map = brw_bo_map(brw, obj->oa.bo, MAP_WRITE);
996 memset(map, 0x80, MI_RPC_BO_SIZE);
997 brw_bo_unmap(obj->oa.bo);
998 #endif
999
1000 obj->oa.begin_report_id = brw->perfquery.next_query_start_report_id;
1001 brw->perfquery.next_query_start_report_id += 2;
1002
1003 /* Take a starting OA counter snapshot. */
1004 emit_mi_report_perf_count(brw, obj->oa.bo, 0,
1005 obj->oa.begin_report_id);
1006 ++brw->perfquery.n_active_oa_queries;
1007
1008 /* No already-buffered samples can possibly be associated with this query
1009 * so create a marker within the list of sample buffers enabling us to
1010 * easily ignore earlier samples when processing this query after
1011 * completion.
1012 */
1013 assert(!exec_list_is_empty(&brw->perfquery.sample_buffers));
1014 obj->oa.samples_head = exec_list_get_tail(&brw->perfquery.sample_buffers);
1015
1016 struct brw_oa_sample_buf *buf =
1017 exec_node_data(struct brw_oa_sample_buf, obj->oa.samples_head, link);
1018
1019 /* This reference will ensure that future/following sample
1020 * buffers (that may relate to this query) can't be freed until
1021 * this drops to zero.
1022 */
1023 buf->refcount++;
1024
1025 memset(obj->oa.accumulator, 0, sizeof(obj->oa.accumulator));
1026 obj->oa.results_accumulated = false;
1027
1028 add_to_unaccumulated_query_list(brw, obj);
1029 break;
1030
1031 case PIPELINE_STATS:
1032 if (obj->pipeline_stats.bo) {
1033 brw_bo_unreference(obj->pipeline_stats.bo);
1034 obj->pipeline_stats.bo = NULL;
1035 }
1036
1037 obj->pipeline_stats.bo =
1038 brw_bo_alloc(brw->bufmgr, "perf. query pipeline stats bo",
1039 STATS_BO_SIZE, 64);
1040
1041 /* Take starting snapshots. */
1042 snapshot_statistics_registers(brw, obj, 0);
1043
1044 ++brw->perfquery.n_active_pipeline_stats_queries;
1045 break;
1046 }
1047
1048 if (INTEL_DEBUG & DEBUG_PERFMON)
1049 dump_perf_queries(brw);
1050
1051 return true;
1052 }
1053
1054 /**
1055 * Driver hook for glEndPerfQueryINTEL().
1056 */
1057 static void
1058 brw_end_perf_query(struct gl_context *ctx,
1059 struct gl_perf_query_object *o)
1060 {
1061 struct brw_context *brw = brw_context(ctx);
1062 struct brw_perf_query_object *obj = brw_perf_query(o);
1063
1064 DBG("End(%d)\n", o->Id);
1065
1066 /* Ensure that the work associated with the queried commands will have
1067 * finished before taking our query end counter readings.
1068 *
1069 * For more details see comment in brw_begin_perf_query for
1070 * corresponding flush.
1071 */
1072 brw_emit_mi_flush(brw);
1073
1074 switch (obj->query->kind) {
1075 case OA_COUNTERS:
1076
1077 /* NB: It's possible that the query will have already been marked
1078 * as 'accumulated' if an error was seen while reading samples
1079 * from perf. In this case we mustn't try and emit a closing
1080 * MI_RPC command in case the OA unit has already been disabled
1081 */
1082 if (!obj->oa.results_accumulated) {
1083 /* Take an ending OA counter snapshot. */
1084 emit_mi_report_perf_count(brw, obj->oa.bo,
1085 MI_RPC_BO_END_OFFSET_BYTES,
1086 obj->oa.begin_report_id + 1);
1087 }
1088
1089 --brw->perfquery.n_active_oa_queries;
1090
1091 /* NB: even though the query has now ended, it can't be accumulated
1092 * until the end MI_REPORT_PERF_COUNT snapshot has been written
1093 * to query->oa.bo
1094 */
1095 break;
1096
1097 case PIPELINE_STATS:
1098 snapshot_statistics_registers(brw, obj,
1099 STATS_BO_END_OFFSET_BYTES);
1100 --brw->perfquery.n_active_pipeline_stats_queries;
1101 break;
1102 }
1103 }
1104
1105 static void
1106 brw_wait_perf_query(struct gl_context *ctx, struct gl_perf_query_object *o)
1107 {
1108 struct brw_context *brw = brw_context(ctx);
1109 struct brw_perf_query_object *obj = brw_perf_query(o);
1110 struct brw_bo *bo = NULL;
1111
1112 assert(!o->Ready);
1113
1114 switch (obj->query->kind) {
1115 case OA_COUNTERS:
1116 bo = obj->oa.bo;
1117 break;
1118
1119 case PIPELINE_STATS:
1120 bo = obj->pipeline_stats.bo;
1121 break;
1122 }
1123
1124 if (bo == NULL)
1125 return;
1126
1127 /* If the current batch references our results bo then we need to
1128 * flush first...
1129 */
1130 if (brw_batch_references(&brw->batch, bo))
1131 intel_batchbuffer_flush(brw);
1132
1133 brw_bo_wait_rendering(brw, bo);
1134 }
1135
1136 static bool
1137 brw_is_perf_query_ready(struct gl_context *ctx,
1138 struct gl_perf_query_object *o)
1139 {
1140 struct brw_context *brw = brw_context(ctx);
1141 struct brw_perf_query_object *obj = brw_perf_query(o);
1142
1143 if (o->Ready)
1144 return true;
1145
1146 switch (obj->query->kind) {
1147 case OA_COUNTERS:
1148 return (obj->oa.results_accumulated ||
1149 (obj->oa.bo &&
1150 !brw_batch_references(&brw->batch, obj->oa.bo) &&
1151 !brw_bo_busy(obj->oa.bo)));
1152
1153 case PIPELINE_STATS:
1154 return (obj->pipeline_stats.bo &&
1155 !brw_batch_references(&brw->batch, obj->pipeline_stats.bo) &&
1156 !brw_bo_busy(obj->pipeline_stats.bo));
1157 }
1158
1159 unreachable("missing ready check for unknown query kind");
1160 return false;
1161 }
1162
1163 static int
1164 get_oa_counter_data(struct brw_context *brw,
1165 struct brw_perf_query_object *obj,
1166 size_t data_size,
1167 uint8_t *data)
1168 {
1169 const struct brw_perf_query_info *query = obj->query;
1170 int n_counters = query->n_counters;
1171 int written = 0;
1172
1173 if (!obj->oa.results_accumulated) {
1174 accumulate_oa_reports(brw, obj);
1175 assert(obj->oa.results_accumulated);
1176 }
1177
1178 for (int i = 0; i < n_counters; i++) {
1179 const struct brw_perf_query_counter *counter = &query->counters[i];
1180 uint64_t *out_uint64;
1181 float *out_float;
1182
1183 if (counter->size) {
1184 switch (counter->data_type) {
1185 case GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL:
1186 out_uint64 = (uint64_t *)(data + counter->offset);
1187 *out_uint64 = counter->oa_counter_read_uint64(brw, query,
1188 obj->oa.accumulator);
1189 break;
1190 case GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL:
1191 out_float = (float *)(data + counter->offset);
1192 *out_float = counter->oa_counter_read_float(brw, query,
1193 obj->oa.accumulator);
1194 break;
1195 default:
1196 /* So far we aren't using uint32, double or bool32... */
1197 unreachable("unexpected counter data type");
1198 }
1199 written = counter->offset + counter->size;
1200 }
1201 }
1202
1203 return written;
1204 }
1205
1206 static int
1207 get_pipeline_stats_data(struct brw_context *brw,
1208 struct brw_perf_query_object *obj,
1209 size_t data_size,
1210 uint8_t *data)
1211
1212 {
1213 const struct brw_perf_query_info *query = obj->query;
1214 int n_counters = obj->query->n_counters;
1215 uint8_t *p = data;
1216
1217 uint64_t *start = brw_bo_map(brw, obj->pipeline_stats.bo, MAP_READ);
1218 uint64_t *end = start + (STATS_BO_END_OFFSET_BYTES / sizeof(uint64_t));
1219
1220 for (int i = 0; i < n_counters; i++) {
1221 const struct brw_perf_query_counter *counter = &query->counters[i];
1222 uint64_t value = end[i] - start[i];
1223
1224 if (counter->pipeline_stat.numerator !=
1225 counter->pipeline_stat.denominator) {
1226 value *= counter->pipeline_stat.numerator;
1227 value /= counter->pipeline_stat.denominator;
1228 }
1229
1230 *((uint64_t *)p) = value;
1231 p += 8;
1232 }
1233
1234 brw_bo_unmap(obj->pipeline_stats.bo);
1235
1236 return p - data;
1237 }
1238
1239 /**
1240 * Driver hook for glGetPerfQueryDataINTEL().
1241 */
1242 static void
1243 brw_get_perf_query_data(struct gl_context *ctx,
1244 struct gl_perf_query_object *o,
1245 GLsizei data_size,
1246 GLuint *data,
1247 GLuint *bytes_written)
1248 {
1249 struct brw_context *brw = brw_context(ctx);
1250 struct brw_perf_query_object *obj = brw_perf_query(o);
1251 int written = 0;
1252
1253 assert(brw_is_perf_query_ready(ctx, o));
1254
1255 DBG("GetData(%d)\n", o->Id);
1256
1257 if (INTEL_DEBUG & DEBUG_PERFMON)
1258 dump_perf_queries(brw);
1259
1260 /* We expect that the frontend only calls this hook when it knows
1261 * that results are available.
1262 */
1263 assert(o->Ready);
1264
1265 switch (obj->query->kind) {
1266 case OA_COUNTERS:
1267 written = get_oa_counter_data(brw, obj, data_size, (uint8_t *)data);
1268 break;
1269
1270 case PIPELINE_STATS:
1271 written = get_pipeline_stats_data(brw, obj, data_size, (uint8_t *)data);
1272 break;
1273 }
1274
1275 if (bytes_written)
1276 *bytes_written = written;
1277 }
1278
1279 static struct gl_perf_query_object *
1280 brw_new_perf_query_object(struct gl_context *ctx, unsigned query_index)
1281 {
1282 struct brw_context *brw = brw_context(ctx);
1283 const struct brw_perf_query_info *query =
1284 &brw->perfquery.queries[query_index];
1285 struct brw_perf_query_object *obj =
1286 calloc(1, sizeof(struct brw_perf_query_object));
1287
1288 if (!obj)
1289 return NULL;
1290
1291 obj->query = query;
1292
1293 brw->perfquery.n_query_instances++;
1294
1295 return &obj->base;
1296 }
1297
1298 /**
1299 * Driver hook for glDeletePerfQueryINTEL().
1300 */
1301 static void
1302 brw_delete_perf_query(struct gl_context *ctx,
1303 struct gl_perf_query_object *o)
1304 {
1305 struct brw_context *brw = brw_context(ctx);
1306 struct brw_perf_query_object *obj = brw_perf_query(o);
1307
1308 /* We can assume that the frontend waits for a query to complete
1309 * before ever calling into here, so we don't have to worry about
1310 * deleting an in-flight query object.
1311 */
1312 assert(!o->Active);
1313 assert(!o->Used || o->Ready);
1314
1315 DBG("Delete(%d)\n", o->Id);
1316
1317 switch (obj->query->kind) {
1318 case OA_COUNTERS:
1319 if (obj->oa.bo) {
1320 if (!obj->oa.results_accumulated) {
1321 drop_from_unaccumulated_query_list(brw, obj);
1322 dec_n_oa_users(brw);
1323 }
1324
1325 brw_bo_unreference(obj->oa.bo);
1326 obj->oa.bo = NULL;
1327 }
1328
1329 obj->oa.results_accumulated = false;
1330 break;
1331
1332 case PIPELINE_STATS:
1333 if (obj->pipeline_stats.bo) {
1334 brw_bo_unreference(obj->pipeline_stats.bo);
1335 obj->pipeline_stats.bo = NULL;
1336 }
1337 break;
1338 }
1339
1340 free(obj);
1341
1342 /* As an indication that the INTEL_performance_query extension is no
1343 * longer in use, it's a good time to free our cache of sample
1344 * buffers and close any current i915-perf stream.
1345 */
1346 if (--brw->perfquery.n_query_instances == 0) {
1347 free_sample_bufs(brw);
1348 close_perf(brw);
1349 }
1350 }
1351
1352 /******************************************************************************/
1353
1354 static struct brw_perf_query_info *
1355 append_query_info(struct brw_context *brw)
1356 {
1357 brw->perfquery.queries =
1358 reralloc(brw, brw->perfquery.queries,
1359 struct brw_perf_query_info, ++brw->perfquery.n_queries);
1360
1361 return &brw->perfquery.queries[brw->perfquery.n_queries - 1];
1362 }
1363
1364 static void
1365 add_stat_reg(struct brw_perf_query_info *query,
1366 uint32_t reg,
1367 uint32_t numerator,
1368 uint32_t denominator,
1369 const char *name,
1370 const char *description)
1371 {
1372 struct brw_perf_query_counter *counter;
1373
1374 assert(query->n_counters < MAX_STAT_COUNTERS);
1375
1376 counter = &query->counters[query->n_counters];
1377 counter->name = name;
1378 counter->desc = description;
1379 counter->type = GL_PERFQUERY_COUNTER_RAW_INTEL;
1380 counter->data_type = GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL;
1381 counter->size = sizeof(uint64_t);
1382 counter->offset = sizeof(uint64_t) * query->n_counters;
1383 counter->pipeline_stat.reg = reg;
1384 counter->pipeline_stat.numerator = numerator;
1385 counter->pipeline_stat.denominator = denominator;
1386
1387 query->n_counters++;
1388 }
1389
1390 static void
1391 add_basic_stat_reg(struct brw_perf_query_info *query,
1392 uint32_t reg, const char *name)
1393 {
1394 add_stat_reg(query, reg, 1, 1, name, name);
1395 }
1396
1397 static void
1398 init_pipeline_statistic_query_registers(struct brw_context *brw)
1399 {
1400 struct brw_perf_query_info *query = append_query_info(brw);
1401
1402 query->kind = PIPELINE_STATS;
1403 query->name = "Pipeline Statistics Registers";
1404 query->n_counters = 0;
1405 query->counters =
1406 rzalloc_array(brw, struct brw_perf_query_counter, MAX_STAT_COUNTERS);
1407
1408 add_basic_stat_reg(query, IA_VERTICES_COUNT,
1409 "N vertices submitted");
1410 add_basic_stat_reg(query, IA_PRIMITIVES_COUNT,
1411 "N primitives submitted");
1412 add_basic_stat_reg(query, VS_INVOCATION_COUNT,
1413 "N vertex shader invocations");
1414
1415 if (brw->gen == 6) {
1416 add_stat_reg(query, GEN6_SO_PRIM_STORAGE_NEEDED, 1, 1,
1417 "SO_PRIM_STORAGE_NEEDED",
1418 "N geometry shader stream-out primitives (total)");
1419 add_stat_reg(query, GEN6_SO_NUM_PRIMS_WRITTEN, 1, 1,
1420 "SO_NUM_PRIMS_WRITTEN",
1421 "N geometry shader stream-out primitives (written)");
1422 } else {
1423 add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(0), 1, 1,
1424 "SO_PRIM_STORAGE_NEEDED (Stream 0)",
1425 "N stream-out (stream 0) primitives (total)");
1426 add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(1), 1, 1,
1427 "SO_PRIM_STORAGE_NEEDED (Stream 1)",
1428 "N stream-out (stream 1) primitives (total)");
1429 add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(2), 1, 1,
1430 "SO_PRIM_STORAGE_NEEDED (Stream 2)",
1431 "N stream-out (stream 2) primitives (total)");
1432 add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(3), 1, 1,
1433 "SO_PRIM_STORAGE_NEEDED (Stream 3)",
1434 "N stream-out (stream 3) primitives (total)");
1435 add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(0), 1, 1,
1436 "SO_NUM_PRIMS_WRITTEN (Stream 0)",
1437 "N stream-out (stream 0) primitives (written)");
1438 add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(1), 1, 1,
1439 "SO_NUM_PRIMS_WRITTEN (Stream 1)",
1440 "N stream-out (stream 1) primitives (written)");
1441 add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(2), 1, 1,
1442 "SO_NUM_PRIMS_WRITTEN (Stream 2)",
1443 "N stream-out (stream 2) primitives (written)");
1444 add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(3), 1, 1,
1445 "SO_NUM_PRIMS_WRITTEN (Stream 3)",
1446 "N stream-out (stream 3) primitives (written)");
1447 }
1448
1449 add_basic_stat_reg(query, HS_INVOCATION_COUNT,
1450 "N TCS shader invocations");
1451 add_basic_stat_reg(query, DS_INVOCATION_COUNT,
1452 "N TES shader invocations");
1453
1454 add_basic_stat_reg(query, GS_INVOCATION_COUNT,
1455 "N geometry shader invocations");
1456 add_basic_stat_reg(query, GS_PRIMITIVES_COUNT,
1457 "N geometry shader primitives emitted");
1458
1459 add_basic_stat_reg(query, CL_INVOCATION_COUNT,
1460 "N primitives entering clipping");
1461 add_basic_stat_reg(query, CL_PRIMITIVES_COUNT,
1462 "N primitives leaving clipping");
1463
1464 if (brw->is_haswell || brw->gen == 8)
1465 add_stat_reg(query, PS_INVOCATION_COUNT, 1, 4,
1466 "N fragment shader invocations",
1467 "N fragment shader invocations");
1468 else
1469 add_basic_stat_reg(query, PS_INVOCATION_COUNT,
1470 "N fragment shader invocations");
1471
1472 add_basic_stat_reg(query, PS_DEPTH_COUNT, "N z-pass fragments");
1473
1474 if (brw->gen >= 7)
1475 add_basic_stat_reg(query, CS_INVOCATION_COUNT,
1476 "N compute shader invocations");
1477
1478 query->data_size = sizeof(uint64_t) * query->n_counters;
1479 }
1480
1481 static bool
1482 read_file_uint64(const char *file, uint64_t *val)
1483 {
1484 char buf[32];
1485 int fd, n;
1486
1487 fd = open(file, 0);
1488 if (fd < 0)
1489 return false;
1490 n = read(fd, buf, sizeof (buf) - 1);
1491 close(fd);
1492 if (n < 0)
1493 return false;
1494
1495 buf[n] = '\0';
1496 *val = strtoull(buf, NULL, 0);
1497
1498 return true;
1499 }
1500
1501 static void
1502 enumerate_sysfs_metrics(struct brw_context *brw, const char *sysfs_dev_dir)
1503 {
1504 char buf[256];
1505 DIR *metricsdir = NULL;
1506 struct dirent *metric_entry;
1507 int len;
1508
1509 len = snprintf(buf, sizeof(buf), "%s/metrics", sysfs_dev_dir);
1510 if (len < 0 || len >= sizeof(buf)) {
1511 DBG("Failed to concatenate path to sysfs metrics/ directory\n");
1512 return;
1513 }
1514
1515 metricsdir = opendir(buf);
1516 if (!metricsdir) {
1517 DBG("Failed to open %s: %m\n", buf);
1518 return;
1519 }
1520
1521 while ((metric_entry = readdir(metricsdir))) {
1522 struct hash_entry *entry;
1523
1524 if ((metric_entry->d_type != DT_DIR &&
1525 metric_entry->d_type != DT_LNK) ||
1526 metric_entry->d_name[0] == '.')
1527 continue;
1528
1529 DBG("metric set: %s\n", metric_entry->d_name);
1530 entry = _mesa_hash_table_search(brw->perfquery.oa_metrics_table,
1531 metric_entry->d_name);
1532 if (entry) {
1533 struct brw_perf_query_info *query;
1534 uint64_t id;
1535
1536 len = snprintf(buf, sizeof(buf), "%s/metrics/%s/id",
1537 sysfs_dev_dir, metric_entry->d_name);
1538 if (len < 0 || len >= sizeof(buf)) {
1539 DBG("Failed to concatenate path to sysfs metric id file\n");
1540 continue;
1541 }
1542
1543 if (!read_file_uint64(buf, &id)) {
1544 DBG("Failed to read metric set id from %s: %m", buf);
1545 continue;
1546 }
1547
1548 query = append_query_info(brw);
1549 *query = *(struct brw_perf_query_info *)entry->data;
1550 query->oa_metrics_set_id = id;
1551
1552 DBG("metric set known by mesa: id = %" PRIu64"\n",
1553 query->oa_metrics_set_id);
1554 } else
1555 DBG("metric set not known by mesa (skipping)\n");
1556 }
1557
1558 closedir(metricsdir);
1559 }
1560
1561 static bool
1562 read_sysfs_drm_device_file_uint64(struct brw_context *brw,
1563 const char *sysfs_dev_dir,
1564 const char *file,
1565 uint64_t *value)
1566 {
1567 char buf[512];
1568 int len;
1569
1570 len = snprintf(buf, sizeof(buf), "%s/%s", sysfs_dev_dir, file);
1571 if (len < 0 || len >= sizeof(buf)) {
1572 DBG("Failed to concatenate sys filename to read u64 from\n");
1573 return false;
1574 }
1575
1576 return read_file_uint64(buf, value);
1577 }
1578
1579 static bool
1580 init_oa_sys_vars(struct brw_context *brw, const char *sysfs_dev_dir)
1581 {
1582 uint64_t min_freq_mhz = 0, max_freq_mhz = 0;
1583
1584 if (!read_sysfs_drm_device_file_uint64(brw, sysfs_dev_dir,
1585 "gt_min_freq_mhz",
1586 &min_freq_mhz))
1587 return false;
1588
1589 if (!read_sysfs_drm_device_file_uint64(brw, sysfs_dev_dir,
1590 "gt_max_freq_mhz",
1591 &max_freq_mhz))
1592 return false;
1593
1594 brw->perfquery.sys_vars.gt_min_freq = min_freq_mhz * 1000000;
1595 brw->perfquery.sys_vars.gt_max_freq = max_freq_mhz * 1000000;
1596
1597 if (brw->is_haswell) {
1598 const struct gen_device_info *info = &brw->screen->devinfo;
1599
1600 brw->perfquery.sys_vars.timestamp_frequency = 12500000;
1601
1602 if (info->gt == 1) {
1603 brw->perfquery.sys_vars.n_eus = 10;
1604 brw->perfquery.sys_vars.n_eu_slices = 1;
1605 brw->perfquery.sys_vars.subslice_mask = 0x1;
1606 } else if (info->gt == 2) {
1607 brw->perfquery.sys_vars.n_eus = 20;
1608 brw->perfquery.sys_vars.n_eu_slices = 1;
1609 brw->perfquery.sys_vars.subslice_mask = 0x3;
1610 } else if (info->gt == 3) {
1611 brw->perfquery.sys_vars.n_eus = 40;
1612 brw->perfquery.sys_vars.n_eu_slices = 2;
1613 brw->perfquery.sys_vars.subslice_mask = 0xf;
1614 } else
1615 unreachable("not reached");
1616
1617 return true;
1618 } else
1619 return false;
1620 }
1621
1622 static bool
1623 get_sysfs_dev_dir(struct brw_context *brw,
1624 char *path_buf,
1625 int path_buf_len)
1626 {
1627 __DRIscreen *screen = brw->screen->driScrnPriv;
1628 struct stat sb;
1629 int min, maj;
1630 DIR *drmdir;
1631 struct dirent *drm_entry;
1632 int len;
1633
1634 assert(path_buf);
1635 assert(path_buf_len);
1636 path_buf[0] = '\0';
1637
1638 if (fstat(screen->fd, &sb)) {
1639 DBG("Failed to stat DRM fd\n");
1640 return false;
1641 }
1642
1643 maj = major(sb.st_rdev);
1644 min = minor(sb.st_rdev);
1645
1646 if (!S_ISCHR(sb.st_mode)) {
1647 DBG("DRM fd is not a character device as expected\n");
1648 return false;
1649 }
1650
1651 len = snprintf(path_buf, path_buf_len,
1652 "/sys/dev/char/%d:%d/device/drm", maj, min);
1653 if (len < 0 || len >= path_buf_len) {
1654 DBG("Failed to concatenate sysfs path to drm device\n");
1655 return false;
1656 }
1657
1658 drmdir = opendir(path_buf);
1659 if (!drmdir) {
1660 DBG("Failed to open %s: %m\n", path_buf);
1661 return false;
1662 }
1663
1664 while ((drm_entry = readdir(drmdir))) {
1665 if ((drm_entry->d_type == DT_DIR ||
1666 drm_entry->d_type == DT_LNK) &&
1667 strncmp(drm_entry->d_name, "card", 4) == 0)
1668 {
1669 len = snprintf(path_buf, path_buf_len,
1670 "/sys/dev/char/%d:%d/device/drm/%s",
1671 maj, min, drm_entry->d_name);
1672 closedir(drmdir);
1673 if (len < 0 || len >= path_buf_len)
1674 return false;
1675 else
1676 return true;
1677 }
1678 }
1679
1680 closedir(drmdir);
1681
1682 DBG("Failed to find cardX directory under /sys/dev/char/%d:%d/device/drm\n",
1683 maj, min);
1684
1685 return false;
1686 }
1687
1688 static unsigned
1689 brw_init_perf_query_info(struct gl_context *ctx)
1690 {
1691 struct brw_context *brw = brw_context(ctx);
1692 struct stat sb;
1693 char sysfs_dev_dir[128];
1694
1695 if (brw->perfquery.n_queries)
1696 return brw->perfquery.n_queries;
1697
1698 init_pipeline_statistic_query_registers(brw);
1699
1700 /* The existence of this sysctl parameter implies the kernel supports
1701 * the i915 perf interface.
1702 */
1703 if (brw->is_haswell &&
1704 stat("/proc/sys/dev/i915/perf_stream_paranoid", &sb) == 0 &&
1705 get_sysfs_dev_dir(brw, sysfs_dev_dir, sizeof(sysfs_dev_dir)) &&
1706 init_oa_sys_vars(brw, sysfs_dev_dir))
1707 {
1708 brw->perfquery.oa_metrics_table =
1709 _mesa_hash_table_create(NULL, _mesa_key_hash_string,
1710 _mesa_key_string_equal);
1711
1712 /* Index all the metric sets mesa knows about before looking to
1713 * see what the kernel is advertising.
1714 */
1715 brw_oa_register_queries_hsw(brw);
1716
1717 enumerate_sysfs_metrics(brw, sysfs_dev_dir);
1718 }
1719
1720 brw->perfquery.unaccumulated =
1721 ralloc_array(brw, struct brw_perf_query_object *, 2);
1722 brw->perfquery.unaccumulated_elements = 0;
1723 brw->perfquery.unaccumulated_array_size = 2;
1724
1725 exec_list_make_empty(&brw->perfquery.sample_buffers);
1726 exec_list_make_empty(&brw->perfquery.free_sample_buffers);
1727
1728 /* It's convenient to guarantee that this linked list of sample
1729 * buffers is never empty so we add an empty head so when we
1730 * Begin an OA query we can always take a reference on a buffer
1731 * in this list.
1732 */
1733 struct brw_oa_sample_buf *buf = get_free_sample_buf(brw);
1734 exec_list_push_head(&brw->perfquery.sample_buffers, &buf->link);
1735
1736 brw->perfquery.oa_stream_fd = -1;
1737
1738 brw->perfquery.next_query_start_report_id = 1000;
1739
1740 return brw->perfquery.n_queries;
1741 }
1742
1743 void
1744 brw_init_performance_queries(struct brw_context *brw)
1745 {
1746 struct gl_context *ctx = &brw->ctx;
1747
1748 ctx->Driver.InitPerfQueryInfo = brw_init_perf_query_info;
1749 ctx->Driver.GetPerfQueryInfo = brw_get_perf_query_info;
1750 ctx->Driver.GetPerfCounterInfo = brw_get_perf_counter_info;
1751 ctx->Driver.NewPerfQueryObject = brw_new_perf_query_object;
1752 ctx->Driver.DeletePerfQuery = brw_delete_perf_query;
1753 ctx->Driver.BeginPerfQuery = brw_begin_perf_query;
1754 ctx->Driver.EndPerfQuery = brw_end_perf_query;
1755 ctx->Driver.WaitPerfQuery = brw_wait_perf_query;
1756 ctx->Driver.IsPerfQueryReady = brw_is_perf_query_ready;
1757 ctx->Driver.GetPerfQueryData = brw_get_perf_query_data;
1758 }