OSDN Git Service

util/vulkan: Move Vulkan utilities to src/vulkan/util
[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 #include <fcntl.h>
37 #include <poll.h>
38 #include <xf86drm.h>
39 #include "util/hash_table.h"
40
41 #include "vk_util.h"
42 #include "wsi_common.h"
43 #include "wsi_common_x11.h"
44 #include "wsi_common_queue.h"
45
46 #define typed_memcpy(dest, src, count) ({ \
47    STATIC_ASSERT(sizeof(*src) == sizeof(*dest)); \
48    memcpy((dest), (src), (count) * sizeof(*(src))); \
49 })
50
51 struct wsi_x11_connection {
52    bool has_dri3;
53    bool has_present;
54    bool is_proprietary_x11;
55 };
56
57 struct wsi_x11 {
58    struct wsi_interface base;
59
60    pthread_mutex_t                              mutex;
61    /* Hash table of xcb_connection -> wsi_x11_connection mappings */
62    struct hash_table *connections;
63 };
64
65
66 /** wsi_dri3_open
67  *
68  * Wrapper around xcb_dri3_open
69  */
70 static int
71 wsi_dri3_open(xcb_connection_t *conn,
72               xcb_window_t root,
73               uint32_t provider)
74 {
75    xcb_dri3_open_cookie_t       cookie;
76    xcb_dri3_open_reply_t        *reply;
77    int                          fd;
78
79    cookie = xcb_dri3_open(conn,
80                           root,
81                           provider);
82
83    reply = xcb_dri3_open_reply(conn, cookie, NULL);
84    if (!reply)
85       return -1;
86
87    if (reply->nfd != 1) {
88       free(reply);
89       return -1;
90    }
91
92    fd = xcb_dri3_open_reply_fds(conn, reply)[0];
93    free(reply);
94    fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
95
96    return fd;
97 }
98
99 static bool
100 wsi_x11_check_dri3_compatible(xcb_connection_t *conn, int local_fd)
101 {
102    xcb_screen_iterator_t screen_iter =
103       xcb_setup_roots_iterator(xcb_get_setup(conn));
104    xcb_screen_t *screen = screen_iter.data;
105
106    int dri3_fd = wsi_dri3_open(conn, screen->root, None);
107    if (dri3_fd != -1) {
108       char *local_dev = drmGetRenderDeviceNameFromFd(local_fd);
109       char *dri3_dev = drmGetRenderDeviceNameFromFd(dri3_fd);
110       int ret;
111
112       close(dri3_fd);
113
114       ret = strcmp(local_dev, dri3_dev);
115
116       free(local_dev);
117       free(dri3_dev);
118
119       if (ret != 0)
120          return false;
121    }
122    return true;
123 }
124
125 static struct wsi_x11_connection *
126 wsi_x11_connection_create(const VkAllocationCallbacks *alloc,
127                           xcb_connection_t *conn)
128 {
129    xcb_query_extension_cookie_t dri3_cookie, pres_cookie, amd_cookie, nv_cookie;
130    xcb_query_extension_reply_t *dri3_reply, *pres_reply, *amd_reply, *nv_reply;
131
132    struct wsi_x11_connection *wsi_conn =
133       vk_alloc(alloc, sizeof(*wsi_conn), 8,
134                 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
135    if (!wsi_conn)
136       return NULL;
137
138    dri3_cookie = xcb_query_extension(conn, 4, "DRI3");
139    pres_cookie = xcb_query_extension(conn, 7, "PRESENT");
140
141    /* We try to be nice to users and emit a warning if they try to use a
142     * Vulkan application on a system without DRI3 enabled.  However, this ends
143     * up spewing the warning when a user has, for example, both Intel
144     * integrated graphics and a discrete card with proprietary drivers and are
145     * running on the discrete card with the proprietary DDX.  In this case, we
146     * really don't want to print the warning because it just confuses users.
147     * As a heuristic to detect this case, we check for a couple of proprietary
148     * X11 extensions.
149     */
150    amd_cookie = xcb_query_extension(conn, 11, "ATIFGLRXDRI");
151    nv_cookie = xcb_query_extension(conn, 10, "NV-CONTROL");
152
153    dri3_reply = xcb_query_extension_reply(conn, dri3_cookie, NULL);
154    pres_reply = xcb_query_extension_reply(conn, pres_cookie, NULL);
155    amd_reply = xcb_query_extension_reply(conn, amd_cookie, NULL);
156    nv_reply = xcb_query_extension_reply(conn, nv_cookie, NULL);
157    if (!dri3_reply || !pres_reply) {
158       free(dri3_reply);
159       free(pres_reply);
160       free(amd_reply);
161       free(nv_reply);
162       vk_free(alloc, wsi_conn);
163       return NULL;
164    }
165
166    wsi_conn->has_dri3 = dri3_reply->present != 0;
167    wsi_conn->has_present = pres_reply->present != 0;
168    wsi_conn->is_proprietary_x11 = false;
169    if (amd_reply && amd_reply->present)
170       wsi_conn->is_proprietary_x11 = true;
171    if (nv_reply && nv_reply->present)
172       wsi_conn->is_proprietary_x11 = true;
173
174    free(dri3_reply);
175    free(pres_reply);
176    free(amd_reply);
177    free(nv_reply);
178
179    return wsi_conn;
180 }
181
182 static void
183 wsi_x11_connection_destroy(const VkAllocationCallbacks *alloc,
184                            struct wsi_x11_connection *conn)
185 {
186    vk_free(alloc, conn);
187 }
188
189 static bool
190 wsi_x11_check_for_dri3(struct wsi_x11_connection *wsi_conn)
191 {
192   if (wsi_conn->has_dri3)
193     return true;
194   if (!wsi_conn->is_proprietary_x11) {
195     fprintf(stderr, "vulkan: No DRI3 support detected - required for presentation\n"
196                     "Note: you can probably enable DRI3 in your Xorg config\n");
197   }
198   return false;
199 }
200
201 static struct wsi_x11_connection *
202 wsi_x11_get_connection(struct wsi_device *wsi_dev,
203                        const VkAllocationCallbacks *alloc,
204                        xcb_connection_t *conn)
205 {
206    struct wsi_x11 *wsi =
207       (struct wsi_x11 *)wsi_dev->wsi[VK_ICD_WSI_PLATFORM_XCB];
208
209    pthread_mutex_lock(&wsi->mutex);
210
211    struct hash_entry *entry = _mesa_hash_table_search(wsi->connections, conn);
212    if (!entry) {
213       /* We're about to make a bunch of blocking calls.  Let's drop the
214        * mutex for now so we don't block up too badly.
215        */
216       pthread_mutex_unlock(&wsi->mutex);
217
218       struct wsi_x11_connection *wsi_conn =
219          wsi_x11_connection_create(alloc, conn);
220       if (!wsi_conn)
221          return NULL;
222
223       pthread_mutex_lock(&wsi->mutex);
224
225       entry = _mesa_hash_table_search(wsi->connections, conn);
226       if (entry) {
227          /* Oops, someone raced us to it */
228          wsi_x11_connection_destroy(alloc, wsi_conn);
229       } else {
230          entry = _mesa_hash_table_insert(wsi->connections, conn, wsi_conn);
231       }
232    }
233
234    pthread_mutex_unlock(&wsi->mutex);
235
236    return entry->data;
237 }
238
239 static const VkFormat formats[] = {
240    VK_FORMAT_B8G8R8A8_SRGB,
241    VK_FORMAT_B8G8R8A8_UNORM,
242 };
243
244 static const VkPresentModeKHR present_modes[] = {
245    VK_PRESENT_MODE_IMMEDIATE_KHR,
246    VK_PRESENT_MODE_MAILBOX_KHR,
247    VK_PRESENT_MODE_FIFO_KHR,
248 };
249
250 static xcb_screen_t *
251 get_screen_for_root(xcb_connection_t *conn, xcb_window_t root)
252 {
253    xcb_screen_iterator_t screen_iter =
254       xcb_setup_roots_iterator(xcb_get_setup(conn));
255
256    for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
257       if (screen_iter.data->root == root)
258          return screen_iter.data;
259    }
260
261    return NULL;
262 }
263
264 static xcb_visualtype_t *
265 screen_get_visualtype(xcb_screen_t *screen, xcb_visualid_t visual_id,
266                       unsigned *depth)
267 {
268    xcb_depth_iterator_t depth_iter =
269       xcb_screen_allowed_depths_iterator(screen);
270
271    for (; depth_iter.rem; xcb_depth_next (&depth_iter)) {
272       xcb_visualtype_iterator_t visual_iter =
273          xcb_depth_visuals_iterator (depth_iter.data);
274
275       for (; visual_iter.rem; xcb_visualtype_next (&visual_iter)) {
276          if (visual_iter.data->visual_id == visual_id) {
277             if (depth)
278                *depth = depth_iter.data->depth;
279             return visual_iter.data;
280          }
281       }
282    }
283
284    return NULL;
285 }
286
287 static xcb_visualtype_t *
288 connection_get_visualtype(xcb_connection_t *conn, xcb_visualid_t visual_id,
289                           unsigned *depth)
290 {
291    xcb_screen_iterator_t screen_iter =
292       xcb_setup_roots_iterator(xcb_get_setup(conn));
293
294    /* For this we have to iterate over all of the screens which is rather
295     * annoying.  Fortunately, there is probably only 1.
296     */
297    for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
298       xcb_visualtype_t *visual = screen_get_visualtype(screen_iter.data,
299                                                        visual_id, depth);
300       if (visual)
301          return visual;
302    }
303
304    return NULL;
305 }
306
307 static xcb_visualtype_t *
308 get_visualtype_for_window(xcb_connection_t *conn, xcb_window_t window,
309                           unsigned *depth)
310 {
311    xcb_query_tree_cookie_t tree_cookie;
312    xcb_get_window_attributes_cookie_t attrib_cookie;
313    xcb_query_tree_reply_t *tree;
314    xcb_get_window_attributes_reply_t *attrib;
315
316    tree_cookie = xcb_query_tree(conn, window);
317    attrib_cookie = xcb_get_window_attributes(conn, window);
318
319    tree = xcb_query_tree_reply(conn, tree_cookie, NULL);
320    attrib = xcb_get_window_attributes_reply(conn, attrib_cookie, NULL);
321    if (attrib == NULL || tree == NULL) {
322       free(attrib);
323       free(tree);
324       return NULL;
325    }
326
327    xcb_window_t root = tree->root;
328    xcb_visualid_t visual_id = attrib->visual;
329    free(attrib);
330    free(tree);
331
332    xcb_screen_t *screen = get_screen_for_root(conn, root);
333    if (screen == NULL)
334       return NULL;
335
336    return screen_get_visualtype(screen, visual_id, depth);
337 }
338
339 static bool
340 visual_has_alpha(xcb_visualtype_t *visual, unsigned depth)
341 {
342    uint32_t rgb_mask = visual->red_mask |
343                        visual->green_mask |
344                        visual->blue_mask;
345
346    uint32_t all_mask = 0xffffffff >> (32 - depth);
347
348    /* Do we have bits left over after RGB? */
349    return (all_mask & ~rgb_mask) != 0;
350 }
351
352 VkBool32 wsi_get_physical_device_xcb_presentation_support(
353     struct wsi_device *wsi_device,
354     VkAllocationCallbacks *alloc,
355     uint32_t                                    queueFamilyIndex,
356     int fd,
357     bool can_handle_different_gpu,
358     xcb_connection_t*                           connection,
359     xcb_visualid_t                              visual_id)
360 {
361    struct wsi_x11_connection *wsi_conn =
362       wsi_x11_get_connection(wsi_device, alloc, connection);
363
364    if (!wsi_conn)
365       return false;
366
367    if (!wsi_x11_check_for_dri3(wsi_conn))
368       return false;
369
370    if (!can_handle_different_gpu)
371       if (!wsi_x11_check_dri3_compatible(connection, fd))
372          return false;
373
374    unsigned visual_depth;
375    if (!connection_get_visualtype(connection, visual_id, &visual_depth))
376       return false;
377
378    if (visual_depth != 24 && visual_depth != 32)
379       return false;
380
381    return true;
382 }
383
384 static xcb_connection_t*
385 x11_surface_get_connection(VkIcdSurfaceBase *icd_surface)
386 {
387    if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
388       return XGetXCBConnection(((VkIcdSurfaceXlib *)icd_surface)->dpy);
389    else
390       return ((VkIcdSurfaceXcb *)icd_surface)->connection;
391 }
392
393 static xcb_window_t
394 x11_surface_get_window(VkIcdSurfaceBase *icd_surface)
395 {
396    if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
397       return ((VkIcdSurfaceXlib *)icd_surface)->window;
398    else
399       return ((VkIcdSurfaceXcb *)icd_surface)->window;
400 }
401
402 static VkResult
403 x11_surface_get_support(VkIcdSurfaceBase *icd_surface,
404                         struct wsi_device *wsi_device,
405                         const VkAllocationCallbacks *alloc,
406                         uint32_t queueFamilyIndex,
407                         int local_fd,
408                         bool can_handle_different_gpu,
409                         VkBool32* pSupported)
410 {
411    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
412    xcb_window_t window = x11_surface_get_window(icd_surface);
413
414    struct wsi_x11_connection *wsi_conn =
415       wsi_x11_get_connection(wsi_device, alloc, conn);
416    if (!wsi_conn)
417       return VK_ERROR_OUT_OF_HOST_MEMORY;
418
419    if (!wsi_x11_check_for_dri3(wsi_conn)) {
420       *pSupported = false;
421       return VK_SUCCESS;
422    }
423
424    if (!can_handle_different_gpu)
425       if (!wsi_x11_check_dri3_compatible(conn, local_fd))
426          return false;
427
428    unsigned visual_depth;
429    if (!get_visualtype_for_window(conn, window, &visual_depth)) {
430       *pSupported = false;
431       return VK_SUCCESS;
432    }
433
434    if (visual_depth != 24 && visual_depth != 32) {
435       *pSupported = false;
436       return VK_SUCCESS;
437    }
438
439    *pSupported = true;
440    return VK_SUCCESS;
441 }
442
443 static VkResult
444 x11_surface_get_capabilities(VkIcdSurfaceBase *icd_surface,
445                              VkSurfaceCapabilitiesKHR *caps)
446 {
447    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
448    xcb_window_t window = x11_surface_get_window(icd_surface);
449    xcb_get_geometry_cookie_t geom_cookie;
450    xcb_generic_error_t *err;
451    xcb_get_geometry_reply_t *geom;
452    unsigned visual_depth;
453
454    geom_cookie = xcb_get_geometry(conn, window);
455
456    /* This does a round-trip.  This is why we do get_geometry first and
457     * wait to read the reply until after we have a visual.
458     */
459    xcb_visualtype_t *visual =
460       get_visualtype_for_window(conn, window, &visual_depth);
461
462    if (!visual)
463       return VK_ERROR_SURFACE_LOST_KHR;
464
465    geom = xcb_get_geometry_reply(conn, geom_cookie, &err);
466    if (geom) {
467       VkExtent2D extent = { geom->width, geom->height };
468       caps->currentExtent = extent;
469       caps->minImageExtent = extent;
470       caps->maxImageExtent = extent;
471    } else {
472       /* This can happen if the client didn't wait for the configure event
473        * to come back from the compositor.  In that case, we don't know the
474        * size of the window so we just return valid "I don't know" stuff.
475        */
476       caps->currentExtent = (VkExtent2D) { -1, -1 };
477       caps->minImageExtent = (VkExtent2D) { 1, 1 };
478       /* This is the maximum supported size on Intel */
479       caps->maxImageExtent = (VkExtent2D) { 1 << 14, 1 << 14 };
480    }
481    free(err);
482    free(geom);
483
484    if (visual_has_alpha(visual, visual_depth)) {
485       caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
486                                       VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
487    } else {
488       caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
489                                       VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
490    }
491
492    /* For true mailbox mode, we need at least 4 images:
493     *  1) One to scan out from
494     *  2) One to have queued for scan-out
495     *  3) One to be currently held by the X server
496     *  4) One to render to
497     */
498    caps->minImageCount = 2;
499    /* There is no real maximum */
500    caps->maxImageCount = 0;
501
502    caps->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
503    caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
504    caps->maxImageArrayLayers = 1;
505    caps->supportedUsageFlags =
506       VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
507       VK_IMAGE_USAGE_SAMPLED_BIT |
508       VK_IMAGE_USAGE_TRANSFER_DST_BIT |
509       VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
510
511    return VK_SUCCESS;
512 }
513
514 static VkResult
515 x11_surface_get_capabilities2(VkIcdSurfaceBase *icd_surface,
516                               const void *info_next,
517                               VkSurfaceCapabilities2KHR *caps)
518 {
519    assert(caps->sType == VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR);
520
521    return x11_surface_get_capabilities(icd_surface, &caps->surfaceCapabilities);
522 }
523
524 static VkResult
525 x11_surface_get_formats(VkIcdSurfaceBase *surface,
526                         struct wsi_device *wsi_device,
527                         uint32_t *pSurfaceFormatCount,
528                         VkSurfaceFormatKHR *pSurfaceFormats)
529 {
530    VK_OUTARRAY_MAKE(out, pSurfaceFormats, pSurfaceFormatCount);
531
532    for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
533       vk_outarray_append(&out, f) {
534          f->format = formats[i];
535          f->colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
536       }
537    }
538
539    return vk_outarray_status(&out);
540 }
541
542 static VkResult
543 x11_surface_get_formats2(VkIcdSurfaceBase *surface,
544                         struct wsi_device *wsi_device,
545                         const void *info_next,
546                         uint32_t *pSurfaceFormatCount,
547                         VkSurfaceFormat2KHR *pSurfaceFormats)
548 {
549    VK_OUTARRAY_MAKE(out, pSurfaceFormats, pSurfaceFormatCount);
550
551    for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
552       vk_outarray_append(&out, f) {
553          assert(f->sType == VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR);
554          f->surfaceFormat.format = formats[i];
555          f->surfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
556       }
557    }
558
559    return vk_outarray_status(&out);
560 }
561
562 static VkResult
563 x11_surface_get_present_modes(VkIcdSurfaceBase *surface,
564                               uint32_t *pPresentModeCount,
565                               VkPresentModeKHR *pPresentModes)
566 {
567    if (pPresentModes == NULL) {
568       *pPresentModeCount = ARRAY_SIZE(present_modes);
569       return VK_SUCCESS;
570    }
571
572    *pPresentModeCount = MIN2(*pPresentModeCount, ARRAY_SIZE(present_modes));
573    typed_memcpy(pPresentModes, present_modes, *pPresentModeCount);
574
575    return *pPresentModeCount < ARRAY_SIZE(present_modes) ?
576       VK_INCOMPLETE : VK_SUCCESS;
577 }
578
579 VkResult wsi_create_xcb_surface(const VkAllocationCallbacks *pAllocator,
580                                 const VkXcbSurfaceCreateInfoKHR *pCreateInfo,
581                                 VkSurfaceKHR *pSurface)
582 {
583    VkIcdSurfaceXcb *surface;
584
585    surface = vk_alloc(pAllocator, sizeof *surface, 8,
586                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
587    if (surface == NULL)
588       return VK_ERROR_OUT_OF_HOST_MEMORY;
589
590    surface->base.platform = VK_ICD_WSI_PLATFORM_XCB;
591    surface->connection = pCreateInfo->connection;
592    surface->window = pCreateInfo->window;
593
594    *pSurface = VkIcdSurfaceBase_to_handle(&surface->base);
595    return VK_SUCCESS;
596 }
597
598 VkResult wsi_create_xlib_surface(const VkAllocationCallbacks *pAllocator,
599                                  const VkXlibSurfaceCreateInfoKHR *pCreateInfo,
600                                  VkSurfaceKHR *pSurface)
601 {
602    VkIcdSurfaceXlib *surface;
603
604    surface = vk_alloc(pAllocator, sizeof *surface, 8,
605                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
606    if (surface == NULL)
607       return VK_ERROR_OUT_OF_HOST_MEMORY;
608
609    surface->base.platform = VK_ICD_WSI_PLATFORM_XLIB;
610    surface->dpy = pCreateInfo->dpy;
611    surface->window = pCreateInfo->window;
612
613    *pSurface = VkIcdSurfaceBase_to_handle(&surface->base);
614    return VK_SUCCESS;
615 }
616
617 struct x11_image {
618    VkImage image;
619    VkImage linear_image; // for prime
620    VkDeviceMemory memory;
621    VkDeviceMemory linear_memory; // for prime
622    xcb_pixmap_t                              pixmap;
623    bool                                      busy;
624    struct xshmfence *                        shm_fence;
625    uint32_t                                  sync_fence;
626 };
627
628 struct x11_swapchain {
629    struct wsi_swapchain                        base;
630
631    xcb_connection_t *                           conn;
632    xcb_window_t                                 window;
633    xcb_gc_t                                     gc;
634    uint32_t                                     depth;
635    VkExtent2D                                   extent;
636
637    xcb_present_event_t                          event_id;
638    xcb_special_event_t *                        special_event;
639    uint64_t                                     send_sbc;
640    uint64_t                                     last_present_msc;
641    uint32_t                                     stamp;
642
643    bool                                         threaded;
644    VkResult                                     status;
645    struct wsi_queue                             present_queue;
646    struct wsi_queue                             acquire_queue;
647    pthread_t                                    queue_manager;
648
649    struct x11_image                             images[0];
650 };
651
652 static VkResult
653 x11_get_images(struct wsi_swapchain *anv_chain,
654                uint32_t* pCount, VkImage *pSwapchainImages)
655 {
656    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
657    uint32_t ret_count;
658    VkResult result;
659
660    if (pSwapchainImages == NULL) {
661       *pCount = chain->base.image_count;
662       return VK_SUCCESS;
663    }
664
665    result = VK_SUCCESS;
666    ret_count = chain->base.image_count;
667    if (chain->base.image_count > *pCount) {
668      ret_count = *pCount;
669      result = VK_INCOMPLETE;
670    }
671
672    for (uint32_t i = 0; i < ret_count; i++)
673       pSwapchainImages[i] = chain->images[i].image;
674
675    return result;
676 }
677
678 static void
679 x11_get_image_and_linear(struct wsi_swapchain *drv_chain,
680                          int imageIndex, VkImage *image, VkImage *linear_image)
681 {
682    struct x11_swapchain *chain = (struct x11_swapchain *)drv_chain;
683    *image = chain->images[imageIndex].image;
684    *linear_image = chain->images[imageIndex].linear_image;
685 }
686
687 static VkResult
688 x11_handle_dri3_present_event(struct x11_swapchain *chain,
689                               xcb_present_generic_event_t *event)
690 {
691    switch (event->evtype) {
692    case XCB_PRESENT_CONFIGURE_NOTIFY: {
693       xcb_present_configure_notify_event_t *config = (void *) event;
694
695       if (config->width != chain->extent.width ||
696           config->height != chain->extent.height)
697          return VK_ERROR_OUT_OF_DATE_KHR;
698
699       break;
700    }
701
702    case XCB_PRESENT_EVENT_IDLE_NOTIFY: {
703       xcb_present_idle_notify_event_t *idle = (void *) event;
704
705       for (unsigned i = 0; i < chain->base.image_count; i++) {
706          if (chain->images[i].pixmap == idle->pixmap) {
707             chain->images[i].busy = false;
708             if (chain->threaded)
709                wsi_queue_push(&chain->acquire_queue, i);
710             break;
711          }
712       }
713
714       break;
715    }
716
717    case XCB_PRESENT_EVENT_COMPLETE_NOTIFY: {
718       xcb_present_complete_notify_event_t *complete = (void *) event;
719       if (complete->kind == XCB_PRESENT_COMPLETE_KIND_PIXMAP)
720          chain->last_present_msc = complete->msc;
721       break;
722    }
723
724    default:
725       break;
726    }
727
728    return VK_SUCCESS;
729 }
730
731
732 static uint64_t wsi_get_current_time(void)
733 {
734    uint64_t current_time;
735    struct timespec tv;
736
737    clock_gettime(CLOCK_MONOTONIC, &tv);
738    current_time = tv.tv_nsec + tv.tv_sec*1000000000ull;
739    return current_time;
740 }
741
742 static uint64_t wsi_get_absolute_timeout(uint64_t timeout)
743 {
744    uint64_t current_time = wsi_get_current_time();
745
746    timeout = MIN2(UINT64_MAX - current_time, timeout);
747
748    return current_time + timeout;
749 }
750
751 static VkResult
752 x11_acquire_next_image_poll_x11(struct x11_swapchain *chain,
753                                 uint32_t *image_index, uint64_t timeout)
754 {
755    xcb_generic_event_t *event;
756    struct pollfd pfds;
757    uint64_t atimeout;
758    while (1) {
759       for (uint32_t i = 0; i < chain->base.image_count; i++) {
760          if (!chain->images[i].busy) {
761             /* We found a non-busy image */
762             xshmfence_await(chain->images[i].shm_fence);
763             *image_index = i;
764             chain->images[i].busy = true;
765             return VK_SUCCESS;
766          }
767       }
768
769       xcb_flush(chain->conn);
770
771       if (timeout == UINT64_MAX) {
772          event = xcb_wait_for_special_event(chain->conn, chain->special_event);
773          if (!event)
774             return VK_ERROR_OUT_OF_DATE_KHR;
775       } else {
776          event = xcb_poll_for_special_event(chain->conn, chain->special_event);
777          if (!event) {
778             int ret;
779             if (timeout == 0)
780                return VK_NOT_READY;
781
782             atimeout = wsi_get_absolute_timeout(timeout);
783
784             pfds.fd = xcb_get_file_descriptor(chain->conn);
785             pfds.events = POLLIN;
786             ret = poll(&pfds, 1, timeout / 1000 / 1000);
787             if (ret == 0)
788                return VK_TIMEOUT;
789             if (ret == -1)
790                return VK_ERROR_OUT_OF_DATE_KHR;
791
792             /* If a non-special event happens, the fd will still
793              * poll. So recalculate the timeout now just in case.
794              */
795             uint64_t current_time = wsi_get_current_time();
796             if (atimeout > current_time)
797                timeout = atimeout - current_time;
798             else
799                timeout = 0;
800             continue;
801          }
802       }
803
804       VkResult result = x11_handle_dri3_present_event(chain, (void *)event);
805       free(event);
806       if (result != VK_SUCCESS)
807          return result;
808    }
809 }
810
811 static VkResult
812 x11_acquire_next_image_from_queue(struct x11_swapchain *chain,
813                                   uint32_t *image_index_out, uint64_t timeout)
814 {
815    assert(chain->threaded);
816
817    uint32_t image_index;
818    VkResult result = wsi_queue_pull(&chain->acquire_queue,
819                                     &image_index, timeout);
820    if (result != VK_SUCCESS) {
821       return result;
822    } else if (chain->status != VK_SUCCESS) {
823       return chain->status;
824    }
825
826    assert(image_index < chain->base.image_count);
827    xshmfence_await(chain->images[image_index].shm_fence);
828
829    *image_index_out = image_index;
830
831    return VK_SUCCESS;
832 }
833
834 static VkResult
835 x11_present_to_x11(struct x11_swapchain *chain, uint32_t image_index,
836                    uint32_t target_msc)
837 {
838    struct x11_image *image = &chain->images[image_index];
839
840    assert(image_index < chain->base.image_count);
841
842    uint32_t options = XCB_PRESENT_OPTION_NONE;
843
844    int64_t divisor = 0;
845    int64_t remainder = 0;
846
847    if (chain->base.present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
848       options |= XCB_PRESENT_OPTION_ASYNC;
849
850    xshmfence_reset(image->shm_fence);
851
852    ++chain->send_sbc;
853    xcb_void_cookie_t cookie =
854       xcb_present_pixmap(chain->conn,
855                          chain->window,
856                          image->pixmap,
857                          (uint32_t) chain->send_sbc,
858                          0,                                    /* valid */
859                          0,                                    /* update */
860                          0,                                    /* x_off */
861                          0,                                    /* y_off */
862                          XCB_NONE,                             /* target_crtc */
863                          XCB_NONE,
864                          image->sync_fence,
865                          options,
866                          target_msc,
867                          divisor,
868                          remainder, 0, NULL);
869    xcb_discard_reply(chain->conn, cookie.sequence);
870    image->busy = true;
871
872    xcb_flush(chain->conn);
873
874    return VK_SUCCESS;
875 }
876
877 static VkResult
878 x11_acquire_next_image(struct wsi_swapchain *anv_chain,
879                        uint64_t timeout,
880                        VkSemaphore semaphore,
881                        uint32_t *image_index)
882 {
883    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
884
885    if (chain->threaded) {
886       return x11_acquire_next_image_from_queue(chain, image_index, timeout);
887    } else {
888       return x11_acquire_next_image_poll_x11(chain, image_index, timeout);
889    }
890 }
891
892 static VkResult
893 x11_queue_present(struct wsi_swapchain *anv_chain,
894                   uint32_t image_index,
895                   const VkPresentRegionKHR *damage)
896 {
897    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
898
899    if (chain->threaded) {
900       wsi_queue_push(&chain->present_queue, image_index);
901       return chain->status;
902    } else {
903       return x11_present_to_x11(chain, image_index, 0);
904    }
905 }
906
907 static void *
908 x11_manage_fifo_queues(void *state)
909 {
910    struct x11_swapchain *chain = state;
911    VkResult result;
912
913    assert(chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR);
914
915    while (chain->status == VK_SUCCESS) {
916       /* It should be safe to unconditionally block here.  Later in the loop
917        * we blocks until the previous present has landed on-screen.  At that
918        * point, we should have received IDLE_NOTIFY on all images presented
919        * before that point so the client should be able to acquire any image
920        * other than the currently presented one.
921        */
922       uint32_t image_index;
923       result = wsi_queue_pull(&chain->present_queue, &image_index, INT64_MAX);
924       if (result != VK_SUCCESS) {
925          goto fail;
926       } else if (chain->status != VK_SUCCESS) {
927          return NULL;
928       }
929
930       uint64_t target_msc = chain->last_present_msc + 1;
931       result = x11_present_to_x11(chain, image_index, target_msc);
932       if (result != VK_SUCCESS)
933          goto fail;
934
935       while (chain->last_present_msc < target_msc) {
936          xcb_generic_event_t *event =
937             xcb_wait_for_special_event(chain->conn, chain->special_event);
938          if (!event)
939             goto fail;
940
941          result = x11_handle_dri3_present_event(chain, (void *)event);
942          if (result != VK_SUCCESS)
943             goto fail;
944       }
945    }
946
947 fail:
948    chain->status = result;
949    wsi_queue_push(&chain->acquire_queue, UINT32_MAX);
950
951    return NULL;
952 }
953
954 static VkResult
955 x11_image_init(VkDevice device_h, struct x11_swapchain *chain,
956                const VkSwapchainCreateInfoKHR *pCreateInfo,
957                const VkAllocationCallbacks* pAllocator,
958                struct x11_image *image)
959 {
960    xcb_void_cookie_t cookie;
961    VkResult result;
962    uint32_t row_pitch;
963    uint32_t offset;
964    uint32_t bpp = 32;
965    int fd;
966    uint32_t size;
967
968    result = chain->base.image_fns->create_wsi_image(device_h,
969                                                     pCreateInfo,
970                                                     pAllocator,
971                                                     chain->base.needs_linear_copy,
972                                                     false,
973                                                     &image->image,
974                                                     &image->memory,
975                                                     &size,
976                                                     &offset,
977                                                     &row_pitch,
978                                                     &fd);
979    if (result != VK_SUCCESS)
980       return result;
981
982    if (chain->base.needs_linear_copy) {
983       result = chain->base.image_fns->create_wsi_image(device_h,
984                                                        pCreateInfo,
985                                                        pAllocator,
986                                                        chain->base.needs_linear_copy,
987                                                        true,
988                                                        &image->linear_image,
989                                                        &image->linear_memory,
990                                                        &size,
991                                                        &offset,
992                                                        &row_pitch,
993                                                        &fd);
994       if (result != VK_SUCCESS) {
995          chain->base.image_fns->free_wsi_image(device_h, pAllocator,
996                                                image->image, image->memory);
997          return result;
998       }
999    }
1000
1001    image->pixmap = xcb_generate_id(chain->conn);
1002
1003    cookie =
1004       xcb_dri3_pixmap_from_buffer_checked(chain->conn,
1005                                           image->pixmap,
1006                                           chain->window,
1007                                           size,
1008                                           pCreateInfo->imageExtent.width,
1009                                           pCreateInfo->imageExtent.height,
1010                                           row_pitch,
1011                                           chain->depth, bpp, fd);
1012    xcb_discard_reply(chain->conn, cookie.sequence);
1013
1014    int fence_fd = xshmfence_alloc_shm();
1015    if (fence_fd < 0)
1016       goto fail_pixmap;
1017
1018    image->shm_fence = xshmfence_map_shm(fence_fd);
1019    if (image->shm_fence == NULL)
1020       goto fail_shmfence_alloc;
1021
1022    image->sync_fence = xcb_generate_id(chain->conn);
1023    xcb_dri3_fence_from_fd(chain->conn,
1024                           image->pixmap,
1025                           image->sync_fence,
1026                           false,
1027                           fence_fd);
1028
1029    image->busy = false;
1030    xshmfence_trigger(image->shm_fence);
1031
1032    return VK_SUCCESS;
1033
1034 fail_shmfence_alloc:
1035    close(fence_fd);
1036
1037 fail_pixmap:
1038    cookie = xcb_free_pixmap(chain->conn, image->pixmap);
1039    xcb_discard_reply(chain->conn, cookie.sequence);
1040
1041    if (chain->base.needs_linear_copy) {
1042       chain->base.image_fns->free_wsi_image(device_h, pAllocator,
1043                                             image->linear_image, image->linear_memory);
1044    }
1045    chain->base.image_fns->free_wsi_image(device_h, pAllocator,
1046                                          image->image, image->memory);
1047
1048    return result;
1049 }
1050
1051 static void
1052 x11_image_finish(struct x11_swapchain *chain,
1053                  const VkAllocationCallbacks* pAllocator,
1054                  struct x11_image *image)
1055 {
1056    xcb_void_cookie_t cookie;
1057
1058    cookie = xcb_sync_destroy_fence(chain->conn, image->sync_fence);
1059    xcb_discard_reply(chain->conn, cookie.sequence);
1060    xshmfence_unmap_shm(image->shm_fence);
1061
1062    cookie = xcb_free_pixmap(chain->conn, image->pixmap);
1063    xcb_discard_reply(chain->conn, cookie.sequence);
1064
1065    if (chain->base.needs_linear_copy) {
1066       chain->base.image_fns->free_wsi_image(chain->base.device, pAllocator,
1067                                             image->linear_image, image->linear_memory);
1068    }
1069    chain->base.image_fns->free_wsi_image(chain->base.device, pAllocator,
1070                                         image->image, image->memory);
1071 }
1072
1073 static VkResult
1074 x11_swapchain_destroy(struct wsi_swapchain *anv_chain,
1075                       const VkAllocationCallbacks *pAllocator)
1076 {
1077    struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1078    xcb_void_cookie_t cookie;
1079
1080    for (uint32_t i = 0; i < chain->base.image_count; i++)
1081       x11_image_finish(chain, pAllocator, &chain->images[i]);
1082
1083    if (chain->threaded) {
1084       chain->status = VK_ERROR_OUT_OF_DATE_KHR;
1085       /* Push a UINT32_MAX to wake up the manager */
1086       wsi_queue_push(&chain->present_queue, UINT32_MAX);
1087       pthread_join(chain->queue_manager, NULL);
1088       wsi_queue_destroy(&chain->acquire_queue);
1089       wsi_queue_destroy(&chain->present_queue);
1090    }
1091
1092    xcb_unregister_for_special_event(chain->conn, chain->special_event);
1093    cookie = xcb_present_select_input_checked(chain->conn, chain->event_id,
1094                                              chain->window,
1095                                              XCB_PRESENT_EVENT_MASK_NO_EVENT);
1096    xcb_discard_reply(chain->conn, cookie.sequence);
1097
1098    vk_free(pAllocator, chain);
1099
1100    return VK_SUCCESS;
1101 }
1102
1103 static VkResult
1104 x11_surface_create_swapchain(VkIcdSurfaceBase *icd_surface,
1105                              VkDevice device,
1106                              struct wsi_device *wsi_device,
1107                              int local_fd,
1108                              const VkSwapchainCreateInfoKHR *pCreateInfo,
1109                              const VkAllocationCallbacks* pAllocator,
1110                              const struct wsi_image_fns *image_fns,
1111                              struct wsi_swapchain **swapchain_out)
1112 {
1113    struct x11_swapchain *chain;
1114    xcb_void_cookie_t cookie;
1115    VkResult result;
1116
1117    assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR);
1118
1119    const unsigned num_images = pCreateInfo->minImageCount;
1120
1121    size_t size = sizeof(*chain) + num_images * sizeof(chain->images[0]);
1122    chain = vk_alloc(pAllocator, size, 8,
1123                       VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1124    if (chain == NULL)
1125       return VK_ERROR_OUT_OF_HOST_MEMORY;
1126
1127    xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
1128    xcb_window_t window = x11_surface_get_window(icd_surface);
1129    xcb_get_geometry_reply_t *geometry =
1130       xcb_get_geometry_reply(conn, xcb_get_geometry(conn, window), NULL);
1131
1132    if (geometry == NULL)
1133       return VK_ERROR_SURFACE_LOST_KHR;
1134
1135    chain->base.device = device;
1136    chain->base.destroy = x11_swapchain_destroy;
1137    chain->base.get_images = x11_get_images;
1138    chain->base.get_image_and_linear = x11_get_image_and_linear;
1139    chain->base.acquire_next_image = x11_acquire_next_image;
1140    chain->base.queue_present = x11_queue_present;
1141    chain->base.image_fns = image_fns;
1142    chain->base.present_mode = pCreateInfo->presentMode;
1143    chain->base.image_count = num_images;
1144    chain->conn = conn;
1145    chain->window = window;
1146    chain->depth = geometry->depth;
1147    chain->extent = pCreateInfo->imageExtent;
1148    chain->send_sbc = 0;
1149    chain->last_present_msc = 0;
1150    chain->threaded = false;
1151    chain->status = VK_SUCCESS;
1152
1153    free(geometry);
1154
1155    chain->base.needs_linear_copy = false;
1156    if (!wsi_x11_check_dri3_compatible(conn, local_fd))
1157        chain->base.needs_linear_copy = true;
1158
1159    chain->event_id = xcb_generate_id(chain->conn);
1160    xcb_present_select_input(chain->conn, chain->event_id, chain->window,
1161                             XCB_PRESENT_EVENT_MASK_CONFIGURE_NOTIFY |
1162                             XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY |
1163                             XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY);
1164
1165    /* Create an XCB event queue to hold present events outside of the usual
1166     * application event queue
1167     */
1168    chain->special_event =
1169       xcb_register_for_special_xge(chain->conn, &xcb_present_id,
1170                                    chain->event_id, NULL);
1171
1172    chain->gc = xcb_generate_id(chain->conn);
1173    if (!chain->gc) {
1174       /* FINISHME: Choose a better error. */
1175       result = VK_ERROR_OUT_OF_HOST_MEMORY;
1176       goto fail_register;
1177    }
1178
1179    cookie = xcb_create_gc(chain->conn,
1180                           chain->gc,
1181                           chain->window,
1182                           XCB_GC_GRAPHICS_EXPOSURES,
1183                           (uint32_t []) { 0 });
1184    xcb_discard_reply(chain->conn, cookie.sequence);
1185
1186    uint32_t image = 0;
1187    for (; image < chain->base.image_count; image++) {
1188       result = x11_image_init(device, chain, pCreateInfo, pAllocator,
1189                               &chain->images[image]);
1190       if (result != VK_SUCCESS)
1191          goto fail_init_images;
1192    }
1193
1194    if (chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR) {
1195       chain->threaded = true;
1196
1197       /* Initialize our queues.  We make them base.image_count + 1 because we will
1198        * occasionally use UINT32_MAX to signal the other thread that an error
1199        * has occurred and we don't want an overflow.
1200        */
1201       int ret;
1202       ret = wsi_queue_init(&chain->acquire_queue, chain->base.image_count + 1);
1203       if (ret) {
1204          goto fail_init_images;
1205       }
1206
1207       ret = wsi_queue_init(&chain->present_queue, chain->base.image_count + 1);
1208       if (ret) {
1209          wsi_queue_destroy(&chain->acquire_queue);
1210          goto fail_init_images;
1211       }
1212
1213       for (unsigned i = 0; i < chain->base.image_count; i++)
1214          wsi_queue_push(&chain->acquire_queue, i);
1215
1216       ret = pthread_create(&chain->queue_manager, NULL,
1217                            x11_manage_fifo_queues, chain);
1218       if (ret) {
1219          wsi_queue_destroy(&chain->present_queue);
1220          wsi_queue_destroy(&chain->acquire_queue);
1221          goto fail_init_images;
1222       }
1223    }
1224
1225    *swapchain_out = &chain->base;
1226
1227    return VK_SUCCESS;
1228
1229 fail_init_images:
1230    for (uint32_t j = 0; j < image; j++)
1231       x11_image_finish(chain, pAllocator, &chain->images[j]);
1232
1233 fail_register:
1234    xcb_unregister_for_special_event(chain->conn, chain->special_event);
1235
1236    vk_free(pAllocator, chain);
1237
1238    return result;
1239 }
1240
1241 VkResult
1242 wsi_x11_init_wsi(struct wsi_device *wsi_device,
1243                  const VkAllocationCallbacks *alloc)
1244 {
1245    struct wsi_x11 *wsi;
1246    VkResult result;
1247
1248    wsi = vk_alloc(alloc, sizeof(*wsi), 8,
1249                    VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1250    if (!wsi) {
1251       result = VK_ERROR_OUT_OF_HOST_MEMORY;
1252       goto fail;
1253    }
1254
1255    int ret = pthread_mutex_init(&wsi->mutex, NULL);
1256    if (ret != 0) {
1257       if (ret == ENOMEM) {
1258          result = VK_ERROR_OUT_OF_HOST_MEMORY;
1259       } else {
1260          /* FINISHME: Choose a better error. */
1261          result = VK_ERROR_OUT_OF_HOST_MEMORY;
1262       }
1263
1264       goto fail_alloc;
1265    }
1266
1267    wsi->connections = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
1268                                               _mesa_key_pointer_equal);
1269    if (!wsi->connections) {
1270       result = VK_ERROR_OUT_OF_HOST_MEMORY;
1271       goto fail_mutex;
1272    }
1273
1274    wsi->base.get_support = x11_surface_get_support;
1275    wsi->base.get_capabilities = x11_surface_get_capabilities;
1276    wsi->base.get_capabilities2 = x11_surface_get_capabilities2;
1277    wsi->base.get_formats = x11_surface_get_formats;
1278    wsi->base.get_formats2 = x11_surface_get_formats2;
1279    wsi->base.get_present_modes = x11_surface_get_present_modes;
1280    wsi->base.create_swapchain = x11_surface_create_swapchain;
1281
1282    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = &wsi->base;
1283    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = &wsi->base;
1284
1285    return VK_SUCCESS;
1286
1287 fail_mutex:
1288    pthread_mutex_destroy(&wsi->mutex);
1289 fail_alloc:
1290    vk_free(alloc, wsi);
1291 fail:
1292    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = NULL;
1293    wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = NULL;
1294
1295    return result;
1296 }
1297
1298 void
1299 wsi_x11_finish_wsi(struct wsi_device *wsi_device,
1300                    const VkAllocationCallbacks *alloc)
1301 {
1302    struct wsi_x11 *wsi =
1303       (struct wsi_x11 *)wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB];
1304
1305    if (wsi) {
1306       struct hash_entry *entry;
1307       hash_table_foreach(wsi->connections, entry)
1308          wsi_x11_connection_destroy(alloc, entry->data);
1309
1310       _mesa_hash_table_destroy(wsi->connections, NULL);
1311
1312       pthread_mutex_destroy(&wsi->mutex);
1313
1314       vk_free(alloc, wsi);
1315    }
1316 }