Merge commit 'f61ecf3b' into night/light
# Conflicts: # crates/victory-gpu/src/shadow.rs
This commit is contained in:
commit
6553e304b3
20 files changed
+1452
-96
No files matched your search
@@ -81,6 +81,16 @@ pub(crate) struct Replay {
|
||||
/// Each list sent on its own, and waited for.
|
||||
#[arg(long)]
|
||||
wait_lists: bool,
|
||||
/// Milliseconds to wait after sending each submission: the card stands
|
||||
/// idle between them, as it does while the title prepares the next.
|
||||
#[arg(long, default_value_t = 0.0)]
|
||||
pace: f64,
|
||||
/// Keep the card's clocks up meanwhile (VICTORY_CARD_AWAKE=1).
|
||||
#[arg(long)]
|
||||
awake: bool,
|
||||
/// The system's breadcrumbs after every command (VICTORY_D3D12_DRED=light).
|
||||
#[arg(long)]
|
||||
breadcrumbs: bool,
|
||||
/// Run only these lists, by their place in the frame (`3..7`, or `5`);
|
||||
/// of the others only barriers.
|
||||
#[arg(long)]
|
||||
@@ -255,11 +265,14 @@ pub(crate) fn run(r: Replay) -> Result<()> {
|
||||
merge: !r.no_merge,
|
||||
wait_all: r.wait_all,
|
||||
wait_lists: r.wait_lists,
|
||||
pace: r.pace,
|
||||
awake: r.awake,
|
||||
only,
|
||||
until,
|
||||
skip_shaders: r.skip_shader,
|
||||
compare: r.compare,
|
||||
debug: r.debug_layer,
|
||||
breadcrumbs: r.breadcrumbs,
|
||||
};
|
||||
if let Some(text) = &r.slots {
|
||||
let (list, command) = text
|
||||
|
||||
@@ -1163,7 +1163,7 @@ impl HostHeap {
|
||||
dynamic: extra,
|
||||
sampler,
|
||||
raw,
|
||||
twins: (0..if raw == 0 { 0 } else { count }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(),
|
||||
twins: (0..if raw == 0 { 0 } else { count + extra }).map(|_| std::sync::atomic::AtomicBool::new(false)).collect(),
|
||||
made: Mutex::new(vec![0; count as usize]),
|
||||
copied: Mutex::new(Vec::new()),
|
||||
waiting: Mutex::default(),
|
||||
@@ -2031,11 +2031,12 @@ impl HostHeap {
|
||||
/// Makes slot `index` (a dynamic one) from `view`; a null view if the
|
||||
/// host cannot.
|
||||
pub(crate) fn make_at(&self, index: u32, view: &View) {
|
||||
let kept = make(view, self.at(index));
|
||||
let kept = make_twinned(view, self.at(index), self.twin(index));
|
||||
if kept.is_none() {
|
||||
null_for(view, self.at(index));
|
||||
}
|
||||
self.put(index);
|
||||
self.twin_made(index, kept.is_some() && twinned(view));
|
||||
self.keep(index, kept.flatten());
|
||||
}
|
||||
|
||||
@@ -2047,15 +2048,28 @@ impl HostHeap {
|
||||
null_view(self.at(index));
|
||||
self.put(index);
|
||||
}
|
||||
self.clear_twin(index);
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
/// Where the raw twin of title slot `index` is.
|
||||
/// Where the raw twin of slot `index` is made.
|
||||
fn twin(&self, index: u32) -> Option<D3D12_CPU_DESCRIPTOR_HANDLE> {
|
||||
(index < self.twins.len() as u32).then(|| staged(self.sampler, 1).unwrap_or_else(|| self.cpu(self.raw + index)))
|
||||
}
|
||||
|
||||
/// The raw twin of title slot `index` is a null view again.
|
||||
/// The raw twin of slot `index` was made by this thread ([`make_twinned`]),
|
||||
/// or is a null view if it was not.
|
||||
fn twin_made(&self, index: u32, made: bool) {
|
||||
if !made {
|
||||
return self.clear_twin(index);
|
||||
}
|
||||
if let Some(shown) = self.twins.get(index as usize) {
|
||||
self.put_twin(index);
|
||||
shown.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw twin of slot `index` is a null view again.
|
||||
fn clear_twin(&self, index: u32) {
|
||||
if let Some(made) = self.twins.get(index as usize)
|
||||
&& made.swap(false, std::sync::atomic::Ordering::Relaxed)
|
||||
@@ -2108,6 +2122,8 @@ impl HostHeap {
|
||||
.CreateShaderResourceView(buffer, Some(&desc), self.at(index))
|
||||
};
|
||||
self.put(index);
|
||||
// (Bound by its handle, not read by index.)
|
||||
self.clear_twin(index);
|
||||
self.keep(index, Some(buffer.clone()));
|
||||
}
|
||||
|
||||
@@ -2116,6 +2132,7 @@ impl HostHeap {
|
||||
pub(crate) fn null_raw_at(&self, index: u32) {
|
||||
null_buffer_view(self.at(index));
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
@@ -2149,6 +2166,7 @@ impl HostHeap {
|
||||
)
|
||||
};
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.keep(index, Some(buffer.clone()));
|
||||
}
|
||||
|
||||
@@ -2177,6 +2195,7 @@ impl HostHeap {
|
||||
)
|
||||
};
|
||||
self.put(index);
|
||||
self.clear_twin(index);
|
||||
self.keep(index, None);
|
||||
}
|
||||
|
||||
@@ -2212,6 +2231,28 @@ impl HostHeap {
|
||||
.CreateConstantBufferView(Some(&desc), self.at(index))
|
||||
};
|
||||
self.put(index);
|
||||
// A program that reads it as raw bytes reads its twin.
|
||||
let twin = self.twin(index).filter(|_| desc.SizeInBytes > 0);
|
||||
if let Some(twin) = twin {
|
||||
// SAFETY: a live buffer that holds the range.
|
||||
let first = (gpu - unsafe { buffer.GetGPUVirtualAddress() }) / 4;
|
||||
let raw = D3D12_SHADER_RESOURCE_VIEW_DESC {
|
||||
Format: DXGI_FORMAT_R32_TYPELESS,
|
||||
ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
|
||||
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
|
||||
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
|
||||
Buffer: D3D12_BUFFER_SRV {
|
||||
FirstElement: first,
|
||||
NumElements: desc.SizeInBytes / 4,
|
||||
StructureByteStride: 0,
|
||||
Flags: D3D12_BUFFER_SRV_FLAG_RAW,
|
||||
},
|
||||
},
|
||||
};
|
||||
// SAFETY: as above, and a slot of our heaps.
|
||||
unsafe { host.device.CreateShaderResourceView(buffer, Some(&raw), twin) };
|
||||
}
|
||||
self.twin_made(index, twin.is_some());
|
||||
// After the descriptor: what it showed is let go when nothing shows
|
||||
// it any more.
|
||||
self.keep(index, holds.then(|| buffer.clone()));
|
||||
@@ -2370,7 +2411,6 @@ impl HostHeap {
|
||||
// title released): nothing to read.
|
||||
if made[index as usize] != 0 {
|
||||
made[index as usize] = 0;
|
||||
self.clear_twin(index);
|
||||
self.make_null(index);
|
||||
let _ = self.note_buffer(index, None, false);
|
||||
} else if for_draw {
|
||||
@@ -2424,14 +2464,7 @@ impl HostHeap {
|
||||
if kept.is_some() || !self.sampler {
|
||||
self.put(index);
|
||||
}
|
||||
if kept.is_some() && twinned(&view) {
|
||||
self.put_twin(index);
|
||||
if let Some(made) = self.twins.get(index as usize) {
|
||||
made.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
} else {
|
||||
self.clear_twin(index);
|
||||
}
|
||||
self.twin_made(index, kept.is_some() && twinned(&view));
|
||||
self.keep(index, kept.flatten());
|
||||
}
|
||||
Some(view)
|
||||
|
||||
@@ -866,6 +866,10 @@ impl State {
|
||||
/// Viewports, scissors, the blend factor and the stencil reference: set
|
||||
/// on the host list at once, and kept for [`State::replay`].
|
||||
pub(crate) fn set_viewports(&mut self, list: &HostList, viewports: &[D3D12_VIEWPORT]) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some(v) = viewports.first() {
|
||||
crate::host::spans::viewport(v.Width as u32, v.Height as u32);
|
||||
}
|
||||
self.viewports.clear();
|
||||
self.viewports.extend_from_slice(viewports);
|
||||
crate::draw::viewports(list, viewports);
|
||||
|
||||
@@ -3227,10 +3227,13 @@ fn late_line(frames: f64) {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) mod awake;
|
||||
mod card_steps;
|
||||
pub(crate) mod indirects;
|
||||
mod place;
|
||||
mod send;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
pub(crate) mod spans;
|
||||
mod torn;
|
||||
pub(crate) mod upcheck;
|
||||
|
||||
@@ -5090,11 +5093,17 @@ impl Host {
|
||||
let prepared = std::time::Instant::now();
|
||||
if late {
|
||||
*submitted += 1;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if let Some([front, behind]) = self.span_lists() {
|
||||
lists.insert(0, Some(front));
|
||||
lists.push(Some(behind));
|
||||
}
|
||||
// SAFETY: closed lists; the fence is ours.
|
||||
let signalled = unsafe {
|
||||
self.queue.ExecuteCommandLists(&lists);
|
||||
self.queue.Signal(&self.fence, *submitted)
|
||||
};
|
||||
awake::sent(&self.device);
|
||||
self.card_sent();
|
||||
if let Err(e) = signalled {
|
||||
fail(format_args!("a submission sent ahead could not be followed by a signal ({e})"));
|
||||
@@ -7434,6 +7443,8 @@ impl Meter {
|
||||
crate::descriptor::sync_line(frames);
|
||||
late_line(frames);
|
||||
card_clock_line(frames, ms);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
spans::line(frames);
|
||||
crate::shadow::back_line(frames);
|
||||
#[cfg(feature = "diagnostics")]
|
||||
split_line(frames);
|
||||
@@ -8021,6 +8032,87 @@ impl Host {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether buffers can lie in the card's memory and be mapped by the CPU
|
||||
/// (`D3D12_HEAP_TYPE_GPU_UPLOAD`: a resizable BAR, and a system and driver
|
||||
/// that offer it); logged once.
|
||||
pub(crate) fn mapped_card_memory(&self) -> bool {
|
||||
static THERE: OnceLock<bool> = OnceLock::new();
|
||||
*THERE.get_or_init(|| {
|
||||
let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS16::default();
|
||||
// SAFETY: writes `options` of the given size.
|
||||
let ok = unsafe {
|
||||
self.device
|
||||
.CheckFeatureSupport(
|
||||
D3D12_FEATURE_D3D12_OPTIONS16,
|
||||
(&raw mut options).cast(),
|
||||
size_of_val(&options) as u32,
|
||||
)
|
||||
.is_ok()
|
||||
};
|
||||
let supported = ok && options.GPUUploadHeapSupported.as_bool();
|
||||
tracing::info!(supported, "card memory the CPU maps");
|
||||
supported
|
||||
})
|
||||
}
|
||||
|
||||
/// A buffer in the card's own memory that the CPU maps, shaders read and
|
||||
/// (with `written`) may write. The CPU should only write it: a read of the
|
||||
/// mapping crosses the bus a few bytes at a time.
|
||||
pub(crate) fn mapped_card_buffer(&self, size: u64, written: bool) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
if !self.mapped_card_memory() {
|
||||
return None;
|
||||
}
|
||||
MADE[4].fetch_add(1, Ordering::Relaxed);
|
||||
MADE[5].fetch_add(size, Ordering::Relaxed);
|
||||
let heap = D3D12_HEAP_PROPERTIES {
|
||||
Type: D3D12_HEAP_TYPE_GPU_UPLOAD,
|
||||
..Default::default()
|
||||
};
|
||||
let desc = D3D12_RESOURCE_DESC {
|
||||
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
|
||||
Width: size.max(1),
|
||||
Height: 1,
|
||||
DepthOrArraySize: 1,
|
||||
MipLevels: 1,
|
||||
SampleDesc: DXGI_SAMPLE_DESC {
|
||||
Count: 1,
|
||||
Quality: 0,
|
||||
},
|
||||
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
|
||||
Flags: if written {
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS
|
||||
} else {
|
||||
D3D12_RESOURCE_FLAG_NONE
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut buffer: Option<ID3D12Resource> = None;
|
||||
let mut data = std::ptr::null_mut();
|
||||
// SAFETY: plain creation and mapping of a CPU-visible buffer.
|
||||
let made = unsafe {
|
||||
self.device
|
||||
.CreateCommittedResource(
|
||||
&heap,
|
||||
D3D12_HEAP_FLAG_NONE,
|
||||
&desc,
|
||||
D3D12_RESOURCE_STATE_COMMON,
|
||||
None,
|
||||
&mut buffer,
|
||||
)
|
||||
.and_then(|()| {
|
||||
let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
|
||||
b.Map(0, None, Some(&mut data))
|
||||
})
|
||||
};
|
||||
match made {
|
||||
Ok(()) => Some((buffer?, data.cast())),
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, size, "no buffer in card memory the CPU maps");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A device-local buffer shaders may write (unordered access) and indirect
|
||||
/// execution may read, starting in the common state.
|
||||
pub(crate) fn uav_buffer(&self, size: u64) -> Option<ID3D12Resource> {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -88,8 +88,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> {
|
||||
{
|
||||
@@ -100,7 +114,11 @@ fn memory(host: &Host, size: u64) -> Option<Memory> {
|
||||
}
|
||||
}
|
||||
let size = size.next_multiple_of(8 << 20);
|
||||
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,
|
||||
@@ -114,7 +132,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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,7 @@
|
||||
//! run empty, saturating without 32-bit wraparound so a list of thousands of
|
||||
//! garbage records cannot run for seconds either.
|
||||
//!
|
||||
//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
|
||||
//! shortcut: the bounds (below 2^23 vertices an instance, 2^26 vertex instances, 65,535
|
||||
//! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh
|
||||
//! dispatches, the budget) cut legitimate work beyond them; raise them if
|
||||
//! the title needs more.
|
||||
@@ -62,6 +62,8 @@ RWByteAddressBuffer dst_args : register(u0);
|
||||
// records run empty.
|
||||
RWByteAddressBuffer budget : register(u1);
|
||||
static const uint BUDGET = 1u << 27;
|
||||
// The vertices or indices an instance from which a draw record runs empty.
|
||||
static const uint MOST_DRAW = 1u << 23;
|
||||
// Groups of one dispatch; more run empty.
|
||||
static const uint GROUPS = 1u << 20;
|
||||
// Each group charges the budget once: the costs of its records go here,
|
||||
@@ -102,7 +104,14 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
if (ahead && (want.x > (1u << 24) || want.y > (1u << 24))) {
|
||||
want = uint2(0, 0);
|
||||
}
|
||||
uint count = min(want.x, 1u << 24);
|
||||
// A record of MOST_DRAW vertices or indices an instance, or more, is
|
||||
// no draw of the title's (a slot it has not filled): it runs empty
|
||||
// and charges nothing (victory-fork f85101b6, its window checker
|
||||
// found 90 of 2^24 vertices in one list).
|
||||
if (want.x >= MOST_DRAW) {
|
||||
want = uint2(0, 0);
|
||||
}
|
||||
uint count = want.x;
|
||||
uint instances = min(want.y, (1u << 26) / max(count, 1u));
|
||||
cost = count * instances;
|
||||
draw_counts = uint2(count, instances);
|
||||
@@ -119,10 +128,11 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
} else if (active) {
|
||||
// Mesh dispatches: the console's are one-dimensional.
|
||||
uint3 g = src_args.Load3(src_at);
|
||||
// Ahead of its draw, a record over the most a dispatch runs is a
|
||||
// slot the title has not filled (the title leaves all
|
||||
// ones there): empty, and not counted below either.
|
||||
if (ahead && g.x > 65535u) {
|
||||
// A record over the most a dispatch runs is a slot the title has
|
||||
// not filled (the title leaves all ones there): empty,
|
||||
// and not counted below either. (65,535 groups of meshlets read
|
||||
// through the garbage beside it read past every buffer.)
|
||||
if (g.x > 65535u) {
|
||||
g = uint3(0, 0, 0);
|
||||
}
|
||||
asked = g.x;
|
||||
@@ -1006,6 +1016,7 @@ RWByteAddressBuffer o : register(u0);
|
||||
void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) {
|
||||
if (step == 0) { if (id.x == 0) o.Store(at, v[which].Load(first)); }
|
||||
else if (step == 1) { if (id.x == 0) o.Store(at, c[which].d[first / 16][(first / 4) & 3]); }
|
||||
else if (step == 16) { o.Store(at + id.x * 4, c[which].d[first / 16 + id.x][(first / 4) & 3]); }
|
||||
else { o.Store(at + id.x * 4, v[which].Load(first + id.x * step)); }
|
||||
}
|
||||
"#;
|
||||
@@ -1071,7 +1082,7 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) {
|
||||
}
|
||||
let table2 = D3D12_GPU_DESCRIPTOR_HANDLE { ptr: table.ptr + 8 * step as u64 };
|
||||
let offsets = [0u32, 4092, 4096, 4104, 8192, 65536, 524_288, (1 << 20) - 4];
|
||||
for mode in ["one load (uniform)", "a load a thread", "constant buffer load"] {
|
||||
for mode in ["one load (uniform)", "a load a thread", "constant buffer load", "Constant buffer load a thread"] {
|
||||
println!("{mode}:");
|
||||
for (which, name) in names.iter().enumerate() {
|
||||
// SAFETY: our open list, live buffers.
|
||||
@@ -1087,6 +1098,7 @@ void main(uint3 id : SV_DispatchThreadID, uint g : SV_GroupIndex) {
|
||||
let step = match mode.as_bytes()[0] {
|
||||
b'o' => 0u32,
|
||||
b'c' => 1,
|
||||
b'C' => 16,
|
||||
_ => 4,
|
||||
};
|
||||
// (A thread's loads end at the offset.)
|
||||
@@ -1832,18 +1844,13 @@ void main(uint3 t : SV_DispatchThreadID) {
|
||||
assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}");
|
||||
}
|
||||
let charged_filled = (5 + 519) * 128;
|
||||
if ahead {
|
||||
for i in filled.len()..RECORDS as usize {
|
||||
assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
|
||||
assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
|
||||
}
|
||||
assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
|
||||
assert_eq!(largest, 519, "and are not counted as asked for");
|
||||
} else {
|
||||
// Thirteen slots at 65,535 groups: sixteen would be all of it.
|
||||
assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most");
|
||||
assert_eq!(largest, u32::MAX);
|
||||
// As one window ahead of its draws and one by one alike.
|
||||
for i in filled.len()..RECORDS as usize {
|
||||
assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty");
|
||||
assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are");
|
||||
}
|
||||
assert_eq!(spent, charged_filled, "unfilled slots charge nothing");
|
||||
assert_eq!(largest, 519, "and are not counted as asked for");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1866,8 +1873,9 @@ void main(uint3 t : SV_DispatchThreadID) {
|
||||
let mut initial_src = vec![0u8; total_bytes];
|
||||
for i in 0..RECORDS as usize {
|
||||
let words: [u32; 6] = [
|
||||
u32::MAX, // IndexCount -> clamps to 1 << 24
|
||||
u32::MAX, // InstanceCount -> clamps to 4 (cost = 1 << 26)
|
||||
// The last is no draw: empty, and free.
|
||||
if i + 1 < RECORDS as usize { 1 << 22 } else { 1 << 23 }, // IndexCount
|
||||
u32::MAX, // InstanceCount -> clamps to 16 (cost = 1 << 26)
|
||||
1000 + i as u32, // StartIndexLocation
|
||||
(-200i32 + i as i32) as u32, // BaseVertexLocation
|
||||
5000 + i as u32, // StartInstanceLocation
|
||||
@@ -1932,7 +1940,7 @@ void main(uint3 t : SV_DispatchThreadID) {
|
||||
let mut zeroed = 0usize;
|
||||
for i in 0..RECORDS as usize {
|
||||
let rec = &out_words[i * 6..(i + 1) * 6];
|
||||
if rec[0] == (1 << 24) && rec[1] == 4 {
|
||||
if rec[0] == (1 << 22) && rec[1] == 16 {
|
||||
kept += 1;
|
||||
} else {
|
||||
assert_eq!((rec[0], rec[1]), (0, 0), "excess draw must be zeroed");
|
||||
@@ -2519,7 +2527,7 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
|
||||
};
|
||||
let pass = make_from(&warp.device, batch::SOURCE).expect("the batched clamp must compile on WARP");
|
||||
let kinds = [0u32, 1, 2, 10];
|
||||
let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, 1 << 24, (1 << 26) + 1, u32::MAX];
|
||||
let values = [0u32, 1, 3, 100, 65_535, 65_536, 1 << 20, (1 << 23) - 1, 1 << 23, 1 << 24, (1 << 26) + 1, u32::MAX];
|
||||
// Every kind with many records, in two sources.
|
||||
let mut records: Vec<(u32, [u32; 5])> = Vec::new();
|
||||
for kind in kinds {
|
||||
@@ -2612,7 +2620,7 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
|
||||
let mut table = unsafe {
|
||||
std::ptr::write_bytes(budget_ptr, 0, 256);
|
||||
for r in 0..records {
|
||||
for (w, word) in [1u32 << 24, 4, 5, 6].into_iter().enumerate() {
|
||||
for (w, word) in [1u32 << 22, 16, 5, 6].into_iter().enumerate() {
|
||||
src_ptr.cast::<u32>().add(r as usize * 4 + w).write_volatile(word);
|
||||
}
|
||||
}
|
||||
@@ -2636,8 +2644,8 @@ void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
|
||||
(0..records as usize).map(|r| back_ptr.cast::<u32>().add(r * batch::SLOT as usize / 4).read_volatile()).collect(),
|
||||
)
|
||||
};
|
||||
assert_eq!(out.iter().filter(|&&v| v == 1 << 24).count(), filled, "{times} times {records}: {out:?}");
|
||||
assert!(out.iter().all(|&v| v == 0 || v == 1 << 24));
|
||||
assert_eq!(out.iter().filter(|&&v| v == 1 << 22).count(), filled, "{times} times {records}: {out:?}");
|
||||
assert!(out.iter().all(|&v| v == 0 || v == 1 << 22));
|
||||
assert_eq!(spent, BUDGET.min((1 << 26) * times * records as u32));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,10 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
record[w] = load(job.x & 3, job.y + w * 4);
|
||||
}
|
||||
if (kind <= 1) {
|
||||
record[0] = min(record[0], 1u << 24);
|
||||
if (record[0] >= 1u << 23) {
|
||||
record[0] = 0;
|
||||
record[1] = 0;
|
||||
}
|
||||
record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
|
||||
cost = record[0] * record[1];
|
||||
} else if (kind == 2) {
|
||||
@@ -91,8 +94,12 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
record[1] = g.y;
|
||||
record[2] = g.z;
|
||||
} else {
|
||||
if (record[0] > 65535u) {
|
||||
record[0] = 0;
|
||||
record[1] = 0;
|
||||
record[2] = 0;
|
||||
}
|
||||
asked = record[0];
|
||||
record[0] = min(record[0], 65535u);
|
||||
record[1] = min(record[1], 1u);
|
||||
record[2] = min(record[2], 1u);
|
||||
cost = record[0] * record[1] * record[2] * 128u;
|
||||
|
||||
@@ -715,7 +715,10 @@ impl Written {
|
||||
Written::GpuTimestamp => {
|
||||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||||
let elapsed = START.get_or_init(std::time::Instant::now).elapsed();
|
||||
(elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64
|
||||
let now = (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64;
|
||||
#[cfg(all(windows, feature = "diagnostics"))]
|
||||
crate::host::spans::stamped(at as usize, now);
|
||||
as_loaded(now, at as usize, gpu_load())
|
||||
}
|
||||
Written::SystemTimestamp => system_timestamp(),
|
||||
};
|
||||
@@ -730,6 +733,31 @@ impl Written {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the title's GPU time is made to look like, in ticks
|
||||
/// (`VICTORY_GPU_LOAD_MS`; unset: as it is).
|
||||
///
|
||||
/// The title asks for four GPU timestamps a frame, in pairs of 16 bytes, the
|
||||
/// start in the second eight and the end in the first. All of them are written
|
||||
/// when the frame's last submissions land, within microseconds, so every pair
|
||||
/// says the card did nothing.
|
||||
fn gpu_load() -> u64 {
|
||||
static LOAD: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
*LOAD.get_or_init(|| {
|
||||
let ms = std::env::var("VICTORY_GPU_LOAD_MS").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0);
|
||||
ms * (TIMESTAMP_FREQUENCY / 1000)
|
||||
})
|
||||
}
|
||||
|
||||
/// The timestamp written at `at` when the clock says `now`, if a pair's start
|
||||
/// is to lie `load` ticks before its end.
|
||||
fn as_loaded(now: u64, at: usize, load: u64) -> u64 {
|
||||
if at & 8 != 0 {
|
||||
now.saturating_sub(load).max(1)
|
||||
} else {
|
||||
now
|
||||
}
|
||||
}
|
||||
|
||||
fn system_timestamp() -> u64 {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
@@ -919,6 +947,15 @@ extern "system" fn copy_page_mappings(
|
||||
unsafe { std::slice::from_raw_parts(batches, count as usize) }
|
||||
});
|
||||
let mut ok = true;
|
||||
let many = crate::resource::many_page_mapper();
|
||||
let mut gathered: Vec<(u64, u64, u64)> = Vec::new();
|
||||
let mut map = |to: u64, from: u64, len: u64| match many {
|
||||
Some(_) => {
|
||||
gathered.push((to, from, len));
|
||||
true
|
||||
}
|
||||
None => map(to, from, len),
|
||||
};
|
||||
for b in batches.into_iter().flatten() {
|
||||
if b.ranges.is_null() {
|
||||
continue;
|
||||
@@ -940,6 +977,9 @@ extern "system" fn copy_page_mappings(
|
||||
at += len;
|
||||
}
|
||||
}
|
||||
if let Some(many) = many {
|
||||
ok &= many(&gathered);
|
||||
}
|
||||
if !ok {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
|
||||
@@ -1072,6 +1112,14 @@ mod tests {
|
||||
assert_eq!(new[35], execute_x as *const ()); // 0x118
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pair_of_timestamps_shows_the_load_it_is_given() {
|
||||
let (start, end) = (0xd0419_6698, 0xd0419_6690);
|
||||
assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000);
|
||||
assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000);
|
||||
assert_eq!(as_loaded(5, start, 100), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timestamps_and_values_are_written() {
|
||||
let mut at = [0u64; 2];
|
||||
|
||||
@@ -84,6 +84,11 @@ pub struct Options {
|
||||
pub wait_all: bool,
|
||||
/// Each list sent on its own, and waited for.
|
||||
pub wait_lists: bool,
|
||||
/// Milliseconds the sender waits after each submission, as a title does
|
||||
/// that prepares the next one meanwhile: the card stands idle.
|
||||
pub pace: f64,
|
||||
/// The card kept awake meanwhile (`crate::host::awake`).
|
||||
pub awake: bool,
|
||||
/// Run only these lists (by their place in the frame).
|
||||
pub only: Option<(u32, u32)>,
|
||||
/// The last command that runs (list, command); after it only barriers.
|
||||
@@ -95,6 +100,9 @@ pub struct Options {
|
||||
pub compare: bool,
|
||||
/// The debug layer, if it is installed.
|
||||
pub debug: bool,
|
||||
/// The system's breadcrumbs after every command, as
|
||||
/// `VICTORY_D3D12_DRED=light` has them.
|
||||
pub breadcrumbs: bool,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
@@ -116,11 +124,14 @@ impl Default for Options {
|
||||
merge: true,
|
||||
wait_all: false,
|
||||
wait_lists: false,
|
||||
pace: 0.0,
|
||||
awake: false,
|
||||
only: None,
|
||||
until: None,
|
||||
skip_shaders: Vec::new(),
|
||||
compare: false,
|
||||
debug: false,
|
||||
breadcrumbs: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -150,6 +161,7 @@ impl Options {
|
||||
one_submit: false,
|
||||
wait_all: false,
|
||||
wait_lists: false,
|
||||
awake: false,
|
||||
only: None,
|
||||
skip_shaders: Vec::new(),
|
||||
..self.clone()
|
||||
@@ -488,6 +500,10 @@ pub struct Player {
|
||||
/// What a command of a list is timed as.
|
||||
type Stamp = (usize, &'static str, u32);
|
||||
|
||||
/// With a stamp of a copy to a texture: this bit and the texture's number
|
||||
/// stand for the pipeline's.
|
||||
const COPY_TO: u32 = 1 << 31;
|
||||
|
||||
/// A list made from commands, with what its timestamps are of.
|
||||
struct Built {
|
||||
_allocator: ID3D12CommandAllocator,
|
||||
@@ -503,7 +519,7 @@ impl Player {
|
||||
let folder = find(folder)?;
|
||||
let began = Instant::now();
|
||||
let frame = Frame::read(&folder.join("frame.bin"))?;
|
||||
let (device, info) = make_device(&frame, options.debug)?;
|
||||
let (device, info) = make_device(&frame, options.debug, options.breadcrumbs)?;
|
||||
// SAFETY: plain creation and queries.
|
||||
let (queue, frequency) = unsafe {
|
||||
let queue: ID3D12CommandQueue =
|
||||
@@ -570,7 +586,7 @@ impl Player {
|
||||
step("descriptors", &mut at);
|
||||
player.load_contents()?;
|
||||
step("contents", &mut at);
|
||||
player.make_masters(options.buffers)?;
|
||||
player.make_masters(options.buffers, options.restore)?;
|
||||
step("copies to restore from", &mut at);
|
||||
let steps: Vec<String> = steps
|
||||
.iter()
|
||||
@@ -1554,7 +1570,7 @@ impl Player {
|
||||
}
|
||||
|
||||
/// Copies of what the frame changes; and the states it leaves.
|
||||
fn make_masters(&mut self, buffers: Buffers) -> Result<()> {
|
||||
fn make_masters(&mut self, buffers: Buffers, wanted: bool) -> Result<()> {
|
||||
let mut states = States::default();
|
||||
for r in &self.frame.resources {
|
||||
if r.desc.dimension == D3D12_RESOURCE_DIMENSION_BUFFER.0 {
|
||||
@@ -1687,6 +1703,11 @@ impl Player {
|
||||
})
|
||||
.collect();
|
||||
ids.sort_unstable();
|
||||
// Without restoring they are of no use, and their room may be what
|
||||
// the frame itself lacks.
|
||||
if !wanted {
|
||||
ids.clear();
|
||||
}
|
||||
let mut total = 0u64;
|
||||
let mut in_pc = 0u64;
|
||||
for id in ids {
|
||||
@@ -2413,9 +2434,18 @@ impl Player {
|
||||
"clears"
|
||||
}
|
||||
Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolves",
|
||||
_ => "copies",
|
||||
_ => self.copy_kind(c),
|
||||
};
|
||||
let runs = match c {
|
||||
c if c.runs_shaders() => bound,
|
||||
// Copies to textures by what they go to.
|
||||
Cmd::CopyResource { dst, .. }
|
||||
| Cmd::CopyTexture {
|
||||
dst: Loc::Sub { res: dst, .. },
|
||||
..
|
||||
} => COPY_TO | dst,
|
||||
_ => NONE,
|
||||
};
|
||||
let runs = if c.runs_shaders() { bound } else { NONE };
|
||||
stamps.push((**next as usize, category, runs));
|
||||
**next += 1;
|
||||
}
|
||||
@@ -2423,6 +2453,34 @@ impl Player {
|
||||
stamps
|
||||
}
|
||||
|
||||
/// Which copies a copy is counted with: by the memory it crosses.
|
||||
fn copy_kind(&self, c: &Cmd) -> &'static str {
|
||||
let pc = |id: u32| {
|
||||
self.objects.get(&id).is_some_and(|o| {
|
||||
matches!(&self.frame.resources[o.index].place,
|
||||
Place::Committed { props, .. } if gpu::seen(props) != Seen::No)
|
||||
})
|
||||
};
|
||||
let res = |l: &Loc| match l {
|
||||
Loc::Sub { res, .. } | Loc::Placed { res, .. } => *res,
|
||||
};
|
||||
match c {
|
||||
Cmd::CopyBuffer { dst, src, .. } => match (pc(*dst), pc(*src)) {
|
||||
(false, true) => "copies of buffers, PC to card",
|
||||
(true, false) => "copies of buffers, card to PC",
|
||||
(true, true) => "copies of buffers, PC to PC",
|
||||
(false, false) => "copies of buffers, card to card",
|
||||
},
|
||||
Cmd::CopyTexture { dst, src, .. } => match (pc(res(dst)), pc(res(src))) {
|
||||
(false, true) => "copies of textures, PC to card",
|
||||
(true, _) => "copies of textures, to the PC",
|
||||
(false, false) => "copies of textures, card to card",
|
||||
},
|
||||
Cmd::CopyResource { .. } => "copies of whole resources",
|
||||
_ => "copies",
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn command(&self, l: &ID3D12GraphicsCommandList, c: &Cmd, version: usize) {
|
||||
let res = |id: u32| self.resource(id);
|
||||
let view = |s: &Slot| self.targets.get(s).copied().unwrap_or_default();
|
||||
@@ -2886,6 +2944,12 @@ impl Player {
|
||||
for all in &submissions {
|
||||
if !o.wait_lists {
|
||||
self.worker.queue.ExecuteCommandLists(all);
|
||||
if o.pace > 0.0 {
|
||||
let until = Instant::now() + std::time::Duration::from_secs_f64(o.pace / 1e3);
|
||||
while Instant::now() < until {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for l in all {
|
||||
@@ -2907,6 +2971,7 @@ impl Player {
|
||||
/// Runs the frame as the options say.
|
||||
pub fn run(&mut self, o: &Options) -> Result<Report> {
|
||||
let mut made = self.prepare(o)?;
|
||||
let _awake = if o.awake { crate::host::awake::start(&self.device, || true) } else { None };
|
||||
let mut stamps = Vec::new();
|
||||
for _ in 0..o.loops.max(1) {
|
||||
stamps = self.once(o, &mut made)?;
|
||||
@@ -3014,7 +3079,16 @@ impl Player {
|
||||
all.truncate(o.top);
|
||||
report.shaders = all
|
||||
.into_iter()
|
||||
.map(|(ms, n, pso)| (ms, n, self.pipeline_name(pso)))
|
||||
.map(|(ms, n, pso)| {
|
||||
let name = match self.objects.get(&(pso & !COPY_TO)).filter(|_| pso & COPY_TO != 0) {
|
||||
Some(o) => {
|
||||
let r = &self.frame.resources[o.index];
|
||||
format!("copies to #{} {}", pso & !COPY_TO, r.name)
|
||||
}
|
||||
None => self.pipeline_name(pso),
|
||||
};
|
||||
(ms, n, name)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
@@ -3229,7 +3303,7 @@ fn read_at(file: &File, mut to: &mut [u8], mut at: u64) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option<ID3D12InfoQueue>)> {
|
||||
fn make_device(frame: &Frame, debug: bool, breadcrumbs: bool) -> Result<(ID3D12Device, Option<ID3D12InfoQueue>)> {
|
||||
// SAFETY: plain creation and queries.
|
||||
unsafe {
|
||||
if debug {
|
||||
@@ -3247,6 +3321,14 @@ fn make_device(frame: &Frame, debug: bool) -> Result<(ID3D12Device, Option<ID3D1
|
||||
Err(e) => tracing::warn!("no debug layer: {e}"),
|
||||
}
|
||||
}
|
||||
if breadcrumbs {
|
||||
let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
|
||||
D3D12GetDebugInterface(&mut dred)?;
|
||||
if let Some(dred) = dred {
|
||||
dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
|
||||
}
|
||||
}
|
||||
let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
|
||||
let mut adapter = None;
|
||||
for i in 0.. {
|
||||
|
||||
@@ -961,6 +961,20 @@ pub fn use_page_mapper(mapper: PageMapper) {
|
||||
let _ = PAGE_MAPPER.set(mapper);
|
||||
}
|
||||
|
||||
/// As a [`PageMapper`], many at once: `(to, from, len)` each, in order.
|
||||
pub type ManyPageMapper = fn(&[(u64, u64, u64)]) -> bool;
|
||||
|
||||
static MANY_PAGE_MAPPER: std::sync::OnceLock<ManyPageMapper> = std::sync::OnceLock::new();
|
||||
|
||||
/// The runtime's mapper of many pages at once.
|
||||
pub fn use_many_page_mapper(mapper: ManyPageMapper) {
|
||||
let _ = MANY_PAGE_MAPPER.set(mapper);
|
||||
}
|
||||
|
||||
pub(crate) fn many_page_mapper() -> Option<ManyPageMapper> {
|
||||
MANY_PAGE_MAPPER.get().copied()
|
||||
}
|
||||
|
||||
pub(crate) fn page_mapper() -> Option<PageMapper> {
|
||||
PAGE_MAPPER.get().copied()
|
||||
}
|
||||
|
||||
@@ -86,6 +86,8 @@ pub(crate) struct Shadow {
|
||||
/// Of a copy with two sides: only the dwords the title changed go up,
|
||||
/// as with [`send_changed`] ([`by_address`]).
|
||||
changes_only: bool,
|
||||
/// A window in card memory the CPU maps ([`window_mapped_for`]).
|
||||
mapped: bool,
|
||||
/// With `crate::inplace`: not a copy at all. `buffer` is placed in a
|
||||
/// heap opened on the title memory itself, so shaders read and write
|
||||
/// the title's own bytes and nothing is copied either way. The heap,
|
||||
@@ -302,7 +304,9 @@ pub(crate) fn card_stats() -> [u64; 10] {
|
||||
out[i] = stat.swap(0, Ordering::Relaxed);
|
||||
}
|
||||
out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64;
|
||||
out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed);
|
||||
out[8] = CARD_BYTES[0].load(Ordering::Relaxed)
|
||||
+ WINDOW_CARD_BYTES.load(Ordering::Relaxed)
|
||||
+ WINDOW_MAPPED_BYTES.load(Ordering::Relaxed);
|
||||
out[9] = CARD_BYTES[1].load(Ordering::Relaxed);
|
||||
out
|
||||
}
|
||||
@@ -450,6 +454,51 @@ fn window_card_for(size: u64) -> Option<ID3D12Resource> {
|
||||
Some(buffer)
|
||||
}
|
||||
|
||||
/// The most bytes of windows outside buffers that lie in the card's memory
|
||||
/// and are filled by the CPU through the bus (`VICTORY_WINDOWS_BAR_MB`; 0, the
|
||||
/// default, none): one buffer (`D3D12_HEAP_TYPE_GPU_UPLOAD`), no CPU's side, no
|
||||
/// copy to send and no list of changes, unlike [`window_card_most`]. The CPU
|
||||
/// only writes them, as no shader is declared to write a window; if one were,
|
||||
/// its snapshot and compare would read through the bus, right but slow. In a
|
||||
/// captured frame the lists take 26 ms of the card instead of 29, the frame 32
|
||||
/// instead of 36; filling them costs the CPU what it did.
|
||||
///
|
||||
/// Windows go there while a fifth of the card's budget is free, as with
|
||||
/// [`window_room_for`], which this comes before.
|
||||
fn window_mapped_most() -> u64 {
|
||||
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
*MOST.get_or_init(|| {
|
||||
std::env::var("VICTORY_WINDOWS_BAR_MB").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0) << 20
|
||||
})
|
||||
}
|
||||
|
||||
/// Bytes alive of windows in card memory the CPU maps.
|
||||
static WINDOW_MAPPED_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// A buffer for a window of `size` bytes in card memory the CPU maps, if it is
|
||||
/// to be there ([`window_mapped_most`]).
|
||||
fn window_mapped_for(size: u64) -> Option<(ID3D12Resource, *mut u8)> {
|
||||
let most = window_mapped_most();
|
||||
if most == 0 {
|
||||
return None;
|
||||
}
|
||||
let host = host()?;
|
||||
if let Some([budget, used, ..]) = host.video_memory()
|
||||
&& used + size > budget / 10 * 8
|
||||
{
|
||||
return None;
|
||||
}
|
||||
if WINDOW_MAPPED_BYTES.fetch_add(size, Ordering::Relaxed) + size > most {
|
||||
WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed);
|
||||
return None;
|
||||
}
|
||||
let made = host.mapped_card_buffer(size, true);
|
||||
if made.is_none() {
|
||||
WINDOW_MAPPED_BYTES.fetch_sub(size, Ordering::Relaxed);
|
||||
}
|
||||
made
|
||||
}
|
||||
|
||||
/// Whether windows outside buffers have two sides too, so that submissions
|
||||
/// in the air read the bytes they were prepared with (`VICTORY_WINDOWS_OWN=1`;
|
||||
/// off by default: it takes the windows' bytes again, 3.3 GB in capture
|
||||
@@ -2250,6 +2299,9 @@ impl Drop for Shadow {
|
||||
KEPT_BYTES.fetch_sub(self.len, Ordering::Relaxed);
|
||||
}
|
||||
let window = self.window;
|
||||
if self.mapped {
|
||||
WINDOW_MAPPED_BYTES.fetch_sub(self.len, Ordering::Relaxed);
|
||||
}
|
||||
if let Some(card) = &mut self.card {
|
||||
if window {
|
||||
WINDOW_CARD_BYTES.fetch_sub(card.size, Ordering::Relaxed);
|
||||
@@ -2635,6 +2687,7 @@ impl Shadow {
|
||||
card: None,
|
||||
window: false,
|
||||
changes_only: false,
|
||||
mapped: false,
|
||||
place: None,
|
||||
}
|
||||
}
|
||||
@@ -4682,6 +4735,19 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option<Arc<Sha
|
||||
map.insert((start, len), shadow.clone());
|
||||
return Some(shadow);
|
||||
}
|
||||
// One buffer in the card's memory, filled by the CPU through the bus.
|
||||
if let Some((buffer, data)) = window_mapped_for(len) {
|
||||
crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} mapped on the card"));
|
||||
// SAFETY: a live buffer.
|
||||
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
|
||||
let mut shadow = Shadow::new(buffer, data, gpu, start, len);
|
||||
shadow.window = true;
|
||||
shadow.mapped = true;
|
||||
let shadow = Arc::new(shadow);
|
||||
note(&shadow);
|
||||
map.insert((start, len), shadow.clone());
|
||||
return Some(shadow);
|
||||
}
|
||||
let (buffer, data) = host()?.shared_buffer(len)?;
|
||||
crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
|
||||
// With room for windows on the card (`window_card_most`): shaders get a
|
||||
|
||||
@@ -19,6 +19,7 @@ extern "system" fn create_device(
|
||||
) -> HRESULT {
|
||||
victory_gpu::resource::use_allocator(super::xmem::XMemAlloc, super::xmem::XMemFree);
|
||||
victory_gpu::resource::use_page_mapper(super::xmem::map_alias);
|
||||
victory_gpu::resource::use_many_page_mapper(super::xmem::map_aliases);
|
||||
#[cfg(windows)]
|
||||
victory_gpu::on_failure(host_gpu_failed);
|
||||
device::create(adapter, parameters, iid, out)
|
||||
|
||||
@@ -406,6 +406,34 @@ pub extern "C" fn __p___argv() -> *mut *mut *mut c_char {
|
||||
argv().list.get()
|
||||
}
|
||||
|
||||
/// The title's thread priorities, but for the lowest two, which become
|
||||
/// "below normal". Six of the title's threads run at "idle", the streaming
|
||||
/// pager's among them; on the console they have what the rest of the title
|
||||
/// leaves of its cores. A PC's processors are also wanted by other programs
|
||||
/// and by our own workers (sixteen when pipelines are made): with every
|
||||
/// one of them busy such a thread ran once in four seconds or so, when the
|
||||
/// host's scheduler took pity, and the loading that waits for it with it
|
||||
/// (run stream-3: loads seen to be done 1.1 s late on average, 4.8 s at
|
||||
/// worst). `VICTORY_TITLE_PRIORITIES=0`: as the title sets them.
|
||||
fn title_priority(asked: i32) -> i32 {
|
||||
const IDLE: i32 = -15;
|
||||
const LOWEST: i32 = -2;
|
||||
const BELOW_NORMAL: i32 = -1;
|
||||
match asked {
|
||||
IDLE..=LOWEST => BELOW_NORMAL,
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// [`title_priority`].
|
||||
pub extern "system" fn SetThreadPriority(thread: *mut c_void, priority: i32) -> i32 {
|
||||
static AS_SET: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
let as_set = *AS_SET.get_or_init(|| std::env::var_os("VICTORY_TITLE_PRIORITIES").is_some_and(|v| v == "0"));
|
||||
let priority = if as_set { priority } else { title_priority(priority) };
|
||||
// SAFETY: the title passes a thread handle.
|
||||
unsafe { windows_sys::Win32::System::Threading::SetThreadPriority(thread, priority) }
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "kernel",
|
||||
@@ -440,6 +468,7 @@ pub(crate) fn module() -> HleModule {
|
||||
hle_export!(_invalid_parameter_noinfo_noreturn),
|
||||
hle_export!(TerminateProcess),
|
||||
hle_export!(SetUnhandledExceptionFilter),
|
||||
hle_export!(SetThreadPriority),
|
||||
],
|
||||
}
|
||||
}
|
||||
@@ -654,6 +683,24 @@ mod host {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The title's idle and lowest threads run below normal; the others as
|
||||
/// it sets them.
|
||||
#[test]
|
||||
fn no_title_thread_waits_for_idle_processors() {
|
||||
let given: Vec<i32> = [-15, -2, -1, 0, 1, 2, 15].into_iter().map(title_priority).collect();
|
||||
assert_eq!(given, [-1, -1, -1, 0, 1, 2, 15]);
|
||||
use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadPriority};
|
||||
std::thread::spawn(|| {
|
||||
// SAFETY: plain calls on this thread.
|
||||
let thread = unsafe { GetCurrentThread() };
|
||||
assert_eq!(SetThreadPriority(thread, -15), 1);
|
||||
// SAFETY: as above.
|
||||
assert_eq!(unsafe { GetThreadPriority(thread) }, -1);
|
||||
})
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn title_images_report_their_original_path() {
|
||||
let base = 0x7000_0000_0000;
|
||||
|
||||
@@ -487,6 +487,20 @@ struct Physical {
|
||||
holes: HashMap<usize, usize>,
|
||||
}
|
||||
|
||||
impl Physical {
|
||||
/// What the page at `at` shows.
|
||||
fn slice_at(&self, at: usize) -> Option<Slice> {
|
||||
self.views
|
||||
.range(..=at)
|
||||
.next_back()
|
||||
.filter(|(base, (size, _))| at < *base + size)
|
||||
.map(|(base, (_, s))| Slice {
|
||||
index: s.index + (at - base) / PAGE,
|
||||
section: s.section.clone(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The title's pages by number.
|
||||
struct Pages {
|
||||
next_page: usize,
|
||||
@@ -1103,6 +1117,16 @@ pub extern "system" fn XMemMapPhysicalPagesScatter(
|
||||
return 0;
|
||||
}
|
||||
lift_thread();
|
||||
if side_by_side() > 1 && n > 1 {
|
||||
// Read before any lock is taken, as in `XMemMapPhysicalPages`.
|
||||
let wanted: Vec<(usize, usize)> = (0..n)
|
||||
// SAFETY: the title passes `n` addresses and, unless null, `n` pages.
|
||||
.map(|i| unsafe { (*addresses.add(i) as usize, if pages.is_null() { 0 } else { *pages.add(i) }) })
|
||||
.collect();
|
||||
if wanted.iter().all(|w| w.0 % PAGE == 0) {
|
||||
return scatter(&wanted).into();
|
||||
}
|
||||
}
|
||||
for i in 0..n {
|
||||
// SAFETY: the title passes `n` addresses and, unless null, `n` pages.
|
||||
let (address, page) = unsafe {
|
||||
@@ -1139,16 +1163,7 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
|
||||
break;
|
||||
}
|
||||
let at = from + k;
|
||||
let Some(slice) = physical
|
||||
.views
|
||||
.range(..=at)
|
||||
.next_back()
|
||||
.filter(|(base, (size, _))| at < *base + size)
|
||||
.map(|(base, (_, s))| Slice {
|
||||
index: s.index + (at - base) / PAGE,
|
||||
section: s.section.clone(),
|
||||
})
|
||||
else {
|
||||
let Some(slice) = physical.slice_at(at) else {
|
||||
return false;
|
||||
};
|
||||
if !map(&mut physical, to + k, PAGE, slice) {
|
||||
@@ -1158,9 +1173,353 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// [`map_alias`] of many ranges, in order.
|
||||
pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool {
|
||||
let _costed = Costed::begin(None);
|
||||
lift_thread();
|
||||
if side_by_side() <= 1 {
|
||||
return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len));
|
||||
}
|
||||
// By the page: the address, and the one whose page it is to show.
|
||||
let pages: Vec<(usize, Option<usize>)> = ranges
|
||||
.iter()
|
||||
.flat_map(|&(to, from, len)| {
|
||||
(0..len as usize).step_by(PAGE).map(move |k| (to as usize + k, (from != 0).then_some(from as usize + k)))
|
||||
})
|
||||
.collect();
|
||||
if pages.iter().any(|p| p.0 % PAGE != 0 || p.1.is_some_and(|from| from % PAGE != 0)) {
|
||||
return ranges.iter().all(|&(to, from, len)| map_alias(to, from, len));
|
||||
}
|
||||
let mut ok = true;
|
||||
let mut at = 0;
|
||||
while at < pages.len() {
|
||||
let mut physical = physical();
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let mut touched = std::collections::HashSet::new();
|
||||
for &(to, from) in &pages[at..] {
|
||||
// A page the group changes already, or one it would be mapped
|
||||
// from: after it.
|
||||
if ops.len() == GROUP || touched.contains(&to) || from.is_some_and(|from| touched.contains(&from)) {
|
||||
break;
|
||||
}
|
||||
let slice = from.map(|from| physical.slice_at(from));
|
||||
ok &= !matches!(slice, Some(None));
|
||||
touched.insert(to);
|
||||
ops.push(Op::new(to, slice.flatten()));
|
||||
at += 1;
|
||||
}
|
||||
let _changing = victory_gpu::title_memory_remapping();
|
||||
ok &= change(&mut physical, ops);
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Maps (page number not 0) or unmaps each address; false if a page is not
|
||||
/// the title's or the host refuses one.
|
||||
fn scatter(wanted: &[(usize, usize)]) -> bool {
|
||||
let mut ok = true;
|
||||
let mut at = 0;
|
||||
while at < wanted.len() {
|
||||
let mut costed = Costed::begin(None);
|
||||
let mut ops: Vec<Op> = Vec::new();
|
||||
let mut physical = physical();
|
||||
if let Some(costed) = &mut costed {
|
||||
costed.waited = costed.started.elapsed().as_nanos() as u64;
|
||||
}
|
||||
{
|
||||
let table = page_table();
|
||||
let mut touched = std::collections::HashSet::new();
|
||||
for &(to, page) in &wanted[at..] {
|
||||
if ops.len() == GROUP || !touched.insert(to) {
|
||||
break;
|
||||
}
|
||||
let slice = table.pages.get(&page).cloned();
|
||||
if page != 0 && slice.is_none() {
|
||||
tracing::warn!(page, "XMemMapPhysicalPagesScatter: unknown page");
|
||||
ok = false;
|
||||
}
|
||||
ops.push(Op::new(to, slice));
|
||||
at += 1;
|
||||
}
|
||||
}
|
||||
if let Some(costed) = &mut costed {
|
||||
costed.pages = Some(ops.len());
|
||||
}
|
||||
let _changing = victory_gpu::title_memory_remapping();
|
||||
ok &= change(&mut physical, ops);
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// Pages changed under the locks at once.
|
||||
const GROUP: usize = 64;
|
||||
|
||||
/// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`;
|
||||
/// 1: the caller alone, a page after the other, as before).
|
||||
///
|
||||
/// Mapping and unmapping a view wait for a lock that every protection change
|
||||
/// of a view takes too, and our guards make 100,000 of those a second, from
|
||||
/// many threads, in the world: 0.2 to 4 ms a page. One thread stands in that
|
||||
/// queue once at a time. In a bench (60,000 views, five threads changing
|
||||
/// protections) one thread mapped 1,500 pages a second, eight 30,000.
|
||||
fn side_by_side() -> usize {
|
||||
static THREADS: LazyLock<usize> = LazyLock::new(|| {
|
||||
std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32)
|
||||
});
|
||||
*THREADS
|
||||
}
|
||||
|
||||
/// A page of address space to unmap and, with a slice, map anew.
|
||||
struct Op {
|
||||
at: usize,
|
||||
slice: Option<Slice>,
|
||||
/// A view of this page alone is there, to be unmapped.
|
||||
had: bool,
|
||||
/// The placeholder is the page's own (or will be, after the unmapping).
|
||||
own: bool,
|
||||
}
|
||||
|
||||
impl Op {
|
||||
fn new(at: usize, slice: Option<Slice>) -> Op {
|
||||
Op { at, slice, had: false, own: false }
|
||||
}
|
||||
|
||||
/// The system calls; whether the host did as asked.
|
||||
fn run(&self) -> bool {
|
||||
if self.had {
|
||||
// SAFETY: a view we mapped; it becomes a placeholder again.
|
||||
let gone = counted(Call::Unmap, || unsafe {
|
||||
UnmapViewOfFile2(
|
||||
GetCurrentProcess(),
|
||||
MEMORY_MAPPED_VIEW_ADDRESS { Value: self.at as *mut c_void },
|
||||
MEM_PRESERVE_PLACEHOLDER,
|
||||
)
|
||||
});
|
||||
if gone == 0 {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
let Some(slice) = &self.slice else {
|
||||
return true;
|
||||
};
|
||||
show(self.at, PAGE, slice, self.own)
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `ops`, each of another page, side by side: first what is noted of
|
||||
/// the pages goes, then the system calls, then what is there now is noted.
|
||||
/// With [`PHYSICAL`] and the change of mapping (`title_memory_remapping`)
|
||||
/// held.
|
||||
fn change(physical: &mut Physical, mut ops: Vec<Op>) -> bool {
|
||||
for op in &mut ops {
|
||||
let there = physical
|
||||
.views
|
||||
.range(..=op.at)
|
||||
.next_back()
|
||||
.filter(|(base, view)| op.at < **base + view.0)
|
||||
.map(|(base, view)| (*base, view.0));
|
||||
match there {
|
||||
Some((base, PAGE)) if base == op.at => {
|
||||
if let Some((size, slice)) = physical.views.remove(&op.at) {
|
||||
shown_mut().forget(op.at, size, &slice);
|
||||
}
|
||||
victory_gpu::title_memory_unmapping(op.at, PAGE);
|
||||
physical.holes.remove(&op.at);
|
||||
(op.had, op.own) = (true, lean());
|
||||
}
|
||||
// Part of a larger view.
|
||||
Some(_) => {
|
||||
unmap(physical, op.at, PAGE);
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
if op.had {
|
||||
continue;
|
||||
}
|
||||
op.own = physical.holes.remove(&op.at) == Some(PAGE) && lean();
|
||||
if op.slice.is_some() && !op.own {
|
||||
// Cut out of a larger placeholder here, not side by side: a
|
||||
// thread that maps a piece while others cut the same one can
|
||||
// fail.
|
||||
split(op.at, PAGE);
|
||||
op.own = true;
|
||||
}
|
||||
}
|
||||
let done = pool::all(ops);
|
||||
let mut ok = true;
|
||||
for (op, done) in done {
|
||||
match op.slice {
|
||||
Some(slice) if done => {
|
||||
// As in `map`.
|
||||
shown_mut().note(op.at, PAGE, &slice);
|
||||
victory_gpu::title_memory_remapped(op.at, PAGE);
|
||||
victory_gpu::title_memory_view(op.at, PAGE, slice.section.handle as usize, (slice.index * PAGE) as u64);
|
||||
physical.views.insert(op.at, (PAGE, slice));
|
||||
}
|
||||
None if op.had && done => {
|
||||
physical.holes.insert(op.at, PAGE);
|
||||
}
|
||||
_ => ok &= done,
|
||||
}
|
||||
}
|
||||
ok
|
||||
}
|
||||
|
||||
/// The threads that do the system calls of [`change`].
|
||||
mod pool {
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
|
||||
use super::{Op, side_by_side};
|
||||
|
||||
struct Batch {
|
||||
ops: Vec<(Op, AtomicBool)>,
|
||||
next: AtomicUsize,
|
||||
/// Ops not done yet.
|
||||
left: AtomicUsize,
|
||||
over: (Mutex<bool>, Condvar),
|
||||
}
|
||||
|
||||
impl Batch {
|
||||
/// Does ops until none is left to begin.
|
||||
fn work(&self) {
|
||||
loop {
|
||||
let i = self.next.fetch_add(1, Ordering::Relaxed);
|
||||
let Some((op, done)) = self.ops.get(i) else {
|
||||
return;
|
||||
};
|
||||
done.store(op.run(), Ordering::Release);
|
||||
if self.left.fetch_sub(1, Ordering::AcqRel) == 1 {
|
||||
*self.over.0.lock().unwrap_or_else(|e| e.into_inner()) = true;
|
||||
self.over.1.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Pool {
|
||||
batches: Mutex<VecDeque<Arc<Batch>>>,
|
||||
more: Condvar,
|
||||
}
|
||||
|
||||
fn pool() -> &'static Pool {
|
||||
static POOL: OnceLock<Pool> = OnceLock::new();
|
||||
static STARTED: std::sync::Once = std::sync::Once::new();
|
||||
let pool = POOL.get_or_init(|| Pool { batches: Mutex::default(), more: Condvar::new() });
|
||||
STARTED.call_once(|| {
|
||||
let started = (1..side_by_side())
|
||||
.filter(|i| std::thread::Builder::new().name(format!("mapping {i}")).spawn(|| serve(pool)).is_ok())
|
||||
.count();
|
||||
tracing::info!(started, "threads that map pages side by side (VICTORY_MAP_THREADS=1: none)");
|
||||
});
|
||||
pool
|
||||
}
|
||||
|
||||
fn serve(pool: &Pool) {
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL,
|
||||
};
|
||||
// SAFETY: a plain call on our own thread.
|
||||
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) };
|
||||
let mut batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
let Some(batch) = batches.front().cloned() else {
|
||||
batches = pool.more.wait(batches).unwrap_or_else(|e| e.into_inner());
|
||||
continue;
|
||||
};
|
||||
if batch.next.load(Ordering::Relaxed) >= batch.ops.len() {
|
||||
// All begun: nobody needs to see it any more.
|
||||
if batches.front().is_some_and(|b| Arc::ptr_eq(b, &batch)) {
|
||||
batches.pop_front();
|
||||
}
|
||||
continue;
|
||||
}
|
||||
drop(batches);
|
||||
batch.work();
|
||||
batches = pool.batches.lock().unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `ops`; each with whether the host did it.
|
||||
pub(super) fn all(ops: Vec<Op>) -> Vec<(Op, bool)> {
|
||||
// Waking the others takes longer than a few quick calls.
|
||||
if ops.len() < 3 {
|
||||
return ops
|
||||
.into_iter()
|
||||
.map(|op| {
|
||||
let done = op.run();
|
||||
(op, done)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
let n = ops.len();
|
||||
let batch = Arc::new(Batch {
|
||||
ops: ops.into_iter().map(|op| (op, AtomicBool::new(false))).collect(),
|
||||
next: AtomicUsize::new(0),
|
||||
left: AtomicUsize::new(n),
|
||||
over: Default::default(),
|
||||
});
|
||||
let pool = pool();
|
||||
pool.batches.lock().unwrap_or_else(|e| e.into_inner()).push_back(batch.clone());
|
||||
if n > side_by_side() {
|
||||
pool.more.notify_all();
|
||||
} else {
|
||||
(1..n).for_each(|_| pool.more.notify_one());
|
||||
}
|
||||
batch.work();
|
||||
let mut over = batch.over.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
while !*over {
|
||||
over = batch.over.1.wait(over).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
drop(over);
|
||||
// No worker changes it any more (one may still hold it for a moment).
|
||||
batch
|
||||
.ops
|
||||
.iter()
|
||||
.map(|(op, done)| {
|
||||
let op = Op { at: op.at, slice: op.slice.clone(), had: op.had, own: op.own };
|
||||
(op, done.load(Ordering::Acquire))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps `slice` and the slices after it over `[base, base + len)`, which
|
||||
/// must lie in one placeholder.
|
||||
fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
|
||||
let own = physical.holes.remove(&base) == Some(len) && lean();
|
||||
if !show(base, len, &slice, own) {
|
||||
return false;
|
||||
}
|
||||
// Noted before the GPU side is told: bytes DirectStorage put in earlier,
|
||||
// without notice at these addresses ([`pages_written`]), are there by
|
||||
// the time the copies of them go.
|
||||
shown_mut().note(base, len, &slice);
|
||||
// New contents, read-write: the GPU side's copies no longer guard it.
|
||||
victory_gpu::title_memory_remapped(base, len);
|
||||
// What the range shows now, for the GPU side's in-place census.
|
||||
victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64);
|
||||
physical.views.insert(base, (len, slice));
|
||||
true
|
||||
}
|
||||
|
||||
/// Cuts `[base, base + len)` out of the placeholder it is in (which fails
|
||||
/// harmlessly when the range is the whole placeholder).
|
||||
fn split(base: usize, len: usize) {
|
||||
// SAFETY: acts only on a placeholder.
|
||||
counted(Call::Split, || unsafe {
|
||||
VirtualFree(
|
||||
base as *mut c_void,
|
||||
len,
|
||||
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// The system calls of [`map`]; `own`: the placeholder at `base` is `len`
|
||||
/// long already.
|
||||
fn show(base: usize, len: usize, slice: &Slice, own: bool) -> bool {
|
||||
let map_view = || {
|
||||
// SAFETY: maps the section over a placeholder; acts only on one.
|
||||
counted(Call::Map, || unsafe {
|
||||
@@ -1177,18 +1536,9 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
|
||||
)
|
||||
})
|
||||
};
|
||||
let own = physical.holes.remove(&base) == Some(len) && lean();
|
||||
let mut view = if own { map_view() } else { MEMORY_MAPPED_VIEW_ADDRESS { Value: std::ptr::null_mut() } };
|
||||
if view.Value as usize != base {
|
||||
// SAFETY: splits the placeholder around the range (failing
|
||||
// harmlessly when the range is the whole placeholder).
|
||||
counted(Call::Split, || unsafe {
|
||||
VirtualFree(
|
||||
base as *mut c_void,
|
||||
len,
|
||||
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
|
||||
)
|
||||
});
|
||||
split(base, len);
|
||||
view = map_view();
|
||||
}
|
||||
if view.Value as usize != base {
|
||||
@@ -1205,15 +1555,6 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
|
||||
unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
|
||||
return false;
|
||||
}
|
||||
// Noted before the GPU side is told: bytes DirectStorage put in earlier,
|
||||
// without notice at these addresses ([`pages_written`]), are there by
|
||||
// the time the copies of them go.
|
||||
shown_mut().note(base, len, &slice);
|
||||
// New contents, read-write: the GPU side's copies no longer guard it.
|
||||
victory_gpu::title_memory_remapped(base, len);
|
||||
// What the range shows now, for the GPU side's in-place census.
|
||||
victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64);
|
||||
physical.views.insert(base, (len, slice));
|
||||
true
|
||||
}
|
||||
|
||||
@@ -1754,6 +2095,67 @@ mod tests {
|
||||
assert_eq!(XMemFreePhysicalPages(4, pages.as_ptr()), 1);
|
||||
}
|
||||
|
||||
/// Many pages in one call: mapped, moved over each other's addresses,
|
||||
/// given twice in one list, copied by the GPU's mappings and unmapped.
|
||||
#[test]
|
||||
fn a_scatter_of_many_pages_is_what_one_after_the_other_is() {
|
||||
const N: usize = 200;
|
||||
let pages = allocate(N);
|
||||
let a = XMemVirtualAlloc(std::ptr::null_mut(), 2 * N * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE) as usize;
|
||||
let at = |k: usize| (a + k * PAGE) as *mut c_void;
|
||||
let first = |k: usize| at(k).cast::<u64>();
|
||||
for round in 0..4_usize {
|
||||
// Every address shows another page each round.
|
||||
let to: Vec<*mut c_void> = (0..N).map(|i| at((i + 7 * round) % N)).collect();
|
||||
assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), N, pages.as_ptr()), 1);
|
||||
for i in 0..N {
|
||||
// SAFETY: mapped read-write.
|
||||
unsafe {
|
||||
if round > 0 {
|
||||
assert_eq!(first((i + 7 * round) % N).read(), (1000 * (round - 1) + i) as u64);
|
||||
}
|
||||
first((i + 7 * round) % N).write((1000 * round + i) as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The GPU's copies of the mappings, in ranges and one by one; a page
|
||||
// mapped from one the same call has mapped shows the same.
|
||||
let half = (N / 2 * PAGE) as u64;
|
||||
let (from, to) = (a as u64, at(N) as u64);
|
||||
assert!(map_aliases(&[(to, from, half), (to + half, to, half)]));
|
||||
for k in 0..N / 2 {
|
||||
// SAFETY: mapped read-write.
|
||||
unsafe {
|
||||
assert_eq!(first(N + k).read(), first(k).read());
|
||||
assert_eq!(first(N + N / 2 + k).read(), first(k).read());
|
||||
first(N + k).write(5);
|
||||
assert_eq!(first(k).read(), 5);
|
||||
}
|
||||
}
|
||||
// An address twice: the last one counts; page 0 unmaps.
|
||||
let to = [at(0), at(1), at(0), at(2), at(3), at(0)];
|
||||
let what = [pages[5], pages[6], 0, 0, pages[7], pages[8]];
|
||||
assert_eq!(XMemMapPhysicalPagesScatter(to.as_ptr(), 6, what.as_ptr()), 1);
|
||||
assert_eq!(query(at(2)).host.State, MEM_RESERVE);
|
||||
// SAFETY: mapped read-write; the same page at both.
|
||||
unsafe {
|
||||
first(0).write(77);
|
||||
assert_eq!(XMemMapPhysicalPagesScatter([at(2), at(4), at(6)].as_ptr(), 3, [pages[8]; 3].as_ptr()), 1);
|
||||
assert_eq!((first(2).read(), first(4).read(), first(6).read()), (77, 77, 77));
|
||||
}
|
||||
// A page the title does not own.
|
||||
assert_eq!(XMemMapPhysicalPagesScatter([at(0), at(1)].as_ptr(), 2, [pages[0], 1].as_ptr()), 0);
|
||||
// All gone, also parts of a larger view.
|
||||
assert_eq!(XMemMapPhysicalPages(at(0), 4, std::ptr::null()), at(0));
|
||||
// SAFETY: placeholders of ours, nothing mapped in them.
|
||||
unsafe { VirtualFree(at(0), 4 * PAGE, MEM_RELEASE | 1 /* MEM_COALESCE_PLACEHOLDERS */) };
|
||||
assert_eq!(XMemMapPhysicalPages(at(0), 4, pages.as_ptr()), at(0));
|
||||
assert!(map_aliases(&[(a as u64, 0, (2 * N * PAGE) as u64)]));
|
||||
assert!((0..2 * N).all(|k| query(at(k)).host.State == MEM_RESERVE));
|
||||
assert!(physical().views.range(a..a + 2 * N * PAGE).next().is_none());
|
||||
assert_eq!(XMemFreePhysicalPages(N, pages.as_ptr()), 1);
|
||||
}
|
||||
|
||||
/// Pages keep what they hold however often they are mapped, moved and
|
||||
/// unmapped without a commit or a split of their own.
|
||||
#[test]
|
||||
|
||||
@@ -6890,11 +6890,17 @@ impl<'a> Lower<'a> {
|
||||
}
|
||||
|
||||
/// The heap index to read descriptor `src` at, `index` being the title's:
|
||||
/// for a buffer picked from the heap itself and read as raw bytes (or as
|
||||
/// a constant buffer), the host's raw twin of that slot
|
||||
/// ([`super::shader::raw_views`]), whose reads end where the view does.
|
||||
/// Everything else (tables, textures, typed buffers) stays in place.
|
||||
/// And whether it is a twin's (inside the host's heap).
|
||||
/// for a buffer read as raw bytes, through a table or picked from the
|
||||
/// heap itself (or picked and read as a constant buffer), the host's raw
|
||||
/// twin of that slot ([`super::shader::raw_views`]), whose reads end where
|
||||
/// the view does. Everything else (textures, typed buffers, tables'
|
||||
/// constant buffers) stays in place. And whether it is a twin's (inside
|
||||
/// the host's heap).
|
||||
///
|
||||
/// Tables too: a view that does not begin on 16 bytes cannot be raw, and
|
||||
/// a pixel program of the main pass (3711fdad456538a1, stopped at in the
|
||||
/// device losses of runs n03 and n04) reads a structured one of 8 byte
|
||||
/// elements at 8 as raw bytes per lane.
|
||||
fn raw_twin(&mut self, src: &Source, index: V, sampler: bool, props: (u32, u32)) -> (V, bool) {
|
||||
// Raw and constant buffers (DXIL resource kinds 11 and 13).
|
||||
const RAW: u32 = 11;
|
||||
@@ -6907,7 +6913,9 @@ impl<'a> Lower<'a> {
|
||||
self.scalar
|
||||
.get(load)
|
||||
.and_then(|a| self.x.native.layout.get(a.param))
|
||||
.is_some_and(|p| p.root == RootType::ResourceHeap)
|
||||
.is_some_and(|p| {
|
||||
p.root == RootType::ResourceHeap || (p.root == RootType::Table && props.0 & 0xFF == RAW)
|
||||
})
|
||||
};
|
||||
if first == 0 || sampler || !matches!(props.0 & 0xFF, RAW | CONSTANT) || !src.leaves().iter().all(picked) {
|
||||
return (index, false);
|
||||
|
||||
@@ -149,9 +149,10 @@ pub fn view_heap_limit() -> u32 {
|
||||
/// entry nothing wrote. On AMD a raw load through a view that is not raw (typed, structured, a
|
||||
/// constant buffer's) has no end: it reads whatever lies there, up to 4 GiB on, and loses the
|
||||
/// device where nothing does; and a texture's descriptor read as a buffer's is a wild address.
|
||||
/// So the host keeps, for title slot `i`, a raw view of the same bytes at this place + `i`
|
||||
/// (a constant buffer view of a constant buffer, a null raw view of everything else and of every
|
||||
/// slot past the title's), and shaders translated while this is set read picked buffers there.
|
||||
/// So the host keeps, for slot `i`, a raw view of the same bytes at this place + `i` (a constant
|
||||
/// buffer view of a constant buffer in a title slot, a null raw view of everything else), and
|
||||
/// shaders translated while this is set read picked buffers there, and tables' buffers that they
|
||||
/// read as raw bytes.
|
||||
/// A power of two above every slot index.
|
||||
static RAW_VIEWS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
|
||||
|
||||
@@ -322,15 +322,17 @@ fn a_picked_buffer_is_read_at_its_raw_twin() {
|
||||
};
|
||||
let (title, twin, last, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [9u32, 10, 11, 12], [[0.0; 4]; 1]);
|
||||
let raw = |data| View::Buffer { data, stride: Stride::Raw };
|
||||
let views = || {
|
||||
// (The store goes through the table's third entry: its twin, too.)
|
||||
let views = |twins: bool| {
|
||||
let uav = |here: bool| if here { View::RawUav(2) } else { View::Texture(1, 1, &texel) };
|
||||
[
|
||||
View::Texture(1, 1, &texel),
|
||||
raw(&title),
|
||||
View::RawUav(2),
|
||||
uav(!twins),
|
||||
View::Texture(1, 1, &texel),
|
||||
View::Texture(1, 1, &texel),
|
||||
raw(&twin),
|
||||
View::Texture(1, 1, &texel),
|
||||
uav(twins),
|
||||
raw(&last),
|
||||
]
|
||||
};
|
||||
@@ -338,8 +340,32 @@ fn a_picked_buffer_is_read_at_its_raw_twin() {
|
||||
super::shader::RAW_VIEWS_HERE.set(Some(first));
|
||||
let shader = build(&program(at), (8, 0)).expect("translates");
|
||||
super::shader::RAW_VIEWS_HERE.set(None);
|
||||
for (label, got) in run(&shader, &views()) {
|
||||
for (label, got) in run(&shader, &views(first != 0)) {
|
||||
assert_eq!(got[..2], [0, expected], "{label}: twins from {first}, byte {at}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A table's buffer read as raw bytes is read at its raw twin too.
|
||||
#[test]
|
||||
fn a_tables_raw_buffer_is_read_at_its_raw_twin() {
|
||||
let load = [
|
||||
0xF408_0201u32, // s_load_dwordx4 s[8:11], s[2:3], 0
|
||||
0xFA00_0000,
|
||||
0xE030_0004, // buffer_load_dword v5, off, s[8:11], 0 offset:4
|
||||
0x8002_0500,
|
||||
0x7E0A_0505, // v_readfirstlane_b32 s5, v5
|
||||
0xBE84_0380, // s_mov_b32 s4, 0
|
||||
];
|
||||
let words = [TABLE, &load, STORE].concat();
|
||||
let (title, twin, texel) = ([1u32, 2, 3, 4], [5u32, 6, 7, 8], [[0.0; 4]; 1]);
|
||||
let raw = |data| View::Buffer { data, stride: Stride::Raw };
|
||||
super::shader::RAW_VIEWS_HERE.set(Some(4));
|
||||
let shader = build(&words, (4, 0)).expect("translates");
|
||||
super::shader::RAW_VIEWS_HERE.set(None);
|
||||
let other = || View::Texture(1, 1, &texel);
|
||||
let views = [raw(&title), other(), other(), other(), raw(&twin), other(), View::RawUav(2)];
|
||||
for (label, got) in run(&shader, &views) {
|
||||
assert_eq!(got[..2], [0, 6], "{label}");
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -69,7 +69,10 @@ with the presented one.
|
||||
| `--only 3..7` | runs these lists; of the others only barriers |
|
||||
| `--no-merge` | copies of what the CPU wrote also overwrite the card's own results (below) |
|
||||
| `--skip-shader <text>` | leaves out what runs pipelines with the text in their name or DXIL hash (repeatable) |
|
||||
| `--no-restore` | leaves what a loop changed |
|
||||
| `--no-restore` | leaves what a loop changed, and makes no copies to restore from (of a capture that does not fit in the card's memory with them) |
|
||||
| `--pace <ms>` | a wait after each submission sent: the card stands idle between them, as in a game that prepares the next one |
|
||||
| `--awake` | keeps the card's clocks up (`VICTORY_CARD_AWAKE=1`) |
|
||||
| `--breadcrumbs` | the system's breadcrumbs (`VICTORY_D3D12_DRED=light`) |
|
||||
| `--debug-layer` | D3D12's debug layer; its errors in the report |
|
||||
|
||||
Use the median of several loops; the first is slower. An experiment that
|
||||
|
||||
Reference in new issue
Block a user