845: Finish error model refactor r=kvark a=GabrielMajeri

**Connections**
I think this is the last part of #638. I've reviewed all the remaining `unwrap`s and `assert`s in the code, and these should be the last ones left which ought to return errors (the remaining ones seem to uphold internal invariants).

**Description**
Implements error handling for various conditions, which are then returned to the caller. Including, but not limited to:
- running out of memory when creating a command pool
- running out of memory when creating a frame buffer for a render pass
- invalid dimensions when creating a texture

**Testing**
Tested with core and player.

Co-authored-by: Gabriel Majeri <gabriel.majeri6@gmail.com>
This commit is contained in:
bors[bot]andGabriel Majeri authored and GitHub committed 2020-07-29 18:10:33 +00:00
commit f6ba5b8298
9 files changed
+149 -74

No files matched your search

+7 -5
View File
@@ -306,11 +306,13 @@ impl GlobalPlay for wgc::hub::Global<IdentityPassThroughFactory> {
.unwrap();
}
A::Submit(_index, commands) => {
let encoder = self.device_create_command_encoder::<B>(
device,
&wgt::CommandEncoderDescriptor { label: ptr::null() },
comb_manager.alloc(device.backend()),
);
let encoder = self
.device_create_command_encoder::<B>(
device,
&wgt::CommandEncoderDescriptor { label: ptr::null() },
comb_manager.alloc(device.backend()),
)
.unwrap();
let cmdbuf = self.encode_commands::<B>(encoder, commands);
self.queue_submit::<B>(device, &[cmdbuf]).unwrap();
}
+41 -24
View File
@@ -10,6 +10,7 @@ use crate::{
use hal::{command::CommandBuffer as _, device::Device as _, pool::CommandPool as _};
use parking_lot::Mutex;
use thiserror::Error;
use std::thread;
@@ -80,30 +81,37 @@ impl<B: GfxBackend> CommandAllocator<B> {
limits: wgt::Limits,
private_features: PrivateFeatures,
#[cfg(feature = "trace")] enable_tracing: bool,
) -> CommandBuffer<B> {
) -> Result<CommandBuffer<B>, CommandAllocatorError> {
//debug_assert_eq!(device_id.backend(), B::VARIANT);
let thread_id = thread::current().id();
let mut inner = self.inner.lock();
let init = inner
.pools
.entry(thread_id)
.or_insert_with(|| CommandPool {
raw: unsafe {
tracing::info!("Starting on thread {:?}", thread_id);
device.create_command_pool(
self.queue_family,
hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL,
)
}
.unwrap(),
total: 0,
available: Vec::new(),
pending: Vec::new(),
})
.allocate();
use std::collections::hash_map::Entry;
let pool = match inner.pools.entry(thread_id) {
Entry::Occupied(e) => e.into_mut(),
Entry::Vacant(e) => {
tracing::info!("Starting on thread {:?}", thread_id);
let raw = unsafe {
device
.create_command_pool(
self.queue_family,
hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL,
)
.or(Err(CommandAllocatorError::OutOfMemory))?
};
let pool = CommandPool {
raw,
total: 0,
available: Vec::new(),
pending: Vec::new(),
};
e.insert(pool)
}
};
CommandBuffer {
let init = pool.allocate();
Ok(CommandBuffer {
raw: vec![init],
is_recording: true,
recorded_thread_id: thread_id,
@@ -118,12 +126,15 @@ impl<B: GfxBackend> CommandAllocator<B> {
} else {
None
},
}
})
}
}
impl<B: hal::Backend> CommandAllocator<B> {
pub fn new(queue_family: hal::queue::QueueFamilyId, device: &B::Device) -> Self {
pub fn new(
queue_family: hal::queue::QueueFamilyId,
device: &B::Device,
) -> Result<Self, CommandAllocatorError> {
let internal_thread_id = thread::current().id();
tracing::info!("Starting on (internal) thread {:?}", internal_thread_id);
let mut pools = FastHashMap::default();
@@ -136,18 +147,18 @@ impl<B: hal::Backend> CommandAllocator<B> {
queue_family,
hal::pool::CommandPoolCreateFlags::RESET_INDIVIDUAL,
)
.unwrap()
.or(Err(CommandAllocatorError::OutOfMemory))?
},
total: 0,
available: Vec::new(),
pending: Vec::new(),
},
);
CommandAllocator {
Ok(CommandAllocator {
queue_family,
internal_thread_id,
inner: Mutex::new(Inner { pools }),
}
})
}
fn allocate_for_thread_id(&self, thread_id: thread::ThreadId) -> B::CommandBuffer {
@@ -242,3 +253,9 @@ impl<B: hal::Backend> CommandAllocator<B> {
}
}
}
#[derive(Clone, Debug, Error)]
pub enum CommandAllocatorError {
#[error("not enough memory left")]
OutOfMemory,
}
+1
View File
@@ -10,6 +10,7 @@ mod render;
mod transfer;
pub(crate) use self::allocator::CommandAllocator;
pub use self::allocator::CommandAllocatorError;
pub use self::bundle::*;
pub use self::compute::*;
pub use self::render::*;
+11 -7
View File
@@ -413,6 +413,8 @@ pub enum RenderPassError {
InvalidResolveSourceSampleCount,
#[error("resolve target must have a sample count of 1")]
InvalidResolveTargetSampleCount,
#[error("not enough memory left")]
OutOfMemory,
#[error("extent state {state_extent:?} must match extent from view {view_extent:?}")]
ExtentStateMismatch {
state_extent: hal::image::Extent,
@@ -885,7 +887,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
device
.raw
.create_framebuffer(&render_pass, attachments, extent.unwrap())
.unwrap()
.or(Err(RenderPassError::OutOfMemory))?
};
cmb.used_swap_chain = Some((sc_id, framebuffer));
&mut cmb.used_swap_chain.as_mut().unwrap().1
@@ -905,13 +907,15 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
});
unsafe {
device.raw.create_framebuffer(
&render_pass,
attachments,
extent.unwrap(),
)
device
.raw
.create_framebuffer(
&render_pass,
attachments,
extent.unwrap(),
)
.or(Err(RenderPassError::OutOfMemory))?
}
.unwrap()
};
e.insert(fb)
}
+42 -18
View File
@@ -7,6 +7,9 @@ use crate::{
resource, PrivateFeatures,
};
use std::convert::TryInto;
use thiserror::Error;
pub fn map_buffer_usage(usage: wgt::BufferUsage) -> (hal::buffer::Usage, hal::memory::Properties) {
use hal::buffer::Usage as U;
use hal::memory::Properties as P;
@@ -429,11 +432,6 @@ pub fn map_vertex_format(vertex_format: wgt::VertexFormat) -> hal::format::Forma
}
}
fn checked_u32_as_u16(value: u32) -> u16 {
assert!(value <= ::std::u16::MAX as u32);
value as u16
}
pub fn is_power_of_two(val: u32) -> bool {
val != 0 && (val & (val - 1)) == 0
}
@@ -446,28 +444,54 @@ pub fn map_texture_dimension_size(
depth,
}: wgt::Extent3d,
sample_size: u32,
) -> hal::image::Kind {
) -> Result<hal::image::Kind, MapTextureDimensionSizeError> {
use hal::image::Kind as H;
use wgt::TextureDimension::*;
match dimension {
Ok(match dimension {
D1 => {
assert_eq!(height, 1);
assert_eq!(sample_size, 1);
H::D1(width, checked_u32_as_u16(depth))
if height != 1 {
return Err(MapTextureDimensionSizeError::InvalidHeight);
}
if sample_size != 1 {
return Err(MapTextureDimensionSizeError::InvalidSampleCount(
sample_size,
));
}
let layers = depth
.try_into()
.or(Err(MapTextureDimensionSizeError::TooManyLayers(depth)))?;
H::D1(width, layers)
}
D2 => {
assert!(
sample_size <= 32 && is_power_of_two(sample_size),
"Invalid sample_count of {}",
sample_size
);
H::D2(width, height, checked_u32_as_u16(depth), sample_size as u8)
if sample_size > 32 || !is_power_of_two(sample_size) {
return Err(MapTextureDimensionSizeError::InvalidSampleCount(
sample_size,
));
}
let layers = depth
.try_into()
.or(Err(MapTextureDimensionSizeError::TooManyLayers(depth)))?;
H::D2(width, height, layers, sample_size as u8)
}
D3 => {
assert_eq!(sample_size, 1);
if sample_size != 1 {
return Err(MapTextureDimensionSizeError::InvalidSampleCount(
sample_size,
));
}
H::D3(width, height, depth)
}
}
})
}
#[derive(Clone, Debug, Error)]
pub enum MapTextureDimensionSizeError {
#[error("too many layers ({0}) for texture array")]
TooManyLayers(u32),
#[error("1D textures must have height set to 1")]
InvalidHeight,
#[error("sample count {0} is invalid")]
InvalidSampleCount(u32),
}
pub fn map_texture_view_dimension(dimension: wgt::TextureViewDimension) -> hal::image::ViewKind {
+1 -1
View File
@@ -304,7 +304,7 @@ impl<B: hal::Backend> LifetimeTracker<B> {
let done_count = self
.active
.iter()
.position(|a| unsafe { !device.get_fence_status(&a.fence).unwrap() })
.position(|a| unsafe { !device.get_fence_status(&a.fence).unwrap_or(false) })
.unwrap_or_else(|| self.active.len());
let last_done = if done_count != 0 {
self.active[done_count - 1].index
+21 -9
View File
@@ -217,8 +217,9 @@ impl<B: GfxBackend> Device<B> {
private_features: PrivateFeatures,
desc: &wgt::DeviceDescriptor,
trace_path: Option<&std::path::Path>,
) -> Self {
let cmd_allocator = command::CommandAllocator::new(queue_group.family, &raw);
) -> Result<Self, CreateDeviceError> {
let cmd_allocator = command::CommandAllocator::new(queue_group.family, &raw)
.or(Err(CreateDeviceError::OutOfMemory))?;
let heaps = unsafe {
Heaps::new(
&mem_props,
@@ -240,7 +241,7 @@ impl<B: GfxBackend> Device<B> {
None => (),
}
Device {
Ok(Device {
raw,
adapter_id,
cmd_allocator,
@@ -273,7 +274,7 @@ impl<B: GfxBackend> Device<B> {
limits: desc.limits.clone(),
features: desc.features.clone(),
pending_writes: queue::PendingWrites::new(),
}
})
}
pub(crate) fn last_completed_submission_index(&self) -> SubmissionIndex {
@@ -484,7 +485,7 @@ impl<B: GfxBackend> Device<B> {
_ => {}
}
let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.sample_count);
let kind = conv::map_texture_dimension_size(desc.dimension, desc.size, desc.sample_count)?;
let format = conv::map_texture_format(desc.format, self.private_features);
let aspects = format.surface_desc().aspects;
let usage = conv::map_texture_usage(desc.usage, aspects);
@@ -2049,7 +2050,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
device_id: id::DeviceId,
desc: &wgt::CommandEncoderDescriptor<Label>,
id_in: Input<G, id::CommandEncoderId>,
) -> id::CommandEncoderId {
) -> Result<id::CommandEncoderId, command::CommandAllocatorError> {
span!(_guard, INFO, "Device::create_command_encoder");
let hub = B::hub(self);
@@ -2070,7 +2071,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
device.private_features,
#[cfg(feature = "trace")]
device.trace.is_some(),
);
)?;
unsafe {
let raw_command_buffer = command_buffer.raw.last_mut().unwrap();
@@ -2083,8 +2084,11 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
raw_command_buffer.begin_primary(hal::command::CommandBufferFlags::ONE_TIME_SUBMIT);
}
hub.command_buffers
.register_identity(id_in, command_buffer, &mut token)
let id = hub
.command_buffers
.register_identity(id_in, command_buffer, &mut token);
Ok(id)
}
pub fn command_encoder_destroy<B: GfxBackend>(&self, command_encoder_id: id::CommandEncoderId) {
@@ -3053,6 +3057,12 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
}
}
#[derive(Clone, Debug, Error)]
pub enum CreateDeviceError {
#[error("not enough memory left")]
OutOfMemory,
}
#[derive(Clone, Debug, Error)]
pub enum CreateBufferError {
#[error("failed to map buffer while creating: {0}")]
@@ -3071,6 +3081,8 @@ pub enum CreateBufferError {
pub enum CreateTextureError {
#[error("D24Plus textures cannot be copied")]
CannotCopyD24Plus,
#[error(transparent)]
InvalidDimension(#[from] conv::MapTextureDimensionSizeError),
#[error(
"texture descriptor mip level count ({0}) must be less than device max mip levels ({})",
MAX_MIP_LEVELS
+4 -3
View File
@@ -423,9 +423,10 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
let cmdbuf = &mut command_buffer_guard[cmb_id];
#[cfg(feature = "trace")]
match device.trace {
Some(ref trace) => trace
.lock()
.add(Action::Submit(submit_index, cmdbuf.commands.take().unwrap())),
Some(ref trace) => trace.lock().add(Action::Submit(
submit_index,
cmdbuf.commands.take().unwrap(),
)),
None => (),
};
+21 -7
View File
@@ -248,14 +248,18 @@ impl AdapterInfo {
#[derive(Clone, Debug, Error, PartialEq)]
/// Error when requesting a device from the adaptor
pub enum RequestDeviceError {
#[error("unsupported features were requested: {0:?}")]
UnsupportedFeature(wgt::Features),
#[error("device has no queue supporting graphics")]
NoGraphicsQueue,
#[error(transparent)]
DeviceCreationError(#[from] hal::device::CreationError),
#[error("connection to device was lost during initialization")]
DeviceLost,
#[error("device initialization failed due to implementation specific errors")]
Internal,
#[error("some of the requested device limits are not supported")]
LimitsExceeded,
#[error("device has no queue supporting graphics")]
NoGraphicsQueue,
#[error("not enough memory left")]
OutOfMemory,
#[error("unsupported features were requested: {0:?}")]
UnsupportedFeature(wgt::Features),
}
/// Supported physical device types.
@@ -679,7 +683,16 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
.iter()
.find(|family| family.queue_type().supports_graphics())
.ok_or(RequestDeviceError::NoGraphicsQueue)?;
let mut gpu = unsafe { phd.open(&[(family, &[1.0])], enabled_features)? };
let mut gpu =
unsafe { phd.open(&[(family, &[1.0])], enabled_features) }.map_err(|err| {
use hal::device::CreationError::*;
match err {
DeviceLost => RequestDeviceError::DeviceLost,
InitializationFailed => RequestDeviceError::Internal,
OutOfMemory(_) => RequestDeviceError::OutOfMemory,
_ => panic!("failed to create `gfx-hal` device: {}", err),
}
})?;
let limits = phd.limits();
assert_eq!(
@@ -722,6 +735,7 @@ impl<G: GlobalIdentityHandlerFactory> Global<G> {
desc,
trace_path,
)
.or(Err(RequestDeviceError::OutOfMemory))?
};
Ok(hub.devices.register_identity(id_in, device, &mut token))