Skip to content
Merged
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
13 changes: 10 additions & 3 deletions crates/victory-gpu/src/bindless.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,14 @@ pub(crate) fn uploads(
heaps: &[Arc<Viewed>],
textures: &[(Arc<crate::texture::Staging>, Arc<crate::resource::HostTexture>)],
) -> Option<Uploads> {
static LIST: Mutex<Holder> = Mutex::new(Holder(None));
static LIST: Mutex<Holder> = Mutex::new(Holder(None, false));
let mut guard = LIST.lock().unwrap_or_else(|e| e.into_inner());
crate::texture::recycle();
// Nothing to bring up, and the list holds nothing of the last submission
// to let go of: it stays as it is.
if heaps.is_empty() && textures.is_empty() && !guard.1 {
return None;
}
match &guard.0 {
// Closed by the last submission, which has run.
Some(list) => list.reset(),
Expand Down Expand Up @@ -280,12 +285,14 @@ pub(crate) fn uploads(
unsafe { list.list.ResourceBarrier(&readable) };
}
list.close();
guard.1 = recorded;
// A list recording nothing is not run (its reset next time is fine).
recorded.then_some(Uploads(guard))
}

/// The upload list, used under its lock only.
pub(crate) struct Holder(Option<HostList>);
/// The upload list, used under its lock only, and whether it holds what it
/// recorded (the staging it names) until the next reset.
pub(crate) struct Holder(Option<HostList>, bool);
// SAFETY: D3D12 objects are free-threaded; the list is used by one
// submission at a time, under the lock.
unsafe impl Send for Holder {}
Expand Down
55 changes: 52 additions & 3 deletions crates/victory-gpu/src/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -926,6 +926,21 @@ pub(crate) mod tests {
list.close();
}

#[test]
fn a_shed_list_makes_its_scratch_again_from_the_first_chunk() {
let Some(host) = host() else { return };
let Ok(list) = host.new_list() else { return };
list.scratch(200 << 10).unwrap();
list.close();
list.reset();
assert!(list.scratch_bytes() > 0, "kept for the next cycle");
list.shed_scratch();
assert_eq!(list.scratch_bytes(), 0);
list.scratch(1).unwrap();
assert_eq!(list.scratch_bytes(), FIRST_SCRATCH_CHUNK);
list.close();
}

#[test]
fn warp_adapter_accepts_only_software() {
// This probes DXGI without creating a D3D12 device or running a title.
Expand Down Expand Up @@ -1802,11 +1817,14 @@ impl Host {
.collect::<Vec<_>>()
})
.collect();
// Every submission, not only those with textures to bring up: the
// staging pools and the upload list (it holds what the last
// submission staged) age on each one (`uploads`), and so do the
// idle spare lists. The last submission has run.
crate::list::trim_idle();
#[cfg(feature = "diagnostics")]
let uploading = crate::watch::Timed(std::time::Instant::now(), crate::copystat::C::UploadsUs);
let uploads = (!heaps.is_empty() || !textures.is_empty())
.then(|| crate::bindless::uploads(&heaps, &textures))
.flatten();
let uploads = crate::bindless::uploads(&heaps, &textures);
#[cfg(feature = "diagnostics")]
drop(uploading);
let runs: Vec<&HostList> = uploads
Expand Down Expand Up @@ -3292,6 +3310,27 @@ impl HostList {
}
}

/// The upload memory the list keeps for its next cycle, in bytes.
pub(crate) fn scratch_bytes(&self) -> u64 {
let s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
s.chunks.iter().map(|c| c.capacity).sum()
}

/// Gives up all the scratch of a list that is reset and that no title
/// list or submission uses (`list::SPARE`): the next cycle makes what it
/// needs again. Released as [`Self::trim_scratch`] releases its chunks.
pub(crate) fn shed_scratch(&self) {
let spent = {
let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
(s.current, s.used) = (0, 0);
std::mem::take(&mut s.chunks)
};
// Each release is a kernel call, as in [`release_later`].
if !spent.is_empty() {
release_later(Box::new(spent));
}
}

/// The host address of the list's indirect-work budget, zeroed at each
/// submission of the list from the first use after a reset on.
pub(crate) fn budget(&self) -> Option<u64> {
Expand Down Expand Up @@ -4370,6 +4409,16 @@ impl Meter {
own as f64 / report_frames
);
}
#[cfg(feature = "diagnostics")]
{
let (lists, bytes) = crate::list::spare_scratch();
let shed = crate::list::SPARE_SHED.swap(0, Ordering::Relaxed);
tracing::info!(
"spare host lists: {lists}, keeping {:.1} MB of scratch; {:.1} MB given up since the last line",
bytes as f64 / 1e6,
shed as f64 / 1e6
);
}
for (why, n) in drops.iter().take(40) {
tracing::info!(
"dropped {:.1}/frame without a host pipeline: {why}",
Expand Down
65 changes: 62 additions & 3 deletions crates/victory-gpu/src/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@ fn restart(this: This) -> Result<Option<std::sync::Arc<crate::host::HostList>>,
|| {
let spare = SPARE.lock().unwrap_or_else(|e| e.into_inner()).pop();
if let Some(fresh) = spare {
Ok(std::sync::Arc::new(fresh))
Ok(std::sync::Arc::new(fresh.list))
} else if let Some(host) = crate::host::host() {
host.new_list().map(std::sync::Arc::new).map_err(|e| {
tracing::warn!(error = %e, "no replacement host command list");
Expand All @@ -319,8 +319,36 @@ fn restart(this: This) -> Result<Option<std::sync::Arc<crate::host::HostList>>,
/// Host lists [`restart`] left to a queue, back once they ran: the next
/// ones it hands out (a host list and its allocators are not free to make;
/// Grand Theft Auto VI resets up to 21 lists a frame while they are held).
/// Oldest first: the newest is the one [`restart`] takes.
#[cfg(windows)]
static SPARE: std::sync::Mutex<Vec<crate::host::HostList>> = std::sync::Mutex::new(Vec::new());
static SPARE: std::sync::Mutex<Vec<Idle>> = std::sync::Mutex::new(Vec::new());

/// A list in [`SPARE`], with when it went idle and the scratch it keeps.
#[cfg(windows)]
struct Idle {
list: crate::host::HostList,
at: std::time::Instant,
bytes: u64,
}

/// The scratch [`SPARE`] keeps in all, at most: the most the texture staging
/// buffers keep (`texture::KEPT_BYTES_MAX`). A list keeps what its last
/// cycle needed and nothing bounded that (64 lists of 12 MB held 764 MB), so
/// the oldest entries give theirs up past this.
#[cfg(windows)]
const SPARE_BYTES: u64 = 256 << 20;

/// Scratch [`shed`] gave up since the last frame-rate line, in bytes
/// (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) static SPARE_SHED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);

/// The spare lists and the scratch they keep, in bytes (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn spare_scratch() -> (usize, u64) {
let spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
(spare.len(), spare.iter().map(|i| i.bytes).sum())
}

/// A host list a queue has run: one no title list holds any more is reset
/// and kept for [`restart`].
Expand All @@ -329,9 +357,40 @@ pub(crate) fn recycle(list: std::sync::Arc<crate::host::HostList>) {
const KEPT: usize = 64;
if let Ok(list) = std::sync::Arc::try_unwrap(list) {
list.reset();
let bytes = list.scratch_bytes();
let now = std::time::Instant::now();
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
if spare.len() < KEPT {
spare.push(list);
spare.push(Idle {
list,
at: now,
bytes,
});
}
shed(&mut spare, now);
}
}

/// At each submission: the scratch of spare lists idle past
/// [`crate::recent::WINDOW`] is given up, and of the oldest while the rest
/// keep more than [`SPARE_BYTES`]. A spare list is reset and no title list
/// holds it, so nothing uses its scratch.
#[cfg(windows)]
pub(crate) fn trim_idle() {
let now = std::time::Instant::now();
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
shed(&mut spare, now);
}

#[cfg(windows)]
fn shed(spare: &mut [Idle], now: std::time::Instant) {
let n = crate::recent::idle_shed(spare.iter().map(|i| (i.at, i.bytes)), now, SPARE_BYTES);
for idle in &mut spare[..n] {
if idle.bytes > 0 {
idle.list.shed_scratch();
#[cfg(feature = "diagnostics")]
SPARE_SHED.fetch_add(idle.bytes, std::sync::atomic::Ordering::Relaxed);
idle.bytes = 0;
}
}
}
Expand Down
74 changes: 74 additions & 0 deletions crates/victory-gpu/src/recent.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,28 @@ impl Pool {
}
}

/// How many of the oldest idle entries give up what they hold at `now`: the
/// leading ones idle longer than [`WINDOW`], then, while the entries left
/// hold more than `cap` bytes, the oldest of those. `idle` is (when an entry
/// went idle, the bytes it holds), oldest first, so the ones past the window
/// come first.
pub(crate) fn idle_shed(
idle: impl Iterator<Item = (Instant, u64)> + Clone,
now: Instant,
cap: u64,
) -> usize {
let mut kept: u64 = idle.clone().map(|(_, bytes)| bytes).sum();
let mut shed = 0;
for (at, bytes) in idle {
if kept <= cap && now.saturating_duration_since(at) <= WINDOW {
break;
}
kept -= bytes;
shed += 1;
}
shed
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -503,4 +525,56 @@ mod tests {
run(&mut u, 3, &[512 * MIB]);
assert_eq!(u.made, made + 3);
}

#[test]
fn idle_shed_gives_up_what_is_past_the_window_then_the_oldest_over_the_cap() {
let t = Instant::now();
let at = |s: u64| t + Duration::from_secs(s);
let now = at(20);
let shed = |idle: &[(u64, u64)], cap: u64| {
idle_shed(idle.iter().map(|&(s, b)| (at(s), b)), now, cap)
};
assert_eq!(shed(&[], 0), 0);
// Exactly one window old is still kept.
assert_eq!(shed(&[(10, 5), (15, 5)], 10), 0);
// Past the window (11 s old) goes; the rest fits the cap.
assert_eq!(shed(&[(9, 5), (15, 5)], 10), 1);
assert_eq!(shed(&[(0, 1), (1, 2)], u64::MAX), 2);
// Over the cap, the oldest go until what is left fits.
assert_eq!(shed(&[(12, 4), (14, 4), (16, 4)], 8), 1);
assert_eq!(shed(&[(12, 4), (14, 4), (16, 4)], 3), 3);
}

/// `idle_shed` against its definition: the least number of oldest entries
/// after which no entry is past the window and the bytes left fit the cap.
#[test]
fn idle_shed_is_the_least_prefix_that_leaves_no_old_entry_and_fits_the_cap() {
let t = Instant::now();
let mut seed = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move |n: u64| {
seed = seed
.wrapping_mul(6_364_136_223_846_793_005)
.wrapping_add(1_442_695_040_888_963_407);
(seed >> 33) % n
};
for _ in 0..200_000 {
let len = next(12) as usize;
let mut when = 0;
let idle: Vec<(Instant, u64)> = (0..len)
.map(|_| {
when += next(6);
(t + Duration::from_secs(when), next(8))
})
.collect();
let now = t + Duration::from_secs(next(40));
let cap = next(30);
let aged = |at: Instant| now.saturating_duration_since(at) > WINDOW;
let fits = |k: usize| {
idle[k..].iter().all(|&(at, _)| !aged(at))
&& idle[k..].iter().map(|&(_, b)| b).sum::<u64>() <= cap
};
let least = (0..=len).find(|&k| fits(k)).unwrap();
assert_eq!(idle_shed(idle.iter().copied(), now, cap), least);
}
}
}