Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions d3d12/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,9 @@ Also in, off by default:
every 2D target.
- `LEONIDA_ADAPTER=<part of a card's name, or #index>` (`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.

---

Expand Down
1 change: 1 addition & 0 deletions d3d12/crates/leonida-gpu/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
323 changes: 291 additions & 32 deletions d3d12/crates/leonida-gpu/src/host.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion d3d12/crates/leonida-gpu/src/host/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 },
Expand Down
200 changes: 200 additions & 0 deletions d3d12/crates/leonida-gpu/src/host/segments.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
//! 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; 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.

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<D3DKMT_QUERYSTATISTICS_RESULT> {
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<LUID> {
// SAFETY: a plain query.
unsafe { adapter.GetDesc1() }.ok().map(|d| d.AdapterLuid)
}

/// The adapter's segments.
pub(crate) fn segments(adapter: &IDXGIAdapter3) -> Vec<Segment> {
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; 80 by default, 0: never).
static TIGHT_PERCENT: LazyLock<u64> =
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 ([`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);
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 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
{
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" },
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));
}
}
86 changes: 82 additions & 4 deletions d3d12/crates/leonida-gpu/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,38 @@ fn fresh_list() -> Option<crate::host::HostList> {
}
}

/// Host lists kept idle while an aperture segment of the card's memory is near its limit
/// (`crate::host::segments`).
#[cfg(windows)]
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<T>(pool: &mut Vec<T>, keep: usize) -> Vec<T> {
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.
/// 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)]
pub(crate) fn trim_idle() {
let gone: Vec<Idle> = {
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::<u64>();
gone
};
// (Outside the lock: freeing lists takes the graphics kernel's time.)
crate::host::let_go_apart(gone);
}

/// 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
Expand All @@ -341,10 +373,44 @@ pub(crate) fn recycle(lists: Vec<Detached>, 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`). 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<Detached>, 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<Item = crate::host::HostList>, 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();
Expand Down Expand Up @@ -2939,6 +3005,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]
Expand Down
1 change: 1 addition & 0 deletions d3d12/docs/README-fxceless.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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.
Expand Down
10 changes: 8 additions & 2 deletions d3d12/scripts/play-nvidia.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -351,12 +357,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
Expand Down
2 changes: 1 addition & 1 deletion d3d12/scripts/play.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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'
}
Expand Down