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