intel_context.c revision bd2410b48df261251f75c2c69785c8cc3182d94d
1/**************************************************************************
2 *
3 * Copyright 2003 Tungsten Graphics, Inc., Cedar Park, Texas.
4 * All Rights Reserved.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sub license, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice (including the
15 * next paragraph) shall be included in all copies or substantial portions
16 * of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
21 * IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS BE LIABLE FOR
22 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 *
26 **************************************************************************/
27
28
29#include "main/glheader.h"
30#include "main/context.h"
31#include "main/extensions.h"
32#include "main/fbobject.h"
33#include "main/framebuffer.h"
34#include "main/imports.h"
35#include "main/points.h"
36#include "main/renderbuffer.h"
37
38#include "swrast/swrast.h"
39#include "swrast_setup/swrast_setup.h"
40#include "tnl/tnl.h"
41#include "drivers/common/driverfuncs.h"
42#include "drivers/common/meta.h"
43
44#include "intel_chipset.h"
45#include "intel_buffers.h"
46#include "intel_tex.h"
47#include "intel_batchbuffer.h"
48#include "intel_clear.h"
49#include "intel_extensions.h"
50#include "intel_pixel.h"
51#include "intel_regions.h"
52#include "intel_buffer_objects.h"
53#include "intel_fbo.h"
54#include "intel_bufmgr.h"
55#include "intel_screen.h"
56#include "intel_mipmap_tree.h"
57
58#include "utils.h"
59#include "../glsl/ralloc.h"
60
61#ifndef INTEL_DEBUG
62int INTEL_DEBUG = (0);
63#endif
64
65
66static const GLubyte *
67intelGetString(struct gl_context * ctx, GLenum name)
68{
69   const struct intel_context *const intel = intel_context(ctx);
70   const char *chipset;
71   static char buffer[128];
72
73   switch (name) {
74   case GL_VENDOR:
75      return (GLubyte *) "Tungsten Graphics, Inc";
76      break;
77
78   case GL_RENDERER:
79      switch (intel->intelScreen->deviceID) {
80      case PCI_CHIP_845_G:
81         chipset = "Intel(R) 845G";
82         break;
83      case PCI_CHIP_I830_M:
84         chipset = "Intel(R) 830M";
85         break;
86      case PCI_CHIP_I855_GM:
87         chipset = "Intel(R) 852GM/855GM";
88         break;
89      case PCI_CHIP_I865_G:
90         chipset = "Intel(R) 865G";
91         break;
92      case PCI_CHIP_I915_G:
93         chipset = "Intel(R) 915G";
94         break;
95      case PCI_CHIP_E7221_G:
96	 chipset = "Intel (R) E7221G (i915)";
97	 break;
98      case PCI_CHIP_I915_GM:
99         chipset = "Intel(R) 915GM";
100         break;
101      case PCI_CHIP_I945_G:
102         chipset = "Intel(R) 945G";
103         break;
104      case PCI_CHIP_I945_GM:
105         chipset = "Intel(R) 945GM";
106         break;
107      case PCI_CHIP_I945_GME:
108         chipset = "Intel(R) 945GME";
109         break;
110      case PCI_CHIP_G33_G:
111	 chipset = "Intel(R) G33";
112	 break;
113      case PCI_CHIP_Q35_G:
114	 chipset = "Intel(R) Q35";
115	 break;
116      case PCI_CHIP_Q33_G:
117	 chipset = "Intel(R) Q33";
118	 break;
119      case PCI_CHIP_IGD_GM:
120      case PCI_CHIP_IGD_G:
121	 chipset = "Intel(R) IGD";
122	 break;
123      case PCI_CHIP_I965_Q:
124	 chipset = "Intel(R) 965Q";
125	 break;
126      case PCI_CHIP_I965_G:
127      case PCI_CHIP_I965_G_1:
128	 chipset = "Intel(R) 965G";
129	 break;
130      case PCI_CHIP_I946_GZ:
131	 chipset = "Intel(R) 946GZ";
132	 break;
133      case PCI_CHIP_I965_GM:
134	 chipset = "Intel(R) 965GM";
135	 break;
136      case PCI_CHIP_I965_GME:
137	 chipset = "Intel(R) 965GME/GLE";
138	 break;
139      case PCI_CHIP_GM45_GM:
140	 chipset = "Mobile Intel® GM45 Express Chipset";
141	 break;
142      case PCI_CHIP_IGD_E_G:
143	 chipset = "Intel(R) Integrated Graphics Device";
144	 break;
145      case PCI_CHIP_G45_G:
146         chipset = "Intel(R) G45/G43";
147         break;
148      case PCI_CHIP_Q45_G:
149         chipset = "Intel(R) Q45/Q43";
150         break;
151      case PCI_CHIP_G41_G:
152         chipset = "Intel(R) G41";
153         break;
154      case PCI_CHIP_B43_G:
155      case PCI_CHIP_B43_G1:
156         chipset = "Intel(R) B43";
157         break;
158      case PCI_CHIP_ILD_G:
159         chipset = "Intel(R) Ironlake Desktop";
160         break;
161      case PCI_CHIP_ILM_G:
162         chipset = "Intel(R) Ironlake Mobile";
163         break;
164      case PCI_CHIP_SANDYBRIDGE_GT1:
165      case PCI_CHIP_SANDYBRIDGE_GT2:
166      case PCI_CHIP_SANDYBRIDGE_GT2_PLUS:
167	 chipset = "Intel(R) Sandybridge Desktop";
168	 break;
169      case PCI_CHIP_SANDYBRIDGE_M_GT1:
170      case PCI_CHIP_SANDYBRIDGE_M_GT2:
171      case PCI_CHIP_SANDYBRIDGE_M_GT2_PLUS:
172	 chipset = "Intel(R) Sandybridge Mobile";
173	 break;
174      case PCI_CHIP_SANDYBRIDGE_S:
175	 chipset = "Intel(R) Sandybridge Server";
176	 break;
177      case PCI_CHIP_IVYBRIDGE_GT1:
178      case PCI_CHIP_IVYBRIDGE_GT2:
179	 chipset = "Intel(R) Ivybridge Desktop";
180	 break;
181      case PCI_CHIP_IVYBRIDGE_M_GT1:
182      case PCI_CHIP_IVYBRIDGE_M_GT2:
183	 chipset = "Intel(R) Ivybridge Mobile";
184	 break;
185      case PCI_CHIP_IVYBRIDGE_S_GT1:
186	 chipset = "Intel(R) Ivybridge Server";
187	 break;
188      case PCI_CHIP_HASWELL_GT1:
189      case PCI_CHIP_HASWELL_GT2:
190	 chipset = "Intel(R) Haswell Desktop";
191	 break;
192      case PCI_CHIP_HASWELL_M_GT1:
193      case PCI_CHIP_HASWELL_M_GT2:
194      case PCI_CHIP_HASWELL_M_ULT_GT2:
195	 chipset = "Intel(R) Haswell Mobile";
196	 break;
197      default:
198         chipset = "Unknown Intel Chipset";
199         break;
200      }
201
202      (void) driGetRendererString(buffer, chipset, 0);
203      return (GLubyte *) buffer;
204
205   default:
206      return NULL;
207   }
208}
209
210static void
211intel_flush_front(struct gl_context *ctx)
212{
213   struct intel_context *intel = intel_context(ctx);
214    __DRIcontext *driContext = intel->driContext;
215    __DRIscreen *const screen = intel->intelScreen->driScrnPriv;
216
217   if ((ctx->DrawBuffer->Name == 0) && intel->front_buffer_dirty) {
218      if (screen->dri2.loader &&
219          (screen->dri2.loader->base.version >= 2)
220	  && (screen->dri2.loader->flushFrontBuffer != NULL) &&
221          driContext->driDrawablePriv &&
222	  driContext->driDrawablePriv->loaderPrivate) {
223	 (*screen->dri2.loader->flushFrontBuffer)(driContext->driDrawablePriv,
224						  driContext->driDrawablePriv->loaderPrivate);
225
226	 /* We set the dirty bit in intel_prepare_render() if we're
227	  * front buffer rendering once we get there.
228	  */
229	 intel->front_buffer_dirty = false;
230      }
231   }
232}
233
234static unsigned
235intel_bits_per_pixel(const struct intel_renderbuffer *rb)
236{
237   return _mesa_get_format_bytes(intel_rb_format(rb)) * 8;
238}
239
240static void
241intel_query_dri2_buffers_no_separate_stencil(struct intel_context *intel,
242					     __DRIdrawable *drawable,
243					     __DRIbuffer **buffers,
244					     int *count);
245
246static void
247intel_process_dri2_buffer_no_separate_stencil(struct intel_context *intel,
248					      __DRIdrawable *drawable,
249					      __DRIbuffer *buffer,
250					      struct intel_renderbuffer *rb,
251					      const char *buffer_name);
252
253static void
254intel_query_dri2_buffers_with_separate_stencil(struct intel_context *intel,
255					       __DRIdrawable *drawable,
256					       __DRIbuffer **buffers,
257					       unsigned **attachments,
258					       int *count);
259
260static void
261intel_process_dri2_buffer_with_separate_stencil(struct intel_context *intel,
262						__DRIdrawable *drawable,
263						__DRIbuffer *buffer,
264						struct intel_renderbuffer *rb,
265						const char *buffer_name);
266static void
267intel_verify_dri2_has_hiz(struct intel_context *intel,
268			  __DRIdrawable *drawable,
269			  __DRIbuffer **buffers,
270			  unsigned **attachments,
271			  int *count);
272
273void
274intel_update_renderbuffers(__DRIcontext *context, __DRIdrawable *drawable)
275{
276   struct gl_framebuffer *fb = drawable->driverPrivate;
277   struct intel_renderbuffer *rb;
278   struct intel_context *intel = context->driverPrivate;
279   __DRIbuffer *buffers = NULL;
280   unsigned *attachments = NULL;
281   int i, count;
282   const char *region_name;
283
284   bool try_separate_stencil =
285      intel->has_separate_stencil &&
286      intel->intelScreen->dri2_has_hiz != INTEL_DRI2_HAS_HIZ_FALSE &&
287      intel->intelScreen->driScrnPriv->dri2.loader != NULL &&
288      intel->intelScreen->driScrnPriv->dri2.loader->base.version > 2 &&
289      intel->intelScreen->driScrnPriv->dri2.loader->getBuffersWithFormat != NULL;
290
291   assert(!intel->must_use_separate_stencil || try_separate_stencil);
292
293   /* If we're rendering to the fake front buffer, make sure all the
294    * pending drawing has landed on the real front buffer.  Otherwise
295    * when we eventually get to DRI2GetBuffersWithFormat the stale
296    * real front buffer contents will get copied to the new fake front
297    * buffer.
298    */
299   if (intel->is_front_buffer_rendering) {
300      intel_flush(&intel->ctx);
301      intel_flush_front(&intel->ctx);
302   }
303
304   /* Set this up front, so that in case our buffers get invalidated
305    * while we're getting new buffers, we don't clobber the stamp and
306    * thus ignore the invalidate. */
307   drawable->lastStamp = drawable->dri2.stamp;
308
309   if (unlikely(INTEL_DEBUG & DEBUG_DRI))
310      fprintf(stderr, "enter %s, drawable %p\n", __func__, drawable);
311
312   if (try_separate_stencil) {
313      intel_query_dri2_buffers_with_separate_stencil(intel, drawable, &buffers,
314						     &attachments, &count);
315   } else {
316      intel_query_dri2_buffers_no_separate_stencil(intel, drawable, &buffers,
317						   &count);
318   }
319
320   if (buffers == NULL)
321      return;
322
323   for (i = 0; i < count; i++) {
324       switch (buffers[i].attachment) {
325       case __DRI_BUFFER_FRONT_LEFT:
326	   rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
327	   region_name = "dri2 front buffer";
328	   break;
329
330       case __DRI_BUFFER_FAKE_FRONT_LEFT:
331	   rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
332	   region_name = "dri2 fake front buffer";
333	   break;
334
335       case __DRI_BUFFER_BACK_LEFT:
336	   rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
337	   region_name = "dri2 back buffer";
338	   break;
339
340       case __DRI_BUFFER_DEPTH:
341	   rb = intel_get_renderbuffer(fb, BUFFER_DEPTH);
342	   region_name = "dri2 depth buffer";
343	   break;
344
345       case __DRI_BUFFER_HIZ:
346	   /* The hiz region resides in the depth renderbuffer. */
347	   rb = intel_get_renderbuffer(fb, BUFFER_DEPTH);
348	   region_name = "dri2 hiz buffer";
349	   break;
350
351       case __DRI_BUFFER_DEPTH_STENCIL:
352	   rb = intel_get_renderbuffer(fb, BUFFER_DEPTH);
353	   region_name = "dri2 depth / stencil buffer";
354	   break;
355
356       case __DRI_BUFFER_STENCIL:
357	   rb = intel_get_renderbuffer(fb, BUFFER_STENCIL);
358	   region_name = "dri2 stencil buffer";
359	   break;
360
361       case __DRI_BUFFER_ACCUM:
362       default:
363	   fprintf(stderr,
364		   "unhandled buffer attach event, attachment type %d\n",
365		   buffers[i].attachment);
366	   return;
367       }
368
369       if (try_separate_stencil) {
370	 intel_process_dri2_buffer_with_separate_stencil(intel, drawable,
371						         &buffers[i], rb,
372						         region_name);
373       } else {
374	 intel_process_dri2_buffer_no_separate_stencil(intel, drawable,
375						       &buffers[i], rb,
376						       region_name);
377       }
378   }
379
380   if (try_separate_stencil
381       && intel->intelScreen->dri2_has_hiz == INTEL_DRI2_HAS_HIZ_UNKNOWN) {
382      intel_verify_dri2_has_hiz(intel, drawable, &buffers, &attachments,
383				&count);
384   }
385
386   if (attachments)
387      free(attachments);
388
389   driUpdateFramebufferSize(&intel->ctx, drawable);
390}
391
392/**
393 * intel_prepare_render should be called anywhere that curent read/drawbuffer
394 * state is required.
395 */
396void
397intel_prepare_render(struct intel_context *intel)
398{
399   __DRIcontext *driContext = intel->driContext;
400   __DRIdrawable *drawable;
401
402   drawable = driContext->driDrawablePriv;
403   if (drawable && drawable->dri2.stamp != driContext->dri2.draw_stamp) {
404      if (drawable->lastStamp != drawable->dri2.stamp)
405	 intel_update_renderbuffers(driContext, drawable);
406      intel_draw_buffer(&intel->ctx);
407      driContext->dri2.draw_stamp = drawable->dri2.stamp;
408   }
409
410   drawable = driContext->driReadablePriv;
411   if (drawable && drawable->dri2.stamp != driContext->dri2.read_stamp) {
412      if (drawable->lastStamp != drawable->dri2.stamp)
413	 intel_update_renderbuffers(driContext, drawable);
414      driContext->dri2.read_stamp = drawable->dri2.stamp;
415   }
416
417   /* If we're currently rendering to the front buffer, the rendering
418    * that will happen next will probably dirty the front buffer.  So
419    * mark it as dirty here.
420    */
421   if (intel->is_front_buffer_rendering)
422      intel->front_buffer_dirty = true;
423
424   /* Wait for the swapbuffers before the one we just emitted, so we
425    * don't get too many swaps outstanding for apps that are GPU-heavy
426    * but not CPU-heavy.
427    *
428    * We're using intelDRI2Flush (called from the loader before
429    * swapbuffer) and glFlush (for front buffer rendering) as the
430    * indicator that a frame is done and then throttle when we get
431    * here as we prepare to render the next frame.  At this point for
432    * round trips for swap/copy and getting new buffers are done and
433    * we'll spend less time waiting on the GPU.
434    *
435    * Unfortunately, we don't have a handle to the batch containing
436    * the swap, and getting our hands on that doesn't seem worth it,
437    * so we just us the first batch we emitted after the last swap.
438    */
439   if (intel->need_throttle && intel->first_post_swapbuffers_batch) {
440      drm_intel_bo_wait_rendering(intel->first_post_swapbuffers_batch);
441      drm_intel_bo_unreference(intel->first_post_swapbuffers_batch);
442      intel->first_post_swapbuffers_batch = NULL;
443      intel->need_throttle = false;
444   }
445}
446
447static void
448intel_viewport(struct gl_context *ctx, GLint x, GLint y, GLsizei w, GLsizei h)
449{
450    struct intel_context *intel = intel_context(ctx);
451    __DRIcontext *driContext = intel->driContext;
452
453    if (intel->saved_viewport)
454	intel->saved_viewport(ctx, x, y, w, h);
455
456    if (ctx->DrawBuffer->Name == 0) {
457       dri2InvalidateDrawable(driContext->driDrawablePriv);
458       dri2InvalidateDrawable(driContext->driReadablePriv);
459    }
460}
461
462static const struct dri_debug_control debug_control[] = {
463   { "tex",   DEBUG_TEXTURE},
464   { "state", DEBUG_STATE},
465   { "ioctl", DEBUG_IOCTL},
466   { "blit",  DEBUG_BLIT},
467   { "mip",   DEBUG_MIPTREE},
468   { "fall",  DEBUG_FALLBACKS},
469   { "verb",  DEBUG_VERBOSE},
470   { "bat",   DEBUG_BATCH},
471   { "pix",   DEBUG_PIXEL},
472   { "buf",   DEBUG_BUFMGR},
473   { "reg",   DEBUG_REGION},
474   { "fbo",   DEBUG_FBO},
475   { "gs",    DEBUG_GS},
476   { "sync",  DEBUG_SYNC},
477   { "prim",  DEBUG_PRIMS },
478   { "vert",  DEBUG_VERTS },
479   { "dri",   DEBUG_DRI },
480   { "sf",    DEBUG_SF },
481   { "san",   DEBUG_SANITY },
482   { "sleep", DEBUG_SLEEP },
483   { "stats", DEBUG_STATS },
484   { "tile",  DEBUG_TILE },
485   { "wm",    DEBUG_WM },
486   { "urb",   DEBUG_URB },
487   { "vs",    DEBUG_VS },
488   { "clip",  DEBUG_CLIP },
489   { "aub",   DEBUG_AUB },
490   { NULL,    0 }
491};
492
493
494static void
495intelInvalidateState(struct gl_context * ctx, GLuint new_state)
496{
497    struct intel_context *intel = intel_context(ctx);
498
499   _swrast_InvalidateState(ctx, new_state);
500   _vbo_InvalidateState(ctx, new_state);
501
502   intel->NewGLState |= new_state;
503
504   if (intel->vtbl.invalidate_state)
505      intel->vtbl.invalidate_state( intel, new_state );
506}
507
508void
509intel_flush_rendering_to_batch(struct gl_context *ctx)
510{
511   struct intel_context *intel = intel_context(ctx);
512
513   if (intel->Fallback)
514      _swrast_flush(ctx);
515
516   if (intel->gen < 4)
517      INTEL_FIREVERTICES(intel);
518}
519
520void
521_intel_flush(struct gl_context *ctx, const char *file, int line)
522{
523   struct intel_context *intel = intel_context(ctx);
524
525   intel_flush_rendering_to_batch(ctx);
526
527   if (intel->batch.used)
528      _intel_batchbuffer_flush(intel, file, line);
529}
530
531static void
532intel_glFlush(struct gl_context *ctx)
533{
534   struct intel_context *intel = intel_context(ctx);
535
536   intel_flush(ctx);
537   intel_flush_front(ctx);
538   if (intel->is_front_buffer_rendering)
539      intel->need_throttle = true;
540}
541
542void
543intelFinish(struct gl_context * ctx)
544{
545   struct intel_context *intel = intel_context(ctx);
546
547   intel_flush(ctx);
548   intel_flush_front(ctx);
549
550   if (intel->batch.last_bo)
551      drm_intel_bo_wait_rendering(intel->batch.last_bo);
552}
553
554void
555intelInitDriverFunctions(struct dd_function_table *functions)
556{
557   _mesa_init_driver_functions(functions);
558
559   functions->Flush = intel_glFlush;
560   functions->Finish = intelFinish;
561   functions->GetString = intelGetString;
562   functions->UpdateState = intelInvalidateState;
563
564   intelInitTextureFuncs(functions);
565   intelInitTextureImageFuncs(functions);
566   intelInitTextureSubImageFuncs(functions);
567   intelInitTextureCopyImageFuncs(functions);
568   intelInitStateFuncs(functions);
569   intelInitClearFuncs(functions);
570   intelInitBufferFuncs(functions);
571   intelInitPixelFuncs(functions);
572   intelInitBufferObjectFuncs(functions);
573   intel_init_syncobj_functions(functions);
574}
575
576bool
577intelInitContext(struct intel_context *intel,
578		 int api,
579                 const struct gl_config * mesaVis,
580                 __DRIcontext * driContextPriv,
581                 void *sharedContextPrivate,
582                 struct dd_function_table *functions)
583{
584   struct gl_context *ctx = &intel->ctx;
585   struct gl_context *shareCtx = (struct gl_context *) sharedContextPrivate;
586   __DRIscreen *sPriv = driContextPriv->driScreenPriv;
587   struct intel_screen *intelScreen = sPriv->driverPrivate;
588   int bo_reuse_mode;
589   struct gl_config visual;
590
591   /* we can't do anything without a connection to the device */
592   if (intelScreen->bufmgr == NULL)
593      return false;
594
595   /* Can't rely on invalidate events, fall back to glViewport hack */
596   if (!driContextPriv->driScreenPriv->dri2.useInvalidate) {
597      intel->saved_viewport = functions->Viewport;
598      functions->Viewport = intel_viewport;
599   }
600
601   if (mesaVis == NULL) {
602      memset(&visual, 0, sizeof visual);
603      mesaVis = &visual;
604   }
605
606   if (!_mesa_initialize_context(&intel->ctx, api, mesaVis, shareCtx,
607                                 functions, (void *) intel)) {
608      printf("%s: failed to init mesa context\n", __FUNCTION__);
609      return false;
610   }
611
612   driContextPriv->driverPrivate = intel;
613   intel->intelScreen = intelScreen;
614   intel->driContext = driContextPriv;
615   intel->driFd = sPriv->fd;
616
617   intel->gen = intelScreen->gen;
618
619   const int devID = intelScreen->deviceID;
620   if (IS_SNB_GT1(devID) || IS_IVB_GT1(devID) || IS_HSW_GT1(devID))
621      intel->gt = 1;
622   else if (IS_SNB_GT2(devID) || IS_IVB_GT2(devID) || IS_HSW_GT2(devID))
623      intel->gt = 2;
624   else
625      intel->gt = 0;
626
627   if (IS_HASWELL(devID)) {
628      intel->is_haswell = true;
629   } else if (IS_G4X(devID)) {
630      intel->is_g4x = true;
631   } else if (IS_945(devID)) {
632      intel->is_945 = true;
633   }
634
635   if (intel->gen >= 5) {
636      intel->needs_ff_sync = true;
637   }
638
639   intel->has_separate_stencil = intel->intelScreen->hw_has_separate_stencil;
640   intel->must_use_separate_stencil = intel->intelScreen->hw_must_use_separate_stencil;
641   intel->has_hiz = intel->gen >= 6 && !intel->is_haswell;
642   intel->has_llc = intel->intelScreen->hw_has_llc;
643   intel->has_swizzling = intel->intelScreen->hw_has_swizzling;
644
645   memset(&ctx->TextureFormatSupported,
646	  0, sizeof(ctx->TextureFormatSupported));
647
648   driParseConfigFiles(&intel->optionCache, &intelScreen->optionCache,
649                       sPriv->myNum, (intel->gen >= 4) ? "i965" : "i915");
650   if (intel->gen < 4)
651      intel->maxBatchSize = 4096;
652   else
653      intel->maxBatchSize = sizeof(intel->batch.map);
654
655   intel->bufmgr = intelScreen->bufmgr;
656
657   bo_reuse_mode = driQueryOptioni(&intel->optionCache, "bo_reuse");
658   switch (bo_reuse_mode) {
659   case DRI_CONF_BO_REUSE_DISABLED:
660      break;
661   case DRI_CONF_BO_REUSE_ALL:
662      intel_bufmgr_gem_enable_reuse(intel->bufmgr);
663      break;
664   }
665
666   ctx->Const.MinLineWidth = 1.0;
667   ctx->Const.MinLineWidthAA = 1.0;
668   ctx->Const.MaxLineWidth = 5.0;
669   ctx->Const.MaxLineWidthAA = 5.0;
670   ctx->Const.LineWidthGranularity = 0.5;
671
672   ctx->Const.MinPointSize = 1.0;
673   ctx->Const.MinPointSizeAA = 1.0;
674   ctx->Const.MaxPointSize = 255.0;
675   ctx->Const.MaxPointSizeAA = 3.0;
676   ctx->Const.PointSizeGranularity = 1.0;
677
678   ctx->Const.MaxSamples = 1.0;
679
680   if (intel->gen >= 6)
681      ctx->Const.MaxClipPlanes = 8;
682
683   ctx->Const.StripTextureBorder = GL_TRUE;
684
685   /* reinitialize the context point state.
686    * It depend on constants in __struct gl_contextRec::Const
687    */
688   _mesa_init_point(ctx);
689
690   if (intel->gen >= 4) {
691      ctx->Const.MaxRenderbufferSize = 8192;
692   } else {
693      ctx->Const.MaxRenderbufferSize = 2048;
694   }
695
696   /* Initialize the software rasterizer and helper modules. */
697   _swrast_CreateContext(ctx);
698   _vbo_CreateContext(ctx);
699   _tnl_CreateContext(ctx);
700   _swsetup_CreateContext(ctx);
701
702   /* Configure swrast to match hardware characteristics: */
703   _swrast_allow_pixel_fog(ctx, false);
704   _swrast_allow_vertex_fog(ctx, true);
705
706   _mesa_meta_init(ctx);
707
708   intel->hw_stencil = mesaVis->stencilBits && mesaVis->depthBits == 24;
709   intel->hw_stipple = 1;
710
711   /* XXX FBO: this doesn't seem to be used anywhere */
712   switch (mesaVis->depthBits) {
713   case 0:                     /* what to do in this case? */
714   case 16:
715      intel->polygon_offset_scale = 1.0;
716      break;
717   case 24:
718      intel->polygon_offset_scale = 2.0;     /* req'd to pass glean */
719      break;
720   default:
721      assert(0);
722      break;
723   }
724
725   if (intel->gen >= 4)
726      intel->polygon_offset_scale /= 0xffff;
727
728   intel->RenderIndex = ~0;
729
730   switch (ctx->API) {
731   case API_OPENGL:
732      intelInitExtensions(ctx);
733      break;
734   case API_OPENGLES:
735      intelInitExtensionsES1(ctx);
736      break;
737   case API_OPENGLES2:
738      intelInitExtensionsES2(ctx);
739      break;
740   }
741
742   INTEL_DEBUG = driParseDebugString(getenv("INTEL_DEBUG"), debug_control);
743   if (INTEL_DEBUG & DEBUG_BUFMGR)
744      dri_bufmgr_set_debug(intel->bufmgr, true);
745
746   if (INTEL_DEBUG & DEBUG_AUB)
747      drm_intel_bufmgr_gem_set_aub_dump(intel->bufmgr, true);
748
749   intel_batchbuffer_init(intel);
750
751   intel_fbo_init(intel);
752
753   intel->use_texture_tiling = driQueryOptionb(&intel->optionCache,
754					       "texture_tiling");
755   intel->use_early_z = driQueryOptionb(&intel->optionCache, "early_z");
756
757   if (!driQueryOptionb(&intel->optionCache, "hiz")) {
758       intel->has_hiz = false;
759       /* On gen6, you can only do separate stencil with HIZ. */
760       if (intel->gen == 6)
761	  intel->has_separate_stencil = false;
762   }
763
764   intel->prim.primitive = ~0;
765
766   /* Force all software fallbacks */
767   if (driQueryOptionb(&intel->optionCache, "no_rast")) {
768      fprintf(stderr, "disabling 3D rasterization\n");
769      intel->no_rast = 1;
770   }
771
772   if (driQueryOptionb(&intel->optionCache, "always_flush_batch")) {
773      fprintf(stderr, "flushing batchbuffer before/after each draw call\n");
774      intel->always_flush_batch = 1;
775   }
776
777   if (driQueryOptionb(&intel->optionCache, "always_flush_cache")) {
778      fprintf(stderr, "flushing GPU caches before/after each draw call\n");
779      intel->always_flush_cache = 1;
780   }
781
782   return true;
783}
784
785void
786intelDestroyContext(__DRIcontext * driContextPriv)
787{
788   struct intel_context *intel =
789      (struct intel_context *) driContextPriv->driverPrivate;
790
791   assert(intel);               /* should never be null */
792   if (intel) {
793      INTEL_FIREVERTICES(intel);
794
795      _mesa_meta_free(&intel->ctx);
796
797      intel->vtbl.destroy(intel);
798
799      _swsetup_DestroyContext(&intel->ctx);
800      _tnl_DestroyContext(&intel->ctx);
801      _vbo_DestroyContext(&intel->ctx);
802
803      _swrast_DestroyContext(&intel->ctx);
804      intel->Fallback = 0x0;      /* don't call _swrast_Flush later */
805
806      intel_batchbuffer_free(intel);
807
808      free(intel->prim.vb);
809      intel->prim.vb = NULL;
810      drm_intel_bo_unreference(intel->prim.vb_bo);
811      intel->prim.vb_bo = NULL;
812      drm_intel_bo_unreference(intel->first_post_swapbuffers_batch);
813      intel->first_post_swapbuffers_batch = NULL;
814
815      driDestroyOptionCache(&intel->optionCache);
816
817      /* free the Mesa context */
818      _mesa_free_context_data(&intel->ctx);
819
820      _math_matrix_dtr(&intel->ViewportMatrix);
821
822      ralloc_free(intel);
823      driContextPriv->driverPrivate = NULL;
824   }
825}
826
827GLboolean
828intelUnbindContext(__DRIcontext * driContextPriv)
829{
830   /* Unset current context and dispath table */
831   _mesa_make_current(NULL, NULL, NULL);
832
833   return true;
834}
835
836GLboolean
837intelMakeCurrent(__DRIcontext * driContextPriv,
838                 __DRIdrawable * driDrawPriv,
839                 __DRIdrawable * driReadPriv)
840{
841   struct intel_context *intel;
842   GET_CURRENT_CONTEXT(curCtx);
843
844   if (driContextPriv)
845      intel = (struct intel_context *) driContextPriv->driverPrivate;
846   else
847      intel = NULL;
848
849   /* According to the glXMakeCurrent() man page: "Pending commands to
850    * the previous context, if any, are flushed before it is released."
851    * But only flush if we're actually changing contexts.
852    */
853   if (intel_context(curCtx) && intel_context(curCtx) != intel) {
854      _mesa_flush(curCtx);
855   }
856
857   if (driContextPriv) {
858      struct gl_framebuffer *fb, *readFb;
859
860      if (driDrawPriv == NULL && driReadPriv == NULL) {
861	 fb = _mesa_get_incomplete_framebuffer();
862	 readFb = _mesa_get_incomplete_framebuffer();
863      } else {
864	 fb = driDrawPriv->driverPrivate;
865	 readFb = driReadPriv->driverPrivate;
866	 driContextPriv->dri2.draw_stamp = driDrawPriv->dri2.stamp - 1;
867	 driContextPriv->dri2.read_stamp = driReadPriv->dri2.stamp - 1;
868      }
869
870      intel_prepare_render(intel);
871      _mesa_make_current(&intel->ctx, fb, readFb);
872
873      /* We do this in intel_prepare_render() too, but intel->ctx.DrawBuffer
874       * is NULL at that point.  We can't call _mesa_makecurrent()
875       * first, since we need the buffer size for the initial
876       * viewport.  So just call intel_draw_buffer() again here. */
877      intel_draw_buffer(&intel->ctx);
878   }
879   else {
880      _mesa_make_current(NULL, NULL, NULL);
881   }
882
883   return true;
884}
885
886/**
887 * \brief Query DRI2 to obtain a DRIdrawable's buffers.
888 *
889 * To determine which DRI buffers to request, examine the renderbuffers
890 * attached to the drawable's framebuffer. Then request the buffers with
891 * DRI2GetBuffers() or DRI2GetBuffersWithFormat().
892 *
893 * This is called from intel_update_renderbuffers(). It is used only if either
894 * the hardware or the X driver lacks separate stencil support.
895 *
896 * \param drawable      Drawable whose buffers are queried.
897 * \param buffers       [out] List of buffers returned by DRI2 query.
898 * \param buffer_count  [out] Number of buffers returned.
899 *
900 * \see intel_update_renderbuffers()
901 * \see DRI2GetBuffers()
902 * \see DRI2GetBuffersWithFormat()
903 */
904static void
905intel_query_dri2_buffers_no_separate_stencil(struct intel_context *intel,
906					     __DRIdrawable *drawable,
907					     __DRIbuffer **buffers,
908					     int *buffer_count)
909{
910   assert(!intel->must_use_separate_stencil);
911
912   __DRIscreen *screen = intel->intelScreen->driScrnPriv;
913   struct gl_framebuffer *fb = drawable->driverPrivate;
914
915   if (screen->dri2.loader
916       && screen->dri2.loader->base.version > 2
917       && screen->dri2.loader->getBuffersWithFormat != NULL) {
918
919      int i = 0;
920      const int max_attachments = 4;
921      unsigned *attachments = calloc(2 * max_attachments, sizeof(unsigned));
922
923      struct intel_renderbuffer *front_rb;
924      struct intel_renderbuffer *back_rb;
925      struct intel_renderbuffer *depth_rb;
926      struct intel_renderbuffer *stencil_rb;
927
928      front_rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
929      back_rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
930      depth_rb = intel_get_renderbuffer(fb, BUFFER_DEPTH);
931      stencil_rb = intel_get_renderbuffer(fb, BUFFER_STENCIL);
932
933      if ((intel->is_front_buffer_rendering ||
934	   intel->is_front_buffer_reading ||
935	   !back_rb) && front_rb) {
936	 attachments[i++] = __DRI_BUFFER_FRONT_LEFT;
937	 attachments[i++] = intel_bits_per_pixel(front_rb);
938      }
939
940      if (back_rb) {
941	 attachments[i++] = __DRI_BUFFER_BACK_LEFT;
942	 attachments[i++] = intel_bits_per_pixel(back_rb);
943      }
944
945      if (depth_rb && stencil_rb) {
946	 attachments[i++] = __DRI_BUFFER_DEPTH_STENCIL;
947	 attachments[i++] = intel_bits_per_pixel(depth_rb);
948      } else if (depth_rb) {
949	 attachments[i++] = __DRI_BUFFER_DEPTH;
950	 attachments[i++] = intel_bits_per_pixel(depth_rb);
951      } else if (stencil_rb) {
952	 attachments[i++] = __DRI_BUFFER_STENCIL;
953	 attachments[i++] = intel_bits_per_pixel(stencil_rb);
954      }
955
956      assert(i <= 2 * max_attachments);
957
958      *buffers = screen->dri2.loader->getBuffersWithFormat(drawable,
959							   &drawable->w,
960							   &drawable->h,
961							   attachments, i / 2,
962							   buffer_count,
963							   drawable->loaderPrivate);
964      free(attachments);
965
966   } else if (screen->dri2.loader) {
967
968      int i = 0;
969      const int max_attachments = 4;
970      unsigned *attachments = calloc(max_attachments, sizeof(unsigned));
971
972      if (intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT))
973	 attachments[i++] = __DRI_BUFFER_FRONT_LEFT;
974      if (intel_get_renderbuffer(fb, BUFFER_BACK_LEFT))
975	 attachments[i++] = __DRI_BUFFER_BACK_LEFT;
976      if (intel_get_renderbuffer(fb, BUFFER_DEPTH))
977	 attachments[i++] = __DRI_BUFFER_DEPTH;
978      if (intel_get_renderbuffer(fb, BUFFER_STENCIL))
979	 attachments[i++] = __DRI_BUFFER_STENCIL;
980
981      assert(i <= max_attachments);
982
983      *buffers = screen->dri2.loader->getBuffersWithFormat(drawable,
984							   &drawable->w,
985							   &drawable->h,
986							   attachments, i,
987							   buffer_count,
988							   drawable->loaderPrivate);
989      free(attachments);
990
991   } else {
992      *buffers = NULL;
993      *buffer_count = 0;
994   }
995}
996
997/**
998 * \brief Assign a DRI buffer's DRM region to a renderbuffer.
999 *
1000 * This is called from intel_update_renderbuffers().  It is used only if
1001 * either the hardware or the X driver lacks separate stencil support.
1002 *
1003 * \par Note:
1004 *    DRI buffers whose attachment point is DRI2BufferStencil or
1005 *    DRI2BufferDepthStencil are handled as special cases.
1006 *
1007 * \param buffer_name is a human readable name, such as "dri2 front buffer",
1008 *        that is passed to intel_region_alloc_for_handle().
1009 *
1010 * \see intel_update_renderbuffers()
1011 * \see intel_region_alloc_for_handle()
1012 */
1013static void
1014intel_process_dri2_buffer_no_separate_stencil(struct intel_context *intel,
1015					      __DRIdrawable *drawable,
1016					      __DRIbuffer *buffer,
1017					      struct intel_renderbuffer *rb,
1018					      const char *buffer_name)
1019{
1020   assert(!intel->must_use_separate_stencil);
1021
1022   struct gl_framebuffer *fb = drawable->driverPrivate;
1023   struct intel_renderbuffer *depth_rb = NULL;
1024
1025   if (!rb)
1026      return;
1027
1028   if (rb->mt &&
1029       rb->mt->region &&
1030       rb->mt->region->name == buffer->name)
1031      return;
1032
1033   if (unlikely(INTEL_DEBUG & DEBUG_DRI)) {
1034      fprintf(stderr,
1035	      "attaching buffer %d, at %d, cpp %d, pitch %d\n",
1036	      buffer->name, buffer->attachment,
1037	      buffer->cpp, buffer->pitch);
1038   }
1039
1040   bool identify_depth_and_stencil = false;
1041   if (buffer->attachment == __DRI_BUFFER_STENCIL) {
1042      struct intel_renderbuffer *depth_rb =
1043	 intel_get_renderbuffer(fb, BUFFER_DEPTH);
1044      identify_depth_and_stencil = depth_rb && depth_rb->mt;
1045   }
1046
1047   if (identify_depth_and_stencil) {
1048      if (unlikely(INTEL_DEBUG & DEBUG_DRI)) {
1049	 fprintf(stderr, "(reusing depth buffer as stencil)\n");
1050      }
1051      intel_miptree_reference(&rb->mt, depth_rb->mt);
1052   } else {
1053      intel_miptree_release(&rb->mt);
1054      struct intel_region *region =
1055                   intel_region_alloc_for_handle(intel->intelScreen,
1056						 buffer->cpp,
1057						 drawable->w,
1058						 drawable->h,
1059						 buffer->pitch / buffer->cpp,
1060						 buffer->name,
1061						 buffer_name);
1062      if (!region)
1063	 return;
1064
1065      rb->mt = intel_miptree_create_for_region(intel,
1066                                               GL_TEXTURE_2D,
1067                                               intel_rb_format(rb),
1068                                               region);
1069      intel_region_release(&region);
1070      if (!rb->mt)
1071	 return;
1072   }
1073
1074   if (buffer->attachment == __DRI_BUFFER_DEPTH_STENCIL) {
1075      struct intel_renderbuffer *stencil_rb =
1076	 intel_get_renderbuffer(fb, BUFFER_STENCIL);
1077
1078      if (!stencil_rb)
1079	 return;
1080
1081      /* The rb passed in is the BUFFER_DEPTH attachment, and we need
1082       * to associate this region to BUFFER_STENCIL as well.
1083       */
1084      intel_miptree_reference(&stencil_rb->mt, rb->mt);
1085   }
1086}
1087
1088/**
1089 * \brief Query DRI2 to obtain a DRIdrawable's buffers.
1090 *
1091 * To determine which DRI buffers to request, examine the renderbuffers
1092 * attached to the drawable's framebuffer. Then request the buffers with
1093 * DRI2GetBuffersWithFormat().
1094 *
1095 * This is called from intel_update_renderbuffers(). It is used when 1) the
1096 * hardware supports separate stencil and 2) the X driver's separate stencil
1097 * support has been verified to work or is still unknown.
1098 *
1099 * \param drawable      Drawable whose buffers are queried.
1100 * \param buffers       [out] List of buffers returned by DRI2 query.
1101 * \param buffer_count  [out] Number of buffers returned.
1102 * \param attachments   [out] List of pairs (attachment_point, bits_per_pixel)
1103 *                      that were submitted in the DRI2 query. Number of pairs
1104 *                      is same as buffer_count.
1105 *
1106 * \see intel_update_renderbuffers()
1107 * \see DRI2GetBuffersWithFormat()
1108 * \see enum intel_dri2_has_hiz
1109 */
1110static void
1111intel_query_dri2_buffers_with_separate_stencil(struct intel_context *intel,
1112					       __DRIdrawable *drawable,
1113					       __DRIbuffer **buffers,
1114					       unsigned **attachments,
1115					       int *count)
1116{
1117   assert(intel->has_separate_stencil);
1118
1119   __DRIscreen *screen = intel->intelScreen->driScrnPriv;
1120   struct gl_framebuffer *fb = drawable->driverPrivate;
1121
1122   const int max_attachments = 5;
1123   int i = 0;
1124
1125   *attachments = calloc(2 * max_attachments, sizeof(unsigned));
1126   if (!*attachments) {
1127      *buffers = NULL;
1128      *count = 0;
1129      return;
1130   }
1131
1132   struct intel_renderbuffer *front_rb;
1133   struct intel_renderbuffer *back_rb;
1134   struct intel_renderbuffer *depth_rb;
1135   struct intel_renderbuffer *stencil_rb;
1136
1137   front_rb = intel_get_renderbuffer(fb, BUFFER_FRONT_LEFT);
1138   back_rb = intel_get_renderbuffer(fb, BUFFER_BACK_LEFT);
1139   depth_rb = intel_get_renderbuffer(fb, BUFFER_DEPTH);
1140   stencil_rb = intel_get_renderbuffer(fb, BUFFER_STENCIL);
1141
1142   if ((intel->is_front_buffer_rendering ||
1143	intel->is_front_buffer_reading ||
1144	!back_rb) && front_rb) {
1145      (*attachments)[i++] = __DRI_BUFFER_FRONT_LEFT;
1146      (*attachments)[i++] = intel_bits_per_pixel(front_rb);
1147   }
1148
1149   if (back_rb) {
1150      (*attachments)[i++] = __DRI_BUFFER_BACK_LEFT;
1151      (*attachments)[i++] = intel_bits_per_pixel(back_rb);
1152   }
1153
1154   /*
1155    * We request a separate stencil buffer, and perhaps a hiz buffer too, even
1156    * if we do not yet know if the X driver supports it. See the comments for
1157    * 'enum intel_dri2_has_hiz'.
1158    */
1159
1160   if (depth_rb) {
1161      (*attachments)[i++] = __DRI_BUFFER_DEPTH;
1162      (*attachments)[i++] = intel_bits_per_pixel(depth_rb);
1163
1164      if (intel->vtbl.is_hiz_depth_format(intel, intel_rb_format(depth_rb))) {
1165	 /* Depth and hiz buffer have same bpp. */
1166	 (*attachments)[i++] = __DRI_BUFFER_HIZ;
1167	 (*attachments)[i++] = intel_bits_per_pixel(depth_rb);
1168      }
1169   }
1170
1171   if (stencil_rb) {
1172      assert(intel_rb_format(stencil_rb) == MESA_FORMAT_S8);
1173      (*attachments)[i++] = __DRI_BUFFER_STENCIL;
1174      (*attachments)[i++] = intel_bits_per_pixel(stencil_rb);
1175   }
1176
1177   assert(i <= 2 * max_attachments);
1178
1179   *buffers = screen->dri2.loader->getBuffersWithFormat(drawable,
1180							&drawable->w,
1181							&drawable->h,
1182							*attachments, i / 2,
1183							count,
1184							drawable->loaderPrivate);
1185
1186   if (!*buffers) {
1187      free(*attachments);
1188      *attachments = NULL;
1189      *count = 0;
1190   }
1191}
1192
1193/**
1194 * \brief Assign a DRI buffer's DRM region to a renderbuffer.
1195 *
1196 * This is called from intel_update_renderbuffers().  It is used when 1) the
1197 * hardware supports separate stencil and 2) the X driver's separate stencil
1198 * support has been verified to work or is still unknown.
1199 *
1200 * \par Note:
1201 *    DRI buffers whose attachment point is DRI2BufferStencil or DRI2BufferHiz
1202 *    are handled as special cases.
1203 *
1204 * \param buffer_name is a human readable name, such as "dri2 front buffer",
1205 *        that is passed to intel_region_alloc_for_handle().
1206 *
1207 * \see intel_update_renderbuffers()
1208 * \see intel_region_alloc_for_handle()
1209 * \see enum intel_dri2_has_hiz
1210 */
1211static void
1212intel_process_dri2_buffer_with_separate_stencil(struct intel_context *intel,
1213						__DRIdrawable *drawable,
1214						__DRIbuffer *buffer,
1215						struct intel_renderbuffer *rb,
1216						const char *buffer_name)
1217{
1218   assert(intel->has_separate_stencil);
1219   assert(buffer->attachment != __DRI_BUFFER_DEPTH_STENCIL);
1220
1221   if (!rb)
1222      return;
1223
1224   /* Check if we failed to allocate the depth miptree earlier. */
1225   if (buffer->attachment == __DRI_BUFFER_HIZ && rb->mt == NULL)
1226     return;
1227
1228   /* If the renderbuffer's and DRIbuffer's regions match, then continue. */
1229   if ((buffer->attachment != __DRI_BUFFER_HIZ &&
1230	rb->mt &&
1231	rb->mt->region &&
1232	rb->mt->region->name == buffer->name) ||
1233       (buffer->attachment == __DRI_BUFFER_HIZ &&
1234	rb->mt &&
1235	rb->mt->hiz_mt &&
1236	rb->mt->hiz_mt->region->name == buffer->name)) {
1237      return;
1238   }
1239
1240   if (unlikely(INTEL_DEBUG & DEBUG_DRI)) {
1241      fprintf(stderr,
1242	      "attaching buffer %d, at %d, cpp %d, pitch %d\n",
1243	      buffer->name, buffer->attachment,
1244	      buffer->cpp, buffer->pitch);
1245   }
1246
1247   int buffer_width;
1248   int buffer_height;
1249   if (buffer->attachment == __DRI_BUFFER_STENCIL) {
1250      /* The stencil buffer has quirky pitch requirements.  From Section
1251       * 2.11.5.6.2.1 3DSTATE_STENCIL_BUFFER, field "Surface Pitch":
1252       *    The pitch must be set to 2x the value computed based on width, as
1253       *    the stencil buffer is stored with two rows interleaved.
1254       *
1255       * To satisfy the pitch requirement, the X driver allocated the region
1256       * with the following dimensions.
1257       */
1258       buffer_width = ALIGN(drawable->w, 64);
1259       buffer_height = ALIGN(ALIGN(drawable->h, 2) / 2, 64);
1260   } else {
1261       buffer_width = drawable->w;
1262       buffer_height = drawable->h;
1263   }
1264
1265   /* Release the buffer storage now in case we have to return early
1266    * due to failure to allocate new storage.
1267    */
1268   if (buffer->attachment == __DRI_BUFFER_HIZ) {
1269      assert(rb->mt);
1270      intel_miptree_release(&rb->mt->hiz_mt);
1271   } else {
1272      intel_miptree_release(&rb->mt);
1273   }
1274
1275   struct intel_region *region =
1276      intel_region_alloc_for_handle(intel->intelScreen,
1277				    buffer->cpp,
1278				    buffer_width,
1279				    buffer_height,
1280				    buffer->pitch / buffer->cpp,
1281				    buffer->name,
1282				    buffer_name);
1283   if (!region)
1284      return;
1285
1286   struct intel_mipmap_tree *mt =
1287      intel_miptree_create_for_region(intel,
1288				      GL_TEXTURE_2D,
1289				      intel_rb_format(rb),
1290				      region);
1291   intel_region_release(&region);
1292
1293   /* Associate buffer with new storage. */
1294   if (buffer->attachment == __DRI_BUFFER_HIZ) {
1295      assert(rb->mt);
1296      rb->mt->hiz_mt = mt;
1297   } else {
1298      rb->mt = mt;
1299   }
1300}
1301
1302/**
1303 * \brief Verify that the X driver supports hiz and separate stencil.
1304 *
1305 * This implements the cleanup stage of the handshake described in the
1306 * comments for 'enum intel_dri2_has_hiz'.
1307 *
1308 * This should be called from intel_update_renderbuffers() after 1) the
1309 * DRIdrawable has been queried for its buffers via DRI2GetBuffersWithFormat()
1310 * and 2) the DRM region of each returned DRIbuffer has been assigned to the
1311 * appropriate intel_renderbuffer. Furthermore, this should be called *only*
1312 * when 1) intel_update_renderbuffers() tried to used the X driver's separate
1313 * stencil functionality and 2) it has not yet been determined if the X driver
1314 * supports separate stencil.
1315 *
1316 * If we determine that the X driver does have support, then we set
1317 * intel_screen.dri2_has_hiz to true and return.
1318 *
1319 * If we determine that the X driver lacks support, and we requested
1320 * a DRI2BufferDepth and DRI2BufferStencil, then we must remedy the mistake by
1321 * taking the following actions:
1322 *    1. Discard the framebuffer's stencil and depth renderbuffers.
1323 *    2. Create a combined depth/stencil renderbuffer and attach
1324 *       it to the framebuffer's depth and stencil attachment points.
1325 *    3. Query the drawable for a new set of buffers, which consists of the
1326 *       originally requested set plus DRI2BufferDepthStencil.
1327 *    4. Assign the DRI2BufferDepthStencil's DRM region to the new
1328 *       depth/stencil renderbuffer.
1329 *
1330 * \pre intel->intelScreen->dri2_has_hiz == INTEL_DRI2_HAS_HIZ_UNKNOWN
1331 *
1332 * \param drawable      Drawable whose buffers were queried.
1333 *
1334 * \param buffers       [in/out] As input, the buffer list returned by the
1335 *                      original DRI2 query. As output, the current buffer
1336 *                      list, which may have been altered by a new DRI2 query.
1337 *
1338 * \param attachments   [in/out] As input, the attachment list submitted
1339 *                      in the original DRI2 query. As output, the attachment
1340 *                      list that was submitted in the DRI2 query that
1341 *                      obtained the current buffer list, as returned in the
1342 *                      output parameter \c buffers.  (Note: If no new query
1343 *                      was made, then the list remains unaltered).
1344 *
1345 * \param count         [out] Number of buffers in the current buffer list, as
1346 *                      returned in the output parameter \c buffers.
1347 *
1348 * \see enum intel_dri2_has_hiz
1349 * \see struct intel_screen::dri2_has_hiz
1350 * \see intel_update_renderbuffers
1351 */
1352static void
1353intel_verify_dri2_has_hiz(struct intel_context *intel,
1354			  __DRIdrawable *drawable,
1355			  __DRIbuffer **buffers,
1356			  unsigned **attachments,
1357			  int *count)
1358{
1359   assert(intel->intelScreen->dri2_has_hiz == INTEL_DRI2_HAS_HIZ_UNKNOWN);
1360
1361   struct gl_framebuffer *fb = drawable->driverPrivate;
1362   struct intel_renderbuffer *stencil_rb =
1363      intel_get_renderbuffer(fb, BUFFER_STENCIL);
1364
1365   if (stencil_rb) {
1366      /*
1367       * We requested a DRI2BufferStencil without knowing if the X driver
1368       * supports it. Now, check if X handled the request correctly and clean
1369       * up if it did not. (See comments for 'enum intel_dri2_has_hiz').
1370       */
1371      struct intel_renderbuffer *depth_rb =
1372	 intel_get_renderbuffer(fb, BUFFER_DEPTH);
1373      assert(intel_rb_format(stencil_rb) == MESA_FORMAT_S8);
1374      assert(depth_rb && intel_rb_format(depth_rb) == MESA_FORMAT_X8_Z24);
1375
1376      if (stencil_rb->mt->region->tiling == I915_TILING_NONE) {
1377	 /*
1378	  * The stencil buffer is actually W tiled. The region's tiling is
1379	  * I915_TILING_NONE, however, because the GTT is incapable of W
1380	  * fencing.
1381	  */
1382	 intel->intelScreen->dri2_has_hiz = INTEL_DRI2_HAS_HIZ_TRUE;
1383	 return;
1384      } else {
1385	 /*
1386	  * Oops... the screen doesn't support separate stencil. Discard the
1387	  * separate depth and stencil buffers and replace them with
1388	  * a combined depth/stencil buffer. Discard the hiz buffer too.
1389	  */
1390	 intel->intelScreen->dri2_has_hiz = INTEL_DRI2_HAS_HIZ_FALSE;
1391	 if (intel->must_use_separate_stencil) {
1392	    _mesa_problem(&intel->ctx,
1393			  "intel_context requires separate stencil, but the "
1394			  "DRIscreen does not support it. You may need to "
1395			  "upgrade the Intel X driver to 2.16.0");
1396	    abort();
1397	 }
1398
1399	 /* 1. Discard depth and stencil renderbuffers. */
1400	 _mesa_remove_renderbuffer(fb, BUFFER_DEPTH);
1401	 depth_rb = NULL;
1402	 _mesa_remove_renderbuffer(fb, BUFFER_STENCIL);
1403	 stencil_rb = NULL;
1404
1405	 /* 2. Create new depth/stencil renderbuffer. */
1406	 struct intel_renderbuffer *depth_stencil_rb =
1407	    intel_create_renderbuffer(MESA_FORMAT_S8_Z24);
1408	 _mesa_add_renderbuffer(fb, BUFFER_DEPTH, &depth_stencil_rb->Base.Base);
1409	 _mesa_add_renderbuffer(fb, BUFFER_STENCIL, &depth_stencil_rb->Base.Base);
1410
1411	 /* 3. Append DRI2BufferDepthStencil to attachment list. */
1412	 int old_count = *count;
1413	 unsigned int *old_attachments = *attachments;
1414	 *count = old_count + 1;
1415	 *attachments = malloc(2 * (*count) * sizeof(unsigned));
1416	 memcpy(*attachments, old_attachments, 2 * old_count * sizeof(unsigned));
1417	 free(old_attachments);
1418	 (*attachments)[2 * old_count + 0] = __DRI_BUFFER_DEPTH_STENCIL;
1419	 (*attachments)[2 * old_count + 1] = intel_bits_per_pixel(depth_stencil_rb);
1420
1421	 /* 4. Request new set of DRI2 attachments. */
1422	 __DRIscreen *screen = intel->intelScreen->driScrnPriv;
1423	 *buffers = screen->dri2.loader->getBuffersWithFormat(drawable,
1424							      &drawable->w,
1425							      &drawable->h,
1426							      *attachments,
1427							      *count,
1428							      count,
1429							      drawable->loaderPrivate);
1430	 if (!*buffers)
1431	    return;
1432
1433	 /*
1434	  * I don't know how to recover from the failure assertion below.
1435	  * Rather than fail gradually and unexpectedly, we should just die
1436	  * now.
1437	  */
1438	 assert(*count == old_count + 1);
1439
1440	 /* 5. Assign the DRI buffer's DRM region to the its renderbuffers. */
1441	 __DRIbuffer *depth_stencil_buffer = NULL;
1442	 for (int i = 0; i < *count; ++i) {
1443	    if ((*buffers)[i].attachment == __DRI_BUFFER_DEPTH_STENCIL) {
1444	       depth_stencil_buffer = &(*buffers)[i];
1445	       break;
1446	    }
1447	 }
1448	 struct intel_region *region =
1449	    intel_region_alloc_for_handle(intel->intelScreen,
1450					  depth_stencil_buffer->cpp,
1451					  drawable->w,
1452					  drawable->h,
1453					  depth_stencil_buffer->pitch
1454					     / depth_stencil_buffer->cpp,
1455					  depth_stencil_buffer->name,
1456					  "dri2 depth / stencil buffer");
1457	 if (!region)
1458	    return;
1459
1460	 struct intel_mipmap_tree *mt =
1461	       intel_miptree_create_for_region(intel,
1462	                                       GL_TEXTURE_2D,
1463	                                       intel_rb_format(depth_stencil_rb),
1464	                                       region);
1465	 intel_region_release(&region);
1466	 if (!mt)
1467	    return;
1468
1469	 intel_miptree_reference(&intel_get_renderbuffer(fb, BUFFER_DEPTH)->mt, mt);
1470	 intel_miptree_reference(&intel_get_renderbuffer(fb, BUFFER_STENCIL)->mt, mt);
1471	 intel_miptree_release(&mt);
1472      }
1473   }
1474
1475   if (intel_framebuffer_has_hiz(fb)) {
1476      /*
1477       * In the future, the driver may advertise a GL config with hiz
1478       * compatible depth bits and 0 stencil bits (for example, when the
1479       * driver gains support for float32 depth buffers). When that day comes,
1480       * here we need to verify that the X driver does in fact support hiz and
1481       * clean up if it doesn't.
1482       *
1483       * Presently, however, no verification or clean up is necessary, and
1484       * execution should not reach here. If the framebuffer still has a hiz
1485       * region, then we have already set dri2_has_hiz to true after
1486       * confirming above that the stencil buffer is W tiled.
1487       */
1488      assert(0);
1489   }
1490}
1491