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