xref: /aosp_15_r20/external/mesa3d/src/egl/drivers/dri2/platform_x11.c (revision 6104692788411f58d303aa86923a9ff6ecaded22)
1 /*
2  * Copyright © 2011 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 <[email protected]>
26  */
27 
28 #include <dlfcn.h>
29 #include <errno.h>
30 #include <fcntl.h>
31 #include <limits.h>
32 #include <stdbool.h>
33 #include <stdint.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 /* clang-format off */
39 #include <xcb/xcb.h>
40 #include <xcb/shm.h>
41 #include <vulkan/vulkan_core.h>
42 #include <vulkan/vulkan_xcb.h>
43 /* clang-format on */
44 #ifdef HAVE_LIBDRM
45 #include <xf86drm.h>
46 #include "platform_x11_dri3.h"
47 #endif
48 #include "util/bitscan.h"
49 #include "util/macros.h"
50 #include "util/u_debug.h"
51 #include "util/log.h"
52 #include <sys/stat.h>
53 #include <sys/types.h>
54 #include "loader_x11.h"
55 #include "kopper_interface.h"
56 #include "loader.h"
57 #include "platform_x11.h"
58 #include "drm-uapi/drm_fourcc.h"
59 #include "dri_util.h"
60 
61 
62 static EGLBoolean
63 dri2_x11_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval);
64 
65 static void
swrastCreateDrawable(struct dri2_egl_display * dri2_dpy,struct dri2_egl_surface * dri2_surf)66 swrastCreateDrawable(struct dri2_egl_display *dri2_dpy,
67                      struct dri2_egl_surface *dri2_surf)
68 {
69    uint32_t mask;
70    const uint32_t function = GXcopy;
71    uint32_t valgc[2];
72 
73    /* create GC's */
74    dri2_surf->gc = xcb_generate_id(dri2_dpy->conn);
75    mask = XCB_GC_FUNCTION;
76    xcb_create_gc(dri2_dpy->conn, dri2_surf->gc, dri2_surf->drawable, mask,
77                  &function);
78 
79    dri2_surf->swapgc = xcb_generate_id(dri2_dpy->conn);
80    mask = XCB_GC_FUNCTION | XCB_GC_GRAPHICS_EXPOSURES;
81    valgc[0] = function;
82    valgc[1] = False;
83    xcb_create_gc(dri2_dpy->conn, dri2_surf->swapgc, dri2_surf->drawable, mask,
84                  valgc);
85    switch (dri2_surf->depth) {
86    case 32:
87    case 30:
88    case 24:
89       dri2_surf->bytes_per_pixel = 4;
90       break;
91    case 16:
92       dri2_surf->bytes_per_pixel = 2;
93       break;
94    case 8:
95       dri2_surf->bytes_per_pixel = 1;
96       break;
97    case 0:
98       dri2_surf->bytes_per_pixel = 0;
99       break;
100    default:
101       _eglLog(_EGL_WARNING, "unsupported depth %d", dri2_surf->depth);
102    }
103 }
104 
105 static void
swrastDestroyDrawable(struct dri2_egl_display * dri2_dpy,struct dri2_egl_surface * dri2_surf)106 swrastDestroyDrawable(struct dri2_egl_display *dri2_dpy,
107                       struct dri2_egl_surface *dri2_surf)
108 {
109    xcb_free_gc(dri2_dpy->conn, dri2_surf->gc);
110    xcb_free_gc(dri2_dpy->conn, dri2_surf->swapgc);
111 }
112 
113 static bool
x11_get_drawable_info(__DRIdrawable * draw,int * x,int * y,int * w,int * h,void * loaderPrivate)114 x11_get_drawable_info(__DRIdrawable *draw, int *x, int *y, int *w, int *h,
115                       void *loaderPrivate)
116 {
117    struct dri2_egl_surface *dri2_surf = loaderPrivate;
118    struct dri2_egl_display *dri2_dpy =
119       dri2_egl_display(dri2_surf->base.Resource.Display);
120 
121    xcb_get_geometry_cookie_t cookie;
122    xcb_get_geometry_reply_t *reply;
123    xcb_generic_error_t *error;
124    bool ret;
125 
126    cookie = xcb_get_geometry(dri2_dpy->conn, dri2_surf->drawable);
127    reply = xcb_get_geometry_reply(dri2_dpy->conn, cookie, &error);
128    if (reply == NULL)
129       return false;
130 
131    if (error != NULL) {
132       ret = false;
133       _eglLog(_EGL_WARNING, "error in xcb_get_geometry");
134       free(error);
135    } else {
136       *x = reply->x;
137       *y = reply->y;
138       *w = reply->width;
139       *h = reply->height;
140       ret = true;
141    }
142    free(reply);
143    return ret;
144 }
145 
146 static void
swrastGetDrawableInfo(__DRIdrawable * draw,int * x,int * y,int * w,int * h,void * loaderPrivate)147 swrastGetDrawableInfo(__DRIdrawable *draw, int *x, int *y, int *w, int *h,
148                       void *loaderPrivate)
149 {
150    *x = *y = *w = *h = 0;
151    x11_get_drawable_info(draw, x, y, w, h, loaderPrivate);
152 }
153 
154 static void
swrastPutImage2(__DRIdrawable * draw,int op,int x,int y,int w,int h,int stride,char * data,void * loaderPrivate)155 swrastPutImage2(__DRIdrawable *draw, int op, int x, int y, int w, int h,
156                 int stride, char *data, void *loaderPrivate)
157 {
158    struct dri2_egl_surface *dri2_surf = loaderPrivate;
159    struct dri2_egl_display *dri2_dpy =
160       dri2_egl_display(dri2_surf->base.Resource.Display);
161    int stride_b = dri2_surf->bytes_per_pixel * w;
162    size_t hdr_len = sizeof(xcb_put_image_request_t);
163    size_t size = (hdr_len + stride_b * h) >> 2;
164    uint64_t max_req_len = xcb_get_maximum_request_length(dri2_dpy->conn);
165 
166    xcb_gcontext_t gc;
167    xcb_void_cookie_t cookie;
168    switch (op) {
169    case __DRI_SWRAST_IMAGE_OP_DRAW:
170       gc = dri2_surf->gc;
171       break;
172    case __DRI_SWRAST_IMAGE_OP_SWAP:
173       gc = dri2_surf->swapgc;
174       break;
175    default:
176       return;
177    }
178 
179    /* clamp to drawable size */
180    if (y + h > dri2_surf->base.Height)
181       h = dri2_surf->base.Height - y;
182 
183    /* If stride of pixels to copy is different from the surface stride
184     * then we need to copy lines one by one.
185     */
186    if (stride_b != stride) {
187       for (unsigned i = 0; i < h; i++) {
188          cookie = xcb_put_image(
189             dri2_dpy->conn, XCB_IMAGE_FORMAT_Z_PIXMAP, dri2_surf->drawable, gc, w,
190             1, x, y+i, 0, dri2_surf->depth, stride_b, (uint8_t*)data);
191          xcb_discard_reply(dri2_dpy->conn, cookie.sequence);
192 
193          data += stride;
194       }
195    } else if (size < max_req_len) {
196       cookie = xcb_put_image(
197          dri2_dpy->conn, XCB_IMAGE_FORMAT_Z_PIXMAP, dri2_surf->drawable, gc, w,
198          h, x, y, 0, dri2_surf->depth, h * stride_b, (const uint8_t *)data);
199       xcb_discard_reply(dri2_dpy->conn, cookie.sequence);
200    } else {
201       int num_lines = ((max_req_len << 2) - hdr_len) / stride_b;
202       int y_start = 0;
203       int y_todo = h;
204       while (y_todo) {
205          int this_lines = MIN2(num_lines, y_todo);
206          cookie =
207             xcb_put_image(dri2_dpy->conn, XCB_IMAGE_FORMAT_Z_PIXMAP,
208                           dri2_surf->drawable, gc, w, this_lines, x, y_start, 0,
209                           dri2_surf->depth, this_lines * stride_b,
210                           ((const uint8_t *)data + y_start * stride_b));
211          xcb_discard_reply(dri2_dpy->conn, cookie.sequence);
212          y_start += this_lines;
213          y_todo -= this_lines;
214       }
215    }
216    xcb_flush(dri2_dpy->conn);
217 }
218 
219 static void
swrastPutImage(__DRIdrawable * draw,int op,int x,int y,int w,int h,char * data,void * loaderPrivate)220 swrastPutImage(__DRIdrawable *draw, int op, int x, int y, int w, int h,
221                char *data, void *loaderPrivate)
222 {
223    struct dri2_egl_surface *dri2_surf = loaderPrivate;
224    int stride_b = dri2_surf->bytes_per_pixel * w;
225    swrastPutImage2(draw, op, x, y, w, h, stride_b, data, loaderPrivate);
226 }
227 
228 static void
swrastGetImage2(__DRIdrawable * read,int x,int y,int w,int h,int stride,char * data,void * loaderPrivate)229 swrastGetImage2(__DRIdrawable * read,
230                 int x, int y, int w, int h, int stride,
231                 char *data, void *loaderPrivate)
232 {
233    struct dri2_egl_surface *dri2_surf = loaderPrivate;
234    struct dri2_egl_display *dri2_dpy =
235       dri2_egl_display(dri2_surf->base.Resource.Display);
236 
237    xcb_get_image_cookie_t cookie;
238    xcb_get_image_reply_t *reply;
239    xcb_generic_error_t *error;
240 
241    cookie = xcb_get_image(dri2_dpy->conn, XCB_IMAGE_FORMAT_Z_PIXMAP,
242                           dri2_surf->drawable, x, y, w, h, ~0);
243    reply = xcb_get_image_reply(dri2_dpy->conn, cookie, &error);
244    if (reply == NULL)
245       return;
246 
247    if (error != NULL) {
248       _eglLog(_EGL_WARNING, "error in xcb_get_image");
249       free(error);
250    } else {
251       uint32_t bytes = xcb_get_image_data_length(reply);
252       uint8_t *idata = xcb_get_image_data(reply);
253       int stride_b = w * dri2_surf->bytes_per_pixel;
254       /* Only copy line by line if we have a different stride */
255       if (stride != stride_b) {
256          for (int i = 0; i < h; i++) {
257             memcpy(data, idata, stride_b);
258             data += stride;
259             idata += stride_b;
260          }
261       } else {
262          memcpy(data, idata, bytes);
263       }
264    }
265    free(reply);
266 }
267 
268 static void
swrastGetImage(__DRIdrawable * read,int x,int y,int w,int h,char * data,void * loaderPrivate)269 swrastGetImage(__DRIdrawable *read, int x, int y, int w, int h, char *data,
270                void *loaderPrivate)
271 {
272    struct dri2_egl_surface *dri2_surf = loaderPrivate;
273    int stride_b = w * dri2_surf->bytes_per_pixel;
274    swrastGetImage2(read, x, y, w, h, stride_b, data, loaderPrivate);
275 }
276 
277 static void
swrastPutImageShm(__DRIdrawable * draw,int op,int x,int y,int w,int h,int stride,int shmid,char * shmaddr,unsigned offset,void * loaderPrivate)278 swrastPutImageShm(__DRIdrawable * draw, int op,
279                   int x, int y, int w, int h, int stride,
280                   int shmid, char *shmaddr, unsigned offset,
281                   void *loaderPrivate)
282 {
283    struct dri2_egl_surface *dri2_surf = loaderPrivate;
284    struct dri2_egl_display *dri2_dpy =
285       dri2_egl_display(dri2_surf->base.Resource.Display);
286    xcb_generic_error_t *error = NULL;
287 
288    xcb_shm_seg_t shm_seg = xcb_generate_id(dri2_dpy->conn);
289    error = xcb_request_check(dri2_dpy->conn,
290                              xcb_shm_attach_checked(dri2_dpy->conn,
291                                                     shm_seg, shmid, 0));
292    if (error) {
293       mesa_loge("Failed to attach to x11 shm");
294       _eglError(EGL_BAD_SURFACE, "xcb_shm_attach_checked");
295       free(error);
296       return;
297    }
298 
299    xcb_gcontext_t gc;
300    xcb_void_cookie_t cookie;
301    switch (op) {
302    case __DRI_SWRAST_IMAGE_OP_DRAW:
303       gc = dri2_surf->gc;
304       break;
305    case __DRI_SWRAST_IMAGE_OP_SWAP:
306       gc = dri2_surf->swapgc;
307       break;
308    default:
309       return;
310    }
311 
312    cookie = xcb_shm_put_image(dri2_dpy->conn,
313          dri2_surf->drawable,
314          gc,
315          stride / dri2_surf->bytes_per_pixel, h,
316          x, 0,
317          w, h,
318          x, y,
319          dri2_surf->depth,
320          XCB_IMAGE_FORMAT_Z_PIXMAP,
321          0, shm_seg, stride * y);
322    xcb_discard_reply(dri2_dpy->conn, cookie.sequence);
323 
324    xcb_flush(dri2_dpy->conn);
325    xcb_shm_detach(dri2_dpy->conn, shm_seg);
326 }
327 
328 static void
swrastGetImageShm(__DRIdrawable * read,int x,int y,int w,int h,int shmid,void * loaderPrivate)329 swrastGetImageShm(__DRIdrawable * read,
330                   int x, int y, int w, int h,
331                   int shmid, void *loaderPrivate)
332 {
333    struct dri2_egl_surface *dri2_surf = loaderPrivate;
334    struct dri2_egl_display *dri2_dpy =
335       dri2_egl_display(dri2_surf->base.Resource.Display);
336    xcb_generic_error_t *error = NULL;
337 
338    xcb_shm_seg_t shm_seg = xcb_generate_id(dri2_dpy->conn);
339    error = xcb_request_check(dri2_dpy->conn,
340                              xcb_shm_attach_checked(dri2_dpy->conn,
341                                                     shm_seg, shmid, 0));
342    if (error) {
343       mesa_loge("Failed to attach to x11 shm");
344       _eglError(EGL_BAD_SURFACE, "xcb_shm_attach_checked");
345       free(error);
346       return;
347    }
348 
349    xcb_shm_get_image_cookie_t cookie;
350    xcb_shm_get_image_reply_t *reply;
351 
352    cookie = xcb_shm_get_image(dri2_dpy->conn,
353          dri2_surf->drawable,
354          x, y,
355          w, h,
356          ~0, XCB_IMAGE_FORMAT_Z_PIXMAP,
357          shm_seg, 0);
358    reply = xcb_shm_get_image_reply(dri2_dpy->conn, cookie, NULL);
359    if (reply == NULL)
360       _eglLog(_EGL_WARNING, "error in xcb_shm_get_image");
361    else
362       free(reply);
363 
364    xcb_shm_detach(dri2_dpy->conn, shm_seg);
365 }
366 
367 static xcb_screen_t *
get_xcb_screen(xcb_screen_iterator_t iter,int screen)368 get_xcb_screen(xcb_screen_iterator_t iter, int screen)
369 {
370    for (; iter.rem; --screen, xcb_screen_next(&iter))
371       if (screen == 0)
372          return iter.data;
373 
374    return NULL;
375 }
376 
377 static xcb_visualtype_t *
get_xcb_visualtype_for_depth(struct dri2_egl_display * dri2_dpy,int depth)378 get_xcb_visualtype_for_depth(struct dri2_egl_display *dri2_dpy, int depth)
379 {
380    xcb_visualtype_iterator_t visual_iter;
381    xcb_screen_t *screen = dri2_dpy->screen;
382    xcb_depth_iterator_t depth_iter = xcb_screen_allowed_depths_iterator(screen);
383 
384    for (; depth_iter.rem; xcb_depth_next(&depth_iter)) {
385       if (depth_iter.data->depth != depth)
386          continue;
387 
388       visual_iter = xcb_depth_visuals_iterator(depth_iter.data);
389       if (visual_iter.rem)
390          return visual_iter.data;
391    }
392 
393    return NULL;
394 }
395 
396 /* Get red channel mask for given depth. */
397 unsigned int
dri2_x11_get_red_mask_for_depth(struct dri2_egl_display * dri2_dpy,int depth)398 dri2_x11_get_red_mask_for_depth(struct dri2_egl_display *dri2_dpy, int depth)
399 {
400    xcb_visualtype_t *visual = get_xcb_visualtype_for_depth(dri2_dpy, depth);
401 
402    if (visual)
403       return visual->red_mask;
404 
405    return 0;
406 }
407 
408 /**
409  * Called via eglCreateWindowSurface(), drv->CreateWindowSurface().
410  */
411 static _EGLSurface *
dri2_x11_create_surface(_EGLDisplay * disp,EGLint type,_EGLConfig * conf,void * native_surface,const EGLint * attrib_list)412 dri2_x11_create_surface(_EGLDisplay *disp, EGLint type, _EGLConfig *conf,
413                         void *native_surface, const EGLint *attrib_list)
414 {
415    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
416    struct dri2_egl_config *dri2_conf = dri2_egl_config(conf);
417    struct dri2_egl_surface *dri2_surf;
418    xcb_get_geometry_cookie_t cookie;
419    xcb_get_geometry_reply_t *reply;
420    xcb_generic_error_t *error;
421    const __DRIconfig *config;
422 
423    dri2_surf = calloc(1, sizeof *dri2_surf);
424    if (!dri2_surf) {
425       _eglError(EGL_BAD_ALLOC, "dri2_create_surface");
426       return NULL;
427    }
428 
429    if (!dri2_init_surface(&dri2_surf->base, disp, type, conf, attrib_list,
430                           false, native_surface))
431       goto cleanup_surf;
432 
433    dri2_surf->region = XCB_NONE;
434    if (type == EGL_PBUFFER_BIT) {
435       dri2_surf->drawable = xcb_generate_id(dri2_dpy->conn);
436       xcb_create_pixmap(dri2_dpy->conn, conf->BufferSize, dri2_surf->drawable,
437                         dri2_dpy->screen->root, dri2_surf->base.Width,
438                         dri2_surf->base.Height);
439    } else {
440       STATIC_ASSERT(sizeof(uintptr_t) == sizeof(native_surface));
441       dri2_surf->drawable = (uintptr_t)native_surface;
442    }
443 
444    config = dri2_get_dri_config(dri2_conf, type, dri2_surf->base.GLColorspace);
445 
446    if (!config) {
447       _eglError(EGL_BAD_MATCH,
448                 "Unsupported surfacetype/colorspace configuration");
449       goto cleanup_pixmap;
450    }
451 
452    if (type != EGL_PBUFFER_BIT) {
453       cookie = xcb_get_geometry(dri2_dpy->conn, dri2_surf->drawable);
454       reply = xcb_get_geometry_reply(dri2_dpy->conn, cookie, &error);
455       if (error != NULL) {
456          if (error->error_code == BadAlloc)
457             _eglError(EGL_BAD_ALLOC, "xcb_get_geometry");
458          else if (type == EGL_WINDOW_BIT)
459             _eglError(EGL_BAD_NATIVE_WINDOW, "xcb_get_geometry");
460          else
461             _eglError(EGL_BAD_NATIVE_PIXMAP, "xcb_get_geometry");
462          free(error);
463          free(reply);
464          goto cleanup_dri_drawable;
465       } else if (reply == NULL) {
466          _eglError(EGL_BAD_ALLOC, "xcb_get_geometry");
467          goto cleanup_dri_drawable;
468       }
469 
470       dri2_surf->base.Width = reply->width;
471       dri2_surf->base.Height = reply->height;
472       dri2_surf->depth = reply->depth;
473       free(reply);
474    }
475 
476    if (!dri2_create_drawable(dri2_dpy, config, dri2_surf, dri2_surf))
477       goto cleanup_pixmap;
478 
479 #ifdef HAVE_X11_DRI2
480    if (!dri2_dpy->swrast) {
481       xcb_void_cookie_t cookie;
482       int conn_error;
483 
484       cookie =
485          xcb_dri2_create_drawable_checked(dri2_dpy->conn, dri2_surf->drawable);
486       error = xcb_request_check(dri2_dpy->conn, cookie);
487       conn_error = xcb_connection_has_error(dri2_dpy->conn);
488       if (conn_error || error != NULL) {
489          if (type == EGL_PBUFFER_BIT || conn_error ||
490              error->error_code == BadAlloc)
491             _eglError(EGL_BAD_ALLOC, "xcb_dri2_create_drawable_checked");
492          else if (type == EGL_WINDOW_BIT)
493             _eglError(EGL_BAD_NATIVE_WINDOW,
494                       "xcb_dri2_create_drawable_checked");
495          else
496             _eglError(EGL_BAD_NATIVE_PIXMAP,
497                       "xcb_dri2_create_drawable_checked");
498          free(error);
499          goto cleanup_dri_drawable;
500       }
501    } else
502 #endif
503    {
504       if (type == EGL_PBUFFER_BIT) {
505          dri2_surf->depth = conf->BufferSize;
506       }
507       swrastCreateDrawable(dri2_dpy, dri2_surf);
508    }
509 
510    /* we always copy the back buffer to front */
511    dri2_surf->base.PostSubBufferSupportedNV = EGL_TRUE;
512 
513    return &dri2_surf->base;
514 
515 cleanup_dri_drawable:
516    driDestroyDrawable(dri2_surf->dri_drawable);
517 cleanup_pixmap:
518    if (type == EGL_PBUFFER_BIT)
519       xcb_free_pixmap(dri2_dpy->conn, dri2_surf->drawable);
520 cleanup_surf:
521    free(dri2_surf);
522 
523    return NULL;
524 }
525 
526 /**
527  * Called via eglCreateWindowSurface(), drv->CreateWindowSurface().
528  */
529 static _EGLSurface *
dri2_x11_create_window_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)530 dri2_x11_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
531                                void *native_window, const EGLint *attrib_list)
532 {
533    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
534    _EGLSurface *surf;
535 
536    surf = dri2_x11_create_surface(disp, EGL_WINDOW_BIT, conf, native_window,
537                                   attrib_list);
538    if (surf != NULL) {
539       /* When we first create the DRI2 drawable, its swap interval on the
540        * server side is 1.
541        */
542       surf->SwapInterval = 1;
543 
544       /* Override that with a driconf-set value. */
545       dri2_x11_swap_interval(disp, surf, dri2_dpy->default_swap_interval);
546    }
547 
548    return surf;
549 }
550 
551 static _EGLSurface *
dri2_x11_create_pixmap_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_pixmap,const EGLint * attrib_list)552 dri2_x11_create_pixmap_surface(_EGLDisplay *disp, _EGLConfig *conf,
553                                void *native_pixmap, const EGLint *attrib_list)
554 {
555    return dri2_x11_create_surface(disp, EGL_PIXMAP_BIT, conf, native_pixmap,
556                                   attrib_list);
557 }
558 
559 static _EGLSurface *
dri2_x11_create_pbuffer_surface(_EGLDisplay * disp,_EGLConfig * conf,const EGLint * attrib_list)560 dri2_x11_create_pbuffer_surface(_EGLDisplay *disp, _EGLConfig *conf,
561                                 const EGLint *attrib_list)
562 {
563    return dri2_x11_create_surface(disp, EGL_PBUFFER_BIT, conf, NULL,
564                                   attrib_list);
565 }
566 
567 static EGLBoolean
dri2_x11_destroy_surface(_EGLDisplay * disp,_EGLSurface * surf)568 dri2_x11_destroy_surface(_EGLDisplay *disp, _EGLSurface *surf)
569 {
570    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
571    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
572 
573    driDestroyDrawable(dri2_surf->dri_drawable);
574 
575    if (!dri2_dpy->swrast) {
576 #ifdef HAVE_X11_DRI2
577       xcb_dri2_destroy_drawable(dri2_dpy->conn, dri2_surf->drawable);
578 #endif
579    } else {
580       swrastDestroyDrawable(dri2_dpy, dri2_surf);
581    }
582 
583    if (surf->Type == EGL_PBUFFER_BIT)
584       xcb_free_pixmap(dri2_dpy->conn, dri2_surf->drawable);
585 
586    dri2_fini_surface(surf);
587    free(surf);
588 
589    return EGL_TRUE;
590 }
591 
592 /**
593  * Function utilizes swrastGetDrawableInfo to get surface
594  * geometry from x server and calls default query surface
595  * implementation that returns the updated values.
596  *
597  * In case of errors we still return values that we currently
598  * have.
599  */
600 static EGLBoolean
dri2_query_surface(_EGLDisplay * disp,_EGLSurface * surf,EGLint attribute,EGLint * value)601 dri2_query_surface(_EGLDisplay *disp, _EGLSurface *surf, EGLint attribute,
602                    EGLint *value)
603 {
604    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
605    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
606    int x, y, w, h;
607 
608    __DRIdrawable *drawable = dri2_dpy->vtbl->get_dri_drawable(surf);
609 
610    switch (attribute) {
611    case EGL_WIDTH:
612    case EGL_HEIGHT:
613       if (x11_get_drawable_info(drawable, &x, &y, &w, &h, dri2_surf)) {
614          bool changed = surf->Width != w || surf->Height != h;
615          surf->Width = w;
616          surf->Height = h;
617          if (changed && !dri2_dpy->swrast_not_kms)
618             dri_invalidate_drawable(drawable);
619       }
620       break;
621    default:
622       break;
623    }
624    return _eglQuerySurface(disp, surf, attribute, value);
625 }
626 
627 #ifdef HAVE_X11_DRI2
628 /**
629  * Process list of buffer received from the server
630  *
631  * Processes the list of buffers received in a reply from the server to either
632  * \c DRI2GetBuffers or \c DRI2GetBuffersWithFormat.
633  */
634 static void
dri2_x11_process_buffers(struct dri2_egl_surface * dri2_surf,xcb_dri2_dri2_buffer_t * buffers,unsigned count)635 dri2_x11_process_buffers(struct dri2_egl_surface *dri2_surf,
636                          xcb_dri2_dri2_buffer_t *buffers, unsigned count)
637 {
638    struct dri2_egl_display *dri2_dpy =
639       dri2_egl_display(dri2_surf->base.Resource.Display);
640    xcb_rectangle_t rectangle;
641 
642    dri2_surf->have_fake_front = false;
643 
644    /* This assumes the DRI2 buffer attachment tokens matches the
645     * __DRIbuffer tokens. */
646    for (unsigned i = 0; i < count; i++) {
647       dri2_surf->buffers[i].attachment = buffers[i].attachment;
648       dri2_surf->buffers[i].name = buffers[i].name;
649       dri2_surf->buffers[i].pitch = buffers[i].pitch;
650       dri2_surf->buffers[i].cpp = buffers[i].cpp;
651       dri2_surf->buffers[i].flags = buffers[i].flags;
652 
653       /* We only use the DRI drivers single buffer configs.  This
654        * means that if we try to render to a window, DRI2 will give us
655        * the fake front buffer, which we'll use as a back buffer.
656        * Note that EGL doesn't require that several clients rendering
657        * to the same window must see the same aux buffers. */
658       if (dri2_surf->buffers[i].attachment == __DRI_BUFFER_FAKE_FRONT_LEFT)
659          dri2_surf->have_fake_front = true;
660    }
661 
662    if (dri2_surf->region != XCB_NONE)
663       xcb_xfixes_destroy_region(dri2_dpy->conn, dri2_surf->region);
664 
665    rectangle.x = 0;
666    rectangle.y = 0;
667    rectangle.width = dri2_surf->base.Width;
668    rectangle.height = dri2_surf->base.Height;
669    dri2_surf->region = xcb_generate_id(dri2_dpy->conn);
670    xcb_xfixes_create_region(dri2_dpy->conn, dri2_surf->region, 1, &rectangle);
671 }
672 
673 static __DRIbuffer *
dri2_x11_get_buffers(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)674 dri2_x11_get_buffers(__DRIdrawable *driDrawable, int *width, int *height,
675                      unsigned int *attachments, int count, int *out_count,
676                      void *loaderPrivate)
677 {
678    struct dri2_egl_surface *dri2_surf = loaderPrivate;
679    struct dri2_egl_display *dri2_dpy =
680       dri2_egl_display(dri2_surf->base.Resource.Display);
681    xcb_dri2_dri2_buffer_t *buffers;
682    xcb_dri2_get_buffers_reply_t *reply;
683    xcb_dri2_get_buffers_cookie_t cookie;
684 
685    (void)driDrawable;
686 
687    cookie = xcb_dri2_get_buffers_unchecked(dri2_dpy->conn, dri2_surf->drawable,
688                                            count, count, attachments);
689    reply = xcb_dri2_get_buffers_reply(dri2_dpy->conn, cookie, NULL);
690    if (reply == NULL)
691       return NULL;
692    buffers = xcb_dri2_get_buffers_buffers(reply);
693    if (buffers == NULL) {
694       free(reply);
695       return NULL;
696    }
697 
698    *out_count = reply->count;
699    dri2_surf->base.Width = *width = reply->width;
700    dri2_surf->base.Height = *height = reply->height;
701    dri2_x11_process_buffers(dri2_surf, buffers, *out_count);
702 
703    free(reply);
704 
705    return dri2_surf->buffers;
706 }
707 
708 static __DRIbuffer *
dri2_x11_get_buffers_with_format(__DRIdrawable * driDrawable,int * width,int * height,unsigned int * attachments,int count,int * out_count,void * loaderPrivate)709 dri2_x11_get_buffers_with_format(__DRIdrawable *driDrawable, int *width,
710                                  int *height, unsigned int *attachments,
711                                  int count, int *out_count, void *loaderPrivate)
712 {
713    struct dri2_egl_surface *dri2_surf = loaderPrivate;
714    struct dri2_egl_display *dri2_dpy =
715       dri2_egl_display(dri2_surf->base.Resource.Display);
716    xcb_dri2_dri2_buffer_t *buffers;
717    xcb_dri2_get_buffers_with_format_reply_t *reply;
718    xcb_dri2_get_buffers_with_format_cookie_t cookie;
719    xcb_dri2_attach_format_t *format_attachments;
720 
721    (void)driDrawable;
722 
723    format_attachments = (xcb_dri2_attach_format_t *)attachments;
724    cookie = xcb_dri2_get_buffers_with_format_unchecked(
725       dri2_dpy->conn, dri2_surf->drawable, count, count, format_attachments);
726 
727    reply = xcb_dri2_get_buffers_with_format_reply(dri2_dpy->conn, cookie, NULL);
728    if (reply == NULL)
729       return NULL;
730 
731    buffers = xcb_dri2_get_buffers_with_format_buffers(reply);
732    dri2_surf->base.Width = *width = reply->width;
733    dri2_surf->base.Height = *height = reply->height;
734    *out_count = reply->count;
735    dri2_x11_process_buffers(dri2_surf, buffers, *out_count);
736 
737    free(reply);
738 
739    return dri2_surf->buffers;
740 }
741 
742 static void
dri2_x11_flush_front_buffer(__DRIdrawable * driDrawable,void * loaderPrivate)743 dri2_x11_flush_front_buffer(__DRIdrawable *driDrawable, void *loaderPrivate)
744 {
745    (void)driDrawable;
746 
747    /* FIXME: Does EGL support front buffer rendering at all? */
748 
749 #if 0
750    struct dri2_egl_surface *dri2_surf = loaderPrivate;
751 
752    dri2WaitGL(dri2_surf);
753 #else
754    (void)loaderPrivate;
755 #endif
756 }
757 
758 static int
dri2_x11_do_authenticate(struct dri2_egl_display * dri2_dpy,uint32_t id)759 dri2_x11_do_authenticate(struct dri2_egl_display *dri2_dpy, uint32_t id)
760 {
761    xcb_dri2_authenticate_reply_t *authenticate;
762    xcb_dri2_authenticate_cookie_t authenticate_cookie;
763    int ret = 0;
764 
765    authenticate_cookie = xcb_dri2_authenticate_unchecked(
766       dri2_dpy->conn, dri2_dpy->screen->root, id);
767    authenticate =
768       xcb_dri2_authenticate_reply(dri2_dpy->conn, authenticate_cookie, NULL);
769 
770    if (authenticate == NULL || !authenticate->authenticated)
771       ret = -1;
772 
773    free(authenticate);
774 
775    return ret;
776 }
777 
778 static EGLBoolean
dri2_x11_local_authenticate(struct dri2_egl_display * dri2_dpy)779 dri2_x11_local_authenticate(struct dri2_egl_display *dri2_dpy)
780 {
781 #ifdef HAVE_LIBDRM
782    drm_magic_t magic;
783 
784    if (drmGetMagic(dri2_dpy->fd_render_gpu, &magic)) {
785       _eglLog(_EGL_WARNING, "DRI2: failed to get drm magic");
786       return EGL_FALSE;
787    }
788 
789    if (dri2_x11_do_authenticate(dri2_dpy, magic) < 0) {
790       _eglLog(_EGL_WARNING, "DRI2: failed to authenticate");
791       return EGL_FALSE;
792    }
793 #endif
794    return EGL_TRUE;
795 }
796 
797 static EGLBoolean
dri2_x11_connect(struct dri2_egl_display * dri2_dpy)798 dri2_x11_connect(struct dri2_egl_display *dri2_dpy)
799 {
800    xcb_xfixes_query_version_reply_t *xfixes_query;
801    xcb_xfixes_query_version_cookie_t xfixes_query_cookie;
802    xcb_dri2_query_version_reply_t *dri2_query;
803    xcb_dri2_query_version_cookie_t dri2_query_cookie;
804    xcb_dri2_connect_reply_t *connect;
805    xcb_dri2_connect_cookie_t connect_cookie;
806    xcb_generic_error_t *error;
807    char *driver_name, *loader_driver_name, *device_name;
808    const xcb_query_extension_reply_t *extension;
809 
810    xcb_prefetch_extension_data(dri2_dpy->conn, &xcb_xfixes_id);
811    xcb_prefetch_extension_data(dri2_dpy->conn, &xcb_dri2_id);
812 
813    extension = xcb_get_extension_data(dri2_dpy->conn, &xcb_xfixes_id);
814    if (!(extension && extension->present))
815       return EGL_FALSE;
816 
817    extension = xcb_get_extension_data(dri2_dpy->conn, &xcb_dri2_id);
818    if (!(extension && extension->present))
819       return EGL_FALSE;
820 
821    xfixes_query_cookie = xcb_xfixes_query_version(
822       dri2_dpy->conn, XCB_XFIXES_MAJOR_VERSION, XCB_XFIXES_MINOR_VERSION);
823 
824    dri2_query_cookie = xcb_dri2_query_version(
825       dri2_dpy->conn, XCB_DRI2_MAJOR_VERSION, XCB_DRI2_MINOR_VERSION);
826 
827    connect_cookie = xcb_dri2_connect_unchecked(
828       dri2_dpy->conn, dri2_dpy->screen->root, XCB_DRI2_DRIVER_TYPE_DRI);
829 
830    xfixes_query = xcb_xfixes_query_version_reply(dri2_dpy->conn,
831                                                  xfixes_query_cookie, &error);
832    if (xfixes_query == NULL || error != NULL ||
833        xfixes_query->major_version < 2) {
834       _eglLog(_EGL_WARNING, "DRI2: failed to query xfixes version");
835       free(error);
836       free(xfixes_query);
837       return EGL_FALSE;
838    }
839    free(xfixes_query);
840 
841    dri2_query =
842       xcb_dri2_query_version_reply(dri2_dpy->conn, dri2_query_cookie, &error);
843    if (dri2_query == NULL || error != NULL) {
844       _eglLog(_EGL_WARNING, "DRI2: failed to query version");
845       free(error);
846       free(dri2_query);
847       return EGL_FALSE;
848    }
849    dri2_dpy->dri2_major = dri2_query->major_version;
850    dri2_dpy->dri2_minor = dri2_query->minor_version;
851    free(dri2_query);
852 
853    connect = xcb_dri2_connect_reply(dri2_dpy->conn, connect_cookie, NULL);
854    if (connect == NULL ||
855        connect->driver_name_length + connect->device_name_length == 0) {
856       _eglLog(_EGL_WARNING, "DRI2: failed to authenticate");
857       free(connect);
858       return EGL_FALSE;
859    }
860 
861    device_name = xcb_dri2_connect_device_name(connect);
862 
863    dri2_dpy->fd_render_gpu = loader_open_device(device_name);
864    if (dri2_dpy->fd_render_gpu == -1) {
865       _eglLog(_EGL_WARNING, "DRI2: could not open %s (%s)", device_name,
866               strerror(errno));
867       free(connect);
868       return EGL_FALSE;
869    }
870 
871    if (!dri2_x11_local_authenticate(dri2_dpy)) {
872       close(dri2_dpy->fd_render_gpu);
873       free(connect);
874       return EGL_FALSE;
875    }
876 
877    driver_name = xcb_dri2_connect_driver_name(connect);
878 
879    /* If Mesa knows about the appropriate driver for this fd, then trust it.
880     * Otherwise, default to the server's value.
881     */
882    loader_driver_name = loader_get_driver_for_fd(dri2_dpy->fd_render_gpu);
883    if (loader_driver_name) {
884       dri2_dpy->driver_name = loader_driver_name;
885    } else {
886       dri2_dpy->driver_name =
887          strndup(driver_name, xcb_dri2_connect_driver_name_length(connect));
888    }
889 
890    if (!strcmp(dri2_dpy->driver_name, "zink")) {
891       close(dri2_dpy->fd_render_gpu);
892       return EGL_FALSE;
893    }
894 
895    if (dri2_dpy->driver_name == NULL) {
896       close(dri2_dpy->fd_render_gpu);
897       free(connect);
898       return EGL_FALSE;
899    }
900 
901 #ifdef HAVE_WAYLAND_PLATFORM
902    dri2_dpy->device_name =
903       strndup(device_name, xcb_dri2_connect_device_name_length(connect));
904 #endif
905 
906    free(connect);
907 
908    return EGL_TRUE;
909 }
910 
911 static int
dri2_x11_authenticate(_EGLDisplay * disp,uint32_t id)912 dri2_x11_authenticate(_EGLDisplay *disp, uint32_t id)
913 {
914    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
915 
916    return dri2_x11_do_authenticate(dri2_dpy, id);
917 }
918 #endif
919 
920 static void
dri2_x11_add_configs_for_visuals(struct dri2_egl_display * dri2_dpy,_EGLDisplay * disp,bool supports_preserved)921 dri2_x11_add_configs_for_visuals(struct dri2_egl_display *dri2_dpy,
922                                  _EGLDisplay *disp, bool supports_preserved)
923 {
924    xcb_depth_iterator_t d;
925    xcb_visualtype_t *visuals;
926    EGLint surface_type;
927 
928    d = xcb_screen_allowed_depths_iterator(dri2_dpy->screen);
929 
930    surface_type = EGL_WINDOW_BIT | EGL_PIXMAP_BIT | EGL_PBUFFER_BIT;
931 
932    if (supports_preserved)
933       surface_type |= EGL_SWAP_BEHAVIOR_PRESERVED_BIT;
934 
935    while (d.rem > 0) {
936       EGLBoolean class_added[6] = {
937          0,
938       };
939 
940       visuals = xcb_depth_visuals(d.data);
941 
942       for (int i = 0; i < xcb_depth_visuals_length(d.data); i++) {
943          if (class_added[visuals[i]._class])
944             continue;
945 
946          class_added[visuals[i]._class] = EGL_TRUE;
947 
948          const int rgb_shifts[3] = {
949             ffs(visuals[i].red_mask) - 1,
950             ffs(visuals[i].green_mask) - 1,
951             ffs(visuals[i].blue_mask) - 1,
952          };
953 
954          const unsigned int rgb_sizes[3] = {
955             util_bitcount(visuals[i].red_mask),
956             util_bitcount(visuals[i].green_mask),
957             util_bitcount(visuals[i].blue_mask),
958          };
959 
960          const EGLint config_attrs[] = {
961             EGL_NATIVE_VISUAL_ID,
962             visuals[i].visual_id,
963             EGL_NATIVE_VISUAL_TYPE,
964             visuals[i]._class,
965             EGL_NONE,
966          };
967 
968          const EGLint config_attrs_2nd_group[] = {
969             EGL_NATIVE_VISUAL_ID,
970             visuals[i].visual_id,
971             EGL_NATIVE_VISUAL_TYPE,
972             visuals[i]._class,
973             EGL_CONFIG_SELECT_GROUP_EXT,
974             1,
975             EGL_NONE,
976          };
977 
978          for (int j = 0; dri2_dpy->driver_configs[j]; j++) {
979             const __DRIconfig *config = dri2_dpy->driver_configs[j];
980             int shifts[4];
981             unsigned int sizes[4];
982 
983             dri2_get_shifts_and_sizes(config, shifts, sizes);
984 
985             if (memcmp(shifts, rgb_shifts, sizeof(rgb_shifts)) != 0 ||
986                 memcmp(sizes, rgb_sizes, sizeof(rgb_sizes)) != 0) {
987                continue;
988             }
989 
990             /* Allows RGB visuals to match a 32-bit RGBA EGLConfig.
991              * Otherwise it will only match a 32-bit RGBA visual.  On a
992              * composited window manager on X11, this will make all of the
993              * EGLConfigs with destination alpha get blended by the
994              * compositor.  This is probably not what the application
995              * wants... especially on drivers that only have 32-bit RGBA
996              * EGLConfigs! */
997             if (sizes[3] != 0) {
998                unsigned int rgba_mask =
999                   ~(visuals[i].red_mask | visuals[i].green_mask |
1000                     visuals[i].blue_mask);
1001 
1002                if (shifts[3] != ffs(rgba_mask) - 1 ||
1003                    sizes[3] != util_bitcount(rgba_mask))
1004                   continue;
1005             }
1006 
1007             unsigned int bit_per_pixel = sizes[0] + sizes[1] + sizes[2] + sizes[3];
1008             if (sizes[3] != 0 && d.data->depth == bit_per_pixel) {
1009                dri2_add_config(disp, config, surface_type, config_attrs_2nd_group);
1010             } else {
1011                dri2_add_config(disp, config, surface_type, config_attrs);
1012             }
1013          }
1014       }
1015 
1016       xcb_depth_next(&d);
1017    }
1018 }
1019 
1020 #ifdef HAVE_X11_DRI2
1021 static EGLBoolean
dri2_copy_region(_EGLDisplay * disp,_EGLSurface * draw,xcb_xfixes_region_t region)1022 dri2_copy_region(_EGLDisplay *disp, _EGLSurface *draw,
1023                  xcb_xfixes_region_t region)
1024 {
1025    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1026    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1027    enum xcb_dri2_attachment_t render_attachment;
1028    xcb_dri2_copy_region_cookie_t cookie;
1029 
1030    /* No-op for a pixmap or pbuffer surface */
1031    if (draw->Type == EGL_PIXMAP_BIT || draw->Type == EGL_PBUFFER_BIT)
1032       return EGL_TRUE;
1033 
1034    assert(!dri2_dpy->kopper);
1035    dri_flush_drawable(dri2_surf->dri_drawable);
1036 
1037    if (dri2_surf->have_fake_front)
1038       render_attachment = XCB_DRI2_ATTACHMENT_BUFFER_FAKE_FRONT_LEFT;
1039    else
1040       render_attachment = XCB_DRI2_ATTACHMENT_BUFFER_BACK_LEFT;
1041 
1042    cookie = xcb_dri2_copy_region_unchecked(
1043       dri2_dpy->conn, dri2_surf->drawable, region,
1044       XCB_DRI2_ATTACHMENT_BUFFER_FRONT_LEFT, render_attachment);
1045    free(xcb_dri2_copy_region_reply(dri2_dpy->conn, cookie, NULL));
1046 
1047    return EGL_TRUE;
1048 }
1049 
1050 static int64_t
dri2_x11_swap_buffers_msc(_EGLDisplay * disp,_EGLSurface * draw,int64_t msc,int64_t divisor,int64_t remainder)1051 dri2_x11_swap_buffers_msc(_EGLDisplay *disp, _EGLSurface *draw, int64_t msc,
1052                           int64_t divisor, int64_t remainder)
1053 {
1054    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1055    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1056    uint32_t msc_hi = msc >> 32;
1057    uint32_t msc_lo = msc & 0xffffffff;
1058    uint32_t divisor_hi = divisor >> 32;
1059    uint32_t divisor_lo = divisor & 0xffffffff;
1060    uint32_t remainder_hi = remainder >> 32;
1061    uint32_t remainder_lo = remainder & 0xffffffff;
1062    xcb_dri2_swap_buffers_cookie_t cookie;
1063    xcb_dri2_swap_buffers_reply_t *reply;
1064    int64_t swap_count = -1;
1065 
1066    if (draw->SwapBehavior == EGL_BUFFER_PRESERVED ||
1067        !dri2_dpy->swap_available) {
1068       swap_count = dri2_copy_region(disp, draw, dri2_surf->region) ? 0 : -1;
1069    } else {
1070       dri2_flush_drawable_for_swapbuffers(disp, draw);
1071 
1072       cookie = xcb_dri2_swap_buffers_unchecked(
1073          dri2_dpy->conn, dri2_surf->drawable, msc_hi, msc_lo, divisor_hi,
1074          divisor_lo, remainder_hi, remainder_lo);
1075 
1076       reply = xcb_dri2_swap_buffers_reply(dri2_dpy->conn, cookie, NULL);
1077 
1078       if (reply) {
1079          swap_count = combine_u32_into_u64(reply->swap_hi, reply->swap_lo);
1080          free(reply);
1081       }
1082    }
1083 
1084    /* Since we aren't watching for the server's invalidate events like we're
1085     * supposed to (due to XCB providing no mechanism for filtering the events
1086     * the way xlib does), and SwapBuffers is a common cause of invalidate
1087     * events, just shove one down to the driver, even though we haven't told
1088     * the driver that we're the kind of loader that provides reliable
1089     * invalidate events.  This causes the driver to request buffers again at
1090     * its next draw, so that we get the correct buffers if a pageflip
1091     * happened.  The driver should still be using the viewport hack to catch
1092     * window resizes.
1093     */
1094    dri_invalidate_drawable(dri2_surf->dri_drawable);
1095 
1096    return swap_count;
1097 }
1098 #endif
1099 
1100 static EGLBoolean
dri2_x11_swap_buffers(_EGLDisplay * disp,_EGLSurface * draw)1101 dri2_x11_swap_buffers(_EGLDisplay *disp, _EGLSurface *draw)
1102 {
1103    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1104    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1105 
1106    if (dri2_dpy->kopper) {
1107       /* From the EGL 1.4 spec (page 52):
1108        *
1109        *     "The contents of ancillary buffers are always undefined
1110        *      after calling eglSwapBuffers."
1111        */
1112       kopperSwapBuffers(dri2_surf->dri_drawable,
1113                                     __DRI2_FLUSH_INVALIDATE_ANCILLARY);
1114       return EGL_TRUE;
1115    } else if (dri2_dpy->swrast) {
1116       /* aka the swrast path, which does the swap in the gallium driver. */
1117       driSwapBuffers(dri2_surf->dri_drawable);
1118       return EGL_TRUE;
1119    }
1120 
1121 #ifdef HAVE_X11_DRI2
1122    if (dri2_x11_swap_buffers_msc(disp, draw, 0, 0, 0) == -1) {
1123       /* Swap failed with a window drawable. */
1124       return _eglError(EGL_BAD_NATIVE_WINDOW, __func__);
1125    }
1126 #endif
1127    return EGL_TRUE;
1128 }
1129 
1130 #ifdef HAVE_X11_DRI2
1131 static EGLBoolean
dri2_x11_swap_buffers_region(_EGLDisplay * disp,_EGLSurface * draw,EGLint numRects,const EGLint * rects)1132 dri2_x11_swap_buffers_region(_EGLDisplay *disp, _EGLSurface *draw,
1133                              EGLint numRects, const EGLint *rects)
1134 {
1135    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1136    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1137    EGLBoolean ret;
1138    xcb_xfixes_region_t region;
1139    xcb_rectangle_t rectangles[16];
1140 
1141    if (numRects > (int)ARRAY_SIZE(rectangles))
1142       return dri2_copy_region(disp, draw, dri2_surf->region);
1143 
1144    for (int i = 0; i < numRects; i++) {
1145       rectangles[i].x = rects[i * 4];
1146       rectangles[i].y =
1147          dri2_surf->base.Height - rects[i * 4 + 1] - rects[i * 4 + 3];
1148       rectangles[i].width = rects[i * 4 + 2];
1149       rectangles[i].height = rects[i * 4 + 3];
1150    }
1151 
1152    region = xcb_generate_id(dri2_dpy->conn);
1153    xcb_xfixes_create_region(dri2_dpy->conn, region, numRects, rectangles);
1154    ret = dri2_copy_region(disp, draw, region);
1155    xcb_xfixes_destroy_region(dri2_dpy->conn, region);
1156 
1157    return ret;
1158 }
1159 
1160 static EGLBoolean
dri2_x11_post_sub_buffer(_EGLDisplay * disp,_EGLSurface * draw,EGLint x,EGLint y,EGLint width,EGLint height)1161 dri2_x11_post_sub_buffer(_EGLDisplay *disp, _EGLSurface *draw, EGLint x,
1162                          EGLint y, EGLint width, EGLint height)
1163 {
1164    const EGLint rect[4] = {x, y, width, height};
1165 
1166    if (x < 0 || y < 0 || width < 0 || height < 0)
1167       _eglError(EGL_BAD_PARAMETER, "eglPostSubBufferNV");
1168 
1169    return dri2_x11_swap_buffers_region(disp, draw, 1, rect);
1170 }
1171 #else
1172 #define dri2_x11_swap_buffers_region NULL
1173 #define dri2_x11_post_sub_buffer NULL
1174 #endif
1175 
1176 static EGLBoolean
dri2_x11_kopper_swap_buffers_with_damage(_EGLDisplay * disp,_EGLSurface * draw,const EGLint * rects,EGLint numRects)1177 dri2_x11_kopper_swap_buffers_with_damage(_EGLDisplay *disp, _EGLSurface *draw,
1178                                          const EGLint *rects, EGLint numRects)
1179 {
1180    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1181    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1182    /* swrast path unsupported for now */
1183    assert(dri2_dpy->kopper);
1184    if (numRects) {
1185       if (dri2_dpy->kopper)
1186          kopperSwapBuffersWithDamage(dri2_surf->dri_drawable, __DRI2_FLUSH_INVALIDATE_ANCILLARY, numRects, rects);
1187       else
1188          driSwapBuffersWithDamage(dri2_surf->dri_drawable, numRects, rects);
1189    } else {
1190       if (dri2_dpy->kopper)
1191          kopperSwapBuffers(dri2_surf->dri_drawable, __DRI2_FLUSH_INVALIDATE_ANCILLARY);
1192       else
1193          driSwapBuffers(dri2_surf->dri_drawable);
1194    }
1195    return EGL_TRUE;
1196 }
1197 
1198 static EGLBoolean
dri2_x11_swap_buffers_with_damage(_EGLDisplay * disp,_EGLSurface * draw,const EGLint * rects,EGLint numRects)1199 dri2_x11_swap_buffers_with_damage(_EGLDisplay *disp, _EGLSurface *draw,
1200                                   const EGLint *rects, EGLint numRects)
1201 {
1202    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(draw);
1203    if (numRects)
1204       driSwapBuffersWithDamage(dri2_surf->dri_drawable, numRects, rects);
1205    else
1206       driSwapBuffers(dri2_surf->dri_drawable);
1207    return EGL_TRUE;
1208 }
1209 
1210 static EGLBoolean
dri2_x11_swap_interval(_EGLDisplay * disp,_EGLSurface * surf,EGLint interval)1211 dri2_x11_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
1212 {
1213    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1214    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1215 
1216    if (dri2_dpy->kopper) {
1217       kopperSetSwapInterval(dri2_surf->dri_drawable, interval);
1218       return EGL_TRUE;
1219    }
1220 
1221 #ifdef HAVE_X11_DRI2
1222    if (dri2_dpy->swap_available)
1223       xcb_dri2_swap_interval(dri2_dpy->conn, dri2_surf->drawable, interval);
1224 #endif
1225 
1226    return EGL_TRUE;
1227 }
1228 
1229 static EGLBoolean
dri2_x11_copy_buffers(_EGLDisplay * disp,_EGLSurface * surf,void * native_pixmap_target)1230 dri2_x11_copy_buffers(_EGLDisplay *disp, _EGLSurface *surf,
1231                       void *native_pixmap_target)
1232 {
1233    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1234    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1235    xcb_gcontext_t gc;
1236    xcb_pixmap_t target;
1237 
1238    STATIC_ASSERT(sizeof(uintptr_t) == sizeof(native_pixmap_target));
1239    target = (uintptr_t)native_pixmap_target;
1240 
1241    if (!dri2_dpy->swrast_not_kms)
1242       dri_flush_drawable(dri2_surf->dri_drawable);
1243    else {
1244       /* This should not be a swapBuffers, because it could present an
1245        * incomplete frame, and it could invalidate the back buffer if it's not
1246        * preserved.  We really do want to flush.  But it ends up working out
1247        * okay-ish on swrast because those aren't invalidating the back buffer on
1248        * swap.
1249        */
1250       driSwapBuffers(dri2_surf->dri_drawable);
1251    }
1252 
1253    gc = xcb_generate_id(dri2_dpy->conn);
1254    xcb_create_gc(dri2_dpy->conn, gc, target, 0, NULL);
1255    xcb_copy_area(dri2_dpy->conn, dri2_surf->drawable, target, gc, 0, 0, 0, 0,
1256                  dri2_surf->base.Width, dri2_surf->base.Height);
1257    xcb_free_gc(dri2_dpy->conn, gc);
1258 
1259    return EGL_TRUE;
1260 }
1261 
1262 uint32_t
dri2_fourcc_for_depth(struct dri2_egl_display * dri2_dpy,uint32_t depth)1263 dri2_fourcc_for_depth(struct dri2_egl_display *dri2_dpy, uint32_t depth)
1264 {
1265    switch (depth) {
1266    case 16:
1267       return DRM_FORMAT_RGB565;
1268    case 24:
1269       return DRM_FORMAT_XRGB8888;
1270    case 30:
1271       /* Different preferred formats for different hw */
1272       if (dri2_x11_get_red_mask_for_depth(dri2_dpy, 30) == 0x3ff)
1273          return DRM_FORMAT_XBGR2101010;
1274       else
1275          return DRM_FORMAT_XRGB2101010;
1276    case 32:
1277       return DRM_FORMAT_ARGB8888;
1278    default:
1279       return DRM_FORMAT_INVALID;
1280    }
1281 }
1282 
1283 #ifdef HAVE_X11_DRI2
1284 static _EGLImage *
dri2_create_image_khr_pixmap(_EGLDisplay * disp,_EGLContext * ctx,EGLClientBuffer buffer,const EGLint * attr_list)1285 dri2_create_image_khr_pixmap(_EGLDisplay *disp, _EGLContext *ctx,
1286                              EGLClientBuffer buffer, const EGLint *attr_list)
1287 {
1288    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1289    struct dri2_egl_image *dri2_img;
1290    unsigned int attachments[1];
1291    xcb_drawable_t drawable;
1292    xcb_dri2_get_buffers_cookie_t buffers_cookie;
1293    xcb_dri2_get_buffers_reply_t *buffers_reply;
1294    xcb_dri2_dri2_buffer_t *buffers;
1295    xcb_get_geometry_cookie_t geometry_cookie;
1296    xcb_get_geometry_reply_t *geometry_reply;
1297    xcb_generic_error_t *error;
1298    int fourcc;
1299 
1300    (void)ctx;
1301 
1302    drawable = (xcb_drawable_t)(uintptr_t)buffer;
1303    xcb_dri2_create_drawable(dri2_dpy->conn, drawable);
1304    attachments[0] = XCB_DRI2_ATTACHMENT_BUFFER_FRONT_LEFT;
1305    buffers_cookie = xcb_dri2_get_buffers_unchecked(dri2_dpy->conn, drawable, 1,
1306                                                    1, attachments);
1307    geometry_cookie = xcb_get_geometry(dri2_dpy->conn, drawable);
1308    buffers_reply =
1309       xcb_dri2_get_buffers_reply(dri2_dpy->conn, buffers_cookie, NULL);
1310    if (buffers_reply == NULL)
1311       return NULL;
1312 
1313    buffers = xcb_dri2_get_buffers_buffers(buffers_reply);
1314    if (buffers == NULL) {
1315       free(buffers_reply);
1316       return NULL;
1317    }
1318 
1319    geometry_reply =
1320       xcb_get_geometry_reply(dri2_dpy->conn, geometry_cookie, &error);
1321    if (geometry_reply == NULL || error != NULL) {
1322       _eglError(EGL_BAD_ALLOC, "xcb_get_geometry");
1323       free(error);
1324       free(buffers_reply);
1325       free(geometry_reply);
1326       return NULL;
1327    }
1328 
1329    fourcc = dri2_fourcc_for_depth(dri2_dpy, geometry_reply->depth);
1330    if (fourcc == DRM_FORMAT_INVALID) {
1331       _eglError(EGL_BAD_PARAMETER,
1332                 "dri2_create_image_khr: unsupported pixmap depth");
1333       free(buffers_reply);
1334       free(geometry_reply);
1335       return NULL;
1336    }
1337 
1338    dri2_img = malloc(sizeof *dri2_img);
1339    if (!dri2_img) {
1340       free(buffers_reply);
1341       free(geometry_reply);
1342       _eglError(EGL_BAD_ALLOC, "dri2_create_image_khr");
1343       return EGL_NO_IMAGE_KHR;
1344    }
1345 
1346    _eglInitImage(&dri2_img->base, disp);
1347 
1348    dri2_img->dri_image = dri2_from_names(
1349       dri2_dpy->dri_screen_render_gpu, buffers_reply->width,
1350       buffers_reply->height, fourcc, (int *) &buffers[0].name, 1,
1351       (int *) &buffers[0].pitch, 0, dri2_img);
1352 
1353    free(buffers_reply);
1354    free(geometry_reply);
1355 
1356    return &dri2_img->base;
1357 }
1358 
1359 static _EGLImage *
dri2_x11_create_image_khr(_EGLDisplay * disp,_EGLContext * ctx,EGLenum target,EGLClientBuffer buffer,const EGLint * attr_list)1360 dri2_x11_create_image_khr(_EGLDisplay *disp, _EGLContext *ctx, EGLenum target,
1361                           EGLClientBuffer buffer, const EGLint *attr_list)
1362 {
1363    switch (target) {
1364    case EGL_NATIVE_PIXMAP_KHR:
1365       return dri2_create_image_khr_pixmap(disp, ctx, buffer, attr_list);
1366    default:
1367       return dri2_create_image_khr(disp, ctx, target, buffer, attr_list);
1368    }
1369 }
1370 
1371 static EGLBoolean
dri2_x11_get_sync_values(_EGLDisplay * display,_EGLSurface * surface,EGLuint64KHR * ust,EGLuint64KHR * msc,EGLuint64KHR * sbc)1372 dri2_x11_get_sync_values(_EGLDisplay *display, _EGLSurface *surface,
1373                          EGLuint64KHR *ust, EGLuint64KHR *msc,
1374                          EGLuint64KHR *sbc)
1375 {
1376    struct dri2_egl_display *dri2_dpy = dri2_egl_display(display);
1377    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surface);
1378    xcb_dri2_get_msc_cookie_t cookie;
1379    xcb_dri2_get_msc_reply_t *reply;
1380 
1381    cookie = xcb_dri2_get_msc(dri2_dpy->conn, dri2_surf->drawable);
1382    reply = xcb_dri2_get_msc_reply(dri2_dpy->conn, cookie, NULL);
1383 
1384    if (!reply)
1385       return _eglError(EGL_BAD_ACCESS, __func__);
1386 
1387    *ust = ((EGLuint64KHR)reply->ust_hi << 32) | reply->ust_lo;
1388    *msc = ((EGLuint64KHR)reply->msc_hi << 32) | reply->msc_lo;
1389    *sbc = ((EGLuint64KHR)reply->sbc_hi << 32) | reply->sbc_lo;
1390    free(reply);
1391 
1392    return EGL_TRUE;
1393 }
1394 #endif
1395 
1396 static int
box_intersection_area(int16_t a_x,int16_t a_y,int16_t a_width,int16_t a_height,int16_t b_x,int16_t b_y,int16_t b_width,int16_t b_height)1397 box_intersection_area(int16_t a_x, int16_t a_y, int16_t a_width,
1398                       int16_t a_height, int16_t b_x, int16_t b_y,
1399                       int16_t b_width, int16_t b_height)
1400 {
1401    int w = MIN2(a_x + a_width, b_x + b_width) - MAX2(a_x, b_x);
1402    int h = MIN2(a_y + a_height, b_y + b_height) - MAX2(a_y, b_y);
1403 
1404    return (w < 0 || h < 0) ? 0 : w * h;
1405 }
1406 
1407 EGLBoolean
dri2_x11_get_msc_rate(_EGLDisplay * display,_EGLSurface * surface,EGLint * numerator,EGLint * denominator)1408 dri2_x11_get_msc_rate(_EGLDisplay *display, _EGLSurface *surface,
1409                       EGLint *numerator, EGLint *denominator)
1410 {
1411    struct dri2_egl_display *dri2_dpy = dri2_egl_display(display);
1412 
1413 #ifdef HAVE_LIBDRM
1414    loader_update_screen_resources(&dri2_dpy->screen_resources);
1415 
1416    if (dri2_dpy->screen_resources.num_crtcs == 0) {
1417       /* If there's no CRTC active, use the present fake vblank of 1Hz */
1418       *numerator = 1;
1419       *denominator = 1;
1420       return EGL_TRUE;
1421    }
1422 
1423    /* Default to the first CRTC in the list */
1424    *numerator = dri2_dpy->screen_resources.crtcs[0].refresh_numerator;
1425    *denominator = dri2_dpy->screen_resources.crtcs[0].refresh_denominator;
1426 
1427    /* If there's only one active CRTC, we're done */
1428    if (dri2_dpy->screen_resources.num_crtcs == 1)
1429       return EGL_TRUE;
1430 #else
1431    *numerator = 0;
1432    *denominator = 1;
1433 #endif
1434 
1435 
1436    /* In a multi-monitor setup, look at each CRTC and perform a box
1437     * intersection between the CRTC and surface.  Use the CRTC whose
1438     * box intersection has the largest area.
1439     */
1440    if (surface->Type != EGL_WINDOW_BIT)
1441       return EGL_TRUE;
1442 
1443    xcb_window_t window = (uintptr_t)surface->NativeSurface;
1444 
1445    xcb_translate_coordinates_cookie_t cookie =
1446       xcb_translate_coordinates_unchecked(dri2_dpy->conn, window,
1447                                           dri2_dpy->screen->root, 0, 0);
1448    xcb_translate_coordinates_reply_t *reply =
1449       xcb_translate_coordinates_reply(dri2_dpy->conn, cookie, NULL);
1450 
1451    if (!reply) {
1452       _eglError(EGL_BAD_SURFACE,
1453                 "eglGetMscRateANGLE failed to translate coordinates");
1454       return EGL_FALSE;
1455    }
1456 
1457 #ifdef HAVE_LIBDRM
1458    int area = 0;
1459 
1460    for (unsigned c = 0; c < dri2_dpy->screen_resources.num_crtcs; c++) {
1461       struct loader_crtc_info *crtc = &dri2_dpy->screen_resources.crtcs[c];
1462 
1463       int c_area = box_intersection_area(
1464          reply->dst_x, reply->dst_y, surface->Width, surface->Height, crtc->x,
1465          crtc->y, crtc->width, crtc->height);
1466       if (c_area > area) {
1467          *numerator = crtc->refresh_numerator;
1468          *denominator = crtc->refresh_denominator;
1469          area = c_area;
1470       }
1471    }
1472 #endif
1473    /* If the window is entirely off-screen, then area will still be 0.
1474     * We defaulted to the first CRTC in the list's refresh rate, earlier.
1475     */
1476 
1477    return EGL_TRUE;
1478 }
1479 
1480 static EGLBoolean
dri2_kopper_swap_interval(_EGLDisplay * disp,_EGLSurface * surf,EGLint interval)1481 dri2_kopper_swap_interval(_EGLDisplay *disp, _EGLSurface *surf, EGLint interval)
1482 {
1483    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1484    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1485 
1486    /* This can legitimately be null for lavapipe */
1487    if (dri2_dpy->kopper)
1488       kopperSetSwapInterval(dri2_surf->dri_drawable, interval);
1489 
1490    return EGL_TRUE;
1491 }
1492 
1493 static _EGLSurface *
dri2_kopper_create_window_surface(_EGLDisplay * disp,_EGLConfig * conf,void * native_window,const EGLint * attrib_list)1494 dri2_kopper_create_window_surface(_EGLDisplay *disp, _EGLConfig *conf,
1495                                   void *native_window,
1496                                   const EGLint *attrib_list)
1497 {
1498    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1499    _EGLSurface *surf;
1500 
1501    surf = dri2_x11_create_surface(disp, EGL_WINDOW_BIT, conf, native_window,
1502                                   attrib_list);
1503    if (surf != NULL) {
1504       /* When we first create the DRI2 drawable, its swap interval on the
1505        * server side is 1.
1506        */
1507       surf->SwapInterval = 1;
1508 
1509       /* Override that with a driconf-set value. */
1510       dri2_kopper_swap_interval(disp, surf, dri2_dpy->default_swap_interval);
1511    }
1512 
1513    return surf;
1514 }
1515 
1516 static EGLint
dri2_kopper_query_buffer_age(_EGLDisplay * disp,_EGLSurface * surf)1517 dri2_kopper_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surf)
1518 {
1519    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1520    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1521 
1522    /* This can legitimately be null for lavapipe */
1523    if (dri2_dpy->kopper)
1524       return kopperQueryBufferAge(dri2_surf->dri_drawable);
1525    else
1526       return driSWRastQueryBufferAge(dri2_surf->dri_drawable);
1527 
1528    return 0;
1529 }
1530 
1531 static EGLint
dri2_swrast_query_buffer_age(_EGLDisplay * disp,_EGLSurface * surf)1532 dri2_swrast_query_buffer_age(_EGLDisplay *disp, _EGLSurface *surf)
1533 {
1534    struct dri2_egl_surface *dri2_surf = dri2_egl_surface(surf);
1535 
1536    return driSWRastQueryBufferAge(dri2_surf->dri_drawable);
1537 }
1538 
1539 static const struct dri2_egl_display_vtbl dri2_x11_swrast_display_vtbl = {
1540    .authenticate = NULL,
1541    .create_window_surface = dri2_x11_create_window_surface,
1542    .create_pixmap_surface = dri2_x11_create_pixmap_surface,
1543    .create_pbuffer_surface = dri2_x11_create_pbuffer_surface,
1544    .destroy_surface = dri2_x11_destroy_surface,
1545    .create_image = dri2_create_image_khr,
1546    .swap_buffers = dri2_x11_swap_buffers,
1547    .swap_buffers_region = dri2_x11_swap_buffers_region,
1548    .swap_buffers_with_damage = dri2_x11_swap_buffers_with_damage,
1549    .post_sub_buffer = dri2_x11_post_sub_buffer,
1550    .copy_buffers = dri2_x11_copy_buffers,
1551    .query_buffer_age = dri2_swrast_query_buffer_age,
1552    /* XXX: should really implement this since X11 has pixmaps */
1553    .query_surface = dri2_query_surface,
1554    .get_msc_rate = dri2_x11_get_msc_rate,
1555    .get_dri_drawable = dri2_surface_get_dri_drawable,
1556 };
1557 
1558 static const struct dri2_egl_display_vtbl dri2_x11_kopper_display_vtbl = {
1559    .authenticate = NULL,
1560    .create_window_surface = dri2_kopper_create_window_surface,
1561    .create_pixmap_surface = dri2_x11_create_pixmap_surface,
1562    .create_pbuffer_surface = dri2_x11_create_pbuffer_surface,
1563    .destroy_surface = dri2_x11_destroy_surface,
1564    .create_image = dri2_create_image_khr,
1565    .swap_interval = dri2_kopper_swap_interval,
1566    .swap_buffers = dri2_x11_swap_buffers,
1567    .swap_buffers_region = dri2_x11_swap_buffers_region,
1568    .swap_buffers_with_damage = dri2_x11_kopper_swap_buffers_with_damage,
1569    .post_sub_buffer = dri2_x11_post_sub_buffer,
1570    .copy_buffers = dri2_x11_copy_buffers,
1571    .query_buffer_age = dri2_kopper_query_buffer_age,
1572    /* XXX: should really implement this since X11 has pixmaps */
1573    .query_surface = dri2_query_surface,
1574    .get_msc_rate = dri2_x11_get_msc_rate,
1575    .get_dri_drawable = dri2_surface_get_dri_drawable,
1576 };
1577 
1578 #ifdef HAVE_X11_DRI2
1579 static const struct dri2_egl_display_vtbl dri2_x11_display_vtbl = {
1580    .authenticate = dri2_x11_authenticate,
1581    .create_window_surface = dri2_x11_create_window_surface,
1582    .create_pixmap_surface = dri2_x11_create_pixmap_surface,
1583    .create_pbuffer_surface = dri2_x11_create_pbuffer_surface,
1584    .destroy_surface = dri2_x11_destroy_surface,
1585    .create_image = dri2_x11_create_image_khr,
1586    .swap_interval = dri2_x11_swap_interval,
1587    .swap_buffers = dri2_x11_swap_buffers,
1588    .swap_buffers_region = dri2_x11_swap_buffers_region,
1589    .post_sub_buffer = dri2_x11_post_sub_buffer,
1590    .copy_buffers = dri2_x11_copy_buffers,
1591    .query_surface = dri2_query_surface,
1592    .get_sync_values = dri2_x11_get_sync_values,
1593    .get_msc_rate = dri2_x11_get_msc_rate,
1594    .get_dri_drawable = dri2_surface_get_dri_drawable,
1595 };
1596 #endif
1597 
1598 static const __DRIswrastLoaderExtension swrast_loader_extension = {
1599    .base = {__DRI_SWRAST_LOADER, 1},
1600 
1601    .getDrawableInfo = swrastGetDrawableInfo,
1602    .putImage = swrastPutImage,
1603    .putImage2 = swrastPutImage2,
1604    .getImage = swrastGetImage,
1605 };
1606 
1607 static const __DRIswrastLoaderExtension swrast_loader_shm_extension = {
1608    .base = {__DRI_SWRAST_LOADER, 4},
1609 
1610    .getDrawableInfo = swrastGetDrawableInfo,
1611    .putImage = swrastPutImage,
1612    .putImage2 = swrastPutImage2,
1613    .putImageShm = swrastPutImageShm,
1614    .getImage = swrastGetImage,
1615    .getImage2 = swrastGetImage2,
1616    .getImageShm = swrastGetImageShm,
1617 };
1618 
1619 static_assert(sizeof(struct kopper_vk_surface_create_storage) >=
1620                  sizeof(VkXcbSurfaceCreateInfoKHR),
1621               "");
1622 
1623 static void
kopperSetSurfaceCreateInfo(void * _draw,struct kopper_loader_info * ci)1624 kopperSetSurfaceCreateInfo(void *_draw, struct kopper_loader_info *ci)
1625 {
1626    struct dri2_egl_surface *dri2_surf = _draw;
1627    struct dri2_egl_display *dri2_dpy =
1628       dri2_egl_display(dri2_surf->base.Resource.Display);
1629    VkXcbSurfaceCreateInfoKHR *xcb = (VkXcbSurfaceCreateInfoKHR *)&ci->bos;
1630 
1631    if (dri2_surf->base.Type != EGL_WINDOW_BIT)
1632       return;
1633    xcb->sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR;
1634    xcb->pNext = NULL;
1635    xcb->flags = 0;
1636    xcb->connection = dri2_dpy->conn;
1637    xcb->window = dri2_surf->drawable;
1638    ci->has_alpha = dri2_surf->depth == 32;
1639    ci->present_opaque = dri2_surf->base.PresentOpaque;
1640 }
1641 
1642 static const __DRIkopperLoaderExtension kopper_loader_extension = {
1643    .base = {__DRI_KOPPER_LOADER, 1},
1644 
1645    .SetSurfaceCreateInfo = kopperSetSurfaceCreateInfo,
1646 };
1647 
1648 static const __DRIextension *kopper_loader_extensions[] = {
1649    &swrast_loader_extension.base,
1650    &image_lookup_extension.base,
1651    &kopper_loader_extension.base,
1652    &use_invalidate.base,
1653    NULL,
1654 };
1655 
1656 static const __DRIextension *swrast_loader_extensions[] = {
1657    &swrast_loader_extension.base,
1658    &image_lookup_extension.base,
1659    &kopper_loader_extension.base,
1660    NULL,
1661 };
1662 
1663 static const __DRIextension *swrast_loader_shm_extensions[] = {
1664    &swrast_loader_shm_extension.base,
1665    &image_lookup_extension.base,
1666    &kopper_loader_extension.base,
1667    NULL,
1668 };
1669 
1670 static int
dri2_find_screen_for_display(const _EGLDisplay * disp,int fallback_screen)1671 dri2_find_screen_for_display(const _EGLDisplay *disp, int fallback_screen)
1672 {
1673    const EGLAttrib *attr;
1674 
1675    if (!disp->Options.Attribs)
1676       return fallback_screen;
1677 
1678    for (attr = disp->Options.Attribs; attr[0] != EGL_NONE; attr += 2) {
1679       if (attr[0] == EGL_PLATFORM_X11_SCREEN_EXT ||
1680           attr[0] == EGL_PLATFORM_XCB_SCREEN_EXT)
1681          return attr[1];
1682    }
1683 
1684    return fallback_screen;
1685 }
1686 
1687 static EGLBoolean
dri2_get_xcb_connection(_EGLDisplay * disp,struct dri2_egl_display * dri2_dpy)1688 dri2_get_xcb_connection(_EGLDisplay *disp, struct dri2_egl_display *dri2_dpy)
1689 {
1690    xcb_screen_iterator_t s;
1691    int screen;
1692    const char *msg;
1693 
1694    disp->DriverData = (void *)dri2_dpy;
1695    if (disp->PlatformDisplay == NULL) {
1696       dri2_dpy->conn = xcb_connect(NULL, &screen);
1697       dri2_dpy->own_device = true;
1698       screen = dri2_find_screen_for_display(disp, screen);
1699    } else if (disp->Platform == _EGL_PLATFORM_X11) {
1700       Display *dpy = disp->PlatformDisplay;
1701       dri2_dpy->conn = XGetXCBConnection(dpy);
1702       screen = DefaultScreen(dpy);
1703    } else {
1704       /*   _EGL_PLATFORM_XCB   */
1705       dri2_dpy->conn = disp->PlatformDisplay;
1706       screen = dri2_find_screen_for_display(disp, 0);
1707    }
1708 
1709    if (!dri2_dpy->conn || xcb_connection_has_error(dri2_dpy->conn)) {
1710       msg = "xcb_connect failed";
1711       goto disconnect;
1712    }
1713 
1714    s = xcb_setup_roots_iterator(xcb_get_setup(dri2_dpy->conn));
1715    dri2_dpy->screen = get_xcb_screen(s, screen);
1716    if (!dri2_dpy->screen) {
1717       msg = "failed to get xcb screen";
1718       goto disconnect;
1719    }
1720 
1721    return EGL_TRUE;
1722 disconnect:
1723    if (disp->PlatformDisplay == NULL)
1724       xcb_disconnect(dri2_dpy->conn);
1725 
1726    return _eglError(EGL_BAD_ALLOC, msg);
1727 }
1728 
1729 static void
dri2_x11_setup_swap_interval(_EGLDisplay * disp)1730 dri2_x11_setup_swap_interval(_EGLDisplay *disp)
1731 {
1732    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1733    int arbitrary_max_interval = 1000;
1734 
1735    /* default behavior for no SwapBuffers support: no vblank syncing
1736     * either.
1737     */
1738    dri2_dpy->min_swap_interval = 0;
1739    dri2_dpy->max_swap_interval = 0;
1740    dri2_dpy->default_swap_interval = 0;
1741 
1742    if (!dri2_dpy->swap_available)
1743       return;
1744 
1745    /* If we do have swapbuffers, then we can support pretty much any swap
1746     * interval. Unless we're kopper, for now.
1747     */
1748    if (dri2_dpy->kopper)
1749       arbitrary_max_interval = 1;
1750 
1751    dri2_setup_swap_interval(disp, arbitrary_max_interval);
1752 }
1753 
1754 static bool
check_xshm(struct dri2_egl_display * dri2_dpy)1755 check_xshm(struct dri2_egl_display *dri2_dpy)
1756 {
1757    xcb_void_cookie_t cookie;
1758    xcb_generic_error_t *error;
1759    int ret = true;
1760    xcb_query_extension_cookie_t shm_cookie;
1761    xcb_query_extension_reply_t *shm_reply;
1762    bool has_mit_shm;
1763 
1764    shm_cookie = xcb_query_extension(dri2_dpy->conn, 7, "MIT-SHM");
1765    shm_reply = xcb_query_extension_reply(dri2_dpy->conn, shm_cookie, NULL);
1766 
1767    has_mit_shm = shm_reply->present;
1768    free(shm_reply);
1769    if (!has_mit_shm)
1770       return false;
1771 
1772    cookie = xcb_shm_detach_checked(dri2_dpy->conn, 0);
1773    if ((error = xcb_request_check(dri2_dpy->conn, cookie))) {
1774       /* BadRequest means we're a remote client. If we were local we'd
1775        * expect BadValue since 'info' has an invalid segment name.
1776        */
1777       if (error->error_code == BadRequest)
1778          ret = false;
1779       free(error);
1780    }
1781 
1782    return ret;
1783 }
1784 
1785 static EGLBoolean
dri2_x11_check_multibuffers(_EGLDisplay * disp)1786 dri2_x11_check_multibuffers(_EGLDisplay *disp)
1787 {
1788    struct dri2_egl_display *dri2_dpy = dri2_egl_display(disp);
1789 
1790 #ifdef HAVE_X11_DRM
1791    bool err;
1792    dri2_dpy->multibuffers_available = x11_dri3_check_multibuffer(dri2_dpy->conn, &err, &dri2_dpy->explicit_modifiers);
1793 
1794    if (disp->Options.Zink && !disp->Options.ForceSoftware &&
1795        !dri2_dpy->multibuffers_available &&
1796        !dri2_dpy->kopper_without_modifiers)
1797       return EGL_FALSE;
1798 #endif
1799 
1800    return EGL_TRUE;
1801 }
1802 
1803 static EGLBoolean
dri2_initialize_x11_swrast(_EGLDisplay * disp)1804 dri2_initialize_x11_swrast(_EGLDisplay *disp)
1805 {
1806    struct dri2_egl_display *dri2_dpy = dri2_display_create();
1807    if (!dri2_dpy)
1808       return EGL_FALSE;
1809 
1810    if (!dri2_get_xcb_connection(disp, dri2_dpy))
1811       goto cleanup;
1812 
1813    /*
1814     * Every hardware driver_name is set using strdup. Doing the same in
1815     * here will allow is to simply free the memory at dri2_terminate().
1816     */
1817    dri2_dpy->driver_name = strdup(disp->Options.Zink ? "zink" : "swrast");
1818 
1819 #ifdef HAVE_LIBDRM
1820    if (disp->Options.Zink &&
1821        !debug_get_bool_option("LIBGL_DRI3_DISABLE", false) &&
1822        (!disp->Options.Zink || !debug_get_bool_option("LIBGL_KOPPER_DRI2", false)))
1823       dri3_x11_connect(dri2_dpy, disp->Options.Zink, disp->Options.ForceSoftware);
1824 #endif
1825 
1826    if (!dri2_load_driver(disp))
1827       goto cleanup;
1828 
1829    if (disp->Options.Zink && !disp->Options.ForceSoftware) {
1830       dri2_dpy->loader_extensions = kopper_loader_extensions;
1831    } else if (check_xshm(dri2_dpy)) {
1832       dri2_dpy->loader_extensions = swrast_loader_shm_extensions;
1833    } else {
1834       dri2_dpy->loader_extensions = swrast_loader_extensions;
1835    }
1836 
1837    if (!dri2_x11_check_multibuffers(disp))
1838       goto cleanup;
1839 
1840    if (!dri2_create_screen(disp))
1841       goto cleanup;
1842 
1843    if (!dri2_setup_device(disp, disp->Options.ForceSoftware || dri2_dpy->kopper_without_modifiers)) {
1844       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to setup EGLDevice");
1845       goto cleanup;
1846    }
1847 
1848    dri2_setup_screen(disp);
1849 
1850    if (disp->Options.Zink) {
1851       /* kopper */
1852 #ifdef HAVE_WAYLAND_PLATFORM
1853       dri2_dpy->device_name = strdup("zink");
1854 #endif
1855       dri2_dpy->swap_available = EGL_TRUE;
1856       dri2_x11_setup_swap_interval(disp);
1857       if (dri2_dpy->fd_render_gpu == dri2_dpy->fd_display_gpu)
1858          disp->Extensions.KHR_image_pixmap = EGL_TRUE;
1859       disp->Extensions.NOK_texture_from_pixmap = EGL_TRUE;
1860       disp->Extensions.CHROMIUM_sync_control = EGL_TRUE;
1861       disp->Extensions.EXT_swap_buffers_with_damage = !!dri2_dpy->kopper;
1862 
1863 #ifdef HAVE_LIBDRM
1864       if (dri2_dpy->multibuffers_available)
1865          dri2_set_WL_bind_wayland_display(disp);
1866 #endif
1867    } else {
1868       disp->Extensions.EXT_swap_buffers_with_damage = EGL_TRUE;
1869    }
1870    disp->Extensions.EXT_buffer_age = EGL_TRUE;
1871    disp->Extensions.ANGLE_sync_control_rate = EGL_TRUE;
1872 
1873    dri2_x11_add_configs_for_visuals(dri2_dpy, disp, !disp->Options.Zink);
1874 
1875    /* Fill vtbl last to prevent accidentally calling virtual function during
1876     * initialization.
1877     */
1878    if (disp->Options.Zink)
1879       dri2_dpy->vtbl = &dri2_x11_kopper_display_vtbl;
1880    else
1881       dri2_dpy->vtbl = &dri2_x11_swrast_display_vtbl;
1882 
1883    return EGL_TRUE;
1884 
1885 cleanup:
1886    dri2_display_destroy(disp);
1887    return EGL_FALSE;
1888 }
1889 
1890 #ifdef HAVE_LIBDRM
1891 static const __DRIextension *dri3_image_loader_extensions[] = {
1892    &dri3_image_loader_extension.base,
1893    &image_lookup_extension.base,
1894    &use_invalidate.base,
1895    &background_callable_extension.base,
1896    NULL,
1897 };
1898 
1899 static enum dri2_egl_driver_fail
dri2_initialize_x11_dri3(_EGLDisplay * disp)1900 dri2_initialize_x11_dri3(_EGLDisplay *disp)
1901 {
1902    struct dri2_egl_display *dri2_dpy = dri2_display_create();
1903    enum dri2_egl_driver_fail status = DRI2_EGL_DRIVER_FAILED;
1904    if (!dri2_dpy)
1905       return DRI2_EGL_DRIVER_FAILED;
1906 
1907    if (!dri2_get_xcb_connection(disp, dri2_dpy))
1908       goto cleanup;
1909 
1910    status = dri3_x11_connect(dri2_dpy, disp->Options.Zink, disp->Options.ForceSoftware);
1911    if (status != DRI2_EGL_DRIVER_LOADED)
1912       goto cleanup;
1913 
1914    if (!dri2_load_driver(disp))
1915       goto cleanup;
1916 
1917    dri2_dpy->loader_extensions = dri3_image_loader_extensions;
1918 
1919    dri2_dpy->swap_available = true;
1920    dri2_dpy->invalidate_available = true;
1921 
1922    if (!dri2_x11_check_multibuffers(disp))
1923       goto cleanup;
1924 
1925    if (!dri2_create_screen(disp))
1926       goto cleanup;
1927 
1928    if (!dri2_setup_device(disp, false)) {
1929       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to setup EGLDevice");
1930       goto cleanup;
1931    }
1932 
1933    dri2_setup_screen(disp);
1934 
1935    dri2_x11_setup_swap_interval(disp);
1936 
1937    if (dri2_dpy->fd_render_gpu == dri2_dpy->fd_display_gpu)
1938       disp->Extensions.KHR_image_pixmap = EGL_TRUE;
1939    disp->Extensions.NOK_texture_from_pixmap = EGL_TRUE;
1940    disp->Extensions.CHROMIUM_sync_control = EGL_TRUE;
1941    disp->Extensions.ANGLE_sync_control_rate = EGL_TRUE;
1942    disp->Extensions.EXT_buffer_age = EGL_TRUE;
1943    disp->Extensions.EXT_swap_buffers_with_damage = EGL_TRUE;
1944 
1945    dri2_set_WL_bind_wayland_display(disp);
1946 
1947    dri2_x11_add_configs_for_visuals(dri2_dpy, disp, false);
1948 
1949    loader_init_screen_resources(&dri2_dpy->screen_resources, dri2_dpy->conn,
1950                                 dri2_dpy->screen);
1951 
1952    /* Fill vtbl last to prevent accidentally calling virtual function during
1953     * initialization.
1954     */
1955    dri2_dpy->vtbl = &dri3_x11_display_vtbl;
1956 
1957    _eglLog(_EGL_INFO, "Using DRI3");
1958 
1959    return DRI2_EGL_DRIVER_LOADED;
1960 
1961 cleanup:
1962    dri2_display_destroy(disp);
1963    return status == DRI2_EGL_DRIVER_PREFER_ZINK ?
1964           DRI2_EGL_DRIVER_PREFER_ZINK :
1965           DRI2_EGL_DRIVER_FAILED;
1966 }
1967 #endif
1968 
1969 #ifdef HAVE_X11_DRI2
1970 static const __DRIdri2LoaderExtension dri2_loader_extension_old = {
1971    .base = {__DRI_DRI2_LOADER, 2},
1972 
1973    .getBuffers = dri2_x11_get_buffers,
1974    .flushFrontBuffer = dri2_x11_flush_front_buffer,
1975    .getBuffersWithFormat = NULL,
1976 };
1977 
1978 static const __DRIdri2LoaderExtension dri2_loader_extension = {
1979    .base = {__DRI_DRI2_LOADER, 3},
1980 
1981    .getBuffers = dri2_x11_get_buffers,
1982    .flushFrontBuffer = dri2_x11_flush_front_buffer,
1983    .getBuffersWithFormat = dri2_x11_get_buffers_with_format,
1984 };
1985 
1986 static const __DRIextension *dri2_loader_extensions_old[] = {
1987    &dri2_loader_extension_old.base,
1988    &image_lookup_extension.base,
1989    &background_callable_extension.base,
1990    NULL,
1991 };
1992 
1993 static const __DRIextension *dri2_loader_extensions[] = {
1994    &dri2_loader_extension.base,
1995    &image_lookup_extension.base,
1996    &use_invalidate.base,
1997    &background_callable_extension.base,
1998    NULL,
1999 };
2000 
2001 static EGLBoolean
dri2_initialize_x11_dri2(_EGLDisplay * disp)2002 dri2_initialize_x11_dri2(_EGLDisplay *disp)
2003 {
2004    struct dri2_egl_display *dri2_dpy = dri2_display_create();
2005    if (!dri2_dpy)
2006       return EGL_FALSE;
2007 
2008    if (!dri2_get_xcb_connection(disp, dri2_dpy))
2009       goto cleanup;
2010 
2011    if (!dri2_x11_connect(dri2_dpy))
2012       goto cleanup;
2013 
2014    if (!dri2_load_driver(disp))
2015       goto cleanup;
2016 
2017    if (dri2_dpy->dri2_minor >= 1)
2018       dri2_dpy->loader_extensions = dri2_loader_extensions;
2019    else
2020       dri2_dpy->loader_extensions = dri2_loader_extensions_old;
2021 
2022    dri2_dpy->swap_available = (dri2_dpy->dri2_minor >= 2);
2023    dri2_dpy->invalidate_available = (dri2_dpy->dri2_minor >= 3);
2024 
2025    if (!dri2_x11_check_multibuffers(disp))
2026       goto cleanup;
2027 
2028    if (!dri2_create_screen(disp))
2029       goto cleanup;
2030 
2031    if (!dri2_setup_device(disp, false)) {
2032       _eglError(EGL_NOT_INITIALIZED, "DRI2: failed to setup EGLDevice");
2033       goto cleanup;
2034    }
2035 
2036    dri2_setup_screen(disp);
2037 
2038    dri2_x11_setup_swap_interval(disp);
2039 
2040    disp->Extensions.KHR_image_pixmap = EGL_TRUE;
2041    disp->Extensions.NOK_swap_region = EGL_TRUE;
2042    disp->Extensions.NOK_texture_from_pixmap = EGL_TRUE;
2043    disp->Extensions.NV_post_sub_buffer = EGL_TRUE;
2044    disp->Extensions.CHROMIUM_sync_control = EGL_TRUE;
2045    disp->Extensions.ANGLE_sync_control_rate = EGL_TRUE;
2046 
2047    dri2_set_WL_bind_wayland_display(disp);
2048 
2049    dri2_x11_add_configs_for_visuals(dri2_dpy, disp, true);
2050 
2051    /* Fill vtbl last to prevent accidentally calling virtual function during
2052     * initialization.
2053     */
2054    dri2_dpy->vtbl = &dri2_x11_display_vtbl;
2055 
2056    _eglLog(_EGL_INFO, "Using DRI2");
2057 
2058    return EGL_TRUE;
2059 
2060 cleanup:
2061    dri2_display_destroy(disp);
2062    return EGL_FALSE;
2063 }
2064 #endif
2065 
2066 EGLBoolean
dri2_initialize_x11(_EGLDisplay * disp)2067 dri2_initialize_x11(_EGLDisplay *disp)
2068 {
2069    enum dri2_egl_driver_fail status = DRI2_EGL_DRIVER_FAILED;
2070    if (disp->Options.ForceSoftware ||
2071        (disp->Options.Zink && !debug_get_bool_option("LIBGL_KOPPER_DISABLE", false)))
2072       return dri2_initialize_x11_swrast(disp);
2073 
2074 #ifdef HAVE_LIBDRM
2075    if (!debug_get_bool_option("LIBGL_DRI3_DISABLE", false)) {
2076       status = dri2_initialize_x11_dri3(disp);
2077       if (status == DRI2_EGL_DRIVER_LOADED)
2078          return EGL_TRUE;
2079    }
2080 #endif
2081 
2082 #ifdef HAVE_X11_DRI2
2083    if (!debug_get_bool_option("LIBGL_DRI2_DISABLE", false) &&
2084        status != DRI2_EGL_DRIVER_PREFER_ZINK)
2085       if (dri2_initialize_x11_dri2(disp))
2086          return EGL_TRUE;
2087 #endif
2088 
2089    return EGL_FALSE;
2090 }
2091 
2092 void
dri2_teardown_x11(struct dri2_egl_display * dri2_dpy)2093 dri2_teardown_x11(struct dri2_egl_display *dri2_dpy)
2094 {
2095 #ifdef HAVE_LIBDRM
2096    if (dri2_dpy->dri2_major >= 3)
2097       loader_destroy_screen_resources(&dri2_dpy->screen_resources);
2098 #endif
2099 
2100    if (dri2_dpy->own_device)
2101       xcb_disconnect(dri2_dpy->conn);
2102 }
2103