Debian Codegraph @

third_party/rust/wgpu-hal/src/vulkan/instance.rs

raw
1 use alloc::{
2 borrow::ToOwned as _,
3 boxed::Box,
4 ffi::CString,
5 string::{String, ToString as _},
6 sync::Arc,
7 vec::Vec,
8 };
9 use core::{
10 ffi::{c_void, CStr},
11 slice,
12 str::FromStr,
13 };
14 use std::thread;
15
16 use arrayvec::ArrayVec;
17 use ash::{ext, khr, vk};
18 use parking_lot::RwLock;
19
20 unsafe extern "system" fn debug_utils_messenger_callback(
21 message_severity: vk::DebugUtilsMessageSeverityFlagsEXT,
22 message_type: vk::DebugUtilsMessageTypeFlagsEXT,
23 callback_data_ptr: *const vk::DebugUtilsMessengerCallbackDataEXT,
24 user_data: *mut c_void,
25 ) -> vk::Bool32 {
26 use alloc::borrow::Cow;
27
28 if thread::panicking() {
29 return vk::FALSE;
30 }
31
32 let cd = unsafe { &*callback_data_ptr };
33 let user_data = unsafe { &*user_data.cast::<super::DebugUtilsMessengerUserData>() };
34
35 const VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912: i32 = 0x56146426;
36 if cd.message_id_number == VUID_VKCMDENDDEBUGUTILSLABELEXT_COMMANDBUFFER_01912 {
37 // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/5671
38 // Versions 1.3.240 through 1.3.250 return a spurious error here if
39 // the debug range start and end appear in different command buffers.
40 if let Some(layer_properties) = user_data.validation_layer_properties.as_ref() {
41 if layer_properties.layer_description.as_ref() == c"Khronos Validation Layer"
42 && layer_properties.layer_spec_version >= vk::make_api_version(0, 1, 3, 240)
43 && layer_properties.layer_spec_version <= vk::make_api_version(0, 1, 3, 250)
44 {
45 return vk::FALSE;
46 }
47 }
48 }
49
50 // Silence Vulkan Validation error "VUID-VkSwapchainCreateInfoKHR-pNext-07781"
51 // This happens when a surface is configured with a size outside the allowed extent.
52 // It's a false positive due to the inherent racy-ness of surface resizing.
53 const VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781: i32 = 0x4c8929c1;
54 if cd.message_id_number == VUID_VKSWAPCHAINCREATEINFOKHR_PNEXT_07781 {
55 return vk::FALSE;
56 }
57
58 // Silence Vulkan Validation error "VUID-VkRenderPassBeginInfo-framebuffer-04627"
59 // if the OBS layer is enabled. This is a bug in the OBS layer. As the OBS layer
60 // does not have a version number they increment, there is no way to qualify the
61 // suppression of the error to a specific version of the OBS layer.
62 //
63 // See https://github.com/obsproject/obs-studio/issues/9353
64 const VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627: i32 = 0x45125641;
65 if cd.message_id_number == VUID_VKRENDERPASSBEGININFO_FRAMEBUFFER_04627
66 && user_data.has_obs_layer
67 {
68 return vk::FALSE;
69 }
70
71 // Silence Vulkan Validation error "VUID-vkCmdCopyImageToBuffer-pRegions-00184".
72 // While we aren't sure yet, we suspect this is probably a VVL issue.
73 // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/9276
74 const VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184: i32 = 0x45ef177c;
75 if cd.message_id_number == VUID_VKCMDCOPYIMAGETOBUFFER_PREGIONS_00184 {
76 return vk::FALSE;
77 }
78
79 let level = match message_severity {
80 vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE => log::Level::Debug,
81 vk::DebugUtilsMessageSeverityFlagsEXT::INFO => log::Level::Info,
82 vk::DebugUtilsMessageSeverityFlagsEXT::WARNING => log::Level::Warn,
83 vk::DebugUtilsMessageSeverityFlagsEXT::ERROR => log::Level::Error,
84 _ => log::Level::Warn,
85 };
86
87 let message_id_name =
88 unsafe { cd.message_id_name_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy);
89 let message = unsafe { cd.message_as_c_str() }.map_or(Cow::Borrowed(""), CStr::to_string_lossy);
90
91 let _ = std::panic::catch_unwind(|| {
92 log::log!(
93 level,
94 "{:?} [{} (0x{:x})]\n\t{}",
95 message_type,
96 message_id_name,
97 cd.message_id_number,
98 message,
99 );
100 });
101
102 if cd.queue_label_count != 0 {
103 let labels =
104 unsafe { slice::from_raw_parts(cd.p_queue_labels, cd.queue_label_count as usize) };
105 let names = labels
106 .iter()
107 .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy))
108 .collect::<Vec<_>>();
109
110 let _ = std::panic::catch_unwind(|| {
111 log::log!(level, "\tqueues: {}", names.join(", "));
112 });
113 }
114
115 if cd.cmd_buf_label_count != 0 {
116 let labels =
117 unsafe { slice::from_raw_parts(cd.p_cmd_buf_labels, cd.cmd_buf_label_count as usize) };
118 let names = labels
119 .iter()
120 .flat_map(|dul_obj| unsafe { dul_obj.label_name_as_c_str() }.map(CStr::to_string_lossy))
121 .collect::<Vec<_>>();
122
123 let _ = std::panic::catch_unwind(|| {
124 log::log!(level, "\tcommand buffers: {}", names.join(", "));
125 });
126 }
127
128 if cd.object_count != 0 {
129 let labels = unsafe { slice::from_raw_parts(cd.p_objects, cd.object_count as usize) };
130 //TODO: use color fields of `vk::DebugUtilsLabelExt`?
131 let names = labels
132 .iter()
133 .map(|obj_info| {
134 let name = unsafe { obj_info.object_name_as_c_str() }
135 .map_or(Cow::Borrowed("?"), CStr::to_string_lossy);
136
137 format!(
138 "(type: {:?}, hndl: 0x{:x}, name: {})",
139 obj_info.object_type, obj_info.object_handle, name
140 )
141 })
142 .collect::<Vec<_>>();
143 let _ = std::panic::catch_unwind(|| {
144 log::log!(level, "\tobjects: {}", names.join(", "));
145 });
146 }
147
148 if cfg!(debug_assertions) && level == log::Level::Error {
149 // Set canary and continue
150 crate::VALIDATION_CANARY.add(message.to_string());
151 }
152
153 vk::FALSE
154 }
155
156 impl super::DebugUtilsCreateInfo {
157 fn to_vk_create_info(&self) -> vk::DebugUtilsMessengerCreateInfoEXT<'_> {
158 let user_data_ptr: *const super::DebugUtilsMessengerUserData = &*self.callback_data;
159 vk::DebugUtilsMessengerCreateInfoEXT::default()
160 .message_severity(self.severity)
161 .message_type(self.message_type)
162 .user_data(user_data_ptr as *mut _)
163 .pfn_user_callback(Some(debug_utils_messenger_callback))
164 }
165 }
166
167 impl super::Swapchain {
168 /// # Safety
169 ///
170 /// - The device must have been made idle before calling this function.
171 unsafe fn release_resources(mut self, device: &ash::Device) -> Self {
172 profiling::scope!("Swapchain::release_resources");
173 {
174 profiling::scope!("vkDeviceWaitIdle");
175 // We need to also wait until all presentation work is done. Because there is no way to portably wait until
176 // the presentation work is done, we are forced to wait until the device is idle.
177 let _ = unsafe {
178 device
179 .device_wait_idle()
180 .map_err(super::map_host_device_oom_and_lost_err)
181 };
182 };
183
184 // We cannot take this by value, as the function returns `self`.
185 for semaphore in self.surface_semaphores.drain(..) {
186 let arc_removed = Arc::into_inner(semaphore).expect(
187 "Trying to destroy a SurfaceSemaphores that is still in use by a SurfaceTexture",
188 );
189 let mutex_removed = arc_removed.into_inner();
190
191 unsafe { mutex_removed.destroy(device) };
192 }
193
194 self
195 }
196 }
197
198 impl super::InstanceShared {
199 pub fn entry(&self) -> &ash::Entry {
200 &self.entry
201 }
202
203 pub fn raw_instance(&self) -> &ash::Instance {
204 &self.raw
205 }
206
207 pub fn instance_api_version(&self) -> u32 {
208 self.instance_api_version
209 }
210
211 pub fn extensions(&self) -> &[&'static CStr] {
212 &self.extensions[..]
213 }
214 }
215
216 impl super::Instance {
217 pub fn shared_instance(&self) -> &super::InstanceShared {
218 &self.shared
219 }
220
221 fn enumerate_instance_extension_properties(
222 entry: &ash::Entry,
223 layer_name: Option<&CStr>,
224 ) -> Result<Vec<vk::ExtensionProperties>, crate::InstanceError> {
225 let instance_extensions = {
226 profiling::scope!("vkEnumerateInstanceExtensionProperties");
227 unsafe { entry.enumerate_instance_extension_properties(layer_name) }
228 };
229 instance_extensions.map_err(|e| {
230 crate::InstanceError::with_source(
231 String::from("enumerate_instance_extension_properties() failed"),
232 e,
233 )
234 })
235 }
236
237 /// Return the instance extension names wgpu would like to enable.
238 ///
239 /// Return a vector of the names of instance extensions actually available
240 /// on `entry` that wgpu would like to enable.
241 ///
242 /// The `instance_api_version` argument should be the instance's Vulkan API
243 /// version, as obtained from `vkEnumerateInstanceVersion`. This is the same
244 /// space of values as the `VK_API_VERSION` constants.
245 ///
246 /// Note that wgpu can function without many of these extensions (for
247 /// example, `VK_KHR_wayland_surface` is certainly not going to be available
248 /// everywhere), but if one of these extensions is available at all, wgpu
249 /// assumes that it has been enabled.
250 pub fn desired_extensions(
251 entry: &ash::Entry,
252 _instance_api_version: u32,
253 flags: wgt::InstanceFlags,
254 ) -> Result<Vec<&'static CStr>, crate::InstanceError> {
255 let instance_extensions = Self::enumerate_instance_extension_properties(entry, None)?;
256
257 // Check our extensions against the available extensions
258 let mut extensions: Vec<&'static CStr> = Vec::new();
259
260 // VK_KHR_surface
261 extensions.push(khr::surface::NAME);
262
263 // Platform-specific WSI extensions
264 if cfg!(all(
265 unix,
266 not(target_os = "android"),
267 not(target_os = "macos")
268 )) {
269 // VK_KHR_xlib_surface
270 extensions.push(khr::xlib_surface::NAME);
271 // VK_KHR_xcb_surface
272 extensions.push(khr::xcb_surface::NAME);
273 // VK_KHR_wayland_surface
274 extensions.push(khr::wayland_surface::NAME);
275 }
276 if cfg!(target_os = "android") {
277 // VK_KHR_android_surface
278 extensions.push(khr::android_surface::NAME);
279 }
280 if cfg!(target_os = "windows") {
281 // VK_KHR_win32_surface
282 extensions.push(khr::win32_surface::NAME);
283 }
284 if cfg!(target_os = "macos") {
285 // VK_EXT_metal_surface
286 extensions.push(ext::metal_surface::NAME);
287 extensions.push(khr::portability_enumeration::NAME);
288 }
289 if cfg!(all(
290 unix,
291 not(target_vendor = "apple"),
292 not(target_family = "wasm")
293 )) {
294 // VK_EXT_acquire_drm_display -> VK_EXT_direct_mode_display -> VK_KHR_display
295 extensions.push(ext::acquire_drm_display::NAME);
296 extensions.push(ext::direct_mode_display::NAME);
297 extensions.push(khr::display::NAME);
298 // VK_EXT_physical_device_drm -> VK_KHR_get_physical_device_properties2
299 extensions.push(ext::physical_device_drm::NAME);
300 extensions.push(khr::get_display_properties2::NAME);
301 }
302
303 if flags.contains(wgt::InstanceFlags::DEBUG) {
304 // VK_EXT_debug_utils
305 extensions.push(ext::debug_utils::NAME);
306 }
307
308 // VK_EXT_swapchain_colorspace
309 // Provides wide color gamut
310 extensions.push(ext::swapchain_colorspace::NAME);
311
312 // VK_KHR_get_physical_device_properties2
313 // Even though the extension was promoted to Vulkan 1.1, we still require the extension
314 // so that we don't have to conditionally use the functions provided by the 1.1 instance
315 extensions.push(khr::get_physical_device_properties2::NAME);
316
317 // Only keep available extensions.
318 extensions.retain(|&ext| {
319 if instance_extensions
320 .iter()
321 .any(|inst_ext| inst_ext.extension_name_as_c_str() == Ok(ext))
322 {
323 true
324 } else {
325 log::warn!("Unable to find extension: {}", ext.to_string_lossy());
326 false
327 }
328 });
329 Ok(extensions)
330 }
331
332 /// # Safety
333 ///
334 /// - `raw_instance` must be created from `entry`
335 /// - `raw_instance` must be created respecting `instance_api_version`, `extensions` and `flags`
336 /// - `extensions` must be a superset of `desired_extensions()` and must be created from the
337 /// same entry, `instance_api_version`` and flags.
338 /// - `android_sdk_version` is ignored and can be `0` for all platforms besides Android
339 /// - If `drop_callback` is [`None`], wgpu-hal will take ownership of `raw_instance`. If
340 /// `drop_callback` is [`Some`], `raw_instance` must be valid until the callback is called.
341 ///
342 /// If `debug_utils_user_data` is `Some`, then the validation layer is
343 /// available, so create a [`vk::DebugUtilsMessengerEXT`].
344 #[allow(clippy::too_many_arguments)]
345 pub unsafe fn from_raw(
346 entry: ash::Entry,
347 raw_instance: ash::Instance,
348 instance_api_version: u32,
349 android_sdk_version: u32,
350 debug_utils_create_info: Option<super::DebugUtilsCreateInfo>,
351 extensions: Vec<&'static CStr>,
352 flags: wgt::InstanceFlags,
353 memory_budget_thresholds: wgt::MemoryBudgetThresholds,
354 has_nv_optimus: bool,
355 drop_callback: Option<crate::DropCallback>,
356 ) -> Result<Self, crate::InstanceError> {
357 log::debug!("Instance version: 0x{:x}", instance_api_version);
358
359 let debug_utils = if let Some(debug_utils_create_info) = debug_utils_create_info {
360 if extensions.contains(&ext::debug_utils::NAME) {
361 log::info!("Enabling debug utils");
362
363 let extension = ext::debug_utils::Instance::new(&entry, &raw_instance);
364 let vk_info = debug_utils_create_info.to_vk_create_info();
365 let messenger =
366 unsafe { extension.create_debug_utils_messenger(&vk_info, None) }.unwrap();
367
368 Some(super::DebugUtils {
369 extension,
370 messenger,
371 callback_data: debug_utils_create_info.callback_data,
372 })
373 } else {
374 log::debug!("Debug utils not enabled: extension not listed");
375 None
376 }
377 } else {
378 log::debug!(
379 "Debug utils not enabled: \
380 debug_utils_user_data not passed to Instance::from_raw"
381 );
382 None
383 };
384
385 let get_physical_device_properties =
386 if extensions.contains(&khr::get_physical_device_properties2::NAME) {
387 log::debug!("Enabling device properties2");
388 Some(khr::get_physical_device_properties2::Instance::new(
389 &entry,
390 &raw_instance,
391 ))
392 } else {
393 None
394 };
395
396 let drop_guard = crate::DropGuard::from_option(drop_callback);
397
398 Ok(Self {
399 shared: Arc::new(super::InstanceShared {
400 raw: raw_instance,
401 extensions,
402 drop_guard,
403 flags,
404 memory_budget_thresholds,
405 debug_utils,
406 get_physical_device_properties,
407 entry,
408 has_nv_optimus,
409 instance_api_version,
410 android_sdk_version,
411 }),
412 })
413 }
414
415 fn create_surface_from_xlib(
416 &self,
417 dpy: *mut vk::Display,
418 window: vk::Window,
419 ) -> Result<super::Surface, crate::InstanceError> {
420 if !self.shared.extensions.contains(&khr::xlib_surface::NAME) {
421 return Err(crate::InstanceError::new(String::from(
422 "Vulkan driver does not support VK_KHR_xlib_surface",
423 )));
424 }
425
426 let surface = {
427 let xlib_loader =
428 khr::xlib_surface::Instance::new(&self.shared.entry, &self.shared.raw);
429 let info = vk::XlibSurfaceCreateInfoKHR::default()
430 .flags(vk::XlibSurfaceCreateFlagsKHR::empty())
431 .window(window)
432 .dpy(dpy);
433
434 unsafe { xlib_loader.create_xlib_surface(&info, None) }
435 .expect("XlibSurface::create_xlib_surface() failed")
436 };
437
438 Ok(self.create_surface_from_vk_surface_khr(surface))
439 }
440
441 fn create_surface_from_xcb(
442 &self,
443 connection: *mut vk::xcb_connection_t,
444 window: vk::xcb_window_t,
445 ) -> Result<super::Surface, crate::InstanceError> {
446 if !self.shared.extensions.contains(&khr::xcb_surface::NAME) {
447 return Err(crate::InstanceError::new(String::from(
448 "Vulkan driver does not support VK_KHR_xcb_surface",
449 )));
450 }
451
452 let surface = {
453 let xcb_loader = khr::xcb_surface::Instance::new(&self.shared.entry, &self.shared.raw);
454 let info = vk::XcbSurfaceCreateInfoKHR::default()
455 .flags(vk::XcbSurfaceCreateFlagsKHR::empty())
456 .window(window)
457 .connection(connection);
458
459 unsafe { xcb_loader.create_xcb_surface(&info, None) }
460 .expect("XcbSurface::create_xcb_surface() failed")
461 };
462
463 Ok(self.create_surface_from_vk_surface_khr(surface))
464 }
465
466 fn create_surface_from_wayland(
467 &self,
468 display: *mut vk::wl_display,
469 surface: *mut vk::wl_surface,
470 ) -> Result<super::Surface, crate::InstanceError> {
471 if !self.shared.extensions.contains(&khr::wayland_surface::NAME) {
472 return Err(crate::InstanceError::new(String::from(
473 "Vulkan driver does not support VK_KHR_wayland_surface",
474 )));
475 }
476
477 let surface = {
478 let w_loader =
479 khr::wayland_surface::Instance::new(&self.shared.entry, &self.shared.raw);
480 let info = vk::WaylandSurfaceCreateInfoKHR::default()
481 .flags(vk::WaylandSurfaceCreateFlagsKHR::empty())
482 .display(display)
483 .surface(surface);
484
485 unsafe { w_loader.create_wayland_surface(&info, None) }.expect("WaylandSurface failed")
486 };
487
488 Ok(self.create_surface_from_vk_surface_khr(surface))
489 }
490
491 fn create_surface_android(
492 &self,
493 window: *mut vk::ANativeWindow,
494 ) -> Result<super::Surface, crate::InstanceError> {
495 if !self.shared.extensions.contains(&khr::android_surface::NAME) {
496 return Err(crate::InstanceError::new(String::from(
497 "Vulkan driver does not support VK_KHR_android_surface",
498 )));
499 }
500
501 let surface = {
502 let a_loader =
503 khr::android_surface::Instance::new(&self.shared.entry, &self.shared.raw);
504 let info = vk::AndroidSurfaceCreateInfoKHR::default()
505 .flags(vk::AndroidSurfaceCreateFlagsKHR::empty())
506 .window(window);
507
508 unsafe { a_loader.create_android_surface(&info, None) }.expect("AndroidSurface failed")
509 };
510
511 Ok(self.create_surface_from_vk_surface_khr(surface))
512 }
513
514 fn create_surface_from_hwnd(
515 &self,
516 hinstance: vk::HINSTANCE,
517 hwnd: vk::HWND,
518 ) -> Result<super::Surface, crate::InstanceError> {
519 if !self.shared.extensions.contains(&khr::win32_surface::NAME) {
520 return Err(crate::InstanceError::new(String::from(
521 "Vulkan driver does not support VK_KHR_win32_surface",
522 )));
523 }
524
525 let surface = {
526 let info = vk::Win32SurfaceCreateInfoKHR::default()
527 .flags(vk::Win32SurfaceCreateFlagsKHR::empty())
528 .hinstance(hinstance)
529 .hwnd(hwnd);
530 let win32_loader =
531 khr::win32_surface::Instance::new(&self.shared.entry, &self.shared.raw);
532 unsafe {
533 win32_loader
534 .create_win32_surface(&info, None)
535 .expect("Unable to create Win32 surface")
536 }
537 };
538
539 Ok(self.create_surface_from_vk_surface_khr(surface))
540 }
541
542 #[cfg(metal)]
543 fn create_surface_from_view(
544 &self,
545 view: core::ptr::NonNull<c_void>,
546 ) -> Result<super::Surface, crate::InstanceError> {
547 if !self.shared.extensions.contains(&ext::metal_surface::NAME) {
548 return Err(crate::InstanceError::new(String::from(
549 "Vulkan driver does not support VK_EXT_metal_surface",
550 )));
551 }
552
553 let layer = unsafe { crate::metal::Surface::get_metal_layer(view.cast()) };
554 // NOTE: The layer is retained by Vulkan's `vkCreateMetalSurfaceEXT`,
555 // so no need to retain it beyond the scope of this function.
556 let layer_ptr = (*layer).cast();
557
558 let surface = {
559 let metal_loader =
560 ext::metal_surface::Instance::new(&self.shared.entry, &self.shared.raw);
561 let vk_info = vk::MetalSurfaceCreateInfoEXT::default()
562 .flags(vk::MetalSurfaceCreateFlagsEXT::empty())
563 .layer(layer_ptr);
564
565 unsafe { metal_loader.create_metal_surface(&vk_info, None).unwrap() }
566 };
567
568 Ok(self.create_surface_from_vk_surface_khr(surface))
569 }
570
571 pub(super) fn create_surface_from_vk_surface_khr(
572 &self,
573 surface: vk::SurfaceKHR,
574 ) -> super::Surface {
575 let functor = khr::surface::Instance::new(&self.shared.entry, &self.shared.raw);
576 super::Surface {
577 raw: surface,
578 functor,
579 instance: Arc::clone(&self.shared),
580 swapchain: RwLock::new(None),
581 }
582 }
583 }
584
585 impl Drop for super::InstanceShared {
586 fn drop(&mut self) {
587 unsafe {
588 // Keep du alive since destroy_instance may also log
589 let _du = self.debug_utils.take().inspect(|du| {
590 du.extension
591 .destroy_debug_utils_messenger(du.messenger, None);
592 });
593 if self.drop_guard.is_none() {
594 self.raw.destroy_instance(None);
595 }
596 }
597 }
598 }
599
600 impl crate::Instance for super::Instance {
601 type A = super::Api;
602
603 unsafe fn init(desc: &crate::InstanceDescriptor) -> Result<Self, crate::InstanceError> {
604 profiling::scope!("Init Vulkan Backend");
605
606 let entry = unsafe {
607 profiling::scope!("Load vk library");
608 ash::Entry::load()
609 }
610 .map_err(|err| {
611 crate::InstanceError::with_source(String::from("missing Vulkan entry points"), err)
612 })?;
613 let version = {
614 profiling::scope!("vkEnumerateInstanceVersion");
615 unsafe { entry.try_enumerate_instance_version() }
616 };
617 let instance_api_version = match version {
618 // Vulkan 1.1+
619 Ok(Some(version)) => version,
620 Ok(None) => vk::API_VERSION_1_0,
621 Err(err) => {
622 return Err(crate::InstanceError::with_source(
623 String::from("try_enumerate_instance_version() failed"),
624 err,
625 ));
626 }
627 };
628
629 let app_name = CString::new(desc.name).unwrap();
630 let app_info = vk::ApplicationInfo::default()
631 .application_name(app_name.as_c_str())
632 .application_version(1)
633 .engine_name(c"wgpu-hal")
634 .engine_version(2)
635 .api_version(
636 // Vulkan 1.0 doesn't like anything but 1.0 passed in here...
637 if instance_api_version < vk::API_VERSION_1_1 {
638 vk::API_VERSION_1_0
639 } else {
640 // This is the max Vulkan API version supported by `wgpu-hal`.
641 //
642 // If we want to increment this, there are some things that must be done first:
643 // - Audit the behavioral differences between the previous and new API versions.
644 // - Audit all extensions used by this backend:
645 // - If any were promoted in the new API version and the behavior has changed, we must handle the new behavior in addition to the old behavior.
646 // - If any were obsoleted in the new API version, we must implement a fallback for the new API version
647 // - If any are non-KHR-vendored, we must ensure the new behavior is still correct (since backwards-compatibility is not guaranteed).
648 vk::API_VERSION_1_3
649 },
650 );
651
652 let extensions = Self::desired_extensions(&entry, instance_api_version, desc.flags)?;
653
654 let instance_layers = {
655 profiling::scope!("vkEnumerateInstanceLayerProperties");
656 unsafe { entry.enumerate_instance_layer_properties() }
657 };
658 let instance_layers = instance_layers.map_err(|e| {
659 log::debug!("enumerate_instance_layer_properties: {:?}", e);
660 crate::InstanceError::with_source(
661 String::from("enumerate_instance_layer_properties() failed"),
662 e,
663 )
664 })?;
665
666 fn find_layer<'layers>(
667 instance_layers: &'layers [vk::LayerProperties],
668 name: &CStr,
669 ) -> Option<&'layers vk::LayerProperties> {
670 instance_layers
671 .iter()
672 .find(|inst_layer| inst_layer.layer_name_as_c_str() == Ok(name))
673 }
674
675 let validation_layer_name = c"VK_LAYER_KHRONOS_validation";
676 let validation_layer_properties = find_layer(&instance_layers, validation_layer_name);
677
678 // Determine if VK_EXT_validation_features is available, so we can enable
679 // GPU assisted validation and synchronization validation.
680 let validation_features_are_enabled = if validation_layer_properties.is_some() {
681 // Get the all the instance extension properties.
682 let exts =
683 Self::enumerate_instance_extension_properties(&entry, Some(validation_layer_name))?;
684 // Convert all the names of the extensions into an iterator of CStrs.
685 let mut ext_names = exts
686 .iter()
687 .filter_map(|ext| ext.extension_name_as_c_str().ok());
688 // Find the validation features extension.
689 ext_names.any(|ext_name| ext_name == ext::validation_features::NAME)
690 } else {
691 false
692 };
693
694 let should_enable_gpu_based_validation = desc
695 .flags
696 .intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION)
697 && validation_features_are_enabled;
698
699 let has_nv_optimus = find_layer(&instance_layers, c"VK_LAYER_NV_optimus").is_some();
700
701 let has_obs_layer = find_layer(&instance_layers, c"VK_LAYER_OBS_HOOK").is_some();
702
703 let mut layers: Vec<&'static CStr> = Vec::new();
704
705 let has_debug_extension = extensions.contains(&ext::debug_utils::NAME);
706 let mut debug_user_data = has_debug_extension.then(|| {
707 // Put the callback data on the heap, to ensure it will never be
708 // moved.
709 Box::new(super::DebugUtilsMessengerUserData {
710 validation_layer_properties: None,
711 has_obs_layer,
712 })
713 });
714
715 // Request validation layer if asked.
716 if desc.flags.intersects(wgt::InstanceFlags::VALIDATION)
717 || should_enable_gpu_based_validation
718 {
719 if let Some(layer_properties) = validation_layer_properties {
720 layers.push(validation_layer_name);
721
722 if let Some(debug_user_data) = debug_user_data.as_mut() {
723 debug_user_data.validation_layer_properties =
724 Some(super::ValidationLayerProperties {
725 layer_description: layer_properties
726 .description_as_c_str()
727 .unwrap()
728 .to_owned(),
729 layer_spec_version: layer_properties.spec_version,
730 });
731 }
732 } else {
733 log::warn!(
734 "InstanceFlags::VALIDATION requested, but unable to find layer: {}",
735 validation_layer_name.to_string_lossy()
736 );
737 }
738 }
739 let mut debug_utils = if let Some(callback_data) = debug_user_data {
740 // having ERROR unconditionally because Vk doesn't like empty flags
741 let mut severity = vk::DebugUtilsMessageSeverityFlagsEXT::ERROR;
742 if log::max_level() >= log::LevelFilter::Debug {
743 severity |= vk::DebugUtilsMessageSeverityFlagsEXT::VERBOSE;
744 }
745 if log::max_level() >= log::LevelFilter::Info {
746 severity |= vk::DebugUtilsMessageSeverityFlagsEXT::INFO;
747 }
748 if log::max_level() >= log::LevelFilter::Warn {
749 severity |= vk::DebugUtilsMessageSeverityFlagsEXT::WARNING;
750 }
751
752 let message_type = vk::DebugUtilsMessageTypeFlagsEXT::GENERAL
753 | vk::DebugUtilsMessageTypeFlagsEXT::VALIDATION
754 | vk::DebugUtilsMessageTypeFlagsEXT::PERFORMANCE;
755
756 let create_info = super::DebugUtilsCreateInfo {
757 severity,
758 message_type,
759 callback_data,
760 };
761
762 Some(create_info)
763 } else {
764 None
765 };
766
767 #[cfg(target_os = "android")]
768 let android_sdk_version = {
769 let properties = android_system_properties::AndroidSystemProperties::new();
770 // See: https://developer.android.com/reference/android/os/Build.VERSION_CODES
771 if let Some(val) = properties.get("ro.build.version.sdk") {
772 match val.parse::<u32>() {
773 Ok(sdk_ver) => sdk_ver,
774 Err(err) => {
775 log::error!(
776 concat!(
777 "Couldn't parse Android's ",
778 "ro.build.version.sdk system property ({}): {}",
779 ),
780 val,
781 err,
782 );
783 0
784 }
785 }
786 } else {
787 log::error!("Couldn't read Android's ro.build.version.sdk system property");
788 0
789 }
790 };
791 #[cfg(not(target_os = "android"))]
792 let android_sdk_version = 0;
793
794 let mut flags = vk::InstanceCreateFlags::empty();
795
796 // Avoid VUID-VkInstanceCreateInfo-flags-06559: Only ask the instance to
797 // enumerate incomplete Vulkan implementations (which we need on Mac) if
798 // we managed to find the extension that provides the flag.
799 if extensions.contains(&khr::portability_enumeration::NAME) {
800 flags |= vk::InstanceCreateFlags::ENUMERATE_PORTABILITY_KHR;
801 }
802 let vk_instance = {
803 let str_pointers = layers
804 .iter()
805 .chain(extensions.iter())
806 .map(|&s: &&'static _| {
807 // Safe because `layers` and `extensions` entries have static lifetime.
808 s.as_ptr()
809 })
810 .collect::<Vec<_>>();
811
812 let mut create_info = vk::InstanceCreateInfo::default()
813 .flags(flags)
814 .application_info(&app_info)
815 .enabled_layer_names(&str_pointers[..layers.len()])
816 .enabled_extension_names(&str_pointers[layers.len()..]);
817
818 let mut debug_utils_create_info = debug_utils
819 .as_mut()
820 .map(|create_info| create_info.to_vk_create_info());
821 if let Some(debug_utils_create_info) = debug_utils_create_info.as_mut() {
822 create_info = create_info.push_next(debug_utils_create_info);
823 }
824
825 // Enable explicit validation features if available
826 let mut validation_features;
827 let mut validation_feature_list: ArrayVec<_, 3>;
828 if validation_features_are_enabled {
829 validation_feature_list = ArrayVec::new();
830
831 // Always enable synchronization validation
832 validation_feature_list
833 .push(vk::ValidationFeatureEnableEXT::SYNCHRONIZATION_VALIDATION);
834
835 // Only enable GPU assisted validation if requested.
836 if should_enable_gpu_based_validation {
837 validation_feature_list.push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED);
838 validation_feature_list
839 .push(vk::ValidationFeatureEnableEXT::GPU_ASSISTED_RESERVE_BINDING_SLOT);
840 }
841
842 validation_features = vk::ValidationFeaturesEXT::default()
843 .enabled_validation_features(&validation_feature_list);
844 create_info = create_info.push_next(&mut validation_features);
845 }
846
847 unsafe {
848 profiling::scope!("vkCreateInstance");
849 entry.create_instance(&create_info, None)
850 }
851 .map_err(|e| {
852 crate::InstanceError::with_source(
853 String::from("Entry::create_instance() failed"),
854 e,
855 )
856 })?
857 };
858
859 unsafe {
860 Self::from_raw(
861 entry,
862 vk_instance,
863 instance_api_version,
864 android_sdk_version,
865 debug_utils,
866 extensions,
867 desc.flags,
868 desc.memory_budget_thresholds,
869 has_nv_optimus,
870 None,
871 )
872 }
873 }
874
875 unsafe fn create_surface(
876 &self,
877 display_handle: raw_window_handle::RawDisplayHandle,
878 window_handle: raw_window_handle::RawWindowHandle,
879 ) -> Result<super::Surface, crate::InstanceError> {
880 use raw_window_handle::{RawDisplayHandle as Rdh, RawWindowHandle as Rwh};
881
882 // TODO: Replace with ash-window, which also lazy-loads the extension based on handle type
883
884 match (window_handle, display_handle) {
885 (Rwh::Wayland(handle), Rdh::Wayland(display)) => {
886 self.create_surface_from_wayland(display.display.as_ptr(), handle.surface.as_ptr())
887 }
888 (Rwh::Xlib(handle), Rdh::Xlib(display)) => {
889 let display = display.display.expect("Display pointer is not set.");
890 self.create_surface_from_xlib(display.as_ptr(), handle.window)
891 }
892 (Rwh::Xcb(handle), Rdh::Xcb(display)) => {
893 let connection = display.connection.expect("Pointer to X-Server is not set.");
894 self.create_surface_from_xcb(connection.as_ptr(), handle.window.get())
895 }
896 (Rwh::AndroidNdk(handle), _) => {
897 self.create_surface_android(handle.a_native_window.as_ptr())
898 }
899 (Rwh::Win32(handle), _) => {
900 let hinstance = handle.hinstance.ok_or_else(|| {
901 crate::InstanceError::new(String::from(
902 "Vulkan requires raw-window-handle's Win32::hinstance to be set",
903 ))
904 })?;
905 self.create_surface_from_hwnd(hinstance.get(), handle.hwnd.get())
906 }
907 #[cfg(all(target_os = "macos", feature = "metal"))]
908 (Rwh::AppKit(handle), _)
909 if self.shared.extensions.contains(&ext::metal_surface::NAME) =>
910 {
911 self.create_surface_from_view(handle.ns_view)
912 }
913 #[cfg(all(any(target_os = "ios", target_os = "visionos"), feature = "metal"))]
914 (Rwh::UiKit(handle), _)
915 if self.shared.extensions.contains(&ext::metal_surface::NAME) =>
916 {
917 self.create_surface_from_view(handle.ui_view)
918 }
919 (_, _) => Err(crate::InstanceError::new(format!(
920 "window handle {window_handle:?} is not a Vulkan-compatible handle"
921 ))),
922 }
923 }
924
925 unsafe fn enumerate_adapters(
926 &self,
927 _surface_hint: Option<&super::Surface>,
928 ) -> Vec<crate::ExposedAdapter<super::Api>> {
929 use crate::auxil::db;
930
931 let raw_devices = match unsafe { self.shared.raw.enumerate_physical_devices() } {
932 Ok(devices) => devices,
933 Err(err) => {
934 log::error!("enumerate_adapters: {}", err);
935 Vec::new()
936 }
937 };
938
939 let mut exposed_adapters = raw_devices
940 .into_iter()
941 .flat_map(|device| self.expose_adapter(device))
942 .collect::<Vec<_>>();
943
944 // Detect if it's an Intel + NVidia configuration with Optimus
945 let has_nvidia_dgpu = exposed_adapters.iter().any(|exposed| {
946 exposed.info.device_type == wgt::DeviceType::DiscreteGpu
947 && exposed.info.vendor == db::nvidia::VENDOR
948 });
949 if cfg!(target_os = "linux") && has_nvidia_dgpu && self.shared.has_nv_optimus {
950 for exposed in exposed_adapters.iter_mut() {
951 if exposed.info.device_type == wgt::DeviceType::IntegratedGpu
952 && exposed.info.vendor == db::intel::VENDOR
953 {
954 // Check if mesa driver and version less than 21.2
955 if let Some(version) = exposed.info.driver_info.split_once("Mesa ").map(|s| {
956 let mut components = s.1.split('.');
957 let major = components.next().and_then(|s| u8::from_str(s).ok());
958 let minor = components.next().and_then(|s| u8::from_str(s).ok());
959 if let (Some(major), Some(minor)) = (major, minor) {
960 (major, minor)
961 } else {
962 (0, 0)
963 }
964 }) {
965 if version < (21, 2) {
966 // See https://gitlab.freedesktop.org/mesa/mesa/-/issues/4688
967 log::warn!(
968 concat!(
969 "Disabling presentation on '{}' (id {:?}) ",
970 "due to NV Optimus and Intel Mesa < v21.2"
971 ),
972 exposed.info.name,
973 exposed.adapter.raw
974 );
975 exposed.adapter.private_caps.can_present = false;
976 }
977 }
978 }
979 }
980 }
981
982 exposed_adapters
983 }
984 }
985
986 impl Drop for super::Surface {
987 fn drop(&mut self) {
988 unsafe { self.functor.destroy_surface(self.raw, None) };
989 }
990 }
991
992 impl crate::Surface for super::Surface {
993 type A = super::Api;
994
995 unsafe fn configure(
996 &self,
997 device: &super::Device,
998 config: &crate::SurfaceConfiguration,
999 ) -> Result<(), crate::SurfaceError> {
1000 // SAFETY: `configure`'s contract guarantees there are no resources derived from the swapchain in use.
1001 let mut swap_chain = self.swapchain.write();
1002 let old = swap_chain
1003 .take()
1004 .map(|sc| unsafe { sc.release_resources(&device.shared.raw) });
1005
1006 let swapchain = unsafe { device.create_swapchain(self, config, old)? };
1007 *swap_chain = Some(swapchain);
1008
1009 Ok(())
1010 }
1011
1012 unsafe fn unconfigure(&self, device: &super::Device) {
1013 if let Some(sc) = self.swapchain.write().take() {
1014 // SAFETY: `unconfigure`'s contract guarantees there are no resources derived from the swapchain in use.
1015 let swapchain = unsafe { sc.release_resources(&device.shared.raw) };
1016 unsafe { swapchain.functor.destroy_swapchain(swapchain.raw, None) };
1017 }
1018 }
1019
1020 unsafe fn acquire_texture(
1021 &self,
1022 timeout: Option<core::time::Duration>,
1023 fence: &super::Fence,
1024 ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
1025 let mut swapchain = self.swapchain.write();
1026 let swapchain = swapchain.as_mut().unwrap();
1027
1028 let mut timeout_ns = match timeout {
1029 Some(duration) => duration.as_nanos() as u64,
1030 None => u64::MAX,
1031 };
1032
1033 // AcquireNextImageKHR on Android (prior to Android 11) doesn't support timeouts
1034 // and will also log verbose warnings if tying to use a timeout.
1035 //
1036 // Android 10 implementation for reference:
1037 // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-10.0.0_r13/vulkan/libvulkan/swapchain.cpp#1426
1038 // Android 11 implementation for reference:
1039 // https://android.googlesource.com/platform/frameworks/native/+/refs/tags/android-mainline-11.0.0_r45/vulkan/libvulkan/swapchain.cpp#1438
1040 //
1041 // Android 11 corresponds to an SDK_INT/ro.build.version.sdk of 30
1042 if cfg!(target_os = "android") && self.instance.android_sdk_version < 30 {
1043 timeout_ns = u64::MAX;
1044 }
1045
1046 let swapchain_semaphores_arc = swapchain.get_surface_semaphores();
1047 // Nothing should be using this, so we don't block, but panic if we fail to lock.
1048 let locked_swapchain_semaphores = swapchain_semaphores_arc
1049 .try_lock()
1050 .expect("Failed to lock a SwapchainSemaphores.");
1051
1052 // Wait for all commands writing to the previously acquired image to
1053 // complete.
1054 //
1055 // Almost all the steps in the usual acquire-draw-present flow are
1056 // asynchronous: they get something started on the presentation engine
1057 // or the GPU, but on the CPU, control returns immediately. Without some
1058 // sort of intervention, the CPU could crank out frames much faster than
1059 // the presentation engine can display them.
1060 //
1061 // This is the intervention: if any submissions drew on this image, and
1062 // thus waited for `locked_swapchain_semaphores.acquire`, wait for all
1063 // of them to finish, thus ensuring that it's okay to pass `acquire` to
1064 // `vkAcquireNextImageKHR` again.
1065 swapchain.device.wait_for_fence(
1066 fence,
1067 locked_swapchain_semaphores.previously_used_submission_index,
1068 timeout_ns,
1069 )?;
1070
1071 // will block if no image is available
1072 let (index, suboptimal) = match unsafe {
1073 profiling::scope!("vkAcquireNextImageKHR");
1074 swapchain.functor.acquire_next_image(
1075 swapchain.raw,
1076 timeout_ns,
1077 locked_swapchain_semaphores.acquire,
1078 vk::Fence::null(),
1079 )
1080 } {
1081 // We treat `VK_SUBOPTIMAL_KHR` as `VK_SUCCESS` on Android.
1082 // See the comment in `Queue::present`.
1083 #[cfg(target_os = "android")]
1084 Ok((index, _)) => (index, false),
1085 #[cfg(not(target_os = "android"))]
1086 Ok(pair) => pair,
1087 Err(error) => {
1088 return match error {
1089 vk::Result::TIMEOUT => Ok(None),
1090 vk::Result::NOT_READY | vk::Result::ERROR_OUT_OF_DATE_KHR => {
1091 Err(crate::SurfaceError::Outdated)
1092 }
1093 vk::Result::ERROR_SURFACE_LOST_KHR => Err(crate::SurfaceError::Lost),
1094 // We don't use VK_EXT_full_screen_exclusive
1095 // VK_ERROR_FULL_SCREEN_EXCLUSIVE_MODE_LOST_EXT
1096 other => Err(super::map_host_device_oom_and_lost_err(other).into()),
1097 };
1098 }
1099 };
1100
1101 drop(locked_swapchain_semaphores);
1102 // We only advance the surface semaphores if we successfully acquired an image, otherwise
1103 // we should try to re-acquire using the same semaphores.
1104 swapchain.advance_surface_semaphores();
1105
1106 // special case for Intel Vulkan returning bizarre values (ugh)
1107 if swapchain.device.vendor_id == crate::auxil::db::intel::VENDOR && index > 0x100 {
1108 return Err(crate::SurfaceError::Outdated);
1109 }
1110
1111 let texture = super::SurfaceTexture {
1112 index,
1113 texture: super::Texture {
1114 raw: swapchain.images[index as usize],
1115 drop_guard: None,
1116 block: None,
1117 external_memory: None,
1118 format: swapchain.config.format,
1119 copy_size: crate::CopyExtent {
1120 width: swapchain.config.extent.width,
1121 height: swapchain.config.extent.height,
1122 depth: 1,
1123 },
1124 },
1125 surface_semaphores: swapchain_semaphores_arc,
1126 };
1127 Ok(Some(crate::AcquiredSurfaceTexture {
1128 texture,
1129 suboptimal,
1130 }))
1131 }
1132
1133 unsafe fn discard_texture(&self, _texture: super::SurfaceTexture) {}
1134 }