Streaming, copy queue, texture pools and a shader cache that survives rebuilds

Textures and staging cut from 64 MB blocks; a kept view per page section and
page lists read again until the title has filled them in; the GPU side told
when streamed bytes land; results fetched over the copy queue
(VICTORY_RELAY_COPY=1); the write-watch journal behind a reader-writer lock;
the shader cache keyed by the translator's sources and `victory shaders`;
helper lanes as in upstream 1733 (VICTORY_HELPER_OWN).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-24 18:55:40 -06:00
1 parent 7f166af4f3
commit 9fea7434cd
20 files changed
+1629 -232

No files matched your search

+10
View File
@@ -85,6 +85,15 @@ enum Command {
#[arg(long)]
jobs: Option<usize>,
},
/// Translate every shader found (as `translate` finds them) into the
/// shader cache, so that no run has to: a few minutes, once per change
/// of the translator.
Shaders {
paths: Vec<PathBuf>,
/// Worker threads (default: every logical core).
#[arg(long)]
jobs: Option<usize>,
},
/// Prepare, map and bind a title executable; with --execute, run it.
Run {
exe: PathBuf,
@@ -163,6 +172,7 @@ fn main() -> Result<()> {
}
translate::run(paths, validate, pipelines, list, jobs)
}
Command::Shaders { paths, jobs } => translate::precompile(paths, jobs),
Command::Run {
exe,
unimplemented,
+61
View File
@@ -306,6 +306,67 @@ pub fn run(
Ok(())
}
/// Every shader found into the cache runs translate from.
pub fn precompile(paths: Vec<PathBuf>, jobs: Option<usize>) -> Result<()> {
let cfg = victory_core::Config::load()?;
victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
let paths = crate::default_paths(paths)?;
let threads =
jobs.unwrap_or_else(|| std::thread::available_parallelism().map_or(4, |n| n.get()));
let started = std::time::Instant::now();
let seen = Mutex::new(HashSet::new());
let done = AtomicUsize::new(0);
let failed = Mutex::new(BTreeMap::<String, (usize, String)>::new());
for root in &paths {
for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) {
if !entry.file_type().is_file() || entry.metadata().map_or(0, |m| m.len()) > MAX_FILE {
continue;
}
let Ok(data) = std::fs::read(entry.path()) else {
continue;
};
let jobs = sources(&data);
let next = AtomicUsize::new(0);
std::thread::scope(|s| {
for _ in 0..threads.min(jobs.len()) {
s.spawn(|| {
while let Some(job) = jobs.get(next.fetch_add(1, Ordering::Relaxed)) {
let Some(bytes) = job.bytes() else { continue };
let hash = blake3::hash(&bytes);
if !lock(&seen).insert(hash) {
continue;
}
match victory_hle::modules::d3d12x::precompile(&bytes) {
Ok(_) => {
let n = done.fetch_add(1, Ordering::Relaxed) + 1;
if n.is_multiple_of(1000) {
println!("{n} shaders in the cache, {:.0} s", started.elapsed().as_secs_f64());
}
}
Err(why) => {
let mut failed = lock(&failed);
failed.entry(why).or_insert_with(|| (0, hash.to_hex()[..16].to_owned())).0 += 1;
}
}
}
});
}
});
}
}
let failed = failed.into_inner().unwrap_or_else(|e| e.into_inner());
println!(
"{} shaders in the cache, {} do not translate, {:.0} s",
done.load(Ordering::Relaxed),
failed.values().map(|f| f.0).sum::<usize>(),
started.elapsed().as_secs_f64()
);
for (why, (n, hash)) in failed {
println!(" {n:>5} {why} (e.g. {hash})");
}
Ok(())
}
fn translate(
source: &Source,
path: &Path,
+3
View File
@@ -16,6 +16,9 @@ victory-formats.workspace = true
victory-pipeline.workspace = true
victory-shader.workspace = true
[build-dependencies]
blake3.workspace = true
[dev-dependencies]
tempfile.workspace = true
+45
View File
@@ -0,0 +1,45 @@
//! Fingerprints the shader translator, so that cached translations
//! (`src/shader_cache.rs`) last until the translator itself changes and not
//! only until the next build of anything.
use std::path::{Path, PathBuf};
fn files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
let path = entry.path();
if path.is_dir() {
files(&path, out);
} else {
out.push(path);
}
}
}
fn main() {
let here = PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap_or_default());
let crates = here.join("..");
let root = crates.join("..");
// The translator, what it is built from, and the form entries are kept in.
let mut all = vec![
crates.join("victory-shader/Cargo.toml"),
here.join("src/shader_cache.rs"),
root.join("Cargo.lock"),
root.join("rust-toolchain.toml"),
];
let source = crates.join("victory-shader/src");
println!("cargo:rerun-if-changed={}", source.display());
files(&source, &mut all);
all.sort();
let mut hash = blake3::Hasher::new();
for path in &all {
println!("cargo:rerun-if-changed={}", path.display());
// Names and line endings as they are in every checkout.
let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
let bytes: Vec<u8> = std::fs::read(path).unwrap_or_default().into_iter().filter(|&b| b != 13).collect();
hash.update(name.as_bytes());
hash.update(&(bytes.len() as u64).to_le_bytes());
hash.update(&bytes);
}
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rustc-env=VICTORY_TRANSLATOR={}", hash.finalize().to_hex());
}
+4
View File
@@ -740,6 +740,10 @@ fn log_memory() {
mb(card[0]),
mb(card[3]),
);
{
let [textures, staging] = crate::pool::memory();
tracing::info!("memory in blocks (VICTORY_TEXTURE_POOL=0 turns them off): {textures} MB of textures, {staging} MB of their staging buffers");
}
tracing::info!(
"memory let go since the start: {} windows outside buffers {:.0} MB, {} staging buffers \
{:.0} MB; of the windows alive, {:.0} MB lie between the lowest and highest address \
+157 -9
View File
@@ -1547,6 +1547,9 @@ struct CardPlan {
/// The lists of ours the plan recorded (whether the compare, the
/// list), given back by `Host::card_done`.
lists: Vec<(bool, Prelude)>,
/// With [`relay`]: the number of the send to copies in the card's memory
/// that the submission ran behind ([`QUEUE_ORDER`]).
sent_as: u64,
}
/// One piece of submission-time work, in recorded order.
@@ -1778,6 +1781,27 @@ fn relay_exact() -> bool {
*ON.get_or_init(|| relay() && std::env::var_os("VICTORY_RELAY").is_some_and(|v| v == "2"))
}
/// Whether the pieces the relay fetches from the card's memory come over the
/// card's copy queue (`VICTORY_RELAY_COPY=1`) and not over the queue that
/// draws.
///
/// On the drawing queue a fetch runs behind whatever was sent meanwhile,
/// and with the relay that is most of a frame: the thread that lands flights
/// stood 48 ms of a 120 ms frame waiting for seven fetches of 94 MB in all,
/// a few milliseconds of copying, and everything that waits for a landing
/// (the title's fences, reads of memory flights may write) waited with it.
///
/// What changes: the fetch runs when its flights are done and beside later
/// submissions, so of the sends of title bytes it is only known to have run
/// behind those its own flights ran behind (`CardPlan::sent_as`). Bytes sent
/// later are left out of the merge (`Shadow::card_merge_relay`): they are
/// the title's, newer than what the flights wrote. A later flight's bytes
/// may be in what is fetched, as before.
fn relay_copy() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_RELAY_COPY").is_some_and(|v| v == "1"))
}
/// Told when something joins [`LINE`], for the thread that lands flights
/// ([`relay`]); [`LINE_MOVED`] stays the word for the thread that looks at
/// what queues hold.
@@ -2041,6 +2065,74 @@ fn late_blocked(runs: &[&HostList]) -> Option<usize> {
blocked_by(&written, runs, true)
}
/// Whether a small fill of upload memory, or copy of a title buffer, goes on without waiting for
/// flights when the title itself wrote the memory since they were given it
/// (`VICTORY_FILL_TITLE=1`; off by default).
///
/// The title's 174 MB heap is declared written as a whole (a root view has
/// no size), and the title keeps a ring of constants in it: one fill of 480
/// bytes a frame, at a new place each time, waited for every flight's
/// copy-back, some 30 ms of a 130 ms frame (run blame1: 38 of the 40 waits
/// named). The title writes those bytes just before the draw that reads
/// them, which takes the block's guard off ([`crate::watch::written_since_taken`]).
///
/// Or no shader's write went into that page in the last 600 frames
/// ([`crate::watch::landed_lately`]): the first alone left two thirds of
/// the wait, for constants at the end of a 64 KiB page that the title wrote
/// before the page was taken.
///
/// What can go wrong: a constant a flight's shader really writes, in a
/// block that the title (or an earlier flight's copy-back) also wrote, or
/// for the first time, is read as it was before that flight.
fn fill_is_titles(src: usize, len: usize) -> bool {
const SMALL: usize = 64 << 10;
static ON: OnceLock<bool> = OnceLock::new();
let on = *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_TITLE").is_some_and(|v| v == "1"));
on && len <= SMALL && (crate::watch::written_since_taken(src, len) || !crate::watch::landed_lately(src, len, 600))
}
/// Diagnostics: the reads that made a submission wait for flights: what
/// kind, where, how much, and the declared write it lies in; how often and
/// how long the wait was.
#[cfg(feature = "diagnostics")]
type Blame = std::collections::HashMap<(&'static str, usize, usize, usize, usize), (u64, u64)>;
#[cfg(feature = "diagnostics")]
static BLAME: Mutex<Option<Blame>> = Mutex::new(None);
#[cfg(feature = "diagnostics")]
static BLAMED: Mutex<Option<(&'static str, usize, usize, usize, usize)>> = Mutex::new(None);
#[cfg(feature = "diagnostics")]
fn blame(kind: &'static str, written: &[(usize, usize)], at: usize, len: usize) {
let i = written.partition_point(|r| r.1 <= at);
let (from, to) = written.get(i).copied().unwrap_or((0, 0));
*BLAMED.lock().unwrap_or_else(|e| e.into_inner()) = Some((kind, at, len, from, to - from));
}
/// The wait for what [`blame`] last named took `us`.
#[cfg(feature = "diagnostics")]
fn blamed(us: u64) {
if let Some(key) = BLAMED.lock().unwrap_or_else(|e| e.into_inner()).take() {
let mut all = BLAME.lock().unwrap_or_else(|e| e.into_inner());
let e = all.get_or_insert_with(Default::default).entry(key).or_insert((0, 0));
e.0 += 1;
e.1 += us;
}
}
#[cfg(feature = "diagnostics")]
fn log_blame(frames: f64) {
let all = BLAME.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
let mut all: Vec<_> = all.into_iter().collect();
all.sort_unstable_by_key(|(_, (_, us))| std::cmp::Reverse(*us));
for ((kind, at, len, from, size), (n, us)) in all.into_iter().take(8) {
tracing::info!(
"waited for flights, per frame: {:.1} ms in {:.2} waits for {kind} {at:#x}+{len:#x}, in shader writes declared over {from:#x}+{size:#x}",
us as f64 / 1e3 / frames,
n as f64 / frames
);
}
}
/// [`late_blocked`] against `written`, the title memory flights' shaders
/// may write (in order, joined); `count` whether the kind of read is
/// counted for the frame line.
@@ -2052,17 +2144,26 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
for step in &list.deferred().copies {
match step {
&Step::Copy(dst, src, len) => {
if touches(written, src, src + len) || touches(written, dst, dst + len) {
let read = touches(written, src, src + len) && !fill_is_titles(src, len);
if read || touches(written, dst, dst + len) {
if count {
LATE_STATS[15].fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
if read {
blame("a buffer copy's source", written, src, len);
} else {
blame("a buffer copy's destination", written, dst, len);
}
}
return Some(WHY_READ);
}
}
&Step::Fill(_, src, len) => {
if touches(written, src, src + len) {
if touches(written, src, src + len) && !fill_is_titles(src, len) {
if count {
LATE_STATS[16].fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
blame("a fill of upload memory", written, src, len);
}
return Some(WHY_READ);
}
@@ -2072,6 +2173,8 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
if touches(written, at, at + len) {
if count {
LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
blame("a texture", written, at, len);
}
return Some(WHY_READ);
}
@@ -2316,6 +2419,8 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
LATE_STATS[12].fetch_add(us, Ordering::Relaxed);
LATE_WAITED[why.min(10)].fetch_add(us, Ordering::Relaxed);
SUBMISSION_US[1].fetch_add(us, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
blamed(us);
}
/// What the thread that lands flights fetches card copies' pieces with
@@ -2323,6 +2428,8 @@ fn relay_wait(why: usize, done: impl Fn(&Line) -> bool) {
/// behind the submission lock), and the memory the pieces come down to.
struct RelayFetch {
list: Prelude,
/// With [`relay_copy`]: the card's copy queue, which `list` is for.
queue: Option<ID3D12CommandQueue>,
fence: ID3D12Fence,
event: HANDLE,
/// The last value signalled on `fence`.
@@ -3096,6 +3203,7 @@ impl Host {
check: None,
_synced: dirty.into_iter().map(|(shadow, _)| shadow).collect(),
lists: used,
sent_as,
};
// Each byte once, as the copy-back joins the declared ranges. The
// results go behind those of plans still in the air.
@@ -3212,13 +3320,36 @@ impl Host {
/// The relay's own list, fence, event for [`Host::relay_card_back`].
fn make_relay_fetch(&self) -> Option<RelayFetch> {
let list = self.make_prelude()?;
// SAFETY: plain object creation.
let copying = relay_copy().then(|| unsafe {
(|| -> windows::core::Result<(Prelude, ID3D12CommandQueue)> {
let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
let list: ID3D12GraphicsCommandList =
self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
list.Close()?;
let queue: ID3D12CommandQueue = self.device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_COPY,
Priority: D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0,
..Default::default()
})?;
Ok(((allocator, list), queue))
})()
});
let (list, queue) = match copying {
Some(Ok((list, queue))) => (list, Some(queue)),
Some(Err(e)) => {
tracing::warn!(error = %e, "no copy queue: what shaders wrote to the card's memory is fetched on the drawing queue");
(self.make_prelude()?, None)
}
None => (self.make_prelude()?, None),
};
// SAFETY: plain objects of our own.
unsafe {
let fence: ID3D12Fence = self.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
let event = CreateEventW(None, false, false, None).ok()?;
Some(RelayFetch {
list,
queue,
fence,
event,
sent: 0,
@@ -3278,14 +3409,22 @@ impl Host {
}
}
}
if pieces.is_empty() {
// Nothing to fetch: every send so far is older than the next fetch.
crate::shadow::relay_fetched(*QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()));
return;
}
if fetch.is_none() {
*fetch = self.make_relay_fetch();
}
// The sends these flights ran behind, all a fetch on the copy queue
// is known to have run behind.
let behind = plans.iter().map(|p| p.sent_as).max().unwrap_or(0);
if pieces.is_empty() {
// Nothing to fetch: every send so far is older than the next
// fetch, if that goes to the queue the sends went to.
let after = match fetch.as_ref().is_some_and(|f| f.queue.is_some()) {
true => behind,
false => *QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner()),
};
crate::shadow::relay_fetched(after);
return;
}
let Some(f) = fetch.as_mut() else {
fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)"));
};
@@ -3298,6 +3437,7 @@ impl Host {
};
f.sent += 1;
let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent);
let copy_queue = f.queue.clone();
let waiting = std::time::Instant::now();
// SAFETY: the list's last run was waited for by this thread; live
// buffers (the copies are held by the plans); the fence and the
@@ -3311,6 +3451,13 @@ impl Host {
}
list.Close()?;
let lists = [Some(list.cast::<ID3D12CommandList>()?)];
if let Some(queue) = &copy_queue {
queue.ExecuteCommandLists(&lists);
queue.Signal(&fence, sent)?;
fence.SetEventOnCompletion(sent, event)?;
WaitForSingleObject(event, INFINITE);
return Ok(behind);
}
// In the order of the queue: the sends of title bytes so
// far are ahead of this fetch, every later one behind it.
let order = QUEUE_ORDER.lock().unwrap_or_else(|e| e.into_inner());
@@ -5848,6 +5995,7 @@ impl Meter {
);
#[cfg(feature = "diagnostics")]
{
log_blame(frames);
crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
for (why, n) in drops.iter().take(40) {
tracing::info!(
@@ -6509,4 +6657,4 @@ mod batch { // Batch::texture_due lives here; `mod tests` is already taken at
);
}
}
+2
View File
@@ -37,6 +37,8 @@ pub mod list;
pub mod object;
pub mod pipeline;
#[cfg(windows)]
mod pool;
#[cfg(windows)]
mod primitive;
pub mod query;
pub mod queue;
+11 -1
View File
@@ -607,7 +607,9 @@ pub(crate) fn save(now: bool) {
size
}
};
let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect();
// Through `used`: a process that asked for none yet (`victory shaders`)
// must not write the earlier runs' list over with nothing.
let used: Vec<String> = used().iter().flatten().cloned().collect();
let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) };
if bytes > 0 && library_written.is_ok() {
// In place unless the system refused and the new one waits beside it.
@@ -694,7 +696,15 @@ fn used() -> std::sync::MutexGuard<'static, Option<HashSet<String>>> {
}
/// Whether the title pipeline with `key` was requested in this or an earlier run.
///
/// `VICTORY_EARLY_ALL=1`: every title pipeline is started at creation,
/// requested before or not, so that the driver's own cache holds it for
/// later runs.
pub(crate) fn wanted_early(key: &str) -> bool {
static ALL: OnceLock<bool> = OnceLock::new();
if *ALL.get_or_init(|| std::env::var_os("VICTORY_EARLY_ALL").is_some_and(|v| v == "1")) {
return true;
}
used().as_ref().is_some_and(|s| s.contains(key))
}
+456
View File
@@ -0,0 +1,456 @@
//! Host memory for the textures the title fills, and for their staging
//! buffers, cut from blocks made once.
//!
//! Each such texture had an allocation of its own and its staging buffer
//! another. On an RX 7900 XTX an allocation takes about 310 microseconds
//! whatever its size, on one thread (`texture::allocation_costs`), and a
//! texture cut from a block 6: the pass that makes the textures shaders
//! pick by index (`draw.rs` `heap_textures`) got through 350-500 of the
//! 24,000 queued when the world loads in each of its 250 ms turns, some
//! forty seconds of a world without its textures.
//! `VICTORY_TEXTURE_POOL=0` makes every one an allocation of its own again.
//!
//! A piece given back is used again only two seconds later (nothing the card
//! was told before that is still running: Windows resets a card that takes
//! that long over one submission), and by then no list names it (the owners' rule, as for allocations of their own): a
//! texture's piece comes back when the last reference to the host texture
//! goes (an object of ours the texture holds says so), a staging buffer's
//! when the last list that recorded its copy is reset.
use std::collections::{BTreeMap, VecDeque};
use std::ffi::c_void;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, 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.
const BLOCK: u64 = 64 << 20;
/// Blocks with nothing in them that are kept.
const SPARE: usize = 2;
/// Milliseconds until a piece given back is used again. (It was three
/// frames, a tenth of a second while the title shows a loading screen at 30
/// a second, with up to 18 submissions in the air.)
const REST: u64 = 2500;
fn now() -> u64 {
crate::host::now_ms()
}
pub(crate) fn on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0"))
}
/// The free ranges of a block: start and length, never two that touch.
struct Ranges(BTreeMap<u64, u64>);
impl Ranges {
fn new(size: u64) -> Ranges {
Ranges(BTreeMap::from([(0, size)]))
}
/// The lowest place for `len` bytes at a multiple of `align`.
fn take(&mut self, len: u64, align: u64) -> Option<u64> {
let (start, size, at) = self.0.iter().find_map(|(&start, &size)| {
let at = start.next_multiple_of(align);
(at + len <= start + size).then_some((start, size, at))
})?;
self.0.remove(&start);
if at > start {
self.0.insert(start, at - start);
}
if at + len < start + size {
self.0.insert(at + len, start + size - at - len);
}
Some(at)
}
fn give(&mut self, mut start: u64, mut len: u64) {
if let Some((&before, &size)) = self.0.range(..start).next_back()
&& before + size == start
{
self.0.remove(&before);
(start, len) = (before, len + size);
}
if let Some(size) = self.0.remove(&(start + len)) {
len += size;
}
self.0.insert(start, len);
}
fn whole(&self, size: u64) -> bool {
self.0.get(&0) == Some(&size)
}
}
/// A part of a block.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Piece {
block: usize,
start: u64,
len: u64,
}
struct Block<B> {
memory: B,
free: Ranges,
/// The end of the highest piece ever taken: above it the memory is as
/// it was made (zeros).
used_to: u64,
}
struct Pool<B> {
/// `None`: a block let go, its place to be used again.
blocks: Vec<Option<Block<B>>>,
/// Pieces given back, and when each may be used again.
resting: VecDeque<(u64, Piece)>,
}
impl<B: Clone> Pool<B> {
const fn new() -> Pool<B> {
Pool { blocks: Vec::new(), resting: VecDeque::new() }
}
/// 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 {
return None;
}
self.rested(now);
let mut found = None;
for (i, block) in self.blocks.iter_mut().enumerate() {
if let Some(block) = block
&& let Some(start) = block.free.take(len, align)
{
found = Some((i, start));
break;
}
}
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 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 give(&mut self, piece: Piece, now: u64) {
self.resting.push_back((now + REST, piece));
}
/// Makes the pieces that rested long enough free, and lets go of empty
/// blocks past [`SPARE`].
fn rested(&mut self, now: u64) {
let mut any = false;
while let Some(&(ready, piece)) = self.resting.front()
&& ready <= now
{
self.resting.pop_front();
if let Some(block) = self.blocks[piece.block].as_mut() {
block.free.give(piece.start, piece.len);
any |= block.free.whole(BLOCK);
}
}
if any {
let mut spare = 0;
for block in &mut self.blocks {
if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
spare += 1;
if spare > SPARE {
*block = None;
}
}
}
}
}
fn blocks(&self) -> usize {
self.blocks.iter().flatten().count()
}
}
/// A mapped upload buffer's memory.
#[derive(Clone)]
struct Upload(ID3D12Resource, *mut u8);
// SAFETY: the mapping is written by the owners of its pieces, each its own.
unsafe impl Send for Upload {}
static TEXTURES: Mutex<Pool<ID3D12Heap>> = Mutex::new(Pool::new());
static STAGING: Mutex<Pool<Upload>> = Mutex::new(Pool::new());
fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// For the memory line: blocks of textures and of staging buffers, in MiB.
#[cfg(feature = "diagnostics")]
pub(crate) fn memory() -> [u64; 2] {
[lock(&TEXTURES).blocks() as u64 * (BLOCK >> 20), lock(&STAGING).blocks() as u64 * (BLOCK >> 20)]
}
/// Part of a block of mapped upload memory, back in the pool when dropped.
pub(crate) struct StagingPiece(Piece);
impl Drop for StagingPiece {
fn drop(&mut self) {
lock(&STAGING).give(self.0, now());
}
}
/// `bytes` of upload memory, all zeros: the buffer it lies in, where in
/// that buffer, and its mapping. `None`: not pooled.
pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> {
if !on() {
return None;
}
// Copies from a buffer begin at multiples of 512.
let bytes = bytes.next_multiple_of(512);
let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
let (buffer, data) = host.upload_buffer(BLOCK)?;
crate::host::name(&buffer, || "staging of textures (a block)".into());
Some(Upload(buffer, data))
})?;
let owned = StagingPiece(piece);
// SAFETY: the piece lies in the block's mapping.
let data = unsafe { memory.1.add(piece.start as usize) };
if again {
// What is not detiled into it (an unmapped texture) uploads zeros,
// as from a buffer of its own.
// SAFETY: the piece is ours alone.
unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
}
Some((owned, memory.0, piece.start, data))
}
/// An object the host texture holds and releases when it goes: its piece
/// is free then.
#[repr(C)]
struct Reclaim {
methods: &'static [*const (); 3],
references: AtomicU32,
piece: Piece,
}
struct Methods([*const (); 3]);
// SAFETY: function addresses only.
unsafe impl Sync for Methods {}
static RECLAIM: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]);
unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
const E_NOINTERFACE: HRESULT = HRESULT(0x8000_4002_u32 as i32);
// SAFETY: COM's arguments.
unsafe {
if out.is_null() {
return HRESULT(0x8000_4003_u32 as i32);
}
if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) {
add_ref(this);
*out = this;
return HRESULT(0);
}
*out = std::ptr::null_mut();
}
E_NOINTERFACE
}
unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
// SAFETY: one of ours, alive while a reference to it is.
unsafe { (*this.cast::<Reclaim>()).references.fetch_add(1, Ordering::Relaxed) + 1 }
}
unsafe extern "system" fn release(this: *mut c_void) -> u32 {
// SAFETY: as above; the last reference frees the box it was made as.
unsafe {
let left = (*this.cast::<Reclaim>()).references.fetch_sub(1, Ordering::AcqRel) - 1;
if left == 0 {
let gone = Box::from_raw(this.cast::<Reclaim>());
lock(&TEXTURES).give(gone.piece, now());
}
left
}
}
/// Makes `texture` give `piece` back when the last reference to it goes.
fn give_back_with(texture: &ID3D12Resource, piece: Piece) {
const KEY: GUID = GUID::from_u128(0x6f0e2f0c_5a59_4b1e_9a3f_7f4d2c9be713);
let made = Box::into_raw(Box::new(Reclaim { methods: &RECLAIM.0, references: AtomicU32::new(1), piece }));
// SAFETY: a COM object of ours with one reference, which this takes and
// drops at the end; the texture takes its own.
unsafe {
let object = IUnknown::from_raw(made.cast());
if texture.SetPrivateDataInterface(&KEY, &object).is_err() {
// Never given back: the piece stays taken, nothing is reused
// under a texture that may be alive.
std::mem::forget(object);
}
}
}
/// A texture of `desc` (no target, depth or unordered access) in a block;
/// `None`: not pooled, or the host refused.
///
/// # Safety
/// `desc` is a valid description.
pub(crate) unsafe fn texture(
device: &ID3D12Device,
desc: *const D3D12_RESOURCE_DESC,
state: D3D12_RESOURCE_STATES,
) -> Option<ID3D12Resource> {
if !on() {
return None;
}
// Small textures lie at multiples of 4 KiB where the host allows it
// (the top mip is 64 KiB at most): 64 KiB each otherwise.
// SAFETY: the caller's description.
let mut d = unsafe { *desc };
d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT);
// SAFETY: plain queries.
let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment {
d.Alignment = 0;
info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
}
if info.SizeInBytes == u64::MAX {
return None;
}
let (piece, heap, _) = lock(&TEXTURES).take(info.SizeInBytes, info.Alignment.max(1), 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,
};
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");
}
heap
})?;
let mut made: Option<ID3D12Resource> = None;
// SAFETY: the piece is no one else's; the heap lives while a piece of
// it is taken.
let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) };
match (result, made) {
(Ok(()), Some(made)) => {
give_back_with(&made, piece);
Some(made)
}
_ => {
lock(&TEXTURES).give(piece, now());
None
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ranges_are_cut_aligned_and_join_again() {
let mut r = Ranges::new(1024);
assert_eq!(r.take(100, 64), Some(0));
assert_eq!(r.take(100, 64), Some(128));
assert_eq!(r.take(28, 4), Some(100));
assert_eq!(r.take(2000, 4), None);
r.give(128, 100);
r.give(0, 100);
assert!(!r.whole(1024));
r.give(100, 28);
assert!(r.whole(1024));
}
#[test]
fn pieces_never_overlap_and_rest_before_they_are_used_again() {
let mut pool: Pool<u32> = Pool::new();
let made = std::cell::Cell::new(0);
let make = || {
made.set(made.get() + 1);
Some(made.get())
};
let mut taken: Vec<Piece> = Vec::new();
for i in 0..500u64 {
let (p, _, again) = pool.take(65536 * (1 + i % 7), 65536, 0, make).unwrap();
assert!(!again);
assert!(taken.iter().all(|q| q.block != p.block || p.start + p.len <= q.start || q.start + q.len <= p.start));
taken.push(p);
}
let blocks = pool.blocks();
assert!(blocks >= 2);
// Given back at 10: not used again before 10 + REST.
let first = taken[0];
pool.give(first, 10);
let (p, _, _) = pool.take(first.len, 65536, 10 + REST - 1, make).unwrap();
assert_ne!((p.block, p.start), (first.block, first.start));
let (q, _, again) = pool.take(first.len, 65536, 10 + REST, make).unwrap();
assert_eq!((q.block, q.start, again), (first.block, first.start, true));
// Everything back: the empty blocks past the spare ones go.
for p in taken.drain(1..).chain([p, q]) {
pool.give(p, 20);
}
pool.rested(20 + REST);
assert_eq!(pool.blocks(), blocks.min(SPARE));
// Too big for a block, and a block that cannot be made.
assert!(pool.take(BLOCK, 65536, 30, make).is_none());
let mut none: Pool<u32> = Pool::new();
assert!(none.take(65536, 65536, 0, || None).is_none());
}
/// A pooled texture's piece comes back when its last reference goes, not
/// before; its staging piece begins as zeros.
#[test]
fn a_texture_gives_its_piece_back_when_it_goes() {
let Some(host) = crate::host::host() else { return };
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: 256,
Height: 256,
DepthOrArraySize: 1,
MipLevels: 1,
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
};
// SAFETY: a valid description.
let Some(t) = (unsafe { texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }) else { return };
assert_eq!(crate::host::references(&t), 1, "what the texture holds is no reference to it");
let resting = || lock(&TEXTURES).resting.len();
let before = resting();
let other = t.clone();
drop(t);
assert_eq!(resting(), before);
drop(other);
assert_eq!(resting(), before + 1);
// SAFETY: the piece's mapping, 4096 bytes of it ours.
unsafe {
let (piece, _, at, data) = staging(host, 4096).unwrap();
assert!(at.is_multiple_of(512));
std::ptr::write_bytes(data, 0xAB, 4096);
drop(piece);
lock(&STAGING).rested(u64::MAX);
let (_piece, _, _, data) = staging(host, 4096).unwrap();
assert!((0..4096).all(|i| *data.add(i) == 0));
// SAFETY: plain query.
assert!(host.device.GetDeviceRemovedReason().is_ok());
}
}
}
+21
View File
@@ -1687,6 +1687,27 @@ fn host_texture(
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
// A texture the title fills, whose every subresource is uploaded before
// anything reads it: cut from a block (what the piece held before shows
// in no texel).
if fills(desc)
&& d.sample_count <= 1
&& clear_value.is_none()
&& texture_layout(desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor())
// SAFETY: the description has the host layout, as below.
&& let Some(t) = unsafe {
crate::pool::texture(
&host.device,
(&raw const d).cast(),
D3D12_RESOURCE_STATES(crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32),
)
}
{
crate::host::name(&t, || {
format!("texture {}x{} f{} flags {:#x} (in a block)", d.width, d.height, d.format, d.flags)
});
return Some(t);
}
let mut texture: Option<ID3D12Resource> = None;
// SAFETY: the description has the host layout (checked size, same
// fields); the out pointer is ours.
+56 -45
View File
@@ -1,7 +1,7 @@
//! Translated shaders kept on disk (decision 0003): under the configured
//! cache folder, keyed by the container's content and by the VIctory build
//! that translated it (the BLAKE3 of our executable), so a rebuilt
//! translator never serves an old translation. Entries go through
//! cache folder, keyed by the container's content and by the translator
//! (the BLAKE3 of its sources) and its settings, so a changed translator
//! never serves an old translation. Entries go through
//! `victory-pipeline`'s content-addressed cache, which writes them
//! atomically; an entry that does not read back is translated again.
//!
@@ -37,13 +37,13 @@ pub(crate) fn counts() -> (u64, u64) {
(HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed))
}
/// What identifies this build: the BLAKE3 of our executable file and of
/// the translation settings it runs with (the loop limit, which a
/// diagnostics build can change at run time).
fn build() -> &'static [u8; 32] {
static BUILD: OnceLock<[u8; 32]> = OnceLock::new();
BUILD.get_or_init(|| {
let exe = std::env::current_exe().and_then(std::fs::read);
/// What identifies a translation beside its container: the translator
/// (the BLAKE3 of its sources, `build.rs`), the settings it runs with, and
/// what it was told of the host. Not our executable: a rebuild of anything
/// else used to translate every shader again.
fn build() -> [u8; 32] {
static FIXED: OnceLock<Vec<u8>> = OnceLock::new();
let fixed = FIXED.get_or_init(|| {
let limit = victory_shader::emit::loop_limit();
if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT {
tracing::warn!(
@@ -51,42 +51,53 @@ fn build() -> &'static [u8; 32] {
"VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"
);
}
match exe {
Ok(mut bytes) => {
bytes.extend_from_slice(&limit.to_le_bytes());
// Which group barriers wait is part of the translation too.
bytes.push(victory_shader::emit::group_sync());
// So are the switches that pick the form of a wave64 program:
// without them here a run with `VICTORY_WAVE_WIDE=0` was
// served the translations an earlier run of the same
// executable had cached with the switch unset.
for name in [
"VICTORY_WAVE_WIDE",
"VICTORY_WAVE_DEEP_SKIPS",
"VICTORY_WAVE_OWN_BITS",
"VICTORY_F16_NEAREST",
] {
bytes.extend_from_slice(name.as_bytes());
bytes.push(b'=');
if let Some(value) = std::env::var_os(name) {
bytes.extend_from_slice(value.as_encoded_bytes());
}
bytes.push(0);
}
// And which clean-up passes ran over the translated code.
bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes());
*blake3::hash(&bytes).as_bytes()
}
Err(e) => {
// Without it no entry can be trusted: a fresh key per run.
tracing::warn!(error = %e, "cannot read our executable; shader cache unused");
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
*blake3::hash(&now.as_nanos().to_le_bytes()).as_bytes()
let mut bytes = env!("VICTORY_TRANSLATOR").as_bytes().to_vec();
bytes.extend_from_slice(&limit.to_le_bytes());
// Which group barriers wait is part of the translation too.
bytes.push(victory_shader::emit::group_sync());
// So are the switches that pick the form of a wave64 program:
// without them here a run with `VICTORY_WAVE_WIDE=0` was
// served the translations an earlier run of the same
// executable had cached with the switch unset.
for name in [
"VICTORY_WAVE_WIDE",
"VICTORY_WAVE_DEEP_SKIPS",
"VICTORY_WAVE_OWN_BITS",
"VICTORY_WAVE_LOCAL",
"VICTORY_F16_NEAREST",
"VICTORY_HELPER_OWN",
"VICTORY_STRICT_JOINS",
"VICTORY_MESH_OUTPUT_STRICT",
] {
bytes.extend_from_slice(name.as_bytes());
bytes.push(b'=');
if let Some(value) = std::env::var_os(name) {
bytes.extend_from_slice(value.as_encoded_bytes());
}
bytes.push(0);
}
})
// And which clean-up passes ran over the translated code.
bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes());
bytes
});
let mut hash = blake3::Hasher::new();
hash.update(fixed);
for value in victory_shader::emit::host_settings() {
hash.update(&value.to_le_bytes());
}
*hash.finalize().as_bytes()
}
/// Puts the translation of `container` into the cache before any title asks
/// for it (`victory shaders`): whether it was there already, or why it does
/// not translate. The host is opened first, as a run does: what the card
/// can do decides the form of some programs.
pub fn precompile(container: &[u8]) -> Result<bool, String> {
let _ = crate::host::host();
let misses = MISSES.load(Ordering::Relaxed);
host_shader(container)?;
// (Counts other threads' misses too: the caller only adds them up.)
Ok(MISSES.load(Ordering::Relaxed) == misses)
}
/// The translation of a console shader container, from the cache when
@@ -94,7 +105,7 @@ fn build() -> &'static [u8; 32] {
pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
match CACHE.get() {
Some(cache) => cached(cache, build(), container, translate),
Some(cache) => cached(cache, &build(), container, translate),
None => translate(container),
}
}
+4 -4
View File
@@ -2001,7 +2001,7 @@ impl Shadow {
*h = merged;
}
if differs != 0 {
crate::watch::writing(start + at, n);
crate::watch::landing(start + at, n);
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
written += n;
}
@@ -2090,7 +2090,7 @@ impl Shadow {
if !merge_piece(now, held, title) {
return 0;
}
crate::watch::writing(start + at, n);
crate::watch::landing(start + at, n);
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
n
}
@@ -2618,7 +2618,7 @@ impl Shadow {
*o = merged;
}
if differs != 0 {
crate::watch::writing(start + at, n);
crate::watch::landing(start + at, n);
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
written = n;
}
@@ -2693,7 +2693,7 @@ impl Shadow {
if !mapped || !changed {
return 0;
}
crate::watch::writing(start + at, n);
crate::watch::landing(start + at, n);
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
n
}
+158 -10
View File
@@ -33,7 +33,12 @@ macro_rules! once {
/// A texture's upload state: the staging buffer laid out as the host
/// texture's subresources, and what was last detiled.
pub(crate) struct Staging {
/// A buffer of its own, or the block [`Staging::piece`] is part of.
buffer: ID3D12Resource,
/// Where in `buffer` it begins (the footprints count from there).
base: u64,
/// Back in the pool with the last list that names it.
_piece: Option<crate::pool::StagingPiece>,
/// Its bytes.
#[cfg(feature = "diagnostics")]
size: u64,
@@ -552,6 +557,23 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::TexUploads, 1);
const COPY_DEST: u32 = 0x400;
// A texture cut from a block may lie where another did: what the card
// holds of that one is done with before the first upload into this one.
if crate::pool::on() && !staging.uploaded.load(Relaxed) {
let aliasing = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: std::mem::ManuallyDrop::new(None),
// SAFETY: a borrowed pointer the barrier never releases.
pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
}),
},
};
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[aliasing]) };
}
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging buffer lives as long as `staging`, which the deferred
// refresh below holds until the list is reset.
@@ -573,14 +595,14 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
d.MipLevels,
staging.footprints.len(),
staging.size,
footprint.Offset,
staging.base + footprint.Offset,
f.Width,
f.Height,
f.Depth,
f.RowPitch
)
},
(gpu + footprint.Offset, len),
(gpu + staging.base + footprint.Offset, len),
);
}
let to = D3D12_TEXTURE_COPY_LOCATION {
@@ -596,7 +618,10 @@ pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource)
pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: *footprint,
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: staging.base + footprint.Offset,
..*footprint
},
},
};
// SAFETY: an open list; both locations name live resources.
@@ -1074,18 +1099,26 @@ fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
Some(&mut total),
);
}
let (buffer, data) = host.upload_buffer(total)?;
crate::host::name(&buffer, || {
format!(
"staging of {resource:?} {}x{}x{} f{}",
d.Width, d.Height, d.DepthOrArraySize, d.Format.0
)
});
let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
None => {
let (buffer, data) = host.upload_buffer(total)?;
crate::host::name(&buffer, || {
format!(
"staging of {resource:?} {}x{}x{} f{}",
d.Width, d.Height, d.DepthOrArraySize, d.Format.0
)
});
(None, buffer, 0, data)
}
};
tracing::debug!(?desc, total, "texture contents uploaded from title memory");
STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed);
let s = Arc::new(Staging {
buffer,
base,
_piece: piece,
#[cfg(feature = "diagnostics")]
size: total,
data,
@@ -1214,3 +1247,118 @@ mod title_memory_tests {
}
}
}
/// How long this PC's card takes to make the allocations a staged texture needs, for
/// `cargo test -p victory-gpu allocation_costs -- --ignored --nocapture`.
#[cfg(test)]
mod allocation_costs {
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
fn texture(size: u32) -> D3D12_RESOURCE_DESC {
D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
Width: u64::from(size),
Height: size,
DepthOrArraySize: 1,
MipLevels: 0,
Format: DXGI_FORMAT_BC7_UNORM,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
..Default::default()
}
}
fn buffer(size: u64) -> D3D12_RESOURCE_DESC {
D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
}
}
fn committed(device: &ID3D12Device, kind: D3D12_HEAP_TYPE, flags: D3D12_HEAP_FLAGS, desc: &D3D12_RESOURCE_DESC) -> ID3D12Resource {
let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() };
let state = if kind == D3D12_HEAP_TYPE_UPLOAD { D3D12_RESOURCE_STATE_GENERIC_READ } else { D3D12_RESOURCE_STATE_COMMON };
let mut out = None;
// SAFETY: plain creation.
unsafe { device.CreateCommittedResource(&heap, flags, desc, state, None, &mut out) }.expect("committed");
out.unwrap()
}
fn timed(what: &str, n: usize, threads: usize, make: &(dyn Fn(usize) -> ID3D12Resource + Sync)) {
let began = std::time::Instant::now();
let all: Vec<_> = std::thread::scope(|s| {
(0..threads)
.map(|t| s.spawn(move || (t..n).step_by(threads).map(make).collect::<Vec<_>>()))
.collect::<Vec<_>>()
.into_iter()
.flat_map(|h| h.join().unwrap())
.collect()
});
let took = began.elapsed().as_secs_f64() * 1e3;
println!("{what}, {threads} thread(s): {n} in {took:.1} ms, {:.0} us each", took * 1e3 / n as f64);
drop(all);
}
#[test]
#[ignore = "a measurement, not a check"]
fn allocation_costs() {
let Some(host) = crate::host::host() else { return };
let device = &host.device;
let not_zeroed = D3D12_HEAP_FLAG_CREATE_NOT_ZEROED;
const N: usize = 1000;
for size in [128u32, 512, 1024] {
let (t, b) = (texture(size), buffer(u64::from(size * size) * 4 / 3 + 65536));
println!("-- BC7 {size}x{size}");
for threads in [1, 4, 8] {
timed("texture committed", N, threads, &|_| committed(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_FLAG_NONE, &t));
timed("texture committed not zeroed", N, threads, &|_| committed(device, D3D12_HEAP_TYPE_DEFAULT, not_zeroed, &t));
let mapped = |flags| {
let b = &b;
move |_| {
let r = committed(device, D3D12_HEAP_TYPE_UPLOAD, flags, b);
let mut data = std::ptr::null_mut();
// SAFETY: a live upload buffer.
unsafe { r.Map(0, None, Some(&mut data)) }.unwrap();
// SAFETY: the first byte of the mapping (its first touch).
unsafe { data.cast::<u8>().write_volatile(1) };
r
}
};
timed("staging committed and mapped", N, threads, &mapped(D3D12_HEAP_FLAG_NONE));
timed("staging committed and mapped, not zeroed", N, threads, &mapped(not_zeroed));
}
// SAFETY: plain query.
let info = unsafe { device.GetResourceAllocationInfo(0, &[t]) };
let per_heap = ((64u64 << 20) / info.SizeInBytes).max(1) as usize;
let heaps: Vec<ID3D12Heap> = (0..N.div_ceil(per_heap))
.map(|_| {
let desc = D3D12_HEAP_DESC {
SizeInBytes: per_heap as u64 * info.SizeInBytes,
Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | not_zeroed,
..Default::default()
};
let mut heap = None;
// SAFETY: plain creation.
unsafe { device.CreateHeap(&desc, &mut heap) }.expect("heap");
heap.unwrap()
})
.collect();
let place = |i: usize| {
let mut out: Option<ID3D12Resource> = None;
let at = (i % per_heap) as u64 * info.SizeInBytes;
// SAFETY: a part of a live heap no other texture has.
unsafe { device.CreatePlacedResource(&heaps[i / per_heap], at, &t, D3D12_RESOURCE_STATE_COMMON, None, &mut out) }.expect("placed");
out.unwrap()
};
timed("texture placed in 64 MB heaps", N, 1, &place);
timed("texture placed in 64 MB heaps", N, 8, &place);
}
}
}
+282 -136
View File
@@ -21,7 +21,7 @@
//! (none is known to).
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Mutex;
use std::sync::{Condvar, Mutex, RwLock};
/// The unit tracked and copied: 64 KiB, the console's page (the kernel's
/// 4 KiB pages fold into it). Finer units made the checks of the world's
@@ -30,13 +30,17 @@ pub(crate) const PAGE: usize = 64 << 10;
/// The kernel's page, the unit of its answers.
const KERNEL_PAGE: usize = 4096;
/// Numbers the askings; 0 is "never". Counted up with the journal held
/// (shared will do: what notes an answer holds it alone).
static ASKED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn next_asking() -> u64 {
ASKED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
}
struct Journal {
/// Numbers the askings; 0 is "never".
asked: u64,
/// Page number → the asking that last found it written.
written: BTreeMap<usize, u64>,
/// Room for the kernel's answer.
found: Vec<usize>,
/// Page ranges asked ahead for a submission's refreshes ([`ask_ahead`])
/// and the asking that did: `writes` answers for a range inside one
/// from the journal, without another kernel call.
@@ -48,15 +52,110 @@ struct Journal {
kept: bool,
}
static JOURNAL: Mutex<Journal> = Mutex::new(Journal {
asked: 0,
/// Read by many threads at once (a submission's refreshes run on several),
/// written only to note an answer: the kernel is asked, and view memory
/// guarded, with the range held in [`ASKING`] and not under this lock. Under
/// one lock for all of it those threads ran one at a time: 22 of 96 looks at
/// the submitting thread, and one in six of those at the six threads beside
/// it, found it waiting for that lock (run pooloff1).
static JOURNAL: RwLock<Journal> = RwLock::new(Journal {
written: BTreeMap::new(),
found: Vec::new(),
ahead: Vec::new(),
ahead_asked: 0,
kept: false,
});
fn journal() -> std::sync::RwLockReadGuard<'static, Journal> {
JOURNAL.read().unwrap_or_else(|e| e.into_inner())
}
fn journal_mut() -> std::sync::RwLockWriteGuard<'static, Journal> {
JOURNAL.write().unwrap_or_else(|e| e.into_inner())
}
/// The page ranges some thread is asking about: asking forgets what it
/// answers, so until the answer is in the journal no other thread may ask
/// about any of the same pages (it would be told they were not written).
/// Taken before the journal's lock, never under it.
static ASKING: (Mutex<Vec<(usize, usize)>>, Condvar) = (Mutex::new(Vec::new()), Condvar::new());
/// Pages `[first, last)` held in [`ASKING`] until dropped.
struct Asking(usize, usize);
impl Asking {
fn hold(first: usize, last: usize) -> Asking {
let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner());
while held.iter().any(|&(a, b)| a < last && first < b) {
held = ASKING.1.wait(held).unwrap_or_else(|e| e.into_inner());
}
held.push((first, last));
Asking(first, last)
}
/// Everything: an asking for a whole submission.
fn hold_all() -> Asking {
Asking::hold(0, usize::MAX)
}
}
impl Drop for Asking {
fn drop(&mut self) {
let mut held = ASKING.0.lock().unwrap_or_else(|e| e.into_inner());
if let Some(i) = held.iter().position(|&r| r == (self.0, self.1)) {
held.swap_remove(i);
}
drop(held);
ASKING.1.notify_all();
}
}
thread_local! {
/// Room for the kernel's answer.
static FOUND: std::cell::RefCell<Vec<usize>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// The pages of `[first, last)` the kernel says were written since it was
/// last asked, in order, each once; `None` if the range is not write-watched
/// memory of one reservation. The caller holds the range ([`Asking`]).
fn kernel_written(first: usize, last: usize) -> Option<Vec<usize>> {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
FOUND.with(|found| {
let mut found = found.borrow_mut();
let mut count = (last - first) * PAGE / KERNEL_PAGE;
if found.len() < count {
found.resize(count, 0);
}
let mut granularity = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: the answer buffer holds `count` entries.
let failed = unsafe {
GetWriteWatch(
WRITE_WATCH_FLAG_RESET,
(first * PAGE) as *const _,
(last - first) * PAGE,
found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
} != 0;
if failed {
return None;
}
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
}
let mut pages: Vec<usize> = found[..count].iter().map(|&at| at / PAGE).collect();
pages.dedup();
Some(pages)
})
}
/// Ranges of one submission closer than this are asked about together:
/// walking the pages between them costs less than another kernel call (a
/// call that resets written pages costs 30-70 microseconds whatever the
@@ -81,16 +180,13 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
return;
}
pieces.sort_unstable();
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
// The submission's one asking stands ([`ask_once`]): what it does not
// hold is left to `writes`.
if j.kept {
if journal().kept {
return;
}
j.asked += 1;
j.ahead_asked = j.asked;
j.ahead.clear();
let _all = Asking::hold_all();
let (mut asked, mut written) = (Vec::new(), Vec::new());
let mut i = 0;
while i < pieces.len() {
let first = pieces[i].0;
@@ -103,9 +199,14 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) {
last = last.max(pieces[k].1);
k += 1;
}
ask_run(j, &pieces[i..k]);
ask_run(&pieces[i..k], &mut asked, &mut written);
i = k;
}
let mut j = journal_mut();
j.ahead_asked = next_asking();
j.ahead = asked;
let now = j.ahead_asked;
j.written.extend(written.into_iter().map(|page| (page, now)));
}
/// Since the last frame line: the kernel askings that took a millisecond
@@ -135,7 +236,7 @@ pub(crate) fn slow_asks() -> [u64; 3] {
/// The submission's refreshes are done: `writes` asks the kernel again.
pub(crate) fn ask_ahead_done() {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let mut j = journal_mut();
if !j.kept {
j.ahead.clear();
}
@@ -174,34 +275,44 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
}
ask_once_end();
ask_ahead(ranges);
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
if j.ahead.is_empty() {
// `ask_ahead` asked nothing (fewer than two ranges).
j.asked += 1;
j.ahead_asked = j.asked;
}
let _all = Asking::hold_all();
let mut ahead = {
let mut j = journal_mut();
if j.ahead.is_empty() {
// `ask_ahead` asked nothing (fewer than two ranges).
j.ahead_asked = next_asking();
}
std::mem::take(&mut j.ahead)
};
// `ask_ahead` leaves a range that lies alone to `writes`, which asks
// once per flush: with one asking for the submission that was every
// such range asked again at each of its 70 flushes (run 76: 2,300
// askings a frame with the switch on, as without it). They are asked
// here, once; what is not write-watched stays with `writes`.
let mut written = Vec::new();
for &(start, end) in ranges {
if start >= end {
continue;
}
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
if !j.ahead.iter().any(|&(a, b)| a <= first && last <= b) && ask_kernel(j, first, last) {
j.ahead.push((first, last));
if !ahead.iter().any(|&(a, b)| a <= first && last <= b)
&& let Some(pages) = kernel_written(first, last)
{
written.extend(pages);
ahead.push((first, last));
}
}
j.kept = !j.ahead.is_empty();
let mut j = journal_mut();
let now = j.ahead_asked;
j.written.extend(written.into_iter().map(|page| (page, now)));
j.kept = !ahead.is_empty();
j.ahead = ahead;
}
/// The submission's one asking stands no longer: its refreshes are done,
/// or title memory was written in a way the journal was not told.
pub(crate) fn ask_once_end() {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let mut j = journal_mut();
if j.kept {
j.kept = false;
j.ahead.clear();
@@ -212,12 +323,15 @@ pub(crate) fn ask_once_end() {
/// stands (the title's buffer copies, done at submission): its pages count
/// as written after that asking, so the refreshes that follow copy them.
pub(crate) fn wrote(at: usize, len: usize) {
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let mut j = journal_mut();
if !j.kept || len == 0 {
return;
}
j.asked += 1;
let now = j.asked;
let now = next_asking();
// What is copied from now on counts as copied after these writes (fork
// PR 410): answers older than the writes in them made every refresh
// until the next asking copy the pages again.
j.ahead_asked = now;
for page in at / PAGE..at.saturating_add(len).div_ceil(PAGE) {
j.written.insert(page, now);
}
@@ -225,60 +339,22 @@ pub(crate) fn wrote(at: usize, len: usize) {
/// One kernel asking for `pieces` (page ranges in order); by halves if it
/// fails, as a run across two reservations or into memory that is not
/// write-watched does. A piece alone is left to [`writes`].
fn ask_run(j: &mut Journal, pieces: &[(usize, usize)]) {
/// write-watched does. A piece alone is left to [`writes`]. Adds what was
/// asked to `asked` and the pages found written to `written`.
fn ask_run(pieces: &[(usize, usize)], asked: &mut Vec<(usize, usize)>, written: &mut Vec<usize>) {
if pieces.len() < 2 {
return;
}
let first = pieces[0].0;
let last = pieces.iter().map(|p| p.1).max().unwrap_or(first);
if ask_kernel(j, first, last) {
j.ahead.push((first, last));
if let Some(pages) = kernel_written(first, last) {
written.extend(pages);
asked.push((first, last));
return;
}
let (a, b) = pieces.split_at(pieces.len() / 2);
ask_run(j, a);
ask_run(j, b);
}
/// Asks the kernel for the written pages of pages `[first, last)` and notes
/// them in the journal under the ahead asking; false (and nothing changed)
/// if the range is not write-watched memory of one reservation.
fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: the answer buffer holds `count` entries.
let failed = unsafe {
GetWriteWatch(
WRITE_WATCH_FLAG_RESET,
(first * PAGE) as *const _,
(last - first) * PAGE,
j.found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
} != 0;
if failed {
return false;
}
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
}
let now = j.ahead_asked;
for k in 0..count {
let page = j.found[k] / PAGE;
j.written.insert(page, now);
}
true
ask_run(a, asked, written);
ask_run(b, asked, written);
}
/// What [`writes`] would say of `[start, end)` from the journal alone, if
@@ -288,7 +364,7 @@ fn ask_kernel(j: &mut Journal, first: usize, last: usize) -> bool {
/// it). `None` if the kernel would have to be asked.
pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)> {
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = journal();
j.ahead
.iter()
.any(|&(a, b)| a <= first && last <= b)
@@ -301,71 +377,51 @@ pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>)
/// kernel just reported. `None` if the memory is not write-watched (nor,
/// with `guarded`, view memory, which is then guarded).
pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Vec<(usize, u64)>)> {
use windows_sys::Win32::System::Memory::GetWriteWatch;
const WRITE_WATCH_FLAG_RESET: u32 = 1;
let (first, last) = (start / PAGE, end.div_ceil(PAGE));
let mut j = JOURNAL.lock().unwrap_or_else(|e| e.into_inner());
let j = &mut *j;
let of = |j: &Journal| -> Vec<(usize, u64)> { j.written.range(first..last).map(|(&p, &w)| (p, w)).collect() };
// Asked ahead with the submission's other ranges: the journal has it.
if j.ahead.iter().any(|&(a, b)| a <= first && last <= b) {
return Some((
j.ahead_asked,
j.written
.range(first..last)
.map(|(&p, &w)| (p, w))
.collect(),
));
let ahead = |j: &Journal| j.ahead.iter().any(|&(a, b)| a <= first && last <= b).then(|| (j.ahead_asked, of(j)));
if let Some(known) = ahead(&journal()) {
return Some(known);
}
let mut count = (last - first) * PAGE / KERNEL_PAGE;
j.found.resize(count.max(j.found.len()), 0);
let mut granularity = 0;
#[cfg(feature = "diagnostics")]
let started = std::time::Instant::now();
// SAFETY: the answer buffer holds `count` entries.
let failed = unsafe {
GetWriteWatch(
WRITE_WATCH_FLAG_RESET,
(first * PAGE) as *const _,
(last - first) * PAGE,
j.found.as_mut_ptr().cast(),
&mut count,
&mut granularity,
)
} != 0;
let guarded = if failed {
count = 0;
if !guarded {
return None;
// Asked, and the answer noted, with the range held: nothing else asks
// about any of it in between.
let _range = Asking::hold(first, last);
if let Some(known) = ahead(&journal()) {
return Some(known);
}
let pages = match kernel_written(first, last) {
Some(pages) => pages,
None => {
if !guarded {
return None;
}
#[cfg(feature = "diagnostics")]
let guarding = std::time::Instant::now();
let written = guard(first * PAGE, last * PAGE);
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
let us = guarding.elapsed().as_micros() as u64;
add(C::GuardUs, us);
if written.is_some() {
add(C::Watches, 1);
add(C::WatchUs, us);
slow(us);
}
}
written?
}
#[cfg(feature = "diagnostics")]
let guarding = std::time::Instant::now();
let written = guard(first * PAGE, last * PAGE);
#[cfg(feature = "diagnostics")]
crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64);
written?
} else {
Vec::new()
};
#[cfg(feature = "diagnostics")]
{
use crate::copystat::{C, add};
add(C::Watches, 1);
add(C::WatchUs, started.elapsed().as_micros() as u64);
slow(started.elapsed().as_micros() as u64);
if pages.is_empty() {
// Nothing to note: the others may go on reading.
let j = journal();
return Some((next_asking(), of(&j)));
}
j.asked += 1;
let now = j.asked;
let pages = j.found[..count].iter().map(|&at| at / PAGE).chain(guarded);
for page in pages.collect::<Vec<_>>() {
j.written.insert(page, now);
}
Some((
now,
j.written
.range(first..last)
.map(|(&p, &w)| (p, w))
.collect(),
))
let mut j = journal_mut();
let now = next_asking();
j.written.extend(pages.into_iter().map(|page| (page, now)));
Some((now, of(&j)))
}
/// Guarded blocks of view memory.
@@ -391,6 +447,47 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> {
GUARDS.lock().unwrap_or_else(|e| e.into_inner())
}
/// The 4 KiB pages of title memory that what shaders wrote was put into,
/// and the frame it last was.
static LANDED: Mutex<Option<std::collections::HashMap<usize, u64>>> = Mutex::new(None);
/// What shaders wrote is about to go into title memory at `[at, at + len)`.
pub(crate) fn landing(at: usize, len: usize) {
{
let frame = crate::frame::current();
let mut landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
let landed = landed.get_or_insert_with(Default::default);
for page in at / 4096..=(at + len.max(1) - 1) / 4096 {
landed.insert(page, frame);
}
}
writing(at, len);
}
/// Whether shaders' writes went into a page of `[at, at + len)` in the last
/// `frames` frames.
pub(crate) fn landed_lately(at: usize, len: usize, frames: u64) -> bool {
let since = crate::frame::current().saturating_sub(frames);
let landed = LANDED.lock().unwrap_or_else(|e| e.into_inner());
landed.as_ref().is_some_and(|landed| {
(at / 4096..=(at + len.max(1) - 1) / 4096).any(|page| landed.get(&page).is_some_and(|&f| f >= since))
})
}
/// Whether every block of `[at, at + len)` is view memory written since a
/// host copy last took it: guarded then, and the guard is off. (Written by
/// the title, or by us putting a flight's shader writes into it.) Not for
/// blocks no copy ever took, which were never guarded: the caller's range
/// lies in a copy a flight was given, which took all of it.
pub(crate) fn written_since_taken(at: usize, len: usize) -> bool {
if len == 0 {
return false;
}
let g = guards();
(at / BLOCK..=(at + len - 1) / BLOCK)
.all(|b| !g.protected.contains(&b) && !g.clean.contains(&b) && !g.absent.contains(&b))
}
/// For view memory: the pages of `[start, end)`'s blocks written since
/// they were last guarded (all of a block's pages), guarding them again
/// before the caller copies them. `None` if the memory is not a view.
@@ -1106,3 +1203,52 @@ mod mapping_tests {
assert!(read.load(Ordering::SeqCst));
}
}
#[cfg(test)]
mod many_askers_tests {
use super::{PAGE, writes};
use windows_sys::Win32::System::Memory::*;
/// Threads that write pages and ask about overlapping ranges at the same
/// time: whoever wrote a page before asking is told of that write (by
/// its own asking or by one that took the kernel's answer before it).
#[test]
fn no_write_is_lost_between_askers() {
const MEM_WRITE_WATCH: u32 = 0x20_0000;
const PAGES: usize = 48;
const THREADS: usize = 8;
// SAFETY: a reservation of our own, freed at the end.
let at = unsafe {
VirtualAlloc(std::ptr::null(), PAGES * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
} as usize;
assert!(at != 0 && at.is_multiple_of(PAGE));
std::thread::scope(|s| {
for t in 0..THREADS {
s.spawn(move || {
let mut last = [0u64; PAGES];
let mut seed = t as u64 * 7919 + 1;
let mut next = |n: usize| {
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
(seed >> 33) as usize % n
};
for _ in 0..4000 {
let page = next(PAGES);
let from = page - next(page.min(12) + 1);
let to = page + 1 + next((PAGES - page).min(12));
// SAFETY: committed memory of ours; what the racing
// writers leave in it does not matter.
unsafe { ((at + page * PAGE + t * 8) as *mut u64).write_volatile(1) };
let (now, written) = writes(at + from * PAGE, at + to * PAGE, false).expect("write-watched");
let number = written.iter().find(|w| w.0 == at / PAGE + page).map_or(0, |w| w.1);
assert!(number > last[page], "page {page}: {number} is not after {}", last[page]);
for l in &mut last[from..to] {
*l = now;
}
}
});
}
});
// SAFETY: the reservation made above.
unsafe { VirtualFree(at as *mut _, 0, MEM_RELEASE) };
}
}
+14
View File
@@ -36,6 +36,20 @@ fn host_gpu_failed(what: &str) -> ! {
unreachable!("the process has ended")
}
/// Translates `container` into the cache ([`use_shader_cache`]) ahead of
/// any run: whether it was there already, or why it does not translate.
pub fn precompile(container: &[u8]) -> Result<bool, String> {
#[cfg(windows)]
{
victory_gpu::shader_cache::precompile(container)
}
#[cfg(not(windows))]
{
let _ = container;
Err("no host".into())
}
}
/// Keeps the host's translations of the title's shaders in `dir` (a
/// folder of the cache) across runs, and its compiled pipelines beside it
/// (`pipelines`).
+44 -10
View File
@@ -955,25 +955,27 @@ fn into_destination(
// SAFETY: the title's destination holds `destination_size` bytes, at
// least `len`, and nothing else writes it until completion.
let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) };
return fill(out).map(drop);
let filled = fill(out).map(drop);
// Again now that the bytes are there: a texture looked at in between
// was uploaded without them (`xmem::pages_written`).
if super::xmem::stream_notice() {
victory_gpu::kernel_will_write(request.destination as usize, len);
}
return filled;
}
let offset = (request.page_offset & 0xffff) as usize;
// SAFETY: the title passes a page number per 64 KiB of destination,
// which holds at least `len` bytes from `offset`.
let pages = unsafe {
std::slice::from_raw_parts(
request.destination.cast::<usize>(),
(offset + len).div_ceil(PAGE),
)
};
let pages = &page_list(request.destination.cast(), offset, len)[..];
// Consecutive pages of one allocation (the usual case): written in
// place through one view.
if let Some(mut window) = super::xmem::page_window(pages, offset, len) {
return fill(window.bytes()).map(drop);
let filled = fill(window.bytes()).map(drop);
super::xmem::pages_written(pages, offset, len);
return filled;
}
let mut data = vec![0; len];
let n = fill(&mut data)?;
if super::xmem::write_physical(pages, offset, &data[..n]) {
super::xmem::pages_written(pages, offset, n);
Ok(())
} else {
// Said aloud: the title never reads a request's result
@@ -990,6 +992,38 @@ fn into_destination(
}
}
/// The request's page numbers, one per 64 KiB of destination. The title
/// queues a request before it has filled its page list in, and a worker that
/// reads the list at once finds page 0 in it (pages of models and textures
/// that were then never written: walls missing for the whole run). So a list
/// with a page the title does not own is read again for a while, up to
/// 1.5 s; what it holds then is used as it is.
fn page_list(list: *const usize, offset: usize, len: usize) -> Vec<usize> {
let read = || -> Vec<usize> {
(0..(offset + len).div_ceil(PAGE))
// SAFETY: the title passes a page number per 64 KiB of
// destination, which holds at least `len` bytes from `offset`;
// it may be writing them.
.map(|i| unsafe { list.add(i).read_volatile() })
.collect()
};
let started = std::time::Instant::now();
let mut pages = read();
while !super::xmem::pages_known(&pages, offset, len) && started.elapsed().as_millis() < 1500 {
std::thread::sleep(std::time::Duration::from_millis(1));
pages = read();
}
let waited = started.elapsed();
if waited.as_millis() >= 1 {
tracing::info!(
ms = waited.as_millis() as u64,
known = super::xmem::pages_known(&pages, offset, len),
"dstorage: a destination's page list was not filled in yet"
);
}
pages
}
/// Slots by the 2020 order, which the argument shapes at
/// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called).
static QUEUE_VTABLE: Methods<12> = Methods([
+225 -15
View File
@@ -342,7 +342,64 @@ pub extern "system" fn XMemIsToolsMemAvailable() -> BOOL {
const PAGE: usize = 64 << 10;
struct Section(HANDLE);
struct Section {
handle: HANDLE,
pages: usize,
/// A view of the whole section, kept ([`Section::window`]); 0 if the
/// host gave none.
window: std::sync::OnceLock<usize>,
/// A bit per page: committed, as far as [`Section::window`] asked.
committed: Box<[std::sync::atomic::AtomicU64]>,
}
impl Section {
/// Where bytes of `n` pages from page `index` on can be written,
/// whether or not the pages are mapped anywhere, committed.
///
/// Every DirectStorage write mapped a view of its pages, committed it,
/// faulted each of its 4 KiB pages in and unmapped it again, all of it
/// under the process's one address-space lock, with 24 workers, the
/// title's own mapping calls (about 100,000 views of one page) and our
/// guards asking for the same lock. One view of the section, kept,
/// costs that once per page.
/// `VICTORY_SECTION_WINDOW=0`: a view for each write, as before.
fn window(&self, index: usize, n: usize) -> Option<usize> {
use std::sync::atomic::Ordering;
use windows_sys::Win32::System::Memory::{FILE_MAP_WRITE, MapViewOfFile};
static ON: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("VICTORY_SECTION_WINDOW").is_none_or(|v| v != "0"));
if !*ON || index + n > self.pages {
return None;
}
let base = *self.window.get_or_init(|| {
// SAFETY: the whole of a section we own.
unsafe { MapViewOfFile(self.handle, FILE_MAP_WRITE, 0, 0, self.pages * PAGE) }.Value as usize
});
if base == 0 {
return None;
}
let missing = |page: usize| self.committed[page / 64].load(Ordering::Acquire) >> (page % 64) & 1 == 0;
let mut page = index;
while page < index + n {
if !missing(page) {
page += 1;
continue;
}
let run = (page..index + n).take_while(|&p| missing(p)).count();
if run == 0 {
continue; // another worker committed it meanwhile
}
if !commit(base + page * PAGE, run * PAGE) {
return None;
}
for p in page..page + run {
self.committed[p / 64].fetch_or(1 << (p % 64), Ordering::AcqRel);
}
page += run;
}
Some(base + index * PAGE)
}
}
// SAFETY: a section handle may be used from any thread.
unsafe impl Send for Section {}
@@ -351,8 +408,19 @@ unsafe impl Sync for Section {}
impl Drop for Section {
fn drop(&mut self) {
use windows_sys::Win32::System::Memory::UnmapViewOfFile;
if let Some(&base) = self.window.get()
&& base != 0
{
// SAFETY: our view; whoever writes through it holds the section.
unsafe {
UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS {
Value: base as *mut c_void,
})
};
}
// SAFETY: our handle; views keep the section alive on their own.
unsafe { CloseHandle(self.0) };
unsafe { CloseHandle(self.handle) };
}
}
@@ -370,6 +438,103 @@ struct Physical {
pages: HashMap<usize, Slice>,
/// Mapped views by address: their length and what they show.
views: BTreeMap<usize, (usize, Slice)>,
/// The other way: the views (by address) that show a page, by the page's
/// section and index. Views of more than [`SHORT`] pages are in `long`.
shown: HashMap<(usize, usize), Vec<usize>>,
long: Vec<usize>,
}
/// Pages of a view noted page by page in [`Physical::shown`].
const SHORT: usize = 64;
impl Physical {
fn note_view(&mut self, base: usize, len: usize, slice: &Slice) {
if len / PAGE > SHORT {
self.long.push(base);
return;
}
let section = Arc::as_ptr(&slice.section) as usize;
for k in 0..len / PAGE {
self.shown.entry((section, slice.index + k)).or_default().push(base);
}
}
fn forget_view(&mut self, base: usize, len: usize, slice: &Slice) {
if len / PAGE > SHORT {
self.long.retain(|&b| b != base);
return;
}
let section = Arc::as_ptr(&slice.section) as usize;
for k in 0..len / PAGE {
let key = (section, slice.index + k);
if let Some(views) = self.shown.get_mut(&key) {
views.retain(|&b| b != base);
if views.is_empty() {
self.shown.remove(&key);
}
}
}
}
/// Where the title sees `n` pages from `slice` on: addresses and bytes.
fn shown_at(&self, slice: &Slice, n: usize) -> Vec<(usize, usize)> {
let section = Arc::as_ptr(&slice.section) as usize;
let mut out: Vec<(usize, usize)> = Vec::new();
for k in 0..n {
for &base in self.shown.get(&(section, slice.index + k)).into_iter().flatten() {
if let Some((_, s)) = self.views.get(&base) {
out.push((base + (slice.index + k - s.index) * PAGE, PAGE));
}
}
}
for &base in &self.long {
let Some((len, s)) = self.views.get(&base) else { continue };
let from = slice.index.max(s.index);
let to = (slice.index + n).min(s.index + len / PAGE);
if Arc::as_ptr(&s.section) as usize == section && from < to {
out.push((base + (from - s.index) * PAGE, (to - from) * PAGE));
}
}
out
}
}
/// DirectStorage has put bytes `[offset, offset + len)` of `pages` into
/// memory: the GPU side is told where the title sees them, so that what it
/// copied there before they arrived (a texture uploaded when its view was
/// written holds whatever the pages held then) is copied again.
/// `VICTORY_STREAM_NOTICE=0`: not told, as before.
pub(crate) fn pages_written(pages: &[usize], offset: usize, len: usize) {
if !stream_notice() || len == 0 {
return;
}
let mut seen: Vec<(usize, usize)> = {
let physical = physical();
let numbers = pages.get(offset / PAGE..(offset + len).div_ceil(PAGE)).unwrap_or_default();
numbers
.iter()
.filter_map(|n| physical.pages.get(n))
.flat_map(|slice| physical.shown_at(slice, 1))
.collect()
};
seen.sort_unstable();
let mut runs: Vec<(usize, usize)> = Vec::new();
for (at, len) in seen {
match runs.last_mut() {
Some(last) if last.0 + last.1 == at => last.1 += len,
_ => runs.push((at, len)),
}
}
for (at, len) in runs {
victory_gpu::kernel_will_write(at, len);
}
}
/// See [`pages_written`].
pub(crate) fn stream_notice() -> bool {
static ON: LazyLock<bool> =
LazyLock::new(|| std::env::var_os("VICTORY_STREAM_NOTICE").is_none_or(|v| v != "0"));
*ON
}
static PHYSICAL: LazyLock<Mutex<Physical>> = LazyLock::new(|| {
@@ -431,7 +596,12 @@ pub extern "system" fn XMemAllocatePhysicalPages(
// For the GPU side's in-place census: only a committed section can be
// opened as a host heap.
victory_gpu::title_memory_section(handle as usize, size as u64, on_wine());
let section = Arc::new(Section(handle));
let section = Arc::new(Section {
handle,
pages: n,
window: std::sync::OnceLock::new(),
committed: (0..n.div_ceil(64)).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(),
});
let mut physical = physical();
let first = physical.next_page;
physical.next_page += n * FRAMES;
@@ -481,7 +651,7 @@ impl View {
// SAFETY: slices of a section we own; the view is ours until dropped.
let at = unsafe {
MapViewOfFile(
slice.section.0,
slice.section.handle,
FILE_MAP_WRITE,
(offset >> 32) as u32,
offset as u32,
@@ -489,10 +659,15 @@ impl View {
)
};
if at.Value.is_null() {
tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not mapped for a write");
return None;
}
let view = View { at, len };
commit(at.Value as usize, len).then_some(view)
if !commit(at.Value as usize, len) {
tracing::warn!(error = %std::io::Error::last_os_error(), n, "physical pages not committed for a write");
return None;
}
Some(view)
}
fn bytes(&mut self) -> &mut [u8] {
@@ -522,7 +697,10 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize)
let physical = physical();
let mut runs: Vec<(Slice, usize)> = Vec::new();
for page in pages {
let slice = physical.pages.get(page)?;
let Some(slice) = physical.pages.get(page) else {
tracing::warn!(page, offset, len, "a physical page the title does not own (any more)");
return None;
};
match runs.last_mut() {
Some((first, n))
if Arc::ptr_eq(&first.section, &slice.section)
@@ -536,6 +714,14 @@ fn runs(pages: &[usize], offset: usize, len: usize) -> Option<Vec<(Slice, usize)
Some(runs)
}
/// Whether the title owns every page under bytes `[offset, offset + len)`.
pub(crate) fn pages_known(pages: &[usize], offset: usize, len: usize) -> bool {
let physical = physical();
pages
.get(offset / PAGE..(offset + len).div_ceil(PAGE))
.is_some_and(|pages| pages.iter().all(|page| physical.pages.contains_key(page)))
}
/// Copies `data` into physical pages, from `offset` bytes into the first,
/// whether or not they are mapped anywhere (DirectStorage destinations).
/// One view per run of consecutive pages, not one per page: each view
@@ -547,11 +733,17 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo
};
let (mut within, mut done) = (offset % PAGE, 0);
for (slice, n) in &runs {
let Some(mut view) = View::map(slice, *n) else {
return false;
};
let k = (n * PAGE - within).min(data.len() - done);
view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]);
if let Some(at) = slice.section.window(slice.index, *n) {
// SAFETY: committed bytes of the section's view, which `runs`
// holds; the title's other uses of them race as on the console.
unsafe { std::ptr::copy_nonoverlapping(data[done..].as_ptr(), (at + within) as *mut u8, k) };
} else {
let Some(mut view) = View::map(slice, *n) else {
return false;
};
view.bytes()[within..within + k].copy_from_slice(&data[done..done + k]);
}
(within, done) = (0, done + k);
}
true
@@ -561,15 +753,27 @@ pub(crate) fn write_physical(pages: &[usize], offset: usize, data: &[u8]) -> boo
/// until dropped: DirectStorage decodes into it instead of a buffer it
/// would then copy.
pub(crate) struct PageWindow {
view: View,
view: Window,
within: usize,
len: usize,
}
enum Window {
/// In the section's own view, which the section holds.
Kept(usize, #[expect(dead_code, reason = "held for the view")] Arc<Section>),
Own(View),
}
impl PageWindow {
pub(crate) fn bytes(&mut self) -> &mut [u8] {
let (within, len) = (self.within, self.len);
&mut self.view.bytes()[within..within + len]
match &mut self.view {
// SAFETY: committed bytes of the section's view, ours alone as
// far as the runtime goes (other views alias them, as the
// console's do).
Window::Kept(at, _) => unsafe { std::slice::from_raw_parts_mut((*at + within) as *mut u8, len) },
Window::Own(view) => &mut view.bytes()[within..within + len],
}
}
}
@@ -583,8 +787,12 @@ pub(crate) fn page_window(pages: &[usize], offset: usize, len: usize) -> Option<
let [(slice, n)] = runs.as_slice() else {
return None;
};
let view = match slice.section.window(slice.index, *n) {
Some(at) => Window::Kept(at, slice.section.clone()),
None => Window::Own(View::map(slice, *n)?),
};
Some(PageWindow {
view: View::map(slice, *n)?,
view,
within: offset % PAGE,
len,
})
@@ -711,7 +919,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER,
);
MapViewOfFile3(
slice.section.0,
slice.section.handle,
GetCurrentProcess(),
base as *const c_void,
(slice.index * PAGE) as u64,
@@ -739,7 +947,8 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
// 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.0 as usize, (slice.index * PAGE) as u64);
victory_gpu::title_memory_view(base, len, slice.section.handle as usize, (slice.index * PAGE) as u64);
physical.note_view(base, len, &slice);
physical.views.insert(base, (len, slice));
true
}
@@ -818,6 +1027,7 @@ fn unmap(physical: &mut Physical, base: usize, len: usize) {
let Some((size, slice)) = physical.views.remove(&at) else {
continue;
};
physical.forget_view(at, size, &slice);
victory_gpu::title_memory_remapped(at, size);
// SAFETY: a view we mapped; it becomes a placeholder again.
unsafe {
+36 -1
View File
@@ -1016,6 +1016,12 @@ fn own_bits_on() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_WAVE_OWN_BITS").is_none_or(|v| v != "0"))
}
/// What the translator was told of the host, for a cache's key: the widest
/// wave and the view heap's limit.
pub fn host_settings() -> [u32; 2] {
[host_max_wave(), super::shader::view_heap_limit()]
}
pub(super) fn host_max_wave() -> u32 {
#[cfg(test)]
if let Some(lanes) = TEST_HOST_WAVE.get() {
@@ -4203,7 +4209,30 @@ impl<'a> Lower<'a> {
/// `x` in the first lane of this host wave where `guard` holds, and whether it has such a
/// lane: the console reads the first lane of EXEC, and a lane that got here with EXEC clear
/// (a guard, not a branch) is not one. With none, `x` of the wave's first lane here.
///
/// A helper lane of a pixel shader takes its own value: the console's whole-quad mode has
/// helper lanes in EXEC, so a waterfall loop serves them too, and the host's wave operations
/// leave them out. Once only helper lanes are left in such a loop none of them ever matched:
/// they ran to the iteration limit, and left with no sample for their quad's derivatives,
/// along every triangle's edges (upstream #908, the fix of #1733 for this tree's form).
fn first_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
let (first, any) = self.first_live_lane(x, guard);
if !self.s.pixel || !super::helper_own() {
return (first, any);
}
let helper = self.helper_lane();
let c = self.cur;
let yes = self.s.m.bool(true);
(self.s.m.select(c, helper, x, first), self.s.m.select(c, helper, yes, any))
}
/// Whether this lane of a pixel shader is a helper lane.
fn helper_lane(&mut self) -> V {
let i1t = self.s.t.i1;
self.s.op(self.cur, "isHelperLane.i1", Attr::ReadOnly, i1t, 221, &[])
}
fn first_live_lane(&mut self, x: V, guard: Option<V>) -> (V, V) {
let c = self.cur;
let i32t = self.s.t.i32;
self.s.flags |= flags::WAVE_OPS;
@@ -5823,7 +5852,13 @@ impl<'a> Lower<'a> {
if per_lane {
self.s.flags |= flags::WAVE_OPS;
let i32t = self.s.t.i32;
d = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
let first = self.s.op(c, "waveReadLaneFirst.i32", Attr::NoUnwind, i32t, 118, &[d]);
d = if self.s.pixel && super::helper_own() {
let helper = self.helper_lane();
self.s.m.select(c, helper, d, first)
} else {
first
};
}
addr = self.s.m.bin(c, Bin::Add, addr, d);
}
+35 -1
View File
@@ -112,7 +112,7 @@ use crate::{ShaderError, io, ir, resource, structure};
pub use bitcode::census;
pub use sampler::StaticSampler;
pub use lower::set_host_max_wave;
pub use lower::{host_settings, set_host_max_wave};
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
@@ -143,6 +143,14 @@ pub fn loop_limit() -> u32 {
})
}
/// Whether a pixel shader's helper lane reads its own value where the console reads the first
/// lane's (`lower.rs` `first_lane`); on unless `VICTORY_HELPER_OWN=0`. Part of the translation:
/// the shader cache keys on it.
pub fn helper_own() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_HELPER_OWN").is_none_or(|v| v != "0"))
}
/// Which of a translated program's group barriers wait for the whole
/// group (`GroupMemoryBarrierWithGroupSync`); the others keep their memory
/// fence and lose the wait. A wait that some thread of the group never
@@ -1546,6 +1554,32 @@ mod barycentric_tests {
emit(&c, &native, &p, &st, &io, &res)
}
/// A pixel program's first-lane loop (no table entry in it, so not a waterfall the tracker
/// knows) asks for helper lanes, which is valid DXIL (upstream #946's program).
#[test]
fn a_pixel_first_lane_loop_serves_helper_lanes() {
let shader = pixel(
&[
0xD765_0000, 0x0001_00C1, // v_mbcnt_lo_u32_b32 v0, -1, 0
0x7E02_0280, // v_mov_b32 v1, 0
0xBE97_037E, // s_mov_b32 s23, exec_lo
0x7E18_0500, // v_readfirstlane_b32 s12, v0
0x7D84_000C, // v_cmp_eq_u32 vcc, s12, v0
0xBE95_3C6A, // s_and_saveexec_b32 s21, vcc_lo
0xBF80_0000, // s_nop 0
0x7E02_02FF, 0x3F80_0000, // v_mov_b32 v1, 1.0
0x897E_157E, // s_xor_b32 exec_lo, exec_lo, s21
0xBF89_FFF8, // s_cbranch_execnz loop
0xBEFE_0317, // s_mov_b32 exec_lo, s23
0xF800_180F, 0x0101_0101, // exp mrt0 v1 v1 v1 v1 done vm
0xBF81_0000, // s_endpgm
],
0,
)
.unwrap();
validate(&shader);
}
/// The translation's `SFI0` features and `ISG1` rows.
fn parts(shader: &HostShader) -> (u64, Vec<SigElement>) {
let c = Container::parse(&shader.dxil).unwrap();
+5
View File
@@ -125,6 +125,11 @@ pub fn set_view_heap_limit(null_slot: u32) {
VIEW_LIMIT.store(null_slot, std::sync::atomic::Ordering::Relaxed);
}
/// See [`set_view_heap_limit`].
pub(super) fn view_heap_limit() -> u32 {
VIEW_LIMIT.load(std::sync::atomic::Ordering::Relaxed)
}
pub(crate) struct Shader {
pub m: Module,
pub t: Types,