Merge branch 'local/next' into night/cpu

This commit is contained in:
local committed 2026-11-25 09:03:29 -06:00
commit e7c7210657
5 files changed
+655 -26

No files matched your search

+49 -2
View File
@@ -61,7 +61,15 @@ static BOOK: Mutex<Option<Book>> = Mutex::new(None);
/// Root descriptors given by address lately: time, address, bytes.
static ROOTS: Mutex<VecDeque<(u64, u64, u64)>> = Mutex::new(VecDeque::new());
/// Tests that want the book.
#[cfg(test)]
static FORCED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
pub(crate) fn on() -> bool {
#[cfg(test)]
if FORCED.load(Ordering::Relaxed) {
return true;
}
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| {
std::env::var_os("VICTORY_BOOK").is_none_or(|v| v != "0")
@@ -334,10 +342,15 @@ pub(crate) fn block(heap: &ID3D12Heap, resource: &ID3D12Resource, offset: u64, b
let raw = heap.as_raw() as usize;
let now = crate::host::now_ms();
let id = with(|b| {
if b.by_object.contains_key(&raw) {
let at = b.by_object.get(&(object.as_raw() as usize)).and_then(|id| b.live.get(id))?.start;
// Known, unless the entry is of what had the pointer before.
if b.by_object
.get(&raw)
.and_then(|id| b.live.get(id))
.is_some_and(|e| at >= e.start && at - e.start < e.size)
{
return None;
}
let at = b.by_object.get(&(object.as_raw() as usize)).and_then(|id| b.live.get(id))?.start;
Some(b.add(raw, at.checked_sub(offset)?, bytes, "a block of textures".into(), now))
});
if let Some(id) = id {
@@ -652,6 +665,40 @@ mod tests {
}
/// Who has an address, and who had it, newest first.
/// A texture of the pool and its block stand in the book while they
/// live, and not after.
#[test]
fn a_pooled_texture_and_its_block_are_in_the_book() {
let Some(host) = crate::host::host() else { return };
FORCED.store(true, Ordering::Relaxed);
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 128,
Height: 256,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT(83),
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
// SAFETY: a valid description.
let texture = unsafe { crate::pool::texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) };
if let Some(texture) = texture {
let at = texture_address(&texture, &desc);
println!("address {at:x?}");
if let Some(at) = at {
let names = || with(|b| b.holders(at).iter().map(|e| e.what.clone()).collect::<Vec<_>>());
let found = names();
println!("held by {found:?}");
assert!(found.iter().any(|n| n.contains("a texture in a block")), "{found:?}");
assert!(found.iter().any(|n| n.contains("a block of textures")), "{found:?}");
drop(texture);
assert!(!names().iter().any(|n| n.contains("a texture in a block")));
}
}
FORCED.store(false, Ordering::Relaxed);
}
#[test]
fn the_book_knows_what_is_gone() {
let mut b = Book::default();
+154 -4
View File
@@ -202,6 +202,150 @@ fn vram_idle_for(video_memory: Option<[u64; 4]>, keep: bool) -> u64 {
}
}
/// Whether new memory is made resident, and waited for, before anything can
/// name it (on by default; `VICTORY_WAIT_RESIDENT=0`: as before). A heap or
/// resource of the default kind is resident once it is made, but its
/// mapping into the card's address space is work of the system's that runs
/// later: only lists sent after it wait for it. Lists sent before run on,
/// and read our descriptor heaps as they are: a slot that shows a texture
/// in a new block is a page fault for them until the block is mapped. The
/// device losses of the night of 2026-11-25 were that (run n08: the fault
/// lay in a texture made in the same tenth of a second, in a new block).
fn wait_resident() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_RESIDENT").is_none_or(|v| v != "0"))
}
/// The flag memory is made with that [`resident`] waits for.
pub(crate) fn not_resident() -> D3D12_HEAP_FLAGS {
if wait_resident() { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE }
}
/// A queue of its own that new memory is waited for with ([`mapped`]).
struct Aside {
queue: ID3D12CommandQueue,
list: ID3D12CommandList,
fence: ID3D12Fence,
event: windows::Win32::Foundation::HANDLE,
value: u64,
_keep: (ID3D12CommandAllocator, [ID3D12Resource; 2]),
}
// SAFETY: D3D12 objects are free-threaded, the event is waited on by one
// thread at a time (the lock).
unsafe impl Send for Aside {}
/// New memory of the card is mapped into its address space when this
/// returns: a copy of a few bytes is sent to a queue of ours after the
/// memory was made, which the system starts only when all mappings asked
/// for so far are done, and waited for. (`MakeResident` came back before
/// that: run n11 was lost as n08 was with it alone.) Best done off a hot
/// path: a tenth of a millisecond to some.
pub(crate) fn mapped(device: &ID3D12Device) -> windows::core::Result<()> {
static ASIDE: Mutex<Option<Aside>> = Mutex::new(None);
if !wait_resident() {
return Ok(());
}
let started = std::time::Instant::now();
let mut aside = ASIDE.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: plain object creation; the objects the list names are kept.
unsafe {
if aside.is_none() {
let buffer = |kind: D3D12_HEAP_TYPE, state: D3D12_RESOURCE_STATES| -> windows::core::Result<ID3D12Resource> {
let mut made: Option<ID3D12Resource> = None;
device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() },
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: 256,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
state,
None,
&mut made,
)?;
made.ok_or_else(windows::core::Error::empty)
};
let from = buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ)?;
let to = buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST)?;
let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_COPY,
..Default::default()
})?;
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
list.CopyBufferRegion(&to, 0, &from, 0, 16);
list.Close()?;
*aside = Some(Aside {
queue,
list: list.cast()?,
fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?,
event: CreateEventW(None, false, false, None)?,
value: 0,
_keep: (allocator, [from, to]),
});
}
let Some(a) = aside.as_mut() else { return Ok(()) };
a.queue.ExecuteCommandLists(&[Some(a.list.clone())]);
a.value += 1;
a.queue.Signal(&a.fence, a.value)?;
if a.fence.GetCompletedValue() < a.value {
a.fence.SetEventOnCompletion(a.value, a.event)?;
WaitForSingleObject(a.event, INFINITE);
}
}
let us = started.elapsed().as_micros() as u64;
MAPPED[0].fetch_add(1, Ordering::Relaxed);
MAPPED[1].fetch_add(us, Ordering::Relaxed);
MAPPED[2].fetch_max(us, Ordering::Relaxed);
let n = MAPPED[0].load(Ordering::Relaxed);
if n == 1 || n.is_multiple_of(200) {
tracing::info!(
"new card memory waited for until it is mapped (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms",
MAPPED[1].load(Ordering::Relaxed) as f64 / 1000.0,
MAPPED[2].load(Ordering::Relaxed) as f64 / 1000.0
);
}
Ok(())
}
/// Times, microseconds and the longest of [`mapped`].
static MAPPED: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
/// New memory (made with [`not_resident`]) is resident when this returns.
pub(crate) fn resident(device: &ID3D12Device, object: &impl Interface) -> windows::core::Result<()> {
if !wait_resident() {
return Ok(());
}
let started = std::time::Instant::now();
let object: ID3D12Pageable = object.cast()?;
// SAFETY: a live heap or resource of the device's.
let made = unsafe { device.MakeResident(&[Some(object)]) };
let us = started.elapsed().as_micros() as u64;
RESIDENT[0].fetch_add(1, Ordering::Relaxed);
RESIDENT[1].fetch_add(us, Ordering::Relaxed);
RESIDENT[2].fetch_max(us, Ordering::Relaxed);
static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = RESIDENT[0].load(Ordering::Relaxed);
if n >= 1000 * (SAID.load(Ordering::Relaxed) + 1) {
SAID.store(n / 1000, Ordering::Relaxed);
tracing::info!(
"new memory waited for (VICTORY_WAIT_RESIDENT=0: not), since the start: {n} times, {:.1} ms, the longest {:.1} ms",
RESIDENT[1].load(Ordering::Relaxed) as f64 / 1000.0,
RESIDENT[2].load(Ordering::Relaxed) as f64 / 1000.0
);
}
made
}
/// Times, microseconds and the longest of [`resident`].
static RESIDENT: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3];
/// Whether memory the card was given stays with it while there is room (on
/// by default; `VICTORY_KEEP_FREED=0`: it is given back as before). A shader
/// that reads past a view (a raw load through a typed, structured or
@@ -7762,7 +7906,7 @@ impl Host {
self.device
.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
not_resident(),
&desc,
D3D12_RESOURCE_STATE_GENERIC_READ,
None,
@@ -7770,6 +7914,7 @@ impl Host {
)
.and_then(|()| {
let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
resident(&self.device, b)?;
b.Map(0, None, Some(&mut data))
})
};
@@ -8466,7 +8611,7 @@ impl Host {
self.device
.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
not_resident(),
&desc,
D3D12_RESOURCE_STATE_COMMON,
None,
@@ -8474,6 +8619,8 @@ impl Host {
)
.and_then(|()| {
let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
resident(&self.device, b)?;
mapped(&self.device)?;
b.Map(0, None, Some(&mut data))
})
};
@@ -8553,7 +8700,7 @@ impl Host {
self.device
.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
not_resident(),
&desc,
D3D12_RESOURCE_STATE_COMMON,
None,
@@ -8561,6 +8708,8 @@ impl Host {
)
.and_then(|()| {
let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
resident(&self.device, b)?;
mapped(&self.device)?;
b.Map(0, None, Some(&mut data))
})
};
@@ -8601,7 +8750,7 @@ impl Host {
let made = unsafe {
self.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
not_resident(),
&desc,
D3D12_RESOURCE_STATE_COMMON,
None,
@@ -8612,6 +8761,7 @@ impl Host {
if let Some(b) = &buffer {
crate::book::made(b, || "an unordered access buffer".into());
}
let made = made.and_then(|()| buffer.as_ref().map_or(Ok(()), |b| resident(&self.device, b))).and_then(|()| mapped(&self.device));
match made {
Ok(()) => buffer,
Err(e) => {
+297
View File
@@ -1738,6 +1738,303 @@ void main(uint3 t : SV_DispatchThreadID) {
}
}
/// Whether lists on the card may read a texture of a block made after
/// they were sent, through a slot they read by index (ignored: a
/// measurement that loses the device, so each way runs in a process of
/// its own; `VICTORY_BENCH_S` seconds a way, 30; `VICTORY_BENCH_N` runs of
/// each, 3). Threads (`VICTORY_BENCH_THREADS`, 4) make blocks of 64 MiB, a texture in each and its
/// view, and copies the view into a slot; long dispatches that read all
/// the slots are always on the card.
#[test]
#[ignore]
fn new_blocks_under_readers() {
if let Ok(way) = std::env::var("VICTORY_BLOCK_WAY") {
return new_blocks(&way);
}
let times: u32 = std::env::var("VICTORY_BENCH_N").ok().and_then(|v| v.parse().ok()).unwrap_or(3);
let seconds = std::env::var("VICTORY_BENCH_S").unwrap_or_else(|_| "30".into());
// "never": never resident, what must lose the device. "fresh-": no
// block goes (280 of them, 18 GB), so each has addresses no block had.
for way in ["fresh-made", "fresh-waited", "fresh-enqueued", "made", "waited", "enqueued", "never"] {
let fresh = way.starts_with("fresh-");
for n in 0..if way == "never" { 1 } else if fresh { times * 5 } else { times } {
let out = std::process::Command::new(std::env::current_exe().unwrap())
.args(["indirect::tests::new_blocks_under_readers", "--exact", "--ignored", "--nocapture"])
.env("VICTORY_BLOCK_WAY", way)
.env("VICTORY_BENCH_S", if fresh { "3" } else { &seconds })
.output()
.unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let said = |what: &str| text.lines().find(|l| l.contains(what)).unwrap_or("(nothing said)").trim().to_owned();
println!("{way}, run {n}: {}; {} (exit {:?})", said("dispatches a"), said("blocks,"), out.status.code());
}
}
}
fn new_blocks(way: &str) {
let Some(gpu) = WarpHarness::on(false) else {
println!("no card: 0 blocks,");
return;
};
let (way, fresh) = match way.strip_prefix("fresh-") {
Some(way) => (way, true),
None => (way, false),
};
const SLOTS: usize = 64;
const BLOCK: u64 = 64 << 20;
let seconds = std::env::var("VICTORY_BENCH_S").ok().and_then(|v| v.parse().ok()).unwrap_or(30u64);
const SOURCE: &str = r#"
#define RS "DescriptorTable(SRV(t0,numDescriptors=64,flags=DESCRIPTORS_VOLATILE|DATA_VOLATILE)), UAV(u0)"
Texture2D<float4> t[64] : register(t0);
RWByteAddressBuffer o : register(u0);
[RootSignature(RS)]
[numthreads(64, 1, 1)]
void main(uint3 g : SV_GroupID, uint i : SV_GroupIndex) {
uint which = g.x & 63;
float4 c = 0;
for (uint k = 0; k < 8; k++)
c += t[(which + k * 8) & 63].Load(int3((i + k * 13) & 127, (g.y + k * 29) & 255, 0));
if (c.x < -1) o.Store(0, 1);
}
"#;
let pass = compile_cs(&gpu.device, SOURCE).expect("the pass must compile");
// SAFETY: plain heap creation.
let heap = |visible: bool, n: u32| -> ID3D12DescriptorHeap {
unsafe {
gpu.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV,
NumDescriptors: n,
Flags: if visible { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE } else { D3D12_DESCRIPTOR_HEAP_FLAG_NONE },
NodeMask: 0,
})
}
.unwrap()
};
let (shown, beside) = (heap(true, SLOTS as u32), heap(false, 65));
// SAFETY: live heaps.
let (to, from, step) = unsafe {
(
shown.GetCPUDescriptorHandleForHeapStart().ptr,
beside.GetCPUDescriptorHandleForHeapStart().ptr,
gpu.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize,
)
};
let null = D3D12_SHADER_RESOURCE_VIEW_DESC {
Format: DXGI_FORMAT(28),
ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
Texture2D: D3D12_TEX2D_SRV { MipLevels: 1, ..Default::default() },
},
};
let slot = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to + i * step };
let own = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from + i * step };
// SAFETY: slots of our heaps.
unsafe {
gpu.device.CreateShaderResourceView(None::<&ID3D12Resource>, Some(&null), own(0));
for i in 0..SLOTS {
gpu.device.CopyDescriptorsSimple(1, slot(i), own(0), D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
}
let (_out, _, out_gpu) = gpu.shared_buffer(1 << 12);
// SAFETY: a live heap.
let table = unsafe { shown.GetGPUDescriptorHandleForHeapStart() };
let list = |dispatches: u32| -> (ID3D12CommandAllocator, ID3D12GraphicsCommandList) {
// SAFETY: plain creation and recording.
unsafe {
let allocator: ID3D12CommandAllocator =
gpu.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
let list: ID3D12GraphicsCommandList =
gpu.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
list.SetDescriptorHeaps(&[Some(shown.clone())]);
list.SetComputeRootSignature(&pass.root);
list.SetPipelineState(&pass.pso);
list.SetComputeRootDescriptorTable(0, table);
list.SetComputeRootUnorderedAccessView(1, out_gpu);
for _ in 0..dispatches {
list.Dispatch(1024, 64, 1);
}
list.Close().unwrap();
(allocator, list)
}
};
// Lists of some 5 ms, always five sent: some run while a slot changes.
let mut sent = 0u64;
let mut dispatches = 8;
let ms = loop {
let one = list(dispatches);
let began = std::time::Instant::now();
// SAFETY: a closed list of ours; waited for.
unsafe {
gpu.queue.ExecuteCommandLists(&[Some(one.1.cast().unwrap())]);
sent += 1;
gpu.queue.Signal(&gpu.fence, sent).unwrap();
let _ = gpu.fence.SetEventOnCompletion(sent, gpu.event);
WaitForSingleObject(gpu.event, 10_000);
}
let ms = began.elapsed().as_secs_f64() * 1e3;
if ms >= 4.0 || dispatches >= 1 << 14 {
break ms;
}
dispatches *= 2;
};
println!("{dispatches} dispatches a list, {ms:.1} ms each");
let lists: Vec<_> = (0..6).map(|_| list(dispatches)).collect();
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::SeqCst};
let sent = AtomicU64::new(sent);
let stop = AtomicBool::new(false);
// Blocks; microseconds making a block, the longest; waiting, the longest.
let counts: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5];
let threads: usize = std::env::var("VICTORY_BENCH_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4);
let started = std::time::Instant::now();
let lost = std::thread::scope(|scope| {
for thread in 0..threads {
let (device, fence) = (gpu.device.clone(), gpu.fence.clone());
let (sent, stop, counts) = (&sent, &stop, &counts);
scope.spawn(move || {
// Slots of its own, and a staged view of its own.
let mine = SLOTS / threads;
let slot = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to + (thread * mine + i) * step };
let own = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from + i * step };
let wait = way != "made";
let mut alive: Vec<(ID3D12Heap, ID3D12Resource)> = Vec::new();
let mut n = 0u64;
while !stop.load(SeqCst) {
// SAFETY: plain creation; slots of our heaps, this thread's.
unsafe {
let mut block: Option<ID3D12Heap> = None;
let flags = D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES
| if wait { D3D12_HEAP_FLAG_CREATE_NOT_RESIDENT } else { D3D12_HEAP_FLAG_NONE };
let heap = D3D12_HEAP_DESC {
SizeInBytes: BLOCK,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Alignment: 0,
Flags: flags,
};
let began = std::time::Instant::now();
if device.CreateHeap(&heap, &mut block).is_err() {
break;
}
let us = began.elapsed().as_micros() as u64;
counts[1].fetch_add(us, SeqCst);
counts[2].fetch_max(us, SeqCst);
let block = block.unwrap();
let pageable: ID3D12Pageable = block.cast().unwrap();
let began = std::time::Instant::now();
if way == "waited" && device.MakeResident(&[Some(pageable.clone())]).is_err() {
break;
}
if way == "enqueued" {
let device: ID3D12Device3 = device.cast().unwrap();
let paged: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
let asked =
device.EnqueueMakeResident(D3D12_RESIDENCY_FLAG_NONE, &[Some(pageable)], &paged, 1);
if asked.is_err() {
break;
}
while paged.GetCompletedValue() < 1 {
std::hint::spin_loop();
}
}
let us = began.elapsed().as_micros() as u64;
counts[3].fetch_add(us, SeqCst);
counts[4].fetch_max(us, SeqCst);
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 128,
Height: 256,
DepthOrArraySize: 1,
MipLevels: 1,
Format: DXGI_FORMAT(28),
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
let mut texture: Option<ID3D12Resource> = None;
// Somewhere in the block, as the pool's pieces are.
let at = (n * 7 % 900) << 16;
if device
.CreatePlacedResource(&block, at, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut texture)
.is_err()
{
break;
}
let texture = texture.unwrap();
let kind = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
device.CreateShaderResourceView(&texture, None, own(1 + thread));
device.CopyDescriptorsSimple(1, slot(n as usize % mine), own(1 + thread), kind);
alive.push((block, texture));
n += 1;
counts[0].fetch_add(1, SeqCst);
if fresh {
if alive.len() >= 280 / threads {
break;
}
} else if alive.len() >= 24 {
// Nothing shows or reads them any more when they go.
for i in 0..mine {
device.CopyDescriptorsSimple(1, slot(i), own(0), kind);
}
let until = sent.load(SeqCst) + 1;
while fence.GetCompletedValue() < until && !stop.load(SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(1));
}
if fence.GetCompletedValue() < until {
break;
}
alive.clear();
}
}
}
// The lists sent last may read them: the process goes next.
std::mem::forget(alive);
});
}
let lost = loop {
// SAFETY: closed lists of ours, each run again only when it has run.
unsafe {
let done = gpu.fence.GetCompletedValue();
if done == u64::MAX || gpu.device.GetDeviceRemovedReason().is_err() {
break true;
}
while sent.load(SeqCst) < done + 5 {
let n = sent.load(SeqCst);
let list: ID3D12CommandList = lists[(n % 6) as usize].1.cast().unwrap();
gpu.queue.ExecuteCommandLists(&[Some(list)]);
let _ = gpu.queue.Signal(&gpu.fence, n + 1);
sent.store(n + 1, SeqCst);
}
}
if started.elapsed().as_secs() >= seconds {
break false;
}
std::thread::sleep(std::time::Duration::from_micros(300));
};
stop.store(true, SeqCst);
lost
});
let sent = sent.into_inner();
let counts = counts.map(|c| c.into_inner());
let blocks = counts[0];
// SAFETY: a plain query.
let reason = unsafe { gpu.device.GetDeviceRemovedReason() };
println!(
"{blocks} blocks, {sent} lists in {:.1} s; making {:.0} us a block, the longest {}; waiting {:.0} us, the longest {}; {}",
started.elapsed().as_secs_f64(),
counts[1] as f64 / blocks.max(1) as f64,
counts[2],
counts[3] as f64 / blocks.max(1) as f64,
counts[4],
if lost { format!("LOST: {reason:?}") } else { "the device lives".to_owned() }
);
if !lost {
// SAFETY: waits for what was sent.
unsafe {
let _ = gpu.fence.SetEventOnCompletion(sent, gpu.event);
WaitForSingleObject(gpu.event, 10_000);
}
}
}
/// The clamp compiles with the system's compiler and the host takes it.
#[test]
fn argument_clamp_builds() {
+141 -16
View File
@@ -25,7 +25,8 @@ use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::{GUID, HRESULT, IUnknown, Interface};
/// Bytes of a block; pieces of more than half of one are not pooled.
/// Bytes of a block; pieces of more than half of one are not pooled (with
/// blocks made ahead, [`ahead`]: of more than one).
const BLOCK: u64 = 64 << 20;
/// Blocks with nothing in them that are kept.
const SPARE: usize = 2;
@@ -65,6 +66,49 @@ pub(crate) fn on() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0"))
}
/// How many blocks of textures are made ahead, so that one has been there
/// for a while when its first piece is taken (`VICTORY_RIPE_BLOCKS`, 12;
/// 0: none, and new blocks are used at once, as before).
///
/// A page fault of lists already on the card, in a texture made the same
/// tenth of a second as the first piece of a block made for it, lost the
/// device in runs n08 and n11 (2026-11-25): the title gives a slot that
/// those lists read by index a new texture. Why the card does not have the
/// new block's addresses yet is not known (n11 waited for `MakeResident`;
/// `indirect::tests::new_blocks_under_readers` never loses it). A block that
/// every submission begun before its making has left behind ([`Ripe`]) has
/// no such lists: pieces are cut from those first.
fn ahead() -> usize {
static AHEAD: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
*AHEAD.get_or_init(|| std::env::var("VICTORY_RIPE_BLOCKS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12))
}
/// Submissions begun and finished ([`crate::host::submissions`]), and how
/// many blocks to make ahead (0: every block is ripe at once).
#[derive(Clone, Copy)]
struct Ripe {
started: u64,
finished: u64,
ahead: usize,
}
impl Ripe {
const ALL: Ripe = Ripe { started: 0, finished: 0, ahead: 0 };
fn now() -> Ripe {
let (started, finished) = crate::host::submissions();
// Not more than are kept ([`room`]): they would go and be made again.
Ripe { started, finished, ahead: ahead().min(SPARES.load(Ordering::Relaxed)) }
}
fn is<B>(self, block: &Block<B>) -> bool {
self.ahead == 0 || block.made <= self.finished
}
}
/// Pieces cut from blocks that were not ripe, for want of a ripe one.
static UNRIPE: AtomicU64 = AtomicU64::new(0);
/// The free ranges of a block: start and length, never two that touch.
struct Ranges(BTreeMap<u64, u64>);
@@ -121,6 +165,8 @@ struct Block<B> {
/// The end of the highest piece ever taken: above it the memory is as
/// it was made (zeros).
used_to: u64,
/// The newest submission begun when it was made ([`Ripe`]).
made: u64,
}
struct Pool<B> {
@@ -140,42 +186,82 @@ impl<B: Clone> Pool<B> {
/// A piece of `len` bytes and the memory it lies in, and whether that
/// part was ever used before; `make` makes a block when none has room.
fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnOnce() -> Option<B>) -> Option<(Piece, B, bool)> {
if len == 0 || len > BLOCK / 2 {
fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnMut() -> Option<B>) -> Option<(Piece, B, bool)> {
self.take_ripe(len, align, now, Ripe::ALL, make)
}
/// The same from a block that is ripe, if one has room; `make` makes one
/// ahead too, when few are empty.
fn take_ripe(
&mut self,
len: u64,
align: u64,
now: u64,
ripe: Ripe,
mut make: impl FnMut() -> Option<B>,
) -> Option<(Piece, B, bool)> {
// With blocks made ahead, what would be an allocation of its own (and
// new when the card first reads it) lies in one of those too.
if len == 0 || len > if ripe.ahead > 0 { BLOCK } else { BLOCK / 2 } {
return None;
}
self.rested(now);
let mut found = None;
for (i, block) in self.blocks.iter_mut().enumerate() {
if let Some(block) = block
&& ripe.is(block)
&& let Some(start) = block.free.take(len, align)
{
found = Some((i, start));
break;
}
}
if found.is_none() && ripe.ahead > 0 {
// The one that has been there the longest.
let mut unripe: Vec<(u64, usize)> =
self.blocks.iter().enumerate().filter_map(|(i, b)| Some((b.as_ref()?.made, i))).collect();
unripe.sort_unstable();
found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?)));
}
let (i, start) = match found {
Some(found) => found,
None => {
let mut block = Block { memory: make()?, free: Ranges::new(BLOCK), used_to: 0 };
let start = block.free.take(len, align)?;
let i = match self.blocks.iter().position(Option::is_none) {
Some(i) => i,
None => {
self.blocks.push(None);
self.blocks.len() - 1
}
};
self.blocks[i] = Some(block);
(i, start)
let i = self.add(make()?, ripe.started);
(i, self.blocks[i].as_mut()?.free.take(len, align)?)
}
};
if ripe.ahead > 0 {
if !ripe.is(self.blocks[i].as_ref()?) {
let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1;
if n.is_power_of_two() {
tracing::info!("textures cut from blocks made while lists ran that still run: {n}");
}
}
let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count();
if empty < ripe.ahead
&& let Some(memory) = make()
{
self.add(memory, ripe.started);
}
}
let block = self.blocks[i].as_mut()?;
let again = start < block.used_to;
block.used_to = block.used_to.max(start + len);
Some((Piece { block: i, start, len }, block.memory.clone(), again))
}
fn add(&mut self, memory: B, made: u64) -> usize {
let i = match self.blocks.iter().position(Option::is_none) {
Some(i) => i,
None => {
self.blocks.push(None);
self.blocks.len() - 1
}
};
self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made });
i
}
fn give(&mut self, piece: Piece, now: u64) {
self.resting.push_back((now + REST, piece));
}
@@ -369,18 +455,24 @@ pub(crate) unsafe fn texture(
if info.SizeInBytes == u64::MAX {
return None;
}
let (piece, heap, _) = lock(&TEXTURES).take(info.SizeInBytes, info.Alignment.max(1), now(), || {
let (piece, heap, _) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || {
let desc = D3D12_HEAP_DESC {
SizeInBytes: BLOCK,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Alignment: 0,
Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES,
Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(),
};
let mut heap: Option<ID3D12Heap> = None;
// SAFETY: plain creation.
if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
tracing::warn!(error = %e, "no block of texture memory");
}
if let Some(h) = &heap
&& let Err(e) = crate::host::resident(device, h).and_then(|()| crate::host::mapped(device))
{
tracing::warn!(error = %e, "a block of texture memory is not resident");
return None;
}
heap
})?;
let mut made: Option<ID3D12Resource> = None;
@@ -467,6 +559,39 @@ mod tests {
assert!(none.take(65536, 65536, 0, || None).is_none());
}
#[test]
fn pieces_come_from_blocks_older_than_the_lists_that_run() {
let mut pool: Pool<u64> = Pool::new(SPARE_KEPT);
let made = std::cell::Cell::new(0);
let make = || {
made.set(made.get() + 1);
Some(made.get())
};
let at = |started, finished| Ripe { started, finished, ahead: 2 };
let take = |pool: &mut Pool<u64>, ripe| pool.take_ripe(BLOCK / 2, 65536, 0, ripe, make).unwrap().1;
// Nothing runs: at once, and two are made ahead, one a time.
assert_eq!(take(&mut pool, at(0, 0)), 1);
assert_eq!(made.get(), 2);
assert_eq!(take(&mut pool, at(0, 0)), 1);
assert_eq!(made.get(), 3);
// 4 is made while submission 5 runs.
assert_eq!(take(&mut pool, at(5, 4)), 2);
assert_eq!(made.get(), 4);
assert_eq!(take(&mut pool, at(5, 4)), 2);
assert_eq!(take(&mut pool, at(6, 4)), 3);
assert_eq!(take(&mut pool, at(6, 4)), 3);
// None is ripe: the oldest; it is ripe once 5 has finished.
assert_eq!(take(&mut pool, at(7, 4)), 4);
assert_eq!(take(&mut pool, at(7, 5)), 4);
// A whole block's worth too.
assert_eq!(pool.take_ripe(BLOCK, 65536, 0, at(8, 7), make).unwrap().1, 5);
// Off: the first with room, whatever its age, none ahead.
let n = made.get();
assert_eq!(pool.take(BLOCK / 2, 65536, 0, make).unwrap().1, 6);
assert_eq!(made.get(), n);
assert!(pool.take(BLOCK, 65536, 0, make).is_none());
}
/// A pooled texture's piece comes back when its last reference goes, not
/// before; its staging piece begins as zeros.
#[test]
+14 -4
View File
@@ -495,7 +495,7 @@ fn twin_texture(
let made = unsafe {
host.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
crate::host::not_resident(),
(&raw const d).cast(),
D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32),
None,
@@ -509,6 +509,7 @@ fn twin_texture(
TWINS[1].fetch_add(1, Relaxed);
return None;
};
let _ = crate::host::resident(&host.device, &texture);
crate::host::name(&texture, || {
format!("depth twin {}x{} f{}", d.width, d.height, d.format)
});
@@ -558,7 +559,7 @@ fn twin_texture(
let made = unsafe {
host.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
crate::host::not_resident(),
(&raw const d).cast(),
D3D12_RESOURCE_STATES(UNORDERED_ACCESS as i32),
None,
@@ -569,6 +570,7 @@ fn twin_texture(
tracing::warn!(error = %e, desc = ?d, "no twin for a depth plane");
}
texture.map(|texture| {
let _ = crate::host::resident(&host.device, &texture);
crate::host::name(&texture, || {
format!("depth plane twin {}x{} f{}", d.width, d.height, d.format)
});
@@ -2507,7 +2509,7 @@ fn host_texture_as(
unsafe {
host.device.CreateCommittedResource(
&heap,
D3D12_HEAP_FLAG_NONE,
crate::host::not_resident(),
(&raw const d).cast(),
D3D12_RESOURCE_STATES(
crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32,
@@ -2518,9 +2520,17 @@ fn host_texture_as(
)
}
};
if let Err(e) = made {
if let Err(e) = &made {
tracing::warn!(error = %e, desc = ?d, reserved, "no host texture");
}
if !reserved
&& made.is_ok()
&& let Some(t) = &texture
&& let Err(e) = crate::host::resident(&host.device, t).and_then(|()| crate::host::mapped(&host.device))
{
tracing::warn!(error = %e, desc = ?d, "a host texture is not resident");
texture = None;
}
if let Some(t) = &texture {
crate::host::name(t, || {
format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags)