use wayland-gbm to create/destroy wl_buffer
[mesa-gbm:mesa.git] / src / egl / drivers / dri2 / egl_dri2.c
1 /*
2  * Copyright © 2010 Intel Corporation
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
18  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
19  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
20  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  *
24  * Authors:
25  *    Kristian Høgsberg <krh@bitplanet.net>
26  */
27
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <limits.h>
32 #include <dlfcn.h>
33 #include <fcntl.h>
34 #include <errno.h>
35 #include <unistd.h>
36 #include <xf86drm.h>
37 #include <GL/gl.h>
38 #include <GL/internal/dri_interface.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41
42 #include "egl_dri2.h"
43
44 const __DRIuseInvalidateExtension use_invalidate = {
45    { __DRI_USE_INVALIDATE, 1 }
46 };
47
48 EGLint dri2_to_egl_attribute_map[] = {
49    0,
50    EGL_BUFFER_SIZE,             /* __DRI_ATTRIB_BUFFER_SIZE */
51    EGL_LEVEL,                   /* __DRI_ATTRIB_LEVEL */
52    EGL_RED_SIZE,                /* __DRI_ATTRIB_RED_SIZE */
53    EGL_GREEN_SIZE,              /* __DRI_ATTRIB_GREEN_SIZE */
54    EGL_BLUE_SIZE,               /* __DRI_ATTRIB_BLUE_SIZE */
55    EGL_LUMINANCE_SIZE,          /* __DRI_ATTRIB_LUMINANCE_SIZE */
56    EGL_ALPHA_SIZE,              /* __DRI_ATTRIB_ALPHA_SIZE */
57    0,                           /* __DRI_ATTRIB_ALPHA_MASK_SIZE */
58    EGL_DEPTH_SIZE,              /* __DRI_ATTRIB_DEPTH_SIZE */
59    EGL_STENCIL_SIZE,            /* __DRI_ATTRIB_STENCIL_SIZE */
60    0,                           /* __DRI_ATTRIB_ACCUM_RED_SIZE */
61    0,                           /* __DRI_ATTRIB_ACCUM_GREEN_SIZE */
62    0,                           /* __DRI_ATTRIB_ACCUM_BLUE_SIZE */
63    0,                           /* __DRI_ATTRIB_ACCUM_ALPHA_SIZE */
64    EGL_SAMPLE_BUFFERS,          /* __DRI_ATTRIB_SAMPLE_BUFFERS */
65    EGL_SAMPLES,                 /* __DRI_ATTRIB_SAMPLES */
66    0,                           /* __DRI_ATTRIB_RENDER_TYPE, */
67    0,                           /* __DRI_ATTRIB_CONFIG_CAVEAT */
68    0,                           /* __DRI_ATTRIB_CONFORMANT */
69    0,                           /* __DRI_ATTRIB_DOUBLE_BUFFER */
70    0,                           /* __DRI_ATTRIB_STEREO */
71    0,                           /* __DRI_ATTRIB_AUX_BUFFERS */
72    0,                           /* __DRI_ATTRIB_TRANSPARENT_TYPE */
73    0,                           /* __DRI_ATTRIB_TRANSPARENT_INDEX_VALUE */
74    0,                           /* __DRI_ATTRIB_TRANSPARENT_RED_VALUE */
75    0,                           /* __DRI_ATTRIB_TRANSPARENT_GREEN_VALUE */
76    0,                           /* __DRI_ATTRIB_TRANSPARENT_BLUE_VALUE */
77    0,                           /* __DRI_ATTRIB_TRANSPARENT_ALPHA_VALUE */
78    0,                           /* __DRI_ATTRIB_FLOAT_MODE */
79    0,                           /* __DRI_ATTRIB_RED_MASK */
80    0,                           /* __DRI_ATTRIB_GREEN_MASK */
81    0,                           /* __DRI_ATTRIB_BLUE_MASK */
82    0,                           /* __DRI_ATTRIB_ALPHA_MASK */
83    EGL_MAX_PBUFFER_WIDTH,       /* __DRI_ATTRIB_MAX_PBUFFER_WIDTH */
84    EGL_MAX_PBUFFER_HEIGHT,      /* __DRI_ATTRIB_MAX_PBUFFER_HEIGHT */
85    EGL_MAX_PBUFFER_PIXELS,      /* __DRI_ATTRIB_MAX_PBUFFER_PIXELS */
86    0,                           /* __DRI_ATTRIB_OPTIMAL_PBUFFER_WIDTH */
87    0,                           /* __DRI_ATTRIB_OPTIMAL_PBUFFER_HEIGHT */
88    0,                           /* __DRI_ATTRIB_VISUAL_SELECT_GROUP */
89    0,                           /* __DRI_ATTRIB_SWAP_METHOD */
90    EGL_MAX_SWAP_INTERVAL,       /* __DRI_ATTRIB_MAX_SWAP_INTERVAL */
91    EGL_MIN_SWAP_INTERVAL,       /* __DRI_ATTRIB_MIN_SWAP_INTERVAL */
92    0,                           /* __DRI_ATTRIB_BIND_TO_TEXTURE_RGB */
93    0,                           /* __DRI_ATTRIB_BIND_TO_TEXTURE_RGBA */
94    0,                           /* __DRI_ATTRIB_BIND_TO_MIPMAP_TEXTURE */
95    0,                           /* __DRI_ATTRIB_BIND_TO_TEXTURE_TARGETS */
96    EGL_Y_INVERTED_NOK,          /* __DRI_ATTRIB_YINVERTED */
97    0,                           /* __DRI_ATTRIB_FRAMEBUFFER_SRGB_CAPABLE */
98 };
99
100 static EGLBoolean
101 dri2_match_config(const _EGLConfig *conf, const _EGLConfig *criteria)
102 {
103    if (_eglCompareConfigs(conf, criteria, NULL, EGL_FALSE) != 0)
104       return EGL_FALSE;
105
106    if (!_eglMatchConfig(conf, criteria))
107       return EGL_FALSE;
108
109    return EGL_TRUE;
110 }
111
112 struct dri2_egl_config *
113 dri2_add_config(_EGLDisplay *disp, const __DRIconfig *dri_config, int id,
114                 int depth, EGLint surface_type, const EGLint *attr_list,
115                 const unsigned int *rgba_masks)
116 {
117    struct dri2_egl_config *conf;
118    struct dri2_egl_display *dri2_dpy;
119    _EGLConfig base;
120    unsigned int attrib, value, double_buffer;
121    EGLint key, bind_to_texture_rgb, bind_to_texture_rgba;
122    unsigned int dri_masks[4] = { 0, 0, 0, 0 };
123    _EGLConfig *matching_config;
124    EGLint num_configs = 0;
125    EGLint config_id;
126    int i;
127
128    dri2_dpy = disp->DriverData;
129    _eglInitConfig(&base, disp, id);
130    
131    i = 0;
132    double_buffer = 0;
133    bind_to_texture_rgb = 0;
134    bind_to_texture_rgba = 0;
135
136    while (dri2_dpy->core->indexConfigAttrib(dri_config, i++, &attrib, &value)) {
137       switch (attrib) {
138       case __DRI_ATTRIB_RENDER_TYPE:
139          if (value & __DRI_ATTRIB_RGBA_BIT)
140             value = EGL_RGB_BUFFER;
141          else if (value & __DRI_ATTRIB_LUMINANCE_BIT)
142             value = EGL_LUMINANCE_BUFFER;
143          else
144             /* not valid */;
145          _eglSetConfigKey(&base, EGL_COLOR_BUFFER_TYPE, value);
146          break;  
147
148       case __DRI_ATTRIB_CONFIG_CAVEAT:
149          if (value & __DRI_ATTRIB_NON_CONFORMANT_CONFIG)
150             value = EGL_NON_CONFORMANT_CONFIG;
151          else if (value & __DRI_ATTRIB_SLOW_BIT)
152             value = EGL_SLOW_CONFIG;
153          else
154             value = EGL_NONE;
155          _eglSetConfigKey(&base, EGL_CONFIG_CAVEAT, value);
156          break;
157
158       case __DRI_ATTRIB_BIND_TO_TEXTURE_RGB:
159          bind_to_texture_rgb = value;
160          break;
161
162       case __DRI_ATTRIB_BIND_TO_TEXTURE_RGBA:
163          bind_to_texture_rgba = value;
164          break;
165
166       case __DRI_ATTRIB_DOUBLE_BUFFER:
167          double_buffer = value;
168          break;
169
170       case __DRI_ATTRIB_RED_MASK:
171          dri_masks[0] = value;
172          break;
173
174       case __DRI_ATTRIB_GREEN_MASK:
175          dri_masks[1] = value;
176          break;
177
178       case __DRI_ATTRIB_BLUE_MASK:
179          dri_masks[2] = value;
180          break;
181
182       case __DRI_ATTRIB_ALPHA_MASK:
183          dri_masks[3] = value;
184          break;
185
186       default:
187          key = dri2_to_egl_attribute_map[attrib];
188          if (key != 0)
189             _eglSetConfigKey(&base, key, value);
190          break;
191       }
192    }
193
194    if (attr_list)
195       for (i = 0; attr_list[i] != EGL_NONE; i += 2)
196          _eglSetConfigKey(&base, attr_list[i], attr_list[i+1]);
197
198    if (depth > 0 && depth != base.BufferSize)
199       return NULL;
200
201    if (rgba_masks && memcmp(rgba_masks, dri_masks, sizeof(dri_masks)))
202       return NULL;
203
204    base.NativeRenderable = EGL_TRUE;
205
206    base.SurfaceType = surface_type;
207    if (surface_type & (EGL_PBUFFER_BIT |
208        (disp->Extensions.NOK_texture_from_pixmap ? EGL_PIXMAP_BIT : 0))) {
209       base.BindToTextureRGB = bind_to_texture_rgb;
210       if (base.AlphaSize > 0)
211          base.BindToTextureRGBA = bind_to_texture_rgba;
212    }
213
214    base.RenderableType = disp->ClientAPIs;
215    base.Conformant = disp->ClientAPIs;
216
217    if (!_eglValidateConfig(&base, EGL_FALSE)) {
218       _eglLog(_EGL_DEBUG, "DRI2: failed to validate config %d", id);
219       return NULL;
220    }
221
222    config_id = base.ConfigID;
223    base.ConfigID    = EGL_DONT_CARE;
224    base.SurfaceType = EGL_DONT_CARE;
225    num_configs = _eglFilterArray(disp->Configs, (void **) &matching_config, 1,
226                                  (_EGLArrayForEach) dri2_match_config, &base);
227
228    if (num_configs == 1) {
229       conf = (struct dri2_egl_config *) matching_config;
230
231       if (double_buffer && !conf->dri_double_config)
232          conf->dri_double_config = dri_config;
233       else if (!double_buffer && !conf->dri_single_config)
234          conf->dri_single_config = dri_config;
235       else
236          /* a similar config type is already added (unlikely) => discard */
237          return NULL;
238    }
239    else if (num_configs == 0) {
240       conf = malloc(sizeof *conf);
241       if (conf == NULL)
242          return NULL;
243
244       memcpy(&conf->base, &base, sizeof base);
245       if (double_buffer) {
246          conf->dri_double_config = dri_config;
247          conf->dri_single_config = NULL;
248       } else {
249          conf->dri_single_config = dri_config;
250          conf->dri_double_config = NULL;
251       }
252       conf->base.SurfaceType = 0;
253       conf->base.ConfigID = config_id;
254
255       _eglLinkConfig(&conf->base);
256    }
257    else {
258       assert(0);
259       return NULL;
260    }
261
262    if (double_buffer) {
263       surface_type &= ~EGL_PIXMAP_BIT;
264
265       if (dri2_dpy->swap_available) {
266          conf->base.MinSwapInterval = 0;
267          conf->base.MaxSwapInterval = 1000; /* XXX arbitrary value */
268       }
269    }
270
271    conf->base.SurfaceType |= surface_type;
272
273    return conf;
274 }
275
276 __DRIimage *
277 dri2_lookup_egl_image(__DRIscreen *screen, void *image, void *data)
278 {
279    _EGLDisplay *disp = data;
280    struct dri2_egl_image *dri2_img;
281    _EGLImage *img;
282
283    (void) screen;
284
285    img = _eglLookupImage(image, disp);
286    if (img == NULL) {
287       _eglError(EGL_BAD_PARAMETER, "dri2_lookup_egl_image");
288       return NULL;
289    }
290
291    dri2_img = dri2_egl_image(image);
292
293    return dri2_img->dri_image;
294 }
295
296 const __DRIimageLookupExtension image_lookup_extension = {
297    { __DRI_IMAGE_LOOKUP, 1 },
298    dri2_lookup_egl_image
299 };
300
301 static const char dri_driver_path[] = DEFAULT_DRIVER_DIR;
302
303 struct dri2_extension_match {
304    const char *name;
305    int version;
306    int offset;
307 };
308
309 static struct dri2_extension_match dri2_driver_extensions[] = {
310    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
311    { __DRI_DRI2, 1, offsetof(struct dri2_egl_display, dri2) },
312    { NULL, 0, 0 }
313 };
314
315 static struct dri2_extension_match dri2_core_extensions[] = {
316    { __DRI2_FLUSH, 1, offsetof(struct dri2_egl_display, flush) },
317    { __DRI_TEX_BUFFER, 2, offsetof(struct dri2_egl_display, tex_buffer) },
318    { __DRI_IMAGE, 1, offsetof(struct dri2_egl_display, image) },
319    { NULL, 0, 0 }
320 };
321
322 static struct dri2_extension_match swrast_driver_extensions[] = {
323    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
324    { __DRI_SWRAST, 2, offsetof(struct dri2_egl_display, swrast) },
325    { NULL }
326 };
327
328 static struct dri2_extension_match swrast_core_extensions[] = {
329    { __DRI_TEX_BUFFER, 2, offsetof(struct dri2_egl_display, tex_buffer) },
330    { NULL }
331 };
332
333 static EGLBoolean
334 dri2_bind_extensions(struct dri2_egl_display *dri2_dpy,
335                      struct dri2_extension_match *matches,
336                      const __DRIextension **extensions)
337 {
338    int i, j, ret = EGL_TRUE;
339    void *field;
340
341    for (i = 0; extensions[i]; i++) {
342       _eglLog(_EGL_DEBUG, "DRI2: found extension `%s'", extensions[i]->name);
343       for (j = 0; matches[j].name; j++) {
344          if (strcmp(extensions[i]->name, matches[j].name) == 0 &&
345              extensions[i]->version >= matches[j].version) {
346             field = ((char *) dri2_dpy + matches[j].offset);
347             *(const __DRIextension **) field = extensions[i];
348             _eglLog(_EGL_INFO, "DRI2: found extension %s version %d",
349                     extensions[i]->name, extensions[i]->version);
350          }
351       }
352    }
353    
354    for (j = 0; matches[j].name; j++) {
355       field = ((char *) dri2_dpy + matches[j].offset);
356       if (*(const __DRIextension **) field == NULL) {
357          _eglLog(_EGL_FATAL, "DRI2: did not find extension %s version %d",
358                  matches[j].name, matches[j].version);
359          ret = EGL_FALSE;
360       }
361    }
362
363    return ret;
364 }
365
366 static const __DRIextension **
367 dri2_open_driver(_EGLDisplay *disp)
368 {
369    struct dri2_egl_display *dri2_dpy = disp->DriverData;
370    const __DRIextension **extensions;
371    char path[PATH_MAX], *search_paths, *p, *next, *end;
372
373    search_paths = NULL;
374    if (geteuid() == getuid()) {
375       /* don't allow setuid apps to use LIBGL_DRIVERS_PATH */
376       search_paths = getenv("LIBGL_DRIVERS_PATH");
377    }
378    if (search_paths == NULL)
379       search_paths = DEFAULT_DRIVER_DIR;
380
381    dri2_dpy->driver = NULL;
382    end = search_paths + strlen(search_paths);
383    for (p = search_paths; p < end && dri2_dpy->driver == NULL; p = next + 1) {
384       int len;
385       next = strchr(p, ':');
386       if (next == NULL)
387          next = end;
388
389       len = next - p;
390 #if GLX_USE_TLS
391       snprintf(path, sizeof path,
392                "%.*s/tls/%s_dri.so", len, p, dri2_dpy->driver_name);
393       dri2_dpy->driver = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
394 #endif
395       if (dri2_dpy->driver == NULL) {
396          snprintf(path, sizeof path,
397                   "%.*s/%s_dri.so", len, p, dri2_dpy->driver_name);
398          dri2_dpy->driver = dlopen(path, RTLD_NOW | RTLD_GLOBAL);
399          if (dri2_dpy->driver == NULL)
400             _eglLog(_EGL_DEBUG, "failed to open %s: %s\n", path, dlerror());
401       }
402    }
403
404    if (dri2_dpy->driver == NULL) {
405       _eglLog(_EGL_WARNING,
406               "DRI2: failed to open %s (search paths %s)",
407               dri2_dpy->driver_name, search_paths);
408       return NULL;
409    }
410
411    _eglLog(_EGL_DEBUG, "DRI2: dlopen(%s)", path);
412    extensions = dlsym(dri2_dpy->driver, __DRI_DRIVER_EXTENSIONS);
413    if (extensions == NULL) {
414       _eglLog(_EGL_WARNING,
415               "DRI2: driver exports no extensions (%s)", dlerror());
416       dlclose(dri2_dpy->driver);
417    }
418
419    return extensions;
420 }
421
422 EGLBoolean
423 dri2_load_driver(_EGLDisplay *disp)
424 {
425    struct dri2_egl_display *dri2_dpy = disp->DriverData;
426    const __DRIextension **extensions;
427
428    extensions = dri2_open_driver(disp);
429    if (!extensions)
430       return EGL_FALSE;
431
432    if (!dri2_bind_extensions(dri2_dpy, dri2_driver_extensions, extensions)) {
433       dlclose(dri2_dpy->driver);
434       return EGL_FALSE;
435    }
436
437    return EGL_TRUE;
438 }
439
440 EGLBoolean
441 dri2_load_driver_swrast(_EGLDisplay *disp)
442 {
443    struct dri2_egl_display *dri2_dpy = disp->DriverData;
444    const __DRIextension **extensions;
445
446    dri2_dpy->driver_name = "swrast";
447    extensions = dri2_open_driver(disp);
448
449    if (!extensions)
450       return EGL_FALSE;
451
452    if (!dri2_bind_extensions(dri2_dpy, swrast_driver_extensions, extensions)) {
453       dlclose(dri2_dpy->driver);
454       return EGL_FALSE;
455    }
456
457    return EGL_TRUE;
458 }
459
460 void
461 dri2_setup_screen(_EGLDisplay *disp)
462 {
463    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
464    unsigned int api_mask;
465
466    if (dri2_dpy->dri2) {
467       if (dri2_dpy->dri2->base.version >= 2)
468          api_mask = dri2_dpy->dri2->getAPIMask(dri2_dpy->dri_screen);
469       else
470          api_mask = 1 << __DRI_API_OPENGL;
471    } else {
472       assert(dri2_dpy->swrast);
473       if (dri2_dpy->swrast->base.version >= 2)
474          api_mask = 1 << __DRI_API_OPENGL | 1 << __DRI_API_GLES | 1 << __DRI_API_GLES2;
475       else
476          api_mask = 1 << __DRI_API_OPENGL;
477    }
478
479    disp->ClientAPIs = 0;
480    if (api_mask & (1 <<__DRI_API_OPENGL))
481       disp->ClientAPIs |= EGL_OPENGL_BIT;
482    if (api_mask & (1 <<__DRI_API_GLES))
483       disp->ClientAPIs |= EGL_OPENGL_ES_BIT;
484    if (api_mask & (1 << __DRI_API_GLES2))
485       disp->ClientAPIs |= EGL_OPENGL_ES2_BIT;
486
487    if (dri2_dpy->dri2) {
488       if (dri2_dpy->dri2->base.version >= 2) {
489          disp->Extensions.KHR_surfaceless_gles1 = EGL_TRUE;
490          disp->Extensions.KHR_surfaceless_gles2 = EGL_TRUE;
491          disp->Extensions.KHR_surfaceless_opengl = EGL_TRUE;
492       }
493    } else {
494       assert(dri2_dpy->swrast);
495       if (dri2_dpy->swrast->base.version >= 2) {
496          disp->Extensions.KHR_surfaceless_gles1 = EGL_TRUE;
497          disp->Extensions.KHR_surfaceless_gles2 = EGL_TRUE;
498          disp->Extensions.KHR_surfaceless_opengl = EGL_TRUE;
499       }
500    }
501
502    if (dri2_dpy->image) {
503       disp->Extensions.MESA_drm_image = EGL_TRUE;
504       disp->Extensions.KHR_image_base = EGL_TRUE;
505       disp->Extensions.KHR_gl_renderbuffer_image = EGL_TRUE;
506    }
507 }
508
509 EGLBoolean
510 dri2_create_screen(_EGLDisplay *disp)
511 {
512    const __DRIextension **extensions;
513    struct dri2_egl_display *dri2_dpy;
514
515    dri2_dpy = disp->DriverData;
516
517    if (dri2_dpy->dri2) {
518       dri2_dpy->dri_screen =
519          dri2_dpy->dri2->createNewScreen(0, dri2_dpy->fd, dri2_dpy->extensions,
520                                          &dri2_dpy->driver_configs, disp);
521    } else {
522       assert(dri2_dpy->swrast);
523       dri2_dpy->dri_screen =
524          dri2_dpy->swrast->createNewScreen(0, dri2_dpy->extensions,
525                                            &dri2_dpy->driver_configs, disp);
526    }
527
528    if (dri2_dpy->dri_screen == NULL) {
529       _eglLog(_EGL_WARNING, "DRI2: failed to create dri screen");
530       return EGL_FALSE;
531    }
532
533    dri2_dpy->own_dri_screen = 1;
534
535    extensions = dri2_dpy->core->getExtensions(dri2_dpy->dri_screen);
536    
537    if (dri2_dpy->dri2) {
538       if (!dri2_bind_extensions(dri2_dpy, dri2_core_extensions, extensions))
539          goto cleanup_dri_screen;
540    } else {
541       assert(dri2_dpy->swrast);
542       if (!dri2_bind_extensions(dri2_dpy, swrast_core_extensions, extensions))
543          goto cleanup_dri_screen;
544    }
545
546    dri2_setup_screen(disp);
547
548    return EGL_TRUE;
549
550  cleanup_dri_screen:
551    dri2_dpy->core->destroyScreen(dri2_dpy->dri_screen);
552
553    return EGL_FALSE;
554 }
555
556 /**
557  * Called via eglInitialize(), GLX_drv->API.Initialize().
558  */
559 static EGLBoolean
560 dri2_initialize(_EGLDriver *drv, _EGLDisplay *disp)
561 {
562    /* not until swrast_dri is supported */
563    if (disp->Options.UseFallback)
564       return EGL_FALSE;
565
566    switch (disp->Platform) {
567 #ifdef HAVE_X11_PLATFORM
568    case _EGL_PLATFORM_X11:
569       if (disp->Options.TestOnly)
570          return EGL_TRUE;
571       return dri2_initialize_x11(drv, disp);
572 #endif
573
574 #ifdef HAVE_LIBUDEV
575 #ifdef HAVE_DRM_PLATFORM
576    case _EGL_PLATFORM_DRM:
577       if (disp->Options.TestOnly)
578          return EGL_TRUE;
579       return dri2_initialize_drm(drv, disp);
580 #endif
581 #ifdef HAVE_WAYLAND_PLATFORM
582    case _EGL_PLATFORM_WAYLAND:
583       if (disp->Options.TestOnly)
584          return EGL_TRUE;
585       return dri2_initialize_wayland(drv, disp);
586 #endif
587 #endif
588 #ifdef HAVE_ANDROID_PLATFORM
589    case _EGL_PLATFORM_ANDROID:
590       if (disp->Options.TestOnly)
591          return EGL_TRUE;
592       return dri2_initialize_android(drv, disp);
593 #endif
594
595    default:
596       return EGL_FALSE;
597    }
598 }
599
600 /**
601  * Called via eglTerminate(), drv->API.Terminate().
602  */
603 static EGLBoolean
604 dri2_terminate(_EGLDriver *drv, _EGLDisplay *disp)
605 {
606    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
607
608    _eglReleaseDisplayResources(drv, disp);
609    _eglCleanupDisplay(disp);
610
611    if (dri2_dpy->own_dri_screen)
612       dri2_dpy->core->destroyScreen(dri2_dpy->dri_screen);
613    if (dri2_dpy->fd)
614       close(dri2_dpy->fd);
615    if (dri2_dpy->driver)
616       dlclose(dri2_dpy->driver);
617    if (dri2_dpy->device_name)
618       free(dri2_dpy->device_name);
619
620    if (disp->PlatformDisplay == NULL) {
621       switch (disp->Platform) {
622 #ifdef HAVE_X11_PLATFORM
623       case _EGL_PLATFORM_X11:
624          xcb_disconnect(dri2_dpy->conn);
625          break;
626 #endif
627 #ifdef HAVE_DRM_PLATFORM
628       case _EGL_PLATFORM_DRM:
629          if (dri2_dpy->own_device) {
630             gbm_device_destroy(&dri2_dpy->gbm_dri->base.base);
631          }
632          break;
633 #endif
634       default:
635          break;
636       }
637    }
638
639    free(dri2_dpy);
640    disp->DriverData = NULL;
641
642    return EGL_TRUE;
643 }
644
645
646 /**
647  * Called via eglCreateContext(), drv->API.CreateContext().
648  */
649 static _EGLContext *
650 dri2_create_context(_EGLDriver *drv, _EGLDisplay *disp, _EGLConfig *conf,
651                     _EGLContext *share_list, const EGLint *attrib_list)
652 {
653    struct dri2_egl_context *dri2_ctx;
654    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
655    struct dri2_egl_context *dri2_ctx_shared = dri2_egl_context(share_list);
656    struct dri2_egl_config *dri2_config = dri2_egl_config(conf);
657    const __DRIconfig *dri_config;
658    int api;
659
660    (void) drv;
661
662    dri2_ctx = malloc(sizeof *dri2_ctx);
663    if (!dri2_ctx) {
664       _eglError(EGL_BAD_ALLOC, "eglCreateContext");
665       return NULL;
666    }
667
668    if (!_eglInitContext(&dri2_ctx->base, disp, conf, attrib_list))
669       goto cleanup;
670
671    switch (dri2_ctx->base.ClientAPI) {
672    case EGL_OPENGL_ES_API:
673       switch (dri2_ctx->base.ClientVersion) {
674       case 1:
675          api = __DRI_API_GLES;
676          break;
677       case 2:
678          api = __DRI_API_GLES2;
679          break;
680       default:
681          _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
682          return NULL;
683       }
684       break;
685    case EGL_OPENGL_API:
686       api = __DRI_API_OPENGL;
687       break;
688    default:
689       _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
690       return NULL;
691    }
692
693    if (conf != NULL) {
694       /* The config chosen here isn't necessarily
695        * used for surfaces later.
696        * A pixmap surface will use the single config.
697        * This opportunity depends on disabling the
698        * doubleBufferMode check in
699        * src/mesa/main/context.c:check_compatible()
700        */
701       if (dri2_config->dri_double_config)
702          dri_config = dri2_config->dri_double_config;
703       else
704          dri_config = dri2_config->dri_single_config;
705
706       /* EGL_WINDOW_BIT is set only when there is a dri_double_config.  This
707        * makes sure the back buffer will always be used.
708        */
709       if (conf->SurfaceType & EGL_WINDOW_BIT)
710          dri2_ctx->base.WindowRenderBuffer = EGL_BACK_BUFFER;
711    }
712    else
713       dri_config = NULL;
714
715    if (dri2_dpy->dri2) {
716       if (dri2_dpy->dri2->base.version >= 2) {
717          dri2_ctx->dri_context =
718             dri2_dpy->dri2->createNewContextForAPI(dri2_dpy->dri_screen,
719                                                    api,
720                                                    dri_config,
721                                                    dri2_ctx_shared ? 
722                                                    dri2_ctx_shared->dri_context : NULL,
723                                                    dri2_ctx);
724       } else if (api == __DRI_API_OPENGL) {
725          dri2_ctx->dri_context =
726             dri2_dpy->dri2->createNewContext(dri2_dpy->dri_screen,
727                                              dri_config,
728                                              dri2_ctx_shared ? 
729                                              dri2_ctx_shared->dri_context : NULL,
730                                              dri2_ctx);
731       } else {
732          /* fail */
733       }
734    } else {
735       assert(dri2_dpy->swrast);
736       if (dri2_dpy->swrast->base.version >= 2) {
737          dri2_ctx->dri_context =
738             dri2_dpy->swrast->createNewContextForAPI(dri2_dpy->dri_screen,
739                                                      api,
740                                                      dri_config,
741                                                      dri2_ctx_shared ? 
742                                                      dri2_ctx_shared->dri_context : NULL,
743                                                      dri2_ctx);
744       } else if (api == __DRI_API_OPENGL) {
745          dri2_ctx->dri_context =
746             dri2_dpy->core->createNewContext(dri2_dpy->dri_screen,
747                                              dri_config,
748                                              dri2_ctx_shared ?
749                                              dri2_ctx_shared->dri_context : NULL,
750                                              dri2_ctx);
751       } else {
752          /* fail */
753       }
754    }
755
756    if (!dri2_ctx->dri_context)
757       goto cleanup;
758
759    return &dri2_ctx->base;
760
761  cleanup:
762    free(dri2_ctx);
763    return NULL;
764 }
765
766 /**
767  * Called via eglDestroyContext(), drv->API.DestroyContext().
768  */
769 static EGLBoolean
770 dri2_destroy_context(_EGLDriver *drv, _EGLDisplay *disp, _EGLContext *ctx)
771 {
772    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
773    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
774
775    if (_eglPutContext(ctx)) {
776       dri2_dpy->core->destroyContext(dri2_ctx->dri_context);
777       free(dri2_ctx);
778    }
779
780    return EGL_TRUE;
781 }
782
783 /**
784  * Called via eglMakeCurrent(), drv->API.MakeCurrent().
785  */
786 static EGLBoolean
787 dri2_make_current(_EGLDriver *drv, _EGLDisplay *disp, _EGLSurface *dsurf,
788                   _EGLSurface *rsurf, _EGLContext *ctx)
789 {
790    struct dri2_egl_driver *dri2_drv = dri2_egl_driver(drv);
791    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
792    struct dri2_egl_surface *dri2_dsurf = dri2_egl_surface(dsurf);
793    struct dri2_egl_surface *dri2_rsurf = dri2_egl_surface(rsurf);
794    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
795    _EGLContext *old_ctx;
796    _EGLSurface *old_dsurf, *old_rsurf;
797    __DRIdrawable *ddraw, *rdraw;
798    __DRIcontext *cctx;
799
800    /* make new bindings */
801    if (!_eglBindContext(ctx, dsurf, rsurf, &old_ctx, &old_dsurf, &old_rsurf))
802       return EGL_FALSE;
803
804    /* flush before context switch */
805    if (old_ctx && dri2_drv->glFlush)
806       dri2_drv->glFlush();
807
808    ddraw = (dri2_dsurf) ? dri2_dsurf->dri_drawable : NULL;
809    rdraw = (dri2_rsurf) ? dri2_rsurf->dri_drawable : NULL;
810    cctx = (dri2_ctx) ? dri2_ctx->dri_context : NULL;
811
812    if (old_ctx) {
813       __DRIcontext *old_cctx = dri2_egl_context(old_ctx)->dri_context;
814       dri2_dpy->core->unbindContext(old_cctx);
815    }
816
817    if ((cctx == NULL && ddraw == NULL && rdraw == NULL) ||
818        dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
819       if (old_dsurf)
820          drv->API.DestroySurface(drv, disp, old_dsurf);
821       if (old_rsurf)
822          drv->API.DestroySurface(drv, disp, old_rsurf);
823       if (old_ctx)
824          drv->API.DestroyContext(drv, disp, old_ctx);
825
826       return EGL_TRUE;
827    } else {
828       /* undo the previous _eglBindContext */
829       _eglBindContext(old_ctx, old_dsurf, old_rsurf, &ctx, &dsurf, &rsurf);
830       assert(&dri2_ctx->base == ctx &&
831              &dri2_dsurf->base == dsurf &&
832              &dri2_rsurf->base == rsurf);
833
834       _eglPutSurface(dsurf);
835       _eglPutSurface(rsurf);
836       _eglPutContext(ctx);
837
838       _eglPutSurface(old_dsurf);
839       _eglPutSurface(old_rsurf);
840       _eglPutContext(old_ctx);
841
842       return EGL_FALSE;
843    }
844 }
845
846 /*
847  * Called from eglGetProcAddress() via drv->API.GetProcAddress().
848  */
849 static _EGLProc
850 dri2_get_proc_address(_EGLDriver *drv, const char *procname)
851 {
852    struct dri2_egl_driver *dri2_drv = dri2_egl_driver(drv);
853
854    return dri2_drv->get_proc_address(procname);
855 }
856
857 static EGLBoolean
858 dri2_wait_client(_EGLDriver *drv, _EGLDisplay *disp, _EGLContext *ctx)
859 {
860    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
861    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(ctx->DrawSurface);
862
863    (void) drv;
864
865    /* FIXME: If EGL allows frontbuffer rendering for window surfaces,
866     * we need to copy fake to real here.*/
867
868    (*dri2_dpy->flush->flush)(dri2_surf->dri_drawable);
869
870    return EGL_TRUE;
871 }
872
873 static EGLBoolean
874 dri2_wait_native(_EGLDriver *drv, _EGLDisplay *disp, EGLint engine)
875 {
876    (void) drv;
877    (void) disp;
878
879    if (engine != EGL_CORE_NATIVE_ENGINE)
880       return _eglError(EGL_BAD_PARAMETER, "eglWaitNative");
881    /* glXWaitX(); */
882
883    return EGL_TRUE;
884 }
885
886 static EGLBoolean
887 dri2_bind_tex_image(_EGLDriver *drv,
888                     _EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
889 {
890    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
891    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
892    struct dri2_egl_context *dri2_ctx;
893    _EGLContext *ctx;
894    GLint format, target;
895
896    ctx = _eglGetCurrentContext();
897    dri2_ctx = dri2_egl_context(ctx);
898
899    if (!_eglBindTexImage(drv, disp, surf, buffer))
900       return EGL_FALSE;
901
902    switch (dri2_surf->base.TextureFormat) {
903    case EGL_TEXTURE_RGB:
904       format = __DRI_TEXTURE_FORMAT_RGB;
905       break;
906    case EGL_TEXTURE_RGBA:
907       format = __DRI_TEXTURE_FORMAT_RGBA;
908       break;
909    default:
910       assert(0);
911    }
912
913    switch (dri2_surf->base.TextureTarget) {
914    case EGL_TEXTURE_2D:
915       target = GL_TEXTURE_2D;
916       break;
917    default:
918       assert(0);
919    }
920
921    (*dri2_dpy->tex_buffer->setTexBuffer2)(dri2_ctx->dri_context,
922                                           target, format,
923                                           dri2_surf->dri_drawable);
924
925    return EGL_TRUE;
926 }
927
928 static EGLBoolean
929 dri2_release_tex_image(_EGLDriver *drv,
930                        _EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
931 {
932 #if __DRI_TEX_BUFFER_VERSION >= 3
933    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
934    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
935    struct dri2_egl_context *dri2_ctx;
936    _EGLContext *ctx;
937    GLint  target;
938
939    ctx = _eglGetCurrentContext();
940    dri2_ctx = dri2_egl_context(ctx);
941
942    if (!_eglReleaseTexImage(drv, disp, surf, buffer))
943       return EGL_FALSE;
944
945    switch (dri2_surf->base.TextureTarget) {
946    case EGL_TEXTURE_2D:
947       target = GL_TEXTURE_2D;
948       break;
949    default:
950       assert(0);
951    }
952    if (dri2_dpy->tex_buffer->releaseTexBuffer!=NULL)
953     (*dri2_dpy->tex_buffer->releaseTexBuffer)(dri2_ctx->dri_context,
954                                              target,
955                                              dri2_surf->dri_drawable);
956 #endif
957
958    return EGL_TRUE;
959 }
960
961 static _EGLImage *
962 dri2_create_image_khr_renderbuffer(_EGLDisplay *disp, _EGLContext *ctx,
963                                    EGLClientBuffer buffer,
964                                    const EGLint *attr_list)
965 {
966    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
967    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
968    struct dri2_egl_image *dri2_img;
969    GLuint renderbuffer = (GLuint) (uintptr_t) buffer;
970
971    if (renderbuffer == 0) {
972       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
973       return EGL_NO_IMAGE_KHR;
974    }
975
976    dri2_img = malloc(sizeof *dri2_img);
977    if (!dri2_img) {
978       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
979       return EGL_NO_IMAGE_KHR;
980    }
981
982    if (!_eglInitImage(&dri2_img->base, disp)) {
983       free(dri2_img);
984       return EGL_NO_IMAGE_KHR;
985    }
986
987    dri2_img->dri_image = 
988       dri2_dpy->image->createImageFromRenderbuffer(dri2_ctx->dri_context,
989                                                    renderbuffer,
990                                                    dri2_img);
991
992    return &dri2_img->base;
993 }
994
995 static _EGLImage *
996 dri2_create_image_drm_name(_EGLDisplay *disp, _EGLContext *ctx,
997                            EGLint name,
998                            const _EGLImageAttribs *attrs,
999                            EGLint format,
1000                            EGLint pitch)
1001 {
1002    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1003    struct dri2_egl_image *dri2_img;
1004
1005    (void) ctx;
1006
1007    dri2_img = malloc(sizeof *dri2_img);
1008    if (!dri2_img) {
1009       _eglError(EGL_BAD_ALLOC, "dri2_create_image_mesa_drm");
1010       return NULL;
1011    }
1012
1013    if (!_eglInitImage(&dri2_img->base, disp)) {
1014       free(dri2_img);
1015       return NULL;
1016    }
1017
1018    dri2_img->dri_image =
1019       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
1020                                            attrs->Width,
1021                                            attrs->Height,
1022                                            format,
1023                                            name,
1024                                            pitch,
1025                                            dri2_img);
1026    if (dri2_img->dri_image == NULL) {
1027       free(dri2_img);
1028       _eglError(EGL_BAD_ALLOC, "dri2_create_image_mesa_drm");
1029       return NULL;
1030    }
1031
1032    return &dri2_img->base;
1033 }
1034
1035 static _EGLImage *
1036 dri2_create_image_mesa_drm_buffer(_EGLDisplay *disp, _EGLContext *ctx,
1037                                   EGLClientBuffer buffer, const EGLint *attr_list)
1038 {
1039    EGLint format, name, pitch, err;
1040    _EGLImageAttribs attrs;
1041
1042    name = (EGLint) (uintptr_t) buffer;
1043
1044    err = _eglParseImageAttribList(&attrs, disp, attr_list);
1045    if (err != EGL_SUCCESS)
1046       return NULL;
1047
1048    if (attrs.Width <= 0 || attrs.Height <= 0 ||
1049        attrs.DRMBufferStrideMESA <= 0) {
1050       _eglError(EGL_BAD_PARAMETER,
1051                 "bad width, height or stride");
1052       return NULL;
1053    }
1054
1055    switch (attrs.DRMBufferFormatMESA) {
1056    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
1057       format = __DRI_IMAGE_FORMAT_ARGB8888;
1058       pitch = attrs.DRMBufferStrideMESA;
1059       break;
1060    default:
1061       _eglError(EGL_BAD_PARAMETER,
1062                 "dri2_create_image_khr: unsupported pixmap depth");
1063       return NULL;
1064    }
1065
1066    return dri2_create_image_drm_name (disp, ctx, name, &attrs, format, pitch);
1067 }
1068
1069 #ifdef HAVE_WAYLAND_PLATFORM
1070 static _EGLImage *
1071 dri2_create_image_wayland_wl_buffer(_EGLDisplay *disp, _EGLContext *ctx,
1072                                     EGLClientBuffer _buffer,
1073                                     const EGLint *attr_list)
1074 {
1075    struct wl_buffer *buffer = (struct wl_buffer *) _buffer;
1076    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1077    __DRIimage *dri_image;
1078    _EGLImageAttribs attrs;
1079    EGLint format, name, stride, pitch, err;
1080
1081    if (!wayland_buffer_is_gbm(buffer))
1082        return NULL;
1083
1084    dri_image = wl_gbm_buffer_get_buffer(buffer);
1085    
1086    dri2_dpy->image->queryImage(dri_image, __DRI_IMAGE_ATTRIB_NAME, &name);
1087    dri2_dpy->image->queryImage(dri_image, __DRI_IMAGE_ATTRIB_STRIDE, &stride);
1088
1089    err = _eglParseImageAttribList(&attrs, disp, attr_list);
1090    if (err != EGL_SUCCESS)
1091       return NULL;
1092
1093    attrs.Width = buffer->width;
1094    attrs.Height = buffer->height;
1095
1096    switch (wl_gbm_buffer_get_format(buffer)) {
1097    case WL_GBM_FORMAT_ARGB8888:
1098       format = __DRI_IMAGE_FORMAT_ARGB8888;
1099       break;
1100    case WL_GBM_FORMAT_XRGB8888:
1101       format = __DRI_IMAGE_FORMAT_XRGB8888;
1102       break;
1103    default:
1104       _eglError(EGL_BAD_PARAMETER,
1105                 "dri2_create_image_khr: unsupported wl_buffer format");
1106       return NULL;
1107    }
1108
1109    pitch = stride / 4;
1110
1111    return dri2_create_image_drm_name(disp, ctx, name, &attrs, format, pitch);
1112 }
1113 #endif
1114
1115 _EGLImage *
1116 dri2_create_image_khr(_EGLDriver *drv, _EGLDisplay *disp,
1117                       _EGLContext *ctx, EGLenum target,
1118                       EGLClientBuffer buffer, const EGLint *attr_list)
1119 {
1120    (void) drv;
1121
1122    switch (target) {
1123    case EGL_GL_RENDERBUFFER_KHR:
1124       return dri2_create_image_khr_renderbuffer(disp, ctx, buffer, attr_list);
1125    case EGL_DRM_BUFFER_MESA:
1126       return dri2_create_image_mesa_drm_buffer(disp, ctx, buffer, attr_list);
1127 #ifdef HAVE_WAYLAND_PLATFORM
1128    case EGL_WAYLAND_BUFFER_WL:
1129       return dri2_create_image_wayland_wl_buffer(disp, ctx, buffer, attr_list);
1130 #endif
1131    default:
1132       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
1133       return EGL_NO_IMAGE_KHR;
1134    }
1135 }
1136
1137 static EGLBoolean
1138 dri2_destroy_image_khr(_EGLDriver *drv, _EGLDisplay *disp, _EGLImage *image)
1139 {
1140    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1141    struct dri2_egl_image *dri2_img = dri2_egl_image(image);
1142
1143    (void) drv;
1144
1145    dri2_dpy->image->destroyImage(dri2_img->dri_image);
1146    free(dri2_img);
1147
1148    return EGL_TRUE;
1149 }
1150
1151 static _EGLImage *
1152 dri2_create_drm_image_mesa(_EGLDriver *drv, _EGLDisplay *disp,
1153                            const EGLint *attr_list)
1154 {
1155    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1156    struct dri2_egl_image *dri2_img;
1157    _EGLImageAttribs attrs;
1158    unsigned int dri_use, valid_mask;
1159    int format;
1160    EGLint err = EGL_SUCCESS;
1161
1162    (void) drv;
1163
1164    dri2_img = malloc(sizeof *dri2_img);
1165    if (!dri2_img) {
1166       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
1167       return EGL_NO_IMAGE_KHR;
1168    }
1169
1170    if (!attr_list) {
1171       err = EGL_BAD_PARAMETER;
1172       goto cleanup_img;
1173    }
1174
1175    if (!_eglInitImage(&dri2_img->base, disp)) {
1176       err = EGL_BAD_PARAMETER;
1177       goto cleanup_img;
1178    }
1179
1180    err = _eglParseImageAttribList(&attrs, disp, attr_list);
1181    if (err != EGL_SUCCESS)
1182       goto cleanup_img;
1183
1184    if (attrs.Width <= 0 || attrs.Height <= 0) {
1185       _eglLog(_EGL_WARNING, "bad width or height (%dx%d)",
1186             attrs.Width, attrs.Height);
1187       goto cleanup_img;
1188    }
1189
1190    switch (attrs.DRMBufferFormatMESA) {
1191    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
1192       format = __DRI_IMAGE_FORMAT_ARGB8888;
1193       break;
1194    default:
1195       _eglLog(_EGL_WARNING, "bad image format value 0x%04x",
1196             attrs.DRMBufferFormatMESA);
1197       goto cleanup_img;
1198    }
1199
1200    valid_mask =
1201       EGL_DRM_BUFFER_USE_SCANOUT_MESA |
1202       EGL_DRM_BUFFER_USE_SHARE_MESA |
1203       EGL_DRM_BUFFER_USE_CURSOR_MESA;
1204    if (attrs.DRMBufferUseMESA & ~valid_mask) {
1205       _eglLog(_EGL_WARNING, "bad image use bit 0x%04x",
1206             attrs.DRMBufferUseMESA & ~valid_mask);
1207       goto cleanup_img;
1208    }
1209
1210    dri_use = 0;
1211    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SHARE_MESA)
1212       dri_use |= __DRI_IMAGE_USE_SHARE;
1213    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SCANOUT_MESA)
1214       dri_use |= __DRI_IMAGE_USE_SCANOUT;
1215    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_CURSOR_MESA)
1216       dri_use |= __DRI_IMAGE_USE_CURSOR;
1217
1218    dri2_img->dri_image = 
1219       dri2_dpy->image->createImage(dri2_dpy->dri_screen,
1220                                    attrs.Width, attrs.Height,
1221                                    format, dri_use, dri2_img);
1222    if (dri2_img->dri_image == NULL) {
1223       err = EGL_BAD_ALLOC;
1224       goto cleanup_img;
1225    }
1226
1227    return &dri2_img->base;
1228
1229  cleanup_img:
1230    free(dri2_img);
1231    _eglError(err, "dri2_create_drm_image_mesa");
1232
1233    return EGL_NO_IMAGE_KHR;
1234 }
1235
1236 static EGLBoolean
1237 dri2_export_drm_image_mesa(_EGLDriver *drv, _EGLDisplay *disp, _EGLImage *img,
1238                           EGLint *name, EGLint *handle, EGLint *stride)
1239 {
1240    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1241    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
1242
1243    (void) drv;
1244
1245    if (name && !dri2_dpy->image->queryImage(dri2_img->dri_image,
1246                                             __DRI_IMAGE_ATTRIB_NAME, name)) {
1247       _eglError(EGL_BAD_ALLOC, "dri2_export_drm_image_mesa");
1248       return EGL_FALSE;
1249    }
1250
1251    if (handle)
1252       dri2_dpy->image->queryImage(dri2_img->dri_image,
1253                                   __DRI_IMAGE_ATTRIB_HANDLE, handle);
1254
1255    if (stride)
1256       dri2_dpy->image->queryImage(dri2_img->dri_image,
1257                                   __DRI_IMAGE_ATTRIB_STRIDE, stride);
1258
1259    return EGL_TRUE;
1260 }
1261
1262 #ifdef HAVE_WAYLAND_PLATFORM
1263
1264 static void *
1265 dri2_wl_reference_buffer(void *user_data, uint32_t name,
1266                          int32_t width, int32_t height,
1267                          uint32_t stride, uint32_t format)
1268 {
1269    _EGLDisplay *disp = user_data;
1270    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1271    __DRIimage *image;
1272    int dri_format;
1273
1274    switch (format) {
1275    case WL_GBM_FORMAT_ARGB8888:
1276       dri_format =__DRI_IMAGE_FORMAT_ARGB8888;
1277       break;
1278    case WL_GBM_FORMAT_XRGB8888:
1279       dri_format = __DRI_IMAGE_FORMAT_XRGB8888;
1280       break;
1281    default:
1282       return NULL;         
1283    }
1284
1285    image = dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
1286                                                 width, height, 
1287                                                 dri_format, name, stride / 4,
1288                                                 NULL);
1289
1290    return image;
1291 }
1292
1293 static void
1294 dri2_wl_release_buffer(void *user_data, void *buffer)
1295 {
1296    _EGLDisplay *disp = user_data;
1297    __DRIimage *image = buffer;
1298    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1299
1300    dri2_dpy->image->destroyImage(image);
1301 }
1302
1303 static struct wl_gbm_callbacks wl_gbm_callbacks = {
1304         .authenticate = NULL,
1305         .reference_buffer = dri2_wl_reference_buffer,
1306         .release_buffer = dri2_wl_release_buffer
1307 };
1308
1309 static EGLBoolean
1310 dri2_bind_wayland_display_wl(_EGLDriver *drv, _EGLDisplay *disp,
1311                              struct wl_display *wl_dpy)
1312 {
1313    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1314
1315    (void) drv;
1316
1317    if (dri2_dpy->wl_server_gbm)
1318            return EGL_FALSE;
1319
1320    wl_gbm_callbacks.authenticate =
1321       (int(*)(void *, uint32_t)) dri2_dpy->authenticate;
1322
1323    dri2_dpy->wl_server_gbm =
1324            wl_gbm_init(wl_dpy, dri2_dpy->device_name, dri2_dpy->fd, 
1325                             &wl_gbm_callbacks, disp);
1326
1327    if (!dri2_dpy->wl_server_gbm)
1328            return EGL_FALSE;
1329
1330    return EGL_TRUE;
1331 }
1332
1333 static EGLBoolean
1334 dri2_unbind_wayland_display_wl(_EGLDriver *drv, _EGLDisplay *disp,
1335                                struct wl_display *wl_dpy)
1336 {
1337    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1338
1339    (void) drv;
1340
1341    if (!dri2_dpy->wl_server_gbm)
1342            return EGL_FALSE;
1343
1344    wl_gbm_uninit(dri2_dpy->wl_server_gbm);
1345    dri2_dpy->wl_server_gbm = NULL;
1346
1347    return EGL_TRUE;
1348 }
1349 #endif
1350
1351 static void
1352 dri2_unload(_EGLDriver *drv)
1353 {
1354    struct dri2_egl_driver *dri2_drv = dri2_egl_driver(drv);
1355
1356    if (dri2_drv->handle)
1357       dlclose(dri2_drv->handle);
1358    free(dri2_drv);
1359 }
1360
1361 static EGLBoolean
1362 dri2_load(_EGLDriver *drv)
1363 {
1364    struct dri2_egl_driver *dri2_drv = dri2_egl_driver(drv);
1365 #ifdef HAVE_SHARED_GLAPI
1366 #ifdef HAVE_ANDROID_PLATFORM
1367    const char *libname = "libglapi.so";
1368 #else
1369    const char *libname = "libglapi.so.0";
1370 #endif
1371 #else
1372    /*
1373     * Both libGL.so and libglapi.so are glapi providers.  There is no way to
1374     * tell which one to load.
1375     */
1376    const char *libname = NULL;
1377 #endif
1378    void *handle;
1379
1380    /* RTLD_GLOBAL to make sure glapi symbols are visible to DRI drivers */
1381    handle = dlopen(libname, RTLD_LAZY | RTLD_GLOBAL);
1382    if (handle) {
1383       dri2_drv->get_proc_address = (_EGLProc (*)(const char *))
1384          dlsym(handle, "_glapi_get_proc_address");
1385       if (!dri2_drv->get_proc_address || !libname) {
1386          /* no need to keep a reference */
1387          dlclose(handle);
1388          handle = NULL;
1389       }
1390    }
1391
1392    /* if glapi is not available, loading DRI drivers will fail */
1393    if (!dri2_drv->get_proc_address) {
1394       _eglLog(_EGL_WARNING, "DRI2: failed to find _glapi_get_proc_address");
1395       return EGL_FALSE;
1396    }
1397
1398    dri2_drv->glFlush = (void (*)(void))
1399       dri2_drv->get_proc_address("glFlush");
1400
1401    dri2_drv->handle = handle;
1402
1403    return EGL_TRUE;
1404 }
1405
1406 /**
1407  * This is the main entrypoint into the driver, called by libEGL.
1408  * Create a new _EGLDriver object and init its dispatch table.
1409  */
1410 _EGLDriver *
1411 _eglBuiltInDriverDRI2(const char *args)
1412 {
1413    struct dri2_egl_driver *dri2_drv;
1414
1415    (void) args;
1416
1417    dri2_drv = malloc(sizeof *dri2_drv);
1418    if (!dri2_drv)
1419       return NULL;
1420
1421    memset(dri2_drv, 0, sizeof *dri2_drv);
1422
1423    if (!dri2_load(&dri2_drv->base)) {
1424       free(dri2_drv);
1425       return NULL;
1426    }
1427
1428    _eglInitDriverFallbacks(&dri2_drv->base);
1429    dri2_drv->base.API.Initialize = dri2_initialize;
1430    dri2_drv->base.API.Terminate = dri2_terminate;
1431    dri2_drv->base.API.CreateContext = dri2_create_context;
1432    dri2_drv->base.API.DestroyContext = dri2_destroy_context;
1433    dri2_drv->base.API.MakeCurrent = dri2_make_current;
1434    dri2_drv->base.API.GetProcAddress = dri2_get_proc_address;
1435    dri2_drv->base.API.WaitClient = dri2_wait_client;
1436    dri2_drv->base.API.WaitNative = dri2_wait_native;
1437    dri2_drv->base.API.BindTexImage = dri2_bind_tex_image;
1438    dri2_drv->base.API.ReleaseTexImage = dri2_release_tex_image;
1439    dri2_drv->base.API.CreateImageKHR = dri2_create_image_khr;
1440    dri2_drv->base.API.DestroyImageKHR = dri2_destroy_image_khr;
1441    dri2_drv->base.API.CreateDRMImageMESA = dri2_create_drm_image_mesa;
1442    dri2_drv->base.API.ExportDRMImageMESA = dri2_export_drm_image_mesa;
1443 #ifdef HAVE_WAYLAND_PLATFORM
1444    dri2_drv->base.API.BindWaylandDisplayWL = dri2_bind_wayland_display_wl;
1445    dri2_drv->base.API.UnbindWaylandDisplayWL = dri2_unbind_wayland_display_wl;
1446 #endif
1447
1448    dri2_drv->base.Name = "DRI2";
1449    dri2_drv->base.Unload = dri2_unload;
1450
1451    return &dri2_drv->base;
1452 }