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