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