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