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