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