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