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