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