Merge remote-tracking branch 'mesa-public/master' into vulkan
[mesa.git] / src / mesa / drivers / dri / i965 / brw_context.c
1 /*
2 Copyright 2003 VMware, Inc.
3 Copyright (C) Intel Corp. 2006. All Rights Reserved.
4 Intel funded Tungsten Graphics to
5 develop this 3D driver.
6
7 Permission is hereby granted, free of charge, to any person obtaining
8 a copy of this software and associated documentation files (the
9 "Software"), to deal in the Software without restriction, including
10 without limitation the rights to use, copy, modify, merge, publish,
11 distribute, sublicense, and/or sell copies of the Software, and to
12 permit persons to whom the Software is furnished to do so, subject to
13 the following conditions:
14
15 The above copyright notice and this permission notice (including the
16 next paragraph) shall be included in all copies or substantial
17 portions of the Software.
18
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
22 IN NO EVENT SHALL THE COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS BE
23 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
27 **********************************************************************/
28 /*
29 * Authors:
30 * Keith Whitwell <keithw@vmware.com>
31 */
32
33
34 #include "main/api_exec.h"
35 #include "main/context.h"
36 #include "main/fbobject.h"
37 #include "main/extensions.h"
38 #include "main/imports.h"
39 #include "main/macros.h"
40 #include "main/points.h"
41 #include "main/version.h"
42 #include "main/vtxfmt.h"
43 #include "main/texobj.h"
44 #include "main/framebuffer.h"
45
46 #include "vbo/vbo_context.h"
47
48 #include "drivers/common/driverfuncs.h"
49 #include "drivers/common/meta.h"
50 #include "utils.h"
51
52 #include "brw_context.h"
53 #include "brw_defines.h"
54 #include "brw_compiler.h"
55 #include "brw_draw.h"
56 #include "brw_state.h"
57
58 #include "intel_batchbuffer.h"
59 #include "intel_buffer_objects.h"
60 #include "intel_buffers.h"
61 #include "intel_fbo.h"
62 #include "intel_mipmap_tree.h"
63 #include "intel_pixel.h"
64 #include "intel_image.h"
65 #include "intel_tex.h"
66 #include "intel_tex_obj.h"
67
68 #include "swrast_setup/swrast_setup.h"
69 #include "tnl/tnl.h"
70 #include "tnl/t_pipeline.h"
71 #include "util/ralloc.h"
72
73 /***************************************
74 * Mesa's Driver Functions
75 ***************************************/
76
77 static size_t
78 brw_query_samples_for_format(struct gl_context *ctx, GLenum target,
79 GLenum internalFormat, int samples[16])
80 {
81 struct brw_context *brw = brw_context(ctx);
82
83 (void) target;
84
85 switch (brw->gen) {
86 case 9:
87 samples[0] = 16;
88 samples[1] = 8;
89 samples[2] = 4;
90 samples[3] = 2;
91 return 4;
92
93 case 8:
94 samples[0] = 8;
95 samples[1] = 4;
96 samples[2] = 2;
97 return 3;
98
99 case 7:
100 samples[0] = 8;
101 samples[1] = 4;
102 return 2;
103
104 case 6:
105 samples[0] = 4;
106 return 1;
107
108 default:
109 assert(brw->gen < 6);
110 samples[0] = 1;
111 return 1;
112 }
113 }
114
115 const char *const brw_vendor_string = "Intel Open Source Technology Center";
116
117 const char *
118 brw_get_renderer_string(unsigned deviceID)
119 {
120 const char *chipset;
121 static char buffer[128];
122
123 switch (deviceID) {
124 #undef CHIPSET
125 #define CHIPSET(id, symbol, str) case id: chipset = str; break;
126 #include "pci_ids/i965_pci_ids.h"
127 default:
128 chipset = "Unknown Intel Chipset";
129 break;
130 }
131
132 (void) driGetRendererString(buffer, chipset, 0);
133 return buffer;
134 }
135
136 static const GLubyte *
137 intel_get_string(struct gl_context * ctx, GLenum name)
138 {
139 const struct brw_context *const brw = brw_context(ctx);
140
141 switch (name) {
142 case GL_VENDOR:
143 return (GLubyte *) brw_vendor_string;
144
145 case GL_RENDERER:
146 return
147 (GLubyte *) brw_get_renderer_string(brw->intelScreen->deviceID);
148
149 default:
150 return NULL;
151 }
152 }
153
154 static void
155 intel_viewport(struct gl_context *ctx)
156 {
157 struct brw_context *brw = brw_context(ctx);
158 __DRIcontext *driContext = brw->driContext;
159
160 if (_mesa_is_winsys_fbo(ctx->DrawBuffer)) {
161 dri2InvalidateDrawable(driContext->driDrawablePriv);
162 dri2InvalidateDrawable(driContext->driReadablePriv);
163 }
164 }
165
166 static void
167 intel_update_state(struct gl_context * ctx, GLuint new_state)
168 {
169 struct brw_context *brw = brw_context(ctx);
170 struct intel_texture_object *tex_obj;
171 struct intel_renderbuffer *depth_irb;
172
173 if (ctx->swrast_context)
174 _swrast_InvalidateState(ctx, new_state);
175 _vbo_InvalidateState(ctx, new_state);
176
177 brw->NewGLState |= new_state;
178
179 _mesa_unlock_context_textures(ctx);
180
181 /* Resolve the depth buffer's HiZ buffer. */
182 depth_irb = intel_get_renderbuffer(ctx->DrawBuffer, BUFFER_DEPTH);
183 if (depth_irb)
184 intel_renderbuffer_resolve_hiz(brw, depth_irb);
185
186 /* Resolve depth buffer and render cache of each enabled texture. */
187 int maxEnabledUnit = ctx->Texture._MaxEnabledTexImageUnit;
188 for (int i = 0; i <= maxEnabledUnit; i++) {
189 if (!ctx->Texture.Unit[i]._Current)
190 continue;
191 tex_obj = intel_texture_object(ctx->Texture.Unit[i]._Current);
192 if (!tex_obj || !tex_obj->mt)
193 continue;
194 intel_miptree_all_slices_resolve_depth(brw, tex_obj->mt);
195 intel_miptree_resolve_color(brw, tex_obj->mt);
196 brw_render_cache_set_check_flush(brw, tex_obj->mt->bo);
197 }
198
199 _mesa_lock_context_textures(ctx);
200 }
201
202 #define flushFront(screen) ((screen)->image.loader ? (screen)->image.loader->flushFrontBuffer : (screen)->dri2.loader->flushFrontBuffer)
203
204 static void
205 intel_flush_front(struct gl_context *ctx)
206 {
207 struct brw_context *brw = brw_context(ctx);
208 __DRIcontext *driContext = brw->driContext;
209 __DRIdrawable *driDrawable = driContext->driDrawablePriv;
210 __DRIscreen *const screen = brw->intelScreen->driScrnPriv;
211
212 if (brw->front_buffer_dirty && _mesa_is_winsys_fbo(ctx->DrawBuffer)) {
213 if (flushFront(screen) && driDrawable &&
214 driDrawable->loaderPrivate) {
215
216 /* Resolve before flushing FAKE_FRONT_LEFT to FRONT_LEFT.
217 *
218 * This potentially resolves both front and back buffer. It
219 * is unnecessary to resolve the back, but harms nothing except
220 * performance. And no one cares about front-buffer render
221 * performance.
222 */
223 intel_resolve_for_dri2_flush(brw, driDrawable);
224 intel_batchbuffer_flush(brw);
225
226 flushFront(screen)(driDrawable, driDrawable->loaderPrivate);
227
228 /* We set the dirty bit in intel_prepare_render() if we're
229 * front buffer rendering once we get there.
230 */
231 brw->front_buffer_dirty = false;
232 }
233 }
234 }
235
236 static void
237 intel_glFlush(struct gl_context *ctx)
238 {
239 struct brw_context *brw = brw_context(ctx);
240
241 intel_batchbuffer_flush(brw);
242 intel_flush_front(ctx);
243
244 brw->need_flush_throttle = true;
245 }
246
247 static void
248 intel_finish(struct gl_context * ctx)
249 {
250 struct brw_context *brw = brw_context(ctx);
251
252 intel_glFlush(ctx);
253
254 if (brw->batch.last_bo)
255 drm_intel_bo_wait_rendering(brw->batch.last_bo);
256 }
257
258 static void
259 brw_init_driver_functions(struct brw_context *brw,
260 struct dd_function_table *functions)
261 {
262 _mesa_init_driver_functions(functions);
263
264 /* GLX uses DRI2 invalidate events to handle window resizing.
265 * Unfortunately, EGL does not - libEGL is written in XCB (not Xlib),
266 * which doesn't provide a mechanism for snooping the event queues.
267 *
268 * So EGL still relies on viewport hacks to handle window resizing.
269 * This should go away with DRI3000.
270 */
271 if (!brw->driContext->driScreenPriv->dri2.useInvalidate)
272 functions->Viewport = intel_viewport;
273
274 functions->Flush = intel_glFlush;
275 functions->Finish = intel_finish;
276 functions->GetString = intel_get_string;
277 functions->UpdateState = intel_update_state;
278
279 intelInitTextureFuncs(functions);
280 intelInitTextureImageFuncs(functions);
281 intelInitTextureSubImageFuncs(functions);
282 intelInitTextureCopyImageFuncs(functions);
283 intelInitCopyImageFuncs(functions);
284 intelInitClearFuncs(functions);
285 intelInitBufferFuncs(functions);
286 intelInitPixelFuncs(functions);
287 intelInitBufferObjectFuncs(functions);
288 intel_init_syncobj_functions(functions);
289 brw_init_object_purgeable_functions(functions);
290
291 brwInitFragProgFuncs( functions );
292 brw_init_common_queryobj_functions(functions);
293 if (brw->gen >= 6)
294 gen6_init_queryobj_functions(functions);
295 else
296 gen4_init_queryobj_functions(functions);
297 brw_init_compute_functions(functions);
298 if (brw->gen >= 7)
299 brw_init_conditional_render_functions(functions);
300
301 functions->QuerySamplesForFormat = brw_query_samples_for_format;
302
303 functions->NewTransformFeedback = brw_new_transform_feedback;
304 functions->DeleteTransformFeedback = brw_delete_transform_feedback;
305 functions->GetTransformFeedbackVertexCount =
306 brw_get_transform_feedback_vertex_count;
307 if (brw->gen >= 7) {
308 functions->BeginTransformFeedback = gen7_begin_transform_feedback;
309 functions->EndTransformFeedback = gen7_end_transform_feedback;
310 functions->PauseTransformFeedback = gen7_pause_transform_feedback;
311 functions->ResumeTransformFeedback = gen7_resume_transform_feedback;
312 } else {
313 functions->BeginTransformFeedback = brw_begin_transform_feedback;
314 functions->EndTransformFeedback = brw_end_transform_feedback;
315 }
316
317 if (brw->gen >= 6)
318 functions->GetSamplePosition = gen6_get_sample_position;
319 }
320
321 static void
322 brw_initialize_context_constants(struct brw_context *brw)
323 {
324 struct gl_context *ctx = &brw->ctx;
325 const struct brw_compiler *compiler = brw->intelScreen->compiler;
326
327 const bool stage_exists[MESA_SHADER_STAGES] = {
328 [MESA_SHADER_VERTEX] = true,
329 [MESA_SHADER_TESS_CTRL] = false,
330 [MESA_SHADER_TESS_EVAL] = false,
331 [MESA_SHADER_GEOMETRY] = brw->gen >= 6,
332 [MESA_SHADER_FRAGMENT] = true,
333 [MESA_SHADER_COMPUTE] = _mesa_extension_override_enables.ARB_compute_shader,
334 };
335
336 unsigned num_stages = 0;
337 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
338 if (stage_exists[i])
339 num_stages++;
340 }
341
342 unsigned max_samplers =
343 brw->gen >= 8 || brw->is_haswell ? BRW_MAX_TEX_UNIT : 16;
344
345 ctx->Const.MaxDualSourceDrawBuffers = 1;
346 ctx->Const.MaxDrawBuffers = BRW_MAX_DRAW_BUFFERS;
347 ctx->Const.MaxCombinedShaderOutputResources =
348 MAX_IMAGE_UNITS + BRW_MAX_DRAW_BUFFERS;
349
350 ctx->Const.QueryCounterBits.Timestamp = 36;
351
352 ctx->Const.MaxTextureCoordUnits = 8; /* Mesa limit */
353 ctx->Const.MaxImageUnits = MAX_IMAGE_UNITS;
354 ctx->Const.MaxRenderbufferSize = 8192;
355 ctx->Const.MaxTextureLevels = MIN2(14 /* 8192 */, MAX_TEXTURE_LEVELS);
356 ctx->Const.Max3DTextureLevels = 12; /* 2048 */
357 ctx->Const.MaxCubeTextureLevels = 14; /* 8192 */
358 ctx->Const.MaxArrayTextureLayers = brw->gen >= 7 ? 2048 : 512;
359 ctx->Const.MaxTextureMbytes = 1536;
360 ctx->Const.MaxTextureRectSize = 1 << 12;
361 ctx->Const.MaxTextureMaxAnisotropy = 16.0;
362 ctx->Const.StripTextureBorder = true;
363 if (brw->gen >= 7)
364 ctx->Const.MaxProgramTextureGatherComponents = 4;
365 else if (brw->gen == 6)
366 ctx->Const.MaxProgramTextureGatherComponents = 1;
367
368 ctx->Const.MaxUniformBlockSize = 65536;
369
370 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
371 struct gl_program_constants *prog = &ctx->Const.Program[i];
372
373 if (!stage_exists[i])
374 continue;
375
376 prog->MaxTextureImageUnits = max_samplers;
377
378 prog->MaxUniformBlocks = BRW_MAX_UBO;
379 prog->MaxCombinedUniformComponents =
380 prog->MaxUniformComponents +
381 ctx->Const.MaxUniformBlockSize / 4 * prog->MaxUniformBlocks;
382
383 prog->MaxAtomicCounters = MAX_ATOMIC_COUNTERS;
384 prog->MaxAtomicBuffers = BRW_MAX_ABO;
385 prog->MaxImageUniforms = compiler->scalar_stage[i] ? BRW_MAX_IMAGES : 0;
386 prog->MaxShaderStorageBlocks = BRW_MAX_SSBO;
387 }
388
389 ctx->Const.MaxTextureUnits =
390 MIN2(ctx->Const.MaxTextureCoordUnits,
391 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits);
392
393 ctx->Const.MaxUniformBufferBindings = num_stages * BRW_MAX_UBO;
394 ctx->Const.MaxCombinedUniformBlocks = num_stages * BRW_MAX_UBO;
395 ctx->Const.MaxCombinedAtomicBuffers = num_stages * BRW_MAX_ABO;
396 ctx->Const.MaxCombinedShaderStorageBlocks = num_stages * BRW_MAX_SSBO;
397 ctx->Const.MaxShaderStorageBufferBindings = num_stages * BRW_MAX_SSBO;
398 ctx->Const.MaxCombinedTextureImageUnits = num_stages * max_samplers;
399 ctx->Const.MaxCombinedImageUniforms = num_stages * BRW_MAX_IMAGES;
400
401
402 /* Hardware only supports a limited number of transform feedback buffers.
403 * So we need to override the Mesa default (which is based only on software
404 * limits).
405 */
406 ctx->Const.MaxTransformFeedbackBuffers = BRW_MAX_SOL_BUFFERS;
407
408 /* On Gen6, in the worst case, we use up one binding table entry per
409 * transform feedback component (see comments above the definition of
410 * BRW_MAX_SOL_BINDINGS, in brw_context.h), so we need to advertise a value
411 * for MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS equal to
412 * BRW_MAX_SOL_BINDINGS.
413 *
414 * In "separate components" mode, we need to divide this value by
415 * BRW_MAX_SOL_BUFFERS, so that the total number of binding table entries
416 * used up by all buffers will not exceed BRW_MAX_SOL_BINDINGS.
417 */
418 ctx->Const.MaxTransformFeedbackInterleavedComponents = BRW_MAX_SOL_BINDINGS;
419 ctx->Const.MaxTransformFeedbackSeparateComponents =
420 BRW_MAX_SOL_BINDINGS / BRW_MAX_SOL_BUFFERS;
421
422 ctx->Const.AlwaysUseGetTransformFeedbackVertexCount = true;
423
424 int max_samples;
425 const int *msaa_modes = intel_supported_msaa_modes(brw->intelScreen);
426 const int clamp_max_samples =
427 driQueryOptioni(&brw->optionCache, "clamp_max_samples");
428
429 if (clamp_max_samples < 0) {
430 max_samples = msaa_modes[0];
431 } else {
432 /* Select the largest supported MSAA mode that does not exceed
433 * clamp_max_samples.
434 */
435 max_samples = 0;
436 for (int i = 0; msaa_modes[i] != 0; ++i) {
437 if (msaa_modes[i] <= clamp_max_samples) {
438 max_samples = msaa_modes[i];
439 break;
440 }
441 }
442 }
443
444 ctx->Const.MaxSamples = max_samples;
445 ctx->Const.MaxColorTextureSamples = max_samples;
446 ctx->Const.MaxDepthTextureSamples = max_samples;
447 ctx->Const.MaxIntegerSamples = max_samples;
448 ctx->Const.MaxImageSamples = 0;
449
450 /* gen6_set_sample_maps() sets SampleMap{2,4,8}x variables which are used
451 * to map indices of rectangular grid to sample numbers within a pixel.
452 * These variables are used by GL_EXT_framebuffer_multisample_blit_scaled
453 * extension implementation. For more details see the comment above
454 * gen6_set_sample_maps() definition.
455 */
456 gen6_set_sample_maps(ctx);
457
458 ctx->Const.MinLineWidth = 1.0;
459 ctx->Const.MinLineWidthAA = 1.0;
460 if (brw->gen >= 6) {
461 ctx->Const.MaxLineWidth = 7.375;
462 ctx->Const.MaxLineWidthAA = 7.375;
463 ctx->Const.LineWidthGranularity = 0.125;
464 } else {
465 ctx->Const.MaxLineWidth = 7.0;
466 ctx->Const.MaxLineWidthAA = 7.0;
467 ctx->Const.LineWidthGranularity = 0.5;
468 }
469
470 /* For non-antialiased lines, we have to round the line width to the
471 * nearest whole number. Make sure that we don't advertise a line
472 * width that, when rounded, will be beyond the actual hardware
473 * maximum.
474 */
475 assert(roundf(ctx->Const.MaxLineWidth) <= ctx->Const.MaxLineWidth);
476
477 ctx->Const.MinPointSize = 1.0;
478 ctx->Const.MinPointSizeAA = 1.0;
479 ctx->Const.MaxPointSize = 255.0;
480 ctx->Const.MaxPointSizeAA = 255.0;
481 ctx->Const.PointSizeGranularity = 1.0;
482
483 if (brw->gen >= 5 || brw->is_g4x)
484 ctx->Const.MaxClipPlanes = 8;
485
486 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeInstructions = 16 * 1024;
487 ctx->Const.Program[MESA_SHADER_VERTEX].MaxAluInstructions = 0;
488 ctx->Const.Program[MESA_SHADER_VERTEX].MaxTexInstructions = 0;
489 ctx->Const.Program[MESA_SHADER_VERTEX].MaxTexIndirections = 0;
490 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeAluInstructions = 0;
491 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeTexInstructions = 0;
492 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeTexIndirections = 0;
493 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeAttribs = 16;
494 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeTemps = 256;
495 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeAddressRegs = 1;
496 ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeParameters = 1024;
497 ctx->Const.Program[MESA_SHADER_VERTEX].MaxEnvParams =
498 MIN2(ctx->Const.Program[MESA_SHADER_VERTEX].MaxNativeParameters,
499 ctx->Const.Program[MESA_SHADER_VERTEX].MaxEnvParams);
500
501 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeInstructions = 1024;
502 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeAluInstructions = 1024;
503 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeTexInstructions = 1024;
504 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeTexIndirections = 1024;
505 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeAttribs = 12;
506 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeTemps = 256;
507 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeAddressRegs = 0;
508 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeParameters = 1024;
509 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxEnvParams =
510 MIN2(ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxNativeParameters,
511 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxEnvParams);
512
513 /* Fragment shaders use real, 32-bit twos-complement integers for all
514 * integer types.
515 */
516 ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt.RangeMin = 31;
517 ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt.RangeMax = 30;
518 ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt.Precision = 0;
519 ctx->Const.Program[MESA_SHADER_FRAGMENT].HighInt = ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt;
520 ctx->Const.Program[MESA_SHADER_FRAGMENT].MediumInt = ctx->Const.Program[MESA_SHADER_FRAGMENT].LowInt;
521
522 ctx->Const.Program[MESA_SHADER_VERTEX].LowInt.RangeMin = 31;
523 ctx->Const.Program[MESA_SHADER_VERTEX].LowInt.RangeMax = 30;
524 ctx->Const.Program[MESA_SHADER_VERTEX].LowInt.Precision = 0;
525 ctx->Const.Program[MESA_SHADER_VERTEX].HighInt = ctx->Const.Program[MESA_SHADER_VERTEX].LowInt;
526 ctx->Const.Program[MESA_SHADER_VERTEX].MediumInt = ctx->Const.Program[MESA_SHADER_VERTEX].LowInt;
527
528 /* Gen6 converts quads to polygon in beginning of 3D pipeline,
529 * but we're not sure how it's actually done for vertex order,
530 * that affect provoking vertex decision. Always use last vertex
531 * convention for quad primitive which works as expected for now.
532 */
533 if (brw->gen >= 6)
534 ctx->Const.QuadsFollowProvokingVertexConvention = false;
535
536 ctx->Const.NativeIntegers = true;
537 ctx->Const.VertexID_is_zero_based = true;
538
539 /* Regarding the CMP instruction, the Ivybridge PRM says:
540 *
541 * "For each enabled channel 0b or 1b is assigned to the appropriate flag
542 * bit and 0/all zeros or all ones (e.g, byte 0xFF, word 0xFFFF, DWord
543 * 0xFFFFFFFF) is assigned to dst."
544 *
545 * but PRMs for earlier generations say
546 *
547 * "In dword format, one GRF may store up to 8 results. When the register
548 * is used later as a vector of Booleans, as only LSB at each channel
549 * contains meaning [sic] data, software should make sure all higher bits
550 * are masked out (e.g. by 'and-ing' an [sic] 0x01 constant)."
551 *
552 * We select the representation of a true boolean uniform to be ~0, and fix
553 * the results of Gen <= 5 CMP instruction's with -(result & 1).
554 */
555 ctx->Const.UniformBooleanTrue = ~0;
556
557 /* From the gen4 PRM, volume 4 page 127:
558 *
559 * "For SURFTYPE_BUFFER non-rendertarget surfaces, this field specifies
560 * the base address of the first element of the surface, computed in
561 * software by adding the surface base address to the byte offset of
562 * the element in the buffer."
563 *
564 * However, unaligned accesses are slower, so enforce buffer alignment.
565 */
566 ctx->Const.UniformBufferOffsetAlignment = 16;
567
568 /* ShaderStorageBufferOffsetAlignment should be a cacheline (64 bytes) so
569 * that we can safely have the CPU and GPU writing the same SSBO on
570 * non-cachecoherent systems (our Atom CPUs). With UBOs, the GPU never
571 * writes, so there's no problem. For an SSBO, the GPU and the CPU can
572 * be updating disjoint regions of the buffer simultaneously and that will
573 * break if the regions overlap the same cacheline.
574 */
575 ctx->Const.ShaderStorageBufferOffsetAlignment = 64;
576 ctx->Const.TextureBufferOffsetAlignment = 16;
577 ctx->Const.MaxTextureBufferSize = 128 * 1024 * 1024;
578
579 if (brw->gen >= 6) {
580 ctx->Const.MaxVarying = 32;
581 ctx->Const.Program[MESA_SHADER_VERTEX].MaxOutputComponents = 128;
582 ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxInputComponents = 64;
583 ctx->Const.Program[MESA_SHADER_GEOMETRY].MaxOutputComponents = 128;
584 ctx->Const.Program[MESA_SHADER_FRAGMENT].MaxInputComponents = 128;
585 }
586
587 /* We want the GLSL compiler to emit code that uses condition codes */
588 for (int i = 0; i < MESA_SHADER_STAGES; i++) {
589 ctx->Const.ShaderCompilerOptions[i] =
590 brw->intelScreen->compiler->glsl_compiler_options[i];
591 }
592
593 /* ARB_viewport_array */
594 if (brw->gen >= 6 && ctx->API == API_OPENGL_CORE) {
595 ctx->Const.MaxViewports = GEN6_NUM_VIEWPORTS;
596 ctx->Const.ViewportSubpixelBits = 0;
597
598 /* Cast to float before negating because MaxViewportWidth is unsigned.
599 */
600 ctx->Const.ViewportBounds.Min = -(float)ctx->Const.MaxViewportWidth;
601 ctx->Const.ViewportBounds.Max = ctx->Const.MaxViewportWidth;
602 }
603
604 /* ARB_gpu_shader5 */
605 if (brw->gen >= 7)
606 ctx->Const.MaxVertexStreams = MIN2(4, MAX_VERTEX_STREAMS);
607
608 /* ARB_framebuffer_no_attachments */
609 ctx->Const.MaxFramebufferWidth = ctx->Const.MaxViewportWidth;
610 ctx->Const.MaxFramebufferHeight = ctx->Const.MaxViewportHeight;
611 ctx->Const.MaxFramebufferLayers = ctx->Const.MaxArrayTextureLayers;
612 ctx->Const.MaxFramebufferSamples = max_samples;
613 }
614
615 static void
616 brw_adjust_cs_context_constants(struct brw_context *brw)
617 {
618 struct gl_context *ctx = &brw->ctx;
619
620 /* For ES, we set these constants based on SIMD8.
621 *
622 * TODO: Once we can always generate SIMD16, we should update this.
623 *
624 * For GL, we assume we can generate a SIMD16 program, but this currently
625 * is not always true. This allows us to run more test cases, and will be
626 * required based on desktop GL compute shader requirements.
627 */
628 const int simd_size = ctx->API == API_OPENGL_CORE ? 16 : 8;
629
630 const uint32_t max_invocations = simd_size * brw->max_cs_threads;
631 ctx->Const.MaxComputeWorkGroupSize[0] = max_invocations;
632 ctx->Const.MaxComputeWorkGroupSize[1] = max_invocations;
633 ctx->Const.MaxComputeWorkGroupSize[2] = max_invocations;
634 ctx->Const.MaxComputeWorkGroupInvocations = max_invocations;
635 }
636
637 /**
638 * Process driconf (drirc) options, setting appropriate context flags.
639 *
640 * intelInitExtensions still pokes at optionCache directly, in order to
641 * avoid advertising various extensions. No flags are set, so it makes
642 * sense to continue doing that there.
643 */
644 static void
645 brw_process_driconf_options(struct brw_context *brw)
646 {
647 struct gl_context *ctx = &brw->ctx;
648
649 driOptionCache *options = &brw->optionCache;
650 driParseConfigFiles(options, &brw->intelScreen->optionCache,
651 brw->driContext->driScreenPriv->myNum, "i965");
652
653 int bo_reuse_mode = driQueryOptioni(options, "bo_reuse");
654 switch (bo_reuse_mode) {
655 case DRI_CONF_BO_REUSE_DISABLED:
656 break;
657 case DRI_CONF_BO_REUSE_ALL:
658 intel_bufmgr_gem_enable_reuse(brw->bufmgr);
659 break;
660 }
661
662 if (!driQueryOptionb(options, "hiz")) {
663 brw->has_hiz = false;
664 /* On gen6, you can only do separate stencil with HIZ. */
665 if (brw->gen == 6)
666 brw->has_separate_stencil = false;
667 }
668
669 if (driQueryOptionb(options, "always_flush_batch")) {
670 fprintf(stderr, "flushing batchbuffer before/after each draw call\n");
671 brw->always_flush_batch = true;
672 }
673
674 if (driQueryOptionb(options, "always_flush_cache")) {
675 fprintf(stderr, "flushing GPU caches before/after each draw call\n");
676 brw->always_flush_cache = true;
677 }
678
679 if (driQueryOptionb(options, "disable_throttling")) {
680 fprintf(stderr, "disabling flush throttling\n");
681 brw->disable_throttling = true;
682 }
683
684 brw->precompile = driQueryOptionb(&brw->optionCache, "shader_precompile");
685
686 ctx->Const.ForceGLSLExtensionsWarn =
687 driQueryOptionb(options, "force_glsl_extensions_warn");
688
689 ctx->Const.DisableGLSLLineContinuations =
690 driQueryOptionb(options, "disable_glsl_line_continuations");
691
692 ctx->Const.AllowGLSLExtensionDirectiveMidShader =
693 driQueryOptionb(options, "allow_glsl_extension_directive_midshader");
694 }
695
696 GLboolean
697 brwCreateContext(gl_api api,
698 const struct gl_config *mesaVis,
699 __DRIcontext *driContextPriv,
700 unsigned major_version,
701 unsigned minor_version,
702 uint32_t flags,
703 bool notify_reset,
704 unsigned *dri_ctx_error,
705 void *sharedContextPrivate)
706 {
707 __DRIscreen *sPriv = driContextPriv->driScreenPriv;
708 struct gl_context *shareCtx = (struct gl_context *) sharedContextPrivate;
709 struct intel_screen *screen = sPriv->driverPrivate;
710 const struct brw_device_info *devinfo = screen->devinfo;
711 struct dd_function_table functions;
712
713 /* Only allow the __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS flag if the kernel
714 * provides us with context reset notifications.
715 */
716 uint32_t allowed_flags = __DRI_CTX_FLAG_DEBUG
717 | __DRI_CTX_FLAG_FORWARD_COMPATIBLE;
718
719 if (screen->has_context_reset_notification)
720 allowed_flags |= __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS;
721
722 if (flags & ~allowed_flags) {
723 *dri_ctx_error = __DRI_CTX_ERROR_UNKNOWN_FLAG;
724 return false;
725 }
726
727 struct brw_context *brw = rzalloc(NULL, struct brw_context);
728 if (!brw) {
729 fprintf(stderr, "%s: failed to alloc context\n", __func__);
730 *dri_ctx_error = __DRI_CTX_ERROR_NO_MEMORY;
731 return false;
732 }
733
734 driContextPriv->driverPrivate = brw;
735 brw->driContext = driContextPriv;
736 brw->intelScreen = screen;
737 brw->bufmgr = screen->bufmgr;
738
739 brw->gen = devinfo->gen;
740 brw->gt = devinfo->gt;
741 brw->is_g4x = devinfo->is_g4x;
742 brw->is_baytrail = devinfo->is_baytrail;
743 brw->is_haswell = devinfo->is_haswell;
744 brw->is_cherryview = devinfo->is_cherryview;
745 brw->is_broxton = devinfo->is_broxton;
746 brw->has_llc = devinfo->has_llc;
747 brw->has_hiz = devinfo->has_hiz_and_separate_stencil;
748 brw->has_separate_stencil = devinfo->has_hiz_and_separate_stencil;
749 brw->has_pln = devinfo->has_pln;
750 brw->has_compr4 = devinfo->has_compr4;
751 brw->has_surface_tile_offset = devinfo->has_surface_tile_offset;
752 brw->has_negative_rhw_bug = devinfo->has_negative_rhw_bug;
753 brw->needs_unlit_centroid_workaround =
754 devinfo->needs_unlit_centroid_workaround;
755
756 brw->must_use_separate_stencil = screen->hw_must_use_separate_stencil;
757 brw->has_swizzling = screen->hw_has_swizzling;
758
759 brw->vs.base.stage = MESA_SHADER_VERTEX;
760 brw->gs.base.stage = MESA_SHADER_GEOMETRY;
761 brw->wm.base.stage = MESA_SHADER_FRAGMENT;
762 if (brw->gen >= 8) {
763 gen8_init_vtable_surface_functions(brw);
764 brw->vtbl.emit_depth_stencil_hiz = gen8_emit_depth_stencil_hiz;
765 } else if (brw->gen >= 7) {
766 gen7_init_vtable_surface_functions(brw);
767 brw->vtbl.emit_depth_stencil_hiz = gen7_emit_depth_stencil_hiz;
768 } else if (brw->gen >= 6) {
769 gen6_init_vtable_surface_functions(brw);
770 brw->vtbl.emit_depth_stencil_hiz = gen6_emit_depth_stencil_hiz;
771 } else {
772 gen4_init_vtable_surface_functions(brw);
773 brw->vtbl.emit_depth_stencil_hiz = brw_emit_depth_stencil_hiz;
774 }
775
776 brw_init_driver_functions(brw, &functions);
777
778 if (notify_reset)
779 functions.GetGraphicsResetStatus = brw_get_graphics_reset_status;
780
781 struct gl_context *ctx = &brw->ctx;
782
783 if (!_mesa_initialize_context(ctx, api, mesaVis, shareCtx, &functions)) {
784 *dri_ctx_error = __DRI_CTX_ERROR_NO_MEMORY;
785 fprintf(stderr, "%s: failed to init mesa context\n", __func__);
786 intelDestroyContext(driContextPriv);
787 return false;
788 }
789
790 driContextSetFlags(ctx, flags);
791
792 /* Initialize the software rasterizer and helper modules.
793 *
794 * As of GL 3.1 core, the gen4+ driver doesn't need the swrast context for
795 * software fallbacks (which we have to support on legacy GL to do weird
796 * glDrawPixels(), glBitmap(), and other functions).
797 */
798 if (api != API_OPENGL_CORE && api != API_OPENGLES2) {
799 _swrast_CreateContext(ctx);
800 }
801
802 _vbo_CreateContext(ctx);
803 if (ctx->swrast_context) {
804 _tnl_CreateContext(ctx);
805 TNL_CONTEXT(ctx)->Driver.RunPipeline = _tnl_run_pipeline;
806 _swsetup_CreateContext(ctx);
807
808 /* Configure swrast to match hardware characteristics: */
809 _swrast_allow_pixel_fog(ctx, false);
810 _swrast_allow_vertex_fog(ctx, true);
811 }
812
813 _mesa_meta_init(ctx);
814
815 brw_process_driconf_options(brw);
816
817 if (INTEL_DEBUG & DEBUG_PERF)
818 brw->perf_debug = true;
819
820 brw_initialize_context_constants(brw);
821
822 ctx->Const.ResetStrategy = notify_reset
823 ? GL_LOSE_CONTEXT_ON_RESET_ARB : GL_NO_RESET_NOTIFICATION_ARB;
824
825 /* Reinitialize the context point state. It depends on ctx->Const values. */
826 _mesa_init_point(ctx);
827
828 intel_fbo_init(brw);
829
830 intel_batchbuffer_init(brw);
831
832 if (brw->gen >= 6) {
833 /* Create a new hardware context. Using a hardware context means that
834 * our GPU state will be saved/restored on context switch, allowing us
835 * to assume that the GPU is in the same state we left it in.
836 *
837 * This is required for transform feedback buffer offsets, query objects,
838 * and also allows us to reduce how much state we have to emit.
839 */
840 brw->hw_ctx = drm_intel_gem_context_create(brw->bufmgr);
841
842 if (!brw->hw_ctx) {
843 fprintf(stderr, "Gen6+ requires Kernel 3.6 or later.\n");
844 intelDestroyContext(driContextPriv);
845 return false;
846 }
847 }
848
849 if (brw_init_pipe_control(brw, devinfo)) {
850 *dri_ctx_error = __DRI_CTX_ERROR_NO_MEMORY;
851 intelDestroyContext(driContextPriv);
852 return false;
853 }
854
855 brw_init_state(brw);
856
857 intelInitExtensions(ctx);
858
859 brw_init_surface_formats(brw);
860
861 brw->max_vs_threads = devinfo->max_vs_threads;
862 brw->max_hs_threads = devinfo->max_hs_threads;
863 brw->max_ds_threads = devinfo->max_ds_threads;
864 brw->max_gs_threads = devinfo->max_gs_threads;
865 brw->max_wm_threads = devinfo->max_wm_threads;
866 brw->max_cs_threads = devinfo->max_cs_threads;
867 brw->urb.size = devinfo->urb.size;
868 brw->urb.min_vs_entries = devinfo->urb.min_vs_entries;
869 brw->urb.max_vs_entries = devinfo->urb.max_vs_entries;
870 brw->urb.max_hs_entries = devinfo->urb.max_hs_entries;
871 brw->urb.max_ds_entries = devinfo->urb.max_ds_entries;
872 brw->urb.max_gs_entries = devinfo->urb.max_gs_entries;
873
874 brw_adjust_cs_context_constants(brw);
875
876 /* Estimate the size of the mappable aperture into the GTT. There's an
877 * ioctl to get the whole GTT size, but not one to get the mappable subset.
878 * It turns out it's basically always 256MB, though some ancient hardware
879 * was smaller.
880 */
881 uint32_t gtt_size = 256 * 1024 * 1024;
882
883 /* We don't want to map two objects such that a memcpy between them would
884 * just fault one mapping in and then the other over and over forever. So
885 * we would need to divide the GTT size by 2. Additionally, some GTT is
886 * taken up by things like the framebuffer and the ringbuffer and such, so
887 * be more conservative.
888 */
889 brw->max_gtt_map_object_size = gtt_size / 4;
890
891 if (brw->gen == 6)
892 brw->urb.gs_present = false;
893
894 brw->prim_restart.in_progress = false;
895 brw->prim_restart.enable_cut_index = false;
896 brw->gs.enabled = false;
897 brw->sf.viewport_transform_enable = true;
898
899 brw->predicate.state = BRW_PREDICATE_STATE_RENDER;
900
901 brw->use_resource_streamer = screen->has_resource_streamer &&
902 (brw_env_var_as_boolean("INTEL_USE_HW_BT", false) ||
903 brw_env_var_as_boolean("INTEL_USE_GATHER", false));
904
905 ctx->VertexProgram._MaintainTnlProgram = true;
906 ctx->FragmentProgram._MaintainTexEnvProgram = true;
907
908 brw_draw_init( brw );
909
910 if ((flags & __DRI_CTX_FLAG_DEBUG) != 0) {
911 /* Turn on some extra GL_ARB_debug_output generation. */
912 brw->perf_debug = true;
913 }
914
915 if ((flags & __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS) != 0)
916 ctx->Const.ContextFlags |= GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB;
917
918 if (INTEL_DEBUG & DEBUG_SHADER_TIME)
919 brw_init_shader_time(brw);
920
921 _mesa_compute_version(ctx);
922
923 _mesa_initialize_dispatch_tables(ctx);
924 _mesa_initialize_vbo_vtxfmt(ctx);
925
926 if (ctx->Extensions.AMD_performance_monitor) {
927 brw_init_performance_monitors(brw);
928 }
929
930 vbo_use_buffer_objects(ctx);
931 vbo_always_unmap_buffers(ctx);
932
933 return true;
934 }
935
936 void
937 intelDestroyContext(__DRIcontext * driContextPriv)
938 {
939 struct brw_context *brw =
940 (struct brw_context *) driContextPriv->driverPrivate;
941 struct gl_context *ctx = &brw->ctx;
942
943 /* Dump a final BMP in case the application doesn't call SwapBuffers */
944 if (INTEL_DEBUG & DEBUG_AUB) {
945 intel_batchbuffer_flush(brw);
946 aub_dump_bmp(&brw->ctx);
947 }
948
949 _mesa_meta_free(&brw->ctx);
950 brw_meta_fast_clear_free(brw);
951
952 if (INTEL_DEBUG & DEBUG_SHADER_TIME) {
953 /* Force a report. */
954 brw->shader_time.report_time = 0;
955
956 brw_collect_and_report_shader_time(brw);
957 brw_destroy_shader_time(brw);
958 }
959
960 brw_destroy_state(brw);
961 brw_draw_destroy(brw);
962
963 drm_intel_bo_unreference(brw->curbe.curbe_bo);
964 if (brw->vs.base.scratch_bo)
965 drm_intel_bo_unreference(brw->vs.base.scratch_bo);
966 if (brw->gs.base.scratch_bo)
967 drm_intel_bo_unreference(brw->gs.base.scratch_bo);
968 if (brw->wm.base.scratch_bo)
969 drm_intel_bo_unreference(brw->wm.base.scratch_bo);
970
971 gen7_reset_hw_bt_pool_offsets(brw);
972 drm_intel_bo_unreference(brw->hw_bt_pool.bo);
973 brw->hw_bt_pool.bo = NULL;
974
975 drm_intel_gem_context_destroy(brw->hw_ctx);
976
977 if (ctx->swrast_context) {
978 _swsetup_DestroyContext(&brw->ctx);
979 _tnl_DestroyContext(&brw->ctx);
980 }
981 _vbo_DestroyContext(&brw->ctx);
982
983 if (ctx->swrast_context)
984 _swrast_DestroyContext(&brw->ctx);
985
986 brw_fini_pipe_control(brw);
987 intel_batchbuffer_free(brw);
988
989 drm_intel_bo_unreference(brw->throttle_batch[1]);
990 drm_intel_bo_unreference(brw->throttle_batch[0]);
991 brw->throttle_batch[1] = NULL;
992 brw->throttle_batch[0] = NULL;
993
994 driDestroyOptionCache(&brw->optionCache);
995
996 /* free the Mesa context */
997 _mesa_free_context_data(&brw->ctx);
998
999 ralloc_free(brw);
1000 driContextPriv->driverPrivate = NULL;
1001 }
1002
1003 GLboolean
1004 intelUnbindContext(__DRIcontext * driContextPriv)
1005 {
1006 /* Unset current context and dispath table */
1007 _mesa_make_current(NULL, NULL, NULL);
1008
1009 return true;
1010 }
1011
1012 /**
1013 * Fixes up the context for GLES23 with our default-to-sRGB-capable behavior
1014 * on window system framebuffers.
1015 *
1016 * Desktop GL is fairly reasonable in its handling of sRGB: You can ask if
1017 * your renderbuffer can do sRGB encode, and you can flip a switch that does
1018 * sRGB encode if the renderbuffer can handle it. You can ask specifically
1019 * for a visual where you're guaranteed to be capable, but it turns out that
1020 * everyone just makes all their ARGB8888 visuals capable and doesn't offer
1021 * incapable ones, because there's no difference between the two in resources
1022 * used. Applications thus get built that accidentally rely on the default
1023 * visual choice being sRGB, so we make ours sRGB capable. Everything sounds
1024 * great...
1025 *
1026 * But for GLES2/3, they decided that it was silly to not turn on sRGB encode
1027 * for sRGB renderbuffers you made with the GL_EXT_texture_sRGB equivalent.
1028 * So they removed the enable knob and made it "if the renderbuffer is sRGB
1029 * capable, do sRGB encode". Then, for your window system renderbuffers, you
1030 * can ask for sRGB visuals and get sRGB encode, or not ask for sRGB visuals
1031 * and get no sRGB encode (assuming that both kinds of visual are available).
1032 * Thus our choice to support sRGB by default on our visuals for desktop would
1033 * result in broken rendering of GLES apps that aren't expecting sRGB encode.
1034 *
1035 * Unfortunately, renderbuffer setup happens before a context is created. So
1036 * in intel_screen.c we always set up sRGB, and here, if you're a GLES2/3
1037 * context (without an sRGB visual, though we don't have sRGB visuals exposed
1038 * yet), we go turn that back off before anyone finds out.
1039 */
1040 static void
1041 intel_gles3_srgb_workaround(struct brw_context *brw,
1042 struct gl_framebuffer *fb)
1043 {
1044 struct gl_context *ctx = &brw->ctx;
1045
1046 if (_mesa_is_desktop_gl(ctx) || !fb->Visual.sRGBCapable)
1047 return;
1048
1049 /* Some day when we support the sRGB capable bit on visuals available for
1050 * GLES, we'll need to respect that and not disable things here.
1051 */
1052 fb->Visual.sRGBCapable = false;
1053 for (int i = 0; i < BUFFER_COUNT; i++) {
1054 if (fb->Attachment[i].Renderbuffer &&
1055 fb->Attachment[i].Renderbuffer->Format == MESA_FORMAT_B8G8R8A8_SRGB) {
1056 fb->Attachment[i].Renderbuffer->Format = MESA_FORMAT_B8G8R8A8_UNORM;
1057 }
1058 }
1059 }
1060
1061 GLboolean
1062 intelMakeCurrent(__DRIcontext * driContextPriv,
1063 __DRIdrawable * driDrawPriv,
1064 __DRIdrawable * driReadPriv)
1065 {
1066 struct brw_context *brw;
1067 GET_CURRENT_CONTEXT(curCtx);
1068
1069 if (driContextPriv)
1070 brw = (struct brw_context *) driContextPriv->driverPrivate;
1071 else
1072 brw = NULL;
1073
1074 /* According to the glXMakeCurrent() man page: "Pending commands to
1075 * the previous context, if any, are flushed before it is released."
1076 * But only flush if we're actually changing contexts.
1077 */
1078 if (brw_context(curCtx) && brw_context(curCtx) != brw) {
1079 _mesa_flush(curCtx);
1080 }
1081
1082 if (driContextPriv) {
1083 struct gl_context *ctx = &brw->ctx;
1084 struct gl_framebuffer *fb, *readFb;
1085
1086 if (driDrawPriv == NULL) {
1087 fb = _mesa_get_incomplete_framebuffer();
1088 } else {
1089 fb = driDrawPriv->driverPrivate;
1090 driContextPriv->dri2.draw_stamp = driDrawPriv->dri2.stamp - 1;
1091 }
1092
1093 if (driReadPriv == NULL) {
1094 readFb = _mesa_get_incomplete_framebuffer();
1095 } else {
1096 readFb = driReadPriv->driverPrivate;
1097 driContextPriv->dri2.read_stamp = driReadPriv->dri2.stamp - 1;
1098 }
1099
1100 /* The sRGB workaround changes the renderbuffer's format. We must change
1101 * the format before the renderbuffer's miptree get's allocated, otherwise
1102 * the formats of the renderbuffer and its miptree will differ.
1103 */
1104 intel_gles3_srgb_workaround(brw, fb);
1105 intel_gles3_srgb_workaround(brw, readFb);
1106
1107 /* If the context viewport hasn't been initialized, force a call out to
1108 * the loader to get buffers so we have a drawable size for the initial
1109 * viewport. */
1110 if (!brw->ctx.ViewportInitialized)
1111 intel_prepare_render(brw);
1112
1113 _mesa_make_current(ctx, fb, readFb);
1114 } else {
1115 _mesa_make_current(NULL, NULL, NULL);
1116 }
1117
1118 return true;
1119 }
1120
1121 void
1122 intel_resolve_for_dri2_flush(struct brw_context *brw,
1123 __DRIdrawable *drawable)
1124 {
1125 if (brw->gen < 6) {
1126 /* MSAA and fast color clear are not supported, so don't waste time
1127 * checking whether a resolve is needed.
1128 */
1129 return;
1130 }
1131
1132 struct gl_framebuffer *fb = drawable->driverPrivate;
1133 struct intel_renderbuffer *rb;
1134
1135 /* Usually, only the back buffer will need to be downsampled. However,
1136 * the front buffer will also need it if the user has rendered into it.
1137 */
1138 static const gl_buffer_index buffers[2] = {
1139 BUFFER_BACK_LEFT,
1140 BUFFER_FRONT_LEFT,
1141 };
1142
1143 for (int i = 0; i < 2; ++i) {
1144 rb = intel_get_renderbuffer(fb, buffers[i]);
1145 if (rb == NULL || rb->mt == NULL)
1146 continue;
1147 if (rb->mt->num_samples <= 1)
1148 intel_miptree_resolve_color(brw, rb->mt);
1149 else
1150 intel_renderbuffer_downsample(brw, rb);
1151 }
1152 }
1153
1154 static unsigned
1155 intel_bits_per_pixel(const struct intel_renderbuffer *rb)
1156 {
1157 return _mesa_get_format_bytes(intel_rb_format(rb)) * 8;
1158 }
1159
1160 static void
1161 intel_query_dri2_buffers(struct brw_context *brw,
1162 __DRIdrawable *drawable,
1163 __DRIbuffer **buffers,
1164 int *count);
1165
1166 static void
1167 intel_process_dri2_buffer(struct brw_context *brw,
1168 __DRIdrawable *drawable,
1169 __DRIbuffer *buffer,
1170 struct intel_renderbuffer *rb,
1171 const char *buffer_name);
1172
1173 static void
1174 intel_update_image_buffers(struct brw_context *brw, __DRIdrawable *drawable);
1175
1176 static void
1177 intel_update_dri2_buffers(struct brw_context *brw, __DRIdrawable *drawable)
1178 {
1179 struct gl_framebuffer *fb = drawable->driverPrivate;
1180 struct intel_renderbuffer *rb;
1181 __DRIbuffer *buffers = NULL;
1182 int i, count;
1183 const char *region_name;
1184
1185 /* Set this up front, so that in case our buffers get invalidated
1186 * while we're getting new buffers, we don't clobber the stamp and
1187 * thus ignore the invalidate. */
1188 drawable->lastStamp = drawable->dri2.stamp;
1189
1190 if (unlikely(INTEL_DEBUG & DEBUG_DRI))
1191 fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
1192
1193 intel_query_dri2_buffers(brw, drawable, &buffers, &count);
1194
1195 if (buffers == NULL)
1196 return;
1197
1198 for (i = 0; i < count; i++) {
1199 switch (buffers[i].attachment) {
1200 case __DRI_BUFFER_FRONT_LEFT:
1201 rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1202 region_name = "dri2 front buffer";
1203 break;
1204
1205 case __DRI_BUFFER_FAKE_FRONT_LEFT:
1206 rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1207 region_name = "dri2 fake front buffer";
1208 break;
1209
1210 case __DRI_BUFFER_BACK_LEFT:
1211 rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1212 region_name = "dri2 back buffer";
1213 break;
1214
1215 case __DRI_BUFFER_DEPTH:
1216 case __DRI_BUFFER_HIZ:
1217 case __DRI_BUFFER_DEPTH_STENCIL:
1218 case __DRI_BUFFER_STENCIL:
1219 case __DRI_BUFFER_ACCUM:
1220 default:
1221 fprintf(stderr,
1222 "unhandled buffer attach event, attachment type %d\n",
1223 buffers[i].attachment);
1224 return;
1225 }
1226
1227 intel_process_dri2_buffer(brw, drawable, &buffers[i], rb, region_name);
1228 }
1229
1230 }
1231
1232 void
1233 intel_update_renderbuffers(__DRIcontext *context, __DRIdrawable *drawable)
1234 {
1235 struct brw_context *brw = context->driverPrivate;
1236 __DRIscreen *screen = brw->intelScreen->driScrnPriv;
1237
1238 /* Set this up front, so that in case our buffers get invalidated
1239 * while we're getting new buffers, we don't clobber the stamp and
1240 * thus ignore the invalidate. */
1241 drawable->lastStamp = drawable->dri2.stamp;
1242
1243 if (unlikely(INTEL_DEBUG & DEBUG_DRI))
1244 fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
1245
1246 if (screen->image.loader)
1247 intel_update_image_buffers(brw, drawable);
1248 else
1249 intel_update_dri2_buffers(brw, drawable);
1250
1251 driUpdateFramebufferSize(&brw->ctx, drawable);
1252 }
1253
1254 /**
1255 * intel_prepare_render should be called anywhere that curent read/drawbuffer
1256 * state is required.
1257 */
1258 void
1259 intel_prepare_render(struct brw_context *brw)
1260 {
1261 struct gl_context *ctx = &brw->ctx;
1262 __DRIcontext *driContext = brw->driContext;
1263 __DRIdrawable *drawable;
1264
1265 drawable = driContext->driDrawablePriv;
1266 if (drawable && drawable->dri2.stamp != driContext->dri2.draw_stamp) {
1267 if (drawable->lastStamp != drawable->dri2.stamp)
1268 intel_update_renderbuffers(driContext, drawable);
1269 driContext->dri2.draw_stamp = drawable->dri2.stamp;
1270 }
1271
1272 drawable = driContext->driReadablePriv;
1273 if (drawable && drawable->dri2.stamp != driContext->dri2.read_stamp) {
1274 if (drawable->lastStamp != drawable->dri2.stamp)
1275 intel_update_renderbuffers(driContext, drawable);
1276 driContext->dri2.read_stamp = drawable->dri2.stamp;
1277 }
1278
1279 /* If we're currently rendering to the front buffer, the rendering
1280 * that will happen next will probably dirty the front buffer. So
1281 * mark it as dirty here.
1282 */
1283 if (_mesa_is_front_buffer_drawing(ctx->DrawBuffer))
1284 brw->front_buffer_dirty = true;
1285 }
1286
1287 /**
1288 * \brief Query DRI2 to obtain a DRIdrawable's buffers.
1289 *
1290 * To determine which DRI buffers to request, examine the renderbuffers
1291 * attached to the drawable's framebuffer. Then request the buffers with
1292 * DRI2GetBuffers() or DRI2GetBuffersWithFormat().
1293 *
1294 * This is called from intel_update_renderbuffers().
1295 *
1296 * \param drawable Drawable whose buffers are queried.
1297 * \param buffers [out] List of buffers returned by DRI2 query.
1298 * \param buffer_count [out] Number of buffers returned.
1299 *
1300 * \see intel_update_renderbuffers()
1301 * \see DRI2GetBuffers()
1302 * \see DRI2GetBuffersWithFormat()
1303 */
1304 static void
1305 intel_query_dri2_buffers(struct brw_context *brw,
1306 __DRIdrawable *drawable,
1307 __DRIbuffer **buffers,
1308 int *buffer_count)
1309 {
1310 __DRIscreen *screen = brw->intelScreen->driScrnPriv;
1311 struct gl_framebuffer *fb = drawable->driverPrivate;
1312 int i = 0;
1313 unsigned attachments[8];
1314
1315 struct intel_renderbuffer *front_rb;
1316 struct intel_renderbuffer *back_rb;
1317
1318 front_rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1319 back_rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1320
1321 memset(attachments, 0, sizeof(attachments));
1322 if ((_mesa_is_front_buffer_drawing(fb) ||
1323 _mesa_is_front_buffer_reading(fb) ||
1324 !back_rb) && front_rb) {
1325 /* If a fake front buffer is in use, then querying for
1326 * __DRI_BUFFER_FRONT_LEFT will cause the server to copy the image from
1327 * the real front buffer to the fake front buffer. So before doing the
1328 * query, we need to make sure all the pending drawing has landed in the
1329 * real front buffer.
1330 */
1331 intel_batchbuffer_flush(brw);
1332 intel_flush_front(&brw->ctx);
1333
1334 attachments[i++] = __DRI_BUFFER_FRONT_LEFT;
1335 attachments[i++] = intel_bits_per_pixel(front_rb);
1336 } else if (front_rb && brw->front_buffer_dirty) {
1337 /* We have pending front buffer rendering, but we aren't querying for a
1338 * front buffer. If the front buffer we have is a fake front buffer,
1339 * the X server is going to throw it away when it processes the query.
1340 * So before doing the query, make sure all the pending drawing has
1341 * landed in the real front buffer.
1342 */
1343 intel_batchbuffer_flush(brw);
1344 intel_flush_front(&brw->ctx);
1345 }
1346
1347 if (back_rb) {
1348 attachments[i++] = __DRI_BUFFER_BACK_LEFT;
1349 attachments[i++] = intel_bits_per_pixel(back_rb);
1350 }
1351
1352 assert(i <= ARRAY_SIZE(attachments));
1353
1354 *buffers = screen->dri2.loader->getBuffersWithFormat(drawable,
1355 &drawable->w,
1356 &drawable->h,
1357 attachments, i / 2,
1358 buffer_count,
1359 drawable->loaderPrivate);
1360 }
1361
1362 /**
1363 * \brief Assign a DRI buffer's DRM region to a renderbuffer.
1364 *
1365 * This is called from intel_update_renderbuffers().
1366 *
1367 * \par Note:
1368 * DRI buffers whose attachment point is DRI2BufferStencil or
1369 * DRI2BufferDepthStencil are handled as special cases.
1370 *
1371 * \param buffer_name is a human readable name, such as "dri2 front buffer",
1372 * that is passed to drm_intel_bo_gem_create_from_name().
1373 *
1374 * \see intel_update_renderbuffers()
1375 */
1376 static void
1377 intel_process_dri2_buffer(struct brw_context *brw,
1378 __DRIdrawable *drawable,
1379 __DRIbuffer *buffer,
1380 struct intel_renderbuffer *rb,
1381 const char *buffer_name)
1382 {
1383 struct gl_framebuffer *fb = drawable->driverPrivate;
1384 drm_intel_bo *bo;
1385
1386 if (!rb)
1387 return;
1388
1389 unsigned num_samples = rb->Base.Base.NumSamples;
1390
1391 /* We try to avoid closing and reopening the same BO name, because the first
1392 * use of a mapping of the buffer involves a bunch of page faulting which is
1393 * moderately expensive.
1394 */
1395 struct intel_mipmap_tree *last_mt;
1396 if (num_samples == 0)
1397 last_mt = rb->mt;
1398 else
1399 last_mt = rb->singlesample_mt;
1400
1401 uint32_t old_name = 0;
1402 if (last_mt) {
1403 /* The bo already has a name because the miptree was created by a
1404 * previous call to intel_process_dri2_buffer(). If a bo already has a
1405 * name, then drm_intel_bo_flink() is a low-cost getter. It does not
1406 * create a new name.
1407 */
1408 drm_intel_bo_flink(last_mt->bo, &old_name);
1409 }
1410
1411 if (old_name == buffer->name)
1412 return;
1413
1414 if (unlikely(INTEL_DEBUG & DEBUG_DRI)) {
1415 fprintf(stderr,
1416 "attaching buffer %d, at %d, cpp %d, pitch %d\n",
1417 buffer->name, buffer->attachment,
1418 buffer->cpp, buffer->pitch);
1419 }
1420
1421 bo = drm_intel_bo_gem_create_from_name(brw->bufmgr, buffer_name,
1422 buffer->name);
1423 if (!bo) {
1424 fprintf(stderr,
1425 "Failed to open BO for returned DRI2 buffer "
1426 "(%dx%d, %s, named %d).\n"
1427 "This is likely a bug in the X Server that will lead to a "
1428 "crash soon.\n",
1429 drawable->w, drawable->h, buffer_name, buffer->name);
1430 return;
1431 }
1432
1433 intel_update_winsys_renderbuffer_miptree(brw, rb, bo,
1434 drawable->w, drawable->h,
1435 buffer->pitch);
1436
1437 if (_mesa_is_front_buffer_drawing(fb) &&
1438 (buffer->attachment == __DRI_BUFFER_FRONT_LEFT ||
1439 buffer->attachment == __DRI_BUFFER_FAKE_FRONT_LEFT) &&
1440 rb->Base.Base.NumSamples > 1) {
1441 intel_renderbuffer_upsample(brw, rb);
1442 }
1443
1444 assert(rb->mt);
1445
1446 drm_intel_bo_unreference(bo);
1447 }
1448
1449 /**
1450 * \brief Query DRI image loader to obtain a DRIdrawable's buffers.
1451 *
1452 * To determine which DRI buffers to request, examine the renderbuffers
1453 * attached to the drawable's framebuffer. Then request the buffers from
1454 * the image loader
1455 *
1456 * This is called from intel_update_renderbuffers().
1457 *
1458 * \param drawable Drawable whose buffers are queried.
1459 * \param buffers [out] List of buffers returned by DRI2 query.
1460 * \param buffer_count [out] Number of buffers returned.
1461 *
1462 * \see intel_update_renderbuffers()
1463 */
1464
1465 static void
1466 intel_update_image_buffer(struct brw_context *intel,
1467 __DRIdrawable *drawable,
1468 struct intel_renderbuffer *rb,
1469 __DRIimage *buffer,
1470 enum __DRIimageBufferMask buffer_type)
1471 {
1472 struct gl_framebuffer *fb = drawable->driverPrivate;
1473
1474 if (!rb || !buffer->bo)
1475 return;
1476
1477 unsigned num_samples = rb->Base.Base.NumSamples;
1478
1479 /* Check and see if we're already bound to the right
1480 * buffer object
1481 */
1482 struct intel_mipmap_tree *last_mt;
1483 if (num_samples == 0)
1484 last_mt = rb->mt;
1485 else
1486 last_mt = rb->singlesample_mt;
1487
1488 if (last_mt && last_mt->bo == buffer->bo)
1489 return;
1490
1491 intel_update_winsys_renderbuffer_miptree(intel, rb, buffer->bo,
1492 buffer->width, buffer->height,
1493 buffer->pitch);
1494
1495 if (_mesa_is_front_buffer_drawing(fb) &&
1496 buffer_type == __DRI_IMAGE_BUFFER_FRONT &&
1497 rb->Base.Base.NumSamples > 1) {
1498 intel_renderbuffer_upsample(intel, rb);
1499 }
1500 }
1501
1502 static void
1503 intel_update_image_buffers(struct brw_context *brw, __DRIdrawable *drawable)
1504 {
1505 struct gl_framebuffer *fb = drawable->driverPrivate;
1506 __DRIscreen *screen = brw->intelScreen->driScrnPriv;
1507 struct intel_renderbuffer *front_rb;
1508 struct intel_renderbuffer *back_rb;
1509 struct __DRIimageList images;
1510 unsigned int format;
1511 uint32_t buffer_mask = 0;
1512
1513 front_rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1514 back_rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1515
1516 if (back_rb)
1517 format = intel_rb_format(back_rb);
1518 else if (front_rb)
1519 format = intel_rb_format(front_rb);
1520 else
1521 return;
1522
1523 if (front_rb && (_mesa_is_front_buffer_drawing(fb) ||
1524 _mesa_is_front_buffer_reading(fb) || !back_rb)) {
1525 buffer_mask |= __DRI_IMAGE_BUFFER_FRONT;
1526 }
1527
1528 if (back_rb)
1529 buffer_mask |= __DRI_IMAGE_BUFFER_BACK;
1530
1531 (*screen->image.loader->getBuffers) (drawable,
1532 driGLFormatToImageFormat(format),
1533 &drawable->dri2.stamp,
1534 drawable->loaderPrivate,
1535 buffer_mask,
1536 &images);
1537
1538 if (images.image_mask & __DRI_IMAGE_BUFFER_FRONT) {
1539 drawable->w = images.front->width;
1540 drawable->h = images.front->height;
1541 intel_update_image_buffer(brw,
1542 drawable,
1543 front_rb,
1544 images.front,
1545 __DRI_IMAGE_BUFFER_FRONT);
1546 }
1547 if (images.image_mask & __DRI_IMAGE_BUFFER_BACK) {
1548 drawable->w = images.back->width;
1549 drawable->h = images.back->height;
1550 intel_update_image_buffer(brw,
1551 drawable,
1552 back_rb,
1553 images.back,
1554 __DRI_IMAGE_BUFFER_BACK);
1555 }
1556 }