From fd01f6a710b3c42e8fbf15650b5e7324f38cefa7 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:54:53 +0000 Subject: [PATCH 1/9] Landed flights give their host lists back at once, and only what the commands named waits On an RX 6800 XT with LEONIDA_RELAY=2 the host device is lost (0x887A0007, nothing in the air) in the first heavy scene, at some 1,270 host lists alive. land() kept the lists of the last bury_lag() (64) flights, and each list's allocator keeps its command buffers (1 MB and 64 KB per list) in the driver's 2 GB aperture segment, which fills up and the kernel marks the device failed. The lists go back to the pool as soon as their flight has landed (list::recycle_landed). What their commands named (the Detached state and uploads, and HostList::take_held: deferred work, host textures, twins, refreshes still being found) goes through host::retire and waits the bury lag, as any other object let go. The reaper thread uses recycle_landed too; the send_late fallback and the synchronous path stay on recycle. After kyokyotosh/VIctory-6700XT f173347 (GPL-3.0), via PastiiJay/klbf-lab #127. AI-assisted. Not yet built or run on a GPU. --- d3d12/crates/leonida-gpu/src/host.rs | 57 +++++++++++++++++++++------- d3d12/crates/leonida-gpu/src/list.rs | 42 ++++++++++++++++++-- 2 files changed, 81 insertions(+), 18 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index b2d09e42ca..4b715ba0ac 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -570,11 +570,12 @@ pub(crate) fn retire_resource(object: ID3D12Resource) { } /// How many submissions later than it could (the last one that may use it -/// has finished) an object let go is dropped, and a host list that has run -/// is reset, about two frames: the device losses of the night of 2026-11-25 -/// were page faults in memory nothing of ours named any more, at no command -/// in particular. Objects let go while nothing runs wait as well: lists -/// recorded and not yet sent may name them. `LEONIDA_BURY_LAG=0`: not. +/// has finished) an object let go is dropped, about two frames: the device +/// losses of the night of 2026-11-25 were page faults in memory nothing of +/// ours named any more, at no command in particular. Objects let go while +/// nothing runs wait as well: lists recorded and not yet sent may name +/// them. What a host list that ran sent ahead held waits the same +/// ([`land`]); the list itself does not. `LEONIDA_BURY_LAG=0`: not. fn bury_lag() -> u64 { static LAG: OnceLock = OnceLock::new(); *LAG.get_or_init(|| { @@ -713,7 +714,7 @@ fn reaping() -> bool { /// on the submitting thread at the end of each submission sent ahead: in a /// timeline of the world (Series X, RX 7900 XTX) host lists were reset 250 /// times a frame, 20 ms of threads' time. Only what is already due is -/// sent ([`bury_lag`] and [`land`]'s lag are unchanged). After mgrein's +/// sent ([`bury_lag`] is unchanged). After mgrein's /// VIctory-7900XTX a2cf68bb (GPL-3.0-or-later, as this), through /// Grimkaaah/Victory-Grimkaaah f2586ef (GPL-3.0), which measured -2.3 to /// -3.8 ms a frame with it on its host. @@ -733,7 +734,7 @@ fn reaper() -> Option<&'static std::sync::mpsc::Sender> { Reaped::Lists(landed) => { let _reaping = crate::timeline::span("reaper: landed lists reset and given back"); for (lists, order) in landed { - crate::list::recycle(lists, &order); + crate::list::recycle_landed(lists, &order); } } Reaped::Objects(objects) => { @@ -1651,6 +1652,21 @@ pub(crate) struct HostList { stamps: OnceLock>, } +/// What a host list that ran still held for its commands +/// ([`HostList::take_held`]), kept through [`retire`]: its deferred work +/// (upload buffers, kept pipelines and heaps, read-back buffers, prelude +/// uploads, fronts), the host textures and twins it names, the refreshes +/// still being found. What a reset hands to a pool at once (scratch chunks, +/// batched-clamp buffers) is not here, as in the other way of resetting. +/// After kyokyotosh/VIctory-6700XT f173347 (GPL-3.0), via PastiiJay/klbf-lab +/// #127. +pub(crate) struct Held { + _deferred: Deferred, + _states: States, + _twins: ByCopy, + _coming: Option<(usize, std::sync::Arc)>, +} + /// A list's prelude: an allocator and a closed list. type Prelude = (ID3D12CommandAllocator, ID3D12GraphicsCommandList); @@ -4817,13 +4833,14 @@ unsafe fn wait_host_fence(fence: &ID3D12Fence, target: u64, event: HANDLE, conte } /// Resets the host lists of settled flights and keeps them for reuse, as -/// a queue does for the lists it ran (`crate::list::recycle`). +/// a queue does for the lists it ran (`crate::list::recycle_landed`): what +/// their commands named waits [`bury_lag`] submissions more ([`retire`]); +/// the lists and their allocators are used again at once. After +/// kyokyotosh/VIctory-6700XT f173347 (GPL-3.0), via PastiiJay/klbf-lab #127: +/// holding the lists themselves for that lag kept their command memory in +/// the driver's 2 GB aperture segment until it ran full. fn land() { - let landed: Vec<_> = { - let mut line = line(); - let n = line.landed.len().saturating_sub(bury_lag() as usize); - line.landed.drain(..n).collect() - }; + let landed = std::mem::take(&mut line().landed); if landed.is_empty() { return; } @@ -4838,7 +4855,7 @@ fn land() { None => landed, }; for (lists, order) in landed { - crate::list::recycle(lists, &order); + crate::list::recycle_landed(lists, &order); } } @@ -8376,6 +8393,18 @@ impl HostList { .splice(at..at, found.into_iter().map(|(shadow, from, to)| Step::Refresh(shadow, from as usize, (to - from) as usize))); } + /// What the list holds for the commands it recorded, taken out to be + /// kept through [`retire`] while the list itself is reset and used again + /// ([`land`]); [`HostList::reset`] then finds them empty. + pub(crate) fn take_held(&self) -> Held { + Held { + _deferred: std::mem::take(&mut *self.deferred()), + _states: std::mem::take(&mut *self.states.lock().unwrap_or_else(|e| e.into_inner())), + _twins: std::mem::take(&mut *self.twins.lock().unwrap_or_else(|e| e.into_inner())), + _coming: self.coming.lock().unwrap_or_else(|e| e.into_inner()).take(), + } + } + /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 0d46fa077d..4b6e058651 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -341,10 +341,44 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { if !pools() { return; } - for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { - // The descriptor slots and the upload memory its commands named. - drop(_state); - drop(_uploads); + keep_idle( + lists.into_iter().map(|Detached { host, _uploads, _state }| { + // The descriptor slots and the upload memory its commands named. + drop(_state); + drop(_uploads); + host + }), + ran, + ); +} + +/// [`recycle`] for lists sent ahead whose flight has landed (`crate::host::land`): what their commands named +/// (descriptor slots, upload memory, the host textures and refreshes they held) waits `crate::host::retire`'s lag, +/// and the lists go back to the pool at once. After kyokyotosh/VIctory-6700XT f173347 (GPL-3.0), via +/// PastiiJay/klbf-lab #127. +/// +/// Held in the line of landed flights for that lag instead, 64 flights of lists (some 700 at the first world load) +/// kept their allocators' command memory, and lists for new recordings were made meanwhile: on an RX 6700 XT in a +/// 32 GB PC the driver's 2 GB aperture segment for that memory ran full and the device was removed (0x887A0007, +/// nothing in the air; VIctory-6700XT `FINDINGS-6700XT.md`). Not measured here on an RX 6800 XT, which klbf-lab #127 +/// reports the same way. +#[cfg(windows)] +pub(crate) fn recycle_landed(lists: Vec, ran: &[usize]) { + let hosts = lists.into_iter().map(|Detached { host, _uploads, _state }| { + crate::host::retire((_state, _uploads, host.take_held())); + host + }); + if pools() { + keep_idle(hosts, ran); + } else { + hosts.for_each(crate::host::retire); + } +} + +/// Resets the host lists that ran and keeps them for [`fresh_list`], up to [`IDLE_MOST`]; the others go. +#[cfg(windows)] +fn keep_idle(hosts: impl Iterator, ran: &[usize]) { + for (i, host) in hosts.enumerate() { // Reset and closed here for the line's next detaches ([`IDLE_CLOSED`]), while that pool wants some. if ran.contains(&i) && closed_ahead() && IDLE_CLOSED.lock().unwrap_or_else(|e| e.into_inner()).len() < CLOSED_MOST { host.reset(); From 5a3ccef098ea96b53860e03ab3b143604642c02b Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:55:11 +0000 Subject: [PATCH 2/9] Look at the card's aperture segment and let flights land first when it is nearly full The driver keeps its command buffers in a system-memory (aperture) segment that DXGI's budgets leave out (2 GB on RDNA2 cards in klbf-lab #127 and the 6700 XT's FINDINGS). When host lists are made faster than flights give them back, it runs full and the device is lost. host/segments.rs reads the segments with D3DKMTQueryStatistics, logs them once when the device is created, and tight() says whether an aperture segment is above LEONIDA_SEGMENT_TIGHT percent (85 by default, 0: never), looked at every 100 ms at most. send_late settles the flights then when no idle host list is left. After kyokyotosh/VIctory-6700XT 018d372 (GPL-3.0), via PastiiJay/klbf-lab #127. AI-assisted. Not yet built or run on a GPU. --- d3d12/crates/leonida-gpu/Cargo.toml | 1 + d3d12/crates/leonida-gpu/src/host.rs | 9 ++ d3d12/crates/leonida-gpu/src/host/segments.rs | 126 ++++++++++++++++++ d3d12/crates/leonida-gpu/src/list.rs | 6 + 4 files changed, 142 insertions(+) create mode 100644 d3d12/crates/leonida-gpu/src/host/segments.rs diff --git a/d3d12/crates/leonida-gpu/Cargo.toml b/d3d12/crates/leonida-gpu/Cargo.toml index 617a774c2f..9ecf68abd6 100644 --- a/d3d12/crates/leonida-gpu/Cargo.toml +++ b/d3d12/crates/leonida-gpu/Cargo.toml @@ -40,6 +40,7 @@ workspace = true [target.'cfg(windows)'.dependencies] windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Cryptography", "Win32_Security_WinTrust", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] } windows = { workspace = true, features = [ + "Wdk_Graphics_Direct3D", "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", "Win32_Graphics_Direct3D12", diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 4b715ba0ac..f0d569d1c8 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1335,6 +1335,9 @@ fn create() -> windows::core::Result { let adapter = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) .ok(); + if let Some(adapter) = adapter.as_ref() { + segments::log(adapter); + } tracing::info!("host D3D12 device ready"); Ok(Host { device, @@ -5337,6 +5340,7 @@ mod menu; // Leonida: the trainer menu laid over the picture (`leonida-menu`, F4). mod trainer; mod place; +mod segments; mod send; pub(crate) use send::{goes_as_words, words_under}; // For the frame line, with `LEONIDA_SEND_TAKE_BESIDE=check` (`crate::copystat`). @@ -6994,10 +6998,15 @@ impl Host { }; LATE_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_MOVED.notify_one(); + // An aperture segment near its limit with no idle host list: the + // flights land and give their lists back before more are made. + let tight = !crate::list::has_idle() && self.adapter.as_ref().is_some_and(segments::tight); if told && !late_writes() { self.settle(&mut submitted, WHY_WRITES); } else if sizes { self.settle(&mut submitted, WHY_READ); + } else if tight { + self.settle(&mut submitted, WHY_MOST); } else if most && relay_exact() { // Until there are fewer, not until there are none. relay_wait(WHY_MOST, |line| line.lists < late_most()); diff --git a/d3d12/crates/leonida-gpu/src/host/segments.rs b/d3d12/crates/leonida-gpu/src/host/segments.rs new file mode 100644 index 0000000000..fe7106f5fa --- /dev/null +++ b/d3d12/crates/leonida-gpu/src/host/segments.rs @@ -0,0 +1,126 @@ +//! The adapter's memory segments as the graphics kernel counts them +//! (`D3DKMTQueryStatistics`): the size and use of the system-memory +//! (aperture) segments, which DXGI's budgets leave out. +//! +//! On an RX 6700 XT in a 32 GB PC one of them is 2 GB, and it holds the +//! driver's command buffers (1 MB and more for each command list), upload +//! heaps and CPU-cached custom heaps. Sending submissions ahead, the host +//! made lists faster than flights gave them back during the first world +//! load; the segment ran full, the video memory manager could not make a +//! new command list resident, and the device was removed (0x887A0007, with +//! nothing in the air, at some 1,270 host lists alive; VIctory-6700XT +//! `FINDINGS-6700XT.md`, klbf-lab #127 on an RX 6800 XT). [`tight`] says +//! when to let the flights land first. After kyokyotosh/VIctory-6700XT +//! 018d372 (GPL-3.0), via PastiiJay/klbf-lab #127. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{LazyLock, Mutex}; + +use windows::Wdk::Graphics::Direct3D::{ + D3DKMT_QUERYSTATISTICS, D3DKMT_QUERYSTATISTICS_ADAPTER, D3DKMT_QUERYSTATISTICS_QUERY_SEGMENT, + D3DKMT_QUERYSTATISTICS_RESULT, D3DKMT_QUERYSTATISTICS_SEGMENT, D3DKMT_QUERYSTATISTICS_TYPE, D3DKMTQueryStatistics, +}; +use windows::Win32::Foundation::LUID; +use windows::Win32::Graphics::Dxgi::IDXGIAdapter3; + +/// A segment: its id, whether it is an aperture (system memory the card +/// maps), its limit and the bytes resident in it (all processes'). +#[derive(Clone, Copy, Debug)] +pub(crate) struct Segment { + pub(crate) id: u32, + pub(crate) aperture: bool, + pub(crate) limit: u64, + pub(crate) resident: u64, +} + +fn query(luid: LUID, kind: D3DKMT_QUERYSTATISTICS_TYPE, segment: u32) -> Option { + let mut q = D3DKMT_QUERYSTATISTICS { Type: kind, AdapterLuid: luid, ..Default::default() }; + q.Anonymous.QuerySegment = D3DKMT_QUERYSTATISTICS_QUERY_SEGMENT { SegmentId: segment }; + // SAFETY: a plain query that fills `q`. + unsafe { D3DKMTQueryStatistics(&q) }.is_ok().then_some(q.QueryResult) +} + +fn luid(adapter: &IDXGIAdapter3) -> Option { + // SAFETY: a plain query. + unsafe { adapter.GetDesc1() }.ok().map(|d| d.AdapterLuid) +} + +/// The adapter's segments. +pub(crate) fn segments(adapter: &IDXGIAdapter3) -> Vec { + let Some(luid) = luid(adapter) else { + return Vec::new(); + }; + let Some(info) = query(luid, D3DKMT_QUERYSTATISTICS_ADAPTER, 0) else { + return Vec::new(); + }; + // SAFETY: the member an adapter query fills. + let count = unsafe { info.AdapterInformation.NbSegments }; + (0..count) + .filter_map(|id| { + let result = query(luid, D3DKMT_QUERYSTATISTICS_SEGMENT, id)?; + // SAFETY: the member a segment query fills. + let s = unsafe { result.SegmentInformation }; + Some(Segment { id, aperture: s.Aperture != 0, limit: s.CommitLimit, resident: s.BytesResident }) + }) + .collect() +} + +/// Says the segments once, at the start. +pub(crate) fn log(adapter: &IDXGIAdapter3) { + for s in segments(adapter) { + tracing::info!( + id = s.id, + aperture = s.aperture, + limit_mb = s.limit >> 20, + resident_mb = s.resident >> 20, + "the card's memory segment as the graphics kernel counts it" + ); + } +} + +/// The share of an aperture segment's limit from which it counts as full +/// (`LEONIDA_SEGMENT_TIGHT`, in percent; 85 by default, 0: never). +static TIGHT_PERCENT: LazyLock = + LazyLock::new(|| std::env::var("LEONIDA_SEGMENT_TIGHT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(85)); + +/// How often the segments are looked at, at most. +const LOOK_MS: u64 = 100; + +/// Whether an aperture segment holds more than [`TIGHT_PERCENT`] of its +/// limit, as of the last look (one every [`LOOK_MS`], by +/// whichever thread asks first). Said in the log when it starts and stops. +pub(crate) fn tight(adapter: &IDXGIAdapter3) -> bool { + static TIGHT: AtomicBool = AtomicBool::new(false); + static LOOKED: AtomicU64 = AtomicU64::new(0); + static LOOKING: Mutex<()> = Mutex::new(()); + let percent = *TIGHT_PERCENT; + if percent == 0 { + return false; + } + let now = super::now_ms(); + if now >= LOOKED.load(Ordering::Relaxed) + LOOK_MS + && let Ok(_looking) = LOOKING.try_lock() + { + LOOKED.store(now, Ordering::Relaxed); + let fullest = segments(adapter) + .into_iter() + .filter(|s| s.aperture && s.limit > 0) + .max_by_key(|s| s.resident * 1000 / s.limit); + let tight = fullest.is_some_and(|s| s.resident * 100 > s.limit * percent); + if TIGHT.swap(tight, Ordering::Relaxed) != tight + && let Some(s) = fullest + { + tracing::info!( + tight, + segment = s.id, + resident_mb = s.resident >> 20, + limit_mb = s.limit >> 20, + "an aperture segment of the card's memory {} {}% of its limit: flights sent ahead {}", + if tight { "passed" } else { "fell below" }, + percent, + if tight { "land before host lists are made" } else { "go on as before" } + ); + } + } + TIGHT.load(Ordering::Relaxed) +} diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 4b6e058651..3f27c3b888 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -332,6 +332,12 @@ fn fresh_list() -> Option { } } +/// Whether a host list that ran waits for [`fresh_list`]. +#[cfg(windows)] +pub(crate) fn has_idle() -> bool { + !IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.is_empty() +} + /// The host sides of lists whose submission has run (submissions are /// waited for; `ran` names the ones it ran, by their place in `lists`): /// what they held is let go, as before, and the host lists are reset and From ff245ac6a04062806d3652b9596fd8f5d857cef0 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:55:42 +0000 Subject: [PATCH 3/9] Near the limit, every flight lands before the next is sent and idle host lists go Looking at the segment only when no host list was idle came too late: lists kept idle were already holding their command memory in the 2 GB aperture segment. Now tight is looked at on every send, and while it holds, list::trim_idle leaves 64 idle host lists and lets the rest go with their allocators. The threshold is 80 percent by default and has hysteresis: it stops being tight 10 points below (70 percent), because near the limit the video memory manager pages and the card waited a second a frame. The threshold decision is a pure function (is_tight) with unit tests, as is the trim's split. The trim is not counted in ALLOCATOR_TRIMS, which reports LEONIDA_ALLOCATOR_TRIM's own lets-go. After kyokyotosh/VIctory-6700XT e3c0703 (GPL-3.0), via PastiiJay/klbf-lab #127. AI-assisted. Not yet built or run on a GPU. --- d3d12/crates/leonida-gpu/src/host.rs | 10 ++- d3d12/crates/leonida-gpu/src/host/segments.rs | 87 +++++++++++++++++-- d3d12/crates/leonida-gpu/src/list.rs | 42 ++++++++- 3 files changed, 126 insertions(+), 13 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index f0d569d1c8..20aee94fac 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -6998,9 +6998,13 @@ impl Host { }; LATE_STATS[0].fetch_add(1, Ordering::Relaxed); RELAY_MOVED.notify_one(); - // An aperture segment near its limit with no idle host list: the - // flights land and give their lists back before more are made. - let tight = !crate::list::has_idle() && self.adapter.as_ref().is_some_and(segments::tight); + // An aperture segment near its limit: every flight lands before the + // next is sent, as without sending ahead, and idle host lists past a + // few go, their command memory with them ([`segments`]). + let tight = self.adapter.as_ref().is_some_and(segments::tight); + if tight { + crate::list::trim_idle(); + } if told && !late_writes() { self.settle(&mut submitted, WHY_WRITES); } else if sizes { diff --git a/d3d12/crates/leonida-gpu/src/host/segments.rs b/d3d12/crates/leonida-gpu/src/host/segments.rs index fe7106f5fa..17a6824a9a 100644 --- a/d3d12/crates/leonida-gpu/src/host/segments.rs +++ b/d3d12/crates/leonida-gpu/src/host/segments.rs @@ -11,7 +11,7 @@ //! nothing in the air, at some 1,270 host lists alive; VIctory-6700XT //! `FINDINGS-6700XT.md`, klbf-lab #127 on an RX 6800 XT). [`tight`] says //! when to let the flights land first. After kyokyotosh/VIctory-6700XT -//! 018d372 (GPL-3.0), via PastiiJay/klbf-lab #127. +//! 018d372 and e3c0703 (GPL-3.0), via PastiiJay/klbf-lab #127. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{LazyLock, Mutex}; @@ -79,15 +79,28 @@ pub(crate) fn log(adapter: &IDXGIAdapter3) { } /// The share of an aperture segment's limit from which it counts as full -/// (`LEONIDA_SEGMENT_TIGHT`, in percent; 85 by default, 0: never). +/// (`LEONIDA_SEGMENT_TIGHT`, in percent; 80 by default, 0: never). static TIGHT_PERCENT: LazyLock = - LazyLock::new(|| std::env::var("LEONIDA_SEGMENT_TIGHT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(85)); + LazyLock::new(|| std::env::var("LEONIDA_SEGMENT_TIGHT").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(80)); /// How often the segments are looked at, at most. const LOOK_MS: u64 = 100; +/// Whether a segment holding `resident` bytes of `limit` counts as full: +/// above `percent` of it, and, once it did, until below `percent` less 10 +/// points (near the limit the video memory manager pages, and the card +/// waited a second a frame). `percent` 0 and a `limit` of 0 (a segment the +/// kernel gave no size) are never full. +pub(crate) fn is_tight(resident: u64, limit: u64, percent: u64, was_tight: bool) -> bool { + if percent == 0 || limit == 0 { + return false; + } + let percent = if was_tight { percent.saturating_sub(10) } else { percent }; + u128::from(resident) * 100 > u128::from(limit) * u128::from(percent) +} + /// Whether an aperture segment holds more than [`TIGHT_PERCENT`] of its -/// limit, as of the last look (one every [`LOOK_MS`], by +/// limit ([`is_tight`]), as of the last look (one every [`LOOK_MS`], by /// whichever thread asks first). Said in the log when it starts and stops. pub(crate) fn tight(adapter: &IDXGIAdapter3) -> bool { static TIGHT: AtomicBool = AtomicBool::new(false); @@ -106,7 +119,8 @@ pub(crate) fn tight(adapter: &IDXGIAdapter3) -> bool { .into_iter() .filter(|s| s.aperture && s.limit > 0) .max_by_key(|s| s.resident * 1000 / s.limit); - let tight = fullest.is_some_and(|s| s.resident * 100 > s.limit * percent); + let was = TIGHT.load(Ordering::Relaxed); + let tight = fullest.is_some_and(|s| is_tight(s.resident, s.limit, percent, was)); if TIGHT.swap(tight, Ordering::Relaxed) != tight && let Some(s) = fullest { @@ -117,10 +131,69 @@ pub(crate) fn tight(adapter: &IDXGIAdapter3) -> bool { limit_mb = s.limit >> 20, "an aperture segment of the card's memory {} {}% of its limit: flights sent ahead {}", if tight { "passed" } else { "fell below" }, - percent, - if tight { "land before host lists are made" } else { "go on as before" } + if tight { percent } else { percent.saturating_sub(10) }, + if tight { "land as they are sent and idle host lists go" } else { "go on as before" } ); } } TIGHT.load(Ordering::Relaxed) } + +#[cfg(test)] +mod tests { + use super::is_tight; + + const GB: u64 = 1 << 30; + + #[test] + fn below_the_percent_is_not_tight() { + assert!(!is_tight(GB, 2 * GB, 80, false)); + assert!(!is_tight(0, 2 * GB, 80, false)); + } + + #[test] + fn above_the_percent_is_tight() { + assert!(is_tight(GB * 17 / 10, 2 * GB, 80, false)); + assert!(is_tight(2 * GB, 2 * GB, 80, true)); + // Exactly at the percent is not above it. + assert!(!is_tight(80, 100, 80, false)); + assert!(is_tight(81, 100, 80, false)); + } + + /// Between 70 and 80 percent a segment stays full once it was, and does + /// not become full from below. + #[test] + fn it_stays_tight_ten_points_below_the_percent() { + for resident in [71, 75, 80] { + assert!(is_tight(resident, 100, 80, true), "{resident}"); + assert!(!is_tight(resident, 100, 80, false) || resident > 80, "{resident}"); + } + assert!(!is_tight(70, 100, 80, true)); + assert!(!is_tight(50, 100, 80, true)); + } + + #[test] + fn percent_zero_is_never() { + assert!(!is_tight(2 * GB, 2 * GB, 0, false)); + assert!(!is_tight(2 * GB, 2 * GB, 0, true)); + } + + #[test] + fn a_limit_of_zero_is_never() { + assert!(!is_tight(GB, 0, 80, false)); + assert!(!is_tight(GB, 0, 80, true)); + assert!(!is_tight(0, 0, 80, true)); + } + + #[test] + fn a_percent_under_ten_does_not_wrap_when_it_was_tight() { + assert!(is_tight(1, 100, 5, true)); + assert!(!is_tight(0, 100, 5, true)); + } + + #[test] + fn huge_sizes_do_not_overflow() { + assert!(is_tight(u64::MAX, u64::MAX / 2, 80, false)); + assert!(!is_tight(u64::MAX / 4, u64::MAX, 80, false)); + } +} diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 3f27c3b888..28d5e58e7f 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -332,10 +332,34 @@ fn fresh_list() -> Option { } } -/// Whether a host list that ran waits for [`fresh_list`]. +/// Host lists kept idle while an aperture segment of the card's memory is near its limit +/// (`crate::host::segments`). #[cfg(windows)] -pub(crate) fn has_idle() -> bool { - !IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.is_empty() +const IDLE_WHEN_TIGHT: usize = 64; + +/// What is past the first `keep` of `pool`, taken out (the pools are last in, first out: the oldest are first). +#[cfg(any(windows, test))] +pub(crate) fn past_first(pool: &mut Vec, keep: usize) -> Vec { + pool.split_off(keep.min(pool.len())) +} + +/// Lets idle host lists past [`IDLE_WHEN_TIGHT`] go, and their allocators' command memory with them: on an RX 6700 XT +/// that memory lies in a 2 GB aperture segment (VIctory-6700XT `FINDINGS-6700XT.md`). They have run and been reset. +/// Not counted in `ALLOCATOR_TRIMS`, which is `LEONIDA_ALLOCATOR_TRIM`'s. After kyokyotosh/VIctory-6700XT e3c0703 +/// (GPL-3.0), via PastiiJay/klbf-lab #127. +#[cfg(windows)] +pub(crate) fn trim_idle() { + let gone: Vec = { + let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner()); + if idle.0.len() <= IDLE_WHEN_TIGHT { + return; + } + let gone = past_first(&mut idle.0, IDLE_WHEN_TIGHT); + idle.1 -= gone.iter().map(|Idle(_, bytes, _)| bytes).sum::(); + gone + }; + // (Outside the lock: freeing lists takes the graphics kernel's time.) + drop(gone); } /// The host sides of lists whose submission has run (submissions are @@ -2979,6 +3003,18 @@ mod tests { Shape { format, width: u64::from(side), height: side, depth_or_array: 1, levels, volume: false } } + /// What a tight segment's trim lets go is what is past the first `keep`, and a pool with fewer loses nothing. + #[test] + fn a_trim_keeps_the_first_and_takes_the_rest() { + let mut pool = vec![1, 2, 3, 4, 5]; + assert_eq!(past_first(&mut pool, 2), [3, 4, 5]); + assert_eq!(pool, [1, 2]); + assert!(past_first(&mut pool, 2).is_empty()); + assert!(past_first(&mut pool, 9).is_empty()); + assert_eq!(past_first(&mut pool, 0), [1, 2]); + assert!(pool.is_empty()); + } + /// (`LEONIDA_ALLOCATOR_TRIM`) The idle lists let go are the oldest put /// by, those older than the trim's time; the pool is in that order. #[test] From 423406cdc8d38620723be00aeccf98fefa1370c3 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:56:25 +0000 Subject: [PATCH 4/9] Preludes go back to a pool when their list resets, instead of living as long as the list Every host list that ever needed texture transitions kept a prelude (a second allocator and command list) for its whole life, even while idle. On an RX 6700 XT that was 952 preludes for 1,476 host lists, near 1 GB of the 2 GB aperture segment whose filling loses the device (VIctory-6700XT FINDINGS-6700XT.md); klbf-lab #127 reports the same on an RX 6800 XT. HostList::prelude is now a Mutex>: the list takes one from PRELUDES the first time it is submitted with transitions (take_prelude) and HostList::reset, which only runs once the submissions have finished, gives it back (give_prelude). At most 128 stay idle, and trim_preludes cuts them to 16 while the aperture segment is tight, next to trim_idle. The pool keeps each allocator's creation instant, so LEONIDA_ALLOCATOR_TRIM's refresh of preludes (allocator_refresh with which = 1) sees the real age. LEONIDA_LAZY_PRELUDE=0 still makes one with the list. The preludes-made counter now counts real creations, not first uses. After kyokyotosh/VIctory-6700XT 63a773e (GPL-3.0), via PastiiJay/klbf-lab #127. AI-assisted. Not yet built or run on a GPU. --- d3d12/crates/leonida-gpu/src/host.rs | 77 ++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 20aee94fac..ef71cbee78 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1120,8 +1120,8 @@ pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync:: pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; /// About host lists, for the memory line: lists made by the host since the -/// start; preludes made (a list's second allocator and list, made when it -/// first needs one, [`lazy_prelude`]); and, in diagnostics builds, the +/// start; preludes made (a second allocator and list, made when a list +/// first needs one and none is idle, [`lazy_prelude`], [`PRELUDES`]); and, in diagnostics builds, the /// bytes the process's private memory grew by while lists were being made /// (what a list costs: host objects with the driver's command memory; 631 /// lists were alive in run 65, each with a prelude it may never use). @@ -1603,9 +1603,10 @@ pub(crate) struct HostList { /// What the list does with depth textures that have a colour twin, by /// twin ([`TwinUse`]). twins: Mutex>, - /// The list that runs those transitions just before this one, made - /// when the list first has such transitions ([`lazy_prelude`]). - prelude: OnceLock>, + /// The list that runs those transitions just before this one, taken + /// when the list is first submitted with such transitions and given + /// back at its reset ([`take_prelude`], [`lazy_prelude`]). + prelude: Mutex>, /// The pipelines the list binds, for reports of slow submissions. pipelines: std::sync::Arc>>, /// What its indirect executions ran, for the report of a removed device. @@ -1682,12 +1683,55 @@ fn list_prelude((allocator, list): Prelude) -> ListPrelude { (Mutex::new((allocator, now_ms())), list) } +/// A prelude in [`PRELUDES`]. +struct IdlePrelude(ListPrelude); + +// SAFETY: D3D12 objects (free-threaded), touched by nobody while idle. +unsafe impl Send for IdlePrelude {} + +/// Preludes of host lists that ran ([`HostList::reset`]), for the next list +/// that needs one, with the instant each allocator was made (the trim of +/// `LEONIDA_ALLOCATOR_TRIM` goes by it). Kept by its list for the list's +/// life, a prelude held its allocator's command memory while the list sat +/// idle or recorded: 952 for 1,476 host lists, near 1 GB of a 2 GB aperture +/// segment on an RX 6700 XT (VIctory-6700XT `FINDINGS-6700XT.md`), where +/// only lists being submitted or in the air need one. After +/// kyokyotosh/VIctory-6700XT 63a773e (GPL-3.0), via PastiiJay/klbf-lab #127. +static PRELUDES: Mutex> = Mutex::new(Vec::new()); + +/// The most preludes kept idle, and while an aperture segment of the card's +/// memory is near its limit ([`trim_preludes`]). +const PRELUDES_MOST: (usize, usize) = (128, 16); + +/// A prelude for a list about to be submitted: an idle one, or a new one. +fn take_prelude() -> Option { + let idle = PRELUDES.lock().unwrap_or_else(|e| e.into_inner()).pop(); + idle.map(|IdlePrelude(prelude)| prelude).or_else(|| host().and_then(|h| h.make_prelude()).map(list_prelude)) +} + +/// Keeps `prelude`, whose submission has finished, for [`take_prelude`]. +fn give_prelude(prelude: ListPrelude) { + let mut idle = PRELUDES.lock().unwrap_or_else(|e| e.into_inner()); + if idle.len() < PRELUDES_MOST.0 { + idle.push(IdlePrelude(prelude)); + } +} + +/// Lets idle preludes past [`PRELUDES_MOST`]'s second number go, and their +/// command memory with them. +pub(crate) fn trim_preludes() { + let gone: Vec = crate::list::past_first(&mut PRELUDES.lock().unwrap_or_else(|e| e.into_inner()), PRELUDES_MOST.1); + // (Outside the lock: freeing lists takes the graphics kernel's time.) + drop(gone); +} + /// Whether a host list's prelude is made when the list first needs one. A /// prelude runs the texture transitions and twin copies a list needs before /// it; lists that name no texture never have one, and every host list was /// made with one all the same: twice the host objects per list, for the /// title's 630 lists and for every list made anew. -/// `LEONIDA_LAZY_PRELUDE=0`: made with the list, as before. +/// `LEONIDA_LAZY_PRELUDE=0`: made with the list, as before (it goes back to +/// [`PRELUDES`] at the list's first reset like any other). fn lazy_prelude() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("LEONIDA_LAZY_PRELUDE").is_none_or(|v| v != "0")) @@ -5779,10 +5823,7 @@ impl Host { &allocator, None, )?; - let prelude = OnceLock::new(); - if !lazy_prelude() { - let _ = prelude.set(self.make_prelude().map(list_prelude)); - } + let prelude = Mutex::new(if lazy_prelude() { None } else { self.make_prelude().map(list_prelude) }); #[cfg(feature = "diagnostics")] let notes = std::sync::Arc::>>::default(); let pipelines = std::sync::Arc::>>::default(); @@ -7004,6 +7045,7 @@ impl Host { let tight = self.adapter.as_ref().is_some_and(segments::tight); if tight { crate::list::trim_idle(); + trim_preludes(); } if told && !late_writes() { self.settle(&mut submitted, WHY_WRITES); @@ -8427,6 +8469,11 @@ impl HostList { let started = std::time::Instant::now(); let _resetting = crate::timeline::span("resetting a host list"); self._alive.used(); + // Every submission of the list has run, its prelude's too. + let prelude = self.prelude.lock().unwrap_or_else(|e| e.into_inner()).take(); + if let Some(prelude) = prelude { + give_prelude(prelude); + } self.hudless.store(0, Ordering::Relaxed); *self.gbuffer.lock().unwrap_or_else(|e| e.into_inner()) = None; self.gate.store(0, Ordering::Relaxed); @@ -8894,11 +8941,11 @@ impl HostList { if barriers.is_empty() && syncs.is_empty() && uploads.is_empty() { return None; } - let Some((allocator, list)) = self - .prelude - .get_or_init(|| host().and_then(|h| h.make_prelude()).map(list_prelude)) - .as_ref() - else { + let mut held = self.prelude.lock().unwrap_or_else(|e| e.into_inner()); + if held.is_none() { + *held = take_prelude(); + } + let Some((allocator, list)) = held.as_ref() else { fail(format_args!("no host list for a state prelude")); }; let mut allocator = allocator.lock().unwrap_or_else(|e| e.into_inner()); From 633da79a0d35e8763406025ffc41c7a904c4a0a7 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Sun, 29 Nov 2026 23:56:40 +0000 Subject: [PATCH 5/9] Document LEONIDA_SEGMENT_TIGHT and the RDNA2 aperture-segment fix in the d3d12 README The device loss on RDNA2 cards in the first heavy scene had no mention anywhere a user would look for a switch to turn the new behaviour off or tune it. AI-assisted. --- d3d12/docs/README-fxceless.md | 1 + 1 file changed, 1 insertion(+) diff --git a/d3d12/docs/README-fxceless.md b/d3d12/docs/README-fxceless.md index bca384781e..370681f095 100644 --- a/d3d12/docs/README-fxceless.md +++ b/d3d12/docs/README-fxceless.md @@ -133,6 +133,7 @@ Speed and memory: - Waits for memory values, write-watch queries and page queries no longer walk page tables per call. - Large title buffers get a copy in card memory, with shader writes found by hashing on the card. - Submissions can be sent ahead of the wait for the card (`LEONIDA_LATE_WAIT`), with a relay thread that lands results as the card finishes (`LEONIDA_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. +- On RDNA2 cards the driver's command buffers fill a 2 GB system-memory (aperture) segment that DXGI's budgets leave out, and the device was lost in the first heavy scene with about 1,270 host lists alive (RX 6800 XT, klbf-lab #127). Landed flights now give their host lists back at once, preludes are pooled, and the segment is read with `D3DKMTQueryStatistics`: above `LEONIDA_SEGMENT_TIGHT` percent (80 by default, `0` never; it stays tight until 10 points below) every flight lands before the next is sent and idle host lists and preludes are let go. - Independent host-copy refreshes run in parallel by default on systems with at least four logical CPUs (`LEONIDA_WIDE_REFRESH=0` disables this; `=1` forces it). This targets the serial memory reads that previously cost about 45–50 ms per frame on the test run. - Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`LEONIDA_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). - The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. From 75b32686530a68f7f175fae0395d2d1b82885794 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:20:52 +0000 Subject: [PATCH 6/9] Say where the RDNA2 aperture-segment losses were measured: here on an RX 6800 XT, klbf-lab #127 on an RX 6900 XT The doc comments put klbf-lab #127 on an RX 6800 XT; it measured an RX 6900 XT, and the 1,270 host lists alive at the loss are this tree's own run (relay 2, 2026-11-29). --- d3d12/crates/leonida-gpu/src/host/segments.rs | 5 +++-- d3d12/crates/leonida-gpu/src/list.rs | 4 ++-- d3d12/docs/README-fxceless.md | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host/segments.rs b/d3d12/crates/leonida-gpu/src/host/segments.rs index 17a6824a9a..54e4033719 100644 --- a/d3d12/crates/leonida-gpu/src/host/segments.rs +++ b/d3d12/crates/leonida-gpu/src/host/segments.rs @@ -8,8 +8,9 @@ //! made lists faster than flights gave them back during the first world //! load; the segment ran full, the video memory manager could not make a //! new command list resident, and the device was removed (0x887A0007, with -//! nothing in the air, at some 1,270 host lists alive; VIctory-6700XT -//! `FINDINGS-6700XT.md`, klbf-lab #127 on an RX 6800 XT). [`tight`] says +//! nothing in the air; VIctory-6700XT `FINDINGS-6700XT.md`, klbf-lab #127 +//! on an RX 6900 XT; here on an RX 6800 XT, with some 1,270 host lists +//! alive at the loss, relay 2, 2026-11-29). [`tight`] says //! when to let the flights land first. After kyokyotosh/VIctory-6700XT //! 018d372 and e3c0703 (GPL-3.0), via PastiiJay/klbf-lab #127. diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 28d5e58e7f..2ddaccb567 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -390,8 +390,8 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { /// Held in the line of landed flights for that lag instead, 64 flights of lists (some 700 at the first world load) /// kept their allocators' command memory, and lists for new recordings were made meanwhile: on an RX 6700 XT in a /// 32 GB PC the driver's 2 GB aperture segment for that memory ran full and the device was removed (0x887A0007, -/// nothing in the air; VIctory-6700XT `FINDINGS-6700XT.md`). Not measured here on an RX 6800 XT, which klbf-lab #127 -/// reports the same way. +/// nothing in the air; VIctory-6700XT `FINDINGS-6700XT.md`). The same loss here on an RX 6800 XT (relay 2, some 1,270 +/// host lists alive, 2026-11-29) and in klbf-lab #127 on an RX 6900 XT. #[cfg(windows)] pub(crate) fn recycle_landed(lists: Vec, ran: &[usize]) { let hosts = lists.into_iter().map(|Detached { host, _uploads, _state }| { diff --git a/d3d12/docs/README-fxceless.md b/d3d12/docs/README-fxceless.md index 370681f095..e422ba1e4e 100644 --- a/d3d12/docs/README-fxceless.md +++ b/d3d12/docs/README-fxceless.md @@ -133,7 +133,7 @@ Speed and memory: - Waits for memory values, write-watch queries and page queries no longer walk page tables per call. - Large title buffers get a copy in card memory, with shader writes found by hashing on the card. - Submissions can be sent ahead of the wait for the card (`LEONIDA_LATE_WAIT`), with a relay thread that lands results as the card finishes (`LEONIDA_RELAY`): in a first five-minute run the card's idle time behind the submitting thread fell from about 136 to 30 ms per frame. -- On RDNA2 cards the driver's command buffers fill a 2 GB system-memory (aperture) segment that DXGI's budgets leave out, and the device was lost in the first heavy scene with about 1,270 host lists alive (RX 6800 XT, klbf-lab #127). Landed flights now give their host lists back at once, preludes are pooled, and the segment is read with `D3DKMTQueryStatistics`: above `LEONIDA_SEGMENT_TIGHT` percent (80 by default, `0` never; it stays tight until 10 points below) every flight lands before the next is sent and idle host lists and preludes are let go. +- On RDNA2 cards the driver's command buffers fill a 2 GB system-memory (aperture) segment that DXGI's budgets leave out, and the device was lost in the first heavy scene with about 1,270 host lists alive (RX 6800 XT, relay 2; the same loss as klbf-lab #127 on an RX 6900 XT). Landed flights now give their host lists back at once, preludes are pooled, and the segment is read with `D3DKMTQueryStatistics`: above `LEONIDA_SEGMENT_TIGHT` percent (80 by default, `0` never; it stays tight until 10 points below) every flight lands before the next is sent and idle host lists and preludes are let go. - Independent host-copy refreshes run in parallel by default on systems with at least four logical CPUs (`LEONIDA_WIDE_REFRESH=0` disables this; `=1` forces it). This targets the serial memory reads that previously cost about 45–50 ms per frame on the test run. - Title memory can be opened as a graphics heap so that buffers are used in place instead of copied (`LEONIDA_INPLACE`, first stage only; a probe confirmed the approach on the test GPU). - The bindless texture queue no longer uploads stale views; the view table no longer grows without bound; the pipeline library is mapped instead of read into memory. From 1462e3e8d2ff3522ba6dca5dbce20ae232b072a5 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Mon, 30 Nov 2026 01:10:33 +0000 Subject: [PATCH 7/9] On RX 6000 cards the launcher no longer turns the relay copy on: the light went black On an RX 6800 XT with relay 2 and the launcher's default settings the lighting rose and fell with where the camera looked and ended black (the automatic exposure seems to read a late value). The same build and place with LEONIDA_RELAY_COPY=0: the light right at 17 to 20 fps (relay 0 is right too, at 8 fps). Measured 2026-11-30 on that card only. play-nvidia.ps1 now drops LEONIDA_RELAY_COPY from its defaults when the card name matches Radeon RX 6000; the card name is read once and shared with the frame generation check. -More @{LEONIDA_RELAY_COPY='1'} is applied after and still wins. AI-assisted. --- d3d12/scripts/play-nvidia.ps1 | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 28543ca199..82cdd8b49f 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -351,12 +351,12 @@ if ($Resolution -or $Lowest) { if ($Dlss -and -not $dlssOn) { Write-Host "-Dlss ${Dlss}: no DLSS here (its files, or a build with it): the title's picture is not made by DLSS." } if ($FrameGen) { $settings.LEONIDA_FRAME_GEN = "$FrameGen" } if ($FsrFrameGen) { $settings.LEONIDA_FSR_FRAMEGEN = '1' } +$card = try { (Get-CimInstance Win32_VideoController -ErrorAction Stop | ForEach-Object { $_.Name }) -join ';' } catch { '' } # Leonida: DLSS frame generation twice the frames shown by default on cards that make it (RTX 40 and 50) when its # Streamline files are here and the title upscales by itself (-Resolution: its depth and motion vectors are the # G-buffer pass's, fg.rs). Series X at -Resolution 1080 on an RTX 4060 Ti (2026-11-28): 15 frames rendered, 29 # shown. It generates only while the game's window has the focus. -NoFrameGen leaves it off (Smooth Motion then). if (-not $FrameGen -and -not $NoFrameGen -and ($Resolution -or $Lowest) -and -not $RayTracing -and $StreamlineDir) { - $card = try { (Get-CimInstance Win32_VideoController -ErrorAction Stop | ForEach-Object { $_.Name }) -join ';' } catch { '' } if ($card -match 'RTX\s*(40|50)\d\d') { $settings.LEONIDA_FRAME_GEN = '2' # Reflex holds the frames shown to 28 a second (14 rendered, 71.4 ms apart), so that the made frames fall @@ -372,6 +372,11 @@ if (-not $FrameGen -and -not $NoFrameGen -and ($Resolution -or $Lowest) -and -no $settings.LEONIDA_FG_LIMIT_FPS = '28' } } +# Leonida: no relay copy on Radeon RX 6000 (RDNA2). RX 6800 XT, relay 2 (2026-11-30): with LEONIDA_RELAY_COPY=1 the +# light rose and fell with where the camera looked and went black (the automatic exposure reading a late value); the +# same build and place with it at 0: the light right, 17 to 20 fps (relay 0: right too, 8 fps). Only that card is +# measured. -More @{LEONIDA_RELAY_COPY='1'} puts it back. +if ($card -match 'RX\s*6\d\d\d') { $settings.Remove('LEONIDA_RELAY_COPY') } if ($Aspect) { $settings.LEONIDA_ASPECT = $Aspect } if ($PresentScale) { $settings.LEONIDA_PRESENT_SCALE = $PresentScale } if ($StreamlineDir) { $settings.LEONIDA_STREAMLINE_DIR = $StreamlineDir } From 077d6084cc481cea2e67e5e54f70dd2707049438 Mon Sep 17 00:00:00 2001 From: amujark <362839617+amujark@users.noreply.github.com> Date: Mon, 30 Nov 2026 09:11:32 +0100 Subject: [PATCH 8/9] A PC with an NVIDIA and an RX 6000 card lost the relay copy on the NVIDIA: the card it plays on decides now --- d3d12/README.md | 3 ++ d3d12/crates/leonida-gpu/src/host.rs | 65 +++++++++++++++++++++-- d3d12/crates/leonida-gpu/src/host/menu.rs | 2 +- d3d12/scripts/play-nvidia.ps1 | 13 ++--- d3d12/scripts/play.ps1 | 2 +- 5 files changed, 74 insertions(+), 11 deletions(-) diff --git a/d3d12/README.md b/d3d12/README.md index abc7de93ac..1c37ce5a27 100644 --- a/d3d12/README.md +++ b/d3d12/README.md @@ -263,6 +263,9 @@ Also in, off by default: every 2D target. - `LEONIDA_ADAPTER=` (`host.rs`): the card to run on when there is more than one (`play-nvidia.ps1 -Adapter`). +- `LEONIDA_RELAY_COPY=0|1|auto` (`host.rs`): whether the relay's fetches come + over the card's copy queue. `auto` (the launchers' default) is on except on + Radeon RX 6000 cards, judged by the card the device is made on. --- diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index ef71cbee78..5a6eb2caa5 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1337,6 +1337,11 @@ fn create() -> windows::core::Result { .ok(); if let Some(adapter) = adapter.as_ref() { segments::log(adapter); + if let Ok(desc) = adapter.cast::().and_then(|a| a.GetDesc1()) { + let len = desc.Description.iter().position(|&c| c == 0).unwrap_or(desc.Description.len()); + let name = String::from_utf16_lossy(&desc.Description[..len]); + let _ = HOST_RX6000.set(rx6000(desc.VendorId, &name)); + } } tracing::info!("host D3D12 device ready"); Ok(Host { @@ -1438,6 +1443,23 @@ pub(crate) fn warp_adapter() -> windows::core::Result { #[cfg(test)] mod tests { + #[test] + fn rx6000_is_amd_and_rx_then_6_and_three_digits() { + for (vendor, name, want) in [ + (0x1002, "AMD Radeon RX 6800 XT", true), + (0x1002, "AMD Radeon RX 6700M", true), + (0x1002, "AMD Radeon RX6600", true), + (0x1002, "AMD Radeon RX 7900 XTX", false), + (0x1002, "AMD Radeon(TM) Graphics", false), + (0x1002, "AMD Radeon RX 580", false), + (0x10de, "NVIDIA GeForce RTX 4070 SUPER", false), + (0x10de, "RX 6800", false), + (0x1414, "Microsoft Basic Render Driver", false), + ] { + assert_eq!(super::rx6000(vendor, name), want, "{name}"); + } + } + /// A list of ours is found by its name, with the debug layer's note or not. #[cfg(feature = "diagnostics")] #[test] @@ -3668,9 +3690,34 @@ fn relay_exact() -> bool { *ON.get_or_init(|| relay() && std::env::var_os("LEONIDA_RELAY").is_none_or(|v| v == "2")) } +/// Whether the card the host's device was made on is a Radeon RX 6000 +/// (RDNA2), set when the first [`Host`] is made. Unset: the card is not known. +static HOST_RX6000: OnceLock = OnceLock::new(); + +/// A Radeon RX 6000 by its adapter description: AMD's vendor id and `RX`, +/// optional spaces, `6` and three digits in the name ("RX 6800 XT", "RX6600"). +fn rx6000(vendor: u32, name: &str) -> bool { + if vendor != 0x1002 { + return false; + } + let name = name.to_ascii_uppercase(); + let bytes = name.as_bytes(); + name.match_indices("RX").any(|(at, _)| { + let rest = &bytes[at + 2..]; + let digits = &rest[rest.iter().take_while(|b| b.is_ascii_whitespace()).count()..]; + digits.len() >= 4 && digits[0] == b'6' && digits[1..4].iter().all(u8::is_ascii_digit) + }) +} + /// Whether the pieces the relay fetches from the card's memory come over the -/// card's copy queue (`LEONIDA_RELAY_COPY=1`) and not over the queue that -/// draws. +/// card's copy queue and not over the queue that draws. `LEONIDA_RELAY_COPY`: +/// `1` on, `auto` on unless the host's card is a Radeon RX 6000 (on if the +/// card is not known), anything else or unset off. +/// +/// RX 6000 is off under `auto` because of what an RX 6800 XT showed at relay +/// 2 (2026-11-30): with the copy queue the light rose and fell with where +/// the camera looked and went black; the same build and place at 0 had the +/// light right. /// /// On the drawing queue a fetch runs behind whatever was sent meanwhile, /// and with the relay that is most of a frame: the thread that lands flights @@ -3686,7 +3733,19 @@ fn relay_exact() -> bool { /// may be in what is fetched, as before. fn relay_copy() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("LEONIDA_RELAY_COPY").is_some_and(|v| v == "1")) + *ON.get_or_init(|| match std::env::var_os("LEONIDA_RELAY_COPY") { + Some(v) if v == "1" => true, + Some(v) if v == "auto" => { + let rx6000 = HOST_RX6000.get().copied().unwrap_or(false); + tracing::info!( + rx6000, + "LEONIDA_RELAY_COPY=auto: relay copy queue {}", + if rx6000 { "off, the host's card is a Radeon RX 6000" } else { "on, the host's card is not a Radeon RX 6000" } + ); + !rx6000 + } + _ => false, + }) } /// Told when something joins [`LINE`], for the thread that lands flights diff --git a/d3d12/crates/leonida-gpu/src/host/menu.rs b/d3d12/crates/leonida-gpu/src/host/menu.rs index 0abafbb91a..b1e855c053 100644 --- a/d3d12/crates/leonida-gpu/src/host/menu.rs +++ b/d3d12/crates/leonida-gpu/src/host/menu.rs @@ -77,7 +77,7 @@ const ITEMS: &[Item] = &[ Item { var: "LEONIDA_ADAPTER", label: "GRAPHICS CARD", values: &[("", "WINDOWS DEFAULT"), ("#0", "CARD 0"), ("#1", "CARD 1"), ("#2", "CARD 2")], live: false }, Item { var: "LEONIDA_PANEL", label: "STATS PANEL (F3)", values: UNSET_ON, live: true }, Item { var: "LEONIDA_RELAY", label: "RELAY (SPEED, TRIANGLES)", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, - Item { var: "LEONIDA_RELAY_COPY", label: "RELAY COPY QUEUE", values: OFF_ON, live: false }, + Item { var: "LEONIDA_RELAY_COPY", label: "RELAY COPY QUEUE", values: &[("0", "OFF"), ("1", "ON"), ("auto", "BY CARD (RX 6000 OFF)")], live: false }, Item { var: "LEONIDA_FETCH_CHECK", label: "FETCH CHECK", values: OFF_ON, live: false }, Item { var: "LEONIDA_WIDE_BACK", label: "WIDE COPY BACK", values: OFF_ON, live: false }, Item { var: "LEONIDA_CARD_STEPS", label: "CARD STEPS", values: &[("2", "2"), ("1", "1"), ("0", "0 OFF")], live: false }, diff --git a/d3d12/scripts/play-nvidia.ps1 b/d3d12/scripts/play-nvidia.ps1 index 82cdd8b49f..85221d7d77 100644 --- a/d3d12/scripts/play-nvidia.ps1 +++ b/d3d12/scripts/play-nvidia.ps1 @@ -139,7 +139,13 @@ $settings = @{ # The play set. Textures are waited for: one loaded once at the start could stay empty for the run otherwise. LEONIDA_TEXTURE_NO_WAIT = '0'; LEONIDA_RELAY = '2'; LEONIDA_CARD_STEPS = '2' LEONIDA_WIDE_BACK = '1'; LEONIDA_CARD_REHASH_RUNS = '1' - LEONIDA_JOIN_COPIES = '1'; LEONIDA_INDIRECT_WINDOW = '1'; LEONIDA_RELAY_COPY = '1' + LEONIDA_JOIN_COPIES = '1'; LEONIDA_INDIRECT_WINDOW = '1' + # Leonida: the relay copy queue is on except on Radeon RX 6000 (RDNA2); the layer decides by the card it makes its + # device on (host.rs relay_copy), so -Adapter, LEONIDA_ADAPTER and the F1 menu's card count. RX 6800 XT, relay 2 + # (2026-11-30): with it the light rose and fell with where the camera looked and went black (the automatic + # exposure reading a late value); the same build and place with it at 0: the light right, 17 to 20 fps (relay 0: + # right too, 8 fps). Only that card is measured. -More @{LEONIDA_RELAY_COPY='1'} forces it on, '0' off. + LEONIDA_RELAY_COPY = 'auto' # Copy-backs caught half-written are fetched again (torn.rs). LEONIDA_FETCH_CHECK = '1' # Leonida: an indirect batch stays open past a program only if all it can store goes through views its bind @@ -372,11 +378,6 @@ if (-not $FrameGen -and -not $NoFrameGen -and ($Resolution -or $Lowest) -and -no $settings.LEONIDA_FG_LIMIT_FPS = '28' } } -# Leonida: no relay copy on Radeon RX 6000 (RDNA2). RX 6800 XT, relay 2 (2026-11-30): with LEONIDA_RELAY_COPY=1 the -# light rose and fell with where the camera looked and went black (the automatic exposure reading a late value); the -# same build and place with it at 0: the light right, 17 to 20 fps (relay 0: right too, 8 fps). Only that card is -# measured. -More @{LEONIDA_RELAY_COPY='1'} puts it back. -if ($card -match 'RX\s*6\d\d\d') { $settings.Remove('LEONIDA_RELAY_COPY') } if ($Aspect) { $settings.LEONIDA_ASPECT = $Aspect } if ($PresentScale) { $settings.LEONIDA_PRESENT_SCALE = $PresentScale } if ($StreamlineDir) { $settings.LEONIDA_STREAMLINE_DIR = $StreamlineDir } diff --git a/d3d12/scripts/play.ps1 b/d3d12/scripts/play.ps1 index 7e5ef3f55e..8f09d9a08a 100644 --- a/d3d12/scripts/play.ps1 +++ b/d3d12/scripts/play.ps1 @@ -14,7 +14,7 @@ param( ) $settings = @{ LEONIDA_TEXTURE_NO_WAIT = '1'; LEONIDA_RELAY = '2'; LEONIDA_WIDE_BACK = '1'; LEONIDA_CARD_REHASH_RUNS = '1' - LEONIDA_JOIN_COPIES = '1'; LEONIDA_INDIRECT_WINDOW = '1'; LEONIDA_RELAY_COPY = '1'; LEONIDA_CARD_STEPS = '2' + LEONIDA_JOIN_COPIES = '1'; LEONIDA_INDIRECT_WINDOW = '1'; LEONIDA_RELAY_COPY = 'auto'; LEONIDA_CARD_STEPS = '2' LEONIDA_INDIRECT_BATCH = '2'; LEONIDA_MAP_THREADS = '1'; LEONIDA_TITLE_PRIORITIES = '0'; LEONIDA_CARD_AWAKE = '1' LEONIDA_SHOW_AFTER = '1'; LEONIDA_AMBIENT = '0.8'; LEONIDA_D3D12_DRED = 'light'; LEONIDA_SKIP_PIPELINES = 'none' } From aace3e26406f6dbe0998019d4eae54f1e6182beb Mon Sep 17 00:00:00 2001 From: amujark Date: Mon, 30 Nov 2026 19:51:42 +0000 Subject: [PATCH 9/9] The title and every submission stood still for 150-260 ms whenever the card's memory neared its limit, while the submitting thread freed 448 idle lists and 112 preludes; now a thread of its own frees them (LEONIDA_TRIM_ASYNC=0: as before) --- d3d12/crates/leonida-gpu/src/host.rs | 119 ++++++++++++++++++++++++++- d3d12/crates/leonida-gpu/src/list.rs | 4 +- 2 files changed, 118 insertions(+), 5 deletions(-) diff --git a/d3d12/crates/leonida-gpu/src/host.rs b/d3d12/crates/leonida-gpu/src/host.rs index 5a6eb2caa5..0d1c9f2107 100644 --- a/d3d12/crates/leonida-gpu/src/host.rs +++ b/d3d12/crates/leonida-gpu/src/host.rs @@ -1740,11 +1740,93 @@ fn give_prelude(prelude: ListPrelude) { } /// Lets idle preludes past [`PRELUDES_MOST`]'s second number go, and their -/// command memory with them. +/// command memory with them: taken out here, under the lock, and freed by +/// [`let_go_apart`]. pub(crate) fn trim_preludes() { let gone: Vec = crate::list::past_first(&mut PRELUDES.lock().unwrap_or_else(|e| e.into_inner()), PRELUDES_MOST.1); - // (Outside the lock: freeing lists takes the graphics kernel's time.) - drop(gone); + let_go_apart(gone); +} + +/// Since the last frame line: the microseconds spent freeing what a trim took +/// out ([`let_go_apart`]) and the objects freed, on `leonida-trim` or inline. +#[cfg(feature = "diagnostics")] +static TRIM_FREED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; + +/// Whether what a trim takes out is freed on a thread of its own +/// (`LEONIDA_TRIM_ASYNC=0`: by the thread that trims, as before). Diagnostics +/// builds: on and off while the title runs (`crate::ab`). +fn trim_async() -> bool { + crate::toggled!("LEONIDA_TRIM_ASYNC") +} + +/// Frees `gone`, what a trim ([`crate::list::trim_idle`], [`trim_preludes`]) +/// took out of its pool, outside the pool's lock and, unless +/// `LEONIDA_TRIM_ASYNC=0`, on a thread of its own, `leonida-trim`. Freeing a +/// host list is the graphics kernel's time (some 0.2 ms a list), and some 448 +/// lists and 112 preludes freed by the submitting thread held the line of +/// submissions and the title's present for 153 and 262 ms at a trim (two +/// captures, RX 6800 XT, 2026-11-30). The memory is still freed at once, by a +/// thread that does nothing else (not the reaper of [`retire`], which sits +/// behind other work). Where that thread cannot be made or the send fails, +/// `gone` is freed here. +pub(crate) fn let_go_apart(gone: Vec) { + type Gone = (Box, usize); + if gone.is_empty() { + return; + } + let count = gone.len(); + let gone: Gone = (Box::new(gone), count); + static TRIMMER: OnceLock>> = OnceLock::new(); + let free = |(gone, _count): Gone| { + #[cfg(feature = "diagnostics")] + let began = std::time::Instant::now(); + drop(gone); + #[cfg(feature = "diagnostics")] + { + TRIM_FREED[0].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed); + TRIM_FREED[1].fetch_add(_count as u64, Ordering::Relaxed); + } + }; + let gone = if trim_async() { + let sender = TRIMMER.get_or_init(|| { + let (tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("leonida-trim".into()) + .spawn(move || { + crate::cores::keep_helper_on_fast_cores("leonida-trim"); + for gone in rx { + let _freeing = crate::timeline::span("trim: idle lists and preludes freed"); + free(gone); + } + }) + .ok() + .map(|_| tx) + }); + match sender { + Some(tx) => match tx.send(gone) { + Ok(()) => return, + Err(std::sync::mpsc::SendError(gone)) => gone, + }, + None => gone, + } + } else { + gone + }; + free(gone); +} + +/// The trim's line of the frame lines, per frame ([`TRIM_FREED`]). +#[cfg(feature = "diagnostics")] +fn trim_line(frames: f64) { + let n: Vec = TRIM_FREED.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + if n[1] == 0.0 { + return; + } + tracing::info!( + "trim of an aperture segment per frame (LEONIDA_TRIM_ASYNC): {:.2} ms freeing {:.1} idle lists and preludes", + n[0] / 1000.0, + n[1] + ); } /// Whether a host list's prelude is made when the list first needs one. A @@ -5409,6 +5491,8 @@ fn late_line(frames: f64) { #[cfg(feature = "diagnostics")] retire_waits_line(frames); #[cfg(feature = "diagnostics")] + trim_line(frames); + #[cfg(feature = "diagnostics")] buffers_made::line(); #[cfg(feature = "diagnostics")] crate::residency::line(); @@ -7100,7 +7184,9 @@ impl Host { RELAY_MOVED.notify_one(); // An aperture segment near its limit: every flight lands before the // next is sent, as without sending ahead, and idle host lists past a - // few go, their command memory with them ([`segments`]). + // few go, their command memory with them ([`segments`]). They are + // taken out here and freed on `leonida-trim` ([`let_go_apart`]), so + // that the line does not stand behind the graphics kernel. let tight = self.adapter.as_ref().is_some_and(segments::tight); if tight { crate::list::trim_idle(); @@ -14778,3 +14864,28 @@ mod gate_tests { } } + +#[cfg(test)] +mod trim_tests { + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// What a trim took out is freed whole, by the trim's thread or a thread of its own, and an empty take is a no-op. + #[test] + fn what_a_trim_took_out_is_freed() { + struct Counted(Arc); + impl Drop for Counted { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + let freed = Arc::new(AtomicUsize::new(0)); + super::let_go_apart(Vec::::new()); + super::let_go_apart((0..40).map(|_| Counted(freed.clone())).collect()); + let until = std::time::Instant::now() + std::time::Duration::from_secs(10); + while freed.load(Ordering::SeqCst) < 40 && std::time::Instant::now() < until { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(freed.load(Ordering::SeqCst), 40); + } +} diff --git a/d3d12/crates/leonida-gpu/src/list.rs b/d3d12/crates/leonida-gpu/src/list.rs index 2ddaccb567..7cc0b84687 100644 --- a/d3d12/crates/leonida-gpu/src/list.rs +++ b/d3d12/crates/leonida-gpu/src/list.rs @@ -345,6 +345,8 @@ pub(crate) fn past_first(pool: &mut Vec, keep: usize) -> Vec { /// Lets idle host lists past [`IDLE_WHEN_TIGHT`] go, and their allocators' command memory with them: on an RX 6700 XT /// that memory lies in a 2 GB aperture segment (VIctory-6700XT `FINDINGS-6700XT.md`). They have run and been reset. +/// They are taken out here under the pool's lock and freed by `crate::host::let_go_apart` (on a thread of its own +/// unless `LEONIDA_TRIM_ASYNC=0`: freeing 448 lists took the submitting thread 150-260 ms). /// Not counted in `ALLOCATOR_TRIMS`, which is `LEONIDA_ALLOCATOR_TRIM`'s. After kyokyotosh/VIctory-6700XT e3c0703 /// (GPL-3.0), via PastiiJay/klbf-lab #127. #[cfg(windows)] @@ -359,7 +361,7 @@ pub(crate) fn trim_idle() { gone }; // (Outside the lock: freeing lists takes the graphics kernel's time.) - drop(gone); + crate::host::let_go_apart(gone); } /// The host sides of lists whose submission has run (submissions are