intel/perf: move initialization of pipeline statistics metrics to gen_perf
[mesa.git] / src / intel / perf / gen_perf.c
index 99f9cd7e0976256353feec290757c0c74c92ca2a..4e29bc17c0a53529bb10dfb4e9c8934cb0d05e72 100644 (file)
 #include "dev/gen_debug.h"
 #include "dev/gen_device_info.h"
 #include "util/bitscan.h"
+#include "util/u_math.h"
 
 #define FILE_DEBUG_FLAG DEBUG_PERFMON
+#define MI_RPC_BO_SIZE              4096
+#define MI_FREQ_START_OFFSET_BYTES  (3072)
+#define MI_RPC_BO_END_OFFSET_BYTES  (MI_RPC_BO_SIZE / 2)
+#define MI_FREQ_END_OFFSET_BYTES    (3076)
+
+#define INTEL_MASK(high, low) (((1u<<((high)-(low)+1))-1)<<(low))
+
+#define GEN7_RPSTAT1                       0xA01C
+#define  GEN7_RPSTAT1_CURR_GT_FREQ_SHIFT   7
+#define  GEN7_RPSTAT1_CURR_GT_FREQ_MASK    INTEL_MASK(13, 7)
+#define  GEN7_RPSTAT1_PREV_GT_FREQ_SHIFT   0
+#define  GEN7_RPSTAT1_PREV_GT_FREQ_MASK    INTEL_MASK(6, 0)
+
+#define GEN9_RPSTAT0                       0xA01C
+#define  GEN9_RPSTAT0_CURR_GT_FREQ_SHIFT   23
+#define  GEN9_RPSTAT0_CURR_GT_FREQ_MASK    INTEL_MASK(31, 23)
+#define  GEN9_RPSTAT0_PREV_GT_FREQ_SHIFT   0
+#define  GEN9_RPSTAT0_PREV_GT_FREQ_MASK    INTEL_MASK(8, 0)
+
+#define GEN6_SO_PRIM_STORAGE_NEEDED     0x2280
+#define GEN7_SO_PRIM_STORAGE_NEEDED(n)  (0x5240 + (n) * 8)
+#define GEN6_SO_NUM_PRIMS_WRITTEN       0x2288
+#define GEN7_SO_NUM_PRIMS_WRITTEN(n)    (0x5200 + (n) * 8)
+
+#define MAP_READ  (1 << 0)
+#define MAP_WRITE (1 << 1)
 
 static bool
 get_sysfs_dev_dir(struct gen_perf_config *perf, int fd)
@@ -143,13 +170,32 @@ read_sysfs_drm_device_file_uint64(struct gen_perf_config *perf,
    return read_file_uint64(buf, value);
 }
 
+static inline struct gen_perf_query_info *
+append_query_info(struct gen_perf_config *perf, int max_counters)
+{
+   struct gen_perf_query_info *query;
+
+   perf->queries = reralloc(perf, perf->queries,
+                            struct gen_perf_query_info,
+                            ++perf->n_queries);
+   query = &perf->queries[perf->n_queries - 1];
+   memset(query, 0, sizeof(*query));
+
+   if (max_counters > 0) {
+      query->max_counters = max_counters;
+      query->counters =
+         rzalloc_array(perf, struct gen_perf_query_counter, max_counters);
+   }
+
+   return query;
+}
+
 static void
 register_oa_config(struct gen_perf_config *perf,
                    const struct gen_perf_query_info *query,
                    uint64_t config_id)
 {
-   struct gen_perf_query_info *registred_query =
-      gen_perf_query_append_query_info(perf, 0);
+   struct gen_perf_query_info *registred_query = append_query_info(perf, 0);
 
    *registred_query = *query;
    registred_query->oa_metrics_set_id = config_id;
@@ -373,8 +419,123 @@ get_register_queries_function(const struct gen_device_info *devinfo)
    return NULL;
 }
 
-bool
-gen_perf_load_oa_metrics(struct gen_perf_config *perf, int fd,
+static inline void
+add_stat_reg(struct gen_perf_query_info *query, uint32_t reg,
+             uint32_t numerator, uint32_t denominator,
+             const char *name, const char *description)
+{
+   struct gen_perf_query_counter *counter;
+
+   assert(query->n_counters < query->max_counters);
+
+   counter = &query->counters[query->n_counters];
+   counter->name = name;
+   counter->desc = description;
+   counter->type = GEN_PERF_COUNTER_TYPE_RAW;
+   counter->data_type = GEN_PERF_COUNTER_DATA_TYPE_UINT64;
+   counter->offset = sizeof(uint64_t) * query->n_counters;
+   counter->pipeline_stat.reg = reg;
+   counter->pipeline_stat.numerator = numerator;
+   counter->pipeline_stat.denominator = denominator;
+
+   query->n_counters++;
+}
+
+static inline void
+add_basic_stat_reg(struct gen_perf_query_info *query,
+                                       uint32_t reg, const char *name)
+{
+   add_stat_reg(query, reg, 1, 1, name, name);
+}
+
+static void
+load_pipeline_statistic_metrics(struct gen_perf_config *perf_cfg,
+                                         const struct gen_device_info *devinfo)
+{
+   struct gen_perf_query_info *query =
+      append_query_info(perf_cfg, MAX_STAT_COUNTERS);
+
+   query->kind = GEN_PERF_QUERY_TYPE_PIPELINE;
+   query->name = "Pipeline Statistics Registers";
+
+   add_basic_stat_reg(query, IA_VERTICES_COUNT,
+                                          "N vertices submitted");
+   add_basic_stat_reg(query, IA_PRIMITIVES_COUNT,
+                                          "N primitives submitted");
+   add_basic_stat_reg(query, VS_INVOCATION_COUNT,
+                                          "N vertex shader invocations");
+
+   if (devinfo->gen == 6) {
+      add_stat_reg(query, GEN6_SO_PRIM_STORAGE_NEEDED, 1, 1,
+                   "SO_PRIM_STORAGE_NEEDED",
+                   "N geometry shader stream-out primitives (total)");
+      add_stat_reg(query, GEN6_SO_NUM_PRIMS_WRITTEN, 1, 1,
+                   "SO_NUM_PRIMS_WRITTEN",
+                   "N geometry shader stream-out primitives (written)");
+   } else {
+      add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(0), 1, 1,
+                   "SO_PRIM_STORAGE_NEEDED (Stream 0)",
+                   "N stream-out (stream 0) primitives (total)");
+      add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(1), 1, 1,
+                   "SO_PRIM_STORAGE_NEEDED (Stream 1)",
+                   "N stream-out (stream 1) primitives (total)");
+      add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(2), 1, 1,
+                   "SO_PRIM_STORAGE_NEEDED (Stream 2)",
+                   "N stream-out (stream 2) primitives (total)");
+      add_stat_reg(query, GEN7_SO_PRIM_STORAGE_NEEDED(3), 1, 1,
+                   "SO_PRIM_STORAGE_NEEDED (Stream 3)",
+                   "N stream-out (stream 3) primitives (total)");
+      add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(0), 1, 1,
+                   "SO_NUM_PRIMS_WRITTEN (Stream 0)",
+                   "N stream-out (stream 0) primitives (written)");
+      add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(1), 1, 1,
+                   "SO_NUM_PRIMS_WRITTEN (Stream 1)",
+                   "N stream-out (stream 1) primitives (written)");
+      add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(2), 1, 1,
+                   "SO_NUM_PRIMS_WRITTEN (Stream 2)",
+                   "N stream-out (stream 2) primitives (written)");
+      add_stat_reg(query, GEN7_SO_NUM_PRIMS_WRITTEN(3), 1, 1,
+                   "SO_NUM_PRIMS_WRITTEN (Stream 3)",
+                   "N stream-out (stream 3) primitives (written)");
+   }
+
+   add_basic_stat_reg(query, HS_INVOCATION_COUNT,
+                                          "N TCS shader invocations");
+   add_basic_stat_reg(query, DS_INVOCATION_COUNT,
+                                          "N TES shader invocations");
+
+   add_basic_stat_reg(query, GS_INVOCATION_COUNT,
+                                          "N geometry shader invocations");
+   add_basic_stat_reg(query, GS_PRIMITIVES_COUNT,
+                                          "N geometry shader primitives emitted");
+
+   add_basic_stat_reg(query, CL_INVOCATION_COUNT,
+                                          "N primitives entering clipping");
+   add_basic_stat_reg(query, CL_PRIMITIVES_COUNT,
+                                          "N primitives leaving clipping");
+
+   if (devinfo->is_haswell || devinfo->gen == 8) {
+      add_stat_reg(query, PS_INVOCATION_COUNT, 1, 4,
+                   "N fragment shader invocations",
+                   "N fragment shader invocations");
+   } else {
+      add_basic_stat_reg(query, PS_INVOCATION_COUNT,
+                                             "N fragment shader invocations");
+   }
+
+   add_basic_stat_reg(query, PS_DEPTH_COUNT,
+                                          "N z-pass fragments");
+
+   if (devinfo->gen >= 7) {
+      add_basic_stat_reg(query, CS_INVOCATION_COUNT,
+                                             "N compute shader invocations");
+   }
+
+   query->data_size = sizeof(uint64_t) * query->n_counters;
+}
+
+static bool
+load_oa_metrics(struct gen_perf_config *perf, int fd,
                          const struct gen_device_info *devinfo)
 {
    perf_register_oa_queries_t oa_register = get_register_queries_function(devinfo);
@@ -560,6 +721,62 @@ gen_perf_query_result_clear(struct gen_perf_query_result *result)
    result->hw_id = 0xffffffff; /* invalid */
 }
 
+static void
+gen_perf_query_register_mdapi_statistic_query(struct gen_perf_config *perf_cfg,
+                                              const struct gen_device_info *devinfo)
+{
+   if (!(devinfo->gen >= 7 && devinfo->gen <= 11))
+      return;
+
+   struct gen_perf_query_info *query =
+      append_query_info(perf_cfg, MAX_STAT_COUNTERS);
+
+   query->kind = GEN_PERF_QUERY_TYPE_PIPELINE;
+   query->name = "Intel_Raw_Pipeline_Statistics_Query";
+
+   /* The order has to match mdapi_pipeline_metrics. */
+   add_basic_stat_reg(query, IA_VERTICES_COUNT,
+                      "N vertices submitted");
+   add_basic_stat_reg(query, IA_PRIMITIVES_COUNT,
+                      "N primitives submitted");
+   add_basic_stat_reg(query, VS_INVOCATION_COUNT,
+                      "N vertex shader invocations");
+   add_basic_stat_reg(query, GS_INVOCATION_COUNT,
+                      "N geometry shader invocations");
+   add_basic_stat_reg(query, GS_PRIMITIVES_COUNT,
+                      "N geometry shader primitives emitted");
+   add_basic_stat_reg(query, CL_INVOCATION_COUNT,
+                      "N primitives entering clipping");
+   add_basic_stat_reg(query, CL_PRIMITIVES_COUNT,
+                      "N primitives leaving clipping");
+   if (devinfo->is_haswell || devinfo->gen == 8) {
+      add_stat_reg(query, PS_INVOCATION_COUNT, 1, 4,
+                   "N fragment shader invocations",
+                   "N fragment shader invocations");
+   } else {
+      add_basic_stat_reg(query, PS_INVOCATION_COUNT,
+                         "N fragment shader invocations");
+   }
+   add_basic_stat_reg(query, HS_INVOCATION_COUNT,
+                      "N TCS shader invocations");
+   add_basic_stat_reg(query, DS_INVOCATION_COUNT,
+                      "N TES shader invocations");
+   if (devinfo->gen >= 7) {
+      add_basic_stat_reg(query, CS_INVOCATION_COUNT,
+                         "N compute shader invocations");
+   }
+
+   if (devinfo->gen >= 10) {
+      /* Reuse existing CS invocation register until we can expose this new
+       * one.
+       */
+      add_basic_stat_reg(query, CS_INVOCATION_COUNT,
+                         "Reserved1");
+   }
+
+   query->data_size = sizeof(uint64_t) * query->n_counters;
+}
+
 static void
 fill_mdapi_perf_query_counter(struct gen_perf_query_info *query,
                               const char *name,
@@ -596,9 +813,9 @@ fill_mdapi_perf_query_counter(struct gen_perf_query_info *query,
                                  sizeof(struct_name.field_name[0]),     \
                                  GEN_PERF_COUNTER_DATA_TYPE_##type_name)
 
-void
-gen_perf_query_register_mdapi_oa_query(const struct gen_device_info *devinfo,
-                                       struct gen_perf_config *perf)
+static void
+register_mdapi_oa_query(const struct gen_device_info *devinfo,
+                        struct gen_perf_config *perf)
 {
    struct gen_perf_query_info *query = NULL;
 
@@ -610,7 +827,7 @@ gen_perf_query_register_mdapi_oa_query(const struct gen_device_info *devinfo,
 
    switch (devinfo->gen) {
    case 7: {
-      query = gen_perf_query_append_query_info(perf, 1 + 45 + 16 + 7);
+      query = append_query_info(perf, 1 + 45 + 16 + 7);
       query->oa_format = I915_OA_FORMAT_A45_B8_C8;
 
       struct gen7_mdapi_metrics metric_data;
@@ -635,7 +852,7 @@ gen_perf_query_register_mdapi_oa_query(const struct gen_device_info *devinfo,
       break;
    }
    case 8: {
-      query = gen_perf_query_append_query_info(perf, 2 + 36 + 16 + 16);
+      query = append_query_info(perf, 2 + 36 + 16 + 16);
       query->oa_format = I915_OA_FORMAT_A32u40_A4u32_B8_C8;
 
       struct gen8_mdapi_metrics metric_data;
@@ -672,7 +889,7 @@ gen_perf_query_register_mdapi_oa_query(const struct gen_device_info *devinfo,
    case 9:
    case 10:
    case 11: {
-      query = gen_perf_query_append_query_info(perf, 2 + 36 + 16 + 16 + 16 + 2);
+      query = append_query_info(perf, 2 + 36 + 16 + 16 + 16 + 2);
       query->oa_format = I915_OA_FORMAT_A32u40_A4u32_B8_C8;
 
       struct gen9_mdapi_metrics metric_data;
@@ -734,62 +951,6 @@ gen_perf_query_register_mdapi_oa_query(const struct gen_device_info *devinfo,
    }
 }
 
-void
-gen_perf_query_register_mdapi_statistic_query(const struct gen_device_info *devinfo,
-                                              struct gen_perf_config *perf)
-{
-   if (!(devinfo->gen >= 7 && devinfo->gen <= 11))
-      return;
-
-   struct gen_perf_query_info *query =
-      gen_perf_query_append_query_info(perf, MAX_STAT_COUNTERS);
-
-   query->kind = GEN_PERF_QUERY_TYPE_PIPELINE;
-   query->name = "Intel_Raw_Pipeline_Statistics_Query";
-
-   /* The order has to match mdapi_pipeline_metrics. */
-   gen_perf_query_info_add_basic_stat_reg(query, IA_VERTICES_COUNT,
-                                          "N vertices submitted");
-   gen_perf_query_info_add_basic_stat_reg(query, IA_PRIMITIVES_COUNT,
-                                          "N primitives submitted");
-   gen_perf_query_info_add_basic_stat_reg(query, VS_INVOCATION_COUNT,
-                                          "N vertex shader invocations");
-   gen_perf_query_info_add_basic_stat_reg(query, GS_INVOCATION_COUNT,
-                                          "N geometry shader invocations");
-   gen_perf_query_info_add_basic_stat_reg(query, GS_PRIMITIVES_COUNT,
-                                          "N geometry shader primitives emitted");
-   gen_perf_query_info_add_basic_stat_reg(query, CL_INVOCATION_COUNT,
-                                          "N primitives entering clipping");
-   gen_perf_query_info_add_basic_stat_reg(query, CL_PRIMITIVES_COUNT,
-                                          "N primitives leaving clipping");
-   if (devinfo->is_haswell || devinfo->gen == 8) {
-      gen_perf_query_info_add_stat_reg(query, PS_INVOCATION_COUNT, 1, 4,
-                                       "N fragment shader invocations",
-                                       "N fragment shader invocations");
-   } else {
-      gen_perf_query_info_add_basic_stat_reg(query, PS_INVOCATION_COUNT,
-                                             "N fragment shader invocations");
-   }
-   gen_perf_query_info_add_basic_stat_reg(query, HS_INVOCATION_COUNT,
-                                          "N TCS shader invocations");
-   gen_perf_query_info_add_basic_stat_reg(query, DS_INVOCATION_COUNT,
-                                          "N TES shader invocations");
-   if (devinfo->gen >= 7) {
-      gen_perf_query_info_add_basic_stat_reg(query, CS_INVOCATION_COUNT,
-                                             "N compute shader invocations");
-   }
-
-   if (devinfo->gen >= 10) {
-      /* Reuse existing CS invocation register until we can expose this new
-       * one.
-       */
-      gen_perf_query_info_add_basic_stat_reg(query, CS_INVOCATION_COUNT,
-                                             "Reserved1");
-   }
-
-   query->data_size = sizeof(uint64_t) * query->n_counters;
-}
-
 uint64_t
 gen_perf_query_get_metric_id(struct gen_perf_config *perf,
                              const struct gen_perf_query_info *query)
@@ -918,3 +1079,1053 @@ gen_perf_close(struct gen_perf_context *perfquery,
       raw_query->oa_metrics_set_id = 0;
    }
 }
+
+bool
+gen_perf_open(struct gen_perf_context *perf_ctx,
+              int metrics_set_id,
+              int report_format,
+              int period_exponent,
+              int drm_fd,
+              uint32_t ctx_id)
+{
+   uint64_t properties[] = {
+      /* Single context sampling */
+      DRM_I915_PERF_PROP_CTX_HANDLE, ctx_id,
+
+      /* Include OA reports in samples */
+      DRM_I915_PERF_PROP_SAMPLE_OA, true,
+
+      /* OA unit configuration */
+      DRM_I915_PERF_PROP_OA_METRICS_SET, metrics_set_id,
+      DRM_I915_PERF_PROP_OA_FORMAT, report_format,
+      DRM_I915_PERF_PROP_OA_EXPONENT, period_exponent,
+   };
+   struct drm_i915_perf_open_param param = {
+      .flags = I915_PERF_FLAG_FD_CLOEXEC |
+               I915_PERF_FLAG_FD_NONBLOCK |
+               I915_PERF_FLAG_DISABLED,
+      .num_properties = ARRAY_SIZE(properties) / 2,
+      .properties_ptr = (uintptr_t) properties,
+   };
+   int fd = gen_ioctl(drm_fd, DRM_IOCTL_I915_PERF_OPEN, &param);
+   if (fd == -1) {
+      DBG("Error opening gen perf OA stream: %m\n");
+      return false;
+   }
+
+   perf_ctx->oa_stream_fd = fd;
+
+   perf_ctx->current_oa_metrics_set_id = metrics_set_id;
+   perf_ctx->current_oa_format = report_format;
+
+   return true;
+}
+
+bool
+gen_perf_inc_n_users(struct gen_perf_context *perf_ctx)
+{
+   if (perf_ctx->n_oa_users == 0 &&
+       gen_ioctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_ENABLE, 0) < 0)
+   {
+      return false;
+   }
+   ++perf_ctx->n_oa_users;
+
+   return true;
+}
+
+void
+gen_perf_dec_n_users(struct gen_perf_context *perf_ctx)
+{
+   /* Disabling the i915 perf stream will effectively disable the OA
+    * counters.  Note it's important to be sure there are no outstanding
+    * MI_RPC commands at this point since they could stall the CS
+    * indefinitely once OACONTROL is disabled.
+    */
+   --perf_ctx->n_oa_users;
+   if (perf_ctx->n_oa_users == 0 &&
+       gen_ioctl(perf_ctx->oa_stream_fd, I915_PERF_IOCTL_DISABLE, 0) < 0)
+   {
+      DBG("WARNING: Error disabling gen perf stream: %m\n");
+   }
+}
+
+void
+gen_perf_init_metrics(struct gen_perf_config *perf_cfg,
+                      const struct gen_device_info *devinfo,
+                      int drm_fd)
+{
+   load_pipeline_statistic_metrics(perf_cfg, devinfo);
+   gen_perf_query_register_mdapi_statistic_query(perf_cfg, devinfo);
+   if (load_oa_metrics(perf_cfg, drm_fd, devinfo))
+      register_mdapi_oa_query(devinfo, perf_cfg);
+}
+
+void
+gen_perf_init_context(struct gen_perf_context *perf_ctx,
+                      struct gen_perf_config *perf_cfg,
+                      void * ctx,  /* driver context (eg, brw_context) */
+                      void * bufmgr,  /* eg brw_bufmgr */
+                      const struct gen_device_info *devinfo,
+                      uint32_t hw_ctx,
+                      int drm_fd)
+{
+   perf_ctx->perf = perf_cfg;
+   perf_ctx->ctx = ctx;
+   perf_ctx->bufmgr = bufmgr;
+   perf_ctx->drm_fd = drm_fd;
+   perf_ctx->hw_ctx = hw_ctx;
+   perf_ctx->devinfo = devinfo;
+
+   perf_ctx->unaccumulated =
+      ralloc_array(ctx, struct gen_perf_query_object *, 2);
+   perf_ctx->unaccumulated_elements = 0;
+   perf_ctx->unaccumulated_array_size = 2;
+
+   exec_list_make_empty(&perf_ctx->sample_buffers);
+   exec_list_make_empty(&perf_ctx->free_sample_buffers);
+
+   /* It's convenient to guarantee that this linked list of sample
+    * buffers is never empty so we add an empty head so when we
+    * Begin an OA query we can always take a reference on a buffer
+    * in this list.
+    */
+   struct oa_sample_buf *buf = gen_perf_get_free_sample_buf(perf_ctx);
+   exec_list_push_head(&perf_ctx->sample_buffers, &buf->link);
+
+   perf_ctx->oa_stream_fd = -1;
+   perf_ctx->next_query_start_report_id = 1000;
+}
+
+/**
+ * Add a query to the global list of "unaccumulated queries."
+ *
+ * Queries are tracked here until all the associated OA reports have
+ * been accumulated via accumulate_oa_reports() after the end
+ * MI_REPORT_PERF_COUNT has landed in query->oa.bo.
+ */
+static void
+add_to_unaccumulated_query_list(struct gen_perf_context *perf_ctx,
+                                struct gen_perf_query_object *obj)
+{
+   if (perf_ctx->unaccumulated_elements >=
+       perf_ctx->unaccumulated_array_size)
+   {
+      perf_ctx->unaccumulated_array_size *= 1.5;
+      perf_ctx->unaccumulated =
+         reralloc(perf_ctx->ctx, perf_ctx->unaccumulated,
+                  struct gen_perf_query_object *,
+                  perf_ctx->unaccumulated_array_size);
+   }
+
+   perf_ctx->unaccumulated[perf_ctx->unaccumulated_elements++] = obj;
+}
+
+bool
+gen_perf_begin_query(struct gen_perf_context *perf_ctx,
+                     struct gen_perf_query_object *query)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+   const struct gen_perf_query_info *queryinfo = query->queryinfo;
+
+   /* XXX: We have to consider that the command parser unit that parses batch
+    * buffer commands and is used to capture begin/end counter snapshots isn't
+    * implicitly synchronized with what's currently running across other GPU
+    * units (such as the EUs running shaders) that the performance counters are
+    * associated with.
+    *
+    * The intention of performance queries is to measure the work associated
+    * with commands between the begin/end delimiters and so for that to be the
+    * case we need to explicitly synchronize the parsing of commands to capture
+    * Begin/End counter snapshots with what's running across other parts of the
+    * GPU.
+    *
+    * When the command parser reaches a Begin marker it effectively needs to
+    * drain everything currently running on the GPU until the hardware is idle
+    * before capturing the first snapshot of counters - otherwise the results
+    * would also be measuring the effects of earlier commands.
+    *
+    * When the command parser reaches an End marker it needs to stall until
+    * everything currently running on the GPU has finished before capturing the
+    * end snapshot - otherwise the results won't be a complete representation
+    * of the work.
+    *
+    * Theoretically there could be opportunities to minimize how much of the
+    * GPU pipeline is drained, or that we stall for, when we know what specific
+    * units the performance counters being queried relate to but we don't
+    * currently attempt to be clever here.
+    *
+    * Note: with our current simple approach here then for back-to-back queries
+    * we will redundantly emit duplicate commands to synchronize the command
+    * streamer with the rest of the GPU pipeline, but we assume that in HW the
+    * second synchronization is effectively a NOOP.
+    *
+    * N.B. The final results are based on deltas of counters between (inside)
+    * Begin/End markers so even though the total wall clock time of the
+    * workload is stretched by larger pipeline bubbles the bubbles themselves
+    * are generally invisible to the query results. Whether that's a good or a
+    * bad thing depends on the use case. For a lower real-time impact while
+    * capturing metrics then periodic sampling may be a better choice than
+    * INTEL_performance_query.
+    *
+    *
+    * This is our Begin synchronization point to drain current work on the
+    * GPU before we capture our first counter snapshot...
+    */
+   perf_cfg->vtbl.emit_mi_flush(perf_ctx->ctx);
+
+   switch (queryinfo->kind) {
+   case GEN_PERF_QUERY_TYPE_OA:
+   case GEN_PERF_QUERY_TYPE_RAW: {
+
+      /* Opening an i915 perf stream implies exclusive access to the OA unit
+       * which will generate counter reports for a specific counter set with a
+       * specific layout/format so we can't begin any OA based queries that
+       * require a different counter set or format unless we get an opportunity
+       * to close the stream and open a new one...
+       */
+      uint64_t metric_id = gen_perf_query_get_metric_id(perf_ctx->perf, queryinfo);
+
+      if (perf_ctx->oa_stream_fd != -1 &&
+          perf_ctx->current_oa_metrics_set_id != metric_id) {
+
+         if (perf_ctx->n_oa_users != 0) {
+            DBG("WARNING: Begin failed already using perf config=%i/%"PRIu64"\n",
+                perf_ctx->current_oa_metrics_set_id, metric_id);
+            return false;
+         } else
+            gen_perf_close(perf_ctx, queryinfo);
+      }
+
+      /* If the OA counters aren't already on, enable them. */
+      if (perf_ctx->oa_stream_fd == -1) {
+         const struct gen_device_info *devinfo = perf_ctx->devinfo;
+
+         /* The period_exponent gives a sampling period as follows:
+          *   sample_period = timestamp_period * 2^(period_exponent + 1)
+          *
+          * The timestamps increments every 80ns (HSW), ~52ns (GEN9LP) or
+          * ~83ns (GEN8/9).
+          *
+          * The counter overflow period is derived from the EuActive counter
+          * which reads a counter that increments by the number of clock
+          * cycles multiplied by the number of EUs. It can be calculated as:
+          *
+          * 2^(number of bits in A counter) / (n_eus * max_gen_freq * 2)
+          *
+          * (E.g. 40 EUs @ 1GHz = ~53ms)
+          *
+          * We select a sampling period inferior to that overflow period to
+          * ensure we cannot see more than 1 counter overflow, otherwise we
+          * could loose information.
+          */
+
+         int a_counter_in_bits = 32;
+         if (devinfo->gen >= 8)
+            a_counter_in_bits = 40;
+
+         uint64_t overflow_period = pow(2, a_counter_in_bits) / (perf_cfg->sys_vars.n_eus *
+             /* drop 1GHz freq to have units in nanoseconds */
+             2);
+
+         DBG("A counter overflow period: %"PRIu64"ns, %"PRIu64"ms (n_eus=%"PRIu64")\n",
+             overflow_period, overflow_period / 1000000ul, perf_cfg->sys_vars.n_eus);
+
+         int period_exponent = 0;
+         uint64_t prev_sample_period, next_sample_period;
+         for (int e = 0; e < 30; e++) {
+            prev_sample_period = 1000000000ull * pow(2, e + 1) / devinfo->timestamp_frequency;
+            next_sample_period = 1000000000ull * pow(2, e + 2) / devinfo->timestamp_frequency;
+
+            /* Take the previous sampling period, lower than the overflow
+             * period.
+             */
+            if (prev_sample_period < overflow_period &&
+                next_sample_period > overflow_period)
+               period_exponent = e + 1;
+         }
+
+         if (period_exponent == 0) {
+            DBG("WARNING: enable to find a sampling exponent\n");
+            return false;
+         }
+
+         DBG("OA sampling exponent: %i ~= %"PRIu64"ms\n", period_exponent,
+             prev_sample_period / 1000000ul);
+
+         if (!gen_perf_open(perf_ctx, metric_id, queryinfo->oa_format,
+                            period_exponent, perf_ctx->drm_fd,
+                            perf_ctx->hw_ctx))
+            return false;
+      } else {
+         assert(perf_ctx->current_oa_metrics_set_id == metric_id &&
+                perf_ctx->current_oa_format == queryinfo->oa_format);
+      }
+
+      if (!gen_perf_inc_n_users(perf_ctx)) {
+         DBG("WARNING: Error enabling i915 perf stream: %m\n");
+         return false;
+      }
+
+      if (query->oa.bo) {
+         perf_cfg->vtbl.bo_unreference(query->oa.bo);
+         query->oa.bo = NULL;
+      }
+
+      query->oa.bo = perf_cfg->vtbl.bo_alloc(perf_ctx->bufmgr,
+                                             "perf. query OA MI_RPC bo",
+                                             MI_RPC_BO_SIZE);
+#ifdef DEBUG
+      /* Pre-filling the BO helps debug whether writes landed. */
+      void *map = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->oa.bo, MAP_WRITE);
+      memset(map, 0x80, MI_RPC_BO_SIZE);
+      perf_cfg->vtbl.bo_unmap(query->oa.bo);
+#endif
+
+      query->oa.begin_report_id = perf_ctx->next_query_start_report_id;
+      perf_ctx->next_query_start_report_id += 2;
+
+      /* We flush the batchbuffer here to minimize the chances that MI_RPC
+       * delimiting commands end up in different batchbuffers. If that's the
+       * case, the measurement will include the time it takes for the kernel
+       * scheduler to load a new request into the hardware. This is manifested in
+       * tools like frameretrace by spikes in the "GPU Core Clocks" counter.
+       */
+      perf_cfg->vtbl.batchbuffer_flush(perf_ctx->ctx, __FILE__, __LINE__);
+
+      /* Take a starting OA counter snapshot. */
+      perf_cfg->vtbl.emit_mi_report_perf_count(perf_ctx->ctx, query->oa.bo, 0,
+                                               query->oa.begin_report_id);
+      perf_cfg->vtbl.capture_frequency_stat_register(perf_ctx->ctx, query->oa.bo,
+                                                     MI_FREQ_START_OFFSET_BYTES);
+
+      ++perf_ctx->n_active_oa_queries;
+
+      /* No already-buffered samples can possibly be associated with this query
+       * so create a marker within the list of sample buffers enabling us to
+       * easily ignore earlier samples when processing this query after
+       * completion.
+       */
+      assert(!exec_list_is_empty(&perf_ctx->sample_buffers));
+      query->oa.samples_head = exec_list_get_tail(&perf_ctx->sample_buffers);
+
+      struct oa_sample_buf *buf =
+         exec_node_data(struct oa_sample_buf, query->oa.samples_head, link);
+
+      /* This reference will ensure that future/following sample
+       * buffers (that may relate to this query) can't be freed until
+       * this drops to zero.
+       */
+      buf->refcount++;
+
+      gen_perf_query_result_clear(&query->oa.result);
+      query->oa.results_accumulated = false;
+
+      add_to_unaccumulated_query_list(perf_ctx, query);
+      break;
+   }
+
+   case GEN_PERF_QUERY_TYPE_PIPELINE:
+      if (query->pipeline_stats.bo) {
+         perf_cfg->vtbl.bo_unreference(query->pipeline_stats.bo);
+         query->pipeline_stats.bo = NULL;
+      }
+
+      query->pipeline_stats.bo =
+         perf_cfg->vtbl.bo_alloc(perf_ctx->bufmgr,
+                                 "perf. query pipeline stats bo",
+                                 STATS_BO_SIZE);
+
+      /* Take starting snapshots. */
+      gen_perf_snapshot_statistics_registers(perf_ctx->ctx , perf_cfg, query, 0);
+
+      ++perf_ctx->n_active_pipeline_stats_queries;
+      break;
+
+   default:
+      unreachable("Unknown query type");
+      break;
+   }
+
+   return true;
+}
+
+void
+gen_perf_end_query(struct gen_perf_context *perf_ctx,
+                   struct gen_perf_query_object *query)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+
+   /* Ensure that the work associated with the queried commands will have
+    * finished before taking our query end counter readings.
+    *
+    * For more details see comment in brw_begin_perf_query for
+    * corresponding flush.
+    */
+  perf_cfg->vtbl.emit_mi_flush(perf_ctx->ctx);
+
+   switch (query->queryinfo->kind) {
+   case GEN_PERF_QUERY_TYPE_OA:
+   case GEN_PERF_QUERY_TYPE_RAW:
+
+      /* NB: It's possible that the query will have already been marked
+       * as 'accumulated' if an error was seen while reading samples
+       * from perf. In this case we mustn't try and emit a closing
+       * MI_RPC command in case the OA unit has already been disabled
+       */
+      if (!query->oa.results_accumulated) {
+         /* Take an ending OA counter snapshot. */
+         perf_cfg->vtbl.capture_frequency_stat_register(perf_ctx->ctx, query->oa.bo,
+                                                     MI_FREQ_END_OFFSET_BYTES);
+         perf_cfg->vtbl.emit_mi_report_perf_count(perf_ctx->ctx, query->oa.bo,
+                                             MI_RPC_BO_END_OFFSET_BYTES,
+                                             query->oa.begin_report_id + 1);
+      }
+
+      --perf_ctx->n_active_oa_queries;
+
+      /* NB: even though the query has now ended, it can't be accumulated
+       * until the end MI_REPORT_PERF_COUNT snapshot has been written
+       * to query->oa.bo
+       */
+      break;
+
+   case GEN_PERF_QUERY_TYPE_PIPELINE:
+      gen_perf_snapshot_statistics_registers(perf_ctx->ctx, perf_cfg, query,
+                                             STATS_BO_END_OFFSET_BYTES);
+      --perf_ctx->n_active_pipeline_stats_queries;
+      break;
+
+   default:
+      unreachable("Unknown query type");
+      break;
+   }
+}
+
+enum OaReadStatus {
+   OA_READ_STATUS_ERROR,
+   OA_READ_STATUS_UNFINISHED,
+   OA_READ_STATUS_FINISHED,
+};
+
+static enum OaReadStatus
+read_oa_samples_until(struct gen_perf_context *perf_ctx,
+                      uint32_t start_timestamp,
+                      uint32_t end_timestamp)
+{
+   struct exec_node *tail_node =
+      exec_list_get_tail(&perf_ctx->sample_buffers);
+   struct oa_sample_buf *tail_buf =
+      exec_node_data(struct oa_sample_buf, tail_node, link);
+   uint32_t last_timestamp = tail_buf->last_timestamp;
+
+   while (1) {
+      struct oa_sample_buf *buf = gen_perf_get_free_sample_buf(perf_ctx);
+      uint32_t offset;
+      int len;
+
+      while ((len = read(perf_ctx->oa_stream_fd, buf->buf,
+                         sizeof(buf->buf))) < 0 && errno == EINTR)
+         ;
+
+      if (len <= 0) {
+         exec_list_push_tail(&perf_ctx->free_sample_buffers, &buf->link);
+
+         if (len < 0) {
+            if (errno == EAGAIN)
+               return ((last_timestamp - start_timestamp) >=
+                       (end_timestamp - start_timestamp)) ?
+                      OA_READ_STATUS_FINISHED :
+                      OA_READ_STATUS_UNFINISHED;
+            else {
+               DBG("Error reading i915 perf samples: %m\n");
+            }
+         } else
+            DBG("Spurious EOF reading i915 perf samples\n");
+
+         return OA_READ_STATUS_ERROR;
+      }
+
+      buf->len = len;
+      exec_list_push_tail(&perf_ctx->sample_buffers, &buf->link);
+
+      /* Go through the reports and update the last timestamp. */
+      offset = 0;
+      while (offset < buf->len) {
+         const struct drm_i915_perf_record_header *header =
+            (const struct drm_i915_perf_record_header *) &buf->buf[offset];
+         uint32_t *report = (uint32_t *) (header + 1);
+
+         if (header->type == DRM_I915_PERF_RECORD_SAMPLE)
+            last_timestamp = report[1];
+
+         offset += header->size;
+      }
+
+      buf->last_timestamp = last_timestamp;
+   }
+
+   unreachable("not reached");
+   return OA_READ_STATUS_ERROR;
+}
+
+/**
+ * Try to read all the reports until either the delimiting timestamp
+ * or an error arises.
+ */
+static bool
+read_oa_samples_for_query(struct gen_perf_context *perf_ctx,
+                          struct gen_perf_query_object *query,
+                          void *current_batch)
+{
+   uint32_t *start;
+   uint32_t *last;
+   uint32_t *end;
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+
+   /* We need the MI_REPORT_PERF_COUNT to land before we can start
+    * accumulate. */
+   assert(!perf_cfg->vtbl.batch_references(current_batch, query->oa.bo) &&
+          !perf_cfg->vtbl.bo_busy(query->oa.bo));
+
+   /* Map the BO once here and let accumulate_oa_reports() unmap
+    * it. */
+   if (query->oa.map == NULL)
+      query->oa.map = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->oa.bo, MAP_READ);
+
+   start = last = query->oa.map;
+   end = query->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
+
+   if (start[0] != query->oa.begin_report_id) {
+      DBG("Spurious start report id=%"PRIu32"\n", start[0]);
+      return true;
+   }
+   if (end[0] != (query->oa.begin_report_id + 1)) {
+      DBG("Spurious end report id=%"PRIu32"\n", end[0]);
+      return true;
+   }
+
+   /* Read the reports until the end timestamp. */
+   switch (read_oa_samples_until(perf_ctx, start[1], end[1])) {
+   case OA_READ_STATUS_ERROR:
+      /* Fallthrough and let accumulate_oa_reports() deal with the
+       * error. */
+   case OA_READ_STATUS_FINISHED:
+      return true;
+   case OA_READ_STATUS_UNFINISHED:
+      return false;
+   }
+
+   unreachable("invalid read status");
+   return false;
+}
+
+void
+gen_perf_wait_query(struct gen_perf_context *perf_ctx,
+                    struct gen_perf_query_object *query,
+                    void *current_batch)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+   struct brw_bo *bo = NULL;
+
+   switch (query->queryinfo->kind) {
+   case GEN_PERF_QUERY_TYPE_OA:
+   case GEN_PERF_QUERY_TYPE_RAW:
+      bo = query->oa.bo;
+      break;
+
+   case GEN_PERF_QUERY_TYPE_PIPELINE:
+      bo = query->pipeline_stats.bo;
+      break;
+
+   default:
+      unreachable("Unknown query type");
+      break;
+   }
+
+   if (bo == NULL)
+      return;
+
+   /* If the current batch references our results bo then we need to
+    * flush first...
+    */
+   if (perf_cfg->vtbl.batch_references(current_batch, bo))
+      perf_cfg->vtbl.batchbuffer_flush(perf_ctx->ctx, __FILE__, __LINE__);
+
+   perf_cfg->vtbl.bo_wait_rendering(bo);
+
+   /* Due to a race condition between the OA unit signaling report
+    * availability and the report actually being written into memory,
+    * we need to wait for all the reports to come in before we can
+    * read them.
+    */
+   if (query->queryinfo->kind == GEN_PERF_QUERY_TYPE_OA ||
+       query->queryinfo->kind == GEN_PERF_QUERY_TYPE_RAW) {
+      while (!read_oa_samples_for_query(perf_ctx, query, current_batch))
+         ;
+   }
+}
+
+bool
+gen_perf_is_query_ready(struct gen_perf_context *perf_ctx,
+                        struct gen_perf_query_object *query,
+                        void *current_batch)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+
+   switch (query->queryinfo->kind) {
+   case GEN_PERF_QUERY_TYPE_OA:
+   case GEN_PERF_QUERY_TYPE_RAW:
+      return (query->oa.results_accumulated ||
+              (query->oa.bo &&
+               !perf_cfg->vtbl.batch_references(current_batch, query->oa.bo) &&
+               !perf_cfg->vtbl.bo_busy(query->oa.bo) &&
+               read_oa_samples_for_query(perf_ctx, query, current_batch)));
+   case GEN_PERF_QUERY_TYPE_PIPELINE:
+      return (query->pipeline_stats.bo &&
+              !perf_cfg->vtbl.batch_references(current_batch, query->pipeline_stats.bo) &&
+              !perf_cfg->vtbl.bo_busy(query->pipeline_stats.bo));
+
+   default:
+      unreachable("Unknown query type");
+      break;
+   }
+
+   return false;
+}
+
+/**
+ * Remove a query from the global list of unaccumulated queries once
+ * after successfully accumulating the OA reports associated with the
+ * query in accumulate_oa_reports() or when discarding unwanted query
+ * results.
+ */
+static void
+drop_from_unaccumulated_query_list(struct gen_perf_context *perf_ctx,
+                                   struct gen_perf_query_object *query)
+{
+   for (int i = 0; i < perf_ctx->unaccumulated_elements; i++) {
+      if (perf_ctx->unaccumulated[i] == query) {
+         int last_elt = --perf_ctx->unaccumulated_elements;
+
+         if (i == last_elt)
+            perf_ctx->unaccumulated[i] = NULL;
+         else {
+            perf_ctx->unaccumulated[i] =
+               perf_ctx->unaccumulated[last_elt];
+         }
+
+         break;
+      }
+   }
+
+   /* Drop our samples_head reference so that associated periodic
+    * sample data buffers can potentially be reaped if they aren't
+    * referenced by any other queries...
+    */
+
+   struct oa_sample_buf *buf =
+      exec_node_data(struct oa_sample_buf, query->oa.samples_head, link);
+
+   assert(buf->refcount > 0);
+   buf->refcount--;
+
+   query->oa.samples_head = NULL;
+
+   gen_perf_reap_old_sample_buffers(perf_ctx);
+}
+
+/* In general if we see anything spurious while accumulating results,
+ * we don't try and continue accumulating the current query, hoping
+ * for the best, we scrap anything outstanding, and then hope for the
+ * best with new queries.
+ */
+static void
+discard_all_queries(struct gen_perf_context *perf_ctx)
+{
+   while (perf_ctx->unaccumulated_elements) {
+      struct gen_perf_query_object *query = perf_ctx->unaccumulated[0];
+
+      query->oa.results_accumulated = true;
+      drop_from_unaccumulated_query_list(perf_ctx, query);
+
+      gen_perf_dec_n_users(perf_ctx);
+   }
+}
+
+/**
+ * Accumulate raw OA counter values based on deltas between pairs of
+ * OA reports.
+ *
+ * Accumulation starts from the first report captured via
+ * MI_REPORT_PERF_COUNT (MI_RPC) by brw_begin_perf_query() until the
+ * last MI_RPC report requested by brw_end_perf_query(). Between these
+ * two reports there may also some number of periodically sampled OA
+ * reports collected via the i915 perf interface - depending on the
+ * duration of the query.
+ *
+ * These periodic snapshots help to ensure we handle counter overflow
+ * correctly by being frequent enough to ensure we don't miss multiple
+ * overflows of a counter between snapshots. For Gen8+ the i915 perf
+ * snapshots provide the extra context-switch reports that let us
+ * subtract out the progress of counters associated with other
+ * contexts running on the system.
+ */
+static void
+accumulate_oa_reports(struct gen_perf_context *perf_ctx,
+                      struct gen_perf_query_object *query)
+{
+   const struct gen_device_info *devinfo = perf_ctx->devinfo;
+   uint32_t *start;
+   uint32_t *last;
+   uint32_t *end;
+   struct exec_node *first_samples_node;
+   bool in_ctx = true;
+   int out_duration = 0;
+
+   assert(query->oa.map != NULL);
+
+   start = last = query->oa.map;
+   end = query->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
+
+   if (start[0] != query->oa.begin_report_id) {
+      DBG("Spurious start report id=%"PRIu32"\n", start[0]);
+      goto error;
+   }
+   if (end[0] != (query->oa.begin_report_id + 1)) {
+      DBG("Spurious end report id=%"PRIu32"\n", end[0]);
+      goto error;
+   }
+
+   /* See if we have any periodic reports to accumulate too... */
+
+   /* N.B. The oa.samples_head was set when the query began and
+    * pointed to the tail of the perf_ctx->sample_buffers list at
+    * the time the query started. Since the buffer existed before the
+    * first MI_REPORT_PERF_COUNT command was emitted we therefore know
+    * that no data in this particular node's buffer can possibly be
+    * associated with the query - so skip ahead one...
+    */
+   first_samples_node = query->oa.samples_head->next;
+
+   foreach_list_typed_from(struct oa_sample_buf, buf, link,
+                           &perf_ctx.sample_buffers,
+                           first_samples_node)
+   {
+      int offset = 0;
+
+      while (offset < buf->len) {
+         const struct drm_i915_perf_record_header *header =
+            (const struct drm_i915_perf_record_header *)(buf->buf + offset);
+
+         assert(header->size != 0);
+         assert(header->size <= buf->len);
+
+         offset += header->size;
+
+         switch (header->type) {
+         case DRM_I915_PERF_RECORD_SAMPLE: {
+            uint32_t *report = (uint32_t *)(header + 1);
+            bool add = true;
+
+            /* Ignore reports that come before the start marker.
+             * (Note: takes care to allow overflow of 32bit timestamps)
+             */
+            if (gen_device_info_timebase_scale(devinfo,
+                                               report[1] - start[1]) > 5000000000) {
+               continue;
+            }
+
+            /* Ignore reports that come after the end marker.
+             * (Note: takes care to allow overflow of 32bit timestamps)
+             */
+            if (gen_device_info_timebase_scale(devinfo,
+                                               report[1] - end[1]) <= 5000000000) {
+               goto end;
+            }
+
+            /* For Gen8+ since the counters continue while other
+             * contexts are running we need to discount any unrelated
+             * deltas. The hardware automatically generates a report
+             * on context switch which gives us a new reference point
+             * to continuing adding deltas from.
+             *
+             * For Haswell we can rely on the HW to stop the progress
+             * of OA counters while any other context is acctive.
+             */
+            if (devinfo->gen >= 8) {
+               if (in_ctx && report[2] != query->oa.result.hw_id) {
+                  DBG("i915 perf: Switch AWAY (observed by ID change)\n");
+                  in_ctx = false;
+                  out_duration = 0;
+               } else if (in_ctx == false && report[2] == query->oa.result.hw_id) {
+                  DBG("i915 perf: Switch TO\n");
+                  in_ctx = true;
+
+                  /* From experimentation in IGT, we found that the OA unit
+                   * might label some report as "idle" (using an invalid
+                   * context ID), right after a report for a given context.
+                   * Deltas generated by those reports actually belong to the
+                   * previous context, even though they're not labelled as
+                   * such.
+                   *
+                   * We didn't *really* Switch AWAY in the case that we e.g.
+                   * saw a single periodic report while idle...
+                   */
+                  if (out_duration >= 1)
+                     add = false;
+               } else if (in_ctx) {
+                  assert(report[2] == query->oa.result.hw_id);
+                  DBG("i915 perf: Continuation IN\n");
+               } else {
+                  assert(report[2] != query->oa.result.hw_id);
+                  DBG("i915 perf: Continuation OUT\n");
+                  add = false;
+                  out_duration++;
+               }
+            }
+
+            if (add) {
+               gen_perf_query_result_accumulate(&query->oa.result, query->queryinfo,
+                                                last, report);
+            }
+
+            last = report;
+
+            break;
+         }
+
+         case DRM_I915_PERF_RECORD_OA_BUFFER_LOST:
+             DBG("i915 perf: OA error: all reports lost\n");
+             goto error;
+         case DRM_I915_PERF_RECORD_OA_REPORT_LOST:
+             DBG("i915 perf: OA report lost\n");
+             break;
+         }
+      }
+   }
+
+end:
+
+   gen_perf_query_result_accumulate(&query->oa.result, query->queryinfo,
+                                    last, end);
+
+   query->oa.results_accumulated = true;
+   drop_from_unaccumulated_query_list(perf_ctx, query);
+   gen_perf_dec_n_users(perf_ctx);
+
+   return;
+
+error:
+
+   discard_all_queries(perf_ctx);
+}
+
+void
+gen_perf_delete_query(struct gen_perf_context *perf_ctx,
+                      struct gen_perf_query_object *query)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+
+   /* We can assume that the frontend waits for a query to complete
+    * before ever calling into here, so we don't have to worry about
+    * deleting an in-flight query object.
+    */
+   switch (query->queryinfo->kind) {
+   case GEN_PERF_QUERY_TYPE_OA:
+   case GEN_PERF_QUERY_TYPE_RAW:
+      if (query->oa.bo) {
+         if (!query->oa.results_accumulated) {
+            drop_from_unaccumulated_query_list(perf_ctx, query);
+            gen_perf_dec_n_users(perf_ctx);
+         }
+
+         perf_cfg->vtbl.bo_unreference(query->oa.bo);
+         query->oa.bo = NULL;
+      }
+
+      query->oa.results_accumulated = false;
+      break;
+
+   case GEN_PERF_QUERY_TYPE_PIPELINE:
+      if (query->pipeline_stats.bo) {
+         perf_cfg->vtbl.bo_unreference(query->pipeline_stats.bo);
+         query->pipeline_stats.bo = NULL;
+      }
+      break;
+
+   default:
+      unreachable("Unknown query type");
+      break;
+   }
+
+   /* As an indication that the INTEL_performance_query extension is no
+    * longer in use, it's a good time to free our cache of sample
+    * buffers and close any current i915-perf stream.
+    */
+   if (--perf_ctx->n_query_instances == 0) {
+      gen_perf_free_sample_bufs(perf_ctx);
+      gen_perf_close(perf_ctx, query->queryinfo);
+   }
+
+   free(query);
+}
+
+#define GET_FIELD(word, field) (((word)  & field ## _MASK) >> field ## _SHIFT)
+
+static void
+read_gt_frequency(struct gen_perf_context *perf_ctx,
+                  struct gen_perf_query_object *obj)
+{
+   const struct gen_device_info *devinfo = perf_ctx->devinfo;
+   uint32_t start = *((uint32_t *)(obj->oa.map + MI_FREQ_START_OFFSET_BYTES)),
+      end = *((uint32_t *)(obj->oa.map + MI_FREQ_END_OFFSET_BYTES));
+
+   switch (devinfo->gen) {
+   case 7:
+   case 8:
+      obj->oa.gt_frequency[0] = GET_FIELD(start, GEN7_RPSTAT1_CURR_GT_FREQ) * 50ULL;
+      obj->oa.gt_frequency[1] = GET_FIELD(end, GEN7_RPSTAT1_CURR_GT_FREQ) * 50ULL;
+      break;
+   case 9:
+   case 10:
+   case 11:
+      obj->oa.gt_frequency[0] = GET_FIELD(start, GEN9_RPSTAT0_CURR_GT_FREQ) * 50ULL / 3ULL;
+      obj->oa.gt_frequency[1] = GET_FIELD(end, GEN9_RPSTAT0_CURR_GT_FREQ) * 50ULL / 3ULL;
+      break;
+   default:
+      unreachable("unexpected gen");
+   }
+
+   /* Put the numbers into Hz. */
+   obj->oa.gt_frequency[0] *= 1000000ULL;
+   obj->oa.gt_frequency[1] *= 1000000ULL;
+}
+
+static int
+get_oa_counter_data(struct gen_perf_context *perf_ctx,
+                    struct gen_perf_query_object *query,
+                    size_t data_size,
+                    uint8_t *data)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+   const struct gen_perf_query_info *queryinfo = query->queryinfo;
+   int n_counters = queryinfo->n_counters;
+   int written = 0;
+
+   for (int i = 0; i < n_counters; i++) {
+      const struct gen_perf_query_counter *counter = &queryinfo->counters[i];
+      uint64_t *out_uint64;
+      float *out_float;
+      size_t counter_size = gen_perf_query_counter_get_size(counter);
+
+      if (counter_size) {
+         switch (counter->data_type) {
+         case GEN_PERF_COUNTER_DATA_TYPE_UINT64:
+            out_uint64 = (uint64_t *)(data + counter->offset);
+            *out_uint64 =
+               counter->oa_counter_read_uint64(perf_cfg, queryinfo,
+                                               query->oa.result.accumulator);
+            break;
+         case GEN_PERF_COUNTER_DATA_TYPE_FLOAT:
+            out_float = (float *)(data + counter->offset);
+            *out_float =
+               counter->oa_counter_read_float(perf_cfg, queryinfo,
+                                              query->oa.result.accumulator);
+            break;
+         default:
+            /* So far we aren't using uint32, double or bool32... */
+            unreachable("unexpected counter data type");
+         }
+         written = counter->offset + counter_size;
+      }
+   }
+
+   return written;
+}
+
+static int
+get_pipeline_stats_data(struct gen_perf_context *perf_ctx,
+                        struct gen_perf_query_object *query,
+                        size_t data_size,
+                        uint8_t *data)
+
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+   const struct gen_perf_query_info *queryinfo = query->queryinfo;
+   int n_counters = queryinfo->n_counters;
+   uint8_t *p = data;
+
+   uint64_t *start = perf_cfg->vtbl.bo_map(perf_ctx->ctx, query->pipeline_stats.bo, MAP_READ);
+   uint64_t *end = start + (STATS_BO_END_OFFSET_BYTES / sizeof(uint64_t));
+
+   for (int i = 0; i < n_counters; i++) {
+      const struct gen_perf_query_counter *counter = &queryinfo->counters[i];
+      uint64_t value = end[i] - start[i];
+
+      if (counter->pipeline_stat.numerator !=
+          counter->pipeline_stat.denominator) {
+         value *= counter->pipeline_stat.numerator;
+         value /= counter->pipeline_stat.denominator;
+      }
+
+      *((uint64_t *)p) = value;
+      p += 8;
+   }
+
+   perf_cfg->vtbl.bo_unmap(query->pipeline_stats.bo);
+
+   return p - data;
+}
+
+void
+gen_perf_get_query_data(struct gen_perf_context *perf_ctx,
+                        struct gen_perf_query_object *query,
+                        int data_size,
+                        unsigned *data,
+                        unsigned *bytes_written)
+{
+   struct gen_perf_config *perf_cfg = perf_ctx->perf;
+   int written = 0;
+
+   switch (query->queryinfo->kind) {
+   case GEN_PERF_QUERY_TYPE_OA:
+   case GEN_PERF_QUERY_TYPE_RAW:
+      if (!query->oa.results_accumulated) {
+         read_gt_frequency(perf_ctx, query);
+         uint32_t *begin_report = query->oa.map;
+         uint32_t *end_report = query->oa.map + MI_RPC_BO_END_OFFSET_BYTES;
+         gen_perf_query_result_read_frequencies(&query->oa.result,
+                                                perf_ctx->devinfo,
+                                                begin_report,
+                                                end_report);
+         accumulate_oa_reports(perf_ctx, query);
+         assert(query->oa.results_accumulated);
+
+         perf_cfg->vtbl.bo_unmap(query->oa.bo);
+         query->oa.map = NULL;
+      }
+      if (query->queryinfo->kind == GEN_PERF_QUERY_TYPE_OA) {
+         written = get_oa_counter_data(perf_ctx, query, data_size, (uint8_t *)data);
+      } else {
+         const struct gen_device_info *devinfo = perf_ctx->devinfo;
+
+         written = gen_perf_query_result_write_mdapi((uint8_t *)data, data_size,
+                                                     devinfo, &query->oa.result,
+                                                     query->oa.gt_frequency[0],
+                                                     query->oa.gt_frequency[1]);
+      }
+      break;
+
+   case GEN_PERF_QUERY_TYPE_PIPELINE:
+      written = get_pipeline_stats_data(perf_ctx, query, data_size, (uint8_t *)data);
+      break;
+
+   default:
+      unreachable("Unknown query type");
+      break;
+   }
+
+   if (bytes_written)
+      *bytes_written = written;
+}