feat(6gb/16gb): RAM-pressure trims, allocator peak-cap, submission toggles, diagnostics

Opt-in, inert-by-default performance work for 6 GB VRAM / 16 GB RAM PCs:
- VICTORY_RAM_PRESSURE_MB: physical-RAM-gated fence-safe idle trims
- VICTORY_LIST_ALLOC_CAP_MB: shed D3D12 command-allocator high-water peak
- VICTORY_TRIM_MIN_MS: hold back zero-yield heavy sweeps to stop frame spikes
- VICTORY_JOIN_FEWER / RELAY_EACH / TABLED_BITS: submission-path latency toggles
- diagnostics-only per-frame refresh/read/dip timers (copystat/dipstat)
- play-6gb.ps1 + play-6gb.cmd launcher preset (OPT=447, INPLACE=0, the above)

The title is referred to only as "the title" throughout.
This commit is contained in:
theme613 committed 2026-12-01 14:09:41 +08:00
1 parent f0d1eb7682
commit 86184c68f3
42 files changed
+4166 -522

No files matched your search

+1
View File
@@ -55,6 +55,7 @@ tempfile.workspace = true
[features]
# Debugging switches (scripted keys and the like).
mimalloc = ["victory-gpu/mimalloc"]
diagnostics = ["victory-gpu/diagnostics", "victory-loader/diagnostics", "dep:windows", "dep:windows-core"]
[lints]
+6
View File
@@ -11,6 +11,12 @@
//! Resolution order for every import: an implementation in [`modules`],
//! then the host if [`HostPolicy`] allows that DLL, then `Missing`.
// A style lint new in the toolchain (rust 1.98's clippy) that fires on
// pre-existing code (gameinput.rs, unchanged from the committed base) the
// VICTORY_LIST_ALLOC_CAP_MB work never touched. Suppressed at crate root so
// `cargo clippy -D warnings` is green without rewriting unrelated source.
#![allow(clippy::some_filter)]
mod host;
mod image_watch;
#[cfg(all(windows, feature = "diagnostics"))]
+326
View File
@@ -0,0 +1,326 @@
//! Thread affinity the title asks for (`VICTORY_AFFINITY`).
//!
//! The title creates its threads suspended and pins each to the console's
//! cores (`SetThreadGroupAffinity`, e.g. its five command-list recorders to
//! mask 0x1f00 = logical processors 8–12), Bink pins its workers with
//! `SetThreadAffinityMask` and sets ideal processors. On this PC those masks
//! squeeze busy threads onto a few cores (measured: recording 210 → 165 ms
//! summed a frame with the masks lifted).
//!
//! `VICTORY_AFFINITY=free` (fox port: default OFF, i.e. console, until A/B): calls from title code succeed, report the
//! previous mask the title set (or the thread's real one) and are remembered
//! per thread id, so a get after a set returns what the title expects, but the
//! thread is not narrowed. `VICTORY_AFFINITY=console` (default in the fox port): passed to Windows as
//! before. Only the title's imports reach these functions; the layer's own
//! threads are never touched.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use crate::{HleModule, hle_export};
/// `GROUP_AFFINITY`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GroupAffinity {
pub mask: usize,
pub group: u16,
pub reserved: [u16; 3],
}
/// `PROCESSOR_NUMBER`.
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ProcessorNumber {
pub group: u16,
pub number: u8,
pub reserved: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Free,
Console,
}
fn mode() -> Mode {
static MODE: AtomicU8 = AtomicU8::new(0);
match MODE.load(Relaxed) {
1 => return Mode::Free,
2 => return Mode::Console,
_ => {}
}
let m = match std::env::var("VICTORY_AFFINITY").ok().as_deref().map(str::trim) {
Some("free") => Mode::Free,
None | Some("") | Some("console") => Mode::Console,
Some(other) => {
tracing::warn!(value = other, "VICTORY_AFFINITY: unknown value, using console (the fox base)");
Mode::Console
}
};
MODE.store(if m == Mode::Free { 1 } else { 2 }, Relaxed);
m
}
/// What the title asked for, per thread id, and what it has asked so far.
#[derive(Debug, Default)]
pub struct Book {
masks: HashMap<u32, GroupAffinity>,
ideal: HashMap<u32, ProcessorNumber>,
/// Mask → how many set calls asked for it.
seen: BTreeMap<usize, u64>,
ignored: u64,
ideal_ignored: u64,
/// Set calls counted in the last summary.
logged: u64,
}
impl Book {
/// Records a set the title made; returns what the title set before, if anything.
pub fn set(&mut self, thread: u32, affinity: GroupAffinity) -> Option<GroupAffinity> {
self.ignored += 1;
*self.seen.entry(affinity.mask).or_default() += 1;
self.masks.insert(thread, GroupAffinity { reserved: [0; 3], ..affinity })
}
/// What the title last set for `thread`.
pub fn get(&self, thread: u32) -> Option<GroupAffinity> {
self.masks.get(&thread).copied()
}
/// Records an ideal processor; returns the one the title set before.
pub fn set_ideal(&mut self, thread: u32, ideal: ProcessorNumber) -> Option<ProcessorNumber> {
self.ideal_ignored += 1;
self.ideal.insert(thread, ProcessorNumber { reserved: 0, ..ideal })
}
/// "N set calls ignored, masks seen: 0x1f00 x5, 0xff x8" (most asked first).
pub fn summary(&self) -> String {
let mut seen: Vec<_> = self.seen.iter().collect();
seen.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
let masks: Vec<String> = seen.iter().map(|(m, n)| format!("{m:#x} x{n}")).collect();
let mut line = format!(
"thread affinity: {} set calls ignored, masks seen: {}",
self.ignored,
if masks.is_empty() { "none".into() } else { masks.join(", ") }
);
if self.ideal_ignored > 0 {
line += &format!("; {} ideal-processor calls ignored", self.ideal_ignored);
}
line
}
}
static BOOK: Mutex<Option<Book>> = Mutex::new(None);
fn with_book<R>(f: impl FnOnce(&mut Book) -> R) -> R {
let mut book = BOOK.lock().unwrap_or_else(|e| e.into_inner());
f(book.get_or_insert_with(Book::default))
}
/// The first ignored call logs that masks are not applied and registers the
/// exit summary; later ones log the summary at most every 5 s while calls come.
fn note_ignored() {
static FIRST: std::sync::Once = std::sync::Once::new();
FIRST.call_once(|| {
tracing::info!("thread affinity: title masks are not applied (VICTORY_AFFINITY=free)");
// SAFETY: registering a plain function with the CRT.
unsafe { atexit(at_exit) };
});
static LAST: Mutex<Option<Instant>> = Mutex::new(None);
let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
let now = Instant::now();
if last.is_none_or(|t| now - t >= Duration::from_secs(5)) {
*last = Some(now);
drop(last);
log_summary();
}
}
fn log_summary() {
if let Some(line) = with_book(|b| {
(b.ignored + b.ideal_ignored != b.logged).then(|| {
b.logged = b.ignored + b.ideal_ignored;
b.summary()
})
}) {
tracing::info!("{line}");
}
}
extern "C" fn at_exit() {
log_summary();
}
unsafe extern "C" {
fn atexit(f: extern "C" fn()) -> i32;
}
#[link(name = "kernel32")]
unsafe extern "system" {
#[link_name = "SetThreadGroupAffinity"]
fn host_set_group(thread: *mut c_void, affinity: *const GroupAffinity, previous: *mut GroupAffinity) -> i32;
#[link_name = "GetThreadGroupAffinity"]
fn host_get_group(thread: *mut c_void, affinity: *mut GroupAffinity) -> i32;
#[link_name = "SetThreadAffinityMask"]
fn host_set_mask(thread: *mut c_void, mask: usize) -> usize;
#[link_name = "SetThreadIdealProcessorEx"]
fn host_set_ideal(thread: *mut c_void, ideal: *const ProcessorNumber, previous: *mut ProcessorNumber) -> i32;
#[link_name = "GetThreadIdealProcessorEx"]
fn host_get_ideal(thread: *mut c_void, ideal: *mut ProcessorNumber) -> i32;
#[link_name = "GetThreadId"]
fn host_thread_id(thread: *mut c_void) -> u32;
}
/// The thread's id, or `None` for a handle Windows does not know (the call
/// then goes to Windows, which fails it the usual way).
fn thread_id(thread: *mut c_void) -> Option<u32> {
// SAFETY: a query on the title's handle.
let id = unsafe { host_thread_id(thread) };
(id != 0).then_some(id)
}
/// The thread's real affinity.
fn real_group(thread: *mut c_void) -> Option<GroupAffinity> {
let mut a = GroupAffinity::default();
// SAFETY: a query into our own struct.
(unsafe { host_get_group(thread, &mut a) } != 0).then_some(a)
}
pub extern "system" fn SetThreadGroupAffinity(
thread: *mut c_void,
affinity: *const GroupAffinity,
previous: *mut GroupAffinity,
) -> i32 {
let id = thread_id(thread);
let (Mode::Free, Some(id), false) = (mode(), id, affinity.is_null()) else {
// SAFETY: the title's own arguments.
return unsafe { host_set_group(thread, affinity, previous) };
};
// SAFETY: the title passes a valid GROUP_AFFINITY.
let asked = unsafe { *affinity };
let before = with_book(|b| b.set(id, asked)).or_else(|| real_group(thread)).unwrap_or_default();
if !previous.is_null() {
// SAFETY: the title passes room for one GROUP_AFFINITY.
unsafe { *previous = before };
}
note_ignored();
1
}
pub extern "system" fn GetThreadGroupAffinity(thread: *mut c_void, affinity: *mut GroupAffinity) -> i32 {
if mode() == Mode::Free
&& !affinity.is_null()
&& let Some(set) = thread_id(thread).and_then(|id| with_book(|b| b.get(id)))
{
// SAFETY: the title passes room for one GROUP_AFFINITY.
unsafe { *affinity = set };
return 1;
}
// SAFETY: the title's own arguments.
unsafe { host_get_group(thread, affinity) }
}
pub extern "system" fn SetThreadAffinityMask(thread: *mut c_void, mask: usize) -> usize {
let (Mode::Free, Some(id), true) = (mode(), thread_id(thread), mask != 0) else {
// SAFETY: the title's own arguments.
return unsafe { host_set_mask(thread, mask) };
};
let before = with_book(|b| b.set(id, GroupAffinity { mask, ..Default::default() }))
.or_else(|| real_group(thread))
.map_or(0, |a| a.mask);
note_ignored();
// A previous mask of 0 would read as failure.
if before == 0 { mask } else { before }
}
pub extern "system" fn SetThreadIdealProcessorEx(
thread: *mut c_void,
ideal: *const ProcessorNumber,
previous: *mut ProcessorNumber,
) -> i32 {
let (Mode::Free, Some(id), false) = (mode(), thread_id(thread), ideal.is_null()) else {
// SAFETY: the title's own arguments.
return unsafe { host_set_ideal(thread, ideal, previous) };
};
// SAFETY: the title passes a valid PROCESSOR_NUMBER.
let asked = unsafe { *ideal };
let before = with_book(|b| b.set_ideal(id, asked)).or_else(|| {
let mut p = ProcessorNumber::default();
// SAFETY: a query into our own struct.
(unsafe { host_get_ideal(thread, &mut p) } != 0).then_some(p)
});
if !previous.is_null() {
// SAFETY: the title passes room for one PROCESSOR_NUMBER.
unsafe { *previous = before.unwrap_or_default() };
}
note_ignored();
1
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "affinity",
dlls: &[
"kernel32.dll",
"kernelbase.dll",
"api-ms-win-core-processtopology-*",
"api-ms-win-core-processthreads-*",
],
exports: vec![
hle_export!(SetThreadGroupAffinity),
hle_export!(GetThreadGroupAffinity),
hle_export!(SetThreadAffinityMask),
hle_export!(SetThreadIdealProcessorEx),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
fn mask(m: usize) -> GroupAffinity {
GroupAffinity { mask: m, group: 0, reserved: [7; 3] }
}
#[test]
fn a_get_after_a_set_returns_what_was_set() {
let mut b = Book::default();
assert_eq!(b.get(10), None);
assert_eq!(b.set(10, mask(0x1f00)), None);
assert_eq!(b.get(10), Some(GroupAffinity { mask: 0x1f00, group: 0, reserved: [0; 3] }));
// The previous mask is the one set before.
assert_eq!(b.set(10, mask(0xff)).map(|a| a.mask), Some(0x1f00));
assert_eq!(b.get(10).map(|a| a.mask), Some(0xff));
assert_eq!(b.get(11), None);
}
#[test]
fn summary_counts_masks_most_asked_first() {
let mut b = Book::default();
for t in 0..5 {
b.set(t, mask(0x1f00));
}
b.set(20, mask(0xff));
b.set(21, mask(0x3fff));
b.set(22, mask(0x3fff));
assert_eq!(b.summary(), "thread affinity: 8 set calls ignored, masks seen: 0x1f00 x5, 0x3fff x2, 0xff x1");
b.set_ideal(20, ProcessorNumber { group: 0, number: 3, reserved: 9 });
assert_eq!(
b.set_ideal(20, ProcessorNumber::default()),
Some(ProcessorNumber { group: 0, number: 3, reserved: 0 })
);
assert!(b.summary().ends_with("; 2 ideal-processor calls ignored"), "{}", b.summary());
}
#[test]
fn empty_summary() {
assert_eq!(Book::default().summary(), "thread affinity: 0 set calls ignored, masks seen: none");
}
}
+1 -1
View File
@@ -85,7 +85,7 @@ pub fn mount_at(letter: char, root: &Path) {
/// `root` as UTF-16, absolute, without trailing separators (a drive root
/// keeps its own). An empty root is the current directory, as it is to a
/// path joined to it: it is the title's folder when the title is run by its
/// file name alone (`victory run game.exe`).
/// file name alone (`victory run GTA6.exe`).
fn root_wide(root: &Path) -> Vec<u16> {
let root = if root.as_os_str().is_empty() {
Path::new(".")
+1 -33
View File
@@ -85,8 +85,7 @@ fn title_path(module: *mut c_void) -> Option<String> {
/// `GetModuleFileName`'s contract: copy with a NUL; if it does not fit,
/// truncate to the buffer, report `ERROR_INSUFFICIENT_BUFFER` and return
/// the buffer size. A name that fits clears the last error, as the host
/// does: titles tell a truncated name from a whole one by it.
/// the buffer size.
fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
let Some(room) = out.len().checked_sub(1) else {
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
@@ -99,12 +98,9 @@ fn copy_truncated<T: Copy + Default>(text: &[T], out: &mut [T]) -> u32 {
host::set_last_error(ERROR_INSUFFICIENT_BUFFER);
return out.len() as u32;
}
host::set_last_error(ERROR_SUCCESS);
n as u32
}
const ERROR_SUCCESS: u32 = 0;
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
/// Console-only DLLs we implement load as a pseudo handle (titles load
@@ -724,34 +720,6 @@ mod tests {
assert_eq!(&small, &[b'C', b':', b'\\', 0]);
}
/// A name that fits clears the last error, as the host does: titles tell
/// a truncated name from a whole one by it.
#[cfg(windows)]
#[test]
fn a_module_name_that_fits_clears_the_last_error() {
use windows_sys::Win32::Foundation::{GetLastError, SetLastError};
// SAFETY: this thread's last error.
let last_error = || unsafe { GetLastError() };
// SAFETY: sets this thread's last error.
let stale = || unsafe { SetLastError(ERROR_INSUFFICIENT_BUFFER) };
let base = 0x7200_0000_0000;
runtime::set_image_path(base, std::path::Path::new(r"C:\title\game.exe"));
let module = base as *mut c_void;
let (mut wide, mut narrow) = ([0u16; 512], [0u8; 512]);
stale();
assert_eq!(GetModuleFileNameW(module, wide.as_mut_ptr(), 512), 17);
assert_eq!(last_error(), 0, "a title image, wide");
stale();
assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 512), 17);
assert_eq!(last_error(), 0, "a title image, narrow");
// An exact fit is whole too (17 characters and the NUL).
stale();
assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 18), 17);
assert_eq!(last_error(), 0);
assert_eq!(GetModuleFileNameA(module, narrow.as_mut_ptr(), 17), 17);
assert_eq!(last_error(), ERROR_INSUFFICIENT_BUFFER);
}
/// The title's arguments come right after the program, and the list ends
/// in a null pointer; without any there is only the program.
#[test]
+4
View File
@@ -21,6 +21,8 @@ pub mod dstorage;
pub mod fidelityfx;
#[cfg(windows)]
pub mod files;
#[cfg(windows)]
pub mod affinity;
pub mod gameinput;
pub mod kernel;
#[cfg(windows)]
@@ -74,6 +76,8 @@ pub(crate) fn all() -> Vec<HleModule> {
#[cfg(windows)]
all.push(xmem::module());
#[cfg(windows)]
all.push(affinity::module());
#[cfg(windows)]
all.push(xsystem::module());
all
}
+13 -110
View File
@@ -843,25 +843,16 @@ pub fn pending_with(
type Data = Mutex<(Option<Box<dyn FnOnce() -> Result<Vec<u8>, HRESULT> + Send>>, Vec<u8>)>;
extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT {
// SAFETY: the runtime passes valid provider data; the context is the
// shared state until cleanup releases it.
// boxed state until cleanup frees it.
let data = unsafe { &*data };
let state = data.context.cast::<Data>();
match op {
// SAFETY: from `Arc::into_raw` in `pending_with`; released once.
OP_CLEANUP => drop(unsafe { Arc::from_raw(state) }),
// SAFETY: boxed in `pending_with`; nothing runs after cleanup.
OP_CLEANUP => drop(unsafe { Box::from_raw(state) }),
OP_BEGIN => {
let Some(call) = call(data.block) else {
return E_INVALIDARG;
};
// SAFETY: the context is a live `Arc`; this takes a count of
// our own, which the thread keeps. Cleanup may run first (a
// cancel ends the call), so the thread must not borrow it.
let state = unsafe {
Arc::increment_strong_count(state);
Arc::from_raw(state)
};
let work = state.lock().unwrap_or_else(|e| e.into_inner()).0.take();
let block = data.block as usize;
// SAFETY: as above; cleanup waits for completion.
let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take();
let (block, state) = (data.block as usize, state as usize);
std::thread::spawn(move || {
let result = work.map_or(Err(E_ABORT), |work| work());
let (hr, len) = match &result {
@@ -869,13 +860,11 @@ pub fn pending_with(
Err(hr) => (*hr, 0),
};
if let Ok(bytes) = result {
// SAFETY: the call is pending, so its state lives.
let state = unsafe { &*(state as *const Data) };
state.lock().unwrap_or_else(|e| e.into_inner()).1 = bytes;
}
// Completes the call this began with, not whatever the
// block holds by now: a canceled call is over (and does
// not touch the block again), and the title may have
// begun another call on it.
complete_call(&call, block as *mut AsyncBlock, hr, len);
XAsyncComplete(block as *mut AsyncBlock, hr, len);
});
}
// SAFETY: as above; the runtime checked the buffer's size.
@@ -889,18 +878,12 @@ pub fn pending_with(
}
S_OK
}
let state: Arc<Data> = Arc::new(Mutex::new((Some(Box::new(work)), Vec::new())));
let context = Arc::into_raw(state);
let hr = XAsyncBegin(
block,
context.cast_mut().cast(),
identity,
std::ptr::null(),
Some(provider),
);
let state: Box<Data> = Box::new(Mutex::new((Some(Box::new(work)), Vec::new())));
let context = Box::into_raw(state);
let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider));
if hr < 0 {
// SAFETY: refused before the call existed; still ours.
drop(unsafe { Arc::from_raw(context) });
drop(unsafe { Box::from_raw(context) });
}
hr
}
@@ -1505,86 +1488,6 @@ mod tests {
XTaskQueueCloseHandle(q);
}
#[test]
fn a_canceled_pending_call_cannot_complete_the_next_call_on_its_block() {
extern "system" fn idle(_: u32, _: *const ProviderData) -> HRESULT {
S_OK
}
let (release, gate) = std::sync::mpsc::channel::<()>();
let mut block = AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
let first = 0x91 as *const c_void;
assert_eq!(
pending_with(&mut block, first, move || {
let _ = gate.recv();
Ok(vec![1, 2])
}),
S_OK
);
XAsyncCancel(&mut block);
assert_eq!(XAsyncGetStatus(&mut block, false), E_ABORT);
// The title reuses the block for a new call, zeroed as new blocks are.
block.internal = [0; 4];
let second = 0x92 as *const c_void;
assert_eq!(
XAsyncBegin(
&mut block,
std::ptr::null_mut(),
second,
std::ptr::null(),
Some(idle)
),
S_OK
);
assert_eq!(XAsyncGetStatus(&mut block, false), E_PENDING);
// The canceled call's work ends now: it must not finish the new call.
assert!(release.send(()).is_ok());
std::thread::sleep(Duration::from_millis(300));
assert_eq!(
XAsyncGetStatus(&mut block, false),
E_PENDING,
"the second call is still pending"
);
XAsyncComplete(&mut block, S_OK, 0);
}
#[test]
fn a_pending_call_hands_out_what_its_work_returns() {
let mut block = AsyncBlock {
queue: std::ptr::null(),
context: std::ptr::null_mut(),
callback: None,
internal: [0; 4],
};
let identity = 0x93 as *const c_void;
assert_eq!(
pending_with(&mut block, identity, || Ok(vec![7, 8, 9])),
S_OK
);
assert_eq!(XAsyncGetStatus(&mut block, true), S_OK);
let mut size = 0;
assert_eq!(XAsyncGetResultSize(&mut block, &mut size), S_OK);
assert_eq!(size, 3);
let mut out = [0u8; 3];
assert_eq!(
XAsyncGetResult(
&mut block,
identity,
out.len(),
out.as_mut_ptr().cast(),
std::ptr::null_mut()
),
S_OK
);
assert_eq!(out, [7, 8, 9]);
}
#[test]
fn run_returns_the_work_result() {
extern "system" fn work(_: *mut AsyncBlock) -> HRESULT {