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