From 21a01a4d7b17dace817aa81e4cbdeb5b850c1eec Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 11 Nov 2026 07:56:33 -0800 Subject: [PATCH] Device creation: a device the driver refuses for want of resources takes its least queue plan once, else Error::DeviceRefused What: create_on makes the device through made_within_resources. Where vkCreateDevice answers VK_ERROR_INITIALIZATION_FAILED or VK_ERROR_OUT_OF_DEVICE_MEMORY for the queue plan's VkQueues and the least plan (LEAST_QUEUE_LIMITS: a round robin of one VkQueue, none reserved for presenting; the reserved, extra and staging queues kept, as DeviceOptions::queue_limits of one and none places them) takes fewer, it asks once more with the least plan's. A device made so announces the new Performance degradation least-queue-plan (Degradation::LeastQueuePlan, naming both plans' VkQueues and the driver's answer), sends none of the queue limits' informational messages (the limits are the runtime's, not the caller's), and its presenting queue's shared-present-queue notice says why it reserved none. A second refusal, or one where the least plan takes no fewer (RADV's and lavapipe's one graphics queue), is the new typed Error::DeviceRefused(DeviceRefused { device, attempts }), naming each attempt's VkQueues and answer; before, it was Error::Vulkan(-3) or Error::OutOfMemory(Device). Any other failure is the driver's as before. A recovery's new VkDevice is made the same way. Why: on an RTX 2080 (NVIDIA 620.70.06) devices of the plan's 17 VkQueues were refused from the eighth live one, in one process and across processes alike (tests::many_devices at 655ed906fb: seven made, p8 to p16 refused with VK_ERROR_INITIALIZATION_FAILED while BAR1 had 38 MiB free), where a consumer measured the GPU's channel heap holding about 160 to 180 channels, raw 16-queue devices refused from the 11th and 1-queue devices made 24 of 24. Public surface (api_signatures.tsv blessed): Error::DeviceRefused and DeviceRefused are new, and Degradation::LeastQueuePlan. A consumer that matched Error::Vulkan or Error::OutOfMemory from Device::system_default* for a refused device now gets Error::DeviceRefused. Tests: tests::queue_limits::a_device_refused_for_want_of_resources_is_asked_for_once_with_its_least_plan (no device: NVIDIA's family shape with a reserved and an extra queue, 18 VkQueues then 4; made at once, made with the least plan after either refusal, refused naming both attempts, any other failure the driver's, and one attempt where the least plan takes no fewer). tests::least_queue_plan (device tests, refuse_next_devices stands in for the driver's refusal on the creating thread): refused once, a device whose plan takes more than one VkQueue is made with 1 + 0 and announces least-queue-plan once, its presenting queue's shared-present-queue naming it; refused twice, it is Error::DeviceRefused with an attempt per plan. Verified on lavapipe (ms01, job m3-max-16047): both pass on the refused branch (llvmpipe's plan is one VkQueue: "ERROR_INITIALIZATION_FAILED with 1 VkQueue(s)"); the made branch runs on NVIDIA next. scripts/refusal-surface --check passes (REFUSALS.md does not list top-level Error variants). Docs: docs/API.md's catalogue entry for least-queue-plan; the runtime README's device opening (the fallback) and error table (DeviceRefused). RUNTIME_VERSION is the orchestrator's to bump at landing. --- crates/metal2vulkan-runtime/README.md | 12 + .../metal2vulkan-runtime/src/degradation.rs | 13 + .../metal2vulkan-runtime/src/device/adopt.rs | 1 + .../metal2vulkan-runtime/src/device/create.rs | 235 +++++++++++++++--- crates/metal2vulkan-runtime/src/device/mod.rs | 8 + crates/metal2vulkan-runtime/src/error.rs | 40 +++ crates/metal2vulkan-runtime/src/lib.rs | 4 +- crates/metal2vulkan-runtime/src/queue.rs | 16 +- .../src/tests/least_queue_plan.rs | 132 ++++++++++ crates/metal2vulkan-runtime/src/tests/mod.rs | 2 + .../src/tests/queue_limits.rs | 106 +++++++- crates/metal2vulkan/tests/api_signatures.tsv | 6 + docs/API.md | 10 + 13 files changed, 546 insertions(+), 39 deletions(-) create mode 100644 crates/metal2vulkan-runtime/src/tests/least_queue_plan.rs diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 16b382e23..9241a5062 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -193,6 +193,17 @@ Vulkan-side choices Metal has no counterpart for: | `lowering_refuses` | Degradation kinds that refuse a render encoder's call when its lowering after the call meets them (`RenderLoweringPolicy::Worker`), failing its command buffer, instead of being announced. Empty by default. | | `record_executions` | Keep, per command buffer, which pipeline each dispatch and draw ran (`CommandBuffer::executions`). Off by default. | +**A driver short of resources.** Where the driver refuses a device with its queue plan's `VkQueue`s +for want of its resources (`vkCreateDevice` answering `VK_ERROR_INITIALIZATION_FAILED` or +`VK_ERROR_OUT_OF_DEVICE_MEMORY`: on NVIDIA's driver, other devices of the GPU, in this process or +others, holding its channels or its BAR), the runtime asks once more with its least plan's: a round +robin of one `VkQueue` and none reserved for presenting, the reserved, extra and staging queues +kept (`queue_limits` of one and none, without that option's messages). A device made so announces +`metal2vulkan-degrade-least-queue-plan` once, as it is made: its command queues share that one +`VkQueue`. A device the driver refuses again, or whose least plan takes no fewer queues, is refused, +`Error::DeviceRefused`. On an RTX 2080 and an RTX 3090 (NVIDIA 620.70.06) one process made seven +devices of the plan's 17 `VkQueue`s and the driver refused the eighth. + While a handle lives, equal options give the same device for a physical device, as Metal has one `MTLDevice` per GPU. Nothing is read from the environment but the platform's default cache directory. `Device::registry_ids_with` lists each qualifying physical device's `registryID`, @@ -674,6 +685,7 @@ message text. The ones a consumer meets most: | `OutOfMemory`, `DeviceLost`, `Vulkan`, `NoDevice` | The device's own failures. `NoDevice`: the loader opened but found no usable device. A device holding `maxMemoryAllocationCount` allocations live has the next refused (`Vulkan`, `VK_ERROR_TOO_MANY_OBJECTS`) without a call of the driver, counted in `WorkCounts::memory_allocations_refused_at_limit`, once the frees its releases posted to its free thread (which count until they run) completed. | | `LoaderNotFound(LoaderNotFound)` | The Vulkan loader did not open; `tried` lists each path. | | `DriverSetting(DriverSetting)` | A driver setting the runtime cannot run under, such as MoltenVK with `MVK_CONFIG_USE_METAL_ARGUMENT_BUFFERS` off. | +| `DeviceRefused(DeviceRefused)` | The driver refused to make the device for want of its resources (`VK_ERROR_INITIALIZATION_FAILED` or `VK_ERROR_OUT_OF_DEVICE_MEMORY`), with its queue plan's `VkQueue`s and then with its least plan's; `attempts` names each. Other devices of the GPU, in any process, hold what it lacks; once fewer are live it may be made. | | `WaitWouldDeadlock(DeadlockCause)` | A command buffer wait that would deadlock, refused at once instead of hanging. | | `ShaderCache(...)` | The shader cache directory cannot be made or written. | diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 3c83b501a..6bd08e067 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2240,6 +2240,19 @@ degradations! { "the driver keeps its own cache of the device's pipelines beside the shader cache's \ records, with whatever it writes to disk and holds in memory for it; the pipelines \ made are the same"; + /// A device the driver refused to make for want of its resources with the `VkQueue`s of + /// its queue plan (`vkCreateDevice` answering `VK_ERROR_INITIALIZATION_FAILED` or + /// `VK_ERROR_OUT_OF_DEVICE_MEMORY`: on NVIDIA's driver, other devices of the GPU, in this + /// process or others, holding its channels or its BAR), made with those of its least + /// plan: a round robin of one `VkQueue` and none reserved for presenting, beside the + /// plan's reserved, extra and staging queues (`DeviceOptions::queue_limits` of one and + /// none, without its informational messages). Announced once, as the device is made; the + /// payload names the device, the `VkQueue`s of each plan and the driver's answer. A device + /// the driver refuses with its least plan too is refused (`Error::DeviceRefused`). + LeastQueuePlan = "least-queue-plan", Performance, + "its command queues, presenting ones included, share one `VkQueue`, so one queue's \ + command buffers wait behind another's whole command buffer where Metal's run beside \ + each other; what each command buffer does is the same"; /// A device whose `VkDevice` was lost made a new one behind it, as Metal's device /// survives its GPU's recovery (`device/line.rs`): its command buffers in flight failed, /// the oldest incomplete one as the hang (`GpuHang`) and the rest as its victims diff --git a/crates/metal2vulkan-runtime/src/device/adopt.rs b/crates/metal2vulkan-runtime/src/device/adopt.rs index 05547a915..f0c11389b 100644 --- a/crates/metal2vulkan-runtime/src/device/adopt.rs +++ b/crates/metal2vulkan-runtime/src/device/adopt.rs @@ -330,6 +330,7 @@ impl Device { queues: vec![(raw.queue_family, raw.queue_index)], present_queues: 0, planned: None, + least_plan: false, staging: None, reserved_queues: Vec::new(), extra_queues: Vec::new(), diff --git a/crates/metal2vulkan-runtime/src/device/create.rs b/crates/metal2vulkan-runtime/src/device/create.rs index ef4e573f6..ca67cb213 100644 --- a/crates/metal2vulkan-runtime/src/device/create.rs +++ b/crates/metal2vulkan-runtime/src/device/create.rs @@ -36,7 +36,9 @@ use super::properties::{DeviceKind, PhysicalDeviceIdentity}; use super::{device_error, holds, lock, Device, InstanceShared, Parts}; use crate::degradation::{Degradation, DegradeNotice, Told}; use crate::enables::{host_image_copy_names, listed_reported, listed_structures, Enables}; -use crate::error::{vulkan, Error, InstanceApiVersion, LoaderNotFound}; +use crate::error::{ + vulkan, DeviceRefused, Error, InstanceApiVersion, LoaderNotFound, VkResultCode, +}; use crate::exit_guard; use crate::gpu_time; use crate::image_barrier::MemoryReads; @@ -1280,6 +1282,159 @@ pub(crate) struct PlannedQueues { pub(crate) extra: Vec>, } +/// A device's queues: its queue plan, and its extra queues' places +/// (`DeviceOptions::extra_queues`, [`extra_queue_places`]), `None` for one the device has none of. +pub(crate) type PlacedQueues = (QueuePlan, Vec>); + +/// The queue limits of a device's least queue plan ([`made_within_resources`]): a round robin of +/// one `VkQueue`, none reserved for presenting. +pub(crate) const LEAST_QUEUE_LIMITS: QueueLimits = QueueLimits { + round_robin: 1, + presenting: 0, +}; + +/// The least queue plan of a device of `families` made with `options`, its textures' images in +/// memory the host caches or not (`cached`, as [`queue_plan`] takes it): the plan within +/// [`LEAST_QUEUE_LIMITS`], with the reserved and extra queues `options` asks for, placed as +/// [`extra_queue_places`] places them. +pub(crate) fn least_queue_plan( + families: &[vk::QueueFamilyProperties], + options: &DeviceOptions, + cached: bool, +) -> Option { + let limits = Some(LEAST_QUEUE_LIMITS); + let mut plan = queue_plan_within(families, options.reserved_queues, limits, cached)?; + let extra = extra_queue_places(families, &mut plan, &options.extra_queues); + Some((plan, extra)) +} + +/// The `VkQueue`s a device of `placed` makes: its round robin's, those reserved for presenting +/// and for the caller, its staging queue and its extra queues. +pub(crate) fn vk_queues((plan, extra): &PlacedQueues) -> usize { + plan.queues.len() + + plan.present.len() + + plan.reserved.len() + + usize::from(plan.staging.is_some()) + + extra.iter().flatten().count() +} + +/// The families a device of `plan` and `extra_places` takes queues of, each with how many: one +/// `VkDeviceQueueCreateInfo` each. +fn families_taken(plan: &QueuePlan, extra_places: &[Option<(u32, u32)>]) -> Vec<(u32, usize)> { + let mut taken: Vec<(u32, usize)> = Vec::new(); + let all = (plan.queues.iter().chain(&plan.present)) + .chain(&plan.reserved) + .chain(&plan.staging) + .chain(extra_places.iter().flatten()); + for &(family, _) in all { + match taken.iter_mut().find(|(at, _)| *at == family) { + Some((_, count)) => *count += 1, + None => taken.push((family, 1)), + } + } + taken +} + +/// A device made with its least queue plan's `VkQueue`s, the driver having refused its queue +/// plan's ([`made_within_resources`], `Degradation::LeastQueuePlan`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct LeastPlanTaken { + /// The `VkQueue`s of the queue plan. + pub(crate) planned: usize, + /// The driver's answer to them. + pub(crate) refusal: vk::Result, + /// The `VkQueue`s of the least plan, which the device took. + pub(crate) least: usize, +} + +/// Whether `result` is a driver's refusal of a device for want of its resources: +/// `VK_ERROR_INITIALIZATION_FAILED` (NVIDIA's driver, its GPU's channels or BAR taken by other +/// devices) or `VK_ERROR_OUT_OF_DEVICE_MEMORY`. +fn for_want_of_resources(result: vk::Result) -> bool { + matches!( + result, + vk::Result::ERROR_INITIALIZATION_FAILED | vk::Result::ERROR_OUT_OF_DEVICE_MEMORY + ) +} + +/// The device `make` makes with the queues of `planned`, with them and `None`; where the driver +/// refuses it for want of its resources ([`for_want_of_resources`]) and `least`, the least queue +/// plan's queues ([`least_queue_plan`]), takes fewer `VkQueue`s ([`vk_queues`]), the device made +/// once more with `least`'s, with them and what it took ([`LeastPlanTaken`]). On an RTX 2080 +/// (NVIDIA 620.70.06) one process made seven devices of the plan's 17 `VkQueue`s, and the driver +/// refused the eighth (`VK_ERROR_INITIALIZATION_FAILED`). Refused, naming the device (`device`) +/// and each attempt +/// ([`Error::DeviceRefused`]), where the driver refuses the least plan's for want of resources +/// too, or where the least plan takes no fewer; any other failure is the driver's +/// ([`vulkan`]). +pub(crate) fn made_within_resources( + device: &str, + planned: PlacedQueues, + least: Option, + mut make: impl FnMut(&PlacedQueues) -> Result, +) -> Result<(D, PlacedQueues, Option), Error> { + let refusal = match make(&planned) { + Ok(made) => return Ok((made, planned, None)), + Err(result) if for_want_of_resources(result) => result, + Err(result) => return Err(vulkan(result)), + }; + let asked = vk_queues(&planned); + let refused = |attempts: &[(usize, vk::Result)]| { + Error::DeviceRefused(DeviceRefused { + device: device.to_owned(), + attempts: (attempts.iter()) + .map(|&(queues, result)| (queues, VkResultCode(result.as_raw()))) + .collect(), + }) + }; + let Some(least) = least.filter(|least| vk_queues(least) < asked) else { + return Err(refused(&[(asked, refusal)])); + }; + let fewer = vk_queues(&least); + match make(&least) { + Ok(made) => { + let taken = LeastPlanTaken { + planned: asked, + refusal, + least: fewer, + }; + Ok((made, least, Some(taken))) + } + Err(result) if for_want_of_resources(result) => { + Err(refused(&[(asked, refusal), (fewer, result)])) + } + Err(result) => Err(vulkan(result)), + } +} + +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +thread_local! { + /// How many of the next `vkCreateDevice` calls of this thread a test refuses before they + /// reach the driver ([`refuse_next_devices`]). + static REFUSED: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Refuse this thread's next `count` `vkCreateDevice` calls as the driver refuses one for want of +/// its resources (`VK_ERROR_INITIALIZATION_FAILED`): a test's stand-in for a GPU whose other +/// devices hold its channels ([`made_within_resources`]). +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +pub(crate) fn refuse_next_devices(count: u32) { + REFUSED.with(|refused| refused.set(count)); +} + +/// The stand-in's refusal of this `vkCreateDevice` call, where [`refuse_next_devices`] asked for +/// one. +#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] +fn refusal_stand_in() -> Option { + REFUSED.with(|refused| { + let left = refused.get(); + (left > 0).then(|| { + refused.set(left - 1); + vk::Result::ERROR_INITIALIZATION_FAILED + }) + }) +} + /// Whether the `made`th queue counted from 0 of the round robin, or of the presenting queues, /// that the limits give `limited` `VkQueue`s takes one another took where the plan's `planned` /// give it one of its own (`DeviceOptions::queue_limits`). @@ -1904,7 +2059,6 @@ pub(super) fn create_on( cached, ) }); - let reserved_places = plan.reserved.clone(); let queue_family = plan.primary; let api = description.api_version; let mut set = enable_set(&description, options); @@ -2102,34 +2256,32 @@ pub(super) fn create_on( sparse::device::wanted(&available) }); enables.enable_sparse(&sparse_features); - // One create info per family taken, of as many queues as the plan takes of it. - let mut taken: Vec<(u32, usize)> = Vec::new(); - let extra: Vec<(u32, u32)> = extra_places.iter().flatten().copied().collect(); - let all = (plan.queues.iter().chain(&plan.present)) - .chain(&plan.reserved) - .chain(&plan.staging); - for &(family, _) in all.chain(&extra) { - match taken.iter_mut().find(|(at, _)| *at == family) { - Some((_, count)) => *count += 1, - None => taken.push((family, 1)), + // The device of the plan's queues, else, where the driver refuses it for want of its + // resources, of the least plan's (`made_within_resources`). + let least = least_queue_plan(&families, options, cached); + let make = |(plan, extra_places): &PlacedQueues| { + #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] + if let Some(refused) = refusal_stand_in() { + return Err(refused); } - } - // One priority per queue of the family the plan and the extra queues take most of, so the - // slice each create info names is always within it: the round robin alone takes up to - // `ROUND_ROBIN_CEILING` of one family, presenting `PRESENT_QUEUES` more, and the reserved and - // extra queues at most the family's own count. - let priorities = vec![1.0f32; taken.iter().map(|&(_, count)| count).max().unwrap_or(0)]; - let queues: Vec> = taken - .iter() - .map(|&(family, count)| { - vk::DeviceQueueCreateInfo::default() - .queue_family_index(family) - .queue_priorities(&priorities[..count]) - }) - .collect(); - // At the user-initiated class: MoltenVK compiles its command shaders as it makes the device. - let raw = enables - .with_create_info(&queues, |info| { + // One create info per family taken, of as many queues as the plan takes of it. + let taken = families_taken(plan, extra_places); + // One priority per queue of the family the plan and the extra queues take most of, so + // the slice each create info names is always within it: the round robin alone takes up + // to `ROUND_ROBIN_CEILING` of one family, presenting `PRESENT_QUEUES` more, and the + // reserved and extra queues at most the family's own count. + let priorities = vec![1.0f32; taken.iter().map(|&(_, count)| count).max().unwrap_or(0)]; + let queues: Vec> = taken + .iter() + .map(|&(family, count)| { + vk::DeviceQueueCreateInfo::default() + .queue_family_index(family) + .queue_priorities(&priorities[..count]) + }) + .collect(); + // At the user-initiated class: MoltenVK compiles its command shaders as it makes the + // device. + enables.with_create_info(&queues, |info| { let asked = super::compiles::Sent::new(info); let instance = &instance.raw; super::compiles::at_user_initiated(move || { @@ -2138,7 +2290,13 @@ pub(super) fn create_on( unsafe { instance.create_device(physical, asked.into_inner(), None) } }) }) - .map_err(vulkan)?; + }; + let name = &enabled.device_name; + let (raw, (plan, extra_places), took_least) = + made_within_resources(name, (plan, extra_places), least, make)?; + // The least plan's queues are the runtime's own choice, not the caller's limits: no limits' + // messages ([`LeastPlanTaken`]). + let planned = planned.filter(|_| took_least.is_none()); // SAFETY: the device was just created: its word is the loader's. let loader_word = unsafe { DeviceWord::of_device(raw.handle()) }; let primary = families.get(queue_family as usize); @@ -2147,6 +2305,7 @@ pub(super) fn create_on( enables.names(), ); let reserved = plan.reserved.len(); + let plan_reserved = plan.reserved.clone(); let parts = Parts { instance: Arc::clone(instance), physical, @@ -2155,6 +2314,7 @@ pub(super) fn create_on( queue_family, present_queues: plan.present.len(), planned: (planned.as_ref()).map(|planned| (planned.round_robin, planned.presenting)), + least_plan: took_least.is_some(), queues: plan.queues.into_iter().chain(plan.present).collect(), staging: plan.staging, reserved_queues: plan.reserved, @@ -2219,8 +2379,21 @@ pub(super) fn create_on( if let Some(text) = reserved_queues_absent(options.reserved_queues, reserved, device.name()) { device.inform(RESERVED_QUEUES_ABSENT, text); } + if let Some(taken) = took_least { + device.degrade(Degradation::LeastQueuePlan, || { + ( + format!("the device, on {}", device.name()), + format!( + "the driver refused it with its queue plan's {} VkQueue(s) ({:?}); it took \ + its least plan's {}", + taken.planned, taken.refusal, taken.least + ), + ) + }); + } + let reserved_places = &plan_reserved; if let Some(planned) = &planned { - if planned.reserved != reserved_places { + if planned.reserved != *reserved_places { device.inform_once(Told::QueueLimitsReached, QUEUE_LIMITS_REACHED, || { let what = format!( "the queues reserved for the caller are {reserved_places:?} (family, index), \ diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index bd9c7d4f1..59c181723 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -278,6 +278,9 @@ pub(super) struct DeviceShared { /// queue plan's round robin and presenting `VkQueue`s: what the device's notes of the limits /// compare with (`Device::next_queue`). planned: Option<(usize, usize)>, + /// The driver refused the device with its queue plan's `VkQueue`s, and it took its least + /// plan's: the reason a presenting queue shares one (`Device::place_queue`). + pub(super) least_plan: bool, /// The presenting queues made so far, on a reserved `VkQueue` or not, counted only where /// `planned` is. presenting_asked: AtomicU64, @@ -1716,6 +1719,9 @@ pub(super) struct Parts { /// Where the device's queue limits changed its queues (`DeviceOptions::queue_limits`), the /// queue plan's round robin and presenting `VkQueue`s; `None` for an adopted device. pub(super) planned: Option<(usize, usize)>, + /// The driver refused the device with its queue plan's `VkQueue`s, and it took its least + /// plan's (`create.rs`'s `made_within_resources`, `Degradation::LeastQueuePlan`). + pub(super) least_plan: bool, /// The queue reserved for staging copies, its family and index there, outside `queues` /// (`staging.rs`): `None` for an adopted device, or where the families have no more. pub(super) staging: Option<(u32, u32)>, @@ -1843,6 +1849,7 @@ impl Device { queues: queue_places, present_queues, planned, + least_plan, staging: staging_place, reserved_queues: reserved_places, extra_queues: extra_places, @@ -2631,6 +2638,7 @@ impl Device { round_robin_made: AtomicU64::new(0), presenting_made: AtomicU64::new(0), planned, + least_plan, presenting_asked: AtomicU64::new(0), program_queues_made: AtomicU64::new(0), queue_switch: Arc::new(crate::queue_share::QueueSwitch::new( diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 09b8dd2db..6b8884c53 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -130,6 +130,10 @@ pub enum Error { /// A driver setting the runtime cannot run under, read from the device when it is made or /// adopted: the device is refused, naming the setting ([`DriverSetting`]). Turn it back on. DriverSetting(DriverSetting), + /// A device the driver refused to make for want of its resources, with its queue plan and + /// then its least one ([`DeviceRefused`]): other devices of the GPU hold them. Metal makes + /// the device. + DeviceRefused(DeviceRefused), /// What plain Metal answers nil for, the process going on: the call and the problem (the /// module's docs). Nil(Nil), @@ -207,6 +211,7 @@ impl fmt::Display for Error { Error::DynamicLibrary(error) => write!(f, "{error}"), Error::LoaderNotFound(missing) => write!(f, "{missing}"), Error::DriverSetting(setting) => write!(f, "{setting}"), + Error::DeviceRefused(refused) => write!(f, "{refused}"), Error::Nil(nil) => { write!(f, "Metal answers nil for {}: {:?}", nil.call, nil.problem) } @@ -390,6 +395,41 @@ impl fmt::Display for DriverSetting { } } +/// A device the driver refused to make for want of its resources ([`Error::DeviceRefused`]): +/// `vkCreateDevice` answered `VK_ERROR_INITIALIZATION_FAILED` or `VK_ERROR_OUT_OF_DEVICE_MEMORY` +/// for the `VkQueue`s of the device's queue plan, and again for those of its least plan (a round +/// robin of one `VkQueue` and none reserved for presenting, beside the plan's reserved, extra and +/// staging queues), or the least plan takes no fewer and the device was asked for once. Other +/// devices of the GPU, in this process or others, hold what the driver lacks: on NVIDIA's driver +/// its channels, one or more a `VkQueue`, and its BAR. Its counterpart, Metal's +/// `MTLCreateSystemDefaultDevice`, makes a device on its GPU however many processes use it; a +/// device asked for again once fewer are live may be made. +#[non_exhaustive] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DeviceRefused { + /// The device, by its Vulkan name (`VkPhysicalDeviceProperties::deviceName`). + pub device: String, + /// Each attempt in order, the queue plan's first: the `VkQueue`s it asked for and the + /// driver's answer. + pub attempts: Vec<(usize, VkResultCode)>, +} + +impl fmt::Display for DeviceRefused { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!( + f, + "the driver refused a device on {} for want of resources:", + self.device + )?; + for (i, &(queues, code)) in self.attempts.iter().enumerate() { + let separator = if i == 0 { " " } else { ", then " }; + let result = ash::vk::Result::from_raw(code.0); + write!(f, "{separator}{result:?} with {queues} VkQueue(s)")?; + } + Ok(()) + } +} + impl std::error::Error for Error {} /// A call plain Metal itself refuses, ending its process or failing the creation (the module's diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs index 86eb6c3ac..113b1b768 100644 --- a/crates/metal2vulkan-runtime/src/lib.rs +++ b/crates/metal2vulkan-runtime/src/lib.rs @@ -300,8 +300,8 @@ pub use error::NotInPlace; pub use error::Unproven; pub use error::{ ArchivedPipeline, BinaryArchiveError, BinaryArchiveMiss, CommandBufferError, DeadlockCause, - DriverSetting, EncoderCall, Error, InstanceApiVersion, Invalid, LoaderNotFound, MemoryKind, - MeshRecordsOverflow, Problem, RuntimeGap, SamplerLimit, ShaderCacheError, + DeviceRefused, DriverSetting, EncoderCall, Error, InstanceApiVersion, Invalid, LoaderNotFound, + MemoryKind, MeshRecordsOverflow, Problem, RuntimeGap, SamplerLimit, ShaderCacheError, TessellationRecordsOverflow, TimedOut, VkResultCode, }; pub use error::{FailedPipeline, FailedState, PipelineCreationCause}; diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs index a1185f2e6..09c82e0c6 100644 --- a/crates/metal2vulkan-runtime/src/queue.rs +++ b/crates/metal2vulkan-runtime/src/queue.rs @@ -517,11 +517,21 @@ impl Device { Some(reserved) => reserved, None => { self.degrade(Degradation::SharedPresentQueue, || { + let why = match self.shared().least_plan { + true => { + "the device reserved no `VkQueue` for presenting: the driver \ + refused its queue plan's, and it took its least plan's \ + (`least-queue-plan`)" + } + false => { + "the device reserved no `VkQueue` for presenting: its queue \ + families have no queue past the ones its other command queues \ + share" + } + }; ( "a command queue made for presenting".to_owned(), - "the device reserved no `VkQueue` for presenting: its queue families \ - have no queue past the ones its other command queues share" - .to_owned(), + why.to_owned(), ) }); self.next_queue(None) diff --git a/crates/metal2vulkan-runtime/src/tests/least_queue_plan.rs b/crates/metal2vulkan-runtime/src/tests/least_queue_plan.rs new file mode 100644 index 000000000..778f82bd3 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/least_queue_plan.rs @@ -0,0 +1,132 @@ +//! A device the driver refuses for want of its resources (`create.rs`'s `made_within_resources`, +//! the driver's refusal stood in for by `refuse_next_devices`): refused once, it is made with its +//! least queue plan's `VkQueue`s where that takes fewer, a round robin of one and none reserved +//! for presenting, and announces `least-queue-plan` once as it is made, its first presenting queue +//! sharing the round robin's `VkQueue` (`shared-present-queue`, saying why); where the least plan +//! takes no fewer (RADV's and lavapipe's one graphics queue), and wherever it is refused twice, +//! it is refused (`Error::DeviceRefused`), naming each attempt. Each test prints a +//! `LEAST-QUEUE-PLAN:` line with what the device took or the refusal, the evidence of the path +//! that ran. +//! +//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind +//! of device the cfg selects. + +use super::blit_holds::Scratch; +use crate::device::create::refuse_next_devices; +use crate::{ + Degradation, DegradeNotice, Device, DeviceKind, DeviceOptions, Error, MessageSink, + ShaderCacheOptions, +}; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +/// The notices a device's sink heard. +type Heard = Arc>>; + +/// The device the cfg selects, its shader cache in `cache` and a message sink of its own, so a +/// device of its own, whose notices go to `heard`. +fn device(cache: &Path, heard: &Heard) -> Result { + let heard = Arc::clone(heard); + let options = DeviceOptions { + kinds: match cfg!(m2v_cpu_icd) { + true => vec![DeviceKind::Cpu], + false => vec![DeviceKind::Discrete, DeviceKind::Integrated], + }, + shader_cache: ShaderCacheOptions { + directory: Some(cache.to_owned()), + ..ShaderCacheOptions::default() + }, + messages: Some(MessageSink::new(move |message| { + if let Some(notice) = &message.degradation { + heard.lock().unwrap().push(notice.clone()); + } + })), + ..DeviceOptions::default() + }; + Device::system_default_with(&options) +} + +/// The `VkQueue`s of `device`'s round robin and those reserved for presenting. +fn queues(device: &Device) -> (usize, usize) { + let shared = device.shared(); + let round_robin = shared.round_robin(); + (round_robin, shared.queues.len() - round_robin) +} + +/// The kinds `heard` heard, in order. +fn kinds(heard: &Heard) -> Vec { + (heard.lock().unwrap().iter()) + .map(|notice| notice.degradation) + .collect() +} + +#[test] +fn a_device_refused_once_takes_its_least_plan_where_it_takes_fewer_queues() { + let scratch = Scratch::new("least-queue-plan-once"); + // The device as its plan makes it, beside which the refused one is made. + let planned = device(&scratch.0.join("planned"), &Heard::default()).unwrap(); + let (round_robin, presenting) = queues(&planned); + let heard = Heard::default(); + refuse_next_devices(1); + let made = device(&scratch.0.join("refused"), &heard); + match made { + Ok(device) => { + println!( + "LEAST-QUEUE-PLAN: {} took 1 + 0 of the plan's {round_robin} + {presenting}", + device.name() + ); + assert!(round_robin + presenting > 1, "the least plan took no fewer"); + assert_eq!(queues(&device), (1, 0)); + let least: Vec = (heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::LeastQueuePlan) + .cloned() + .collect(); + assert_eq!(least.len(), 1, "{least:?}"); + assert!( + least[0].reason.contains("ERROR_INITIALIZATION_FAILED"), + "{least:?}" + ); + // A presenting queue shares the round robin's `VkQueue`, saying why. + let _present = device.new_command_queue_for_presenting().unwrap(); + let shared: Vec = (heard.lock().unwrap().iter()) + .filter(|notice| notice.degradation == Degradation::SharedPresentQueue) + .cloned() + .collect(); + assert_eq!(shared.len(), 1, "{shared:?}"); + assert!(shared[0].reason.contains("least-queue-plan"), "{shared:?}"); + } + Err(Error::DeviceRefused(refused)) => { + println!("LEAST-QUEUE-PLAN: refused, its least plan the plan: {refused}"); + assert_eq!(round_robin + presenting, 1, "{refused}"); + assert_eq!(refused.attempts.len(), 1, "{refused}"); + assert!(!kinds(&heard).contains(&Degradation::LeastQueuePlan)); + } + Err(error) => panic!("the device: {error}"), + } +} + +#[test] +fn a_device_refused_twice_is_refused_naming_each_attempt() { + let scratch = Scratch::new("least-queue-plan-twice"); + let planned = device(&scratch.0.join("planned"), &Heard::default()).unwrap(); + let (round_robin, presenting) = queues(&planned); + let heard = Heard::default(); + refuse_next_devices(2); + let made = device(&scratch.0.join("refused"), &heard); + let Err(Error::DeviceRefused(refused)) = made else { + panic!( + "a device refused twice: {:?}", + made.map(|device| queues(&device)) + ); + }; + println!("LEAST-QUEUE-PLAN: {refused}"); + let attempts = match round_robin + presenting > 1 { + true => 2, + false => 1, + }; + assert_eq!(refused.attempts.len(), attempts, "{refused}"); + assert_eq!(refused.device, planned.name()); + assert!(heard.lock().unwrap().is_empty(), "{:?}", kinds(&heard)); + // The refusal stood in for the driver's, which the next device meets no more. + refuse_next_devices(0); +} diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 5c851f0a4..13fa222ce 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -296,6 +296,8 @@ mod kernel_end_device; mod layer_claim; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod learned_coverage; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod least_queue_plan; mod left; mod linear_alignment; mod linear_attachment; diff --git a/crates/metal2vulkan-runtime/src/tests/queue_limits.rs b/crates/metal2vulkan-runtime/src/tests/queue_limits.rs index 6e3aaf232..60be09969 100644 --- a/crates/metal2vulkan-runtime/src/tests/queue_limits.rs +++ b/crates/metal2vulkan-runtime/src/tests/queue_limits.rs @@ -9,10 +9,11 @@ //! that a device sends exactly those messages, and none without limits. use crate::device::create::{ - extra_queue_places, planned_queues, queue_limits_reached, queue_plan, queue_plan_within, - shares_past_limit, PlannedQueues, QUEUE_LIMITS_REACHED, + extra_queue_places, least_queue_plan, made_within_resources, planned_queues, + queue_limits_reached, queue_plan, queue_plan_within, shares_past_limit, vk_queues, + LeastPlanTaken, PlacedQueues, PlannedQueues, LEAST_QUEUE_LIMITS, QUEUE_LIMITS_REACHED, }; -use crate::QueueLimits; +use crate::{DeviceOptions, DeviceRefused, Error, QueueLimits, VkResultCode}; use ash::vk; /// Every flag a graphics family of NVIDIA's, MoltenVK's or RADV's has. @@ -264,3 +265,102 @@ fn reserved_and_extra_queues_placed_otherwise_are_noted() { ); assert_eq!(QUEUE_LIMITS_REACHED, "metal2vulkan-queue-limits-reached"); } + +/// The queues a device of `families` takes with `options`: its queue plan's, and its extra +/// queues' places. +fn planned(families: &[vk::QueueFamilyProperties], options: &DeviceOptions) -> PlacedQueues { + let mut plan = queue_plan(families, options.reserved_queues, true).unwrap(); + let extra = extra_queue_places(families, &mut plan, &options.extra_queues); + (plan, extra) +} + +/// A device the driver refuses for want of its resources (`VK_ERROR_INITIALIZATION_FAILED`, +/// `VK_ERROR_OUT_OF_DEVICE_MEMORY`) with its queue plan's `VkQueue`s is asked for once more with +/// its least plan's (the lane's limits: one for the round robin, none for presenting, the +/// reserved, extra and staging queues kept), and made with them, saying what it took; refused +/// twice, it is refused naming both attempts, and where the least plan takes no fewer (RADV's and +/// lavapipe's one graphics queue) it is asked for once and refused naming it. Any other failure is +/// the driver's, asked for once, and a device made at once takes its plan. +#[test] +fn a_device_refused_for_want_of_resources_is_asked_for_once_with_its_least_plan() { + const FAILED: vk::Result = vk::Result::ERROR_INITIALIZATION_FAILED; + const MEMORY: vk::Result = vk::Result::ERROR_OUT_OF_DEVICE_MEMORY; + assert_eq!(LEAST_QUEUE_LIMITS, LEAN); + let options = DeviceOptions { + reserved_queues: 1, + extra_queues: vec![vk::QueueFlags::VIDEO_DECODE_KHR], + ..DeviceOptions::default() + }; + let families = nvidia(); + let plan = planned(&families, &options); + let least = least_queue_plan(&families, &options, true).unwrap(); + // NVIDIA's: 13 for the round robin, two presenting, one reserved, the copy engine's staging + // queue and the decode queue; then one for the round robin beside the last three. + assert_eq!((vk_queues(&plan), vk_queues(&least)), (18, 4)); + assert_eq!((least.0.queues.len(), least.0.present.len()), (1, 0)); + assert_eq!(least.0.reserved.len(), 1); + assert_eq!((least.0.staging, &least.1), (plan.0.staging, &plan.1)); + // Each call's answer in turn, and the queues each asked for. + let run = |answers: &[vk::Result]| { + let mut asked = Vec::new(); + let mut answers = answers.iter(); + let made = made_within_resources("a GPU", plan.clone(), Some(least.clone()), |placed| { + asked.push(vk_queues(placed)); + match answers.next() { + Some(&refused) => Err(refused), + None => Ok("made"), + } + }); + ( + made.map(|(made, placed, took)| (made, vk_queues(&placed), took)), + asked, + ) + }; + assert_eq!(run(&[]), (Ok(("made", 18, None)), vec![18])); + for refusal in [FAILED, MEMORY] { + let took = LeastPlanTaken { + planned: 18, + refusal, + least: 4, + }; + assert_eq!(run(&[refusal]), (Ok(("made", 4, Some(took))), vec![18, 4])); + } + let refused = |attempts: &[(usize, vk::Result)]| { + Error::DeviceRefused(DeviceRefused { + device: "a GPU".to_owned(), + attempts: (attempts.iter()) + .map(|&(queues, result)| (queues, VkResultCode(result.as_raw()))) + .collect(), + }) + }; + assert_eq!( + run(&[FAILED, MEMORY]), + (Err(refused(&[(18, FAILED), (4, MEMORY)])), vec![18, 4]) + ); + let other = vk::Result::ERROR_FEATURE_NOT_PRESENT; + let driver = Err(Error::Vulkan(VkResultCode(other.as_raw()))); + assert_eq!(run(&[other]), (driver.clone(), vec![18])); + assert_eq!(run(&[FAILED, other]), (driver, vec![18, 4])); + let text = refused(&[(18, FAILED), (4, MEMORY)]).to_string(); + assert_eq!( + text, + "the driver refused a device on a GPU for want of resources: \ + ERROR_INITIALIZATION_FAILED with 18 VkQueue(s), then ERROR_OUT_OF_DEVICE_MEMORY with 4 \ + VkQueue(s)" + ); + // A shape whose least plan takes no fewer: asked for once. + for families in [vec![family(ALL, 1)], radv()] { + let options = DeviceOptions::default(); + let plan = planned(&families, &options); + let least = least_queue_plan(&families, &options, true); + let queues = vk_queues(&plan); + assert_eq!(least.as_ref().map(vk_queues), Some(queues)); + let mut calls = 0; + let made = made_within_resources("a GPU", plan, least, |_| -> Result<(), _> { + calls += 1; + Err(FAILED) + }); + assert_eq!(made.err(), Some(refused(&[(queues, FAILED)]))); + assert_eq!(calls, 1); + } +} diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 12e60e620..e1decfbda 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2135,6 +2135,8 @@ field metal2vulkan-runtime::DeviceProperties.pci_bus pub pci_bus: Option<(u32, u field metal2vulkan-runtime::DeviceProperties.read_write_texture_support pub read_write_texture_support: ReadWriteTextureTier field metal2vulkan-runtime::DeviceProperties.supports_32bit_float_filtering pub supports_32bit_float_filtering: bool field metal2vulkan-runtime::DeviceProperties.vendor_id pub vendor_id: u32 +field metal2vulkan-runtime::DeviceRefused.attempts pub attempts: Vec<(usize, VkResultCode)> +field metal2vulkan-runtime::DeviceRefused.device pub device: String field metal2vulkan-runtime::DmaBufChunk.fd pub fd: OwnedFd field metal2vulkan-runtime::DmaBufChunk.length pub length: u64 field metal2vulkan-runtime::DmaBufRequest.granule pub granule: u64 @@ -5505,6 +5507,7 @@ macro-member metal2vulkan-runtime::Degradation::IndirectNilBufferOffset Indirect macro-member metal2vulkan-runtime::Degradation::InterlockedBufferOrder InterlockedBufferOrder = "interlocked-buffer-order", Precision, macro-member metal2vulkan-runtime::Degradation::IsolatedIndexBytes IsolatedIndexBytes = "isolated-index-bytes", Performance, macro-member metal2vulkan-runtime::Degradation::LandedVisibilityResults LandedVisibilityResults = "landed-visibility-results", Performance, +macro-member metal2vulkan-runtime::Degradation::LeastQueuePlan LeastQueuePlan = "least-queue-plan", Performance, macro-member metal2vulkan-runtime::Degradation::LinearAttachmentClearCopies LinearAttachmentClearCopies = "linear-attachment-clear-copies", Performance, macro-member metal2vulkan-runtime::Degradation::LinearAttachmentCopies LinearAttachmentCopies = "linear-attachment-copies", Performance, macro-member metal2vulkan-runtime::Degradation::LinesAtNearestWidth LinesAtNearestWidth = "lines-at-nearest-width", Precision, @@ -9894,6 +9897,7 @@ struct metal2vulkan-runtime::DeviceCheckWork #[derive(Clone, Copy, Debug, Defaul struct metal2vulkan-runtime::DeviceHandles #[derive(Clone, Copy)] #[non_exhaustive] pub struct DeviceHandles<'a> struct metal2vulkan-runtime::DeviceOptions #[derive(Clone, Default)] #[non_exhaustive] pub struct DeviceOptions struct metal2vulkan-runtime::DeviceProperties #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceProperties +struct metal2vulkan-runtime::DeviceRefused #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceRefused struct metal2vulkan-runtime::DirtyStamp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DirtyStamp(pub u64) struct metal2vulkan-runtime::DmaBufChunk #[derive(Debug)] pub struct DmaBufChunk struct metal2vulkan-runtime::DmaBufRequest #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DmaBufRequest @@ -10418,6 +10422,7 @@ trait-impl metal2vulkan-runtime::Device impl ImageMaker impl ImageMaker for Devi trait-impl metal2vulkan-runtime::Device impl std::fmt::Debug impl std::fmt::Debug for Device trait-impl metal2vulkan-runtime::DeviceHandles impl std::fmt::Debug impl std::fmt::Debug for DeviceHandles<'_> trait-impl metal2vulkan-runtime::DeviceOptions impl std::fmt::Debug impl std::fmt::Debug for DeviceOptions +trait-impl metal2vulkan-runtime::DeviceRefused impl fmt::Display impl fmt::Display for DeviceRefused trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Send unsafe impl Send for DmaBufRequest trait-impl metal2vulkan-runtime::DmaBufRequest impl fe impl Sync unsafe impl Sync for DmaBufRequest trait-impl metal2vulkan-runtime::DrawPrimitiveType impl From impl From for DrawPrimitiveType @@ -11862,6 +11867,7 @@ variant metal2vulkan-runtime::Error::Bind Bind(BindError) variant metal2vulkan-runtime::Error::Compile Compile(CompileError) variant metal2vulkan-runtime::Error::Degraded Degraded(Box) variant metal2vulkan-runtime::Error::DeviceLost DeviceLost +variant metal2vulkan-runtime::Error::DeviceRefused DeviceRefused(DeviceRefused) variant metal2vulkan-runtime::Error::DriverSetting DriverSetting(DriverSetting) variant metal2vulkan-runtime::Error::DynamicLibrary DynamicLibrary(DynamicLibraryError) variant metal2vulkan-runtime::Error::ExtensionFeature ExtensionFeature(ExtensionFeature) diff --git a/docs/API.md b/docs/API.md index 832269b00..9e1fb35fc 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3375,6 +3375,16 @@ bound. which the extension requires. Cost: the driver keeps its own cache of the device's pipelines beside the shader cache's records, with whatever it writes to disk and holds in memory for it; the pipelines made are the same. +- `metal2vulkan-degrade-least-queue-plan` (performance). `LeastQueuePlan`: A device the driver + refused to make for want of its resources with the `VkQueue`s of its queue plan + (`vkCreateDevice` answering `VK_ERROR_INITIALIZATION_FAILED` or `VK_ERROR_OUT_OF_DEVICE_MEMORY`; + on NVIDIA's driver, other devices of the GPU holding its channels or its BAR), made with those of + its least plan: a round robin of one `VkQueue` and none reserved for presenting, beside the + reserved, extra and staging queues. Announced once, as the device is made, naming the `VkQueue`s + of each plan and the driver's answer; a device the driver refuses with the least plan too is + refused, `Error::DeviceRefused`. Cost: its command queues, presenting ones included, share one + `VkQueue`, so one queue's command buffers wait behind another's whole command buffer where + Metal's run beside each other; what each command buffer does is the same. - `metal2vulkan-degrade-device-recovered` (performance). `DeviceRecovered`: A device whose `VkDevice` was lost made a new one behind it, as Metal's device survives its GPU's recovery: its command buffers in flight failed, the oldest incomplete one as the hang (`GpuHang`, counted