Merge local/next into day/shaders; pipeline workers are all woken

Queue: passes over the screen first (local/next), then what draws asked
for, the early ones, and those known to take long by a quarter of the
workers. start() woke one worker, which could be one of the two that take
passes over the screen alone: the pipeline then waited for the next push.
All are woken now. victory warm goes through the pipelines no run drew with
in no order, 40 a process. victory translate: VICTORY_HOST_RDNA=1.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
localandClaude Opus 5.5 committed 2026-11-25 15:32:48 -06:00
commit 35bd011453
51 files changed
+7121 -558

No files matched your search

+6
View File
@@ -68,6 +68,7 @@ pub fn run(
// and their patched copy are not read again, and were held for the
// whole run (two blocks of 114.7 MB each for the title, in
// physical memory: run 65's memory map).
let image_name = prepared.file_name();
drop(prepared);
drop(original);
victory_hle::runtime::set_main_image(image.base());
@@ -162,6 +163,11 @@ pub fn run(
}
let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
show(&exe_name, image.bind_imports(&with_dlls, policy)?);
if execute {
let size = image.info().size_of_image as usize;
// SAFETY: the image stays mapped, and nothing of it has run yet.
unsafe { victory_loader::write_sites::apply_asked(&image_name, image.base(), size) };
}
if !execute {
println!("not executing (pass --execute to start the title)");
return Ok(());
+2
View File
@@ -250,6 +250,8 @@ pub fn run(
if let Some(n) = std::env::var("VICTORY_HOST_MAX_WAVE").ok().and_then(|v| v.parse().ok()) {
victory_shader::emit::set_host_max_wave(n);
}
// `VICTORY_HOST_RDNA=1`: as for an AMD RDNA card (`VICTORY_RDNA_FLOAT`).
victory_shader::emit::set_host_rdna(std::env::var_os("VICTORY_HOST_RDNA").is_some_and(|v| v == "1"));
let dll = validate.then(Validator::default_path).flatten();
if validate {
Validator::load(dll.as_deref()).map_err(anyhow::Error::msg)?;
+2 -2
View File
@@ -50,14 +50,14 @@ pub fn run(jobs: Option<usize>, limit: Option<usize>, again: bool, used: bool, t
let bad: HashSet<&str> = bad.lines().filter_map(|l| l.split(' ').next()).collect();
let early = std::fs::read_to_string(dir.join("early-pipelines.txt")).unwrap_or_default();
let early: HashSet<&str> = early.lines().collect();
// Those earlier runs drew with first.
// Those earlier runs drew with first, the others in no order (by key).
let mut all: Vec<usize> = (0..keys.len())
.filter(|&n| {
let key = keys[n].as_str();
(again || !done.contains(key)) && !bad.contains(key) && (!used || early.contains(key))
})
.collect();
all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), n));
all.sort_by_key(|&n| (!early.contains(keys[n].as_str()), &keys[n]));
all.truncate(limit.unwrap_or(usize::MAX));
let cores = std::thread::available_parallelism().map_or(4, |n| n.get());
let jobs = jobs.unwrap_or(cores * 2 / 3).max(1);
+1 -1
View File
@@ -30,7 +30,7 @@ diagnostics = []
workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading"] }
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
windows = { workspace = true, features = [
"Win32_Graphics_Direct3D",
"Win32_Graphics_Direct3D_Fxc",
+530
View File
@@ -0,0 +1,530 @@
//! A stand-in for the indirect light the title traces rays for.
//!
//! With the ray-tracing structure builder off (`crate::pipeline::builder_runs`)
//! the title's rays find nothing. Its program that resolves the diffuse light
//! of its screen probes (`CS_ScreenProbes_TemporalResolve_*`) then leaves the
//! sky's light outdoors, nothing indoors (walls are black where no lamp or
//! sun reaches) and, in blocks of the picture's tiles, what the probes'
//! memory held. Right after that program the light is raised to an estimate
//! and bounded by a multiple of it.
//!
//! That a stand-in can be put there, and in which of the program's images,
//! is beloooo's find (VIctory-Belobug-AMD, 06031237, 4f45ab88, cd9f78ce,
//! GPL-3.0-or-later), which puts a constant there, shaded in creases from the
//! scene's depth. The estimate here is worked out from the frame instead, so
//! it follows the hour, the room and its lamps by itself: the light the
//! visible surfaces send out (the title keeps it for its own screen traces:
//! `CS_CacheScreenSpaceRadiance`, the frame before) is averaged in 64x36
//! cells, and every point gets the mean of the cells weighted by the share of
//! its surroundings they cover, as a directional value (first-order harmonics
//! at 160x90 points, taken between them by depth).
//!
//! What it assumes: what is not on screen sends out what is (with a slow
//! mean of the last seconds, so that turning into a dark corner is not black
//! at once). No occlusion but the creases'.
//!
//! `VICTORY_AMBIENT`:
//! - unset or `0`/`off`: the title's own output.
//! - a number: that share of the estimate (1: all of it).
//! - `constant:<level>`: the constant, as beloooo's fork has it.
//!
//! `VICTORY_AMBIENT_SHADE=<strength>,<radius in metres>` sets the creases.
//!
//! The air of a room is lit by the same probes: without rays they hold the
//! sky's light indoors too, a brown veil at sunset. `VICTORY_AMBIENT_AIR`
//! bounds what the air scatters by a multiple of the light around.
use std::sync::{Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::s;
use crate::host::{HostList, host};
/// Programs of the title the stand-in follows.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum Role {
/// Resolves the diffuse light.
Resolve,
/// Keeps the light visible surfaces send out.
Radiance,
/// Adds the lamps' light to what the air scatters (the last program
/// that writes that volume before it is summed up along the view).
Air,
}
/// The program's part in this, by its name in the container.
pub(crate) fn role(container: &[u8]) -> Option<Role> {
let has = |name: &[u8]| container.windows(name.len()).any(|w| w == name);
if has(b"CS_ScreenProbes_TemporalResolve") {
Some(Role::Resolve)
} else if has(b"CS_CacheScreenSpaceRadiance") {
Some(Role::Radiance)
} else if has(b"CS_AccumulateLocalLightInscatteringVolume") {
Some(Role::Air)
} else {
None
}
}
/// Where the resolve writes the diffuse light (R9G9B9E5 as 32-bit integers)
/// and reads the scene's depth, and where the other writes the light of
/// visible surfaces: root parameter and place in its table, in dwords.
pub(crate) const LIGHT: (u8, u32) = (1, 176);
pub(crate) const DEPTH: (u8, u32) = (0, 464);
pub(crate) const RADIANCE: (u8, u32) = (1, 16);
/// Where the light the air scatters is.
pub(crate) const AIR: (u8, u32) = (1, 32);
#[derive(Clone, Copy, PartialEq, Debug)]
enum Set {
Off,
Estimate(f32),
Constant(f32),
}
fn parse(set: &str) -> Set {
let set = set.trim();
let number = |t: &str| t.trim().parse::<f32>().ok().filter(|v| v.is_finite() && *v > 0.0);
match set.strip_prefix("constant:") {
Some(level) => number(level).map_or(Set::Off, Set::Constant),
None => number(set).map_or(Set::Off, Set::Estimate),
}
}
fn set() -> Set {
static SET: OnceLock<Set> = OnceLock::new();
*SET.get_or_init(|| parse(&std::env::var("VICTORY_AMBIENT").unwrap_or_default()))
}
/// Whether the stand-in is on: set, and the title's rays find nothing.
pub(crate) fn on() -> bool {
set() != Set::Off && !crate::pipeline::builder_runs()
}
/// The most the air scatters, as a multiple of the light around
/// (`VICTORY_AMBIENT_AIR=<multiple>`; unset or 0: what the title has).
fn air() -> f32 {
static SET: OnceLock<f32> = OnceLock::new();
*SET.get_or_init(|| {
let set = std::env::var("VICTORY_AMBIENT_AIR").unwrap_or_default();
set.trim().parse().ok().filter(|v: &f32| v.is_finite() && *v > 0.0).unwrap_or(0.0)
})
}
/// Strength and radius of the creases' shade.
fn shade() -> [f32; 2] {
static SET: OnceLock<[f32; 2]> = OnceLock::new();
*SET.get_or_init(|| {
let mut shade = [1.0, 0.6];
let set = std::env::var("VICTORY_AMBIENT_SHADE").unwrap_or_default();
for (to, v) in shade.iter_mut().zip(set.split(',')) {
if let Ok(v) = v.trim().parse() {
*to = v;
}
}
shade
})
}
const SOURCE: &str = r#"
#define RS "RootConstants(num32BitConstants=12, b0), DescriptorTable(SRV(t0)), DescriptorTable(UAV(u0)), UAV(u1), UAV(u2)"
#define CX 64
#define CY 36
#define CELLS (CX * CY)
#define PX 160
#define PY 90
cbuffer Set : register(b0) {
float level; float constant; float strength; float radius;
float near; float tan_y; uint width; uint height;
float follow; float most; float air; float unused;
};
Texture2D<float> depth : register(t0);
// Cells: the light they send out (then, at CELLS, the slow mean), from
// CELLS + 1 on where they are.
RWStructuredBuffer<float4> cells : register(u1);
// Three a point: red, green and blue, each a mean and a direction.
RWStructuredBuffer<float4> points : register(u2);
static const float3 LUMA = float3(0.2126, 0.7152, 0.0722);
// The point seen at a texel, in metres from the eye (x right, y up, z away).
float3 seen(int2 p, float2 size) {
float d = depth.Load(int3(clamp(p, int2(0, 0), int2(size) - 1), 0));
float z = min(near / max(d, 1e-7), 1000.0);
float2 ndc = (float2(p) + 0.5) / size * 2.0 - 1.0;
return float3(ndc.x * tan_y * size.x / size.y * z, -ndc.y * tan_y * z, z);
}
#ifdef KEEP
RWTexture2D<float3> radiance : register(u0);
[RootSignature(RS)]
[numthreads(8, 4, 1)]
void keep(uint3 at : SV_DispatchThreadID) {
uint w, h;
radiance.GetDimensions(w, h);
float3 sum = 0;
for (uint y = 0; y < 5; y++) for (uint x = 0; x < 5; x++) {
uint2 p = uint2((float2(at.xy) + (float2(x, y) + 0.5) / 5.0) * float2(w, h) / float2(CX, CY));
float3 c = max(radiance[p], 0.0);
c = any(isnan(c)) || any(isinf(c)) ? 0.0 : c;
// Lamps and glints count, but not for everything.
sum += c / max(1.0, dot(c, LUMA) / 20.0);
}
cells[at.y * CX + at.x] = float4(sum / 25.0, 1.0);
}
[RootSignature(RS)]
[numthreads(1, 1, 1)]
void mean() {
float3 sum = 0;
for (uint i = 0; i < CELLS; i++) sum += cells[i].rgb;
float4 was = cells[CELLS];
float3 now = sum / CELLS;
cells[CELLS] = float4(was.a > 0.0 ? lerp(was.rgb, now, follow) : now, 1.0);
}
#endif
#ifdef PLACE
[RootSignature(RS)]
[numthreads(8, 4, 1)]
void place(uint3 at : SV_DispatchThreadID) {
float2 size = float2(width, height);
float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(CX, CY)), size);
cells[CELLS + 1 + at.y * CX + at.x] = float4(p, p.z * p.z);
}
#endif
#ifdef GATHER
[RootSignature(RS)]
[numthreads(8, 2, 1)]
void gather(uint3 at : SV_DispatchThreadID) {
float2 size = float2(width, height);
float3 p = seen(int2((float2(at.xy) + 0.5) * size / float2(PX, PY)), size);
float r2 = 0.25 + 0.0025 * p.z * p.z;
float whole = 0;
float3 toward = 0, light = 0, red = 0, green = 0, blue = 0;
for (uint i = 0; i < CELLS; i++) {
float4 c = cells[CELLS + 1 + i];
float3 L = cells[i].rgb;
float3 d = c.xyz - p;
float dd = dot(d, d);
float w = c.w / (dd + r2);
float3 dir = d / sqrt(dd + 0.25 * r2);
whole += w;
toward += w * dir;
light += w * L;
red += w * L.r * dir;
green += w * L.g * dir;
blue += w * L.b * dir;
}
whole = max(whole, 1e-6);
light /= whole;
toward /= whole;
uint at0 = (at.y * PX + at.x) * 3;
points[at0] = float4(red / whole - light.r * toward, light.r);
points[at0 + 1] = float4(green / whole - light.g * toward, light.g);
points[at0 + 2] = float4(blue / whole - light.b * toward, light.b);
}
#endif
#ifdef AIR
RWTexture3D<float3> scattered : register(u0);
// No more than a multiple of the light around: of the room as the last
// seconds showed it, and of the surface seen in this direction (towards a
// window the air outside may be as bright as the sky is).
[RootSignature(RS)]
[numthreads(8, 8, 2)]
void clear_air(uint3 at : SV_DispatchThreadID) {
uint w, h, d;
scattered.GetDimensions(w, h, d);
if (at.x >= w || at.y >= h || at.z >= d) return;
uint2 q = min(uint2((float2(at.xy) + 0.5) / float2(w, h) * float2(PX, PY)), uint2(PX - 1, PY - 1));
uint at0 = (q.y * PX + q.x) * 3;
float3 seen_there = float3(points[at0].w, points[at0 + 1].w, points[at0 + 2].w);
float far = float(at.z) / float(d);
float cap = air * lerp(dot(cells[CELLS].rgb, LUMA), dot(seen_there, LUMA), far);
float3 c = scattered[at];
float has = dot(c, LUMA);
if (has > cap) scattered[at] = c * (cap / has);
}
#endif
#ifdef RAISE
RWTexture2D<uint> light : register(u0);
float3 unpack(uint v) {
return float3(v & 511, (v >> 9) & 511, (v >> 18) & 511) * exp2(float(v >> 27) - 24.0);
}
uint pack(float3 c) {
c = clamp(c, 0.0, 65408.0);
float top = max(c.r, max(c.g, c.b));
int e = clamp(int(floor(log2(max(top, 1e-9)))) + 16, 0, 31);
float scale = exp2(float(24 - e));
if (top * scale >= 511.5) { e = min(e + 1, 31); scale = exp2(float(24 - e)); }
uint3 m = min(uint3(c * scale + 0.5), 511u);
return m.r | (m.g << 9) | (m.b << 18) | (uint(e) << 27);
}
[RootSignature(RS)]
[numthreads(8, 8, 1)]
void raise(uint3 at : SV_DispatchThreadID) {
float2 size = float2(width, height);
if (at.x >= width || at.y >= height) return;
int2 p = int2(at.xy);
float3 c = seen(p, size);
float3 l = seen(p + int2(-1, 0), size), r = seen(p + int2(1, 0), size);
float3 u = seen(p + int2(0, -1), size), d = seen(p + int2(0, 1), size);
float3 dx = abs(l.z - c.z) < abs(r.z - c.z) ? c - l : r - c;
float3 dy = abs(u.z - c.z) < abs(d.z - c.z) ? c - u : d - c;
float3 n = normalize(cross(dy, dx) + float3(0, 0, -1e-9));
if (dot(n, c) > 0.0) n = -n;
// How open it is (as in beloooo's cd9f78ce).
float open = 1.0;
float px = min(radius * size.y / (2.0 * tan_y * c.z), 128.0);
float noise = frac(52.9829189 * frac(dot(float2(p), float2(0.06711056, 0.00583715))));
if (strength > 0.0 && px >= 1.5 && c.z < 400.0) {
float sum = 0.0;
const int N = 12;
for (int i = 0; i < N; i++) {
float a = i * 2.399963 + noise * 6.2831853;
float2 o = float2(cos(a), sin(a)) * (sqrt((i + 0.5) / N) * px);
float3 v = seen(p + int2(round(o)), size) - c;
float vv = dot(v, v);
float over = dot(v, n) - 0.004 * c.z - 0.005;
sum += max(over, 0.0) / sqrt(vv + 1e-6) * saturate(1.0 - vv / (radius * radius));
}
open = saturate(1.0 - strength * 2.0 * sum / N);
}
float3 found;
if (constant > 0.0) {
found = float3(1.0, 0.98, 0.94) * constant * open;
light[p] = pack(found);
return;
}
// Between the four points around, those at its own depth first; which
// four is dithered a little.
float2 g = (float2(p) + 0.5) / size * float2(PX, PY) - 0.5 + (noise - 0.5) * 0.5;
int2 g0 = int2(floor(g));
float2 f = g - float2(g0);
float4 sr = 0, sg = 0, sb = 0;
float sum = 0;
for (int k = 0; k < 4; k++) {
int2 q = clamp(g0 + int2(k & 1, k >> 1), int2(0, 0), int2(PX, PY) - 1);
float z = seen(int2((float2(q) + 0.5) * size / float2(PX, PY)), size).z;
float2 b = float2(k & 1 ? f.x : 1 - f.x, k >> 1 ? f.y : 1 - f.y);
float w = (b.x * b.y + 1e-3) / (0.02 + abs(z - c.z) / c.z);
uint at0 = (q.y * PX + q.x) * 3;
sr += w * points[at0];
sg += w * points[at0 + 1];
sb += w * points[at0 + 2];
sum += w;
}
float3 all = float3(sr.w, sg.w, sb.w) / sum;
found = all + 1.2 * float3(dot(sr.xyz, n), dot(sg.xyz, n), dot(sb.xyz, n)) / sum;
found = clamp(found, 0.2 * all, 2.5 * all);
found = lerp(found, cells[CELLS].rgb, 0.2) * level * open;
float3 was = unpack(light[p]);
// What the program left counts as far as it can be true: the sky's light
// outdoors, not the blocks of other memory.
float top = max(dot(found, LUMA) * most, 1e-6);
float has = dot(was, LUMA);
was *= min(1.0, top / max(has, 1e-6));
light[p] = pack(max(was, found));
}
#endif
"#;
/// Bytes of the cells' buffer and of the points'.
const CELLS: u64 = 64 * 36;
const CELL_BYTES: u64 = (2 * CELLS + 1) * 16;
const POINT_BYTES: u64 = 160 * 90 * 48;
struct Pass {
root: ID3D12RootSignature,
keep: ID3D12PipelineState,
mean: ID3D12PipelineState,
place: ID3D12PipelineState,
gather: ID3D12PipelineState,
raise: ID3D12PipelineState,
air: ID3D12PipelineState,
cells: ID3D12Resource,
points: ID3D12Resource,
}
// SAFETY: D3D12 objects are free-threaded.
unsafe impl Send for Pass {}
// SAFETY: as above.
unsafe impl Sync for Pass {}
fn make(device: &ID3D12Device, buffer: impl Fn(u64) -> Option<ID3D12Resource>) -> windows::core::Result<Pass> {
let mut root: Option<ID3D12RootSignature> = None;
let mut pipeline = |part: &str, entry| -> windows::core::Result<ID3D12PipelineState> {
let code = crate::host::compile(&format!("#define {part}\n{SOURCE}"), entry, s!("cs_5_1"))?;
// SAFETY: the root signature is inside the shader; plain creations.
unsafe {
if root.is_none() {
root = Some(device.CreateRootSignature(0, &code)?);
}
let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE { pShaderBytecode: code.as_ptr().cast(), BytecodeLength: code.len() },
..Default::default()
};
device.CreateComputePipelineState(&desc)
}
};
let keep = pipeline("KEEP", s!("keep"))?;
let mean = pipeline("KEEP", s!("mean"))?;
let place = pipeline("PLACE", s!("place"))?;
let gather = pipeline("GATHER", s!("gather"))?;
let raise = pipeline("RAISE", s!("raise"))?;
let air = pipeline("AIR", s!("clear_air"))?;
let made = |bytes| buffer(bytes).ok_or_else(windows::core::Error::empty);
Ok(Pass {
root: root.ok_or_else(windows::core::Error::empty)?,
keep,
mean,
place,
gather,
raise,
air,
cells: made(CELL_BYTES)?,
points: made(POINT_BYTES)?,
})
}
fn pass() -> Option<&'static Pass> {
static PASS: OnceLock<Option<Pass>> = OnceLock::new();
PASS.get_or_init(|| {
let host = host()?;
make(&host.device, |bytes| host.uav_buffer(bytes))
.inspect_err(|e| tracing::warn!(error = %e, "no stand-in for the indirect light"))
.ok()
})
.as_ref()
}
fn uav_barrier(list: &ID3D12GraphicsCommandList) {
let barrier = D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, ..Default::default() };
// SAFETY: an open list; the barrier names no resource.
unsafe { list.ResourceBarrier(&[barrier]) };
}
/// Whether the light of a frame has been kept: the estimate has something
/// to begin with.
static KEPT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// What the passes read and write, as views in the heap the list has set.
pub(crate) struct Views {
/// The image the title's program just wrote.
pub(crate) image: D3D12_GPU_DESCRIPTOR_HANDLE,
/// The scene's depth, for [`Role::Resolve`].
pub(crate) depth: D3D12_GPU_DESCRIPTOR_HANDLE,
/// The size of the image, and how many slices it has.
pub(crate) size: [u32; 2],
pub(crate) slices: u32,
}
/// After the title's program of that role, in `list` with the program's view
/// heap set. Replaces the list's compute root signature and pipeline; false
/// if it recorded nothing.
pub(crate) fn after(list: &HostList, role: Role, views: &Views) -> bool {
use std::sync::atomic::Ordering;
let Some(pass) = pass() else {
return false;
};
let (level, constant) = match set() {
Set::Off => return false,
Set::Estimate(level) => (level, 0.0f32),
Set::Constant(level) => (0.0, level),
};
if role != Role::Radiance && constant == 0.0 && !KEPT.load(Ordering::Relaxed) {
return false;
}
if role == Role::Air && (constant > 0.0 || air() == 0.0) {
return false;
}
static SAID: Mutex<u32> = Mutex::new(0);
{
let mut said = SAID.lock().unwrap_or_else(|e| e.into_inner());
if *said < 4 {
*said += 1;
tracing::info!(?role, size = ?views.size, level, constant, "a stand-in for the indirect light");
}
}
list.keep(&pass.cells);
list.keep(&pass.points);
let [strength, radius] = shade();
let floats = [level, constant, strength, radius, 0.1, 0.45];
let mut words = [0u32; 12];
for (to, v) in words.iter_mut().zip(floats) {
*to = v.to_bits();
}
words[6] = views.size[0];
words[7] = views.size[1];
words[8] = 0.04f32.to_bits();
words[9] = 4.0f32.to_bits();
words[10] = air().to_bits();
let l = &list.list;
// SAFETY: an open list with the heap of the views set; the title's
// program has just used both views, so their textures are in the states
// these views need; buffers the list keeps.
unsafe {
uav_barrier(l);
l.SetComputeRootSignature(&pass.root);
l.SetComputeRoot32BitConstants(0, 12, words.as_ptr().cast(), 0);
l.SetComputeRootDescriptorTable(1, views.depth);
l.SetComputeRootDescriptorTable(2, views.image);
l.SetComputeRootUnorderedAccessView(3, pass.cells.GetGPUVirtualAddress());
l.SetComputeRootUnorderedAccessView(4, pass.points.GetGPUVirtualAddress());
let run = |pso: &ID3D12PipelineState, x, y, z| {
l.SetPipelineState(pso);
l.Dispatch(x, y, z);
uav_barrier(l);
};
match role {
Role::Radiance => {
run(&pass.keep, 8, 9, 1);
run(&pass.mean, 1, 1, 1);
KEPT.store(true, Ordering::Relaxed);
}
Role::Air => run(&pass.air, views.size[0].div_ceil(8), views.size[1].div_ceil(8), views.slices.div_ceil(2)),
Role::Resolve => {
if constant == 0.0 {
run(&pass.place, 8, 9, 1);
run(&pass.gather, 20, 45, 1);
}
run(&pass.raise, views.size[0].div_ceil(8), views.size[1].div_ceil(8), 1);
}
}
}
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn settings() {
assert_eq!(parse(""), Set::Off);
assert_eq!(parse("off"), Set::Off);
assert_eq!(parse("0"), Set::Off);
assert_eq!(parse("0.8"), Set::Estimate(0.8));
assert_eq!(parse("constant:0.3"), Set::Constant(0.3));
assert_eq!(parse("constant:nan"), Set::Off);
}
#[test]
fn roles_by_name() {
assert_eq!(role(b"..CS_ScreenProbes_TemporalResolve_a911b49c_Wrapped.."), Some(Role::Resolve));
assert_eq!(role(b"..CS_CacheScreenSpaceRadiance_eed2fc35.."), Some(Role::Radiance));
assert_eq!(role(b"CS_AccumulateLocalLightInscatteringVolume_7e2f5eef"), Some(Role::Air));
assert_eq!(role(b"CS_TemporalResolve"), None);
}
/// The passes compile with the system's compiler and the host takes them.
#[test]
fn the_passes_build() {
let Some(host) = host() else {
return;
};
make(&host.device, |bytes| host.uav_buffer(bytes)).expect("the passes");
}
}
+16 -1
View File
@@ -161,6 +161,13 @@ pub(crate) fn add(c: C, n: u64) {
COUNT[bank()].0[c as usize].fetch_add(n, Relaxed);
}
/// The counter, all sets together, as it is now (it goes back to 0 with
/// [`log`]).
pub(crate) fn peek(c: C) -> u64 {
let i = c as usize;
COUNT.iter().map(|b| b.0[i].load(Relaxed)).sum()
}
/// Counter `i`, all sets together, from now on 0.
fn taken(i: usize) -> u64 {
COUNT.iter().map(|b| b.0[i].swap(0, Relaxed)).sum()
@@ -491,7 +498,7 @@ mod own_tests {
/// The process's memory in bytes: in physical memory, and committed
/// (private bytes).
fn process_memory() -> (u64, u64) {
pub(crate) fn process_memory() -> (u64, u64) {
use windows_sys::Win32::System::ProcessStatus::{
K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,
};
@@ -1203,6 +1210,14 @@ pub(crate) fn log(frames: f64) {
"guards over several views of a page, since the start: {together} blocks guarded with their other views, \
{written} views opened by a write through another, {mapped} ranges opened because a view of them was mapped"
);
let [copies, blocks, opened, stores, unknown, full, stayed, copied_same] =
[0, 1, 2, 3, 4, 5, 6, 7].map(|n| crate::titlewrite::DONE[n].load(std::sync::atomic::Ordering::Relaxed));
tracing::info!(
"the title's writes beside the guards, since the start: {copies} copies (VICTORY_COPY_BESIDE=1), {blocks} blocks, {opened} opened; \
{stores} stores (VICTORY_STORE_BESIDE=1), {unknown} not understood, {full} blocks opened for too many; left out for changing nothing: {stayed} stores, {copied_same} parts of copies; \
the busiest stores (left out/changed): {}",
crate::titlewrite::busiest()
);
// Where the wall clock of a frame goes: the phases of a frame, the
// processor time of the whole process, and what each submitting and
// recording thread did.
+10 -1
View File
@@ -39,7 +39,10 @@ fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> {
}
/// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for
/// one by one; 2 (the default): the threads they share their work with too.
/// one by one; 2 (the default): the threads they share their work with too;
/// 3: those that work beside the rest as well (lists translated, descriptors
/// made): more threads by then than the fast cores run at a time, while the
/// slow ones stood idle.
fn stage() -> u32 {
static STAGE: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
*STAGE.get_or_init(|| std::env::var("VICTORY_FAST_CORES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2))
@@ -60,6 +63,12 @@ pub(crate) fn keep_helper_on_fast_cores(what: &str) {
ask(what, 2);
}
/// [`keep_on_fast_cores`] for one of many threads whose work is ahead of what
/// a frame waits for.
pub(crate) fn keep_many_on_fast_cores(what: &str) {
ask(what, 3);
}
fn ask(what: &str, from: u32) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
if stage() < from {
+57 -12
View File
@@ -301,6 +301,7 @@ pub(crate) fn sync_heaps() {
}
let started = std::time::Instant::now();
let (mut pages, mut looked, mut mirrored, mut tabled, mut later) = (0u64, 0u64, 0u64, 0u64, 0u64);
let mut kinds = [0u64; 6];
let mut page_bytes: Vec<u8> = Vec::new();
let mut changed: Vec<u32> = Vec::new();
let mut wait: Vec<u32> = Vec::new();
@@ -320,14 +321,23 @@ pub(crate) fn sync_heaps() {
let mirrored_count = heap.desc.count.min(host.count());
// The records of some frames ago that no draw read through a table
// since: a shader may pick them by index.
for index in host.copied_before(frame) {
if host.copied_tabled(index, frame) {
tabled += 1;
} else {
host.mirror(index, start + u64::from(index) * step, false);
mirrored += 1;
let before = host.copied_before(frame);
let of_tables = std::sync::atomic::AtomicU64::new(0);
crate::land::each_view(true, before.len().div_ceil(SYNC_AT_A_TIME), &|n| {
for &index in before.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() {
if host.copied_tabled(index, frame) {
of_tables.fetch_add(1, Relaxed);
} else {
host.mirror(index, start + u64::from(index) * step, false);
}
}
}
});
let of_tables = of_tables.into_inner();
tabled += of_tables;
mirrored += before.len() as u64 - of_tables;
kinds[4] += before.len() as u64 - of_tables;
// Those of the changed pages, made together at the end.
let mut make: Vec<u32> = Vec::new();
for (range_from, range_end) in written.take(start as usize, end as usize) {
let mut page = range_from & !(crate::watch::PAGE - 1);
while page < range_end {
@@ -378,13 +388,28 @@ pub(crate) fn sync_heaps() {
continue;
}
}
host.mirror(index, start + u64::from(index) * step, false);
make.push(index);
mirrored += 1;
kinds[if heap.samplers() {
3
} else if word(0) != VIEW_TAG {
0
} else if word(2) >> KIND_SHIFT == 0 {
1
} else {
2
}] += 1;
kinds[5] += u64::from(!heap.samplers() && host.near_tabled(index, frame));
}
}
page += crate::watch::PAGE;
}
}
crate::land::each_view(true, make.len().div_ceil(SYNC_AT_A_TIME), &|n| {
for &index in make.chunks(SYNC_AT_A_TIME).nth(n).unwrap_or_default() {
host.mirror(index, start + u64::from(index) * step, false);
}
});
if !wait.is_empty() {
host.copied_wait(frame, std::mem::take(&mut wait));
}
@@ -394,8 +419,20 @@ pub(crate) fn sync_heaps() {
for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, micros, tabled, later]) {
count.fetch_add(n, Relaxed);
}
for (count, n) in SYNCED_KINDS.iter().zip(kinds) {
count.fetch_add(n, Relaxed);
}
}
/// Of those mirrored, since the last frame line: no view, a view of an object,
/// another, a sampler; waited and no draw came; next to a slot of a table's.
#[cfg(windows)]
static SYNCED_KINDS: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
/// Records [`sync_heaps`] gives a thread at a time.
#[cfg(windows)]
const SYNC_AT_A_TIME: usize = 256;
/// Since the last frame line, of [`sync_heaps`]: changed pages of placed
/// shader-visible heaps looked at, slots on them, slots whose record was
/// not the one last seen and was mirrored, the microseconds it took; then
@@ -419,20 +456,28 @@ pub(crate) fn sync_line(frames: f64) {
);
}
let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
let kinds = [0, 1, 2, 3, 4, 5].map(|i| SYNCED_KINDS[i].swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames);
if pages == 0 {
return;
}
tracing::info!(
"descriptor records the title copied into its heap as bytes (VICTORY_HEAP_SYNC=0: not looked for): per frame \
{:.1} changed heap pages, {:.0} slots looked at, {:.1} whose record was new and was mirrored, {:.1} new ones of \
draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for)",
draws' tables left to the draws, {:.1} that waited for a draw first, {:.2} ms ({:.2} ms waited for); of the mirrored \
{:.0} no views, {:.0} of objects, {:.0} others, {:.0} samplers, {:.0} that waited and no draw came, {:.0} near a table's slot",
pages as f64 / frames,
looked as f64 / frames,
mirrored as f64 / frames,
tabled as f64 / frames,
later as f64 / frames,
micros as f64 / 1000.0 / frames,
waited as f64 / 1000.0 / frames
waited as f64 / 1000.0 / frames,
kinds[0],
kinds[1],
kinds[2],
kinds[3],
kinds[4],
kinds[5]
);
}
@@ -497,8 +542,8 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
}
/// Runs `f` with the host heap of the title's largest view heap, if there is
/// one (reports: nothing is waited for).
#[cfg(all(windows, feature = "diagnostics"))]
/// one (nothing is waited for).
#[cfg(windows)]
pub(crate) fn with_view_heap<T>(f: impl FnOnce(&host::HostHeap) -> T) -> Option<T> {
let heaps = SHADER_HEAPS.try_read().ok()?;
let host = heaps
+502 -87
View File
@@ -13,6 +13,104 @@ use windows::Win32::Graphics::Dxgi::Common::*;
use super::{VIEW_TAG, View, view_at};
use crate::host::host;
/// A set of a heap's slots, a bit for each: no lock (a pass that went through
/// a set of 70,000 under its lock kept everyone who writes slots waiting for
/// 5 ms of a frame, timeline thin-6).
struct Slots(Vec<std::sync::atomic::AtomicU64>);
impl Slots {
fn new(count: usize) -> Self {
let mut bits = Vec::new();
bits.resize_with(count.div_ceil(64), Default::default);
Slots(bits)
}
fn put(&self, slot: u32) {
if let Some(bits) = self.0.get(slot as usize / 64) {
bits.fetch_or(1 << (slot % 64), std::sync::atomic::Ordering::AcqRel);
}
}
/// Whether it was there.
fn remove(&self, slot: u32) -> bool {
use std::sync::atomic::Ordering::{AcqRel, Acquire};
let bit = 1 << (slot % 64);
self.0.get(slot as usize / 64).is_some_and(|bits| {
bits.load(Acquire) & bit != 0 && bits.fetch_and(!bit, AcqRel) & bit != 0
})
}
fn of(n: usize, mut bits: u64, out: &mut Vec<u32>, which: &impl Fn(u32) -> bool) {
while bits != 0 {
let slot = n as u32 * 64 + bits.trailing_zeros();
bits &= bits - 1;
if which(slot) {
out.push(slot);
}
}
}
/// Those that `which` says, in order.
fn all(&self, which: impl Fn(u32) -> bool) -> Vec<u32> {
let mut out = Vec::new();
for (n, bits) in self.0.iter().enumerate() {
Self::of(n, bits.load(std::sync::atomic::Ordering::Acquire), &mut out, &which);
}
out
}
/// All of them, and none is left.
fn take(&self) -> Vec<u32> {
use std::sync::atomic::Ordering::{AcqRel, Acquire};
let mut out = Vec::new();
for (n, bits) in self.0.iter().enumerate() {
if bits.load(Acquire) != 0 {
Self::of(n, bits.swap(0, AcqRel), &mut out, &|_| true);
}
}
out
}
}
/// The record each slot of a heap was last made from, and a lock for every
/// few hundredth of the slots: whoever makes a slot holds its lock, and no
/// other.
///
/// One lock for the heap was what everything of a frame waited for once the
/// lists were translated by threads of ours: half of what those did, two
/// thirds of the heaps' records and half of the pass over the buffer views
/// (profile thin-2).
struct Made {
keys: Vec<std::sync::atomic::AtomicU64>,
locks: [Mutex<()>; Self::LOCKS],
}
impl Made {
const LOCKS: usize = 512;
fn new(count: usize) -> Self {
let mut keys = Vec::new();
keys.resize_with(count, Default::default);
Made { keys, locks: [const { Mutex::new(()) }; Self::LOCKS] }
}
/// The lock slot `index` is made under. Neighbours have different ones.
fn lock(&self, index: u32) -> std::sync::MutexGuard<'_, ()> {
self.locks[index as usize % Self::LOCKS].lock().unwrap_or_else(|e| e.into_inner())
}
fn get(&self, index: u32) -> Option<u64> {
Some(self.keys.get(index as usize)?.load(std::sync::atomic::Ordering::Acquire))
}
/// Under the slot's lock.
fn set(&self, index: u32, key: u64) {
if let Some(k) = self.keys.get(index as usize) {
k.store(key, std::sync::atomic::Ordering::Release);
}
}
}
pub(crate) struct HostHeap {
pub(crate) heap: ID3D12DescriptorHeap,
cpu: usize,
@@ -33,7 +131,7 @@ pub(crate) struct HostHeap {
#[cfg(feature = "diagnostics")]
written: Vec<std::sync::atomic::AtomicU32>,
/// The record (view index and generation) each slot was last made from.
made: Mutex<Vec<u64>>,
made: Made,
/// The same for a slot whose descriptor is made and stays (else 0): what
/// [`HostHeap::mirror`] asks first, without the lock. Changed under it.
quick: Vec<std::sync::atomic::AtomicU64>,
@@ -84,10 +182,10 @@ pub(crate) struct HostHeap {
/// (and its memory a host copy) only when something reads it: a draw
/// through a table, or [`HostHeap::buffer_slots`] for shaders that pick
/// buffers from the whole heap.
buffers: Mutex<std::collections::BTreeSet<u32>>,
buffers: Slots,
/// Of those and of the slots that left the set: the ones written since
/// [`HostHeap::buffer_changes`] last took them.
changed: Mutex<std::collections::HashSet<u32>>,
changed: Slots,
/// Title slots holding a view of a texture the title may fill itself (a
/// placed texture, a texture object), with the frame from which they
/// are due: such a texture is uploaded when a draw reads it through a
@@ -326,6 +424,13 @@ fn neutral_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<ID3D12Res
static FLIPS: Mutex<Vec<Flip>> = Mutex::new(Vec::new());
/// Makes the slots whose new texture's upload has run
/// ([`HostHeap::texture_slots_flip`]); on any thread. Not if the heap is at
/// something else: the next texture pass does.
pub(crate) fn flip_now() {
let _ = super::with_view_heap(HostHeap::texture_slots_flip);
}
/// Since the start: slots made from their new view after its upload had run,
/// and those the title had written again by then.
pub(crate) static FLIPPED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
@@ -715,6 +820,20 @@ pub(crate) fn remapped(at: usize, len: usize) {
ranges.push((start, end));
}
/// Ranges of memory, those that touch made one (DexNom/VIctory 921d8d3b:
/// several threads map and write, some 5,000 ranges a frame, the same
/// textures' over and over, and each was looked up).
fn join(ranges: &mut Vec<(u64, u64)>) {
ranges.sort_unstable();
ranges.dedup_by(|next, last| {
if next.0 > last.1 {
return false;
}
last.1 = last.1.max(next.1);
true
});
}
/// Frames for which a slot a draw read through a table counts as a table's
/// slot ([`HostHeap::tabled`]).
const TABLED_FRAMES: u64 = 240;
@@ -998,6 +1117,17 @@ fn view_stride(view: &View) -> Option<u32> {
})
}
/// What else the table of strides says of a typed buffer view of an integer
/// format (`victory_shader::emit::VIEW_INTEGER`); 0 for any other view.
fn view_kind(view: &View) -> u32 {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
match view_elements(view) {
Some((0, false, 3 | 7 | 12 | 17 | 25 | 30 | 36 | 42 | 50 | 57 | 62)) => VIEW_INTEGER,
Some((0, false, 4 | 8 | 14 | 18 | 32 | 38 | 43 | 52 | 59 | 64)) => VIEW_INTEGER | VIEW_SIGNED,
_ => 0,
}
}
/// A buffer view's structure stride, whether it is raw, and its format;
/// `None` if `view` is not a buffer view.
fn view_elements(view: &View) -> Option<(u32, bool, u32)> {
@@ -1406,7 +1536,7 @@ impl HostHeap {
written: (0..if sampler || !crate::book::on() { 0 } else { size })
.map(|_| std::sync::atomic::AtomicU32::new(0))
.collect(),
made: Mutex::new(vec![0; count as usize]),
made: Made::new(count as usize),
quick: (0..count).map(|_| std::sync::atomic::AtomicU64::new(0)).collect(),
copied: Mutex::new(Vec::new()),
waiting: Mutex::default(),
@@ -1416,8 +1546,8 @@ impl HostHeap {
free: std::sync::atomic::AtomicU32::new(extra),
too_long: std::sync::atomic::AtomicU32::new(u32::MAX),
strides,
buffers: Mutex::default(),
changed: Mutex::default(),
buffers: Slots::new(count as usize),
changed: Slots::new(count as usize),
textures: Mutex::default(),
tabled: (0..if sampler { 0 } else { count })
.map(|_| std::sync::atomic::AtomicU32::new(0))
@@ -1693,10 +1823,11 @@ impl HostHeap {
pub(crate) fn texture_slots_remapped(&self, frame: u64) -> usize {
use std::sync::atomic::Ordering::Relaxed;
self.texture_slots_page_written(frame);
let ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
let mut ranges = std::mem::take(&mut *REMAPPED.lock().unwrap_or_else(|e| e.into_inner()));
if ranges.is_empty() {
return 0;
}
join(&mut ranges);
let mut slots: Vec<u32> = {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect()
@@ -1802,11 +1933,12 @@ impl HostHeap {
// from a view the host could not make (`make` gave nothing, the
// slot is null and keeps nothing). The host copy of such a
// texture is held by no slot, may have been let go, and would be
// made anew here, with the card full. `made` first, then `kept`,
// as `mirror` takes them.
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
made.get(index as usize).is_some_and(|&made| made != 0 && made == key)
&& self.kept_in(index).is_some()
// made anew here, with the card full.
if key == 0 || self.made.get(index) != Some(key) {
return false;
}
let _made = self.made.lock(index);
self.made.get(index) == Some(key) && self.kept_in(index).is_some()
}
/// Levels on demand (`crate::tiles`): makes again the host slots of the
@@ -1897,15 +2029,12 @@ impl HostHeap {
let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner());
starts.iter().flat_map(|&start| placed.slots_at(start)).collect()
};
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let mut remade = 0;
for slot in slots {
let Some(&key) = made.get(slot as usize) else {
let _made = self.made.lock(slot);
let Some(key) = self.made.get(slot).filter(|&key| key != 0) else {
continue;
};
if key == 0 {
continue;
}
let Some(view) = view_at(key as u32, (key >> 32) as u32) else {
continue;
};
@@ -1935,8 +2064,8 @@ impl HostHeap {
let wait = *WAIT.get_or_init(|| {
std::env::var("VICTORY_TEXTURE_AWAY_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(AWAY_MS)
});
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let Some(key) = made.get(index as usize).copied().filter(|&key| key != 0) else {
let _made = self.made.lock(index);
let Some(key) = self.made.get(index).filter(|&key| key != 0) else {
return false;
};
let now = crate::host::now_ms();
@@ -1954,7 +2083,7 @@ impl HostHeap {
}
}
}
self.unmake(&mut made, index);
self.unmake(index);
STALE[4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
true
}
@@ -1963,8 +2092,7 @@ impl HostHeap {
/// at `handle` views, by an earlier view of it.
pub(crate) fn texture_slot_shows_other(&self, index: u32, handle: u64) -> bool {
let key = record_key(handle);
let made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let Some(&shown) = made.get(index as usize) else {
let Some(shown) = self.made.get(index) else {
return false;
};
if key == 0 || shown == 0 || shown == key {
@@ -1986,40 +2114,64 @@ impl HostHeap {
/// `handle` views, or something else: until then it shows the neutral
/// texture ([`show_after`]).
pub(crate) fn texture_slot_show_after(&self, list: &crate::host::HostList, index: u32, handle: u64) {
if self.show_later(index, handle) {
self.flip(list, index, handle, Some(crate::frame::current()));
}
}
/// What slot `index` shows until the texture the record at `handle` views
/// is shown. False: it shows it, or there is none.
fn show_later(&self, index: u32, handle: u64) -> bool {
use std::sync::atomic::Ordering::Relaxed;
let key = record_key(handle);
let view = view_at(key as u32, (key >> 32) as u32);
let (true, Some(view)) = (key != 0, view) else {
return;
return false;
};
{
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let Some(&shown) = made.get(index as usize) else {
return;
let stale = {
let _made = self.made.lock(index);
let Some(shown) = self.made.get(index) else {
return false;
};
if shown == key {
return;
return false;
}
// (As `mirror`.)
for stale in self.note_buffer(index, Some(&view), true) {
if stale != index {
self.unmake(&mut made, stale);
}
}
let stale = self.note_buffer(index, Some(&view), true);
let old = view_at(shown as u32, (shown >> 32) as u32);
if shown == 0 || !old.is_some_and(|old| same_placed_texture(&old, &view)) {
let kept = old.is_some_and(|old| match kin(&old, &view) {
Kin::Same => true,
kin => kin.kept(keep_shown()),
});
if shown == 0 || !kept {
#[cfg(feature = "diagnostics")]
note_before(index, shown, "neutral");
self.quick_is(index, 0);
made[index as usize] = 0;
self.made.set(index, 0);
let kept = neutral_for(&view, self.at(index));
self.put(index);
self.clear_twin(index);
LATE[3].fetch_add(u64::from(kept.is_some()), Relaxed);
self.keep(index, kept);
}
stale
};
self.unmake_stale(index, stale);
true
}
/// [`HostHeap::texture_slot_show_after`] of a texture whose upload `job`
/// makes: shown when that has run.
pub(crate) fn texture_slot_show_ahead(&self, job: &crate::texture::ahead::Job, index: u32, handle: u64) {
if !self.show_later(index, handle) {
return;
}
self.flip(list, index, handle, Some(crate::frame::current()));
let (heap, key) = (std::ptr::from_ref(self) as usize, record_key(handle));
let late = Some(crate::frame::current());
job.then(move || {
let flip = Flip { after: 0, heap, index, handle, key, late };
FLIPS.lock().unwrap_or_else(|e| e.into_inner()).push(flip);
});
}
/// [`HostHeap::mirror`] of a slot whose table a draw read: a texture made
@@ -2033,6 +2185,7 @@ impl HostHeap {
&& let Some(View::Shader(resource, _)) = placed_texture(&view).or(Some(view))
&& crate::resource::buffer_bytes(resource as crate::object::This).is_none()
&& crate::resource::host_resource(resource as crate::object::This).is_some_and(crate::pool::fresh)
&& !crate::texture::ahead::there(resource as crate::object::This)
{
return self.texture_slot_show_after(list, index, handle);
}
@@ -2065,18 +2218,18 @@ impl HostHeap {
ready
};
let mut flipped = 0;
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
for f in ready {
let Some(shown) = made.get_mut(f.index as usize) else {
let _made = self.made.lock(f.index);
let Some(shown) = self.made.get(f.index) else {
continue;
};
if *shown == f.key {
if shown == f.key {
continue;
}
// Written again since, or made null: that write is in the queue.
// (A slot shown late is null until now.)
let view = view_at(f.key as u32, (f.key >> 32) as u32);
let there = *shown != 0 || f.late.is_some();
let there = shown != 0 || f.late.is_some();
let (true, true, Some(view)) = (f.key != 0 && record_key(f.handle) == f.key, there, view) else {
FLIPPED[1].fetch_add(1, Relaxed);
LATE[4].fetch_add(u64::from(f.late.is_some()), Relaxed);
@@ -2095,10 +2248,17 @@ impl HostHeap {
}
if let Some(kept) = make(&view, self.at(f.index)) {
#[cfg(feature = "diagnostics")]
note_before(f.index, *shown, if f.late.is_some() { "shown after its upload" } else { "flip" });
note_before(f.index, shown, if f.late.is_some() { "shown after its upload" } else { "flip" });
self.put(f.index);
*shown = f.key;
#[cfg(feature = "diagnostics")]
let was = shown;
self.quick_is(f.index, 0);
self.made.set(f.index, f.key);
self.keep(f.index, kept);
#[cfg(feature = "diagnostics")]
if f.late.is_some() && was != 0 {
same_bytes(was, f.key);
}
if let Some(since) = f.late {
let frames = crate::frame::current().saturating_sub(since);
let n = LATE[0].fetch_add(1, Relaxed) + 1;
@@ -2131,12 +2291,13 @@ impl HostHeap {
}
/// Makes host slot `index` null again, as it is before its view is
/// made: a null view of the kind it held.
fn unmake(&self, made: &mut [u64], index: u32) {
/// made: a null view of the kind it held. Under its lock ([`Made`]).
fn unmake(&self, index: u32) {
self.quick_is(index, 0);
let Some(key) = made.get_mut(index as usize).map(std::mem::take) else {
let Some(key) = self.made.get(index) else {
return;
};
self.made.set(index, 0);
if key == 0 {
return;
}
@@ -2149,6 +2310,21 @@ impl HostHeap {
self.keep(index, None);
}
/// The slots [`HostHeap::note_buffer`] found stale for slot `index`, with
/// what they were made from then, become null. None of their locks is
/// held here; one made from another record meanwhile is left as it is.
fn unmake_stale(&self, index: u32, stale: Vec<(u32, u64)>) {
for (slot, key) in stale {
if slot == index || key == 0 {
continue;
}
let _made = self.made.lock(slot);
if self.made.get(slot) == Some(key) {
self.unmake(slot);
}
}
}
/// Title slot `index` is a table's ([`HostHeap::tabled`]). `read`: a
/// draw read it through the table and brought what it views up to
/// date, so the slot leaves the queue of textures picked by index; the
@@ -2234,22 +2410,19 @@ impl HostHeap {
/// The title slots that hold buffer views.
pub(crate) fn buffer_slots(&self) -> Vec<u32> {
let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
buffers.iter().copied().collect()
self.buffers.all(|_| true)
}
/// Of [`HostHeap::buffer_slots`], those of one of `parts` parts: every
/// slot is in the same part each time.
pub(crate) fn buffer_slots_of(&self, part: u32, parts: u32) -> Vec<u32> {
let buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
buffers.iter().copied().filter(|slot| slot % parts == part).collect()
self.buffers.all(|slot| slot % parts == part)
}
/// The title slots whose buffer view was written, or went, since the
/// last call.
pub(crate) fn buffer_changes(&self) -> Vec<u32> {
let mut changed = self.changed.lock().unwrap_or_else(|e| e.into_inner());
std::mem::take(&mut *changed).into_iter().collect()
self.changed.take()
}
/// Records what title slot `index` now holds for shaders that pick
@@ -2258,9 +2431,11 @@ impl HostHeap {
/// `seen`: the slot was not written now, a draw or a pass made its
/// host slot from what it held.
/// Returns the title slots whose placed texture view the write made
/// stale ([`Spans`]): out of the queue of textures already, their host
/// slots are the caller's to make null (it holds `made`).
fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<u32> {
/// stale ([`Spans`]), each with the record its host slot is made from:
/// out of the queue of textures already, their host slots are the
/// caller's to make null when it has let go of its own slot's lock
/// ([`HostHeap::unmake_stale`]).
fn note_buffer(&self, index: u32, view: Option<&View>, seen: bool) -> Vec<(u32, u64)> {
if self.sampler {
return Vec::new();
}
@@ -2310,7 +2485,9 @@ impl HostHeap {
placed.rule = stale_rule();
let stale = placed.note(index, start, end, !seen);
placed.shows(index, first, held);
stale
// (Under the lock of `placed`: a later write of one of
// them comes by here before it makes the slot.)
stale.into_iter().map(|slot| (slot, self.made.get(slot).unwrap_or(0))).collect()
}
None => {
placed.forget(index);
@@ -2321,30 +2498,27 @@ impl HostHeap {
if !stale.is_empty() {
STALE[0].fetch_add(stale.len() as u64, std::sync::atomic::Ordering::Relaxed);
let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner());
for &slot in &stale {
for &(slot, _) in &stale {
textures.remove(slot);
}
}
let stride = view.and_then(view_stride);
let kind = view.map_or(0, view_kind);
if let Some((_, _, data)) = &self.strides
&& index < victory_shader::emit::SLOT_STRIDES_COUNT
{
// SAFETY: inside the mapping; shaders read it while we write (a
// dword, either value is one the slot had).
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) };
unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0) | kind) };
}
let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner());
let was = if stride.is_some() {
buffers.insert(index);
self.buffers.put(index);
true
} else {
buffers.remove(&index)
self.buffers.remove(index)
};
if was {
self.changed
.lock()
.unwrap_or_else(|e| e.into_inner())
.insert(index);
self.changed.put(index);
}
stale
}
@@ -2767,6 +2941,13 @@ impl HostHeap {
stamp != 0 && now.wrapping_sub(stamp) & !TABLED_READ <= COPIED_FRAMES
}
/// Whether a slot within 64 of `index` is a table's lately (counted for
/// the log: such a slot is likely one of a table not read yet).
pub(crate) fn near_tabled(&self, index: u32, frame: u64) -> bool {
let first = index & !63;
(first..first + 64).any(|i| i < self.count && self.copied_tabled(i, frame))
}
/// New records the title copied into slots `slots` in `frame` wait for
/// the draw that may read them through a table.
pub(crate) fn copied_wait(&self, frame: u64, slots: Vec<u32>) {
@@ -2821,14 +3002,15 @@ impl HostHeap {
{
return Some(view);
}
let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
let held = self.made.lock(index);
let shown = self.made.get(index).unwrap_or(0);
let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
let Some(view) = view else {
// Not a view of ours (never written, or of a resource the
// title released): nothing to read.
if made[index as usize] != 0 {
if shown != 0 {
self.quick_is(index, 0);
made[index as usize] = 0;
self.made.set(index, 0);
self.make_null(index);
let _ = self.note_buffer(index, None, false);
} else if for_draw {
@@ -2837,15 +3019,12 @@ impl HostHeap {
}
return None;
};
if made[index as usize] != key {
if shown != key {
// Views of other textures in the memory this one describes
// are stale: their host slots read nothing from here on, and
// let go of the host copies they held.
for stale in self.note_buffer(index, Some(&view), for_draw) {
if stale != index {
self.unmake(&mut made, stale);
}
}
// (When this slot's lock is let go: a lock at a time.)
let stale = self.note_buffer(index, Some(&view), for_draw);
// A view of a texture object that has no host copy yet waits
// for it, as buffer views wait for a draw: the slot is made
// when the texture is first used (`super::make_waiting`), or
@@ -2864,18 +3043,34 @@ impl HostHeap {
// time it got sharper.
if later
&& keep_views()
&& view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32)
.is_some_and(|old| same_placed_texture(&old, &view))
&& let Some(old) = view_at(shown as u32, (shown >> 32) as u32)
{
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
return Some(view);
let kin = kin(&old, &view);
if kin == Kin::Same {
KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
drop(held);
self.unmake_stale(index, stale);
return Some(view);
}
// And of another texture that can stand for it
// ([`keep_shown`]): black, then grey for a frame or two is
// what popped.
if is_texture_view(&old) {
let kept = kin.kept(keep_shown());
rewritten(kin, kept);
if kept {
drop(held);
self.unmake_stale(index, stale);
return Some(view);
}
}
}
#[cfg(feature = "diagnostics")]
if !self.sampler && is_texture_view(&view) {
note_before(index, made[index as usize], if later { "null, waits" } else { "at once" });
note_before(index, shown, if later { "null, waits" } else { "at once" });
}
self.quick_is(index, 0);
made[index as usize] = if later { 0 } else { key };
self.made.set(index, if later { 0 } else { key });
let kept = if later {
None
} else {
@@ -2889,7 +3084,9 @@ impl HostHeap {
}
self.twin_made(index, kept.is_some() && twinned(&view));
self.keep(index, kept.flatten());
self.quick_is(index, made[index as usize]);
self.quick_is(index, if later { 0 } else { key });
drop(held);
self.unmake_stale(index, stale);
}
Some(view)
}
@@ -2905,11 +3102,7 @@ impl HostHeap {
/// Whether slot `index` is backed by a made host descriptor (tests).
#[cfg(test)]
pub(crate) fn made(&self, index: u32) -> bool {
self.made
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(index as usize)
.is_some_and(|&key| key != 0)
self.made.get(index).is_some_and(|key| key != 0)
}
/// Whether host slot `index` shows `buffer`; `None` if it shows no
@@ -2944,7 +3137,7 @@ impl HostHeap {
/// a slot never made or left null.
#[cfg(feature = "diagnostics")]
pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
let key = self.made.get(index)?;
if key == 0 {
return Some("null".into());
}
@@ -3964,6 +4157,160 @@ fn keep_views() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_KEEP_VIEWS").is_none_or(|v| v != "0"))
}
/// What the texture view a slot is written with has to do with the one it
/// shows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kin {
/// A view of the same placed texture ([`same_placed_texture`]).
Same,
/// A texture of the same description placed elsewhere (moved, or one of
/// its kind).
Moved,
/// One of the same format and shape in another size: the same texture
/// with more or fewer levels, as a title streams it.
Sized,
/// A view of the same dimension, of another texture.
Other,
/// A view no shader that reads the one can read.
None,
}
impl Kin {
/// Whether the slot goes on showing what it shows, by [`keep_shown`].
fn kept(self, keep: u8) -> bool {
match self {
Kin::Same => true,
Kin::Moved | Kin::Sized => keep >= 1,
Kin::Other => keep >= 2,
Kin::None => false,
}
}
}
/// [`Kin`] of the view `old`, which a slot shows, and `new`.
fn kin(old: &View, new: &View) -> Kin {
if same_placed_texture(old, new) {
return Kin::Same;
}
if let (View::Placed(false, a, from), View::Placed(false, b, to)) = (old, new) {
if a[0] == 1 || b[0] == 1 || from[1] != to[1] {
return Kin::None;
}
// (Width, 64 bits, height, depth and levels, format: words 4 to 8.)
if a[0] == b[0] && a[2..13] == b[2..13] {
return Kin::Moved;
}
let (wide, high) = ([a[4], b[4]].map(u64::from), [a[6], b[6]].map(u64::from));
return if from[0] == to[0] && a[0] == b[0] && wide[0] * high[1] == wide[1] * high[0] {
Kin::Sized
} else {
Kin::Other
};
}
let dimension = |view: &View| match view {
View::Placed(false, resource, desc) if resource[0] != 1 => desc[1],
View::Shader(r, Some(desc)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => desc[1],
_ => 0,
};
match (dimension(old), dimension(new)) {
(0, _) | (_, 0) => Kin::None,
(a, b) if a == b => Kin::Other,
_ => Kin::None,
}
}
/// Whether a slot that is written with a view of another texture goes on
/// showing the one it shows until the new one is made and its upload has run
/// (`VICTORY_KEEP_SHOWN`): 0: never, it reads as zeros, then as the neutral
/// texture; 1: one of the same kind in another place or size; 2: any of the
/// same dimension.
fn keep_shown() -> u8 {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_KEEP_SHOWN") {
return if on { 2 } else { 0 };
}
static KEEP: std::sync::OnceLock<u8> = std::sync::OnceLock::new();
*KEEP.get_or_init(|| std::env::var("VICTORY_KEEP_SHOWN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(1))
}
/// Slots that showed a texture and were written with a view of another,
/// since the start, by [`Kin`] (moved, sized, other, none), and those of
/// them that kept what they showed.
static REWRITTEN: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];
fn rewritten(kin: Kin, kept: bool) {
use std::sync::atomic::Ordering::Relaxed;
let class = match kin {
Kin::Moved | Kin::Same => 0,
Kin::Sized => 1,
Kin::Other => 2,
Kin::None => 3,
};
REWRITTEN[class].fetch_add(1, Relaxed);
REWRITTEN[4].fetch_add(u64::from(kept), Relaxed);
let n: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
if n.is_multiple_of(5000) {
tracing::info!(
"slots that showed a texture and were written with another, since the start: {} of the same kind elsewhere, {} of another size, {} others, {} of another dimension; {} of them kept what they showed meanwhile (VICTORY_KEEP_SHOWN)",
REWRITTEN[0].load(Relaxed),
REWRITTEN[1].load(Relaxed),
REWRITTEN[2].load(Relaxed),
REWRITTEN[3].load(Relaxed),
REWRITTEN[4].load(Relaxed)
);
}
}
/// Diagnostics: whether a texture that a slot showed until its new one came
/// holds the new one's bytes (the title moved it), by the bytes their host
/// copies were filled from: equal, different, not known.
#[cfg(feature = "diagnostics")]
fn same_bytes(old: u64, new: u64) {
use std::sync::atomic::Ordering::Relaxed;
static SEEN: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6];
let view = |key: u64| view_at(key as u32, (key >> 32) as u32);
let (Some(old), Some(new)) = (view(old), view(new)) else {
return;
};
let held = |view: &View| {
let View::Placed(false, resource, desc) = view else {
return None;
};
let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
crate::resource::texture_held(crate::resource::texture_at_made(address, resource)?)
};
let class = match kin(&old, &new) {
Kin::Moved => 0,
Kin::Same | Kin::None => return,
_ => 3,
};
let which = match (held(&old), held(&new)) {
(Some(a), Some(b)) if a == b => 0,
(Some(a), Some(b)) if a.0 == b.0 => 1,
_ => 2,
};
SEEN[class + which].fetch_add(1, Relaxed);
let n: u64 = SEEN.iter().map(|n| n.load(Relaxed)).sum();
if n.is_multiple_of(1000) {
let seen: Vec<u64> = SEEN.iter().map(|n| n.load(Relaxed)).collect();
tracing::info!(
"slots that went on showing another texture until the new one came, since the start: of one of the same kind elsewhere {} had the new one's bytes, {} others, {} not known; of others {}, {}, {}",
seen[0], seen[1], seen[2], seen[3], seen[4], seen[5]
);
}
}
/// For `crate::popwatch`, since the start: slots made null as they were
/// written with another texture, such that kept the old one, slots given the
/// neutral texture, slots made null as their memory was another's.
#[cfg(feature = "diagnostics")]
pub(crate) fn pop_causes() -> [u64; 4] {
use std::sync::atomic::Ordering::Relaxed;
let all: u64 = REWRITTEN[..4].iter().map(|n| n.load(Relaxed)).sum();
let kept = REWRITTEN[4].load(Relaxed);
[all.saturating_sub(kept), kept, LATE[3].load(Relaxed), STALE[0].load(Relaxed)]
}
/// Whether a slot already made from its record is told so without the lock
/// (`VICTORY_QUICK_MIRROR=0`: with it, as before).
fn quick_mirror() -> bool {
@@ -4373,6 +4720,61 @@ mod tests {
assert!(!same_placed_texture(&low, &View::Shader(0, None)));
}
#[test]
fn ranges_that_touch_are_one() {
let mut ranges = vec![(40, 50), (30, 40), (35, 40), (10, 20), (45, 60), (60, 61), (1, 1)];
join(&mut ranges);
assert_eq!(ranges, [(1, 1), (10, 20), (30, 61)]);
join(&mut ranges);
assert_eq!(ranges.len(), 3);
}
/// Typed buffer views of integer formats are marked in the table of
/// strides; float, normalized, raw and structured ones are not.
#[test]
fn integer_typed_buffer_views_are_marked_in_the_table_of_strides() {
use victory_shader::emit::{VIEW_INTEGER, VIEW_SIGNED};
// Format, dimension (buffer), first element, count, stride, counter, flags.
let uav = |format, stride, flags| View::Unordered(0, 0, Some([format, 1, 0, 0, 64, stride, 0, 0, flags, 0]));
assert_eq!(view_kind(&uav(12, 0, 0)), VIEW_INTEGER, "R16G16B16A16_UINT");
assert_eq!(view_kind(&uav(59, 0, 0)), VIEW_INTEGER | VIEW_SIGNED, "R16_SINT");
assert_eq!(view_kind(&uav(10, 0, 0)), 0, "R16G16B16A16_FLOAT");
assert_eq!(view_kind(&uav(58, 0, 0)), 0, "R16_SNORM");
assert_eq!(view_kind(&uav(39, 0, 1)), 0, "raw");
assert_eq!(view_kind(&uav(0, 16, 0)), 0, "structured");
assert_eq!(view_stride(&uav(12, 0, 0)), Some(8));
}
/// What may stand for a texture that is not there yet: one of its kind in
/// another place or size; another one only if asked; nothing a shader
/// cannot read in its place.
#[test]
fn a_slot_shows_on_what_can_stand_for_its_new_texture() {
let texture = [3, 0, 0, 0, 512, 0, 256, 0x8_0001, 98, 1, 0, 0x105, 0, 0];
let view = |resource: [u32; 14], format: u32, dimension: u32, address: u32| {
let mut desc = [0u32; 16];
(desc[0], desc[1], desc[10], desc[11]) = (format, dimension, address, 0xb);
View::Placed(false, resource, desc)
};
let old = view(texture, 98, 4, 0x1000_0000);
let mut twice = texture;
(twice[4], twice[6], twice[7]) = (1024, 512, 0x9_0001);
let mut square = texture;
square[6] = 512;
let mut buffer = texture;
buffer[0] = 1;
assert_eq!(kin(&old, &view(texture, 98, 4, 0x1000_0000)), Kin::Same);
assert_eq!(kin(&old, &view(texture, 98, 4, 0x2000_0000)), Kin::Moved);
assert_eq!(kin(&old, &view(twice, 98, 4, 0x2000_0000)), Kin::Sized);
assert_eq!(kin(&old, &view(square, 98, 4, 0x2000_0000)), Kin::Other);
assert_eq!(kin(&old, &view(twice, 83, 4, 0x2000_0000)), Kin::Other);
assert_eq!(kin(&old, &view(texture, 98, 9, 0x2000_0000)), Kin::None);
assert_eq!(kin(&old, &view(buffer, 98, 1, 0x2000_0000)), Kin::None);
for (kin, kept) in [(Kin::Same, [true; 3]), (Kin::Moved, [false, true, true]), (Kin::Sized, [false, true, true]), (Kin::Other, [false, false, true]), (Kin::None, [false; 3])] {
assert_eq!([0, 1, 2].map(|keep| kin.kept(keep)), kept, "{kin:?}");
}
}
/// A constant buffer view larger than the host takes is cut to what it
/// takes: the device, which such a view removes, stays.
#[test]
@@ -4920,10 +5322,23 @@ mod tests {
assert_eq!(slots(50), []);
assert_eq!(slots(51), [1]);
// A wider texture written at the same address: slot 1 is stale.
assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [1]);
assert_eq!(heap.note_buffer(2, Some(&view(at, 128)), false), [(1, 0)]);
assert_eq!(slots(u64::MAX), [2]);
}
#[test]
fn a_set_of_slots_holds_what_was_put_in() {
let set = Slots::new(200);
for slot in [199, 0, 64, 63, 130, 64] {
set.put(slot);
}
assert_eq!(set.all(|_| true), [0, 63, 64, 130, 199]);
assert_eq!(set.all(|slot| slot % 2 == 0), [0, 64, 130]);
assert!(set.remove(64) && !set.remove(64) && !set.remove(5));
assert_eq!(set.take(), [0, 63, 130, 199]);
assert!(set.take().is_empty());
}
/// A slot a draw read through a table leaves the queue; the title's
/// next write of it waits for its draw, and is due after the grace
/// frames if none reads it.
+153 -34
View File
@@ -321,6 +321,10 @@ pub(crate) struct State {
/// report of a removed device, `crate::host::indirects`).
#[cfg(feature = "diagnostics")]
user: Vec<u32>,
/// The tables the last bind made afresh for a program the stand-in for
/// the indirect light follows (`crate::ambient`): root parameter, bytes
/// into the view heap.
ambient_tables: Vec<(u8, u32)>,
/// What the host list has: pipeline, root signature, heaps.
host_pipeline: usize,
/// Graphics, compute.
@@ -452,6 +456,12 @@ pub(crate) fn take_frame() -> Vec<String> {
std::mem::take(&mut *FRAME.lock().unwrap_or_else(|e| e.into_inner()))
}
/// The draws dropped since [`take_dropped`].
#[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
pub(crate) fn dropped_now() -> u64 {
DROPPED.load(Ordering::Relaxed)
}
/// Draws, mesh dispatches and dispatches recorded but not run on the host
/// (no host pipeline) since the last call.
pub(crate) fn take_dropped() -> u64 {
@@ -761,48 +771,66 @@ fn heap_buffer_pass(heap: &crate::descriptor::Heap, host: &crate::descriptor::ho
// Whether the device was there before the pass: a view that removes
// it is named below.
static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
let alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none();
let mut unordered = Vec::new();
for (n, &index) in slots.iter().enumerate() {
ranges.set(index, None);
/// The title's heap, for the threads that look.
struct Shared<'a>(&'a crate::descriptor::Heap);
// SAFETY: a heap is free-threaded (its methods are called by any thread of
// the title's), and it lives until all of them have looked.
unsafe impl Sync for Shared<'_> {}
impl Shared<'_> {
fn handle(&self, index: u32) -> Option<u64> {
self.0.handle(index)
}
}
let heap = Shared(heap);
// What a slot of the title's shows: its copy and range, and whether it is
// an unordered view.
let look = |index: u32| {
// A draw's table's: the draw brings what it reads up to date.
if host.copied_tabled(index, frame) {
continue;
}
let Some(handle) = heap.handle(index) else {
continue;
};
let Some(view) = host.mirror(index, handle, true) else {
continue;
};
// Every 64 views while the device lives (a cheap query).
if alive
&& n % 64 == 63
&& let Some(why) = crate::descriptor::host::device_removed()
{
alive = false;
GONE.store(true, Ordering::Relaxed);
let last: Vec<String> = slots[n - 63..=n]
.iter()
.filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}")))
.map(|s| s.chars().take(200).collect())
.collect();
tracing::error!(why, slot = index, "the host device went while buffer views of the heap were made; one of: {last:#?}");
crate::host::log_removal_context();
return None;
}
let view = host.mirror(index, heap.handle(index)?, true)?;
// The copy the slot shows (`buffer_copy`), not the one the
// view's range alone would find.
let Some((shadow, address, len)) = crate::descriptor::host::buffer_copy(&view) else {
continue;
};
let (shadow, address, len) = crate::descriptor::host::buffer_copy(&view)?;
#[cfg(feature = "diagnostics")]
if host.shows(index, &shadow.buffer) == Some(false) {
HEAP_VIEWS_ELSEWHERE.fetch_add(1, Ordering::Relaxed);
}
if crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav) {
unordered.push((shadow.clone(), address, address + len));
let written = crate::picked::on() && view_kind(&view) == Some(ResourceType::Uav);
Some(((shadow, address, address + len), written))
};
// Some slots at a time, on several threads.
const AT_A_TIME: usize = 256;
let parts: Vec<&[u32]> = slots.chunks(AT_A_TIME).collect();
let found: Vec<std::sync::OnceLock<Vec<_>>> = parts.iter().map(|_| Default::default()).collect();
crate::land::each_view(false, parts.len(), &|n| {
let looked: Vec<_> = parts[n].iter().map(|&index| (index, look(index))).collect();
// (After each piece while the device lives: a cheap query.)
if alive
&& let Some(why) = crate::descriptor::host::device_removed()
&& !GONE.swap(true, Ordering::Relaxed)
{
let last: Vec<String> = parts[n]
.iter()
.filter_map(|&i| crate::descriptor::view(heap.handle(i)?).map(|v| format!("{i}: {v:?}")))
.map(|s| s.chars().take(200).collect())
.collect();
tracing::error!(why, "the host device went while buffer views of the heap were made; perhaps one of: {last:#?}");
crate::host::log_removal_context();
}
ranges.set(index, Some((shadow, address, address + len)));
let _ = found[n].set(looked);
});
for (index, shows) in found.into_iter().filter_map(std::sync::OnceLock::into_inner).flatten() {
let range = shows.map(|(range, written)| {
if written {
unordered.push(range.clone());
}
range
});
ranges.set(index, range);
}
if crate::picked::on() {
crate::picked::shown(unordered, all);
@@ -1260,7 +1288,7 @@ impl State {
addresses.push(self.view_address(compute, u.slot, u.dword));
}
}
crate::memory::ready(list, heap, &addresses, &written, &constants, use_)
crate::memory::ready(list, heap, &addresses, &written, &constants, use_, t.threads)
}
/// The bound heap holding `handle`.
@@ -1449,6 +1477,10 @@ impl State {
once!("a draw whose descriptor table found no free slots is dropped");
return false;
}
if stage.shader.ambient.is_some() {
self.ambient_tables.clear();
self.ambient_tables.extend(made.iter().copied());
}
// What the shader stores through root views and raw addresses is
// copied back into title memory afterwards.
let writes = (t.stores || !write_skip())
@@ -2380,7 +2412,7 @@ impl State {
let _ = host.mirror(index, handle, true);
}
// Its bytes are in, or on the way there in a list before.
if late && texture.is_some_and(crate::pool::fresh) {
if late && texture.is_some_and(crate::pool::fresh) && !crate::texture::ahead::there(resource) {
if let Some(handle) = heap.handle(index) {
host.texture_slot_show_after(list, index, handle);
}
@@ -2398,7 +2430,27 @@ impl State {
}
continue;
}
if let Some(view) = &view {
// The first upload of a texture no list has used: on a queue of
// its own, and the slot shows it as soon as that has run.
let ahead = if late && !tabled && texture.is_some_and(crate::pool::fresh) {
crate::texture::ahead::take(resource, first, there.filter(|_| partly.is_none()).unwrap_or(u64::MAX))
} else {
None
};
if let Some(ahead) = &ahead {
use crate::texture::ahead::Taken;
let (Taken::New(job) | Taken::Known(job)) = ahead;
if let Some(handle) = heap.handle(index) {
host.texture_slot_show_ahead(job, index, handle);
}
if let Taken::New(job) = ahead {
crate::texture::ahead::send(job);
}
}
let late = late && ahead.is_none();
if let Some(view) = &view
&& ahead.is_none()
{
// (What was found mapped of it a moment ago is not asked
// again, unless the host copy may need more.)
crate::texture::PICKING.set(Some(there.filter(|_| partly.is_none()).unwrap_or(u64::MAX)));
@@ -2603,6 +2655,73 @@ impl State {
unsafe { list.list.Dispatch(x, y, z) };
self.buffers_written();
DISPATCHED.fetch_add(1, Ordering::Relaxed);
if let Some(role) = p.stages.first().and_then(|s| s.shader.ambient)
&& crate::ambient::on()
&& self.ambient(list, p, role)
{
self.host_pipeline = 0;
self.host_roots[1] = 0;
}
}
/// The stand-in for the indirect light after a dispatch of `p`
/// (`crate::ambient`). Whether it recorded anything.
fn ambient(&self, list: &HostList, p: &HostPipeline, role: crate::ambient::Role) -> bool {
use crate::ambient::{AIR, DEPTH, LIGHT, RADIANCE, Role, Views};
let Some(t) = p.stages.first().map(|s| s.translated()) else {
return false;
};
let Some(heap) = (self.heaps[0] != 0).then(|| crate::descriptor::heap(self.heaps[0] as This).host()).flatten()
else {
return false;
};
let entry = |kind: ResourceType, (slot, offset): (u8, u32)| {
t.used.iter().find(|u| {
u.kind == kind && u.root == RootType::Table && (u.slot, u.table_offset_dwords) == (slot, offset)
})?;
let Some(Root::Table(table)) = self.roots_ref(true).get(usize::from(slot)) else {
return None;
};
let resource = match crate::descriptor::view(table + u64::from(offset) * 4)? {
View::Shader(r, _) | View::Unordered(r, ..) => r,
_ => return None,
};
let start = match self.ambient_tables.iter().find(|m| m.0 == slot) {
Some(m) => m.1,
None => self.user_value(true, slot, RootType::Table, 0),
};
let host = crate::resource::host_resource(resource as This)?;
// SAFETY: a live resource.
let desc = unsafe { host.GetDesc() };
Some((desc, heap.gpu_handle((start + offset * 4) / 32)))
};
let at = match role {
Role::Resolve => LIGHT,
Role::Radiance => RADIANCE,
Role::Air => AIR,
};
let image = entry(ResourceType::Uav, at);
let depth = match role {
Role::Resolve => entry(ResourceType::Srv, DEPTH),
Role::Radiance | Role::Air => image,
};
let (Some((of, image)), Some((seen, depth))) = (image, depth) else {
once!(?role, "no stand-in for the indirect light: other tables");
return false;
};
// (R32_UINT holding R9G9B9E5; R11G11B10_FLOAT.)
let format = if role == Role::Resolve { 42 } else { 26 };
let volume = of.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D;
if of.Format.0 != format || (seen.Width, seen.Height) != (of.Width, of.Height) || volume != (role == Role::Air) {
once!(?role, format = of.Format.0, "no stand-in for the indirect light: another image");
return false;
}
crate::ambient::after(list, role, &Views {
image,
depth,
size: [of.Width as u32, of.Height],
slices: u32::from(of.DepthOrArraySize),
})
}
/// What a draw or dispatch runs, for the device-removed report
+113
View File
@@ -0,0 +1,113 @@
//! A book of the title's write faults on guarded view memory
//! (`VICTORY_FAULT_BOOK=<file>`; builds with diagnostics): which block, when
//! in the frame, what it waited for, and what else happened to the block
//! (taken by a refresh, asked about), for 40 frames from each of the times
//! `VICTORY_FAULT_BOOK_AT` gives (seconds after the start; 150,210,270 unless
//! given). Written as `<file>.<n>.bin`, records of 40 bytes: ticks of the
//! performance counter, two words, thread, what.
#![cfg(feature = "diagnostics")]
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::sync::{Mutex, OnceLock};
/// What a record is of.
#[derive(Clone, Copy)]
#[repr(u32)]
pub(crate) enum What {
/// A frame ended (a: its number).
Frame = 0,
/// A write fault opened block `a`; b: blocks opened with it (the upper
/// 32 bits), nanoseconds of waiting for the guards' lock; c: nanoseconds
/// with it.
Fault = 1,
/// Blocks `[a, b)` were found written, or never taken, and made read-only.
Taken = 2,
/// `[a, b)` was asked about and known unwritten by its bits.
Known = 3,
/// `[a, b)` was asked about block by block; c: how many were written.
Asked = 4,
/// We opened block `a` ourselves.
Ours = 5,
/// Another view of a page taken, block `a`, was made read-only.
Alias = 6,
/// A fault on block `a` that someone else had opened; b: nanoseconds.
Open = 7,
/// The instruction at `a` made the fault before (block `b`).
Site = 9,
/// A store (the instruction at `a`) was done beside the guard of block
/// `b`.
Stored = 10,
}
#[repr(C)]
#[derive(Clone, Copy)]
struct Record {
at: i64,
a: u64,
b: u64,
c: u64,
thread: u32,
what: u32,
}
static ON: AtomicBool = AtomicBool::new(false);
static BOOK: Mutex<Vec<Record>> = Mutex::new(Vec::new());
fn ticks() -> i64 {
let mut t = 0;
// SAFETY: an out pointer of the right size.
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut t) };
t
}
/// Whether records are kept now.
pub(crate) fn on() -> bool {
ON.load(Relaxed)
}
pub(crate) fn note(what: What, a: usize, b: usize, c: u64) {
if !on() {
return;
}
// SAFETY: a question about this thread.
let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() };
let record = Record { at: ticks(), a: a as u64, b: b as u64, c, thread, what: what as u32 };
BOOK.lock().unwrap_or_else(|e| e.into_inner()).push(record);
}
/// A frame ended.
pub(crate) fn frame() {
const FRAMES: u64 = 40;
static SETTINGS: OnceLock<Option<(String, Vec<u64>)>> = OnceLock::new();
static BEGAN: OnceLock<std::time::Instant> = OnceLock::new();
static LEFT: AtomicU64 = AtomicU64::new(0);
static MADE: AtomicU64 = AtomicU64::new(0);
let began = *BEGAN.get_or_init(std::time::Instant::now);
let Some((file, times)) = SETTINGS.get_or_init(|| {
let file = std::env::var("VICTORY_FAULT_BOOK").ok().filter(|f| !f.is_empty())?;
let times = std::env::var("VICTORY_FAULT_BOOK_AT").unwrap_or_else(|_| "150,210,270".into());
Some((file, times.split(',').filter_map(|t| t.trim().parse().ok()).collect()))
}) else {
return;
};
note(What::Frame, crate::frame::current() as usize, 0, 0);
if on() {
if LEFT.fetch_sub(1, Relaxed) > 1 {
return;
}
ON.store(false, Relaxed);
let records = std::mem::take(&mut *BOOK.lock().unwrap_or_else(|e| e.into_inner()));
let file = format!("{file}.{}.bin", MADE.fetch_add(1, Relaxed));
std::thread::spawn(move || {
// SAFETY: plain data, every byte of it written.
let bytes = unsafe { std::slice::from_raw_parts(records.as_ptr().cast::<u8>(), size_of_val(&records[..])) };
match std::fs::write(&file, bytes) {
Ok(()) => tracing::info!(file, records = records.len(), "book of faults written"),
Err(e) => tracing::warn!(file, %e, "book of faults not written"),
}
});
} else if times.get(MADE.load(Relaxed) as usize).is_some_and(|&t| began.elapsed().as_secs() >= t) {
LEFT.store(FRAMES, Relaxed);
ON.store(true, Relaxed);
}
}
+398 -39
View File
@@ -2985,6 +2985,87 @@ fn stale_under_flights(runs: &[&HostList]) -> Vec<(std::sync::Arc<crate::shadow:
spans
}
/// How many parts of submissions, and lists, the line's thread gives to the
/// host as one (`VICTORY_JOIN_PARTS=<n>`; off by default, 1; `VICTORY_JOIN_LISTS`,
/// 48).
///
/// The idea is fxceless/victory-fork's, commit 39731795 (GPL-3.0-or-later, as
/// this): the title's lists wait for memory values, which cuts a frame into
/// some 29 parts, each prepared on its own: the write watch asked, the heaps'
/// records, the title's bytes under the flights' writes, a list that sends
/// what changed and one that compares. (Run submit-1, the dorm, 12 of 28 parts
/// joined, eight at most: the thread works 51.4 ms a frame instead of 54.8, the
/// frame is 0.6 to 3 ms shorter.) What differs here: the parts are taken
/// off one queue's entries of the line (`crate::queue`), still go to the queue
/// in calls of their own, and everything they refresh is brought up to date in
/// front of the first ([`refresh_front`], without which a later part's title
/// bytes under an earlier part's declared writes would go missing).
pub(crate) fn joins() -> (usize, usize) {
if ahead_of_writes() { joins_asked() } else { (1, 1) }
}
fn joins_asked() -> (usize, usize) {
static MOST: OnceLock<(usize, usize)> = OnceLock::new();
let of = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<usize>().ok());
let (parts, lists) = *MOST.get_or_init(|| (of("VICTORY_JOIN_PARTS").unwrap_or(1).max(1), of("VICTORY_JOIN_LISTS").unwrap_or(48).max(1)));
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_JOIN_PARTS") {
return (if on { 8 } else { 1 }, lists);
}
(parts, lists)
}
/// Whether the part `next` can be prepared together with `ahead`, which goes
/// before it and has not been sent: nothing done on the CPU for it reads what
/// those give their shaders, write back or write when they are done, and it
/// changes no title memory that they read ([`Step::Copy`], [`Step::Run`]).
pub(crate) fn joinable<'a>(ahead: impl Iterator<Item = &'a HostList>, next: &[&HostList]) -> bool {
if next.iter().any(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Copy(..) | Step::Run(_)))) {
return false;
}
let ahead: Vec<&HostList> = ahead.collect();
let mut written: Vec<(usize, usize)> = declared_writes(&ahead).into_iter().flat_map(|(_, ranges)| ranges).collect();
for list in &ahead {
let deferred = list.deferred();
written.extend(deferred.writes.iter().map(|&(at, _, bytes)| (at, at + bytes)));
written.extend(deferred.backs.iter().map(|&(_, at, [row, rows, pitch])| (at, at + rows.saturating_sub(1) * pitch + row)));
}
let mut joined = Vec::new();
join_ranges(&mut joined, written);
blocked_by(&joined, next, false).is_none()
}
/// Whether a bottom-of-pipe write of `list` meets `wait`.
pub(crate) fn will_meet(list: &HostList, wait: &crate::list::ValueWait) -> bool {
let (address, bytes) = wait.place();
// The last write there says.
let deferred = list.deferred();
let last = deferred.writes.iter().rev().find(|(at, _, n)| *at < address + bytes && address < *at + *n);
matches!(last, Some((at, crate::queue::Written::Value(v), n)) if *at == address && *n >= bytes && wait.holds_for(*v))
}
/// Lists and the order they run in.
type Run<T> = (Vec<T>, Vec<usize>);
/// `order`'s first `cut` places and the rest, each with the lists they name;
/// as it was if a list is named on both sides.
fn split<T>(lists: Vec<T>, order: Vec<usize>, cut: usize) -> Result<[Run<T>; 2], Run<T>> {
let (first, second) = order.split_at(cut);
if first.is_empty() || second.is_empty() || first.iter().any(|i| second.contains(i)) {
return Err((lists, order));
}
let behind: Vec<bool> = (0..lists.len()).map(|i| second.contains(&i)).collect();
let place = |i: usize| behind[..i].iter().filter(|&&b| b == behind[i]).count();
let orders = [first, second].map(|half| half.iter().map(|&i| place(i)).collect::<Vec<_>>());
let mut halves: [Vec<T>; 2] = [Vec::new(), Vec::new()];
for (list, behind) in lists.into_iter().zip(&behind) {
halves[usize::from(*behind)].push(list);
}
let [a, b] = halves;
let [x, y] = orders;
Ok([(a, x), (b, y)])
}
/// A fence signal on a queue ([`late`]): goes behind the flights in the
/// air, if there are any, and is set when they are settled. Whether it
/// did; if not the caller sets the fence now.
@@ -3014,11 +3095,20 @@ pub(crate) fn late_signal(fence: usize, value: u64) -> bool {
/// the value in a way not known here (shaders, a timestamp, another
/// width), they are settled and memory is asked again.
pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
if let Some(met) = late_met_known(wait) {
return met;
}
settle_now(WHY_VALUE);
wait.met()
}
/// [`late_met`] without a wait for the card; `None`: it has to be waited for.
pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> Option<bool> {
let (address, bytes) = wait.place();
{
let line = line();
if line.line.is_empty() && line.in_hand.is_empty() {
return false;
return Some(false);
}
let mut unsure = touches(&line.written, address, address + bytes);
// (With the relay: first the writes of flights being landed.)
@@ -3034,18 +3124,17 @@ pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool {
crate::queue::Written::Value(v) if *at == address && *n >= bytes => {
if wait.holds_for(*v) {
LATE_STATS[13].fetch_add(1, Ordering::Relaxed);
return true;
return Some(true);
}
}
_ => unsure = true,
}
}
if !unsure {
return false;
return Some(false);
}
}
settle_now(WHY_VALUE);
wait.met()
None
}
/// Settles the flights in the air, if any ([`Host::settle`]), for reason
@@ -3508,12 +3597,16 @@ pub(crate) mod aside;
pub(crate) mod awake;
mod card_steps;
pub(crate) mod indirects;
#[cfg(feature = "diagnostics")]
mod panel;
mod place;
mod send;
pub(crate) use send::{goes_as_words, words_under};
#[cfg(feature = "diagnostics")]
pub(crate) mod spans;
mod torn;
#[cfg(feature = "diagnostics")]
mod traffic;
pub(crate) mod upcheck;
#[cfg(feature = "diagnostics")]
mod stamps;
@@ -4055,30 +4148,13 @@ impl Host {
/// `relay`).
/// `picked`: ranges that may be written too, and ranges to look at
/// (`crate::picked`).
fn card_before(&self, runs: &[&HostList], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
fn card_before(&self, declared: &[Declared], picked: &crate::picked::Ranges, flown: bool) -> Option<CardPlan> {
use std::sync::Arc;
if !crate::shadow::cards() {
return None;
}
// The ranges this submission's shaders may write, per copy.
let mut declared: Vec<(Arc<crate::shadow::Shadow>, Vec<(usize, usize)>)> = Vec::new();
for list in runs {
for step in &list.deferred().copies {
if let Step::GpuWrite(shadow, address, len) = step
&& shadow.carded()
{
let range = (*address, *address + *len);
match declared.iter_mut().find(|(s, _)| Arc::ptr_eq(s, shadow)) {
Some((_, ranges)) => {
if !ranges.contains(&range) {
ranges.push(range);
}
}
None => declared.push((shadow.clone(), vec![range])),
}
}
}
}
let declared: Vec<Declared> = declared.iter().filter(|(shadow, _)| shadow.carded()).cloned().collect();
let declared = if crate::picked::lands() { crate::picked::with(declared, &picked.written) } else { declared };
// (Of a copy with a declared range here, that says it.)
let looked: Vec<&crate::picked::Range> =
@@ -4151,6 +4227,8 @@ impl Host {
crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed);
}
crate::shadow::CARD_STATS[1].fetch_add(ranges.len() as u64, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
traffic::moved(traffic::UP, shadow.span(), ranges.iter().copied());
if own.is_none() && before.is_some() && !ranges.is_empty() {
sent.push(transition(
&shadow.buffer,
@@ -4494,6 +4572,10 @@ impl Host {
if let Some(check) = &check {
total = check.total;
}
#[cfg(feature = "diagnostics")]
for (shadow, lo, hi, _) in &pieces {
traffic::moved(traffic::FETCHED, shadow.span(), std::iter::once((*lo, *hi)));
}
// The sends these flights ran behind, all a fetch on the copy queue
// is known to have run behind.
let behind = plans.iter().map(|p| p.0.sent_as).max().unwrap_or(0);
@@ -4922,7 +5004,7 @@ impl Host {
pub(crate) fn execute(&self, runs: &[&HostList]) {
// Behind what the title's queues were given before it.
crate::queue::before_sync();
let _ = self.submit(runs, false);
let _ = self.submit(runs, &[], false);
}
/// A queue's submission with [`late`]: the host lists `lists`, taken
@@ -4932,14 +5014,39 @@ impl Host {
/// ([`late`] lists those points); their host lists are reset and kept
/// for reuse then, as a queue does for the lists it ran.
pub(crate) fn execute_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>) {
self.execute_parts(lists, order, &[]);
}
/// [`Host::execute_late`] of parts of submissions in one: another begins
/// at each place of `order` in `parts` ([`joins`]).
pub(crate) fn execute_parts(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) {
if order.is_empty() {
crate::list::recycle(lists, &order);
return;
}
late_threads();
if let Some(cut) = {
let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
card_steps::cut_for(&runs)
} {
match split(lists, order, cut) {
Ok([(lists, order), (more, behind)]) => {
let first: Vec<usize> = parts.iter().copied().filter(|&p| p < cut).collect();
let second: Vec<usize> = parts.iter().filter(|&&p| p > cut).map(|p| p - cut).collect();
self.execute_parts(lists, order, &first);
self.execute_parts(more, behind, &second);
}
Err((lists, order)) => self.send_late(lists, order, parts),
}
return;
}
self.send_late(lists, order, parts);
}
fn send_late(&self, lists: Vec<crate::list::Detached>, order: Vec<usize>, parts: &[usize]) {
let sent = {
let runs: Vec<&HostList> = order.iter().map(|&i| lists[i].host()).collect();
self.submit(&runs, true)
self.submit(&runs, parts, true)
};
let Some((mut submitted, sent)) = sent else {
// (Not reached: a submission sent ahead always comes back.)
@@ -4947,6 +5054,7 @@ impl Host {
return;
};
let told = !sent.writes.is_empty();
let sizes = crate::memory::asked_sizes(order.iter().map(|&i| lists[i].host()));
let most = {
let mut line = line();
let Line { line: items, written, lists: flying, target, .. } = &mut *line;
@@ -4969,6 +5077,8 @@ impl Host {
RELAY_MOVED.notify_one();
if told && !late_writes() {
self.settle(&mut submitted, WHY_WRITES);
} else if sizes {
self.settle(&mut submitted, WHY_READ);
} else if most && relay_exact() {
// Until there are fewer, not until there are none.
relay_wait(WHY_MOST, |line| line.lists < late_most());
@@ -4989,7 +5099,7 @@ impl Host {
/// it ran and was waited for after all.
fn execute_own(&self, list: &HostList) -> u64 {
late_threads();
let Some((submitted, sent)) = self.submit(&[list], true) else {
let Some((submitted, sent)) = self.submit(&[list], &[], true) else {
return 0;
};
let number = sent.number;
@@ -5211,7 +5321,11 @@ impl Host {
/// [`Host::execute_late`]: the lists are prepared and sent, and what is
/// to be done once they have run comes back with the submission lock
/// still held.
fn submit<'a>(&'a self, runs: &[&HostList], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
///
/// `parts`: the lists of `runs` at which another part begins
/// ([`joins`]): those go to the queue in calls of their own, one after the
/// other, as they would have.
fn submit<'a>(&'a self, runs: &[&HostList], parts: &[usize], late: bool) -> Option<(std::sync::MutexGuard<'a, u64>, Sent)> {
#[cfg(feature = "diagnostics")]
let called = std::time::Instant::now();
#[cfg(feature = "diagnostics")]
@@ -5264,6 +5378,7 @@ impl Host {
}
None => runs,
};
let parts: Vec<usize> = parts.iter().map(|&n| n + usize::from(own.is_some())).collect();
stage.next("submit: the sweep");
let behind = late && flying();
// Before this submission counts as started: what the sweep lets go
@@ -5359,7 +5474,9 @@ impl Host {
// What flights in the air may write.
let air = line().written.clone();
stage.next("submit: refreshes ahead of writes");
if ahead_of_writes() {
if refresh_front() {
batch.refresh_front(runs, &parts);
} else if ahead_of_writes() {
batch.refresh_ahead(runs, |list, i| own.as_ref().is_some_and(|own| own.takes(list, i)));
}
stage.next("submit: the lists' steps");
@@ -5406,7 +5523,8 @@ impl Host {
for (shadow, at, len) in &picked.written {
shadow.writing(*at, *len);
}
let card = self.card_before(runs, &picked, flown);
let declared = declared_writes(runs);
let card = self.card_before(&declared, &picked, flown);
// The sends are taken: from here on the references hold what the
// copies in the lists put.
for (shadow, at, bytes) in batch.placed.drain(..) {
@@ -5443,10 +5561,16 @@ impl Host {
if let Some([front, behind]) = self.span_lists() {
lists.insert(0, Some(front));
lists.push(Some(behind));
firsts.iter_mut().for_each(|first| *first += 1);
}
let cuts: Vec<usize> = parts.iter().filter_map(|&n| firsts.get(n).copied()).collect();
// SAFETY: closed lists; the fence is ours.
let signalled = unsafe {
self.queue.ExecuteCommandLists(&lists);
let mut from = 0;
for to in cuts.into_iter().chain([lists.len()]) {
self.queue.ExecuteCommandLists(&lists[from..to]);
from = to;
}
self.queue.Signal(&self.fence, *submitted)
};
awake::sent(&self.device);
@@ -5459,7 +5583,7 @@ impl Host {
}
#[cfg(feature = "diagnostics")]
split.part(5);
let back = crate::picked::with(declared_writes(runs), &picked.written);
let back = crate::picked::with(declared, &picked.written);
let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect();
SUBMISSION_US[0].fetch_add((prepared - started).saturating_sub(settled).as_micros() as u64, Ordering::Relaxed);
submitting(0, 0);
@@ -5584,7 +5708,7 @@ impl Host {
if let Some(card) = &card {
self.card_back(card, &mut submitted, &mut std::collections::HashSet::new());
}
let back = crate::picked::with(declared_writes(runs), &picked.written);
let back = crate::picked::with(declared, &picked.written);
hand_back(&back);
if let Some(card) = card {
self.card_done(card);
@@ -7221,6 +7345,9 @@ struct Batch {
/// Copies (by address) brought up to date ahead of the steps, and the
/// range (from, to) ([`Batch::refresh_ahead`]).
ahead: ByCopy<(usize, usize)>,
/// `ahead` holds everything the submission refreshes
/// ([`Batch::refresh_front`]).
front: bool,
}
/// Whether the copies that a submission's shaders write are brought up to
@@ -7234,6 +7361,73 @@ fn ahead_of_writes() -> bool {
*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_AHEAD").is_none_or(|v| v != "0") && wide_refresh() && crate::watch::light())
}
/// Whether everything a submission refreshes is brought up to date in one go,
/// on several threads, ahead of its steps (`VICTORY_REFRESH_FRONT=1`, and with
/// `VICTORY_JOIN_PARTS`, which needs it; else in groups where the steps ask
/// for it). Measured on its own at nothing (run submit-1: refreshes 17.1 ms a
/// frame without, 18.3 with).
///
/// A submission's refreshes were done in up to five groups one after the other
/// (the copies its shaders write, those between its steps, what is left),
/// each ending with the threads waiting for the last copy; and the submitting
/// thread went over all the steps once for each question it has (what to ask
/// about, what flights may write too, what shaders write). A refresh may come
/// earlier than its step: the title's bytes are the same until a step writes
/// title memory, and behind such a step everything is asked for again, as it
/// was.
fn refresh_front() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
ahead_of_writes() && (joins_asked().0 > 1 || *ON.get_or_init(|| crate::switch::on("VICTORY_REFRESH_FRONT")))
}
/// Per copy what is refreshed in front of a submission's steps, as
/// [`written_spans`]'s but of all copies, up to the copy's first write by
/// shaders in each part of the submission (`Touch::Part`: another begins).
/// What a part refreshes of a copy it has given to its shaders stays where it
/// stands: around what they write. What a later part refreshes is the
/// title's bytes of before either.
fn front_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize)> {
let mut at: ByCopy<usize> = ByCopy::default();
// (Copy, from, to), in the order they come, and the part that gave it to
// shaders last.
let mut spans: Vec<(usize, usize, usize)> = Vec::new();
let mut given: Vec<u32> = Vec::new();
let (mut part, mut last) = (1, usize::MAX);
for step in steps {
match step {
Touch::Refresh(copy, from, to) => {
// (Most come several times on end.)
let i = if spans.get(last).is_some_and(|s| s.0 == copy) {
last
} else {
*at.entry(copy).or_insert_with(|| {
spans.push((copy, usize::MAX, 0));
given.push(0);
spans.len() - 1
})
};
last = i;
if given[i] != part {
let span = &mut spans[i];
(span.1, span.2) = (span.1.min(from), span.2.max(to));
}
}
Touch::Write(copy) => {
let i = *at.entry(copy).or_insert_with(|| {
spans.push((copy, usize::MAX, 0));
given.push(0);
spans.len() - 1
});
given[i] = part;
}
Touch::Part => part += 1,
Touch::Title | Touch::Nothing => {}
}
}
spans.retain(|s| s.1 < s.2);
spans
}
/// What a step is to the copies' refreshes, for [`written_spans`].
enum Touch {
/// A refresh of a copy (by address), from, to.
@@ -7243,6 +7437,8 @@ enum Touch {
/// Title memory is written.
Title,
Nothing,
/// Another part of the submission begins.
Part,
}
/// Of `steps`, up to the first that writes title memory: the copies given to
@@ -7265,7 +7461,7 @@ fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize
}
}
Touch::Title => break,
Touch::Nothing => {}
Touch::Nothing | Touch::Part => {}
}
}
spans.into_iter().filter(|(_, s)| s.2).map(|(copy, (from, to, _))| (copy, from, to)).collect()
@@ -7273,7 +7469,47 @@ fn written_spans(steps: impl Iterator<Item = Touch>) -> Vec<(usize, usize, usize
#[cfg(test)]
mod written_spans_tests {
use super::{Touch, written_spans};
use super::{Touch, front_spans, split, written_spans};
#[test]
fn everything_is_refreshed_in_front_but_what_a_part_gave_its_shaders() {
use Touch::{Nothing, Part, Refresh, Title, Write};
let found = front_spans(
[
Refresh(1, 10, 20),
Refresh(1, 12, 25),
Refresh(2, 0, 5),
Nothing,
Write(1),
// (Around what the part's own shaders write.)
Refresh(1, 0, 100),
Write(3),
Refresh(3, 1, 2),
Title,
Refresh(4, 7, 9),
Part,
// The next part's bytes under the first one's writes.
Refresh(1, 30, 40),
Write(4),
Refresh(4, 0, 9),
]
.into_iter(),
);
assert_eq!(found, [(1, 10, 40), (2, 0, 5), (4, 7, 9)]);
}
#[test]
fn a_submission_is_cut_between_its_lists() {
// Lists c and e are in neither half's order: they go with the first.
let Ok([first, second]) = split(vec!['a', 'b', 'c', 'd', 'e'], vec![1, 3, 0], 1) else {
panic!("no list is named twice");
};
let run = |(lists, order): &(Vec<char>, Vec<usize>)| order.iter().map(|&i| lists[i]).collect::<String>();
assert_eq!((run(&first), run(&second)), ("b".into(), "da".into()));
assert_eq!(first.0.len() + second.0.len(), 5);
assert!(split(vec!['a', 'b'], vec![0, 1, 0], 2).is_err());
assert!(split(vec!['a', 'b'], vec![0, 1], 0).is_err());
}
#[test]
fn what_is_written_is_refreshed_ahead_up_to_its_write_and_to_title_writes() {
@@ -7354,8 +7590,11 @@ impl Batch {
/// Before shaders are given a range of `shadow`'s copy: its pending
/// refresh is done, the others stay pending.
fn flush_one(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>) {
// From here on it is refreshed around what the shaders write.
self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
// From here on it is refreshed around what the shaders write. (What
// is in front of all the steps was, up to here.)
if !self.front {
self.ahead.remove(&(std::sync::Arc::as_ptr(shadow) as usize));
}
let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else {
return;
};
@@ -7404,6 +7643,99 @@ impl Batch {
self.textures.clear();
}
/// Before the steps of `runs` ([`refresh_front`]), a new part of the
/// submission beginning at each of `parts`.
fn refresh_front(&mut self, runs: &[&HostList], parts: &[usize]) {
let mut copies: ByCopy<std::sync::Arc<crate::shadow::Shadow>> = ByCopy::default();
let mut due = Vec::new();
let mut touches = Vec::new();
for (n, list) in runs.iter().enumerate() {
if parts.contains(&n) {
touches.push(Touch::Part);
}
let mut last = 0;
for step in &list.deferred().copies {
match step {
Step::Refresh(shadow, at, len) => {
let key = std::sync::Arc::as_ptr(shadow) as usize;
if key != last {
copies.entry(key).or_insert_with(|| shadow.clone());
last = key;
}
touches.push(Touch::Refresh(key, *at, *at + *len));
}
Step::GpuWrite(shadow, ..) => touches.push(Touch::Write(std::sync::Arc::as_ptr(shadow) as usize)),
Step::Texture(staging) if wide_textures() => {
if self.texture_due(staging) {
due.push(staging.clone());
}
}
_ => {}
}
}
}
let spans: Vec<_> = front_spans(touches.into_iter())
.into_iter()
.filter_map(|(key, from, to)| Some((copies.remove(&key)?, from, to)))
.collect();
self.front = true;
for (shadow, from, to) in &spans {
self.ahead.insert(std::sync::Arc::as_ptr(shadow) as usize, (*from, *to));
}
#[cfg(feature = "diagnostics")]
{
FLUSHES[0].fetch_add(1, Ordering::Relaxed);
FLUSHES[1].fetch_add(spans.len() as u64, Ordering::Relaxed);
}
let _flush = crate::timeline::span("refreshes of copies");
let started = std::time::Instant::now();
let before = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed));
// Those known to copy nothing are said so here, unless they are very
// many: then beside the others.
const FEW: usize = 256;
let mut spans = spans;
let many = spans.len() > FEW;
if !many {
#[cfg(feature = "diagnostics")]
let all = spans.len();
spans.retain(|(shadow, from, to)| !shadow.nothing_new(*from, *to - *from));
#[cfg(feature = "diagnostics")]
FLUSHES[2].fetch_add((all - spans.len()) as u64, Ordering::Relaxed);
}
let ahead = spans.len() > 1;
if ahead {
let ranges: Vec<(usize, usize)> = spans.iter().filter(|r| r.0.asked_ahead()).map(|r| (r.1, r.2)).collect();
crate::watch::ask_ahead(&ranges);
}
#[cfg(feature = "diagnostics")]
FLUSHES[3].fetch_add(spans.len() as u64, Ordering::Relaxed);
crate::shadow::wide_each(spans.len() + due.len(), move |i| {
// The textures first: they are the longer pieces.
let Some(i) = i.checked_sub(due.len()) else {
due[i].refresh();
return;
};
let (shadow, from, to) = &spans[i];
if many && shadow.nothing_new(*from, *to - *from) {
#[cfg(feature = "diagnostics")]
FLUSHES[2].fetch_add(1, Ordering::Relaxed);
return;
}
Self::update(shadow, *from, *to);
});
if ahead {
crate::watch::ask_ahead_done();
}
// The time counted is the time it took, not the threads' sum.
let took = started.elapsed().as_micros() as u64;
let summed = [0, 2].map(|i| PREPARING[i].load(Ordering::Relaxed)).iter().zip(before).map(|(now, was)| now.saturating_sub(was)).collect::<Vec<_>>();
PREPARING[2].fetch_sub(summed[1], Ordering::Relaxed);
PREPARING[0].fetch_sub(summed[0], Ordering::Relaxed);
PREPARING[0].fetch_add(took, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
SPLIT[6].fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
}
/// Before the steps of `runs` ([`ahead_of_writes`]); copies and fills
/// that `taken` names are not done on the CPU.
fn refresh_ahead(&mut self, runs: &[&HostList], taken: impl Fn(&HostList, usize) -> bool) {
@@ -8001,6 +8333,8 @@ struct Presenter {
ahead: Vec<(HostList, u64)>,
hwnd: HWND,
meter: Meter,
#[cfg(feature = "diagnostics")]
panel: panel::Panel,
}
/// The frame rate, shown in the window's caption every second and logged
@@ -8030,6 +8364,12 @@ impl Meter {
}
}
/// Whether the next frame counted makes the frame-rate line.
#[cfg(feature = "diagnostics")]
fn line_due(&self) -> bool {
self.since.elapsed() >= std::time::Duration::from_secs(1)
}
/// Counts a presented frame.
fn frame(&mut self, hwnd: HWND) {
#[cfg(feature = "diagnostics")]
@@ -8263,6 +8603,7 @@ impl Meter {
put[2] / 1e6,
put[3]
);
traffic::line(self.copy_stats_frames as f64);
crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
for (why, n) in drops.iter().take(40) {
tracing::info!(
@@ -8404,6 +8745,10 @@ impl Host {
.flatten();
#[cfg(feature = "diagnostics")]
let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) };
#[cfg(feature = "diagnostics")]
let watched = crate::popwatch::take(&self.device, list, texture);
#[cfg(feature = "diagnostics")]
p.panel.draw(self, copy, &back, (width, height), format);
#[cfg(not(feature = "diagnostics"))]
let _ = frame;
list.ResourceBarrier(&[
@@ -8415,13 +8760,23 @@ impl Host {
),
]);
copy.close();
match slot {
let flown = match slot {
Some(i) => {
let flown = self.execute_own(copy);
p.ahead[i].1 = flown;
flown
}
None => self.execute(&[copy]),
None => {
self.execute(&[copy]);
0
}
};
#[cfg(feature = "diagnostics")]
if let Some(taken) = watched {
crate::popwatch::sent(taken, flown, frame);
}
#[cfg(not(feature = "diagnostics"))]
let _ = flown;
#[cfg(feature = "diagnostics")]
if let Some((buffer, footprint)) = capture {
crate::capture::save_read_back(frame, &buffer, &footprint);
@@ -8431,6 +8786,8 @@ impl Host {
let mut showing = crate::timeline::span("the host's Present");
let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
showing.next("the frame meter");
#[cfg(feature = "diagnostics")]
p.panel.frame(p.meter.line_due());
p.meter.frame(p.hwnd);
showing.end();
#[cfg(feature = "diagnostics")]
@@ -8483,6 +8840,8 @@ impl Host {
ahead: Vec::new(),
hwnd,
meter: Meter::new(),
#[cfg(feature = "diagnostics")]
panel: panel::Panel::new(),
})
}
}
+148 -57
View File
@@ -83,6 +83,29 @@ pub(super) fn stage() -> u32 {
})
}
/// Whether a copy at its place in a list ([`place`]) is only in the way of
/// what is done on the card in front of the lists if that stands behind it in
/// them (`VICTORY_PLACED_ORDER=1`; off: wherever it stands), and a
/// submission where it does is cut behind the copy's list ([`cut_for`]). Off:
/// the case did not come up once in runs submit-1 to submit-3, so it has only
/// its tests behind it.
///
/// The fills of constant buffers read the title's ring (7,500 a frame in the
/// opening), and one copy of a few hundred bytes a frame writes into it at its
/// place in a list. The whole submission was refused for it, and stood 40 to
/// 60 ms until the flights had landed (run n19).
fn placed_order() -> bool {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_PLACED_ORDER") {
return on;
}
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| crate::switch::on("VICTORY_PLACED_ORDER"))
}
/// Why [`plan`] refuses for [`place`].
const BEHIND_PLACED: &str = "a copy at its place in a list writes what it reads, or reads or writes what it writes";
/// The bytes of our buffer between reading and writing: what one submission
/// may do this way (each place read once, however many fills take it).
const BETWEEN: u64 = 4 << 20;
@@ -226,10 +249,13 @@ fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool {
/// only what a taken copy has not been told to write yet: bytes a step
/// ahead of it reads, in title memory as it is.
///
/// `behind`: for [`BEHIND_PLACED`], the copy at its place and the first step
/// behind it that is in its way.
///
/// Steps of a level are done together, every read before every write; a
/// step that writes what an earlier one reads or writes, or reads what it
/// writes, is of a higher level. Our list does them level by level.
fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
fn plan(does: &[Does], stage: u32, by_order: bool, behind: &mut Option<(usize, usize)>) -> Result<Vec<(usize, u32)>, &'static str> {
let takes = |d: &Does| match *d {
Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"),
Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"),
@@ -281,12 +307,21 @@ fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
}
}
// A copy at its place in a list comes after what is done in front of all
// of them.
for d in does {
// of them: as it should after the steps ahead of it, but not after those
// behind it that read or write its bytes.
for (p, d) in does.iter().enumerate() {
if let Does::Placed { dst, src, len } = *d
&& (touched(&read, (dst, dst + len)) || touched(&written, (dst, dst + len)) || touched(&written, (src, src + len)))
{
return Err("a copy at its place in a list writes what it reads, or reads or writes what it writes");
let (to, from) = ((dst, dst + len), (src, src + len));
let in_the_way = |i: usize| {
reads_writes(&does[i]).is_some_and(|(r, w)| meet(r, to) || w.0 < w.1 && (meet(w, to) || meet(w, from)))
};
let found = (p + 1..does.len()).find(|&i| taken[i] && in_the_way(i));
*behind = found.map(|i| (p, i));
if !by_order || found.is_some() {
return Err(BEHIND_PLACED);
}
}
}
let order: Vec<usize> = (0..does.len()).filter(|&i| taken[i]).collect();
@@ -375,6 +410,78 @@ fn holder(writers: &[Writer], from: usize, to: usize) -> Result<Arc<Shadow>, &'s
Ok(shadow)
}
/// What the steps of `runs` do, and which step each is (its list by address,
/// its place in it). `written`: what flights may write.
fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec<Does>, Vec<(usize, usize)>) {
let mut does = Vec::new();
// Which step each is. One list's lock at a time: a submission may
// name a list twice.
let mut steps = Vec::new();
for list in runs {
for (i, step) in list.deferred().copies.iter().enumerate() {
does.push(match step {
&Step::Copy(dst, src, len) => Does::Copy {
dst,
src,
len,
asked: copy_blocked(written, dst, src, len).is_some(),
},
Step::Fill(_, src, len, to) => Does::Fill {
src: *src,
len: *len,
asked: read_blocked(written, *src, *len),
to: to.is_some(),
},
Step::Texture(staging) => {
let (at, len) = staging.memory();
Does::Read {
from: at,
to: at + len,
asked: touches(written, at, at + len),
}
}
&Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
Step::Refresh(shadow, at, len) => Does::Refresh {
shadow: Arc::as_ptr(shadow) as usize,
from: *at,
to: *at + *len,
},
Step::Run(_) => Does::Run,
Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len },
Step::GpuWrite(..) | Step::Host(..) => continue,
});
steps.push((std::ptr::from_ref::<HostList>(list) as usize, i));
}
}
(does, steps)
}
/// With flights in the air: before which of `runs` the submission is cut so
/// that what reads or writes the bytes of a copy at its place in an earlier
/// list ([`BEHIND_PLACED`]) is done on the card in front of a submission of
/// its own, behind that copy.
pub(super) fn cut_for(runs: &[&HostList]) -> Option<usize> {
if stage() == 0 || !relay_exact() || !placed_order() || runs.len() < 2 {
return None;
}
// (Most submissions have none.)
let first = runs.iter().position(|l| l.deferred().copies.iter().any(|s| matches!(s, Step::Placed(_))))?;
if first + 1 == runs.len() {
return None;
}
let written = line().written.clone();
blocked_by(&written, runs, false)?;
let (does, steps) = does_of(&written, runs);
let mut behind = None;
if plan(&does, stage(), true, &mut behind) != Err(BEHIND_PLACED) {
return None;
}
let (placed, reader) = behind?;
let place = |i: usize| runs.iter().position(|l| std::ptr::from_ref::<HostList>(l) as usize == steps[i].0);
let cut = place(placed)? + 1;
(place(reader)? >= cut).then_some(cut)
}
/// Whether every page of `[from, to)` can be read (through the kernel:
/// asking Windows walks the page tables, milliseconds in the title's heap).
/// `room`: for what is read.
@@ -567,47 +674,8 @@ impl Host {
}
fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
let mut does = Vec::new();
// Which step each is. One list's lock at a time: a submission may
// name a list twice.
let mut steps = Vec::new();
for list in runs {
for (i, step) in list.deferred().copies.iter().enumerate() {
does.push(match step {
&Step::Copy(dst, src, len) => Does::Copy {
dst,
src,
len,
asked: copy_blocked(written, dst, src, len).is_some(),
},
Step::Fill(_, src, len, to) => Does::Fill {
src: *src,
len: *len,
asked: read_blocked(written, *src, *len),
to: to.is_some(),
},
Step::Texture(staging) => {
let (at, len) = staging.memory();
Does::Read {
from: at,
to: at + len,
asked: touches(written, at, at + len),
}
}
&Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
Step::Refresh(shadow, at, len) => Does::Refresh {
shadow: Arc::as_ptr(shadow) as usize,
from: *at,
to: *at + *len,
},
Step::Run(_) => Does::Run,
Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len },
Step::GpuWrite(..) | Step::Host(..) => continue,
});
steps.push((std::ptr::from_ref::<HostList>(list) as usize, i));
}
}
let chosen = plan(&does, stage())?;
let (does, steps) = does_of(written, runs);
let chosen = plan(&does, stage(), placed_order(), &mut None)?;
if chosen.is_empty() {
return Ok(None);
}
@@ -863,7 +931,7 @@ mod tests {
/// What is done on the card, as (place, level), in stage 2.
fn planned(does: &[Does]) -> Vec<(usize, u32)> {
plan(does, 2).unwrap()
plan(does, 2, true, &mut None).unwrap()
}
/// Only what is asked for is taken, all of it, and a step that stands
@@ -881,8 +949,8 @@ mod tests {
];
assert_eq!(planned(&does), [(1, 0), (3, 0)]);
// Two fills of the same bytes.
assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![(0, 0), (1, 0)]));
assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![]));
assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1, true, &mut None), Ok(vec![(0, 0), (1, 0)]));
assert_eq!(plan(&[fill(0, 64, false)], 1, true, &mut None), Ok(vec![]));
// Ends that touch are apart.
let does = [
copy(1000, 5000, 100, true),
@@ -927,6 +995,29 @@ mod tests {
assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]);
}
/// A copy at its place in a list is in the way of what reads or writes its
/// bytes behind it, not of what did ahead of it.
#[test]
fn copies_at_their_place_stand_in_the_way_of_what_is_behind_them() {
let placed = Does::Placed { dst: 2000, src: 3000, len: 64 };
let behind = |does: &[Does]| {
let mut found = None;
let refused = plan(does, 2, true, &mut found);
assert!(refused.is_ok() || found.is_some() && refused == Err(BEHIND_PLACED));
assert_eq!(plan(does, 2, false, &mut None).is_err(), does.len() > 1 && !matches!(does, [_, Does::Fill { src: 5000, .. }]));
found
};
assert_eq!(behind(&[fill(2032, 64, true), placed]), None);
assert_eq!(behind(&[placed, fill(2032, 64, true)]), Some((0, 1)));
assert_eq!(behind(&[placed, fill(5000, 64, true)]), None);
assert_eq!(behind(&[fill(2000, 8, true), placed, fill(2000, 8, true)]), Some((1, 2)));
// One that writes what it copies from, and one that writes over it.
assert_eq!(behind(&[copy(3000, 5000, 8, true), placed]), None);
assert_eq!(behind(&[placed, copy(3000, 5000, 8, true)]), Some((0, 1)));
assert_eq!(behind(&[copy(2060, 5000, 8, true), placed]), None);
assert_eq!(behind(&[placed, copy(2060, 5000, 8, true)]), Some((0, 1)));
}
/// Whatever the steps, done level by level (in a level every read
/// before every write) they read and leave what they read and leave one
/// after the other, the CPU's steps ahead of all of them.
@@ -951,7 +1042,7 @@ mod tests {
}
})
.collect();
let Ok(chosen) = plan(&does, 2) else {
let Ok(chosen) = plan(&does, 2, true, &mut None) else {
refused += 1;
continue;
};
@@ -1005,22 +1096,22 @@ mod tests {
#[test]
fn steps_in_the_way_are_refused() {
let taken = copy(1000, 5000, 100, true);
assert!(plan(&[taken, Does::Run], 2).is_err());
assert!(plan(&[taken, Does::Run], 2, true, &mut None).is_err());
// A texture that itself waits for flights; a fill that cannot be
// taken but waits.
assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2).is_err());
assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2).is_err());
assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2, true, &mut None).is_err());
assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2, true, &mut None).is_err());
// Reads on the CPU of what it writes: behind it, not ahead of it.
for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] {
assert!(plan(&[taken, read], 2).is_err(), "{read:?} behind");
assert!(plan(&[taken, read], 2, true, &mut None).is_err(), "{read:?} behind");
assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead");
}
// Also of what is taken along.
assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2).is_err());
assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2, true, &mut None).is_err());
// Into itself, and copies without stage 2.
assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err());
assert!(plan(&[taken], 1).is_err());
assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err());
assert!(plan(&[copy(1000, 1050, 100, true)], 2, true, &mut None).is_err());
assert!(plan(&[taken], 1, true, &mut None).is_err());
assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1, true, &mut None).is_err());
}
#[test]
+474
View File
@@ -0,0 +1,474 @@
//! Diagnostics: the run's numbers on the picture (`VICTORY_PANEL=1`; off by
//! default; F3 shows and hides it while our window has the focus): white
//! text on a black box in the upper left corner of what is shown, so that a
//! screenshot carries them, with what it costs itself on the submitting
//! thread. Made again twice a second from the counters of
//! the frame-rate line, memory and textures; a frame itself only copies the
//! box out of a buffer in the card's memory. Copied onto the swap chain's
//! buffer, behind the title's picture: saved frames and the frame recorder
//! see the title's own.
use std::sync::OnceLock;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetAsyncKeyState, VK_F3};
use windows_sys::Win32::UI::WindowsAndMessaging::{GetForegroundWindow, GetWindowThreadProcessId};
use super::{Host, HostList, transition};
/// How often the numbers change.
const EVERY: Duration = Duration::from_millis(500);
/// A character's dots, and with the space beside and below it.
const GLYPH: (u32, u32) = (5, 7);
const CELL: (u32, u32) = (6, 9);
/// Characters in a line, lines, and the box's rim in dots.
const COLUMNS: u32 = 40;
const LINES: u32 = 9;
const RIM: u32 = 3;
/// The texts are put into one of these in turn: the card reads the others,
/// at most half a second old.
const UPLOADS: usize = 4;
fn asked() -> bool {
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| crate::switch::on("VICTORY_PANEL"))
}
/// Whether it is shown now.
fn shown() -> &'static AtomicBool {
static SHOWN: OnceLock<AtomicBool> = OnceLock::new();
SHOWN.get_or_init(|| AtomicBool::new(asked()))
}
/// F3 was pressed since the last call, with one of our windows in front.
fn pressed() -> bool {
static DOWN: AtomicBool = AtomicBool::new(false);
// SAFETY: a plain query.
let down = unsafe { GetAsyncKeyState(i32::from(VK_F3)) } < 0;
if DOWN.swap(down, Ordering::Relaxed) || !down {
return false;
}
let mut process = 0;
// SAFETY: plain queries; room for the answer.
unsafe { GetWindowThreadProcessId(GetForegroundWindow(), &mut process) };
process == std::process::id()
}
/// Seven rows of five dots, the leftmost the highest bit.
#[rustfmt::skip]
const fn glyph(c: u8) -> [u8; 7] {
match c {
b'0' => [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
b'1' => [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
b'2' => [0b01110, 0b10001, 0b00001, 0b00110, 0b01000, 0b10000, 0b11111],
b'3' => [0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],
b'4' => [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
b'5' => [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
b'6' => [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
b'7' => [0b11111, 0b00001, 0b00010, 0b00010, 0b00100, 0b00100, 0b00100],
b'8' => [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
b'9' => [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
b'A' => [0b00100, 0b01010, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001],
b'B' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
b'C' => [0b01111, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b01111],
b'D' => [0b11110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11110],
b'E' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
b'F' => [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
b'G' => [0b01111, 0b10000, 0b10000, 0b10011, 0b10001, 0b10001, 0b01111],
b'H' => [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
b'I' => [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
b'J' => [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
b'K' => [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
b'L' => [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
b'M' => [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
b'N' => [0b10001, 0b11001, 0b11001, 0b10101, 0b10011, 0b10011, 0b10001],
b'O' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
b'P' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
b'Q' => [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
b'R' => [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
b'S' => [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
b'T' => [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
b'U' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
b'V' => [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
b'W' => [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b11011, 0b10001],
b'X' => [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
b'Y' => [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
b'Z' => [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
b'.' => [0, 0, 0, 0, 0, 0b01100, 0b01100],
b'/' => [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
b'-' => [0, 0, 0, 0b11111, 0, 0, 0],
b' ' => [0; 7],
_ => [0b11111, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b11111],
}
}
/// The box's size in pixels, a dot being `scale` of them each way.
const fn size(scale: u32) -> (u32, u32) {
((COLUMNS * CELL.0 + 2 * RIM) * scale, (LINES * CELL.1 + 2 * RIM) * scale)
}
/// Pixels to a dot for a picture that high: a 720-line screenshot of it
/// shows one and a third.
fn scale(height: u32) -> u32 {
(height / 540).max(1)
}
/// Whether a dot of the picture of `lines` is white.
fn lit(lines: &[String], x: u32, y: u32) -> bool {
let (Some(x), Some(y)) = (x.checked_sub(RIM), y.checked_sub(RIM)) else {
return false;
};
if x % CELL.0 >= GLYPH.0 || y % CELL.1 >= GLYPH.1 || x / CELL.0 >= COLUMNS {
return false;
}
let Some(&c) = lines.get((y / CELL.1) as usize).and_then(|l| l.as_bytes().get((x / CELL.0) as usize)) else {
return false;
};
(glyph(c.to_ascii_uppercase())[(y % CELL.1) as usize] >> (GLYPH.0 - 1 - x % CELL.0)) & 1 != 0
}
/// The bytes of a black and a white pixel of a swap chain's format.
fn colours(format: DXGI_FORMAT) -> Option<[&'static [u8]; 2]> {
Some(match format {
DXGI_FORMAT_R8G8B8A8_UNORM | DXGI_FORMAT_B8G8R8A8_UNORM => [&[0, 0, 0, 0xFF], &[0xFF; 4]],
DXGI_FORMAT_R10G10B10A2_UNORM => [&[0, 0, 0, 0xC0], &[0xFF; 4]],
// Halves of 0 and 1.
DXGI_FORMAT_R16G16B16A16_FLOAT => [
&[0, 0, 0, 0, 0, 0, 0, 0x3C],
&[0, 0x3C, 0, 0x3C, 0, 0x3C, 0, 0x3C],
],
_ => return None,
})
}
/// The box as rows of `pitch` bytes.
fn painted(lines: &[String], scale: u32, colours: [&[u8]; 2], pitch: usize) -> Vec<u8> {
let (width, height) = size(scale);
let bytes = colours[0].len();
let mut out = vec![0; pitch * height as usize];
for y in 0..height / scale {
let top = pitch * (y * scale) as usize;
for x in 0..width / scale {
let colour = colours[usize::from(lit(lines, x, y))];
for i in 0..scale {
let at = top + (x * scale + i) as usize * bytes;
out[at..at + bytes].copy_from_slice(colour);
}
}
for i in 1..scale as usize {
out.copy_within(top..top + pitch, top + i * pitch);
}
}
out
}
/// The counters read for it. They grow, and go back to 0 with the frame-rate
/// line (right behind a look of ours).
#[derive(Clone, Copy, Default)]
struct Counters([u64; COUNTERS]);
const COUNTERS: usize = 11;
impl Counters {
fn now() -> Counters {
use super::{CARD_CLOCK_US, COPY_BACK, PREPARING};
use crate::copystat::{C, peek};
let get = |a: &std::sync::atomic::AtomicU64| a.load(Ordering::Relaxed);
Counters([
super::worked(),
get(&CARD_CLOCK_US[0]),
get(&CARD_CLOCK_US[1]),
get(&CARD_CLOCK_US[2]),
get(&PREPARING[3]),
get(&COPY_BACK[0]),
get(&COPY_BACK[1]),
get(&crate::shadow::CARD_STATS[0]),
crate::draw::dropped_now(),
peek(C::RecordNs),
crate::draw::drawn(),
])
}
/// What came since `before`, per frame.
fn since(self, before: Counters, frames: f64) -> [f64; COUNTERS] {
let mut out = [0.0; COUNTERS];
for (i, out) in out.iter_mut().enumerate() {
let (was, is) = (before.0[i], self.0[i]);
*out = if is >= was { is - was } else { is } as f64 / frames;
}
out
}
}
/// The text. `c`: [`Counters`] per frame, `ms` a frame's time, `worst` the
/// longest frame's, `cost` what this takes of a frame, in microseconds.
fn text(c: &[f64; COUNTERS], ms: f64, worst: f64, cost: f64, host: &Host) -> Vec<String> {
let gb = |bytes: u64| bytes as f64 / (1u64 << 30) as f64;
let (working, private) = crate::copystat::process_memory();
let [budget, used, _, shared] = host.video_memory().unwrap_or_default();
let idle = (c[1] / 1e3).min(ms);
vec![
format!("FPS {:.1} FRAME {ms:.1} MS LONGEST {worst:.0}", 1e3 / ms.max(0.001)),
format!("DRAWS {:.0} DROPPED {:.0}", c[10], c[8]),
format!("SUBMIT BUSY {:.1} WAITS FOR GPU {:.1}", c[0] / 1e3, c[3] / 1e3),
format!("GPU BUSY {:.1} IDLE BEHIND US {:.1}", ms - idle, c[2] / 1e3),
format!("RECORDING {:.0} MS COPY BACK {:.1}", c[9] / 1e6, c[5] / 1e3),
format!("MB UP {:.0} TEXTURES {:.0} BACK {:.0}", c[7] / 1e6, c[4] / 1e6, c[6] / 1e6),
format!("RAM {:.1} GB IN MEMORY {:.1}", gb(private), gb(working)),
format!("VRAM {:.1}/{:.1} GB SHARED {:.1}", gb(used), gb(budget), gb(shared)),
format!("THIS PANEL {:.0} US A FRAME", cost),
]
}
/// The buffers of a box that size and format.
struct Buffers {
format: DXGI_FORMAT,
scale: u32,
pitch: u32,
uploads: Vec<(ID3D12Resource, *mut u8)>,
card: ID3D12Resource,
/// The upload written last.
turn: usize,
/// It is not in the card's buffer yet.
fresh: bool,
}
// SAFETY: free-threaded resources, and memory only written under the presenter's lock.
unsafe impl Send for Buffers {}
impl Buffers {
fn new(host: &Host, format: DXGI_FORMAT, scale: u32) -> Option<Buffers> {
let (width, height) = size(scale);
let pitch = (width * colours(format)?[0].len() as u32).next_multiple_of(256);
let bytes = u64::from(pitch) * u64::from(height);
let uploads = (0..UPLOADS).map(|_| host.upload_buffer(bytes)).collect::<Option<Vec<_>>>()?;
let heap = D3D12_HEAP_PROPERTIES {
Type: D3D12_HEAP_TYPE_DEFAULT,
..Default::default()
};
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: bytes,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
};
let mut card: Option<ID3D12Resource> = None;
// SAFETY: plain creation of a buffer.
unsafe {
host.device
.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut card)
.ok()?;
}
Some(Buffers { format, scale, pitch, uploads, card: card?, turn: 0, fresh: false })
}
fn write(&mut self, lines: &[String]) {
let Some(colours) = colours(self.format) else { return };
let picture = painted(lines, self.scale, colours, self.pitch as usize);
self.turn = (self.turn + 1) % UPLOADS;
// SAFETY: a mapped upload buffer of the picture's size, which the card read a second or more ago.
unsafe { std::ptr::copy_nonoverlapping(picture.as_ptr(), self.uploads[self.turn].1, picture.len()) };
self.fresh = true;
}
}
/// The panel of a presenter.
pub(super) struct Panel {
since: Instant,
frames: u32,
last: Instant,
worst: f64,
/// What this took since the last text.
cost: Duration,
before: Counters,
lines: Vec<String>,
changed: bool,
buffers: Option<Buffers>,
failed: bool,
}
impl Panel {
pub(super) fn new() -> Panel {
let now = Instant::now();
Panel {
since: now,
frames: 0,
last: now,
worst: 0.0,
cost: Duration::ZERO,
before: Counters::default(),
lines: Vec::new(),
changed: false,
buffers: None,
failed: false,
}
}
/// A frame was presented; `line`: the counters go back to 0 right behind
/// this call. (Not shown it asks for the key's state and no more.)
pub(super) fn frame(&mut self, line: bool) {
if pressed() {
shown().fetch_xor(true, Ordering::Relaxed);
}
if !shown().load(Ordering::Relaxed) {
self.frames = 0;
return;
}
let now = Instant::now();
if self.frames == 0 && now - self.last > 2 * EVERY {
// (Shown from here on.)
(self.since, self.last, self.worst, self.before) = (now, now, 0.0, Counters::now());
self.frames = 0;
}
self.frames += 1;
self.worst = self.worst.max((now - self.last).as_secs_f64() * 1e3);
self.last = now;
let elapsed = now - self.since;
if elapsed < EVERY && !(line && elapsed * 2 >= EVERY) {
return;
}
let Some(host) = super::host() else { return };
let frames = f64::from(self.frames);
let counters = Counters::now();
let c = counters.since(self.before, frames);
self.before = counters;
let cost = self.cost.as_secs_f64() * 1e6 / frames;
self.lines = text(&c, elapsed.as_secs_f64() * 1e3 / frames, self.worst, cost, host);
self.changed = true;
(self.since, self.frames, self.worst) = (now, 0, 0.0);
self.cost = now.elapsed();
}
/// Records the copy of the box onto `back`, a buffer of the swap chain of
/// that size and format in the state to be copied into.
pub(super) fn draw(
&mut self,
host: &Host,
list: &HostList,
back: &ID3D12Resource,
(width, height): (u32, u32),
format: DXGI_FORMAT,
) {
if !shown().load(Ordering::Relaxed) || self.lines.is_empty() || self.failed {
return;
}
let began = Instant::now();
// Not the title's: the frame recorder leaves it out.
let _ours = crate::replay::record::unrecorded();
let scale = scale(height);
if self.buffers.as_ref().is_none_or(|b| (b.format, b.scale) != (format, scale)) {
// (What the card may still read stays: a picture's size changes once or twice in a run.)
std::mem::forget(self.buffers.take());
self.buffers = Buffers::new(host, format, scale);
self.failed = self.buffers.is_none();
self.changed = true;
}
let Some(buffers) = &mut self.buffers else { return };
if std::mem::take(&mut self.changed) {
buffers.write(&self.lines);
}
let (w, h) = size(scale);
let list = &list.list;
// SAFETY: an open list and live resources; the box lies within both.
unsafe {
if std::mem::take(&mut buffers.fresh) {
list.CopyResource(&buffers.card, &buffers.uploads[buffers.turn].0);
list.ResourceBarrier(&[transition(
&buffers.card,
D3D12_RESOURCE_STATE_COPY_DEST,
D3D12_RESOURCE_STATE_COPY_SOURCE,
)]);
}
let from = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(&buffers.card),
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: format,
Width: w,
Height: h,
Depth: 1,
RowPitch: buffers.pitch,
},
},
},
};
let to = D3D12_TEXTURE_COPY_LOCATION {
pResource: std::mem::transmute_copy(back),
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
let part = D3D12_BOX {
left: 0,
top: 0,
front: 0,
right: w.min(width),
bottom: h.min(height),
back: 1,
};
list.CopyTextureRegion(&to, 0, 0, 0, &from, Some(&part));
}
self.cost += began.elapsed();
}
}
#[cfg(test)]
mod tests {
use super::*;
/// Every character the lines use has its own picture, and no two look
/// alike.
#[test]
fn characters_differ() {
let used: Vec<u8> = (b'0'..=b'9').chain(b'A'..=b'Z').chain(*b"./- ").collect();
for (i, a) in used.iter().enumerate() {
assert_ne!(glyph(*a), glyph(b'#'), "{} has a picture", *a as char);
assert!(glyph(*a).iter().all(|row| row >> GLYPH.0 == 0));
for b in &used[i + 1..] {
assert_ne!(glyph(*a), glyph(*b), "{} {}", *a as char, *b as char);
}
}
}
#[test]
fn a_box_is_painted() {
let lines = vec!["I".to_owned(), " i".to_owned()];
for scale in [1, 2, 4] {
let (width, height) = size(scale);
let pitch = (width * 4).next_multiple_of(256) as usize;
let colours = colours(DXGI_FORMAT_R10G10B10A2_UNORM).unwrap();
let picture = painted(&lines, scale, colours, pitch);
assert_eq!(picture.len(), pitch * height as usize);
let at = |x: u32, y: u32| &picture[y as usize * pitch + x as usize * 4..][..4];
// The rim is black, the first letter's top row lit in its middle.
assert_eq!(at(0, 0), colours[0]);
assert_eq!(at((RIM + 2) * scale, RIM * scale), colours[1]);
assert_eq!(at((RIM + 2) * scale + scale - 1, RIM * scale + scale - 1), colours[1]);
assert_eq!(at(RIM * scale, RIM * scale), colours[0]);
// Small letters are shown as capitals, a line and a cell on.
assert_eq!(at((RIM + CELL.0 + 2) * scale, (RIM + CELL.1) * scale), colours[1]);
// Nothing past a line's end.
assert_eq!(at((RIM + CELL.0 * 2 + 2) * scale, (RIM + CELL.1) * scale), colours[0]);
}
}
#[test]
fn counters_that_went_back_to_nothing_count_from_there() {
let (mut a, mut b) = (Counters::default(), Counters::default());
(a.0[0], b.0[0]) = (10, 30);
(a.0[1], b.0[1]) = (50, 20);
let c = b.since(a, 10.0);
assert_eq!((c[0], c[1]), (2.0, 2.0));
}
}
+22 -4
View File
@@ -186,6 +186,9 @@ pub(super) struct Own {
copies: Vec<Copy>,
}
/// Runs whose pairs are one piece of work.
const RUNS_AT_A_TIME: usize = 4096;
/// Takes what `dirty` sends up out of the CPU sides.
pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
let began = std::time::Instant::now();
@@ -210,15 +213,29 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
}
let memory = memory(host, at)?;
let mut moves: Vec<(usize, usize, usize)> = Vec::new();
let mut work: Vec<(usize, &[(usize, usize)], usize)> = Vec::new();
for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
let from = shadow.card_data() as usize;
moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2];
// (80,000 runs of some words a frame: in pieces of work.)
let mut to = memory.data + copy.pairs.0 as usize;
for ranges in ranges.chunks(RUNS_AT_A_TIME) {
let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
if words > 0 {
work.push((from, ranges, to));
to += words * 8;
}
}
}
let one = |i: usize| {
let (from, ranges, to) = work[i];
let mut to = to as *mut [u32; 2];
for &(a, b) in ranges.iter().filter(|r| short(r)) {
for offset in (a..b).step_by(4) {
// SAFETY: inside the copy's mapping (its CPU side, which
// this thread alone writes in these ranges) and inside the
// memory, which has room for every pair.
// the thread that asked, and waits, alone writes in these
// ranges) and inside the memory, which has room for every
// pair, a piece of work's behind the last one's.
unsafe {
let word = ((from + offset) as *const u32).read_unaligned();
to.write([offset as u32, word]);
@@ -226,7 +243,8 @@ pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, us
}
}
}
}
};
crate::land::each_under(work.len(), &one);
STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
+73
View File
@@ -0,0 +1,73 @@
//! Diagnostics: which host copies' bytes cross the bus, and which way: per
//! copy (title address, bytes) what was sent up and what shaders wrote that
//! was fetched, a frame; and how many different 64 KiB pieces of it. Every
//! five seconds, the eight that move most. For placing resources: a copy whose
//! pieces are fetched every frame and never sent up is written by shaders
//! alone, and nobody but shaders may read it.
use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
/// Of a copy, each way (up, fetched): bytes, and the pieces (64 KiB).
#[derive(Default)]
struct Moved {
bytes: [u64; 2],
pieces: [HashSet<u32>; 2],
}
pub(super) const UP: usize = 0;
pub(super) const FETCHED: usize = 1;
static MOVED: Mutex<Option<HashMap<(u64, u64), Moved>>> = Mutex::new(None);
/// Offsets `ranges` of the copy of `span` (title address, bytes) went `way`.
pub(super) fn moved(way: usize, span: (u64, u64), ranges: impl Iterator<Item = (usize, usize)>) {
let mut all = MOVED.lock().unwrap_or_else(|e| e.into_inner());
let m = all.get_or_insert_with(Default::default).entry(span).or_default();
// (Thousands of runs lie in one piece, one after the other.)
let mut last = u32::MAX;
for (from, to) in ranges.filter(|r| r.0 < r.1) {
m.bytes[way] += (to - from) as u64;
let (first, end) = ((from >> 16) as u32, ((to - 1) >> 16) as u32);
if (first, end) != (last, last) {
m.pieces[way].extend(first..=end);
}
last = end;
}
}
/// For the log, over `frames` frames.
pub(super) fn line(frames: f64) {
let all = MOVED.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
let mut all: Vec<_> = all.into_iter().collect();
all.sort_by_key(|(_, m)| std::cmp::Reverse(m.bytes[0] + m.bytes[1]));
let mb = |b: u64| b as f64 / 1e6 / frames.max(1.0);
let sum = |way: usize| all.iter().map(|(_, m)| m.bytes[way]).sum::<u64>();
// Copies that only move one way.
let only = |way: usize| all.iter().filter(|(_, m)| m.bytes[1 - way] == 0).map(|(_, m)| m.bytes[way]).sum::<u64>();
tracing::info!(
"landings in title memory looked at by refreshes per frame (VICTORY_LAND_ECHO=0: sent up): {:.1} MB held already and left, \
{:.1} MB the title's too",
mb(crate::shadow::ECHO[0].swap(0, std::sync::atomic::Ordering::Relaxed)),
mb(crate::shadow::ECHO[1].swap(0, std::sync::atomic::Ordering::Relaxed)),
);
tracing::info!(
"bytes of host copies over the bus per frame: {:.1} MB up ({:.1} of copies nothing was fetched from), {:.1} MB fetched \
({:.1} of copies nothing was sent up to), {} copies; the most:",
mb(sum(UP)),
mb(only(UP)),
mb(sum(FETCHED)),
mb(only(FETCHED)),
all.len()
);
for ((start, len), m) in all.into_iter().take(8) {
let both = m.pieces[0].intersection(&m.pieces[1]).count();
tracing::info!(
" {start:#x}+{len:#x}: {:.2} MB up in {} different pieces, {:.2} MB fetched in {}, {both} of them both ways",
mb(m.bytes[0]),
m.pieces[0].len(),
mb(m.bytes[1]),
m.pieces[1].len()
);
}
}
+52 -9
View File
@@ -37,7 +37,6 @@
use std::collections::BTreeMap;
use std::ffi::c_void;
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use windows::Win32::Foundation::HANDLE;
@@ -281,7 +280,9 @@ struct Views {
whole: Vec<(usize, usize)>,
}
static VIEWS: Mutex<Views> = Mutex::new(Views {
/// Read by many threads at once (write faults, landings), changed when the
/// runtime maps or unmaps.
static VIEWS: std::sync::RwLock<Views> = std::sync::RwLock::new(Views {
views: BTreeMap::new(),
pages: BTreeMap::new(),
pages_twice: 0,
@@ -289,14 +290,18 @@ static VIEWS: Mutex<Views> = Mutex::new(Views {
whole: Vec::new(),
});
fn views() -> std::sync::MutexGuard<'static, Views> {
VIEWS.lock().unwrap_or_else(|e| e.into_inner())
fn views() -> std::sync::RwLockReadGuard<'static, Views> {
VIEWS.read().unwrap_or_else(|e| e.into_inner())
}
fn views_mut() -> std::sync::RwLockWriteGuard<'static, Views> {
VIEWS.write().unwrap_or_else(|e| e.into_inner())
}
/// The runtime made a section of `bytes` for physical pages; `committed`
/// if with `SEC_COMMIT` (only such a section can be opened as a heap).
pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
let mut v = views();
let mut v = views_mut();
v.sections.retain(|s| s.0 != section);
// A handle's number given out again: the view was of the section that
// had it before (it stays mapped: someone may be writing through it).
@@ -308,7 +313,7 @@ pub fn title_memory_section(section: usize, bytes: u64, committed: bool) {
/// sees is of it any more, and [`beside`]'s view goes.
pub fn title_memory_section_gone(section: usize) {
let whole = {
let mut v = views();
let mut v = views_mut();
let at = v.whole.iter().position(|w| w.0 == section);
at.map(|i| v.whole.swap_remove(i).1)
};
@@ -324,7 +329,7 @@ pub fn title_memory_section_gone(section: usize) {
/// `offset` on. Call after [`crate::title_memory_remapped`] of the range.
pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
{
let mut v = views();
let mut v = views_mut();
v.views.insert(at, (len, section, offset));
for k in 0..len.div_ceil(K64) {
let shown = v.pages.entry((section, offset + (k * K64) as u64)).or_default();
@@ -343,7 +348,7 @@ pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) {
/// the views that touch it are forgotten (the runtime tells again those it
/// maps anew).
pub(crate) fn views_gone(at: usize, len: usize) {
let mut v = views();
let mut v = views_mut();
if v.views.is_empty() {
return;
}
@@ -529,7 +534,17 @@ pub(crate) fn cover(at: usize, len: usize) -> Cover {
/// `crate::watch::title_memory_reading`: until it lets go the title sees
/// the same pages at `at`.
pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
let mut v = views();
let known = {
let v = views();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
v.whole.iter().find(|w| w.0 == section).map(|w| (w.1, offset))
};
if let Some((base, offset)) = known {
return (base != 0).then(|| base + offset as usize);
}
let mut v = views_mut();
let Cover::Run(section, offset) = cover_in(&v.views, at, len) else {
return None;
};
@@ -550,6 +565,34 @@ pub(crate) fn beside(at: usize, len: usize) -> Option<usize> {
(base != 0).then(|| base + offset as usize)
}
/// Our own address of the 64 KiB page the title sees at `page` ([`beside`]),
/// and every address the title sees it at (0: no more); `None` if the page is
/// in no view of a section, or in very many. While the caller holds
/// `crate::watch::title_memory_reading`.
pub(crate) fn beside_page(page: usize) -> Option<(usize, [usize; 8])> {
for asked in [false, true] {
{
let v = views();
let (&base, &(bytes, section, offset)) = v.views.range(..=page).next_back()?;
let within = page.wrapping_sub(base);
if within >= bytes || !within.is_multiple_of(K64) {
return None;
}
let offset = offset + within as u64;
if let Some(whole) = v.whole.iter().find(|w| w.0 == section) {
let mut shown = [0; 8];
let all = v.pages.get(&(section, offset))?;
shown.get_mut(..all.len())?.copy_from_slice(all);
return (whole.1 != 0).then(|| (whole.1 + offset as usize, shown));
}
}
if asked || beside(page, K64).is_none() {
return None;
}
}
None
}
/// Whether `[at, at + len)` is private memory, all committed and
/// read-write: what [`From::Part`] takes. One question to Windows (it
/// walks the page tables to the end of the pages that share the first
+34 -4
View File
@@ -227,7 +227,7 @@ impl Pool {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn new(threads: usize) -> &'static Pool {
fn new(name: &'static str, threads: usize) -> &'static Pool {
let pool: &'static Pool = Box::leak(Box::new(Pool {
state: Mutex::new(State { work: None, next: 0, count: 0, running: 0, panicked: false }),
more: Condvar::new(),
@@ -237,8 +237,12 @@ impl Pool {
}));
for i in 1..threads {
// (A helper that is not there is only missed.)
let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || {
crate::cores::keep_helper_on_fast_cores("victory-land");
let _ = std::thread::Builder::new().name(format!("{name}-{i}")).spawn(move || {
if name == "victory-land" {
crate::cores::keep_helper_on_fast_cores(name);
} else {
crate::cores::keep_many_on_fast_cores(name);
}
pool.help()
});
}
@@ -321,7 +325,33 @@ fn take(state: &mut State) -> Option<(Work, usize)> {
/// [`Pool::each`] on the threads kept for landing.
pub(crate) fn each(count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOL: OnceLock<&'static Pool> = OnceLock::new();
POOL.get_or_init(|| Pool::new(threads())).each(count, f);
POOL.get_or_init(|| Pool::new("victory-land", threads())).each(count, f);
}
/// [`Pool::each`] on threads kept for the title's bytes under flights' writes
/// (`VICTORY_UNDER_THREADS`, 6 with this one).
pub(crate) fn each_under(count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOL: OnceLock<&'static Pool> = OnceLock::new();
POOL.get_or_init(|| {
let threads = std::env::var("VICTORY_UNDER_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(6usize);
Pool::new("victory-under", threads.clamp(1, 16))
})
.each(count, f);
}
/// Calls `f` with every number below `count`, on this thread and on threads
/// kept for making descriptors (`VICTORY_VIEW_THREADS`, 4 with this one; 1:
/// on this one alone). Those for `records`, the heaps' records copied as
/// bytes, are others than those for the views picked by index: submissions
/// wait for the first, lists for the second, and each kept the other waiting.
pub(crate) fn each_view(records: bool, count: usize, f: &(dyn Fn(usize) + Sync)) {
static POOLS: [OnceLock<&'static Pool>; 2] = [const { OnceLock::new() }; 2];
POOLS[usize::from(records)]
.get_or_init(|| {
let threads = std::env::var("VICTORY_VIEW_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(4usize);
Pool::new(if records { "victory-records" } else { "victory-views" }, threads.clamp(1, 16))
})
.each(count, f);
}
/// A piece to land: the copy's number, the title address, its bytes.
+3 -3
View File
@@ -48,7 +48,7 @@ impl Title {
#[test]
fn the_pool_calls_every_number_once() {
for threads in [1usize, 2, 4, 7] {
let pool = Pool::new(threads);
let pool = Pool::new("victory-land", threads);
std::thread::scope(|s| {
for _ in 0..3 {
s.spawn(|| {
@@ -69,7 +69,7 @@ fn the_pool_calls_every_number_once() {
/// A job that panics is told to the caller, and the pool goes on.
#[test]
fn a_panicking_job_reaches_the_caller() {
let pool = Pool::new(3);
let pool = Pool::new("victory-land", 3);
for bad in 0..8usize {
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
pool.each(8, &|i| assert_ne!(i, bad, "(expected)"));
@@ -448,7 +448,7 @@ fn what_landing_costs() {
frame("as before, guards opened ahead", dense, 1, before);
frame("as before, nothing guarded", dense, 0, before);
for threads in [1usize, 2, 3, 4, 5, 6, 8] {
let pool = Pool::new(threads);
let pool = Pool::new("victory-land", threads);
for beside in [false, true] {
frame(&format!("{threads} threads, beside {beside}"), dense, 2, &|landing| {
let cut: Vec<(usize, usize)> = landing.iter().map(|p| (p.0, BLOCK)).collect();
+8
View File
@@ -15,11 +15,15 @@
//! share, [`console`] which console model the title sees. Planned:
//! `present` (swap chain).
#[cfg(windows)]
mod ambient;
#[cfg(all(windows, feature = "diagnostics"))]
mod capture;
pub mod console;
#[cfg(all(windows, feature = "diagnostics"))]
mod copystat;
#[cfg(all(windows, feature = "diagnostics"))]
mod faultbook;
#[cfg(windows)]
mod cores;
pub mod descriptor;
@@ -46,6 +50,8 @@ pub mod pipeline;
mod picked;
#[cfg(windows)]
mod pool;
#[cfg(all(windows, feature = "diagnostics"))]
mod popwatch;
#[cfg(windows)]
mod primitive;
pub mod query;
@@ -76,6 +82,8 @@ mod tdr;
mod texture;
pub mod timeline;
#[cfg(windows)]
pub mod titlewrite;
#[cfg(windows)]
mod upload;
#[cfg(windows)]
mod watch;
+1 -1
View File
@@ -303,7 +303,7 @@ fn start() {
let threads = std::env::var("VICTORY_THIN_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8usize).clamp(1, 32);
for i in 0..threads {
let worker = move || {
crate::cores::keep_helper_on_fast_cores("victory-list");
crate::cores::keep_many_on_fast_cores("victory-list");
crate::queue::no_drain_here();
loop {
let recording = {
+163 -2
View File
@@ -181,6 +181,8 @@ struct Memory {
stats: Stats,
#[cfg(feature = "diagnostics")]
dump: dump::Dump,
#[cfg(feature = "diagnostics")]
trace: trace::Trace,
}
/// Since the last report.
@@ -254,6 +256,8 @@ impl Memory {
stats: Stats::default(),
#[cfg(feature = "diagnostics")]
dump: Default::default(),
#[cfg(feature = "diagnostics")]
trace: Default::default(),
})
}
@@ -789,6 +793,55 @@ impl Memory {
}
}
/// A list with this key ([`HostList::used`]) asks the builder for sizes.
const SIZES: usize = usize::MAX - (9 << 33);
/// Whether a submission that asks for the sizes of structures is waited for,
/// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=1`; off).
///
/// Off: it does not help. In run light-15, with it, 33 of 154 copies had the
/// slot's old size still (all of them recorded one frame after the size was
/// asked for) against 53 of 230 in light-11, 48 of 275 dynamic structures
/// were good, and the title asks in every frame, so every frame waits (109 ms
/// against 90). The title reads the slot before our submission of the asking
/// list is through, or reads it for another purpose; not known.
///
/// The title asks for a new structure's compacted size (a program of one
/// thread stores it into a small buffer), reads it a frame or two later
/// without looking whether it is there, takes memory of that size and copies
/// the structure into it. With submissions that land up to two frames late it
/// read what the slot held before, some other structure's size, and the copy
/// wrote over its neighbours: of 230 such copies of run light-11, 99 were
/// asked for two frames earlier and landed in that frame, none of those with
/// the right size.
fn sizes_wait() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_some_and(|v| v == "1"))
}
/// Whether a dispatch of the builder is its program of a structure's size:
/// one thread, the structure's address and what to store (1: the compacted
/// size) as constants, a small title buffer to store into.
fn asks_size(written: &[u64], constants: &[u32], threads: Option<[u32; 3]>) -> bool {
threads == Some([1, 1, 1])
&& matches!(*constants, [_, hi, 1..=3, ..] if (1..0x20).contains(&hi))
&& written.first().is_some_and(|&at| crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK))
}
/// Whether one of `lists` asks for sizes.
pub(crate) fn asked_sizes<'a>(lists: impl Iterator<Item = &'a HostList>) -> bool {
let mut lists = lists;
let asked = sizes_wait() && lists.any(|l| l.used(SIZES));
if asked {
static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
if n.is_power_of_two() || n.is_multiple_of(100) {
tracing::info!(n, frame = crate::frame::current(), "submissions that ask for structures' sizes, waited for");
}
}
asked
}
/// [`fill`] of a page stores by address do not reach.
fn close(entry: *mut u32, n: usize, offset: u64) {
fill(entry, n | MEMORY_READ_ONLY as usize, offset);
@@ -809,7 +862,10 @@ fn fill(entry: *mut u32, n: usize, offset: u64) {
fn packed_len(header: u64) -> Option<u64> {
let (version, nodes) = (header as u32, header >> 32);
let marks = version >> 16;
(version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && nodes * 64 <= PACKED).then_some(nodes * 64)
// The header counts its nodes of 64 bytes without the last one: the
// builder's own program of a structure's size stores one more.
let len = (nodes + 1) * 64;
(version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && len <= PACKED).then_some(len)
}
/// Puts what `title` holds into `ours` (what was last taken): the dwords that
@@ -845,6 +901,7 @@ pub(crate) fn ready(
written: &[u64],
constants: &[u32],
use_: Use,
threads: Option<[u32; 3]>,
) -> Option<Ready> {
let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner());
if guard.is_none() {
@@ -858,8 +915,17 @@ pub(crate) fn ready(
m.take_faults();
m.look_again();
m.report();
#[cfg(feature = "diagnostics")]
m.trace.look(frame);
}
#[cfg(feature = "diagnostics")]
if use_ != Use::Reads {
m.trace.dispatch(frame, list, addresses, written, constants, threads);
}
let builds = use_ != Use::Reads;
if builds && sizes_wait() && asks_size(written, constants, threads) {
list.first_use(SIZES);
}
while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {}
m.stats.uses[usize::from(builds)] += 1;
// Once per list and page named: the builder dispatches hundreds of times
@@ -1004,6 +1070,101 @@ pub(crate) fn ready(
})
}
/// `VICTORY_BVH_TRACE=1`: the sizes the builder is asked for (its program of
/// one thread that stores a structure's compacted size) and when title memory
/// has them, and the copies to a place of that size.
#[cfg(feature = "diagnostics")]
mod trace {
use super::*;
#[derive(Default)]
pub(super) struct Trace {
/// Frame, where the size goes, the structure, what title memory had.
asked: Vec<(u64, u64, u64, u64)>,
/// By structure, what its size was when last seen to change.
sizes: HashMap<u64, (u64, u64)>,
said: u32,
}
fn on() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_TRACE").is_some_and(|v| v == "1"))
}
fn value(at: u64) -> u64 {
let mut b = [0u8; 8];
crate::host::copy_mapped(b.as_mut_ptr(), at as *const u8, 8, false);
u64::from_le_bytes(b)
}
impl Trace {
fn say(&mut self, text: String) {
self.said += 1;
if self.said < 6000 {
tracing::info!("bvh trace: {text}");
}
}
pub(super) fn look(&mut self, frame: u64) {
if !on() {
return;
}
let mut gone = Vec::new();
for i in 0..self.asked.len() {
let (then, at, structure, was) = self.asked[i];
let now = value(at);
if now != was {
self.sizes.insert(structure, (now, frame));
gone.push(i);
self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: {was:#x} -> {now:#x}"));
} else if frame > then + 60 {
gone.push(i);
self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: still {was:#x}"));
}
}
for i in gone.into_iter().rev() {
self.asked.swap_remove(i);
}
}
pub(super) fn dispatch(
&mut self,
frame: u64,
list: &HostList,
addresses: &[u64],
written: &[u64],
constants: &[u32],
threads: Option<[u32; 3]>,
) {
if !on() {
return;
}
let _ = addresses;
let list = std::ptr::from_ref(list) as usize & 0xFFFF_FFFF;
if threads == Some([1, 1, 1])
&& let [lo, hi, mode, ..] = *constants
&& (1..=3).contains(&mode)
&& hi < 0x20
&& let Some(&at) = written.first()
&& crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK)
{
let structure = u64::from(lo) | u64::from(hi) << 32;
let was = value(at);
self.say(format!("frame {frame} list {list:x}: asks mode {mode} of {structure:#x} to {at:#x}, there {was:#x}"));
if mode == 1 {
self.asked.push((frame, at, structure, was));
}
} else if threads == Some([32, 1, 1])
&& let [from, to] = *written
&& [from, to].iter().all(|&a| a >= 1 << 32 && crate::shadow::in_buffer(a, 1).is_none())
{
let known = self.sizes.get(&from).copied();
self.say(format!("frame {frame} list {list:x}: copies {from:#x} to {to:#x} constants {:x?}, its size was {known:x?}", &constants[..constants.len().min(4)]));
}
}
}
}
/// `VICTORY_MEMORY_DUMP=<folder>`: when a file `go` appears there, the arenas
/// as the card holds them are copied out and written (`arena-<n>.bin`), with
/// `pages.txt` (title page, arena, offset) and the structures the walking
@@ -1132,7 +1293,7 @@ mod tests {
#[test]
fn a_packed_structure_is_known_by_its_header() {
let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32;
assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1a * 64));
assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1b * 64));
// Unpacked, a top level, another version, no size, too big.
assert_eq!(packed_len(header(0x8002_0006, 0x9a1a)), None);
assert_eq!(packed_len(header(0x0000_0006, 5)), None);
+5
View File
@@ -61,6 +61,9 @@ pub(crate) struct Shader {
/// The first 8 bytes of its BLAKE3, as logged.
pub(crate) hash: String,
container: Vec<u8>,
/// Its part in the stand-in for the indirect light.
#[cfg(windows)]
pub(crate) ambient: Option<crate::ambient::Role>,
#[cfg(windows)]
translated: OnceLock<Option<Translated>>,
}
@@ -112,6 +115,8 @@ fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
hash: full.to_hex()[..16].to_owned(),
container: bytes.to_vec(),
#[cfg(windows)]
ambient: (stage == "compute").then(|| crate::ambient::role(bytes)).flatten(),
#[cfg(windows)]
translated: OnceLock::new(),
})
})
+11
View File
@@ -151,6 +151,17 @@ fn host_blend(blend: &D3D12_BLEND_DESC, targets: &D3D12_RT_FORMAT_ARRAY) -> D3D1
}
impl GraphicsState {
/// Whether the draws are a pass over the screen: no vertex input, no
/// depth or stencil, a target. Such passes fill tables once; their shaders
/// are few. (After Belobug/VIctory-Belobug-AMD 18e57db8.)
pub(crate) fn screen_pass(&self) -> bool {
self.inputs.is_empty()
&& (self.depth_format == DXGI_FORMAT_UNKNOWN
|| !self.depth.DepthEnable.as_bool() && !self.depth.StencilEnable.as_bool())
&& self.targets.NumRenderTargets > 0
&& self.topology == D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE
}
/// Takes in one subobject of a stream: its type, then its data at +4
/// (+8 for those holding pointers).
///
+101 -33
View File
@@ -13,7 +13,13 @@
//! whose pipeline is not ready is dropped, as an untranslated one is.
//!
//! The default budget is half a second per title frame. A pass the title
//! runs only once and whose pipeline takes longer is lost.
//! runs only once and whose pipeline takes longer is lost. Passes over the
//! screen (no vertex input, no depth) have workers and a longer budget of
//! their own ([`screen_budget`]): the title fills its lighting tables with
//! such draws once, at the world's first frame, and behind a world's worth of
//! pipelines they were dropped; that run had no lamps and no diffuse light to
//! its end (run textures-d2, the first after a new translation; Belobug
//! 18e57db8 found the same).
use std::collections::VecDeque;
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
@@ -35,6 +41,8 @@ pub(crate) struct Pending {
/// whether a draw or dispatch has requested it yet.
key: String,
used: AtomicBool,
/// A pass over the screen ([`GraphicsState::screen_pass`]).
screen: bool,
}
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
@@ -52,6 +60,7 @@ impl Pending {
}
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
Pending {
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
shaders,
graphics,
queue_state: AtomicU8::new(NOT_QUEUED),
@@ -124,6 +133,21 @@ fn wait_budget() -> Duration {
})
}
/// As [`wait_budget`], for passes over the screen (`VICTORY_SCREEN_WAIT_MS`,
/// 10 s; 0: like the others). Below the title's 30 s watchdog.
fn screen_budget() -> Duration {
static BUDGET: OnceLock<Duration> = OnceLock::new();
*BUDGET.get_or_init(|| {
let millis = std::env::var("VICTORY_SCREEN_WAIT_MS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(10_000);
Duration::from_millis(millis)
})
}
/// Whether passes over the screen go before the others.
fn screens_first() -> bool {
!screen_budget().is_zero()
}
/// Pipelines queued and not made yet.
static WAITING: AtomicU64 = AtomicU64::new(0);
@@ -178,16 +202,18 @@ fn shared_budget() -> bool {
/// Waits for `p` while frame `frame` has budget left.
fn wait(p: &Pending, frame: u64) {
let budget = wait_budget();
let screen = p.screen && screens_first();
let budget = if screen { screen_budget() } else { wait_budget() };
if budget.is_zero() {
return;
}
// The frame the budget belongs to, and what was waited of it (or is
// taken by a thread waiting now).
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
// taken by a thread waiting now); of the passes over the screen too.
static SPENT: [Mutex<(u64, Duration)>; 2] = [const { Mutex::new((u64::MAX, Duration::ZERO)) }; 2];
let spent_of = &SPENT[usize::from(screen)];
let shared = shared_budget();
let left = {
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner());
if spent.0 != frame {
*spent = (frame, Duration::ZERO);
}
@@ -212,8 +238,16 @@ fn wait(p: &Pending, frame: u64) {
}
drop(held);
let waited = started.elapsed().min(left);
if screen && waited > Duration::from_millis(500) {
tracing::info!(
ms = waited.as_millis() as u64,
made = p.made.get().is_some(),
shaders = ?p.shaders,
"a pass over the screen was waited for (VICTORY_SCREEN_WAIT_MS=0: dropped past half a second a frame)"
);
}
{
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
let mut spent = spent_of.lock().unwrap_or_else(|e| e.into_inner());
// A frame that began meanwhile has its own budget.
if spent.0 == frame {
if shared {
@@ -255,6 +289,9 @@ fn slow_limit() -> usize {
}
struct Queue {
/// Requested passes over the screen: before all others, and the only ones
/// [`SCREEN_WORKERS`] take.
screen: VecDeque<Arc<Pending>>,
early: VecDeque<Arc<Pending>>,
/// Those of the early ones known to take long, and how many of them are
/// being made ([`slow_limit`]).
@@ -266,6 +303,7 @@ struct Queue {
impl Queue {
const fn new() -> Self {
Self {
screen: VecDeque::new(),
early: VecDeque::new(),
slow: VecDeque::new(),
slow_now: 0,
@@ -285,7 +323,9 @@ impl Queue {
return None;
}
p.queue_state.store(priority, Ordering::Relaxed);
if priority == REQUESTED {
if priority == REQUESTED && p.screen && screens_first() {
self.screen.push_back(p.clone());
} else if priority == REQUESTED {
self.requested.push_back(p.clone());
} else if slow {
self.slow.push_back(p.clone());
@@ -295,17 +335,20 @@ impl Queue {
Some(prev == NOT_QUEUED)
}
fn pop(&mut self, slow_limit: usize) -> Option<Arc<Pending>> {
fn pop(&mut self, screens_only: bool, slow_limit: usize) -> Option<Arc<Pending>> {
// An early entry can have been promoted and claimed already.
let unclaimed = |list: &mut VecDeque<Arc<Pending>>| {
std::iter::from_fn(|| list.pop_front()).find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
};
let mut p = self.requested.pop_front().or_else(|| unclaimed(&mut self.early));
if p.is_none() && self.slow_now < slow_limit {
p = unclaimed(&mut self.slow);
if let Some(p) = &p {
p.was_slow.store(true, Ordering::Relaxed);
self.slow_now += 1;
let mut p = self.screen.pop_front();
if p.is_none() && !screens_only {
p = self.requested.pop_front().or_else(|| unclaimed(&mut self.early));
if p.is_none() && self.slow_now < slow_limit {
p = unclaimed(&mut self.slow);
if let Some(p) = &p {
p.was_slow.store(true, Ordering::Relaxed);
self.slow_now += 1;
}
}
}
let p = p?;
@@ -334,14 +377,19 @@ fn start(p: &Arc<Pending>, priority: u8) {
if new {
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
}
AVAILABLE.notify_one();
// (One woken could be a worker that takes passes over the screen
// alone: it would leave the pipeline to nobody.)
AVAILABLE.notify_all();
}
}
fn next() -> Arc<Pending> {
/// Workers that make passes over the screen alone, besides the others.
const SCREEN_WORKERS: usize = 2;
fn next(screens_only: bool) -> Arc<Pending> {
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(p) = queue.pop(slow_limit()) {
if let Some(p) = queue.pop(screens_only, slow_limit()) {
return p;
}
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
@@ -370,14 +418,16 @@ fn workers() -> bool {
std::thread::available_parallelism().map_or(2, |n| n.get()),
);
tracing::info!(workers, "pipeline workers");
for i in 0..workers {
let screens = if screens_first() { SCREEN_WORKERS } else { 0 };
for i in 0..workers + screens {
let screens_only = i >= workers;
let spawned = std::thread::Builder::new()
.name(format!("victory-pipelines-{i}"))
.spawn(|| {
.spawn(move || {
// Below the title's own threads (loading, recording),
// and the streaming one, which is below normal itself
// (`VICTORY_PIPELINE_LOWEST=0`: level with it, as before).
let lowest = std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
let lowest = !screens_only && std::env::var_os("VICTORY_PIPELINE_LOWEST").is_none_or(|v| v != "0");
// SAFETY: a plain call on our own thread.
unsafe {
use windows::Win32::System::Threading::*;
@@ -385,12 +435,12 @@ fn workers() -> bool {
let _ = SetThreadPriority(GetCurrentThread(), priority);
}
loop {
let p = next();
let p = next(screens_only);
p.make();
if p.was_slow.load(Ordering::Relaxed) {
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
queue.slow_now -= 1;
AVAILABLE.notify_one();
AVAILABLE.notify_all();
}
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
drained();
@@ -481,11 +531,11 @@ mod tests {
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
assert_eq!(queue.push(&promoted, REQUESTED), None);
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &requested));
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &promoted));
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &requested));
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &promoted));
assert_eq!(queue.push(&promoted, REQUESTED), None);
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &earlier));
assert!(queue.pop(1).is_none());
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &earlier));
assert!(queue.pop(false, 1).is_none());
}
#[test]
@@ -499,15 +549,33 @@ mod tests {
assert_eq!(queue.push_as(&quick, EARLY, false), Some(true));
// The quick one first, then one long one at a time; one a draw asks
// for waits for nobody.
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &quick));
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &long));
assert!(queue.pop(1).is_none());
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &quick));
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &long));
assert!(queue.pop(false, 1).is_none());
assert_eq!(queue.push_as(&asked, REQUESTED, true), Some(false));
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &asked));
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &asked));
assert!(!asked.was_slow.load(Ordering::Relaxed));
assert!(queue.pop(1).is_none());
assert!(queue.pop(false, 1).is_none());
queue.slow_now -= 1;
assert!(Arc::ptr_eq(&queue.pop(1).unwrap(), &longer));
assert!(queue.pop(1).is_none());
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &longer));
assert!(queue.pop(false, 1).is_none());
}
/// Passes over the screen go before all others, and workers of their own
/// take nothing else.
#[test]
fn passes_over_the_screen_go_first() {
let of = |screen| {
let mut p = Pending::new(Vec::new(), None);
p.screen = screen;
Arc::new(p)
};
let (world, screen) = (of(false), of(true));
let mut queue = Queue::new();
assert_eq!(queue.push(&world, REQUESTED), Some(true));
assert_eq!(queue.push(&screen, REQUESTED), Some(true));
assert!(Arc::ptr_eq(&queue.pop(true, 1).unwrap(), &screen));
assert!(queue.pop(true, 1).is_none());
assert!(Arc::ptr_eq(&queue.pop(false, 1).unwrap(), &world));
}
}
+451
View File
@@ -0,0 +1,451 @@
//! Diagnostics: textures that pop. `VICTORY_POP_WATCH=<from>-<to>[,<from>-<to>..]`
//! (seconds since the start): every presented frame in those times is read
//! back, made small on a thread of its own and compared with its neighbours,
//! block by block. Counted and logged:
//! - blips: blocks that one frame shows otherwise than the frames before and
//! after it, which agree (a texture black, grey or another one for a frame);
//! - steps: blocks that change from one frame to the next and stay so, while
//! most of the picture does not move;
//! - lone blocks: blocks found in neither neighbour, wherever the camera may
//! have moved them, while the neighbours' blocks there are found in each
//! other (a blip while the camera moves).
//!
//! `VICTORY_POP_FOLDER=<folder>`: the three pictures around a frame with
//! blips (at most 200 times) are saved there, 640 wide; with
//! `VICTORY_POP_ALL=1` every frame's is.
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::sync::{Mutex, OnceLock, mpsc};
use windows::Win32::Graphics::Direct3D12::*;
/// A small picture: so many pixels wide and high.
const WIDE: usize = 640;
const HIGH: usize = 360;
/// Pixels per side of a block.
const BLOCK: usize = 16;
/// A block changed: so much in the mean of its pixels' largest channel change.
const CHANGED: f32 = 10.0;
/// A block stayed.
const STAYED: f32 = 4.0;
/// `10-20,30-40` as seconds.
fn parse(text: &str) -> Vec<(f64, f64)> {
text.split(',')
.filter_map(|part| {
let (from, to) = part.trim().split_once('-')?;
Some((from.trim().parse().ok()?, to.trim().parse().ok()?))
})
.collect()
}
fn asked() -> &'static [(f64, f64)] {
static ASKED: OnceLock<Vec<(f64, f64)>> = OnceLock::new();
ASKED.get_or_init(|| std::env::var("VICTORY_POP_WATCH").map(|v| parse(&v)).unwrap_or_default())
}
/// Whether frames are watched now.
pub(crate) fn on() -> bool {
let asked = asked();
if asked.is_empty() {
return false;
}
let now = crate::host::now_ms() as f64 / 1e3;
asked.iter().any(|&(from, to)| now >= from && now < to)
}
/// A frame on its way back.
pub(crate) struct Taken {
buffer: ID3D12Resource,
footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
}
struct Job {
frame: u64,
taken: Taken,
/// The submission that copies it.
flown: u64,
ms: u64,
causes: [u64; 4],
phase: usize,
}
/// Read-back buffers not in use.
static FREE: Mutex<Vec<Taken>> = Mutex::new(Vec::new());
/// How far a block is looked for in a neighbour's picture, in pixels of half
/// the small picture's size, and the side of a block there.
const REACH: i32 = 14;
const HALF_BLOCK: usize = BLOCK / 2;
/// A small picture at half its size, as brightness and two colour differences.
fn half(rgb: &[u8]) -> Vec<[i16; 3]> {
let (w, h) = (WIDE / 2, HIGH / 2);
let mut out = Vec::with_capacity(w * h);
for y in 0..h {
for x in 0..w {
let mut s = [0i16; 3];
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let at = ((y * 2 + dy) * WIDE + x * 2 + dx) * 3;
for (s, v) in s.iter_mut().zip(&rgb[at..at + 3]) {
*s += i16::from(*v);
}
}
out.push(s.map(|s| s / 4));
}
}
out
}
/// Per block of `a`: how much it differs from the place in `b` that is most
/// like it, as [`differ`] says it.
fn moved(a: &[[i16; 3]], b: &[[i16; 3]]) -> Vec<f32> {
let (w, h) = (WIDE / 2, HIGH / 2);
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
let mut out = vec![f32::MAX; across * down];
for (n, best) in out.iter_mut().enumerate() {
let (bx, by) = (n % across * HALF_BLOCK, n / across * HALF_BLOCK);
let mut least = u32::MAX;
for dy in -REACH..=REACH {
let y0 = by as i32 + dy;
if y0 < 0 || y0 as usize + HALF_BLOCK > h {
continue;
}
for dx in -REACH..=REACH {
let x0 = bx as i32 + dx;
if x0 < 0 || x0 as usize + HALF_BLOCK > w {
continue;
}
let mut sum = 0u32;
for row in 0..HALF_BLOCK {
let ra = &a[(by + row) * w + bx..][..HALF_BLOCK];
let rb = &b[(y0 as usize + row) * w + x0 as usize..][..HALF_BLOCK];
sum += ra
.iter()
.zip(rb)
.map(|(p, q)| (0..3).map(|i| p[i].abs_diff(q[i])).max().unwrap_or(0) as u32)
.sum::<u32>();
if sum >= least {
break;
}
}
least = least.min(sum);
}
}
*best = least as f32 / (HALF_BLOCK * HALF_BLOCK) as f32;
}
out
}
/// Blocks of `now` found in neither neighbour, where `before` is found in
/// `after`.
fn lone(before: &[[i16; 3]], now: &[[i16; 3]], after: &[[i16; 3]]) -> Vec<usize> {
let (one, two) = (moved(now, before), moved(now, after));
let both = moved(before, after);
// A cut on either side is none.
if one.iter().filter(|&&d| d > CHANGED).count() * 4 > one.len()
|| two.iter().filter(|&&d| d > CHANGED).count() * 4 > two.len()
{
return Vec::new();
}
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] > CHANGED && both[n] < CHANGED / 2.0).collect()
}
/// Frames on their way.
static WAITING: AtomicU64 = AtomicU64::new(0);
/// Records the read-back of `texture` (in the copy-source state).
pub(crate) fn take(device: &ID3D12Device, list: &ID3D12GraphicsCommandList, texture: &ID3D12Resource) -> Option<Taken> {
if !on() || WAITING.load(Relaxed) > 8 {
return None;
}
let free = FREE.lock().unwrap_or_else(|e| e.into_inner()).pop();
let Some(taken) = free else {
let (buffer, footprint) = crate::capture::read_back(device, list, texture)?;
return Some(Taken { buffer, footprint });
};
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(&taken.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: taken.footprint },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
// SAFETY: an open list, live resources.
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
Some(taken)
}
/// The list with `taken` went to the card as submission `flown` (0: it has
/// run). `frame`: the frame it shows.
pub(crate) fn sent(taken: Taken, flown: u64, frame: u64) {
static THREAD: OnceLock<Option<mpsc::Sender<Job>>> = OnceLock::new();
let Some(to) = THREAD.get_or_init(|| {
let (to, from) = mpsc::channel::<Job>();
std::thread::Builder::new().name("pop watch".into()).spawn(move || watch(&from)).ok().map(|_| to)
}) else {
return;
};
WAITING.fetch_add(1, Relaxed);
let job = Job {
frame,
taken,
flown,
ms: crate::host::now_ms(),
causes: crate::descriptor::host::pop_causes(),
phase: usize::from(crate::ab::pick("VICTORY_KEEP_SHOWN").unwrap_or(false))
+ 2 * usize::from(crate::ab::pick("VICTORY_UPLOAD_AHEAD").unwrap_or(false)),
};
let _ = to.send(job);
}
/// What was seen of the frames so far.
#[derive(Default)]
struct Seen {
frames: u64,
blips: u64,
blip_frames: u64,
steps: u64,
still: u64,
lone: u64,
lone_frames: u64,
}
struct Picture {
frame: u64,
ms: u64,
causes: [u64; 4],
phase: usize,
rgb: Vec<u8>,
half: Vec<[i16; 3]>,
/// Per block: how much it differs from the frame before.
changed: Vec<f32>,
saved: bool,
}
/// Per block, the mean of the pixels' largest channel change.
fn differ(a: &[u8], b: &[u8]) -> Vec<f32> {
let (across, down) = (WIDE / BLOCK, HIGH / BLOCK);
let mut out = vec![0.0; across * down];
for (n, sum) in out.iter_mut().enumerate() {
let (bx, by) = (n % across * BLOCK, n / across * BLOCK);
let mut total = 0u32;
for y in by..by + BLOCK {
let at = (y * WIDE + bx) * 3;
let (ra, rb) = (&a[at..at + BLOCK * 3], &b[at..at + BLOCK * 3]);
total += ra
.chunks_exact(3)
.zip(rb.chunks_exact(3))
.map(|(p, q)| p.iter().zip(q).map(|(x, y)| u32::from(x.abs_diff(*y))).max().unwrap_or(0))
.sum::<u32>();
}
*sum = total as f32 / (BLOCK * BLOCK) as f32;
}
out
}
/// The blips of `now` between `before` and `after`, and its steps (the frame
/// before `before` had `quiet` changes): numbers of blocks. `None` for the
/// steps if the picture moves.
fn judge(before: &[u8], now: &[u8], after: &[u8], quiet: &[f32]) -> (usize, Option<usize>) {
let (one, two, across) = (differ(before, now), differ(now, after), differ(before, after));
let blips = (0..one.len())
.filter(|&n| one[n] > CHANGED && two[n] > CHANGED && across[n] < STAYED && across[n] * 3.0 < one[n])
.count();
let still = one.iter().filter(|&&d| d < 3.0).count() * 10 >= one.len() * 7;
let steps = still.then(|| {
(0..one.len()).filter(|&n| one[n] > CHANGED && two[n] < STAYED && quiet.get(n).is_some_and(|&d| d < STAYED)).count()
});
(blips, steps)
}
/// `width * height` 8-bit RGBA (or BGRA) pixels made small.
fn small(rows: &[u8], width: usize, height: usize, pitch: usize, bgra: bool) -> Vec<u8> {
let mut out = Vec::with_capacity(WIDE * HIGH * 3);
for y in 0..HIGH {
for x in 0..WIDE {
let mut sum = [0u32; 3];
for sy in 0..3 {
for sx in 0..3 {
let px = ((x * 3 + sx) * 2 + 1) * width / (WIDE * 6);
let py = ((y * 3 + sy) * 2 + 1) * height / (HIGH * 6);
let p = &rows[py.min(height - 1) * pitch + px.min(width - 1) * 4..][..3];
for (s, v) in sum.iter_mut().zip(p) {
*s += u32::from(*v);
}
}
}
let c = sum.map(|s| (s / 9) as u8);
out.extend(if bgra { [c[2], c[1], c[0]] } else { c });
}
}
out
}
fn folder() -> Option<&'static PathBuf> {
static FOLDER: OnceLock<Option<PathBuf>> = OnceLock::new();
FOLDER
.get_or_init(|| {
let folder = PathBuf::from(std::env::var_os("VICTORY_POP_FOLDER")?);
std::fs::create_dir_all(&folder).ok()?;
Some(folder)
})
.as_ref()
}
fn save(p: &mut Picture) {
if p.saved {
return;
}
p.saved = true;
if let Some(folder) = folder() {
let png = crate::capture::png(WIDE as u32, HIGH as u32, &p.rgb);
let _ = std::fs::write(folder.join(format!("{:07}-f{}.png", p.ms, p.frame)), png);
}
}
fn watch(from: &mpsc::Receiver<Job>) {
let all = std::env::var_os("VICTORY_POP_ALL").is_some_and(|v| v == "1");
let mut last: VecDeque<Picture> = VecDeque::new();
let mut seen: [Seen; 4] = Default::default();
let mut told = crate::host::now_ms();
let mut sets = 0;
while let Ok(job) = from.recv() {
while crate::host::submissions().1 < job.flown {
std::thread::sleep(std::time::Duration::from_millis(1));
}
let f = job.taken.footprint.Footprint;
let (rgba, bgra) = (matches!(f.Format.0, 27..=29), matches!(f.Format.0, 87 | 90 | 91));
let mut data = std::ptr::null_mut();
// SAFETY: the copy has run; the mapping spans the footprint's rows.
let rgb = unsafe {
if !(rgba || bgra) || job.taken.buffer.Map(0, None, Some(&mut data)).is_err() {
WAITING.fetch_sub(1, Relaxed);
continue;
}
let rows = std::slice::from_raw_parts(data.cast::<u8>(), f.RowPitch as usize * f.Height as usize);
let rgb = small(rows, f.Width as usize, f.Height as usize, f.RowPitch as usize, bgra);
job.taken.buffer.Unmap(0, None);
rgb
};
FREE.lock().unwrap_or_else(|e| e.into_inner()).push(job.taken);
WAITING.fetch_sub(1, Relaxed);
// Frames that follow each other only.
if last.back().is_some_and(|p| p.frame + 1 != job.frame) {
last.clear();
}
let changed = last.back().map(|p| differ(&p.rgb, &rgb)).unwrap_or_default();
let (frame, ms, causes, phase) = (job.frame, job.ms, job.causes, job.phase);
let half = half(&rgb);
last.push_back(Picture { frame, ms, causes, phase, rgb, half, changed, saved: false });
if all && let Some(p) = last.back_mut() {
save(p);
}
if last.len() > 4 {
last.pop_front();
}
if let [first, before, now, after] = last.make_contiguous() {
let (blips, steps) = judge(&before.rgb, &now.rgb, &after.rgb, &before.changed);
let side = &mut seen[now.phase];
side.frames += 1;
side.blips += blips as u64;
side.blip_frames += u64::from(blips > 0);
side.still += u64::from(steps.is_some());
side.steps += steps.unwrap_or(0) as u64;
let lone = lone(&before.half, &now.half, &after.half);
side.lone += lone.len() as u64;
side.lone_frames += u64::from(!lone.is_empty());
if blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 0) {
let since: Vec<u64> = now.causes.iter().zip(&first.causes).map(|(a, b)| a.saturating_sub(*b)).collect();
tracing::info!(
"pop watch: frame {} at {:.2} s: {blips} blips, {steps:?} steps, lone blocks {lone:?}; in the two frames before it [made null for another texture, kept, neutral, stale] {since:?}",
now.frame,
now.ms as f64 / 1e3
);
}
if (blips > 0 || lone.len() > 1 || steps.is_some_and(|s| s > 2)) && sets < 200 {
sets += 1;
save(before);
save(now);
save(after);
}
}
if crate::host::now_ms().saturating_sub(told) > 5000 {
told = crate::host::now_ms();
for (n, s) in seen.iter().enumerate().filter(|(_, s)| s.frames > 0) {
tracing::info!(
"pop watch, since the start, A/B VICTORY_KEEP_SHOWN {} VICTORY_UPLOAD_AHEAD {}: {} frames, blips in {} of them ({} blocks of 16x16), {} frames whose picture stood still with {} blocks stepped, lone blocks in {} frames ({} blocks)",
n & 1,
n >> 1,
s.frames,
s.blip_frames,
s.blips,
s.still,
s.steps,
s.lone_frames,
s.lone
);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn picture(color: u8) -> Vec<u8> {
vec![color; WIDE * HIGH * 3]
}
fn patch(p: &mut [u8], bx: usize, by: usize, color: u8) {
for y in by * BLOCK..(by + 1) * BLOCK {
let at = (y * WIDE + bx * BLOCK) * 3;
p[at..at + BLOCK * 3].fill(color);
}
}
#[test]
fn one_frame_otherwise_is_a_blip_and_a_lasting_change_a_step() {
let (a, mut b) = (picture(100), picture(100));
patch(&mut b, 3, 4, 0);
let quiet = vec![0.0; (WIDE / BLOCK) * (HIGH / BLOCK)];
assert_eq!(judge(&a, &b, &a, &quiet), (1, Some(0)));
assert_eq!(judge(&a, &b, &b, &quiet), (0, Some(1)));
assert_eq!(judge(&a, &a, &a, &quiet), (0, Some(0)));
// All of it changes: a cut, no step.
assert_eq!(judge(&a, &picture(0), &picture(0), &quiet), (0, None));
// What moved just before is no step either.
assert_eq!(judge(&a, &b, &b, &vec![9.0; quiet.len()]), (0, Some(0)));
}
#[test]
fn a_block_one_frame_alone_shows_is_found_while_the_camera_moves() {
// A picture of noise, moved by 6 pixels a frame.
let at = |shift: usize| -> Vec<u8> {
(0..HIGH)
.flat_map(|y| (0..WIDE).map(move |x| ((x + shift) / 8 * 37 + y / 8 * 91) as u8))
.flat_map(|v| [v, v.wrapping_mul(3), 255 - v])
.collect()
};
let (a, mut b, c) = (at(0), at(8), at(16));
assert!(lone(&half(&a), &half(&b), &half(&c)).is_empty());
patch(&mut b, 20, 10, 128);
assert_eq!(lone(&half(&a), &half(&b), &half(&c)), vec![10 * (WIDE / BLOCK) + 20]);
}
#[test]
fn times_are_read_and_pictures_made_small() {
assert_eq!(parse("10-20, 30.5-40"), vec![(10.0, 20.0), (30.5, 40.0)]);
assert!(parse("x").is_empty());
let rows: Vec<u8> = [1u8, 2, 3, 255].repeat(1280 * 720);
let out = small(&rows, 1280, 720, 1280 * 4, true);
assert_eq!((out.len(), &out[..3]), (WIDE * HIGH * 3, &[3u8, 2, 1][..]));
}
}
+1
View File
@@ -985,6 +985,7 @@ extern "system" fn present(
#[cfg(all(windows, feature = "diagnostics"))]
fn frame_ends() {
crate::timeline::presented();
crate::faultbook::frame();
crate::ab::presented(|switch, was, will| {
if switch == "VICTORY_ASYNC_SUBMIT" && was && !will {
behind::leave();
+198 -16
View File
@@ -74,6 +74,14 @@ pub(super) trait Work: Send {
}
/// Waits until a folded one is free to go.
fn settle(_: &Self::Ask) {}
/// Takes `next`, what its queue was given behind it, along to be done with
/// it; or gives it back. Whether it is a submission that was taken.
fn take_along(&mut self, next: Self) -> Result<bool, Self>
where
Self: Sized,
{
Err(next)
}
/// Does it. `forced`: its wait was not met.
fn go(self, forced: bool);
}
@@ -245,6 +253,17 @@ impl<W: Work> Lane<W> {
while self.step(limit) {}
}
/// The parts of `entry`, which stands for them, in place `at`.
fn unfold(state: &mut State<W>, at: usize, entry: Entry<W>) {
let (number, queue, runs) = (entry.number, entry.queue, usize::from(entry.what.runs()));
let parts = entry.what.unfold();
state.runs -= runs;
state.runs += parts.iter().filter(|p| p.runs()).count();
for (i, what) in parts.into_iter().enumerate() {
state.items.insert(at + i, Entry { number, queue, what });
}
}
/// Does one entry: the oldest that is the first of its queue and free to
/// run. Whether there was one. Only one thread calls this.
fn step(&self, limit: u64) -> bool {
@@ -286,7 +305,7 @@ impl<W: Work> Lane<W> {
(first, true)
}
};
let entry = {
let mut entry = {
let mut state = self.lock();
let Some(at) = state.items.iter().position(|e| e.number == number) else {
return false;
@@ -297,31 +316,56 @@ impl<W: Work> Lane<W> {
state.running = Some(entry.queue);
entry
};
let (shows, runs) = (entry.what.shows(), entry.what.runs());
let (shows, mut runs) = (entry.what.shows(), usize::from(entry.what.runs()));
if entry.what.folded() {
// Its parts take its place: behind everything before it, before
// everything after it (they share its number; the first of them
// is found first).
let (number, queue) = (entry.number, entry.queue);
let parts = entry.what.unfold();
let mut state = self.lock();
state.running = None;
state.runs -= usize::from(runs);
state.runs += parts.iter().filter(|p| p.runs()).count();
let place = state.items.iter().position(|e| e.number > number).unwrap_or(state.items.len());
for (i, what) in parts.into_iter().enumerate() {
state.items.insert(place + i, Entry { number, queue, what });
}
let at = state.items.iter().position(|e| e.number > entry.number).unwrap_or(state.items.len());
Self::unfold(&mut state, at, entry);
drop(state);
self.moved.notify_all();
return true;
}
// What follows it in its queue, if that can go with it. (Nobody else
// takes anything out, and what comes in goes to the end.)
while runs > 0 && !forced {
let next = {
let mut state = self.lock();
let at = state.items.iter().position(|e| e.queue == entry.queue && e.number < limit);
at.and_then(|at| Some((at, state.items.remove(at)?)))
};
let Some((at, next)) = next else {
break;
};
// (Back where it was: parts of one submission share a number.)
if next.what.folded() {
let free = next.what.ask().is_none_or(|ask| W::met(&ask));
let mut state = self.lock();
if free {
Self::unfold(&mut state, at, next);
continue;
}
state.items.insert(at, next);
break;
}
let Entry { number, queue, what } = next;
match entry.what.take_along(what) {
Ok(run) => runs += usize::from(run),
Err(what) => {
self.lock().items.insert(at, Entry { number, queue, what });
break;
}
}
}
entry.what.go(forced);
{
let mut state = self.lock();
state.running = None;
state.presents -= usize::from(shows);
state.runs -= usize::from(runs);
state.runs -= runs;
}
self.moved.notify_all();
true
@@ -342,6 +386,9 @@ enum Job {
/// A submission whose lists are being translated ([`crate::list::thin`]):
/// the parts of it are known when they are.
Lists(usize, Recordings),
/// Parts taken along with a submission ([`crate::host::joins`]): where they
/// begin in the order, and the signals given behind them.
Joined(usize, Vec<crate::list::Detached>, Vec<usize>, Vec<usize>, Vec<(usize, u64)>),
/// A signal of the queue's.
Signal(usize, u64),
/// A frame is shown: the texture and the state its lists leave it in.
@@ -408,13 +455,73 @@ impl Work for Job {
}
fn runs(&self) -> bool {
matches!(self, Job::Run(..) | Job::Lists(..))
matches!(self, Job::Run(..) | Job::Joined(..) | Job::Lists(..))
}
fn take_along(&mut self, next: Job) -> Result<bool, Job> {
let (most, most_lists) = crate::host::joins();
if most < 2 {
return Err(next);
}
// Nothing but waits and signals that a submission may follow.
let (count, lists, signals) = match self {
Job::Run(_, lists, order) => (1, (&*lists, &*order), &[][..]),
Job::Joined(_, lists, order, parts, signals) => (1 + parts.len(), (&*lists, &*order), &signals[..]),
_ => return Err(next),
};
let hosts = || lists.1.iter().map(|&i| lists.0[i].host());
match &next {
Job::Value(wait) => {
let met = wait.met()
|| crate::host::late_met_known(wait) == Some(true)
|| hosts().any(|list| crate::host::will_meet(list, wait));
if !met {
return Err(next);
}
}
&Job::Wait(fence, value) => {
if crate::fence::completed(fence as This) < value && !signals.iter().any(|&(f, v)| f == fence && v >= value) {
return Err(next);
}
}
Job::Signal(..) => {}
Job::Run(_, more, order) => {
let runs: Vec<&crate::host::HostList> = order.iter().map(|&i| more[i].host()).collect();
if count >= most || lists.1.len() + runs.len() > most_lists || !crate::host::joinable(hosts(), &runs) {
return Err(next);
}
}
Job::Joined(..) | Job::Present(..) | Job::Lists(..) => return Err(next),
}
let taken = std::mem::replace(self, Job::Wait(0, 0));
let (queue, mut lists, mut order, mut parts, mut signals) = match taken {
Job::Run(queue, lists, order) => (queue, lists, order, Vec::new(), Vec::new()),
Job::Joined(queue, lists, order, parts, signals) => (queue, lists, order, parts, signals),
other => {
*self = other;
return Err(next);
}
};
let run = matches!(next, Job::Run(..));
match next {
Job::Run(_, more, then) => {
parts.push(order.len());
order.extend(then.into_iter().map(|i| i + lists.len()));
lists.extend(more);
STATS[JOINED].fetch_add(1, Relaxed);
}
Job::Signal(fence, value) => signals.push((fence, value)),
_ => {}
}
*self = Job::Joined(queue, lists, order, parts, signals);
Ok(run)
}
fn go(self, forced: bool) {
let began = Instant::now();
let _doing = crate::timeline::span(match self {
Job::Run(..) => "the line: a submission",
Job::Joined(..) => "the line: submissions joined",
Job::Present(..) => "the line: a present",
Job::Signal(..) => "the line: a signal",
_ => "the line: a wait that is met",
@@ -439,6 +546,24 @@ impl Work for Job {
}
QUEUED.fetch_sub(1, Relaxed);
}
Job::Joined(queue, lists, order, parts, signals) => {
let _ = queue;
#[cfg(feature = "diagnostics")]
crate::capture::op(queue, || {
format!("RUN {} parts of submissions in one, {} lists (its thread's)", 1 + parts.len(), order.len())
});
match crate::host::host() {
Some(host) => host.execute_parts(lists, order, &parts),
None => drop(lists),
}
// (A part that had no list is one all the same.)
QUEUED.fetch_sub(1 + parts.len() as u64, Relaxed);
for (fence, value) in signals {
if !crate::host::late_signal(fence, value) {
crate::fence::set(fence as This, value);
}
}
}
Job::Signal(fence, value) => {
if !crate::host::late_signal(fence, value) {
crate::fence::set(fence as This, value);
@@ -469,7 +594,7 @@ static QUEUED: AtomicU64 = AtomicU64::new(0);
/// threads of the title waited, in microseconds, for room in the line, at a
/// present, and for a drain, and the drains; what our thread worked; waits
/// not met at a present.
static STATS: [AtomicU64; 10] = [const { AtomicU64::new(0) }; 10];
static STATS: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11];
const RUNS: usize = 0;
const PRESENTS: usize = 1;
const DEPTH: usize = 2;
@@ -480,6 +605,8 @@ const DRAINING: usize = 6;
const DRAINS: usize = 7;
const BUSY: usize = 8;
const FORCED: usize = 9;
/// Parts prepared together with the one before them.
const JOINED: usize = 10;
/// How many submissions may be in the line when a submit call returns
/// (`VICTORY_SUBMIT_DEPTH`; 64: about two frames of the title's).
@@ -701,7 +828,8 @@ pub(super) fn line(frames: f64) {
tracing::info!(
"submissions prepared by a thread of ours, per frame (VICTORY_ASYNC_SUBMIT): {:.1} in {:.1} presents, {:.1} in the line \
when one was added (at most {:.0}); that thread worked {:.1} ms; threads of the title waited {:.1} ms for room in the \
line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}",
line, {:.1} ms at presents, {:.1} ms in {:.1} drains; waits not met at a present {:.2}; {:.1} of the \
submissions were prepared together with the one before them (VICTORY_JOIN_PARTS)",
s[RUNS] / frames,
s[PRESENTS] / frames,
s[DEPTH] / s[RUNS].max(1.0),
@@ -711,7 +839,8 @@ pub(super) fn line(frames: f64) {
ms(AT_PRESENT),
ms(DRAINING),
s[DRAINS] / frames,
s[FORCED] / frames
s[FORCED] / frames,
s[JOINED] / frames
);
}
@@ -731,6 +860,8 @@ mod tests {
Slow(&'static str, Log, Arc<(Mutex<bool>, Condvar)>),
Signal(usize, u64, Log),
Present(&'static str, Log),
/// Takes others of its kind, waits that are met, and signals along.
Group(Vec<&'static str>, Log, Vec<(usize, u64)>),
}
impl Work for T {
@@ -748,7 +879,24 @@ mod tests {
matches!(self, T::Present(..))
}
fn runs(&self) -> bool {
matches!(self, T::Run(..) | T::Slow(..))
matches!(self, T::Run(..) | T::Slow(..) | T::Group(..))
}
fn take_along(&mut self, next: T) -> Result<bool, T> {
let T::Group(names, _, signals) = self else {
return Err(next);
};
match next {
T::Group(more, ..) if names.len() < 3 => {
names.extend(more);
Ok(true)
}
T::Wait(f, v) if crate::fence::completed(f as This) >= v || signals.contains(&(f, v)) => Ok(false),
T::Signal(f, v, _) => {
signals.push((f, v));
Ok(false)
}
other => Err(other),
}
}
fn go(self, forced: bool) {
match self {
@@ -769,6 +917,12 @@ mod tests {
log.lock().unwrap().push(format!("signal {value}"));
crate::fence::set(fence as This, value);
}
T::Group(names, log, signals) => {
log.lock().unwrap().push(names.join("+"));
for (fence, value) in signals {
crate::fence::set(fence as This, value);
}
}
}
}
}
@@ -814,6 +968,34 @@ mod tests {
assert!(done);
}
/// A submission takes what follows it in its queue along, up to what it
/// cannot take, which stays at its place; the counts come out even.
#[test]
fn submissions_take_those_behind_them_along() {
let lane = Lane::new();
let log: Log = Default::default();
let f = fence();
let part = |name| T::Group(vec![name], log.clone(), Vec::new());
lane.push(1, [part("a"), T::Wait(f, 0), part("b")]);
lane.push(2, [part("other queue"), T::Wait(f, 1), part("behind a's signal")]);
lane.push(1, [T::Signal(f, 1, log.clone()), T::Wait(f, 1), part("c"), part("d")]);
lane.push(1, [T::Wait(f, 9), part("held"), T::Present("present", log.clone()), part("next frame")]);
// What came after the look was asked for is not touched.
let limit = lane.lock().next;
lane.push(1, [part("later")]);
lane.look(limit);
assert_eq!(
*log.lock().unwrap(),
["a+b+c", "other queue+behind a's signal", "d", "held", "present", "next frame"],
"{:?}",
lane.lock().items.len()
);
look(&lane);
assert_eq!(log.lock().unwrap().last().unwrap(), "later");
let state = lane.lock();
assert_eq!((state.presents, state.runs, state.items.len()), (0, 0, 0));
}
/// A wait that nothing meets holds its queue until a present, which
/// comes behind everything given before it and before what comes after.
#[test]
+6
View File
@@ -393,6 +393,12 @@ impl Drop for Ours {
}
}
/// While what this returns lives, this thread's D3D12 calls are not
/// recorded.
pub(crate) fn unrecorded() -> impl Drop {
Ours::new()
}
fn ours() -> bool {
OURS.with(|o| o.get() > 0)
}
+11
View File
@@ -1177,6 +1177,8 @@ pub(crate) struct HostTexture {
pub(crate) grown: std::sync::atomic::AtomicBool,
/// What the last submitted upload put in it.
pub(crate) holds: std::sync::Arc<Holds>,
/// Who makes its first upload (`crate::texture::ahead`).
pub(crate) ahead: std::sync::atomic::AtomicU8,
/// The texture's flags (asked once: the runtime takes 100 ns to say, and
/// every texture of every draw is asked about).
flags: u32,
@@ -2295,6 +2297,7 @@ impl HostTexture {
serial: SERIAL.fetch_add(1, Relaxed) + 1,
grown: Default::default(),
holds: Default::default(),
ahead: crate::texture::ahead::fresh(),
flags,
}
}
@@ -2319,6 +2322,7 @@ impl HostTexture {
serial: SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1,
grown: Default::default(),
holds: Default::default(),
ahead: crate::texture::ahead::fresh(),
flags,
}
}
@@ -2968,6 +2972,13 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option<This> {
Some(*found as This)
}
/// From which level on the title texture's host copy was filled, and from
/// which bytes (diagnostics).
#[cfg(all(windows, feature = "diagnostics"))]
pub(crate) fn texture_held(resource: This) -> Option<(u32, crate::texture::Digest)> {
*made_copy(resource)?.holds.lock().unwrap_or_else(|e| e.into_inner())
}
/// The resource for a texture placed at `address` with the resource
/// description `desc` (as words), made on first use.
#[cfg(windows)]
+2
View File
@@ -73,6 +73,8 @@ fn build() -> [u8; 32] {
"VICTORY_FIRST_HALF",
"VICTORY_STRICT_JOINS",
"VICTORY_MESH_OUTPUT_STRICT",
"VICTORY_BVH_FENCES",
"VICTORY_BVH_BOUNDS",
] {
bytes.extend_from_slice(name.as_bytes());
bytes.push(b'=');
+409 -75
View File
@@ -26,6 +26,12 @@ use crate::watch::PAGE;
/// A title buffer's host copy.
pub(crate) struct Shadow {
/// Title memory's pages of 4 KiB (from the one `start` lies in on), a bit
/// each, that what shaders wrote was put into since a refresh last looked
/// at them ([`Shadow::take_landed`]); empty until then.
landings: Mutex<Vec<u64>>,
/// Whether any is.
landing: std::sync::atomic::AtomicBool,
/// The bytes of `buffer`, once asked.
width: std::sync::OnceLock<u64>,
pub(crate) buffer: ID3D12Resource,
@@ -736,7 +742,7 @@ fn joined(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> {
/// so a piece that held several ranges was hashed once for each.
pub(crate) fn joined_piece_runs(mut runs: Vec<CardSpan>) -> Vec<CardSpan> {
runs.sort_unstable_by_key(|r| r.first);
let mut out: Vec<CardSpan> = Vec::with_capacity(runs.len());
let mut out: Vec<CardSpan> = Vec::new();
for run in runs {
match out.last_mut() {
Some(last) if run.first <= last.first + last.pieces => {
@@ -1438,6 +1444,25 @@ type Job = Box<dyn FnOnce() + Send>;
struct Workers {
jobs: Mutex<std::collections::VecDeque<Job>>,
more: std::sync::Condvar,
/// How many jobs there are, for [`spin`].
there: std::sync::atomic::AtomicUsize,
}
/// Waits awake until `there` says so, `VICTORY_WIDE_SPIN` microseconds at
/// most (0, the default: not at all): asleep, a thread is woken in 50 us and
/// more, 95 times a frame.
fn spin(there: impl Fn() -> bool) {
static MOST: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
let most = *MOST.get_or_init(|| std::env::var("VICTORY_WIDE_SPIN").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0));
if most == 0 {
return;
}
let began = std::time::Instant::now();
while !there() && (began.elapsed().as_micros() as u64) < most {
for _ in 0..16 {
std::hint::spin_loop();
}
}
}
/// How many threads are kept for [`wide`].
@@ -1451,6 +1476,7 @@ fn workers() -> &'static Workers {
let workers = WORKERS.get_or_init(|| Workers {
jobs: Mutex::new(std::collections::VecDeque::new()),
more: std::sync::Condvar::new(),
there: std::sync::atomic::AtomicUsize::new(0),
});
STARTED.call_once(|| {
for i in 0..wide_threads() {
@@ -1459,9 +1485,13 @@ fn workers() -> &'static Workers {
let workers = WORKERS.get().expect("made above");
loop {
let job = {
// A little while awake first: the next work comes
// within microseconds more often than not.
spin(|| workers.there.load(Ordering::Acquire) > 0);
let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
loop {
if let Some(job) = jobs.pop_front() {
workers.there.fetch_sub(1, Ordering::AcqRel);
break job;
}
jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner());
@@ -1492,6 +1522,7 @@ fn wide(jobs: Vec<Job>) {
let mut queue = workers.jobs.lock().unwrap_or_else(|e| e.into_inner());
for job in jobs {
let left = left.clone();
workers.there.fetch_add(1, Ordering::AcqRel);
queue.push_back(Box::new(move || {
job();
let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
@@ -1506,10 +1537,14 @@ fn wide(jobs: Vec<Job>) {
loop {
let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front();
match job {
Some(job) => job(),
Some(job) => {
workers.there.fetch_sub(1, Ordering::AcqRel);
job()
}
None => break,
}
}
spin(|| left.0.try_lock().is_ok_and(|n| *n == 0));
let mut n = left.0.lock().unwrap_or_else(|e| e.into_inner());
while *n > 0 {
n = left.1.wait(n).unwrap_or_else(|e| e.into_inner());
@@ -1949,6 +1984,29 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
runs
}
/// The kernel's page.
const KERNEL_PAGE: usize = 4096;
/// Whether a refresh looks if what counts as written is only what a landing
/// put there, and then sends nothing of it up (`VICTORY_LAND_ECHO=0`: it copies
/// and sends it, as before).
///
/// What shaders wrote comes down, goes into title memory and into the CPU's
/// side of the copy alike. In memory the kernel watches that is a write like
/// any other (it cannot be told as the guards' blocks can, `crate::land`), and
/// the next refresh of it copied the pages and sent them up again: in the dorm
/// 14.4 MB a frame of one copy of 90 MB whose 263 pieces were all fetched and
/// all sent, 28 of 72 MB over the bus in all (run submit-2). Only pages a
/// landing was noted in are compared, 4 KiB at a time: a page that is not the
/// same goes up whole, as before, and so does every other.
fn land_echo() -> bool {
crate::toggled!("VICTORY_LAND_ECHO")
}
/// Since the last frame-rate line: bytes found to be a landing's alone, and
/// bytes a landing was noted in that were the title's too.
pub(crate) static ECHO: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
/// Whether a refresh of a copy in the card's memory takes, and sends up,
/// the dwords that title memory changed and no others
/// (`VICTORY_SEND_CHANGED=1`; off: the 64 KiB pages written since it last
@@ -2030,6 +2088,68 @@ fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize,
runs
}
/// [`dword_runs`] with no gap, the fast way where it can be: a frame compares
/// 12 MB this way and finds 80,000 runs.
fn word_runs(at: usize, title: &[u8], held: &[u8]) -> Vec<(usize, usize)> {
#[cfg(target_arch = "x86_64")]
if at % 4 == 0 && title.len() % 4 == 0 && title.len() == held.len() && std::arch::is_x86_feature_detected!("avx2") {
// SAFETY: the processor has AVX2, and the lengths are the same.
return unsafe { word_runs_avx2(title, held) };
}
dword_runs(at, title, held, 0)
}
/// # Safety
/// AVX2, and two slices of one length, whole words.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
unsafe fn word_runs_avx2(title: &[u8], held: &[u8]) -> Vec<(usize, usize)> {
use std::arch::x86_64::*;
let mut runs: Vec<(usize, usize)> = Vec::new();
let mut push = |from: usize, len: usize| match runs.last_mut() {
Some((a, n)) if *a + *n == from => *n += len,
_ => runs.push((from, len)),
};
let n = title.len();
let mut i = 0;
while i + 256 <= n {
let mut differ = 0u64;
for k in 0..8 {
// SAFETY: inside both slices (`i + 256 <= n`).
let same = unsafe {
_mm256_cmpeq_epi32(
_mm256_loadu_si256(title.as_ptr().add(i + 32 * k).cast()),
_mm256_loadu_si256(held.as_ptr().add(i + 32 * k).cast()),
)
};
differ |= u64::from(!_mm256_movemask_ps(_mm256_castsi256_ps(same)) as u8) << (8 * k);
}
while differ != 0 {
let first = differ.trailing_zeros();
let count = (differ >> first).trailing_ones();
push(i + 4 * first as usize, 4 * count as usize);
if first + count >= 64 {
break;
}
differ &= u64::MAX << (first + count);
}
i += 256;
}
while i + 4 <= n {
if title[i..i + 4] != held[i..i + 4] {
push(i, 4);
}
i += 4;
}
runs
}
/// Whether the pages of [`Shadow::merge_under_writes`] are compared on several
/// threads (`VICTORY_UNDER_WIDE=0`: on the submitting one).
fn under_wide() -> bool {
crate::toggled!("VICTORY_UNDER_WIDE")
}
/// What shaders wrote goes into title memory from `at` on: `title` is what
/// was read there, `merged` the same with their bytes put in. Only the
/// dwords that differ are written. The whole stretch from the first changed
@@ -2111,7 +2231,7 @@ pub(crate) fn land_as_before(start: usize, now: usize, held: usize, n: usize, ti
#[cfg(test)]
mod merge_tests {
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed};
use super::{PIECE, back_piece, changed_runs, dword_runs, put_changed, word_runs};
/// A piece put back takes the GPU's bytes where the copy changed and
/// the title's everywhere else, reads and writes title memory only from
@@ -2282,6 +2402,31 @@ mod merge_tests {
println!("64 KiB that are the same: {:.1} us by eights, {:.1} us now", best(&eights), best(&runs));
}
#[test]
fn word_runs_are_the_dword_runs() {
let mut seed = 7u32;
let mut random = move || {
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
seed >> 8
};
for round in 0..200 {
let n = 4 * (random() as usize % 400);
let was: Vec<u8> = (0..n).map(|_| random() as u8).collect();
let mut now = was.clone();
for _ in 0..random() % 200 {
if n == 0 {
break;
}
let at = random() as usize % n;
let len = (random() as usize % 24).min(n - at);
for b in &mut now[at..at + len] {
*b = random() as u8;
}
}
assert_eq!(word_runs(0x1000, &now, &was), dword_runs(0x1000, &now, &was, 0), "round {round}");
}
}
#[test]
fn changed_runs_are_exactly_the_bytes_that_differ() {
let was: Vec<u8> = (0..300u32).map(|i| (i * 13 + 5) as u8).collect();
@@ -2479,6 +2624,49 @@ fn by_parts(runs: Vec<(usize, usize, bool)>, pages: &[(usize, u64)], parts: &[u1
out
}
#[cfg(test)]
mod landing_tests {
use super::{KERNEL_PAGE, Shadow};
/// A page that only a landing wrote is not sent up again; one the title
/// wrote too is, and so is every page no landing was noted in.
#[test]
fn what_a_landing_wrote_is_not_sent_up_again() {
const PAGES: usize = 6;
let room = vec![7u8; (PAGES + 1) * KERNEL_PAGE];
let title = room.as_ptr() as usize;
let title = title.next_multiple_of(KERNEL_PAGE);
let mut side = vec![7u8; PAGES * KERNEL_PAGE];
let copy = Shadow::unbacked(title as u64, side.as_mut_ptr(), side.len() as u64, true);
let write = |page: usize| {
// SAFETY: in `room`.
unsafe { ((title + page * KERNEL_PAGE + 9) as *mut u8).write_volatile(8) }
};
let page = |from: usize, to: usize| (title + from * KERNEL_PAGE, title + to * KERNEL_PAGE);
copy.note_landing(KERNEL_PAGE, 4 * KERNEL_PAGE);
// Page 2: the title's too.
write(2);
let (from, to) = page(0, 6);
copy.take_landed(from, to);
let mut dirty = copy.take_dirty();
dirty.sort_unstable();
let part = |a: usize, b: usize| (a * KERNEL_PAGE, b * KERNEL_PAGE);
assert_eq!(super::joined(dirty), [part(0, 1), part(2, 3), part(4, 6)]);
assert_eq!(side[2 * KERNEL_PAGE + 9], 8);
// Looked at: from here on as any other.
let (from, to) = page(1, 2);
copy.take_landed(from, to);
assert_eq!(copy.take_dirty(), [part(1, 2)]);
// In part: looked at again when the rest is.
copy.note_landing(3 * KERNEL_PAGE, 3 * KERNEL_PAGE + 1);
let (from, to) = page(3, 4);
copy.take_landed(from, from + 100);
copy.take_landed(from, to);
assert_eq!(copy.take_dirty(), []);
drop(room);
}
}
#[cfg(test)]
mod parts_tests {
use super::{PAGE, by_parts};
@@ -2754,6 +2942,8 @@ impl Shadow {
LIVE[0].fetch_add(1, Ordering::Relaxed);
LIVE[1].fetch_add(len, Ordering::Relaxed);
Shadow {
landings: Mutex::default(),
landing: Default::default(),
width: Default::default(),
buffer,
data,
@@ -3303,7 +3493,6 @@ impl Shadow {
// copy in the PC's memory in the snapshot.
let busy = if crate::watch::light() { joined(busy) } else { busy };
let base = start / PAGE;
let mut title = vec![0u8; PAGE];
for (a, e) in busy {
// As the refresh itself asks (`update_free`): the journal if
// the submission's asking covered the range, else the kernel,
@@ -3319,89 +3508,150 @@ impl Shadow {
let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
stale_pages_in(base, &copied, a, e, &written)
};
for page in stale {
let (lo, hi) = ((page * PAGE).max(a), ((page + 1) * PAGE).min(e));
if lo >= hi {
if stale.is_empty() {
continue;
}
// The lock of the copy's reference (the snapshot, or the
// CPU's side of a copy in the card's memory), from before
// title memory is read until the title's bytes are in: with
// the copy-back on its own thread ([`relay`]) that thread
// puts what the card wrote into title memory and into the
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
let held = if self.card.is_some() {
self.data as usize
} else {
before.as_mut().map_or(0, |snapshot| snapshot.as_mut_ptr() as usize)
};
if held == 0 {
note_stale(3);
return true;
}
// A page's part in the range, compared and put in: the runs it
// changed; none for a page that is not there (left as it is, and
// looked at again next time) or that had too many.
type Done = Option<Vec<(usize, usize)>>;
let left = std::sync::atomic::AtomicI64::new(*runs_left as i64);
let over = std::sync::atomic::AtomicBool::new(false);
let done: Vec<Mutex<Done>> = stale.iter().map(|_| Mutex::new(None)).collect();
let page_of = |i: usize| -> (usize, usize) { ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e)) };
let one = |i: usize| {
let (lo, hi) = page_of(i);
if lo < hi && !over.load(Ordering::Relaxed) {
// SAFETY: the reference holds the copy's bytes at the
// copy's offsets, and these are in a declared range; the
// locks held above keep out what else writes them, and
// no two pages are the same.
let runs = unsafe { self.merge_page_under_writes(lo, hi - lo, held as *mut u8, &left) };
match runs {
Ok(runs) => *done[i].lock().unwrap_or_else(|e| e.into_inner()) = runs,
Err(()) => over.store(true, Ordering::Relaxed),
}
}
};
// (Not on the threads of `wide`: the thread that waits there
// takes whatever work comes, and a landing's takes the lock.)
if stale.len() > 2 && under_wide() {
crate::land::each_under(stale.len(), &one);
} else {
(0..stale.len()).for_each(one);
}
*runs_left = left.into_inner().max(0) as usize;
let mut taken = Vec::new();
for (i, runs) in done.into_iter().enumerate() {
let Some(runs) = runs.into_inner().unwrap_or_else(|e| e.into_inner()) else {
continue;
}
let n = hi - lo;
let title = &mut title[..n];
// The lock of the copy's reference (the snapshot, or the
// CPU's side of a copy in the card's memory), from before
// title memory is read until the title's bytes are in: with
// the copy-back on its own thread ([`relay`]) that thread
// puts what the card wrote into title memory and into the
// reference under the same lock, and a page read before
// such a merge and compared after it would take the card's
// bytes for the title's.
let _merging = self.merging.write().unwrap_or_else(|e| e.into_inner());
let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
// A page that is not there is left as it is, and looked at
// again next time.
if !crate::host::read_into(lo as *const u8, title) {
continue;
}
MERGED[0].fetch_add(1, Ordering::Relaxed);
let at = lo - start;
if self.card.is_some() {
// SAFETY: inside the mapping of the copy's CPU side,
// which only the submitting thread writes.
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
// Whole words go up as pairs, all of them in one
// dispatch: only what is a copy of its own counts.
let runs = if crate::host::words_under() { dword_runs(lo, title, held, 0) } else { changed_runs(title, held) };
let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
let copies = runs.iter().filter(own).count();
if copies > *runs_left {
note_stale(2);
return true;
}
*runs_left -= copies;
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for &(r, m) in &runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
self.card_changed_runs(runs.into_iter().map(|(r, m)| (at + r, at + r + m)));
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
} else {
let Some(snapshot) = before.as_mut() else {
note_stale(3);
return true;
};
// SAFETY: the snapshot's allocation holds the copy's
// bytes at the copy's offsets (`writing`), and these
// are in a declared range.
let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) };
for (r, m) in changed_runs(title, held) {
// SAFETY: inside the copy's mapping. The card may be
// writing the copy beside these bytes; they are
// written here and nothing around them.
unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
held[r..r + m].copy_from_slice(&title[r..r + m]);
MERGED[1].fetch_add(1, Ordering::Relaxed);
MERGED[2].fetch_add(m as u64, Ordering::Relaxed);
}
}
drop(before);
drop(_merging);
};
let (lo, hi) = ((stale[i] * PAGE).max(a), ((stale[i] + 1) * PAGE).min(e));
MERGED[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
MERGED[2].fetch_add(runs.iter().map(|r| r.1 as u64).sum(), Ordering::Relaxed);
self.card_changed_runs(runs.into_iter().map(|(r, m)| (lo - start + r, lo - start + r + m)));
// Taken, if the range holds all of the page that is in the
// copy; else the rest of it is the refresh's, which notes
// only whole pages, and the page is looked at again.
if (page * PAGE).max(start) >= a && ((page + 1) * PAGE).min(end) <= e {
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
if lo < hi && (stale[i] * PAGE).max(start) >= a && ((stale[i] + 1) * PAGE).min(end) <= e {
taken.push(stale[i]);
}
}
drop(before);
drop(merging);
{
let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
for page in taken {
if let Some(at) = copied.get_mut(page - base) {
*at = now;
}
}
}
if over.into_inner() {
note_stale(2);
return true;
}
}
false
}
/// Of [`Shadow::merge_under_writes`]: title memory `[lo, lo + n)`, in one
/// page, compared with the reference, which begins at `held`, and put in.
/// The runs that changed, none if it cannot be read, and an error if
/// there were more to copy one by one than `left`.
///
/// # Safety
/// The reference holds the copy's length, and nothing else writes these
/// bytes of it during the call.
unsafe fn merge_page_under_writes(
&self,
lo: usize,
n: usize,
held: *mut u8,
left: &std::sync::atomic::AtomicI64,
) -> Result<Option<Vec<(usize, usize)>>, ()> {
thread_local! {
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
TITLE.with_borrow_mut(|title| {
title.resize(PAGE, 0);
let title = &mut title[..n];
if !crate::host::read_into(lo as *const u8, title) {
return Ok(None);
}
MERGED[0].fetch_add(1, Ordering::Relaxed);
let at = lo - self.start as usize;
// SAFETY: the caller's.
let held = unsafe { std::slice::from_raw_parts_mut(held.add(at), n) };
if self.card.is_some() {
// Whole words go up as pairs, all of them in one
// dispatch: only what is a copy of its own counts.
let runs = if crate::host::words_under() { word_runs(lo, title, held) } else { changed_runs(title, held) };
let own = |&&(r, m): &&(usize, usize)| !crate::host::words_under() || !crate::host::goes_as_words(at + r, m);
let copies = runs.iter().filter(own).count() as i64;
if copies > 0 && left.fetch_sub(copies, Ordering::Relaxed) < copies {
return Err(());
}
let was = (!runs.is_empty() && crate::host::upcheck::on()).then(|| held.to_vec());
for &(r, m) in &runs {
held[r..r + m].copy_from_slice(&title[r..r + m]);
}
if let Some(was) = was {
crate::host::upcheck::note(self.id, at, &was, held);
}
return Ok(Some(runs));
}
let runs = changed_runs(title, held);
for &(r, m) in &runs {
// SAFETY: inside the copy's mapping. The card may be
// writing the copy beside these bytes; they are
// written here and nothing around them.
unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) };
held[r..r + m].copy_from_slice(&title[r..r + m]);
}
Ok(Some(runs))
})
}
/// At submission: copies what changed of `[address, address + len)`
/// since it was last copied (all of it if the memory is not
/// write-watched). Returns the bytes copied.
@@ -3485,7 +3735,8 @@ impl Shadow {
fn update_free(&self, from: usize, to: usize) -> usize {
if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
if let Some((now, written)) = crate::watch::writes(from, to, true) {
let guarded = crate::watch::guarded(from, to);
// (A range whose blocks rest after a write has no guard now.)
let guarded = crate::watch::guarded(from, to) || self.watched.load(Ordering::Relaxed) == GUARDED;
self.watched.store(if guarded { GUARDED } else { 1 }, Ordering::Relaxed);
let copied = self.copy_stale(from, to, now, &written);
self.refresh_check(from, to);
@@ -3667,6 +3918,83 @@ impl Shadow {
bytes
}
/// What shaders wrote in `[from, to)` (offsets) was put into title memory.
fn note_landing(&self, from: usize, to: usize) {
let first = self.start as usize / KERNEL_PAGE;
let pages = (self.start as usize + from) / KERNEL_PAGE - first..(self.start as usize + to).div_ceil(KERNEL_PAGE) - first;
let mut bits = self.landings.lock().unwrap_or_else(|e| e.into_inner());
if bits.is_empty() {
let all = (self.start + self.len).div_ceil(KERNEL_PAGE as u64) as usize - first;
bits.resize(all.div_ceil(64), 0);
}
for page in pages {
bits[page / 64] |= 1 << (page % 64);
}
self.landing.store(true, Ordering::Release);
}
/// [`Shadow::take`] of `[from, to)`, which the copy held before and which
/// is written since: where it may be only the landing that wrote it, the
/// 4 KiB that title memory and the CPU's side have alike are left as they
/// are, and nothing of them is sent ([`land_echo`]).
fn take_landed(&self, from: usize, to: usize) -> usize {
thread_local! {
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
let start = self.start as usize;
let first = start / KERNEL_PAGE;
// Runs of pages noted, and not noted (any more).
let mut runs: Vec<(usize, usize, bool)> = Vec::new();
{
let mut bits = self.landings.lock().unwrap_or_else(|e| e.into_inner());
let mut at = from;
while at < to {
let next = ((at / KERNEL_PAGE + 1) * KERNEL_PAGE).min(to);
let page = at / KERNEL_PAGE - first;
let noted = bits.get(page / 64).is_some_and(|word| word >> (page % 64) & 1 != 0);
// (A page looked at in part is looked at again.)
if noted && next - at == KERNEL_PAGE {
bits[page / 64] &= !(1 << (page % 64));
}
match runs.last_mut() {
Some(last) if last.2 == noted && next - last.0 <= PAGE => last.1 = next,
_ => runs.push((at, next, noted)),
}
at = next;
}
}
TITLE.with_borrow_mut(|title| {
for (from, to, noted) in runs {
if !noted {
self.copy(from, to);
continue;
}
title.resize(to - from, 0);
// (Pages that are not there read as zeros.)
crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, to - from, false);
let mut at = from;
while at < to {
let next = ((at / KERNEL_PAGE + 1) * KERNEL_PAGE).min(to);
let title = &title[at - from..next - from];
// SAFETY: inside the mapping of the copy's CPU side, which
// nothing else reads or writes there: no shader's range
// holds it, and the parts of a refresh lie apart.
let held = unsafe { std::slice::from_raw_parts_mut(self.data.add(at - start), next - at) };
if title == held {
ECHO[0].fetch_add((next - at) as u64, Ordering::Relaxed);
} else {
ECHO[1].fetch_add((next - at) as u64, Ordering::Relaxed);
held.copy_from_slice(title);
self.changed(at - start, next - start);
self.card_changed(at - start, next - start);
}
at = next;
}
}
});
to - from
}
/// Copies title memory `[from, to)` (inside the buffer) into the copy;
/// `known`: the copy held it before ([`send_changed`]).
fn take(&self, from: usize, to: usize, known: bool) -> usize {
@@ -3675,6 +4003,9 @@ impl Shadow {
static TITLE: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
}
let Some(card) = self.card.as_ref().filter(|_| self.changes_only.load(Ordering::Relaxed) || send_changed()) else {
if known && self.card.is_some() && self.landing.load(Ordering::Acquire) && land_echo() && !crate::host::upcheck::on() {
return self.take_landed(from, to);
}
return self.copy(from, to);
};
let whole = !known && card.before.lock().unwrap_or_else(|e| e.into_inner()).is_none();
@@ -4134,6 +4465,9 @@ impl Shadow {
let merged =
unsafe { crate::land::piece(self.start as usize + lo, now as *const u8, self.data.add(lo), &parts, true, notes, self) };
self.walls_merged(hi - lo, merged as usize);
if merged > 0 {
self.note_landing(lo, hi);
}
put += merged;
}
put
+3
View File
@@ -15,6 +15,8 @@
//! (directly indexed views are not known per draw); plane 0 is uploaded
//! (every mip and array slice), depth and stencil planes are not.
pub(crate) mod ahead;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@@ -745,6 +747,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
return;
};
let texture = &copy.texture;
ahead::listed(&copy);
let Some(staging) = staging(resource, &copy, first) else {
return;
};
+417
View File
@@ -0,0 +1,417 @@
//! First uploads of textures picked by index on a copy queue of their own
//! (`VICTORY_UPLOAD_AHEAD`): read, detiled and copied by threads of ours as
//! soon as the texture pass has made them, and the slots that wait for them
//! shown when the copy has run. Recorded into the pass's list, as every other
//! upload is, the copy ran with the frame that needs it, so a slot that shows
//! its texture only after its upload ([`crate::descriptor::host::show_after`])
//! was black or grey in that frame, and in the next.
//!
//! Only a texture that no list has used is taken: made in the last second,
//! in the common state, and never asked for an upload before
//! ([`crate::resource::HostTexture::ahead`]). It stays in the common state
//! (a copy queue's copies leave it there), from which the card's shaders read
//! it as any texture.
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use windows::Win32::Graphics::Direct3D12::*;
use windows::core::Interface;
use super::Staging;
use crate::object::This;
use crate::resource::HostTexture;
/// [`HostTexture::ahead`]: no upload was asked for yet; one is on its way
/// here; it has run; one was recorded into a list.
pub(crate) const NONE: u8 = 0;
const PENDING: u8 = 1;
const DONE: u8 = 2;
pub(crate) const LISTED: u8 = 3;
/// Bytes of title memory on their way at most: past it uploads go into the
/// lists, as before.
const MOST: u64 = 96 << 20;
/// Bytes and textures of one submission at most.
const BATCH: (u64, usize) = (16 << 20, 64);
/// Whether it is on (`VICTORY_UPLOAD_AHEAD`; off).
pub(crate) fn on() -> bool {
#[cfg(feature = "diagnostics")]
if let Some(on) = crate::ab::pick("VICTORY_UPLOAD_AHEAD") {
return on;
}
static ON: OnceLock<bool> = OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_AHEAD").is_some_and(|v| v != "0"))
}
/// An upload on its way.
pub(crate) struct Job {
staging: Arc<Staging>,
copy: Arc<HostTexture>,
asked: std::time::Instant,
/// What to do when it has run; `None`: it has.
then: Mutex<Option<Vec<Box<dyn FnOnce() + Send>>>>,
}
impl Job {
/// Calls `f` when the copy has run: now if it has.
pub(crate) fn then(&self, f: impl FnOnce() + Send + 'static) {
let mut then = self.then.lock().unwrap_or_else(|e| e.into_inner());
match then.as_mut() {
Some(then) => then.push(Box::new(f)),
None => {
drop(then);
f();
}
}
}
}
/// What a texture asked for here gets.
pub(crate) enum Taken {
/// A job of its own, to be [`send`] once what follows it is added.
New(Arc<Job>),
/// One already on its way, or that has run.
Known(Arc<Job>),
}
static QUEUE: (Mutex<VecDeque<Arc<Job>>>, Condvar) = (Mutex::new(VecDeque::new()), Condvar::new());
/// Those on their way, by host copy ([`HostTexture::serial`]).
static ON_THEIR_WAY: Mutex<Vec<(u64, Arc<Job>)>> = Mutex::new(Vec::new());
static LANDED: Condvar = Condvar::new();
static BYTES: AtomicU64 = AtomicU64::new(0);
/// Since the start: uploads, bytes, microseconds from the asking until the
/// copy had run, the longest; askings turned down; waits of lists.
static STATS: [AtomicU64; 6] = [const { AtomicU64::new(0) }; 6];
/// Takes the first upload of `resource`'s levels from `first` on, `there` of
/// whose bytes are mapped (`u64::MAX`: not known). `None`: the list's.
pub(crate) fn take(resource: This, first: u32, there: u64) -> Option<Taken> {
if on() { claim(resource, first, there) } else { None }
}
fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
workers()?;
let turned_down = || {
STATS[4].fetch_add(1, Relaxed);
None
};
let copy = crate::resource::host_copy(resource)?;
if copy.ahead.load(Relaxed) == PENDING {
let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
}
if BYTES.load(Relaxed) >= MOST
|| copy.flags() & 0x7 != 0
|| copy.state.load(Relaxed) != 0
|| copy.grown.load(Relaxed)
|| copy.tiled.is_some()
|| copy.holds.lock().unwrap_or_else(|e| e.into_inner()).is_some()
|| !crate::pool::fresh(&copy.texture)
|| super::host_wrote(resource as usize)
|| crate::resource::alias_of(resource).is_some()
{
return turned_down();
}
if copy.ahead.compare_exchange(NONE, PENDING, Relaxed, Relaxed).is_err() {
return turned_down();
}
super::PICKING.set(Some(there));
let staging = super::staging(resource, &copy, first);
super::PICKING.set(None);
let Some(staging) = staging.filter(|s| {
!s.on_demand && s.first == s.level0 && !s.uploaded.load(Relaxed) && s.once.load(Relaxed)
}) else {
copy.ahead.store(LISTED, Relaxed);
return turned_down();
};
if super::no_wait() && super::fill_unlocked() {
staging.expected.store(if there == u64::MAX { super::mapped_bytes(staging.memory, staging.read) } else { there }, Relaxed);
}
let job = Arc::new(Job { staging, copy, asked: std::time::Instant::now(), then: Mutex::new(Some(Vec::new())) });
BYTES.fetch_add(job.staging.read as u64, Relaxed);
ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner()).push((job.copy.serial, job.clone()));
Some(Taken::New(job))
}
/// Sends a job of [`take`] on its way.
pub(crate) fn send(job: &Arc<Job>) {
QUEUE.0.lock().unwrap_or_else(|e| e.into_inner()).push_back(job.clone());
QUEUE.1.notify_one();
}
/// A list is about to record an upload into `copy`: one on its way here runs
/// first, and no other is taken after it.
pub(crate) fn listed(copy: &HostTexture) {
if copy.ahead.compare_exchange(NONE, LISTED, Relaxed, Relaxed) != Err(PENDING) {
return;
}
STATS[5].fetch_add(1, Relaxed);
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
let started = std::time::Instant::now();
while way.iter().any(|(serial, _)| *serial == copy.serial) && started.elapsed().as_millis() < 1000 {
way = LANDED.wait_timeout(way, std::time::Duration::from_millis(50)).unwrap_or_else(|e| e.into_inner()).0;
}
}
/// The copy queue and its threads, made on first use.
fn workers() -> Option<&'static ID3D12CommandQueue> {
/// Free-threaded.
struct Queue(ID3D12CommandQueue);
// SAFETY: a command queue is free-threaded.
unsafe impl Send for Queue {}
// SAFETY: as above.
unsafe impl Sync for Queue {}
static WORKERS: OnceLock<Option<Queue>> = OnceLock::new();
WORKERS
.get_or_init(|| {
let host = crate::host::host()?;
// SAFETY: plain object creation.
let queue: ID3D12CommandQueue = unsafe {
host.device
.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_COPY,
..Default::default()
})
.ok()?
};
for n in 0..2 {
let worker = Worker::new(&host.device, queue.clone()).ok()?;
std::thread::Builder::new().name(format!("uploads ahead {n}")).spawn(move || worker.work()).ok()?;
}
Some(Queue(queue))
})
.as_ref()
.map(|q| &q.0)
}
struct Worker {
queue: ID3D12CommandQueue,
allocator: ID3D12CommandAllocator,
list: ID3D12GraphicsCommandList,
fence: ID3D12Fence,
}
// SAFETY: a worker's objects are its thread's own; the queue is free-threaded.
unsafe impl Send for Worker {}
impl Worker {
fn new(device: &ID3D12Device, queue: ID3D12CommandQueue) -> windows::core::Result<Worker> {
// SAFETY: plain object creation.
unsafe {
let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
list.Close()?;
Ok(Worker { queue, allocator, list, fence: device.CreateFence(0, D3D12_FENCE_FLAG_NONE)? })
}
}
fn work(self) {
let mut value = 0;
loop {
let mut jobs = Vec::new();
{
let mut queue = QUEUE.0.lock().unwrap_or_else(|e| e.into_inner());
while queue.is_empty() {
queue = QUEUE.1.wait(queue).unwrap_or_else(|e| e.into_inner());
}
let mut bytes = 0;
while bytes < BATCH.0 && jobs.len() < BATCH.1
&& let Some(job) = queue.pop_front()
{
bytes += job.staging.read as u64;
jobs.push(job);
}
}
value += 1;
if let Err(e) = self.copy(&jobs, value) {
tracing::warn!(error = %e, "uploads ahead did not run");
}
finish(jobs);
}
}
fn copy(&self, jobs: &[Arc<Job>], value: u64) -> windows::core::Result<()> {
for job in jobs {
job.staging.refresh();
}
// SAFETY: this worker's allocator and list, whose last submission has
// run; the jobs hold what the list names until after the wait.
unsafe {
self.allocator.Reset()?;
self.list.Reset(&self.allocator, None)?;
for job in jobs {
job.record(&self.list);
}
self.list.Close()?;
self.queue.ExecuteCommandLists(&[Some(self.list.cast()?)]);
self.queue.Signal(&self.fence, value)?;
// (Without an event: this waits.)
self.fence.SetEventOnCompletion(value, windows::Win32::Foundation::HANDLE::default())?;
}
Ok(())
}
}
impl Job {
/// # Safety
/// `list` is an open copy list, and the job lives until it has run.
unsafe fn record(&self, list: &ID3D12GraphicsCommandList) {
let (s, texture) = (&self.staging, &self.copy.texture);
for (i, footprint) in s.footprints.iter().enumerate() {
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: s.first - s.level0 + i as u32 },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&s.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: s.base + footprint.Offset, ..*footprint },
},
};
// SAFETY: the caller's.
unsafe { list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
}
}
/// The jobs' copies have run.
fn finish(jobs: Vec<Arc<Job>>) {
for job in &jobs {
job.staging.uploaded.store(true, Relaxed);
job.staging.dirty.store(false, Relaxed);
job.staging.note_held();
job.copy.ahead.store(DONE, Relaxed);
BYTES.fetch_sub(job.staging.read as u64, Relaxed);
}
{
let mut way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
way.retain(|(serial, _)| !jobs.iter().any(|job| job.copy.serial == *serial));
LANDED.notify_all();
}
for job in &jobs {
let us = job.asked.elapsed().as_micros() as u64;
let n = STATS[0].fetch_add(1, Relaxed) + 1;
let bytes = STATS[1].fetch_add(job.staging.read as u64, Relaxed) + job.staging.read as u64;
let all = STATS[2].fetch_add(us, Relaxed) + us;
let most = STATS[3].fetch_max(us, Relaxed).max(us);
if n == 1 || n.is_multiple_of(5000) {
tracing::info!(
"textures uploaded ahead of the lists (VICTORY_UPLOAD_AHEAD=1), since the start: {n}, {} MB, {:.1} ms from the asking until they were there, the longest {:.0}; {} turned down, {} waited for by lists",
bytes >> 20,
all as f64 / n as f64 / 1e3,
most as f64 / 1e3,
STATS[4].load(Relaxed),
STATS[5].load(Relaxed)
);
}
let then = job.then.lock().unwrap_or_else(|e| e.into_inner()).take();
for f in then.into_iter().flatten() {
f();
}
}
crate::descriptor::host::flip_now();
}
/// Whether `resource`'s host copy was filled here: no list still brings what
/// it shows.
pub(crate) fn there(resource: This) -> bool {
crate::resource::made_copy(resource).is_some_and(|copy| copy.ahead.load(Relaxed) == DONE)
}
/// The state of [`HostTexture::ahead`] of a new host copy.
pub(crate) fn fresh() -> AtomicU8 {
AtomicU8::new(NONE)
}
#[cfg(test)]
mod tests {
use super::*;
/// The texels of a placed texture arrive by the copy queue, all levels of
/// them, and what waits for them is called then; a second asking finds the
/// first on its way, and a later one is the list's.
#[test]
fn a_placed_texture_is_filled_ahead_of_the_lists() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
let Some(host) = crate::host::host() else { return };
// 256x256 BC7, nine levels.
let desc = [3u32, 0, 0, 0, 256, 0, 256, 0x9_0001, 98, 1, 0, 0x105, 0, 0];
let whole = crate::resource::placed_bytes(&desc).unwrap() as usize;
// SAFETY: memory of our own that stays.
let at = unsafe { VirtualAlloc(std::ptr::null(), whole, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) }.cast::<u8>();
// SAFETY: as above.
unsafe { (0..whole).for_each(|i| at.add(i).write((i * 13 + i / 509) as u8)) };
let texture = crate::resource::texture_at(at as u64, &desc).unwrap();
crate::resource::want_level(texture, 0);
let copy = crate::resource::host_copy(texture).unwrap();
if !crate::pool::fresh(&copy.texture) {
return;
}
assert!(!there(texture));
let Some(Taken::New(job)) = claim(texture, 0, u64::MAX) else { panic!("not taken") };
let (told, heard) = std::sync::mpsc::channel();
let also = told.clone();
let Some(Taken::Known(same)) = claim(texture, 0, u64::MAX) else { panic!("not known") };
assert!(Arc::ptr_eq(&job, &same));
job.then(move || told.send(1).unwrap());
same.then(move || also.send(2).unwrap());
send(&job);
let wait = std::time::Duration::from_secs(20);
assert_eq!((heard.recv_timeout(wait), heard.recv_timeout(wait)), (Ok(1), Ok(2)));
assert!(there(texture) && claim(texture, 0, u64::MAX).is_none());
// Level 0 as the card has it, and as the layout says.
let layout = crate::resource::texture_memory(texture)
.and_then(|(_, d)| crate::resource::texture_layout(&d).map(|t| t.planes[0].layout.clone()))
.unwrap();
let (pitch, rows) = (1024usize, 64usize);
let mut expected = vec![0u8; pitch * rows];
// SAFETY: the memory above.
let tiled = unsafe { std::slice::from_raw_parts(at, whole) };
layout.detile(tiled, 0, 0, &mut expected, pitch, pitch * rows).unwrap();
let back = host.read_back_buffer((pitch * rows) as u64).unwrap();
let list = host.new_list().unwrap();
list.close();
list.reset();
let footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: 0,
Footprint: D3D12_SUBRESOURCE_FOOTPRINT {
Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(98),
Width: 256,
Height: 256,
Depth: 1,
RowPitch: pitch as u32,
},
};
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(&back) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&copy.texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 },
};
// SAFETY: an open list, live resources; the mapping spans the buffer.
unsafe {
list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None);
list.close();
host.execute(&[&list]);
let mut data = std::ptr::null_mut();
back.Map(0, None, Some(&mut data)).unwrap();
let seen = std::slice::from_raw_parts(data.cast::<u8>(), pitch * rows);
assert!(seen == expected.as_slice(), "level 0's blocks");
back.Unmap(0, None);
}
}
}
+395
View File
@@ -0,0 +1,395 @@
//! The title's writes into guarded view memory that do not go through a
//! fault that opens the block (`crate::watch`): its bytes are put in through
//! our own view of the same pages (`crate::inplace`), which no guard covers,
//! and the block is told as written (`crate::watch::put_beside`). The block
//! stays read-only, so neither this write nor the block's next taking changes
//! a protection.
//!
//! A change of protection is some 5 us in the game's process, one at a time
//! whoever asks; a frame had 590 write faults, and made as many blocks
//! read-only again (run faults-1). What faults is, by the time spent in it,
//! for a third the title's `memcpy`, and for most of the rest single stores
//! into objects that lie in memory some buffer's copy covers: a flag, a
//! reference count, the link of a free list.
//!
//! - [`import`]: the title's `memcpy`, `memmove` and `memset` are ours
//! (`VICTORY_COPY_BESIDE=1`; off unless asked for). They look at the bits
//! of the blocks they write and go to the runtime's own, but for the parts
//! that lie in guarded blocks.
//! - [`store`]: a store that faults is done here, and the thread goes on
//! behind it (`VICTORY_STORE_BESIDE=1`; off unless asked for). Nothing of
//! the title's code is known ahead: the instruction is read where it
//! faulted, and one that is not understood opens the block as before. So
//! does a block's fifth store since it was taken, and one at a place in the
//! code most of whose blocks come to that ([`SITES`]): code that fills a
//! block would fault at every store.
mod decode;
use crate::watch::Beside;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering::Relaxed};
/// Diagnostics, since the start: copies of the title's that put bytes beside
/// the guards, blocks they did so in, blocks they opened instead; stores done
/// beside the guards, faulting stores not understood, and blocks opened
/// because too many came; stores and parts of copies that left the memory as
/// it was, and were not made.
pub(crate) static DONE: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8];
fn add(what: usize) {
DONE[what].fetch_add(1, Relaxed);
}
/// A switch that is off unless its variable is `1` (or `VICTORY_AB` names it:
/// on and off while the title runs).
macro_rules! asked_for {
($name:literal) => {{
static ASKED: std::sync::OnceLock<Result<bool, u32>> = std::sync::OnceLock::new();
let asked = ASKED.get_or_init(|| {
#[cfg(feature = "diagnostics")]
if let Some(bit) = crate::ab::bit($name) {
return Err(bit);
}
Ok(std::env::var_os($name).is_some_and(|v| v == "1"))
});
match *asked {
Ok(on) => on,
#[cfg(feature = "diagnostics")]
Err(bit) => crate::ab::on(bit),
#[cfg(not(feature = "diagnostics"))]
Err(_) => false,
}
}};
}
fn copies_on() -> bool {
#[cfg(test)]
if ON_IN_TEST.get() {
return true;
}
asked_for!("VICTORY_COPY_BESIDE")
}
fn stores_on() -> bool {
#[cfg(test)]
if ON_IN_TEST.get() {
return true;
}
asked_for!("VICTORY_STORE_BESIDE")
}
#[cfg(test)]
thread_local! {
/// Both, for this thread's writes.
pub(crate) static ON_IN_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// The runtime's own `memcpy`, `memmove` and `memset`.
static REAL: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3];
type Copy = unsafe extern "system-unwind" fn(*mut u8, *const u8, usize) -> *mut u8;
type Set = unsafe extern "system-unwind" fn(*mut u8, i32, usize) -> *mut u8;
/// What the title's import of `name`, which the host has at `address`, is
/// bound to.
pub fn import(name: &str, address: usize) -> usize {
let (which, ours) = match name {
"memcpy" => (0, copy as *const () as usize),
"memmove" => (1, shift as *const () as usize),
"memset" => (2, set as *const () as usize),
_ => return address,
};
#[cfg(feature = "diagnostics")]
let on = crate::ab::bit("VICTORY_COPY_BESIDE").is_some() || copies_on();
#[cfg(not(feature = "diagnostics"))]
let on = copies_on();
if !on {
return address;
}
REAL[which].store(address, Relaxed);
ours
}
#[cfg(test)]
pub(crate) fn copy_for_test(real: usize) -> usize {
REAL[0].store(real, Relaxed);
copy as *const () as usize
}
/// The most a block takes of copies beside its guard before it is opened; a
/// store counts as [`A_STORE`].
pub(crate) const MOST: u32 = 32;
const A_STORE: u32 = 8;
unsafe extern "system-unwind" fn copy(to: *mut u8, from: *const u8, n: usize) -> *mut u8 {
// SAFETY: the title's copy, as it asked for it, by the function it asked.
unsafe { copied(to, from, n, REAL[0].load(Relaxed)) }
}
unsafe extern "system-unwind" fn shift(to: *mut u8, from: *const u8, n: usize) -> *mut u8 {
// SAFETY: as above.
unsafe { copied(to, from, n, REAL[1].load(Relaxed)) }
}
/// # Safety
/// `real` copies as `memcpy` (or `memmove`) does, `to`, `from` and `n` are
/// the title's.
#[inline]
unsafe fn copied(to: *mut u8, from: *const u8, n: usize, real: usize) -> *mut u8 {
// SAFETY: the host's function, noted by `import` before the title ran.
let real: Copy = unsafe { std::mem::transmute(real) };
if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() || overlap(to as usize, from as usize, n) {
// SAFETY: by the caller.
return unsafe { real(to, from, n) };
}
let same = |at: usize, offset: usize, len: usize| {
// SAFETY: both are the title's, the one read-only by our hand, the other read by it next.
unsafe { std::slice::from_raw_parts(at as *const u8, len) == std::slice::from_raw_parts(from.add(offset), len) }
};
in_pieces(to as usize, n, same, |at, offset, len| {
// SAFETY: a part of what the title asked for; or the same bytes at
// our view of the pages.
unsafe { real(at as *mut u8, from.add(offset), len) };
});
to
}
unsafe extern "system-unwind" fn set(to: *mut u8, byte: i32, n: usize) -> *mut u8 {
// SAFETY: as in `copied`.
let real: Set = unsafe { std::mem::transmute(REAL[2].load(Relaxed)) };
if n == 0 || !crate::watch::guards_any(to as usize, n) || !copies_on() {
// SAFETY: the title's, as it asked for it.
return unsafe { real(to, byte, n) };
}
let same = |at: usize, _: usize, len: usize| {
// SAFETY: the title's, read-only by our hand.
unsafe { std::slice::from_raw_parts(at as *const u8, len) }.iter().all(|&there| there == byte as u8)
};
in_pieces(to as usize, n, same, |at, _, len| {
// SAFETY: as in `copied`.
unsafe { real(at as *mut u8, byte, len) };
});
to
}
/// Whether the two ranges meet, if only in a block (of which only one might
/// be written at another address).
fn overlap(to: usize, from: usize, n: usize) -> bool {
const BLOCK: usize = crate::watch::PAGE;
let (first, last) = (to / BLOCK * BLOCK, to.saturating_add(n).next_multiple_of(BLOCK));
from < last && first < from.saturating_add(n)
}
/// Does `[to, to + n)` block by block: `put(at, offset, len)` with the
/// address to write at, the title's or ours.
///
/// What is there already (`same`, of a part in one guarded block) is not
/// written.
fn in_pieces(to: usize, n: usize, same: impl Fn(usize, usize, usize) -> bool, put: impl Fn(usize, usize, usize)) {
const BLOCK: usize = crate::watch::PAGE;
add(0);
let mut offset = 0;
while offset < n {
let at = to + offset;
let len = (BLOCK - at % BLOCK).min(n - offset);
if crate::watch::guards_any(at, len) {
if same(at, offset, len) {
add(7);
offset += len;
continue;
}
match crate::watch::put_beside(at / BLOCK, 1, |delta| put(at.wrapping_add(delta), offset, len)) {
Beside::Done => {
add(1);
offset += len;
continue;
}
// Opened with no fault: the next copies here are plain ones.
_ => crate::watch::opened_for_writing(at),
}
add(2);
}
put(at, offset, len);
offset += len;
}
}
/// Places of the title's code whose stores faulted, by a hash of the address:
/// the stores done beside the guards (the low half) and the blocks that had
/// too many of them (the high half).
static SITES: [AtomicU64; 1 << 10] = [const { AtomicU64::new(0) }; 1 << 10];
fn site(rip: usize) -> &'static AtomicU64 {
&SITES[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 54 & 1023]
}
/// Whether a site's stores come one to a block, as far as is known.
fn sparse(counts: u64) -> bool {
let (done, full) = (counts & 0xffff_ffff, counts >> 32);
full < 4 || full * 12 < done
}
/// Faulting stores by their place in the title's code: the place, and how
/// many left the memory as it was (the low half) or did not (the high one).
static LEARNED: [(AtomicUsize, AtomicU64); 1 << 9] = [const { (AtomicUsize::new(0), AtomicU64::new(0)) }; 1 << 9];
/// A store at `rip` would leave the memory as it is, or not. With
/// `VICTORY_WRITE_SITES=<file>`, a place that can be made to look first
/// (`can_look`) and mostly left it is written into that file, for the next
/// start (`victory_loader::write_sites`).
fn learn(rip: usize, same: bool, can_look: bool) {
let slot = &LEARNED[(rip as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) as usize >> 55 & 511];
let there = slot.0.compare_exchange(0, rip, Relaxed, Relaxed).unwrap_or_else(|there| there);
if there != 0 && there != rip {
return;
}
let counts = slot.1.fetch_add(if same { 1 } else { 1 << 32 }, Relaxed);
let (stayed, changed) = (counts & 0xffff_ffff, counts >> 32);
if !same || !can_look || stayed != 256 || changed * 4 > stayed {
return;
}
let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else {
return;
};
// (Not here, under a fault of the title's.)
std::thread::spawn(move || {
let Some((image, offset)) = place(rip) else {
return;
};
use std::io::Write;
let line = format!("{image} {offset:x} or\n");
let known = std::fs::read_to_string(&file).unwrap_or_default();
if known.lines().any(|l| l == line.trim_end()) {
return;
}
if let Ok(mut file) = std::fs::OpenOptions::new().append(true).create(true).open(&file) {
let _ = file.write_all(line.as_bytes());
}
tracing::info!(image, offset = format_args!("{offset:#x}"), stayed, changed, "a write of the title's that mostly changes nothing, noted");
});
}
/// The file name of the image `address` is in, and where in it.
fn place(address: usize) -> Option<(String, usize)> {
use windows_sys::Win32::System::LibraryLoader::{
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, GetModuleHandleExW,
};
const FLAGS: u32 = GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
let mut module = std::ptr::null_mut();
let mut name = [0u16; 1024];
// SAFETY: an address, and room for the answers.
let n = unsafe {
if GetModuleHandleExW(FLAGS, address as *const u16, &mut module) == 0 {
return None;
}
GetModuleFileNameW(module, name.as_mut_ptr(), name.len() as u32)
} as usize;
let path = String::from_utf16_lossy(&name[..n]);
let file = path.rsplit(['\\', '/']).next()?.to_owned();
(!file.is_empty()).then(|| (file, address - module as usize))
}
/// The places with the most faulting stores, for the log: offset in its
/// image, how many left the memory as it was, how many did not.
#[cfg(feature = "diagnostics")]
pub(crate) fn busiest() -> String {
let mut all: Vec<(u64, u64, usize)> = LEARNED
.iter()
.map(|(rip, counts)| (counts.load(Relaxed), rip.load(Relaxed)))
.filter(|s| s.1 != 0)
.map(|(counts, rip)| (counts & 0xffff_ffff, counts >> 32, rip))
.collect();
all.sort_unstable_by_key(|s| std::cmp::Reverse(s.0 + s.1));
let of = |&(stayed, changed, rip): &(u64, u64, usize)| {
let (image, offset) = place(rip).unwrap_or_default();
format!("{}+{offset:x} {stayed}/{changed}", image.chars().skip(14).take(4).collect::<String>())
};
all.iter().take(16).map(of).collect::<Vec<_>>().join(", ")
}
/// Does the store that faulted at `at`, a byte of a guarded block, beside the
/// guards; `false` if it is to open the block (and nothing was done).
pub(crate) fn store(context: &mut windows_sys::Win32::System::Diagnostics::Debug::CONTEXT, at: usize) -> bool {
if !stores_on() {
return false;
}
let rip = context.Rip as usize;
let site = site(rip);
let counts = site.load(Relaxed);
let mut code = [0u8; 15];
// (To the end of the page if the next is not there.)
let left = 4096 - rip % 4096;
let there = crate::host::read_into(rip as *const u8, &mut code) || {
let n = left.min(15);
n < 15 && crate::host::read_into(rip as *const u8, &mut code[..n])
};
let Some(store) = there.then(|| decode::store(&code, context)).flatten() else {
add(4);
return false;
};
const BLOCK: usize = crate::watch::PAGE;
let end = store.at.wrapping_add(store.size);
if !(store.at..end).contains(&at) || store.at / BLOCK != (end - 1) / BLOCK {
add(4);
return false;
}
// SAFETY: a guarded block's, which can be read.
if let Some((same, flags)) = unsafe { store.same(context) } {
learn(rip, same, store.can_look(&code));
if same && crate::watch::nothing_put(store.at / BLOCK) {
context.EFlags = flags;
context.Rip += store.len as u64;
add(6);
return true;
}
}
if !sparse(counts) {
// Looked at anew some time.
if site.fetch_add(1 << 32, Relaxed) >> 32 > 4096 {
site.store(0, Relaxed);
}
return false;
}
let mut done = false;
let put = crate::watch::put_beside(store.at / BLOCK, A_STORE, |delta| {
// SAFETY: the bytes the title is storing to, at our view of them.
done = unsafe { store.run(context, store.at.wrapping_add(delta)) };
});
if put != Beside::Done {
if put == Beside::Full {
site.fetch_add(1 << 32, Relaxed);
add(5);
}
return false;
}
if !done {
// (A locked one that is not aligned: told as written for nothing.)
add(4);
return false;
}
context.Rip += store.len as u64;
site.fetch_add(1, Relaxed);
add(3);
#[cfg(feature = "diagnostics")]
crate::faultbook::note(crate::faultbook::What::Stored, rip, at / BLOCK, 0);
true
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sites_that_fill_blocks_are_told_from_others() {
assert!(sparse(0) && sparse(1000) && sparse(3 << 32));
assert!(!sparse(4 << 32 | 16) && sparse(4 << 32 | 60));
}
#[test]
fn copies_that_meet_are_left_to_the_runtime() {
const B: usize = crate::watch::PAGE;
assert!(overlap(10 * B + 5, 10 * B + 900, 8), "in one block");
assert!(!overlap(10 * B + 5, 12 * B, 8) && !overlap(10 * B, 9 * B, B));
assert!(overlap(10 * B, 9 * B, B + 1));
}
}
+664
View File
@@ -0,0 +1,664 @@
//! The stores of x86-64 code that [`super::store`] does in the title's place:
//! moves from a register or a constant, arithmetic of those with memory
//! (locked or not), exchanges, and the 4, 8 and 16 byte stores of the vector
//! registers. Everything else is `None`.
use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU32, AtomicU64, Ordering::SeqCst};
use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Alu {
Add,
Or,
And,
Sub,
Xor,
}
#[derive(Clone, Copy, PartialEq, Debug)]
enum Op {
/// These bytes (the low `size` of them).
Put([u8; 16]),
/// With a value; `keeps` carry (`inc`, `dec`).
Alu { alu: Alu, with: u64, keeps: bool },
/// With a register, which gets what was there.
Xchg(Register),
Xadd(Register),
Cmpxchg(Register),
}
/// A general register, or (`high`) the second byte of one of the first four.
#[derive(Clone, Copy, PartialEq, Debug)]
struct Register {
number: usize,
high: bool,
}
pub(super) struct Store {
/// Where it stores, and how many bytes.
pub(super) at: usize,
pub(super) size: usize,
/// The instruction's length.
pub(super) len: usize,
op: Op,
locked: bool,
}
fn general(c: &CONTEXT, number: usize) -> u64 {
match number {
0 => c.Rax,
1 => c.Rcx,
2 => c.Rdx,
3 => c.Rbx,
4 => c.Rsp,
5 => c.Rbp,
6 => c.Rsi,
7 => c.Rdi,
8 => c.R8,
9 => c.R9,
10 => c.R10,
11 => c.R11,
12 => c.R12,
13 => c.R13,
14 => c.R14,
_ => c.R15,
}
}
fn general_mut(c: &mut CONTEXT, number: usize) -> &mut u64 {
match number {
0 => &mut c.Rax,
1 => &mut c.Rcx,
2 => &mut c.Rdx,
3 => &mut c.Rbx,
4 => &mut c.Rsp,
5 => &mut c.Rbp,
6 => &mut c.Rsi,
7 => &mut c.Rdi,
8 => &mut c.R8,
9 => &mut c.R9,
10 => &mut c.R10,
11 => &mut c.R11,
12 => &mut c.R12,
13 => &mut c.R13,
14 => &mut c.R14,
_ => &mut c.R15,
}
}
impl Register {
/// Operand `number` of `size` bytes, with or without a REX prefix.
fn of(number: usize, size: usize, rex: bool) -> Register {
if size == 1 && !rex && (4..8).contains(&number) {
Register { number: number - 4, high: true }
} else {
Register { number, high: false }
}
}
fn get(self, c: &CONTEXT) -> u64 {
general(c, self.number) >> if self.high { 8 } else { 0 }
}
/// As an instruction writes it: 32 bits clear the rest, fewer leave it.
fn put(self, c: &mut CONTEXT, value: u64, size: usize) {
let register = general_mut(c, self.number);
let shift = if self.high { 8 } else { 0 };
*register = match size {
8 => value,
4 => value & 0xffff_ffff,
_ => *register & !(mask(size) << shift) | (value & mask(size)) << shift,
};
}
}
fn mask(size: usize) -> u64 {
if size >= 8 { u64::MAX } else { (1 << (size * 8)) - 1 }
}
/// The store at the start of `code`, which the registers are those of.
pub(super) fn store(code: &[u8], c: &CONTEXT) -> Option<Store> {
let mut at = 0;
let mut next = || {
let byte = code.get(at).copied();
at += 1;
byte
};
let (mut locked, mut narrow, mut repeat) = (false, false, 0u8);
let mut byte = next()?;
loop {
match byte {
0xf0 => locked = true,
0x66 => narrow = true,
0xf2 | 0xf3 => repeat = byte,
// (Of data and stack segments nothing is used; branch hints.)
0x2e | 0x36 | 0x3e | 0x26 => {}
_ => break,
}
byte = next()?;
}
let mut rex = 0u8;
if byte & 0xf0 == 0x40 {
rex = byte;
byte = next()?;
}
// The vector prefixes, with their own forms of the others.
let vector = match byte {
0xc5 if rex == 0 => {
let b = next()?;
rex = if b & 0x80 == 0 { 0x44 } else { 0x40 };
Some(b)
}
0xc4 if rex == 0 => {
let (b, d) = (next()?, next()?);
if b & 0x1f != 1 {
return None;
}
rex = 0x40 | (!b >> 5 & 7) | (d >> 4 & 8);
Some(d)
}
_ => None,
};
if let Some(b) = vector {
// (No 32 byte ones: they fill memory.)
if b & 4 != 0 || narrow || repeat != 0 || locked {
return None;
}
// (A store has no third register.)
if b >> 3 & 15 != 15 {
return None;
}
(narrow, repeat) = match b & 3 {
0 => (false, 0),
1 => (true, 0),
2 => (false, 0xf3),
_ => (false, 0xf2),
};
byte = next()?;
}
let two = vector.is_some() || byte == 0x0f;
if two && vector.is_none() {
byte = next()?;
}
let wide = rex & 8 != 0;
let modrm = next()?;
let (mode, reg, rm) = (modrm >> 6, (modrm >> 3 & 7) as usize | (rex as usize & 4) << 1, modrm & 7);
if mode == 3 {
return None;
}
// The address, all but what hangs on the instruction's length.
let mut address = 0u64;
let mut on_rip = false;
let mut base = Some(rm as usize | (rex as usize & 1) << 3);
if rm == 4 {
let sib = next()?;
let index = (sib >> 3 & 7) as usize | (rex as usize & 2) << 2;
if index != 4 {
address = general(c, index) << (sib >> 6);
}
base = Some((sib & 7) as usize | (rex as usize & 1) << 3);
if sib & 7 == 5 && mode == 0 {
base = None;
}
} else if rm == 5 && mode == 0 {
base = None;
on_rip = true;
}
if let Some(base) = base {
address = address.wrapping_add(general(c, base));
}
let displacement = match mode {
1 => i64::from(next()? as i8),
2 => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])),
_ if base.is_none() => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])),
_ => 0,
};
address = address.wrapping_add(displacement as u64);
let words = if wide {
8
} else if narrow {
2
} else {
4
};
let put = |value: u64| {
let mut bytes = [0; 16];
bytes[..8].copy_from_slice(&value.to_le_bytes());
Op::Put(bytes)
};
let of = |size: usize| Register::of(reg, size, rex != 0);
let vector_bytes = || {
// SAFETY: the registers, whichever way they are named.
let x = unsafe { &c.Anonymous.FltSave }.XmmRegisters[reg];
let mut bytes = [0; 16];
bytes[..8].copy_from_slice(&x.Low.to_le_bytes());
bytes[8..].copy_from_slice(&x.High.to_le_bytes());
bytes
};
let alu_of = |kind: u8| match kind {
0 => Some(Alu::Add),
1 => Some(Alu::Or),
4 => Some(Alu::And),
5 => Some(Alu::Sub),
6 => Some(Alu::Xor),
_ => None,
};
let (op, size) = if two {
match (byte, narrow, repeat) {
(0x11, _, 0) | (0x29, _, 0) | (0x7f, true, 0) | (0x7f, false, 0xf3) | (0xe7, true, 0) => (Op::Put(vector_bytes()), 16),
(0x11, false, 0xf3) => (Op::Put(vector_bytes()), 4),
(0x11, false, 0xf2) | (0x13, _, 0) | (0xd6, true, 0) => (Op::Put(vector_bytes()), 8),
(0x17, _, 0) => {
let mut bytes = vector_bytes();
bytes.copy_within(8.., 0);
(Op::Put(bytes), 8)
}
(0x7e, true, 0) => (Op::Put(vector_bytes()), if wide { 8 } else { 4 }),
_ if vector.is_some() || repeat != 0 => return None,
(0xc3, false, _) => (put(of(words).get(c)), words),
(0xb0 | 0xb1, _, _) => {
let size = if byte & 1 == 0 { 1 } else { words };
(Op::Cmpxchg(of(size)), size)
}
(0xc0 | 0xc1, _, _) => {
let size = if byte & 1 == 0 { 1 } else { words };
(Op::Xadd(of(size)), size)
}
_ => return None,
}
} else {
if repeat != 0 {
return None;
}
let size = if byte & 1 == 0 { 1 } else { words };
let mut constant = |bytes: usize| -> Option<u64> {
Some(match bytes {
1 => next()? as i8 as i64 as u64,
2 => i64::from(i16::from_le_bytes([next()?, next()?])) as u64,
_ => i64::from(i32::from_le_bytes([next()?, next()?, next()?, next()?])) as u64,
})
};
match byte {
0x88 | 0x89 => (put(of(size).get(c)), size),
0xc6 | 0xc7 if reg & 7 == 0 => (put(constant(size)?), size),
0x00 | 0x01 | 0x08 | 0x09 | 0x20 | 0x21 | 0x28 | 0x29 | 0x30 | 0x31 => {
(Op::Alu { alu: alu_of(byte >> 3)?, with: of(size).get(c), keeps: false }, size)
}
0x80 | 0x81 | 0x83 => {
let alu = alu_of(reg as u8 & 7)?;
(Op::Alu { alu, with: constant(if byte == 0x81 { size } else { 1 })?, keeps: false }, size)
}
0x86 | 0x87 => {
locked = true;
(Op::Xchg(of(size)), size)
}
0xfe | 0xff if reg & 7 < 2 => {
(Op::Alu { alu: if reg & 7 == 0 { Alu::Add } else { Alu::Sub }, with: 1, keeps: true }, size)
}
_ => return None,
}
};
if locked && matches!(op, Op::Put(_)) {
return None;
}
// What is read of memory decides nothing but what is stored: no
// register but the operand is written.
if on_rip {
address = address.wrapping_add(c.Rip).wrapping_add(at as u64);
}
Some(Store { at: address as usize, size, len: at, op, locked })
}
const CF: u32 = 1;
const PF: u32 = 4;
const AF: u32 = 0x10;
const ZF: u32 = 0x40;
const SF: u32 = 0x80;
const OF: u32 = 0x800;
/// The result of an operation on `size` bytes and the flags it leaves.
fn arithmetic(alu: Alu, a: u64, b: u64, size: usize, keeps: bool, flags: u32) -> (u64, u32) {
let m = mask(size);
let (a, b) = (a & m, b & m);
let top = |v: u64| v >> (size * 8 - 1) & 1 != 0;
let r = match alu {
Alu::Add => a.wrapping_add(b),
Alu::Or => a | b,
Alu::And => a & b,
Alu::Sub => a.wrapping_sub(b),
Alu::Xor => a ^ b,
} & m;
let mut out = flags & !(CF | PF | AF | ZF | SF | OF);
let mut flag = |set: bool, flag: u32| out |= if set { flag } else { 0 };
flag(r == 0, ZF);
flag(top(r), SF);
flag((r as u8).count_ones().is_multiple_of(2), PF);
match alu {
Alu::Add => {
flag(r < a, CF);
flag(top((a ^ r) & (b ^ r)), OF);
flag((a ^ b ^ r) & 16 != 0, AF);
}
Alu::Sub => {
flag(a < b, CF);
flag(top((a ^ b) & (a ^ r)), OF);
flag((a ^ b ^ r) & 16 != 0, AF);
}
_ => {}
}
if keeps {
out = out & !CF | flags & CF;
}
(r, out)
}
/// A value of `size` bytes in memory, changed by `f` as one if `locked`: what
/// was there (`None`: not aligned).
///
/// # Safety
/// `size` bytes can be read and written at `at`.
unsafe fn change(at: usize, size: usize, locked: bool, f: impl Fn(u64) -> u64) -> Option<u64> {
if !locked {
let mut bytes = [0u8; 8];
// SAFETY (both): by the caller.
unsafe { std::ptr::copy_nonoverlapping(at as *const u8, bytes.as_mut_ptr(), size) };
let was = u64::from_le_bytes(bytes);
unsafe { std::ptr::copy_nonoverlapping(f(was).to_le_bytes().as_ptr(), at as *mut u8, size) };
return Some(was);
}
if !at.is_multiple_of(size) {
return None;
}
// SAFETY (all): by the caller, and aligned.
Some(unsafe {
match size {
1 => u64::from(AtomicU8::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u8)).ok()?),
2 => u64::from(AtomicU16::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u16)).ok()?),
4 => u64::from(AtomicU32::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v.into()) as u32)).ok()?),
_ => AtomicU64::from_ptr(at as *mut _).fetch_update(SeqCst, SeqCst, |v| Some(f(v))).ok()?,
}
})
}
impl Store {
/// Whether it leaves the memory as it is, and what it leaves in the flags
/// then; `None` for those of which that is not asked (locked ones,
/// exchanges).
///
/// # Safety
/// [`Store::size`] bytes can be read at `at`.
pub(super) unsafe fn same(&self, c: &CONTEXT) -> Option<(bool, u32)> {
if self.locked {
return None;
}
let mut there = [0u8; 32];
// SAFETY: by the caller.
unsafe { std::ptr::copy_nonoverlapping(self.at as *const u8, there.as_mut_ptr(), self.size) };
match self.op {
Op::Put(bytes) => Some((there[..self.size] == bytes[..self.size], c.EFlags)),
Op::Alu { alu, with, keeps } => {
let was = u64::from_le_bytes(there[..8].try_into().expect("eight bytes")) & mask(self.size);
let (value, flags) = arithmetic(alu, was, with, self.size, keeps, c.EFlags);
Some((value == was, flags))
}
_ => None,
}
}
/// Whether the loader can make it look before it writes
/// (`victory_loader::write_sites`): an `or` of a byte with a constant, of
/// the five bytes a jump needs.
pub(super) fn can_look(&self, code: &[u8]) -> bool {
let at = usize::from(code[0] & 0xf0 == 0x40);
self.len >= 5 && code[at] == 0x80 && matches!(self.op, Op::Alu { alu: Alu::Or, .. })
}
/// Does it, with `to` for the address, and gives the registers what the
/// instruction leaves in them (but the instruction pointer). `false`:
/// nothing was done.
///
/// # Safety
/// [`Store::size`] bytes can be read and written at `to`.
pub(super) unsafe fn run(&self, c: &mut CONTEXT, to: usize) -> bool {
let (size, locked, m) = (self.size, self.locked, mask(self.size));
// SAFETY (all `change`s): by the caller.
match self.op {
Op::Put(bytes) => {
// As one, for those the processor stores as one.
// SAFETY (all): by the caller, aligned where it must be.
unsafe {
let low = u64::from_le_bytes(bytes[..8].try_into().expect("eight bytes"));
match size {
1 => (to as *mut u8).write_volatile(bytes[0]),
2 if to.is_multiple_of(2) => (to as *mut u16).write_volatile(low as u16),
4 if to.is_multiple_of(4) => (to as *mut u32).write_volatile(low as u32),
8 if to.is_multiple_of(8) => (to as *mut u64).write_volatile(low),
_ => std::ptr::copy_nonoverlapping(bytes.as_ptr(), to as *mut u8, size),
}
}
}
Op::Alu { alu, with, keeps } => {
let flags = c.EFlags;
let Some(was) = (unsafe { change(to, size, locked, |v| arithmetic(alu, v, with, size, keeps, flags).0) }) else {
return false;
};
c.EFlags = arithmetic(alu, was, with, size, keeps, flags).1;
}
Op::Xchg(register) => {
let value = register.get(c) & m;
let Some(was) = (unsafe { change(to, size, true, |_| value) }) else {
return false;
};
register.put(c, was & m, size);
}
Op::Xadd(register) => {
let value = register.get(c);
let Some(was) = (unsafe { change(to, size, locked, |v| v.wrapping_add(value) & m) }) else {
return false;
};
c.EFlags = arithmetic(Alu::Add, was, value, size, false, c.EFlags).1;
register.put(c, was & m, size);
}
Op::Cmpxchg(register) => {
let (value, expected) = (register.get(c) & m, c.Rax & m);
let Some(was) = (unsafe { change(to, size, locked, |v| if v & m == expected { value } else { v }) }) else {
return false;
};
let was = was & m;
c.EFlags = arithmetic(Alu::Sub, expected, was, size, false, c.EFlags).1;
if was != expected {
Register { number: 0, high: false }.put(c, was, size);
}
}
}
true
}
}
#[cfg(test)]
mod tests {
use super::*;
fn context() -> CONTEXT {
// SAFETY: plain data.
unsafe { std::mem::zeroed() }
}
/// The instruction's address, size and length, with every register its
/// number times 0x10000.
fn decoded(code: &[u8]) -> Option<(usize, usize, usize)> {
let mut c = context();
for n in 0..16 {
*general_mut(&mut c, n) = n as u64 * 0x10000;
}
c.Rip = 0x7000_0000;
let mut padded = code.to_vec();
padded.resize(15, 0xcc);
store(&padded, &c).map(|s| (s.at, s.size, s.len))
}
#[test]
fn stores_are_told_by_their_bytes() {
// mov [rcx+rax+48h], rbx
assert_eq!(decoded(&[0x48, 0x89, 0x5c, 0x01, 0x48]), Some((0x10048, 8, 5)));
// mov [rbx], rdx
assert_eq!(decoded(&[0x48, 0x89, 0x13]), Some((0x30000, 8, 3)));
// or byte [r9+9eh], 1
assert_eq!(decoded(&[0x41, 0x80, 0x89, 0x9e, 0, 0, 0, 1]), Some((0x9009e, 1, 8)));
// lock dec dword [rcx+10h]
assert_eq!(decoded(&[0xf0, 0xff, 0x49, 0x10]), Some((0x10010, 4, 4)));
// lock xadd [r10+r12*8-1], eax
assert_eq!(decoded(&[0xf0, 0x43, 0x0f, 0xc1, 0x44, 0xe2, 0xff]), Some((0xa0000 + 0xc0000 * 8 - 1, 4, 7)));
// mov word [rsp], 1234h
assert_eq!(decoded(&[0x66, 0xc7, 0x04, 0x24, 0x34, 0x12]), Some((0x40000, 2, 6)));
// mov [rip+10h], al; mov byte [rip+10h], 5 (counted from its end)
assert_eq!(decoded(&[0x88, 0x05, 0x10, 0, 0, 0]), Some((0x7000_0016, 1, 6)));
assert_eq!(decoded(&[0xc6, 0x05, 0x10, 0, 0, 0, 5]), Some((0x7000_0017, 1, 7)));
// mov [12345678h], eax (no base)
assert_eq!(decoded(&[0x89, 0x04, 0x25, 0x78, 0x56, 0x34, 0x12]), Some((0x1234_5678, 4, 7)));
// vmovaps [rsi+10h], xmm4; vmovaps [r12], xmm3; movups [rax], xmm9
assert_eq!(decoded(&[0xc5, 0xf8, 0x29, 0x66, 0x10]), Some((0x60010, 16, 5)));
assert_eq!(decoded(&[0xc4, 0xc1, 0x78, 0x29, 0x1c, 0x24]), Some((0xc0000, 16, 6)));
assert_eq!(decoded(&[0x44, 0x0f, 0x11, 0x08]), Some((0, 16, 4)));
// vmovss [rax], xmm0; movlps, movhps, vmovq, movd
assert_eq!(decoded(&[0xc5, 0xfa, 0x11, 0x00]), Some((0, 4, 4)));
assert_eq!(decoded(&[0x0f, 0x13, 0x00]), Some((0, 8, 3)));
assert_eq!(decoded(&[0xc5, 0xf9, 0xd6, 0x00]), Some((0, 8, 4)));
assert_eq!(decoded(&[0x66, 0x0f, 0x7e, 0x00]), Some((0, 4, 4)));
// Not stores of these: a 32 byte one, a load, a register's, a string
// instruction, a thread's own memory, a compare, adc.
assert_eq!(decoded(&[0xc5, 0xfc, 0x11, 0x04, 0x31]), None);
assert_eq!(decoded(&[0x48, 0x8b, 0x13]), None);
assert_eq!(decoded(&[0x48, 0x89, 0xd3]), None);
assert_eq!(decoded(&[0xf3, 0xa4]), None);
assert_eq!(decoded(&[0x65, 0x48, 0x89, 0x13]), None);
assert_eq!(decoded(&[0x83, 0x38, 1]), None);
assert_eq!(decoded(&[0x11, 0x00]), None);
// blend by a mask (vmaskmov is of another map), vmovss with a third
// register.
assert_eq!(decoded(&[0xc4, 0xe2, 0x79, 0x2e, 0x00]), None);
}
/// What the processor makes of `code` with rax as the address, rcx and
/// rdx as operands; against [`Store::run`].
fn against_the_processor(code: &[u8], seed: u64) {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc};
static PLACE: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
static ONE: std::sync::Mutex<()> = std::sync::Mutex::new(());
let _one = ONE.lock().unwrap_or_else(|e| e.into_inner());
// SAFETY: fresh memory for code.
let place = *PLACE.get_or_init(|| unsafe {
VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize
});
let spread = |n: u64| {
let v = (seed + n).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ seed << 7;
// Small, edge and large ones.
match v >> 61 {
0 => 0,
1 => v & 1,
2 => u64::MAX,
3 => 0x8000_0000_0000_0000u64 | 0x8000 | 0x80 | 0x8000_0000,
_ => v,
}
};
// f(address, operand, compared, flags, out):
// mov r11, rcx ; the address (its instruction takes [r11])
// mov rax, r8 ; mov r10, r9 ; push r10 ; popfq ; <code> ; pushfq ; pop r10
// mov rcx, [rsp+28h] ; mov [rcx], r10 ; mov [rcx+8], rdx ; mov [rcx+16], rax ; ret
let mut f = vec![0x49, 0x89, 0xcb, 0x4c, 0x89, 0xc0, 0x41, 0x51, 0x9d];
f.extend(code);
f.extend([0x9c, 0x41, 0x5a, 0x48, 0x8b, 0x4c, 0x24, 0x28]);
f.extend([0x4c, 0x89, 0x11, 0x48, 0x89, 0x51, 0x08, 0x48, 0x89, 0x41, 0x10, 0xc3]);
type F = unsafe extern "system" fn(*mut u64, u64, u64, u64, *mut [u64; 3]);
let (there, operand, compared) = (spread(1), spread(2), if seed % 3 == 0 { spread(1) } else { spread(3) });
let flags = 0x202 | (spread(4) & 0x8d5) as u32;
let (mut memory, mut out) = (there, [0; 3]);
// SAFETY: the code above, which keeps to the calling convention.
unsafe {
std::ptr::copy_nonoverlapping(f.as_ptr(), place as *mut u8, f.len());
let f: F = std::mem::transmute(place);
f(&mut memory, operand, compared, u64::from(flags), &mut out);
}
let mut c = context();
let mut ours = there;
(c.R11, c.Rdx, c.Rax, c.EFlags) = (&raw mut ours as u64, operand, compared, flags);
let mut padded = code.to_vec();
padded.resize(15, 0xcc);
let store = store(&padded, &c).unwrap_or_else(|| panic!("{code:x?}"));
assert_eq!((store.at, store.len), (&raw mut ours as usize, code.len()), "{code:x?}");
// SAFETY: our word.
assert!(unsafe { store.run(&mut c, &raw mut ours as usize) });
assert_eq!(ours, memory, "{code:x?} of {there:x} with {operand:x}");
assert_eq!((c.Rdx, c.Rax), (out[1], out[2]), "{code:x?} of {there:x} with {operand:x}, {compared:x}");
// (`and`, `or` and `xor` leave AF as they like.)
const SEEN: u32 = CF | PF | ZF | SF | OF;
assert_eq!(c.EFlags & SEEN, out[0] as u32 & SEEN, "{code:x?} of {there:x} with {operand:x}");
}
#[test]
fn stores_do_what_the_processor_does() {
let mut codes: Vec<Vec<u8>> = Vec::new();
// op [r11], rdx in all sizes; op [r11], constant; inc, dec; xchg, xadd, cmpxchg.
for op in [0x00, 0x08, 0x20, 0x28, 0x30, 0x88, 0x86] {
codes.push(vec![0x41, op, 0x13]);
codes.push(vec![0x66, 0x41, op | 1, 0x13]);
codes.push(vec![0x41, op | 1, 0x13]);
codes.push(vec![0x49, op | 1, 0x13]);
if op < 0x80 {
codes.push(vec![0xf0, 0x41, op | 1, 0x13]);
codes.push(vec![0xf0, 0x49, op | 1, 0x13]);
}
}
for kind in [0u8, 1, 4, 5, 6] {
let modrm = 0x03 | kind << 3;
for constant in [1, 0x7f, 0x80, 0xff] {
codes.push(vec![0x41, 0x80, modrm, constant]);
codes.push(vec![0x41, 0x83, modrm, constant]);
codes.push(vec![0x49, 0x83, modrm, constant]);
codes.push(vec![0x66, 0x41, 0x83, modrm, constant]);
codes.push(vec![0xf0, 0x41, 0x83, modrm, constant]);
codes.push(vec![0x49, 0x81, modrm, 3, 0, 0, constant]);
codes.push(vec![0x66, 0x41, 0x81, modrm, 3, constant]);
}
}
for modrm in [0x03, 0x0b] {
codes.push(vec![0x41, 0xfe, modrm]);
codes.push(vec![0x41, 0xff, modrm]);
codes.push(vec![0x49, 0xff, modrm]);
codes.push(vec![0xf0, 0x41, 0xff, modrm]);
codes.push(vec![0x66, 0x41, 0xff, modrm]);
}
for op in [0xb0, 0xc0] {
codes.push(vec![0x41, 0x0f, op, 0x13]);
codes.push(vec![0xf0, 0x41, 0x0f, op, 0x13]);
codes.push(vec![0xf0, 0x66, 0x41, 0x0f, op | 1, 0x13]);
codes.push(vec![0xf0, 0x41, 0x0f, op | 1, 0x13]);
codes.push(vec![0xf0, 0x49, 0x0f, op | 1, 0x13]);
}
codes.push(vec![0x41, 0xc6, 0x03, 0x99]);
codes.push(vec![0x66, 0x41, 0xc7, 0x03, 0x99, 0x88]);
codes.push(vec![0x41, 0xc7, 0x03, 1, 2, 3, 0x84]);
codes.push(vec![0x49, 0xc7, 0x03, 1, 2, 3, 0x84]);
for code in &codes {
for seed in 0..200 {
against_the_processor(code, seed);
}
}
}
/// The second byte of a register, and 32 bits that clear the rest.
#[test]
fn registers_are_read_and_written_as_by_the_processor() {
let mut c = context();
c.Rax = 0x1122_3344_5566_7788;
assert_eq!(Register::of(4, 1, false).get(&c) & 0xff, 0x77, "ah");
assert_eq!(Register::of(4, 1, true), Register { number: 4, high: false }, "spl");
Register { number: 0, high: true }.put(&mut c, 0xff, 1);
assert_eq!(c.Rax, 0x1122_3344_5566_ff88);
Register { number: 0, high: false }.put(&mut c, 0xabcd, 2);
assert_eq!(c.Rax, 0x1122_3344_5566_abcd);
Register { number: 0, high: false }.put(&mut c, u64::MAX, 4);
assert_eq!(c.Rax, 0xffff_ffff);
}
}
File diff suppressed because it is too large. Load diff
+8
View File
@@ -79,6 +79,14 @@ impl HostPolicy {
return None;
}
let address = imp::resolve(dll, symbol)?;
// The title's copies of memory look where they write.
#[cfg(windows)]
if let ImportSymbol::Name { name, .. } = symbol {
let ours = victory_gpu::titlewrite::import(name, address);
if ours != address {
return Some(ours);
}
}
// With a timeline asked for, what threads wait with is wrapped.
#[cfg(all(windows, feature = "diagnostics"))]
if let ImportSymbol::Name { name, .. } = symbol {
+118 -6
View File
@@ -10,7 +10,7 @@
use std::alloc::{Layout, alloc, dealloc};
use std::collections::{BTreeMap, HashMap};
use std::ffi::c_void;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, LazyLock, Mutex, MutexGuard, RwLock, RwLockReadGuard, RwLockWriteGuard};
use windows_sys::Win32::Foundation::{
@@ -101,6 +101,7 @@ pub extern "system" fn XMemVirtualAlloc(
0
},
};
let asked = protect;
let mut protect = match protect & HOST_PROTECTION {
0 => PAGE_NOACCESS,
p => p,
@@ -179,9 +180,32 @@ pub extern "system" fn XMemVirtualAlloc(
if !at.is_null() && !placeholder {
victory_gpu::title_memory_allocated(at as usize, size);
}
note_protection(asked, kind, flags, at as usize, size);
at
}
/// What the title asks its memory to be (the console's protection, with the
/// bits that say how each processor reaches it: 0x200 uncached, 0x400
/// write-combined, 0x800 and on the GPU's): said for the 1st, 2nd, 4th.. time of
/// each, with how much so far. (For placing it: memory the CPU reaches
/// uncached or write-combined is memory it does not read.)
fn note_protection(protect: u32, kind: u32, flags: u64, at: usize, size: usize) {
type Seen = std::collections::HashMap<(u32, u32, u64), (u64, usize)>;
static SEEN: std::sync::Mutex<Option<Seen>> = std::sync::Mutex::new(None);
let (n, bytes) = {
let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
let e = seen.get_or_insert_with(Default::default).entry((protect, kind, flags)).or_default();
*e = (e.0 + 1, e.1 + size);
*e
};
if n.is_power_of_two() {
tracing::info!(
"title memory asked for as protection {protect:#x}, kind {kind:#x}, flags {flags:#x}: {n} times, {} MB, last {at:#x}+{size:#x}",
bytes >> 20
);
}
}
/// `MEMORY_BASIC_INFORMATION` (the console's first 0x30 bytes are the
/// same), then the XMem flags and tag.
#[repr(C)]
@@ -1066,6 +1090,7 @@ pub extern "system" fn XMemMapPhysicalPages(
let pages = (!pages.is_null()).then(|| unsafe { std::slice::from_raw_parts(pages, n) }.to_vec());
let mut costed = Costed::begin(Some(n));
let _called = victory_gpu::timeline::span("the title's XMemMapPhysicalPages");
let _busy = Busy::begin();
let mut physical = physical();
if let Some(costed) = &mut costed {
costed.waited = costed.started.elapsed().as_nanos() as u64;
@@ -1155,6 +1180,7 @@ pub extern "system" fn XMemMapPhysicalPagesScatter(
pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
let (to, from, len) = (to as usize, from as usize, len as usize);
let _costed = Costed::begin(None);
let _busy = Busy::begin();
let mut physical = physical();
// As in `XMemMapPhysicalPages`: no read in place meets the gap.
let _changing = victory_gpu::title_memory_remapping();
@@ -1194,6 +1220,7 @@ pub fn map_aliases(ranges: &[(u64, u64, u64)]) -> bool {
let mut ok = true;
let mut at = 0;
while at < pages.len() {
let _busy = Busy::begin();
let mut physical = physical();
let mut ops: Vec<Op> = Vec::new();
let mut touched = std::collections::HashSet::new();
@@ -1221,6 +1248,7 @@ fn scatter(wanted: &[(usize, usize)]) -> bool {
let mut ok = true;
let mut at = 0;
while at < wanted.len() {
let _busy = Busy::begin();
let mut costed = Costed::begin(None);
let mut ops: Vec<Op> = Vec::new();
let mut physical = physical();
@@ -1256,7 +1284,15 @@ fn scatter(wanted: &[(usize, usize)]) -> bool {
const GROUP: usize = 64;
/// How many threads map a group of pages side by side (`VICTORY_MAP_THREADS`;
/// 1: the caller alone, a page after the other, as before).
/// 8 unless set; 1: the caller alone, a page after the other; `auto`: 1 while
/// mapping takes little of the time, [`WIDE`] while the title streams as fast
/// as its pages are mapped, [`Busy`]).
///
/// shortcut: `auto` is not the default. The intro's diner was there in time
/// with it (one run, textures-d3), but in the dorm, where each call takes 0.3
/// ms of something that only one at a time gets (until a step of the mission,
/// after which it takes 0.01), 16 threads map no more pages than one, and the
/// groups hold the mapping lock: 260 ms a frame against 125 (textures-d4, -d2).
///
/// Mapping and unmapping a view wait for a lock that every protection change
/// of a view takes too, and our guards make 100,000 of those a second, from
@@ -1269,10 +1305,77 @@ fn side_by_side() -> usize {
if let Some(on) = victory_gpu::switched("VICTORY_MAP_THREADS") {
return if on { 8 } else { 1 };
}
static THREADS: LazyLock<usize> = LazyLock::new(|| {
std::env::var("VICTORY_MAP_THREADS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32)
match asked_threads() {
Some(n) => n,
None if BUSY.2.load(Ordering::Relaxed) => WIDE,
None => 1,
}
}
/// Threads while the title streams fast: they stand in the host's queue side
/// by side, each for a millisecond or two a page in the world's first seconds.
const WIDE: usize = 16;
/// `VICTORY_MAP_THREADS` as a number; `None`: by how much there is to map.
fn asked_threads() -> Option<usize> {
static ASKED: LazyLock<Option<usize>> = LazyLock::new(|| {
match std::env::var("VICTORY_MAP_THREADS") {
Ok(v) if v.trim() == "auto" => None,
v => Some(v.ok().and_then(|v| v.trim().parse().ok()).unwrap_or(8).clamp(1, 32)),
}
});
*THREADS
*ASKED
}
/// Of the window under way: when it began, the nanoseconds spent mapping in
/// it; and whether the last one was busy.
static BUSY: (Mutex<Option<std::time::Instant>>, AtomicU64, std::sync::atomic::AtomicBool) =
(Mutex::new(None), AtomicU64::new(0), std::sync::atomic::AtomicBool::new(false));
/// Counts the time a mapping call of the title's takes, as long as it lives.
/// More than a quarter of a window, and the calls are what loading waits for
/// (one thread of the title's makes them); less than a twentieth, they are
/// not any more.
struct Busy(std::time::Instant);
impl Busy {
fn begin() -> Busy {
Busy(std::time::Instant::now())
}
}
/// Whether mapping is busy after a window of `window` with `spent` in it.
fn busy_after(was: bool, spent: std::time::Duration, window: std::time::Duration) -> bool {
spent * if was { 20 } else { 4 } > window
}
impl Drop for Busy {
fn drop(&mut self) {
const WINDOW: std::time::Duration = std::time::Duration::from_millis(250);
let now = std::time::Instant::now();
let all = BUSY.1.fetch_add((now - self.0).as_nanos() as u64, Ordering::Relaxed) + (now - self.0).as_nanos() as u64;
let mut began = BUSY.0.lock().unwrap_or_else(|e| e.into_inner());
let window = now - *began.get_or_insert(self.0);
if window < WINDOW {
return;
}
*began = Some(now);
BUSY.1.store(0, Ordering::Relaxed);
let was = BUSY.2.load(Ordering::Relaxed);
let is = busy_after(was, std::time::Duration::from_nanos(all), window);
if was != is {
BUSY.2.store(is, Ordering::Relaxed);
static SAID: AtomicU64 = AtomicU64::new(0);
if asked_threads().is_none() && SAID.fetch_add(1, Ordering::Relaxed) < 200 {
tracing::info!(
"title pages are mapped by {} (VICTORY_MAP_THREADS): {:.0} ms of the last {:.0} ms went into mapping calls",
if is { "several threads" } else { "the caller alone" },
all as f64 / 1e6,
window.as_secs_f64() * 1e3
);
}
}
}
}
/// A page of address space to unmap and, with a slice, map anew.
@@ -1414,7 +1517,7 @@ mod pool {
static STARTED: std::sync::Once = std::sync::Once::new();
let pool = POOL.get_or_init(|| Pool { batches: Mutex::default(), more: Condvar::new() });
STARTED.call_once(|| {
let started = (1..side_by_side())
let started = (1..super::asked_threads().unwrap_or(super::WIDE).max(side_by_side()))
.filter(|i| std::thread::Builder::new().name(format!("mapping {i}")).spawn(|| serve(pool)).is_ok())
.count();
tracing::info!(started, "threads that map pages side by side (VICTORY_MAP_THREADS=1: none)");
@@ -2415,6 +2518,15 @@ mod tests {
assert_eq!(XMemFreePhysicalPages(3, pages.as_ptr()), 1);
}
#[test]
fn mapping_is_busy_from_a_quarter_of_the_time_to_a_twentieth() {
let ms = std::time::Duration::from_millis;
assert!(!busy_after(false, ms(60), ms(250)) && busy_after(false, ms(70), ms(250)));
assert!(busy_after(true, ms(15), ms(250)) && !busy_after(true, ms(12), ms(250)));
// A window without a call, then one short one.
assert!(!busy_after(true, ms(5), ms(4000)));
}
#[test]
fn page_windows_cover_one_run_in_place() {
let (a, b) = (allocate(3), allocate(1));
+3 -3
View File
@@ -77,7 +77,7 @@ fn patches_clzero() -> bool {
}
/// `jmp rel32` at `at` to `to`, if it reaches.
fn jump(at: usize, to: usize) -> Option<[u8; 5]> {
pub(crate) fn jump(at: usize, to: usize) -> Option<[u8; 5]> {
let rel = i32::try_from(to as i64 - (at as i64 + 5)).ok()?;
let [a, b, c, d] = rel.to_le_bytes();
Some([0xe9, a, b, c, d])
@@ -111,10 +111,10 @@ fn clzero_stub(at: usize, stub: usize, cmp: [u8; 3]) -> Option<Vec<u8>> {
/// Room for [`clzero_stub`]s near the title's code: where it is and the bytes used.
static STUBS: std::sync::Mutex<Option<(usize, usize)>> = std::sync::Mutex::new(None);
const STUBS_LEN: usize = 64 << 10;
pub(crate) const STUBS_LEN: usize = 64 << 10;
/// Memory for code within reach of a `jmp rel32` at `at`.
fn near(at: usize) -> Option<usize> {
pub(crate) fn near(at: usize) -> Option<usize> {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc};
let at = at & !0xffff;
(0x10_0000..0x7000_0000).step_by(0x10_0000).flat_map(|d| [at.checked_sub(d), at.checked_add(d)]).flatten().find_map(|place| {
+2
View File
@@ -38,6 +38,8 @@ mod thunks;
#[cfg(windows)]
mod tls;
#[cfg(windows)]
pub mod write_sites;
#[cfg(windows)]
mod windows;
#[cfg(windows)]
+255
View File
@@ -0,0 +1,255 @@
//! Places in the title's code that set a bit of a byte which is nearly always set already, changed
//! at load to look first (`VICTORY_WRITE_SITES=<file>`; off without it).
//!
//! The title's threads raise flags in their objects at every use ("drawn this frame"): `or byte
//! [object+n], bit`. The objects lie in memory that copies for the card are kept of, and each such
//! write was a fault on a guarded page, a copy of its block and a guard again, for a byte that
//! stayed as it was (a fifth of a frame's write faults at one place, run faults-3). Here the
//! instruction becomes a jump to code of ours that reads the byte, leaves the flags the instruction
//! leaves, and runs the instruction only if the byte would change.
//!
//! The places are not ours to know: `victory-gpu` (`titlewrite`) finds them while the title runs,
//! by their faults, and writes them into that file, a line each: the image file's name, the place's
//! offset in it (hexadecimal). Nothing of the title's code is kept. What is not such an instruction
//! is left alone.
use std::path::Path;
/// An `or byte [m], constant` at the start of `code`: its length, the bytes that name its address
/// (prefix or 0, ModRM without its register field, what follows up to the constant), the constant.
fn or_byte(code: &[u8]) -> Option<(usize, u8, u8, &[u8], u8)> {
let mut at = 0;
let mut rex = 0;
if code.first()? & 0xf0 == 0x40 {
rex = code[0];
at = 1;
}
let (&op, &modrm) = (code.get(at)?, code.get(at + 1)?);
if op != 0x80 || modrm >> 3 & 7 != 1 {
return None;
}
let (mode, rm) = (modrm >> 6, modrm & 7);
// Not a register, nor the instruction pointer's neighbourhood.
if mode == 3 || mode == 0 && rm == 5 {
return None;
}
let rest = at + 2;
let mut end = rest;
if rm == 4 {
let sib = *code.get(end)?;
// Not the stack, whose pointer is another in our code; a plain address is left too.
if sib & 7 == 4 && rex & 1 == 0 || sib & 7 == 5 && mode == 0 {
return None;
}
end += 1;
}
end += match mode {
1 => 1,
2 => 4,
_ => 0,
};
let constant = *code.get(end)?;
Some((end + 1, rex, modrm, &code[rest..end], constant))
}
/// The code at `stub` for the instruction at `at` (`code` from there).
fn stub(code: &[u8], at: usize, stub: usize) -> Option<(usize, Vec<u8>)> {
let (len, rex, modrm, rest, constant) = or_byte(code)?;
if len < 5 {
return None;
}
let mut out = vec![0x50, 0x51]; // push rax, push rcx
// movzx eax, byte [m] (the prefix's register field is none of it)
if rex & 0x43 != 0 {
out.push(rex & 0x43);
}
out.extend([0x0f, 0xb6, modrm & 0xc7]);
out.extend(rest);
out.extend([0x89, 0xc1]); // mov ecx, eax
out.extend([0xf7, 0xd1]); // not ecx
out.extend([0x81, 0xe1, constant, 0, 0, 0]); // and ecx, constant: the bits to be set
out.extend([0x0c, constant]); // or al, constant: the flags
let back = |out: &mut Vec<u8>| {
let from = stub + out.len();
out.extend(crate::console_insn::jump(from, at + len)?);
Some(())
};
let mut write = vec![0x59, 0x58]; // pop rcx, pop rax
write.extend(&code[..len]);
out.extend([0x67, 0xe3, u8::try_from(write.len() + 5).ok()?]); // jecxz past it
out.extend(write);
back(&mut out)?;
out.extend([0x59, 0x58]);
back(&mut out)?;
Some((len, out))
}
/// Changes the places of `list` that are in the image called `name`, mapped at `base` with `size`
/// bytes: how many.
///
/// # Safety
/// The image stays mapped, and no thread runs its code yet.
pub unsafe fn apply(name: &str, base: usize, size: usize, list: &str) -> usize {
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut room: Option<(usize, usize)> = None;
let mut done = 0;
let mut seen = std::collections::BTreeSet::new();
for line in list.lines() {
let mut words = line.split_whitespace();
let (Some(image), Some(offset)) = (words.next(), words.next()) else {
continue;
};
let Ok(offset) = usize::from_str_radix(offset.trim_start_matches("0x"), 16) else {
continue;
};
if !image.eq_ignore_ascii_case(name) || offset + 16 > size || !seen.insert(offset) {
continue;
}
let at = base + offset;
if room.is_none() {
room = crate::console_insn::near(at).map(|place| (place, 0));
}
let Some((place, used)) = room.as_mut() else {
return done;
};
// SAFETY: sixteen bytes inside the image; what is not mapped in it is not named.
let code: [u8; 16] = unsafe { std::ptr::read_unaligned(at as *const _) };
let to = *place + *used;
let Some((len, body)) = stub(&code, at, to) else {
tracing::warn!(image, offset = format_args!("{offset:#x}"), "not a write of the kind that can be looked at first");
continue;
};
let Some(jump) = crate::console_insn::jump(at, to) else {
continue;
};
if *used + body.len() > crate::console_insn::STUBS_LEN {
return done;
}
let mut old = 0;
// SAFETY: our own code memory, which nothing runs yet; then the instruction, whose page is
// made writable for it and put back, and which nothing runs either.
unsafe {
std::ptr::copy_nonoverlapping(body.as_ptr(), to as *mut u8, body.len());
if VirtualProtect(at as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) == 0 {
continue;
}
std::ptr::write_bytes(at as *mut u8, 0x90, len);
std::ptr::copy_nonoverlapping(jump.as_ptr(), at as *mut u8, jump.len());
VirtualProtect(at as *const _, len, old, &mut old);
FlushInstructionCache(GetCurrentProcess(), at as *const _, len);
}
*used += body.len().next_multiple_of(16);
done += 1;
}
done
}
/// [`apply`] with the file `VICTORY_WRITE_SITES` names.
///
/// # Safety
/// As [`apply`].
pub unsafe fn apply_asked(name: &str, base: usize, size: usize) {
let Some(file) = std::env::var_os("VICTORY_WRITE_SITES") else {
return;
};
let Ok(list) = std::fs::read_to_string(Path::new(&file)) else {
return;
};
// SAFETY: by the caller.
let places = unsafe { apply(name, base, size, &list) };
tracing::info!(image = name, places, "writes of the title's that look first (VICTORY_WRITE_SITES)");
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn what_can_be_looked_at_first() {
// or byte [r9+9eh], 1
let (len, rex, modrm, rest, constant) = or_byte(&[0x41, 0x80, 0x89, 0x9e, 0, 0, 0, 1, 0, 0]).unwrap();
assert_eq!((len, rex, modrm, rest, constant), (8, 0x41, 0x89, &[0x9e, 0, 0, 0][..], 1));
// or byte [r9+31h], 80h; [rax+rcx*8+5]; [r12+5] (a base of its own)
assert_eq!(or_byte(&[0x41, 0x80, 0x49, 0x31, 0x80]).unwrap().0, 5);
assert_eq!(or_byte(&[0x80, 0x4c, 0xc8, 5, 1]).unwrap().0, 5);
assert_eq!(or_byte(&[0x41, 0x80, 0x4c, 0x24, 5, 1]).unwrap().0, 6);
// Of the stack, beside the instruction, a register's, another operation.
assert!(or_byte(&[0x80, 0x4c, 0x24, 5, 1]).is_none());
assert!(or_byte(&[0x80, 0x0d, 1, 0, 0, 0, 1]).is_none());
assert!(or_byte(&[0x80, 0xc9, 1]).is_none());
assert!(or_byte(&[0x80, 0x61, 5, 1, 0]).is_none());
}
/// The instruction in code of a test's, changed, run: the byte, the registers and the flags
/// are what it makes of them unchanged.
#[test]
fn a_changed_write_does_what_it_did() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualProtect};
type F = unsafe extern "system" fn(*mut u8, *mut [u64; 3]);
for (constant, with) in [(0x80u8, 0x49u8), (1, 0x49), (0x7f, 0x49), (0xff, 0x48), (0x10, 0x49)] {
// mov rax, rcx ; mov r9, rcx ; mov rcx, 1234h ; xor r10, r10 ; or byte [r9+31h | rax+31h], constant ;
// pushfq ; pop r10 ; mov [rdx], r10 ; mov [rdx+8], rax ; mov [rdx+16], rcx ; ret
let mut code = vec![0x48, 0x89, 0xc8, 0x49, 0x89, 0xc9, 0x48, 0xc7, 0xc1, 0x34, 0x12, 0, 0, 0x4d, 0x31, 0xd2];
let at = code.len();
if with == 0x49 {
code.extend([0x41, 0x80, 0x49, 0x31, constant]);
} else {
// (With a long address, for the five bytes.)
code.extend([0x80, 0x88, 0x31, 0, 0, 0, constant]);
}
code.extend([0x9c, 0x41, 0x5a, 0x4c, 0x89, 0x12, 0x48, 0x89, 0x42, 0x08, 0x48, 0x89, 0x4a, 0x10, 0xc3]);
// SAFETY: fresh memory for code, twice, one of them changed before it runs.
unsafe {
let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize;
assert_ne!(place, 0);
std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len());
let second = place + 0x1000;
std::ptr::copy_nonoverlapping(code.as_ptr(), second as *mut u8, code.len());
let mut old = 0;
VirtualProtect(second as *const _, 0x1000, PAGE_EXECUTE_READ, &mut old);
let list = format!("other.dll {:x}\nT.dll 0x{at:x}\nt.dll {at:x}\nt.dll 5\nt.dll\n", at);
assert_eq!(apply("t.dll", second, 0x1000, &list), 1);
assert_eq!(std::ptr::read((second + at) as *const u8), 0xe9);
let (plain, changed): (F, F) = (std::mem::transmute(place), std::mem::transmute(second));
for was in 0..=255u8 {
let mut bytes = [[0u8; 0x40]; 2];
bytes[0][0x31] = was;
bytes[1][0x31] = was;
let mut out = [[0u64; 3]; 2];
plain(bytes[0].as_mut_ptr(), &mut out[0]);
changed(bytes[1].as_mut_ptr(), &mut out[1]);
assert_eq!(bytes[0], bytes[1], "{was:x} | {constant:x}");
out[0][1] = out[0][1].wrapping_sub(bytes[0].as_ptr() as u64);
out[1][1] = out[1][1].wrapping_sub(bytes[1].as_ptr() as u64);
// (AF is left as it likes.)
out[0][0] &= 0x8c5;
out[1][0] &= 0x8c5;
assert_eq!(out[0], out[1], "{was:x} | {constant:x}");
}
}
}
}
/// A byte that would not change is not written.
#[test]
fn a_byte_that_stays_is_not_written() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, PAGE_READONLY, VirtualAlloc, VirtualProtect};
// mov r9, rcx ; or byte [r9+31h], 80h ; ret
let code = [0x49, 0x89, 0xc9, 0x41, 0x80, 0x49, 0x31, 0x80, 0xc3];
// SAFETY: fresh memory for code and for a byte, which is read-only when the code runs.
unsafe {
let place = VirtualAlloc(std::ptr::null(), 0x10000, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize;
std::ptr::copy_nonoverlapping(code.as_ptr(), place as *mut u8, code.len());
assert_eq!(apply("t.dll", place, 0x10000, "t.dll 3"), 1);
let data = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8;
data.add(0x31).write(0x83);
let mut old = 0;
VirtualProtect(data.cast(), 4096, PAGE_READONLY, &mut old);
let f: unsafe extern "system" fn(*mut u8) = std::mem::transmute(place);
f(data);
assert_eq!(data.add(0x31).read(), 0x83);
}
}
}
@@ -0,0 +1,139 @@
//! Cube samples with gradients select their level by the footprint (after
//! DexNom/VIctory 921d8d3b).
use super::host::{Dispatch, Host, Root, View};
use super::intersect_tests::build_compute_shader;
use crate::native::{
ComputeIo, HwStage, NativeProgram, ResourceType, RootParam, RootType, StageIo, UsedResource,
};
use windows::Win32::Graphics::Direct3D12::*;
/// The level is the red channel on all six faces so every sample returns
/// its selected mip directly (including the fraction with trilinear filtering).
#[test]
fn guest_cube_gradient_selects_mip_by_footprint() {
const SIZE: usize = 64;
const MIPS: u16 = 7;
let mut words = vec![
0xBE81_0380,
0xBE83_0380, // s1, s3 = 0 (upper halves of the tables)
0xF40C_0400,
0xFA00_0000, // cube SRV to s[16:23] from s[0:1]
0xF408_0300,
0xFA00_0020, // raw output UAV to s[12:15] from s[0:1]+32
0xF408_0601,
0xFA00_0000, // sampler to s[24:27] from s[2:3]
0x7E1E_0280, // v15 = 0 for output byte offsets
];
let cases = [
// image_sample_d: successive XY footprints (in texels).
(0x22, 1.0, 0.0, 0.0),
(0x22, 2.0, 0.0, 1.0),
(0x22, 16.0, 0.0, 4.0),
(0x22, 0.000001, 0.0, 0.0),
(0x22, 0.0, 0.0, 0.0),
// image_sample_d_cl: an instruction-specified minimum level.
(0x23, 1.0, 3.0, 3.0),
(0x23, 16.0, 2.0, 4.0),
(0x23, 0.0, 2.0, 2.0),
// image_sample_l and image_sample_lz: the level is given directly.
(0x24, 0.0, 2.0, 2.0),
(0x27, 0.0, 0.0, 0.0),
];
for (i, &(op, footprint, lod, _)) in cases.iter().enumerate() {
let delta = footprint / SIZE as f32;
let mut addr = Vec::new();
if op == 0x22 || op == 0x23 {
addr.extend([delta, 0.0, 0.0, delta]); // derivatives along the face
}
addr.extend([1.5f32, 1.5, 0.0]); // positive X face, center
if op == 0x23 || op == 0x24 {
addr.push(lod);
}
for (reg, value) in addr.iter().enumerate() {
words.extend([0x7E00_02FF | ((reg as u32) << 17), value.to_bits()]);
}
// MIMG, CUBE, dmask:R, v0... inputs, SRV s16, sampler s24, result v10.
words.extend([0xF000_0118 | (op << 18), 0x00C4_0A00]);
// buffer_store_dword v10, v15, s[12:15], 0 offen offset:i*4
words.extend([0xE070_1000 | (i as u32 * 4), 0x8003_0A0F]);
}
words.push(0xBF81_0000); // s_endpgm
let table = |slot, user_data| RootParam {
root: RootType::Table,
table_offset_dwords: 0,
sgprs: 1,
base_register: 0,
user_data,
slot,
};
let range = |kind, at, words, slot, user_data| UsedResource {
kind,
root: RootType::Table,
table_offset_dwords: at,
lower_bound: 0,
stride: 0,
dwords: words,
user_data,
slot,
};
let native = NativeProgram {
stage: HwStage::Cs,
wave64: false,
vgprs: 16,
layout: vec![table(0, 0), table(1, 2)],
used: vec![
range(ResourceType::Srv, 0, 8, 0, 0),
range(ResourceType::Uav, 8, 4, 0, 0),
range(ResourceType::Sampler, 0, 4, 1, 2),
],
io: StageIo::Cs(ComputeIo {
rsrc2: 3 << 1,
threads: [1, 1, 1],
}),
code: words.into_iter().flat_map(u32::to_le_bytes).collect(),
};
let (shader, _) = build_compute_shader(&native).unwrap();
let texels: Vec<_> = (0..6)
.flat_map(|_| {
(0..MIPS).flat_map(|mip| std::iter::repeat_n([f32::from(mip); 4], (SIZE >> mip).pow(2)))
})
.collect();
let sampler = D3D12_SAMPLER_DESC {
Filter: D3D12_FILTER_MIN_MAG_MIP_LINEAR,
AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
MaxLOD: f32::MAX,
MaxAnisotropy: 1,
..Default::default()
};
for (name, warp) in [("WARP", true), ("hardware", false)] {
let Ok(host) = Host::new(warp) else {
eprintln!("no SM 6.6 {name} device; skipped");
continue;
};
let (root, pso) = host.compute_pipeline(&shader).unwrap();
let out = host
.dispatch(
&root,
&pso,
&Dispatch {
roots: vec![(
0,
Root::Constants(vec![0; shader.user_data_dwords() as usize]),
)],
views: &[
View::Cube(SIZE as u32, MIPS, &texels),
View::RawUav(cases.len() as u32),
],
samplers: &[sampler],
groups: [1, 1, 1],
},
)
.unwrap();
let levels: Vec<_> = out[0].iter().copied().map(f32::from_bits).collect();
let expected = cases.map(|(_, _, _, mip)| mip);
assert_eq!(levels.as_slice(), expected, "{name}");
}
}
+1 -1
View File
@@ -1164,7 +1164,7 @@ fn translated_compute_matches_pc() {
typed_view(DXGI_FORMAT_R8_UNORM, 1),
typed_view(DXGI_FORMAT_R16_FLOAT, 2),
typed_view(DXGI_FORMAT_R8G8B8A8_SNORM, 4),
View::Cube(4, &cube_texels),
View::Cube(4, 1, &cube_texels),
])
.collect();
let root_cbv = floats(64, -0.125);
+15 -11
View File
@@ -994,8 +994,8 @@ fn transition(
pub enum View<'a> {
/// An RGBA32F texture SRV (width, height, texels).
Texture(u32, u32, &'a [[f32; 4]]),
/// An RGBA32F cube SRV (face size, texels of faces +x -x +y -y +z -z).
Cube(u32, &'a [[f32; 4]]),
/// An RGBA32F cube SRV (face size, mip count, texels in D3D subresource order).
Cube(u32, u16, &'a [[f32; 4]]),
/// A raw buffer UAV of this many dwords, zeroed.
RawUav(u32),
/// An RGBA32F texture UAV (width, height), zeroed.
@@ -1170,20 +1170,23 @@ impl Host {
at.ptr += i * view_size;
match *v {
View::Texture(..) | View::Cube(..) => {
let (w, h, texels, faces) = match *v {
View::Texture(w, h, t) => (w, h, t, 1),
View::Cube(n, t) => (n, n, t, 6),
let (w, h, mut texels, faces, mips) = match *v {
View::Texture(w, h, t) => (w, h, t, 1, 1),
View::Cube(n, mips, t) => (n, n, t, 6, mips),
_ => unreachable!(),
};
let mut desc = texture(w, h, D3D12_RESOURCE_FLAG_NONE);
desc.DepthOrArraySize = faces as u16;
desc.MipLevels = mips;
let tex = make(
D3D12_HEAP_TYPE_DEFAULT,
&desc,
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
let pitch = (w as usize * 16).next_multiple_of(256);
for face in 0..faces as usize {
for sub in 0..u32::from(mips) * faces {
let mip = sub % u32::from(mips);
let (w, h) = ((w >> mip).max(1), (h >> mip).max(1));
let pitch = (w as usize * 16).next_multiple_of(256);
let upload = make(
D3D12_HEAP_TYPE_UPLOAD,
&buffer((pitch * h as usize) as u64, D3D12_RESOURCE_FLAG_NONE),
@@ -1191,9 +1194,10 @@ impl Host {
)?;
let mut p = std::ptr::null_mut();
upload.Map(0, None, Some(&mut p)).map_err(err)?;
let texels = &texels[face * (w * h) as usize..];
let (level, rest) = texels.split_at((w * h) as usize);
texels = rest;
for y in 0..h as usize {
let row = &texels[y * w as usize..(y + 1) * w as usize];
let row = &level[y * w as usize..(y + 1) * w as usize];
std::ptr::copy_nonoverlapping(
row.as_ptr().cast::<u8>(),
p.cast::<u8>().add(y * pitch),
@@ -1202,7 +1206,7 @@ impl Host {
}
upload.Unmap(0, None);
let mut at_face = subresource(&tex);
at_face.Anonymous.SubresourceIndex = face as u32;
at_face.Anonymous.SubresourceIndex = sub;
list.CopyTextureRegion(
&at_face,
0,
@@ -1224,7 +1228,7 @@ impl Host {
Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
TextureCube: D3D12_TEXCUBE_SRV {
MipLevels: 1,
MipLevels: u32::from(mips),
..Default::default()
},
},
@@ -162,13 +162,19 @@ fn build(
wide: bool,
descriptor: Descriptor,
) -> Result<(HostShader, resource::Resources), ShaderError> {
let native = native(&program(wide, descriptor));
build_compute_shader(&native(&program(wide, descriptor)))
}
/// `native`, a compute program, translated (the tests' own way: no container).
pub(super) fn build_compute_shader(
native: &NativeProgram,
) -> Result<(HostShader, resource::Resources), ShaderError> {
let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build");
let st = structure::structure(&p).expect("structure");
let res = resource::track(&p, &native.layout, native.stage, Some(&st))?;
let io = io::raise(&p, &native).expect("io::raise");
let io = io::raise(&p, native).expect("io::raise");
let lowered = lower::lower(&lower::Parts {
native: &native,
native,
p: &p,
st: &st,
io: &io,
+273 -21
View File
@@ -3208,7 +3208,19 @@ impl<'a> Lower<'a> {
let k31 = self.s.m.i32(31);
let sign = self.s.m.bin(c, Bin::AShr, off, k31);
let hi = self.s.m.bin(c, Bin::Add, hi, carry);
let hi = self.s.m.bin(c, Bin::Add, hi, sign);
let mut hi = self.s.m.bin(c, Bin::Add, hi, sign);
let mut sum = sum;
if super::builder_bounds() {
// No structure is near 64 MiB (the greatest seen has 14). One
// whose memory was written over says it has gigabytes, and the
// builder's copy of it went through all other structures' memory
// after it and, past 2 GiB, before it. Nothing is there instead.
let (below, all, zero) = (self.s.m.i32(16 << 20), self.s.m.i32(80 << 20), self.s.m.i32(0));
let at = self.s.m.bin(c, Bin::Add, off, below);
let near = self.s.m.cmp(c, pred::IULT, at, all);
sum = self.s.m.select(c, near, sum, zero);
hi = self.s.m.select(c, near, hi, zero);
}
let (h, byte) = self.memory(sum, hi, guard, store);
self.root_copy = Some(h);
Some((h, byte))
@@ -5301,6 +5313,17 @@ impl<'a> Lower<'a> {
let void = self.s.t.void;
self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
}
// The structure builder's threads take turns through atomics (a tree
// built from its leaves up): what one wrote before its atomic is
// seen by the thread that comes after it. The console's program
// waits for its writes there, and those waits are not in the code
// here (after beloooo's 72e748ea, VIctory-Belobug-AMD).
let ordered = (name.starts_with("buffer_atomic") || name.starts_with("global_atomic"))
&& crate::spill::is_spilled(self.x.native)
&& super::builder_fences();
if ordered {
self.memory_fence();
}
let r = match &inst.fields {
Fields::Sop { .. } => self.sop(inst),
Fields::Sopp { .. } if name == "s_barrier" && self.no_barrier.contains(&b) => Ok(()),
@@ -5346,6 +5369,9 @@ impl<'a> Lower<'a> {
Fields::Flat { .. } if name.starts_with("global_") => self.flat(inst, b, i),
Fields::Flat { .. } => Err("flat memory"),
};
if ordered && r.is_ok() {
self.memory_fence();
}
match r {
Ok(()) => Ok(()),
Err(why) if effect => Err(unsupported(offset, why)),
@@ -5358,6 +5384,12 @@ impl<'a> Lower<'a> {
}
}
/// Writes to buffers made before are seen, by every group, before those made after.
fn memory_fence(&mut self) {
let (mode, void) = (self.s.m.i32(2), self.s.t.void);
self.s.op(self.cur, "barrier", Attr::NoDuplicate, void, 80, &[mode]);
}
/// The two host waves of a console wave meet (a group barrier with a shared-memory
/// fence): LDS writes before are seen by reads after.
fn lds_meeting(&mut self) {
@@ -6137,9 +6169,18 @@ impl<'a> Lower<'a> {
return Ok(());
}
if matches!(kind, Some(u) if u.kind == ResourceType::Srv) {
// The size in a structure's header (its second dword), which a
// copy of it loops over.
let size = *offset == 4
&& count == 1
&& extra.is_none()
&& matches!(soffset, Operand::Scalar { code: NULL, .. })
&& super::builder_bounds();
let mut root = false;
let h = match self.root_memory(src, addr, None, false) {
Some((h, byte)) => {
addr = byte;
root = true;
h
}
None => self.handle(site, src, false, (11, 0))?,
@@ -6159,7 +6200,12 @@ impl<'a> Lower<'a> {
&[h, a, u, mask, al],
);
let x = self.s.m.extract(c, r, 0);
let x = self.as_int(x);
let mut x = self.as_int(x);
if size && root {
let (most, zero) = (self.s.m.i32(1 << 20), self.s.m.i32(0));
let sane = self.s.m.cmp(c, pred::IULT, x, most);
x = self.s.m.select(c, sane, x, zero);
}
self.write(inst, Reg::S(code + k as u8), x, None);
}
return Ok(());
@@ -6665,10 +6711,7 @@ impl<'a> Lower<'a> {
/// typed loads do (channels past the format's read 0, 0, 0, 1).
// shortcut: the descriptor's channel swizzle is taken as the identity
// (it is for raw views and the descriptors code builds), elements of 4
// bytes or more as dword-aligned. Norm formats divide, which the AMD
// driver does 1 ULP off the hardware's correctly rounded conversion for
// some values; correct it with an integer check if a title compares
// converted values exactly.
// bytes or more as dword-aligned.
fn format_load(&mut self, h: V, off: V, format: u8, channels: u32) -> Result<Vec<V>, Why> {
let (bits, numeric) = buffer_format(format).ok_or("a buffer format")?;
let c = self.cur;
@@ -6731,10 +6774,15 @@ impl<'a> Lower<'a> {
// 4 loaded 16_16_UNORM's 65535 as the half 0x3BFF, not 0x3C00.
let x = match numeric {
Numeric::Unorm => {
let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
let top = (1u64 << w) - 1;
let max = self.s.m.f32((top as f32).to_bits());
let q = self.s.m.bin(c, Bin::SDiv, f, max);
let q = if w <= 16 {
let q = self.norm_quotient(field, w);
self.as_float(q)
} else {
let f = self.s.m.cast(c, Cast::UiToFp, field, f32t);
let max = self.s.m.f32((top as f32).to_bits());
self.s.m.bin(c, Bin::SDiv, f, max)
};
let (high, one) = (self.s.m.i32(top as u32), self.s.m.f32(1.0f32.to_bits()));
let at_top = self.s.m.cmp(c, pred::EQ, field, high);
let q = self.s.m.select(c, at_top, one, q);
@@ -6742,10 +6790,23 @@ impl<'a> Lower<'a> {
}
Numeric::Snorm => {
let s = signed(self);
let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
let top = (1u32 << (w - 1)) - 1;
let max = self.s.m.f32((top as f32).to_bits());
let q = self.s.m.bin(c, Bin::SDiv, f, max);
let q = if w <= 17 {
// The magnitude's quotient, signed (codes at and
// below -top are -1.0 below).
let (zero, sign) = (self.s.m.i32(0), self.s.m.i32(0x8000_0000));
let neg = self.s.m.cmp(c, pred::SLT, s, zero);
let minus = self.s.m.bin(c, Bin::Sub, zero, s);
let m = self.s.m.select(c, neg, minus, s);
let q = self.norm_quotient(m, w - 1);
let sign = self.s.m.select(c, neg, sign, zero);
let q = self.s.m.bin(c, Bin::Or, q, sign);
self.as_float(q)
} else {
let f = self.s.m.cast(c, Cast::SiToFp, s, f32t);
let max = self.s.m.f32((top as f32).to_bits());
self.s.m.bin(c, Bin::SDiv, f, max)
};
// The lowest value is -1.0 too, as is the one above it.
let (high, one) = (self.s.m.i32(top), self.s.m.f32(1.0f32.to_bits()));
let at_top = self.s.m.cmp(c, pred::SGE, s, high);
@@ -6795,6 +6856,144 @@ impl<'a> Lower<'a> {
Ok(out)
}
/// The bits of the float nearest to `a / d`, `d = 2^w - 1`, for codes
/// `0 <= a < d` and `w <= 16`: what the console's buffer unit gives for
/// a normalized code. The host's division is not exact (the RX 6700 XT
/// returns 8-bit codes one ulp high and some 16-bit codes one ulp low),
/// and titles truncate `x * d` back to the code (a material index in a
/// vertex colour's alpha), which a quotient one ulp low turns into the
/// code below.
///
/// `Q = floor(a * 2^32 / d) = a * K + floor(a * r / d)` with `K =
/// floor(2^32 / d)` and `r = 2^32 mod d` (no division when `r` is 1:
/// widths dividing 32). `a / d` is never exact for `0 < a < d` (`d`
/// odd, `r` coprime to it), so `Q` rounds to 24 bits up exactly when
/// its highest dropped bit is set, and the result is that integer (at
/// most 2^24, so its conversion is exact on any host) scaled by a power
/// of two; `Q` itself when it fits, the quotient's further bits then
/// lying below half an ulp. That holds for every code of every width but
/// 11 and 12 (checked for all codes of widths 2 to 16), which take
/// [`Self::exact_norm`]. The host's conversion of a larger integer is
/// not relied on: WARP rounds those above 2^31 otherwise.
fn norm_quotient(&mut self, a: V, w: u32) -> V {
if matches!(w, 11 | 12) {
return self.exact_norm(a, w);
}
let c = self.cur;
let d = (1u64 << w) - 1;
let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
let (one, kv) = (k(self, 1), k(self, kk));
let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
if r != 1 {
let (rv, dv) = (k(self, r), k(self, d));
let t = self.s.m.bin(c, Bin::Mul, a, rv);
let more = self.s.m.bin(c, Bin::UDiv, t, dv);
q = self.s.m.bin(c, Bin::Add, q, more);
}
// The bits to drop (1 to 8) from the exponent of `q >> 8`, which
// converts exactly (fewer than 25 bits); none when `q` fits.
let k8 = k(self, 8);
let top = self.s.m.bin(c, Bin::LShr, q, k8);
let top = self.s.m.cast(c, Cast::UiToFp, top, self.s.t.f32);
let top = self.as_int(top);
let k23 = k(self, 23);
let e = self.s.m.bin(c, Bin::LShr, top, k23);
let bias = k(self, 127 + 15);
let shift = self.s.m.bin(c, Bin::Sub, e, bias);
let (zero, b24) = (k(self, 0), k(self, 1 << 24));
let fits = self.s.m.cmp(c, pred::IULT, q, b24);
let shift = self.s.m.select(c, fits, zero, shift);
// Rounded up when the highest dropped bit is set: `a / d` is never
// exact, so a dropped half is more than half, never a tie.
let up = self.s.m.bin(c, Bin::Shl, q, one);
let up = self.s.m.bin(c, Bin::LShr, up, shift);
let up = self.s.m.bin(c, Bin::And, up, one);
let m = self.s.m.bin(c, Bin::LShr, q, shift);
let m = self.s.m.bin(c, Bin::Add, m, up);
// At most 2^24: exact as a float, and so its scale by 2^(shift - 32).
let f = self.s.m.cast(c, Cast::UiToFp, m, self.s.t.f32);
let b95 = k(self, 127 - 32);
let scale = self.s.m.bin(c, Bin::Add, shift, b95);
let scale = self.s.m.bin(c, Bin::Shl, scale, k23);
let scale = self.as_float(scale);
let f = self.s.m.bin(c, Bin::Mul, f, scale);
self.as_int(f)
}
/// [`Self::norm_quotient`] in integers only, for any width up to 16: `Q`
/// as there, 8 more bits when that leaves fewer than 25 (codes of wide
/// formats near 0), then rounded to 24 bits to nearest even with the
/// remainder as sticky bit, and assembled as float bits.
fn exact_norm(&mut self, a: V, w: u32) -> V {
let c = self.cur;
let d = (1u64 << w) - 1;
let (kk, r) = ((1u64 << 32) / d, (1u64 << 32) % d);
let k = |l: &mut Self, v: u64| l.s.m.i32(v as u32);
let (one, zero, dv, k8) = (k(self, 1), k(self, 0), k(self, d), k(self, 8));
let kv = k(self, kk);
let mut q = self.s.m.bin(c, Bin::Mul, a, kv);
let mut rem = a;
if r != 1 {
let rv = k(self, r);
let t = self.s.m.bin(c, Bin::Mul, a, rv);
let more = self.s.m.bin(c, Bin::UDiv, t, dv);
q = self.s.m.bin(c, Bin::Add, q, more);
rem = self.s.m.bin(c, Bin::URem, t, dv);
}
// The exponent's bias less the 32 (or 40) fraction bits of `q`; the
// shift below is added.
let mut bias = k(self, 127 + 23 - 32);
if kk < 1 << 24 {
// Fewer than 25 bits for the smallest codes: 8 more.
let t = self.s.m.bin(c, Bin::Shl, rem, k8);
let more = self.s.m.bin(c, Bin::UDiv, t, dv);
let rest = self.s.m.bin(c, Bin::URem, t, dv);
let wide = self.s.m.bin(c, Bin::Shl, q, k8);
let wide = self.s.m.bin(c, Bin::Or, wide, more);
let limit = k(self, 1 << 24);
let small = self.s.m.cmp(c, pred::IULT, q, limit);
q = self.s.m.select(c, small, wide, q);
rem = self.s.m.select(c, small, rest, rem);
let b40 = k(self, 127 + 23 - 40);
bias = self.s.m.select(c, small, b40, bias);
}
// Bits to drop: the bit length less 24, 1 to 8.
let mut shift = one;
for bit in 25..32 {
let at = k(self, 1 << bit);
let ge = self.s.m.cmp(c, pred::IUGE, q, at);
let add = self.s.m.select(c, ge, one, zero);
shift = self.s.m.bin(c, Bin::Add, shift, add);
}
let mant = self.s.m.bin(c, Bin::LShr, q, shift);
let below = self.s.m.bin(c, Bin::Sub, shift, one);
let half = self.s.m.bin(c, Bin::LShr, q, below);
let half = self.s.m.bin(c, Bin::And, half, one);
let low = self.s.m.bin(c, Bin::Shl, one, below);
let low = self.s.m.bin(c, Bin::Sub, low, one);
let low = self.s.m.bin(c, Bin::And, q, low);
let rest = self.s.m.bin(c, Bin::Or, low, rem);
let sticky = self.s.m.cmp(c, pred::NE, rest, zero);
let odd = self.s.m.bin(c, Bin::And, mant, one);
let tie = self.s.m.select(c, sticky, one, odd);
let up = self.s.m.bin(c, Bin::And, half, tie);
let mant = self.s.m.bin(c, Bin::Add, mant, up);
// Rounding up to 2^24 moves to the next exponent.
let k24 = k(self, 24);
let carry = self.s.m.bin(c, Bin::LShr, mant, k24);
let mant = self.s.m.bin(c, Bin::LShr, mant, carry);
let e = self.s.m.bin(c, Bin::Add, bias, shift);
let e = self.s.m.bin(c, Bin::Add, e, carry);
let k23 = k(self, 23);
let e = self.s.m.bin(c, Bin::Shl, e, k23);
let fraction = k(self, 0x7F_FFFF);
let m = self.s.m.bin(c, Bin::And, mant, fraction);
let bits = self.s.m.bin(c, Bin::Or, e, m);
let is_zero = self.s.m.cmp(c, pred::EQ, a, zero);
self.s.m.select(c, is_zero, zero, bits)
}
/// Channels of buffer format `format`, as [`Self::format_load`] gives
/// them, as d16 data: 16 bits each, two per dword, low half first (an
/// odd last high half 0). Integer formats keep their low 16 bits; the
@@ -7223,6 +7422,33 @@ impl<'a> Lower<'a> {
/// `ResourceHeap`): read from the host's table by heap slot in the
/// current block.
fn slot_stride(&mut self, src: &Source) -> Result<Option<V>, Why> {
let word = self.slot_word(src)?;
Ok(word.map(|word| {
let bits = self.s.m.i32(super::shader::VIEW_STRIDE_BITS);
self.s.m.bin(self.cur, Bin::And, word, bits)
}))
}
/// Whether the typed buffer view `src` names is one of an integer format,
/// and whether a signed one, as [`Self::slot_stride`] (`None`: a view the
/// program does not pick from the heap).
fn integer_view(&mut self, src: &Source) -> Result<Option<(V, V)>, Why> {
let Some(word) = self.slot_word(src)? else {
return Ok(None);
};
let c = self.cur;
let zero = self.s.m.i32(0);
let [int, signed] = [super::shader::VIEW_INTEGER, super::shader::VIEW_SIGNED].map(|bit| {
let bit = self.s.m.i32(bit);
let x = self.s.m.bin(c, Bin::And, word, bit);
self.s.m.cmp(c, pred::NE, x, zero)
});
Ok(Some((int, signed)))
}
/// The host's word for the buffer view `src` names: its stride and
/// format kind ([`super::shader::SLOT_STRIDES`]).
fn slot_word(&mut self, src: &Source) -> Result<Option<V>, Why> {
let Source::Loaded { load, first } = src else {
return Ok(None);
};
@@ -11009,11 +11235,14 @@ impl<'a> Lower<'a> {
let width = self.s.m.extract(c, d, 0);
let width = self.s.m.cast(c, Cast::UiToFp, width, self.s.t.f32);
let texels = self.s.m.bin(c, Bin::Mul, longer, width);
// log2 = natural logarithm / ln 2; a length of 0 gives
// DXIL's logarithm is the one to base 2 (it was taken for
// the natural one: every level came out 1.44 times too
// high; DexNom/VIctory 921d8d3b). A length of 0 gives
// minus infinity, which the sampler clamps to level 0.
let ln = self.unary(23, texels);
let per_ln2 = self.s.m.f32(std::f32::consts::LOG2_E.to_bits());
let lod = self.s.m.bin(c, Bin::Mul, ln, per_ln2);
// SampleLevel takes no clamp: the instruction's least
// level is applied here.
let lod = self.unary(23, texels);
let lod = if has_cl { self.binary(35, lod, clamp) } else { lod };
args.extend(&os);
args.push(lod);
call_sample(self, "sampleLevel.f32", 62, &args, &mut gathered)
@@ -11580,8 +11809,14 @@ impl<'a> Lower<'a> {
let mut vals =
self.vgprs(inst, data.as_ref().ok_or("buffer store data")?, regs as u8)?;
if d16 {
// shortcut: d16 data is taken as f16 (integer formats would
// keep 16 bits), widened for the 32-bit float store.
// d16 data is taken as f16, widened for the 32-bit float
// store; through a view of an integer format it is a 16-bit
// integer, zero- or sign-extended (VIctory 4243a96a: the face
// network keeps its halves in UINT views; its output was
// noise). shortcut: that is known of the views a program
// picks from the heap, not of those in its tables; and the
// handle stays a float one, whose bits the drivers pass.
let integer = if typed { self.integer_view(src)? } else { None };
let mut wide = Vec::new();
for k in 0..count {
let mut x = vals[(k / 2) as usize];
@@ -11593,7 +11828,16 @@ impl<'a> Lower<'a> {
let f = self
.s
.op(c, "legacyF16ToF32", Attr::ReadNone, f32t, 131, &[x]);
wide.push(self.as_int(f));
let mut w = self.as_int(f);
if let Some((int, signed)) = integer {
let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
let zero_ext = self.s.m.bin(c, Bin::And, x, low);
let up = self.s.m.bin(c, Bin::Shl, x, k16);
let sign_ext = self.s.m.bin(c, Bin::AShr, up, k16);
let n = self.s.m.select(c, signed, sign_ext, zero_ext);
w = self.s.m.select(c, int, n, w);
}
wide.push(w);
}
vals = wide;
}
@@ -11728,16 +11972,24 @@ impl<'a> Lower<'a> {
return Err("a buffer result");
};
if d16 {
// Two f16 channels per VGPR (an odd last high half 0).
// Two f16 channels per VGPR (an odd last high half 0); the low
// 16 bits of an integer view's (see the stores above).
let integer = if typed { self.integer_view(src)? } else { None };
let k16 = self.s.m.i32(16);
let i32t = self.s.t.i32;
for k in 0..count.div_ceil(2) {
let mut x = None;
for ch in (2 * k..(2 * k + 2).min(count)).rev() {
let f = self.s.m.extract(c, r, ch);
let h = self
let mut h = self
.s
.op(c, "legacyF32ToF16", Attr::ReadNone, i32t, 130, &[f]);
if let Some((int, _)) = integer {
let bits = self.as_int(f);
let low = self.s.m.i32(0xFFFF);
let low = self.s.m.bin(c, Bin::And, bits, low);
h = self.s.m.select(c, int, low, h);
}
x = Some(match x {
Some(hi) => {
let hi = self.s.m.bin(c, Bin::Shl, hi, k16);
+20 -1
View File
@@ -83,6 +83,8 @@
mod bitcode;
mod container;
#[cfg(all(test, windows))]
mod cube_lod_tests;
#[cfg(all(test, windows))]
mod diff_tests;
#[cfg(all(test, windows))]
mod intersect_tests;
@@ -120,7 +122,7 @@ pub use lower::{host_settings, set_host_max_wave, set_host_rdna};
pub use rect::rect_list_gs;
pub use shader::{
MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY, ROOT_CBV_SPACE, SAMPLER_SPACE, SLOT_FAULTS, SLOT_MEMORY, SLOT_STRIDES,
SLOT_STRIDES_COUNT, USER_DATA_SPACE, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
SLOT_STRIDES_COUNT, USER_DATA_SPACE, VIEW_INTEGER, VIEW_SIGNED, VIEW_STRIDE_BITS, USER_DISPATCH_THREADS_X, USER_MEMORY_BASE, USER_ROOT_ADDRESS, USER_VIEW_ADDRESS, USER_VIEW_BIAS,
raw_views, set_raw_views, set_view_heap_limit, view_heap_limit,
};
@@ -182,6 +184,23 @@ pub fn group_sync() -> u8 {
})
}
/// Whether buffer atomics of the ray-tracing structure builder stand between
/// two fences (`VICTORY_BVH_FENCES=0`: they do not). Part of the
/// translation: the shader cache keys on it.
pub fn builder_fences() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_FENCES").is_none_or(|v| v != "0"))
}
/// Whether the structure builder's accesses through its root views stay near
/// them, and a size in a structure's header that cannot be one counts as none
/// (`VICTORY_BVH_BOUNDS=0`: neither). Part of the translation: the shader
/// cache keys on it.
pub fn builder_bounds() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_BOUNDS").is_none_or(|v| v != "0"))
}
/// The clean-up passes that run over a translated program before it is
/// written (`bitcode::opt`): a set of that module's pass bits. Every pass
/// is exact, so the switch is for telling a translator fault from a
+20
View File
@@ -24,6 +24,14 @@ pub const ROOT_CBV_SPACE: u32 = 1;
/// root SRV also tells the host that the buffer views of the whole heap
/// must be ready when it runs, not only those its tables name.
pub const SLOT_STRIDES: u8 = 255;
/// The bits of a [`SLOT_STRIDES`] dword that hold the stride.
pub const VIEW_STRIDE_BITS: u32 = (1 << 30) - 1;
/// In a [`SLOT_STRIDES`] dword: a typed buffer view of an integer format
/// (`UINT` or `SINT`), whose 16-bit typed accesses (`_d16`) pass bits.
/// (After VIctory 4243a96a.)
pub const VIEW_INTEGER: u32 = 1 << 31;
/// With [`VIEW_INTEGER`]: a signed (`SINT`) format.
pub const VIEW_SIGNED: u32 = 1 << 30;
/// Dwords of the [`SLOT_STRIDES`] buffer: heap indices are clamped to it.
pub const SLOT_STRIDES_COUNT: u32 = 1 << 21;
@@ -93,6 +101,8 @@ pub(crate) mod flags {
pub const DOUBLES: u64 = 1 << 2;
pub const STENCIL_REF: u64 = 1 << 11;
pub const TYPED_UAV_LOADS: u64 = 1 << 13;
/// Unordered views in a vertex, geometry or mesh program.
pub const UAVS_EVERY_STAGE: u64 = 1 << 16;
pub const ROVS: u64 = 1 << 18;
pub const WAVE_OPS: u64 = 1 << 19;
pub const BARYCENTRICS: u64 = 1 << 22;
@@ -557,6 +567,13 @@ impl Shader {
}
}
}
// Unordered views outside pixel and compute programs (memory by
// address), as DXC counts them: ranges declared below, not views
// picked from the heap (VIctory a1a2077a).
let compute = self.threads.is_some() && self.mesh.is_none() && self.geometry.is_none();
if !self.root_uavs.is_empty() && !self.pixel && !compute {
self.flags |= flags::UAVS_EVERY_STAGE;
}
let mut resources = None;
let mut bindings = Vec::new();
let i32c = |s: &mut Self, v: u32| {
@@ -871,6 +888,9 @@ impl Shader {
if self.flags & flags::DOUBLES != 0 {
features |= 0x1;
}
if self.flags & flags::UAVS_EVERY_STAGE != 0 {
features |= 0x4;
}
if self.flags & flags::STENCIL_REF != 0 {
features |= 0x200;
}
@@ -415,6 +415,66 @@ fn normalized_buffer_formats_load_their_ends_exactly() {
}
}
/// Codes of the normalized formats sampled below: every 8-bit code; for
/// 16 bits a stride, the RX 6700 XT's division misses (257, 261, ...) and
/// the ends.
fn normalized_codes(bits: u32) -> Vec<u32> {
if bits <= 10 {
return (0..1 << bits).collect();
}
let edges = [1, 2, 3, 255, 256, 257, 261, 265, 269, 511, 512, 1000, 0x7FFF, 0x8000, 0x8001, 0xFFFE];
(0..=0xFFFF).step_by(257).chain(edges).collect()
}
/// Every normalized code loads as the float nearest its exact quotient,
/// as the console's buffer unit converts it, not as the host divides (the
/// RX 6700 XT gave 125 of the 8-bit codes one ulp high and 16-bit codes
/// such as 257 one ulp low): unsigned and signed, 8, 10 (the x channel of
/// 2_10_10_10) and 16 bits, the signed formats' two lowest codes -1.0.
#[test]
fn normalized_buffer_formats_load_correctly_rounded_quotients() {
let x = 0;
// (format, bits, signed): 8_UNORM, 16_UNORM, 8_SNORM, 16_SNORM,
// 2_10_10_10_UNORM and _SNORM.
for (format, bits, signed) in [(1u8, 8u32, false), (7, 16, false), (2, 8, true), (8, 16, true), (50, 10, false), (51, 10, true)] {
let shader = tbuffer_load_of_v1(x, format);
let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect();
run_cases(&shader, &cases, |backend, _, [a, ..], got| {
let want = if signed {
let top = (1i32 << (bits - 1)) - 1;
let s = ((a << (32 - bits)) as i32) >> (32 - bits);
(s.max(-top) as f32 / top as f32).to_bits()
} else {
(a as f32 / ((1u32 << bits) - 1) as f32).to_bits()
};
let sign = if signed { "signed" } else { "unsigned" };
assert_eq!(got, want, "{backend}: {bits}-bit {sign} normalized {a:#x} loads as {got:#010x}, want {want:#010x}");
});
}
}
/// A title truncates `x * (2^n - 1)` back to the code it stored (the
/// material index a mesh program reads from a vertex colour's alpha, as
/// `v_mul_legacy_f32` by 255.0 then `v_cvt_u32_f32`): every code comes back
/// as itself, on hardware and WARP, which a quotient one ulp low breaks.
#[test]
fn normalized_codes_truncate_back_to_themselves() {
let x = 0;
for (format, bits) in [(1u8, 8u32), (7, 16)] {
let scale = (((1u32 << bits) - 1) as f32).to_bits();
let mut body = buffer_store_dword(1, 8, 0).to_vec();
body.extend(mtbuf(x, 0, 8, format));
// v_mul_legacy_f32 v0, literal, v0; v_cvt_u32_f32 v0, v0.
body.extend([0x07 << 25 | 0xFF, scale]);
body.push(vop1(0x07, 0, vgpr(0)));
let shader = build_valu_cs(&body);
let cases: Vec<[u32; 4]> = normalized_codes(bits).iter().map(|&a| [a, 0, 0, 0]).collect();
run_cases(&shader, &cases, |backend, _, [a, ..], got| {
assert_eq!(got, a, "{backend}: {bits}-bit code {a} comes back as {got}");
});
}
}
#[test]
fn packed_add_selects_halves_of_inline_constants() {
// Add the inline constant 1/(2*pi) to v1 (zero) to read back its two halves.
+55 -9
View File
@@ -1,10 +1,10 @@
# Ray tracing in this fork: what the title does and what has been built
Status, 2026-11-25, 06:00: **with `VICTORY_BVH_BUILDER=1` the builder runs on
the RX 7900 XTX and rooms get their indirect light** (run light-6, the dorm:
bunk, locker, window frame, posters; 100-116 ms a frame against 84-95 without).
Some structures are still wrong; one run of four with it lost the device early,
in a list without a builder stage. Off by default.
Status, 2026-11-25, midday: **with `VICTORY_BVH_BUILDER=1` rooms get their
indirect light** (runs light-10, light-11, n19), for some 40 ms more of the
card's time a frame (the dorm: 75 of 90 ms busy against 34 of 64). Off by
default. **`VICTORY_AMBIENT=1`** puts an estimate of that light in its place
for next to nothing (below).
## What the title does
@@ -92,6 +92,10 @@ after it was given them as an unordered access view.
| variable | does |
|---|---|
| `VICTORY_BVH_BUILDER=1` | the builder's stages run |
| `VICTORY_BVH_FENCES=0` | no fences around the builder's buffer atomics (beloooo's 72e748ea has them too) |
| `VICTORY_BVH_SIZES_WAIT=1` | submissions that ask for structures' sizes are waited for (off: no help, slow) |
| `VICTORY_BVH_BOUNDS=0` | the builder's accesses are not bounded |
| `VICTORY_BVH_TRACE=1` | logs what sizes are asked, when they came, and the copies (diagnostics) |
| `VICTORY_BVH_QUARANTINE=1` | nothing it stores comes back to title memory |
| `VICTORY_MEMORY_CARD_MB` | the most of it on the card (4096) |
| `VICTORY_MEMORY_DUMP=<folder>` | a file `go` there writes the arenas out (diagnostics) |
@@ -102,10 +106,25 @@ dispatches, faults and what came.
## Known gaps
- About 4,000 pages a frame that are not there are still touched (the notes'
limit): some structures are wrong and rays go anywhere in them. Guess: sizes
that came back late or not (fixed after light-6, not seen working), so places
overlap.
- Dynamic structures overlap each other (8 of 65 good in run light-10, 48 of
275 in light-15). Part of the cause, run light-11's trace (`VICTORY_BVH_TRACE=1`): the title asks for a new
structure's compacted size, reads it one or two frames later without looking
whether it is there, takes memory of that size and has the structure copied
into it. Our submissions land up to two frames late; the title read what the
slot held before, another structure's size, and the copy wrote over the
neighbours. Waiting for a submission that asks (`VICTORY_BVH_SIZES_WAIT=1`)
did not mend it and costs some 20 ms a frame (light-15): the title asks in
every frame, and what it read was as old as before. Open.
- What a structure that was written over says of its size sent the builder's
copy of it through gigabytes of other structures; bounded now
(`VICTORY_BVH_BOUNDS`). Pages touched that are not there: 2,500 a frame
before, 90 after (the dorm).
- The card's time in the dorm with the builder (timing run light-13, title's
commands 84 ms): `CopyForBVHUpdate` 13.3 ms in 63 dispatches (before the
bound), traces 24 ms (`RaytraceVBuffer` 7.9, screen probes 6.4, irradiance
cache 3.5, primary probes 2.3, shadows 1.6).
- Captures made on 2026-11-25 (builder on or off) hang the card in a replay
(cause unknown; do not try).
- Five shadow-mask trace programs do not translate (a structure's address out
of a descriptor picked from the heap by a computed index: the host would have
to give a table of addresses by slot). The title did not create them in any
@@ -116,6 +135,33 @@ dispatches, faults and what came.
of two boxes entered at the same distance, and the result for a ray exactly
through an edge.
## Without rays: the stand-in (`crates/victory-gpu/src/ambient.rs`)
Without structures every ray misses. The title's program that resolves the
diffuse light of its screen probes (`CS_ScreenProbes_TemporalResolve_*`, list
184 of a frame) then leaves the sky's light outdoors, nothing indoors, and in
blocks of tiles what the probes' memory held. `VICTORY_AMBIENT=<share>` raises
it to an estimate right after that program: the title keeps, for its own screen
traces, the light visible surfaces send out (`CS_CacheScreenSpaceRadiance`,
1280x720, the frame before); its mean in 64x36 cells is gathered at 160x90
points, each cell weighted by the share of the surroundings it covers, as a
directional value; each pixel takes it between the points by depth, with its
normal and a shade in creases. So level and tint follow the hour, the room and
its lamps. What the program left counts up to four times the estimate.
Where it can be put, and the crease shade, are beloooo's (VIctory-Belobug-AMD
06031237, 4f45ab88, cd9f78ce); `VICTORY_AMBIENT=constant:<level>` is that
fork's constant.
| variable | does |
|---|---|
| `VICTORY_AMBIENT=<share>` | the estimate, 1 all of it (unset: the title's own) |
| `VICTORY_AMBIENT=constant:<level>` | the same light everywhere |
| `VICTORY_AMBIENT_SHADE=<strength>,<metres>` | the creases (1,0.6) |
| `VICTORY_AMBIENT_AIR=<multiple>` | what the air scatters is bounded by a multiple of the light around (off: the brown veil in the day room stays with it, light-14) |
It is off while the builder runs.
## Where to look
- `crates/victory-shader/src/bvh.rs`: the reference for the node test.