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