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