Revert "egl: Factor some common terminate cleanup up to common code"
[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_CONTENT);
1030 }
1031
1032 void
1033 dri2_setup_swap_interval(_EGLDisplay *disp, int max_swap_interval)
1034 {
1035    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1036    GLint vblank_mode = DRI_CONF_VBLANK_DEF_INTERVAL_1;
1037
1038    /* Allow driconf to override applications.*/
1039    if (dri2_dpy->config)
1040       dri2_dpy->config->configQueryi(dri2_dpy->dri_screen,
1041                                      "vblank_mode", &vblank_mode);
1042    switch (vblank_mode) {
1043    case DRI_CONF_VBLANK_NEVER:
1044       dri2_dpy->min_swap_interval = 0;
1045       dri2_dpy->max_swap_interval = 0;
1046       dri2_dpy->default_swap_interval = 0;
1047       break;
1048    case DRI_CONF_VBLANK_ALWAYS_SYNC:
1049       dri2_dpy->min_swap_interval = 1;
1050       dri2_dpy->max_swap_interval = max_swap_interval;
1051       dri2_dpy->default_swap_interval = 1;
1052       break;
1053    case DRI_CONF_VBLANK_DEF_INTERVAL_0:
1054       dri2_dpy->min_swap_interval = 0;
1055       dri2_dpy->max_swap_interval = max_swap_interval;
1056       dri2_dpy->default_swap_interval = 0;
1057       break;
1058    default:
1059    case DRI_CONF_VBLANK_DEF_INTERVAL_1:
1060       dri2_dpy->min_swap_interval = 0;
1061       dri2_dpy->max_swap_interval = max_swap_interval;
1062       dri2_dpy->default_swap_interval = 1;
1063       break;
1064    }
1065 }
1066
1067 /* All platforms but DRM call this function to create the screen and populate
1068  * the driver_configs. DRM inherits that information from its display - GBM.
1069  */
1070 EGLBoolean
1071 dri2_create_screen(_EGLDisplay *disp)
1072 {
1073    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1074
1075    if (dri2_dpy->image_driver) {
1076       dri2_dpy->dri_screen =
1077          dri2_dpy->image_driver->createNewScreen2(0, dri2_dpy->fd,
1078                                                   dri2_dpy->loader_extensions,
1079                                                   dri2_dpy->driver_extensions,
1080                                                   &dri2_dpy->driver_configs,
1081                                                   disp);
1082    } else if (dri2_dpy->dri2) {
1083       if (dri2_dpy->dri2->base.version >= 4) {
1084          dri2_dpy->dri_screen =
1085             dri2_dpy->dri2->createNewScreen2(0, dri2_dpy->fd,
1086                                              dri2_dpy->loader_extensions,
1087                                              dri2_dpy->driver_extensions,
1088                                              &dri2_dpy->driver_configs, disp);
1089       } else {
1090          dri2_dpy->dri_screen =
1091             dri2_dpy->dri2->createNewScreen(0, dri2_dpy->fd,
1092                                             dri2_dpy->loader_extensions,
1093                                             &dri2_dpy->driver_configs, disp);
1094       }
1095    } else {
1096       assert(dri2_dpy->swrast);
1097       if (dri2_dpy->swrast->base.version >= 4) {
1098          dri2_dpy->dri_screen =
1099             dri2_dpy->swrast->createNewScreen2(0, dri2_dpy->loader_extensions,
1100                                                dri2_dpy->driver_extensions,
1101                                                &dri2_dpy->driver_configs, disp);
1102       } else {
1103          dri2_dpy->dri_screen =
1104             dri2_dpy->swrast->createNewScreen(0, dri2_dpy->loader_extensions,
1105                                               &dri2_dpy->driver_configs, disp);
1106       }
1107    }
1108
1109    if (dri2_dpy->dri_screen == NULL) {
1110       _eglLog(_EGL_WARNING, "egl: failed to create dri2 screen");
1111       return EGL_FALSE;
1112    }
1113
1114    dri2_dpy->own_dri_screen = true;
1115    return EGL_TRUE;
1116 }
1117
1118 EGLBoolean
1119 dri2_setup_extensions(_EGLDisplay *disp)
1120 {
1121    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1122    const struct dri2_extension_match *mandatory_core_extensions;
1123    const __DRIextension **extensions;
1124
1125    extensions = dri2_dpy->core->getExtensions(dri2_dpy->dri_screen);
1126
1127    if (dri2_dpy->image_driver || dri2_dpy->dri2)
1128       mandatory_core_extensions = dri2_core_extensions;
1129    else
1130       mandatory_core_extensions = swrast_core_extensions;
1131
1132    if (!dri2_bind_extensions(dri2_dpy, mandatory_core_extensions, extensions, false))
1133       return EGL_FALSE;
1134
1135 #ifdef HAVE_DRI3_MODIFIERS
1136    dri2_dpy->multibuffers_available =
1137       (dri2_dpy->dri3_major_version > 1 || (dri2_dpy->dri3_major_version == 1 &&
1138                                             dri2_dpy->dri3_minor_version >= 2)) &&
1139       (dri2_dpy->present_major_version > 1 || (dri2_dpy->present_major_version == 1 &&
1140                                                dri2_dpy->present_minor_version >= 2)) &&
1141       (dri2_dpy->image && dri2_dpy->image->base.version >= 15);
1142 #endif
1143
1144    dri2_bind_extensions(dri2_dpy, optional_core_extensions, extensions, true);
1145    return EGL_TRUE;
1146 }
1147
1148 /**
1149  * Called via eglInitialize(), drv->Initialize().
1150  *
1151  * This must be guaranteed to be called exactly once, even if eglInitialize is
1152  * called many times (without a eglTerminate in between).
1153  */
1154 static EGLBoolean
1155 dri2_initialize(_EGLDisplay *disp)
1156 {
1157    EGLBoolean ret = EGL_FALSE;
1158    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1159
1160    /* In the case where the application calls eglMakeCurrent(context1),
1161     * eglTerminate, then eglInitialize again (without a call to eglReleaseThread
1162     * or eglMakeCurrent(NULL) before that), dri2_dpy structure is still
1163     * initialized, as we need it to be able to free context1 correctly.
1164     *
1165     * It would probably be safest to forcibly release the display with
1166     * dri2_display_release, to make sure the display is reinitialized correctly.
1167     * However, the EGL spec states that we need to keep a reference to the
1168     * current context (so we cannot call dri2_make_current(NULL)), and therefore
1169     * we would leak context1 as we would be missing the old display connection
1170     * to free it up correctly.
1171     */
1172    if (dri2_dpy) {
1173       p_atomic_inc(&dri2_dpy->ref_count);
1174       return EGL_TRUE;
1175    }
1176
1177    loader_set_logger(_eglLog);
1178
1179    switch (disp->Platform) {
1180    case _EGL_PLATFORM_SURFACELESS:
1181       ret = dri2_initialize_surfaceless(disp);
1182       break;
1183    case _EGL_PLATFORM_DEVICE:
1184       ret = dri2_initialize_device(disp);
1185       break;
1186    case _EGL_PLATFORM_X11:
1187    case _EGL_PLATFORM_XCB:
1188       ret = dri2_initialize_x11(disp);
1189       break;
1190    case _EGL_PLATFORM_DRM:
1191       ret = dri2_initialize_drm(disp);
1192       break;
1193    case _EGL_PLATFORM_WAYLAND:
1194       ret = dri2_initialize_wayland(disp);
1195       break;
1196    case _EGL_PLATFORM_ANDROID:
1197       ret = dri2_initialize_android(disp);
1198       break;
1199    default:
1200       unreachable("Callers ensure we cannot get here.");
1201       return EGL_FALSE;
1202    }
1203
1204    if (!ret)
1205       return EGL_FALSE;
1206
1207    dri2_dpy = dri2_egl_display(disp);
1208    p_atomic_inc(&dri2_dpy->ref_count);
1209
1210    mtx_init(&dri2_dpy->lock, mtx_plain);
1211
1212    return EGL_TRUE;
1213 }
1214
1215 /**
1216  * Decrement display reference count, and free up display if necessary.
1217  */
1218 static void
1219 dri2_display_release(_EGLDisplay *disp)
1220 {
1221    struct dri2_egl_display *dri2_dpy;
1222
1223    if (!disp)
1224       return;
1225
1226    dri2_dpy = dri2_egl_display(disp);
1227
1228    assert(dri2_dpy->ref_count > 0);
1229
1230    if (!p_atomic_dec_zero(&dri2_dpy->ref_count))
1231       return;
1232
1233    _eglCleanupDisplay(disp);
1234    dri2_display_destroy(disp);
1235 }
1236
1237 void
1238 dri2_display_destroy(_EGLDisplay *disp)
1239 {
1240    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1241
1242    if (dri2_dpy->own_dri_screen) {
1243       if (dri2_dpy->vtbl && dri2_dpy->vtbl->close_screen_notify)
1244          dri2_dpy->vtbl->close_screen_notify(disp);
1245       dri2_dpy->core->destroyScreen(dri2_dpy->dri_screen);
1246    }
1247    if (dri2_dpy->fd >= 0)
1248       close(dri2_dpy->fd);
1249
1250    /* Don't dlclose the driver when building with the address sanitizer, so you
1251     * get good symbols from the leak reports.
1252     */
1253 #if !BUILT_WITH_ASAN || defined(NDEBUG)
1254    if (dri2_dpy->driver)
1255       dlclose(dri2_dpy->driver);
1256 #endif
1257
1258    free(dri2_dpy->driver_name);
1259
1260 #ifdef HAVE_WAYLAND_PLATFORM
1261    free(dri2_dpy->device_name);
1262 #endif
1263
1264    switch (disp->Platform) {
1265    case _EGL_PLATFORM_X11:
1266       dri2_teardown_x11(dri2_dpy);
1267       break;
1268    case _EGL_PLATFORM_DRM:
1269       dri2_teardown_drm(dri2_dpy);
1270       break;
1271    case _EGL_PLATFORM_WAYLAND:
1272       dri2_teardown_wayland(dri2_dpy);
1273       break;
1274    default:
1275       /* TODO: add teardown for other platforms */
1276       break;
1277    }
1278
1279    /* The drm platform does not create the screen/driver_configs but reuses
1280     * the ones from the gbm device. As such the gbm itself is responsible
1281     * for the cleanup.
1282     */
1283    if (disp->Platform != _EGL_PLATFORM_DRM && dri2_dpy->driver_configs) {
1284       for (unsigned i = 0; dri2_dpy->driver_configs[i]; i++)
1285          free((__DRIconfig *) dri2_dpy->driver_configs[i]);
1286       free(dri2_dpy->driver_configs);
1287    }
1288    free(dri2_dpy);
1289    disp->DriverData = NULL;
1290 }
1291
1292 __DRIbuffer *
1293 dri2_egl_surface_alloc_local_buffer(struct dri2_egl_surface *dri2_surf,
1294                                     unsigned int att, unsigned int format)
1295 {
1296    struct dri2_egl_display *dri2_dpy =
1297       dri2_egl_display(dri2_surf->base.Resource.Display);
1298
1299    if (att >= ARRAY_SIZE(dri2_surf->local_buffers))
1300       return NULL;
1301
1302    if (!dri2_surf->local_buffers[att]) {
1303       dri2_surf->local_buffers[att] =
1304          dri2_dpy->dri2->allocateBuffer(dri2_dpy->dri_screen, att, format,
1305                                         dri2_surf->base.Width, dri2_surf->base.Height);
1306    }
1307
1308    return dri2_surf->local_buffers[att];
1309 }
1310
1311 void
1312 dri2_egl_surface_free_local_buffers(struct dri2_egl_surface *dri2_surf)
1313 {
1314    struct dri2_egl_display *dri2_dpy =
1315       dri2_egl_display(dri2_surf->base.Resource.Display);
1316
1317    for (int i = 0; i < ARRAY_SIZE(dri2_surf->local_buffers); i++) {
1318       if (dri2_surf->local_buffers[i]) {
1319          dri2_dpy->dri2->releaseBuffer(dri2_dpy->dri_screen,
1320                                        dri2_surf->local_buffers[i]);
1321          dri2_surf->local_buffers[i] = NULL;
1322       }
1323    }
1324 }
1325
1326 /**
1327  * Called via eglTerminate(), drv->Terminate().
1328  *
1329  * This must be guaranteed to be called exactly once, even if eglTerminate is
1330  * called many times (without a eglInitialize in between).
1331  */
1332 static EGLBoolean
1333 dri2_terminate(_EGLDisplay *disp)
1334 {
1335    /* Release all non-current Context/Surfaces. */
1336    _eglReleaseDisplayResources(disp);
1337
1338    dri2_display_release(disp);
1339
1340    return EGL_TRUE;
1341 }
1342
1343 /**
1344  * Set the error code after a call to
1345  * dri2_egl_display::dri2::createContextAttribs.
1346  */
1347 static void
1348 dri2_create_context_attribs_error(int dri_error)
1349 {
1350    EGLint egl_error;
1351
1352    switch (dri_error) {
1353    case __DRI_CTX_ERROR_SUCCESS:
1354       return;
1355
1356    case __DRI_CTX_ERROR_NO_MEMORY:
1357       egl_error = EGL_BAD_ALLOC;
1358       break;
1359
1360   /* From the EGL_KHR_create_context spec, section "Errors":
1361    *
1362    *   * If <config> does not support a client API context compatible
1363    *     with the requested API major and minor version, [...] context flags,
1364    *     and context reset notification behavior (for client API types where
1365    *     these attributes are supported), then an EGL_BAD_MATCH error is
1366    *     generated.
1367    *
1368    *   * If an OpenGL ES context is requested and the values for
1369    *     attributes EGL_CONTEXT_MAJOR_VERSION_KHR and
1370    *     EGL_CONTEXT_MINOR_VERSION_KHR specify an OpenGL ES version that
1371    *     is not defined, than an EGL_BAD_MATCH error is generated.
1372    *
1373    *   * If an OpenGL context is requested, the requested version is
1374    *     greater than 3.2, and the value for attribute
1375    *     EGL_CONTEXT_OPENGL_PROFILE_MASK_KHR has no bits set; has any
1376    *     bits set other than EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR and
1377    *     EGL_CONTEXT_OPENGL_COMPATIBILITY_PROFILE_BIT_KHR; has more than
1378    *     one of these bits set; or if the implementation does not support
1379    *     the requested profile, then an EGL_BAD_MATCH error is generated.
1380    */
1381    case __DRI_CTX_ERROR_BAD_API:
1382    case __DRI_CTX_ERROR_BAD_VERSION:
1383    case __DRI_CTX_ERROR_BAD_FLAG:
1384       egl_error = EGL_BAD_MATCH;
1385       break;
1386
1387   /* From the EGL_KHR_create_context spec, section "Errors":
1388    *
1389    *   * If an attribute name or attribute value in <attrib_list> is not
1390    *     recognized (including unrecognized bits in bitmask attributes),
1391    *     then an EGL_BAD_ATTRIBUTE error is generated."
1392    */
1393    case __DRI_CTX_ERROR_UNKNOWN_ATTRIBUTE:
1394    case __DRI_CTX_ERROR_UNKNOWN_FLAG:
1395       egl_error = EGL_BAD_ATTRIBUTE;
1396       break;
1397
1398    default:
1399       assert(!"unknown dri_error code");
1400       egl_error = EGL_BAD_MATCH;
1401       break;
1402    }
1403
1404    _eglError(egl_error, "dri2_create_context");
1405 }
1406
1407 static bool
1408 dri2_fill_context_attribs(struct dri2_egl_context *dri2_ctx,
1409                           struct dri2_egl_display *dri2_dpy,
1410                           uint32_t *ctx_attribs,
1411                           unsigned *num_attribs)
1412 {
1413    int pos = 0;
1414
1415    assert(*num_attribs >= NUM_ATTRIBS);
1416
1417    ctx_attribs[pos++] = __DRI_CTX_ATTRIB_MAJOR_VERSION;
1418    ctx_attribs[pos++] = dri2_ctx->base.ClientMajorVersion;
1419    ctx_attribs[pos++] = __DRI_CTX_ATTRIB_MINOR_VERSION;
1420    ctx_attribs[pos++] = dri2_ctx->base.ClientMinorVersion;
1421
1422    if (dri2_ctx->base.Flags != 0) {
1423       /* If the implementation doesn't support the __DRI2_ROBUSTNESS
1424        * extension, don't even try to send it the robust-access flag.
1425        * It may explode.  Instead, generate the required EGL error here.
1426        */
1427       if ((dri2_ctx->base.Flags & EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR) != 0
1428             && !dri2_dpy->robustness) {
1429          _eglError(EGL_BAD_MATCH, "eglCreateContext");
1430          return false;
1431       }
1432
1433       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_FLAGS;
1434       ctx_attribs[pos++] = dri2_ctx->base.Flags;
1435    }
1436
1437    if (dri2_ctx->base.ResetNotificationStrategy != EGL_NO_RESET_NOTIFICATION_KHR) {
1438       /* If the implementation doesn't support the __DRI2_ROBUSTNESS
1439        * extension, don't even try to send it a reset strategy.  It may
1440        * explode.  Instead, generate the required EGL error here.
1441        */
1442       if (!dri2_dpy->robustness) {
1443          _eglError(EGL_BAD_CONFIG, "eglCreateContext");
1444          return false;
1445       }
1446
1447       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_RESET_STRATEGY;
1448       ctx_attribs[pos++] = __DRI_CTX_RESET_LOSE_CONTEXT;
1449    }
1450
1451    if (dri2_ctx->base.ContextPriority != EGL_CONTEXT_PRIORITY_MEDIUM_IMG) {
1452       unsigned val;
1453
1454       switch (dri2_ctx->base.ContextPriority) {
1455       case EGL_CONTEXT_PRIORITY_HIGH_IMG:
1456          val = __DRI_CTX_PRIORITY_HIGH;
1457          break;
1458       case EGL_CONTEXT_PRIORITY_MEDIUM_IMG:
1459          val = __DRI_CTX_PRIORITY_MEDIUM;
1460          break;
1461       case EGL_CONTEXT_PRIORITY_LOW_IMG:
1462          val = __DRI_CTX_PRIORITY_LOW;
1463          break;
1464       default:
1465          _eglError(EGL_BAD_CONFIG, "eglCreateContext");
1466          return false;
1467       }
1468
1469       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_PRIORITY;
1470       ctx_attribs[pos++] = val;
1471    }
1472
1473    if (dri2_ctx->base.ReleaseBehavior == EGL_CONTEXT_RELEASE_BEHAVIOR_NONE_KHR) {
1474       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_RELEASE_BEHAVIOR;
1475       ctx_attribs[pos++] = __DRI_CTX_RELEASE_BEHAVIOR_NONE;
1476    }
1477
1478    if (dri2_ctx->base.NoError) {
1479       ctx_attribs[pos++] = __DRI_CTX_ATTRIB_NO_ERROR;
1480       ctx_attribs[pos++] = true;
1481    }
1482
1483    *num_attribs = pos;
1484
1485    return true;
1486 }
1487
1488 /**
1489  * Called via eglCreateContext(), drv->CreateContext().
1490  */
1491 static _EGLContext *
1492 dri2_create_context(_EGLDisplay *disp, _EGLConfig *conf,
1493                     _EGLContext *share_list, const EGLint *attrib_list)
1494 {
1495    struct dri2_egl_context *dri2_ctx;
1496    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1497    struct dri2_egl_context *dri2_ctx_shared = dri2_egl_context(share_list);
1498    __DRIcontext *shared =
1499       dri2_ctx_shared ? dri2_ctx_shared->dri_context : NULL;
1500    struct dri2_egl_config *dri2_config = dri2_egl_config(conf);
1501    const __DRIconfig *dri_config;
1502    int api;
1503    unsigned error;
1504    unsigned num_attribs = NUM_ATTRIBS;
1505    uint32_t ctx_attribs[NUM_ATTRIBS];
1506
1507    dri2_ctx = malloc(sizeof *dri2_ctx);
1508    if (!dri2_ctx) {
1509       dri2_egl_error_unlock(dri2_dpy, EGL_BAD_ALLOC, "eglCreateContext");
1510       return NULL;
1511    }
1512
1513    if (!_eglInitContext(&dri2_ctx->base, disp, conf, attrib_list))
1514       goto cleanup;
1515
1516    /* The EGL_EXT_create_context_robustness spec says:
1517     *
1518     *    "Add to the eglCreateContext context creation errors: [...]
1519     *
1520     *     * If the reset notification behavior of <share_context> and the
1521     *       newly created context are different then an EGL_BAD_MATCH error is
1522     *       generated."
1523     */
1524    if (share_list && share_list->ResetNotificationStrategy !=
1525                      dri2_ctx->base.ResetNotificationStrategy) {
1526       _eglError(EGL_BAD_MATCH, "eglCreateContext");
1527       goto cleanup;
1528    }
1529
1530    /* The EGL_KHR_create_context_no_error spec says:
1531     *
1532     *    "BAD_MATCH is generated if the value of EGL_CONTEXT_OPENGL_NO_ERROR_KHR
1533     *    used to create <share_context> does not match the value of
1534     *    EGL_CONTEXT_OPENGL_NO_ERROR_KHR for the context being created."
1535     */
1536    if (share_list && share_list->NoError != dri2_ctx->base.NoError) {
1537       _eglError(EGL_BAD_MATCH, "eglCreateContext");
1538       goto cleanup;
1539    }
1540
1541    switch (dri2_ctx->base.ClientAPI) {
1542    case EGL_OPENGL_ES_API:
1543       switch (dri2_ctx->base.ClientMajorVersion) {
1544       case 1:
1545          api = __DRI_API_GLES;
1546          break;
1547       case 2:
1548          api = __DRI_API_GLES2;
1549          break;
1550       case 3:
1551          api = __DRI_API_GLES3;
1552          break;
1553       default:
1554          _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
1555          goto cleanup;
1556       }
1557       break;
1558    case EGL_OPENGL_API:
1559       if ((dri2_ctx->base.ClientMajorVersion >= 4
1560            || (dri2_ctx->base.ClientMajorVersion == 3
1561                && dri2_ctx->base.ClientMinorVersion >= 2))
1562           && dri2_ctx->base.Profile == EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT_KHR)
1563          api = __DRI_API_OPENGL_CORE;
1564       else if (dri2_ctx->base.ClientMajorVersion == 3 &&
1565                dri2_ctx->base.ClientMinorVersion == 1)
1566          api = __DRI_API_OPENGL_CORE;
1567       else
1568          api = __DRI_API_OPENGL;
1569       break;
1570    default:
1571       _eglError(EGL_BAD_PARAMETER, "eglCreateContext");
1572       goto cleanup;
1573    }
1574
1575    if (conf != NULL) {
1576       /* The config chosen here isn't necessarily
1577        * used for surfaces later.
1578        * A pixmap surface will use the single config.
1579        * This opportunity depends on disabling the
1580        * doubleBufferMode check in
1581        * src/mesa/main/context.c:check_compatible()
1582        */
1583       if (dri2_config->dri_config[1][0])
1584          dri_config = dri2_config->dri_config[1][0];
1585       else
1586          dri_config = dri2_config->dri_config[0][0];
1587    }
1588    else
1589       dri_config = NULL;
1590
1591    if (!dri2_fill_context_attribs(dri2_ctx, dri2_dpy, ctx_attribs,
1592                                   &num_attribs))
1593       goto cleanup;
1594
1595    if (dri2_dpy->image_driver) {
1596       dri2_ctx->dri_context =
1597          dri2_dpy->image_driver->createContextAttribs(dri2_dpy->dri_screen,
1598                                                       api,
1599                                                       dri_config,
1600                                                       shared,
1601                                                       num_attribs / 2,
1602                                                       ctx_attribs,
1603                                                       & error,
1604                                                       dri2_ctx);
1605       dri2_create_context_attribs_error(error);
1606    } else if (dri2_dpy->dri2) {
1607       if (dri2_dpy->dri2->base.version >= 3) {
1608          dri2_ctx->dri_context =
1609             dri2_dpy->dri2->createContextAttribs(dri2_dpy->dri_screen,
1610                                                  api,
1611                                                  dri_config,
1612                                                  shared,
1613                                                  num_attribs / 2,
1614                                                  ctx_attribs,
1615                                                  & error,
1616                                                  dri2_ctx);
1617          dri2_create_context_attribs_error(error);
1618       } else {
1619          dri2_ctx->dri_context =
1620             dri2_dpy->dri2->createNewContextForAPI(dri2_dpy->dri_screen,
1621                                                    api,
1622                                                    dri_config,
1623                                                    shared,
1624                                                    dri2_ctx);
1625       }
1626    } else {
1627       assert(dri2_dpy->swrast);
1628       if (dri2_dpy->swrast->base.version >= 3) {
1629          dri2_ctx->dri_context =
1630             dri2_dpy->swrast->createContextAttribs(dri2_dpy->dri_screen,
1631                                                    api,
1632                                                    dri_config,
1633                                                    shared,
1634                                                    num_attribs / 2,
1635                                                    ctx_attribs,
1636                                                    & error,
1637                                                    dri2_ctx);
1638          dri2_create_context_attribs_error(error);
1639       } else {
1640          dri2_ctx->dri_context =
1641             dri2_dpy->swrast->createNewContextForAPI(dri2_dpy->dri_screen,
1642                                                      api,
1643                                                      dri_config,
1644                                                      shared,
1645                                                      dri2_ctx);
1646       }
1647    }
1648
1649    if (!dri2_ctx->dri_context)
1650       goto cleanup;
1651
1652    mtx_unlock(&dri2_dpy->lock);
1653
1654    return &dri2_ctx->base;
1655
1656  cleanup:
1657    mtx_unlock(&dri2_dpy->lock);
1658    free(dri2_ctx);
1659    return NULL;
1660 }
1661
1662 /**
1663  * Called via eglDestroyContext(), drv->DestroyContext().
1664  */
1665 static EGLBoolean
1666 dri2_destroy_context(_EGLDisplay *disp, _EGLContext *ctx)
1667 {
1668    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1669    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1670
1671    if (_eglPutContext(ctx)) {
1672       dri2_dpy->core->destroyContext(dri2_ctx->dri_context);
1673       free(dri2_ctx);
1674    }
1675
1676    return EGL_TRUE;
1677 }
1678
1679 EGLBoolean
1680 dri2_init_surface(_EGLSurface *surf, _EGLDisplay *disp, EGLint type,
1681         _EGLConfig *conf, const EGLint *attrib_list,
1682         EGLBoolean enable_out_fence, void *native_surface)
1683 {
1684    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1685    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1686
1687    dri2_surf->out_fence_fd = -1;
1688    dri2_surf->enable_out_fence = false;
1689    if (dri2_dpy->fence && dri2_dpy->fence->base.version >= 2 &&
1690        dri2_dpy->fence->get_capabilities &&
1691        (dri2_dpy->fence->get_capabilities(dri2_dpy->dri_screen) &
1692         __DRI_FENCE_CAP_NATIVE_FD)) {
1693       dri2_surf->enable_out_fence = enable_out_fence;
1694    }
1695
1696    return _eglInitSurface(surf, disp, type, conf, attrib_list, native_surface);
1697 }
1698
1699 static void
1700 dri2_surface_set_out_fence_fd( _EGLSurface *surf, int fence_fd)
1701 {
1702    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1703
1704    if (dri2_surf->out_fence_fd >= 0)
1705       close(dri2_surf->out_fence_fd);
1706
1707    dri2_surf->out_fence_fd = fence_fd;
1708 }
1709
1710 void
1711 dri2_fini_surface(_EGLSurface *surf)
1712 {
1713    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1714
1715    dri2_surface_set_out_fence_fd(surf, -1);
1716    dri2_surf->enable_out_fence = false;
1717 }
1718
1719 static EGLBoolean
1720 dri2_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
1721 {
1722    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1723    EGLBoolean ret = EGL_TRUE;
1724
1725    if (_eglPutSurface(surf))
1726       ret = dri2_dpy->vtbl->destroy_surface(disp, surf);
1727
1728    return ret;
1729 }
1730
1731 static void
1732 dri2_surf_update_fence_fd(_EGLContext *ctx,
1733                           _EGLDisplay *disp, _EGLSurface *surf)
1734 {
1735    __DRIcontext *dri_ctx = dri2_egl_context(ctx)->dri_context;
1736    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1737    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1738    int fence_fd = -1;
1739    void *fence;
1740
1741    if (!dri2_surf->enable_out_fence)
1742       return;
1743
1744    fence = dri2_dpy->fence->create_fence_fd(dri_ctx, -1);
1745    if (fence) {
1746       fence_fd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
1747                                                fence);
1748       dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, fence);
1749    }
1750    dri2_surface_set_out_fence_fd(surf, fence_fd);
1751 }
1752
1753 EGLBoolean
1754 dri2_create_drawable(struct dri2_egl_display *dri2_dpy,
1755                      const __DRIconfig *config,
1756                      struct dri2_egl_surface *dri2_surf,
1757                      void *loaderPrivate)
1758 {
1759    if (dri2_dpy->kopper) {
1760       dri2_surf->dri_drawable =
1761           dri2_dpy->kopper->createNewDrawable(dri2_dpy->dri_screen, config, loaderPrivate,
1762                                               dri2_surf->base.Type == EGL_PBUFFER_BIT ||
1763                                               dri2_surf->base.Type == EGL_PIXMAP_BIT);
1764    } else {
1765       __DRIcreateNewDrawableFunc createNewDrawable;
1766       if (dri2_dpy->image_driver)
1767          createNewDrawable = dri2_dpy->image_driver->createNewDrawable;
1768       else if (dri2_dpy->dri2)
1769          createNewDrawable = dri2_dpy->dri2->createNewDrawable;
1770       else if (dri2_dpy->swrast)
1771          createNewDrawable = dri2_dpy->swrast->createNewDrawable;
1772       else
1773          return _eglError(EGL_BAD_ALLOC, "no createNewDrawable");
1774
1775       dri2_surf->dri_drawable = createNewDrawable(dri2_dpy->dri_screen,
1776                                                   config, loaderPrivate);
1777    }
1778    if (dri2_surf->dri_drawable == NULL)
1779       return _eglError(EGL_BAD_ALLOC, "createNewDrawable");
1780
1781    return EGL_TRUE;
1782 }
1783
1784 /**
1785  * Called via eglMakeCurrent(), drv->MakeCurrent().
1786  */
1787 static EGLBoolean
1788 dri2_make_current(_EGLDisplay *disp, _EGLSurface *dsurf,
1789                   _EGLSurface *rsurf, _EGLContext *ctx)
1790 {
1791    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1792    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1793    _EGLDisplay *old_disp = NULL;
1794    struct dri2_egl_display *old_dri2_dpy = NULL;
1795    _EGLContext *old_ctx;
1796    _EGLSurface *old_dsurf, *old_rsurf;
1797    _EGLSurface *tmp_dsurf, *tmp_rsurf;
1798    __DRIdrawable *ddraw, *rdraw;
1799    __DRIcontext *cctx;
1800    EGLint egl_error = EGL_SUCCESS;
1801
1802    if (!dri2_dpy)
1803       return _eglError(EGL_NOT_INITIALIZED, "eglMakeCurrent");
1804
1805    /* make new bindings, set the EGL error otherwise */
1806    if (!_eglBindContext(ctx, dsurf, rsurf, &old_ctx, &old_dsurf, &old_rsurf))
1807       return EGL_FALSE;
1808
1809    if (old_ctx == ctx && old_dsurf == dsurf && old_rsurf == rsurf) {
1810       _eglPutSurface(old_dsurf);
1811       _eglPutSurface(old_rsurf);
1812       _eglPutContext(old_ctx);
1813       return EGL_TRUE;
1814    }
1815
1816    if (old_ctx) {
1817       __DRIcontext *old_cctx = dri2_egl_context(old_ctx)->dri_context;
1818       old_disp = old_ctx->Resource.Display;
1819       old_dri2_dpy = dri2_egl_display(old_disp);
1820
1821       /* Disable shared buffer mode */
1822       if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1823           old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1824          old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, false);
1825       }
1826
1827       old_dri2_dpy->core->unbindContext(old_cctx);
1828
1829       if (old_dsurf)
1830          dri2_surf_update_fence_fd(old_ctx, old_disp, old_dsurf);
1831    }
1832
1833    ddraw = (dsurf) ? dri2_dpy->vtbl->get_dri_drawable(dsurf) : NULL;
1834    rdraw = (rsurf) ? dri2_dpy->vtbl->get_dri_drawable(rsurf) : NULL;
1835    cctx = (dri2_ctx) ? dri2_ctx->dri_context : NULL;
1836
1837    if (cctx) {
1838       if (!dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1839          _EGLContext *tmp_ctx;
1840
1841          /* dri2_dpy->core->bindContext failed. We cannot tell for sure why, but
1842           * setting the error to EGL_BAD_MATCH is surely better than leaving it
1843           * as EGL_SUCCESS.
1844           */
1845          egl_error = EGL_BAD_MATCH;
1846
1847          /* undo the previous _eglBindContext */
1848          _eglBindContext(old_ctx, old_dsurf, old_rsurf, &ctx, &tmp_dsurf, &tmp_rsurf);
1849          assert(&dri2_ctx->base == ctx &&
1850                 tmp_dsurf == dsurf &&
1851                 tmp_rsurf == rsurf);
1852
1853          _eglPutSurface(dsurf);
1854          _eglPutSurface(rsurf);
1855          _eglPutContext(ctx);
1856
1857          _eglPutSurface(old_dsurf);
1858          _eglPutSurface(old_rsurf);
1859          _eglPutContext(old_ctx);
1860
1861          ddraw = (old_dsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_dsurf) : NULL;
1862          rdraw = (old_rsurf) ? dri2_dpy->vtbl->get_dri_drawable(old_rsurf) : NULL;
1863          cctx = (old_ctx) ? dri2_egl_context(old_ctx)->dri_context : NULL;
1864
1865          /* undo the previous dri2_dpy->core->unbindContext */
1866          if (dri2_dpy->core->bindContext(cctx, ddraw, rdraw)) {
1867             if (old_dsurf && _eglSurfaceInSharedBufferMode(old_dsurf) &&
1868                 old_dri2_dpy->vtbl->set_shared_buffer_mode) {
1869                old_dri2_dpy->vtbl->set_shared_buffer_mode(old_disp, old_dsurf, true);
1870             }
1871
1872             return _eglError(egl_error, "eglMakeCurrent");
1873          }
1874
1875          /* We cannot restore the same state as it was before calling
1876           * eglMakeCurrent() and the spec isn't clear about what to do. We
1877           * can prevent EGL from calling into the DRI driver with no DRI
1878           * context bound.
1879           */
1880          dsurf = rsurf = NULL;
1881          ctx = NULL;
1882
1883          _eglBindContext(ctx, dsurf, rsurf, &tmp_ctx, &tmp_dsurf, &tmp_rsurf);
1884          assert(tmp_ctx == old_ctx && tmp_dsurf == old_dsurf &&
1885                 tmp_rsurf == old_rsurf);
1886
1887          _eglLog(_EGL_WARNING, "DRI2: failed to rebind the previous context");
1888       } else {
1889          /* dri2_dpy->core->bindContext succeeded, so take a reference on the
1890           * dri2_dpy. This prevents dri2_dpy from being reinitialized when a
1891           * EGLDisplay is terminated and then initialized again while a
1892           * context is still bound. See dri2_initialize() for a more in depth
1893           * explanation. */
1894          p_atomic_inc(&dri2_dpy->ref_count);
1895       }
1896    }
1897
1898    dri2_destroy_surface(disp, old_dsurf);
1899    dri2_destroy_surface(disp, old_rsurf);
1900
1901    if (old_ctx) {
1902       dri2_destroy_context(disp, old_ctx);
1903       dri2_display_release(old_disp);
1904    }
1905
1906    if (egl_error != EGL_SUCCESS)
1907       return _eglError(egl_error, "eglMakeCurrent");
1908
1909    if (dsurf && _eglSurfaceHasMutableRenderBuffer(dsurf) &&
1910        dri2_dpy->vtbl->set_shared_buffer_mode) {
1911       /* Always update the shared buffer mode. This is obviously needed when
1912        * the active EGL_RENDER_BUFFER is EGL_SINGLE_BUFFER. When
1913        * EGL_RENDER_BUFFER is EGL_BACK_BUFFER, the update protects us in the
1914        * case where external non-EGL API may have changed window's shared
1915        * buffer mode since we last saw it.
1916        */
1917       bool mode = (dsurf->ActiveRenderBuffer == EGL_SINGLE_BUFFER);
1918       dri2_dpy->vtbl->set_shared_buffer_mode(disp, dsurf, mode);
1919    }
1920
1921    return EGL_TRUE;
1922 }
1923
1924 __DRIdrawable *
1925 dri2_surface_get_dri_drawable(_EGLSurface *surf)
1926 {
1927    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1928
1929    return dri2_surf->dri_drawable;
1930 }
1931
1932 /*
1933  * Called from eglGetProcAddress() via drv->GetProcAddress().
1934  */
1935 static _EGLProc
1936 dri2_get_proc_address(const char *procname)
1937 {
1938    return _glapi_get_proc_address(procname);
1939 }
1940
1941 static _EGLSurface*
1942 dri2_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
1943                            void *native_window, const EGLint *attrib_list)
1944 {
1945    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1946    _EGLSurface *ret =
1947          dri2_dpy->vtbl->create_window_surface(disp, conf, native_window,
1948                                                attrib_list);
1949    mtx_unlock(&dri2_dpy->lock);
1950    return ret;
1951 }
1952
1953 static _EGLSurface*
1954 dri2_create_pixmap_surface(_EGLDisplay *disp, _EGLConfig *conf,
1955                            void *native_pixmap, const EGLint *attrib_list)
1956 {
1957    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1958    _EGLSurface *ret = NULL;
1959
1960    if (dri2_dpy->vtbl->create_pixmap_surface)
1961       ret = dri2_dpy->vtbl->create_pixmap_surface(disp, conf, native_pixmap,
1962                                                   attrib_list);
1963
1964    mtx_unlock(&dri2_dpy->lock);
1965
1966    return ret;
1967 }
1968
1969 static _EGLSurface*
1970 dri2_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
1971                             const EGLint *attrib_list)
1972 {
1973    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1974    _EGLSurface *ret = NULL;
1975
1976    if (dri2_dpy->vtbl->create_pbuffer_surface)
1977       ret = dri2_dpy->vtbl->create_pbuffer_surface(disp, conf, attrib_list);
1978
1979    mtx_unlock(&dri2_dpy->lock);
1980
1981    return ret;
1982 }
1983
1984 static EGLBoolean
1985 dri2_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
1986 {
1987    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
1988    EGLBoolean ret = EGL_TRUE;
1989
1990    if (dri2_dpy->vtbl->swap_interval)
1991       ret = dri2_dpy->vtbl->swap_interval(disp, surf, interval);
1992
1993    mtx_unlock(&dri2_dpy->lock);
1994
1995    return ret;
1996 }
1997
1998 /**
1999  * Asks the client API to flush any rendering to the drawable so that we can
2000  * do our swapbuffers.
2001  */
2002 void
2003 dri2_flush_drawable_for_swapbuffers(_EGLDisplay *disp, _EGLSurface *draw)
2004 {
2005    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2006    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(draw);
2007
2008    if (dri2_dpy->flush) {
2009       if (dri2_dpy->flush->base.version >= 4) {
2010          /* We know there's a current context because:
2011           *
2012           *     "If surface is not bound to the calling thread’s current
2013           *      context, an EGL_BAD_SURFACE error is generated."
2014          */
2015          _EGLContext *ctx = _eglGetCurrentContext();
2016          struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2017
2018          /* From the EGL 1.4 spec (page 52):
2019           *
2020           *     "The contents of ancillary buffers are always undefined
2021           *      after calling eglSwapBuffers."
2022           */
2023          dri2_dpy->flush->flush_with_flags(dri2_ctx->dri_context,
2024                                            dri_drawable,
2025                                            __DRI2_FLUSH_DRAWABLE |
2026                                            __DRI2_FLUSH_INVALIDATE_ANCILLARY,
2027                                            __DRI2_THROTTLE_SWAPBUFFER);
2028       } else {
2029          dri2_dpy->flush->flush(dri_drawable);
2030       }
2031    }
2032 }
2033
2034 static EGLBoolean
2035 dri2_swap_buffers(_EGLDisplay *disp, _EGLSurface *surf)
2036 {
2037    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2038    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2039    _EGLContext *ctx = _eglGetCurrentContext();
2040    EGLBoolean ret;
2041
2042    if (ctx && surf)
2043       dri2_surf_update_fence_fd(ctx, disp, surf);
2044    ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2045
2046    /* SwapBuffers marks the end of the frame; reset the damage region for
2047     * use again next time.
2048     */
2049    if (ret && dri2_dpy->buffer_damage &&
2050        dri2_dpy->buffer_damage->set_damage_region)
2051       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2052
2053    return ret;
2054 }
2055
2056 static EGLBoolean
2057 dri2_swap_buffers_with_damage(_EGLDisplay *disp, _EGLSurface *surf,
2058                               const EGLint *rects, EGLint n_rects)
2059 {
2060    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2061    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2062    _EGLContext *ctx = _eglGetCurrentContext();
2063    EGLBoolean ret;
2064
2065    if (ctx && surf)
2066       dri2_surf_update_fence_fd(ctx, disp, surf);
2067    if (dri2_dpy->vtbl->swap_buffers_with_damage)
2068       ret = dri2_dpy->vtbl->swap_buffers_with_damage(disp, surf,
2069                                                      rects, n_rects);
2070    else
2071       ret = dri2_dpy->vtbl->swap_buffers(disp, surf);
2072
2073    /* SwapBuffers marks the end of the frame; reset the damage region for
2074     * use again next time.
2075     */
2076    if (ret && dri2_dpy->buffer_damage &&
2077        dri2_dpy->buffer_damage->set_damage_region)
2078       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2079
2080    return ret;
2081 }
2082
2083 static EGLBoolean
2084 dri2_swap_buffers_region(_EGLDisplay *disp, _EGLSurface *surf,
2085                          EGLint numRects, const EGLint *rects)
2086 {
2087    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2088    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2089    EGLBoolean ret;
2090
2091    if (!dri2_dpy->vtbl->swap_buffers_region)
2092       return EGL_FALSE;
2093    ret = dri2_dpy->vtbl->swap_buffers_region(disp, surf, numRects, rects);
2094
2095    /* SwapBuffers marks the end of the frame; reset the damage region for
2096     * use again next time.
2097     */
2098    if (ret && dri2_dpy->buffer_damage &&
2099        dri2_dpy->buffer_damage->set_damage_region)
2100       dri2_dpy->buffer_damage->set_damage_region(dri_drawable, 0, NULL);
2101
2102    return ret;
2103 }
2104
2105 static EGLBoolean
2106 dri2_set_damage_region(_EGLDisplay *disp, _EGLSurface *surf,
2107                        EGLint *rects, EGLint n_rects)
2108 {
2109    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2110    __DRIdrawable *drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2111
2112    if (!dri2_dpy->buffer_damage || !dri2_dpy->buffer_damage->set_damage_region) {
2113       mtx_unlock(&dri2_dpy->lock);
2114       return EGL_FALSE;
2115    }
2116
2117    dri2_dpy->buffer_damage->set_damage_region(drawable, n_rects, rects);
2118    mtx_unlock(&dri2_dpy->lock);
2119    return EGL_TRUE;
2120 }
2121
2122 static EGLBoolean
2123 dri2_post_sub_buffer(_EGLDisplay *disp, _EGLSurface *surf,
2124                      EGLint x, EGLint y, EGLint width, EGLint height)
2125 {
2126    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2127    EGLBoolean ret = EGL_FALSE;
2128
2129    if (dri2_dpy->vtbl->post_sub_buffer)
2130       ret = dri2_dpy->vtbl->post_sub_buffer(disp, surf, x, y, width, height);
2131
2132    mtx_unlock(&dri2_dpy->lock);
2133
2134    return ret;
2135 }
2136
2137 static EGLBoolean
2138 dri2_copy_buffers(_EGLDisplay *disp, _EGLSurface *surf, void *native_pixmap_target)
2139 {
2140    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2141    if (!dri2_dpy->vtbl->copy_buffers)
2142       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_NATIVE_PIXMAP, "no support for native pixmaps");
2143    EGLBoolean ret = dri2_dpy->vtbl->copy_buffers(disp, surf, native_pixmap_target);
2144    mtx_unlock(&dri2_dpy->lock);
2145    return ret;
2146 }
2147
2148 static EGLint
2149 dri2_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surf)
2150 {
2151    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2152    if (!dri2_dpy->vtbl->query_buffer_age)
2153       return 0;
2154    return dri2_dpy->vtbl->query_buffer_age(disp, surf);
2155 }
2156
2157 static EGLBoolean
2158 dri2_wait_client(_EGLDisplay *disp, _EGLContext *ctx)
2159 {
2160    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2161    _EGLSurface *surf = ctx->DrawSurface;
2162    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2163
2164    /* FIXME: If EGL allows frontbuffer rendering for window surfaces,
2165     * we need to copy fake to real here.*/
2166
2167    if (dri2_dpy->flush != NULL)
2168       dri2_dpy->flush->flush(dri_drawable);
2169
2170    return EGL_TRUE;
2171 }
2172
2173 static EGLBoolean
2174 dri2_wait_native(EGLint engine)
2175 {
2176    if (engine != EGL_CORE_NATIVE_ENGINE)
2177       return _eglError(EGL_BAD_PARAMETER, "eglWaitNative");
2178    /* glXWaitX(); */
2179
2180    return EGL_TRUE;
2181 }
2182
2183 static EGLBoolean
2184 dri2_bind_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2185 {
2186    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2187    struct dri2_egl_context *dri2_ctx;
2188    _EGLContext *ctx;
2189    GLint format, target;
2190    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2191
2192    ctx = _eglGetCurrentContext();
2193    dri2_ctx = dri2_egl_context(ctx);
2194
2195    if (!_eglBindTexImage(disp, surf, buffer)) {
2196       mtx_unlock(&dri2_dpy->lock);
2197       return EGL_FALSE;
2198    }
2199
2200    switch (surf->TextureFormat) {
2201    case EGL_TEXTURE_RGB:
2202       format = __DRI_TEXTURE_FORMAT_RGB;
2203       break;
2204    case EGL_TEXTURE_RGBA:
2205       format = __DRI_TEXTURE_FORMAT_RGBA;
2206       break;
2207    default:
2208       assert(!"Unexpected texture format in dri2_bind_tex_image()");
2209       format = __DRI_TEXTURE_FORMAT_RGBA;
2210    }
2211
2212    switch (surf->TextureTarget) {
2213    case EGL_TEXTURE_2D:
2214       target = GL_TEXTURE_2D;
2215       break;
2216    default:
2217       target = GL_TEXTURE_2D;
2218       assert(!"Unexpected texture target in dri2_bind_tex_image()");
2219    }
2220
2221    dri2_dpy->tex_buffer->setTexBuffer2(dri2_ctx->dri_context,
2222                                        target, format,
2223                                        dri_drawable);
2224
2225    mtx_unlock(&dri2_dpy->lock);
2226
2227    return EGL_TRUE;
2228 }
2229
2230 static EGLBoolean
2231 dri2_release_tex_image(_EGLDisplay *disp, _EGLSurface *surf, EGLint buffer)
2232 {
2233    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2234    struct dri2_egl_context *dri2_ctx;
2235    _EGLContext *ctx;
2236    GLint  target;
2237    __DRIdrawable *dri_drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
2238
2239    ctx = _eglGetCurrentContext();
2240    dri2_ctx = dri2_egl_context(ctx);
2241
2242    if (!_eglReleaseTexImage(disp, surf, buffer)) {
2243       mtx_unlock(&dri2_dpy->lock);
2244       return EGL_FALSE;
2245    }
2246
2247    switch (surf->TextureTarget) {
2248    case EGL_TEXTURE_2D:
2249       target = GL_TEXTURE_2D;
2250       break;
2251    default:
2252       assert(!"missing texture target");
2253    }
2254
2255    if (dri2_dpy->tex_buffer->base.version >= 3 &&
2256        dri2_dpy->tex_buffer->releaseTexBuffer != NULL) {
2257       dri2_dpy->tex_buffer->releaseTexBuffer(dri2_ctx->dri_context,
2258                                              target, dri_drawable);
2259    }
2260
2261    mtx_unlock(&dri2_dpy->lock);
2262
2263    return EGL_TRUE;
2264 }
2265
2266 static _EGLImage*
2267 dri2_create_image(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
2268                   EGLClientBuffer buffer, const EGLint *attr_list)
2269 {
2270    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2271    _EGLImage *ret = dri2_dpy->vtbl->create_image(disp, ctx, target, buffer,
2272                                                  attr_list);
2273    mtx_unlock(&dri2_dpy->lock);
2274    return ret;
2275 }
2276
2277 _EGLImage *
2278 dri2_create_image_from_dri(_EGLDisplay *disp, __DRIimage *dri_image)
2279 {
2280    struct dri2_egl_image *dri2_img;
2281
2282    if (dri_image == NULL) {
2283       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2284       return NULL;
2285    }
2286
2287    dri2_img = malloc(sizeof *dri2_img);
2288    if (!dri2_img) {
2289       _eglError(EGL_BAD_ALLOC, "dri2_create_image");
2290       return NULL;
2291    }
2292
2293    _eglInitImage(&dri2_img->base, disp);
2294
2295    dri2_img->dri_image = dri_image;
2296
2297    return &dri2_img->base;
2298 }
2299
2300 /**
2301  * Translate a DRI Image extension error code into an EGL error code.
2302  */
2303 static EGLint
2304 egl_error_from_dri_image_error(int dri_error)
2305 {
2306    switch (dri_error) {
2307    case __DRI_IMAGE_ERROR_SUCCESS:
2308       return EGL_SUCCESS;
2309    case __DRI_IMAGE_ERROR_BAD_ALLOC:
2310       return EGL_BAD_ALLOC;
2311    case __DRI_IMAGE_ERROR_BAD_MATCH:
2312       return EGL_BAD_MATCH;
2313    case __DRI_IMAGE_ERROR_BAD_PARAMETER:
2314       return EGL_BAD_PARAMETER;
2315    case __DRI_IMAGE_ERROR_BAD_ACCESS:
2316       return EGL_BAD_ACCESS;
2317    default:
2318       assert(!"unknown dri_error code");
2319       return EGL_BAD_ALLOC;
2320    }
2321 }
2322
2323 static _EGLImage *
2324 dri2_create_image_khr_renderbuffer(_EGLDisplay *disp, _EGLContext *ctx,
2325                                    EGLClientBuffer buffer,
2326                                    const EGLint *attr_list)
2327 {
2328    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2329    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2330    GLuint renderbuffer = (GLuint) (uintptr_t) buffer;
2331    __DRIimage *dri_image;
2332
2333    if (renderbuffer == 0) {
2334       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2335       return EGL_NO_IMAGE_KHR;
2336    }
2337
2338    if (!disp->Extensions.KHR_gl_renderbuffer_image) {
2339       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2340       return EGL_NO_IMAGE_KHR;
2341    }
2342
2343    if (dri2_dpy->image->base.version >= 17 &&
2344        dri2_dpy->image->createImageFromRenderbuffer2) {
2345       unsigned error = ~0;
2346
2347       dri_image = dri2_dpy->image->createImageFromRenderbuffer2(
2348                dri2_ctx->dri_context, renderbuffer, NULL, &error);
2349
2350       assert(!!dri_image == (error == __DRI_IMAGE_ERROR_SUCCESS));
2351
2352       if (!dri_image) {
2353          _eglError(egl_error_from_dri_image_error(error), "dri2_create_image_khr");
2354          return EGL_NO_IMAGE_KHR;
2355       }
2356    } else {
2357       dri_image = dri2_dpy->image->createImageFromRenderbuffer(
2358                dri2_ctx->dri_context, renderbuffer, NULL);
2359       if (!dri_image) {
2360          _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2361          return EGL_NO_IMAGE_KHR;
2362       }
2363    }
2364
2365    return dri2_create_image_from_dri(disp, dri_image);
2366 }
2367
2368 #ifdef HAVE_WAYLAND_PLATFORM
2369
2370 /* This structure describes how a wl_buffer maps to one or more
2371  * __DRIimages.  A wl_drm_buffer stores the wl_drm format code and the
2372  * offsets and strides of the planes in the buffer.  This table maps a
2373  * wl_drm format code to a description of the planes in the buffer
2374  * that lets us create a __DRIimage for each of the planes. */
2375
2376 static const struct wl_drm_components_descriptor {
2377    uint32_t dri_components;
2378    EGLint components;
2379    int nplanes;
2380 } wl_drm_components[] = {
2381    { __DRI_IMAGE_COMPONENTS_RGB, EGL_TEXTURE_RGB, 1 },
2382    { __DRI_IMAGE_COMPONENTS_RGBA, EGL_TEXTURE_RGBA, 1 },
2383    { __DRI_IMAGE_COMPONENTS_Y_U_V, EGL_TEXTURE_Y_U_V_WL, 3 },
2384    { __DRI_IMAGE_COMPONENTS_Y_UV, EGL_TEXTURE_Y_UV_WL, 2 },
2385    { __DRI_IMAGE_COMPONENTS_Y_XUXV, EGL_TEXTURE_Y_XUXV_WL, 2 },
2386 };
2387
2388 static _EGLImage *
2389 dri2_create_image_wayland_wl_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2390                                     EGLClientBuffer _buffer,
2391                                     const EGLint *attr_list)
2392 {
2393    struct wl_drm_buffer *buffer;
2394    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2395    const struct wl_drm_components_descriptor *f;
2396    __DRIimage *dri_image;
2397    _EGLImageAttribs attrs;
2398    int32_t plane;
2399
2400    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm,
2401                                    (struct wl_resource *) _buffer);
2402    if (!buffer)
2403        return NULL;
2404
2405    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2406       return NULL;
2407
2408    plane = attrs.PlaneWL;
2409    f = buffer->driver_format;
2410    if (plane < 0 || plane >= f->nplanes) {
2411       _eglError(EGL_BAD_PARAMETER,
2412                 "dri2_create_image_wayland_wl_buffer (plane out of bounds)");
2413       return NULL;
2414    }
2415
2416    dri_image = dri2_dpy->image->fromPlanar(buffer->driver_buffer, plane, NULL);
2417    if (dri_image == NULL && plane == 0)
2418       dri_image = dri2_dpy->image->dupImage(buffer->driver_buffer, NULL);
2419    if (dri_image == NULL) {
2420       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_wayland_wl_buffer");
2421       return NULL;
2422    }
2423
2424    return dri2_create_image_from_dri(disp, dri_image);
2425 }
2426 #endif
2427
2428 static EGLBoolean
2429 dri2_get_sync_values_chromium(_EGLDisplay *disp, _EGLSurface *surf,
2430                               EGLuint64KHR *ust, EGLuint64KHR *msc,
2431                               EGLuint64KHR *sbc)
2432 {
2433    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2434    EGLBoolean ret = EGL_FALSE;
2435
2436    if (dri2_dpy->vtbl->get_sync_values)
2437       ret = dri2_dpy->vtbl->get_sync_values(disp, surf, ust, msc, sbc);
2438
2439    mtx_unlock(&dri2_dpy->lock);
2440
2441    return ret;
2442 }
2443
2444 static EGLBoolean
2445 dri2_get_msc_rate_angle(_EGLDisplay *disp, _EGLSurface *surf,
2446                         EGLint *numerator, EGLint *denominator)
2447 {
2448    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2449    if (!dri2_dpy->vtbl->get_msc_rate)
2450       return EGL_FALSE;
2451    return dri2_dpy->vtbl->get_msc_rate(disp, surf, numerator, denominator);
2452 }
2453
2454 /**
2455  * Set the error code after a call to
2456  * dri2_egl_image::dri_image::createImageFromTexture.
2457  */
2458 static void
2459 dri2_create_image_khr_texture_error(int dri_error)
2460 {
2461    EGLint egl_error = egl_error_from_dri_image_error(dri_error);
2462
2463    if (egl_error != EGL_SUCCESS)
2464       _eglError(egl_error, "dri2_create_image_khr_texture");
2465 }
2466
2467 static _EGLImage *
2468 dri2_create_image_khr_texture(_EGLDisplay *disp, _EGLContext *ctx,
2469                                    EGLenum target,
2470                                    EGLClientBuffer buffer,
2471                                    const EGLint *attr_list)
2472 {
2473    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2474    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
2475    struct dri2_egl_image *dri2_img;
2476    GLuint texture = (GLuint) (uintptr_t) buffer;
2477    _EGLImageAttribs attrs;
2478    GLuint depth;
2479    GLenum gl_target;
2480    unsigned error;
2481
2482    if (texture == 0) {
2483       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2484       return EGL_NO_IMAGE_KHR;
2485    }
2486
2487    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2488       return EGL_NO_IMAGE_KHR;
2489
2490    switch (target) {
2491    case EGL_GL_TEXTURE_2D_KHR:
2492       if (!disp->Extensions.KHR_gl_texture_2D_image) {
2493          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2494          return EGL_NO_IMAGE_KHR;
2495       }
2496       depth = 0;
2497       gl_target = GL_TEXTURE_2D;
2498       break;
2499    case EGL_GL_TEXTURE_3D_KHR:
2500       if (!disp->Extensions.KHR_gl_texture_3D_image) {
2501          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2502          return EGL_NO_IMAGE_KHR;
2503       }
2504
2505       depth = attrs.GLTextureZOffset;
2506       gl_target = GL_TEXTURE_3D;
2507       break;
2508    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
2509    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
2510    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
2511    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
2512    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
2513    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
2514       if (!disp->Extensions.KHR_gl_texture_cubemap_image) {
2515          _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
2516          return EGL_NO_IMAGE_KHR;
2517       }
2518
2519       depth = target - EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR;
2520       gl_target = GL_TEXTURE_CUBE_MAP;
2521       break;
2522    default:
2523       unreachable("Unexpected target in dri2_create_image_khr_texture()");
2524       return EGL_NO_IMAGE_KHR;
2525    }
2526
2527    dri2_img = malloc(sizeof *dri2_img);
2528    if (!dri2_img) {
2529       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
2530       return EGL_NO_IMAGE_KHR;
2531    }
2532
2533    _eglInitImage(&dri2_img->base, disp);
2534
2535    dri2_img->dri_image =
2536       dri2_dpy->image->createImageFromTexture(dri2_ctx->dri_context,
2537                                               gl_target,
2538                                               texture,
2539                                               depth,
2540                                               attrs.GLTextureLevel,
2541                                               &error,
2542                                               NULL);
2543    dri2_create_image_khr_texture_error(error);
2544
2545    if (!dri2_img->dri_image) {
2546       free(dri2_img);
2547       return EGL_NO_IMAGE_KHR;
2548    }
2549    return &dri2_img->base;
2550 }
2551
2552 static EGLBoolean
2553 dri2_query_surface(_EGLDisplay *disp, _EGLSurface *surf,
2554                    EGLint attribute, EGLint *value)
2555 {
2556    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2557    EGLBoolean ret;
2558
2559    if (!dri2_dpy->vtbl->query_surface) {
2560       ret = _eglQuerySurface(disp, surf, attribute, value);
2561    } else {
2562       ret = dri2_dpy->vtbl->query_surface(disp, surf, attribute, value);
2563    }
2564
2565    mtx_unlock(&dri2_dpy->lock);
2566
2567    return ret;
2568 }
2569
2570 static struct wl_buffer*
2571 dri2_create_wayland_buffer_from_image(_EGLDisplay *disp, _EGLImage *img)
2572 {
2573    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2574    struct wl_buffer *ret = NULL;
2575
2576    if (dri2_dpy->vtbl->create_wayland_buffer_from_image)
2577       ret = dri2_dpy->vtbl->create_wayland_buffer_from_image(disp, img);
2578
2579    mtx_unlock(&dri2_dpy->lock);
2580
2581    return ret;
2582 }
2583
2584 #ifdef HAVE_LIBDRM
2585 static _EGLImage *
2586 dri2_create_image_mesa_drm_buffer(_EGLDisplay *disp, _EGLContext *ctx,
2587                                   EGLClientBuffer buffer, const EGLint *attr_list)
2588 {
2589    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2590    EGLint format, name, pitch;
2591    _EGLImageAttribs attrs;
2592    __DRIimage *dri_image;
2593
2594    name = (EGLint) (uintptr_t) buffer;
2595
2596    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2597       return NULL;
2598
2599    if (attrs.Width <= 0 || attrs.Height <= 0 ||
2600        attrs.DRMBufferStrideMESA <= 0) {
2601       _eglError(EGL_BAD_PARAMETER,
2602                 "bad width, height or stride");
2603       return NULL;
2604    }
2605
2606    switch (attrs.DRMBufferFormatMESA) {
2607    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
2608       format = __DRI_IMAGE_FORMAT_ARGB8888;
2609       pitch = attrs.DRMBufferStrideMESA;
2610       break;
2611    default:
2612       _eglError(EGL_BAD_PARAMETER,
2613                 "dri2_create_image_khr: unsupported pixmap depth");
2614       return NULL;
2615    }
2616
2617    dri_image =
2618       dri2_dpy->image->createImageFromName(dri2_dpy->dri_screen,
2619                                            attrs.Width,
2620                                            attrs.Height,
2621                                            format,
2622                                            name,
2623                                            pitch,
2624                                            NULL);
2625
2626    return dri2_create_image_from_dri(disp, dri_image);
2627 }
2628
2629 static EGLBoolean
2630 dri2_check_dma_buf_attribs(const _EGLImageAttribs *attrs)
2631 {
2632    /**
2633      * The spec says:
2634      *
2635      * "Required attributes and their values are as follows:
2636      *
2637      *  * EGL_WIDTH & EGL_HEIGHT: The logical dimensions of the buffer in pixels
2638      *
2639      *  * EGL_LINUX_DRM_FOURCC_EXT: The pixel format of the buffer, as specified
2640      *    by drm_fourcc.h and used as the pixel_format parameter of the
2641      *    drm_mode_fb_cmd2 ioctl."
2642      *
2643      * and
2644      *
2645      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2646      *    incomplete, EGL_BAD_PARAMETER is generated."
2647      */
2648    if (attrs->Width <= 0 || attrs->Height <= 0 ||
2649        !attrs->DMABufFourCC.IsPresent)
2650       return _eglError(EGL_BAD_PARAMETER, "attribute(s) missing");
2651
2652    /**
2653     * Also:
2654     *
2655     * "If <target> is EGL_LINUX_DMA_BUF_EXT and one or more of the values
2656     *  specified for a plane's pitch or offset isn't supported by EGL,
2657     *  EGL_BAD_ACCESS is generated."
2658     */
2659    for (unsigned i = 0; i < ARRAY_SIZE(attrs->DMABufPlanePitches); ++i) {
2660       if (attrs->DMABufPlanePitches[i].IsPresent &&
2661           attrs->DMABufPlanePitches[i].Value <= 0)
2662          return _eglError(EGL_BAD_ACCESS, "invalid pitch");
2663    }
2664
2665    /**
2666     * If <target> is EGL_LINUX_DMA_BUF_EXT, both or neither of the following
2667     * attribute values may be given.
2668     *
2669     * This is referring to EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT and
2670     * EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, and the same for other planes.
2671     */
2672    for (unsigned i = 0; i < DMA_BUF_MAX_PLANES; ++i) {
2673       if (attrs->DMABufPlaneModifiersLo[i].IsPresent !=
2674           attrs->DMABufPlaneModifiersHi[i].IsPresent)
2675          return _eglError(EGL_BAD_PARAMETER, "modifier attribute lo or hi missing");
2676    }
2677
2678    /* Although the EGL_EXT_image_dma_buf_import_modifiers spec doesn't
2679     * mandate it, we only accept the same modifier across all planes. */
2680    for (unsigned i = 1; i < DMA_BUF_MAX_PLANES; ++i) {
2681       if (attrs->DMABufPlaneFds[i].IsPresent) {
2682          if ((attrs->DMABufPlaneModifiersLo[0].IsPresent !=
2683                attrs->DMABufPlaneModifiersLo[i].IsPresent) ||
2684              (attrs->DMABufPlaneModifiersLo[0].Value !=
2685                attrs->DMABufPlaneModifiersLo[i].Value) ||
2686              (attrs->DMABufPlaneModifiersHi[0].Value !=
2687                attrs->DMABufPlaneModifiersHi[i].Value))
2688             return _eglError(EGL_BAD_PARAMETER, "modifier attributes not equal");
2689       }
2690    }
2691
2692    return EGL_TRUE;
2693 }
2694
2695 /* Returns the total number of planes for the format or zero if it isn't a
2696  * valid fourcc format.
2697  */
2698 static unsigned
2699 dri2_num_fourcc_format_planes(EGLint format)
2700 {
2701    switch (format) {
2702    case DRM_FORMAT_R8:
2703    case DRM_FORMAT_RG88:
2704    case DRM_FORMAT_GR88:
2705    case DRM_FORMAT_R16:
2706    case DRM_FORMAT_GR1616:
2707    case DRM_FORMAT_RGB332:
2708    case DRM_FORMAT_BGR233:
2709    case DRM_FORMAT_XRGB4444:
2710    case DRM_FORMAT_XBGR4444:
2711    case DRM_FORMAT_RGBX4444:
2712    case DRM_FORMAT_BGRX4444:
2713    case DRM_FORMAT_ARGB4444:
2714    case DRM_FORMAT_ABGR4444:
2715    case DRM_FORMAT_RGBA4444:
2716    case DRM_FORMAT_BGRA4444:
2717    case DRM_FORMAT_XRGB1555:
2718    case DRM_FORMAT_XBGR1555:
2719    case DRM_FORMAT_RGBX5551:
2720    case DRM_FORMAT_BGRX5551:
2721    case DRM_FORMAT_ARGB1555:
2722    case DRM_FORMAT_ABGR1555:
2723    case DRM_FORMAT_RGBA5551:
2724    case DRM_FORMAT_BGRA5551:
2725    case DRM_FORMAT_RGB565:
2726    case DRM_FORMAT_BGR565:
2727    case DRM_FORMAT_RGB888:
2728    case DRM_FORMAT_BGR888:
2729    case DRM_FORMAT_XRGB8888:
2730    case DRM_FORMAT_XBGR8888:
2731    case DRM_FORMAT_RGBX8888:
2732    case DRM_FORMAT_BGRX8888:
2733    case DRM_FORMAT_ARGB8888:
2734    case DRM_FORMAT_ABGR8888:
2735    case DRM_FORMAT_RGBA8888:
2736    case DRM_FORMAT_BGRA8888:
2737    case DRM_FORMAT_XRGB2101010:
2738    case DRM_FORMAT_XBGR2101010:
2739    case DRM_FORMAT_RGBX1010102:
2740    case DRM_FORMAT_BGRX1010102:
2741    case DRM_FORMAT_ARGB2101010:
2742    case DRM_FORMAT_ABGR2101010:
2743    case DRM_FORMAT_RGBA1010102:
2744    case DRM_FORMAT_BGRA1010102:
2745    case DRM_FORMAT_ABGR16161616:
2746    case DRM_FORMAT_XBGR16161616:
2747    case DRM_FORMAT_XBGR16161616F:
2748    case DRM_FORMAT_ABGR16161616F:
2749    case DRM_FORMAT_YUYV:
2750    case DRM_FORMAT_YVYU:
2751    case DRM_FORMAT_UYVY:
2752    case DRM_FORMAT_VYUY:
2753    case DRM_FORMAT_AYUV:
2754    case DRM_FORMAT_XYUV8888:
2755    case DRM_FORMAT_Y210:
2756    case DRM_FORMAT_Y212:
2757    case DRM_FORMAT_Y216:
2758    case DRM_FORMAT_Y410:
2759    case DRM_FORMAT_Y412:
2760    case DRM_FORMAT_Y416:
2761       return 1;
2762
2763    case DRM_FORMAT_NV12:
2764    case DRM_FORMAT_NV21:
2765    case DRM_FORMAT_NV16:
2766    case DRM_FORMAT_NV61:
2767    case DRM_FORMAT_P010:
2768    case DRM_FORMAT_P012:
2769    case DRM_FORMAT_P016:
2770       return 2;
2771
2772    case DRM_FORMAT_YUV410:
2773    case DRM_FORMAT_YVU410:
2774    case DRM_FORMAT_YUV411:
2775    case DRM_FORMAT_YVU411:
2776    case DRM_FORMAT_YUV420:
2777    case DRM_FORMAT_YVU420:
2778    case DRM_FORMAT_YUV422:
2779    case DRM_FORMAT_YVU422:
2780    case DRM_FORMAT_YUV444:
2781    case DRM_FORMAT_YVU444:
2782       return 3;
2783
2784    default:
2785       return 0;
2786    }
2787 }
2788
2789 /* Returns the total number of file descriptors. Zero indicates an error. */
2790 static unsigned
2791 dri2_check_dma_buf_format(const _EGLImageAttribs *attrs)
2792 {
2793    unsigned plane_n = dri2_num_fourcc_format_planes(attrs->DMABufFourCC.Value);
2794    if (plane_n == 0) {
2795       _eglError(EGL_BAD_MATCH, "unknown drm fourcc format");
2796       return 0;
2797    }
2798
2799    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; i++) {
2800       /**
2801        * The modifiers extension spec says:
2802        *
2803        * "Modifiers may modify any attribute of a buffer import, including
2804        *  but not limited to adding extra planes to a format which
2805        *  otherwise does not have those planes. As an example, a modifier
2806        *  may add a plane for an external compression buffer to a
2807        *  single-plane format. The exact meaning and effect of any
2808        *  modifier is canonically defined by drm_fourcc.h, not as part of
2809        *  this extension."
2810        */
2811       if (attrs->DMABufPlaneModifiersLo[i].IsPresent &&
2812           attrs->DMABufPlaneModifiersHi[i].IsPresent) {
2813          plane_n = i + 1;
2814       }
2815    }
2816
2817    /**
2818      * The spec says:
2819      *
2820      * "* If <target> is EGL_LINUX_DMA_BUF_EXT, and the list of attributes is
2821      *    incomplete, EGL_BAD_PARAMETER is generated."
2822      */
2823    for (unsigned i = 0; i < plane_n; ++i) {
2824       if (!attrs->DMABufPlaneFds[i].IsPresent ||
2825           !attrs->DMABufPlaneOffsets[i].IsPresent ||
2826           !attrs->DMABufPlanePitches[i].IsPresent) {
2827          _eglError(EGL_BAD_PARAMETER, "plane attribute(s) missing");
2828          return 0;
2829       }
2830    }
2831
2832    /**
2833     * The spec also says:
2834     *
2835     * "If <target> is EGL_LINUX_DMA_BUF_EXT, and the EGL_LINUX_DRM_FOURCC_EXT
2836     *  attribute indicates a single-plane format, EGL_BAD_ATTRIBUTE is
2837     *  generated if any of the EGL_DMA_BUF_PLANE1_* or EGL_DMA_BUF_PLANE2_*
2838     *  or EGL_DMA_BUF_PLANE3_* attributes are specified."
2839     */
2840    for (unsigned i = plane_n; i < DMA_BUF_MAX_PLANES; ++i) {
2841       if (attrs->DMABufPlaneFds[i].IsPresent ||
2842           attrs->DMABufPlaneOffsets[i].IsPresent ||
2843           attrs->DMABufPlanePitches[i].IsPresent) {
2844          _eglError(EGL_BAD_ATTRIBUTE, "too many plane attributes");
2845          return 0;
2846       }
2847    }
2848
2849    return plane_n;
2850 }
2851
2852 static EGLBoolean
2853 dri2_query_dma_buf_formats(_EGLDisplay *disp, EGLint max,
2854                            EGLint *formats, EGLint *count)
2855 {
2856    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2857    if (max < 0 || (max > 0 && formats == NULL)) {
2858       _eglError(EGL_BAD_PARAMETER, "invalid value for max count of formats");
2859       goto fail;
2860    }
2861
2862    if (dri2_dpy->image->base.version < 15 ||
2863        dri2_dpy->image->queryDmaBufFormats == NULL)
2864       goto fail;
2865
2866    if (!dri2_dpy->image->queryDmaBufFormats(dri2_dpy->dri_screen, max,
2867                                             formats, count))
2868       goto fail;
2869
2870    if (max > 0) {
2871       /* Assert that all of the formats returned are actually fourcc formats.
2872        * Some day, if we want the internal interface function to be able to
2873        * return the fake fourcc formats defined in dri_interface.h, we'll have
2874        * to do something more clever here to pair the list down to just real
2875        * fourcc formats so that we don't leak the fake internal ones.
2876        */
2877       for (int i = 0; i < *count; i++) {
2878          assert(dri2_num_fourcc_format_planes(formats[i]) > 0);
2879       }
2880    }
2881
2882    mtx_unlock(&dri2_dpy->lock);
2883
2884    return EGL_TRUE;
2885
2886 fail:
2887    mtx_unlock(&dri2_dpy->lock);
2888    return EGL_FALSE;
2889 }
2890
2891 static EGLBoolean
2892 dri2_query_dma_buf_modifiers(_EGLDisplay *disp, EGLint format,
2893                              EGLint max, EGLuint64KHR *modifiers,
2894                              EGLBoolean *external_only, EGLint *count)
2895 {
2896    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
2897
2898    if (dri2_num_fourcc_format_planes(format) == 0)
2899       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid fourcc format");
2900
2901    if (max < 0)
2902       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid value for max count of formats");
2903
2904    if (max > 0 && modifiers == NULL)
2905       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid modifiers array");
2906
2907    if (dri2_dpy->image->base.version < 15 ||
2908        dri2_dpy->image->queryDmaBufModifiers == NULL) {
2909       mtx_unlock(&dri2_dpy->lock);
2910       return EGL_FALSE;
2911    }
2912
2913    if (dri2_dpy->image->queryDmaBufModifiers(dri2_dpy->dri_screen, format,
2914                                              max, modifiers,
2915                                              (unsigned int *) external_only,
2916                                              count) == false)
2917       return dri2_egl_error_unlock(dri2_dpy, EGL_BAD_PARAMETER, "invalid format");
2918
2919    mtx_unlock(&dri2_dpy->lock);
2920
2921    return EGL_TRUE;
2922 }
2923
2924 /**
2925  * The spec says:
2926  *
2927  * "If eglCreateImageKHR is successful for a EGL_LINUX_DMA_BUF_EXT target, the
2928  *  EGL will take a reference to the dma_buf(s) which it will release at any
2929  *  time while the EGLDisplay is initialized. It is the responsibility of the
2930  *  application to close the dma_buf file descriptors."
2931  *
2932  * Therefore we must never close or otherwise modify the file descriptors.
2933  */
2934 _EGLImage *
2935 dri2_create_image_dma_buf(_EGLDisplay *disp, _EGLContext *ctx,
2936                           EGLClientBuffer buffer, const EGLint *attr_list)
2937 {
2938    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
2939    _EGLImage *res;
2940    _EGLImageAttribs attrs;
2941    __DRIimage *dri_image;
2942    unsigned num_fds;
2943    int fds[DMA_BUF_MAX_PLANES];
2944    int pitches[DMA_BUF_MAX_PLANES];
2945    int offsets[DMA_BUF_MAX_PLANES];
2946    uint64_t modifier;
2947    bool has_modifier = false;
2948    unsigned error;
2949
2950    /**
2951     * The spec says:
2952     *
2953     * ""* If <target> is EGL_LINUX_DMA_BUF_EXT and <buffer> is not NULL, the
2954     *     error EGL_BAD_PARAMETER is generated."
2955     */
2956    if (buffer != NULL) {
2957       _eglError(EGL_BAD_PARAMETER, "buffer not NULL");
2958       return NULL;
2959    }
2960
2961    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
2962       return NULL;
2963
2964    if (!dri2_check_dma_buf_attribs(&attrs))
2965       return NULL;
2966
2967    num_fds = dri2_check_dma_buf_format(&attrs);
2968    if (!num_fds)
2969       return NULL;
2970
2971    for (unsigned i = 0; i < num_fds; ++i) {
2972       fds[i] = attrs.DMABufPlaneFds[i].Value;
2973       pitches[i] = attrs.DMABufPlanePitches[i].Value;
2974       offsets[i] = attrs.DMABufPlaneOffsets[i].Value;
2975    }
2976
2977    /* dri2_check_dma_buf_attribs ensures that the modifier, if available,
2978     * will be present in attrs.DMABufPlaneModifiersLo[0] and
2979     * attrs.DMABufPlaneModifiersHi[0] */
2980    if (attrs.DMABufPlaneModifiersLo[0].IsPresent) {
2981       modifier = combine_u32_into_u64(attrs.DMABufPlaneModifiersHi[0].Value,
2982                                       attrs.DMABufPlaneModifiersLo[0].Value);
2983       has_modifier = true;
2984    }
2985
2986    if (attrs.ProtectedContent) {
2987       if (dri2_dpy->image->base.version < 18 ||
2988           dri2_dpy->image->createImageFromDmaBufs3 == NULL) {
2989          _eglError(EGL_BAD_MATCH, "unsupported protected_content attribute");
2990          return EGL_NO_IMAGE_KHR;
2991       }
2992       if (!has_modifier)
2993          modifier = DRM_FORMAT_MOD_INVALID;
2994
2995       dri_image =
2996          dri2_dpy->image->createImageFromDmaBufs3(dri2_dpy->dri_screen,
2997             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
2998             modifier, fds, num_fds, pitches, offsets,
2999             attrs.DMABufYuvColorSpaceHint.Value,
3000             attrs.DMABufSampleRangeHint.Value,
3001             attrs.DMABufChromaHorizontalSiting.Value,
3002             attrs.DMABufChromaVerticalSiting.Value,
3003             attrs.ProtectedContent ? __DRI_IMAGE_PROTECTED_CONTENT_FLAG : 0,
3004             &error,
3005             NULL);
3006    }
3007    else if (has_modifier) {
3008       if (dri2_dpy->image->base.version < 15 ||
3009           dri2_dpy->image->createImageFromDmaBufs2 == NULL) {
3010          _eglError(EGL_BAD_MATCH, "unsupported dma_buf format modifier");
3011          return EGL_NO_IMAGE_KHR;
3012       }
3013       dri_image =
3014          dri2_dpy->image->createImageFromDmaBufs2(dri2_dpy->dri_screen,
3015             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
3016             modifier, fds, num_fds, pitches, offsets,
3017             attrs.DMABufYuvColorSpaceHint.Value,
3018             attrs.DMABufSampleRangeHint.Value,
3019             attrs.DMABufChromaHorizontalSiting.Value,
3020             attrs.DMABufChromaVerticalSiting.Value,
3021             &error,
3022             NULL);
3023    }
3024    else {
3025       dri_image =
3026          dri2_dpy->image->createImageFromDmaBufs(dri2_dpy->dri_screen,
3027             attrs.Width, attrs.Height, attrs.DMABufFourCC.Value,
3028             fds, num_fds, pitches, offsets,
3029             attrs.DMABufYuvColorSpaceHint.Value,
3030             attrs.DMABufSampleRangeHint.Value,
3031             attrs.DMABufChromaHorizontalSiting.Value,
3032             attrs.DMABufChromaVerticalSiting.Value,
3033             &error,
3034             NULL);
3035    }
3036    dri2_create_image_khr_texture_error(error);
3037
3038    if (!dri_image)
3039       return EGL_NO_IMAGE_KHR;
3040
3041    res = dri2_create_image_from_dri(disp, dri_image);
3042
3043    return res;
3044 }
3045 static _EGLImage *
3046 dri2_create_drm_image_mesa(_EGLDisplay *disp, const EGLint *attr_list)
3047 {
3048    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3049    struct dri2_egl_image *dri2_img;
3050    _EGLImageAttribs attrs;
3051    unsigned int dri_use, valid_mask;
3052    int format;
3053
3054    if (!attr_list) {
3055       _eglError(EGL_BAD_PARAMETER, __func__);
3056       goto fail;
3057    }
3058
3059    if (!_eglParseImageAttribList(&attrs, disp, attr_list))
3060       goto fail;
3061
3062    if (attrs.Width <= 0 || attrs.Height <= 0) {
3063       _eglError(EGL_BAD_PARAMETER, __func__);
3064       goto fail;
3065    }
3066
3067    switch (attrs.DRMBufferFormatMESA) {
3068    case EGL_DRM_BUFFER_FORMAT_ARGB32_MESA:
3069       format = __DRI_IMAGE_FORMAT_ARGB8888;
3070       break;
3071    default:
3072       _eglError(EGL_BAD_PARAMETER, __func__);
3073       goto fail;
3074    }
3075
3076    valid_mask =
3077       EGL_DRM_BUFFER_USE_SCANOUT_MESA |
3078       EGL_DRM_BUFFER_USE_SHARE_MESA |
3079       EGL_DRM_BUFFER_USE_CURSOR_MESA;
3080    if (attrs.DRMBufferUseMESA & ~valid_mask) {
3081       _eglError(EGL_BAD_PARAMETER, __func__);
3082       goto fail;
3083    }
3084
3085    dri_use = 0;
3086    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SHARE_MESA)
3087       dri_use |= __DRI_IMAGE_USE_SHARE;
3088    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_SCANOUT_MESA)
3089       dri_use |= __DRI_IMAGE_USE_SCANOUT;
3090    if (attrs.DRMBufferUseMESA & EGL_DRM_BUFFER_USE_CURSOR_MESA)
3091       dri_use |= __DRI_IMAGE_USE_CURSOR;
3092
3093    dri2_img = malloc(sizeof *dri2_img);
3094    if (!dri2_img) {
3095       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
3096       goto fail;
3097    }
3098
3099    _eglInitImage(&dri2_img->base, disp);
3100
3101    dri2_img->dri_image =
3102       dri2_dpy->image->createImage(dri2_dpy->dri_screen,
3103                                    attrs.Width, attrs.Height,
3104                                    format, dri_use, dri2_img);
3105    if (dri2_img->dri_image == NULL) {
3106       free(dri2_img);
3107       _eglError(EGL_BAD_ALLOC, "dri2_create_drm_image_mesa");
3108       goto fail;
3109    }
3110
3111    mtx_unlock(&dri2_dpy->lock);
3112
3113    return &dri2_img->base;
3114
3115 fail:
3116    mtx_unlock(&dri2_dpy->lock);
3117    return EGL_NO_IMAGE_KHR;
3118 }
3119
3120 static EGLBoolean
3121 dri2_export_drm_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3122                           EGLint *name, EGLint *handle, EGLint *stride)
3123 {
3124    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3125    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3126
3127    if (name && !dri2_dpy->image->queryImage(dri2_img->dri_image,
3128                                             __DRI_IMAGE_ATTRIB_NAME, name))
3129       return _eglError(EGL_BAD_ALLOC, "dri2_export_drm_image_mesa");
3130
3131    if (handle)
3132       dri2_dpy->image->queryImage(dri2_img->dri_image,
3133                                   __DRI_IMAGE_ATTRIB_HANDLE, handle);
3134
3135    if (stride)
3136       dri2_dpy->image->queryImage(dri2_img->dri_image,
3137                                   __DRI_IMAGE_ATTRIB_STRIDE, stride);
3138
3139    mtx_unlock(&dri2_dpy->lock);
3140
3141    return EGL_TRUE;
3142 }
3143
3144 /**
3145  * Checks if we can support EGL_MESA_image_dma_buf_export on this image.
3146
3147  * The spec provides a boolean return for the driver to reject exporting for
3148  * basically any reason, but doesn't specify any particular error cases.  For
3149  * now, we just fail if we don't have a DRM fourcc for the format.
3150  */
3151 static bool
3152 dri2_can_export_dma_buf_image(_EGLDisplay *disp, _EGLImage *img)
3153 {
3154    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3155    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3156    EGLint fourcc;
3157
3158    if (!dri2_dpy->image->queryImage(dri2_img->dri_image,
3159                                     __DRI_IMAGE_ATTRIB_FOURCC, &fourcc)) {
3160       return false;
3161    }
3162
3163    return true;
3164 }
3165
3166 static EGLBoolean
3167 dri2_export_dma_buf_image_query_mesa(_EGLDisplay *disp, _EGLImage *img,
3168                                      EGLint *fourcc, EGLint *nplanes,
3169                                      EGLuint64KHR *modifiers)
3170 {
3171    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3172    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3173    int num_planes;
3174
3175    if (!dri2_can_export_dma_buf_image(disp, img)) {
3176       mtx_unlock(&dri2_dpy->lock);
3177       return EGL_FALSE;
3178    }
3179
3180    dri2_dpy->image->queryImage(dri2_img->dri_image,
3181                                __DRI_IMAGE_ATTRIB_NUM_PLANES, &num_planes);
3182    if (nplanes)
3183      *nplanes = num_planes;
3184
3185    if (fourcc)
3186       dri2_dpy->image->queryImage(dri2_img->dri_image,
3187                                   __DRI_IMAGE_ATTRIB_FOURCC, fourcc);
3188
3189    if (modifiers) {
3190       int mod_hi, mod_lo;
3191       uint64_t modifier = DRM_FORMAT_MOD_INVALID;
3192       bool query;
3193
3194       query = dri2_dpy->image->queryImage(dri2_img->dri_image,
3195                                           __DRI_IMAGE_ATTRIB_MODIFIER_UPPER,
3196                                           &mod_hi);
3197       query &= dri2_dpy->image->queryImage(dri2_img->dri_image,
3198                                            __DRI_IMAGE_ATTRIB_MODIFIER_LOWER,
3199                                            &mod_lo);
3200       if (query)
3201          modifier = combine_u32_into_u64 (mod_hi, mod_lo);
3202
3203       for (int i = 0; i < num_planes; i++)
3204         modifiers[i] = modifier;
3205    }
3206
3207    mtx_unlock(&dri2_dpy->lock);
3208
3209    return EGL_TRUE;
3210 }
3211
3212 static EGLBoolean
3213 dri2_export_dma_buf_image_mesa(_EGLDisplay *disp, _EGLImage *img,
3214                                int *fds, EGLint *strides, EGLint *offsets)
3215 {
3216    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3217    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
3218    EGLint nplanes;
3219
3220    if (!dri2_can_export_dma_buf_image(disp, img))
3221       return EGL_FALSE;
3222
3223    /* EGL_MESA_image_dma_buf_export spec says:
3224     *    "If the number of fds is less than the number of planes, then
3225     *    subsequent fd slots should contain -1."
3226     */
3227    if (fds) {
3228       /* Query nplanes so that we know how big the given array is. */
3229       dri2_dpy->image->queryImage(dri2_img->dri_image,
3230                                   __DRI_IMAGE_ATTRIB_NUM_PLANES, &nplanes);
3231       memset(fds, -1, nplanes * sizeof(int));
3232    }
3233
3234    /* rework later to provide multiple fds/strides/offsets */
3235    if (fds)
3236       dri2_dpy->image->queryImage(dri2_img->dri_image,
3237                                   __DRI_IMAGE_ATTRIB_FD, fds);
3238
3239    if (strides)
3240       dri2_dpy->image->queryImage(dri2_img->dri_image,
3241                                   __DRI_IMAGE_ATTRIB_STRIDE, strides);
3242
3243    if (offsets) {
3244       int img_offset;
3245       bool ret = dri2_dpy->image->queryImage(dri2_img->dri_image,
3246                      __DRI_IMAGE_ATTRIB_OFFSET, &img_offset);
3247       if (ret)
3248          offsets[0] = img_offset;
3249       else
3250          offsets[0] = 0;
3251    }
3252
3253    mtx_unlock(&dri2_dpy->lock);
3254
3255    return EGL_TRUE;
3256 }
3257
3258 #endif
3259
3260 _EGLImage *
3261 dri2_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
3262                       EGLClientBuffer buffer, const EGLint *attr_list)
3263 {
3264    switch (target) {
3265    case EGL_GL_TEXTURE_2D_KHR:
3266    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
3267    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
3268    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
3269    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
3270    case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
3271    case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
3272    case EGL_GL_TEXTURE_3D_KHR:
3273       return dri2_create_image_khr_texture(disp, ctx, target, buffer, attr_list);
3274    case EGL_GL_RENDERBUFFER_KHR:
3275       return dri2_create_image_khr_renderbuffer(disp, ctx, buffer, attr_list);
3276 #ifdef HAVE_LIBDRM
3277    case EGL_DRM_BUFFER_MESA:
3278       return dri2_create_image_mesa_drm_buffer(disp, ctx, buffer, attr_list);
3279    case EGL_LINUX_DMA_BUF_EXT:
3280       return dri2_create_image_dma_buf(disp, ctx, buffer, attr_list);
3281 #endif
3282 #ifdef HAVE_WAYLAND_PLATFORM
3283    case EGL_WAYLAND_BUFFER_WL:
3284       return dri2_create_image_wayland_wl_buffer(disp, ctx, buffer, attr_list);
3285 #endif
3286    default:
3287       _eglError(EGL_BAD_PARAMETER, "dri2_create_image_khr");
3288       return EGL_NO_IMAGE_KHR;
3289    }
3290 }
3291
3292 static EGLBoolean
3293 dri2_destroy_image_khr(_EGLDisplay *disp, _EGLImage *image)
3294 {
3295    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3296    struct dri2_egl_image *dri2_img = dri2_egl_image(image);
3297
3298    dri2_dpy->image->destroyImage(dri2_img->dri_image);
3299    free(dri2_img);
3300
3301    mtx_unlock(&dri2_dpy->lock);
3302
3303    return EGL_TRUE;
3304 }
3305
3306 #ifdef HAVE_WAYLAND_PLATFORM
3307
3308 static void
3309 dri2_wl_reference_buffer(void *user_data, uint32_t name, int fd,
3310                          struct wl_drm_buffer *buffer)
3311 {
3312    _EGLDisplay *disp = user_data;
3313    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3314    __DRIimage *img;
3315    int dri_components = 0;
3316
3317    if (fd == -1)
3318       img = dri2_dpy->image->createImageFromNames(dri2_dpy->dri_screen,
3319                                                   buffer->width,
3320                                                   buffer->height,
3321                                                   buffer->format,
3322                                                   (int*)&name, 1,
3323                                                   buffer->stride,
3324                                                   buffer->offset,
3325                                                   NULL);
3326    else
3327       img = dri2_dpy->image->createImageFromFds(dri2_dpy->dri_screen,
3328                                                 buffer->width,
3329                                                 buffer->height,
3330                                                 buffer->format,
3331                                                 &fd, 1,
3332                                                 buffer->stride,
3333                                                 buffer->offset,
3334                                                 NULL);
3335
3336    if (img == NULL)
3337       return;
3338
3339    dri2_dpy->image->queryImage(img, __DRI_IMAGE_ATTRIB_COMPONENTS, &dri_components);
3340
3341    buffer->driver_format = NULL;
3342    for (int i = 0; i < ARRAY_SIZE(wl_drm_components); i++)
3343       if (wl_drm_components[i].dri_components == dri_components)
3344          buffer->driver_format = &wl_drm_components[i];
3345
3346    if (buffer->driver_format == NULL)
3347       dri2_dpy->image->destroyImage(img);
3348    else
3349       buffer->driver_buffer = img;
3350 }
3351
3352 static void
3353 dri2_wl_release_buffer(void *user_data, struct wl_drm_buffer *buffer)
3354 {
3355    _EGLDisplay *disp = user_data;
3356    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3357
3358    dri2_dpy->image->destroyImage(buffer->driver_buffer);
3359 }
3360
3361 static EGLBoolean
3362 dri2_bind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3363 {
3364    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3365    const struct wayland_drm_callbacks wl_drm_callbacks = {
3366       .authenticate = (int(*)(void *, uint32_t)) dri2_dpy->vtbl->authenticate,
3367       .reference_buffer = dri2_wl_reference_buffer,
3368       .release_buffer = dri2_wl_release_buffer,
3369       .is_format_supported = dri2_wl_is_format_supported
3370    };
3371    int flags = 0;
3372    char *device_name;
3373    uint64_t cap;
3374
3375    if (dri2_dpy->wl_server_drm)
3376       goto fail;
3377
3378    device_name = drmGetRenderDeviceNameFromFd(dri2_dpy->fd);
3379    if (!device_name)
3380       device_name = strdup(dri2_dpy->device_name);
3381    if (!device_name)
3382       goto fail;
3383
3384    if (drmGetCap(dri2_dpy->fd, DRM_CAP_PRIME, &cap) == 0 &&
3385        cap == (DRM_PRIME_CAP_IMPORT | DRM_PRIME_CAP_EXPORT) &&
3386        dri2_dpy->image->base.version >= 7 &&
3387        dri2_dpy->image->createImageFromFds != NULL)
3388       flags |= WAYLAND_DRM_PRIME;
3389
3390    dri2_dpy->wl_server_drm =
3391            wayland_drm_init(wl_dpy, device_name,
3392                             &wl_drm_callbacks, disp, flags);
3393
3394    free(device_name);
3395
3396    if (!dri2_dpy->wl_server_drm)
3397       goto fail;
3398
3399 #ifdef HAVE_DRM_PLATFORM
3400    /* We have to share the wl_drm instance with gbm, so gbm can convert
3401     * wl_buffers to gbm bos. */
3402    if (dri2_dpy->gbm_dri)
3403       dri2_dpy->gbm_dri->wl_drm = dri2_dpy->wl_server_drm;
3404 #endif
3405
3406    mtx_unlock(&dri2_dpy->lock);
3407    return EGL_TRUE;
3408
3409 fail:
3410    mtx_unlock(&dri2_dpy->lock);
3411    return EGL_FALSE;
3412 }
3413
3414 static EGLBoolean
3415 dri2_unbind_wayland_display_wl(_EGLDisplay *disp, struct wl_display *wl_dpy)
3416 {
3417    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3418
3419    if (!dri2_dpy->wl_server_drm)
3420            return EGL_FALSE;
3421
3422    wayland_drm_uninit(dri2_dpy->wl_server_drm);
3423    dri2_dpy->wl_server_drm = NULL;
3424
3425    return EGL_TRUE;
3426 }
3427
3428 static EGLBoolean
3429 dri2_query_wayland_buffer_wl(_EGLDisplay *disp, struct wl_resource *buffer_resource,
3430                              EGLint attribute, EGLint *value)
3431 {
3432    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3433    struct wl_drm_buffer *buffer;
3434    const struct wl_drm_components_descriptor *format;
3435
3436    buffer = wayland_drm_buffer_get(dri2_dpy->wl_server_drm, buffer_resource);
3437    if (!buffer)
3438       return EGL_FALSE;
3439
3440    format = buffer->driver_format;
3441    switch (attribute) {
3442    case EGL_TEXTURE_FORMAT:
3443       *value = format->components;
3444       return EGL_TRUE;
3445    case EGL_WIDTH:
3446       *value = buffer->width;
3447       return EGL_TRUE;
3448    case EGL_HEIGHT:
3449       *value = buffer->height;
3450       return EGL_TRUE;
3451    }
3452
3453    return EGL_FALSE;
3454 }
3455 #endif
3456
3457 static void
3458 dri2_egl_ref_sync(struct dri2_egl_sync *sync)
3459 {
3460    p_atomic_inc(&sync->refcount);
3461 }
3462
3463 static void
3464 dri2_egl_unref_sync(struct dri2_egl_display *dri2_dpy,
3465                     struct dri2_egl_sync *dri2_sync)
3466 {
3467    if (p_atomic_dec_zero(&dri2_sync->refcount)) {
3468       switch (dri2_sync->base.Type) {
3469       case EGL_SYNC_REUSABLE_KHR:
3470          cnd_destroy(&dri2_sync->cond);
3471          break;
3472       case EGL_SYNC_NATIVE_FENCE_ANDROID:
3473          if (dri2_sync->base.SyncFd != EGL_NO_NATIVE_FENCE_FD_ANDROID)
3474             close(dri2_sync->base.SyncFd);
3475          break;
3476       default:
3477          break;
3478       }
3479
3480       if (dri2_sync->fence)
3481          dri2_dpy->fence->destroy_fence(dri2_dpy->dri_screen, dri2_sync->fence);
3482
3483       free(dri2_sync);
3484    }
3485 }
3486
3487 static _EGLSync *
3488 dri2_create_sync(_EGLDisplay *disp, EGLenum type, const EGLAttrib *attrib_list)
3489 {
3490    _EGLContext *ctx = _eglGetCurrentContext();
3491    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3492    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3493    struct dri2_egl_sync *dri2_sync;
3494    EGLint ret;
3495    pthread_condattr_t attr;
3496
3497    dri2_sync = calloc(1, sizeof(struct dri2_egl_sync));
3498    if (!dri2_sync) {
3499       _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3500       goto fail;
3501    }
3502
3503    if (!_eglInitSync(&dri2_sync->base, disp, type, attrib_list)) {
3504       goto fail;
3505    }
3506
3507    switch (type) {
3508    case EGL_SYNC_FENCE_KHR:
3509       dri2_sync->fence = dri2_dpy->fence->create_fence(dri2_ctx->dri_context);
3510       if (!dri2_sync->fence) {
3511          /* Why did it fail? DRI doesn't return an error code, so we emit
3512           * a generic EGL error that doesn't communicate user error.
3513           */
3514          _eglError(EGL_BAD_ALLOC, "eglCreateSyncKHR");
3515          goto fail;
3516       }
3517       break;
3518
3519    case EGL_SYNC_CL_EVENT_KHR:
3520       dri2_sync->fence = dri2_dpy->fence->get_fence_from_cl_event(
3521                                  dri2_dpy->dri_screen,
3522                                  dri2_sync->base.CLEvent);
3523       /* this can only happen if the cl_event passed in is invalid. */
3524       if (!dri2_sync->fence) {
3525          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3526          goto fail;
3527       }
3528
3529       /* the initial status must be "signaled" if the cl_event is signaled */
3530       if (dri2_dpy->fence->client_wait_sync(dri2_ctx->dri_context,
3531                                             dri2_sync->fence, 0, 0))
3532          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3533       break;
3534
3535    case EGL_SYNC_REUSABLE_KHR:
3536       /* intialize attr */
3537       ret = pthread_condattr_init(&attr);
3538
3539       if (ret) {
3540          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3541          goto fail;
3542       }
3543
3544       /* change clock attribute to CLOCK_MONOTONIC */
3545       ret = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
3546
3547       if (ret) {
3548          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3549          goto fail;
3550       }
3551
3552       ret = pthread_cond_init(&dri2_sync->cond, &attr);
3553
3554       if (ret) {
3555          _eglError(EGL_BAD_ACCESS, "eglCreateSyncKHR");
3556          goto fail;
3557       }
3558
3559       /* initial status of reusable sync must be "unsignaled" */
3560       dri2_sync->base.SyncStatus = EGL_UNSIGNALED_KHR;
3561       break;
3562
3563    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3564       if (dri2_dpy->fence->create_fence_fd) {
3565          dri2_sync->fence = dri2_dpy->fence->create_fence_fd(
3566                                     dri2_ctx->dri_context,
3567                                     dri2_sync->base.SyncFd);
3568       }
3569       if (!dri2_sync->fence) {
3570          _eglError(EGL_BAD_ATTRIBUTE, "eglCreateSyncKHR");
3571          goto fail;
3572       }
3573       break;
3574    }
3575
3576    p_atomic_set(&dri2_sync->refcount, 1);
3577    mtx_unlock(&dri2_dpy->lock);
3578
3579    return &dri2_sync->base;
3580
3581 fail:
3582    free(dri2_sync);
3583    mtx_unlock(&dri2_dpy->lock);
3584    return NULL;
3585 }
3586
3587 static EGLBoolean
3588 dri2_destroy_sync(_EGLDisplay *disp, _EGLSync *sync)
3589 {
3590    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3591    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3592    EGLint ret = EGL_TRUE;
3593    EGLint err;
3594
3595    /* if type of sync is EGL_SYNC_REUSABLE_KHR and it is not signaled yet,
3596     * then unlock all threads possibly blocked by the reusable sync before
3597     * destroying it.
3598     */
3599    if (dri2_sync->base.Type == EGL_SYNC_REUSABLE_KHR &&
3600        dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3601       dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3602       /* unblock all threads currently blocked by sync */
3603       err = cnd_broadcast(&dri2_sync->cond);
3604
3605       if (err) {
3606          _eglError(EGL_BAD_ACCESS, "eglDestroySyncKHR");
3607          ret = EGL_FALSE;
3608       }
3609    }
3610
3611    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3612
3613    mtx_unlock(&dri2_dpy->lock);
3614
3615    return ret;
3616 }
3617
3618 static EGLint
3619 dri2_dup_native_fence_fd(_EGLDisplay *disp, _EGLSync *sync)
3620 {
3621    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3622    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3623
3624    assert(sync->Type == EGL_SYNC_NATIVE_FENCE_ANDROID);
3625
3626    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3627       /* try to retrieve the actual native fence fd.. if rendering is
3628        * not flushed this will just return -1, aka NO_NATIVE_FENCE_FD:
3629        */
3630       sync->SyncFd = dri2_dpy->fence->get_fence_fd(dri2_dpy->dri_screen,
3631                                                    dri2_sync->fence);
3632    }
3633
3634    mtx_unlock(&dri2_dpy->lock);
3635
3636    if (sync->SyncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3637       /* if native fence fd still not created, return an error: */
3638       _eglError(EGL_BAD_PARAMETER, "eglDupNativeFenceFDANDROID");
3639       return EGL_NO_NATIVE_FENCE_FD_ANDROID;
3640    }
3641
3642    assert(sync_valid_fd(sync->SyncFd));
3643
3644    return os_dupfd_cloexec(sync->SyncFd);
3645 }
3646
3647 static void
3648 dri2_set_blob_cache_funcs(_EGLDisplay *disp,
3649                           EGLSetBlobFuncANDROID set,
3650                           EGLGetBlobFuncANDROID get)
3651 {
3652    struct dri2_egl_display *dri2_dpy = dri2_egl_display_lock(disp);
3653    dri2_dpy->blob->set_cache_funcs(dri2_dpy->dri_screen, set, get);
3654    mtx_unlock(&dri2_dpy->lock);
3655 }
3656
3657 static EGLint
3658 dri2_client_wait_sync(_EGLDisplay *disp, _EGLSync *sync,
3659                       EGLint flags, EGLTime timeout)
3660 {
3661    _EGLContext *ctx = _eglGetCurrentContext();
3662    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3663    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3664    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3665    unsigned wait_flags = 0;
3666
3667    EGLint ret = EGL_CONDITION_SATISFIED_KHR;
3668
3669    /* The EGL_KHR_fence_sync spec states:
3670     *
3671     *    "If no context is current for the bound API,
3672     *     the EGL_SYNC_FLUSH_COMMANDS_BIT_KHR bit is ignored.
3673     */
3674    if (dri2_ctx && flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)
3675       wait_flags |= __DRI2_FENCE_FLAG_FLUSH_COMMANDS;
3676
3677    /* the sync object should take a reference while waiting */
3678    dri2_egl_ref_sync(dri2_sync);
3679
3680    switch (sync->Type) {
3681    case EGL_SYNC_FENCE_KHR:
3682    case EGL_SYNC_NATIVE_FENCE_ANDROID:
3683    case EGL_SYNC_CL_EVENT_KHR:
3684       if (dri2_dpy->fence->client_wait_sync(dri2_ctx ? dri2_ctx->dri_context : NULL,
3685                                          dri2_sync->fence, wait_flags,
3686                                          timeout))
3687          dri2_sync->base.SyncStatus = EGL_SIGNALED_KHR;
3688       else
3689          ret = EGL_TIMEOUT_EXPIRED_KHR;
3690       break;
3691
3692    case EGL_SYNC_REUSABLE_KHR:
3693       if (dri2_ctx && dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR &&
3694           (flags & EGL_SYNC_FLUSH_COMMANDS_BIT_KHR)) {
3695          /* flush context if EGL_SYNC_FLUSH_COMMANDS_BIT_KHR is set */
3696          dri2_gl_flush();
3697       }
3698
3699       /* if timeout is EGL_FOREVER_KHR, it should wait without any timeout.*/
3700       if (timeout == EGL_FOREVER_KHR) {
3701          mtx_lock(&dri2_sync->mutex);
3702          cnd_wait(&dri2_sync->cond, &dri2_sync->mutex);
3703          mtx_unlock(&dri2_sync->mutex);
3704       } else {
3705          /* if reusable sync has not been yet signaled */
3706          if (dri2_sync->base.SyncStatus != EGL_SIGNALED_KHR) {
3707             /* timespecs for cnd_timedwait */
3708             struct timespec current;
3709             struct timespec expire;
3710
3711             /* We override the clock to monotonic when creating the condition
3712              * variable. */
3713             clock_gettime(CLOCK_MONOTONIC, &current);
3714
3715             /* calculating when to expire */
3716             expire.tv_nsec = timeout % 1000000000L;
3717             expire.tv_sec = timeout / 1000000000L;
3718
3719             expire.tv_nsec += current.tv_nsec;
3720             expire.tv_sec += current.tv_sec;
3721
3722             /* expire.nsec now is a number between 0 and 1999999998 */
3723             if (expire.tv_nsec > 999999999L) {
3724                expire.tv_sec++;
3725                expire.tv_nsec -= 1000000000L;
3726             }
3727
3728             mtx_lock(&dri2_sync->mutex);
3729             ret = cnd_timedwait(&dri2_sync->cond, &dri2_sync->mutex, &expire);
3730             mtx_unlock(&dri2_sync->mutex);
3731
3732             if (ret == thrd_timedout) {
3733                if (dri2_sync->base.SyncStatus == EGL_UNSIGNALED_KHR) {
3734                   ret = EGL_TIMEOUT_EXPIRED_KHR;
3735                } else {
3736                   _eglError(EGL_BAD_ACCESS, "eglClientWaitSyncKHR");
3737                   ret = EGL_FALSE;
3738                }
3739             }
3740          }
3741       }
3742       break;
3743    }
3744
3745    dri2_egl_unref_sync(dri2_dpy, dri2_sync);
3746
3747    return ret;
3748 }
3749
3750 static EGLBoolean
3751 dri2_signal_sync(_EGLDisplay *disp, _EGLSync *sync, EGLenum mode)
3752 {
3753    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3754    EGLint ret;
3755
3756    if (sync->Type != EGL_SYNC_REUSABLE_KHR)
3757       return _eglError(EGL_BAD_MATCH, "eglSignalSyncKHR");
3758
3759    if (mode != EGL_SIGNALED_KHR && mode != EGL_UNSIGNALED_KHR)
3760       return _eglError(EGL_BAD_ATTRIBUTE, "eglSignalSyncKHR");
3761
3762    dri2_sync->base.SyncStatus = mode;
3763
3764    if (mode == EGL_SIGNALED_KHR) {
3765       ret = cnd_broadcast(&dri2_sync->cond);
3766
3767       /* fail to broadcast */
3768       if (ret)
3769          return _eglError(EGL_BAD_ACCESS, "eglSignalSyncKHR");
3770    }
3771
3772    return EGL_TRUE;
3773 }
3774
3775 static EGLint
3776 dri2_server_wait_sync(_EGLDisplay *disp, _EGLSync *sync)
3777 {
3778    _EGLContext *ctx = _eglGetCurrentContext();
3779    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3780    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3781    struct dri2_egl_sync *dri2_sync = dri2_egl_sync(sync);
3782
3783    dri2_dpy->fence->server_wait_sync(dri2_ctx->dri_context,
3784                                      dri2_sync->fence, 0);
3785    return EGL_TRUE;
3786 }
3787
3788 static int
3789 dri2_interop_query_device_info(_EGLDisplay *disp, _EGLContext *ctx,
3790                                struct mesa_glinterop_device_info *out)
3791 {
3792    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3793    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3794
3795    if (!dri2_dpy->interop)
3796       return MESA_GLINTEROP_UNSUPPORTED;
3797
3798    return dri2_dpy->interop->query_device_info(dri2_ctx->dri_context, out);
3799 }
3800
3801 static int
3802 dri2_interop_export_object(_EGLDisplay *disp, _EGLContext *ctx,
3803                            struct mesa_glinterop_export_in *in,
3804                            struct mesa_glinterop_export_out *out)
3805 {
3806    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
3807    struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
3808
3809    if (!dri2_dpy->interop)
3810       return MESA_GLINTEROP_UNSUPPORTED;
3811
3812    return dri2_dpy->interop->export_object(dri2_ctx->dri_context, in, out);
3813 }
3814
3815 const _EGLDriver _eglDriver = {
3816    .Initialize = dri2_initialize,
3817    .Terminate = dri2_terminate,
3818    .CreateContext = dri2_create_context,
3819    .DestroyContext = dri2_destroy_context,
3820    .MakeCurrent = dri2_make_current,
3821    .CreateWindowSurface = dri2_create_window_surface,
3822    .CreatePixmapSurface = dri2_create_pixmap_surface,
3823    .CreatePbufferSurface = dri2_create_pbuffer_surface,
3824    .DestroySurface = dri2_destroy_surface,
3825    .GetProcAddress = dri2_get_proc_address,
3826    .WaitClient = dri2_wait_client,
3827    .WaitNative = dri2_wait_native,
3828    .BindTexImage = dri2_bind_tex_image,
3829    .ReleaseTexImage = dri2_release_tex_image,
3830    .SwapInterval = dri2_swap_interval,
3831    .SwapBuffers = dri2_swap_buffers,
3832    .SwapBuffersWithDamageEXT = dri2_swap_buffers_with_damage,
3833    .SwapBuffersRegionNOK = dri2_swap_buffers_region,
3834    .SetDamageRegion = dri2_set_damage_region,
3835    .PostSubBufferNV = dri2_post_sub_buffer,
3836    .CopyBuffers = dri2_copy_buffers,
3837    .QueryBufferAge = dri2_query_buffer_age,
3838    .CreateImageKHR = dri2_create_image,
3839    .DestroyImageKHR = dri2_destroy_image_khr,
3840    .CreateWaylandBufferFromImageWL = dri2_create_wayland_buffer_from_image,
3841    .QuerySurface = dri2_query_surface,
3842    .QueryDriverName = dri2_query_driver_name,
3843    .QueryDriverConfig = dri2_query_driver_config,
3844 #ifdef HAVE_LIBDRM
3845    .CreateDRMImageMESA = dri2_create_drm_image_mesa,
3846    .ExportDRMImageMESA = dri2_export_drm_image_mesa,
3847    .ExportDMABUFImageQueryMESA = dri2_export_dma_buf_image_query_mesa,
3848    .ExportDMABUFImageMESA = dri2_export_dma_buf_image_mesa,
3849    .QueryDmaBufFormatsEXT = dri2_query_dma_buf_formats,
3850    .QueryDmaBufModifiersEXT = dri2_query_dma_buf_modifiers,
3851 #endif
3852 #ifdef HAVE_WAYLAND_PLATFORM
3853    .BindWaylandDisplayWL = dri2_bind_wayland_display_wl,
3854    .UnbindWaylandDisplayWL = dri2_unbind_wayland_display_wl,
3855    .QueryWaylandBufferWL = dri2_query_wayland_buffer_wl,
3856 #endif
3857    .GetSyncValuesCHROMIUM = dri2_get_sync_values_chromium,
3858    .GetMscRateANGLE = dri2_get_msc_rate_angle,
3859    .CreateSyncKHR = dri2_create_sync,
3860    .ClientWaitSyncKHR = dri2_client_wait_sync,
3861    .SignalSyncKHR = dri2_signal_sync,
3862    .WaitSyncKHR = dri2_server_wait_sync,
3863    .DestroySyncKHR = dri2_destroy_sync,
3864    .GLInteropQueryDeviceInfo = dri2_interop_query_device_info,
3865    .GLInteropExportObject = dri2_interop_export_object,
3866    .DupNativeFenceFDANDROID = dri2_dup_native_fence_fd,
3867    .SetBlobCacheFuncsANDROID = dri2_set_blob_cache_funcs,
3868 };