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