egl/dri2: Error path cleanups
[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 = data;
657    _EGLImage *img;
658
659    simple_mtx_lock(&disp->Mutex);
660    img = _eglLookupImage(image, disp);
661    simple_mtx_unlock(&disp->Mutex);
662
663    if (img == NULL) {
664       _eglError(EGL_BAD_PARAMETER, "dri2_validate_egl_image");
665       return false;
666    }
667
668    return true;
669 }
670
671 __DRIimage *
672 dri2_lookup_egl_image_validated(void *image, void *data)
673 {
674    struct dri2_egl_image *dri2_img;
675
676    (void)data;
677
678    dri2_img = dri2_egl_image(image);
679
680    return dri2_img->dri_image;
681 }
682
683 __DRIimage *
684 dri2_lookup_egl_image(__DRIscreen *screen, void *image, void *data)
685 {
686    (void) screen;
687
688    if (!dri2_validate_egl_image(image, data))
689       return NULL;
690
691    return dri2_lookup_egl_image_validated(image, data);
692 }
693
694 const __DRIimageLookupExtension image_lookup_extension = {
695    .base = { __DRI_IMAGE_LOOKUP, 2 },
696
697    .lookupEGLImage       = dri2_lookup_egl_image,
698    .validateEGLImage     = dri2_validate_egl_image,
699    .lookupEGLImageValidated = dri2_lookup_egl_image_validated,
700 };
701
702 struct dri2_extension_match {
703    const char *name;
704    int version;
705    int offset;
706 };
707
708 static const struct dri2_extension_match dri3_driver_extensions[] = {
709    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
710    { __DRI_IMAGE_DRIVER, 1, offsetof(struct dri2_egl_display, image_driver) },
711    { NULL, 0, 0 }
712 };
713
714 static const struct dri2_extension_match dri2_driver_extensions[] = {
715    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
716    { __DRI_DRI2, 2, offsetof(struct dri2_egl_display, dri2) },
717    { NULL, 0, 0 }
718 };
719
720 static const struct dri2_extension_match dri2_core_extensions[] = {
721    { __DRI2_FLUSH, 1, offsetof(struct dri2_egl_display, flush) },
722    { __DRI_TEX_BUFFER, 2, offsetof(struct dri2_egl_display, tex_buffer) },
723    { __DRI_IMAGE, 1, offsetof(struct dri2_egl_display, image) },
724    { NULL, 0, 0 }
725 };
726
727 static const struct dri2_extension_match swrast_driver_extensions[] = {
728    { __DRI_CORE, 1, offsetof(struct dri2_egl_display, core) },
729    { __DRI_SWRAST, 2, offsetof(struct dri2_egl_display, swrast) },
730    { NULL, 0, 0 }
731 };
732
733 static const struct dri2_extension_match swrast_core_extensions[] = {
734    { __DRI_TEX_BUFFER, 2, offsetof(struct dri2_egl_display, tex_buffer) },
735    { NULL, 0, 0 }
736 };
737
738 static const struct dri2_extension_match optional_driver_extensions[] = {
739    { __DRI_CONFIG_OPTIONS, 1, offsetof(struct dri2_egl_display, configOptions) },
740    { NULL, 0, 0 }
741 };
742
743 static const struct dri2_extension_match optional_core_extensions[] = {
744    { __DRI2_ROBUSTNESS, 1, offsetof(struct dri2_egl_display, robustness) },
745    { __DRI2_CONFIG_QUERY, 1, offsetof(struct dri2_egl_display, config) },
746    { __DRI2_FENCE, 1, offsetof(struct dri2_egl_display, fence) },
747    { __DRI2_BUFFER_DAMAGE, 1, offsetof(struct dri2_egl_display, buffer_damage) },
748    { __DRI2_RENDERER_QUERY, 1, offsetof(struct dri2_egl_display, rendererQuery) },
749    { __DRI2_INTEROP, 1, offsetof(struct dri2_egl_display, interop) },
750    { __DRI_IMAGE, 1, offsetof(struct dri2_egl_display, image) },
751    { __DRI2_FLUSH_CONTROL, 1, offsetof(struct dri2_egl_display, flush_control) },
752    { __DRI2_BLOB, 1, offsetof(struct dri2_egl_display, blob) },
753    { __DRI_MUTABLE_RENDER_BUFFER_DRIVER, 1, offsetof(struct dri2_egl_display, mutable_render_buffer) },
754    { __DRI_KOPPER, 1, offsetof(struct dri2_egl_display, kopper) },
755    { NULL, 0, 0 }
756 };
757
758 static EGLBoolean
759 dri2_bind_extensions(struct dri2_egl_display *dri2_dpy,
760                      const struct dri2_extension_match *matches,
761                      const __DRIextension **extensions,
762                      bool optional)
763 {
764    int ret = EGL_TRUE;
765    void *field;
766
767    for (int i = 0; extensions[i]; i++) {
768       _eglLog(_EGL_DEBUG, "found extension `%s'", extensions[i]->name);
769       for (int j = 0; matches[j].name; j++) {
770          if (strcmp(extensions[i]->name, matches[j].name) == 0 &&
771              extensions[i]->version >= matches[j].version) {
772             field = ((char *) dri2_dpy + matches[j].offset);
773             *(const __DRIextension **) field = extensions[i];
774             _eglLog(_EGL_INFO, "found extension %s version %d",
775                     extensions[i]->name, extensions[i]->version);
776             break;
777          }
778       }
779    }
780
781    for (int j = 0; matches[j].name; j++) {
782       field = ((char *) dri2_dpy + matches[j].offset);
783       if (*(const __DRIextension **) field == NULL) {
784          if (optional) {
785             _eglLog(_EGL_DEBUG, "did not find optional extension %s version %d",
786                     matches[j].name, matches[j].version);
787          } else {
788             _eglLog(_EGL_WARNING, "did not find extension %s version %d",
789                     matches[j].name, matches[j].version);
790             ret = EGL_FALSE;
791          }
792       }
793    }
794
795    return ret;
796 }
797
798 static const __DRIextension **
799 dri2_open_driver(_EGLDisplay *disp)
800 {
801    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
802    static const char *search_path_vars[] = {
803       "LIBGL_DRIVERS_PATH",
804       NULL,
805    };
806
807    return loader_open_driver(dri2_dpy->driver_name,
808                              &dri2_dpy->driver,
809                              search_path_vars);
810 }
811
812 static EGLBoolean
813 dri2_load_driver_common(_EGLDisplay *disp,
814                         const struct dri2_extension_match *driver_extensions)
815 {
816    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
817    const __DRIextension **extensions;
818
819    extensions = dri2_open_driver(disp);
820    if (!extensions)
821       return EGL_FALSE;
822
823    if (!dri2_bind_extensions(dri2_dpy, driver_extensions, extensions, false)) {
824       dlclose(dri2_dpy->driver);
825       dri2_dpy->driver = NULL;
826       return EGL_FALSE;
827    }
828    dri2_dpy->driver_extensions = extensions;
829
830    dri2_bind_extensions(dri2_dpy, optional_driver_extensions, extensions, true);
831
832    return EGL_TRUE;
833 }
834
835 EGLBoolean
836 dri2_load_driver(_EGLDisplay *disp)
837 {
838    return dri2_load_driver_common(disp, dri2_driver_extensions);
839 }
840
841 EGLBoolean
842 dri2_load_driver_dri3(_EGLDisplay *disp)
843 {
844    return dri2_load_driver_common(disp, dri3_driver_extensions);
845 }
846
847 EGLBoolean
848 dri2_load_driver_swrast(_EGLDisplay *disp)
849 {
850    return dri2_load_driver_common(disp, swrast_driver_extensions);
851 }
852
853 static unsigned
854 dri2_renderer_query_integer(struct dri2_egl_display *dri2_dpy, int param)
855 {
856    const __DRI2rendererQueryExtension *rendererQuery = dri2_dpy->rendererQuery;
857    unsigned int value = 0;
858
859    if (!rendererQuery ||
860        rendererQuery->queryInteger(dri2_dpy->dri_screen, param, &value) == -1)
861       return 0;
862
863    return value;
864 }
865
866 static const char *
867 dri2_query_driver_name(_EGLDisplay *disp)
868 {
869     struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
870     return dri2_dpy->driver_name;
871 }
872
873 static char *
874 dri2_query_driver_config(_EGLDisplay *disp)
875 {
876     struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
877     const __DRIconfigOptionsExtension *ext = dri2_dpy->configOptions;
878
879     if (ext->base.version >= 2)
880         return ext->getXml(dri2_dpy->driver_name);
881
882     return strdup(ext->xml);
883 }
884
885
886 void
887 dri2_setup_screen(_EGLDisplay *disp)
888 {
889    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
890    unsigned int api_mask;
891
892    /*
893     * EGL 1.5 specification defines the default value to 1. Moreover,
894     * eglSwapInterval() is required to clamp requested value to the supported
895     * range. Since the default value is implicitly assumed to be supported,
896     * use it as both minimum and maximum for the platforms that do not allow
897     * changing the interval. Platforms, which allow it (e.g. x11, wayland)
898     * override these values already.
899     */
900    dri2_dpy->min_swap_interval = 1;
901    dri2_dpy->max_swap_interval = 1;
902    dri2_dpy->default_swap_interval = 1;
903
904    if (dri2_dpy->image_driver) {
905       api_mask = dri2_dpy->image_driver->getAPIMask(dri2_dpy->dri_screen);
906    } else if (dri2_dpy->dri2) {
907       api_mask = dri2_dpy->dri2->getAPIMask(dri2_dpy->dri_screen);
908    } else {
909       assert(dri2_dpy->swrast);
910       api_mask = 1 << __DRI_API_OPENGL |
911                  1 << __DRI_API_GLES |
912                  1 << __DRI_API_GLES2 |
913                  1 << __DRI_API_GLES3;
914    }
915
916    disp->ClientAPIs = 0;
917    if ((api_mask & (1 <<__DRI_API_OPENGL)) && _eglIsApiValid(EGL_OPENGL_API))
918       disp->ClientAPIs |= EGL_OPENGL_BIT;
919    if ((api_mask & (1 << __DRI_API_GLES)) && _eglIsApiValid(EGL_OPENGL_ES_API))
920       disp->ClientAPIs |= EGL_OPENGL_ES_BIT;
921    if ((api_mask & (1 << __DRI_API_GLES2)) && _eglIsApiValid(EGL_OPENGL_ES_API))
922       disp->ClientAPIs |= EGL_OPENGL_ES2_BIT;
923    if ((api_mask & (1 << __DRI_API_GLES3)) && _eglIsApiValid(EGL_OPENGL_ES_API))
924       disp->ClientAPIs |= EGL_OPENGL_ES3_BIT_KHR;
925
926    assert(dri2_dpy->image_driver || dri2_dpy->dri2 || dri2_dpy->swrast);
927    disp->Extensions.KHR_no_config_context = EGL_TRUE;
928    disp->Extensions.KHR_surfaceless_context = EGL_TRUE;
929
930    if (dri2_dpy->configOptions) {
931        disp->Extensions.MESA_query_driver = EGL_TRUE;
932    }
933
934    /* Report back to EGL the bitmask of priorities supported */
935    disp->Extensions.IMG_context_priority =
936       dri2_renderer_query_integer(dri2_dpy,
937                                   __DRI2_RENDERER_HAS_CONTEXT_PRIORITY);
938
939    disp->Extensions.EXT_pixel_format_float = EGL_TRUE;
940
941    if (dri2_renderer_query_integer(dri2_dpy,
942                                    __DRI2_RENDERER_HAS_FRAMEBUFFER_SRGB))
943       disp->Extensions.KHR_gl_colorspace = EGL_TRUE;
944
945    if (dri2_dpy->image_driver ||
946        (dri2_dpy->dri2 && dri2_dpy->dri2->base.version >= 3) ||
947        (dri2_dpy->swrast && dri2_dpy->swrast->base.version >= 3)) {
948       disp->Extensions.KHR_create_context = EGL_TRUE;
949
950       if (dri2_dpy->robustness)
951          disp->Extensions.EXT_create_context_robustness = EGL_TRUE;
952    }
953
954    if (dri2_renderer_query_integer(dri2_dpy,
955                                    __DRI2_RENDERER_HAS_NO_ERROR_CONTEXT))
956       disp->Extensions.KHR_create_context_no_error = EGL_TRUE;
957
958    if (dri2_dpy->fence) {
959       disp->Extensions.KHR_fence_sync = EGL_TRUE;
960       disp->Extensions.KHR_wait_sync = EGL_TRUE;
961       if (dri2_dpy->fence->get_fence_from_cl_event)
962          disp->Extensions.KHR_cl_event2 = EGL_TRUE;
963       if (dri2_dpy->fence->base.version >= 2 &&
964           dri2_dpy->fence->get_capabilities) {
965          unsigned capabilities =
966             dri2_dpy->fence->get_capabilities(dri2_dpy->dri_screen);
967          disp->Extensions.ANDROID_native_fence_sync =
968             (capabilities & __DRI_FENCE_CAP_NATIVE_FD) != 0;
969       }
970    }
971
972    if (dri2_dpy->blob)
973       disp->Extensions.ANDROID_blob_cache = EGL_TRUE;
974
975    disp->Extensions.KHR_reusable_sync = EGL_TRUE;
976
977    if (dri2_dpy->image) {
978       if (dri2_dpy->image->base.version >= 10 &&
979           dri2_dpy->image->getCapabilities != NULL) {
980          int capabilities;
981
982          capabilities = dri2_dpy->image->getCapabilities(dri2_dpy->dri_screen);
983          disp->Extensions.MESA_drm_image = (capabilities & __DRI_IMAGE_CAP_GLOBAL_NAMES) != 0;
984
985          if (dri2_dpy->image->base.version >= 11)
986             disp->Extensions.MESA_image_dma_buf_export = EGL_TRUE;
987       } else {
988          disp->Extensions.MESA_drm_image = EGL_TRUE;
989          if (dri2_dpy->image->base.version >= 11)
990             disp->Extensions.MESA_image_dma_buf_export = EGL_TRUE;
991       }
992
993       disp->Extensions.KHR_image_base = EGL_TRUE;
994       disp->Extensions.KHR_gl_renderbuffer_image = EGL_TRUE;
995       if (dri2_dpy->image->base.version >= 5 &&
996           dri2_dpy->image->createImageFromTexture) {
997          disp->Extensions.KHR_gl_texture_2D_image = EGL_TRUE;
998          disp->Extensions.KHR_gl_texture_cubemap_image = EGL_TRUE;
999
1000          if (dri2_renderer_query_integer(dri2_dpy,
1001                                          __DRI2_RENDERER_HAS_TEXTURE_3D))
1002              disp->Extensions.KHR_gl_texture_3D_image = EGL_TRUE;
1003       }
1004 #ifdef HAVE_LIBDRM
1005       if (dri2_dpy->image->base.version >= 8 &&
1006           dri2_dpy->image->createImageFromDmaBufs) {
1007          disp->Extensions.EXT_image_dma_buf_import = EGL_TRUE;
1008          disp->Extensions.EXT_image_dma_buf_import_modifiers = EGL_TRUE;
1009       }
1010 #endif
1011    }
1012
1013    if (dri2_dpy->flush_control)
1014       disp->Extensions.KHR_context_flush_control = EGL_TRUE;
1015
1016    if (dri2_dpy->buffer_damage && dri2_dpy->buffer_damage->set_damage_region)
1017       disp->Extensions.KHR_partial_update = EGL_TRUE;
1018
1019    disp->Extensions.EXT_protected_surface =
1020       dri2_renderer_query_integer(dri2_dpy,
1021                                   __DRI2_RENDERER_HAS_PROTECTED_CONTENT);
1022 }
1023
1024 void
1025 dri2_setup_swap_interval(_EGLDisplay *disp, int max_swap_interval)
1026 {
1027    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1028    GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1;
1029
1030    /* Allow driconf to override applications.*/
1031    if (dri2_dpy->config)
1032       dri2_dpy->config->configQueryi(dri2_dpy->dri_screen,
1033                                      "vblank_mode", &vblank_mode);
1034    switch (vblank_mode) {
1035    case DRI_CONF_VBLANK_NEVER:
1036       dri2_dpy->min_swap_interval = 0;
1037       dri2_dpy->max_swap_interval = 0;
1038       dri2_dpy->default_swap_interval = 0;
1039       break;
1040    case DRI_CONF_VBLANK_ALWAYS_SYNC:
1041       dri2_dpy->min_swap_interval = 1;
1042       dri2_dpy->max_swap_interval = max_swap_interval;
1043       dri2_dpy->default_swap_interval = 1;
1044       break;
1045    case DRI_CONF_VBLANK_DEF_INTERVAL_0:
1046       dri2_dpy->min_swap_interval = 0;
1047       dri2_dpy->max_swap_interval = max_swap_interval;
1048       dri2_dpy->default_swap_interval = 0;
1049       break;
1050    default:
1051    case DRI_CONF_VBLANK_DEF_INTERVAL_1:
1052       dri2_dpy->min_swap_interval = 0;
1053       dri2_dpy->max_swap_interval = max_swap_interval;
1054       dri2_dpy->default_swap_interval = 1;
1055       break;
1056    }
1057 }
1058
1059 /* All platforms but DRM call this function to create the screen and populate
1060  * the driver_configs. DRM inherits that information from its display - GBM.
1061  */
1062 EGLBoolean
1063 dri2_create_screen(_EGLDisplay *disp)
1064 {
1065    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1066
1067    if (dri2_dpy->image_driver) {
1068       dri2_dpy->dri_screen =
1069          dri2_dpy->image_driver->createNewScreen2(0, dri2_dpy->fd,
1070                                                   dri2_dpy->loader_extensions,
1071                                                   dri2_dpy->driver_extensions,
1072                                                   &dri2_dpy->driver_configs,
1073                                                   disp);
1074    } else if (dri2_dpy->dri2) {
1075       if (dri2_dpy->dri2->base.version >= 4) {
1076          dri2_dpy->dri_screen =
1077             dri2_dpy->dri2->createNewScreen2(0, dri2_dpy->fd,
1078                                              dri2_dpy->loader_extensions,
1079                                              dri2_dpy->driver_extensions,
1080                                              &dri2_dpy->driver_configs, disp);
1081       } else {
1082          dri2_dpy->dri_screen =
1083             dri2_dpy->dri2->createNewScreen(0, dri2_dpy->fd,
1084                                             dri2_dpy->loader_extensions,
1085                                             &dri2_dpy->driver_configs, disp);
1086       }
1087    } else {
1088       assert(dri2_dpy->swrast);
1089       if (dri2_dpy->swrast->base.version >= 4) {
1090          dri2_dpy->dri_screen =
1091             dri2_dpy->swrast->createNewScreen2(0, dri2_dpy->loader_extensions,
1092                                                dri2_dpy->driver_extensions,
1093                                                &dri2_dpy->driver_configs, disp);
1094       } else {
1095          dri2_dpy->dri_screen =
1096             dri2_dpy->swrast->createNewScreen(0, dri2_dpy->loader_extensions,
1097                                               &dri2_dpy->driver_configs, disp);
1098       }
1099    }
1100
1101    if (dri2_dpy->dri_screen == NULL) {
1102       _eglLog(_EGL_WARNING, "egl: failed to create dri2 screen");
1103       return EGL_FALSE;
1104    }
1105
1106    dri2_dpy->own_dri_screen = true;
1107    return EGL_TRUE;
1108 }
1109
1110 EGLBoolean
1111 dri2_setup_extensions(_EGLDisplay *disp)
1112 {
1113    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1114    const struct dri2_extension_match *mandatory_core_extensions;
1115    const __DRIextension **extensions;
1116
1117    extensions = dri2_dpy->core->getExtensions(dri2_dpy->dri_screen);
1118
1119    if (dri2_dpy->image_driver || dri2_dpy->dri2)
1120       mandatory_core_extensions = dri2_core_extensions;
1121    else
1122       mandatory_core_extensions = swrast_core_extensions;
1123
1124    if (!dri2_bind_extensions(dri2_dpy, mandatory_core_extensions, extensions, false))
1125       return EGL_FALSE;
1126
1127 #ifdef HAVE_DRI3_MODIFIERS
1128    dri2_dpy->multibuffers_available =
1129       (dri2_dpy->dri3_major_version > 1 || (dri2_dpy->dri3_major_version == 1 &&
1130                                             dri2_dpy->dri3_minor_version >= 2)) &&
1131       (dri2_dpy->present_major_version > 1 || (dri2_dpy->present_major_version == 1 &&
1132                                                dri2_dpy->present_minor_version >= 2)) &&
1133       (dri2_dpy->image && dri2_dpy->image->base.version >= 15);
1134 #endif
1135
1136    dri2_bind_extensions(dri2_dpy, optional_core_extensions, extensions, true);
1137    return EGL_TRUE;
1138 }
1139
1140 /**
1141  * Called via eglInitialize(), drv->Initialize().
1142  *
1143  * This must be guaranteed to be called exactly once, even if eglInitialize is
1144  * called many times (without a eglTerminate in between).
1145  */
1146 static EGLBoolean
1147 dri2_initialize(_EGLDisplay *disp)
1148 {
1149    EGLBoolean ret = EGL_FALSE;
1150    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1151
1152    /* In the case where the application calls eglMakeCurrent(context1),
1153     * eglTerminate, then eglInitialize again (without a call to eglReleaseThread
1154     * or eglMakeCurrent(NULL) before that), dri2_dpy structure is still
1155     * initialized, as we need it to be able to free context1 correctly.
1156     *
1157     * It would probably be safest to forcibly release the display with
1158     * dri2_display_release, to make sure the display is reinitialized correctly.
1159     * However, the EGL spec states that we need to keep a reference to the
1160     * current context (so we cannot call dri2_make_current(NULL)), and therefore
1161     * we would leak context1 as we would be missing the old display connection
1162     * to free it up correctly.
1163     */
1164    if (dri2_dpy) {
1165       dri2_dpy->ref_count++;
1166       return EGL_TRUE;
1167    }
1168
1169    loader_set_logger(_eglLog);
1170
1171    switch (disp->Platform) {
1172    case _EGL_PLATFORM_SURFACELESS:
1173       ret = dri2_initialize_surfaceless(disp);
1174       break;
1175    case _EGL_PLATFORM_DEVICE:
1176       ret = dri2_initialize_device(disp);
1177       break;
1178    case _EGL_PLATFORM_X11:
1179    case _EGL_PLATFORM_XCB:
1180       ret = dri2_initialize_x11(disp);
1181       break;
1182    case _EGL_PLATFORM_DRM:
1183       ret = dri2_initialize_drm(disp);
1184       break;
1185    case _EGL_PLATFORM_WAYLAND:
1186       ret = dri2_initialize_wayland(disp);
1187       break;
1188    case _EGL_PLATFORM_ANDROID:
1189       ret = dri2_initialize_android(disp);
1190       break;
1191    default:
1192       unreachable("Callers ensure we cannot get here.");
1193       return EGL_FALSE;
1194    }
1195
1196    if (!ret)
1197       return EGL_FALSE;
1198
1199    dri2_dpy = dri2_egl_display(disp);
1200    dri2_dpy->ref_count++;
1201
1202    return EGL_TRUE;
1203 }
1204
1205 /**
1206  * Decrement display reference count, and free up display if necessary.
1207  */
1208 static void
1209 dri2_display_release(_EGLDisplay *disp)
1210 {
1211    struct dri2_egl_display *dri2_dpy;
1212
1213    if (!disp)
1214       return;
1215
1216    dri2_dpy = dri2_egl_display(disp);
1217
1218    assert(dri2_dpy->ref_count > 0);
1219    dri2_dpy->ref_count--;
1220
1221    if (dri2_dpy->ref_count > 0)
1222       return;
1223
1224    _eglCleanupDisplay(disp);
1225    dri2_display_destroy(disp);
1226 }
1227
1228 void
1229 dri2_display_destroy(_EGLDisplay *disp)
1230 {
1231    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1232
1233    if (dri2_dpy->own_dri_screen) {
1234       if (dri2_dpy->vtbl && dri2_dpy->vtbl->close_screen_notify)
1235          dri2_dpy->vtbl->close_screen_notify(disp);
1236       dri2_dpy->core->destroyScreen(dri2_dpy->dri_screen);
1237    }
1238    if (dri2_dpy->fd >= 0)
1239       close(dri2_dpy->fd);
1240
1241    /* Don't dlclose the driver when building with the address sanitizer, so you
1242     * get good symbols from the leak reports.
1243     */
1244 #if !BUILT_WITH_ASAN || defined(NDEBUG)
1245    if (dri2_dpy->driver)
1246       dlclose(dri2_dpy->driver);
1247 #endif
1248
1249    free(dri2_dpy->driver_name);
1250
1251 #ifdef HAVE_WAYLAND_PLATFORM
1252    free(dri2_dpy->device_name);
1253 #endif
1254
1255    switch (disp->Platform) {
1256    case _EGL_PLATFORM_X11:
1257       dri2_teardown_x11(dri2_dpy);
1258       break;
1259    case _EGL_PLATFORM_DRM:
1260       dri2_teardown_drm(dri2_dpy);
1261       break;
1262    case _EGL_PLATFORM_WAYLAND:
1263       dri2_teardown_wayland(dri2_dpy);
1264       break;
1265    default:
1266       /* TODO: add teardown for other platforms */
1267       break;
1268    }
1269
1270    /* The drm platform does not create the screen/driver_configs but reuses
1271     * the ones from the gbm device. As such the gbm itself is responsible
1272     * for the cleanup.
1273     */
1274    if (disp->Platform != _EGL_PLATFORM_DRM && dri2_dpy->driver_configs) {
1275       for (unsigned i = 0; dri2_dpy->driver_configs[i]; i++)
1276          free((__DRIconfig *) dri2_dpy->driver_configs[i]);
1277       free(dri2_dpy->driver_configs);
1278    }
1279    free(dri2_dpy);
1280    disp->DriverData = NULL;
1281 }
1282
1283 __DRIbuffer *
1284 dri2_egl_surface_alloc_local_buffer(struct dri2_egl_surface *dri2_surf,
1285                                     unsigned int att, unsigned int format)
1286 {
1287    struct dri2_egl_display *dri2_dpy =
1288       dri2_egl_display(dri2_surf->base.Resource.Display);
1289
1290    if (att >= ARRAY_SIZE(dri2_surf->local_buffers))
1291       return NULL;
1292
1293    if (!dri2_surf->local_buffers[att]) {
1294       dri2_surf->local_buffers[att] =
1295          dri2_dpy->dri2->allocateBuffer(dri2_dpy->dri_screen, att, format,
1296                                         dri2_surf->base.Width, dri2_surf->base.Height);
1297    }
1298
1299    return dri2_surf->local_buffers[att];
1300 }
1301
1302 void
1303 dri2_egl_surface_free_local_buffers(struct dri2_egl_surface *dri2_surf)
1304 {
1305    struct dri2_egl_display *dri2_dpy =
1306       dri2_egl_display(dri2_surf->base.Resource.Display);
1307
1308    for (int i = 0; i < ARRAY_SIZE(dri2_surf->local_buffers); i++) {
1309       if (dri2_surf->local_buffers[i]) {
1310          dri2_dpy->dri2->releaseBuffer(dri2_dpy->dri_screen,
1311                                        dri2_surf->local_buffers[i]);
1312          dri2_surf->local_buffers[i] = NULL;
1313       }
1314    }
1315 }
1316
1317 /**
1318  * Called via eglTerminate(), drv->Terminate().
1319  *
1320  * This must be guaranteed to be called exactly once, even if eglTerminate is
1321  * called many times (without a eglInitialize in between).
1322  */
1323 static EGLBoolean
1324 dri2_terminate(_EGLDisplay *disp)
1325 {
1326    /* Release all non-current Context/Surfaces. */
1327    _eglReleaseDisplayResources(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(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       _eglError(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    return &dri2_ctx->base;
1644
1645  cleanup:
1646    free(dri2_ctx);
1647    return NULL;
1648 }
1649
1650 /**
1651  * Called via eglDestroyContext(), drv->DestroyContext().
1652  */
1653 static EGLBoolean
1654 dri2_destroy_context(_EGLDisplay *disp, _EGLContext *ctx)
1655 {
1656    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1657    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1658
1659    if (_eglPutContext(ctx)) {
1660       dri2_dpy->core->destroyContext(dri2_ctx->dri_context);
1661       free(dri2_ctx);
1662    }
1663
1664    return EGL_TRUE;
1665 }
1666
1667 EGLBoolean
1668 dri2_init_surface(_EGLSurface *surf, _EGLDisplay *disp, EGLint type,
1669         _EGLConfig *conf, const EGLint *attrib_list,
1670         EGLBoolean enable_out_fence, void *native_surface)
1671 {
1672    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1673    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1674
1675    dri2_surf->out_fence_fd = -1;
1676    dri2_surf->enable_out_fence = false;
1677    if (dri2_dpy->fence && dri2_dpy->fence->base.version >= 2 &&
1678        dri2_dpy->fence->get_capabilities &&
1679        (dri2_dpy->fence->get_capabilities(dri2_dpy->dri_screen) &
1680         __DRI_FENCE_CAP_NATIVE_FD)) {
1681       dri2_surf->enable_out_fence = enable_out_fence;
1682    }
1683
1684    return _eglInitSurface(surf, disp, type, conf, attrib_list, native_surface);
1685 }
1686
1687 static void
1688 dri2_surface_set_out_fence_fd( _EGLSurface *surf, int fence_fd)
1689 {
1690    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1691
1692    if (dri2_surf->out_fence_fd >= 0)
1693       close(dri2_surf->out_fence_fd);
1694
1695    dri2_surf->out_fence_fd = fence_fd;
1696 }
1697
1698 void
1699 dri2_fini_surface(_EGLSurface *surf)
1700 {
1701    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1702
1703    dri2_surface_set_out_fence_fd(surf, -1);
1704    dri2_surf->enable_out_fence = false;
1705 }
1706
1707 static EGLBoolean
1708 dri2_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
1709 {
1710    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1711
1712    if (!_eglPutSurface(surf))
1713       return EGL_TRUE;
1714
1715    return dri2_dpy->vtbl->destroy_surface(disp, surf);
1716 }
1717
1718 static void
1719 dri2_surf_update_fence_fd(_EGLContext *ctx,
1720                           _EGLDisplay *disp, _EGLSurface *surf)
1721 {
1722    __DRIcontext *dri_ctx = dri2_egl_context(ctx)->dri_context;
1723    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1724    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1725    int fence_fd = -1;
1726    void *fence;
1727
1728    if (!dri2_surf->enable_out_fence)
1729       return;
1730
1731    fence = dri2_dpy->fence->create_fence_fd(dri_ctx, -1);
1732    if (fence) {
1733       fence_fd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
1734                                                fence);
1735       dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, fence);
1736    }
1737    dri2_surface_set_out_fence_fd(surf, fence_fd);
1738 }
1739
1740 EGLBoolean
1741 dri2_create_drawable(struct dri2_egl_display *dri2_dpy,
1742                      const __DRIconfig *config,
1743                      struct dri2_egl_surface *dri2_surf,
1744                      void *loaderPrivate)
1745 {
1746    if (dri2_dpy->kopper) {
1747       dri2_surf->dri_drawable =
1748           dri2_dpy->kopper->createNewDrawable(dri2_dpy->dri_screen, config, loaderPrivate,
1749                                               dri2_surf->base.Type == EGL_PBUFFER_BIT ||
1750                                               dri2_surf->base.Type == EGL_PIXMAP_BIT);
1751    } else {
1752       __DRIcreateNewDrawableFunc createNewDrawable;
1753       if (dri2_dpy->image_driver)
1754          createNewDrawable = dri2_dpy->image_driver->createNewDrawable;
1755       else if (dri2_dpy->dri2)
1756          createNewDrawable = dri2_dpy->dri2->createNewDrawable;
1757       else if (dri2_dpy->swrast)
1758          createNewDrawable = dri2_dpy->swrast->createNewDrawable;
1759       else
1760          return _eglError(EGL_BAD_ALLOC, "no createNewDrawable");
1761
1762       dri2_surf->dri_drawable = createNewDrawable(dri2_dpy->dri_screen,
1763                                                   config, loaderPrivate);
1764    }
1765    if (dri2_surf->dri_drawable == NULL)
1766       return _eglError(EGL_BAD_ALLOC, "createNewDrawable");
1767
1768    return EGL_TRUE;
1769 }
1770
1771 /**
1772  * Called via eglMakeCurrent(), drv->MakeCurrent().
1773  */
1774 static EGLBoolean
1775 dri2_make_current(_EGLDisplay *disp, _EGLSurface *dsurf,
1776                   _EGLSurface *rsurf, _EGLContext *ctx)
1777 {
1778    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1779    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1780    _EGLDisplay *old_disp = NULL;
1781    struct dri2_egl_display *old_dri2_dpy = NULL;
1782    _EGLContext *old_ctx;
1783    _EGLSurface *old_dsurf, *old_rsurf;
1784    _EGLSurface *tmp_dsurf, *tmp_rsurf;
1785    __DRIdrawable *ddraw, *rdraw;
1786    __DRIcontext *cctx;
1787    EGLint egl_error = EGL_SUCCESS;
1788
1789    if (!dri2_dpy)
1790       return _eglError(EGL_NOT_INITIALIZED, "eglMakeCurrent");
1791
1792    /* make new bindings, set the EGL error otherwise */
1793    if (!_eglBindContext(ctx, dsurf, rsurf, &old_ctx, &old_dsurf, &old_rsurf))
1794       return EGL_FALSE;
1795
1796    if (old_ctx == ctx && old_dsurf == dsurf && old_rsurf == rsurf) {
1797       _eglPutSurface(old_dsurf);
1798       _eglPutSurface(old_rsurf);
1799       _eglPutContext(old_ctx);
1800       return EGL_TRUE;
1801    }
1802
1803    if (old_ctx) {
1804       __DRIcontext *old_cctx = dri2_egl_context(old_ctx)->dri_context;
1805       old_disp = old_ctx->Resource.Display;
1806       old_dri2_dpy = dri2_egl_display(old_disp);
1807
1808       /* Disable shared buffer mode */
1809       if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1810           old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1811          old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, false);
1812       }
1813
1814       dri2_dpy->core->unbindContext(old_cctx);
1815
1816       if (old_dsurf)
1817          dri2_surf_update_fence_fd(old_ctx, disp, old_dsurf);
1818    }
1819
1820    ddraw = (dsurf) ? dri2_dpy->vtbl->get_dri_drawable(dsurf) : NULL;
1821    rdraw = (rsurf) ? dri2_dpy->vtbl->get_dri_drawable(rsurf) : NULL;
1822    cctx = (dri2_ctx) ? dri2_ctx->dri_context : NULL;
1823
1824    if (cctx || ddraw || rdraw) {
1825       if (!dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1826          _EGLContext *tmp_ctx;
1827
1828          /* dri2_dpy->core->bindContext failed. We cannot tell for sure why, but
1829           * setting the error to EGL_BAD_MATCH is surely better than leaving it
1830           * as EGL_SUCCESS.
1831           */
1832          egl_error = EGL_BAD_MATCH;
1833
1834          /* undo the previous _eglBindContext */
1835          _eglBindContext(old_ctx, old_dsurf, old_rsurf, &ctx, &tmp_dsurf, &tmp_rsurf);
1836          assert(&dri2_ctx->base == ctx &&
1837                 tmp_dsurf == dsurf &&
1838                 tmp_rsurf == rsurf);
1839
1840          _eglPutSurface(dsurf);
1841          _eglPutSurface(rsurf);
1842          _eglPutContext(ctx);
1843
1844          _eglPutSurface(old_dsurf);
1845          _eglPutSurface(old_rsurf);
1846          _eglPutContext(old_ctx);
1847
1848          ddraw = (old_dsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_dsurf) : NULL;
1849          rdraw = (old_rsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_rsurf) : NULL;
1850          cctx = (old_ctx) ? dri2_egl_context(old_ctx)->dri_context : NULL;
1851
1852          /* undo the previous dri2_dpy->core->unbindContext */
1853          if (dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1854             if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1855                 old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1856                old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, true);
1857             }
1858
1859             return _eglError(egl_error, "eglMakeCurrent");
1860          }
1861
1862          /* We cannot restore the same state as it was before calling
1863           * eglMakeCurrent() and the spec isn't clear about what to do. We
1864           * can prevent EGL from calling into the DRI driver with no DRI
1865           * context bound.
1866           */
1867          dsurf = rsurf = NULL;
1868          ctx = NULL;
1869
1870          _eglBindContext(ctx, dsurf, rsurf, &tmp_ctx, &tmp_dsurf, &tmp_rsurf);
1871          assert(tmp_ctx == old_ctx && tmp_dsurf == old_dsurf &&
1872                 tmp_rsurf == old_rsurf);
1873
1874          _eglLog(_EGL_WARNING, "DRI2: failed to rebind the previous context");
1875       } else {
1876          /* dri2_dpy->core->bindContext succeeded, so take a reference on the
1877           * dri2_dpy. This prevents dri2_dpy from being reinitialized when a
1878           * EGLDisplay is terminated and then initialized again while a
1879           * context is still bound. See dri2_intitialize() for a more in depth
1880           * explanation. */
1881          dri2_dpy->ref_count++;
1882       }
1883    }
1884
1885    dri2_destroy_surface(disp, old_dsurf);
1886    dri2_destroy_surface(disp, old_rsurf);
1887
1888    if (old_ctx) {
1889       dri2_destroy_context(disp, old_ctx);
1890       dri2_display_release(old_disp);
1891    }
1892
1893    if (egl_error != EGL_SUCCESS)
1894       return _eglError(egl_error, "eglMakeCurrent");
1895
1896    if (dsurf && _eglSurfaceHasMutableRenderBuffer(dsurf) &&
1897        dri2_dpy->vtbl->set_shared_buffer_mode) {
1898       /* Always update the shared buffer mode. This is obviously needed when
1899        * the active EGL_RENDER_BUFFER is EGL_SINGLE_BUFFER. When
1900        * EGL_RENDER_BUFFER is EGL_BACK_BUFFER, the update protects us in the
1901        * case where external non-EGL API may have changed window's shared
1902        * buffer mode since we last saw it.
1903        */
1904       bool mode = (dsurf->ActiveRenderBuffer == EGL_SINGLE_BUFFER);
1905       dri2_dpy->vtbl->set_shared_buffer_mode(disp, dsurf, mode);
1906    }
1907
1908    return EGL_TRUE;
1909 }
1910
1911 __DRIdrawable *
1912 dri2_surface_get_dri_drawable(_EGLSurface *surf)
1913 {
1914    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1915
1916    return dri2_surf->dri_drawable;
1917 }
1918
1919 /*
1920  * Called from eglGetProcAddress() via drv->GetProcAddress().
1921  */
1922 static _EGLProc
1923 dri2_get_proc_address(const char *procname)
1924 {
1925    return _glapi_get_proc_address(procname);
1926 }
1927
1928 static _EGLSurface*
1929 dri2_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
1930                            void *native_window, const EGLint *attrib_list)
1931 {
1932    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1933    return dri2_dpy->vtbl->create_window_surface(disp, conf, native_window,
1934                                                 attrib_list);
1935 }
1936
1937 static _EGLSurface*
1938 dri2_create_pixmap_surface(_EGLDisplay *disp, _EGLConfig *conf,
1939                            void *native_pixmap, const EGLint *attrib_list)
1940 {
1941    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1942    if (!dri2_dpy->vtbl->create_pixmap_surface)
1943       return NULL;
1944    return dri2_dpy->vtbl->create_pixmap_surface(disp, conf, native_pixmap,
1945                                                 attrib_list);
1946 }
1947
1948 static _EGLSurface*
1949 dri2_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
1950                             const EGLint *attrib_list)
1951 {
1952    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1953    if (!dri2_dpy->vtbl->create_pbuffer_surface)
1954       return NULL;
1955    return dri2_dpy->vtbl->create_pbuffer_surface(disp, conf, attrib_list);
1956 }
1957
1958 static EGLBoolean
1959 dri2_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
1960 {
1961    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1962    if (!dri2_dpy->vtbl->swap_interval)
1963       return EGL_TRUE;
1964    return dri2_dpy->vtbl->swap_interval(disp, surf, interval);
1965 }
1966
1967 /**
1968  * Asks the client API to flush any rendering to the drawable so that we can
1969  * do our swapbuffers.
1970  */
1971 void
1972 dri2_flush_drawable_for_swapbuffers(_EGLDisplay *disp, _EGLSurface *draw)
1973 {
1974    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1975    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(draw);
1976
1977    if (dri2_dpy->flush) {
1978       if (dri2_dpy->flush->base.version >= 4) {
1979          /* We know there's a current context because:
1980           *
1981           *     "If surface is not bound to the calling thread’s current
1982           *      context, an EGL_BAD_SURFACE error is generated."
1983          */
1984          _EGLContext *ctx = _eglGetCurrentContext();
1985          struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1986
1987          /* From the EGL 1.4 spec (page 52):
1988           *
1989           *     "The contents of ancillary buffers are always undefined
1990           *      after calling eglSwapBuffers."
1991           */
1992          dri2_dpy->flush->flush_with_flags(dri2_ctx->dri_context,
1993                                            dri_drawable,
1994                                            __DRI2_FLUSH_DRAWABLE |
1995                                            __DRI2_FLUSH_INVALIDATE_ANCILLARY,
1996                                            __DRI2_THROTTLE_SWAPBUFFER);
1997       } else {
1998          dri2_dpy->flush->flush(dri_drawable);
1999       }
2000    }
2001 }
2002
2003 static EGLBoolean
2004 dri2_swap_buffers(_EGLDisplay *disp, _EGLSurface *surf)
2005 {
2006    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2007    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2008    _EGLContext *ctx = _eglGetCurrentContext();
2009    EGLBoolean ret;
2010
2011    if (ctx && surf)
2012       dri2_surf_update_fence_fd(ctx, disp, surf);
2013    ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2014
2015    /* SwapBuffers marks the end of the frame; reset the damage region for
2016     * use again next time.
2017     */
2018    if (ret && dri2_dpy->buffer_damage &&
2019        dri2_dpy->buffer_damage->set_damage_region)
2020       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2021
2022    return ret;
2023 }
2024
2025 static EGLBoolean
2026 dri2_swap_buffers_with_damage(_EGLDisplay *disp, _EGLSurface *surf,
2027                               const EGLint *rects, EGLint n_rects)
2028 {
2029    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2030    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2031    _EGLContext *ctx = _eglGetCurrentContext();
2032    EGLBoolean ret;
2033
2034    if (ctx && surf)
2035       dri2_surf_update_fence_fd(ctx, disp, surf);
2036    if (dri2_dpy->vtbl->swap_buffers_with_damage)
2037       ret = dri2_dpy->vtbl->swap_buffers_with_damage(disp, surf,
2038                                                      rects, n_rects);
2039    else
2040       ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2041
2042    /* SwapBuffers marks the end of the frame; reset the damage region for
2043     * use again next time.
2044     */
2045    if (ret && dri2_dpy->buffer_damage &&
2046        dri2_dpy->buffer_damage->set_damage_region)
2047       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2048
2049    return ret;
2050 }
2051
2052 static EGLBoolean
2053 dri2_swap_buffers_region(_EGLDisplay *disp, _EGLSurface *surf,
2054                          EGLint numRects, const EGLint *rects)
2055 {
2056    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2057    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2058    EGLBoolean ret;
2059
2060    if (!dri2_dpy->vtbl->swap_buffers_region)
2061       return EGL_FALSE;
2062    ret = dri2_dpy->vtbl->swap_buffers_region(disp, surf, numRects, rects);
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_set_damage_region(_EGLDisplay *disp, _EGLSurface *surf,
2076                        EGLint *rects, EGLint n_rects)
2077 {
2078    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2079    __DRIdrawable *drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2080
2081    if (!dri2_dpy->buffer_damage || !dri2_dpy->buffer_damage->set_damage_region)
2082       return EGL_FALSE;
2083
2084    dri2_dpy->buffer_damage->set_damage_region(drawable, n_rects, rects);
2085    return EGL_TRUE;
2086 }
2087
2088 static EGLBoolean
2089 dri2_post_sub_buffer(_EGLDisplay *disp, _EGLSurface *surf,
2090                      EGLint x, EGLint y, EGLint width, EGLint height)
2091 {
2092    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2093    if (!dri2_dpy->vtbl->post_sub_buffer)
2094       return EGL_FALSE;
2095    return dri2_dpy->vtbl->post_sub_buffer(disp, surf, x, y, width, height);
2096 }
2097
2098 static EGLBoolean
2099 dri2_copy_buffers(_EGLDisplay *disp, _EGLSurface *surf, void *native_pixmap_target)
2100 {
2101    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2102    if (!dri2_dpy->vtbl->copy_buffers)
2103       return _eglError(EGL_BAD_NATIVE_PIXMAP, "no support for native pixmaps");
2104    return dri2_dpy->vtbl->copy_buffers(disp, surf, native_pixmap_target);
2105 }
2106
2107 static EGLint
2108 dri2_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surf)
2109 {
2110    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2111    if (!dri2_dpy->vtbl->query_buffer_age)
2112       return 0;
2113    return dri2_dpy->vtbl->query_buffer_age(disp, surf);
2114 }
2115
2116 static EGLBoolean
2117 dri2_wait_client(_EGLDisplay *disp, _EGLContext *ctx)
2118 {
2119    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2120    _EGLSurface *surf = ctx->DrawSurface;
2121    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2122
2123    /* FIXME: If EGL allows frontbuffer rendering for window surfaces,
2124     * we need to copy fake to real here.*/
2125
2126    if (dri2_dpy->flush != NULL)
2127       dri2_dpy->flush->flush(dri_drawable);
2128
2129    return EGL_TRUE;
2130 }
2131
2132 static EGLBoolean
2133 dri2_wait_native(EGLint engine)
2134 {
2135    if (engine != EGL_CORE_NATIVE_ENGINE)
2136       return _eglError(EGL_BAD_PARAMETER, "eglWaitNative");
2137    /* glXWaitX(); */
2138
2139    return EGL_TRUE;
2140 }
2141
2142 static EGLBoolean
2143 dri2_bind_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2144 {
2145    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2146    struct dri2_egl_context *dri2_ctx;
2147    _EGLContext *ctx;
2148    GLint format, target;
2149    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2150
2151    ctx = _eglGetCurrentContext();
2152    dri2_ctx = dri2_egl_context(ctx);
2153
2154    if (!_eglBindTexImage(disp, surf, buffer))
2155       return EGL_FALSE;
2156
2157    switch (surf->TextureFormat) {
2158    case EGL_TEXTURE_RGB:
2159       format = __DRI_TEXTURE_FORMAT_RGB;
2160       break;
2161    case EGL_TEXTURE_RGBA:
2162       format = __DRI_TEXTURE_FORMAT_RGBA;
2163       break;
2164    default:
2165       assert(!"Unexpected texture format in dri2_bind_tex_image()");
2166       format = __DRI_TEXTURE_FORMAT_RGBA;
2167    }
2168
2169    switch (surf->TextureTarget) {
2170    case EGL_TEXTURE_2D:
2171       target = GL_TEXTURE_2D;
2172       break;
2173    default:
2174       target = GL_TEXTURE_2D;
2175       assert(!"Unexpected texture target in dri2_bind_tex_image()");
2176    }
2177
2178    dri2_dpy->tex_buffer->setTexBuffer2(dri2_ctx->dri_context,
2179                                        target, format,
2180                                        dri_drawable);
2181
2182    return EGL_TRUE;
2183 }
2184
2185 static EGLBoolean
2186 dri2_release_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2187 {
2188    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2189    struct dri2_egl_context *dri2_ctx;
2190    _EGLContext *ctx;
2191    GLint  target;
2192    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2193
2194    ctx = _eglGetCurrentContext();
2195    dri2_ctx = dri2_egl_context(ctx);
2196
2197    if (!_eglReleaseTexImage(disp, surf, buffer))
2198       return EGL_FALSE;
2199
2200    switch (surf->TextureTarget) {
2201    case EGL_TEXTURE_2D:
2202       target = GL_TEXTURE_2D;
2203       break;
2204    default:
2205       assert(!"missing texture target");
2206    }
2207
2208    if (dri2_dpy->tex_buffer->base.version >= 3 &&
2209        dri2_dpy->tex_buffer->releaseTexBuffer != NULL) {
2210       dri2_dpy->tex_buffer->releaseTexBuffer(dri2_ctx->dri_context,
2211                                              target, dri_drawable);
2212    }
2213
2214    return EGL_TRUE;
2215 }
2216
2217 static _EGLImage*
2218 dri2_create_image(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
2219                   EGLClientBuffer buffer, const EGLint *attr_list)
2220 {
2221    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2222    return dri2_dpy->vtbl->create_image(disp, ctx, target, buffer,
2223                                        attr_list);
2224 }
2225
2226 _EGLImage *
2227 dri2_create_image_from_dri(_EGLDisplay *disp, __DRIimage *dri_image)
2228 {
2229    struct dri2_egl_image *dri2_img;
2230
2231    if (dri_image == NULL) {
2232       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2233       return NULL;
2234    }
2235
2236    dri2_img = malloc(sizeof *dri2_img);
2237    if (!dri2_img) {
2238       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2239       return NULL;
2240    }
2241
2242    _eglInitImage(&dri2_img->base, disp);
2243
2244    dri2_img->dri_image = dri_image;
2245
2246    return &dri2_img->base;
2247 }
2248
2249 /**
2250  * Translate a DRI Image extension error code into an EGL error code.
2251  */
2252 static EGLint
2253 egl_error_from_dri_image_error(int dri_error)
2254 {
2255    switch (dri_error) {
2256    case __DRI_IMAGE_ERROR_SUCCESS:
2257       return EGL_SUCCESS;
2258    case __DRI_IMAGE_ERROR_BAD_ALLOC:
2259       return EGL_BAD_ALLOC;
2260    case __DRI_IMAGE_ERROR_BAD_MATCH:
2261       return EGL_BAD_MATCH;
2262    case __DRI_IMAGE_ERROR_BAD_PARAMETER:
2263       return EGL_BAD_PARAMETER;
2264    case __DRI_IMAGE_ERROR_BAD_ACCESS:
2265       return EGL_BAD_ACCESS;
2266    default:
2267       assert(!"unknown dri_error code");
2268       return EGL_BAD_ALLOC;
2269    }
2270 }
2271
2272 static _EGLImage *
2273 dri2_create_image_khr_renderbuffer(_EGLDisplay *disp, _EGLContext *ctx,
2274                                    EGLClientBuffer buffer,
2275                                    const EGLint *attr_list)
2276 {
2277    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2278    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2279    GLuint renderbuffer = (GLuint) (uintptr_t) buffer;
2280    __DRIimage *dri_image;
2281
2282    if (renderbuffer == 0) {
2283       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2284       return EGL_NO_IMAGE_KHR;
2285    }
2286
2287    if (!disp->Extensions.KHR_gl_renderbuffer_image) {
2288       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2289       return EGL_NO_IMAGE_KHR;
2290    }
2291
2292    if (dri2_dpy->image->base.version >= 17 &&
2293        dri2_dpy->image->createImageFromRenderbuffer2) {
2294       unsigned error = ~0;
2295
2296       dri_image = dri2_dpy->image->createImageFromRenderbuffer2(
2297                dri2_ctx->dri_context, renderbuffer, NULL, &error);
2298
2299       assert(!!dri_image == (error == __DRI_IMAGE_ERROR_SUCCESS));
2300
2301       if (!dri_image) {
2302          _eglError(egl_error_from_dri_image_error(error), "dri2_create_image_khr");
2303          return EGL_NO_IMAGE_KHR;
2304       }
2305    } else {
2306       dri_image = dri2_dpy->image->createImageFromRenderbuffer(
2307                dri2_ctx->dri_context, renderbuffer, NULL);
2308       if (!dri_image) {
2309          _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2310          return EGL_NO_IMAGE_KHR;
2311       }
2312    }
2313
2314    return dri2_create_image_from_dri(disp, dri_image);
2315 }
2316
2317 #ifdef HAVE_WAYLAND_PLATFORM
2318
2319 /* This structure describes how a wl_buffer maps to one or more
2320  * __DRIimages.  A wl_drm_buffer stores the wl_drm format code and the
2321  * offsets and strides of the planes in the buffer.  This table maps a
2322  * wl_drm format code to a description of the planes in the buffer
2323  * that lets us create a __DRIimage for each of the planes. */
2324
2325 static const struct wl_drm_components_descriptor {
2326    uint32_t dri_components;
2327    EGLint components;
2328    int nplanes;
2329 } wl_drm_components[] = {
2330    { __DRI_IMAGE_COMPONENTS_RGB, EGL_TEXTURE_RGB, 1 },
2331    { __DRI_IMAGE_COMPONENTS_RGBA, EGL_TEXTURE_RGBA, 1 },
2332    { __DRI_IMAGE_COMPONENTS_Y_U_V, EGL_TEXTURE_Y_U_V_WL, 3 },
2333    { __DRI_IMAGE_COMPONENTS_Y_UV, EGL_TEXTURE_Y_UV_WL, 2 },
2334    { __DRI_IMAGE_COMPONENTS_Y_XUXV, EGL_TEXTURE_Y_XUXV_WL, 2 },
2335 };
2336
2337 static _EGLImage *
2338 dri2_create_image_wayland_wl_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2339                                     EGLClientBuffer _buffer,
2340                                     const EGLint *attr_list)
2341 {
2342    struct wl_drm_buffer *buffer;
2343    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2344    const struct wl_drm_components_descriptor *f;
2345    __DRIimage *dri_image;
2346    _EGLImageAttribs attrs;
2347    int32_t plane;
2348
2349    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm,
2350                                    (struct wl_resource *) _buffer);
2351    if (!buffer)
2352        return NULL;
2353
2354    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2355       return NULL;
2356
2357    plane = attrs.PlaneWL;
2358    f = buffer->driver_format;
2359    if (plane < 0 || plane >= f->nplanes) {
2360       _eglError(EGL_BAD_PARAMETER,
2361                 "dri2_create_image_wayland_wl_buffer (plane out of bounds)");
2362       return NULL;
2363    }
2364
2365    dri_image = dri2_dpy->image->fromPlanar(buffer->driver_buffer, plane, NULL);
2366    if (dri_image == NULL && plane == 0)
2367       dri_image = dri2_dpy->image->dupImage(buffer->driver_buffer, NULL);
2368    if (dri_image == NULL) {
2369       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_wayland_wl_buffer");
2370       return NULL;
2371    }
2372
2373    return dri2_create_image_from_dri(disp, dri_image);
2374 }
2375 #endif
2376
2377 static EGLBoolean
2378 dri2_get_sync_values_chromium(_EGLDisplay *disp, _EGLSurface *surf,
2379                               EGLuint64KHR *ust, EGLuint64KHR *msc,
2380                               EGLuint64KHR *sbc)
2381 {
2382    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2383    if (!dri2_dpy->vtbl->get_sync_values)
2384       return EGL_FALSE;
2385    return dri2_dpy->vtbl->get_sync_values(disp, surf, ust, msc, sbc);
2386 }
2387
2388 static EGLBoolean
2389 dri2_get_msc_rate_angle(_EGLDisplay *disp, _EGLSurface *surf,
2390                         EGLint *numerator, EGLint *denominator)
2391 {
2392    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2393    if (!dri2_dpy->vtbl->get_msc_rate)
2394       return EGL_FALSE;
2395    return dri2_dpy->vtbl->get_msc_rate(disp, surf, numerator, denominator);
2396 }
2397
2398 /**
2399  * Set the error code after a call to
2400  * dri2_egl_image::dri_image::createImageFromTexture.
2401  */
2402 static void
2403 dri2_create_image_khr_texture_error(int dri_error)
2404 {
2405    EGLint egl_error = egl_error_from_dri_image_error(dri_error);
2406
2407    if (egl_error != EGL_SUCCESS)
2408       _eglError(egl_error, "dri2_create_image_khr_texture");
2409 }
2410
2411 static _EGLImage *
2412 dri2_create_image_khr_texture(_EGLDisplay *disp, _EGLContext *ctx,
2413                                    EGLenum target,
2414                                    EGLClientBuffer buffer,
2415                                    const EGLint *attr_list)
2416 {
2417    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2418    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2419    struct dri2_egl_image *dri2_img;
2420    GLuint texture = (GLuint) (uintptr_t) buffer;
2421    _EGLImageAttribs attrs;
2422    GLuint depth;
2423    GLenum gl_target;
2424    unsigned error;
2425
2426    if (texture == 0) {
2427       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2428       return EGL_NO_IMAGE_KHR;
2429    }
2430
2431    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2432       return EGL_NO_IMAGE_KHR;
2433
2434    switch (target) {
2435    case EGL_GL_TEXTURE_2D_KHR:
2436       if (!disp->Extensions.KHR_gl_texture_2D_image) {
2437          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2438          return EGL_NO_IMAGE_KHR;
2439       }
2440       depth = 0;
2441       gl_target = GL_TEXTURE_2D;
2442       break;
2443    case EGL_GL_TEXTURE_3D_KHR:
2444       if (!disp->Extensions.KHR_gl_texture_3D_image) {
2445          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2446          return EGL_NO_IMAGE_KHR;
2447       }
2448
2449       depth = attrs.GLTextureZOffset;
2450       gl_target = GL_TEXTURE_3D;
2451       break;
2452    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
2453    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
2454    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
2455    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
2456    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
2457    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
2458       if (!disp->Extensions.KHR_gl_texture_cubemap_image) {
2459          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2460          return EGL_NO_IMAGE_KHR;
2461       }
2462
2463       depth = target - EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR;
2464       gl_target = GL_TEXTURE_CUBE_MAP;
2465       break;
2466    default:
2467       unreachable("Unexpected target in dri2_create_image_khr_texture()");
2468       return EGL_NO_IMAGE_KHR;
2469    }
2470
2471    dri2_img = malloc(sizeof *dri2_img);
2472    if (!dri2_img) {
2473       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2474       return EGL_NO_IMAGE_KHR;
2475    }
2476
2477    _eglInitImage(&dri2_img->base, disp);
2478
2479    dri2_img->dri_image =
2480       dri2_dpy->image->createImageFromTexture(dri2_ctx->dri_context,
2481                                               gl_target,
2482                                               texture,
2483                                               depth,
2484                                               attrs.GLTextureLevel,
2485                                               &error,
2486                                               NULL);
2487    dri2_create_image_khr_texture_error(error);
2488
2489    if (!dri2_img->dri_image) {
2490       free(dri2_img);
2491       return EGL_NO_IMAGE_KHR;
2492    }
2493    return &dri2_img->base;
2494 }
2495
2496 static EGLBoolean
2497 dri2_query_surface(_EGLDisplay *disp, _EGLSurface *surf,
2498                    EGLint attribute, EGLint *value)
2499 {
2500    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2501    if (!dri2_dpy->vtbl->query_surface)
2502       return _eglQuerySurface(disp, surf, attribute, value);
2503    return dri2_dpy->vtbl->query_surface(disp, surf, attribute, value);
2504 }
2505
2506 static struct wl_buffer*
2507 dri2_create_wayland_buffer_from_image(_EGLDisplay *disp, _EGLImage *img)
2508 {
2509    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2510    if (!dri2_dpy->vtbl->create_wayland_buffer_from_image)
2511       return NULL;
2512    return dri2_dpy->vtbl->create_wayland_buffer_from_image(disp, img);
2513 }
2514
2515 #ifdef HAVE_LIBDRM
2516 static _EGLImage *
2517 dri2_create_image_mesa_drm_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2518                                   EGLClientBuffer buffer, const EGLint *attr_list)
2519 {
2520    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2521    EGLint format, name, pitch;
2522    _EGLImageAttribs attrs;
2523    __DRIimage *dri_image;
2524
2525    name = (EGLint) (uintptr_t) buffer;
2526
2527    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2528       return NULL;
2529
2530    if (attrs.Width <= 0 || attrs.Height <= 0 ||
2531        attrs.DRMBufferStrideMESA <= 0) {
2532       _eglError(EGL_BAD_PARAMETER,
2533                 "bad width, height or stride");
2534       return NULL;
2535    }
2536
2537    switch (attrs.DRMBufferFormatMESA) {
2538    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2539       format = __DRI_IMAGE_FORMAT_ARGB8888;
2540       pitch = attrs.DRMBufferStrideMESA;
2541       break;
2542    default:
2543       _eglError(EGL_BAD_PARAMETER,
2544                 "dri2_create_image_khr: unsupported pixmap depth");
2545       return NULL;
2546    }
2547
2548    dri_image =
2549       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
2550                                            attrs.Width,
2551                                            attrs.Height,
2552                                            format,
2553                                            name,
2554                                            pitch,
2555                                            NULL);
2556
2557    return dri2_create_image_from_dri(disp, dri_image);
2558 }
2559
2560 static EGLBoolean
2561 dri2_check_dma_buf_attribs(const _EGLImageAttribs *attrs)
2562 {
2563    /**
2564      * The spec says:
2565      *
2566      * "Required attributes and their values are as follows:
2567      *
2568      *  * EGL_WIDTH & EGL_HEIGHT: The logical dimensions of the buffer in pixels
2569      *
2570      *  * EGL_LINUX_DRM_FOURCC_EXT: The pixel format of the buffer, as specified
2571      *    by drm_fourcc.h and used as the pixel_format parameter of the
2572      *    drm_mode_fb_cmd2 ioctl."
2573      *
2574      * and
2575      *
2576      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2577      *    incomplete, EGL_BAD_PARAMETER is generated."
2578      */
2579    if (attrs->Width <= 0 || attrs->Height <= 0 ||
2580        !attrs->DMABufFourCC.IsPresent)
2581       return _eglError(EGL_BAD_PARAMETER, "attribute(s) missing");
2582
2583    /**
2584     * Also:
2585     *
2586     * "If <target> is EGL_LINUX_DMA_BUF_EXT and one or more of the values
2587     *  specified for a plane's pitch or offset isn't supported by EGL,
2588     *  EGL_BAD_ACCESS is generated."
2589     */
2590    for (unsigned i = 0; i < ARRAY_SIZE(attrs->DMABufPlanePitches); ++i) {
2591       if (attrs->DMABufPlanePitches[i].IsPresent &&
2592           attrs->DMABufPlanePitches[i].Value <= 0)
2593          return _eglError(EGL_BAD_ACCESS, "invalid pitch");
2594    }
2595
2596    /**
2597     * If <target> is EGL_LINUX_DMA_BUF_EXT, both or neither of the following
2598     * attribute values may be given.
2599     *
2600     * This is referring to EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT and
2601     * EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, and the same for other planes.
2602     */
2603    for (unsigned i = 0; i < DMA_BUF_MAX_PLANES; ++i) {
2604       if (attrs->DMABufPlaneModifiersLo[i].IsPresent !=
2605           attrs->DMABufPlaneModifiersHi[i].IsPresent)
2606          return _eglError(EGL_BAD_PARAMETER, "modifier attribute lo or hi missing");
2607    }
2608
2609    /* Although the EGL_EXT_image_dma_buf_import_modifiers spec doesn't
2610     * mandate it, we only accept the same modifier across all planes. */
2611    for (unsigned i = 1; i < DMA_BUF_MAX_PLANES; ++i) {
2612       if (attrs->DMABufPlaneFds[i].IsPresent) {
2613          if ((attrs->DMABufPlaneModifiersLo[0].IsPresent !=
2614                attrs->DMABufPlaneModifiersLo[i].IsPresent) ||
2615              (attrs->DMABufPlaneModifiersLo[0].Value !=
2616                attrs->DMABufPlaneModifiersLo[i].Value) ||
2617              (attrs->DMABufPlaneModifiersHi[0].Value !=
2618                attrs->DMABufPlaneModifiersHi[i].Value))
2619             return _eglError(EGL_BAD_PARAMETER, "modifier attributes not equal");
2620       }
2621    }
2622
2623    return EGL_TRUE;
2624 }
2625
2626 /* Returns the total number of planes for the format or zero if it isn't a
2627  * valid fourcc format.
2628  */
2629 static unsigned
2630 dri2_num_fourcc_format_planes(EGLint format)
2631 {
2632    switch (format) {
2633    case DRM_FORMAT_R8:
2634    case DRM_FORMAT_RG88:
2635    case DRM_FORMAT_GR88:
2636    case DRM_FORMAT_R16:
2637    case DRM_FORMAT_GR1616:
2638    case DRM_FORMAT_RGB332:
2639    case DRM_FORMAT_BGR233:
2640    case DRM_FORMAT_XRGB4444:
2641    case DRM_FORMAT_XBGR4444:
2642    case DRM_FORMAT_RGBX4444:
2643    case DRM_FORMAT_BGRX4444:
2644    case DRM_FORMAT_ARGB4444:
2645    case DRM_FORMAT_ABGR4444:
2646    case DRM_FORMAT_RGBA4444:
2647    case DRM_FORMAT_BGRA4444:
2648    case DRM_FORMAT_XRGB1555:
2649    case DRM_FORMAT_XBGR1555:
2650    case DRM_FORMAT_RGBX5551:
2651    case DRM_FORMAT_BGRX5551:
2652    case DRM_FORMAT_ARGB1555:
2653    case DRM_FORMAT_ABGR1555:
2654    case DRM_FORMAT_RGBA5551:
2655    case DRM_FORMAT_BGRA5551:
2656    case DRM_FORMAT_RGB565:
2657    case DRM_FORMAT_BGR565:
2658    case DRM_FORMAT_RGB888:
2659    case DRM_FORMAT_BGR888:
2660    case DRM_FORMAT_XRGB8888:
2661    case DRM_FORMAT_XBGR8888:
2662    case DRM_FORMAT_RGBX8888:
2663    case DRM_FORMAT_BGRX8888:
2664    case DRM_FORMAT_ARGB8888:
2665    case DRM_FORMAT_ABGR8888:
2666    case DRM_FORMAT_RGBA8888:
2667    case DRM_FORMAT_BGRA8888:
2668    case DRM_FORMAT_XRGB2101010:
2669    case DRM_FORMAT_XBGR2101010:
2670    case DRM_FORMAT_RGBX1010102:
2671    case DRM_FORMAT_BGRX1010102:
2672    case DRM_FORMAT_ARGB2101010:
2673    case DRM_FORMAT_ABGR2101010:
2674    case DRM_FORMAT_RGBA1010102:
2675    case DRM_FORMAT_BGRA1010102:
2676    case DRM_FORMAT_ABGR16161616:
2677    case DRM_FORMAT_XBGR16161616:
2678    case DRM_FORMAT_XBGR16161616F:
2679    case DRM_FORMAT_ABGR16161616F:
2680    case DRM_FORMAT_YUYV:
2681    case DRM_FORMAT_YVYU:
2682    case DRM_FORMAT_UYVY:
2683    case DRM_FORMAT_VYUY:
2684    case DRM_FORMAT_AYUV:
2685    case DRM_FORMAT_XYUV8888:
2686    case DRM_FORMAT_Y210:
2687    case DRM_FORMAT_Y212:
2688    case DRM_FORMAT_Y216:
2689    case DRM_FORMAT_Y410:
2690    case DRM_FORMAT_Y412:
2691    case DRM_FORMAT_Y416:
2692       return 1;
2693
2694    case DRM_FORMAT_NV12:
2695    case DRM_FORMAT_NV21:
2696    case DRM_FORMAT_NV16:
2697    case DRM_FORMAT_NV61:
2698    case DRM_FORMAT_P010:
2699    case DRM_FORMAT_P012:
2700    case DRM_FORMAT_P016:
2701       return 2;
2702
2703    case DRM_FORMAT_YUV410:
2704    case DRM_FORMAT_YVU410:
2705    case DRM_FORMAT_YUV411:
2706    case DRM_FORMAT_YVU411:
2707    case DRM_FORMAT_YUV420:
2708    case DRM_FORMAT_YVU420:
2709    case DRM_FORMAT_YUV422:
2710    case DRM_FORMAT_YVU422:
2711    case DRM_FORMAT_YUV444:
2712    case DRM_FORMAT_YVU444:
2713       return 3;
2714
2715    default:
2716       return 0;
2717    }
2718 }
2719
2720 /* Returns the total number of file descriptors. Zero indicates an error. */
2721 static unsigned
2722 dri2_check_dma_buf_format(const _EGLImageAttribs *attrs)
2723 {
2724    unsigned plane_n = dri2_num_fourcc_format_planes(attrs->DMABufFourCC.Value);
2725    if (plane_n == 0) {
2726       _eglError(EGL_BAD_MATCH, "unknown drm fourcc format");
2727       return 0;
2728    }
2729
2730    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; i++) {
2731       /**
2732        * The modifiers extension spec says:
2733        *
2734        * "Modifiers may modify any attribute of a buffer import, including
2735        *  but not limited to adding extra planes to a format which
2736        *  otherwise does not have those planes. As an example, a modifier
2737        *  may add a plane for an external compression buffer to a
2738        *  single-plane format. The exact meaning and effect of any
2739        *  modifier is canonically defined by drm_fourcc.h, not as part of
2740        *  this extension."
2741        */
2742       if (attrs->DMABufPlaneModifiersLo[i].IsPresent &&
2743           attrs->DMABufPlaneModifiersHi[i].IsPresent) {
2744          plane_n = i + 1;
2745       }
2746    }
2747
2748    /**
2749      * The spec says:
2750      *
2751      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2752      *    incomplete, EGL_BAD_PARAMETER is generated."
2753      */
2754    for (unsigned i = 0; i < plane_n; ++i) {
2755       if (!attrs->DMABufPlaneFds[i].IsPresent ||
2756           !attrs->DMABufPlaneOffsets[i].IsPresent ||
2757           !attrs->DMABufPlanePitches[i].IsPresent) {
2758          _eglError(EGL_BAD_PARAMETER, "plane attribute(s) missing");
2759          return 0;
2760       }
2761    }
2762
2763    /**
2764     * The spec also says:
2765     *
2766     * "If <target> is EGL_LINUX_DMA_BUF_EXT, and the EGL_LINUX_DRM_FOURCC_EXT
2767     *  attribute indicates a single-plane format, EGL_BAD_ATTRIBUTE is
2768     *  generated if any of the EGL_DMA_BUF_PLANE1_* or EGL_DMA_BUF_PLANE2_*
2769     *  or EGL_DMA_BUF_PLANE3_* attributes are specified."
2770     */
2771    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; ++i) {
2772       if (attrs->DMABufPlaneFds[i].IsPresent ||
2773           attrs->DMABufPlaneOffsets[i].IsPresent ||
2774           attrs->DMABufPlanePitches[i].IsPresent) {
2775          _eglError(EGL_BAD_ATTRIBUTE, "too many plane attributes");
2776          return 0;
2777       }
2778    }
2779
2780    return plane_n;
2781 }
2782
2783 static EGLBoolean
2784 dri2_query_dma_buf_formats(_EGLDisplay *disp, EGLint max,
2785                            EGLint *formats, EGLint *count)
2786 {
2787    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2788    if (max < 0 || (max > 0 && formats == NULL))
2789       return _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2790
2791    if (dri2_dpy->image->base.version < 15 ||
2792        dri2_dpy->image->queryDmaBufFormats == NULL)
2793       goto fail;
2794
2795    if (!dri2_dpy->image->queryDmaBufFormats(dri2_dpy->dri_screen, max,
2796                                             formats, count))
2797       goto fail;
2798
2799    if (max > 0) {
2800       /* Assert that all of the formats returned are actually fourcc formats.
2801        * Some day, if we want the internal interface function to be able to
2802        * return the fake fourcc formats defined in dri_interface.h, we'll have
2803        * to do something more clever here to pair the list down to just real
2804        * fourcc formats so that we don't leak the fake internal ones.
2805        */
2806       for (int i = 0; i < *count; i++) {
2807          assert(dri2_num_fourcc_format_planes(formats[i]) > 0);
2808       }
2809    }
2810
2811    return EGL_TRUE;
2812
2813 fail:
2814    return EGL_FALSE;
2815 }
2816
2817 static EGLBoolean
2818 dri2_query_dma_buf_modifiers(_EGLDisplay *disp, EGLint format,
2819                              EGLint max, EGLuint64KHR *modifiers,
2820                              EGLBoolean *external_only, EGLint *count)
2821 {
2822    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2823
2824    if (dri2_num_fourcc_format_planes(format) == 0)
2825       return _eglError(EGL_BAD_PARAMETER, "invalid fourcc format");
2826
2827    if (max < 0)
2828       return _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2829
2830    if (max > 0 && modifiers == NULL)
2831       return _eglError(EGL_BAD_PARAMETER, "invalid modifiers array");
2832
2833    if (dri2_dpy->image->base.version < 15 ||
2834        dri2_dpy->image->queryDmaBufModifiers == NULL)
2835       return EGL_FALSE;
2836
2837    if (dri2_dpy->image->queryDmaBufModifiers(dri2_dpy->dri_screen, format,
2838                                              max, modifiers,
2839                                              (unsigned int *) external_only,
2840                                              count) == false)
2841       return _eglError(EGL_BAD_PARAMETER, "invalid format");
2842
2843    return EGL_TRUE;
2844 }
2845
2846 /**
2847  * The spec says:
2848  *
2849  * "If eglCreateImageKHR is successful for a EGL_LINUX_DMA_BUF_EXT target, the
2850  *  EGL will take a reference to the dma_buf(s) which it will release at any
2851  *  time while the EGLDisplay is initialized. It is the responsibility of the
2852  *  application to close the dma_buf file descriptors."
2853  *
2854  * Therefore we must never close or otherwise modify the file descriptors.
2855  */
2856 _EGLImage *
2857 dri2_create_image_dma_buf(_EGLDisplay *disp, _EGLContext *ctx,
2858                           EGLClientBuffer buffer, const EGLint *attr_list)
2859 {
2860    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2861    _EGLImage *res;
2862    _EGLImageAttribs attrs;
2863    __DRIimage *dri_image;
2864    unsigned num_fds;
2865    int fds[DMA_BUF_MAX_PLANES];
2866    int pitches[DMA_BUF_MAX_PLANES];
2867    int offsets[DMA_BUF_MAX_PLANES];
2868    uint64_t modifier;
2869    bool has_modifier = false;
2870    unsigned error;
2871
2872    /**
2873     * The spec says:
2874     *
2875     * ""* If <target> is EGL_LINUX_DMA_BUF_EXT and <buffer> is not NULL, the
2876     *     error EGL_BAD_PARAMETER is generated."
2877     */
2878    if (buffer != NULL) {
2879       _eglError(EGL_BAD_PARAMETER, "buffer not NULL");
2880       return NULL;
2881    }
2882
2883    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2884       return NULL;
2885
2886    if (!dri2_check_dma_buf_attribs(&attrs))
2887       return NULL;
2888
2889    num_fds = dri2_check_dma_buf_format(&attrs);
2890    if (!num_fds)
2891       return NULL;
2892
2893    for (unsigned i = 0; i < num_fds; ++i) {
2894       fds[i] = attrs.DMABufPlaneFds[i].Value;
2895       pitches[i] = attrs.DMABufPlanePitches[i].Value;
2896       offsets[i] = attrs.DMABufPlaneOffsets[i].Value;
2897    }
2898
2899    /* dri2_check_dma_buf_attribs ensures that the modifier, if available,
2900     * will be present in attrs.DMABufPlaneModifiersLo[0] and
2901     * attrs.DMABufPlaneModifiersHi[0] */
2902    if (attrs.DMABufPlaneModifiersLo[0].IsPresent) {
2903       modifier = combine_u32_into_u64(attrs.DMABufPlaneModifiersHi[0].Value,
2904                                       attrs.DMABufPlaneModifiersLo[0].Value);
2905       has_modifier = true;
2906    }
2907
2908    if (attrs.ProtectedContent) {
2909       if (dri2_dpy->image->base.version < 18 ||
2910           dri2_dpy->image->createImageFromDmaBufs3 == NULL) {
2911          _eglError(EGL_BAD_MATCH, "unsupported protected_content attribute");
2912          return EGL_NO_IMAGE_KHR;
2913       }
2914       if (!has_modifier)
2915          modifier = DRM_FORMAT_MOD_INVALID;
2916
2917       dri_image =
2918          dri2_dpy->image->createImageFromDmaBufs3(dri2_dpy->dri_screen,
2919             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2920             modifier, fds, num_fds, pitches, offsets,
2921             attrs.DMABufYuvColorSpaceHint.Value,
2922             attrs.DMABufSampleRangeHint.Value,
2923             attrs.DMABufChromaHorizontalSiting.Value,
2924             attrs.DMABufChromaVerticalSiting.Value,
2925             attrs.ProtectedContent ? __DRI_IMAGE_PROTECTED_CONTENT_FLAG : 0,
2926             &error,
2927             NULL);
2928    }
2929    else if (has_modifier) {
2930       if (dri2_dpy->image->base.version < 15 ||
2931           dri2_dpy->image->createImageFromDmaBufs2 == NULL) {
2932          _eglError(EGL_BAD_MATCH, "unsupported dma_buf format modifier");
2933          return EGL_NO_IMAGE_KHR;
2934       }
2935       dri_image =
2936          dri2_dpy->image->createImageFromDmaBufs2(dri2_dpy->dri_screen,
2937             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2938             modifier, fds, num_fds, pitches, offsets,
2939             attrs.DMABufYuvColorSpaceHint.Value,
2940             attrs.DMABufSampleRangeHint.Value,
2941             attrs.DMABufChromaHorizontalSiting.Value,
2942             attrs.DMABufChromaVerticalSiting.Value,
2943             &error,
2944             NULL);
2945    }
2946    else {
2947       dri_image =
2948          dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
2949             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2950             fds, num_fds, pitches, offsets,
2951             attrs.DMABufYuvColorSpaceHint.Value,
2952             attrs.DMABufSampleRangeHint.Value,
2953             attrs.DMABufChromaHorizontalSiting.Value,
2954             attrs.DMABufChromaVerticalSiting.Value,
2955             &error,
2956             NULL);
2957    }
2958    dri2_create_image_khr_texture_error(error);
2959
2960    if (!dri_image)
2961       return EGL_NO_IMAGE_KHR;
2962
2963    res = dri2_create_image_from_dri(disp, dri_image);
2964
2965    return res;
2966 }
2967 static _EGLImage *
2968 dri2_create_drm_image_mesa(_EGLDisplay *disp, const EGLint *attr_list)
2969 {
2970    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2971    struct dri2_egl_image *dri2_img;
2972    _EGLImageAttribs attrs;
2973    unsigned int dri_use, valid_mask;
2974    int format;
2975
2976    if (!attr_list) {
2977       _eglError(EGL_BAD_PARAMETER, __func__);
2978       goto fail;
2979    }
2980
2981    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2982       goto fail;
2983
2984    if (attrs.Width <= 0 || attrs.Height <= 0) {
2985       _eglError(EGL_BAD_PARAMETER, __func__);
2986       goto fail;
2987    }
2988
2989    switch (attrs.DRMBufferFormatMESA) {
2990    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2991       format = __DRI_IMAGE_FORMAT_ARGB8888;
2992       break;
2993    default:
2994       _eglError(EGL_BAD_PARAMETER, __func__);
2995       goto fail;
2996    }
2997
2998    valid_mask =
2999       EGL_DRM_BUFFER_USE_SCANOUT_MESA |
3000       EGL_DRM_BUFFER_USE_SHARE_MESA |
3001       EGL_DRM_BUFFER_USE_CURSOR_MESA;
3002    if (attrs.DRMBufferUseMESA & ~valid_mask) {
3003       _eglError(EGL_BAD_PARAMETER, __func__);
3004       goto fail;
3005    }
3006
3007    dri_use = 0;
3008    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SHARE_MESA)
3009       dri_use |= __DRI_IMAGE_USE_SHARE;
3010    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SCANOUT_MESA)
3011       dri_use |= __DRI_IMAGE_USE_SCANOUT;
3012    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_CURSOR_MESA)
3013       dri_use |= __DRI_IMAGE_USE_CURSOR;
3014
3015    dri2_img = malloc(sizeof *dri2_img);
3016    if (!dri2_img) {
3017       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
3018       goto fail;
3019    }
3020
3021    _eglInitImage(&dri2_img->base, disp);
3022
3023    dri2_img->dri_image =
3024       dri2_dpy->image->createImage(dri2_dpy->dri_screen,
3025                                    attrs.Width, attrs.Height,
3026                                    format, dri_use, dri2_img);
3027    if (dri2_img->dri_image == NULL) {
3028       free(dri2_img);
3029       _eglError(EGL_BAD_ALLOC, "dri2_create_drm_image_mesa");
3030       goto fail;
3031    }
3032
3033    return &dri2_img->base;
3034
3035 fail:
3036    return EGL_NO_IMAGE_KHR;
3037 }
3038
3039 static EGLBoolean
3040 dri2_export_drm_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3041                           EGLint *name, EGLint *handle, EGLint *stride)
3042 {
3043    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3044    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3045
3046    if (name && !dri2_dpy->image->queryImage(dri2_img->dri_image,
3047                                             __DRI_IMAGE_ATTRIB_NAME, name))
3048       return _eglError(EGL_BAD_ALLOC, "dri2_export_drm_image_mesa");
3049
3050    if (handle)
3051       dri2_dpy->image->queryImage(dri2_img->dri_image,
3052                                   __DRI_IMAGE_ATTRIB_HANDLE, handle);
3053
3054    if (stride)
3055       dri2_dpy->image->queryImage(dri2_img->dri_image,
3056                                   __DRI_IMAGE_ATTRIB_STRIDE, stride);
3057
3058    return EGL_TRUE;
3059 }
3060
3061 /**
3062  * Checks if we can support EGL_MESA_image_dma_buf_export on this image.
3063
3064  * The spec provides a boolean return for the driver to reject exporting for
3065  * basically any reason, but doesn't specify any particular error cases.  For
3066  * now, we just fail if we don't have a DRM fourcc for the format.
3067  */
3068 static bool
3069 dri2_can_export_dma_buf_image(_EGLDisplay *disp, _EGLImage *img)
3070 {
3071    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3072    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3073    EGLint fourcc;
3074
3075    if (!dri2_dpy->image->queryImage(dri2_img->dri_image,
3076                                     __DRI_IMAGE_ATTRIB_FOURCC, &fourcc)) {
3077       return false;
3078    }
3079
3080    return true;
3081 }
3082
3083 static EGLBoolean
3084 dri2_export_dma_buf_image_query_mesa(_EGLDisplay *disp, _EGLImage *img,
3085                                      EGLint *fourcc, EGLint *nplanes,
3086                                      EGLuint64KHR *modifiers)
3087 {
3088    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3089    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3090    int num_planes;
3091
3092    if (!dri2_can_export_dma_buf_image(disp, img))
3093       return EGL_FALSE;
3094
3095    dri2_dpy->image->queryImage(dri2_img->dri_image,
3096                                __DRI_IMAGE_ATTRIB_NUM_PLANES, &num_planes);
3097    if (nplanes)
3098      *nplanes = num_planes;
3099
3100    if (fourcc)
3101       dri2_dpy->image->queryImage(dri2_img->dri_image,
3102                                   __DRI_IMAGE_ATTRIB_FOURCC, fourcc);
3103
3104    if (modifiers) {
3105       int mod_hi, mod_lo;
3106       uint64_t modifier = DRM_FORMAT_MOD_INVALID;
3107       bool query;
3108
3109       query = dri2_dpy->image->queryImage(dri2_img->dri_image,
3110                                           __DRI_IMAGE_ATTRIB_MODIFIER_UPPER,
3111                                           &mod_hi);
3112       query &= dri2_dpy->image->queryImage(dri2_img->dri_image,
3113                                            __DRI_IMAGE_ATTRIB_MODIFIER_LOWER,
3114                                            &mod_lo);
3115       if (query)
3116          modifier = combine_u32_into_u64 (mod_hi, mod_lo);
3117
3118       for (int i = 0; i < num_planes; i++)
3119         modifiers[i] = modifier;
3120    }
3121
3122    return EGL_TRUE;
3123 }
3124
3125 static EGLBoolean
3126 dri2_export_dma_buf_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3127                                int *fds, EGLint *strides, EGLint *offsets)
3128 {
3129    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3130    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3131    EGLint nplanes;
3132
3133    if (!dri2_can_export_dma_buf_image(disp, img))
3134       return EGL_FALSE;
3135
3136    /* EGL_MESA_image_dma_buf_export spec says:
3137     *    "If the number of fds is less than the number of planes, then
3138     *    subsequent fd slots should contain -1."
3139     */
3140    if (fds) {
3141       /* Query nplanes so that we know how big the given array is. */
3142       dri2_dpy->image->queryImage(dri2_img->dri_image,
3143                                   __DRI_IMAGE_ATTRIB_NUM_PLANES, &nplanes);
3144       memset(fds, -1, nplanes * sizeof(int));
3145    }
3146
3147    /* rework later to provide multiple fds/strides/offsets */
3148    if (fds)
3149       dri2_dpy->image->queryImage(dri2_img->dri_image,
3150                                   __DRI_IMAGE_ATTRIB_FD, fds);
3151
3152    if (strides)
3153       dri2_dpy->image->queryImage(dri2_img->dri_image,
3154                                   __DRI_IMAGE_ATTRIB_STRIDE, strides);
3155
3156    if (offsets) {
3157       int img_offset;
3158       bool ret = dri2_dpy->image->queryImage(dri2_img->dri_image,
3159                      __DRI_IMAGE_ATTRIB_OFFSET, &img_offset);
3160       if (ret)
3161          offsets[0] = img_offset;
3162       else
3163          offsets[0] = 0;
3164    }
3165
3166    return EGL_TRUE;
3167 }
3168
3169 #endif
3170
3171 _EGLImage *
3172 dri2_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
3173                       EGLClientBuffer buffer, const EGLint *attr_list)
3174 {
3175    switch (target) {
3176    case EGL_GL_TEXTURE_2D_KHR:
3177    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
3178    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
3179    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
3180    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
3181    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
3182    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
3183    case EGL_GL_TEXTURE_3D_KHR:
3184       return dri2_create_image_khr_texture(disp, ctx, target, buffer, attr_list);
3185    case EGL_GL_RENDERBUFFER_KHR:
3186       return dri2_create_image_khr_renderbuffer(disp, ctx, buffer, attr_list);
3187 #ifdef HAVE_LIBDRM
3188    case EGL_DRM_BUFFER_MESA:
3189       return dri2_create_image_mesa_drm_buffer(disp, ctx, buffer, attr_list);
3190    case EGL_LINUX_DMA_BUF_EXT:
3191       return dri2_create_image_dma_buf(disp, ctx, buffer, attr_list);
3192 #endif
3193 #ifdef HAVE_WAYLAND_PLATFORM
3194    case EGL_WAYLAND_BUFFER_WL:
3195       return dri2_create_image_wayland_wl_buffer(disp, ctx, buffer, attr_list);
3196 #endif
3197    default:
3198       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
3199       return EGL_NO_IMAGE_KHR;
3200    }
3201 }
3202
3203 static EGLBoolean
3204 dri2_destroy_image_khr(_EGLDisplay *disp, _EGLImage *image)
3205 {
3206    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3207    struct dri2_egl_image *dri2_img = dri2_egl_image(image);
3208
3209    dri2_dpy->image->destroyImage(dri2_img->dri_image);
3210    free(dri2_img);
3211
3212    return EGL_TRUE;
3213 }
3214
3215 #ifdef HAVE_WAYLAND_PLATFORM
3216
3217 static void
3218 dri2_wl_reference_buffer(void *user_data, uint32_t name, int fd,
3219                          struct wl_drm_buffer *buffer)
3220 {
3221    _EGLDisplay *disp = user_data;
3222    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3223    __DRIimage *img;
3224    int dri_components = 0;
3225
3226    if (fd == -1)
3227       img = dri2_dpy->image->createImageFromNames(dri2_dpy->dri_screen,
3228                                                   buffer->width,
3229                                                   buffer->height,
3230                                                   buffer->format,
3231                                                   (int*)&name, 1,
3232                                                   buffer->stride,
3233                                                   buffer->offset,
3234                                                   NULL);
3235    else
3236       img = dri2_dpy->image->createImageFromFds(dri2_dpy->dri_screen,
3237                                                 buffer->width,
3238                                                 buffer->height,
3239                                                 buffer->format,
3240                                                 &fd, 1,
3241                                                 buffer->stride,
3242                                                 buffer->offset,
3243                                                 NULL);
3244
3245    if (img == NULL)
3246       return;
3247
3248    dri2_dpy->image->queryImage(img, __DRI_IMAGE_ATTRIB_COMPONENTS, &dri_components);
3249
3250    buffer->driver_format = NULL;
3251    for (int i = 0; i < ARRAY_SIZE(wl_drm_components); i++)
3252       if (wl_drm_components[i].dri_components == dri_components)
3253          buffer->driver_format = &wl_drm_components[i];
3254
3255    if (buffer->driver_format == NULL)
3256       dri2_dpy->image->destroyImage(img);
3257    else
3258       buffer->driver_buffer = img;
3259 }
3260
3261 static void
3262 dri2_wl_release_buffer(void *user_data, struct wl_drm_buffer *buffer)
3263 {
3264    _EGLDisplay *disp = user_data;
3265    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3266
3267    dri2_dpy->image->destroyImage(buffer->driver_buffer);
3268 }
3269
3270 static EGLBoolean
3271 dri2_bind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3272 {
3273    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3274    const struct wayland_drm_callbacks wl_drm_callbacks = {
3275       .authenticate = (int(*)(void *, uint32_t)) dri2_dpy->vtbl->authenticate,
3276       .reference_buffer = dri2_wl_reference_buffer,
3277       .release_buffer = dri2_wl_release_buffer,
3278       .is_format_supported = dri2_wl_is_format_supported
3279    };
3280    int flags = 0;
3281    char *device_name;
3282    uint64_t cap;
3283
3284    if (dri2_dpy->wl_server_drm)
3285       goto fail;
3286
3287    device_name = drmGetRenderDeviceNameFromFd(dri2_dpy->fd);
3288    if (!device_name)
3289       device_name = strdup(dri2_dpy->device_name);
3290    if (!device_name)
3291       goto fail;
3292
3293    if (drmGetCap(dri2_dpy->fd, DRM_CAP_PRIME, &cap) == 0 &&
3294        cap == (DRM_PRIME_CAP_IMPORT | DRM_PRIME_CAP_EXPORT) &&
3295        dri2_dpy->image->base.version >= 7 &&
3296        dri2_dpy->image->createImageFromFds != NULL)
3297       flags |= WAYLAND_DRM_PRIME;
3298
3299    dri2_dpy->wl_server_drm =
3300            wayland_drm_init(wl_dpy, device_name,
3301                             &wl_drm_callbacks, disp, flags);
3302
3303    free(device_name);
3304
3305    if (!dri2_dpy->wl_server_drm)
3306       goto fail;
3307
3308 #ifdef HAVE_DRM_PLATFORM
3309    /* We have to share the wl_drm instance with gbm, so gbm can convert
3310     * wl_buffers to gbm bos. */
3311    if (dri2_dpy->gbm_dri)
3312       dri2_dpy->gbm_dri->wl_drm = dri2_dpy->wl_server_drm;
3313 #endif
3314
3315    return EGL_TRUE;
3316
3317 fail:
3318    return EGL_FALSE;
3319 }
3320
3321 static EGLBoolean
3322 dri2_unbind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3323 {
3324    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3325
3326    if (!dri2_dpy->wl_server_drm)
3327            return EGL_FALSE;
3328
3329    wayland_drm_uninit(dri2_dpy->wl_server_drm);
3330    dri2_dpy->wl_server_drm = NULL;
3331
3332    return EGL_TRUE;
3333 }
3334
3335 static EGLBoolean
3336 dri2_query_wayland_buffer_wl(_EGLDisplay *disp, struct wl_resource *buffer_resource,
3337                              EGLint attribute, EGLint *value)
3338 {
3339    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3340    struct wl_drm_buffer *buffer;
3341    const struct wl_drm_components_descriptor *format;
3342
3343    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm, buffer_resource);
3344    if (!buffer)
3345       return EGL_FALSE;
3346
3347    format = buffer->driver_format;
3348    switch (attribute) {
3349    case EGL_TEXTURE_FORMAT:
3350       *value = format->components;
3351       return EGL_TRUE;
3352    case EGL_WIDTH:
3353       *value = buffer->width;
3354       return EGL_TRUE;
3355    case EGL_HEIGHT:
3356       *value = buffer->height;
3357       return EGL_TRUE;
3358    }
3359
3360    return EGL_FALSE;
3361 }
3362 #endif
3363
3364 static void
3365 dri2_egl_ref_sync(struct dri2_egl_sync *sync)
3366 {
3367    p_atomic_inc(&sync->refcount);
3368 }
3369
3370 static void
3371 dri2_egl_unref_sync(struct dri2_egl_display *dri2_dpy,
3372                     struct dri2_egl_sync *dri2_sync)
3373 {
3374    if (p_atomic_dec_zero(&dri2_sync->refcount)) {
3375       switch (dri2_sync->base.Type) {
3376       case EGL_SYNC_REUSABLE_KHR:
3377          cnd_destroy(&dri2_sync->cond);
3378          break;
3379       case EGL_SYNC_NATIVE_FENCE_ANDROID:
3380          if (dri2_sync->base.SyncFd != EGL_NO_NATIVE_FENCE_FD_ANDROID)
3381             close(dri2_sync->base.SyncFd);
3382          break;
3383       default:
3384          break;
3385       }
3386
3387       if (dri2_sync->fence)
3388          dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, dri2_sync->fence);
3389
3390       free(dri2_sync);
3391    }
3392 }
3393
3394 static _EGLSync *
3395 dri2_create_sync(_EGLDisplay *disp, EGLenum type, const EGLAttrib *attrib_list)
3396 {
3397    _EGLContext *ctx = _eglGetCurrentContext();
3398    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3399    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3400    struct dri2_egl_sync *dri2_sync;
3401    EGLint ret;
3402    pthread_condattr_t attr;
3403
3404    dri2_sync = calloc(1, sizeof(struct dri2_egl_sync));
3405    if (!dri2_sync) {
3406       _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3407       goto fail;
3408    }
3409
3410    if (!_eglInitSync(&dri2_sync->base, disp, type, attrib_list)) {
3411       goto fail;
3412    }
3413
3414    switch (type) {
3415    case EGL_SYNC_FENCE_KHR:
3416       dri2_sync->fence = dri2_dpy->fence->create_fence(dri2_ctx->dri_context);
3417       if (!dri2_sync->fence) {
3418          /* Why did it fail? DRI doesn't return an error code, so we emit
3419           * a generic EGL error that doesn't communicate user error.
3420           */
3421          _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3422          goto fail;
3423       }
3424       break;
3425
3426    case EGL_SYNC_CL_EVENT_KHR:
3427       dri2_sync->fence = dri2_dpy->fence->get_fence_from_cl_event(
3428                                  dri2_dpy->dri_screen,
3429                                  dri2_sync->base.CLEvent);
3430       /* this can only happen if the cl_event passed in is invalid. */
3431       if (!dri2_sync->fence) {
3432          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3433          goto fail;
3434       }
3435
3436       /* the initial status must be "signaled" if the cl_event is signaled */
3437       if (dri2_dpy->fence->client_wait_sync(dri2_ctx->dri_context,
3438                                             dri2_sync->fence, 0, 0))
3439          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3440       break;
3441
3442    case EGL_SYNC_REUSABLE_KHR:
3443       /* intialize attr */
3444       ret = pthread_condattr_init(&attr);
3445
3446       if (ret) {
3447          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3448          goto fail;
3449       }
3450
3451       /* change clock attribute to CLOCK_MONOTONIC */
3452       ret = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
3453
3454       if (ret) {
3455          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3456          goto fail;
3457       }
3458
3459       ret = pthread_cond_init(&dri2_sync->cond, &attr);
3460
3461       if (ret) {
3462          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3463          goto fail;
3464       }
3465
3466       /* initial status of reusable sync must be "unsignaled" */
3467       dri2_sync->base.SyncStatus = EGL_UNSIGNALED_KHR;
3468       break;
3469
3470    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3471       if (dri2_dpy->fence->create_fence_fd) {
3472          dri2_sync->fence = dri2_dpy->fence->create_fence_fd(
3473                                     dri2_ctx->dri_context,
3474                                     dri2_sync->base.SyncFd);
3475       }
3476       if (!dri2_sync->fence) {
3477          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3478          goto fail;
3479       }
3480       break;
3481    }
3482
3483    p_atomic_set(&dri2_sync->refcount, 1);
3484    return &dri2_sync->base;
3485
3486 fail:
3487    free(dri2_sync);
3488    return NULL;
3489 }
3490
3491 static EGLBoolean
3492 dri2_destroy_sync(_EGLDisplay *disp, _EGLSync *sync)
3493 {
3494    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3495    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3496    EGLint ret = EGL_TRUE;
3497    EGLint err;
3498
3499    /* if type of sync is EGL_SYNC_REUSABLE_KHR and it is not signaled yet,
3500     * then unlock all threads possibly blocked by the reusable sync before
3501     * destroying it.
3502     */
3503    if (dri2_sync->base.Type == EGL_SYNC_REUSABLE_KHR &&
3504        dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3505       dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3506       /* unblock all threads currently blocked by sync */
3507       err = cnd_broadcast(&dri2_sync->cond);
3508
3509       if (err) {
3510          _eglError(EGL_BAD_ACCESS, "eglDestroySyncKHR");
3511          ret = EGL_FALSE;
3512       }
3513    }
3514
3515    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3516
3517    return ret;
3518 }
3519
3520 static EGLint
3521 dri2_dup_native_fence_fd(_EGLDisplay *disp, _EGLSync *sync)
3522 {
3523    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3524    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3525
3526    assert(sync->Type == EGL_SYNC_NATIVE_FENCE_ANDROID);
3527
3528    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3529       /* try to retrieve the actual native fence fd.. if rendering is
3530        * not flushed this will just return -1, aka NO_NATIVE_FENCE_FD:
3531        */
3532       sync->SyncFd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
3533                                                    dri2_sync->fence);
3534    }
3535
3536    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3537       /* if native fence fd still not created, return an error: */
3538       _eglError(EGL_BAD_PARAMETER, "eglDupNativeFenceFDANDROID");
3539       return EGL_NO_NATIVE_FENCE_FD_ANDROID;
3540    }
3541
3542    assert(sync_valid_fd(sync->SyncFd));
3543
3544    return os_dupfd_cloexec(sync->SyncFd);
3545 }
3546
3547 static void
3548 dri2_set_blob_cache_funcs(_EGLDisplay *disp,
3549                           EGLSetBlobFuncANDROID set,
3550                           EGLGetBlobFuncANDROID get)
3551 {
3552    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3553    dri2_dpy->blob->set_cache_funcs(dri2_dpy->dri_screen,
3554                                    disp->BlobCacheSet,
3555                                    disp->BlobCacheGet);
3556 }
3557
3558 static EGLint
3559 dri2_client_wait_sync(_EGLDisplay *disp, _EGLSync *sync,
3560                       EGLint flags, EGLTime timeout)
3561 {
3562    _EGLContext *ctx = _eglGetCurrentContext();
3563    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3564    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3565    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3566    unsigned wait_flags = 0;
3567
3568    EGLint ret = EGL_CONDITION_SATISFIED_KHR;
3569
3570    /* The EGL_KHR_fence_sync spec states:
3571     *
3572     *    "If no context is current for the bound API,
3573     *     the EGL_SYNC_FLUSH_COMMANDS_BIT_KHR bit is ignored.
3574     */
3575    if (dri2_ctx && flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)
3576       wait_flags |= __DRI2_FENCE_FLAG_FLUSH_COMMANDS;
3577
3578    /* the sync object should take a reference while waiting */
3579    dri2_egl_ref_sync(dri2_sync);
3580
3581    switch (sync->Type) {
3582    case EGL_SYNC_FENCE_KHR:
3583    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3584    case EGL_SYNC_CL_EVENT_KHR:
3585       if (dri2_dpy->fence->client_wait_sync(dri2_ctx ? dri2_ctx->dri_context : NULL,
3586                                          dri2_sync->fence, wait_flags,
3587                                          timeout))
3588          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3589       else
3590          ret = EGL_TIMEOUT_EXPIRED_KHR;
3591       break;
3592
3593    case EGL_SYNC_REUSABLE_KHR:
3594       if (dri2_ctx && dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR &&
3595           (flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)) {
3596          /* flush context if EGL_SYNC_FLUSH_COMMANDS_BIT_KHR is set */
3597          dri2_gl_flush();
3598       }
3599
3600       /* if timeout is EGL_FOREVER_KHR, it should wait without any timeout.*/
3601       if (timeout == EGL_FOREVER_KHR) {
3602          mtx_lock(&dri2_sync->mutex);
3603          cnd_wait(&dri2_sync->cond, &dri2_sync->mutex);
3604          mtx_unlock(&dri2_sync->mutex);
3605       } else {
3606          /* if reusable sync has not been yet signaled */
3607          if (dri2_sync->base.SyncStatus != EGL_SIGNALED_KHR) {
3608             /* timespecs for cnd_timedwait */
3609             struct timespec current;
3610             struct timespec expire;
3611
3612             /* We override the clock to monotonic when creating the condition
3613              * variable. */
3614             clock_gettime(CLOCK_MONOTONIC, &current);
3615
3616             /* calculating when to expire */
3617             expire.tv_nsec = timeout % 1000000000L;
3618             expire.tv_sec = timeout / 1000000000L;
3619
3620             expire.tv_nsec += current.tv_nsec;
3621             expire.tv_sec += current.tv_sec;
3622
3623             /* expire.nsec now is a number between 0 and 1999999998 */
3624             if (expire.tv_nsec > 999999999L) {
3625                expire.tv_sec++;
3626                expire.tv_nsec -= 1000000000L;
3627             }
3628
3629             mtx_lock(&dri2_sync->mutex);
3630             ret = cnd_timedwait(&dri2_sync->cond, &dri2_sync->mutex, &expire);
3631             mtx_unlock(&dri2_sync->mutex);
3632
3633             if (ret == thrd_timedout) {
3634                if (dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3635                   ret = EGL_TIMEOUT_EXPIRED_KHR;
3636                } else {
3637                   _eglError(EGL_BAD_ACCESS, "eglClientWaitSyncKHR");
3638                   ret = EGL_FALSE;
3639                }
3640             }
3641          }
3642       }
3643       break;
3644    }
3645
3646    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3647
3648    return ret;
3649 }
3650
3651 static EGLBoolean
3652 dri2_signal_sync(_EGLDisplay *disp, _EGLSync *sync, EGLenum mode)
3653 {
3654    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3655    EGLint ret;
3656
3657    if (sync->Type != EGL_SYNC_REUSABLE_KHR)
3658       return _eglError(EGL_BAD_MATCH, "eglSignalSyncKHR");
3659
3660    if (mode != EGL_SIGNALED_KHR && mode != EGL_UNSIGNALED_KHR)
3661       return _eglError(EGL_BAD_ATTRIBUTE, "eglSignalSyncKHR");
3662
3663    dri2_sync->base.SyncStatus = mode;
3664
3665    if (mode == EGL_SIGNALED_KHR) {
3666       ret = cnd_broadcast(&dri2_sync->cond);
3667
3668       /* fail to broadcast */
3669       if (ret)
3670          return _eglError(EGL_BAD_ACCESS, "eglSignalSyncKHR");
3671    }
3672
3673    return EGL_TRUE;
3674 }
3675
3676 static EGLint
3677 dri2_server_wait_sync(_EGLDisplay *disp, _EGLSync *sync)
3678 {
3679    _EGLContext *ctx = _eglGetCurrentContext();
3680    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3681    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3682    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3683
3684    dri2_dpy->fence->server_wait_sync(dri2_ctx->dri_context,
3685                                      dri2_sync->fence, 0);
3686    return EGL_TRUE;
3687 }
3688
3689 static int
3690 dri2_interop_query_device_info(_EGLDisplay *disp, _EGLContext *ctx,
3691                                struct mesa_glinterop_device_info *out)
3692 {
3693    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3694    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3695
3696    if (!dri2_dpy->interop)
3697       return MESA_GLINTEROP_UNSUPPORTED;
3698
3699    return dri2_dpy->interop->query_device_info(dri2_ctx->dri_context, out);
3700 }
3701
3702 static int
3703 dri2_interop_export_object(_EGLDisplay *disp, _EGLContext *ctx,
3704                            struct mesa_glinterop_export_in *in,
3705                            struct mesa_glinterop_export_out *out)
3706 {
3707    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3708    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3709
3710    if (!dri2_dpy->interop)
3711       return MESA_GLINTEROP_UNSUPPORTED;
3712
3713    return dri2_dpy->interop->export_object(dri2_ctx->dri_context, in, out);
3714 }
3715
3716 const _EGLDriver _eglDriver = {
3717    .Initialize = dri2_initialize,
3718    .Terminate = dri2_terminate,
3719    .CreateContext = dri2_create_context,
3720    .DestroyContext = dri2_destroy_context,
3721    .MakeCurrent = dri2_make_current,
3722    .CreateWindowSurface = dri2_create_window_surface,
3723    .CreatePixmapSurface = dri2_create_pixmap_surface,
3724    .CreatePbufferSurface = dri2_create_pbuffer_surface,
3725    .DestroySurface = dri2_destroy_surface,
3726    .GetProcAddress = dri2_get_proc_address,
3727    .WaitClient = dri2_wait_client,
3728    .WaitNative = dri2_wait_native,
3729    .BindTexImage = dri2_bind_tex_image,
3730    .ReleaseTexImage = dri2_release_tex_image,
3731    .SwapInterval = dri2_swap_interval,
3732    .SwapBuffers = dri2_swap_buffers,
3733    .SwapBuffersWithDamageEXT = dri2_swap_buffers_with_damage,
3734    .SwapBuffersRegionNOK = dri2_swap_buffers_region,
3735    .SetDamageRegion = dri2_set_damage_region,
3736    .PostSubBufferNV = dri2_post_sub_buffer,
3737    .CopyBuffers = dri2_copy_buffers,
3738    .QueryBufferAge = dri2_query_buffer_age,
3739    .CreateImageKHR = dri2_create_image,
3740    .DestroyImageKHR = dri2_destroy_image_khr,
3741    .CreateWaylandBufferFromImageWL = dri2_create_wayland_buffer_from_image,
3742    .QuerySurface = dri2_query_surface,
3743    .QueryDriverName = dri2_query_driver_name,
3744    .QueryDriverConfig = dri2_query_driver_config,
3745 #ifdef HAVE_LIBDRM
3746    .CreateDRMImageMESA = dri2_create_drm_image_mesa,
3747    .ExportDRMImageMESA = dri2_export_drm_image_mesa,
3748    .ExportDMABUFImageQueryMESA = dri2_export_dma_buf_image_query_mesa,
3749    .ExportDMABUFImageMESA = dri2_export_dma_buf_image_mesa,
3750    .QueryDmaBufFormatsEXT = dri2_query_dma_buf_formats,
3751    .QueryDmaBufModifiersEXT = dri2_query_dma_buf_modifiers,
3752 #endif
3753 #ifdef HAVE_WAYLAND_PLATFORM
3754    .BindWaylandDisplayWL = dri2_bind_wayland_display_wl,
3755    .UnbindWaylandDisplayWL = dri2_unbind_wayland_display_wl,
3756    .QueryWaylandBufferWL = dri2_query_wayland_buffer_wl,
3757 #endif
3758    .GetSyncValuesCHROMIUM = dri2_get_sync_values_chromium,
3759    .GetMscRateANGLE = dri2_get_msc_rate_angle,
3760    .CreateSyncKHR = dri2_create_sync,
3761    .ClientWaitSyncKHR = dri2_client_wait_sync,
3762    .SignalSyncKHR = dri2_signal_sync,
3763    .WaitSyncKHR = dri2_server_wait_sync,
3764    .DestroySyncKHR = dri2_destroy_sync,
3765    .GLInteropQueryDeviceInfo = dri2_interop_query_device_info,
3766    .GLInteropExportObject = dri2_interop_export_object,
3767    .DupNativeFenceFDANDROID = dri2_dup_native_fence_fd,
3768    .SetBlobCacheFuncsANDROID = dri2_set_blob_cache_funcs,
3769 };