OSDN Git Service

vulkan/wsi/x11: Fix behavior of vkGetPhysicalDeviceSurfacePresentModesKHR
[android-x86/external-mesa.git] / src / vulkan / wsi / wsi_common_x11.c
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
37 #include <poll.h>
38 #include "util/hash_table.h"
39
40 #include "wsi_common.h"
41 #include "wsi_common_x11.h"
42
43 #define typed_memcpy(dest, src, count) ({ \
44    static_assert(sizeof(*src) == sizeof(*dest), ""); \
45    memcpy((dest), (src), (count) * sizeof(*(src))); \
46 })
47
48 struct wsi_x11_connection {
49    bool has_dri3;
50    bool has_present;
51 };
52
53 struct wsi_x11 {
54    struct wsi_interface base;
55
56    pthread_mutex_t                              mutex;
57    /* Hash table of xcb_connection -> wsi_x11_connection mappings */
58    struct hash_table *connections;
59 };
60
61 static struct wsi_x11_connection *
62 wsi_x11_connection_create(const VkAllocationCallbacks *alloc,
63                           xcb_connection_t *conn)
64 {
65    xcb_query_extension_cookie_t dri3_cookie, pres_cookie;
66    xcb_query_extension_reply_t *dri3_reply, *pres_reply;
67
68    struct wsi_x11_connection *wsi_conn =
69       vk_alloc(alloc, sizeof(*wsi_conn), 8,
70                 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
71    if (!wsi_conn)
72       return NULL;
73
74    dri3_cookie = xcb_query_extension(conn, 4, "DRI3");
75    pres_cookie = xcb_query_extension(conn, 7, "PRESENT");
76
77    dri3_reply = xcb_query_extension_reply(conn, dri3_cookie, NULL);
78    pres_reply = xcb_query_extension_reply(conn, pres_cookie, NULL);
79    if (dri3_reply == NULL || pres_reply == NULL) {
80       free(dri3_reply);
81       free(pres_reply);
82       vk_free(alloc, wsi_conn);
83       return NULL;
84    }
85
86    wsi_conn->has_dri3 = dri3_reply->present != 0;
87    wsi_conn->has_present = pres_reply->present != 0;
88
89    free(dri3_reply);
90    free(pres_reply);
91
92    return wsi_conn;
93 }
94
95 static void
96 wsi_x11_connection_destroy(const VkAllocationCallbacks *alloc,
97                            struct wsi_x11_connection *conn)
98 {
99    vk_free(alloc, conn);
100 }
101
102 static struct wsi_x11_connection *
103 wsi_x11_get_connection(struct wsi_device *wsi_dev,
104                        const VkAllocationCallbacks *alloc,
105                        xcb_connection_t *conn)
106 {
107    struct wsi_x11 *wsi =
108       (struct wsi_x11 *)wsi_dev->wsi[VK_ICD_WSI_PLATFORM_XCB];
109
110    pthread_mutex_lock(&wsi->mutex);
111
112    struct hash_entry *entry = _mesa_hash_table_search(wsi->connections, conn);
113    if (!entry) {
114       /* We're about to make a bunch of blocking calls.  Let's drop the
115        * mutex for now so we don't block up too badly.
116        */
117       pthread_mutex_unlock(&wsi->mutex);
118
119       struct wsi_x11_connection *wsi_conn =
120          wsi_x11_connection_create(alloc, conn);
121
122       pthread_mutex_lock(&wsi->mutex);
123
124       entry = _mesa_hash_table_search(wsi->connections, conn);
125       if (entry) {
126          /* Oops, someone raced us to it */
127          wsi_x11_connection_destroy(alloc, wsi_conn);
128       } else {
129          entry = _mesa_hash_table_insert(wsi->connections, conn, wsi_conn);
130       }
131    }
132
133    pthread_mutex_unlock(&wsi->mutex);
134
135    return entry->data;
136 }
137
138 static const VkSurfaceFormatKHR formats[] = {
139    { .format = VK_FORMAT_B8G8R8A8_SRGB, },
140    { .format = VK_FORMAT_B8G8R8A8_UNORM, },
141 };
142
143 static const VkPresentModeKHR present_modes[] = {
144    VK_PRESENT_MODE_IMMEDIATE_KHR,
145    VK_PRESENT_MODE_MAILBOX_KHR,
146 };
147
148 static xcb_screen_t *
149 get_screen_for_root(xcb_connection_t *conn, xcb_window_t root)
150 {
151    xcb_screen_iterator_t screen_iter =
152       xcb_setup_roots_iterator(xcb_get_setup(conn));
153
154    for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
155       if (screen_iter.data->root == root)
156          return screen_iter.data;
157    }
158
159    return NULL;
160 }
161
162 static xcb_visualtype_t *
163 screen_get_visualtype(xcb_screen_t *screen, xcb_visualid_t visual_id,
164                       unsigned *depth)
165 {
166    xcb_depth_iterator_t depth_iter =
167       xcb_screen_allowed_depths_iterator(screen);
168
169    for (; depth_iter.rem; xcb_depth_next (&depth_iter)) {
170       xcb_visualtype_iterator_t visual_iter =
171          xcb_depth_visuals_iterator (depth_iter.data);
172
173       for (; visual_iter.rem; xcb_visualtype_next (&visual_iter)) {
174          if (visual_iter.data->visual_id == visual_id) {
175             if (depth)
176                *depth = depth_iter.data->depth;
177             return visual_iter.data;
178          }
179       }
180    }
181
182    return NULL;
183 }
184
185 static xcb_visualtype_t *
186 connection_get_visualtype(xcb_connection_t *conn, xcb_visualid_t visual_id,
187                           unsigned *depth)
188 {
189    xcb_screen_iterator_t screen_iter =
190       xcb_setup_roots_iterator(xcb_get_setup(conn));
191
192    /* For this we have to iterate over all of the screens which is rather
193     * annoying.  Fortunately, there is probably only 1.
194     */
195    for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
196       xcb_visualtype_t *visual = screen_get_visualtype(screen_iter.data,
197                                                        visual_id, depth);
198       if (visual)
199          return visual;
200    }
201
202    return NULL;
203 }
204
205 static xcb_visualtype_t *
206 get_visualtype_for_window(xcb_connection_t *conn, xcb_window_t window,
207                           unsigned *depth)
208 {
209    xcb_query_tree_cookie_t tree_cookie;
210    xcb_get_window_attributes_cookie_t attrib_cookie;
211    xcb_query_tree_reply_t *tree;
212    xcb_get_window_attributes_reply_t *attrib;
213
214    tree_cookie = xcb_query_tree(conn, window);
215    attrib_cookie = xcb_get_window_attributes(conn, window);
216
217    tree = xcb_query_tree_reply(conn, tree_cookie, NULL);
218    attrib = xcb_get_window_attributes_reply(conn, attrib_cookie, NULL);
219    if (attrib == NULL || tree == NULL) {
220       free(attrib);
221       free(tree);
222       return NULL;
223    }
224
225    xcb_window_t root = tree->root;
226    xcb_visualid_t visual_id = attrib->visual;
227    free(attrib);
228    free(tree);
229
230    xcb_screen_t *screen = get_screen_for_root(conn, root);
231    if (screen == NULL)
232       return NULL;
233
234    return screen_get_visualtype(screen, visual_id, depth);
235 }
236
237 static bool
238 visual_has_alpha(xcb_visualtype_t *visual, unsigned depth)
239 {
240    uint32_t rgb_mask = visual->red_mask |
241                        visual->green_mask |
242                        visual->blue_mask;
243
244    uint32_t all_mask = 0xffffffff >> (32 - depth);
245
246    /* Do we have bits left over after RGB? */
247    return (all_mask & ~rgb_mask) != 0;
248 }
249
250 VkBool32 wsi_get_physical_device_xcb_presentation_support(
251     struct wsi_device *wsi_device,
252     VkAllocationCallbacks *alloc,
253     uint32_t                                    queueFamilyIndex,
254     xcb_connection_t*                           connection,
255     xcb_visualid_t                              visual_id)
256 {
257    struct wsi_x11_connection *wsi_conn =
258       wsi_x11_get_connection(wsi_device, alloc, connection);
259
260    if (!wsi_conn->has_dri3) {
261       fprintf(stderr, "vulkan: No DRI3 support\n");
262       return false;
263    }
264
265    unsigned visual_depth;
266    if (!connection_get_visualtype(connection, visual_id, &visual_depth))
267       return false;
268
269    if (visual_depth != 24 && visual_depth != 32)
270       return false;
271
272    return true;
273 }
274
275 static xcb_connection_t*
276 x11_surface_get_connection(VkIcdSurfaceBase *icd_surface)
277 {
278    if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
279       return XGetXCBConnection(((VkIcdSurfaceXlib *)icd_surface)->dpy);
280    else
281       return ((VkIcdSurfaceXcb *)icd_surface)->connection;
282 }
283
284 static xcb_window_t
285 x11_surface_get_window(VkIcdSurfaceBase *icd_surface)
286 {
287    if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
288       return ((VkIcdSurfaceXlib *)icd_surface)->window;
289    else
290       return ((VkIcdSurfaceXcb *)icd_surface)->window;
291 }
292
293 static VkResult
294 x11_surface_get_support(VkIcdSurfaceBase *icd_surface,
295                         struct wsi_device *wsi_device,
296                         const VkAllocationCallbacks *alloc,
297                         uint32_t queueFamilyIndex,
298                         VkBool32* pSupported)
299 {
300    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
301    xcb_window_t window = x11_surface_get_window(icd_surface);
302
303    struct wsi_x11_connection *wsi_conn =
304       wsi_x11_get_connection(wsi_device, alloc, conn);
305    if (!wsi_conn)
306       return VK_ERROR_OUT_OF_HOST_MEMORY;
307
308    if (!wsi_conn->has_dri3) {
309       fprintf(stderr, "vulkan: No DRI3 support\n");
310       *pSupported = false;
311       return VK_SUCCESS;
312    }
313
314    unsigned visual_depth;
315    if (!get_visualtype_for_window(conn, window, &visual_depth)) {
316       *pSupported = false;
317       return VK_SUCCESS;
318    }
319
320    if (visual_depth != 24 && visual_depth != 32) {
321       *pSupported = false;
322       return VK_SUCCESS;
323    }
324
325    *pSupported = true;
326    return VK_SUCCESS;
327 }
328
329 static VkResult
330 x11_surface_get_capabilities(VkIcdSurfaceBase *icd_surface,
331                              VkSurfaceCapabilitiesKHR *caps)
332 {
333    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
334    xcb_window_t window = x11_surface_get_window(icd_surface);
335    xcb_get_geometry_cookie_t geom_cookie;
336    xcb_generic_error_t *err;
337    xcb_get_geometry_reply_t *geom;
338    unsigned visual_depth;
339
340    geom_cookie = xcb_get_geometry(conn, window);
341
342    /* This does a round-trip.  This is why we do get_geometry first and
343     * wait to read the reply until after we have a visual.
344     */
345    xcb_visualtype_t *visual =
346       get_visualtype_for_window(conn, window, &visual_depth);
347
348    geom = xcb_get_geometry_reply(conn, geom_cookie, &err);
349    if (geom) {
350       VkExtent2D extent = { geom->width, geom->height };
351       caps->currentExtent = extent;
352       caps->minImageExtent = extent;
353       caps->maxImageExtent = extent;
354    } else {
355       /* This can happen if the client didn't wait for the configure event
356        * to come back from the compositor.  In that case, we don't know the
357        * size of the window so we just return valid "I don't know" stuff.
358        */
359       caps->currentExtent = (VkExtent2D) { -1, -1 };
360       caps->minImageExtent = (VkExtent2D) { 1, 1 };
361       caps->maxImageExtent = (VkExtent2D) { INT16_MAX, INT16_MAX };
362    }
363    free(err);
364    free(geom);
365
366    if (visual_has_alpha(visual, visual_depth)) {
367       caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
368                                       VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
369    } else {
370       caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
371                                       VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
372    }
373
374    caps->minImageCount = 2;
375    caps->maxImageCount = 4;
376    caps->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
377    caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
378    caps->maxImageArrayLayers = 1;
379    caps->supportedUsageFlags =
380       VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
381       VK_IMAGE_USAGE_SAMPLED_BIT |
382       VK_IMAGE_USAGE_TRANSFER_DST_BIT |
383       VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
384
385    return VK_SUCCESS;
386 }
387
388 static VkResult
389 x11_surface_get_formats(VkIcdSurfaceBase *surface,
390                         struct wsi_device *wsi_device,
391                         uint32_t *pSurfaceFormatCount,
392                         VkSurfaceFormatKHR *pSurfaceFormats)
393 {
394    if (pSurfaceFormats == NULL) {
395       *pSurfaceFormatCount = ARRAY_SIZE(formats);
396       return VK_SUCCESS;
397    }
398
399    VkResult result = VK_SUCCESS;
400
401    if (*pSurfaceFormatCount > ARRAY_SIZE(formats))
402       *pSurfaceFormatCount = ARRAY_SIZE(formats);
403    else if (*pSurfaceFormatCount < ARRAY_SIZE(formats))
404       result = VK_INCOMPLETE;
405
406    typed_memcpy(pSurfaceFormats, formats, *pSurfaceFormatCount);
407
408    return result;
409 }
410
411 static VkResult
412 x11_surface_get_present_modes(VkIcdSurfaceBase *surface,
413                               uint32_t *pPresentModeCount,
414                               VkPresentModeKHR *pPresentModes)
415 {
416    if (pPresentModes == NULL) {
417       *pPresentModeCount = ARRAY_SIZE(present_modes);
418       return VK_SUCCESS;
419    }
420
421    *pPresentModeCount = MIN2(*pPresentModeCount, ARRAY_SIZE(present_modes));
422    typed_memcpy(pPresentModes, present_modes, *pPresentModeCount);
423
424    return *pPresentModeCount < ARRAY_SIZE(present_modes) ?
425       VK_INCOMPLETE : VK_SUCCESS;
426 }
427
428 VkResult wsi_create_xcb_surface(const VkAllocationCallbacks *pAllocator,
429                                 const VkXcbSurfaceCreateInfoKHR *pCreateInfo,
430                                 VkSurfaceKHR *pSurface)
431 {
432    VkIcdSurfaceXcb *surface;
433
434    surface = vk_alloc(pAllocator, sizeof *surface, 8,
435                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
436    if (surface == NULL)
437       return VK_ERROR_OUT_OF_HOST_MEMORY;
438
439    surface->base.platform = VK_ICD_WSI_PLATFORM_XCB;
440    surface->connection = pCreateInfo->connection;
441    surface->window = pCreateInfo->window;
442
443    *pSurface = _VkIcdSurfaceBase_to_handle(&surface->base);
444    return VK_SUCCESS;
445 }
446
447 VkResult wsi_create_xlib_surface(const VkAllocationCallbacks *pAllocator,
448                                  const VkXlibSurfaceCreateInfoKHR *pCreateInfo,
449                                  VkSurfaceKHR *pSurface)
450 {
451    VkIcdSurfaceXlib *surface;
452
453    surface = vk_alloc(pAllocator, sizeof *surface, 8,
454                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
455    if (surface == NULL)
456       return VK_ERROR_OUT_OF_HOST_MEMORY;
457
458    surface->base.platform = VK_ICD_WSI_PLATFORM_XLIB;
459    surface->dpy = pCreateInfo->dpy;
460    surface->window = pCreateInfo->window;
461
462    *pSurface = _VkIcdSurfaceBase_to_handle(&surface->base);
463    return VK_SUCCESS;
464 }
465
466 struct x11_image {
467    VkImage image;
468    VkDeviceMemory memory;
469    xcb_pixmap_t                              pixmap;
470    bool                                      busy;
471    struct xshmfence *                        shm_fence;
472    uint32_t                                  sync_fence;
473 };
474
475 struct x11_swapchain {
476    struct wsi_swapchain                        base;
477
478    xcb_connection_t *                           conn;
479    xcb_window_t                                 window;
480    xcb_gc_t                                     gc;
481    uint32_t                                     depth;
482    VkExtent2D                                   extent;
483    uint32_t                                     image_count;
484
485    xcb_present_event_t                          event_id;
486    xcb_special_event_t *                        special_event;
487    uint64_t                                     send_sbc;
488    uint32_t                                     stamp;
489
490    struct x11_image                             images[0];
491 };
492
493 static VkResult
494 x11_get_images(struct wsi_swapchain *anv_chain,
495                uint32_t* pCount, VkImage *pSwapchainImages)
496 {
497    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
498
499    if (pSwapchainImages == NULL) {
500       *pCount = chain->image_count;
501       return VK_SUCCESS;
502    }
503
504    assert(chain->image_count <= *pCount);
505    for (uint32_t i = 0; i < chain->image_count; i++)
506       pSwapchainImages[i] = chain->images[i].image;
507
508    *pCount = chain->image_count;
509
510    return VK_SUCCESS;
511 }
512
513 static VkResult
514 x11_handle_dri3_present_event(struct x11_swapchain *chain,
515                               xcb_present_generic_event_t *event)
516 {
517    switch (event->evtype) {
518    case XCB_PRESENT_CONFIGURE_NOTIFY: {
519       xcb_present_configure_notify_event_t *config = (void *) event;
520
521       if (config->width != chain->extent.width ||
522           config->height != chain->extent.height)
523          return VK_ERROR_OUT_OF_DATE_KHR;
524
525       break;
526    }
527
528    case XCB_PRESENT_EVENT_IDLE_NOTIFY: {
529       xcb_present_idle_notify_event_t *idle = (void *) event;
530
531       for (unsigned i = 0; i < chain->image_count; i++) {
532          if (chain->images[i].pixmap == idle->pixmap) {
533             chain->images[i].busy = false;
534             break;
535          }
536       }
537
538       break;
539    }
540
541    case XCB_PRESENT_COMPLETE_NOTIFY:
542    default:
543       break;
544    }
545
546    return VK_SUCCESS;
547 }
548
549
550 static uint64_t wsi_get_current_time(void)
551 {
552    uint64_t current_time;
553    struct timespec tv;
554
555    clock_gettime(CLOCK_MONOTONIC, &tv);
556    current_time = tv.tv_nsec + tv.tv_sec*1000000000ull;
557    return current_time;
558 }
559
560 static uint64_t wsi_get_absolute_timeout(uint64_t timeout)
561 {
562    uint64_t current_time = wsi_get_current_time();
563
564    timeout = MIN2(UINT64_MAX - current_time, timeout);
565
566    return current_time + timeout;
567 }
568
569 static VkResult
570 x11_acquire_next_image(struct wsi_swapchain *anv_chain,
571                        uint64_t timeout,
572                        VkSemaphore semaphore,
573                        uint32_t *image_index)
574 {
575    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
576    xcb_generic_event_t *event;
577    struct pollfd pfds;
578    uint64_t atimeout;
579    while (1) {
580       for (uint32_t i = 0; i < chain->image_count; i++) {
581          if (!chain->images[i].busy) {
582             /* We found a non-busy image */
583             xshmfence_await(chain->images[i].shm_fence);
584             *image_index = i;
585             chain->images[i].busy = true;
586             return VK_SUCCESS;
587          }
588       }
589
590       xcb_flush(chain->conn);
591
592       if (timeout == UINT64_MAX) {
593          event = xcb_wait_for_special_event(chain->conn, chain->special_event);
594          if (!event)
595             return VK_ERROR_OUT_OF_DATE_KHR;
596       } else {
597          event = xcb_poll_for_special_event(chain->conn, chain->special_event);
598          if (!event) {
599             int ret;
600             if (timeout == 0)
601                return VK_NOT_READY;
602
603             atimeout = wsi_get_absolute_timeout(timeout);
604
605             pfds.fd = xcb_get_file_descriptor(chain->conn);
606             pfds.events = POLLIN;
607             ret = poll(&pfds, 1, timeout / 1000 / 1000);
608             if (ret == 0)
609                return VK_TIMEOUT;
610             if (ret == -1)
611                return VK_ERROR_OUT_OF_DATE_KHR;
612
613             /* If a non-special event happens, the fd will still
614              * poll. So recalculate the timeout now just in case.
615              */
616             uint64_t current_time = wsi_get_current_time();
617             if (atimeout > current_time)
618                timeout = atimeout - current_time;
619             else
620                timeout = 0;
621             continue;
622          }
623       }
624
625       VkResult result = x11_handle_dri3_present_event(chain, (void *)event);
626       free(event);
627       if (result != VK_SUCCESS)
628          return result;
629    }
630 }
631
632 static VkResult
633 x11_queue_present(struct wsi_swapchain *anv_chain,
634                   uint32_t image_index)
635 {
636    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
637    struct x11_image *image = &chain->images[image_index];
638
639    assert(image_index < chain->image_count);
640
641    uint32_t options = XCB_PRESENT_OPTION_NONE;
642
643    int64_t target_msc = 0;
644    int64_t divisor = 0;
645    int64_t remainder = 0;
646
647    if (chain->base.present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
648       options |= XCB_PRESENT_OPTION_ASYNC;
649
650    xshmfence_reset(image->shm_fence);
651
652    ++chain->send_sbc;
653    xcb_void_cookie_t cookie =
654       xcb_present_pixmap(chain->conn,
655                          chain->window,
656                          image->pixmap,
657                          (uint32_t) chain->send_sbc,
658                          0,                                    /* valid */
659                          0,                                    /* update */
660                          0,                                    /* x_off */
661                          0,                                    /* y_off */
662                          XCB_NONE,                             /* target_crtc */
663                          XCB_NONE,
664                          image->sync_fence,
665                          options,
666                          target_msc,
667                          divisor,
668                          remainder, 0, NULL);
669    xcb_discard_reply(chain->conn, cookie.sequence);
670    image->busy = true;
671
672    xcb_flush(chain->conn);
673
674    return VK_SUCCESS;
675 }
676
677 static VkResult
678 x11_image_init(VkDevice device_h, struct x11_swapchain *chain,
679                const VkSwapchainCreateInfoKHR *pCreateInfo,
680                const VkAllocationCallbacks* pAllocator,
681                struct x11_image *image)
682 {
683    xcb_void_cookie_t cookie;
684    VkResult result;
685    uint32_t row_pitch;
686    uint32_t offset;
687    uint32_t bpp = 32;
688    int fd;
689    uint32_t size;
690
691    result = chain->base.image_fns->create_wsi_image(device_h,
692                                                     pCreateInfo,
693                                                     pAllocator,
694                                                     &image->image,
695                                                     &image->memory,
696                                                     &size,
697                                                     &offset,
698                                                     &row_pitch,
699                                                     &fd);
700    if (result != VK_SUCCESS)
701       return result;
702
703    image->pixmap = xcb_generate_id(chain->conn);
704
705    cookie =
706       xcb_dri3_pixmap_from_buffer_checked(chain->conn,
707                                           image->pixmap,
708                                           chain->window,
709                                           size,
710                                           pCreateInfo->imageExtent.width,
711                                           pCreateInfo->imageExtent.height,
712                                           row_pitch,
713                                           chain->depth, bpp, fd);
714    xcb_discard_reply(chain->conn, cookie.sequence);
715
716    int fence_fd = xshmfence_alloc_shm();
717    if (fence_fd < 0)
718       goto fail_pixmap;
719
720    image->shm_fence = xshmfence_map_shm(fence_fd);
721    if (image->shm_fence == NULL)
722       goto fail_shmfence_alloc;
723
724    image->sync_fence = xcb_generate_id(chain->conn);
725    xcb_dri3_fence_from_fd(chain->conn,
726                           image->pixmap,
727                           image->sync_fence,
728                           false,
729                           fence_fd);
730
731    image->busy = false;
732    xshmfence_trigger(image->shm_fence);
733
734    return VK_SUCCESS;
735
736 fail_shmfence_alloc:
737    close(fence_fd);
738
739 fail_pixmap:
740    cookie = xcb_free_pixmap(chain->conn, image->pixmap);
741    xcb_discard_reply(chain->conn, cookie.sequence);
742
743    chain->base.image_fns->free_wsi_image(device_h, pAllocator,
744                                         image->image, image->memory);
745
746    return result;
747 }
748
749 static void
750 x11_image_finish(struct x11_swapchain *chain,
751                  const VkAllocationCallbacks* pAllocator,
752                  struct x11_image *image)
753 {
754    xcb_void_cookie_t cookie;
755
756    cookie = xcb_sync_destroy_fence(chain->conn, image->sync_fence);
757    xcb_discard_reply(chain->conn, cookie.sequence);
758    xshmfence_unmap_shm(image->shm_fence);
759
760    cookie = xcb_free_pixmap(chain->conn, image->pixmap);
761    xcb_discard_reply(chain->conn, cookie.sequence);
762
763    chain->base.image_fns->free_wsi_image(chain->base.device, pAllocator,
764                                         image->image, image->memory);
765 }
766
767 static VkResult
768 x11_swapchain_destroy(struct wsi_swapchain *anv_chain,
769                       const VkAllocationCallbacks *pAllocator)
770 {
771    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
772    for (uint32_t i = 0; i < chain->image_count; i++)
773       x11_image_finish(chain, pAllocator, &chain->images[i]);
774
775    xcb_unregister_for_special_event(chain->conn, chain->special_event);
776
777    vk_free(pAllocator, chain);
778
779    return VK_SUCCESS;
780 }
781
782 static VkResult
783 x11_surface_create_swapchain(VkIcdSurfaceBase *icd_surface,
784                              VkDevice device,
785                              struct wsi_device *wsi_device,
786                              const VkSwapchainCreateInfoKHR *pCreateInfo,
787                              const VkAllocationCallbacks* pAllocator,
788                              const struct wsi_image_fns *image_fns,
789                              struct wsi_swapchain **swapchain_out)
790 {
791    struct x11_swapchain *chain;
792    xcb_void_cookie_t cookie;
793    VkResult result;
794
795    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR);
796
797    int num_images = pCreateInfo->minImageCount;
798
799    /* For true mailbox mode, we need at least 4 images:
800     *  1) One to scan out from
801     *  2) One to have queued for scan-out
802     *  3) One to be currently held by the Wayland compositor
803     *  4) One to render to
804     */
805    if (pCreateInfo->presentMode == VK_PRESENT_MODE_MAILBOX_KHR)
806       num_images = MAX2(num_images, 4);
807
808    size_t size = sizeof(*chain) + num_images * sizeof(chain->images[0]);
809    chain = vk_alloc(pAllocator, size, 8,
810                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
811    if (chain == NULL)
812       return VK_ERROR_OUT_OF_HOST_MEMORY;
813
814    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
815    xcb_window_t window = x11_surface_get_window(icd_surface);
816    xcb_get_geometry_reply_t *geometry =
817       xcb_get_geometry_reply(conn, xcb_get_geometry(conn, window), NULL);
818
819    if (geometry == NULL)
820       return VK_ERROR_SURFACE_LOST_KHR;
821
822    chain->base.device = device;
823    chain->base.destroy = x11_swapchain_destroy;
824    chain->base.get_images = x11_get_images;
825    chain->base.acquire_next_image = x11_acquire_next_image;
826    chain->base.queue_present = x11_queue_present;
827    chain->base.image_fns = image_fns;
828    chain->base.present_mode = pCreateInfo->presentMode;
829    chain->conn = conn;
830    chain->window = window;
831    chain->depth = geometry->depth;
832    chain->extent = pCreateInfo->imageExtent;
833    chain->image_count = num_images;
834    chain->send_sbc = 0;
835
836    free(geometry);
837
838    chain->event_id = xcb_generate_id(chain->conn);
839    xcb_present_select_input(chain->conn, chain->event_id, chain->window,
840                             XCB_PRESENT_EVENT_MASK_CONFIGURE_NOTIFY |
841                             XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY |
842                             XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY);
843
844    /* Create an XCB event queue to hold present events outside of the usual
845     * application event queue
846     */
847    chain->special_event =
848       xcb_register_for_special_xge(chain->conn, &xcb_present_id,
849                                    chain->event_id, NULL);
850
851    chain->gc = xcb_generate_id(chain->conn);
852    if (!chain->gc) {
853       /* FINISHME: Choose a better error. */
854       result = VK_ERROR_OUT_OF_HOST_MEMORY;
855       goto fail_register;
856    }
857
858    cookie = xcb_create_gc(chain->conn,
859                           chain->gc,
860                           chain->window,
861                           XCB_GC_GRAPHICS_EXPOSURES,
862                           (uint32_t []) { 0 });
863    xcb_discard_reply(chain->conn, cookie.sequence);
864
865    uint32_t image = 0;
866    for (; image < chain->image_count; image++) {
867       result = x11_image_init(device, chain, pCreateInfo, pAllocator,
868                               &chain->images[image]);
869       if (result != VK_SUCCESS)
870          goto fail_init_images;
871    }
872
873    *swapchain_out = &chain->base;
874
875    return VK_SUCCESS;
876
877 fail_init_images:
878    for (uint32_t j = 0; j < image; j++)
879       x11_image_finish(chain, pAllocator, &chain->images[j]);
880
881 fail_register:
882    xcb_unregister_for_special_event(chain->conn, chain->special_event);
883
884    vk_free(pAllocator, chain);
885
886    return result;
887 }
888
889 VkResult
890 wsi_x11_init_wsi(struct wsi_device *wsi_device,
891                  const VkAllocationCallbacks *alloc)
892 {
893    struct wsi_x11 *wsi;
894    VkResult result;
895
896    wsi = vk_alloc(alloc, sizeof(*wsi), 8,
897                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
898    if (!wsi) {
899       result = VK_ERROR_OUT_OF_HOST_MEMORY;
900       goto fail;
901    }
902
903    int ret = pthread_mutex_init(&wsi->mutex, NULL);
904    if (ret != 0) {
905       if (ret == ENOMEM) {
906          result = VK_ERROR_OUT_OF_HOST_MEMORY;
907       } else {
908          /* FINISHME: Choose a better error. */
909          result = VK_ERROR_OUT_OF_HOST_MEMORY;
910       }
911
912       goto fail_alloc;
913    }
914
915    wsi->connections = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
916                                               _mesa_key_pointer_equal);
917    if (!wsi->connections) {
918       result = VK_ERROR_OUT_OF_HOST_MEMORY;
919       goto fail_mutex;
920    }
921
922    wsi->base.get_support = x11_surface_get_support;
923    wsi->base.get_capabilities = x11_surface_get_capabilities;
924    wsi->base.get_formats = x11_surface_get_formats;
925    wsi->base.get_present_modes = x11_surface_get_present_modes;
926    wsi->base.create_swapchain = x11_surface_create_swapchain;
927
928    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = &wsi->base;
929    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = &wsi->base;
930
931    return VK_SUCCESS;
932
933 fail_mutex:
934    pthread_mutex_destroy(&wsi->mutex);
935 fail_alloc:
936    vk_free(alloc, wsi);
937 fail:
938    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = NULL;
939    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = NULL;
940
941    return result;
942 }
943
944 void
945 wsi_x11_finish_wsi(struct wsi_device *wsi_device,
946                    const VkAllocationCallbacks *alloc)
947 {
948    struct wsi_x11 *wsi =
949       (struct wsi_x11 *)wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB];
950
951    if (wsi) {
952       _mesa_hash_table_destroy(wsi->connections, NULL);
953
954       pthread_mutex_destroy(&wsi->mutex);
955
956       vk_free(alloc, wsi);
957    }
958 }