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 #define XK_MISCELLANY
27 #define XK_LATIN1
28 #include <X11/keysymdef.h>
29 #include <xcb/xcb.h>
30 #ifdef XCB_KEYSYMS_AVAILABLE
31 #include <xcb/xcb_keysyms.h>
32 #endif
33 #include <xcb/dri3.h>
34 #include <xcb/present.h>
35 #include <xcb/shm.h>
36
37 #include "util/macros.h"
38 #include <stdatomic.h>
39 #include <stdlib.h>
40 #include <stdio.h>
41 #include <unistd.h>
42 #include <errno.h>
43 #include <string.h>
44 #include <fcntl.h>
45 #include <poll.h>
46 #include <xf86drm.h>
47 #include "drm-uapi/drm_fourcc.h"
48 #include "util/hash_table.h"
49 #include "util/os_file.h"
50 #include "util/os_time.h"
51 #include "util/u_debug.h"
52 #include "util/u_thread.h"
53 #include "util/xmlconfig.h"
54 #include "util/timespec.h"
55
56 #include "vk_format.h"
57 #include "vk_instance.h"
58 #include "vk_physical_device.h"
59 #include "vk_device.h"
60 #include "vk_util.h"
61 #include "vk_enum_to_str.h"
62 #include "wsi_common_entrypoints.h"
63 #include "wsi_common_private.h"
64 #include "wsi_common_queue.h"
65
66 #ifdef HAVE_SYS_SHM_H
67 #include <sys/ipc.h>
68 #include <sys/shm.h>
69 #endif
70
71 #ifndef XCB_PRESENT_OPTION_ASYNC_MAY_TEAR
72 #define XCB_PRESENT_OPTION_ASYNC_MAY_TEAR 16
73 #endif
74 #ifndef XCB_PRESENT_CAPABILITY_ASYNC_MAY_TEAR
75 #define XCB_PRESENT_CAPABILITY_ASYNC_MAY_TEAR 8
76 #endif
77
78 struct wsi_x11_connection {
79 bool has_dri3;
80 bool has_dri3_modifiers;
81 bool has_present;
82 bool is_proprietary_x11;
83 bool is_xwayland;
84 bool has_mit_shm;
85 bool has_xfixes;
86 };
87
88 struct wsi_x11 {
89 struct wsi_interface base;
90
91 pthread_mutex_t mutex;
92 /* Hash table of xcb_connection -> wsi_x11_connection mappings */
93 struct hash_table *connections;
94 };
95
96 struct wsi_x11_vk_surface {
97 union {
98 VkIcdSurfaceXlib xlib;
99 VkIcdSurfaceXcb xcb;
100 };
101 bool has_alpha;
102 };
103
104 /**
105 * Wrapper around xcb_dri3_open. Returns the opened fd or -1 on error.
106 */
107 static int
wsi_dri3_open(xcb_connection_t * conn,xcb_window_t root,uint32_t provider)108 wsi_dri3_open(xcb_connection_t *conn,
109 xcb_window_t root,
110 uint32_t provider)
111 {
112 xcb_dri3_open_cookie_t cookie;
113 xcb_dri3_open_reply_t *reply;
114 int fd;
115
116 cookie = xcb_dri3_open(conn,
117 root,
118 provider);
119
120 reply = xcb_dri3_open_reply(conn, cookie, NULL);
121 if (!reply)
122 return -1;
123
124 /* According to DRI3 extension nfd must equal one. */
125 if (reply->nfd != 1) {
126 free(reply);
127 return -1;
128 }
129
130 fd = xcb_dri3_open_reply_fds(conn, reply)[0];
131 free(reply);
132 fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC);
133
134 return fd;
135 }
136
137 /**
138 * Checks compatibility of the device wsi_dev with the device the X server
139 * provides via DRI3.
140 *
141 * This returns true when no device could be retrieved from the X server or when
142 * the information for the X server device indicate that it is the same device.
143 */
144 static bool
wsi_x11_check_dri3_compatible(const struct wsi_device * wsi_dev,xcb_connection_t * conn)145 wsi_x11_check_dri3_compatible(const struct wsi_device *wsi_dev,
146 xcb_connection_t *conn)
147 {
148 xcb_screen_iterator_t screen_iter =
149 xcb_setup_roots_iterator(xcb_get_setup(conn));
150 xcb_screen_t *screen = screen_iter.data;
151
152 /* Open the DRI3 device from the X server. If we do not retrieve one we
153 * assume our local device is compatible.
154 */
155 int dri3_fd = wsi_dri3_open(conn, screen->root, None);
156 if (dri3_fd == -1)
157 return true;
158
159 bool match = wsi_device_matches_drm_fd(wsi_dev, dri3_fd);
160
161 close(dri3_fd);
162
163 return match;
164 }
165
166 static bool
wsi_x11_detect_xwayland(xcb_connection_t * conn,xcb_query_extension_reply_t * randr_reply,xcb_query_extension_reply_t * xwl_reply)167 wsi_x11_detect_xwayland(xcb_connection_t *conn,
168 xcb_query_extension_reply_t *randr_reply,
169 xcb_query_extension_reply_t *xwl_reply)
170 {
171 /* Newer Xwayland exposes an X11 extension we can check for */
172 if (xwl_reply && xwl_reply->present)
173 return true;
174
175 /* Older Xwayland uses the word "XWAYLAND" in the RandR output names */
176 if (!randr_reply || !randr_reply->present)
177 return false;
178
179 xcb_randr_query_version_cookie_t ver_cookie =
180 xcb_randr_query_version_unchecked(conn, 1, 3);
181 xcb_randr_query_version_reply_t *ver_reply =
182 xcb_randr_query_version_reply(conn, ver_cookie, NULL);
183 bool has_randr_v1_3 = ver_reply && (ver_reply->major_version > 1 ||
184 ver_reply->minor_version >= 3);
185 free(ver_reply);
186
187 if (!has_randr_v1_3)
188 return false;
189
190 const xcb_setup_t *setup = xcb_get_setup(conn);
191 xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);
192
193 xcb_randr_get_screen_resources_current_cookie_t gsr_cookie =
194 xcb_randr_get_screen_resources_current_unchecked(conn, iter.data->root);
195 xcb_randr_get_screen_resources_current_reply_t *gsr_reply =
196 xcb_randr_get_screen_resources_current_reply(conn, gsr_cookie, NULL);
197
198 if (!gsr_reply || gsr_reply->num_outputs == 0) {
199 free(gsr_reply);
200 return false;
201 }
202
203 xcb_randr_output_t *randr_outputs =
204 xcb_randr_get_screen_resources_current_outputs(gsr_reply);
205 xcb_randr_get_output_info_cookie_t goi_cookie =
206 xcb_randr_get_output_info(conn, randr_outputs[0], gsr_reply->config_timestamp);
207 free(gsr_reply);
208
209 xcb_randr_get_output_info_reply_t *goi_reply =
210 xcb_randr_get_output_info_reply(conn, goi_cookie, NULL);
211 if (!goi_reply) {
212 return false;
213 }
214
215 char *output_name = (char*)xcb_randr_get_output_info_name(goi_reply);
216 bool is_xwayland = output_name && strncmp(output_name, "XWAYLAND", 8) == 0;
217 free(goi_reply);
218
219 return is_xwayland;
220 }
221
222 static struct wsi_x11_connection *
wsi_x11_connection_create(struct wsi_device * wsi_dev,xcb_connection_t * conn)223 wsi_x11_connection_create(struct wsi_device *wsi_dev,
224 xcb_connection_t *conn)
225 {
226 xcb_query_extension_cookie_t dri3_cookie, pres_cookie, randr_cookie,
227 amd_cookie, nv_cookie, shm_cookie, sync_cookie,
228 xfixes_cookie, xwl_cookie;
229 xcb_query_extension_reply_t *dri3_reply, *pres_reply, *randr_reply,
230 *amd_reply, *nv_reply, *shm_reply = NULL,
231 *xfixes_reply, *xwl_reply;
232 bool wants_shm = wsi_dev->sw && !(WSI_DEBUG & WSI_DEBUG_NOSHM) &&
233 wsi_dev->has_import_memory_host;
234 bool has_dri3_v1_2 = false;
235 bool has_present_v1_2 = false;
236
237 struct wsi_x11_connection *wsi_conn =
238 vk_alloc(&wsi_dev->instance_alloc, sizeof(*wsi_conn), 8,
239 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
240 if (!wsi_conn)
241 return NULL;
242
243 sync_cookie = xcb_query_extension(conn, 4, "SYNC");
244 dri3_cookie = xcb_query_extension(conn, 4, "DRI3");
245 pres_cookie = xcb_query_extension(conn, 7, "Present");
246 randr_cookie = xcb_query_extension(conn, 5, "RANDR");
247 xfixes_cookie = xcb_query_extension(conn, 6, "XFIXES");
248 xwl_cookie = xcb_query_extension(conn, 8, "XWAYLAND");
249
250 if (wants_shm)
251 shm_cookie = xcb_query_extension(conn, 7, "MIT-SHM");
252
253 /* We try to be nice to users and emit a warning if they try to use a
254 * Vulkan application on a system without DRI3 enabled. However, this ends
255 * up spewing the warning when a user has, for example, both Intel
256 * integrated graphics and a discrete card with proprietary drivers and are
257 * running on the discrete card with the proprietary DDX. In this case, we
258 * really don't want to print the warning because it just confuses users.
259 * As a heuristic to detect this case, we check for a couple of proprietary
260 * X11 extensions.
261 */
262 amd_cookie = xcb_query_extension(conn, 11, "ATIFGLRXDRI");
263 nv_cookie = xcb_query_extension(conn, 10, "NV-CONTROL");
264
265 xcb_discard_reply(conn, sync_cookie.sequence);
266 dri3_reply = xcb_query_extension_reply(conn, dri3_cookie, NULL);
267 pres_reply = xcb_query_extension_reply(conn, pres_cookie, NULL);
268 randr_reply = xcb_query_extension_reply(conn, randr_cookie, NULL);
269 amd_reply = xcb_query_extension_reply(conn, amd_cookie, NULL);
270 nv_reply = xcb_query_extension_reply(conn, nv_cookie, NULL);
271 xfixes_reply = xcb_query_extension_reply(conn, xfixes_cookie, NULL);
272 xwl_reply = xcb_query_extension_reply(conn, xwl_cookie, NULL);
273 if (wants_shm)
274 shm_reply = xcb_query_extension_reply(conn, shm_cookie, NULL);
275 if (!dri3_reply || !pres_reply || !xfixes_reply) {
276 free(dri3_reply);
277 free(pres_reply);
278 free(xfixes_reply);
279 free(xwl_reply);
280 free(randr_reply);
281 free(amd_reply);
282 free(nv_reply);
283 if (wants_shm)
284 free(shm_reply);
285 vk_free(&wsi_dev->instance_alloc, wsi_conn);
286 return NULL;
287 }
288
289 wsi_conn->has_dri3 = dri3_reply->present != 0;
290 #ifdef HAVE_DRI3_MODIFIERS
291 if (wsi_conn->has_dri3) {
292 xcb_dri3_query_version_cookie_t ver_cookie;
293 xcb_dri3_query_version_reply_t *ver_reply;
294
295 ver_cookie = xcb_dri3_query_version(conn, 1, 2);
296 ver_reply = xcb_dri3_query_version_reply(conn, ver_cookie, NULL);
297 has_dri3_v1_2 = ver_reply != NULL &&
298 (ver_reply->major_version > 1 || ver_reply->minor_version >= 2);
299 free(ver_reply);
300 }
301 #endif
302
303 wsi_conn->has_present = pres_reply->present != 0;
304 #ifdef HAVE_DRI3_MODIFIERS
305 if (wsi_conn->has_present) {
306 xcb_present_query_version_cookie_t ver_cookie;
307 xcb_present_query_version_reply_t *ver_reply;
308
309 ver_cookie = xcb_present_query_version(conn, 1, 2);
310 ver_reply = xcb_present_query_version_reply(conn, ver_cookie, NULL);
311 has_present_v1_2 =
312 (ver_reply->major_version > 1 || ver_reply->minor_version >= 2);
313 free(ver_reply);
314 }
315 #endif
316
317 wsi_conn->has_xfixes = xfixes_reply->present != 0;
318 if (wsi_conn->has_xfixes) {
319 xcb_xfixes_query_version_cookie_t ver_cookie;
320 xcb_xfixes_query_version_reply_t *ver_reply;
321
322 ver_cookie = xcb_xfixes_query_version(conn, 6, 0);
323 ver_reply = xcb_xfixes_query_version_reply(conn, ver_cookie, NULL);
324 wsi_conn->has_xfixes = (ver_reply->major_version >= 2);
325 free(ver_reply);
326 }
327
328 wsi_conn->is_xwayland = wsi_x11_detect_xwayland(conn, randr_reply,
329 xwl_reply);
330
331 wsi_conn->has_dri3_modifiers = has_dri3_v1_2 && has_present_v1_2;
332 wsi_conn->is_proprietary_x11 = false;
333 if (amd_reply && amd_reply->present)
334 wsi_conn->is_proprietary_x11 = true;
335 if (nv_reply && nv_reply->present)
336 wsi_conn->is_proprietary_x11 = true;
337
338 wsi_conn->has_mit_shm = false;
339 if (wsi_conn->has_dri3 && wsi_conn->has_present && wants_shm) {
340 bool has_mit_shm = shm_reply->present != 0;
341
342 xcb_shm_query_version_cookie_t ver_cookie;
343 xcb_shm_query_version_reply_t *ver_reply;
344
345 ver_cookie = xcb_shm_query_version(conn);
346 ver_reply = xcb_shm_query_version_reply(conn, ver_cookie, NULL);
347
348 has_mit_shm = ver_reply->shared_pixmaps;
349 free(ver_reply);
350 xcb_void_cookie_t cookie;
351 xcb_generic_error_t *error;
352
353 if (has_mit_shm) {
354 cookie = xcb_shm_detach_checked(conn, 0);
355 if ((error = xcb_request_check(conn, cookie))) {
356 if (error->error_code != BadRequest)
357 wsi_conn->has_mit_shm = true;
358 free(error);
359 }
360 }
361 }
362
363 free(dri3_reply);
364 free(pres_reply);
365 free(randr_reply);
366 free(xwl_reply);
367 free(amd_reply);
368 free(nv_reply);
369 free(xfixes_reply);
370 if (wants_shm)
371 free(shm_reply);
372
373 return wsi_conn;
374 }
375
376 static void
wsi_x11_connection_destroy(struct wsi_device * wsi_dev,struct wsi_x11_connection * conn)377 wsi_x11_connection_destroy(struct wsi_device *wsi_dev,
378 struct wsi_x11_connection *conn)
379 {
380 vk_free(&wsi_dev->instance_alloc, conn);
381 }
382
383 static bool
wsi_x11_check_for_dri3(struct wsi_x11_connection * wsi_conn)384 wsi_x11_check_for_dri3(struct wsi_x11_connection *wsi_conn)
385 {
386 if (wsi_conn->has_dri3)
387 return true;
388 if (!wsi_conn->is_proprietary_x11) {
389 fprintf(stderr, "vulkan: No DRI3 support detected - required for presentation\n"
390 "Note: you can probably enable DRI3 in your Xorg config\n");
391 }
392 return false;
393 }
394
395 /**
396 * Get internal struct representing an xcb_connection_t.
397 *
398 * This can allocate the struct but the caller does not own the struct. It is
399 * deleted on wsi_x11_finish_wsi by the hash table it is inserted.
400 *
401 * If the allocation fails NULL is returned.
402 */
403 static struct wsi_x11_connection *
wsi_x11_get_connection(struct wsi_device * wsi_dev,xcb_connection_t * conn)404 wsi_x11_get_connection(struct wsi_device *wsi_dev,
405 xcb_connection_t *conn)
406 {
407 struct wsi_x11 *wsi =
408 (struct wsi_x11 *)wsi_dev->wsi[VK_ICD_WSI_PLATFORM_XCB];
409
410 pthread_mutex_lock(&wsi->mutex);
411
412 struct hash_entry *entry = _mesa_hash_table_search(wsi->connections, conn);
413 if (!entry) {
414 /* We're about to make a bunch of blocking calls. Let's drop the
415 * mutex for now so we don't block up too badly.
416 */
417 pthread_mutex_unlock(&wsi->mutex);
418
419 struct wsi_x11_connection *wsi_conn =
420 wsi_x11_connection_create(wsi_dev, conn);
421 if (!wsi_conn)
422 return NULL;
423
424 pthread_mutex_lock(&wsi->mutex);
425
426 entry = _mesa_hash_table_search(wsi->connections, conn);
427 if (entry) {
428 /* Oops, someone raced us to it */
429 wsi_x11_connection_destroy(wsi_dev, wsi_conn);
430 } else {
431 entry = _mesa_hash_table_insert(wsi->connections, conn, wsi_conn);
432 }
433 }
434
435 pthread_mutex_unlock(&wsi->mutex);
436
437 return entry->data;
438 }
439
440 static const VkFormat formats[] = {
441 VK_FORMAT_R5G6B5_UNORM_PACK16,
442 VK_FORMAT_B8G8R8A8_SRGB,
443 VK_FORMAT_B8G8R8A8_UNORM,
444 VK_FORMAT_A2R10G10B10_UNORM_PACK32,
445 };
446
447 static const VkPresentModeKHR present_modes[] = {
448 VK_PRESENT_MODE_IMMEDIATE_KHR,
449 VK_PRESENT_MODE_MAILBOX_KHR,
450 VK_PRESENT_MODE_FIFO_KHR,
451 VK_PRESENT_MODE_FIFO_RELAXED_KHR,
452 };
453
454 static xcb_screen_t *
get_screen_for_root(xcb_connection_t * conn,xcb_window_t root)455 get_screen_for_root(xcb_connection_t *conn, xcb_window_t root)
456 {
457 xcb_screen_iterator_t screen_iter =
458 xcb_setup_roots_iterator(xcb_get_setup(conn));
459
460 for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
461 if (screen_iter.data->root == root)
462 return screen_iter.data;
463 }
464
465 return NULL;
466 }
467
468 static xcb_visualtype_t *
screen_get_visualtype(xcb_screen_t * screen,xcb_visualid_t visual_id,unsigned * depth)469 screen_get_visualtype(xcb_screen_t *screen, xcb_visualid_t visual_id,
470 unsigned *depth)
471 {
472 xcb_depth_iterator_t depth_iter =
473 xcb_screen_allowed_depths_iterator(screen);
474
475 for (; depth_iter.rem; xcb_depth_next (&depth_iter)) {
476 xcb_visualtype_iterator_t visual_iter =
477 xcb_depth_visuals_iterator (depth_iter.data);
478
479 for (; visual_iter.rem; xcb_visualtype_next (&visual_iter)) {
480 if (visual_iter.data->visual_id == visual_id) {
481 if (depth)
482 *depth = depth_iter.data->depth;
483 return visual_iter.data;
484 }
485 }
486 }
487
488 return NULL;
489 }
490
491 static xcb_visualtype_t *
connection_get_visualtype(xcb_connection_t * conn,xcb_visualid_t visual_id)492 connection_get_visualtype(xcb_connection_t *conn, xcb_visualid_t visual_id)
493 {
494 xcb_screen_iterator_t screen_iter =
495 xcb_setup_roots_iterator(xcb_get_setup(conn));
496
497 /* For this we have to iterate over all of the screens which is rather
498 * annoying. Fortunately, there is probably only 1.
499 */
500 for (; screen_iter.rem; xcb_screen_next (&screen_iter)) {
501 xcb_visualtype_t *visual = screen_get_visualtype(screen_iter.data,
502 visual_id, NULL);
503 if (visual)
504 return visual;
505 }
506
507 return NULL;
508 }
509
510 static xcb_visualtype_t *
get_visualtype_for_window(xcb_connection_t * conn,xcb_window_t window,unsigned * depth,xcb_visualtype_t ** rootvis)511 get_visualtype_for_window(xcb_connection_t *conn, xcb_window_t window,
512 unsigned *depth, xcb_visualtype_t **rootvis)
513 {
514 xcb_query_tree_cookie_t tree_cookie;
515 xcb_get_window_attributes_cookie_t attrib_cookie;
516 xcb_query_tree_reply_t *tree;
517 xcb_get_window_attributes_reply_t *attrib;
518
519 tree_cookie = xcb_query_tree(conn, window);
520 attrib_cookie = xcb_get_window_attributes(conn, window);
521
522 tree = xcb_query_tree_reply(conn, tree_cookie, NULL);
523 attrib = xcb_get_window_attributes_reply(conn, attrib_cookie, NULL);
524 if (attrib == NULL || tree == NULL) {
525 free(attrib);
526 free(tree);
527 return NULL;
528 }
529
530 xcb_window_t root = tree->root;
531 xcb_visualid_t visual_id = attrib->visual;
532 free(attrib);
533 free(tree);
534
535 xcb_screen_t *screen = get_screen_for_root(conn, root);
536 if (screen == NULL)
537 return NULL;
538
539 if (rootvis)
540 *rootvis = screen_get_visualtype(screen, screen->root_visual, depth);
541 return screen_get_visualtype(screen, visual_id, depth);
542 }
543
544 static bool
visual_has_alpha(xcb_visualtype_t * visual,unsigned depth)545 visual_has_alpha(xcb_visualtype_t *visual, unsigned depth)
546 {
547 uint32_t rgb_mask = visual->red_mask |
548 visual->green_mask |
549 visual->blue_mask;
550
551 uint32_t all_mask = 0xffffffff >> (32 - depth);
552
553 /* Do we have bits left over after RGB? */
554 return (all_mask & ~rgb_mask) != 0;
555 }
556
557 static bool
visual_supported(xcb_visualtype_t * visual)558 visual_supported(xcb_visualtype_t *visual)
559 {
560 if (!visual)
561 return false;
562
563 return visual->_class == XCB_VISUAL_CLASS_TRUE_COLOR ||
564 visual->_class == XCB_VISUAL_CLASS_DIRECT_COLOR;
565 }
566
567 VKAPI_ATTR VkBool32 VKAPI_CALL
wsi_GetPhysicalDeviceXcbPresentationSupportKHR(VkPhysicalDevice physicalDevice,uint32_t queueFamilyIndex,xcb_connection_t * connection,xcb_visualid_t visual_id)568 wsi_GetPhysicalDeviceXcbPresentationSupportKHR(VkPhysicalDevice physicalDevice,
569 uint32_t queueFamilyIndex,
570 xcb_connection_t *connection,
571 xcb_visualid_t visual_id)
572 {
573 VK_FROM_HANDLE(vk_physical_device, pdevice, physicalDevice);
574 struct wsi_device *wsi_device = pdevice->wsi_device;
575 struct wsi_x11_connection *wsi_conn =
576 wsi_x11_get_connection(wsi_device, connection);
577
578 if (!wsi_conn)
579 return false;
580
581 if (!wsi_device->sw) {
582 if (!wsi_x11_check_for_dri3(wsi_conn))
583 return false;
584 }
585
586 if (!visual_supported(connection_get_visualtype(connection, visual_id)))
587 return false;
588
589 return true;
590 }
591
592 VKAPI_ATTR VkBool32 VKAPI_CALL
wsi_GetPhysicalDeviceXlibPresentationSupportKHR(VkPhysicalDevice physicalDevice,uint32_t queueFamilyIndex,Display * dpy,VisualID visualID)593 wsi_GetPhysicalDeviceXlibPresentationSupportKHR(VkPhysicalDevice physicalDevice,
594 uint32_t queueFamilyIndex,
595 Display *dpy,
596 VisualID visualID)
597 {
598 return wsi_GetPhysicalDeviceXcbPresentationSupportKHR(physicalDevice,
599 queueFamilyIndex,
600 XGetXCBConnection(dpy),
601 visualID);
602 }
603
604 static xcb_connection_t*
x11_surface_get_connection(VkIcdSurfaceBase * icd_surface)605 x11_surface_get_connection(VkIcdSurfaceBase *icd_surface)
606 {
607 if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
608 return XGetXCBConnection(((VkIcdSurfaceXlib *)icd_surface)->dpy);
609 else
610 return ((VkIcdSurfaceXcb *)icd_surface)->connection;
611 }
612
613 static xcb_window_t
x11_surface_get_window(VkIcdSurfaceBase * icd_surface)614 x11_surface_get_window(VkIcdSurfaceBase *icd_surface)
615 {
616 if (icd_surface->platform == VK_ICD_WSI_PLATFORM_XLIB)
617 return ((VkIcdSurfaceXlib *)icd_surface)->window;
618 else
619 return ((VkIcdSurfaceXcb *)icd_surface)->window;
620 }
621
622 static VkResult
x11_surface_get_support(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,uint32_t queueFamilyIndex,VkBool32 * pSupported)623 x11_surface_get_support(VkIcdSurfaceBase *icd_surface,
624 struct wsi_device *wsi_device,
625 uint32_t queueFamilyIndex,
626 VkBool32* pSupported)
627 {
628 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
629 xcb_window_t window = x11_surface_get_window(icd_surface);
630
631 struct wsi_x11_connection *wsi_conn =
632 wsi_x11_get_connection(wsi_device, conn);
633 if (!wsi_conn)
634 return VK_ERROR_OUT_OF_HOST_MEMORY;
635
636 if (!wsi_device->sw) {
637 if (!wsi_x11_check_for_dri3(wsi_conn)) {
638 *pSupported = false;
639 return VK_SUCCESS;
640 }
641 }
642
643 if (!visual_supported(get_visualtype_for_window(conn, window, NULL, NULL))) {
644 *pSupported = false;
645 return VK_SUCCESS;
646 }
647
648 *pSupported = true;
649 return VK_SUCCESS;
650 }
651
652 static uint32_t
x11_get_min_image_count(const struct wsi_device * wsi_device,bool is_xwayland)653 x11_get_min_image_count(const struct wsi_device *wsi_device, bool is_xwayland)
654 {
655 if (wsi_device->x11.override_minImageCount)
656 return wsi_device->x11.override_minImageCount;
657
658 /* For IMMEDIATE and FIFO, most games work in a pipelined manner where the
659 * can produce frames at a rate of 1/MAX(CPU duration, GPU duration), but
660 * the render latency is CPU duration + GPU duration.
661 *
662 * This means that with scanout from pageflipping we need 3 frames to run
663 * full speed:
664 * 1) CPU rendering work
665 * 2) GPU rendering work
666 * 3) scanout
667 *
668 * Once we have a nonblocking acquire that returns a semaphore we can merge
669 * 1 and 3. Hence the ideal implementation needs only 2 images, but games
670 * cannot tellwe currently do not have an ideal implementation and that
671 * hence they need to allocate 3 images. So let us do it for them.
672 *
673 * This is a tradeoff as it uses more memory than needed for non-fullscreen
674 * and non-performance intensive applications.
675 *
676 * For Xwayland Venus reports four images as described in
677 * wsi_wl_surface_get_capabilities
678 */
679 return is_xwayland && wsi_device->x11.extra_xwayland_image ? 4 : 3;
680 }
681
682 static unsigned
683 x11_get_min_image_count_for_present_mode(struct wsi_device *wsi_device,
684 struct wsi_x11_connection *wsi_conn,
685 VkPresentModeKHR present_mode);
686
687 static VkResult
x11_surface_get_capabilities(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,const VkSurfacePresentModeEXT * present_mode,VkSurfaceCapabilitiesKHR * caps)688 x11_surface_get_capabilities(VkIcdSurfaceBase *icd_surface,
689 struct wsi_device *wsi_device,
690 const VkSurfacePresentModeEXT *present_mode,
691 VkSurfaceCapabilitiesKHR *caps)
692 {
693 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
694 xcb_window_t window = x11_surface_get_window(icd_surface);
695 struct wsi_x11_vk_surface *surface = (struct wsi_x11_vk_surface*)icd_surface;
696 struct wsi_x11_connection *wsi_conn =
697 wsi_x11_get_connection(wsi_device, conn);
698 xcb_get_geometry_cookie_t geom_cookie;
699 xcb_generic_error_t *err;
700 xcb_get_geometry_reply_t *geom;
701
702 geom_cookie = xcb_get_geometry(conn, window);
703
704 geom = xcb_get_geometry_reply(conn, geom_cookie, &err);
705 if (!geom)
706 return VK_ERROR_SURFACE_LOST_KHR;
707 {
708 VkExtent2D extent = { geom->width, geom->height };
709 caps->currentExtent = extent;
710 caps->minImageExtent = extent;
711 caps->maxImageExtent = extent;
712 }
713 free(err);
714 free(geom);
715
716 if (surface->has_alpha) {
717 caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
718 VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
719 } else {
720 caps->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR |
721 VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
722 }
723
724 if (present_mode) {
725 caps->minImageCount = x11_get_min_image_count_for_present_mode(wsi_device, wsi_conn, present_mode->presentMode);
726 } else {
727 caps->minImageCount = x11_get_min_image_count(wsi_device, wsi_conn->is_xwayland);
728 }
729
730 /* There is no real maximum */
731 caps->maxImageCount = 0;
732
733 caps->supportedTransforms = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
734 caps->currentTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
735 caps->maxImageArrayLayers = 1;
736 caps->supportedUsageFlags =
737 VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
738 VK_IMAGE_USAGE_SAMPLED_BIT |
739 VK_IMAGE_USAGE_TRANSFER_DST_BIT |
740 VK_IMAGE_USAGE_STORAGE_BIT |
741 VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
742 VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
743
744 VK_FROM_HANDLE(vk_physical_device, pdevice, wsi_device->pdevice);
745 if (pdevice->supported_extensions.EXT_attachment_feedback_loop_layout)
746 caps->supportedUsageFlags |= VK_IMAGE_USAGE_ATTACHMENT_FEEDBACK_LOOP_BIT_EXT;
747
748 return VK_SUCCESS;
749 }
750
751 static VkResult
x11_surface_get_capabilities2(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,const void * info_next,VkSurfaceCapabilities2KHR * caps)752 x11_surface_get_capabilities2(VkIcdSurfaceBase *icd_surface,
753 struct wsi_device *wsi_device,
754 const void *info_next,
755 VkSurfaceCapabilities2KHR *caps)
756 {
757 assert(caps->sType == VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR);
758
759 const VkSurfacePresentModeEXT *present_mode = vk_find_struct_const(info_next, SURFACE_PRESENT_MODE_EXT);
760
761 VkResult result =
762 x11_surface_get_capabilities(icd_surface, wsi_device, present_mode,
763 &caps->surfaceCapabilities);
764
765 if (result != VK_SUCCESS)
766 return result;
767
768 vk_foreach_struct(ext, caps->pNext) {
769 switch (ext->sType) {
770 case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
771 VkSurfaceProtectedCapabilitiesKHR *protected = (void *)ext;
772 protected->supportsProtected = VK_FALSE;
773 break;
774 }
775
776 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
777 /* Unsupported. */
778 VkSurfacePresentScalingCapabilitiesEXT *scaling = (void *)ext;
779 scaling->supportedPresentScaling = 0;
780 scaling->supportedPresentGravityX = 0;
781 scaling->supportedPresentGravityY = 0;
782 scaling->minScaledImageExtent = caps->surfaceCapabilities.minImageExtent;
783 scaling->maxScaledImageExtent = caps->surfaceCapabilities.maxImageExtent;
784 break;
785 }
786
787 case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
788 /* To be able to toggle between FIFO and non-FIFO, we would need a rewrite to always use FIFO thread
789 * mechanism. For now, only return the input, making this effectively unsupported. */
790 VkSurfacePresentModeCompatibilityEXT *compat = (void *)ext;
791 if (compat->pPresentModes) {
792 if (compat->presentModeCount) {
793 assert(present_mode);
794 compat->pPresentModes[0] = present_mode->presentMode;
795 compat->presentModeCount = 1;
796 }
797 } else {
798 if (!present_mode)
799 wsi_common_vk_warn_once("Use of VkSurfacePresentModeCompatibilityEXT "
800 "without a VkSurfacePresentModeEXT set. This is an "
801 "application bug.\n");
802 compat->presentModeCount = 1;
803 }
804 break;
805 }
806
807 default:
808 /* Ignored */
809 break;
810 }
811 }
812
813 return result;
814 }
815
816 static int
format_get_component_bits(VkFormat format,int comp)817 format_get_component_bits(VkFormat format, int comp)
818 {
819 return vk_format_get_component_bits(format, UTIL_FORMAT_COLORSPACE_RGB, comp);
820 }
821
822 static bool
rgb_component_bits_are_equal(VkFormat format,const xcb_visualtype_t * type)823 rgb_component_bits_are_equal(VkFormat format, const xcb_visualtype_t* type)
824 {
825 return format_get_component_bits(format, 0) == util_bitcount(type->red_mask) &&
826 format_get_component_bits(format, 1) == util_bitcount(type->green_mask) &&
827 format_get_component_bits(format, 2) == util_bitcount(type->blue_mask);
828 }
829
830 static bool
get_sorted_vk_formats(VkIcdSurfaceBase * surface,struct wsi_device * wsi_device,VkFormat * sorted_formats,unsigned * count)831 get_sorted_vk_formats(VkIcdSurfaceBase *surface, struct wsi_device *wsi_device,
832 VkFormat *sorted_formats, unsigned *count)
833 {
834 xcb_connection_t *conn = x11_surface_get_connection(surface);
835 xcb_window_t window = x11_surface_get_window(surface);
836 xcb_visualtype_t *rootvis = NULL;
837 xcb_visualtype_t *visual = get_visualtype_for_window(conn, window, NULL, &rootvis);
838
839 if (!visual)
840 return false;
841
842 /* use the root window's visual to set the default */
843 *count = 0;
844 for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
845 if (rgb_component_bits_are_equal(formats[i], rootvis))
846 sorted_formats[(*count)++] = formats[i];
847 }
848
849 for (unsigned i = 0; i < ARRAY_SIZE(formats); i++) {
850 for (unsigned j = 0; j < *count; j++)
851 if (formats[i] == sorted_formats[j])
852 goto next_format;
853 if (rgb_component_bits_are_equal(formats[i], visual))
854 sorted_formats[(*count)++] = formats[i];
855 next_format:;
856 }
857
858 if (wsi_device->force_bgra8_unorm_first) {
859 for (unsigned i = 0; i < *count; i++) {
860 if (sorted_formats[i] == VK_FORMAT_B8G8R8A8_UNORM) {
861 sorted_formats[i] = sorted_formats[0];
862 sorted_formats[0] = VK_FORMAT_B8G8R8A8_UNORM;
863 break;
864 }
865 }
866 }
867
868 return true;
869 }
870
871 static VkResult
x11_surface_get_formats(VkIcdSurfaceBase * surface,struct wsi_device * wsi_device,uint32_t * pSurfaceFormatCount,VkSurfaceFormatKHR * pSurfaceFormats)872 x11_surface_get_formats(VkIcdSurfaceBase *surface,
873 struct wsi_device *wsi_device,
874 uint32_t *pSurfaceFormatCount,
875 VkSurfaceFormatKHR *pSurfaceFormats)
876 {
877 VK_OUTARRAY_MAKE_TYPED(VkSurfaceFormatKHR, out,
878 pSurfaceFormats, pSurfaceFormatCount);
879
880 unsigned count;
881 VkFormat sorted_formats[ARRAY_SIZE(formats)];
882 if (!get_sorted_vk_formats(surface, wsi_device, sorted_formats, &count))
883 return VK_ERROR_SURFACE_LOST_KHR;
884
885 for (unsigned i = 0; i < count; i++) {
886 vk_outarray_append_typed(VkSurfaceFormatKHR, &out, f) {
887 f->format = sorted_formats[i];
888 f->colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
889 }
890 }
891
892 return vk_outarray_status(&out);
893 }
894
895 static VkResult
x11_surface_get_formats2(VkIcdSurfaceBase * surface,struct wsi_device * wsi_device,const void * info_next,uint32_t * pSurfaceFormatCount,VkSurfaceFormat2KHR * pSurfaceFormats)896 x11_surface_get_formats2(VkIcdSurfaceBase *surface,
897 struct wsi_device *wsi_device,
898 const void *info_next,
899 uint32_t *pSurfaceFormatCount,
900 VkSurfaceFormat2KHR *pSurfaceFormats)
901 {
902 VK_OUTARRAY_MAKE_TYPED(VkSurfaceFormat2KHR, out,
903 pSurfaceFormats, pSurfaceFormatCount);
904
905 unsigned count;
906 VkFormat sorted_formats[ARRAY_SIZE(formats)];
907 if (!get_sorted_vk_formats(surface, wsi_device, sorted_formats, &count))
908 return VK_ERROR_SURFACE_LOST_KHR;
909
910 for (unsigned i = 0; i < count; i++) {
911 vk_outarray_append_typed(VkSurfaceFormat2KHR, &out, f) {
912 assert(f->sType == VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR);
913 f->surfaceFormat.format = sorted_formats[i];
914 f->surfaceFormat.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
915 }
916 }
917
918 return vk_outarray_status(&out);
919 }
920
921 static VkResult
x11_surface_get_present_modes(VkIcdSurfaceBase * surface,struct wsi_device * wsi_device,uint32_t * pPresentModeCount,VkPresentModeKHR * pPresentModes)922 x11_surface_get_present_modes(VkIcdSurfaceBase *surface,
923 struct wsi_device *wsi_device,
924 uint32_t *pPresentModeCount,
925 VkPresentModeKHR *pPresentModes)
926 {
927 if (pPresentModes == NULL) {
928 *pPresentModeCount = ARRAY_SIZE(present_modes);
929 return VK_SUCCESS;
930 }
931
932 *pPresentModeCount = MIN2(*pPresentModeCount, ARRAY_SIZE(present_modes));
933 typed_memcpy(pPresentModes, present_modes, *pPresentModeCount);
934
935 return *pPresentModeCount < ARRAY_SIZE(present_modes) ?
936 VK_INCOMPLETE : VK_SUCCESS;
937 }
938
939 static VkResult
x11_surface_get_present_rectangles(VkIcdSurfaceBase * icd_surface,struct wsi_device * wsi_device,uint32_t * pRectCount,VkRect2D * pRects)940 x11_surface_get_present_rectangles(VkIcdSurfaceBase *icd_surface,
941 struct wsi_device *wsi_device,
942 uint32_t* pRectCount,
943 VkRect2D* pRects)
944 {
945 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
946 xcb_window_t window = x11_surface_get_window(icd_surface);
947 VK_OUTARRAY_MAKE_TYPED(VkRect2D, out, pRects, pRectCount);
948
949 vk_outarray_append_typed(VkRect2D, &out, rect) {
950 xcb_generic_error_t *err = NULL;
951 xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(conn, window);
952 xcb_get_geometry_reply_t *geom =
953 xcb_get_geometry_reply(conn, geom_cookie, &err);
954 free(err);
955 if (geom) {
956 *rect = (VkRect2D) {
957 .offset = { 0, 0 },
958 .extent = { geom->width, geom->height },
959 };
960 }
961 free(geom);
962 if (!geom)
963 return VK_ERROR_SURFACE_LOST_KHR;
964 }
965
966 return vk_outarray_status(&out);
967 }
968
969 VKAPI_ATTR VkResult VKAPI_CALL
wsi_CreateXcbSurfaceKHR(VkInstance _instance,const VkXcbSurfaceCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkSurfaceKHR * pSurface)970 wsi_CreateXcbSurfaceKHR(VkInstance _instance,
971 const VkXcbSurfaceCreateInfoKHR *pCreateInfo,
972 const VkAllocationCallbacks *pAllocator,
973 VkSurfaceKHR *pSurface)
974 {
975 VK_FROM_HANDLE(vk_instance, instance, _instance);
976 struct wsi_x11_vk_surface *surface;
977
978 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR);
979
980 unsigned visual_depth;
981 xcb_visualtype_t *visual =
982 get_visualtype_for_window(pCreateInfo->connection, pCreateInfo->window, &visual_depth, NULL);
983 if (!visual)
984 return VK_ERROR_OUT_OF_HOST_MEMORY;
985
986 surface = vk_alloc2(&instance->alloc, pAllocator, sizeof(struct wsi_x11_vk_surface), 8,
987 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
988 if (surface == NULL)
989 return VK_ERROR_OUT_OF_HOST_MEMORY;
990
991 surface->xcb.base.platform = VK_ICD_WSI_PLATFORM_XCB;
992 surface->xcb.connection = pCreateInfo->connection;
993 surface->xcb.window = pCreateInfo->window;
994
995 surface->has_alpha = visual_has_alpha(visual, visual_depth);
996
997 *pSurface = VkIcdSurfaceBase_to_handle(&surface->xcb.base);
998 return VK_SUCCESS;
999 }
1000
1001 VKAPI_ATTR VkResult VKAPI_CALL
wsi_CreateXlibSurfaceKHR(VkInstance _instance,const VkXlibSurfaceCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,VkSurfaceKHR * pSurface)1002 wsi_CreateXlibSurfaceKHR(VkInstance _instance,
1003 const VkXlibSurfaceCreateInfoKHR *pCreateInfo,
1004 const VkAllocationCallbacks *pAllocator,
1005 VkSurfaceKHR *pSurface)
1006 {
1007 VK_FROM_HANDLE(vk_instance, instance, _instance);
1008 struct wsi_x11_vk_surface *surface;
1009
1010 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR);
1011
1012 unsigned visual_depth;
1013 xcb_visualtype_t *visual =
1014 get_visualtype_for_window(XGetXCBConnection(pCreateInfo->dpy), pCreateInfo->window, &visual_depth, NULL);
1015 if (!visual)
1016 return VK_ERROR_OUT_OF_HOST_MEMORY;
1017
1018 surface = vk_alloc2(&instance->alloc, pAllocator, sizeof(struct wsi_x11_vk_surface), 8,
1019 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
1020 if (surface == NULL)
1021 return VK_ERROR_OUT_OF_HOST_MEMORY;
1022
1023 surface->xlib.base.platform = VK_ICD_WSI_PLATFORM_XLIB;
1024 surface->xlib.dpy = pCreateInfo->dpy;
1025 surface->xlib.window = pCreateInfo->window;
1026
1027 surface->has_alpha = visual_has_alpha(visual, visual_depth);
1028
1029 *pSurface = VkIcdSurfaceBase_to_handle(&surface->xlib.base);
1030 return VK_SUCCESS;
1031 }
1032
1033 struct x11_image {
1034 struct wsi_image base;
1035 xcb_pixmap_t pixmap;
1036 xcb_xfixes_region_t update_region; /* long lived XID */
1037 xcb_xfixes_region_t update_area; /* the above or None */
1038 atomic_bool busy;
1039 bool present_queued;
1040 struct xshmfence * shm_fence;
1041 uint32_t sync_fence;
1042 uint32_t serial;
1043 xcb_shm_seg_t shmseg;
1044 int shmid;
1045 uint8_t * shmaddr;
1046 uint64_t present_id;
1047 uint64_t signal_present_id;
1048 };
1049
1050 struct x11_swapchain {
1051 struct wsi_swapchain base;
1052
1053 bool has_dri3_modifiers;
1054 bool has_mit_shm;
1055 bool has_async_may_tear;
1056
1057 xcb_connection_t * conn;
1058 xcb_window_t window;
1059 xcb_gc_t gc;
1060 uint32_t depth;
1061 VkExtent2D extent;
1062
1063 xcb_present_event_t event_id;
1064 xcb_special_event_t * special_event;
1065 uint64_t send_sbc;
1066 uint64_t last_present_msc;
1067 uint32_t stamp;
1068 atomic_int sent_image_count;
1069
1070 bool has_present_queue;
1071 bool has_acquire_queue;
1072 VkResult status;
1073 bool copy_is_suboptimal;
1074 struct wsi_queue present_queue;
1075 struct wsi_queue acquire_queue;
1076 pthread_t queue_manager;
1077
1078 /* Lock and condition variable that lets callers monitor forward progress in the swapchain.
1079 * This includes:
1080 * - Present ID completion updates (present_id).
1081 * - Pending ID pending updates (present_id_pending).
1082 * - Any errors happening while blocking on present progress updates (present_progress_error).
1083 * - present_submitted_count.
1084 */
1085 pthread_mutex_t present_progress_mutex;
1086 pthread_cond_t present_progress_cond;
1087
1088 /* Lock needs to be taken when waiting for and reading presentation events.
1089 * Only relevant in non-FIFO modes where AcquireNextImage or WaitForPresentKHR may
1090 * have to pump the XCB connection on its own. */
1091 pthread_mutex_t present_poll_mutex;
1092
1093 /* For VK_KHR_present_wait. */
1094 uint64_t present_id;
1095 uint64_t present_id_pending;
1096
1097 /* When blocking on present progress, this can be set and progress_cond is signalled to unblock waiters. */
1098 VkResult present_progress_error;
1099
1100 /* For handling wait_ready scenario where two different threads can pump the connection. */
1101
1102 /* Updated by presentation thread. Incremented when a present is submitted to X.
1103 * Signals progress_cond when this happens. */
1104 uint64_t present_submitted_count;
1105 /* Total number of images ever pushed to a present queue. */
1106 uint64_t present_queue_push_count;
1107 /* Total number of images returned to application in AcquireNextImage. */
1108 uint64_t present_poll_acquire_count;
1109
1110 struct x11_image images[0];
1111 };
1112 VK_DEFINE_NONDISP_HANDLE_CASTS(x11_swapchain, base.base, VkSwapchainKHR,
1113 VK_OBJECT_TYPE_SWAPCHAIN_KHR)
1114
x11_present_complete(struct x11_swapchain * swapchain,struct x11_image * image)1115 static void x11_present_complete(struct x11_swapchain *swapchain,
1116 struct x11_image *image)
1117 {
1118 if (image->signal_present_id) {
1119 pthread_mutex_lock(&swapchain->present_progress_mutex);
1120 if (image->signal_present_id > swapchain->present_id) {
1121 swapchain->present_id = image->signal_present_id;
1122 pthread_cond_broadcast(&swapchain->present_progress_cond);
1123 }
1124 pthread_mutex_unlock(&swapchain->present_progress_mutex);
1125 }
1126 }
1127
x11_notify_pending_present(struct x11_swapchain * swapchain,struct x11_image * image)1128 static void x11_notify_pending_present(struct x11_swapchain *swapchain,
1129 struct x11_image *image)
1130 {
1131 if (image->present_id || !swapchain->has_acquire_queue) {
1132 pthread_mutex_lock(&swapchain->present_progress_mutex);
1133 if (image->present_id > swapchain->present_id_pending) {
1134 /* Unblock any thread waiting for a presentID out of order. */
1135 swapchain->present_id_pending = image->present_id;
1136 }
1137
1138 /* If we don't have an acquire queue, we might need to let
1139 * vkAcquireNextImageKHR call know that it is safe to poll for presentation events. */
1140 swapchain->present_submitted_count++;
1141
1142 pthread_cond_broadcast(&swapchain->present_progress_cond);
1143 pthread_mutex_unlock(&swapchain->present_progress_mutex);
1144 }
1145
1146 /* It is possible that an IDLE is observed before PRESENT_COMPLETE when
1147 * not flipping. In this case, reading image->present_id might be a race
1148 * in the FIFO management thread. */
1149 if (image->present_id)
1150 image->signal_present_id = image->present_id;
1151 }
1152
x11_swapchain_notify_error(struct x11_swapchain * swapchain,VkResult result)1153 static void x11_swapchain_notify_error(struct x11_swapchain *swapchain, VkResult result)
1154 {
1155 pthread_mutex_lock(&swapchain->present_progress_mutex);
1156 swapchain->present_id = UINT64_MAX;
1157 swapchain->present_id_pending = UINT64_MAX;
1158 swapchain->present_progress_error = result;
1159 pthread_cond_broadcast(&swapchain->present_progress_cond);
1160 pthread_mutex_unlock(&swapchain->present_progress_mutex);
1161 }
1162
1163 /**
1164 * Update the swapchain status with the result of an operation, and return
1165 * the combined status. The chain status will eventually be returned from
1166 * AcquireNextImage and QueuePresent.
1167 *
1168 * We make sure to 'stick' more pessimistic statuses: an out-of-date error
1169 * is permanent once seen, and every subsequent call will return this. If
1170 * this has not been seen, success will be returned.
1171 */
1172 static VkResult
_x11_swapchain_result(struct x11_swapchain * chain,VkResult result,const char * file,int line)1173 _x11_swapchain_result(struct x11_swapchain *chain, VkResult result,
1174 const char *file, int line)
1175 {
1176 if (result < 0)
1177 x11_swapchain_notify_error(chain, result);
1178
1179 /* Prioritise returning existing errors for consistency. */
1180 if (chain->status < 0)
1181 return chain->status;
1182
1183 /* If we have a new error, mark it as permanent on the chain and return. */
1184 if (result < 0) {
1185 #ifndef NDEBUG
1186 fprintf(stderr, "%s:%d: Swapchain status changed to %s\n",
1187 file, line, vk_Result_to_str(result));
1188 #endif
1189 chain->status = result;
1190 return result;
1191 }
1192
1193 /* Return temporary errors, but don't persist them. */
1194 if (result == VK_TIMEOUT || result == VK_NOT_READY)
1195 return result;
1196
1197 /* Suboptimal isn't an error, but is a status which sticks to the swapchain
1198 * and is always returned rather than success.
1199 */
1200 if (result == VK_SUBOPTIMAL_KHR) {
1201 #ifndef NDEBUG
1202 if (chain->status != VK_SUBOPTIMAL_KHR) {
1203 fprintf(stderr, "%s:%d: Swapchain status changed to %s\n",
1204 file, line, vk_Result_to_str(result));
1205 }
1206 #endif
1207 chain->status = result;
1208 return result;
1209 }
1210
1211 /* No changes, so return the last status. */
1212 return chain->status;
1213 }
1214 #define x11_swapchain_result(chain, result) \
1215 _x11_swapchain_result(chain, result, __FILE__, __LINE__)
1216
1217 static struct wsi_image *
x11_get_wsi_image(struct wsi_swapchain * wsi_chain,uint32_t image_index)1218 x11_get_wsi_image(struct wsi_swapchain *wsi_chain, uint32_t image_index)
1219 {
1220 struct x11_swapchain *chain = (struct x11_swapchain *)wsi_chain;
1221 return &chain->images[image_index].base;
1222 }
1223
1224 /* XXX this belongs in presentproto */
1225 #ifndef PresentWindowDestroyed
1226 #define PresentWindowDestroyed (1 << 0)
1227 #endif
1228 /**
1229 * Process an X11 Present event. Does not update chain->status.
1230 */
1231 static VkResult
x11_handle_dri3_present_event(struct x11_swapchain * chain,xcb_present_generic_event_t * event)1232 x11_handle_dri3_present_event(struct x11_swapchain *chain,
1233 xcb_present_generic_event_t *event)
1234 {
1235 switch (event->evtype) {
1236 case XCB_PRESENT_CONFIGURE_NOTIFY: {
1237 xcb_present_configure_notify_event_t *config = (void *) event;
1238 if (config->pixmap_flags & PresentWindowDestroyed)
1239 return VK_ERROR_SURFACE_LOST_KHR;
1240
1241 if (config->width != chain->extent.width ||
1242 config->height != chain->extent.height)
1243 return VK_SUBOPTIMAL_KHR;
1244
1245 break;
1246 }
1247
1248 case XCB_PRESENT_EVENT_IDLE_NOTIFY: {
1249 xcb_present_idle_notify_event_t *idle = (void *) event;
1250
1251 for (unsigned i = 0; i < chain->base.image_count; i++) {
1252 if (chain->images[i].pixmap == idle->pixmap) {
1253 chain->images[i].busy = false;
1254 chain->sent_image_count--;
1255 assert(chain->sent_image_count >= 0);
1256 if (chain->has_acquire_queue)
1257 wsi_queue_push(&chain->acquire_queue, i);
1258 break;
1259 }
1260 }
1261
1262 break;
1263 }
1264
1265 case XCB_PRESENT_EVENT_COMPLETE_NOTIFY: {
1266 xcb_present_complete_notify_event_t *complete = (void *) event;
1267 if (complete->kind == XCB_PRESENT_COMPLETE_KIND_PIXMAP) {
1268 unsigned i;
1269 for (i = 0; i < chain->base.image_count; i++) {
1270 struct x11_image *image = &chain->images[i];
1271 if (image->present_queued && image->serial == complete->serial) {
1272 x11_present_complete(chain, &chain->images[i]);
1273 image->present_queued = false;
1274 }
1275 }
1276 chain->last_present_msc = complete->msc;
1277 }
1278
1279 VkResult result = VK_SUCCESS;
1280 switch (complete->mode) {
1281 case XCB_PRESENT_COMPLETE_MODE_COPY:
1282 if (chain->copy_is_suboptimal)
1283 result = VK_SUBOPTIMAL_KHR;
1284 break;
1285 case XCB_PRESENT_COMPLETE_MODE_FLIP:
1286 /* If we ever go from flipping to copying, the odds are very likely
1287 * that we could reallocate in a more optimal way if we didn't have
1288 * to care about scanout, so we always do this.
1289 */
1290 chain->copy_is_suboptimal = true;
1291 break;
1292 #ifdef HAVE_DRI3_MODIFIERS
1293 case XCB_PRESENT_COMPLETE_MODE_SUBOPTIMAL_COPY:
1294 /* The winsys is now trying to flip directly and cannot due to our
1295 * configuration. Request the user reallocate.
1296 */
1297 result = VK_SUBOPTIMAL_KHR;
1298 break;
1299 #endif
1300 default:
1301 break;
1302 }
1303
1304 return result;
1305 }
1306
1307 default:
1308 break;
1309 }
1310
1311 return VK_SUCCESS;
1312 }
1313
1314 static VkResult
x11_poll_for_special_event(struct x11_swapchain * chain,uint64_t abs_timeout,xcb_generic_event_t ** out_event)1315 x11_poll_for_special_event(struct x11_swapchain *chain, uint64_t abs_timeout, xcb_generic_event_t **out_event)
1316 {
1317 /* Start out with 1 ms intervals since that's what poll() supports. */
1318 uint64_t poll_busywait_ns = 1000 * 1000;
1319 xcb_generic_event_t *event;
1320 uint64_t rel_timeout;
1321 struct pollfd pfds;
1322
1323 assert(abs_timeout != UINT64_MAX);
1324
1325 /* abs_timeout is assumed to be in timebase of os_time_get_absolute_timeout(). */
1326
1327 /* See comments in x11_manage_fifo_queues about problems with xcb_poll followed by poll().
1328 * This path is suboptimal for scenarios where we're doing:
1329 * - IMMEDIATE / MAILBOX (no acquire queue) and
1330 * - Timeout that is neither 0 nor UINT64_MAX (very rare).
1331 * The only real solution is a busy-poll scheme to ensure we don't sleep for too long.
1332 * In a forward progress scenario, the XCB FD will be written at least once per frame,
1333 * so we expect frequent wake-ups either way.
1334 * This is a best-effort pragmatic solution until we have a proper solution in XCB.
1335 */
1336
1337 rel_timeout = abs_timeout;
1338 *out_event = NULL;
1339 event = NULL;
1340
1341 while (1) {
1342 event = xcb_poll_for_special_event(chain->conn, chain->special_event);
1343
1344 if (event || rel_timeout == 0)
1345 break;
1346
1347 /* If a non-special event happens, the fd will still
1348 * poll. So recalculate the timeout now just in case.
1349 */
1350 uint64_t current_time = os_time_get_nano();
1351 if (abs_timeout > current_time)
1352 rel_timeout = MIN2(poll_busywait_ns, abs_timeout - current_time);
1353 else
1354 rel_timeout = 0;
1355
1356 if (rel_timeout) {
1357 pfds.fd = xcb_get_file_descriptor(chain->conn);
1358 pfds.events = POLLIN;
1359 int ret = poll(&pfds, 1, MAX2(rel_timeout / 1000 / 1000, 1u));
1360 if (ret == -1)
1361 return VK_ERROR_OUT_OF_DATE_KHR;
1362
1363 /* Gradually increase the poll duration if it takes a very long time to receive a poll event,
1364 * since at that point, stutter isn't really the main concern anymore.
1365 * We generally expect a special event to be received once every refresh duration. */
1366 poll_busywait_ns += poll_busywait_ns / 2;
1367 poll_busywait_ns = MIN2(10ull * 1000ull * 1000ull, poll_busywait_ns);
1368 }
1369 }
1370
1371 *out_event = event;
1372 return event ? VK_SUCCESS : VK_TIMEOUT;
1373 }
1374
1375 static bool
x11_acquire_next_image_poll_has_forward_progress(struct x11_swapchain * chain)1376 x11_acquire_next_image_poll_has_forward_progress(struct x11_swapchain *chain)
1377 {
1378 /* We have forward progress in the sense that we just error out. */
1379 if (chain->present_progress_error != VK_SUCCESS)
1380 return true;
1381
1382 /* If we got here, there are no available images.
1383 * Some images might be acquired, but not submitted.
1384 * Some images might be submitted to FIFO thread, but not submitted to X yet. */
1385
1386 /* If application holds on to images without presenting, it affects forward progress.
1387 * If application holds on to too many images, forward progress may be impossible.
1388 * Application is allowed to call acquire with timeout in these scenarios, but not UINT64_MAX, since it may deadlock. */
1389 assert(chain->present_poll_acquire_count >= chain->present_queue_push_count);
1390 unsigned application_owned_images = chain->present_poll_acquire_count - chain->present_queue_push_count;
1391 assert(application_owned_images <= chain->base.image_count);
1392
1393 const unsigned minimum_images = 2;
1394
1395 /* To observe an IDLE event, we must have submitted at least 2 present requests to X.
1396 * The first present may replace another swapchain's image, but it cannot IDLE one of our own.
1397 * Refuse forward progress until we have observed two completed present requests.
1398 * If we are in a steady state, we only need one present to be able to idle the current image.
1399 * In a blit style composition (windowed mode), images may be idled immediately, so this requirement is relaxed,
1400 * but we have to assume the worst case of FLIP model where the front buffer holds on to one of the swapchain images. */
1401 if (chain->present_submitted_count < minimum_images)
1402 return false;
1403
1404 /* Since there are no available images, all images not owned by application have been pushed to FIFO thread.
1405 * There must be at least 2 presents queued up. */
1406 unsigned present_queued_images = chain->base.image_count - application_owned_images;
1407 if (present_queued_images < minimum_images)
1408 return false;
1409
1410 /* Present queue must have caught up. */
1411 return (chain->present_queue_push_count - chain->present_submitted_count) <=
1412 (present_queued_images - minimum_images);
1413 }
1414
1415 static VkResult
x11_acquire_next_image_poll_find_index(struct x11_swapchain * chain,uint32_t * image_index)1416 x11_acquire_next_image_poll_find_index(struct x11_swapchain *chain, uint32_t *image_index)
1417 {
1418 /* We don't need a lock here. AcquireNextImageKHR cannot be called concurrently,
1419 * and busy flag is atomic. */
1420 for (uint32_t i = 0; i < chain->base.image_count; i++) {
1421 if (!chain->images[i].busy) {
1422 /* We found a non-busy image */
1423 xshmfence_await(chain->images[i].shm_fence);
1424 *image_index = i;
1425 chain->images[i].busy = true;
1426 chain->present_poll_acquire_count++;
1427 return x11_swapchain_result(chain, VK_SUCCESS);
1428 }
1429 }
1430
1431 return x11_swapchain_result(chain, VK_NOT_READY);
1432 }
1433
1434 /**
1435 * Acquire a ready-to-use image directly from our swapchain. If all images are
1436 * busy wait until one is not anymore or till timeout.
1437 */
1438 static VkResult
x11_acquire_next_image_poll_x11(struct x11_swapchain * chain,uint32_t * image_index,uint64_t timeout)1439 x11_acquire_next_image_poll_x11(struct x11_swapchain *chain,
1440 uint32_t *image_index, uint64_t timeout)
1441 {
1442 struct timespec rel_timeout, abs_timespec_realtime, start_time;
1443 xcb_generic_event_t *event;
1444 VkResult result;
1445
1446 /* If another thread is pumping the event queue, and we're polling with timeout == 0,
1447 * try a quick poll before we try to take any locks. */
1448 result = x11_acquire_next_image_poll_find_index(chain, image_index);
1449 if (result != VK_NOT_READY)
1450 return result;
1451
1452 uint64_t atimeout;
1453 if (timeout == 0 || timeout == UINT64_MAX)
1454 atimeout = timeout;
1455 else
1456 atimeout = os_time_get_absolute_timeout(timeout);
1457
1458 /* Mutex abs_timeout is in REALTIME timebase. */
1459 timespec_from_nsec(&rel_timeout, timeout);
1460 clock_gettime(CLOCK_REALTIME, &start_time);
1461 timespec_add(&abs_timespec_realtime, &rel_timeout, &start_time);
1462
1463 if (chain->has_present_queue) {
1464 /* If we have a present queue (but no acquire queue),
1465 * we might need the present queue to complete
1466 * a request before we can guarantee forward progress in the poll loop below.
1467 * We take the poll_mutex, but so does the present queue. */
1468 pthread_mutex_lock(&chain->present_progress_mutex);
1469
1470 /* There must be at least one present in-flight that has been committed to X,
1471 * otherwise we can never satisfy the acquire operation if all images are busy,
1472 * since we would be waiting on an event that will never happen. */
1473 struct timespec abs_timespec;
1474 timespec_from_nsec(&abs_timespec, atimeout);
1475 result = VK_SUCCESS;
1476
1477 while (!x11_acquire_next_image_poll_has_forward_progress(chain)) {
1478 int ret = pthread_cond_timedwait(&chain->present_progress_cond, &chain->present_progress_mutex, &abs_timespec);
1479
1480 if (ret == ETIMEDOUT) {
1481 result = x11_swapchain_result(chain, timeout == 0 ? VK_NOT_READY : VK_TIMEOUT);
1482 break;
1483 }
1484
1485 if (ret) {
1486 result = VK_ERROR_DEVICE_LOST;
1487 break;
1488 }
1489 }
1490
1491 if (result == VK_SUCCESS && chain->present_progress_error != VK_SUCCESS)
1492 result = chain->present_progress_error;
1493
1494 pthread_mutex_unlock(&chain->present_progress_mutex);
1495
1496 if (result != VK_SUCCESS)
1497 return result;
1498 }
1499
1500 int ret;
1501 if (timeout == UINT64_MAX)
1502 ret = pthread_mutex_lock(&chain->present_poll_mutex);
1503 else
1504 ret = pthread_mutex_timedlock(&chain->present_poll_mutex, &abs_timespec_realtime);
1505
1506 if (ret) {
1507 if (ret == ETIMEDOUT)
1508 return timeout == 0 ? VK_NOT_READY : VK_TIMEOUT;
1509 else
1510 return VK_ERROR_DEVICE_LOST;
1511 }
1512
1513 while (1) {
1514 result = x11_acquire_next_image_poll_find_index(chain, image_index);
1515 if (result != VK_NOT_READY)
1516 goto out_unlock;
1517
1518 xcb_flush(chain->conn);
1519
1520 if (timeout == UINT64_MAX) {
1521 /* See comments in x11_manage_fifo_queues about problem scenarios with this call. */
1522 event = xcb_wait_for_special_event(chain->conn, chain->special_event);
1523 if (!event) {
1524 result = x11_swapchain_result(chain, VK_ERROR_SURFACE_LOST_KHR);
1525 goto out_unlock;
1526 }
1527 } else {
1528 result = x11_poll_for_special_event(chain, atimeout, &event);
1529 if (result == VK_TIMEOUT) {
1530 /* AcquireNextImageKHR reserves a special return value for 0 timeouts. */
1531 result = x11_swapchain_result(chain, timeout == 0 ? VK_NOT_READY : VK_TIMEOUT);
1532 goto out_unlock;
1533 } else if (result != VK_SUCCESS) {
1534 result = x11_swapchain_result(chain, result);
1535 goto out_unlock;
1536 }
1537 }
1538
1539 /* Update the swapchain status here. We may catch non-fatal errors here,
1540 * in which case we need to update the status and continue.
1541 */
1542 result = x11_handle_dri3_present_event(chain, (void *)event);
1543 /* Ensure that VK_SUBOPTIMAL_KHR is reported to the application */
1544 result = x11_swapchain_result(chain, result);
1545 free(event);
1546 if (result < 0)
1547 goto out_unlock;
1548 }
1549
1550 out_unlock:
1551 pthread_mutex_unlock(&chain->present_poll_mutex);
1552 return result;
1553 }
1554
1555 /**
1556 * Acquire a ready-to-use image from the acquire-queue. Only relevant in fifo
1557 * presentation mode.
1558 */
1559 static VkResult
x11_acquire_next_image_from_queue(struct x11_swapchain * chain,uint32_t * image_index_out,uint64_t timeout)1560 x11_acquire_next_image_from_queue(struct x11_swapchain *chain,
1561 uint32_t *image_index_out, uint64_t timeout)
1562 {
1563 assert(chain->has_acquire_queue);
1564
1565 uint32_t image_index;
1566 VkResult result = wsi_queue_pull(&chain->acquire_queue,
1567 &image_index, timeout);
1568 if (result < 0 || result == VK_TIMEOUT) {
1569 /* On error, the thread has shut down, so safe to update chain->status.
1570 * Calling x11_swapchain_result with VK_TIMEOUT won't modify
1571 * chain->status so that is also safe.
1572 */
1573 return x11_swapchain_result(chain, result);
1574 } else if (chain->status < 0) {
1575 return chain->status;
1576 }
1577
1578 assert(image_index < chain->base.image_count);
1579 xshmfence_await(chain->images[image_index].shm_fence);
1580
1581 *image_index_out = image_index;
1582
1583 return chain->status;
1584 }
1585
1586 /**
1587 * Send image to X server via Present extension.
1588 */
1589 static VkResult
x11_present_to_x11_dri3(struct x11_swapchain * chain,uint32_t image_index,uint64_t target_msc)1590 x11_present_to_x11_dri3(struct x11_swapchain *chain, uint32_t image_index,
1591 uint64_t target_msc)
1592 {
1593 struct x11_image *image = &chain->images[image_index];
1594
1595 assert(image_index < chain->base.image_count);
1596
1597 uint32_t options = XCB_PRESENT_OPTION_NONE;
1598
1599 int64_t divisor = 0;
1600 int64_t remainder = 0;
1601
1602 struct wsi_x11_connection *wsi_conn =
1603 wsi_x11_get_connection((struct wsi_device*)chain->base.wsi, chain->conn);
1604 if (!wsi_conn)
1605 return VK_ERROR_OUT_OF_HOST_MEMORY;
1606
1607 if (chain->base.present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR ||
1608 (chain->base.present_mode == VK_PRESENT_MODE_MAILBOX_KHR &&
1609 wsi_conn->is_xwayland) ||
1610 chain->base.present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR)
1611 options |= XCB_PRESENT_OPTION_ASYNC;
1612
1613 if (chain->base.present_mode == VK_PRESENT_MODE_IMMEDIATE_KHR
1614 && chain->has_async_may_tear)
1615 options |= XCB_PRESENT_OPTION_ASYNC_MAY_TEAR;
1616
1617 #ifdef HAVE_DRI3_MODIFIERS
1618 if (chain->has_dri3_modifiers)
1619 options |= XCB_PRESENT_OPTION_SUBOPTIMAL;
1620 #endif
1621
1622 xshmfence_reset(image->shm_fence);
1623
1624 ++chain->sent_image_count;
1625 assert(chain->sent_image_count <= chain->base.image_count);
1626
1627 ++chain->send_sbc;
1628 image->present_queued = true;
1629 image->serial = (uint32_t) chain->send_sbc;
1630
1631 xcb_present_pixmap(chain->conn,
1632 chain->window,
1633 image->pixmap,
1634 image->serial,
1635 0, /* valid */
1636 image->update_area, /* update */
1637 0, /* x_off */
1638 0, /* y_off */
1639 XCB_NONE, /* target_crtc */
1640 XCB_NONE,
1641 image->sync_fence,
1642 options,
1643 target_msc,
1644 divisor,
1645 remainder, 0, NULL);
1646 xcb_flush(chain->conn);
1647 return x11_swapchain_result(chain, VK_SUCCESS);
1648 }
1649
1650 /**
1651 * Send image to X server unaccelerated (software drivers).
1652 */
1653 static VkResult
x11_present_to_x11_sw(struct x11_swapchain * chain,uint32_t image_index,uint64_t target_msc)1654 x11_present_to_x11_sw(struct x11_swapchain *chain, uint32_t image_index,
1655 uint64_t target_msc)
1656 {
1657 struct x11_image *image = &chain->images[image_index];
1658
1659 xcb_void_cookie_t cookie;
1660 void *myptr = image->base.cpu_map;
1661 size_t hdr_len = sizeof(xcb_put_image_request_t);
1662 int stride_b = image->base.row_pitches[0];
1663 size_t size = (hdr_len + stride_b * chain->extent.height) >> 2;
1664 uint64_t max_req_len = xcb_get_maximum_request_length(chain->conn);
1665
1666 if (size < max_req_len) {
1667 cookie = xcb_put_image(chain->conn, XCB_IMAGE_FORMAT_Z_PIXMAP,
1668 chain->window,
1669 chain->gc,
1670 image->base.row_pitches[0] / 4,
1671 chain->extent.height,
1672 0,0,0,24,
1673 image->base.row_pitches[0] * chain->extent.height,
1674 image->base.cpu_map);
1675 xcb_discard_reply(chain->conn, cookie.sequence);
1676 } else {
1677 int num_lines = ((max_req_len << 2) - hdr_len) / stride_b;
1678 int y_start = 0;
1679 int y_todo = chain->extent.height;
1680 while (y_todo) {
1681 int this_lines = MIN2(num_lines, y_todo);
1682 cookie = xcb_put_image(chain->conn, XCB_IMAGE_FORMAT_Z_PIXMAP,
1683 chain->window,
1684 chain->gc,
1685 image->base.row_pitches[0] / 4,
1686 this_lines,
1687 0,y_start,0,24,
1688 this_lines * stride_b,
1689 (const uint8_t *)myptr + (y_start * stride_b));
1690 xcb_discard_reply(chain->conn, cookie.sequence);
1691 y_start += this_lines;
1692 y_todo -= this_lines;
1693 }
1694 }
1695
1696 chain->images[image_index].busy = false;
1697 xcb_flush(chain->conn);
1698 return x11_swapchain_result(chain, VK_SUCCESS);
1699 }
1700
1701 static void
x11_capture_trace(struct x11_swapchain * chain)1702 x11_capture_trace(struct x11_swapchain *chain)
1703 {
1704 #ifdef XCB_KEYSYMS_AVAILABLE
1705 VK_FROM_HANDLE(vk_device, device, chain->base.device);
1706 if (!device->physical->instance->trace_mode)
1707 return;
1708
1709 xcb_query_keymap_cookie_t keys_cookie = xcb_query_keymap(chain->conn);
1710
1711 xcb_generic_error_t *error = NULL;
1712 xcb_query_keymap_reply_t *keys = xcb_query_keymap_reply(chain->conn, keys_cookie, &error);
1713 if (error) {
1714 free(error);
1715 return;
1716 }
1717
1718 xcb_key_symbols_t *key_symbols = xcb_key_symbols_alloc(chain->conn);
1719 xcb_keycode_t *keycodes = xcb_key_symbols_get_keycode(key_symbols, XK_F1);
1720 if (keycodes) {
1721 xcb_keycode_t keycode = keycodes[0];
1722 free(keycodes);
1723
1724 simple_mtx_lock(&device->trace_mtx);
1725 bool capture_key_pressed = keys->keys[keycode / 8] & (1u << (keycode % 8));
1726 device->trace_hotkey_trigger = capture_key_pressed && (capture_key_pressed != chain->base.capture_key_pressed);
1727 chain->base.capture_key_pressed = capture_key_pressed;
1728 simple_mtx_unlock(&device->trace_mtx);
1729 }
1730
1731 xcb_key_symbols_free(key_symbols);
1732 free(keys);
1733 #endif
1734 }
1735
1736 /**
1737 * Send image to the X server for presentation at target_msc.
1738 */
1739 static VkResult
x11_present_to_x11(struct x11_swapchain * chain,uint32_t image_index,uint64_t target_msc)1740 x11_present_to_x11(struct x11_swapchain *chain, uint32_t image_index,
1741 uint64_t target_msc)
1742 {
1743 x11_capture_trace(chain);
1744
1745 VkResult result;
1746 if (chain->base.wsi->sw && !chain->has_mit_shm)
1747 result = x11_present_to_x11_sw(chain, image_index, target_msc);
1748 else
1749 result = x11_present_to_x11_dri3(chain, image_index, target_msc);
1750
1751 if (result < 0)
1752 x11_swapchain_notify_error(chain, result);
1753 else
1754 x11_notify_pending_present(chain, &chain->images[image_index]);
1755
1756 return result;
1757 }
1758
1759 static VkResult
x11_release_images(struct wsi_swapchain * wsi_chain,uint32_t count,const uint32_t * indices)1760 x11_release_images(struct wsi_swapchain *wsi_chain,
1761 uint32_t count, const uint32_t *indices)
1762 {
1763 struct x11_swapchain *chain = (struct x11_swapchain *)wsi_chain;
1764 if (chain->status == VK_ERROR_SURFACE_LOST_KHR)
1765 return chain->status;
1766
1767 for (uint32_t i = 0; i < count; i++) {
1768 uint32_t index = indices[i];
1769 assert(index < chain->base.image_count);
1770
1771 if (chain->has_acquire_queue) {
1772 wsi_queue_push(&chain->acquire_queue, index);
1773 } else {
1774 assert(chain->images[index].busy);
1775 chain->images[index].busy = false;
1776 }
1777 }
1778
1779 if (!chain->has_acquire_queue) {
1780 assert(chain->present_poll_acquire_count >= count);
1781 chain->present_poll_acquire_count -= count;
1782 }
1783
1784 return VK_SUCCESS;
1785 }
1786
1787 /**
1788 * Acquire a ready-to-use image from the swapchain.
1789 *
1790 * This means usually that the image is not waiting on presentation and that the
1791 * image has been released by the X server to be used again by the consumer.
1792 */
1793 static VkResult
x11_acquire_next_image(struct wsi_swapchain * anv_chain,const VkAcquireNextImageInfoKHR * info,uint32_t * image_index)1794 x11_acquire_next_image(struct wsi_swapchain *anv_chain,
1795 const VkAcquireNextImageInfoKHR *info,
1796 uint32_t *image_index)
1797 {
1798 struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1799 uint64_t timeout = info->timeout;
1800
1801 /* If the swapchain is in an error state, don't go any further. */
1802 if (chain->status < 0)
1803 return chain->status;
1804
1805 if (chain->base.wsi->sw && !chain->has_mit_shm) {
1806 for (unsigned i = 0; i < chain->base.image_count; i++) {
1807 if (!chain->images[i].busy) {
1808 *image_index = i;
1809 chain->images[i].busy = true;
1810 chain->present_poll_acquire_count++;
1811 xcb_generic_error_t *err;
1812
1813 xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(chain->conn, chain->window);
1814 xcb_get_geometry_reply_t *geom = xcb_get_geometry_reply(chain->conn, geom_cookie, &err);
1815 VkResult result = VK_SUCCESS;
1816 if (geom) {
1817 if (chain->extent.width != geom->width ||
1818 chain->extent.height != geom->height)
1819 result = VK_SUBOPTIMAL_KHR;
1820 } else {
1821 result = VK_ERROR_SURFACE_LOST_KHR;
1822 }
1823 free(err);
1824 free(geom);
1825 return result;
1826 }
1827 }
1828 return VK_NOT_READY;
1829 }
1830
1831 if (chain->has_acquire_queue) {
1832 return x11_acquire_next_image_from_queue(chain, image_index, timeout);
1833 } else {
1834 return x11_acquire_next_image_poll_x11(chain, image_index, timeout);
1835 }
1836 }
1837
1838 #define MAX_DAMAGE_RECTS 64
1839
1840 /**
1841 * Queue a new presentation of an image that was previously acquired by the
1842 * consumer.
1843 *
1844 * Note that in immediate presentation mode this does not really queue the
1845 * presentation but directly asks the X server to show it.
1846 */
1847 static VkResult
x11_queue_present(struct wsi_swapchain * anv_chain,uint32_t image_index,uint64_t present_id,const VkPresentRegionKHR * damage)1848 x11_queue_present(struct wsi_swapchain *anv_chain,
1849 uint32_t image_index,
1850 uint64_t present_id,
1851 const VkPresentRegionKHR *damage)
1852 {
1853 struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
1854 xcb_xfixes_region_t update_area = 0;
1855
1856 /* If the swapchain is in an error state, don't go any further. */
1857 if (chain->status < 0)
1858 return chain->status;
1859
1860 if (damage && damage->pRectangles && damage->rectangleCount > 0 &&
1861 damage->rectangleCount <= MAX_DAMAGE_RECTS) {
1862 xcb_rectangle_t rects[MAX_DAMAGE_RECTS];
1863
1864 update_area = chain->images[image_index].update_region;
1865 for (unsigned i = 0; i < damage->rectangleCount; i++) {
1866 const VkRectLayerKHR *rect = &damage->pRectangles[i];
1867 assert(rect->layer == 0);
1868 rects[i].x = rect->offset.x;
1869 rects[i].y = rect->offset.y;
1870 rects[i].width = rect->extent.width;
1871 rects[i].height = rect->extent.height;
1872 }
1873 xcb_xfixes_set_region(chain->conn, update_area, damage->rectangleCount, rects);
1874 }
1875 chain->images[image_index].update_area = update_area;
1876 chain->images[image_index].present_id = present_id;
1877
1878 chain->images[image_index].busy = true;
1879 if (chain->has_present_queue) {
1880 wsi_queue_push(&chain->present_queue, image_index);
1881 chain->present_queue_push_count++;
1882 return chain->status;
1883 } else {
1884 /* No present queue means immedate mode, so we present immediately. */
1885 pthread_mutex_lock(&chain->present_poll_mutex);
1886 VkResult result = x11_present_to_x11(chain, image_index, 0);
1887 pthread_mutex_unlock(&chain->present_poll_mutex);
1888 return result;
1889 }
1890 }
1891
1892 /**
1893 * Decides if an early wait on buffer fences before buffer submission is required. That is for:
1894 * - Mailbox mode, as otherwise the latest image in the queue might not be fully rendered at
1895 * present time, what could lead to missing a frame.
1896 * - Immediate mode under Xwayland, as it works practically the same as mailbox mode using the
1897 * mailbox mechanism of Wayland. Sending a buffer with fences not yet signalled can make the
1898 * compositor miss a frame when compositing the final image with this buffer.
1899 *
1900 * Note though that early waits can be disabled in general on Xwayland by setting the
1901 * 'vk_xwayland_wait_ready' DRIConf option to false.
1902 */
1903 static bool
x11_needs_wait_for_fences(const struct wsi_device * wsi_device,struct wsi_x11_connection * wsi_conn,VkPresentModeKHR present_mode)1904 x11_needs_wait_for_fences(const struct wsi_device *wsi_device,
1905 struct wsi_x11_connection *wsi_conn,
1906 VkPresentModeKHR present_mode)
1907 {
1908 if (wsi_conn->is_xwayland && !wsi_device->x11.xwaylandWaitReady) {
1909 return false;
1910 }
1911
1912 switch (present_mode) {
1913 case VK_PRESENT_MODE_MAILBOX_KHR:
1914 return true;
1915 case VK_PRESENT_MODE_IMMEDIATE_KHR:
1916 return wsi_conn->is_xwayland;
1917 default:
1918 return false;
1919 }
1920 }
1921
1922 /**
1923 * The number of images that are not owned by X11:
1924 * (1) in the ownership of the app, or
1925 * (2) app to take ownership through an acquire, or
1926 * (3) in the present queue waiting for the FIFO thread to present to X11.
1927 */
x11_driver_owned_images(const struct x11_swapchain * chain)1928 static unsigned x11_driver_owned_images(const struct x11_swapchain *chain)
1929 {
1930 return chain->base.image_count - chain->sent_image_count;
1931 }
1932
1933 /**
1934 * Our queue manager. Albeit called x11_manage_fifo_queues only directly
1935 * manages the present-queue and does this in general in fifo and mailbox presentation
1936 * modes (there is no present-queue in immediate mode with the exception of Xwayland).
1937 *
1938 * Runs in a separate thread, blocks and reacts to queued images on the
1939 * present-queue
1940 *
1941 * In mailbox mode the queue management is simplified since we only need to
1942 * pull new images from the present queue and can directly present them.
1943 *
1944 * In fifo mode images can only be presented one after the other. For that after
1945 * sending the image to the X server we wait until the image either has been
1946 * presented or released and only then pull a new image from the present-queue.
1947 */
1948 static void *
x11_manage_fifo_queues(void * state)1949 x11_manage_fifo_queues(void *state)
1950 {
1951 struct x11_swapchain *chain = state;
1952 struct wsi_x11_connection *wsi_conn =
1953 wsi_x11_get_connection((struct wsi_device*)chain->base.wsi, chain->conn);
1954 VkResult result = VK_SUCCESS;
1955
1956 assert(chain->has_present_queue);
1957
1958 u_thread_setname("WSI swapchain queue");
1959
1960 while (chain->status >= 0) {
1961 /* We can block here unconditionally because after an image was sent to
1962 * the server (later on in this loop) we ensure at least one image is
1963 * acquirable by the consumer or wait there on such an event.
1964 */
1965 uint32_t image_index = 0;
1966 {
1967 MESA_TRACE_SCOPE("pull present queue");
1968 result = wsi_queue_pull(&chain->present_queue, &image_index, INT64_MAX);
1969 assert(result != VK_TIMEOUT);
1970 }
1971
1972 if (result < 0) {
1973 goto fail;
1974 } else if (chain->status < 0) {
1975 /* The status can change underneath us if the swapchain is destroyed
1976 * from another thread.
1977 */
1978 return NULL;
1979 }
1980
1981 /* Waiting for the GPU work to finish at this point in time is required in certain usage
1982 * scenarios. Otherwise we wait as usual in wsi_common_queue_present.
1983 */
1984 if (x11_needs_wait_for_fences(chain->base.wsi, wsi_conn,
1985 chain->base.present_mode)) {
1986 MESA_TRACE_SCOPE("wait fence");
1987 result = chain->base.wsi->WaitForFences(chain->base.device, 1,
1988 &chain->base.fences[image_index],
1989 true, UINT64_MAX);
1990 if (result != VK_SUCCESS) {
1991 result = VK_ERROR_OUT_OF_DATE_KHR;
1992 goto fail;
1993 }
1994 }
1995
1996 uint64_t target_msc = 0;
1997 if (chain->has_acquire_queue)
1998 target_msc = chain->last_present_msc + 1;
1999
2000 /* Locking here is only relevant if we don't have an acquire queue.
2001 * WaitForPresentKHR will pump the message queue on its own unless
2002 * has_acquire_queue and has_present_queue are both true. */
2003 if (!chain->has_acquire_queue)
2004 pthread_mutex_lock(&chain->present_poll_mutex);
2005 result = x11_present_to_x11(chain, image_index, target_msc);
2006 if (!chain->has_acquire_queue)
2007 pthread_mutex_unlock(&chain->present_poll_mutex);
2008
2009 if (result < 0)
2010 goto fail;
2011
2012 if (chain->has_acquire_queue) {
2013 MESA_TRACE_SCOPE("wait present");
2014
2015 /* Assume this isn't a swapchain where we force 5 images, because those
2016 * don't end up with an acquire queue at the moment.
2017 */
2018 unsigned min_image_count = x11_get_min_image_count(chain->base.wsi, wsi_conn->is_xwayland);
2019
2020 /* With drirc overrides some games have swapchain with less than
2021 * minimum number of images. */
2022 min_image_count = MIN2(min_image_count, chain->base.image_count);
2023
2024 /* We always need to ensure that the app can have this number of images
2025 * acquired concurrently in between presents:
2026 * "VUID-vkAcquireNextImageKHR-swapchain-01802
2027 * If the number of currently acquired images is greater than the difference
2028 * between the number of images in swapchain and the value of
2029 * VkSurfaceCapabilitiesKHR::minImageCount as returned by a call to
2030 * vkGetPhysicalDeviceSurfaceCapabilities2KHR with the surface used to
2031 * create swapchain, timeout must not be UINT64_MAX"
2032 */
2033 unsigned forward_progress_guaranteed_acquired_images =
2034 chain->base.image_count - min_image_count + 1;
2035
2036 /* Wait for our presentation to occur and ensure we have at least one
2037 * image that can be acquired by the client afterwards. This ensures we
2038 * can pull on the present-queue on the next loop.
2039 */
2040 while (chain->images[image_index].present_queued ||
2041 /* If we have images in the present queue the outer loop won't block and a break
2042 * here would end up at this loop again, otherwise a break here satisfies
2043 * VUID-vkAcquireNextImageKHR-swapchain-01802 */
2044 x11_driver_owned_images(chain) < forward_progress_guaranteed_acquired_images) {
2045
2046 /* Calls to xcb_wait_for_special_event are broken by design due to a XCB flaw.
2047 * This call may hang indefinitely if the X window is destroyed before the swapchain.
2048 * An X window destruction does not trigger a special event here, unfortunately.
2049 *
2050 * A workaround was attempted in
2051 * https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/13564#note_1121977, but
2052 * was reverted due to its high CPU usage.
2053 * No pragmatic solution exists that solves CPU usage and stutter problems.
2054 *
2055 * A xcb_poll call followed by poll() is a race condition if other threads read from the XCB connection FD
2056 * between the xcb poll and fd poll(), even if it's completely unrelated to this event queue.
2057 * poll() may end up waiting indefinitely even if the XCB event has been moved from the FD
2058 * to chain->special_event queue.
2059 * The proper fix is a wait_for_special_event_with_timeout, but it does not exist.
2060 * See https://gitlab.freedesktop.org/xorg/lib/libxcb/-/merge_requests/9.
2061 * For now, keep this approach. Applications are generally well-behaved. */
2062 xcb_generic_event_t *event =
2063 xcb_wait_for_special_event(chain->conn, chain->special_event);
2064 if (!event) {
2065 result = VK_ERROR_SURFACE_LOST_KHR;
2066 goto fail;
2067 }
2068
2069 result = x11_handle_dri3_present_event(chain, (void *)event);
2070 /* Ensure that VK_SUBOPTIMAL_KHR is reported to the application */
2071 result = x11_swapchain_result(chain, result);
2072 free(event);
2073 if (result < 0)
2074 goto fail;
2075 }
2076 }
2077 }
2078
2079 fail:
2080 x11_swapchain_result(chain, result);
2081 if (chain->has_acquire_queue)
2082 wsi_queue_push(&chain->acquire_queue, UINT32_MAX);
2083
2084 return NULL;
2085 }
2086
2087 static uint8_t *
alloc_shm(struct wsi_image * imagew,unsigned size)2088 alloc_shm(struct wsi_image *imagew, unsigned size)
2089 {
2090 #ifdef HAVE_SYS_SHM_H
2091 struct x11_image *image = (struct x11_image *)imagew;
2092 image->shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0600);
2093 if (image->shmid < 0)
2094 return NULL;
2095
2096 uint8_t *addr = (uint8_t *)shmat(image->shmid, 0, 0);
2097 /* mark the segment immediately for deletion to avoid leaks */
2098 shmctl(image->shmid, IPC_RMID, 0);
2099
2100 if (addr == (uint8_t *) -1)
2101 return NULL;
2102
2103 image->shmaddr = addr;
2104 return addr;
2105 #else
2106 return NULL;
2107 #endif
2108 }
2109
2110 static VkResult
x11_image_init(VkDevice device_h,struct x11_swapchain * chain,const VkSwapchainCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,struct x11_image * image)2111 x11_image_init(VkDevice device_h, struct x11_swapchain *chain,
2112 const VkSwapchainCreateInfoKHR *pCreateInfo,
2113 const VkAllocationCallbacks* pAllocator,
2114 struct x11_image *image)
2115 {
2116 xcb_void_cookie_t cookie;
2117 xcb_generic_error_t *error = NULL;
2118 VkResult result;
2119 uint32_t bpp = 32;
2120 int fence_fd;
2121
2122 result = wsi_create_image(&chain->base, &chain->base.image_info,
2123 &image->base);
2124 if (result != VK_SUCCESS)
2125 return result;
2126
2127 image->update_region = xcb_generate_id(chain->conn);
2128 xcb_xfixes_create_region(chain->conn, image->update_region, 0, NULL);
2129
2130 if (chain->base.wsi->sw) {
2131 if (!chain->has_mit_shm) {
2132 image->busy = false;
2133 return VK_SUCCESS;
2134 }
2135
2136 image->shmseg = xcb_generate_id(chain->conn);
2137
2138 xcb_shm_attach(chain->conn,
2139 image->shmseg,
2140 image->shmid,
2141 0);
2142 image->pixmap = xcb_generate_id(chain->conn);
2143 cookie = xcb_shm_create_pixmap_checked(chain->conn,
2144 image->pixmap,
2145 chain->window,
2146 image->base.row_pitches[0] / 4,
2147 pCreateInfo->imageExtent.height,
2148 chain->depth,
2149 image->shmseg, 0);
2150 xcb_discard_reply(chain->conn, cookie.sequence);
2151 goto out_fence;
2152 }
2153 image->pixmap = xcb_generate_id(chain->conn);
2154
2155 #ifdef HAVE_DRI3_MODIFIERS
2156 if (image->base.drm_modifier != DRM_FORMAT_MOD_INVALID) {
2157 /* If the image has a modifier, we must have DRI3 v1.2. */
2158 assert(chain->has_dri3_modifiers);
2159
2160 /* XCB requires an array of file descriptors but we only have one */
2161 int fds[4] = { -1, -1, -1, -1 };
2162 for (int i = 0; i < image->base.num_planes; i++) {
2163 fds[i] = os_dupfd_cloexec(image->base.dma_buf_fd);
2164 if (fds[i] == -1) {
2165 for (int j = 0; j < i; j++)
2166 close(fds[j]);
2167
2168 return VK_ERROR_OUT_OF_HOST_MEMORY;
2169 }
2170 }
2171
2172 cookie =
2173 xcb_dri3_pixmap_from_buffers_checked(chain->conn,
2174 image->pixmap,
2175 chain->window,
2176 image->base.num_planes,
2177 pCreateInfo->imageExtent.width,
2178 pCreateInfo->imageExtent.height,
2179 image->base.row_pitches[0],
2180 image->base.offsets[0],
2181 image->base.row_pitches[1],
2182 image->base.offsets[1],
2183 image->base.row_pitches[2],
2184 image->base.offsets[2],
2185 image->base.row_pitches[3],
2186 image->base.offsets[3],
2187 chain->depth, bpp,
2188 image->base.drm_modifier,
2189 fds);
2190 } else
2191 #endif
2192 {
2193 /* Without passing modifiers, we can't have multi-plane RGB images. */
2194 assert(image->base.num_planes == 1);
2195
2196 /* XCB will take ownership of the FD we pass it. */
2197 int fd = os_dupfd_cloexec(image->base.dma_buf_fd);
2198 if (fd == -1)
2199 return VK_ERROR_OUT_OF_HOST_MEMORY;
2200
2201 cookie =
2202 xcb_dri3_pixmap_from_buffer_checked(chain->conn,
2203 image->pixmap,
2204 chain->window,
2205 image->base.sizes[0],
2206 pCreateInfo->imageExtent.width,
2207 pCreateInfo->imageExtent.height,
2208 image->base.row_pitches[0],
2209 chain->depth, bpp, fd);
2210 }
2211
2212 error = xcb_request_check(chain->conn, cookie);
2213 if (error != NULL) {
2214 free(error);
2215 goto fail_image;
2216 }
2217
2218 out_fence:
2219 fence_fd = xshmfence_alloc_shm();
2220 if (fence_fd < 0)
2221 goto fail_pixmap;
2222
2223 image->shm_fence = xshmfence_map_shm(fence_fd);
2224 if (image->shm_fence == NULL)
2225 goto fail_shmfence_alloc;
2226
2227 image->sync_fence = xcb_generate_id(chain->conn);
2228 xcb_dri3_fence_from_fd(chain->conn,
2229 image->pixmap,
2230 image->sync_fence,
2231 false,
2232 fence_fd);
2233
2234 image->busy = false;
2235 xshmfence_trigger(image->shm_fence);
2236
2237 return VK_SUCCESS;
2238
2239 fail_shmfence_alloc:
2240 close(fence_fd);
2241
2242 fail_pixmap:
2243 cookie = xcb_free_pixmap(chain->conn, image->pixmap);
2244 xcb_discard_reply(chain->conn, cookie.sequence);
2245
2246 fail_image:
2247 wsi_destroy_image(&chain->base, &image->base);
2248
2249 return VK_ERROR_INITIALIZATION_FAILED;
2250 }
2251
2252 static void
x11_image_finish(struct x11_swapchain * chain,const VkAllocationCallbacks * pAllocator,struct x11_image * image)2253 x11_image_finish(struct x11_swapchain *chain,
2254 const VkAllocationCallbacks* pAllocator,
2255 struct x11_image *image)
2256 {
2257 xcb_void_cookie_t cookie;
2258
2259 if (!chain->base.wsi->sw || chain->has_mit_shm) {
2260 cookie = xcb_sync_destroy_fence(chain->conn, image->sync_fence);
2261 xcb_discard_reply(chain->conn, cookie.sequence);
2262 xshmfence_unmap_shm(image->shm_fence);
2263
2264 cookie = xcb_free_pixmap(chain->conn, image->pixmap);
2265 xcb_discard_reply(chain->conn, cookie.sequence);
2266
2267 cookie = xcb_xfixes_destroy_region(chain->conn, image->update_region);
2268 xcb_discard_reply(chain->conn, cookie.sequence);
2269 }
2270
2271 wsi_destroy_image(&chain->base, &image->base);
2272 #ifdef HAVE_SYS_SHM_H
2273 if (image->shmaddr)
2274 shmdt(image->shmaddr);
2275 #endif
2276 }
2277
2278 static void
wsi_x11_get_dri3_modifiers(struct wsi_x11_connection * wsi_conn,xcb_connection_t * conn,xcb_window_t window,uint8_t depth,uint8_t bpp,VkCompositeAlphaFlagsKHR vk_alpha,uint64_t ** modifiers_in,uint32_t * num_modifiers_in,uint32_t * num_tranches_in,const VkAllocationCallbacks * pAllocator)2279 wsi_x11_get_dri3_modifiers(struct wsi_x11_connection *wsi_conn,
2280 xcb_connection_t *conn, xcb_window_t window,
2281 uint8_t depth, uint8_t bpp,
2282 VkCompositeAlphaFlagsKHR vk_alpha,
2283 uint64_t **modifiers_in, uint32_t *num_modifiers_in,
2284 uint32_t *num_tranches_in,
2285 const VkAllocationCallbacks *pAllocator)
2286 {
2287 if (!wsi_conn->has_dri3_modifiers)
2288 goto out;
2289
2290 #ifdef HAVE_DRI3_MODIFIERS
2291 xcb_generic_error_t *error = NULL;
2292 xcb_dri3_get_supported_modifiers_cookie_t mod_cookie =
2293 xcb_dri3_get_supported_modifiers(conn, window, depth, bpp);
2294 xcb_dri3_get_supported_modifiers_reply_t *mod_reply =
2295 xcb_dri3_get_supported_modifiers_reply(conn, mod_cookie, &error);
2296 free(error);
2297
2298 if (!mod_reply || (mod_reply->num_window_modifiers == 0 &&
2299 mod_reply->num_screen_modifiers == 0)) {
2300 free(mod_reply);
2301 goto out;
2302 }
2303
2304 uint32_t n = 0;
2305 uint32_t counts[2];
2306 uint64_t *modifiers[2];
2307
2308 if (mod_reply->num_window_modifiers) {
2309 counts[n] = mod_reply->num_window_modifiers;
2310 modifiers[n] = vk_alloc(pAllocator,
2311 counts[n] * sizeof(uint64_t),
2312 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2313 if (!modifiers[n]) {
2314 free(mod_reply);
2315 goto out;
2316 }
2317
2318 memcpy(modifiers[n],
2319 xcb_dri3_get_supported_modifiers_window_modifiers(mod_reply),
2320 counts[n] * sizeof(uint64_t));
2321 n++;
2322 }
2323
2324 if (mod_reply->num_screen_modifiers) {
2325 counts[n] = mod_reply->num_screen_modifiers;
2326 modifiers[n] = vk_alloc(pAllocator,
2327 counts[n] * sizeof(uint64_t),
2328 8, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2329 if (!modifiers[n]) {
2330 if (n > 0)
2331 vk_free(pAllocator, modifiers[0]);
2332 free(mod_reply);
2333 goto out;
2334 }
2335
2336 memcpy(modifiers[n],
2337 xcb_dri3_get_supported_modifiers_screen_modifiers(mod_reply),
2338 counts[n] * sizeof(uint64_t));
2339 n++;
2340 }
2341
2342 for (int i = 0; i < n; i++) {
2343 modifiers_in[i] = modifiers[i];
2344 num_modifiers_in[i] = counts[i];
2345 }
2346 *num_tranches_in = n;
2347
2348 free(mod_reply);
2349 return;
2350 #endif
2351 out:
2352 *num_tranches_in = 0;
2353 }
2354
2355 static VkResult
x11_swapchain_destroy(struct wsi_swapchain * anv_chain,const VkAllocationCallbacks * pAllocator)2356 x11_swapchain_destroy(struct wsi_swapchain *anv_chain,
2357 const VkAllocationCallbacks *pAllocator)
2358 {
2359 struct x11_swapchain *chain = (struct x11_swapchain *)anv_chain;
2360 xcb_void_cookie_t cookie;
2361
2362 if (chain->has_present_queue) {
2363 chain->status = VK_ERROR_OUT_OF_DATE_KHR;
2364 /* Push a UINT32_MAX to wake up the manager */
2365 wsi_queue_push(&chain->present_queue, UINT32_MAX);
2366 pthread_join(chain->queue_manager, NULL);
2367
2368 if (chain->has_acquire_queue)
2369 wsi_queue_destroy(&chain->acquire_queue);
2370 wsi_queue_destroy(&chain->present_queue);
2371 }
2372
2373 for (uint32_t i = 0; i < chain->base.image_count; i++)
2374 x11_image_finish(chain, pAllocator, &chain->images[i]);
2375
2376 xcb_unregister_for_special_event(chain->conn, chain->special_event);
2377 cookie = xcb_present_select_input_checked(chain->conn, chain->event_id,
2378 chain->window,
2379 XCB_PRESENT_EVENT_MASK_NO_EVENT);
2380 xcb_discard_reply(chain->conn, cookie.sequence);
2381
2382 pthread_mutex_destroy(&chain->present_poll_mutex);
2383 pthread_mutex_destroy(&chain->present_progress_mutex);
2384 pthread_cond_destroy(&chain->present_progress_cond);
2385
2386 wsi_swapchain_finish(&chain->base);
2387
2388 vk_free(pAllocator, chain);
2389
2390 return VK_SUCCESS;
2391 }
2392
2393 static void
wsi_x11_set_adaptive_sync_property(xcb_connection_t * conn,xcb_drawable_t drawable,uint32_t state)2394 wsi_x11_set_adaptive_sync_property(xcb_connection_t *conn,
2395 xcb_drawable_t drawable,
2396 uint32_t state)
2397 {
2398 static char const name[] = "_VARIABLE_REFRESH";
2399 xcb_intern_atom_cookie_t cookie;
2400 xcb_intern_atom_reply_t* reply;
2401 xcb_void_cookie_t check;
2402
2403 cookie = xcb_intern_atom(conn, 0, strlen(name), name);
2404 reply = xcb_intern_atom_reply(conn, cookie, NULL);
2405 if (reply == NULL)
2406 return;
2407
2408 if (state)
2409 check = xcb_change_property_checked(conn, XCB_PROP_MODE_REPLACE,
2410 drawable, reply->atom,
2411 XCB_ATOM_CARDINAL, 32, 1, &state);
2412 else
2413 check = xcb_delete_property_checked(conn, drawable, reply->atom);
2414
2415 xcb_discard_reply(conn, check.sequence);
2416 free(reply);
2417 }
2418
x11_wait_for_present_queued(struct x11_swapchain * chain,uint64_t waitValue,uint64_t timeout)2419 static VkResult x11_wait_for_present_queued(
2420 struct x11_swapchain *chain,
2421 uint64_t waitValue, uint64_t timeout)
2422 {
2423 struct timespec abs_timespec;
2424 uint64_t abs_timeout = 0;
2425 if (timeout != 0)
2426 abs_timeout = os_time_get_absolute_timeout(timeout);
2427
2428 /* Need to observe that the swapchain semaphore has been unsignalled,
2429 * as this is guaranteed when a present is complete. */
2430 VkResult result = wsi_swapchain_wait_for_present_semaphore(
2431 &chain->base, waitValue, timeout);
2432 if (result != VK_SUCCESS)
2433 return result;
2434
2435 timespec_from_nsec(&abs_timespec, abs_timeout);
2436
2437 pthread_mutex_lock(&chain->present_progress_mutex);
2438 while (chain->present_id < waitValue) {
2439 int ret = pthread_cond_timedwait(&chain->present_progress_cond,
2440 &chain->present_progress_mutex,
2441 &abs_timespec);
2442 if (ret == ETIMEDOUT) {
2443 result = VK_TIMEOUT;
2444 break;
2445 }
2446 if (ret) {
2447 result = VK_ERROR_DEVICE_LOST;
2448 break;
2449 }
2450 }
2451 if (result == VK_SUCCESS && chain->present_progress_error)
2452 result = chain->present_progress_error;
2453 pthread_mutex_unlock(&chain->present_progress_mutex);
2454 return result;
2455 }
2456
x11_wait_for_present_polled(struct x11_swapchain * chain,uint64_t waitValue,uint64_t timeout)2457 static VkResult x11_wait_for_present_polled(
2458 struct x11_swapchain *chain,
2459 uint64_t waitValue, uint64_t timeout)
2460 {
2461 struct timespec rel_timeout, abs_timespec_realtime, start_time;
2462 struct timespec abs_timespec_monotonic;
2463 uint64_t abs_timeout_monotonic = 0;
2464
2465 if (timeout != 0)
2466 abs_timeout_monotonic = os_time_get_absolute_timeout(timeout);
2467
2468 /* Mutex abs_timeout is in REALTIME timebase. */
2469 timespec_from_nsec(&rel_timeout, timeout);
2470 clock_gettime(CLOCK_REALTIME, &start_time);
2471 timespec_add(&abs_timespec_realtime, &rel_timeout, &start_time);
2472
2473 /* Need to observe that the swapchain semaphore has been unsignalled,
2474 * as this is guaranteed when a present is complete. */
2475 VkResult result = wsi_swapchain_wait_for_present_semaphore(
2476 &chain->base, waitValue, timeout);
2477 if (result != VK_SUCCESS)
2478 return result;
2479
2480 /* If we have satisfied the present ID right away, just return early. */
2481 pthread_mutex_lock(&chain->present_progress_mutex);
2482 if (chain->present_id >= waitValue) {
2483 result = chain->present_progress_error;
2484 } else {
2485 result = VK_TIMEOUT;
2486 }
2487
2488 if (result != VK_TIMEOUT) {
2489 pthread_mutex_unlock(&chain->present_progress_mutex);
2490 return result;
2491 }
2492
2493 timespec_from_nsec(&abs_timespec_monotonic, abs_timeout_monotonic);
2494
2495 /* In a situation of wait-before-signal, we need to ensure that a presentID of at least
2496 * waitValue has been submitted before we're allowed to lock the XCB connection.
2497 * Even if the user does not use wait-before-signal we can still hit this scenario on Xwayland
2498 * where we have a present queue, but no acquire queue. We need to observe that the present queue
2499 * has actually submitted the present to XCB before we're guaranteed forward progress. */
2500 while (chain->present_id_pending < waitValue) {
2501 int ret = pthread_cond_timedwait(&chain->present_progress_cond,
2502 &chain->present_progress_mutex,
2503 &abs_timespec_monotonic);
2504 if (chain->present_progress_error || ret == ETIMEDOUT || ret) {
2505 pthread_mutex_unlock(&chain->present_progress_mutex);
2506
2507 if (chain->present_progress_error)
2508 return chain->present_progress_error;
2509 else if (ret == ETIMEDOUT)
2510 return VK_TIMEOUT;
2511 else
2512 return VK_ERROR_DEVICE_LOST;
2513 }
2514 }
2515 pthread_mutex_unlock(&chain->present_progress_mutex);
2516
2517 /* This scheme of taking the message queue lock is not optimal,
2518 * but it is only problematic in meaningless situations.
2519 * - This path can only be hit by IMMEDIATE or MAILBOX mode.
2520 * Using present wait for IMMEDIATE and MAILBOX is not particularly useful except
2521 * for safe teardown purposes and recycling semaphores.
2522 * - There is contention with multiple threads waiting for PresentWait,
2523 * where the first thread to wait is blocking with no timeout and hogs the message queue until
2524 * that present is processed. */
2525 int ret;
2526 if (timeout == UINT64_MAX)
2527 ret = pthread_mutex_lock(&chain->present_poll_mutex);
2528 else
2529 ret = pthread_mutex_timedlock(&chain->present_poll_mutex, &abs_timespec_realtime);
2530
2531 if (ret) {
2532 if (ret == ETIMEDOUT)
2533 return VK_TIMEOUT;
2534 else
2535 return VK_ERROR_DEVICE_LOST;
2536 }
2537
2538 result = chain->present_progress_error;
2539
2540 while (result == VK_SUCCESS && chain->present_id < waitValue) {
2541 xcb_generic_event_t *event;
2542 xcb_flush(chain->conn);
2543
2544 if (timeout == UINT64_MAX) {
2545 /* See comments in x11_manage_fifo_queues about problem scenarios with this call. */
2546 event = xcb_wait_for_special_event(chain->conn, chain->special_event);
2547 if (!event) {
2548 result = x11_swapchain_result(chain, VK_ERROR_SURFACE_LOST_KHR);
2549 goto fail;
2550 }
2551 } else {
2552 result = x11_poll_for_special_event(chain, abs_timeout_monotonic, &event);
2553 if (result != VK_SUCCESS)
2554 goto fail;
2555 }
2556
2557 result = x11_handle_dri3_present_event(chain, (void *)event);
2558 /* Ensure that VK_SUBOPTIMAL_KHR is reported to the application */
2559 result = x11_swapchain_result(chain, result);
2560 free(event);
2561 }
2562
2563 fail:
2564 pthread_mutex_unlock(&chain->present_poll_mutex);
2565 return result;
2566 }
2567
x11_wait_for_present(struct wsi_swapchain * wsi_chain,uint64_t waitValue,uint64_t timeout)2568 static VkResult x11_wait_for_present(struct wsi_swapchain *wsi_chain,
2569 uint64_t waitValue,
2570 uint64_t timeout)
2571 {
2572 struct x11_swapchain *chain = (struct x11_swapchain *)wsi_chain;
2573 VkResult result;
2574
2575 if (chain->has_present_queue && chain->has_acquire_queue) {
2576 /* In this style we have guaranteed forward progress in the present queue thread,
2577 * so we don't need to do anything.
2578 * This path is hit for FIFO presentation modes. */
2579 result = x11_wait_for_present_queued(chain, waitValue, timeout);
2580 } else {
2581 /* In this style we don't necessarily have forward progress, so we need to pump the message queue ourselves.
2582 * This blocks the message queue for other threads that want to present.
2583 * In practice, we'll only end up blocking on swapchain teardown, so this isn't a big deal. */
2584 result = x11_wait_for_present_polled(chain, waitValue, timeout);
2585 }
2586 return result;
2587 }
2588
2589 static unsigned
x11_get_min_image_count_for_present_mode(struct wsi_device * wsi_device,struct wsi_x11_connection * wsi_conn,VkPresentModeKHR present_mode)2590 x11_get_min_image_count_for_present_mode(struct wsi_device *wsi_device,
2591 struct wsi_x11_connection *wsi_conn,
2592 VkPresentModeKHR present_mode)
2593 {
2594 if (x11_needs_wait_for_fences(wsi_device, wsi_conn, present_mode))
2595 return 5;
2596 else
2597 return x11_get_min_image_count(wsi_device, wsi_conn->is_xwayland);
2598 }
2599
2600 /**
2601 * Create the swapchain.
2602 *
2603 * Supports immediate, fifo and mailbox presentation mode.
2604 *
2605 */
2606 static VkResult
x11_surface_create_swapchain(VkIcdSurfaceBase * icd_surface,VkDevice device,struct wsi_device * wsi_device,const VkSwapchainCreateInfoKHR * pCreateInfo,const VkAllocationCallbacks * pAllocator,struct wsi_swapchain ** swapchain_out)2607 x11_surface_create_swapchain(VkIcdSurfaceBase *icd_surface,
2608 VkDevice device,
2609 struct wsi_device *wsi_device,
2610 const VkSwapchainCreateInfoKHR *pCreateInfo,
2611 const VkAllocationCallbacks* pAllocator,
2612 struct wsi_swapchain **swapchain_out)
2613 {
2614 struct x11_swapchain *chain;
2615 xcb_void_cookie_t cookie;
2616 VkResult result;
2617 VkPresentModeKHR present_mode = wsi_swapchain_get_present_mode(wsi_device, pCreateInfo);
2618
2619 assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR);
2620
2621 /* Get xcb connection from the icd_surface and from that our internal struct
2622 * representing it.
2623 */
2624 xcb_connection_t *conn = x11_surface_get_connection(icd_surface);
2625 struct wsi_x11_connection *wsi_conn =
2626 wsi_x11_get_connection(wsi_device, conn);
2627 if (!wsi_conn)
2628 return VK_ERROR_OUT_OF_HOST_MEMORY;
2629
2630 /* Get number of images in our swapchain. This count depends on:
2631 * - requested minimal image count
2632 * - device characteristics
2633 * - presentation mode.
2634 */
2635 unsigned num_images = pCreateInfo->minImageCount;
2636 if (wsi_device->x11.strict_imageCount)
2637 num_images = pCreateInfo->minImageCount;
2638 else if (x11_needs_wait_for_fences(wsi_device, wsi_conn, present_mode))
2639 num_images = MAX2(num_images, 5);
2640 else if (wsi_device->x11.ensure_minImageCount)
2641 num_images = MAX2(num_images, x11_get_min_image_count(wsi_device, wsi_conn->is_xwayland));
2642
2643 /* Check that we have a window up-front. It is an error to not have one. */
2644 xcb_window_t window = x11_surface_get_window(icd_surface);
2645
2646 /* Get the geometry of that window. The bit depth of the swapchain will be fitted and the
2647 * chain's images extents should fit it for performance-optimizing flips.
2648 */
2649 xcb_get_geometry_reply_t *geometry =
2650 xcb_get_geometry_reply(conn, xcb_get_geometry(conn, window), NULL);
2651 if (geometry == NULL)
2652 return VK_ERROR_SURFACE_LOST_KHR;
2653 const uint32_t bit_depth = geometry->depth;
2654 const uint16_t cur_width = geometry->width;
2655 const uint16_t cur_height = geometry->height;
2656 free(geometry);
2657
2658 /* Allocate the actual swapchain. The size depends on image count. */
2659 size_t size = sizeof(*chain) + num_images * sizeof(chain->images[0]);
2660 chain = vk_zalloc(pAllocator, size, 8,
2661 VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
2662 if (chain == NULL)
2663 return VK_ERROR_OUT_OF_HOST_MEMORY;
2664
2665 int ret = pthread_mutex_init(&chain->present_progress_mutex, NULL);
2666 if (ret != 0) {
2667 vk_free(pAllocator, chain);
2668 return VK_ERROR_OUT_OF_HOST_MEMORY;
2669 }
2670
2671 ret = pthread_mutex_init(&chain->present_poll_mutex, NULL);
2672 if (ret != 0) {
2673 pthread_mutex_destroy(&chain->present_progress_mutex);
2674 vk_free(pAllocator, chain);
2675 return VK_ERROR_OUT_OF_HOST_MEMORY;
2676 }
2677
2678 bool bret = wsi_init_pthread_cond_monotonic(&chain->present_progress_cond);
2679 if (!bret) {
2680 pthread_mutex_destroy(&chain->present_progress_mutex);
2681 pthread_mutex_destroy(&chain->present_poll_mutex);
2682 vk_free(pAllocator, chain);
2683 return VK_ERROR_OUT_OF_HOST_MEMORY;
2684 }
2685
2686 struct wsi_base_image_params *image_params = NULL;
2687 struct wsi_cpu_image_params cpu_image_params;
2688 struct wsi_drm_image_params drm_image_params;
2689 uint64_t *modifiers[2] = {NULL, NULL};
2690 uint32_t num_modifiers[2] = {0, 0};
2691 if (wsi_device->sw) {
2692 cpu_image_params = (struct wsi_cpu_image_params) {
2693 .base.image_type = WSI_IMAGE_TYPE_CPU,
2694 .alloc_shm = wsi_conn->has_mit_shm ? &alloc_shm : NULL,
2695 };
2696 image_params = &cpu_image_params.base;
2697 } else {
2698 drm_image_params = (struct wsi_drm_image_params) {
2699 .base.image_type = WSI_IMAGE_TYPE_DRM,
2700 .same_gpu = wsi_x11_check_dri3_compatible(wsi_device, conn),
2701 };
2702 if (wsi_device->supports_modifiers) {
2703 wsi_x11_get_dri3_modifiers(wsi_conn, conn, window, bit_depth, 32,
2704 pCreateInfo->compositeAlpha,
2705 modifiers, num_modifiers,
2706 &drm_image_params.num_modifier_lists,
2707 pAllocator);
2708 drm_image_params.num_modifiers = num_modifiers;
2709 drm_image_params.modifiers = (const uint64_t **)modifiers;
2710 }
2711 image_params = &drm_image_params.base;
2712 }
2713
2714 result = wsi_swapchain_init(wsi_device, &chain->base, device, pCreateInfo,
2715 image_params, pAllocator);
2716
2717 for (int i = 0; i < ARRAY_SIZE(modifiers); i++)
2718 vk_free(pAllocator, modifiers[i]);
2719
2720 if (result != VK_SUCCESS)
2721 goto fail_alloc;
2722
2723 chain->base.destroy = x11_swapchain_destroy;
2724 chain->base.get_wsi_image = x11_get_wsi_image;
2725 chain->base.acquire_next_image = x11_acquire_next_image;
2726 chain->base.queue_present = x11_queue_present;
2727 chain->base.wait_for_present = x11_wait_for_present;
2728 chain->base.release_images = x11_release_images;
2729 chain->base.present_mode = present_mode;
2730 chain->base.image_count = num_images;
2731 chain->conn = conn;
2732 chain->window = window;
2733 chain->depth = bit_depth;
2734 chain->extent = pCreateInfo->imageExtent;
2735 chain->send_sbc = 0;
2736 chain->sent_image_count = 0;
2737 chain->last_present_msc = 0;
2738 chain->has_acquire_queue = false;
2739 chain->has_present_queue = false;
2740 chain->status = VK_SUCCESS;
2741 chain->has_dri3_modifiers = wsi_conn->has_dri3_modifiers;
2742 chain->has_mit_shm = wsi_conn->has_mit_shm;
2743
2744 xcb_present_query_capabilities_cookie_t present_query_cookie;
2745 xcb_present_query_capabilities_reply_t *present_query_reply;
2746 present_query_cookie = xcb_present_query_capabilities(conn, chain->window);
2747 present_query_reply = xcb_present_query_capabilities_reply(conn, present_query_cookie, NULL);
2748 if (present_query_reply) {
2749 chain->has_async_may_tear = present_query_reply->capabilities & XCB_PRESENT_CAPABILITY_ASYNC_MAY_TEAR;
2750 free(present_query_reply);
2751 }
2752
2753 /* When images in the swapchain don't fit the window, X can still present them, but it won't
2754 * happen by flip, only by copy. So this is a suboptimal copy, because if the client would change
2755 * the chain extents X may be able to flip
2756 */
2757 if (chain->extent.width != cur_width || chain->extent.height != cur_height)
2758 chain->status = VK_SUBOPTIMAL_KHR;
2759
2760 /* On a new swapchain this helper variable is set to false. Once we present it will have an
2761 * impact once we ever do at least one flip and go back to copying afterwards. It is presumed
2762 * that in this case here is a high likelihood X could do flips again if the client reallocates a
2763 * new swapchain.
2764 *
2765 * Note that we used to inheritted this property from 'pCreateInfo->oldSwapchain'. But when it
2766 * was true, and when the next present was completed with copying, we would return
2767 * VK_SUBOPTIMAL_KHR and hint the app to reallocate again for no good reason. If all following
2768 * presents on the surface were completed with copying because of some surface state change, we
2769 * would always return VK_SUBOPTIMAL_KHR no matter how many times the app had reallocated.
2770 *
2771 * Note also that is is questionable in general if that mechanism is really useful. It ist not
2772 * clear why on a change from flipping to copying we can assume a reallocation has a high chance
2773 * of making flips work again per se. In other words it is not clear why there is need for
2774 * another way to inform clients about suboptimal copies besides forwarding the
2775 * 'PresentOptionSuboptimal' complete mode.
2776 */
2777 chain->copy_is_suboptimal = false;
2778
2779 /* For our swapchain we need to listen to following Present extension events:
2780 * - Configure: Window dimensions changed. Images in the swapchain might need
2781 * to be reallocated.
2782 * - Complete: An image from our swapchain was presented on the output.
2783 * - Idle: An image from our swapchain is not anymore accessed by the X
2784 * server and can be reused.
2785 */
2786 chain->event_id = xcb_generate_id(chain->conn);
2787 xcb_present_select_input(chain->conn, chain->event_id, chain->window,
2788 XCB_PRESENT_EVENT_MASK_CONFIGURE_NOTIFY |
2789 XCB_PRESENT_EVENT_MASK_COMPLETE_NOTIFY |
2790 XCB_PRESENT_EVENT_MASK_IDLE_NOTIFY);
2791
2792 /* Create an XCB event queue to hold present events outside of the usual
2793 * application event queue
2794 */
2795 chain->special_event =
2796 xcb_register_for_special_xge(chain->conn, &xcb_present_id,
2797 chain->event_id, NULL);
2798
2799 /* Create the graphics context. */
2800 chain->gc = xcb_generate_id(chain->conn);
2801 if (!chain->gc) {
2802 /* FINISHME: Choose a better error. */
2803 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2804 goto fail_register;
2805 }
2806
2807 cookie = xcb_create_gc(chain->conn,
2808 chain->gc,
2809 chain->window,
2810 XCB_GC_GRAPHICS_EXPOSURES,
2811 (uint32_t []) { 0 });
2812 xcb_discard_reply(chain->conn, cookie.sequence);
2813
2814 uint32_t image = 0;
2815 for (; image < chain->base.image_count; image++) {
2816 result = x11_image_init(device, chain, pCreateInfo, pAllocator,
2817 &chain->images[image]);
2818 if (result != VK_SUCCESS)
2819 goto fail_init_images;
2820 }
2821
2822 /* Initialize queues for images in our swapchain. Possible queues are:
2823 * - Present queue: for images sent to the X server but not yet presented.
2824 * - Acquire queue: for images already presented but not yet released by the
2825 * X server.
2826 *
2827 * In general queues are not used on software drivers, otherwise which queues
2828 * are used depends on our presentation mode:
2829 * - Fifo: present and acquire
2830 * - Mailbox: present only
2831 * - Immediate: present when we wait on fences before buffer submission (Xwayland)
2832 */
2833 if ((chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR ||
2834 chain->base.present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR ||
2835 x11_needs_wait_for_fences(wsi_device, wsi_conn,
2836 chain->base.present_mode)) &&
2837 !chain->base.wsi->sw) {
2838 chain->has_present_queue = true;
2839
2840 /* The queues have a length of base.image_count + 1 because we will
2841 * occasionally use UINT32_MAX to signal the other thread that an error
2842 * has occurred and we don't want an overflow.
2843 */
2844 int ret;
2845 ret = wsi_queue_init(&chain->present_queue, chain->base.image_count + 1);
2846 if (ret) {
2847 goto fail_init_images;
2848 }
2849
2850 if (chain->base.present_mode == VK_PRESENT_MODE_FIFO_KHR ||
2851 chain->base.present_mode == VK_PRESENT_MODE_FIFO_RELAXED_KHR) {
2852 chain->has_acquire_queue = true;
2853
2854 ret = wsi_queue_init(&chain->acquire_queue, chain->base.image_count + 1);
2855 if (ret) {
2856 wsi_queue_destroy(&chain->present_queue);
2857 goto fail_init_images;
2858 }
2859
2860 for (unsigned i = 0; i < chain->base.image_count; i++)
2861 wsi_queue_push(&chain->acquire_queue, i);
2862 }
2863
2864 ret = pthread_create(&chain->queue_manager, NULL,
2865 x11_manage_fifo_queues, chain);
2866 if (ret) {
2867 wsi_queue_destroy(&chain->present_queue);
2868 if (chain->has_acquire_queue)
2869 wsi_queue_destroy(&chain->acquire_queue);
2870
2871 goto fail_init_images;
2872 }
2873 }
2874
2875 assert(chain->has_present_queue || !chain->has_acquire_queue);
2876
2877 /* It is safe to set it here as only one swapchain can be associated with
2878 * the window, and swapchain creation does the association. At this point
2879 * we know the creation is going to succeed. */
2880 wsi_x11_set_adaptive_sync_property(conn, window,
2881 wsi_device->enable_adaptive_sync);
2882
2883 *swapchain_out = &chain->base;
2884
2885 return VK_SUCCESS;
2886
2887 fail_init_images:
2888 for (uint32_t j = 0; j < image; j++)
2889 x11_image_finish(chain, pAllocator, &chain->images[j]);
2890
2891 fail_register:
2892 xcb_unregister_for_special_event(chain->conn, chain->special_event);
2893
2894 wsi_swapchain_finish(&chain->base);
2895
2896 fail_alloc:
2897 vk_free(pAllocator, chain);
2898
2899 return result;
2900 }
2901
2902 VkResult
wsi_x11_init_wsi(struct wsi_device * wsi_device,const VkAllocationCallbacks * alloc,const struct driOptionCache * dri_options)2903 wsi_x11_init_wsi(struct wsi_device *wsi_device,
2904 const VkAllocationCallbacks *alloc,
2905 const struct driOptionCache *dri_options)
2906 {
2907 struct wsi_x11 *wsi;
2908 VkResult result;
2909
2910 wsi = vk_alloc(alloc, sizeof(*wsi), 8,
2911 VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE);
2912 if (!wsi) {
2913 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2914 goto fail;
2915 }
2916
2917 int ret = pthread_mutex_init(&wsi->mutex, NULL);
2918 if (ret != 0) {
2919 if (ret == ENOMEM) {
2920 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2921 } else {
2922 /* FINISHME: Choose a better error. */
2923 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2924 }
2925
2926 goto fail_alloc;
2927 }
2928
2929 wsi->connections = _mesa_hash_table_create(NULL, _mesa_hash_pointer,
2930 _mesa_key_pointer_equal);
2931 if (!wsi->connections) {
2932 result = VK_ERROR_OUT_OF_HOST_MEMORY;
2933 goto fail_mutex;
2934 }
2935
2936 if (dri_options) {
2937 if (driCheckOption(dri_options, "vk_x11_override_min_image_count", DRI_INT)) {
2938 wsi_device->x11.override_minImageCount =
2939 driQueryOptioni(dri_options, "vk_x11_override_min_image_count");
2940 }
2941 if (driCheckOption(dri_options, "vk_x11_strict_image_count", DRI_BOOL)) {
2942 wsi_device->x11.strict_imageCount =
2943 driQueryOptionb(dri_options, "vk_x11_strict_image_count");
2944 }
2945 if (driCheckOption(dri_options, "vk_x11_ensure_min_image_count", DRI_BOOL)) {
2946 wsi_device->x11.ensure_minImageCount =
2947 driQueryOptionb(dri_options, "vk_x11_ensure_min_image_count");
2948 }
2949 wsi_device->x11.xwaylandWaitReady = true;
2950 if (driCheckOption(dri_options, "vk_xwayland_wait_ready", DRI_BOOL)) {
2951 wsi_device->x11.xwaylandWaitReady =
2952 driQueryOptionb(dri_options, "vk_xwayland_wait_ready");
2953 }
2954 }
2955
2956 wsi->base.get_support = x11_surface_get_support;
2957 wsi->base.get_capabilities2 = x11_surface_get_capabilities2;
2958 wsi->base.get_formats = x11_surface_get_formats;
2959 wsi->base.get_formats2 = x11_surface_get_formats2;
2960 wsi->base.get_present_modes = x11_surface_get_present_modes;
2961 wsi->base.get_present_rectangles = x11_surface_get_present_rectangles;
2962 wsi->base.create_swapchain = x11_surface_create_swapchain;
2963
2964 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = &wsi->base;
2965 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = &wsi->base;
2966
2967 return VK_SUCCESS;
2968
2969 fail_mutex:
2970 pthread_mutex_destroy(&wsi->mutex);
2971 fail_alloc:
2972 vk_free(alloc, wsi);
2973 fail:
2974 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB] = NULL;
2975 wsi_device->wsi[VK_ICD_WSI_PLATFORM_XLIB] = NULL;
2976
2977 return result;
2978 }
2979
2980 void
wsi_x11_finish_wsi(struct wsi_device * wsi_device,const VkAllocationCallbacks * alloc)2981 wsi_x11_finish_wsi(struct wsi_device *wsi_device,
2982 const VkAllocationCallbacks *alloc)
2983 {
2984 struct wsi_x11 *wsi =
2985 (struct wsi_x11 *)wsi_device->wsi[VK_ICD_WSI_PLATFORM_XCB];
2986
2987 if (wsi) {
2988 hash_table_foreach(wsi->connections, entry)
2989 wsi_x11_connection_destroy(wsi_device, entry->data);
2990
2991 _mesa_hash_table_destroy(wsi->connections, NULL);
2992
2993 pthread_mutex_destroy(&wsi->mutex);
2994
2995 vk_free(alloc, wsi);
2996 }
2997 }
2998