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