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