vulkan/wsi/x11: Consistently update and return swapchain status
[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_private.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 VkBool32* pSupported)
409 {
410 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
411 xcb_window_t window = x11_surface_get_window(icd_surface);
412
413 struct wsi_x11_connection *wsi_conn =
414 wsi_x11_get_connection(wsi_device, alloc, conn);
415 if (!wsi_conn)
416 return VK_ERROR_OUT_OF_HOST_MEMORY;
417
418 if (!wsi_x11_check_for_dri3(wsi_conn)) {
419 *pSupported = false;
420 return VK_SUCCESS;
421 }
422
423 unsigned visual_depth;
424 if (!get_visualtype_for_window(conn, window, &visual_depth)) {
425 *pSupported = false;
426 return VK_SUCCESS;
427 }
428
429 if (visual_depth != 24 && visual_depth != 32) {
430 *pSupported = false;
431 return VK_SUCCESS;
432 }
433
434 *pSupported = true;
435 return VK_SUCCESS;
436 }
437
438 static VkResult
439 x11_surface_get_capabilities(VkIcdSurfaceBase *icd_surface,
440 VkSurfaceCapabilitiesKHR *caps)
441 {
442 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
443 xcb_window_t window = x11_surface_get_window(icd_surface);
444 xcb_get_geometry_cookie_t geom_cookie;
445 xcb_generic_error_t *err;
446 xcb_get_geometry_reply_t *geom;
447 unsigned visual_depth;
448
449 geom_cookie = xcb_get_geometry(conn, window);
450
451 /* This does a round-trip. This is why we do get_geometry first and
452 * wait to read the reply until after we have a visual.
453 */
454 xcb_visualtype_t *visual =
455 get_visualtype_for_window(conn, window, &visual_depth);
456
457 if (!visual)
458 return VK_ERROR_SURFACE_LOST_KHR;
459
460 geom = xcb_get_geometry_reply(conn, geom_cookie, &err);
461 if (geom) {
462 VkExtent2D extent = { geom->width, geom->height };
463 caps->currentExtent = extent;
464 caps->minImageExtent = extent;
465 caps->maxImageExtent = extent;
466 } else {
467 /* This can happen if the client didn't wait for the configure event
468 * to come back from the compositor. In that case, we don't know the
469 * size of the window so we just return valid "I don't know" stuff.
470 */
471 caps->currentExtent = (VkExtent2D) { -1, -1 };
472 caps->minImageExtent = (VkExtent2D) { 1, 1 };
473 /* This is the maximum supported size on Intel */
474 caps->maxImageExtent = (VkExtent2D) { 1 << 14, 1 << 14 };
475 }
476 free(err);
477 free(geom);
478
479 if (visual_has_alpha(visual, visual_depth)) {
480 caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
481 VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
482 } else {
483 caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
484 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
485 }
486
487 /* For true mailbox mode, we need at least 4 images:
488 * 1) One to scan out from
489 * 2) One to have queued for scan-out
490 * 3) One to be currently held by the X server
491 * 4) One to render to
492 */
493 caps->minImageCount = 2;
494 /* There is no real maximum */
495 caps->maxImageCount = 0;
496
497 caps->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
498 caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
499 caps->maxImageArrayLayers = 1;
500 caps->supportedUsageFlags =
501 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
502 VK_IMAGE_USAGE_SAMPLED_BIT |
503 VK_IMAGE_USAGE_TRANSFER_DST_BIT |
504 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
505
506 return VK_SUCCESS;
507 }
508
509 static VkResult
510 x11_surface_get_capabilities2(VkIcdSurfaceBase *icd_surface,
511 const void *info_next,
512 VkSurfaceCapabilities2KHR *caps)
513 {
514 assert(caps->sType == VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR);
515
516 return x11_surface_get_capabilities(icd_surface, &caps->surfaceCapabilities);
517 }
518
519 static VkResult
520 x11_surface_get_formats(VkIcdSurfaceBase *surface,
521 struct wsi_device *wsi_device,
522 uint32_t *pSurfaceFormatCount,
523 VkSurfaceFormatKHR *pSurfaceFormats)
524 {
525 VK_OUTARRAY_MAKE(out, pSurfaceFormats, pSurfaceFormatCount);
526
527 for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
528 vk_outarray_append(&out, f) {
529 f->format = formats[i];
530 f->colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
531 }
532 }
533
534 return vk_outarray_status(&out);
535 }
536
537 static VkResult
538 x11_surface_get_formats2(VkIcdSurfaceBase *surface,
539 struct wsi_device *wsi_device,
540 const void *info_next,
541 uint32_t *pSurfaceFormatCount,
542 VkSurfaceFormat2KHR *pSurfaceFormats)
543 {
544 VK_OUTARRAY_MAKE(out, pSurfaceFormats, pSurfaceFormatCount);
545
546 for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
547 vk_outarray_append(&out, f) {
548 assert(f->sType == VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR);
549 f->surfaceFormat.format = formats[i];
550 f->surfaceFormat.colorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
551 }
552 }
553
554 return vk_outarray_status(&out);
555 }
556
557 static VkResult
558 x11_surface_get_present_modes(VkIcdSurfaceBase *surface,
559 uint32_t *pPresentModeCount,
560 VkPresentModeKHR *pPresentModes)
561 {
562 if (pPresentModes == NULL) {
563 *pPresentModeCount = ARRAY_SIZE(present_modes);
564 return VK_SUCCESS;
565 }
566
567 *pPresentModeCount = MIN2(*pPresentModeCount, ARRAY_SIZE(present_modes));
568 typed_memcpy(pPresentModes, present_modes, *pPresentModeCount);
569
570 return *pPresentModeCount < ARRAY_SIZE(present_modes) ?
571 VK_INCOMPLETE : VK_SUCCESS;
572 }
573
574 VkResult wsi_create_xcb_surface(const VkAllocationCallbacks *pAllocator,
575 const VkXcbSurfaceCreateInfoKHR *pCreateInfo,
576 VkSurfaceKHR *pSurface)
577 {
578 VkIcdSurfaceXcb *surface;
579
580 surface = vk_alloc(pAllocator, sizeof *surface, 8,
581 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
582 if (surface == NULL)
583 return VK_ERROR_OUT_OF_HOST_MEMORY;
584
585 surface->base.platform = VK_ICD_WSI_PLATFORM_XCB;
586 surface->connection = pCreateInfo->connection;
587 surface->window = pCreateInfo->window;
588
589 *pSurface = VkIcdSurfaceBase_to_handle(&surface->base);
590 return VK_SUCCESS;
591 }
592
593 VkResult wsi_create_xlib_surface(const VkAllocationCallbacks *pAllocator,
594 const VkXlibSurfaceCreateInfoKHR *pCreateInfo,
595 VkSurfaceKHR *pSurface)
596 {
597 VkIcdSurfaceXlib *surface;
598
599 surface = vk_alloc(pAllocator, sizeof *surface, 8,
600 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
601 if (surface == NULL)
602 return VK_ERROR_OUT_OF_HOST_MEMORY;
603
604 surface->base.platform = VK_ICD_WSI_PLATFORM_XLIB;
605 surface->dpy = pCreateInfo->dpy;
606 surface->window = pCreateInfo->window;
607
608 *pSurface = VkIcdSurfaceBase_to_handle(&surface->base);
609 return VK_SUCCESS;
610 }
611
612 struct x11_image {
613 struct wsi_image base;
614 xcb_pixmap_t pixmap;
615 bool busy;
616 struct xshmfence * shm_fence;
617 uint32_t sync_fence;
618 };
619
620 struct x11_swapchain {
621 struct wsi_swapchain base;
622
623 xcb_connection_t * conn;
624 xcb_window_t window;
625 xcb_gc_t gc;
626 uint32_t depth;
627 VkExtent2D extent;
628
629 xcb_present_event_t event_id;
630 xcb_special_event_t * special_event;
631 uint64_t send_sbc;
632 uint64_t last_present_msc;
633 uint32_t stamp;
634
635 bool threaded;
636 VkResult status;
637 struct wsi_queue present_queue;
638 struct wsi_queue acquire_queue;
639 pthread_t queue_manager;
640
641 struct x11_image images[0];
642 };
643
644 /**
645 * Update the swapchain status with the result of an operation, and return
646 * the combined status. The chain status will eventually be returned from
647 * AcquireNextImage and QueuePresent.
648 *
649 * We make sure to 'stick' more pessimistic statuses: an out-of-date error
650 * is permanent once seen, and every subsequent call will return this. If
651 * this has not been seen, success will be returned.
652 */
653 static VkResult
654 x11_swapchain_result(struct x11_swapchain *chain, VkResult result)
655 {
656 /* Prioritise returning existing errors for consistency. */
657 if (chain->status < 0)
658 return chain->status;
659
660 /* If we have a new error, mark it as permanent on the chain and return. */
661 if (result < 0) {
662 chain->status = result;
663 return result;
664 }
665
666 /* Return temporary errors, but don't persist them. */
667 if (result == VK_TIMEOUT || result == VK_NOT_READY)
668 return result;
669
670 /* No changes, so return the last status. */
671 return chain->status;
672 }
673
674 static struct wsi_image *
675 x11_get_wsi_image(struct wsi_swapchain *wsi_chain, uint32_t image_index)
676 {
677 struct x11_swapchain *chain = (struct x11_swapchain *)wsi_chain;
678 return &chain->images[image_index].base;
679 }
680
681 /**
682 * Process an X11 Present event. Does not update chain->status.
683 */
684 static VkResult
685 x11_handle_dri3_present_event(struct x11_swapchain *chain,
686 xcb_present_generic_event_t *event)
687 {
688 switch (event->evtype) {
689 case XCB_PRESENT_CONFIGURE_NOTIFY: {
690 xcb_present_configure_notify_event_t *config = (void *) event;
691
692 if (config->width != chain->extent.width ||
693 config->height != chain->extent.height)
694 return VK_ERROR_OUT_OF_DATE_KHR;
695
696 break;
697 }
698
699 case XCB_PRESENT_EVENT_IDLE_NOTIFY: {
700 xcb_present_idle_notify_event_t *idle = (void *) event;
701
702 for (unsigned i = 0; i < chain->base.image_count; i++) {
703 if (chain->images[i].pixmap == idle->pixmap) {
704 chain->images[i].busy = false;
705 if (chain->threaded)
706 wsi_queue_push(&chain->acquire_queue, i);
707 break;
708 }
709 }
710
711 break;
712 }
713
714 case XCB_PRESENT_EVENT_COMPLETE_NOTIFY: {
715 xcb_present_complete_notify_event_t *complete = (void *) event;
716 if (complete->kind == XCB_PRESENT_COMPLETE_KIND_PIXMAP)
717 chain->last_present_msc = complete->msc;
718 break;
719 }
720
721 default:
722 break;
723 }
724
725 return VK_SUCCESS;
726 }
727
728
729 static uint64_t wsi_get_current_time(void)
730 {
731 uint64_t current_time;
732 struct timespec tv;
733
734 clock_gettime(CLOCK_MONOTONIC, &tv);
735 current_time = tv.tv_nsec + tv.tv_sec*1000000000ull;
736 return current_time;
737 }
738
739 static uint64_t wsi_get_absolute_timeout(uint64_t timeout)
740 {
741 uint64_t current_time = wsi_get_current_time();
742
743 timeout = MIN2(UINT64_MAX - current_time, timeout);
744
745 return current_time + timeout;
746 }
747
748 static VkResult
749 x11_acquire_next_image_poll_x11(struct x11_swapchain *chain,
750 uint32_t *image_index, uint64_t timeout)
751 {
752 xcb_generic_event_t *event;
753 struct pollfd pfds;
754 uint64_t atimeout;
755 while (1) {
756 for (uint32_t i = 0; i < chain->base.image_count; i++) {
757 if (!chain->images[i].busy) {
758 /* We found a non-busy image */
759 xshmfence_await(chain->images[i].shm_fence);
760 *image_index = i;
761 chain->images[i].busy = true;
762 return x11_swapchain_result(chain, VK_SUCCESS);
763 }
764 }
765
766 xcb_flush(chain->conn);
767
768 if (timeout == UINT64_MAX) {
769 event = xcb_wait_for_special_event(chain->conn, chain->special_event);
770 if (!event)
771 return x11_swapchain_result(chain, VK_ERROR_OUT_OF_DATE_KHR);
772 } else {
773 event = xcb_poll_for_special_event(chain->conn, chain->special_event);
774 if (!event) {
775 int ret;
776 if (timeout == 0)
777 return x11_swapchain_result(chain, VK_NOT_READY);
778
779 atimeout = wsi_get_absolute_timeout(timeout);
780
781 pfds.fd = xcb_get_file_descriptor(chain->conn);
782 pfds.events = POLLIN;
783 ret = poll(&pfds, 1, timeout / 1000 / 1000);
784 if (ret == 0)
785 return x11_swapchain_result(chain, VK_TIMEOUT);
786 if (ret == -1)
787 return x11_swapchain_result(chain, VK_ERROR_OUT_OF_DATE_KHR);
788
789 /* If a non-special event happens, the fd will still
790 * poll. So recalculate the timeout now just in case.
791 */
792 uint64_t current_time = wsi_get_current_time();
793 if (atimeout > current_time)
794 timeout = atimeout - current_time;
795 else
796 timeout = 0;
797 continue;
798 }
799 }
800
801 /* Update the swapchain status here. We may catch non-fatal errors here,
802 * in which case we need to update the status and continue.
803 */
804 VkResult result = x11_handle_dri3_present_event(chain, (void *)event);
805 free(event);
806 if (result < 0)
807 return x11_swapchain_result(chain, 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 < 0 || result == VK_TIMEOUT) {
821 /* On error, the thread has shut down, so safe to update chain->status.
822 * Calling x11_swapchain_result with VK_TIMEOUT won't modify
823 * chain->status so that is also safe.
824 */
825 return x11_swapchain_result(chain, result);
826 } else if (chain->status < 0) {
827 return chain->status;
828 }
829
830 assert(image_index < chain->base.image_count);
831 xshmfence_await(chain->images[image_index].shm_fence);
832
833 *image_index_out = image_index;
834
835 return chain->status;
836 }
837
838 static VkResult
839 x11_present_to_x11(struct x11_swapchain *chain, uint32_t image_index,
840 uint32_t target_msc)
841 {
842 struct x11_image *image = &chain->images[image_index];
843
844 assert(image_index < chain->base.image_count);
845
846 uint32_t options = XCB_PRESENT_OPTION_NONE;
847
848 int64_t divisor = 0;
849 int64_t remainder = 0;
850
851 if (chain->base.present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR)
852 options |= XCB_PRESENT_OPTION_ASYNC;
853
854 xshmfence_reset(image->shm_fence);
855
856 ++chain->send_sbc;
857 xcb_void_cookie_t cookie =
858 xcb_present_pixmap(chain->conn,
859 chain->window,
860 image->pixmap,
861 (uint32_t) chain->send_sbc,
862 0, /* valid */
863 0, /* update */
864 0, /* x_off */
865 0, /* y_off */
866 XCB_NONE, /* target_crtc */
867 XCB_NONE,
868 image->sync_fence,
869 options,
870 target_msc,
871 divisor,
872 remainder, 0, NULL);
873 xcb_discard_reply(chain->conn, cookie.sequence);
874 image->busy = true;
875
876 xcb_flush(chain->conn);
877
878 return x11_swapchain_result(chain, VK_SUCCESS);
879 }
880
881 static VkResult
882 x11_acquire_next_image(struct wsi_swapchain *anv_chain,
883 uint64_t timeout,
884 VkSemaphore semaphore,
885 uint32_t *image_index)
886 {
887 struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
888
889 if (chain->threaded) {
890 return x11_acquire_next_image_from_queue(chain, image_index, timeout);
891 } else {
892 return x11_acquire_next_image_poll_x11(chain, image_index, timeout);
893 }
894 }
895
896 static VkResult
897 x11_queue_present(struct wsi_swapchain *anv_chain,
898 uint32_t image_index,
899 const VkPresentRegionKHR *damage)
900 {
901 struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
902
903 if (chain->threaded) {
904 wsi_queue_push(&chain->present_queue, image_index);
905 return chain->status;
906 } else {
907 return x11_present_to_x11(chain, image_index, 0);
908 }
909 }
910
911 static void *
912 x11_manage_fifo_queues(void *state)
913 {
914 struct x11_swapchain *chain = state;
915 VkResult result;
916
917 assert(chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR);
918
919 while (chain->status >= 0) {
920 /* It should be safe to unconditionally block here. Later in the loop
921 * we blocks until the previous present has landed on-screen. At that
922 * point, we should have received IDLE_NOTIFY on all images presented
923 * before that point so the client should be able to acquire any image
924 * other than the currently presented one.
925 */
926 uint32_t image_index;
927 result = wsi_queue_pull(&chain->present_queue, &image_index, INT64_MAX);
928 assert(result != VK_TIMEOUT);
929 if (result < 0) {
930 goto fail;
931 } else if (chain->status < 0) {
932 /* The status can change underneath us if the swapchain is destroyed
933 * from another thread.
934 */
935 return NULL;
936 }
937
938 uint64_t target_msc = chain->last_present_msc + 1;
939 result = x11_present_to_x11(chain, image_index, target_msc);
940 if (result < 0)
941 goto fail;
942
943 while (chain->last_present_msc < target_msc) {
944 xcb_generic_event_t *event =
945 xcb_wait_for_special_event(chain->conn, chain->special_event);
946 if (!event) {
947 result = VK_ERROR_OUT_OF_DATE_KHR;
948 goto fail;
949 }
950
951 result = x11_handle_dri3_present_event(chain, (void *)event);
952 free(event);
953 if (result < 0)
954 goto fail;
955 }
956 }
957
958 fail:
959 result = x11_swapchain_result(chain, result);
960 wsi_queue_push(&chain->acquire_queue, UINT32_MAX);
961
962 return NULL;
963 }
964
965 static VkResult
966 x11_image_init(VkDevice device_h, struct x11_swapchain *chain,
967 const VkSwapchainCreateInfoKHR *pCreateInfo,
968 const VkAllocationCallbacks* pAllocator,
969 struct x11_image *image)
970 {
971 xcb_void_cookie_t cookie;
972 VkResult result;
973 uint32_t bpp = 32;
974
975 if (chain->base.use_prime_blit) {
976 result = wsi_create_prime_image(&chain->base, pCreateInfo, &image->base);
977 } else {
978 result = wsi_create_native_image(&chain->base, pCreateInfo,
979 0, NULL, NULL, &image->base);
980 }
981 if (result < 0)
982 return result;
983
984 image->pixmap = xcb_generate_id(chain->conn);
985
986 /* Without passing modifiers, we can't have multi-plane RGB images. */
987 assert(image->base.num_planes == 1);
988
989 cookie =
990 xcb_dri3_pixmap_from_buffer_checked(chain->conn,
991 image->pixmap,
992 chain->window,
993 image->base.sizes[0],
994 pCreateInfo->imageExtent.width,
995 pCreateInfo->imageExtent.height,
996 image->base.row_pitches[0],
997 chain->depth, bpp,
998 image->base.fds[0]);
999 xcb_discard_reply(chain->conn, cookie.sequence);
1000 image->base.fds[0] = -1; /* XCB has now taken ownership of the FD */
1001
1002 int fence_fd = xshmfence_alloc_shm();
1003 if (fence_fd < 0)
1004 goto fail_pixmap;
1005
1006 image->shm_fence = xshmfence_map_shm(fence_fd);
1007 if (image->shm_fence == NULL)
1008 goto fail_shmfence_alloc;
1009
1010 image->sync_fence = xcb_generate_id(chain->conn);
1011 xcb_dri3_fence_from_fd(chain->conn,
1012 image->pixmap,
1013 image->sync_fence,
1014 false,
1015 fence_fd);
1016
1017 image->busy = false;
1018 xshmfence_trigger(image->shm_fence);
1019
1020 return VK_SUCCESS;
1021
1022 fail_shmfence_alloc:
1023 close(fence_fd);
1024
1025 fail_pixmap:
1026 cookie = xcb_free_pixmap(chain->conn, image->pixmap);
1027 xcb_discard_reply(chain->conn, cookie.sequence);
1028
1029 wsi_destroy_image(&chain->base, &image->base);
1030
1031 return result;
1032 }
1033
1034 static void
1035 x11_image_finish(struct x11_swapchain *chain,
1036 const VkAllocationCallbacks* pAllocator,
1037 struct x11_image *image)
1038 {
1039 xcb_void_cookie_t cookie;
1040
1041 cookie = xcb_sync_destroy_fence(chain->conn, image->sync_fence);
1042 xcb_discard_reply(chain->conn, cookie.sequence);
1043 xshmfence_unmap_shm(image->shm_fence);
1044
1045 cookie = xcb_free_pixmap(chain->conn, image->pixmap);
1046 xcb_discard_reply(chain->conn, cookie.sequence);
1047
1048 wsi_destroy_image(&chain->base, &image->base);
1049 }
1050
1051 static VkResult
1052 x11_swapchain_destroy(struct wsi_swapchain *anv_chain,
1053 const VkAllocationCallbacks *pAllocator)
1054 {
1055 struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1056 xcb_void_cookie_t cookie;
1057
1058 for (uint32_t i = 0; i < chain->base.image_count; i++)
1059 x11_image_finish(chain, pAllocator, &chain->images[i]);
1060
1061 if (chain->threaded) {
1062 chain->status = VK_ERROR_OUT_OF_DATE_KHR;
1063 /* Push a UINT32_MAX to wake up the manager */
1064 wsi_queue_push(&chain->present_queue, UINT32_MAX);
1065 pthread_join(chain->queue_manager, NULL);
1066 wsi_queue_destroy(&chain->acquire_queue);
1067 wsi_queue_destroy(&chain->present_queue);
1068 }
1069
1070 xcb_unregister_for_special_event(chain->conn, chain->special_event);
1071 cookie = xcb_present_select_input_checked(chain->conn, chain->event_id,
1072 chain->window,
1073 XCB_PRESENT_EVENT_MASK_NO_EVENT);
1074 xcb_discard_reply(chain->conn, cookie.sequence);
1075
1076 wsi_swapchain_finish(&chain->base);
1077
1078 vk_free(pAllocator, chain);
1079
1080 return VK_SUCCESS;
1081 }
1082
1083 static VkResult
1084 x11_surface_create_swapchain(VkIcdSurfaceBase *icd_surface,
1085 VkDevice device,
1086 struct wsi_device *wsi_device,
1087 int local_fd,
1088 const VkSwapchainCreateInfoKHR *pCreateInfo,
1089 const VkAllocationCallbacks* pAllocator,
1090 struct wsi_swapchain **swapchain_out)
1091 {
1092 struct x11_swapchain *chain;
1093 xcb_void_cookie_t cookie;
1094 VkResult result;
1095
1096 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR);
1097
1098 const unsigned num_images = pCreateInfo->minImageCount;
1099
1100 /* Check for whether or not we have a window up-front */
1101 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
1102 xcb_window_t window = x11_surface_get_window(icd_surface);
1103 xcb_get_geometry_reply_t *geometry =
1104 xcb_get_geometry_reply(conn, xcb_get_geometry(conn, window), NULL);
1105 if (geometry == NULL)
1106 return VK_ERROR_SURFACE_LOST_KHR;
1107 const uint32_t bit_depth = geometry->depth;
1108 free(geometry);
1109
1110 size_t size = sizeof(*chain) + num_images * sizeof(chain->images[0]);
1111 chain = vk_alloc(pAllocator, size, 8,
1112 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1113 if (chain == NULL)
1114 return VK_ERROR_OUT_OF_HOST_MEMORY;
1115
1116 result = wsi_swapchain_init(wsi_device, &chain->base, device,
1117 pCreateInfo, pAllocator);
1118 if (result != VK_SUCCESS)
1119 goto fail_alloc;
1120
1121 chain->base.destroy = x11_swapchain_destroy;
1122 chain->base.get_wsi_image = x11_get_wsi_image;
1123 chain->base.acquire_next_image = x11_acquire_next_image;
1124 chain->base.queue_present = x11_queue_present;
1125 chain->base.present_mode = pCreateInfo->presentMode;
1126 chain->base.image_count = num_images;
1127 chain->conn = conn;
1128 chain->window = window;
1129 chain->depth = bit_depth;
1130 chain->extent = pCreateInfo->imageExtent;
1131 chain->send_sbc = 0;
1132 chain->last_present_msc = 0;
1133 chain->threaded = false;
1134 chain->status = VK_SUCCESS;
1135
1136 if (!wsi_x11_check_dri3_compatible(conn, local_fd))
1137 chain->base.use_prime_blit = true;
1138
1139 chain->event_id = xcb_generate_id(chain->conn);
1140 xcb_present_select_input(chain->conn, chain->event_id, chain->window,
1141 XCB_PRESENT_EVENT_MASK_CONFIGURE_NOTIFY |
1142 XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY |
1143 XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY);
1144
1145 /* Create an XCB event queue to hold present events outside of the usual
1146 * application event queue
1147 */
1148 chain->special_event =
1149 xcb_register_for_special_xge(chain->conn, &xcb_present_id,
1150 chain->event_id, NULL);
1151
1152 chain->gc = xcb_generate_id(chain->conn);
1153 if (!chain->gc) {
1154 /* FINISHME: Choose a better error. */
1155 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1156 goto fail_register;
1157 }
1158
1159 cookie = xcb_create_gc(chain->conn,
1160 chain->gc,
1161 chain->window,
1162 XCB_GC_GRAPHICS_EXPOSURES,
1163 (uint32_t []) { 0 });
1164 xcb_discard_reply(chain->conn, cookie.sequence);
1165
1166 uint32_t image = 0;
1167 for (; image < chain->base.image_count; image++) {
1168 result = x11_image_init(device, chain, pCreateInfo, pAllocator,
1169 &chain->images[image]);
1170 if (result != VK_SUCCESS)
1171 goto fail_init_images;
1172 }
1173
1174 if (chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR) {
1175 chain->threaded = true;
1176
1177 /* Initialize our queues. We make them base.image_count + 1 because we will
1178 * occasionally use UINT32_MAX to signal the other thread that an error
1179 * has occurred and we don't want an overflow.
1180 */
1181 int ret;
1182 ret = wsi_queue_init(&chain->acquire_queue, chain->base.image_count + 1);
1183 if (ret) {
1184 goto fail_init_images;
1185 }
1186
1187 ret = wsi_queue_init(&chain->present_queue, chain->base.image_count + 1);
1188 if (ret) {
1189 wsi_queue_destroy(&chain->acquire_queue);
1190 goto fail_init_images;
1191 }
1192
1193 for (unsigned i = 0; i < chain->base.image_count; i++)
1194 wsi_queue_push(&chain->acquire_queue, i);
1195
1196 ret = pthread_create(&chain->queue_manager, NULL,
1197 x11_manage_fifo_queues, chain);
1198 if (ret) {
1199 wsi_queue_destroy(&chain->present_queue);
1200 wsi_queue_destroy(&chain->acquire_queue);
1201 goto fail_init_images;
1202 }
1203 }
1204
1205 *swapchain_out = &chain->base;
1206
1207 return VK_SUCCESS;
1208
1209 fail_init_images:
1210 for (uint32_t j = 0; j < image; j++)
1211 x11_image_finish(chain, pAllocator, &chain->images[j]);
1212
1213 fail_register:
1214 xcb_unregister_for_special_event(chain->conn, chain->special_event);
1215
1216 wsi_swapchain_finish(&chain->base);
1217
1218 fail_alloc:
1219 vk_free(pAllocator, chain);
1220
1221 return result;
1222 }
1223
1224 VkResult
1225 wsi_x11_init_wsi(struct wsi_device *wsi_device,
1226 const VkAllocationCallbacks *alloc)
1227 {
1228 struct wsi_x11 *wsi;
1229 VkResult result;
1230
1231 wsi = vk_alloc(alloc, sizeof(*wsi), 8,
1232 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
1233 if (!wsi) {
1234 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1235 goto fail;
1236 }
1237
1238 int ret = pthread_mutex_init(&wsi->mutex, NULL);
1239 if (ret != 0) {
1240 if (ret == ENOMEM) {
1241 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1242 } else {
1243 /* FINISHME: Choose a better error. */
1244 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1245 }
1246
1247 goto fail_alloc;
1248 }
1249
1250 wsi->connections = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
1251 _mesa_key_pointer_equal);
1252 if (!wsi->connections) {
1253 result = VK_ERROR_OUT_OF_HOST_MEMORY;
1254 goto fail_mutex;
1255 }
1256
1257 wsi->base.get_support = x11_surface_get_support;
1258 wsi->base.get_capabilities = x11_surface_get_capabilities;
1259 wsi->base.get_capabilities2 = x11_surface_get_capabilities2;
1260 wsi->base.get_formats = x11_surface_get_formats;
1261 wsi->base.get_formats2 = x11_surface_get_formats2;
1262 wsi->base.get_present_modes = x11_surface_get_present_modes;
1263 wsi->base.create_swapchain = x11_surface_create_swapchain;
1264
1265 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = &wsi->base;
1266 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = &wsi->base;
1267
1268 return VK_SUCCESS;
1269
1270 fail_mutex:
1271 pthread_mutex_destroy(&wsi->mutex);
1272 fail_alloc:
1273 vk_free(alloc, wsi);
1274 fail:
1275 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = NULL;
1276 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = NULL;
1277
1278 return result;
1279 }
1280
1281 void
1282 wsi_x11_finish_wsi(struct wsi_device *wsi_device,
1283 const VkAllocationCallbacks *alloc)
1284 {
1285 struct wsi_x11 *wsi =
1286 (struct wsi_x11 *)wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB];
1287
1288 if (wsi) {
1289 struct hash_entry *entry;
1290 hash_table_foreach(wsi->connections, entry)
1291 wsi_x11_connection_destroy(alloc, entry->data);
1292
1293 _mesa_hash_table_destroy(wsi->connections, NULL);
1294
1295 pthread_mutex_destroy(&wsi->mutex);
1296
1297 vk_free(alloc, wsi);
1298 }
1299 }