egl/x11: implement ANGLE_sync_control_rate
[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    mtx_lock(&disp->Mutex);
660    img = _eglLookupImage(image, disp);
661    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          free(dri2_ctx);
1547          return NULL;
1548       }
1549       break;
1550    case EGL_OPENGL_API:
1551       if ((dri2_ctx->base.ClientMajorVersion >= 4
1552            || (dri2_ctx->base.ClientMajorVersion == 3
1553                && dri2_ctx->base.ClientMinorVersion >= 2))
1554           && dri2_ctx->base.Profile == EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR)
1555          api = __DRI_API_OPENGL_CORE;
1556       else if (dri2_ctx->base.ClientMajorVersion == 3 &&
1557                dri2_ctx->base.ClientMinorVersion == 1)
1558          api = __DRI_API_OPENGL_CORE;
1559       else
1560          api = __DRI_API_OPENGL;
1561       break;
1562    default:
1563       _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
1564       free(dri2_ctx);
1565       return NULL;
1566    }
1567
1568    if (conf != NULL) {
1569       /* The config chosen here isn't necessarily
1570        * used for surfaces later.
1571        * A pixmap surface will use the single config.
1572        * This opportunity depends on disabling the
1573        * doubleBufferMode check in
1574        * src/mesa/main/context.c:check_compatible()
1575        */
1576       if (dri2_config->dri_config[1][0])
1577          dri_config = dri2_config->dri_config[1][0];
1578       else
1579          dri_config = dri2_config->dri_config[0][0];
1580    }
1581    else
1582       dri_config = NULL;
1583
1584    if (!dri2_fill_context_attribs(dri2_ctx, dri2_dpy, ctx_attribs,
1585                                   &num_attribs))
1586       goto cleanup;
1587
1588    if (dri2_dpy->image_driver) {
1589       dri2_ctx->dri_context =
1590          dri2_dpy->image_driver->createContextAttribs(dri2_dpy->dri_screen,
1591                                                       api,
1592                                                       dri_config,
1593                                                       shared,
1594                                                       num_attribs / 2,
1595                                                       ctx_attribs,
1596                                                       & error,
1597                                                       dri2_ctx);
1598       dri2_create_context_attribs_error(error);
1599    } else if (dri2_dpy->dri2) {
1600       if (dri2_dpy->dri2->base.version >= 3) {
1601          dri2_ctx->dri_context =
1602             dri2_dpy->dri2->createContextAttribs(dri2_dpy->dri_screen,
1603                                                  api,
1604                                                  dri_config,
1605                                                  shared,
1606                                                  num_attribs / 2,
1607                                                  ctx_attribs,
1608                                                  & error,
1609                                                  dri2_ctx);
1610          dri2_create_context_attribs_error(error);
1611       } else {
1612          dri2_ctx->dri_context =
1613             dri2_dpy->dri2->createNewContextForAPI(dri2_dpy->dri_screen,
1614                                                    api,
1615                                                    dri_config,
1616                                                    shared,
1617                                                    dri2_ctx);
1618       }
1619    } else {
1620       assert(dri2_dpy->swrast);
1621       if (dri2_dpy->swrast->base.version >= 3) {
1622          dri2_ctx->dri_context =
1623             dri2_dpy->swrast->createContextAttribs(dri2_dpy->dri_screen,
1624                                                    api,
1625                                                    dri_config,
1626                                                    shared,
1627                                                    num_attribs / 2,
1628                                                    ctx_attribs,
1629                                                    & error,
1630                                                    dri2_ctx);
1631          dri2_create_context_attribs_error(error);
1632       } else {
1633          dri2_ctx->dri_context =
1634             dri2_dpy->swrast->createNewContextForAPI(dri2_dpy->dri_screen,
1635                                                      api,
1636                                                      dri_config,
1637                                                      shared,
1638                                                      dri2_ctx);
1639       }
1640    }
1641
1642    if (!dri2_ctx->dri_context)
1643       goto cleanup;
1644
1645    return &dri2_ctx->base;
1646
1647  cleanup:
1648    free(dri2_ctx);
1649    return NULL;
1650 }
1651
1652 /**
1653  * Called via eglDestroyContext(), drv->DestroyContext().
1654  */
1655 static EGLBoolean
1656 dri2_destroy_context(_EGLDisplay *disp, _EGLContext *ctx)
1657 {
1658    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1659    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1660
1661    if (_eglPutContext(ctx)) {
1662       dri2_dpy->core->destroyContext(dri2_ctx->dri_context);
1663       free(dri2_ctx);
1664    }
1665
1666    return EGL_TRUE;
1667 }
1668
1669 EGLBoolean
1670 dri2_init_surface(_EGLSurface *surf, _EGLDisplay *disp, EGLint type,
1671         _EGLConfig *conf, const EGLint *attrib_list,
1672         EGLBoolean enable_out_fence, void *native_surface)
1673 {
1674    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1675    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1676
1677    dri2_surf->out_fence_fd = -1;
1678    dri2_surf->enable_out_fence = false;
1679    if (dri2_dpy->fence && dri2_dpy->fence->base.version >= 2 &&
1680        dri2_dpy->fence->get_capabilities &&
1681        (dri2_dpy->fence->get_capabilities(dri2_dpy->dri_screen) &
1682         __DRI_FENCE_CAP_NATIVE_FD)) {
1683       dri2_surf->enable_out_fence = enable_out_fence;
1684    }
1685
1686    return _eglInitSurface(surf, disp, type, conf, attrib_list, native_surface);
1687 }
1688
1689 static void
1690 dri2_surface_set_out_fence_fd( _EGLSurface *surf, int fence_fd)
1691 {
1692    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1693
1694    if (dri2_surf->out_fence_fd >= 0)
1695       close(dri2_surf->out_fence_fd);
1696
1697    dri2_surf->out_fence_fd = fence_fd;
1698 }
1699
1700 void
1701 dri2_fini_surface(_EGLSurface *surf)
1702 {
1703    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1704
1705    dri2_surface_set_out_fence_fd(surf, -1);
1706    dri2_surf->enable_out_fence = false;
1707 }
1708
1709 static EGLBoolean
1710 dri2_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
1711 {
1712    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1713
1714    if (!_eglPutSurface(surf))
1715       return EGL_TRUE;
1716
1717    return dri2_dpy->vtbl->destroy_surface(disp, surf);
1718 }
1719
1720 static void
1721 dri2_surf_update_fence_fd(_EGLContext *ctx,
1722                           _EGLDisplay *disp, _EGLSurface *surf)
1723 {
1724    __DRIcontext *dri_ctx = dri2_egl_context(ctx)->dri_context;
1725    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1726    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1727    int fence_fd = -1;
1728    void *fence;
1729
1730    if (!dri2_surf->enable_out_fence)
1731       return;
1732
1733    fence = dri2_dpy->fence->create_fence_fd(dri_ctx, -1);
1734    if (fence) {
1735       fence_fd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
1736                                                fence);
1737       dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, fence);
1738    }
1739    dri2_surface_set_out_fence_fd(surf, fence_fd);
1740 }
1741
1742 EGLBoolean
1743 dri2_create_drawable(struct dri2_egl_display *dri2_dpy,
1744                      const __DRIconfig *config,
1745                      struct dri2_egl_surface *dri2_surf,
1746                      void *loaderPrivate)
1747 {
1748    if (dri2_dpy->kopper) {
1749       dri2_surf->dri_drawable =
1750           dri2_dpy->kopper->createNewDrawable(dri2_dpy->dri_screen, config, loaderPrivate,
1751                                               dri2_surf->base.Type == EGL_PBUFFER_BIT ||
1752                                               dri2_surf->base.Type == EGL_PIXMAP_BIT);
1753    } else {
1754       __DRIcreateNewDrawableFunc createNewDrawable;
1755       if (dri2_dpy->image_driver)
1756          createNewDrawable = dri2_dpy->image_driver->createNewDrawable;
1757       else if (dri2_dpy->dri2)
1758          createNewDrawable = dri2_dpy->dri2->createNewDrawable;
1759       else if (dri2_dpy->swrast)
1760          createNewDrawable = dri2_dpy->swrast->createNewDrawable;
1761       else
1762          return _eglError(EGL_BAD_ALLOC, "no createNewDrawable");
1763
1764       dri2_surf->dri_drawable = createNewDrawable(dri2_dpy->dri_screen,
1765                                                   config, loaderPrivate);
1766    }
1767    if (dri2_surf->dri_drawable == NULL)
1768       return _eglError(EGL_BAD_ALLOC, "createNewDrawable");
1769
1770    return EGL_TRUE;
1771 }
1772
1773 /**
1774  * Called via eglMakeCurrent(), drv->MakeCurrent().
1775  */
1776 static EGLBoolean
1777 dri2_make_current(_EGLDisplay *disp, _EGLSurface *dsurf,
1778                   _EGLSurface *rsurf, _EGLContext *ctx)
1779 {
1780    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1781    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1782    _EGLDisplay *old_disp = NULL;
1783    struct dri2_egl_display *old_dri2_dpy = NULL;
1784    _EGLContext *old_ctx;
1785    _EGLSurface *old_dsurf, *old_rsurf;
1786    _EGLSurface *tmp_dsurf, *tmp_rsurf;
1787    __DRIdrawable *ddraw, *rdraw;
1788    __DRIcontext *cctx;
1789    EGLint egl_error = EGL_SUCCESS;
1790
1791    if (!dri2_dpy)
1792       return _eglError(EGL_NOT_INITIALIZED, "eglMakeCurrent");
1793
1794    /* make new bindings, set the EGL error otherwise */
1795    if (!_eglBindContext(ctx, dsurf, rsurf, &old_ctx, &old_dsurf, &old_rsurf))
1796       return EGL_FALSE;
1797
1798    if (old_ctx == ctx && old_dsurf == dsurf && old_rsurf == rsurf) {
1799       _eglPutSurface(old_dsurf);
1800       _eglPutSurface(old_rsurf);
1801       _eglPutContext(old_ctx);
1802       return EGL_TRUE;
1803    }
1804
1805    if (old_ctx) {
1806       __DRIcontext *old_cctx = dri2_egl_context(old_ctx)->dri_context;
1807       old_disp = old_ctx->Resource.Display;
1808       old_dri2_dpy = dri2_egl_display(old_disp);
1809
1810       /* Disable shared buffer mode */
1811       if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1812           old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1813          old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, false);
1814       }
1815
1816       dri2_dpy->core->unbindContext(old_cctx);
1817
1818       if (old_dsurf)
1819          dri2_surf_update_fence_fd(old_ctx, disp, old_dsurf);
1820    }
1821
1822    ddraw = (dsurf) ? dri2_dpy->vtbl->get_dri_drawable(dsurf) : NULL;
1823    rdraw = (rsurf) ? dri2_dpy->vtbl->get_dri_drawable(rsurf) : NULL;
1824    cctx = (dri2_ctx) ? dri2_ctx->dri_context : NULL;
1825
1826    if (cctx || ddraw || rdraw) {
1827       if (!dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1828          _EGLContext *tmp_ctx;
1829
1830          /* dri2_dpy->core->bindContext failed. We cannot tell for sure why, but
1831           * setting the error to EGL_BAD_MATCH is surely better than leaving it
1832           * as EGL_SUCCESS.
1833           */
1834          egl_error = EGL_BAD_MATCH;
1835
1836          /* undo the previous _eglBindContext */
1837          _eglBindContext(old_ctx, old_dsurf, old_rsurf, &ctx, &tmp_dsurf, &tmp_rsurf);
1838          assert(&dri2_ctx->base == ctx &&
1839                 tmp_dsurf == dsurf &&
1840                 tmp_rsurf == rsurf);
1841
1842          _eglPutSurface(dsurf);
1843          _eglPutSurface(rsurf);
1844          _eglPutContext(ctx);
1845
1846          _eglPutSurface(old_dsurf);
1847          _eglPutSurface(old_rsurf);
1848          _eglPutContext(old_ctx);
1849
1850          ddraw = (old_dsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_dsurf) : NULL;
1851          rdraw = (old_rsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_rsurf) : NULL;
1852          cctx = (old_ctx) ? dri2_egl_context(old_ctx)->dri_context : NULL;
1853
1854          /* undo the previous dri2_dpy->core->unbindContext */
1855          if (dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1856             if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1857                 old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1858                old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, true);
1859             }
1860
1861             return _eglError(egl_error, "eglMakeCurrent");
1862          }
1863
1864          /* We cannot restore the same state as it was before calling
1865           * eglMakeCurrent() and the spec isn't clear about what to do. We
1866           * can prevent EGL from calling into the DRI driver with no DRI
1867           * context bound.
1868           */
1869          dsurf = rsurf = NULL;
1870          ctx = NULL;
1871
1872          _eglBindContext(ctx, dsurf, rsurf, &tmp_ctx, &tmp_dsurf, &tmp_rsurf);
1873          assert(tmp_ctx == old_ctx && tmp_dsurf == old_dsurf &&
1874                 tmp_rsurf == old_rsurf);
1875
1876          _eglLog(_EGL_WARNING, "DRI2: failed to rebind the previous context");
1877       } else {
1878          /* dri2_dpy->core->bindContext succeeded, so take a reference on the
1879           * dri2_dpy. This prevents dri2_dpy from being reinitialized when a
1880           * EGLDisplay is terminated and then initialized again while a
1881           * context is still bound. See dri2_intitialize() for a more in depth
1882           * explanation. */
1883          dri2_dpy->ref_count++;
1884       }
1885    }
1886
1887    dri2_destroy_surface(disp, old_dsurf);
1888    dri2_destroy_surface(disp, old_rsurf);
1889
1890    if (old_ctx) {
1891       dri2_destroy_context(disp, old_ctx);
1892       dri2_display_release(old_disp);
1893    }
1894
1895    if (egl_error != EGL_SUCCESS)
1896       return _eglError(egl_error, "eglMakeCurrent");
1897
1898    if (dsurf && _eglSurfaceHasMutableRenderBuffer(dsurf) &&
1899        dri2_dpy->vtbl->set_shared_buffer_mode) {
1900       /* Always update the shared buffer mode. This is obviously needed when
1901        * the active EGL_RENDER_BUFFER is EGL_SINGLE_BUFFER. When
1902        * EGL_RENDER_BUFFER is EGL_BACK_BUFFER, the update protects us in the
1903        * case where external non-EGL API may have changed window's shared
1904        * buffer mode since we last saw it.
1905        */
1906       bool mode = (dsurf->ActiveRenderBuffer == EGL_SINGLE_BUFFER);
1907       dri2_dpy->vtbl->set_shared_buffer_mode(disp, dsurf, mode);
1908    }
1909
1910    return EGL_TRUE;
1911 }
1912
1913 __DRIdrawable *
1914 dri2_surface_get_dri_drawable(_EGLSurface *surf)
1915 {
1916    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1917
1918    return dri2_surf->dri_drawable;
1919 }
1920
1921 /*
1922  * Called from eglGetProcAddress() via drv->GetProcAddress().
1923  */
1924 static _EGLProc
1925 dri2_get_proc_address(const char *procname)
1926 {
1927    return _glapi_get_proc_address(procname);
1928 }
1929
1930 static _EGLSurface*
1931 dri2_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
1932                            void *native_window, const EGLint *attrib_list)
1933 {
1934    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1935    return dri2_dpy->vtbl->create_window_surface(disp, conf, native_window,
1936                                                 attrib_list);
1937 }
1938
1939 static _EGLSurface*
1940 dri2_create_pixmap_surface(_EGLDisplay *disp, _EGLConfig *conf,
1941                            void *native_pixmap, const EGLint *attrib_list)
1942 {
1943    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1944    if (!dri2_dpy->vtbl->create_pixmap_surface)
1945       return NULL;
1946    return dri2_dpy->vtbl->create_pixmap_surface(disp, conf, native_pixmap,
1947                                                 attrib_list);
1948 }
1949
1950 static _EGLSurface*
1951 dri2_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
1952                             const EGLint *attrib_list)
1953 {
1954    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1955    if (!dri2_dpy->vtbl->create_pbuffer_surface)
1956       return NULL;
1957    return dri2_dpy->vtbl->create_pbuffer_surface(disp, conf, attrib_list);
1958 }
1959
1960 static EGLBoolean
1961 dri2_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
1962 {
1963    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1964    if (!dri2_dpy->vtbl->swap_interval)
1965       return EGL_TRUE;
1966    return dri2_dpy->vtbl->swap_interval(disp, surf, interval);
1967 }
1968
1969 /**
1970  * Asks the client API to flush any rendering to the drawable so that we can
1971  * do our swapbuffers.
1972  */
1973 void
1974 dri2_flush_drawable_for_swapbuffers(_EGLDisplay *disp, _EGLSurface *draw)
1975 {
1976    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1977    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(draw);
1978
1979    if (dri2_dpy->flush) {
1980       if (dri2_dpy->flush->base.version >= 4) {
1981          /* We know there's a current context because:
1982           *
1983           *     "If surface is not bound to the calling thread’s current
1984           *      context, an EGL_BAD_SURFACE error is generated."
1985          */
1986          _EGLContext *ctx = _eglGetCurrentContext();
1987          struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1988
1989          /* From the EGL 1.4 spec (page 52):
1990           *
1991           *     "The contents of ancillary buffers are always undefined
1992           *      after calling eglSwapBuffers."
1993           */
1994          dri2_dpy->flush->flush_with_flags(dri2_ctx->dri_context,
1995                                            dri_drawable,
1996                                            __DRI2_FLUSH_DRAWABLE |
1997                                            __DRI2_FLUSH_INVALIDATE_ANCILLARY,
1998                                            __DRI2_THROTTLE_SWAPBUFFER);
1999       } else {
2000          dri2_dpy->flush->flush(dri_drawable);
2001       }
2002    }
2003 }
2004
2005 static EGLBoolean
2006 dri2_swap_buffers(_EGLDisplay *disp, _EGLSurface *surf)
2007 {
2008    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2009    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2010    _EGLContext *ctx = _eglGetCurrentContext();
2011    EGLBoolean ret;
2012
2013    if (ctx && surf)
2014       dri2_surf_update_fence_fd(ctx, disp, surf);
2015    ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2016
2017    /* SwapBuffers marks the end of the frame; reset the damage region for
2018     * use again next time.
2019     */
2020    if (ret && dri2_dpy->buffer_damage &&
2021        dri2_dpy->buffer_damage->set_damage_region)
2022       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2023
2024    return ret;
2025 }
2026
2027 static EGLBoolean
2028 dri2_swap_buffers_with_damage(_EGLDisplay *disp, _EGLSurface *surf,
2029                               const EGLint *rects, EGLint n_rects)
2030 {
2031    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2032    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2033    _EGLContext *ctx = _eglGetCurrentContext();
2034    EGLBoolean ret;
2035
2036    if (ctx && surf)
2037       dri2_surf_update_fence_fd(ctx, disp, surf);
2038    if (dri2_dpy->vtbl->swap_buffers_with_damage)
2039       ret = dri2_dpy->vtbl->swap_buffers_with_damage(disp, surf,
2040                                                      rects, n_rects);
2041    else
2042       ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2043
2044    /* SwapBuffers marks the end of the frame; reset the damage region for
2045     * use again next time.
2046     */
2047    if (ret && dri2_dpy->buffer_damage &&
2048        dri2_dpy->buffer_damage->set_damage_region)
2049       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2050
2051    return ret;
2052 }
2053
2054 static EGLBoolean
2055 dri2_swap_buffers_region(_EGLDisplay *disp, _EGLSurface *surf,
2056                          EGLint numRects, const EGLint *rects)
2057 {
2058    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2059    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2060    EGLBoolean ret;
2061
2062    if (!dri2_dpy->vtbl->swap_buffers_region)
2063       return EGL_FALSE;
2064    ret = dri2_dpy->vtbl->swap_buffers_region(disp, surf, numRects, rects);
2065
2066    /* SwapBuffers marks the end of the frame; reset the damage region for
2067     * use again next time.
2068     */
2069    if (ret && dri2_dpy->buffer_damage &&
2070        dri2_dpy->buffer_damage->set_damage_region)
2071       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2072
2073    return ret;
2074 }
2075
2076 static EGLBoolean
2077 dri2_set_damage_region(_EGLDisplay *disp, _EGLSurface *surf,
2078                        EGLint *rects, EGLint n_rects)
2079 {
2080    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2081    __DRIdrawable *drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2082
2083    if (!dri2_dpy->buffer_damage || !dri2_dpy->buffer_damage->set_damage_region)
2084       return EGL_FALSE;
2085
2086    dri2_dpy->buffer_damage->set_damage_region(drawable, n_rects, rects);
2087    return EGL_TRUE;
2088 }
2089
2090 static EGLBoolean
2091 dri2_post_sub_buffer(_EGLDisplay *disp, _EGLSurface *surf,
2092                      EGLint x, EGLint y, EGLint width, EGLint height)
2093 {
2094    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2095    if (!dri2_dpy->vtbl->post_sub_buffer)
2096       return EGL_FALSE;
2097    return dri2_dpy->vtbl->post_sub_buffer(disp, surf, x, y, width, height);
2098 }
2099
2100 static EGLBoolean
2101 dri2_copy_buffers(_EGLDisplay *disp, _EGLSurface *surf, void *native_pixmap_target)
2102 {
2103    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2104    if (!dri2_dpy->vtbl->copy_buffers)
2105       return _eglError(EGL_BAD_NATIVE_PIXMAP, "no support for native pixmaps");
2106    return dri2_dpy->vtbl->copy_buffers(disp, surf, native_pixmap_target);
2107 }
2108
2109 static EGLint
2110 dri2_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surf)
2111 {
2112    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2113    if (!dri2_dpy->vtbl->query_buffer_age)
2114       return 0;
2115    return dri2_dpy->vtbl->query_buffer_age(disp, surf);
2116 }
2117
2118 static EGLBoolean
2119 dri2_wait_client(_EGLDisplay *disp, _EGLContext *ctx)
2120 {
2121    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2122    _EGLSurface *surf = ctx->DrawSurface;
2123    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2124
2125    /* FIXME: If EGL allows frontbuffer rendering for window surfaces,
2126     * we need to copy fake to real here.*/
2127
2128    if (dri2_dpy->flush != NULL)
2129       dri2_dpy->flush->flush(dri_drawable);
2130
2131    return EGL_TRUE;
2132 }
2133
2134 static EGLBoolean
2135 dri2_wait_native(EGLint engine)
2136 {
2137    if (engine != EGL_CORE_NATIVE_ENGINE)
2138       return _eglError(EGL_BAD_PARAMETER, "eglWaitNative");
2139    /* glXWaitX(); */
2140
2141    return EGL_TRUE;
2142 }
2143
2144 static EGLBoolean
2145 dri2_bind_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2146 {
2147    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2148    struct dri2_egl_context *dri2_ctx;
2149    _EGLContext *ctx;
2150    GLint format, target;
2151    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2152
2153    ctx = _eglGetCurrentContext();
2154    dri2_ctx = dri2_egl_context(ctx);
2155
2156    if (!_eglBindTexImage(disp, surf, buffer))
2157       return EGL_FALSE;
2158
2159    switch (surf->TextureFormat) {
2160    case EGL_TEXTURE_RGB:
2161       format = __DRI_TEXTURE_FORMAT_RGB;
2162       break;
2163    case EGL_TEXTURE_RGBA:
2164       format = __DRI_TEXTURE_FORMAT_RGBA;
2165       break;
2166    default:
2167       assert(!"Unexpected texture format in dri2_bind_tex_image()");
2168       format = __DRI_TEXTURE_FORMAT_RGBA;
2169    }
2170
2171    switch (surf->TextureTarget) {
2172    case EGL_TEXTURE_2D:
2173       target = GL_TEXTURE_2D;
2174       break;
2175    default:
2176       target = GL_TEXTURE_2D;
2177       assert(!"Unexpected texture target in dri2_bind_tex_image()");
2178    }
2179
2180    dri2_dpy->tex_buffer->setTexBuffer2(dri2_ctx->dri_context,
2181                                        target, format,
2182                                        dri_drawable);
2183
2184    return EGL_TRUE;
2185 }
2186
2187 static EGLBoolean
2188 dri2_release_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2189 {
2190    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2191    struct dri2_egl_context *dri2_ctx;
2192    _EGLContext *ctx;
2193    GLint  target;
2194    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2195
2196    ctx = _eglGetCurrentContext();
2197    dri2_ctx = dri2_egl_context(ctx);
2198
2199    if (!_eglReleaseTexImage(disp, surf, buffer))
2200       return EGL_FALSE;
2201
2202    switch (surf->TextureTarget) {
2203    case EGL_TEXTURE_2D:
2204       target = GL_TEXTURE_2D;
2205       break;
2206    default:
2207       assert(!"missing texture target");
2208    }
2209
2210    if (dri2_dpy->tex_buffer->base.version >= 3 &&
2211        dri2_dpy->tex_buffer->releaseTexBuffer != NULL) {
2212       dri2_dpy->tex_buffer->releaseTexBuffer(dri2_ctx->dri_context,
2213                                              target, dri_drawable);
2214    }
2215
2216    return EGL_TRUE;
2217 }
2218
2219 static _EGLImage*
2220 dri2_create_image(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
2221                   EGLClientBuffer buffer, const EGLint *attr_list)
2222 {
2223    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2224    return dri2_dpy->vtbl->create_image(disp, ctx, target, buffer,
2225                                        attr_list);
2226 }
2227
2228 _EGLImage *
2229 dri2_create_image_from_dri(_EGLDisplay *disp, __DRIimage *dri_image)
2230 {
2231    struct dri2_egl_image *dri2_img;
2232
2233    if (dri_image == NULL) {
2234       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2235       return NULL;
2236    }
2237
2238    dri2_img = malloc(sizeof *dri2_img);
2239    if (!dri2_img) {
2240       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2241       return NULL;
2242    }
2243
2244    _eglInitImage(&dri2_img->base, disp);
2245
2246    dri2_img->dri_image = dri_image;
2247
2248    return &dri2_img->base;
2249 }
2250
2251 /**
2252  * Translate a DRI Image extension error code into an EGL error code.
2253  */
2254 static EGLint
2255 egl_error_from_dri_image_error(int dri_error)
2256 {
2257    switch (dri_error) {
2258    case __DRI_IMAGE_ERROR_SUCCESS:
2259       return EGL_SUCCESS;
2260    case __DRI_IMAGE_ERROR_BAD_ALLOC:
2261       return EGL_BAD_ALLOC;
2262    case __DRI_IMAGE_ERROR_BAD_MATCH:
2263       return EGL_BAD_MATCH;
2264    case __DRI_IMAGE_ERROR_BAD_PARAMETER:
2265       return EGL_BAD_PARAMETER;
2266    case __DRI_IMAGE_ERROR_BAD_ACCESS:
2267       return EGL_BAD_ACCESS;
2268    default:
2269       assert(!"unknown dri_error code");
2270       return EGL_BAD_ALLOC;
2271    }
2272 }
2273
2274 static _EGLImage *
2275 dri2_create_image_khr_renderbuffer(_EGLDisplay *disp, _EGLContext *ctx,
2276                                    EGLClientBuffer buffer,
2277                                    const EGLint *attr_list)
2278 {
2279    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2280    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2281    GLuint renderbuffer = (GLuint) (uintptr_t) buffer;
2282    __DRIimage *dri_image;
2283
2284    if (renderbuffer == 0) {
2285       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2286       return EGL_NO_IMAGE_KHR;
2287    }
2288
2289    if (!disp->Extensions.KHR_gl_renderbuffer_image) {
2290       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2291       return EGL_NO_IMAGE_KHR;
2292    }
2293
2294    if (dri2_dpy->image->base.version >= 17 &&
2295        dri2_dpy->image->createImageFromRenderbuffer2) {
2296       unsigned error = ~0;
2297
2298       dri_image = dri2_dpy->image->createImageFromRenderbuffer2(
2299                dri2_ctx->dri_context, renderbuffer, NULL, &error);
2300
2301       assert(!!dri_image == (error == __DRI_IMAGE_ERROR_SUCCESS));
2302
2303       if (!dri_image) {
2304          _eglError(egl_error_from_dri_image_error(error), "dri2_create_image_khr");
2305          return EGL_NO_IMAGE_KHR;
2306       }
2307    } else {
2308       dri_image = dri2_dpy->image->createImageFromRenderbuffer(
2309                dri2_ctx->dri_context, renderbuffer, NULL);
2310       if (!dri_image) {
2311          _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2312          return EGL_NO_IMAGE_KHR;
2313       }
2314    }
2315
2316    return dri2_create_image_from_dri(disp, dri_image);
2317 }
2318
2319 #ifdef HAVE_WAYLAND_PLATFORM
2320
2321 /* This structure describes how a wl_buffer maps to one or more
2322  * __DRIimages.  A wl_drm_buffer stores the wl_drm format code and the
2323  * offsets and strides of the planes in the buffer.  This table maps a
2324  * wl_drm format code to a description of the planes in the buffer
2325  * that lets us create a __DRIimage for each of the planes. */
2326
2327 static const struct wl_drm_components_descriptor {
2328    uint32_t dri_components;
2329    EGLint components;
2330    int nplanes;
2331 } wl_drm_components[] = {
2332    { __DRI_IMAGE_COMPONENTS_RGB, EGL_TEXTURE_RGB, 1 },
2333    { __DRI_IMAGE_COMPONENTS_RGBA, EGL_TEXTURE_RGBA, 1 },
2334    { __DRI_IMAGE_COMPONENTS_Y_U_V, EGL_TEXTURE_Y_U_V_WL, 3 },
2335    { __DRI_IMAGE_COMPONENTS_Y_UV, EGL_TEXTURE_Y_UV_WL, 2 },
2336    { __DRI_IMAGE_COMPONENTS_Y_XUXV, EGL_TEXTURE_Y_XUXV_WL, 2 },
2337 };
2338
2339 static _EGLImage *
2340 dri2_create_image_wayland_wl_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2341                                     EGLClientBuffer _buffer,
2342                                     const EGLint *attr_list)
2343 {
2344    struct wl_drm_buffer *buffer;
2345    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2346    const struct wl_drm_components_descriptor *f;
2347    __DRIimage *dri_image;
2348    _EGLImageAttribs attrs;
2349    int32_t plane;
2350
2351    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm,
2352                                    (struct wl_resource *) _buffer);
2353    if (!buffer)
2354        return NULL;
2355
2356    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2357       return NULL;
2358
2359    plane = attrs.PlaneWL;
2360    f = buffer->driver_format;
2361    if (plane < 0 || plane >= f->nplanes) {
2362       _eglError(EGL_BAD_PARAMETER,
2363                 "dri2_create_image_wayland_wl_buffer (plane out of bounds)");
2364       return NULL;
2365    }
2366
2367    dri_image = dri2_dpy->image->fromPlanar(buffer->driver_buffer, plane, NULL);
2368    if (dri_image == NULL && plane == 0)
2369       dri_image = dri2_dpy->image->dupImage(buffer->driver_buffer, NULL);
2370    if (dri_image == NULL) {
2371       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_wayland_wl_buffer");
2372       return NULL;
2373    }
2374
2375    return dri2_create_image_from_dri(disp, dri_image);
2376 }
2377 #endif
2378
2379 static EGLBoolean
2380 dri2_get_sync_values_chromium(_EGLDisplay *disp, _EGLSurface *surf,
2381                               EGLuint64KHR *ust, EGLuint64KHR *msc,
2382                               EGLuint64KHR *sbc)
2383 {
2384    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2385    if (!dri2_dpy->vtbl->get_sync_values)
2386       return EGL_FALSE;
2387    return dri2_dpy->vtbl->get_sync_values(disp, surf, ust, msc, sbc);
2388 }
2389
2390 static EGLBoolean
2391 dri2_get_msc_rate_angle(_EGLDisplay *disp, _EGLSurface *surf,
2392                         EGLint *numerator, EGLint *denominator)
2393 {
2394    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2395    if (!dri2_dpy->vtbl->get_msc_rate)
2396       return EGL_FALSE;
2397    return dri2_dpy->vtbl->get_msc_rate(disp, surf, numerator, denominator);
2398 }
2399
2400 /**
2401  * Set the error code after a call to
2402  * dri2_egl_image::dri_image::createImageFromTexture.
2403  */
2404 static void
2405 dri2_create_image_khr_texture_error(int dri_error)
2406 {
2407    EGLint egl_error = egl_error_from_dri_image_error(dri_error);
2408
2409    if (egl_error != EGL_SUCCESS)
2410       _eglError(egl_error, "dri2_create_image_khr_texture");
2411 }
2412
2413 static _EGLImage *
2414 dri2_create_image_khr_texture(_EGLDisplay *disp, _EGLContext *ctx,
2415                                    EGLenum target,
2416                                    EGLClientBuffer buffer,
2417                                    const EGLint *attr_list)
2418 {
2419    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2420    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2421    struct dri2_egl_image *dri2_img;
2422    GLuint texture = (GLuint) (uintptr_t) buffer;
2423    _EGLImageAttribs attrs;
2424    GLuint depth;
2425    GLenum gl_target;
2426    unsigned error;
2427
2428    if (texture == 0) {
2429       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2430       return EGL_NO_IMAGE_KHR;
2431    }
2432
2433    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2434       return EGL_NO_IMAGE_KHR;
2435
2436    switch (target) {
2437    case EGL_GL_TEXTURE_2D_KHR:
2438       if (!disp->Extensions.KHR_gl_texture_2D_image) {
2439          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2440          return EGL_NO_IMAGE_KHR;
2441       }
2442       depth = 0;
2443       gl_target = GL_TEXTURE_2D;
2444       break;
2445    case EGL_GL_TEXTURE_3D_KHR:
2446       if (!disp->Extensions.KHR_gl_texture_3D_image) {
2447          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2448          return EGL_NO_IMAGE_KHR;
2449       }
2450
2451       depth = attrs.GLTextureZOffset;
2452       gl_target = GL_TEXTURE_3D;
2453       break;
2454    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
2455    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
2456    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
2457    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
2458    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
2459    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
2460       if (!disp->Extensions.KHR_gl_texture_cubemap_image) {
2461          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2462          return EGL_NO_IMAGE_KHR;
2463       }
2464
2465       depth = target - EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR;
2466       gl_target = GL_TEXTURE_CUBE_MAP;
2467       break;
2468    default:
2469       unreachable("Unexpected target in dri2_create_image_khr_texture()");
2470       return EGL_NO_IMAGE_KHR;
2471    }
2472
2473    dri2_img = malloc(sizeof *dri2_img);
2474    if (!dri2_img) {
2475       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2476       return EGL_NO_IMAGE_KHR;
2477    }
2478
2479    _eglInitImage(&dri2_img->base, disp);
2480
2481    dri2_img->dri_image =
2482       dri2_dpy->image->createImageFromTexture(dri2_ctx->dri_context,
2483                                               gl_target,
2484                                               texture,
2485                                               depth,
2486                                               attrs.GLTextureLevel,
2487                                               &error,
2488                                               NULL);
2489    dri2_create_image_khr_texture_error(error);
2490
2491    if (!dri2_img->dri_image) {
2492       free(dri2_img);
2493       return EGL_NO_IMAGE_KHR;
2494    }
2495    return &dri2_img->base;
2496 }
2497
2498 static EGLBoolean
2499 dri2_query_surface(_EGLDisplay *disp, _EGLSurface *surf,
2500                    EGLint attribute, EGLint *value)
2501 {
2502    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2503    if (!dri2_dpy->vtbl->query_surface)
2504       return _eglQuerySurface(disp, surf, attribute, value);
2505    return dri2_dpy->vtbl->query_surface(disp, surf, attribute, value);
2506 }
2507
2508 static struct wl_buffer*
2509 dri2_create_wayland_buffer_from_image(_EGLDisplay *disp, _EGLImage *img)
2510 {
2511    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2512    if (!dri2_dpy->vtbl->create_wayland_buffer_from_image)
2513       return NULL;
2514    return dri2_dpy->vtbl->create_wayland_buffer_from_image(disp, img);
2515 }
2516
2517 #ifdef HAVE_LIBDRM
2518 static _EGLImage *
2519 dri2_create_image_mesa_drm_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2520                                   EGLClientBuffer buffer, const EGLint *attr_list)
2521 {
2522    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2523    EGLint format, name, pitch;
2524    _EGLImageAttribs attrs;
2525    __DRIimage *dri_image;
2526
2527    name = (EGLint) (uintptr_t) buffer;
2528
2529    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2530       return NULL;
2531
2532    if (attrs.Width <= 0 || attrs.Height <= 0 ||
2533        attrs.DRMBufferStrideMESA <= 0) {
2534       _eglError(EGL_BAD_PARAMETER,
2535                 "bad width, height or stride");
2536       return NULL;
2537    }
2538
2539    switch (attrs.DRMBufferFormatMESA) {
2540    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2541       format = __DRI_IMAGE_FORMAT_ARGB8888;
2542       pitch = attrs.DRMBufferStrideMESA;
2543       break;
2544    default:
2545       _eglError(EGL_BAD_PARAMETER,
2546                 "dri2_create_image_khr: unsupported pixmap depth");
2547       return NULL;
2548    }
2549
2550    dri_image =
2551       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
2552                                            attrs.Width,
2553                                            attrs.Height,
2554                                            format,
2555                                            name,
2556                                            pitch,
2557                                            NULL);
2558
2559    return dri2_create_image_from_dri(disp, dri_image);
2560 }
2561
2562 static EGLBoolean
2563 dri2_check_dma_buf_attribs(const _EGLImageAttribs *attrs)
2564 {
2565    /**
2566      * The spec says:
2567      *
2568      * "Required attributes and their values are as follows:
2569      *
2570      *  * EGL_WIDTH & EGL_HEIGHT: The logical dimensions of the buffer in pixels
2571      *
2572      *  * EGL_LINUX_DRM_FOURCC_EXT: The pixel format of the buffer, as specified
2573      *    by drm_fourcc.h and used as the pixel_format parameter of the
2574      *    drm_mode_fb_cmd2 ioctl."
2575      *
2576      * and
2577      *
2578      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2579      *    incomplete, EGL_BAD_PARAMETER is generated."
2580      */
2581    if (attrs->Width <= 0 || attrs->Height <= 0 ||
2582        !attrs->DMABufFourCC.IsPresent)
2583       return _eglError(EGL_BAD_PARAMETER, "attribute(s) missing");
2584
2585    /**
2586     * Also:
2587     *
2588     * "If <target> is EGL_LINUX_DMA_BUF_EXT and one or more of the values
2589     *  specified for a plane's pitch or offset isn't supported by EGL,
2590     *  EGL_BAD_ACCESS is generated."
2591     */
2592    for (unsigned i = 0; i < ARRAY_SIZE(attrs->DMABufPlanePitches); ++i) {
2593       if (attrs->DMABufPlanePitches[i].IsPresent &&
2594           attrs->DMABufPlanePitches[i].Value <= 0)
2595          return _eglError(EGL_BAD_ACCESS, "invalid pitch");
2596    }
2597
2598    /**
2599     * If <target> is EGL_LINUX_DMA_BUF_EXT, both or neither of the following
2600     * attribute values may be given.
2601     *
2602     * This is referring to EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT and
2603     * EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, and the same for other planes.
2604     */
2605    for (unsigned i = 0; i < DMA_BUF_MAX_PLANES; ++i) {
2606       if (attrs->DMABufPlaneModifiersLo[i].IsPresent !=
2607           attrs->DMABufPlaneModifiersHi[i].IsPresent)
2608          return _eglError(EGL_BAD_PARAMETER, "modifier attribute lo or hi missing");
2609    }
2610
2611    /* Although the EGL_EXT_image_dma_buf_import_modifiers spec doesn't
2612     * mandate it, we only accept the same modifier across all planes. */
2613    for (unsigned i = 1; i < DMA_BUF_MAX_PLANES; ++i) {
2614       if (attrs->DMABufPlaneFds[i].IsPresent) {
2615          if ((attrs->DMABufPlaneModifiersLo[0].IsPresent !=
2616                attrs->DMABufPlaneModifiersLo[i].IsPresent) ||
2617              (attrs->DMABufPlaneModifiersLo[0].Value !=
2618                attrs->DMABufPlaneModifiersLo[i].Value) ||
2619              (attrs->DMABufPlaneModifiersHi[0].Value !=
2620                attrs->DMABufPlaneModifiersHi[i].Value))
2621             return _eglError(EGL_BAD_PARAMETER, "modifier attributes not equal");
2622       }
2623    }
2624
2625    return EGL_TRUE;
2626 }
2627
2628 /* Returns the total number of planes for the format or zero if it isn't a
2629  * valid fourcc format.
2630  */
2631 static unsigned
2632 dri2_num_fourcc_format_planes(EGLint format)
2633 {
2634    switch (format) {
2635    case DRM_FORMAT_R8:
2636    case DRM_FORMAT_RG88:
2637    case DRM_FORMAT_GR88:
2638    case DRM_FORMAT_R16:
2639    case DRM_FORMAT_GR1616:
2640    case DRM_FORMAT_RGB332:
2641    case DRM_FORMAT_BGR233:
2642    case DRM_FORMAT_XRGB4444:
2643    case DRM_FORMAT_XBGR4444:
2644    case DRM_FORMAT_RGBX4444:
2645    case DRM_FORMAT_BGRX4444:
2646    case DRM_FORMAT_ARGB4444:
2647    case DRM_FORMAT_ABGR4444:
2648    case DRM_FORMAT_RGBA4444:
2649    case DRM_FORMAT_BGRA4444:
2650    case DRM_FORMAT_XRGB1555:
2651    case DRM_FORMAT_XBGR1555:
2652    case DRM_FORMAT_RGBX5551:
2653    case DRM_FORMAT_BGRX5551:
2654    case DRM_FORMAT_ARGB1555:
2655    case DRM_FORMAT_ABGR1555:
2656    case DRM_FORMAT_RGBA5551:
2657    case DRM_FORMAT_BGRA5551:
2658    case DRM_FORMAT_RGB565:
2659    case DRM_FORMAT_BGR565:
2660    case DRM_FORMAT_RGB888:
2661    case DRM_FORMAT_BGR888:
2662    case DRM_FORMAT_XRGB8888:
2663    case DRM_FORMAT_XBGR8888:
2664    case DRM_FORMAT_RGBX8888:
2665    case DRM_FORMAT_BGRX8888:
2666    case DRM_FORMAT_ARGB8888:
2667    case DRM_FORMAT_ABGR8888:
2668    case DRM_FORMAT_RGBA8888:
2669    case DRM_FORMAT_BGRA8888:
2670    case DRM_FORMAT_XRGB2101010:
2671    case DRM_FORMAT_XBGR2101010:
2672    case DRM_FORMAT_RGBX1010102:
2673    case DRM_FORMAT_BGRX1010102:
2674    case DRM_FORMAT_ARGB2101010:
2675    case DRM_FORMAT_ABGR2101010:
2676    case DRM_FORMAT_RGBA1010102:
2677    case DRM_FORMAT_BGRA1010102:
2678    case DRM_FORMAT_ABGR16161616:
2679    case DRM_FORMAT_XBGR16161616:
2680    case DRM_FORMAT_XBGR16161616F:
2681    case DRM_FORMAT_ABGR16161616F:
2682    case DRM_FORMAT_YUYV:
2683    case DRM_FORMAT_YVYU:
2684    case DRM_FORMAT_UYVY:
2685    case DRM_FORMAT_VYUY:
2686    case DRM_FORMAT_AYUV:
2687    case DRM_FORMAT_XYUV8888:
2688    case DRM_FORMAT_Y210:
2689    case DRM_FORMAT_Y212:
2690    case DRM_FORMAT_Y216:
2691    case DRM_FORMAT_Y410:
2692    case DRM_FORMAT_Y412:
2693    case DRM_FORMAT_Y416:
2694       return 1;
2695
2696    case DRM_FORMAT_NV12:
2697    case DRM_FORMAT_NV21:
2698    case DRM_FORMAT_NV16:
2699    case DRM_FORMAT_NV61:
2700    case DRM_FORMAT_P010:
2701    case DRM_FORMAT_P012:
2702    case DRM_FORMAT_P016:
2703       return 2;
2704
2705    case DRM_FORMAT_YUV410:
2706    case DRM_FORMAT_YVU410:
2707    case DRM_FORMAT_YUV411:
2708    case DRM_FORMAT_YVU411:
2709    case DRM_FORMAT_YUV420:
2710    case DRM_FORMAT_YVU420:
2711    case DRM_FORMAT_YUV422:
2712    case DRM_FORMAT_YVU422:
2713    case DRM_FORMAT_YUV444:
2714    case DRM_FORMAT_YVU444:
2715       return 3;
2716
2717    default:
2718       return 0;
2719    }
2720 }
2721
2722 /* Returns the total number of file descriptors. Zero indicates an error. */
2723 static unsigned
2724 dri2_check_dma_buf_format(const _EGLImageAttribs *attrs)
2725 {
2726    unsigned plane_n = dri2_num_fourcc_format_planes(attrs->DMABufFourCC.Value);
2727    if (plane_n == 0) {
2728       _eglError(EGL_BAD_MATCH, "unknown drm fourcc format");
2729       return 0;
2730    }
2731
2732    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; i++) {
2733       /**
2734        * The modifiers extension spec says:
2735        *
2736        * "Modifiers may modify any attribute of a buffer import, including
2737        *  but not limited to adding extra planes to a format which
2738        *  otherwise does not have those planes. As an example, a modifier
2739        *  may add a plane for an external compression buffer to a
2740        *  single-plane format. The exact meaning and effect of any
2741        *  modifier is canonically defined by drm_fourcc.h, not as part of
2742        *  this extension."
2743        */
2744       if (attrs->DMABufPlaneModifiersLo[i].IsPresent &&
2745           attrs->DMABufPlaneModifiersHi[i].IsPresent) {
2746          plane_n = i + 1;
2747       }
2748    }
2749
2750    /**
2751      * The spec says:
2752      *
2753      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2754      *    incomplete, EGL_BAD_PARAMETER is generated."
2755      */
2756    for (unsigned i = 0; i < plane_n; ++i) {
2757       if (!attrs->DMABufPlaneFds[i].IsPresent ||
2758           !attrs->DMABufPlaneOffsets[i].IsPresent ||
2759           !attrs->DMABufPlanePitches[i].IsPresent) {
2760          _eglError(EGL_BAD_PARAMETER, "plane attribute(s) missing");
2761          return 0;
2762       }
2763    }
2764
2765    /**
2766     * The spec also says:
2767     *
2768     * "If <target> is EGL_LINUX_DMA_BUF_EXT, and the EGL_LINUX_DRM_FOURCC_EXT
2769     *  attribute indicates a single-plane format, EGL_BAD_ATTRIBUTE is
2770     *  generated if any of the EGL_DMA_BUF_PLANE1_* or EGL_DMA_BUF_PLANE2_*
2771     *  or EGL_DMA_BUF_PLANE3_* attributes are specified."
2772     */
2773    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; ++i) {
2774       if (attrs->DMABufPlaneFds[i].IsPresent ||
2775           attrs->DMABufPlaneOffsets[i].IsPresent ||
2776           attrs->DMABufPlanePitches[i].IsPresent) {
2777          _eglError(EGL_BAD_ATTRIBUTE, "too many plane attributes");
2778          return 0;
2779       }
2780    }
2781
2782    return plane_n;
2783 }
2784
2785 static EGLBoolean
2786 dri2_query_dma_buf_formats(_EGLDisplay *disp, EGLint max,
2787                            EGLint *formats, EGLint *count)
2788 {
2789    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2790    if (max < 0 || (max > 0 && formats == NULL))
2791       return _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2792
2793    if (dri2_dpy->image->base.version < 15 ||
2794        dri2_dpy->image->queryDmaBufFormats == NULL)
2795       return EGL_FALSE;
2796
2797    if (!dri2_dpy->image->queryDmaBufFormats(dri2_dpy->dri_screen, max,
2798                                             formats, count))
2799       return EGL_FALSE;
2800
2801    if (max > 0) {
2802       /* Assert that all of the formats returned are actually fourcc formats.
2803        * Some day, if we want the internal interface function to be able to
2804        * return the fake fourcc formats defined in dri_interface.h, we'll have
2805        * to do something more clever here to pair the list down to just real
2806        * fourcc formats so that we don't leak the fake internal ones.
2807        */
2808       for (int i = 0; i < *count; i++) {
2809          assert(dri2_num_fourcc_format_planes(formats[i]) > 0);
2810       }
2811    }
2812
2813    return EGL_TRUE;
2814 }
2815
2816 static EGLBoolean
2817 dri2_query_dma_buf_modifiers(_EGLDisplay *disp, EGLint format,
2818                              EGLint max, EGLuint64KHR *modifiers,
2819                              EGLBoolean *external_only, EGLint *count)
2820 {
2821    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2822
2823    if (dri2_num_fourcc_format_planes(format) == 0)
2824       return _eglError(EGL_BAD_PARAMETER, "invalid fourcc format");
2825
2826    if (max < 0)
2827       return _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2828
2829    if (max > 0 && modifiers == NULL)
2830       return _eglError(EGL_BAD_PARAMETER, "invalid modifiers array");
2831
2832    if (dri2_dpy->image->base.version < 15 ||
2833        dri2_dpy->image->queryDmaBufModifiers == NULL)
2834       return EGL_FALSE;
2835
2836    if (dri2_dpy->image->queryDmaBufModifiers(dri2_dpy->dri_screen, format,
2837                                              max, modifiers,
2838                                              (unsigned int *) external_only,
2839                                              count) == false)
2840       return _eglError(EGL_BAD_PARAMETER, "invalid format");
2841
2842    return EGL_TRUE;
2843 }
2844
2845 /**
2846  * The spec says:
2847  *
2848  * "If eglCreateImageKHR is successful for a EGL_LINUX_DMA_BUF_EXT target, the
2849  *  EGL will take a reference to the dma_buf(s) which it will release at any
2850  *  time while the EGLDisplay is initialized. It is the responsibility of the
2851  *  application to close the dma_buf file descriptors."
2852  *
2853  * Therefore we must never close or otherwise modify the file descriptors.
2854  */
2855 _EGLImage *
2856 dri2_create_image_dma_buf(_EGLDisplay *disp, _EGLContext *ctx,
2857                           EGLClientBuffer buffer, const EGLint *attr_list)
2858 {
2859    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2860    _EGLImage *res;
2861    _EGLImageAttribs attrs;
2862    __DRIimage *dri_image;
2863    unsigned num_fds;
2864    int fds[DMA_BUF_MAX_PLANES];
2865    int pitches[DMA_BUF_MAX_PLANES];
2866    int offsets[DMA_BUF_MAX_PLANES];
2867    uint64_t modifier;
2868    bool has_modifier = false;
2869    unsigned error;
2870
2871    /**
2872     * The spec says:
2873     *
2874     * ""* If <target> is EGL_LINUX_DMA_BUF_EXT and <buffer> is not NULL, the
2875     *     error EGL_BAD_PARAMETER is generated."
2876     */
2877    if (buffer != NULL) {
2878       _eglError(EGL_BAD_PARAMETER, "buffer not NULL");
2879       return NULL;
2880    }
2881
2882    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2883       return NULL;
2884
2885    if (!dri2_check_dma_buf_attribs(&attrs))
2886       return NULL;
2887
2888    num_fds = dri2_check_dma_buf_format(&attrs);
2889    if (!num_fds)
2890       return NULL;
2891
2892    for (unsigned i = 0; i < num_fds; ++i) {
2893       fds[i] = attrs.DMABufPlaneFds[i].Value;
2894       pitches[i] = attrs.DMABufPlanePitches[i].Value;
2895       offsets[i] = attrs.DMABufPlaneOffsets[i].Value;
2896    }
2897
2898    /* dri2_check_dma_buf_attribs ensures that the modifier, if available,
2899     * will be present in attrs.DMABufPlaneModifiersLo[0] and
2900     * attrs.DMABufPlaneModifiersHi[0] */
2901    if (attrs.DMABufPlaneModifiersLo[0].IsPresent) {
2902       modifier = combine_u32_into_u64(attrs.DMABufPlaneModifiersHi[0].Value,
2903                                       attrs.DMABufPlaneModifiersLo[0].Value);
2904       has_modifier = true;
2905    }
2906
2907    if (attrs.ProtectedContent) {
2908       if (dri2_dpy->image->base.version < 18 ||
2909           dri2_dpy->image->createImageFromDmaBufs3 == NULL) {
2910          _eglError(EGL_BAD_MATCH, "unsupported protected_content attribute");
2911          return EGL_NO_IMAGE_KHR;
2912       }
2913       if (!has_modifier)
2914          modifier = DRM_FORMAT_MOD_INVALID;
2915
2916       dri_image =
2917          dri2_dpy->image->createImageFromDmaBufs3(dri2_dpy->dri_screen,
2918             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2919             modifier, fds, num_fds, pitches, offsets,
2920             attrs.DMABufYuvColorSpaceHint.Value,
2921             attrs.DMABufSampleRangeHint.Value,
2922             attrs.DMABufChromaHorizontalSiting.Value,
2923             attrs.DMABufChromaVerticalSiting.Value,
2924             attrs.ProtectedContent ? __DRI_IMAGE_PROTECTED_CONTENT_FLAG : 0,
2925             &error,
2926             NULL);
2927    }
2928    else if (has_modifier) {
2929       if (dri2_dpy->image->base.version < 15 ||
2930           dri2_dpy->image->createImageFromDmaBufs2 == NULL) {
2931          _eglError(EGL_BAD_MATCH, "unsupported dma_buf format modifier");
2932          return EGL_NO_IMAGE_KHR;
2933       }
2934       dri_image =
2935          dri2_dpy->image->createImageFromDmaBufs2(dri2_dpy->dri_screen,
2936             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2937             modifier, fds, num_fds, pitches, offsets,
2938             attrs.DMABufYuvColorSpaceHint.Value,
2939             attrs.DMABufSampleRangeHint.Value,
2940             attrs.DMABufChromaHorizontalSiting.Value,
2941             attrs.DMABufChromaVerticalSiting.Value,
2942             &error,
2943             NULL);
2944    }
2945    else {
2946       dri_image =
2947          dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
2948             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2949             fds, num_fds, pitches, offsets,
2950             attrs.DMABufYuvColorSpaceHint.Value,
2951             attrs.DMABufSampleRangeHint.Value,
2952             attrs.DMABufChromaHorizontalSiting.Value,
2953             attrs.DMABufChromaVerticalSiting.Value,
2954             &error,
2955             NULL);
2956    }
2957    dri2_create_image_khr_texture_error(error);
2958
2959    if (!dri_image)
2960       return EGL_NO_IMAGE_KHR;
2961
2962    res = dri2_create_image_from_dri(disp, dri_image);
2963
2964    return res;
2965 }
2966 static _EGLImage *
2967 dri2_create_drm_image_mesa(_EGLDisplay *disp, const EGLint *attr_list)
2968 {
2969    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2970    struct dri2_egl_image *dri2_img;
2971    _EGLImageAttribs attrs;
2972    unsigned int dri_use, valid_mask;
2973    int format;
2974
2975    if (!attr_list) {
2976       _eglError(EGL_BAD_PARAMETER, __func__);
2977       return EGL_NO_IMAGE_KHR;
2978    }
2979
2980    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2981       return EGL_NO_IMAGE_KHR;
2982
2983    if (attrs.Width <= 0 || attrs.Height <= 0) {
2984       _eglError(EGL_BAD_PARAMETER, __func__);
2985       return EGL_NO_IMAGE_KHR;
2986    }
2987
2988    switch (attrs.DRMBufferFormatMESA) {
2989    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2990       format = __DRI_IMAGE_FORMAT_ARGB8888;
2991       break;
2992    default:
2993       _eglError(EGL_BAD_PARAMETER, __func__);
2994       return EGL_NO_IMAGE_KHR;
2995    }
2996
2997    valid_mask =
2998       EGL_DRM_BUFFER_USE_SCANOUT_MESA |
2999       EGL_DRM_BUFFER_USE_SHARE_MESA |
3000       EGL_DRM_BUFFER_USE_CURSOR_MESA;
3001    if (attrs.DRMBufferUseMESA & ~valid_mask) {
3002       _eglError(EGL_BAD_PARAMETER, __func__);
3003       return EGL_NO_IMAGE_KHR;
3004    }
3005
3006    dri_use = 0;
3007    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SHARE_MESA)
3008       dri_use |= __DRI_IMAGE_USE_SHARE;
3009    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SCANOUT_MESA)
3010       dri_use |= __DRI_IMAGE_USE_SCANOUT;
3011    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_CURSOR_MESA)
3012       dri_use |= __DRI_IMAGE_USE_CURSOR;
3013
3014    dri2_img = malloc(sizeof *dri2_img);
3015    if (!dri2_img) {
3016       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
3017       return EGL_NO_IMAGE_KHR;
3018    }
3019
3020    _eglInitImage(&dri2_img->base, disp);
3021
3022    dri2_img->dri_image =
3023       dri2_dpy->image->createImage(dri2_dpy->dri_screen,
3024                                    attrs.Width, attrs.Height,
3025                                    format, dri_use, dri2_img);
3026    if (dri2_img->dri_image == NULL) {
3027       free(dri2_img);
3028        _eglError(EGL_BAD_ALLOC, "dri2_create_drm_image_mesa");
3029       return EGL_NO_IMAGE_KHR;
3030    }
3031
3032    return &dri2_img->base;
3033 }
3034
3035 static EGLBoolean
3036 dri2_export_drm_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3037                           EGLint *name, EGLint *handle, EGLint *stride)
3038 {
3039    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3040    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3041
3042    if (name && !dri2_dpy->image->queryImage(dri2_img->dri_image,
3043                                             __DRI_IMAGE_ATTRIB_NAME, name))
3044       return _eglError(EGL_BAD_ALLOC, "dri2_export_drm_image_mesa");
3045
3046    if (handle)
3047       dri2_dpy->image->queryImage(dri2_img->dri_image,
3048                                   __DRI_IMAGE_ATTRIB_HANDLE, handle);
3049
3050    if (stride)
3051       dri2_dpy->image->queryImage(dri2_img->dri_image,
3052                                   __DRI_IMAGE_ATTRIB_STRIDE, stride);
3053
3054    return EGL_TRUE;
3055 }
3056
3057 /**
3058  * Checks if we can support EGL_MESA_image_dma_buf_export on this image.
3059
3060  * The spec provides a boolean return for the driver to reject exporting for
3061  * basically any reason, but doesn't specify any particular error cases.  For
3062  * now, we just fail if we don't have a DRM fourcc for the format.
3063  */
3064 static bool
3065 dri2_can_export_dma_buf_image(_EGLDisplay *disp, _EGLImage *img)
3066 {
3067    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3068    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3069    EGLint fourcc;
3070
3071    if (!dri2_dpy->image->queryImage(dri2_img->dri_image,
3072                                     __DRI_IMAGE_ATTRIB_FOURCC, &fourcc)) {
3073       return false;
3074    }
3075
3076    return true;
3077 }
3078
3079 static EGLBoolean
3080 dri2_export_dma_buf_image_query_mesa(_EGLDisplay *disp, _EGLImage *img,
3081                                      EGLint *fourcc, EGLint *nplanes,
3082                                      EGLuint64KHR *modifiers)
3083 {
3084    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3085    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3086    int num_planes;
3087
3088    if (!dri2_can_export_dma_buf_image(disp, img))
3089       return EGL_FALSE;
3090
3091    dri2_dpy->image->queryImage(dri2_img->dri_image,
3092                                __DRI_IMAGE_ATTRIB_NUM_PLANES, &num_planes);
3093    if (nplanes)
3094      *nplanes = num_planes;
3095
3096    if (fourcc)
3097       dri2_dpy->image->queryImage(dri2_img->dri_image,
3098                                   __DRI_IMAGE_ATTRIB_FOURCC, fourcc);
3099
3100    if (modifiers) {
3101       int mod_hi, mod_lo;
3102       uint64_t modifier = DRM_FORMAT_MOD_INVALID;
3103       bool query;
3104
3105       query = dri2_dpy->image->queryImage(dri2_img->dri_image,
3106                                           __DRI_IMAGE_ATTRIB_MODIFIER_UPPER,
3107                                           &mod_hi);
3108       query &= dri2_dpy->image->queryImage(dri2_img->dri_image,
3109                                            __DRI_IMAGE_ATTRIB_MODIFIER_LOWER,
3110                                            &mod_lo);
3111       if (query)
3112          modifier = combine_u32_into_u64 (mod_hi, mod_lo);
3113
3114       for (int i = 0; i < num_planes; i++)
3115         modifiers[i] = modifier;
3116    }
3117
3118    return EGL_TRUE;
3119 }
3120
3121 static EGLBoolean
3122 dri2_export_dma_buf_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3123                                int *fds, EGLint *strides, EGLint *offsets)
3124 {
3125    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3126    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3127    EGLint nplanes;
3128
3129    if (!dri2_can_export_dma_buf_image(disp, img))
3130       return EGL_FALSE;
3131
3132    /* EGL_MESA_image_dma_buf_export spec says:
3133     *    "If the number of fds is less than the number of planes, then
3134     *    subsequent fd slots should contain -1."
3135     */
3136    if (fds) {
3137       /* Query nplanes so that we know how big the given array is. */
3138       dri2_dpy->image->queryImage(dri2_img->dri_image,
3139                                   __DRI_IMAGE_ATTRIB_NUM_PLANES, &nplanes);
3140       memset(fds, -1, nplanes * sizeof(int));
3141    }
3142
3143    /* rework later to provide multiple fds/strides/offsets */
3144    if (fds)
3145       dri2_dpy->image->queryImage(dri2_img->dri_image,
3146                                   __DRI_IMAGE_ATTRIB_FD, fds);
3147
3148    if (strides)
3149       dri2_dpy->image->queryImage(dri2_img->dri_image,
3150                                   __DRI_IMAGE_ATTRIB_STRIDE, strides);
3151
3152    if (offsets) {
3153       int img_offset;
3154       bool ret = dri2_dpy->image->queryImage(dri2_img->dri_image,
3155                      __DRI_IMAGE_ATTRIB_OFFSET, &img_offset);
3156       if (ret)
3157          offsets[0] = img_offset;
3158       else
3159          offsets[0] = 0;
3160    }
3161
3162    return EGL_TRUE;
3163 }
3164
3165 #endif
3166
3167 _EGLImage *
3168 dri2_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
3169                       EGLClientBuffer buffer, const EGLint *attr_list)
3170 {
3171    switch (target) {
3172    case EGL_GL_TEXTURE_2D_KHR:
3173    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
3174    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
3175    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
3176    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
3177    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
3178    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
3179    case EGL_GL_TEXTURE_3D_KHR:
3180       return dri2_create_image_khr_texture(disp, ctx, target, buffer, attr_list);
3181    case EGL_GL_RENDERBUFFER_KHR:
3182       return dri2_create_image_khr_renderbuffer(disp, ctx, buffer, attr_list);
3183 #ifdef HAVE_LIBDRM
3184    case EGL_DRM_BUFFER_MESA:
3185       return dri2_create_image_mesa_drm_buffer(disp, ctx, buffer, attr_list);
3186    case EGL_LINUX_DMA_BUF_EXT:
3187       return dri2_create_image_dma_buf(disp, ctx, buffer, attr_list);
3188 #endif
3189 #ifdef HAVE_WAYLAND_PLATFORM
3190    case EGL_WAYLAND_BUFFER_WL:
3191       return dri2_create_image_wayland_wl_buffer(disp, ctx, buffer, attr_list);
3192 #endif
3193    default:
3194       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
3195       return EGL_NO_IMAGE_KHR;
3196    }
3197 }
3198
3199 static EGLBoolean
3200 dri2_destroy_image_khr(_EGLDisplay *disp, _EGLImage *image)
3201 {
3202    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3203    struct dri2_egl_image *dri2_img = dri2_egl_image(image);
3204
3205    dri2_dpy->image->destroyImage(dri2_img->dri_image);
3206    free(dri2_img);
3207
3208    return EGL_TRUE;
3209 }
3210
3211 #ifdef HAVE_WAYLAND_PLATFORM
3212
3213 static void
3214 dri2_wl_reference_buffer(void *user_data, uint32_t name, int fd,
3215                          struct wl_drm_buffer *buffer)
3216 {
3217    _EGLDisplay *disp = user_data;
3218    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3219    __DRIimage *img;
3220    int dri_components = 0;
3221
3222    if (fd == -1)
3223       img = dri2_dpy->image->createImageFromNames(dri2_dpy->dri_screen,
3224                                                   buffer->width,
3225                                                   buffer->height,
3226                                                   buffer->format,
3227                                                   (int*)&name, 1,
3228                                                   buffer->stride,
3229                                                   buffer->offset,
3230                                                   NULL);
3231    else
3232       img = dri2_dpy->image->createImageFromFds(dri2_dpy->dri_screen,
3233                                                 buffer->width,
3234                                                 buffer->height,
3235                                                 buffer->format,
3236                                                 &fd, 1,
3237                                                 buffer->stride,
3238                                                 buffer->offset,
3239                                                 NULL);
3240
3241    if (img == NULL)
3242       return;
3243
3244    dri2_dpy->image->queryImage(img, __DRI_IMAGE_ATTRIB_COMPONENTS, &dri_components);
3245
3246    buffer->driver_format = NULL;
3247    for (int i = 0; i < ARRAY_SIZE(wl_drm_components); i++)
3248       if (wl_drm_components[i].dri_components == dri_components)
3249          buffer->driver_format = &wl_drm_components[i];
3250
3251    if (buffer->driver_format == NULL)
3252       dri2_dpy->image->destroyImage(img);
3253    else
3254       buffer->driver_buffer = img;
3255 }
3256
3257 static void
3258 dri2_wl_release_buffer(void *user_data, struct wl_drm_buffer *buffer)
3259 {
3260    _EGLDisplay *disp = user_data;
3261    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3262
3263    dri2_dpy->image->destroyImage(buffer->driver_buffer);
3264 }
3265
3266 static EGLBoolean
3267 dri2_bind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3268 {
3269    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3270    const struct wayland_drm_callbacks wl_drm_callbacks = {
3271       .authenticate = (int(*)(void *, uint32_t)) dri2_dpy->vtbl->authenticate,
3272       .reference_buffer = dri2_wl_reference_buffer,
3273       .release_buffer = dri2_wl_release_buffer,
3274       .is_format_supported = dri2_wl_is_format_supported
3275    };
3276    int flags = 0;
3277    char *device_name;
3278    uint64_t cap;
3279
3280    if (dri2_dpy->wl_server_drm)
3281            return EGL_FALSE;
3282
3283    device_name = drmGetRenderDeviceNameFromFd(dri2_dpy->fd);
3284    if (!device_name)
3285       device_name = strdup(dri2_dpy->device_name);
3286    if (!device_name)
3287       return EGL_FALSE;
3288
3289    if (drmGetCap(dri2_dpy->fd, DRM_CAP_PRIME, &cap) == 0 &&
3290        cap == (DRM_PRIME_CAP_IMPORT | DRM_PRIME_CAP_EXPORT) &&
3291        dri2_dpy->image->base.version >= 7 &&
3292        dri2_dpy->image->createImageFromFds != NULL)
3293       flags |= WAYLAND_DRM_PRIME;
3294
3295    dri2_dpy->wl_server_drm =
3296            wayland_drm_init(wl_dpy, device_name,
3297                             &wl_drm_callbacks, disp, flags);
3298
3299    free(device_name);
3300
3301    if (!dri2_dpy->wl_server_drm)
3302            return EGL_FALSE;
3303
3304 #ifdef HAVE_DRM_PLATFORM
3305    /* We have to share the wl_drm instance with gbm, so gbm can convert
3306     * wl_buffers to gbm bos. */
3307    if (dri2_dpy->gbm_dri)
3308       dri2_dpy->gbm_dri->wl_drm = dri2_dpy->wl_server_drm;
3309 #endif
3310
3311    return EGL_TRUE;
3312 }
3313
3314 static EGLBoolean
3315 dri2_unbind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3316 {
3317    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3318
3319    if (!dri2_dpy->wl_server_drm)
3320            return EGL_FALSE;
3321
3322    wayland_drm_uninit(dri2_dpy->wl_server_drm);
3323    dri2_dpy->wl_server_drm = NULL;
3324
3325    return EGL_TRUE;
3326 }
3327
3328 static EGLBoolean
3329 dri2_query_wayland_buffer_wl(_EGLDisplay *disp, struct wl_resource *buffer_resource,
3330                              EGLint attribute, EGLint *value)
3331 {
3332    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3333    struct wl_drm_buffer *buffer;
3334    const struct wl_drm_components_descriptor *format;
3335
3336    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm, buffer_resource);
3337    if (!buffer)
3338       return EGL_FALSE;
3339
3340    format = buffer->driver_format;
3341    switch (attribute) {
3342    case EGL_TEXTURE_FORMAT:
3343       *value = format->components;
3344       return EGL_TRUE;
3345    case EGL_WIDTH:
3346       *value = buffer->width;
3347       return EGL_TRUE;
3348    case EGL_HEIGHT:
3349       *value = buffer->height;
3350       return EGL_TRUE;
3351    }
3352
3353    return EGL_FALSE;
3354 }
3355 #endif
3356
3357 static void
3358 dri2_egl_ref_sync(struct dri2_egl_sync *sync)
3359 {
3360    p_atomic_inc(&sync->refcount);
3361 }
3362
3363 static void
3364 dri2_egl_unref_sync(struct dri2_egl_display *dri2_dpy,
3365                     struct dri2_egl_sync *dri2_sync)
3366 {
3367    if (p_atomic_dec_zero(&dri2_sync->refcount)) {
3368       switch (dri2_sync->base.Type) {
3369       case EGL_SYNC_REUSABLE_KHR:
3370          cnd_destroy(&dri2_sync->cond);
3371          break;
3372       case EGL_SYNC_NATIVE_FENCE_ANDROID:
3373          if (dri2_sync->base.SyncFd != EGL_NO_NATIVE_FENCE_FD_ANDROID)
3374             close(dri2_sync->base.SyncFd);
3375          break;
3376       default:
3377          break;
3378       }
3379
3380       if (dri2_sync->fence)
3381          dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, dri2_sync->fence);
3382
3383       free(dri2_sync);
3384    }
3385 }
3386
3387 static _EGLSync *
3388 dri2_create_sync(_EGLDisplay *disp, EGLenum type, const EGLAttrib *attrib_list)
3389 {
3390    _EGLContext *ctx = _eglGetCurrentContext();
3391    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3392    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3393    struct dri2_egl_sync *dri2_sync;
3394    EGLint ret;
3395    pthread_condattr_t attr;
3396
3397    dri2_sync = calloc(1, sizeof(struct dri2_egl_sync));
3398    if (!dri2_sync) {
3399       _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3400       return NULL;
3401    }
3402
3403    if (!_eglInitSync(&dri2_sync->base, disp, type, attrib_list)) {
3404       free(dri2_sync);
3405       return NULL;
3406    }
3407
3408    switch (type) {
3409    case EGL_SYNC_FENCE_KHR:
3410       dri2_sync->fence = dri2_dpy->fence->create_fence(dri2_ctx->dri_context);
3411       if (!dri2_sync->fence) {
3412          /* Why did it fail? DRI doesn't return an error code, so we emit
3413           * a generic EGL error that doesn't communicate user error.
3414           */
3415          _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3416          free(dri2_sync);
3417          return NULL;
3418       }
3419       break;
3420
3421    case EGL_SYNC_CL_EVENT_KHR:
3422       dri2_sync->fence = dri2_dpy->fence->get_fence_from_cl_event(
3423                                  dri2_dpy->dri_screen,
3424                                  dri2_sync->base.CLEvent);
3425       /* this can only happen if the cl_event passed in is invalid. */
3426       if (!dri2_sync->fence) {
3427          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3428          free(dri2_sync);
3429          return NULL;
3430       }
3431
3432       /* the initial status must be "signaled" if the cl_event is signaled */
3433       if (dri2_dpy->fence->client_wait_sync(dri2_ctx->dri_context,
3434                                             dri2_sync->fence, 0, 0))
3435          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3436       break;
3437
3438    case EGL_SYNC_REUSABLE_KHR:
3439       /* intialize attr */
3440       ret = pthread_condattr_init(&attr);
3441
3442       if (ret) {
3443          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3444          free(dri2_sync);
3445          return NULL;
3446       }
3447
3448       /* change clock attribute to CLOCK_MONOTONIC */
3449       ret = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
3450
3451       if (ret) {
3452          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3453          free(dri2_sync);
3454          return NULL;
3455       }
3456
3457       ret = pthread_cond_init(&dri2_sync->cond, &attr);
3458
3459       if (ret) {
3460          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3461          free(dri2_sync);
3462          return NULL;
3463       }
3464
3465       /* initial status of reusable sync must be "unsignaled" */
3466       dri2_sync->base.SyncStatus = EGL_UNSIGNALED_KHR;
3467       break;
3468
3469    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3470       if (dri2_dpy->fence->create_fence_fd) {
3471          dri2_sync->fence = dri2_dpy->fence->create_fence_fd(
3472                                     dri2_ctx->dri_context,
3473                                     dri2_sync->base.SyncFd);
3474       }
3475       if (!dri2_sync->fence) {
3476          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3477          free(dri2_sync);
3478          return NULL;
3479       }
3480       break;
3481    }
3482
3483    p_atomic_set(&dri2_sync->refcount, 1);
3484    return &dri2_sync->base;
3485 }
3486
3487 static EGLBoolean
3488 dri2_destroy_sync(_EGLDisplay *disp, _EGLSync *sync)
3489 {
3490    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3491    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3492    EGLint ret = EGL_TRUE;
3493    EGLint err;
3494
3495    /* if type of sync is EGL_SYNC_REUSABLE_KHR and it is not signaled yet,
3496     * then unlock all threads possibly blocked by the reusable sync before
3497     * destroying it.
3498     */
3499    if (dri2_sync->base.Type == EGL_SYNC_REUSABLE_KHR &&
3500        dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3501       dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3502       /* unblock all threads currently blocked by sync */
3503       err = cnd_broadcast(&dri2_sync->cond);
3504
3505       if (err) {
3506          _eglError(EGL_BAD_ACCESS, "eglDestroySyncKHR");
3507          ret = EGL_FALSE;
3508       }
3509    }
3510
3511    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3512
3513    return ret;
3514 }
3515
3516 static EGLint
3517 dri2_dup_native_fence_fd(_EGLDisplay *disp, _EGLSync *sync)
3518 {
3519    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3520    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3521
3522    assert(sync->Type == EGL_SYNC_NATIVE_FENCE_ANDROID);
3523
3524    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3525       /* try to retrieve the actual native fence fd.. if rendering is
3526        * not flushed this will just return -1, aka NO_NATIVE_FENCE_FD:
3527        */
3528       sync->SyncFd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
3529                                                    dri2_sync->fence);
3530    }
3531
3532    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3533       /* if native fence fd still not created, return an error: */
3534       _eglError(EGL_BAD_PARAMETER, "eglDupNativeFenceFDANDROID");
3535       return EGL_NO_NATIVE_FENCE_FD_ANDROID;
3536    }
3537
3538    assert(sync_valid_fd(sync->SyncFd));
3539
3540    return os_dupfd_cloexec(sync->SyncFd);
3541 }
3542
3543 static void
3544 dri2_set_blob_cache_funcs(_EGLDisplay *disp,
3545                           EGLSetBlobFuncANDROID set,
3546                           EGLGetBlobFuncANDROID get)
3547 {
3548    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3549    dri2_dpy->blob->set_cache_funcs(dri2_dpy->dri_screen,
3550                                    disp->BlobCacheSet,
3551                                    disp->BlobCacheGet);
3552 }
3553
3554 static EGLint
3555 dri2_client_wait_sync(_EGLDisplay *disp, _EGLSync *sync,
3556                       EGLint flags, EGLTime timeout)
3557 {
3558    _EGLContext *ctx = _eglGetCurrentContext();
3559    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3560    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3561    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3562    unsigned wait_flags = 0;
3563
3564    EGLint ret = EGL_CONDITION_SATISFIED_KHR;
3565
3566    /* The EGL_KHR_fence_sync spec states:
3567     *
3568     *    "If no context is current for the bound API,
3569     *     the EGL_SYNC_FLUSH_COMMANDS_BIT_KHR bit is ignored.
3570     */
3571    if (dri2_ctx && flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)
3572       wait_flags |= __DRI2_FENCE_FLAG_FLUSH_COMMANDS;
3573
3574    /* the sync object should take a reference while waiting */
3575    dri2_egl_ref_sync(dri2_sync);
3576
3577    switch (sync->Type) {
3578    case EGL_SYNC_FENCE_KHR:
3579    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3580    case EGL_SYNC_CL_EVENT_KHR:
3581       if (dri2_dpy->fence->client_wait_sync(dri2_ctx ? dri2_ctx->dri_context : NULL,
3582                                          dri2_sync->fence, wait_flags,
3583                                          timeout))
3584          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3585       else
3586          ret = EGL_TIMEOUT_EXPIRED_KHR;
3587       break;
3588
3589    case EGL_SYNC_REUSABLE_KHR:
3590       if (dri2_ctx && dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR &&
3591           (flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)) {
3592          /* flush context if EGL_SYNC_FLUSH_COMMANDS_BIT_KHR is set */
3593          dri2_gl_flush();
3594       }
3595
3596       /* if timeout is EGL_FOREVER_KHR, it should wait without any timeout.*/
3597       if (timeout == EGL_FOREVER_KHR) {
3598          mtx_lock(&dri2_sync->mutex);
3599          cnd_wait(&dri2_sync->cond, &dri2_sync->mutex);
3600          mtx_unlock(&dri2_sync->mutex);
3601       } else {
3602          /* if reusable sync has not been yet signaled */
3603          if (dri2_sync->base.SyncStatus != EGL_SIGNALED_KHR) {
3604             /* timespecs for cnd_timedwait */
3605             struct timespec current;
3606             struct timespec expire;
3607
3608             /* We override the clock to monotonic when creating the condition
3609              * variable. */
3610             clock_gettime(CLOCK_MONOTONIC, &current);
3611
3612             /* calculating when to expire */
3613             expire.tv_nsec = timeout % 1000000000L;
3614             expire.tv_sec = timeout / 1000000000L;
3615
3616             expire.tv_nsec += current.tv_nsec;
3617             expire.tv_sec += current.tv_sec;
3618
3619             /* expire.nsec now is a number between 0 and 1999999998 */
3620             if (expire.tv_nsec > 999999999L) {
3621                expire.tv_sec++;
3622                expire.tv_nsec -= 1000000000L;
3623             }
3624
3625             mtx_lock(&dri2_sync->mutex);
3626             ret = cnd_timedwait(&dri2_sync->cond, &dri2_sync->mutex, &expire);
3627             mtx_unlock(&dri2_sync->mutex);
3628
3629             if (ret == thrd_timedout) {
3630                if (dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3631                   ret = EGL_TIMEOUT_EXPIRED_KHR;
3632                } else {
3633                   _eglError(EGL_BAD_ACCESS, "eglClientWaitSyncKHR");
3634                   ret = EGL_FALSE;
3635                }
3636             }
3637          }
3638       }
3639       break;
3640   }
3641   dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3642
3643   return ret;
3644 }
3645
3646 static EGLBoolean
3647 dri2_signal_sync(_EGLDisplay *disp, _EGLSync *sync, EGLenum mode)
3648 {
3649    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3650    EGLint ret;
3651
3652    if (sync->Type != EGL_SYNC_REUSABLE_KHR)
3653       return _eglError(EGL_BAD_MATCH, "eglSignalSyncKHR");
3654
3655    if (mode != EGL_SIGNALED_KHR && mode != EGL_UNSIGNALED_KHR)
3656       return _eglError(EGL_BAD_ATTRIBUTE, "eglSignalSyncKHR");
3657
3658    dri2_sync->base.SyncStatus = mode;
3659
3660    if (mode == EGL_SIGNALED_KHR) {
3661       ret = cnd_broadcast(&dri2_sync->cond);
3662
3663       /* fail to broadcast */
3664       if (ret)
3665          return _eglError(EGL_BAD_ACCESS, "eglSignalSyncKHR");
3666    }
3667
3668    return EGL_TRUE;
3669 }
3670
3671 static EGLint
3672 dri2_server_wait_sync(_EGLDisplay *disp, _EGLSync *sync)
3673 {
3674    _EGLContext *ctx = _eglGetCurrentContext();
3675    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3676    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3677    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3678
3679    dri2_dpy->fence->server_wait_sync(dri2_ctx->dri_context,
3680                                      dri2_sync->fence, 0);
3681    return EGL_TRUE;
3682 }
3683
3684 static int
3685 dri2_interop_query_device_info(_EGLDisplay *disp, _EGLContext *ctx,
3686                                struct mesa_glinterop_device_info *out)
3687 {
3688    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3689    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3690
3691    if (!dri2_dpy->interop)
3692       return MESA_GLINTEROP_UNSUPPORTED;
3693
3694    return dri2_dpy->interop->query_device_info(dri2_ctx->dri_context, out);
3695 }
3696
3697 static int
3698 dri2_interop_export_object(_EGLDisplay *disp, _EGLContext *ctx,
3699                            struct mesa_glinterop_export_in *in,
3700                            struct mesa_glinterop_export_out *out)
3701 {
3702    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3703    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3704
3705    if (!dri2_dpy->interop)
3706       return MESA_GLINTEROP_UNSUPPORTED;
3707
3708    return dri2_dpy->interop->export_object(dri2_ctx->dri_context, in, out);
3709 }
3710
3711 const _EGLDriver _eglDriver = {
3712    .Initialize = dri2_initialize,
3713    .Terminate = dri2_terminate,
3714    .CreateContext = dri2_create_context,
3715    .DestroyContext = dri2_destroy_context,
3716    .MakeCurrent = dri2_make_current,
3717    .CreateWindowSurface = dri2_create_window_surface,
3718    .CreatePixmapSurface = dri2_create_pixmap_surface,
3719    .CreatePbufferSurface = dri2_create_pbuffer_surface,
3720    .DestroySurface = dri2_destroy_surface,
3721    .GetProcAddress = dri2_get_proc_address,
3722    .WaitClient = dri2_wait_client,
3723    .WaitNative = dri2_wait_native,
3724    .BindTexImage = dri2_bind_tex_image,
3725    .ReleaseTexImage = dri2_release_tex_image,
3726    .SwapInterval = dri2_swap_interval,
3727    .SwapBuffers = dri2_swap_buffers,
3728    .SwapBuffersWithDamageEXT = dri2_swap_buffers_with_damage,
3729    .SwapBuffersRegionNOK = dri2_swap_buffers_region,
3730    .SetDamageRegion = dri2_set_damage_region,
3731    .PostSubBufferNV = dri2_post_sub_buffer,
3732    .CopyBuffers = dri2_copy_buffers,
3733    .QueryBufferAge = dri2_query_buffer_age,
3734    .CreateImageKHR = dri2_create_image,
3735    .DestroyImageKHR = dri2_destroy_image_khr,
3736    .CreateWaylandBufferFromImageWL = dri2_create_wayland_buffer_from_image,
3737    .QuerySurface = dri2_query_surface,
3738    .QueryDriverName = dri2_query_driver_name,
3739    .QueryDriverConfig = dri2_query_driver_config,
3740 #ifdef HAVE_LIBDRM
3741    .CreateDRMImageMESA = dri2_create_drm_image_mesa,
3742    .ExportDRMImageMESA = dri2_export_drm_image_mesa,
3743    .ExportDMABUFImageQueryMESA = dri2_export_dma_buf_image_query_mesa,
3744    .ExportDMABUFImageMESA = dri2_export_dma_buf_image_mesa,
3745    .QueryDmaBufFormatsEXT = dri2_query_dma_buf_formats,
3746    .QueryDmaBufModifiersEXT = dri2_query_dma_buf_modifiers,
3747 #endif
3748 #ifdef HAVE_WAYLAND_PLATFORM
3749    .BindWaylandDisplayWL = dri2_bind_wayland_display_wl,
3750    .UnbindWaylandDisplayWL = dri2_unbind_wayland_display_wl,
3751    .QueryWaylandBufferWL = dri2_query_wayland_buffer_wl,
3752 #endif
3753    .GetSyncValuesCHROMIUM = dri2_get_sync_values_chromium,
3754    .GetMscRateANGLE = dri2_get_msc_rate_angle,
3755    .CreateSyncKHR = dri2_create_sync,
3756    .ClientWaitSyncKHR = dri2_client_wait_sync,
3757    .SignalSyncKHR = dri2_signal_sync,
3758    .WaitSyncKHR = dri2_server_wait_sync,
3759    .DestroySyncKHR = dri2_destroy_sync,
3760    .GLInteropQueryDeviceInfo = dri2_interop_query_device_info,
3761    .GLInteropExportObject = dri2_interop_export_object,
3762    .DupNativeFenceFDANDROID = dri2_dup_native_fence_fd,
3763    .SetBlobCacheFuncsANDROID = dri2_set_blob_cache_funcs,
3764 };