intel/perf: move close_perf into perf
[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
44 /* put before sys/types.h to silence glibc warnings */
45 #ifdef MAJOR_IN_MKDEV
46 #include <sys/mkdev.h>
47 #endif
48 #ifdef MAJOR_IN_SYSMACROS
49 #include <sys/sysmacros.h>
50 #endif
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <sys/mman.h>
55 #include <sys/ioctl.h>
56
57 #include <xf86drm.h>
58 #include "drm-uapi/i915_drm.h"
59
60 #include "main/hash.h"
61 #include "main/macros.h"
62 #include "main/mtypes.h"
63 #include "main/performance_query.h"
64
65 #include "util/bitset.h"
66 #include "util/ralloc.h"
67 #include "util/hash_table.h"
68 #include "util/list.h"
69 #include "util/u_math.h"
70
71 #include "brw_context.h"
72 #include "brw_defines.h"
73 #include "intel_batchbuffer.h"
74
75 #include "perf/gen_perf.h"
76 #include "perf/gen_perf_mdapi.h"
77
78 #define FILE_DEBUG_FLAG DEBUG_PERFMON
79
80 #define OAREPORT_REASON_MASK 0x3f
81 #define OAREPORT_REASON_SHIFT 19
82 #define OAREPORT_REASON_TIMER (1<<0)
83 #define OAREPORT_REASON_TRIGGER1 (1<<1)
84 #define OAREPORT_REASON_TRIGGER2 (1<<2)
85 #define OAREPORT_REASON_CTX_SWITCH (1<<3)
86 #define OAREPORT_REASON_GO_TRANSITION (1<<4)
87
88 struct brw_perf_query_object {
89 struct gl_perf_query_object base;
90 struct gen_perf_query_object *query;
91 };
92
93 /** Downcasting convenience macro. */
94 static inline struct brw_perf_query_object *
95 brw_perf_query(struct gl_perf_query_object *o)
96 {
97 return (struct brw_perf_query_object *) o;
98 }
99
100 #define MI_RPC_BO_SIZE 4096
101 #define MI_RPC_BO_END_OFFSET_BYTES (MI_RPC_BO_SIZE / 2)
102 #define MI_FREQ_START_OFFSET_BYTES (3072)
103 #define MI_FREQ_END_OFFSET_BYTES (3076)
104
105 /******************************************************************************/
106
107 static bool
108 brw_is_perf_query_ready(struct gl_context *ctx,
109 struct gl_perf_query_object *o);
110
111 static void
112 dump_perf_query_callback(GLuint id, void *query_void, void *brw_void)
113 {
114 struct gl_context *ctx = brw_void;
115 struct gl_perf_query_object *o = query_void;
116 struct brw_perf_query_object * brw_query = brw_perf_query(o);
117 struct gen_perf_query_object *obj = brw_query->query;
118
119 switch (obj->queryinfo->kind) {
120 case GEN_PERF_QUERY_TYPE_OA:
121 case GEN_PERF_QUERY_TYPE_RAW:
122 DBG("%4d: %-6s %-8s BO: %-4s OA data: %-10s %-15s\n",
123 id,
124 o->Used ? "Dirty," : "New,",
125 o->Active ? "Active," : (o->Ready ? "Ready," : "Pending,"),
126 obj->oa.bo ? "yes," : "no,",
127 brw_is_perf_query_ready(ctx, o) ? "ready," : "not ready,",
128 obj->oa.results_accumulated ? "accumulated" : "not accumulated");
129 break;
130 case GEN_PERF_QUERY_TYPE_PIPELINE:
131 DBG("%4d: %-6s %-8s BO: %-4s\n",
132 id,
133 o->Used ? "Dirty," : "New,",
134 o->Active ? "Active," : (o->Ready ? "Ready," : "Pending,"),
135 obj->pipeline_stats.bo ? "yes" : "no");
136 break;
137 default:
138 unreachable("Unknown query type");
139 break;
140 }
141 }
142
143 static void
144 dump_perf_queries(struct brw_context *brw)
145 {
146 struct gl_context *ctx = &brw->ctx;
147 DBG("Queries: (Open queries = %d, OA users = %d)\n",
148 brw->perf_ctx.n_active_oa_queries, brw->perf_ctx.n_oa_users);
149 _mesa_HashWalk(ctx->PerfQuery.Objects, dump_perf_query_callback, brw);
150 }
151
152 /**
153 * Driver hook for glGetPerfQueryInfoINTEL().
154 */
155 static void
156 brw_get_perf_query_info(struct gl_context *ctx,
157 unsigned query_index,
158 const char **name,
159 GLuint *data_size,
160 GLuint *n_counters,
161 GLuint *n_active)
162 {
163 struct brw_context *brw = brw_context(ctx);
164 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
165 const struct gen_perf_query_info *query =
166 &perf_ctx->perf->queries[query_index];
167
168 *name = query->name;
169 *data_size = query->data_size;
170 *n_counters = query->n_counters;
171
172 switch (query->kind) {
173 case GEN_PERF_QUERY_TYPE_OA:
174 case GEN_PERF_QUERY_TYPE_RAW:
175 *n_active = perf_ctx->n_active_oa_queries;
176 break;
177
178 case GEN_PERF_QUERY_TYPE_PIPELINE:
179 *n_active = perf_ctx->n_active_pipeline_stats_queries;
180 break;
181
182 default:
183 unreachable("Unknown query type");
184 break;
185 }
186 }
187
188 static GLuint
189 gen_counter_type_enum_to_gl_type(enum gen_perf_counter_type type)
190 {
191 switch (type) {
192 case GEN_PERF_COUNTER_TYPE_EVENT: return GL_PERFQUERY_COUNTER_EVENT_INTEL;
193 case GEN_PERF_COUNTER_TYPE_DURATION_NORM: return GL_PERFQUERY_COUNTER_DURATION_NORM_INTEL;
194 case GEN_PERF_COUNTER_TYPE_DURATION_RAW: return GL_PERFQUERY_COUNTER_DURATION_RAW_INTEL;
195 case GEN_PERF_COUNTER_TYPE_THROUGHPUT: return GL_PERFQUERY_COUNTER_THROUGHPUT_INTEL;
196 case GEN_PERF_COUNTER_TYPE_RAW: return GL_PERFQUERY_COUNTER_RAW_INTEL;
197 case GEN_PERF_COUNTER_TYPE_TIMESTAMP: return GL_PERFQUERY_COUNTER_TIMESTAMP_INTEL;
198 default:
199 unreachable("Unknown counter type");
200 }
201 }
202
203 static GLuint
204 gen_counter_data_type_to_gl_type(enum gen_perf_counter_data_type type)
205 {
206 switch (type) {
207 case GEN_PERF_COUNTER_DATA_TYPE_BOOL32: return GL_PERFQUERY_COUNTER_DATA_BOOL32_INTEL;
208 case GEN_PERF_COUNTER_DATA_TYPE_UINT32: return GL_PERFQUERY_COUNTER_DATA_UINT32_INTEL;
209 case GEN_PERF_COUNTER_DATA_TYPE_UINT64: return GL_PERFQUERY_COUNTER_DATA_UINT64_INTEL;
210 case GEN_PERF_COUNTER_DATA_TYPE_FLOAT: return GL_PERFQUERY_COUNTER_DATA_FLOAT_INTEL;
211 case GEN_PERF_COUNTER_DATA_TYPE_DOUBLE: return GL_PERFQUERY_COUNTER_DATA_DOUBLE_INTEL;
212 default:
213 unreachable("Unknown counter data type");
214 }
215 }
216
217 /**
218 * Driver hook for glGetPerfCounterInfoINTEL().
219 */
220 static void
221 brw_get_perf_counter_info(struct gl_context *ctx,
222 unsigned query_index,
223 unsigned counter_index,
224 const char **name,
225 const char **desc,
226 GLuint *offset,
227 GLuint *data_size,
228 GLuint *type_enum,
229 GLuint *data_type_enum,
230 GLuint64 *raw_max)
231 {
232 struct brw_context *brw = brw_context(ctx);
233 const struct gen_perf_query_info *query =
234 &brw->perf_ctx.perf->queries[query_index];
235 const struct gen_perf_query_counter *counter =
236 &query->counters[counter_index];
237
238 *name = counter->name;
239 *desc = counter->desc;
240 *offset = counter->offset;
241 *data_size = gen_perf_query_counter_get_size(counter);
242 *type_enum = gen_counter_type_enum_to_gl_type(counter->type);
243 *data_type_enum = gen_counter_data_type_to_gl_type(counter->data_type);
244 *raw_max = counter->raw_max;
245 }
246
247 /**
248 * Add a query to the global list of "unaccumulated queries."
249 *
250 * Queries are tracked here until all the associated OA reports have
251 * been accumulated via accumulate_oa_reports() after the end
252 * MI_REPORT_PERF_COUNT has landed in query->oa.bo.
253 */
254 static void
255 add_to_unaccumulated_query_list(struct brw_context *brw,
256 struct gen_perf_query_object *obj)
257 {
258 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
259 if (perf_ctx->unaccumulated_elements >=
260 perf_ctx->unaccumulated_array_size)
261 {
262 perf_ctx->unaccumulated_array_size *= 1.5;
263 perf_ctx->unaccumulated =
264 reralloc(brw, perf_ctx->unaccumulated,
265 struct gen_perf_query_object *,
266 perf_ctx->unaccumulated_array_size);
267 }
268
269 perf_ctx->unaccumulated[perf_ctx->unaccumulated_elements++] = obj;
270 }
271
272 /**
273 * Remove a query from the global list of unaccumulated queries once
274 * after successfully accumulating the OA reports associated with the
275 * query in accumulate_oa_reports() or when discarding unwanted query
276 * results.
277 */
278 static void
279 drop_from_unaccumulated_query_list(struct brw_context *brw,
280 struct gen_perf_query_object *obj)
281 {
282 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
283 for (int i = 0; i < perf_ctx->unaccumulated_elements; i++) {
284 if (perf_ctx->unaccumulated[i] == obj) {
285 int last_elt = --perf_ctx->unaccumulated_elements;
286
287 if (i == last_elt)
288 perf_ctx->unaccumulated[i] = NULL;
289 else {
290 perf_ctx->unaccumulated[i] =
291 perf_ctx->unaccumulated[last_elt];
292 }
293
294 break;
295 }
296 }
297
298 /* Drop our samples_head reference so that associated periodic
299 * sample data buffers can potentially be reaped if they aren't
300 * referenced by any other queries...
301 */
302
303 struct oa_sample_buf *buf =
304 exec_node_data(struct oa_sample_buf, obj->oa.samples_head, link);
305
306 assert(buf->refcount > 0);
307 buf->refcount--;
308
309 obj->oa.samples_head = NULL;
310
311 gen_perf_reap_old_sample_buffers(&brw->perf_ctx);
312 }
313
314 static bool
315 inc_n_oa_users(struct brw_context *brw)
316 {
317 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
318 if (perf_ctx->n_oa_users == 0 &&
319 drmIoctl(perf_ctx->oa_stream_fd,
320 I915_PERF_IOCTL_ENABLE, 0) < 0)
321 {
322 return false;
323 }
324 ++perf_ctx->n_oa_users;
325
326 return true;
327 }
328
329 static void
330 dec_n_oa_users(struct brw_context *brw)
331 {
332 /* Disabling the i915 perf stream will effectively disable the OA
333 * counters. Note it's important to be sure there are no outstanding
334 * MI_RPC commands at this point since they could stall the CS
335 * indefinitely once OACONTROL is disabled.
336 */
337 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
338 --perf_ctx->n_oa_users;
339 if (perf_ctx->n_oa_users == 0 &&
340 drmIoctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_DISABLE, 0) < 0)
341 {
342 DBG("WARNING: Error disabling i915 perf stream: %m\n");
343 }
344 }
345
346 /* In general if we see anything spurious while accumulating results,
347 * we don't try and continue accumulating the current query, hoping
348 * for the best, we scrap anything outstanding, and then hope for the
349 * best with new queries.
350 */
351 static void
352 discard_all_queries(struct brw_context *brw)
353 {
354 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
355 while (perf_ctx->unaccumulated_elements) {
356 struct gen_perf_query_object *obj = perf_ctx->unaccumulated[0];
357
358 obj->oa.results_accumulated = true;
359 drop_from_unaccumulated_query_list(brw, perf_ctx->unaccumulated[0]);
360
361 dec_n_oa_users(brw);
362 }
363 }
364
365 enum OaReadStatus {
366 OA_READ_STATUS_ERROR,
367 OA_READ_STATUS_UNFINISHED,
368 OA_READ_STATUS_FINISHED,
369 };
370
371 static enum OaReadStatus
372 read_oa_samples_until(struct brw_context *brw,
373 uint32_t start_timestamp,
374 uint32_t end_timestamp)
375 {
376 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
377 struct exec_node *tail_node =
378 exec_list_get_tail(&perf_ctx->sample_buffers);
379 struct oa_sample_buf *tail_buf =
380 exec_node_data(struct oa_sample_buf, tail_node, link);
381 uint32_t last_timestamp = tail_buf->last_timestamp;
382
383 while (1) {
384 struct oa_sample_buf *buf = gen_perf_get_free_sample_buf(perf_ctx);
385 uint32_t offset;
386 int len;
387
388 while ((len = read(perf_ctx->oa_stream_fd, buf->buf,
389 sizeof(buf->buf))) < 0 && errno == EINTR)
390 ;
391
392 if (len <= 0) {
393 exec_list_push_tail(&perf_ctx->free_sample_buffers, &buf->link);
394
395 if (len < 0) {
396 if (errno == EAGAIN)
397 return ((last_timestamp - start_timestamp) >=
398 (end_timestamp - start_timestamp)) ?
399 OA_READ_STATUS_FINISHED :
400 OA_READ_STATUS_UNFINISHED;
401 else {
402 DBG("Error reading i915 perf samples: %m\n");
403 }
404 } else
405 DBG("Spurious EOF reading i915 perf samples\n");
406
407 return OA_READ_STATUS_ERROR;
408 }
409
410 buf->len = len;
411 exec_list_push_tail(&perf_ctx->sample_buffers, &buf->link);
412
413 /* Go through the reports and update the last timestamp. */
414 offset = 0;
415 while (offset < buf->len) {
416 const struct drm_i915_perf_record_header *header =
417 (const struct drm_i915_perf_record_header *) &buf->buf[offset];
418 uint32_t *report = (uint32_t *) (header + 1);
419
420 if (header->type == DRM_I915_PERF_RECORD_SAMPLE)
421 last_timestamp = report[1];
422
423 offset += header->size;
424 }
425
426 buf->last_timestamp = last_timestamp;
427 }
428
429 unreachable("not reached");
430 return OA_READ_STATUS_ERROR;
431 }
432
433 /**
434 * Try to read all the reports until either the delimiting timestamp
435 * or an error arises.
436 */
437 static bool
438 read_oa_samples_for_query(struct brw_context *brw,
439 struct gen_perf_query_object *obj)
440 {
441 uint32_t *start;
442 uint32_t *last;
443 uint32_t *end;
444
445 /* We need the MI_REPORT_PERF_COUNT to land before we can start
446 * accumulate. */
447 assert(!brw_batch_references(&brw->batch, obj->oa.bo) &&
448 !brw_bo_busy(obj->oa.bo));
449
450 /* Map the BO once here and let accumulate_oa_reports() unmap
451 * it. */
452 if (obj->oa.map == NULL)
453 obj->oa.map = brw_bo_map(brw, obj->oa.bo, MAP_READ);
454
455 start = last = obj->oa.map;
456 end = obj->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
457
458 if (start[0] != obj->oa.begin_report_id) {
459 DBG("Spurious start report id=%"PRIu32"\n", start[0]);
460 return true;
461 }
462 if (end[0] != (obj->oa.begin_report_id + 1)) {
463 DBG("Spurious end report id=%"PRIu32"\n", end[0]);
464 return true;
465 }
466
467 /* Read the reports until the end timestamp. */
468 switch (read_oa_samples_until(brw, start[1], end[1])) {
469 case OA_READ_STATUS_ERROR:
470 /* Fallthrough and let accumulate_oa_reports() deal with the
471 * error. */
472 case OA_READ_STATUS_FINISHED:
473 return true;
474 case OA_READ_STATUS_UNFINISHED:
475 return false;
476 }
477
478 unreachable("invalid read status");
479 return false;
480 }
481
482 /**
483 * Accumulate raw OA counter values based on deltas between pairs of
484 * OA reports.
485 *
486 * Accumulation starts from the first report captured via
487 * MI_REPORT_PERF_COUNT (MI_RPC) by brw_begin_perf_query() until the
488 * last MI_RPC report requested by brw_end_perf_query(). Between these
489 * two reports there may also some number of periodically sampled OA
490 * reports collected via the i915 perf interface - depending on the
491 * duration of the query.
492 *
493 * These periodic snapshots help to ensure we handle counter overflow
494 * correctly by being frequent enough to ensure we don't miss multiple
495 * overflows of a counter between snapshots. For Gen8+ the i915 perf
496 * snapshots provide the extra context-switch reports that let us
497 * subtract out the progress of counters associated with other
498 * contexts running on the system.
499 */
500 static void
501 accumulate_oa_reports(struct brw_context *brw,
502 struct brw_perf_query_object *brw_query)
503 {
504 const struct gen_device_info *devinfo = &brw->screen->devinfo;
505 struct gen_perf_query_object *obj = brw_query->query;
506 uint32_t *start;
507 uint32_t *last;
508 uint32_t *end;
509 struct exec_node *first_samples_node;
510 bool in_ctx = true;
511 int out_duration = 0;
512
513 assert(brw_query->base.Ready);
514 assert(obj->oa.map != NULL);
515
516 start = last = obj->oa.map;
517 end = obj->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
518
519 if (start[0] != obj->oa.begin_report_id) {
520 DBG("Spurious start report id=%"PRIu32"\n", start[0]);
521 goto error;
522 }
523 if (end[0] != (obj->oa.begin_report_id + 1)) {
524 DBG("Spurious end report id=%"PRIu32"\n", end[0]);
525 goto error;
526 }
527
528 /* See if we have any periodic reports to accumulate too... */
529
530 /* N.B. The oa.samples_head was set when the query began and
531 * pointed to the tail of the perf_ctx->sample_buffers list at
532 * the time the query started. Since the buffer existed before the
533 * first MI_REPORT_PERF_COUNT command was emitted we therefore know
534 * that no data in this particular node's buffer can possibly be
535 * associated with the query - so skip ahead one...
536 */
537 first_samples_node = obj->oa.samples_head->next;
538
539 foreach_list_typed_from(struct oa_sample_buf, buf, link,
540 &brw->perf_ctx.sample_buffers,
541 first_samples_node)
542 {
543 int offset = 0;
544
545 while (offset < buf->len) {
546 const struct drm_i915_perf_record_header *header =
547 (const struct drm_i915_perf_record_header *)(buf->buf + offset);
548
549 assert(header->size != 0);
550 assert(header->size <= buf->len);
551
552 offset += header->size;
553
554 switch (header->type) {
555 case DRM_I915_PERF_RECORD_SAMPLE: {
556 uint32_t *report = (uint32_t *)(header + 1);
557 bool add = true;
558
559 /* Ignore reports that come before the start marker.
560 * (Note: takes care to allow overflow of 32bit timestamps)
561 */
562 if (gen_device_info_timebase_scale(devinfo,
563 report[1] - start[1]) > 5000000000) {
564 continue;
565 }
566
567 /* Ignore reports that come after the end marker.
568 * (Note: takes care to allow overflow of 32bit timestamps)
569 */
570 if (gen_device_info_timebase_scale(devinfo,
571 report[1] - end[1]) <= 5000000000) {
572 goto end;
573 }
574
575 /* For Gen8+ since the counters continue while other
576 * contexts are running we need to discount any unrelated
577 * deltas. The hardware automatically generates a report
578 * on context switch which gives us a new reference point
579 * to continuing adding deltas from.
580 *
581 * For Haswell we can rely on the HW to stop the progress
582 * of OA counters while any other context is acctive.
583 */
584 if (devinfo->gen >= 8) {
585 if (in_ctx && report[2] != obj->oa.result.hw_id) {
586 DBG("i915 perf: Switch AWAY (observed by ID change)\n");
587 in_ctx = false;
588 out_duration = 0;
589 } else if (in_ctx == false && report[2] == obj->oa.result.hw_id) {
590 DBG("i915 perf: Switch TO\n");
591 in_ctx = true;
592
593 /* From experimentation in IGT, we found that the OA unit
594 * might label some report as "idle" (using an invalid
595 * context ID), right after a report for a given context.
596 * Deltas generated by those reports actually belong to the
597 * previous context, even though they're not labelled as
598 * such.
599 *
600 * We didn't *really* Switch AWAY in the case that we e.g.
601 * saw a single periodic report while idle...
602 */
603 if (out_duration >= 1)
604 add = false;
605 } else if (in_ctx) {
606 assert(report[2] == obj->oa.result.hw_id);
607 DBG("i915 perf: Continuation IN\n");
608 } else {
609 assert(report[2] != obj->oa.result.hw_id);
610 DBG("i915 perf: Continuation OUT\n");
611 add = false;
612 out_duration++;
613 }
614 }
615
616 if (add) {
617 gen_perf_query_result_accumulate(&obj->oa.result, obj->queryinfo,
618 last, report);
619 }
620
621 last = report;
622
623 break;
624 }
625
626 case DRM_I915_PERF_RECORD_OA_BUFFER_LOST:
627 DBG("i915 perf: OA error: all reports lost\n");
628 goto error;
629 case DRM_I915_PERF_RECORD_OA_REPORT_LOST:
630 DBG("i915 perf: OA report lost\n");
631 break;
632 }
633 }
634 }
635
636 end:
637
638 gen_perf_query_result_accumulate(&obj->oa.result, obj->queryinfo,
639 last, end);
640
641 DBG("Marking %d accumulated - results gathered\n", brw_query->base.Id);
642
643 obj->oa.results_accumulated = true;
644 drop_from_unaccumulated_query_list(brw, obj);
645 dec_n_oa_users(brw);
646
647 return;
648
649 error:
650
651 discard_all_queries(brw);
652 }
653
654 /******************************************************************************/
655
656 static bool
657 open_i915_perf_oa_stream(struct brw_context *brw,
658 int metrics_set_id,
659 int report_format,
660 int period_exponent,
661 int drm_fd,
662 uint32_t ctx_id)
663 {
664 uint64_t properties[] = {
665 /* Single context sampling */
666 DRM_I915_PERF_PROP_CTX_HANDLE, ctx_id,
667
668 /* Include OA reports in samples */
669 DRM_I915_PERF_PROP_SAMPLE_OA, true,
670
671 /* OA unit configuration */
672 DRM_I915_PERF_PROP_OA_METRICS_SET, metrics_set_id,
673 DRM_I915_PERF_PROP_OA_FORMAT, report_format,
674 DRM_I915_PERF_PROP_OA_EXPONENT, period_exponent,
675 };
676 struct drm_i915_perf_open_param param = {
677 .flags = I915_PERF_FLAG_FD_CLOEXEC |
678 I915_PERF_FLAG_FD_NONBLOCK |
679 I915_PERF_FLAG_DISABLED,
680 .num_properties = ARRAY_SIZE(properties) / 2,
681 .properties_ptr = (uintptr_t) properties,
682 };
683 int fd = drmIoctl(drm_fd, DRM_IOCTL_I915_PERF_OPEN, &param);
684 if (fd == -1) {
685 DBG("Error opening i915 perf OA stream: %m\n");
686 return false;
687 }
688
689 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
690 perf_ctx->oa_stream_fd = fd;
691
692 perf_ctx->current_oa_metrics_set_id = metrics_set_id;
693 perf_ctx->current_oa_format = report_format;
694
695 return true;
696 }
697
698 static void
699 capture_frequency_stat_register(struct brw_context *brw,
700 struct brw_bo *bo,
701 uint32_t bo_offset)
702 {
703 const struct gen_device_info *devinfo = &brw->screen->devinfo;
704
705 if (devinfo->gen >= 7 && devinfo->gen <= 8 &&
706 !devinfo->is_baytrail && !devinfo->is_cherryview) {
707 brw_store_register_mem32(brw, bo, GEN7_RPSTAT1, bo_offset);
708 } else if (devinfo->gen >= 9) {
709 brw_store_register_mem32(brw, bo, GEN9_RPSTAT0, bo_offset);
710 }
711 }
712
713 /**
714 * Driver hook for glBeginPerfQueryINTEL().
715 */
716 static bool
717 brw_begin_perf_query(struct gl_context *ctx,
718 struct gl_perf_query_object *o)
719 {
720 struct brw_context *brw = brw_context(ctx);
721 struct brw_perf_query_object *brw_query = brw_perf_query(o);
722 struct gen_perf_query_object *obj = brw_query->query;
723 const struct gen_perf_query_info *query = obj->queryinfo;
724 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
725 struct gen_perf_config *perf_cfg = perf_ctx->perf;
726
727 /* We can assume the frontend hides mistaken attempts to Begin a
728 * query object multiple times before its End. Similarly if an
729 * application reuses a query object before results have arrived
730 * the frontend will wait for prior results so we don't need
731 * to support abandoning in-flight results.
732 */
733 assert(!o->Active);
734 assert(!o->Used || o->Ready); /* no in-flight query to worry about */
735
736 DBG("Begin(%d)\n", o->Id);
737
738 /* XXX: We have to consider that the command parser unit that parses batch
739 * buffer commands and is used to capture begin/end counter snapshots isn't
740 * implicitly synchronized with what's currently running across other GPU
741 * units (such as the EUs running shaders) that the performance counters are
742 * associated with.
743 *
744 * The intention of performance queries is to measure the work associated
745 * with commands between the begin/end delimiters and so for that to be the
746 * case we need to explicitly synchronize the parsing of commands to capture
747 * Begin/End counter snapshots with what's running across other parts of the
748 * GPU.
749 *
750 * When the command parser reaches a Begin marker it effectively needs to
751 * drain everything currently running on the GPU until the hardware is idle
752 * before capturing the first snapshot of counters - otherwise the results
753 * would also be measuring the effects of earlier commands.
754 *
755 * When the command parser reaches an End marker it needs to stall until
756 * everything currently running on the GPU has finished before capturing the
757 * end snapshot - otherwise the results won't be a complete representation
758 * of the work.
759 *
760 * Theoretically there could be opportunities to minimize how much of the
761 * GPU pipeline is drained, or that we stall for, when we know what specific
762 * units the performance counters being queried relate to but we don't
763 * currently attempt to be clever here.
764 *
765 * Note: with our current simple approach here then for back-to-back queries
766 * we will redundantly emit duplicate commands to synchronize the command
767 * streamer with the rest of the GPU pipeline, but we assume that in HW the
768 * second synchronization is effectively a NOOP.
769 *
770 * N.B. The final results are based on deltas of counters between (inside)
771 * Begin/End markers so even though the total wall clock time of the
772 * workload is stretched by larger pipeline bubbles the bubbles themselves
773 * are generally invisible to the query results. Whether that's a good or a
774 * bad thing depends on the use case. For a lower real-time impact while
775 * capturing metrics then periodic sampling may be a better choice than
776 * INTEL_performance_query.
777 *
778 *
779 * This is our Begin synchronization point to drain current work on the
780 * GPU before we capture our first counter snapshot...
781 */
782 perf_cfg->vtbl.emit_mi_flush(brw);
783
784 switch (query->kind) {
785 case GEN_PERF_QUERY_TYPE_OA:
786 case GEN_PERF_QUERY_TYPE_RAW: {
787
788 /* Opening an i915 perf stream implies exclusive access to the OA unit
789 * which will generate counter reports for a specific counter set with a
790 * specific layout/format so we can't begin any OA based queries that
791 * require a different counter set or format unless we get an opportunity
792 * to close the stream and open a new one...
793 */
794 uint64_t metric_id = gen_perf_query_get_metric_id(perf_ctx->perf, query);
795
796 if (perf_ctx->oa_stream_fd != -1 &&
797 perf_ctx->current_oa_metrics_set_id != metric_id) {
798
799 if (perf_ctx->n_oa_users != 0) {
800 DBG("WARNING: Begin(%d) failed already using perf config=%i/%"PRIu64"\n",
801 o->Id, perf_ctx->current_oa_metrics_set_id, metric_id);
802 return false;
803 } else
804 gen_perf_close(perf_ctx, query);
805 }
806
807 /* If the OA counters aren't already on, enable them. */
808
809 if (perf_ctx->oa_stream_fd == -1) {
810 __DRIscreen *screen = brw->screen->driScrnPriv;
811 const struct gen_device_info *devinfo = &brw->screen->devinfo;
812
813 /* The period_exponent gives a sampling period as follows:
814 * sample_period = timestamp_period * 2^(period_exponent + 1)
815 *
816 * The timestamps increments every 80ns (HSW), ~52ns (GEN9LP) or
817 * ~83ns (GEN8/9).
818 *
819 * The counter overflow period is derived from the EuActive counter
820 * which reads a counter that increments by the number of clock
821 * cycles multiplied by the number of EUs. It can be calculated as:
822 *
823 * 2^(number of bits in A counter) / (n_eus * max_gen_freq * 2)
824 *
825 * (E.g. 40 EUs @ 1GHz = ~53ms)
826 *
827 * We select a sampling period inferior to that overflow period to
828 * ensure we cannot see more than 1 counter overflow, otherwise we
829 * could loose information.
830 */
831
832 int a_counter_in_bits = 32;
833 if (devinfo->gen >= 8)
834 a_counter_in_bits = 40;
835
836 uint64_t overflow_period = pow(2, a_counter_in_bits) /
837 (perf_cfg->sys_vars.n_eus *
838 /* drop 1GHz freq to have units in nanoseconds */
839 2);
840
841 DBG("A counter overflow period: %"PRIu64"ns, %"PRIu64"ms (n_eus=%"PRIu64")\n",
842 overflow_period, overflow_period / 1000000ul, perf_cfg->sys_vars.n_eus);
843
844 int period_exponent = 0;
845 uint64_t prev_sample_period, next_sample_period;
846 for (int e = 0; e < 30; e++) {
847 prev_sample_period = 1000000000ull * pow(2, e + 1) / devinfo->timestamp_frequency;
848 next_sample_period = 1000000000ull * pow(2, e + 2) / devinfo->timestamp_frequency;
849
850 /* Take the previous sampling period, lower than the overflow
851 * period.
852 */
853 if (prev_sample_period < overflow_period &&
854 next_sample_period > overflow_period)
855 period_exponent = e + 1;
856 }
857
858 if (period_exponent == 0) {
859 DBG("WARNING: enable to find a sampling exponent\n");
860 return false;
861 }
862
863 DBG("OA sampling exponent: %i ~= %"PRIu64"ms\n", period_exponent,
864 prev_sample_period / 1000000ul);
865
866 if (!open_i915_perf_oa_stream(brw,
867 metric_id,
868 query->oa_format,
869 period_exponent,
870 screen->fd, /* drm fd */
871 brw->hw_ctx))
872 return false;
873 } else {
874 assert(perf_ctx->current_oa_metrics_set_id == metric_id &&
875 perf_ctx->current_oa_format == query->oa_format);
876 }
877
878 if (!inc_n_oa_users(brw)) {
879 DBG("WARNING: Error enabling i915 perf stream: %m\n");
880 return false;
881 }
882
883 if (obj->oa.bo) {
884 perf_cfg->vtbl.bo_unreference(obj->oa.bo);
885 obj->oa.bo = NULL;
886 }
887
888 obj->oa.bo =
889 brw->perf_ctx.perf->vtbl.bo_alloc(brw->bufmgr,
890 "perf. query OA MI_RPC bo",
891 MI_RPC_BO_SIZE);
892 #ifdef DEBUG
893 /* Pre-filling the BO helps debug whether writes landed. */
894 void *map = brw_bo_map(brw, obj->oa.bo, MAP_WRITE);
895 memset(map, 0x80, MI_RPC_BO_SIZE);
896 brw_bo_unmap(obj->oa.bo);
897 #endif
898
899 obj->oa.begin_report_id = perf_ctx->next_query_start_report_id;
900 perf_ctx->next_query_start_report_id += 2;
901
902 /* We flush the batchbuffer here to minimize the chances that MI_RPC
903 * delimiting commands end up in different batchbuffers. If that's the
904 * case, the measurement will include the time it takes for the kernel
905 * scheduler to load a new request into the hardware. This is manifested in
906 * tools like frameretrace by spikes in the "GPU Core Clocks" counter.
907 */
908 perf_cfg->vtbl.batchbuffer_flush(brw, __FILE__, __LINE__);
909
910 /* Take a starting OA counter snapshot. */
911 perf_cfg->vtbl.emit_mi_report_perf_count(brw, obj->oa.bo, 0,
912 obj->oa.begin_report_id);
913 perf_cfg->vtbl.capture_frequency_stat_register(brw, obj->oa.bo,
914 MI_FREQ_START_OFFSET_BYTES);
915
916 ++perf_ctx->n_active_oa_queries;
917
918 /* No already-buffered samples can possibly be associated with this query
919 * so create a marker within the list of sample buffers enabling us to
920 * easily ignore earlier samples when processing this query after
921 * completion.
922 */
923 assert(!exec_list_is_empty(&perf_ctx->sample_buffers));
924 obj->oa.samples_head = exec_list_get_tail(&perf_ctx->sample_buffers);
925
926 struct oa_sample_buf *buf =
927 exec_node_data(struct oa_sample_buf, obj->oa.samples_head, link);
928
929 /* This reference will ensure that future/following sample
930 * buffers (that may relate to this query) can't be freed until
931 * this drops to zero.
932 */
933 buf->refcount++;
934
935 gen_perf_query_result_clear(&obj->oa.result);
936 obj->oa.results_accumulated = false;
937
938 add_to_unaccumulated_query_list(brw, obj);
939 break;
940 }
941
942 case GEN_PERF_QUERY_TYPE_PIPELINE:
943 if (obj->pipeline_stats.bo) {
944 brw->perf_ctx.perf->vtbl.bo_unreference(obj->pipeline_stats.bo);
945 obj->pipeline_stats.bo = NULL;
946 }
947
948 obj->pipeline_stats.bo =
949 brw->perf_ctx.perf->vtbl.bo_alloc(brw->bufmgr,
950 "perf. query pipeline stats bo",
951 STATS_BO_SIZE);
952
953 /* Take starting snapshots. */
954 gen_perf_snapshot_statistics_registers(brw, perf_cfg, obj, 0);
955
956 ++perf_ctx->n_active_pipeline_stats_queries;
957 break;
958
959 default:
960 unreachable("Unknown query type");
961 break;
962 }
963
964 if (INTEL_DEBUG & DEBUG_PERFMON)
965 dump_perf_queries(brw);
966
967 return true;
968 }
969
970 /**
971 * Driver hook for glEndPerfQueryINTEL().
972 */
973 static void
974 brw_end_perf_query(struct gl_context *ctx,
975 struct gl_perf_query_object *o)
976 {
977 struct brw_context *brw = brw_context(ctx);
978 struct brw_perf_query_object *brw_query = brw_perf_query(o);
979 struct gen_perf_query_object *obj = brw_query->query;
980 struct gen_perf_config *perf_cfg = brw->perf_ctx.perf;
981 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
982
983 DBG("End(%d)\n", o->Id);
984
985 /* Ensure that the work associated with the queried commands will have
986 * finished before taking our query end counter readings.
987 *
988 * For more details see comment in brw_begin_perf_query for
989 * corresponding flush.
990 */
991 perf_cfg->vtbl.emit_mi_flush(brw);
992
993 switch (obj->queryinfo->kind) {
994 case GEN_PERF_QUERY_TYPE_OA:
995 case GEN_PERF_QUERY_TYPE_RAW:
996
997 /* NB: It's possible that the query will have already been marked
998 * as 'accumulated' if an error was seen while reading samples
999 * from perf. In this case we mustn't try and emit a closing
1000 * MI_RPC command in case the OA unit has already been disabled
1001 */
1002 if (!obj->oa.results_accumulated) {
1003 /* Take an ending OA counter snapshot. */
1004 perf_cfg->vtbl.capture_frequency_stat_register(brw, obj->oa.bo,
1005 MI_FREQ_END_OFFSET_BYTES);
1006 brw->vtbl.emit_mi_report_perf_count(brw, obj->oa.bo,
1007 MI_RPC_BO_END_OFFSET_BYTES,
1008 obj->oa.begin_report_id + 1);
1009 }
1010
1011 --perf_ctx->n_active_oa_queries;
1012
1013 /* NB: even though the query has now ended, it can't be accumulated
1014 * until the end MI_REPORT_PERF_COUNT snapshot has been written
1015 * to query->oa.bo
1016 */
1017 break;
1018
1019 case GEN_PERF_QUERY_TYPE_PIPELINE:
1020 gen_perf_snapshot_statistics_registers(brw, perf_cfg, obj,
1021 STATS_BO_END_OFFSET_BYTES);
1022 --perf_ctx->n_active_pipeline_stats_queries;
1023 break;
1024
1025 default:
1026 unreachable("Unknown query type");
1027 break;
1028 }
1029 }
1030
1031 static void
1032 brw_wait_perf_query(struct gl_context *ctx, struct gl_perf_query_object *o)
1033 {
1034 struct brw_context *brw = brw_context(ctx);
1035 struct brw_perf_query_object *brw_query = brw_perf_query(o);
1036 struct gen_perf_query_object *obj = brw_query->query;
1037 struct brw_bo *bo = NULL;
1038 struct gen_perf_config *perf_cfg = brw->perf_ctx.perf;
1039
1040 assert(!o->Ready);
1041
1042 switch (obj->queryinfo->kind) {
1043 case GEN_PERF_QUERY_TYPE_OA:
1044 case GEN_PERF_QUERY_TYPE_RAW:
1045 bo = obj->oa.bo;
1046 break;
1047
1048 case GEN_PERF_QUERY_TYPE_PIPELINE:
1049 bo = obj->pipeline_stats.bo;
1050 break;
1051
1052 default:
1053 unreachable("Unknown query type");
1054 break;
1055 }
1056
1057 if (bo == NULL)
1058 return;
1059
1060 /* If the current batch references our results bo then we need to
1061 * flush first...
1062 */
1063 if (brw_batch_references(&brw->batch, bo))
1064 perf_cfg->vtbl.batchbuffer_flush(brw, __FILE__, __LINE__);
1065
1066 brw_bo_wait_rendering(bo);
1067
1068 /* Due to a race condition between the OA unit signaling report
1069 * availability and the report actually being written into memory,
1070 * we need to wait for all the reports to come in before we can
1071 * read them.
1072 */
1073 if (obj->queryinfo->kind == GEN_PERF_QUERY_TYPE_OA ||
1074 obj->queryinfo->kind == GEN_PERF_QUERY_TYPE_RAW) {
1075 while (!read_oa_samples_for_query(brw, obj))
1076 ;
1077 }
1078 }
1079
1080 static bool
1081 brw_is_perf_query_ready(struct gl_context *ctx,
1082 struct gl_perf_query_object *o)
1083 {
1084 struct brw_context *brw = brw_context(ctx);
1085 struct brw_perf_query_object *brw_query = brw_perf_query(o);
1086 struct gen_perf_query_object *obj = brw_query->query;
1087
1088 if (o->Ready)
1089 return true;
1090
1091 switch (obj->queryinfo->kind) {
1092 case GEN_PERF_QUERY_TYPE_OA:
1093 case GEN_PERF_QUERY_TYPE_RAW:
1094 return (obj->oa.results_accumulated ||
1095 (obj->oa.bo &&
1096 !brw_batch_references(&brw->batch, obj->oa.bo) &&
1097 !brw_bo_busy(obj->oa.bo) &&
1098 read_oa_samples_for_query(brw, obj)));
1099 case GEN_PERF_QUERY_TYPE_PIPELINE:
1100 return (obj->pipeline_stats.bo &&
1101 !brw_batch_references(&brw->batch, obj->pipeline_stats.bo) &&
1102 !brw_bo_busy(obj->pipeline_stats.bo));
1103
1104 default:
1105 unreachable("Unknown query type");
1106 break;
1107 }
1108
1109 return false;
1110 }
1111
1112 static void
1113 read_slice_unslice_frequencies(struct brw_context *brw,
1114 struct gen_perf_query_object *obj)
1115 {
1116 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1117 uint32_t *begin_report = obj->oa.map, *end_report = obj->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
1118
1119 gen_perf_query_result_read_frequencies(&obj->oa.result,
1120 devinfo, begin_report, end_report);
1121 }
1122
1123 static void
1124 read_gt_frequency(struct brw_context *brw,
1125 struct gen_perf_query_object *obj)
1126 {
1127 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1128 uint32_t start = *((uint32_t *)(obj->oa.map + MI_FREQ_START_OFFSET_BYTES)),
1129 end = *((uint32_t *)(obj->oa.map + MI_FREQ_END_OFFSET_BYTES));
1130
1131 switch (devinfo->gen) {
1132 case 7:
1133 case 8:
1134 obj->oa.gt_frequency[0] = GET_FIELD(start, GEN7_RPSTAT1_CURR_GT_FREQ) * 50ULL;
1135 obj->oa.gt_frequency[1] = GET_FIELD(end, GEN7_RPSTAT1_CURR_GT_FREQ) * 50ULL;
1136 break;
1137 case 9:
1138 case 10:
1139 case 11:
1140 obj->oa.gt_frequency[0] = GET_FIELD(start, GEN9_RPSTAT0_CURR_GT_FREQ) * 50ULL / 3ULL;
1141 obj->oa.gt_frequency[1] = GET_FIELD(end, GEN9_RPSTAT0_CURR_GT_FREQ) * 50ULL / 3ULL;
1142 break;
1143 default:
1144 unreachable("unexpected gen");
1145 }
1146
1147 /* Put the numbers into Hz. */
1148 obj->oa.gt_frequency[0] *= 1000000ULL;
1149 obj->oa.gt_frequency[1] *= 1000000ULL;
1150 }
1151
1152 static int
1153 get_oa_counter_data(struct brw_context *brw,
1154 struct gen_perf_query_object *obj,
1155 size_t data_size,
1156 uint8_t *data)
1157 {
1158 struct gen_perf_config *perf = brw->perf_ctx.perf;
1159 const struct gen_perf_query_info *query = obj->queryinfo;
1160 int n_counters = query->n_counters;
1161 int written = 0;
1162
1163 for (int i = 0; i < n_counters; i++) {
1164 const struct gen_perf_query_counter *counter = &query->counters[i];
1165 uint64_t *out_uint64;
1166 float *out_float;
1167 size_t counter_size = gen_perf_query_counter_get_size(counter);
1168
1169 if (counter_size) {
1170 switch (counter->data_type) {
1171 case GEN_PERF_COUNTER_DATA_TYPE_UINT64:
1172 out_uint64 = (uint64_t *)(data + counter->offset);
1173 *out_uint64 =
1174 counter->oa_counter_read_uint64(perf, query,
1175 obj->oa.result.accumulator);
1176 break;
1177 case GEN_PERF_COUNTER_DATA_TYPE_FLOAT:
1178 out_float = (float *)(data + counter->offset);
1179 *out_float =
1180 counter->oa_counter_read_float(perf, query,
1181 obj->oa.result.accumulator);
1182 break;
1183 default:
1184 /* So far we aren't using uint32, double or bool32... */
1185 unreachable("unexpected counter data type");
1186 }
1187 written = counter->offset + counter_size;
1188 }
1189 }
1190
1191 return written;
1192 }
1193
1194 static int
1195 get_pipeline_stats_data(struct brw_context *brw,
1196 struct gen_perf_query_object *obj,
1197 size_t data_size,
1198 uint8_t *data)
1199
1200 {
1201 const struct gen_perf_query_info *query = obj->queryinfo;
1202 int n_counters = obj->queryinfo->n_counters;
1203 uint8_t *p = data;
1204
1205 uint64_t *start = brw_bo_map(brw, obj->pipeline_stats.bo, MAP_READ);
1206 uint64_t *end = start + (STATS_BO_END_OFFSET_BYTES / sizeof(uint64_t));
1207
1208 for (int i = 0; i < n_counters; i++) {
1209 const struct gen_perf_query_counter *counter = &query->counters[i];
1210 uint64_t value = end[i] - start[i];
1211
1212 if (counter->pipeline_stat.numerator !=
1213 counter->pipeline_stat.denominator) {
1214 value *= counter->pipeline_stat.numerator;
1215 value /= counter->pipeline_stat.denominator;
1216 }
1217
1218 *((uint64_t *)p) = value;
1219 p += 8;
1220 }
1221
1222 brw_bo_unmap(obj->pipeline_stats.bo);
1223
1224 return p - data;
1225 }
1226
1227 /**
1228 * Driver hook for glGetPerfQueryDataINTEL().
1229 */
1230 static void
1231 brw_get_perf_query_data(struct gl_context *ctx,
1232 struct gl_perf_query_object *o,
1233 GLsizei data_size,
1234 GLuint *data,
1235 GLuint *bytes_written)
1236 {
1237 struct brw_context *brw = brw_context(ctx);
1238 struct brw_perf_query_object *brw_query = brw_perf_query(o);
1239 struct gen_perf_query_object *obj = brw_query->query;
1240 int written = 0;
1241
1242 assert(brw_is_perf_query_ready(ctx, o));
1243
1244 DBG("GetData(%d)\n", o->Id);
1245
1246 if (INTEL_DEBUG & DEBUG_PERFMON)
1247 dump_perf_queries(brw);
1248
1249 /* We expect that the frontend only calls this hook when it knows
1250 * that results are available.
1251 */
1252 assert(o->Ready);
1253
1254 switch (obj->queryinfo->kind) {
1255 case GEN_PERF_QUERY_TYPE_OA:
1256 case GEN_PERF_QUERY_TYPE_RAW:
1257 if (!obj->oa.results_accumulated) {
1258 read_gt_frequency(brw, obj);
1259 read_slice_unslice_frequencies(brw, obj);
1260 accumulate_oa_reports(brw, brw_query);
1261 assert(obj->oa.results_accumulated);
1262
1263 brw_bo_unmap(obj->oa.bo);
1264 obj->oa.map = NULL;
1265 }
1266 if (obj->queryinfo->kind == GEN_PERF_QUERY_TYPE_OA) {
1267 written = get_oa_counter_data(brw, obj, data_size, (uint8_t *)data);
1268 } else {
1269 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1270
1271 written = gen_perf_query_result_write_mdapi((uint8_t *)data, data_size,
1272 devinfo, &obj->oa.result,
1273 obj->oa.gt_frequency[0],
1274 obj->oa.gt_frequency[1]);
1275 }
1276 break;
1277
1278 case GEN_PERF_QUERY_TYPE_PIPELINE:
1279 written = get_pipeline_stats_data(brw, obj, data_size, (uint8_t *)data);
1280 break;
1281
1282 default:
1283 unreachable("Unknown query type");
1284 break;
1285 }
1286
1287 if (bytes_written)
1288 *bytes_written = written;
1289 }
1290
1291 static struct gl_perf_query_object *
1292 brw_new_perf_query_object(struct gl_context *ctx, unsigned query_index)
1293 {
1294 struct brw_context *brw = brw_context(ctx);
1295 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
1296 const struct gen_perf_query_info *queryinfo =
1297 &perf_ctx->perf->queries[query_index];
1298 struct gen_perf_query_object *obj =
1299 calloc(1, sizeof(struct gen_perf_query_object));
1300
1301 if (!obj)
1302 return NULL;
1303
1304 obj->queryinfo = queryinfo;
1305
1306 perf_ctx->n_query_instances++;
1307
1308 struct brw_perf_query_object *brw_query = calloc(1, sizeof(struct brw_perf_query_object));
1309 if (unlikely(!brw_query))
1310 return NULL;
1311 brw_query->query = obj;
1312 return &brw_query->base;
1313 }
1314
1315 /**
1316 * Driver hook for glDeletePerfQueryINTEL().
1317 */
1318 static void
1319 brw_delete_perf_query(struct gl_context *ctx,
1320 struct gl_perf_query_object *o)
1321 {
1322 struct brw_context *brw = brw_context(ctx);
1323 struct gen_perf_config *perf_cfg = brw->perf_ctx.perf;
1324 struct brw_perf_query_object *brw_query = brw_perf_query(o);
1325 struct gen_perf_query_object *obj = brw_query->query;
1326 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
1327
1328 /* We can assume that the frontend waits for a query to complete
1329 * before ever calling into here, so we don't have to worry about
1330 * deleting an in-flight query object.
1331 */
1332 assert(!o->Active);
1333 assert(!o->Used || o->Ready);
1334
1335 DBG("Delete(%d)\n", o->Id);
1336
1337 switch (obj->queryinfo->kind) {
1338 case GEN_PERF_QUERY_TYPE_OA:
1339 case GEN_PERF_QUERY_TYPE_RAW:
1340 if (obj->oa.bo) {
1341 if (!obj->oa.results_accumulated) {
1342 drop_from_unaccumulated_query_list(brw, obj);
1343 dec_n_oa_users(brw);
1344 }
1345
1346 perf_cfg->vtbl.bo_unreference(obj->oa.bo);
1347 obj->oa.bo = NULL;
1348 }
1349
1350 obj->oa.results_accumulated = false;
1351 break;
1352
1353 case GEN_PERF_QUERY_TYPE_PIPELINE:
1354 if (obj->pipeline_stats.bo) {
1355 perf_cfg->vtbl.bo_unreference(obj->pipeline_stats.bo);
1356 obj->pipeline_stats.bo = NULL;
1357 }
1358 break;
1359
1360 default:
1361 unreachable("Unknown query type");
1362 break;
1363 }
1364
1365 /* As an indication that the INTEL_performance_query extension is no
1366 * longer in use, it's a good time to free our cache of sample
1367 * buffers and close any current i915-perf stream.
1368 */
1369 if (--perf_ctx->n_query_instances == 0) {
1370 gen_perf_free_sample_bufs(perf_ctx);
1371 gen_perf_close(perf_ctx, obj->queryinfo);
1372 }
1373
1374 free(obj);
1375 free(brw_query);
1376 }
1377
1378 /******************************************************************************/
1379
1380 static void
1381 init_pipeline_statistic_query_registers(struct brw_context *brw)
1382 {
1383 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1384 struct gen_perf_config *perf = brw->perf_ctx.perf;
1385 struct gen_perf_query_info *query =
1386 gen_perf_query_append_query_info(perf, MAX_STAT_COUNTERS);
1387
1388 query->kind = GEN_PERF_QUERY_TYPE_PIPELINE;
1389 query->name = "Pipeline Statistics Registers";
1390
1391 gen_perf_query_info_add_basic_stat_reg(query, IA_VERTICES_COUNT,
1392 "N vertices submitted");
1393 gen_perf_query_info_add_basic_stat_reg(query, IA_PRIMITIVES_COUNT,
1394 "N primitives submitted");
1395 gen_perf_query_info_add_basic_stat_reg(query, VS_INVOCATION_COUNT,
1396 "N vertex shader invocations");
1397
1398 if (devinfo->gen == 6) {
1399 gen_perf_query_info_add_stat_reg(query, GEN6_SO_PRIM_STORAGE_NEEDED, 1, 1,
1400 "SO_PRIM_STORAGE_NEEDED",
1401 "N geometry shader stream-out primitives (total)");
1402 gen_perf_query_info_add_stat_reg(query, GEN6_SO_NUM_PRIMS_WRITTEN, 1, 1,
1403 "SO_NUM_PRIMS_WRITTEN",
1404 "N geometry shader stream-out primitives (written)");
1405 } else {
1406 gen_perf_query_info_add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(0), 1, 1,
1407 "SO_PRIM_STORAGE_NEEDED (Stream 0)",
1408 "N stream-out (stream 0) primitives (total)");
1409 gen_perf_query_info_add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(1), 1, 1,
1410 "SO_PRIM_STORAGE_NEEDED (Stream 1)",
1411 "N stream-out (stream 1) primitives (total)");
1412 gen_perf_query_info_add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(2), 1, 1,
1413 "SO_PRIM_STORAGE_NEEDED (Stream 2)",
1414 "N stream-out (stream 2) primitives (total)");
1415 gen_perf_query_info_add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(3), 1, 1,
1416 "SO_PRIM_STORAGE_NEEDED (Stream 3)",
1417 "N stream-out (stream 3) primitives (total)");
1418 gen_perf_query_info_add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(0), 1, 1,
1419 "SO_NUM_PRIMS_WRITTEN (Stream 0)",
1420 "N stream-out (stream 0) primitives (written)");
1421 gen_perf_query_info_add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(1), 1, 1,
1422 "SO_NUM_PRIMS_WRITTEN (Stream 1)",
1423 "N stream-out (stream 1) primitives (written)");
1424 gen_perf_query_info_add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(2), 1, 1,
1425 "SO_NUM_PRIMS_WRITTEN (Stream 2)",
1426 "N stream-out (stream 2) primitives (written)");
1427 gen_perf_query_info_add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(3), 1, 1,
1428 "SO_NUM_PRIMS_WRITTEN (Stream 3)",
1429 "N stream-out (stream 3) primitives (written)");
1430 }
1431
1432 gen_perf_query_info_add_basic_stat_reg(query, HS_INVOCATION_COUNT,
1433 "N TCS shader invocations");
1434 gen_perf_query_info_add_basic_stat_reg(query, DS_INVOCATION_COUNT,
1435 "N TES shader invocations");
1436
1437 gen_perf_query_info_add_basic_stat_reg(query, GS_INVOCATION_COUNT,
1438 "N geometry shader invocations");
1439 gen_perf_query_info_add_basic_stat_reg(query, GS_PRIMITIVES_COUNT,
1440 "N geometry shader primitives emitted");
1441
1442 gen_perf_query_info_add_basic_stat_reg(query, CL_INVOCATION_COUNT,
1443 "N primitives entering clipping");
1444 gen_perf_query_info_add_basic_stat_reg(query, CL_PRIMITIVES_COUNT,
1445 "N primitives leaving clipping");
1446
1447 if (devinfo->is_haswell || devinfo->gen == 8) {
1448 gen_perf_query_info_add_stat_reg(query, PS_INVOCATION_COUNT, 1, 4,
1449 "N fragment shader invocations",
1450 "N fragment shader invocations");
1451 } else {
1452 gen_perf_query_info_add_basic_stat_reg(query, PS_INVOCATION_COUNT,
1453 "N fragment shader invocations");
1454 }
1455
1456 gen_perf_query_info_add_basic_stat_reg(query, PS_DEPTH_COUNT,
1457 "N z-pass fragments");
1458
1459 if (devinfo->gen >= 7) {
1460 gen_perf_query_info_add_basic_stat_reg(query, CS_INVOCATION_COUNT,
1461 "N compute shader invocations");
1462 }
1463
1464 query->data_size = sizeof(uint64_t) * query->n_counters;
1465 }
1466
1467 /* gen_device_info will have incorrect default topology values for unsupported kernels.
1468 * verify kernel support to ensure OA metrics are accurate.
1469 */
1470 static bool
1471 oa_metrics_kernel_support(int fd, const struct gen_device_info *devinfo)
1472 {
1473 if (devinfo->gen >= 10) {
1474 /* topology uAPI required for CNL+ (kernel 4.17+) make a call to the api
1475 * to verify support
1476 */
1477 struct drm_i915_query_item item = {
1478 .query_id = DRM_I915_QUERY_TOPOLOGY_INFO,
1479 };
1480 struct drm_i915_query query = {
1481 .num_items = 1,
1482 .items_ptr = (uintptr_t) &item,
1483 };
1484
1485 /* kernel 4.17+ supports the query */
1486 return drmIoctl(fd, DRM_IOCTL_I915_QUERY, &query) == 0;
1487 }
1488
1489 if (devinfo->gen >= 8) {
1490 /* 4.13+ api required for gen8 - gen9 */
1491 int mask;
1492 struct drm_i915_getparam gp = {
1493 .param = I915_PARAM_SLICE_MASK,
1494 .value = &mask,
1495 };
1496 /* kernel 4.13+ supports this parameter */
1497 return drmIoctl(fd, DRM_IOCTL_I915_GETPARAM, &gp) == 0;
1498 }
1499
1500 if (devinfo->gen == 7)
1501 /* default topology values are correct for HSW */
1502 return true;
1503
1504 /* oa not supported before gen 7*/
1505 return false;
1506 }
1507
1508 static void *
1509 brw_oa_bo_alloc(void *bufmgr, const char *name, uint64_t size)
1510 {
1511 return brw_bo_alloc(bufmgr, name, size, BRW_MEMZONE_OTHER);
1512 }
1513
1514 static void
1515 brw_oa_emit_mi_report_perf_count(void *c,
1516 void *bo,
1517 uint32_t offset_in_bytes,
1518 uint32_t report_id)
1519 {
1520 struct brw_context *ctx = c;
1521 ctx->vtbl.emit_mi_report_perf_count(ctx,
1522 bo,
1523 offset_in_bytes,
1524 report_id);
1525 }
1526
1527 typedef void (*bo_unreference_t)(void *);
1528 typedef void (* emit_mi_report_t)(void *, void *, uint32_t, uint32_t);
1529 typedef void (*emit_mi_flush_t)(void *);
1530
1531 static void
1532 brw_oa_batchbuffer_flush(void *c, const char *file, int line)
1533 {
1534 struct brw_context *ctx = c;
1535 _intel_batchbuffer_flush_fence(ctx, -1, NULL, file, line);
1536 }
1537
1538 typedef void (*capture_frequency_stat_register_t)(void *, void *, uint32_t );
1539 typedef void (*store_register_mem64_t)(void *ctx, void *bo,
1540 uint32_t reg, uint32_t offset);
1541
1542 static unsigned
1543 brw_init_perf_query_info(struct gl_context *ctx)
1544 {
1545 struct brw_context *brw = brw_context(ctx);
1546 const struct gen_device_info *devinfo = &brw->screen->devinfo;
1547 __DRIscreen *screen = brw->screen->driScrnPriv;
1548
1549 struct gen_perf_context *perf_ctx = &brw->perf_ctx;
1550 if (perf_ctx->perf)
1551 return perf_ctx->perf->n_queries;
1552
1553 perf_ctx->perf = gen_perf_new(brw);
1554 struct gen_perf_config *perf_cfg = perf_ctx->perf;
1555
1556 perf_cfg->vtbl.bo_alloc = brw_oa_bo_alloc;
1557 perf_cfg->vtbl.bo_unreference = (bo_unreference_t)brw_bo_unreference;
1558 perf_cfg->vtbl.emit_mi_flush = (emit_mi_flush_t)brw_emit_mi_flush;
1559 perf_cfg->vtbl.emit_mi_report_perf_count =
1560 (emit_mi_report_t)brw_oa_emit_mi_report_perf_count;
1561 perf_cfg->vtbl.batchbuffer_flush = brw_oa_batchbuffer_flush;
1562 perf_cfg->vtbl.capture_frequency_stat_register =
1563 (capture_frequency_stat_register_t) capture_frequency_stat_register;
1564 perf_cfg->vtbl.store_register_mem64 =
1565 (store_register_mem64_t) brw_store_register_mem64;
1566
1567 init_pipeline_statistic_query_registers(brw);
1568 gen_perf_query_register_mdapi_statistic_query(&brw->screen->devinfo,
1569 brw->perf_ctx.perf);
1570
1571 if ((oa_metrics_kernel_support(screen->fd, devinfo)) &&
1572 (gen_perf_load_oa_metrics(perf_cfg, screen->fd, devinfo)))
1573 gen_perf_query_register_mdapi_oa_query(devinfo, perf_cfg);
1574
1575 perf_ctx->unaccumulated =
1576 ralloc_array(brw, struct gen_perf_query_object *, 2);
1577 perf_ctx->unaccumulated_elements = 0;
1578 perf_ctx->unaccumulated_array_size = 2;
1579
1580 exec_list_make_empty(&perf_ctx->sample_buffers);
1581 exec_list_make_empty(&perf_ctx->free_sample_buffers);
1582
1583 /* It's convenient to guarantee that this linked list of sample
1584 * buffers is never empty so we add an empty head so when we
1585 * Begin an OA query we can always take a reference on a buffer
1586 * in this list.
1587 */
1588 struct oa_sample_buf *buf = gen_perf_get_free_sample_buf(&brw->perf_ctx);
1589 exec_list_push_head(&perf_ctx->sample_buffers, &buf->link);
1590
1591 perf_ctx->oa_stream_fd = -1;
1592
1593 perf_ctx->next_query_start_report_id = 1000;
1594
1595 return perf_cfg->n_queries;
1596 }
1597
1598 void
1599 brw_init_performance_queries(struct brw_context *brw)
1600 {
1601 struct gl_context *ctx = &brw->ctx;
1602
1603 ctx->Driver.InitPerfQueryInfo = brw_init_perf_query_info;
1604 ctx->Driver.GetPerfQueryInfo = brw_get_perf_query_info;
1605 ctx->Driver.GetPerfCounterInfo = brw_get_perf_counter_info;
1606 ctx->Driver.NewPerfQueryObject = brw_new_perf_query_object;
1607 ctx->Driver.DeletePerfQuery = brw_delete_perf_query;
1608 ctx->Driver.BeginPerfQuery = brw_begin_perf_query;
1609 ctx->Driver.EndPerfQuery = brw_end_perf_query;
1610 ctx->Driver.WaitPerfQuery = brw_wait_perf_query;
1611 ctx->Driver.IsPerfQueryReady = brw_is_perf_query_ready;
1612 ctx->Driver.GetPerfQueryData = brw_get_perf_query_data;
1613 }