Add exception handle for multithread case.
[platform/upstream/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 <stdbool.h>
29 #include <stdint.h>
30 #include <stdbool.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <stdio.h>
34 #include <limits.h>
35 #include <dlfcn.h>
36 #include <fcntl.h>
37 #include <errno.h>
38 #include <unistd.h>
39 #include <c11/threads.h>
40 #include <time.h>
41 #ifdef HAVE_LIBDRM
42 #include <xf86drm.h>
43 #include "drm-uapi/drm_fourcc.h"
44 #endif
45 #include <GL/gl.h>
46 #include <GL/internal/dri_interface.h>
47 #include <sys/types.h>
48 #include <sys/stat.h>
49
50 #ifdef HAVE_WAYLAND_PLATFORM
51 #include <wayland-client.h>
52 #include "wayland-drm.h"
53 #include "wayland-drm-client-protocol.h"
54 #include "linux-dmabuf-unstable-v1-client-protocol.h"
55 #endif
56
57 #ifdef HAVE_X11_PLATFORM
58 #include "X11/Xlibint.h"
59 #endif
60
61 #include "egldefines.h"
62 #include "egl_dri2.h"
63 #include "GL/mesa_glinterop.h"
64 #include "loader/loader.h"
65 #include "util/libsync.h"
66 #include "util/os_file.h"
67 #include "util/u_atomic.h"
68 #include "util/u_call_once.h"
69 #include "util/u_vector.h"
70 #include "mapi/glapi/glapi.h"
71 #include "util/bitscan.h"
72 #include "util/driconf.h"
73 #include "util/u_math.h"
74
75 #define NUM_ATTRIBS 12
76
77 static const struct dri2_pbuffer_visual {
78    const char *format_name;
79    unsigned int dri_image_format;
80    int rgba_shifts[4];
81    unsigned int rgba_sizes[4];
82 } dri2_pbuffer_visuals[] = {
83    {
84       "ABGR16F",
85       __DRI_IMAGE_FORMAT_ABGR16161616F,
86       { 0, 16, 32, 48 },
87       { 16, 16, 16, 16 }
88    },
89    {
90       "XBGR16F",
91       __DRI_IMAGE_FORMAT_XBGR16161616F,
92       { 0, 16, 32, -1 },
93       { 16, 16, 16, 0 }
94    },
95    {
96       "A2RGB10",
97       __DRI_IMAGE_FORMAT_ARGB2101010,
98       { 20, 10, 0, 30 },
99       { 10, 10, 10, 2 }
100    },
101    {
102       "X2RGB10",
103       __DRI_IMAGE_FORMAT_XRGB2101010,
104       { 20, 10, 0, -1 },
105       { 10, 10, 10, 0 }
106    },
107    {
108       "ARGB8888",
109       __DRI_IMAGE_FORMAT_ARGB8888,
110       { 16, 8, 0, 24 },
111       { 8, 8, 8, 8 }
112    },
113    {
114       "RGB888",
115       __DRI_IMAGE_FORMAT_XRGB8888,
116       { 16, 8, 0, -1 },
117       { 8, 8, 8, 0 }
118    },
119    {
120       "RGB565",
121       __DRI_IMAGE_FORMAT_RGB565,
122       { 11, 5, 0, -1 },
123       { 5, 6, 5, 0 }
124    },
125 };
126
127 static void
128 dri_set_background_context(void *loaderPrivate)
129 {
130    _EGLContext *ctx = _eglGetCurrentContext();
131    _EGLThreadInfo *t = _eglGetCurrentThread();
132
133    _eglBindContextToThread(ctx, t);
134 }
135
136 static void
137 dri2_gl_flush_get(_glapi_proc *glFlush)
138 {
139    *glFlush = _glapi_get_proc_address("glFlush");
140 }
141
142 static void
143 dri2_gl_flush()
144 {
145    static void (*glFlush)(void);
146    static util_once_flag once = UTIL_ONCE_FLAG_INIT;
147
148    util_call_once_data(&once,
149       (util_call_once_data_func)dri2_gl_flush_get, &glFlush);
150
151    /* if glFlush is not available things are horribly broken */
152    if (!glFlush) {
153       _eglLog(_EGL_WARNING, "DRI2: failed to find glFlush entry point");
154       return;
155    }
156
157    glFlush();
158 }
159
160 static GLboolean
161 dri_is_thread_safe(UNUSED void *loaderPrivate)
162 {
163 #ifdef HAVE_X11_PLATFORM
164    struct dri2_egl_surface *dri2_surf = loaderPrivate;
165
166    /* loader_dri3_blit_context_get creates a context with
167     * loaderPrivate being NULL. Enabling glthread for a blitting
168     * context isn't useful so return false.
169     */
170    if (!loaderPrivate)
171       return false;
172
173    _EGLDisplay *display =  dri2_surf->base.Resource.Display;
174
175    Display *xdpy = (Display*)display->PlatformDisplay;
176
177    /* Check Xlib is running in thread safe mode when running on EGL/X11-xlib
178     * platform
179     *
180     * 'lock_fns' is the XLockDisplay function pointer of the X11 display 'dpy'.
181     * It wll be NULL if XInitThreads wasn't called.
182     */
183    if (display->Platform == _EGL_PLATFORM_X11 && xdpy && !xdpy->lock_fns)
184       return false;
185 #endif
186
187    return true;
188 }
189
190 const __DRIbackgroundCallableExtension background_callable_extension = {
191    .base = { __DRI_BACKGROUND_CALLABLE, 2 },
192
193    .setBackgroundContext = dri_set_background_context,
194    .isThreadSafe         = dri_is_thread_safe,
195 };
196
197 const __DRIuseInvalidateExtension use_invalidate = {
198    .base = { __DRI_USE_INVALIDATE, 1 }
199 };
200
201 static void
202 dri2_get_pbuffer_drawable_info(__DRIdrawable * draw,
203                                int *x, int *y, int *w, int *h,
204                                void *loaderPrivate)
205 {
206    struct dri2_egl_surface *dri2_surf = loaderPrivate;
207
208    *x = *y = 0;
209    *w = dri2_surf->base.Width;
210    *h = dri2_surf->base.Height;
211 }
212
213 static int
214 dri2_get_bytes_per_pixel(struct dri2_egl_surface *dri2_surf)
215 {
216    const int depth = dri2_surf->base.Config->BufferSize;
217    return depth ? util_next_power_of_two(depth / 8) : 0;
218 }
219
220 static void
221 dri2_put_image(__DRIdrawable * draw, int op,
222                int x, int y, int w, int h,
223                char *data, void *loaderPrivate)
224 {
225    struct dri2_egl_surface *dri2_surf = loaderPrivate;
226    const int bpp = dri2_get_bytes_per_pixel(dri2_surf);
227    const int width = dri2_surf->base.Width;
228    const int height = dri2_surf->base.Height;
229    const int dst_stride = width*bpp;
230    const int src_stride = w*bpp;
231    const int x_offset = x*bpp;
232    int copy_width = src_stride;
233
234    if (!dri2_surf->swrast_device_buffer)
235       dri2_surf->swrast_device_buffer = malloc(height*dst_stride);
236
237    if (dri2_surf->swrast_device_buffer) {
238       const char *src = data;
239       char *dst = dri2_surf->swrast_device_buffer;
240
241       dst += x_offset;
242       dst += y*dst_stride;
243
244       /* Drivers are allowed to submit OOB PutImage requests, so clip here. */
245       if (copy_width > dst_stride - x_offset)
246          copy_width = dst_stride - x_offset;
247       if (h > height - y)
248          h = height - y;
249
250       for (; 0 < h; --h) {
251          memcpy(dst, src, copy_width);
252          dst += dst_stride;
253          src += src_stride;
254       }
255    }
256 }
257
258 static void
259 dri2_get_image(__DRIdrawable * read,
260                int x, int y, int w, int h,
261                char *data, void *loaderPrivate)
262 {
263    struct dri2_egl_surface *dri2_surf = loaderPrivate;
264    const int bpp = dri2_get_bytes_per_pixel(dri2_surf);
265    const int width = dri2_surf->base.Width;
266    const int height = dri2_surf->base.Height;
267    const int src_stride = width*bpp;
268    const int dst_stride = w*bpp;
269    const int x_offset = x*bpp;
270    int copy_width = dst_stride;
271    const char *src = dri2_surf->swrast_device_buffer;
272    char *dst = data;
273
274    if (!src) {
275       memset(data, 0, copy_width * h);
276       return;
277    }
278
279    src += x_offset;
280    src += y*src_stride;
281
282    /* Drivers are allowed to submit OOB GetImage requests, so clip here. */
283    if (copy_width > src_stride - x_offset)
284       copy_width = src_stride - x_offset;
285    if (h > height - y)
286       h = height - y;
287
288    for (; 0 < h; --h) {
289       memcpy(dst, src, copy_width);
290       src += src_stride;
291       dst += dst_stride;
292    }
293
294 }
295
296 /* HACK: technically we should have swrast_null, instead of these.
297  */
298 const __DRIswrastLoaderExtension swrast_pbuffer_loader_extension = {
299    .base            = { __DRI_SWRAST_LOADER, 1 },
300    .getDrawableInfo = dri2_get_pbuffer_drawable_info,
301    .putImage        = dri2_put_image,
302    .getImage        = dri2_get_image,
303 };
304
305 static const EGLint dri2_to_egl_attribute_map[__DRI_ATTRIB_MAX] = {
306    [__DRI_ATTRIB_BUFFER_SIZE ]          = EGL_BUFFER_SIZE,
307    [__DRI_ATTRIB_LEVEL]                 = EGL_LEVEL,
308    [__DRI_ATTRIB_LUMINANCE_SIZE]        = EGL_LUMINANCE_SIZE,
309    [__DRI_ATTRIB_DEPTH_SIZE]            = EGL_DEPTH_SIZE,
310    [__DRI_ATTRIB_STENCIL_SIZE]          = EGL_STENCIL_SIZE,
311    [__DRI_ATTRIB_SAMPLE_BUFFERS]        = EGL_SAMPLE_BUFFERS,
312    [__DRI_ATTRIB_SAMPLES]               = EGL_SAMPLES,
313    [__DRI_ATTRIB_MAX_PBUFFER_WIDTH]     = EGL_MAX_PBUFFER_WIDTH,
314    [__DRI_ATTRIB_MAX_PBUFFER_HEIGHT]    = EGL_MAX_PBUFFER_HEIGHT,
315    [__DRI_ATTRIB_MAX_PBUFFER_PIXELS]    = EGL_MAX_PBUFFER_PIXELS,
316    [__DRI_ATTRIB_MAX_SWAP_INTERVAL]     = EGL_MAX_SWAP_INTERVAL,
317    [__DRI_ATTRIB_MIN_SWAP_INTERVAL]     = EGL_MIN_SWAP_INTERVAL,
318    [__DRI_ATTRIB_YINVERTED]             = EGL_Y_INVERTED_NOK,
319 };
320
321 const __DRIconfig *
322 dri2_get_dri_config(struct dri2_egl_config *conf, EGLint surface_type,
323                     EGLenum colorspace)
324 {
325    const bool double_buffer = surface_type == EGL_WINDOW_BIT;
326    const bool srgb = colorspace == EGL_GL_COLORSPACE_SRGB_KHR;
327
328    return conf->dri_config[double_buffer][srgb];
329 }
330
331 static EGLBoolean
332 dri2_match_config(const _EGLConfig *conf, const _EGLConfig *criteria)
333 {
334    if (_eglCompareConfigs(conf, criteria, NULL, EGL_FALSE) != 0)
335       return EGL_FALSE;
336
337    if (!_eglMatchConfig(conf, criteria))
338       return EGL_FALSE;
339
340    return EGL_TRUE;
341 }
342
343 void
344 dri2_get_shifts_and_sizes(const __DRIcoreExtension *core,
345                           const __DRIconfig *config, int *shifts,
346                           unsigned int *sizes)
347 {
348    unsigned int mask;
349
350    if (core->getConfigAttrib(config, __DRI_ATTRIB_RED_SHIFT, (unsigned int *)&shifts[0])) {
351       core->getConfigAttrib(config, __DRI_ATTRIB_GREEN_SHIFT, (unsigned int *)&shifts[1]);
352       core->getConfigAttrib(config, __DRI_ATTRIB_BLUE_SHIFT, (unsigned int *)&shifts[2]);
353       core->getConfigAttrib(config, __DRI_ATTRIB_ALPHA_SHIFT, (unsigned int *)&shifts[3]);
354    } else {
355       /* Driver isn't exposing shifts, so convert masks to shifts */
356       core->getConfigAttrib(config, __DRI_ATTRIB_RED_MASK, &mask);
357       shifts[0] = ffs(mask) - 1;
358       core->getConfigAttrib(config, __DRI_ATTRIB_GREEN_MASK, &mask);
359       shifts[1] = ffs(mask) - 1;
360       core->getConfigAttrib(config, __DRI_ATTRIB_BLUE_MASK, &mask);
361       shifts[2] = ffs(mask) - 1;
362       core->getConfigAttrib(config, __DRI_ATTRIB_ALPHA_MASK, &mask);
363       shifts[3] = ffs(mask) - 1;
364    }
365
366    core->getConfigAttrib(config, __DRI_ATTRIB_RED_SIZE, &sizes[0]);
367    core->getConfigAttrib(config, __DRI_ATTRIB_GREEN_SIZE, &sizes[1]);
368    core->getConfigAttrib(config, __DRI_ATTRIB_BLUE_SIZE, &sizes[2]);
369    core->getConfigAttrib(config, __DRI_ATTRIB_ALPHA_SIZE, &sizes[3]);
370 }
371
372 void
373 dri2_get_render_type_float(const __DRIcoreExtension *core,
374                            const __DRIconfig *config,
375                            bool *is_float)
376 {
377    unsigned int render_type;
378
379    core->getConfigAttrib(config, __DRI_ATTRIB_RENDER_TYPE, &render_type);
380    *is_float = (render_type & __DRI_ATTRIB_FLOAT_BIT) ? true : false;
381 }
382
383 unsigned int
384 dri2_image_format_for_pbuffer_config(struct dri2_egl_display *dri2_dpy,
385                                      const __DRIconfig *config)
386 {
387    int shifts[4];
388    unsigned int sizes[4];
389
390    dri2_get_shifts_and_sizes(dri2_dpy->core, config, shifts, sizes);
391
392    for (unsigned i = 0; i < ARRAY_SIZE(dri2_pbuffer_visuals); ++i) {
393       const struct dri2_pbuffer_visual *visual = &dri2_pbuffer_visuals[i];
394
395       if (shifts[0] == visual->rgba_shifts[0] &&
396           shifts[1] == visual->rgba_shifts[1] &&
397           shifts[2] == visual->rgba_shifts[2] &&
398           shifts[3] == visual->rgba_shifts[3] &&
399           sizes[0] == visual->rgba_sizes[0] &&
400           sizes[1] == visual->rgba_sizes[1] &&
401           sizes[2] == visual->rgba_sizes[2] &&
402           sizes[3] == visual->rgba_sizes[3]) {
403          return visual->dri_image_format;
404       }
405    }
406
407    return __DRI_IMAGE_FORMAT_NONE;
408 }
409
410 struct dri2_egl_config *
411 dri2_add_config(_EGLDisplay *disp, const __DRIconfig *dri_config, int id,
412                 EGLint surface_type, const EGLint *attr_list,
413                 const int *rgba_shifts, const unsigned int *rgba_sizes)
414 {
415    struct dri2_egl_config *conf;
416    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
417    _EGLConfig base;
418    unsigned int attrib, value, double_buffer;
419    bool srgb = false;
420    EGLint key, bind_to_texture_rgb, bind_to_texture_rgba;
421    int dri_shifts[4] = { -1, -1, -1, -1 };
422    unsigned int dri_sizes[4] = { 0, 0, 0, 0 };
423    _EGLConfig *matching_config;
424    EGLint num_configs = 0;
425    EGLint config_id;
426
427    _eglInitConfig(&base, disp, id);
428
429    double_buffer = 0;
430    bind_to_texture_rgb = 0;
431    bind_to_texture_rgba = 0;
432
433    for (int i = 0; i < __DRI_ATTRIB_MAX; ++i) {
434       if (!dri2_dpy->core->indexConfigAttrib(dri_config, i, &attrib, &value))
435          break;
436
437       switch (attrib) {
438       case __DRI_ATTRIB_RENDER_TYPE:
439          if (value & __DRI_ATTRIB_FLOAT_BIT)
440             base.ComponentType = EGL_COLOR_COMPONENT_TYPE_FLOAT_EXT;
441          if (value & __DRI_ATTRIB_RGBA_BIT)
442             value = EGL_RGB_BUFFER;
443          else if (value & __DRI_ATTRIB_LUMINANCE_BIT)
444             value = EGL_LUMINANCE_BUFFER;
445          else
446             return NULL;
447          base.ColorBufferType = value;
448          break;
449
450       case __DRI_ATTRIB_CONFIG_CAVEAT:
451          if (value & __DRI_ATTRIB_NON_CONFORMANT_CONFIG)
452             value = EGL_NON_CONFORMANT_CONFIG;
453          else if (value & __DRI_ATTRIB_SLOW_BIT)
454             value = EGL_SLOW_CONFIG;
455          else
456             value = EGL_NONE;
457          base.ConfigCaveat = value;
458          break;
459
460       case __DRI_ATTRIB_BIND_TO_TEXTURE_RGB:
461          bind_to_texture_rgb = value;
462          break;
463
464       case __DRI_ATTRIB_BIND_TO_TEXTURE_RGBA:
465          bind_to_texture_rgba = value;
466          break;
467
468       case __DRI_ATTRIB_DOUBLE_BUFFER:
469          double_buffer = value;
470          break;
471
472       case __DRI_ATTRIB_RED_SIZE:
473          dri_sizes[0] = value;
474          base.RedSize = value;
475          break;
476
477       case __DRI_ATTRIB_RED_MASK:
478          dri_shifts[0] = ffs(value) - 1;
479          break;
480
481       case __DRI_ATTRIB_RED_SHIFT:
482          dri_shifts[0] = value;
483          break;
484
485       case __DRI_ATTRIB_GREEN_SIZE:
486          dri_sizes[1] = value;
487          base.GreenSize = value;
488          break;
489
490       case __DRI_ATTRIB_GREEN_MASK:
491          dri_shifts[1] = ffs(value) - 1;
492          break;
493
494       case __DRI_ATTRIB_GREEN_SHIFT:
495          dri_shifts[1] = value;
496          break;
497
498       case __DRI_ATTRIB_BLUE_SIZE:
499          dri_sizes[2] = value;
500          base.BlueSize = value;
501          break;
502
503       case __DRI_ATTRIB_BLUE_MASK:
504          dri_shifts[2] = ffs(value) - 1;
505          break;
506
507       case __DRI_ATTRIB_BLUE_SHIFT:
508          dri_shifts[2] = value;
509          break;
510
511      case __DRI_ATTRIB_ALPHA_SIZE:
512          dri_sizes[3] = value;
513          base.AlphaSize = value;
514          break;
515
516       case __DRI_ATTRIB_ALPHA_MASK:
517          dri_shifts[3] = ffs(value) - 1;
518          break;
519
520       case __DRI_ATTRIB_ALPHA_SHIFT:
521          dri_shifts[3] = value;
522          break;
523
524       case __DRI_ATTRIB_ACCUM_RED_SIZE:
525       case __DRI_ATTRIB_ACCUM_GREEN_SIZE:
526       case __DRI_ATTRIB_ACCUM_BLUE_SIZE:
527       case __DRI_ATTRIB_ACCUM_ALPHA_SIZE:
528          /* Don't expose visuals with the accumulation buffer. */
529          if (value > 0)
530             return NULL;
531          break;
532
533       case __DRI_ATTRIB_FRAMEBUFFER_SRGB_CAPABLE:
534          srgb = value != 0;
535          if (!disp->Extensions.KHR_gl_colorspace && srgb)
536             return NULL;
537          break;
538
539       case __DRI_ATTRIB_MAX_PBUFFER_WIDTH:
540          base.MaxPbufferWidth = _EGL_MAX_PBUFFER_WIDTH;
541          break;
542       case __DRI_ATTRIB_MAX_PBUFFER_HEIGHT:
543          base.MaxPbufferHeight = _EGL_MAX_PBUFFER_HEIGHT;
544          break;
545       case __DRI_ATTRIB_MUTABLE_RENDER_BUFFER:
546          if (disp->Extensions.KHR_mutable_render_buffer)
547             surface_type |= EGL_MUTABLE_RENDER_BUFFER_BIT_KHR;
548          break;
549       default:
550          key = dri2_to_egl_attribute_map[attrib];
551          if (key != 0)
552             _eglSetConfigKey(&base, key, value);
553          break;
554       }
555    }
556
557    if (attr_list)
558       for (int i = 0; attr_list[i] != EGL_NONE; i += 2)
559          _eglSetConfigKey(&base, attr_list[i], attr_list[i+1]);
560
561    if (rgba_shifts && memcmp(rgba_shifts, dri_shifts, sizeof(dri_shifts)))
562       return NULL;
563
564    if (rgba_sizes && memcmp(rgba_sizes, dri_sizes, sizeof(dri_sizes)))
565       return NULL;
566
567    base.NativeRenderable = EGL_TRUE;
568
569    base.SurfaceType = surface_type;
570    if (surface_type & (EGL_PBUFFER_BIT |
571        (disp->Extensions.NOK_texture_from_pixmap ? EGL_PIXMAP_BIT : 0))) {
572       base.BindToTextureRGB = bind_to_texture_rgb;
573       if (base.AlphaSize > 0)
574          base.BindToTextureRGBA = bind_to_texture_rgba;
575    }
576
577    if (double_buffer) {
578       surface_type &= ~EGL_PIXMAP_BIT;
579    }
580
581    if (!surface_type)
582       return NULL;
583
584    base.RenderableType = disp->ClientAPIs;
585    base.Conformant = disp->ClientAPIs;
586
587    base.MinSwapInterval = dri2_dpy->min_swap_interval;
588    base.MaxSwapInterval = dri2_dpy->max_swap_interval;
589
590    if (!_eglValidateConfig(&base, EGL_FALSE)) {
591       _eglLog(_EGL_DEBUG, "DRI2: failed to validate config %d", id);
592       return NULL;
593    }
594
595    config_id = base.ConfigID;
596    base.ConfigID    = EGL_DONT_CARE;
597    base.SurfaceType = EGL_DONT_CARE;
598    num_configs = _eglFilterArray(disp->Configs, (void **) &matching_config, 1,
599                                  (_EGLArrayForEach) dri2_match_config, &base);
600
601    if (num_configs == 1) {
602       conf = (struct dri2_egl_config *) matching_config;
603
604       if (!conf->dri_config[double_buffer][srgb])
605          conf->dri_config[double_buffer][srgb] = dri_config;
606       else
607          /* a similar config type is already added (unlikely) => discard */
608          return NULL;
609    }
610    else if (num_configs == 0) {
611       conf = calloc(1, sizeof *conf);
612       if (conf == NULL)
613          return NULL;
614
615       conf->dri_config[double_buffer][srgb] = dri_config;
616
617       memcpy(&conf->base, &base, sizeof base);
618       conf->base.SurfaceType = 0;
619       conf->base.ConfigID = config_id;
620
621       _eglLinkConfig(&conf->base);
622    }
623    else {
624       unreachable("duplicates should not be possible");
625       return NULL;
626    }
627
628    conf->base.SurfaceType |= surface_type;
629
630    return conf;
631 }
632
633 EGLBoolean
634 dri2_add_pbuffer_configs_for_visuals(_EGLDisplay *disp)
635 {
636    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
637    unsigned int format_count[ARRAY_SIZE(dri2_pbuffer_visuals)] = { 0 };
638    unsigned int config_count = 0;
639
640    for (unsigned i = 0; dri2_dpy->driver_configs[i] != NULL; i++) {
641       for (unsigned j = 0; j < ARRAY_SIZE(dri2_pbuffer_visuals); j++) {
642          struct dri2_egl_config *dri2_conf;
643
644          dri2_conf = dri2_add_config(disp, dri2_dpy->driver_configs[i],
645                config_count + 1, EGL_PBUFFER_BIT, NULL,
646                dri2_pbuffer_visuals[j].rgba_shifts, dri2_pbuffer_visuals[j].rgba_sizes);
647
648          if (dri2_conf) {
649             if (dri2_conf->base.ConfigID == config_count + 1)
650                config_count++;
651             format_count[j]++;
652          }
653       }
654    }
655
656    for (unsigned i = 0; i < ARRAY_SIZE(format_count); i++) {
657       if (!format_count[i]) {
658          _eglLog(_EGL_DEBUG, "No DRI config supports native format %s",
659                dri2_pbuffer_visuals[i].format_name);
660       }
661    }
662
663    return (config_count != 0);
664 }
665
666 GLboolean
667 dri2_validate_egl_image(void *image, void *data)
668 {
669    _EGLDisplay *disp = _eglLockDisplay(data);
670    _EGLImage *img = _eglLookupImage(image, disp);
671    _eglUnlockDisplay(disp);
672
673    if (img == NULL) {
674       _eglError(EGL_BAD_PARAMETER, "dri2_validate_egl_image");
675       return false;
676    }
677
678    return true;
679 }
680
681 __DRIimage *
682 dri2_lookup_egl_image_validated(void *image, void *data)
683 {
684    struct dri2_egl_image *dri2_img;
685
686    (void)data;
687
688    dri2_img = dri2_egl_image(image);
689
690    return dri2_img->dri_image;
691 }
692
693 __DRIimage *
694 dri2_lookup_egl_image(__DRIscreen *screen, void *image, void *data)
695 {
696    (void) screen;
697
698    if (!dri2_validate_egl_image(image, data))
699       return NULL;
700
701    return dri2_lookup_egl_image_validated(image, data);
702 }
703
704 const __DRIimageLookupExtension image_lookup_extension = {
705    .base = { __DRI_IMAGE_LOOKUP, 2 },
706
707    .lookupEGLImage       = dri2_lookup_egl_image,
708    .validateEGLImage     = dri2_validate_egl_image,
709    .lookupEGLImageValidated = dri2_lookup_egl_image_validated,
710 };
711
712 struct dri2_extension_match {
713    const char *name;
714    int version;
715    int offset;
716 };
717
718 static const struct dri2_extension_match dri3_driver_extensions[] = {
719    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
720    { __DRI_IMAGE_DRIVER, 1, offsetof(struct dri2_egl_display, image_driver) },
721    { NULL, 0, 0 }
722 };
723
724 static const struct dri2_extension_match dri2_driver_extensions[] = {
725    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
726    { __DRI_DRI2, 2, offsetof(struct dri2_egl_display, dri2) },
727    { NULL, 0, 0 }
728 };
729
730 static const struct dri2_extension_match dri2_core_extensions[] = {
731    { __DRI2_FLUSH, 1, offsetof(struct dri2_egl_display, flush) },
732    { __DRI_TEX_BUFFER, 2, offsetof(struct dri2_egl_display, tex_buffer) },
733    { __DRI_IMAGE, 1, offsetof(struct dri2_egl_display, image) },
734    { NULL, 0, 0 }
735 };
736
737 static const struct dri2_extension_match swrast_driver_extensions[] = {
738    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
739    { __DRI_SWRAST, 2, offsetof(struct dri2_egl_display, swrast) },
740    { NULL, 0, 0 }
741 };
742
743 static const struct dri2_extension_match swrast_core_extensions[] = {
744    { __DRI_TEX_BUFFER, 2, offsetof(struct dri2_egl_display, tex_buffer) },
745    { NULL, 0, 0 }
746 };
747
748 static const struct dri2_extension_match optional_driver_extensions[] = {
749    { __DRI_CONFIG_OPTIONS, 1, offsetof(struct dri2_egl_display, configOptions) },
750    { NULL, 0, 0 }
751 };
752
753 static const struct dri2_extension_match optional_core_extensions[] = {
754    { __DRI2_ROBUSTNESS, 1, offsetof(struct dri2_egl_display, robustness) },
755    { __DRI2_CONFIG_QUERY, 1, offsetof(struct dri2_egl_display, config) },
756    { __DRI2_FENCE, 1, offsetof(struct dri2_egl_display, fence) },
757    { __DRI2_BUFFER_DAMAGE, 1, offsetof(struct dri2_egl_display, buffer_damage) },
758    { __DRI2_RENDERER_QUERY, 1, offsetof(struct dri2_egl_display, rendererQuery) },
759    { __DRI2_INTEROP, 1, offsetof(struct dri2_egl_display, interop) },
760    { __DRI_IMAGE, 1, offsetof(struct dri2_egl_display, image) },
761    { __DRI2_FLUSH_CONTROL, 1, offsetof(struct dri2_egl_display, flush_control) },
762    { __DRI2_BLOB, 1, offsetof(struct dri2_egl_display, blob) },
763    { __DRI_MUTABLE_RENDER_BUFFER_DRIVER, 1, offsetof(struct dri2_egl_display, mutable_render_buffer) },
764    { __DRI_KOPPER, 1, offsetof(struct dri2_egl_display, kopper) },
765    { NULL, 0, 0 }
766 };
767
768 static EGLBoolean
769 dri2_bind_extensions(struct dri2_egl_display *dri2_dpy,
770                      const struct dri2_extension_match *matches,
771                      const __DRIextension **extensions,
772                      bool optional)
773 {
774    int ret = EGL_TRUE;
775    void *field;
776
777    for (int i = 0; extensions[i]; i++) {
778       _eglLog(_EGL_DEBUG, "found extension `%s'", extensions[i]->name);
779       for (int j = 0; matches[j].name; j++) {
780          if (strcmp(extensions[i]->name, matches[j].name) == 0 &&
781              extensions[i]->version >= matches[j].version) {
782             field = ((char *) dri2_dpy + matches[j].offset);
783             *(const __DRIextension **) field = extensions[i];
784             _eglLog(_EGL_INFO, "found extension %s version %d",
785                     extensions[i]->name, extensions[i]->version);
786             break;
787          }
788       }
789    }
790
791    for (int j = 0; matches[j].name; j++) {
792       field = ((char *) dri2_dpy + matches[j].offset);
793       if (*(const __DRIextension **) field == NULL) {
794          if (optional) {
795             _eglLog(_EGL_DEBUG, "did not find optional extension %s version %d",
796                     matches[j].name, matches[j].version);
797          } else {
798             _eglLog(_EGL_WARNING, "did not find extension %s version %d",
799                     matches[j].name, matches[j].version);
800             ret = EGL_FALSE;
801          }
802       }
803    }
804
805    return ret;
806 }
807
808 static const __DRIextension **
809 dri2_open_driver(_EGLDisplay *disp)
810 {
811    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
812    static const char *search_path_vars[] = {
813       "LIBGL_DRIVERS_PATH",
814       NULL,
815    };
816
817    return loader_open_driver(dri2_dpy->driver_name,
818                              &dri2_dpy->driver,
819                              search_path_vars);
820 }
821
822 static EGLBoolean
823 dri2_load_driver_common(_EGLDisplay *disp,
824                         const struct dri2_extension_match *driver_extensions)
825 {
826    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
827    const __DRIextension **extensions;
828
829    /*This exception only happen in multithread case, when _eglAtExit is *
830     *called and disp is freed in main thread.                           */
831    if (dri2_dpy == NULL) {
832       _eglLog(_EGL_FATAL, "DRI2: disp is freed");
833       return EGL_FALSE;
834    }
835
836    extensions = dri2_open_driver(disp);
837    if (!extensions)
838       return EGL_FALSE;
839
840    if (!dri2_bind_extensions(dri2_dpy, driver_extensions, extensions, false)) {
841       dlclose(dri2_dpy->driver);
842       dri2_dpy->driver = NULL;
843       return EGL_FALSE;
844    }
845    dri2_dpy->driver_extensions = extensions;
846
847    dri2_bind_extensions(dri2_dpy, optional_driver_extensions, extensions, true);
848
849    return EGL_TRUE;
850 }
851
852 EGLBoolean
853 dri2_load_driver(_EGLDisplay *disp)
854 {
855    return dri2_load_driver_common(disp, dri2_driver_extensions);
856 }
857
858 EGLBoolean
859 dri2_load_driver_dri3(_EGLDisplay *disp)
860 {
861    return dri2_load_driver_common(disp, dri3_driver_extensions);
862 }
863
864 EGLBoolean
865 dri2_load_driver_swrast(_EGLDisplay *disp)
866 {
867    return dri2_load_driver_common(disp, swrast_driver_extensions);
868 }
869
870 static unsigned
871 dri2_renderer_query_integer(struct dri2_egl_display *dri2_dpy, int param)
872 {
873    const __DRI2rendererQueryExtension *rendererQuery = dri2_dpy->rendererQuery;
874    unsigned int value = 0;
875
876    if (!rendererQuery ||
877        rendererQuery->queryInteger(dri2_dpy->dri_screen, param, &value) == -1)
878       return 0;
879
880    return value;
881 }
882
883 static const char *
884 dri2_query_driver_name(_EGLDisplay *disp)
885 {
886     struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
887     return dri2_dpy->driver_name;
888 }
889
890 static char *
891 dri2_query_driver_config(_EGLDisplay *disp)
892 {
893     struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
894     const __DRIconfigOptionsExtension *ext = dri2_dpy->configOptions;
895     char *ret;
896
897     if (ext->base.version >= 2) {
898         ret = ext->getXml(dri2_dpy->driver_name);
899     } else {
900        ret = strdup(ext->xml);
901     }
902
903     mtx_unlock(&dri2_dpy->lock);
904
905     return ret;
906 }
907
908
909 void
910 dri2_setup_screen(_EGLDisplay *disp)
911 {
912    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
913    unsigned int api_mask;
914
915    /*
916     * EGL 1.5 specification defines the default value to 1. Moreover,
917     * eglSwapInterval() is required to clamp requested value to the supported
918     * range. Since the default value is implicitly assumed to be supported,
919     * use it as both minimum and maximum for the platforms that do not allow
920     * changing the interval. Platforms, which allow it (e.g. x11, wayland)
921     * override these values already.
922     */
923    dri2_dpy->min_swap_interval = 1;
924    dri2_dpy->max_swap_interval = 1;
925    dri2_dpy->default_swap_interval = 1;
926
927    if (dri2_dpy->image_driver) {
928       api_mask = dri2_dpy->image_driver->getAPIMask(dri2_dpy->dri_screen);
929    } else if (dri2_dpy->dri2) {
930       api_mask = dri2_dpy->dri2->getAPIMask(dri2_dpy->dri_screen);
931    } else {
932       assert(dri2_dpy->swrast);
933       api_mask = 1 << __DRI_API_OPENGL |
934                  1 << __DRI_API_GLES |
935                  1 << __DRI_API_GLES2 |
936                  1 << __DRI_API_GLES3;
937    }
938
939    disp->ClientAPIs = 0;
940    if ((api_mask & (1 <<__DRI_API_OPENGL)) && _eglIsApiValid(EGL_OPENGL_API))
941       disp->ClientAPIs |= EGL_OPENGL_BIT;
942    if ((api_mask & (1 << __DRI_API_GLES)) && _eglIsApiValid(EGL_OPENGL_ES_API))
943       disp->ClientAPIs |= EGL_OPENGL_ES_BIT;
944    if ((api_mask & (1 << __DRI_API_GLES2)) && _eglIsApiValid(EGL_OPENGL_ES_API))
945       disp->ClientAPIs |= EGL_OPENGL_ES2_BIT;
946    if ((api_mask & (1 << __DRI_API_GLES3)) && _eglIsApiValid(EGL_OPENGL_ES_API))
947       disp->ClientAPIs |= EGL_OPENGL_ES3_BIT_KHR;
948
949    assert(dri2_dpy->image_driver || dri2_dpy->dri2 || dri2_dpy->swrast);
950    disp->Extensions.KHR_no_config_context = EGL_TRUE;
951    disp->Extensions.KHR_surfaceless_context = EGL_TRUE;
952
953    if (dri2_dpy->configOptions) {
954        disp->Extensions.MESA_query_driver = EGL_TRUE;
955    }
956
957    /* Report back to EGL the bitmask of priorities supported */
958    disp->Extensions.IMG_context_priority =
959       dri2_renderer_query_integer(dri2_dpy,
960                                   __DRI2_RENDERER_HAS_CONTEXT_PRIORITY);
961
962    disp->Extensions.EXT_pixel_format_float = EGL_TRUE;
963
964    if (dri2_renderer_query_integer(dri2_dpy,
965                                    __DRI2_RENDERER_HAS_FRAMEBUFFER_SRGB))
966       disp->Extensions.KHR_gl_colorspace = EGL_TRUE;
967
968    if (dri2_dpy->image_driver ||
969        (dri2_dpy->dri2 && dri2_dpy->dri2->base.version >= 3) ||
970        (dri2_dpy->swrast && dri2_dpy->swrast->base.version >= 3)) {
971       disp->Extensions.KHR_create_context = EGL_TRUE;
972
973       if (dri2_dpy->robustness)
974          disp->Extensions.EXT_create_context_robustness = EGL_TRUE;
975    }
976
977    if (dri2_renderer_query_integer(dri2_dpy,
978                                    __DRI2_RENDERER_HAS_NO_ERROR_CONTEXT))
979       disp->Extensions.KHR_create_context_no_error = EGL_TRUE;
980
981    if (dri2_dpy->fence) {
982       disp->Extensions.KHR_fence_sync = EGL_TRUE;
983       disp->Extensions.KHR_wait_sync = EGL_TRUE;
984       if (dri2_dpy->fence->get_fence_from_cl_event)
985          disp->Extensions.KHR_cl_event2 = EGL_TRUE;
986       if (dri2_dpy->fence->base.version >= 2 &&
987           dri2_dpy->fence->get_capabilities) {
988          unsigned capabilities =
989             dri2_dpy->fence->get_capabilities(dri2_dpy->dri_screen);
990          disp->Extensions.ANDROID_native_fence_sync =
991             (capabilities & __DRI_FENCE_CAP_NATIVE_FD) != 0;
992       }
993    }
994
995    if (dri2_dpy->blob)
996       disp->Extensions.ANDROID_blob_cache = EGL_TRUE;
997
998    disp->Extensions.KHR_reusable_sync = EGL_TRUE;
999
1000    if (dri2_dpy->image) {
1001       if (dri2_dpy->image->base.version >= 10 &&
1002           dri2_dpy->image->getCapabilities != NULL) {
1003          int capabilities;
1004
1005          capabilities = dri2_dpy->image->getCapabilities(dri2_dpy->dri_screen);
1006          disp->Extensions.MESA_drm_image = (capabilities & __DRI_IMAGE_CAP_GLOBAL_NAMES) != 0;
1007
1008          if (dri2_dpy->image->base.version >= 11)
1009             disp->Extensions.MESA_image_dma_buf_export = EGL_TRUE;
1010       } else {
1011          disp->Extensions.MESA_drm_image = EGL_TRUE;
1012          if (dri2_dpy->image->base.version >= 11)
1013             disp->Extensions.MESA_image_dma_buf_export = EGL_TRUE;
1014       }
1015
1016       disp->Extensions.KHR_image_base = EGL_TRUE;
1017       disp->Extensions.KHR_gl_renderbuffer_image = EGL_TRUE;
1018       if (dri2_dpy->image->base.version >= 5 &&
1019           dri2_dpy->image->createImageFromTexture) {
1020          disp->Extensions.KHR_gl_texture_2D_image = EGL_TRUE;
1021          disp->Extensions.KHR_gl_texture_cubemap_image = EGL_TRUE;
1022
1023          if (dri2_renderer_query_integer(dri2_dpy,
1024                                          __DRI2_RENDERER_HAS_TEXTURE_3D))
1025              disp->Extensions.KHR_gl_texture_3D_image = EGL_TRUE;
1026       }
1027 #ifdef HAVE_LIBDRM
1028       if (dri2_dpy->image->base.version >= 8 &&
1029           dri2_dpy->image->createImageFromDmaBufs) {
1030          disp->Extensions.EXT_image_dma_buf_import = EGL_TRUE;
1031          disp->Extensions.EXT_image_dma_buf_import_modifiers = EGL_TRUE;
1032       }
1033 #endif
1034    }
1035
1036    if (dri2_dpy->flush_control)
1037       disp->Extensions.KHR_context_flush_control = EGL_TRUE;
1038
1039    if (dri2_dpy->buffer_damage && dri2_dpy->buffer_damage->set_damage_region)
1040       disp->Extensions.KHR_partial_update = EGL_TRUE;
1041
1042    disp->Extensions.EXT_protected_surface =
1043       dri2_renderer_query_integer(dri2_dpy,
1044                                   __DRI2_RENDERER_HAS_PROTECTED_SURFACE);
1045    disp->Extensions.EXT_protected_content =
1046       dri2_renderer_query_integer(dri2_dpy,
1047                                   __DRI2_RENDERER_HAS_PROTECTED_CONTEXT);
1048 }
1049
1050 void
1051 dri2_setup_swap_interval(_EGLDisplay *disp, int max_swap_interval)
1052 {
1053    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1054    GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1;
1055
1056    /* Allow driconf to override applications.*/
1057    if (dri2_dpy->config)
1058       dri2_dpy->config->configQueryi(dri2_dpy->dri_screen,
1059                                      "vblank_mode", &vblank_mode);
1060    switch (vblank_mode) {
1061    case DRI_CONF_VBLANK_NEVER:
1062       dri2_dpy->min_swap_interval = 0;
1063       dri2_dpy->max_swap_interval = 0;
1064       dri2_dpy->default_swap_interval = 0;
1065       break;
1066    case DRI_CONF_VBLANK_ALWAYS_SYNC:
1067       dri2_dpy->min_swap_interval = 1;
1068       dri2_dpy->max_swap_interval = max_swap_interval;
1069       dri2_dpy->default_swap_interval = 1;
1070       break;
1071    case DRI_CONF_VBLANK_DEF_INTERVAL_0:
1072       dri2_dpy->min_swap_interval = 0;
1073       dri2_dpy->max_swap_interval = max_swap_interval;
1074       dri2_dpy->default_swap_interval = 0;
1075       break;
1076    default:
1077    case DRI_CONF_VBLANK_DEF_INTERVAL_1:
1078       dri2_dpy->min_swap_interval = 0;
1079       dri2_dpy->max_swap_interval = max_swap_interval;
1080       dri2_dpy->default_swap_interval = 1;
1081       break;
1082    }
1083 }
1084
1085 /* All platforms but DRM call this function to create the screen and populate
1086  * the driver_configs. DRM inherits that information from its display - GBM.
1087  */
1088 EGLBoolean
1089 dri2_create_screen(_EGLDisplay *disp)
1090 {
1091    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1092
1093    if (dri2_dpy->image_driver) {
1094       dri2_dpy->dri_screen =
1095          dri2_dpy->image_driver->createNewScreen2(0, dri2_dpy->fd,
1096                                                   dri2_dpy->loader_extensions,
1097                                                   dri2_dpy->driver_extensions,
1098                                                   &dri2_dpy->driver_configs,
1099                                                   disp);
1100    } else if (dri2_dpy->dri2) {
1101       if (dri2_dpy->dri2->base.version >= 4) {
1102          dri2_dpy->dri_screen =
1103             dri2_dpy->dri2->createNewScreen2(0, dri2_dpy->fd,
1104                                              dri2_dpy->loader_extensions,
1105                                              dri2_dpy->driver_extensions,
1106                                              &dri2_dpy->driver_configs, disp);
1107       } else {
1108          dri2_dpy->dri_screen =
1109             dri2_dpy->dri2->createNewScreen(0, dri2_dpy->fd,
1110                                             dri2_dpy->loader_extensions,
1111                                             &dri2_dpy->driver_configs, disp);
1112       }
1113    } else {
1114       assert(dri2_dpy->swrast);
1115       if (dri2_dpy->swrast->base.version >= 4) {
1116          dri2_dpy->dri_screen =
1117             dri2_dpy->swrast->createNewScreen2(0, dri2_dpy->loader_extensions,
1118                                                dri2_dpy->driver_extensions,
1119                                                &dri2_dpy->driver_configs, disp);
1120       } else {
1121          dri2_dpy->dri_screen =
1122             dri2_dpy->swrast->createNewScreen(0, dri2_dpy->loader_extensions,
1123                                               &dri2_dpy->driver_configs, disp);
1124       }
1125    }
1126
1127    if (dri2_dpy->dri_screen == NULL) {
1128       _eglLog(_EGL_WARNING, "egl: failed to create dri2 screen");
1129       return EGL_FALSE;
1130    }
1131
1132    dri2_dpy->own_dri_screen = true;
1133    return EGL_TRUE;
1134 }
1135
1136 EGLBoolean
1137 dri2_setup_extensions(_EGLDisplay *disp)
1138 {
1139    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1140    const struct dri2_extension_match *mandatory_core_extensions;
1141    const __DRIextension **extensions;
1142
1143    extensions = dri2_dpy->core->getExtensions(dri2_dpy->dri_screen);
1144
1145    if (dri2_dpy->image_driver || dri2_dpy->dri2)
1146       mandatory_core_extensions = dri2_core_extensions;
1147    else
1148       mandatory_core_extensions = swrast_core_extensions;
1149
1150    if (!dri2_bind_extensions(dri2_dpy, mandatory_core_extensions, extensions, false))
1151       return EGL_FALSE;
1152
1153 #ifdef HAVE_DRI3_MODIFIERS
1154    dri2_dpy->multibuffers_available =
1155       (dri2_dpy->dri3_major_version > 1 || (dri2_dpy->dri3_major_version == 1 &&
1156                                             dri2_dpy->dri3_minor_version >= 2)) &&
1157       (dri2_dpy->present_major_version > 1 || (dri2_dpy->present_major_version == 1 &&
1158                                                dri2_dpy->present_minor_version >= 2)) &&
1159       (dri2_dpy->image && dri2_dpy->image->base.version >= 15);
1160 #endif
1161
1162    dri2_bind_extensions(dri2_dpy, optional_core_extensions, extensions, true);
1163    return EGL_TRUE;
1164 }
1165
1166 /**
1167  * Called via eglInitialize(), drv->Initialize().
1168  *
1169  * This must be guaranteed to be called exactly once, even if eglInitialize is
1170  * called many times (without a eglTerminate in between).
1171  */
1172 static EGLBoolean
1173 dri2_initialize(_EGLDisplay *disp)
1174 {
1175    EGLBoolean ret = EGL_FALSE;
1176    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1177
1178    /* In the case where the application calls eglMakeCurrent(context1),
1179     * eglTerminate, then eglInitialize again (without a call to eglReleaseThread
1180     * or eglMakeCurrent(NULL) before that), dri2_dpy structure is still
1181     * initialized, as we need it to be able to free context1 correctly.
1182     *
1183     * It would probably be safest to forcibly release the display with
1184     * dri2_display_release, to make sure the display is reinitialized correctly.
1185     * However, the EGL spec states that we need to keep a reference to the
1186     * current context (so we cannot call dri2_make_current(NULL)), and therefore
1187     * we would leak context1 as we would be missing the old display connection
1188     * to free it up correctly.
1189     */
1190    if (dri2_dpy) {
1191       p_atomic_inc(&dri2_dpy->ref_count);
1192       return EGL_TRUE;
1193    }
1194
1195    loader_set_logger(_eglLog);
1196
1197    switch (disp->Platform) {
1198    case _EGL_PLATFORM_SURFACELESS:
1199       ret = dri2_initialize_surfaceless(disp);
1200       break;
1201    case _EGL_PLATFORM_DEVICE:
1202       ret = dri2_initialize_device(disp);
1203       break;
1204    case _EGL_PLATFORM_X11:
1205    case _EGL_PLATFORM_XCB:
1206       ret = dri2_initialize_x11(disp);
1207       break;
1208    case _EGL_PLATFORM_DRM:
1209       ret = dri2_initialize_drm(disp);
1210       break;
1211    case _EGL_PLATFORM_WAYLAND:
1212       ret = dri2_initialize_wayland(disp);
1213       break;
1214    case _EGL_PLATFORM_ANDROID:
1215       ret = dri2_initialize_android(disp);
1216       break;
1217
1218 #ifdef HAVE_TIZEN_PLATFORM
1219    case _EGL_PLATFORM_TIZEN:
1220       ret = dri2_initialize_tizen(disp);
1221       break;
1222 #endif
1223    default:
1224       unreachable("Callers ensure we cannot get here.");
1225       return EGL_FALSE;
1226    }
1227
1228    if (!ret)
1229       return EGL_FALSE;
1230
1231    dri2_dpy = dri2_egl_display(disp);
1232    p_atomic_inc(&dri2_dpy->ref_count);
1233
1234    mtx_init(&dri2_dpy->lock, mtx_plain);
1235
1236    return EGL_TRUE;
1237 }
1238
1239 /**
1240  * Decrement display reference count, and free up display if necessary.
1241  */
1242 static void
1243 dri2_display_release(_EGLDisplay *disp)
1244 {
1245    struct dri2_egl_display *dri2_dpy;
1246
1247    if (!disp)
1248       return;
1249
1250    dri2_dpy = dri2_egl_display(disp);
1251
1252    assert(dri2_dpy->ref_count > 0);
1253
1254    if (!p_atomic_dec_zero(&dri2_dpy->ref_count))
1255       return;
1256
1257    _eglCleanupDisplay(disp);
1258    dri2_display_destroy(disp);
1259 }
1260
1261 void
1262 dri2_display_destroy(_EGLDisplay *disp)
1263 {
1264    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1265
1266    if (dri2_dpy->own_dri_screen) {
1267       if (dri2_dpy->vtbl && dri2_dpy->vtbl->close_screen_notify)
1268          dri2_dpy->vtbl->close_screen_notify(disp);
1269       dri2_dpy->core->destroyScreen(dri2_dpy->dri_screen);
1270    }
1271    if (dri2_dpy->fd >= 0)
1272       close(dri2_dpy->fd);
1273
1274    /* Don't dlclose the driver when building with the address sanitizer, so you
1275     * get good symbols from the leak reports.
1276     */
1277 #if !BUILT_WITH_ASAN || defined(NDEBUG)
1278    if (dri2_dpy->driver)
1279       dlclose(dri2_dpy->driver);
1280 #endif
1281
1282    free(dri2_dpy->driver_name);
1283
1284 #ifdef HAVE_WAYLAND_PLATFORM
1285    free(dri2_dpy->device_name);
1286 #endif
1287
1288    switch (disp->Platform) {
1289    case _EGL_PLATFORM_X11:
1290       dri2_teardown_x11(dri2_dpy);
1291       break;
1292    case _EGL_PLATFORM_DRM:
1293       dri2_teardown_drm(dri2_dpy);
1294       break;
1295    case _EGL_PLATFORM_WAYLAND:
1296       dri2_teardown_wayland(dri2_dpy);
1297       break;
1298
1299 #ifdef HAVE_TIZEN_PLATFORM
1300    case _EGL_PLATFORM_TIZEN:
1301       dri2_teardown_tizen(disp);
1302       break;
1303 #endif
1304    default:
1305       /* TODO: add teardown for other platforms */
1306       break;
1307    }
1308
1309    /* The drm platform does not create the screen/driver_configs but reuses
1310     * the ones from the gbm device. As such the gbm itself is responsible
1311     * for the cleanup.
1312     */
1313    if (disp->Platform != _EGL_PLATFORM_DRM && dri2_dpy->driver_configs) {
1314       for (unsigned i = 0; dri2_dpy->driver_configs[i]; i++)
1315          free((__DRIconfig *) dri2_dpy->driver_configs[i]);
1316       free(dri2_dpy->driver_configs);
1317    }
1318    free(dri2_dpy);
1319    disp->DriverData = NULL;
1320 }
1321
1322 __DRIbuffer *
1323 dri2_egl_surface_alloc_local_buffer(struct dri2_egl_surface *dri2_surf,
1324                                     unsigned int att, unsigned int format)
1325 {
1326    struct dri2_egl_display *dri2_dpy =
1327       dri2_egl_display(dri2_surf->base.Resource.Display);
1328
1329    if (att >= ARRAY_SIZE(dri2_surf->local_buffers))
1330       return NULL;
1331
1332    if (!dri2_surf->local_buffers[att]) {
1333       dri2_surf->local_buffers[att] =
1334          dri2_dpy->dri2->allocateBuffer(dri2_dpy->dri_screen, att, format,
1335                                         dri2_surf->base.Width, dri2_surf->base.Height);
1336    }
1337
1338    return dri2_surf->local_buffers[att];
1339 }
1340
1341 void
1342 dri2_egl_surface_free_local_buffers(struct dri2_egl_surface *dri2_surf)
1343 {
1344    struct dri2_egl_display *dri2_dpy =
1345       dri2_egl_display(dri2_surf->base.Resource.Display);
1346
1347    for (int i = 0; i < ARRAY_SIZE(dri2_surf->local_buffers); i++) {
1348       if (dri2_surf->local_buffers[i]) {
1349          dri2_dpy->dri2->releaseBuffer(dri2_dpy->dri_screen,
1350                                        dri2_surf->local_buffers[i]);
1351          dri2_surf->local_buffers[i] = NULL;
1352       }
1353    }
1354 }
1355
1356 /**
1357  * Called via eglTerminate(), drv->Terminate().
1358  *
1359  * This must be guaranteed to be called exactly once, even if eglTerminate is
1360  * called many times (without a eglInitialize in between).
1361  */
1362 static EGLBoolean
1363 dri2_terminate(_EGLDisplay *disp)
1364 {
1365    /* Release all non-current Context/Surfaces. */
1366    _eglReleaseDisplayResources(disp);
1367
1368    dri2_display_release(disp);
1369
1370    return EGL_TRUE;
1371 }
1372
1373 /**
1374  * Set the error code after a call to
1375  * dri2_egl_display::dri2::createContextAttribs.
1376  */
1377 static void
1378 dri2_create_context_attribs_error(int dri_error)
1379 {
1380    EGLint egl_error;
1381
1382    switch (dri_error) {
1383    case __DRI_CTX_ERROR_SUCCESS:
1384       return;
1385
1386    case __DRI_CTX_ERROR_NO_MEMORY:
1387       egl_error = EGL_BAD_ALLOC;
1388       break;
1389
1390   /* From the EGL_KHR_create_context spec, section "Errors":
1391    *
1392    *   * If <config> does not support a client API context compatible
1393    *     with the requested API major and minor version, [...] context flags,
1394    *     and context reset notification behavior (for client API types where
1395    *     these attributes are supported), then an EGL_BAD_MATCH error is
1396    *     generated.
1397    *
1398    *   * If an OpenGL ES context is requested and the values for
1399    *     attributes EGL_CONTEXT_MAJOR_VERSION_KHR and
1400    *     EGL_CONTEXT_MINOR_VERSION_KHR specify an OpenGL ES version that
1401    *     is not defined, than an EGL_BAD_MATCH error is generated.
1402    *
1403    *   * If an OpenGL context is requested, the requested version is
1404    *     greater than 3.2, and the value for attribute
1405    *     EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR has no bits set; has any
1406    *     bits set other than EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR and
1407    *     EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR; has more than
1408    *     one of these bits set; or if the implementation does not support
1409    *     the requested profile, then an EGL_BAD_MATCH error is generated.
1410    */
1411    case __DRI_CTX_ERROR_BAD_API:
1412    case __DRI_CTX_ERROR_BAD_VERSION:
1413    case __DRI_CTX_ERROR_BAD_FLAG:
1414       egl_error = EGL_BAD_MATCH;
1415       break;
1416
1417   /* From the EGL_KHR_create_context spec, section "Errors":
1418    *
1419    *   * If an attribute name or attribute value in <attrib_list> is not
1420    *     recognized (including unrecognized bits in bitmask attributes),
1421    *     then an EGL_BAD_ATTRIBUTE error is generated."
1422    */
1423    case __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE:
1424    case __DRI_CTX_ERROR_UNKNOWN_FLAG:
1425       egl_error = EGL_BAD_ATTRIBUTE;
1426       break;
1427
1428    default:
1429       assert(!"unknown dri_error code");
1430       egl_error = EGL_BAD_MATCH;
1431       break;
1432    }
1433
1434    _eglError(egl_error, "dri2_create_context");
1435 }
1436
1437 static bool
1438 dri2_fill_context_attribs(struct dri2_egl_context *dri2_ctx,
1439                           struct dri2_egl_display *dri2_dpy,
1440                           uint32_t *ctx_attribs,
1441                           unsigned *num_attribs)
1442 {
1443    int pos = 0;
1444
1445    assert(*num_attribs >= NUM_ATTRIBS);
1446
1447    ctx_attribs[pos++] = __DRI_CTX_ATTRIB_MAJOR_VERSION;
1448    ctx_attribs[pos++] = dri2_ctx->base.ClientMajorVersion;
1449    ctx_attribs[pos++] = __DRI_CTX_ATTRIB_MINOR_VERSION;
1450    ctx_attribs[pos++] = dri2_ctx->base.ClientMinorVersion;
1451
1452    if (dri2_ctx->base.Flags != 0) {
1453       /* If the implementation doesn't support the __DRI2_ROBUSTNESS
1454        * extension, don't even try to send it the robust-access flag.
1455        * It may explode.  Instead, generate the required EGL error here.
1456        */
1457       if ((dri2_ctx->base.Flags & EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR) != 0
1458             && !dri2_dpy->robustness) {
1459          _eglError(EGL_BAD_MATCH, "eglCreateContext");
1460          return false;
1461       }
1462
1463       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_FLAGS;
1464       ctx_attribs[pos++] = dri2_ctx->base.Flags;
1465    }
1466
1467    if (dri2_ctx->base.ResetNotificationStrategy != EGL_NO_RESET_NOTIFICATION_KHR) {
1468       /* If the implementation doesn't support the __DRI2_ROBUSTNESS
1469        * extension, don't even try to send it a reset strategy.  It may
1470        * explode.  Instead, generate the required EGL error here.
1471        */
1472       if (!dri2_dpy->robustness) {
1473          _eglError(EGL_BAD_CONFIG, "eglCreateContext");
1474          return false;
1475       }
1476
1477       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_RESET_STRATEGY;
1478       ctx_attribs[pos++] = __DRI_CTX_RESET_LOSE_CONTEXT;
1479    }
1480
1481    if (dri2_ctx->base.ContextPriority != EGL_CONTEXT_PRIORITY_MEDIUM_IMG) {
1482       unsigned val;
1483
1484       switch (dri2_ctx->base.ContextPriority) {
1485       case EGL_CONTEXT_PRIORITY_HIGH_IMG:
1486          val = __DRI_CTX_PRIORITY_HIGH;
1487          break;
1488       case EGL_CONTEXT_PRIORITY_MEDIUM_IMG:
1489          val = __DRI_CTX_PRIORITY_MEDIUM;
1490          break;
1491       case EGL_CONTEXT_PRIORITY_LOW_IMG:
1492          val = __DRI_CTX_PRIORITY_LOW;
1493          break;
1494       default:
1495          _eglError(EGL_BAD_CONFIG, "eglCreateContext");
1496          return false;
1497       }
1498
1499       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_PRIORITY;
1500       ctx_attribs[pos++] = val;
1501    }
1502
1503    if (dri2_ctx->base.ReleaseBehavior == EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR) {
1504       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_RELEASE_BEHAVIOR;
1505       ctx_attribs[pos++] = __DRI_CTX_RELEASE_BEHAVIOR_NONE;
1506    }
1507
1508    if (dri2_ctx->base.NoError) {
1509       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_NO_ERROR;
1510       ctx_attribs[pos++] = true;
1511    }
1512
1513    if (dri2_ctx->base.Protected) {
1514       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_PROTECTED;
1515       ctx_attribs[pos++] = true;
1516    }
1517
1518    *num_attribs = pos;
1519
1520    return true;
1521 }
1522
1523 /**
1524  * Called via eglCreateContext(), drv->CreateContext().
1525  */
1526 static _EGLContext *
1527 dri2_create_context(_EGLDisplay *disp, _EGLConfig *conf,
1528                     _EGLContext *share_list, const EGLint *attrib_list)
1529 {
1530    struct dri2_egl_context *dri2_ctx;
1531    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1532    struct dri2_egl_context *dri2_ctx_shared = dri2_egl_context(share_list);
1533    __DRIcontext *shared =
1534       dri2_ctx_shared ? dri2_ctx_shared->dri_context : NULL;
1535    struct dri2_egl_config *dri2_config = dri2_egl_config(conf);
1536    const __DRIconfig *dri_config;
1537    int api;
1538    unsigned error;
1539    unsigned num_attribs = NUM_ATTRIBS;
1540    uint32_t ctx_attribs[NUM_ATTRIBS];
1541
1542    dri2_ctx = malloc(sizeof *dri2_ctx);
1543    if (!dri2_ctx) {
1544       dri2_egl_error_unlock(dri2_dpy, EGL_BAD_ALLOC, "eglCreateContext");
1545       return NULL;
1546    }
1547
1548    if (!_eglInitContext(&dri2_ctx->base, disp, conf, attrib_list))
1549       goto cleanup;
1550
1551    /* The EGL_EXT_create_context_robustness spec says:
1552     *
1553     *    "Add to the eglCreateContext context creation errors: [...]
1554     *
1555     *     * If the reset notification behavior of <share_context> and the
1556     *       newly created context are different then an EGL_BAD_MATCH error is
1557     *       generated."
1558     */
1559    if (share_list && share_list->ResetNotificationStrategy !=
1560                      dri2_ctx->base.ResetNotificationStrategy) {
1561       _eglError(EGL_BAD_MATCH, "eglCreateContext");
1562       goto cleanup;
1563    }
1564
1565    /* The EGL_KHR_create_context_no_error spec says:
1566     *
1567     *    "BAD_MATCH is generated if the value of EGL_CONTEXT_OPENGL_NO_ERROR_KHR
1568     *    used to create <share_context> does not match the value of
1569     *    EGL_CONTEXT_OPENGL_NO_ERROR_KHR for the context being created."
1570     */
1571    if (share_list && share_list->NoError != dri2_ctx->base.NoError) {
1572       _eglError(EGL_BAD_MATCH, "eglCreateContext");
1573       goto cleanup;
1574    }
1575
1576    switch (dri2_ctx->base.ClientAPI) {
1577    case EGL_OPENGL_ES_API:
1578       switch (dri2_ctx->base.ClientMajorVersion) {
1579       case 1:
1580          api = __DRI_API_GLES;
1581          break;
1582       case 2:
1583          api = __DRI_API_GLES2;
1584          break;
1585       case 3:
1586          api = __DRI_API_GLES3;
1587          break;
1588       default:
1589          _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
1590          goto cleanup;
1591       }
1592       break;
1593    case EGL_OPENGL_API:
1594       if ((dri2_ctx->base.ClientMajorVersion >= 4
1595            || (dri2_ctx->base.ClientMajorVersion == 3
1596                && dri2_ctx->base.ClientMinorVersion >= 2))
1597           && dri2_ctx->base.Profile == EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR)
1598          api = __DRI_API_OPENGL_CORE;
1599       else if (dri2_ctx->base.ClientMajorVersion == 3 &&
1600                dri2_ctx->base.ClientMinorVersion == 1)
1601          api = __DRI_API_OPENGL_CORE;
1602       else
1603          api = __DRI_API_OPENGL;
1604       break;
1605    default:
1606       _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
1607       goto cleanup;
1608    }
1609
1610    if (conf != NULL) {
1611       /* The config chosen here isn't necessarily
1612        * used for surfaces later.
1613        * A pixmap surface will use the single config.
1614        * This opportunity depends on disabling the
1615        * doubleBufferMode check in
1616        * src/mesa/main/context.c:check_compatible()
1617        */
1618       if (dri2_config->dri_config[1][0])
1619          dri_config = dri2_config->dri_config[1][0];
1620       else
1621          dri_config = dri2_config->dri_config[0][0];
1622    }
1623    else
1624       dri_config = NULL;
1625
1626    if (!dri2_fill_context_attribs(dri2_ctx, dri2_dpy, ctx_attribs,
1627                                   &num_attribs))
1628       goto cleanup;
1629
1630    if (dri2_dpy->image_driver) {
1631       dri2_ctx->dri_context =
1632          dri2_dpy->image_driver->createContextAttribs(dri2_dpy->dri_screen,
1633                                                       api,
1634                                                       dri_config,
1635                                                       shared,
1636                                                       num_attribs / 2,
1637                                                       ctx_attribs,
1638                                                       & error,
1639                                                       dri2_ctx);
1640       dri2_create_context_attribs_error(error);
1641    } else if (dri2_dpy->dri2) {
1642       if (dri2_dpy->dri2->base.version >= 3) {
1643          dri2_ctx->dri_context =
1644             dri2_dpy->dri2->createContextAttribs(dri2_dpy->dri_screen,
1645                                                  api,
1646                                                  dri_config,
1647                                                  shared,
1648                                                  num_attribs / 2,
1649                                                  ctx_attribs,
1650                                                  & error,
1651                                                  dri2_ctx);
1652          dri2_create_context_attribs_error(error);
1653       } else {
1654          dri2_ctx->dri_context =
1655             dri2_dpy->dri2->createNewContextForAPI(dri2_dpy->dri_screen,
1656                                                    api,
1657                                                    dri_config,
1658                                                    shared,
1659                                                    dri2_ctx);
1660       }
1661    } else {
1662       assert(dri2_dpy->swrast);
1663       if (dri2_dpy->swrast->base.version >= 3) {
1664          dri2_ctx->dri_context =
1665             dri2_dpy->swrast->createContextAttribs(dri2_dpy->dri_screen,
1666                                                    api,
1667                                                    dri_config,
1668                                                    shared,
1669                                                    num_attribs / 2,
1670                                                    ctx_attribs,
1671                                                    & error,
1672                                                    dri2_ctx);
1673          dri2_create_context_attribs_error(error);
1674       } else {
1675          dri2_ctx->dri_context =
1676             dri2_dpy->swrast->createNewContextForAPI(dri2_dpy->dri_screen,
1677                                                      api,
1678                                                      dri_config,
1679                                                      shared,
1680                                                      dri2_ctx);
1681       }
1682    }
1683
1684    if (!dri2_ctx->dri_context)
1685       goto cleanup;
1686
1687    mtx_unlock(&dri2_dpy->lock);
1688
1689    return &dri2_ctx->base;
1690
1691  cleanup:
1692    mtx_unlock(&dri2_dpy->lock);
1693    free(dri2_ctx);
1694    return NULL;
1695 }
1696
1697 /**
1698  * Called via eglDestroyContext(), drv->DestroyContext().
1699  */
1700 static EGLBoolean
1701 dri2_destroy_context(_EGLDisplay *disp, _EGLContext *ctx)
1702 {
1703    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1704    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1705
1706    if (_eglPutContext(ctx)) {
1707       dri2_dpy->core->destroyContext(dri2_ctx->dri_context);
1708       free(dri2_ctx);
1709    }
1710
1711    return EGL_TRUE;
1712 }
1713
1714 EGLBoolean
1715 dri2_init_surface(_EGLSurface *surf, _EGLDisplay *disp, EGLint type,
1716         _EGLConfig *conf, const EGLint *attrib_list,
1717         EGLBoolean enable_out_fence, void *native_surface)
1718 {
1719    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1720    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1721
1722    dri2_surf->out_fence_fd = -1;
1723    dri2_surf->enable_out_fence = false;
1724    if (dri2_dpy->fence && dri2_dpy->fence->base.version >= 2 &&
1725        dri2_dpy->fence->get_capabilities &&
1726        (dri2_dpy->fence->get_capabilities(dri2_dpy->dri_screen) &
1727         __DRI_FENCE_CAP_NATIVE_FD)) {
1728       dri2_surf->enable_out_fence = enable_out_fence;
1729    }
1730
1731    return _eglInitSurface(surf, disp, type, conf, attrib_list, native_surface);
1732 }
1733
1734 static void
1735 dri2_surface_set_out_fence_fd( _EGLSurface *surf, int fence_fd)
1736 {
1737    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1738
1739    if (dri2_surf->out_fence_fd >= 0)
1740       close(dri2_surf->out_fence_fd);
1741
1742    dri2_surf->out_fence_fd = fence_fd;
1743 }
1744
1745 void
1746 dri2_fini_surface(_EGLSurface *surf)
1747 {
1748    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1749
1750    dri2_surface_set_out_fence_fd(surf, -1);
1751    dri2_surf->enable_out_fence = false;
1752 }
1753
1754 static EGLBoolean
1755 dri2_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
1756 {
1757    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1758    EGLBoolean ret = EGL_TRUE;
1759
1760    if (_eglPutSurface(surf))
1761       ret = dri2_dpy->vtbl->destroy_surface(disp, surf);
1762
1763    return ret;
1764 }
1765
1766 static void
1767 dri2_surf_update_fence_fd(_EGLContext *ctx,
1768                           _EGLDisplay *disp, _EGLSurface *surf)
1769 {
1770    __DRIcontext *dri_ctx = dri2_egl_context(ctx)->dri_context;
1771    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1772    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1773    int fence_fd = -1;
1774    void *fence;
1775
1776    if (!dri2_surf->enable_out_fence)
1777       return;
1778
1779    fence = dri2_dpy->fence->create_fence_fd(dri_ctx, -1);
1780    if (fence) {
1781       fence_fd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
1782                                                fence);
1783       dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, fence);
1784    }
1785    dri2_surface_set_out_fence_fd(surf, fence_fd);
1786 }
1787
1788 EGLBoolean
1789 dri2_create_drawable(struct dri2_egl_display *dri2_dpy,
1790                      const __DRIconfig *config,
1791                      struct dri2_egl_surface *dri2_surf,
1792                      void *loaderPrivate)
1793 {
1794    if (dri2_dpy->kopper) {
1795       dri2_surf->dri_drawable =
1796           dri2_dpy->kopper->createNewDrawable(dri2_dpy->dri_screen, config, loaderPrivate,
1797                                               dri2_surf->base.Type == EGL_PBUFFER_BIT ||
1798                                               dri2_surf->base.Type == EGL_PIXMAP_BIT);
1799    } else {
1800       __DRIcreateNewDrawableFunc createNewDrawable;
1801       if (dri2_dpy->image_driver)
1802          createNewDrawable = dri2_dpy->image_driver->createNewDrawable;
1803       else if (dri2_dpy->dri2)
1804          createNewDrawable = dri2_dpy->dri2->createNewDrawable;
1805       else if (dri2_dpy->swrast)
1806          createNewDrawable = dri2_dpy->swrast->createNewDrawable;
1807       else
1808          return _eglError(EGL_BAD_ALLOC, "no createNewDrawable");
1809
1810       dri2_surf->dri_drawable = createNewDrawable(dri2_dpy->dri_screen,
1811                                                   config, loaderPrivate);
1812    }
1813    if (dri2_surf->dri_drawable == NULL)
1814       return _eglError(EGL_BAD_ALLOC, "createNewDrawable");
1815
1816    return EGL_TRUE;
1817 }
1818
1819 /**
1820  * Called via eglMakeCurrent(), drv->MakeCurrent().
1821  */
1822 static EGLBoolean
1823 dri2_make_current(_EGLDisplay *disp, _EGLSurface *dsurf,
1824                   _EGLSurface *rsurf, _EGLContext *ctx)
1825 {
1826    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1827    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1828    _EGLDisplay *old_disp = NULL;
1829    struct dri2_egl_display *old_dri2_dpy = NULL;
1830    _EGLContext *old_ctx;
1831    _EGLSurface *old_dsurf, *old_rsurf;
1832    _EGLSurface *tmp_dsurf, *tmp_rsurf;
1833    __DRIdrawable *ddraw, *rdraw;
1834    __DRIcontext *cctx;
1835    EGLint egl_error = EGL_SUCCESS;
1836
1837    if (!dri2_dpy)
1838       return _eglError(EGL_NOT_INITIALIZED, "eglMakeCurrent");
1839
1840    /* make new bindings, set the EGL error otherwise */
1841    if (!_eglBindContext(ctx, dsurf, rsurf, &old_ctx, &old_dsurf, &old_rsurf))
1842       return EGL_FALSE;
1843
1844    if (old_ctx == ctx && old_dsurf == dsurf && old_rsurf == rsurf) {
1845       _eglPutSurface(old_dsurf);
1846       _eglPutSurface(old_rsurf);
1847       _eglPutContext(old_ctx);
1848       return EGL_TRUE;
1849    }
1850
1851    if (old_ctx) {
1852       __DRIcontext *old_cctx = dri2_egl_context(old_ctx)->dri_context;
1853       old_disp = old_ctx->Resource.Display;
1854       old_dri2_dpy = dri2_egl_display(old_disp);
1855
1856       /* Disable shared buffer mode */
1857       if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1858           old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1859          old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, false);
1860       }
1861
1862       old_dri2_dpy->core->unbindContext(old_cctx);
1863
1864       if (old_dsurf)
1865          dri2_surf_update_fence_fd(old_ctx, old_disp, old_dsurf);
1866    }
1867
1868    ddraw = (dsurf) ? dri2_dpy->vtbl->get_dri_drawable(dsurf) : NULL;
1869    rdraw = (rsurf) ? dri2_dpy->vtbl->get_dri_drawable(rsurf) : NULL;
1870    cctx = (dri2_ctx) ? dri2_ctx->dri_context : NULL;
1871
1872    if (cctx) {
1873       if (!dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1874          _EGLContext *tmp_ctx;
1875
1876          /* dri2_dpy->core->bindContext failed. We cannot tell for sure why, but
1877           * setting the error to EGL_BAD_MATCH is surely better than leaving it
1878           * as EGL_SUCCESS.
1879           */
1880          egl_error = EGL_BAD_MATCH;
1881
1882          /* undo the previous _eglBindContext */
1883          _eglBindContext(old_ctx, old_dsurf, old_rsurf, &ctx, &tmp_dsurf, &tmp_rsurf);
1884          assert(&dri2_ctx->base == ctx &&
1885                 tmp_dsurf == dsurf &&
1886                 tmp_rsurf == rsurf);
1887
1888          _eglPutSurface(dsurf);
1889          _eglPutSurface(rsurf);
1890          _eglPutContext(ctx);
1891
1892          _eglPutSurface(old_dsurf);
1893          _eglPutSurface(old_rsurf);
1894          _eglPutContext(old_ctx);
1895
1896          ddraw = (old_dsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_dsurf) : NULL;
1897          rdraw = (old_rsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_rsurf) : NULL;
1898          cctx = (old_ctx) ? dri2_egl_context(old_ctx)->dri_context : NULL;
1899
1900          /* undo the previous dri2_dpy->core->unbindContext */
1901          if (dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1902             if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1903                 old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1904                old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, true);
1905             }
1906
1907             return _eglError(egl_error, "eglMakeCurrent");
1908          }
1909
1910          /* We cannot restore the same state as it was before calling
1911           * eglMakeCurrent() and the spec isn't clear about what to do. We
1912           * can prevent EGL from calling into the DRI driver with no DRI
1913           * context bound.
1914           */
1915          dsurf = rsurf = NULL;
1916          ctx = NULL;
1917
1918          _eglBindContext(ctx, dsurf, rsurf, &tmp_ctx, &tmp_dsurf, &tmp_rsurf);
1919          assert(tmp_ctx == old_ctx && tmp_dsurf == old_dsurf &&
1920                 tmp_rsurf == old_rsurf);
1921
1922          _eglLog(_EGL_WARNING, "DRI2: failed to rebind the previous context");
1923       } else {
1924          /* dri2_dpy->core->bindContext succeeded, so take a reference on the
1925           * dri2_dpy. This prevents dri2_dpy from being reinitialized when a
1926           * EGLDisplay is terminated and then initialized again while a
1927           * context is still bound. See dri2_initialize() for a more in depth
1928           * explanation. */
1929          p_atomic_inc(&dri2_dpy->ref_count);
1930       }
1931    }
1932
1933    dri2_destroy_surface(disp, old_dsurf);
1934    dri2_destroy_surface(disp, old_rsurf);
1935
1936    if (old_ctx) {
1937       dri2_destroy_context(disp, old_ctx);
1938       dri2_display_release(old_disp);
1939    }
1940
1941    if (egl_error != EGL_SUCCESS)
1942       return _eglError(egl_error, "eglMakeCurrent");
1943
1944    if (dsurf && _eglSurfaceHasMutableRenderBuffer(dsurf) &&
1945        dri2_dpy->vtbl->set_shared_buffer_mode) {
1946       /* Always update the shared buffer mode. This is obviously needed when
1947        * the active EGL_RENDER_BUFFER is EGL_SINGLE_BUFFER. When
1948        * EGL_RENDER_BUFFER is EGL_BACK_BUFFER, the update protects us in the
1949        * case where external non-EGL API may have changed window's shared
1950        * buffer mode since we last saw it.
1951        */
1952       bool mode = (dsurf->ActiveRenderBuffer == EGL_SINGLE_BUFFER);
1953       dri2_dpy->vtbl->set_shared_buffer_mode(disp, dsurf, mode);
1954    }
1955
1956    return EGL_TRUE;
1957 }
1958
1959 __DRIdrawable *
1960 dri2_surface_get_dri_drawable(_EGLSurface *surf)
1961 {
1962    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1963
1964    return dri2_surf->dri_drawable;
1965 }
1966
1967 /*
1968  * Called from eglGetProcAddress() via drv->GetProcAddress().
1969  */
1970 static _EGLProc
1971 dri2_get_proc_address(const char *procname)
1972 {
1973    return _glapi_get_proc_address(procname);
1974 }
1975
1976 static _EGLSurface*
1977 dri2_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
1978                            void *native_window, const EGLint *attrib_list)
1979 {
1980    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1981    _EGLSurface *ret =
1982          dri2_dpy->vtbl->create_window_surface(disp, conf, native_window,
1983                                                attrib_list);
1984    mtx_unlock(&dri2_dpy->lock);
1985    return ret;
1986 }
1987
1988 static _EGLSurface*
1989 dri2_create_pixmap_surface(_EGLDisplay *disp, _EGLConfig *conf,
1990                            void *native_pixmap, const EGLint *attrib_list)
1991 {
1992    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1993    _EGLSurface *ret = NULL;
1994
1995    if (dri2_dpy->vtbl->create_pixmap_surface)
1996       ret = dri2_dpy->vtbl->create_pixmap_surface(disp, conf, native_pixmap,
1997                                                   attrib_list);
1998
1999    mtx_unlock(&dri2_dpy->lock);
2000
2001    return ret;
2002 }
2003
2004 static _EGLSurface*
2005 dri2_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
2006                             const EGLint *attrib_list)
2007 {
2008    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2009    _EGLSurface *ret = NULL;
2010
2011    if (dri2_dpy->vtbl->create_pbuffer_surface)
2012       ret = dri2_dpy->vtbl->create_pbuffer_surface(disp, conf, attrib_list);
2013
2014    mtx_unlock(&dri2_dpy->lock);
2015
2016    return ret;
2017 }
2018
2019 static EGLBoolean
2020 dri2_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
2021 {
2022    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2023    EGLBoolean ret = EGL_TRUE;
2024
2025    if (dri2_dpy->vtbl->swap_interval)
2026       ret = dri2_dpy->vtbl->swap_interval(disp, surf, interval);
2027
2028    mtx_unlock(&dri2_dpy->lock);
2029
2030    return ret;
2031 }
2032
2033 /**
2034  * Asks the client API to flush any rendering to the drawable so that we can
2035  * do our swapbuffers.
2036  */
2037 void
2038 dri2_flush_drawable_for_swapbuffers(_EGLDisplay *disp, _EGLSurface *draw)
2039 {
2040    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2041    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(draw);
2042
2043    if (dri2_dpy->flush) {
2044       if (dri2_dpy->flush->base.version >= 4) {
2045          /* We know there's a current context because:
2046           *
2047           *     "If surface is not bound to the calling thread’s current
2048           *      context, an EGL_BAD_SURFACE error is generated."
2049          */
2050          _EGLContext *ctx = _eglGetCurrentContext();
2051          struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2052
2053          /* From the EGL 1.4 spec (page 52):
2054           *
2055           *     "The contents of ancillary buffers are always undefined
2056           *      after calling eglSwapBuffers."
2057           */
2058          dri2_dpy->flush->flush_with_flags(dri2_ctx->dri_context,
2059                                            dri_drawable,
2060                                            __DRI2_FLUSH_DRAWABLE |
2061                                            __DRI2_FLUSH_INVALIDATE_ANCILLARY,
2062                                            __DRI2_THROTTLE_SWAPBUFFER);
2063       } else {
2064          dri2_dpy->flush->flush(dri_drawable);
2065       }
2066    }
2067 }
2068
2069 static EGLBoolean
2070 dri2_swap_buffers(_EGLDisplay *disp, _EGLSurface *surf)
2071 {
2072    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2073    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2074    _EGLContext *ctx = _eglGetCurrentContext();
2075    EGLBoolean ret;
2076
2077    if (ctx && surf)
2078       dri2_surf_update_fence_fd(ctx, disp, surf);
2079    ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2080
2081    /* SwapBuffers marks the end of the frame; reset the damage region for
2082     * use again next time.
2083     */
2084    if (ret && dri2_dpy->buffer_damage &&
2085        dri2_dpy->buffer_damage->set_damage_region)
2086       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2087
2088    return ret;
2089 }
2090
2091 static EGLBoolean
2092 dri2_swap_buffers_with_damage(_EGLDisplay *disp, _EGLSurface *surf,
2093                               const EGLint *rects, EGLint n_rects)
2094 {
2095    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2096    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2097    _EGLContext *ctx = _eglGetCurrentContext();
2098    EGLBoolean ret;
2099
2100    if (ctx && surf)
2101       dri2_surf_update_fence_fd(ctx, disp, surf);
2102    if (dri2_dpy->vtbl->swap_buffers_with_damage)
2103       ret = dri2_dpy->vtbl->swap_buffers_with_damage(disp, surf,
2104                                                      rects, n_rects);
2105    else
2106       ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2107
2108    /* SwapBuffers marks the end of the frame; reset the damage region for
2109     * use again next time.
2110     */
2111    if (ret && dri2_dpy->buffer_damage &&
2112        dri2_dpy->buffer_damage->set_damage_region)
2113       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2114
2115    return ret;
2116 }
2117
2118 static EGLBoolean
2119 dri2_swap_buffers_region(_EGLDisplay *disp, _EGLSurface *surf,
2120                          EGLint numRects, const EGLint *rects)
2121 {
2122    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2123    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2124    EGLBoolean ret;
2125
2126    if (!dri2_dpy->vtbl->swap_buffers_region)
2127       return EGL_FALSE;
2128    ret = dri2_dpy->vtbl->swap_buffers_region(disp, surf, numRects, rects);
2129
2130    /* SwapBuffers marks the end of the frame; reset the damage region for
2131     * use again next time.
2132     */
2133    if (ret && dri2_dpy->buffer_damage &&
2134        dri2_dpy->buffer_damage->set_damage_region)
2135       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2136
2137    return ret;
2138 }
2139
2140 static EGLBoolean
2141 dri2_set_damage_region(_EGLDisplay *disp, _EGLSurface *surf,
2142                        EGLint *rects, EGLint n_rects)
2143 {
2144    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2145    __DRIdrawable *drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2146
2147    if (!dri2_dpy->buffer_damage || !dri2_dpy->buffer_damage->set_damage_region) {
2148       mtx_unlock(&dri2_dpy->lock);
2149       return EGL_FALSE;
2150    }
2151
2152    dri2_dpy->buffer_damage->set_damage_region(drawable, n_rects, rects);
2153    mtx_unlock(&dri2_dpy->lock);
2154    return EGL_TRUE;
2155 }
2156
2157 static EGLBoolean
2158 dri2_post_sub_buffer(_EGLDisplay *disp, _EGLSurface *surf,
2159                      EGLint x, EGLint y, EGLint width, EGLint height)
2160 {
2161    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2162    EGLBoolean ret = EGL_FALSE;
2163
2164    if (dri2_dpy->vtbl->post_sub_buffer)
2165       ret = dri2_dpy->vtbl->post_sub_buffer(disp, surf, x, y, width, height);
2166
2167    mtx_unlock(&dri2_dpy->lock);
2168
2169    return ret;
2170 }
2171
2172 static EGLBoolean
2173 dri2_copy_buffers(_EGLDisplay *disp, _EGLSurface *surf, void *native_pixmap_target)
2174 {
2175    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2176    if (!dri2_dpy->vtbl->copy_buffers)
2177       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_NATIVE_PIXMAP, "no support for native pixmaps");
2178    EGLBoolean ret = dri2_dpy->vtbl->copy_buffers(disp, surf, native_pixmap_target);
2179    mtx_unlock(&dri2_dpy->lock);
2180    return ret;
2181 }
2182
2183 static EGLint
2184 dri2_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surf)
2185 {
2186    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2187    if (!dri2_dpy->vtbl->query_buffer_age)
2188       return 0;
2189    return dri2_dpy->vtbl->query_buffer_age(disp, surf);
2190 }
2191
2192 static EGLBoolean
2193 dri2_wait_client(_EGLDisplay *disp, _EGLContext *ctx)
2194 {
2195    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2196    _EGLSurface *surf = ctx->DrawSurface;
2197    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2198
2199    /* FIXME: If EGL allows frontbuffer rendering for window surfaces,
2200     * we need to copy fake to real here.*/
2201
2202    if (dri2_dpy->flush != NULL)
2203       dri2_dpy->flush->flush(dri_drawable);
2204
2205    return EGL_TRUE;
2206 }
2207
2208 static EGLBoolean
2209 dri2_wait_native(EGLint engine)
2210 {
2211    if (engine != EGL_CORE_NATIVE_ENGINE)
2212       return _eglError(EGL_BAD_PARAMETER, "eglWaitNative");
2213    /* glXWaitX(); */
2214
2215    return EGL_TRUE;
2216 }
2217
2218 static EGLBoolean
2219 dri2_bind_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2220 {
2221    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2222    struct dri2_egl_context *dri2_ctx;
2223    _EGLContext *ctx;
2224    GLint format, target;
2225    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2226
2227    ctx = _eglGetCurrentContext();
2228    dri2_ctx = dri2_egl_context(ctx);
2229
2230    if (!_eglBindTexImage(disp, surf, buffer)) {
2231       mtx_unlock(&dri2_dpy->lock);
2232       return EGL_FALSE;
2233    }
2234
2235    switch (surf->TextureFormat) {
2236    case EGL_TEXTURE_RGB:
2237       format = __DRI_TEXTURE_FORMAT_RGB;
2238       break;
2239    case EGL_TEXTURE_RGBA:
2240       format = __DRI_TEXTURE_FORMAT_RGBA;
2241       break;
2242    default:
2243       assert(!"Unexpected texture format in dri2_bind_tex_image()");
2244       format = __DRI_TEXTURE_FORMAT_RGBA;
2245    }
2246
2247    switch (surf->TextureTarget) {
2248    case EGL_TEXTURE_2D:
2249       target = GL_TEXTURE_2D;
2250       break;
2251    default:
2252       target = GL_TEXTURE_2D;
2253       assert(!"Unexpected texture target in dri2_bind_tex_image()");
2254    }
2255
2256    dri2_dpy->tex_buffer->setTexBuffer2(dri2_ctx->dri_context,
2257                                        target, format,
2258                                        dri_drawable);
2259
2260    mtx_unlock(&dri2_dpy->lock);
2261
2262    return EGL_TRUE;
2263 }
2264
2265 static EGLBoolean
2266 dri2_release_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2267 {
2268    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2269    struct dri2_egl_context *dri2_ctx;
2270    _EGLContext *ctx;
2271    GLint  target;
2272    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2273
2274    ctx = _eglGetCurrentContext();
2275    dri2_ctx = dri2_egl_context(ctx);
2276
2277    if (!_eglReleaseTexImage(disp, surf, buffer)) {
2278       mtx_unlock(&dri2_dpy->lock);
2279       return EGL_FALSE;
2280    }
2281
2282    switch (surf->TextureTarget) {
2283    case EGL_TEXTURE_2D:
2284       target = GL_TEXTURE_2D;
2285       break;
2286    default:
2287       assert(!"missing texture target");
2288    }
2289
2290    if (dri2_dpy->tex_buffer->base.version >= 3 &&
2291        dri2_dpy->tex_buffer->releaseTexBuffer != NULL) {
2292       dri2_dpy->tex_buffer->releaseTexBuffer(dri2_ctx->dri_context,
2293                                              target, dri_drawable);
2294    }
2295
2296    mtx_unlock(&dri2_dpy->lock);
2297
2298    return EGL_TRUE;
2299 }
2300
2301 static _EGLImage*
2302 dri2_create_image(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
2303                   EGLClientBuffer buffer, const EGLint *attr_list)
2304 {
2305    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2306    _EGLImage *ret = dri2_dpy->vtbl->create_image(disp, ctx, target, buffer,
2307                                                  attr_list);
2308    mtx_unlock(&dri2_dpy->lock);
2309    return ret;
2310 }
2311
2312 _EGLImage *
2313 dri2_create_image_from_dri(_EGLDisplay *disp, __DRIimage *dri_image)
2314 {
2315    struct dri2_egl_image *dri2_img;
2316
2317    if (dri_image == NULL) {
2318       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2319       return NULL;
2320    }
2321
2322    dri2_img = malloc(sizeof *dri2_img);
2323    if (!dri2_img) {
2324       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2325       return NULL;
2326    }
2327
2328    _eglInitImage(&dri2_img->base, disp);
2329
2330    dri2_img->dri_image = dri_image;
2331
2332    return &dri2_img->base;
2333 }
2334
2335 /**
2336  * Translate a DRI Image extension error code into an EGL error code.
2337  */
2338 static EGLint
2339 egl_error_from_dri_image_error(int dri_error)
2340 {
2341    switch (dri_error) {
2342    case __DRI_IMAGE_ERROR_SUCCESS:
2343       return EGL_SUCCESS;
2344    case __DRI_IMAGE_ERROR_BAD_ALLOC:
2345       return EGL_BAD_ALLOC;
2346    case __DRI_IMAGE_ERROR_BAD_MATCH:
2347       return EGL_BAD_MATCH;
2348    case __DRI_IMAGE_ERROR_BAD_PARAMETER:
2349       return EGL_BAD_PARAMETER;
2350    case __DRI_IMAGE_ERROR_BAD_ACCESS:
2351       return EGL_BAD_ACCESS;
2352    default:
2353       assert(!"unknown dri_error code");
2354       return EGL_BAD_ALLOC;
2355    }
2356 }
2357
2358 static _EGLImage *
2359 dri2_create_image_khr_renderbuffer(_EGLDisplay *disp, _EGLContext *ctx,
2360                                    EGLClientBuffer buffer,
2361                                    const EGLint *attr_list)
2362 {
2363    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2364    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2365    GLuint renderbuffer = (GLuint) (uintptr_t) buffer;
2366    __DRIimage *dri_image;
2367
2368    if (renderbuffer == 0) {
2369       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2370       return EGL_NO_IMAGE_KHR;
2371    }
2372
2373    if (!disp->Extensions.KHR_gl_renderbuffer_image) {
2374       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2375       return EGL_NO_IMAGE_KHR;
2376    }
2377
2378    if (dri2_dpy->image->base.version >= 17 &&
2379        dri2_dpy->image->createImageFromRenderbuffer2) {
2380       unsigned error = ~0;
2381
2382       dri_image = dri2_dpy->image->createImageFromRenderbuffer2(
2383                dri2_ctx->dri_context, renderbuffer, NULL, &error);
2384
2385       assert(!!dri_image == (error == __DRI_IMAGE_ERROR_SUCCESS));
2386
2387       if (!dri_image) {
2388          _eglError(egl_error_from_dri_image_error(error), "dri2_create_image_khr");
2389          return EGL_NO_IMAGE_KHR;
2390       }
2391    } else {
2392       dri_image = dri2_dpy->image->createImageFromRenderbuffer(
2393                dri2_ctx->dri_context, renderbuffer, NULL);
2394       if (!dri_image) {
2395          _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2396          return EGL_NO_IMAGE_KHR;
2397       }
2398    }
2399
2400    return dri2_create_image_from_dri(disp, dri_image);
2401 }
2402
2403 #ifdef HAVE_WAYLAND_PLATFORM
2404
2405 /* This structure describes how a wl_buffer maps to one or more
2406  * __DRIimages.  A wl_drm_buffer stores the wl_drm format code and the
2407  * offsets and strides of the planes in the buffer.  This table maps a
2408  * wl_drm format code to a description of the planes in the buffer
2409  * that lets us create a __DRIimage for each of the planes. */
2410
2411 static const struct wl_drm_components_descriptor {
2412    uint32_t dri_components;
2413    EGLint components;
2414    int nplanes;
2415 } wl_drm_components[] = {
2416    { __DRI_IMAGE_COMPONENTS_RGB, EGL_TEXTURE_RGB, 1 },
2417    { __DRI_IMAGE_COMPONENTS_RGBA, EGL_TEXTURE_RGBA, 1 },
2418    { __DRI_IMAGE_COMPONENTS_Y_U_V, EGL_TEXTURE_Y_U_V_WL, 3 },
2419    { __DRI_IMAGE_COMPONENTS_Y_UV, EGL_TEXTURE_Y_UV_WL, 2 },
2420    { __DRI_IMAGE_COMPONENTS_Y_XUXV, EGL_TEXTURE_Y_XUXV_WL, 2 },
2421 };
2422
2423 static _EGLImage *
2424 dri2_create_image_wayland_wl_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2425                                     EGLClientBuffer _buffer,
2426                                     const EGLint *attr_list)
2427 {
2428    struct wl_drm_buffer *buffer;
2429    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2430    const struct wl_drm_components_descriptor *f;
2431    __DRIimage *dri_image;
2432    _EGLImageAttribs attrs;
2433    int32_t plane;
2434
2435    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm,
2436                                    (struct wl_resource *) _buffer);
2437    if (!buffer)
2438        return NULL;
2439
2440    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2441       return NULL;
2442
2443    plane = attrs.PlaneWL;
2444    f = buffer->driver_format;
2445    if (plane < 0 || plane >= f->nplanes) {
2446       _eglError(EGL_BAD_PARAMETER,
2447                 "dri2_create_image_wayland_wl_buffer (plane out of bounds)");
2448       return NULL;
2449    }
2450
2451    dri_image = dri2_dpy->image->fromPlanar(buffer->driver_buffer, plane, NULL);
2452    if (dri_image == NULL && plane == 0)
2453       dri_image = dri2_dpy->image->dupImage(buffer->driver_buffer, NULL);
2454    if (dri_image == NULL) {
2455       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_wayland_wl_buffer");
2456       return NULL;
2457    }
2458
2459    return dri2_create_image_from_dri(disp, dri_image);
2460 }
2461 #endif
2462
2463 static EGLBoolean
2464 dri2_get_sync_values_chromium(_EGLDisplay *disp, _EGLSurface *surf,
2465                               EGLuint64KHR *ust, EGLuint64KHR *msc,
2466                               EGLuint64KHR *sbc)
2467 {
2468    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2469    EGLBoolean ret = EGL_FALSE;
2470
2471    if (dri2_dpy->vtbl->get_sync_values)
2472       ret = dri2_dpy->vtbl->get_sync_values(disp, surf, ust, msc, sbc);
2473
2474    return ret;
2475 }
2476
2477 static EGLBoolean
2478 dri2_get_msc_rate_angle(_EGLDisplay *disp, _EGLSurface *surf,
2479                         EGLint *numerator, EGLint *denominator)
2480 {
2481    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2482    if (!dri2_dpy->vtbl->get_msc_rate)
2483       return EGL_FALSE;
2484    return dri2_dpy->vtbl->get_msc_rate(disp, surf, numerator, denominator);
2485 }
2486
2487 /**
2488  * Set the error code after a call to
2489  * dri2_egl_image::dri_image::createImageFromTexture.
2490  */
2491 static void
2492 dri2_create_image_khr_texture_error(int dri_error)
2493 {
2494    EGLint egl_error = egl_error_from_dri_image_error(dri_error);
2495
2496    if (egl_error != EGL_SUCCESS)
2497       _eglError(egl_error, "dri2_create_image_khr_texture");
2498 }
2499
2500 static _EGLImage *
2501 dri2_create_image_khr_texture(_EGLDisplay *disp, _EGLContext *ctx,
2502                                    EGLenum target,
2503                                    EGLClientBuffer buffer,
2504                                    const EGLint *attr_list)
2505 {
2506    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2507    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2508    struct dri2_egl_image *dri2_img;
2509    GLuint texture = (GLuint) (uintptr_t) buffer;
2510    _EGLImageAttribs attrs;
2511    GLuint depth;
2512    GLenum gl_target;
2513    unsigned error;
2514
2515    if (texture == 0) {
2516       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2517       return EGL_NO_IMAGE_KHR;
2518    }
2519
2520    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2521       return EGL_NO_IMAGE_KHR;
2522
2523    switch (target) {
2524    case EGL_GL_TEXTURE_2D_KHR:
2525       if (!disp->Extensions.KHR_gl_texture_2D_image) {
2526          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2527          return EGL_NO_IMAGE_KHR;
2528       }
2529       depth = 0;
2530       gl_target = GL_TEXTURE_2D;
2531       break;
2532    case EGL_GL_TEXTURE_3D_KHR:
2533       if (!disp->Extensions.KHR_gl_texture_3D_image) {
2534          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2535          return EGL_NO_IMAGE_KHR;
2536       }
2537
2538       depth = attrs.GLTextureZOffset;
2539       gl_target = GL_TEXTURE_3D;
2540       break;
2541    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
2542    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
2543    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
2544    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
2545    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
2546    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
2547       if (!disp->Extensions.KHR_gl_texture_cubemap_image) {
2548          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2549          return EGL_NO_IMAGE_KHR;
2550       }
2551
2552       depth = target - EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR;
2553       gl_target = GL_TEXTURE_CUBE_MAP;
2554       break;
2555    default:
2556       unreachable("Unexpected target in dri2_create_image_khr_texture()");
2557       return EGL_NO_IMAGE_KHR;
2558    }
2559
2560    dri2_img = malloc(sizeof *dri2_img);
2561    if (!dri2_img) {
2562       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2563       return EGL_NO_IMAGE_KHR;
2564    }
2565
2566    _eglInitImage(&dri2_img->base, disp);
2567
2568    dri2_img->dri_image =
2569       dri2_dpy->image->createImageFromTexture(dri2_ctx->dri_context,
2570                                               gl_target,
2571                                               texture,
2572                                               depth,
2573                                               attrs.GLTextureLevel,
2574                                               &error,
2575                                               NULL);
2576    dri2_create_image_khr_texture_error(error);
2577
2578    if (!dri2_img->dri_image) {
2579       free(dri2_img);
2580       return EGL_NO_IMAGE_KHR;
2581    }
2582    return &dri2_img->base;
2583 }
2584
2585 static EGLBoolean
2586 dri2_query_surface(_EGLDisplay *disp, _EGLSurface *surf,
2587                    EGLint attribute, EGLint *value)
2588 {
2589    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2590    EGLBoolean ret;
2591
2592    if (!dri2_dpy->vtbl->query_surface) {
2593       ret = _eglQuerySurface(disp, surf, attribute, value);
2594    } else {
2595       ret = dri2_dpy->vtbl->query_surface(disp, surf, attribute, value);
2596    }
2597
2598    return ret;
2599 }
2600
2601 static struct wl_buffer*
2602 dri2_create_wayland_buffer_from_image(_EGLDisplay *disp, _EGLImage *img)
2603 {
2604    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2605    struct wl_buffer *ret = NULL;
2606
2607    if (dri2_dpy->vtbl->create_wayland_buffer_from_image)
2608       ret = dri2_dpy->vtbl->create_wayland_buffer_from_image(disp, img);
2609
2610    mtx_unlock(&dri2_dpy->lock);
2611
2612    return ret;
2613 }
2614
2615 #ifdef HAVE_LIBDRM
2616 static _EGLImage *
2617 dri2_create_image_mesa_drm_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2618                                   EGLClientBuffer buffer, const EGLint *attr_list)
2619 {
2620    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2621    EGLint format, name, pitch;
2622    _EGLImageAttribs attrs;
2623    __DRIimage *dri_image;
2624
2625    name = (EGLint) (uintptr_t) buffer;
2626
2627    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2628       return NULL;
2629
2630    if (attrs.Width <= 0 || attrs.Height <= 0 ||
2631        attrs.DRMBufferStrideMESA <= 0) {
2632       _eglError(EGL_BAD_PARAMETER,
2633                 "bad width, height or stride");
2634       return NULL;
2635    }
2636
2637    switch (attrs.DRMBufferFormatMESA) {
2638    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2639       format = __DRI_IMAGE_FORMAT_ARGB8888;
2640       pitch = attrs.DRMBufferStrideMESA;
2641       break;
2642    default:
2643       _eglError(EGL_BAD_PARAMETER,
2644                 "dri2_create_image_khr: unsupported pixmap depth");
2645       return NULL;
2646    }
2647
2648    dri_image =
2649       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
2650                                            attrs.Width,
2651                                            attrs.Height,
2652                                            format,
2653                                            name,
2654                                            pitch,
2655                                            NULL);
2656
2657    return dri2_create_image_from_dri(disp, dri_image);
2658 }
2659
2660 static EGLBoolean
2661 dri2_check_dma_buf_attribs(const _EGLImageAttribs *attrs)
2662 {
2663    /**
2664      * The spec says:
2665      *
2666      * "Required attributes and their values are as follows:
2667      *
2668      *  * EGL_WIDTH & EGL_HEIGHT: The logical dimensions of the buffer in pixels
2669      *
2670      *  * EGL_LINUX_DRM_FOURCC_EXT: The pixel format of the buffer, as specified
2671      *    by drm_fourcc.h and used as the pixel_format parameter of the
2672      *    drm_mode_fb_cmd2 ioctl."
2673      *
2674      * and
2675      *
2676      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2677      *    incomplete, EGL_BAD_PARAMETER is generated."
2678      */
2679    if (attrs->Width <= 0 || attrs->Height <= 0 ||
2680        !attrs->DMABufFourCC.IsPresent)
2681       return _eglError(EGL_BAD_PARAMETER, "attribute(s) missing");
2682
2683    /**
2684     * Also:
2685     *
2686     * "If <target> is EGL_LINUX_DMA_BUF_EXT and one or more of the values
2687     *  specified for a plane's pitch or offset isn't supported by EGL,
2688     *  EGL_BAD_ACCESS is generated."
2689     */
2690    for (unsigned i = 0; i < ARRAY_SIZE(attrs->DMABufPlanePitches); ++i) {
2691       if (attrs->DMABufPlanePitches[i].IsPresent &&
2692           attrs->DMABufPlanePitches[i].Value <= 0)
2693          return _eglError(EGL_BAD_ACCESS, "invalid pitch");
2694    }
2695
2696    /**
2697     * If <target> is EGL_LINUX_DMA_BUF_EXT, both or neither of the following
2698     * attribute values may be given.
2699     *
2700     * This is referring to EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT and
2701     * EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, and the same for other planes.
2702     */
2703    for (unsigned i = 0; i < DMA_BUF_MAX_PLANES; ++i) {
2704       if (attrs->DMABufPlaneModifiersLo[i].IsPresent !=
2705           attrs->DMABufPlaneModifiersHi[i].IsPresent)
2706          return _eglError(EGL_BAD_PARAMETER, "modifier attribute lo or hi missing");
2707    }
2708
2709    /* Although the EGL_EXT_image_dma_buf_import_modifiers spec doesn't
2710     * mandate it, we only accept the same modifier across all planes. */
2711    for (unsigned i = 1; i < DMA_BUF_MAX_PLANES; ++i) {
2712       if (attrs->DMABufPlaneFds[i].IsPresent) {
2713          if ((attrs->DMABufPlaneModifiersLo[0].IsPresent !=
2714                attrs->DMABufPlaneModifiersLo[i].IsPresent) ||
2715              (attrs->DMABufPlaneModifiersLo[0].Value !=
2716                attrs->DMABufPlaneModifiersLo[i].Value) ||
2717              (attrs->DMABufPlaneModifiersHi[0].Value !=
2718                attrs->DMABufPlaneModifiersHi[i].Value))
2719             return _eglError(EGL_BAD_PARAMETER, "modifier attributes not equal");
2720       }
2721    }
2722
2723    return EGL_TRUE;
2724 }
2725
2726 /* Returns the total number of planes for the format or zero if it isn't a
2727  * valid fourcc format.
2728  */
2729 static unsigned
2730 dri2_num_fourcc_format_planes(EGLint format)
2731 {
2732    switch (format) {
2733    case DRM_FORMAT_R8:
2734    case DRM_FORMAT_RG88:
2735    case DRM_FORMAT_GR88:
2736    case DRM_FORMAT_R16:
2737    case DRM_FORMAT_GR1616:
2738    case DRM_FORMAT_RGB332:
2739    case DRM_FORMAT_BGR233:
2740    case DRM_FORMAT_XRGB4444:
2741    case DRM_FORMAT_XBGR4444:
2742    case DRM_FORMAT_RGBX4444:
2743    case DRM_FORMAT_BGRX4444:
2744    case DRM_FORMAT_ARGB4444:
2745    case DRM_FORMAT_ABGR4444:
2746    case DRM_FORMAT_RGBA4444:
2747    case DRM_FORMAT_BGRA4444:
2748    case DRM_FORMAT_XRGB1555:
2749    case DRM_FORMAT_XBGR1555:
2750    case DRM_FORMAT_RGBX5551:
2751    case DRM_FORMAT_BGRX5551:
2752    case DRM_FORMAT_ARGB1555:
2753    case DRM_FORMAT_ABGR1555:
2754    case DRM_FORMAT_RGBA5551:
2755    case DRM_FORMAT_BGRA5551:
2756    case DRM_FORMAT_RGB565:
2757    case DRM_FORMAT_BGR565:
2758    case DRM_FORMAT_RGB888:
2759    case DRM_FORMAT_BGR888:
2760    case DRM_FORMAT_XRGB8888:
2761    case DRM_FORMAT_XBGR8888:
2762    case DRM_FORMAT_RGBX8888:
2763    case DRM_FORMAT_BGRX8888:
2764    case DRM_FORMAT_ARGB8888:
2765    case DRM_FORMAT_ABGR8888:
2766    case DRM_FORMAT_RGBA8888:
2767    case DRM_FORMAT_BGRA8888:
2768    case DRM_FORMAT_XRGB2101010:
2769    case DRM_FORMAT_XBGR2101010:
2770    case DRM_FORMAT_RGBX1010102:
2771    case DRM_FORMAT_BGRX1010102:
2772    case DRM_FORMAT_ARGB2101010:
2773    case DRM_FORMAT_ABGR2101010:
2774    case DRM_FORMAT_RGBA1010102:
2775    case DRM_FORMAT_BGRA1010102:
2776    case DRM_FORMAT_ABGR16161616:
2777    case DRM_FORMAT_XBGR16161616:
2778    case DRM_FORMAT_XBGR16161616F:
2779    case DRM_FORMAT_ABGR16161616F:
2780    case DRM_FORMAT_YUYV:
2781    case DRM_FORMAT_YVYU:
2782    case DRM_FORMAT_UYVY:
2783    case DRM_FORMAT_VYUY:
2784    case DRM_FORMAT_AYUV:
2785    case DRM_FORMAT_XYUV8888:
2786    case DRM_FORMAT_Y210:
2787    case DRM_FORMAT_Y212:
2788    case DRM_FORMAT_Y216:
2789    case DRM_FORMAT_Y410:
2790    case DRM_FORMAT_Y412:
2791    case DRM_FORMAT_Y416:
2792       return 1;
2793
2794    case DRM_FORMAT_NV12:
2795    case DRM_FORMAT_NV21:
2796    case DRM_FORMAT_NV16:
2797    case DRM_FORMAT_NV61:
2798    case DRM_FORMAT_P010:
2799    case DRM_FORMAT_P012:
2800    case DRM_FORMAT_P016:
2801       return 2;
2802
2803    case DRM_FORMAT_YUV410:
2804    case DRM_FORMAT_YVU410:
2805    case DRM_FORMAT_YUV411:
2806    case DRM_FORMAT_YVU411:
2807    case DRM_FORMAT_YUV420:
2808    case DRM_FORMAT_YVU420:
2809    case DRM_FORMAT_YUV422:
2810    case DRM_FORMAT_YVU422:
2811    case DRM_FORMAT_YUV444:
2812    case DRM_FORMAT_YVU444:
2813       return 3;
2814
2815    default:
2816       return 0;
2817    }
2818 }
2819
2820 /* Returns the total number of file descriptors. Zero indicates an error. */
2821 static unsigned
2822 dri2_check_dma_buf_format(const _EGLImageAttribs *attrs)
2823 {
2824    unsigned plane_n = dri2_num_fourcc_format_planes(attrs->DMABufFourCC.Value);
2825    if (plane_n == 0) {
2826       _eglError(EGL_BAD_MATCH, "unknown drm fourcc format");
2827       return 0;
2828    }
2829
2830    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; i++) {
2831       /**
2832        * The modifiers extension spec says:
2833        *
2834        * "Modifiers may modify any attribute of a buffer import, including
2835        *  but not limited to adding extra planes to a format which
2836        *  otherwise does not have those planes. As an example, a modifier
2837        *  may add a plane for an external compression buffer to a
2838        *  single-plane format. The exact meaning and effect of any
2839        *  modifier is canonically defined by drm_fourcc.h, not as part of
2840        *  this extension."
2841        */
2842       if (attrs->DMABufPlaneModifiersLo[i].IsPresent &&
2843           attrs->DMABufPlaneModifiersHi[i].IsPresent) {
2844          plane_n = i + 1;
2845       }
2846    }
2847
2848    /**
2849      * The spec says:
2850      *
2851      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2852      *    incomplete, EGL_BAD_PARAMETER is generated."
2853      */
2854    for (unsigned i = 0; i < plane_n; ++i) {
2855       if (!attrs->DMABufPlaneFds[i].IsPresent ||
2856           !attrs->DMABufPlaneOffsets[i].IsPresent ||
2857           !attrs->DMABufPlanePitches[i].IsPresent) {
2858          _eglError(EGL_BAD_PARAMETER, "plane attribute(s) missing");
2859          return 0;
2860       }
2861    }
2862
2863    /**
2864     * The spec also says:
2865     *
2866     * "If <target> is EGL_LINUX_DMA_BUF_EXT, and the EGL_LINUX_DRM_FOURCC_EXT
2867     *  attribute indicates a single-plane format, EGL_BAD_ATTRIBUTE is
2868     *  generated if any of the EGL_DMA_BUF_PLANE1_* or EGL_DMA_BUF_PLANE2_*
2869     *  or EGL_DMA_BUF_PLANE3_* attributes are specified."
2870     */
2871    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; ++i) {
2872       if (attrs->DMABufPlaneFds[i].IsPresent ||
2873           attrs->DMABufPlaneOffsets[i].IsPresent ||
2874           attrs->DMABufPlanePitches[i].IsPresent) {
2875          _eglError(EGL_BAD_ATTRIBUTE, "too many plane attributes");
2876          return 0;
2877       }
2878    }
2879
2880    return plane_n;
2881 }
2882
2883 static EGLBoolean
2884 dri2_query_dma_buf_formats(_EGLDisplay *disp, EGLint max,
2885                            EGLint *formats, EGLint *count)
2886 {
2887    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2888    if (max < 0 || (max > 0 && formats == NULL)) {
2889       _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2890       goto fail;
2891    }
2892
2893    if (dri2_dpy->image->base.version < 15 ||
2894        dri2_dpy->image->queryDmaBufFormats == NULL)
2895       goto fail;
2896
2897    if (!dri2_dpy->image->queryDmaBufFormats(dri2_dpy->dri_screen, max,
2898                                             formats, count))
2899       goto fail;
2900
2901    if (max > 0) {
2902       /* Assert that all of the formats returned are actually fourcc formats.
2903        * Some day, if we want the internal interface function to be able to
2904        * return the fake fourcc formats defined in dri_interface.h, we'll have
2905        * to do something more clever here to pair the list down to just real
2906        * fourcc formats so that we don't leak the fake internal ones.
2907        */
2908       for (int i = 0; i < *count; i++) {
2909          assert(dri2_num_fourcc_format_planes(formats[i]) > 0);
2910       }
2911    }
2912
2913    mtx_unlock(&dri2_dpy->lock);
2914
2915    return EGL_TRUE;
2916
2917 fail:
2918    mtx_unlock(&dri2_dpy->lock);
2919    return EGL_FALSE;
2920 }
2921
2922 static EGLBoolean
2923 dri2_query_dma_buf_modifiers(_EGLDisplay *disp, EGLint format,
2924                              EGLint max, EGLuint64KHR *modifiers,
2925                              EGLBoolean *external_only, EGLint *count)
2926 {
2927    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2928
2929    if (dri2_num_fourcc_format_planes(format) == 0)
2930       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid fourcc format");
2931
2932    if (max < 0)
2933       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid value for max count of formats");
2934
2935    if (max > 0 && modifiers == NULL)
2936       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid modifiers array");
2937
2938    if (dri2_dpy->image->base.version < 15 ||
2939        dri2_dpy->image->queryDmaBufModifiers == NULL) {
2940       mtx_unlock(&dri2_dpy->lock);
2941       return EGL_FALSE;
2942    }
2943
2944    if (dri2_dpy->image->queryDmaBufModifiers(dri2_dpy->dri_screen, format,
2945                                              max, modifiers,
2946                                              (unsigned int *) external_only,
2947                                              count) == false)
2948       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid format");
2949
2950    mtx_unlock(&dri2_dpy->lock);
2951
2952    return EGL_TRUE;
2953 }
2954
2955 /**
2956  * The spec says:
2957  *
2958  * "If eglCreateImageKHR is successful for a EGL_LINUX_DMA_BUF_EXT target, the
2959  *  EGL will take a reference to the dma_buf(s) which it will release at any
2960  *  time while the EGLDisplay is initialized. It is the responsibility of the
2961  *  application to close the dma_buf file descriptors."
2962  *
2963  * Therefore we must never close or otherwise modify the file descriptors.
2964  */
2965 _EGLImage *
2966 dri2_create_image_dma_buf(_EGLDisplay *disp, _EGLContext *ctx,
2967                           EGLClientBuffer buffer, const EGLint *attr_list)
2968 {
2969    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2970    _EGLImage *res;
2971    _EGLImageAttribs attrs;
2972    __DRIimage *dri_image;
2973    unsigned num_fds;
2974    int fds[DMA_BUF_MAX_PLANES];
2975    int pitches[DMA_BUF_MAX_PLANES];
2976    int offsets[DMA_BUF_MAX_PLANES];
2977    uint64_t modifier;
2978    bool has_modifier = false;
2979    unsigned error;
2980    EGLint egl_error;
2981
2982    /**
2983     * The spec says:
2984     *
2985     * ""* If <target> is EGL_LINUX_DMA_BUF_EXT and <buffer> is not NULL, the
2986     *     error EGL_BAD_PARAMETER is generated."
2987     */
2988    if (buffer != NULL) {
2989       _eglError(EGL_BAD_PARAMETER, "buffer not NULL");
2990       return NULL;
2991    }
2992
2993    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2994       return NULL;
2995
2996    if (!dri2_check_dma_buf_attribs(&attrs))
2997       return NULL;
2998
2999    num_fds = dri2_check_dma_buf_format(&attrs);
3000    if (!num_fds)
3001       return NULL;
3002
3003    for (unsigned i = 0; i < num_fds; ++i) {
3004       fds[i] = attrs.DMABufPlaneFds[i].Value;
3005       pitches[i] = attrs.DMABufPlanePitches[i].Value;
3006       offsets[i] = attrs.DMABufPlaneOffsets[i].Value;
3007    }
3008
3009    /* dri2_check_dma_buf_attribs ensures that the modifier, if available,
3010     * will be present in attrs.DMABufPlaneModifiersLo[0] and
3011     * attrs.DMABufPlaneModifiersHi[0] */
3012    if (attrs.DMABufPlaneModifiersLo[0].IsPresent) {
3013       modifier = combine_u32_into_u64(attrs.DMABufPlaneModifiersHi[0].Value,
3014                                       attrs.DMABufPlaneModifiersLo[0].Value);
3015       has_modifier = true;
3016    }
3017
3018    if (attrs.ProtectedContent) {
3019       if (dri2_dpy->image->base.version < 18 ||
3020           dri2_dpy->image->createImageFromDmaBufs3 == NULL) {
3021          _eglError(EGL_BAD_MATCH, "unsupported protected_content attribute");
3022          return EGL_NO_IMAGE_KHR;
3023       }
3024       if (!has_modifier)
3025          modifier = DRM_FORMAT_MOD_INVALID;
3026
3027       dri_image =
3028          dri2_dpy->image->createImageFromDmaBufs3(dri2_dpy->dri_screen,
3029             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
3030             modifier, fds, num_fds, pitches, offsets,
3031             attrs.DMABufYuvColorSpaceHint.Value,
3032             attrs.DMABufSampleRangeHint.Value,
3033             attrs.DMABufChromaHorizontalSiting.Value,
3034             attrs.DMABufChromaVerticalSiting.Value,
3035             attrs.ProtectedContent ? __DRI_IMAGE_PROTECTED_CONTENT_FLAG : 0,
3036             &error,
3037             NULL);
3038    }
3039    else if (has_modifier) {
3040       if (dri2_dpy->image->base.version < 15 ||
3041           dri2_dpy->image->createImageFromDmaBufs2 == NULL) {
3042          _eglError(EGL_BAD_MATCH, "unsupported dma_buf format modifier");
3043          return EGL_NO_IMAGE_KHR;
3044       }
3045       dri_image =
3046          dri2_dpy->image->createImageFromDmaBufs2(dri2_dpy->dri_screen,
3047             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
3048             modifier, fds, num_fds, pitches, offsets,
3049             attrs.DMABufYuvColorSpaceHint.Value,
3050             attrs.DMABufSampleRangeHint.Value,
3051             attrs.DMABufChromaHorizontalSiting.Value,
3052             attrs.DMABufChromaVerticalSiting.Value,
3053             &error,
3054             NULL);
3055    }
3056    else {
3057       dri_image =
3058          dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
3059             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
3060             fds, num_fds, pitches, offsets,
3061             attrs.DMABufYuvColorSpaceHint.Value,
3062             attrs.DMABufSampleRangeHint.Value,
3063             attrs.DMABufChromaHorizontalSiting.Value,
3064             attrs.DMABufChromaVerticalSiting.Value,
3065             &error,
3066             NULL);
3067    }
3068
3069    egl_error = egl_error_from_dri_image_error(error);
3070    if (egl_error != EGL_SUCCESS)
3071       _eglError(egl_error, "createImageFromDmaBufs failed");
3072
3073    if (!dri_image)
3074       return EGL_NO_IMAGE_KHR;
3075
3076    res = dri2_create_image_from_dri(disp, dri_image);
3077
3078    return res;
3079 }
3080 static _EGLImage *
3081 dri2_create_drm_image_mesa(_EGLDisplay *disp, const EGLint *attr_list)
3082 {
3083    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3084    struct dri2_egl_image *dri2_img;
3085    _EGLImageAttribs attrs;
3086    unsigned int dri_use, valid_mask;
3087    int format;
3088
3089    if (!attr_list) {
3090       _eglError(EGL_BAD_PARAMETER, __func__);
3091       goto fail;
3092    }
3093
3094    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
3095       goto fail;
3096
3097    if (attrs.Width <= 0 || attrs.Height <= 0) {
3098       _eglError(EGL_BAD_PARAMETER, __func__);
3099       goto fail;
3100    }
3101
3102    switch (attrs.DRMBufferFormatMESA) {
3103    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
3104       format = __DRI_IMAGE_FORMAT_ARGB8888;
3105       break;
3106    default:
3107       _eglError(EGL_BAD_PARAMETER, __func__);
3108       goto fail;
3109    }
3110
3111    valid_mask =
3112       EGL_DRM_BUFFER_USE_SCANOUT_MESA |
3113       EGL_DRM_BUFFER_USE_SHARE_MESA |
3114       EGL_DRM_BUFFER_USE_CURSOR_MESA;
3115    if (attrs.DRMBufferUseMESA & ~valid_mask) {
3116       _eglError(EGL_BAD_PARAMETER, __func__);
3117       goto fail;
3118    }
3119
3120    dri_use = 0;
3121    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SHARE_MESA)
3122       dri_use |= __DRI_IMAGE_USE_SHARE;
3123    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SCANOUT_MESA)
3124       dri_use |= __DRI_IMAGE_USE_SCANOUT;
3125    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_CURSOR_MESA)
3126       dri_use |= __DRI_IMAGE_USE_CURSOR;
3127
3128    dri2_img = malloc(sizeof *dri2_img);
3129    if (!dri2_img) {
3130       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
3131       goto fail;
3132    }
3133
3134    _eglInitImage(&dri2_img->base, disp);
3135
3136    dri2_img->dri_image =
3137       dri2_dpy->image->createImage(dri2_dpy->dri_screen,
3138                                    attrs.Width, attrs.Height,
3139                                    format, dri_use, dri2_img);
3140    if (dri2_img->dri_image == NULL) {
3141       free(dri2_img);
3142       _eglError(EGL_BAD_ALLOC, "dri2_create_drm_image_mesa");
3143       goto fail;
3144    }
3145
3146    mtx_unlock(&dri2_dpy->lock);
3147
3148    return &dri2_img->base;
3149
3150 fail:
3151    mtx_unlock(&dri2_dpy->lock);
3152    return EGL_NO_IMAGE_KHR;
3153 }
3154
3155 static EGLBoolean
3156 dri2_export_drm_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3157                           EGLint *name, EGLint *handle, EGLint *stride)
3158 {
3159    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3160    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3161
3162    if (name && !dri2_dpy->image->queryImage(dri2_img->dri_image,
3163                                             __DRI_IMAGE_ATTRIB_NAME, name))
3164       return _eglError(EGL_BAD_ALLOC, "dri2_export_drm_image_mesa");
3165
3166    if (handle)
3167       dri2_dpy->image->queryImage(dri2_img->dri_image,
3168                                   __DRI_IMAGE_ATTRIB_HANDLE, handle);
3169
3170    if (stride)
3171       dri2_dpy->image->queryImage(dri2_img->dri_image,
3172                                   __DRI_IMAGE_ATTRIB_STRIDE, stride);
3173
3174    mtx_unlock(&dri2_dpy->lock);
3175
3176    return EGL_TRUE;
3177 }
3178
3179 /**
3180  * Checks if we can support EGL_MESA_image_dma_buf_export on this image.
3181
3182  * The spec provides a boolean return for the driver to reject exporting for
3183  * basically any reason, but doesn't specify any particular error cases.  For
3184  * now, we just fail if we don't have a DRM fourcc for the format.
3185  */
3186 static bool
3187 dri2_can_export_dma_buf_image(_EGLDisplay *disp, _EGLImage *img)
3188 {
3189    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3190    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3191    EGLint fourcc;
3192
3193    if (!dri2_dpy->image->queryImage(dri2_img->dri_image,
3194                                     __DRI_IMAGE_ATTRIB_FOURCC, &fourcc)) {
3195       return false;
3196    }
3197
3198    return true;
3199 }
3200
3201 static EGLBoolean
3202 dri2_export_dma_buf_image_query_mesa(_EGLDisplay *disp, _EGLImage *img,
3203                                      EGLint *fourcc, EGLint *nplanes,
3204                                      EGLuint64KHR *modifiers)
3205 {
3206    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3207    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3208    int num_planes;
3209
3210    if (!dri2_can_export_dma_buf_image(disp, img)) {
3211       mtx_unlock(&dri2_dpy->lock);
3212       return EGL_FALSE;
3213    }
3214
3215    dri2_dpy->image->queryImage(dri2_img->dri_image,
3216                                __DRI_IMAGE_ATTRIB_NUM_PLANES, &num_planes);
3217    if (nplanes)
3218      *nplanes = num_planes;
3219
3220    if (fourcc)
3221       dri2_dpy->image->queryImage(dri2_img->dri_image,
3222                                   __DRI_IMAGE_ATTRIB_FOURCC, fourcc);
3223
3224    if (modifiers) {
3225       int mod_hi, mod_lo;
3226       uint64_t modifier = DRM_FORMAT_MOD_INVALID;
3227       bool query;
3228
3229       query = dri2_dpy->image->queryImage(dri2_img->dri_image,
3230                                           __DRI_IMAGE_ATTRIB_MODIFIER_UPPER,
3231                                           &mod_hi);
3232       query &= dri2_dpy->image->queryImage(dri2_img->dri_image,
3233                                            __DRI_IMAGE_ATTRIB_MODIFIER_LOWER,
3234                                            &mod_lo);
3235       if (query)
3236          modifier = combine_u32_into_u64 (mod_hi, mod_lo);
3237
3238       for (int i = 0; i < num_planes; i++)
3239         modifiers[i] = modifier;
3240    }
3241
3242    mtx_unlock(&dri2_dpy->lock);
3243
3244    return EGL_TRUE;
3245 }
3246
3247 static EGLBoolean
3248 dri2_export_dma_buf_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3249                                int *fds, EGLint *strides, EGLint *offsets)
3250 {
3251    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3252    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3253    EGLint nplanes;
3254
3255    if (!dri2_can_export_dma_buf_image(disp, img))
3256       return EGL_FALSE;
3257
3258    /* EGL_MESA_image_dma_buf_export spec says:
3259     *    "If the number of fds is less than the number of planes, then
3260     *    subsequent fd slots should contain -1."
3261     */
3262    if (fds) {
3263       /* Query nplanes so that we know how big the given array is. */
3264       dri2_dpy->image->queryImage(dri2_img->dri_image,
3265                                   __DRI_IMAGE_ATTRIB_NUM_PLANES, &nplanes);
3266       memset(fds, -1, nplanes * sizeof(int));
3267    }
3268
3269    /* rework later to provide multiple fds/strides/offsets */
3270    if (fds)
3271       dri2_dpy->image->queryImage(dri2_img->dri_image,
3272                                   __DRI_IMAGE_ATTRIB_FD, fds);
3273
3274    if (strides)
3275       dri2_dpy->image->queryImage(dri2_img->dri_image,
3276                                   __DRI_IMAGE_ATTRIB_STRIDE, strides);
3277
3278    if (offsets) {
3279       int img_offset;
3280       bool ret = dri2_dpy->image->queryImage(dri2_img->dri_image,
3281                      __DRI_IMAGE_ATTRIB_OFFSET, &img_offset);
3282       if (ret)
3283          offsets[0] = img_offset;
3284       else
3285          offsets[0] = 0;
3286    }
3287
3288    mtx_unlock(&dri2_dpy->lock);
3289
3290    return EGL_TRUE;
3291 }
3292
3293 #endif
3294
3295 _EGLImage *
3296 dri2_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
3297                       EGLClientBuffer buffer, const EGLint *attr_list)
3298 {
3299    switch (target) {
3300    case EGL_GL_TEXTURE_2D_KHR:
3301    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
3302    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
3303    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
3304    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
3305    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
3306    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
3307    case EGL_GL_TEXTURE_3D_KHR:
3308       return dri2_create_image_khr_texture(disp, ctx, target, buffer, attr_list);
3309    case EGL_GL_RENDERBUFFER_KHR:
3310       return dri2_create_image_khr_renderbuffer(disp, ctx, buffer, attr_list);
3311 #ifdef HAVE_LIBDRM
3312    case EGL_DRM_BUFFER_MESA:
3313       return dri2_create_image_mesa_drm_buffer(disp, ctx, buffer, attr_list);
3314    case EGL_LINUX_DMA_BUF_EXT:
3315       return dri2_create_image_dma_buf(disp, ctx, buffer, attr_list);
3316 #endif
3317 #ifdef HAVE_WAYLAND_PLATFORM
3318    case EGL_WAYLAND_BUFFER_WL:
3319       return dri2_create_image_wayland_wl_buffer(disp, ctx, buffer, attr_list);
3320 #endif
3321    default:
3322       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
3323       return EGL_NO_IMAGE_KHR;
3324    }
3325 }
3326
3327 static EGLBoolean
3328 dri2_destroy_image_khr(_EGLDisplay *disp, _EGLImage *image)
3329 {
3330    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3331    struct dri2_egl_image *dri2_img = dri2_egl_image(image);
3332
3333    dri2_dpy->image->destroyImage(dri2_img->dri_image);
3334    free(dri2_img);
3335
3336    mtx_unlock(&dri2_dpy->lock);
3337
3338    return EGL_TRUE;
3339 }
3340
3341 #ifdef HAVE_WAYLAND_PLATFORM
3342
3343 static void
3344 dri2_wl_reference_buffer(void *user_data, uint32_t name, int fd,
3345                          struct wl_drm_buffer *buffer)
3346 {
3347    _EGLDisplay *disp = user_data;
3348    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3349    __DRIimage *img;
3350    int dri_components = 0;
3351
3352    if (fd == -1)
3353       img = dri2_dpy->image->createImageFromNames(dri2_dpy->dri_screen,
3354                                                   buffer->width,
3355                                                   buffer->height,
3356                                                   buffer->format,
3357                                                   (int*)&name, 1,
3358                                                   buffer->stride,
3359                                                   buffer->offset,
3360                                                   NULL);
3361    else
3362       img = dri2_dpy->image->createImageFromFds(dri2_dpy->dri_screen,
3363                                                 buffer->width,
3364                                                 buffer->height,
3365                                                 buffer->format,
3366                                                 &fd, 1,
3367                                                 buffer->stride,
3368                                                 buffer->offset,
3369                                                 NULL);
3370
3371    if (img == NULL)
3372       return;
3373
3374    dri2_dpy->image->queryImage(img, __DRI_IMAGE_ATTRIB_COMPONENTS, &dri_components);
3375
3376    buffer->driver_format = NULL;
3377    for (int i = 0; i < ARRAY_SIZE(wl_drm_components); i++)
3378       if (wl_drm_components[i].dri_components == dri_components)
3379          buffer->driver_format = &wl_drm_components[i];
3380
3381    if (buffer->driver_format == NULL)
3382       dri2_dpy->image->destroyImage(img);
3383    else
3384       buffer->driver_buffer = img;
3385 }
3386
3387 static void
3388 dri2_wl_release_buffer(void *user_data, struct wl_drm_buffer *buffer)
3389 {
3390    _EGLDisplay *disp = user_data;
3391    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3392
3393    dri2_dpy->image->destroyImage(buffer->driver_buffer);
3394 }
3395
3396 static EGLBoolean
3397 dri2_bind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3398 {
3399    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3400    const struct wayland_drm_callbacks wl_drm_callbacks = {
3401       .authenticate = (int(*)(void *, uint32_t)) dri2_dpy->vtbl->authenticate,
3402       .reference_buffer = dri2_wl_reference_buffer,
3403       .release_buffer = dri2_wl_release_buffer,
3404       .is_format_supported = dri2_wl_is_format_supported
3405    };
3406    int flags = 0;
3407    char *device_name;
3408    uint64_t cap;
3409
3410    if (dri2_dpy->wl_server_drm)
3411       goto fail;
3412
3413    device_name = drmGetRenderDeviceNameFromFd(dri2_dpy->fd);
3414    if (!device_name)
3415       device_name = strdup(dri2_dpy->device_name);
3416    if (!device_name)
3417       goto fail;
3418
3419    if (drmGetCap(dri2_dpy->fd, DRM_CAP_PRIME, &cap) == 0 &&
3420        cap == (DRM_PRIME_CAP_IMPORT | DRM_PRIME_CAP_EXPORT) &&
3421        dri2_dpy->image->base.version >= 7 &&
3422        dri2_dpy->image->createImageFromFds != NULL)
3423       flags |= WAYLAND_DRM_PRIME;
3424
3425    dri2_dpy->wl_server_drm =
3426            wayland_drm_init(wl_dpy, device_name,
3427                             &wl_drm_callbacks, disp, flags);
3428
3429    free(device_name);
3430
3431    if (!dri2_dpy->wl_server_drm)
3432       goto fail;
3433
3434 #ifdef HAVE_DRM_PLATFORM
3435    /* We have to share the wl_drm instance with gbm, so gbm can convert
3436     * wl_buffers to gbm bos. */
3437    if (dri2_dpy->gbm_dri)
3438       dri2_dpy->gbm_dri->wl_drm = dri2_dpy->wl_server_drm;
3439 #endif
3440
3441    mtx_unlock(&dri2_dpy->lock);
3442    return EGL_TRUE;
3443
3444 fail:
3445    mtx_unlock(&dri2_dpy->lock);
3446    return EGL_FALSE;
3447 }
3448
3449 static EGLBoolean
3450 dri2_unbind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3451 {
3452    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3453
3454    if (!dri2_dpy->wl_server_drm)
3455            return EGL_FALSE;
3456
3457    wayland_drm_uninit(dri2_dpy->wl_server_drm);
3458    dri2_dpy->wl_server_drm = NULL;
3459
3460    return EGL_TRUE;
3461 }
3462
3463 static EGLBoolean
3464 dri2_query_wayland_buffer_wl(_EGLDisplay *disp, struct wl_resource *buffer_resource,
3465                              EGLint attribute, EGLint *value)
3466 {
3467    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3468    struct wl_drm_buffer *buffer;
3469    const struct wl_drm_components_descriptor *format;
3470
3471    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm, buffer_resource);
3472    if (!buffer)
3473       return EGL_FALSE;
3474
3475    format = buffer->driver_format;
3476    switch (attribute) {
3477    case EGL_TEXTURE_FORMAT:
3478       *value = format->components;
3479       return EGL_TRUE;
3480    case EGL_WIDTH:
3481       *value = buffer->width;
3482       return EGL_TRUE;
3483    case EGL_HEIGHT:
3484       *value = buffer->height;
3485       return EGL_TRUE;
3486    }
3487
3488    return EGL_FALSE;
3489 }
3490 #endif
3491
3492 #ifdef HAVE_TIZEN_PLATFORM
3493 static EGLBoolean
3494 tizen_bind_wayland_display_wl(_EGLDisplay *disp,
3495                               struct wl_display *wl_dpy)
3496 {
3497    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3498
3499    (void) wl_dpy;
3500
3501    if (!dri2_dpy->tpl_display)
3502      return EGL_FALSE;
3503
3504    if (!tpl_display_get_native_handle(dri2_dpy->tpl_display))
3505      return EGL_FALSE;
3506
3507    return EGL_TRUE;
3508 }
3509
3510 static EGLBoolean
3511 tizen_unbind_wayland_display_wl(_EGLDisplay *disp,
3512                                 struct wl_display *wl_dpy)
3513 {
3514    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3515
3516    (void) wl_dpy;
3517
3518    if (!dri2_dpy->tpl_display)
3519      return EGL_FALSE;
3520
3521    if (!tpl_display_get_native_handle(dri2_dpy->tpl_display))
3522      return EGL_FALSE;
3523
3524    return EGL_TRUE;
3525 }
3526
3527 static EGLBoolean
3528 tizen_query_wayland_buffer_wl(_EGLDisplay *disp,
3529                               struct wl_resource *buffer_resource,
3530                               EGLint attribute, EGLint *value)
3531 {
3532    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3533    tbm_format tbm_format = 0;
3534    int width = 0, height = 0;
3535    tpl_result_t res;
3536
3537    if (!dri2_dpy->tpl_display)
3538      return EGL_FALSE;
3539
3540    if (!tpl_display_get_native_handle(dri2_dpy->tpl_display))
3541      return EGL_FALSE;
3542
3543    res = tpl_display_get_native_pixmap_info(dri2_dpy->tpl_display,
3544                                             (tpl_handle_t)buffer_resource,
3545                                             &width, &height, &tbm_format);
3546    if (res != TPL_ERROR_NONE)
3547      return EGL_FALSE;
3548
3549    switch (attribute) {
3550    case EGL_TEXTURE_FORMAT:
3551       switch (tbm_format) {
3552       case TBM_FORMAT_ARGB8888:
3553          *value = EGL_TEXTURE_RGBA;
3554          return EGL_TRUE;
3555 #pragma GCC diagnostic push
3556 #pragma GCC diagnostic ignored "-Wswitch"
3557       case TBM_FORMAT_XRGB8888:
3558       case TBM_FORMAT_RGB565:
3559 #pragma GCC diagnostic pop
3560          *value = EGL_TEXTURE_RGB;
3561          return EGL_TRUE;
3562       default:
3563          break;
3564       }
3565       break;
3566    case EGL_WIDTH:
3567       *value = width;
3568       return EGL_TRUE;
3569    case EGL_HEIGHT:
3570       *value = height;
3571       return EGL_TRUE;
3572    default:
3573       break;
3574    }
3575
3576    return EGL_FALSE;
3577 }
3578 #endif
3579
3580 static void
3581 dri2_egl_ref_sync(struct dri2_egl_sync *sync)
3582 {
3583    p_atomic_inc(&sync->refcount);
3584 }
3585
3586 static void
3587 dri2_egl_unref_sync(struct dri2_egl_display *dri2_dpy,
3588                     struct dri2_egl_sync *dri2_sync)
3589 {
3590    if (p_atomic_dec_zero(&dri2_sync->refcount)) {
3591       switch (dri2_sync->base.Type) {
3592       case EGL_SYNC_REUSABLE_KHR:
3593          cnd_destroy(&dri2_sync->cond);
3594          break;
3595 #ifdef HAVE_TIZEN_PLATFORM
3596       case EGL_SYNC_NATIVE_FENCE_TIZEN:
3597          if (dri2_sync->base.SyncFd != EGL_NO_NATIVE_FENCE_FD_TIZEN)
3598             close(dri2_sync->base.SyncFd);
3599          break;
3600 #else
3601       case EGL_SYNC_NATIVE_FENCE_ANDROID:
3602          if (dri2_sync->base.SyncFd != EGL_NO_NATIVE_FENCE_FD_ANDROID)
3603             close(dri2_sync->base.SyncFd);
3604          break;
3605 #endif
3606       default:
3607          break;
3608       }
3609
3610       if (dri2_sync->fence)
3611          dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, dri2_sync->fence);
3612
3613       free(dri2_sync);
3614    }
3615 }
3616
3617 static _EGLSync *
3618 dri2_create_sync(_EGLDisplay *disp, EGLenum type, const EGLAttrib *attrib_list)
3619 {
3620    _EGLContext *ctx = _eglGetCurrentContext();
3621    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3622    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3623    struct dri2_egl_sync *dri2_sync;
3624    EGLint ret;
3625    pthread_condattr_t attr;
3626
3627    dri2_sync = calloc(1, sizeof(struct dri2_egl_sync));
3628    if (!dri2_sync) {
3629       _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3630       goto fail;
3631    }
3632
3633    if (!_eglInitSync(&dri2_sync->base, disp, type, attrib_list)) {
3634       goto fail;
3635    }
3636
3637    switch (type) {
3638    case EGL_SYNC_FENCE_KHR:
3639       dri2_sync->fence = dri2_dpy->fence->create_fence(dri2_ctx->dri_context);
3640       if (!dri2_sync->fence) {
3641          /* Why did it fail? DRI doesn't return an error code, so we emit
3642           * a generic EGL error that doesn't communicate user error.
3643           */
3644          _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3645          goto fail;
3646       }
3647       break;
3648
3649    case EGL_SYNC_CL_EVENT_KHR:
3650       dri2_sync->fence = dri2_dpy->fence->get_fence_from_cl_event(
3651                                  dri2_dpy->dri_screen,
3652                                  dri2_sync->base.CLEvent);
3653       /* this can only happen if the cl_event passed in is invalid. */
3654       if (!dri2_sync->fence) {
3655          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3656          goto fail;
3657       }
3658
3659       /* the initial status must be "signaled" if the cl_event is signaled */
3660       if (dri2_dpy->fence->client_wait_sync(dri2_ctx->dri_context,
3661                                             dri2_sync->fence, 0, 0))
3662          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3663       break;
3664
3665    case EGL_SYNC_REUSABLE_KHR:
3666       /* intialize attr */
3667       ret = pthread_condattr_init(&attr);
3668
3669       if (ret) {
3670          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3671          goto fail;
3672       }
3673
3674       /* change clock attribute to CLOCK_MONOTONIC */
3675       ret = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
3676
3677       if (ret) {
3678          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3679          goto fail;
3680       }
3681
3682       ret = pthread_cond_init(&dri2_sync->cond, &attr);
3683
3684       if (ret) {
3685          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3686          goto fail;
3687       }
3688
3689       /* initial status of reusable sync must be "unsignaled" */
3690       dri2_sync->base.SyncStatus = EGL_UNSIGNALED_KHR;
3691       break;
3692
3693 #ifdef HAVE_TIZEN_PLATFORM
3694    case EGL_SYNC_NATIVE_FENCE_TIZEN:
3695       if (dri2_dpy->fence->create_fence_fd) {
3696          dri2_sync->fence = dri2_dpy->fence->create_fence_fd(
3697                                     dri2_ctx->dri_context,
3698                                     dri2_sync->base.SyncFd);
3699       }
3700       if (!dri2_sync->fence) {
3701          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3702          goto fail;
3703       }
3704       break;
3705    }
3706 #else
3707    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3708       if (dri2_dpy->fence->create_fence_fd) {
3709          dri2_sync->fence = dri2_dpy->fence->create_fence_fd(
3710                                     dri2_ctx->dri_context,
3711                                     dri2_sync->base.SyncFd);
3712       }
3713       if (!dri2_sync->fence) {
3714          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3715          free(dri2_sync);
3716          return NULL;
3717       }
3718       break;
3719 #endif
3720
3721    p_atomic_set(&dri2_sync->refcount, 1);
3722    mtx_unlock(&dri2_dpy->lock);
3723
3724    return &dri2_sync->base;
3725
3726 fail:
3727    free(dri2_sync);
3728    mtx_unlock(&dri2_dpy->lock);
3729    return NULL;
3730 }
3731
3732 static EGLBoolean
3733 dri2_destroy_sync(_EGLDisplay *disp, _EGLSync *sync)
3734 {
3735    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3736    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3737    EGLint ret = EGL_TRUE;
3738    EGLint err;
3739
3740    /* if type of sync is EGL_SYNC_REUSABLE_KHR and it is not signaled yet,
3741     * then unlock all threads possibly blocked by the reusable sync before
3742     * destroying it.
3743     */
3744    if (dri2_sync->base.Type == EGL_SYNC_REUSABLE_KHR &&
3745        dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3746       dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3747       /* unblock all threads currently blocked by sync */
3748       err = cnd_broadcast(&dri2_sync->cond);
3749
3750       if (err) {
3751          _eglError(EGL_BAD_ACCESS, "eglDestroySyncKHR");
3752          ret = EGL_FALSE;
3753       }
3754    }
3755
3756    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3757
3758    mtx_unlock(&dri2_dpy->lock);
3759
3760    return ret;
3761 }
3762
3763 static EGLint
3764 dri2_dup_native_fence_fd(_EGLDisplay *disp, _EGLSync *sync)
3765 {
3766    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3767    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3768
3769    assert(sync->Type == EGL_SYNC_NATIVE_FENCE_ANDROID);
3770
3771    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3772       /* try to retrieve the actual native fence fd.. if rendering is
3773        * not flushed this will just return -1, aka NO_NATIVE_FENCE_FD:
3774        */
3775       sync->SyncFd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
3776                                                    dri2_sync->fence);
3777    }
3778
3779    mtx_unlock(&dri2_dpy->lock);
3780
3781    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3782       /* if native fence fd still not created, return an error: */
3783       _eglError(EGL_BAD_PARAMETER, "eglDupNativeFenceFDANDROID");
3784       return EGL_NO_NATIVE_FENCE_FD_ANDROID;
3785    }
3786
3787    assert(sync_valid_fd(sync->SyncFd));
3788
3789    return os_dupfd_cloexec(sync->SyncFd);
3790 }
3791
3792 static EGLint
3793 dri2_dup_native_fence_fd_tizen(_EGLDisplay *dpy, _EGLSync *sync)
3794 {
3795    struct dri2_egl_display *dri2_dpy = dri2_egl_display(dpy);
3796    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3797
3798    assert(sync->Type == EGL_SYNC_NATIVE_FENCE_TIZEN);
3799
3800    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_TIZEN) {
3801       /* try to retrieve the actual native fence fd.. if rendering is
3802        * not flushed this will just return -1, aka NO_NATIVE_FENCE_FD:
3803        */
3804       sync->SyncFd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
3805                                                    dri2_sync->fence);
3806    }
3807
3808    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_TIZEN) {
3809       /* if native fence fd still not created, return an error: */
3810       _eglError(EGL_BAD_PARAMETER, "eglDupNativeFenceFDTIZEN");
3811       return EGL_NO_NATIVE_FENCE_FD_TIZEN;
3812    }
3813
3814    return dup(sync->SyncFd);
3815 }
3816
3817 static void
3818 dri2_set_blob_cache_funcs(_EGLDisplay *disp,
3819                           EGLSetBlobFuncANDROID set,
3820                           EGLGetBlobFuncANDROID get)
3821 {
3822    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3823    dri2_dpy->blob->set_cache_funcs(dri2_dpy->dri_screen, set, get);
3824    mtx_unlock(&dri2_dpy->lock);
3825 }
3826
3827 static EGLint
3828 dri2_client_wait_sync(_EGLDisplay *disp, _EGLSync *sync,
3829                       EGLint flags, EGLTime timeout)
3830 {
3831    _EGLContext *ctx = _eglGetCurrentContext();
3832    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3833    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3834    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3835    unsigned wait_flags = 0;
3836
3837    EGLint ret = EGL_CONDITION_SATISFIED_KHR;
3838
3839    /* The EGL_KHR_fence_sync spec states:
3840     *
3841     *    "If no context is current for the bound API,
3842     *     the EGL_SYNC_FLUSH_COMMANDS_BIT_KHR bit is ignored.
3843     */
3844    if (dri2_ctx && flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)
3845       wait_flags |= __DRI2_FENCE_FLAG_FLUSH_COMMANDS;
3846
3847    /* the sync object should take a reference while waiting */
3848    dri2_egl_ref_sync(dri2_sync);
3849
3850    switch (sync->Type) {
3851    case EGL_SYNC_FENCE_KHR:
3852 #ifdef HAVE_TIZEN_PLATFORM
3853    case EGL_SYNC_NATIVE_FENCE_TIZEN:
3854 #else
3855    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3856 #endif
3857    case EGL_SYNC_CL_EVENT_KHR:
3858       if (dri2_dpy->fence->client_wait_sync(dri2_ctx ? dri2_ctx->dri_context : NULL,
3859                                          dri2_sync->fence, wait_flags,
3860                                          timeout))
3861          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3862       else
3863          ret = EGL_TIMEOUT_EXPIRED_KHR;
3864       break;
3865
3866    case EGL_SYNC_REUSABLE_KHR:
3867       if (dri2_ctx && dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR &&
3868           (flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)) {
3869          /* flush context if EGL_SYNC_FLUSH_COMMANDS_BIT_KHR is set */
3870          dri2_gl_flush();
3871       }
3872
3873       /* if timeout is EGL_FOREVER_KHR, it should wait without any timeout.*/
3874       if (timeout == EGL_FOREVER_KHR) {
3875          mtx_lock(&dri2_sync->mutex);
3876          cnd_wait(&dri2_sync->cond, &dri2_sync->mutex);
3877          mtx_unlock(&dri2_sync->mutex);
3878       } else {
3879          /* if reusable sync has not been yet signaled */
3880          if (dri2_sync->base.SyncStatus != EGL_SIGNALED_KHR) {
3881             /* timespecs for cnd_timedwait */
3882             struct timespec current;
3883             struct timespec expire;
3884
3885             /* We override the clock to monotonic when creating the condition
3886              * variable. */
3887             clock_gettime(CLOCK_MONOTONIC, &current);
3888
3889             /* calculating when to expire */
3890             expire.tv_nsec = timeout % 1000000000L;
3891             expire.tv_sec = timeout / 1000000000L;
3892
3893             expire.tv_nsec += current.tv_nsec;
3894             expire.tv_sec += current.tv_sec;
3895
3896             /* expire.nsec now is a number between 0 and 1999999998 */
3897             if (expire.tv_nsec > 999999999L) {
3898                expire.tv_sec++;
3899                expire.tv_nsec -= 1000000000L;
3900             }
3901
3902             mtx_lock(&dri2_sync->mutex);
3903             ret = cnd_timedwait(&dri2_sync->cond, &dri2_sync->mutex, &expire);
3904             mtx_unlock(&dri2_sync->mutex);
3905
3906             if (ret == thrd_timedout) {
3907                if (dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3908                   ret = EGL_TIMEOUT_EXPIRED_KHR;
3909                } else {
3910                   _eglError(EGL_BAD_ACCESS, "eglClientWaitSyncKHR");
3911                   ret = EGL_FALSE;
3912                }
3913             }
3914          }
3915       }
3916       break;
3917    }
3918
3919    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3920
3921    return ret;
3922 }
3923
3924 static EGLBoolean
3925 dri2_signal_sync(_EGLDisplay *disp, _EGLSync *sync, EGLenum mode)
3926 {
3927    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3928    EGLint ret;
3929
3930    if (sync->Type != EGL_SYNC_REUSABLE_KHR)
3931       return _eglError(EGL_BAD_MATCH, "eglSignalSyncKHR");
3932
3933    if (mode != EGL_SIGNALED_KHR && mode != EGL_UNSIGNALED_KHR)
3934       return _eglError(EGL_BAD_ATTRIBUTE, "eglSignalSyncKHR");
3935
3936    dri2_sync->base.SyncStatus = mode;
3937
3938    if (mode == EGL_SIGNALED_KHR) {
3939       ret = cnd_broadcast(&dri2_sync->cond);
3940
3941       /* fail to broadcast */
3942       if (ret)
3943          return _eglError(EGL_BAD_ACCESS, "eglSignalSyncKHR");
3944    }
3945
3946    return EGL_TRUE;
3947 }
3948
3949 static EGLint
3950 dri2_server_wait_sync(_EGLDisplay *disp, _EGLSync *sync)
3951 {
3952    _EGLContext *ctx = _eglGetCurrentContext();
3953    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3954    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3955    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3956
3957    dri2_dpy->fence->server_wait_sync(dri2_ctx->dri_context,
3958                                      dri2_sync->fence, 0);
3959    return EGL_TRUE;
3960 }
3961
3962 static int
3963 dri2_interop_query_device_info(_EGLDisplay *disp, _EGLContext *ctx,
3964                                struct mesa_glinterop_device_info *out)
3965 {
3966    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3967    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3968
3969    if (!dri2_dpy->interop)
3970       return MESA_GLINTEROP_UNSUPPORTED;
3971
3972    return dri2_dpy->interop->query_device_info(dri2_ctx->dri_context, out);
3973 }
3974
3975 static int
3976 dri2_interop_export_object(_EGLDisplay *disp, _EGLContext *ctx,
3977                            struct mesa_glinterop_export_in *in,
3978                            struct mesa_glinterop_export_out *out)
3979 {
3980    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3981    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3982
3983    if (!dri2_dpy->interop)
3984       return MESA_GLINTEROP_UNSUPPORTED;
3985
3986    return dri2_dpy->interop->export_object(dri2_ctx->dri_context, in, out);
3987 }
3988
3989 static int
3990 dri2_interop_flush_objects(_EGLDisplay *disp, _EGLContext *ctx,
3991                            unsigned count, struct mesa_glinterop_export_in *objects,
3992                            GLsync *sync)
3993 {
3994    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3995    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3996
3997    if (!dri2_dpy->interop || dri2_dpy->interop->base.version < 2)
3998       return MESA_GLINTEROP_UNSUPPORTED;
3999
4000    return dri2_dpy->interop->flush_objects(dri2_ctx->dri_context, count, objects, sync);
4001 }
4002
4003 const _EGLDriver _eglDriver = {
4004    .Initialize = dri2_initialize,
4005    .Terminate = dri2_terminate,
4006    .CreateContext = dri2_create_context,
4007    .DestroyContext = dri2_destroy_context,
4008    .MakeCurrent = dri2_make_current,
4009    .CreateWindowSurface = dri2_create_window_surface,
4010    .CreatePixmapSurface = dri2_create_pixmap_surface,
4011    .CreatePbufferSurface = dri2_create_pbuffer_surface,
4012    .DestroySurface = dri2_destroy_surface,
4013    .GetProcAddress = dri2_get_proc_address,
4014    .WaitClient = dri2_wait_client,
4015    .WaitNative = dri2_wait_native,
4016    .BindTexImage = dri2_bind_tex_image,
4017    .ReleaseTexImage = dri2_release_tex_image,
4018    .SwapInterval = dri2_swap_interval,
4019    .SwapBuffers = dri2_swap_buffers,
4020    .SwapBuffersWithDamageEXT = dri2_swap_buffers_with_damage,
4021    .SwapBuffersRegionNOK = dri2_swap_buffers_region,
4022    .SetDamageRegion = dri2_set_damage_region,
4023    .PostSubBufferNV = dri2_post_sub_buffer,
4024    .CopyBuffers = dri2_copy_buffers,
4025    .QueryBufferAge = dri2_query_buffer_age,
4026    .CreateImageKHR = dri2_create_image,
4027    .DestroyImageKHR = dri2_destroy_image_khr,
4028    .CreateWaylandBufferFromImageWL = dri2_create_wayland_buffer_from_image,
4029    .QuerySurface = dri2_query_surface,
4030    .QueryDriverName = dri2_query_driver_name,
4031    .QueryDriverConfig = dri2_query_driver_config,
4032 #ifdef HAVE_LIBDRM
4033    .CreateDRMImageMESA = dri2_create_drm_image_mesa,
4034    .ExportDRMImageMESA = dri2_export_drm_image_mesa,
4035    .ExportDMABUFImageQueryMESA = dri2_export_dma_buf_image_query_mesa,
4036    .ExportDMABUFImageMESA = dri2_export_dma_buf_image_mesa,
4037    .QueryDmaBufFormatsEXT = dri2_query_dma_buf_formats,
4038    .QueryDmaBufModifiersEXT = dri2_query_dma_buf_modifiers,
4039 #endif
4040 #ifdef HAVE_WAYLAND_PLATFORM
4041    .BindWaylandDisplayWL = dri2_bind_wayland_display_wl,
4042    .UnbindWaylandDisplayWL = dri2_unbind_wayland_display_wl,
4043    .QueryWaylandBufferWL = dri2_query_wayland_buffer_wl,
4044 #endif
4045 #ifdef HAVE_TIZEN_PLATFORM
4046    .BindWaylandDisplayWL = tizen_bind_wayland_display_wl,
4047    .UnbindWaylandDisplayWL = tizen_unbind_wayland_display_wl,
4048    .QueryWaylandBufferWL = tizen_query_wayland_buffer_wl,
4049  #endif
4050    .GetSyncValuesCHROMIUM = dri2_get_sync_values_chromium,
4051    .GetMscRateANGLE = dri2_get_msc_rate_angle,
4052    .CreateSyncKHR = dri2_create_sync,
4053    .ClientWaitSyncKHR = dri2_client_wait_sync,
4054    .SignalSyncKHR = dri2_signal_sync,
4055    .WaitSyncKHR = dri2_server_wait_sync,
4056    .DestroySyncKHR = dri2_destroy_sync,
4057    .GLInteropQueryDeviceInfo = dri2_interop_query_device_info,
4058    .GLInteropExportObject = dri2_interop_export_object,
4059    .GLInteropFlushObjects = dri2_interop_flush_objects,
4060    .DupNativeFenceFDANDROID = dri2_dup_native_fence_fd,
4061    .DupNativeFenceFDTIZEN = dri2_dup_native_fence_fd_tizen,
4062    .SetBlobCacheFuncsANDROID = dri2_set_blob_cache_funcs,
4063 };