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