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