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