dri: add [ax]bgr16161616 to format lookup tables
[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 /**
2391  * Set the error code after a call to
2392  * dri2_egl_image::dri_image::createImageFromTexture.
2393  */
2394 static void
2395 dri2_create_image_khr_texture_error(int dri_error)
2396 {
2397    EGLint egl_error = egl_error_from_dri_image_error(dri_error);
2398
2399    if (egl_error != EGL_SUCCESS)
2400       _eglError(egl_error, "dri2_create_image_khr_texture");
2401 }
2402
2403 static _EGLImage *
2404 dri2_create_image_khr_texture(_EGLDisplay *disp, _EGLContext *ctx,
2405                                    EGLenum target,
2406                                    EGLClientBuffer buffer,
2407                                    const EGLint *attr_list)
2408 {
2409    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2410    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2411    struct dri2_egl_image *dri2_img;
2412    GLuint texture = (GLuint) (uintptr_t) buffer;
2413    _EGLImageAttribs attrs;
2414    GLuint depth;
2415    GLenum gl_target;
2416    unsigned error;
2417
2418    if (texture == 0) {
2419       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2420       return EGL_NO_IMAGE_KHR;
2421    }
2422
2423    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2424       return EGL_NO_IMAGE_KHR;
2425
2426    switch (target) {
2427    case EGL_GL_TEXTURE_2D_KHR:
2428       if (!disp->Extensions.KHR_gl_texture_2D_image) {
2429          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2430          return EGL_NO_IMAGE_KHR;
2431       }
2432       depth = 0;
2433       gl_target = GL_TEXTURE_2D;
2434       break;
2435    case EGL_GL_TEXTURE_3D_KHR:
2436       if (!disp->Extensions.KHR_gl_texture_3D_image) {
2437          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2438          return EGL_NO_IMAGE_KHR;
2439       }
2440
2441       depth = attrs.GLTextureZOffset;
2442       gl_target = GL_TEXTURE_3D;
2443       break;
2444    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
2445    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
2446    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
2447    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
2448    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
2449    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
2450       if (!disp->Extensions.KHR_gl_texture_cubemap_image) {
2451          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2452          return EGL_NO_IMAGE_KHR;
2453       }
2454
2455       depth = target - EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR;
2456       gl_target = GL_TEXTURE_CUBE_MAP;
2457       break;
2458    default:
2459       unreachable("Unexpected target in dri2_create_image_khr_texture()");
2460       return EGL_NO_IMAGE_KHR;
2461    }
2462
2463    dri2_img = malloc(sizeof *dri2_img);
2464    if (!dri2_img) {
2465       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2466       return EGL_NO_IMAGE_KHR;
2467    }
2468
2469    _eglInitImage(&dri2_img->base, disp);
2470
2471    dri2_img->dri_image =
2472       dri2_dpy->image->createImageFromTexture(dri2_ctx->dri_context,
2473                                               gl_target,
2474                                               texture,
2475                                               depth,
2476                                               attrs.GLTextureLevel,
2477                                               &error,
2478                                               NULL);
2479    dri2_create_image_khr_texture_error(error);
2480
2481    if (!dri2_img->dri_image) {
2482       free(dri2_img);
2483       return EGL_NO_IMAGE_KHR;
2484    }
2485    return &dri2_img->base;
2486 }
2487
2488 static EGLBoolean
2489 dri2_query_surface(_EGLDisplay *disp, _EGLSurface *surf,
2490                    EGLint attribute, EGLint *value)
2491 {
2492    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2493    if (!dri2_dpy->vtbl->query_surface)
2494       return _eglQuerySurface(disp, surf, attribute, value);
2495    return dri2_dpy->vtbl->query_surface(disp, surf, attribute, value);
2496 }
2497
2498 static struct wl_buffer*
2499 dri2_create_wayland_buffer_from_image(_EGLDisplay *disp, _EGLImage *img)
2500 {
2501    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2502    if (!dri2_dpy->vtbl->create_wayland_buffer_from_image)
2503       return NULL;
2504    return dri2_dpy->vtbl->create_wayland_buffer_from_image(disp, img);
2505 }
2506
2507 #ifdef HAVE_LIBDRM
2508 static _EGLImage *
2509 dri2_create_image_mesa_drm_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2510                                   EGLClientBuffer buffer, const EGLint *attr_list)
2511 {
2512    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2513    EGLint format, name, pitch;
2514    _EGLImageAttribs attrs;
2515    __DRIimage *dri_image;
2516
2517    name = (EGLint) (uintptr_t) buffer;
2518
2519    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2520       return NULL;
2521
2522    if (attrs.Width <= 0 || attrs.Height <= 0 ||
2523        attrs.DRMBufferStrideMESA <= 0) {
2524       _eglError(EGL_BAD_PARAMETER,
2525                 "bad width, height or stride");
2526       return NULL;
2527    }
2528
2529    switch (attrs.DRMBufferFormatMESA) {
2530    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2531       format = __DRI_IMAGE_FORMAT_ARGB8888;
2532       pitch = attrs.DRMBufferStrideMESA;
2533       break;
2534    default:
2535       _eglError(EGL_BAD_PARAMETER,
2536                 "dri2_create_image_khr: unsupported pixmap depth");
2537       return NULL;
2538    }
2539
2540    dri_image =
2541       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
2542                                            attrs.Width,
2543                                            attrs.Height,
2544                                            format,
2545                                            name,
2546                                            pitch,
2547                                            NULL);
2548
2549    return dri2_create_image_from_dri(disp, dri_image);
2550 }
2551
2552 static EGLBoolean
2553 dri2_check_dma_buf_attribs(const _EGLImageAttribs *attrs)
2554 {
2555    /**
2556      * The spec says:
2557      *
2558      * "Required attributes and their values are as follows:
2559      *
2560      *  * EGL_WIDTH & EGL_HEIGHT: The logical dimensions of the buffer in pixels
2561      *
2562      *  * EGL_LINUX_DRM_FOURCC_EXT: The pixel format of the buffer, as specified
2563      *    by drm_fourcc.h and used as the pixel_format parameter of the
2564      *    drm_mode_fb_cmd2 ioctl."
2565      *
2566      * and
2567      *
2568      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2569      *    incomplete, EGL_BAD_PARAMETER is generated."
2570      */
2571    if (attrs->Width <= 0 || attrs->Height <= 0 ||
2572        !attrs->DMABufFourCC.IsPresent)
2573       return _eglError(EGL_BAD_PARAMETER, "attribute(s) missing");
2574
2575    /**
2576     * Also:
2577     *
2578     * "If <target> is EGL_LINUX_DMA_BUF_EXT and one or more of the values
2579     *  specified for a plane's pitch or offset isn't supported by EGL,
2580     *  EGL_BAD_ACCESS is generated."
2581     */
2582    for (unsigned i = 0; i < ARRAY_SIZE(attrs->DMABufPlanePitches); ++i) {
2583       if (attrs->DMABufPlanePitches[i].IsPresent &&
2584           attrs->DMABufPlanePitches[i].Value <= 0)
2585          return _eglError(EGL_BAD_ACCESS, "invalid pitch");
2586    }
2587
2588    /**
2589     * If <target> is EGL_LINUX_DMA_BUF_EXT, both or neither of the following
2590     * attribute values may be given.
2591     *
2592     * This is referring to EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT and
2593     * EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, and the same for other planes.
2594     */
2595    for (unsigned i = 0; i < DMA_BUF_MAX_PLANES; ++i) {
2596       if (attrs->DMABufPlaneModifiersLo[i].IsPresent !=
2597           attrs->DMABufPlaneModifiersHi[i].IsPresent)
2598          return _eglError(EGL_BAD_PARAMETER, "modifier attribute lo or hi missing");
2599    }
2600
2601    /* Although the EGL_EXT_image_dma_buf_import_modifiers spec doesn't
2602     * mandate it, we only accept the same modifier across all planes. */
2603    for (unsigned i = 1; i < DMA_BUF_MAX_PLANES; ++i) {
2604       if (attrs->DMABufPlaneFds[i].IsPresent) {
2605          if ((attrs->DMABufPlaneModifiersLo[0].IsPresent !=
2606                attrs->DMABufPlaneModifiersLo[i].IsPresent) ||
2607              (attrs->DMABufPlaneModifiersLo[0].Value !=
2608                attrs->DMABufPlaneModifiersLo[i].Value) ||
2609              (attrs->DMABufPlaneModifiersHi[0].Value !=
2610                attrs->DMABufPlaneModifiersHi[i].Value))
2611             return _eglError(EGL_BAD_PARAMETER, "modifier attributes not equal");
2612       }
2613    }
2614
2615    return EGL_TRUE;
2616 }
2617
2618 /* Returns the total number of planes for the format or zero if it isn't a
2619  * valid fourcc format.
2620  */
2621 static unsigned
2622 dri2_num_fourcc_format_planes(EGLint format)
2623 {
2624    switch (format) {
2625    case DRM_FORMAT_R8:
2626    case DRM_FORMAT_RG88:
2627    case DRM_FORMAT_GR88:
2628    case DRM_FORMAT_R16:
2629    case DRM_FORMAT_GR1616:
2630    case DRM_FORMAT_RGB332:
2631    case DRM_FORMAT_BGR233:
2632    case DRM_FORMAT_XRGB4444:
2633    case DRM_FORMAT_XBGR4444:
2634    case DRM_FORMAT_RGBX4444:
2635    case DRM_FORMAT_BGRX4444:
2636    case DRM_FORMAT_ARGB4444:
2637    case DRM_FORMAT_ABGR4444:
2638    case DRM_FORMAT_RGBA4444:
2639    case DRM_FORMAT_BGRA4444:
2640    case DRM_FORMAT_XRGB1555:
2641    case DRM_FORMAT_XBGR1555:
2642    case DRM_FORMAT_RGBX5551:
2643    case DRM_FORMAT_BGRX5551:
2644    case DRM_FORMAT_ARGB1555:
2645    case DRM_FORMAT_ABGR1555:
2646    case DRM_FORMAT_RGBA5551:
2647    case DRM_FORMAT_BGRA5551:
2648    case DRM_FORMAT_RGB565:
2649    case DRM_FORMAT_BGR565:
2650    case DRM_FORMAT_RGB888:
2651    case DRM_FORMAT_BGR888:
2652    case DRM_FORMAT_XRGB8888:
2653    case DRM_FORMAT_XBGR8888:
2654    case DRM_FORMAT_RGBX8888:
2655    case DRM_FORMAT_BGRX8888:
2656    case DRM_FORMAT_ARGB8888:
2657    case DRM_FORMAT_ABGR8888:
2658    case DRM_FORMAT_RGBA8888:
2659    case DRM_FORMAT_BGRA8888:
2660    case DRM_FORMAT_XRGB2101010:
2661    case DRM_FORMAT_XBGR2101010:
2662    case DRM_FORMAT_RGBX1010102:
2663    case DRM_FORMAT_BGRX1010102:
2664    case DRM_FORMAT_ARGB2101010:
2665    case DRM_FORMAT_ABGR2101010:
2666    case DRM_FORMAT_RGBA1010102:
2667    case DRM_FORMAT_BGRA1010102:
2668    case DRM_FORMAT_ABGR16161616:
2669    case DRM_FORMAT_XBGR16161616:
2670    case DRM_FORMAT_XBGR16161616F:
2671    case DRM_FORMAT_ABGR16161616F:
2672    case DRM_FORMAT_YUYV:
2673    case DRM_FORMAT_YVYU:
2674    case DRM_FORMAT_UYVY:
2675    case DRM_FORMAT_VYUY:
2676    case DRM_FORMAT_AYUV:
2677    case DRM_FORMAT_XYUV8888:
2678    case DRM_FORMAT_Y210:
2679    case DRM_FORMAT_Y212:
2680    case DRM_FORMAT_Y216:
2681    case DRM_FORMAT_Y410:
2682    case DRM_FORMAT_Y412:
2683    case DRM_FORMAT_Y416:
2684       return 1;
2685
2686    case DRM_FORMAT_NV12:
2687    case DRM_FORMAT_NV21:
2688    case DRM_FORMAT_NV16:
2689    case DRM_FORMAT_NV61:
2690    case DRM_FORMAT_P010:
2691    case DRM_FORMAT_P012:
2692    case DRM_FORMAT_P016:
2693       return 2;
2694
2695    case DRM_FORMAT_YUV410:
2696    case DRM_FORMAT_YVU410:
2697    case DRM_FORMAT_YUV411:
2698    case DRM_FORMAT_YVU411:
2699    case DRM_FORMAT_YUV420:
2700    case DRM_FORMAT_YVU420:
2701    case DRM_FORMAT_YUV422:
2702    case DRM_FORMAT_YVU422:
2703    case DRM_FORMAT_YUV444:
2704    case DRM_FORMAT_YVU444:
2705       return 3;
2706
2707    default:
2708       return 0;
2709    }
2710 }
2711
2712 /* Returns the total number of file descriptors. Zero indicates an error. */
2713 static unsigned
2714 dri2_check_dma_buf_format(const _EGLImageAttribs *attrs)
2715 {
2716    unsigned plane_n = dri2_num_fourcc_format_planes(attrs->DMABufFourCC.Value);
2717    if (plane_n == 0) {
2718       _eglError(EGL_BAD_MATCH, "unknown drm fourcc format");
2719       return 0;
2720    }
2721
2722    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; i++) {
2723       /**
2724        * The modifiers extension spec says:
2725        *
2726        * "Modifiers may modify any attribute of a buffer import, including
2727        *  but not limited to adding extra planes to a format which
2728        *  otherwise does not have those planes. As an example, a modifier
2729        *  may add a plane for an external compression buffer to a
2730        *  single-plane format. The exact meaning and effect of any
2731        *  modifier is canonically defined by drm_fourcc.h, not as part of
2732        *  this extension."
2733        */
2734       if (attrs->DMABufPlaneModifiersLo[i].IsPresent &&
2735           attrs->DMABufPlaneModifiersHi[i].IsPresent) {
2736          plane_n = i + 1;
2737       }
2738    }
2739
2740    /**
2741      * The spec says:
2742      *
2743      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2744      *    incomplete, EGL_BAD_PARAMETER is generated."
2745      */
2746    for (unsigned i = 0; i < plane_n; ++i) {
2747       if (!attrs->DMABufPlaneFds[i].IsPresent ||
2748           !attrs->DMABufPlaneOffsets[i].IsPresent ||
2749           !attrs->DMABufPlanePitches[i].IsPresent) {
2750          _eglError(EGL_BAD_PARAMETER, "plane attribute(s) missing");
2751          return 0;
2752       }
2753    }
2754
2755    /**
2756     * The spec also says:
2757     *
2758     * "If <target> is EGL_LINUX_DMA_BUF_EXT, and the EGL_LINUX_DRM_FOURCC_EXT
2759     *  attribute indicates a single-plane format, EGL_BAD_ATTRIBUTE is
2760     *  generated if any of the EGL_DMA_BUF_PLANE1_* or EGL_DMA_BUF_PLANE2_*
2761     *  or EGL_DMA_BUF_PLANE3_* attributes are specified."
2762     */
2763    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; ++i) {
2764       if (attrs->DMABufPlaneFds[i].IsPresent ||
2765           attrs->DMABufPlaneOffsets[i].IsPresent ||
2766           attrs->DMABufPlanePitches[i].IsPresent) {
2767          _eglError(EGL_BAD_ATTRIBUTE, "too many plane attributes");
2768          return 0;
2769       }
2770    }
2771
2772    return plane_n;
2773 }
2774
2775 static EGLBoolean
2776 dri2_query_dma_buf_formats(_EGLDisplay *disp, EGLint max,
2777                            EGLint *formats, EGLint *count)
2778 {
2779    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2780    if (max < 0 || (max > 0 && formats == NULL))
2781       return _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2782
2783    if (dri2_dpy->image->base.version < 15 ||
2784        dri2_dpy->image->queryDmaBufFormats == NULL)
2785       return EGL_FALSE;
2786
2787    if (!dri2_dpy->image->queryDmaBufFormats(dri2_dpy->dri_screen, max,
2788                                             formats, count))
2789       return EGL_FALSE;
2790
2791    if (max > 0) {
2792       /* Assert that all of the formats returned are actually fourcc formats.
2793        * Some day, if we want the internal interface function to be able to
2794        * return the fake fourcc formats defined in dri_interface.h, we'll have
2795        * to do something more clever here to pair the list down to just real
2796        * fourcc formats so that we don't leak the fake internal ones.
2797        */
2798       for (int i = 0; i < *count; i++) {
2799          assert(dri2_num_fourcc_format_planes(formats[i]) > 0);
2800       }
2801    }
2802
2803    return EGL_TRUE;
2804 }
2805
2806 static EGLBoolean
2807 dri2_query_dma_buf_modifiers(_EGLDisplay *disp, EGLint format,
2808                              EGLint max, EGLuint64KHR *modifiers,
2809                              EGLBoolean *external_only, EGLint *count)
2810 {
2811    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2812
2813    if (dri2_num_fourcc_format_planes(format) == 0)
2814       return _eglError(EGL_BAD_PARAMETER, "invalid fourcc format");
2815
2816    if (max < 0)
2817       return _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2818
2819    if (max > 0 && modifiers == NULL)
2820       return _eglError(EGL_BAD_PARAMETER, "invalid modifiers array");
2821
2822    if (dri2_dpy->image->base.version < 15 ||
2823        dri2_dpy->image->queryDmaBufModifiers == NULL)
2824       return EGL_FALSE;
2825
2826    if (dri2_dpy->image->queryDmaBufModifiers(dri2_dpy->dri_screen, format,
2827                                              max, modifiers,
2828                                              (unsigned int *) external_only,
2829                                              count) == false)
2830       return _eglError(EGL_BAD_PARAMETER, "invalid format");
2831
2832    return EGL_TRUE;
2833 }
2834
2835 /**
2836  * The spec says:
2837  *
2838  * "If eglCreateImageKHR is successful for a EGL_LINUX_DMA_BUF_EXT target, the
2839  *  EGL will take a reference to the dma_buf(s) which it will release at any
2840  *  time while the EGLDisplay is initialized. It is the responsibility of the
2841  *  application to close the dma_buf file descriptors."
2842  *
2843  * Therefore we must never close or otherwise modify the file descriptors.
2844  */
2845 _EGLImage *
2846 dri2_create_image_dma_buf(_EGLDisplay *disp, _EGLContext *ctx,
2847                           EGLClientBuffer buffer, const EGLint *attr_list)
2848 {
2849    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2850    _EGLImage *res;
2851    _EGLImageAttribs attrs;
2852    __DRIimage *dri_image;
2853    unsigned num_fds;
2854    int fds[DMA_BUF_MAX_PLANES];
2855    int pitches[DMA_BUF_MAX_PLANES];
2856    int offsets[DMA_BUF_MAX_PLANES];
2857    uint64_t modifier;
2858    bool has_modifier = false;
2859    unsigned error;
2860
2861    /**
2862     * The spec says:
2863     *
2864     * ""* If <target> is EGL_LINUX_DMA_BUF_EXT and <buffer> is not NULL, the
2865     *     error EGL_BAD_PARAMETER is generated."
2866     */
2867    if (buffer != NULL) {
2868       _eglError(EGL_BAD_PARAMETER, "buffer not NULL");
2869       return NULL;
2870    }
2871
2872    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2873       return NULL;
2874
2875    if (!dri2_check_dma_buf_attribs(&attrs))
2876       return NULL;
2877
2878    num_fds = dri2_check_dma_buf_format(&attrs);
2879    if (!num_fds)
2880       return NULL;
2881
2882    for (unsigned i = 0; i < num_fds; ++i) {
2883       fds[i] = attrs.DMABufPlaneFds[i].Value;
2884       pitches[i] = attrs.DMABufPlanePitches[i].Value;
2885       offsets[i] = attrs.DMABufPlaneOffsets[i].Value;
2886    }
2887
2888    /* dri2_check_dma_buf_attribs ensures that the modifier, if available,
2889     * will be present in attrs.DMABufPlaneModifiersLo[0] and
2890     * attrs.DMABufPlaneModifiersHi[0] */
2891    if (attrs.DMABufPlaneModifiersLo[0].IsPresent) {
2892       modifier = combine_u32_into_u64(attrs.DMABufPlaneModifiersHi[0].Value,
2893                                       attrs.DMABufPlaneModifiersLo[0].Value);
2894       has_modifier = true;
2895    }
2896
2897    if (attrs.ProtectedContent) {
2898       if (dri2_dpy->image->base.version < 18 ||
2899           dri2_dpy->image->createImageFromDmaBufs3 == NULL) {
2900          _eglError(EGL_BAD_MATCH, "unsupported protected_content attribute");
2901          return EGL_NO_IMAGE_KHR;
2902       }
2903       if (!has_modifier)
2904          modifier = DRM_FORMAT_MOD_INVALID;
2905
2906       dri_image =
2907          dri2_dpy->image->createImageFromDmaBufs3(dri2_dpy->dri_screen,
2908             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2909             modifier, fds, num_fds, pitches, offsets,
2910             attrs.DMABufYuvColorSpaceHint.Value,
2911             attrs.DMABufSampleRangeHint.Value,
2912             attrs.DMABufChromaHorizontalSiting.Value,
2913             attrs.DMABufChromaVerticalSiting.Value,
2914             attrs.ProtectedContent ? __DRI_IMAGE_PROTECTED_CONTENT_FLAG : 0,
2915             &error,
2916             NULL);
2917    }
2918    else if (has_modifier) {
2919       if (dri2_dpy->image->base.version < 15 ||
2920           dri2_dpy->image->createImageFromDmaBufs2 == NULL) {
2921          _eglError(EGL_BAD_MATCH, "unsupported dma_buf format modifier");
2922          return EGL_NO_IMAGE_KHR;
2923       }
2924       dri_image =
2925          dri2_dpy->image->createImageFromDmaBufs2(dri2_dpy->dri_screen,
2926             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2927             modifier, fds, num_fds, pitches, offsets,
2928             attrs.DMABufYuvColorSpaceHint.Value,
2929             attrs.DMABufSampleRangeHint.Value,
2930             attrs.DMABufChromaHorizontalSiting.Value,
2931             attrs.DMABufChromaVerticalSiting.Value,
2932             &error,
2933             NULL);
2934    }
2935    else {
2936       dri_image =
2937          dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
2938             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2939             fds, num_fds, pitches, offsets,
2940             attrs.DMABufYuvColorSpaceHint.Value,
2941             attrs.DMABufSampleRangeHint.Value,
2942             attrs.DMABufChromaHorizontalSiting.Value,
2943             attrs.DMABufChromaVerticalSiting.Value,
2944             &error,
2945             NULL);
2946    }
2947    dri2_create_image_khr_texture_error(error);
2948
2949    if (!dri_image)
2950       return EGL_NO_IMAGE_KHR;
2951
2952    res = dri2_create_image_from_dri(disp, dri_image);
2953
2954    return res;
2955 }
2956 static _EGLImage *
2957 dri2_create_drm_image_mesa(_EGLDisplay *disp, const EGLint *attr_list)
2958 {
2959    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2960    struct dri2_egl_image *dri2_img;
2961    _EGLImageAttribs attrs;
2962    unsigned int dri_use, valid_mask;
2963    int format;
2964
2965    if (!attr_list) {
2966       _eglError(EGL_BAD_PARAMETER, __func__);
2967       return EGL_NO_IMAGE_KHR;
2968    }
2969
2970    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2971       return EGL_NO_IMAGE_KHR;
2972
2973    if (attrs.Width <= 0 || attrs.Height <= 0) {
2974       _eglError(EGL_BAD_PARAMETER, __func__);
2975       return EGL_NO_IMAGE_KHR;
2976    }
2977
2978    switch (attrs.DRMBufferFormatMESA) {
2979    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2980       format = __DRI_IMAGE_FORMAT_ARGB8888;
2981       break;
2982    default:
2983       _eglError(EGL_BAD_PARAMETER, __func__);
2984       return EGL_NO_IMAGE_KHR;
2985    }
2986
2987    valid_mask =
2988       EGL_DRM_BUFFER_USE_SCANOUT_MESA |
2989       EGL_DRM_BUFFER_USE_SHARE_MESA |
2990       EGL_DRM_BUFFER_USE_CURSOR_MESA;
2991    if (attrs.DRMBufferUseMESA & ~valid_mask) {
2992       _eglError(EGL_BAD_PARAMETER, __func__);
2993       return EGL_NO_IMAGE_KHR;
2994    }
2995
2996    dri_use = 0;
2997    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SHARE_MESA)
2998       dri_use |= __DRI_IMAGE_USE_SHARE;
2999    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SCANOUT_MESA)
3000       dri_use |= __DRI_IMAGE_USE_SCANOUT;
3001    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_CURSOR_MESA)
3002       dri_use |= __DRI_IMAGE_USE_CURSOR;
3003
3004    dri2_img = malloc(sizeof *dri2_img);
3005    if (!dri2_img) {
3006       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
3007       return EGL_NO_IMAGE_KHR;
3008    }
3009
3010    _eglInitImage(&dri2_img->base, disp);
3011
3012    dri2_img->dri_image =
3013       dri2_dpy->image->createImage(dri2_dpy->dri_screen,
3014                                    attrs.Width, attrs.Height,
3015                                    format, dri_use, dri2_img);
3016    if (dri2_img->dri_image == NULL) {
3017       free(dri2_img);
3018        _eglError(EGL_BAD_ALLOC, "dri2_create_drm_image_mesa");
3019       return EGL_NO_IMAGE_KHR;
3020    }
3021
3022    return &dri2_img->base;
3023 }
3024
3025 static EGLBoolean
3026 dri2_export_drm_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3027                           EGLint *name, EGLint *handle, EGLint *stride)
3028 {
3029    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3030    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3031
3032    if (name && !dri2_dpy->image->queryImage(dri2_img->dri_image,
3033                                             __DRI_IMAGE_ATTRIB_NAME, name))
3034       return _eglError(EGL_BAD_ALLOC, "dri2_export_drm_image_mesa");
3035
3036    if (handle)
3037       dri2_dpy->image->queryImage(dri2_img->dri_image,
3038                                   __DRI_IMAGE_ATTRIB_HANDLE, handle);
3039
3040    if (stride)
3041       dri2_dpy->image->queryImage(dri2_img->dri_image,
3042                                   __DRI_IMAGE_ATTRIB_STRIDE, stride);
3043
3044    return EGL_TRUE;
3045 }
3046
3047 /**
3048  * Checks if we can support EGL_MESA_image_dma_buf_export on this image.
3049
3050  * The spec provides a boolean return for the driver to reject exporting for
3051  * basically any reason, but doesn't specify any particular error cases.  For
3052  * now, we just fail if we don't have a DRM fourcc for the format.
3053  */
3054 static bool
3055 dri2_can_export_dma_buf_image(_EGLDisplay *disp, _EGLImage *img)
3056 {
3057    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3058    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3059    EGLint fourcc;
3060
3061    if (!dri2_dpy->image->queryImage(dri2_img->dri_image,
3062                                     __DRI_IMAGE_ATTRIB_FOURCC, &fourcc)) {
3063       return false;
3064    }
3065
3066    return true;
3067 }
3068
3069 static EGLBoolean
3070 dri2_export_dma_buf_image_query_mesa(_EGLDisplay *disp, _EGLImage *img,
3071                                      EGLint *fourcc, EGLint *nplanes,
3072                                      EGLuint64KHR *modifiers)
3073 {
3074    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3075    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3076    int num_planes;
3077
3078    if (!dri2_can_export_dma_buf_image(disp, img))
3079       return EGL_FALSE;
3080
3081    dri2_dpy->image->queryImage(dri2_img->dri_image,
3082                                __DRI_IMAGE_ATTRIB_NUM_PLANES, &num_planes);
3083    if (nplanes)
3084      *nplanes = num_planes;
3085
3086    if (fourcc)
3087       dri2_dpy->image->queryImage(dri2_img->dri_image,
3088                                   __DRI_IMAGE_ATTRIB_FOURCC, fourcc);
3089
3090    if (modifiers) {
3091       int mod_hi, mod_lo;
3092       uint64_t modifier = DRM_FORMAT_MOD_INVALID;
3093       bool query;
3094
3095       query = dri2_dpy->image->queryImage(dri2_img->dri_image,
3096                                           __DRI_IMAGE_ATTRIB_MODIFIER_UPPER,
3097                                           &mod_hi);
3098       query &= dri2_dpy->image->queryImage(dri2_img->dri_image,
3099                                            __DRI_IMAGE_ATTRIB_MODIFIER_LOWER,
3100                                            &mod_lo);
3101       if (query)
3102          modifier = combine_u32_into_u64 (mod_hi, mod_lo);
3103
3104       for (int i = 0; i < num_planes; i++)
3105         modifiers[i] = modifier;
3106    }
3107
3108    return EGL_TRUE;
3109 }
3110
3111 static EGLBoolean
3112 dri2_export_dma_buf_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3113                                int *fds, EGLint *strides, EGLint *offsets)
3114 {
3115    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3116    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3117    EGLint nplanes;
3118
3119    if (!dri2_can_export_dma_buf_image(disp, img))
3120       return EGL_FALSE;
3121
3122    /* EGL_MESA_image_dma_buf_export spec says:
3123     *    "If the number of fds is less than the number of planes, then
3124     *    subsequent fd slots should contain -1."
3125     */
3126    if (fds) {
3127       /* Query nplanes so that we know how big the given array is. */
3128       dri2_dpy->image->queryImage(dri2_img->dri_image,
3129                                   __DRI_IMAGE_ATTRIB_NUM_PLANES, &nplanes);
3130       memset(fds, -1, nplanes * sizeof(int));
3131    }
3132
3133    /* rework later to provide multiple fds/strides/offsets */
3134    if (fds)
3135       dri2_dpy->image->queryImage(dri2_img->dri_image,
3136                                   __DRI_IMAGE_ATTRIB_FD, fds);
3137
3138    if (strides)
3139       dri2_dpy->image->queryImage(dri2_img->dri_image,
3140                                   __DRI_IMAGE_ATTRIB_STRIDE, strides);
3141
3142    if (offsets) {
3143       int img_offset;
3144       bool ret = dri2_dpy->image->queryImage(dri2_img->dri_image,
3145                      __DRI_IMAGE_ATTRIB_OFFSET, &img_offset);
3146       if (ret)
3147          offsets[0] = img_offset;
3148       else
3149          offsets[0] = 0;
3150    }
3151
3152    return EGL_TRUE;
3153 }
3154
3155 #endif
3156
3157 _EGLImage *
3158 dri2_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
3159                       EGLClientBuffer buffer, const EGLint *attr_list)
3160 {
3161    switch (target) {
3162    case EGL_GL_TEXTURE_2D_KHR:
3163    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
3164    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
3165    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
3166    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
3167    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
3168    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
3169    case EGL_GL_TEXTURE_3D_KHR:
3170       return dri2_create_image_khr_texture(disp, ctx, target, buffer, attr_list);
3171    case EGL_GL_RENDERBUFFER_KHR:
3172       return dri2_create_image_khr_renderbuffer(disp, ctx, buffer, attr_list);
3173 #ifdef HAVE_LIBDRM
3174    case EGL_DRM_BUFFER_MESA:
3175       return dri2_create_image_mesa_drm_buffer(disp, ctx, buffer, attr_list);
3176    case EGL_LINUX_DMA_BUF_EXT:
3177       return dri2_create_image_dma_buf(disp, ctx, buffer, attr_list);
3178 #endif
3179 #ifdef HAVE_WAYLAND_PLATFORM
3180    case EGL_WAYLAND_BUFFER_WL:
3181       return dri2_create_image_wayland_wl_buffer(disp, ctx, buffer, attr_list);
3182 #endif
3183    default:
3184       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
3185       return EGL_NO_IMAGE_KHR;
3186    }
3187 }
3188
3189 static EGLBoolean
3190 dri2_destroy_image_khr(_EGLDisplay *disp, _EGLImage *image)
3191 {
3192    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3193    struct dri2_egl_image *dri2_img = dri2_egl_image(image);
3194
3195    dri2_dpy->image->destroyImage(dri2_img->dri_image);
3196    free(dri2_img);
3197
3198    return EGL_TRUE;
3199 }
3200
3201 #ifdef HAVE_WAYLAND_PLATFORM
3202
3203 static void
3204 dri2_wl_reference_buffer(void *user_data, uint32_t name, int fd,
3205                          struct wl_drm_buffer *buffer)
3206 {
3207    _EGLDisplay *disp = user_data;
3208    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3209    __DRIimage *img;
3210    int dri_components = 0;
3211
3212    if (fd == -1)
3213       img = dri2_dpy->image->createImageFromNames(dri2_dpy->dri_screen,
3214                                                   buffer->width,
3215                                                   buffer->height,
3216                                                   buffer->format,
3217                                                   (int*)&name, 1,
3218                                                   buffer->stride,
3219                                                   buffer->offset,
3220                                                   NULL);
3221    else
3222       img = dri2_dpy->image->createImageFromFds(dri2_dpy->dri_screen,
3223                                                 buffer->width,
3224                                                 buffer->height,
3225                                                 buffer->format,
3226                                                 &fd, 1,
3227                                                 buffer->stride,
3228                                                 buffer->offset,
3229                                                 NULL);
3230
3231    if (img == NULL)
3232       return;
3233
3234    dri2_dpy->image->queryImage(img, __DRI_IMAGE_ATTRIB_COMPONENTS, &dri_components);
3235
3236    buffer->driver_format = NULL;
3237    for (int i = 0; i < ARRAY_SIZE(wl_drm_components); i++)
3238       if (wl_drm_components[i].dri_components == dri_components)
3239          buffer->driver_format = &wl_drm_components[i];
3240
3241    if (buffer->driver_format == NULL)
3242       dri2_dpy->image->destroyImage(img);
3243    else
3244       buffer->driver_buffer = img;
3245 }
3246
3247 static void
3248 dri2_wl_release_buffer(void *user_data, struct wl_drm_buffer *buffer)
3249 {
3250    _EGLDisplay *disp = user_data;
3251    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3252
3253    dri2_dpy->image->destroyImage(buffer->driver_buffer);
3254 }
3255
3256 static EGLBoolean
3257 dri2_bind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3258 {
3259    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3260    const struct wayland_drm_callbacks wl_drm_callbacks = {
3261       .authenticate = (int(*)(void *, uint32_t)) dri2_dpy->vtbl->authenticate,
3262       .reference_buffer = dri2_wl_reference_buffer,
3263       .release_buffer = dri2_wl_release_buffer,
3264       .is_format_supported = dri2_wl_is_format_supported
3265    };
3266    int flags = 0;
3267    char *device_name;
3268    uint64_t cap;
3269
3270    if (dri2_dpy->wl_server_drm)
3271            return EGL_FALSE;
3272
3273    device_name = drmGetRenderDeviceNameFromFd(dri2_dpy->fd);
3274    if (!device_name)
3275       device_name = strdup(dri2_dpy->device_name);
3276    if (!device_name)
3277       return EGL_FALSE;
3278
3279    if (drmGetCap(dri2_dpy->fd, DRM_CAP_PRIME, &cap) == 0 &&
3280        cap == (DRM_PRIME_CAP_IMPORT | DRM_PRIME_CAP_EXPORT) &&
3281        dri2_dpy->image->base.version >= 7 &&
3282        dri2_dpy->image->createImageFromFds != NULL)
3283       flags |= WAYLAND_DRM_PRIME;
3284
3285    dri2_dpy->wl_server_drm =
3286            wayland_drm_init(wl_dpy, device_name,
3287                             &wl_drm_callbacks, disp, flags);
3288
3289    free(device_name);
3290
3291    if (!dri2_dpy->wl_server_drm)
3292            return EGL_FALSE;
3293
3294 #ifdef HAVE_DRM_PLATFORM
3295    /* We have to share the wl_drm instance with gbm, so gbm can convert
3296     * wl_buffers to gbm bos. */
3297    if (dri2_dpy->gbm_dri)
3298       dri2_dpy->gbm_dri->wl_drm = dri2_dpy->wl_server_drm;
3299 #endif
3300
3301    return EGL_TRUE;
3302 }
3303
3304 static EGLBoolean
3305 dri2_unbind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3306 {
3307    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3308
3309    if (!dri2_dpy->wl_server_drm)
3310            return EGL_FALSE;
3311
3312    wayland_drm_uninit(dri2_dpy->wl_server_drm);
3313    dri2_dpy->wl_server_drm = NULL;
3314
3315    return EGL_TRUE;
3316 }
3317
3318 static EGLBoolean
3319 dri2_query_wayland_buffer_wl(_EGLDisplay *disp, struct wl_resource *buffer_resource,
3320                              EGLint attribute, EGLint *value)
3321 {
3322    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3323    struct wl_drm_buffer *buffer;
3324    const struct wl_drm_components_descriptor *format;
3325
3326    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm, buffer_resource);
3327    if (!buffer)
3328       return EGL_FALSE;
3329
3330    format = buffer->driver_format;
3331    switch (attribute) {
3332    case EGL_TEXTURE_FORMAT:
3333       *value = format->components;
3334       return EGL_TRUE;
3335    case EGL_WIDTH:
3336       *value = buffer->width;
3337       return EGL_TRUE;
3338    case EGL_HEIGHT:
3339       *value = buffer->height;
3340       return EGL_TRUE;
3341    }
3342
3343    return EGL_FALSE;
3344 }
3345 #endif
3346
3347 static void
3348 dri2_egl_ref_sync(struct dri2_egl_sync *sync)
3349 {
3350    p_atomic_inc(&sync->refcount);
3351 }
3352
3353 static void
3354 dri2_egl_unref_sync(struct dri2_egl_display *dri2_dpy,
3355                     struct dri2_egl_sync *dri2_sync)
3356 {
3357    if (p_atomic_dec_zero(&dri2_sync->refcount)) {
3358       switch (dri2_sync->base.Type) {
3359       case EGL_SYNC_REUSABLE_KHR:
3360          cnd_destroy(&dri2_sync->cond);
3361          break;
3362       case EGL_SYNC_NATIVE_FENCE_ANDROID:
3363          if (dri2_sync->base.SyncFd != EGL_NO_NATIVE_FENCE_FD_ANDROID)
3364             close(dri2_sync->base.SyncFd);
3365          break;
3366       default:
3367          break;
3368       }
3369
3370       if (dri2_sync->fence)
3371          dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, dri2_sync->fence);
3372
3373       free(dri2_sync);
3374    }
3375 }
3376
3377 static _EGLSync *
3378 dri2_create_sync(_EGLDisplay *disp, EGLenum type, const EGLAttrib *attrib_list)
3379 {
3380    _EGLContext *ctx = _eglGetCurrentContext();
3381    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3382    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3383    struct dri2_egl_sync *dri2_sync;
3384    EGLint ret;
3385    pthread_condattr_t attr;
3386
3387    dri2_sync = calloc(1, sizeof(struct dri2_egl_sync));
3388    if (!dri2_sync) {
3389       _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3390       return NULL;
3391    }
3392
3393    if (!_eglInitSync(&dri2_sync->base, disp, type, attrib_list)) {
3394       free(dri2_sync);
3395       return NULL;
3396    }
3397
3398    switch (type) {
3399    case EGL_SYNC_FENCE_KHR:
3400       dri2_sync->fence = dri2_dpy->fence->create_fence(dri2_ctx->dri_context);
3401       if (!dri2_sync->fence) {
3402          /* Why did it fail? DRI doesn't return an error code, so we emit
3403           * a generic EGL error that doesn't communicate user error.
3404           */
3405          _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3406          free(dri2_sync);
3407          return NULL;
3408       }
3409       break;
3410
3411    case EGL_SYNC_CL_EVENT_KHR:
3412       dri2_sync->fence = dri2_dpy->fence->get_fence_from_cl_event(
3413                                  dri2_dpy->dri_screen,
3414                                  dri2_sync->base.CLEvent);
3415       /* this can only happen if the cl_event passed in is invalid. */
3416       if (!dri2_sync->fence) {
3417          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3418          free(dri2_sync);
3419          return NULL;
3420       }
3421
3422       /* the initial status must be "signaled" if the cl_event is signaled */
3423       if (dri2_dpy->fence->client_wait_sync(dri2_ctx->dri_context,
3424                                             dri2_sync->fence, 0, 0))
3425          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3426       break;
3427
3428    case EGL_SYNC_REUSABLE_KHR:
3429       /* intialize attr */
3430       ret = pthread_condattr_init(&attr);
3431
3432       if (ret) {
3433          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3434          free(dri2_sync);
3435          return NULL;
3436       }
3437
3438       /* change clock attribute to CLOCK_MONOTONIC */
3439       ret = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
3440
3441       if (ret) {
3442          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3443          free(dri2_sync);
3444          return NULL;
3445       }
3446
3447       ret = pthread_cond_init(&dri2_sync->cond, &attr);
3448
3449       if (ret) {
3450          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3451          free(dri2_sync);
3452          return NULL;
3453       }
3454
3455       /* initial status of reusable sync must be "unsignaled" */
3456       dri2_sync->base.SyncStatus = EGL_UNSIGNALED_KHR;
3457       break;
3458
3459    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3460       if (dri2_dpy->fence->create_fence_fd) {
3461          dri2_sync->fence = dri2_dpy->fence->create_fence_fd(
3462                                     dri2_ctx->dri_context,
3463                                     dri2_sync->base.SyncFd);
3464       }
3465       if (!dri2_sync->fence) {
3466          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3467          free(dri2_sync);
3468          return NULL;
3469       }
3470       break;
3471    }
3472
3473    p_atomic_set(&dri2_sync->refcount, 1);
3474    return &dri2_sync->base;
3475 }
3476
3477 static EGLBoolean
3478 dri2_destroy_sync(_EGLDisplay *disp, _EGLSync *sync)
3479 {
3480    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3481    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3482    EGLint ret = EGL_TRUE;
3483    EGLint err;
3484
3485    /* if type of sync is EGL_SYNC_REUSABLE_KHR and it is not signaled yet,
3486     * then unlock all threads possibly blocked by the reusable sync before
3487     * destroying it.
3488     */
3489    if (dri2_sync->base.Type == EGL_SYNC_REUSABLE_KHR &&
3490        dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3491       dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3492       /* unblock all threads currently blocked by sync */
3493       err = cnd_broadcast(&dri2_sync->cond);
3494
3495       if (err) {
3496          _eglError(EGL_BAD_ACCESS, "eglDestroySyncKHR");
3497          ret = EGL_FALSE;
3498       }
3499    }
3500
3501    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3502
3503    return ret;
3504 }
3505
3506 static EGLint
3507 dri2_dup_native_fence_fd(_EGLDisplay *disp, _EGLSync *sync)
3508 {
3509    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3510    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3511
3512    assert(sync->Type == EGL_SYNC_NATIVE_FENCE_ANDROID);
3513
3514    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3515       /* try to retrieve the actual native fence fd.. if rendering is
3516        * not flushed this will just return -1, aka NO_NATIVE_FENCE_FD:
3517        */
3518       sync->SyncFd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
3519                                                    dri2_sync->fence);
3520    }
3521
3522    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3523       /* if native fence fd still not created, return an error: */
3524       _eglError(EGL_BAD_PARAMETER, "eglDupNativeFenceFDANDROID");
3525       return EGL_NO_NATIVE_FENCE_FD_ANDROID;
3526    }
3527
3528    assert(sync_valid_fd(sync->SyncFd));
3529
3530    return os_dupfd_cloexec(sync->SyncFd);
3531 }
3532
3533 static void
3534 dri2_set_blob_cache_funcs(_EGLDisplay *disp,
3535                           EGLSetBlobFuncANDROID set,
3536                           EGLGetBlobFuncANDROID get)
3537 {
3538    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3539    dri2_dpy->blob->set_cache_funcs(dri2_dpy->dri_screen,
3540                                    disp->BlobCacheSet,
3541                                    disp->BlobCacheGet);
3542 }
3543
3544 static EGLint
3545 dri2_client_wait_sync(_EGLDisplay *disp, _EGLSync *sync,
3546                       EGLint flags, EGLTime timeout)
3547 {
3548    _EGLContext *ctx = _eglGetCurrentContext();
3549    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3550    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3551    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3552    unsigned wait_flags = 0;
3553
3554    EGLint ret = EGL_CONDITION_SATISFIED_KHR;
3555
3556    /* The EGL_KHR_fence_sync spec states:
3557     *
3558     *    "If no context is current for the bound API,
3559     *     the EGL_SYNC_FLUSH_COMMANDS_BIT_KHR bit is ignored.
3560     */
3561    if (dri2_ctx && flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)
3562       wait_flags |= __DRI2_FENCE_FLAG_FLUSH_COMMANDS;
3563
3564    /* the sync object should take a reference while waiting */
3565    dri2_egl_ref_sync(dri2_sync);
3566
3567    switch (sync->Type) {
3568    case EGL_SYNC_FENCE_KHR:
3569    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3570    case EGL_SYNC_CL_EVENT_KHR:
3571       if (dri2_dpy->fence->client_wait_sync(dri2_ctx ? dri2_ctx->dri_context : NULL,
3572                                          dri2_sync->fence, wait_flags,
3573                                          timeout))
3574          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3575       else
3576          ret = EGL_TIMEOUT_EXPIRED_KHR;
3577       break;
3578
3579    case EGL_SYNC_REUSABLE_KHR:
3580       if (dri2_ctx && dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR &&
3581           (flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)) {
3582          /* flush context if EGL_SYNC_FLUSH_COMMANDS_BIT_KHR is set */
3583          dri2_gl_flush();
3584       }
3585
3586       /* if timeout is EGL_FOREVER_KHR, it should wait without any timeout.*/
3587       if (timeout == EGL_FOREVER_KHR) {
3588          mtx_lock(&dri2_sync->mutex);
3589          cnd_wait(&dri2_sync->cond, &dri2_sync->mutex);
3590          mtx_unlock(&dri2_sync->mutex);
3591       } else {
3592          /* if reusable sync has not been yet signaled */
3593          if (dri2_sync->base.SyncStatus != EGL_SIGNALED_KHR) {
3594             /* timespecs for cnd_timedwait */
3595             struct timespec current;
3596             struct timespec expire;
3597
3598             /* We override the clock to monotonic when creating the condition
3599              * variable. */
3600             clock_gettime(CLOCK_MONOTONIC, &current);
3601
3602             /* calculating when to expire */
3603             expire.tv_nsec = timeout % 1000000000L;
3604             expire.tv_sec = timeout / 1000000000L;
3605
3606             expire.tv_nsec += current.tv_nsec;
3607             expire.tv_sec += current.tv_sec;
3608
3609             /* expire.nsec now is a number between 0 and 1999999998 */
3610             if (expire.tv_nsec > 999999999L) {
3611                expire.tv_sec++;
3612                expire.tv_nsec -= 1000000000L;
3613             }
3614
3615             mtx_lock(&dri2_sync->mutex);
3616             ret = cnd_timedwait(&dri2_sync->cond, &dri2_sync->mutex, &expire);
3617             mtx_unlock(&dri2_sync->mutex);
3618
3619             if (ret == thrd_timedout) {
3620                if (dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3621                   ret = EGL_TIMEOUT_EXPIRED_KHR;
3622                } else {
3623                   _eglError(EGL_BAD_ACCESS, "eglClientWaitSyncKHR");
3624                   ret = EGL_FALSE;
3625                }
3626             }
3627          }
3628       }
3629       break;
3630   }
3631   dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3632
3633   return ret;
3634 }
3635
3636 static EGLBoolean
3637 dri2_signal_sync(_EGLDisplay *disp, _EGLSync *sync, EGLenum mode)
3638 {
3639    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3640    EGLint ret;
3641
3642    if (sync->Type != EGL_SYNC_REUSABLE_KHR)
3643       return _eglError(EGL_BAD_MATCH, "eglSignalSyncKHR");
3644
3645    if (mode != EGL_SIGNALED_KHR && mode != EGL_UNSIGNALED_KHR)
3646       return _eglError(EGL_BAD_ATTRIBUTE, "eglSignalSyncKHR");
3647
3648    dri2_sync->base.SyncStatus = mode;
3649
3650    if (mode == EGL_SIGNALED_KHR) {
3651       ret = cnd_broadcast(&dri2_sync->cond);
3652
3653       /* fail to broadcast */
3654       if (ret)
3655          return _eglError(EGL_BAD_ACCESS, "eglSignalSyncKHR");
3656    }
3657
3658    return EGL_TRUE;
3659 }
3660
3661 static EGLint
3662 dri2_server_wait_sync(_EGLDisplay *disp, _EGLSync *sync)
3663 {
3664    _EGLContext *ctx = _eglGetCurrentContext();
3665    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3666    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3667    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3668
3669    dri2_dpy->fence->server_wait_sync(dri2_ctx->dri_context,
3670                                      dri2_sync->fence, 0);
3671    return EGL_TRUE;
3672 }
3673
3674 static int
3675 dri2_interop_query_device_info(_EGLDisplay *disp, _EGLContext *ctx,
3676                                struct mesa_glinterop_device_info *out)
3677 {
3678    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3679    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3680
3681    if (!dri2_dpy->interop)
3682       return MESA_GLINTEROP_UNSUPPORTED;
3683
3684    return dri2_dpy->interop->query_device_info(dri2_ctx->dri_context, out);
3685 }
3686
3687 static int
3688 dri2_interop_export_object(_EGLDisplay *disp, _EGLContext *ctx,
3689                            struct mesa_glinterop_export_in *in,
3690                            struct mesa_glinterop_export_out *out)
3691 {
3692    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3693    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3694
3695    if (!dri2_dpy->interop)
3696       return MESA_GLINTEROP_UNSUPPORTED;
3697
3698    return dri2_dpy->interop->export_object(dri2_ctx->dri_context, in, out);
3699 }
3700
3701 const _EGLDriver _eglDriver = {
3702    .Initialize = dri2_initialize,
3703    .Terminate = dri2_terminate,
3704    .CreateContext = dri2_create_context,
3705    .DestroyContext = dri2_destroy_context,
3706    .MakeCurrent = dri2_make_current,
3707    .CreateWindowSurface = dri2_create_window_surface,
3708    .CreatePixmapSurface = dri2_create_pixmap_surface,
3709    .CreatePbufferSurface = dri2_create_pbuffer_surface,
3710    .DestroySurface = dri2_destroy_surface,
3711    .GetProcAddress = dri2_get_proc_address,
3712    .WaitClient = dri2_wait_client,
3713    .WaitNative = dri2_wait_native,
3714    .BindTexImage = dri2_bind_tex_image,
3715    .ReleaseTexImage = dri2_release_tex_image,
3716    .SwapInterval = dri2_swap_interval,
3717    .SwapBuffers = dri2_swap_buffers,
3718    .SwapBuffersWithDamageEXT = dri2_swap_buffers_with_damage,
3719    .SwapBuffersRegionNOK = dri2_swap_buffers_region,
3720    .SetDamageRegion = dri2_set_damage_region,
3721    .PostSubBufferNV = dri2_post_sub_buffer,
3722    .CopyBuffers = dri2_copy_buffers,
3723    .QueryBufferAge = dri2_query_buffer_age,
3724    .CreateImageKHR = dri2_create_image,
3725    .DestroyImageKHR = dri2_destroy_image_khr,
3726    .CreateWaylandBufferFromImageWL = dri2_create_wayland_buffer_from_image,
3727    .QuerySurface = dri2_query_surface,
3728    .QueryDriverName = dri2_query_driver_name,
3729    .QueryDriverConfig = dri2_query_driver_config,
3730 #ifdef HAVE_LIBDRM
3731    .CreateDRMImageMESA = dri2_create_drm_image_mesa,
3732    .ExportDRMImageMESA = dri2_export_drm_image_mesa,
3733    .ExportDMABUFImageQueryMESA = dri2_export_dma_buf_image_query_mesa,
3734    .ExportDMABUFImageMESA = dri2_export_dma_buf_image_mesa,
3735    .QueryDmaBufFormatsEXT = dri2_query_dma_buf_formats,
3736    .QueryDmaBufModifiersEXT = dri2_query_dma_buf_modifiers,
3737 #endif
3738 #ifdef HAVE_WAYLAND_PLATFORM
3739    .BindWaylandDisplayWL = dri2_bind_wayland_display_wl,
3740    .UnbindWaylandDisplayWL = dri2_unbind_wayland_display_wl,
3741    .QueryWaylandBufferWL = dri2_query_wayland_buffer_wl,
3742 #endif
3743    .GetSyncValuesCHROMIUM = dri2_get_sync_values_chromium,
3744    .CreateSyncKHR = dri2_create_sync,
3745    .ClientWaitSyncKHR = dri2_client_wait_sync,
3746    .SignalSyncKHR = dri2_signal_sync,
3747    .WaitSyncKHR = dri2_server_wait_sync,
3748    .DestroySyncKHR = dri2_destroy_sync,
3749    .GLInteropQueryDeviceInfo = dri2_interop_query_device_info,
3750    .GLInteropExportObject = dri2_interop_export_object,
3751    .DupNativeFenceFDANDROID = dri2_dup_native_fence_fd,
3752    .SetBlobCacheFuncsANDROID = dri2_set_blob_cache_funcs,
3753 };