2 * Copyright © 2008 Intel Corporation
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:
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
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
24 * Eric Anholt <eric@anholt.net>
28 /** @file brw_queryobj.c
30 * Support for query objects (GL_ARB_occlusion_query, GL_ARB_timer_query,
31 * GL_EXT_transform_feedback, and friends).
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'
38 #include "main/imports.h"
40 #include "brw_context.h"
41 #include "brw_defines.h"
42 #include "brw_state.h"
43 #include "intel_batchbuffer.h"
46 brw_timebase_scale(struct brw_context
*brw
, uint64_t gpu_timestamp
)
48 const struct gen_device_info
*devinfo
= &brw
->screen
->devinfo
;
50 return (1000000000ull * gpu_timestamp
) / devinfo
->timestamp_frequency
;
53 /* As best we know currently, the Gen HW timestamps are 36bits across
54 * all platforms, which we need to account for when calculating a
55 * delta to measure elapsed time.
57 * The timestamps read via glGetTimestamp() / brw_get_timestamp() sometimes
58 * only have 32bits due to a kernel bug and so in that case we make sure to
59 * treat all raw timestamps as 32bits so they overflow consistently and remain
60 * comparable. (Note: the timestamps being passed here are not from the kernel
61 * so we don't need to be taking the upper 32bits in this buggy kernel case we
62 * are just clipping to 32bits here for consistency.)
65 brw_raw_timestamp_delta(struct brw_context
*brw
, uint64_t time0
, uint64_t time1
)
67 if (brw
->screen
->hw_has_timestamp
== 2) {
68 /* Kernel clips timestamps to 32bits in this case, so we also clip
69 * PIPE_CONTROL timestamps for consistency.
71 return (uint32_t)time1
- (uint32_t)time0
;
74 return (1ULL << 36) + time1
- time0
;
82 * Emit PIPE_CONTROLs to write the current GPU timestamp into a buffer.
85 brw_write_timestamp(struct brw_context
*brw
, struct brw_bo
*query_bo
, int idx
)
88 /* Emit Sandybridge workaround flush: */
89 brw_emit_pipe_control_flush(brw
,
90 PIPE_CONTROL_CS_STALL
|
91 PIPE_CONTROL_STALL_AT_SCOREBOARD
);
94 uint32_t flags
= PIPE_CONTROL_WRITE_TIMESTAMP
;
96 if (brw
->gen
== 9 && brw
->gt
== 4)
97 flags
|= PIPE_CONTROL_CS_STALL
;
99 brw_emit_pipe_control_write(brw
, flags
,
100 query_bo
, idx
* sizeof(uint64_t), 0);
104 * Emit PIPE_CONTROLs to write the PS_DEPTH_COUNT register into a buffer.
107 brw_write_depth_count(struct brw_context
*brw
, struct brw_bo
*query_bo
, int idx
)
109 uint32_t flags
= PIPE_CONTROL_WRITE_DEPTH_COUNT
| PIPE_CONTROL_DEPTH_STALL
;
111 if (brw
->gen
== 9 && brw
->gt
== 4)
112 flags
|= PIPE_CONTROL_CS_STALL
;
114 if (brw
->gen
>= 10) {
115 /* "Driver must program PIPE_CONTROL with only Depth Stall Enable bit set
116 * prior to programming a PIPE_CONTROL with Write PS Depth Count Post sync
119 brw_emit_pipe_control_flush(brw
, PIPE_CONTROL_DEPTH_STALL
);
122 brw_emit_pipe_control_write(brw
, flags
,
123 query_bo
, idx
* sizeof(uint64_t), 0);
127 * Wait on the query object's BO and calculate the final result.
130 brw_queryobj_get_results(struct gl_context
*ctx
,
131 struct brw_query_object
*query
)
133 struct brw_context
*brw
= brw_context(ctx
);
138 assert(brw
->gen
< 6);
140 if (query
->bo
== NULL
)
143 /* If the application has requested the query result, but this batch is
144 * still contributing to it, flush it now so the results will be present
147 if (brw_batch_references(&brw
->batch
, query
->bo
))
148 intel_batchbuffer_flush(brw
);
150 if (unlikely(brw
->perf_debug
)) {
151 if (brw_bo_busy(query
->bo
)) {
152 perf_debug("Stalling on the GPU waiting for a query object.\n");
156 results
= brw_bo_map(brw
, query
->bo
, MAP_READ
);
157 switch (query
->Base
.Target
) {
158 case GL_TIME_ELAPSED_EXT
:
159 /* The query BO contains the starting and ending timestamps.
160 * Subtract the two and convert to nanoseconds.
162 query
->Base
.Result
= brw_raw_timestamp_delta(brw
, results
[0], results
[1]);
163 query
->Base
.Result
= brw_timebase_scale(brw
, query
->Base
.Result
);
167 /* The query BO contains a single timestamp value in results[0]. */
168 query
->Base
.Result
= brw_timebase_scale(brw
, results
[0]);
170 /* Ensure the scaled timestamp overflows according to
171 * GL_QUERY_COUNTER_BITS
173 query
->Base
.Result
&= (1ull << ctx
->Const
.QueryCounterBits
.Timestamp
) - 1;
176 case GL_SAMPLES_PASSED_ARB
:
177 /* Loop over pairs of values from the BO, which are the PS_DEPTH_COUNT
178 * value at the start and end of the batchbuffer. Subtract them to
179 * get the number of fragments which passed the depth test in each
180 * individual batch, and add those differences up to get the number
181 * of fragments for the entire query.
183 * Note that query->Base.Result may already be non-zero. We may have
184 * run out of space in the query's BO and allocated a new one. If so,
185 * this function was already called to accumulate the results so far.
187 for (i
= 0; i
< query
->last_index
; i
++) {
188 query
->Base
.Result
+= results
[i
* 2 + 1] - results
[i
* 2];
192 case GL_ANY_SAMPLES_PASSED
:
193 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE
:
194 /* If the starting and ending PS_DEPTH_COUNT from any of the batches
195 * differ, then some fragments passed the depth test.
197 for (i
= 0; i
< query
->last_index
; i
++) {
198 if (results
[i
* 2 + 1] != results
[i
* 2]) {
199 query
->Base
.Result
= GL_TRUE
;
206 unreachable("Unrecognized query target in brw_queryobj_get_results()");
208 brw_bo_unmap(query
->bo
);
210 /* Now that we've processed the data stored in the query's buffer object,
213 brw_bo_unreference(query
->bo
);
218 * The NewQueryObject() driver hook.
220 * Allocates and initializes a new query object.
222 static struct gl_query_object
*
223 brw_new_query_object(struct gl_context
*ctx
, GLuint id
)
225 struct brw_query_object
*query
;
227 query
= calloc(1, sizeof(struct brw_query_object
));
230 query
->Base
.Result
= 0;
231 query
->Base
.Active
= false;
232 query
->Base
.Ready
= true;
238 * The DeleteQuery() driver hook.
241 brw_delete_query(struct gl_context
*ctx
, struct gl_query_object
*q
)
243 struct brw_query_object
*query
= (struct brw_query_object
*)q
;
245 brw_bo_unreference(query
->bo
);
250 * Gen4-5 driver hook for glBeginQuery().
252 * Initializes driver structures and emits any GPU commands required to begin
253 * recording data for the query.
256 brw_begin_query(struct gl_context
*ctx
, struct gl_query_object
*q
)
258 struct brw_context
*brw
= brw_context(ctx
);
259 struct brw_query_object
*query
= (struct brw_query_object
*)q
;
261 assert(brw
->gen
< 6);
263 switch (query
->Base
.Target
) {
264 case GL_TIME_ELAPSED_EXT
:
265 /* For timestamp queries, we record the starting time right away so that
266 * we measure the full time between BeginQuery and EndQuery. There's
267 * some debate about whether this is the right thing to do. Our decision
268 * is based on the following text from the ARB_timer_query extension:
270 * "(5) Should the extension measure total time elapsed between the full
271 * completion of the BeginQuery and EndQuery commands, or just time
272 * spent in the graphics library?
274 * RESOLVED: This extension will measure the total time elapsed
275 * between the full completion of these commands. Future extensions
276 * may implement a query to determine time elapsed at different stages
277 * of the graphics pipeline."
279 * We write a starting timestamp now (at index 0). At EndQuery() time,
280 * we'll write a second timestamp (at index 1), and subtract the two to
281 * obtain the time elapsed. Notably, this includes time elapsed while
282 * the system was doing other work, such as running other applications.
284 brw_bo_unreference(query
->bo
);
285 query
->bo
= brw_bo_alloc(brw
->bufmgr
, "timer query", 4096, 4096);
286 brw_write_timestamp(brw
, query
->bo
, 0);
289 case GL_ANY_SAMPLES_PASSED
:
290 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE
:
291 case GL_SAMPLES_PASSED_ARB
:
292 /* For occlusion queries, we delay taking an initial sample until the
293 * first drawing occurs in this batch. See the reasoning in the comments
294 * for brw_emit_query_begin() below.
296 * Since we're starting a new query, we need to be sure to throw away
297 * any previous occlusion query results.
299 brw_bo_unreference(query
->bo
);
301 query
->last_index
= -1;
303 brw
->query
.obj
= query
;
305 /* Depth statistics on Gen4 require strange workarounds, so we try to
306 * avoid them when necessary. They're required for occlusion queries,
307 * so turn them on now.
310 brw
->ctx
.NewDriverState
|= BRW_NEW_STATS_WM
;
314 unreachable("Unrecognized query target in brw_begin_query()");
319 * Gen4-5 driver hook for glEndQuery().
321 * Emits GPU commands to record a final query value, ending any data capturing.
322 * However, the final result isn't necessarily available until the GPU processes
323 * those commands. brw_queryobj_get_results() processes the captured data to
324 * produce the final result.
327 brw_end_query(struct gl_context
*ctx
, struct gl_query_object
*q
)
329 struct brw_context
*brw
= brw_context(ctx
);
330 struct brw_query_object
*query
= (struct brw_query_object
*)q
;
332 assert(brw
->gen
< 6);
334 switch (query
->Base
.Target
) {
335 case GL_TIME_ELAPSED_EXT
:
336 /* Write the final timestamp. */
337 brw_write_timestamp(brw
, query
->bo
, 1);
340 case GL_ANY_SAMPLES_PASSED
:
341 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE
:
342 case GL_SAMPLES_PASSED_ARB
:
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:
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]
357 brw_emit_query_begin(brw
);
362 brw_emit_query_end(brw
);
364 brw
->query
.obj
= NULL
;
367 brw
->ctx
.NewDriverState
|= BRW_NEW_STATS_WM
;
371 unreachable("Unrecognized query target in brw_end_query()");
376 * The Gen4-5 WaitQuery() driver hook.
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.
381 static void brw_wait_query(struct gl_context
*ctx
, struct gl_query_object
*q
)
383 struct brw_query_object
*query
= (struct brw_query_object
*)q
;
385 assert(brw_context(ctx
)->gen
< 6);
387 brw_queryobj_get_results(ctx
, query
);
388 query
->Base
.Ready
= true;
392 * The Gen4-5 CheckQuery() driver hook.
394 * Checks whether a query result is ready yet. If not, flushes.
395 * This is the backing for glGetQueryObjectiv()'s QUERY_RESULT_AVAILABLE pname.
397 static void brw_check_query(struct gl_context
*ctx
, struct gl_query_object
*q
)
399 struct brw_context
*brw
= brw_context(ctx
);
400 struct brw_query_object
*query
= (struct brw_query_object
*)q
;
402 assert(brw
->gen
< 6);
404 /* From the GL_ARB_occlusion_query spec:
406 * "Instead of allowing for an infinite loop, performing a
407 * QUERY_RESULT_AVAILABLE_ARB will perform a flush if the result is
408 * not ready yet on the first time it is queried. This ensures that
409 * the async query will return true in finite time.
411 if (query
->bo
&& brw_batch_references(&brw
->batch
, query
->bo
))
412 intel_batchbuffer_flush(brw
);
414 if (query
->bo
== NULL
|| !brw_bo_busy(query
->bo
)) {
415 brw_queryobj_get_results(ctx
, query
);
416 query
->Base
.Ready
= true;
421 * Ensure there query's BO has enough space to store a new pair of values.
423 * If not, gather the existing BO's results and create a new buffer of the
427 ensure_bo_has_space(struct gl_context
*ctx
, struct brw_query_object
*query
)
429 struct brw_context
*brw
= brw_context(ctx
);
431 assert(brw
->gen
< 6);
433 if (!query
->bo
|| query
->last_index
* 2 + 1 >= 4096 / sizeof(uint64_t)) {
435 if (query
->bo
!= NULL
) {
436 /* The old query BO did not have enough space, so we allocated a new
437 * one. Gather the results so far (adding up the differences) and
438 * release the old BO.
440 brw_queryobj_get_results(ctx
, query
);
443 query
->bo
= brw_bo_alloc(brw
->bufmgr
, "query", 4096, 1);
444 query
->last_index
= 0;
449 * Record the PS_DEPTH_COUNT value (for occlusion queries) just before
452 * In a pre-hardware context world, the single PS_DEPTH_COUNT register is
453 * shared among all applications using the GPU. However, our query value
454 * needs to only include fragments generated by our application/GL context.
456 * To accommodate this, we record PS_DEPTH_COUNT at the start and end of
457 * each batchbuffer (technically, the first primitive drawn and flush time).
458 * Subtracting each pair of values calculates the change in PS_DEPTH_COUNT
459 * caused by a batchbuffer. Since there is no preemption inside batches,
460 * this is guaranteed to only measure the effects of our current application.
462 * Adding each of these differences (in case drawing is done over many batches)
463 * produces the final expected value.
465 * In a world with hardware contexts, PS_DEPTH_COUNT is saved and restored
466 * as part of the context state, so this is unnecessary, and skipped.
469 brw_emit_query_begin(struct brw_context
*brw
)
471 struct gl_context
*ctx
= &brw
->ctx
;
472 struct brw_query_object
*query
= brw
->query
.obj
;
477 /* Skip if we're not doing any queries, or we've already recorded the
478 * initial query value for this batchbuffer.
480 if (!query
|| brw
->query
.begin_emitted
)
483 ensure_bo_has_space(ctx
, query
);
485 brw_write_depth_count(brw
, query
->bo
, query
->last_index
* 2);
487 brw
->query
.begin_emitted
= true;
491 * Called at batchbuffer flush to get an ending PS_DEPTH_COUNT
492 * (for non-hardware context platforms).
494 * See the explanation in brw_emit_query_begin().
497 brw_emit_query_end(struct brw_context
*brw
)
499 struct brw_query_object
*query
= brw
->query
.obj
;
504 if (!brw
->query
.begin_emitted
)
507 brw_write_depth_count(brw
, query
->bo
, query
->last_index
* 2 + 1);
509 brw
->query
.begin_emitted
= false;
514 * Driver hook for glQueryCounter().
516 * This handles GL_TIMESTAMP queries, which perform a pipelined read of the
517 * current GPU time. This is unlike GL_TIME_ELAPSED, which measures the
518 * time while the query is active.
521 brw_query_counter(struct gl_context
*ctx
, struct gl_query_object
*q
)
523 struct brw_context
*brw
= brw_context(ctx
);
524 struct brw_query_object
*query
= (struct brw_query_object
*) q
;
526 assert(q
->Target
== GL_TIMESTAMP
);
528 brw_bo_unreference(query
->bo
);
529 query
->bo
= brw_bo_alloc(brw
->bufmgr
, "timestamp query", 4096, 4096);
530 brw_write_timestamp(brw
, query
->bo
, 0);
532 query
->flushed
= false;
536 * Read the TIMESTAMP register immediately (in a non-pipelined fashion).
538 * This is used to implement the GetTimestamp() driver hook.
541 brw_get_timestamp(struct gl_context
*ctx
)
543 struct brw_context
*brw
= brw_context(ctx
);
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
);
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;
554 case 1: /* 32bit kernel, result is 36bit wide but may be inaccurate! */
555 brw_reg_read(brw
->bufmgr
, TIMESTAMP
, &result
);
559 /* Scale to nanosecond units */
560 result
= brw_timebase_scale(brw
, result
);
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.
567 result
&= (1ull << ctx
->Const
.QueryCounterBits
.Timestamp
) - 1;
572 * Is this type of query written by PIPE_CONTROL?
575 brw_is_query_pipelined(struct brw_query_object
*query
)
577 switch (query
->Base
.Target
) {
579 case GL_TIME_ELAPSED
:
580 case GL_ANY_SAMPLES_PASSED
:
581 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE
:
582 case GL_SAMPLES_PASSED_ARB
:
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
:
603 unreachable("Unrecognized query target in is_query_pipelined()");
607 /* Initialize query object functions used on all generations. */
608 void brw_init_common_queryobj_functions(struct dd_function_table
*functions
)
610 functions
->NewQueryObject
= brw_new_query_object
;
611 functions
->DeleteQuery
= brw_delete_query
;
612 functions
->GetTimestamp
= brw_get_timestamp
;
615 /* Initialize Gen4/5-specific query object functions. */
616 void gen4_init_queryobj_functions(struct dd_function_table
*functions
)
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
;