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