From a7d402ff95e79d08ec499834bd054c4e57cb3c66 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 10:34:35 -0800 Subject: [PATCH 01/17] craft-gpu-device: choose and open a wgpu device Adds the adapter preference (Auto, low power, a named adapter, software) with a key that survives a reordered adapter list and a driver update, wgpu's adapter rule with corrections for drivers that crash, a ranked fallback order ending in a software adapter, a capability report, and device health that records a loss or an uncaptured error without a lock. --- ATTRIBUTION.md | 4 + Cargo.lock | 11 + Cargo.toml | 1 + README.md | 5 + crates/gpu-device/Cargo.toml | 29 ++ crates/gpu-device/NOTICE | 10 + crates/gpu-device/README.md | 55 +++ crates/gpu-device/src/adapter.rs | 581 ++++++++++++++++++++++++++++ crates/gpu-device/src/caps.rs | 203 ++++++++++ crates/gpu-device/src/health.rs | 488 +++++++++++++++++++++++ crates/gpu-device/src/lib.rs | 35 ++ crates/gpu-device/src/open.rs | 304 +++++++++++++++ crates/gpu-device/src/preference.rs | 404 +++++++++++++++++++ crates/gpu-device/src/recovery.rs | 153 ++++++++ 14 files changed, 2283 insertions(+) create mode 100644 crates/gpu-device/Cargo.toml create mode 100644 crates/gpu-device/NOTICE create mode 100644 crates/gpu-device/README.md create mode 100644 crates/gpu-device/src/adapter.rs create mode 100644 crates/gpu-device/src/caps.rs create mode 100644 crates/gpu-device/src/health.rs create mode 100644 crates/gpu-device/src/lib.rs create mode 100644 crates/gpu-device/src/open.rs create mode 100644 crates/gpu-device/src/preference.rs create mode 100644 crates/gpu-device/src/recovery.rs diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f772eede22..f2c076c222 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -141,3 +141,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## HTTP Archive reader `crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned. + +## GPU device selection + +`crates/gpu-device` comes from StudioCraft `crates/craft-gpu-device` at `17e2120f7d79bb677e2871a4192ba1ced1dab57a` (MIT OR Apache-2.0). Its adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. diff --git a/Cargo.lock b/Cargo.lock index da06541564..652fbd1743 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2106,6 +2106,17 @@ dependencies = [ "image", ] +[[package]] +name = "craft-gpu-device" +version = "0.1.0" +dependencies = [ + "log", + "pollster 0.4.0", + "serde", + "serde_json", + "wgpu", +] + [[package]] name = "craft-gridcraft-format" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index c8cd94409b..48cc474b46 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ acadrust = "=0.6.6" log = "0.4" # internal: add each crate here as `craft- = { path = "crates/" }` craft-plist = { path = "crates/plist" } +craft-gpu-device = { path = "crates/gpu-device" } craft-platform = { path = "crates/platform" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } diff --git a/README.md b/README.md index e21de2e1a3..f6d3e55763 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit every frame's position, delay, disposal and transparent colour, the loop count and the first frame's colour table, without decompressing pixels. Tells an animation from a still and whether a file can hold the picture it declares before a decoder runs. +- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto, + low power, a named adapter that survives a reordered list and a driver update, or software; + corrections for drivers that crash; the next adapter and then a software one when a device fails + to open; a capability report; device-loss and error recording without panics; and what to reopen + after a loss. Settings pages and the window stay in each app. - [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook (`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept unread and written back into a list. The workbook model and what follows a read stay in GridCraft. diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml new file mode 100644 index 0000000000..a2561dc3a8 --- /dev/null +++ b/crates/gpu-device/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "craft-gpu-device" +description = "Choosing and opening a wgpu device: an adapter choice the user can set (Auto, high performance, low power, a named adapter, software), fixes for drivers that crash, a software fallback, a capability report, and device health with recovery after a device loss" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +[lints] +workspace = true + +[features] +default = ["serde"] +# Reading and writing `Preference` and `AdapterKey` with serde. +serde = ["dep:serde"] + +[dependencies] +wgpu = "30" +log = { workspace = true } +serde = { workspace = true, optional = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +pollster = "0.4" + +[dev-dependencies] +# The noop backend opens devices without a GPU in the tests. +wgpu = { version = "30", features = ["noop"] } +serde_json = { workspace = true } diff --git a/crates/gpu-device/NOTICE b/crates/gpu-device/NOTICE new file mode 100644 index 0000000000..e7ca2f2c92 --- /dev/null +++ b/crates/gpu-device/NOTICE @@ -0,0 +1,10 @@ +craft-gpu-device +Licensed under the MIT license or the Apache License, Version 2.0, at your option. + +The adapter rule and its driver corrections (src/adapter.rs) come from FilmCraft's +`crates/gpu/src/adapter.rs` (https://github.com/storytold/filmcraft, commit +93a88a839aae370740b09434fdec410abb8c24ca), MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and +the FilmCraft contributors. +Device health (src/health.rs) comes from PhotoCraft's `crates/gpu/src/health.rs` +(https://github.com/storytold/photocraft, commit 01a5b5a389acc93f081e5ce6a8d0580d6438774a), +MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors. diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md new file mode 100644 index 0000000000..ee05ec009b --- /dev/null +++ b/crates/gpu-device/README.md @@ -0,0 +1,55 @@ +# craft-gpu-device + +Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for +drivers that crash, a software fallback, a capability report, and device health with recovery +after a device loss. The crate depends on `wgpu` 30, `pollster` and `log`, with `serde` as an +optional feature (on by default). It depends on no app crate. + +Licensed under MIT OR Apache-2.0. + +## Contents + +| Item | What | +|---|---| +| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface | +| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s | +| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply | +| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) | +| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` | +| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids | +| `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | +| `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | +| `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector` | +| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one | +| `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | +| `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | +| `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | + +## Failure cases + +- With no usable adapter, `select` returns `None` and `open` returns `OpenError::NoAdapter`. +- An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a + `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists + each failure. +- A named adapter that is no longer listed, or can no longer draw to the surface, gives the + automatic choice and `Notice::AdapterMissing`. +- A driver that ends the process cannot be caught. `choose` and `ranked` never use an older + version of a driver that lists one GPU twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 + GPU on Intel's Windows driver. When those are the only adapters that can draw and wgpu's + fallback adapter does not open either, `open` returns `OpenError::UnsafeDriver` with their + names. When a + driver reports no bus id, a second GPU of the same model on the same driver looks like an + older version, and is used through its other backend (DirectX 12 on Windows, OpenGL + elsewhere). +- Only an error that says the device is lost counts as a loss. An error about a destroyed buffer + or texture is recorded as an error. +- `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that + `Device::poll` raises on a lost device and record the loss. + +## Tests + +The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop +backend (the `noop` feature, enabled for tests only), so they do not need a GPU. One test compares +`choose` with wgpu's own `request_adapter` on the machine that runs it, and passes when no adapter +is listed. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs new file mode 100644 index 0000000000..c0d1b5c8ff --- /dev/null +++ b/crates/gpu-device/src/adapter.rs @@ -0,0 +1,581 @@ +//! Which adapter wgpu's own rule would draw with, and two corrections to it for drivers that crash. +//! +//! On Windows the Vulkan loader takes one driver from each display adapter's driver package. A PC +//! whose GPUs were installed from different packages of one vendor (a laptop with an integrated +//! and a discrete AMD GPU, the first on the manufacturer's old package and the second on a current +//! one) loads two versions of that driver, and the newer GPU is listed once through each. wgpu +//! takes the first entry of the device type it prefers, which is whichever version the loader +//! listed first; a window drawn through the stale one ends the process inside the driver +//! (`amdvlk64.dll`, 0xc0000005), where no Rust error handling runs. +//! +//! [`choose`] is wgpu's own rule (`Instance::request_adapter`: the adapters that can draw to the +//! surface, by device type for the power preference, then as enumerated) with one addition: when +//! the adapter that rule picks is listed again by the same driver, the entry exposing the most +//! features is used, which is the newer version. Without such a duplicate the choice is wgpu's own. +//! Entries of one GPU from different drivers (RADV and AMDVLK, a vendor's driver and Dozen) are +//! left alone, and wgpu's order between them stays. +//! +//! An Intel Gen 9 to Gen 11 integrated GPU draws through its DirectX 12 entry rather than Vulkan +//! ([`intel_gen9_to_gen11`]). Intel's Vulkan driver for them (`igvk64.dll`) ends the process with +//! 0xc0000005 when the device is created, after the adapters are listed. + +use std::cmp::Reverse; +use std::fmt; + +use wgpu::{Adapter, Backend, DeviceType, PowerPreference, Surface}; + +/// One enumerated adapter as plain data, so that [`choose`] and [`crate::select`] are pure +/// functions that tests run without a GPU. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Candidate { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + /// PCI vendor and device ids; both zero when the backend reports none (OpenGL). + pub vendor: u32, + pub device: u32, + /// PCI bus id such as `0000:03:00.0`; empty when the driver reports none. + pub pci_bus_id: String, + /// The driver's name (Vulkan) or version (DirectX 12). + pub driver: String, + /// More about the driver, for the log. + pub driver_info: String, + /// How many wgpu features the driver exposes; a newer version of one driver exposes more. + pub features: u32, + /// Whether the surface can be drawn through this adapter (true without a surface). + pub usable: bool, +} + +impl Candidate { + pub fn of(adapter: &Adapter, surface: Option<&Surface<'_>>) -> Self { + let info = adapter.get_info(); + Candidate { + name: info.name, + backend: info.backend, + device_type: info.device_type, + vendor: info.vendor, + device: info.device, + pci_bus_id: info.device_pci_bus_id, + driver: info.driver, + driver_info: info.driver_info, + features: adapter.features().bits().0.iter().map(|word| word.count_ones()).sum(), + usable: surface.is_none_or(|s| adapter.is_surface_supported(s)), + } + } + + /// Whether the adapter draws on the CPU (WARP, llvmpipe, lavapipe, SwiftShader). + pub fn is_software(&self) -> bool { + self.device_type == DeviceType::Cpu + } +} + +impl fmt::Display for Candidate { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let kind = match self.device_type { + DeviceType::DiscreteGpu => "discrete GPU", + DeviceType::IntegratedGpu => "integrated GPU", + DeviceType::VirtualGpu => "virtual GPU", + DeviceType::Cpu => "software", + DeviceType::Other => "unknown type", + }; + let driver = format!("{} {}", self.driver, self.driver_info); + write!(f, "\"{}\" ({:?}, {kind}, driver {}, {} features", self.name, self.backend, driver.trim(), self.features)?; + if !self.pci_bus_id.is_empty() { + write!(f, ", bus {}", self.pci_bus_id)?; + } + if !self.usable { + write!(f, ", cannot draw to the window")?; + } + write!(f, ")") + } +} + +/// Whether `a` and `b` are one GPU listed twice by one driver, through two installed versions of +/// it: the same backend, device type, PCI vendor and device and driver name, and the same bus id +/// when both report one. Adapters without PCI ids (OpenGL reports zeros) are never the same: two +/// of them cannot be told apart. +pub(crate) fn same_gpu_and_driver(a: &Candidate, b: &Candidate) -> bool { + let identified = a.vendor != 0 || a.device != 0; + let same_bus = a.pci_bus_id.is_empty() || b.pci_bus_id.is_empty() || a.pci_bus_id == b.pci_bus_id; + identified + && a.backend == b.backend + && a.device_type == b.device_type + && a.vendor == b.vendor + && a.device == b.device + && a.driver == b.driver + && same_bus +} + +/// wgpu's device type order for `power` (wgpu-core's `Instance::request_adapter`): lower first. +/// Without a preference the adapters stay as enumerated. +pub(crate) fn type_order(device_type: DeviceType, power: PowerPreference) -> u8 { + let prefer_integrated = match power { + PowerPreference::LowPower => true, + PowerPreference::HighPerformance => false, + PowerPreference::None => return 0, + }; + match device_type { + DeviceType::DiscreteGpu if prefer_integrated => 2, + DeviceType::IntegratedGpu if prefer_integrated => 1, + DeviceType::DiscreteGpu => 1, + DeviceType::IntegratedGpu => 2, + DeviceType::Other => 3, + DeviceType::VirtualGpu => 4, + DeviceType::Cpu => 5, + } +} + +/// The index of the adapter wgpu's `request_adapter` picks: the first usable one of the best +/// device type for `power`. `None` without a usable adapter. +pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> Option { + let usable = candidates.iter().enumerate().filter(|(_, c)| c.usable); + usable.min_by_key(|(index, c)| (type_order(c.device_type, power), *index)).map(|(index, _)| index) +} + +/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on +/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's +/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices +/// dropped at the same time can then deadlock in that driver. +pub fn native_instance() -> wgpu::Instance { + wgpu::Instance::new(native_descriptor()) +} + +/// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend +/// options: `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` lists a Vulkan driver that reports no +/// conformance version, such as Mesa's Dozen (the only one on WSL2), and `WGPU_VALIDATION`, +/// `WGPU_DX12_COMPILER` and the others work too. The backends stay as above whatever +/// `WGPU_BACKEND` says. +/// +/// The descriptor has no display handle, which a headless instance does not need. OpenGL on +/// Wayland needs one to draw to a window: add it with `InstanceDescriptor::with_display_handle`, +/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe +/// fills in the window's display handle. +pub fn native_descriptor() -> wgpu::InstanceDescriptor { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + desc.flags = desc.flags.with_env(); + desc.backend_options = desc.backend_options.with_env(); + desc +} + +/// The index of the adapter to draw with for `power`: [`wgpu_choice`], or the entry exposing the +/// most features among those that are the same GPU listed by the same driver (the first of them +/// when several expose as many). For an Intel Gen 9 to Gen 11 GPU on Intel's Windows Vulkan +/// driver it is the same GPU's DirectX 12 entry, or without one the best other usable adapter. +/// `None` without a usable adapter, and when that Intel Vulkan entry is the only one. +pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { + let first = wgpu_choice(candidates, power)?; + let preferred = candidates.get(first)?; + let index = corrected(candidates, first, preferred); + if candidates.get(index).is_some_and(intel_vulkan_crashes) { + // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. + let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); + let (other, c) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(corrected(candidates, other, c)); + } + Some(index) +} + +/// `index` (the entry `preferred`), or the entry to draw with instead of it. +pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { + if let Some(dx12) = dx12_instead(candidates, preferred) { + return dx12; + } + let versions = candidates.iter().enumerate().filter(|(_, c)| c.usable && same_gpu_and_driver(preferred, c)); + versions.max_by_key(|(index, c)| (c.features, Reverse(*index))).map_or(index, |(index, _)| index) +} + +/// Whether the entry at `index` is one [`choose`] never draws with: the Vulkan entry of an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows driver, or an older version of a driver that lists one +/// GPU twice. Creating a device or drawing through either can end the process, so it is never +/// tried as a fallback either. A second GPU of the same model on the same driver, when the +/// driver reports no bus id for either, looks like an older version; it is still listed through +/// the other backends (DirectX 12 on Windows, OpenGL elsewhere). +pub(crate) fn avoided(candidates: &[Candidate], index: usize) -> bool { + let Some(c) = candidates.get(index) else { + return true; + }; + intel_vulkan_crashes(c) || corrected(candidates, index, c) != index +} + +/// PCI vendor id of Intel. +pub(crate) const INTEL: u32 = 0x8086; + +/// Whether `device` is an Intel Gen 9 to Gen 11 integrated GPU: 6th to 10th generation Core, and +/// the Atom, Pentium and Celeron graphics of those years (Skylake, Broxton, Gemini Lake, Kaby +/// Lake, Coffee Lake, Whiskey Lake, Comet Lake, Cannon Lake, Ice Lake, Elkhart Lake, Jasper Lake), +/// by the PCI device ids of Linux's `include/drm/intel/pciids.h`: these prefixes hold those +/// families and no others, except `0x0a84` (Broxton), whose prefix Haswell shares. +/// +/// Their Windows Vulkan driver ends the process with 0xc0000005 in `igvk64.dll` when a device is +/// created, on every version reported, from 25.20.100.6576 (2019) to 31.0.101.2145, the legacy +/// branch that is the last driver Intel ships for them. DirectX 12 works on the same GPUs. +pub fn intel_gen9_to_gen11(device: u32) -> bool { + matches!(device >> 8, 0x19 | 0x1a | 0x31 | 0x3e | 0x45 | 0x4e | 0x59 | 0x5a | 0x87 | 0x8a | 0x9b) || device == 0x0a84 +} + +/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan +/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a +/// driver name with "Mesa" in it and is not included. +pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool { + c.backend == Backend::Vulkan + && c.device_type == DeviceType::IntegratedGpu + && c.vendor == INTEL + && intel_gen9_to_gen11(c.device) + && !c.driver.to_ascii_lowercase().contains("mesa") +} + +/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the +/// index of the same GPU's usable DirectX 12 entry, if there is one. +fn dx12_instead(candidates: &[Candidate], preferred: &Candidate) -> Option { + if !intel_vulkan_crashes(preferred) { + return None; + } + candidates.iter().position(|c| c.usable && c.backend == Backend::Dx12 && c.vendor == INTEL && c.device == preferred.device) +} + +/// Write the adapters and the choice to the log, with a warning when a correction applied. +pub(crate) fn log_choice(candidates: &[Candidate], index: usize, power: PowerPreference) { + for candidate in candidates { + log::info!("graphics adapter available: {candidate}"); + } + let Some(chosen) = candidates.get(index) else { + return; + }; + let others = candidates.iter().enumerate().filter(|(i, c)| *i != index && c.usable && same_gpu_and_driver(chosen, c)).count(); + if others > 0 { + log::warn!( + "{:?} lists \"{}\" {} times: several versions of its driver are installed, and a window drawn through a stale one can crash. Using the one with the most features; installing one driver package for every GPU removes the others.", + chosen.backend, + chosen.name, + others.saturating_add(1) + ); + } + if let Some(wgpu_own) = wgpu_choice(candidates, power).and_then(|i| candidates.get(i)) + && wgpu_own.backend == Backend::Vulkan + && chosen.backend == Backend::Dx12 + && wgpu_own.vendor == INTEL + && wgpu_own.device == chosen.device + { + log::warn!("Intel's Vulkan driver for \"{}\" crashes when the device is created: drawing through DirectX 12", wgpu_own.name); + } + log::info!("graphics adapter chosen: {chosen}"); +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use wgpu::Backend::{Dx12, Gl, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other}; + use wgpu::PowerPreference::{HighPerformance, LowPower}; + + pub(crate) const AMD: u32 = 0x1002; + pub(crate) const RX_6800M: u32 = 0x73df; + pub(crate) const RADEON_IGPU: u32 = 0x1638; + const POWERS: [PowerPreference; 3] = [PowerPreference::None, LowPower, HighPerformance]; + + #[expect(clippy::too_many_arguments, reason = "one line per adapter in the listings below")] + pub(crate) fn gpu( + name: &str, + backend: Backend, + device_type: DeviceType, + vendor: u32, + device: u32, + bus: &str, + driver: &str, + driver_info: &str, + features: u32, + ) -> Candidate { + Candidate { + name: name.into(), + backend, + device_type, + vendor, + device, + pci_bus_id: bus.into(), + driver: driver.into(), + driver_info: driver_info.into(), + features, + usable: true, + } + } + + /// A laptop with an integrated Radeon on a 2021 driver package and an RX 6800M on a 2026 one, + /// as wgpu 30 lists it: the Vulkan loader has both versions of AMD's driver, and the 2021 one + /// lists the RX 6800M first. A window drawn through that entry ended inside `amdvlk64.dll` + /// (0xc0000005) on every launch. + pub(crate) fn two_amd_drivers() -> Vec { + let amd = "AMD proprietary driver"; + vec![ + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2", 60), + gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2 (AMD proprietary shader compiler)", 68), + gpu("AMD Radeon(TM) Graphics", Vulkan, IntegratedGpu, AMD, RADEON_IGPU, "", amd, "21.30.02.13", 56), + gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, AMD, RX_6800M, "0000:03:00.0", "32.0.21045.11001", "", 36), + gpu("AMD Radeon(TM) Graphics", Dx12, IntegratedGpu, AMD, RADEON_IGPU, "0000:08:00.0", "30.0.13002.13003", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9549", "", 36), + ] + } + + #[test] + fn a_gpu_listed_through_two_versions_of_its_driver_draws_with_the_newer_one() { + let adapters = two_amd_drivers(); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(wgpu_choice(&adapters, power), Some(0), "wgpu takes the stale entry, which crashed"); + assert_eq!(choose(&adapters, power), Some(1)); + } + // whichever version the loader lists first + let mut newer_first = adapters.clone(); + newer_first.swap(0, 1); + assert_eq!(choose(&newer_first, HighPerformance), Some(0)); + // two entries exposing as much: wgpu's, the first + let mut equal = adapters.clone(); + if let Some(c) = equal.get_mut(1) { + c.features = 60; + } + assert_eq!(choose(&equal, HighPerformance), Some(0)); + // three versions: the one exposing the most + let mut three = adapters.clone(); + three.insert(1, gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", "AMD proprietary driver", "24.1.1", 64)); + assert_eq!(choose(&three, HighPerformance), Some(2)); + // the stale entries are avoided, the newest is not + assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); + } + + #[test] + fn a_newer_version_never_overtakes_another_gpu_or_backend() { + assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); + let mut dx12_first = two_amd_drivers(); + dx12_first.rotate_left(3); + for power in [HighPerformance, PowerPreference::None] { + assert_eq!(choose(&dx12_first, power), Some(0)); + } + assert_eq!(choose(&dx12_first, LowPower), wgpu_choice(&dx12_first, LowPower)); + } + + #[test] + fn without_two_versions_of_one_driver_the_choice_is_wgpus() { + let nvidia = |backend, bus, driver, features| gpu("NVIDIA GeForce RTX 4070", backend, DiscreteGpu, 0x10de, 0x2786, bus, driver, "", features); + let intel = + |backend, bus, driver, features| gpu("Intel(R) UHD Graphics 770", backend, IntegratedGpu, 0x8086, 0x4680, bus, driver, "", features); + let radeon = |bus, driver, features| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, AMD, 0x744c, bus, driver, "", features); + let gl = |name: &str, features| gpu(name, Gl, Other, 0, 0, "", "", "", features); + let without = |skip: usize| two_amd_drivers().into_iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, c)| c).collect::>(); + let listings: Vec> = vec![ + vec![], + vec![nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // a laptop with two GPUs, through Vulkan and DirectX 12 + vec![ + intel(Vulkan, "0000:00:02.0", "Intel Corporation", 60), + nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70), + nvidia(Dx12, "0000:01:00.0", "32.0.15.6094", 36), + intel(Dx12, "0000:00:02.0", "31.0.101.5186", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.1", "", 36), + ], + // one GPU through two different drivers: Linux with AMDVLK and RADV + vec![radeon("0000:03:00.0", "AMD open-source driver", 58), radeon("0000:03:00.0", "radv", 71)], + // a vendor's driver and Dozen (Vulkan on DirectX 12) + vec![nvidia(Vulkan, "", "Dozen", 75), nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)], + // two cards of one model, on their own buses + vec![radeon("0000:03:00.0", "AMD proprietary driver", 60), radeon("0000:04:00.0", "AMD proprietary driver", 68)], + // OpenGL reports no ids: two adapters cannot be told apart + vec![gl("ANGLE", 20), gl("ANGLE", 30)], + vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)], + without(0), + without(1), + ]; + for adapters in &listings { + for power in POWERS { + assert_eq!(choose(adapters, power), wgpu_choice(adapters, power), "{power:?} over {adapters:#?}"); + } + } + assert_eq!(choose(&[], HighPerformance), None); + } + + /// An Intel UHD Graphics 630 (Coffee Lake) on driver 25.20.100.6576 as wgpu 30 lists it. A + /// Vulkan device on it ended inside `igvk64.dll` (0xc0000005) as it was created. + pub(crate) fn uhd_630() -> Vec { + vec![ + gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Intel Corporation", "Intel driver", 44), + gpu("Intel(R) UHD Graphics 630", Dx12, IntegratedGpu, INTEL, 0x3e91, "0000:00:02.0", "25.20.100.6576", "", 36), + gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9711", "", 36), + ] + } + + fn uhd_630_as(name: &str, device: u32) -> Vec { + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { name: name.into(), device, ..c } } else { c }).collect() + } + + #[test] + fn an_intel_gen9_to_gen11_gpu_draws_through_directx_12() { + for power in POWERS { + assert_eq!(wgpu_choice(&uhd_630(), power), Some(0), "wgpu takes Vulkan, which crashed"); + assert_eq!(choose(&uhd_630(), power), Some(1), "{power:?}"); + } + for (name, device) in [("Intel(R) HD Graphics 520", 0x1916), ("Intel(R) Iris(R) Plus Graphics", 0x8a5a)] { + assert_eq!(choose(&uhd_630_as(name, device), HighPerformance), Some(1), "{name}"); + } + let mut dx12_first = uhd_630(); + dx12_first.swap(0, 1); + assert_eq!(choose(&dx12_first, HighPerformance), Some(0)); + // without a usable DirectX 12 entry, the Vulkan entry is still never drawn with + let vulkan_only: Vec = uhd_630().into_iter().take(1).collect(); + assert_eq!(choose(&vulkan_only, HighPerformance), None); + assert!(avoided(&vulkan_only, 0)); + let mut dx12_unusable = uhd_630(); + if let Some(c) = dx12_unusable.get_mut(1) { + c.usable = false; + } + assert_eq!(choose(&dx12_unusable, HighPerformance), Some(2), "the software adapter"); + // Mesa's Vulkan driver for the same GPU on Linux is drawn with + let mesa = vec![gpu( + "Intel(R) UHD Graphics 630 (CFL GT2)", + Vulkan, + IntegratedGpu, + INTEL, + 0x3e91, + "0000:00:02.0", + "Intel open-source Mesa driver", + "Mesa 25.2.4", + 44, + )]; + assert_eq!(choose(&mesa, HighPerformance), Some(0)); + assert!(!avoided(&mesa, 0)); + // beside a discrete GPU: high performance keeps it; low power takes the Intel GPU's DirectX 12 entry + let mut laptop = uhd_630(); + laptop.insert(1, gpu("NVIDIA GeForce MX250", Vulkan, DiscreteGpu, 0x10de, 0x1d13, "0000:01:00.0", "NVIDIA", "", 70)); + assert_eq!(choose(&laptop, HighPerformance), Some(1)); + assert_eq!(choose(&laptop, LowPower), Some(2)); + assert!(avoided(&laptop, 0)); + } + + #[test] + fn later_intel_gpus_keep_wgpus_choice() { + for (name, device) in [("Intel(R) Iris(R) Xe Graphics", 0x9a49), ("Intel(R) UHD Graphics 770", 0x4680), ("Intel(R) Arc(TM) Graphics", 0x7d55)] + { + let adapters = uhd_630_as(name, device); + for power in POWERS { + assert_eq!(choose(&adapters, power), Some(0), "{name} {power:?}"); + } + } + let discrete: Vec = + uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { device_type: DiscreteGpu, ..c } } else { c }).collect(); + assert_eq!(choose(&discrete, HighPerformance), Some(0)); + } + + #[test] + fn gen9_to_gen11_ids() { + for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] { + assert!(intel_gen9_to_gen11(id), "{id:#06x}"); + } + for id in [0x0a16, 0x0a1e, 0x1616, 0x9a49, 0x4c8a, 0x4680, 0x46a6, 0xa780, 0x4905, 0x56a0, 0x7d55, 0x64a0, 0xe20b, 0xb080] { + assert!(!intel_gen9_to_gen11(id), "{id:#06x}"); + } + } + + #[test] + fn two_entries_are_one_gpu_only_with_the_same_ids_type_driver_and_bus() { + let stale = two_amd_drivers().swap_remove(0); + let newer = two_amd_drivers().swap_remove(1); + assert!(same_gpu_and_driver(&stale, &newer) && same_gpu_and_driver(&stale, &stale)); + let on_bus = |bus: &str| Candidate { pci_bus_id: bus.into(), ..newer.clone() }; + assert!(same_gpu_and_driver(&stale, &on_bus("0000:03:00.0"))); + assert!(same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:03:00.0"))); + assert!(!same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:04:00.0"))); + for other in [ + Candidate { backend: Dx12, ..newer.clone() }, + Candidate { device_type: IntegratedGpu, ..newer.clone() }, + Candidate { vendor: 0x10de, ..newer.clone() }, + Candidate { device: RADEON_IGPU, ..newer.clone() }, + Candidate { driver: "radv".into(), ..newer.clone() }, + ] { + assert!(!same_gpu_and_driver(&stale, &other), "{other}"); + } + let unidentified = Candidate { vendor: 0, device: 0, ..newer }; + assert!(!same_gpu_and_driver(&unidentified, &unidentified)); + } + + #[test] + fn adapters_that_cannot_draw_to_the_window_are_left_out() { + let unusable = |which: &dyn Fn(usize, &Candidate) -> bool| { + let mut adapters = two_amd_drivers(); + for (i, c) in adapters.iter_mut().enumerate() { + c.usable = !which(i, c); + } + adapters + }; + assert_eq!(choose(&unusable(&|i, _| i == 1), HighPerformance), Some(0)); + assert_eq!(choose(&unusable(&|i, _| i == 0), HighPerformance), Some(1)); + assert_eq!(choose(&unusable(&|_, c| c.backend == Vulkan), HighPerformance), Some(3)); + assert_eq!(choose(&unusable(&|_, _| true), HighPerformance), None); + } + + #[test] + fn candidates_describe_themselves_for_the_log() { + let adapters = two_amd_drivers(); + let text = adapters.get(1).map(ToString::to_string).unwrap_or_default(); + assert_eq!( + text, + "\"AMD Radeon RX 6800M\" (Vulkan, discrete GPU, driver AMD proprietary driver 26.9.2 (AMD proprietary shader compiler), 68 features)" + ); + let offscreen = adapters.get(4).map(|c| Candidate { usable: false, ..c.clone() }.to_string()).unwrap_or_default(); + assert_eq!( + offscreen, + "\"AMD Radeon(TM) Graphics\" (Dx12, integrated GPU, driver 30.0.13002.13003, 36 features, bus 0000:08:00.0, cannot draw to the window)" + ); + assert!(adapters.get(5).is_some_and(Candidate::is_software)); + assert!(!adapters.first().is_some_and(Candidate::is_software)); + } + + /// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND` + /// says. Runs in a child process, which has them set. + #[test] + fn native_descriptor_reads_wgpu_flags_but_keeps_its_backends() { + const CHILD: &str = "CRAFT_GPU_DEVICE_TEST_NATIVE_DESCRIPTOR_CHILD"; + if std::env::var_os(CHILD).is_none() { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "adapter::tests::native_descriptor_reads_wgpu_flags_but_keeps_its_backends", "--nocapture"]) + .env(CHILD, "1") + .env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1") + .env("WGPU_BACKEND", "gl") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + return; + } + let desc = native_descriptor(); + assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags); + let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL }; + assert_eq!(desc.backends, backends); + } + + /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's + /// `request_adapter` returns, and [`choose`] returns that adapter too, a version of it exposing + /// more features, or for an Intel Gen 9 to Gen 11 GPU its DirectX 12 entry. Passes without + /// adapters. + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { + let backends = wgpu::Backends::PRIMARY; + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() }); + let adapters = pollster::block_on(instance.enumerate_adapters(backends)); + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, None)).collect(); + for power in POWERS { + let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; + let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); + assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); + let picked = choose(&candidates, power).and_then(|i| candidates.get(i)); + match (&wgpu_own, picked) { + (Some(wgpu_own), Some(picked)) if wgpu_own != picked => { + let newer_version = same_gpu_and_driver(wgpu_own, picked) && picked.features > wgpu_own.features; + let intel_dx12 = wgpu_own.vendor == INTEL + && intel_gen9_to_gen11(wgpu_own.device) + && picked.backend == Backend::Dx12 + && picked.device == wgpu_own.device; + assert!(newer_version || intel_dx12, "{power:?}: {picked} instead of {wgpu_own}"); + } + _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), + } + } + } +} diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs new file mode 100644 index 0000000000..e0841a0293 --- /dev/null +++ b/crates/gpu-device/src/caps.rs @@ -0,0 +1,203 @@ +//! What an adapter can do, for choosing a pipeline and for the settings and the log. + +use std::fmt; + +use wgpu::{AdapterInfo, Backend, DeviceType, Features, Limits}; + +/// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers +/// report instead). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum Vendor { + Nvidia, + Amd, + Intel, + Apple, + Qualcomm, + Arm, + ImgTec, + /// Microsoft's software adapter (WARP) and its virtual GPUs. + Microsoft, + /// Mesa's software drivers (llvmpipe, lavapipe). + Mesa, + /// Another id, or none (0). + Other(u32), +} + +impl Vendor { + pub fn from_id(id: u32) -> Vendor { + match id { + 0x10de => Vendor::Nvidia, + 0x1002 | 0x1022 => Vendor::Amd, + 0x8086 => Vendor::Intel, + 0x106b => Vendor::Apple, + 0x5143 => Vendor::Qualcomm, + 0x13b5 => Vendor::Arm, + 0x1010 => Vendor::ImgTec, + 0x1414 => Vendor::Microsoft, + 0x10005 => Vendor::Mesa, + other => Vendor::Other(other), + } + } +} + +impl fmt::Display for Vendor { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Vendor::Nvidia => "NVIDIA", + Vendor::Amd => "AMD", + Vendor::Intel => "Intel", + Vendor::Apple => "Apple", + Vendor::Qualcomm => "Qualcomm", + Vendor::Arm => "Arm", + Vendor::ImgTec => "Imagination", + Vendor::Microsoft => "Microsoft", + Vendor::Mesa => "Mesa", + Vendor::Other(0) => return f.write_str("unknown vendor"), + Vendor::Other(id) => return write!(f, "vendor {id:#06x}"), + }; + f.write_str(name) + } +} + +/// What an adapter reports it can do. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Capabilities { + pub name: String, + pub backend: Backend, + pub device_type: DeviceType, + pub vendor: Vendor, + /// The adapter draws on the CPU. + pub software: bool, + /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created + /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into + /// `R8Unorm` and `Rg8Unorm` textures instead. + pub nv12: bool, + /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane + /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` + /// textures ([`norm16`](Self::norm16)) instead. + pub p010: bool, + /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without + /// P010. + pub norm16: bool, + /// `f16` in shaders. + pub shader_f16: bool, + /// Timestamp queries, for measuring GPU time per pass. + pub timestamps: bool, + /// The widest and tallest 2D texture. + pub max_texture_2d: u32, + /// The largest buffer, in bytes. + pub max_buffer_size: u64, +} + +impl Capabilities { + /// From an adapter's (or a device's) info, features and limits. + pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self { + Capabilities { + name: info.name.clone(), + backend: info.backend, + device_type: info.device_type, + vendor: Vendor::from_id(info.vendor), + software: info.device_type == DeviceType::Cpu, + nv12: features.contains(Features::TEXTURE_FORMAT_NV12), + p010: features.contains(Features::TEXTURE_FORMAT_P010), + norm16: features.contains(Features::TEXTURE_FORMAT_16BIT_NORM), + shader_f16: features.contains(Features::SHADER_F16), + timestamps: features.contains(Features::TIMESTAMP_QUERY), + max_texture_2d: limits.max_texture_dimension_2d, + max_buffer_size: limits.max_buffer_size, + } + } + + /// What `adapter` can do. + pub fn of_adapter(adapter: &wgpu::Adapter) -> Self { + Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits()) + } + + /// What a device opened on `adapter` can do: the features and limits it was opened with. + pub fn of_device(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Self { + Self::from_parts(&adapter.get_info(), device.features(), &device.limits()) + } + + /// Whether a `width` × `height` texture fits. + pub fn fits(&self, width: u32, height: u32) -> bool { + width > 0 && height > 0 && width <= self.max_texture_2d && height <= self.max_texture_2d + } + + /// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be + /// sampled. + pub fn ten_bit(&self) -> bool { + self.norm16 + } + + /// The features from `wanted` this adapter has, to ask for when opening a device. + pub fn available(adapter_features: Features, wanted: Features) -> Features { + adapter_features & wanted + } +} + +impl fmt::Display for Capabilities { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({}, {:?}", self.name, self.vendor, self.backend)?; + if self.software { + f.write_str(", software")?; + } + let flags = + [(self.nv12, "NV12"), (self.p010, "P010"), (self.norm16, "16-bit norm"), (self.shader_f16, "f16"), (self.timestamps, "timestamps")]; + for (on, name) in flags { + if on { + write!(f, ", {name}")?; + } + } + write!(f, ", textures up to {} px)", self.max_texture_2d) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo { + AdapterInfo { name: name.into(), vendor, ..AdapterInfo::new(device_type, Backend::Vulkan) } + } + + #[test] + fn vendors_from_pci_and_khronos_ids() { + assert_eq!(Vendor::from_id(0x10de), Vendor::Nvidia); + assert_eq!(Vendor::from_id(0x1002), Vendor::Amd); + assert_eq!(Vendor::from_id(0x8086), Vendor::Intel); + assert_eq!(Vendor::from_id(0x10005), Vendor::Mesa); + assert_eq!(Vendor::from_id(0x1414), Vendor::Microsoft); + assert_eq!(Vendor::from_id(0), Vendor::Other(0)); + assert_eq!(Vendor::Other(0).to_string(), "unknown vendor"); + assert_eq!(Vendor::from_id(0x1234).to_string(), "vendor 0x1234"); + } + + #[test] + fn features_and_limits_become_capabilities() { + let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY; + let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() }; + let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert!(c.nv12 && !c.p010 && c.norm16 && c.timestamps && !c.shader_f16 && !c.software); + assert!(c.ten_bit()); + assert_eq!(c.vendor, Vendor::Nvidia); + assert!(c.fits(7680, 4320) && c.fits(16384, 16384)); + assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0)); + assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)"); + } + + #[test] + fn a_software_adapter_without_extras() { + let limits = Limits::downlevel_defaults(); + let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits); + assert!(c.software && !c.ten_bit() && !c.nv12); + // P010 alone is sampled, not drawn to + let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits); + assert!(p010.p010 && !p010.ten_bit()); + assert_eq!(c.max_texture_2d, 2048); + assert!(!c.fits(3840, 2160)); + assert!(c.to_string().contains("software")); + let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; + assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16); + } +} diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs new file mode 100644 index 0000000000..a113ee783c --- /dev/null +++ b/crates/gpu-device/src/health.rs @@ -0,0 +1,488 @@ +//! Device health: notices a lost wgpu device or an uncaptured wgpu error, so callers stop issuing +//! GPU work and reopen a device or fall back, instead of panicking. +//! +//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device +//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the +//! fault and registers the device-lost callback, and the polls here run only while the device is +//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks +//! [`DeviceHealth::fault`] first. +//! +//! Builds for the web too: the callbacks only touch atomics and a mutex. + +use std::fmt; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, OnceLock}; + +#[cfg(not(target_arch = "wasm32"))] +use std::time::{Duration, Instant}; + +/// Outcome of a bounded wait for submitted GPU work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum WaitOutcome { + /// The submitted work finished before the deadline. + Finished, + /// The deadline passed (or the device faulted) before the work finished. + TimedOut, + /// The caller canceled the wait before the work finished. + Canceled, +} + +/// Why the GPU cannot be used any more. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Fault { + /// The device was lost (driver reset, the OS ended a submission, `Device::destroy`). + Lost(String), + /// An uncaptured wgpu error (out of memory, validation, internal): the GPU output cannot be + /// trusted, and on most drivers the device is about to be lost anyway. + Error(String), +} + +impl Fault { + /// Whether the device itself was lost (rather than an error reported). + pub fn is_lost(&self) -> bool { + matches!(self, Fault::Lost(_)) + } + + /// An out-of-memory error on a device that still works: freeing memory and trying again can + /// succeed, unlike after a loss or a validation error. Only wgpu's own out-of-memory error is + /// recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory is not + /// one. + pub fn is_out_of_memory(&self) -> bool { + matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY) + } + + /// The driver's or wgpu's message. + pub fn detail(&self) -> &str { + match self { + Fault::Lost(s) | Fault::Error(s) => s, + } + } +} + +impl fmt::Display for Fault { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Fault::Lost(s) if s.is_empty() => f.write_str("GPU device lost"), + Fault::Lost(s) => write!(f, "GPU device lost: {s}"), + Fault::Error(s) => write!(f, "GPU error: {s}"), + } + } +} + +/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`). +pub const OUT_OF_MEMORY: &str = "Out of Memory"; + +/// The state wgpu's callbacks write and callers read, without a lock: flags in atomics and each +/// fault's text in a [`OnceLock`], whose `get` does not wait. A `set` that races another `set` +/// of the same slot waits only for that one store. +#[derive(Default)] +struct Inner { + faulted: AtomicBool, + /// The first device loss. + lost: OnceLock, + /// An out-of-memory error was seen. + out_of_memory: AtomicBool, + /// The first other error. + error: OnceLock, + errors: AtomicU64, + /// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]). + device_lost: AtomicBool, +} + +/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state. +#[derive(Clone, Default)] +pub struct DeviceHealth(Arc); + +impl fmt::Debug for DeviceHealth { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DeviceHealth").field("fault", &self.fault()).field("errors", &self.errors()).finish() + } +} + +impl DeviceHealth { + /// A healthy flag not attached to a device (tests, CPU-only callers). + pub fn new() -> Self { + Self::default() + } + + /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). + pub fn watch(device: &wgpu::Device) -> Self { + let health = Self::new(); + let lost = health.clone(); + // Called by wgpu with its own locks held: only record, never call back into wgpu. + device.set_device_lost_callback(move |reason, message| { + let detail = match (reason, message.is_empty()) { + (wgpu::DeviceLostReason::Destroyed, true) => "device destroyed".to_string(), + (_, true) => "lost by the driver".to_string(), + (_, false) => message, + }; + log::error!("wgpu device lost ({reason:?}): {detail}"); + lost.0.device_lost.store(true, Ordering::Release); + lost.mark(Fault::Lost(detail)); + }); + let errors = health.clone(); + device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); + health + } + + /// Record an uncaptured wgpu error. + fn uncaptured(&self, e: &wgpu::Error) { + self.0.errors.fetch_add(1, Ordering::Relaxed); + log::error!("uncaptured wgpu error: {e}"); + self.mark(fault_of(e)); + } + + /// Record an error an error scope caught. + /// + /// The uncaptured-error handler never sees a scoped error, so without this a watched device + /// would keep being handed work after it failed. Polls first: a lost device is a + /// [`Fault::Lost`], and its callback may not have run yet (it runs on a poll). The poll does + /// not block. + pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) { + if self.lost() { + return; + } + #[cfg(not(target_arch = "wasm32"))] + self.poll(device); + #[cfg(target_arch = "wasm32")] + let _ = device; + if self.lost() { + return; + } + self.mark(fault_of(error)); + } + + fn lost(&self) -> bool { + self.fault().is_some_and(|f| f.is_lost()) + } + + /// Mark the device unusable. The first fault is kept; a later device loss replaces an error, + /// and a later out-of-memory error replaces another error, so a caller can still free memory + /// and recover after a validation error in the same frame. + pub fn mark(&self, fault: Fault) { + if fault.is_out_of_memory() { + self.0.out_of_memory.store(true, Ordering::Release); + } else { + // A slot already set keeps its first text. + let _ = match fault { + Fault::Lost(text) => self.0.lost.set(text), + Fault::Error(text) => self.0.error.set(text), + }; + } + self.0.faulted.store(true, Ordering::Release); + } + + /// Whether the device may still be used. + pub fn is_ok(&self) -> bool { + !self.0.faulted.load(Ordering::Acquire) + } + + /// Why the device cannot be used, if it cannot. + pub fn fault(&self) -> Option { + if self.is_ok() { + return None; + } + if let Some(text) = self.0.lost.get() { + return Some(Fault::Lost(text.clone())); + } + if self.0.out_of_memory.load(Ordering::Acquire) { + return Some(Fault::Error(OUT_OF_MEMORY.into())); + } + self.0.error.get().map(|text| Fault::Error(text.clone())) + } + + /// Uncaptured wgpu errors seen so far. + pub fn errors(&self) -> u64 { + self.0.errors.load(Ordering::Relaxed) + } + + /// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it + /// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing + /// drawn with the device reaches the screen, the window's own frames included. + pub fn device_lost(&self) -> bool { + self.0.device_lost.load(Ordering::Acquire) + } + + /// Non-blocking poll that runs even after a fault was recorded, so a device that is lost + /// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next + /// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost). + pub fn probe(&self, device: &wgpu::Device) { + if self.device_lost() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// `Device::poll` panicked: wgpu found the device lost. + fn lost_by_poll(&self) { + self.0.device_lost.store(true, Ordering::Release); + self.mark(Fault::Lost("the device stopped responding".into())); + } + + /// Block until `index` (or all submitted work) finished, unless the device is unusable. + /// Returns whether the work finished with the device still healthy: `false` when the device + /// was unusable, when it faulted, and when the poll itself failed, so the work may still be + /// running. A panic in `Device::poll` is caught and recorded as a loss. Native only: the web + /// has no blocking wait. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait(&self, device: &wgpu::Device, index: Option) -> bool { + if !self.is_ok() { + return false; + } + let poll = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Wait { submission_index: index, timeout: None }))); + match poll { + Ok(Ok(_)) => self.is_ok(), + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + false + } + Err(_) => { + self.lost_by_poll(); + false + } + } + } + + /// Non-blocking poll (reclaims staging memory), skipped once the device is unusable. + pub fn poll(&self, device: &wgpu::Device) { + if !self.is_ok() { + return; + } + if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { + self.lost_by_poll(); + } + } + + /// Like [`Self::wait`], but bounded: returns whether the submitted work finished within + /// `timeout`. A timeout marks the device faulted, so later work stops going to a GPU that no + /// longer answers. A submission index the device never issued returns `false` and leaves the + /// device healthy. A zero `timeout`, or + /// one that passes before the first poll, returns `false` and leaves the device healthy. A + /// device that was already faulted returns `false` unchanged. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout(&self, device: &wgpu::Device, index: Option, timeout: Duration) -> bool { + self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished + } + + /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between + /// them, keeping the same overall deadline. A slice that times out means the work has not + /// finished yet; only the overall deadline (or a poll that panics) marks the device faulted. + #[cfg(not(target_arch = "wasm32"))] + pub fn wait_timeout_cancelable( + &self, + device: &wgpu::Device, + index: Option, + timeout: Duration, + canceled: &(dyn Fn() -> bool + Sync), + ) -> WaitOutcome { + if !self.is_ok() { + return WaitOutcome::TimedOut; + } + let mut wrong_index = false; + let mut polled = false; + let outcome = wait_slices(timeout, canceled, |slice| { + polled = true; + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: index.clone(), timeout: Some(slice) }) + })); + match poll { + Ok(Ok(_)) => { + if self.is_ok() { + SlicePoll::Done + } else { + SlicePoll::Failed + } + } + Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + // A submission index the device never issued: the caller's mistake, not the GPU's. + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + wrong_index = true; + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } + } + }); + // A deadline that passed before the first poll says nothing about the device. + if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.is_ok() { + self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64()))); + } + outcome + } +} + +/// What one bounded poll reported. +#[cfg(not(target_arch = "wasm32"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum SlicePoll { + Done, + Pending, + Failed, +} + +/// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between +/// them. A slice that times out is pending, not a failure; only the overall deadline or a failed +/// poll ends the wait early. +#[cfg(not(target_arch = "wasm32"))] +fn wait_slices(total: Duration, canceled: &(dyn Fn() -> bool + Sync), mut poll: impl FnMut(Duration) -> SlicePoll) -> WaitOutcome { + const SLICE: Duration = Duration::from_millis(100); + let start = Instant::now(); + loop { + if canceled() { + return WaitOutcome::Canceled; + } + let remaining = total.saturating_sub(start.elapsed()); + if remaining.is_zero() { + return WaitOutcome::TimedOut; + } + match poll(remaining.min(SLICE)) { + SlicePoll::Done => return WaitOutcome::Finished, + SlicePoll::Pending => {} + SlicePoll::Failed => return WaitOutcome::TimedOut, + } + } +} + +/// The fault a wgpu error stands for. An error that names a lost device follows a device loss +/// whose callback may not have run yet (it runs on the next poll), so it counts as a loss rather +/// than as an error. An error about a destroyed buffer or texture is an error. Only wgpu's own +/// out-of-memory error is [`OUT_OF_MEMORY`]. +fn fault_of(e: &wgpu::Error) -> Fault { + let text = e.to_string(); + let lower = text.to_ascii_lowercase(); + if matches!(e, wgpu::Error::OutOfMemory { .. }) { + Fault::Error(OUT_OF_MEMORY.into()) + } else if lower.contains("device is lost") { + Fault::Lost(first_line(&text)) + } else { + Fault::Error(first_line(&text)) + } +} + +fn first_line(s: &str) -> String { + let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); + let mut out: String = line.chars().take(200).collect(); + if line.chars().count() > 200 { + out.push('…'); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn first_fault_wins_but_loss_replaces_an_error() { + let h = DeviceHealth::new(); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + h.mark(Fault::Error("out of memory".into())); + assert!(!h.is_ok()); + let c = h.clone(); + c.mark(Fault::Error("second".into())); + assert_eq!(h.fault(), Some(Fault::Error("out of memory".into()))); + c.mark(Fault::Lost("reset".into())); + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + c.mark(Fault::Lost("later".into())); + assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset")); + // a recorded loss is not wgpu reporting the device lost + assert!(!h.device_lost()); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_cancel_timeout_and_completion() { + let never = || false; + assert_eq!(wait_slices(Duration::ZERO, &never, |_| SlicePoll::Done), WaitOutcome::TimedOut); + assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Done), WaitOutcome::Finished); + assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Failed), WaitOutcome::TimedOut); + + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &never, |_| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + }); + assert_eq!(outcome, WaitOutcome::Finished); + assert_eq!(polls, 3, "a timed-out slice is retried, not treated as a failure"); + + let canceled = || true; + let mut called = false; + assert_eq!( + wait_slices(Duration::from_secs(1), &canceled, |_| { + called = true; + SlicePoll::Done + }), + WaitOutcome::Canceled + ); + assert!(!called, "cancellation is checked before polling"); + } + + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_observes_cancel_while_pending() { + let flag = AtomicBool::new(false); + let canceled = || flag.load(Ordering::SeqCst); + let mut polls = 0; + let outcome = wait_slices(Duration::from_secs(1), &canceled, |_| { + polls += 1; + flag.store(true, Ordering::SeqCst); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::Canceled); + assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); + } + + #[test] + fn fault_text() { + assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); + assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x"); + assert_eq!(first_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid"); + assert_eq!(first_line(&"a".repeat(300)).chars().count(), 201); + assert!(Fault::Error("Out of Memory".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error".into()).is_out_of_memory()); + assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory()); + let h = DeviceHealth::new(); + h.mark(Fault::Error("Validation Error".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.mark(Fault::Lost("reset".into())); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(h.fault().is_some_and(|f| f.is_lost())); + assert!(!Fault::Lost("out of memory".into()).is_out_of_memory()); + } + + #[test] + fn marks_from_several_threads_keep_the_loss() { + let h = DeviceHealth::new(); + let threads: Vec<_> = (0..8) + .map(|i| { + let h = h.clone(); + std::thread::spawn(move || h.mark(if i == 5 { Fault::Lost("reset".into()) } else { Fault::Error(format!("e{i}")) })) + }) + .collect(); + for t in threads { + t.join().unwrap(); + } + assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); + } + + #[test] + fn only_a_lost_device_counts_as_a_loss() { + let validation = + |description: &str| wgpu::Error::Validation { source: Box::new(std::io::Error::other("x")), description: description.into() }; + let lost = validation("Validation Error\n\nCaused by:\n In Device::create_buffer\n Parent device is lost\n"); + assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); + let destroyed = validation("Validation Error\n\nCaused by:\n In Queue::submit\n Buffer 'pc' has been destroyed\n"); + assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error".into())); + let texture = validation("Validation Error\n\nCaused by:\n Texture with 'frame' label has been destroyed\n"); + assert!(!fault_of(&texture).is_lost()); + } +} diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs new file mode 100644 index 0000000000..72c2ba2acf --- /dev/null +++ b/crates/gpu-device/src/lib.rs @@ -0,0 +1,35 @@ +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +#![forbid(unsafe_code)] + +//! Choosing and opening a wgpu device for a Craft app. +//! +//! - [`list`] gives every adapter as plain [`Candidate`] data for a settings page, and +//! [`AdapterKey`] identifies one across runs. +//! - [`select`] and [`ranked`] choose an adapter for a [`Preference`] (Auto, low power, a named +//! adapter, software) with wgpu's own rule and two corrections for drivers that crash +//! ([`choose`]); [`Notice`] says when the choice was not the one asked for. +//! - [`open`] opens a device, moving to the next adapter and last to a software one when a device +//! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` +//! block on wgpu's futures and are native only; a browser build picks with [`pick`]. +//! - [`Capabilities`] reports what the device can do (NV12 and P010 textures, 16-bit norm +//! formats, `f16`, timestamps, sizes). +//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and +//! [`Recovery`] says what to open after a loss. +//! +//! The selection functions are pure, so tests run without a GPU. + +mod adapter; +mod caps; +mod health; +mod open; +mod preference; +mod recovery; + +pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; +pub use caps::{Capabilities, Vendor}; +pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; +pub use open::{OpenError, Opened, Request, pick}; +#[cfg(not(target_arch = "wasm32"))] +pub use open::{list, open}; +pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select}; +pub use recovery::{Recovery, RecoveryPolicy, RecoveryStep}; diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs new file mode 100644 index 0000000000..5156e09c20 --- /dev/null +++ b/crates/gpu-device/src/open.rs @@ -0,0 +1,304 @@ +//! Listing adapters and opening a device, trying the next adapter when one fails. + +use std::fmt; + +#[cfg(not(target_arch = "wasm32"))] +use wgpu::Instance; +use wgpu::{Adapter, Features, Limits, Surface}; + +use crate::adapter::{Candidate, avoided, log_choice}; +use crate::caps::Capabilities; +use crate::health::DeviceHealth; +use crate::preference::{Notice, Preference, Selection, select}; +#[cfg(not(target_arch = "wasm32"))] +use crate::preference::{asked_for, ranked}; + +/// What the device is opened with. +#[derive(Clone, Debug, Default)] +pub struct Request<'a> { + pub label: Option<&'a str>, + /// Features the device must have. An adapter without them is skipped. + pub required_features: Features, + /// Features asked for when the adapter has them. + pub optional_features: Features, + /// The limits to ask for; `None` asks for the adapter's own limits. + pub limits: Option, +} + +/// An opened device. +#[derive(Debug)] +pub struct Opened { + pub adapter: Adapter, + pub device: wgpu::Device, + pub queue: wgpu::Queue, + /// The adapter as plain data. + pub candidate: Candidate, + /// What the device was opened with. + pub caps: Capabilities, + /// Watches the device for a loss and for uncaptured errors. + pub health: DeviceHealth, + /// What to tell the user about the choice. + pub notices: Vec, +} + +/// Why no device could be opened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum OpenError { + /// No adapter is listed that can draw (to the surface, when there is one). + NoAdapter, + /// Every adapter tried failed to open a device; each failure is a [`Notice::DeviceFailed`]. + NoDevice(Vec), + /// The only adapters that can draw are ones [`choose`](crate::choose) never draws with, + /// because their driver can end the process; these are their names. + UnsafeDriver(Vec), +} + +impl fmt::Display for OpenError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + OpenError::NoAdapter => f.write_str("no graphics adapter is available"), + OpenError::NoDevice(notices) => { + f.write_str("no graphics adapter could be opened")?; + for n in notices { + if let Notice::DeviceFailed { adapter, error } = n { + write!(f, "; \"{adapter}\": {error}")?; + } + } + Ok(()) + } + OpenError::UnsafeDriver(names) => { + let names = names.iter().map(|n| format!("\"{n}\"")).collect::>().join(", "); + write!(f, "the only graphics adapters that can draw ({names}) use a driver that can crash; update the graphics driver") + } + } + } +} + +impl std::error::Error for OpenError {} + +/// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface` +/// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's +/// future, which on the web would wait on the thread that must resolve it. +#[cfg(not(target_arch = "wasm32"))] +pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) +} + +/// The adapter to draw with for `preference`, from adapters already listed, with the choice in the +/// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device +/// itself. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), String> { + let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + let Some(selection) = select(&candidates, preference) else { + let left_out = left_out(&candidates); + if !left_out.is_empty() { + return Err(OpenError::UnsafeDriver(left_out).to_string()); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + return Err(format!("no usable graphics adapter among {}: {listed}", candidates.len())); + }; + log_choice(&candidates, selection.index, preference.power()); + for notice in &selection.notices { + log::warn!("{notice}"); + } + let adapter = + adapters.get(selection.index).cloned().ok_or_else(|| format!("graphics adapter {} of {} is missing", selection.index, adapters.len()))?; + Ok((adapter, selection)) +} + +/// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] +/// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter +/// without `request.required_features`, or whose device fails to open, adds a +/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]. +#[cfg(not(target_arch = "wasm32"))] +pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result { + let (adapters, candidates) = list(instance, surface); + // Whether drawing is in software depends on the adapter that opens, which `finish` knows. + let mut notices: Vec = + select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect(); + let order = ranked(&candidates, preference); + if let Some(first) = order.first() { + log_choice(&candidates, *first, preference.power()); + } + let mut tried_software = false; + for index in order { + let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else { + continue; + }; + tried_software |= candidate.is_software(); + match open_on(adapter, request) { + Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), + Err(error) => { + log::warn!("graphics adapter {candidate} could not be opened: {error}"); + notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }); + } + } + } + if !tried_software { + let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; + if let Ok(adapter) = pollster::block_on(instance.request_adapter(&options)) { + let candidate = Candidate::of(&adapter, surface); + match open_on(&adapter, request) { + Ok((device, queue)) => { + log::info!("graphics adapter chosen: {candidate}"); + return Ok(finish(adapter, device, queue, candidate, preference, notices)); + } + Err(error) => notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }), + } + } + } + if notices.iter().any(|n| matches!(n, Notice::DeviceFailed { .. })) { + return Err(OpenError::NoDevice(notices)); + } + let left_out = left_out(&candidates); + if left_out.is_empty() { Err(OpenError::NoAdapter) } else { Err(OpenError::UnsafeDriver(left_out)) } +} + +/// The names of the adapters that can draw but that [`choose`](crate::choose) never draws with. +fn left_out(candidates: &[Candidate]) -> Vec { + candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect() +} + +#[cfg(not(target_arch = "wasm32"))] +fn finish( + adapter: Adapter, + device: wgpu::Device, + queue: wgpu::Queue, + candidate: Candidate, + preference: &Preference, + mut notices: Vec, +) -> Opened { + let caps = Capabilities::of_device(&adapter, &device); + if candidate.is_software() && !asked_for(preference, &candidate) { + notices.push(Notice::SoftwareOnly); + } + for notice in ¬ices { + log::warn!("{notice}"); + } + log::info!("graphics device opened: {caps}"); + let health = DeviceHealth::watch(&device); + Opened { adapter, device, queue, candidate, caps, health, notices } +} + +/// Open a device on `adapter`, or say why it cannot be. +#[cfg(not(target_arch = "wasm32"))] +fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { + let has = adapter.features(); + if !has.contains(request.required_features) { + return Err(format!("it lacks the features {:?}", request.required_features - has)); + } + let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); + let desc = wgpu::DeviceDescriptor { + label: request.label, + required_features: request.required_features | (request.optional_features & has), + required_limits, + ..Default::default() + }; + pollster::block_on(adapter.request_device(&desc)).map_err(|e| e.to_string()) +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::preference::AdapterKey; + + /// An instance whose only adapter is wgpu's noop one, which opens devices without a GPU. wgpu + /// 30 lists it as a software adapter whatever `NoopBackendOptions::device_type` says. + fn noop(features: Option) -> Instance { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, features, ..Default::default() }; + Instance::new(desc) + } + + #[test] + fn a_device_opens_with_the_optional_features_the_adapter_has() { + let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12, "{}", opened.caps); + assert!(!opened.caps.shader_f16 && !opened.caps.timestamps, "only the features asked for: {}", opened.caps); + assert!(opened.notices.is_empty(), "{:?}", opened.notices); + assert!(opened.health.is_ok()); + } + + #[test] + fn an_adapter_without_a_required_feature_is_reported() { + let instance = noop(Some(Features::empty())); + let request = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = open(&instance, None, &Preference::Auto, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!(notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } if error.contains("SHADER_F16"))), "{notices:?}"); + assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}"); + } + + #[test] + fn a_software_adapter_is_reported_unless_it_was_asked_for() { + let cpu = noop(None); + let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap(); + assert!(opened.caps.software); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap(); + assert!(asked.notices.is_empty(), "{:?}", asked.notices); + // the software adapter picked by name is what was asked for + let named = open(&cpu, None, &Preference::Adapter(AdapterKey::of(&asked.candidate)), &Request::default()).unwrap(); + assert!(named.notices.is_empty(), "{:?}", named.notices); + // a named adapter that is gone: the automatic choice, with both notices + let gone = + AdapterKey { name: "gone".into(), backend: "vulkan".into(), vendor: 0x10de, device: 1, pci_bus_id: String::new(), driver: String::new() }; + let opened = open(&cpu, None, &Preference::Adapter(gone.clone()), &Request::default()).unwrap(); + assert_eq!(opened.notices, vec![Notice::AdapterMissing(gone), Notice::SoftwareOnly]); + } + + #[test] + fn no_adapter_is_an_error() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let instance = Instance::new(desc); + assert_eq!(open(&instance, None, &Preference::Auto, &Request::default()).unwrap_err(), OpenError::NoAdapter); + assert_eq!(OpenError::NoAdapter.to_string(), "no graphics adapter is available"); + assert_eq!( + OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), + "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" + ); + assert!(pick(&[], None, &Preference::Auto).is_err()); + } + + #[test] + fn a_zero_timeout_leaves_a_healthy_device_healthy() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + assert!(!opened.health.wait_timeout(&opened.device, None, std::time::Duration::ZERO)); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + assert!(opened.health.wait_timeout(&opened.device, None, std::time::Duration::from_secs(5))); + // an index from another device's queue is one this device never issued + let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + other.queue.submit([]); + let index = other.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, Some(index), std::time::Duration::from_secs(5))); + assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); + } + + #[test] + fn a_lost_device_is_seen_by_its_health() { + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + opened.device.destroy(); + health.probe(&opened.device); + assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); + assert!(!health.is_ok()); + // a later wait does not touch the lost device + assert!(!health.wait(&opened.device, None)); + } + + #[test] + fn pick_returns_the_selected_adapter() { + let instance = noop(None); + let (adapters, candidates) = list(&instance, None); + assert_eq!(candidates.len(), 1); + let (adapter, selection) = pick(&adapters, None, &Preference::Auto).unwrap(); + assert_eq!(selection.index, 0); + assert_eq!(Candidate::of(&adapter, None), candidates[0]); + } +} diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs new file mode 100644 index 0000000000..7a60529c70 --- /dev/null +++ b/crates/gpu-device/src/preference.rs @@ -0,0 +1,404 @@ +//! The adapter the user asked for, and what was drawn with instead when it is not there. + +use std::fmt; + +use wgpu::{Backend, PowerPreference}; + +use crate::adapter::{Candidate, avoided, choose, corrected, intel_vulkan_crashes, type_order}; + +/// Which adapter to draw with. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", tag = "kind"))] +pub enum Preference { + /// The fastest adapter: a discrete GPU before an integrated one, hardware before software. + #[default] + Auto, + /// An integrated GPU before a discrete one, for battery life. + LowPower, + /// One adapter the user picked from [`crate::list`]. + Adapter(AdapterKey), + /// A software adapter that draws on the CPU. + Software, +} + +impl Preference { + /// The power preference that orders the adapters for this preference: low power for + /// [`Preference::LowPower`], high performance otherwise. + pub fn power(&self) -> PowerPreference { + match self { + Preference::LowPower => PowerPreference::LowPower, + _ => PowerPreference::HighPerformance, + } + } +} + +/// What identifies an adapter across runs: the backend, the PCI ids and bus, the driver name, and +/// the name. The order in which the system lists adapters can change between runs, so an index +/// cannot be kept. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", default))] +pub struct AdapterKey { + pub name: String, + /// wgpu's lowercase backend name (`vulkan`, `dx12`, `metal`, `gl`). + pub backend: String, + pub vendor: u32, + pub device: u32, + /// Empty when the driver reports none. + pub pci_bus_id: String, + /// The Vulkan driver's name, which tells apart two Vulkan drivers for one GPU (such as two on + /// Linux) and stays the same across versions of a driver. Empty on the other backends, and + /// when the driver reports none. + pub driver: String, +} + +impl AdapterKey { + pub fn of(candidate: &Candidate) -> Self { + AdapterKey { + name: candidate.name.clone(), + backend: backend_name(candidate.backend).to_string(), + vendor: candidate.vendor, + device: candidate.device, + pci_bus_id: candidate.pci_bus_id.clone(), + // DirectX 12 reports the driver's version here, which changes with every update. + driver: if candidate.backend == Backend::Vulkan { candidate.driver.clone() } else { String::new() }, + } + } + + /// Whether `candidate` is this adapter: the same backend and PCI ids, the same bus and the + /// same driver when both report one, and the same name when the backend reports no PCI ids. + pub fn matches(&self, candidate: &Candidate) -> bool { + let identified = self.vendor != 0 || self.device != 0; + let same = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b; + self.backend == backend_name(candidate.backend) + && self.vendor == candidate.vendor + && self.device == candidate.device + && same(&self.pci_bus_id, &candidate.pci_bus_id) + && same(&self.driver, &candidate.driver) + && (identified || self.name == candidate.name) + } +} + +impl fmt::Display for AdapterKey { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "\"{}\" ({})", self.name, self.backend) + } +} + +/// wgpu's lowercase name of `backend`. +pub fn backend_name(backend: Backend) -> &'static str { + backend.to_str() +} + +/// Something the app tells the user about the adapter it draws with. The [`fmt::Display`] text is +/// English, for the log; an app shows its own translated text for each variant. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Notice { + /// The adapter the user picked is not listed (unplugged, disabled, or its driver removed). + /// The automatic choice draws instead. + AdapterMissing(AdapterKey), + /// Software was asked for and no software adapter is listed. The automatic choice draws + /// instead. + NoSoftwareAdapter, + /// The only adapter that can draw is a software one: drawing is slower and uses the CPU. + SoftwareOnly, + /// An adapter could not open a device, and the next one was tried. + DeviceFailed { adapter: String, error: String }, + /// The device was lost this many times in a short time, so drawing moved to software. + SoftwareAfterLosses(u32), +} + +impl fmt::Display for Notice { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Notice::AdapterMissing(key) => write!(f, "the graphics adapter {key} is not available; using the automatic choice"), + Notice::NoSoftwareAdapter => f.write_str("no software graphics adapter is available; using the automatic choice"), + Notice::SoftwareOnly => f.write_str("no graphics hardware can be used; drawing in software, which is slower"), + Notice::DeviceFailed { adapter, error } => { + write!(f, "the graphics adapter \"{adapter}\" could not be opened ({error}); trying the next one") + } + Notice::SoftwareAfterLosses(n) => write!(f, "the graphics device stopped working {n} times; drawing in software"), + } + } +} + +/// The adapter chosen for a preference, and what the user should be told about it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Selection { + /// Index into the candidates. + pub index: usize, + pub notices: Vec, +} + +/// The adapter to draw with for `preference`, or `None` when no adapter is usable. +/// +/// - [`Preference::Auto`] and [`Preference::LowPower`] use [`choose`]. +/// - [`Preference::Adapter`] uses the usable entry that matches the key (the one exposing the most +/// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when +/// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and +/// [`Notice::AdapterMissing`]. +/// - [`Preference::Software`] uses the first usable software adapter; without one, the automatic +/// choice and [`Notice::NoSoftwareAdapter`]. +/// +/// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. +pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { + let mut notices = Vec::new(); + let wanted = match preference { + Preference::Auto | Preference::LowPower => None, + Preference::Adapter(key) => { + // An entry that reports no bus id matches any saved bus. When it is the same model on + // the same driver it cannot be told apart from an older version of that driver, and + // the correction draws with the entry exposing the most features. + let found = + candidates.iter().enumerate().filter(|(_, c)| c.usable && key.matches(c)).max_by_key(|(i, c)| (c.features, std::cmp::Reverse(*i))); + match found.map(|(index, c)| corrected(candidates, index, c)) { + Some(index) if !candidates.get(index).is_some_and(intel_vulkan_crashes) => Some(index), + _ => { + notices.push(Notice::AdapterMissing(key.clone())); + None + } + } + } + Preference::Software => { + let found = candidates.iter().position(|c| c.usable && c.is_software()); + if found.is_none() { + notices.push(Notice::NoSoftwareAdapter); + } + found + } + }; + let index = match wanted { + Some(index) => index, + None => { + let index = choose(candidates, preference.power())?; + if candidates.get(index).is_some_and(Candidate::is_software) { + notices.push(Notice::SoftwareOnly); + } + index + } + }; + Some(Selection { index, notices }) +} + +/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key +/// of this adapter. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool { + match preference { + Preference::Software => candidate.is_software(), + Preference::Adapter(key) => key.matches(candidate), + Preference::Auto | Preference::LowPower => false, + } +} + +/// The order in which to try opening a device for `preference`: [`select`]'s choice first, then +/// every other usable adapter by device type for the preference's power (software after +/// hardware), leaving out the entries [`choose`] never draws with: an older version of a driver +/// listed twice, and the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver. +/// Empty when no adapter is usable. +pub fn ranked(candidates: &[Candidate], preference: &Preference) -> Vec { + let Some(first) = select(candidates, preference).map(|s| s.index) else { + return Vec::new(); + }; + let power = preference.power(); + let mut rest: Vec = + (0..candidates.len()).filter(|&i| i != first && candidates.get(i).is_some_and(|c| c.usable) && !avoided(candidates, i)).collect(); + rest.sort_by_key(|&i| (candidates.get(i).map_or(u8::MAX, |c| type_order(c.device_type, power)), i)); + let mut order = vec![first]; + order.extend(rest); + order +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::adapter::tests::{gpu, two_amd_drivers, uhd_630}; + use wgpu::Backend::{Dx12, Vulkan}; + use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu}; + + fn key_of(candidates: &[Candidate], index: usize) -> AdapterKey { + candidates.get(index).map(AdapterKey::of).unwrap_or_default() + } + + #[test] + fn auto_and_low_power_are_the_corrected_wgpu_choice() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Auto), Some(Selection { index: 1, notices: vec![] })); + assert_eq!(select(&adapters, &Preference::LowPower).map(|s| s.index), Some(2)); + assert_eq!(select(&[], &Preference::Auto), None); + assert_eq!(Preference::default(), Preference::Auto); + } + + #[test] + fn a_named_adapter_is_found_wherever_it_is_listed() { + let adapters = two_amd_drivers(); + // the integrated Radeon through DirectX 12, picked by the user + let key = key_of(&adapters, 4); + assert_eq!(select(&adapters, &Preference::Adapter(key.clone())).map(|s| s.index), Some(4)); + // listed in another order on the next run + let mut reordered = adapters.clone(); + reordered.reverse(); + assert_eq!(select(&reordered, &Preference::Adapter(key)).map(|s| s.index), Some(1)); + // the stale Vulkan entry of the RX 6800M stored as the choice: the newer version draws + let stale = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(stale)).map(|s| s.index), Some(1)); + } + + #[test] + fn a_named_intel_gen9_vulkan_entry_draws_through_directx_12() { + let adapters = uhd_630(); + let vulkan = key_of(&adapters, 0); + assert_eq!(select(&adapters, &Preference::Adapter(vulkan.clone())).map(|s| s.index), Some(1)); + // without the DirectX 12 entry, the named Vulkan entry is not available + let mut dx12_unusable = adapters.clone(); + dx12_unusable[1].usable = false; + let s = select(&dx12_unusable, &Preference::Adapter(vulkan.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((2, vec![Notice::AdapterMissing(vulkan), Notice::SoftwareOnly]))); + } + + #[test] + fn a_missing_named_adapter_falls_back_to_auto_with_a_notice() { + let adapters = two_amd_drivers(); + let gone = AdapterKey { + name: "NVIDIA GeForce RTX 4090".into(), + backend: "vulkan".into(), + vendor: 0x10de, + device: 0x2684, + pci_bus_id: String::new(), + driver: "NVIDIA".into(), + }; + let s = select(&adapters, &Preference::Adapter(gone.clone())); + assert_eq!(s, Some(Selection { index: 1, notices: vec![Notice::AdapterMissing(gone.clone())] })); + // listed but unable to draw to the window counts as missing + let mut unusable = adapters.clone(); + for c in &mut unusable { + c.usable = c.backend != Vulkan; + } + let vulkan_key = key_of(&adapters, 1); + let s = select(&unusable, &Preference::Adapter(vulkan_key.clone())); + assert_eq!(s.map(|s| (s.index, s.notices)), Some((3, vec![Notice::AdapterMissing(vulkan_key)]))); + // nothing usable at all + assert_eq!(select(&[], &Preference::Adapter(gone)), None); + } + + #[test] + fn keys_tell_apart_backends_buses_and_unidentified_names() { + let adapters = two_amd_drivers(); + let dx12 = key_of(&adapters, 3); + assert!(dx12.matches(&adapters[3])); + assert!(!dx12.matches(&adapters[1]), "same GPU, other backend"); + let other_bus = Candidate { pci_bus_id: "0000:04:00.0".into(), ..adapters[3].clone() }; + assert!(!dx12.matches(&other_bus)); + // a key stored without a bus id still matches an entry that reports one + let no_bus = AdapterKey { pci_bus_id: String::new(), ..dx12.clone() }; + assert!(no_bus.matches(&adapters[3])); + // two Vulkan drivers for one GPU are told apart by the driver name; a key saved without + // one matches either + let radv = gpu("AMD Radeon RX 6800M (RADV NAVI22)", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "radv", "Mesa 25.2.4", 70); + let amdvlk = gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "AMD open-source driver", "2025.Q2.1", 72); + let two = vec![radv.clone(), amdvlk.clone()]; + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&radv))).map(|s| s.index), Some(0)); + assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&amdvlk))).map(|s| s.index), Some(1)); + let old = AdapterKey { driver: String::new(), ..AdapterKey::of(&radv) }; + assert!(old.matches(&radv) && old.matches(&amdvlk)); + // a DirectX 12 key keeps matching after a driver update changes the reported version + assert!(dx12.driver.is_empty()); + let updated = Candidate { driver: "32.0.21045.12000".into(), ..adapters[3].clone() }; + assert!(dx12.matches(&updated)); + // OpenGL reports no ids: the name decides + let angle = gpu("ANGLE (D3D11)", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let swiftshader = gpu("SwiftShader", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20); + let key = AdapterKey::of(&angle); + assert!(key.matches(&angle) && !key.matches(&swiftshader)); + assert_eq!(dx12.to_string(), "\"AMD Radeon RX 6800M\" (dx12)"); + } + + #[test] + fn software_is_used_when_asked_and_reported_when_it_is_all_there_is() { + let adapters = two_amd_drivers(); + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 5, notices: vec![] })); + let hardware_only: Vec = adapters.iter().filter(|c| !c.is_software()).cloned().collect(); + assert_eq!(select(&hardware_only, &Preference::Software), Some(Selection { index: 1, notices: vec![Notice::NoSoftwareAdapter] })); + let llvmpipe = vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)]; + assert_eq!(select(&llvmpipe, &Preference::Auto), Some(Selection { index: 0, notices: vec![Notice::SoftwareOnly] })); + assert_eq!(select(&llvmpipe, &Preference::Software), Some(Selection { index: 0, notices: vec![] })); + // picked by name, it is what was asked for + let named = Preference::Adapter(AdapterKey::of(&llvmpipe[0])); + assert_eq!(select(&llvmpipe, &named), Some(Selection { index: 0, notices: vec![] })); + #[cfg(not(target_arch = "wasm32"))] + { + assert!(asked_for(&named, &llvmpipe[0]) && asked_for(&Preference::Software, &llvmpipe[0])); + assert!(!asked_for(&Preference::Auto, &llvmpipe[0]) && !asked_for(&Preference::Software, &adapters[1])); + } + } + + #[test] + fn the_fallback_order_never_tries_entries_that_can_crash() { + let adapters = two_amd_drivers(); + // the newer RX 6800M, then the other hardware by type for high performance, then software; + // the stale RX 6800M entry is never tried + assert_eq!(ranked(&adapters, &Preference::Auto), vec![1, 3, 2, 4, 5]); + assert_eq!(ranked(&adapters, &Preference::LowPower), vec![2, 4, 1, 3, 5]); + assert_eq!(ranked(&adapters, &Preference::Software), vec![5, 1, 3, 2, 4]); + // two cards of one model on one driver, one without a Vulkan bus id: the second card's + // Vulkan entry looks like an older version, and the card is tried through DirectX 12 + let card = |bus: &str| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, 0x1002, 0x744c, bus, "AMD proprietary driver", "", 68); + let dx12 = |bus: &str| gpu("AMD Radeon RX 7900 XT", Dx12, DiscreteGpu, 0x1002, 0x744c, bus, "32.0.21045.11001", "", 36); + let twins = vec![card("0000:03:00.0"), card(""), dx12("0000:03:00.0"), dx12("0000:04:00.0")]; + assert_eq!(ranked(&twins, &Preference::Auto), vec![0, 2, 3]); + // the same bus id on both entries: one GPU, and the older version is never tried + let mut versions = vec![card("0000:03:00.0"), card("0000:03:00.0")]; + versions[1].features = 70; + assert_eq!(ranked(&versions, &Preference::Auto), vec![1]); + // a third entry without a bus id and with more features: both older entries are left out + versions.push(card("")); + versions[2].features = 80; + assert_eq!(ranked(&versions, &Preference::Auto), vec![2]); + // two GPUs on different buses are both tried + let cards = vec![card("0000:03:00.0"), card("0000:04:00.0")]; + assert_eq!(ranked(&cards, &Preference::Auto), vec![0, 1]); + // the Intel Gen 9 Vulkan entry is never tried, with or without a usable DirectX 12 entry + assert_eq!(ranked(&uhd_630(), &Preference::Auto), vec![1, 2]); + let mut dx12_unusable = uhd_630(); + dx12_unusable[1].usable = false; + assert_eq!(ranked(&dx12_unusable, &Preference::Auto), vec![2]); + assert!(ranked(&uhd_630()[..1], &Preference::Auto).is_empty()); + assert!(ranked(&[], &Preference::Auto).is_empty()); + let unusable: Vec = adapters.iter().map(|c| Candidate { usable: false, ..c.clone() }).collect(); + assert!(ranked(&unusable, &Preference::Auto).is_empty()); + } + + #[test] + fn a_laptop_with_two_vendors_keeps_the_named_gpu_across_reorders() { + let intel = gpu("Intel(R) UHD Graphics 770", Dx12, IntegratedGpu, 0x8086, 0x4680, "0000:00:02.0", "31.0.101.5186", "", 36); + let nvidia = gpu("NVIDIA GeForce RTX 4070 Laptop GPU", Dx12, DiscreteGpu, 0x10de, 0x2820, "0000:01:00.0", "32.0.15.6094", "", 36); + let a = vec![intel.clone(), nvidia.clone()]; + let b = vec![nvidia, intel]; + let picked = Preference::Adapter(key_of(&a, 0)); + assert_eq!(select(&a, &picked).map(|s| s.index), Some(0)); + assert_eq!(select(&b, &picked).map(|s| s.index), Some(1)); + assert_eq!(ranked(&b, &picked), vec![1, 0]); + } + + #[cfg(feature = "serde")] + #[test] + fn preferences_read_back_what_they_write() { + let key = AdapterKey { + name: "AMD Radeon RX 6800M".into(), + backend: "dx12".into(), + vendor: 0x1002, + device: 0x73df, + pci_bus_id: "0000:03:00.0".into(), + driver: String::new(), + }; + for p in [Preference::Auto, Preference::LowPower, Preference::Software, Preference::Adapter(key)] { + let text = serde_json::to_string(&p).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), p, "{text}"); + } + assert_eq!(serde_json::to_string(&Preference::Auto).unwrap(), r#"{"kind":"auto"}"#); + // a key written by an older version without some fields + let p: Preference = serde_json::from_str(r#"{"kind":"adapter","name":"x","backend":"vulkan"}"#).unwrap(); + assert_eq!(p, Preference::Adapter(AdapterKey { name: "x".into(), backend: "vulkan".into(), ..Default::default() })); + assert!(serde_json::from_str::(r#"{"kind":"fastest"}"#).is_err()); + } +} diff --git a/crates/gpu-device/src/recovery.rs b/crates/gpu-device/src/recovery.rs new file mode 100644 index 0000000000..2732d8c986 --- /dev/null +++ b/crates/gpu-device/src/recovery.rs @@ -0,0 +1,153 @@ +//! What to open after a device loss. +//! +//! A device is lost when the driver resets the GPU, the OS ends a long submission, the PC sleeps, +//! or the GPU is unplugged. The app drops everything it made with the device and opens a new one. +//! [`Recovery`] decides with what preference: the user's own, until the device has been lost +//! [`RecoveryPolicy::max_losses`] times within [`RecoveryPolicy::window`], and software after that, +//! so a GPU that keeps failing does not stop the app from drawing. + +use std::collections::VecDeque; +use std::time::Duration; + +use crate::preference::{Notice, Preference}; + +/// When repeated losses move drawing to software. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RecoveryPolicy { + /// Losses within [`window`](Self::window) after which the next device is a software one. + /// 0 never moves to software. + pub max_losses: u32, + pub window: Duration, +} + +impl Default for RecoveryPolicy { + fn default() -> Self { + RecoveryPolicy { max_losses: 3, window: Duration::from_secs(600) } + } +} + +/// The preference to open the next device with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RecoveryStep { + pub preference: Preference, + /// [`Notice::SoftwareAfterLosses`] when this step moved drawing to software. + pub notice: Option, +} + +/// Device losses seen so far, against the user's preference. +#[derive(Clone, Debug)] +pub struct Recovery { + preference: Preference, + policy: RecoveryPolicy, + /// When each loss inside the window happened, oldest first. + losses: VecDeque, + software: bool, +} + +impl Recovery { + pub fn new(preference: Preference, policy: RecoveryPolicy) -> Self { + Recovery { preference, policy, losses: VecDeque::new(), software: false } + } + + /// The preference to open a device with now. + pub fn preference(&self) -> &Preference { + if self.software { &Preference::Software } else { &self.preference } + } + + /// The user changed the preference: losses counted so far no longer apply. + pub fn set_preference(&mut self, preference: Preference) { + self.preference = preference; + self.losses.clear(); + self.software = false; + } + + /// Record a loss at `at`, a monotonic time the caller keeps (since the app started), and + /// return what to open next. A time earlier than the last loss counts as the same time. + pub fn lost(&mut self, at: Duration) -> RecoveryStep { + let at = self.losses.back().map_or(at, |last| at.max(*last)); + self.losses.push_back(at); + // Only the last `max_losses` losses decide anything, so no more are kept. + let keep = usize::try_from(self.policy.max_losses.max(1)).unwrap_or(usize::MAX); + while self.losses.len() > keep || self.losses.front().is_some_and(|first| at.saturating_sub(*first) > self.policy.window) { + self.losses.pop_front(); + } + let count = u32::try_from(self.losses.len()).unwrap_or(u32::MAX); + let mut notice = None; + if !self.software && self.policy.max_losses > 0 && count >= self.policy.max_losses && self.preference != Preference::Software { + self.software = true; + notice = Some(Notice::SoftwareAfterLosses(count)); + } + RecoveryStep { preference: self.preference().clone(), notice } + } + + /// Losses inside the window, as of the last one, counting at most + /// [`RecoveryPolicy::max_losses`] (at least 1). + pub fn recent_losses(&self) -> usize { + self.losses.len() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(secs: u64) -> Duration { + Duration::from_secs(secs) + } + + #[test] + fn the_third_loss_in_ten_minutes_moves_to_software() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy::default()); + assert_eq!(r.lost(s(10)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(100)), RecoveryStep { preference: Preference::Auto, notice: None }); + assert_eq!(r.lost(s(300)), RecoveryStep { preference: Preference::Software, notice: Some(Notice::SoftwareAfterLosses(3)) }); + // it stays on software, and says so once + assert_eq!(r.lost(s(400)), RecoveryStep { preference: Preference::Software, notice: None }); + assert_eq!(r.preference(), &Preference::Software); + } + + #[test] + fn losses_outside_the_window_are_forgotten() { + let mut r = Recovery::new(Preference::LowPower, RecoveryPolicy::default()); + r.lost(s(0)); + r.lost(s(500)); + // the first loss is more than 600 s before this one + assert_eq!(r.lost(s(601)).preference, Preference::LowPower); + assert_eq!(r.recent_losses(), 2); + // a clock that goes back counts as the last loss's time + assert_eq!(r.lost(s(1)).preference, Preference::Software); + } + + #[test] + fn changing_the_preference_starts_over() { + let mut r = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 2, window: s(60) }); + r.lost(s(1)); + assert_eq!(r.lost(s(2)).preference, Preference::Software); + r.set_preference(Preference::LowPower); + assert_eq!(r.preference(), &Preference::LowPower); + assert_eq!(r.recent_losses(), 0); + assert_eq!(r.lost(s(3)).preference, Preference::LowPower); + } + + #[test] + fn software_and_a_zero_limit_never_add_a_notice() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy::default()); + for t in 0..5 { + assert_eq!(r.lost(s(t)), RecoveryStep { preference: Preference::Software, notice: None }); + } + let mut never = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 0, window: s(60) }); + for t in 0..10 { + assert_eq!(never.lost(s(t)).preference, Preference::Auto); + } + assert_eq!(never.recent_losses(), 1); + } + + #[test] + fn the_loss_history_stays_bounded() { + let mut r = Recovery::new(Preference::Software, RecoveryPolicy { max_losses: 3, window: Duration::MAX }); + for _ in 0..10_000 { + r.lost(s(5)); + } + assert_eq!(r.recent_losses(), 3); + } +} From 5c4c73f4a96ef13aae4118aa1b63e4bad9d01b33 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 11:01:11 -0800 Subject: [PATCH 02/17] craft-gpu-device: bounded waits keep one target, and a label cannot mark a loss - wait_timeout and wait_timeout_cancelable take a submission index instead of an Option. Every 100 ms slice waits for that index, so work submitted during the wait no longer moves the target and can no longer make a healthy device time out. Pass queue.submit([]) to wait for everything submitted so far. - An uncaptured error counts as a device loss only when an error in its source chain is wgpu's "Parent device is lost". A resource label that contains those words, on its own line or not, is recorded as an error. --- crates/gpu-device/README.md | 8 ++- crates/gpu-device/src/health.rs | 90 +++++++++++++++++++++++++-------- crates/gpu-device/src/open.rs | 7 +-- 3 files changed, 78 insertions(+), 27 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index ee05ec009b..32b4750f91 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -42,8 +42,12 @@ Licensed under MIT OR Apache-2.0. driver reports no bus id, a second GPU of the same model on the same driver looks like an older version, and is used through its other backend (DirectX 12 on Windows, OpenGL elsewhere). -- Only an error that says the device is lost counts as a loss. An error about a destroyed buffer - or texture is recorded as an error. +- Only an error whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in + a resource's label do not count. An error about a destroyed buffer or texture is recorded as an + error. +- `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for + everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the + wait. - `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that `Device::poll` raises on a lost device and record the loss. diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index a113ee783c..c2254ee4e9 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -257,25 +257,27 @@ impl DeviceHealth { } } - /// Like [`Self::wait`], but bounded: returns whether the submitted work finished within - /// `timeout`. A timeout marks the device faulted, so later work stops going to a GPU that no - /// longer answers. A submission index the device never issued returns `false` and leaves the - /// device healthy. A zero `timeout`, or - /// one that passes before the first poll, returns `false` and leaves the device healthy. A - /// device that was already faulted returns `false` unchanged. + /// Like [`Self::wait`], but bounded: returns whether the work up to `index` finished within + /// `timeout`. To wait for everything submitted so far, pass the index of an empty submission + /// (`queue.submit([])`); work submitted after it does not extend the wait. A timeout marks the + /// device faulted, so later work stops going to a GPU that no longer answers. A submission + /// index the device never issued returns `false` and leaves the device healthy. A zero + /// `timeout`, or one that passes before the first poll, returns `false` and leaves the device + /// healthy. A device that was already faulted returns `false` unchanged. #[cfg(not(target_arch = "wasm32"))] - pub fn wait_timeout(&self, device: &wgpu::Device, index: Option, timeout: Duration) -> bool { + pub fn wait_timeout(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, timeout: Duration) -> bool { self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished } /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between - /// them, keeping the same overall deadline. A slice that times out means the work has not - /// finished yet; only the overall deadline (or a poll that panics) marks the device faulted. + /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice + /// that times out means the work has not finished yet; only the overall deadline (or a poll + /// that panics) marks the device faulted. #[cfg(not(target_arch = "wasm32"))] pub fn wait_timeout_cancelable( &self, device: &wgpu::Device, - index: Option, + index: wgpu::SubmissionIndex, timeout: Duration, canceled: &(dyn Fn() -> bool + Sync), ) -> WaitOutcome { @@ -287,7 +289,7 @@ impl DeviceHealth { let outcome = wait_slices(timeout, canceled, |slice| { polled = true; let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - device.poll(wgpu::PollType::Wait { submission_index: index.clone(), timeout: Some(slice) }) + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) })); match poll { Ok(Ok(_)) => { @@ -350,16 +352,29 @@ fn wait_slices(total: Duration, canceled: &(dyn Fn() -> bool + Sync), mut poll: } } -/// The fault a wgpu error stands for. An error that names a lost device follows a device loss -/// whose callback may not have run yet (it runs on the next poll), so it counts as a loss rather -/// than as an error. An error about a destroyed buffer or texture is an error. Only wgpu's own -/// out-of-memory error is [`OUT_OF_MEMORY`]. +/// The whole message of wgpu's `DeviceError::Lost`. +const LOST_CAUSE: &str = "Parent device is lost"; + +/// Whether one of the errors that caused `e` (its `source` chain) is wgpu's `DeviceError::Lost`: +/// an error whose whole message is [`LOST_CAUSE`]. A resource label is part of another error's +/// message, so a label never matches. +fn caused_by_loss(e: &wgpu::Error) -> bool { + let source: &(dyn std::error::Error + 'static) = match e { + wgpu::Error::Validation { source, .. } | wgpu::Error::Internal { source, .. } => source.as_ref(), + _ => return false, + }; + std::iter::successors(Some(source), |c| c.source()).any(|c| c.to_string().trim().eq_ignore_ascii_case(LOST_CAUSE)) +} + +/// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`]) +/// follows a device loss whose callback may not have run yet (it runs on the next poll), so it +/// counts as a loss rather than as an error. An error about a destroyed buffer or texture is an +/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. fn fault_of(e: &wgpu::Error) -> Fault { let text = e.to_string(); - let lower = text.to_ascii_lowercase(); if matches!(e, wgpu::Error::OutOfMemory { .. }) { Fault::Error(OUT_OF_MEMORY.into()) - } else if lower.contains("device is lost") { + } else if caused_by_loss(e) { Fault::Lost(first_line(&text)) } else { Fault::Error(first_line(&text)) @@ -474,15 +489,46 @@ mod tests { assert_eq!(h.fault(), Some(Fault::Lost("reset".into()))); } + /// An error and the errors that caused it, outermost first, as wgpu-core chains them. + #[derive(Debug)] + struct Cause(&'static str, Option>); + + impl fmt::Display for Cause { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.0) + } + } + + impl std::error::Error for Cause { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + self.1.as_deref().map(|c| c as _) + } + } + + /// A validation error with the causes `chain` and wgpu's description of them. + fn validation(chain: &[&'static str]) -> wgpu::Error { + let source = chain.iter().rev().fold(None, |inner, text| Some(Box::new(Cause(text, inner)))); + let mut description = String::from("Validation Error\n\nCaused by:\n"); + for c in chain { + description.push_str(&format!(" {c}\n")); + } + wgpu::Error::Validation { source: source.unwrap_or_else(|| Box::new(Cause("", None))), description } + } + #[test] fn only_a_lost_device_counts_as_a_loss() { - let validation = - |description: &str| wgpu::Error::Validation { source: Box::new(std::io::Error::other("x")), description: description.into() }; - let lost = validation("Validation Error\n\nCaused by:\n In Device::create_buffer\n Parent device is lost\n"); + let lost = validation(&["In Device::create_buffer", "Parent device is lost"]); assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); - let destroyed = validation("Validation Error\n\nCaused by:\n In Queue::submit\n Buffer 'pc' has been destroyed\n"); + let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]); assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error".into())); - let texture = validation("Validation Error\n\nCaused by:\n Texture with 'frame' label has been destroyed\n"); + let texture = validation(&["Texture with 'frame' label has been destroyed"]); assert!(!fault_of(&texture).is_lost()); + // a label is the caller's text, not the cause, even on a line of its own + let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]); + assert_eq!(fault_of(&labeled), Fault::Error("Validation Error".into())); + for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] { + let labeled = validation(&["In Queue::submit", label]); + assert!(!fault_of(&labeled).is_lost(), "{label:?}"); + } } } diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 5156e09c20..388d8bdd20 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -269,14 +269,15 @@ mod tests { #[test] fn a_zero_timeout_leaves_a_healthy_device_healthy() { let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); - assert!(!opened.health.wait_timeout(&opened.device, None, std::time::Duration::ZERO)); + let everything = opened.queue.submit([]); + assert!(!opened.health.wait_timeout(&opened.device, everything.clone(), std::time::Duration::ZERO)); assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); - assert!(opened.health.wait_timeout(&opened.device, None, std::time::Duration::from_secs(5))); + assert!(opened.health.wait_timeout(&opened.device, everything, std::time::Duration::from_secs(5))); // an index from another device's queue is one this device never issued let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); other.queue.submit([]); let index = other.queue.submit([]); - assert!(!opened.health.wait_timeout(&opened.device, Some(index), std::time::Duration::from_secs(5))); + assert!(!opened.health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5))); assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); } From 30a5407a74f6245fe820ebad7f53e5e99873b85c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:25:37 -0800 Subject: [PATCH 03/17] craft-gpu-device: keep only third-party sources in ATTRIBUTION.md --- ATTRIBUTION.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f2c076c222..96091a1b5a 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -144,4 +144,4 @@ Sanitization, animation fitting and numeric output policy remain caller-owned. ## GPU device selection -`crates/gpu-device` comes from StudioCraft `crates/craft-gpu-device` at `17e2120f7d79bb677e2871a4192ba1ced1dab57a` (MIT OR Apache-2.0). Its adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. +`crates/gpu-device`'s adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both. From 50b82932cadb25ac99d9ab6ad8ff1227ca337394 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 13:33:20 -0800 Subject: [PATCH 04/17] craft-gpu-device: Software draws with the newest version of a driver listed twice Preference::Software took the first usable software entry without the correction Auto, LowPower and Adapter apply. When one driver listed a software adapter twice, a stale version could be chosen, and the fallback order then left the newer one out. Every preference now goes through the same correction. --- crates/gpu-device/src/preference.rs | 36 +++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 9 deletions(-) diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs index 7a60529c70..a9a107e9a8 100644 --- a/crates/gpu-device/src/preference.rs +++ b/crates/gpu-device/src/preference.rs @@ -137,8 +137,8 @@ pub struct Selection { /// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when /// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and /// [`Notice::AdapterMissing`]. -/// - [`Preference::Software`] uses the first usable software adapter; without one, the automatic -/// choice and [`Notice::NoSoftwareAdapter`]. +/// - [`Preference::Software`] uses the first usable software adapter, with [`choose`]'s +/// corrections; without one, the automatic choice and [`Notice::NoSoftwareAdapter`]. /// /// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`]. pub fn select(candidates: &[Candidate], preference: &Preference) -> Option { @@ -151,16 +151,14 @@ pub fn select(candidates: &[Candidate], preference: &Preference) -> Option Some(index), - _ => { - notices.push(Notice::AdapterMissing(key.clone())); - None - } + let found = found.and_then(|(index, _)| drawn_with(candidates, index)); + if found.is_none() { + notices.push(Notice::AdapterMissing(key.clone())); } + found } Preference::Software => { - let found = candidates.iter().position(|c| c.usable && c.is_software()); + let found = candidates.iter().position(|c| c.usable && c.is_software()).and_then(|index| drawn_with(candidates, index)); if found.is_none() { notices.push(Notice::NoSoftwareAdapter); } @@ -180,6 +178,15 @@ pub fn select(candidates: &[Candidate], preference: &Preference) -> Option Option { + let index = corrected(candidates, index, candidates.get(index)?); + (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) +} + /// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key /// of this adapter. #[cfg(not(target_arch = "wasm32"))] @@ -332,6 +339,17 @@ mod tests { } } + #[test] + fn software_draws_with_the_newer_version_of_a_driver_listed_twice() { + let stale = gpu("llvmpipe (LLVM 15.0.7, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 23.0.4", 40); + let newer = gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 25.2.4", 50); + let hardware = gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "32.0.21045.11001", "", 36); + let adapters = vec![stale, newer, hardware]; + assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 1, notices: vec![] })); + // the stale entry is never tried, and the newer one is not left out + assert_eq!(ranked(&adapters, &Preference::Software), vec![1, 2]); + } + #[test] fn the_fallback_order_never_tries_entries_that_can_crash() { let adapters = two_amd_drivers(); From 383ae5d15b656b04c54ee79896772f7176ddaf29 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Tue, 17 Nov 2026 17:47:09 -0800 Subject: [PATCH 05/17] craft-gpu-device: pick returns OpenError, and the docs describe the web path pick now returns OpenError instead of a String, so a caller can tell UnsafeDriver from NoAdapter. With no usable adapter it logs the listed adapters and returns NoAdapter. egui-wgpu's selector takes a String, so that caller converts with map_err(|e| e.to_string()). The crate docs and README now say what applies in a browser: WebGPU lists only the adapter the browser offers, a web build requests it with Preference::power(), and Capabilities, Recovery and DeviceHealth (apart from its blocking waits) work there. --- crates/gpu-device/README.md | 11 ++++++++-- crates/gpu-device/src/lib.rs | 6 +++++- crates/gpu-device/src/open.rs | 39 +++++++++++++++++++++++++---------- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 32b4750f91..fe8037fcae 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -20,7 +20,7 @@ Licensed under MIT OR Apache-2.0. | `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | | `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | | `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | -| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector` | +| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that selector) | | `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one | | `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | | `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | @@ -28,7 +28,14 @@ Licensed under MIT OR Apache-2.0. ## Failure cases -- With no usable adapter, `select` returns `None` and `open` returns `OpenError::NoAdapter`. +- With no usable adapter, `select` returns `None`, and `open` and `pick` return + `OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the + process can draw. +- In a browser, WebGPU lists only the adapter the browser offers, so a named adapter cannot be + chosen. A web build requests the adapter with `Preference::power()` as the power preference + and opens the device itself. `Capabilities` and `Recovery` work there as they do on native, + and so does `DeviceHealth` apart from `wait`, `wait_timeout` and `wait_timeout_cancelable`, + which are native only. - An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists each failure. diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs index 72c2ba2acf..c41f041f5f 100644 --- a/crates/gpu-device/src/lib.rs +++ b/crates/gpu-device/src/lib.rs @@ -10,7 +10,11 @@ //! ([`choose`]); [`Notice`] says when the choice was not the one asked for. //! - [`open`] opens a device, moving to the next adapter and last to a software one when a device //! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` -//! block on wgpu's futures and are native only; a browser build picks with [`pick`]. +//! block on wgpu's futures and are native only. +//! - In a browser, WebGPU lists only the adapter the browser offers, so a named adapter cannot be +//! chosen. A web build requests the adapter with [`Preference::power`] as the power preference +//! and opens the device itself. [`Capabilities`] and [`Recovery`] work there as they do on +//! native, and so does [`DeviceHealth`] apart from its blocking waits, which are native only. //! - [`Capabilities`] reports what the device can do (NV12 and P010 textures, 16-bit norm //! formats, `f16`, timestamps, sizes). //! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 388d8bdd20..8f31a851ee 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -88,26 +88,35 @@ pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec /// The adapter to draw with for `preference`, from adapters already listed, with the choice in the /// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device -/// itself. -pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), String> { +/// itself; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`. +/// With no usable adapter the error is [`OpenError::UnsafeDriver`] when only adapters that +/// [`choose`](crate::choose) never draws with can draw, and [`OpenError::NoAdapter`] otherwise, +/// with the listed adapters in the log. +pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), OpenError> { let candidates: Vec = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); let Some(selection) = select(&candidates, preference) else { - let left_out = left_out(&candidates); - if !left_out.is_empty() { - return Err(OpenError::UnsafeDriver(left_out).to_string()); - } - let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); - return Err(format!("no usable graphics adapter among {}: {listed}", candidates.len())); + return Err(unselected(&candidates)); }; log_choice(&candidates, selection.index, preference.power()); for notice in &selection.notices { log::warn!("{notice}"); } - let adapter = - adapters.get(selection.index).cloned().ok_or_else(|| format!("graphics adapter {} of {} is missing", selection.index, adapters.len()))?; + let adapter = adapters.get(selection.index).cloned().ok_or(OpenError::NoAdapter)?; Ok((adapter, selection)) } +/// The error for `candidates` among which `select` found no adapter, with the list in the log +/// when it is not [`OpenError::UnsafeDriver`]. +fn unselected(candidates: &[Candidate]) -> OpenError { + let left_out = left_out(candidates); + if !left_out.is_empty() { + return OpenError::UnsafeDriver(left_out); + } + let listed = candidates.iter().map(ToString::to_string).collect::>().join(", "); + log::warn!("no usable graphics adapter among {}: {listed}", candidates.len()); + OpenError::NoAdapter +} + /// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] /// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter /// without `request.required_features`, or whose device fails to open, adds a @@ -263,7 +272,15 @@ mod tests { OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(), "the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver" ); - assert!(pick(&[], None, &Preference::Auto).is_err()); + assert_eq!(pick(&[], None, &Preference::Auto).unwrap_err(), OpenError::NoAdapter); + } + + #[test] + fn pick_says_when_only_a_driver_that_can_crash_can_draw() { + let vulkan_only: Vec = crate::adapter::tests::uhd_630().into_iter().take(1).collect(); + assert_eq!(select(&vulkan_only, &Preference::Auto), None); + assert_eq!(unselected(&vulkan_only), OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()])); + assert_eq!(unselected(&[]), OpenError::NoAdapter); } #[test] From 03ec8838b62ee1b5b893165331a5b30fe4ca4d82 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 18 Nov 2026 13:43:25 -0800 Subject: [PATCH 06/17] craft-gpu-device: polls run after an out-of-memory error, and faults keep their cause After an out-of-memory error, `poll`, `wait` and the bounded waits still run, so staging memory is reclaimed. `clear_out_of_memory` takes the count from `out_of_memory_count` and clears only the errors seen up to it, so an error that arrives while memory is freed stays recorded. A loss or another error still stops polls and waits, also when an out-of-memory error follows it. A fault's text now holds wgpu's heading and each cause on one line, for example "Validation Error: In Queue::submit: Buffer 'pc' has been destroyed", instead of only "Validation Error". The text is built up to 200 characters without joining the whole message first. `wait_slices` takes the elapsed time from a closure. The wait uses the system clock, and the tests use a clock that does not move or one that advances by each slice, so their results do not depend on scheduling. --- crates/gpu-device/README.md | 5 + crates/gpu-device/src/health.rs | 226 +++++++++++++++++++++++--------- crates/gpu-device/src/open.rs | 16 +++ 3 files changed, 187 insertions(+), 60 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index fe8037fcae..20add770e8 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -57,6 +57,11 @@ Licensed under MIT OR Apache-2.0. wait. - `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that `Device::poll` raises on a lost device and record the loss. +- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. + The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and + passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, + unless it was lost, another error was recorded, or a new out-of-memory error came in after the + count was read. ## Tests diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index c2254ee4e9..5eb454cdbc 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -43,10 +43,12 @@ impl Fault { matches!(self, Fault::Lost(_)) } - /// An out-of-memory error on a device that still works: freeing memory and trying again can - /// succeed, unlike after a loss or a validation error. Only wgpu's own out-of-memory error is - /// recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory is not - /// one. + /// An out-of-memory error on a device that still works: freeing memory, calling + /// [`DeviceHealth::clear_out_of_memory`] with the count read from + /// [`DeviceHealth::out_of_memory_count`] and trying again can succeed, unlike after a loss or + /// a validation error. Polls and waits keep running meanwhile. Only wgpu's own out-of-memory + /// error is recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory + /// is not one. pub fn is_out_of_memory(&self) -> bool { matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY) } @@ -77,11 +79,12 @@ pub const OUT_OF_MEMORY: &str = "Out of Memory"; /// of the same slot waits only for that one store. #[derive(Default)] struct Inner { - faulted: AtomicBool, /// The first device loss. lost: OnceLock, - /// An out-of-memory error was seen. - out_of_memory: AtomicBool, + /// Out-of-memory errors seen. + out_of_memory_seen: AtomicU64, + /// Out-of-memory errors the caller cleared ([`DeviceHealth::clear_out_of_memory`]). + out_of_memory_cleared: AtomicU64, /// The first other error. error: OnceLock, errors: AtomicU64, @@ -158,35 +161,60 @@ impl DeviceHealth { } /// Mark the device unusable. The first fault is kept; a later device loss replaces an error, - /// and a later out-of-memory error replaces another error, so a caller can still free memory - /// and recover after a validation error in the same frame. + /// and a later out-of-memory error is reported over another error, so a caller still sees + /// that freeing memory may help after a validation error in the same frame. pub fn mark(&self, fault: Fault) { if fault.is_out_of_memory() { - self.0.out_of_memory.store(true, Ordering::Release); - } else { - // A slot already set keeps its first text. - let _ = match fault { - Fault::Lost(text) => self.0.lost.set(text), - Fault::Error(text) => self.0.error.set(text), - }; + self.0.out_of_memory_seen.fetch_add(1, Ordering::AcqRel); + return; } - self.0.faulted.store(true, Ordering::Release); + // A slot already set keeps its first text. + let _ = match fault { + Fault::Lost(text) => self.0.lost.set(text), + Fault::Error(text) => self.0.error.set(text), + }; } - /// Whether the device may still be used. + /// Out-of-memory errors recorded so far. Read it when handling an out-of-memory fault, and + /// pass it to [`clear_out_of_memory`](Self::clear_out_of_memory) once memory was freed. + pub fn out_of_memory_count(&self) -> u64 { + self.0.out_of_memory_seen.load(Ordering::Acquire) + } + + /// Clear the out-of-memory errors up to `count` (from + /// [`out_of_memory_count`](Self::out_of_memory_count)) after the caller freed memory. One + /// recorded after `count` was read stays. The device counts as healthy again unless it was + /// lost or another error was recorded, which [`fault`](Self::fault) then reports. + pub fn clear_out_of_memory(&self, count: u64) { + let count = count.min(self.0.out_of_memory_seen.load(Ordering::Acquire)); + self.0.out_of_memory_cleared.fetch_max(count, Ordering::AcqRel); + } + + /// Whether an out-of-memory error is recorded and not cleared. + fn out_of_memory(&self) -> bool { + let cleared = self.0.out_of_memory_cleared.load(Ordering::Acquire); + self.0.out_of_memory_seen.load(Ordering::Acquire) > cleared + } + + /// Whether the device may still be used: no fault was recorded, or only out-of-memory errors + /// that [`clear_out_of_memory`](Self::clear_out_of_memory) cleared. pub fn is_ok(&self) -> bool { - !self.0.faulted.load(Ordering::Acquire) + self.0.lost.get().is_none() && self.0.error.get().is_none() && !self.out_of_memory() + } + + /// Whether polls and waits still run: the device was not lost and reported no error other + /// than out of memory. A poll reclaims the staging memory that recovering from an + /// out-of-memory error needs. + fn pollable(&self) -> bool { + self.0.lost.get().is_none() && self.0.error.get().is_none() } /// Why the device cannot be used, if it cannot. pub fn fault(&self) -> Option { - if self.is_ok() { - return None; - } if let Some(text) = self.0.lost.get() { return Some(Fault::Lost(text.clone())); } - if self.0.out_of_memory.load(Ordering::Acquire) { + if self.out_of_memory() { return Some(Fault::Error(OUT_OF_MEMORY.into())); } self.0.error.get().map(|text| Fault::Error(text.clone())) @@ -222,20 +250,21 @@ impl DeviceHealth { self.mark(Fault::Lost("the device stopped responding".into())); } - /// Block until `index` (or all submitted work) finished, unless the device is unusable. - /// Returns whether the work finished with the device still healthy: `false` when the device - /// was unusable, when it faulted, and when the poll itself failed, so the work may still be - /// running. A panic in `Device::poll` is caught and recorded as a loss. Native only: the web - /// has no blocking wait. + /// Block until `index` (or all submitted work) finished, unless the device was lost or + /// reported an error other than out of memory. Returns whether the work finished with the + /// device still usable: `false` when it was lost or reported such an error, before or during + /// the wait, and when the poll itself failed, so the work may still be running. After an + /// out-of-memory error the wait still runs. A panic in `Device::poll` is caught and recorded + /// as a loss. Native only: the web has no blocking wait. #[cfg(not(target_arch = "wasm32"))] pub fn wait(&self, device: &wgpu::Device, index: Option) -> bool { - if !self.is_ok() { + if !self.pollable() { return false; } let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Wait { submission_index: index, timeout: None }))); match poll { - Ok(Ok(_)) => self.is_ok(), + Ok(Ok(_)) => self.pollable(), Ok(Err(e)) => { log::warn!("wgpu poll: {e}"); false @@ -247,9 +276,10 @@ impl DeviceHealth { } } - /// Non-blocking poll (reclaims staging memory), skipped once the device is unusable. + /// Non-blocking poll (reclaims staging memory), skipped once the device was lost or reported + /// an error other than out of memory. pub fn poll(&self, device: &wgpu::Device) { - if !self.is_ok() { + if !self.pollable() { return; } if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() { @@ -263,7 +293,8 @@ impl DeviceHealth { /// device faulted, so later work stops going to a GPU that no longer answers. A submission /// index the device never issued returns `false` and leaves the device healthy. A zero /// `timeout`, or one that passes before the first poll, returns `false` and leaves the device - /// healthy. A device that was already faulted returns `false` unchanged. + /// healthy. A device that was already lost, or that reported an error other than out of + /// memory, returns `false` unchanged. #[cfg(not(target_arch = "wasm32"))] pub fn wait_timeout(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex, timeout: Duration) -> bool { self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished @@ -281,19 +312,21 @@ impl DeviceHealth { timeout: Duration, canceled: &(dyn Fn() -> bool + Sync), ) -> WaitOutcome { - if !self.is_ok() { + if !self.pollable() { return WaitOutcome::TimedOut; } let mut wrong_index = false; let mut polled = false; - let outcome = wait_slices(timeout, canceled, |slice| { + let start = Instant::now(); + let elapsed = || start.elapsed(); + let outcome = wait_slices(timeout, canceled, elapsed, |slice| { polled = true; let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) })); match poll { Ok(Ok(_)) => { - if self.is_ok() { + if self.pollable() { SlicePoll::Done } else { SlicePoll::Failed @@ -313,7 +346,7 @@ impl DeviceHealth { } }); // A deadline that passed before the first poll says nothing about the device. - if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.is_ok() { + if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.pollable() { self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64()))); } outcome @@ -330,17 +363,21 @@ enum SlicePoll { } /// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between -/// them. A slice that times out is pending, not a failure; only the overall deadline or a failed -/// poll ends the wait early. +/// them. `elapsed` gives the time since the wait started. A slice that times out is pending, not +/// a failure; only the overall deadline or a failed poll ends the wait early. #[cfg(not(target_arch = "wasm32"))] -fn wait_slices(total: Duration, canceled: &(dyn Fn() -> bool + Sync), mut poll: impl FnMut(Duration) -> SlicePoll) -> WaitOutcome { +fn wait_slices( + total: Duration, + canceled: &(dyn Fn() -> bool + Sync), + mut elapsed: impl FnMut() -> Duration, + mut poll: impl FnMut(Duration) -> SlicePoll, +) -> WaitOutcome { const SLICE: Duration = Duration::from_millis(100); - let start = Instant::now(); loop { if canceled() { return WaitOutcome::Canceled; } - let remaining = total.saturating_sub(start.elapsed()); + let remaining = total.saturating_sub(elapsed()); if remaining.is_zero() { return WaitOutcome::TimedOut; } @@ -369,23 +406,36 @@ fn caused_by_loss(e: &wgpu::Error) -> bool { /// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`]) /// follows a device loss whose callback may not have run yet (it runs on the next poll), so it /// counts as a loss rather than as an error. An error about a destroyed buffer or texture is an -/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. +/// error. Only wgpu's own out-of-memory error is [`OUT_OF_MEMORY`]. The text keeps the causes +/// ([`one_line`]). fn fault_of(e: &wgpu::Error) -> Fault { let text = e.to_string(); if matches!(e, wgpu::Error::OutOfMemory { .. }) { Fault::Error(OUT_OF_MEMORY.into()) } else if caused_by_loss(e) { - Fault::Lost(first_line(&text)) + Fault::Lost(one_line(&text)) } else { - Fault::Error(first_line(&text)) + Fault::Error(one_line(&text)) } } -fn first_line(s: &str) -> String { - let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or(""); - let mut out: String = line.chars().take(200).collect(); - if line.chars().count() > 200 { - out.push('…'); +/// wgpu's multi-line error text on one line: the heading and each cause, joined with ": ", +/// without wgpu's "Caused by:" line, cut to 200 characters. +fn one_line(s: &str) -> String { + const MAX: usize = 200; + let mut out = String::new(); + let mut count = 0; + let lines = s.lines().map(str::trim).filter(|l| !l.is_empty() && !l.eq_ignore_ascii_case("Caused by:")); + for (i, line) in lines.enumerate() { + let separator = if i == 0 { "" } else { ": " }; + for c in separator.chars().chain(line.chars()) { + if count == MAX { + out.push('…'); + return out; + } + out.push(c); + count += 1; + } } out } @@ -416,12 +466,14 @@ mod tests { #[cfg(not(target_arch = "wasm32"))] fn wait_slices_cancel_timeout_and_completion() { let never = || false; - assert_eq!(wait_slices(Duration::ZERO, &never, |_| SlicePoll::Done), WaitOutcome::TimedOut); - assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Done), WaitOutcome::Finished); - assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Failed), WaitOutcome::TimedOut); + // a clock that does not move: only the polls end these waits + let still = || Duration::ZERO; + assert_eq!(wait_slices(Duration::ZERO, &never, still, |_| SlicePoll::Done), WaitOutcome::TimedOut); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Done), WaitOutcome::Finished); + assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Failed), WaitOutcome::TimedOut); let mut polls = 0; - let outcome = wait_slices(Duration::from_secs(1), &never, |_| { + let outcome = wait_slices(Duration::from_secs(1), &never, still, |_| { polls += 1; if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } }); @@ -431,7 +483,7 @@ mod tests { let canceled = || true; let mut called = false; assert_eq!( - wait_slices(Duration::from_secs(1), &canceled, |_| { + wait_slices(Duration::from_secs(1), &canceled, still, |_| { called = true; SlicePoll::Done }), @@ -440,13 +492,30 @@ mod tests { assert!(!called, "cancellation is checked before polling"); } + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn wait_slices_end_at_the_deadline_of_a_moving_clock() { + let never = || false; + let now = std::cell::Cell::new(Duration::ZERO); + let mut slices = Vec::new(); + let clock = || now.get(); + let outcome = wait_slices(Duration::from_millis(250), &never, clock, |slice| { + slices.push(slice); + now.set(now.get() + slice); + SlicePoll::Pending + }); + assert_eq!(outcome, WaitOutcome::TimedOut); + assert_eq!(slices, [Duration::from_millis(100), Duration::from_millis(100), Duration::from_millis(50)]); + } + #[test] #[cfg(not(target_arch = "wasm32"))] fn wait_slices_observes_cancel_while_pending() { let flag = AtomicBool::new(false); let canceled = || flag.load(Ordering::SeqCst); let mut polls = 0; - let outcome = wait_slices(Duration::from_secs(1), &canceled, |_| { + let still = || Duration::ZERO; + let outcome = wait_slices(Duration::from_secs(1), &canceled, still, |_| { polls += 1; flag.store(true, Ordering::SeqCst); SlicePoll::Pending @@ -459,8 +528,10 @@ mod tests { fn fault_text() { assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x"); - assert_eq!(first_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid"); - assert_eq!(first_line(&"a".repeat(300)).chars().count(), 201); + assert_eq!(one_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid: more"); + assert_eq!(one_line(&"a".repeat(300)).chars().count(), 201); + assert_eq!(one_line(&"a".repeat(200)), "a".repeat(200)); + assert_eq!(one_line(&format!("{}\nb", "a".repeat(199))), format!("{}:…", "a".repeat(199))); assert!(Fault::Error("Out of Memory".into()).is_out_of_memory()); assert!(!Fault::Error("Validation Error".into()).is_out_of_memory()); assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory()); @@ -474,6 +545,39 @@ mod tests { assert!(!Fault::Lost("out of memory".into()).is_out_of_memory()); } + #[test] + fn out_of_memory_keeps_polls_running_until_cleared() { + let h = DeviceHealth::new(); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + assert!(h.pollable(), "polls reclaim the memory that recovery needs"); + let seen = h.out_of_memory_count(); + // one recorded while the caller freed memory is not cleared with the earlier ones + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.clear_out_of_memory(seen); + assert!(h.fault().is_some_and(|f| f.is_out_of_memory())); + h.clear_out_of_memory(h.out_of_memory_count()); + assert!(h.is_ok()); + assert_eq!(h.fault(), None); + // a count larger than the ones recorded does not hide later errors + h.clear_out_of_memory(u64::MAX); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.is_ok()); + h.clear_out_of_memory(h.out_of_memory_count()); + // an earlier error is still there once the out-of-memory error is cleared + h.mark(Fault::Error("Validation Error".into())); + assert!(!h.pollable()); + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert!(!h.pollable(), "a later out-of-memory error does not undo the earlier error"); + h.clear_out_of_memory(h.out_of_memory_count()); + assert_eq!(h.fault(), Some(Fault::Error("Validation Error".into()))); + assert!(!h.is_ok() && !h.pollable()); + let lost = DeviceHealth::new(); + lost.mark(Fault::Error(OUT_OF_MEMORY.into())); + lost.mark(Fault::Lost("reset".into())); + assert!(!lost.pollable()); + } + #[test] fn marks_from_several_threads_keep_the_loss() { let h = DeviceHealth::new(); @@ -520,12 +624,14 @@ mod tests { let lost = validation(&["In Device::create_buffer", "Parent device is lost"]); assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost)); let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]); - assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error".into())); + // the stored text names what failed, not only wgpu's heading + assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error: In Queue::submit: Buffer 'pc' has been destroyed".into())); + assert_eq!(fault_of(&lost), Fault::Lost("Validation Error: In Device::create_buffer: Parent device is lost".into())); let texture = validation(&["Texture with 'frame' label has been destroyed"]); assert!(!fault_of(&texture).is_lost()); // a label is the caller's text, not the cause, even on a line of its own let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]); - assert_eq!(fault_of(&labeled), Fault::Error("Validation Error".into())); + assert_eq!(fault_of(&labeled), Fault::Error("Validation Error: In Queue::submit: Buffer 'device is lost' has been destroyed".into())); for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] { let labeled = validation(&["In Queue::submit", label]); assert!(!fault_of(&labeled).is_lost(), "{label:?}"); diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 8f31a851ee..dacfa5724f 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -298,6 +298,22 @@ mod tests { assert!(opened.health.is_ok(), "{:?}", opened.health.fault()); } + #[test] + fn waits_run_after_an_out_of_memory_error() { + use crate::health::{Fault, OUT_OF_MEMORY}; + let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); + let health = opened.health.clone(); + health.mark(Fault::Error(OUT_OF_MEMORY.into())); + let index = opened.queue.submit([]); + assert!(health.wait(&opened.device, Some(index.clone())), "{health:?}"); + assert!(health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5)), "{health:?}"); + health.clear_out_of_memory(health.out_of_memory_count()); + assert!(health.is_ok(), "{health:?}"); + // any other error still stops them + health.mark(Fault::Error("Validation Error".into())); + assert!(!health.wait(&opened.device, None)); + } + #[test] fn a_lost_device_is_seen_by_its_health() { let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); From 99b402b29f581dd6e78cc02c3a4c03ee2eb42351 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 09:48:14 -0800 Subject: [PATCH 07/17] craft-gpu-device: report caps and device loss in craft-gpu's types - device_caps (and Opened::device_caps) gives a device's craft_gpu::DeviceCaps: the limits and enabled feature names the device was opened with, in the form craft-gpu-wgpu reports. - DeviceHealth::device_status reports a recorded loss as GpuFault::DeviceLost, in the form of GpuContext::device_status, and a Fault converts to a GpuFault (a loss to DeviceLost, an error to Operation). - wgpu keeps one device-lost callback per device, so a craft-gpu context on a device DeviceHealth::watch watches reads the loss from device_status instead of setting its own callback. The README says so. - pollster comes from the workspace dependency. --- Cargo.lock | 1 + crates/gpu-device/Cargo.toml | 3 ++- crates/gpu-device/README.md | 9 ++++++-- crates/gpu-device/src/caps.rs | 36 +++++++++++++++++++++++++++++ crates/gpu-device/src/health.rs | 40 +++++++++++++++++++++++++++++++++ crates/gpu-device/src/lib.rs | 5 ++++- crates/gpu-device/src/open.rs | 15 +++++++++++++ 7 files changed, 105 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index a872e904cc..f99595d8da 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2245,6 +2245,7 @@ dependencies = [ name = "craft-gpu-device" version = "0.1.0" dependencies = [ + "craft-gpu", "log", "pollster 0.4.0", "serde", diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml index a2561dc3a8..88ac88149a 100644 --- a/crates/gpu-device/Cargo.toml +++ b/crates/gpu-device/Cargo.toml @@ -16,12 +16,13 @@ default = ["serde"] serde = ["dep:serde"] [dependencies] +craft-gpu = { workspace = true } wgpu = "30" log = { workspace = true } serde = { workspace = true, optional = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -pollster = "0.4" +pollster = { workspace = true } [dev-dependencies] # The noop backend opens devices without a GPU in the tests. diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 20add770e8..99629f999c 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -2,8 +2,8 @@ Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for drivers that crash, a software fallback, a capability report, and device health with recovery -after a device loss. The crate depends on `wgpu` 30, `pollster` and `log`, with `serde` as an -optional feature (on by default). It depends on no app crate. +after a device loss. The crate depends on `craft-gpu`, `wgpu` 30, `pollster` and `log`, with +`serde` as an optional feature (on by default). It depends on no app crate. Licensed under MIT OR Apache-2.0. @@ -24,6 +24,8 @@ Licensed under MIT OR Apache-2.0. | `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one | | `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | | `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | +| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits and enabled feature names, in the form `craft-gpu-wgpu` reports | +| `DeviceHealth::device_status` | a recorded loss as `craft_gpu::GpuFault::DeviceLost`, in the form of `GpuContext::device_status`; `Fault` converts to `GpuFault` (a loss to `DeviceLost`, an error to `Operation`) | | `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | ## Failure cases @@ -57,6 +59,9 @@ Licensed under MIT OR Apache-2.0. wait. - `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that `Device::poll` raises on a lost device and record the loss. +- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` + replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads + `DeviceHealth::device_status` instead of setting its own callback. - After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed. The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again, diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs index e0841a0293..07656e5bdb 100644 --- a/crates/gpu-device/src/caps.rs +++ b/crates/gpu-device/src/caps.rs @@ -153,6 +153,24 @@ impl fmt::Display for Capabilities { } } +/// The [`DeviceCaps`](craft_gpu::DeviceCaps) a `craft-gpu` context reports for `device`: the +/// limits and features the device was opened with, not the adapter's, in the same form +/// `craft-gpu-wgpu` reports for a device it opens itself. +pub fn device_caps(device: &wgpu::Device) -> craft_gpu::DeviceCaps { + device_caps_of(&device.adapter_info(), device.features(), &device.limits()) +} + +fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> craft_gpu::DeviceCaps { + craft_gpu::DeviceCaps { + backend_name: format!("{:?}", info.backend), + device_name: info.name.clone(), + max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, + max_buffer_size: limits.max_buffer_size, + max_texture_dimension_2d: limits.max_texture_dimension_2d, + features: features.iter_names().map(|(name, _)| name.to_string()).collect(), + } +} + #[cfg(test)] mod tests { use super::*; @@ -200,4 +218,22 @@ mod tests { let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16); } + + #[test] + fn device_caps_carry_the_device_limits_and_feature_names() { + let limits = + Limits { max_texture_dimension_2d: 16384, max_buffer_size: 1 << 30, max_storage_buffer_binding_size: 1 << 28, ..Limits::default() }; + let features = Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY; + let caps = device_caps_of(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); + assert_eq!(caps.backend_name, "Vulkan"); + assert_eq!(caps.device_name, "NVIDIA GeForce RTX 4070"); + assert_eq!((caps.max_texture_dimension_2d, caps.max_buffer_size, caps.max_storage_buffer_binding_size), (16384, 1 << 30, 1 << 28)); + let mut names = caps.features.clone(); + names.sort(); + assert_eq!(names, ["TEXTURE_FORMAT_NV12", "TIMESTAMP_QUERY"]); + // a device opened without features reports none + let bare = device_caps_of(&info("llvmpipe", 0x10005, DeviceType::Cpu), Features::empty(), &Limits::downlevel_defaults()); + assert!(bare.features.is_empty()); + assert_eq!(bare.max_texture_dimension_2d, 2048); + } } diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index 5eb454cdbc..f1ff61b640 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -71,6 +71,18 @@ impl fmt::Display for Fault { } } +/// A loss becomes [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost), and any other +/// fault becomes [`GpuFault::Operation`](craft_gpu::GpuFault::Operation), each with the fault's +/// text. +impl From for craft_gpu::GpuFault { + fn from(fault: Fault) -> Self { + match fault { + Fault::Lost(s) => craft_gpu::GpuFault::DeviceLost(s), + Fault::Error(s) => craft_gpu::GpuFault::Operation(s), + } + } +} + /// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`). pub const OUT_OF_MEMORY: &str = "Out of Memory"; @@ -220,6 +232,18 @@ impl DeviceHealth { self.0.error.get().map(|text| Fault::Error(text.clone())) } + /// The device loss in the form of `craft_gpu::GpuContext::device_status`: + /// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded, + /// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one + /// device-lost callback per device, so a `craft-gpu` context on a device that + /// [`watch`](Self::watch) watches reads the loss here instead of setting its own callback. + pub fn device_status(&self) -> Result<(), craft_gpu::GpuFault> { + match self.0.lost.get() { + Some(text) => Err(craft_gpu::GpuFault::DeviceLost(text.clone())), + None => Ok(()), + } + } + /// Uncaptured wgpu errors seen so far. pub fn errors(&self) -> u64 { self.0.errors.load(Ordering::Relaxed) @@ -462,6 +486,22 @@ mod tests { assert!(!h.device_lost()); } + #[test] + fn faults_in_the_craft_gpu_form() { + use craft_gpu::GpuFault; + let h = DeviceHealth::new(); + assert_eq!(h.device_status(), Ok(())); + // an error, out of memory included, is not a loss + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + h.mark(Fault::Error("Validation Error".into())); + assert_eq!(h.device_status(), Ok(())); + h.mark(Fault::Lost("reset".into())); + assert_eq!(h.device_status(), Err(GpuFault::DeviceLost("reset".into()))); + assert_eq!(GpuFault::from(Fault::Lost("reset".into())), GpuFault::DeviceLost("reset".into())); + assert_eq!(GpuFault::from(Fault::Error(OUT_OF_MEMORY.into())), GpuFault::Operation(OUT_OF_MEMORY.into())); + assert_eq!(h.fault().map(GpuFault::from), Some(GpuFault::DeviceLost("reset".into()))); + } + #[test] #[cfg(not(target_arch = "wasm32"))] fn wait_slices_cancel_timeout_and_completion() { diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs index c41f041f5f..15d57a378b 100644 --- a/crates/gpu-device/src/lib.rs +++ b/crates/gpu-device/src/lib.rs @@ -19,6 +19,9 @@ //! formats, `f16`, timestamps, sizes). //! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and //! [`Recovery`] says what to open after a loss. +//! - For a `craft-gpu` context on an opened device, [`device_caps`] gives the device's +//! `craft_gpu::DeviceCaps`, [`DeviceHealth::device_status`] reports a loss as +//! `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`. //! //! The selection functions are pure, so tests run without a GPU. @@ -30,7 +33,7 @@ mod preference; mod recovery; pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; -pub use caps::{Capabilities, Vendor}; +pub use caps::{Capabilities, Vendor, device_caps}; pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; pub use open::{OpenError, Opened, Request, pick}; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index dacfa5724f..845356fc5b 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -41,6 +41,14 @@ pub struct Opened { pub notices: Vec, } +impl Opened { + /// The device's [`DeviceCaps`](craft_gpu::DeviceCaps) for a `craft-gpu` context + /// ([`device_caps`](crate::device_caps)). + pub fn device_caps(&self) -> craft_gpu::DeviceCaps { + crate::caps::device_caps(&self.device) + } +} + /// Why no device could be opened. #[derive(Clone, Debug, PartialEq, Eq)] pub enum OpenError { @@ -231,6 +239,12 @@ mod tests { assert!(!opened.caps.shader_f16 && !opened.caps.timestamps, "only the features asked for: {}", opened.caps); assert!(opened.notices.is_empty(), "{:?}", opened.notices); assert!(opened.health.is_ok()); + // the craft-gpu caps name only the features the device was opened with + let caps = opened.device_caps(); + assert_eq!(caps.features, ["TEXTURE_FORMAT_NV12"]); + assert_eq!(caps.device_name, opened.caps.name); + assert_eq!(caps.max_texture_dimension_2d, opened.device.limits().max_texture_dimension_2d); + assert_eq!(opened.health.device_status(), Ok(())); } #[test] @@ -322,6 +336,7 @@ mod tests { health.probe(&opened.device); assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); assert!(!health.is_ok()); + assert!(matches!(health.device_status(), Err(craft_gpu::GpuFault::DeviceLost(_))), "{health:?}"); // a later wait does not touch the lost device assert!(!health.wait(&opened.device, None)); } From c18e5240d145ba6a3845a6cd8ae6fc25ce7d7aca Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 10:13:54 -0800 Subject: [PATCH 08/17] craft-gpu-device: read capabilities from DeviceCaps, open from async code - craft-gpu's DeviceCaps gains `vendor_id` and `software` (serde default 0 and false) and `has_feature`. craft-gpu-wgpu fills both. - `Capabilities` holds a DeviceCaps and reads NV12, P010, 16-bit norm, f16 and timestamps from its feature names and the vendor from its vendor id. It derefs to DeviceCaps and converts both ways. - `list_async` and `open_async` are `list` and `open` as futures, for a wasm32 web worker. In a browser they request the adapter for the preference's power; wgpu 30 does not pass the fallback-adapter option to the browser, so `Software` there opens the browser's adapter. - The README lists what a caller rebuilds after a device loss. --- crates/gpu-device/README.md | 44 +++++- crates/gpu-device/src/caps.rs | 204 +++++++++++++++++++--------- crates/gpu-device/src/lib.rs | 25 ++-- crates/gpu-device/src/open.rs | 119 ++++++++++++---- crates/gpu-device/src/preference.rs | 1 - crates/gpu-wgpu/src/lib.rs | 4 + crates/gpu/src/caps.rs | 16 +++ crates/gpu/src/tests.rs | 12 ++ 8 files changed, 314 insertions(+), 111 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 99629f999c..3c7da59b5c 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -20,11 +20,12 @@ Licensed under MIT OR Apache-2.0. | `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s | | `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver | | `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` | +| `list_async`, `open_async` | `list` and `open` as futures, for a `wasm32` web worker as well as native; in a browser `list_async` gives the high-performance adapter, the one `open_async` opens for `Auto` and a named adapter | | `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that selector) | -| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one | +| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one, read from the `craft_gpu::DeviceCaps` it holds (its fields are readable through `Deref`; `From` converts both ways) | | `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device | | `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) | -| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits and enabled feature names, in the form `craft-gpu-wgpu` reports | +| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits, enabled feature names, vendor id and software flag, in the form `craft-gpu-wgpu` reports | | `DeviceHealth::device_status` | a recorded loss as `craft_gpu::GpuFault::DeviceLost`, in the form of `GpuContext::device_status`; `Fault` converts to `GpuFault` (a loss to `DeviceLost`, an error to `Operation`) | | `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log | @@ -33,11 +34,14 @@ Licensed under MIT OR Apache-2.0. - With no usable adapter, `select` returns `None`, and `open` and `pick` return `OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the process can draw. -- In a browser, WebGPU lists only the adapter the browser offers, so a named adapter cannot be - chosen. A web build requests the adapter with `Preference::power()` as the power preference - and opens the device itself. `Capabilities` and `Recovery` work there as they do on native, - and so does `DeviceHealth` apart from `wait`, `wait_timeout` and `wait_timeout_cancelable`, - which are native only. +- In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be + chosen. `open_async` asks for the adapter with `Preference::power()` as the power preference, + and gives the automatic choice with `Notice::AdapterMissing` for a named adapter. wgpu 30 + does not pass the fallback-adapter option to the browser, so `Preference::Software` opens the + browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and + `Recovery` cannot move drawing to software there. `Capabilities` and + `Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`, + `wait_timeout` and `wait_timeout_cancelable`, which are native only. - An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists each failure. @@ -68,6 +72,32 @@ Licensed under MIT OR Apache-2.0. unless it was lost, another error was recorded, or a new out-of-memory error came in after the count was read. +## After a device loss + +`DeviceHealth::device_lost` turns true, and `DeviceHealth::device_status` returns +`GpuFault::DeviceLost`, once the device is lost. Nothing made with the lost device can be used +again, and wgpu keeps none of its contents. The caller then: + +1. Drops the old `Opened` and everything made with its device: buffers, textures and their + views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and + pipelines, query sets, unsubmitted command encoders, and any renderer that holds them (an + egui-wgpu `Renderer`, for example). Work submitted before the loss does not complete, and + waits on it return `false`. +2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`, + using the returned preference and the same `Request`. When the step has a notice + (`Notice::SoftwareAfterLosses`), the app shows it. +3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another + adapter, or a software one, with other features and limits: for example, without NV12 the + planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead. +4. Configures each window surface again with the new device (`Surface::configure`). The surface + itself is kept when it was passed to `open`, which then opens only an adapter that can draw + to it. +5. Builds the pipelines, bind groups and renderers again, and uploads the textures and buffers + again from the app's own copies of their data. +6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and + submits again the jobs and frames that did not complete. +7. Uses the new `Opened::health`. The old `DeviceHealth` keeps reporting the loss. + ## Tests The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop diff --git a/crates/gpu-device/src/caps.rs b/crates/gpu-device/src/caps.rs index 07656e5bdb..ea72379bbe 100644 --- a/crates/gpu-device/src/caps.rs +++ b/crates/gpu-device/src/caps.rs @@ -1,8 +1,10 @@ //! What an adapter can do, for choosing a pipeline and for the settings and the log. use std::fmt; +use std::ops::Deref; -use wgpu::{AdapterInfo, Backend, DeviceType, Features, Limits}; +use craft_gpu::DeviceCaps; +use wgpu::{AdapterInfo, DeviceType, Features, Limits}; /// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers /// report instead). @@ -60,74 +62,93 @@ impl fmt::Display for Vendor { } } -/// What an adapter reports it can do. +/// What a device (or an adapter) can do, read from the [`DeviceCaps`] a `craft-gpu` context +/// reports. It holds only that `DeviceCaps`: the video formats, `f16` and timestamps come from its +/// feature names, the vendor from its vendor id, and its fields (the name, the backend and the +/// limits) can be read through `Deref`. #[derive(Clone, Debug, PartialEq, Eq)] -pub struct Capabilities { - pub name: String, - pub backend: Backend, - pub device_type: DeviceType, - pub vendor: Vendor, - /// The adapter draws on the CPU. - pub software: bool, - /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created - /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into - /// `R8Unorm` and `Rg8Unorm` textures instead. - pub nv12: bool, - /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane - /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` - /// textures ([`norm16`](Self::norm16)) instead. - pub p010: bool, - /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without - /// P010. - pub norm16: bool, - /// `f16` in shaders. - pub shader_f16: bool, - /// Timestamp queries, for measuring GPU time per pass. - pub timestamps: bool, - /// The widest and tallest 2D texture. - pub max_texture_2d: u32, - /// The largest buffer, in bytes. - pub max_buffer_size: u64, -} +pub struct Capabilities(DeviceCaps); impl Capabilities { /// From an adapter's (or a device's) info, features and limits. pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self { - Capabilities { - name: info.name.clone(), - backend: info.backend, - device_type: info.device_type, - vendor: Vendor::from_id(info.vendor), - software: info.device_type == DeviceType::Cpu, - nv12: features.contains(Features::TEXTURE_FORMAT_NV12), - p010: features.contains(Features::TEXTURE_FORMAT_P010), - norm16: features.contains(Features::TEXTURE_FORMAT_16BIT_NORM), - shader_f16: features.contains(Features::SHADER_F16), - timestamps: features.contains(Features::TIMESTAMP_QUERY), - max_texture_2d: limits.max_texture_dimension_2d, - max_buffer_size: limits.max_buffer_size, - } + Capabilities(device_caps_of(info, features, limits)) } - /// What `adapter` can do. + /// What `adapter` offers, for a settings page before a device is opened. A `craft-gpu` + /// context reports [`of_device`](Self::of_device) instead: a device can be granted less. pub fn of_adapter(adapter: &wgpu::Adapter) -> Self { Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits()) } - /// What a device opened on `adapter` can do: the features and limits it was opened with. - pub fn of_device(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Self { - Self::from_parts(&adapter.get_info(), device.features(), &device.limits()) + /// What `device` can do: the features and limits it was opened with. + pub fn of_device(device: &wgpu::Device) -> Self { + Self::from_parts(&device.adapter_info(), device.features(), &device.limits()) + } + + /// The `DeviceCaps` these capabilities read. + pub fn device_caps(&self) -> &DeviceCaps { + &self.0 + } + + pub fn into_device_caps(self) -> DeviceCaps { + self.0 + } + + /// Whether every feature in `features` is named in the caps. + fn has(&self, features: Features) -> bool { + features.iter_names().all(|(name, _)| self.0.has_feature(name)) + } + + /// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created + /// and sampled through plane views. wgpu 30 does not render to them: draw the planes into + /// `R8Unorm` and `Rg8Unorm` textures instead. + pub fn nv12(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_NV12) + } + + /// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane + /// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm` + /// textures ([`norm16`](Self::norm16)) instead. + pub fn p010(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_P010) + } + + /// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without + /// P010. + pub fn norm16(&self) -> bool { + self.has(Features::TEXTURE_FORMAT_16BIT_NORM) + } + + /// `f16` in shaders. + pub fn shader_f16(&self) -> bool { + self.has(Features::SHADER_F16) + } + + /// Timestamp queries, for measuring GPU time per pass. + pub fn timestamps(&self) -> bool { + self.has(Features::TIMESTAMP_QUERY) + } + + pub fn vendor(&self) -> Vendor { + Vendor::from_id(self.0.vendor_id) + } + + /// The adapter draws on the CPU. + pub fn software(&self) -> bool { + self.0.software } /// Whether a `width` × `height` texture fits. pub fn fits(&self, width: u32, height: u32) -> bool { - width > 0 && height > 0 && width <= self.max_texture_2d && height <= self.max_texture_2d + let max = self.0.max_texture_dimension_2d; + width > 0 && height > 0 && width <= max && height <= max } /// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be /// sampled. pub fn ten_bit(&self) -> bool { - self.norm16 + self.norm16() } /// The features from `wanted` this adapter has, to ask for when opening a device. @@ -136,43 +157,72 @@ impl Capabilities { } } +impl Deref for Capabilities { + type Target = DeviceCaps; + + fn deref(&self) -> &DeviceCaps { + &self.0 + } +} + +impl From for Capabilities { + fn from(caps: DeviceCaps) -> Self { + Capabilities(caps) + } +} + +impl From for DeviceCaps { + fn from(caps: Capabilities) -> Self { + caps.0 + } +} + impl fmt::Display for Capabilities { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "\"{}\" ({}, {:?}", self.name, self.vendor, self.backend)?; - if self.software { + write!(f, "\"{}\" ({}, {}", self.0.device_name, self.vendor(), self.0.backend_name)?; + if self.software() { f.write_str(", software")?; } - let flags = - [(self.nv12, "NV12"), (self.p010, "P010"), (self.norm16, "16-bit norm"), (self.shader_f16, "f16"), (self.timestamps, "timestamps")]; + let flags = [ + (self.nv12(), "NV12"), + (self.p010(), "P010"), + (self.norm16(), "16-bit norm"), + (self.shader_f16(), "f16"), + (self.timestamps(), "timestamps"), + ]; for (on, name) in flags { if on { write!(f, ", {name}")?; } } - write!(f, ", textures up to {} px)", self.max_texture_2d) + write!(f, ", textures up to {} px)", self.0.max_texture_dimension_2d) } } -/// The [`DeviceCaps`](craft_gpu::DeviceCaps) a `craft-gpu` context reports for `device`: the -/// limits and features the device was opened with, not the adapter's, in the same form -/// `craft-gpu-wgpu` reports for a device it opens itself. -pub fn device_caps(device: &wgpu::Device) -> craft_gpu::DeviceCaps { - device_caps_of(&device.adapter_info(), device.features(), &device.limits()) +/// The [`DeviceCaps`] a `craft-gpu` context reports for `device`: the limits and features the +/// device was opened with, not the adapter's, in the same form `craft-gpu-wgpu` reports for a +/// device it opens itself. +pub fn device_caps(device: &wgpu::Device) -> DeviceCaps { + Capabilities::of_device(device).into_device_caps() } -fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> craft_gpu::DeviceCaps { - craft_gpu::DeviceCaps { +fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> DeviceCaps { + DeviceCaps { backend_name: format!("{:?}", info.backend), device_name: info.name.clone(), max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size, max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, features: features.iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == DeviceType::Cpu, } } #[cfg(test)] mod tests { + use wgpu::Backend; + use super::*; fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo { @@ -196,9 +246,9 @@ mod tests { let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY; let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() }; let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits); - assert!(c.nv12 && !c.p010 && c.norm16 && c.timestamps && !c.shader_f16 && !c.software); + assert!(c.nv12() && !c.p010() && c.norm16() && c.timestamps() && !c.shader_f16() && !c.software()); assert!(c.ten_bit()); - assert_eq!(c.vendor, Vendor::Nvidia); + assert_eq!(c.vendor(), Vendor::Nvidia); assert!(c.fits(7680, 4320) && c.fits(16384, 16384)); assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0)); assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)"); @@ -208,11 +258,11 @@ mod tests { fn a_software_adapter_without_extras() { let limits = Limits::downlevel_defaults(); let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits); - assert!(c.software && !c.ten_bit() && !c.nv12); + assert!(c.software() && !c.ten_bit() && !c.nv12()); // P010 alone is sampled, not drawn to let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits); - assert!(p010.p010 && !p010.ten_bit()); - assert_eq!(c.max_texture_2d, 2048); + assert!(p010.p010() && !p010.ten_bit()); + assert_eq!(c.max_texture_dimension_2d, 2048); assert!(!c.fits(3840, 2160)); assert!(c.to_string().contains("software")); let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16; @@ -228,6 +278,7 @@ mod tests { assert_eq!(caps.backend_name, "Vulkan"); assert_eq!(caps.device_name, "NVIDIA GeForce RTX 4070"); assert_eq!((caps.max_texture_dimension_2d, caps.max_buffer_size, caps.max_storage_buffer_binding_size), (16384, 1 << 30, 1 << 28)); + assert_eq!((caps.vendor_id, caps.software), (0x10de, false)); let mut names = caps.features.clone(); names.sort(); assert_eq!(names, ["TEXTURE_FORMAT_NV12", "TIMESTAMP_QUERY"]); @@ -235,5 +286,26 @@ mod tests { let bare = device_caps_of(&info("llvmpipe", 0x10005, DeviceType::Cpu), Features::empty(), &Limits::downlevel_defaults()); assert!(bare.features.is_empty()); assert_eq!(bare.max_texture_dimension_2d, 2048); + assert_eq!((bare.vendor_id, bare.software), (0x10005, true)); + } + + #[test] + fn caps_from_a_craft_gpu_context_read_as_capabilities() { + let caps = DeviceCaps { + backend_name: "Dx12".into(), + device_name: "Intel(R) Arc(TM) A770".into(), + features: vec!["TEXTURE_FORMAT_P010".into(), "SHADER_F16".into(), "TEXTURE_FORMAT_16BIT_NORM".into()], + vendor_id: 0x8086, + ..DeviceCaps::default() + }; + let c = Capabilities::from(caps.clone()); + assert!(c.p010() && c.shader_f16() && c.ten_bit() && !c.nv12() && !c.timestamps() && !c.software()); + assert_eq!(c.vendor(), Vendor::Intel); + assert_eq!(c.to_string(), "\"Intel(R) Arc(TM) A770\" (Intel, Dx12, P010, 16-bit norm, f16, textures up to 8192 px)"); + assert_eq!(DeviceCaps::from(c), caps); + // the caps of a backend with no device claim nothing + let none = Capabilities::from(DeviceCaps::default()); + assert!(!none.nv12() && !none.p010() && !none.norm16() && !none.shader_f16() && !none.timestamps() && !none.software()); + assert_eq!(none.vendor(), Vendor::Other(0)); } } diff --git a/crates/gpu-device/src/lib.rs b/crates/gpu-device/src/lib.rs index 15d57a378b..a2988b90d2 100644 --- a/crates/gpu-device/src/lib.rs +++ b/crates/gpu-device/src/lib.rs @@ -10,18 +10,19 @@ //! ([`choose`]); [`Notice`] says when the choice was not the one asked for. //! - [`open`] opens a device, moving to the next adapter and last to a software one when a device //! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open` -//! block on wgpu's futures and are native only. -//! - In a browser, WebGPU lists only the adapter the browser offers, so a named adapter cannot be -//! chosen. A web build requests the adapter with [`Preference::power`] as the power preference -//! and opens the device itself. [`Capabilities`] and [`Recovery`] work there as they do on -//! native, and so does [`DeviceHealth`] apart from its blocking waits, which are native only. -//! - [`Capabilities`] reports what the device can do (NV12 and P010 textures, 16-bit norm -//! formats, `f16`, timestamps, sizes). +//! block on wgpu's futures and are native only; [`list_async`] and [`open_async`] are the same +//! as futures, for a `wasm32` web worker as well as native. +//! - In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be +//! chosen, and wgpu 30 cannot ask for the browser's fallback (software) adapter. `open_async` +//! asks for the adapter with [`Preference::power`]. [`Capabilities`] and [`Recovery`] work +//! there as they do on native, and so does [`DeviceHealth`] apart from its blocking waits, +//! which are native only. +//! - [`Capabilities`] reads what the device can do (NV12 and P010 textures, 16-bit norm formats, +//! `f16`, timestamps, the vendor, a software adapter, sizes) from the `craft_gpu::DeviceCaps` +//! it holds, which [`device_caps`] and [`Opened::device_caps`] give for a `craft-gpu` context. //! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and -//! [`Recovery`] says what to open after a loss. -//! - For a `craft-gpu` context on an opened device, [`device_caps`] gives the device's -//! `craft_gpu::DeviceCaps`, [`DeviceHealth::device_status`] reports a loss as -//! `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`. +//! [`Recovery`] says what to open after a loss. [`DeviceHealth::device_status`] reports a loss +//! as `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`. //! //! The selection functions are pure, so tests run without a GPU. @@ -35,7 +36,7 @@ mod recovery; pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance}; pub use caps::{Capabilities, Vendor, device_caps}; pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome}; -pub use open::{OpenError, Opened, Request, pick}; +pub use open::{OpenError, Opened, Request, list_async, open_async, pick}; #[cfg(not(target_arch = "wasm32"))] pub use open::{list, open}; pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select}; diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 845356fc5b..48325095cb 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -2,16 +2,12 @@ use std::fmt; -#[cfg(not(target_arch = "wasm32"))] -use wgpu::Instance; -use wgpu::{Adapter, Features, Limits, Surface}; +use wgpu::{Adapter, Features, Instance, Limits, Surface}; use crate::adapter::{Candidate, avoided, log_choice}; use crate::caps::Capabilities; use crate::health::DeviceHealth; -use crate::preference::{Notice, Preference, Selection, select}; -#[cfg(not(target_arch = "wasm32"))] -use crate::preference::{asked_for, ranked}; +use crate::preference::{Notice, Preference, Selection, asked_for, ranked, select}; /// What the device is opened with. #[derive(Clone, Debug, Default)] @@ -33,7 +29,7 @@ pub struct Opened { pub queue: wgpu::Queue, /// The adapter as plain data. pub candidate: Candidate, - /// What the device was opened with. + /// What the device was opened with, as the `craft_gpu::DeviceCaps` it reports. pub caps: Capabilities, /// Watches the device for a loss and for uncaptured errors. pub health: DeviceHealth, @@ -45,7 +41,7 @@ impl Opened { /// The device's [`DeviceCaps`](craft_gpu::DeviceCaps) for a `craft-gpu` context /// ([`device_caps`](crate::device_caps)). pub fn device_caps(&self) -> craft_gpu::DeviceCaps { - crate::caps::device_caps(&self.device) + self.caps.device_caps().clone() } } @@ -86,14 +82,32 @@ impl std::error::Error for OpenError {} /// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface` /// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's -/// future, which on the web would wait on the thread that must resolve it. +/// future, which on the web would wait on the thread that must resolve it. [`list_async`] works +/// on both. #[cfg(not(target_arch = "wasm32"))] pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { - let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); + pollster::block_on(list_async(instance, surface)) +} + +/// [`list`] as a future, for a `wasm32` web worker as well as native. In a browser, WebGPU offers +/// one adapter for a power preference, and the list holds the high-performance one, which +/// [`open_async`] opens for `Auto` and for a named adapter. +pub async fn list_async(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await; + #[cfg(target_arch = "wasm32")] + let adapters = browser_adapter(instance, surface, wgpu::PowerPreference::HighPerformance).await; let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); (adapters, candidates) } +/// The adapter a browser offers for `power`, if any. +#[cfg(target_arch = "wasm32")] +async fn browser_adapter(instance: &Instance, surface: Option<&Surface<'_>>, power: wgpu::PowerPreference) -> Vec { + let options = wgpu::RequestAdapterOptions { power_preference: power, compatible_surface: surface, ..Default::default() }; + instance.request_adapter(&options).await.into_iter().collect() +} + /// The adapter to draw with for `preference`, from adapters already listed, with the choice in the /// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device /// itself; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`. @@ -128,10 +142,26 @@ fn unselected(candidates: &[Candidate]) -> OpenError { /// Open a device for `preference`: the selected adapter first, then the others in [`ranked`] /// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter /// without `request.required_features`, or whose device fails to open, adds a -/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]. +/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`]; [`open_async`] +/// works on both. #[cfg(not(target_arch = "wasm32"))] pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result { - let (adapters, candidates) = list(instance, surface); + pollster::block_on(open_async(instance, surface, preference, request)) +} + +/// [`open`] as a future, for a `wasm32` web worker as well as native. On native it lists every +/// adapter, as `open` does. In a browser, WebGPU offers one adapter for a power preference, so +/// `open_async` asks for the adapter with [`Preference::power`]. A named adapter then gives the +/// automatic choice with [`Notice::AdapterMissing`]. wgpu 30 does not pass the fallback-adapter +/// option to the browser, so [`Preference::Software`] gives the browser's adapter with +/// [`Notice::NoSoftwareAdapter`] unless that adapter is itself a software one. +pub async fn open_async( + instance: &Instance, + surface: Option<&Surface<'_>>, + preference: &Preference, + request: &Request<'_>, +) -> Result { + let (adapters, candidates) = adapters_for(instance, surface, preference).await; // Whether drawing is in software depends on the adapter that opens, which `finish` knows. let mut notices: Vec = select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect(); @@ -145,7 +175,7 @@ pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Pre continue; }; tried_software |= candidate.is_software(); - match open_on(adapter, request) { + match open_on(adapter, request).await { Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), Err(error) => { log::warn!("graphics adapter {candidate} could not be opened: {error}"); @@ -153,11 +183,12 @@ pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Pre } } } - if !tried_software { + // In a browser the request below would ask for the same adapter again. + if cfg!(not(target_arch = "wasm32")) && !tried_software { let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; - if let Ok(adapter) = pollster::block_on(instance.request_adapter(&options)) { + if let Ok(adapter) = instance.request_adapter(&options).await { let candidate = Candidate::of(&adapter, surface); - match open_on(&adapter, request) { + match open_on(&adapter, request).await { Ok((device, queue)) => { log::info!("graphics adapter chosen: {candidate}"); return Ok(finish(adapter, device, queue, candidate, preference, notices)); @@ -178,7 +209,22 @@ fn left_out(candidates: &[Candidate]) -> Vec { candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect() } -#[cfg(not(target_arch = "wasm32"))] +/// The adapters `open_async` chooses among: every listed one on native, and in a browser the one +/// it offers for the preference's power. +async fn adapters_for(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference) -> (Vec, Vec) { + #[cfg(not(target_arch = "wasm32"))] + { + let _ = preference; + list_async(instance, surface).await + } + #[cfg(target_arch = "wasm32")] + { + let adapters = browser_adapter(instance, surface, preference.power()).await; + let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect(); + (adapters, candidates) + } +} + fn finish( adapter: Adapter, device: wgpu::Device, @@ -187,7 +233,7 @@ fn finish( preference: &Preference, mut notices: Vec, ) -> Opened { - let caps = Capabilities::of_device(&adapter, &device); + let caps = Capabilities::of_device(&device); if candidate.is_software() && !asked_for(preference, &candidate) { notices.push(Notice::SoftwareOnly); } @@ -200,8 +246,7 @@ fn finish( } /// Open a device on `adapter`, or say why it cannot be. -#[cfg(not(target_arch = "wasm32"))] -fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { +async fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> { let has = adapter.features(); if !has.contains(request.required_features) { return Err(format!("it lacks the features {:?}", request.required_features - has)); @@ -213,7 +258,7 @@ fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wg required_limits, ..Default::default() }; - pollster::block_on(adapter.request_device(&desc)).map_err(|e| e.to_string()) + adapter.request_device(&desc).await.map_err(|e| e.to_string()) } #[cfg(all(test, not(target_arch = "wasm32")))] @@ -235,18 +280,42 @@ mod tests { let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY)); let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() }; let opened = open(&instance, None, &Preference::Software, &request).unwrap(); - assert!(opened.caps.nv12, "{}", opened.caps); - assert!(!opened.caps.shader_f16 && !opened.caps.timestamps, "only the features asked for: {}", opened.caps); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.caps.shader_f16() && !opened.caps.timestamps(), "only the features asked for: {}", opened.caps); assert!(opened.notices.is_empty(), "{:?}", opened.notices); assert!(opened.health.is_ok()); // the craft-gpu caps name only the features the device was opened with let caps = opened.device_caps(); assert_eq!(caps.features, ["TEXTURE_FORMAT_NV12"]); - assert_eq!(caps.device_name, opened.caps.name); + assert_eq!(&caps, opened.caps.device_caps()); + assert_eq!(caps, crate::device_caps(&opened.device)); assert_eq!(caps.max_texture_dimension_2d, opened.device.limits().max_texture_dimension_2d); + assert!(caps.software && caps.vendor_id == opened.candidate.vendor, "{caps:?}"); assert_eq!(opened.health.device_status(), Ok(())); } + #[test] + fn open_async_opens_as_open_does() { + let instance = noop(Some(Features::TEXTURE_FORMAT_P010)); + let request = Request { optional_features: Features::TEXTURE_FORMAT_P010 | Features::SHADER_F16, ..Default::default() }; + let opened = pollster::block_on(open_async(&instance, None, &Preference::Auto, &request)).unwrap(); + let blocking = open(&instance, None, &Preference::Auto, &request).unwrap(); + assert!(opened.caps.p010() && !opened.caps.shader_f16(), "{}", opened.caps); + assert_eq!(opened.caps, blocking.caps); + assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); + assert_eq!(opened.notices, blocking.notices); + let (adapters, candidates) = pollster::block_on(list_async(&instance, None)); + assert_eq!((adapters.len(), candidates), (1, list(&instance, None).1)); + // the same errors + let missing = Request { required_features: Features::SHADER_F16, ..Default::default() }; + let err = pollster::block_on(open_async(&instance, None, &Preference::Auto, &missing)).unwrap_err(); + assert!(matches!(&err, OpenError::NoDevice(n) if n.len() == 1), "{err}"); + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + let none = Instance::new(desc); + assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); + } + #[test] fn an_adapter_without_a_required_feature_is_reported() { let instance = noop(Some(Features::empty())); @@ -261,7 +330,7 @@ mod tests { fn a_software_adapter_is_reported_unless_it_was_asked_for() { let cpu = noop(None); let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap(); - assert!(opened.caps.software); + assert!(opened.caps.software()); assert_eq!(opened.notices, vec![Notice::SoftwareOnly]); let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap(); assert!(asked.notices.is_empty(), "{:?}", asked.notices); diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs index a9a107e9a8..539cde153f 100644 --- a/crates/gpu-device/src/preference.rs +++ b/crates/gpu-device/src/preference.rs @@ -189,7 +189,6 @@ fn drawn_with(candidates: &[Candidate], index: usize) -> Option { /// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key /// of this adapter. -#[cfg(not(target_arch = "wasm32"))] pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool { match preference { Preference::Software => candidate.is_software(), diff --git a/crates/gpu-wgpu/src/lib.rs b/crates/gpu-wgpu/src/lib.rs index 1b26b30383..ec0e71b276 100644 --- a/crates/gpu-wgpu/src/lib.rs +++ b/crates/gpu-wgpu/src/lib.rs @@ -46,6 +46,8 @@ fn probe_caps_native() -> DeviceCaps { max_buffer_size: limits.max_buffer_size, max_texture_dimension_2d: limits.max_texture_dimension_2d, features: Vec::new(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, } } @@ -133,6 +135,8 @@ mod native { max_buffer_size: device_limits.max_buffer_size, max_texture_dimension_2d: device_limits.max_texture_dimension_2d, features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(), + vendor_id: info.vendor, + software: info.device_type == wgpu::DeviceType::Cpu, }; let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() }); Some((caps, backing)) diff --git a/crates/gpu/src/caps.rs b/crates/gpu/src/caps.rs index 75dcf173d0..1ae87a0d30 100644 --- a/crates/gpu/src/caps.rs +++ b/crates/gpu/src/caps.rs @@ -20,6 +20,20 @@ pub struct DeviceCaps { /// never on what the adapter merely advertised. #[serde(default)] pub features: Vec, + /// The PCI vendor id of the device's adapter (or the Khronos vendor id some Vulkan drivers + /// report instead); 0 when unknown or on backends with no device. + #[serde(default)] + pub vendor_id: u32, + /// The device draws on the CPU (a software adapter such as WARP, llvmpipe or lavapipe). + #[serde(default)] + pub software: bool, +} + +impl DeviceCaps { + /// Whether the feature named `name` (as in [`features`](Self::features)) is enabled. + pub fn has_feature(&self, name: &str) -> bool { + self.features.iter().any(|f| f == name) + } } impl Default for DeviceCaps { @@ -31,6 +45,8 @@ impl Default for DeviceCaps { max_buffer_size: 256 * 1024 * 1024, max_texture_dimension_2d: 8192, features: Vec::new(), + vendor_id: 0, + software: false, } } } diff --git a/crates/gpu/src/tests.rs b/crates/gpu/src/tests.rs index 528b2e587d..25ee131bc3 100644 --- a/crates/gpu/src/tests.rs +++ b/crates/gpu/src/tests.rs @@ -126,3 +126,15 @@ fn chunk_buffer_splits_on_storage_binding_limit() { let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer"); assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]); } + +#[test] +fn caps_without_vendor_or_software_read_as_unknown_hardware() { + let json = r#"{"backend_name":"Vulkan","device_name":"gpu","max_storage_buffer_binding_size":1,"max_buffer_size":2,"max_texture_dimension_2d":3,"features":["TEXTURE_FORMAT_NV12"]}"#; + let caps: DeviceCaps = serde_json::from_str(json).expect("caps"); + assert_eq!((caps.vendor_id, caps.software), (0, false)); + assert!(caps.has_feature("TEXTURE_FORMAT_NV12")); + assert!(!caps.has_feature("TEXTURE_FORMAT_P010") && !caps.has_feature("")); + let software = DeviceCaps { vendor_id: 0x10005, software: true, ..caps }; + let back: DeviceCaps = serde_json::from_str(&serde_json::to_string(&software).expect("json")).expect("caps"); + assert_eq!(back, software); +} From 928692ebfddd2126f12d8312c910eada564b7a89 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:15:59 -0800 Subject: [PATCH 09/17] craft-gpu-device: keep the choice off avoided entries, stop waits on a recorded fault - choose and a named or software preference follow the newest-version correction until the entry is its own newest version. An entry without a bus id between two cards of one model no longer leaves the choice on an entry that avoided() excludes. The host test accepts every safe fallback, and None only when the Intel Vulkan entry is all there is. - An optional experimental feature is no longer requested, so the device opens without it instead of failing the adapter. - A bounded wait stops after the current slice once another clone records a loss or an error other than out of memory. - Both loss writers record the loss before setting device_lost. - Docs: recovery starts on device_status; the software notice shows only when a software adapter opened; surfaces are configured from the new adapter's capabilities; GPUInternalError on the browser backend panics in wgpu 30 before the handler runs; late completion counts as Finished. --- crates/gpu-device/README.md | 23 ++++++--- crates/gpu-device/src/adapter.rs | 73 +++++++++++++++++++++-------- crates/gpu-device/src/health.rs | 59 ++++++++++++++++++----- crates/gpu-device/src/open.rs | 18 ++++++- crates/gpu-device/src/preference.rs | 5 +- 5 files changed, 135 insertions(+), 43 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 3c7da59b5c..f1f5a9a558 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -41,7 +41,9 @@ Licensed under MIT OR Apache-2.0. browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and `Recovery` cannot move drawing to software there. `Capabilities` and `Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`, - `wait_timeout` and `wait_timeout_cancelable`, which are native only. + `wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend, + wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch` + installs runs, so such an error is not recorded. Validation and out-of-memory errors are. - An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists each failure. @@ -74,9 +76,11 @@ Licensed under MIT OR Apache-2.0. ## After a device loss -`DeviceHealth::device_lost` turns true, and `DeviceHealth::device_status` returns -`GpuFault::DeviceLost`, once the device is lost. Nothing made with the lost device can be used -again, and wgpu keeps none of its contents. The caller then: +`DeviceHealth::device_status` returns `GpuFault::DeviceLost` once a loss is recorded, and the +caller starts recovery then. `DeviceHealth::device_lost` turns true only when wgpu itself reported +the loss; it stays false for a loss the health layer recorded on its own, such as a bounded wait +that reached its deadline. Nothing made with the lost device can be used again, and wgpu keeps +none of its contents. The caller then: 1. Drops the old `Opened` and everything made with its device: buffers, textures and their views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and @@ -85,14 +89,19 @@ again, and wgpu keeps none of its contents. The caller then: waits on it return `false`. 2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`, using the returned preference and the same `Request`. When the step has a notice - (`Notice::SoftwareAfterLosses`), the app shows it. + (`Notice::SoftwareAfterLosses`), the app shows it only if the new `Opened::caps.software()` is + true. Otherwise no software adapter opened (in a browser, or with none listed), and the new + `Opened::notices` say what was opened instead. 3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another adapter, or a software one, with other features and limits: for example, without NV12 the planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead. 4. Configures each window surface again with the new device (`Surface::configure`). The surface itself is kept when it was passed to `open`, which then opens only an adapter that can draw - to it. -5. Builds the pipelines, bind groups and renderers again, and uploads the textures and buffers + to it. The new adapter may not support the old configuration (an HDR format, for example), so + the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present + mode and alpha mode from it. +5. Builds the pipelines for the surface format picked in step 4, the bind groups and renderers + again, bind groups and renderers again, and uploads the textures and buffers again from the app's own copies of their data. 6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and submits again the jobs and frames that did not complete. diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs index c0d1b5c8ff..ce62be43ec 100644 --- a/crates/gpu-device/src/adapter.rs +++ b/crates/gpu-device/src/adapter.rs @@ -160,22 +160,40 @@ pub fn native_descriptor() -> wgpu::InstanceDescriptor { /// The index of the adapter to draw with for `power`: [`wgpu_choice`], or the entry exposing the /// most features among those that are the same GPU listed by the same driver (the first of them -/// when several expose as many). For an Intel Gen 9 to Gen 11 GPU on Intel's Windows Vulkan -/// driver it is the same GPU's DirectX 12 entry, or without one the best other usable adapter. -/// `None` without a usable adapter, and when that Intel Vulkan entry is the only one. +/// when several expose as many), repeated until the entry is its own newest version. For an Intel +/// Gen 9 to Gen 11 GPU on Intel's Windows Vulkan driver it is the same GPU's DirectX 12 entry, or +/// without one the best other usable adapter. `None` without a usable adapter, and when that +/// Intel Vulkan entry is the only one. The result is never an entry [`avoided`] excludes. pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { let first = wgpu_choice(candidates, power)?; - let preferred = candidates.get(first)?; - let index = corrected(candidates, first, preferred); + let index = settled(candidates, first); if candidates.get(index).is_some_and(intel_vulkan_crashes) { // No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take. let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c)); - let (other, c) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; - return Some(corrected(candidates, other, c)); + let (other, _) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?; + return Some(settled(candidates, other)); } Some(index) } +/// [`corrected`] applied until it returns the entry it was given. An entry without a bus id can +/// be the same GPU as two entries on different buses, so one correction can land on an entry that +/// has a newer version of its own. Each step moves to an entry exposing more features (or the +/// same number at a lower index), or to a DirectX 12 entry, so the loop ends. +pub(crate) fn settled(candidates: &[Candidate], mut index: usize) -> usize { + for _ in 0..=candidates.len() { + let Some(c) = candidates.get(index) else { + return index; + }; + let next = corrected(candidates, index, c); + if next == index { + return index; + } + index = next; + } + index +} + /// `index` (the entry `preferred`), or the entry to draw with instead of it. pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize { if let Some(dx12) = dx12_instead(candidates, preferred) { @@ -341,6 +359,20 @@ pub(crate) mod tests { assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2)); } + #[test] + fn an_entry_without_a_bus_between_two_cards_is_never_drawn_with_when_avoided() { + // two cards of one model on their own buses, and an entry of the same driver without a bus + // id, which can be either card's other version + let radeon = |bus, features| gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, bus, "AMD proprietary driver", "", features); + let adapters = vec![radeon("0000:03:00.0", 60), radeon("", 70), radeon("0000:04:00.0", 80)]; + for power in POWERS { + let chosen = choose(&adapters, power); + assert_eq!(chosen, Some(2), "{power:?}"); + assert!(chosen.is_some_and(|i| !avoided(&adapters, i)), "{power:?}"); + } + assert!(avoided(&adapters, 0) && avoided(&adapters, 1) && !avoided(&adapters, 2)); + } + #[test] fn a_newer_version_never_overtakes_another_gpu_or_backend() { assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2)); @@ -550,9 +582,10 @@ pub(crate) mod tests { } /// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's - /// `request_adapter` returns, and [`choose`] returns that adapter too, a version of it exposing - /// more features, or for an Intel Gen 9 to Gen 11 GPU its DirectX 12 entry. Passes without - /// adapters. + /// `request_adapter` returns, and [`choose`] returns that adapter too, or, when wgpu's choice + /// is one [`avoided`] excludes, an adapter it does not exclude: a version exposing more + /// features, an Intel Gen 9 to Gen 11 GPU's DirectX 12 entry, or the best other adapter. + /// `None` only when every usable adapter is that Intel Vulkan entry. Passes without adapters. #[test] #[cfg(not(target_arch = "wasm32"))] fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() { @@ -564,15 +597,17 @@ pub(crate) mod tests { let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() }; let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None)); assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}"); - let picked = choose(&candidates, power).and_then(|i| candidates.get(i)); - match (&wgpu_own, picked) { - (Some(wgpu_own), Some(picked)) if wgpu_own != picked => { - let newer_version = same_gpu_and_driver(wgpu_own, picked) && picked.features > wgpu_own.features; - let intel_dx12 = wgpu_own.vendor == INTEL - && intel_gen9_to_gen11(wgpu_own.device) - && picked.backend == Backend::Dx12 - && picked.device == wgpu_own.device; - assert!(newer_version || intel_dx12, "{power:?}: {picked} instead of {wgpu_own}"); + let own_index = wgpu_choice(&candidates, power); + let chosen = choose(&candidates, power); + let picked = chosen.and_then(|i| candidates.get(i)); + match (own_index, chosen) { + (Some(own), Some(index)) if own != index => { + assert!(avoided(&candidates, own), "{power:?}: {picked:?} instead of {wgpu_own:?}, which is not avoided"); + assert!(!avoided(&candidates, index), "{power:?}: {picked:?} is avoided"); + } + (Some(own), None) => { + let only_intel_vulkan = candidates.iter().filter(|c| c.usable).all(intel_vulkan_crashes); + assert!(only_intel_vulkan, "{power:?}: nothing instead of {:?}", candidates.get(own)); } _ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"), } diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index f1ff61b640..bad057b6b5 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -19,7 +19,8 @@ use std::time::{Duration, Instant}; /// Outcome of a bounded wait for submitted GPU work. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum WaitOutcome { - /// The submitted work finished before the deadline. + /// The submitted work finished before the deadline, or just after it, when wgpu read the + /// fence again at the end of the last poll. Finished, /// The deadline passed (or the device faulted) before the work finished. TimedOut, @@ -121,7 +122,9 @@ impl DeviceHealth { } /// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag - /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). + /// instead of panicking. Replaces any handler set before (wgpu keeps one of each). On the + /// browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before this handler + /// runs, so such an error is not recorded; validation and out-of-memory errors are. pub fn watch(device: &wgpu::Device) -> Self { let health = Self::new(); let lost = health.clone(); @@ -133,8 +136,9 @@ impl DeviceHealth { (_, false) => message, }; log::error!("wgpu device lost ({reason:?}): {detail}"); - lost.0.device_lost.store(true, Ordering::Release); + // The loss first: a caller that sees `device_lost` then also sees the fault. lost.mark(Fault::Lost(detail)); + lost.0.device_lost.store(true, Ordering::Release); }); let errors = health.clone(); device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e))); @@ -270,8 +274,8 @@ impl DeviceHealth { /// `Device::poll` panicked: wgpu found the device lost. fn lost_by_poll(&self) { - self.0.device_lost.store(true, Ordering::Release); self.mark(Fault::Lost("the device stopped responding".into())); + self.0.device_lost.store(true, Ordering::Release); } /// Block until `index` (or all submitted work) finished, unless the device was lost or @@ -327,7 +331,10 @@ impl DeviceHealth { /// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between /// them, keeping the same overall deadline. Every slice waits for the same `index`. A slice /// that times out means the work has not finished yet; only the overall deadline (or a poll - /// that panics) marks the device faulted. + /// that panics) marks the device faulted. A loss or an error other than out of memory that + /// another clone records during the wait ends it after the current slice, with + /// [`WaitOutcome::TimedOut`]. wgpu reads the fence again after a slice's own timeout, so work + /// that finishes in that gap, just after the deadline, is [`WaitOutcome::Finished`]. #[cfg(not(target_arch = "wasm32"))] pub fn wait_timeout_cancelable( &self, @@ -349,14 +356,8 @@ impl DeviceHealth { device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) }) })); match poll { - Ok(Ok(_)) => { - if self.pollable() { - SlicePoll::Done - } else { - SlicePoll::Failed - } - } - Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + Ok(Ok(_)) => self.after_slice(true), + Ok(Err(wgpu::PollError::Timeout)) => self.after_slice(false), // A submission index the device never issued: the caller's mistake, not the GPU's. Ok(Err(e)) => { log::warn!("wgpu poll: {e}"); @@ -375,6 +376,20 @@ impl DeviceHealth { } outcome } + + /// What a slice that returned reports, `finished` or not: failed once a clone of this flag + /// recorded a loss or an error other than out of memory, so the next slice does not poll a + /// device that is not to be used. + #[cfg(not(target_arch = "wasm32"))] + fn after_slice(&self, finished: bool) -> SlicePoll { + if !self.pollable() { + SlicePoll::Failed + } else if finished { + SlicePoll::Done + } else { + SlicePoll::Pending + } + } } /// What one bounded poll reported. @@ -564,6 +579,24 @@ mod tests { assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait"); } + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_a_wait_stops_the_next_slice() { + let h = DeviceHealth::new(); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + assert_eq!(h.after_slice(true), SlicePoll::Done); + // out of memory alone: polls keep reclaiming memory + h.mark(Fault::Error(OUT_OF_MEMORY.into())); + assert_eq!(h.after_slice(false), SlicePoll::Pending); + // another clone records a validation error while a slice is pending + h.clone().mark(Fault::Error("Validation Error".into())); + assert_eq!(h.after_slice(false), SlicePoll::Failed, "the next slice must not poll"); + assert_eq!(h.after_slice(true), SlicePoll::Failed); + let lost = DeviceHealth::new(); + lost.clone().mark(Fault::Lost("reset".into())); + assert_eq!(lost.after_slice(false), SlicePoll::Failed); + } + #[test] fn fault_text() { assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 48325095cb..984f53f34b 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -15,7 +15,9 @@ pub struct Request<'a> { pub label: Option<&'a str>, /// Features the device must have. An adapter without them is skipped. pub required_features: Features, - /// Features asked for when the adapter has them. + /// Features asked for when the adapter has them. Experimental features + /// (`Features::all_experimental_mask`) are left out here: the device descriptor does not + /// enable experimental features, and wgpu refuses a device that asks for one without that. pub optional_features: Features, /// The limits to ask for; `None` asks for the adapter's own limits. pub limits: Option, @@ -254,7 +256,7 @@ async fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Devi let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits()); let desc = wgpu::DeviceDescriptor { label: request.label, - required_features: request.required_features | (request.optional_features & has), + required_features: request.required_features | (request.optional_features & has & !Features::all_experimental_mask()), required_limits, ..Default::default() }; @@ -316,6 +318,18 @@ mod tests { assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); } + #[test] + fn an_optional_experimental_feature_does_not_stop_the_device_opening() { + let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12)); + let request = Request { optional_features: Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12, ..Default::default() }; + let opened = open(&instance, None, &Preference::Software, &request).unwrap(); + assert!(opened.caps.nv12(), "{}", opened.caps); + assert!(!opened.device.features().contains(Features::EXPERIMENTAL_RAY_QUERY)); + // a required one still fails as before + let required = Request { required_features: Features::EXPERIMENTAL_RAY_QUERY, ..Default::default() }; + assert!(matches!(open(&instance, None, &Preference::Software, &required), Err(OpenError::NoDevice(_)))); + } + #[test] fn an_adapter_without_a_required_feature_is_reported() { let instance = noop(Some(Features::empty())); diff --git a/crates/gpu-device/src/preference.rs b/crates/gpu-device/src/preference.rs index 539cde153f..542bf66305 100644 --- a/crates/gpu-device/src/preference.rs +++ b/crates/gpu-device/src/preference.rs @@ -4,7 +4,7 @@ use std::fmt; use wgpu::{Backend, PowerPreference}; -use crate::adapter::{Candidate, avoided, choose, corrected, intel_vulkan_crashes, type_order}; +use crate::adapter::{Candidate, avoided, choose, intel_vulkan_crashes, settled, type_order}; /// Which adapter to draw with. #[derive(Clone, Debug, Default, PartialEq, Eq)] @@ -183,7 +183,8 @@ pub fn select(candidates: &[Candidate], preference: &Preference) -> Option Option { - let index = corrected(candidates, index, candidates.get(index)?); + candidates.get(index)?; + let index = settled(candidates, index); (!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index) } From f3958d58c6b67e22ef2e2af58fe3001cafdbb15d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 11:31:36 -0800 Subject: [PATCH 10/17] craft-gpu-device: drop the no-software notice when a software device opens wgpu's fallback adapter can open a software device that the listing did not show. The notice that no software adapter was listed no longer stays on the returned Opened in that case. --- crates/gpu-device/src/open.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 984f53f34b..97d0740dd9 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -236,6 +236,10 @@ fn finish( mut notices: Vec, ) -> Opened { let caps = Capabilities::of_device(&device); + // wgpu's fallback adapter can be a software one that the listing did not show. + if candidate.is_software() { + notices.retain(|n| *n != Notice::NoSoftwareAdapter); + } if candidate.is_software() && !asked_for(preference, &candidate) { notices.push(Notice::SoftwareOnly); } @@ -318,6 +322,17 @@ mod tests { assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter); } + #[test] + fn a_software_device_drops_the_no_software_notice() { + let instance = noop(None); + let opened = open(&instance, None, &Preference::Software, &Request::default()).unwrap(); + assert!(opened.candidate.is_software()); + // as when the listing showed no software adapter and wgpu's fallback adapter opened + let notices = vec![Notice::NoSoftwareAdapter]; + let again = finish(opened.adapter, opened.device, opened.queue, opened.candidate, &Preference::Software, notices); + assert!(again.notices.is_empty(), "{:?}", again.notices); + } + #[test] fn an_optional_experimental_feature_does_not_stop_the_device_opening() { let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12)); From 8fd418260eed416e9b7a776d02cb676bbe6b6049 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 14:44:29 -0800 Subject: [PATCH 11/17] craft-gpu-device: end an unbounded wait on a fault another clone records DeviceHealth::wait polls in slices of at most 100 ms and checks the health between them, so a loss or an error other than out of memory recorded elsewhere while the work has not finished ends the wait instead of leaving it blocked. It takes a submission index, as wait_timeout does, so work submitted during the wait does not extend it. The README step that lists what to build again after a loss no longer repeats a phrase. --- crates/gpu-device/README.md | 10 ++-- crates/gpu-device/src/health.rs | 91 +++++++++++++++++++++++++-------- crates/gpu-device/src/open.rs | 9 ++-- 3 files changed, 82 insertions(+), 28 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index f1f5a9a558..1b0affc7af 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -60,9 +60,11 @@ Licensed under MIT OR Apache-2.0. - Only an error whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in a resource's label do not count. An error about a destroyed buffer or texture is recorded as an error. -- `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for +- `wait`, `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the wait. +- `wait` has no deadline. It polls in slices of at most 100 ms, and a loss or an error other than + out of memory that another clone of the `DeviceHealth` records ends it after the current slice. - `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that `Device::poll` raises on a lost device and record the loss. - wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback` @@ -100,9 +102,9 @@ none of its contents. The caller then: to it. The new adapter may not support the old configuration (an HDR format, for example), so the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present mode and alpha mode from it. -5. Builds the pipelines for the surface format picked in step 4, the bind groups and renderers - again, bind groups and renderers again, and uploads the textures and buffers - again from the app's own copies of their data. +5. Builds the pipelines for the surface format picked in step 4, and the bind groups and + renderers, again, and uploads the textures and buffers again from the app's own copies of + their data. 6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and submits again the jobs and frames that did not complete. 7. Uses the new `Opened::health`. The old `DeviceHealth` keeps reporting the loss. diff --git a/crates/gpu-device/src/health.rs b/crates/gpu-device/src/health.rs index bad057b6b5..9374175a6b 100644 --- a/crates/gpu-device/src/health.rs +++ b/crates/gpu-device/src/health.rs @@ -278,28 +278,51 @@ impl DeviceHealth { self.0.device_lost.store(true, Ordering::Release); } - /// Block until `index` (or all submitted work) finished, unless the device was lost or - /// reported an error other than out of memory. Returns whether the work finished with the - /// device still usable: `false` when it was lost or reported such an error, before or during - /// the wait, and when the poll itself failed, so the work may still be running. After an - /// out-of-memory error the wait still runs. A panic in `Device::poll` is caught and recorded - /// as a loss. Native only: the web has no blocking wait. + /// Block until the work up to `index` finished, unless the device was lost or reported an + /// error other than out of memory. To wait for everything submitted so far, pass the index of + /// an empty submission (`queue.submit([])`); work submitted after it does not extend the + /// wait. Returns whether the work finished with the device still usable: `false` when it was + /// lost or reported such an error, before or during the wait, and when the poll itself + /// failed, so the work may still be running. After an out-of-memory error the wait still + /// runs. The wait has no deadline, but it polls in slices of at most 100 ms, so a loss or an + /// error other than out of memory that another clone records while the work has not finished + /// ends it after the current slice. A panic in `Device::poll` is caught and recorded as a + /// loss. Native only: the web has no blocking wait. #[cfg(not(target_arch = "wasm32"))] - pub fn wait(&self, device: &wgpu::Device, index: Option) -> bool { - if !self.pollable() { - return false; - } - let poll = - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Wait { submission_index: index, timeout: None }))); - match poll { - Ok(Ok(_)) => self.pollable(), - Ok(Err(e)) => { - log::warn!("wgpu poll: {e}"); - false + pub fn wait(&self, device: &wgpu::Device, index: wgpu::SubmissionIndex) -> bool { + const SLICE: Duration = Duration::from_millis(100); + self.wait_unbounded(|| { + let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) }) + })); + match poll { + Ok(Ok(_)) => SlicePoll::Done, + Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending, + Ok(Err(e)) => { + log::warn!("wgpu poll: {e}"); + SlicePoll::Failed + } + Err(_) => { + self.lost_by_poll(); + SlicePoll::Failed + } } - Err(_) => { - self.lost_by_poll(); - false + }) + } + + /// [`Self::wait`]'s loop: `poll` runs one slice and reports what wgpu returned. The loop ends + /// when a slice finished or failed, and before the next slice once a clone of this flag + /// recorded a loss or an error other than out of memory. + #[cfg(not(target_arch = "wasm32"))] + fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll) -> bool { + loop { + if !self.pollable() { + return false; + } + match poll() { + SlicePoll::Done => return self.pollable(), + SlicePoll::Pending => {} + SlicePoll::Failed => return false, } } } @@ -597,6 +620,34 @@ mod tests { assert_eq!(lost.after_slice(false), SlicePoll::Failed); } + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn a_fault_recorded_during_an_unbounded_wait_ends_it() { + let h = DeviceHealth::new(); + let other = h.clone(); + let mut polls = 0; + let finished = h.wait_unbounded(|| { + polls += 1; + if polls == 2 { + other.mark(Fault::Error("Validation Error".into())); + } + assert!(polls <= 2, "a slice ran after the fault"); + SlicePoll::Pending + }); + assert!(!finished); + assert_eq!(polls, 2); + // out of memory alone keeps the wait going until the work finishes + let oom = DeviceHealth::new(); + oom.mark(Fault::Error(OUT_OF_MEMORY.into())); + let mut polls = 0; + assert!(oom.wait_unbounded(|| { + polls += 1; + if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done } + })); + assert_eq!(polls, 3); + assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed)); + } + #[test] fn fault_text() { assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost"); diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 97d0740dd9..6f77dca96e 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -417,26 +417,27 @@ mod tests { let health = opened.health.clone(); health.mark(Fault::Error(OUT_OF_MEMORY.into())); let index = opened.queue.submit([]); - assert!(health.wait(&opened.device, Some(index.clone())), "{health:?}"); - assert!(health.wait_timeout(&opened.device, index, std::time::Duration::from_secs(5)), "{health:?}"); + assert!(health.wait(&opened.device, index.clone()), "{health:?}"); + assert!(health.wait_timeout(&opened.device, index.clone(), std::time::Duration::from_secs(5)), "{health:?}"); health.clear_out_of_memory(health.out_of_memory_count()); assert!(health.is_ok(), "{health:?}"); // any other error still stops them health.mark(Fault::Error("Validation Error".into())); - assert!(!health.wait(&opened.device, None)); + assert!(!health.wait(&opened.device, index)); } #[test] fn a_lost_device_is_seen_by_its_health() { let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap(); let health = opened.health.clone(); + let index = opened.queue.submit([]); opened.device.destroy(); health.probe(&opened.device); assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}"); assert!(!health.is_ok()); assert!(matches!(health.device_status(), Err(craft_gpu::GpuFault::DeviceLost(_))), "{health:?}"); // a later wait does not touch the lost device - assert!(!health.wait(&opened.device, None)); + assert!(!health.wait(&opened.device, index)); } #[test] From 840e2657d30c5fb659bdce6b8f13d9c8f08a62de Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 20 Nov 2026 15:14:35 -0800 Subject: [PATCH 12/17] craft-gpu-device: test that an adapter below the requested limits is skipped request_device returns an error for limits above the adapter's, and open reports that adapter as DeviceFailed and tries the next one. A test now covers it, and the docs say so. --- crates/gpu-device/README.md | 6 +++--- crates/gpu-device/src/open.rs | 23 ++++++++++++++++++++++- 2 files changed, 25 insertions(+), 4 deletions(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 1b0affc7af..38b5314de1 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -44,9 +44,9 @@ Licensed under MIT OR Apache-2.0. `wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch` installs runs, so such an error is not recorded. Validation and out-of-memory errors are. -- An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a - `Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists - each failure. +- An adapter that lacks `Request::required_features`, whose limits are lower than + `Request::limits`, or whose `request_device` fails, adds a `Notice::DeviceFailed`, and `open` + tries the next one. When every adapter fails, the error lists each failure. - A named adapter that is no longer listed, or can no longer draw to the surface, gives the automatic choice and `Notice::AdapterMissing`. - A driver that ends the process cannot be caught. `choose` and `ranked` never use an older diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 6f77dca96e..2f52b976e3 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -19,7 +19,8 @@ pub struct Request<'a> { /// (`Features::all_experimental_mask`) are left out here: the device descriptor does not /// enable experimental features, and wgpu refuses a device that asks for one without that. pub optional_features: Features, - /// The limits to ask for; `None` asks for the adapter's own limits. + /// The limits to ask for; `None` asks for the adapter's own limits. An adapter whose limits + /// are lower is skipped. pub limits: Option, } @@ -355,6 +356,26 @@ mod tests { assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}"); } + #[test] + fn an_adapter_below_the_requested_limits_is_reported() { + let mut desc = wgpu::InstanceDescriptor::new_without_display_handle(); + desc.backends = wgpu::Backends::NOOP; + desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, limits: Some(Limits::default()), ..Default::default() }; + let instance = Instance::new(desc); + let over = Limits::default().max_texture_dimension_2d + 1; + let request = Request { limits: Some(Limits { max_texture_dimension_2d: over, ..Limits::default() }), ..Default::default() }; + let err = open(&instance, None, &Preference::Software, &request).unwrap_err(); + let OpenError::NoDevice(notices) = &err else { panic!("{err}") }; + assert!( + notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } + if error.contains("max_texture_dimension_2d"))), + "{notices:?}" + ); + // limits within the adapter's still open + let within = Request { limits: Some(Limits::downlevel_defaults()), ..Default::default() }; + assert!(open(&instance, None, &Preference::Software, &within).is_ok()); + } + #[test] fn a_software_adapter_is_reported_unless_it_was_asked_for() { let cpu = noop(None); From a59865c9a24d9826b883c892b9542c256005431d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:19:07 -0800 Subject: [PATCH 13/17] craft-gpu-device: take wgpu from the workspace and forward backend features Cargo.toml used wgpu = "30", which turns on all of wgpu's default backends in every app that depends on the crate. It now uses the workspace's wgpu (std and wgsl only), adds WebGPU on wasm32, and forwards native-vulkan, native-dx12, native-metal and native-gles as craft-gpu-wgpu does. The noop dev-dependency also comes from the workspace. --- crates/gpu-device/Cargo.toml | 13 +++++++++++-- crates/gpu-device/README.md | 5 +++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/crates/gpu-device/Cargo.toml b/crates/gpu-device/Cargo.toml index 88ac88149a..19f6cfa356 100644 --- a/crates/gpu-device/Cargo.toml +++ b/crates/gpu-device/Cargo.toml @@ -14,17 +14,26 @@ workspace = true default = ["serde"] # Reading and writing `Preference` and `AdapterKey` with serde. serde = ["dep:serde"] +# Native wgpu backends, as in craft-gpu-wgpu. None is on by default; the app turns on the ones it +# ships, through this crate or through craft-gpu-wgpu. +native-vulkan = ["wgpu/vulkan"] +native-dx12 = ["wgpu/dx12"] +native-metal = ["wgpu/metal"] +native-gles = ["wgpu/gles"] [dependencies] craft-gpu = { workspace = true } -wgpu = "30" log = { workspace = true } serde = { workspace = true, optional = true } +[target.'cfg(target_arch = "wasm32")'.dependencies] +wgpu = { workspace = true, features = ["webgpu"] } + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] pollster = { workspace = true } +wgpu = { workspace = true } [dev-dependencies] # The noop backend opens devices without a GPU in the tests. -wgpu = { version = "30", features = ["noop"] } +wgpu = { workspace = true, features = ["noop"] } serde_json = { workspace = true } diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index 38b5314de1..af09d89333 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -5,6 +5,11 @@ drivers that crash, a software fallback, a capability report, and device health after a device loss. The crate depends on `craft-gpu`, `wgpu` 30, `pollster` and `log`, with `serde` as an optional feature (on by default). It depends on no app crate. +It uses the workspace's `wgpu`, which turns on no native backend, and the WebGPU backend on +`wasm32`. The `native-vulkan`, `native-dx12`, `native-metal` and `native-gles` features turn on +wgpu's backends, as the features of the same names in `craft-gpu-wgpu` do. Cargo merges the +features, so an app can turn them on through either crate. + Licensed under MIT OR Apache-2.0. ## Contents From 8bd8f865ff286be03074e77ced6a4ebc6743d0fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 19:33:43 -0800 Subject: [PATCH 14/17] craft-gpu-device: try wgpu's fallback adapter after a listed software adapter fails open_async skipped the fallback request once any software adapter had been tried, even when wgpu's fallback adapter was a different one. It now skips only an adapter the ranked loop already tried. --- crates/gpu-device/src/open.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/crates/gpu-device/src/open.rs b/crates/gpu-device/src/open.rs index 2f52b976e3..cb55cdfcc3 100644 --- a/crates/gpu-device/src/open.rs +++ b/crates/gpu-device/src/open.rs @@ -172,12 +172,12 @@ pub async fn open_async( if let Some(first) = order.first() { log_choice(&candidates, *first, preference.power()); } - let mut tried_software = false; + let mut tried: Vec<&Candidate> = Vec::new(); for index in order { let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else { continue; }; - tried_software |= candidate.is_software(); + tried.push(candidate); match open_on(adapter, request).await { Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)), Err(error) => { @@ -186,11 +186,12 @@ pub async fn open_async( } } } - // In a browser the request below would ask for the same adapter again. - if cfg!(not(target_arch = "wasm32")) && !tried_software { + // wgpu's fallback adapter, unless the loop above already tried it. In a browser the request + // below would ask for the same adapter again. + if cfg!(not(target_arch = "wasm32")) { let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() }; - if let Ok(adapter) = instance.request_adapter(&options).await { - let candidate = Candidate::of(&adapter, surface); + let fallback = instance.request_adapter(&options).await.ok().map(|a| (Candidate::of(&a, surface), a)); + if let Some((candidate, adapter)) = fallback.filter(|(c, _)| !tried.contains(&c)) { match open_on(&adapter, request).await { Ok((device, queue)) => { log::info!("graphics adapter chosen: {candidate}"); From 6195baabe68810e667ca7b3458bf891905ff1da2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 00:00:47 -0800 Subject: [PATCH 15/17] gpu-device: stop linking private items from choose's documentation --- crates/gpu-device/src/adapter.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs index ce62be43ec..64c13a432e 100644 --- a/crates/gpu-device/src/adapter.rs +++ b/crates/gpu-device/src/adapter.rs @@ -158,12 +158,12 @@ pub fn native_descriptor() -> wgpu::InstanceDescriptor { desc } -/// The index of the adapter to draw with for `power`: [`wgpu_choice`], or the entry exposing the +/// The index of the adapter to draw with for `power`: `wgpu_choice`, or the entry exposing the /// most features among those that are the same GPU listed by the same driver (the first of them /// when several expose as many), repeated until the entry is its own newest version. For an Intel /// Gen 9 to Gen 11 GPU on Intel's Windows Vulkan driver it is the same GPU's DirectX 12 entry, or /// without one the best other usable adapter. `None` without a usable adapter, and when that -/// Intel Vulkan entry is the only one. The result is never an entry [`avoided`] excludes. +/// Intel Vulkan entry is the only one. The result is never an entry `avoided` excludes. pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option { let first = wgpu_choice(candidates, power)?; let index = settled(candidates, first); From cabc6e06058e2ef714806be01608810b3e9b91b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:24:38 -0800 Subject: [PATCH 16/17] craft: expose GPU device selection through the facade --- Cargo.lock | 1 + crates/craft/Cargo.toml | 8 ++++++++ crates/craft/src/lib.rs | 2 ++ crates/gpu-device/README.md | 2 ++ 4 files changed, 13 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index ea0dec51fe..0af0a637b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1819,6 +1819,7 @@ dependencies = [ "craft-geom", "craft-gif", "craft-gpu", + "craft-gpu-device", "craft-gpu-null", "craft-gpu-providers", "craft-gpu-wgpu", diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 81f53fd10e..22d21fbbeb 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -221,6 +221,7 @@ craft-geom = { workspace = true, optional = true } craft-suite-account = { workspace = true, optional = true } craft-xfa = { workspace = true, optional = true } craft-gpu = { workspace = true, optional = true } +craft-gpu-device = { workspace = true, optional = true } craft-gpu-null = { workspace = true, optional = true } craft-gpu-providers = { workspace = true, optional = true } craft-gpu-wgpu = { workspace = true, optional = true } @@ -531,6 +532,13 @@ gif-frames = ["gif", "craft-gif/frames"] gpu = ["dep:craft-gpu"] gpu-startup = ["gpu", "craft-gpu/startup"] +gpu-device = ["dep:craft-gpu-device"] +gpu-device-native-dx12 = ["gpu-device", "craft-gpu-device/native-dx12"] +gpu-device-native-gles = ["gpu-device", "craft-gpu-device/native-gles"] +gpu-device-native-metal = ["gpu-device", "craft-gpu-device/native-metal"] +gpu-device-native-vulkan = ["gpu-device", "craft-gpu-device/native-vulkan"] +gpu-device-serde = ["gpu-device", "craft-gpu-device/serde"] + gpu-null = ["dep:craft-gpu-null"] gpu-providers = ["dep:craft-gpu-providers"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 8946df18b6..c681dd7fd1 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -161,6 +161,8 @@ pub use craft_geom as geom; pub use craft_gif as gif; #[cfg(feature = "gpu")] pub use craft_gpu as gpu; +#[cfg(feature = "gpu-device")] +pub use craft_gpu_device as gpu_device; #[cfg(feature = "gpu-null")] pub use craft_gpu_null as gpu_null; #[cfg(feature = "gpu-providers")] diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index af09d89333..e755b1ec57 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -10,6 +10,8 @@ It uses the workspace's `wgpu`, which turns on no native backend, and the WebGPU wgpu's backends, as the features of the same names in `craft-gpu-wgpu` do. Cargo merges the features, so an app can turn them on through either crate. +The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`. + Licensed under MIT OR Apache-2.0. ## Contents From 272e4685bff2235401995c4cb3488fc4ec877b70 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 17:31:23 -0800 Subject: [PATCH 17/17] gpu-device: share the native wgpu instance --- crates/gpu-device/README.md | 4 ++++ crates/gpu-device/src/adapter.rs | 33 +++++++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/gpu-device/README.md b/crates/gpu-device/README.md index e755b1ec57..bb083932ad 100644 --- a/crates/gpu-device/README.md +++ b/crates/gpu-device/README.md @@ -12,6 +12,10 @@ features, so an app can turn them on through either crate. The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`. +`native_instance` shares one instance across calls on native targets. It reads wgpu's environment +settings for flags and backend options when that instance is first created. `native_descriptor` +reads those settings on every call. + Licensed under MIT OR Apache-2.0. ## Contents diff --git a/crates/gpu-device/src/adapter.rs b/crates/gpu-device/src/adapter.rs index 64c13a432e..b837d47b1b 100644 --- a/crates/gpu-device/src/adapter.rs +++ b/crates/gpu-device/src/adapter.rs @@ -136,8 +136,19 @@ pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> O /// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's /// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices /// dropped at the same time can then deadlock in that driver. +/// +/// On native targets, the first call creates one shared instance and reads wgpu's environment +/// settings for flags and backend options. Later calls return clones of that instance. pub fn native_instance() -> wgpu::Instance { - wgpu::Instance::new(native_descriptor()) + #[cfg(not(target_arch = "wasm32"))] + { + static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); + SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone() + } + #[cfg(target_arch = "wasm32")] + { + wgpu::Instance::new(native_descriptor()) + } } /// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend @@ -558,6 +569,26 @@ pub(crate) mod tests { assert!(!adapters.first().is_some_and(Candidate::is_software)); } + #[test] + #[cfg(not(target_arch = "wasm32"))] + fn native_instance_is_shared_across_callers() { + let gate = std::sync::Barrier::new(3); + std::thread::scope(|scope| { + let first = scope.spawn(|| { + gate.wait(); + native_instance() + }); + let second = scope.spawn(|| { + gate.wait(); + native_instance() + }); + gate.wait(); + let first = first.join().unwrap(); + assert_eq!(first, second.join().unwrap()); + assert_eq!(first, native_instance()); + }); + } + /// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND` /// says. Runs in a child process, which has them set. #[test]