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