• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2015 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, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21  * IN THE SOFTWARE.
22  */
23 
24 #include <X11/Xlib-xcb.h>
25 #include <X11/xshmfence.h>
26 #include <xcb/xcb.h>
27 #include <xcb/dri3.h>
28 #include <xcb/present.h>
29 
30 #include "util/macros.h"
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <unistd.h>
34 #include <errno.h>
35 #include <string.h>
36 #include <fcntl.h>
37 #include <poll.h>
38 #include <xf86drm.h>
39 #include "drm-uapi/drm_fourcc.h"
40 #include "util/hash_table.h"
41 #include "util/xmlconfig.h"
42 
43 #include "vk_util.h"
44 #include "vk_enum_to_str.h"
45 #include "wsi_common_private.h"
46 #include "wsi_common_x11.h"
47 #include "wsi_common_queue.h"
48 
49 #define typed_memcpy(dest, src, count) ({ \
50    STATIC_ASSERT(sizeof(*src) == sizeof(*dest)); \
51    memcpy((dest), (src), (count) * sizeof(*(src))); \
52 })
53 
54 struct wsi_x11_connection {
55    bool has_dri3;
56    bool has_dri3_modifiers;
57    bool has_present;
58    bool is_proprietary_x11;
59 };
60 
61 struct wsi_x11 {
62    struct wsi_interface base;
63 
64    pthread_mutex_t                              mutex;
65    /* Hash table of xcb_connection -> wsi_x11_connection mappings */
66    struct hash_table *connections;
67 };
68 
69 
70 /** wsi_dri3_open
71  *
72  * Wrapper around xcb_dri3_open
73  */
74 static int
wsi_dri3_open(xcb_connection_t * conn,xcb_window_t root,uint32_t provider)75 wsi_dri3_open(xcb_connection_t *conn,
76 	      xcb_window_t root,
77 	      uint32_t provider)
78 {
79    xcb_dri3_open_cookie_t       cookie;
80    xcb_dri3_open_reply_t        *reply;
81    int                          fd;
82 
83    cookie = xcb_dri3_open(conn,
84                           root,
85                           provider);
86 
87    reply = xcb_dri3_open_reply(conn, cookie, NULL);
88    if (!reply)
89       return -1;
90 
91    if (reply->nfd != 1) {
92       free(reply);
93       return -1;
94    }
95 
96    fd = xcb_dri3_open_reply_fds(conn, reply)[0];
97    free(reply);
98    fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
99 
100    return fd;
101 }
102 
103 static bool
wsi_x11_check_dri3_compatible(const struct wsi_device * wsi_dev,xcb_connection_t * conn)104 wsi_x11_check_dri3_compatible(const struct wsi_device *wsi_dev,
105                               xcb_connection_t *conn)
106 {
107    xcb_screen_iterator_t screen_iter =
108       xcb_setup_roots_iterator(xcb_get_setup(conn));
109    xcb_screen_t *screen = screen_iter.data;
110 
111    int dri3_fd = wsi_dri3_open(conn, screen->root, None);
112    if (dri3_fd == -1)
113       return true;
114 
115    bool match = wsi_device_matches_drm_fd(wsi_dev, dri3_fd);
116 
117    close(dri3_fd);
118 
119    return match;
120 }
121 
122 static struct wsi_x11_connection *
wsi_x11_connection_create(struct wsi_device * wsi_dev,xcb_connection_t * conn)123 wsi_x11_connection_create(struct wsi_device *wsi_dev,
124                           xcb_connection_t *conn)
125 {
126    xcb_query_extension_cookie_t dri3_cookie, pres_cookie, amd_cookie, nv_cookie;
127    xcb_query_extension_reply_t *dri3_reply, *pres_reply, *amd_reply, *nv_reply;
128    bool has_dri3_v1_2 = false;
129    bool has_present_v1_2 = false;
130 
131    struct wsi_x11_connection *wsi_conn =
132       vk_alloc(&wsi_dev->instance_alloc, sizeof(*wsi_conn), 8,
133                 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
134    if (!wsi_conn)
135       return NULL;
136 
137    dri3_cookie = xcb_query_extension(conn, 4, "DRI3");
138    pres_cookie = xcb_query_extension(conn, 7, "Present");
139 
140    /* We try to be nice to users and emit a warning if they try to use a
141     * Vulkan application on a system without DRI3 enabled.  However, this ends
142     * up spewing the warning when a user has, for example, both Intel
143     * integrated graphics and a discrete card with proprietary drivers and are
144     * running on the discrete card with the proprietary DDX.  In this case, we
145     * really don't want to print the warning because it just confuses users.
146     * As a heuristic to detect this case, we check for a couple of proprietary
147     * X11 extensions.
148     */
149    amd_cookie = xcb_query_extension(conn, 11, "ATIFGLRXDRI");
150    nv_cookie = xcb_query_extension(conn, 10, "NV-CONTROL");
151 
152    dri3_reply = xcb_query_extension_reply(conn, dri3_cookie, NULL);
153    pres_reply = xcb_query_extension_reply(conn, pres_cookie, NULL);
154    amd_reply = xcb_query_extension_reply(conn, amd_cookie, NULL);
155    nv_reply = xcb_query_extension_reply(conn, nv_cookie, NULL);
156    if (!dri3_reply || !pres_reply) {
157       free(dri3_reply);
158       free(pres_reply);
159       free(amd_reply);
160       free(nv_reply);
161       vk_free(&wsi_dev->instance_alloc, wsi_conn);
162       return NULL;
163    }
164 
165    wsi_conn->has_dri3 = dri3_reply->present != 0;
166 #ifdef HAVE_DRI3_MODIFIERS
167    if (wsi_conn->has_dri3) {
168       xcb_dri3_query_version_cookie_t ver_cookie;
169       xcb_dri3_query_version_reply_t *ver_reply;
170 
171       ver_cookie = xcb_dri3_query_version(conn, 1, 2);
172       ver_reply = xcb_dri3_query_version_reply(conn, ver_cookie, NULL);
173       has_dri3_v1_2 =
174          (ver_reply->major_version > 1 || ver_reply->minor_version >= 2);
175       free(ver_reply);
176    }
177 #endif
178 
179    wsi_conn->has_present = pres_reply->present != 0;
180 #ifdef HAVE_DRI3_MODIFIERS
181    if (wsi_conn->has_present) {
182       xcb_present_query_version_cookie_t ver_cookie;
183       xcb_present_query_version_reply_t *ver_reply;
184 
185       ver_cookie = xcb_present_query_version(conn, 1, 2);
186       ver_reply = xcb_present_query_version_reply(conn, ver_cookie, NULL);
187       has_present_v1_2 =
188         (ver_reply->major_version > 1 || ver_reply->minor_version >= 2);
189       free(ver_reply);
190    }
191 #endif
192 
193    wsi_conn->has_dri3_modifiers = has_dri3_v1_2 && has_present_v1_2;
194    wsi_conn->is_proprietary_x11 = false;
195    if (amd_reply && amd_reply->present)
196       wsi_conn->is_proprietary_x11 = true;
197    if (nv_reply && nv_reply->present)
198       wsi_conn->is_proprietary_x11 = true;
199 
200    free(dri3_reply);
201    free(pres_reply);
202    free(amd_reply);
203    free(nv_reply);
204 
205    return wsi_conn;
206 }
207 
208 static void
wsi_x11_connection_destroy(struct wsi_device * wsi_dev,struct wsi_x11_connection * conn)209 wsi_x11_connection_destroy(struct wsi_device *wsi_dev,
210                            struct wsi_x11_connection *conn)
211 {
212    vk_free(&wsi_dev->instance_alloc, conn);
213 }
214 
215 static bool
wsi_x11_check_for_dri3(struct wsi_x11_connection * wsi_conn)216 wsi_x11_check_for_dri3(struct wsi_x11_connection *wsi_conn)
217 {
218   if (wsi_conn->has_dri3)
219     return true;
220   if (!wsi_conn->is_proprietary_x11) {
221     fprintf(stderr, "vulkan: No DRI3 support detected - required for presentation\n"
222                     "Note: you can probably enable DRI3 in your Xorg config\n");
223   }
224   return false;
225 }
226 
227 static struct wsi_x11_connection *
wsi_x11_get_connection(struct wsi_device * wsi_dev,xcb_connection_t * conn)228 wsi_x11_get_connection(struct wsi_device *wsi_dev,
229                        xcb_connection_t *conn)
230 {
231    struct wsi_x11 *wsi =
232       (struct wsi_x11 *)wsi_dev->wsi[VK_ICD_WSI_PLATFORM_XCB];
233 
234    pthread_mutex_lock(&wsi->mutex);
235 
236    struct hash_entry *entry = _mesa_hash_table_search(wsi->connections, conn);
237    if (!entry) {
238       /* We're about to make a bunch of blocking calls.  Let's drop the
239        * mutex for now so we don't block up too badly.
240        */
241       pthread_mutex_unlock(&wsi->mutex);
242 
243       struct wsi_x11_connection *wsi_conn =
244          wsi_x11_connection_create(wsi_dev, conn);
245       if (!wsi_conn)
246          return NULL;
247 
248       pthread_mutex_lock(&wsi->mutex);
249 
250       entry = _mesa_hash_table_search(wsi->connections, conn);
251       if (entry) {
252          /* Oops, someone raced us to it */
253          wsi_x11_connection_destroy(wsi_dev, wsi_conn);
254       } else {
255          entry = _mesa_hash_table_insert(wsi->connections, conn, wsi_conn);
256       }
257    }
258 
259    pthread_mutex_unlock(&wsi->mutex);
260 
261    return entry->data;
262 }
263 
264 static const VkFormat formats[] = {
265    VK_FORMAT_B8G8R8A8_SRGB,
266    VK_FORMAT_B8G8R8A8_UNORM,
267 };
268 
269 static const VkPresentModeKHR present_modes[] = {
270    VK_PRESENT_MODE_IMMEDIATE_KHR,
271    VK_PRESENT_MODE_MAILBOX_KHR,
272    VK_PRESENT_MODE_FIFO_KHR,
273    VK_PRESENT_MODE_FIFO_RELAXED_KHR,
274 };
275 
276 static xcb_screen_t *
get_screen_for_root(xcb_connection_t * conn,xcb_window_t root)277 get_screen_for_root(xcb_connection_t *conn, xcb_window_t root)
278 {
279    xcb_screen_iterator_t screen_iter =
280       xcb_setup_roots_iterator(xcb_get_setup(conn));
281 
282    for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
283       if (screen_iter.data->root == root)
284          return screen_iter.data;
285    }
286 
287    return NULL;
288 }
289 
290 static xcb_visualtype_t *
screen_get_visualtype(xcb_screen_t * screen,xcb_visualid_t visual_id,unsigned * depth)291 screen_get_visualtype(xcb_screen_t *screen, xcb_visualid_t visual_id,
292                       unsigned *depth)
293 {
294    xcb_depth_iterator_t depth_iter =
295       xcb_screen_allowed_depths_iterator(screen);
296 
297    for (; depth_iter.rem; xcb_depth_next (&depth_iter)) {
298       xcb_visualtype_iterator_t visual_iter =
299          xcb_depth_visuals_iterator (depth_iter.data);
300 
301       for (; visual_iter.rem; xcb_visualtype_next (&visual_iter)) {
302          if (visual_iter.data->visual_id == visual_id) {
303             if (depth)
304                *depth = depth_iter.data->depth;
305             return visual_iter.data;
306          }
307       }
308    }
309 
310    return NULL;
311 }
312 
313 static xcb_visualtype_t *
connection_get_visualtype(xcb_connection_t * conn,xcb_visualid_t visual_id,unsigned * depth)314 connection_get_visualtype(xcb_connection_t *conn, xcb_visualid_t visual_id,
315                           unsigned *depth)
316 {
317    xcb_screen_iterator_t screen_iter =
318       xcb_setup_roots_iterator(xcb_get_setup(conn));
319 
320    /* For this we have to iterate over all of the screens which is rather
321     * annoying.  Fortunately, there is probably only 1.
322     */
323    for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
324       xcb_visualtype_t *visual = screen_get_visualtype(screen_iter.data,
325                                                        visual_id, depth);
326       if (visual)
327          return visual;
328    }
329 
330    return NULL;
331 }
332 
333 static xcb_visualtype_t *
get_visualtype_for_window(xcb_connection_t * conn,xcb_window_t window,unsigned * depth)334 get_visualtype_for_window(xcb_connection_t *conn, xcb_window_t window,
335                           unsigned *depth)
336 {
337    xcb_query_tree_cookie_t tree_cookie;
338    xcb_get_window_attributes_cookie_t attrib_cookie;
339    xcb_query_tree_reply_t *tree;
340    xcb_get_window_attributes_reply_t *attrib;
341 
342    tree_cookie = xcb_query_tree(conn, window);
343    attrib_cookie = xcb_get_window_attributes(conn, window);
344 
345    tree = xcb_query_tree_reply(conn, tree_cookie, NULL);
346    attrib = xcb_get_window_attributes_reply(conn, attrib_cookie, NULL);
347    if (attrib == NULL || tree == NULL) {
348       free(attrib);
349       free(tree);
350       return NULL;
351    }
352 
353    xcb_window_t root = tree->root;
354    xcb_visualid_t visual_id = attrib->visual;
355    free(attrib);
356    free(tree);
357 
358    xcb_screen_t *screen = get_screen_for_root(conn, root);
359    if (screen == NULL)
360       return NULL;
361 
362    return screen_get_visualtype(screen, visual_id, depth);
363 }
364 
365 static bool
visual_has_alpha(xcb_visualtype_t * visual,unsigned depth)366 visual_has_alpha(xcb_visualtype_t *visual, unsigned depth)
367 {
368    uint32_t rgb_mask = visual->red_mask |
369                        visual->green_mask |
370                        visual->blue_mask;
371 
372    uint32_t all_mask = 0xffffffff >> (32 - depth);
373 
374    /* Do we have bits left over after RGB? */
375    return (all_mask & ~rgb_mask) != 0;
376 }
377 
wsi_get_physical_device_xcb_presentation_support(struct wsi_device * wsi_device,uint32_t queueFamilyIndex,xcb_connection_t * connection,xcb_visualid_t visual_id)378 VkBool32 wsi_get_physical_device_xcb_presentation_support(
379     struct wsi_device *wsi_device,
380     uint32_t                                    queueFamilyIndex,
381     xcb_connection_t*                           connection,
382     xcb_visualid_t                              visual_id)
383 {
384    struct wsi_x11_connection *wsi_conn =
385       wsi_x11_get_connection(wsi_device, connection);
386 
387    if (!wsi_conn)
388       return false;
389 
390    if (!wsi_x11_check_for_dri3(wsi_conn))
391       return false;
392 
393    unsigned visual_depth;
394    if (!connection_get_visualtype(connection, visual_id, &visual_depth))
395       return false;
396 
397    if (visual_depth != 24 && visual_depth != 32)
398       return false;
399 
400    return true;
401 }
402 
403 static xcb_connection_t*
x11_surface_get_connection(VkIcdSurfaceBase * icd_surface)404 x11_surface_get_connection(VkIcdSurfaceBase *icd_surface)
405 {
406    if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
407       return XGetXCBConnection(((VkIcdSurfaceXlib *)icd_surface)->dpy);
408    else
409       return ((VkIcdSurfaceXcb *)icd_surface)->connection;
410 }
411 
412 static xcb_window_t
x11_surface_get_window(VkIcdSurfaceBase * icd_surface)413 x11_surface_get_window(VkIcdSurfaceBase *icd_surface)
414 {
415    if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
416       return ((VkIcdSurfaceXlib *)icd_surface)->window;
417    else
418       return ((VkIcdSurfaceXcb *)icd_surface)->window;
419 }
420 
421 static VkResult
x11_surface_get_support(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,uint32_t queueFamilyIndex,VkBool32 * pSupported)422 x11_surface_get_support(VkIcdSurfaceBase *icd_surface,
423                         struct wsi_device *wsi_device,
424                         uint32_t queueFamilyIndex,
425                         VkBool32* pSupported)
426 {
427    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
428    xcb_window_t window = x11_surface_get_window(icd_surface);
429 
430    struct wsi_x11_connection *wsi_conn =
431       wsi_x11_get_connection(wsi_device, conn);
432    if (!wsi_conn)
433       return VK_ERROR_OUT_OF_HOST_MEMORY;
434 
435    if (!wsi_x11_check_for_dri3(wsi_conn)) {
436       *pSupported = false;
437       return VK_SUCCESS;
438    }
439 
440    unsigned visual_depth;
441    if (!get_visualtype_for_window(conn, window, &visual_depth)) {
442       *pSupported = false;
443       return VK_SUCCESS;
444    }
445 
446    if (visual_depth != 24 && visual_depth != 32) {
447       *pSupported = false;
448       return VK_SUCCESS;
449    }
450 
451    *pSupported = true;
452    return VK_SUCCESS;
453 }
454 
455 static uint32_t
x11_get_min_image_count(struct wsi_device * wsi_device)456 x11_get_min_image_count(struct wsi_device *wsi_device)
457 {
458    if (wsi_device->x11.override_minImageCount)
459       return wsi_device->x11.override_minImageCount;
460 
461    /* For IMMEDIATE and FIFO, most games work in a pipelined manner where the
462     * can produce frames at a rate of 1/MAX(CPU duration, GPU duration), but
463     * the render latency is CPU duration + GPU duration.
464     *
465     * This means that with scanout from pageflipping we need 3 frames to run
466     * full speed:
467     * 1) CPU rendering work
468     * 2) GPU rendering work
469     * 3) scanout
470     *
471     * Once we have a nonblocking acquire that returns a semaphore we can merge
472     * 1 and 3. Hence the ideal implementation needs only 2 images, but games
473     * cannot tellwe currently do not have an ideal implementation and that
474     * hence they need to allocate 3 images. So let us do it for them.
475     *
476     * This is a tradeoff as it uses more memory than needed for non-fullscreen
477     * and non-performance intensive applications.
478     */
479    return 3;
480 }
481 
482 static VkResult
x11_surface_get_capabilities(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,VkSurfaceCapabilitiesKHR * caps)483 x11_surface_get_capabilities(VkIcdSurfaceBase *icd_surface,
484                              struct wsi_device *wsi_device,
485                              VkSurfaceCapabilitiesKHR *caps)
486 {
487    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
488    xcb_window_t window = x11_surface_get_window(icd_surface);
489    xcb_get_geometry_cookie_t geom_cookie;
490    xcb_generic_error_t *err;
491    xcb_get_geometry_reply_t *geom;
492    unsigned visual_depth;
493 
494    geom_cookie = xcb_get_geometry(conn, window);
495 
496    /* This does a round-trip.  This is why we do get_geometry first and
497     * wait to read the reply until after we have a visual.
498     */
499    xcb_visualtype_t *visual =
500       get_visualtype_for_window(conn, window, &visual_depth);
501 
502    if (!visual)
503       return VK_ERROR_SURFACE_LOST_KHR;
504 
505    geom = xcb_get_geometry_reply(conn, geom_cookie, &err);
506    if (geom) {
507       VkExtent2D extent = { geom->width, geom->height };
508       caps->currentExtent = extent;
509       caps->minImageExtent = extent;
510       caps->maxImageExtent = extent;
511    } else {
512       /* This can happen if the client didn't wait for the configure event
513        * to come back from the compositor.  In that case, we don't know the
514        * size of the window so we just return valid "I don't know" stuff.
515        */
516       caps->currentExtent = (VkExtent2D) { UINT32_MAX, UINT32_MAX };
517       caps->minImageExtent = (VkExtent2D) { 1, 1 };
518       caps->maxImageExtent = (VkExtent2D) {
519          wsi_device->maxImageDimension2D,
520          wsi_device->maxImageDimension2D,
521       };
522    }
523    free(err);
524    free(geom);
525 
526    if (visual_has_alpha(visual, visual_depth)) {
527       caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
528                                       VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
529    } else {
530       caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
531                                       VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
532    }
533 
534    caps->minImageCount = x11_get_min_image_count(wsi_device);
535    /* There is no real maximum */
536    caps->maxImageCount = 0;
537 
538    caps->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
539    caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
540    caps->maxImageArrayLayers = 1;
541    caps->supportedUsageFlags =
542       VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
543       VK_IMAGE_USAGE_SAMPLED_BIT |
544       VK_IMAGE_USAGE_TRANSFER_DST_BIT |
545       VK_IMAGE_USAGE_STORAGE_BIT |
546       VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
547 
548    return VK_SUCCESS;
549 }
550 
551 static VkResult
x11_surface_get_capabilities2(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,const void * info_next,VkSurfaceCapabilities2KHR * caps)552 x11_surface_get_capabilities2(VkIcdSurfaceBase *icd_surface,
553                               struct wsi_device *wsi_device,
554                               const void *info_next,
555                               VkSurfaceCapabilities2KHR *caps)
556 {
557    assert(caps->sType == VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR);
558 
559    VkResult result =
560       x11_surface_get_capabilities(icd_surface, wsi_device,
561                                    &caps->surfaceCapabilities);
562 
563    vk_foreach_struct(ext, caps->pNext) {
564       switch (ext->sType) {
565       case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
566          VkSurfaceProtectedCapabilitiesKHR *protected = (void *)ext;
567          protected->supportsProtected = VK_FALSE;
568          break;
569       }
570 
571       default:
572          /* Ignored */
573          break;
574       }
575    }
576 
577    return result;
578 }
579 
580 static void
get_sorted_vk_formats(struct wsi_device * wsi_device,VkFormat * sorted_formats)581 get_sorted_vk_formats(struct wsi_device *wsi_device, VkFormat *sorted_formats)
582 {
583    memcpy(sorted_formats, formats, sizeof(formats));
584 
585    if (wsi_device->force_bgra8_unorm_first) {
586       for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
587          if (sorted_formats[i] == VK_FORMAT_B8G8R8A8_UNORM) {
588             sorted_formats[i] = sorted_formats[0];
589             sorted_formats[0] = VK_FORMAT_B8G8R8A8_UNORM;
590             break;
591          }
592       }
593    }
594 }
595 
596 static VkResult
x11_surface_get_formats(VkIcdSurfaceBase * surface,struct wsi_device * wsi_device,uint32_t * pSurfaceFormatCount,VkSurfaceFormatKHR * pSurfaceFormats)597 x11_surface_get_formats(VkIcdSurfaceBase *surface,
598                         struct wsi_device *wsi_device,
599                         uint32_t *pSurfaceFormatCount,
600                         VkSurfaceFormatKHR *pSurfaceFormats)
601 {
602    VK_OUTARRAY_MAKE(out, pSurfaceFormats, pSurfaceFormatCount);
603 
604    VkFormat sorted_formats[ARRAY_SIZE(formats)];
605    get_sorted_vk_formats(wsi_device, sorted_formats);
606 
607    for (unsigned i = 0; i < ARRAY_SIZE(sorted_formats); i++) {
608       vk_outarray_append(&out, f) {
609          f->format = sorted_formats[i];
610          f->colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
611       }
612    }
613 
614    return vk_outarray_status(&out);
615 }
616 
617 static VkResult
x11_surface_get_formats2(VkIcdSurfaceBase * surface,struct wsi_device * wsi_device,const void * info_next,uint32_t * pSurfaceFormatCount,VkSurfaceFormat2KHR * pSurfaceFormats)618 x11_surface_get_formats2(VkIcdSurfaceBase *surface,
619                         struct wsi_device *wsi_device,
620                         const void *info_next,
621                         uint32_t *pSurfaceFormatCount,
622                         VkSurfaceFormat2KHR *pSurfaceFormats)
623 {
624    VK_OUTARRAY_MAKE(out, pSurfaceFormats, pSurfaceFormatCount);
625 
626    VkFormat sorted_formats[ARRAY_SIZE(formats)];
627    get_sorted_vk_formats(wsi_device, sorted_formats);
628 
629    for (unsigned i = 0; i < ARRAY_SIZE(sorted_formats); i++) {
630       vk_outarray_append(&out, f) {
631          assert(f->sType == VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR);
632          f->surfaceFormat.format = sorted_formats[i];
633          f->surfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
634       }
635    }
636 
637    return vk_outarray_status(&out);
638 }
639 
640 static VkResult
x11_surface_get_present_modes(VkIcdSurfaceBase * surface,uint32_t * pPresentModeCount,VkPresentModeKHR * pPresentModes)641 x11_surface_get_present_modes(VkIcdSurfaceBase *surface,
642                               uint32_t *pPresentModeCount,
643                               VkPresentModeKHR *pPresentModes)
644 {
645    if (pPresentModes == NULL) {
646       *pPresentModeCount = ARRAY_SIZE(present_modes);
647       return VK_SUCCESS;
648    }
649 
650    *pPresentModeCount = MIN2(*pPresentModeCount, ARRAY_SIZE(present_modes));
651    typed_memcpy(pPresentModes, present_modes, *pPresentModeCount);
652 
653    return *pPresentModeCount < ARRAY_SIZE(present_modes) ?
654       VK_INCOMPLETE : VK_SUCCESS;
655 }
656 
657 static VkResult
x11_surface_get_present_rectangles(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,uint32_t * pRectCount,VkRect2D * pRects)658 x11_surface_get_present_rectangles(VkIcdSurfaceBase *icd_surface,
659                                    struct wsi_device *wsi_device,
660                                    uint32_t* pRectCount,
661                                    VkRect2D* pRects)
662 {
663    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
664    xcb_window_t window = x11_surface_get_window(icd_surface);
665    VK_OUTARRAY_MAKE(out, pRects, pRectCount);
666 
667    vk_outarray_append(&out, rect) {
668       xcb_generic_error_t *err = NULL;
669       xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(conn, window);
670       xcb_get_geometry_reply_t *geom =
671          xcb_get_geometry_reply(conn, geom_cookie, &err);
672       free(err);
673       if (geom) {
674          *rect = (VkRect2D) {
675             .offset = { 0, 0 },
676             .extent = { geom->width, geom->height },
677          };
678       } else {
679          /* This can happen if the client didn't wait for the configure event
680           * to come back from the compositor.  In that case, we don't know the
681           * size of the window so we just return valid "I don't know" stuff.
682           */
683          *rect = (VkRect2D) {
684             .offset = { 0, 0 },
685             .extent = { UINT32_MAX, UINT32_MAX },
686          };
687       }
688       free(geom);
689    }
690 
691    return vk_outarray_status(&out);
692 }
693 
wsi_create_xcb_surface(const VkAllocationCallbacks * pAllocator,const VkXcbSurfaceCreateInfoKHR * pCreateInfo,VkSurfaceKHR * pSurface)694 VkResult wsi_create_xcb_surface(const VkAllocationCallbacks *pAllocator,
695 				const VkXcbSurfaceCreateInfoKHR *pCreateInfo,
696 				VkSurfaceKHR *pSurface)
697 {
698    VkIcdSurfaceXcb *surface;
699 
700    surface = vk_alloc(pAllocator, sizeof *surface, 8,
701                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
702    if (surface == NULL)
703       return VK_ERROR_OUT_OF_HOST_MEMORY;
704 
705    surface->base.platform = VK_ICD_WSI_PLATFORM_XCB;
706    surface->connection = pCreateInfo->connection;
707    surface->window = pCreateInfo->window;
708 
709    *pSurface = VkIcdSurfaceBase_to_handle(&surface->base);
710    return VK_SUCCESS;
711 }
712 
wsi_create_xlib_surface(const VkAllocationCallbacks * pAllocator,const VkXlibSurfaceCreateInfoKHR * pCreateInfo,VkSurfaceKHR * pSurface)713 VkResult wsi_create_xlib_surface(const VkAllocationCallbacks *pAllocator,
714 				 const VkXlibSurfaceCreateInfoKHR *pCreateInfo,
715 				 VkSurfaceKHR *pSurface)
716 {
717    VkIcdSurfaceXlib *surface;
718 
719    surface = vk_alloc(pAllocator, sizeof *surface, 8,
720                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
721    if (surface == NULL)
722       return VK_ERROR_OUT_OF_HOST_MEMORY;
723 
724    surface->base.platform = VK_ICD_WSI_PLATFORM_XLIB;
725    surface->dpy = pCreateInfo->dpy;
726    surface->window = pCreateInfo->window;
727 
728    *pSurface = VkIcdSurfaceBase_to_handle(&surface->base);
729    return VK_SUCCESS;
730 }
731 
732 struct x11_image {
733    struct wsi_image                          base;
734    xcb_pixmap_t                              pixmap;
735    bool                                      busy;
736    struct xshmfence *                        shm_fence;
737    uint32_t                                  sync_fence;
738 };
739 
740 struct x11_swapchain {
741    struct wsi_swapchain                        base;
742 
743    bool                                         has_dri3_modifiers;
744 
745    xcb_connection_t *                           conn;
746    xcb_window_t                                 window;
747    xcb_gc_t                                     gc;
748    uint32_t                                     depth;
749    VkExtent2D                                   extent;
750 
751    xcb_present_event_t                          event_id;
752    xcb_special_event_t *                        special_event;
753    uint64_t                                     send_sbc;
754    uint64_t                                     last_present_msc;
755    uint32_t                                     stamp;
756    int                                          sent_image_count;
757 
758    bool                                         has_present_queue;
759    bool                                         has_acquire_queue;
760    VkResult                                     status;
761    xcb_present_complete_mode_t                  last_present_mode;
762    struct wsi_queue                             present_queue;
763    struct wsi_queue                             acquire_queue;
764    pthread_t                                    queue_manager;
765 
766    struct x11_image                             images[0];
767 };
768 VK_DEFINE_NONDISP_HANDLE_CASTS(x11_swapchain, base.base, VkSwapchainKHR,
769                                VK_OBJECT_TYPE_SWAPCHAIN_KHR)
770 
771 /**
772  * Update the swapchain status with the result of an operation, and return
773  * the combined status. The chain status will eventually be returned from
774  * AcquireNextImage and QueuePresent.
775  *
776  * We make sure to 'stick' more pessimistic statuses: an out-of-date error
777  * is permanent once seen, and every subsequent call will return this. If
778  * this has not been seen, success will be returned.
779  */
780 static VkResult
_x11_swapchain_result(struct x11_swapchain * chain,VkResult result,const char * file,int line)781 _x11_swapchain_result(struct x11_swapchain *chain, VkResult result,
782                       const char *file, int line)
783 {
784    /* Prioritise returning existing errors for consistency. */
785    if (chain->status < 0)
786       return chain->status;
787 
788    /* If we have a new error, mark it as permanent on the chain and return. */
789    if (result < 0) {
790 #ifndef NDEBUG
791       fprintf(stderr, "%s:%d: Swapchain status changed to %s\n",
792               file, line, vk_Result_to_str(result));
793 #endif
794       chain->status = result;
795       return result;
796    }
797 
798    /* Return temporary errors, but don't persist them. */
799    if (result == VK_TIMEOUT || result == VK_NOT_READY)
800       return result;
801 
802    /* Suboptimal isn't an error, but is a status which sticks to the swapchain
803     * and is always returned rather than success.
804     */
805    if (result == VK_SUBOPTIMAL_KHR) {
806 #ifndef NDEBUG
807       if (chain->status != VK_SUBOPTIMAL_KHR) {
808          fprintf(stderr, "%s:%d: Swapchain status changed to %s\n",
809                  file, line, vk_Result_to_str(result));
810       }
811 #endif
812       chain->status = result;
813       return result;
814    }
815 
816    /* No changes, so return the last status. */
817    return chain->status;
818 }
819 #define x11_swapchain_result(chain, result) \
820    _x11_swapchain_result(chain, result, __FILE__, __LINE__)
821 
822 static struct wsi_image *
x11_get_wsi_image(struct wsi_swapchain * wsi_chain,uint32_t image_index)823 x11_get_wsi_image(struct wsi_swapchain *wsi_chain, uint32_t image_index)
824 {
825    struct x11_swapchain *chain = (struct x11_swapchain *)wsi_chain;
826    return &chain->images[image_index].base;
827 }
828 
829 /**
830  * Process an X11 Present event. Does not update chain->status.
831  */
832 static VkResult
x11_handle_dri3_present_event(struct x11_swapchain * chain,xcb_present_generic_event_t * event)833 x11_handle_dri3_present_event(struct x11_swapchain *chain,
834                               xcb_present_generic_event_t *event)
835 {
836    switch (event->evtype) {
837    case XCB_PRESENT_CONFIGURE_NOTIFY: {
838       xcb_present_configure_notify_event_t *config = (void *) event;
839 
840       if (config->width != chain->extent.width ||
841           config->height != chain->extent.height)
842          return VK_ERROR_OUT_OF_DATE_KHR;
843 
844       break;
845    }
846 
847    case XCB_PRESENT_EVENT_IDLE_NOTIFY: {
848       xcb_present_idle_notify_event_t *idle = (void *) event;
849 
850       for (unsigned i = 0; i < chain->base.image_count; i++) {
851          if (chain->images[i].pixmap == idle->pixmap) {
852             chain->images[i].busy = false;
853             chain->sent_image_count--;
854             assert(chain->sent_image_count >= 0);
855             if (chain->has_acquire_queue)
856                wsi_queue_push(&chain->acquire_queue, i);
857             break;
858          }
859       }
860 
861       break;
862    }
863 
864    case XCB_PRESENT_EVENT_COMPLETE_NOTIFY: {
865       xcb_present_complete_notify_event_t *complete = (void *) event;
866       if (complete->kind == XCB_PRESENT_COMPLETE_KIND_PIXMAP)
867          chain->last_present_msc = complete->msc;
868 
869       VkResult result = VK_SUCCESS;
870 
871       /* The winsys is now trying to flip directly and cannot due to our
872        * configuration. Request the user reallocate.
873        */
874 #ifdef HAVE_DRI3_MODIFIERS
875       if (complete->mode == XCB_PRESENT_COMPLETE_MODE_SUBOPTIMAL_COPY &&
876           chain->last_present_mode != XCB_PRESENT_COMPLETE_MODE_SUBOPTIMAL_COPY)
877          result = VK_SUBOPTIMAL_KHR;
878 #endif
879 
880       /* When we go from flipping to copying, the odds are very likely that
881        * we could reallocate in a more optimal way if we didn't have to care
882        * about scanout, so we always do this.
883        */
884       if (complete->mode == XCB_PRESENT_COMPLETE_MODE_COPY &&
885           chain->last_present_mode == XCB_PRESENT_COMPLETE_MODE_FLIP)
886          result = VK_SUBOPTIMAL_KHR;
887 
888       chain->last_present_mode = complete->mode;
889       return result;
890    }
891 
892    default:
893       break;
894    }
895 
896    return VK_SUCCESS;
897 }
898 
899 
wsi_get_absolute_timeout(uint64_t timeout)900 static uint64_t wsi_get_absolute_timeout(uint64_t timeout)
901 {
902    uint64_t current_time = wsi_common_get_current_time();
903 
904    timeout = MIN2(UINT64_MAX - current_time, timeout);
905 
906    return current_time + timeout;
907 }
908 
909 static VkResult
x11_acquire_next_image_poll_x11(struct x11_swapchain * chain,uint32_t * image_index,uint64_t timeout)910 x11_acquire_next_image_poll_x11(struct x11_swapchain *chain,
911                                 uint32_t *image_index, uint64_t timeout)
912 {
913    xcb_generic_event_t *event;
914    struct pollfd pfds;
915    uint64_t atimeout;
916    while (1) {
917       for (uint32_t i = 0; i < chain->base.image_count; i++) {
918          if (!chain->images[i].busy) {
919             /* We found a non-busy image */
920             xshmfence_await(chain->images[i].shm_fence);
921             *image_index = i;
922             chain->images[i].busy = true;
923             return x11_swapchain_result(chain, VK_SUCCESS);
924          }
925       }
926 
927       xcb_flush(chain->conn);
928 
929       if (timeout == UINT64_MAX) {
930          event = xcb_wait_for_special_event(chain->conn, chain->special_event);
931          if (!event)
932             return x11_swapchain_result(chain, VK_ERROR_OUT_OF_DATE_KHR);
933       } else {
934          event = xcb_poll_for_special_event(chain->conn, chain->special_event);
935          if (!event) {
936             int ret;
937             if (timeout == 0)
938                return x11_swapchain_result(chain, VK_NOT_READY);
939 
940             atimeout = wsi_get_absolute_timeout(timeout);
941 
942             pfds.fd = xcb_get_file_descriptor(chain->conn);
943             pfds.events = POLLIN;
944             ret = poll(&pfds, 1, timeout / 1000 / 1000);
945             if (ret == 0)
946                return x11_swapchain_result(chain, VK_TIMEOUT);
947             if (ret == -1)
948                return x11_swapchain_result(chain, VK_ERROR_OUT_OF_DATE_KHR);
949 
950             /* If a non-special event happens, the fd will still
951              * poll. So recalculate the timeout now just in case.
952              */
953             uint64_t current_time = wsi_common_get_current_time();
954             if (atimeout > current_time)
955                timeout = atimeout - current_time;
956             else
957                timeout = 0;
958             continue;
959          }
960       }
961 
962       /* Update the swapchain status here. We may catch non-fatal errors here,
963        * in which case we need to update the status and continue.
964        */
965       VkResult result = x11_handle_dri3_present_event(chain, (void *)event);
966       free(event);
967       if (result < 0)
968          return x11_swapchain_result(chain, result);
969    }
970 }
971 
972 static VkResult
x11_acquire_next_image_from_queue(struct x11_swapchain * chain,uint32_t * image_index_out,uint64_t timeout)973 x11_acquire_next_image_from_queue(struct x11_swapchain *chain,
974                                   uint32_t *image_index_out, uint64_t timeout)
975 {
976    assert(chain->has_acquire_queue);
977 
978    uint32_t image_index;
979    VkResult result = wsi_queue_pull(&chain->acquire_queue,
980                                     &image_index, timeout);
981    if (result < 0 || result == VK_TIMEOUT) {
982       /* On error, the thread has shut down, so safe to update chain->status.
983        * Calling x11_swapchain_result with VK_TIMEOUT won't modify
984        * chain->status so that is also safe.
985        */
986       return x11_swapchain_result(chain, result);
987    } else if (chain->status < 0) {
988       return chain->status;
989    }
990 
991    assert(image_index < chain->base.image_count);
992    xshmfence_await(chain->images[image_index].shm_fence);
993 
994    *image_index_out = image_index;
995 
996    return chain->status;
997 }
998 
999 static VkResult
x11_present_to_x11_dri3(struct x11_swapchain * chain,uint32_t image_index,uint32_t target_msc)1000 x11_present_to_x11_dri3(struct x11_swapchain *chain, uint32_t image_index,
1001                         uint32_t target_msc)
1002 {
1003    struct x11_image *image = &chain->images[image_index];
1004 
1005    assert(image_index < chain->base.image_count);
1006 
1007    uint32_t options = XCB_PRESENT_OPTION_NONE;
1008 
1009    int64_t divisor = 0;
1010    int64_t remainder = 0;
1011 
1012    if (chain->base.present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR ||
1013        chain->base.present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
1014       options |= XCB_PRESENT_OPTION_ASYNC;
1015 
1016 #ifdef HAVE_DRI3_MODIFIERS
1017    if (chain->has_dri3_modifiers)
1018       options |= XCB_PRESENT_OPTION_SUBOPTIMAL;
1019 #endif
1020 
1021    /* Poll for any available event and update the swapchain status. This could
1022     * update the status of the swapchain to SUBOPTIMAL or OUT_OF_DATE if the
1023     * associated X11 surface has been resized.
1024     */
1025    xcb_generic_event_t *event;
1026    while ((event = xcb_poll_for_special_event(chain->conn, chain->special_event))) {
1027       VkResult result = x11_handle_dri3_present_event(chain, (void *)event);
1028       free(event);
1029       if (result < 0)
1030          return x11_swapchain_result(chain, result);
1031       x11_swapchain_result(chain, result);
1032    }
1033 
1034    xshmfence_reset(image->shm_fence);
1035 
1036    ++chain->sent_image_count;
1037    assert(chain->sent_image_count <= chain->base.image_count);
1038 
1039    ++chain->send_sbc;
1040 
1041    xcb_void_cookie_t cookie =
1042       xcb_present_pixmap(chain->conn,
1043                          chain->window,
1044                          image->pixmap,
1045                          (uint32_t) chain->send_sbc,
1046                          0,                                    /* valid */
1047                          0,                                    /* update */
1048                          0,                                    /* x_off */
1049                          0,                                    /* y_off */
1050                          XCB_NONE,                             /* target_crtc */
1051                          XCB_NONE,
1052                          image->sync_fence,
1053                          options,
1054                          target_msc,
1055                          divisor,
1056                          remainder, 0, NULL);
1057    xcb_discard_reply(chain->conn, cookie.sequence);
1058 
1059    xcb_flush(chain->conn);
1060 
1061    return x11_swapchain_result(chain, VK_SUCCESS);
1062 }
1063 
1064 static VkResult
x11_present_to_x11_sw(struct x11_swapchain * chain,uint32_t image_index,uint32_t target_msc)1065 x11_present_to_x11_sw(struct x11_swapchain *chain, uint32_t image_index,
1066                       uint32_t target_msc)
1067 {
1068    struct x11_image *image = &chain->images[image_index];
1069 
1070    xcb_void_cookie_t cookie;
1071    void *myptr;
1072    chain->base.wsi->MapMemory(chain->base.device,
1073                               image->base.memory,
1074                               0, 0, 0, &myptr);
1075 
1076    cookie = xcb_put_image(chain->conn, XCB_IMAGE_FORMAT_Z_PIXMAP,
1077                           chain->window,
1078                           chain->gc,
1079 			  image->base.row_pitches[0] / 4,
1080                           chain->extent.height,
1081                           0,0,0,24,
1082                           image->base.row_pitches[0] * chain->extent.height,
1083                           myptr);
1084 
1085    chain->base.wsi->UnmapMemory(chain->base.device, image->base.memory);
1086    xcb_discard_reply(chain->conn, cookie.sequence);
1087    xcb_flush(chain->conn);
1088    return x11_swapchain_result(chain, VK_SUCCESS);
1089 }
1090 static VkResult
x11_present_to_x11(struct x11_swapchain * chain,uint32_t image_index,uint32_t target_msc)1091 x11_present_to_x11(struct x11_swapchain *chain, uint32_t image_index,
1092                    uint32_t target_msc)
1093 {
1094    if (chain->base.wsi->sw)
1095       return x11_present_to_x11_sw(chain, image_index, target_msc);
1096    return x11_present_to_x11_dri3(chain, image_index, target_msc);
1097 }
1098 
1099 static VkResult
x11_acquire_next_image(struct wsi_swapchain * anv_chain,const VkAcquireNextImageInfoKHR * info,uint32_t * image_index)1100 x11_acquire_next_image(struct wsi_swapchain *anv_chain,
1101                        const VkAcquireNextImageInfoKHR *info,
1102                        uint32_t *image_index)
1103 {
1104    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1105    uint64_t timeout = info->timeout;
1106 
1107    /* If the swapchain is in an error state, don't go any further. */
1108    if (chain->status < 0)
1109       return chain->status;
1110 
1111    if (chain->base.wsi->sw) {
1112       *image_index = 0;
1113       return VK_SUCCESS;
1114    }
1115    if (chain->has_acquire_queue) {
1116       return x11_acquire_next_image_from_queue(chain, image_index, timeout);
1117    } else {
1118       return x11_acquire_next_image_poll_x11(chain, image_index, timeout);
1119    }
1120 }
1121 
1122 static VkResult
x11_queue_present(struct wsi_swapchain * anv_chain,uint32_t image_index,const VkPresentRegionKHR * damage)1123 x11_queue_present(struct wsi_swapchain *anv_chain,
1124                   uint32_t image_index,
1125                   const VkPresentRegionKHR *damage)
1126 {
1127    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1128 
1129    /* If the swapchain is in an error state, don't go any further. */
1130    if (chain->status < 0)
1131       return chain->status;
1132 
1133    chain->images[image_index].busy = true;
1134    if (chain->has_present_queue) {
1135       wsi_queue_push(&chain->present_queue, image_index);
1136       return chain->status;
1137    } else {
1138       return x11_present_to_x11(chain, image_index, 0);
1139    }
1140 }
1141 
1142 static void *
x11_manage_fifo_queues(void * state)1143 x11_manage_fifo_queues(void *state)
1144 {
1145    struct x11_swapchain *chain = state;
1146    VkResult result = VK_SUCCESS;
1147 
1148    assert(chain->has_present_queue);
1149    while (chain->status >= 0) {
1150       /* We can block here unconditionally because after an image was sent to
1151        * the server (later on in this loop) we ensure at least one image is
1152        * acquirable by the consumer or wait there on such an event.
1153        */
1154       uint32_t image_index = 0;
1155       result = wsi_queue_pull(&chain->present_queue, &image_index, INT64_MAX);
1156       assert(result != VK_TIMEOUT);
1157       if (result < 0) {
1158          goto fail;
1159       } else if (chain->status < 0) {
1160          /* The status can change underneath us if the swapchain is destroyed
1161           * from another thread.
1162           */
1163          return NULL;
1164       }
1165 
1166       if (chain->base.present_mode == VK_PRESENT_MODE_MAILBOX_KHR) {
1167          result = chain->base.wsi->WaitForFences(chain->base.device, 1,
1168                                         &chain->base.fences[image_index],
1169                                         true, UINT64_MAX);
1170          if (result != VK_SUCCESS) {
1171             result = VK_ERROR_OUT_OF_DATE_KHR;
1172             goto fail;
1173          }
1174       }
1175 
1176       uint64_t target_msc = 0;
1177       if (chain->has_acquire_queue)
1178          target_msc = chain->last_present_msc + 1;
1179 
1180       result = x11_present_to_x11(chain, image_index, target_msc);
1181       if (result < 0)
1182          goto fail;
1183 
1184       if (chain->has_acquire_queue) {
1185          /* Wait for our presentation to occur and ensure we have at least one
1186           * image that can be acquired by the client afterwards. This ensures we
1187           * can pull on the present-queue on the next loop.
1188           */
1189          while (chain->last_present_msc < target_msc ||
1190                 chain->sent_image_count == chain->base.image_count) {
1191             xcb_generic_event_t *event =
1192                xcb_wait_for_special_event(chain->conn, chain->special_event);
1193             if (!event) {
1194                result = VK_ERROR_OUT_OF_DATE_KHR;
1195                goto fail;
1196             }
1197 
1198             result = x11_handle_dri3_present_event(chain, (void *)event);
1199             free(event);
1200             if (result < 0)
1201                goto fail;
1202          }
1203       }
1204    }
1205 
1206 fail:
1207    x11_swapchain_result(chain, result);
1208    if (chain->has_acquire_queue)
1209       wsi_queue_push(&chain->acquire_queue, UINT32_MAX);
1210 
1211    return NULL;
1212 }
1213 
1214 static VkResult
x11_image_init(VkDevice device_h,struct x11_swapchain * chain,const VkSwapchainCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,const uint64_t * const * modifiers,const uint32_t * num_modifiers,int num_tranches,struct x11_image * image)1215 x11_image_init(VkDevice device_h, struct x11_swapchain *chain,
1216                const VkSwapchainCreateInfoKHR *pCreateInfo,
1217                const VkAllocationCallbacks* pAllocator,
1218                const uint64_t *const *modifiers,
1219                const uint32_t *num_modifiers,
1220                int num_tranches, struct x11_image *image)
1221 {
1222    xcb_void_cookie_t cookie;
1223    VkResult result;
1224    uint32_t bpp = 32;
1225 
1226    if (chain->base.use_prime_blit) {
1227       bool use_modifier = num_tranches > 0;
1228       result = wsi_create_prime_image(&chain->base, pCreateInfo, use_modifier, &image->base);
1229    } else {
1230       result = wsi_create_native_image(&chain->base, pCreateInfo,
1231                                        num_tranches, num_modifiers, modifiers,
1232                                        &image->base);
1233    }
1234    if (result < 0)
1235       return result;
1236 
1237    if (chain->base.wsi->sw) {
1238       image->busy = false;
1239       return VK_SUCCESS;
1240    }
1241    image->pixmap = xcb_generate_id(chain->conn);
1242 
1243 #ifdef HAVE_DRI3_MODIFIERS
1244    if (image->base.drm_modifier != DRM_FORMAT_MOD_INVALID) {
1245       /* If the image has a modifier, we must have DRI3 v1.2. */
1246       assert(chain->has_dri3_modifiers);
1247 
1248       cookie =
1249          xcb_dri3_pixmap_from_buffers_checked(chain->conn,
1250                                               image->pixmap,
1251                                               chain->window,
1252                                               image->base.num_planes,
1253                                               pCreateInfo->imageExtent.width,
1254                                               pCreateInfo->imageExtent.height,
1255                                               image->base.row_pitches[0],
1256                                               image->base.offsets[0],
1257                                               image->base.row_pitches[1],
1258                                               image->base.offsets[1],
1259                                               image->base.row_pitches[2],
1260                                               image->base.offsets[2],
1261                                               image->base.row_pitches[3],
1262                                               image->base.offsets[3],
1263                                               chain->depth, bpp,
1264                                               image->base.drm_modifier,
1265                                               image->base.fds);
1266    } else
1267 #endif
1268    {
1269       /* Without passing modifiers, we can't have multi-plane RGB images. */
1270       assert(image->base.num_planes == 1);
1271 
1272       cookie =
1273          xcb_dri3_pixmap_from_buffer_checked(chain->conn,
1274                                              image->pixmap,
1275                                              chain->window,
1276                                              image->base.sizes[0],
1277                                              pCreateInfo->imageExtent.width,
1278                                              pCreateInfo->imageExtent.height,
1279                                              image->base.row_pitches[0],
1280                                              chain->depth, bpp,
1281                                              image->base.fds[0]);
1282    }
1283 
1284    xcb_discard_reply(chain->conn, cookie.sequence);
1285 
1286    /* XCB has now taken ownership of the FDs. */
1287    for (int i = 0; i < image->base.num_planes; i++)
1288       image->base.fds[i] = -1;
1289 
1290    int fence_fd = xshmfence_alloc_shm();
1291    if (fence_fd < 0)
1292       goto fail_pixmap;
1293 
1294    image->shm_fence = xshmfence_map_shm(fence_fd);
1295    if (image->shm_fence == NULL)
1296       goto fail_shmfence_alloc;
1297 
1298    image->sync_fence = xcb_generate_id(chain->conn);
1299    xcb_dri3_fence_from_fd(chain->conn,
1300                           image->pixmap,
1301                           image->sync_fence,
1302                           false,
1303                           fence_fd);
1304 
1305    image->busy = false;
1306    xshmfence_trigger(image->shm_fence);
1307 
1308    return VK_SUCCESS;
1309 
1310 fail_shmfence_alloc:
1311    close(fence_fd);
1312 
1313 fail_pixmap:
1314    cookie = xcb_free_pixmap(chain->conn, image->pixmap);
1315    xcb_discard_reply(chain->conn, cookie.sequence);
1316 
1317    wsi_destroy_image(&chain->base, &image->base);
1318 
1319    return result;
1320 }
1321 
1322 static void
x11_image_finish(struct x11_swapchain * chain,const VkAllocationCallbacks * pAllocator,struct x11_image * image)1323 x11_image_finish(struct x11_swapchain *chain,
1324                  const VkAllocationCallbacks* pAllocator,
1325                  struct x11_image *image)
1326 {
1327    xcb_void_cookie_t cookie;
1328 
1329    if (!chain->base.wsi->sw) {
1330       cookie = xcb_sync_destroy_fence(chain->conn, image->sync_fence);
1331       xcb_discard_reply(chain->conn, cookie.sequence);
1332       xshmfence_unmap_shm(image->shm_fence);
1333 
1334       cookie = xcb_free_pixmap(chain->conn, image->pixmap);
1335       xcb_discard_reply(chain->conn, cookie.sequence);
1336    }
1337 
1338    wsi_destroy_image(&chain->base, &image->base);
1339 }
1340 
1341 static void
wsi_x11_get_dri3_modifiers(struct wsi_x11_connection * wsi_conn,xcb_connection_t * conn,xcb_window_t window,uint8_t depth,uint8_t bpp,VkCompositeAlphaFlagsKHR vk_alpha,uint64_t ** modifiers_in,uint32_t * num_modifiers_in,uint32_t * num_tranches_in,const VkAllocationCallbacks * pAllocator)1342 wsi_x11_get_dri3_modifiers(struct wsi_x11_connection *wsi_conn,
1343                            xcb_connection_t *conn, xcb_window_t window,
1344                            uint8_t depth, uint8_t bpp,
1345                            VkCompositeAlphaFlagsKHR vk_alpha,
1346                            uint64_t **modifiers_in, uint32_t *num_modifiers_in,
1347                            uint32_t *num_tranches_in,
1348                            const VkAllocationCallbacks *pAllocator)
1349 {
1350    if (!wsi_conn->has_dri3_modifiers)
1351       goto out;
1352 
1353 #ifdef HAVE_DRI3_MODIFIERS
1354    xcb_generic_error_t *error = NULL;
1355    xcb_dri3_get_supported_modifiers_cookie_t mod_cookie =
1356       xcb_dri3_get_supported_modifiers(conn, window, depth, bpp);
1357    xcb_dri3_get_supported_modifiers_reply_t *mod_reply =
1358       xcb_dri3_get_supported_modifiers_reply(conn, mod_cookie, &error);
1359    free(error);
1360 
1361    if (!mod_reply || (mod_reply->num_window_modifiers == 0 &&
1362                       mod_reply->num_screen_modifiers == 0)) {
1363       free(mod_reply);
1364       goto out;
1365    }
1366 
1367    uint32_t n = 0;
1368    uint32_t counts[2];
1369    uint64_t *modifiers[2];
1370 
1371    if (mod_reply->num_window_modifiers) {
1372       counts[n] = mod_reply->num_window_modifiers;
1373       modifiers[n] = vk_alloc(pAllocator,
1374                               counts[n] * sizeof(uint64_t),
1375                               8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1376       if (!modifiers[n]) {
1377          free(mod_reply);
1378          goto out;
1379       }
1380 
1381       memcpy(modifiers[n],
1382              xcb_dri3_get_supported_modifiers_window_modifiers(mod_reply),
1383              counts[n] * sizeof(uint64_t));
1384       n++;
1385    }
1386 
1387    if (mod_reply->num_screen_modifiers) {
1388       counts[n] = mod_reply->num_screen_modifiers;
1389       modifiers[n] = vk_alloc(pAllocator,
1390                               counts[n] * sizeof(uint64_t),
1391                               8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1392       if (!modifiers[n]) {
1393 	 if (n > 0)
1394             vk_free(pAllocator, modifiers[0]);
1395          free(mod_reply);
1396          goto out;
1397       }
1398 
1399       memcpy(modifiers[n],
1400              xcb_dri3_get_supported_modifiers_screen_modifiers(mod_reply),
1401              counts[n] * sizeof(uint64_t));
1402       n++;
1403    }
1404 
1405    for (int i = 0; i < n; i++) {
1406       modifiers_in[i] = modifiers[i];
1407       num_modifiers_in[i] = counts[i];
1408    }
1409    *num_tranches_in = n;
1410 
1411    free(mod_reply);
1412    return;
1413 #endif
1414 out:
1415    *num_tranches_in = 0;
1416 }
1417 
1418 static VkResult
x11_swapchain_destroy(struct wsi_swapchain * anv_chain,const VkAllocationCallbacks * pAllocator)1419 x11_swapchain_destroy(struct wsi_swapchain *anv_chain,
1420                       const VkAllocationCallbacks *pAllocator)
1421 {
1422    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1423    xcb_void_cookie_t cookie;
1424 
1425    if (chain->has_present_queue) {
1426       chain->status = VK_ERROR_OUT_OF_DATE_KHR;
1427       /* Push a UINT32_MAX to wake up the manager */
1428       wsi_queue_push(&chain->present_queue, UINT32_MAX);
1429       pthread_join(chain->queue_manager, NULL);
1430 
1431       if (chain->has_acquire_queue)
1432          wsi_queue_destroy(&chain->acquire_queue);
1433       wsi_queue_destroy(&chain->present_queue);
1434    }
1435 
1436    for (uint32_t i = 0; i < chain->base.image_count; i++)
1437       x11_image_finish(chain, pAllocator, &chain->images[i]);
1438 
1439    xcb_unregister_for_special_event(chain->conn, chain->special_event);
1440    cookie = xcb_present_select_input_checked(chain->conn, chain->event_id,
1441                                              chain->window,
1442                                              XCB_PRESENT_EVENT_MASK_NO_EVENT);
1443    xcb_discard_reply(chain->conn, cookie.sequence);
1444 
1445    wsi_swapchain_finish(&chain->base);
1446 
1447    vk_free(pAllocator, chain);
1448 
1449    return VK_SUCCESS;
1450 }
1451 
1452 static void
wsi_x11_set_adaptive_sync_property(xcb_connection_t * conn,xcb_drawable_t drawable,uint32_t state)1453 wsi_x11_set_adaptive_sync_property(xcb_connection_t *conn,
1454                                    xcb_drawable_t drawable,
1455                                    uint32_t state)
1456 {
1457    static char const name[] = "_VARIABLE_REFRESH";
1458    xcb_intern_atom_cookie_t cookie;
1459    xcb_intern_atom_reply_t* reply;
1460    xcb_void_cookie_t check;
1461 
1462    cookie = xcb_intern_atom(conn, 0, strlen(name), name);
1463    reply = xcb_intern_atom_reply(conn, cookie, NULL);
1464    if (reply == NULL)
1465       return;
1466 
1467    if (state)
1468       check = xcb_change_property_checked(conn, XCB_PROP_MODE_REPLACE,
1469                                           drawable, reply->atom,
1470                                           XCB_ATOM_CARDINAL, 32, 1, &state);
1471    else
1472       check = xcb_delete_property_checked(conn, drawable, reply->atom);
1473 
1474    xcb_discard_reply(conn, check.sequence);
1475    free(reply);
1476 }
1477 
1478 
1479 static VkResult
x11_surface_create_swapchain(VkIcdSurfaceBase * icd_surface,VkDevice device,struct wsi_device * wsi_device,const VkSwapchainCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,struct wsi_swapchain ** swapchain_out)1480 x11_surface_create_swapchain(VkIcdSurfaceBase *icd_surface,
1481                              VkDevice device,
1482                              struct wsi_device *wsi_device,
1483                              const VkSwapchainCreateInfoKHR *pCreateInfo,
1484                              const VkAllocationCallbacks* pAllocator,
1485                              struct wsi_swapchain **swapchain_out)
1486 {
1487    struct x11_swapchain *chain;
1488    xcb_void_cookie_t cookie;
1489    VkResult result;
1490    VkPresentModeKHR present_mode = wsi_swapchain_get_present_mode(wsi_device, pCreateInfo);
1491 
1492    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR);
1493 
1494    unsigned num_images = pCreateInfo->minImageCount;
1495    if (wsi_device->x11.strict_imageCount)
1496       num_images = pCreateInfo->minImageCount;
1497    else if (present_mode == VK_PRESENT_MODE_MAILBOX_KHR)
1498       num_images = MAX2(num_images, 5);
1499    else if (wsi_device->x11.ensure_minImageCount)
1500       num_images = MAX2(num_images, x11_get_min_image_count(wsi_device));
1501 
1502    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
1503    struct wsi_x11_connection *wsi_conn =
1504       wsi_x11_get_connection(wsi_device, conn);
1505    if (!wsi_conn)
1506       return VK_ERROR_OUT_OF_HOST_MEMORY;
1507 
1508    /* Check for whether or not we have a window up-front */
1509    xcb_window_t window = x11_surface_get_window(icd_surface);
1510    xcb_get_geometry_reply_t *geometry =
1511       xcb_get_geometry_reply(conn, xcb_get_geometry(conn, window), NULL);
1512    if (geometry == NULL)
1513       return VK_ERROR_SURFACE_LOST_KHR;
1514    const uint32_t bit_depth = geometry->depth;
1515    free(geometry);
1516 
1517    size_t size = sizeof(*chain) + num_images * sizeof(chain->images[0]);
1518    chain = vk_alloc(pAllocator, size, 8,
1519                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1520    if (chain == NULL)
1521       return VK_ERROR_OUT_OF_HOST_MEMORY;
1522 
1523    result = wsi_swapchain_init(wsi_device, &chain->base, device,
1524                                pCreateInfo, pAllocator);
1525    if (result != VK_SUCCESS)
1526       goto fail_alloc;
1527 
1528    chain->base.destroy = x11_swapchain_destroy;
1529    chain->base.get_wsi_image = x11_get_wsi_image;
1530    chain->base.acquire_next_image = x11_acquire_next_image;
1531    chain->base.queue_present = x11_queue_present;
1532    chain->base.present_mode = present_mode;
1533    chain->base.image_count = num_images;
1534    chain->conn = conn;
1535    chain->window = window;
1536    chain->depth = bit_depth;
1537    chain->extent = pCreateInfo->imageExtent;
1538    chain->send_sbc = 0;
1539    chain->sent_image_count = 0;
1540    chain->last_present_msc = 0;
1541    chain->has_acquire_queue = false;
1542    chain->has_present_queue = false;
1543    chain->status = VK_SUCCESS;
1544    chain->has_dri3_modifiers = wsi_conn->has_dri3_modifiers;
1545 
1546    /* If we are reallocating from an old swapchain, then we inherit its
1547     * last completion mode, to ensure we don't get into reallocation
1548     * cycles. If we are starting anew, we set 'COPY', as that is the only
1549     * mode which provokes reallocation when anything changes, to make
1550     * sure we have the most optimal allocation.
1551     */
1552    VK_FROM_HANDLE(x11_swapchain, old_chain, pCreateInfo->oldSwapchain);
1553    if (old_chain)
1554       chain->last_present_mode = old_chain->last_present_mode;
1555    else
1556       chain->last_present_mode = XCB_PRESENT_COMPLETE_MODE_COPY;
1557 
1558    if (!wsi_device->sw)
1559       if (!wsi_x11_check_dri3_compatible(wsi_device, conn))
1560          chain->base.use_prime_blit = true;
1561 
1562    chain->event_id = xcb_generate_id(chain->conn);
1563    xcb_present_select_input(chain->conn, chain->event_id, chain->window,
1564                             XCB_PRESENT_EVENT_MASK_CONFIGURE_NOTIFY |
1565                             XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY |
1566                             XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY);
1567 
1568    /* Create an XCB event queue to hold present events outside of the usual
1569     * application event queue
1570     */
1571    chain->special_event =
1572       xcb_register_for_special_xge(chain->conn, &xcb_present_id,
1573                                    chain->event_id, NULL);
1574 
1575    chain->gc = xcb_generate_id(chain->conn);
1576    if (!chain->gc) {
1577       /* FINISHME: Choose a better error. */
1578       result = VK_ERROR_OUT_OF_HOST_MEMORY;
1579       goto fail_register;
1580    }
1581 
1582    cookie = xcb_create_gc(chain->conn,
1583                           chain->gc,
1584                           chain->window,
1585                           XCB_GC_GRAPHICS_EXPOSURES,
1586                           (uint32_t []) { 0 });
1587    xcb_discard_reply(chain->conn, cookie.sequence);
1588 
1589    uint64_t *modifiers[2] = {NULL, NULL};
1590    uint32_t num_modifiers[2] = {0, 0};
1591    uint32_t num_tranches = 0;
1592    if (wsi_device->supports_modifiers)
1593       wsi_x11_get_dri3_modifiers(wsi_conn, conn, window, chain->depth, 32,
1594                                  pCreateInfo->compositeAlpha,
1595                                  modifiers, num_modifiers, &num_tranches,
1596                                  pAllocator);
1597 
1598    uint32_t image = 0;
1599    for (; image < chain->base.image_count; image++) {
1600       result = x11_image_init(device, chain, pCreateInfo, pAllocator,
1601                               (const uint64_t *const *)modifiers,
1602                               num_modifiers, num_tranches,
1603                               &chain->images[image]);
1604       if (result != VK_SUCCESS)
1605          goto fail_init_images;
1606    }
1607 
1608    if ((chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR ||
1609        chain->base.present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR ||
1610        chain->base.present_mode == VK_PRESENT_MODE_MAILBOX_KHR) && !chain->base.wsi->sw) {
1611       chain->has_present_queue = true;
1612 
1613       /* Initialize our queues.  We make them base.image_count + 1 because we will
1614        * occasionally use UINT32_MAX to signal the other thread that an error
1615        * has occurred and we don't want an overflow.
1616        */
1617       int ret;
1618       ret = wsi_queue_init(&chain->present_queue, chain->base.image_count + 1);
1619       if (ret) {
1620          goto fail_init_images;
1621       }
1622 
1623       if (chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR ||
1624           chain->base.present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
1625          chain->has_acquire_queue = true;
1626 
1627          ret = wsi_queue_init(&chain->acquire_queue, chain->base.image_count + 1);
1628          if (ret) {
1629             wsi_queue_destroy(&chain->present_queue);
1630             goto fail_init_images;
1631          }
1632 
1633          for (unsigned i = 0; i < chain->base.image_count; i++)
1634             wsi_queue_push(&chain->acquire_queue, i);
1635       }
1636 
1637       ret = pthread_create(&chain->queue_manager, NULL,
1638                            x11_manage_fifo_queues, chain);
1639       if (ret) {
1640          wsi_queue_destroy(&chain->present_queue);
1641          if (chain->has_acquire_queue)
1642             wsi_queue_destroy(&chain->acquire_queue);
1643 
1644          goto fail_init_images;
1645       }
1646    }
1647 
1648    assert(chain->has_present_queue || !chain->has_acquire_queue);
1649 
1650    for (int i = 0; i < ARRAY_SIZE(modifiers); i++)
1651       vk_free(pAllocator, modifiers[i]);
1652 
1653    /* It is safe to set it here as only one swapchain can be associated with
1654     * the window, and swapchain creation does the association. At this point
1655     * we know the creation is going to succeed. */
1656    wsi_x11_set_adaptive_sync_property(conn, window,
1657                                       wsi_device->enable_adaptive_sync);
1658 
1659    *swapchain_out = &chain->base;
1660 
1661    return VK_SUCCESS;
1662 
1663 fail_init_images:
1664    for (uint32_t j = 0; j < image; j++)
1665       x11_image_finish(chain, pAllocator, &chain->images[j]);
1666 
1667    for (int i = 0; i < ARRAY_SIZE(modifiers); i++)
1668       vk_free(pAllocator, modifiers[i]);
1669 
1670 fail_register:
1671    xcb_unregister_for_special_event(chain->conn, chain->special_event);
1672 
1673    wsi_swapchain_finish(&chain->base);
1674 
1675 fail_alloc:
1676    vk_free(pAllocator, chain);
1677 
1678    return result;
1679 }
1680 
1681 VkResult
wsi_x11_init_wsi(struct wsi_device * wsi_device,const VkAllocationCallbacks * alloc,const struct driOptionCache * dri_options)1682 wsi_x11_init_wsi(struct wsi_device *wsi_device,
1683                  const VkAllocationCallbacks *alloc,
1684                  const struct driOptionCache *dri_options)
1685 {
1686    struct wsi_x11 *wsi;
1687    VkResult result;
1688 
1689    wsi = vk_alloc(alloc, sizeof(*wsi), 8,
1690                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1691    if (!wsi) {
1692       result = VK_ERROR_OUT_OF_HOST_MEMORY;
1693       goto fail;
1694    }
1695 
1696    int ret = pthread_mutex_init(&wsi->mutex, NULL);
1697    if (ret != 0) {
1698       if (ret == ENOMEM) {
1699          result = VK_ERROR_OUT_OF_HOST_MEMORY;
1700       } else {
1701          /* FINISHME: Choose a better error. */
1702          result = VK_ERROR_OUT_OF_HOST_MEMORY;
1703       }
1704 
1705       goto fail_alloc;
1706    }
1707 
1708    wsi->connections = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
1709                                               _mesa_key_pointer_equal);
1710    if (!wsi->connections) {
1711       result = VK_ERROR_OUT_OF_HOST_MEMORY;
1712       goto fail_mutex;
1713    }
1714 
1715    if (dri_options) {
1716       if (driCheckOption(dri_options, "vk_x11_override_min_image_count", DRI_INT)) {
1717          wsi_device->x11.override_minImageCount =
1718             driQueryOptioni(dri_options, "vk_x11_override_min_image_count");
1719       }
1720       if (driCheckOption(dri_options, "vk_x11_strict_image_count", DRI_BOOL)) {
1721          wsi_device->x11.strict_imageCount =
1722             driQueryOptionb(dri_options, "vk_x11_strict_image_count");
1723       }
1724       if (driCheckOption(dri_options, "vk_x11_ensure_min_image_count", DRI_BOOL)) {
1725          wsi_device->x11.ensure_minImageCount =
1726             driQueryOptionb(dri_options, "vk_x11_ensure_min_image_count");
1727       }
1728 
1729    }
1730 
1731    wsi->base.get_support = x11_surface_get_support;
1732    wsi->base.get_capabilities2 = x11_surface_get_capabilities2;
1733    wsi->base.get_formats = x11_surface_get_formats;
1734    wsi->base.get_formats2 = x11_surface_get_formats2;
1735    wsi->base.get_present_modes = x11_surface_get_present_modes;
1736    wsi->base.get_present_rectangles = x11_surface_get_present_rectangles;
1737    wsi->base.create_swapchain = x11_surface_create_swapchain;
1738 
1739    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = &wsi->base;
1740    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = &wsi->base;
1741 
1742    return VK_SUCCESS;
1743 
1744 fail_mutex:
1745    pthread_mutex_destroy(&wsi->mutex);
1746 fail_alloc:
1747    vk_free(alloc, wsi);
1748 fail:
1749    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = NULL;
1750    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = NULL;
1751 
1752    return result;
1753 }
1754 
1755 void
wsi_x11_finish_wsi(struct wsi_device * wsi_device,const VkAllocationCallbacks * alloc)1756 wsi_x11_finish_wsi(struct wsi_device *wsi_device,
1757                    const VkAllocationCallbacks *alloc)
1758 {
1759    struct wsi_x11 *wsi =
1760       (struct wsi_x11 *)wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB];
1761 
1762    if (wsi) {
1763       hash_table_foreach(wsi->connections, entry)
1764          wsi_x11_connection_destroy(wsi_device, entry->data);
1765 
1766       _mesa_hash_table_destroy(wsi->connections, NULL);
1767 
1768       pthread_mutex_destroy(&wsi->mutex);
1769 
1770       vk_free(alloc, wsi);
1771    }
1772 }
1773