Path: blob/21.2-virgl/src/intel/perf/intel_perf_query.c
4547 views
/*1* Copyright © 2019 Intel Corporation2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20* IN THE SOFTWARE.21*/2223#include <unistd.h>24#include <poll.h>2526#include "common/intel_gem.h"2728#include "dev/intel_debug.h"29#include "dev/intel_device_info.h"3031#include "perf/intel_perf.h"32#include "perf/intel_perf_mdapi.h"33#include "perf/intel_perf_private.h"34#include "perf/intel_perf_query.h"35#include "perf/intel_perf_regs.h"3637#include "drm-uapi/i915_drm.h"3839#include "util/compiler.h"40#include "util/u_math.h"4142#define FILE_DEBUG_FLAG DEBUG_PERFMON4344#define MI_RPC_BO_SIZE (4096)45#define MI_FREQ_OFFSET_BYTES (256)46#define MI_PERF_COUNTERS_OFFSET_BYTES (260)4748#define ALIGN(x, y) (((x) + (y)-1) & ~((y)-1))4950/* Align to 64bytes, requirement for OA report write address. */51#define TOTAL_QUERY_DATA_SIZE \52ALIGN(256 /* OA report */ + \534 /* freq register */ + \548 + 8 /* perf counter 1 & 2 */, \5564)565758static uint32_t field_offset(bool end, uint32_t offset)59{60return (end ? TOTAL_QUERY_DATA_SIZE : 0) + offset;61}6263#define MAP_READ (1 << 0)64#define MAP_WRITE (1 << 1)6566/**67* Periodic OA samples are read() into these buffer structures via the68* i915 perf kernel interface and appended to the69* perf_ctx->sample_buffers linked list. When we process the70* results of an OA metrics query we need to consider all the periodic71* samples between the Begin and End MI_REPORT_PERF_COUNT command72* markers.73*74* 'Periodic' is a simplification as there are other automatic reports75* written by the hardware also buffered here.76*77* Considering three queries, A, B and C:78*79* Time ---->80* ________________A_________________81* | |82* | ________B_________ _____C___________83* | | | | | |84*85* And an illustration of sample buffers read over this time frame:86* [HEAD ][ ][ ][ ][ ][ ][ ][ ][TAIL ]87*88* These nodes may hold samples for query A:89* [ ][ ][ A ][ A ][ A ][ A ][ A ][ ][ ]90*91* These nodes may hold samples for query B:92* [ ][ ][ B ][ B ][ B ][ ][ ][ ][ ]93*94* These nodes may hold samples for query C:95* [ ][ ][ ][ ][ ][ C ][ C ][ C ][ ]96*97* The illustration assumes we have an even distribution of periodic98* samples so all nodes have the same size plotted against time:99*100* Note, to simplify code, the list is never empty.101*102* With overlapping queries we can see that periodic OA reports may103* relate to multiple queries and care needs to be take to keep104* track of sample buffers until there are no queries that might105* depend on their contents.106*107* We use a node ref counting system where a reference ensures that a108* node and all following nodes can't be freed/recycled until the109* reference drops to zero.110*111* E.g. with a ref of one here:112* [ 0 ][ 0 ][ 1 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ]113*114* These nodes could be freed or recycled ("reaped"):115* [ 0 ][ 0 ]116*117* These must be preserved until the leading ref drops to zero:118* [ 1 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ][ 0 ]119*120* When a query starts we take a reference on the current tail of121* the list, knowing that no already-buffered samples can possibly122* relate to the newly-started query. A pointer to this node is123* also saved in the query object's ->oa.samples_head.124*125* E.g. starting query A while there are two nodes in .sample_buffers:126* ________________A________127* |128*129* [ 0 ][ 1 ]130* ^_______ Add a reference and store pointer to node in131* A->oa.samples_head132*133* Moving forward to when the B query starts with no new buffer nodes:134* (for reference, i915 perf reads() are only done when queries finish)135* ________________A_______136* | ________B___137* | |138*139* [ 0 ][ 2 ]140* ^_______ Add a reference and store pointer to141* node in B->oa.samples_head142*143* Once a query is finished, after an OA query has become 'Ready',144* once the End OA report has landed and after we we have processed145* all the intermediate periodic samples then we drop the146* ->oa.samples_head reference we took at the start.147*148* So when the B query has finished we have:149* ________________A________150* | ______B___________151* | | |152* [ 0 ][ 1 ][ 0 ][ 0 ][ 0 ]153* ^_______ Drop B->oa.samples_head reference154*155* We still can't free these due to the A->oa.samples_head ref:156* [ 1 ][ 0 ][ 0 ][ 0 ]157*158* When the A query finishes: (note there's a new ref for C's samples_head)159* ________________A_________________160* | |161* | _____C_________162* | | |163* [ 0 ][ 0 ][ 0 ][ 0 ][ 1 ][ 0 ][ 0 ]164* ^_______ Drop A->oa.samples_head reference165*166* And we can now reap these nodes up to the C->oa.samples_head:167* [ X ][ X ][ X ][ X ]168* keeping -> [ 1 ][ 0 ][ 0 ]169*170* We reap old sample buffers each time we finish processing an OA171* query by iterating the sample_buffers list from the head until we172* find a referenced node and stop.173*174* Reaped buffers move to a perfquery.free_sample_buffers list and175* when we come to read() we first look to recycle a buffer from the176* free_sample_buffers list before allocating a new buffer.177*/178struct oa_sample_buf {179struct exec_node link;180int refcount;181int len;182uint8_t buf[I915_PERF_OA_SAMPLE_SIZE * 10];183uint32_t last_timestamp;184};185186/**187* gen representation of a performance query object.188*189* NB: We want to keep this structure relatively lean considering that190* applications may expect to allocate enough objects to be able to191* query around all draw calls in a frame.192*/193struct intel_perf_query_object194{195const struct intel_perf_query_info *queryinfo;196197/* See query->kind to know which state below is in use... */198union {199struct {200201/**202* BO containing OA counter snapshots at query Begin/End time.203*/204void *bo;205206/**207* Address of mapped of @bo208*/209void *map;210211/**212* The MI_REPORT_PERF_COUNT command lets us specify a unique213* ID that will be reflected in the resulting OA report214* that's written by the GPU. This is the ID we're expecting215* in the begin report and the the end report should be216* @begin_report_id + 1.217*/218int begin_report_id;219220/**221* Reference the head of the brw->perfquery.sample_buffers222* list at the time that the query started (so we only need223* to look at nodes after this point when looking for samples224* related to this query)225*226* (See struct brw_oa_sample_buf description for more details)227*/228struct exec_node *samples_head;229230/**231* false while in the unaccumulated_elements list, and set to232* true when the final, end MI_RPC snapshot has been233* accumulated.234*/235bool results_accumulated;236237/**238* Accumulated OA results between begin and end of the query.239*/240struct intel_perf_query_result result;241} oa;242243struct {244/**245* BO containing starting and ending snapshots for the246* statistics counters.247*/248void *bo;249} pipeline_stats;250};251};252253struct intel_perf_context {254struct intel_perf_config *perf;255256void * mem_ctx; /* ralloc context */257void * ctx; /* driver context (eg, brw_context) */258void * bufmgr;259const struct intel_device_info *devinfo;260261uint32_t hw_ctx;262int drm_fd;263264/* The i915 perf stream we open to setup + enable the OA counters */265int oa_stream_fd;266267/* An i915 perf stream fd gives exclusive access to the OA unit that will268* report counter snapshots for a specific counter set/profile in a269* specific layout/format so we can only start OA queries that are270* compatible with the currently open fd...271*/272int current_oa_metrics_set_id;273int current_oa_format;274275/* List of buffers containing OA reports */276struct exec_list sample_buffers;277278/* Cached list of empty sample buffers */279struct exec_list free_sample_buffers;280281int n_active_oa_queries;282int n_active_pipeline_stats_queries;283284/* The number of queries depending on running OA counters which285* extends beyond brw_end_perf_query() since we need to wait until286* the last MI_RPC command has parsed by the GPU.287*288* Accurate accounting is important here as emitting an289* MI_REPORT_PERF_COUNT command while the OA unit is disabled will290* effectively hang the gpu.291*/292int n_oa_users;293294/* To help catch an spurious problem with the hardware or perf295* forwarding samples, we emit each MI_REPORT_PERF_COUNT command296* with a unique ID that we can explicitly check for...297*/298int next_query_start_report_id;299300/**301* An array of queries whose results haven't yet been assembled302* based on the data in buffer objects.303*304* These may be active, or have already ended. However, the305* results have not been requested.306*/307struct intel_perf_query_object **unaccumulated;308int unaccumulated_elements;309int unaccumulated_array_size;310311/* The total number of query objects so we can relinquish312* our exclusive access to perf if the application deletes313* all of its objects. (NB: We only disable perf while314* there are no active queries)315*/316int n_query_instances;317318int period_exponent;319};320321static bool322inc_n_users(struct intel_perf_context *perf_ctx)323{324if (perf_ctx->n_oa_users == 0 &&325intel_ioctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_ENABLE, 0) < 0)326{327return false;328}329++perf_ctx->n_oa_users;330331return true;332}333334static void335dec_n_users(struct intel_perf_context *perf_ctx)336{337/* Disabling the i915 perf stream will effectively disable the OA338* counters. Note it's important to be sure there are no outstanding339* MI_RPC commands at this point since they could stall the CS340* indefinitely once OACONTROL is disabled.341*/342--perf_ctx->n_oa_users;343if (perf_ctx->n_oa_users == 0 &&344intel_ioctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_DISABLE, 0) < 0)345{346DBG("WARNING: Error disabling gen perf stream: %m\n");347}348}349350void351intel_perf_close(struct intel_perf_context *perfquery,352const struct intel_perf_query_info *query)353{354if (perfquery->oa_stream_fd != -1) {355close(perfquery->oa_stream_fd);356perfquery->oa_stream_fd = -1;357}358if (query && query->kind == INTEL_PERF_QUERY_TYPE_RAW) {359struct intel_perf_query_info *raw_query =360(struct intel_perf_query_info *) query;361raw_query->oa_metrics_set_id = 0;362}363}364365bool366intel_perf_open(struct intel_perf_context *perf_ctx,367int metrics_set_id,368int report_format,369int period_exponent,370int drm_fd,371uint32_t ctx_id,372bool enable)373{374uint64_t properties[DRM_I915_PERF_PROP_MAX * 2];375uint32_t p = 0;376377/* Single context sampling if valid context id. */378if (ctx_id != INTEL_PERF_INVALID_CTX_ID) {379properties[p++] = DRM_I915_PERF_PROP_CTX_HANDLE;380properties[p++] = ctx_id;381}382383/* Include OA reports in samples */384properties[p++] = DRM_I915_PERF_PROP_SAMPLE_OA;385properties[p++] = true;386387/* OA unit configuration */388properties[p++] = DRM_I915_PERF_PROP_OA_METRICS_SET;389properties[p++] = metrics_set_id;390391properties[p++] = DRM_I915_PERF_PROP_OA_FORMAT;392properties[p++] = report_format;393394properties[p++] = DRM_I915_PERF_PROP_OA_EXPONENT;395properties[p++] = period_exponent;396397/* SSEU configuration */398if (intel_perf_has_global_sseu(perf_ctx->perf)) {399properties[p++] = DRM_I915_PERF_PROP_GLOBAL_SSEU;400properties[p++] = to_user_pointer(&perf_ctx->perf->sseu);401}402403assert(p <= ARRAY_SIZE(properties));404405struct drm_i915_perf_open_param param = {406.flags = I915_PERF_FLAG_FD_CLOEXEC |407I915_PERF_FLAG_FD_NONBLOCK |408(enable ? 0 : I915_PERF_FLAG_DISABLED),409.num_properties = p / 2,410.properties_ptr = (uintptr_t) properties,411};412int fd = intel_ioctl(drm_fd, DRM_IOCTL_I915_PERF_OPEN, ¶m);413if (fd == -1) {414DBG("Error opening gen perf OA stream: %m\n");415return false;416}417418perf_ctx->oa_stream_fd = fd;419420perf_ctx->current_oa_metrics_set_id = metrics_set_id;421perf_ctx->current_oa_format = report_format;422423if (enable)424++perf_ctx->n_oa_users;425426return true;427}428429static uint64_t430get_metric_id(struct intel_perf_config *perf,431const struct intel_perf_query_info *query)432{433/* These queries are know not to ever change, their config ID has been434* loaded upon the first query creation. No need to look them up again.435*/436if (query->kind == INTEL_PERF_QUERY_TYPE_OA)437return query->oa_metrics_set_id;438439assert(query->kind == INTEL_PERF_QUERY_TYPE_RAW);440441/* Raw queries can be reprogrammed up by an external application/library.442* When a raw query is used for the first time it's id is set to a value !=443* 0. When it stops being used the id returns to 0. No need to reload the444* ID when it's already loaded.445*/446if (query->oa_metrics_set_id != 0) {447DBG("Raw query '%s' guid=%s using cached ID: %"PRIu64"\n",448query->name, query->guid, query->oa_metrics_set_id);449return query->oa_metrics_set_id;450}451452struct intel_perf_query_info *raw_query = (struct intel_perf_query_info *)query;453if (!intel_perf_load_metric_id(perf, query->guid,454&raw_query->oa_metrics_set_id)) {455DBG("Unable to read query guid=%s ID, falling back to test config\n", query->guid);456raw_query->oa_metrics_set_id = perf->fallback_raw_oa_metric;457} else {458DBG("Raw query '%s'guid=%s loaded ID: %"PRIu64"\n",459query->name, query->guid, query->oa_metrics_set_id);460}461return query->oa_metrics_set_id;462}463464static struct oa_sample_buf *465get_free_sample_buf(struct intel_perf_context *perf_ctx)466{467struct exec_node *node = exec_list_pop_head(&perf_ctx->free_sample_buffers);468struct oa_sample_buf *buf;469470if (node)471buf = exec_node_data(struct oa_sample_buf, node, link);472else {473buf = ralloc_size(perf_ctx->perf, sizeof(*buf));474475exec_node_init(&buf->link);476buf->refcount = 0;477}478buf->len = 0;479480return buf;481}482483static void484reap_old_sample_buffers(struct intel_perf_context *perf_ctx)485{486struct exec_node *tail_node =487exec_list_get_tail(&perf_ctx->sample_buffers);488struct oa_sample_buf *tail_buf =489exec_node_data(struct oa_sample_buf, tail_node, link);490491/* Remove all old, unreferenced sample buffers walking forward from492* the head of the list, except always leave at least one node in493* the list so we always have a node to reference when we Begin494* a new query.495*/496foreach_list_typed_safe(struct oa_sample_buf, buf, link,497&perf_ctx->sample_buffers)498{499if (buf->refcount == 0 && buf != tail_buf) {500exec_node_remove(&buf->link);501exec_list_push_head(&perf_ctx->free_sample_buffers, &buf->link);502} else503return;504}505}506507static void508free_sample_bufs(struct intel_perf_context *perf_ctx)509{510foreach_list_typed_safe(struct oa_sample_buf, buf, link,511&perf_ctx->free_sample_buffers)512ralloc_free(buf);513514exec_list_make_empty(&perf_ctx->free_sample_buffers);515}516517518struct intel_perf_query_object *519intel_perf_new_query(struct intel_perf_context *perf_ctx, unsigned query_index)520{521const struct intel_perf_query_info *query =522&perf_ctx->perf->queries[query_index];523524switch (query->kind) {525case INTEL_PERF_QUERY_TYPE_OA:526case INTEL_PERF_QUERY_TYPE_RAW:527if (perf_ctx->period_exponent == 0)528return NULL;529break;530case INTEL_PERF_QUERY_TYPE_PIPELINE:531break;532}533534struct intel_perf_query_object *obj =535calloc(1, sizeof(struct intel_perf_query_object));536537if (!obj)538return NULL;539540obj->queryinfo = query;541542perf_ctx->n_query_instances++;543return obj;544}545546int547intel_perf_active_queries(struct intel_perf_context *perf_ctx,548const struct intel_perf_query_info *query)549{550assert(perf_ctx->n_active_oa_queries == 0 || perf_ctx->n_active_pipeline_stats_queries == 0);551552switch (query->kind) {553case INTEL_PERF_QUERY_TYPE_OA:554case INTEL_PERF_QUERY_TYPE_RAW:555return perf_ctx->n_active_oa_queries;556break;557558case INTEL_PERF_QUERY_TYPE_PIPELINE:559return perf_ctx->n_active_pipeline_stats_queries;560break;561562default:563unreachable("Unknown query type");564break;565}566}567568const struct intel_perf_query_info*569intel_perf_query_info(const struct intel_perf_query_object *query)570{571return query->queryinfo;572}573574struct intel_perf_context *575intel_perf_new_context(void *parent)576{577struct intel_perf_context *ctx = rzalloc(parent, struct intel_perf_context);578if (! ctx)579fprintf(stderr, "%s: failed to alloc context\n", __func__);580return ctx;581}582583struct intel_perf_config *584intel_perf_config(struct intel_perf_context *ctx)585{586return ctx->perf;587}588589void590intel_perf_init_context(struct intel_perf_context *perf_ctx,591struct intel_perf_config *perf_cfg,592void * mem_ctx, /* ralloc context */593void * ctx, /* driver context (eg, brw_context) */594void * bufmgr, /* eg brw_bufmgr */595const struct intel_device_info *devinfo,596uint32_t hw_ctx,597int drm_fd)598{599perf_ctx->perf = perf_cfg;600perf_ctx->mem_ctx = mem_ctx;601perf_ctx->ctx = ctx;602perf_ctx->bufmgr = bufmgr;603perf_ctx->drm_fd = drm_fd;604perf_ctx->hw_ctx = hw_ctx;605perf_ctx->devinfo = devinfo;606607perf_ctx->unaccumulated =608ralloc_array(mem_ctx, struct intel_perf_query_object *, 2);609perf_ctx->unaccumulated_elements = 0;610perf_ctx->unaccumulated_array_size = 2;611612exec_list_make_empty(&perf_ctx->sample_buffers);613exec_list_make_empty(&perf_ctx->free_sample_buffers);614615/* It's convenient to guarantee that this linked list of sample616* buffers is never empty so we add an empty head so when we617* Begin an OA query we can always take a reference on a buffer618* in this list.619*/620struct oa_sample_buf *buf = get_free_sample_buf(perf_ctx);621exec_list_push_head(&perf_ctx->sample_buffers, &buf->link);622623perf_ctx->oa_stream_fd = -1;624perf_ctx->next_query_start_report_id = 1000;625626/* The period_exponent gives a sampling period as follows:627* sample_period = timestamp_period * 2^(period_exponent + 1)628*629* The timestamps increments every 80ns (HSW), ~52ns (GFX9LP) or630* ~83ns (GFX8/9).631*632* The counter overflow period is derived from the EuActive counter633* which reads a counter that increments by the number of clock634* cycles multiplied by the number of EUs. It can be calculated as:635*636* 2^(number of bits in A counter) / (n_eus * max_intel_freq * 2)637*638* (E.g. 40 EUs @ 1GHz = ~53ms)639*640* We select a sampling period inferior to that overflow period to641* ensure we cannot see more than 1 counter overflow, otherwise we642* could loose information.643*/644645int a_counter_in_bits = 32;646if (devinfo->ver >= 8)647a_counter_in_bits = 40;648649uint64_t overflow_period = pow(2, a_counter_in_bits) / (perf_cfg->sys_vars.n_eus *650/* drop 1GHz freq to have units in nanoseconds */6512);652653DBG("A counter overflow period: %"PRIu64"ns, %"PRIu64"ms (n_eus=%"PRIu64")\n",654overflow_period, overflow_period / 1000000ul, perf_cfg->sys_vars.n_eus);655656int period_exponent = 0;657uint64_t prev_sample_period, next_sample_period;658for (int e = 0; e < 30; e++) {659prev_sample_period = 1000000000ull * pow(2, e + 1) / devinfo->timestamp_frequency;660next_sample_period = 1000000000ull * pow(2, e + 2) / devinfo->timestamp_frequency;661662/* Take the previous sampling period, lower than the overflow663* period.664*/665if (prev_sample_period < overflow_period &&666next_sample_period > overflow_period)667period_exponent = e + 1;668}669670perf_ctx->period_exponent = period_exponent;671672if (period_exponent == 0) {673DBG("WARNING: enable to find a sampling exponent\n");674} else {675DBG("OA sampling exponent: %i ~= %"PRIu64"ms\n", period_exponent,676prev_sample_period / 1000000ul);677}678}679680/**681* Add a query to the global list of "unaccumulated queries."682*683* Queries are tracked here until all the associated OA reports have684* been accumulated via accumulate_oa_reports() after the end685* MI_REPORT_PERF_COUNT has landed in query->oa.bo.686*/687static void688add_to_unaccumulated_query_list(struct intel_perf_context *perf_ctx,689struct intel_perf_query_object *obj)690{691if (perf_ctx->unaccumulated_elements >=692perf_ctx->unaccumulated_array_size)693{694perf_ctx->unaccumulated_array_size *= 1.5;695perf_ctx->unaccumulated =696reralloc(perf_ctx->mem_ctx, perf_ctx->unaccumulated,697struct intel_perf_query_object *,698perf_ctx->unaccumulated_array_size);699}700701perf_ctx->unaccumulated[perf_ctx->unaccumulated_elements++] = obj;702}703704/**705* Emit MI_STORE_REGISTER_MEM commands to capture all of the706* pipeline statistics for the performance query object.707*/708static void709snapshot_statistics_registers(struct intel_perf_context *ctx,710struct intel_perf_query_object *obj,711uint32_t offset_in_bytes)712{713struct intel_perf_config *perf = ctx->perf;714const struct intel_perf_query_info *query = obj->queryinfo;715const int n_counters = query->n_counters;716717for (int i = 0; i < n_counters; i++) {718const struct intel_perf_query_counter *counter = &query->counters[i];719720assert(counter->data_type == INTEL_PERF_COUNTER_DATA_TYPE_UINT64);721722perf->vtbl.store_register_mem(ctx->ctx, obj->pipeline_stats.bo,723counter->pipeline_stat.reg, 8,724offset_in_bytes + counter->offset);725}726}727728static void729snapshot_query_layout(struct intel_perf_context *perf_ctx,730struct intel_perf_query_object *query,731bool end_snapshot)732{733struct intel_perf_config *perf_cfg = perf_ctx->perf;734const struct intel_perf_query_field_layout *layout = &perf_cfg->query_layout;735uint32_t offset = end_snapshot ? align(layout->size, layout->alignment) : 0;736737for (uint32_t f = 0; f < layout->n_fields; f++) {738const struct intel_perf_query_field *field =739&layout->fields[end_snapshot ? f : (layout->n_fields - 1 - f)];740741switch (field->type) {742case INTEL_PERF_QUERY_FIELD_TYPE_MI_RPC:743perf_cfg->vtbl.emit_mi_report_perf_count(perf_ctx->ctx, query->oa.bo,744offset + field->location,745query->oa.begin_report_id +746(end_snapshot ? 1 : 0));747break;748case INTEL_PERF_QUERY_FIELD_TYPE_SRM_PERFCNT:749case INTEL_PERF_QUERY_FIELD_TYPE_SRM_RPSTAT:750case INTEL_PERF_QUERY_FIELD_TYPE_SRM_OA_B:751case INTEL_PERF_QUERY_FIELD_TYPE_SRM_OA_C:752perf_cfg->vtbl.store_register_mem(perf_ctx->ctx, query->oa.bo,753field->mmio_offset, field->size,754offset + field->location);755break;756default:757unreachable("Invalid field type");758}759}760}761762bool763intel_perf_begin_query(struct intel_perf_context *perf_ctx,764struct intel_perf_query_object *query)765{766struct intel_perf_config *perf_cfg = perf_ctx->perf;767const struct intel_perf_query_info *queryinfo = query->queryinfo;768769/* XXX: We have to consider that the command parser unit that parses batch770* buffer commands and is used to capture begin/end counter snapshots isn't771* implicitly synchronized with what's currently running across other GPU772* units (such as the EUs running shaders) that the performance counters are773* associated with.774*775* The intention of performance queries is to measure the work associated776* with commands between the begin/end delimiters and so for that to be the777* case we need to explicitly synchronize the parsing of commands to capture778* Begin/End counter snapshots with what's running across other parts of the779* GPU.780*781* When the command parser reaches a Begin marker it effectively needs to782* drain everything currently running on the GPU until the hardware is idle783* before capturing the first snapshot of counters - otherwise the results784* would also be measuring the effects of earlier commands.785*786* When the command parser reaches an End marker it needs to stall until787* everything currently running on the GPU has finished before capturing the788* end snapshot - otherwise the results won't be a complete representation789* of the work.790*791* To achieve this, we stall the pipeline at pixel scoreboard (prevent any792* additional work to be processed by the pipeline until all pixels of the793* previous draw has be completed).794*795* N.B. The final results are based on deltas of counters between (inside)796* Begin/End markers so even though the total wall clock time of the797* workload is stretched by larger pipeline bubbles the bubbles themselves798* are generally invisible to the query results. Whether that's a good or a799* bad thing depends on the use case. For a lower real-time impact while800* capturing metrics then periodic sampling may be a better choice than801* INTEL_performance_query.802*803*804* This is our Begin synchronization point to drain current work on the805* GPU before we capture our first counter snapshot...806*/807perf_cfg->vtbl.emit_stall_at_pixel_scoreboard(perf_ctx->ctx);808809switch (queryinfo->kind) {810case INTEL_PERF_QUERY_TYPE_OA:811case INTEL_PERF_QUERY_TYPE_RAW: {812813/* Opening an i915 perf stream implies exclusive access to the OA unit814* which will generate counter reports for a specific counter set with a815* specific layout/format so we can't begin any OA based queries that816* require a different counter set or format unless we get an opportunity817* to close the stream and open a new one...818*/819uint64_t metric_id = get_metric_id(perf_ctx->perf, queryinfo);820821if (perf_ctx->oa_stream_fd != -1 &&822perf_ctx->current_oa_metrics_set_id != metric_id) {823824if (perf_ctx->n_oa_users != 0) {825DBG("WARNING: Begin failed already using perf config=%i/%"PRIu64"\n",826perf_ctx->current_oa_metrics_set_id, metric_id);827return false;828} else829intel_perf_close(perf_ctx, queryinfo);830}831832/* If the OA counters aren't already on, enable them. */833if (perf_ctx->oa_stream_fd == -1) {834assert(perf_ctx->period_exponent != 0);835836if (!intel_perf_open(perf_ctx, metric_id, queryinfo->oa_format,837perf_ctx->period_exponent, perf_ctx->drm_fd,838perf_ctx->hw_ctx, false))839return false;840} else {841assert(perf_ctx->current_oa_metrics_set_id == metric_id &&842perf_ctx->current_oa_format == queryinfo->oa_format);843}844845if (!inc_n_users(perf_ctx)) {846DBG("WARNING: Error enabling i915 perf stream: %m\n");847return false;848}849850if (query->oa.bo) {851perf_cfg->vtbl.bo_unreference(query->oa.bo);852query->oa.bo = NULL;853}854855query->oa.bo = perf_cfg->vtbl.bo_alloc(perf_ctx->bufmgr,856"perf. query OA MI_RPC bo",857MI_RPC_BO_SIZE);858#ifdef DEBUG859/* Pre-filling the BO helps debug whether writes landed. */860void *map = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->oa.bo, MAP_WRITE);861memset(map, 0x80, MI_RPC_BO_SIZE);862perf_cfg->vtbl.bo_unmap(query->oa.bo);863#endif864865query->oa.begin_report_id = perf_ctx->next_query_start_report_id;866perf_ctx->next_query_start_report_id += 2;867868snapshot_query_layout(perf_ctx, query, false /* end_snapshot */);869870++perf_ctx->n_active_oa_queries;871872/* No already-buffered samples can possibly be associated with this query873* so create a marker within the list of sample buffers enabling us to874* easily ignore earlier samples when processing this query after875* completion.876*/877assert(!exec_list_is_empty(&perf_ctx->sample_buffers));878query->oa.samples_head = exec_list_get_tail(&perf_ctx->sample_buffers);879880struct oa_sample_buf *buf =881exec_node_data(struct oa_sample_buf, query->oa.samples_head, link);882883/* This reference will ensure that future/following sample884* buffers (that may relate to this query) can't be freed until885* this drops to zero.886*/887buf->refcount++;888889intel_perf_query_result_clear(&query->oa.result);890query->oa.results_accumulated = false;891892add_to_unaccumulated_query_list(perf_ctx, query);893break;894}895896case INTEL_PERF_QUERY_TYPE_PIPELINE:897if (query->pipeline_stats.bo) {898perf_cfg->vtbl.bo_unreference(query->pipeline_stats.bo);899query->pipeline_stats.bo = NULL;900}901902query->pipeline_stats.bo =903perf_cfg->vtbl.bo_alloc(perf_ctx->bufmgr,904"perf. query pipeline stats bo",905STATS_BO_SIZE);906907/* Take starting snapshots. */908snapshot_statistics_registers(perf_ctx, query, 0);909910++perf_ctx->n_active_pipeline_stats_queries;911break;912913default:914unreachable("Unknown query type");915break;916}917918return true;919}920921void922intel_perf_end_query(struct intel_perf_context *perf_ctx,923struct intel_perf_query_object *query)924{925struct intel_perf_config *perf_cfg = perf_ctx->perf;926927/* Ensure that the work associated with the queried commands will have928* finished before taking our query end counter readings.929*930* For more details see comment in brw_begin_perf_query for931* corresponding flush.932*/933perf_cfg->vtbl.emit_stall_at_pixel_scoreboard(perf_ctx->ctx);934935switch (query->queryinfo->kind) {936case INTEL_PERF_QUERY_TYPE_OA:937case INTEL_PERF_QUERY_TYPE_RAW:938939/* NB: It's possible that the query will have already been marked940* as 'accumulated' if an error was seen while reading samples941* from perf. In this case we mustn't try and emit a closing942* MI_RPC command in case the OA unit has already been disabled943*/944if (!query->oa.results_accumulated)945snapshot_query_layout(perf_ctx, query, true /* end_snapshot */);946947--perf_ctx->n_active_oa_queries;948949/* NB: even though the query has now ended, it can't be accumulated950* until the end MI_REPORT_PERF_COUNT snapshot has been written951* to query->oa.bo952*/953break;954955case INTEL_PERF_QUERY_TYPE_PIPELINE:956snapshot_statistics_registers(perf_ctx, query,957STATS_BO_END_OFFSET_BYTES);958--perf_ctx->n_active_pipeline_stats_queries;959break;960961default:962unreachable("Unknown query type");963break;964}965}966967bool intel_perf_oa_stream_ready(struct intel_perf_context *perf_ctx)968{969struct pollfd pfd;970971pfd.fd = perf_ctx->oa_stream_fd;972pfd.events = POLLIN;973pfd.revents = 0;974975if (poll(&pfd, 1, 0) < 0) {976DBG("Error polling OA stream\n");977return false;978}979980if (!(pfd.revents & POLLIN))981return false;982983return true;984}985986ssize_t987intel_perf_read_oa_stream(struct intel_perf_context *perf_ctx,988void* buf,989size_t nbytes)990{991return read(perf_ctx->oa_stream_fd, buf, nbytes);992}993994enum OaReadStatus {995OA_READ_STATUS_ERROR,996OA_READ_STATUS_UNFINISHED,997OA_READ_STATUS_FINISHED,998};9991000static enum OaReadStatus1001read_oa_samples_until(struct intel_perf_context *perf_ctx,1002uint32_t start_timestamp,1003uint32_t end_timestamp)1004{1005struct exec_node *tail_node =1006exec_list_get_tail(&perf_ctx->sample_buffers);1007struct oa_sample_buf *tail_buf =1008exec_node_data(struct oa_sample_buf, tail_node, link);1009uint32_t last_timestamp =1010tail_buf->len == 0 ? start_timestamp : tail_buf->last_timestamp;10111012while (1) {1013struct oa_sample_buf *buf = get_free_sample_buf(perf_ctx);1014uint32_t offset;1015int len;10161017while ((len = read(perf_ctx->oa_stream_fd, buf->buf,1018sizeof(buf->buf))) < 0 && errno == EINTR)1019;10201021if (len <= 0) {1022exec_list_push_tail(&perf_ctx->free_sample_buffers, &buf->link);10231024if (len == 0) {1025DBG("Spurious EOF reading i915 perf samples\n");1026return OA_READ_STATUS_ERROR;1027}10281029if (errno != EAGAIN) {1030DBG("Error reading i915 perf samples: %m\n");1031return OA_READ_STATUS_ERROR;1032}10331034if ((last_timestamp - start_timestamp) >= INT32_MAX)1035return OA_READ_STATUS_UNFINISHED;10361037if ((last_timestamp - start_timestamp) <1038(end_timestamp - start_timestamp))1039return OA_READ_STATUS_UNFINISHED;10401041return OA_READ_STATUS_FINISHED;1042}10431044buf->len = len;1045exec_list_push_tail(&perf_ctx->sample_buffers, &buf->link);10461047/* Go through the reports and update the last timestamp. */1048offset = 0;1049while (offset < buf->len) {1050const struct drm_i915_perf_record_header *header =1051(const struct drm_i915_perf_record_header *) &buf->buf[offset];1052uint32_t *report = (uint32_t *) (header + 1);10531054if (header->type == DRM_I915_PERF_RECORD_SAMPLE)1055last_timestamp = report[1];10561057offset += header->size;1058}10591060buf->last_timestamp = last_timestamp;1061}10621063unreachable("not reached");1064return OA_READ_STATUS_ERROR;1065}10661067/**1068* Try to read all the reports until either the delimiting timestamp1069* or an error arises.1070*/1071static bool1072read_oa_samples_for_query(struct intel_perf_context *perf_ctx,1073struct intel_perf_query_object *query,1074void *current_batch)1075{1076uint32_t *start;1077uint32_t *last;1078uint32_t *end;1079struct intel_perf_config *perf_cfg = perf_ctx->perf;10801081/* We need the MI_REPORT_PERF_COUNT to land before we can start1082* accumulate. */1083assert(!perf_cfg->vtbl.batch_references(current_batch, query->oa.bo) &&1084!perf_cfg->vtbl.bo_busy(query->oa.bo));10851086/* Map the BO once here and let accumulate_oa_reports() unmap1087* it. */1088if (query->oa.map == NULL)1089query->oa.map = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->oa.bo, MAP_READ);10901091start = last = query->oa.map + field_offset(false, 0);1092end = query->oa.map + field_offset(true, 0);10931094if (start[0] != query->oa.begin_report_id) {1095DBG("Spurious start report id=%"PRIu32"\n", start[0]);1096return true;1097}1098if (end[0] != (query->oa.begin_report_id + 1)) {1099DBG("Spurious end report id=%"PRIu32"\n", end[0]);1100return true;1101}11021103/* Read the reports until the end timestamp. */1104switch (read_oa_samples_until(perf_ctx, start[1], end[1])) {1105case OA_READ_STATUS_ERROR:1106FALLTHROUGH; /* Let accumulate_oa_reports() deal with the error. */1107case OA_READ_STATUS_FINISHED:1108return true;1109case OA_READ_STATUS_UNFINISHED:1110return false;1111}11121113unreachable("invalid read status");1114return false;1115}11161117void1118intel_perf_wait_query(struct intel_perf_context *perf_ctx,1119struct intel_perf_query_object *query,1120void *current_batch)1121{1122struct intel_perf_config *perf_cfg = perf_ctx->perf;1123struct brw_bo *bo = NULL;11241125switch (query->queryinfo->kind) {1126case INTEL_PERF_QUERY_TYPE_OA:1127case INTEL_PERF_QUERY_TYPE_RAW:1128bo = query->oa.bo;1129break;11301131case INTEL_PERF_QUERY_TYPE_PIPELINE:1132bo = query->pipeline_stats.bo;1133break;11341135default:1136unreachable("Unknown query type");1137break;1138}11391140if (bo == NULL)1141return;11421143/* If the current batch references our results bo then we need to1144* flush first...1145*/1146if (perf_cfg->vtbl.batch_references(current_batch, bo))1147perf_cfg->vtbl.batchbuffer_flush(perf_ctx->ctx, __FILE__, __LINE__);11481149perf_cfg->vtbl.bo_wait_rendering(bo);1150}11511152bool1153intel_perf_is_query_ready(struct intel_perf_context *perf_ctx,1154struct intel_perf_query_object *query,1155void *current_batch)1156{1157struct intel_perf_config *perf_cfg = perf_ctx->perf;11581159switch (query->queryinfo->kind) {1160case INTEL_PERF_QUERY_TYPE_OA:1161case INTEL_PERF_QUERY_TYPE_RAW:1162return (query->oa.results_accumulated ||1163(query->oa.bo &&1164!perf_cfg->vtbl.batch_references(current_batch, query->oa.bo) &&1165!perf_cfg->vtbl.bo_busy(query->oa.bo)));11661167case INTEL_PERF_QUERY_TYPE_PIPELINE:1168return (query->pipeline_stats.bo &&1169!perf_cfg->vtbl.batch_references(current_batch, query->pipeline_stats.bo) &&1170!perf_cfg->vtbl.bo_busy(query->pipeline_stats.bo));11711172default:1173unreachable("Unknown query type");1174break;1175}11761177return false;1178}11791180/**1181* Remove a query from the global list of unaccumulated queries once1182* after successfully accumulating the OA reports associated with the1183* query in accumulate_oa_reports() or when discarding unwanted query1184* results.1185*/1186static void1187drop_from_unaccumulated_query_list(struct intel_perf_context *perf_ctx,1188struct intel_perf_query_object *query)1189{1190for (int i = 0; i < perf_ctx->unaccumulated_elements; i++) {1191if (perf_ctx->unaccumulated[i] == query) {1192int last_elt = --perf_ctx->unaccumulated_elements;11931194if (i == last_elt)1195perf_ctx->unaccumulated[i] = NULL;1196else {1197perf_ctx->unaccumulated[i] =1198perf_ctx->unaccumulated[last_elt];1199}12001201break;1202}1203}12041205/* Drop our samples_head reference so that associated periodic1206* sample data buffers can potentially be reaped if they aren't1207* referenced by any other queries...1208*/12091210struct oa_sample_buf *buf =1211exec_node_data(struct oa_sample_buf, query->oa.samples_head, link);12121213assert(buf->refcount > 0);1214buf->refcount--;12151216query->oa.samples_head = NULL;12171218reap_old_sample_buffers(perf_ctx);1219}12201221/* In general if we see anything spurious while accumulating results,1222* we don't try and continue accumulating the current query, hoping1223* for the best, we scrap anything outstanding, and then hope for the1224* best with new queries.1225*/1226static void1227discard_all_queries(struct intel_perf_context *perf_ctx)1228{1229while (perf_ctx->unaccumulated_elements) {1230struct intel_perf_query_object *query = perf_ctx->unaccumulated[0];12311232query->oa.results_accumulated = true;1233drop_from_unaccumulated_query_list(perf_ctx, query);12341235dec_n_users(perf_ctx);1236}1237}12381239/* Looks for the validity bit of context ID (dword 2) of an OA report. */1240static bool1241oa_report_ctx_id_valid(const struct intel_device_info *devinfo,1242const uint32_t *report)1243{1244assert(devinfo->ver >= 8);1245if (devinfo->ver == 8)1246return (report[0] & (1 << 25)) != 0;1247return (report[0] & (1 << 16)) != 0;1248}12491250/**1251* Accumulate raw OA counter values based on deltas between pairs of1252* OA reports.1253*1254* Accumulation starts from the first report captured via1255* MI_REPORT_PERF_COUNT (MI_RPC) by brw_begin_perf_query() until the1256* last MI_RPC report requested by brw_end_perf_query(). Between these1257* two reports there may also some number of periodically sampled OA1258* reports collected via the i915 perf interface - depending on the1259* duration of the query.1260*1261* These periodic snapshots help to ensure we handle counter overflow1262* correctly by being frequent enough to ensure we don't miss multiple1263* overflows of a counter between snapshots. For Gfx8+ the i915 perf1264* snapshots provide the extra context-switch reports that let us1265* subtract out the progress of counters associated with other1266* contexts running on the system.1267*/1268static void1269accumulate_oa_reports(struct intel_perf_context *perf_ctx,1270struct intel_perf_query_object *query)1271{1272const struct intel_device_info *devinfo = perf_ctx->devinfo;1273uint32_t *start;1274uint32_t *last;1275uint32_t *end;1276struct exec_node *first_samples_node;1277bool last_report_ctx_match = true;1278int out_duration = 0;12791280assert(query->oa.map != NULL);12811282start = last = query->oa.map + field_offset(false, 0);1283end = query->oa.map + field_offset(true, 0);12841285if (start[0] != query->oa.begin_report_id) {1286DBG("Spurious start report id=%"PRIu32"\n", start[0]);1287goto error;1288}1289if (end[0] != (query->oa.begin_report_id + 1)) {1290DBG("Spurious end report id=%"PRIu32"\n", end[0]);1291goto error;1292}12931294/* On Gfx12+ OA reports are sourced from per context counters, so we don't1295* ever have to look at the global OA buffer. Yey \o/1296*/1297if (perf_ctx->devinfo->ver >= 12) {1298last = start;1299goto end;1300}13011302/* See if we have any periodic reports to accumulate too... */13031304/* N.B. The oa.samples_head was set when the query began and1305* pointed to the tail of the perf_ctx->sample_buffers list at1306* the time the query started. Since the buffer existed before the1307* first MI_REPORT_PERF_COUNT command was emitted we therefore know1308* that no data in this particular node's buffer can possibly be1309* associated with the query - so skip ahead one...1310*/1311first_samples_node = query->oa.samples_head->next;13121313foreach_list_typed_from(struct oa_sample_buf, buf, link,1314&perf_ctx->sample_buffers,1315first_samples_node)1316{1317int offset = 0;13181319while (offset < buf->len) {1320const struct drm_i915_perf_record_header *header =1321(const struct drm_i915_perf_record_header *)(buf->buf + offset);13221323assert(header->size != 0);1324assert(header->size <= buf->len);13251326offset += header->size;13271328switch (header->type) {1329case DRM_I915_PERF_RECORD_SAMPLE: {1330uint32_t *report = (uint32_t *)(header + 1);1331bool report_ctx_match = true;1332bool add = true;13331334/* Ignore reports that come before the start marker.1335* (Note: takes care to allow overflow of 32bit timestamps)1336*/1337if (intel_device_info_timebase_scale(devinfo,1338report[1] - start[1]) > 5000000000) {1339continue;1340}13411342/* Ignore reports that come after the end marker.1343* (Note: takes care to allow overflow of 32bit timestamps)1344*/1345if (intel_device_info_timebase_scale(devinfo,1346report[1] - end[1]) <= 5000000000) {1347goto end;1348}13491350/* For Gfx8+ since the counters continue while other1351* contexts are running we need to discount any unrelated1352* deltas. The hardware automatically generates a report1353* on context switch which gives us a new reference point1354* to continuing adding deltas from.1355*1356* For Haswell we can rely on the HW to stop the progress1357* of OA counters while any other context is acctive.1358*/1359if (devinfo->ver >= 8) {1360/* Consider that the current report matches our context only if1361* the report says the report ID is valid.1362*/1363report_ctx_match = oa_report_ctx_id_valid(devinfo, report) &&1364report[2] == start[2];1365if (report_ctx_match)1366out_duration = 0;1367else1368out_duration++;13691370/* Only add the delta between <last, report> if the last report1371* was clearly identified as our context, or if we have at most1372* 1 report without a matching ID.1373*1374* The OA unit will sometimes label reports with an invalid1375* context ID when i915 rewrites the execlist submit register1376* with the same context as the one currently running. This1377* happens when i915 wants to notify the HW of ringbuffer tail1378* register update. We have to consider this report as part of1379* our context as the 3d pipeline behind the OACS unit is still1380* processing the operations started at the previous execlist1381* submission.1382*/1383add = last_report_ctx_match && out_duration < 2;1384}13851386if (add) {1387intel_perf_query_result_accumulate(&query->oa.result,1388query->queryinfo,1389devinfo,1390last, report);1391} else {1392/* We're not adding the delta because we've identified it's not1393* for the context we filter for. We can consider that the1394* query was split.1395*/1396query->oa.result.query_disjoint = true;1397}13981399last = report;1400last_report_ctx_match = report_ctx_match;14011402break;1403}14041405case DRM_I915_PERF_RECORD_OA_BUFFER_LOST:1406DBG("i915 perf: OA error: all reports lost\n");1407goto error;1408case DRM_I915_PERF_RECORD_OA_REPORT_LOST:1409DBG("i915 perf: OA report lost\n");1410break;1411}1412}1413}14141415end:14161417intel_perf_query_result_accumulate(&query->oa.result, query->queryinfo,1418devinfo, last, end);14191420query->oa.results_accumulated = true;1421drop_from_unaccumulated_query_list(perf_ctx, query);1422dec_n_users(perf_ctx);14231424return;14251426error:14271428discard_all_queries(perf_ctx);1429}14301431void1432intel_perf_delete_query(struct intel_perf_context *perf_ctx,1433struct intel_perf_query_object *query)1434{1435struct intel_perf_config *perf_cfg = perf_ctx->perf;14361437/* We can assume that the frontend waits for a query to complete1438* before ever calling into here, so we don't have to worry about1439* deleting an in-flight query object.1440*/1441switch (query->queryinfo->kind) {1442case INTEL_PERF_QUERY_TYPE_OA:1443case INTEL_PERF_QUERY_TYPE_RAW:1444if (query->oa.bo) {1445if (!query->oa.results_accumulated) {1446drop_from_unaccumulated_query_list(perf_ctx, query);1447dec_n_users(perf_ctx);1448}14491450perf_cfg->vtbl.bo_unreference(query->oa.bo);1451query->oa.bo = NULL;1452}14531454query->oa.results_accumulated = false;1455break;14561457case INTEL_PERF_QUERY_TYPE_PIPELINE:1458if (query->pipeline_stats.bo) {1459perf_cfg->vtbl.bo_unreference(query->pipeline_stats.bo);1460query->pipeline_stats.bo = NULL;1461}1462break;14631464default:1465unreachable("Unknown query type");1466break;1467}14681469/* As an indication that the INTEL_performance_query extension is no1470* longer in use, it's a good time to free our cache of sample1471* buffers and close any current i915-perf stream.1472*/1473if (--perf_ctx->n_query_instances == 0) {1474free_sample_bufs(perf_ctx);1475intel_perf_close(perf_ctx, query->queryinfo);1476}14771478free(query);1479}14801481static int1482get_oa_counter_data(struct intel_perf_context *perf_ctx,1483struct intel_perf_query_object *query,1484size_t data_size,1485uint8_t *data)1486{1487struct intel_perf_config *perf_cfg = perf_ctx->perf;1488const struct intel_perf_query_info *queryinfo = query->queryinfo;1489int n_counters = queryinfo->n_counters;1490int written = 0;14911492for (int i = 0; i < n_counters; i++) {1493const struct intel_perf_query_counter *counter = &queryinfo->counters[i];1494uint64_t *out_uint64;1495float *out_float;1496size_t counter_size = intel_perf_query_counter_get_size(counter);14971498if (counter_size) {1499switch (counter->data_type) {1500case INTEL_PERF_COUNTER_DATA_TYPE_UINT64:1501out_uint64 = (uint64_t *)(data + counter->offset);1502*out_uint64 =1503counter->oa_counter_read_uint64(perf_cfg, queryinfo,1504&query->oa.result);1505break;1506case INTEL_PERF_COUNTER_DATA_TYPE_FLOAT:1507out_float = (float *)(data + counter->offset);1508*out_float =1509counter->oa_counter_read_float(perf_cfg, queryinfo,1510&query->oa.result);1511break;1512default:1513/* So far we aren't using uint32, double or bool32... */1514unreachable("unexpected counter data type");1515}15161517if (counter->offset + counter_size > written)1518written = counter->offset + counter_size;1519}1520}15211522return written;1523}15241525static int1526get_pipeline_stats_data(struct intel_perf_context *perf_ctx,1527struct intel_perf_query_object *query,1528size_t data_size,1529uint8_t *data)15301531{1532struct intel_perf_config *perf_cfg = perf_ctx->perf;1533const struct intel_perf_query_info *queryinfo = query->queryinfo;1534int n_counters = queryinfo->n_counters;1535uint8_t *p = data;15361537uint64_t *start = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->pipeline_stats.bo, MAP_READ);1538uint64_t *end = start + (STATS_BO_END_OFFSET_BYTES / sizeof(uint64_t));15391540for (int i = 0; i < n_counters; i++) {1541const struct intel_perf_query_counter *counter = &queryinfo->counters[i];1542uint64_t value = end[i] - start[i];15431544if (counter->pipeline_stat.numerator !=1545counter->pipeline_stat.denominator) {1546value *= counter->pipeline_stat.numerator;1547value /= counter->pipeline_stat.denominator;1548}15491550*((uint64_t *)p) = value;1551p += 8;1552}15531554perf_cfg->vtbl.bo_unmap(query->pipeline_stats.bo);15551556return p - data;1557}15581559void1560intel_perf_get_query_data(struct intel_perf_context *perf_ctx,1561struct intel_perf_query_object *query,1562void *current_batch,1563int data_size,1564unsigned *data,1565unsigned *bytes_written)1566{1567struct intel_perf_config *perf_cfg = perf_ctx->perf;1568int written = 0;15691570switch (query->queryinfo->kind) {1571case INTEL_PERF_QUERY_TYPE_OA:1572case INTEL_PERF_QUERY_TYPE_RAW:1573if (!query->oa.results_accumulated) {1574/* Due to the sampling frequency of the OA buffer by the i915-perf1575* driver, there can be a 5ms delay between the Mesa seeing the query1576* complete and i915 making all the OA buffer reports available to us.1577* We need to wait for all the reports to come in before we can do1578* the post processing removing unrelated deltas.1579* There is a i915-perf series to address this issue, but it's1580* not been merged upstream yet.1581*/1582while (!read_oa_samples_for_query(perf_ctx, query, current_batch))1583;15841585uint32_t *begin_report = query->oa.map;1586uint32_t *end_report = query->oa.map + perf_cfg->query_layout.size;1587intel_perf_query_result_accumulate_fields(&query->oa.result,1588query->queryinfo,1589perf_ctx->devinfo,1590begin_report,1591end_report,1592true /* no_oa_accumulate */);1593accumulate_oa_reports(perf_ctx, query);1594assert(query->oa.results_accumulated);15951596perf_cfg->vtbl.bo_unmap(query->oa.bo);1597query->oa.map = NULL;1598}1599if (query->queryinfo->kind == INTEL_PERF_QUERY_TYPE_OA) {1600written = get_oa_counter_data(perf_ctx, query, data_size, (uint8_t *)data);1601} else {1602const struct intel_device_info *devinfo = perf_ctx->devinfo;16031604written = intel_perf_query_result_write_mdapi((uint8_t *)data, data_size,1605devinfo, query->queryinfo,1606&query->oa.result);1607}1608break;16091610case INTEL_PERF_QUERY_TYPE_PIPELINE:1611written = get_pipeline_stats_data(perf_ctx, query, data_size, (uint8_t *)data);1612break;16131614default:1615unreachable("Unknown query type");1616break;1617}16181619if (bytes_written)1620*bytes_written = written;1621}16221623void1624intel_perf_dump_query_count(struct intel_perf_context *perf_ctx)1625{1626DBG("Queries: (Open queries = %d, OA users = %d)\n",1627perf_ctx->n_active_oa_queries, perf_ctx->n_oa_users);1628}16291630void1631intel_perf_dump_query(struct intel_perf_context *ctx,1632struct intel_perf_query_object *obj,1633void *current_batch)1634{1635switch (obj->queryinfo->kind) {1636case INTEL_PERF_QUERY_TYPE_OA:1637case INTEL_PERF_QUERY_TYPE_RAW:1638DBG("BO: %-4s OA data: %-10s %-15s\n",1639obj->oa.bo ? "yes," : "no,",1640intel_perf_is_query_ready(ctx, obj, current_batch) ? "ready," : "not ready,",1641obj->oa.results_accumulated ? "accumulated" : "not accumulated");1642break;1643case INTEL_PERF_QUERY_TYPE_PIPELINE:1644DBG("BO: %-4s\n",1645obj->pipeline_stats.bo ? "yes" : "no");1646break;1647default:1648unreachable("Unknown query type");1649break;1650}1651}165216531654