Merge local/next (f61ecf3b) into night/cpu

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 05:44:51 -06:00
commit 19be44dd6f
11 files changed
+813 -14

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
//! Keeps the card's clocks up between submissions (`VICTORY_CARD_AWAKE=1`; off
//! by default). The card stands idle half of every frame, some thirty times for
//! a millisecond or two each, while the CPU prepares the next submission. The
//! driver takes that for a light load and lowers the clocks, and what comes
//! next starts slow: a captured frame whose lists take 30 ms sent in one go
//! takes 38-40 ms with waits of 1.2-2.4 ms between its submissions
//! (`victory replay --pace`).
//!
//! One group of 64 threads counts on a compute queue, over and
//! over: it takes one or two of the card's few thousand wave slots, and the
//! card is never idle. Nothing is sent once no submission has gone out for a
//! while (a menu at 30 fps, a minimized window).
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use windows::Win32::Foundation::CloseHandle;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
use windows::core::Interface;
/// About 2 ms at full clocks: 500 sends a second.
const COUNT: &str = r#"
#define RS "UAV(u0)"
RWByteAddressBuffer sum : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 id : SV_DispatchThreadID) {
uint x = id.x;
[loop] for (uint i = 0; i < 400000u; i++) x = x * 1664525u + 1013904223u;
sum.Store(id.x * 4u, x);
}
"#;
/// Quiet this long after the last submission.
const QUIET_MS: u64 = 250;
fn now_ms() -> u64 {
static START: OnceLock<std::time::Instant> = OnceLock::new();
START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
}
/// When a submission was last sent ([`now_ms`] plus one; 0: never).
static LAST: AtomicU64 = AtomicU64::new(0);
fn wanted() -> bool {
let (last, now) = (LAST.load(Ordering::Relaxed), now_ms());
last != 0 && now + 1 < last + QUIET_MS && (mode() != Mode::ByTurns || now / TURN_MS % 2 == 1)
}
/// With `VICTORY_CARD_AWAKE=turns`: this long on, this long off.
const TURN_MS: u64 = 20_000;
#[derive(Clone, Copy, PartialEq)]
enum Mode {
Off,
On,
/// On and off by turns, to compare the two in one run (the log says when).
ByTurns,
}
fn mode() -> Mode {
static MODE: OnceLock<Mode> = OnceLock::new();
*MODE.get_or_init(|| match std::env::var("VICTORY_CARD_AWAKE").as_deref() {
Ok("1") => Mode::On,
Ok("turns") => Mode::ByTurns,
_ => Mode::Off,
})
}
/// A submission of the title's goes to `device`'s drawing queue.
pub(super) fn sent(device: &ID3D12Device) {
if mode() == Mode::Off {
return;
}
let now = now_ms();
let before = LAST.swap(now + 1, Ordering::Relaxed);
if mode() == Mode::ByTurns && before.saturating_sub(1) / TURN_MS != now / TURN_MS {
tracing::info!(on = now / TURN_MS % 2 == 1, "the card is kept awake, by turns");
}
static STARTED: std::sync::Once = std::sync::Once::new();
STARTED.call_once(|| {
// Runs as long as the process does.
std::mem::forget(start(device, wanted));
});
}
/// The thread that keeps the card busy; it ends when this is dropped.
pub(crate) struct Awake {
stop: std::sync::Arc<AtomicBool>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl Drop for Awake {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
/// Keeps the card of `device` busy while `wanted`.
pub(crate) fn start(device: &ID3D12Device, wanted: impl Fn() -> bool + Send + 'static) -> Option<Awake> {
let stop = std::sync::Arc::new(AtomicBool::new(false));
let (device, ended) = (device.clone(), stop.clone());
let thread = std::thread::Builder::new()
.name("victory-card-awake".into())
.spawn(move || {
if let Err(e) = run(&device, &wanted, &ended) {
tracing::warn!(error = %e, "the card is not kept awake");
}
})
.ok()?;
Some(Awake {
stop,
thread: Some(thread),
})
}
fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> windows::core::Result<()> {
let code = super::compile(COUNT, windows::core::s!("main"), windows::core::s!("cs_5_1"))?;
// SAFETY: plain object creation; the code lives through the calls, the
// root signature is inside it. Two closed lists, sent in turn, whose
// objects live until what was sent last has run.
unsafe {
let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?;
let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})?;
let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_COMPUTE,
Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0,
..Default::default()
})?;
let mut sum: Option<ID3D12Resource> = None;
device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
},
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: 256,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
..Default::default()
},
D3D12_RESOURCE_STATE_COMMON,
None,
&mut sum,
)?;
let sum = sum.ok_or_else(windows::core::Error::empty)?;
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE)?;
let mut lists = Vec::new();
for _ in 0..2 {
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &allocator, &pso)?;
list.SetComputeRootSignature(&root);
list.SetComputeRootUnorderedAccessView(0, sum.GetGPUVirtualAddress());
list.Dispatch(1, 1, 1);
list.Close()?;
lists.push(Some(list.cast::<ID3D12CommandList>()?));
}
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
let event = CreateEventW(None, false, false, None)?;
let mut value = 0u64;
let mut result = Ok(());
while !stop.load(Ordering::Relaxed) && result.is_ok() {
if !wanted() {
std::thread::sleep(Duration::from_millis(2));
continue;
}
// Never more than two on the way.
if value >= 2 && fence.GetCompletedValue() + 2 <= value {
result = fence.SetEventOnCompletion(value - 1, event);
if result.is_ok() {
WaitForSingleObject(event, 1000);
result = device.GetDeviceRemovedReason();
}
continue;
}
queue.ExecuteCommandLists(&lists[(value % 2) as usize..][..1]);
value += 1;
result = queue.Signal(&fence, value);
}
if result.is_ok() && fence.GetCompletedValue() < value && fence.SetEventOnCompletion(value, event).is_ok() {
WaitForSingleObject(event, INFINITE);
}
let _ = CloseHandle(event);
result
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Card memory the CPU maps holds what the CPU wrote, with the card kept
/// awake meanwhile; the thread ends when it is let go.
#[test]
fn mapped_card_memory_is_written_by_the_cpu_and_read_by_the_card() {
let Some(host) = crate::host::host() else {
return;
};
let awake = start(&host.device, || true);
assert!(awake.is_some());
let Some((buffer, data)) = host.mapped_card_buffer(4096, true) else {
return;
};
let (seen, back) = host.shared_buffer(4096).unwrap();
// SAFETY: mappings of 4096 bytes; a list, a queue and a fence of the
// test's own, and nothing is read before the copy has run.
let read = unsafe {
for i in 0..4096 {
data.add(i).write((i * 7 + i / 251) as u8);
}
let device = &host.device;
let queue: ID3D12CommandQueue = device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
..Default::default()
})
.unwrap();
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
list.CopyBufferRegion(&seen, 0, &buffer, 0, 4096);
list.Close().unwrap();
queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
queue.Signal(&fence, 1).unwrap();
// No event: returns when the fence is there.
fence.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap();
std::slice::from_raw_parts(back, 4096).to_vec()
};
assert!(read.iter().enumerate().all(|(i, &b)| b == (i * 7 + i / 251) as u8));
drop(awake);
}
}
+22 -4
View File
@@ -118,8 +118,22 @@ unsafe impl Send for Memory {}
/// What submissions that have run gave back.
static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new());
/// At most this much is kept.
const KEPT: u64 = 768 << 20;
/// At most this much is kept (of the card's memory, with [`on_card`]).
fn kept() -> u64 {
if on_card() { 256 << 20 } else { 768 << 20 }
}
/// Whether the memory lies in the card's memory, written by the CPU through
/// the bus (`VICTORY_SEND_BAR=1`): the copies on the card's drawing queue, which
/// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of
/// the card's 30 (342 copies), and take 0.4 this way; but filling it takes the
/// submitting thread 8-9 ms a frame instead of 3 (73-93 MB, run card-3 against
/// card-1), so it is a loss while the card waits for that thread: off by
/// default.
fn on_card() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_SEND_BAR").is_some_and(|v| v == "1"))
}
fn memory(host: &Host, size: u64) -> Option<Memory> {
{
@@ -132,7 +146,11 @@ fn memory(host: &Host, size: u64) -> Option<Memory> {
// By doubles, so that the next of about this size finds it: what
// submissions send differs from frame to frame.
let size = size.max(8 << 20).next_power_of_two();
let (buffer, data) = host.upload_buffer(size)?;
let mapped = if on_card() { host.mapped_card_buffer(size, false) } else { None };
let (buffer, data) = match mapped {
Some(made) => made,
None => host.upload_buffer(size)?,
};
name(&buffer, || "bytes a submission sends up".into());
Some(Memory {
buffer,
@@ -146,7 +164,7 @@ pub(super) fn give_back(memory: Memory) {
let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
spare.push(memory);
spare.sort_by_key(|m| std::cmp::Reverse(m.size));
while spare.iter().map(|m| m.size).sum::<u64>() > KEPT {
while spare.iter().map(|m| m.size).sum::<u64>() > kept() {
spare.remove(0);
}
}
+232
View File
@@ -0,0 +1,232 @@
//! Diagnostics: how long the card itself works on our submissions, by its own
//! timestamps (`VICTORY_CARD_SPANS=1`). The clock of the frame line
//! (`card_clock_line`) counts from the call that sends a submission to the
//! moment a thread of ours wakes behind its last signal: the time the system
//! takes to hand a submission to the card and to report it done is in it, 40
//! times a frame. Here two lists made once, of nothing but a timestamp, stand
//! around each submission.
use std::sync::Mutex;
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::Interface;
use super::Host;
/// Submissions stamped before the first stamps are read and used again.
const SPANS: usize = 512;
/// The stamps of one queue's submissions.
pub(super) struct Spans {
_allocator: ID3D12CommandAllocator,
_heap: ID3D12QueryHeap,
_back: ID3D12Resource,
/// The mapped results, two a submission.
data: usize,
lists: Vec<ID3D12CommandList>,
ticks_per_ms: f64,
next: usize,
sums: Sums,
}
// SAFETY: free-threaded objects and a mapping only read behind a lock.
unsafe impl Send for Spans {}
/// What the stamps read so far add up to.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
struct Sums {
/// Submissions, ticks the card worked on them, ticks between them.
count: u64,
busy: u64,
between: u64,
/// Ticks of the longest one, and the last one's end.
longest: u64,
last: u64,
}
impl Sums {
/// A submission that ran from `start` to `end` (card ticks), after those
/// before it. The start's stamp may be of before the last one's end: the
/// part before that end is the last one's.
fn add(&mut self, start: u64, end: u64) {
if start == 0 || end < start {
return;
}
let start = start.max(self.last);
let took = end.saturating_sub(start);
if self.last != 0 {
self.between += start - self.last;
}
self.count += 1;
self.busy += took;
self.longest = self.longest.max(took);
self.last = end.max(self.last);
}
}
fn on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_SPANS").is_some_and(|v| v == "1"))
}
static SPANS_MADE: Mutex<Option<Option<Spans>>> = Mutex::new(None);
impl Host {
/// The lists that go in front of and behind a submission about to be
/// sent to the drawing queue, if stamps are asked for.
pub(super) fn span_lists(&self) -> Option<[ID3D12CommandList; 2]> {
if !on() {
return None;
}
let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner());
let spans = made
.get_or_insert_with(|| {
self.make_spans()
.inspect_err(|e| tracing::warn!(error = %e, "no stamps around submissions"))
.ok()
})
.as_mut()?;
let i = spans.next;
spans.next = (i + 1) % SPANS;
// The stamps of the submission that had these lists, that many
// submissions ago: long done.
// SAFETY: inside the mapping; written by the card at whole words.
let (start, end) = unsafe {
let at = (spans.data as *mut u64).add(2 * i);
let read = (at.read_volatile(), at.add(1).read_volatile());
at.write_volatile(0);
at.add(1).write_volatile(0);
read
};
spans.sums.add(start, end);
Some([spans.lists[2 * i].clone(), spans.lists[2 * i + 1].clone()])
}
fn make_spans(&self) -> windows::core::Result<Spans> {
let device = &self.device;
// SAFETY: plain object creation; lists of one allocator recorded one
// after the other.
unsafe {
let mut heap: Option<ID3D12QueryHeap> = None;
device.CreateQueryHeap(
&D3D12_QUERY_HEAP_DESC {
Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP,
Count: 2 * SPANS as u32,
NodeMask: 0,
},
&mut heap,
)?;
let heap = heap.ok_or_else(windows::core::Error::empty)?;
let back = self.read_back_buffer(16 * SPANS as u64).ok_or_else(windows::core::Error::empty)?;
let mut data = std::ptr::null_mut();
back.Map(0, None, Some(&mut data))?;
std::ptr::write_bytes(data.cast::<u8>(), 0, 16 * SPANS);
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
let mut lists = Vec::with_capacity(2 * SPANS);
for i in 0..2 * SPANS as u32 {
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?;
list.EndQuery(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i);
list.ResolveQueryData(&heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, &back, u64::from(i) * 8);
list.Close()?;
lists.push(list.cast()?);
}
Ok(Spans {
_allocator: allocator,
_heap: heap,
_back: back,
data: data as usize,
lists,
ticks_per_ms: self.queue.GetTimestampFrequency()? as f64 / 1000.0,
next: 0,
sums: Sums::default(),
})
}
}
}
/// The GPU timestamps the title was given since the last frame-rate line:
/// how many, how often a later one was 1 ms or more after the one before
/// (written with another submission), and where the first few lie.
static STAMPED: Mutex<(u64, u64, u64, Vec<usize>)> = Mutex::new((0, 0, 0, Vec::new()));
/// The title's GPU timestamp at `at` was given the value `now` (ticks of 10
/// ns).
pub(crate) fn stamped(at: usize, now: u64) {
if !on() {
return;
}
let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner());
s.0 += 1;
s.1 += u64::from(now.saturating_sub(s.2) > 100_000);
s.2 = now;
if s.3.len() < 64 && !s.3.contains(&at) {
s.3.push(at);
tracing::info!(address = format_args!("{at:#x}"), now, "a GPU timestamp of the title");
}
}
/// The viewports' sizes seen (each said once): whether the title draws its
/// scene at sizes of its choice.
pub(crate) fn viewport(width: u32, height: u32) {
if !on() || width < 1024 || height < 576 {
return;
}
static SEEN: Mutex<Vec<(u32, u32)>> = Mutex::new(Vec::new());
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
if seen.len() < 200 && !seen.contains(&(width, height)) {
seen.push((width, height));
tracing::info!(width, height, "a viewport of the title");
}
}
/// For the frame-rate line: what the stamps read since the last one say, per
/// frame (they are of some [`SPANS`] submissions ago).
pub(super) fn line(frames: f64) {
{
let mut s = STAMPED.lock().unwrap_or_else(|e| e.into_inner());
if s.0 > 0 {
tracing::info!(
"GPU timestamps the title asked for per frame: {:.1}, in {:.1} groups written at one time",
s.0 as f64 / frames,
s.1 as f64 / frames
);
}
(s.0, s.1) = (0, 0);
}
let mut made = SPANS_MADE.lock().unwrap_or_else(|e| e.into_inner());
let Some(Some(spans)) = made.as_mut() else {
return;
};
let last = spans.sums.last;
let s = std::mem::replace(&mut spans.sums, Sums { last, ..Sums::default() });
let ms = |ticks: u64| ticks as f64 / spans.ticks_per_ms / frames;
tracing::info!(
"the card's own stamps per frame: {:.1} submissions, working {:.1} ms, idle between them {:.1} ms, the longest {:.1} ms",
s.count as f64 / frames,
ms(s.busy),
ms(s.between),
s.longest as f64 / spans.ticks_per_ms
);
}
#[cfg(test)]
mod tests {
use super::Sums;
#[test]
fn submissions_add_up_without_counting_anything_twice() {
let mut s = Sums::default();
s.add(100, 150);
s.add(140, 200); // began before the last one ended
s.add(260, 270);
assert_eq!((s.count, s.busy, s.between, s.longest, s.last), (3, 110, 60, 50, 270));
// Never written, or nonsense: nothing.
s.add(0, 0);
s.add(300, 290);
assert_eq!(s.count, 3);
// Whole inside the last one.
s.add(265, 268);
assert_eq!((s.count, s.busy, s.between), (4, 110, 60));
}
}