brw_context.c revision a7bdd4cba8ddcab8dff59ecaaa7efbd436c6c307
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_TYPES; 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   /* Initialize the software rasterizer and helper modules.
635    *
636    * As of GL 3.1 core, the gen4+ driver doesn't need the swrast context for
637    * software fallbacks (which we have to support on legacy GL to do weird
638    * glDrawPixels(), glBitmap(), and other functions).
639    */
640   if (api != API_OPENGL_CORE && api != API_OPENGLES2) {
641      _swrast_CreateContext(ctx);
642   }
643
644   _vbo_CreateContext(ctx);
645   if (ctx->swrast_context) {
646      _tnl_CreateContext(ctx);
647      TNL_CONTEXT(ctx)->Driver.RunPipeline = _tnl_run_pipeline;
648      _swsetup_CreateContext(ctx);
649
650      /* Configure swrast to match hardware characteristics: */
651      _swrast_allow_pixel_fog(ctx, false);
652      _swrast_allow_vertex_fog(ctx, true);
653   }
654
655   _mesa_meta_init(ctx);
656
657   brw_process_driconf_options(brw);
658   brw_process_intel_debug_variable(brw);
659   brw_initialize_context_constants(brw);
660
661   ctx->Const.ResetStrategy = notify_reset
662      ? GL_LOSE_CONTEXT_ON_RESET_ARB : GL_NO_RESET_NOTIFICATION_ARB;
663
664   /* Reinitialize the context point state.  It depends on ctx->Const values. */
665   _mesa_init_point(ctx);
666
667   intel_batchbuffer_init(brw);
668
669   brw_init_state(brw);
670
671   intelInitExtensions(ctx);
672
673   intel_fbo_init(brw);
674
675   if (brw->gen >= 6) {
676      /* Create a new hardware context.  Using a hardware context means that
677       * our GPU state will be saved/restored on context switch, allowing us
678       * to assume that the GPU is in the same state we left it in.
679       *
680       * This is required for transform feedback buffer offsets, query objects,
681       * and also allows us to reduce how much state we have to emit.
682       */
683      brw->hw_ctx = drm_intel_gem_context_create(brw->bufmgr);
684
685      if (!brw->hw_ctx) {
686         fprintf(stderr, "Gen6+ requires Kernel 3.6 or later.\n");
687         intelDestroyContext(driContextPriv);
688         return false;
689      }
690   }
691
692   brw_init_surface_formats(brw);
693
694   if (brw->is_g4x || brw->gen >= 5) {
695      brw->CMD_VF_STATISTICS = GM45_3DSTATE_VF_STATISTICS;
696      brw->CMD_PIPELINE_SELECT = CMD_PIPELINE_SELECT_GM45;
697  } else {
698      brw->CMD_VF_STATISTICS = GEN4_3DSTATE_VF_STATISTICS;
699      brw->CMD_PIPELINE_SELECT = CMD_PIPELINE_SELECT_965;
700   }
701
702   brw->max_vs_threads = devinfo->max_vs_threads;
703   brw->max_gs_threads = devinfo->max_gs_threads;
704   brw->max_wm_threads = devinfo->max_wm_threads;
705   brw->urb.size = devinfo->urb.size;
706   brw->urb.min_vs_entries = devinfo->urb.min_vs_entries;
707   brw->urb.max_vs_entries = devinfo->urb.max_vs_entries;
708   brw->urb.max_gs_entries = devinfo->urb.max_gs_entries;
709
710   /* Estimate the size of the mappable aperture into the GTT.  There's an
711    * ioctl to get the whole GTT size, but not one to get the mappable subset.
712    * It turns out it's basically always 256MB, though some ancient hardware
713    * was smaller.
714    */
715   uint32_t gtt_size = 256 * 1024 * 1024;
716
717   /* We don't want to map two objects such that a memcpy between them would
718    * just fault one mapping in and then the other over and over forever.  So
719    * we would need to divide the GTT size by 2.  Additionally, some GTT is
720    * taken up by things like the framebuffer and the ringbuffer and such, so
721    * be more conservative.
722    */
723   brw->max_gtt_map_object_size = gtt_size / 4;
724
725   if (brw->gen == 6)
726      brw->urb.gen6_gs_previously_active = false;
727
728   brw->prim_restart.in_progress = false;
729   brw->prim_restart.enable_cut_index = false;
730   brw->gs.enabled = false;
731
732   if (brw->gen < 6) {
733      brw->curbe.last_buf = calloc(1, 4096);
734      brw->curbe.next_buf = calloc(1, 4096);
735   }
736
737   ctx->VertexProgram._MaintainTnlProgram = true;
738   ctx->FragmentProgram._MaintainTexEnvProgram = true;
739
740   brw_draw_init( brw );
741
742   if ((flags & __DRI_CTX_FLAG_DEBUG) != 0) {
743      /* Turn on some extra GL_ARB_debug_output generation. */
744      brw->perf_debug = true;
745   }
746
747   if ((flags & __DRI_CTX_FLAG_ROBUST_BUFFER_ACCESS) != 0)
748      ctx->Const.ContextFlags |= GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB;
749
750   brw_fs_alloc_reg_sets(brw);
751   brw_vec4_alloc_reg_set(brw);
752
753   if (INTEL_DEBUG & DEBUG_SHADER_TIME)
754      brw_init_shader_time(brw);
755
756   _mesa_compute_version(ctx);
757
758   _mesa_initialize_dispatch_tables(ctx);
759   _mesa_initialize_vbo_vtxfmt(ctx);
760
761   if (ctx->Extensions.AMD_performance_monitor) {
762      brw_init_performance_monitors(brw);
763   }
764
765   return true;
766}
767
768void
769intelDestroyContext(__DRIcontext * driContextPriv)
770{
771   struct brw_context *brw =
772      (struct brw_context *) driContextPriv->driverPrivate;
773   struct gl_context *ctx = &brw->ctx;
774
775   assert(brw); /* should never be null */
776   if (!brw)
777      return;
778
779   /* Dump a final BMP in case the application doesn't call SwapBuffers */
780   if (INTEL_DEBUG & DEBUG_AUB) {
781      intel_batchbuffer_flush(brw);
782      aub_dump_bmp(&brw->ctx);
783   }
784
785   _mesa_meta_free(&brw->ctx);
786
787   if (INTEL_DEBUG & DEBUG_SHADER_TIME) {
788      /* Force a report. */
789      brw->shader_time.report_time = 0;
790
791      brw_collect_and_report_shader_time(brw);
792      brw_destroy_shader_time(brw);
793   }
794
795   brw_destroy_state(brw);
796   brw_draw_destroy(brw);
797
798   drm_intel_bo_unreference(brw->curbe.curbe_bo);
799   drm_intel_bo_unreference(brw->vs.base.const_bo);
800   drm_intel_bo_unreference(brw->wm.base.const_bo);
801
802   free(brw->curbe.last_buf);
803   free(brw->curbe.next_buf);
804
805   drm_intel_gem_context_destroy(brw->hw_ctx);
806
807   if (ctx->swrast_context) {
808      _swsetup_DestroyContext(&brw->ctx);
809      _tnl_DestroyContext(&brw->ctx);
810   }
811   _vbo_DestroyContext(&brw->ctx);
812
813   if (ctx->swrast_context)
814      _swrast_DestroyContext(&brw->ctx);
815
816   intel_batchbuffer_free(brw);
817
818   drm_intel_bo_unreference(brw->first_post_swapbuffers_batch);
819   brw->first_post_swapbuffers_batch = NULL;
820
821   driDestroyOptionCache(&brw->optionCache);
822
823   /* free the Mesa context */
824   _mesa_free_context_data(&brw->ctx);
825
826   ralloc_free(brw);
827   driContextPriv->driverPrivate = NULL;
828}
829
830GLboolean
831intelUnbindContext(__DRIcontext * driContextPriv)
832{
833   /* Unset current context and dispath table */
834   _mesa_make_current(NULL, NULL, NULL);
835
836   return true;
837}
838
839/**
840 * Fixes up the context for GLES23 with our default-to-sRGB-capable behavior
841 * on window system framebuffers.
842 *
843 * Desktop GL is fairly reasonable in its handling of sRGB: You can ask if
844 * your renderbuffer can do sRGB encode, and you can flip a switch that does
845 * sRGB encode if the renderbuffer can handle it.  You can ask specifically
846 * for a visual where you're guaranteed to be capable, but it turns out that
847 * everyone just makes all their ARGB8888 visuals capable and doesn't offer
848 * incapable ones, becuase there's no difference between the two in resources
849 * used.  Applications thus get built that accidentally rely on the default
850 * visual choice being sRGB, so we make ours sRGB capable.  Everything sounds
851 * great...
852 *
853 * But for GLES2/3, they decided that it was silly to not turn on sRGB encode
854 * for sRGB renderbuffers you made with the GL_EXT_texture_sRGB equivalent.
855 * So they removed the enable knob and made it "if the renderbuffer is sRGB
856 * capable, do sRGB encode".  Then, for your window system renderbuffers, you
857 * can ask for sRGB visuals and get sRGB encode, or not ask for sRGB visuals
858 * and get no sRGB encode (assuming that both kinds of visual are available).
859 * Thus our choice to support sRGB by default on our visuals for desktop would
860 * result in broken rendering of GLES apps that aren't expecting sRGB encode.
861 *
862 * Unfortunately, renderbuffer setup happens before a context is created.  So
863 * in intel_screen.c we always set up sRGB, and here, if you're a GLES2/3
864 * context (without an sRGB visual, though we don't have sRGB visuals exposed
865 * yet), we go turn that back off before anyone finds out.
866 */
867static void
868intel_gles3_srgb_workaround(struct brw_context *brw,
869                            struct gl_framebuffer *fb)
870{
871   struct gl_context *ctx = &brw->ctx;
872
873   if (_mesa_is_desktop_gl(ctx) || !fb->Visual.sRGBCapable)
874      return;
875
876   /* Some day when we support the sRGB capable bit on visuals available for
877    * GLES, we'll need to respect that and not disable things here.
878    */
879   fb->Visual.sRGBCapable = false;
880   for (int i = 0; i < BUFFER_COUNT; i++) {
881      if (fb->Attachment[i].Renderbuffer &&
882          fb->Attachment[i].Renderbuffer->Format == MESA_FORMAT_SARGB8) {
883         fb->Attachment[i].Renderbuffer->Format = MESA_FORMAT_ARGB8888;
884      }
885   }
886}
887
888GLboolean
889intelMakeCurrent(__DRIcontext * driContextPriv,
890                 __DRIdrawable * driDrawPriv,
891                 __DRIdrawable * driReadPriv)
892{
893   struct brw_context *brw;
894   GET_CURRENT_CONTEXT(curCtx);
895
896   if (driContextPriv)
897      brw = (struct brw_context *) driContextPriv->driverPrivate;
898   else
899      brw = NULL;
900
901   /* According to the glXMakeCurrent() man page: "Pending commands to
902    * the previous context, if any, are flushed before it is released."
903    * But only flush if we're actually changing contexts.
904    */
905   if (brw_context(curCtx) && brw_context(curCtx) != brw) {
906      _mesa_flush(curCtx);
907   }
908
909   if (driContextPriv) {
910      struct gl_context *ctx = &brw->ctx;
911      struct gl_framebuffer *fb, *readFb;
912
913      if (driDrawPriv == NULL && driReadPriv == NULL) {
914         fb = _mesa_get_incomplete_framebuffer();
915         readFb = _mesa_get_incomplete_framebuffer();
916      } else {
917         fb = driDrawPriv->driverPrivate;
918         readFb = driReadPriv->driverPrivate;
919         driContextPriv->dri2.draw_stamp = driDrawPriv->dri2.stamp - 1;
920         driContextPriv->dri2.read_stamp = driReadPriv->dri2.stamp - 1;
921      }
922
923      /* The sRGB workaround changes the renderbuffer's format. We must change
924       * the format before the renderbuffer's miptree get's allocated, otherwise
925       * the formats of the renderbuffer and its miptree will differ.
926       */
927      intel_gles3_srgb_workaround(brw, fb);
928      intel_gles3_srgb_workaround(brw, readFb);
929
930      intel_prepare_render(brw);
931      _mesa_make_current(ctx, fb, readFb);
932   } else {
933      _mesa_make_current(NULL, NULL, NULL);
934   }
935
936   return true;
937}
938
939void
940intel_resolve_for_dri2_flush(struct brw_context *brw,
941                             __DRIdrawable *drawable)
942{
943   if (brw->gen < 6) {
944      /* MSAA and fast color clear are not supported, so don't waste time
945       * checking whether a resolve is needed.
946       */
947      return;
948   }
949
950   struct gl_framebuffer *fb = drawable->driverPrivate;
951   struct intel_renderbuffer *rb;
952
953   /* Usually, only the back buffer will need to be downsampled. However,
954    * the front buffer will also need it if the user has rendered into it.
955    */
956   static const gl_buffer_index buffers[2] = {
957         BUFFER_BACK_LEFT,
958         BUFFER_FRONT_LEFT,
959   };
960
961   for (int i = 0; i < 2; ++i) {
962      rb = intel_get_renderbuffer(fb, buffers[i]);
963      if (rb == NULL || rb->mt == NULL)
964         continue;
965      if (rb->mt->num_samples <= 1)
966         intel_miptree_resolve_color(brw, rb->mt);
967      else
968         intel_miptree_downsample(brw, rb->mt);
969   }
970}
971
972static unsigned
973intel_bits_per_pixel(const struct intel_renderbuffer *rb)
974{
975   return _mesa_get_format_bytes(intel_rb_format(rb)) * 8;
976}
977
978static void
979intel_query_dri2_buffers(struct brw_context *brw,
980                         __DRIdrawable *drawable,
981                         __DRIbuffer **buffers,
982                         int *count);
983
984static void
985intel_process_dri2_buffer(struct brw_context *brw,
986                          __DRIdrawable *drawable,
987                          __DRIbuffer *buffer,
988                          struct intel_renderbuffer *rb,
989                          const char *buffer_name);
990
991static void
992intel_update_image_buffers(struct brw_context *brw, __DRIdrawable *drawable);
993
994static void
995intel_update_dri2_buffers(struct brw_context *brw, __DRIdrawable *drawable)
996{
997   struct gl_framebuffer *fb = drawable->driverPrivate;
998   struct intel_renderbuffer *rb;
999   __DRIbuffer *buffers = NULL;
1000   int i, count;
1001   const char *region_name;
1002
1003   /* Set this up front, so that in case our buffers get invalidated
1004    * while we're getting new buffers, we don't clobber the stamp and
1005    * thus ignore the invalidate. */
1006   drawable->lastStamp = drawable->dri2.stamp;
1007
1008   if (unlikely(INTEL_DEBUG & DEBUG_DRI))
1009      fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
1010
1011   intel_query_dri2_buffers(brw, drawable, &buffers, &count);
1012
1013   if (buffers == NULL)
1014      return;
1015
1016   for (i = 0; i < count; i++) {
1017       switch (buffers[i].attachment) {
1018       case __DRI_BUFFER_FRONT_LEFT:
1019           rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1020           region_name = "dri2 front buffer";
1021           break;
1022
1023       case __DRI_BUFFER_FAKE_FRONT_LEFT:
1024           rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1025           region_name = "dri2 fake front buffer";
1026           break;
1027
1028       case __DRI_BUFFER_BACK_LEFT:
1029           rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1030           region_name = "dri2 back buffer";
1031           break;
1032
1033       case __DRI_BUFFER_DEPTH:
1034       case __DRI_BUFFER_HIZ:
1035       case __DRI_BUFFER_DEPTH_STENCIL:
1036       case __DRI_BUFFER_STENCIL:
1037       case __DRI_BUFFER_ACCUM:
1038       default:
1039           fprintf(stderr,
1040                   "unhandled buffer attach event, attachment type %d\n",
1041                   buffers[i].attachment);
1042           return;
1043       }
1044
1045       intel_process_dri2_buffer(brw, drawable, &buffers[i], rb, region_name);
1046   }
1047
1048}
1049
1050void
1051intel_update_renderbuffers(__DRIcontext *context, __DRIdrawable *drawable)
1052{
1053   struct brw_context *brw = context->driverPrivate;
1054   __DRIscreen *screen = brw->intelScreen->driScrnPriv;
1055
1056   /* Set this up front, so that in case our buffers get invalidated
1057    * while we're getting new buffers, we don't clobber the stamp and
1058    * thus ignore the invalidate. */
1059   drawable->lastStamp = drawable->dri2.stamp;
1060
1061   if (unlikely(INTEL_DEBUG & DEBUG_DRI))
1062      fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
1063
1064   if (screen->image.loader)
1065      intel_update_image_buffers(brw, drawable);
1066   else
1067      intel_update_dri2_buffers(brw, drawable);
1068
1069   driUpdateFramebufferSize(&brw->ctx, drawable);
1070}
1071
1072/**
1073 * intel_prepare_render should be called anywhere that curent read/drawbuffer
1074 * state is required.
1075 */
1076void
1077intel_prepare_render(struct brw_context *brw)
1078{
1079   __DRIcontext *driContext = brw->driContext;
1080   __DRIdrawable *drawable;
1081
1082   drawable = driContext->driDrawablePriv;
1083   if (drawable && drawable->dri2.stamp != driContext->dri2.draw_stamp) {
1084      if (drawable->lastStamp != drawable->dri2.stamp)
1085         intel_update_renderbuffers(driContext, drawable);
1086      driContext->dri2.draw_stamp = drawable->dri2.stamp;
1087   }
1088
1089   drawable = driContext->driReadablePriv;
1090   if (drawable && drawable->dri2.stamp != driContext->dri2.read_stamp) {
1091      if (drawable->lastStamp != drawable->dri2.stamp)
1092         intel_update_renderbuffers(driContext, drawable);
1093      driContext->dri2.read_stamp = drawable->dri2.stamp;
1094   }
1095
1096   /* If we're currently rendering to the front buffer, the rendering
1097    * that will happen next will probably dirty the front buffer.  So
1098    * mark it as dirty here.
1099    */
1100   if (brw->is_front_buffer_rendering)
1101      brw->front_buffer_dirty = true;
1102
1103   /* Wait for the swapbuffers before the one we just emitted, so we
1104    * don't get too many swaps outstanding for apps that are GPU-heavy
1105    * but not CPU-heavy.
1106    *
1107    * We're using intelDRI2Flush (called from the loader before
1108    * swapbuffer) and glFlush (for front buffer rendering) as the
1109    * indicator that a frame is done and then throttle when we get
1110    * here as we prepare to render the next frame.  At this point for
1111    * round trips for swap/copy and getting new buffers are done and
1112    * we'll spend less time waiting on the GPU.
1113    *
1114    * Unfortunately, we don't have a handle to the batch containing
1115    * the swap, and getting our hands on that doesn't seem worth it,
1116    * so we just us the first batch we emitted after the last swap.
1117    */
1118   if (brw->need_throttle && brw->first_post_swapbuffers_batch) {
1119      if (!brw->disable_throttling)
1120         drm_intel_bo_wait_rendering(brw->first_post_swapbuffers_batch);
1121      drm_intel_bo_unreference(brw->first_post_swapbuffers_batch);
1122      brw->first_post_swapbuffers_batch = NULL;
1123      brw->need_throttle = false;
1124   }
1125}
1126
1127/**
1128 * \brief Query DRI2 to obtain a DRIdrawable's buffers.
1129 *
1130 * To determine which DRI buffers to request, examine the renderbuffers
1131 * attached to the drawable's framebuffer. Then request the buffers with
1132 * DRI2GetBuffers() or DRI2GetBuffersWithFormat().
1133 *
1134 * This is called from intel_update_renderbuffers().
1135 *
1136 * \param drawable      Drawable whose buffers are queried.
1137 * \param buffers       [out] List of buffers returned by DRI2 query.
1138 * \param buffer_count  [out] Number of buffers returned.
1139 *
1140 * \see intel_update_renderbuffers()
1141 * \see DRI2GetBuffers()
1142 * \see DRI2GetBuffersWithFormat()
1143 */
1144static void
1145intel_query_dri2_buffers(struct brw_context *brw,
1146                         __DRIdrawable *drawable,
1147                         __DRIbuffer **buffers,
1148                         int *buffer_count)
1149{
1150   __DRIscreen *screen = brw->intelScreen->driScrnPriv;
1151   struct gl_framebuffer *fb = drawable->driverPrivate;
1152   int i = 0;
1153   unsigned attachments[8];
1154
1155   struct intel_renderbuffer *front_rb;
1156   struct intel_renderbuffer *back_rb;
1157
1158   front_rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1159   back_rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1160
1161   memset(attachments, 0, sizeof(attachments));
1162   if ((brw->is_front_buffer_rendering ||
1163        brw->is_front_buffer_reading ||
1164        !back_rb) && front_rb) {
1165      /* If a fake front buffer is in use, then querying for
1166       * __DRI_BUFFER_FRONT_LEFT will cause the server to copy the image from
1167       * the real front buffer to the fake front buffer.  So before doing the
1168       * query, we need to make sure all the pending drawing has landed in the
1169       * real front buffer.
1170       */
1171      intel_batchbuffer_flush(brw);
1172      intel_flush_front(&brw->ctx);
1173
1174      attachments[i++] = __DRI_BUFFER_FRONT_LEFT;
1175      attachments[i++] = intel_bits_per_pixel(front_rb);
1176   } else if (front_rb && brw->front_buffer_dirty) {
1177      /* We have pending front buffer rendering, but we aren't querying for a
1178       * front buffer.  If the front buffer we have is a fake front buffer,
1179       * the X server is going to throw it away when it processes the query.
1180       * So before doing the query, make sure all the pending drawing has
1181       * landed in the real front buffer.
1182       */
1183      intel_batchbuffer_flush(brw);
1184      intel_flush_front(&brw->ctx);
1185   }
1186
1187   if (back_rb) {
1188      attachments[i++] = __DRI_BUFFER_BACK_LEFT;
1189      attachments[i++] = intel_bits_per_pixel(back_rb);
1190   }
1191
1192   assert(i <= ARRAY_SIZE(attachments));
1193
1194   *buffers = screen->dri2.loader->getBuffersWithFormat(drawable,
1195                                                        &drawable->w,
1196                                                        &drawable->h,
1197                                                        attachments, i / 2,
1198                                                        buffer_count,
1199                                                        drawable->loaderPrivate);
1200}
1201
1202/**
1203 * \brief Assign a DRI buffer's DRM region to a renderbuffer.
1204 *
1205 * This is called from intel_update_renderbuffers().
1206 *
1207 * \par Note:
1208 *    DRI buffers whose attachment point is DRI2BufferStencil or
1209 *    DRI2BufferDepthStencil are handled as special cases.
1210 *
1211 * \param buffer_name is a human readable name, such as "dri2 front buffer",
1212 *        that is passed to intel_region_alloc_for_handle().
1213 *
1214 * \see intel_update_renderbuffers()
1215 * \see intel_region_alloc_for_handle()
1216 */
1217static void
1218intel_process_dri2_buffer(struct brw_context *brw,
1219                          __DRIdrawable *drawable,
1220                          __DRIbuffer *buffer,
1221                          struct intel_renderbuffer *rb,
1222                          const char *buffer_name)
1223{
1224   struct intel_region *region = NULL;
1225
1226   if (!rb)
1227      return;
1228
1229   unsigned num_samples = rb->Base.Base.NumSamples;
1230
1231   /* We try to avoid closing and reopening the same BO name, because the first
1232    * use of a mapping of the buffer involves a bunch of page faulting which is
1233    * moderately expensive.
1234    */
1235   if (num_samples == 0) {
1236       if (rb->mt &&
1237           rb->mt->region &&
1238           rb->mt->region->name == buffer->name)
1239          return;
1240   } else {
1241       if (rb->mt &&
1242           rb->mt->singlesample_mt &&
1243           rb->mt->singlesample_mt->region &&
1244           rb->mt->singlesample_mt->region->name == buffer->name)
1245          return;
1246   }
1247
1248   if (unlikely(INTEL_DEBUG & DEBUG_DRI)) {
1249      fprintf(stderr,
1250              "attaching buffer %d, at %d, cpp %d, pitch %d\n",
1251              buffer->name, buffer->attachment,
1252              buffer->cpp, buffer->pitch);
1253   }
1254
1255   intel_miptree_release(&rb->mt);
1256   region = intel_region_alloc_for_handle(brw->intelScreen,
1257                                          buffer->cpp,
1258                                          drawable->w,
1259                                          drawable->h,
1260                                          buffer->pitch,
1261                                          buffer->name,
1262                                          buffer_name);
1263   if (!region)
1264      return;
1265
1266   rb->mt = intel_miptree_create_for_dri2_buffer(brw,
1267                                                 buffer->attachment,
1268                                                 intel_rb_format(rb),
1269                                                 num_samples,
1270                                                 region);
1271   intel_region_release(&region);
1272}
1273
1274/**
1275 * \brief Query DRI image loader to obtain a DRIdrawable's buffers.
1276 *
1277 * To determine which DRI buffers to request, examine the renderbuffers
1278 * attached to the drawable's framebuffer. Then request the buffers from
1279 * the image loader
1280 *
1281 * This is called from intel_update_renderbuffers().
1282 *
1283 * \param drawable      Drawable whose buffers are queried.
1284 * \param buffers       [out] List of buffers returned by DRI2 query.
1285 * \param buffer_count  [out] Number of buffers returned.
1286 *
1287 * \see intel_update_renderbuffers()
1288 */
1289
1290static void
1291intel_update_image_buffer(struct brw_context *intel,
1292                          __DRIdrawable *drawable,
1293                          struct intel_renderbuffer *rb,
1294                          __DRIimage *buffer,
1295                          enum __DRIimageBufferMask buffer_type)
1296{
1297   struct intel_region *region = buffer->region;
1298
1299   if (!rb || !region)
1300      return;
1301
1302   unsigned num_samples = rb->Base.Base.NumSamples;
1303
1304   if (rb->mt &&
1305       rb->mt->region &&
1306       rb->mt->region == region)
1307      return;
1308
1309   intel_miptree_release(&rb->mt);
1310   rb->mt = intel_miptree_create_for_image_buffer(intel,
1311                                                  buffer_type,
1312                                                  intel_rb_format(rb),
1313                                                  num_samples,
1314                                                  region);
1315}
1316
1317static void
1318intel_update_image_buffers(struct brw_context *brw, __DRIdrawable *drawable)
1319{
1320   struct gl_framebuffer *fb = drawable->driverPrivate;
1321   __DRIscreen *screen = brw->intelScreen->driScrnPriv;
1322   struct intel_renderbuffer *front_rb;
1323   struct intel_renderbuffer *back_rb;
1324   struct __DRIimageList images;
1325   unsigned int format;
1326   uint32_t buffer_mask = 0;
1327
1328   front_rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1329   back_rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1330
1331   if (back_rb)
1332      format = intel_rb_format(back_rb);
1333   else if (front_rb)
1334      format = intel_rb_format(front_rb);
1335   else
1336      return;
1337
1338   if ((brw->is_front_buffer_rendering || brw->is_front_buffer_reading || !back_rb) && front_rb)
1339      buffer_mask |= __DRI_IMAGE_BUFFER_FRONT;
1340
1341   if (back_rb)
1342      buffer_mask |= __DRI_IMAGE_BUFFER_BACK;
1343
1344   (*screen->image.loader->getBuffers) (drawable,
1345                                        driGLFormatToImageFormat(format),
1346                                        &drawable->dri2.stamp,
1347                                        drawable->loaderPrivate,
1348                                        buffer_mask,
1349                                        &images);
1350
1351   if (images.image_mask & __DRI_IMAGE_BUFFER_FRONT) {
1352      drawable->w = images.front->width;
1353      drawable->h = images.front->height;
1354      intel_update_image_buffer(brw,
1355                                drawable,
1356                                front_rb,
1357                                images.front,
1358                                __DRI_IMAGE_BUFFER_FRONT);
1359   }
1360   if (images.image_mask & __DRI_IMAGE_BUFFER_BACK) {
1361      drawable->w = images.back->width;
1362      drawable->h = images.back->height;
1363      intel_update_image_buffer(brw,
1364                                drawable,
1365                                back_rb,
1366                                images.back,
1367                                __DRI_IMAGE_BUFFER_BACK);
1368   }
1369}
1370