use crate::{
device::{physical::PhysicalDevice, Device, DeviceOwned, Queue},
instance::InstanceOwnedDebugWrapper,
macros::{impl_id_counter, vulkan_bitflags, vulkan_bitflags_enum},
Requires, RequiresAllOf, RequiresOneOf, Validated, ValidationError, Version, VulkanError,
VulkanObject,
};
use parking_lot::{Mutex, MutexGuard};
use std::{
fs::File,
mem::MaybeUninit,
num::NonZeroU64,
ptr,
sync::{Arc, Weak},
};
#[derive(Debug)]
pub struct Semaphore {
handle: ash::vk::Semaphore,
device: InstanceOwnedDebugWrapper<Arc<Device>>,
id: NonZeroU64,
export_handle_types: ExternalSemaphoreHandleTypes,
must_put_in_pool: bool,
state: Mutex<SemaphoreState>,
}
impl Semaphore {
#[inline]
pub fn new(
device: Arc<Device>,
create_info: SemaphoreCreateInfo,
) -> Result<Semaphore, Validated<VulkanError>> {
Self::validate_new(&device, &create_info)?;
unsafe { Ok(Self::new_unchecked(device, create_info)?) }
}
fn validate_new(
device: &Device,
create_info: &SemaphoreCreateInfo,
) -> Result<(), Box<ValidationError>> {
create_info
.validate(device)
.map_err(|err| err.add_context("create_info"))?;
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
pub unsafe fn new_unchecked(
device: Arc<Device>,
create_info: SemaphoreCreateInfo,
) -> Result<Semaphore, VulkanError> {
let SemaphoreCreateInfo {
export_handle_types,
_ne: _,
} = create_info;
let mut create_info_vk = ash::vk::SemaphoreCreateInfo {
flags: ash::vk::SemaphoreCreateFlags::empty(),
..Default::default()
};
let mut export_semaphore_create_info_vk = None;
if !export_handle_types.is_empty() {
let _ = export_semaphore_create_info_vk.insert(ash::vk::ExportSemaphoreCreateInfo {
handle_types: export_handle_types.into(),
..Default::default()
});
};
if let Some(info) = export_semaphore_create_info_vk.as_mut() {
info.p_next = create_info_vk.p_next;
create_info_vk.p_next = info as *const _ as *const _;
}
let handle = {
let fns = device.fns();
let mut output = MaybeUninit::uninit();
(fns.v1_0.create_semaphore)(
device.handle(),
&create_info_vk,
ptr::null(),
output.as_mut_ptr(),
)
.result()
.map_err(VulkanError::from)?;
output.assume_init()
};
Ok(Self::from_handle(device, handle, create_info))
}
#[inline]
pub fn from_pool(device: Arc<Device>) -> Result<Semaphore, VulkanError> {
let handle = device.semaphore_pool().lock().pop();
let semaphore = match handle {
Some(handle) => Semaphore {
handle,
device: InstanceOwnedDebugWrapper(device),
id: Self::next_id(),
export_handle_types: ExternalSemaphoreHandleTypes::empty(),
must_put_in_pool: true,
state: Mutex::new(Default::default()),
},
None => {
let mut semaphore =
unsafe { Semaphore::new_unchecked(device, Default::default())? };
semaphore.must_put_in_pool = true;
semaphore
}
};
Ok(semaphore)
}
#[inline]
pub unsafe fn from_handle(
device: Arc<Device>,
handle: ash::vk::Semaphore,
create_info: SemaphoreCreateInfo,
) -> Semaphore {
let SemaphoreCreateInfo {
export_handle_types,
_ne: _,
} = create_info;
Semaphore {
handle,
device: InstanceOwnedDebugWrapper(device),
id: Self::next_id(),
export_handle_types,
must_put_in_pool: false,
state: Mutex::new(Default::default()),
}
}
#[inline]
pub fn export_handle_types(&self) -> ExternalSemaphoreHandleTypes {
self.export_handle_types
}
#[inline]
pub fn export_fd(
&self,
handle_type: ExternalSemaphoreHandleType,
) -> Result<File, Validated<VulkanError>> {
let mut state = self.state.lock();
self.validate_export_fd(handle_type, &state)?;
unsafe { Ok(self.export_fd_unchecked_locked(handle_type, &mut state)?) }
}
fn validate_export_fd(
&self,
handle_type: ExternalSemaphoreHandleType,
state: &SemaphoreState,
) -> Result<(), Box<ValidationError>> {
if !self.device.enabled_extensions().khr_external_semaphore_fd {
return Err(Box::new(ValidationError {
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
"khr_external_semaphore_fd",
)])]),
..Default::default()
}));
}
handle_type.validate_device(&self.device).map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkSemaphoreGetFdInfoKHR-handleType-parameter"])
})?;
if !matches!(
handle_type,
ExternalSemaphoreHandleType::OpaqueFd | ExternalSemaphoreHandleType::SyncFd
) {
return Err(Box::new(ValidationError {
context: "handle_type".into(),
problem: "is not `ExternalSemaphoreHandleType::OpaqueFd` or \
`ExternalSemaphoreHandleType::SyncFd`"
.into(),
vuids: &["VUID-VkSemaphoreGetFdInfoKHR-handleType-01136"],
..Default::default()
}));
}
if !self.export_handle_types.intersects(handle_type.into()) {
return Err(Box::new(ValidationError {
problem: "`self.export_handle_types()` does not contain `handle_type`".into(),
vuids: &["VUID-VkSemaphoreGetFdInfoKHR-handleType-01132"],
..Default::default()
}));
}
if let Some(imported_handle_type) = state.current_import {
match imported_handle_type {
ImportType::SwapchainAcquire => {
return Err(Box::new(ValidationError {
problem: "the semaphore currently has an imported payload from a \
swapchain acquire operation"
.into(),
vuids: &["VUID-VkSemaphoreGetFdInfoKHR-semaphore-01133"],
..Default::default()
}));
}
ImportType::ExternalSemaphore(imported_handle_type) => {
let external_semaphore_properties = unsafe {
self.device
.physical_device()
.external_semaphore_properties_unchecked(
ExternalSemaphoreInfo::handle_type(handle_type),
)
};
if !external_semaphore_properties
.export_from_imported_handle_types
.intersects(imported_handle_type.into())
{
return Err(Box::new(ValidationError {
problem: "the semaphore currently has an imported payload, whose type \
does not allow re-exporting as `handle_type`, as \
returned by `PhysicalDevice::external_semaphore_properties`"
.into(),
vuids: &["VUID-VkSemaphoreGetFdInfoKHR-semaphore-01133"],
..Default::default()
}));
}
}
}
}
if handle_type.has_copy_transference() {
if state.is_wait_pending() {
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
a wait operation on the semaphore is pending"
.into(),
vuids: &["VUID-VkSemaphoreGetFdInfoKHR-handleType-01134"],
..Default::default()
}));
}
if !(state.is_signaled().unwrap_or(false) || state.is_signal_pending()) {
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
the semaphore is not signaled, and \
a signal operation on the semaphore is not pending"
.into(),
vuids: &[
"VUID-VkSemaphoreGetFdInfoKHR-handleType-01135",
"VUID-VkSemaphoreGetFdInfoKHR-handleType-03254",
],
..Default::default()
}));
}
}
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
#[inline]
pub unsafe fn export_fd_unchecked(
&self,
handle_type: ExternalSemaphoreHandleType,
) -> Result<File, VulkanError> {
let mut state = self.state.lock();
self.export_fd_unchecked_locked(handle_type, &mut state)
}
unsafe fn export_fd_unchecked_locked(
&self,
handle_type: ExternalSemaphoreHandleType,
state: &mut SemaphoreState,
) -> Result<File, VulkanError> {
let info_vk = ash::vk::SemaphoreGetFdInfoKHR {
semaphore: self.handle,
handle_type: handle_type.into(),
..Default::default()
};
let mut output = MaybeUninit::uninit();
let fns = self.device.fns();
(fns.khr_external_semaphore_fd.get_semaphore_fd_khr)(
self.device.handle(),
&info_vk,
output.as_mut_ptr(),
)
.result()
.map_err(VulkanError::from)?;
state.export(handle_type);
#[cfg(unix)]
{
use std::os::unix::io::FromRawFd;
Ok(File::from_raw_fd(output.assume_init()))
}
#[cfg(not(unix))]
{
let _ = output;
unreachable!("`khr_external_semaphore_fd` was somehow enabled on a non-Unix system");
}
}
#[inline]
pub fn export_win32_handle(
&self,
handle_type: ExternalSemaphoreHandleType,
) -> Result<*mut std::ffi::c_void, Validated<VulkanError>> {
let mut state = self.state.lock();
self.validate_export_win32_handle(handle_type, &state)?;
unsafe { Ok(self.export_win32_handle_unchecked_locked(handle_type, &mut state)?) }
}
fn validate_export_win32_handle(
&self,
handle_type: ExternalSemaphoreHandleType,
state: &SemaphoreState,
) -> Result<(), Box<ValidationError>> {
if !self
.device
.enabled_extensions()
.khr_external_semaphore_win32
{
return Err(Box::new(ValidationError {
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
"khr_external_semaphore_win32",
)])]),
..Default::default()
}));
}
handle_type.validate_device(&self.device).map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-parameter"])
})?;
if !matches!(
handle_type,
ExternalSemaphoreHandleType::OpaqueWin32
| ExternalSemaphoreHandleType::OpaqueWin32Kmt
| ExternalSemaphoreHandleType::D3D12Fence
) {
return Err(Box::new(ValidationError {
context: "handle_type".into(),
problem: "is not `ExternalSemaphoreHandleType::OpaqueWin32`, \
`ExternalSemaphoreHandleType::OpaqueWin32Kmt` or \
`ExternalSemaphoreHandleType::D3D12Fence`"
.into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01131"],
..Default::default()
}));
}
if !self.export_handle_types.intersects(handle_type.into()) {
return Err(Box::new(ValidationError {
problem: "`self.export_handle_types()` does not contain `handle_type`".into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01126"],
..Default::default()
}));
}
if matches!(
handle_type,
ExternalSemaphoreHandleType::OpaqueWin32 | ExternalSemaphoreHandleType::D3D12Fence
) && state.is_exported(handle_type)
{
return Err(Box::new(ValidationError {
problem: "`handle_type` is `ExternalSemaphoreHandleType::OpaqueWin32` or \
`ExternalSemaphoreHandleType::D3D12Fence`, but \
a handle of this type has already been exported from this semaphore"
.into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01127"],
..Default::default()
}));
}
if let Some(imported_handle_type) = state.current_import {
match imported_handle_type {
ImportType::SwapchainAcquire => {
return Err(Box::new(ValidationError {
problem: "the semaphore currently has an imported payload from a \
swapchain acquire operation"
.into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-semaphore-01128"],
..Default::default()
}));
}
ImportType::ExternalSemaphore(imported_handle_type) => {
let external_semaphore_properties = unsafe {
self.device
.physical_device()
.external_semaphore_properties_unchecked(
ExternalSemaphoreInfo::handle_type(handle_type),
)
};
if !external_semaphore_properties
.export_from_imported_handle_types
.intersects(imported_handle_type.into())
{
return Err(Box::new(ValidationError {
problem: "the semaphore currently has an imported payload, whose type \
does not allow re-exporting as `handle_type`, as \
returned by `PhysicalDevice::external_semaphore_properties`"
.into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-semaphore-01128"],
..Default::default()
}));
}
}
}
}
if handle_type.has_copy_transference() {
if state.is_wait_pending() {
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
a wait operation on the semaphore is pending"
.into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01129"],
..Default::default()
}));
}
if !(state.is_signaled().unwrap_or(false) || state.is_signal_pending()) {
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
the semaphore is not signaled, and \
a signal operation on the semaphore is not pending"
.into(),
vuids: &["VUID-VkSemaphoreGetWin32HandleInfoKHR-handleType-01130"],
..Default::default()
}));
}
}
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
#[inline]
pub unsafe fn export_win32_handle_unchecked(
&self,
handle_type: ExternalSemaphoreHandleType,
) -> Result<*mut std::ffi::c_void, VulkanError> {
let mut state = self.state.lock();
self.export_win32_handle_unchecked_locked(handle_type, &mut state)
}
unsafe fn export_win32_handle_unchecked_locked(
&self,
handle_type: ExternalSemaphoreHandleType,
state: &mut SemaphoreState,
) -> Result<*mut std::ffi::c_void, VulkanError> {
let info_vk = ash::vk::SemaphoreGetWin32HandleInfoKHR {
semaphore: self.handle,
handle_type: handle_type.into(),
..Default::default()
};
let mut output = MaybeUninit::uninit();
let fns = self.device.fns();
(fns.khr_external_semaphore_win32
.get_semaphore_win32_handle_khr)(
self.device.handle(), &info_vk, output.as_mut_ptr()
)
.result()
.map_err(VulkanError::from)?;
state.export(handle_type);
Ok(output.assume_init())
}
#[inline]
pub fn export_zircon_handle(
&self,
handle_type: ExternalSemaphoreHandleType,
) -> Result<ash::vk::zx_handle_t, Validated<VulkanError>> {
let mut state = self.state.lock();
self.validate_export_zircon_handle(handle_type, &state)?;
unsafe { Ok(self.export_zircon_handle_unchecked_locked(handle_type, &mut state)?) }
}
fn validate_export_zircon_handle(
&self,
handle_type: ExternalSemaphoreHandleType,
state: &SemaphoreState,
) -> Result<(), Box<ValidationError>> {
if !self.device.enabled_extensions().fuchsia_external_semaphore {
return Err(Box::new(ValidationError {
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
"fuchsia_external_semaphore",
)])]),
..Default::default()
}));
}
handle_type.validate_device(&self.device).map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-handleType-parameter"])
})?;
if !matches!(handle_type, ExternalSemaphoreHandleType::ZirconEvent) {
return Err(Box::new(ValidationError {
context: "handle_type".into(),
problem: "is not `ExternalSemaphoreHandleType::ZirconEvent`".into(),
vuids: &["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-handleType-04762"],
..Default::default()
}));
}
if !self.export_handle_types.intersects(handle_type.into()) {
return Err(Box::new(ValidationError {
problem: "`self.export_handle_types()` does not contain `handle_type`".into(),
vuids: &["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-handleType-04758"],
..Default::default()
}));
}
if let Some(imported_handle_type) = state.current_import {
match imported_handle_type {
ImportType::SwapchainAcquire => {
return Err(Box::new(ValidationError {
problem: "the semaphore currently has an imported payload from a \
swapchain acquire operation"
.into(),
vuids: &["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-semaphore-04759"],
..Default::default()
}));
}
ImportType::ExternalSemaphore(imported_handle_type) => {
let external_semaphore_properties = unsafe {
self.device
.physical_device()
.external_semaphore_properties_unchecked(
ExternalSemaphoreInfo::handle_type(handle_type),
)
};
if !external_semaphore_properties
.export_from_imported_handle_types
.intersects(imported_handle_type.into())
{
return Err(Box::new(ValidationError {
problem: "the semaphore currently has an imported payload, whose type \
does not allow re-exporting as `handle_type`, as \
returned by `PhysicalDevice::external_semaphore_properties`"
.into(),
vuids: &["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-semaphore-04759"],
..Default::default()
}));
}
}
}
}
if handle_type.has_copy_transference() {
if state.is_wait_pending() {
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
a wait operation on the semaphore is pending"
.into(),
vuids: &["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-handleType-04760"],
..Default::default()
}));
}
if !(state.is_signaled().unwrap_or(false) || state.is_signal_pending()) {
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
the semaphore is not signaled, and \
a signal operation on the semaphore is not pending"
.into(),
vuids: &["VUID-VkSemaphoreGetZirconHandleInfoFUCHSIA-handleType-04761"],
..Default::default()
}));
}
}
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
#[inline]
pub unsafe fn export_zircon_handle_unchecked(
&self,
handle_type: ExternalSemaphoreHandleType,
) -> Result<ash::vk::zx_handle_t, VulkanError> {
let mut state = self.state.lock();
self.export_zircon_handle_unchecked_locked(handle_type, &mut state)
}
unsafe fn export_zircon_handle_unchecked_locked(
&self,
handle_type: ExternalSemaphoreHandleType,
state: &mut SemaphoreState,
) -> Result<ash::vk::zx_handle_t, VulkanError> {
let info_vk = ash::vk::SemaphoreGetZirconHandleInfoFUCHSIA {
semaphore: self.handle,
handle_type: handle_type.into(),
..Default::default()
};
let mut output = MaybeUninit::uninit();
let fns = self.device.fns();
(fns.fuchsia_external_semaphore
.get_semaphore_zircon_handle_fuchsia)(
self.device.handle(),
&info_vk,
output.as_mut_ptr(),
)
.result()
.map_err(VulkanError::from)?;
state.export(handle_type);
Ok(output.assume_init())
}
#[inline]
pub unsafe fn import_fd(
&self,
import_semaphore_fd_info: ImportSemaphoreFdInfo,
) -> Result<(), Validated<VulkanError>> {
let mut state = self.state.lock();
self.validate_import_fd(&import_semaphore_fd_info, &state)?;
Ok(self.import_fd_unchecked_locked(import_semaphore_fd_info, &mut state)?)
}
fn validate_import_fd(
&self,
import_semaphore_fd_info: &ImportSemaphoreFdInfo,
state: &SemaphoreState,
) -> Result<(), Box<ValidationError>> {
if !self.device.enabled_extensions().khr_external_semaphore_fd {
return Err(Box::new(ValidationError {
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
"khr_external_semaphore_fd",
)])]),
..Default::default()
}));
}
if state.is_in_queue() {
return Err(Box::new(ValidationError {
problem: "the semaphore is in use".into(),
vuids: &["VUID-vkImportSemaphoreFdKHR-semaphore-01142"],
..Default::default()
}));
}
import_semaphore_fd_info
.validate(&self.device)
.map_err(|err| err.add_context("import_semaphore_fd_info"))?;
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
#[inline]
pub unsafe fn import_fd_unchecked(
&self,
import_semaphore_fd_info: ImportSemaphoreFdInfo,
) -> Result<(), VulkanError> {
let mut state = self.state.lock();
self.import_fd_unchecked_locked(import_semaphore_fd_info, &mut state)
}
unsafe fn import_fd_unchecked_locked(
&self,
import_semaphore_fd_info: ImportSemaphoreFdInfo,
state: &mut SemaphoreState,
) -> Result<(), VulkanError> {
let ImportSemaphoreFdInfo {
flags,
handle_type,
file,
_ne: _,
} = import_semaphore_fd_info;
#[cfg(unix)]
let fd = {
use std::os::fd::IntoRawFd;
file.map_or(-1, |file| file.into_raw_fd())
};
#[cfg(not(unix))]
let fd = {
let _ = file;
-1
};
let info_vk = ash::vk::ImportSemaphoreFdInfoKHR {
semaphore: self.handle,
flags: flags.into(),
handle_type: handle_type.into(),
fd,
..Default::default()
};
let fns = self.device.fns();
(fns.khr_external_semaphore_fd.import_semaphore_fd_khr)(self.device.handle(), &info_vk)
.result()
.map_err(VulkanError::from)?;
state.import(
handle_type,
flags.intersects(SemaphoreImportFlags::TEMPORARY),
);
Ok(())
}
#[inline]
pub unsafe fn import_win32_handle(
&self,
import_semaphore_win32_handle_info: ImportSemaphoreWin32HandleInfo,
) -> Result<(), Validated<VulkanError>> {
let mut state = self.state.lock();
self.validate_import_win32_handle(&import_semaphore_win32_handle_info, &state)?;
Ok(self
.import_win32_handle_unchecked_locked(import_semaphore_win32_handle_info, &mut state)?)
}
fn validate_import_win32_handle(
&self,
import_semaphore_win32_handle_info: &ImportSemaphoreWin32HandleInfo,
state: &SemaphoreState,
) -> Result<(), Box<ValidationError>> {
if !self
.device
.enabled_extensions()
.khr_external_semaphore_win32
{
return Err(Box::new(ValidationError {
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
"khr_external_semaphore_win32",
)])]),
..Default::default()
}));
}
if state.is_in_queue() {
return Err(Box::new(ValidationError {
problem: "the semaphore is in use".into(),
..Default::default()
}));
}
import_semaphore_win32_handle_info
.validate(&self.device)
.map_err(|err| err.add_context("import_semaphore_win32_handle_info"))?;
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
#[inline]
pub unsafe fn import_win32_handle_unchecked(
&self,
import_semaphore_win32_handle_info: ImportSemaphoreWin32HandleInfo,
) -> Result<(), VulkanError> {
let mut state = self.state.lock();
self.import_win32_handle_unchecked_locked(import_semaphore_win32_handle_info, &mut state)
}
unsafe fn import_win32_handle_unchecked_locked(
&self,
import_semaphore_win32_handle_info: ImportSemaphoreWin32HandleInfo,
state: &mut SemaphoreState,
) -> Result<(), VulkanError> {
let ImportSemaphoreWin32HandleInfo {
flags,
handle_type,
handle,
_ne: _,
} = import_semaphore_win32_handle_info;
let info_vk = ash::vk::ImportSemaphoreWin32HandleInfoKHR {
semaphore: self.handle,
flags: flags.into(),
handle_type: handle_type.into(),
handle,
name: ptr::null(), ..Default::default()
};
let fns = self.device.fns();
(fns.khr_external_semaphore_win32
.import_semaphore_win32_handle_khr)(self.device.handle(), &info_vk)
.result()
.map_err(VulkanError::from)?;
state.import(
handle_type,
flags.intersects(SemaphoreImportFlags::TEMPORARY),
);
Ok(())
}
#[inline]
pub unsafe fn import_zircon_handle(
&self,
import_semaphore_zircon_handle_info: ImportSemaphoreZirconHandleInfo,
) -> Result<(), Validated<VulkanError>> {
let mut state = self.state.lock();
self.validate_import_zircon_handle(&import_semaphore_zircon_handle_info, &state)?;
Ok(self.import_zircon_handle_unchecked_locked(
import_semaphore_zircon_handle_info,
&mut state,
)?)
}
fn validate_import_zircon_handle(
&self,
import_semaphore_zircon_handle_info: &ImportSemaphoreZirconHandleInfo,
state: &SemaphoreState,
) -> Result<(), Box<ValidationError>> {
if !self.device.enabled_extensions().fuchsia_external_semaphore {
return Err(Box::new(ValidationError {
requires_one_of: RequiresOneOf(&[RequiresAllOf(&[Requires::DeviceExtension(
"fuchsia_external_semaphore",
)])]),
..Default::default()
}));
}
if state.is_in_queue() {
return Err(Box::new(ValidationError {
problem: "the semaphore is in use".into(),
vuids: &["VUID-vkImportSemaphoreZirconHandleFUCHSIA-semaphore-04764"],
..Default::default()
}));
}
import_semaphore_zircon_handle_info
.validate(&self.device)
.map_err(|err| err.add_context("import_semaphore_zircon_handle_info"))?;
Ok(())
}
#[cfg_attr(not(feature = "document_unchecked"), doc(hidden))]
#[inline]
pub unsafe fn import_zircon_handle_unchecked(
&self,
import_semaphore_zircon_handle_info: ImportSemaphoreZirconHandleInfo,
) -> Result<(), VulkanError> {
let mut state = self.state.lock();
self.import_zircon_handle_unchecked_locked(import_semaphore_zircon_handle_info, &mut state)
}
unsafe fn import_zircon_handle_unchecked_locked(
&self,
import_semaphore_zircon_handle_info: ImportSemaphoreZirconHandleInfo,
state: &mut SemaphoreState,
) -> Result<(), VulkanError> {
let ImportSemaphoreZirconHandleInfo {
flags,
handle_type,
zircon_handle,
_ne: _,
} = import_semaphore_zircon_handle_info;
let info_vk = ash::vk::ImportSemaphoreZirconHandleInfoFUCHSIA {
semaphore: self.handle,
flags: flags.into(),
handle_type: handle_type.into(),
zircon_handle,
..Default::default()
};
let fns = self.device.fns();
(fns.fuchsia_external_semaphore
.import_semaphore_zircon_handle_fuchsia)(self.device.handle(), &info_vk)
.result()
.map_err(VulkanError::from)?;
state.import(
handle_type,
flags.intersects(SemaphoreImportFlags::TEMPORARY),
);
Ok(())
}
pub(crate) fn state(&self) -> MutexGuard<'_, SemaphoreState> {
self.state.lock()
}
}
impl Drop for Semaphore {
#[inline]
fn drop(&mut self) {
unsafe {
if self.must_put_in_pool {
let raw_sem = self.handle;
self.device.semaphore_pool().lock().push(raw_sem);
} else {
let fns = self.device.fns();
(fns.v1_0.destroy_semaphore)(self.device.handle(), self.handle, ptr::null());
}
}
}
}
unsafe impl VulkanObject for Semaphore {
type Handle = ash::vk::Semaphore;
#[inline]
fn handle(&self) -> Self::Handle {
self.handle
}
}
unsafe impl DeviceOwned for Semaphore {
#[inline]
fn device(&self) -> &Arc<Device> {
&self.device
}
}
impl_id_counter!(Semaphore);
#[derive(Clone, Debug)]
pub struct SemaphoreCreateInfo {
pub export_handle_types: ExternalSemaphoreHandleTypes,
pub _ne: crate::NonExhaustive,
}
impl Default for SemaphoreCreateInfo {
#[inline]
fn default() -> Self {
Self {
export_handle_types: ExternalSemaphoreHandleTypes::empty(),
_ne: crate::NonExhaustive(()),
}
}
}
impl SemaphoreCreateInfo {
pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
let &Self {
export_handle_types,
_ne: _,
} = self;
if !export_handle_types.is_empty() {
if !(device.api_version() >= Version::V1_1
|| device.enabled_extensions().khr_external_semaphore)
{
return Err(Box::new(ValidationError {
context: "export_handle_types".into(),
problem: "is not empty".into(),
requires_one_of: RequiresOneOf(&[
RequiresAllOf(&[Requires::APIVersion(Version::V1_1)]),
RequiresAllOf(&[Requires::DeviceExtension("khr_external_semaphore")]),
]),
..Default::default()
}));
}
export_handle_types.validate_device(device).map_err(|err| {
err.add_context("export_handle_types")
.set_vuids(&["VUID-VkExportSemaphoreCreateInfo-handleTypes-parameter"])
})?;
for handle_type in export_handle_types.into_iter() {
let external_semaphore_properties = unsafe {
device
.physical_device()
.external_semaphore_properties_unchecked(
ExternalSemaphoreInfo::handle_type(handle_type),
)
};
if !external_semaphore_properties.exportable {
return Err(Box::new(ValidationError {
context: "export_handle_types".into(),
problem: format!(
"the handle type `ExternalSemaphoreHandleTypes::{:?}` is not \
exportable, as returned by \
`PhysicalDevice::external_semaphore_properties`",
ExternalSemaphoreHandleTypes::from(handle_type)
)
.into(),
vuids: &["VUID-VkExportSemaphoreCreateInfo-handleTypes-01124"],
..Default::default()
}));
}
if !external_semaphore_properties
.compatible_handle_types
.contains(export_handle_types)
{
return Err(Box::new(ValidationError {
context: "export_handle_types".into(),
problem: format!(
"the handle type `ExternalSemaphoreHandleTypes::{:?}` is not \
compatible with the other specified handle types, as returned by \
`PhysicalDevice::external_semaphore_properties`",
ExternalSemaphoreHandleTypes::from(handle_type)
)
.into(),
vuids: &["VUID-VkExportSemaphoreCreateInfo-handleTypes-01124"],
..Default::default()
}));
}
}
}
Ok(())
}
}
vulkan_bitflags_enum! {
#[non_exhaustive]
ExternalSemaphoreHandleTypes,
ExternalSemaphoreHandleType impl {
#[inline]
pub fn has_copy_transference(self) -> bool {
matches!(self, Self::SyncFd)
}
},
= ExternalSemaphoreHandleTypeFlags(u32);
OPAQUE_FD, OpaqueFd = OPAQUE_FD,
OPAQUE_WIN32, OpaqueWin32 = OPAQUE_WIN32,
OPAQUE_WIN32_KMT, OpaqueWin32Kmt = OPAQUE_WIN32_KMT,
D3D12_FENCE, D3D12Fence = D3D12_FENCE,
SYNC_FD, SyncFd = SYNC_FD,
ZIRCON_EVENT, ZirconEvent = ZIRCON_EVENT_FUCHSIA
RequiresOneOf([
RequiresAllOf([DeviceExtension(fuchsia_external_semaphore)]),
]),
}
vulkan_bitflags! {
#[non_exhaustive]
SemaphoreImportFlags = SemaphoreImportFlags(u32);
TEMPORARY = TEMPORARY,
}
#[derive(Debug)]
pub struct ImportSemaphoreFdInfo {
pub flags: SemaphoreImportFlags,
pub handle_type: ExternalSemaphoreHandleType,
pub file: Option<File>,
pub _ne: crate::NonExhaustive,
}
impl ImportSemaphoreFdInfo {
#[inline]
pub fn handle_type(handle_type: ExternalSemaphoreHandleType) -> Self {
Self {
flags: SemaphoreImportFlags::empty(),
handle_type,
file: None,
_ne: crate::NonExhaustive(()),
}
}
pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
let &Self {
flags,
handle_type,
file: _,
_ne: _,
} = self;
flags.validate_device(device).map_err(|err| {
err.add_context("flags")
.set_vuids(&["VUID-VkImportSemaphoreFdInfoKHR-flags-parameter"])
})?;
handle_type.validate_device(device).map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkImportSemaphoreFdInfoKHR-handleType-parameter"])
})?;
if !matches!(
handle_type,
ExternalSemaphoreHandleType::OpaqueFd | ExternalSemaphoreHandleType::SyncFd
) {
return Err(Box::new(ValidationError {
context: "handle_type".into(),
problem: "is not `ExternalSemaphoreHandleType::OpaqueFd` or \
`ExternalSemaphoreHandleType::SyncFd`"
.into(),
vuids: &["VUID-VkImportSemaphoreFdInfoKHR-handleType-01143"],
..Default::default()
}));
}
if handle_type.has_copy_transference() && !flags.intersects(SemaphoreImportFlags::TEMPORARY)
{
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
`flags` does not contain `SemaphoreImportFlags::TEMPORARY`"
.into(),
vuids: &["VUID-VkImportSemaphoreFdInfoKHR-handleType-07307"],
..Default::default()
}));
}
Ok(())
}
}
#[derive(Debug)]
pub struct ImportSemaphoreWin32HandleInfo {
pub flags: SemaphoreImportFlags,
pub handle_type: ExternalSemaphoreHandleType,
pub handle: *mut std::ffi::c_void,
pub _ne: crate::NonExhaustive,
}
impl ImportSemaphoreWin32HandleInfo {
#[inline]
pub fn handle_type(handle_type: ExternalSemaphoreHandleType) -> Self {
Self {
flags: SemaphoreImportFlags::empty(),
handle_type,
handle: ptr::null_mut(),
_ne: crate::NonExhaustive(()),
}
}
pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
let &Self {
flags,
handle_type,
handle: _,
_ne: _,
} = self;
flags.validate_device(device).map_err(|err| {
err.add_context("flags")
.set_vuids(&["VUID-VkImportSemaphoreWin32HandleInfoKHR-flags-parameter"])
})?;
handle_type.validate_device(device).map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01140"])
})?;
if !matches!(
handle_type,
ExternalSemaphoreHandleType::OpaqueWin32
| ExternalSemaphoreHandleType::OpaqueWin32Kmt
| ExternalSemaphoreHandleType::D3D12Fence
) {
return Err(Box::new(ValidationError {
context: "handle_type".into(),
problem: "is not `ExternalSemaphoreHandleType::OpaqueWin32`, \
`ExternalSemaphoreHandleType::OpaqueWin32Kmt` or \
`ExternalSemaphoreHandleType::D3D12Fence`"
.into(),
vuids: &["VUID-VkImportSemaphoreWin32HandleInfoKHR-handleType-01140"],
..Default::default()
}));
}
if handle_type.has_copy_transference() && !flags.intersects(SemaphoreImportFlags::TEMPORARY)
{
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
`flags` does not contain `SemaphoreImportFlags::TEMPORARY`"
.into(),
..Default::default()
}));
}
Ok(())
}
}
#[derive(Debug)]
pub struct ImportSemaphoreZirconHandleInfo {
pub flags: SemaphoreImportFlags,
pub handle_type: ExternalSemaphoreHandleType,
pub zircon_handle: ash::vk::zx_handle_t,
pub _ne: crate::NonExhaustive,
}
impl ImportSemaphoreZirconHandleInfo {
#[inline]
pub fn handle_type(handle_type: ExternalSemaphoreHandleType) -> Self {
Self {
flags: SemaphoreImportFlags::empty(),
handle_type,
zircon_handle: 0,
_ne: crate::NonExhaustive(()),
}
}
pub(crate) fn validate(&self, device: &Device) -> Result<(), Box<ValidationError>> {
let &Self {
flags,
handle_type,
zircon_handle: _,
_ne: _,
} = self;
flags.validate_device(device).map_err(|err| {
err.add_context("flags")
.set_vuids(&["VUID-VkImportSemaphoreZirconHandleInfoFUCHSIA-flags-parameter"])
})?;
handle_type.validate_device(device).map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkImportSemaphoreZirconHandleInfoFUCHSIA-handleType-parameter"])
})?;
if !matches!(handle_type, ExternalSemaphoreHandleType::ZirconEvent) {
return Err(Box::new(ValidationError {
context: "handle_type".into(),
problem: "is not `ExternalSemaphoreHandleType::ZirconEvent`".into(),
vuids: &["VUID-VkImportSemaphoreZirconHandleInfoFUCHSIA-handleType-04765"],
..Default::default()
}));
}
if handle_type.has_copy_transference() && !flags.intersects(SemaphoreImportFlags::TEMPORARY)
{
return Err(Box::new(ValidationError {
problem: "`handle_type` has copy transference, but \
`flags` does not contain `SemaphoreImportFlags::TEMPORARY`"
.into(),
..Default::default()
}));
}
Ok(())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ExternalSemaphoreInfo {
pub handle_type: ExternalSemaphoreHandleType,
pub _ne: crate::NonExhaustive,
}
impl ExternalSemaphoreInfo {
#[inline]
pub fn handle_type(handle_type: ExternalSemaphoreHandleType) -> Self {
Self {
handle_type,
_ne: crate::NonExhaustive(()),
}
}
pub(crate) fn validate(
&self,
physical_device: &PhysicalDevice,
) -> Result<(), Box<ValidationError>> {
let &Self {
handle_type,
_ne: _,
} = self;
handle_type
.validate_physical_device(physical_device)
.map_err(|err| {
err.add_context("handle_type")
.set_vuids(&["VUID-VkPhysicalDeviceExternalSemaphoreInfo-handleType-parameter"])
})?;
Ok(())
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct ExternalSemaphoreProperties {
pub exportable: bool,
pub importable: bool,
pub export_from_imported_handle_types: ExternalSemaphoreHandleTypes,
pub compatible_handle_types: ExternalSemaphoreHandleTypes,
}
#[derive(Debug, Default)]
pub(crate) struct SemaphoreState {
is_signaled: bool,
pending_signal: Option<SignalType>,
pending_wait: Option<Weak<Queue>>,
reference_exported: bool,
exported_handle_types: ExternalSemaphoreHandleTypes,
current_import: Option<ImportType>,
permanent_import: Option<ExternalSemaphoreHandleType>,
}
impl SemaphoreState {
#[inline]
fn is_signaled(&self) -> Option<bool> {
if self.pending_signal.is_some()
|| self.pending_wait.is_some()
|| self.has_external_reference()
{
None
} else {
Some(self.is_signaled)
}
}
#[inline]
fn is_signal_pending(&self) -> bool {
self.pending_signal.is_some()
}
#[inline]
fn is_wait_pending(&self) -> bool {
self.pending_wait.is_some()
}
#[inline]
fn is_in_queue(&self) -> bool {
matches!(self.pending_signal, Some(SignalType::Queue(_))) || self.pending_wait.is_some()
}
#[inline]
fn has_external_reference(&self) -> bool {
self.reference_exported || self.current_import.is_some()
}
#[allow(dead_code)]
#[inline]
fn is_exported(&self, handle_type: ExternalSemaphoreHandleType) -> bool {
self.exported_handle_types.intersects(handle_type.into())
}
#[inline]
pub(crate) unsafe fn add_queue_signal(&mut self, queue: &Arc<Queue>) {
self.pending_signal = Some(SignalType::Queue(Arc::downgrade(queue)));
}
#[inline]
pub(crate) unsafe fn add_queue_wait(&mut self, queue: &Arc<Queue>) {
self.pending_wait = Some(Arc::downgrade(queue));
}
#[inline]
pub(crate) unsafe fn set_signal_finished(&mut self) {
self.pending_signal = None;
self.is_signaled = true;
}
#[inline]
pub(crate) unsafe fn set_wait_finished(&mut self) {
self.pending_wait = None;
self.current_import = self.permanent_import.map(Into::into);
self.is_signaled = false;
}
#[allow(dead_code)]
#[inline]
unsafe fn export(&mut self, handle_type: ExternalSemaphoreHandleType) {
self.exported_handle_types |= handle_type.into();
if handle_type.has_copy_transference() {
self.current_import = self.permanent_import.map(Into::into);
self.is_signaled = false;
} else {
self.reference_exported = true;
}
}
#[allow(dead_code)]
#[inline]
unsafe fn import(&mut self, handle_type: ExternalSemaphoreHandleType, temporary: bool) {
self.current_import = Some(handle_type.into());
if !temporary {
self.permanent_import = Some(handle_type);
}
}
#[inline]
pub(crate) unsafe fn swapchain_acquire(&mut self) {
self.pending_signal = Some(SignalType::SwapchainAcquire);
self.current_import = Some(ImportType::SwapchainAcquire);
}
}
#[derive(Clone, Debug)]
enum SignalType {
Queue(Weak<Queue>),
SwapchainAcquire,
}
#[derive(Clone, Copy, Debug)]
enum ImportType {
SwapchainAcquire,
ExternalSemaphore(ExternalSemaphoreHandleType),
}
impl From<ExternalSemaphoreHandleType> for ImportType {
#[inline]
fn from(handle_type: ExternalSemaphoreHandleType) -> Self {
Self::ExternalSemaphore(handle_type)
}
}
#[cfg(test)]
mod tests {
use crate::{
device::{Device, DeviceCreateInfo, DeviceExtensions, QueueCreateInfo},
instance::{Instance, InstanceCreateInfo, InstanceExtensions},
sync::semaphore::{
ExternalSemaphoreHandleType, ExternalSemaphoreHandleTypes, Semaphore,
SemaphoreCreateInfo,
},
VulkanLibrary, VulkanObject,
};
#[test]
fn semaphore_create() {
let (device, _) = gfx_dev_and_queue!();
let _ = Semaphore::new(device, Default::default());
}
#[test]
fn semaphore_pool() {
let (device, _) = gfx_dev_and_queue!();
assert_eq!(device.semaphore_pool().lock().len(), 0);
let sem1_internal_obj = {
let sem = Semaphore::from_pool(device.clone()).unwrap();
assert_eq!(device.semaphore_pool().lock().len(), 0);
sem.handle()
};
assert_eq!(device.semaphore_pool().lock().len(), 1);
let sem2 = Semaphore::from_pool(device.clone()).unwrap();
assert_eq!(device.semaphore_pool().lock().len(), 0);
assert_eq!(sem2.handle(), sem1_internal_obj);
}
#[test]
fn semaphore_export_fd() {
let library = match VulkanLibrary::new() {
Ok(x) => x,
Err(_) => return,
};
let instance = match Instance::new(
library,
InstanceCreateInfo {
enabled_extensions: InstanceExtensions {
khr_get_physical_device_properties2: true,
khr_external_semaphore_capabilities: true,
..InstanceExtensions::empty()
},
..Default::default()
},
) {
Ok(x) => x,
Err(_) => return,
};
let physical_device = match instance.enumerate_physical_devices() {
Ok(mut x) => x.next().unwrap(),
Err(_) => return,
};
let (device, _) = match Device::new(
physical_device,
DeviceCreateInfo {
queue_create_infos: vec![QueueCreateInfo {
queue_family_index: 0,
..Default::default()
}],
enabled_extensions: DeviceExtensions {
khr_external_semaphore: true,
khr_external_semaphore_fd: true,
..DeviceExtensions::empty()
},
..Default::default()
},
) {
Ok(x) => x,
Err(_) => return,
};
let sem = Semaphore::new(
device,
SemaphoreCreateInfo {
export_handle_types: ExternalSemaphoreHandleTypes::OPAQUE_FD,
..Default::default()
},
)
.unwrap();
let _fd = sem
.export_fd(ExternalSemaphoreHandleType::OpaqueFd)
.unwrap();
}
}