Merge commit '572bd4c' into local/upcopies
This commit is contained in:
commit
47ae1737c2
39 files changed
+3961
-238
No files matched your search
@@ -861,12 +861,16 @@ impl HostHeap {
|
||||
let enough = self.free.load(std::sync::atomic::Ordering::Relaxed) >= n
|
||||
&& n < self.too_long.load(std::sync::atomic::Ordering::Relaxed);
|
||||
let n = n as usize;
|
||||
// Search from `next` on, then from the start.
|
||||
let starts = (*next as usize..self.dynamic as usize).chain(0..*next as usize);
|
||||
// Search from `next` on, then from the start (extending past cursor by
|
||||
// n - 1 so contiguous runs crossing the cursor are not missed).
|
||||
let cursor = *next as usize;
|
||||
let end = self.dynamic as usize;
|
||||
let second_end = cursor.saturating_add(n.saturating_sub(1)).min(end);
|
||||
let starts = (cursor..end).chain(0..second_end);
|
||||
let mut run = 0;
|
||||
let mut found = None;
|
||||
let mut last = usize::MAX;
|
||||
for at in starts.take(if enough { DYNAMIC as usize } else { 0 }) {
|
||||
for at in starts.take(if enough { usize::MAX } else { 0 }) {
|
||||
// A run cannot wrap past the end.
|
||||
if at != last.wrapping_add(1) {
|
||||
run = 0;
|
||||
@@ -2836,4 +2840,31 @@ mod tests {
|
||||
assert_eq!(heap.dynamic(50), Some(4));
|
||||
assert_eq!(heap.dynamic(40), Some(4 + heap.dynamic - 40));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_search_can_find_a_run_across_the_cursor() {
|
||||
let Some(heap) = HostHeap::new(false, 4) else {
|
||||
eprintln!("no host descriptor heap; skipped");
|
||||
return;
|
||||
};
|
||||
let first = heap.dynamic(1).unwrap();
|
||||
let left = heap.dynamic(2).unwrap();
|
||||
let right = heap.dynamic(2).unwrap();
|
||||
let rest = heap.dynamic(heap.dynamic - 5).unwrap();
|
||||
assert_eq!((first, left, right, rest), (4, 5, 7, 9));
|
||||
|
||||
// Reallocating the left half puts the cursor back in the middle.
|
||||
heap.release(left, 2);
|
||||
assert_eq!(heap.dynamic(2), Some(left));
|
||||
heap.release(left, 2);
|
||||
heap.release(right, 2);
|
||||
assert_eq!(heap.dynamic(4), Some(left));
|
||||
assert_eq!(heap.dynamic(1), None);
|
||||
|
||||
// A free slot at each physical end does not form a two-slot range.
|
||||
heap.release(first, 1);
|
||||
let last = first + heap.dynamic - 1;
|
||||
heap.release(last, 1);
|
||||
assert_eq!(heap.dynamic(2), None);
|
||||
}
|
||||
}
|
||||
@@ -214,7 +214,8 @@ mod tests {
|
||||
let mut second = 0;
|
||||
assert_eq!(wait(null, 0, 1_000, std::ptr::null(), 0, &mut second), S_OK);
|
||||
assert!(second > first);
|
||||
assert!(before.elapsed() <= Duration::from_millis(50));
|
||||
// At the tick, not at the time-out (a busy PC may wake it late).
|
||||
assert!(before.elapsed() <= Duration::from_millis(500));
|
||||
assert_eq!(wait(null, 0, 0, std::ptr::null(), 0, &mut second), TIMEOUT);
|
||||
// Tokens count frames, a frame started early on a time-out too.
|
||||
let mut early = 0;
|
||||
|
||||
@@ -704,6 +704,22 @@ fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
/// Zeros for a title destination that went meanwhile are no fault.
|
||||
#[test]
|
||||
fn zeros_where_nothing_is_are_lost() {
|
||||
use windows_sys::Win32::System::Memory::*;
|
||||
// SAFETY: a reservation of ours, its first page committed.
|
||||
unsafe {
|
||||
let at = VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
|
||||
assert!(!VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE).is_null());
|
||||
at.write_bytes(7, 4096);
|
||||
super::zero(at, 4096);
|
||||
assert!(std::slice::from_raw_parts(at, 4096).iter().all(|&b| b == 0));
|
||||
super::zero(at.add(4096), 4096);
|
||||
VirtualFree(at.cast(), 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_copies_preserve_islands_and_observe_remaps() {
|
||||
use windows_sys::Win32::System::Memory::*;
|
||||
@@ -6642,7 +6658,10 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let moved = std::time::Instant::now();
|
||||
let whole = read(src, dst, len);
|
||||
let since = crate::watch::changes();
|
||||
// (A title destination that is away only while the runtime changes a
|
||||
// mapping beside it is written when that is done.)
|
||||
let whole = read(src, dst, len) || title_dst && crate::watch::again_after_change(since, || read(src, dst, len));
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
|
||||
if whole {
|
||||
@@ -6652,6 +6671,7 @@ pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: b
|
||||
// not all mapped. Then the destination stays as it is (the kernel may
|
||||
// have written its first pages).
|
||||
if title_dst && !ask_first && !crate::texture::committed(dst, len) {
|
||||
crate::watch::lost("a copy of the title's", dst as usize, len);
|
||||
return;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -6711,14 +6731,29 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) {
|
||||
if !read(at as *const u8, to, n) {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
|
||||
// SAFETY: inside the destination, which is mapped.
|
||||
unsafe { to.write_bytes(0, n) };
|
||||
zero(to, n);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Zeros at `to`, in one 4 KiB page or two. It may be title memory (the
|
||||
/// destination of a title's copy), which can go between the question whether
|
||||
/// it is there and this.
|
||||
fn zero(to: *mut u8, n: usize) {
|
||||
static ZEROS: [u8; 4096] = [0; 4096];
|
||||
if n <= ZEROS.len() && crate::safecopy::on() {
|
||||
// SAFETY: a destination that is not there fails the copy.
|
||||
if !unsafe { crate::safecopy::copy(to, ZEROS.as_ptr(), n) } {
|
||||
crate::watch::lost("zeros", to as usize, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// SAFETY: inside the destination, which is mapped.
|
||||
unsafe { to.write_bytes(0, n) };
|
||||
}
|
||||
|
||||
/// Reads title memory at `src` into `dst`; false if a page of it is not
|
||||
/// readable.
|
||||
pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
|
||||
@@ -6772,6 +6807,7 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
let direct = direct_writes();
|
||||
let since = crate::watch::changes();
|
||||
let write = |at: usize, n: usize| {
|
||||
let from = src.wrapping_add(at - dst as usize);
|
||||
if crate::safecopy::on() {
|
||||
@@ -6798,7 +6834,16 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
|
||||
for_pieces(dst as usize, len, 64 << 10, |at, n| {
|
||||
if !write(at, n) {
|
||||
for_pieces(at, n, 4 << 10, |at, n| {
|
||||
write(at, n);
|
||||
if write(at, n) {
|
||||
return;
|
||||
}
|
||||
// The kernel's write (`VICTORY_SAFE_COPY=0`) fails where a
|
||||
// refresh guarded the block again since the caller opened
|
||||
// it; and any where the runtime was changing a mapping.
|
||||
crate::watch::writing(at, n);
|
||||
if !write(at, n) && !crate::watch::again_after_change(since, || write(at, n)) {
|
||||
crate::watch::lost("a host copy's bytes", at, n);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -29,7 +29,7 @@
|
||||
//! garbage records cannot run for seconds either.
|
||||
//!
|
||||
//! shortcut: the bounds (2^24 vertices, 2^26 vertex instances, 65,535
|
||||
//! groups per dimension and 2^20 per dispatch, one-dimensional mesh
|
||||
//! groups per dimension, in x 2^20 ([`widest`]), and 2^20 per dispatch, one-dimensional mesh
|
||||
//! dispatches, the budget) cut legitimate work beyond them; raise them if
|
||||
//! the title needs more.
|
||||
|
||||
@@ -107,9 +107,11 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
cost = count * instances;
|
||||
draw_counts = uint2(count, instances);
|
||||
} else if (active && kind == 2) {
|
||||
uint3 g = min(src_args.Load3(src_at), uint3(65535u, 65535u, 65535u));
|
||||
// x * y fits 32 bits; the whole count may not.
|
||||
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
|
||||
uint3 g = src_args.Load3(src_at);
|
||||
// Up to WIDEST groups in x run as asked (`widest`).
|
||||
g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));
|
||||
// x * y fits 32 bits where it is looked at; the whole count may not.
|
||||
if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) {
|
||||
g = uint3(0, 0, 0);
|
||||
}
|
||||
cost = g.x * g.y * g.z * 64u;
|
||||
@@ -237,9 +239,42 @@ fn make_for(device: &ID3D12Device) -> windows::core::Result<Clamp> {
|
||||
make_from(device, SOURCE)
|
||||
}
|
||||
|
||||
/// The most groups in x that an indirect dispatch runs as the title asks:
|
||||
/// 65,535 is the most D3D12 names for a dispatch, 2^20 ([`SOURCE`]'s GROUPS)
|
||||
/// what is bounded here anyway (`VICTORY_INDIRECT_WIDE=0`: 65,535; a record
|
||||
/// that asks for more still runs 65,535).
|
||||
///
|
||||
/// The title's tile lists are dispatches of one group per tile, and two of
|
||||
/// them are classes of the picture's 8x4 tiles, 115,200 in all at
|
||||
/// 2560x1440: in a captured frame 67,440 and 47,760 (the program
|
||||
/// 2dc364df5d3278b8 and 940c2635dc1312f4). Cut to 65,535 the first list lost
|
||||
/// its last 1,905 tiles, the lowest of the picture. The console runs what it
|
||||
/// is asked (its dispatch counts are 32 bits), and so does an AMD card, whose
|
||||
/// dispatch packets and group numbers are the same; D3D12 does not look at
|
||||
/// indirect counts. Other cards stay at 65,535.
|
||||
fn widest(amd: bool) -> u32 {
|
||||
let on = std::env::var_os("VICTORY_INDIRECT_WIDE").is_none_or(|v| v != "0");
|
||||
if amd && on { 1 << 20 } else { 65_535 }
|
||||
}
|
||||
|
||||
/// Whether `device` is an AMD card's.
|
||||
fn amd(device: &ID3D12Device) -> bool {
|
||||
use windows::Win32::Graphics::Dxgi::{CreateDXGIFactory2, DXGI_CREATE_FACTORY_FLAGS, IDXGIAdapter1, IDXGIFactory4};
|
||||
// SAFETY: plain queries.
|
||||
unsafe {
|
||||
CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
|
||||
.and_then(|f| f.EnumAdapterByLuid::<IDXGIAdapter1>(device.GetAdapterLuid()))
|
||||
.and_then(|a| a.GetDesc1())
|
||||
.is_ok_and(|d| d.VendorId == 0x1002)
|
||||
}
|
||||
}
|
||||
|
||||
/// The clamp compiled from `source` (ours, or in the benchmark the one it
|
||||
/// replaced).
|
||||
fn make_from(device: &ID3D12Device, source: &str) -> windows::core::Result<Clamp> {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let batched = source == batch::SOURCE;
|
||||
let source = &format!("#define WIDEST {}u\n{source}", widest(amd(device)));
|
||||
let mut code: Option<ID3DBlob> = None;
|
||||
let mut errors: Option<ID3DBlob> = None;
|
||||
// SAFETY: the source and names live through the call; out pointers ours.
|
||||
@@ -1027,11 +1062,11 @@ void main() {
|
||||
1,
|
||||
[5, 1, 1, 0x7777_8888, 0x9999_AAAA, 0xBBBB_CCCC],
|
||||
);
|
||||
// Record 2 exceeds 65,535 in X -> clamped to (65535, 1, 1).
|
||||
// Record 2 exceeds what any card runs in X -> clamped to (65535, 1, 1).
|
||||
write_record(
|
||||
&mut initial_src,
|
||||
2,
|
||||
[100_000, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
|
||||
[(1 << 20) + 1, 1, 1, 0xDDDD_EEEE, 0xFFFF_0001, 0x0123_4567],
|
||||
);
|
||||
for slot in 3..MAX as usize {
|
||||
// Each garbage slot would clamp to 65535 * 16 * 1 = 1,048,560 groups
|
||||
@@ -1832,6 +1867,75 @@ void main() {
|
||||
sig.unwrap()
|
||||
}
|
||||
|
||||
/// An AMD card runs every group of an indirect dispatch of more than
|
||||
/// 65,535, each under its own number: the title's tile lists
|
||||
/// ([`widest`]), clamped one by one and in a batch. Others are not asked.
|
||||
#[test]
|
||||
fn card_runs_wide_indirect_dispatches() {
|
||||
const CS: &str = r#"
|
||||
#define RS "UAV(u0)"
|
||||
RWByteAddressBuffer seen : register(u0);
|
||||
[RootSignature(RS)]
|
||||
[numthreads(1, 1, 1)]
|
||||
void main(uint3 group : SV_GroupID, uint3 thread : SV_DispatchThreadID) {
|
||||
uint was;
|
||||
seen.InterlockedAdd(0, 1, was);
|
||||
seen.InterlockedMax(4, group.x, was);
|
||||
seen.InterlockedMax(8, thread.x, was);
|
||||
seen.InterlockedAdd(16 + group.x * 4, 1, was);
|
||||
}
|
||||
"#;
|
||||
let Some(mut gpu) = WarpHarness::on(false) else {
|
||||
return;
|
||||
};
|
||||
if !amd(&gpu.device) || widest(true) == 65_535 {
|
||||
return;
|
||||
}
|
||||
let worker = compile_cs(&gpu.device, CS).expect("the worker must compile");
|
||||
let pass = make_from(&gpu.device, batch::SOURCE).expect("the batched clamp must compile");
|
||||
let sig = gpu.signature(2, 12);
|
||||
for asked in [67_440u32, 115_200, 1 << 20, (1 << 20) + 1] {
|
||||
let runs = if asked > 1 << 20 { 65_535 } else { asked };
|
||||
for batched in [false, true] {
|
||||
let (src, src_ptr, src_gpu) = gpu.shared_buffer(1024);
|
||||
let (_budget, budget_ptr, budget_gpu) = gpu.shared_buffer(256);
|
||||
let (_table, table_ptr, table_gpu) = gpu.shared_buffer(batch::TABLE);
|
||||
let size = 16 + (4 << 20) + 16;
|
||||
let seen = gpu.default_uav(size);
|
||||
let (back, back_ptr, _) = gpu.shared_buffer(size);
|
||||
let dst = gpu.default_uav(64 << 10);
|
||||
// SAFETY: mapped buffers, which nothing reads yet; an open
|
||||
// list and live buffers.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(budget_ptr, 0, 256);
|
||||
for (w, word) in [asked, 1, 1].into_iter().enumerate() {
|
||||
src_ptr.cast::<u32>().add(w).write_volatile(word);
|
||||
}
|
||||
if batched {
|
||||
batch::record(&pass, &gpu.list, (&dst, D3D12_RESOURCE_STATE_COMMON), budget_gpu, [src_gpu; 4], table_gpu);
|
||||
assert_eq!(batch::Table::new(table_ptr, 0, [1, 0, 0, 0]).place(1, 0, 2), Some(0));
|
||||
} else {
|
||||
let to = (&dst, D3D12_RESOURCE_STATE_COMMON);
|
||||
assert!(record_clamp_as(&gpu.clamp, &gpu.list, to, budget_gpu, (&src, 0), None, (2, 12, 1), false));
|
||||
}
|
||||
gpu.list.SetComputeRootSignature(&worker.root);
|
||||
gpu.list.SetPipelineState(&worker.pso);
|
||||
gpu.list.SetComputeRootUnorderedAccessView(0, seen.GetGPUVirtualAddress());
|
||||
gpu.list.ExecuteIndirect(&sig, 1, &dst, 0, None, 0);
|
||||
gpu.list.ResourceBarrier(&[uav_barrier()]);
|
||||
gpu.list.ResourceBarrier(&[transition(&seen, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
|
||||
gpu.list.CopyBufferRegion(&back, 0, &seen, 0, size);
|
||||
}
|
||||
gpu.submit_and_wait();
|
||||
// SAFETY: the list has run; mapped words.
|
||||
let word = |i: usize| unsafe { back_ptr.cast::<u32>().add(i).read_volatile() };
|
||||
assert_eq!([word(0), word(1), word(2)], [runs, runs - 1, runs - 1], "asked for {asked}, batched {batched}");
|
||||
let wrong = (0..runs as usize).find(|&g| word(4 + g) != 1);
|
||||
assert_eq!((wrong, word(4 + runs as usize)), (None, 0), "every group once, asked for {asked}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a batch's table says of records added to it: one job per
|
||||
/// record, charged for every execution that reads it, and none for what
|
||||
/// the pass cannot read.
|
||||
|
||||
@@ -81,8 +81,9 @@ void main(uint3 id : SV_DispatchThreadID, uint gi : SV_GroupIndex) {
|
||||
record[1] = min(record[1], (1u << 26) / max(record[0], 1u));
|
||||
cost = record[0] * record[1];
|
||||
} else if (kind == 2) {
|
||||
uint3 g = min(uint3(record[0], record[1], record[2]), uint3(65535u, 65535u, 65535u));
|
||||
if (g.z != 0 && g.x * g.y > GROUPS / g.z) {
|
||||
uint3 g = uint3(record[0], record[1], record[2]);
|
||||
g = min(g, uint3(g.x <= WIDEST ? WIDEST : 65535u, 65535u, 65535u));
|
||||
if ((g.y != 0 && g.x > GROUPS / g.y) || (g.z != 0 && g.x * g.y > GROUPS / g.z)) {
|
||||
g = uint3(0, 0, 0);
|
||||
}
|
||||
cost = g.x * g.y * g.z * 64u;
|
||||
|
||||
@@ -329,6 +329,26 @@ pub(crate) fn views_gone(at: usize, len: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// How many bytes of `[at, at + len)` views of physical pages show; `None`
|
||||
/// if no view touches it (nothing is mapped there, or memory of another
|
||||
/// kind). The runtime's own record of what it mapped: no question to the
|
||||
/// host.
|
||||
pub(crate) fn shown_bytes(at: usize, len: usize) -> Option<u64> {
|
||||
let end = at.saturating_add(len);
|
||||
let v = views();
|
||||
let first = v.views.range(..=at).next_back();
|
||||
let rest = v.views.range(at.saturating_add(1)..end.max(at.saturating_add(1)));
|
||||
let (mut there, mut any) = (0u64, false);
|
||||
for (&base, view) in first.into_iter().chain(rest) {
|
||||
let (from, to) = (base.max(at), base.saturating_add(view.0).min(end));
|
||||
if from < to {
|
||||
there += (to - from) as u64;
|
||||
any = true;
|
||||
}
|
||||
}
|
||||
any.then_some(there)
|
||||
}
|
||||
|
||||
/// How the views cover `[at, at + len)`.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub(crate) enum Cover {
|
||||
@@ -1074,6 +1094,27 @@ mod tests {
|
||||
/// Views as the runtime tells them: a range inside one view, or over
|
||||
/// views that continue each other in one section, is one run; over
|
||||
/// views from elsewhere it is scattered; over a gap it has holes.
|
||||
#[test]
|
||||
fn the_views_say_how_much_of_a_range_is_there() {
|
||||
const K64: usize = 64 << 10;
|
||||
// Addresses nothing has: only the record is asked.
|
||||
let at = 0x7ff1_0000_0000_usize;
|
||||
for (block, blocks) in [(0, 1), (1, 1), (4, 2)] {
|
||||
super::title_memory_view(at + block * K64, blocks * K64, 7, 0);
|
||||
}
|
||||
let shown = |from: usize, len: usize| super::shown_bytes(at + from, len);
|
||||
assert_eq!(shown(0, 8 * K64), Some(4 * K64 as u64));
|
||||
assert_eq!(shown(100, K64), Some(K64 as u64));
|
||||
assert_eq!(shown(K64 + 100, 2 * K64), Some(K64 as u64 - 100));
|
||||
assert_eq!(shown(5 * K64 + 1, 10), Some(10));
|
||||
assert_eq!(shown(2 * K64, 2 * K64), None);
|
||||
assert_eq!(shown(6 * K64, 2 * K64), None);
|
||||
super::views_gone(at + K64, K64);
|
||||
assert_eq!(shown(0, 2 * K64), Some(K64 as u64));
|
||||
super::views_gone(at, 8 * K64);
|
||||
assert_eq!(shown(0, 8 * K64), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn views_say_what_one_placed_buffer_could_show() {
|
||||
let mut views = BTreeMap::new();
|
||||
|
||||
@@ -557,6 +557,7 @@ unsafe fn piece_at(
|
||||
spent(stat::NOTES, opening);
|
||||
}
|
||||
let into = beside.unwrap_or(title);
|
||||
let since = crate::watch::changes();
|
||||
let (mut pages, mut new_pages, mut blocks, mut dwords, mut missing) = (0, 0u64, 0, 0, 0);
|
||||
let mut span: Option<(usize, usize)> = None;
|
||||
for_pages(title, parts, |from, n| {
|
||||
@@ -566,7 +567,26 @@ unsafe fn piece_at(
|
||||
}
|
||||
// SAFETY: the caller's; title memory, by an address that shows it
|
||||
// (`beside`) or the title's own.
|
||||
let done = unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
|
||||
let merge = |take| unsafe { crate::safecopy::merge(into.wrapping_add(from) as *mut u8, now.add(from), held.add(from), n, take) };
|
||||
let mut done = merge(take && beside.is_some());
|
||||
if !done.there && beside.is_none() {
|
||||
// Away only while the runtime changes a mapping beside it: the
|
||||
// rest of it when that is done. What is still not there then is
|
||||
// taken as the caller says.
|
||||
let mut put = done.dwords;
|
||||
let again = crate::watch::again_after_change(since, || {
|
||||
done = merge(false);
|
||||
put += done.dwords;
|
||||
done.there
|
||||
});
|
||||
if !again && take {
|
||||
done = merge(true);
|
||||
put += done.dwords;
|
||||
}
|
||||
done.dwords = put;
|
||||
// (What was new to the first try was new.)
|
||||
done.new = done.new.max(1);
|
||||
}
|
||||
blocks += done.new;
|
||||
dwords += done.dwords;
|
||||
missing += u64::from(!done.there);
|
||||
|
||||
@@ -213,6 +213,43 @@ fn a_piece_lands_what_the_card_wrote_in_its_parts() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A piece whose title memory is away only while the runtime changes a
|
||||
/// mapping lands when that is done; where it stays away the copy's CPU side
|
||||
/// takes the card's bytes (`take`) or not.
|
||||
#[test]
|
||||
fn a_piece_waits_for_a_change_of_mapping() {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, VirtualAlloc, VirtualFree};
|
||||
assert!(crate::safecopy::on());
|
||||
// SAFETY: a reservation of ours, nothing of it committed.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), BLOCK, MEM_RESERVE, PAGE_NOACCESS) } as usize;
|
||||
assert_ne!(at, 0);
|
||||
let now = [9u8; 100];
|
||||
for take in [true, false] {
|
||||
let mut held = [0u8; 100];
|
||||
// SAFETY: arrays of 100 bytes.
|
||||
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], take, &mut Notes::default(), std::ptr::null()) };
|
||||
assert_eq!((put, held), (0, [if take { 9 } else { 0 }; 100]));
|
||||
}
|
||||
let (began, wait) = std::sync::mpsc::channel();
|
||||
let change = std::thread::spawn(move || {
|
||||
let _changing = crate::watch::title_memory_remapping();
|
||||
began.send(()).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
// SAFETY: the reservation's first page.
|
||||
assert!(!unsafe { VirtualAlloc(at as _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null());
|
||||
});
|
||||
wait.recv().unwrap();
|
||||
let mut held = [0u8; 100];
|
||||
// SAFETY: as above.
|
||||
let put = unsafe { piece(at, now.as_ptr(), held.as_mut_ptr(), &[(0, 100)], true, &mut Notes::default(), std::ptr::null()) };
|
||||
change.join().unwrap();
|
||||
assert_eq!((put, held), (100, now));
|
||||
// SAFETY: committed by now.
|
||||
assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 100) }, now);
|
||||
// SAFETY: our reservation.
|
||||
unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
|
||||
}
|
||||
|
||||
/// Landings on several threads beside title threads that write the same
|
||||
/// blocks (other dwords) and a thread that refreshes a copy, guarding what
|
||||
/// it takes: no write of the title's is lost or undone, all the card wrote
|
||||
|
||||
@@ -72,6 +72,6 @@ pub use host::on_failure;
|
||||
pub use inplace::{title_memory_freeing, title_memory_section, title_memory_section_gone, title_memory_view};
|
||||
#[cfg(windows)]
|
||||
pub use watch::{
|
||||
title_memory_allocated, title_memory_reading, title_memory_remapped, title_memory_remapping, title_memory_unmapping,
|
||||
writing as kernel_will_write,
|
||||
kernel_writing, title_memory_allocated, title_memory_freed, title_memory_reading, title_memory_remapped,
|
||||
title_memory_remapping, title_memory_unmapping, writing as kernel_will_write,
|
||||
};
|
||||
@@ -296,13 +296,19 @@ impl GraphicsState {
|
||||
.map(|e| {
|
||||
let slot = e.InputSlot.min(31) as usize;
|
||||
let format = e.Format.0 as u32;
|
||||
let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
|
||||
// An appended element starts at the next multiple of
|
||||
// min(4, its size) after the previous one, where D3D12 (and
|
||||
// vkd3d) place it; the host pipeline gets the title's
|
||||
// descriptions, so the offsets read here must match.
|
||||
let offset = if e.AlignedByteOffset == D3D12_APPEND_ALIGNED_ELEMENT {
|
||||
next[slot]
|
||||
.checked_next_multiple_of(bytes.clamp(1, 4))
|
||||
.unwrap_or(u32::MAX)
|
||||
} else {
|
||||
e.AlignedByteOffset
|
||||
};
|
||||
let bytes = crate::resource::element(format).map_or(0, |(b, _)| b as u32);
|
||||
next[slot] = offset + bytes;
|
||||
next[slot] = offset.saturating_add(bytes);
|
||||
Input {
|
||||
slot: slot as u32,
|
||||
offset,
|
||||
@@ -437,6 +443,19 @@ impl HostPipeline {
|
||||
}
|
||||
let host = host()?;
|
||||
|
||||
let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS19::default();
|
||||
// SAFETY: the feature query writes the structure of the given size.
|
||||
// Older runtimes may not recognize OPTIONS19; that means no support.
|
||||
let aniso_point_mip_supported = unsafe {
|
||||
host.device.CheckFeatureSupport(
|
||||
D3D12_FEATURE_D3D12_OPTIONS19,
|
||||
(&raw mut options).cast(),
|
||||
size_of_val(&options) as u32,
|
||||
)
|
||||
}
|
||||
.is_ok()
|
||||
&& options.AnisoFilterWithPointMipSupported.as_bool();
|
||||
|
||||
// The root signature the translated shaders' bindings define.
|
||||
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
|
||||
// The ranges table parameters point at, alive until the root
|
||||
@@ -544,7 +563,7 @@ impl HostPipeline {
|
||||
}
|
||||
for (n, s) in t.static_samplers.iter().enumerate() {
|
||||
samplers.push(D3D12_STATIC_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER(s.filter as i32),
|
||||
Filter: D3D12_FILTER(s.filter_for_host(aniso_point_mip_supported) as i32),
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE(s.address[0] as i32),
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE(s.address[1] as i32),
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE(s.address[2] as i32),
|
||||
@@ -1431,4 +1450,63 @@ mod tests {
|
||||
assert_eq!(run_draw(0.6, 1.0), 0, "depth 0.5 outside [0.6, 1.0] must be rejected");
|
||||
assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass");
|
||||
}
|
||||
|
||||
fn element(format: DXGI_FORMAT, offset: u32) -> D3D12_INPUT_ELEMENT_DESC {
|
||||
D3D12_INPUT_ELEMENT_DESC {
|
||||
SemanticName: PCSTR(c"TEXCOORD".as_ptr().cast()),
|
||||
SemanticIndex: 0,
|
||||
Format: format,
|
||||
InputSlot: 0,
|
||||
AlignedByteOffset: offset,
|
||||
InputSlotClass: D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA,
|
||||
InstanceDataStepRate: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn offsets(inputs: &[D3D12_INPUT_ELEMENT_DESC]) -> Vec<u32> {
|
||||
let state = GraphicsState {
|
||||
inputs: inputs.to_vec(),
|
||||
..GraphicsState::default()
|
||||
};
|
||||
state.elements().iter().map(|e| e.offset).collect()
|
||||
}
|
||||
|
||||
/// An appended element after one of 1 or 2 bytes started right after
|
||||
/// it; D3D12 aligns it to min(4, its size), so the rectangle expansion
|
||||
/// read its vertices from the wrong bytes.
|
||||
#[test]
|
||||
fn appended_elements_are_aligned() {
|
||||
const APPEND: u32 = D3D12_APPEND_ALIGNED_ELEMENT;
|
||||
// RG8 (2 bytes) then RG32 float: 4, not 2.
|
||||
let a = [
|
||||
element(DXGI_FORMAT_R8G8_UNORM, 0),
|
||||
element(DXGI_FORMAT_R32G32_FLOAT, APPEND),
|
||||
];
|
||||
assert_eq!(offsets(&a), [0, 4]);
|
||||
// R8 then R16 float: 2, not 1; then R8 packs right after it.
|
||||
let b = [
|
||||
element(DXGI_FORMAT_R8_UNORM, 0),
|
||||
element(DXGI_FORMAT_R16_FLOAT, APPEND),
|
||||
element(DXGI_FORMAT_R8_UNORM, APPEND),
|
||||
];
|
||||
assert_eq!(offsets(&b), [0, 2, 4]);
|
||||
// Already aligned layouts are unchanged.
|
||||
let c = [
|
||||
element(DXGI_FORMAT_R8G8B8A8_UNORM, 0),
|
||||
element(DXGI_FORMAT_R32G32_FLOAT, APPEND),
|
||||
element(DXGI_FORMAT_R32G32B32_FLOAT, APPEND),
|
||||
];
|
||||
assert_eq!(offsets(&c), [0, 4, 12]);
|
||||
}
|
||||
|
||||
/// An explicit offset near 4 GiB overflowed the next appended offset
|
||||
/// (a panic in debug builds).
|
||||
#[test]
|
||||
fn a_huge_explicit_offset_does_not_overflow() {
|
||||
let inputs = [
|
||||
element(DXGI_FORMAT_R32G32B32A32_FLOAT, u32::MAX - 8),
|
||||
element(DXGI_FORMAT_R32_FLOAT, D3D12_APPEND_ALIGNED_ELEMENT),
|
||||
];
|
||||
let _ = offsets(&inputs);
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,8 @@ enum Kind {
|
||||
F16,
|
||||
Unorm8,
|
||||
Unorm16,
|
||||
Snorm8,
|
||||
Snorm16,
|
||||
}
|
||||
|
||||
/// Component count and kind of the vertex formats rectangles use.
|
||||
@@ -69,7 +71,16 @@ fn components(format: u32) -> Option<(usize, Kind)> {
|
||||
54 => (1, Kind::F16),
|
||||
11 => (4, Kind::Unorm16),
|
||||
35 => (2, Kind::Unorm16),
|
||||
56 => (1, Kind::Unorm16),
|
||||
28 | 29 | 87 | 91 => (4, Kind::Unorm8),
|
||||
49 => (2, Kind::Unorm8),
|
||||
61 => (1, Kind::Unorm8),
|
||||
13 => (4, Kind::Snorm16),
|
||||
37 => (2, Kind::Snorm16),
|
||||
58 => (1, Kind::Snorm16),
|
||||
31 => (4, Kind::Snorm8),
|
||||
51 => (2, Kind::Snorm8),
|
||||
63 => (1, Kind::Snorm8),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -78,8 +89,8 @@ impl Kind {
|
||||
fn bytes(self) -> usize {
|
||||
match self {
|
||||
Kind::F32 => 4,
|
||||
Kind::F16 | Kind::Unorm16 => 2,
|
||||
Kind::Unorm8 => 1,
|
||||
Kind::F16 | Kind::Unorm16 | Kind::Snorm16 => 2,
|
||||
Kind::Unorm8 | Kind::Snorm8 => 1,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,6 +101,8 @@ impl Kind {
|
||||
Kind::F16 => half_to_f32(u16::from_le_bytes([b[0], b[1]])),
|
||||
Kind::Unorm16 => f32::from(u16::from_le_bytes([b[0], b[1]])) / 65535.0,
|
||||
Kind::Unorm8 => f32::from(b[0]) / 255.0,
|
||||
Kind::Snorm16 => (f32::from(i16::from_le_bytes([b[0], b[1]])) / 32767.0).max(-1.0),
|
||||
Kind::Snorm8 => (f32::from(b[0] as i8) / 127.0).max(-1.0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,6 +116,10 @@ impl Kind {
|
||||
b.copy_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_le_bytes())
|
||||
}
|
||||
Kind::Unorm8 => b[0] = (v.clamp(0.0, 1.0) * 255.0).round() as u8,
|
||||
Kind::Snorm16 => {
|
||||
b.copy_from_slice(&((v.clamp(-1.0, 1.0) * 32767.0).round() as i16).to_le_bytes())
|
||||
}
|
||||
Kind::Snorm8 => b[0] = (v.clamp(-1.0, 1.0) * 127.0).round() as i8 as u8,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -218,6 +235,33 @@ mod tests {
|
||||
assert_eq!(dst[40..], vertex(4.0, 6.0)[..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalized_attributes_are_interpolated_in_their_own_range() {
|
||||
let vertex = |rg: [u8; 2], u16_value: u16, u8_value: u8, snorm8: i8, snorm16: i16| {
|
||||
[
|
||||
&rg[..],
|
||||
&u16_value.to_le_bytes(),
|
||||
&[u8_value, snorm8 as u8],
|
||||
&snorm16.to_le_bytes(),
|
||||
]
|
||||
.concat()
|
||||
};
|
||||
let src = [
|
||||
vertex([3, 250], 1000, 10, i8::MIN, -23000),
|
||||
vertex([8, 200], 500, 3, -120, -18000),
|
||||
vertex([20, 253], 10000, 100, -120, -32000),
|
||||
]
|
||||
.concat();
|
||||
let mut dst = [0; 6 * 8];
|
||||
expand_rects(
|
||||
&src,
|
||||
&mut dst,
|
||||
8,
|
||||
&[(0, 49), (2, 56), (4, 61), (5, 63), (6, 58)],
|
||||
);
|
||||
assert_eq!(dst[40..], vertex([15, 255], 10500, 107, -127, -32767));
|
||||
}
|
||||
|
||||
/// `half_to_f32` reads subnormals, so an f16 rectangle output must be
|
||||
/// able to write them back instead of flushing every one to zero.
|
||||
#[test]
|
||||
|
||||
@@ -8,6 +8,10 @@ use super::wire::{ALL, Barrier, Cmd, NONE, Va, slot};
|
||||
/// The buffer the clamped arguments of all clamp passes lie in, in lists
|
||||
/// edited by [`clamps`].
|
||||
pub const RESULTS: u32 = u32::MAX - 1;
|
||||
/// The buffer texels are read back through (`play::pixel`).
|
||||
pub const PROBE: u32 = u32::MAX - 2;
|
||||
/// A buffer of the card's that depth goes through on the way there.
|
||||
pub const SCRATCH: u32 = u32::MAX - 3;
|
||||
|
||||
const INDIRECT_ARGUMENT: i32 = 0x200;
|
||||
const UNORDERED_ACCESS: i32 = 0x8;
|
||||
|
||||
@@ -31,6 +31,7 @@ use super::wire::{
|
||||
|
||||
pub mod diverge;
|
||||
mod merge;
|
||||
pub mod pixel;
|
||||
mod upcopies;
|
||||
|
||||
/// The name of the argument clamp's pipeline, by which its passes are
|
||||
@@ -359,6 +360,12 @@ pub fn listing(folder: &Path, lists: (u32, u32), line: &mut dyn FnMut(&str)) ->
|
||||
other => format!("{other:?}"),
|
||||
};
|
||||
line(&format!("buffer {} {} bytes, {place}: {}", r.id, r.desc.width, r.name));
|
||||
} else {
|
||||
let d = &r.desc;
|
||||
line(&format!(
|
||||
"texture {} {}x{}x{} mips {} f{}: {}",
|
||||
r.id, d.width, d.height, d.depth, d.mips, d.format, r.name
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut place = 0;
|
||||
@@ -464,6 +471,8 @@ pub struct Player {
|
||||
card_writes: HashSet<u32>,
|
||||
/// The results of clamp passes ([`RESULTS`]).
|
||||
results: Option<ID3D12Resource>,
|
||||
/// Other buffers of ours that commands name.
|
||||
extra: HashMap<u32, ID3D12Resource>,
|
||||
commands: Vec<Vec<Cmd>>,
|
||||
/// Resources in the states of the start (not those of the end).
|
||||
fresh: bool,
|
||||
@@ -531,6 +540,7 @@ impl Player {
|
||||
merging: false,
|
||||
card_writes: HashSet::new(),
|
||||
results: None,
|
||||
extra: HashMap::new(),
|
||||
commands,
|
||||
fresh: true,
|
||||
at: States::default(),
|
||||
@@ -628,7 +638,10 @@ impl Player {
|
||||
if id == RESULTS {
|
||||
return self.results.as_ref();
|
||||
}
|
||||
self.objects.get(&id).map(|o| &o.res)
|
||||
self.objects
|
||||
.get(&id)
|
||||
.map(|o| &o.res)
|
||||
.or_else(|| self.extra.get(&id))
|
||||
}
|
||||
|
||||
fn va(&self, va: &Va) -> u64 {
|
||||
|
||||
@@ -0,0 +1,843 @@
|
||||
//! What draws a pixel: `--pixel`. After every command that can change a
|
||||
//! texture, the texel under the pixel is copied out of it (of a draw: of its
|
||||
//! targets, where the pixel lies in its viewport, and of the textures shaders
|
||||
//! may write; of a dispatch: of those; of a copy, clear or resolve: of where
|
||||
//! it goes), and commands that changed one are named with the values before
|
||||
//! and after.
|
||||
|
||||
use super::edit::{PROBE, SCRATCH};
|
||||
use super::*;
|
||||
|
||||
/// What to look at.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Pixels {
|
||||
/// Points of the presented picture.
|
||||
pub points: Vec<(u32, u32)>,
|
||||
/// Texels of textures: resource, subresource, place.
|
||||
pub texels: Vec<(u32, u32, u32, u32)>,
|
||||
/// Only these lists are looked into.
|
||||
pub lists: Option<(u32, u32)>,
|
||||
/// Depth targets too (a copy of the whole target for each draw).
|
||||
pub depth: bool,
|
||||
/// Textures shaders may write too.
|
||||
pub written: bool,
|
||||
/// Indirect draws that are run one by one: list, command.
|
||||
pub split: Vec<(u32, u32)>,
|
||||
}
|
||||
|
||||
/// Bytes a sample has.
|
||||
const ROOM: u64 = 512;
|
||||
/// The most samples of one run.
|
||||
const MOST: usize = 1 << 20;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Sample {
|
||||
list: u32,
|
||||
command: usize,
|
||||
/// Of a split draw: which one.
|
||||
part: u32,
|
||||
before: bool,
|
||||
spot: Spot,
|
||||
pso: u32,
|
||||
what: &'static str,
|
||||
}
|
||||
|
||||
/// A texture's part that a sample can be taken from.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
struct Spot {
|
||||
res: u32,
|
||||
sub: u32,
|
||||
x: u32,
|
||||
y: u32,
|
||||
z: u32,
|
||||
/// The point of the picture it stands for (or [`OWN`]).
|
||||
point: usize,
|
||||
format: i32,
|
||||
depth: bool,
|
||||
}
|
||||
|
||||
/// In [`Spot::point`]: a texel asked for by itself.
|
||||
const OWN: usize = usize::MAX;
|
||||
|
||||
/// The texel of a target of `size` that shows the point `(x, y)` of a picture
|
||||
/// of `picture`, drawn through `view` (x, y, width, height): none if the
|
||||
/// target has another shape than the picture.
|
||||
fn texel(
|
||||
(x, y): (u32, u32),
|
||||
picture: (u32, u32),
|
||||
view: [f32; 4],
|
||||
size: (u32, u32),
|
||||
) -> Option<(u32, u32)> {
|
||||
let (w, h) = (picture.0 as f32, picture.1 as f32);
|
||||
if !same_shape((view[2], view[3]), (w, h)) || view[2] < 16.0 {
|
||||
return None;
|
||||
}
|
||||
let a = (view[0] + (x as f32 + 0.5) / w * view[2]).floor();
|
||||
let b = (view[1] + (y as f32 + 0.5) / h * view[3]).floor();
|
||||
(a >= 0.0 && b >= 0.0 && a < size.0 as f32 && b < size.1 as f32).then_some((a as u32, b as u32))
|
||||
}
|
||||
|
||||
fn same_shape(a: (f32, f32), b: (f32, f32)) -> bool {
|
||||
(0.97..1.03).contains(&(a.0 * b.1 / (a.1 * b.0).max(1e-6)))
|
||||
}
|
||||
|
||||
/// A float from a small one's bits (5 bits of exponent, `mantissa` of
|
||||
/// mantissa, no sign).
|
||||
fn small(bits: u32, mantissa: u32) -> f32 {
|
||||
let (e, m) = (
|
||||
bits >> mantissa & 31,
|
||||
(bits & ((1 << mantissa) - 1)) as f32,
|
||||
);
|
||||
let unit = (1u32 << mantissa) as f32;
|
||||
match e {
|
||||
0 => m / unit * 2f32.powi(-14),
|
||||
31 if m == 0.0 => f32::INFINITY,
|
||||
31 => f32::NAN,
|
||||
e => (1.0 + m / unit) * 2f32.powi(e as i32 - 15),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of a texel of a format; 0 for formats not read.
|
||||
fn texel_bytes(format: i32) -> usize {
|
||||
match format {
|
||||
1..=4 => 16,
|
||||
5..=8 => 12,
|
||||
9..=22 => 8,
|
||||
23..=47 => 4,
|
||||
48..=59 => 2,
|
||||
60..=65 => 1,
|
||||
67 | 85..=93 => 4,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// A texel in words.
|
||||
fn texel_text(format: i32, b: &[u8]) -> String {
|
||||
let n = texel_bytes(format);
|
||||
if n == 0 || b.len() < n {
|
||||
return format!("{b:02x?}");
|
||||
}
|
||||
let word = |i: usize| u32::from_le_bytes([b[i * 4], b[i * 4 + 1], b[i * 4 + 2], b[i * 4 + 3]]);
|
||||
let float = |i: usize| f32::from_bits(word(i));
|
||||
let short = |i: usize| u16::from_le_bytes([b[i * 2], b[i * 2 + 1]]);
|
||||
let half = |i: usize| {
|
||||
let v = small(u32::from(short(i) & 0x7FFF), 10);
|
||||
if short(i) >> 15 != 0 { -v } else { v }
|
||||
};
|
||||
let unorm16 = |i: usize| f32::from(short(i)) / 65535.0;
|
||||
let snorm16 = |i: usize| f32::from(short(i) as i16) / 32767.0;
|
||||
let unorm8 = |i: usize| f32::from(b[i]) / 255.0;
|
||||
let snorm8 = |i: usize| f32::from(b[i] as i8) / 127.0;
|
||||
let all: Vec<f32> = match format {
|
||||
1 | 2 => (0..4).map(float).collect(),
|
||||
5 | 6 => (0..3).map(float).collect(),
|
||||
9 | 10 => (0..4).map(half).collect(),
|
||||
11 => (0..4).map(unorm16).collect(),
|
||||
13 => (0..4).map(snorm16).collect(),
|
||||
15 | 16 => (0..2).map(float).collect(),
|
||||
23 | 24 => vec![
|
||||
(word(0) & 1023) as f32 / 1023.0,
|
||||
(word(0) >> 10 & 1023) as f32 / 1023.0,
|
||||
(word(0) >> 20 & 1023) as f32 / 1023.0,
|
||||
(word(0) >> 30) as f32 / 3.0,
|
||||
],
|
||||
26 => vec![
|
||||
small(word(0) & 2047, 6),
|
||||
small(word(0) >> 11 & 2047, 6),
|
||||
small(word(0) >> 22, 5),
|
||||
],
|
||||
27..=29 | 87 | 90 | 91 => (0..4).map(unorm8).collect(),
|
||||
31 => (0..4).map(snorm8).collect(),
|
||||
33 | 34 => (0..2).map(half).collect(),
|
||||
35 => (0..2).map(unorm16).collect(),
|
||||
37 => (0..2).map(snorm16).collect(),
|
||||
39..=41 => vec![float(0)],
|
||||
48 | 49 => (0..2).map(unorm8).collect(),
|
||||
51 => (0..2).map(snorm8).collect(),
|
||||
53 | 54 => vec![half(0)],
|
||||
55 | 56 => vec![unorm16(0)],
|
||||
58 => vec![snorm16(0)],
|
||||
60 | 61 => vec![unorm8(0)],
|
||||
63 => vec![snorm8(0)],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let all: Vec<String> = all.iter().map(|v| format!("{v:.5}")).collect();
|
||||
format!("{} {:02x?}", all.join(" "), &b[..n]).trim().to_owned()
|
||||
}
|
||||
|
||||
/// One draw of an indirect call that has many.
|
||||
fn part_of(c: &Cmd, i: u32, stride: u32) -> Cmd {
|
||||
match c {
|
||||
Cmd::Indirect {
|
||||
signature,
|
||||
args,
|
||||
at,
|
||||
..
|
||||
} => Cmd::Indirect {
|
||||
signature: *signature,
|
||||
most: 1,
|
||||
args: *args,
|
||||
at: at + u64::from(i) * u64::from(stride),
|
||||
count: NONE,
|
||||
count_at: 0,
|
||||
},
|
||||
c => c.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn transition(res: u32, sub: u32, before: u32, after: u32) -> Barrier {
|
||||
Barrier::Transition {
|
||||
flags: 0,
|
||||
res,
|
||||
sub,
|
||||
before: before as i32,
|
||||
after: after as i32,
|
||||
}
|
||||
}
|
||||
|
||||
/// What is known of the frame's textures.
|
||||
struct Textures {
|
||||
/// Formats copies have.
|
||||
copied_as: HashMap<u32, i32>,
|
||||
/// Textures shaders may write and that have the picture's shape.
|
||||
shaped: Vec<u32>,
|
||||
/// The viewport targets of a size were last drawn through.
|
||||
drawn: HashMap<(u32, u32), [f32; 4]>,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
fn texture(&self, id: u32) -> Option<&wire::Resource> {
|
||||
let o = self.objects.get(&id)?;
|
||||
let r = &self.frame.resources[o.index];
|
||||
(r.desc.dimension != D3D12_RESOURCE_DIMENSION_BUFFER.0 && r.desc.samples[0] <= 1)
|
||||
.then_some(r)
|
||||
}
|
||||
|
||||
/// What a view of a target is of: subresource, depth slice, size, format.
|
||||
fn seen_by(&self, s: &Slot) -> Option<(u32, u32, (u32, u32), i32)> {
|
||||
let r = self.texture(s.res)?;
|
||||
let word = |i: usize| {
|
||||
u32::from_le_bytes([
|
||||
s.desc[i * 4],
|
||||
s.desc[i * 4 + 1],
|
||||
s.desc[i * 4 + 2],
|
||||
s.desc[i * 4 + 3],
|
||||
])
|
||||
};
|
||||
let (mut mip, mut slice, mut z, mut format) = (0, 0, 0, 0);
|
||||
if s.described != 0 {
|
||||
format = word(0) as i32;
|
||||
match (s.kind, word(1) as i32) {
|
||||
// 2D, 2D array and 3D views.
|
||||
(slot::RTV, 4) => mip = word(2),
|
||||
(slot::RTV, 5) => (mip, slice) = (word(2), word(3)),
|
||||
(slot::RTV, 8) => (mip, z) = (word(2), word(3)),
|
||||
(slot::DSV, 3) => mip = word(3),
|
||||
(slot::DSV, 4) => (mip, slice) = (word(3), word(4)),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
if format == 0 {
|
||||
format = r.desc.format;
|
||||
}
|
||||
let mips = u32::from(r.desc.mips.max(1));
|
||||
let mip = mip.min(mips - 1);
|
||||
let size = (
|
||||
(r.desc.width as u32 >> mip).max(1),
|
||||
(r.desc.height >> mip).max(1),
|
||||
);
|
||||
Some((mip + slice * mips, z, size, format))
|
||||
}
|
||||
|
||||
/// Width and height of the presented picture.
|
||||
pub fn picture_size(&self) -> Option<(u32, u32)> {
|
||||
self.frame.presents.last().map(|p| (p.width, p.height))
|
||||
}
|
||||
|
||||
/// Says which commands change the texels under points of the picture.
|
||||
pub fn pixel(&mut self, o: &Options, p: &Pixels, say: &mut dyn FnMut(String)) -> Result<()> {
|
||||
let picture = self.picture_size().context("no picture was presented")?;
|
||||
self.set_merging(o.merge)?;
|
||||
let mut report = Report::default();
|
||||
let submits = self.edited(o, &mut report, &[]);
|
||||
let counts = self.counts_of(o, p, &submits)?;
|
||||
let mut samples: Vec<Sample> = Vec::new();
|
||||
let made = self.sampled(p, &submits, picture, &counts, &mut samples)?;
|
||||
let bytes = self.probed(o, &made, samples.len() as u64 * ROOM)?;
|
||||
say(format!(
|
||||
"{} texels taken; picture {}x{}; points {:?}",
|
||||
samples.len(),
|
||||
picture.0,
|
||||
picture.1,
|
||||
p.points
|
||||
));
|
||||
report.notes.drain(..).for_each(&mut *say);
|
||||
let mut last: HashMap<(u32, u32, (u32, u32), usize), Vec<u8>> = HashMap::new();
|
||||
let mut said = None;
|
||||
for (i, s) in samples.iter().enumerate() {
|
||||
let t = &s.spot;
|
||||
let n = texel_bytes(t.format).max(1);
|
||||
let now = bytes[i * ROOM as usize..][..n].to_vec();
|
||||
let was = last.insert((t.res, t.sub, (t.x, t.y), t.point), now.clone());
|
||||
if was.as_ref() == Some(&now) {
|
||||
continue;
|
||||
}
|
||||
let point = match t.point {
|
||||
OWN => String::new(),
|
||||
n => format!("point {n} "),
|
||||
};
|
||||
let spot = format!(
|
||||
" {point}{} sub {} at {},{}:",
|
||||
self.called(t.res),
|
||||
t.sub,
|
||||
t.x,
|
||||
t.y
|
||||
);
|
||||
let now = texel_text(t.format, &now);
|
||||
if s.before {
|
||||
// Seen for the first time, or changed by what is not looked
|
||||
// into.
|
||||
if was.is_some() {
|
||||
say(format!("{spot} changed unseen to {now}"));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if said != Some((s.list, s.command, s.part)) {
|
||||
said = Some((s.list, s.command, s.part));
|
||||
let part = match p.split.contains(&(s.list, s.command as u32)) {
|
||||
true => format!(" draw {}", s.part),
|
||||
false => String::new(),
|
||||
};
|
||||
let of = match s.pso {
|
||||
NONE => String::new(),
|
||||
pso => format!(" of {pso} {}", self.pipeline_name(pso)),
|
||||
};
|
||||
say(format!("{}:{}{part} {}{of}", s.list, s.command, s.what));
|
||||
}
|
||||
let was = was.map_or("?".to_owned(), |w| texel_text(t.format, &w));
|
||||
say(format!("{spot} {was} -> {now}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs the frame with commands that copy to [`PROBE`], which is of
|
||||
/// `len` bytes; its bytes after that.
|
||||
fn probed(&mut self, o: &Options, submits: &[Vec<Vec<Cmd>>], len: u64) -> Result<Vec<u8>> {
|
||||
let (back, data) = gpu::buffer(
|
||||
&self.device,
|
||||
D3D12_HEAP_TYPE_READBACK,
|
||||
len.max(4),
|
||||
D3D12_RESOURCE_FLAG_NONE,
|
||||
)?;
|
||||
self.extra.insert(PROBE, back);
|
||||
self.restore(o.restore)?;
|
||||
let built = self.build(submits, o)?;
|
||||
self.fresh = false;
|
||||
self.send(&built, o)?;
|
||||
// SAFETY: the mapping; the copies into it have run.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(data, len as usize) }.to_vec();
|
||||
self.extra.remove(&PROBE);
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// How many draws the calls to be split have.
|
||||
fn counts_of(
|
||||
&mut self,
|
||||
o: &Options,
|
||||
p: &Pixels,
|
||||
submits: &[Vec<Vec<Cmd>>],
|
||||
) -> Result<HashMap<(u32, u32), u32>> {
|
||||
let mut counts = HashMap::new();
|
||||
if p.split.is_empty() {
|
||||
return Ok(counts);
|
||||
}
|
||||
const ARGS: u32 = 0x200;
|
||||
let mut made = submits.to_vec();
|
||||
let mut asked: Vec<(u32, u32)> = Vec::new();
|
||||
for (here, cmds) in made.iter_mut().flatten().enumerate() {
|
||||
let mut out = Vec::new();
|
||||
for (n, c) in std::mem::take(cmds).into_iter().enumerate() {
|
||||
let key = (here as u32, n as u32);
|
||||
if let Cmd::Indirect {
|
||||
most,
|
||||
count,
|
||||
count_at,
|
||||
..
|
||||
} = c
|
||||
&& p.split.contains(&key)
|
||||
{
|
||||
counts.insert(key, most);
|
||||
if count != NONE {
|
||||
out.push(Cmd::Barriers {
|
||||
all: vec![transition(count, ALL, ARGS, COPY_SOURCE)],
|
||||
});
|
||||
out.push(Cmd::CopyBuffer {
|
||||
dst: PROBE,
|
||||
dst_at: asked.len() as u64 * 4,
|
||||
src: count,
|
||||
src_at: count_at,
|
||||
len: 4,
|
||||
});
|
||||
out.push(Cmd::Barriers {
|
||||
all: vec![transition(count, ALL, COPY_SOURCE, ARGS)],
|
||||
});
|
||||
asked.push(key);
|
||||
}
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
*cmds = out;
|
||||
}
|
||||
let bytes = self.probed(o, &made, asked.len() as u64 * 4)?;
|
||||
for (key, n) in asked.iter().zip(bytes.chunks_exact(4)) {
|
||||
if let Some(most) = counts.get_mut(key) {
|
||||
*most = (*most).min(u32::from_le_bytes([n[0], n[1], n[2], n[3]]));
|
||||
}
|
||||
}
|
||||
Ok(counts)
|
||||
}
|
||||
|
||||
fn textures(&self, picture: (u32, u32)) -> Textures {
|
||||
let textures = || {
|
||||
self.frame
|
||||
.resources
|
||||
.iter()
|
||||
.filter(|r| self.texture(r.id).is_some())
|
||||
};
|
||||
let shaped = textures()
|
||||
.filter(|r| {
|
||||
let d = &r.desc;
|
||||
d.dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D.0
|
||||
&& d.flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
|
||||
&& d.width as u32 * 4 >= picture.0
|
||||
&& same_shape(
|
||||
(d.width as f32, d.height as f32),
|
||||
(picture.0 as f32, picture.1 as f32),
|
||||
)
|
||||
})
|
||||
.map(|r| r.id)
|
||||
.collect();
|
||||
let copied_as = textures()
|
||||
.map(|r| {
|
||||
let f = gpu::footprints(&self.device, &gpu::to_desc(&r.desc), 0, 1).0;
|
||||
(r.id, f[0].Footprint.Format.0)
|
||||
})
|
||||
.collect();
|
||||
Textures {
|
||||
copied_as,
|
||||
shaped,
|
||||
drawn: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The spots of a texture (of its subresource `sub`) that is written not
|
||||
/// as a target.
|
||||
fn spots_of(
|
||||
&self,
|
||||
p: &Pixels,
|
||||
t: &Textures,
|
||||
picture: (u32, u32),
|
||||
id: u32,
|
||||
sub: u32,
|
||||
out: &mut Vec<Spot>,
|
||||
) {
|
||||
let Some(r) = self.texture(id) else { return };
|
||||
let depth = r.desc.flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL.0 != 0;
|
||||
for &(res, at, x, y) in &p.texels {
|
||||
if res == id && (sub == at || sub == ALL) {
|
||||
out.push(Spot {
|
||||
res,
|
||||
sub: at,
|
||||
x,
|
||||
y,
|
||||
z: 0,
|
||||
point: OWN,
|
||||
format: r.desc.format,
|
||||
depth,
|
||||
});
|
||||
}
|
||||
}
|
||||
if r.desc.dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D.0 || !(sub == 0 || sub == ALL) {
|
||||
return;
|
||||
}
|
||||
let size = (r.desc.width as u32, r.desc.height);
|
||||
let whole = [0.0, 0.0, size.0 as f32, size.1 as f32];
|
||||
let view = t.drawn.get(&size).copied().unwrap_or(whole);
|
||||
for (point, at) in p.points.iter().enumerate() {
|
||||
if let Some((x, y)) = texel(*at, picture, view, size) {
|
||||
out.push(Spot {
|
||||
res: id,
|
||||
sub: 0,
|
||||
x,
|
||||
y,
|
||||
z: 0,
|
||||
point,
|
||||
format: r.desc.format,
|
||||
depth,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a texture is the one in use of those that share its memory.
|
||||
fn in_use(&self, states: &States, id: u32) -> bool {
|
||||
self.objects.get(&id).is_some_and(|o| {
|
||||
!self.frame.resources[o.index].idle || states.used.contains_key(&id)
|
||||
})
|
||||
}
|
||||
|
||||
/// The commands that copy the texels of `spots` to [`PROBE`] from `first`
|
||||
/// on; `copied`: a copy to them went before.
|
||||
fn take(
|
||||
&self,
|
||||
spots: &[Spot],
|
||||
first: u64,
|
||||
states: &States,
|
||||
t: &Textures,
|
||||
copied: bool,
|
||||
scratch: &mut u64,
|
||||
out: &mut Vec<Cmd>,
|
||||
) {
|
||||
let (mut to, mut from, mut copies) = (Vec::new(), Vec::new(), Vec::new());
|
||||
let mut moved = HashSet::new();
|
||||
for (i, s) in spots.iter().enumerate() {
|
||||
let Some(r) = self.texture(s.res) else {
|
||||
continue;
|
||||
};
|
||||
let all = states.get(s.res).unwrap_or(vec![COMMON]);
|
||||
let mut state = all
|
||||
.get(s.sub as usize)
|
||||
.or(all.first())
|
||||
.copied()
|
||||
.unwrap_or(COMMON);
|
||||
if copied && state == COMMON {
|
||||
state = COPY_DEST;
|
||||
}
|
||||
if state & COPY_SOURCE == 0 && moved.insert((s.res, s.sub)) {
|
||||
to.push(transition(s.res, s.sub, state, COPY_SOURCE));
|
||||
from.push(transition(s.res, s.sub, COPY_SOURCE, state));
|
||||
}
|
||||
let offset = (first + i as u64) * ROOM;
|
||||
if !s.depth {
|
||||
copies.push(Cmd::CopyTexture {
|
||||
dst: Loc::Placed {
|
||||
res: PROBE,
|
||||
offset,
|
||||
format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format),
|
||||
size: [1, 1, 1],
|
||||
pitch: 256,
|
||||
},
|
||||
at: [0; 3],
|
||||
src: Loc::Sub {
|
||||
res: s.res,
|
||||
sub: s.sub,
|
||||
},
|
||||
part: Some([s.x, s.y, s.z, s.x + 1, s.y + 1, s.z + 1]),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
// Depth is only copied whole.
|
||||
let mip = s.sub % u32::from(r.desc.mips.max(1));
|
||||
let w = (r.desc.width as u32 >> mip).max(1);
|
||||
let h = (r.desc.height >> mip).max(1);
|
||||
let bytes = texel_bytes(s.format) as u64;
|
||||
let pitch = (w * bytes as u32).next_multiple_of(256);
|
||||
*scratch = (*scratch).max(u64::from(pitch) * u64::from(h));
|
||||
copies.push(Cmd::CopyTexture {
|
||||
dst: Loc::Placed {
|
||||
res: SCRATCH,
|
||||
offset: 0,
|
||||
format: t.copied_as.get(&s.res).copied().unwrap_or(r.desc.format),
|
||||
size: [w, h, 1],
|
||||
pitch,
|
||||
},
|
||||
at: [0; 3],
|
||||
src: Loc::Sub {
|
||||
res: s.res,
|
||||
sub: s.sub,
|
||||
},
|
||||
part: None,
|
||||
});
|
||||
copies.push(Cmd::Barriers {
|
||||
all: vec![transition(SCRATCH, ALL, COPY_DEST, COPY_SOURCE)],
|
||||
});
|
||||
copies.push(Cmd::CopyBuffer {
|
||||
dst: PROBE,
|
||||
dst_at: offset,
|
||||
src: SCRATCH,
|
||||
src_at: u64::from(pitch) * u64::from(s.y) + u64::from(s.x) * bytes,
|
||||
len: bytes,
|
||||
});
|
||||
copies.push(Cmd::Barriers {
|
||||
all: vec![transition(SCRATCH, ALL, COPY_SOURCE, COPY_DEST)],
|
||||
});
|
||||
}
|
||||
if !to.is_empty() {
|
||||
out.push(Cmd::Barriers { all: to });
|
||||
}
|
||||
out.extend(copies);
|
||||
if !from.is_empty() {
|
||||
out.push(Cmd::Barriers { all: from });
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame's lists with copies of texels after commands.
|
||||
fn sampled(
|
||||
&mut self,
|
||||
p: &Pixels,
|
||||
submits: &[Vec<Vec<Cmd>>],
|
||||
picture: (u32, u32),
|
||||
counts: &HashMap<(u32, u32), u32>,
|
||||
samples: &mut Vec<Sample>,
|
||||
) -> Result<Vec<Vec<Vec<Cmd>>>> {
|
||||
let strides: HashMap<u32, u32> = self
|
||||
.frame
|
||||
.signatures
|
||||
.iter()
|
||||
.map(|s| (s.id, s.stride))
|
||||
.collect();
|
||||
let dispatching: HashSet<u32> = self
|
||||
.frame
|
||||
.signatures
|
||||
.iter()
|
||||
.filter(|s| {
|
||||
s.args
|
||||
.iter()
|
||||
.any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)
|
||||
})
|
||||
.map(|s| s.id)
|
||||
.collect();
|
||||
let mut t = self.textures(picture);
|
||||
let mut states = self.start_states();
|
||||
let mut known: HashSet<Spot> = HashSet::new();
|
||||
let mut made = Vec::new();
|
||||
let mut here = 0;
|
||||
let mut scratch = 0u64;
|
||||
for lists in submits {
|
||||
let mut out_lists = Vec::new();
|
||||
for cmds in lists {
|
||||
let wanted = p.lists.is_none_or(|(a, b)| (a..=b).contains(&here));
|
||||
let mut out = Vec::with_capacity(cmds.len());
|
||||
let mut pso = NONE;
|
||||
let mut targets: Vec<Slot> = Vec::new();
|
||||
let mut view: Option<[f32; 4]> = None;
|
||||
for (n, c) in cmds.iter().enumerate() {
|
||||
match c {
|
||||
Cmd::Pipeline { pso: id } => pso = *id,
|
||||
Cmd::Targets { colors, depth } => {
|
||||
targets = colors.iter().chain(depth).copied().collect();
|
||||
}
|
||||
Cmd::Viewports { all } => {
|
||||
view = all.first().map(|v| [v[0], v[1], v[2], v[3]]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let dispatches = matches!(c, Cmd::Dispatch { .. })
|
||||
|| matches!(c, Cmd::Indirect { signature, .. } if dispatching.contains(signature));
|
||||
let draws = c.runs_shaders() && !dispatches;
|
||||
let mut spots: Vec<Spot> = Vec::new();
|
||||
let looked = wanted && c.works() && samples.len() < MOST;
|
||||
for s in targets.iter().filter(|_| looked && draws) {
|
||||
let Some((sub, z, size, format)) = self.seen_by(s) else {
|
||||
continue;
|
||||
};
|
||||
let depth = s.kind == slot::DSV;
|
||||
let spot = |x, y, point| Spot {
|
||||
res: s.res,
|
||||
sub,
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
point,
|
||||
format,
|
||||
depth,
|
||||
};
|
||||
let view = view.unwrap_or([0.0, 0.0, size.0 as f32, size.1 as f32]);
|
||||
for (point, at) in p.points.iter().enumerate() {
|
||||
if let Some((x, y)) = texel(*at, picture, view, size) {
|
||||
t.drawn.insert(size, view);
|
||||
spots.push(spot(x, y, point));
|
||||
}
|
||||
}
|
||||
for &(res, at, x, y) in &p.texels {
|
||||
if (res, at) == (s.res, sub) {
|
||||
spots.push(spot(x, y, OWN));
|
||||
}
|
||||
}
|
||||
}
|
||||
if looked && c.runs_shaders() {
|
||||
let all = p.texels.iter().map(|t| t.0);
|
||||
let some = p.written && (dispatches || !targets.is_empty());
|
||||
let all: HashSet<u32> =
|
||||
all.chain(t.shaped.iter().copied().filter(|_| some)).collect();
|
||||
for id in all {
|
||||
let writable = states
|
||||
.get(id)
|
||||
.is_some_and(|s| s.iter().any(|s| s & UNORDERED_ACCESS != 0));
|
||||
if writable && self.in_use(&states, id) {
|
||||
self.spots_of(p, &t, picture, id, ALL, &mut spots);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut copied = false;
|
||||
if looked {
|
||||
let mut to = None;
|
||||
match c {
|
||||
Cmd::CopyTexture {
|
||||
dst: Loc::Sub { res, sub },
|
||||
..
|
||||
} => to = Some((*res, *sub, true)),
|
||||
Cmd::CopyResource { dst, .. } => to = Some((*dst, ALL, true)),
|
||||
Cmd::Resolve { dst, dst_sub, .. }
|
||||
| Cmd::ResolveRegion { dst, dst_sub, .. } => {
|
||||
to = Some((*dst, *dst_sub, false));
|
||||
}
|
||||
Cmd::ClearTarget { view, .. } | Cmd::ClearDepth { view, .. } => {
|
||||
to = self.seen_by(view).map(|s| (view.res, s.0, false));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some((res, sub, is_copy)) = to {
|
||||
copied = is_copy;
|
||||
self.spots_of(p, &t, picture, res, sub, &mut spots);
|
||||
}
|
||||
}
|
||||
let mut seen = HashSet::new();
|
||||
spots.retain(|s| {
|
||||
(p.depth || !s.depth) && texel_bytes(s.format) > 0 && seen.insert(*s)
|
||||
});
|
||||
let what = match c {
|
||||
Cmd::Draw { .. } => "Draw",
|
||||
Cmd::DrawIndexed { .. } => "DrawIndexed",
|
||||
Cmd::DispatchMesh { .. } => "DispatchMesh",
|
||||
Cmd::Dispatch { .. } => "Dispatch",
|
||||
Cmd::Indirect { .. } if dispatches => "indirect Dispatch",
|
||||
Cmd::Indirect { .. } => "indirect draw",
|
||||
Cmd::ClearTarget { .. } | Cmd::ClearDepth { .. } => "clear",
|
||||
Cmd::Resolve { .. } | Cmd::ResolveRegion { .. } => "resolve",
|
||||
_ => "copy",
|
||||
};
|
||||
let runs = if c.runs_shaders() { pso } else { NONE };
|
||||
let mut take = |before: bool, part: u32, spots: &[Spot], out: &mut Vec<Cmd>| {
|
||||
let first = samples.len() as u64;
|
||||
self.take(spots, first, &states, &t, copied && !before, &mut scratch, out);
|
||||
samples.extend(spots.iter().map(|spot| Sample {
|
||||
list: here,
|
||||
command: n,
|
||||
part,
|
||||
before,
|
||||
spot: *spot,
|
||||
pso: runs,
|
||||
what,
|
||||
}));
|
||||
};
|
||||
// What was not seen before this command, as it is now.
|
||||
let new: Vec<Spot> =
|
||||
spots.iter().filter(|s| known.insert(**s)).copied().collect();
|
||||
if !new.is_empty() {
|
||||
take(true, 0, &new, &mut out);
|
||||
}
|
||||
match (counts.get(&(here, n as u32)), c) {
|
||||
(Some(&count), Cmd::Indirect { signature, .. }) => {
|
||||
let stride = strides.get(signature).copied().unwrap_or(0);
|
||||
for i in 0..count {
|
||||
out.push(part_of(c, i, stride));
|
||||
take(false, i, &spots, &mut out);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
out.push(c.clone());
|
||||
if !spots.is_empty() {
|
||||
take(false, 0, &spots, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut all = Vec::new();
|
||||
states::changes(c, &mut all);
|
||||
all.iter().for_each(|c| states.change(c));
|
||||
}
|
||||
out_lists.push(out);
|
||||
here += 1;
|
||||
}
|
||||
states.decay();
|
||||
made.push(out_lists);
|
||||
}
|
||||
if scratch > 0 {
|
||||
let buffer = gpu::buffer(
|
||||
&self.device,
|
||||
D3D12_HEAP_TYPE_DEFAULT,
|
||||
scratch,
|
||||
D3D12_RESOURCE_FLAG_NONE,
|
||||
)?;
|
||||
self.extra.insert(SCRATCH, buffer.0);
|
||||
}
|
||||
Ok(made)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn points_lie_in_viewports_of_the_pictures_shape() {
|
||||
let whole = |w: u32, h: u32| ([0.0, 0.0, w as f32, h as f32], (w, h));
|
||||
let picture = (3840, 2160);
|
||||
let (view, size) = whole(1920, 1080);
|
||||
assert_eq!(texel((3839, 2159), picture, view, size), Some((1919, 1079)));
|
||||
assert_eq!(texel((0, 0), picture, view, size), Some((0, 0)));
|
||||
let (view, size) = whole(2048, 2048);
|
||||
assert_eq!(texel((0, 0), picture, view, size), None);
|
||||
// A part of a larger target.
|
||||
let part = [0.0, 0.0, 1920.0, 1080.0];
|
||||
assert_eq!(
|
||||
texel((1920, 1080), picture, part, (3840, 2160)),
|
||||
Some((960, 540))
|
||||
);
|
||||
let beside = [1920.0, 0.0, 1920.0, 1080.0];
|
||||
assert_eq!(texel((1920, 1080), picture, beside, (1920, 1080)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn texels_are_read() {
|
||||
assert_eq!(
|
||||
texel_text(41, &1.5f32.to_le_bytes()),
|
||||
"1.50000 [00, 00, c0, 3f]"
|
||||
);
|
||||
assert_eq!(
|
||||
texel_text(28, &[255, 0, 0, 51]),
|
||||
"1.00000 0.00000 0.00000 0.20000 [ff, 00, 00, 33]"
|
||||
);
|
||||
assert!(
|
||||
texel_text(10, &[0, 0x3C, 0, 0xBC, 0, 0, 0, 0x38])
|
||||
.starts_with("1.00000 -1.00000 0.00000 0.50000 ")
|
||||
);
|
||||
let v = 0x3C0u32 | 0x380 << 11 | 0x200 << 22;
|
||||
assert!(texel_text(26, &v.to_le_bytes()).starts_with("1.00000 0.50000 2.00000 "));
|
||||
assert_eq!(texel_text(42, &[1, 2, 3, 4]), "[01, 02, 03, 04]");
|
||||
// Too few bytes, or a format that is not read.
|
||||
assert_eq!(texel_text(41, &[1]), "[01]");
|
||||
assert_eq!(texel_text(98, &[1, 2]), "[01, 02]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_indirect_draw_is_taken_apart() {
|
||||
let all = Cmd::Indirect {
|
||||
signature: 1,
|
||||
most: 8,
|
||||
args: 2,
|
||||
at: 100,
|
||||
count: 3,
|
||||
count_at: 4,
|
||||
};
|
||||
let one = Cmd::Indirect {
|
||||
signature: 1,
|
||||
most: 1,
|
||||
args: 2,
|
||||
at: 124,
|
||||
count: NONE,
|
||||
count_at: 0,
|
||||
};
|
||||
assert_eq!(part_of(&all, 2, 12), one);
|
||||
}
|
||||
}
|
||||
@@ -585,7 +585,7 @@ pub(crate) fn family(format: u32) -> u32 {
|
||||
(44, 47),
|
||||
(48, 52),
|
||||
(53, 59),
|
||||
(60, 65),
|
||||
(60, 64),
|
||||
(70, 72),
|
||||
(73, 75),
|
||||
(76, 78),
|
||||
@@ -695,8 +695,7 @@ const NO_FOOTPRINT: PlacedFootprint = PlacedFootprint {
|
||||
row_pitch: 0,
|
||||
};
|
||||
|
||||
/// One subresource's size in an upload buffer: footprint (offset 0), rows
|
||||
/// and bytes per row. Planes of depth-stencil formats are not told apart.
|
||||
/// One subresource's upload footprint (offset 0), row count and unpadded row size.
|
||||
fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32, u64)> {
|
||||
const PITCH: u64 = 256;
|
||||
if desc.dimension == BUFFER {
|
||||
@@ -716,11 +715,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32,
|
||||
} else {
|
||||
u32::from(desc.depth_or_array_size).max(1)
|
||||
};
|
||||
let (mip, slice) = (index % mips, index / mips);
|
||||
if slice >= slices {
|
||||
return None;
|
||||
}
|
||||
let (element, block) = element(desc.format)?;
|
||||
let mip = index % mips;
|
||||
let plane = index / mips / slices;
|
||||
let depth_stencil = matches!(desc.format, 19..=22 | 44..=47);
|
||||
// Each plane contains all the mip levels and array slices. Depth and
|
||||
// stencil copies use separate formats and 512-byte row alignment.
|
||||
let (format, pitch_alignment) = match (depth_stencil, plane) {
|
||||
(true, 0) => (39, 512), // DXGI_FORMAT_R32_TYPELESS
|
||||
(true, 1) => (60, 512), // DXGI_FORMAT_R8_TYPELESS
|
||||
(false, 0) => (desc.format, PITCH),
|
||||
_ => return None,
|
||||
};
|
||||
let (element, block) = element(format)?;
|
||||
let width = (desc.width >> mip).max(1).next_multiple_of(block);
|
||||
let height = (u64::from(desc.height) >> mip)
|
||||
.max(1)
|
||||
@@ -733,18 +739,18 @@ fn subresource(desc: &ResourceDesc, index: u32) -> Option<(PlacedFootprint, u32,
|
||||
let row_size = width / block * element;
|
||||
let footprint = PlacedFootprint {
|
||||
offset: 0,
|
||||
format: desc.format,
|
||||
format,
|
||||
width: u32::try_from(width).ok()?,
|
||||
height: u32::try_from(height).ok()?,
|
||||
depth,
|
||||
row_pitch: u32::try_from(row_size.next_multiple_of(PITCH)).ok()?,
|
||||
row_pitch: u32::try_from(row_size.next_multiple_of(pitch_alignment)).ok()?,
|
||||
};
|
||||
Some((footprint, u32::try_from(height / block).ok()?, row_size))
|
||||
}
|
||||
|
||||
/// Device method: where each subresource goes in an upload buffer, rows
|
||||
/// 256-byte and subresources 512-byte aligned, as on PC. Unknown sizes give
|
||||
/// the documented all-ones values.
|
||||
/// Places subresources at 512-byte boundaries in an upload buffer.
|
||||
/// Row pitch is aligned to 512 bytes for depth/stencil planes and 256 bytes
|
||||
/// otherwise. Unknown sizes give the documented all-ones values.
|
||||
pub(crate) extern "system" fn copyable_footprints(
|
||||
_: This,
|
||||
desc: *const ResourceDesc,
|
||||
@@ -2559,6 +2565,22 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::object::slot;
|
||||
|
||||
#[test]
|
||||
fn a8_unorm_is_not_in_the_r8_typeless_family() {
|
||||
// DXGI_FORMAT values: 60 R8_TYPELESS, 61 R8_UNORM, 62 R8_UINT,
|
||||
// 63 R8_SNORM, 64 R8_SINT, 65 A8_UNORM. The R8 typeless family is
|
||||
// 60..=64; A8_UNORM has no typeless family and cannot be cast to R8,
|
||||
// so it must stand alone rather than fold into R8_TYPELESS.
|
||||
assert_eq!(family(60), 60);
|
||||
for f in 61..=64 {
|
||||
assert_eq!(family(f), 60);
|
||||
}
|
||||
assert_eq!(family(65), 65);
|
||||
// Boundaries: 59 belongs to the preceding family, 66 is unmapped.
|
||||
assert_eq!(family(59), 53);
|
||||
assert_eq!(family(66), 66);
|
||||
}
|
||||
|
||||
type Release = extern "system" fn(This) -> u32;
|
||||
type Map = extern "system" fn(This, u32, *const c_void, *mut *mut u8) -> HRESULT;
|
||||
type Address = extern "system" fn(This) -> u64;
|
||||
@@ -2790,6 +2812,55 @@ mod tests {
|
||||
assert_eq!(t, u64::MAX, "no second subresource");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn depth_stencil_footprints_follow_the_pc_plane_order() {
|
||||
// Native D3D12 reports the same layout for both depth/stencil families
|
||||
// and their view formats. Mips vary fastest, then array slices, then planes.
|
||||
let expected = [
|
||||
(512, 39, 16, 8),
|
||||
(4_608, 39, 8, 4),
|
||||
(6_656, 39, 16, 8),
|
||||
(10_752, 39, 8, 4),
|
||||
(12_800, 60, 16, 8),
|
||||
(16_896, 60, 8, 4),
|
||||
(18_944, 60, 16, 8),
|
||||
(23_040, 60, 8, 4),
|
||||
];
|
||||
for format in (19..=22).chain(44..=47) {
|
||||
let desc = ResourceDesc {
|
||||
depth_or_array_size: 2,
|
||||
..texture(16, 8, format, 2)
|
||||
};
|
||||
let mut layouts = [NO_FOOTPRINT; 8];
|
||||
let (mut rows, mut sizes, mut total) = ([0; 8], [0; 8], 0);
|
||||
copyable_footprints(
|
||||
std::ptr::null(),
|
||||
&desc,
|
||||
0,
|
||||
8,
|
||||
512,
|
||||
layouts.as_mut_ptr(),
|
||||
rows.as_mut_ptr(),
|
||||
sizes.as_mut_ptr(),
|
||||
&mut total,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
layouts.map(|l| (l.offset, l.format, l.width, l.height)),
|
||||
expected,
|
||||
"format {format}"
|
||||
);
|
||||
assert!(
|
||||
layouts.iter().all(|l| l.depth == 1 && l.row_pitch == 512),
|
||||
"format {format}"
|
||||
);
|
||||
assert_eq!(rows, [8, 4, 8, 4, 8, 4, 8, 4], "format {format}");
|
||||
assert_eq!(sizes, [64, 32, 64, 32, 16, 8, 16, 8], "format {format}");
|
||||
assert_eq!(total, 24_072, "format {format}");
|
||||
assert!(subresource(&desc, 8).is_none(), "format {format}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 4x4 texture filled from a title buffer through our list and queue,
|
||||
/// then read back from the host GPU.
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -47,30 +47,58 @@ impl Fields {
|
||||
} else {
|
||||
linear(self.min) << 4 | linear(self.mag) << 2 | u32::from(self.mip == 2)
|
||||
};
|
||||
let min_lod = finite_lod(self.min_lod, 0.0);
|
||||
// Without a mip filter the console clamps sampling to `min_lod`.
|
||||
let max_lod = if self.mip == 0 {
|
||||
min_lod
|
||||
} else {
|
||||
finite_lod(self.max_lod, min_lod).max(min_lod)
|
||||
};
|
||||
D3D12_SAMPLER_DESC {
|
||||
Filter: D3D12_FILTER((reduction << 7 | filter) as i32),
|
||||
AddressU: D3D12_TEXTURE_ADDRESS_MODE(self.address[0] as i32),
|
||||
AddressV: D3D12_TEXTURE_ADDRESS_MODE(self.address[1] as i32),
|
||||
AddressW: D3D12_TEXTURE_ADDRESS_MODE(self.address[2] as i32),
|
||||
MipLODBias: self.bias,
|
||||
AddressU: address_mode(self.address[0]),
|
||||
AddressV: address_mode(self.address[1]),
|
||||
AddressW: address_mode(self.address[2]),
|
||||
MipLODBias: if self.bias.is_nan() {
|
||||
0.0
|
||||
} else {
|
||||
self.bias
|
||||
.clamp(D3D12_MIP_LOD_BIAS_MIN, D3D12_MIP_LOD_BIAS_MAX)
|
||||
},
|
||||
MaxAnisotropy: if aniso {
|
||||
self.anisotropy.clamp(1, 16)
|
||||
} else {
|
||||
1
|
||||
},
|
||||
ComparisonFunc: D3D12_COMPARISON_FUNC(self.compare.max(1) as i32),
|
||||
BorderColor: self.border,
|
||||
MinLOD: self.min_lod,
|
||||
// Without a mip filter the console samples mip 0 only.
|
||||
MaxLOD: if self.mip == 0 {
|
||||
self.min_lod
|
||||
ComparisonFunc: if reduction == 1 {
|
||||
D3D12_COMPARISON_FUNC(self.compare as i32)
|
||||
} else {
|
||||
self.max_lod
|
||||
D3D12_COMPARISON_FUNC_NEVER
|
||||
},
|
||||
BorderColor: self.border,
|
||||
MinLOD: min_lod,
|
||||
MaxLOD: max_lod,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a console address mode (`1..=5`) to host D3D12, falling back to `CLAMP`.
|
||||
fn address_mode(mode: u32) -> D3D12_TEXTURE_ADDRESS_MODE {
|
||||
match mode {
|
||||
1..=5 => D3D12_TEXTURE_ADDRESS_MODE(mode as i32),
|
||||
_ => D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
|
||||
}
|
||||
}
|
||||
|
||||
/// Sanitizes an LOD bound for D3D12, substituting `fallback` for `NaN` and clamping infinities.
|
||||
fn finite_lod(value: f32, fallback: f32) -> f32 {
|
||||
if value.is_nan() {
|
||||
fallback
|
||||
} else {
|
||||
value.clamp(-D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX)
|
||||
}
|
||||
}
|
||||
|
||||
/// The console's sampler description (27 words): flags, magnification,
|
||||
/// minification, mip and depth filters, filter mode, three address modes,
|
||||
/// minimum and maximum LOD, LOD bias, secondary bias, anisotropy, its bias
|
||||
@@ -116,4 +144,86 @@ mod tests {
|
||||
w[16] = 1;
|
||||
assert_eq!(console(&w).Filter.0, 0x5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mip_none_clamps_to_min_lod_and_inverted_lod_range_clamps() {
|
||||
let mut w = [0u32; 27];
|
||||
w[3] = 0; // mip none
|
||||
w[9] = 3.0f32.to_bits();
|
||||
w[10] = 8.0f32.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!((d.MinLOD, d.MaxLOD), (3.0, 3.0));
|
||||
|
||||
w[9] = f32::NAN.to_bits();
|
||||
w[10] = 8.0f32.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!((d.MinLOD, d.MaxLOD), (0.0, 0.0));
|
||||
|
||||
w[9] = f32::INFINITY.to_bits();
|
||||
w[10] = 8.0f32.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!((d.MinLOD, d.MaxLOD), (D3D12_FLOAT32_MAX, D3D12_FLOAT32_MAX));
|
||||
|
||||
w[3] = 2; // linear mips
|
||||
w[9] = 4.0f32.to_bits();
|
||||
w[10] = 1.0f32.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!((d.MinLOD, d.MaxLOD), (4.0, 4.0));
|
||||
|
||||
w[9] = f32::NAN.to_bits();
|
||||
w[10] = f32::INFINITY.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!((d.MinLOD, d.MaxLOD), (0.0, D3D12_FLOAT32_MAX));
|
||||
|
||||
w[9] = 2.5f32.to_bits();
|
||||
w[10] = f32::NAN.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!((d.MinLOD, d.MaxLOD), (2.5, 2.5));
|
||||
|
||||
w[9] = f32::NEG_INFINITY.to_bits();
|
||||
w[10] = f32::NEG_INFINITY.to_bits();
|
||||
let d = console(&w);
|
||||
assert_eq!(
|
||||
(d.MinLOD, d.MaxLOD),
|
||||
(-D3D12_FLOAT32_MAX, -D3D12_FLOAT32_MAX)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bias_address_and_comparison_stay_in_host_bounds() {
|
||||
let mut w = [0u32; 27];
|
||||
w[6..9].copy_from_slice(&[0, 6, 3]);
|
||||
w[11] = 24.0f32.to_bits();
|
||||
w[16] = 99;
|
||||
let d = console(&w);
|
||||
assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MAX);
|
||||
assert_eq!(
|
||||
[d.AddressU, d.AddressV, d.AddressW],
|
||||
[D3D12_TEXTURE_ADDRESS_MODE_CLAMP; 3]
|
||||
);
|
||||
assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER);
|
||||
|
||||
w[11] = (-24.0f32).to_bits();
|
||||
w[5] = 1; // minimum reduction
|
||||
w[16] = 4; // less-or-equal, ignored when reduction != 1
|
||||
let d = console(&w);
|
||||
assert_eq!(d.MipLODBias, D3D12_MIP_LOD_BIAS_MIN);
|
||||
assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_NEVER);
|
||||
|
||||
w[11] = f32::NAN.to_bits();
|
||||
w[5] = 0; // plain mode, reduction == 1 from compare == 4
|
||||
w[6..9].copy_from_slice(&[1, 4, 5]);
|
||||
w[16] = 4;
|
||||
let d = console(&w);
|
||||
assert_eq!(d.MipLODBias, 0.0);
|
||||
assert_eq!(
|
||||
[d.AddressU, d.AddressV, d.AddressW],
|
||||
[
|
||||
D3D12_TEXTURE_ADDRESS_MODE_WRAP,
|
||||
D3D12_TEXTURE_ADDRESS_MODE_BORDER,
|
||||
D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE,
|
||||
]
|
||||
);
|
||||
assert_eq!(d.ComparisonFunc, D3D12_COMPARISON_FUNC_LESS_EQUAL);
|
||||
}
|
||||
}
|
||||
@@ -1776,6 +1776,7 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
|
||||
if crate::safecopy::on() {
|
||||
PUT[0].fetch_add(1, Ordering::Relaxed);
|
||||
PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed);
|
||||
let since = crate::watch::changes();
|
||||
// SAFETY: title memory; a page of it that is not there fails the
|
||||
// put, and the rest is put page by page.
|
||||
if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } {
|
||||
@@ -1784,8 +1785,14 @@ fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
|
||||
let mut from = 0;
|
||||
while from < merged.len() {
|
||||
let n = (4096 - (at + from) % 4096).min(merged.len() - from);
|
||||
let (was, now) = (&title[from..from + n], &merged[from..from + n]);
|
||||
// SAFETY: as above.
|
||||
unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) };
|
||||
let put = || unsafe { crate::safecopy::put_changed((at + from) as *mut u8, was, now) };
|
||||
// A page that is away only while the runtime changes a mapping
|
||||
// beside it gets its bytes when that is done.
|
||||
if !put() && !crate::watch::again_after_change(since, put) {
|
||||
crate::watch::lost("what shaders wrote", at + from, n);
|
||||
}
|
||||
from += n;
|
||||
}
|
||||
return merged.len();
|
||||
@@ -1829,7 +1836,35 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti
|
||||
|
||||
#[cfg(test)]
|
||||
mod merge_tests {
|
||||
use super::{changed_runs, dword_runs};
|
||||
use super::{changed_runs, dword_runs, put_changed};
|
||||
|
||||
/// What shaders wrote reaches a page that is away only while the runtime
|
||||
/// changes a mapping; a page that stays away loses it, and nothing else.
|
||||
#[test]
|
||||
fn a_put_waits_for_a_change_of_mapping() {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree,
|
||||
};
|
||||
// SAFETY: a reservation of ours, nothing of it committed.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), 1 << 16, MEM_RESERVE, PAGE_NOACCESS) } as usize;
|
||||
assert_ne!(at, 0);
|
||||
put_changed(at, &[0; 64], &[3; 64]);
|
||||
let (began, wait) = std::sync::mpsc::channel();
|
||||
let change = std::thread::spawn(move || {
|
||||
let _changing = crate::watch::title_memory_remapping();
|
||||
began.send(()).unwrap();
|
||||
std::thread::sleep(std::time::Duration::from_millis(50));
|
||||
// SAFETY: the reservation's first page.
|
||||
assert!(!unsafe { VirtualAlloc(at as _, 4096, MEM_COMMIT, PAGE_READWRITE) }.is_null());
|
||||
});
|
||||
wait.recv().unwrap();
|
||||
put_changed(at, &[0; 64], &[1; 64]);
|
||||
change.join().unwrap();
|
||||
// SAFETY: committed by now.
|
||||
assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 64) }, [1; 64]);
|
||||
// SAFETY: our reservation.
|
||||
unsafe { VirtualFree(at as _, 0, MEM_RELEASE) };
|
||||
}
|
||||
|
||||
/// Whole dwords around every changed byte and no other, whatever the
|
||||
/// alignment; small gaps joined only when asked.
|
||||
|
||||
@@ -1119,6 +1119,16 @@ pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
|
||||
}
|
||||
let start = at as usize;
|
||||
let end = start.saturating_add(len);
|
||||
// Streamed textures lie in views of physical pages, of which the runtime
|
||||
// knows which are there: one look, where the host was asked for every
|
||||
// 64 KiB of the texture (and once more for each that is not there).
|
||||
// `VICTORY_MAPPED_BY_VIEWS=0`: the host is asked, as before.
|
||||
static BY_VIEWS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0"))
|
||||
&& let Some(there) = crate::inplace::shown_bytes(start, len)
|
||||
{
|
||||
return there;
|
||||
}
|
||||
if !committed(at, 1) && !committed((end - 1) as *const u8, 1) {
|
||||
return 0;
|
||||
}
|
||||
@@ -1417,6 +1427,40 @@ mod allocation_costs {
|
||||
drop(all);
|
||||
}
|
||||
|
||||
/// What a look at how much of a texture is there costs: by questions to
|
||||
/// the host, and by the runtime's record of its views.
|
||||
#[test]
|
||||
#[ignore = "a measurement, not a check"]
|
||||
fn look_costs() {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
|
||||
const BLOCK: usize = 64 << 10;
|
||||
for (name, blocks, there) in [("350 KB, all there", 6, 6), ("22 MB, all there", 350, 350), ("22 MB, 1 MB there", 350, 16)] {
|
||||
let make = || {
|
||||
// SAFETY: a reservation of our own, of which the first part
|
||||
// is committed and touched.
|
||||
unsafe {
|
||||
let at = VirtualAlloc(std::ptr::null(), blocks * BLOCK, MEM_RESERVE, PAGE_READWRITE);
|
||||
VirtualAlloc(at, there * BLOCK, MEM_COMMIT, PAGE_READWRITE);
|
||||
std::ptr::write_bytes(at.cast::<u8>(), 1, there * BLOCK);
|
||||
at as usize
|
||||
}
|
||||
};
|
||||
let (asked, noted) = (make(), make());
|
||||
for block in 0..there {
|
||||
crate::title_memory_view(noted + block * BLOCK, BLOCK, 9, 0);
|
||||
}
|
||||
for (how, at) in [("asking the host", asked), ("by the views", noted)] {
|
||||
const N: u32 = 200;
|
||||
let began = std::time::Instant::now();
|
||||
for _ in 0..N {
|
||||
assert_eq!(super::mapped_bytes(at as *const u8, blocks * BLOCK), (there * BLOCK) as u64);
|
||||
}
|
||||
println!("{name}, {how}: {:.1} us a look", began.elapsed().as_secs_f64() * 1e6 / f64::from(N));
|
||||
}
|
||||
crate::inplace::views_gone(noted, blocks * BLOCK);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "a measurement, not a check"]
|
||||
fn allocation_costs() {
|
||||
|
||||
+617
-18
@@ -285,13 +285,15 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
|
||||
}
|
||||
ask_once_end();
|
||||
ask_ahead(ranges);
|
||||
ask_rest(ranges);
|
||||
}
|
||||
|
||||
/// [`ask_once`] after its [`ask_ahead`]: what that left to `writes`, and the
|
||||
/// asking stands.
|
||||
fn ask_rest(ranges: &[(usize, usize)]) {
|
||||
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
|
||||
@@ -313,7 +315,12 @@ pub(crate) fn ask_once(ranges: &[(usize, usize)]) {
|
||||
}
|
||||
}
|
||||
let mut j = journal_mut();
|
||||
let now = j.ahead_asked;
|
||||
// A number of its own, and the one this asking stands under: between
|
||||
// the two parts another thread may have asked about a range of the
|
||||
// second, copied it, and the title written it since. Under the first
|
||||
// part's number that write was older than the copy, and never copied.
|
||||
let now = next_asking();
|
||||
j.ahead_asked = now;
|
||||
j.written.extend(written.into_iter().map(|page| (page, now)));
|
||||
j.kept = !ahead.is_empty();
|
||||
j.ahead = ahead;
|
||||
@@ -781,6 +788,21 @@ struct Guards {
|
||||
absent: BTreeSet<usize>,
|
||||
/// Of those, the ones in placeholders ([`known_holes`]).
|
||||
held: BTreeSet<usize>,
|
||||
/// Blocks that were absent and turned out to be other memory than views
|
||||
/// when something was there again: never guarded, copied every time.
|
||||
foreign: BTreeSet<usize>,
|
||||
/// Blocks (first, past the last) the kernel writes now
|
||||
/// ([`kernel_writing`]), and blocks the runtime has unmapped in a change
|
||||
/// not yet done ([`title_memory_unmapping`]). Not in the sets above, and
|
||||
/// left as they are by [`guard`], which reports them written.
|
||||
kernel: Vec<(usize, usize)>,
|
||||
changing: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
impl Guards {
|
||||
fn left_alone(&self, block: usize) -> bool {
|
||||
self.kernel.iter().chain(&self.changing).any(|&(first, last)| (first..last).contains(&block))
|
||||
}
|
||||
}
|
||||
|
||||
static GUARDS: Mutex<Guards> = Mutex::new(Guards {
|
||||
@@ -788,6 +810,9 @@ static GUARDS: Mutex<Guards> = Mutex::new(Guards {
|
||||
clean: BTreeSet::new(),
|
||||
absent: BTreeSet::new(),
|
||||
held: BTreeSet::new(),
|
||||
foreign: BTreeSet::new(),
|
||||
kernel: Vec::new(),
|
||||
changing: Vec::new(),
|
||||
});
|
||||
|
||||
fn guards() -> std::sync::MutexGuard<'static, Guards> {
|
||||
@@ -948,7 +973,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
|
||||
}
|
||||
g.absent.range(first..last).filter(|block| !g.held.contains(block)).copied().collect()
|
||||
};
|
||||
let mut came: Vec<usize> = Vec::new();
|
||||
let mut came: Vec<(usize, bool)> = Vec::new();
|
||||
let mut uncommitted_until = first;
|
||||
for block in unsure {
|
||||
// One question for the blocks of a region.
|
||||
@@ -958,14 +983,18 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
|
||||
tally(9, 1);
|
||||
}
|
||||
if block >= uncommitted_until {
|
||||
came.push(block);
|
||||
// The hole may have been given up, and its address be the
|
||||
// title's heap's, or code's, now: not ours to guard.
|
||||
came.push((block, is_view(block * BLOCK, (block + 1) * BLOCK)));
|
||||
}
|
||||
}
|
||||
let mut g = guards_timed();
|
||||
#[cfg(feature = "diagnostics")]
|
||||
tally(4, 1);
|
||||
for block in &came {
|
||||
g.absent.remove(block);
|
||||
for &(block, view) in &came {
|
||||
if g.absent.remove(&block) && !view {
|
||||
g.foreign.insert(block);
|
||||
}
|
||||
}
|
||||
let mut written = Vec::new();
|
||||
let mut run: Option<usize> = None;
|
||||
@@ -986,7 +1015,7 @@ fn guard(start: usize, end: usize) -> Option<Vec<usize>> {
|
||||
if g.protected.contains(&block) {
|
||||
// Written through the runtime, still read-only.
|
||||
g.clean.insert(block);
|
||||
} else {
|
||||
} else if !g.foreign.contains(&block) && !g.left_alone(block) {
|
||||
run.get_or_insert(block);
|
||||
continue;
|
||||
}
|
||||
@@ -1046,13 +1075,13 @@ fn is_view(start: usize, end: usize) -> bool {
|
||||
/// block by block if they span views, leaving out any that fail, and
|
||||
/// noting those not committed (unmapped) absent.
|
||||
fn protect(g: &mut Guards, from: usize, to: usize) {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READONLY, VirtualProtect};
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
|
||||
let set = |from: usize, to: usize| {
|
||||
let mut old = 0;
|
||||
#[cfg(feature = "diagnostics")]
|
||||
let started = std::time::Instant::now();
|
||||
// SAFETY: title view memory; only its protection changes.
|
||||
let done = unsafe {
|
||||
let mut done = unsafe {
|
||||
VirtualProtect(
|
||||
(from * BLOCK) as *const _,
|
||||
(to - from) * BLOCK,
|
||||
@@ -1060,6 +1089,13 @@ fn protect(g: &mut Guards, from: usize, to: usize) {
|
||||
&mut old,
|
||||
) != 0
|
||||
};
|
||||
if done && !matches!(old, PAGE_READWRITE | PAGE_READONLY) {
|
||||
// What is there is not for us to guard (code, or memory the
|
||||
// title protects itself): as it was.
|
||||
// SAFETY: as above.
|
||||
unsafe { VirtualProtect((from * BLOCK) as *const _, (to - from) * BLOCK, old, &mut old) };
|
||||
done = false;
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
tally(5, (to - from) as u64);
|
||||
@@ -1118,7 +1154,7 @@ fn uncommitted_end(block: usize) -> usize {
|
||||
/// Gives write access back to the guarded blocks of `[start, end)` and
|
||||
/// notes them written; true if any was guarded.
|
||||
fn open(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect};
|
||||
use windows_sys::Win32::System::Memory::{PAGE_READONLY, PAGE_READWRITE, VirtualProtect};
|
||||
let blocks: Vec<usize> = g
|
||||
.protected
|
||||
.range(start / BLOCK..end.div_ceil(BLOCK))
|
||||
@@ -1133,7 +1169,15 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool {
|
||||
PUBLISHED.clear(block);
|
||||
let mut old = 0;
|
||||
// SAFETY: a block we made read-only.
|
||||
unsafe { VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) };
|
||||
unsafe {
|
||||
if VirtualProtect((block * BLOCK) as *const _, BLOCK, PAGE_READWRITE, &mut old) != 0
|
||||
&& !matches!(old, PAGE_READONLY | PAGE_READWRITE)
|
||||
{
|
||||
// Not what we left there: the address is other memory's
|
||||
// (code's, say), which keeps its protection.
|
||||
VirtualProtect((block * BLOCK) as *const _, BLOCK, old, &mut old);
|
||||
}
|
||||
}
|
||||
PROTECTED.clear(block);
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
@@ -1162,6 +1206,49 @@ pub fn writing(at: usize, len: usize) {
|
||||
crate::descriptor::host::remapped(at, len);
|
||||
}
|
||||
|
||||
/// The kernel writes title memory `[at, at + len)` until what this returns
|
||||
/// is dropped ([`kernel_writing`]).
|
||||
pub struct KernelWrite(usize, usize);
|
||||
|
||||
/// The runtime is about to have the kernel write title memory
|
||||
/// `[at, at + len)` (a file read): its guarded blocks are opened, as by
|
||||
/// [`writing`], and no refresh guards them again before what this returns is
|
||||
/// dropped, at the end of that call. One that did would make the kernel's
|
||||
/// write fail (the kernel does not fault into our handler): a read cut
|
||||
/// short, which the title takes for what the file holds.
|
||||
pub fn kernel_writing(at: usize, len: usize) -> KernelWrite {
|
||||
let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK));
|
||||
{
|
||||
let mut g = guards_timed();
|
||||
open(&mut g, at, at.saturating_add(len));
|
||||
if len != 0 {
|
||||
// Nothing known of them stands while they are left alone.
|
||||
let absent: Vec<usize> = g.absent.range(first..last).copied().collect();
|
||||
for block in absent {
|
||||
g.absent.remove(&block);
|
||||
if g.held.remove(&block) {
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
}
|
||||
g.kernel.push((first, last));
|
||||
}
|
||||
}
|
||||
crate::descriptor::host::remapped(at, len);
|
||||
KernelWrite(first, if len == 0 { first } else { last })
|
||||
}
|
||||
|
||||
impl Drop for KernelWrite {
|
||||
fn drop(&mut self) {
|
||||
if self.0 == self.1 {
|
||||
return;
|
||||
}
|
||||
let mut g = guards();
|
||||
if let Some(i) = g.kernel.iter().position(|&r| r == (self.0, self.1)) {
|
||||
g.kernel.swap_remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Held shared by a read of title memory in place, and alone by the runtime
|
||||
/// while it changes what title memory shows.
|
||||
///
|
||||
@@ -1181,12 +1268,149 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
/// ([`title_memory_remapping`]).
|
||||
pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>);
|
||||
|
||||
impl Drop for Remapping {
|
||||
fn drop(&mut self) {
|
||||
// The change is done: what is there now may be guarded.
|
||||
if CHANGING.replace((false, false)).1 {
|
||||
guards().changing.clear();
|
||||
}
|
||||
CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// How often the runtime began or ended a change of what title memory
|
||||
/// shows: odd while one is under way.
|
||||
static CHANGES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
thread_local! {
|
||||
/// This thread holds [`Remapping`]; and put blocks in
|
||||
/// [`Guards::changing`].
|
||||
static CHANGING: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, false)) };
|
||||
}
|
||||
|
||||
/// For [`again_after_change`]: to be asked before what may fail.
|
||||
pub(crate) fn changes() -> u64 {
|
||||
CHANGES.load(std::sync::atomic::Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// `f` failed to read or write title memory, at some time since [`changes`]
|
||||
/// said `since`. If the runtime changed a mapping in that time, the pages
|
||||
/// may have been away for that moment only ([`MAPPING`]): again, when the
|
||||
/// change is done. Whether `f` did it.
|
||||
pub(crate) fn again_after_change(since: u64, mut f: impl FnMut() -> bool) -> bool {
|
||||
let mut since = since;
|
||||
for _ in 0..4 {
|
||||
let now = change_done();
|
||||
if now == since {
|
||||
return false;
|
||||
}
|
||||
since = now;
|
||||
if f() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// [`changes`], when no change is under way (or one has been for a second).
|
||||
fn change_done() -> u64 {
|
||||
let mut tries = 0;
|
||||
let mut started = None;
|
||||
loop {
|
||||
let now = changes();
|
||||
if now.is_multiple_of(2) {
|
||||
return now;
|
||||
}
|
||||
tries += 1;
|
||||
if tries < 100 {
|
||||
std::hint::spin_loop();
|
||||
continue;
|
||||
}
|
||||
if started.get_or_insert_with(std::time::Instant::now).elapsed().as_secs() >= 1 {
|
||||
return now;
|
||||
}
|
||||
// SAFETY: gives the processor to another thread.
|
||||
unsafe { windows_sys::Win32::System::Threading::Sleep(u32::from(tries > 200)) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Faults of title threads that met a change of mapping and went on after
|
||||
/// it ([`came_back`]).
|
||||
static MET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// A title thread's access to `at` (`write`: a write) faulted. Whether it
|
||||
/// can be made now: if a change of mapping is under way, after it.
|
||||
///
|
||||
/// The console changes one page's mapping and no other's. Here the rest of
|
||||
/// a view is unmapped and mapped again ([`MAPPING`]), and a title thread that
|
||||
/// uses a page of it just then, which the title never gave up, faulted
|
||||
/// ("reserved, never committed", or read-only for the moment between our
|
||||
/// forgetting a guarded block and its unmapping). It waits here instead.
|
||||
/// Memory that is not there with no change under way is not waited for.
|
||||
fn came_back(at: usize, write: bool) -> bool {
|
||||
let there = || {
|
||||
if !write {
|
||||
return readable_view(at);
|
||||
}
|
||||
// (A refresh may have guarded the page that came back.)
|
||||
open(&mut guards(), at, at + 1) || writable(at)
|
||||
};
|
||||
let before = changes();
|
||||
if there() || again_after_change(before, there) {
|
||||
MET.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Whether `at` is in a committed page of a view that can be read.
|
||||
fn readable_view(at: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, PAGE_READONLY, PAGE_READWRITE, VirtualQuery,
|
||||
};
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let n = unsafe { VirtualQuery(at as *const _, &mut info, size_of_val(&info)) };
|
||||
n != 0
|
||||
&& info.State == MEM_COMMIT
|
||||
&& info.Type == MEM_MAPPED
|
||||
&& matches!(info.Protect, PAGE_READONLY | PAGE_READWRITE)
|
||||
}
|
||||
|
||||
/// Title memory that could not be written with what was to go there (what a
|
||||
/// shader wrote, a title's copy): counted, and said at the 1st, 2nd, 4th, 8th
|
||||
/// and so on. A page the title unmapped loses nothing by it; a page that is
|
||||
/// there does.
|
||||
pub(crate) fn lost(what: &'static str, at: usize, len: usize) {
|
||||
static LOST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
let n = LOST.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
|
||||
if n.is_power_of_two() {
|
||||
let there = writable(at);
|
||||
tracing::warn!(n, what, at = format_args!("{at:#x}"), len, there, "title memory not written");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// The runtime is about to map, unmap or move physical pages of title
|
||||
/// memory: until what it returns is dropped, no read of title memory in
|
||||
/// place is under way and none begins ([`title_memory_reading`]). Taken
|
||||
/// around the whole change, the unmapping and the mapping again.
|
||||
pub fn title_memory_remapping() -> Remapping {
|
||||
Remapping(MAPPING.write().unwrap_or_else(|e| e.into_inner()))
|
||||
// For the title's own threads ([`came_back`]).
|
||||
install();
|
||||
let met = MET.load(std::sync::atomic::Ordering::Relaxed);
|
||||
if met != 0 {
|
||||
static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
if met >= 2 * SAID.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
SAID.store(met, std::sync::atomic::Ordering::Relaxed);
|
||||
tracing::info!(met, "accesses of title threads that waited for a change of mapping");
|
||||
}
|
||||
}
|
||||
let changing = MAPPING.write().unwrap_or_else(|e| e.into_inner());
|
||||
CHANGES.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
CHANGING.set((true, false));
|
||||
Remapping(changing)
|
||||
}
|
||||
|
||||
/// What a read of title memory in place holds ([`title_memory_reading`]).
|
||||
@@ -1226,9 +1450,20 @@ pub fn title_memory_remapped(at: usize, len: usize) {
|
||||
}
|
||||
|
||||
/// The runtime is about to unmap title memory `[at, at + len)`: it is
|
||||
/// nothing of ours any more. Its protection goes with it.
|
||||
/// nothing of ours any more. Its protection goes with it. Until the change
|
||||
/// is done ([`Remapping`]) no refresh guards what is there: one that did
|
||||
/// before the unmapping would leave the address guarded, clean and known by
|
||||
/// its bits ([`PUBLISHED`]) with no view behind it.
|
||||
pub fn title_memory_unmapping(at: usize, len: usize) {
|
||||
let mut g = title_memory_changed(at, len);
|
||||
if CHANGING.get().0 && len != 0 {
|
||||
CHANGING.set((true, true));
|
||||
let (first, last) = (at / BLOCK, at.saturating_add(len).div_ceil(BLOCK));
|
||||
match g.changing.last_mut() {
|
||||
Some(before) if before.1 == first => before.1 = last,
|
||||
_ => g.changing.push((first, last)),
|
||||
}
|
||||
}
|
||||
let blocks: Vec<usize> = g
|
||||
.protected
|
||||
.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK))
|
||||
@@ -1242,6 +1477,61 @@ pub fn title_memory_unmapping(at: usize, len: usize) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The title is about to free or decommit memory of its own,
|
||||
/// `[at, at + len)`, or with no length the whole allocation at `at`: what
|
||||
/// was noted of its blocks (guarded, clean, absent) would be taken for true
|
||||
/// of the next memory at the address.
|
||||
pub fn title_memory_freed(at: usize, len: usize) {
|
||||
let mut g = guards();
|
||||
let first = at / BLOCK;
|
||||
let noted = [&g.protected, &g.absent, &g.foreign].map(|set| set.range(first..).next());
|
||||
let Some(noted) = noted.into_iter().flatten().min().copied() else {
|
||||
return;
|
||||
};
|
||||
let end = if len != 0 {
|
||||
at.saturating_add(len).div_ceil(BLOCK)
|
||||
} else {
|
||||
allocation_end(at, noted * BLOCK).div_ceil(BLOCK)
|
||||
};
|
||||
if noted >= end {
|
||||
return;
|
||||
}
|
||||
let absent: Vec<usize> = g.absent.range(first..end).copied().collect();
|
||||
for block in absent {
|
||||
g.absent.remove(&block);
|
||||
if g.held.remove(&block) {
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
}
|
||||
let foreign: Vec<usize> = g.foreign.range(first..end).copied().collect();
|
||||
for block in foreign {
|
||||
g.foreign.remove(&block);
|
||||
}
|
||||
// (Memory that is still a view is not freed by that call, which fails:
|
||||
// it must not stay read-only.)
|
||||
open(&mut g, at, end * BLOCK);
|
||||
}
|
||||
|
||||
/// The end of the allocation at `at`, if `inside` lies in it; else `at`.
|
||||
fn allocation_end(at: usize, inside: usize) -> usize {
|
||||
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
|
||||
let ask = |address: usize| {
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let n = unsafe { VirtualQuery(address as *const _, &mut info, size_of_val(&info)) };
|
||||
(n != 0 && info.AllocationBase as usize == at)
|
||||
.then(|| (info.BaseAddress as usize).saturating_add(info.RegionSize))
|
||||
};
|
||||
let mut end = at;
|
||||
let mut next = ask(inside.max(at));
|
||||
while let Some(to) = next {
|
||||
end = to;
|
||||
next = ask(to);
|
||||
}
|
||||
end
|
||||
}
|
||||
|
||||
/// Tells what keeps track of what title memory shows; the guards, with no
|
||||
/// block of the range known unmapped.
|
||||
fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static, Guards> {
|
||||
@@ -1254,13 +1544,17 @@ fn title_memory_changed(at: usize, len: usize) -> std::sync::MutexGuard<'static,
|
||||
crate::inplace::title_memory_freeing(at, len);
|
||||
let mut g = guards();
|
||||
let range = at / BLOCK..at.saturating_add(len).div_ceil(BLOCK);
|
||||
let absent: Vec<usize> = g.absent.range(range).copied().collect();
|
||||
let absent: Vec<usize> = g.absent.range(range.clone()).copied().collect();
|
||||
for block in absent {
|
||||
g.absent.remove(&block);
|
||||
if g.held.remove(&block) {
|
||||
PUBLISHED.clear(block);
|
||||
}
|
||||
}
|
||||
let foreign: Vec<usize> = g.foreign.range(range).copied().collect();
|
||||
for block in foreign {
|
||||
g.foreign.remove(&block);
|
||||
}
|
||||
g
|
||||
}
|
||||
|
||||
@@ -1275,6 +1569,7 @@ pub(crate) fn install() {
|
||||
unsafe extern "system" fn on_write(info: *mut EXCEPTION_POINTERS) -> i32 {
|
||||
// SAFETY: the system passes the exception being dispatched.
|
||||
let r = unsafe { &*(*info).ExceptionRecord };
|
||||
const READ: usize = 0;
|
||||
const WRITE: usize = 1;
|
||||
// A fault of our own copies (`crate::safecopy`): whatever it is, if
|
||||
// it is not a block we guard, the copy fails and goes on from there.
|
||||
@@ -1290,6 +1585,13 @@ pub(crate) fn install() {
|
||||
{
|
||||
return match ours {
|
||||
Some(exit) => fail(exit),
|
||||
None if r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION as NTSTATUS
|
||||
&& r.NumberParameters >= 2
|
||||
&& r.ExceptionInformation[0] == READ
|
||||
&& came_back(r.ExceptionInformation[1], false) =>
|
||||
{
|
||||
EXCEPTION_CONTINUE_EXECUTION
|
||||
}
|
||||
None => EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
}
|
||||
@@ -1306,8 +1608,11 @@ pub(crate) fn install() {
|
||||
if writable(at) {
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
// (The runtime wants the guards to end a change.)
|
||||
drop(g);
|
||||
match ours {
|
||||
Some(exit) => fail(exit),
|
||||
None if came_back(at, true) => EXCEPTION_CONTINUE_EXECUTION,
|
||||
None => EXCEPTION_CONTINUE_SEARCH,
|
||||
}
|
||||
}
|
||||
@@ -1434,6 +1739,299 @@ mod tests {
|
||||
};
|
||||
}
|
||||
|
||||
/// A placeholder of `blocks` blocks, each its own.
|
||||
fn placeholder(blocks: usize) -> usize {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_PRESERVE_PLACEHOLDER, MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, VirtualAlloc2,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
// SAFETY: a fresh placeholder, split.
|
||||
unsafe {
|
||||
let p = VirtualAlloc2(
|
||||
GetCurrentProcess(),
|
||||
std::ptr::null(),
|
||||
blocks * BLOCK,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
|
||||
PAGE_NOACCESS,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
) as usize;
|
||||
assert_ne!(p, 0);
|
||||
for block in 0..blocks - 1 {
|
||||
assert_ne!(
|
||||
VirtualFree((p + block * BLOCK) as *mut _, BLOCK, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER),
|
||||
0
|
||||
);
|
||||
}
|
||||
p
|
||||
}
|
||||
}
|
||||
|
||||
/// Private memory of `protect` in place of the placeholder of one block.
|
||||
fn private_at(at: usize, protect: u32) {
|
||||
use windows_sys::Win32::System::Memory::{MEM_REPLACE_PLACEHOLDER, VirtualAlloc2};
|
||||
// SAFETY: our placeholder.
|
||||
let got = unsafe {
|
||||
VirtualAlloc2(
|
||||
windows_sys::Win32::System::Threading::GetCurrentProcess(),
|
||||
at as *const _,
|
||||
BLOCK,
|
||||
MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER,
|
||||
protect,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert_eq!(got as usize, at);
|
||||
}
|
||||
|
||||
fn protection(at: usize) -> u32 {
|
||||
use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery};
|
||||
// SAFETY: plain data the query fills in.
|
||||
unsafe {
|
||||
let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
|
||||
VirtualQuery(at as *const _, &mut info, size_of_val(&info));
|
||||
info.Protect
|
||||
}
|
||||
}
|
||||
|
||||
/// A refresh between the opening of a kernel read's destination and the
|
||||
/// read itself leaves it open: the read lands, and is seen.
|
||||
#[test]
|
||||
fn a_refresh_leaves_open_what_the_kernel_is_writing() {
|
||||
use std::io::{Read, Seek, Write};
|
||||
use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
|
||||
// SAFETY: a pagefile section of two blocks, mapped read-write.
|
||||
let view = unsafe {
|
||||
let section = CreateFileMappingW(
|
||||
-1isize as _,
|
||||
std::ptr::null(),
|
||||
PAGE_READWRITE,
|
||||
0,
|
||||
(2 * BLOCK) as u32,
|
||||
std::ptr::null(),
|
||||
);
|
||||
assert!(!section.is_null());
|
||||
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, 2 * BLOCK)
|
||||
};
|
||||
let at = view.Value as usize;
|
||||
assert_ne!(at, 0);
|
||||
let pages = |block: usize| at / PAGE + block..at / PAGE + block + 1;
|
||||
assert!(writes(at, at + 2 * BLOCK, true).is_some());
|
||||
assert!(published(at, at + 2 * BLOCK) || !light());
|
||||
let mut file = tempfile::tempfile().unwrap();
|
||||
file.write_all(b"from the disk").unwrap();
|
||||
file.rewind().unwrap();
|
||||
let writing = kernel_writing(at + 100, 13);
|
||||
// The refresh: the block being written is new to it every time, and
|
||||
// stays open; the other is as it was.
|
||||
for _ in 0..2 {
|
||||
assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect()));
|
||||
let (now, found) = writes(at, at + BLOCK, true).expect("a view");
|
||||
assert!(found.contains(&(at / PAGE, now)));
|
||||
assert!(writable(at) && !writable(at + BLOCK));
|
||||
assert!(!published(at, at + BLOCK));
|
||||
}
|
||||
// SAFETY: 13 bytes of our view, nothing else refers to them.
|
||||
let into = unsafe { std::slice::from_raw_parts_mut((at + 100) as *mut u8, 13) };
|
||||
assert_eq!(file.read(into).expect("the kernel's write lands"), 13);
|
||||
assert_eq!(into, b"from the disk");
|
||||
drop(writing);
|
||||
// Seen by the next refresh, and guarded again.
|
||||
assert_eq!(guard(at, at + 2 * BLOCK), Some(pages(0).collect()));
|
||||
assert!(!writable(at));
|
||||
assert_eq!(guard(at, at + 2 * BLOCK), Some(Vec::new()));
|
||||
title_memory_unmapping(at, 2 * BLOCK);
|
||||
// SAFETY: our view.
|
||||
unsafe { UnmapViewOfFile(view) };
|
||||
}
|
||||
|
||||
/// A hole the kernel is to write is no known hole meanwhile, nor is one
|
||||
/// the runtime has begun to change; after that it is again.
|
||||
#[test]
|
||||
fn what_is_left_alone_is_no_known_hole() {
|
||||
let p = placeholder(3);
|
||||
let known = |block: usize| published(p + block * BLOCK, p + (block + 1) * BLOCK);
|
||||
let ask = || writes(p, p + 3 * BLOCK, true).expect("as a view");
|
||||
ask();
|
||||
let holes = known_holes();
|
||||
assert!((0..3).all(known) == holes);
|
||||
let writing = kernel_writing(p + BLOCK + 5, 100);
|
||||
for _ in 0..2 {
|
||||
assert!(known(0) == holes && !known(1) && known(2) == holes);
|
||||
let (now, written) = ask();
|
||||
assert!(written.contains(&(p / PAGE + 1, now)));
|
||||
assert!(written.iter().all(|w| w.0 == p / PAGE + 1 || w.1 < now));
|
||||
}
|
||||
assert!(!guards().held.contains(&(p / BLOCK + 1)));
|
||||
drop(writing);
|
||||
ask();
|
||||
assert!((0..3).all(known) == holes);
|
||||
{
|
||||
let _changing = title_memory_remapping();
|
||||
title_memory_unmapping(p, BLOCK);
|
||||
ask();
|
||||
assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
|
||||
}
|
||||
ask();
|
||||
assert!((0..3).all(known) == holes);
|
||||
title_memory_freed(p, BLOCK);
|
||||
assert!(!known(0) && !guards().held.contains(&(p / BLOCK)));
|
||||
title_memory_unmapping(p, 3 * BLOCK);
|
||||
// SAFETY: our placeholders.
|
||||
unsafe {
|
||||
for block in 0..3 {
|
||||
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A refresh during a change of mapping guards nothing the runtime has
|
||||
/// begun to unmap: no note of it stays behind.
|
||||
#[test]
|
||||
fn nothing_is_guarded_between_our_forgetting_it_and_its_unmapping() {
|
||||
use windows_sys::Win32::System::Memory::{CreateFileMappingW, FILE_MAP_WRITE, MapViewOfFile, UnmapViewOfFile};
|
||||
// SAFETY: a pagefile section of a block, mapped read-write.
|
||||
let view = unsafe {
|
||||
let section =
|
||||
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null());
|
||||
assert!(!section.is_null());
|
||||
MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, BLOCK)
|
||||
};
|
||||
let at = view.Value as usize;
|
||||
assert_ne!(at, 0);
|
||||
assert!(writes(at, at + BLOCK, true).is_some());
|
||||
let changing = title_memory_remapping();
|
||||
title_memory_unmapping(at, BLOCK);
|
||||
assert!(writes(at, at + BLOCK, true).is_some());
|
||||
{
|
||||
let g = guards();
|
||||
assert!(!g.protected.contains(&(at / BLOCK)) && !g.clean.contains(&(at / BLOCK)));
|
||||
}
|
||||
assert!(!published(at, at + BLOCK));
|
||||
// SAFETY: our view.
|
||||
unsafe { UnmapViewOfFile(view) };
|
||||
drop(changing);
|
||||
assert!(!guards().left_alone(at / BLOCK));
|
||||
}
|
||||
|
||||
/// Memory at an address where blocks were guarded or absent is not
|
||||
/// taken for them: code stays code, private memory is not guarded.
|
||||
#[test]
|
||||
fn other_memory_at_a_guarded_address_keeps_its_protection() {
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
CreateFileMappingW, MEM_PRESERVE_PLACEHOLDER, MEM_REPLACE_PLACEHOLDER, MapViewOfFile3, PAGE_EXECUTE_READ,
|
||||
PAGE_EXECUTE_READWRITE, UnmapViewOfFile2,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
let p = placeholder(3);
|
||||
// SAFETY: a section's block in place of the first placeholder.
|
||||
let view = unsafe {
|
||||
let section =
|
||||
CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, BLOCK as u32, std::ptr::null());
|
||||
assert!(!section.is_null());
|
||||
MapViewOfFile3(
|
||||
section,
|
||||
GetCurrentProcess(),
|
||||
p as *const _,
|
||||
0,
|
||||
BLOCK,
|
||||
MEM_REPLACE_PLACEHOLDER,
|
||||
PAGE_READWRITE,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
assert_eq!(view.Value as usize, p);
|
||||
// One block guarded, two absent.
|
||||
assert_eq!(guard(p, p + 3 * BLOCK).map(|w| w.len()), Some(3));
|
||||
// Not told of what comes: the view goes, code is there; and private
|
||||
// memory in the holes.
|
||||
// SAFETY: our view.
|
||||
assert_ne!(unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) }, 0);
|
||||
private_at(p, PAGE_EXECUTE_READ);
|
||||
private_at(p + BLOCK, PAGE_READWRITE);
|
||||
private_at(p + 2 * BLOCK, PAGE_EXECUTE_READWRITE);
|
||||
// (The runtime's allocations it tells of, or the holes stay known.)
|
||||
title_memory_allocated(p + BLOCK, 2 * BLOCK);
|
||||
let as_made = || {
|
||||
assert_eq!(protection(p), PAGE_EXECUTE_READ);
|
||||
assert_eq!(protection(p + BLOCK), PAGE_READWRITE);
|
||||
assert_eq!(protection(p + 2 * BLOCK), PAGE_EXECUTE_READWRITE);
|
||||
};
|
||||
let holes = [p / PAGE + 1, p / PAGE + 2];
|
||||
for _ in 0..2 {
|
||||
let written = guard(p, p + 3 * BLOCK).expect("as a view");
|
||||
assert!(holes.iter().all(|page| written.contains(page)), "copied every time");
|
||||
as_made();
|
||||
let g = guards();
|
||||
assert!(holes.iter().all(|block| !g.held.contains(block) && !g.absent.contains(block)));
|
||||
}
|
||||
writing(p, BLOCK);
|
||||
as_made();
|
||||
title_memory_unmapping(p, 3 * BLOCK);
|
||||
// SAFETY: our allocations.
|
||||
unsafe {
|
||||
for block in 0..3 {
|
||||
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Memory the title frees leaves no note of its blocks, whether it names
|
||||
/// its length or the allocation.
|
||||
#[test]
|
||||
fn freed_memory_leaves_no_notes() {
|
||||
let p = placeholder(3);
|
||||
let noted = |block: usize| {
|
||||
let g = guards();
|
||||
let block = p / BLOCK + block;
|
||||
g.protected.contains(&block) || g.clean.contains(&block) || g.absent.contains(&block)
|
||||
};
|
||||
assert!(guard(p, p + 3 * BLOCK).is_some());
|
||||
assert!(noted(0) && noted(1) && noted(2));
|
||||
// The middle allocation.
|
||||
title_memory_freed(p + BLOCK, 0);
|
||||
assert!(noted(0) && !noted(1) && noted(2));
|
||||
title_memory_freed(p, BLOCK);
|
||||
assert!(!noted(0) && noted(2));
|
||||
// Nothing noted there: nothing to do, and nothing beside it.
|
||||
title_memory_freed(p + BLOCK, 0);
|
||||
assert!(noted(2));
|
||||
title_memory_freed(p + 2 * BLOCK, 0);
|
||||
assert!(!noted(2));
|
||||
// SAFETY: our placeholders.
|
||||
unsafe {
|
||||
for block in 0..3 {
|
||||
VirtualFree((p + block * BLOCK) as *mut _, 0, MEM_RELEASE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A write between another thread's asking about a range and the second
|
||||
/// part of a submission's one asking is later than what that thread
|
||||
/// copied.
|
||||
#[test]
|
||||
fn the_rest_of_the_one_asking_has_a_number_of_its_own() {
|
||||
// SAFETY: a fresh write-watched allocation, freed at the end.
|
||||
let p = unsafe {
|
||||
VirtualAlloc(std::ptr::null(), 4 * PAGE, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE)
|
||||
} as usize;
|
||||
assert_ne!(p, 0);
|
||||
// One range: `ask_ahead` leaves it.
|
||||
let ranges = [(p, p + 4 * PAGE)];
|
||||
ask_ahead(&ranges);
|
||||
let (copied, _) = writes(p, p + 4 * PAGE, false).expect("watched");
|
||||
// SAFETY: committed pages of ours.
|
||||
unsafe { ((p + PAGE) as *mut u8).write_volatile(1) };
|
||||
ask_rest(&ranges);
|
||||
let last = journal().written.get(&(p / PAGE + 1)).copied();
|
||||
ask_once_end();
|
||||
assert!(last.is_some_and(|last| last > copied), "{last:?} is not after {copied}");
|
||||
// SAFETY: our allocation.
|
||||
unsafe { VirtualFree(p as *mut _, 0, MEM_RELEASE) };
|
||||
}
|
||||
|
||||
/// The runtime maps a view and then tells us; a copy's refresh on another
|
||||
/// thread can guard it in between. Told, it is the title's to write: a
|
||||
/// block left read-only and forgotten would be an access violation in
|
||||
@@ -1868,7 +2466,8 @@ mod many_askers_tests {
|
||||
// or past the guard.
|
||||
let word = at + page * PAGE + t * 8;
|
||||
// SAFETY (both): as above.
|
||||
let reading = (next(3) == 0).then(super::title_memory_reading_now).flatten();
|
||||
// (Waited for: other tests hold changes of mapping.)
|
||||
let reading = (next(3) == 0).then(super::title_memory_reading);
|
||||
let beside = reading.as_ref().and_then(|_| crate::inplace::beside(word, 8));
|
||||
if let Some(to) = beside {
|
||||
unsafe { (to as *mut u64).write_volatile(2) };
|
||||
|
||||
Reference in new issue
Block a user