Files
lightcraft/crates/gpu/src/vram.rs
T
PiMinusMax 3943279105 Colour noise reduction: joint linear chroma filter with speck brake, CPU and GPU (#815) (#1348)
* WIP: colour NR v2 prototype (env LIGHTCRAFT_NR_V2, CPU only)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 on by default (LIGHTCRAFT_NR_V2=0 turns it off), GPU renders read back for it

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: cache renders with the new colour NR apart from older ones

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 on the GPU (fused down / apply kernels), coefficient grid sigma / 2

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 on the CPU without full-size intermediates (row-streamed passes)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: report peak device-buffer use per GPU stage with LIGHTCRAFT_PROFILE

* WIP: colour NR v2 linear mode (NRV2_LINEAR=1: c - Y, additive, noise model), Jensen term, mean-drift probe

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 noise model with equal-count luminance bands and a non-negative fit; probe asserts the mean over 3 noise realisations

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 linear mode by default (per channel, K 64, coarse pass smooths only the coarse part); CPU on GPU renders; real-colour probe

Known: tests_window::noise_reduction_does_not_depend_on_the_window fails (the noise is measured in the
rendered window; the square-root mode failed it too).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 joint guide (NRV2_JOINT=1, opt-in), luminance guide knobs, leaf-next-to-black probe, camera-look guard from 858

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: colour NR v2 reads its env knobs once (per-pixel env reads made the linear mode 11x slower); joint stage timings with LIGHTCRAFT_PROFILE

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR without redundant passes (fused paths + next weights, none after the last scale, delta-1 weights from the path), two-component buffers, parallel reconstruction

Bit-identical to 8b89526d (test joint_matches_the_reference_bit_for_bit against a test-only copy).
Cat 32.7 MP, CPU: 6.2 -> 5.0 s at Color 25, 7.0 -> 5.6 s at 100; working buffers 2.36 -> 1.44 GB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR with separate H/V slice loops and zero-difference shortcuts (no division, weight 1 without exp)

Still bit-identical to 8b89526d. Interleaved 24 MP bench: 2.72 s vs 4.52 s for the reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR on the GPU (nrcj.wgsl), default on; whole-image noise model from samples, halo bands above 2 GB

Kernels mirror nrc_joint step for step (same scale plan, noise model fitted on the CPU from GPU samples).
Cat 32.7 MP on a Quadro M2200: wb/nr 1.2-1.3 s vs 4-5 s CPU; against the CPU max 1 LSB; bands = single.
Waits after dropping large buffers (freed memory otherwise piled up to the whole 4 GB). Cache key includes joint.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: GPU joint NR plans its bands from a budget that includes the output buffer and the device buffer limit; halo 2*sum(delta) + max delta + 8; a band that cannot fit runs only this stage on the CPU

Bands vs one piece: at most 1 LSB in a few dozen pixels (running-sum boxes round differently per band start).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: GPU joint NR budgets its bands from the free device memory where it can be asked without unsafe (nvidia-smi, amdgpu sysfs), cached 3 s; fixed 2 GB otherwise

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: docs/nr-color-v2-history.md: every approach tried, measured and dropped, speed numbers, known limits (no outlier brake yet)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: history doc: speck behaviour stated qualitatively until measured on full-size renders

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint colour NR speck brake: compact colour specks (chroma far past the noise, small luminance step, shift not reaching the 5x5 border) lose their colour before the guide is built; weak at Color 25, full at 100; CPU and GPU

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint NR CPU 5.2 -> 3.5 s (33 MP), bit for bit: guide as planes with branch-free distance rows, exponentiated paths, pilot straight into planes, speck brake in place with a min/max pre-test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: joint NR GPU: path and weight pairs instead of quads (48 instead of 60 bytes per pixel, 33 MP in one piece), speck and pilot kernels without loop-indexed private arrays, noise fit cached for identical samples; Quadro M2200 2.15 -> 1.47 s, HD 630 5.66 -> 4.26 s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* WIP: speck brake: compactness from the second largest border share (a line or edge crosses the 5x5 border twice; one noisy border pixel no longer protects a speck)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: colour noise reduction as process V3

The joint method (linear R−Y / B−Y, edge-aware guide, speck brake) is process V3 and the latest; edits on V1 and V2 keep main's blurred chromaticity. The prototype switches (LIGHTCRAFT_NR_V2, NRV2_*) and the square-root and per-channel variants they selected are gone, with their GPU kernels; nrc_params uses the former defaults as constants, so V3 renders as the prototype did. The GPU falls back to the CPU joint filter when no band fits. vram is native only (wasm build). Docs: process-versions, nr-color-joint, parity checklist, what's new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: process routing test initialises its settings in place (clippy field_reassign_with_default)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: one GPU band plan at a time, with a reserve for every render on the device

An export batch renders two photos side by side (`export_parallelism`). Each joint colour NR planned
its bands from the device memory free at that moment and counted the shared buffer pool as its own,
so two plans made at once could together ask for more than there is. Measured on a Quadro M2200
(4 GB): two 33 MP exports side by side peaked at 3761 of 4096 MiB.

The plan and its bands now run under one lock (`BANDS`), and the budget leaves `VRAM_RESERVE` for
each render on the device (`RENDERS`), not just for this one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: the joint colour NR's noise fit and pilot no longer switch at a hard bound

With main's preview-scaled luminance NR (#960) the CPU and GPU renders of a 640-px preview differed
by up to 10 levels (gpu equivalence `output_spaces_match`). Their images after luminance NR differ by
9e-7 rms, but one luminance band of the noise fit sat at exactly 4 times the first fit: the CPU's
samples dropped it, the GPU's kept it, and the fitted noise came out 2.6 % apart. The pilot's axis
choice then switched at a few pixels, and the edge-aware weights carried that on.

- robust_line: a band's weight fades to 0 between 4 and 5 times the fit instead of dropping at 4
  (identical below 4).
- pilot_pick: the smoother-axis mean fades in between 0.8 and 1.25 times its bound instead of
  switching at it (identical outside), on the CPU, in nrcj.wgsl and in the test reference.

All 19 CPU/GPU comparisons of the equivalence suite are within 1 level again. The new test
noise_line_does_not_jump_when_a_band_crosses_the_outlier_bound uses the bands of that preview and
fails on the old fit (5.6 % jump).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* #815: the joint colour NR measures the whole frame's noise and is keyed by process

A window measured the noise model on the pixels it held, so a loupe window
could smooth differently from the same pixels of the full render or the
export. The model now comes from fixed tiles of the whole frame
(`lightcraft_pipeline::colour_noise`, `nrc_joint::tiles`), the same for every
window, for the CPU and the GPU, and is kept in the stage cache.

The linear stage's cache key now includes the colour filter in use, so a
process change (Update to Current Process, undo) no longer reuses the other
filter's denoised image.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M-NR: deep windows match the whole render; the VRAM query no longer stalls renders

- A U16 / F32 window with the joint colour NR is grown by the filter's reach and
  cut back, like an 8-bit one (DeepImage::crop).
- The free device memory is refreshed in the background once the cached answer is
  stale; only the first question for an adapter waits. The joint NR asks before it
  takes the BANDS lock.
- nvidia-smi starts without a console window on Windows (CREATE_NO_WINDOW).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M-NR: the VRAM query finds the right card and keeps one answer per adapter

- A card is found by its PCI address (wgpu device_pci_bus_id, nvidia-smi pci.bus_id,
  the amdgpu sysfs directory) where both sides report one; else by a device id that
  only one card has. Two cards of one model without an address give no answer, and
  the fixed band budget applies.
- Each adapter keeps its own cached answer, so a late background refresh cannot
  replace another adapter's answer. A refresh not done after 10 s is retried.
- The cache tests wait on signals instead of fixed sleeps.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* M-NR: the VRAM cache tests no longer depend on timing

The two cache tests used a 20 ms TTL: on a slow machine a refreshed answer could go
stale again between assertions and start an extra query. They now use a 30 s TTL and
age an answer explicitly (Cache::expire, test only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* GPU: allow joint_band's eight arguments, as color_nr_joint does

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-11-06 09:44:58 +01:00

374 lines
16 KiB
Rust

//! How much device memory is free right now, where that can be asked without `unsafe`: the NVIDIA
//! driver's `nvidia-smi` (Linux and Windows) and the amdgpu driver's sysfs counters (Linux). Other
//! devices (AMD/Intel on Windows needs DXGI; integrated GPUs share system memory) report `None`, and the
//! caller keeps its fixed budget. The answer is cached for a few seconds: renders ask often, and the
//! query starts a process on NVIDIA. Only the first question for an adapter waits for the query; later
//! ones get the last answer while a background thread asks again, so no render (and no lock it holds)
//! waits for `nvidia-smi`. A card is found by its PCI address where the backend reports it, else by its
//! device id; when that matches several cards (two of the same model), the answer is `None`.
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, Instant};
/// How long an answer is fresh; an older one is still returned while a newer one is asked for.
const TTL: Duration = Duration::from_secs(3);
/// How long `nvidia-smi` may take before it is given up on.
const QUERY_TIMEOUT: Duration = Duration::from_secs(2);
const NVIDIA: u32 = 0x10de;
const AMD: u32 = 0x1002;
static CACHE: Cache = Cache::new(TTL);
/// Free device memory of the adapter `info` describes, in bytes, or `None` when it cannot be asked.
pub fn free_bytes(info: &wgpu::AdapterInfo) -> Option<u64> {
let adapter = Adapter { vendor: info.vendor, device: info.device, bus: pci_address(&info.device_pci_bus_id) };
CACHE.get(&adapter, query)
}
/// Which card: vendor and device id, and the PCI address where the backend reports it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Adapter {
vendor: u32,
device: u32,
bus: Option<Pci>,
}
/// A PCI address: domain, bus, device, function.
type Pci = [u32; 4];
/// `0000:01:00.0` (Vulkan, sysfs) or `00000000:01:00.0` (`nvidia-smi`).
fn pci_address(s: &str) -> Option<Pci> {
let mut parts = s.trim().split(':');
let (domain, bus, rest) = (parts.next()?, parts.next()?, parts.next()?);
let (device, function) = rest.split_once('.')?;
if parts.next().is_some() {
return None;
}
let hex = |x: &str| u32::from_str_radix(x.trim(), 16).ok();
Some([hex(domain)?, hex(bus)?, hex(device)?, hex(function)?])
}
/// One card a driver lists, with its free memory in bytes.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Card {
bus: Option<Pci>,
device: u32,
free: u64,
}
/// The free memory of `want` among the listed `cards`: the card at its PCI address when both sides
/// report one, else the only card with its device id, else the only card listed. `None` when that is
/// ambiguous or the address is listed by no card.
fn pick(cards: &[Card], want: &Adapter) -> Option<u64> {
if let Some(bus) = want.bus
&& cards.iter().any(|c| c.bus.is_some())
{
return cards.iter().find(|c| c.bus == Some(bus)).map(|c| c.free);
}
let mut same = cards.iter().filter(|c| c.device == want.device);
match (same.next(), same.next()) {
(Some(c), None) => Some(c.free),
(None, _) if cards.len() == 1 => cards.first().map(|c| c.free),
_ => None,
}
}
/// The last answer for one adapter: when it was asked, the answer, and since when a newer one is
/// being asked for.
struct Answer {
adapter: Adapter,
at: Instant,
free: Option<u64>,
asking: Option<Instant>,
}
type Ask = fn(&Adapter) -> Option<u64>;
/// Adapters remembered (a renderer, a face finder and a model may each use another device).
const ADAPTERS: usize = 4;
/// A background query not done after this is taken as lost, and the next question asks again.
const LOST: Duration = Duration::from_secs(10);
struct Cache {
ttl: Duration,
answers: Mutex<Vec<Answer>>,
}
impl Cache {
const fn new(ttl: Duration) -> Self {
Cache { ttl, answers: Mutex::new(Vec::new()) }
}
/// The answer of `ask` for `adapter`: cached, refreshed in the background once it is older than the
/// TTL (in the caller where no thread can be started), and asked for directly the first time.
fn get(&'static self, adapter: &Adapter, ask: Ask) -> Option<u64> {
{
let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
if let Some(a) = answers.iter_mut().find(|a| a.adapter == *adapter) {
let busy = a.asking.is_some_and(|t| t.elapsed() < LOST);
if a.at.elapsed() >= self.ttl && !busy {
let adapter = *adapter;
let refresh = std::thread::Builder::new().name("vram-query".into()).spawn(move || self.store(adapter, ask(&adapter)));
if refresh.is_err() {
drop(answers);
return self.ask_now(&adapter, ask);
}
a.asking = Some(Instant::now());
}
return a.free;
}
}
self.ask_now(adapter, ask)
}
fn ask_now(&self, adapter: &Adapter, ask: Ask) -> Option<u64> {
let free = ask(adapter);
self.store(*adapter, free);
free
}
/// Keep `adapter`'s answer (each adapter has its own; the oldest one goes when the list is full).
fn store(&self, adapter: Adapter, free: Option<u64>) {
let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
answers.retain(|a| a.adapter != adapter);
if answers.len() >= ADAPTERS {
answers.remove(0);
}
answers.push(Answer { adapter, at: Instant::now(), free, asking: None });
}
/// Make `adapter`'s answer as old as the TTL (tests: no waiting, so no answer goes stale by itself
/// on a slow machine). `false` when there is no answer, or the clock does not reach that far back.
#[cfg(test)]
fn expire(&self, adapter: &Adapter) -> bool {
let mut answers = self.answers.lock().unwrap_or_else(PoisonError::into_inner);
let Some(a) = answers.iter_mut().find(|a| a.adapter == *adapter) else { return false };
let Some(at) = a.at.checked_sub(self.ttl) else { return false };
a.at = at;
true
}
#[cfg(test)]
fn asking(&self, adapter: &Adapter) -> bool {
self.answers.lock().unwrap_or_else(PoisonError::into_inner).iter().any(|a| a.adapter == *adapter && a.asking.is_some())
}
}
#[cfg(not(target_arch = "wasm32"))]
fn query(adapter: &Adapter) -> Option<u64> {
match adapter.vendor {
NVIDIA => nvidia(adapter),
AMD => amdgpu(adapter),
_ => None,
}
}
/// `nvidia-smi --query-gpu=pci.bus_id,pci.device_id,memory.free`: one line per GPU,
/// `DDDDDDDD:BB:DD.F, 0xDDDDVVVV, <MiB>`.
#[cfg(not(target_arch = "wasm32"))]
fn nvidia(adapter: &Adapter) -> Option<u64> {
let out = run_with_timeout("nvidia-smi", &["--query-gpu=pci.bus_id,pci.device_id,memory.free", "--format=csv,noheader,nounits"])?;
pick(&parse_nvidia(&out), adapter)
}
/// The cards `nvidia-smi` lists, free memory in bytes.
fn parse_nvidia(out: &str) -> Vec<Card> {
out.lines()
.filter_map(|l| {
let mut f = l.split(',');
let (bus, id, free) = (f.next()?, f.next()?, f.next()?);
let id = u32::from_str_radix(id.trim().trim_start_matches("0x").trim_start_matches("0X"), 16).ok()?;
let free = free.trim().parse::<u64>().ok()?.checked_mul(1 << 20)?;
Some(Card { bus: pci_address(bus), device: id >> 16, free })
})
.collect()
}
/// `mem_info_vram_total - mem_info_vram_used` of the amdgpu card (its sysfs device directory is named
/// by its PCI address).
#[cfg(not(target_arch = "wasm32"))]
fn amdgpu(adapter: &Adapter) -> Option<u64> {
let read_hex = |p: &std::path::Path| -> Option<u32> {
let s = std::fs::read_to_string(p).ok()?;
u32::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok()
};
let read_u64 = |p: &std::path::Path| -> Option<u64> { std::fs::read_to_string(p).ok()?.trim().parse().ok() };
let mut cards: Vec<Card> = Vec::new();
let mut seen = Vec::new();
for entry in std::fs::read_dir("/sys/class/drm").ok()?.flatten() {
// card0 and renderD128 are the same device
let Ok(dev) = std::fs::canonicalize(entry.path().join("device")) else { continue };
if seen.contains(&dev) || read_hex(&dev.join("vendor")) != Some(adapter.vendor) {
continue;
}
seen.push(dev.clone());
let (Some(device), Some(total), Some(used)) =
(read_hex(&dev.join("device")), read_u64(&dev.join("mem_info_vram_total")), read_u64(&dev.join("mem_info_vram_used")))
else {
continue;
};
let bus = dev.file_name().and_then(|n| pci_address(&n.to_string_lossy()));
cards.push(Card { bus, device, free: total.saturating_sub(used) });
}
pick(&cards, adapter)
}
/// Run a program and return its standard output, or `None` if it is missing, fails or takes too long.
#[cfg(not(target_arch = "wasm32"))]
fn run_with_timeout(program: &str, args: &[&str]) -> Option<String> {
use std::io::Read;
use std::process::{Command, Stdio};
let mut cmd = Command::new(program);
cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::null()).stdin(Stdio::null());
// the release app has no console: without this, Windows opens one for each query
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
cmd.creation_flags(CREATE_NO_WINDOW);
}
let mut child = cmd.spawn().ok()?;
let start = Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => break,
Ok(Some(_)) | Err(_) => return None,
Ok(None) if start.elapsed() > QUERY_TIMEOUT => {
let _ = child.kill();
let _ = child.wait();
return None;
}
Ok(None) => std::thread::sleep(Duration::from_millis(5)),
}
}
let mut out = String::new();
child.stdout.take()?.read_to_string(&mut out).ok()?;
Some(out)
}
#[cfg(test)]
mod tests {
use super::*;
const fn adapter(vendor: u32, device: u32) -> Adapter {
Adapter { vendor, device, bus: None }
}
/// Wait until `flag` is set (a fake query that answers when the test says so), at most 10 s.
fn wait_for(flag: &std::sync::atomic::AtomicBool) {
let start = Instant::now();
while !flag.load(std::sync::atomic::Ordering::SeqCst) && start.elapsed() < Duration::from_secs(10) {
std::thread::sleep(Duration::from_millis(1));
}
}
/// Wait until `cache` has no background query for `a` running, at most 10 s.
fn settled(cache: &Cache, a: &Adapter) {
let start = Instant::now();
while cache.asking(a) && start.elapsed() < Duration::from_secs(10) {
std::thread::sleep(Duration::from_millis(1));
}
assert!(!cache.asking(a), "the background query finished");
}
#[test]
fn a_stale_answer_is_returned_while_a_new_one_is_asked_for() {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
static CACHE: Cache = Cache::new(Duration::from_secs(30));
static ASKED: AtomicU64 = AtomicU64::new(0);
static ANSWER: AtomicBool = AtomicBool::new(true);
fn blocked(_: &Adapter) -> Option<u64> {
wait_for(&ANSWER);
Some(ASKED.fetch_add(1, Ordering::SeqCst) + 1)
}
let a = adapter(NVIDIA, 1);
// the first question waits for the answer
assert_eq!(CACHE.get(&a, blocked), Some(1));
assert!(CACHE.expire(&a));
// stale, and the driver does not answer: the old answer at once, a new one in the background
ANSWER.store(false, Ordering::SeqCst);
let t = Instant::now();
assert_eq!(CACHE.get(&a, blocked), Some(1));
assert_eq!(CACHE.get(&a, blocked), Some(1));
assert!(t.elapsed() < Duration::from_secs(5), "waited {:?} for the query", t.elapsed());
assert!(CACHE.asking(&a));
ANSWER.store(true, Ordering::SeqCst);
settled(&CACHE, &a);
assert_eq!(CACHE.get(&a, blocked), Some(2), "the background answer is kept");
assert_eq!(ASKED.load(Ordering::SeqCst), 2, "one query in the background, not one per question");
// another adapter is asked for directly
assert_eq!(CACHE.get(&adapter(AMD, 2), blocked), Some(3));
}
#[test]
fn each_adapter_keeps_its_own_answer() {
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
static CACHE: Cache = Cache::new(Duration::from_secs(30));
static ASKED: AtomicU64 = AtomicU64::new(0);
static ANSWER: AtomicBool = AtomicBool::new(true);
// card 1 answers when the test says so, card 2 at once; 1000s and 2000s
fn ask(a: &Adapter) -> Option<u64> {
if a.device == 1 {
wait_for(&ANSWER);
}
Some(a.device as u64 * 1000 + ASKED.fetch_add(1, Ordering::SeqCst))
}
let (one, two) = (adapter(NVIDIA, 1), adapter(NVIDIA, 2));
assert_eq!(CACHE.get(&one, ask), Some(1000));
assert_eq!(CACHE.get(&two, ask), Some(2001));
assert!(CACHE.expire(&one) && CACHE.expire(&two));
// card 1 refreshes in the background while card 2 is asked for: neither waits, nor replaces the other
ANSWER.store(false, Ordering::SeqCst);
assert_eq!(CACHE.get(&one, ask), Some(1000));
assert_eq!(CACHE.get(&two, ask), Some(2001));
settled(&CACHE, &two);
ANSWER.store(true, Ordering::SeqCst);
settled(&CACHE, &one);
let asked = ASKED.load(Ordering::SeqCst);
assert_eq!(asked, 4, "one background query per card");
let (a1, a2) = (CACHE.get(&one, ask), CACHE.get(&two, ask));
assert!(a1.is_some_and(|v| v / 1000 == 1) && a2.is_some_and(|v| v / 1000 == 2), "{a1:?} {a2:?}");
assert_eq!(ASKED.load(Ordering::SeqCst), asked, "fresh answers are not asked for again");
}
#[test]
fn pci_addresses_parse_in_both_forms() {
assert_eq!(pci_address("0000:01:00.0"), Some([0, 1, 0, 0]));
assert_eq!(pci_address("00000000:0A:00.1"), Some([0, 10, 0, 1]));
assert_eq!(pci_address(""), None);
assert_eq!(pci_address("01:00.0"), None);
assert_eq!(pci_address("0000:01:00.0:9"), None);
}
#[test]
fn nvidia_output_is_matched_by_address_then_device_id() {
let two = "00000000:01:00.0, 0x179B10DE, 3990\n00000000:02:00.0, 0x1F0810DE, 5120\n";
let cards = parse_nvidia(two);
assert_eq!(pick(&cards, &adapter(NVIDIA, 0x1f08)), Some(5120 << 20));
assert_eq!(pick(&cards, &adapter(NVIDIA, 0x179b)), Some(3990 << 20));
// several GPUs and none matches: unknown
assert_eq!(pick(&cards, &adapter(NVIDIA, 0x2204)), None);
// a single GPU is taken even if its id is reported differently
assert_eq!(pick(&parse_nvidia("00000000:01:00.0, 0x179B10DE, 3990\n"), &adapter(NVIDIA, 0x1234)), Some(3990 << 20));
// garbage is not a number
assert!(parse_nvidia("No devices were found\n").is_empty());
assert_eq!(pick(&parse_nvidia(""), &adapter(NVIDIA, 0x179b)), None);
}
#[test]
fn two_cards_of_one_model_are_told_apart_by_address_or_not_at_all() {
let twins = parse_nvidia("00000000:01:00.0, 0x1F0810DE, 1000\n00000000:02:00.0, 0x1F0810DE, 6000\n");
let at = |bus| Adapter { bus: pci_address(bus), ..adapter(NVIDIA, 0x1f08) };
assert_eq!(pick(&twins, &at("0000:02:00.0")), Some(6000 << 20));
assert_eq!(pick(&twins, &at("0000:01:00.0")), Some(1000 << 20));
// without an address the model alone is ambiguous: no answer, the caller keeps its fixed budget
assert_eq!(pick(&twins, &adapter(NVIDIA, 0x1f08)), None);
assert_eq!(pick(&twins, &at("")), None);
// an address no card has is no card: the model is not looked up instead
let mixed = parse_nvidia("00000000:01:00.0, 0x1F0810DE, 1000\n00000000:02:00.0, 0x220410DE, 6000\n");
assert_eq!(pick(&mixed, &at("0000:03:00.0")), None);
}
}