Merge branch 'night/light' into local/next
This commit is contained in:
commit
35d4815d37
14 files changed
+1557
-246
No files matched your search
@@ -329,6 +329,27 @@ fn changed_slots(
|
||||
first.min(last)..last
|
||||
}
|
||||
|
||||
/// The title's view heap that shaders of a list without one get their views
|
||||
/// from (`draw.rs`, `bind`): the title's structure builder binds root views
|
||||
/// only, and the host shows those, and memory by address, through heap slots.
|
||||
/// The biggest there is. `VICTORY_LENT_HEAP=0`: none, such a dispatch is
|
||||
/// dropped, as before.
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn lent_heap() -> Option<usize> {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if !*ON.get_or_init(|| std::env::var_os("VICTORY_LENT_HEAP").is_none_or(|v| v != "0")) {
|
||||
return None;
|
||||
}
|
||||
let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
|
||||
heaps
|
||||
.iter()
|
||||
// SAFETY: registered heaps are live (removed when dropped).
|
||||
.map(|&(_, _, h)| (h, unsafe { &*(h as *const Heap) }))
|
||||
.filter(|(_, heap)| !heap.samplers() && matches!(heap.host.get(), Some(Some(_))))
|
||||
.max_by_key(|(_, heap)| heap.desc.count)
|
||||
.map(|(h, _)| h)
|
||||
}
|
||||
|
||||
/// Gives back dynamic slots of the host heap behind the title heap at
|
||||
/// `heap`, if that heap still exists.
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -996,10 +996,17 @@ impl State {
|
||||
dword: u32,
|
||||
memory: Option<&crate::memory::Ready>,
|
||||
) -> u32 {
|
||||
use victory_shader::emit::{USER_MEMORY_BASE, USER_VIEW_ADDRESS, USER_VIEW_BIAS};
|
||||
use victory_shader::emit::{USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS};
|
||||
if kind == USER_MEMORY_BASE {
|
||||
return memory.map_or(0, |m| m.base);
|
||||
}
|
||||
if kind == USER_ROOT_ADDRESS || kind == USER_ROOT_ADDRESS + 1 {
|
||||
return match self.roots_ref(compute).get(usize::from(slot)) {
|
||||
Some(&Root::View(address)) if kind == USER_ROOT_ADDRESS => address as u32,
|
||||
Some(&Root::View(address)) => (address >> 32) as u32,
|
||||
_ => 0,
|
||||
};
|
||||
}
|
||||
if kind == USER_VIEW_BIAS {
|
||||
// The view begins on 16 bytes of the copy the address finds
|
||||
// (`root_uav`, `root_srv_table`).
|
||||
@@ -1057,16 +1064,28 @@ impl State {
|
||||
list: &HostList,
|
||||
t: &crate::pipeline::Translated,
|
||||
compute: bool,
|
||||
writes: bool,
|
||||
use_: crate::memory::Use,
|
||||
) -> Option<crate::memory::Ready> {
|
||||
let heap = match self.heaps[0] {
|
||||
0 => None,
|
||||
h => crate::descriptor::heap(h as This).host(),
|
||||
}?;
|
||||
let (mut addresses, mut constants) = (Vec::new(), Vec::new());
|
||||
// (What it may write: its root views of unordered access.)
|
||||
let written: Vec<u64> = t
|
||||
.used
|
||||
.iter()
|
||||
.filter(|u| u.kind == ResourceType::Uav && u.root == RootType::Descriptor)
|
||||
.filter_map(|u| match self.roots_ref(compute).get(usize::from(u.slot)) {
|
||||
Some(&Root::View(address)) => Some(address),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for root in self.roots_ref(compute) {
|
||||
match root {
|
||||
Root::View(address) => addresses.push(*address),
|
||||
// (Of a program that only walks structures, the structures'
|
||||
// views below: its root views are constants and tables.)
|
||||
Root::View(address) if use_ != crate::memory::Use::Reads => addresses.push(*address),
|
||||
Root::Constants(values) => constants.extend_from_slice(values),
|
||||
_ => {}
|
||||
}
|
||||
@@ -1076,7 +1095,7 @@ impl State {
|
||||
addresses.push(self.view_address(compute, u.slot, u.dword));
|
||||
}
|
||||
}
|
||||
crate::memory::ready(list, heap, &addresses, &constants, writes)
|
||||
crate::memory::ready(list, heap, &addresses, &written, &constants, use_)
|
||||
}
|
||||
|
||||
/// The bound heap holding `handle`.
|
||||
@@ -1197,6 +1216,15 @@ impl State {
|
||||
if crate::host::walls_trace() {
|
||||
self.walls_census(p, compute);
|
||||
}
|
||||
// A list without a view heap: one of the title's for the views the
|
||||
// host itself puts into heap slots.
|
||||
if self.heaps[0] == 0
|
||||
&& p.stages.iter().any(|s| !s.root_uavs.is_empty() || !s.root_srvs.is_empty())
|
||||
&& let Some(heap) = crate::descriptor::lent_heap()
|
||||
{
|
||||
once!("a dispatch without a view heap that needs one gets the title's");
|
||||
self.heaps[0] = heap;
|
||||
}
|
||||
// Heaps first: a root signature with directly indexed heaps must be
|
||||
// set after them.
|
||||
if self.host_heaps != self.heaps {
|
||||
@@ -1264,8 +1292,12 @@ impl State {
|
||||
let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) {
|
||||
// Only through a store by address: what it stores through
|
||||
// views is declared with them.
|
||||
let writes = writes && t.stores_by_address;
|
||||
let Some(ready) = self.memory_ready(list, &t, compute, writes) else {
|
||||
let use_ = if crate::pipeline::is_builder(self.pipeline as This) || writes && t.stores_by_address {
|
||||
crate::memory::Use::Builds { back: writes }
|
||||
} else {
|
||||
crate::memory::Use::Reads
|
||||
};
|
||||
let Some(ready) = self.memory_ready(list, &t, compute, use_) else {
|
||||
once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped");
|
||||
return false;
|
||||
};
|
||||
@@ -2450,12 +2482,17 @@ impl State {
|
||||
// A stage of the structure builder that cannot be bound is a
|
||||
// dropped stage: the others stop too.
|
||||
if crate::pipeline::is_builder(self.pipeline as This) {
|
||||
crate::pipeline::builder_off("one of its dispatches could not be bound");
|
||||
crate::pipeline::builder_rests("one of its dispatches could not be bound");
|
||||
}
|
||||
return;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
list.note_op(|| self.op_text(format!("dispatch {x}x{y}x{z}"), true));
|
||||
#[cfg(feature = "diagnostics")]
|
||||
if crate::pipeline::is_builder(self.pipeline as This) {
|
||||
crate::capture::op(list as *const _ as usize, || format!("builder {}", p.name));
|
||||
self.list_dropped_roots([x, y, z]);
|
||||
}
|
||||
// SAFETY: an open list with everything set.
|
||||
unsafe { list.list.Dispatch(x, y, z) };
|
||||
self.buffers_written();
|
||||
|
||||
@@ -69,6 +69,8 @@ mod tdr;
|
||||
#[cfg(windows)]
|
||||
mod texture;
|
||||
#[cfg(windows)]
|
||||
mod upload;
|
||||
#[cfg(windows)]
|
||||
mod watch;
|
||||
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -114,7 +114,7 @@ struct List {
|
||||
/// Ours, after the console layout: memory handed out by
|
||||
/// [`allocate_upload`], kept until the list is reset; the host list the
|
||||
/// calls record into (decision 0007), and the draw state the title set.
|
||||
uploads: std::sync::Mutex<Vec<Vec<u8>>>,
|
||||
uploads: std::sync::Mutex<Vec<Upload>>,
|
||||
#[cfg(windows)]
|
||||
host: Option<crate::host::HostList>,
|
||||
#[cfg(windows)]
|
||||
@@ -187,7 +187,7 @@ pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
|
||||
#[cfg(windows)]
|
||||
pub(crate) struct Detached {
|
||||
host: crate::host::HostList,
|
||||
_uploads: Vec<Vec<u8>>,
|
||||
_uploads: Vec<Upload>,
|
||||
_state: crate::draw::State,
|
||||
}
|
||||
|
||||
@@ -1558,6 +1558,23 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags:
|
||||
reset(this, allocator, pipeline)
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
use crate::upload::Upload;
|
||||
|
||||
/// The memory of [`allocate_upload`] where no host GPU reads it by address.
|
||||
#[cfg(not(windows))]
|
||||
struct Upload(Vec<u8>);
|
||||
|
||||
#[cfg(not(windows))]
|
||||
impl Upload {
|
||||
fn new(len: usize) -> Option<Upload> {
|
||||
Some(Upload(vec![0; len]))
|
||||
}
|
||||
fn start(&mut self) -> *mut u8 {
|
||||
self.0.as_mut_ptr()
|
||||
}
|
||||
}
|
||||
|
||||
/// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
|
||||
/// owns until it is reset, which the CPU writes and the GPU reads at the
|
||||
/// same address; null on failure. The title's BVH builder puts
|
||||
@@ -1571,13 +1588,14 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu
|
||||
if this.is_null() || !align.is_power_of_two() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let mut block = vec![0u8; len];
|
||||
let start = block.as_mut_ptr();
|
||||
let Some(mut block) = Upload::new(len) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let start = block.start();
|
||||
// SAFETY: the offset is below `align`, so `size` bytes fit after it.
|
||||
let at = unsafe { start.add(start.align_offset(align)) };
|
||||
// SAFETY: the title passes one of our lists.
|
||||
let uploads = unsafe { &(*this.cast::<List>()).uploads };
|
||||
// Moving the vector keeps its heap block where it is.
|
||||
uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
|
||||
at
|
||||
}
|
||||
|
||||
+976
-173
File diff suppressed because it is too large.
Load diff
@@ -233,8 +233,11 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
|
||||
/// So a builder dispatch runs only while every builder pipeline the title
|
||||
/// has created has a host pipeline; the first builder dispatch makes them
|
||||
/// all on the spot instead of over the next frames (a stage "still being
|
||||
/// made" would be a dropped stage). One that cannot be made turns the
|
||||
/// builder off for the rest of the run.
|
||||
/// made" would be a dropped stage). While one cannot be made the builder
|
||||
/// is off; it is looked at again when the title creates another. A stage
|
||||
/// that could not be bound stops the stages after it for the rest of that
|
||||
/// frame and the next ([`builder_rests`]); it turned the builder off for the
|
||||
/// rest of the run at first.
|
||||
///
|
||||
/// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown
|
||||
/// the whole builder and the host side of title memory by address
|
||||
@@ -245,15 +248,18 @@ struct Builder {
|
||||
pipelines: Vec<Arc<make::Pending>>,
|
||||
/// Every one of `pipelines` has a host pipeline.
|
||||
whole: bool,
|
||||
/// One could not be made.
|
||||
off: bool,
|
||||
/// One could not be made, of so many (0: none).
|
||||
off: usize,
|
||||
/// No stage runs before this frame.
|
||||
rests: u64,
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
static BUILDER: Mutex<Builder> = Mutex::new(Builder {
|
||||
pipelines: Vec::new(),
|
||||
whole: false,
|
||||
off: false,
|
||||
off: 0,
|
||||
rests: 0,
|
||||
});
|
||||
|
||||
/// Whether `shaders` are a pipeline of the structure builder.
|
||||
@@ -292,13 +298,15 @@ pub(crate) fn is_builder(this: This) -> bool {
|
||||
!this.is_null() && pipeline(this).builder
|
||||
}
|
||||
|
||||
/// A stage of the builder was dropped after all: none runs from here on.
|
||||
/// A stage of the builder was dropped after all: none runs for the rest of
|
||||
/// this frame and the next (what it fed is not there).
|
||||
#[cfg(windows)]
|
||||
pub(crate) fn builder_off(why: &'static str) {
|
||||
pub(crate) fn builder_rests(why: &'static str) {
|
||||
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !b.off {
|
||||
b.off = true;
|
||||
tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none");
|
||||
b.rests = crate::frame::current() + 2;
|
||||
static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
|
||||
if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 20 {
|
||||
tracing::warn!(why, "the ray-tracing structure builder rests for this frame and the next: its stages run all or none");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -311,22 +319,24 @@ pub(crate) fn builder_runs() -> bool {
|
||||
return false;
|
||||
}
|
||||
let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if b.off {
|
||||
if b.off == b.pipelines.len() || crate::frame::current() < b.rests {
|
||||
return false;
|
||||
}
|
||||
if b.whole {
|
||||
return true;
|
||||
}
|
||||
let missing = b.pipelines.iter().filter(|p| !make::now(p)).count();
|
||||
if missing > 0 {
|
||||
b.off = true;
|
||||
let missing: Vec<String> = b.pipelines.iter().filter(|p| !make::now(p)).map(|p| make::hashes(p)).collect();
|
||||
if !missing.is_empty() {
|
||||
b.off = b.pipelines.len();
|
||||
tracing::warn!(
|
||||
missing,
|
||||
missing = missing.len(),
|
||||
of = b.pipelines.len(),
|
||||
which = ?missing,
|
||||
"the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
b.off = 0;
|
||||
tracing::info!(
|
||||
pipelines = b.pipelines.len(),
|
||||
"the ray-tracing structure builder runs: all of its programs have host pipelines"
|
||||
|
||||
@@ -91,6 +91,12 @@ pub(crate) fn missing(p: &Pending) -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The hashes of the shaders `p` is made of.
|
||||
pub(crate) fn hashes(p: &Pending) -> String {
|
||||
let hashes: Vec<&str> = p.shaders.iter().map(|s| s.hash.as_str()).collect();
|
||||
hashes.join("+")
|
||||
}
|
||||
|
||||
/// Signalled whenever a worker has made a pipeline.
|
||||
static DONE: (Mutex<()>, Condvar) = (Mutex::new(()), Condvar::new());
|
||||
|
||||
|
||||
@@ -83,6 +83,9 @@ pub(crate) struct Shadow {
|
||||
card: Option<Card>,
|
||||
/// A window of title memory outside buffers, not a title buffer's copy.
|
||||
window: bool,
|
||||
/// Of a copy with two sides: only the dwords the title changed go up,
|
||||
/// as with [`send_changed`] ([`by_address`]).
|
||||
changes_only: std::sync::atomic::AtomicBool,
|
||||
/// 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
|
||||
@@ -2683,6 +2686,7 @@ impl Shadow {
|
||||
},
|
||||
card: None,
|
||||
window: false,
|
||||
changes_only: Default::default(),
|
||||
mapped: false,
|
||||
place: None,
|
||||
}
|
||||
@@ -3568,7 +3572,7 @@ impl Shadow {
|
||||
/// A page of title memory, as read.
|
||||
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
|
||||
}
|
||||
let Some(card) = self.card.as_ref().filter(|_| send_changed()) else {
|
||||
let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else {
|
||||
return self.copy(from, to);
|
||||
};
|
||||
let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
|
||||
@@ -3636,6 +3640,17 @@ impl Shadow {
|
||||
self.card.is_some()
|
||||
}
|
||||
|
||||
/// Shaders store in it what is not declared: from here on only the dwords
|
||||
/// the title changes go up ([`by_address`]).
|
||||
pub(crate) fn keep_stores(&self) {
|
||||
self.changes_only.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Offsets `[from, to)` go up again whole, as the CPU's side has them.
|
||||
pub(crate) fn resend(&self, from: usize, to: usize) {
|
||||
self.card_changed(from, to);
|
||||
}
|
||||
|
||||
/// The CPU side's bytes at offsets `[from, to)` changed: they go to the
|
||||
/// card's side before the next submission.
|
||||
fn card_changed(&self, from: usize, to: usize) {
|
||||
@@ -4607,6 +4622,77 @@ fn longest_tail(windows: impl Iterator<Item = (u64, u64)>, address: u64, end: u6
|
||||
.min()
|
||||
}
|
||||
|
||||
/// Whether `[address, address + len)` lies in one title buffer.
|
||||
pub(crate) fn in_buffer(address: u64, len: u64) -> Option<(u64, u64)> {
|
||||
let end = address.checked_add(len)?;
|
||||
let map = buffers_read();
|
||||
let found = map.range(..=(address, usize::MAX)).rev().take(64).find(|(_, e)| e.end >= end);
|
||||
found.map(|(k, e)| (k.0, e.end - k.0))
|
||||
}
|
||||
|
||||
/// Whether a title buffer of at most `most` bytes lies in `[address, address
|
||||
/// + len)`, all of it or in part.
|
||||
pub(crate) fn small_buffer_in(address: u64, len: u64, most: u64) -> bool {
|
||||
let map = buffers_read();
|
||||
map.range((address.saturating_sub(most), 0)..(address + len, 0))
|
||||
.any(|(key, entry)| entry.end > address && entry.end - key.0 <= most)
|
||||
}
|
||||
|
||||
/// A copy of the memory `[start, start + len)` (an arena of
|
||||
/// [`crate::memory`]'s, its directory, title memory around a small buffer)
|
||||
/// for the programs that find memory by address, on the card: the structures
|
||||
/// rays are traced through, read with every step of every ray.
|
||||
///
|
||||
/// What shaders write there by address is not brought back, so the copy is
|
||||
/// the only place that has it. The CPU's side holds the bytes as they were
|
||||
/// last taken, and only dwords that changed since go up.
|
||||
pub(crate) fn by_address(start: u64, len: u64) -> Option<Arc<Shadow>> {
|
||||
let host = host()?;
|
||||
if !cards() || !host.card_ready() {
|
||||
return None;
|
||||
}
|
||||
// At most so much on the card's own memory (4 GiB unless
|
||||
// `VICTORY_MEMORY_CARD_MB` says otherwise), and while it has room; past
|
||||
// that the side shaders see is in the PC's memory.
|
||||
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
|
||||
static USED: AtomicU64 = AtomicU64::new(0);
|
||||
let most = *MOST.get_or_init(|| {
|
||||
let mb = std::env::var("VICTORY_MEMORY_CARD_MB").ok().and_then(|v| v.trim().parse::<u64>().ok());
|
||||
mb.unwrap_or(4096) << 20
|
||||
});
|
||||
let room = host.video_memory().is_none_or(|[budget, used, ..]| used + len < budget / 100 * 97);
|
||||
let (staging, data) = host.shared_buffer(len)?;
|
||||
let on_card = if room && USED.fetch_add(len, Ordering::Relaxed) + len <= most {
|
||||
host.uav_buffer(len)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let buffer = match on_card {
|
||||
Some(buffer) => buffer,
|
||||
None => host.shared_buffer(len)?.0,
|
||||
};
|
||||
crate::host::name(&staging, || format!("title memory {start:#x}+{len:#x} by address, the CPU's side"));
|
||||
crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x} by address"));
|
||||
// (Counted down with the windows' on the card when it goes.)
|
||||
WINDOW_CARD_BYTES.fetch_add(len, Ordering::Relaxed);
|
||||
// SAFETY: a live buffer.
|
||||
let gpu = unsafe { buffer.GetGPUVirtualAddress() };
|
||||
let mut shadow = Shadow::new(buffer, data, gpu, start, len);
|
||||
shadow.window = true;
|
||||
shadow.changes_only.store(true, Ordering::Relaxed);
|
||||
shadow.card = Some(Card {
|
||||
staging,
|
||||
before: Mutex::default(),
|
||||
dirty: Mutex::default(),
|
||||
sent: Mutex::default(),
|
||||
touched: Default::default(),
|
||||
size: len,
|
||||
});
|
||||
let shadow = Arc::new(shadow);
|
||||
CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow));
|
||||
Some(shadow)
|
||||
}
|
||||
|
||||
/// Copies of title memory outside buffers, by (start, length).
|
||||
static LOOSE: std::sync::RwLock<BTreeMap<(u64, u64), Arc<Shadow>>> = std::sync::RwLock::new(BTreeMap::new());
|
||||
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
//! Memory `allocate_upload` (`list.rs`) hands out: the title's CPU writes
|
||||
//! it and its shaders read it at the same address (the structure builder's
|
||||
//! instance descriptions lie there).
|
||||
//!
|
||||
//! The console's GPU addresses have 40 bits, and a translated shader that
|
||||
//! reads by address has no more (`victory_shader`'s `Lower::memory`): memory
|
||||
//! from the process heap lies above 2^40 and was read at another address, as
|
||||
//! zeros. So this memory is taken in blocks of 64 KiB out of arenas in
|
||||
//! [4 GiB, 2^37), as upstream VIctory 0f637570 and 6d021fe3 place it (there
|
||||
//! an allocation of its own each). An arena is a title buffer to the host
|
||||
//! copies ([`crate::shadow`]) and lives as long as the process: the directory
|
||||
//! of memory by address ([`crate::memory`]) keeps the copy it found at an
|
||||
//! address for good, so the same addresses must stay the same copy.
|
||||
//! `VICTORY_UPLOAD_LOW=0`: from the process heap, as before.
|
||||
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
|
||||
/// What blocks are cut on: a page of the directory of memory by address.
|
||||
const BLOCK: usize = 64 << 10;
|
||||
/// An arena's size, if one request does not need more.
|
||||
const ARENA: usize = 4 << 20;
|
||||
|
||||
struct Arena {
|
||||
at: usize,
|
||||
/// Per block whether it is handed out.
|
||||
taken: Vec<bool>,
|
||||
}
|
||||
|
||||
static ARENAS: Mutex<Vec<Arena>> = Mutex::new(Vec::new());
|
||||
|
||||
/// Upload memory of one request, zeroed, given back when dropped.
|
||||
pub(crate) struct Upload(Kind);
|
||||
|
||||
enum Kind {
|
||||
/// Address, bytes.
|
||||
Low(usize, usize),
|
||||
Heap(Vec<u8>),
|
||||
}
|
||||
|
||||
fn low() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_LOW").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// The first place of `n` free blocks side by side.
|
||||
fn gap(taken: &[bool], n: usize) -> Option<usize> {
|
||||
let mut free = 0;
|
||||
for (i, &t) in taken.iter().enumerate() {
|
||||
free = if t { 0 } else { free + 1 };
|
||||
if free == n {
|
||||
return Some(i + 1 - n);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Fresh zeroed memory in [4 GiB, 2^37) (where the directory of memory by
|
||||
/// address reaches, `MEMORY_PAGES`), write-watched as the title's own
|
||||
/// pools are (copies then take only written pages).
|
||||
pub(crate) fn reserve(len: usize) -> Option<usize> {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RESERVE, MemExtendedParameterAddressRequirements,
|
||||
PAGE_READWRITE, VirtualAlloc2,
|
||||
};
|
||||
const MEM_WRITE_WATCH: u32 = 0x20_0000;
|
||||
let mut requirements = MEM_ADDRESS_REQUIREMENTS {
|
||||
LowestStartingAddress: (1usize << 32) as *mut _,
|
||||
HighestEndingAddress: ((1usize << 37) - 1) as *mut _,
|
||||
Alignment: 0,
|
||||
};
|
||||
let mut parameter = MEM_EXTENDED_PARAMETER::default();
|
||||
parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
|
||||
parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
|
||||
// SAFETY: a fresh allocation; the parameter points at `requirements`,
|
||||
// which outlives the call.
|
||||
let at = unsafe {
|
||||
VirtualAlloc2(
|
||||
std::ptr::null_mut(),
|
||||
std::ptr::null(),
|
||||
len,
|
||||
MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
|
||||
PAGE_READWRITE,
|
||||
&mut parameter,
|
||||
1,
|
||||
)
|
||||
} as usize;
|
||||
(at != 0).then_some(at)
|
||||
}
|
||||
|
||||
impl Upload {
|
||||
pub(crate) fn new(len: usize) -> Option<Upload> {
|
||||
if !low() {
|
||||
return Some(Upload(Kind::Heap(vec![0; len])));
|
||||
}
|
||||
let n = len.max(1).div_ceil(BLOCK);
|
||||
let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let found = arenas.iter().enumerate().find_map(|(a, arena)| Some((a, gap(&arena.taken, n)?)));
|
||||
let (a, first) = match found {
|
||||
Some(place) => place,
|
||||
None => {
|
||||
let blocks = n.max(ARENA / BLOCK);
|
||||
let at = reserve(blocks * BLOCK)?;
|
||||
crate::shadow::register(at, at as u64, (blocks * BLOCK) as u64);
|
||||
tracing::info!(at = format_args!("{at:#x}"), bytes = blocks * BLOCK, "memory for lists' uploads, where shaders reach it by address");
|
||||
arenas.push(Arena { at, taken: vec![false; blocks] });
|
||||
(arenas.len() - 1, 0)
|
||||
}
|
||||
};
|
||||
let arena = &mut arenas[a];
|
||||
arena.taken[first..first + n].fill(true);
|
||||
let at = arena.at + first * BLOCK;
|
||||
// SAFETY: the blocks are the arena's and nobody else's now.
|
||||
unsafe { std::ptr::write_bytes(at as *mut u8, 0, len) };
|
||||
Some(Upload(Kind::Low(at, len)))
|
||||
}
|
||||
|
||||
pub(crate) fn start(&mut self) -> *mut u8 {
|
||||
match &mut self.0 {
|
||||
Kind::Low(at, _) => *at as *mut u8,
|
||||
Kind::Heap(block) => block.as_mut_ptr(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Upload {
|
||||
fn drop(&mut self) {
|
||||
let Kind::Low(at, len) = self.0 else { return };
|
||||
let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(arena) = arenas.iter_mut().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&at)) {
|
||||
let first = (at - arena.at) / BLOCK;
|
||||
arena.taken[first..first + len.max(1).div_ceil(BLOCK)].fill(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The block handed out that holds `address`: its start and bytes (whole
|
||||
/// [`BLOCK`]s).
|
||||
pub(crate) fn block(address: usize) -> Option<(usize, usize)> {
|
||||
let arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let arena = arenas.iter().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&address))?;
|
||||
let first = (address - arena.at) / BLOCK;
|
||||
let n = arena.taken[first..].iter().take_while(|t| **t).count();
|
||||
(n > 0).then_some((arena.at + first * BLOCK, n * BLOCK))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn blocks_lie_below_40_bits_and_are_used_again_zeroed() {
|
||||
let mut a = Upload::new(100).unwrap();
|
||||
let mut b = Upload::new(BLOCK + 1).unwrap();
|
||||
let (pa, pb) = (a.start(), b.start());
|
||||
assert!((pa as usize) >= 1 << 32 && (pb as usize) + 2 * BLOCK <= 1 << 40);
|
||||
assert!((pa as usize).is_multiple_of(BLOCK) && pa != pb);
|
||||
// SAFETY: 100 bytes were handed out.
|
||||
unsafe { pa.write_bytes(0xab, 100) };
|
||||
drop(a);
|
||||
// The lowest free place (another test may have taken it meanwhile;
|
||||
// zeroed either way).
|
||||
let mut c = Upload::new(100).unwrap();
|
||||
// SAFETY: as above.
|
||||
assert!(unsafe { std::slice::from_raw_parts(c.start(), 100) }.iter().all(|&x| x == 0));
|
||||
// More than an arena.
|
||||
let mut d = Upload::new(ARENA + 1).unwrap();
|
||||
// SAFETY: the bytes were handed out.
|
||||
unsafe { d.start().add(ARENA).write(1) };
|
||||
drop(b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gap_is_blocks_side_by_side() {
|
||||
assert_eq!(gap(&[true, false, true, false, false, true], 1), Some(1));
|
||||
assert_eq!(gap(&[true, false, true, false, false, true], 2), Some(3));
|
||||
assert_eq!(gap(&[true, false, true, false, false, true], 3), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user