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