• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2011-2012 Intel Corporation
3  * Copyright © 2012 Collabora, Ltd.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23  * DEALINGS IN THE SOFTWARE.
24  *
25  * Authors:
26  *    Kristian Høgsberg <krh@bitplanet.net>
27  *    Benjamin Franzke <benjaminfranzke@googlemail.com>
28  */
29 
30 #include <stdint.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <limits.h>
34 #include <dlfcn.h>
35 #include <errno.h>
36 #include <unistd.h>
37 #include <fcntl.h>
38 #include <xf86drm.h>
39 #include "drm-uapi/drm_fourcc.h"
40 #include <sys/mman.h>
41 
42 #include "egl_dri2.h"
43 #include "loader.h"
44 #include "util/u_vector.h"
45 #include "util/anon_file.h"
46 #include "eglglobals.h"
47 
48 #include <wayland-egl-backend.h>
49 #include <wayland-client.h>
50 #include "wayland-drm-client-protocol.h"
51 #include "linux-dmabuf-unstable-v1-client-protocol.h"
52 
53 /* cheesy workaround until wayland 1.18 is released */
54 #if WAYLAND_VERSION_MAJOR > 1 || \
55    (WAYLAND_VERSION_MAJOR == 1 && WAYLAND_VERSION_MINOR < 18)
56 #define WL_SHM_FORMAT_ABGR16161616F 0x48344241
57 #define WL_SHM_FORMAT_XBGR16161616F 0x48344258
58 #endif
59 
60 /*
61  * The index of entries in this table is used as a bitmask in
62  * dri2_dpy->formats, which tracks the formats supported by our server.
63  */
64 static const struct dri2_wl_visual {
65    const char *format_name;
66    uint32_t wl_drm_format;
67    uint32_t wl_shm_format;
68    int dri_image_format;
69    /* alt_dri_image_format is a substitute wl_buffer format to use for a
70     * wl-server unsupported dri_image_format, ie. some other dri_image_format in
71     * the table, of the same precision but with different channel ordering, or
72     * __DRI_IMAGE_FORMAT_NONE if an alternate format is not needed or supported.
73     * The code checks if alt_dri_image_format can be used as a fallback for a
74     * dri_image_format for a given wl-server implementation.
75     */
76    int alt_dri_image_format;
77    int bpp;
78    int rgba_shifts[4];
79    unsigned int rgba_sizes[4];
80 } dri2_wl_visuals[] = {
81    {
82       "ABGR16F",
83       WL_DRM_FORMAT_ABGR16F, WL_SHM_FORMAT_ABGR16161616F,
84       __DRI_IMAGE_FORMAT_ABGR16161616F, 0, 64,
85       { 0, 16, 32, 48 },
86       { 16, 16, 16, 16 },
87    },
88    {
89       "XBGR16F",
90       WL_DRM_FORMAT_XBGR16F, WL_SHM_FORMAT_XBGR16161616F,
91       __DRI_IMAGE_FORMAT_XBGR16161616F, 0, 64,
92       { 0, 16, 32, -1 },
93       { 16, 16, 16, 0 },
94    },
95    {
96       "XRGB2101010",
97       WL_DRM_FORMAT_XRGB2101010, WL_SHM_FORMAT_XRGB2101010,
98       __DRI_IMAGE_FORMAT_XRGB2101010, __DRI_IMAGE_FORMAT_XBGR2101010, 32,
99       { 20, 10, 0, -1 },
100       { 10, 10, 10, 0 },
101    },
102    {
103       "ARGB2101010",
104       WL_DRM_FORMAT_ARGB2101010, WL_SHM_FORMAT_ARGB2101010,
105       __DRI_IMAGE_FORMAT_ARGB2101010, __DRI_IMAGE_FORMAT_ABGR2101010, 32,
106       { 20, 10, 0, 30 },
107       { 10, 10, 10, 2 },
108    },
109    {
110       "XBGR2101010",
111       WL_DRM_FORMAT_XBGR2101010, WL_SHM_FORMAT_XBGR2101010,
112       __DRI_IMAGE_FORMAT_XBGR2101010, __DRI_IMAGE_FORMAT_XRGB2101010, 32,
113       { 0, 10, 20, -1 },
114       { 10, 10, 10, 0 },
115    },
116    {
117       "ABGR2101010",
118       WL_DRM_FORMAT_ABGR2101010, WL_SHM_FORMAT_ABGR2101010,
119       __DRI_IMAGE_FORMAT_ABGR2101010, __DRI_IMAGE_FORMAT_ARGB2101010, 32,
120       { 0, 10, 20, 30 },
121       { 10, 10, 10, 2 },
122    },
123    {
124       "XRGB8888",
125       WL_DRM_FORMAT_XRGB8888, WL_SHM_FORMAT_XRGB8888,
126       __DRI_IMAGE_FORMAT_XRGB8888, __DRI_IMAGE_FORMAT_NONE, 32,
127       { 16, 8, 0, -1 },
128       { 8, 8, 8, 0 },
129    },
130    {
131       "ARGB8888",
132       WL_DRM_FORMAT_ARGB8888, WL_SHM_FORMAT_ARGB8888,
133       __DRI_IMAGE_FORMAT_ARGB8888, __DRI_IMAGE_FORMAT_NONE, 32,
134       { 16, 8, 0, 24 },
135       { 8, 8, 8, 8 },
136    },
137    {
138       "RGB565",
139       WL_DRM_FORMAT_RGB565, WL_SHM_FORMAT_RGB565,
140       __DRI_IMAGE_FORMAT_RGB565, __DRI_IMAGE_FORMAT_NONE, 16,
141       { 11, 5, 0, -1 },
142       { 5, 6, 5, 0 },
143    },
144 };
145 
146 static_assert(ARRAY_SIZE(dri2_wl_visuals) <= EGL_DRI2_MAX_FORMATS,
147               "dri2_egl_display::formats is not large enough for "
148               "the formats in dri2_wl_visuals");
149 
150 static int
dri2_wl_visual_idx_from_config(struct dri2_egl_display * dri2_dpy,const __DRIconfig * config)151 dri2_wl_visual_idx_from_config(struct dri2_egl_display *dri2_dpy,
152                                const __DRIconfig *config)
153 {
154    int shifts[4];
155    unsigned int sizes[4];
156 
157    dri2_get_shifts_and_sizes(dri2_dpy->core, config, shifts, sizes);
158 
159    for (unsigned int i = 0; i < ARRAY_SIZE(dri2_wl_visuals); i++) {
160       const struct dri2_wl_visual *wl_visual = &dri2_wl_visuals[i];
161 
162       if (shifts[0] == wl_visual->rgba_shifts[0] &&
163           shifts[1] == wl_visual->rgba_shifts[1] &&
164           shifts[2] == wl_visual->rgba_shifts[2] &&
165           shifts[3] == wl_visual->rgba_shifts[3] &&
166           sizes[0] == wl_visual->rgba_sizes[0] &&
167           sizes[1] == wl_visual->rgba_sizes[1] &&
168           sizes[2] == wl_visual->rgba_sizes[2] &&
169           sizes[3] == wl_visual->rgba_sizes[3]) {
170          return i;
171       }
172    }
173 
174    return -1;
175 }
176 
177 static int
dri2_wl_visual_idx_from_fourcc(uint32_t fourcc)178 dri2_wl_visual_idx_from_fourcc(uint32_t fourcc)
179 {
180    for (int i = 0; i < ARRAY_SIZE(dri2_wl_visuals); i++) {
181       /* wl_drm format codes overlap with DRIImage FourCC codes for all formats
182        * we support. */
183       if (dri2_wl_visuals[i].wl_drm_format == fourcc)
184          return i;
185    }
186 
187    return -1;
188 }
189 
190 static int
dri2_wl_visual_idx_from_dri_image_format(uint32_t dri_image_format)191 dri2_wl_visual_idx_from_dri_image_format(uint32_t dri_image_format)
192 {
193    for (int i = 0; i < ARRAY_SIZE(dri2_wl_visuals); i++) {
194       if (dri2_wl_visuals[i].dri_image_format == dri_image_format)
195          return i;
196    }
197 
198    return -1;
199 }
200 
201 static int
dri2_wl_visual_idx_from_shm_format(uint32_t shm_format)202 dri2_wl_visual_idx_from_shm_format(uint32_t shm_format)
203 {
204    for (int i = 0; i < ARRAY_SIZE(dri2_wl_visuals); i++) {
205       if (dri2_wl_visuals[i].wl_shm_format == shm_format)
206          return i;
207    }
208 
209    return -1;
210 }
211 
212 bool
dri2_wl_is_format_supported(void * user_data,uint32_t format)213 dri2_wl_is_format_supported(void* user_data, uint32_t format)
214 {
215    _EGLDisplay *disp = (_EGLDisplay *) user_data;
216    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
217    int j = dri2_wl_visual_idx_from_fourcc(format);
218 
219    if (j == -1)
220       return false;
221 
222    for (int i = 0; dri2_dpy->driver_configs[i]; i++)
223       if (j == dri2_wl_visual_idx_from_config(dri2_dpy,
224                                               dri2_dpy->driver_configs[i]))
225          return true;
226 
227    return false;
228 }
229 
230 static int
roundtrip(struct dri2_egl_display * dri2_dpy)231 roundtrip(struct dri2_egl_display *dri2_dpy)
232 {
233    return wl_display_roundtrip_queue(dri2_dpy->wl_dpy, dri2_dpy->wl_queue);
234 }
235 
236 static void
wl_buffer_release(void * data,struct wl_buffer * buffer)237 wl_buffer_release(void *data, struct wl_buffer *buffer)
238 {
239    struct dri2_egl_surface *dri2_surf = data;
240    int i;
241 
242    for (i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); ++i)
243       if (dri2_surf->color_buffers[i].wl_buffer == buffer)
244          break;
245 
246    assert (i < ARRAY_SIZE(dri2_surf->color_buffers));
247 
248    if (dri2_surf->color_buffers[i].wl_release) {
249       wl_buffer_destroy(buffer);
250       dri2_surf->color_buffers[i].wl_release = false;
251       dri2_surf->color_buffers[i].wl_buffer = NULL;
252    }
253 
254    dri2_surf->color_buffers[i].locked = false;
255 }
256 
257 static const struct wl_buffer_listener wl_buffer_listener = {
258    .release = wl_buffer_release
259 };
260 
261 static void
resize_callback(struct wl_egl_window * wl_win,void * data)262 resize_callback(struct wl_egl_window *wl_win, void *data)
263 {
264    struct dri2_egl_surface *dri2_surf = data;
265    struct dri2_egl_display *dri2_dpy =
266       dri2_egl_display(dri2_surf->base.Resource.Display);
267 
268    if (dri2_surf->base.Width == wl_win->width &&
269        dri2_surf->base.Height == wl_win->height)
270       return;
271 
272    /* Update the surface size as soon as native window is resized; from user
273     * pov, this makes the effect that resize is done immediately after native
274     * window resize, without requiring to wait until the first draw.
275     *
276     * A more detailed and lengthy explanation can be found at
277     * https://lists.freedesktop.org/archives/mesa-dev/2018-June/196474.html
278     */
279    if (!dri2_surf->back) {
280       dri2_surf->base.Width = wl_win->width;
281       dri2_surf->base.Height = wl_win->height;
282    }
283    dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
284 }
285 
286 static void
destroy_window_callback(void * data)287 destroy_window_callback(void *data)
288 {
289    struct dri2_egl_surface *dri2_surf = data;
290    dri2_surf->wl_win = NULL;
291 }
292 
293 static struct wl_surface *
get_wl_surface_proxy(struct wl_egl_window * window)294 get_wl_surface_proxy(struct wl_egl_window *window)
295 {
296     /* Version 3 of wl_egl_window introduced a version field at the same
297      * location where a pointer to wl_surface was stored. Thus, if
298      * window->version is dereferenceable, we've been given an older version of
299      * wl_egl_window, and window->version points to wl_surface */
300    if (_eglPointerIsDereferencable((void *)(window->version))) {
301       return wl_proxy_create_wrapper((void *)(window->version));
302    }
303    return wl_proxy_create_wrapper(window->surface);
304 }
305 
306 /**
307  * Called via eglCreateWindowSurface(), drv->CreateWindowSurface().
308  */
309 static _EGLSurface *
dri2_wl_create_window_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)310 dri2_wl_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
311                               void *native_window, const EGLint *attrib_list)
312 {
313    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
314    struct dri2_egl_config *dri2_conf = dri2_egl_config(conf);
315    struct wl_egl_window *window = native_window;
316    struct dri2_egl_surface *dri2_surf;
317    int visual_idx;
318    const __DRIconfig *config;
319 
320    dri2_surf = calloc(1, sizeof *dri2_surf);
321    if (!dri2_surf) {
322       _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
323       return NULL;
324    }
325 
326    if (!dri2_init_surface(&dri2_surf->base, disp, EGL_WINDOW_BIT, conf,
327                           attrib_list, false, native_window))
328       goto cleanup_surf;
329 
330    config = dri2_get_dri_config(dri2_conf, EGL_WINDOW_BIT,
331                                 dri2_surf->base.GLColorspace);
332 
333    if (!config) {
334       _eglError(EGL_BAD_MATCH, "Unsupported surfacetype/colorspace configuration");
335       goto cleanup_surf;
336    }
337 
338    dri2_surf->base.Width = window->width;
339    dri2_surf->base.Height = window->height;
340 
341    visual_idx = dri2_wl_visual_idx_from_config(dri2_dpy, config);
342    assert(visual_idx != -1);
343 
344    if (dri2_dpy->wl_dmabuf || dri2_dpy->wl_drm) {
345       dri2_surf->format = dri2_wl_visuals[visual_idx].wl_drm_format;
346    } else {
347       assert(dri2_dpy->wl_shm);
348       dri2_surf->format = dri2_wl_visuals[visual_idx].wl_shm_format;
349    }
350 
351    dri2_surf->wl_queue = wl_display_create_queue(dri2_dpy->wl_dpy);
352    if (!dri2_surf->wl_queue) {
353       _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
354       goto cleanup_surf;
355    }
356 
357    if (dri2_dpy->wl_drm) {
358       dri2_surf->wl_drm_wrapper = wl_proxy_create_wrapper(dri2_dpy->wl_drm);
359       if (!dri2_surf->wl_drm_wrapper) {
360          _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
361          goto cleanup_queue;
362       }
363       wl_proxy_set_queue((struct wl_proxy *)dri2_surf->wl_drm_wrapper,
364                          dri2_surf->wl_queue);
365    }
366 
367    dri2_surf->wl_dpy_wrapper = wl_proxy_create_wrapper(dri2_dpy->wl_dpy);
368    if (!dri2_surf->wl_dpy_wrapper) {
369       _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
370       goto cleanup_drm;
371    }
372    wl_proxy_set_queue((struct wl_proxy *)dri2_surf->wl_dpy_wrapper,
373                       dri2_surf->wl_queue);
374 
375    dri2_surf->wl_surface_wrapper = get_wl_surface_proxy(window);
376    if (!dri2_surf->wl_surface_wrapper) {
377       _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
378       goto cleanup_dpy_wrapper;
379    }
380    wl_proxy_set_queue((struct wl_proxy *)dri2_surf->wl_surface_wrapper,
381                       dri2_surf->wl_queue);
382 
383    dri2_surf->wl_win = window;
384    dri2_surf->wl_win->driver_private = dri2_surf;
385    dri2_surf->wl_win->destroy_window_callback = destroy_window_callback;
386    if (dri2_dpy->flush)
387       dri2_surf->wl_win->resize_callback = resize_callback;
388 
389    if (!dri2_create_drawable(dri2_dpy, config, dri2_surf, dri2_surf))
390        goto cleanup_surf_wrapper;
391 
392    dri2_surf->base.SwapInterval = dri2_dpy->default_swap_interval;
393 
394    return &dri2_surf->base;
395 
396  cleanup_surf_wrapper:
397    wl_proxy_wrapper_destroy(dri2_surf->wl_surface_wrapper);
398  cleanup_dpy_wrapper:
399    wl_proxy_wrapper_destroy(dri2_surf->wl_dpy_wrapper);
400  cleanup_drm:
401    if (dri2_surf->wl_drm_wrapper)
402       wl_proxy_wrapper_destroy(dri2_surf->wl_drm_wrapper);
403  cleanup_queue:
404    wl_event_queue_destroy(dri2_surf->wl_queue);
405  cleanup_surf:
406    free(dri2_surf);
407 
408    return NULL;
409 }
410 
411 static _EGLSurface *
dri2_wl_create_pixmap_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)412 dri2_wl_create_pixmap_surface(_EGLDisplay *disp, _EGLConfig *conf,
413                               void *native_window, const EGLint *attrib_list)
414 {
415    /* From the EGL_EXT_platform_wayland spec, version 3:
416     *
417     *   It is not valid to call eglCreatePlatformPixmapSurfaceEXT with a <dpy>
418     *   that belongs to Wayland. Any such call fails and generates
419     *   EGL_BAD_PARAMETER.
420     */
421    _eglError(EGL_BAD_PARAMETER, "cannot create EGL pixmap surfaces on "
422              "Wayland");
423    return NULL;
424 }
425 
426 /**
427  * Called via eglDestroySurface(), drv->DestroySurface().
428  */
429 static EGLBoolean
dri2_wl_destroy_surface(_EGLDisplay * disp,_EGLSurface * surf)430 dri2_wl_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
431 {
432    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
433    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
434 
435    dri2_dpy->core->destroyDrawable(dri2_surf->dri_drawable);
436 
437    for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
438       if (dri2_surf->color_buffers[i].wl_buffer)
439          wl_buffer_destroy(dri2_surf->color_buffers[i].wl_buffer);
440       if (dri2_surf->color_buffers[i].dri_image)
441          dri2_dpy->image->destroyImage(dri2_surf->color_buffers[i].dri_image);
442       if (dri2_surf->color_buffers[i].linear_copy)
443          dri2_dpy->image->destroyImage(dri2_surf->color_buffers[i].linear_copy);
444       if (dri2_surf->color_buffers[i].data)
445          munmap(dri2_surf->color_buffers[i].data,
446                 dri2_surf->color_buffers[i].data_size);
447    }
448 
449    if (dri2_dpy->dri2)
450       dri2_egl_surface_free_local_buffers(dri2_surf);
451 
452    if (dri2_surf->throttle_callback)
453       wl_callback_destroy(dri2_surf->throttle_callback);
454 
455    if (dri2_surf->wl_win) {
456       dri2_surf->wl_win->driver_private = NULL;
457       dri2_surf->wl_win->resize_callback = NULL;
458       dri2_surf->wl_win->destroy_window_callback = NULL;
459    }
460 
461    wl_proxy_wrapper_destroy(dri2_surf->wl_surface_wrapper);
462    wl_proxy_wrapper_destroy(dri2_surf->wl_dpy_wrapper);
463    if (dri2_surf->wl_drm_wrapper)
464       wl_proxy_wrapper_destroy(dri2_surf->wl_drm_wrapper);
465    wl_event_queue_destroy(dri2_surf->wl_queue);
466 
467    dri2_fini_surface(surf);
468    free(surf);
469 
470    return EGL_TRUE;
471 }
472 
473 static void
dri2_wl_release_buffers(struct dri2_egl_surface * dri2_surf)474 dri2_wl_release_buffers(struct dri2_egl_surface *dri2_surf)
475 {
476    struct dri2_egl_display *dri2_dpy =
477       dri2_egl_display(dri2_surf->base.Resource.Display);
478 
479    for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
480       if (dri2_surf->color_buffers[i].wl_buffer) {
481          if (dri2_surf->color_buffers[i].locked) {
482             dri2_surf->color_buffers[i].wl_release = true;
483          } else {
484             wl_buffer_destroy(dri2_surf->color_buffers[i].wl_buffer);
485             dri2_surf->color_buffers[i].wl_buffer = NULL;
486          }
487       }
488       if (dri2_surf->color_buffers[i].dri_image)
489          dri2_dpy->image->destroyImage(dri2_surf->color_buffers[i].dri_image);
490       if (dri2_surf->color_buffers[i].linear_copy)
491          dri2_dpy->image->destroyImage(dri2_surf->color_buffers[i].linear_copy);
492       if (dri2_surf->color_buffers[i].data)
493          munmap(dri2_surf->color_buffers[i].data,
494                 dri2_surf->color_buffers[i].data_size);
495 
496       dri2_surf->color_buffers[i].dri_image = NULL;
497       dri2_surf->color_buffers[i].linear_copy = NULL;
498       dri2_surf->color_buffers[i].data = NULL;
499    }
500 
501    if (dri2_dpy->dri2)
502       dri2_egl_surface_free_local_buffers(dri2_surf);
503 }
504 
505 static int
get_back_bo(struct dri2_egl_surface * dri2_surf)506 get_back_bo(struct dri2_egl_surface *dri2_surf)
507 {
508    struct dri2_egl_display *dri2_dpy =
509       dri2_egl_display(dri2_surf->base.Resource.Display);
510    int use_flags;
511    int visual_idx;
512    unsigned int dri_image_format;
513    unsigned int linear_dri_image_format;
514    uint64_t *modifiers;
515    int num_modifiers;
516 
517    visual_idx = dri2_wl_visual_idx_from_fourcc(dri2_surf->format);
518    assert(visual_idx != -1);
519    dri_image_format = dri2_wl_visuals[visual_idx].dri_image_format;
520    linear_dri_image_format = dri_image_format;
521    modifiers = u_vector_tail(&dri2_dpy->wl_modifiers[visual_idx]);
522    num_modifiers = u_vector_length(&dri2_dpy->wl_modifiers[visual_idx]);
523 
524    if (num_modifiers == 1 && modifiers[0] == DRM_FORMAT_MOD_INVALID) {
525       /* For the purposes of this function, an INVALID modifier on its own
526        * means the modifiers aren't supported.
527        */
528       num_modifiers = 0;
529    }
530 
531    /* Substitute dri image format if server does not support original format */
532    if (!BITSET_TEST(dri2_dpy->formats, visual_idx))
533       linear_dri_image_format = dri2_wl_visuals[visual_idx].alt_dri_image_format;
534 
535    /* These asserts hold, as long as dri2_wl_visuals[] is self-consistent and
536     * the PRIME substitution logic in dri2_wl_add_configs_for_visuals() is free
537     * of bugs.
538     */
539    assert(linear_dri_image_format != __DRI_IMAGE_FORMAT_NONE);
540    assert(BITSET_TEST(dri2_dpy->formats,
541           dri2_wl_visual_idx_from_dri_image_format(linear_dri_image_format)));
542 
543    /* There might be a buffer release already queued that wasn't processed */
544    wl_display_dispatch_queue_pending(dri2_dpy->wl_dpy, dri2_surf->wl_queue);
545 
546    while (dri2_surf->back == NULL) {
547       for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
548          /* Get an unlocked buffer, preferably one with a dri_buffer
549           * already allocated. */
550          if (dri2_surf->color_buffers[i].locked)
551             continue;
552          if (dri2_surf->back == NULL)
553             dri2_surf->back = &dri2_surf->color_buffers[i];
554          else if (dri2_surf->back->dri_image == NULL)
555             dri2_surf->back = &dri2_surf->color_buffers[i];
556       }
557 
558       if (dri2_surf->back)
559          break;
560 
561       /* If we don't have a buffer, then block on the server to release one for
562        * us, and try again. wl_display_dispatch_queue will process any pending
563        * events, however not all servers flush on issuing a buffer release
564        * event. So, we spam the server with roundtrips as they always cause a
565        * client flush.
566        */
567       if (wl_display_roundtrip_queue(dri2_dpy->wl_dpy,
568                                      dri2_surf->wl_queue) < 0)
569           return -1;
570    }
571 
572    if (dri2_surf->back == NULL)
573       return -1;
574 
575    use_flags = __DRI_IMAGE_USE_SHARE | __DRI_IMAGE_USE_BACKBUFFER;
576 
577    if (dri2_surf->base.ProtectedContent) {
578       /* Protected buffers can't be read from another GPU */
579       if (dri2_dpy->is_different_gpu)
580          return -1;
581       use_flags |= __DRI_IMAGE_USE_PROTECTED;
582    }
583 
584    if (dri2_dpy->is_different_gpu &&
585        dri2_surf->back->linear_copy == NULL) {
586       /* The LINEAR modifier should be a perfect alias of the LINEAR use
587        * flag; try the new interface first before the old, then fall back. */
588       if (dri2_dpy->image->base.version >= 15 &&
589            dri2_dpy->image->createImageWithModifiers) {
590          uint64_t linear_mod = DRM_FORMAT_MOD_LINEAR;
591 
592          dri2_surf->back->linear_copy =
593             dri2_dpy->image->createImageWithModifiers(dri2_dpy->dri_screen,
594                                                       dri2_surf->base.Width,
595                                                       dri2_surf->base.Height,
596                                                       linear_dri_image_format,
597                                                       &linear_mod,
598                                                       1,
599                                                       NULL);
600       } else {
601          dri2_surf->back->linear_copy =
602             dri2_dpy->image->createImage(dri2_dpy->dri_screen,
603                                          dri2_surf->base.Width,
604                                          dri2_surf->base.Height,
605                                          linear_dri_image_format,
606                                          use_flags |
607                                          __DRI_IMAGE_USE_LINEAR,
608                                          NULL);
609       }
610       if (dri2_surf->back->linear_copy == NULL)
611           return -1;
612    }
613 
614    if (dri2_surf->back->dri_image == NULL) {
615       /* If our DRIImage implementation does not support
616        * createImageWithModifiers, then fall back to the old createImage,
617        * and hope it allocates an image which is acceptable to the winsys.
618         */
619       if (num_modifiers && dri2_dpy->image->base.version >= 15 &&
620           dri2_dpy->image->createImageWithModifiers) {
621          dri2_surf->back->dri_image =
622            dri2_dpy->image->createImageWithModifiers(dri2_dpy->dri_screen,
623                                                      dri2_surf->base.Width,
624                                                      dri2_surf->base.Height,
625                                                      dri_image_format,
626                                                      modifiers,
627                                                      num_modifiers,
628                                                      NULL);
629       } else {
630          dri2_surf->back->dri_image =
631             dri2_dpy->image->createImage(dri2_dpy->dri_screen,
632                                          dri2_surf->base.Width,
633                                          dri2_surf->base.Height,
634                                          dri_image_format,
635                                          dri2_dpy->is_different_gpu ?
636                                               0 : use_flags,
637                                          NULL);
638       }
639 
640       dri2_surf->back->age = 0;
641    }
642    if (dri2_surf->back->dri_image == NULL)
643       return -1;
644 
645    dri2_surf->back->locked = true;
646 
647    return 0;
648 }
649 
650 
651 static void
back_bo_to_dri_buffer(struct dri2_egl_surface * dri2_surf,__DRIbuffer * buffer)652 back_bo_to_dri_buffer(struct dri2_egl_surface *dri2_surf, __DRIbuffer *buffer)
653 {
654    struct dri2_egl_display *dri2_dpy =
655       dri2_egl_display(dri2_surf->base.Resource.Display);
656    __DRIimage *image;
657    int name, pitch;
658 
659    image = dri2_surf->back->dri_image;
660 
661    dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_NAME, &name);
662    dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_STRIDE, &pitch);
663 
664    buffer->attachment = __DRI_BUFFER_BACK_LEFT;
665    buffer->name = name;
666    buffer->pitch = pitch;
667    buffer->cpp = 4;
668    buffer->flags = 0;
669 }
670 
671 static int
update_buffers(struct dri2_egl_surface * dri2_surf)672 update_buffers(struct dri2_egl_surface *dri2_surf)
673 {
674    struct dri2_egl_display *dri2_dpy =
675       dri2_egl_display(dri2_surf->base.Resource.Display);
676 
677    if (dri2_surf->base.Width != dri2_surf->wl_win->width ||
678        dri2_surf->base.Height != dri2_surf->wl_win->height) {
679 
680       dri2_surf->base.Width  = dri2_surf->wl_win->width;
681       dri2_surf->base.Height = dri2_surf->wl_win->height;
682       dri2_surf->dx = dri2_surf->wl_win->dx;
683       dri2_surf->dy = dri2_surf->wl_win->dy;
684    }
685 
686    if (dri2_surf->base.Width != dri2_surf->wl_win->attached_width ||
687        dri2_surf->base.Height != dri2_surf->wl_win->attached_height) {
688       dri2_wl_release_buffers(dri2_surf);
689    }
690 
691    if (get_back_bo(dri2_surf) < 0) {
692       _eglError(EGL_BAD_ALLOC, "failed to allocate color buffer");
693       return -1;
694    }
695 
696    /* If we have an extra unlocked buffer at this point, we had to do triple
697     * buffering for a while, but now can go back to just double buffering.
698     * That means we can free any unlocked buffer now. */
699    for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
700       if (!dri2_surf->color_buffers[i].locked &&
701           dri2_surf->color_buffers[i].wl_buffer) {
702          wl_buffer_destroy(dri2_surf->color_buffers[i].wl_buffer);
703          dri2_dpy->image->destroyImage(dri2_surf->color_buffers[i].dri_image);
704          if (dri2_dpy->is_different_gpu)
705             dri2_dpy->image->destroyImage(dri2_surf->color_buffers[i].linear_copy);
706          dri2_surf->color_buffers[i].wl_buffer = NULL;
707          dri2_surf->color_buffers[i].dri_image = NULL;
708          dri2_surf->color_buffers[i].linear_copy = NULL;
709       }
710    }
711 
712    return 0;
713 }
714 
715 static int
update_buffers_if_needed(struct dri2_egl_surface * dri2_surf)716 update_buffers_if_needed(struct dri2_egl_surface *dri2_surf)
717 {
718    if (dri2_surf->back != NULL)
719       return 0;
720 
721    return update_buffers(dri2_surf);
722 }
723 
724 static __DRIbuffer *
dri2_wl_get_buffers_with_format(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)725 dri2_wl_get_buffers_with_format(__DRIdrawable * driDrawable,
726                                 int *width, int *height,
727                                 unsigned int *attachments, int count,
728                                 int *out_count, void *loaderPrivate)
729 {
730    struct dri2_egl_surface *dri2_surf = loaderPrivate;
731    int i, j;
732 
733    if (update_buffers(dri2_surf) < 0)
734       return NULL;
735 
736    for (i = 0, j = 0; i < 2 * count; i += 2, j++) {
737       __DRIbuffer *local;
738 
739       switch (attachments[i]) {
740       case __DRI_BUFFER_BACK_LEFT:
741          back_bo_to_dri_buffer(dri2_surf, &dri2_surf->buffers[j]);
742          break;
743       default:
744          local = dri2_egl_surface_alloc_local_buffer(dri2_surf, attachments[i],
745                                                      attachments[i + 1]);
746 
747          if (!local) {
748             _eglError(EGL_BAD_ALLOC, "failed to allocate local buffer");
749             return NULL;
750          }
751          dri2_surf->buffers[j] = *local;
752          break;
753       }
754    }
755 
756    *out_count = j;
757    if (j == 0)
758       return NULL;
759 
760    *width = dri2_surf->base.Width;
761    *height = dri2_surf->base.Height;
762 
763    return dri2_surf->buffers;
764 }
765 
766 static __DRIbuffer *
dri2_wl_get_buffers(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)767 dri2_wl_get_buffers(__DRIdrawable * driDrawable,
768                     int *width, int *height,
769                     unsigned int *attachments, int count,
770                     int *out_count, void *loaderPrivate)
771 {
772    struct dri2_egl_surface *dri2_surf = loaderPrivate;
773    unsigned int *attachments_with_format;
774    __DRIbuffer *buffer;
775    int visual_idx = dri2_wl_visual_idx_from_fourcc(dri2_surf->format);
776 
777    if (visual_idx == -1)
778       return NULL;
779 
780    attachments_with_format = calloc(count, 2 * sizeof(unsigned int));
781    if (!attachments_with_format) {
782       *out_count = 0;
783       return NULL;
784    }
785 
786    for (int i = 0; i < count; ++i) {
787       attachments_with_format[2*i] = attachments[i];
788       attachments_with_format[2*i + 1] = dri2_wl_visuals[visual_idx].bpp;
789    }
790 
791    buffer =
792       dri2_wl_get_buffers_with_format(driDrawable,
793                                       width, height,
794                                       attachments_with_format, count,
795                                       out_count, loaderPrivate);
796 
797    free(attachments_with_format);
798 
799    return buffer;
800 }
801 
802 static int
image_get_buffers(__DRIdrawable * driDrawable,unsigned int format,uint32_t * stamp,void * loaderPrivate,uint32_t buffer_mask,struct __DRIimageList * buffers)803 image_get_buffers(__DRIdrawable *driDrawable,
804                   unsigned int format,
805                   uint32_t *stamp,
806                   void *loaderPrivate,
807                   uint32_t buffer_mask,
808                   struct __DRIimageList *buffers)
809 {
810    struct dri2_egl_surface *dri2_surf = loaderPrivate;
811 
812    if (update_buffers(dri2_surf) < 0)
813       return 0;
814 
815    buffers->image_mask = __DRI_IMAGE_BUFFER_BACK;
816    buffers->back = dri2_surf->back->dri_image;
817 
818    return 1;
819 }
820 
821 static void
dri2_wl_flush_front_buffer(__DRIdrawable * driDrawable,void * loaderPrivate)822 dri2_wl_flush_front_buffer(__DRIdrawable * driDrawable, void *loaderPrivate)
823 {
824    (void) driDrawable;
825    (void) loaderPrivate;
826 }
827 
828 static unsigned
dri2_wl_get_capability(void * loaderPrivate,enum dri_loader_cap cap)829 dri2_wl_get_capability(void *loaderPrivate, enum dri_loader_cap cap)
830 {
831    switch (cap) {
832    case DRI_LOADER_CAP_FP16:
833       return 1;
834    default:
835       return 0;
836    }
837 }
838 
839 static const __DRIdri2LoaderExtension dri2_loader_extension = {
840    .base = { __DRI_DRI2_LOADER, 4 },
841 
842    .getBuffers           = dri2_wl_get_buffers,
843    .flushFrontBuffer     = dri2_wl_flush_front_buffer,
844    .getBuffersWithFormat = dri2_wl_get_buffers_with_format,
845    .getCapability        = dri2_wl_get_capability,
846 };
847 
848 static const __DRIimageLoaderExtension image_loader_extension = {
849    .base = { __DRI_IMAGE_LOADER, 2 },
850 
851    .getBuffers          = image_get_buffers,
852    .flushFrontBuffer    = dri2_wl_flush_front_buffer,
853    .getCapability       = dri2_wl_get_capability,
854 };
855 
856 static void
wayland_throttle_callback(void * data,struct wl_callback * callback,uint32_t time)857 wayland_throttle_callback(void *data,
858                           struct wl_callback *callback,
859                           uint32_t time)
860 {
861    struct dri2_egl_surface *dri2_surf = data;
862 
863    dri2_surf->throttle_callback = NULL;
864    wl_callback_destroy(callback);
865 }
866 
867 static const struct wl_callback_listener throttle_listener = {
868    .done = wayland_throttle_callback
869 };
870 
871 static EGLBoolean
get_fourcc(struct dri2_egl_display * dri2_dpy,__DRIimage * image,int * fourcc)872 get_fourcc(struct dri2_egl_display *dri2_dpy,
873            __DRIimage *image, int *fourcc)
874 {
875    EGLBoolean query;
876    int dri_format;
877    int visual_idx;
878 
879    query = dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_FOURCC,
880                                        fourcc);
881    if (query)
882       return true;
883 
884    query = dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_FORMAT,
885                                        &dri_format);
886    if (!query)
887       return false;
888 
889    visual_idx = dri2_wl_visual_idx_from_dri_image_format(dri_format);
890    if (visual_idx == -1)
891       return false;
892 
893    *fourcc = dri2_wl_visuals[visual_idx].wl_drm_format;
894    return true;
895 }
896 
897 static struct wl_buffer *
create_wl_buffer(struct dri2_egl_display * dri2_dpy,struct dri2_egl_surface * dri2_surf,__DRIimage * image)898 create_wl_buffer(struct dri2_egl_display *dri2_dpy,
899                  struct dri2_egl_surface *dri2_surf,
900                  __DRIimage *image)
901 {
902    struct wl_buffer *ret;
903    EGLBoolean query;
904    int width, height, fourcc, num_planes;
905    uint64_t modifier = DRM_FORMAT_MOD_INVALID;
906 
907    query = dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_WIDTH, &width);
908    query &= dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_HEIGHT,
909                                         &height);
910    query &= get_fourcc(dri2_dpy, image, &fourcc);
911    if (!query)
912       return NULL;
913 
914    query = dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_NUM_PLANES,
915                                        &num_planes);
916    if (!query)
917       num_planes = 1;
918 
919    if (dri2_dpy->image->base.version >= 15) {
920       int mod_hi, mod_lo;
921 
922       query = dri2_dpy->image->queryImage(image,
923                                           __DRI_IMAGE_ATTRIB_MODIFIER_UPPER,
924                                           &mod_hi);
925       query &= dri2_dpy->image->queryImage(image,
926                                            __DRI_IMAGE_ATTRIB_MODIFIER_LOWER,
927                                            &mod_lo);
928       if (query) {
929          modifier = combine_u32_into_u64(mod_hi, mod_lo);
930       }
931    }
932 
933    bool supported_modifier = false;
934    bool mod_invalid_supported = false;
935    int visual_idx = dri2_wl_visual_idx_from_fourcc(fourcc);
936    assert(visual_idx != -1);
937 
938    uint64_t *mod;
939    u_vector_foreach(mod, &dri2_dpy->wl_modifiers[visual_idx]) {
940       if (*mod == DRM_FORMAT_MOD_INVALID) {
941          mod_invalid_supported = true;
942       }
943       if (*mod == modifier) {
944          supported_modifier = true;
945          break;
946       }
947    }
948    if (!supported_modifier && mod_invalid_supported) {
949       /* If the server has advertised DRM_FORMAT_MOD_INVALID then we trust
950        * that the client has allocated the buffer with the right implicit
951        * modifier for the format, even though it's allocated a buffer the
952        * server hasn't explicitly claimed to support. */
953       modifier = DRM_FORMAT_MOD_INVALID;
954       supported_modifier = true;
955    }
956 
957    if (dri2_dpy->wl_dmabuf && supported_modifier) {
958       struct zwp_linux_buffer_params_v1 *params;
959       int i;
960 
961       /* We don't need a wrapper for wl_dmabuf objects, because we have to
962        * create the intermediate params object; we can set the queue on this,
963        * and the wl_buffer inherits it race-free. */
964       params = zwp_linux_dmabuf_v1_create_params(dri2_dpy->wl_dmabuf);
965       if (dri2_surf)
966          wl_proxy_set_queue((struct wl_proxy *) params, dri2_surf->wl_queue);
967 
968       for (i = 0; i < num_planes; i++) {
969          __DRIimage *p_image;
970          int stride, offset;
971          int fd = -1;
972 
973          p_image = dri2_dpy->image->fromPlanar(image, i, NULL);
974          if (!p_image) {
975             assert(i == 0);
976             p_image = image;
977          }
978 
979          query = dri2_dpy->image->queryImage(p_image,
980                                              __DRI_IMAGE_ATTRIB_FD,
981                                              &fd);
982          query &= dri2_dpy->image->queryImage(p_image,
983                                               __DRI_IMAGE_ATTRIB_STRIDE,
984                                               &stride);
985          query &= dri2_dpy->image->queryImage(p_image,
986                                               __DRI_IMAGE_ATTRIB_OFFSET,
987                                               &offset);
988          if (image != p_image)
989             dri2_dpy->image->destroyImage(p_image);
990 
991          if (!query) {
992             if (fd >= 0)
993                close(fd);
994             zwp_linux_buffer_params_v1_destroy(params);
995             return NULL;
996          }
997 
998          zwp_linux_buffer_params_v1_add(params, fd, i, offset, stride,
999                                         modifier >> 32, modifier & 0xffffffff);
1000          close(fd);
1001       }
1002 
1003       ret = zwp_linux_buffer_params_v1_create_immed(params, width, height,
1004                                                     fourcc, 0);
1005       zwp_linux_buffer_params_v1_destroy(params);
1006    } else if (dri2_dpy->capabilities & WL_DRM_CAPABILITY_PRIME) {
1007       struct wl_drm *wl_drm =
1008          dri2_surf ? dri2_surf->wl_drm_wrapper : dri2_dpy->wl_drm;
1009       int fd, stride;
1010 
1011       if (num_planes > 1)
1012          return NULL;
1013 
1014       dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_FD, &fd);
1015       dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_STRIDE, &stride);
1016       ret = wl_drm_create_prime_buffer(wl_drm, fd, width, height, fourcc, 0,
1017                                        stride, 0, 0, 0, 0);
1018       close(fd);
1019    } else {
1020       struct wl_drm *wl_drm =
1021          dri2_surf ? dri2_surf->wl_drm_wrapper : dri2_dpy->wl_drm;
1022       int name, stride;
1023 
1024       if (num_planes > 1)
1025          return NULL;
1026 
1027       dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_NAME, &name);
1028       dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_STRIDE, &stride);
1029       ret = wl_drm_create_buffer(wl_drm, name, width, height, stride, fourcc);
1030    }
1031 
1032    return ret;
1033 }
1034 
1035 static EGLBoolean
try_damage_buffer(struct dri2_egl_surface * dri2_surf,const EGLint * rects,EGLint n_rects)1036 try_damage_buffer(struct dri2_egl_surface *dri2_surf,
1037                   const EGLint *rects,
1038                   EGLint n_rects)
1039 {
1040    if (wl_proxy_get_version((struct wl_proxy *) dri2_surf->wl_surface_wrapper)
1041        < WL_SURFACE_DAMAGE_BUFFER_SINCE_VERSION)
1042       return EGL_FALSE;
1043 
1044    for (int i = 0; i < n_rects; i++) {
1045       const int *rect = &rects[i * 4];
1046 
1047       wl_surface_damage_buffer(dri2_surf->wl_surface_wrapper,
1048                                rect[0],
1049                                dri2_surf->base.Height - rect[1] - rect[3],
1050                                rect[2], rect[3]);
1051    }
1052    return EGL_TRUE;
1053 }
1054 
1055 /**
1056  * Called via eglSwapBuffers(), drv->SwapBuffers().
1057  */
1058 static EGLBoolean
dri2_wl_swap_buffers_with_damage(_EGLDisplay * disp,_EGLSurface * draw,const EGLint * rects,EGLint n_rects)1059 dri2_wl_swap_buffers_with_damage(_EGLDisplay *disp,
1060                                  _EGLSurface *draw,
1061                                  const EGLint *rects,
1062                                  EGLint n_rects)
1063 {
1064    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1065    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1066 
1067    while (dri2_surf->throttle_callback != NULL)
1068       if (wl_display_dispatch_queue(dri2_dpy->wl_dpy,
1069                                     dri2_surf->wl_queue) == -1)
1070          return -1;
1071 
1072    for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++)
1073       if (dri2_surf->color_buffers[i].age > 0)
1074          dri2_surf->color_buffers[i].age++;
1075 
1076    /* Make sure we have a back buffer in case we're swapping without ever
1077     * rendering. */
1078    if (update_buffers_if_needed(dri2_surf) < 0)
1079       return _eglError(EGL_BAD_ALLOC, "dri2_swap_buffers");
1080 
1081    if (draw->SwapInterval > 0) {
1082       dri2_surf->throttle_callback =
1083          wl_surface_frame(dri2_surf->wl_surface_wrapper);
1084       wl_callback_add_listener(dri2_surf->throttle_callback,
1085                                &throttle_listener, dri2_surf);
1086    }
1087 
1088    dri2_surf->back->age = 1;
1089    dri2_surf->current = dri2_surf->back;
1090    dri2_surf->back = NULL;
1091 
1092    if (!dri2_surf->current->wl_buffer) {
1093       __DRIimage *image;
1094 
1095       if (dri2_dpy->is_different_gpu)
1096          image = dri2_surf->current->linear_copy;
1097       else
1098          image = dri2_surf->current->dri_image;
1099 
1100       dri2_surf->current->wl_buffer =
1101          create_wl_buffer(dri2_dpy, dri2_surf, image);
1102 
1103       dri2_surf->current->wl_release = false;
1104 
1105       wl_buffer_add_listener(dri2_surf->current->wl_buffer,
1106                              &wl_buffer_listener, dri2_surf);
1107    }
1108 
1109    wl_surface_attach(dri2_surf->wl_surface_wrapper,
1110                      dri2_surf->current->wl_buffer,
1111                      dri2_surf->dx, dri2_surf->dy);
1112 
1113    dri2_surf->wl_win->attached_width  = dri2_surf->base.Width;
1114    dri2_surf->wl_win->attached_height = dri2_surf->base.Height;
1115    /* reset resize growing parameters */
1116    dri2_surf->dx = 0;
1117    dri2_surf->dy = 0;
1118 
1119    /* If the compositor doesn't support damage_buffer, we deliberately
1120     * ignore the damage region and post maximum damage, due to
1121     * https://bugs.freedesktop.org/78190 */
1122    if (!n_rects || !try_damage_buffer(dri2_surf, rects, n_rects))
1123       wl_surface_damage(dri2_surf->wl_surface_wrapper,
1124                         0, 0, INT32_MAX, INT32_MAX);
1125 
1126    if (dri2_dpy->is_different_gpu) {
1127       _EGLContext *ctx = _eglGetCurrentContext();
1128       struct dri2_egl_context *dri2_ctx = dri2_egl_context(ctx);
1129       dri2_dpy->image->blitImage(dri2_ctx->dri_context,
1130                                  dri2_surf->current->linear_copy,
1131                                  dri2_surf->current->dri_image,
1132                                  0, 0, dri2_surf->base.Width,
1133                                  dri2_surf->base.Height,
1134                                  0, 0, dri2_surf->base.Width,
1135                                  dri2_surf->base.Height, 0);
1136    }
1137 
1138    dri2_flush_drawable_for_swapbuffers(disp, draw);
1139    dri2_dpy->flush->invalidate(dri2_surf->dri_drawable);
1140 
1141    wl_surface_commit(dri2_surf->wl_surface_wrapper);
1142 
1143    /* If we're not waiting for a frame callback then we'll at least throttle
1144     * to a sync callback so that we always give a chance for the compositor to
1145     * handle the commit and send a release event before checking for a free
1146     * buffer */
1147    if (dri2_surf->throttle_callback == NULL) {
1148       dri2_surf->throttle_callback = wl_display_sync(dri2_surf->wl_dpy_wrapper);
1149       wl_callback_add_listener(dri2_surf->throttle_callback,
1150                                &throttle_listener, dri2_surf);
1151    }
1152 
1153    wl_display_flush(dri2_dpy->wl_dpy);
1154 
1155    return EGL_TRUE;
1156 }
1157 
1158 static EGLint
dri2_wl_query_buffer_age(_EGLDisplay * disp,_EGLSurface * surface)1159 dri2_wl_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surface)
1160 {
1161    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surface);
1162 
1163    if (update_buffers_if_needed(dri2_surf) < 0) {
1164       _eglError(EGL_BAD_ALLOC, "dri2_query_buffer_age");
1165       return -1;
1166    }
1167 
1168    return dri2_surf->back->age;
1169 }
1170 
1171 static EGLBoolean
dri2_wl_swap_buffers(_EGLDisplay * disp,_EGLSurface * draw)1172 dri2_wl_swap_buffers(_EGLDisplay *disp, _EGLSurface *draw)
1173 {
1174    return dri2_wl_swap_buffers_with_damage(disp, draw, NULL, 0);
1175 }
1176 
1177 static struct wl_buffer *
dri2_wl_create_wayland_buffer_from_image(_EGLDisplay * disp,_EGLImage * img)1178 dri2_wl_create_wayland_buffer_from_image(_EGLDisplay *disp, _EGLImage *img)
1179 {
1180    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1181    struct dri2_egl_image *dri2_img = dri2_egl_image(img);
1182    __DRIimage *image = dri2_img->dri_image;
1183    struct wl_buffer *buffer;
1184    int format, visual_idx;
1185 
1186    /* Check the upstream display supports this buffer's format. */
1187    dri2_dpy->image->queryImage(image, __DRI_IMAGE_ATTRIB_FORMAT, &format);
1188    visual_idx = dri2_wl_visual_idx_from_dri_image_format(format);
1189    if (visual_idx == -1)
1190       goto bad_format;
1191 
1192    if (!BITSET_TEST(dri2_dpy->formats, visual_idx))
1193       goto bad_format;
1194 
1195    buffer = create_wl_buffer(dri2_dpy, NULL, image);
1196 
1197    /* The buffer object will have been created with our internal event queue
1198     * because it is using wl_dmabuf/wl_drm as a proxy factory. We want the
1199     * buffer to be used by the application so we'll reset it to the display's
1200     * default event queue. This isn't actually racy, as the only event the
1201     * buffer can get is a buffer release, which doesn't happen with an explicit
1202     * attach. */
1203    if (buffer)
1204       wl_proxy_set_queue((struct wl_proxy *) buffer, NULL);
1205 
1206    return buffer;
1207 
1208 bad_format:
1209    _eglError(EGL_BAD_MATCH, "unsupported image format");
1210    return NULL;
1211 }
1212 
1213 static int
dri2_wl_authenticate(_EGLDisplay * disp,uint32_t id)1214 dri2_wl_authenticate(_EGLDisplay *disp, uint32_t id)
1215 {
1216    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1217    int ret = 0;
1218 
1219    if (dri2_dpy->is_render_node) {
1220       _eglLog(_EGL_WARNING, "wayland-egl: client asks server to "
1221                             "authenticate for render-nodes");
1222       return 0;
1223    }
1224    dri2_dpy->authenticated = false;
1225 
1226    wl_drm_authenticate(dri2_dpy->wl_drm, id);
1227    if (roundtrip(dri2_dpy) < 0)
1228       ret = -1;
1229 
1230    if (!dri2_dpy->authenticated)
1231       ret = -1;
1232 
1233    /* reset authenticated */
1234    dri2_dpy->authenticated = true;
1235 
1236    return ret;
1237 }
1238 
1239 static void
drm_handle_device(void * data,struct wl_drm * drm,const char * device)1240 drm_handle_device(void *data, struct wl_drm *drm, const char *device)
1241 {
1242    struct dri2_egl_display *dri2_dpy = data;
1243    drm_magic_t magic;
1244 
1245    dri2_dpy->device_name = strdup(device);
1246    if (!dri2_dpy->device_name)
1247       return;
1248 
1249    dri2_dpy->fd = loader_open_device(dri2_dpy->device_name);
1250    if (dri2_dpy->fd == -1) {
1251       _eglLog(_EGL_WARNING, "wayland-egl: could not open %s (%s)",
1252               dri2_dpy->device_name, strerror(errno));
1253       free(dri2_dpy->device_name);
1254       dri2_dpy->device_name = NULL;
1255       return;
1256    }
1257 
1258    if (drmGetNodeTypeFromFd(dri2_dpy->fd) == DRM_NODE_RENDER) {
1259       dri2_dpy->authenticated = true;
1260    } else {
1261       if (drmGetMagic(dri2_dpy->fd, &magic)) {
1262          close(dri2_dpy->fd);
1263          dri2_dpy->fd = -1;
1264          free(dri2_dpy->device_name);
1265          dri2_dpy->device_name = NULL;
1266          _eglLog(_EGL_WARNING, "wayland-egl: drmGetMagic failed");
1267          return;
1268       }
1269       wl_drm_authenticate(dri2_dpy->wl_drm, magic);
1270    }
1271 }
1272 
1273 static void
drm_handle_format(void * data,struct wl_drm * drm,uint32_t format)1274 drm_handle_format(void *data, struct wl_drm *drm, uint32_t format)
1275 {
1276    struct dri2_egl_display *dri2_dpy = data;
1277    int visual_idx = dri2_wl_visual_idx_from_fourcc(format);
1278 
1279    if (visual_idx == -1)
1280       return;
1281 
1282    BITSET_SET(dri2_dpy->formats, visual_idx);
1283 }
1284 
1285 static void
drm_handle_capabilities(void * data,struct wl_drm * drm,uint32_t value)1286 drm_handle_capabilities(void *data, struct wl_drm *drm, uint32_t value)
1287 {
1288    struct dri2_egl_display *dri2_dpy = data;
1289 
1290    dri2_dpy->capabilities = value;
1291 }
1292 
1293 static void
drm_handle_authenticated(void * data,struct wl_drm * drm)1294 drm_handle_authenticated(void *data, struct wl_drm *drm)
1295 {
1296    struct dri2_egl_display *dri2_dpy = data;
1297 
1298    dri2_dpy->authenticated = true;
1299 }
1300 
1301 static const struct wl_drm_listener drm_listener = {
1302    .device = drm_handle_device,
1303    .format = drm_handle_format,
1304    .authenticated = drm_handle_authenticated,
1305    .capabilities = drm_handle_capabilities
1306 };
1307 
1308 static void
dmabuf_ignore_format(void * data,struct zwp_linux_dmabuf_v1 * dmabuf,uint32_t format)1309 dmabuf_ignore_format(void *data, struct zwp_linux_dmabuf_v1 *dmabuf,
1310                      uint32_t format)
1311 {
1312    /* formats are implicitly advertised by the 'modifier' event, so ignore */
1313 }
1314 
1315 static void
dmabuf_handle_modifier(void * data,struct zwp_linux_dmabuf_v1 * dmabuf,uint32_t format,uint32_t modifier_hi,uint32_t modifier_lo)1316 dmabuf_handle_modifier(void *data, struct zwp_linux_dmabuf_v1 *dmabuf,
1317                        uint32_t format, uint32_t modifier_hi,
1318                        uint32_t modifier_lo)
1319 {
1320    struct dri2_egl_display *dri2_dpy = data;
1321    int visual_idx = dri2_wl_visual_idx_from_fourcc(format);
1322    uint64_t *mod;
1323 
1324    if (visual_idx == -1)
1325       return;
1326 
1327    BITSET_SET(dri2_dpy->formats, visual_idx);
1328 
1329    mod = u_vector_add(&dri2_dpy->wl_modifiers[visual_idx]);
1330    *mod = combine_u32_into_u64(modifier_hi, modifier_lo);
1331 }
1332 
1333 static const struct zwp_linux_dmabuf_v1_listener dmabuf_listener = {
1334    .format = dmabuf_ignore_format,
1335    .modifier = dmabuf_handle_modifier,
1336 };
1337 
1338 static void
registry_handle_global_drm(void * data,struct wl_registry * registry,uint32_t name,const char * interface,uint32_t version)1339 registry_handle_global_drm(void *data, struct wl_registry *registry,
1340                            uint32_t name, const char *interface,
1341                            uint32_t version)
1342 {
1343    struct dri2_egl_display *dri2_dpy = data;
1344 
1345    if (strcmp(interface, "wl_drm") == 0) {
1346       dri2_dpy->wl_drm =
1347          wl_registry_bind(registry, name, &wl_drm_interface, MIN2(version, 2));
1348       wl_drm_add_listener(dri2_dpy->wl_drm, &drm_listener, dri2_dpy);
1349    } else if (strcmp(interface, "zwp_linux_dmabuf_v1") == 0 && version >= 3) {
1350       dri2_dpy->wl_dmabuf =
1351          wl_registry_bind(registry, name, &zwp_linux_dmabuf_v1_interface,
1352                           MIN2(version, 3));
1353       zwp_linux_dmabuf_v1_add_listener(dri2_dpy->wl_dmabuf, &dmabuf_listener,
1354                                        dri2_dpy);
1355    }
1356 }
1357 
1358 static void
registry_handle_global_remove(void * data,struct wl_registry * registry,uint32_t name)1359 registry_handle_global_remove(void *data, struct wl_registry *registry,
1360                               uint32_t name)
1361 {
1362 }
1363 
1364 static const struct wl_registry_listener registry_listener_drm = {
1365    .global = registry_handle_global_drm,
1366    .global_remove = registry_handle_global_remove
1367 };
1368 
1369 static void
dri2_wl_setup_swap_interval(_EGLDisplay * disp)1370 dri2_wl_setup_swap_interval(_EGLDisplay *disp)
1371 {
1372    /* We can't use values greater than 1 on Wayland because we are using the
1373     * frame callback to synchronise the frame and the only way we be sure to
1374     * get a frame callback is to attach a new buffer. Therefore we can't just
1375     * sit drawing nothing to wait until the next ‘n’ frame callbacks */
1376 
1377    dri2_setup_swap_interval(disp, 1);
1378 }
1379 
1380 static const struct dri2_egl_display_vtbl dri2_wl_display_vtbl = {
1381    .authenticate = dri2_wl_authenticate,
1382    .create_window_surface = dri2_wl_create_window_surface,
1383    .create_pixmap_surface = dri2_wl_create_pixmap_surface,
1384    .destroy_surface = dri2_wl_destroy_surface,
1385    .create_image = dri2_create_image_khr,
1386    .swap_buffers = dri2_wl_swap_buffers,
1387    .swap_buffers_with_damage = dri2_wl_swap_buffers_with_damage,
1388    .query_buffer_age = dri2_wl_query_buffer_age,
1389    .create_wayland_buffer_from_image = dri2_wl_create_wayland_buffer_from_image,
1390    .get_dri_drawable = dri2_surface_get_dri_drawable,
1391 };
1392 
1393 static const __DRIextension *dri2_loader_extensions[] = {
1394    &dri2_loader_extension.base,
1395    &image_loader_extension.base,
1396    &image_lookup_extension.base,
1397    &use_invalidate.base,
1398    NULL,
1399 };
1400 
1401 static const __DRIextension *image_loader_extensions[] = {
1402    &image_loader_extension.base,
1403    &image_lookup_extension.base,
1404    &use_invalidate.base,
1405    NULL,
1406 };
1407 
1408 static EGLBoolean
dri2_wl_add_configs_for_visuals(_EGLDisplay * disp)1409 dri2_wl_add_configs_for_visuals(_EGLDisplay *disp)
1410 {
1411    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1412    unsigned int format_count[ARRAY_SIZE(dri2_wl_visuals)] = { 0 };
1413    unsigned int count = 0;
1414    bool assigned;
1415 
1416    for (unsigned i = 0; dri2_dpy->driver_configs[i]; i++) {
1417       assigned = false;
1418 
1419       for (unsigned j = 0; j < ARRAY_SIZE(dri2_wl_visuals); j++) {
1420          struct dri2_egl_config *dri2_conf;
1421 
1422          if (!BITSET_TEST(dri2_dpy->formats, j))
1423             continue;
1424 
1425          dri2_conf = dri2_add_config(disp, dri2_dpy->driver_configs[i],
1426                count + 1, EGL_WINDOW_BIT, NULL, dri2_wl_visuals[j].rgba_shifts, dri2_wl_visuals[j].rgba_sizes);
1427          if (dri2_conf) {
1428             if (dri2_conf->base.ConfigID == count + 1)
1429                count++;
1430             format_count[j]++;
1431             assigned = true;
1432          }
1433       }
1434 
1435       if (!assigned && dri2_dpy->is_different_gpu) {
1436          struct dri2_egl_config *dri2_conf;
1437          int alt_dri_image_format, c, s;
1438 
1439          /* No match for config. Try if we can blitImage convert to a visual */
1440          c = dri2_wl_visual_idx_from_config(dri2_dpy,
1441                                             dri2_dpy->driver_configs[i]);
1442 
1443          if (c == -1)
1444             continue;
1445 
1446          /* Find optimal target visual for blitImage conversion, if any. */
1447          alt_dri_image_format = dri2_wl_visuals[c].alt_dri_image_format;
1448          s = dri2_wl_visual_idx_from_dri_image_format(alt_dri_image_format);
1449 
1450          if (s == -1 || !BITSET_TEST(dri2_dpy->formats, s))
1451             continue;
1452 
1453          /* Visual s works for the Wayland server, and c can be converted into s
1454           * by our client gpu during PRIME blitImage conversion to a linear
1455           * wl_buffer, so add visual c as supported by the client renderer.
1456           */
1457          dri2_conf = dri2_add_config(disp, dri2_dpy->driver_configs[i],
1458                                      count + 1, EGL_WINDOW_BIT, NULL,
1459                                      dri2_wl_visuals[c].rgba_shifts,
1460                                      dri2_wl_visuals[c].rgba_sizes);
1461          if (dri2_conf) {
1462             if (dri2_conf->base.ConfigID == count + 1)
1463                count++;
1464             format_count[c]++;
1465             if (format_count[c] == 1)
1466                _eglLog(_EGL_DEBUG, "Client format %s to server format %s via "
1467                        "PRIME blitImage.", dri2_wl_visuals[c].format_name,
1468                        dri2_wl_visuals[s].format_name);
1469          }
1470       }
1471    }
1472 
1473    for (unsigned i = 0; i < ARRAY_SIZE(format_count); i++) {
1474       if (!format_count[i]) {
1475          _eglLog(_EGL_DEBUG, "No DRI config supports native format %s",
1476                  dri2_wl_visuals[i].format_name);
1477       }
1478    }
1479 
1480    return (count != 0);
1481 }
1482 
1483 static EGLBoolean
dri2_initialize_wayland_drm(_EGLDisplay * disp)1484 dri2_initialize_wayland_drm(_EGLDisplay *disp)
1485 {
1486    _EGLDevice *dev;
1487    struct dri2_egl_display *dri2_dpy;
1488 
1489    dri2_dpy = calloc(1, sizeof *dri2_dpy);
1490    if (!dri2_dpy)
1491       return _eglError(EGL_BAD_ALLOC, "eglInitialize");
1492 
1493    dri2_dpy->fd = -1;
1494    disp->DriverData = (void *) dri2_dpy;
1495    if (disp->PlatformDisplay == NULL) {
1496       dri2_dpy->wl_dpy = wl_display_connect(NULL);
1497       if (dri2_dpy->wl_dpy == NULL)
1498          goto cleanup;
1499       dri2_dpy->own_device = true;
1500    } else {
1501       dri2_dpy->wl_dpy = disp->PlatformDisplay;
1502    }
1503 
1504    dri2_dpy->wl_modifiers =
1505       calloc(ARRAY_SIZE(dri2_wl_visuals), sizeof(*dri2_dpy->wl_modifiers));
1506    if (!dri2_dpy->wl_modifiers)
1507       goto cleanup;
1508    for (int i = 0; i < ARRAY_SIZE(dri2_wl_visuals); i++) {
1509       if (!u_vector_init(&dri2_dpy->wl_modifiers[i], sizeof(uint64_t), 32))
1510          goto cleanup;
1511    }
1512 
1513    dri2_dpy->wl_queue = wl_display_create_queue(dri2_dpy->wl_dpy);
1514 
1515    dri2_dpy->wl_dpy_wrapper = wl_proxy_create_wrapper(dri2_dpy->wl_dpy);
1516    if (dri2_dpy->wl_dpy_wrapper == NULL)
1517       goto cleanup;
1518 
1519    wl_proxy_set_queue((struct wl_proxy *) dri2_dpy->wl_dpy_wrapper,
1520                       dri2_dpy->wl_queue);
1521 
1522    if (dri2_dpy->own_device)
1523       wl_display_dispatch_pending(dri2_dpy->wl_dpy);
1524 
1525    dri2_dpy->wl_registry = wl_display_get_registry(dri2_dpy->wl_dpy_wrapper);
1526    wl_registry_add_listener(dri2_dpy->wl_registry,
1527                             &registry_listener_drm, dri2_dpy);
1528    if (roundtrip(dri2_dpy) < 0 || dri2_dpy->wl_drm == NULL)
1529       goto cleanup;
1530 
1531    if (roundtrip(dri2_dpy) < 0 || dri2_dpy->fd == -1)
1532       goto cleanup;
1533 
1534    if (roundtrip(dri2_dpy) < 0 || !dri2_dpy->authenticated)
1535       goto cleanup;
1536 
1537    dri2_dpy->fd = loader_get_user_preferred_fd(dri2_dpy->fd,
1538                                                &dri2_dpy->is_different_gpu);
1539    dev = _eglAddDevice(dri2_dpy->fd, false);
1540    if (!dev) {
1541       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to find EGLDevice");
1542       goto cleanup;
1543    }
1544 
1545    disp->Device = dev;
1546 
1547    if (dri2_dpy->is_different_gpu) {
1548       free(dri2_dpy->device_name);
1549       dri2_dpy->device_name = loader_get_device_name_for_fd(dri2_dpy->fd);
1550       if (!dri2_dpy->device_name) {
1551          _eglError(EGL_BAD_ALLOC, "wayland-egl: failed to get device name "
1552                                   "for requested GPU");
1553          goto cleanup;
1554       }
1555    }
1556 
1557    /* we have to do the check now, because loader_get_user_preferred_fd
1558     * will return a render-node when the requested gpu is different
1559     * to the server, but also if the client asks for the same gpu than
1560     * the server by requesting its pci-id */
1561    dri2_dpy->is_render_node = drmGetNodeTypeFromFd(dri2_dpy->fd) == DRM_NODE_RENDER;
1562 
1563    dri2_dpy->driver_name = loader_get_driver_for_fd(dri2_dpy->fd);
1564    if (dri2_dpy->driver_name == NULL) {
1565       _eglError(EGL_BAD_ALLOC, "DRI2: failed to get driver name");
1566       goto cleanup;
1567    }
1568 
1569    /* render nodes cannot use Gem names, and thus do not support
1570     * the __DRI_DRI2_LOADER extension */
1571    if (!dri2_dpy->is_render_node) {
1572       dri2_dpy->loader_extensions = dri2_loader_extensions;
1573       if (!dri2_load_driver(disp)) {
1574          _eglError(EGL_BAD_ALLOC, "DRI2: failed to load driver");
1575          goto cleanup;
1576       }
1577    } else {
1578       dri2_dpy->loader_extensions = image_loader_extensions;
1579       if (!dri2_load_driver_dri3(disp)) {
1580          _eglError(EGL_BAD_ALLOC, "DRI3: failed to load driver");
1581          goto cleanup;
1582       }
1583    }
1584 
1585    if (!dri2_create_screen(disp))
1586       goto cleanup;
1587 
1588    if (!dri2_setup_extensions(disp))
1589       goto cleanup;
1590 
1591    dri2_setup_screen(disp);
1592 
1593    dri2_wl_setup_swap_interval(disp);
1594 
1595    /* To use Prime, we must have _DRI_IMAGE v7 at least.
1596     * createImageFromFds support indicates that Prime export/import
1597     * is supported by the driver. Fall back to
1598     * gem names if we don't have Prime support. */
1599 
1600    if (dri2_dpy->image->base.version < 7 ||
1601        dri2_dpy->image->createImageFromFds == NULL)
1602       dri2_dpy->capabilities &= ~WL_DRM_CAPABILITY_PRIME;
1603 
1604    /* We cannot use Gem names with render-nodes, only prime fds (dma-buf).
1605     * The server needs to accept them */
1606    if (dri2_dpy->is_render_node &&
1607        !(dri2_dpy->capabilities & WL_DRM_CAPABILITY_PRIME)) {
1608       _eglLog(_EGL_WARNING, "wayland-egl: display is not render-node capable");
1609       goto cleanup;
1610    }
1611 
1612    if (dri2_dpy->is_different_gpu &&
1613        (dri2_dpy->image->base.version < 9 ||
1614         dri2_dpy->image->blitImage == NULL)) {
1615       _eglLog(_EGL_WARNING, "wayland-egl: Different GPU selected, but the "
1616                             "Image extension in the driver is not "
1617                             "compatible. Version 9 or later and blitImage() "
1618                             "are required");
1619       goto cleanup;
1620    }
1621 
1622    if (!dri2_wl_add_configs_for_visuals(disp)) {
1623       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to add configs");
1624       goto cleanup;
1625    }
1626 
1627    dri2_set_WL_bind_wayland_display(disp);
1628    /* When cannot convert EGLImage to wl_buffer when on a different gpu,
1629     * because the buffer of the EGLImage has likely a tiling mode the server
1630     * gpu won't support. These is no way to check for now. Thus do not support the
1631     * extension */
1632    if (!dri2_dpy->is_different_gpu)
1633       disp->Extensions.WL_create_wayland_buffer_from_image = EGL_TRUE;
1634 
1635    disp->Extensions.EXT_buffer_age = EGL_TRUE;
1636 
1637    disp->Extensions.EXT_swap_buffers_with_damage = EGL_TRUE;
1638 
1639    /* Fill vtbl last to prevent accidentally calling virtual function during
1640     * initialization.
1641     */
1642    dri2_dpy->vtbl = &dri2_wl_display_vtbl;
1643 
1644    return EGL_TRUE;
1645 
1646  cleanup:
1647    dri2_display_destroy(disp);
1648    return EGL_FALSE;
1649 }
1650 
1651 static int
dri2_wl_swrast_get_stride_for_format(int format,int w)1652 dri2_wl_swrast_get_stride_for_format(int format, int w)
1653 {
1654    int visual_idx = dri2_wl_visual_idx_from_shm_format(format);
1655 
1656    assume(visual_idx != -1);
1657 
1658    return w * (dri2_wl_visuals[visual_idx].bpp / 8);
1659 }
1660 
1661 static EGLBoolean
dri2_wl_swrast_allocate_buffer(struct dri2_egl_surface * dri2_surf,int format,int w,int h,void ** data,int * size,struct wl_buffer ** buffer)1662 dri2_wl_swrast_allocate_buffer(struct dri2_egl_surface *dri2_surf,
1663                                int format, int w, int h,
1664                                void **data, int *size,
1665                                struct wl_buffer **buffer)
1666 {
1667    struct dri2_egl_display *dri2_dpy =
1668       dri2_egl_display(dri2_surf->base.Resource.Display);
1669    struct wl_shm_pool *pool;
1670    int fd, stride, size_map;
1671    void *data_map;
1672 
1673    stride = dri2_wl_swrast_get_stride_for_format(format, w);
1674    size_map = h * stride;
1675 
1676    /* Create a shareable buffer */
1677    fd = os_create_anonymous_file(size_map, NULL);
1678    if (fd < 0)
1679       return EGL_FALSE;
1680 
1681    data_map = mmap(NULL, size_map, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
1682    if (data_map == MAP_FAILED) {
1683       close(fd);
1684       return EGL_FALSE;
1685    }
1686 
1687    /* Share it in a wl_buffer */
1688    pool = wl_shm_create_pool(dri2_dpy->wl_shm, fd, size_map);
1689    wl_proxy_set_queue((struct wl_proxy *)pool, dri2_surf->wl_queue);
1690    *buffer = wl_shm_pool_create_buffer(pool, 0, w, h, stride, format);
1691    wl_shm_pool_destroy(pool);
1692    close(fd);
1693 
1694    *data = data_map;
1695    *size = size_map;
1696    return EGL_TRUE;
1697 }
1698 
1699 static int
swrast_update_buffers(struct dri2_egl_surface * dri2_surf)1700 swrast_update_buffers(struct dri2_egl_surface *dri2_surf)
1701 {
1702    struct dri2_egl_display *dri2_dpy =
1703       dri2_egl_display(dri2_surf->base.Resource.Display);
1704 
1705    /* we need to do the following operations only once per frame */
1706    if (dri2_surf->back)
1707       return 0;
1708 
1709    if (dri2_surf->base.Width != dri2_surf->wl_win->width ||
1710        dri2_surf->base.Height != dri2_surf->wl_win->height) {
1711 
1712       dri2_wl_release_buffers(dri2_surf);
1713 
1714       dri2_surf->base.Width  = dri2_surf->wl_win->width;
1715       dri2_surf->base.Height = dri2_surf->wl_win->height;
1716       dri2_surf->dx = dri2_surf->wl_win->dx;
1717       dri2_surf->dy = dri2_surf->wl_win->dy;
1718       dri2_surf->current = NULL;
1719    }
1720 
1721    /* find back buffer */
1722 
1723    /* There might be a buffer release already queued that wasn't processed */
1724    wl_display_dispatch_queue_pending(dri2_dpy->wl_dpy, dri2_surf->wl_queue);
1725 
1726    /* try get free buffer already created */
1727    for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
1728       if (!dri2_surf->color_buffers[i].locked &&
1729           dri2_surf->color_buffers[i].wl_buffer) {
1730           dri2_surf->back = &dri2_surf->color_buffers[i];
1731           break;
1732       }
1733    }
1734 
1735    /* else choose any another free location */
1736    if (!dri2_surf->back) {
1737       for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
1738          if (!dri2_surf->color_buffers[i].locked) {
1739              dri2_surf->back = &dri2_surf->color_buffers[i];
1740              if (!dri2_wl_swrast_allocate_buffer(dri2_surf,
1741                                                  dri2_surf->format,
1742                                                  dri2_surf->base.Width,
1743                                                  dri2_surf->base.Height,
1744                                                  &dri2_surf->back->data,
1745                                                  &dri2_surf->back->data_size,
1746                                                  &dri2_surf->back->wl_buffer)) {
1747                 _eglError(EGL_BAD_ALLOC, "failed to allocate color buffer");
1748                  return -1;
1749              }
1750              wl_buffer_add_listener(dri2_surf->back->wl_buffer,
1751                                     &wl_buffer_listener, dri2_surf);
1752              break;
1753          }
1754       }
1755    }
1756 
1757    if (!dri2_surf->back) {
1758       _eglError(EGL_BAD_ALLOC, "failed to find free buffer");
1759       return -1;
1760    }
1761 
1762    dri2_surf->back->locked = true;
1763 
1764    /* If we have an extra unlocked buffer at this point, we had to do triple
1765     * buffering for a while, but now can go back to just double buffering.
1766     * That means we can free any unlocked buffer now. */
1767    for (int i = 0; i < ARRAY_SIZE(dri2_surf->color_buffers); i++) {
1768       if (!dri2_surf->color_buffers[i].locked &&
1769           dri2_surf->color_buffers[i].wl_buffer) {
1770          wl_buffer_destroy(dri2_surf->color_buffers[i].wl_buffer);
1771          munmap(dri2_surf->color_buffers[i].data,
1772                 dri2_surf->color_buffers[i].data_size);
1773          dri2_surf->color_buffers[i].wl_buffer = NULL;
1774          dri2_surf->color_buffers[i].data = NULL;
1775       }
1776    }
1777 
1778    return 0;
1779 }
1780 
1781 static void*
dri2_wl_swrast_get_frontbuffer_data(struct dri2_egl_surface * dri2_surf)1782 dri2_wl_swrast_get_frontbuffer_data(struct dri2_egl_surface *dri2_surf)
1783 {
1784    /* if there has been a resize: */
1785    if (!dri2_surf->current)
1786       return NULL;
1787 
1788    return dri2_surf->current->data;
1789 }
1790 
1791 static void*
dri2_wl_swrast_get_backbuffer_data(struct dri2_egl_surface * dri2_surf)1792 dri2_wl_swrast_get_backbuffer_data(struct dri2_egl_surface *dri2_surf)
1793 {
1794    assert(dri2_surf->back);
1795    return dri2_surf->back->data;
1796 }
1797 
1798 static void
dri2_wl_swrast_commit_backbuffer(struct dri2_egl_surface * dri2_surf)1799 dri2_wl_swrast_commit_backbuffer(struct dri2_egl_surface *dri2_surf)
1800 {
1801    struct dri2_egl_display *dri2_dpy = dri2_egl_display(dri2_surf->base.Resource.Display);
1802 
1803    while (dri2_surf->throttle_callback != NULL)
1804       if (wl_display_dispatch_queue(dri2_dpy->wl_dpy,
1805                                     dri2_surf->wl_queue) == -1)
1806          return;
1807 
1808    if (dri2_surf->base.SwapInterval > 0) {
1809       dri2_surf->throttle_callback =
1810          wl_surface_frame(dri2_surf->wl_surface_wrapper);
1811       wl_callback_add_listener(dri2_surf->throttle_callback,
1812                                &throttle_listener, dri2_surf);
1813    }
1814 
1815    dri2_surf->current = dri2_surf->back;
1816    dri2_surf->back = NULL;
1817 
1818    wl_surface_attach(dri2_surf->wl_surface_wrapper,
1819                      dri2_surf->current->wl_buffer,
1820                      dri2_surf->dx, dri2_surf->dy);
1821 
1822    dri2_surf->wl_win->attached_width  = dri2_surf->base.Width;
1823    dri2_surf->wl_win->attached_height = dri2_surf->base.Height;
1824    /* reset resize growing parameters */
1825    dri2_surf->dx = 0;
1826    dri2_surf->dy = 0;
1827 
1828    wl_surface_damage(dri2_surf->wl_surface_wrapper,
1829                      0, 0, INT32_MAX, INT32_MAX);
1830    wl_surface_commit(dri2_surf->wl_surface_wrapper);
1831 
1832    /* If we're not waiting for a frame callback then we'll at least throttle
1833     * to a sync callback so that we always give a chance for the compositor to
1834     * handle the commit and send a release event before checking for a free
1835     * buffer */
1836    if (dri2_surf->throttle_callback == NULL) {
1837       dri2_surf->throttle_callback = wl_display_sync(dri2_surf->wl_dpy_wrapper);
1838       wl_callback_add_listener(dri2_surf->throttle_callback,
1839                                &throttle_listener, dri2_surf);
1840    }
1841 
1842    wl_display_flush(dri2_dpy->wl_dpy);
1843 }
1844 
1845 static void
dri2_wl_swrast_get_drawable_info(__DRIdrawable * draw,int * x,int * y,int * w,int * h,void * loaderPrivate)1846 dri2_wl_swrast_get_drawable_info(__DRIdrawable * draw,
1847                                  int *x, int *y, int *w, int *h,
1848                                  void *loaderPrivate)
1849 {
1850    struct dri2_egl_surface *dri2_surf = loaderPrivate;
1851 
1852    (void) swrast_update_buffers(dri2_surf);
1853    *x = 0;
1854    *y = 0;
1855    *w = dri2_surf->base.Width;
1856    *h = dri2_surf->base.Height;
1857 }
1858 
1859 static void
dri2_wl_swrast_get_image(__DRIdrawable * read,int x,int y,int w,int h,char * data,void * loaderPrivate)1860 dri2_wl_swrast_get_image(__DRIdrawable * read,
1861                          int x, int y, int w, int h,
1862                          char *data, void *loaderPrivate)
1863 {
1864    struct dri2_egl_surface *dri2_surf = loaderPrivate;
1865    int copy_width = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, w);
1866    int x_offset = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, x);
1867    int src_stride = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, dri2_surf->base.Width);
1868    int dst_stride = copy_width;
1869    char *src, *dst;
1870 
1871    src = dri2_wl_swrast_get_frontbuffer_data(dri2_surf);
1872    if (!src) {
1873       memset(data, 0, copy_width * h);
1874       return;
1875    }
1876 
1877    assert(data != src);
1878    assert(copy_width <= src_stride);
1879 
1880    src += x_offset;
1881    src += y * src_stride;
1882    dst = data;
1883 
1884    if (copy_width > src_stride-x_offset)
1885       copy_width = src_stride-x_offset;
1886    if (h > dri2_surf->base.Height-y)
1887       h = dri2_surf->base.Height-y;
1888 
1889    for (; h>0; h--) {
1890       memcpy(dst, src, copy_width);
1891       src += src_stride;
1892       dst += dst_stride;
1893    }
1894 }
1895 
1896 static void
dri2_wl_swrast_put_image2(__DRIdrawable * draw,int op,int x,int y,int w,int h,int stride,char * data,void * loaderPrivate)1897 dri2_wl_swrast_put_image2(__DRIdrawable * draw, int op,
1898                          int x, int y, int w, int h, int stride,
1899                          char *data, void *loaderPrivate)
1900 {
1901    struct dri2_egl_surface *dri2_surf = loaderPrivate;
1902    int copy_width = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, w);
1903    int dst_stride = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, dri2_surf->base.Width);
1904    int x_offset = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, x);
1905    char *src, *dst;
1906 
1907    assert(copy_width <= stride);
1908 
1909    (void) swrast_update_buffers(dri2_surf);
1910    dst = dri2_wl_swrast_get_backbuffer_data(dri2_surf);
1911 
1912    /* partial copy, copy old content */
1913    if (copy_width < dst_stride)
1914       dri2_wl_swrast_get_image(draw, 0, 0,
1915                                dri2_surf->base.Width, dri2_surf->base.Height,
1916                                dst, loaderPrivate);
1917 
1918    dst += x_offset;
1919    dst += y * dst_stride;
1920 
1921    src = data;
1922 
1923    /* drivers expect we do these checks (and some rely on it) */
1924    if (copy_width > dst_stride-x_offset)
1925       copy_width = dst_stride-x_offset;
1926    if (h > dri2_surf->base.Height-y)
1927       h = dri2_surf->base.Height-y;
1928 
1929    for (; h>0; h--) {
1930       memcpy(dst, src, copy_width);
1931       src += stride;
1932       dst += dst_stride;
1933    }
1934    dri2_wl_swrast_commit_backbuffer(dri2_surf);
1935 }
1936 
1937 static void
dri2_wl_swrast_put_image(__DRIdrawable * draw,int op,int x,int y,int w,int h,char * data,void * loaderPrivate)1938 dri2_wl_swrast_put_image(__DRIdrawable * draw, int op,
1939                          int x, int y, int w, int h,
1940                          char *data, void *loaderPrivate)
1941 {
1942    struct dri2_egl_surface *dri2_surf = loaderPrivate;
1943    int stride;
1944 
1945    stride = dri2_wl_swrast_get_stride_for_format(dri2_surf->format, w);
1946    dri2_wl_swrast_put_image2(draw, op, x, y, w, h,
1947                              stride, data, loaderPrivate);
1948 }
1949 
1950 static EGLBoolean
dri2_wl_swrast_swap_buffers(_EGLDisplay * disp,_EGLSurface * draw)1951 dri2_wl_swrast_swap_buffers(_EGLDisplay *disp, _EGLSurface *draw)
1952 {
1953    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1954    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1955 
1956    dri2_dpy->core->swapBuffers(dri2_surf->dri_drawable);
1957    return EGL_TRUE;
1958 }
1959 
1960 static void
shm_handle_format(void * data,struct wl_shm * shm,uint32_t format)1961 shm_handle_format(void *data, struct wl_shm *shm, uint32_t format)
1962 {
1963    struct dri2_egl_display *dri2_dpy = data;
1964    int visual_idx = dri2_wl_visual_idx_from_shm_format(format);
1965 
1966    if (visual_idx == -1)
1967       return;
1968 
1969    BITSET_SET(dri2_dpy->formats, visual_idx);
1970 }
1971 
1972 static const struct wl_shm_listener shm_listener = {
1973    .format = shm_handle_format
1974 };
1975 
1976 static void
registry_handle_global_swrast(void * data,struct wl_registry * registry,uint32_t name,const char * interface,uint32_t version)1977 registry_handle_global_swrast(void *data, struct wl_registry *registry,
1978                               uint32_t name, const char *interface,
1979                               uint32_t version)
1980 {
1981    struct dri2_egl_display *dri2_dpy = data;
1982 
1983    if (strcmp(interface, "wl_shm") == 0) {
1984       dri2_dpy->wl_shm =
1985          wl_registry_bind(registry, name, &wl_shm_interface, 1);
1986       wl_shm_add_listener(dri2_dpy->wl_shm, &shm_listener, dri2_dpy);
1987    }
1988 }
1989 
1990 static const struct wl_registry_listener registry_listener_swrast = {
1991    .global = registry_handle_global_swrast,
1992    .global_remove = registry_handle_global_remove
1993 };
1994 
1995 static const struct dri2_egl_display_vtbl dri2_wl_swrast_display_vtbl = {
1996    .authenticate = NULL,
1997    .create_window_surface = dri2_wl_create_window_surface,
1998    .create_pixmap_surface = dri2_wl_create_pixmap_surface,
1999    .destroy_surface = dri2_wl_destroy_surface,
2000    .create_image = dri2_create_image_khr,
2001    .swap_buffers = dri2_wl_swrast_swap_buffers,
2002    .get_dri_drawable = dri2_surface_get_dri_drawable,
2003 };
2004 
2005 static const __DRIswrastLoaderExtension swrast_loader_extension = {
2006    .base = { __DRI_SWRAST_LOADER, 2 },
2007 
2008    .getDrawableInfo = dri2_wl_swrast_get_drawable_info,
2009    .putImage        = dri2_wl_swrast_put_image,
2010    .getImage        = dri2_wl_swrast_get_image,
2011    .putImage2       = dri2_wl_swrast_put_image2,
2012 };
2013 
2014 static const __DRIextension *swrast_loader_extensions[] = {
2015    &swrast_loader_extension.base,
2016    &image_lookup_extension.base,
2017    NULL,
2018 };
2019 
2020 static EGLBoolean
dri2_initialize_wayland_swrast(_EGLDisplay * disp)2021 dri2_initialize_wayland_swrast(_EGLDisplay *disp)
2022 {
2023    _EGLDevice *dev;
2024    struct dri2_egl_display *dri2_dpy;
2025 
2026    dri2_dpy = calloc(1, sizeof *dri2_dpy);
2027    if (!dri2_dpy)
2028       return _eglError(EGL_BAD_ALLOC, "eglInitialize");
2029 
2030    dri2_dpy->fd = -1;
2031    disp->DriverData = (void *) dri2_dpy;
2032    if (disp->PlatformDisplay == NULL) {
2033       dri2_dpy->wl_dpy = wl_display_connect(NULL);
2034       if (dri2_dpy->wl_dpy == NULL)
2035          goto cleanup;
2036       dri2_dpy->own_device = true;
2037    } else {
2038       dri2_dpy->wl_dpy = disp->PlatformDisplay;
2039    }
2040 
2041    dev = _eglAddDevice(dri2_dpy->fd, true);
2042    if (!dev) {
2043       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to find EGLDevice");
2044       goto cleanup;
2045    }
2046 
2047    disp->Device = dev;
2048 
2049    dri2_dpy->wl_queue = wl_display_create_queue(dri2_dpy->wl_dpy);
2050 
2051    dri2_dpy->wl_dpy_wrapper = wl_proxy_create_wrapper(dri2_dpy->wl_dpy);
2052    if (dri2_dpy->wl_dpy_wrapper == NULL)
2053       goto cleanup;
2054 
2055    wl_proxy_set_queue((struct wl_proxy *) dri2_dpy->wl_dpy_wrapper,
2056                       dri2_dpy->wl_queue);
2057 
2058    if (dri2_dpy->own_device)
2059       wl_display_dispatch_pending(dri2_dpy->wl_dpy);
2060 
2061    dri2_dpy->wl_registry = wl_display_get_registry(dri2_dpy->wl_dpy_wrapper);
2062    wl_registry_add_listener(dri2_dpy->wl_registry,
2063                             &registry_listener_swrast, dri2_dpy);
2064 
2065    if (roundtrip(dri2_dpy) < 0 || dri2_dpy->wl_shm == NULL)
2066       goto cleanup;
2067 
2068    if (roundtrip(dri2_dpy) < 0 || !BITSET_TEST_RANGE(dri2_dpy->formats,
2069                                                      0, EGL_DRI2_MAX_FORMATS))
2070       goto cleanup;
2071 
2072    dri2_dpy->driver_name = strdup("swrast");
2073    if (!dri2_load_driver_swrast(disp))
2074       goto cleanup;
2075 
2076    dri2_dpy->loader_extensions = swrast_loader_extensions;
2077 
2078    if (!dri2_create_screen(disp))
2079       goto cleanup;
2080 
2081    if (!dri2_setup_extensions(disp))
2082       goto cleanup;
2083 
2084    dri2_setup_screen(disp);
2085 
2086    dri2_wl_setup_swap_interval(disp);
2087 
2088    if (!dri2_wl_add_configs_for_visuals(disp)) {
2089       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to add configs");
2090       goto cleanup;
2091    }
2092 
2093    /* Fill vtbl last to prevent accidentally calling virtual function during
2094     * initialization.
2095     */
2096    dri2_dpy->vtbl = &dri2_wl_swrast_display_vtbl;
2097 
2098    return EGL_TRUE;
2099 
2100  cleanup:
2101    dri2_display_destroy(disp);
2102    return EGL_FALSE;
2103 }
2104 
2105 EGLBoolean
dri2_initialize_wayland(_EGLDisplay * disp)2106 dri2_initialize_wayland(_EGLDisplay *disp)
2107 {
2108    if (disp->Options.ForceSoftware)
2109       return dri2_initialize_wayland_swrast(disp);
2110    else
2111       return dri2_initialize_wayland_drm(disp);
2112 }
2113 
2114 void
dri2_teardown_wayland(struct dri2_egl_display * dri2_dpy)2115 dri2_teardown_wayland(struct dri2_egl_display *dri2_dpy)
2116 {
2117    if (dri2_dpy->wl_drm)
2118       wl_drm_destroy(dri2_dpy->wl_drm);
2119    if (dri2_dpy->wl_dmabuf)
2120       zwp_linux_dmabuf_v1_destroy(dri2_dpy->wl_dmabuf);
2121    if (dri2_dpy->wl_shm)
2122       wl_shm_destroy(dri2_dpy->wl_shm);
2123    if (dri2_dpy->wl_registry)
2124       wl_registry_destroy(dri2_dpy->wl_registry);
2125    if (dri2_dpy->wl_queue)
2126       wl_event_queue_destroy(dri2_dpy->wl_queue);
2127    if (dri2_dpy->wl_dpy_wrapper)
2128       wl_proxy_wrapper_destroy(dri2_dpy->wl_dpy_wrapper);
2129 
2130    for (int i = 0; dri2_dpy->wl_modifiers && i < ARRAY_SIZE(dri2_wl_visuals); i++)
2131       u_vector_finish(&dri2_dpy->wl_modifiers[i]);
2132    free(dri2_dpy->wl_modifiers);
2133 
2134    if (dri2_dpy->own_device)
2135       wl_display_disconnect(dri2_dpy->wl_dpy);
2136 }
2137