b27a685d052ef9169365e9c4679e01c13bdc6d28
[mesa.git] / src / mesa / drivers / dri / i965 / brw_queryobj.c
1 /*
2 * Copyright © 2008 Intel Corporation
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice (including the next
12 * paragraph) shall be included in all copies or substantial portions of the
13 * Software.
14 *
15 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 * IN THE SOFTWARE.
22 *
23 * Authors:
24 * Eric Anholt <eric@anholt.net>
25 *
26 */
27
28 /** @file brw_queryobj.c
29 *
30 * Support for query objects (GL_ARB_occlusion_query, GL_ARB_timer_query,
31 * GL_EXT_transform_feedback, and friends).
32 *
33 * The hardware provides a PIPE_CONTROL command that can report the number of
34 * fragments that passed the depth test, or the hardware timer. They are
35 * appropriately synced with the stage of the pipeline for our extensions'
36 * needs.
37 */
38 #include "util/imports.h"
39 #include "main/queryobj.h"
40
41 #include "brw_context.h"
42 #include "brw_defines.h"
43 #include "brw_state.h"
44 #include "intel_batchbuffer.h"
45
46 /* As best we know currently, the Gen HW timestamps are 36bits across
47 * all platforms, which we need to account for when calculating a
48 * delta to measure elapsed time.
49 *
50 * The timestamps read via glGetTimestamp() / brw_get_timestamp() sometimes
51 * only have 32bits due to a kernel bug and so in that case we make sure to
52 * treat all raw timestamps as 32bits so they overflow consistently and remain
53 * comparable. (Note: the timestamps being passed here are not from the kernel
54 * so we don't need to be taking the upper 32bits in this buggy kernel case we
55 * are just clipping to 32bits here for consistency.)
56 */
57 uint64_t
58 brw_raw_timestamp_delta(struct brw_context *brw, uint64_t time0, uint64_t time1)
59 {
60 if (brw->screen->hw_has_timestamp == 2) {
61 /* Kernel clips timestamps to 32bits in this case, so we also clip
62 * PIPE_CONTROL timestamps for consistency.
63 */
64 return (uint32_t)time1 - (uint32_t)time0;
65 } else {
66 if (time0 > time1) {
67 return (1ULL << 36) + time1 - time0;
68 } else {
69 return time1 - time0;
70 }
71 }
72 }
73
74 /**
75 * Emit PIPE_CONTROLs to write the current GPU timestamp into a buffer.
76 */
77 void
78 brw_write_timestamp(struct brw_context *brw, struct brw_bo *query_bo, int idx)
79 {
80 const struct gen_device_info *devinfo = &brw->screen->devinfo;
81
82 if (devinfo->gen == 6) {
83 /* Emit Sandybridge workaround flush: */
84 brw_emit_pipe_control_flush(brw,
85 PIPE_CONTROL_CS_STALL |
86 PIPE_CONTROL_STALL_AT_SCOREBOARD);
87 }
88
89 uint32_t flags = PIPE_CONTROL_WRITE_TIMESTAMP;
90
91 if (devinfo->gen == 9 && devinfo->gt == 4)
92 flags |= PIPE_CONTROL_CS_STALL;
93
94 brw_emit_pipe_control_write(brw, flags,
95 query_bo, idx * sizeof(uint64_t), 0);
96 }
97
98 /**
99 * Emit PIPE_CONTROLs to write the PS_DEPTH_COUNT register into a buffer.
100 */
101 void
102 brw_write_depth_count(struct brw_context *brw, struct brw_bo *query_bo, int idx)
103 {
104 const struct gen_device_info *devinfo = &brw->screen->devinfo;
105 uint32_t flags = PIPE_CONTROL_WRITE_DEPTH_COUNT | PIPE_CONTROL_DEPTH_STALL;
106
107 if (devinfo->gen == 9 && devinfo->gt == 4)
108 flags |= PIPE_CONTROL_CS_STALL;
109
110 if (devinfo->gen >= 10) {
111 /* "Driver must program PIPE_CONTROL with only Depth Stall Enable bit set
112 * prior to programming a PIPE_CONTROL with Write PS Depth Count Post sync
113 * operation."
114 */
115 brw_emit_pipe_control_flush(brw, PIPE_CONTROL_DEPTH_STALL);
116 }
117
118 brw_emit_pipe_control_write(brw, flags,
119 query_bo, idx * sizeof(uint64_t), 0);
120 }
121
122 /**
123 * Wait on the query object's BO and calculate the final result.
124 */
125 static void
126 brw_queryobj_get_results(struct gl_context *ctx,
127 struct brw_query_object *query)
128 {
129 struct brw_context *brw = brw_context(ctx);
130 UNUSED const struct gen_device_info *devinfo = &brw->screen->devinfo;
131
132 int i;
133 uint64_t *results;
134
135 assert(devinfo->gen < 6);
136
137 if (query->bo == NULL)
138 return;
139
140 /* If the application has requested the query result, but this batch is
141 * still contributing to it, flush it now so the results will be present
142 * when mapped.
143 */
144 if (brw_batch_references(&brw->batch, query->bo))
145 intel_batchbuffer_flush(brw);
146
147 if (unlikely(brw->perf_debug)) {
148 if (brw_bo_busy(query->bo)) {
149 perf_debug("Stalling on the GPU waiting for a query object.\n");
150 }
151 }
152
153 results = brw_bo_map(brw, query->bo, MAP_READ);
154 switch (query->Base.Target) {
155 case GL_TIME_ELAPSED_EXT:
156 /* The query BO contains the starting and ending timestamps.
157 * Subtract the two and convert to nanoseconds.
158 */
159 query->Base.Result = brw_raw_timestamp_delta(brw, results[0], results[1]);
160 query->Base.Result = gen_device_info_timebase_scale(devinfo, query->Base.Result);
161 break;
162
163 case GL_TIMESTAMP:
164 /* The query BO contains a single timestamp value in results[0]. */
165 query->Base.Result = gen_device_info_timebase_scale(devinfo, results[0]);
166
167 /* Ensure the scaled timestamp overflows according to
168 * GL_QUERY_COUNTER_BITS
169 */
170 query->Base.Result &= (1ull << ctx->Const.QueryCounterBits.Timestamp) - 1;
171 break;
172
173 case GL_SAMPLES_PASSED_ARB:
174 /* Loop over pairs of values from the BO, which are the PS_DEPTH_COUNT
175 * value at the start and end of the batchbuffer. Subtract them to
176 * get the number of fragments which passed the depth test in each
177 * individual batch, and add those differences up to get the number
178 * of fragments for the entire query.
179 *
180 * Note that query->Base.Result may already be non-zero. We may have
181 * run out of space in the query's BO and allocated a new one. If so,
182 * this function was already called to accumulate the results so far.
183 */
184 for (i = 0; i < query->last_index; i++) {
185 query->Base.Result += results[i * 2 + 1] - results[i * 2];
186 }
187 break;
188
189 case GL_ANY_SAMPLES_PASSED:
190 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
191 /* If the starting and ending PS_DEPTH_COUNT from any of the batches
192 * differ, then some fragments passed the depth test.
193 */
194 for (i = 0; i < query->last_index; i++) {
195 if (results[i * 2 + 1] != results[i * 2]) {
196 query->Base.Result = GL_TRUE;
197 break;
198 }
199 }
200 break;
201
202 default:
203 unreachable("Unrecognized query target in brw_queryobj_get_results()");
204 }
205 brw_bo_unmap(query->bo);
206
207 /* Now that we've processed the data stored in the query's buffer object,
208 * we can release it.
209 */
210 brw_bo_unreference(query->bo);
211 query->bo = NULL;
212 }
213
214 /**
215 * The NewQueryObject() driver hook.
216 *
217 * Allocates and initializes a new query object.
218 */
219 static struct gl_query_object *
220 brw_new_query_object(struct gl_context *ctx, GLuint id)
221 {
222 struct brw_query_object *query;
223
224 query = calloc(1, sizeof(struct brw_query_object));
225
226 query->Base.Id = id;
227 query->Base.Result = 0;
228 query->Base.Active = false;
229 query->Base.Ready = true;
230
231 return &query->Base;
232 }
233
234 /**
235 * The DeleteQuery() driver hook.
236 */
237 static void
238 brw_delete_query(struct gl_context *ctx, struct gl_query_object *q)
239 {
240 struct brw_query_object *query = (struct brw_query_object *)q;
241
242 brw_bo_unreference(query->bo);
243 _mesa_delete_query(ctx, q);
244 }
245
246 /**
247 * Gen4-5 driver hook for glBeginQuery().
248 *
249 * Initializes driver structures and emits any GPU commands required to begin
250 * recording data for the query.
251 */
252 static void
253 brw_begin_query(struct gl_context *ctx, struct gl_query_object *q)
254 {
255 struct brw_context *brw = brw_context(ctx);
256 struct brw_query_object *query = (struct brw_query_object *)q;
257 UNUSED const struct gen_device_info *devinfo = &brw->screen->devinfo;
258
259 assert(devinfo->gen < 6);
260
261 switch (query->Base.Target) {
262 case GL_TIME_ELAPSED_EXT:
263 /* For timestamp queries, we record the starting time right away so that
264 * we measure the full time between BeginQuery and EndQuery. There's
265 * some debate about whether this is the right thing to do. Our decision
266 * is based on the following text from the ARB_timer_query extension:
267 *
268 * "(5) Should the extension measure total time elapsed between the full
269 * completion of the BeginQuery and EndQuery commands, or just time
270 * spent in the graphics library?
271 *
272 * RESOLVED: This extension will measure the total time elapsed
273 * between the full completion of these commands. Future extensions
274 * may implement a query to determine time elapsed at different stages
275 * of the graphics pipeline."
276 *
277 * We write a starting timestamp now (at index 0). At EndQuery() time,
278 * we'll write a second timestamp (at index 1), and subtract the two to
279 * obtain the time elapsed. Notably, this includes time elapsed while
280 * the system was doing other work, such as running other applications.
281 */
282 brw_bo_unreference(query->bo);
283 query->bo =
284 brw_bo_alloc(brw->bufmgr, "timer query", 4096, BRW_MEMZONE_OTHER);
285 brw_write_timestamp(brw, query->bo, 0);
286 break;
287
288 case GL_ANY_SAMPLES_PASSED:
289 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
290 case GL_SAMPLES_PASSED_ARB:
291 /* For occlusion queries, we delay taking an initial sample until the
292 * first drawing occurs in this batch. See the reasoning in the comments
293 * for brw_emit_query_begin() below.
294 *
295 * Since we're starting a new query, we need to be sure to throw away
296 * any previous occlusion query results.
297 */
298 brw_bo_unreference(query->bo);
299 query->bo = NULL;
300 query->last_index = -1;
301
302 brw->query.obj = query;
303
304 /* Depth statistics on Gen4 require strange workarounds, so we try to
305 * avoid them when necessary. They're required for occlusion queries,
306 * so turn them on now.
307 */
308 brw->stats_wm++;
309 brw->ctx.NewDriverState |= BRW_NEW_STATS_WM;
310 break;
311
312 default:
313 unreachable("Unrecognized query target in brw_begin_query()");
314 }
315 }
316
317 /**
318 * Gen4-5 driver hook for glEndQuery().
319 *
320 * Emits GPU commands to record a final query value, ending any data capturing.
321 * However, the final result isn't necessarily available until the GPU processes
322 * those commands. brw_queryobj_get_results() processes the captured data to
323 * produce the final result.
324 */
325 static void
326 brw_end_query(struct gl_context *ctx, struct gl_query_object *q)
327 {
328 struct brw_context *brw = brw_context(ctx);
329 struct brw_query_object *query = (struct brw_query_object *)q;
330 UNUSED const struct gen_device_info *devinfo = &brw->screen->devinfo;
331
332 assert(devinfo->gen < 6);
333
334 switch (query->Base.Target) {
335 case GL_TIME_ELAPSED_EXT:
336 /* Write the final timestamp. */
337 brw_write_timestamp(brw, query->bo, 1);
338 break;
339
340 case GL_ANY_SAMPLES_PASSED:
341 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
342 case GL_SAMPLES_PASSED_ARB:
343
344 /* No query->bo means that EndQuery was called after BeginQuery with no
345 * intervening drawing. Rather than doing nothing at all here in this
346 * case, we emit the query_begin and query_end state to the
347 * hardware. This is to guarantee that waiting on the result of this
348 * empty state will cause all previous queries to complete at all, as
349 * required by the specification:
350 *
351 * It must always be true that if any query object
352 * returns a result available of TRUE, all queries of the
353 * same type issued prior to that query must also return
354 * TRUE. [Open GL 4.3 (Core Profile) Section 4.2.1]
355 */
356 if (!query->bo) {
357 brw_emit_query_begin(brw);
358 }
359
360 assert(query->bo);
361
362 brw_emit_query_end(brw);
363
364 brw->query.obj = NULL;
365
366 brw->stats_wm--;
367 brw->ctx.NewDriverState |= BRW_NEW_STATS_WM;
368 break;
369
370 default:
371 unreachable("Unrecognized query target in brw_end_query()");
372 }
373 }
374
375 /**
376 * The Gen4-5 WaitQuery() driver hook.
377 *
378 * Wait for a query result to become available and return it. This is the
379 * backing for glGetQueryObjectiv() with the GL_QUERY_RESULT pname.
380 */
381 static void brw_wait_query(struct gl_context *ctx, struct gl_query_object *q)
382 {
383 struct brw_query_object *query = (struct brw_query_object *)q;
384 UNUSED const struct gen_device_info *devinfo =
385 &brw_context(ctx)->screen->devinfo;
386
387 assert(devinfo->gen < 6);
388
389 brw_queryobj_get_results(ctx, query);
390 query->Base.Ready = true;
391 }
392
393 /**
394 * The Gen4-5 CheckQuery() driver hook.
395 *
396 * Checks whether a query result is ready yet. If not, flushes.
397 * This is the backing for glGetQueryObjectiv()'s QUERY_RESULT_AVAILABLE pname.
398 */
399 static void brw_check_query(struct gl_context *ctx, struct gl_query_object *q)
400 {
401 struct brw_context *brw = brw_context(ctx);
402 struct brw_query_object *query = (struct brw_query_object *)q;
403 UNUSED const struct gen_device_info *devinfo = &brw->screen->devinfo;
404
405 assert(devinfo->gen < 6);
406
407 /* From the GL_ARB_occlusion_query spec:
408 *
409 * "Instead of allowing for an infinite loop, performing a
410 * QUERY_RESULT_AVAILABLE_ARB will perform a flush if the result is
411 * not ready yet on the first time it is queried. This ensures that
412 * the async query will return true in finite time.
413 */
414 if (query->bo && brw_batch_references(&brw->batch, query->bo))
415 intel_batchbuffer_flush(brw);
416
417 if (query->bo == NULL || !brw_bo_busy(query->bo)) {
418 brw_queryobj_get_results(ctx, query);
419 query->Base.Ready = true;
420 }
421 }
422
423 /**
424 * Ensure there query's BO has enough space to store a new pair of values.
425 *
426 * If not, gather the existing BO's results and create a new buffer of the
427 * same size.
428 */
429 static void
430 ensure_bo_has_space(struct gl_context *ctx, struct brw_query_object *query)
431 {
432 struct brw_context *brw = brw_context(ctx);
433 UNUSED const struct gen_device_info *devinfo = &brw->screen->devinfo;
434
435 assert(devinfo->gen < 6);
436
437 if (!query->bo || query->last_index * 2 + 1 >= 4096 / sizeof(uint64_t)) {
438
439 if (query->bo != NULL) {
440 /* The old query BO did not have enough space, so we allocated a new
441 * one. Gather the results so far (adding up the differences) and
442 * release the old BO.
443 */
444 brw_queryobj_get_results(ctx, query);
445 }
446
447 query->bo = brw_bo_alloc(brw->bufmgr, "query", 4096, BRW_MEMZONE_OTHER);
448 query->last_index = 0;
449 }
450 }
451
452 /**
453 * Record the PS_DEPTH_COUNT value (for occlusion queries) just before
454 * primitive drawing.
455 *
456 * In a pre-hardware context world, the single PS_DEPTH_COUNT register is
457 * shared among all applications using the GPU. However, our query value
458 * needs to only include fragments generated by our application/GL context.
459 *
460 * To accommodate this, we record PS_DEPTH_COUNT at the start and end of
461 * each batchbuffer (technically, the first primitive drawn and flush time).
462 * Subtracting each pair of values calculates the change in PS_DEPTH_COUNT
463 * caused by a batchbuffer. Since there is no preemption inside batches,
464 * this is guaranteed to only measure the effects of our current application.
465 *
466 * Adding each of these differences (in case drawing is done over many batches)
467 * produces the final expected value.
468 *
469 * In a world with hardware contexts, PS_DEPTH_COUNT is saved and restored
470 * as part of the context state, so this is unnecessary, and skipped.
471 */
472 void
473 brw_emit_query_begin(struct brw_context *brw)
474 {
475 struct gl_context *ctx = &brw->ctx;
476 struct brw_query_object *query = brw->query.obj;
477
478 /* Skip if we're not doing any queries, or we've already recorded the
479 * initial query value for this batchbuffer.
480 */
481 if (!query || brw->query.begin_emitted)
482 return;
483
484 ensure_bo_has_space(ctx, query);
485
486 brw_write_depth_count(brw, query->bo, query->last_index * 2);
487
488 brw->query.begin_emitted = true;
489 }
490
491 /**
492 * Called at batchbuffer flush to get an ending PS_DEPTH_COUNT
493 * (for non-hardware context platforms).
494 *
495 * See the explanation in brw_emit_query_begin().
496 */
497 void
498 brw_emit_query_end(struct brw_context *brw)
499 {
500 struct brw_query_object *query = brw->query.obj;
501
502 if (!brw->query.begin_emitted)
503 return;
504
505 brw_write_depth_count(brw, query->bo, query->last_index * 2 + 1);
506
507 brw->query.begin_emitted = false;
508 query->last_index++;
509 }
510
511 /**
512 * Driver hook for glQueryCounter().
513 *
514 * This handles GL_TIMESTAMP queries, which perform a pipelined read of the
515 * current GPU time. This is unlike GL_TIME_ELAPSED, which measures the
516 * time while the query is active.
517 */
518 void
519 brw_query_counter(struct gl_context *ctx, struct gl_query_object *q)
520 {
521 struct brw_context *brw = brw_context(ctx);
522 struct brw_query_object *query = (struct brw_query_object *) q;
523
524 assert(q->Target == GL_TIMESTAMP);
525
526 brw_bo_unreference(query->bo);
527 query->bo =
528 brw_bo_alloc(brw->bufmgr, "timestamp query", 4096, BRW_MEMZONE_OTHER);
529 brw_write_timestamp(brw, query->bo, 0);
530
531 query->flushed = false;
532 }
533
534 /**
535 * Read the TIMESTAMP register immediately (in a non-pipelined fashion).
536 *
537 * This is used to implement the GetTimestamp() driver hook.
538 */
539 static uint64_t
540 brw_get_timestamp(struct gl_context *ctx)
541 {
542 struct brw_context *brw = brw_context(ctx);
543 const struct gen_device_info *devinfo = &brw->screen->devinfo;
544 uint64_t result = 0;
545
546 switch (brw->screen->hw_has_timestamp) {
547 case 3: /* New kernel, always full 36bit accuracy */
548 brw_reg_read(brw->bufmgr, TIMESTAMP | 1, &result);
549 break;
550 case 2: /* 64bit kernel, result is left-shifted by 32bits, losing 4bits */
551 brw_reg_read(brw->bufmgr, TIMESTAMP, &result);
552 result = result >> 32;
553 break;
554 case 1: /* 32bit kernel, result is 36bit wide but may be inaccurate! */
555 brw_reg_read(brw->bufmgr, TIMESTAMP, &result);
556 break;
557 }
558
559 /* Scale to nanosecond units */
560 result = gen_device_info_timebase_scale(devinfo, result);
561
562 /* Ensure the scaled timestamp overflows according to
563 * GL_QUERY_COUNTER_BITS. Technically this isn't required if
564 * querying GL_TIMESTAMP via glGetInteger but it seems best to keep
565 * QueryObject and GetInteger timestamps consistent.
566 */
567 result &= (1ull << ctx->Const.QueryCounterBits.Timestamp) - 1;
568 return result;
569 }
570
571 /**
572 * Is this type of query written by PIPE_CONTROL?
573 */
574 bool
575 brw_is_query_pipelined(struct brw_query_object *query)
576 {
577 switch (query->Base.Target) {
578 case GL_TIMESTAMP:
579 case GL_TIME_ELAPSED:
580 case GL_ANY_SAMPLES_PASSED:
581 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE:
582 case GL_SAMPLES_PASSED_ARB:
583 return true;
584
585 case GL_PRIMITIVES_GENERATED:
586 case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
587 case GL_TRANSFORM_FEEDBACK_STREAM_OVERFLOW_ARB:
588 case GL_TRANSFORM_FEEDBACK_OVERFLOW_ARB:
589 case GL_VERTICES_SUBMITTED_ARB:
590 case GL_PRIMITIVES_SUBMITTED_ARB:
591 case GL_VERTEX_SHADER_INVOCATIONS_ARB:
592 case GL_GEOMETRY_SHADER_INVOCATIONS:
593 case GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED_ARB:
594 case GL_FRAGMENT_SHADER_INVOCATIONS_ARB:
595 case GL_CLIPPING_INPUT_PRIMITIVES_ARB:
596 case GL_CLIPPING_OUTPUT_PRIMITIVES_ARB:
597 case GL_COMPUTE_SHADER_INVOCATIONS_ARB:
598 case GL_TESS_CONTROL_SHADER_PATCHES_ARB:
599 case GL_TESS_EVALUATION_SHADER_INVOCATIONS_ARB:
600 return false;
601
602 default:
603 unreachable("Unrecognized query target in is_query_pipelined()");
604 }
605 }
606
607 /* Initialize query object functions used on all generations. */
608 void brw_init_common_queryobj_functions(struct dd_function_table *functions)
609 {
610 functions->NewQueryObject = brw_new_query_object;
611 functions->DeleteQuery = brw_delete_query;
612 functions->GetTimestamp = brw_get_timestamp;
613 }
614
615 /* Initialize Gen4/5-specific query object functions. */
616 void gen4_init_queryobj_functions(struct dd_function_table *functions)
617 {
618 functions->BeginQuery = brw_begin_query;
619 functions->EndQuery = brw_end_query;
620 functions->CheckQuery = brw_check_query;
621 functions->WaitQuery = brw_wait_query;
622 functions->QueryCounter = brw_query_counter;
623 }