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