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