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