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