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