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