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