hal/vk: queue operations

This commit is contained in:
Dzmitry Malyshau committed 2021-06-15 11:38:07 -04:00
1 parent 668fedd1c0
commit a260cff0f0
6 files changed
+227 -53

No files matched your search

+3 -2
View File
@@ -303,7 +303,7 @@ impl crate::Queue<Api> for Queue {
raw.set_label("_Signal");
raw.add_completed_handler(&block);
fence.update();
fence.maintain();
fence.pending_command_buffers.push((value, raw.to_owned()));
// only return an extra one if it's extra
match command_buffers.last() {
@@ -619,6 +619,7 @@ unsafe impl Sync for QuerySet {}
#[derive(Debug)]
pub struct Fence {
completed_value: Arc<atomic::AtomicU64>,
/// The pending fence values have to be ascending.
pending_command_buffers: Vec<(crate::FenceValue, mtl::CommandBuffer)>,
}
@@ -636,7 +637,7 @@ impl Fence {
max_value
}
fn update(&mut self) {
fn maintain(&mut self) {
let latest = self.get_latest();
self.pending_command_buffers
.retain(|&(value, _)| value > latest);
+26 -18
View File
@@ -541,6 +541,11 @@ impl super::Instance {
.raw
.get_physical_device_queue_family_properties(phd)
};
let queue_flags = queue_families.first()?.queue_flags;
if !queue_flags.contains(vk::QueueFlags::GRAPHICS) {
log::warn!("The first queue only exposes {:?}", queue_flags);
return None;
}
let private_caps = super::PrivateCapabilities {
flip_y_requires_shift: phd_capabilities.properties.api_version >= vk::API_VERSION_1_1
@@ -579,14 +584,14 @@ impl super::Instance {
let adapter = super::Adapter {
raw: phd,
instance: Arc::clone(&self.shared),
queue_families,
//queue_families,
known_memory_flags: vk::MemoryPropertyFlags::DEVICE_LOCAL
| vk::MemoryPropertyFlags::HOST_VISIBLE
| vk::MemoryPropertyFlags::HOST_COHERENT
| vk::MemoryPropertyFlags::HOST_CACHED
| vk::MemoryPropertyFlags::LAZILY_ALLOCATED,
phd_capabilities,
phd_features,
//phd_features,
downlevel_flags,
private_caps,
};
@@ -706,15 +711,30 @@ impl crate::Adapter<super::Api> for super::Adapter {
}
};
log::info!("Private capabilities: {:?}", self.private_caps);
let family_index = 0; //TODO
let raw_queue = raw_device.get_device_queue(family_index, 0);
let shared = Arc::new(super::DeviceShared {
raw: raw_device,
instance: Arc::clone(&self.instance),
extension_fns: super::DeviceExtensionFunctions {
draw_indirect_count: indirect_count_fn,
},
features,
vendor_id: self.phd_capabilities.properties.vendor_id,
downlevel_flags: self.downlevel_flags,
private_caps: self.private_caps.clone(),
_timestamp_period: self.phd_capabilities.properties.limits.timestamp_period,
render_passes: Mutex::new(Default::default()),
});
let queue = super::Queue {
raw: raw_device.get_device_queue(family_index, 0),
raw: raw_queue,
swapchain_fn,
device: Arc::clone(&shared),
family_index,
};
log::info!("Private capabilities: {:?}", self.private_caps);
let mem_allocator = {
let limits = self.phd_capabilities.properties.limits;
let config = gpu_alloc::Config::i_am_prototyping(); //TODO
@@ -745,19 +765,7 @@ impl crate::Adapter<super::Api> for super::Adapter {
let desc_allocator = gpu_descriptor::DescriptorAllocator::new(0);
let device = super::Device {
shared: Arc::new(super::DeviceShared {
raw: raw_device,
instance: Arc::clone(&self.instance),
extension_fns: super::DeviceExtensionFunctions {
draw_indirect_count: indirect_count_fn,
},
features,
vendor_id: self.phd_capabilities.properties.vendor_id,
downlevel_flags: self.downlevel_flags,
private_caps: self.private_caps.clone(),
timestamp_period: self.phd_capabilities.properties.limits.timestamp_period,
render_passes: Mutex::new(Default::default()),
}),
shared,
mem_allocator: Mutex::new(mem_allocator),
desc_allocator: Mutex::new(desc_allocator),
valid_ash_memory_types,
+5 -7
View File
@@ -2,8 +2,6 @@ use std::ops::Range;
use ash::{version::DeviceV1_0, vk};
use super::Resource; // TEMP
const ALLOCATION_GRANULARITY: u32 = 16;
impl crate::CommandEncoder<super::Api> for super::CommandEncoder {
@@ -100,13 +98,13 @@ impl crate::CommandEncoder<super::Api> for super::CommandEncoder {
) {
}
unsafe fn begin_query(&mut self, set: &Resource, index: u32) {}
unsafe fn end_query(&mut self, set: &Resource, index: u32) {}
unsafe fn write_timestamp(&mut self, set: &Resource, index: u32) {}
unsafe fn reset_queries(&mut self, set: &Resource, range: Range<u32>) {}
unsafe fn begin_query(&mut self, set: &super::QuerySet, index: u32) {}
unsafe fn end_query(&mut self, set: &super::QuerySet, index: u32) {}
unsafe fn write_timestamp(&mut self, set: &super::QuerySet, index: u32) {}
unsafe fn reset_queries(&mut self, set: &super::QuerySet, range: Range<u32>) {}
unsafe fn copy_query_results(
&mut self,
set: &Resource,
set: &super::QuerySet,
range: Range<u32>,
buffer: &super::Buffer,
offset: wgt::BufferAddress,
+23
View File
@@ -561,3 +561,26 @@ pub fn map_blend_component(
let dst = map_blend_factor(component.dst_factor);
(op, src, dst)
}
pub fn map_pipeline_statistics(
types: wgt::PipelineStatisticsTypes,
) -> vk::QueryPipelineStatisticFlags {
use wgt::PipelineStatisticsTypes as Pst;
let mut flags = vk::QueryPipelineStatisticFlags::empty();
if types.contains(Pst::VERTEX_SHADER_INVOCATIONS) {
flags |= vk::QueryPipelineStatisticFlags::VERTEX_SHADER_INVOCATIONS;
}
if types.contains(Pst::CLIPPER_INVOCATIONS) {
flags |= vk::QueryPipelineStatisticFlags::CLIPPING_INVOCATIONS;
}
if types.contains(Pst::CLIPPER_PRIMITIVES_OUT) {
flags |= vk::QueryPipelineStatisticFlags::CLIPPING_PRIMITIVES;
}
if types.contains(Pst::FRAGMENT_SHADER_INVOCATIONS) {
flags |= vk::QueryPipelineStatisticFlags::FRAGMENT_SHADER_INVOCATIONS;
}
if types.contains(Pst::COMPUTE_SHADER_INVOCATIONS) {
flags |= vk::QueryPipelineStatisticFlags::COMPUTE_SHADER_INVOCATIONS;
}
flags
}
+70 -14
View File
@@ -436,8 +436,6 @@ impl super::Device {
}
}
use super::{DeviceResult, Resource}; //temporary
impl crate::Device<super::Api> for super::Device {
unsafe fn create_buffer(
&self,
@@ -1173,24 +1171,82 @@ impl crate::Device<super::Api> for super::Device {
self.shared.raw.destroy_pipeline(pipeline.raw, None);
}
unsafe fn create_query_set(&self, desc: &wgt::QuerySetDescriptor) -> DeviceResult<Resource> {
Ok(Resource)
unsafe fn create_query_set(
&self,
desc: &wgt::QuerySetDescriptor,
) -> Result<super::QuerySet, crate::DeviceError> {
let (vk_type, pipeline_statistics) = match desc.ty {
wgt::QueryType::Occlusion => (
vk::QueryType::OCCLUSION,
vk::QueryPipelineStatisticFlags::empty(),
),
wgt::QueryType::PipelineStatistics(statistics) => (
vk::QueryType::PIPELINE_STATISTICS,
conv::map_pipeline_statistics(statistics),
),
wgt::QueryType::Timestamp => (
vk::QueryType::TIMESTAMP,
vk::QueryPipelineStatisticFlags::empty(),
),
};
let vk_info = vk::QueryPoolCreateInfo::builder()
.query_type(vk_type)
.query_count(desc.count)
.pipeline_statistics(pipeline_statistics)
.build();
let raw = self.shared.raw.create_query_pool(&vk_info, None)?;
Ok(super::QuerySet { raw })
}
unsafe fn destroy_query_set(&self, set: Resource) {}
unsafe fn create_fence(&self) -> DeviceResult<Resource> {
Ok(Resource)
unsafe fn destroy_query_set(&self, set: super::QuerySet) {
self.shared.raw.destroy_query_pool(set.raw, None);
}
unsafe fn destroy_fence(&self, fence: Resource) {}
unsafe fn get_fence_value(&self, fence: &Resource) -> DeviceResult<crate::FenceValue> {
Ok(0)
unsafe fn create_fence(&self) -> Result<super::Fence, crate::DeviceError> {
Ok(super::Fence {
last_completed: 0,
active: Vec::new(),
free: Vec::new(),
})
}
unsafe fn destroy_fence(&self, fence: super::Fence) {
for (_, raw) in fence.active {
self.shared.raw.destroy_fence(raw, None);
}
for raw in fence.free {
self.shared.raw.destroy_fence(raw, None);
}
}
unsafe fn get_fence_value(
&self,
fence: &super::Fence,
) -> Result<crate::FenceValue, crate::DeviceError> {
fence.get_latest(&self.shared.raw)
}
unsafe fn wait(
&self,
fence: &Resource,
value: crate::FenceValue,
fence: &super::Fence,
wait_value: crate::FenceValue,
timeout_ms: u32,
) -> DeviceResult<bool> {
Ok(true)
) -> Result<bool, crate::DeviceError> {
if wait_value <= fence.last_completed {
Ok(true)
} else {
match fence.active.iter().find(|&&(value, _)| value >= wait_value) {
Some(&(_, raw)) => {
let timeout_us = timeout_ms as u64 * super::MILLIS_TO_NANOS;
match self.shared.raw.wait_for_fences(&[raw], true, timeout_us) {
Ok(()) => Ok(true),
Err(vk::Result::TIMEOUT) => Ok(false),
Err(other) => Err(other.into()),
}
}
None => {
log::error!("No signals reached value {}", wait_value);
Err(crate::DeviceError::Lost)
}
}
}
}
unsafe fn start_capture(&self) -> bool {
+100 -12
View File
@@ -11,6 +11,7 @@ use std::{borrow::Borrow, ffi::CStr, sync::Arc};
use arrayvec::ArrayVec;
use ash::{
extensions::{ext, khr},
version::DeviceV1_0,
vk,
};
use parking_lot::Mutex;
@@ -19,10 +20,6 @@ const MILLIS_TO_NANOS: u64 = 1_000_000;
#[derive(Clone)]
pub struct Api;
#[derive(Debug)]
pub struct Resource;
type DeviceResult<T> = Result<T, crate::DeviceError>;
impl crate::Api for Api {
type Instance = Instance;
@@ -39,8 +36,8 @@ impl crate::Api for Api {
type SurfaceTexture = SurfaceTexture;
type TextureView = TextureView;
type Sampler = Sampler;
type QuerySet = Resource;
type Fence = Resource;
type QuerySet = QuerySet;
type Fence = Fence;
type BindGroupLayout = BindGroupLayout;
type BindGroup = BindGroup;
@@ -100,10 +97,10 @@ impl Borrow<Texture> for SurfaceTexture {
pub struct Adapter {
raw: vk::PhysicalDevice,
instance: Arc<InstanceShared>,
queue_families: Vec<vk::QueueFamilyProperties>,
//queue_families: Vec<vk::QueueFamilyProperties>,
known_memory_flags: vk::MemoryPropertyFlags,
phd_capabilities: adapter::PhysicalDeviceCapabilities,
phd_features: adapter::PhysicalDeviceFeatures,
//phd_features: adapter::PhysicalDeviceFeatures,
downlevel_flags: wgt::DownlevelFlags,
private_caps: PrivateCapabilities,
}
@@ -181,7 +178,7 @@ struct DeviceShared {
extension_fns: DeviceExtensionFunctions,
features: wgt::Features,
vendor_id: u32,
timestamp_period: f32,
_timestamp_period: f32,
downlevel_flags: wgt::DownlevelFlags,
private_caps: PrivateCapabilities,
render_passes: Mutex<fxhash::FxHashMap<RenderPassKey, vk::RenderPass>>,
@@ -199,8 +196,8 @@ pub struct Device {
pub struct Queue {
raw: vk::Queue,
swapchain_fn: khr::Swapchain,
device: Arc<DeviceShared>,
family_index: u32,
//device: Arc<DeviceShared>,
}
#[derive(Debug)]
@@ -270,19 +267,110 @@ pub struct ComputePipeline {
raw: vk::Pipeline,
}
#[derive(Debug)]
pub struct QuerySet {
raw: vk::QueryPool,
}
#[derive(Debug)]
pub struct Fence {
last_completed: crate::FenceValue,
/// The pending fence values have to be ascending.
active: Vec<(crate::FenceValue, vk::Fence)>,
free: Vec<vk::Fence>,
}
impl Fence {
fn get_latest(&self, device: &ash::Device) -> Result<crate::FenceValue, crate::DeviceError> {
let mut max_value = self.last_completed;
for &(value, raw) in self.active.iter() {
unsafe {
if value > max_value && device.get_fence_status(raw)? {
max_value = value;
}
}
}
Ok(max_value)
}
fn maintain(&mut self, device: &ash::Device) -> Result<(), crate::DeviceError> {
let latest = self.get_latest(device)?;
let base_free = self.free.len();
for &(value, raw) in self.active.iter() {
if value <= latest {
self.free.push(raw);
}
}
self.active.retain(|&(value, _)| value > latest);
unsafe {
device.reset_fences(&self.free[base_free..])?;
}
Ok(())
}
}
impl crate::Queue<Api> for Queue {
unsafe fn submit(
&mut self,
command_buffers: &[&CommandBuffer],
signal_fence: Option<(&mut Resource, crate::FenceValue)>,
) -> DeviceResult<()> {
signal_fence: Option<(&mut Fence, crate::FenceValue)>,
) -> Result<(), crate::DeviceError> {
let fence_raw = match signal_fence {
Some((fence, value)) => {
fence.maintain(&self.device.raw)?;
let raw = match fence.free.pop() {
Some(raw) => raw,
None => {
let vk_info = vk::FenceCreateInfo::builder().build();
self.device.raw.create_fence(&vk_info, None)?
}
};
fence.active.push((value, raw));
raw
}
None => vk::Fence::null(),
};
let vk_cmd_buffers = command_buffers
.iter()
.map(|cmd| cmd.raw)
.collect::<Vec<_>>();
//TODO: semaphores
let vk_info = vk::SubmitInfo::builder()
.command_buffers(&vk_cmd_buffers)
.build();
self.device
.raw
.queue_submit(self.raw, &[vk_info], fence_raw)?;
Ok(())
}
unsafe fn present(
&mut self,
surface: &mut Surface,
texture: SurfaceTexture,
) -> Result<(), crate::SurfaceError> {
let ssc = surface.swapchain.as_ref().unwrap();
let swapchains = [ssc.raw];
let image_indices = [texture.index];
let vk_info = vk::PresentInfoKHR::builder()
.swapchains(&swapchains)
.image_indices(&image_indices);
let suboptimal = self
.swapchain_fn
.queue_present(self.raw, &vk_info)
.map_err(|error| match error {
vk::Result::ERROR_OUT_OF_DATE_KHR => crate::SurfaceError::Outdated,
vk::Result::ERROR_SURFACE_LOST_KHR => crate::SurfaceError::Lost,
_ => crate::DeviceError::from(error).into(),
})?;
if suboptimal {
log::warn!("Suboptimal present of frame {}", texture.index);
}
Ok(())
}
}