use std::{
mem::ManuallyDrop,
sync::{Arc, Mutex, OnceLock},
};
use crate::{Error, Result, runtime::dna::kernel::KernelId};
pub(in crate::runtime) mod buffer;
pub(in crate::runtime) mod command;
pub(in crate::runtime) mod commands;
pub(in crate::runtime) mod descriptor;
pub(in crate::runtime) mod dispatch;
pub(in crate::runtime) mod image;
pub(crate) mod pipeline;
pub(in crate::runtime) mod pqc;
pub(in crate::runtime) mod retirement;
#[cfg_attr(
not(test),
expect(
dead_code,
reason = "private PQC storage substrate; secret algorithms are not admitted"
)
)]
pub(in crate::runtime) mod secret_buffer;
pub(in crate::runtime) mod specialization;
pub(in crate::runtime) mod swapchain;
pub(in crate::runtime) mod timeline;
pub(in crate::runtime) mod timestamp;
pub(in crate::runtime) mod video;
pub(in crate::runtime) mod vkcache;
use buffer::RecycledBuffer;
use command::{CommandPool, CommandPoolKind};
use commands::{RenderingCommands, SyncCommands};
use descriptor::DescriptorHeap;
use pipeline::ComputePipeline;
use timeline::Timeline;
use super::{
configuration::DeviceConfiguration, features::ExecutionProfile, physical::DevicePhysical,
};
use crate::runtime::Instance;
pub(super) const MAX_RECYCLED_STORAGE_BUFFERS: usize = 256;
pub(super) const MAX_RECYCLED_STORAGE_BYTES: usize = 256 * 1024 * 1024;
pub(crate) struct SceneDrawCmd {
pub index_start: u32,
pub index_count: u32,
pub push_data: Vec<u8>,
pub material_set: vk::DescriptorSet,
pub is_blend: bool,
}
pub(in crate::runtime) enum FrameDraw {
Indexed {
vertex_buffer: vk::Buffer,
index_buffer: vk::Buffer,
index_count: u32,
},
Vertexless {
vertex_count: u32,
},
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(in crate::runtime) enum TileReduceOrder {
Default,
Deterministic,
Throughput,
}
pub(in crate::runtime) struct DeviceLogical {
pub(super) handle: ManuallyDrop<std::sync::Arc<vk::Device>>,
pub(super) sync_commands: SyncCommands,
pub(super) rendering_commands: RenderingCommands,
pub(super) allocator: ManuallyDrop<vk::mem::SynchronizedAllocator<'static>>,
pub(super) command_pool: Mutex<CommandPool>,
pub(super) graphics_command_pool: Mutex<Option<CommandPool>>,
pub(super) transfer_command_pool: Mutex<Option<CommandPool>>,
pub(super) video_decode_command_pool: Mutex<Option<CommandPool>>,
pub(super) video_encode_command_pool: Mutex<Option<CommandPool>>,
pub(super) timeline: Timeline,
pub(super) descriptors: DescriptorHeap,
pub(super) storage_pool: Mutex<StoragePool>,
pub(super) pipelines: Vec<Option<OnceLock<ComputePipeline>>>,
pub(super) pipeline_creation: Mutex<PipelineCreation>,
pub(super) jit: Mutex<specialization::JitFusion>,
pub(super) extensions: Mutex<std::collections::HashMap<Vec<u8>, Arc<pipeline::ComputePipeline>>>,
pub(super) fusion_census: crate::runtime::dna::fusion::census::FusionCensus,
pub(super) tape_bound_elements: u32,
pub(super) single_head_sdpa_route: bool,
pub(super) submission_budget_ns: u64,
pub(super) compute_queue: vk::Queue,
pub(super) graphics_queue: Option<vk::Queue>,
pub(super) transfer_queue: Option<vk::Queue>,
pub(super) video_decode_queue: Option<vk::Queue>,
pub(super) video_encode_queue: Option<vk::Queue>,
pub(super) timestamp_period_ns: f64,
pub(super) compute_timestamp_valid_bits: u32,
}
#[derive(Default)]
pub(super) struct StoragePool {
pub(super) free: Vec<RecycledBuffer>,
pub(super) bytes: usize,
}
pub(super) struct PipelineCreation {
pub(super) cache: Option<pipeline::PipelineCache>,
}
pub(in crate::runtime) struct PipelineCacheGuard<'a> {
pub(in crate::runtime::device) _guard: std::sync::MutexGuard<'a, PipelineCreation>,
pub(in crate::runtime::device) raw: vk::PipelineCache,
}
impl PipelineCacheGuard<'_> {
pub(in crate::runtime) const fn raw(&self) -> vk::PipelineCache {
self.raw
}
}
impl DeviceLogical {
pub(super) fn new(
instance: &Instance,
physical: &DevicePhysical,
configuration: &DeviceConfiguration,
) -> Result<Self> {
let shader_requirements = KernelId::ALL
.into_iter()
.map(|kernel| kernel.artifact().requirements())
.collect::<Result<Vec<_>>>()?;
let handle = std::sync::Arc::new(configuration.create_device(instance, physical.handle)?);
let sync_commands = SyncCommands::new(instance, &handle, physical.api_version);
let rendering_commands = RenderingCommands::new(instance, &handle, physical.api_version);
let compute_queue =
unsafe { handle.get_device_queue(physical.compute_queue_family, 0) }.map_err(Error::from)?;
let graphics_queue = physical
.graphics_queue_family
.map(|family| {
unsafe { handle.get_device_queue(family, 0) }.map_err(Error::from)
})
.transpose()?;
let video_decode_queue = physical
.video
.decode_queue_family
.map(|family| {
unsafe { handle.get_device_queue(family, 0) }.map_err(Error::from)
})
.transpose()?;
let video_encode_queue = physical
.video
.encode_queue_family
.map(|family| {
unsafe { handle.get_device_queue(family, 0) }.map_err(Error::from)
})
.transpose()?;
let transfer_queue = physical
.transfer_queue_family
.filter(|family| *family != physical.compute_queue_family)
.map(|family| {
unsafe { handle.get_device_queue(family, 0) }.map_err(Error::from)
})
.transpose()?;
let mut command_pool = match CommandPool::new(
&handle,
physical.compute_queue_family,
CommandPoolKind::Compute,
) {
Ok(command_pool) => command_pool,
Err(error) => {
if let Some(device) = std::sync::Arc::into_inner(handle) {
unsafe {
device.destroy(None);
}
}
return Err(error);
}
};
let mut timeline = match Timeline::new(&handle) {
Ok(timeline) => timeline,
Err(error) => {
command_pool.destroy(&handle);
if let Some(device) = std::sync::Arc::into_inner(handle) {
unsafe {
device.destroy(None);
}
}
return Err(error);
}
};
let allocator = match unsafe {
vk::mem::Allocator::new_retained_from_physical_device(
instance.raw(),
physical.handle,
handle.clone(),
)
} {
Ok(allocator) => allocator,
Err(source) => {
timeline.destroy(&handle);
command_pool.destroy(&handle);
if let Some(device) = std::sync::Arc::into_inner(handle) {
unsafe {
device.destroy(None);
}
}
return Err(Error::backend_failure(
"Vulkan",
"memory-allocator creation",
source,
));
}
};
let allocator = vk::mem::SynchronizedAllocator::new_owned(allocator);
let descriptors = match DescriptorHeap::new(&handle, physical.limits) {
Ok(descriptors) => descriptors,
Err(error) => {
unsafe {
let _ = allocator.with_allocator(|a| a.close());
}
drop(allocator);
timeline.destroy(&handle);
command_pool.destroy(&handle);
if let Some(device) = std::sync::Arc::into_inner(handle) {
unsafe {
device.destroy(None);
}
}
return Err(error);
}
};
let timestamp_period_ns = physical.limits.timestamp_period_ns;
let compute_timestamp_valid_bits = physical.limits.compute_timestamp_valid_bits;
let pipeline_cache = pipeline::PipelineCache::open(&handle, physical);
let mut logical = Self {
handle: ManuallyDrop::new(handle),
sync_commands,
rendering_commands,
allocator: ManuallyDrop::new(allocator),
command_pool: Mutex::new(command_pool),
graphics_command_pool: Mutex::new(None),
transfer_command_pool: Mutex::new(None),
video_decode_command_pool: Mutex::new(None),
video_encode_command_pool: Mutex::new(None),
timeline,
descriptors,
storage_pool: Mutex::new(StoragePool::default()),
pipelines: Vec::with_capacity(KernelId::ALL.len()),
pipeline_creation: Mutex::new(PipelineCreation {
cache: pipeline_cache,
}),
jit: Mutex::new(specialization::JitFusion::new()),
extensions: Mutex::new(std::collections::HashMap::new()),
fusion_census: crate::runtime::dna::fusion::census::FusionCensus::new(),
tape_bound_elements: crate::runtime::dna::fusion::tape_bound_seed(&physical.device_info()),
single_head_sdpa_route: crate::runtime::dna::fusion::single_head_sdpa_seed(
&physical.device_info(),
),
submission_budget_ns: crate::runtime::graph::executable::submission_budget_seed(
&physical.device_info(),
),
compute_queue,
graphics_queue,
transfer_queue,
video_decode_queue,
video_encode_queue,
timestamp_period_ns,
compute_timestamp_valid_bits,
};
for (kernel, requirements) in KernelId::ALL.into_iter().zip(shader_requirements) {
if !configuration
.missing_shader_requirements(
physical.limits.subgroup_supported_stages,
physical.limits.subgroup_supported_operations,
requirements,
)
.is_empty()
{
logical.pipelines.push(None);
continue;
}
let artifact = kernel.artifact();
if artifact.workgroup_memory_size()? > physical.limits.max_compute_shared_memory_size {
logical.pipelines.push(None);
continue;
}
if physical.profile == ExecutionProfile::Compatibility
&& logical
.descriptors
.bounded_layout(kernel.bounded_buffer_count())
.is_none()
{
logical.pipelines.push(None);
continue;
}
match pipeline::validate_artifact_limits(
artifact.workgroup_size,
artifact.push_constant_size()?,
physical.limits,
) {
Ok(()) => {}
Err(error) if error.kind() == crate::ErrorKind::MissingCapability => {
logical.pipelines.push(None);
continue;
}
Err(error) => return Err(error),
}
logical.pipelines.push(Some(OnceLock::new()));
}
Ok(logical)
}
pub(super) fn pipeline_cache_data(&self) -> Option<Vec<u8>> {
self
.pipeline_creation
.lock()
.ok()?
.cache
.as_ref()?
.data()
.ok()
}
}
impl Drop for DeviceLogical {
fn drop(&mut self) {
let storage_pool = match self.storage_pool.get_mut() {
Ok(pool) => pool,
Err(poisoned) => poisoned.into_inner(),
};
for mut buffer in storage_pool.free.drain(..) {
unsafe {
let _ = self
.allocator
.with_allocator(|allocator| allocator.free(&mut buffer.allocation));
let _ = self.handle.destroy_buffer(buffer.handle, None);
}
}
let jit = self
.jit
.get_mut()
.unwrap_or_else(|poisoned| poisoned.into_inner());
drop(std::mem::replace(jit, specialization::JitFusion::new()));
for slot in self.pipelines.iter_mut().flatten() {
if let Some(mut pipeline) = slot.take() {
pipeline.destroy(&self.handle);
}
}
let creation = match self.pipeline_creation.get_mut() {
Ok(creation) => creation,
Err(poisoned) => poisoned.into_inner(),
};
creation.cache.take();
self.descriptors.destroy(&self.handle);
unsafe {
let _ = self.allocator.with_allocator(|allocator| allocator.close());
ManuallyDrop::drop(&mut self.allocator);
}
self.timeline.destroy(&self.handle);
let command_pool = match self.command_pool.get_mut() {
Ok(command_pool) => command_pool,
Err(poisoned) => poisoned.into_inner(),
};
command_pool.destroy(&self.handle);
let video_decode_pool = match self.video_decode_command_pool.get_mut() {
Ok(pool) => pool,
Err(poisoned) => poisoned.into_inner(),
};
if let Some(pool) = video_decode_pool.as_mut() {
pool.destroy(&self.handle);
}
let video_encode_pool = match self.video_encode_command_pool.get_mut() {
Ok(pool) => pool,
Err(poisoned) => poisoned.into_inner(),
};
if let Some(pool) = video_encode_pool.as_mut() {
pool.destroy(&self.handle);
}
let graphics_pool = match self.graphics_command_pool.get_mut() {
Ok(pool) => pool,
Err(poisoned) => poisoned.into_inner(),
};
if let Some(pool) = graphics_pool.as_mut() {
pool.destroy(&self.handle);
}
if let Some(device) =
std::sync::Arc::into_inner(unsafe { ManuallyDrop::take(&mut self.handle) })
{
unsafe {
device.destroy(None);
}
}
}
}
#[cfg(test)]
#[path = "../../../../../test/rs/runtime/device_logical_unit.rs"]
mod tests;
#[cfg(test)]
#[path = "../../../../../test/rs/runtime/jit_device_unit.rs"]
mod jit_lab;