diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc905cb1bc..4ceaa9d97f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -51,4 +51,4 @@ jobs: - name: Build and test shell: pwsh - run: ./scripts/test.ps1 --skip test_title_runs_and_game_folder_is_untouched + run: ./scripts/test.ps1 --nocapture --skip test_title_runs_and_game_folder_is_untouched diff --git a/README.md b/README.md index 321cc03a9e..556a644068 100644 --- a/README.md +++ b/README.md @@ -127,7 +127,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **kernelx** | ✅ | title memory (budget from MicrosoftGame.Config, physical pages), threads on the PC's processors, modules, OS / console info | unit + end-to-end tests | | **Memory** | ✅ | title graphics memory shared by CPU and GPU without copies, up to 16 GB (4 GiB windows) | GPU tests: loads, stores and atomics across windows | | **File system** | ✅ | console paths (`GAME:`, `G:`, `D:` …) → the game folder; writes go to an overlay, the game folder is never modified; the console's drives: `S:\` (persistent local storage) and `T:\` (temp) in the title's data folder; free disk space answered for console paths | end-to-end: the test title's folder stays byte-identical; PLS and free space through the real call path | -| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | +| **DirectStorage** | ✅ | the console's DirectStorage queues: file and memory sources, queued event notifications, zlib, and BCPack – the console's texture compression – for BC1, BC3, BC4, BC5, BC6H and BC7 (BC2 and the hardware swizzle are refused) | unit tests on synthetic streams; retail BCPack chunks of all six modes byte-identical with a reference decoder (`XCL_SAMPLE_BCPACK`) | @@ -151,7 +151,7 @@ A gamepad is recommended ([Controls](#controls)). The game folder is never modif | **Pipelines** | ✅ | PSOs from console shaders: VS+PS, CS, MS+PS, VS+GS+PS; root signature with the shaders' static samplers; non-blocking creation – a pipeline whose shaders are not compiled yet gets a stand-in at once and is built in the background | GPU tests drawing the game's own VS / PS pairs, also built in the background | | **D3D12.X compute** | ✅ | console device slots, console descriptor heaps (T# / V# / S#), buffers at their console addresses, compute command lists recorded in the console format and replayed (tables, barriers, clears, copies) | the game's BVH builder and FSR 4 record and run through XCL | | **D3D12.X graphics** | ✅ | device, resources and heaps (also placed in title memory), pipelines; the title's graphics command lists – draws, indirect draws, graphics root arguments, barriers, copies, clears – and command lists recorded by console code, replayed; `PresentX` and frame pacing into an XCL window | Minecraft Preview plays its worlds (millions of draws, none skipped); Fortnite and XDefiant draw their screens | -| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | +| **Textures** | ✅ | GFX10 tiling (all 14 2D swizzle modes, the 6 3D thick modes, linear), mip chains with mip tail, arrays, cubes and 3D textures → PC textures; supported GPU-written title subresources copy back before their writer queue's title fence becomes visible | 909 / 912 retail textures exact (the 3 volume LUTs decode smooth); GPU upload bit exact | | **Ray tracing** | ✅ | BLAS / TLAS built on the GPU by the game's own XboxBvhBuilder; RDNA2 BVH node format; BVH intersection instructions emulated in shaders | GPU traversal = brute force reference; the game's builder output checked on the GPU | | **Upscaling** | ✅ | the game's AMD FSR 4 console DLL (`amd_fidelityfx_upscaler_xbox.dll`): context, the 29 pipelines in the console driver's own container (FSPX) translated, a frame's 20 passes recorded and run on the GPU | end-to-end with the real DLL: a 1280×720 → 1920×1080 frame on an RX 9070, the input's gradient in the output | @@ -222,7 +222,7 @@ xcl inspect D:\Game\game.exe # the game's imports and what XCL has xcl run D:\Game [-- game arguments] # run xcl disasm [--hex] # RDNA2 disassembler (console containers too) xcl shaders D:\data\shaders.rpf --top 50 # pack statistics; --recomp / --compile N -xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run +xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines # build compute pipelines and save driver blobs for the next run (except by default on AMD) xcl shaders D:\data\shaders.rpf --precompile --only cs --pipelines --used-only # only the compute pipelines an earlier run of the title used xcl shaders D:\data\shaders.rpf --export-hlsl out --record-hash HEX # exact compute HLSL for investigation xcl shaders D:\data\shaders.rpf --measure-pso HEX --repeat 3 # cold driver PSO timing (cache disabled) @@ -235,6 +235,11 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder - For compute shaders that XCL can split, the runtime first tries the saved driver blob for the whole shader. A usable blob lets the GPU run it in one dispatch. If the blob is missing or the driver rejects it, XCL builds the split pieces. +- A split program first seen through `ExecuteIndirect` is also kept in + `used-indirect-split.txt` beside the DXIL cache. A later `--pipelines --used-only` pass still + builds its direct-dispatch pieces and whole fallback, and additionally saves both its pieces and + whole fallback under the indirect root; other split programs do not pay for those potentially + long driver compiles. - **`--pipelines` size cap**: a compute program whose DXIL is over 8 MiB and that has no saved blob is left to the runtime instead of being compiled in the pass — those compiles take tens of minutes and gigabytes and stopped the pass on the biggest programs. `XCL_PIPELINE_MAX_KB` @@ -263,6 +268,12 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder default. - Translated shaders are reused across XCL rebuilds when the translator sources and DXC toolchain are unchanged; `XCL_TRANSLATED_CACHE=0` disables that disk cache. + Loading a cached shader without split pieces reuses the file buffer, avoiding a second + payload-sized allocation. +- XCL saves an eligible driver blob when its pipeline takes at least 250 ms to build, even + after the bounded in-memory blob cache fills. This is off by default on AMD; + `XCL_PSO_DISK_CACHE=1` forces it on, and `XCL_PSO_DISK_CACHE=0` disables it elsewhere. + Compute blobs with different ordered static-sampler root signatures use separate entries. - Direct compute dispatches can split large programs into pipelines built in parallel. `XCL_DIRECT_SPLIT_INSTRUCTIONS` sets the target instructions per piece (default 12500, zero disables splitting). Loops stay in one piece. A strongly connected component over the @@ -280,11 +291,16 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `XCL_PSO_TRACE=1` logs every driver compile. A huge compute program the driver refuses is logged with the driver's verdict (`the driver refused the compute PSO of record HASH … with 0x…`): its dispatches are skipped. + On AMD, cold 128–256 KiB compute pipelines use a separate lane (three background / four + wanted at once on hosts with at least 32 GiB RAM, two / three below that), configurable with + `XCL_MEDIUM_PSO_CONCURRENCY` and `XCL_MEDIUM_PSO_WANTED_CONCURRENCY`. - With `XCL_DRED=1`, a D3D12 device removal logs GPU breadcrumbs in `xcl.log`. XCL examines up to 4,096 command lists and reports up to 64 unfinished lists, starting with those on which the GPU completed at least one operation. For each, it names the translated pipeline bound at the last operation DRED saw complete and those bound after it, by their console shaders' hashes (`cs`, `vs` / `ps`, `ms` / `ps`, `vs` / `gs` / `ps`). +- `XCL_TEXTURE_LEVEL_PAGES=1` gives sampled title textures backing as their mip levels stream in. + Zero-filled mip uploads in a batch share one staging span and still clear any mapped tiles. - `XCL_DSTORAGE_PARALLEL_DECOMPRESS=1` enables parallel CPU decompression for file-backed zlib requests with virtual destinations. Defaults: four workers and a shared 32 MiB staging budget (`XCL_DSTORAGE_WORKERS`, `XCL_DSTORAGE_MEMORY_BUDGET_MIB`). Requests retire in queue order. @@ -297,14 +313,32 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder `null` if its format cannot be decoded. Intermediate render-target dumps do not update it. Sampling uses every fourth pixel in each direction (`XCL_FRAME_DUMP_FULL=1`: every pixel). A coarse sample can miss detail; a non-dark sample does not establish correct rendering or gameplay. + With `XCL_STALL_TRACE=1`, `report.json` also contains versioned aggregate counts, total/max time and + log2-nanosecond histograms for coarse runtime stalls, plus a bounded list of the newest spans of at + least 50 ms. The tracing is off by default. + `XCL_STALL_TRACE_DETAIL=1` includes high-frequency draw, dispatch, binding, descriptor/view, + barrier, copy and command-list lifecycle recording costs on the title's first observed submitting + thread; it also enables the coarse trace. Use it only for a diagnostic run because every recorded + call reads the clock and updates counters. + `XCL_GPU_TIMING=1` times each native title `ExecuteCommandLists` chunk on the CPU. The count and + slowest duration/list count are written to `report.json`; chunks taking at least 50 ms are logged + (`XCL_GPU_TIMING_MS` changes that threshold). It does not measure when the GPU finishes. - **Diagnostics for a bug report** (all off by default; set them in the environment of `xcl run`): - `XCL_RUN_SECONDS=n`: the title ends itself after `n` seconds, with the GPU drained and `xcl.log` and `report.json` written, so a run of a fixed length can be attached. A value that is not a whole number is ignored. - `XCL_ACTIVITY=1` (any value turns it on): every 2 seconds `xcl.log` gets an `activity (2 s)` line with what the title did in that time (presents, submits, draws, dispatches, frame-event - waits, DirectStorage requests), and a `memory:` line with the process's commit and the video - memory in use. Where the lines stop changing is where the title stopped. + waits, DirectStorage requests), a `memory:` line with the process's commit and video memory in + use, a `memory by owner` line splitting the known XCL allocations from `other`, and sampled + texture resident / SRV-addressable / virtual texel totals. It also reports completed background + pipelines retained behind stand-ins and how many frames ago they were last used, and the + active foreground time plus + serialization wait spent looking for CPU writes before submits (write-watch bytes/ranges/pages, + sparse queue/fence-state/copy phases and zero/dirty volume, upload-gate wait/hold time split + between submit preparation and synchronous readback, and other refresh work). A negative + `other` exposes an overlapping or stale sample; unavailable + adapter segments say `unknown`. Where the lines stop changing is where the title stopped. - `XCL_THREAD_DUMP_AT=s1,s2,…`: at each of those seconds after the start, the state of every thread of the title goes into `xcl.log`, for a title that stalls. - `XCL_TRACE_FAULTS=1` (any value): the first 32 access violations are logged as they are raised @@ -328,12 +362,65 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder +## Reproducible cold and warm runs + +On a clean commit, build and run the same title once with fresh XCL caches and once with those +exact caches warm: + +```powershell +.\scripts\perf-run.ps1 -Game 'D:\Games\SomeTitle' -OutDir 'D:\xcl-perf\run-1' -Seconds 120 +``` + +The script builds `xcl` in release mode and refuses a dirty worktree or a non-empty output +folder. Both runs use a new temporary `XCL_DATA_ROOT` and `XCL_DXIL_CACHE`; the warm run reuses +the cold run's directories. They are deleted afterwards, and existing user caches are never read, +changed, or deleted. The output folder contains only each run's `xcl.log` and `report.json`, plus +a versioned `manifest.json` with the commit, run order, hardware/toolchain, selected XCL +environment, cache identity, durations, and exit status. It contains no game files or cache data. + +The manifest identifies the workload with a SHA-256 metadata fingerprint over its sorted relative +file paths, lengths, and UTC modification-time ticks. Only the fingerprint and its algorithm/version +are recorded; the inventory's file names and absolute paths are not persisted. This is a metadata +fingerprint, not a content hash: a content change that preserves the path, length, and modification +time is not detected. + +The manifest calls these states **XCL-cold** and **XCL-warm**. GPU driver caches are +driver-controlled and are explicitly recorded as `uncontrolled`; this is not a fully cold-driver +benchmark. + +Compare two completed artifact folders without modifying them: + +```powershell +.\scripts\perf-compare.ps1 -Baseline 'D:\xcl-perf\main' -Candidate 'D:\xcl-perf\change' > comparison.json +``` + +The console shows raw cold/warm duration, exit/timeout state, stall totals/counts/maxima, the five +compute-build coalescing counters, and ranked-preload submissions, starts and promotions. The +allocator section also reports execute/chunk topology, retirement-signal outcomes, mark writes and +allocator-state lock timing. Sparse upload-gate submit/readback wait and hold times are summed from +the activity log; artifacts from older builds label those counters missing rather than zero. The +redirected JSON keeps those values, raw deltas, and stall log2 +histograms. Missing reports or preparation summaries and unsupported preparation versions remain +explicit states; they are not treated as zero. The tool +refuses different workload fingerprints or identity algorithm/versions, run order, requested +duration, runtime environment, system, GPU, or GPU driver. Missing reports and stall summaries are +labelled as missing; it does not infer significance or percentages. + ## Tests ```powershell .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace +.\scripts\perf-run.tests.ps1 # cold/warm runner fixture (no game is run) +.\scripts\perf-compare.tests.ps1 # comparison fixture (synthetic artifacts) +cargo bench -p xcl # synthetic performance benchmarks +cargo bench -p xcl --bench core # run one benchmark target ``` +Benchmarks use generated inputs and public XCL APIs; they do not require game files or a title +executable. The dependency-free harness prints median, mean and minimum time plus throughput; a +positional substring selects benchmarks, and `cargo bench -p xcl -- --test` runs every closure once +as a fast smoke check. + Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests (D3D12, SM 6.6; skipped without a GPU / DXC; `XCL_ADAPTER=1` or `XCL_ADAPTER=radeon` picks another adapter than the first high-performance one, for titles too). A GPU test that cannot run on diff --git a/crates/xcl/Cargo.toml b/crates/xcl/Cargo.toml index c3b23a1b8b..42aa7a365b 100644 --- a/crates/xcl/Cargo.toml +++ b/crates/xcl/Cargo.toml @@ -68,3 +68,19 @@ features = [ "Win32_UI_Controls_Dialogs", "Win32_UI_WindowsAndMessaging", ] + +[[bench]] +name = "core" +harness = false + +[[bench]] +name = "formats" +harness = false + +[[bench]] +name = "gpu_cpu" +harness = false + +[[bench]] +name = "runtime" +harness = false diff --git a/crates/xcl/benches/core.rs b/crates/xcl/benches/core.rs new file mode 100644 index 0000000000..1de00df098 --- /dev/null +++ b/crates/xcl/benches/core.rs @@ -0,0 +1,36 @@ +mod support; + +use std::hint::black_box; +use support::Criterion; + +fn core_benches(c: &mut Criterion) { + let encoded = xcl::gpu::rdna2::encode( + "V_ADD_F32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", 258), ("VSRC1", 3)], + None, + ) + .expect("the built-in instruction table must encode V_ADD_F32"); + + c.bench_function("rdna2/decode_vop2", |b| { + b.iter(|| { + black_box( + xcl::gpu::rdna2::decode(black_box(&encoded), 0) + .expect("benchmark instruction must decode"), + ); + }); + }); + + c.bench_function("descriptor/component_mapping", |b| { + b.iter(|| { + black_box(xcl::gpu::desc::component_mapping( + black_box([4, 5, 6, 7]), + black_box([0, 1, 2, 3]), + )); + }); + }); +} + +fn main() { + support::run(&[core_benches]); +} diff --git a/crates/xcl/benches/formats.rs b/crates/xcl/benches/formats.rs new file mode 100644 index 0000000000..a6c1730c91 --- /dev/null +++ b/crates/xcl/benches/formats.rs @@ -0,0 +1,182 @@ +mod support; + +use std::hint::black_box; +use std::time::Duration; +use support::{BenchmarkId, Criterion, Throughput}; +use xcl::gpu::{desc, pack, rdna2}; +use xcl::pe::{Layout, Pe}; + +fn instruction() -> Vec { + rdna2::encode( + "V_ADD_F32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", 128), ("VSRC1", 2)], + None, + ) + .expect("benchmark instruction must encode") +} + +fn rdna2_benches(c: &mut Criterion) { + let inst = instruction(); + let mut group = c.benchmark_group("rdna2_instruction"); + group.throughput(Throughput::Elements(1)); + group.bench_function("encode", |b| { + b.iter(|| { + rdna2::encode( + black_box("V_ADD_F32"), + black_box("ENC_VOP2"), + black_box(&[("VDST", 1), ("SRC0", 128), ("VSRC1", 2)]), + None, + ) + .unwrap() + }) + }); + group.bench_function("decode", |b| { + b.iter(|| rdna2::decode(black_box(&inst), black_box(0x1_0000)).unwrap()) + }); + let decoded = rdna2::decode(&inst, 0x1_0000).unwrap(); + group.bench_function("format", |b| b.iter(|| rdna2::format(black_box(&decoded)))); + group.bench_function("register_uses", |b| { + b.iter(|| { + ( + rdna2::sgpr_uses(black_box(&decoded)), + rdna2::vgpr_uses(black_box(&decoded)), + ) + }) + }); + group.finish(); + + let mut group = c.benchmark_group("rdna2_stream"); + for instructions in [64usize, 1024, 16_384] { + let code = inst.repeat(instructions); + group.throughput(Throughput::Bytes(code.len() as u64)); + group.bench_with_input( + BenchmarkId::new("disassemble", instructions), + &code, + |b, code| b.iter(|| rdna2::disassemble(black_box(code), 0, false)), + ); + } + group.finish(); + + let mut group = c.benchmark_group("rdna2_program_scan"); + for bytes in [4 * 1024usize, 256 * 1024, 4 * 1024 * 1024] { + let mut blob = vec![0x5au8; bytes]; + // s_endpgm is enough to exercise the scanner's candidate handling without title data. + for at in (0..bytes.saturating_sub(4)).step_by(256) { + blob[at..at + 4].copy_from_slice(&0xbf81_0000u32.to_le_bytes()); + } + group.throughput(Throughput::Bytes(bytes as u64)); + group.bench_with_input(BenchmarkId::from_parameter(bytes), &blob, |b, blob| { + b.iter(|| rdna2::find_programs(black_box(blob))) + }); + } + group.finish(); +} + +fn descriptor_benches(c: &mut Criterion) { + let buffer = desc::buffer_words(0x1_2345_6780, 16, 65_536, 32); + let image = desc::xcl_image_for_view(17, 10, desc::ImageType::D2, 1920, 1080, 1, 11); + let sampler = [0x0000_1000, 0x0000_0000, 0x0000_0000, 0x0000_0000]; + let mut group = c.benchmark_group("gpu_descriptors"); + group.throughput(Throughput::Elements(1)); + group.bench_function("decode_buffer", |b| { + b.iter(|| desc::buffer(black_box(&buffer))) + }); + group.bench_function("decode_image", |b| { + b.iter(|| desc::image(black_box(&image))) + }); + group.bench_function("image_to_d3d12", |b| { + let decoded = desc::image(&image).unwrap(); + b.iter(|| desc::image_d3d12(black_box(&decoded))) + }); + group.bench_function("sampler_to_d3d12", |b| { + b.iter(|| desc::sampler_d3d12(black_box(&sampler), black_box(false))) + }); + group.finish(); +} + +fn manifest_and_config_benches(c: &mut Criterion) { + let languages = (0..64) + .map(|i| format!(r#""#)) + .collect::(); + let xml = format!( + r#"4096StandardAdvanced12345678{languages}"# + ); + let config = toml::to_string(&xcl::config::Config::default()).unwrap(); + let mut group = c.benchmark_group("text_formats"); + group.throughput(Throughput::Bytes(xml.len() as u64)); + group.bench_function("manifest_xml", |b| { + b.iter(|| xcl::manifest::parse(black_box(&xml))) + }); + group.throughput(Throughput::Bytes(config.len() as u64)); + group.bench_function("config_toml", |b| { + b.iter(|| toml::from_str::(black_box(&config)).unwrap()) + }); + group.finish(); +} + +fn record(name: &str, payload: &[u8]) -> Vec { + let compressed = miniz_oxide::deflate::compress_to_vec(payload, 6); + let mut out = vec![(name.len() + 1) as u8]; + out.extend_from_slice(name.as_bytes()); + out.push(0); + out.push(50); + for value in [ + compressed.len() as u32, + 0, + compressed.len() as u32, + payload.len() as u32, + ] { + out.extend_from_slice(&value.to_le_bytes()); + } + out.extend_from_slice(&compressed); + out +} + +fn pack_benches(c: &mut Criterion) { + let payload = (0..16 * 1024).map(|i| (i % 251) as u8).collect::>(); + let one = record("CS_SyntheticBenchmark", &payload); + let mut archive = b"9FPR".to_vec(); + archive.resize(4096, 0xa5); + for i in 0..256 { + archive.extend_from_slice(&record(&format!("CS_Synthetic_{i:04}"), &payload)); + archive.extend_from_slice(&[0xde, 0xad, 0xbe, 0xef]); + } + archive.extend_from_slice(&[0; 40]); + let records = pack::scan(&one, 0); + assert_eq!(records.len(), 1); + + let mut group = c.benchmark_group("rpf_records"); + group.sample_size(20); + group.measurement_time(Duration::from_secs(4)); + group.throughput(Throughput::Bytes(archive.len() as u64)); + group.bench_function("scan_256_records", |b| { + b.iter(|| pack::scan(black_box(&archive), 0)) + }); + group.throughput(Throughput::Bytes(payload.len() as u64)); + group.bench_function("inflate_16k", |b| { + b.iter(|| pack::inflate(black_box(&one), black_box(&records[0])).unwrap()) + }); + group.finish(); +} + +fn pe_benches(c: &mut Criterion) { + let exe = std::env::current_exe().expect("benchmark executable path"); + let bytes = std::fs::read(exe).expect("benchmark executable bytes"); + let mut group = c.benchmark_group("pe"); + group.throughput(Throughput::Bytes(bytes.len() as u64)); + group.bench_function("parse_benchmark_executable", |b| { + b.iter(|| Pe::parse(black_box(&bytes), Layout::File).unwrap()) + }); + group.finish(); +} + +fn main() { + support::run(&[ + rdna2_benches, + descriptor_benches, + manifest_and_config_benches, + pack_benches, + pe_benches, + ]); +} diff --git a/crates/xcl/benches/gpu_cpu.rs b/crates/xcl/benches/gpu_cpu.rs new file mode 100644 index 0000000000..7bdf2079df --- /dev/null +++ b/crates/xcl/benches/gpu_cpu.rs @@ -0,0 +1,173 @@ +mod support; + +use std::hint::black_box; +use support::{BenchmarkId, Criterion, Throughput}; +use xcl::gpu::{desc, rdna2, recomp, shader, xbox}; + +const VGPR0: u64 = 256; + +fn instruction(name: &str, encoding: &str, fields: &[(&str, u64)]) -> Vec { + rdna2::encode(name, encoding, fields, None).unwrap() +} + +fn arithmetic_program(instructions: usize) -> Vec { + let add = instruction( + "V_ADD_NC_U32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", VGPR0 + 2), ("VSRC1", 3)], + ); + let xor = instruction( + "V_XOR_B32", + "ENC_VOP2", + &[("VDST", 4), ("SRC0", VGPR0 + 1), ("VSRC1", 5)], + ); + let mut code = Vec::with_capacity(instructions * 4 + 4); + for i in 0..instructions { + code.extend(if i & 1 == 0 { &add } else { &xor }); + } + code.extend(instruction("S_ENDPGM", "ENC_SOPP", &[])); + code +} + +fn branch_program(blocks: usize) -> Vec { + let mov = instruction("S_MOV_B32", "ENC_SOP1", &[("SDST", 0), ("SSRC0", 128)]); + let branch = instruction("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 1)]); + let add = instruction( + "V_ADD_NC_U32", + "ENC_VOP2", + &[("VDST", 1), ("SRC0", VGPR0 + 2), ("VSRC1", 3)], + ); + let mut code = Vec::with_capacity(blocks * 12 + 4); + for _ in 0..blocks { + code.extend(&mov); + code.extend(&branch); + code.extend(&add); + } + code.extend(instruction("S_ENDPGM", "ENC_SOPP", &[])); + code +} + +fn rdna2_frontend(c: &mut Criterion) { + let code = arithmetic_program(1024); + let mesh_control_flow = branch_program(256); + let mut group = c.benchmark_group("rdna2_frontend"); + group.throughput(Throughput::Bytes(code.len() as u64)); + group.bench_function("decode_stream", |b| { + b.iter(|| { + let mut offset = 0; + while offset < code.len() { + let decoded = rdna2::decode(black_box(&code[offset..]), offset as u64).unwrap(); + offset += black_box(decoded.len); + } + black_box(offset) + }) + }); + group.bench_function("disassemble", |b| { + b.iter(|| black_box(rdna2::disassemble(black_box(&code), 0, false))) + }); + group.bench_function("wave_hazard_scan", |b| { + b.iter(|| black_box(recomp::wave_hazards(black_box(&code)))) + }); + group.bench_function("geometry_wave32_hazard_scan", |b| { + b.iter(|| black_box(recomp::geometry_wave32_hazards(black_box(&code)))) + }); + group.throughput(Throughput::Bytes(mesh_control_flow.len() as u64)); + group.bench_function("mesh_wave_analysis", |b| { + b.iter(|| black_box(recomp::mesh_wave::analyze(black_box(&mesh_control_flow)))) + }); + group.finish(); +} + +fn translate(c: &mut Criterion) { + let mut group = c.benchmark_group("recompiler_translate"); + group.sample_size(20); + for size in [16usize, 64, 256] { + let code = arithmetic_program(size); + group.throughput(Throughput::Elements((size + 1) as u64)); + group.bench_with_input(BenchmarkId::new("linear", size), &code, |b, code| { + b.iter(|| { + let translated = + recomp::translate(black_box(code), black_box(&recomp::Options::default())) + .unwrap(); + black_box(( + translated.hlsl.len(), + translated.instructions, + translated.blocks, + )) + }) + }); + } + for blocks in [8usize, 32] { + let code = branch_program(blocks); + group.throughput(Throughput::Elements((blocks * 3 + 1) as u64)); + group.bench_with_input( + BenchmarkId::new("control_flow", blocks), + &code, + |b, code| { + b.iter(|| { + let translated = + recomp::translate(black_box(code), black_box(&recomp::Options::default())) + .unwrap(); + black_box(( + translated.hlsl.len(), + translated.instructions, + translated.blocks, + )) + }) + }, + ); + } + group.finish(); +} + +fn descriptors(c: &mut Criterion) { + let image = desc::xcl_image_for_view(7, 10, desc::ImageType::D2, 1920, 1080, 1, 11); + let buffer = desc::buffer_words(0x1_2345_6000, 16, 65_536, 74); + let sampler = [0x0000_0002, 0x0000_0101, 0x3f80_0000, 0x0000_0000]; + let mut group = c.benchmark_group("descriptor_conversion"); + group.bench_function("decode_image", |b| { + b.iter(|| black_box(desc::image(black_box(&image)))) + }); + group.bench_function("image_to_d3d12", |b| { + let decoded = desc::image(&image).unwrap(); + b.iter(|| black_box(desc::image_d3d12(black_box(&decoded)))) + }); + group.bench_function("decode_buffer", |b| { + b.iter(|| black_box(desc::buffer(black_box(&buffer)))) + }); + group.bench_function("sampler_to_d3d12", |b| { + b.iter(|| black_box(desc::sampler_d3d12(black_box(&sampler), false))) + }); + group.finish(); +} + +fn shader_scans(c: &mut Criterion) { + let program = arithmetic_program(1024); + let mut blob = vec![0u8; 4096]; + for _ in 0..16 { + blob.extend_from_slice(&program); + blob.extend_from_slice(&[0u8; 64]); + } + let mut group = c.benchmark_group("shader_scans"); + group.throughput(Throughput::Bytes(blob.len() as u64)); + group.bench_function("find_rdna2_programs", |b| { + b.iter(|| black_box(rdna2::find_programs(black_box(&blob)))) + }); + group.throughput(Throughput::Bytes(program.len() as u64)); + group.bench_function("classify_raw_rdna2", |b| { + b.iter(|| black_box(shader::classify(black_box(&program)))) + }); + group.throughput(Throughput::Bytes(blob.len() as u64)); + group.bench_function("fnv64", |b| { + b.iter(|| black_box(shader::fnv64(black_box(&blob)))) + }); + group.throughput(Throughput::Bytes(program.len() as u64)); + group.bench_function("split_segments", |b| { + b.iter(|| black_box(xbox::split_segments(black_box(&program)))) + }); + group.finish(); +} + +fn main() { + support::run(&[rdna2_frontend, translate, descriptors, shader_scans]); +} diff --git a/crates/xcl/benches/runtime.rs b/crates/xcl/benches/runtime.rs new file mode 100644 index 0000000000..6dd6d4f33c --- /dev/null +++ b/crates/xcl/benches/runtime.rs @@ -0,0 +1,310 @@ +mod support; + +use std::collections::BTreeMap; +use std::hint::black_box; +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Barrier}; +use std::thread::JoinHandle; +use support::{BatchSize, BenchmarkId, Criterion, Throughput}; +use xcl::config::Config; +use xcl::manifest; +use xcl::util; +use xcl::vfs::Vfs; + +const MANIFEST: &str = r#" + + 4096 + + Advanced + Standard + + 12345678 + + + + +"#; + +const CONFIG: &str = r#" +device_type = "anaconda" +gamertag = "Player" +user_id = 281474976710655 +title_memory = "auto" +pls_mb = 0 +uma_mb = 0 +log_level = "info" +graphics = "d3d12" +d3d12_adapter = "auto" +present = "auto" +raytracing = "auto" +window_width = 1280 +window_height = 720 +keyboard_mouse = true +mouse_sensitivity = 1.0 + +[mounts] +"GAME:" = "{game}" +"G:" = "{game}" +"S:" = "{data}\\pls" + +[aliases] +"api-ms-win-*" = "@system" +"kernelx.dll" = "kernelx.dll" + +[stub_returns] +"example.dll!Example" = "S_OK" +"#; + +const ALLOCATION_JOBS: usize = 128; + +struct AllocationJob { + owner: Arc<[u8; 64]>, + label: String, + payload: Vec, +} + +fn allocation_job_batch(seed: usize) -> usize { + let owner = Arc::new([seed as u8; 64]); + let mut jobs = Vec::with_capacity(ALLOCATION_JOBS); + for index in 0..ALLOCATION_JOBS { + let mut label = String::with_capacity(48); + label.push_str("pipeline-job-"); + label.extend(std::iter::repeat_n((b'a' + (index % 26) as u8) as char, 16 + index % 16)); + jobs.push(Box::new(AllocationJob { + owner: owner.clone(), + label, + payload: vec![(seed ^ index) as u8; 96 + index % 64], + })); + } + let checksum = jobs.iter().fold(0usize, |checksum, job| { + checksum ^ job.owner[0] as usize ^ job.label.len() ^ job.payload.len() + }); + black_box(&jobs); + checksum +} + +#[repr(align(64))] +struct AllocationResult(AtomicUsize); + +struct AllocationWorkers { + start: Arc, + done: Arc, + stop: Arc, + epoch: Arc, + results: Arc>, + threads: Vec>, +} + +impl AllocationWorkers { + fn new(count: usize) -> Self { + let start = Arc::new(Barrier::new(count + 1)); + let done = Arc::new(Barrier::new(count + 1)); + let stop = Arc::new(AtomicBool::new(false)); + let epoch = Arc::new(AtomicUsize::new(0)); + let results: Arc> = + Arc::new((0..count).map(|_| AllocationResult(AtomicUsize::new(0))).collect()); + let threads = (0..count).map(|worker| { + let start = start.clone(); + let done = done.clone(); + let stop = stop.clone(); + let epoch = epoch.clone(); + let results = results.clone(); + std::thread::Builder::new().name(format!("alloc-bench-{worker}")).spawn(move || loop { + start.wait(); + if stop.load(Ordering::Acquire) { break } + let checksum = allocation_job_batch(epoch.load(Ordering::Acquire).wrapping_add(worker)); + results[worker].0.store(checksum, Ordering::Release); + done.wait(); + }).expect("allocator benchmark worker") + }).collect(); + Self { start, done, stop, epoch, results, threads } + } + + fn run(&self) -> usize { + self.epoch.fetch_add(1, Ordering::Release); + self.start.wait(); + self.done.wait(); + self.results.iter().fold(0, |checksum, result| checksum ^ result.0.load(Ordering::Acquire)) + } +} + +impl Drop for AllocationWorkers { + fn drop(&mut self) { + self.stop.store(true, Ordering::Release); + self.start.wait(); + for thread in self.threads.drain(..) { + thread.join().expect("allocator benchmark worker panicked"); + } + } +} + +fn allocator_benches(c: &mut Criterion) { + let mut group = c.benchmark_group("runtime/allocator"); + group.throughput(Throughput::Elements(ALLOCATION_JOBS as u64)); + group.bench_function("job_mix_single", |b| { + let mut seed = 0usize; + b.iter(|| { + seed = seed.wrapping_add(1); + allocation_job_batch(black_box(seed)) + }); + }); + + let workers = std::thread::available_parallelism().map_or(4, |count| count.get()) + .saturating_sub(1).clamp(2, 8); + let pool = AllocationWorkers::new(workers); + group.throughput(Throughput::Elements((ALLOCATION_JOBS * workers) as u64)); + group.bench_function(&format!("job_mix_parallel_{workers}"), |b| b.iter(|| pool.run())); + group.finish(); +} + +fn utility_benches(c: &mut Criterion) { + let mut group = c.benchmark_group("runtime/util"); + for (name, pattern, value) in [ + ("glob_exact", "kernelx.dll", "kernelx.dll"), + ( + "glob_prefix", + "api-ms-win-*", + "api-ms-win-core-file-l2-1-0.dll", + ), + ("glob_bounded", "xgame*.dll", "xgameruntime.dll"), + ] { + group.bench_function(name, |b| { + b.iter(|| util::glob_match(black_box(pattern), black_box(value))) + }); + } + for value in [ + "kernelx", + "D:\\Game\\D3D12_XS.DLL", + "api-ms-win-core-file-l2-1-0", + ] { + group.bench_with_input( + BenchmarkId::new("dll_key", value.len()), + value, + |b, value| { + b.iter(|| util::dll_key(black_box(value))); + }, + ); + } + for value in ["S_OK", "E_NOTIMPL", "0x80004005", "42"] { + group.bench_with_input( + BenchmarkId::new("parse_return", value), + value, + |b, value| { + b.iter(|| util::parse_ret(black_box(value))); + }, + ); + } + for value in [ + "short", + "D:\\Synthetic Game\\Content\\localization\\en-US\\strings.bin", + ] { + group.throughput(Throughput::Bytes(value.len() as u64)); + group.bench_with_input(BenchmarkId::new("utf16", value.len()), value, |b, value| { + b.iter(|| util::wide(black_box(value))); + }); + } + group.finish(); +} + +fn manifest_and_config_benches(c: &mut Criterion) { + let mut group = c.benchmark_group("runtime/config"); + group.throughput(Throughput::Bytes(MANIFEST.len() as u64)); + group.bench_function("manifest_parse", |b| { + b.iter(|| manifest::parse(black_box(MANIFEST))) + }); + + group.throughput(Throughput::Bytes(CONFIG.len() as u64)); + group.bench_function("toml_parse", |b| { + b.iter(|| toml::from_str::(black_box(CONFIG)).unwrap()); + }); + + let parsed_manifest = manifest::parse(MANIFEST); + group.throughput(Throughput::Elements(1)); + group.bench_function("resolve_defaults", |b| { + b.iter_batched( + Config::default, + |mut config| black_box(config.resolve(black_box(Some(&parsed_manifest)))), + BatchSize::SmallInput, + ); + }); + + let mut mounts = BTreeMap::new(); + mounts.insert("GAME:".to_owned(), "{game}".to_owned()); + mounts.insert("S:".to_owned(), "{data}\\pls".to_owned()); + let mut resolved = Config { + mounts, + ..Config::default() + }; + resolved.resolve(Some(&parsed_manifest)); + group.throughput(Throughput::Elements(1)); + group.bench_function("resolved_memory_queries", |b| { + b.iter(|| { + black_box(resolved.title_memory_budget_mb()); + black_box(resolved.pls_drive()); + black_box(resolved.raytracing_tier_override()); + }); + }); + group.finish(); +} + +fn vfs_benches(c: &mut Criterion) { + let vfs = Vfs::new( + Path::new(r"C:\bench\game"), + Path::new(r"C:\bench\data"), + vec![ + ("GAME:".to_owned(), r"C:\bench\game".to_owned()), + ("G:".to_owned(), r"C:\bench\game".to_owned()), + ("S:".to_owned(), r"C:\bench\data\pls".to_owned()), + ], + ); + let full = |path: &str| Some(path.replace('/', "\\")); + let cases = [ + ("mounted_game", r"GAME:\data\textures.bin"), + ("mounted_drive", r"G:\data\textures.bin"), + ("embedded_mount", r"C:\cwd\GAME:\data\textures.bin"), + ("direct_game", r"C:\bench\game\data\textures.bin"), + ("host_path", r"C:\Windows\System32\kernel32.dll"), + ("unc", r"\\server\share\file.bin"), + ]; + + let mut group = c.benchmark_group("runtime/vfs"); + for (name, path) in cases { + group.throughput(Throughput::Bytes(path.len() as u64)); + group.bench_with_input(BenchmarkId::new("classify", name), path, |b, path| { + b.iter(|| vfs.classify_with(black_box(path), black_box(full))); + }); + } + group.throughput(Throughput::Bytes( + cases.iter().map(|(_, path)| path.len() as u64).sum(), + )); + group.bench_function("classify_mixed_batch", |b| { + b.iter(|| { + for (_, path) in black_box(&cases) { + black_box(vfs.classify_with(path, full)); + } + }); + }); + for rel in ["", "data", r"data\textures\terrain.bin"] { + group.throughput(Throughput::Elements(1)); + group.bench_with_input( + BenchmarkId::new("overlay_path", rel.len()), + rel, + |b, rel| { + b.iter(|| vfs.overlay_path(black_box(rel))); + }, + ); + group.bench_with_input( + BenchmarkId::new("original_path", rel.len()), + rel, + |b, rel| { + b.iter(|| vfs.original_path(black_box(rel))); + }, + ); + } + group.finish(); +} + +fn main() { + support::run(&[utility_benches, manifest_and_config_benches, vfs_benches, allocator_benches]); +} diff --git a/crates/xcl/benches/support/mod.rs b/crates/xcl/benches/support/mod.rs new file mode 100644 index 0000000000..74c6d6fee7 --- /dev/null +++ b/crates/xcl/benches/support/mod.rs @@ -0,0 +1,265 @@ +#![allow(dead_code)] + +use std::fmt::Display; +use std::hint::black_box; +use std::time::{Duration, Instant}; + +#[derive(Clone)] +struct Config { + test: bool, + filter: Option, +} + +pub struct Criterion { + config: Config, + ran: usize, +} + +pub struct BenchmarkGroup<'a> { + criterion: &'a mut Criterion, + name: String, + throughput: Option, + sample_size: usize, + measurement_time: Duration, +} + +pub struct Bencher { + name: String, + test: bool, + throughput: Option, + sample_size: usize, + measurement_time: Duration, +} + +#[derive(Clone, Copy)] +pub enum Throughput { + Bytes(u64), + Elements(u64), +} + +pub enum BatchSize { + SmallInput, +} + +pub struct BenchmarkId(String); + +fn median(sorted: &[f64]) -> f64 { + let middle = sorted.len() / 2; + if sorted.len() % 2 == 0 { + (sorted[middle - 1] + sorted[middle]) / 2.0 + } else { + sorted[middle] + } +} + +fn test_helpers() { + assert_eq!(median(&[1.0, 3.0]), 2.0); + assert_eq!(median(&[1.0, 4.0, 9.0]), 4.0); +} + +impl BenchmarkId { + pub fn new(name: impl Display, parameter: impl Display) -> Self { + Self(format!("{name}/{parameter}")) + } + + pub fn from_parameter(parameter: impl Display) -> Self { + Self(parameter.to_string()) + } +} + +impl Display for BenchmarkId { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.0.fmt(f) + } +} + +impl Criterion { + fn from_args() -> Self { + let mut test = false; + let mut filter = None; + for argument in std::env::args().skip(1) { + if argument == "--test" { + test = true; + } else if !argument.starts_with('-') && filter.is_none() { + filter = Some(argument); + } + } + Self { config: Config { test, filter }, ran: 0 } + } + + pub fn benchmark_group<'a>(&'a mut self, name: &str) -> BenchmarkGroup<'a> { + BenchmarkGroup { + criterion: self, + name: name.to_owned(), + throughput: None, + sample_size: 30, + measurement_time: Duration::from_secs(2), + } + } + + pub fn bench_function(&mut self, name: &str, routine: impl FnMut(&mut Bencher)) { + self.run_one(name.to_owned(), None, 30, Duration::from_secs(2), routine); + } + + fn run_one( + &mut self, + name: String, + throughput: Option, + sample_size: usize, + measurement_time: Duration, + mut routine: impl FnMut(&mut Bencher), + ) { + if self.config.filter.as_ref().is_some_and(|filter| !name.contains(filter)) { + return; + } + self.ran += 1; + routine(&mut Bencher { + name, + test: self.config.test, + throughput, + sample_size: sample_size.max(3), + measurement_time, + }); + } +} + +impl BenchmarkGroup<'_> { + pub fn throughput(&mut self, throughput: Throughput) { + self.throughput = Some(throughput); + } + + pub fn sample_size(&mut self, sample_size: usize) { + self.sample_size = sample_size; + } + + pub fn measurement_time(&mut self, measurement_time: Duration) { + self.measurement_time = measurement_time; + } + + pub fn bench_function(&mut self, name: &str, routine: impl FnMut(&mut Bencher)) { + let name = format!("{}/{}", self.name, name); + self.criterion.run_one( + name, self.throughput, self.sample_size, self.measurement_time, routine, + ); + } + + pub fn bench_with_input( + &mut self, + id: BenchmarkId, + input: &T, + mut routine: impl FnMut(&mut Bencher, &T), + ) { + let name = format!("{}/{}", self.name, id); + self.criterion.run_one( + name, + self.throughput, + self.sample_size, + self.measurement_time, + |bencher| routine(bencher, input), + ); + } + + pub fn finish(self) {} +} + +impl Bencher { + pub fn iter(&mut self, mut routine: impl FnMut() -> R) { + if self.test { + let _ = black_box(routine()); + println!("test {} ... ok", self.name); + return; + } + self.measure_iterations(|iterations| { + let started = Instant::now(); + for _ in 0..iterations { + let _ = black_box(routine()); + } + started.elapsed() + }); + } + + pub fn iter_batched( + &mut self, + mut setup: impl FnMut() -> I, + mut routine: impl FnMut(I) -> R, + _batch_size: BatchSize, + ) { + if self.test { + let input = setup(); + let _ = black_box(routine(input)); + println!("test {} ... ok", self.name); + return; + } + self.measure_iterations(|iterations| { + let mut elapsed = Duration::ZERO; + let mut remaining = iterations; + while remaining != 0 { + let batch = remaining.min(1_024) as usize; + let inputs: Vec<_> = (0..batch).map(|_| setup()).collect(); + let started = Instant::now(); + for input in inputs { + let _ = black_box(routine(input)); + } + elapsed += started.elapsed(); + remaining -= batch as u64; + } + elapsed + }); + } + + fn measure_iterations(&self, mut run: impl FnMut(u64) -> Duration) { + let warmup = self.measurement_time.div_f64(10.0).min(Duration::from_millis(100)); + let mut iterations = 1u64; + let elapsed = loop { + let elapsed = run(iterations); + if elapsed >= warmup || iterations >= 1 << 40 { + break elapsed; + } + let scale = (warmup.as_secs_f64() / elapsed.as_secs_f64().max(1e-9)).ceil() as u64; + iterations = iterations.saturating_mul(scale.clamp(2, 10)).min(1 << 40); + }; + + let seconds_per_iteration = elapsed.as_secs_f64() / iterations as f64; + let target_sample = self.measurement_time.as_secs_f64() / self.sample_size as f64; + let sample_iterations = (target_sample / seconds_per_iteration.max(1e-12)) + .ceil() + .clamp(1.0, (1u64 << 40) as f64) as u64; + let mut samples = Vec::with_capacity(self.sample_size); + for _ in 0..self.sample_size { + samples.push(run(sample_iterations).as_secs_f64() / sample_iterations as f64); + } + samples.sort_unstable_by(f64::total_cmp); + let median = median(&samples); + let mean = samples.iter().sum::() / samples.len() as f64; + let minimum = samples[0]; + print!( + "bench {}: median {:.1} ns/iter, mean {:.1}, min {:.1}", + self.name, + median * 1e9, + mean * 1e9, + minimum * 1e9, + ); + if let Some(throughput) = self.throughput { + let (amount, unit) = match throughput { + Throughput::Bytes(amount) => (amount, "B/s"), + Throughput::Elements(amount) => (amount, "elem/s"), + }; + print!(", {:.1} {unit}", amount as f64 / median.max(1e-12)); + } + println!(); + } +} + +pub fn run(groups: &[fn(&mut Criterion)]) { + let mut criterion = Criterion::from_args(); + if criterion.config.test { + test_helpers(); + } + for group in groups { + group(&mut criterion); + } + if criterion.ran == 0 { + eprintln!("no benchmark matched the requested filter"); + std::process::exit(2); + } +} diff --git a/crates/xcl/build.rs b/crates/xcl/build.rs index 22b136da8e..65ab22ece0 100644 --- a/crates/xcl/build.rs +++ b/crates/xcl/build.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; // `pso.rs` also contains cache storage and pipeline setup. Keep it out of the source hash so // those changes do not discard translations; bump this only when its container parsing, // translation options, profiles, or post-translation HLSL changes. -const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v2"; +const TRANSLATION_GLUE_REVISION: &str = "pso-glue-v3"; const TRANSLATOR_SOURCES: &[&str] = &[ "src/gpu/dxbc.rs", diff --git a/crates/xcl/src/eh.rs b/crates/xcl/src/eh.rs index 2d431e5a47..2a94cd36e0 100644 --- a/crates/xcl/src/eh.rs +++ b/crates/xcl/src/eh.rs @@ -136,6 +136,8 @@ unsafe extern "system" fn hk_nt_terminate_process(h: isize, status: i32) -> i32 crate::xlog_info!("process ends (thread {tid}); on the stack: {stack}"); } crate::log::flush(); + crate::hle::d3d12x::pso_async::flush_used_bounded(std::time::Duration::from_millis(100)); + crate::hle::d3d12x::real::flush_indirect_split_records(std::time::Duration::from_millis(100)); } let orig: unsafe extern "system" fn(isize, i32) -> i32 = std::mem::transmute(ORIG_NT_TERMINATE.load(Ordering::Acquire)); orig(h, status) @@ -245,6 +247,97 @@ unsafe fn bounded_cstr(p: usize, max: usize) -> String { String::from_utf8_lossy(&bytes).into_owned() } +/// Code-page protection is page-wide. Serialize these rare first-fault rewrites so two sites on +/// one page cannot restore stale protection over each other. +static CODE_REWRITE: Mutex<()> = Mutex::new(()); +/// A second thread may have faulted at a wait site before the first thread replaced it, then enter +/// the handler after replacement. Recognize that stale exception and retry the now-native bytes. +static REWRITTEN_WAITS: Mutex)>> = Mutex::new(Vec::new()); + +fn rewritten_wait(at: usize, code: &[u8]) -> bool { + let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); + let mut sites = REWRITTEN_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + let Some(index) = sites.iter().position(|(site, _)| *site == at) else { return false }; + if code.starts_with(&sites[index].1) { + true + } else { + sites.swap_remove(index); + false + } +} + +fn remember_rewritten_wait(at: usize, replacement: &[u8]) { + let mut sites = REWRITTEN_WAITS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some((_, bytes)) = sites.iter_mut().find(|(site, _)| *site == at) { + bytes.clear(); + bytes.extend_from_slice(replacement); + } else { + sites.push((at, replacement.to_vec())); + } +} + +#[cfg(test)] +fn forget_rewritten_waits(start: usize, end: usize) { + let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); + REWRITTEN_WAITS.lock().unwrap_or_else(|e| e.into_inner()).retain(|(site, _)| *site < start || *site >= end); +} + +/// Atomically replace `expected` at `off` in an aligned instruction word. A failed compare is +/// retried from the newly observed word so an adjacent rewrite is never overwritten or mistaken +/// for success. +fn replace_code_word(cell: &std::sync::atomic::AtomicU64, off: usize, expected: &[u8], new: &[u8]) -> bool { + replace_code_word_from(cell, off, expected, new, cell.load(Ordering::Acquire)) +} + +fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expected: &[u8], new: &[u8], mut was: u64) -> bool { + loop { + let mut bytes = was.to_le_bytes(); + if bytes[off..off + new.len()] == *new { + return true; + } + if bytes[off..off + expected.len()] != *expected { + return false; + } + bytes[off..off + new.len()].copy_from_slice(new); + match cell.compare_exchange(was, u64::from_le_bytes(bytes), Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(now) => was = now, + } + } +} + +/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads +/// executing it observe either the complete old instruction or the complete replacement. +fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; + use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + let word = at & !7; + let off = at - word; + if expected.is_empty() || expected.len() != new.len() || off + new.len() > 8 { + return false; + } + let _serial = CODE_REWRITE.lock().unwrap_or_else(|e| e.into_inner()); + let mut old = 0u32; + unsafe { + if VirtualProtect(word as *const c_void, 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 { + return false; + } + let cell = &*(word as *const std::sync::atomic::AtomicU64); + let replaced = replace_code_word(cell, off, expected, new); + // Publish while CODE_REWRITE is still held. A stale exception lookup takes the same lock + // first, so it cannot observe the replacement without its registry entry. The bytes have + // changed even if restoring protection or flushing the cache below reports failure. + if replaced { + remember_rewritten_wait(at, new); + } + let mut ignored = 0u32; + let restored = VirtualProtect(word as *const c_void, 8, old, &mut ignored) != 0; + let flushed = FlushInstructionCache(GetCurrentProcess(), word as *const c_void, 8) != 0; + replaced && restored && flushed + } +} + fn is_writable(va: usize, bytes: usize) -> bool { use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READWRITE, PAGE_READWRITE}; // a committed window of unified memory is read-write as a whole and is not asked about, as in @@ -253,6 +346,9 @@ fn is_writable(va: usize, bytes: usize) -> bool { if bytes > 0 && crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(va, bytes)) { return true; } + if crate::hle::d3d12x::sparse::known_writable(va, bytes) { + return true; + } let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let found = unsafe { VirtualQuery(va as *const std::ffi::c_void, &mut m, std::mem::size_of_val(&m)) } != 0; found @@ -321,6 +417,9 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics let n = code_bytes_at(rip, 16); let code = std::slice::from_raw_parts(rip as *const u8, n); let Some((what, len)) = crate::insn::decode(code) else { + if rewritten_wait(rip, code) { + return -1; + } crate::xlog_error!("illegal instruction in {}: code bytes {}", modules::describe_address(rip), crate::insn::hex(code)); return 0; }; @@ -347,9 +446,19 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; } } - ConsoleOnly::Monitorx => {} + ConsoleOnly::Monitorx => { + let mut expected = [0u8; 16]; + expected[..len].copy_from_slice(&code[..len]); + let replacement = &[0x90; 16][..len]; + rewrite_code(rip, &expected[..len], replacement); + } ConsoleOnly::Mwaitx => { std::hint::spin_loop(); + let mut expected = [0u8; 16]; + expected[..len].copy_from_slice(&code[..len]); + let mut replacement = [0x90u8; 16]; + replacement[0] = 0xF3; + rewrite_code(rip, &expected[..len], &replacement[..len]); } ConsoleOnly::Clzero => { // with an address-size prefix (0x67, among the prefixes before 0F 01 FC) the line @@ -1001,6 +1110,111 @@ mod tests { assert_eq!(find_gs_check(&[0x48; 64]), None); } + #[test] + fn monitorx_and_mwaitx_are_rewritten_at_their_first_fault() { + use std::sync::{atomic::AtomicBool, Arc}; + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE}; + let code = unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE) as usize }; + assert_ne!(code, 0); + modules::register_mapped(Arc::new(modules::MappedModule { + name: "wait_rewrite.exe".into(), path: "wait_rewrite.exe".into(), base: code, size: 0x1000, entry_rva: 0, is_dll: false, + exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), stack_reserve: 0, + })); + for (offset, before, after) in [ + (0x10usize, [0x0F, 0x01, 0xFA], [0x90, 0x90, 0x90]), + (0x20usize, [0x0F, 0x01, 0xFB], [0xF3, 0x90, 0x90]), + ] { + unsafe { + std::ptr::copy_nonoverlapping(before.as_ptr(), (code + offset) as *mut u8, before.len()); + let mut ctx: windows_sys::Win32::System::Diagnostics::Debug::CONTEXT = std::mem::zeroed(); + ctx.Rip = (code + offset) as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (code + offset + before.len()) as u64); + assert_eq!(std::slice::from_raw_parts((code + offset) as *const u8, before.len()), &after); + // A second exception may already be in flight with RIP at the old instruction. + // Retry the replacement at the same RIP instead of treating its NOPs as unknown. + ctx.Rip = (code + offset) as u64; + assert_eq!(emulate_console_only(&mut ctx), -1); + assert_eq!(ctx.Rip, (code + offset) as u64); + } + } + forget_rewritten_waits(code, code + 0x1000); + modules::unregister_mapped(code); + unsafe { VirtualFree(code as *mut c_void, 0, MEM_RELEASE) }; + } + + #[test] + fn a_lost_compare_reloads_and_preserves_an_adjacent_rewrite() { + use std::sync::atomic::AtomicU64; + let original = u64::from_le_bytes([0x0F, 0x01, 0xFA, 0xCC, 0x0F, 0x01, 0xFB, 0xCC]); + let cell = AtomicU64::new(original); + let stale = cell.load(Ordering::Acquire); + // The other site wins after our initial load, exactly the raw PR's lost-CAS window. + cell.store(u64::from_le_bytes([0x0F, 0x01, 0xFA, 0xCC, 0xF3, 0x90, 0x90, 0xCC]), Ordering::Release); + assert!(replace_code_word_from(&cell, 0, &[0x0F, 0x01, 0xFA], &[0x90; 3], stale)); + assert_eq!(cell.load(Ordering::Acquire).to_le_bytes(), [0x90, 0x90, 0x90, 0xCC, 0xF3, 0x90, 0x90, 0xCC]); + } + + #[test] + fn concurrent_adjacent_rewrites_preserve_bytes_and_page_protection() { + use std::sync::{Arc, Barrier}; + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE, + }; + let page = unsafe { VirtualAlloc(std::ptr::null(), 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize }; + assert_ne!(page, 0); + let first = [0x0F, 0x01, 0xFA]; + let second = [0x0F, 0x01, 0xFB]; + unsafe { + std::ptr::copy_nonoverlapping(first.as_ptr(), page as *mut u8, first.len()); + std::ptr::copy_nonoverlapping(second.as_ptr(), (page + 4) as *mut u8, second.len()); + let mut old = 0u32; + assert_ne!(VirtualProtect(page as *const c_void, 0x1000, PAGE_EXECUTE_READ, &mut old), 0); + } + // Enough simultaneous callers to force the raw PR's word-CAS and page-protection windows + // to overlap. Serialization makes every caller observe the completed adjacent update. + const THREADS: usize = 32; + let start = Arc::new(Barrier::new(THREADS + 1)); + let mut workers = Vec::new(); + for n in 0..THREADS { + let start = start.clone(); + workers.push(std::thread::spawn(move || { + start.wait(); + if n & 1 == 0 { + rewrite_code(page, &first, &[0x90; 3]) + } else { + rewrite_code(page + 4, &second, &[0xF3, 0x90, 0x90]) + } + })); + } + start.wait(); + for worker in workers { + assert!(worker.join().unwrap()); + } + unsafe { + assert_eq!(std::slice::from_raw_parts(page as *const u8, 3), &[0x90; 3]); + assert_eq!(std::slice::from_raw_parts((page + 4) as *const u8, 3), &[0xF3, 0x90, 0x90]); + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(page as *const c_void, &mut info, std::mem::size_of_val(&info)), 0); + assert_eq!(info.Protect, PAGE_EXECUTE_READ, "concurrent rewrites must restore RX, not stale RWX"); + forget_rewritten_waits(page, page + 0x1000); + VirtualFree(page as *mut c_void, 0, MEM_RELEASE); + } + } + + #[test] + fn a_rewrite_crossing_an_atomic_word_stays_emulated() { + let mut buf = [0xCCu8; 24]; + let word = (buf.as_mut_ptr() as usize + 7) & !7; + let at = word + 6; + let before = [0x0F, 0x01, 0xFA]; + unsafe { std::ptr::copy_nonoverlapping(before.as_ptr(), at as *mut u8, before.len()) }; + assert!(!rewrite_code(at, &before, &[0x90; 3])); + assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, 3) }, &before); + } + /// `67 0F 01 FC`: CLZERO at EAX. rax's upper half set, and memory mapped at both the 64- and /// the 32-bit address: only the 32-bit one's line is zeroed. #[test] diff --git a/crates/xcl/src/gpu/dxil/cfg.rs b/crates/xcl/src/gpu/dxil/cfg.rs index 31b3dcec2a..4f114cb15e 100644 --- a/crates/xcl/src/gpu/dxil/cfg.rs +++ b/crates/xcl/src/gpu/dxil/cfg.rs @@ -1,7 +1,7 @@ //! Basic blocks of a decoded RDNA2 program, their edges and a reverse //! post-order (the emission order: every block after its dominators). -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeSet; use crate::gpu::rdna2::{self, Decoded}; @@ -58,35 +58,47 @@ impl Cfg { insts.push(d); } rdna2::resolve_far_jumps(&mut insts); - let index: BTreeMap = insts.iter().enumerate().map(|(i, d)| (d.pc, i)).collect(); - let mut leaders: BTreeSet = BTreeSet::from([0]); + let index_of = |pc: u64| insts.binary_search_by_key(&pc, |d| d.pc).ok(); + let mut is_leader = vec![false; insts.len()]; + if !is_leader.is_empty() { + is_leader[0] = true; + } let is_setpc = |d: &Decoded| setpc.is_some() && d.inst.name == "S_SETPC_B64" && d.far_target.is_none(); let setpc_target = match setpc { - Some(Some(t)) => Some(*index.get(&t).ok_or_else(|| format!("GS start {t:#x} is not the start of an instruction"))?), + Some(Some(t)) => Some(index_of(t).ok_or_else(|| format!("GS start {t:#x} is not the start of an instruction"))?), _ => None, }; if let Some(t) = setpc_target { - leaders.insert(t); + is_leader[t] = true; } for (i, d) in insts.iter().enumerate() { if is_setpc(d) { - leaders.insert(i + 1); + if i + 1 < is_leader.len() { + is_leader[i + 1] = true; + } continue; } if let Some(t) = rdna2::branch_target(d) { - let ti = *index.get(&t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which is not the start of an instruction", d.pc))?; - leaders.insert(ti); - leaders.insert(i + 1); + let ti = index_of(t).ok_or_else(|| format!("+{:#x}: branch to {t:#x}, which is not the start of an instruction", d.pc))?; + is_leader[ti] = true; + if i + 1 < is_leader.len() { + is_leader[i + 1] = true; + } } else if d.inst.flags & rdna2::F_TERMINATOR != 0 || is_end(d.inst.name) { - leaders.insert(i + 1); + if i + 1 < is_leader.len() { + is_leader[i + 1] = true; + } } } - let starts: Vec = leaders.into_iter().filter(|&l| l < insts.len()).collect(); - let block_of: BTreeMap = starts.iter().enumerate().map(|(b, &i)| (i, b)).collect(); - let mut blocks = Vec::new(); + let starts: Vec = (0..insts.len()).filter(|&i| is_leader[i]).collect(); + let mut block_of = vec![usize::MAX; insts.len()]; + for (b, &i) in starts.iter().enumerate() { + block_of[i] = b; + } + let mut blocks = Vec::with_capacity(starts.len()); for (b, &s) in starts.iter().enumerate() { let e = starts.get(b + 1).copied().unwrap_or(insts.len()); - let mut list = Vec::new(); + let mut list = Vec::with_capacity(e - s); let mut term = if e < insts.len() { Term::Jump(b + 1) } else { Term::End }; for i in s..e { let d = &insts[i]; @@ -96,13 +108,13 @@ impl Cfg { } if is_setpc(d) { term = match setpc_target { - Some(t) => Term::Jump(block_of[&t]), + Some(t) => Term::Jump(block_of[t]), None => Term::End, }; break; } if let Some(t) = rdna2::branch_target(d) { - let tb = block_of[&index[&t]]; + let tb = block_of[index_of(t).unwrap()]; let name = d.inst.name; term = if name == "S_BRANCH" || d.far_target.is_some() { Term::Jump(tb) @@ -131,16 +143,13 @@ impl Cfg { // CFG; the console compiler emits loops entered in the middle): split nodes until // every retreating edge is a back edge to a dominator let (post, headers) = make_reducible(&mut blocks)?; - let succ = succ_of; - let reach: BTreeSet = post.iter().copied().collect(); for &b in &post { - for t in succ(&blocks[b]) { + for t in succ_of(&blocks[b]) { if !blocks[t].preds.contains(&b) { blocks[t].preds.push(b); } } } - let _ = reach; Ok(Cfg { insts, blocks, rpo: post, headers }) } } @@ -150,10 +159,20 @@ impl Cfg { /// it elsewhere. The reverse post-order and loop headers of the result; gives up past four /// times the original block count. fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet), String> { + let (post, headers, _) = make_reducible_inner(blocks)?; + Ok((post, headers)) +} + +fn make_reducible_inner(blocks: &mut Vec) -> Result<(Vec, BTreeSet, usize), String> { let limit = 4 * blocks.len() + 256; + let mut dom_passes = 0usize; loop { let (post, headers) = order(blocks); - let Some((_, t)) = irreducible_edge(blocks, &post) else { return Ok((post, headers)) }; + if headers.is_empty() { + return Ok((post, headers, dom_passes)); + } + dom_passes += 1; + let Some((_, t)) = irreducible_edge(blocks, &post) else { return Ok((post, headers, dom_passes)) }; let n = blocks.len(); let mut pos = vec![usize::MAX; n]; for (i, &b) in post.iter().enumerate() { @@ -171,8 +190,9 @@ fn make_reducible(blocks: &mut Vec) -> Result<(Vec, BTreeSet) -> Result<(Vec, BTreeSet Vec { +#[derive(Clone, Copy)] +struct Succs { + buf: [usize; 2], + len: usize, +} + +impl Succs { + fn as_slice(&self) -> &[usize] { + &self.buf[..self.len] + } +} + +impl IntoIterator for Succs { + type Item = usize; + type IntoIter = std::iter::Take>; + fn into_iter(self) -> Self::IntoIter { + self.buf.into_iter().take(self.len) + } +} + +fn succ_of(b: &CfgBlock) -> Succs { match b.term { - Term::Jump(t) => vec![t], - Term::Cond(_, t, f) => vec![t, f], - Term::End => vec![], + Term::Jump(t) => Succs { buf: [t, 0], len: 1 }, + Term::Cond(_, t, f) => Succs { buf: [t, f], len: 2 }, + Term::End => Succs { buf: [0, 0], len: 0 }, } } @@ -236,15 +276,16 @@ fn succ_of(b: &CfgBlock) -> Vec { /// retreating edges. fn order(blocks: &[CfgBlock]) -> (Vec, BTreeSet) { let n = blocks.len(); - let succ = succ_of; let mut state = vec![0u8; n]; // 0 new, 1 on stack, 2 done - let mut post = Vec::new(); + let mut post = Vec::with_capacity(n); let mut headers = BTreeSet::new(); if n > 0 { - let mut stack: Vec<(usize, usize)> = vec![(0, 0)]; + let mut stack: Vec<(usize, usize)> = Vec::with_capacity(n.min(64).max(1)); + stack.push((0, 0)); state[0] = 1; while let Some(&mut (b, ref mut k)) = stack.last_mut() { - let s = succ(&blocks[b]); + let succs = succ_of(&blocks[b]); + let s = succs.as_slice(); if *k < s.len() { let t = s[*k]; *k += 1; @@ -346,4 +387,79 @@ mod tests { assert_eq!(headers.len(), 1); assert_eq!(headers2.len(), 1); } + + #[test] + fn acyclic_cfg_skips_dominator_pass_and_matches_rpo_and_preds() { + let mut code = Vec::new(); + code.extend(rdna2::encode("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 2)], None).unwrap()); + code.extend(rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + code.extend(rdna2::encode("S_BRANCH", "ENC_SOPP", &[("SIMM16", 1)], None).unwrap()); + code.extend(rdna2::encode("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + code.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code.extend(rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + + let mut cfg = Cfg::build(&code).unwrap(); + assert_eq!(cfg.blocks.len(), 5); + assert_eq!(cfg.blocks[2].term, Term::Jump(3)); + assert!(cfg.headers.is_empty()); + assert_eq!(cfg.rpo, vec![0, 1, 2, 3]); + assert_eq!(cfg.blocks[0].preds, Vec::::new()); + assert_eq!(cfg.blocks[1].preds, vec![0]); + assert_eq!(cfg.blocks[2].preds, vec![0]); + assert_eq!(cfg.blocks[3].preds, vec![1, 2]); + assert_eq!(cfg.blocks[4].preds, Vec::::new()); + assert!(irreducible_edge(&cfg.blocks, &cfg.rpo).is_none()); + + let (rpo, headers, dom_passes) = make_reducible_inner(&mut cfg.blocks).unwrap(); + assert_eq!(dom_passes, 0, "acyclic CFG must skip dominator pass"); + assert!(headers.is_empty()); + assert_eq!(rpo, cfg.rpo); + } + + #[test] + fn succ_of_is_copy_and_covers_all_terminators() { + fn assert_copy() {} + assert_copy::(); + for (term, want) in [ + (Term::End, &[][..]), + (Term::Jump(5), &[5][..]), + (Term::Cond(9, 2, 7), &[2, 7][..]), + ] { + let s = succ_of(&blk(term)); + assert_eq!(s.as_slice(), want); + assert_eq!(s.into_iter().collect::>(), want); + } + } + + #[test] + fn empty_reducible_loop_irreducible_and_geometry_cfgs_match() { + let empty = Cfg::build(&[]).unwrap(); + assert!(empty.insts.is_empty() && empty.blocks.is_empty() && empty.rpo.is_empty() && empty.headers.is_empty()); + + let mut red = vec![blk(Term::Jump(1)), blk(Term::Cond(0, 1, 2)), blk(Term::End)]; + let (rpo, headers, dom_passes) = make_reducible_inner(&mut red).unwrap(); + assert_eq!((dom_passes, rpo, headers), (1, vec![0, 1, 2], BTreeSet::from([1]))); + + let mut irred = vec![blk(Term::Cond(0, 3, 1)), blk(Term::Jump(2)), blk(Term::Jump(3)), blk(Term::Cond(0, 2, 4)), blk(Term::End)]; + let (rpo, headers, dom_passes) = make_reducible_inner(&mut irred).unwrap(); + assert!(dom_passes >= 2 && headers.len() == 1 && irreducible_edge(&irred, &rpo).is_none()); + + let mut gs = Vec::new(); + gs.extend(rdna2::encode("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)], None).unwrap()); + gs.extend(rdna2::encode("S_NOP", "ENC_SOPP", &[("SIMM16", 0)], None).unwrap()); + gs.extend(rdna2::encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let with_gs = Cfg::build_geometry(&gs, Some(8)).unwrap(); + assert_eq!(with_gs.blocks[0].term, Term::Jump(2)); + assert_eq!((with_gs.blocks[2].pc, with_gs.rpo), (8, vec![0, 2])); + for start in [None, Some(0)] { + let ended = Cfg::build_geometry(&gs, start).unwrap(); + assert_eq!((&ended.blocks[0].term, &ended.rpo), (&Term::End, &vec![0])); + } + assert!(Cfg::build_geometry(&gs, Some(2)).err().unwrap().contains("GS start")); + + let bad_br = rdna2::encode("S_BRANCH", "ENC_SOPP", &[("SIMM16", 8)], None).unwrap(); + assert!(Cfg::build(&bad_br).err().unwrap().contains("not the start of an instruction")); + let bad_cbr = rdna2::encode("S_CBRANCH_SCC0", "ENC_SOPP", &[("SIMM16", (-1i16) as u16 as u64)], None).unwrap(); + assert!(Cfg::build(&bad_cbr).err().unwrap().contains("conditional branch at the end of the code")); + } } diff --git a/crates/xcl/src/gpu/dxil/compact.rs b/crates/xcl/src/gpu/dxil/compact.rs index b84298be5e..c8bfab774b 100644 --- a/crates/xcl/src/gpu/dxil/compact.rs +++ b/crates/xcl/src/gpu/dxil/compact.rs @@ -22,9 +22,7 @@ pub struct Plan { } /// Most 32-bit words of tables a program may need to take the form by itself. -pub const TABLE_WORDS: usize = 8192; -/// `TABLE_WORDS` on a GPU that runs only 32-lane waves. -pub const TABLE_WORDS_WAVE32: usize = 12288; +const MAX_TABLE_WORDS: usize = 12288; impl Plan { /// Bits of a table entry: the class, and the taken successor or the index of the pair of offsets. @@ -48,11 +46,11 @@ pub(super) fn atomic_candidate(cfg: &Cfg) -> bool { }) } -pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool, tables: usize) -> Option { +pub fn automatic_plan(cfg: &Cfg, lw: &Lw, split_compute: bool) -> Option { let large = large(cfg); if !large && !(split_compute && atomic_candidate(cfg)) { return None; } let p = plan(cfg, lw)?; - if p.words() > tables { return None; } + if p.words() > MAX_TABLE_WORDS { return None; } let insts = |n: usize| cfg.blocks[p.order[n]].insts.len(); let all: usize = (0..p.order.len()).map(insts).sum(); let once: usize = p.rep.iter().map(|&n| insts(n)).sum(); diff --git a/crates/xcl/src/gpu/dxil/compact_tests.rs b/crates/xcl/src/gpu/dxil/compact_tests.rs index e0bb2e8935..86d41bfd68 100644 --- a/crates/xcl/src/gpu/dxil/compact_tests.rs +++ b/crates/xcl/src/gpu/dxil/compact_tests.rs @@ -181,7 +181,16 @@ fn a_mask_read_whole_after_one_copy_only_splits_the_class() { assert_ne!(p.class[0], p.class[2]); } -fn two_segments(copies: usize) -> Vec { +#[test] +fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { + if compact_mode().is_some() { + return; + } + match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { + (Ok(_), Ok(true), Ok(_)) => {} + (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), + } + const COPIES: usize = 8192; let i = |n: &str, e: &str, f: &[(&str, u64)]| encode(n, e, f, None).unwrap_or_else(|x| panic!("{n}: {x}")); let mut code = Vec::new(); code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 2)])); @@ -189,48 +198,21 @@ fn two_segments(copies: usize) -> Vec { code.extend(i("V_MOV_B32", "ENC_VOP1", &[("VDST", r), ("SRC0", 256 + r)])); } for marker in [3, 4] { - for k in 0..copies { + for k in 0..COPIES { code.extend(i("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 1)])); code.extend(i("V_ADD_NC_U32", "ENC_VOP2", &[("VDST", 1), ("SRC0", 256), ("VSRC1", 1)])); - let offset = (copies - 1 - k) * 3 + 1; + let offset = (COPIES - 1 - k) * 3 + 1; assert!(offset <= i16::MAX as usize); code.extend(i("S_CBRANCH_SCC1", "ENC_SOPP", &[("SIMM16", offset as u64)])); } code.extend(i("S_MOV_B32", "ENC_SOP1", &[("SDST", marker), ("SSRC0", 129)])); } code.extend(i("S_ENDPGM", "ENC_SOPP", &[])); - code -} - -#[test] -fn a_gpu_with_64_lane_waves_keeps_the_first_table_limit() { - if compact_mode().is_some() { - return; - } - let code = two_segments(8192); - let o = KernelOptions { wave64: true, split: false, mem_windows: 1, sampler_base: 0 }; - let cs = crate::gpu::recomp::CsInterface { threads: [64, 1, 1], user_sgprs: 4, tgid: [false; 3], tg_size: false, tid_components: 1 }; - let size = |wave32_only| super::kernel::translate_compute_on(&code, o, &cs, wave32_only).unwrap().dxil.len(); - let (compact, plain) = (size(true), size(false)); - assert!(compact * 20 < plain, "{compact} B on a GPU with 32-lane waves only, {plain} B on one with 64-lane waves"); -} - -#[test] -fn gpu_compact_inline_table_above_old_cap_checks_late_entries() { - if compact_mode().is_some() { - return; - } - match (runner::adapter(), runner::wave64_programs_supported(), crate::gpu::recomp::dxc::location()) { - (Ok(_), Ok(true), Ok(_)) => {} - (a, _, d) => return runner::skip_test(if a.is_err() { "no GPU" } else if d.is_err() { "no DXC" } else { "no wave64" }), - } - const COPIES: usize = 8192; - let code = two_segments(COPIES); let o = KernelOptions { wave64: true, split: runner::split_wave64(), mem_windows: 1, sampler_base: 0 }; let cfg = super::cfg::Cfg::build(&code).unwrap(); let leaders = cfg.blocks.iter().filter_map(|b| b.insts.first().map(|&i| cfg.insts[i].pc)).collect(); let lw = super::lower::Lw::new(&cfg.insts, &leaders, o, &super::kernel::Entry::Kernel); - let p = super::compact::automatic_plan(&cfg, &lw, false, super::compact::TABLE_WORDS_WAVE32).unwrap(); + let p = super::compact::automatic_plan(&cfg, &lw, false).unwrap(); assert!(p.inline && p.words() > 8192 && p.words() <= 12288); let k = translate_full(&code, o).unwrap(); for initial in [0u32, u32::MAX - 1, 0u32.wrapping_sub(COPIES as u32), 0u32.wrapping_sub((2 * COPIES) as u32), 0u32.wrapping_sub(COPIES as u32 + 1)] { diff --git a/crates/xcl/src/gpu/dxil/container.rs b/crates/xcl/src/gpu/dxil/container.rs index b92b10ede7..903538ce14 100644 --- a/crates/xcl/src/gpu/dxil/container.rs +++ b/crates/xcl/src/gpu/dxil/container.rs @@ -134,24 +134,31 @@ fn fourcc(s: &[u8; 4]) -> u32 { u32::from_le_bytes(*s) } -/// The `DXIL` part: program header, bitcode header, bitcode. -fn program_part(stage: Stage, sm: (u32, u32), dxil_version: (u32, u32), bitcode: &[u8]) -> Vec { - assert!(bitcode.len() % 4 == 0); - let mut p = Vec::with_capacity(24 + bitcode.len()); - let total = 24 + bitcode.len(); - p.extend_from_slice(&(((stage as u32) << 16) | (sm.0 << 4) | sm.1).to_le_bytes()); - p.extend_from_slice(&((total / 4) as u32).to_le_bytes()); - p.extend_from_slice(&fourcc(b"DXIL").to_le_bytes()); - p.extend_from_slice(&((dxil_version.0 << 8) | dxil_version.1).to_le_bytes()); - p.extend_from_slice(&16u32.to_le_bytes()); - p.extend_from_slice(&(bitcode.len() as u32).to_le_bytes()); - p.extend_from_slice(bitcode); - p +/// The 24-byte `DXIL` part header: program header + bitcode header. +fn program_header(stage: Stage, sm: (u32, u32), dxil_version: (u32, u32), bitcode_len: usize) -> [u8; 24] { + assert!(bitcode_len % 4 == 0); + let words = [ + ((stage as u32) << 16) | (sm.0 << 4) | sm.1, + ((24 + bitcode_len) / 4) as u32, + fourcc(b"DXIL"), + (dxil_version.0 << 8) | dxil_version.1, + 16u32, + bitcode_len as u32, + ]; + let mut hdr = [0u8; 24]; + for (i, v) in words.into_iter().enumerate() { + hdr[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes()); + } + hdr } /// PSV0 with `PSVRuntimeInfo3` (validator 1.8+). fn psv_part(psv: &Psv) -> Vec { - let mut p = Vec::new(); + let str_raw = psv.entry.len() + 2; + let str_len = str_raw.next_multiple_of(4); + let res_len = if psv.resources.is_empty() { 0 } else { 4 + 24 * psv.resources.len() }; + let exact_len = 68 + res_len + str_len; + let mut p = Vec::with_capacity(exact_len); let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); w(&mut p, 52); p.extend_from_slice(&[0; 16]); // stage-specific union (none for compute) @@ -174,60 +181,69 @@ fn psv_part(psv: &Psv) -> Vec { } } // String table: "" then the entry name, padded to 4 bytes. - let mut strings = vec![0u8]; - strings.extend_from_slice(psv.entry.as_bytes()); - strings.push(0); - while strings.len() % 4 != 0 { - strings.push(0); - } - w(&mut p, strings.len() as u32); - p.extend_from_slice(&strings); + w(&mut p, str_len as u32); + p.push(0); + p.extend_from_slice(psv.entry.as_bytes()); + p.push(0); + p.extend_from_slice(&[0u8; 3][..str_len - str_raw]); w(&mut p, 0); // semantic index table + debug_assert_eq!(p.len(), exact_len); p } -/// An empty input / output signature. -fn empty_signature() -> Vec { - let mut p = Vec::new(); - p.extend_from_slice(&0u32.to_le_bytes()); - p.extend_from_slice(&8u32.to_le_bytes()); - p -} +/// An empty input / output signature (`0u32`, `8u32` LE). +const EMPTY_SIGNATURE: [u8; 8] = [0, 0, 0, 0, 8, 0, 0, 0]; -/// Builds the signed container for a DXIL program. -pub fn container(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, psv: &Psv) -> Vec { +/// Assembles and signs a DXBC container directly from borrowed prefix parts and `bitcode` +/// (single bitcode copy, exact allocation). +fn assemble_container(prefix_parts: &[([u8; 4], &[u8])], stage: Stage, sm: (u32, u32), bitcode: &[u8]) -> Vec { let dxil_version = (1, sm.1.min(8)); - let parts: Vec<([u8; 4], Vec)> = vec![ - (*b"SFI0", features.to_le_bytes().to_vec()), - (*b"ISG1", empty_signature()), - (*b"OSG1", empty_signature()), - (*b"PSV0", psv_part(psv)), - (*b"DXIL", program_part(stage, sm, dxil_version, bitcode)), - ]; - let header = 32 + 4 * parts.len(); - let total: usize = header + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let dxil_hdr = program_header(stage, sm, dxil_version, bitcode.len()); + let dxil_len = dxil_hdr.len() + bitcode.len(); + let part_count = prefix_parts.len() + 1; + let header = 32 + 4 * part_count; + let total = header + prefix_parts.iter().map(|(_, d)| 8 + d.len()).sum::() + 8 + dxil_len; let mut out = Vec::with_capacity(total); out.extend_from_slice(b"DXBC"); out.extend_from_slice(&[0; 16]); out.extend_from_slice(&1u16.to_le_bytes()); out.extend_from_slice(&0u16.to_le_bytes()); out.extend_from_slice(&(total as u32).to_le_bytes()); - out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + out.extend_from_slice(&(part_count as u32).to_le_bytes()); let mut off = header; - for (_, d) in &parts { + for (_, d) in prefix_parts { out.extend_from_slice(&(off as u32).to_le_bytes()); off += 8 + d.len(); } - for (cc, d) in &parts { + out.extend_from_slice(&(off as u32).to_le_bytes()); + for (cc, d) in prefix_parts { out.extend_from_slice(cc); out.extend_from_slice(&(d.len() as u32).to_le_bytes()); out.extend_from_slice(d); } + out.extend_from_slice(b"DXIL"); + out.extend_from_slice(&(dxil_len as u32).to_le_bytes()); + out.extend_from_slice(&dxil_hdr); + out.extend_from_slice(bitcode); + debug_assert_eq!(out.len(), total); let digest = hash(&out[20..]); out[4..20].copy_from_slice(&digest); out } +/// Builds the signed container for a DXIL program. +pub fn container(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, psv: &Psv) -> Vec { + let sfi0 = features.to_le_bytes(); + let psv_bytes = psv_part(psv); + let prefix = [ + (*b"SFI0", sfi0.as_slice()), + (*b"ISG1", EMPTY_SIGNATURE.as_slice()), + (*b"OSG1", EMPTY_SIGNATURE.as_slice()), + (*b"PSV0", psv_bytes.as_slice()), + ]; + assemble_container(&prefix, stage, sm, bitcode) +} + // ------------------------------------------------- graphics signatures /// One row of an `ISG1`/`OSG1`/`PSG1` signature (`DxilProgramSignatureElement`). @@ -253,11 +269,11 @@ pub struct SigPartElement { /// (DXC writes names in declaration order while sorting elements by register). pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec { let mut strings: Vec = Vec::new(); - let mut offs: Vec<(String, u32)> = Vec::new(); + let mut offs: Vec<(&str, u32)> = Vec::with_capacity(name_order.len() + elems.len()); let base = 8 + 32 * elems.len() as u32; for n in name_order.iter().copied().chain(elems.iter().map(|e| e.name.as_str())) { - if !offs.iter().any(|(s, _)| s == n) { - offs.push((n.to_string(), base + strings.len() as u32)); + if !offs.iter().any(|&(s, _)| s == n) { + offs.push((n, base + strings.len() as u32)); strings.extend_from_slice(n.as_bytes()); strings.push(0); } @@ -265,12 +281,13 @@ pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec while strings.len() % 4 != 0 { strings.push(0); } - let mut p = Vec::new(); + let exact_len = 8 + 32 * elems.len() + strings.len(); + let mut p = Vec::with_capacity(exact_len); let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); w(&mut p, elems.len() as u32); w(&mut p, 8); for e in elems { - let off = offs.iter().find(|(s, _)| *s == e.name).unwrap().1; + let off = offs.iter().find(|&&(s, _)| s == e.name).unwrap().1; for v in [e.stream, off, e.index, e.system_value, e.comp_type, e.register] { w(&mut p, v); } @@ -278,6 +295,7 @@ pub fn signature_part(elems: &[SigPartElement], name_order: &[&str]) -> Vec w(&mut p, e.min_precision); } p.extend_from_slice(&strings); + debug_assert_eq!(p.len(), exact_len); p } @@ -330,24 +348,15 @@ pub struct PsvFull { /// Writes PSV0 for [`PsvFull`]. pub fn psv_part_full(psv: &PsvFull) -> Vec { - let mut p = Vec::new(); - let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); - w(&mut p, 52); - p.extend_from_slice(&psv.stage_info); - w(&mut p, psv.min_wave); - w(&mut p, psv.max_wave); - p.extend_from_slice(&[psv.stage as u8, psv.uses_view_id as u8, psv.info1[0], psv.info1[1]]); - p.extend_from_slice(&[psv.inputs.len() as u8, psv.outputs.len() as u8, psv.prims.len() as u8, psv.input_vectors]); - p.extend_from_slice(&psv.output_vectors); - for n in psv.numthreads { - w(&mut p, n); - } - let all: Vec<&PsvSigElement> = psv.inputs.iter().chain(&psv.outputs).chain(&psv.prims).collect(); + let total_elems = psv.inputs.len() + psv.outputs.len() + psv.prims.len(); + let elems = || psv.inputs.iter().chain(&psv.outputs).chain(&psv.prims); // String table: "" then non-system names in element order (not // deduplicated, as DXC writes it), then the entry name. - let mut strings = vec![0u8]; - let mut name_off = Vec::new(); - for e in &all { + let str_raw = 1 + elems().map(|e| if e.name.is_empty() { 0 } else { e.name.len() + 1 }).sum::() + psv.entry.len() + 1; + let mut strings = Vec::with_capacity(str_raw.next_multiple_of(4)); + strings.push(0); + let mut name_off = Vec::with_capacity(total_elems); + for e in elems() { if e.name.is_empty() { name_off.push(0); } else { @@ -362,22 +371,10 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { while strings.len() % 4 != 0 { strings.push(0); } - w(&mut p, entry_off); - w(&mut p, psv.resources.len() as u32); - if !psv.resources.is_empty() { - w(&mut p, 24); - for r in &psv.resources { - for v in [r.res_type as u32, r.space, r.lower, r.upper, r.kind, r.flags] { - w(&mut p, v); - } - } - } - w(&mut p, strings.len() as u32); - p.extend_from_slice(&strings); // Semantic index table: each element's index list, reusing an existing run. let mut table: Vec = Vec::new(); - let mut idx_off = Vec::new(); - for e in &all { + let mut idx_off = Vec::with_capacity(total_elems); + for e in elems() { let n = e.indices.len(); let found = if n == 0 || table.len() < n { None } else { (0..=table.len() - n).find(|&i| table[i..i + n] == e.indices[..]) }; idx_off.push(match found { @@ -388,13 +385,41 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { } }); } + let res_len = if psv.resources.is_empty() { 0 } else { 4 + 24 * psv.resources.len() }; + let sig_len = if total_elems == 0 { 0 } else { 4 + 16 * total_elems }; + let tbl_len = 4 * psv.tables.iter().map(Vec::len).sum::(); + let p_len = 68 + res_len + strings.len() + 4 * table.len() + sig_len + tbl_len; + let mut p = Vec::with_capacity(p_len); + let w = |p: &mut Vec, v: u32| p.extend_from_slice(&v.to_le_bytes()); + w(&mut p, 52); + p.extend_from_slice(&psv.stage_info); + w(&mut p, psv.min_wave); + w(&mut p, psv.max_wave); + p.extend_from_slice(&[psv.stage as u8, psv.uses_view_id as u8, psv.info1[0], psv.info1[1]]); + p.extend_from_slice(&[psv.inputs.len() as u8, psv.outputs.len() as u8, psv.prims.len() as u8, psv.input_vectors]); + p.extend_from_slice(&psv.output_vectors); + for n in psv.numthreads { + w(&mut p, n); + } + w(&mut p, entry_off); + w(&mut p, psv.resources.len() as u32); + if !psv.resources.is_empty() { + w(&mut p, 24); + for r in &psv.resources { + for v in [r.res_type as u32, r.space, r.lower, r.upper, r.kind, r.flags] { + w(&mut p, v); + } + } + } + w(&mut p, strings.len() as u32); + p.extend_from_slice(&strings); w(&mut p, table.len() as u32); for v in &table { w(&mut p, *v); } - if !all.is_empty() { + if total_elems > 0 { w(&mut p, 16); - for (i, e) in all.iter().enumerate() { + for (i, e) in elems().enumerate() { w(&mut p, name_off[i]); w(&mut p, idx_off[i]); let cs = (e.cols & 0xF) | ((e.start_col & 3) << 4) | ((e.allocated as u8) << 6); @@ -406,6 +431,7 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { w(&mut p, *v); } } + debug_assert_eq!(p.len(), p_len); p } @@ -413,35 +439,17 @@ pub fn psv_part_full(psv: &PsvFull) -> Vec { /// mesh primitive outputs) and a prebuilt PSV0. #[allow(clippy::too_many_arguments)] pub fn container_with_signatures(stage: Stage, sm: (u32, u32), bitcode: &[u8], features: u64, isg: Vec, osg: Vec, psg: Option>, psv: Vec) -> Vec { - let dxil_version = (1, sm.1.min(8)); - let mut parts: Vec<([u8; 4], Vec)> = vec![(*b"SFI0", features.to_le_bytes().to_vec()), (*b"ISG1", isg), (*b"OSG1", osg)]; - if let Some(p) = psg { - parts.push((*b"PSG1", p)); - } - parts.push((*b"PSV0", psv)); - parts.push((*b"DXIL", program_part(stage, sm, dxil_version, bitcode))); - let header = 32 + 4 * parts.len(); - let total: usize = header + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); - let mut out = Vec::with_capacity(total); - out.extend_from_slice(b"DXBC"); - out.extend_from_slice(&[0; 16]); - out.extend_from_slice(&1u16.to_le_bytes()); - out.extend_from_slice(&0u16.to_le_bytes()); - out.extend_from_slice(&(total as u32).to_le_bytes()); - out.extend_from_slice(&(parts.len() as u32).to_le_bytes()); - let mut off = header; - for (_, d) in &parts { - out.extend_from_slice(&(off as u32).to_le_bytes()); - off += 8 + d.len(); + let sfi0 = features.to_le_bytes(); + match psg.as_deref() { + Some(p) => assemble_container( + &[(*b"SFI0", sfi0.as_slice()), (*b"ISG1", isg.as_slice()), (*b"OSG1", osg.as_slice()), (*b"PSG1", p), (*b"PSV0", psv.as_slice())], + stage, sm, bitcode, + ), + None => assemble_container( + &[(*b"SFI0", sfi0.as_slice()), (*b"ISG1", isg.as_slice()), (*b"OSG1", osg.as_slice()), (*b"PSV0", psv.as_slice())], + stage, sm, bitcode, + ), } - for (cc, d) in &parts { - out.extend_from_slice(cc); - out.extend_from_slice(&(d.len() as u32).to_le_bytes()); - out.extend_from_slice(d); - } - let digest = hash(&out[20..]); - out[4..20].copy_from_slice(&digest); - out } #[cfg(test)] @@ -484,6 +492,124 @@ mod tests { assert_eq!(ours, theirs); } + #[test] + fn parts_and_containers_are_exact_sized_and_match_reference_layout() { + let ref_dxbc = |parts: &[([u8; 4], &[u8])]| -> Vec { + let hdr = 32 + 4 * parts.len(); + let tot = hdr + parts.iter().map(|(_, d)| 8 + d.len()).sum::(); + let mut o = Vec::with_capacity(tot); + o.extend_from_slice(b"DXBC"); + o.extend_from_slice(&[0; 16]); + o.extend_from_slice(&1u16.to_le_bytes()); + o.extend_from_slice(&0u16.to_le_bytes()); + o.extend_from_slice(&(tot as u32).to_le_bytes()); + o.extend_from_slice(&(parts.len() as u32).to_le_bytes()); + let mut off = hdr; + for (_, d) in parts { o.extend_from_slice(&(off as u32).to_le_bytes()); off += 8 + d.len(); } + for (cc, d) in parts { o.extend_from_slice(cc); o.extend_from_slice(&(d.len() as u32).to_le_bytes()); o.extend_from_slice(d); } + let d = hash(&o[20..]); + o[4..20].copy_from_slice(&d); + o + }; + let ref_dxil = |stage: Stage, sm: (u32, u32), bc: &[u8]| -> Vec { + let mut p = Vec::new(); + for v in [((stage as u32) << 16) | (sm.0 << 4) | sm.1, ((24 + bc.len()) / 4) as u32, fourcc(b"DXIL"), (1 << 8) | sm.1.min(8), 16, bc.len() as u32] { + p.extend_from_slice(&v.to_le_bytes()); + } + p.extend_from_slice(bc); + p + }; + let res = PsvResource { res_type: PsvResType::UavRaw, space: 1, lower: 2, upper: 4, kind: 11, flags: 3 }; + let bc = [0xDEu8, 0xAD, 0xBE, 0xEF, 1, 2, 3, 4]; + + // 1. psv_part + container across 0 & N resources and all entry padding remainders. + for n_res in [0usize, 3] { + for entry in ["", "a", "ab", "abc", "main"] { + let psv = Psv { stage: Stage::Compute, min_wave: 32, max_wave: 64, numthreads: [8, 4, 1], resources: vec![res.clone(); n_res], entry: entry.into() }; + let p = psv_part(&psv); + assert_eq!(p.capacity(), p.len(), "psv_part over-allocated for n_res={n_res} entry={entry:?}"); + let s0 = 0x1234_5678_9ABC_DEF0u64.to_le_bytes(); + let dxil = ref_dxil(Stage::Compute, (6, 9), &bc); + let got = container(Stage::Compute, (6, 9), &bc, 0x1234_5678_9ABC_DEF0, &psv); + let want = ref_dxbc(&[(*b"SFI0", &s0), (*b"ISG1", &EMPTY_SIGNATURE), (*b"OSG1", &EMPTY_SIGNATURE), (*b"PSV0", &p), (*b"DXIL", &dxil)]); + assert_eq!(got.capacity(), got.len()); + assert_eq!(got, want); + assert_eq!(part(&got, b"PSV0"), p.as_slice()); + } + } + + // 2. signature_part with empty & repeated names + name_order reordering. + let empty_sig = signature_part(&[], &[]); + assert_eq!(empty_sig.as_slice(), &EMPTY_SIGNATURE); + assert_eq!(empty_sig.capacity(), empty_sig.len()); + let mk_sig = |name: &str, idx: u32, reg: u32| SigPartElement { + stream: 0, name: name.into(), index: idx, system_value: 0, comp_type: 3, register: reg, mask: 0xF, rw_mask: 0x3, min_precision: 0, + }; + let elems = [mk_sig("TEXCOORD", 0, 0), mk_sig("SV_Position", 0, 1), mk_sig("TEXCOORD", 1, 2)]; + let isg = signature_part(&elems, &["SV_Position", "TEXCOORD"]); + assert_eq!(isg.capacity(), isg.len()); + let off0 = u32::from_le_bytes(isg[12..16].try_into().unwrap()) as usize; + let off1 = u32::from_le_bytes(isg[44..48].try_into().unwrap()) as usize; + let off2 = u32::from_le_bytes(isg[76..80].try_into().unwrap()) as usize; + assert_eq!(off0, off2, "repeated semantic name must share one string offset"); + assert!(off1 < off0, "name_order must place SV_Position before TEXCOORD"); + + // 3. psv_part_full (inputs/outputs/prims, empty & non-empty names, reused index runs, view_id, tables) + // + container_with_signatures with PSG1 = Some and None. + let mk_psv_el = |name: &str, indices: &[u32], row: u8| PsvSigElement { + name: name.into(), indices: indices.to_vec(), rows: 1, start_row: row, cols: 4, start_col: 0, + allocated: true, kind: 0, comp_type: 3, interp: 2, dynamic_mask: 0, stream: 0, + }; + let full = PsvFull { + stage: Stage::Mesh, stage_info: [7; 16], min_wave: 32, max_wave: 32, uses_view_id: true, + info1: [1, 2], numthreads: [32, 1, 1], resources: vec![res], entry: "mesh_main".into(), + inputs: vec![mk_psv_el("", &[0], 0), mk_psv_el("TEXCOORD", &[0, 1], 1)], + outputs: vec![mk_psv_el("COLOR", &[1], 0)], + prims: vec![mk_psv_el("PRIM", &[0, 1], 0)], + input_vectors: 2, output_vectors: [1, 0, 0, 0], tables: vec![vec![0x11, 0x22], vec![0x33]], + }; + let pfull = psv_part_full(&full); + // Captured from the pre-refactor serializer. Keep this oracle independent of the + // container/reference helpers above so a same-length PSV field reordering is visible. + let golden = concat!( + "340000000707070707070707070707070707070720000000200000000d010102", + "0201010201000000200000000100000001000000150000000100000018000000", + "070000000100000002000000040000000b000000030000002000000000544558", + "434f4f524400434f4c4f52005052494d006d6573685f6d61696e000003000000", + "0000000000000000010000001000000000000000000000000100440003020000", + "010000000100000001014400030200000a000000020000000100440003020000", + "10000000010000000100440003020000110000002200000033000000", + ); + let golden: Vec = golden.as_bytes().chunks_exact(2).map(|b| { + u8::from_str_radix(std::str::from_utf8(b).unwrap(), 16).unwrap() + }).collect(); + assert_eq!(pfull, golden, "full PSV bytes changed from the pre-refactor serializer"); + assert_eq!(pfull.capacity(), pfull.len()); + let pfull_empty = psv_part_full(&PsvFull { + stage: Stage::Vertex, stage_info: [0; 16], min_wave: 0, max_wave: 0, uses_view_id: false, + info1: [0; 2], numthreads: [0; 3], resources: vec![], entry: "vs".into(), + inputs: vec![], outputs: vec![], prims: vec![], input_vectors: 0, output_vectors: [0; 4], tables: vec![], + }); + assert_eq!(pfull_empty.capacity(), pfull_empty.len()); + + let osg = signature_part(&[mk_sig("COLOR", 0, 0)], &[]); + let psg = signature_part(&[mk_sig("PRIM", 0, 0)], &[]); + let sfi = 0x55u64.to_le_bytes(); + let dxil = ref_dxil(Stage::Mesh, (6, 6), &bc); + let with_psg = container_with_signatures(Stage::Mesh, (6, 6), &bc, 0x55, isg.clone(), osg.clone(), Some(psg.clone()), pfull.clone()); + assert_eq!(with_psg.capacity(), with_psg.len()); + assert_eq!(with_psg, ref_dxbc(&[(*b"SFI0", &sfi), (*b"ISG1", &isg), (*b"OSG1", &osg), (*b"PSG1", &psg), (*b"PSV0", &pfull), (*b"DXIL", &dxil)])); + let without_psg = container_with_signatures(Stage::Mesh, (6, 6), &bc, 0x55, isg.clone(), osg.clone(), None, pfull.clone()); + assert_eq!(without_psg.capacity(), without_psg.len()); + assert_eq!(without_psg, ref_dxbc(&[(*b"SFI0", &sfi), (*b"ISG1", &isg), (*b"OSG1", &osg), (*b"PSV0", &pfull), (*b"DXIL", &dxil)])); + } + + #[test] + #[should_panic] + fn program_header_rejects_unaligned_bitcode() { + let _ = program_header(Stage::Compute, (6, 6), (1, 6), 6); + } + pub(crate) fn part<'a>(c: &'a [u8], cc: &[u8; 4]) -> &'a [u8] { let n = u32::from_le_bytes(c[28..32].try_into().unwrap()) as usize; for i in 0..n { diff --git a/crates/xcl/src/gpu/dxil/core_tests.rs b/crates/xcl/src/gpu/dxil/core_tests.rs index 7492f54b9c..ae8b956d49 100644 --- a/crates/xcl/src/gpu/dxil/core_tests.rs +++ b/crates/xcl/src/gpu/dxil/core_tests.rs @@ -659,6 +659,17 @@ fn raw_loads_in_root_windows_are_branchless() { let heap_dxil = translate(&loads, KernelOptions { wave64: false, split: false, mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS, sampler_base: 0 }) .expect("heap windows translate"); super::validate::validate(&heap_dxil).expect("heap windows validate"); + let flat_dxil = translate(&loads, KernelOptions { + wave64: false, + split: false, + mem_windows: 4 | crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT, + sampler_base: 0, + }).expect("flat heap windows translate"); + super::validate::validate(&flat_dxil).expect("flat heap windows validate"); + if let (Ok(heap), Ok(flat)) = (super::validate::disassemble(&heap_dxil), super::validate::disassemble(&flat_dxil)) { + let branches = |s: &str| s.lines().filter(|line| line.trim_start().starts_with("br i1 ")).count(); + assert!(branches(&flat) < branches(&heap), "flat heap reads must remove guarded-read branches: guarded {}, flat {}", branches(&heap), branches(&flat)); + } let writes = prog(&[ ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 0), ("DATA", 2), ("SADDR", 0x7D), ("OFFSET", 0)], None), diff --git a/crates/xcl/src/gpu/dxil/kernel.rs b/crates/xcl/src/gpu/dxil/kernel.rs index 82cf4c0905..8212d12948 100644 --- a/crates/xcl/src/gpu/dxil/kernel.rs +++ b/crates/xcl/src/gpu/dxil/kernel.rs @@ -91,39 +91,60 @@ pub fn compact_nest_tag() -> Option { /// `translate_full` in the compact form (`compact = true`) or the plain one. #[cfg(test)] pub fn translate_full_as(code: &[u8], o: KernelOptions, compact: bool) -> Result { - translate_entry(code, o, Entry::Kernel, Some(compact), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(compact), None) } /// `translate_full` in the compact form with an explicit dispatch nesting policy. #[cfg(test)] pub fn translate_full_nested(code: &[u8], o: KernelOptions, nest: super::compact::Nest) -> Result { - translate_entry(code, o, Entry::Kernel, Some(true), Some(nest), super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, Some(true), Some(nest)) } pub fn translate_full(code: &[u8], o: KernelOptions) -> Result { - translate_entry(code, o, Entry::Kernel, compact_mode(), None, super::compact::TABLE_WORDS_WAVE32) + translate_entry(code, o, Entry::Kernel, compact_mode(), None) } /// A mesh-mode (NGG) program: the first pass that writes one record per group into /// `res` (the recompiler's `Mode::Mesh`; the pass-through mesh shader draws them). pub fn translate_mesh(code: &[u8], o: KernelOptions, ms: &MsInterface) -> Result { - translate_entry(code, o, Entry::Mesh(ms.clone()), None, None, 0) + translate_entry(code, o, Entry::Mesh(ms.clone()), None, None) } /// A vertex shader (the recompiler's `Mode::Vertex`; wave-size independent). pub fn translate_vertex(code: &[u8], o: KernelOptions, vs: &VsInterface) -> Result { - translate_entry(code, o, Entry::Vertex(vs.clone()), None, None, 0) + translate_entry(code, o, Entry::Vertex(vs.clone()), None, None) } /// A pixel shader (the recompiler's `Mode::Pixel`; wave-size independent). pub fn translate_pixel(code: &[u8], o: KernelOptions, ps: &PsInterface) -> Result { - translate_entry(code, o, Entry::Pixel(ps.clone()), None, None, 0) + translate_entry(code, o, Entry::Pixel(ps.clone()), None, None) } /// A geometry-mode (ES+GS) program: the compute pass that writes one mesh record per /// group of 21 triangles into `res` (the recompiler's `Mode::Geometry`). Always wave64. pub fn translate_geometry(code: &[u8], o: KernelOptions, g: &GsInterface) -> Result { - translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None, 0) + translate_entry(code, KernelOptions { wave64: true, ..o }, Entry::Geometry(g.clone()), None, None) +} + +/// Whether `entry` uses the measured, one-path heap-window read form. Graphics, mesh and +/// geometry stages retain the guarded form until they have stage-specific measurements. +fn reads_heap_flat(entry: &Entry, heap: bool, mem_windows: u32) -> bool { + heap && matches!(entry, Entry::Kernel | Entry::Compute(_)) && mem_windows & crate::gpu::recomp::HEAP_FLAT != 0 +} + +#[cfg(test)] +#[test] +fn only_compute_programs_read_heap_windows_flat() { + use crate::gpu::recomp::{GsInterface, MsInterface, HEAP_FLAT, HEAP_WINDOWS}; + let flat = 4 | HEAP_WINDOWS | HEAP_FLAT; + assert!(reads_heap_flat(&Entry::Kernel, true, flat)); + assert!(reads_heap_flat(&Entry::Compute(CsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Mesh(MsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Geometry(GsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Vertex(VsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Pixel(PsInterface::default()), true, flat)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), true, 4 | HEAP_WINDOWS)); + assert!(!reads_heap_flat(&Entry::Compute(CsInterface::default()), false, flat)); } /// The entry ABI. @@ -139,13 +160,7 @@ pub enum Entry { /// A compute-mode program (the CS ABI of `cs`). pub fn translate_compute(code: &[u8], o: KernelOptions, cs: &CsInterface) -> Result { - translate_compute_on(code, o, cs, true) -} - -/// `translate_compute` for a GPU: one that runs only 32-lane waves takes larger compact tables. -pub fn translate_compute_on(code: &[u8], o: KernelOptions, cs: &CsInterface, wave32_only: bool) -> Result { - let tables = if wave32_only { super::compact::TABLE_WORDS_WAVE32 } else { super::compact::TABLE_WORDS }; - translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None, tables) + translate_entry(code, o, Entry::Compute(cs.clone()), compact_mode(), None) } fn translate_entry( @@ -154,15 +169,20 @@ fn translate_entry( entry: Entry, compact: Option, nest: Option, - tables: usize, ) -> Result { // SSA construction recurses along the CFG (one level per guarded memory access between // a register's definition and its use): a thread with a large stack for big programs let code = code.to_vec(); + #[cfg(test)] + let no_select_fold = super::module::NO_SELECT_FOLD.with(|c| c.get()); std::thread::Builder::new() .name("xcl-dxil-translate".into()) .stack_size(256 << 20) - .spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables)) + .spawn(move || { + #[cfg(test)] + super::module::NO_SELECT_FOLD.with(|c| c.set(no_select_fold)); + translate_on_this_thread(&code, o, entry, compact, nest) + }) .map_err(|e| format!("translator thread: {e}"))? .join() .map_err(|e| { @@ -178,7 +198,7 @@ fn translate_entry( fn mem_windows(s: &mut Shader, mem_windows: u32, coherent: bool) -> (Vec, Option) { let heap = mem_windows & crate::gpu::recomp::HEAP_WINDOWS != 0; let max = if heap { crate::gpu::uma::MAX_HEAP_WINDOWS as u32 } else { crate::gpu::uma::MAX_WINDOWS as u32 }; - let n = (mem_windows & !crate::gpu::recomp::HEAP_WINDOWS).clamp(1, max); + let n = (mem_windows & !(crate::gpu::recomp::HEAP_WINDOWS | crate::gpu::recomp::HEAP_FLAT)).clamp(1, max); if heap && n > 1 { let z = s.m.i32c(0); return (vec![RawUav { handle: z, binding: None }; n as usize], Some(coherent)); @@ -192,7 +212,6 @@ fn translate_on_this_thread( entry: Entry, compact: Option, nest: Option, - tables: usize, ) -> Result { let geo = match &entry { Entry::Geometry(g) => Some(g.clone()), @@ -282,7 +301,7 @@ fn translate_on_this_thread( _ if !compute && !kernel => None, Some(false) => None, Some(true) => super::compact::plan(&cfg, &lw), - None => super::compact::automatic_plan(&cfg, &lw, compute && split, tables), + None => super::compact::automatic_plan(&cfg, &lw, compute && split), }; if let Some(p) = &plan { crate::xlog_info!("[SHADER] direct DXIL compact form: {} blocks of {} kinds", p.order.len(), p.rep.len()); @@ -517,6 +536,7 @@ impl Lw { half: z, mems, heap_mem, + heap_flat: reads_heap_flat(entry, heap_mem.is_some(), o.mem_windows), res, fmt_table: None, fmt_desc_cache: HashMap::new(), @@ -537,6 +557,7 @@ impl Lw { xs: None, xw: None, xc: None, + barrier_waves: None, waves: 1, cw: z, xn: z, @@ -595,6 +616,10 @@ impl Lw { if let (Some(t), true) = (group_threads, split) { lw.waves = t.div_ceil(64).max(1); } + if let (Some(t), Entry::Compute(_) | Entry::Mesh(_)) = (group_threads, entry) { + let hw_lanes = if split || !o.wave64 { 32 } else { 64 }; + lw.barrier_waves = Some(t.div_ceil(hw_lanes).max(1)); + } if split && std::env::var_os("XCL_X64_ALL_MASKS").is_none() { lw.whole_live = crate::gpu::recomp::x64_masks::by_pc(insts, kernel); } @@ -741,7 +766,44 @@ pub fn compute_init(lw: &mut Lw, cs: &CsInterface, tid: Value, gtid: [Value; 3]) } let zero = lw.c(0); sgpr.insert(VAR_SCC, zero); + let io = lw.init.io.expect("the I/O buffer"); + let mut dispatch_limited = lw.s.m.i1c(false); + let mut limits = Vec::new(); + for (k, _) in cs.threads.iter().enumerate().filter(|(_, &threads)| threads > 1) { + let off = lw.c((crate::gpu::recomp::IO_THREAD_LIMIT[k] * 4) as u32); + let limit = lw.s.raw_load(io, off, 1)[0]; + let zero = lw.c(0); + let limited = lw.cmp(Pred::Ne, limit, zero); + dispatch_limited = lw.lor(dispatch_limited, limited); + limits.push((k, limit)); + } let (lo, hi) = entry_exec(lw, total, tid); + let (exec_lo, exec_hi) = (lw.tmp_var(), lw.tmp_var()); + lw.wr(exec_lo, lo); + lw.wr(exec_hi, hi); + let _ = lw.guarded(dispatch_limited, &mut |lw| { + let mut dispatch_live = lw.s.m.i1c(true); + for &(k, limit) in &limits { + let zero = lw.c(0); + let unlimited = lw.cmp(Pred::Eq, limit, zero); + let group = lw.s.group_id(k as u32); + let width = lw.c(cs.threads[k]); + let base = lw.mul(group, width); + let id = lw.add(base, gtid[k]); + let inside = lw.cmp(Pred::ULt, id, limit); + let axis_live = lw.lor(unlimited, inside); + dispatch_live = lw.land(dispatch_live, axis_live); + } + let (dispatch_lo, dispatch_hi) = lw.ballot(dispatch_live); + let old_lo = lw.rd(exec_lo); + let old_hi = lw.rd(exec_hi); + let lo = lw.and(old_lo, dispatch_lo); + let hi = lw.and(old_hi, dispatch_hi); + lw.wr(exec_lo, lo); + lw.wr(exec_hi, hi); + Ok(()) + }); + let (lo, hi) = (lw.rd(exec_lo), lw.rd(exec_hi)); sgpr.insert(126, lo); sgpr.insert(127, hi); let mut vgpr = HashMap::new(); diff --git a/crates/xcl/src/gpu/dxil/lower.rs b/crates/xcl/src/gpu/dxil/lower.rs index 5034d31903..f38769dfd0 100644 --- a/crates/xcl/src/gpu/dxil/lower.rs +++ b/crates/xcl/src/gpu/dxil/lower.rs @@ -187,6 +187,8 @@ pub struct Lw { /// the windows come from the descriptor heap (`lower_window`; `mems` only counts them): /// Some(globallycoherent) pub heap_mem: Option, + /// Heap windows read without a branch (`recomp::HEAP_FLAT`; compute programs only). + pub heap_flat: bool, pub res: Option, /// the buffer format table (`FMT_INFO`), created on first use pub fmt_table: Option, @@ -226,6 +228,9 @@ pub struct Lw { pub xw: Option<(super::ops::GroupShared, u32)>, /// arrival counters of the spin exchange (two per console wave) pub xc: Option<(super::ops::GroupShared, u32)>, + /// hardware waves of a compute or mesh thread group (None: another kind of entry), as the + /// HLSL emitter's `compute_or_mesh_hw_waves` + pub barrier_waves: Option, /// console waves per group, this thread's console wave and its partner half's lanes pub waves: u32, pub cw: Value, @@ -1016,6 +1021,18 @@ impl Lw { fn sopp(&mut self, d: &Decoded, name: &str) -> LResult<()> { match name { "s_barrier" => { + // A compute or mesh group of several hardware waves: this barrier waits for + // every one of them at a barrier, and a console wave that has left – s_endpgm + // behind a branch around the barrier, the loop budget – or that ran one barrier + // fewer never arrives. On the console the waves left go on; on NVIDIA they wait + // for ever and the GPU hangs (`recomp::emit::PRELUDE_SAFE_BARRIER`). A retail + // title's mesh programs all have it: the first wave of a group whose vertex or + // primitive count is 0 runs a barrier the other waves branch around, then the + // one they all run. The HLSL path counts the waves still there + // (`xcl_s_barrier`): such a program is left to it. + if self.barrier_waves.is_some_and(|w| w > 1) && crate::gpu::recomp::emit::safe_barrier_wanted() { + return err(d, "s_barrier in a group of several hardware waves"); + } self.s.barrier(super::ops::barrier::GROUP_SYNC); Ok(()) } @@ -1703,20 +1720,20 @@ impl Lw { } "s_bfm_b64" => { nz = false; - let wdt = self.andc(al, 63); - let off = self.andc(bl, 63); - let all = self.c64(u64::MAX); - let k64 = self.c(64); - let sh = self.sub(k64, wdt); - let sh = self.andc(sh, 63); - let sh = self.zext64(sh); - let m = self.bin(BinOp::LShr, all, sh); - let wz = self.cmpc(Pred::Eq, wdt, 0); - let z64 = self.c64(0); - let m = self.sel(wz, z64, m); - let off = self.zext64(off); - let r = self.bin(BinOp::Shl, m, off); - self.unpack64(r) + if let (Some(av), Some(bv)) = (self.s.m.const_u64(al), self.s.m.const_u64(bl)) { + let r = ((1u64 << (av & 63)).wrapping_sub(1)) << (bv & 63); + (self.c(r as u32), self.c((r >> 32) as u32)) + } else { + let wdt = self.andc(al, 63); + let off = self.andc(bl, 63); + let one = self.c64(1); + let w64 = self.zext64(wdt); + let bit = self.bin(BinOp::Shl, one, w64); + let m = self.sub(bit, one); + let o64 = self.zext64(off); + let r = self.bin(BinOp::Shl, m, o64); + self.unpack64(r) + } } "s_bfe_u64" | "s_bfe_i64" => { let v = self.pack64(al, ah); @@ -1804,22 +1821,22 @@ impl Lw { self.trunc32(h) } pub fn bfm(&mut self, a: Value, b: Value) -> Value { - let w = self.andc(a, 31); - let wz = self.cmpc(Pred::Eq, w, 0); - let k = self.c(32); - let s = self.sub(k, w); - let s = self.andc(s, 31); - let all = self.c(u32::MAX); - let m = self.bin(BinOp::LShr, all, s); - let m = self.selc(wz, 0, m); - self.shl(m, b) + let m = if let Some(av) = self.s.m.const_u64(a) { + self.c((1u32 << (av & 31)).wrapping_sub(1)) + } else { + let w = self.andc(a, 31); + let one = self.c(1); + let bit = self.bin(BinOp::Shl, one, w); + self.sub(bit, one) + }; + if let (Some(mv), Some(bv)) = (self.s.m.const_u64(m), self.s.m.const_u64(b)) { + self.c((mv as u32) << (bv & 31)) + } else { + self.shl(m, b) + } } pub fn ffbh_i(&mut self, v: Value) -> Value { - let z = self.c(0); - let neg = self.cmp(Pred::SLt, v, z); - let n = self.not(v); - let x = self.sel(neg, n, v); - self.lzcnt(x) + self.s.bit_count(BitCount::FirstbitSHi, v) } pub fn sbfe_u(&mut self, v: Value, c: Value) -> Value { let o = self.andc(c, 31); @@ -2194,3 +2211,136 @@ mod saveexec_tests { assert_eq!(r.scc, 1, "SCC = (final EXEC_LO != 0)"); } } + +#[cfg(test)] +mod bfm_ffbh_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + fn prog(insns: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut code = Vec::new(); + for &(name, enc, fields) in insns { + code.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code + } + + #[test] + fn bfm_and_ffbh_i_ir_and_gpu_parity() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + + // 1. Constant S_BFM_B64 folds with zero i64 ops and zero Int64Ops flag. + // Inline integers: 128 + k (k in 0..=64) => 160 = 32, 144 = 16, 128 = 0. + let const_bfm64 = prog(&[ + ("S_BFM_B64", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 160), ("SSRC1", 144)]), + ("S_BFM_B64", "ENC_SOP2", &[("SDST", 2), ("SSRC0", 128), ("SSRC1", 144)]), + ]); + let dxil_const64 = kernel::translate(&const_bfm64, ko).expect("translate const s_bfm_b64"); + validate::validate(&dxil_const64).expect("validate const s_bfm_b64"); + let dis_const64 = validate::disassemble(&dxil_const64).expect("disasm const s_bfm_b64"); + assert!(!dis_const64.contains("64-Bit integer"), "const s_bfm_b64 must not require Int64Ops:\n{dis_const64}"); + + // 2. V_FFBH_I32 / S_FLBIT_I32 lower directly to dx.op.unaryBits.i32(34, ...) (FirstbitSHi). + let ffbh_code = prog(&[ + ("V_FFBH_I32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 256)]), + ("S_FLBIT_I32", "ENC_SOP1", &[("SDST", 1), ("SSRC0", 0)]), + ]); + let dxil_ffbh = kernel::translate(&ffbh_code, ko).expect("translate ffbh_i"); + validate::validate(&dxil_ffbh).expect("validate ffbh_i"); + let dis_ffbh = validate::disassemble(&dxil_ffbh).expect("disasm ffbh_i"); + assert!(dis_ffbh.contains("call i32 @dx.op.unaryBits.i32(i32 34,"), "ffbh_i must emit FirstbitSHi:\n{dis_ffbh}"); + assert!(!dis_ffbh.contains("icmp slt"), "ffbh_i must not emit manual sign-bit branch/select:\n{dis_ffbh}"); + + // 3. Dynamic V_BFM_B32 / S_BFM_B32 / S_BFM_B64 lower without icmp/select. + let bfm_code = prog(&[ + ("V_BFM_B32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 257)]), + ("S_BFM_B32", "ENC_SOP2", &[("SDST", 4), ("SSRC0", 2), ("SSRC1", 3)]), + ("S_BFM_B64", "ENC_SOP2", &[("SDST", 6), ("SSRC0", 2), ("SSRC1", 3)]), + ]); + let dxil_bfm = kernel::translate(&bfm_code, ko).expect("translate dynamic bfm"); + validate::validate(&dxil_bfm).expect("validate dynamic bfm"); + let dis_bfm = validate::disassemble(&dxil_bfm).expect("disasm dynamic bfm"); + assert!(!dis_bfm.contains("select i32"), "bfm must not emit select:\n{dis_bfm}"); + assert!(!dis_bfm.contains("select i64"), "s_bfm_b64 must not emit select:\n{dis_bfm}"); + + // 4. GPU parity across edge cases. + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + // Constant s_bfm_b64 GPU check. + let r0 = runner::run(&dxil_const64, &runner::KernelState::default(), &[]).expect("run const s_bfm_b64"); + let want_const64 = ((1u64 << 32) - 1) << 16; + assert_eq!(r0.sgpr[0], want_const64 as u32); + assert_eq!(r0.sgpr[1], (want_const64 >> 32) as u32); + assert_eq!((r0.sgpr[2], r0.sgpr[3]), (0, 0)); + + // V_FFBH_I32 / S_FLBIT_I32 GPU check. + let ffbh_vals: [u32; 12] = [ + 0, + u32::MAX, + 1, + (-2i32) as u32, + 0x7FFF_FFFF, + 0x8000_0000, + 0x0000_0080, + 0xFFFF_FF7F, + 0x0001_0000, + 0xFFFE_FFFF, + 0x4000_0000, + 0xBFFF_FFFF, + ]; + let mut st_f = runner::KernelState::default(); + st_f.sgpr[0] = 0xFFFF_FF7F; + for (l, &v) in ffbh_vals.iter().enumerate() { + st_f.vgpr[l][0] = v; + } + let rf = runner::run(&dxil_ffbh, &st_f, &[]).expect("run ffbh_i"); + let ref_ffbh_i = |v: u32| -> u32 { + let x = if (v as i32) < 0 { !v } else { v }; + if x == 0 { u32::MAX } else { x.leading_zeros() } + }; + for (l, &v) in ffbh_vals.iter().enumerate() { + assert_eq!(rf.vgpr[l][1], ref_ffbh_i(v), "v_ffbh_i32({v:#010x})"); + } + assert_eq!(rf.sgpr[1], ref_ffbh_i(st_f.sgpr[0]), "s_flbit_i32"); + + // Dynamic V_BFM_B32 / S_BFM_B32 / S_BFM_B64 GPU check. + let pairs: [(u32, u32); 12] = [ + (0, 0), + (0, 17), + (1, 0), + (1, 31), + (16, 8), + (31, 0), + (31, 1), + (32, 0), + (35, 33), + (63, 0), + (63, 1), + (64, 15), + ]; + let mut st_b = runner::KernelState::default(); + for (l, &(w, o)) in pairs.iter().enumerate() { + st_b.vgpr[l][0] = w; + st_b.vgpr[l][1] = o; + } + for &(sw, so) in &[(0u32, 16u32), (31, 1), (32, 32), (63, 1), (64, 5)] { + st_b.sgpr[2] = sw; + st_b.sgpr[3] = so; + let rb = runner::run(&dxil_bfm, &st_b, &[]).expect("run bfm"); + for (l, &(w, o)) in pairs.iter().enumerate() { + let want32 = ((1u32 << (w & 31)).wrapping_sub(1)) << (o & 31); + assert_eq!(rb.vgpr[l][2], want32, "v_bfm_b32({w}, {o})"); + } + let want_s32 = ((1u32 << (sw & 31)).wrapping_sub(1)) << (so & 31); + assert_eq!(rb.sgpr[4], want_s32, "s_bfm_b32({sw}, {so})"); + let want_s64 = ((1u64 << (sw & 63)).wrapping_sub(1)) << (so & 63); + assert_eq!(rb.sgpr[6], want_s64 as u32, "s_bfm_b64 lo({sw}, {so})"); + assert_eq!(rb.sgpr[7], (want_s64 >> 32) as u32, "s_bfm_b64 hi({sw}, {so})"); + } + } +} diff --git a/crates/xcl/src/gpu/dxil/lower_mem.rs b/crates/xcl/src/gpu/dxil/lower_mem.rs index cc7cd0116a..c0ee9b6398 100644 --- a/crates/xcl/src/gpu/dxil/lower_mem.rs +++ b/crates/xcl/src/gpu/dxil/lower_mem.rs @@ -407,6 +407,24 @@ impl Lw { n: usize, f: &mut dyn FnMut(&mut Lw, RawUav) -> Vec, ) -> Vec { + if let (Some(coherent), true) = (self.heap_mem, self.heap_flat) { + let z = self.c(0); + if guard.is_some_and(|g| self.s.m.const_u64(g) == Some(0)) { + return vec![z; n]; + } + let w = self.rd(super::lower::VAR_WIN); + let inside = self.cmpc(Pred::ULt, w, self.mems.len() as u32); + let ok = match guard { + Some(g) if self.s.m.const_u64(g) != Some(1) => self.and(g, inside), + _ => inside, + }; + let w = self.sel(ok, w, z); + let i = self.addc(w, crate::gpu::recomp::MEM_HEAP_BASE); + let m = self.s.heap_raw_buffer_uav(i, coherent); + let vals = f(self, m); + debug_assert_eq!(vals.len(), n); + return vals.into_iter().map(|v| self.sel(ok, v, z)).collect(); + } let i32 = self.s.m.i32(); let tys = vec![i32; n]; self.with_mem_many_tys(guard, &tys, f) diff --git a/crates/xcl/src/gpu/dxil/lower_valu.rs b/crates/xcl/src/gpu/dxil/lower_valu.rs index 08e15a5580..7ac2b436f6 100644 --- a/crates/xcl/src/gpu/dxil/lower_valu.rs +++ b/crates/xcl/src/gpu/dxil/lower_valu.rs @@ -1040,16 +1040,19 @@ impl Lw { let cb = self.lane_of(l, h); let cin = self.u(cb); let (x, y) = if name == "v_subrev_co_ci_u32" { (b, a) } else { (a, b) }; - let (x6, y6, c6) = (self.zext64(x), self.zext64(y), self.zext64(cin)); - let w = if name == "v_add_co_ci_u32" { - let s = self.add(x6, y6); - self.add(s, c6) + let (t, carry) = if name == "v_add_co_ci_u32" { + let t0 = self.add(x, y); + let t = self.add(t0, cin); + let c0 = self.cmp(Pred::ULt, t0, x); + let c1 = self.cmp(Pred::ULt, t, t0); + (t, self.lor(c0, c1)) } else { - let s = self.sub(x6, y6); - self.sub(s, c6) + let t0 = self.sub(x, y); + let t = self.sub(t0, cin); + let c0 = self.cmp(Pred::ULt, x, y); + let c1 = self.cmp(Pred::ULt, t0, cin); + (t, self.lor(c0, c1)) }; - let (t, hi) = self.unpack64(w); - let carry = self.nz(hi); let sdst = outs.get(1).map(|o| Self::dst_of(d, o)).unwrap_or(Dst::S(106)); self.write_mask(&sdst, carry); self.vwrite(d, &dst, t); @@ -1428,3 +1431,110 @@ impl Lw { } } } + +#[cfg(test)] +mod valu_carry_tests { + use super::super::kernel::{self, KernelOptions}; + use super::super::validate; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + #[test] + fn valu_carry_ops_avoid_i64_and_match_gpu() { + let mut code = Vec::new(); + for &(name, enc, fields) in &[ + // v2 = v0 + v1 + cin(s0), carry -> s2 + ("V_ADD_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 2u64), ("SDST", 2), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)][..]), + // v3 = v0 - v1 - cin(s0), borrow -> s4 + ("V_SUB_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 3), ("SDST", 4), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + // v4 = v1 - v0 - cin(s0), borrow -> s6 + ("V_SUBREV_CO_CI_U32", "VOP3_SDST_ENC", &[("VDST", 4), ("SDST", 6), ("SRC0", 256), ("SRC1", 257), ("SRC2", 0)]), + ] { + code.extend(encode(name, enc, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("translate valu carry ops"); + validate::validate(&dxil).expect("validate valu carry ops"); + let dis = validate::disassemble(&dxil).expect("disasm valu carry ops"); + assert!(!dis.contains("64-Bit integer"), "32-bit VALU carry ops must not require Int64Ops:\n{dis}"); + assert!(!dis.contains("zext i32"), "32-bit VALU carry ops must not widen to i64:\n{dis}"); + + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + // Boundary triples (x, y, cin) covering overflow/underflow with and without carry/borrow-in. + let cases: [(u32, u32, bool); 32] = [ + (0, 0, false), + (0, 0, true), + (0, 1, false), + (0, 1, true), + (1, 0, false), + (1, 0, true), + (1, 1, false), + (1, 1, true), + (u32::MAX, 0, false), + (u32::MAX, 0, true), + (u32::MAX, 1, false), + (u32::MAX, 1, true), + (0, u32::MAX, false), + (0, u32::MAX, true), + (u32::MAX, u32::MAX, false), + (u32::MAX, u32::MAX, true), + (u32::MAX - 1, 1, false), + (u32::MAX - 1, 1, true), + (0x7FFF_FFFF, 0x8000_0000, false), + (0x7FFF_FFFF, 0x8000_0000, true), + (0x8000_0000, 0x8000_0000, false), + (0x8000_0000, 0x8000_0000, true), + (0x8000_0000, 0x7FFF_FFFF, false), + (0x8000_0000, 0x7FFF_FFFF, true), + (2, 1, false), + (2, 1, true), + (1, 2, false), + (1, 2, true), + (0x1234_5678, 0xEDCB_A987, false), + (0x1234_5678, 0xEDCB_A987, true), + (0x1234_5678, 0xEDCB_A988, false), + (0x1234_5678, 0xEDCB_A988, true), + ]; + let mut st = runner::KernelState::default(); + let mut cin_mask = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + st.vgpr[l][0] = x; + st.vgpr[l][1] = y; + if cin { + cin_mask |= 1u32 << l; + } + } + st.sgpr[0] = cin_mask; + let r = runner::run(&dxil, &st, &[]).expect("GPU run valu carry ops"); + + let mut want_add_c = 0u32; + let mut want_sub_b = 0u32; + let mut want_subrev_b = 0u32; + for (l, &(x, y, cin)) in cases.iter().enumerate() { + let c = cin as u64; + let add64 = x as u64 + y as u64 + c; + assert_eq!(r.vgpr[l][2], add64 as u32, "add_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (add64 >> 32) != 0 { + want_add_c |= 1u32 << l; + } + let sub64 = (x as u64).wrapping_sub(y as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][3], sub64 as u32, "sub_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (sub64 >> 32) != 0 { + want_sub_b |= 1u32 << l; + } + let subrev64 = (y as u64).wrapping_sub(x as u64).wrapping_sub(c); + assert_eq!(r.vgpr[l][4], subrev64 as u32, "subrev_co_ci lane {l} ({x:#x}, {y:#x}, {cin})"); + if (subrev64 >> 32) != 0 { + want_subrev_b |= 1u32 << l; + } + } + assert_eq!(r.sgpr[2], want_add_c, "add_co_ci carry-out mask"); + assert_eq!(r.sgpr[4], want_sub_b, "sub_co_ci borrow-out mask"); + assert_eq!(r.sgpr[6], want_subrev_b, "subrev_co_ci borrow-out mask"); + } +} diff --git a/crates/xcl/src/gpu/dxil/mod.rs b/crates/xcl/src/gpu/dxil/mod.rs index a0ec94583f..9540026ed1 100644 --- a/crates/xcl/src/gpu/dxil/mod.rs +++ b/crates/xcl/src/gpu/dxil/mod.rs @@ -57,3 +57,5 @@ mod msaa_tests; mod round_tests; #[cfg(test)] mod geometry_tests; +#[cfg(test)] +mod select_tests; diff --git a/crates/xcl/src/gpu/dxil/module.rs b/crates/xcl/src/gpu/dxil/module.rs index d72ef6fc38..da9932c11d 100644 --- a/crates/xcl/src/gpu/dxil/module.rs +++ b/crates/xcl/src/gpu/dxil/module.rs @@ -16,6 +16,8 @@ use std::collections::HashMap; use super::bitstream::{signed, BitWriter}; mod opt; +#[cfg(test)] +pub(crate) use opt::NO_SELECT_FOLD; pub(super) mod split; // ---------------------------------------------------------------- types @@ -815,6 +817,31 @@ impl Module { self.try_to_bitcode(triple, datalayout).unwrap_or_else(|e| panic!("DXIL builder: {e}")) } + /// Static resource ranges referenced by reachable `createHandleFromBinding` + /// calls. A dynamic binding descriptor makes the result unknowable. + pub(super) fn referenced_bindings(&self) -> Option> { + let (order, _) = self.block_layout(); + let mut refs = Vec::new(); + for &block in &order { + for &inst in &self.blocks[block] { + let Op::Call(func, args) = &self.insts[inst as usize].op else { continue }; + if self.funcs[*func as usize].name != "dx.op.createHandleFromBinding" { + continue; + } + let Some(&Value::Const(bind)) = args.get(1) else { return None }; + let ConstDef::Aggregate(_, fields) = &self.consts[bind as usize] else { return None }; + let [lower, upper, space, class] = fields.as_slice() else { return None }; + refs.push(( + self.const_u64(*class)? as u8, + self.const_u64(*space)? as u32, + self.const_u64(*lower)? as u32, + self.const_u64(*upper)? as u32, + )); + } + } + Some(refs) + } + fn write_bitcode(&mut self, triple: &str, datalayout: &str) -> Vec { // Every type the writer references must exist before the type table: // pointers to the declared functions (call / metadata operands). @@ -827,37 +854,10 @@ impl Module { // are dropped. Value numbering follows that order. let (order, pos) = self.block_layout(); - // Global variables nothing references (e.g. an exchange array the code never - // needed) are left out: the validator rejects unused internal declarations. - // Likewise declarations of functions no longer called (after `optimize`). - let mut gused = vec![false; self.globals.len()]; - let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); - { - let mut mark = |v: Value| match v { - Value::Global(g) => gused[g as usize] = true, - Value::Func(f) => fused[f as usize] = true, - _ => {} - }; - for &b in &order { - for &i in &self.blocks[b] { - let op = &self.insts[i as usize].op; - if let Op::Call(f, _) = op { - mark(Value::Func(*f)); - } - op.for_each_operand(&mut mark); - } - } - for c in &self.consts { - if let ConstDef::Aggregate(_, e) = c { - e.iter().copied().for_each(&mut mark); - } - } - for m in &self.md { - if let MdDef::Val(_, v) = m { - mark(*v); - } - } - } + // Global variables, declarations, and module constants nothing references + // are left out: the validator rejects unused internal declarations, and + // pruning dead constants keeps BLOCK_CONSTANTS compact after `optimize`. + let (gused, fused, cused) = self.live_values(&order, &pos); let mut gmap: Vec> = vec![None; self.globals.len()]; let mut n_globals = 0u64; for (g, used) in gused.iter().enumerate() { @@ -876,7 +876,11 @@ impl Module { } } let fmap = &fmap; - let n_consts = self.consts.len() as u64; + let (mut cmap, mut n_consts) = (vec![None; self.consts.len()], 0u64); + for (c, &used) in cused.iter().enumerate() { + if used { cmap[c] = Some(n_consts); n_consts += 1; } + } + let cmap = &cmap; let const_base = n_globals + n_funcs; let inst_base = const_base + n_consts; @@ -897,7 +901,7 @@ impl Module { match v { Value::Global(g) => gmap[g as usize].expect("use of a dropped global"), Value::Func(f) => n_globals + fmap[f as usize].expect("use of a dropped function"), - Value::Const(c) => const_base + c as u64, + Value::Const(c) => const_base + cmap[c as usize].expect("use of a dropped constant"), Value::Inst(i) => inst_ids[i as usize].unwrap_or_else(|| { self.fail(format!("use of a void instruction %{i}")); 0 @@ -952,10 +956,10 @@ impl Module { } // Module-level constants. - if !self.consts.is_empty() { + if n_consts > 0 { w.enter_block(BLOCK_CONSTANTS); let mut cur_ty = None; - for c in &self.consts { + for c in self.consts.iter().enumerate().filter(|(i, _)| cused[*i]).map(|x| x.1) { let t = match c { ConstDef::Int(t, _) | ConstDef::Float(t, _) | ConstDef::Undef(t) | ConstDef::Null(t) | ConstDef::Aggregate(t, _) => *t, }; @@ -1036,6 +1040,51 @@ impl Module { matches!(self.types[t.0 as usize], TypeDef::Void) } + /// `(gused, fused, cused)` liveness over reachable blocks (`order`) and metadata. + fn live_values(&self, order: &[usize], pos: &[Option]) -> (Vec, Vec, Vec) { + let mut gused = vec![false; self.globals.len()]; + let mut fused: Vec = self.funcs.iter().map(|f| f.defined).collect(); + let mut cused = vec![false; self.consts.len()]; + let mut work = Vec::new(); + let mark = |v: Value, g: &mut [bool], f: &mut [bool], c: &mut [bool], w: &mut Vec| match v { + Value::Global(i) if !g[i as usize] => { g[i as usize] = true; w.push(v); } + Value::Func(i) => f[i as usize] = true, + Value::Const(i) if !c[i as usize] => { c[i as usize] = true; w.push(v); } + _ => {} + }; + for &b in order { + for &i in &self.blocks[b] { + match &self.insts[i as usize].op { + Op::Call(f, args) => { + mark(Value::Func(*f), &mut gused, &mut fused, &mut cused, &mut work); + args.iter().for_each(|&a| mark(a, &mut gused, &mut fused, &mut cused, &mut work)); + } + Op::Phi(inc) => for &(v, pred) in inc { + if pos.get(pred.0 as usize).copied().flatten().is_some() { + mark(v, &mut gused, &mut fused, &mut cused, &mut work); + } + }, + op => op.for_each_operand(|v| mark(v, &mut gused, &mut fused, &mut cused, &mut work)), + } + } + } + for m in &self.md { + if let MdDef::Val(_, v) = m { mark(*v, &mut gused, &mut fused, &mut cused, &mut work); } + } + while let Some(v) = work.pop() { + match v { + Value::Global(g) => if let Some(init) = self.globals[g as usize].init { + mark(init, &mut gused, &mut fused, &mut cused, &mut work); + }, + Value::Const(c) => if let ConstDef::Aggregate(_, elems) = &self.consts[c as usize] { + elems.iter().for_each(|&e| mark(e, &mut gused, &mut fused, &mut cused, &mut work)); + }, + _ => {} + } + } + (gused, fused, cused) + } + fn write_types(&self, w: &mut BitWriter) { w.enter_block(BLOCK_TYPE); w.record(TYPE_CODE_NUMENTRY, &[self.types.len() as u64]); @@ -1541,6 +1590,7 @@ impl Module { #[cfg(test)] mod tests { use super::*; + use crate::gpu::dxil::{container::Stage, shader::{self, Shader}, validate}; #[test] fn sign_extension_does_not_intern_unrelated_integer_types() { @@ -1569,4 +1619,105 @@ mod tests { if source == bit && module.int_width(ty) == Some(32))); assert!(matches!(second.op, Op::Cast(CastOp::SExt, Value::Inst(0), ty) if ty == i64)); } + + fn symtab_names(bc: &[u8]) -> Vec { + assert!(bc.starts_with(&[b'B', b'C', 0xC0, 0xDE])); + let (mut bit, mut w, mut blk, mut stack, mut out) = (32usize, 2u32, 0u32, Vec::new(), Vec::new()); + let bits = |bit: &mut usize, n: u32| (0..n).fold(0u64, |v, k| { let b = (bc[*bit / 8] >> (*bit % 8)) & 1; *bit += 1; v | ((b as u64) << k) }); + let vbr = |bit: &mut usize, n: u32| { + let (mut o, mut s, hi) = (0u64, 0u32, 1u64 << (n - 1)); + loop { let c = bits(bit, n); o |= (c & (hi - 1)) << s; if c & hi == 0 { return o; } s += n - 1; } + }; + while bit + w as usize <= bc.len() * 8 { + match bits(&mut bit, w) { + 0 => { bit = (bit + 31) & !31; if let Some((pw, pb)) = stack.pop() { w = pw; blk = pb; } else { break; } } + 1 => { let (id, nw) = (vbr(&mut bit, 8) as u32, vbr(&mut bit, 4) as u32); bit = ((bit + 31) & !31) + 32; stack.push((w, blk)); w = nw; blk = id; } + 3 => { + let (code, n) = (vbr(&mut bit, 6) as u32, vbr(&mut bit, 6) as usize); + let ops: Vec = (0..n).map(|_| vbr(&mut bit, 6)).collect(); + if blk == BLOCK_VALUE_SYMTAB && code == VST_CODE_ENTRY { out.push(String::from_utf8(ops[1..].iter().map(|&x| x as u8).collect()).unwrap()); } + } + other => panic!("unexpected abbrev {other}"), + } + } + out + } + + #[test] + fn unused_scalar_constants_produce_identical_bitcode() { + let build = |with_dead: bool| { + let mut m = Module::new(); + m.define_entry("main"); + let (entry, merge, i32) = (m.entry_block(), m.new_block(), m.i32()); + let (c_i, c_f, c_md) = (m.i32c(7), m.f32c(1.0f32.to_bits()), m.i32c(99)); + let _ = m.md_value(c_md); + let sum = m.bin(BinOp::Add, c_i, c_i); + let _ = m.fbin(BinOp::Add, c_f, c_f, fmf::NONE); + m.br(merge); m.set_block(merge); + let phi = m.phi(i32); m.add_incoming(phi, sum, entry); m.ret(); + let mut dead = Vec::new(); + if with_dead { + for k in 0..256u32 { dead.extend([m.i32c(10_000 + k), m.f32c((2.0f32 + k as f32).to_bits())]); } + let unreach = m.new_block(); m.set_block(unreach); + let (c_u, c_phi) = (m.i32c(0xDEAD_0001), m.i32c(0xDEAD_0002)); + let _ = m.bin(BinOp::Add, c_u, c_u); m.br(merge); + m.add_incoming(phi, c_phi, unreach); dead.extend([c_u, c_phi]); + } + (m, [c_i, c_f, c_md], dead) + }; + let ((mut clean, _, _), (mut noisy, live, dead)) = (build(false), build(true)); + let (order, pos) = noisy.block_layout(); let (_, _, cused) = noisy.live_values(&order, &pos); + for v in live { let Value::Const(c) = v else { unreachable!() }; assert!(cused[c as usize]); } + for v in dead { let Value::Const(c) = v else { unreachable!() }; assert!(!cused[c as usize]); } + assert_eq!(clean.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap(), noisy.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap()); + } + + #[test] + fn dead_aggregate_does_not_retain_unused_global_while_live_global_init_is_kept() { + let mut m = Module::new(); m.define_entry("main"); + let i32 = m.i32(); + let (inner_ty, p_i32) = (m.array(2, i32), m.ptr(i32, 0)); + let (outer_ty, dead_arr_ty) = (m.array(2, inner_ty), m.array(1, p_i32)); + let (a0, a1, a2, a3, z, d_val) = (m.i32c(11), m.i32c(22), m.i32c(33), m.i32c(44), m.i32c(0), m.i32c(77)); + let (r0, r1) = (m.aggregate(inner_ty, &[a0, a1]), m.aggregate(inner_ty, &[a2, a3])); + let live_init = m.aggregate(outer_ty, &[r0, r1]); + let g_live = m.global("live_tbl", outer_ty, 0, Some(live_init), true, 4); + let p = m.gep(g_live, &[z, z, z]); let _ = m.load(p, 4); m.ret(); + let g_dead_inner = m.global("dead_inner_sym", i32, 0, Some(d_val), true, 4); + let dead_agg = m.aggregate(dead_arr_ty, &[g_dead_inner]); + let g_dead = m.global("dead_outer_sym", dead_arr_ty, 0, Some(dead_agg), true, 4); + let (order, pos) = m.block_layout(); let (gused, _, cused) = m.live_values(&order, &pos); + let (Value::Global(gl), Value::Global(gd), Value::Global(gdi)) = (g_live, g_dead, g_dead_inner) else { unreachable!() }; + assert!(gused[gl as usize] && !gused[gd as usize] && !gused[gdi as usize], "globals: {gused:?}"); + for v in [a0, a1, a2, a3, r0, r1, live_init, z] { let Value::Const(c) = v else { unreachable!() }; assert!(cused[c as usize]); } + for v in [d_val, dead_agg] { let Value::Const(c) = v else { unreachable!() }; assert!(!cused[c as usize]); } + let bc = m.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap(); + assert_eq!(bc, m.try_to_bitcode(shader::TRIPLE, shader::DATALAYOUT).unwrap()); + let names = symtab_names(&bc); + assert!(names.iter().any(|n| n == "live_tbl") && !names.iter().any(|n| n == "dead_outer_sym" || n == "dead_inner_sym"), "{names:?}"); + } + + #[test] + fn pruned_direct_dxil_shader_with_live_table_and_dead_constants_validates() { + let mut s = Shader::new(Stage::Compute, (6, 6)); + let (uav, i32) = (s.raw_uav(0, 0), s.m.i32()); + let (at, p_i32) = (s.m.array(4, i32), s.m.ptr(i32, 0)); + let vals = [s.m.i32c(10), s.m.i32c(20), s.m.i32c(30), s.m.i32c(40)]; + let init = s.m.aggregate(at, &vals); let tbl = s.m.global("live_tbl", at, 0, Some(init), true, 4); + let tid = s.thread_id_in_group(0); + let (c0, c2, c3) = (s.m.i32c(0), s.m.i32c(2), s.m.i32c(3)); + let idx = s.m.bin(BinOp::And, tid, c3); let ptr = s.m.gep(tbl, &[c0, idx]); + let loaded = s.m.load(ptr, 4); let off = s.m.bin(BinOp::Shl, tid, c2); + s.raw_store(uav, off, &[loaded]); + for k in 0..64u32 { let _ = s.m.i32c(10_000 + k); } + let d0 = s.m.i32c(9999); let g_dead = s.m.global("dead_inner_tbl", i32, 0, Some(d0), true, 4); + let d_arr = s.m.array(1, p_i32); let _dead_agg = s.m.aggregate(d_arr, &[g_dead]); + let dxil = s.try_finish([1, 1, 1], None).expect("try_finish must succeed"); + assert!(dxil.len() >= 32 && &dxil[..4] == b"DXBC"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("pruned DXIL shader must validate"); + let dis = validate::disassemble(&dxil).expect("disassemble pruned DXIL shader"); + assert!(dis.contains("@live_tbl") && !dis.contains("@dead_inner_tbl"), "unexpected globals:\n{dis}"); + } + } } diff --git a/crates/xcl/src/gpu/dxil/module/opt.rs b/crates/xcl/src/gpu/dxil/module/opt.rs index 230a59f9f9..14dbbca01f 100644 --- a/crates/xcl/src/gpu/dxil/module/opt.rs +++ b/crates/xcl/src/gpu/dxil/module/opt.rs @@ -68,6 +68,12 @@ impl Op { } } +#[cfg(test)] +thread_local! { + /// Tests can compare emitted code with the guarded-select fold disabled. + pub(crate) static NO_SELECT_FOLD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + /// How an instruction may be merged with an identical one. #[derive(PartialEq)] enum Cse { @@ -106,12 +112,195 @@ impl Module { } } + /// Conservative unsigned `[lo, hi]` value range of an `i32` value, up to `depth` steps deep. + fn unsigned_range_i32(&self, v: Value, depth: u8) -> (u32, u32) { + if let Some(c) = self.const_u64(v) { + let k = c as u32; + return (k, k); + } + if depth == 0 { + return (0, u32::MAX); + } + let Value::Inst(j) = v else { return (0, u32::MAX) }; + let d = depth - 1; + match &self.insts[j as usize].op { + Op::Bin(BinOp::And, x, y, 0) => match self.const_u64(*x).or_else(|| self.const_u64(*y)) { + Some(m) => (0, m as u32), + None => (0, u32::MAX), + }, + Op::Bin(BinOp::LShr, _, sh, 0) => match self.const_u64(*sh) { + Some(s) if s < 32 => (0, u32::MAX >> s), + _ => (0, u32::MAX), + }, + Op::Cast(CastOp::ZExt, inner, _) => match self.int_width(self.value_ty(*inner)) { + Some(iw) if iw < 32 => (0, (1u32 << iw) - 1), + _ => (0, u32::MAX), + }, + Op::Select(_, t, f) => { + let (lt, ht) = self.unsigned_range_i32(*t, d); + let (lf, hf) = self.unsigned_range_i32(*f, d); + (lt.min(lf), ht.max(hf)) + } + Op::Call(f, args) if args.len() == 3 && self.funcs[*f as usize].name == "dx.op.binary.i32" => { + match self.const_u64(args[0]) { + Some(39) => { + let (la, ha) = self.unsigned_range_i32(args[1], d); + let (lb, hb) = self.unsigned_range_i32(args[2], d); + (la.max(lb), ha.max(hb)) + } + Some(40) => { + let (la, ha) = self.unsigned_range_i32(args[1], d); + let (lb, hb) = self.unsigned_range_i32(args[2], d); + (la.min(lb), ha.min(hb)) + } + _ => (0, u32::MAX), + } + } + _ => (0, u32::MAX), + } + } + + /// Conservative signed `[lo, hi]` value range of an `i32` value, up to `depth` steps deep. + fn signed_range_i32(&self, v: Value, depth: u8) -> (i32, i32) { + if let Some(c) = self.const_u64(v) { + let k = c as u32 as i32; + return (k, k); + } + if depth == 0 { + return (i32::MIN, i32::MAX); + } + let Value::Inst(j) = v else { return (i32::MIN, i32::MAX) }; + let d = depth - 1; + match &self.insts[j as usize].op { + Op::Bin(BinOp::And, x, y, 0) => match self.const_u64(*x).or_else(|| self.const_u64(*y)) { + Some(m) if (m as u32) <= i32::MAX as u32 => (0, m as u32 as i32), + _ => (i32::MIN, i32::MAX), + }, + Op::Bin(BinOp::LShr, _, sh, 0) => match self.const_u64(*sh) { + Some(s) if (1..32).contains(&s) => (0, (u32::MAX >> s) as i32), + _ => (i32::MIN, i32::MAX), + }, + Op::Bin(BinOp::AShr, _, sh, 0) => match self.const_u64(*sh) { + Some(s) if (1..32).contains(&s) => (i32::MIN >> s, i32::MAX >> s), + _ => (i32::MIN, i32::MAX), + }, + Op::Cast(CastOp::ZExt, inner, _) => match self.int_width(self.value_ty(*inner)) { + Some(iw) if iw < 32 => (0, ((1u32 << iw) - 1) as i32), + _ => (i32::MIN, i32::MAX), + }, + Op::Cast(CastOp::SExt, inner, _) => match self.int_width(self.value_ty(*inner)) { + Some(iw) if (1..32).contains(&iw) => (-(1i32 << (iw - 1)), (1i32 << (iw - 1)) - 1), + _ => (i32::MIN, i32::MAX), + }, + Op::Select(_, t, f) => { + let (lt, ht) = self.signed_range_i32(*t, d); + let (lf, hf) = self.signed_range_i32(*f, d); + (lt.min(lf), ht.max(hf)) + } + Op::Call(f, args) if args.len() == 3 && self.funcs[*f as usize].name == "dx.op.binary.i32" => { + match self.const_u64(args[0]) { + Some(37) => { + let (la, ha) = self.signed_range_i32(args[1], d); + let (lb, hb) = self.signed_range_i32(args[2], d); + (la.max(lb), ha.max(hb)) + } + Some(38) => { + let (la, ha) = self.signed_range_i32(args[1], d); + let (lb, hb) = self.signed_range_i32(args[2], d); + (la.min(lb), ha.min(hb)) + } + _ => (i32::MIN, i32::MAX), + } + } + _ => (i32::MIN, i32::MAX), + } + } + + /// Simplifies `dx.op.binary.i32` integer min/max (`IMax=37`, `IMin=38`, `UMax=39`, `UMin=40`) + /// via operand identity, lattice absorption, and conservative `[lo, hi]` interval bounds. + fn simplify_int_minmax(&self, op_code: u64, a: Value, b: Value) -> Option { + let (is_signed, is_max, dual) = match op_code { + 37 => (true, true, 38u64), + 38 => (true, false, 37u64), + 39 => (false, true, 40u64), + 40 => (false, false, 39u64), + _ => return None, + }; + if a == b { + return Some(a); + } + // Lattice idempotence & absorption: min(min(x,y), x) = min(x,y), min(max(x,y), x) = x, etc. + for (cand, other) in [(a, b), (b, a)] { + if let Value::Inst(j) = cand { + if let Op::Call(f2, a2) = &self.insts[j as usize].op { + if a2.len() == 3 && self.funcs[*f2 as usize].name == "dx.op.binary.i32" { + let inner_op = self.const_u64(a2[0]); + if a2[1] == other || a2[2] == other { + if inner_op == Some(op_code) { + return Some(cand); + } + if inner_op == Some(dual) { + return Some(other); + } + } + } + } + } + } + if is_signed { + let (la, ha) = self.signed_range_i32(a, 4); + let (lb, hb) = self.signed_range_i32(b, 4); + if is_max { + if la >= hb { + return Some(a); + } + if lb >= ha { + return Some(b); + } + } else { + if ha <= lb { + return Some(a); + } + if hb <= la { + return Some(b); + } + } + } else { + let (la, ha) = self.unsigned_range_i32(a, 4); + let (lb, hb) = self.unsigned_range_i32(b, 4); + if is_max { + if la >= hb { + return Some(a); + } + if lb >= ha { + return Some(b); + } + } else { + if ha <= lb { + return Some(a); + } + if hb <= la { + return Some(b); + } + } + } + None + } + /// Cheap algebraic & constant simplification on already-resolved operands. fn simplify_op(&mut self, op: &Op, ty: Ty) -> Option { // Keep 64-bit instructions intact so Int64Ops / Doubles shader flags stay consistent. if matches!(self.types[ty.0 as usize], super::TypeDef::Int(64) | super::TypeDef::Double) { return None; } + if let Op::Call(f, args) = op { + if args.len() == 3 && self.funcs[*f as usize].name == "dx.op.binary.i32" { + if let Some(op_code) = self.const_u64(args[0]) { + return self.simplify_int_minmax(op_code, args[1], args[2]); + } + } + return None; + } match *op { Op::Select(c, t, f) => { if t == f { @@ -427,7 +616,7 @@ impl Module { /// Cleans up the entry function (see the module docs of `opt`). Values /// keep their identities; replaced ones simply lose their uses. /// - /// `XCL_DXIL_NO_OPT=phi,cse,dce,merge` (any subset, or `all`) skips passes, for bisecting. + /// `XCL_DXIL_NO_OPT=phi,cse,select,dce,merge` (any subset, or `all`) skips passes, for bisecting. pub fn optimize(&mut self) { let off = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); let skip = |p: &str| off.split(',').any(|x| x.trim() == p || x.trim() == "all"); @@ -457,6 +646,14 @@ impl Module { } let mut repl: Vec> = vec![None; self.insts.len()]; + let mut inst_at = vec![usize::MAX; self.insts.len()]; + let mut at = 0; + for &b in &order { + for &i in &self.blocks[b as usize] { + inst_at[i as usize] = at; + at += 1; + } + } // trivial phis (all incoming values the phi itself or one value), to a fixed point while !skip("phi") { @@ -482,7 +679,14 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + // A phi may refer to a value produced on a backedge. Replacing the phi + // with that value would make uses near the block header precede its + // definition in the serialized function. + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl[i] = Some(v); changed = true; } @@ -586,7 +790,11 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl[i] = Some(v); changed = true; } @@ -605,6 +813,14 @@ impl Module { } } + #[cfg(test)] + let skip_select = NO_SELECT_FOLD.with(|c| c.get()); + #[cfg(not(test))] + let skip_select = false; + if !skip("select") && !skip_select { + self.fold_guarded_selects(&order, &repl); + } + // dead instructions: live = side effects, terminators and their operands, transitively let (i64t, f64t) = self.existing_i64_f64(); let wide: Vec = i64t.into_iter().chain(f64t).collect(); @@ -634,6 +850,14 @@ impl Module { if !skip("merge") && self.simplify_cfg() { let order: Vec = self.block_layout().0.into_iter().map(|b| b as u32).collect(); + inst_at.fill(usize::MAX); + let mut at = 0; + for &b in &order { + for &i in &self.blocks[b as usize] { + inst_at[i as usize] = at; + at += 1; + } + } let mut repl2: Vec> = vec![None; self.insts.len()]; let mut phi_changed = false; while !skip("phi") { @@ -659,7 +883,11 @@ impl Module { } same = Some(v); } - if let (true, Some(v)) = (trivial, same) { + let available = same.is_some_and(|v| match v { + Value::Inst(j) => inst_at[j as usize] < inst_at[i], + _ => true, + }); + if let (true, true, Some(v)) = (trivial, available, same) { repl2[i] = Some(v); changed = true; phi_changed = true; @@ -707,6 +935,115 @@ impl Module { } } + /// Whether `op` computes each lane from only that lane's operands. Operations whose + /// evaluation observes other lanes, memory, or undefined integer division operands are + /// deliberately excluded. + fn lane_local(&self, op: &Op, ty: Ty) -> bool { + match op { + Op::Bin(BinOp::UDiv | BinOp::URem, ..) => false, + Op::Bin(BinOp::SDiv | BinOp::SRem, ..) => self.is_float(ty), + Op::Bin(..) | Op::Cast(..) | Op::Cmp(..) | Op::Select(..) | Op::Extract(..) => true, + Op::Call(f, args) => { + let d = &self.funcs[*f as usize]; + d.attrs == FnAttrs::ReadNone + && d.name.starts_with("dx.op.") + && args.first().and_then(|&a| self.const_u64(a)).is_some_and(|id| matches!(id, 6..=56 | 101 | 102 | 124..=132)) + } + _ => false, + } + } + + /// Reads through `select(c, current, old)` only where the value is ultimately observed + /// under the same `c`. This removes guest-EXEC preservation arms from chains of lane-local + /// operations without changing inactive lanes. Phis and non-lane-local operations observe + /// all lanes and stop the fold. + fn fold_guarded_selects(&mut self, order: &[u32], repl: &[Option]) { + #[derive(Clone, Copy, PartialEq)] + enum Seen { + Unused, + Where(Value), + All, + } + fn meet(s: &mut Seen, by: Seen) { + *s = match (*s, by) { + (x, Seen::Unused) => x, + (Seen::Unused, y) => y, + (Seen::Where(a), Seen::Where(b)) if a == b => Seen::Where(a), + _ => Seen::All, + } + } + + let live = |i: u32| repl[i as usize].is_none(); + let mut seen = vec![Seen::Unused; self.insts.len()]; + for &b in order { + for &i in &self.blocks[b as usize] { + if let (true, Op::Phi(inc)) = (live(i), &self.insts[i as usize].op) { + for &(v, _) in inc { + if let Value::Inst(j) = v { + seen[j as usize] = Seen::All; + } + } + } + } + } + for &b in order.iter().rev() { + for &i in self.blocks[b as usize].iter().rev() { + if !live(i) { + continue; + } + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if matches!(op, Op::Phi(_)) { + continue; + } + let me = if self.lane_local(op, ty) { seen[i as usize] } else { Seen::All }; + if me == Seen::Unused { + continue; + } + let mut by = |v: Value, s: Seen| { + if let Value::Inst(j) = v { + meet(&mut seen[j as usize], s); + } + }; + match *op { + Op::Select(c, a, b) => { + by(c, me); + by(a, Seen::Where(c)); + by(b, me); + } + _ => op.for_each_operand(|v| by(v, me)), + } + } + } + for &b in order { + for k in 0..self.blocks[b as usize].len() { + let i = self.blocks[b as usize][k]; + let (op, ty) = (&self.insts[i as usize].op, self.insts[i as usize].ty); + if !live(i) || seen[i as usize] == Seen::Unused || !self.lane_local(op, ty) { + continue; + } + let me = seen[i as usize]; + let outer_condition = if let Op::Select(c, ..) = *op { Some(c) } else { None }; + let mut op = op.clone(); + let mut pos = 0; + op.map_operands(|mut v| { + let at = pos; + pos += 1; + while let Value::Inst(j) = v { + let Op::Select(c, t, f) = self.insts[j as usize].op else { break }; + v = match (outer_condition, at) { + (Some(outer), 1) if outer == c => t, + (Some(outer), 2) if outer == c => f, + _ if me == Seen::Where(c) => t, + _ => break, + }; + } + v + }); + self.insts[i as usize].op = op; + } + } + } + /// Simplifies the CFG to a fixed point: /// 1. Collapses degenerate `CondBr(_, t, t)` and `Switch` cases matching the default target. /// 2. Bypasses empty trampoline blocks (`[Br(t)]`) whenever `t`'s phis allow it. @@ -1261,6 +1598,47 @@ mod tests { assert!(!inc.iter().any(|&(_, b)| b == latch), "merged latch must not remain in header phi"); } + #[test] + fn trivial_loop_phi_keeps_backedge_definition_after_header_uses() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + let header = m.new_block(); + let latch = m.new_block(); + let exit = m.new_block(); + + let void = m.void(); + let i32t = m.i32(); + let sink_ty = m.func_ty(void, &[i32t]); + let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind); + + m.set_block(entry); + let one = m.i32c(1); + let limit = m.i32c(10); + m.br(header); + + m.set_block(header); + let iv = m.phi(i32t); + m.add_incoming(iv, iv, entry); + m.br(latch); + + m.set_block(latch); + let next = m.bin(BinOp::Add, iv, one); + m.add_incoming(iv, next, latch); + let cont = m.cmp(Pred::ULt, next, limit); + m.cond_br(cont, header, exit); + + m.set_block(exit); + m.call(sink, &[next]); + m.ret(); + + m.optimize(); + let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); + assert!(m.uses_well_formed(&order)); + let Value::Inst(iv_i) = iv else { unreachable!() }; + assert!(m.blocks.iter().any(|b| b.contains(&iv_i)), "the backedge value cannot replace the header phi"); + } + #[test] fn simplify_cfg_does_not_inflate_multi_pred_phi_trampoline() { let mut m = Module::new(); @@ -1401,4 +1779,218 @@ mod tests { let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); assert!(m.uses_well_formed(&order)); } + #[test] + fn guarded_selects_fold_only_for_same_condition_lane_local_uses() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + m.set_block(entry); + + let void = m.void(); + let i32t = m.i32(); + let src_ty = m.func_ty(i32t, &[]); + let src = m.declare("dx.op.waveGetLaneIndex", src_ty, FnAttrs::ReadNone); + let sink_ty = m.func_ty(void, &[i32t]); + let sink = m.declare("dx.op.storeOutput.i32", sink_ty, FnAttrs::NoUnwind); + + let x = m.call(src, &[]); + let (one, three, five, sentinel) = (m.i32c(1), m.i32c(3), m.i32c(5), m.i32c(0xA5A5_5A5A)); + let exec = m.cmp(Pred::ULt, x, five); + let old = m.bin(BinOp::Xor, x, sentinel); + let current = m.bin(BinOp::Add, x, one); + let saved = m.select(exec, current, old); + let product = m.bin(BinOp::Mul, saved, three); + let guarded = m.select(exec, product, saved); + + // A second preserved value is read by an all-lane observer and must remain intact. + let must_stay = m.select(exec, current, x); + let all_lane_use = m.bin(BinOp::Sub, must_stay, one); + m.call(sink, &[guarded]); + m.call(sink, &[all_lane_use]); + m.ret(); + m.optimize(); + + let Value::Inst(guarded_i) = guarded else { panic!() }; + let Value::Inst(product_i) = product else { panic!() }; + assert!(matches!(m.insts[guarded_i as usize].op, Op::Select(c, t, f) if c == exec && t == product && f == old)); + assert!(matches!(m.insts[product_i as usize].op, Op::Bin(BinOp::Mul, a, b, 0) if (a, b) == (current, three) || (a, b) == (three, current))); + let body = &m.blocks[entry.0 as usize]; + let present = |v: Value| matches!(v, Value::Inst(i) if body.contains(&i)); + assert!(!present(saved), "the EXEC-preservation select should have no uses"); + assert!(present(must_stay), "an all-lane use must retain its preservation select"); + let order: Vec = m.block_layout().0.into_iter().map(|b| b as u32).collect(); + assert!(m.uses_well_formed(&order)); + } +} + +#[cfg(test)] +mod int_minmax_tests { + use super::*; + use crate::gpu::dxil::{ + kernel::{self, KernelOptions}, + validate, + }; + use crate::gpu::rdna2::encode; + use crate::gpu::recomp::runner; + + #[test] + fn simplify_int_minmax_folds_bounds_absorption_and_clamps() { + let mut m = Module::new(); + m.define_entry("main"); + let entry = m.entry_block(); + let i32t = m.i32(); + let void = m.void(); + let src_ty = m.func_ty(i32t, &[]); + let sink_ty = m.func_ty(void, &[i32t]); + let bin_ty = m.func_ty(i32t, &[i32t, i32t, i32t]); + let src = m.declare("src", src_ty, FnAttrs::NoUnwind); + let sink = m.declare("sink", sink_ty, FnAttrs::NoUnwind); + let bin_fn = m.declare("dx.op.binary.i32", bin_ty, FnAttrs::ReadNone); + m.set_block(entry); + + let x = m.call(src, &[]); + let y = m.call(src, &[]); + let imax = m.i32c(37); + let imin = m.i32c(38); + let umax = m.i32c(39); + let umin = m.i32c(40); + let c0 = m.i32c(0); + let c16 = m.i32c(16); + let c255 = m.i32c(255); + let c100 = m.i32c(100); + let cneg = m.i32c((-10i32) as u32); + let cu_max = m.i32c(u32::MAX); + let ci_min = m.i32c(i32::MIN as u32); + let ci_max = m.i32c(i32::MAX as u32); + let mff = m.i32c(0xFF); + + // 1. Constant folding & identity/absorbing bounds. + let k_umin = m.call(bin_fn, &[umin, c255, c100]); + let k_imax = m.call(bin_fn, &[imax, cneg, c100]); + let umin_zero = m.call(bin_fn, &[umin, x, c0]); + let umax_zero = m.call(bin_fn, &[umax, x, c0]); + let umin_all = m.call(bin_fn, &[umin, x, cu_max]); + let imin_min = m.call(bin_fn, &[imin, x, ci_min]); + let imax_min = m.call(bin_fn, &[imax, x, ci_min]); + let imin_max = m.call(bin_fn, &[imin, x, ci_max]); + + // 2. Lattice idempotence & absorption. + let mxy = m.call(bin_fn, &[umin, x, y]); + let idemp = m.call(bin_fn, &[umin, mxy, x]); + let absorb = m.call(bin_fn, &[umax, mxy, x]); + + // 3. Range-based elision on masked byte (0..=255) and ashr16 (-32768..=32767). + let byte = m.bin(BinOp::And, x, mff); + let byte_imax0 = m.call(bin_fn, &[imax, byte, c0]); + let byte_umin255 = m.call(bin_fn, &[umin, byte, c255]); + let s16 = m.bin(BinOp::AShr, x, c16); + let c_i16_lo = m.i32c((-32768i32) as u32); + let c_i16_hi = m.i32c(32767); + let s16_lo = m.call(bin_fn, &[imax, s16, c_i16_lo]); + let s16_hi = m.call(bin_fn, &[imin, s16_lo, c_i16_hi]); + + // 4. Full 4-op med3_i32(x, 0, 255) collapses to 2 ops: imin(imax(x, 0), 255). + let p = m.call(bin_fn, &[imin, x, c0]); + let q = m.call(bin_fn, &[imax, x, c0]); + let r = m.call(bin_fn, &[imin, q, c255]); + let med = m.call(bin_fn, &[imax, p, r]); + + // 5. Soundness check: signed mask with bit 31 set MUST NOT fold imax(x & 0x8000_00FF, 0). + let m_sign = m.i32c(0x8000_00FF); + let signed_bits = m.bin(BinOp::And, x, m_sign); + let must_stay = m.call(bin_fn, &[imax, signed_bits, c0]); + + for v in [ + k_umin, + k_imax, + umin_zero, + umax_zero, + umin_all, + imin_min, + imax_min, + imin_max, + idemp, + absorb, + byte_imax0, + byte_umin255, + s16_hi, + med, + must_stay, + ] { + m.call(sink, &[v]); + } + m.ret(); + m.optimize(); + + let args: Vec = m.blocks[entry.0 as usize] + .iter() + .filter_map(|&i| match &m.insts[i as usize].op { + Op::Call(f, a) if *f == sink => Some(a[0]), + _ => None, + }) + .collect(); + assert_eq!(args.len(), 15); + assert_eq!(m.const_u64(args[0]), Some(100), "umin(255, 100) -> 100"); + assert_eq!(m.const_u64(args[1]), Some(100), "imax(-10, 100) -> 100"); + assert_eq!(m.const_u64(args[2]), Some(0), "umin(x, 0) -> 0"); + assert_eq!(args[3], x, "umax(x, 0) -> x"); + assert_eq!(args[4], x, "umin(x, u32::MAX) -> x"); + assert_eq!(m.const_u64(args[5]), Some(i32::MIN as u32 as u64), "imin(x, i32::MIN) -> i32::MIN"); + assert_eq!(args[6], x, "imax(x, i32::MIN) -> x"); + assert_eq!(args[7], x, "imin(x, i32::MAX) -> x"); + assert_eq!(args[8], mxy, "umin(umin(x, y), x) -> umin(x, y)"); + assert_eq!(args[9], x, "umax(umin(x, y), x) -> x"); + assert_eq!(args[10], byte, "imax(x & 0xFF, 0) -> x & 0xFF"); + assert_eq!(args[11], byte, "umin(x & 0xFF, 255) -> x & 0xFF"); + assert_eq!(args[12], s16, "clamp(ashr(x, 16), -32768, 32767) -> ashr(x, 16)"); + assert_eq!(args[13], r, "med3_i32(x, 0, 255) collapses to imin(imax(x, 0), 255)"); + assert_eq!(args[14], must_stay, "imax(x & 0x800000FF, 0) must not fold"); + } + + #[test] + fn med3_via_sgpr_bounds_collapses_and_matches_gpu() { + // Real RDNA2 pattern: upper bound loaded into an SGPR (becomes constant only after mem2reg), + // then fed into v_med3_i32 / v_med3_u32 in both bound orders. + let mut code = Vec::new(); + code.extend(encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 255)], Some(255)).unwrap()); + code.extend(encode("S_MOV_B32", "ENC_SOP1", &[("SDST", 3), ("SSRC0", 128)], None).unwrap()); // 0 + // v2 = med3_i32(v0, s3=0, s2=255) -> 2 ops (down from 4) + code.extend(encode("V_MED3_I32", "ENC_VOP3", &[("VDST", 2), ("SRC0", 256), ("SRC1", 3), ("SRC2", 2)], None).unwrap()); + // v3 = med3_i32(v0, s2=255, s3=0) -> 2 ops (reversed bounds, down from 4) + code.extend(encode("V_MED3_I32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 256), ("SRC1", 2), ("SRC2", 3)], None).unwrap()); + // v4 = med3_u32(v0, s3=0, s2=255) -> 1 op (umin(v0, 255), down from 4) + code.extend(encode("V_MED3_U32", "ENC_VOP3", &[("VDST", 4), ("SRC0", 256), ("SRC1", 3), ("SRC2", 2)], None).unwrap()); + // v5 = med3_u32(v0, s3=0, v1) -> 1 op (umin(v0, v1), down from 4) + code.extend(encode("V_MED3_U32", "ENC_VOP3", &[("VDST", 5), ("SRC0", 256), ("SRC1", 3), ("SRC2", 257)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let dxil = kernel::translate(&code, ko).expect("translate sgpr med3"); + validate::validate(&dxil).expect("validate sgpr med3"); + let dis = validate::disassemble(&dxil).expect("disasm sgpr med3"); + let calls = dis.matches("call i32 @dx.op.binary.i32(").count(); + assert_eq!(calls, 6, "expected 6 binary.i32 calls (2+2+1+1, down from 16), got {calls}:\n{dis}"); + + if !matches!(runner::wave32_supported(), Ok(true)) { + runner::skip_test("no wave32"); + return; + } + let v0s: [u32; 10] = [0, 1, 128, 255, 256, 1000, (-1i32) as u32, (-255i32) as u32, i32::MIN as u32, i32::MAX as u32]; + let v1s: [u32; 10] = [10, 0, 200, 100, 300, 50, u32::MAX, 42, 0x8000_0001, 500]; + let mut st = runner::KernelState::default(); + for l in 0..v0s.len() { + st.vgpr[l][0] = v0s[l]; + st.vgpr[l][1] = v1s[l]; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run sgpr med3"); + for l in 0..v0s.len() { + let (a, b) = (v0s[l], v1s[l]); + let want_clamp_i = (a as i32).clamp(0, 255) as u32; + assert_eq!(r.vgpr[l][2], want_clamp_i, "med3_i32(v0, 0, 255) lane {l}"); + assert_eq!(r.vgpr[l][3], want_clamp_i, "med3_i32(v0, 255, 0) lane {l}"); + assert_eq!(r.vgpr[l][4], a.min(255), "med3_u32(v0, 0, 255) lane {l}"); + assert_eq!(r.vgpr[l][5], a.min(b), "med3_u32(v0, 0, v1) lane {l}"); + } + } + } diff --git a/crates/xcl/src/gpu/dxil/module/split.rs b/crates/xcl/src/gpu/dxil/module/split.rs index 7a88b9ae11..dd3fe3e4fd 100644 --- a/crates/xcl/src/gpu/dxil/module/split.rs +++ b/crates/xcl/src/gpu/dxil/module/split.rs @@ -271,7 +271,12 @@ impl Shader { // a refused piece leaves the whole program unsplit: say so let refused = |e: String| crate::xlog_warn!("compute split: piece {} of {} refused, the program stays whole: {}", stage + 1, plan.blocks.len(), e.lines().next().unwrap_or_default()); - let blob = dst.try_finish(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; + if !dst.m.terminated() { + dst.m.ret(); + } + dst.m.optimize(); + dst.prune_unused_bindings(); + let blob = dst.finish_optimized(threads, Some(32)).map_err(|e| refused(e.to_string())).ok()?; crate::gpu::dxil::validate::validate(&blob).map_err(refused).ok()?; Some(blob) } @@ -711,10 +716,33 @@ impl Module { #[cfg(test)] mod tests { use crate::gpu::{ - dxil::{kernel::{Entry, KernelOptions}, lower::Lw, module::{BinOp, CastOp, Pred}}, + dxil::{ + container::Stage, + kernel::{Entry, KernelOptions}, + lower::Lw, + module::{BinOp, CastOp, Pred}, + shader::{ResClass, Shader}, + }, recomp::{runner, CsInterface}, }; + #[test] + fn optimized_piece_prunes_only_unreferenced_static_bindings() { + let mut shader = Shader::new(Stage::Compute, (6, 6)); + let used = shader.raw_uav(2, 0); + let _unused = shader.cbv(7, 1, 16); + let zero = shader.m.i32c(0); + shader.raw_store(used, zero, &[zero]); + shader.m.ret(); + shader.m.optimize(); + + shader.prune_unused_bindings(); + + assert_eq!(shader.bindings.len(), 1); + assert_eq!(shader.bindings[0].class, ResClass::Uav); + assert_eq!((shader.bindings[0].space, shader.bindings[0].lower), (0, 2)); + } + #[test] fn oversized_loop_occupies_one_piece_up_to_the_hard_ceiling() { use super::{Block, Module}; @@ -844,6 +872,13 @@ mod tests { crate::gpu::dxil::validate::validate(&whole).expect("valid unsplit fixture"); let chain = chain.expect("split the synthetic program"); assert!(chain.pieces.len() >= 3); + let has_memory_binding: Vec<_> = chain.pieces.iter().map(|piece| { + crate::gpu::dxil::validate::disassemble(piece).unwrap() + .contains("ResBind { i32 0, i32 0, i32 0, i8 1 }") + }).collect(); + assert!(has_memory_binding.iter().any(|&present| present)); + assert!(has_memory_binding.iter().any(|&present| !present), + "pieces that only transport scratch must omit the title-memory binding"); let initial: Vec<_> = (1..=threads * 3).collect(); let expected: Vec<_> = initial.iter().enumerate().map(|(i, &v)| { let n = (i as u32 % 4) + 1; diff --git a/crates/xcl/src/gpu/dxil/prelude.rs b/crates/xcl/src/gpu/dxil/prelude.rs index 7a5e5b65c4..33369da2d2 100644 --- a/crates/xcl/src/gpu/dxil/prelude.rs +++ b/crates/xcl/src/gpu/dxil/prelude.rs @@ -78,42 +78,28 @@ impl Lw { let k = self.s.m.f32c(0x3F7F_FFFF); self.sel(ge, k, r) } - /// HLSL `frexp` as DXC lowers it: (mantissa, exponent as float). - fn frexp_dxc(&mut self, x: Value) -> (Value, Value) { - let i = self.bits(x); - let e = self.andc(i, 0x7F80_0000); - let mant = self.andc(i, 0x007F_FFFF); // DXC drops the sign - let e = self.addc(e, (-0x3F00_0000i32) as u32); - let e = self.ashrc(e, 23); - let mant = self.orc(mant, 0x3F00_0000); - let z = self.fc(0.0); - let nz = self.fcmp(Pred::FUNe, x, z); - let ef = self.sitof(e); - let ef = self.sel(nz, ef, z); - let mf = self.f(mant); - let mf = self.sel(nz, mf, z); - (mf, ef) - } - /// The ISA's mantissa keeps the input's sign (as `frexp_mant_d` does); DXC's `frexp` drops it. + /// The ISA's mantissa keeps the input's sign (as `frexp_mant_d` does); 0 / FTZ subnormal / Inf / NaN pass through. pub fn frexp_mant(&mut self, x: Value) -> Value { - let (m, _) = self.frexp_dxc(x); - let mb = self.bits(m); - let xb = self.bits(x); - let sign = self.andc(xb, 0x8000_0000); - let mb = self.or(mb, sign); - let m = self.f(mb); - let a = self.isinf(x); - let b = self.isnan(x); - let s = self.lor(a, b); - self.sel(s, x, m) + let i = self.bits(x); + let e_raw = self.andc(i, 0x7F80_0000); + let zero = self.cmpc(Pred::Eq, e_raw, 0); + let special = self.cmpc(Pred::Eq, e_raw, 0x7F80_0000); + let sign = self.andc(i, 0x8000_0000); + let norm = self.andc(i, 0x807F_FFFF); + let norm = self.orc(norm, 0x3F00_0000); + let mb = self.sel(zero, sign, norm); + let mb = self.sel(special, i, mb); + self.f(mb) } pub fn frexp_exp(&mut self, x: Value) -> Value { - let (_, e) = self.frexp_dxc(x); - let a = self.isinf(x); - let b = self.isnan(x); - let s = self.lor(a, b); - let ei = self.ftosi(e); - self.selc(s, 0, ei) + let i = self.bits(x); + let e_raw = self.andc(i, 0x7F80_0000); + let e = self.addc(e_raw, (-0x3F00_0000i32) as u32); + let e = self.ashrc(e, 23); + let zero = self.cmpc(Pred::Eq, e_raw, 0); + let special = self.cmpc(Pred::Eq, e_raw, 0x7F80_0000); + let zero_or_special = self.lor(zero, special); + self.selc(zero_or_special, 0, e) } pub fn frexp_exp_f32(&mut self, bits: Value, legacy_src: impl FnOnce(&mut Self) -> Value) -> Value { use super::lower_round::{F32_DENORM_INPUT_WRITTEN, VAR_F32_MODE}; @@ -302,15 +288,22 @@ impl Lw { self.ashrc(s, 8) } pub fn alignbit(&mut self, s0: Value, s1: Value, s: Value) -> Value { - let s = self.andc(s, 31); - let a = self.bin(BinOp::LShr, s1, s); - let k = self.c(32); - let t = self.sub(k, s); - let t = self.andc(t, 31); - let b = self.bin(BinOp::Shl, s0, t); - let r = self.or(a, b); - let z = self.cmpc(Pred::Eq, s, 0); - self.sel(z, s1, r) + if let Some(k) = self.s.m.const_u64(s) { + let sh = (k as u32) & 31; + if sh == 0 { + return s1; + } + let lo = self.lshrc(s1, sh); + let hi = self.shlc(s0, 32 - sh); + return self.or(hi, lo); + } + let sh = self.andc(s, 31); + let lo = self.bin(BinOp::LShr, s1, sh); + let k31 = self.c(31); + let inv = self.xor(sh, k31); + let s0_1 = self.shlc(s0, 1); + let hi = self.bin(BinOp::Shl, s0_1, inv); + self.or(hi, lo) } pub fn perm_b32(&mut self, s0: Value, s1: Value, sel: Value) -> Value { let mut r = self.c(0); @@ -927,4 +920,142 @@ mod fclass_const_tests { } } } + + #[test] + fn gpu_direct_frexp_avoids_special_float_and_int_float_roundtrip() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = Vec::new(); + code.extend(encode("V_FREXP_MANT_F32", "ENC_VOP1", &[("VDST", 1), ("SRC0", 256)], None).unwrap()); + code.extend(encode("V_FREXP_EXP_I32_F32", "ENC_VOP1", &[("VDST", 2), ("SRC0", 256)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let dxil = translate(&code, ko).expect("translate frexp"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("validate frexp"); + let dis = validate::disassemble(&dxil).expect("disassemble frexp"); + assert!(!dis.contains("@dx.op.isSpecialFloat"), "unexpected isSpecialFloat:\n{dis}"); + assert!(!dis.contains("sitofp "), "unexpected sitofp:\n{dis}"); + assert!(!dis.contains("fptosi "), "unexpected fptosi:\n{dis}"); + assert!(!dis.contains("fcmp oeq"), "unexpected float zero-compare (driver FTZ dependent):\n{dis}"); + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32"); + return; + } + // (bits, expected_mant, expected_exp) under D3D12 FTZ; ±subnormal -> (±0.0, 0). + const CASES: [(u32, u32, i32); 12] = [ + (0x0000_0000, 0x0000_0000, 0), // +0.0 + (0x8000_0000, 0x8000_0000, 0), // -0.0 + (0x0000_0001, 0x0000_0000, 0), // +subnormal (FTZ) + (0x8040_0000, 0x8000_0000, 0), // -subnormal (FTZ) + (0x0080_0000, 0x3F00_0000, -125), // +min normal + (0xBF80_0000, 0xBF00_0000, 1), // -1.0 + (0x4060_0000, 0x3F60_0000, 2), // +3.5 + (0xC122_0000, 0xBF22_0000, 4), // -10.125 + (0x7F80_0000, 0x7F80_0000, 0), // +Inf + (0xFF80_0000, 0xFF80_0000, 0), // -Inf + (0x7F80_0001, 0x7F80_0001, 0), // +sNaN + (0xFFC0_1234, 0xFFC0_1234, 0), // -qNaN + ]; + let mut st = KernelState::default(); + for (lane, &(bits, _, _)) in CASES.iter().enumerate() { + st.vgpr[lane][0] = bits; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run frexp"); + for (lane, &(bits, want_m, want_e)) in CASES.iter().enumerate() { + assert_eq!(r.vgpr[lane][1], want_m, "frexp_mant lane {lane} bits={bits:#010x}"); + assert_eq!(r.vgpr[lane][2] as i32, want_e, "frexp_exp lane {lane} bits={bits:#010x}"); + } + } + + #[test] + fn gpu_direct_frexp_f16_avoids_special_float_and_matches_isa() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = Vec::new(); + code.extend(encode("V_FREXP_MANT_F16", "ENC_VOP1", &[("VDST", 1), ("SRC0", 256)], None).unwrap()); + code.extend(encode("V_FREXP_EXP_I16_F16", "ENC_VOP1", &[("VDST", 2), ("SRC0", 256)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let dxil = translate(&code, ko).expect("translate frexp_f16"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("validate frexp_f16"); + let dis = validate::disassemble(&dxil).expect("disassemble frexp_f16"); + assert!(!dis.contains("@dx.op.isSpecialFloat"), "unexpected isSpecialFloat in f16:\n{dis}"); + assert!(!dis.contains("sitofp "), "unexpected sitofp in f16:\n{dis}"); + assert!(!dis.contains("fptosi "), "unexpected fptosi in f16:\n{dis}"); + assert!(!dis.contains("fcmp oeq"), "unexpected float zero-compare in f16:\n{dis}"); + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32"); + return; + } + // (f16_bits, expected_mant_f16 (None = NaN), expected_exp_i16) + const CASES: [(u16, Option, i16); 11] = [ + (0x0000, Some(0x0000), 0), // +0.0 + (0x8000, Some(0x8000), 0), // -0.0 + (0x0001, Some(0x3800), -23), // +min subnormal (2^-24 = 0.5 * 2^-23) + (0x8200, Some(0xB800), -14), // -subnormal (-2^-15 = -0.5 * 2^-14) + (0xBC00, Some(0xB800), 1), // -1.0 -> (-0.5, 1) + (0xC910, Some(0xB910), 4), // -10.125 -> (-0.6328125, 4) + (0x4200, Some(0x3A00), 2), // +3.0 -> (0.75, 2) + (0x7C00, Some(0x7C00), 0), // +Inf + (0xFC00, Some(0xFC00), 0), // -Inf + (0x7E00, None, 0), // +qNaN + (0xFE01, None, 0), // -qNaN + ]; + let mut st = KernelState::default(); + for (lane, &(bits, _, _)) in CASES.iter().enumerate() { + st.vgpr[lane][0] = bits as u32; + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run frexp_f16"); + for (lane, &(bits, want_m, want_e)) in CASES.iter().enumerate() { + let got_m = (r.vgpr[lane][1] & 0xFFFF) as u16; + let got_e = (r.vgpr[lane][2] & 0xFFFF) as i16; + match want_m { + Some(m) => assert_eq!(got_m, m, "frexp_mant_f16 lane {lane} bits={bits:#06x}"), + None => assert!((got_m & 0x7C00) == 0x7C00 && (got_m & 0x03FF) != 0, "frexp_mant_f16 NaN lane {lane} bits={bits:#06x} got={got_m:#06x}"), + } + assert_eq!(got_e, want_e, "frexp_exp_i16_f16 lane {lane} bits={bits:#06x}"); + } + } + + #[test] + fn gpu_direct_alignbit_is_select_free_and_matches_isa() { + let ko = KernelOptions { wave64: false, split: false, mem_windows: 1, sampler_base: 0 }; + let mut code = Vec::new(); + code.extend(encode("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 3), ("SRC0", 256), ("SRC1", 257), ("SRC2", 258)], None).unwrap()); + for (i, sh) in [0u64, 1, 13, 31, 32].into_iter().enumerate() { + code.extend(encode("V_ALIGNBIT_B32", "ENC_VOP3", &[("VDST", 4 + i as u64), ("SRC0", 256), ("SRC1", 257), ("SRC2", 128 + sh)], None).unwrap()); + } + code.extend(encode("V_ALIGNBYTE_B32", "ENC_VOP3", &[("VDST", 9), ("SRC0", 256), ("SRC1", 257), ("SRC2", 258)], None).unwrap()); + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + let dxil = translate(&code, ko).expect("translate alignbit"); + if crate::gpu::recomp::dxc::create_instance().is_some() { + validate::validate(&dxil).expect("validate alignbit"); + let dis = validate::disassemble(&dxil).expect("disassemble alignbit"); + assert_eq!(dis.matches(" = select i1 ").count(), 7, "only the 7 EXEC-mask VGPR writes may use select:\n{dis}"); + assert_eq!(dis.matches("icmp eq i32 ").count(), 1, "only the lane-0 epilogue guard may use icmp eq:\n{dis}"); + assert!(!dis.contains("sub i32 32,"), "unexpected sub-32 shift workaround:\n{dis}"); + } + if runner::wave32_supported() != Ok(true) { + runner::skip_test("no wave32"); + return; + } + let ref_ab = |s0: u32, s1: u32, s: u32| ((((s0 as u64) << 32) | (s1 as u64)) >> (s & 31)) as u32; + for base in [0u32, 32, 0xFFFF_FFE0] { + let mut st = KernelState::default(); + for lane in 0..32usize { + st.vgpr[lane][0] = 0xA5C3_1E79u32.wrapping_add((lane as u32).wrapping_mul(0x0101_0101)); + st.vgpr[lane][1] = 0x1234_5678u32.wrapping_add((lane as u32).wrapping_mul(0x1020_3040)); + st.vgpr[lane][2] = base.wrapping_add(lane as u32); + } + let r = runner::run(&dxil, &st, &[]).expect("GPU run alignbit"); + for lane in 0..32usize { + let (s0, s1, s) = (st.vgpr[lane][0], st.vgpr[lane][1], st.vgpr[lane][2]); + assert_eq!(r.vgpr[lane][3], ref_ab(s0, s1, s), "dyn alignbit base={base:#x} lane={lane} s={s:#x}"); + for (i, sh) in [0u32, 1, 13, 31, 32].into_iter().enumerate() { + assert_eq!(r.vgpr[lane][4 + i], ref_ab(s0, s1, sh), "const alignbit sh={sh} lane={lane}"); + } + assert_eq!(r.vgpr[lane][9], ref_ab(s0, s1, (s & 3) * 8), "alignbyte base={base:#x} lane={lane} s={s:#x}"); + } + } + } } diff --git a/crates/xcl/src/gpu/dxil/robustness_tests.rs b/crates/xcl/src/gpu/dxil/robustness_tests.rs index 46a06c63d4..9bd172ef70 100644 --- a/crates/xcl/src/gpu/dxil/robustness_tests.rs +++ b/crates/xcl/src/gpu/dxil/robustness_tests.rs @@ -87,12 +87,43 @@ fn translation_is_byte_identical_across_runs_and_threads() { for _ in 0..3 { assert!(translate_all() == first, "a second translation differs"); } - let threads: Vec<_> = (0..4).map(|_| std::thread::Builder::new().stack_size(64 << 20).spawn(translate_all).unwrap()).collect(); + // Every translate already runs on its own 256 MiB-stack worker. Keep genuine concurrent + // translator coverage without adding four redundant 64 MiB outer stacks or crowding the + // other direct-DXIL tests which the harness runs in parallel. + let threads: Vec<_> = (0..2).map(|_| std::thread::spawn(translate_all)).collect(); for t in threads { assert!(t.join().unwrap() == first, "a translation on another thread differs"); } } +/// A group barrier in a compute group of several hardware waves is not translated here: the +/// plain barrier waits for waves that have left (the GPU hangs on NVIDIA), and only the HLSL +/// path has the barrier that counts the waves still there. +#[test] +fn a_group_barrier_of_several_hardware_waves_is_left_to_the_hlsl_path() { + let code = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); + let o = |wave64, split| KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let cs = |threads| CsInterface { threads, user_sgprs: 4, tgid: [true, false, false], tg_size: false, tid_components: 1 }; + // 16 x 16 threads: 8 hardware waves in the split form, 4 native 64-lane ones, 8 of a + // 32-lane program; and the two 32-lane halves of one console wave + for (wave64, split, threads) in [(true, true, [16, 16, 1]), (true, false, [16, 16, 1]), (false, false, [16, 16, 1]), (true, true, [64, 1, 1]), (false, false, [64, 1, 1])] { + let e = kernel::translate_compute(&code, o(wave64, split), &cs(threads)).err().unwrap_or_else(|| panic!("translated: wave64 {wave64}, split {split}, {threads:?}")); + assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); + } + // one hardware wave has nobody to wait for: translated as before + kernel::translate_compute(&code, o(true, false), &cs([64, 1, 1])).expect("one 64-lane wave"); + kernel::translate_compute(&code, o(false, false), &cs([32, 1, 1])).expect("one 32-lane wave"); + // (the kernel form of the tests is no thread group of a title's: its barrier stays) + kernel::translate(&code, o(true, true)).expect("kernel"); + // a mesh program's compute pass: two console waves a group, as a retail title's + let ms = |threads| crate::gpu::recomp::MsInterface { outputs: vec![el("SV_Position", 0, 1, 3, 0, 0xF)], threads, max_vertices: 64, max_primitives: 64 }; + for split in [true, false] { + let e = kernel::translate_mesh(&code, o(true, split), &ms(128)).err().unwrap_or_else(|| panic!("a mesh pass translated (split {split})")); + assert!(e.contains("s_barrier in a group of several hardware waves"), "{e}"); + } + kernel::translate_mesh(&code, o(true, false), &ms(64)).expect("a mesh pass of one 64-lane wave"); +} + // ---- builder misuse: recorded as the first error, finish fails instead of panicking use super::container::Stage; diff --git a/crates/xcl/src/gpu/dxil/select_tests.rs b/crates/xcl/src/gpu/dxil/select_tests.rs new file mode 100644 index 0000000000..2d9c1d3663 --- /dev/null +++ b/crates/xcl/src/gpu/dxil/select_tests.rs @@ -0,0 +1,95 @@ +//! GPU equivalence for the guarded-select fold, including inactive lanes. + +use super::kernel::{translate, KernelOptions}; +use super::module::NO_SELECT_FOLD; +use crate::gpu::rdna2::encode; +use crate::gpu::recomp::runner::{self, KernelState}; + +const V: u64 = 256; + +fn program(list: &[(&str, &str, &[(&str, u64)])]) -> Vec { + let mut code = Vec::new(); + for (name, encoding, fields) in list { + code.extend(encode(name, encoding, fields, None).unwrap_or_else(|e| panic!("{name}: {e}"))); + } + code.extend(encode("S_ENDPGM", "ENC_SOPP", &[], None).unwrap()); + code +} + +fn translate_with_fold(code: &[u8], options: KernelOptions, enabled: bool) -> Vec { + NO_SELECT_FOLD.with(|c| c.set(!enabled)); + let result = translate(code, options); + NO_SELECT_FOLD.with(|c| c.set(false)); + result.unwrap_or_else(|e| panic!("translate (select fold {enabled}): {e}")) +} + +#[test] +fn gpu_guarded_select_fold_preserves_inactive_lanes() { + match (runner::adapter(), runner::wave64_programs_supported()) { + (Ok(_), Ok(true)) => {} + (adapter, _) => return runner::skip_test(if adapter.is_err() { "no GPU" } else { "no wave64" }), + } + let code = program(&[ + ("S_AND_SAVEEXEC_B64", "ENC_SOP1", &[("SDST", 10), ("SSRC0", 0)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V), ("VSRC1", 1)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 2)]), + ("V_FMA_F32", "ENC_VOP3", &[("VDST", 5), ("SRC0", V + 4), ("SRC1", V + 3), ("SRC2", V + 4)]), + ("V_MUL_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 5), ("VSRC1", 4)]), + ("V_CMP_GT_F32", "ENC_VOPC", &[("SRC0", V + 4), ("VSRC1", 5)]), + ("V_CNDMASK_B32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 4), ("VSRC1", 5)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 20), ("SRC0", V + 4), ("SRC1", 131)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 21), ("SRC0", V + 6), ("SRC1", 137)]), + ("S_AND_B64", "ENC_SOP2", &[("SDST", 126), ("SSRC0", 126), ("SSRC1", 2)]), + ("V_SUB_F32", "ENC_VOP2", &[("VDST", 4), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MAX_F32", "ENC_VOP2", &[("VDST", 7), ("SRC0", V + 4), ("VSRC1", 0)]), + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 8), ("SRC0", V + 4)]), + ("V_MOV_B32", "VOP1_VOP_DPP16", &[("VDST", 9), ("SRC0", 0xFA), ("VSRC0", 4), ("DPP_CTRL", 0x111), ("ROW_MASK", 0xF), ("BANK_MASK", 0xF)]), + ("V_READLANE_B32", "ENC_VOP3", &[("VDST", 22), ("SRC0", V + 4), ("SRC1", 133)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 6), ("SRC0", V + 6), ("VSRC1", 6)]), + ("S_MOV_B64", "ENC_SOP1", &[("SDST", 126), ("SSRC0", 10)]), + ("V_ADD_F32", "ENC_VOP2", &[("VDST", 10), ("SRC0", V + 4), ("VSRC1", 6)]), + ("V_MUL_LEGACY_F32", "ENC_VOP2", &[("VDST", 11), ("SRC0", V + 7), ("VSRC1", 8)]), + ]); + const EDGE: [u32; 12] = [0x7FC0_1234, 0, 0x8000_0000, 0x7F80_0000, 0xFF80_0000, 1, 0x807F_FFFF, 0x3FC0_0000, 0xC000_0000, 0x3F80_0000, 0x4120_0000, 0xBE80_0000]; + let mut state = KernelState::default(); + let mut random = 0x9E37_79B9_7F4A_7C15u64; + for (lane, regs) in state.vgpr.iter_mut().enumerate() { + for word in regs.iter_mut().take(4) { + random ^= random << 13; + random ^= random >> 7; + random ^= random << 17; + *word = if random % 3 == 0 { random as u32 } else { EDGE[(random >> 8) as usize % EDGE.len()] }; + } + for (reg, word) in regs.iter_mut().enumerate().skip(4).take(8) { + *word = 0xA000_0000 | (lane as u32) << 8 | reg as u32; + } + } + (state.sgpr[0], state.sgpr[1]) = (0xF0F0_5A3C, 0x0FF0_C3A5); + (state.sgpr[2], state.sgpr[3]) = (0x3333_FF0F, 0xFFFF_3333); + + let mut ran = 0; + for (wave64, split) in [(false, false), (true, true), (true, false)] { + if wave64 && !split && runner::wave64_supported() != Ok(true) { + continue; + } + let options = KernelOptions { wave64, split, mem_windows: 1, sampler_base: 0 }; + let (before, after) = (translate_with_fold(&code, options, false), translate_with_fold(&code, options, true)); + assert!(after.len() < before.len(), "wave64 {wave64} split {split}: nothing folded ({} -> {} B)", before.len(), after.len()); + let a = runner::run(&before, &state, &[]).expect("GPU run before fold"); + let b = runner::run(&after, &state, &[]).expect("GPU run after fold"); + let lanes = if wave64 { 64 } else { 32 }; + for lane in 0..lanes { + assert_eq!(a.vgpr[lane][..12], b.vgpr[lane][..12], "wave64 {wave64} split {split}: lane {lane}"); + let active = (state.sgpr[lane / 32] >> (lane % 32)) & 1 != 0; + if !active { + for reg in [4, 5, 7, 8] { + assert_eq!(b.vgpr[lane][reg], state.vgpr[lane][reg], "wave64 {wave64} split {split}: inactive lane {lane} v{reg}"); + } + } + } + assert_eq!(a.sgpr, b.sgpr, "wave64 {wave64} split {split}: SGPRs"); + assert_eq!(a.scc, b.scc, "wave64 {wave64} split {split}: SCC"); + ran += 1; + } + assert!(ran >= 2); +} diff --git a/crates/xcl/src/gpu/dxil/shader.rs b/crates/xcl/src/gpu/dxil/shader.rs index a0a970925d..b72e1066e6 100644 --- a/crates/xcl/src/gpu/dxil/shader.rs +++ b/crates/xcl/src/gpu/dxil/shader.rs @@ -518,6 +518,17 @@ impl Shader { } } + /// Drop static binding metadata that this optimized shader cannot reach. + /// Dynamic binding descriptors conservatively keep the complete table. + pub(super) fn prune_unused_bindings(&mut self) { + let Some(refs) = self.m.referenced_bindings() else { return }; + self.bindings.retain(|binding| refs.iter().any(|&(class, space, lower, upper)| { + class == binding.class as u8 + && space == binding.space + && (lower..=upper).contains(&binding.lower) + })); + } + /// Writes metadata, bitcode and the signed container (panics on a builder error: tests; /// translators use [`Shader::try_finish`]). pub fn finish(self, numthreads: [u32; 3], wave_size: Option) -> Vec { diff --git a/crates/xcl/src/gpu/effects.rs b/crates/xcl/src/gpu/effects.rs index 4fe79eb859..b76be2aaa9 100644 --- a/crates/xcl/src/gpu/effects.rs +++ b/crates/xcl/src/gpu/effects.rs @@ -21,16 +21,73 @@ pub struct Effects { pub instructions: usize, } -/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it). -/// None when the program cannot be decoded through a terminator, falls through past decoded -/// code, contains an unresolved indirect transfer, or branches outside the decoded instructions. -pub fn of(code: &[u8]) -> Option { - let mut insts = Vec::new(); +fn update_writes(e: &mut Effects, d: &rdna2::Decoded) { + let n = d.inst.name; + let writes = n.contains("_STORE") || n.contains("_ATOMIC"); + match d.enc.name { + "ENC_MIMG" => e.images |= writes, + "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, + // LDS is the group's own and gone after it; the global data share is not + "ENC_DS" => { + let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0); + e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_"); + } + _ => {} + } +} + +fn analyze(code: &[u8], stop_on_memory: bool) -> Option { + let cap = if stop_on_memory { (code.len() / 6).min(256) } else { code.len() / 6 }; + let mut pcs = Vec::with_capacity(cap); + let mut targets = Vec::new(); let mut off = 0; // the whole program: code can follow an early terminator (a branch to it, or past it); what // does not decode (or S_CODE_END padding) after one is taken for trailing data, unless a // decoded branch still targets past it or the tail falls through into it let mut ended = false; + let mut last_ok_end = false; + let mut e = Effects::default(); + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { + if ended { + break; + } + return None; + }; + if ended && d.inst.name == "S_CODE_END" { + break; + } + if d.inst.name == "S_SETPC_B64" { + return analyze_with_far_jumps(code, stop_on_memory); + } + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 { + targets.push(rdna2::branch_target(&d)?); + } + off += d.len; + let term = d.inst.flags & rdna2::F_TERMINATOR != 0; + ended |= term; + last_ok_end = term || d.inst.name == "S_BRANCH"; + e.instructions += 1; + update_writes(&mut e, &d); + if stop_on_memory && e.memory { + return None; + } + pcs.push(d.pc); + } + if !ended || !last_ok_end || !targets.iter().all(|t| pcs.binary_search(t).is_ok()) { + return None; + } + Some(e) +} + +fn analyze_with_far_jumps(code: &[u8], stop_on_memory: bool) -> Option { + // Keep early memory-writer rejection cheap even when an initial SETPC selects this slower + // path; grow only if analysis actually has to retain the rest of a large shader. + let cap = if stop_on_memory { (code.len() / 6).min(256) } else { code.len() / 6 }; + let mut insts = Vec::with_capacity(cap); + let mut off = 0; + let mut ended = false; + let mut e = Effects::default(); while off + 4 <= code.len() { let Ok(d) = rdna2::decode(&code[off..], off as u64) else { if ended { @@ -43,6 +100,11 @@ pub fn of(code: &[u8]) -> Option { } off += d.len; ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; + e.instructions += 1; + update_writes(&mut e, &d); + if stop_on_memory && e.memory { + return None; + } insts.push(d); } if !ended { @@ -53,42 +115,25 @@ pub fn of(code: &[u8]) -> Option { if last.inst.flags & rdna2::F_TERMINATOR == 0 && last.inst.name != "S_BRANCH" && last.far_target.is_none() { return None; } - let pcs: std::collections::HashSet = insts.iter().map(|d| d.pc).collect(); - let mut e = Effects::default(); for d in &insts { - if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 && rdna2::branch_target(d).is_none_or(|t| !pcs.contains(&t)) { + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 + && rdna2::branch_target(d).is_none_or(|t| insts.binary_search_by_key(&t, |x| x.pc).is_err()) + { return None; } - e.instructions += 1; - let n = d.inst.name; - let writes = n.contains("_STORE") || n.contains("_ATOMIC"); - match d.enc.name { - "ENC_MIMG" => e.images |= writes, - "ENC_MUBUF" | "ENC_MTBUF" | "ENC_FLAT" | "ENC_FLAT_GLBL" | "ENC_FLAT_SCRATCH" | "ENC_SMEM" => e.memory |= writes, - // LDS is the group's own and gone after it; the global data share is not - "ENC_DS" => { - let gds = rdna2::field_value(d.enc, &d.words, "GDS").is_some_and(|v| v != 0); - e.memory |= gds || n == "DS_APPEND" || n == "DS_CONSUME" || n == "DS_ORDERED_COUNT" || n.starts_with("DS_GWS_"); - } - _ => {} - } } Some(e) } -/// The compute program of a console shader container (the hardware CS variant of an FSSM, or -/// an FSPX driver container), as the translators take it. -fn compute_code(blob: &[u8]) -> Option> { - if let Some(f) = recomp::pso::fspx(blob) { - return Some(f.code.to_vec()); - } - let sh = xbox::parse(blob)?; - let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; - if f.error.is_some() { - return None; - } - let p = f.programs.first()?; - Some(f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec()) +/// The writes of the RDNA2 program `code` (one program, as `xbox::Fssm::programs` cuts it). +/// None when the program cannot be decoded through a terminator, falls through past decoded +/// code, contains an unresolved indirect transfer, or branches outside the decoded instructions. +pub fn of(code: &[u8]) -> Option { + analyze(code, false) +} + +fn is_big_image_only_code(code: &[u8]) -> bool { + code.len() >= BIG_CODE && analyze(code, true).is_some() } /// Console code a compute program needs to be `big`: 16 KiB, about 4 000 instructions. The @@ -100,8 +145,17 @@ pub const BIG_CODE: usize = 16 << 10; /// title can do without for the frames its pipeline takes to build. False for anything that /// cannot be read. pub fn big_and_image_only(blob: &[u8]) -> bool { - let Some(code) = compute_code(blob) else { return false }; - code.len() >= BIG_CODE && of(&code).is_some_and(|e| !e.memory) + if let Some(f) = recomp::pso::fspx(blob) { + return is_big_image_only_code(f.code); + } + let Some(sh) = xbox::parse(blob) else { return false }; + let Some(f) = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)) else { return false }; + if f.error.is_some() { + return false; + } + let Some(p) = f.programs.first() else { return false }; + let Some(end) = p.offset.checked_add(p.len) else { return false }; + f.data.get(p.offset..end).is_some_and(is_big_image_only_code) } #[cfg(test)] @@ -255,4 +309,113 @@ mod tests { assert!(sh.fssm[0].error.is_some() && !sh.fssm[0].programs.is_empty()); assert!(!big_and_image_only(&errored)); } + + fn of_reference(code: &[u8]) -> Option { + let (mut insts, mut off, mut ended) = (Vec::new(), 0, false); + while off + 4 <= code.len() { + let Ok(d) = rdna2::decode(&code[off..], off as u64) else { if ended { break; } return None; }; + if ended && d.inst.name == "S_CODE_END" { break; } + off += d.len; ended |= d.inst.flags & rdna2::F_TERMINATOR != 0; insts.push(d); + } + if !ended { return None; } + rdna2::resolve_far_jumps(&mut insts); + let last = insts.last()?; + if last.inst.flags & rdna2::F_TERMINATOR == 0 && last.inst.name != "S_BRANCH" && last.far_target.is_none() { return None; } + let pcs: std::collections::HashSet = insts.iter().map(|d| d.pc).collect(); + let mut e = Effects::default(); + for d in &insts { + if d.inst.flags & (rdna2::F_BRANCH | rdna2::F_INDIRECT) != 0 && rdna2::branch_target(d).is_none_or(|t| !pcs.contains(&t)) { return None; } + e.instructions += 1; update_writes(&mut e, d); + } + Some(e) + } + + fn fspx_blob(code: &[u8]) -> Vec { + let mut head = [0u8; 0x20]; + for o in [0x0C, 0x0E, 0x10] { head[o..o + 2].copy_from_slice(&1u16.to_le_bytes()); } + let mut accc = [b"FSPX".as_slice(), &[0; 4], &2u32.to_le_bytes(), &[0; 4]].concat(); + for w in [0u32, 0x30, 0x20, 0, 6, 0x50, (0x24 + code.len()) as u32, 0] { accc.extend_from_slice(&w.to_le_bytes()); } + accc.extend_from_slice(&head); accc.extend_from_slice(&[0u8; 0x24]); accc.extend_from_slice(code); + let mut out = [b"DXBC".as_slice(), &[0; 16]].concat(); + for w in [1u32, (44 + accc.len()) as u32, 1, 36] { out.extend_from_slice(&w.to_le_bytes()); } + out.extend_from_slice(b"ACCC"); out.extend_from_slice(&(accc.len() as u32).to_le_bytes()); out.extend_from_slice(&accc); + out + } + + #[test] + fn streaming_matches_reference_of_across_edge_cases() { + let store: (&str, &str, &[(&str, u64)]) = ("BUFFER_STORE_DWORD", "ENC_MUBUF", &[("VDATA", 1), ("SRSRC", 2)]); + let setpc: (&str, &str, &[(&str, u64)]) = ("S_SETPC_B64", "ENC_SOP1", &[("SSRC0", 0)]); + let swappc: (&str, &str, &[(&str, u64)]) = ("S_SWAPPC_B64", "ENC_SOP1", &[("SDST", 2), ("SSRC0", 0)]); + let call_ok: (&str, &str, &[(&str, u64)]) = ("S_CALL_B64", "ENC_SOPK", &[("SDST", 0), ("SIMM16", 0)]); + let code_end: (&str, &str, &[(&str, u64)]) = ("S_CODE_END", "ENC_SOPP", &[]); + let oob_br: (&str, &str, &[(&str, u64)]) = ("S_BRANCH", "ENC_SOPP", &[("SIMM16", 9)]); + let getpc: (&str, &str, &[(&str, u64)]) = ("S_GETPC_B64", "ENC_SOP1", &[("SDST", 0)]); + let add16: (&str, &str, &[(&str, u64)]) = ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 16)]); + let addc0: (&str, &str, &[(&str, u64)]) = ("S_ADDC_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)]); + let mut cases = vec![ + Vec::new(), + [asm(&[store]), vec![0xff; 8]].concat(), + asm(&[store, oob_br, END]), + asm(&[store, END, code_end]), + asm(&[IMAGE_STORE, END, store, END]), + asm(&[getpc, add16, addc0, setpc, END, IMAGE_STORE, END]), + asm(&[IMAGE_STORE, END, getpc, ("S_SUB_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 16)]), ("S_SUBB_U32", "ENC_SOP2", &[("SDST", 1), ("SSRC0", 1), ("SSRC1", 128)]), setpc]), + asm(&[getpc, ("S_ADD_U32", "ENC_SOP2", &[("SDST", 0), ("SSRC0", 0), ("SSRC1", 128 + 64)]), addc0, setpc, END]), + asm(&[getpc, add16, addc0, setpc, END, store, END]), + asm(&[store, getpc, add16, addc0, setpc, END, IMAGE_STORE, END]), + asm(&[IMAGE_STORE, swappc, END]), + asm(&[IMAGE_STORE, call_ok, END]), + ]; + assert_eq!(of(&cases[6]), Some(Effects { memory: false, images: true, instructions: 6 })); + let pool = [asm(&[MOV]), asm(&[IMAGE_STORE]), asm(&[store]), asm(&[END]), asm(&[code_end]), asm(&[("S_BRANCH", "ENC_SOPP", &[("SIMM16", 0)])]), asm(&[oob_br]), asm(&[setpc])]; + let mut rng = 0x9E37_79B9_7F4A_7C15u64; + for _ in 0..64 { + let mut s = Vec::new(); + for _ in 0..16 { rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17; s.extend_from_slice(&pool[(rng as usize) % pool.len()]); } + cases.push(s); + } + for c in &cases { + let want = of_reference(c); + assert_eq!(of(c), want); + assert_eq!(analyze(c, true).is_some(), want.is_some_and(|e| !e.memory)); + } + + let (mov, small) = (asm(&[MOV]), asm(&[IMAGE_STORE, END])); + assert!(!big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&small, &[(6, 0)])]))); + assert!(!big_and_image_only(&fspx_blob(&small))); + let mut big_img = Vec::with_capacity(BIG_CODE + 16); + while big_img.len() < BIG_CODE { big_img.extend_from_slice(&mov); } + big_img.extend(asm(&[IMAGE_STORE, END])); + let mut big_mem = asm(&[store]); + while big_mem.len() < BIG_CODE { big_mem.extend_from_slice(&mov); } + big_mem.extend(asm(&[END])); + assert!(big_and_image_only(&fspx_blob(&big_img)) && !big_and_image_only(&fspx_blob(&big_mem)) && !big_and_image_only(&fspx_blob(&big_img)[..40])); + assert!(big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&big_img, &[(6, 0)])])) && !big_and_image_only(&xbox::tests::sample(5, &[xbox::tests::fssm(&big_mem, &[(6, 0)])]))); + + if !cfg!(debug_assertions) { + fn bench(iters: u32, mut f: impl FnMut() -> bool) -> (f64, u32) { + let (t0, mut acc) = (std::time::Instant::now(), 0u32); + for _ in 0..iters { acc += u32::from(std::hint::black_box(f())); } + (t0.elapsed().as_micros() as f64 / iters as f64, acc) + } + let (mut img_100k, mut mem_100k) = (Vec::with_capacity(100_016), asm(&[store])); + while img_100k.len() < 100_000 { img_100k.extend_from_slice(&mov); } + img_100k.extend(asm(&[IMAGE_STORE, END])); + while mem_100k.len() < 100_000 { mem_100k.extend_from_slice(&mov); } + mem_100k.extend(asm(&[END])); + let (blob_img, blob_mem) = (xbox::tests::sample(5, &[xbox::tests::fssm(&img_100k, &[(6, 0)])]), xbox::tests::sample(5, &[xbox::tests::fssm(&mem_100k, &[(6, 0)])])); + let ref_big = |blob: &[u8]| { + let sh = xbox::parse(blob)?; + let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; + let p = f.programs.first()?; + let c = f.data.get(p.offset..p.offset.checked_add(p.len)?)?.to_vec(); + Some(c.len() >= BIG_CODE && of_reference(&c).is_some_and(|e| !e.memory)) + }; + let ((ib, a1), (ia, a2)) = (bench(50, || ref_big(&blob_img).unwrap_or(false)), bench(50, || big_and_image_only(&blob_img))); + let ((mb, b1), (ma, b2)) = (bench(50, || ref_big(&blob_mem).unwrap_or(false)), bench(50, || big_and_image_only(&blob_mem))); + assert_eq!((a1, a2, b1, b2), (50, 50, 0, 0)); + println!("EFFECTS_BENCH_US img_100k: before={ib:.1} after={ia:.1} | mem_100k: before={mb:.1} after={ma:.1}"); + } + } } diff --git a/crates/xcl/src/gpu/fence.rs b/crates/xcl/src/gpu/fence.rs index 4d702802c6..37595ffe8e 100644 --- a/crates/xcl/src/gpu/fence.rs +++ b/crates/xcl/src/gpu/fence.rs @@ -73,6 +73,7 @@ pub(crate) unsafe fn wait( } let start = Instant::now(); let mut remaining = timeout_ms; + let wait_stall = crate::stall::span(crate::stall::StallKind::GpuWait); loop { let status = WaitForSingleObject(event, remaining); let error = (status == WAIT_FAILED).then(Error::from_thread); @@ -88,6 +89,7 @@ pub(crate) unsafe fn wait( } let elapsed = start.elapsed().as_millis(); if status == WAIT_TIMEOUT || elapsed >= u128::from(timeout_ms) { + drop(wait_stall); return Err(dev.GetDeviceRemovedReason().err().map_or(FenceError::Timeout(timeout_ms), FenceError::Removed)); } remaining = timeout_ms - elapsed as u32; diff --git a/crates/xcl/src/gpu/recomp/dxc.rs b/crates/xcl/src/gpu/recomp/dxc.rs index 379bd8518f..167bd4413b 100644 --- a/crates/xcl/src/gpu/recomp/dxc.rs +++ b/crates/xcl/src/gpu/recomp/dxc.rs @@ -9,11 +9,11 @@ //! kept for `report.json` ([`toolchain`]). use std::cell::RefCell; -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; use std::ffi::c_void; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Arc, Mutex, OnceLock, Weak}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, Condvar, Mutex, OnceLock, Weak}; use windows::core::{Interface, GUID, HRESULT, PCWSTR}; use windows::Win32::Graphics::Direct3D::Dxc::{ @@ -391,11 +391,106 @@ struct Job { reply: std::sync::mpsc::Sender, String>>, /// one of the title's threads waits for it wanted: Wanted, + /// time from submission until a worker admits this compile under the memory limit + queue_stall: Option>, +} + +struct CompileQueue { + jobs: Mutex>, + changed: Condvar, + workers: AtomicUsize, +} + +impl CompileQueue { + fn new() -> Self { + Self { jobs: Mutex::new(VecDeque::new()), changed: Condvar::new(), workers: AtomicUsize::new(0) } + } + + fn push(&self, job: Job) -> Result<(), Job> { + let mut jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner()); + if self.workers.load(Ordering::Acquire) == 0 { + return Err(job); + } + jobs.push_back(job); + drop(jobs); + self.changed.notify_one(); + Ok(()) + } + + fn take(&self) -> Job { + let mut jobs = self.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = take_next_job(&mut jobs) { + return job; + } + jobs = self.changed.wait(jobs).unwrap_or_else(|e| e.into_inner()); + } + } +} + +struct CompileWorker(Arc); + +impl Drop for CompileWorker { + fn drop(&mut self) { + if self.0.workers.fetch_sub(1, Ordering::AcqRel) == 1 { + self.0.jobs.lock().unwrap_or_else(|e| e.into_inner()).clear(); + } + } +} + +/// Wanted jobs overtake unwanted ones; both classes remain FIFO. +fn take_next_job(jobs: &mut VecDeque) -> Option { + let position = jobs.iter().position(|job| (job.wanted)()).unwrap_or(0); + jobs.remove(position) } /// Whether one of the title's threads waits for a compile (asked again while it is held back). pub type Wanted = Box bool + Send>; +#[cfg(test)] +mod queue_tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + fn job(name: &str, wanted: Wanted) -> Job { + let (reply, _) = std::sync::mpsc::channel(); + Job { + src: name.into(), + entry: String::new(), + profile: String::new(), + extra: Vec::new(), + reply, + wanted, + queue_stall: None, + } + } + + #[test] + fn wanted_dxc_jobs_overtake_background_fifo() { + let mut jobs = VecDeque::from([ + job("background-1", Box::new(|| false)), + job("wanted-1", Box::new(|| true)), + job("wanted-2", Box::new(|| true)), + job("background-2", Box::new(|| false)), + ]); + let order: Vec<_> = (0..4).map(|_| take_next_job(&mut jobs).unwrap().src).collect(); + assert_eq!(order, ["wanted-1", "wanted-2", "background-1", "background-2"]); + } + + #[test] + fn queued_job_is_rechecked_after_foreground_promotion() { + let wanted = Arc::new(AtomicBool::new(false)); + let check = wanted.clone(); + let mut jobs = VecDeque::from([ + job("background", Box::new(|| false)), + job("promoted", Box::new(move || check.load(Ordering::Acquire))), + ]); + wanted.store(true, Ordering::Release); + assert_eq!(take_next_job(&mut jobs).unwrap().src, "promoted"); + assert_eq!(take_next_job(&mut jobs).unwrap().src, "background"); + } +} + /// Compiles the title waits for that go on at once however little commit is left (each takes /// 0.1 – 0.7 GB). const WANTED_AT_ONCE: usize = 6; @@ -424,17 +519,62 @@ pub fn set_memory_reserve(gb: u64) { } /// Compiles running on the DXC workers (`wait_for_memory` lets them in). -static WORKING: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +struct MemoryGate { + gate: Mutex<()>, + working: std::sync::atomic::AtomicUsize, +} + +impl MemoryGate { + const fn new() -> Self { + Self { gate: Mutex::new(()), working: std::sync::atomic::AtomicUsize::new(0) } + } + + /// Evaluates commit headroom and `WANTED_AT_ONCE` atomically with `working` admission so + /// concurrent worker wakeups cannot admit a burst past either cap. + fn try_admit(&self, reserve_bytes: u64, avail: impl FnOnce() -> Option, timed_out: bool, wanted: &Wanted) -> bool { + let _guard = self.gate.lock().unwrap_or_else(|e| e.into_inner()); + let cur = self.working.load(Ordering::Acquire); + let need = reserve_bytes.saturating_add((cur as u64) << 30); + let plenty = avail().is_none_or(|a| a >= need); + if plenty || timed_out || cur == 0 || (cur < WANTED_AT_ONCE && wanted()) { + self.working.fetch_add(1, Ordering::AcqRel); + return true; + } + false + } + + /// Waits until [`Self::try_admit`] grants a slot, sleeping outside the gate mutex. + fn wait_with(&self, reserve_bytes: u64, mut avail: impl FnMut() -> Option, timeout: std::time::Duration, wanted: &Wanted) { + let start = std::time::Instant::now(); + while !self.try_admit(reserve_bytes, &mut avail, start.elapsed() >= timeout, wanted) { + std::thread::sleep(std::time::Duration::from_millis(50)); + } + } + + fn release(&self) { + self.working.fetch_sub(1, Ordering::AcqRel); + } +} + +static MEMORY_GATE: MemoryGate = MemoryGate::new(); /// A compile let in by `wait_for_memory`, until it is dropped. pub struct MemorySlot; impl Drop for MemorySlot { fn drop(&mut self) { - WORKING.fetch_sub(1, std::sync::atomic::Ordering::AcqRel); + MEMORY_GATE.release(); } } +/// Available page-file commit bytes from Windows, or `None` if the query fails. +fn avail_page_file() -> Option { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullAvailPageFile) +} + /// Before a compile: with 6 GB of commit left or more, plus 1 GB for every compile already /// running (each can still grow to ~0.7 GB), at once; with less, one compile at a /// time – it goes when no other is running (and after a minute in any case). Each compile used @@ -444,55 +584,55 @@ impl Drop for MemorySlot { /// of its threads waited for cold compiles, four of which stood in this queue, until its watchdog /// ended it. pub fn wait_for_memory(wanted: &Wanted) -> MemorySlot { - use std::sync::atomic::Ordering; - use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; - let start = std::time::Instant::now(); - loop { - let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; - m.dwLength = std::mem::size_of::() as u32; - let need = (RESERVE_GB.load(Ordering::Relaxed) << 30) + ((WORKING.load(Ordering::Acquire) as u64) << 30); - let plenty = unsafe { GlobalMemoryStatusEx(&mut m) } == 0 || m.ullAvailPageFile >= need; - if plenty || start.elapsed().as_secs() >= 60 || (WORKING.load(Ordering::Acquire) < WANTED_AT_ONCE && wanted()) { - WORKING.fetch_add(1, Ordering::AcqRel); - return MemorySlot; - } - if WORKING.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire).is_ok() { - return MemorySlot; - } - std::thread::sleep(std::time::Duration::from_millis(50)); - } + MEMORY_GATE.wait_with(RESERVE_GB.load(Ordering::Relaxed) << 30, avail_page_file, std::time::Duration::from_secs(60), wanted); + MemorySlot } /// DXC workers (`compile_threads`, each with its own compiler and a `DXC_STACK` stack), started /// on first use; callers wait for their job. -fn pool() -> &'static std::sync::Mutex> { - static POOL: OnceLock>> = OnceLock::new(); +fn pool() -> &'static Arc { + static POOL: OnceLock> = OnceLock::new(); POOL.get_or_init(|| { - let (tx, rx) = std::sync::mpsc::channel::(); - let rx = std::sync::Arc::new(std::sync::Mutex::new(rx)); + let queue = Arc::new(CompileQueue::new()); for k in 0..compile_threads() { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || loop { - let job = match rx.lock().unwrap().recv() { - Ok(j) => j, - Err(_) => return, - }; - let _slot = wait_for_memory(&job.wanted); - let extra: Vec<&str> = job.extra.iter().map(|s| s.as_str()).collect(); - let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| compile_here(&job.src, &job.entry, &job.profile, &extra))) - .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); - let _ = job.reply.send(r); - }); + let worker_queue = queue.clone(); + queue.workers.fetch_add(1, Ordering::Release); + if std::thread::Builder::new().name(format!("xcl-dxc-{k}")).stack_size(DXC_STACK).spawn(move || { + let _worker = CompileWorker(worker_queue.clone()); + loop { + let job = worker_queue.take(); + let Job { src, entry, profile, extra, reply, wanted, queue_stall } = job; + let _slot = wait_for_memory(&wanted); + drop(queue_stall); + let extra: Vec<&str> = extra.iter().map(|s| s.as_str()).collect(); + let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _stall = crate::stall::span(crate::stall::StallKind::DxcCompile); + compile_here(&src, &entry, &profile, &extra) + })) + .unwrap_or_else(|_| Err("DXC: panic in the compile thread".into())); + let _ = reply.send(r); + } + }).is_err() { + queue.workers.fetch_sub(1, Ordering::AcqRel); + } } - std::sync::Mutex::new(tx) + queue }) } /// Compile HLSL to signed DXIL. `profile` e.g. "cs_6_6"; `extra` are dxc arguments. pub fn compile(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { let (reply, rx) = std::sync::mpsc::channel(); - let job = Job { src: src.into(), entry: entry.into(), profile: profile.into(), extra: extra.iter().map(|s| s.to_string()).collect(), reply, wanted: crate::hle::d3d12x::pso_async::wanted_here() }; - pool().lock().unwrap().send(job).map_err(|_| "DXC: no compile threads".to_string())?; + let job = Job { + src: src.into(), + entry: entry.into(), + profile: profile.into(), + extra: extra.iter().map(|s| s.to_string()).collect(), + reply, + wanted: crate::hle::d3d12x::pso_async::wanted_here(), + queue_stall: crate::stall::span(crate::stall::StallKind::DxcQueue), + }; + pool().push(job).map_err(|_| "DXC: no compile threads".to_string())?; rx.recv().map_err(|_| "DXC: the compile thread exited".to_string())? } @@ -505,15 +645,11 @@ fn compile_here(src: &str, entry: &str, profile: &str, extra: &[&str]) -> Result // linear this way (`emit::linked_form`). Anything wrong with it: as one program, as before. if profile.starts_with("cs_") && linking() { if let Some((program, library)) = super::emit::linked_form(src, LINK_MIN_ACCESSES) { - match compile_linked(&program, &library, entry, profile, extra) { - Ok(dxil) => return Ok(dxil), - Err(e) => { - // the same DXC fails the same way for the next program: stop trying - if LINK_GATE.close() { - crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole, and no more programs are linked: {e}"); - } - } - } + return compile_linked_or_fallback( + &LINK_GATE, + || compile_linked(&program, &library, entry, profile, extra), + || compile_whole(src, entry, profile, extra), + ); } } compile_whole(src, entry, profile, extra) @@ -544,6 +680,47 @@ impl LinkGate { static LINK_GATE: LinkGate = LinkGate::new(); +pub(crate) fn is_oom_error(err: &str) -> bool { + let lower = err.to_ascii_lowercase(); + lower.contains("0x8007000e") || lower.contains("e_outofmemory") +} + +/// Try `linked()` while `gate` is open; transient OOM propagates without closing `gate` or +/// falling back to the heavier `whole()`, while deterministic failures close `gate` and retry whole. +fn compile_linked_or_fallback( + gate: &LinkGate, + linked: impl FnOnce() -> Result, String>, + whole: impl FnOnce() -> Result, String>, +) -> Result, String> { + if !gate.open() { + return whole(); + } + match linked() { + Ok(dxil) => Ok(dxil), + Err(e) if is_oom_error(&e) => Err(e), + Err(e) => { + // the same DXC fails the same way for the next program: stop trying + if gate.close() { + crate::xlog_warn!("DXC: a program could not be linked with its memory accessors, compiled whole, and no more programs are linked: {e}"); + } + whole() + } + } +} + +fn link_opt_args<'a>(src_len: usize, extra: &'a [&'a str]) -> Vec<&'a str> { + let mut args = Vec::with_capacity(extra.len() + 3); + if !extra.iter().any(|a| a.starts_with("-O") || *a == "-Od") { + if src_len > UNOPTIMISED_ABOVE { + args.extend(["-O0", "-opt-disable", "debug-nops"]); + } else if src_len > 1024 * 1024 { + args.push("-O1"); + } + } + args.extend(extra.iter().copied()); + args +} + /// `XCL_LINK_MEM=0`: every program is compiled whole (into the same cache: compare with /// another `XCL_DXIL_CACHE`). fn linking() -> bool { @@ -568,6 +745,7 @@ fn kept_once(map: &Mutex>>> /// Compile `program` and `library` (its memory accessors, kept once compiled) as libraries and /// link them to `profile`. fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extra: &[&str]) -> Result, String> { + let program_src_len = program.len(); let model = profile.split_once('_').map_or("6_6", |(_, m)| m); let lib = format!("lib_{model}"); let accessors = { @@ -584,17 +762,20 @@ fn compile_linked(program: &str, library: &str, entry: &str, profile: &str, extr } Ok(p) }; + let link_args_w: Vec> = link_opt_args(program_src_len, extra).into_iter().map(crate::util::wide).collect(); + let link_ptrs: Vec = link_args_w.iter().map(|a| PCWSTR(a.as_ptr())).collect(); unsafe { let linker = IDxcLinker::from_raw(instance(&CLSID_DxcLinker, &IDxcLinker::IID)?); let utils = IDxcUtils::from_raw(instance(&CLSID_DxcUtils, &IDxcUtils::IID)?); let names = [crate::util::wide("program"), crate::util::wide("accessors")]; for (name, dxil) in names.iter().zip([&program, &*accessors]) { - let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, dxil.len() as u32, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; + let len = u32::try_from(dxil.len()).map_err(|_| "DXIL library larger than 4 GiB".to_string())?; + let blob = utils.CreateBlob(dxil.as_ptr() as *const c_void, len, DXC_CP(0)).map_err(|e| format!("CreateBlob: {e}"))?; linker.RegisterLibrary(PCWSTR(name.as_ptr()), &blob).map_err(|e| format!("RegisterLibrary: {e}"))?; } let (entry, profile) = (crate::util::wide(entry), crate::util::wide(profile)); let r = linker - .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), None) + .Link(PCWSTR(entry.as_ptr()), PCWSTR(profile.as_ptr()), &names.each_ref().map(|n| PCWSTR(n.as_ptr())), (!link_ptrs.is_empty()).then_some(link_ptrs.as_slice())) .map_err(|e| format!("Link: {e}"))?; output(r.GetStatus(), r.GetErrorBuffer(), r.GetResult()) } @@ -839,7 +1020,9 @@ fn process_cache_lock(file: &Path) -> Result { if handle.is_null() { return Err("DXIL cache: cannot create the cross-process mutex".into()); } + let wait_stall = crate::stall::span(crate::stall::StallKind::LockContention); let wait = unsafe { WaitForSingleObject(handle, INFINITE) }; + drop(wait_stall); if wait != WAIT_OBJECT_0 && wait != WAIT_ABANDONED { unsafe { CloseHandle(handle) }; return Err(format!("DXIL cache: waiting for the cross-process mutex failed ({wait:#x})")); @@ -848,7 +1031,11 @@ fn process_cache_lock(file: &Path) -> Result { } fn cached_file(file: &Path) -> Option> { - if let Ok(b) = std::fs::read(&file) { + let read = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(file) + }; + if let Ok(b) = read { if valid_dxil_container(&b) { return Some(b); } @@ -914,7 +1101,10 @@ fn is_cacheable_dxc_error(raw: &str) -> bool { } fn cached_error_file(file: &Path, key: u64, src_len: usize) -> Option { - let b = std::fs::read(file).ok()?; + let b = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(file) + }.ok()?; let rest = b.strip_prefix(ERR_MAGIC.as_slice())?; let (k_bytes, rest) = rest.split_first_chunk::<8>()?; let (len_bytes, rest) = rest.split_first_chunk::<8>()?; @@ -944,7 +1134,16 @@ fn store_error_file(file: &Path, key: u64, src_len: usize, reason: &str) { b.extend_from_slice(&(reason.len() as u32).to_le_bytes()); b.extend_from_slice(reason.as_bytes()); let tmp = file.with_extension(format!("err.tmp{}", std::process::id())); - if std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, file).is_err() { + let written = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, file).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -993,6 +1192,7 @@ where // A corrupt target must be removed before the atomic rename on Windows; // rename does not replace an existing file there. if file.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&file); } counters.compilations.fetch_add(1, Ordering::Relaxed); @@ -1022,12 +1222,22 @@ where } }; if err_file.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&err_file); } if std::fs::create_dir_all(&dir).is_ok() { // write to a temporary name first: another thread / process may be reading let tmp = file.with_extension(format!("tmp{}", std::process::id())); - if std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, &file).is_err() { + let written = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, &file).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -1619,4 +1829,178 @@ mod accessor_library_tests { assert!(!gate.open()); assert!(!gate.close()); } + + #[test] + fn compile_linked_or_fallback_keeps_gate_open_on_oom() { + let gate = LinkGate::new(); + for oom in ["dxc (0x8007000E): out of memory", "Link: HRESULT(0x8007000e)", "CreateBlob: E_OUTOFMEMORY"] { + let mut whole_ran = false; + let err = compile_linked_or_fallback(&gate, || Err(oom.into()), || { whole_ran = true; Ok(vec![1]) }).unwrap_err(); + assert_eq!(err, oom); + assert!(gate.open() && !whole_ran, "OOM must keep LinkGate open and skip whole fallback: {oom}"); + } + // Deterministic non-OOM failure closes the gate and falls back to whole; subsequent calls skip linked. + let mut whole_runs = 0usize; + let ok = compile_linked_or_fallback(&gate, || Err("dxc: unsupported WaveSize on library".into()), || { whole_runs += 1; Ok(vec![42]) }).unwrap(); + assert_eq!((ok, gate.open(), whole_runs), (vec![42], false, 1)); + let ok = compile_linked_or_fallback(&gate, || panic!("linked must not run once gate is closed"), || { whole_runs += 1; Ok(vec![99]) }).unwrap(); + assert_eq!((ok, whole_runs), (vec![99], 2)); + } + + #[test] + fn link_opt_args_selects_tier_and_preserves_extra() { + assert_eq!(link_opt_args(1024 * 1024, &[]), Vec::<&str>::new()); + assert_eq!(link_opt_args(1024 * 1024 + 1, &[]), vec!["-O1"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE, &[]), vec!["-O1"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &[]), vec!["-O0", "-opt-disable", "debug-nops"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-O2"]), vec!["-O2"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-Od"]), vec!["-Od"]); + assert_eq!(link_opt_args(512, &["-Gis"]), vec!["-Gis"]); + assert_eq!(link_opt_args(1024 * 1024 + 1, &["-Gis"]), vec!["-O1", "-Gis"]); + assert_eq!(link_opt_args(UNOPTIMISED_ABOVE + 1, &["-Gis"]), vec!["-O0", "-opt-disable", "debug-nops", "-Gis"]); + } + + #[test] + fn compile_linked_forwards_opt_and_extra_args_to_dxc_linker() { + if location().is_err() { + return super::super::runner::skip_test("no DXC"); + } + let library = "RWByteAddressBuffer res : register(u0);\nexport uint helper_add(uint a, uint b) { return a + b; }\n"; + let program = "RWByteAddressBuffer res : register(u0);\nuint helper_add(uint a, uint b);\n[shader(\"compute\")]\n[numthreads(64, 1, 1)]\nvoid main(uint gi : SV_GroupIndex) {\n float x = asfloat(res.Load(gi * 4u));\n float y = (x + 1.0) - 1.0;\n res.Store(gi * 4u, helper_add(asuint(y), gi));\n}\n"; + let run = |args: &[&str]| -> String { + let dxil = compile_linked(program, library, "main", "cs_6_6", args).unwrap_or_else(|e| panic!("args={args:?}: {e}")); + super::super::super::dxil::validate::validate(&dxil).unwrap_or_else(|e| panic!("validate args={args:?}: {e}")); + disassemble(&dxil).unwrap_or_else(|e| panic!("disasm args={args:?}: {e}")) + }; + let d_def = run(&[]); + assert!(!d_def.contains("fadd "), "default link should optimize (x + 1) - 1 away:\n{d_def}"); + let _ = run(&["-O1"]); + let d_o0 = run(&["-O0", "-opt-disable", "debug-nops"]); + assert!(d_o0.contains("fadd fast float") && d_o0.contains("mul i32 ") && !d_o0.contains("dx.op.nop"), "-O0 link must skip -O3 folding and debug-nops:\n{d_o0}"); + let d_gis = run(&["-Gis"]); + assert!(d_gis.contains("fadd float ") && !d_gis.contains("fadd fast "), "-Gis must keep strict IEEE fadd:\n{d_gis}"); + // Also check auto -O1 / -O0 when program.len() > 1 MiB (while library is small). + let big_prog = format!("{program}// {}\n", "a".repeat(1024 * 1024 + 16)); + let dxil_big = compile_linked(&big_prog, library, "main", "cs_6_6", &[]).unwrap(); + super::super::super::dxil::validate::validate(&dxil_big).unwrap(); + } +} + +#[cfg(test)] +mod memory_gate_tests { + use super::*; + use std::sync::atomic::AtomicUsize; + use std::sync::Barrier; + use std::time::Duration; + + #[test] + fn tight_commit_headroom_bounds_concurrent_admissions() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let avail_gb = 7u64 << 30; // fits working == 0 (6 GiB) and working == 1 (7 GiB), not 2 (8 GiB) + let threads = 16; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| false); + barrier.wait(); + if gate.try_admit( + reserve, + || { + std::thread::sleep(Duration::from_millis(2)); + Some(avail_gb) + }, + false, + &wanted, + ) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), 2, "burst admitted more compiles than commit headroom allows"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } + + #[test] + fn wanted_burst_never_exceeds_wanted_at_once() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 16; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| { + std::thread::sleep(Duration::from_millis(2)); + true + }); + barrier.wait(); + if gate.try_admit(reserve, || Some(low_avail), false, &wanted) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), WANTED_AT_ONCE, "wanted burst exceeded WANTED_AT_ONCE"); + assert_eq!(gate.working.load(Ordering::SeqCst), WANTED_AT_ONCE); + } + + #[test] + fn wait_for_memory_drains_concurrent_waiters_within_cap() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 12; + let barrier = Barrier::new(threads); + let active = AtomicUsize::new(0); + let max_active = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| true); + barrier.wait(); + gate.wait_with(reserve, || Some(low_avail), Duration::from_secs(60), &wanted); + let cur = active.fetch_add(1, Ordering::SeqCst) + 1; + max_active.fetch_max(cur, Ordering::SeqCst); + std::thread::sleep(Duration::from_millis(25)); + active.fetch_sub(1, Ordering::SeqCst); + gate.release(); + }); + } + }); + let peak = max_active.load(Ordering::SeqCst); + assert!(peak <= WANTED_AT_ONCE, "peak concurrent slots {peak} exceeded WANTED_AT_ONCE ({WANTED_AT_ONCE})"); + assert_eq!(gate.working.load(Ordering::SeqCst), 0); + } + + #[test] + fn low_commit_unwanted_admits_only_one_progress_slot() { + let gate = MemoryGate::new(); + let reserve = 6u64 << 30; + let low_avail = 1u64 << 30; + let threads = 8; + let barrier = Barrier::new(threads); + let admitted = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..threads { + s.spawn(|| { + let wanted: Wanted = Box::new(|| false); + barrier.wait(); + if gate.try_admit(reserve, || Some(low_avail), false, &wanted) { + admitted.fetch_add(1, Ordering::SeqCst); + } + }); + } + }); + assert_eq!(admitted.load(Ordering::SeqCst), 1, "only one progress compile may run when commit is short and unwanted"); + assert_eq!(gate.working.load(Ordering::SeqCst), 1); + let wanted: Wanted = Box::new(|| false); + assert!(gate.try_admit(reserve, || Some(low_avail), true, &wanted), "timed-out waiter must still admit"); + assert_eq!(gate.working.load(Ordering::SeqCst), 2); + } } diff --git a/crates/xcl/src/gpu/recomp/emit.rs b/crates/xcl/src/gpu/recomp/emit.rs index 2f817a809f..b551dfd7cb 100644 --- a/crates/xcl/src/gpu/recomp/emit.rs +++ b/crates/xcl/src/gpu/recomp/emit.rs @@ -72,6 +72,8 @@ pub(super) struct Em { /// LDS arrival barrier (`xcl_s_barrier`) so RDNA2 early `s_endpgm`, `LOOP_GUARD` exits, /// or split-wave64 desyncs cannot permanently hang an NVIDIA SM at `bar.sync`. safe_barrier: bool, + /// any console group barrier; with LDS, this excludes cross-wave-local remapping + has_s_barrier: bool, /// the T# SGPRs of the program's image stores and atomics (`image_write_srsrcs`) img_writes: Vec, /// compute program needs `globallycoherent` on flat memory windows (`needs_coherent_mem`) @@ -624,6 +626,7 @@ impl Em { dynamic_f16_rm: false, track_frexp_denorm: false, safe_barrier: false, + has_s_barrier: false, img_writes: Vec::new(), coherent_mem: false, } @@ -689,9 +692,10 @@ impl Em { } } self.dynamic_f16_rm = writes_nonzero_dp && self.has_f16_round_op && !self.has_f64_round_op; + self.has_s_barrier = has_s_barrier; self.safe_barrier = has_s_barrier && self.compute_or_mesh_hw_waves().is_some_and(|w| w > 1) - && std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"); + && safe_barrier_wanted(); } pub fn take(&mut self) -> String { @@ -4758,11 +4762,42 @@ impl Em { } } + /// Split-wave64 compute whose console waves share neither LDS nor a group barrier: groups per + /// console group, scaled dispatch dimension, and the one-wave hardware group shape. + pub(crate) fn remap(&self) -> Option<(u32, usize, [u32; 3])> { + if self.opt.no_remap || !self.x64() || self.uses_lds || self.has_s_barrier { + return None; + } + let Mode::Compute(cs) = &self.opt.mode else { return None }; + let [x, y, z] = cs.threads; + let threads = x.checked_mul(y)?.checked_mul(z)?; + if x == 0 || threads <= 64 || threads % 64 != 0 { + return None; + } + if x >= 64 && x % 64 == 0 && y == 1 && z == 1 { + return Some((x / 64, 0, [64, 1, 1])); + } + if x <= 64 && 64 % x == 0 { + let rows = 64 / x; + if rows <= y && y % rows == 0 && z == 1 { + return Some((y / rows, 1, [x, rows, 1])); + } + } + None + } + + fn x64_hw_threads(&self) -> u32 { + self.remap().map_or(self.x64_threads(), |_| 64) + } + /// Split wave64: meet through bounded arrival counters (`XCL_X_SPIN 1`) by default so /// divergent wave32 halves can never permanently deadlock a GPU SM at an unbounded /// `GroupMemoryBarrierWithGroupSync()`. Set `XCL_WAVE64_SPIN=0` to force group barriers /// for 1-wave64 groups. fn x64_spin(&self) -> bool { + if self.remap().is_some() { + return false; + } self.x64_threads() > 64 || std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") } @@ -4775,7 +4810,7 @@ impl Em { /// Storage and functions of the split wave64 form (`PRELUDE_X64`). fn x64_prelude(&self, h: &mut String) { - let threads = self.x64_threads(); + let threads = self.x64_hw_threads(); let waves = threads.div_ceil(64).max(1) as usize; let slot = self.x64_words; // slots (console wave, half, parity), the arrival counters (console wave, half), the @@ -4982,6 +5017,8 @@ impl Em { h.push_str("groupshared uint xcl_lds[8192]; // D3D12 limit: 32 KB (the console allows 64 KB)\n"); } let [x, y, z] = cs.threads; + let remap = self.remap(); + let [nx, ny, nz] = remap.map_or([x, y, z], |(_, _, hw)| hw); // split wave64: the same group in hardware wave32s (a console wave = two of them) let hw_lanes = if self.x64() { 32 } else { lanes }; // 2-D / 3-D groups: the PC driver need not form its waves from consecutive @@ -5002,12 +5039,16 @@ impl Em { self.safe_barrier_prelude(&mut h); let _ = writeln!( h, - "[WaveSize({hw_lanes})]\n[numthreads({x}, {y}, {z})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" + "[WaveSize({hw_lanes})]\n[numthreads({nx}, {ny}, {nz})]\nvoid main(uint3 gid : SV_GroupID, uint3 gtid : SV_GroupThreadID, uint gi : SV_GroupIndex)\n{{" ); if self.safe_barrier { h.push_str(" xcl_s_barrier_init(gi);\n"); } - if self.x64() { + if let Some((ratio, dim, _)) = remap { + let d = ["x", "y", "z"][dim]; + h.push_str(" uint xcl_local = xcl_x_thread(gi);\n lane_id = xcl_local & 63u;\n xcl_half = (xcl_local >> 5) & 1u;\n xcl_cw = 0u;\n xcl_xn = XCL_X_THREADS > ((xcl_local & ~31u) ^ 32u) ? min(32u, XCL_X_THREADS - ((xcl_local & ~31u) ^ 32u)) : 0u;\n"); + let _ = writeln!(h, " uint xcl_tid = (gid.{d} % {ratio}u) * 64u + xcl_local;\n gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); + } else if self.x64() { // the console thread's ids (`xcl_x_thread`), not this hardware thread's self.x64_entry(&mut h); let _ = writeln!(h, " gtid = uint3(xcl_tid % {x}u, (xcl_tid / {x}u) % {y}u, xcl_tid / {}u);\n gi = xcl_tid;", x * y); @@ -5028,7 +5069,11 @@ impl Em { for (k, c) in ["x", "y", "z"].iter().enumerate() { if cs.tgid[k] { if sg.contains(&next) { - let _ = writeln!(h, " {} = gid.{c};", sname(next).unwrap()); + let div = match remap { + Some((ratio, dim, _)) if ["x", "y", "z"][dim] == *c => format!(" / {ratio}u"), + _ => String::new(), + }; + let _ = writeln!(h, " {} = gid.{c}{div};", sname(next).unwrap()); } next += 1; } @@ -5037,7 +5082,23 @@ impl Em { // waves in the group: a last, partial wave counts (96 threads: 2 of 64) let _ = writeln!(h, " {} = {}u | ((gi / {lanes}u) << 6);", sname(next).unwrap(), (x * y * z).div_ceil(lanes)); } - let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0 = {}(true); exec_lo = e0.x; exec_hi = e0.y; }}", self.ballot_fn()); + h.push_str(" bool xcl_dispatch_limited = false;\n"); + for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) { + let slot = super::IO_THREAD_LIMIT[k] * 4; + let _ = writeln!(h, " uint xcl_limit_{c} = io.Load({slot}u);\n xcl_dispatch_limited = xcl_dispatch_limited || xcl_limit_{c} != 0u;"); + } + let _ = writeln!(h, " uint scc = 0u;\n {{ uint2 e0;"); + let _ = writeln!(h, " if (xcl_dispatch_limited) {{\n bool xcl_dispatch_live = true;"); + for (k, c) in ["x", "y", "z"].iter().enumerate().filter(|(k, _)| cs.threads[*k] > 1) { + let group = match remap { + Some((ratio, dim, _)) if dim == k => format!("(gid.{c} / {ratio}u)"), + _ => format!("gid.{c}"), + }; + let threads = cs.threads[k]; + let _ = writeln!(h, " xcl_dispatch_live = xcl_dispatch_live && (xcl_limit_{c} == 0u || {group} * {threads}u + gtid.{c} < xcl_limit_{c});"); + } + let ballot = self.ballot_fn(); + let _ = writeln!(h, " e0 = {ballot}(xcl_dispatch_live);\n }} else {{\n e0 = {ballot}(true);\n }}\n exec_lo = e0.x; exec_hi = e0.y; }}"); for &v in &self.vgprs { let init = match v { 0 => "gtid.x", @@ -5831,15 +5892,28 @@ fn method_switch(windows: u32, w: &str, ret: &str, name: &str, args: &str, def: fn mem_accessors(windows: u32, heap: Option<&str>) -> String { let mut s = String::new(); if let Some(coherent) = heap { - // one access: window k is descriptor MEM_HEAP_BASE + k; an `xcl_w` outside the windows - // does what the switch's `default` does + // Redirect ordinary out-of-window loads/stores to null raw UAVs without a divergent + // branch. Atomics keep the guard because their out parameter must be set to zero. + let buf = |nul: u32| format!( + "{{ bool xcl_o = xcl_w >= {windows}u; {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex(select(xcl_o, {nul}u, {}u + xcl_w))]; ", + super::MEM_HEAP_BASE + ); let _ = writeln!(s, "#define XCL_MW {coherent}RWByteAddressBuffer m = ResourceDescriptorHeap[NonUniformResourceIndex({}u + xcl_w)]", super::MEM_HEAP_BASE); - let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {{ [branch] if (xcl_w >= {windows}u) {{ return uint4(0u, 0u, 0u, 0u); }} XCL_MW; return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}"); + let _ = writeln!(s, "uint4 xcl_loadx4(uint4 a) {}return uint4(m.Load(a.x), m.Load(a.y), m.Load(a.z), m.Load(a.w)); }}", buf(super::MEM_NULL_LOAD)); for (ret, name, params, args, def) in mem_methods() { - let r = if ret == "void" { "" } else { "return " }; - // (the switch's `break` leaves the accessor) - let outside = def.replace("break;", "return;"); - let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + if name.starts_with("Load") || name.starts_with("Store") { + let nul = if name.starts_with("Store") { super::MEM_NULL_STORE } else { super::MEM_NULL_LOAD }; + let call = if name.starts_with("Store") { + format!("m.{name}(a, {});", &args[3..]) + } else { + format!("return m.{name}(a);") + }; + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {}{}}}", buf(nul), call); + } else { + let r = if ret == "void" { "" } else { "return " }; + let outside = def.replace("break;", "return;"); + let _ = writeln!(s, "{ret} xcl_m{name}({params}) {{ [branch] if (xcl_w >= {windows}u) {{ {outside} }} XCL_MW; {r}m.{name}({args}); }}"); + } } return s; } @@ -6194,6 +6268,12 @@ uint2 xcl_x_ballot_local(bool b) { uint xcl_x_rla_half(uint v, uint l) { return WaveReadLaneAt(v, l & 31u); } "#; +/// Whether a multi-warp Compute / Mesh `s_barrier` gets the early-exit-safe barrier +/// (`XCL_SAFE_BARRIER=0`: the plain group barrier, in both translators). +pub(crate) fn safe_barrier_wanted() -> bool { + std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0") +} + /// Early-exit-safe, bounded workgroup barrier for multi-warp Compute / Mesh `s_barrier`. /// /// On RDNA2, `S_ENDPGM` decrements the CU's active wave count so remaining waves executing @@ -6718,7 +6798,19 @@ uint fclass64(double f) { #[cfg(test)] mod tests { - use super::{PRELUDE, PRELUDE_MEM}; + use super::{mem_accessors, PRELUDE, PRELUDE_MEM}; + + #[test] + fn heap_window_loads_and_stores_use_null_descriptors_without_branches() { + let h = mem_accessors(4, Some("globallycoherent ")); + let load = format!("select(xcl_o, {}u,", super::super::MEM_NULL_LOAD); + let store = format!("select(xcl_o, {}u,", super::super::MEM_NULL_STORE); + assert!(h.contains(&load), "load accessor did not select the null-load UAV:\n{h}"); + assert!(h.contains(&store), "store accessor did not select the null-store UAV:\n{h}"); + assert!(h.contains("xcl_mInterlockedAdd(uint a, uint v, out uint o) { [branch] if"), "atomic guard was removed:\n{h}"); + assert!(!h.contains("xcl_mLoad(uint a) { [branch]"), "ordinary load kept a divergent guard:\n{h}"); + assert!(!h.contains("xcl_mStore(uint a, uint v) { [branch]"), "ordinary store kept a divergent guard:\n{h}"); + } #[test] fn format_helpers_select_uint4_components_without_runtime_indexing() { diff --git a/crates/xcl/src/gpu/recomp/heap_window_tests.rs b/crates/xcl/src/gpu/recomp/heap_window_tests.rs index 1ae5c75a4e..2f0084b2f0 100644 --- a/crates/xcl/src/gpu/recomp/heap_window_tests.rs +++ b/crates/xcl/src/gpu/recomp/heap_window_tests.rs @@ -209,6 +209,133 @@ fn compile_variant(code: &[u8], direct: bool, heap: bool, mem_windows: u32) -> V } } +/// Direct-DXIL flat heap reads produce the same output as guarded heap reads for four windows +/// and the largest supported heap. This includes inactive lanes, null and outside-UMA +/// addresses, and a dwordx2 load ending at the raw view boundary. The one-window case is a +/// root-UAV-only degenerate baseline (heap flags intentionally collapse to that form). +/// Run native and explicitly split wave64 forms wherever the adapter supports them. +#[test] +fn gpu_heap_flat_reads_match_guarded_and_root_output() { + use crate::gpu::dxil::kernel::{translate, KernelOptions}; + + if let Err(err) = super::runner::adapter() { + println!("GPU unavailable – skipping ({err})"); + super::runner::skip_test("no GPU"); + return; + } + let mut wave_modes = Vec::new(); + if super::runner::wave64_supported() == Ok(true) { + wave_modes.push(("native wave64", false)); + } + if super::runner::wave32_supported() == Ok(true) { + wave_modes.push(("split wave64", true)); + } + if wave_modes.is_empty() { + println!("GPU has neither native wave64 nor wave32 for split wave64 – skipping"); + super::runner::skip_test("no wave64"); + return; + } + + let e = |n: &str, enc: &str, f: &[(&str, u64)]| crate::gpu::rdna2::encode(n, enc, f, None).unwrap(); + let mut code = Vec::new(); + code.extend(e("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 30), ("SBASE", 1), ("OFFSET", 0)])); + code.extend(e("S_LOAD_DWORD", "ENC_SMEM", &[("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)])); + code.extend(e("S_BUFFER_LOAD_DWORDX4", "ENC_SMEM", &[("SDATA", 24), ("SBASE", 4), ("OFFSET", 4)])); + // Only lanes 33..63 execute the vector reads; inactive lanes retain their sentinels. + code.extend(e("V_CMPX_LT_U32", "ENC_VOPC", &[("SRC0", 160), ("VSRC1", 0)])); + code.extend(e("BUFFER_LOAD_DWORD", "ENC_MUBUF", &[("VDATA", 7), ("VADDR", 0), ("SRSRC", 3), ("SOFFSET", 128), ("IDXEN", 1)])); + code.extend(e("GLOBAL_LOAD_DWORD", "ENC_FLAT_GLBL", &[("VDST", 6), ("ADDR", 4), ("SADDR", 0x7D), ("OFFSET", 0)])); + code.extend(e("GLOBAL_LOAD_DWORDX2", "ENC_FLAT_GLBL", &[("VDST", 8), ("ADDR", 10), ("SADDR", 0x7D), ("OFFSET", 0)])); + code.extend(e("S_ENDPGM", "ENC_SOPP", &[])); + + const BYTES: usize = 1 << 20; + const OLD: u32 = 0x7777_7777; + for windows in [1usize, 4, crate::gpu::uma::MAX_HEAP_WINDOWS] { + let arena = crate::gpu::uma::Uma::with_windows(windows, BYTES).unwrap(); + let bases: Vec = (0..windows).map(|k| arena.window(k).0 as u64).collect(); + let base_hi = (bases[0] >> 32) as u32; + let target = windows - 1; + let word = |a: u64| unsafe { &mut *(a as *mut u32) }; + for (k, &base) in bases.iter().enumerate() { + *word(base + 0x40) = 0xA000 + k as u32; + for lane in 0..64u64 { + *word(base + 0x100 + 4 * lane) = (k as u32 + 1) * 1000 + lane as u32; + } + *word(base + BYTES as u64 - 8) = 0xD000 + k as u32; + *word(base + BYTES as u64 - 4) = 0xE000 + k as u32; + } + + let mut st = super::runner::KernelState::default(); + st.sgpr[2..4].copy_from_slice(&[0x40, base_hi + target as u32]); + st.sgpr[4..6].copy_from_slice(&[0x40, base_hi + windows as u32 + 1]); + st.sgpr[8..12].copy_from_slice(&[0x100, (base_hi + target as u32) & 0xFFFF, 0x400, 0]); + st.sgpr[12..16].copy_from_slice(&[0x100, (base_hi + target as u32) & 0xFFFF | 4 << 16, 64, 0]); + for (lane, r) in st.vgpr.iter_mut().enumerate() { + let lane = lane as u32; + r[0] = lane; + r[4] = if lane % 8 == 6 { 0 } else { 0x100 + 4 * lane }; + r[5] = match lane % 8 { + 6 => 0, // null + 7 => base_hi + windows as u32 + 1, // outside UMA + _ => base_hi + lane % windows as u32, + }; + r[6..10].fill(OLD); + // One window uses a root UAV (no descriptor bounds); heap forms use the + // straddling read to verify the descriptor-view boundary. + r[10] = BYTES as u32 - if windows == 1 { 8 } else { 4 }; + r[11] = base_hi + target as u32; + } + + for &(wave, split) in &wave_modes { + let run = |mem_windows, state: &super::runner::KernelState| { + let dxil = translate(&code, KernelOptions { wave64: true, split, mem_windows, sampler_base: 0 }) + .unwrap_or_else(|err| panic!("{wave}, {windows} windows ({mem_windows:#x}): {err}")); + super::runner::run_in_arena(&dxil, state, &arena) + .unwrap_or_else(|err| panic!("{wave}, {windows} windows ({mem_windows:#x}): {err}")) + }; + let output = if windows == 1 { + run(1, &st) + } else { + let guarded = run(windows as u32 | super::HEAP_WINDOWS, &st); + let flat = run(windows as u32 | super::HEAP_WINDOWS | super::HEAP_FLAT, &st); + assert_eq!(guarded.sgpr[..32], flat.sgpr[..32], "{wave}, {windows} heap windows: SGPR parity"); + for lane in 0..64 { + assert_eq!(guarded.vgpr[lane][..12], flat.vgpr[lane][..12], "{wave}, {windows} heap windows: lane {lane} parity"); + } + flat + }; + if windows == crate::gpu::uma::MAX_WINDOWS { + // Root UAVs have no view bounds, so use an in-view dwordx2 for this baseline. + let mut root_st = st.clone(); + for r in &mut root_st.vgpr { + r[10] = BYTES as u32 - 8; + } + let root = run(windows as u32, &root_st); + let guarded_root = run(windows as u32 | super::HEAP_WINDOWS, &root_st); + assert_eq!(guarded_root.sgpr[..32], root.sgpr[..32], "{wave}, {windows} windows: branchless root-UAV SGPR baseline"); + for lane in 0..64 { + assert_eq!(guarded_root.vgpr[lane][..12], root.vgpr[lane][..12], "{wave}, {windows} windows: branchless root-UAV lane {lane} baseline"); + } + } + + assert_eq!((output.sgpr[30], output.sgpr[31]), (0xA000 + target as u32, 0), "{wave}, {windows} windows: scalar valid/outside"); + assert_eq!(output.sgpr[24..28], [1000 * windows as u32 + 1, 1000 * windows as u32 + 2, 1000 * windows as u32 + 3, 1000 * windows as u32 + 4], "{wave}, {windows} windows: scalar vector load"); + for lane in 0..64u32 { + let v = &output.vgpr[lane as usize]; + let active = lane > 32; + assert_eq!(v[7], if active { 1000 * windows as u32 + lane } else { OLD }, "{wave}, {windows} windows, lane {lane}: buffer load"); + let global = match lane % 8 { + 6 | 7 => 0, + _ => (lane % windows as u32 + 1) * 1000 + lane, + }; + assert_eq!(v[6], if active { global } else { OLD }, "{wave}, {windows} windows, lane {lane}: null/outside global load"); + let edge = if windows == 1 { [0xD000, 0xE000] } else { [0xE000 + target as u32, 0] }; + assert_eq!(v[8..10], if active { edge } else { [OLD, OLD] }, "{wave}, {windows} windows, lane {lane}: end-of-view dwordx2"); + } + } + } +} + /// Divergent per-lane window indexing (`NonUniformResourceIndex`): in a single wave, lanes hit /// window 0 (`l % 3 == 0`), window 1 (`l % 3 == 1`), and out-of-UMA (`l % 3 == 2`, aliasing w0 /// under `& 3`) simultaneously on loads, stores, and atomics. HLSL and direct DXIL must match diff --git a/crates/xcl/src/gpu/recomp/mod.rs b/crates/xcl/src/gpu/recomp/mod.rs index 528493d6e5..a8ffdc7a10 100644 --- a/crates/xcl/src/gpu/recomp/mod.rs +++ b/crates/xcl/src/gpu/recomp/mod.rs @@ -81,10 +81,20 @@ mod link_tests; /// (`console_heap::null_views`). pub const MEM_HEAP_BASE: u32 = 4; +/// Null raw-UAV descriptors just after all window slots. Heap-window loads outside the active +/// layout read zero from `MEM_NULL_LOAD`; stores are redirected to `MEM_NULL_STORE` and dropped. +pub const MEM_NULL_LOAD: u32 = MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32; +pub const MEM_NULL_STORE: u32 = MEM_NULL_LOAD + 1; + /// Flag in a memory-windows count (`pso::mem_windows`, the translation caches' keys): /// `Options::heap_windows`. `translate` takes it out of `mem_windows`. pub const HEAP_WINDOWS: u32 = 0x100; +/// Flag in a memory-windows count next to `HEAP_WINDOWS` (`pso::mem_windows`, the caches' keys): +/// the direct DXIL translator reads the heap windows of compute stages without a branch +/// (`Lw::with_mem_i32s`). The HLSL path ignores it. +pub const HEAP_FLAT: u32 = 0x200; + pub(crate) fn valid_window_count(windows: usize, heap: bool) -> bool { windows <= crate::gpu::uma::MAX_WINDOWS || (heap && windows.is_power_of_two() && windows <= crate::gpu::uma::MAX_HEAP_WINDOWS) @@ -204,6 +214,11 @@ pub const GS_PRIMS_PER_GROUP: u32 = 21; pub const IO_GS_PRIMS: usize = 110; pub const IO_GS_VERTICES: usize = 111; pub const IO_UMA_BASE_HI: usize = 112; +/// io slots of a `DispatchX` with thread dimensions (flag 0x20): the thread count of each axis +/// when it is not a whole number of groups (0: the last group is whole), so the program can leave +/// the lanes past it out of EXEC. Written by D3D12.X and read by both compute backends. +/// (113 is left for the group-limit slot of #1428.) +pub const IO_THREAD_LIMIT: [usize; 3] = [114, 115, 116]; impl GsInterface { /// bytes of one ES vertex in LDS (ESGS item: 16 per ES output register) @@ -528,11 +543,13 @@ pub struct Options { /// structured control flow when the program allows it (false, or `XCL_RECOMP_NO_STRUCTURED`: /// always the guarded block chain) pub structured: bool, + /// force the console-sized form used when an indirect dispatch cannot scale GPU arguments + pub no_remap: bool, } impl Default for Options { fn default() -> Self { - Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true } + Options { mode: Mode::Kernel, wave64: true, hw_wave: 0, split_wave64: false, static_sampler_base: 0, mem_windows: 1, heap_windows: false, structured: true, no_remap: false } } } @@ -552,6 +569,8 @@ pub struct Translation { /// console root signature's static samplers): (S#, comparison), register /// `static_sampler_base + i` in space 1 pub static_samplers: Vec<([u32; 4], bool)>, + /// `(hardware groups per console group, scaled dimension)` for wave-local split-wave64 compute + pub dispatch_remap: Option<(u32, u32)>, } impl Translation { @@ -1497,11 +1516,17 @@ pub(crate) fn needs_coherent_mem(insts: &[Decoded]) -> bool { }) } +#[inline] pub fn translate(code: &[u8], opt: &Options) -> Result { + let _stall = crate::stall::span(crate::stall::StallKind::ShaderTranslation); + translate_inner(code, opt) +} + +fn translate_inner(code: &[u8], opt: &Options) -> Result { let program = code; let normalized; let opt = if opt.mem_windows & HEAP_WINDOWS != 0 { - normalized = Options { mem_windows: opt.mem_windows & !HEAP_WINDOWS, heap_windows: true, ..opt.clone() }; + normalized = Options { mem_windows: opt.mem_windows & !(HEAP_WINDOWS | HEAP_FLAT), heap_windows: true, ..opt.clone() }; &normalized } else { opt @@ -1609,7 +1634,7 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { // smaller for DXC and the driver on big programs) emit_structured(&sctx, &mut em, &mut code, 0, u64::MAX, None, 0, &Conts::default(), &BTreeSet::new(), 1, &mut blocks, &mut flags); if code.len() > STRUCTURED_BYTES_PER_CODE_BYTE * program.len() { - return translate(program, &Options { structured: false, ..opt.clone() }); + return translate_inner(program, &Options { structured: false, ..opt.clone() }); } } else { if gs_jump.is_some() && opt.split_wave64 && opt.wave64 { @@ -1626,7 +1651,8 @@ pub fn translate(code: &[u8], opt: &Options) -> Result { } let hlsl = em.finish(&body); let static_samplers = em.static_used.clone(); - Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers }) + let dispatch_remap = em.remap().map(|(ratio, dim, _)| (ratio, dim as u32)); + Ok(Translation { hlsl, unsupported: em.unsupported, unsupported_why: em.unsupported_why, ignored: em.ignored, instructions: insts.len(), blocks, static_samplers, dispatch_remap }) } #[cfg(test)] diff --git a/crates/xcl/src/gpu/recomp/pso.rs b/crates/xcl/src/gpu/recomp/pso.rs index b8b0cde0f1..abe3728260 100644 --- a/crates/xcl/src/gpu/recomp/pso.rs +++ b/crates/xcl/src/gpu/recomp/pso.rs @@ -26,6 +26,48 @@ pub enum Stage { Mesh, } +/// Output-affecting process policy for a compute shader translation. This is kept semantic: +/// diagnostic/cache switches are absent, while environment values are normalized to the choices +/// the translators actually make. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(crate) struct ComputePolicyKey { + pub direct: bool, + pub structured: bool, + pub precise_x64_masks: bool, + pub wave64_spin: bool, + pub safe_barrier: bool, + pub direct_compact: Option, + pub direct_compact_nest: Option, + pub direct_piece_limit: usize, + pub per_lane: bool, + pub disabled_dxil_optimizations: u8, +} + +pub(crate) fn compute_policy_key() -> ComputePolicyKey { + let direct = crate::gpu::dxil::kernel::enabled(); + let disabled = std::env::var("XCL_DXIL_NO_OPT").unwrap_or_default(); + let skip = |name: &str| disabled.split(',').any(|v| { + let v = v.trim(); + v == name || v == "all" + }); + ComputePolicyKey { + direct, + structured: std::env::var_os("XCL_RECOMP_NO_STRUCTURED").is_none(), + precise_x64_masks: std::env::var_os("XCL_X64_ALL_MASKS").is_none(), + wave64_spin: std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0"), + safe_barrier: std::env::var("XCL_SAFE_BARRIER").map_or(true, |v| v.trim() != "0"), + // The HLSL path can route enormous compute programs through the direct translator too. + direct_compact: crate::gpu::dxil::kernel::compact_mode(), + direct_compact_nest: crate::gpu::dxil::kernel::compact_nest_tag(), + direct_piece_limit: crate::gpu::dxil::kernel::dispatch_piece_limit(), + per_lane: crate::gpu::recomp::lower_dxil::enabled(), + disabled_dxil_optimizations: ["phi", "cse", "dce", "merge"] + .iter() + .enumerate() + .fold(0, |bits, (i, name)| bits | ((skip(name) as u8) << i)), + } +} + /// A console (xbox-native) shader container? pub fn is_console(blob: &[u8]) -> bool { xbox::is_xbox(blob) || fspx(blob).is_some() @@ -80,14 +122,24 @@ pub fn fspx(blob: &[u8]) -> Option> { /// Memory windows of the title's unified memory (1 without it), with `HEAP_WINDOWS` when /// shaders take them from the descriptor heap (`heap_windows`). pub fn mem_windows() -> u32 { - let n = crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32); + windows_for(crate::gpu::uma::get().map_or(1, |u| u.shader_windows() as u32)) +} + +/// `n` windows as this run's programs take them (`mem_windows`; also the keys +/// `xcl shaders --precompile` makes, so they are the ones the runtime looks up). +pub fn windows_for(n: u32) -> u32 { if n > 1 && heap_windows() && !SWITCH_FORM.with(|s| s.get()) { - n | super::HEAP_WINDOWS + n | super::HEAP_WINDOWS | if heap_flat() { super::HEAP_FLAT } else { 0 } } else { n } } +/// `HEAP_FLAT` changes only compute translation; other stages keep their existing cache identity. +fn windows_for_stage(windows: u32, stage: Stage) -> u32 { + if stage == Stage::Compute { windows } else { windows & !super::HEAP_FLAT } +} + thread_local! { /// this thread translates in the switch form (`in_switch_form`) static SWITCH_FORM: std::cell::Cell = const { std::cell::Cell::new(false) }; @@ -118,6 +170,13 @@ pub fn heap_windows() -> bool { *ENV.get_or_init(|| std::env::var("XCL_HEAP_WINDOWS").is_ok_and(|v| v.trim() == "1")) && !crate::hle::d3d12x::console_heap::window_views_failed() } +/// `XCL_HEAP_FLAT=1` (with heap windows): the direct DXIL translator reads a compute stage's heap +/// windows without a branch per access (`HEAP_FLAT`). Opt-in while it is measured. +pub fn heap_flat() -> bool { + static ENV: OnceLock = OnceLock::new(); + *ENV.get_or_init(|| std::env::var("XCL_HEAP_FLAT").is_ok_and(|v| v.trim() == "1")) +} + /// A static sampler of a translated program: (S#, comparison) – see `Translation`. pub type StaticSampler = ([u32; 4], bool); @@ -127,6 +186,7 @@ pub struct Compiled { pub dispatch_chain: Option>, pub dxil: Vec, pub samplers: Vec, + pub dispatch_remap: Option<(u32, u32)>, } /// Translate a console shader for `stage` to signed DXIL (DXC, disk-cached); its static @@ -153,6 +213,7 @@ fn shader_cache() -> &'static Mutex { /// `console_to_dxil_for` with the title's memory windows given (`xcl shaders --precompile` /// fills the caches without a title: the same keys as at its run). pub fn console_to_dxil_in(blob: &[u8], stage: Stage, sampler_base: u32, split_wave64: bool, windows: u32) -> Result { + let windows = windows_for_stage(windows, stage); let compile_one = || compile_console_shader(blob, stage, sampler_base, windows, split_wave64); if !cache_allowed(stage, |name| std::env::var_os(name).is_some()) { return compile_one().map(|(c, _)| c); @@ -183,7 +244,7 @@ mod translated { use std::path::{Path, PathBuf}; use std::sync::OnceLock; - const MAGIC: &[u8; 8] = b"XCLTRAN2"; + const MAGIC: &[u8; 8] = b"XCLTRAN3"; const ERR_MAGIC: &[u8; 8] = b"XCLTERR1"; const MAX_CACHED_ERR_BYTES: usize = 64 * 1024; @@ -300,7 +361,14 @@ mod translated { } pub(super) fn load_in(path: &Path, ident: u64, blob: &[u8]) -> Option { - let b = std::fs::read(path).ok()?; + let b = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(path) + }.ok()?; + decode_entry(b, ident, blob) + } + + pub(super) fn decode_entry(mut b: Vec, ident: u64, blob: &[u8]) -> Option { let head = header(ident, blob); let mut r = b.strip_prefix(head.as_slice())?; let u32_ = |r: &mut &[u8]| -> Option { @@ -308,6 +376,9 @@ mod translated { *r = rest; Some(u32::from_le_bytes(*v)) }; + let ratio = u32_(&mut r)?; + let dim = u32_(&mut r)?; + let dispatch_remap = (ratio > 1 && dim < 3).then_some((ratio, dim)); let n = u32_(&mut r)? as usize; if n > r.len() / 17 { return None; @@ -324,7 +395,12 @@ mod translated { let (whole, mut rest) = r.split_at_checked(len)?; if !super::dxc::valid_dxil_container(whole) { return None; } let dispatch_chain = if rest.is_empty() { - None + // Keep the file allocation instead of allocating a second payload-sized buffer. + // Split entries still copy below, so the whole shader does not retain all pieces. + let start = b.len() - len; + b.copy_within(start.., 0); + b.truncate(len); + return Some(Compiled { dxil: b, samplers, dispatch_chain: None, dispatch_remap }); } else { let dwords_per_group = u32_(&mut rest)?; let count = u32_(&mut rest)?; @@ -341,7 +417,7 @@ mod translated { if !rest.is_empty() { return None; } Some(std::sync::Arc::new(crate::gpu::dxil::kernel::DispatchChain { dwords_per_group, pieces })) }; - Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain }) + Some(Compiled { dxil: whole.to_vec(), samplers, dispatch_chain, dispatch_remap }) } pub(super) fn store_in(path: &Path, ident: u64, blob: &[u8], c: &Compiled) { @@ -349,6 +425,9 @@ mod translated { return; } let mut b = header(ident, blob); + let (ratio, dim) = c.dispatch_remap.unwrap_or((1, 0)); + b.extend_from_slice(&ratio.to_le_bytes()); + b.extend_from_slice(&dim.to_le_bytes()); b.extend_from_slice(&(c.samplers.len() as u32).to_le_bytes()); for (s, cmp) in &c.samplers { s.iter().for_each(|v| b.extend_from_slice(&v.to_le_bytes())); @@ -367,9 +446,23 @@ mod translated { let Some(dir) = path.parent() else { return }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); // written whole, then renamed: a reader never sees half a file - if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() { + let written = std::fs::create_dir_all(dir).is_ok() && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, path).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(path); - if std::fs::rename(&tmp, path).is_err() { + let retried = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, path).is_ok() + }; + if !retried { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -405,7 +498,10 @@ mod translated { } pub(super) fn load_err_in(path: &Path, ident: u64, blob: &[u8]) -> Option { - let b = std::fs::read(path).ok()?; + let b = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::read(path) + }.ok()?; let head = err_header(ident, blob); let rest = b.strip_prefix(head.as_slice())?; let (len_bytes, msg_bytes) = rest.split_first_chunk::<4>()?; @@ -425,7 +521,16 @@ mod translated { b.extend_from_slice(reason.as_bytes()); let Some(dir) = path.parent() else { return }; let tmp = dir.join(format!("{}.{}.{:?}.tmp", path.file_name().unwrap_or_default().to_string_lossy(), std::process::id(), std::thread::current().id())); - if std::fs::create_dir_all(dir).is_ok() && std::fs::write(&tmp, &b).is_ok() && std::fs::rename(&tmp, path).is_err() { + let written = std::fs::create_dir_all(dir).is_ok() && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::write(&tmp, &b).is_ok() + }; + let renamed = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, path).is_ok() + }; + if written && !renamed { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } } @@ -460,6 +565,7 @@ mod translated { return Err("translated cache: translator returned an invalid DXIL container".into()); } if err_path.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&err_path); } store_in(&path, ident, blob, &c); @@ -553,6 +659,7 @@ mod translated { match translate() { Ok((c, direct)) => { if err_path.is_file() { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&err_path); } let id = if direct { rerouted } else { ident }; @@ -612,7 +719,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: Err(e) => direct_fallback(if stage == Stage::Vertex { "VS" } else { "PS" }, &e), } } - let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64)?; + let (mut t, profile) = console_translation(blob, stage, sampler_base, windows, split_wave64, false)?; if enormous(stage, t.hlsl.len()) && !crate::gpu::dxil::kernel::enabled() { if dxc::defer() { return Err("DXIL not compiled yet".into()); @@ -660,7 +767,7 @@ fn compile_console_shader(blob: &[u8], stage: Stage, sampler_base: u32, windows: t.hlsl = t.hlsl.replacen(" if (!xcl_live) discard;\n return xo;\n}", &format!(" xo.t0 = {expr};\n return xo;\n}}"), 1); } let dxil = dxc::compile_cached(&t.hlsl, "main", profile)?.0; - Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }, false)) + Ok((Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: t.dispatch_remap }, false)) } /// Every `X_T.Sample(args)` of generated HLSL as `X_T.SampleLevel(args, 0.0f)`. @@ -718,7 +825,7 @@ fn debug_color(blob: &[u8]) -> Option<[f32; 3]> { /// The HLSL (and its DXC profile) `console_to_dxil` compiles. pub fn console_to_hlsl(blob: &[u8], stage: Stage) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0, mem_windows(), false).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, mem_windows(), false, false).map(|(t, p)| (t.hlsl, p)) } /// Upper entry cap for `ShaderCache` (the 64 MiB byte limit is the primary bound; a retail game @@ -827,6 +934,7 @@ impl ShaderCache { let bytes = blob.len() + key.cache_dir.capacity() + shader.dxil.capacity() + + shader.dispatch_chain.as_ref().map_or(0, |chain| chain.pieces.iter().map(Vec::capacity).sum()) + shader.samplers.capacity() * std::mem::size_of::(); if bytes > self.limit { return; @@ -923,13 +1031,19 @@ fn cache_allowed(stage: Stage, present: impl Fn(&str) -> bool) -> bool { /// s0…s3 are the driver's, so what is above 4 is the root arguments its compiler passed in /// registers. None: not a console compute shader. pub fn compute_user_sgprs(blob: &[u8]) -> Option { + compute_interface(blob).map(|cs| cs.user_sgprs) +} + +/// The dispatch ABI of a console compute program: its user SGPRs and the console's group shape +/// (`numthreads`). None: not a console compute program. +pub fn compute_interface(blob: &[u8]) -> Option { if let Some(f) = fspx(blob) { - return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2).user_sgprs); + return Some(super::CsInterface::from_rsrc2(f.threads, f.rsrc2)); } let sh = xbox::parse(blob)?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6))?; match interface(blob, &sh, f)? { - Mode::Compute(cs) => Some(cs.user_sgprs), + Mode::Compute(cs) => Some(cs), _ => None, } } @@ -937,7 +1051,12 @@ pub fn compute_user_sgprs(blob: &[u8]) -> Option { /// The HLSL and profile a console program compiles from at pipeline creation (for /// `xcl shaders --export-hlsl`: compile-time investigations outside a title). pub fn console_hlsl(blob: &[u8], stage: Stage, windows: u32, split_wave64: bool) -> Result<(String, &'static str), String> { - console_translation(blob, stage, 0, windows, split_wave64).map(|(t, p)| (t.hlsl, p)) + console_translation(blob, stage, 0, windows, split_wave64, false).map(|(t, p)| (t.hlsl, p)) +} + +pub fn console_dxil_noremap(blob: &[u8], split_wave64: bool, windows: u32) -> Result, String> { + let (t, profile) = console_translation(blob, Stage::Compute, 0, windows, split_wave64, true)?; + Ok(dxc::compile_cached(&t.hlsl, "main", profile)?.0) } /// A direct DXIL translation that fell back to the HLSL path: one structured log line @@ -954,6 +1073,9 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo let sh = xbox::parse(blob).ok_or("not a console shader container")?; let f = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == 6)).ok_or("no hardware CS variant")?; let Some(Mode::Compute(cs)) = interface(blob, &sh, f) else { return Err("not a compute interface".into()) }; + if direct_compute_needs_hlsl(&cs) { + return Err("multidimensional groups need the HLSL console-linear thread reorder".into()); + } let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; let wave64 = super::fssm_wave64(f, code); @@ -964,7 +1086,7 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo Ok(k) => { crate::gpu::dxil::coverage::record_translated("CS per-lane"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => { let reason = crate::gpu::dxil::coverage::record_fallback("CS per-lane", &e); @@ -972,9 +1094,22 @@ fn direct_compute(blob: &[u8], sampler_base: u32, windows: u32, split_wave64: bo } } } - let k = crate::gpu::dxil::kernel::translate_compute_on(code, o, &cs, split_wave64)?; + let k = crate::gpu::dxil::kernel::translate_compute(code, o, &cs)?; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: k.dispatch_chain, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) +} + +fn direct_compute_needs_hlsl(cs: &super::CsInterface) -> bool { + cs.threads[1] > 1 || cs.threads[2] > 1 +} + +#[cfg(test)] +#[test] +fn direct_compute_routes_multidimensional_thread_groups_to_hlsl() { + let cs = |threads| super::CsInterface { threads, user_sgprs: 0, tgid: [false; 3], tg_size: false, tid_components: 3 }; + assert!(!direct_compute_needs_hlsl(&cs([64, 1, 1]))); + assert!(direct_compute_needs_hlsl(&cs([8, 8, 1]))); + assert!(direct_compute_needs_hlsl(&cs([4, 4, 4]))); } /// `XCL_DXIL_DUMP=[,…]` (`[SHADER]` hashes, or `all`): writes the direct path's @@ -1009,16 +1144,16 @@ fn direct_graphics(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32) - _ => return Err("the shader stage does not match its slot in the PSO".into()), }; dump_direct(blob, &k.dxil); - Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }) } -pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool) -> Result<(super::Translation, &'static str), String> { +pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, windows: u32, split_wave64: bool, no_remap: bool) -> Result<(super::Translation, &'static str), String> { if let Some(f) = fspx(blob) { if stage != Stage::Compute { return Err("an FSPX (driver) container in a graphics slot".into()); } let cs = super::CsInterface::from_rsrc2(f.threads, f.rsrc2); - let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(f.code, &Options { mode: Mode::Compute(cs), wave64: super::detect_wave64(f.code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, no_remap, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1047,7 +1182,7 @@ pub(crate) fn console_translation(blob: &[u8], stage: Stage, sampler_base: u32, }; let p = f.programs.first().ok_or("FSSM without a program")?; let code = &f.data[p.offset..p.offset + p.len]; - let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, ..Default::default() })?; + let t = translate(code, &Options { mode, wave64: super::fssm_wave64(f, code), split_wave64, static_sampler_base: sampler_base, mem_windows: windows, no_remap, ..Default::default() })?; if !t.complete() { let missing: Vec<&String> = t.unsupported.keys().collect(); return Err(format!("incomplete translation, missing: {missing:?}")); @@ -1084,7 +1219,7 @@ fn finish_two_pass(t: super::Translation, record: super::MsInterface, ps: Option return Err(format!("incomplete translation, missing: {missing:?}")); } let cs = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers }, record, ps) + finish_two_pass_compiled(Compiled { dispatch_chain: None, dxil: cs, samplers: t.static_samplers, dispatch_remap: None }, record, ps) } fn compile_console_mesh( @@ -1110,7 +1245,7 @@ fn compile_console_mesh( Ok(k) => { crate::gpu::dxil::coverage::record_translated("MS"); dump_direct(blob, &k.dxil); - return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers }); + return Ok(Compiled { dispatch_chain: None, dxil: k.dxil, samplers: k.static_samplers, dispatch_remap: None }); } Err(e) => direct_fallback("MS", &e), } @@ -1121,7 +1256,7 @@ fn compile_console_mesh( return Err(format!("incomplete translation, missing: {missing:?}")); } let dxil = dxc::compile_cached(&t.hlsl, "main", "cs_6_6")?.0; - Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers }) + Ok(Compiled { dispatch_chain: None, dxil, samplers: t.static_samplers, dispatch_remap: None }) } fn console_mesh_with( @@ -1165,7 +1300,7 @@ fn console_mesh_with( /// The mesh-shader (NGG) program of a console MS container; the pass-through carries what /// the pixel shader `ps` (its container: console or PC) reads. pub fn console_mesh(blob: &[u8], ps: Option<&[u8]>, split_wave64: bool) -> Result { - let windows = mem_windows(); + let windows = windows_for_stage(mem_windows(), Stage::Mesh); let dir = dxc::cache_dir(); console_mesh_with(blob, ps, split_wave64, windows, &dir, shader_cache(), |code, ms, wave64| { compile_console_mesh(blob, code, ms, wave64, windows, split_wave64) @@ -1221,8 +1356,9 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b let (code, g) = super::geometry_program(vs, gs)?; let record = g.record(); // `XCL_DIRECT_DXIL=1`: the compute pass through the direct DXIL translator (HLSL fallback) + let windows = windows_for_stage(mem_windows(), Stage::Mesh); if crate::gpu::dxil::kernel::enabled() { - let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: mem_windows(), sampler_base: 0 }; + let o = crate::gpu::dxil::kernel::KernelOptions { wave64: true, split: split_wave64, mem_windows: windows, sampler_base: 0 }; match crate::gpu::dxil::kernel::translate_geometry(&code, o, &g) { Ok(k) => { crate::gpu::dxil::coverage::record_translated("GS"); @@ -1234,7 +1370,7 @@ pub fn console_geometry(vs: &[u8], gs: &[u8], ps: Option<&[u8]>, split_wave64: b Err(e) => direct_fallback("GS", &e), } } - let translation = super::translate_geometry(&code, g, split_wave64, mem_windows())?; + let translation = super::translate_geometry(&code, g, split_wave64, windows)?; finish_two_pass(translation, record, ps) } @@ -1282,7 +1418,15 @@ pub fn static_sampler_desc(k: u32, (w, comparison): &StaticSampler) -> D3D12_STA /// The ABI root signature with the pipeline's static samplers (registers 0.., space 1). pub fn abi_root_signature_with(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler]) -> Result { - abi_signature(dev, graphics, samplers, false) + abi_signature(dev, graphics, samplers, None) +} + +/// The per-dispatch slab data used by a split compute pipeline. Direct command-list dispatches +/// keep root constants; an indirect-only pipeline can use a root CBV without changing their ABI. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ChainSlabBinding { + RootConstants, + RootCbv, } /// Record all piece dispatches after the six common root views have been bound. @@ -1328,11 +1472,181 @@ pub(crate) unsafe fn record_dispatch_chain<'a>( } } +/// One round's root-CBV constants, padded to D3D12's 256-byte CBV alignment. Its Dispatch +/// arguments begin after the eight words and are shared by every piece in that round. +pub(crate) const CHAIN_COMMAND_BYTES: u32 = 256; +pub(crate) const CHAIN_DISPATCH_AT: u64 = 32; + +pub(crate) fn dispatch_command_signature(dev: &ID3D12Device) -> Result { + static MADE: Mutex> = Mutex::new(None); + let mut made = MADE.lock().unwrap(); + if let Some((_, sig)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok(sig.clone()); + } + let arg = D3D12_INDIRECT_ARGUMENT_DESC { Type: D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH, ..Default::default() }; + let desc = D3D12_COMMAND_SIGNATURE_DESC { ByteStride: 12, NumArgumentDescs: 1, pArgumentDescs: &arg, NodeMask: 0 }; + let mut sig = None; + unsafe { dev.CreateCommandSignature(&desc, None, &mut sig) }.map_err(|e| format!("CreateCommandSignature: {e}"))?; + let sig: ID3D12CommandSignature = sig.ok_or("CreateCommandSignature")?; + *made = Some((windows::core::Interface::as_raw(dev) as usize, sig.clone())); + Ok(sig) +} + +const INDIRECT_SLICER: &str = r#" +#define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)" +cbuffer C : register(b0) { uint rounds; uint most; }; +ByteAddressBuffer args : register(t0); +RWByteAddressBuffer cmds : register(u0); +void put(uint r, uint3 n, uint3 o) { + uint at = r * 256; + cmds.Store4(at, uint4(n, 0)); + cmds.Store4(at + 16, uint4(o, 0)); + cmds.Store3(at + 32, n); +} +[RootSignature(RS)] +[numthreads(1, 1, 1)] +void main() { + uint3 g = min(args.Load3(0), 65535); + uint3 s; + s.x = min(g.x, max(most, 1)); + s.y = s.x == g.x ? min(g.y, max(most / max(g.x, 1), 1)) : 1; + s.z = s.x == g.x && s.y == g.y ? min(g.z, max(most / max(g.x, 1) / max(g.y, 1), 1)) : 1; + uint3 c = (g + s - 1) / s; + bool partial = any(g == 0) ? false : c.x > rounds || c.y > rounds / max(c.x, 1) || c.z > rounds / max(c.x * c.y, 1); + uint r = 0; + if (!partial && all(g != 0)) + for (uint oz = 0; oz < g.z; oz += s.z) + for (uint oy = 0; oy < g.y; oy += s.y) + for (uint ox = 0; ox < g.x; ox += s.x) { + uint3 o = uint3(ox, oy, oz); + put(r++, min(s, g - o), o); + } + for (; r < rounds; r++) put(r, 0, 0); + uint at = rounds * 256; + cmds.Store3(at, partial ? g : 0); +} +"#; + +pub(crate) fn chain_tail_offset(rounds: u32) -> u64 { + u64::from(rounds) * u64::from(CHAIN_COMMAND_BYTES) +} + +fn indirect_slicer(dev: &ID3D12Device) -> Result<(ID3D12RootSignature, ID3D12PipelineState), String> { + static MADE: Mutex> = Mutex::new(None); + let mut made = MADE.lock().unwrap(); + if let Some((_, rs, pso)) = made.as_ref().filter(|m| m.0 == windows::core::Interface::as_raw(dev) as usize) { + return Ok((rs.clone(), pso.clone())); + } + let dxil = super::dxc::compile(INDIRECT_SLICER, "main", "cs_6_0", &[])?; + unsafe { + let rs: ID3D12RootSignature = dev.CreateRootSignature(0, &dxil).map_err(|e| format!("indirect slicer root signature: {e}"))?; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; + let pso: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).map_err(|e| format!("indirect slicer pipeline: {e}"))?; + *made = Some((windows::core::Interface::as_raw(dev) as usize, rs.clone(), pso.clone())); + Ok((rs, pso)) + } +} + +#[cfg(test)] +pub(crate) unsafe fn chain_commands_buffer(dev: &ID3D12Device, rounds: u32) -> Option { + chain_commands_storage(dev, chain_tail_offset(rounds) + 12) +} + +pub(crate) unsafe fn chain_commands_storage(dev: &ID3D12Device, bytes: u64) -> Option { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: bytes, Height: 1, DepthOrArraySize: 1, MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() + }; + let mut resource = None; + dev.CreateCommittedResource(&D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, CreationNodeMask: 1, VisibleNodeMask: 1, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, None, &mut resource).ok()?; + resource +} + +pub(crate) unsafe fn record_indirect_slicer( + list: &ID3D12GraphicsCommandList, args: u64, rounds: u32, most: u64, out: &ID3D12Resource, +) -> Result<(), String> { + let mut dev = None; + list.GetDevice(&mut dev).map_err(|e| e.to_string())?; + let (rs, pso) = indirect_slicer(&dev.ok_or("device")?)?; + let constants = [rounds, most.min(u64::from(u32::MAX)) as u32]; + list.SetComputeRootSignature(&rs); + list.SetPipelineState(&pso); + list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0); + list.SetComputeRootShaderResourceView(1, args); + list.SetComputeRootUnorderedAccessView(2, out.GetGPUVirtualAddress()); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + list.Dispatch(1, 1, 1); + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(out), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + StateAfter: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER }) } }]); + Ok(()) +} + +/// Complete the command-storage state cycle. A closed list can then be submitted repeatedly, and +/// another indirect dispatch recorded later on this list can overwrite the same commands at zero. +pub(crate) unsafe fn restore_indirect_commands(list: &ID3D12GraphicsCommandList, commands: &ID3D12Resource) { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(commands), Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + StateBefore: D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, + StateAfter: D3D12_RESOURCE_STATE_UNORDERED_ACCESS }) } }]); +} + +pub(crate) unsafe fn record_dispatch_chain_indirect<'a>( + list: &ID3D12GraphicsCommandList, sig: &ID3D12CommandSignature, commands: &ID3D12Resource, rounds: u32, + scratch: &ID3D12Resource, pieces: impl IntoIterator + Clone, +) { + list.SetComputeRootUnorderedAccessView(6, scratch.GetGPUVirtualAddress()); + for r in 0..rounds { + let offset = u64::from(r) * u64::from(CHAIN_COMMAND_BYTES); + list.SetComputeRootConstantBufferView(7, commands.GetGPUVirtualAddress() + offset); + for piece in pieces.clone() { + list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER { Type: D3D12_RESOURCE_BARRIER_TYPE_UAV, Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER { pResource: std::mem::ManuallyDrop::new(None) }) } }]); + list.SetPipelineState(piece); + list.ExecuteIndirect(sig, 1, commands, offset + CHAIN_DISPATCH_AT, None::<&ID3D12Resource>, 0); + } + } +} + pub(crate) fn dispatch_chain_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result { - abi_signature(dev, false, samplers, true) + abi_signature(dev, false, samplers, Some(ChainSlabBinding::RootConstants)) +} + +/// A split-pipeline root signature specialized for indirect dispatch. Its pipeline states must +/// remain separate from those made by `dispatch_chain_root_signature` because their root ABIs differ. +#[allow(dead_code)] +pub(crate) fn dispatch_chain_indirect_root_signature(dev: &ID3D12Device, samplers: &[StaticSampler]) -> Result { + abi_signature(dev, false, samplers, Some(ChainSlabBinding::RootCbv)) } -fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: bool) -> Result { +fn chain_slab_parameter(binding: ChainSlabBinding) -> D3D12_ROOT_PARAMETER1 { + let (ty, value) = match binding { + ChainSlabBinding::RootConstants => ( + D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { + ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 8, + } }, + ), + ChainSlabBinding::RootCbv => ( + D3D12_ROOT_PARAMETER_TYPE_CBV, + D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { + ShaderRegister: 0, RegisterSpace: 2, Flags: D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, + } }, + ), + }; + D3D12_ROOT_PARAMETER1 { ParameterType: ty, Anonymous: value, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL } +} + +fn abi_signature( + dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], split: Option, +) -> Result { let statics: Vec = samplers.iter().enumerate().map(|(k, s)| static_sampler_desc(k as u32, s)).collect(); unsafe { // u0 io, u1 res, u2..u5 the memory windows (`gpu::uma`; unused ones need no binding) @@ -1345,7 +1659,7 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }) .collect(); - if split { + if let Some(binding) = split { params.push(D3D12_ROOT_PARAMETER1 { ParameterType: D3D12_ROOT_PARAMETER_TYPE_UAV, Anonymous: D3D12_ROOT_PARAMETER1_0 { Descriptor: D3D12_ROOT_DESCRIPTOR1 { @@ -1353,13 +1667,7 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], } }, ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, }); - params.push(D3D12_ROOT_PARAMETER1 { - ParameterType: D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, - Anonymous: D3D12_ROOT_PARAMETER1_0 { Constants: D3D12_ROOT_CONSTANTS { - ShaderRegister: 0, RegisterSpace: 2, Num32BitValues: 8, - } }, - ShaderVisibility: D3D12_SHADER_VISIBILITY_ALL, - }); + params.push(chain_slab_parameter(binding)); } let mut flags = D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED | D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED; if graphics { @@ -1386,7 +1694,37 @@ fn abi_signature(dev: &ID3D12Device, graphics: bool, samplers: &[StaticSampler], #[cfg(test)] mod slab_tests { - use super::dispatch_slabs; + use super::{chain_slab_parameter, chain_tail_offset, dispatch_slabs, ChainSlabBinding, CHAIN_COMMAND_BYTES, CHAIN_DISPATCH_AT}; + use windows::Win32::Graphics::Direct3D12::{ + D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS, + D3D12_ROOT_PARAMETER_TYPE_CBV, + }; + + #[test] + fn direct_and_indirect_chain_slab_parameters_have_distinct_abis() { + let direct = chain_slab_parameter(ChainSlabBinding::RootConstants); + let indirect = chain_slab_parameter(ChainSlabBinding::RootCbv); + assert_eq!(direct.ParameterType, D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS); + assert_eq!(indirect.ParameterType, D3D12_ROOT_PARAMETER_TYPE_CBV); + unsafe { + assert_eq!(direct.Anonymous.Constants.ShaderRegister, 0); + assert_eq!(direct.Anonymous.Constants.RegisterSpace, 2); + assert_eq!(direct.Anonymous.Constants.Num32BitValues, 8); + assert_eq!(indirect.Anonymous.Descriptor.ShaderRegister, 0); + assert_eq!(indirect.Anonymous.Descriptor.RegisterSpace, 2); + assert_eq!(indirect.Anonymous.Descriptor.Flags, D3D12_ROOT_DESCRIPTOR_FLAG_DATA_VOLATILE); + } + } + + #[test] + fn indirect_whole_arguments_follow_aligned_piece_commands() { + for rounds in [1, 16, 1024] { + let tail = chain_tail_offset(rounds); + assert_eq!(tail, u64::from(rounds * CHAIN_COMMAND_BYTES)); + assert_eq!(tail % 256, 0); + assert_eq!(CHAIN_DISPATCH_AT, 32); + } + } #[test] fn slabs_cover_a_dispatch_once_within_their_size() { @@ -1416,6 +1754,15 @@ mod slab_tests { mod shader_cache_tests { use super::*; + #[test] + fn heap_flat_partitions_only_compute_cache_keys() { + let windows = 4 | super::super::HEAP_WINDOWS | super::super::HEAP_FLAT; + assert_eq!(windows_for_stage(windows, Stage::Compute), windows); + for stage in [Stage::Vertex, Stage::Pixel, Stage::Mesh] { + assert_eq!(windows_for_stage(windows, stage), windows & !super::super::HEAP_FLAT); + } + } + #[test] fn translated_identity_tracks_sources_and_dxc() { let built_source = env!("XCL_TRANSLATOR_SOURCE_ID"); @@ -1451,10 +1798,10 @@ mod shader_cache_tests { fn translations_on_disk_need_the_same_bytes_and_identity() { let dir = std::env::temp_dir().join(format!("xcl-translated-{}", std::process::id())); let path = dir.join("t.bin"); - let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)] }; + let c = Compiled { dispatch_chain: None, dxil: synthetic_dxil(5), samplers: vec![([7, 8, 9, 10], true), ([1, 2, 3, 4], false)], dispatch_remap: Some((2, 1)) }; translated::store_in(&path, 42, b"console", &c); let back = translated::load_in(&path, 42, b"console").expect("stored"); - assert_eq!((back.dxil, back.samplers), (c.dxil.clone(), c.samplers.clone())); + assert_eq!((back.dxil, back.samplers, back.dispatch_remap), (c.dxil.clone(), c.samplers.clone(), c.dispatch_remap)); assert!(translated::load_in(&path, 43, b"console").is_none(), "another identity"); assert!(translated::load_in(&path, 42, b"consolf").is_none(), "other bytes"); let full = std::fs::read(&path).unwrap(); @@ -1687,7 +2034,7 @@ mod shader_cache_tests { // Store a valid entry first, then corrupt only the DXIL payload while keeping the // XCLTRAN2 header and payload length intact (e.g. zeroed blocks after a hard reset). - let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)] }; + let valid = Compiled { dispatch_chain: None, dxil: synthetic_dxil(1), samplers: vec![([1, 2, 3, 4], false)], dispatch_remap: None }; translated::store_in(&path, ident, blob, &valid); let mut raw = std::fs::read(&path).unwrap(); let dxil_start = raw.len() - valid.dxil.len(); @@ -1706,7 +2053,7 @@ mod shader_cache_tests { let mut calls = 0usize; let rebuilt = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { calls += 1; - Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)] }) + Ok(Compiled { dispatch_chain: None, dxil: synthetic_dxil(9), samplers: vec![([5, 6, 7, 8], true)], dispatch_remap: None }) }) .unwrap(); assert_eq!(calls, 1); @@ -1730,20 +2077,20 @@ mod shader_cache_tests { let path = translated::file(&dir, ident, blob, Stage::Compute, 0, 1, false); let err = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }) }) .err() .expect("invalid fresh DXIL must be rejected"); assert!(err.contains("invalid DXIL container"), "{err}"); assert!(!path.exists(), "invalid fresh DXIL must not be written to disk"); - translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new() }); + translated::store_in(&path, ident, blob, &Compiled { dispatch_chain: None, dxil: b"not DXIL".to_vec(), samplers: Vec::new(), dispatch_remap: None }); assert!(!path.exists(), "store_in must not write an invalid DXIL container"); // A real container emitted by the direct DXIL backend must be accepted and cached. let real_direct = crate::gpu::dxil::shader::Shader::new(crate::gpu::dxil::container::Stage::Compute, (6, 6)).finish([1, 1, 1], None); let stored = translated::cached_in(&dir, ident, blob, Stage::Compute, 0, 1, false, || { - Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new() }) + Ok(Compiled { dispatch_chain: None, dxil: real_direct.clone(), samplers: Vec::new(), dispatch_remap: None }) }) .unwrap(); assert_eq!(stored.dxil, real_direct); @@ -1760,9 +2107,75 @@ mod shader_cache_tests { dispatch_chain: None, dxil: synthetic_dxil(marker), samplers: vec![([marker as u32; 4], false)], + dispatch_remap: None, } } + #[test] + fn translated_cache_reuses_unsplit_read_buffer() { + let dir = std::env::temp_dir().join(format!("xcl-translated-buffer-{}", std::process::id())); + let path = dir.join("entry"); + let blob = b"console-buffer"; + for count in [0, 1, 65] { + let mut expected = compiled(7); + expected.samplers = (0..count).map(|i| ([i, i + 1, i + 2, i + 3], i % 2 != 0)).collect(); + translated::store_in(&path, 42, blob, &expected); + let raw = std::fs::read(&path).unwrap(); + let (ptr, capacity) = (raw.as_ptr(), raw.capacity()); + let actual = translated::decode_entry(raw, 42, blob).unwrap(); + assert_eq!(actual.dxil, expected.dxil); + assert_eq!(actual.samplers, expected.samplers); + assert!(actual.dispatch_chain.is_none()); + assert_eq!(actual.dxil.as_ptr(), ptr, "reuse the file allocation"); + assert_eq!(actual.dxil.capacity(), capacity); + } + std::fs::remove_dir_all(dir).unwrap(); + } + + #[test] + fn translated_cache_buffer_decode_preserves_validation_and_split_entries() { + let dir = std::env::temp_dir().join(format!("xcl-translated-decode-{}", std::process::id())); + let path = dir.join("entry"); + let blob = b"console-decode"; + let mut expected = compiled(9); + translated::store_in(&path, 42, blob, &expected); + let raw = std::fs::read(&path).unwrap(); + for len in 0..raw.len() { + assert!(translated::decode_entry(raw[..len].to_vec(), 42, blob).is_none(), "truncated at {len}"); + } + for count in 1..=16 { + let mut trailing = raw.clone(); + trailing.resize(raw.len() + count, 0); + assert!(translated::decode_entry(trailing, 42, blob).is_none(), "{count} trailing bytes"); + } + + let chain = Arc::new(crate::gpu::dxil::kernel::DispatchChain { + dwords_per_group: 8, + pieces: vec![synthetic_dxil(2), synthetic_dxil(3)], + }); + expected.dispatch_chain = Some(chain.clone()); + translated::store_in(&path, 42, blob, &expected); + let split = std::fs::read(&path).unwrap(); + let actual = translated::load_in(&path, 42, blob).unwrap(); + assert_eq!(actual.dxil, expected.dxil); + assert_eq!(actual.samplers, expected.samplers); + let actual_chain = actual.dispatch_chain.unwrap(); + assert_eq!(actual_chain.dwords_per_group, chain.dwords_per_group); + assert_eq!(actual_chain.pieces, chain.pieces); + for len in raw.len() + 1..split.len() { + assert!(translated::decode_entry(split[..len].to_vec(), 42, blob).is_none(), "split truncated at {len}"); + } + for offset in [0, 4, 8, 12] { + let mut corrupt = split.clone(); + corrupt[raw.len() + offset..raw.len() + offset + 4].fill(0); + assert!(translated::decode_entry(corrupt, 42, blob).is_none(), "invalid split field at {offset}"); + } + let mut trailing = split; + trailing.push(0); + assert!(translated::decode_entry(trailing, 42, blob).is_none()); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] fn shader_cache_skips_repeated_translation_and_disk_lookups() { let cache = Mutex::new(ShaderCache::new(1 << 20)); @@ -1836,6 +2249,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil, samplers: Vec::new(), + dispatch_remap: None, }) }) }); @@ -1870,6 +2284,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil: vec![0; limit + 1], samplers: Vec::new(), + dispatch_remap: None, }), ); assert!(cache.get(&key(4), b"d").is_none()); @@ -1883,6 +2298,22 @@ mod shader_cache_tests { assert!(cache.get(&key(0), b"a").is_none()); } + #[test] + fn shader_cache_charges_split_piece_capacity_on_insert() { + let mut split = compiled(7); + split.dispatch_chain = Some(Arc::new(crate::gpu::dxil::kernel::DispatchChain { + dwords_per_group: 8, + pieces: vec![vec![0u8; 4096], vec![0u8; 2048]], + })); + let split = Arc::new(split); + let entry = ShaderEntry { key: key(1), blob: b"split".to_vec(), shader: split.clone(), gen: 0 }; + let piece_bytes: usize = split.dispatch_chain.as_ref().unwrap().pieces.iter().map(Vec::capacity).sum(); + let mut cache = ShaderCache::new(entry.bytes() - piece_bytes); + cache.insert(key(1), b"split", split); + assert!(cache.entries.is_empty(), "a split shader larger than the byte budget is not admitted"); + assert_eq!(cache.bytes, 0); + } + #[test] fn shader_cache_coalesces_concurrent_same_key_compiles() { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -2045,6 +2476,7 @@ mod shader_cache_tests { dispatch_chain: None, dxil, samplers: Vec::new(), + dispatch_remap: None, }) }) }); @@ -2133,7 +2565,7 @@ mod shader_cache_tests { let (res, missed) = dxc::cached_only(|| { translated::cached_in(&dir, ident_v1, deferred_blob, Stage::Compute, 0, 1, false, || { let dxil = dxc::compile_cached_in(&dir, "deferred probe", "main", "cs_6_6")?.0; - Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None }) + Ok(Compiled { dxil, samplers: Vec::new(), dispatch_chain: None, dispatch_remap: None }) }) }); assert!(res.is_err() && missed); diff --git a/crates/xcl/src/gpu/recomp/runner.rs b/crates/xcl/src/gpu/recomp/runner.rs index 34b5c65201..e2f49929fd 100644 --- a/crates/xcl/src/gpu/recomp/runner.rs +++ b/crates/xcl/src/gpu/recomp/runner.rs @@ -1532,7 +1532,7 @@ fn run_in_region(dxil: &[u8], state: &KernelState, arena: &Arena) -> Result Result, Some(&raw_window_uav(size as u64)), h); } + for idx in [super::MEM_NULL_LOAD, super::MEM_NULL_STORE] { + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += idx as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(4)), h); + } list.SetDescriptorHeaps(&[Some(dh.clone())]); list.SetComputeRootSignature(&gpu.rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); @@ -1607,6 +1612,14 @@ pub fn try_create_texture(desc: &D3D12_RESOURCE_DESC) -> Result<(), String> { /// A compute shader with the console dispatch ABI (`Mode::Compute`): `groups` thread groups, /// u0 = user SGPRs, u2 = flat memory. Returns the memory afterwards. pub fn dispatch(dxil: &[u8], groups: [u32; 3], sgprs: &[u32], mem: &[u32]) -> Result, String> { + dispatch_remapped(dxil, groups, None, sgprs, mem) +} + +pub fn dispatch_remapped(dxil: &[u8], mut groups: [u32; 3], remap: Option<(u32, u32)>, sgprs: &[u32], mem: &[u32]) -> Result, String> { + if let Some((ratio, dim)) = remap { + let count = groups.get_mut(dim as usize).ok_or("invalid remap dimension")?; + *count = count.checked_mul(ratio).ok_or("remapped dispatch overflows")?; + } let mut g = GPU.lock().unwrap(); let gpu = g.get_or_insert_with(init).as_mut().map_err(|x| x.clone())?; let pso: ID3D12PipelineState = unsafe { @@ -1783,7 +1796,7 @@ fn dispatch_with( let dh: ID3D12DescriptorHeap = dev .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, - NumDescriptors: super::MEM_HEAP_BASE + win_count as u32, + NumDescriptors: (super::MEM_HEAP_BASE + win_count as u32).max(super::MEM_NULL_STORE + 1), Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, NodeMask: 0, }) @@ -1794,6 +1807,11 @@ fn dispatch_with( h.ptr += (super::MEM_HEAP_BASE as usize + k) * inc; dev.CreateUnorderedAccessView(&mem_buf, None::<&ID3D12Resource>, Some(&raw_window_uav(mem_bytes)), h); } + for idx in [super::MEM_NULL_LOAD, super::MEM_NULL_STORE] { + let mut h = dh.GetCPUDescriptorHandleForHeapStart(); + h.ptr += idx as usize * inc; + dev.CreateUnorderedAccessView(None::<&ID3D12Resource>, None::<&ID3D12Resource>, Some(&raw_window_uav(4)), h); + } list.SetDescriptorHeaps(&[Some(dh.clone()), Some(bound._heaps[1].clone())]); list.SetComputeRootSignature(rs); list.SetComputeRootUnorderedAccessView(0, io_buf.GetGPUVirtualAddress()); diff --git a/crates/xcl/src/gpu/recomp/tests.rs b/crates/xcl/src/gpu/recomp/tests.rs index 0b018edc36..747f1542f2 100644 --- a/crates/xcl/src/gpu/recomp/tests.rs +++ b/crates/xcl/src/gpu/recomp/tests.rs @@ -72,10 +72,13 @@ fn kernel_wave(code: &[u8], wave64: bool) -> (Vec, Vec) { /// `XCL_DIRECT_DXIL=1`: the direct DXIL translator's kernel for a kernel-mode program with /// one memory window (else `hlsl`, the HLSL path's container). +fn direct_enabled(opt: &Options) -> bool { + runner::direct_dxil() && opt.mem_windows <= 4 && (opt.hw_wave == 0 || (opt.hw_wave == 32 && !opt.wave64)) +} + fn direct_or(code: &[u8], opt: &Options, hlsl: Vec) -> Vec { use crate::gpu::dxil::kernel::{translate, translate_compute, KernelOptions}; - let windows = opt.mem_windows <= 4 && (opt.hw_wave == 0 || (opt.hw_wave == 32 && !opt.wave64)); - if !runner::direct_dxil() || !windows { + if !direct_enabled(opt) { return hlsl; } let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64()); @@ -84,8 +87,18 @@ fn direct_or(code: &[u8], opt: &Options, hlsl: Vec) -> Vec { let o = KernelOptions { wave64: opt.wave64, split, mem_windows, sampler_base: opt.static_sampler_base }; match &opt.mode { Mode::Kernel => translate(code, o).unwrap_or_else(|e| panic!("direct DXIL: {e}")), - Mode::Compute(cs) => translate_compute(code, o, cs).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, - Mode::Mesh(ms) => crate::gpu::dxil::kernel::translate_mesh(code, o, ms).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, + // (a group barrier in a group of several hardware waves is left to the HLSL path, as + // the runtime's fallback does: `dxil::lower`'s s_barrier) + Mode::Compute(cs) => match translate_compute(code, o, cs) { + Ok(k) => k.dxil, + Err(e) if e.contains("s_barrier in a group of several hardware waves") => hlsl, + Err(e) => panic!("direct DXIL: {e}"), + }, + Mode::Mesh(ms) => match crate::gpu::dxil::kernel::translate_mesh(code, o, ms) { + Ok(k) => k.dxil, + Err(e) if e.contains("s_barrier in a group of several hardware waves") => hlsl, + Err(e) => panic!("direct DXIL: {e}"), + }, Mode::Vertex(vs) => crate::gpu::dxil::kernel::translate_vertex(code, o, vs).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, Mode::Pixel(ps) => crate::gpu::dxil::kernel::translate_pixel(code, o, ps).unwrap_or_else(|e| panic!("direct DXIL: {e}")).dxil, _ => hlsl, @@ -4066,6 +4079,14 @@ fn gpu_memory_windows_from_the_heap() { memory_windows_above_4_gib(true); } +#[test] +fn heap_flat_cache_flag_does_not_change_hlsl_translation() { + let p = prog(&[("S_ENDPGM", "ENC_SOPP", &[], None)]); + let guarded = translate(&p, &Options { mem_windows: 4 | super::HEAP_WINDOWS, ..Default::default() }).unwrap(); + let flat = translate(&p, &Options { mem_windows: 4 | super::HEAP_WINDOWS | super::HEAP_FLAT, ..Default::default() }).unwrap(); + assert_eq!(flat.hlsl, guarded.hlsl, "HEAP_FLAT distinguishes direct-DXIL cache entries but is ignored by HLSL"); +} + fn memory_windows_above_4_gib(heap: bool) { if !gpu_ready() { return; @@ -5175,10 +5196,19 @@ fn gpu_compute_mode_dispatch_abi() { ("V_MOV_B32", "ENC_VOP1", &[("VDST", 10), ("SRC0", 128)], None), ("GLOBAL_STORE_DWORDX2", "ENC_FLAT_GLBL", &[("ADDR", 9), ("DATA", 11), ("SADDR", 0x7D)], None), ]); - let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); + let opt = on_gpu(Options { mode: Mode::Compute(cs.clone()), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); + let hlsl_dxil = dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}")); + let split = opt.wave64 && (opt.split_wave64 || runner::split_wave64()); + let direct_dxil = crate::gpu::dxil::kernel::translate_compute( + &p, + crate::gpu::dxil::kernel::KernelOptions { wave64: opt.wave64, split, mem_windows: opt.mem_windows, sampler_base: opt.static_sampler_base }, + &cs, + ) + .unwrap_or_else(|e| panic!("direct DXIL: {e}")) + .dxil; + let dxil = if direct_enabled(&opt) { direct_dxil.clone() } else { hlsl_dxil.clone() }; let (w, h, base) = (32usize, 24usize, 0x100usize); let mut io = vec![0u32; 128]; io[0] = base as u32; @@ -5193,6 +5223,24 @@ fn gpu_compute_mode_dispatch_abi() { assert_eq!(out[at + 1], (px | py << 16) as u32, "({x}, {y}): value of thread {} through LDS", 127 - i); } } + + // DispatchX thread limits seed EXEC in both backends. The hardware groups still contain + // 32x24 threads, but only the 20x17 console dispatch rectangle may reach memory. + for (backend, dxil) in [("HLSL", hlsl_dxil), ("direct DXIL", direct_dxil)] { + let mut limited_io = io.clone(); + limited_io[super::IO_THREAD_LIMIT[0]] = 20; + limited_io[super::IO_THREAD_LIMIT[1]] = 17; + let sentinel = 0xA5A5_5A5Au32; + let out = runner::dispatch(&dxil, [2, 3, 1], &limited_io, &vec![sentinel; (base + w * h * 8) / 4]).unwrap(); + for y in 0..h { + for x in 0..w { + let at = (base + (y * w + x) * 8) / 4; + let written = x < 20 && y < 17; + assert_eq!(out[at] != sentinel, written, "{backend} ({x}, {y}) own write"); + assert_eq!(out[at + 1] != sentinel, written, "{backend} ({x}, {y}) partner write"); + } + } + } } /// A wave32 program in a 64-lane hardware wave (what VS / PS may get from the driver): the @@ -7305,6 +7353,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { assert_eq!(t.hlsl.matches("= xcl_x_ballot(and(").count(), 1, "the v_cmp: read whole by the odd waves"); assert_eq!(t.hlsl.matches("= xcl_x_ballot_local(and(").count(), 2, "the carries"); } + let remap = if direct_enabled(&opt) { None } else { t.dispatch_remap }; let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; let mut io = vec![0u32; 128]; @@ -7312,7 +7361,7 @@ fn gpu_split_wave64_local_and_exchanged_masks_in_diverging_waves() { io[1] = dims[0]; io[2] = dims[0] * dims[1]; let groups = 3usize; - let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 256 * 16) / 4]).unwrap(); + let out = runner::dispatch_remapped(&dxil, [groups as u32, 1, 1], remap, &io, &vec![0u32; (base + groups * 256 * 16) / 4]).unwrap(); for g in 0..groups { for tid in 0..threads as usize { let (w, l) = (tid / 64, (tid % 64) as u32); @@ -7380,9 +7429,10 @@ fn gpu_split_wave64_waves_diverge() { let opt = on_gpu(Options { mode: Mode::Compute(cs), wave64: true, ..Default::default() }); let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); - if runner::split_wave64() && std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") { + if runner::split_wave64() && t.dispatch_remap.is_none() && std::env::var("XCL_WAVE64_SPIN").map_or(true, |v| v.trim() != "0") { assert!(t.hlsl.contains("[WaveSize(32)]") && t.hlsl.contains("#define XCL_X_SPIN 1"), "{dims:?}"); } + let remap = if direct_enabled(&opt) { None } else { t.dispatch_remap }; let dxil = direct_or(&p, &opt, dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}"))); let base = 0x100usize; let mut io = vec![0u32; 128]; @@ -7390,7 +7440,7 @@ fn gpu_split_wave64_waves_diverge() { io[1] = dims[0]; io[2] = dims[0] * dims[1]; let groups = 3usize; - let out = runner::dispatch(&dxil, [groups as u32, 1, 1], &io, &vec![0u32; (base + groups * 256 * 8) / 4]).unwrap(); + let out = runner::dispatch_remapped(&dxil, [groups as u32, 1, 1], remap, &io, &vec![0u32; (base + groups * 256 * 8) / 4]).unwrap(); for g in 0..groups { for tid in 0..threads as usize { let (w, l) = (tid / 64, tid % 64); @@ -7403,6 +7453,73 @@ fn gpu_split_wave64_waves_diverge() { } } +#[test] +fn wave_local_remap_decision_and_console_ids() { + use super::{CsInterface, Mode, Options}; + let store = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None), + ]); + let translate_as = |code: &[u8], threads, tgid, no_remap| { + let cs = CsInterface { threads, user_sgprs: 2, tgid, tg_size: false, tid_components: 3 }; + translate(code, &Options { mode: Mode::Compute(cs), wave64: true, split_wave64: true, no_remap, ..Default::default() }).unwrap() + }; + for (threads, remap, shape, group_id) in [ + ([128, 1, 1], Some((2, 0)), "numthreads(64, 1, 1)", "gid.x / 2u"), + ([8, 16, 1], Some((2, 1)), "numthreads(8, 8, 1)", "gid.y / 2u"), + ([256, 1, 1], Some((4, 0)), "numthreads(64, 1, 1)", "gid.x / 4u"), + ] { + let t = translate_as(&store, threads, [true; 3], false); + assert_eq!(t.dispatch_remap, remap, "{threads:?}"); + assert!(t.hlsl.contains(shape) && t.hlsl.contains(group_id), "{threads:?}"); + assert!(t.hlsl.contains("#define XCL_X_SPIN 0"), "{threads:?}"); + } + let barrier = prog(&[("S_BARRIER", "ENC_SOPP", &[], None)]); + let lds = prog(&[("DS_WRITE_B32", "ENC_DS", &[("ADDR", 1), ("DATA0", 0)], None)]); + for (code, threads) in [(&store[..], [8, 8, 4]), (&store[..], [96, 1, 1]), (&barrier, [128, 1, 1]), (&lds, [128, 1, 1])] { + assert_eq!(translate_as(code, threads, [false; 3], false).dispatch_remap, None, "{threads:?}"); + } + let fallback = translate_as(&store, [128, 1, 1], [false; 3], true); + assert_eq!(fallback.dispatch_remap, None); + assert!(fallback.hlsl.contains("numthreads(128, 1, 1)") && fallback.hlsl.contains("#define XCL_X_SPIN 1")); +} + +#[test] +fn dispatch_thread_limits_seed_compute_exec_for_native_and_remapped_groups() { + use super::{CsInterface, Mode, Options}; + let p = prog(&[ + ("V_MOV_B32", "ENC_VOP1", &[("VDST", 7), ("SRC0", 128)], None), + ("GLOBAL_STORE_DWORD", "ENC_FLAT_GLBL", &[("ADDR", 6), ("DATA", 0), ("SADDR", 0x7D)], None), + ]); + let translated = |threads, split_wave64| { + translate( + &p, + &Options { + mode: Mode::Compute(CsInterface { threads, user_sgprs: 2, tgid: [true; 3], tg_size: false, tid_components: 3 }), + wave64: true, + split_wave64, + ..Default::default() + }, + ) + .unwrap() + }; + + let native = translated([8, 8, 1], false); + assert!(native.hlsl.contains("uint xcl_limit_x = io.Load(456u);")); + assert!(native.hlsl.contains("gid.x * 8u + gtid.x < xcl_limit_x")); + assert!(native.hlsl.contains("uint xcl_limit_y = io.Load(460u);")); + assert!(native.hlsl.contains("gid.y * 8u + gtid.y < xcl_limit_y")); + assert!(!native.hlsl.contains("xcl_limit_z"), "a one-thread axis is always whole"); + assert!(native.hlsl.contains("if (xcl_dispatch_limited)")); + assert!(native.hlsl.contains("ballot(xcl_dispatch_live)")); + assert!(native.hlsl.contains("ballot(true)"), "ordinary Dispatch keeps the original entry ballot"); + + let remapped = translated([128, 1, 1], true); + assert_eq!(remapped.dispatch_remap, Some((2, 0))); + assert!(remapped.hlsl.contains("(gid.x / 2u) * 128u + gtid.x < xcl_limit_x")); + assert!(remapped.hlsl.contains("xcl_x_ballot(xcl_dispatch_live)")); +} + /// What the split wave64 form costs (`cargo test --release -- --ignored bench_split_wave64 /// --nocapture`): a loop of a few VALU instructions and one mask (`v_cmp`, an exchange in the /// split form), plus a readfirstlane (another exchange) in the second variant, as a wave32 @@ -7510,8 +7627,9 @@ fn gpu_compute_tg_size_counts_a_partial_last_wave() { let t = translate(&p, &opt).unwrap(); assert!(t.complete(), "{:?}", t.unsupported_why); // `XCL_DIRECT_DXIL=1`: the direct translator's kernel, which sets up TG_SIZE on its own + let remap = if direct_enabled(&opt) { None } else { t.dispatch_remap }; let dxil = direct_or(&p, &opt, super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).unwrap_or_else(|e| panic!("{e}\n{}", t.hlsl))); - let mem = runner::dispatch(&dxil, [1, 1, 1], &[0u32; 128], &vec![0xFFFF_FFFFu32; threads as usize]).unwrap(); + let mem = runner::dispatch_remapped(&dxil, [1, 1, 1], remap, &[0u32; 128], &vec![0xFFFF_FFFFu32; threads as usize]).unwrap(); let waves = threads.div_ceil(lanes); for (k, &got) in mem.iter().take(threads as usize).enumerate() { assert_eq!(got, waves | (k as u32 / lanes) << 6, "{threads} threads, wave{lanes}: thread {k}"); @@ -9882,9 +10000,12 @@ fn compute_globallycoherent_only_when_needed() { // Direct DXIL backend: check the IsGloballyCoherent bit (0x4000) in annotateHandle properties // (RAW_BUFFER=11 | IsUAV=0x1000 = 4107 vs RAW_BUFFER=11 | IsUAV=0x1000 | IsGloballyCoherent=0x4000 = 20491). + // (the plain program in a group of one 32-lane wave: its s_barrier in a group of several + // hardware waves is left to the HLSL path) + let one_wave = super::CsInterface { threads: [32, 1, 1], ..cs.clone() }; for mw in [1u32, super::HEAP_WINDOWS | 2] { let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows: mw, sampler_base: 0 }; - let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &cs).unwrap(); + let plain_k = crate::gpu::dxil::kernel::translate_compute(&plain, o, &one_wave).unwrap(); let coh_k = crate::gpu::dxil::kernel::translate_compute(&coherent_cases[6].1, o, &cs).unwrap(); if super::dxc::location().is_ok() { let plain_dis = crate::gpu::dxil::validate::disassemble(&plain_k.dxil).unwrap(); diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index cde3561492..944457a32b 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -195,7 +195,8 @@ pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D1 let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; let staging = record_upload(dev, &list, res, subs, before, after)?; list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&list).map_err(err)?)]); + let list = windows::core::Interface::cast(&list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &list); let r = wait(dev, queue); drop(staging); r @@ -263,11 +264,24 @@ impl Uploader { } } +pub(crate) type UploadBatchItem = (ID3D12Resource, Vec, Vec); + /// Several uploads on one list, one wait: (resource, subresources, states) each – the states /// the texture is in and is left in: one for every subresource, or one per subresource (D3D12 /// order). A failure of one is returned with its index; the others still run. The texels go /// through the queue's kept upload buffer (`Uploader`). pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result, String> { + upload_batch_with_zero_mips(dev, queue, items, &[]) +} + +/// As `upload_batch`, with an optional mask per item for subresources already verified to be all +/// zero. The copies still run, but these subresources all source the same zeroed staging span. +pub(crate) unsafe fn upload_batch_with_zero_mips( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[UploadBatchItem], + zero_mips: &[Vec], +) -> Result, String> { if items.is_empty() { return Ok(Vec::new()); } @@ -278,35 +292,29 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items None => Uploader::new(dev)?, }; // where each texture's texels go in the upload buffer - let mut failed = Vec::new(); - let mut planned = Vec::with_capacity(items.len()); - let mut total = 0u64; - for (k, (res, subs, states)) in items.iter().enumerate() { - match layout(dev, res, subs, states, states) { - Ok(l) => { - let base = total.div_ceil(PLACEMENT) * PLACEMENT; - total = base + l.total; - planned.push((k, l, base)); - } - Err(e) => failed.push((k, e)), - } - } + let (failed, planned, zero) = plan_batch(dev, items, zero_mips)?; if planned.is_empty() { put_back(key, up); return Ok(failed); } - let (staging, mapped) = up.staging(dev, total)?; + let (staging, mapped) = up.staging(dev, zero.end)?; + clear_staging_span(mapped, &zero); up.alloc.Reset().map_err(err)?; up.list.Reset(&up.alloc, None).map_err(err)?; - for (k, l, base) in &planned { - let (res, subs, states) = &items[*k]; - record_into(&up.list, res, subs, l, states, states, &staging, mapped, *base); + for (k, l, offsets) in planned { + let (res, subs, states) = &items[k]; + record_into(&up.list, res, subs, &l, states, states, &staging, mapped, offsets); } up.list.Close().map_err(err)?; - queue.ExecuteCommandLists(&[Some(windows::core::Interface::cast(&up.list).map_err(err)?)]); + let list = windows::core::Interface::cast(&up.list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &list); up.value += 1; let copy_error = |e| format!("texture copy: {e}"); - queue.Signal(&up.fence, up.value).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; + if let Err(e) = crate::hle::d3d12x::real::native_queue_signal(queue, &up.fence, up.value) { + let signal = copy_error(fence::api_error(dev, "Signal", e)); + drop_after_wait(up, wait(dev, queue))?; + return Err(signal); + } if let Err(e) = fence::wait(&up.fence, up.value, dev, None, 10_000) { // the GPU may still read the upload buffer and run the list: they stay alive (a fresh // uploader next time) – freeing them under the GPU removed the device @@ -317,6 +325,78 @@ pub unsafe fn upload_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items Ok(failed) } +unsafe fn plan_batch<'a>( + dev: &ID3D12Device, + items: &[UploadBatchItem], + zero_mips: &'a [Vec], +) -> Result<(Vec<(usize, String)>, Vec<(usize, Layout, StagingOffsets<'a>)>, std::ops::Range), String> { + let mut failed = Vec::new(); + let mut laid_out = Vec::with_capacity(items.len()); + for (k, (res, subs, states)) in items.iter().enumerate() { + let zeros = zero_mips.get(k).map(Vec::as_slice).unwrap_or_default(); + match layout(dev, res, subs, states, states) { + Ok(l) if zeros.is_empty() || zeros.len() == l.fps.len() => laid_out.push((k, l, zeros)), + Ok(_) => failed.push((k, "texture upload zero mask does not match its subresources".into())), + Err(e) => failed.push((k, e)), + } + } + // A lone valid zero source cannot share and reserving its last row's padding could grow + // staging. Count after validation so a failed item cannot enable that padded path. + let share_zeros = laid_out.iter().flat_map(|(_, _, zeros)| *zeros).filter(|&&zero| zero).nth(1).is_some(); + let mut planned = Vec::with_capacity(laid_out.len()); + let mut storage = BatchStaging::default(); + for (k, mut l, zeros) in laid_out { + let zeros = if share_zeros { zeros } else { &[] }; + match storage.add(&mut l, zeros) { + Ok(base) => planned.push((k, l, StagingOffsets { base, zero: 0, zero_mips: zeros })), + Err(e) => failed.push((k, e)), + } + } + let zero = storage.zero_span()?; + for (_, _, offsets) in &mut planned { + offsets.zero = zero.start; + } + Ok((failed, planned, zero)) +} + +pub struct InFlight { + _alloc: ID3D12CommandAllocator, + _list: ID3D12GraphicsCommandList, + _staging: ID3D12Resource, + pub bytes: u64, +} + +pub unsafe fn submit_batch(dev: &ID3D12Device, queue: &ID3D12CommandQueue, items: &[(ID3D12Resource, Vec, Vec)]) -> Result<(Vec<(usize, String)>, Option), String> { + submit_batch_with_zero_mips(dev, queue, items, &[]) +} + +pub(crate) unsafe fn submit_batch_with_zero_mips( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + items: &[UploadBatchItem], + zero_mips: &[Vec], +) -> Result<(Vec<(usize, String)>, Option), String> { + let (failed, planned, zero) = plan_batch(dev, items, zero_mips)?; + if planned.is_empty() { + return Ok((failed, None)); + } + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).map_err(err)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).map_err(err)?; + let staging = buffer(dev, zero.end)?; + let mut mapped = std::ptr::null_mut(); + staging.Map(0, None, Some(&mut mapped)).map_err(err)?; + clear_staging_span(mapped as *mut u8, &zero); + for (k, layout, offsets) in planned { + let (res, subs, states) = &items[k]; + record_into(&list, res, subs, &layout, states, states, &staging, mapped as *mut u8, offsets); + } + staging.Unmap(0, None); + list.Close().map_err(err)?; + let cmd = windows::core::Interface::cast(&list).map_err(err)?; + crate::hle::d3d12x::real::native_queue_execute(queue, &cmd); + Ok((failed, Some(InFlight { _alloc: alloc, _list: list, _staging: staging, bytes: zero.end }))) +} + fn put_back(key: usize, up: Uploader) { UPLOADERS.lock().unwrap().get_or_insert_with(Default::default).insert(key, up); } @@ -342,7 +422,7 @@ pub unsafe fn record_upload_states( let up = buffer(dev, l.total)?; let mut p = std::ptr::null_mut(); up.Map(0, None, Some(&mut p)).map_err(err)?; - record_into(list, res, subs, &l, before, after, &up, p as *mut u8, 0); + record_into(list, res, subs, &l, before, after, &up, p as *mut u8, StagingOffsets::default()); up.Unmap(0, None); Ok(up) } @@ -355,6 +435,83 @@ struct Layout { total: u64, } +#[derive(Default)] +struct BatchStaging { + data_bytes: u64, + zero_bytes: u64, +} + +impl BatchStaging { + /// Keep the driver's dimensions and pitches. Only repack offsets when an item can share the + /// zero span. Each ordinary footprint keeps at least the byte range supplied by the driver. + fn add(&mut self, l: &mut Layout, zeros: &[bool]) -> Result { + let overflow = || "texture upload staging size overflow".to_string(); + if !zeros.is_empty() && zeros.len() != l.fps.len() { + return Err("texture upload zero mask does not match its subresources".into()); + } + let base = self.data_bytes.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + let mut next = l.total; + let mut zero_bytes = self.zero_bytes; + if zeros.contains(&true) { + next = 0; + for (k, &zero) in zeros.iter().enumerate() { + let fp = l.fps[k]; + let end = l.fps.get(k + 1).map_or(l.total, |next| next.Offset); + let bytes = end.checked_sub(fp.Offset).ok_or_else(overflow)?; + if zero { + // Zero full pitched rows, including padding on the last row of each slice. + let pitched_bytes = u64::from(fp.Footprint.RowPitch) + .checked_mul(u64::from(l.rows[k])) + .and_then(|bytes| bytes.checked_mul(u64::from(fp.Footprint.Depth))) + .ok_or_else(overflow)?; + zero_bytes = zero_bytes.max(pitched_bytes.max(bytes)); + } else { + let at = next.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + next = at.checked_add(bytes).ok_or_else(overflow)?; + l.fps[k].Offset = at; + } + } + } + self.data_bytes = base.checked_add(next).ok_or_else(overflow)?; + self.zero_bytes = zero_bytes; + Ok(base) + } + + fn zero_span(&self) -> Result, String> { + if self.zero_bytes == 0 { + return Ok(self.data_bytes..self.data_bytes); + } + let overflow = || "texture upload staging size overflow".to_string(); + let start = self.data_bytes.checked_next_multiple_of(PLACEMENT).ok_or_else(overflow)?; + let end = start.checked_add(self.zero_bytes).ok_or_else(overflow)?; + Ok(start..end) + } +} + +/// The mapped staging buffer covers `span`, which can contain data from an earlier batch. +unsafe fn clear_staging_span(mapped: *mut u8, span: &std::ops::Range) { + if !span.is_empty() { + mapped.add(span.start as usize).write_bytes(0, (span.end - span.start) as usize); + } +} + +#[derive(Default)] +struct StagingOffsets<'a> { + base: u64, + zero: u64, + zero_mips: &'a [bool], +} + +impl StagingOffsets<'_> { + fn is_zero(&self, sub: usize) -> bool { + self.zero_mips.get(sub) == Some(&true) + } + + fn at(&self, sub: usize, offset: u64) -> u64 { + if self.is_zero(sub) { self.zero } else { self.base + offset } + } +} + /// The `Layout` of uploading `subs` into `res`, checked against the resource. unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES]) -> Result { validate_subresources(subs)?; @@ -371,6 +528,9 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], let mut row_bytes = vec![0u64; n]; let mut total = 0u64; dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + if total == u64::MAX { + return Err("invalid texture copy footprints".into()); + } for (i, ((s, fp), (&nrows, &nbytes))) in subs.iter().zip(&fps).zip(rows.iter().zip(&row_bytes)).enumerate() { if s.rows != nrows as usize || s.depth != fp.Footprint.Depth as usize || s.row_bytes != nbytes as usize { return Err(format!( @@ -382,20 +542,23 @@ unsafe fn layout(dev: &ID3D12Device, res: &ID3D12Resource, subs: &[Subresource], Ok(Layout { fps, rows, total }) } -/// Write `subs` into the mapped upload buffer `up` (`mapped`) from `base` (a multiple of -/// D3D12_TEXTURE_DATA_PLACEMENT_ALIGNMENT) as `l` places them, and record their copies into -/// `res` on `list` (barriers from `before` and back to `after`). +/// Write `subs` into the mapped upload buffer `up` (`mapped`) where `l` and `offsets` place them, +/// and record every copy into `res` on `list` (barriers from `before` and back to `after`). #[allow(clippy::too_many_arguments)] -unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, base: u64) { +unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, subs: &[Subresource], l: &Layout, before: &[D3D12_RESOURCE_STATES], after: &[D3D12_RESOURCE_STATES], up: &ID3D12Resource, mapped: *mut u8, offsets: StagingOffsets<'_>) { let n = subs.len(); - for ((s, fp), &nrows) in subs.iter().zip(&l.fps).zip(&l.rows) { + for (k, ((s, fp), &nrows)) in subs.iter().zip(&l.fps).zip(&l.rows).enumerate() { + if offsets.is_zero(k) { + continue; + } + let start = offsets.at(k, fp.Offset) as usize; let pitch = fp.Footprint.RowPitch as usize; let row = s.row_bytes.min(pitch); // depth slices are NumRows rows apart (rows of 4×4 blocks for BCn) let slice_pitch = pitch * nrows as usize; for z in 0..(fp.Footprint.Depth as usize).min(s.depth) { for y in 0..(nrows as usize).min(s.rows) { - let at = base as usize + fp.Offset as usize + z * slice_pitch + y * pitch; + let at = start + z * slice_pitch + y * pitch; std::ptr::copy_nonoverlapping(s.data[(z * s.rows + y) * s.row_bytes..].as_ptr(), mapped.add(at), row); } } @@ -410,7 +573,7 @@ unsafe fn record_into(list: &ID3D12GraphicsCommandList, res: &ID3D12Resource, su Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: k as u32 }, }; - let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: base + fp.Offset, Footprint: fp.Footprint }; + let placed = D3D12_PLACED_SUBRESOURCE_FOOTPRINT { Offset: offsets.at(k, fp.Offset), Footprint: fp.Footprint }; let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(up), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: placed } }; list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); } @@ -436,10 +599,19 @@ pub unsafe fn wait(dev: &ID3D12Device, queue: &ID3D12CommandQueue) -> Result<(), let copy_error = |e| format!("texture copy: {e}"); let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| copy_error(fence::api_error(dev, "CreateFence", e)))?; - queue.Signal(&fence, 1).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; + crate::hle::d3d12x::real::native_queue_signal(queue, &fence, 1).map_err(|e| copy_error(fence::api_error(dev, "Signal", e)))?; fence::wait(&fence, 1, dev, None, 10_000).map_err(copy_error) } +/// Release GPU submission objects only once a fallback queue wait made that safe. If the wait +/// itself fails, deliberately retain them: submitted work may still reference their resources. +pub(crate) fn drop_after_wait(objects: T, waited: Result<(), String>) -> Result<(), String> { + if waited.is_err() { + std::mem::forget(objects); + } + waited +} + unsafe fn buffer(dev: &ID3D12Device, size: u64) -> Result { let rd = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, @@ -482,6 +654,92 @@ mod tests { use std::collections::HashMap; use windows::Win32::Graphics::Dxgi::Common::*; + #[test] + fn submitted_objects_are_retained_when_the_fallback_wait_fails() { + struct CountDrop<'a>(&'a std::sync::atomic::AtomicUsize); + impl Drop for CountDrop<'_> { + fn drop(&mut self) { + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + + let drops = std::sync::atomic::AtomicUsize::new(0); + assert!(drop_after_wait(CountDrop(&drops), Ok(())).is_ok()); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 1); + assert_eq!(drop_after_wait(CountDrop(&drops), Err("wait failed".into())).unwrap_err(), "wait failed"); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 1); + } + + #[test] + fn shared_zero_mip_staging_compacts_and_clears_the_full_span() { + // A 1024² R8 texture with five mips, including the driver's row and placement alignment. + let layout = || Layout { + fps: [0, 1_048_576, 1_310_720, 1_376_256, 1_409_024].into_iter() + .zip([1024, 512, 256, 128, 64]) + .map(|(offset, width)| D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8_UNORM, + Width: width, + Height: width, + Depth: 1, + RowPitch: width.max(256), + }, + }).collect(), + rows: vec![1024, 512, 256, 128, 64], + total: 1_425_216, + }; + let zeros = [true, false, false, false, false]; + let mut original = BatchStaging::default(); + let mut shared = BatchStaging::default(); + let mut items = Vec::new(); + for _ in 0..8 { + original.add(&mut layout(), &[]).unwrap(); + let mut l = layout(); + let base = shared.add(&mut l, &zeros).unwrap(); + items.push((l, base)); + } + let old = original.zero_span().unwrap(); + let zero = shared.zero_span().unwrap(); + assert!(old.is_empty()); + assert_eq!(old.end, 11_403_072); + assert_eq!(zero.end, 4_063_232); + assert_eq!(staging_capacity(old.end), Some(16 << 20)); + assert_eq!(staging_capacity(zero.end), Some(4 << 20)); + for (l, base) in items { + let offsets = StagingOffsets { base, zero: zero.start, zero_mips: &zeros }; + assert_eq!(offsets.at(0, l.fps[0].Offset), zero.start); + for (k, fp) in l.fps.iter().enumerate().skip(1) { + let at = offsets.at(k, fp.Offset); + assert_eq!(at % PLACEMENT, 0); + assert!(at + u64::from(fp.Footprint.RowPitch * l.rows[k]) <= zero.start); + assert_eq!(fp.Footprint, layout().fps[k].Footprint); + } + } + + // A fully zero footprint uses whole pitched rows, including the last row of the + // last slice, even when GetCopyableFootprints reports a shorter last row. + let mut volume = Layout { + fps: vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: 0, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: DXGI_FORMAT_R8_UNORM, Width: 13, Height: 2, Depth: 3, RowPitch: 256, + }, + }], + rows: vec![2], + total: 5 * 256 + 13, + }; + let mut volume_batch = BatchStaging { data_bytes: 268, zero_bytes: 0 }; + volume_batch.add(&mut volume, &[true]).unwrap(); + let zero = volume_batch.zero_span().unwrap(); + assert_eq!(zero, 512..2048); + let mut bytes = vec![0x72; 2049]; + unsafe { clear_staging_span(bytes.as_mut_ptr(), &zero); } + assert!(bytes[..512].iter().all(|&b| b == 0x72)); + assert!(bytes[512..2048].iter().all(|&b| b == 0)); + assert_eq!(bytes[2048], 0x72); + } + fn image(format: u32, ty: ImageType, w: u32, h: u32, slices: u32, mips: u32, mode: u32, address: u64) -> Image { Image { address, diff --git a/crates/xcl/src/gpu/tiling.rs b/crates/xcl/src/gpu/tiling.rs index b9fa1abdd3..9515bd44c2 100644 --- a/crates/xcl/src/gpu/tiling.rs +++ b/crates/xcl/src/gpu/tiling.rs @@ -66,6 +66,9 @@ pub struct Layout { /// XORed into every in-block byte offset: the pipe / bank swizzle a T# base address carries /// in its low bits (`base & (block_bytes - 1)`), 0 otherwise pub base_xor: usize, + /// largest power-of-two horizontal element run inside a block whose byte offsets advance + /// contiguously by `+e` with zero interference from `oy`/`oz`/`hx`/`hy`/`hz` + run_elems: usize, ox: &'static [u32], oy: &'static [u32], oz: &'static [u32], @@ -108,7 +111,7 @@ impl Layout { if mode == 0 { let bw = 256 >> elem_log2; let ox: &'static [u32] = (0..bw as u32).map(|x| x << elem_log2).collect::>().leak(); - return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); + return Some(Layout { mode, elem_log2, block_w: bw, block_h: 1, block_d: 1, block_bytes: 256, base_xor: 0, run_elems: bw, ox, oy: &[0], oz: &[0], hx: &[0], hy: &[0], hz: &[0] }); } let blk = block_log2(mode)?; let bits = pattern_bits(PATTERNS, mode, elem_log2, cfg)?; @@ -161,6 +164,29 @@ impl Layout { let used = bits[..blk as usize].iter().fold(0u32, |m, &b| m | ((b >> shift) & 0xFFFF) as u32) >> l.min(16); table(1 << (32 - used.leading_zeros()), shift, l) }; + let ox = table(bw, 0, 0); + let oy = table(bh, 16, 0); + let oz = table(bd, 32, 0); + let hx = high(wl, 0); + let hy = high(hl, 16); + let hz = high(dl, 32); + let other_bits = oy.iter().chain(oz).chain(hx).chain(hy).chain(hz).fold(0u32, |a, &b| a | b); + let mut run_elems = 1usize; + while run_elems * 2 <= bw { + let next = run_elems * 2; + let mask = ((next << elem_log2) - 1) as u32; + if (other_bits & mask) != 0 { + break; + } + let ok = (0..bw).all(|x| { + let base = ox[x & !(next - 1)]; + (base & mask) == 0 && ox[x] == base + (((x & (next - 1)) << elem_log2) as u32) + }); + if !ok { + break; + } + run_elems = next; + } Layout { mode, elem_log2, @@ -169,12 +195,13 @@ impl Layout { block_d: bd, block_bytes: 1 << blk, base_xor: 0, - ox: table(bw, 0, 0), - oy: table(bh, 16, 0), - oz: table(bd, 32, 0), - hx: high(wl, 0), - hy: high(hl, 16), - hz: high(dl, 32), + run_elems, + ox, + oy, + oz, + hx, + hy, + hz, } } @@ -204,34 +231,215 @@ impl Layout { block * self.block_bytes + (xor as usize ^ self.base_xor) } + /// Effective horizontal contiguous run width in elements, respecting any `base_xor` low bits. + #[inline] + fn effective_run(&self) -> usize { + if self.base_xor == 0 { + self.run_elems + } else { + let lim = (1usize << self.base_xor.trailing_zeros()) >> self.elem_log2; + self.run_elems.min(lim).max(1) + } + } + /// tiled → linear rows (`w << elem_log2` bytes each); bytes past the end of `src` read as 0 pub fn detile(&self, src: &[u8], w: usize, h: usize) -> Vec { let e = 1usize << self.elem_log2; let mut out = vec![0u8; w * h * e]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - if let Some(s) = src.get(o..o + e) { - let d = (y * w + x) * e; - out[d..d + e].copy_from_slice(s); - } - } - } + self.detile_2d(src, &mut out, 0, w, h, w, (0, 0), 0); out } /// linear rows → tiled (the inverse of `detile`) pub fn tile(&self, linear: &[u8], w: usize, h: usize) -> Vec { - let e = 1usize << self.elem_log2; let mut out = vec![0u8; self.size(w, h)]; - for y in 0..h { - for x in 0..w { - let o = self.offset(x, y, w); - let s = (y * w + x) * e; - out[o..o + e].copy_from_slice(&linear[s..s + e]); + self.tile_2d(&mut out, linear, 0, w, h, w, (0, 0), 0); + out + } + + /// Block-slab 2D detile with contiguous horizontal run copies (`src` tiled -> `out` linear). + /// Iterating one tiled block `(by, bx)` at a time keeps each 4 KiB / 64 KiB block hot in L1 + /// cache and eliminates per-element block arithmetic and bounds checks on complete blocks. + #[allow(clippy::too_many_arguments)] + fn detile_2d(&self, src: &[u8], out: &mut [u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + let n = src.len().saturating_sub(o).min(row) / e * e; + if n > 0 { + out[y * row..][..n].copy_from_slice(&src[o..o + n]); + } + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + if block_base.checked_add(self.block_bytes).is_some_and(|end| end <= src.len()) { + let blk = &src[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + run_bytes].copy_from_slice(&blk[o..o + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + dst_row[x * e..x * e + e].copy_from_slice(&blk[o..o + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(&blk[o..o + e]); + } + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let dst_row = &mut out[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = block_base + (x_off ^ y_xor) as usize; + if let Some(s) = src.get(o..o + e) { + let d = (x_lo + dx) * e; + dst_row[d..d + e].copy_from_slice(s); + } + } + } + } + } + } + } + + /// Block-slab 2D tile with contiguous horizontal run copies (`linear` -> `dst` tiled). + #[allow(clippy::too_many_arguments)] + fn tile_2d(&self, dst: &mut [u8], linear: &[u8], base_off: usize, w: usize, h: usize, pitch: usize, origin: (usize, usize), slice: usize) { + if w == 0 || h == 0 { + return; + } + let e = 1usize << self.elem_log2; + if self.mode == 0 && self.base_xor == 0 && origin == (0, 0) { + let row = w * e; + let pitch_blocks = pitch.div_ceil(self.block_w); + for y in 0..h { + let o = base_off + (y / self.block_h) * pitch_blocks * self.block_bytes + self.oy[y % self.block_h] as usize; + dst[o..o + row].copy_from_slice(&linear[y * row..][..row]); + } + return; + } + let pitch_blocks = pitch.div_ceil(self.block_w); + let z = self.oz[slice % self.block_d] ^ self.hz[(slice / self.block_d) % self.hz.len()]; + let run = self.effective_run(); + let run_bytes = run * e; + let row_bytes = w * e; + let (ox0, oy0) = origin; + let bx_start = ox0 / self.block_w; + let bx_end = (ox0 + w - 1) / self.block_w; + let by_start = oy0 / self.block_h; + let by_end = (oy0 + h - 1) / self.block_h; + + for by in by_start..=by_end { + let y_lo = (by * self.block_h).max(oy0) - oy0; + let y_hi = ((by + 1) * self.block_h).min(oy0 + h) - oy0; + let hy = self.hy[by % self.hy.len()] ^ z; + let row_blocks = by * pitch_blocks; + for bx in bx_start..=bx_end { + let x_lo = (bx * self.block_w).max(ox0) - ox0; + let x_hi = ((bx + 1) * self.block_w).min(ox0 + w) - ox0; + let block_base = base_off + (row_blocks + bx) * self.block_bytes; + let b_xor = self.hx[bx % self.hx.len()] ^ hy ^ self.base_xor as u32; + let xi_lo = x_lo + ox0 - bx * self.block_w; + let xi_hi = x_hi + ox0 - bx * self.block_w; + let blk = &mut dst[block_base..block_base + self.block_bytes]; + if run > 1 { + let aligned_lo = (xi_lo + run - 1) & !(run - 1); + let aligned_hi = xi_hi & !(run - 1); + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + let mut xi = xi_lo; + let mut x = x_lo; + let pre = aligned_lo.min(xi_hi); + while xi < pre { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + while xi < aligned_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + run_bytes].copy_from_slice(&src_row[x * e..x * e + run_bytes]); + xi += run; + x += run; + } + while xi < xi_hi { + let o = (self.ox[xi] ^ y_xor) as usize; + blk[o..o + e].copy_from_slice(&src_row[x * e..x * e + e]); + xi += 1; + x += 1; + } + } + } else { + for y in y_lo..y_hi { + let y_xor = self.oy[y + oy0 - by * self.block_h] ^ b_xor; + let src_row = &linear[y * row_bytes..(y + 1) * row_bytes]; + for (dx, &x_off) in self.ox[xi_lo..xi_hi].iter().enumerate() { + let o = (x_off ^ y_xor) as usize; + let s = (x_lo + dx) * e; + blk[o..o + e].copy_from_slice(&src_row[s..s + e]); + } + } + } } } - out } } @@ -378,6 +586,7 @@ impl Chain { /// element (x, y) of level `l` in array slice `slice` (from the slice's start): the slice /// is z of the 2D patterns – the XOR modes take pipe bits from it + #[cfg(test)] fn element_at(&self, l: &MipLevel, x: usize, y: usize, slice: usize) -> usize { l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch) } @@ -425,59 +634,37 @@ impl Chain { /// bytes past the end of `src` read as 0 pub fn detile_level(&self, src: &[u8], i: usize, slice: usize) -> Vec { let l = self.levels[i]; - let t = &self.layout; - let e = 1usize << t.elem_log2; + let e = 1usize << self.layout.elem_log2; let mut out = vec![0u8; l.width * l.height * e]; - if t.mode == 0 && t.base_xor == 0 && l.origin == (0, 0) { - // linear: a row's elements are contiguous, so it is copied whole (the elements that - // are all in `src`, as below) – a video plane of 3840×2160 is 2160 copies, not 8 M - let row = l.width * e; + if self.layout.block_d != 1 { for y in 0..l.height { - let o = self.element_at(&l, 0, y, slice); - let n = src.len().saturating_sub(o).min(row) / e * e; - if n > 0 { - out[y * row..][..n].copy_from_slice(&src[o..o + n]); + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + if let Some(bytes) = src.get(offset..offset + e) { + out[(y * l.width + x) * e..][..e].copy_from_slice(bytes); + } } } return out; } - // `element_at` (`Layout::offset_z`) split: what depends on x alone once per level, what - // depends on y (and the slice) once per row – per element only two lookups and an XOR. - // Element by element it was most of a retail game's render thread while it streamed - // textures the CPU writes. - let hi = |tab: &[u32], c: usize, b: usize| tab[(c / b) % tab.len()]; - let pitch_blocks = l.pitch.div_ceil(t.block_w); - let columns: Vec<(usize, u32)> = (0..l.width) - .map(|x| { - let x = x + l.origin.0; - (x / t.block_w, t.ox[x % t.block_w] ^ hi(&t.hx, x, t.block_w)) - }) - .collect(); - let z = t.oz[slice % t.block_d] ^ hi(&t.hz, slice, t.block_d); - for (y, row) in out.chunks_exact_mut(l.width * e).enumerate() { - let y = y + l.origin.1; - let row_blocks = (y / t.block_h) * pitch_blocks; - let yz = t.oy[y % t.block_h] ^ hi(&t.hy, y, t.block_h) ^ z; - for (&(block_x, x), dst) in columns.iter().zip(row.chunks_exact_mut(e)) { - let o = l.offset + (row_blocks + block_x) * t.block_bytes + ((x ^ yz) as usize ^ t.base_xor); - if let Some(s) = src.get(o..o + e) { - dst.copy_from_slice(s); - } - } - } + self.layout.detile_2d(src, &mut out, l.offset, l.width, l.height, l.pitch, l.origin, slice); out } /// linear rows of level `i` → its place in array slice `slice` (`dst`, `slice_bytes` long) pub fn tile_level(&self, dst: &mut [u8], i: usize, slice: usize, linear: &[u8]) { let l = self.levels[i]; - let e = 1usize << self.layout.elem_log2; - for y in 0..l.height { - for x in 0..l.width { - let o = self.element_at(&l, x, y, slice); - dst[o..o + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); + if self.layout.block_d != 1 { + let e = 1usize << self.layout.elem_log2; + for y in 0..l.height { + for x in 0..l.width { + let offset = l.offset + self.layout.offset_z(x + l.origin.0, y + l.origin.1, slice, l.pitch); + dst[offset..offset + e].copy_from_slice(&linear[(y * l.width + x) * e..][..e]); + } } + return; } + self.layout.tile_2d(dst, linear, l.offset, l.width, l.height, l.pitch, l.origin, slice); } } @@ -705,6 +892,15 @@ mod tests { let cfg = PipeConfig { pipes_log2: 0, pkrs_log2: 0 }; assert_eq!(Layout::new_3d(24, 2, cfg).unwrap().block_d, 1); assert!(Layout::new_3d(10, 2, cfg).is_none() && Layout::new_3d(1, 2, cfg).is_none()); + + // The 2D block-slab fast path must not change the legacy single-slice helpers on a + // thick layout (volume callers normally use `tile_volume` / `detile_volume`). + let chain = Chain::new_3d(Layout::new_3d(5, 2, cfg).unwrap(), 19, 13, 4, 1, 1); + let level = chain.levels[0]; + let linear: Vec = (0..level.width * level.height * 4).map(|i| (i * 37) as u8).collect(); + let mut tiled = vec![0u8; chain.slice_bytes]; + chain.tile_level(&mut tiled, 0, 1, &linear); + assert_eq!(chain.detile_level(&tiled, 0, 1), linear); } /// The three volume textures of the retail TTPF archive (4 KB tiles, thick): the space each @@ -872,5 +1068,68 @@ mod tests { assert!(!g.contains_key(&(false, 9, 5, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); assert!(!g.contains_key(&(true, 10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }))); } + + #[test] + fn tile_level_matches_element_by_element_and_exploits_contiguous_runs() { + // Standard 2D modes with 1..4B elements must detect multi-element contiguous runs. + assert!(Layout::new(5, 0, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 4); + assert!(Layout::new(10, 2, PipeConfig { pipes_log2: 0, pkrs_log2: 0 }).unwrap().run_elems >= 2); + for mode in MODES { + for e in 0..5u32 { + for cfg in configs() { + let mut lay = Layout::new(mode, e, cfg).unwrap(); + lay.base_xor = (lay.block_bytes / 2) & !((1 << e) - 1); + let c = Chain::new(lay, 77, 45, 1, 7); + let es = 1usize << e; + for (k, l) in c.levels.iter().enumerate() { + let lin: Vec = (0..l.width * l.height * es).map(|i| ((i * 53 + k * 17) % 251) as u8 | 1).collect(); + for slice in [0usize, 3] { + let mut got = vec![0u8; c.slice_bytes]; + let mut want = vec![0u8; c.slice_bytes]; + c.tile_level(&mut got, k, slice, &lin); + for y in 0..l.height { + for x in 0..l.width { + let o = c.element_at(l, x, y, slice); + want[o..o + es].copy_from_slice(&lin[(y * l.width + x) * es..][..es]); + } + } + assert!(got == want, "tile_level mismatch: mode {mode} e {e} {cfg:?} level {k} slice {slice}"); + } + } + } + } + } + } + + #[test] + fn low_base_xor_bits_bound_runs_without_changing_bytes() { + for (mode, e) in [(5, 0u32), (10, 2)] { + let es = 1usize << e; + for cfg in configs() { + let plain = Layout::new(mode, e, cfg).unwrap(); + for xor in [es, 3 * es, plain.block_bytes / 2] { + let mut layout = plain; + layout.base_xor = xor; + if xor == es { + assert_eq!(layout.effective_run(), 1, "mode {mode} e {e} {cfg:?}"); + } + let chain = Chain::new(layout, 77, 45, 1, 1); + let level = chain.levels[0]; + let linear: Vec = (0..level.width * level.height * es).map(|i| (i * 53 % 251) as u8).collect(); + let mut tiled = vec![0u8; chain.slice_bytes]; + chain.tile_level(&mut tiled, 0, 0, &linear); + let mut want = vec![0u8; chain.slice_bytes]; + for y in 0..level.height { + for x in 0..level.width { + let offset = chain.element_at(&level, x, y, 0); + want[offset..offset + es].copy_from_slice(&linear[(y * level.width + x) * es..][..es]); + } + } + assert_eq!(tiled, want, "mode {mode} e {e} {cfg:?} xor {xor:#x}"); + assert_eq!(chain.detile_level(&tiled, 0, 0), linear, "mode {mode} e {e} {cfg:?} xor {xor:#x}"); + } + } + } + } } diff --git a/crates/xcl/src/hle/bcpack/victory.rs b/crates/xcl/src/hle/bcpack/victory.rs index 20b8fa5129..9886e914d9 100644 --- a/crates/xcl/src/hle/bcpack/victory.rs +++ b/crates/xcl/src/hle/bcpack/victory.rs @@ -331,10 +331,39 @@ fn references(s: &[u8], paired: bool) -> (usize, usize) { (usize::from(ix.wrapping_add(delta)), usize::from(ix)) } +/// Spreads a 4-bit symbol onto even bit positions `0, 2, 4, 6`. +const SPREAD4: [u8; 16] = [ + 0x00, 0x01, 0x04, 0x05, 0x10, 0x11, 0x14, 0x15, + 0x40, 0x41, 0x44, 0x45, 0x50, 0x51, 0x54, 0x55, +]; + +/// Spreads an 8-bit symbol onto even bit positions `0, 2, ..., 14`. +const SPREAD8: [u16; 256] = { + let mut t = [0u16; 256]; + let mut v = 0usize; + while v < 256 { + let mut out = 0u16; + let mut k = 0; + while k < 8 { + out |= (((v >> k) & 1) as u16) << (2 * k); + k += 1; + } + t[v] = out; + v += 1; + } + t +}; + /// Two 4-bit symbols, the first on the even bits. +#[inline(always)] fn interleave(a: u8, b: u8) -> u8 { - let spread = |v: u8| (0..4).fold(0, |acc, k| acc | (v >> k & 1) << (2 * k)); - spread(a) | spread(b) << 1 + SPREAD4[usize::from(a & 15)] | (SPREAD4[usize::from(b & 15)] << 1) +} + +/// Two 8-bit symbols, the first on the even bits. +#[inline(always)] +fn wide_interleave(a: u8, b: u8) -> u16 { + SPREAD8[usize::from(a)] | (SPREAD8[usize::from(b)] << 1) } /// Block `i`'s reference `r`: 0 none, else `r` blocks back, before the first @@ -348,26 +377,40 @@ fn pick<'a, T>(i: usize, r: usize, history: &'a [T], dictionary: &'a [T], zero: } /// Zigzag residual (0, -1, 1, -2, ...) modulo 2^bits. +#[inline(always)] fn zz(v: u8, bits: u32) -> u8 { let mask = ((1u32 << bits) - 1) as u8; ((v >> 1) ^ if v & 1 != 0 { mask } else { 0 }) & mask } -/// Element widths of the plain formats' endpoints and indices. +/// Element masks and active counts of the plain formats' endpoints and indices. struct Widths { - ep: [u8; 8], - ix: [u8; 32], + ep_mask: [u8; 8], + ep_len: usize, + ix_mask: [u8; 32], + ix_len: usize, paired: bool, } const fn widths(ep: [u8; 8], ix3: usize, ix2: usize, paired: bool) -> Widths { - let mut ix = [0; 32]; + let mut ep_mask = [0u8; 8]; + let mut ep_len = 0; let mut k = 0; - while k < ix3 + ix2 { - ix[k] = if k < ix3 { 3 } else { 2 }; + while k < 8 { + if ep[k] != 0 { + ep_mask[k] = ((1u16 << ep[k]) - 1) as u8; + ep_len = k + 1; + } k += 1; } - Widths { ep, ix, paired } + let mut ix_mask = [0u8; 32]; + let ix_len = ix3 + ix2; + let mut k = 0; + while k < ix_len { + ix_mask[k] = if k < ix3 { 7 } else { 3 }; + k += 1; + } + Widths { ep_mask, ep_len, ix_mask, ix_len, paired } } const BC1: Widths = widths([5, 6, 5, 5, 6, 5, 0, 0], 0, 16, false); @@ -390,11 +433,17 @@ fn plain<'a>( let ep_ref = &pick(i, ep_ref, &history, dictionary, &zero).ep; let ix_ref = &pick(i, ix_ref, &history, dictionary, &zero).ix; let mut v = residual(s); - for ((v, r), bits) in v.ep.iter_mut().zip(ep_ref).zip(w.ep) { - *v = v.wrapping_add(*r) & ((1u16 << bits) - 1) as u8; + for ((v, &r), &mask) in v.ep[..w.ep_len].iter_mut().zip(ep_ref).zip(&w.ep_mask) { + *v = v.wrapping_add(r) & mask; } - for ((v, r), bits) in v.ix.iter_mut().zip(ix_ref).zip(w.ix) { - *v = v.wrapping_add(*r) & ((1u8 << bits) - 1); + if w.ix_len == 16 { + for ((v, &r), &mask) in v.ix[..16].iter_mut().zip(&ix_ref[..16]).zip(&w.ix_mask[..16]) { + *v = v.wrapping_add(r) & mask; + } + } else { + for ((v, &r), &mask) in v.ix[..w.ix_len].iter_mut().zip(ix_ref).zip(&w.ix_mask) { + *v = v.wrapping_add(r) & mask; + } } history[i % HISTORY] = v; pack(&v, block); @@ -403,22 +452,26 @@ fn plain<'a>( } /// 2-bit index residuals: one symbol per 2x2 quad. -fn quads(rank: &[u8; 256], s: &[u8], ix: &mut [u8]) { +#[inline(always)] +fn quads(rank: &[u8; 256], s: &[u8; 4], ix: &mut [u8; 16]) { for (q, &sym) in s.iter().enumerate() { let v = rank[usize::from(sym)]; let base = (q >> 1) * 8 + (q & 1) * 2; - for (k, p) in [0, 1, 4, 5].into_iter().enumerate() { - ix[base + p] = v >> (2 * k) & 3; - } + ix[base] = v & 3; + ix[base + 1] = (v >> 2) & 3; + ix[base + 4] = (v >> 4) & 3; + ix[base + 5] = (v >> 6) & 3; } } /// 3-bit index residuals: one symbol per two pixels in raster order. +#[inline(always)] fn pairs(rank: &[u8; 64], s: &[u8], ix: &mut [u8]) { - for (k, &sym) in s.iter().enumerate() { + let (chunks, _) = ix.as_chunks_mut::<2>(); + for (&sym, dst) in s.iter().zip(chunks) { let v = rank[usize::from(sym & 63)]; - ix[2 * k] = v & 7; - ix[2 * k + 1] = v >> 4 & 7; + dst[0] = v & 7; + dst[1] = (v >> 4) & 7; } } @@ -427,7 +480,7 @@ fn bc1_residual(t: &Tables, s: &[u8]) -> Plain { for (k, bits) in [5, 6, 5, 5, 6, 5].into_iter().enumerate() { v.ep[k] = zz(s[2 + k], bits); } - quads(&t.rank1, &s[8..12], &mut v.ix); + quads(t.rank1, s[8..12].try_into().unwrap(), (&mut v.ix[..16]).try_into().unwrap()); v } @@ -447,7 +500,7 @@ fn bc3_residual(t: &Tables, s: &[u8]) -> Plain { ..Default::default() }; pairs(&t.rank3a, &s[6..14], &mut v.ix[..16]); - quads(&t.rank3c, &s[20..24], &mut v.ix[16..]); + quads(t.rank3c, s[20..24].try_into().unwrap(), (&mut v.ix[16..]).try_into().unwrap()); v } @@ -471,54 +524,88 @@ fn bc5_residual(t: &Tables, s: &[u8]) -> Plain { const BC1_CODE: [u32; 4] = [0, 2, 3, 1]; const BC4_CODE: [u64; 8] = [0, 2, 3, 4, 5, 6, 7, 1]; -fn bc1_color(ep: &[u8], ix: &[u8], out: &mut [u8]) { +#[inline(always)] +fn bc1_color(ep: &[u8; 6], ix: &[u8; 16], out: &mut [u8; 8]) { let c0 = u16::from(ep[0]) << 11 | u16::from(ep[1]) << 5 | u16::from(ep[2]); let c1 = u16::from(ep[3]) << 11 | u16::from(ep[4]) << 5 | u16::from(ep[5]); - let bits = (0..16).fold(0, |acc, p| { - acc | BC1_CODE[usize::from(ix[p] & 3)] << (2 * p) - }); - out[..2].copy_from_slice(&c0.to_le_bytes()); - out[2..4].copy_from_slice(&c1.to_le_bytes()); - out[4..8].copy_from_slice(&bits.to_le_bytes()); + let mut bits = 0u32; + for (p, &val) in ix.iter().enumerate() { + bits |= BC1_CODE[usize::from(val & 3)] << (2 * p); + } + let word = u64::from(c0) | (u64::from(c1) << 16) | (u64::from(bits) << 32); + *out = word.to_le_bytes(); } /// BC4 half: endpoints are kept 128 below their stored value. -fn bc4_alpha(e0: u8, e1: u8, ix: &[u8], out: &mut [u8]) { - let bits = (0..16).fold(0u64, |acc, p| { - acc | BC4_CODE[usize::from(ix[p] & 7)] << (16 + 3 * p) - }); +#[inline(always)] +fn bc4_alpha(e0: u8, e1: u8, ix: &[u8; 16], out: &mut [u8; 8]) { + let mut bits = 0u64; + for (p, &val) in ix.iter().enumerate() { + bits |= BC4_CODE[usize::from(val & 7)] << (16 + 3 * p); + } let v = u64::from(e0 ^ 0x80) | u64::from(e1 ^ 0x80) << 8 | bits; - out[..8].copy_from_slice(&v.to_le_bytes()); + *out = v.to_le_bytes(); } fn bc1_pack(v: &Plain, out: &mut [u8]) { - bc1_color(&v.ep, &v.ix, out); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[..16].try_into().unwrap(), + (&mut out[..8]).try_into().unwrap(), + ); } fn bc3_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[6], v.ep[7], &v.ix[..16], &mut out[..8]); - bc1_color(&v.ep, &v.ix[16..], &mut out[8..]); + let (a, c) = out.split_at_mut(8); + bc4_alpha(v.ep[6], v.ep[7], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc1_color( + v.ep[..6].try_into().unwrap(), + v.ix[16..].try_into().unwrap(), + (&mut c[..8]).try_into().unwrap(), + ); } fn bc4_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix, out); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), (&mut out[..8]).try_into().unwrap()); } fn bc5_pack(v: &Plain, out: &mut [u8]) { - bc4_alpha(v.ep[0], v.ep[1], &v.ix[..16], &mut out[..8]); - bc4_alpha(v.ep[2], v.ep[3], &v.ix[16..], &mut out[8..]); + let (a, b) = out.split_at_mut(8); + bc4_alpha(v.ep[0], v.ep[1], v.ix[..16].try_into().unwrap(), a.try_into().unwrap()); + bc4_alpha(v.ep[2], v.ep[3], v.ix[16..].try_into().unwrap(), (&mut b[..8]).try_into().unwrap()); } +/// Even and odd bit nibbles of every byte, zigzag-decoded to signed 4-bit residuals. +const NIBBLES: [[i16; 2]; 256] = { + let mut t = [[0i16; 2]; 256]; + let mut b = 0usize; + while b < 256 { + let mut even = 0u8; + let mut odd = 0u8; + let mut k = 0; + while k < 4 { + even |= (((b as u8) >> (2 * k)) & 1) << k; + odd |= (((b as u8) >> (2 * k + 1)) & 1) << k; + k += 1; + } + let ze = (even >> 1) as i16 ^ -((even & 1) as i16); + let zo = (odd >> 1) as i16 ^ -((odd & 1) as i16); + t[b] = [ze, zo]; + b += 1; + } + t +}; + /// A byte's even and odd bits as two zigzag-coded 4-bit residuals. +#[inline(always)] fn nibbles(b: u8, odd_first: bool) -> [i16; 2] { - let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | (v >> (2 * k) & 1) << k); - let z = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); - let (even, odd) = (z(half(b)), z(half(b >> 1))); + let [even, odd] = NIBBLES[usize::from(b)]; if odd_first { [odd, even] } else { [even, odd] } } /// Index residual plus reference, both left-aligned to 16 bits at their own /// widths, back to `bits` bits (signed). +#[inline(always)] fn add_index(cur: i16, bits: u8, refv: i16, ref_bits: u8) -> i16 { let up = |v: i16, b: u8| { if b == 0 || b > 16 { @@ -539,9 +626,11 @@ struct Bits { } impl Bits { + #[inline(always)] fn put(&mut self, value: u64, n: u32) { if n > 0 && self.at < 128 { - self.v |= (u128::from(value) & ((1u128 << n) - 1)) << self.at; + let masked = if n < 64 { value & ((1u64 << n) - 1) } else { value }; + self.v |= u128::from(masked) << self.at; } self.at += n; } @@ -735,15 +824,15 @@ fn bc7_pack(ep: &Bc7Ep, ix: &Bc7Ix, prec: [u8; 4], out: &mut [u8]) { m if pbits(m) => (0..ends).for_each(|e| w.put(field(e / 2, e % 2, prec[0]) & 1, 1)), _ => {} } - let anchors: &[u8] = match subsets { - 2 => &[0, ANCHOR2[part]], - 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], - _ => &[0], + let anchor_mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, }; let mut indices = |set: usize| { - let bits = ix.bits[set]; + let bits = u32::from(ix.bits[set]); for (p, &v) in ix.ix[set].iter().enumerate() { - let n = u32::from(bits) - u32::from(anchors.contains(&(p as u8))); + let n = bits - u32::from((anchor_mask >> p) & 1); w.put(u64::from(v as u16), n); } }; @@ -920,11 +1009,7 @@ fn bc6<'a>( }, ); let z = |v: u16| (v >> 1) ^ (v & 1).wrapping_neg(); - let wide = |a: u8, b: u8| { - (0..8).fold(0u16, |acc, k| { - acc | u16::from(a >> k & 1) << (2 * k) | u16::from(b >> k & 1) << (2 * k + 1) - }) - }; + let wide = wide_interleave; for (i, (s, block)) in records.zip(out).enumerate() { let (ep_ref, ix_ref) = references(s, true); let mode = s[30].wrapping_add(1); @@ -999,14 +1084,186 @@ fn bc6<'a>( ); } } - let anchor = if two { ANCHOR2[usize::from(part)] } else { 0 }; + let anchor_mask: u16 = if two { 1 | (1 << ANCHOR2[usize::from(part)]) } else { 1 }; + let bias = 1u16 << (bits - 1); for (p, &v) in ix.ix.iter().enumerate() { - let short = p == 0 || p == usize::from(anchor); - let v = (v as u16).wrapping_add(1 << (bits - 1)); - w.put(v.into(), u32::from(bits) - u32::from(short)); + let v = (v as u16).wrapping_add(bias); + w.put(v.into(), u32::from(bits) - u32::from((anchor_mask >> p) & 1)); } block.copy_from_slice(&w.v.to_le_bytes()); } Ok(()) } +#[cfg(test)] +mod tests { + use super::*; + + fn fnv1a(bytes: &[u8]) -> u64 { + let mut h = 0xcbf29ce484222325u64; + for &b in bytes { + h ^= u64::from(b); + h = h.wrapping_mul(0x100000001b3); + } + h + } + + #[test] + fn lut_helpers_match_scalar_reference_exhaustively() { + let spread4 = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> k) & 1) << (2 * k)); + let half = |v: u8| (0..4).fold(0u8, |acc, k| acc | ((v >> (2 * k)) & 1) << k); + let z4 = |u: u8| i16::from(u >> 1) ^ -i16::from(u & 1); + for a in 0..=255u8 { + let (even, odd) = (z4(half(a)), z4(half(a >> 1))); + assert_eq!(nibbles(a, false), [even, odd]); + assert_eq!(nibbles(a, true), [odd, even]); + for b in 0..=255u8 { + assert_eq!(interleave(a, b), spread4(a) | (spread4(b) << 1)); + let wide_ref = (0..8).fold(0u16, |acc, k| { + acc | (u16::from((a >> k) & 1) << (2 * k)) | (u16::from((b >> k) & 1) << (2 * k + 1)) + }); + assert_eq!(wide_interleave(a, b), wide_ref); + } + } + + // Precomputed Widths masks and active lengths for BC1/BC3/BC4/BC5. + for (w, ep_bits, ix3, ix2) in [ + (&BC1, [5u8, 6, 5, 5, 6, 5, 0, 0], 0usize, 16usize), + (&BC3, [5, 6, 5, 5, 6, 5, 8, 8], 16, 16), + (&BC4, [8, 8, 0, 0, 0, 0, 0, 0], 16, 0), + (&BC5, [8, 8, 8, 8, 0, 0, 0, 0], 32, 0), + ] { + let want_ep_len = ep_bits.iter().rposition(|&b| b != 0).map_or(0, |i| i + 1); + assert_eq!(w.ep_len, want_ep_len); + assert_eq!(w.ix_len, ix3 + ix2); + for (k, &bits) in ep_bits.iter().enumerate() { + assert_eq!(w.ep_mask[k], ((1u16 << bits) - 1) as u8); + } + for (k, &mask) in w.ix_mask.iter().enumerate() { + let bits = if k < ix3 { 3 } else if k < ix3 + ix2 { 2 } else { 0 }; + assert_eq!(mask, (1u8 << bits) - 1); + } + } + + // BC7 and BC6H u16 anchor bitmasks match slice/branch anchor predicates. + for part in 0..64usize { + for subsets in [1usize, 2, 3] { + let anchors: &[u8] = match subsets { + 2 => &[0, ANCHOR2[part]], + 3 => &[0, ANCHOR3A[part], ANCHOR3B[part]], + _ => &[0], + }; + let mask: u16 = match subsets { + 2 => 1 | (1 << ANCHOR2[part]), + 3 => 1 | (1 << ANCHOR3A[part]) | (1 << ANCHOR3B[part]), + _ => 1, + }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, anchors.contains(&(p as u8))); + } + } + if part < 32 { + for two in [false, true] { + let anchor = if two { ANCHOR2[part] } else { 0 }; + let mask: u16 = if two { 1 | (1 << ANCHOR2[part]) } else { 1 }; + for p in 0..16usize { + assert_eq!(((mask >> p) & 1) != 0, p == 0 || p == usize::from(anchor)); + } + } + } + } + + // Bits::put matches u128 reference across n = 0, small widths, 64, and overflow past 128. + let mut got = Bits::default(); + let mut ref_v = 0u128; + let mut ref_at = 0u32; + for (val, n) in [(0xFFFFu64, 0u32), (0x55, 5), (0xDEAD_BEEF_CAFE_BABE, 64), (0x3FF, 10), (0xFFFF, 60)] { + got.put(val, n); + if n > 0 && ref_at < 128 { + ref_v |= (u128::from(val) & ((1u128 << n) - 1)) << ref_at; + } + ref_at += n; + assert_eq!((got.v, got.at), (ref_v, ref_at)); + } + } + + #[test] + fn all_bc_fixtures_and_packers_match_baseline() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/data/bcpack"); + let tables = Tables::builtin(); + let cases: [(&str, u8, usize, u64); 12] = [ + ("bc1-2-0", 1, 2 * 8, 0x00241ed045f935b7), + ("bc1-16-1", 1, 16 * 8, 0xaa27d5c23c617a11), + ("bc1-16-9", 1, 16 * 8, 0x5af81e16cde0f88b), + ("bc1-700-2", 1, 700 * 8, 0x6c1294776a5e0f7f), + ("bc1-8192-3", 1, 8192 * 8, 0xa0d8a27ea25cb660), + ("bc3-16-1", 3, 16 * 8, 0xc9b128a6e1beda7b), + ("bc4-16-1", 4, 16 * 8, 0x80173d43d3e12784), + ("bc5-16-1", 5, 16 * 8, 0x4338d58b289e83fc), + ("bc6-16-1", 6, 16 * 8, 0x4312c31241f68f5f), + ("bc7-2-0", 7, 2 * 8, 0xb3e3f4cd147b0999), + ("bc7-16-1", 7, 16 * 8, 0x013a7ec1ceec8b71), + ("bc7-8192-3", 7, 8192 * 8, 0x0b54870998ec2325), + ]; + for (stem, mode, out_len, want_hash) in cases { + let src = std::fs::read(dir.join(format!("{stem}.bin"))).unwrap(); + let mut dst = vec![0u8; out_len]; + decode(mode, &src, &mut dst, tables).unwrap_or_else(|e| panic!("{stem}: {e}")); + assert_eq!(fnv1a(&dst), want_hash, "{stem} output diverged from baseline"); + } + let bad_src = std::fs::read(dir.join("bc7-700-2.bin")).unwrap(); + let mut bad_dst = vec![0u8; 700 * 8]; + assert_eq!(decode(7, &bad_src, &mut bad_dst, tables), Err(Error("unused BC7 control code"))); + + // Verify fixed-size bc1_color/bc4_alpha and every BC6H mode 1..=14 / BC7 mode 0..=7. + let ep6 = [19u8, 45, 7, 29, 12, 31]; + let ix16: [u8; 16] = std::array::from_fn(|p| ((p * 5 + 3) & 7) as u8); + let (mut got1, mut got4) = ([0u8; 8], [0u8; 8]); + bc1_color(&ep6, &ix16, &mut got1); + let c0 = u16::from(ep6[0]) << 11 | u16::from(ep6[1]) << 5 | u16::from(ep6[2]); + let c1 = u16::from(ep6[3]) << 11 | u16::from(ep6[4]) << 5 | u16::from(ep6[5]); + let ref_bits1 = (0..16).fold(0u32, |acc, p| acc | (BC1_CODE[usize::from(ix16[p] & 3)] << (2 * p))); + assert_eq!(&got1[..2], &c0.to_le_bytes()); + assert_eq!(&got1[2..4], &c1.to_le_bytes()); + assert_eq!(&got1[4..8], &ref_bits1.to_le_bytes()); + bc4_alpha(0x2A, 0xD5, &ix16, &mut got4); + let ref_v4 = u64::from(0x2Au8 ^ 0x80) + | (u64::from(0xD5u8 ^ 0x80) << 8) + | (0..16).fold(0u64, |acc, p| acc | (BC4_CODE[usize::from(ix16[p] & 7)] << (16 + 3 * p))); + assert_eq!(got4, ref_v4.to_le_bytes()); + + // Exercise all 14 BC6H modes (1..=14) and all 8 BC7 modes (0..=7) end-to-end. + let bc6_recs: Vec<[u8; 32]> = (1u8..=14) + .map(|m| { + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = (m.wrapping_mul(17).wrapping_add((k as u8).wrapping_mul(11))) & 0x7F; + } + r[30] = m - 1; + r[31] = (m * 3) & 31; + r + }) + .collect(); + let mut bc6_out = [[0u8; 16]; 14]; + bc6(bc6_recs.iter().map(|r| &r[..]), bc6_out.iter_mut().map(|b| &mut b[..]), tables.bc6).unwrap(); + assert!(bc6_out.iter().all(|b| b.iter().any(|&x| x != 0))); + + let mut bc7_recs = Vec::new(); + for mode in 0u16..8 { + let idx = tables.ctrl7.iter().position(|&c| c != 0 && (c & 7) == mode).unwrap(); + let mut r = [0u8; 32]; + for (k, slot) in r.iter_mut().enumerate().take(30) { + *slot = ((mode as u8 + 1).wrapping_mul(13).wrapping_add((k as u8).wrapping_mul(7))) & 0x3F; + } + r[30] = (idx & 31) as u8; + r[31] = ((idx >> 5) & 15) as u8; + bc7_recs.push(r); + } + let mut bc7_out = [[0u8; 16]; 8]; + bc7(bc7_recs.iter().map(|r| &r[..]), bc7_out.iter_mut().map(|b| &mut b[..]), tables).unwrap(); + for (mode, block) in bc7_out.iter().enumerate() { + assert_eq!(block[0].trailing_zeros() as usize, mode, "BC7 mode {mode} header bit"); + } + } +} + diff --git a/crates/xcl/src/hle/d3d12x/alloc_pool.rs b/crates/xcl/src/hle/d3d12x/alloc_pool.rs index 8b81b85913..49614531ff 100644 --- a/crates/xcl/src/hle/d3d12x/alloc_pool.rs +++ b/crates/xcl/src/hle/d3d12x/alloc_pool.rs @@ -13,9 +13,11 @@ //! put aside earlier whose lists have all been reset since and whose submits are done, or a new //! one. A list reset on the title's allocator records on the PC allocator in use. A list holds //! one recording, so no more allocators are put aside than there are lists. -use std::collections::{HashMap, HashSet}; +use std::collections::{hash_map::Entry, HashMap, HashSet}; use std::ffi::c_void; -use std::sync::Mutex; +use std::ops::{Deref, DerefMut}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -24,16 +26,20 @@ use crate::util::HRESULT; #[derive(Default)] struct Backing { + /// Raw-address generation: a completed probe must not free a replacement at the same key. + generation: u64, /// PC lists whose recording is on this allocator users: HashSet, /// queue → (fence, value after the last submit of one of them) marks: HashMap, -} - -impl Backing { - unsafe fn free(&self) -> bool { - self.users.is_empty() && self.marks.values().all(|(f, v)| f.GetCompletedValue() >= *v) - } + /// Submits reserved before ExecuteCommandLists whose completion is not marked yet. + submit_pins: usize, + /// Probe reference transferred from the title's Release while this backing is busy. + release_owner: Option, + /// Its allocator namespace is gone; release its retained/raw owner once it becomes free. + retire_when_free: bool, + /// The driver Reset this backing while idle, and no recording has used it since. + already_reset: bool, } #[derive(Default)] @@ -43,19 +49,51 @@ struct State { /// title allocator → PC allocators put aside aside: HashMap>, backings: HashMap, + next_backing_generation: u64, + /// Title allocator -> exact reset operation currently outside this lock. + resetting: HashMap, + next_reset_generation: u64, of_list: HashMap, /// title allocator → the type of the lists on it types: HashMap, - fences: HashMap, + fences: HashMap>, made: u64, swaps: u64, /// PC list → its last submit (queue, fence, value after it, recording number then) last_submit: HashMap, /// PC list → recordings so far (a Reset or creation starts the next one) recordings: HashMap, + /// PC list → object lifetime, so a late reservation cannot mark a reused address. + list_lifetimes: HashMap, + next_list_lifetime: u64, resubmits: u64, + /// (PC list, object lifetime) → reserved submits not yet associated with a queue fence. + submit_pins: HashMap<(usize, u64), usize>, +} + +enum ResetWork { + Reset { owner: ID3D12CommandAllocator, swap: bool, needed: bool }, + Create { owner: ID3D12CommandAllocator, ty: i32 }, +} + +struct ResetClaim { + alloc: usize, + current: usize, + token: u64, + mine: Vec, + probes: Vec, + work: ResetWork, } +struct IdleResetClaim { + alloc: usize, + token: u64, + mine: Vec, + probes: Vec, + work: Vec<(BackingProbe, ID3D12CommandAllocator)>, +} + +#[derive(Clone)] struct LastSubmit { queue: usize, fence: ID3D12Fence, @@ -63,10 +101,685 @@ struct LastSubmit { recording: u64, } +struct QueueFence { + fence: ID3D12Fence, + next_value: AtomicU64, +} + +impl QueueFence { + fn new(fence: ID3D12Fence) -> Self { + Self { fence, next_value: AtomicU64::new(0) } + } +} + +fn same_submit(a: &LastSubmit, b: &LastSubmit) -> bool { + a.queue == b.queue + && a.fence.as_raw() == b.fence.as_raw() + && a.value == b.value + && a.recording == b.recording +} + unsafe impl Send for State {} static STATE: Mutex> = Mutex::new(None); +#[derive(Clone)] +struct BackingProbe { + raw: usize, + generation: u64, + users: HashSet, + marks: Vec<(usize, ID3D12Fence, u64)>, + submit_pins: usize, + release_owner: Option, + retire_when_free: bool, + already_reset: bool, +} + +impl BackingProbe { + fn new(raw: usize, backing: &Backing) -> Self { + Self { + raw, + generation: backing.generation, + users: backing.users.clone(), + marks: backing.marks.iter().map(|(&queue, (fence, value))| (queue, fence.clone(), *value)).collect(), + submit_pins: backing.submit_pins, + release_owner: backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize), + retire_when_free: backing.retire_when_free, + already_reset: backing.already_reset, + } + } + + unsafe fn free(&self) -> bool { + self.users.is_empty() && self.submit_pins == 0 && self.marks.iter().all(|(_, fence, value)| fence.GetCompletedValue() >= *value) + } + + unsafe fn in_flight(&self) -> bool { + self.submit_pins != 0 || self.marks.iter().any(|(_, fence, value)| fence.GetCompletedValue() < *value) + } + + fn matches(&self, backing: &Backing) -> bool { + self.generation == backing.generation + && self.users == backing.users + && self.submit_pins == backing.submit_pins + && self.release_owner == backing.release_owner.as_ref().map(|owner| owner.as_raw() as usize) + && self.retire_when_free == backing.retire_when_free + && self.already_reset == backing.already_reset + && self.marks.len() == backing.marks.len() + && self.marks.iter().all(|(queue, fence, value)| { + backing.marks.get(queue).is_some_and(|(current, current_value)| current.as_raw() == fence.as_raw() && current_value == value) + }) + } +} + +fn backing_mut(state: &mut State, raw: usize) -> &mut Backing { + if !state.backings.contains_key(&raw) { + state.next_backing_generation = state.next_backing_generation.wrapping_add(1).max(1); + state.backings.insert(raw, Backing { generation: state.next_backing_generation, ..Default::default() }); + } + state.backings.get_mut(&raw).unwrap() +} + +fn namespace(state: &State, alloc: usize) -> Vec { + let mut mine: Vec<_> = state.cur.get(&alloc).into_iter().chain(state.aside.get(&alloc).into_iter().flatten()).chain([&alloc]).copied().collect(); + mine.sort_unstable(); + mine.dedup(); + mine +} + +fn namespace_probes(state: &State, alloc: usize) -> (Vec, Vec) { + let mine = namespace(state, alloc); + let probes = mine.iter().filter_map(|raw| state.backings.get(raw).map(|backing| BackingProbe::new(*raw, backing))).collect(); + (mine, probes) +} + +fn namespace_matches(state: &State, alloc: usize, mine: &[usize], probes: &[BackingProbe]) -> bool { + namespace(state, alloc) == mine + && mine.iter().all(|raw| match (state.backings.get(raw), probes.iter().find(|probe| probe.raw == *raw)) { + (None, None) => true, + (Some(backing), Some(probe)) => probe.matches(backing), + _ => false, + }) +} + +fn reserve_reset(state: &mut State, alloc: usize) -> Option { + if state.resetting.contains_key(&alloc) { + return None; + } + state.next_reset_generation = state.next_reset_generation.wrapping_add(1).max(1); + let token = state.next_reset_generation; + state.resetting.insert(alloc, token); + Some(token) +} + +fn cancel_reset(state: &mut State, alloc: usize, token: u64) { + if state.resetting.get(&alloc) == Some(&token) { + state.resetting.remove(&alloc); + } +} + +fn run_reset(raw: *mut c_void, reset: impl FnOnce(*mut c_void) -> HRESULT) -> HRESULT { + reset(raw) +} + +#[cfg(test)] +unsafe fn backing_free_for_test(backing: &Backing) -> bool { BackingProbe::new(0, backing).free() } + +/// Remove completion caches for a retired queue before its raw address can be reused. This is +/// called only after its retirement mark completes; every removed COM fence drops unlocked. +pub(super) fn forget_queue(id: super::present::QueueId) { + let queue = id.raw(); + let (marker, gone) = { + let mut state = STATE.lock().unwrap(); + let Some(state) = state.as_mut() else { return }; + let mut gone = Vec::new(); + let marker = state.fences.remove(&queue); + for backing in state.backings.values_mut() { + if let Some((fence, _)) = backing.marks.remove(&queue) { + gone.push(fence); + } + } + let lists: Vec<_> = state.last_submit.iter().filter_map(|(&list, submit)| (submit.queue == queue).then_some(list)).collect(); + for list in lists { + if let Some(submit) = state.last_submit.remove(&list) { + gone.push(submit.fence); + } + } + (marker, gone) + }; + drop(marker); + drop(gone); +} + +pub(super) fn release_with_probe( + add_ref: impl FnOnce(), + mut release: impl FnMut() -> u32, + retain_probe: impl FnOnce() -> bool, +) -> (u32, bool) { + add_ref(); + let after_caller = release(); + if after_caller == 1 && retain_probe() { (0, true) } else { (release(), false) } +} + +/// Transfer the caller's temporary AddRef probe into pool ownership when releasing `raw` would +/// otherwise destroy an allocator that still owns recordings or unretired GPU work. +pub(super) unsafe fn retain_release_probe(raw: *mut c_void) -> bool { + let key = raw as usize; + loop { + let probe = { + let g = STATE.lock().unwrap(); + let Some(backing) = g.as_ref().and_then(|s| s.backings.get(&key)) else { return false }; + if backing.release_owner.is_some() { return false } + BackingProbe::new(key, backing) + }; + let free = probe.free(); + let mut g = STATE.lock().unwrap(); + let Some(backing) = g.as_mut().and_then(|s| s.backings.get_mut(&key)) else { return false }; + if backing.release_owner.is_some() { + return false; + } + if backing.generation != probe.generation || !probe.matches(backing) { + drop(g); + continue; + } + if free { + return false; + } + backing.release_owner = Some(ID3D12CommandAllocator::from_raw(raw)); + return true; + } +} + +/// Drop transferred Release probes only after leaving STATE: their hooked Release re-enters here. +pub(super) fn sweep_release_owners() { + sweep_release_owners_with(super::real::release_retained_allocator, drop); +} + +fn sweep_release_owners_with( + mut release_transferred: impl FnMut(ID3D12CommandAllocator), + mut release_made: impl FnMut(ID3D12CommandAllocator), +) { + loop { + let probes: Vec<_> = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return }; + s.backings.iter().filter_map(|(&raw, backing)| backing.retire_when_free.then(|| BackingProbe::new(raw, backing))).collect() + }; + let ready: Vec<_> = probes.into_iter().filter(|probe| unsafe { probe.free() }).collect(); + if ready.is_empty() { return } + let removed = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + ready.iter().find_map(|probe| { + s.backings.get(&probe.raw).is_some_and(|backing| probe.matches(backing)).then(|| probe.raw) + }).and_then(|raw| s.backings.remove(&raw).map(|backing| (raw, backing))) + }; + let Some((raw, mut backing)) = removed else { continue }; + let owner = backing.release_owner.take(); + drop(backing); + super::console_list::allocator_reset(raw as *mut c_void); + match owner { + Some(owner) => release_transferred(owner), + None => release_made(unsafe { ID3D12CommandAllocator::from_raw(raw as *mut c_void) }), + } + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(default)] +pub struct AllocatorSubmitStats { + pub outer_execute_calls: u64, + pub chunks: u64, + pub multi_chunk_calls: u64, + pub forced_wait_boundaries: u64, + pub lists_marked: u64, + /// Backing mark-map insertions, including overwrites when lists share a backing. + pub backing_mark_writes: u64, + pub signal_attempts: u64, + pub signal_failures: u64, + pub state_lock_wait_ns: u64, + pub state_lock_hold_ns: u64, +} + +struct SubmitCounters { + outer_execute_calls: AtomicU64, + chunks: AtomicU64, + multi_chunk_calls: AtomicU64, + forced_wait_boundaries: AtomicU64, + lists_marked: AtomicU64, + backing_mark_writes: AtomicU64, + signal_attempts: AtomicU64, + signal_failures: AtomicU64, + state_lock_wait_ns: AtomicU64, + state_lock_hold_ns: AtomicU64, +} + +macro_rules! submit_counters { + ($($name:ident),+ $(,)?) => { + static SUBMIT: SubmitCounters = SubmitCounters { $($name: AtomicU64::new(0)),+ }; + + pub fn submit_stats() -> AllocatorSubmitStats { + AllocatorSubmitStats { $($name: SUBMIT.$name.load(Ordering::Relaxed)),+ } + } + }; +} + +submit_counters!( + outer_execute_calls, chunks, multi_chunk_calls, forced_wait_boundaries, + lists_marked, backing_mark_writes, signal_attempts, signal_failures, + state_lock_wait_ns, state_lock_hold_ns, +); + +fn add_duration(counter: &AtomicU64, elapsed: std::time::Duration) { + counter.fetch_add(elapsed.as_nanos().min(u64::MAX as u128) as u64, Ordering::Relaxed); +} + +struct SubmitStateGuard<'a> { + guard: MutexGuard<'a, Option>, + held: std::time::Instant, +} + +impl Deref for SubmitStateGuard<'_> { + type Target = Option; + fn deref(&self) -> &Self::Target { &self.guard } +} + +impl DerefMut for SubmitStateGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.guard } +} + +impl Drop for SubmitStateGuard<'_> { + fn drop(&mut self) { + add_duration(&SUBMIT.state_lock_hold_ns, self.held.elapsed()); + } +} + +fn lock_for_submit() -> SubmitStateGuard<'static> { + let waiting = std::time::Instant::now(); + let guard = STATE.lock().unwrap(); + add_duration(&SUBMIT.state_lock_wait_ns, waiting.elapsed()); + SubmitStateGuard { guard, held: std::time::Instant::now() } +} + +pub fn note_execute_call(chunks: usize) { + let (multi_chunk, boundaries) = execute_topology(chunks); + SUBMIT.outer_execute_calls.fetch_add(1, Ordering::Relaxed); + SUBMIT.chunks.fetch_add(chunks as u64, Ordering::Relaxed); + SUBMIT.multi_chunk_calls.fetch_add(multi_chunk, Ordering::Relaxed); + SUBMIT.forced_wait_boundaries.fetch_add(boundaries, Ordering::Relaxed); +} + +fn execute_topology(chunks: usize) -> (u64, u64) { + ((chunks > 1) as u64, chunks.saturating_sub(1) as u64) +} + +#[derive(Clone, Copy)] +struct SubmitEntry { + list: usize, + backing: Option, + recording: u64, + lifetime: u64, +} + +/// A fail-closed reservation made before native ExecuteCommandLists. Dropping it before +/// `execution_possible` releases the reservation because no GPU work can refer to it yet. +#[must_use] +pub(super) struct BeginSubmit { + entries: Vec, +} + +/// A reservation armed immediately before native execution. Once armed, execution may begin at +/// any point, so dropping it before `finish` deliberately leaves its allocator and lists pinned. +#[must_use] +pub(super) struct PendingSubmit { + entries: Vec, +} + +/// Exact queue progress after a native submission. Keeping the fence owner makes this receipt +/// independent of a command queue raw address being released and reused for another generation. +#[derive(Clone)] +#[allow(dead_code)] // consumed by the later opt-in generation-pin stage +pub(super) struct SubmissionReceipt { + fence: ID3D12Fence, + value: u64, +} + +#[allow(dead_code)] // consumed by the later opt-in generation-pin stage +impl SubmissionReceipt { + /// Whether the GPU is past the native submission represented by this receipt. + pub(super) fn is_complete(&self) -> bool { + unsafe { self.fence.GetCompletedValue() >= self.value } + } +} + +/// Result of a receipt-requesting submission. Once execution begins, failure to mark it cannot +/// be turned back into `NotExecuted`: callers must retain dependent objects indefinitely. +#[allow(dead_code)] // consumed by the later opt-in generation-pin stage +pub(super) enum ReceiptedSubmission { + NotExecuted, + Executed(SubmissionReceipt), + ExecutedUntracked, +} + +fn release_submit_pins(s: &mut State, entries: &[SubmitEntry]) { + for entry in entries { + let key = (entry.list, entry.lifetime); + if let Some(n) = s.submit_pins.get_mut(&key) { + *n -= 1; + if *n == 0 { + s.submit_pins.remove(&key); + } + } + if let Some(backing) = entry.backing.and_then(|b| s.backings.get_mut(&b)) { + backing.submit_pins = backing.submit_pins.saturating_sub(1); + } + } +} + +fn record_submit(s: &mut State, entries: &[SubmitEntry], queue: usize, fence: &ID3D12Fence, value: u64) -> (u64, Vec) { + let mut backing_mark_writes = 0; + let mut replaced = Vec::new(); + for entry in entries { + if let Some(backing) = entry.backing { + backing_mark_writes += 1; + let backing = backing_mut(s, backing); + backing.already_reset = false; + if let Some((old, _)) = backing.marks.insert(queue, (fence.clone(), value)) { + replaced.push(old); + } + } + if s.list_lifetimes.get(&entry.list) == Some(&entry.lifetime) { + if let Some(old) = s.last_submit.insert( + entry.list, + LastSubmit { queue, fence: fence.clone(), value, recording: entry.recording }, + ) { + replaced.push(old.fence); + } + } + } + release_submit_pins(s, entries); + (backing_mark_writes, replaced) +} + +/// Capture and pin the exact backing and recording that a native submit will execute. The caller +/// must keep this token until it knows ExecuteCommandLists cannot have run, or convert it with +/// `execution_possible` immediately before making the native call. +pub(super) fn begin_submit(lists: &[*mut c_void]) -> Option { + sweep_release_owners(); + if !enabled() { + return Some(BeginSubmit { entries: Vec::new() }); + } + let mut entries = Vec::new(); + entries.try_reserve(lists.len()).ok()?; + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.list_lifetimes.try_reserve(lists.len()).ok()?; + s.submit_pins.try_reserve(lists.len()).ok()?; + for &list in lists { + let list = list as usize; + if entries.iter().any(|entry: &SubmitEntry| entry.list == list) { + continue; + } + let lifetime = match s.list_lifetimes.get(&list) { + Some(&lifetime) => lifetime, + None => { + s.next_list_lifetime = s.next_list_lifetime.wrapping_add(1).max(1); + s.list_lifetimes.insert(list, s.next_list_lifetime); + s.next_list_lifetime + } + }; + entries.push(SubmitEntry { + list, + backing: s.of_list.get(&list).copied(), + recording: s.recordings.get(&list).copied().unwrap_or(0), + lifetime, + }); + } + for entry in &entries { + *s.submit_pins.entry((entry.list, entry.lifetime)).or_default() += 1; + if let Some(backing) = entry.backing { + s.backings.get_mut(&backing).unwrap().submit_pins += 1; + } + } + Some(BeginSubmit { entries }) +} + +impl BeginSubmit { + /// Arm immediately before calling native ExecuteCommandLists. From this point onward, any + /// unwind, drop, or completion-mark failure must retain the reservation permanently. + pub(super) fn execution_possible(mut self) -> PendingSubmit { + PendingSubmit { entries: std::mem::take(&mut self.entries) } + } +} + +impl Drop for BeginSubmit { + fn drop(&mut self) { + if !self.entries.is_empty() { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + release_submit_pins(s, &self.entries); + } + drop(g); + sweep_release_owners(); + } + } +} + +impl PendingSubmit { + /// Associate the captured submit with the queue's existing retirement fence. `false` leaves + /// all reservations permanently pinned: execution may have happened but cannot be retired. + pub(super) unsafe fn finish(self, queue: *mut c_void) -> bool { + if self.entries.is_empty() { + return true; + } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return false }; + let key = queue as usize; + super::queue_submit::with(key, || self.finish_with_queue_ops( + key, + || { + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok() + }, + |fence, value| super::real::native_queue_signal(q, fence, value).is_ok(), + )) + } + + /// Mark a submission and return its exact queue fence/value. Unlike `finish`, this also makes + /// a marker when allocator swapping is disabled and therefore `entries` is empty. + #[allow(dead_code)] // consumed through `submit_receipted` by the later generation-pin stage + unsafe fn finish_receipted(self, queue: *mut c_void) -> Option { + let q = ID3D12CommandQueue::from_raw_borrowed(&queue)?; + let key = queue as usize; + super::queue_submit::with(key, || self.finish_with_queue_ops_receipted( + key, + || { + let mut dev: Option = None; + q.GetDevice(&mut dev).ok()?; + dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok() + }, + |fence, value| super::real::native_queue_signal(q, fence, value).is_ok(), + )) + } + + /// The queue turn excludes another thread while the state lock is released around driver + /// calls. An `Arc` keeps the exact marker alive; replacement means the queue generation was + /// invalidated, so the submitted work deliberately remains pinned. + fn finish_with_queue_ops( + self, + key: usize, + create: impl FnOnce() -> Option, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> bool { + if self.entries.is_empty() { + return true; + } + self.finish_with_queue_ops_inner(key, create, signal).is_some() + } + + #[allow(dead_code)] // production consumer lands with the generation-pin stage + fn finish_with_queue_ops_receipted( + self, + key: usize, + create: impl FnOnce() -> Option, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> Option { + // `begin_submit` intentionally does not initialize allocator state when swapping is off; + // a requested receipt still needs the shared queue-generation marker namespace. + if self.entries.is_empty() { + STATE.lock().unwrap().get_or_insert_with(State::default); + } + self.finish_with_queue_ops_inner(key, create, signal) + } + + fn finish_with_queue_ops_inner( + mut self, + key: usize, + create: impl FnOnce() -> Option, + signal: impl FnOnce(&ID3D12Fence, u64) -> bool, + ) -> Option { + let marker = { + let g = lock_for_submit(); + let s = g.as_ref()?; + s.fences.get(&key).cloned() + }; + let marker = match marker { + Some(marker) => marker, + None => { + let fence = create()?; + let made = Arc::new(QueueFence::new(fence)); + let mut g = lock_for_submit(); + let s = g.as_mut()?; + let (marker, unused) = match s.fences.entry(key) { + Entry::Occupied(entry) => (Arc::clone(entry.get()), Some(made)), + Entry::Vacant(entry) => { + let marker = Arc::clone(&made); + entry.insert(made); + (marker, None) + } + }; + drop(g); + drop(unused); + marker + } + }; + // Reserve before entering the driver. The queue lease excludes another thread, while an + // atomic reservation lets intentional same-thread re-entry take a distinct later value. + // A failed Signal burns its value; its submit remains pinned and a gap is harmless. + let Ok(value) = marker.next_value.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |v| v.checked_add(1)) else { + return None; + }; + let value = value + 1; + SUBMIT.signal_attempts.fetch_add(1, Ordering::Relaxed); + if !signal(&marker.fence, value) { + SUBMIT.signal_failures.fetch_add(1, Ordering::Relaxed); + return None; + } + let fence = marker.fence.clone(); + let mut g = lock_for_submit(); + let s = g.as_mut()?; + if s.fences.get(&key).is_none_or(|current| !Arc::ptr_eq(current, &marker)) { + return None; + } + let (backing_mark_writes, replaced) = record_submit(s, &self.entries, key, &fence, value); + SUBMIT.lists_marked.fetch_add(self.entries.len() as u64, Ordering::Relaxed); + SUBMIT.backing_mark_writes.fetch_add(backing_mark_writes, Ordering::Relaxed); + self.entries.clear(); + drop(g); + drop(replaced); + sweep_release_owners(); + Some(SubmissionReceipt { fence, value }) + } + + #[cfg(test)] + fn finish_with_mark(mut self, queue: usize, fence: &ID3D12Fence, value: u64) { + let mut g = STATE.lock().unwrap(); + let (_, replaced) = record_submit(g.as_mut().unwrap(), &self.entries, queue, fence, value); + self.entries.clear(); + drop(g); + drop(replaced); + } +} + +fn reserve_and_execute_with( + failed: &mut bool, + begin: impl FnOnce() -> Option, + prepare: impl FnOnce(), + arm: impl FnOnce(B) -> P, + execute: impl FnOnce(), + finish: impl FnOnce(P) -> bool, +) -> bool { + if *failed { + return false; + } + let Some(begin) = begin() else { + *failed = true; + return false; + }; + prepare(); + let pending = arm(begin); + execute(); + let _ = finish(pending); + true +} + +#[derive(Default)] +pub(super) struct SubmissionGate { + failed: bool, +} + +impl SubmissionGate { + /// `prepare` runs before the reservation is armed; `execute` must contain only the native call. + pub(super) unsafe fn submit( + &mut self, + queue: *mut c_void, + lists: &[*mut c_void], + prepare: impl FnOnce(), + execute: impl FnOnce(), + ) -> bool { + reserve_and_execute_with( + &mut self.failed, + || begin_submit(lists), + prepare, + BeginSubmit::execution_possible, + execute, + |pending| pending.finish(queue), + ) + } + + /// Submit and request an exact retirement receipt. The existing `submit` path remains the + /// zero-extra-marker path; this variant is for future resources that need queue-fenced pins. + #[allow(dead_code)] // production consumer lands with the generation-pin stage + pub(super) unsafe fn submit_receipted( + &mut self, + queue: *mut c_void, + lists: &[*mut c_void], + prepare: impl FnOnce(), + execute: impl FnOnce(), + ) -> ReceiptedSubmission { + if self.failed { + return ReceiptedSubmission::NotExecuted; + } + let Some(begin) = begin_submit(lists) else { + self.failed = true; + return ReceiptedSubmission::NotExecuted; + }; + prepare(); + let pending = begin.execution_possible(); + execute(); + match pending.finish_receipted(queue) { + Some(receipt) => ReceiptedSubmission::Executed(receipt), + None => { + self.failed = true; + ReceiptedSubmission::ExecutedUntracked + } + } + } + + pub(super) fn failed(&self) -> bool { + self.failed + } +} + /// `XCL_ALLOC_SWAP=0` turns it off. pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -81,7 +794,27 @@ fn move_list(s: &mut State, list: usize, backing: usize) { } } } - s.backings.entry(backing).or_default().users.insert(list); + let backing = backing_mut(s, backing); + backing.users.insert(list); + backing.already_reset = false; +} + +/// Detach a recording that is no longer in the title list's submission graph. Its object +/// lifetime, last submit and submit pins remain, so address reuse and GPU completion stay exact. +pub(super) fn retire_recording(list: usize) { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + retire_recording_in(s, list); + drop(g); + sweep_release_owners(); +} + +fn retire_recording_in(s: &mut State, list: usize) { + if let Some(backing) = s.of_list.remove(&list) { + if let Some(backing) = s.backings.get_mut(&backing) { + backing.users.remove(&list); + } + } } /// The PC list's final Release ended its recording. Submitted work still holds the backing @@ -89,13 +822,19 @@ fn move_list(s: &mut State, list: usize, backing: usize) { pub(super) fn forget_list(list: usize) { let mut g = STATE.lock().unwrap(); let Some(s) = g.as_mut() else { return }; - s.last_submit.remove(&list); + let last_submit = s.last_submit.remove(&list); s.recordings.remove(&list); + if let Some(lifetime) = s.list_lifetimes.remove(&list) { + s.submit_pins.remove(&(list, lifetime)); + } if let Some(backing) = s.of_list.remove(&list) { if let Some(b) = s.backings.get_mut(&backing) { b.users.remove(&list); } } + drop(g); + drop(last_submit); + sweep_release_owners(); } /// Reset `list` on the title's allocator `alloc`, committing its new recording association @@ -153,27 +892,54 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize if !enabled() { return 0; } - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return 0 }; - let mut found = 0; - for &l in lists { - let l = l as usize; - let Some(last) = s.last_submit.get(&l) else { continue }; - if last.fence.GetCompletedValue() >= last.value { - continue; + // A driver query may block or call back into XCL. Keep strong fence snapshots alive, but + // never make GetCompletedValue while the allocator pool's global state is locked. + let mut probes = Vec::with_capacity(lists.len()); + { + let g = lock_for_submit(); + let Some(s) = g.as_ref() else { return 0 }; + for &list in lists { + let list = list as usize; + if let (Some(&lifetime), Some(last)) = (s.list_lifetimes.get(&list), s.last_submit.get(&list)) { + probes.push((list, lifetime, last.clone())); + } } - let same_recording = s.recordings.get(&l).copied().unwrap_or(0) == last.recording; - let same_queue = last.queue == queue as usize; - found += 1; - s.resubmits += 1; - let n = s.resubmits; - if n <= 8 || n.is_power_of_two() { - crate::xlog_warn!( - "D3D12.X: a command list is submitted while its previous submit is still on the GPU ({}, {}; #{n} so far) – the PC does not allow it (debug layer id 553)", - if same_recording { "the same recording" } else { "a new recording" }, - if same_queue { "the same queue" } else { "another queue" }, - ); + } + let incomplete: Vec<_> = probes + .into_iter() + .filter(|(_, _, last)| last.fence.GetCompletedValue() < last.value) + .collect(); + if incomplete.is_empty() { + return 0; + } + let mut warnings = Vec::with_capacity(incomplete.len()); + let found = { + let mut g = lock_for_submit(); + let Some(s) = g.as_mut() else { return 0 }; + let mut found = 0; + for (list, lifetime, observed) in incomplete { + if s.list_lifetimes.get(&list) != Some(&lifetime) + || s.last_submit.get(&list).is_none_or(|current| !same_submit(current, &observed)) + { + continue; + } + let same_recording = s.recordings.get(&list).copied().unwrap_or(0) == observed.recording; + let same_queue = observed.queue == queue as usize; + found += 1; + s.resubmits += 1; + let n = s.resubmits; + if n <= 8 || n.is_power_of_two() { + warnings.push((same_recording, same_queue, n)); + } } + found + }; + for (same_recording, same_queue, n) in warnings { + crate::xlog_warn!( + "D3D12.X: a command list is submitted while its previous submit is still on the GPU ({}, {}; #{n} so far) – the PC does not allow it (debug layer id 553)", + if same_recording { "the same recording" } else { "a new recording" }, + if same_queue { "the same queue" } else { "another queue" }, + ); } found } @@ -181,141 +947,405 @@ pub unsafe fn note_resubmits(queue: *mut c_void, lists: &[*mut c_void]) -> usize /// Whether the GPU has not finished the last submit of the PC list `list` (#1452: it must not be /// submitted again before that; `title_list` records the title's next recording elsewhere). pub fn in_flight(list: usize) -> bool { + let (lifetime, last) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + let Some(&lifetime) = s.list_lifetimes.get(&list) else { return false }; + if s.submit_pins.get(&(list, lifetime)).copied().unwrap_or(0) != 0 { + return true; + } + let Some(last) = s.last_submit.get(&list).cloned() else { return false }; + (lifetime, last) + }; + if unsafe { last.fence.GetCompletedValue() } < last.value { + return true; + } + // If the address changed generation, or another submit was reserved/published while the + // driver call ran, fail closed. The caller may spend another list/allocator but cannot reset + // storage that newly became busy. let g = STATE.lock().unwrap(); - g.as_ref().and_then(|s| s.last_submit.get(&list)).is_some_and(|l| unsafe { l.fence.GetCompletedValue() } < l.value) + let Some(s) = g.as_ref() else { return false }; + s.list_lifetimes.get(&list) != Some(&lifetime) + || s.submit_pins.get(&(list, lifetime)).copied().unwrap_or(0) != 0 + || s.last_submit.get(&list).is_none_or(|current| !same_submit(current, &last)) } -/// `lists` were just submitted to `queue`. +/// Compatibility helper for tests that submit directly instead of using `SubmissionGate`. +#[cfg(test)] pub unsafe fn executed(queue: *mut c_void, lists: &[*mut c_void]) { - if !enabled() || queue.is_null() { - return; - } - // (every submit is marked, also of lists this module does not track – the PC lists behind - // console lists – so note_resubmits sees them all) - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; - let key = queue as usize; - if !s.fences.contains_key(&key) { - let mut dev: Option = None; - let Some(f) = q.GetDevice(&mut dev).ok().and(dev).and_then(|d| d.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()) else { return }; - s.fences.insert(key, (f, 0)); - } - let (fence, value) = { - let (f, v) = s.fences.get_mut(&key).unwrap(); - if q.Signal(&*f, *v + 1).is_err() { - return; - } - *v += 1; - (f.clone(), *v) - }; - for &l in lists { - if let Some(&b) = s.of_list.get(&(l as usize)) { - s.backings.entry(b).or_default().marks.insert(key, (fence.clone(), value)); - } - let recording = s.recordings.get(&(l as usize)).copied().unwrap_or(0); - s.last_submit.insert(l as usize, LastSubmit { queue: key, fence: fence.clone(), value, recording }); - } + let Some(begin) = begin_submit(lists) else { return }; + let _ = begin.execution_possible().finish(queue); } /// Whether the GPU may still run a recording made on the title's allocator `alloc`. pub(super) unsafe fn allocator_in_flight(alloc: usize) -> bool { - let g = STATE.lock().unwrap(); - let Some(s) = g.as_ref() else { return false }; - let mine = s.cur.get(&alloc).into_iter().chain(s.aside.get(&alloc).into_iter().flatten()).chain([&alloc]); - let busy = mine.filter_map(|b| s.backings.get(b)).any(|b| b.marks.values().any(|(f, v)| f.GetCompletedValue() < *v)); - busy + let (mine, probes) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + namespace_probes(s, alloc) + }; + let busy = probes.iter().any(|probe| probe.in_flight()); + let stable = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return false }; + namespace_matches(s, alloc, &mine, &probes) + }; + sweep_release_owners(); + busy || !stable } -/// The title's allocator `alloc` is gone (its last Release): nothing of it stays here – a later -/// allocator may get its address, and must not go on with this one's PC allocators. The ones -/// made here go with it (those lists still record on are left alone: not freed, not tracked). -pub unsafe fn forget(alloc: usize) { - let made: Vec = { - let mut g = STATE.lock().unwrap(); - let Some(s) = g.as_mut() else { return }; - s.types.remove(&alloc); - let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); - mine.extend(s.cur.remove(&alloc)); - mine.push(alloc); - let mut made = Vec::new(); - for b in mine { - let free = s.backings.get(&b).is_none_or(|x| x.free()); - if let Some(gone) = s.backings.remove(&b) { - for l in gone.users { - s.of_list.remove(&l); - } +/// The title's allocator `alloc` reached its logical final Release. Detach its namespace now; +/// backings still used by recordings/submits retain their native owner until a later sweep. +unsafe fn forget_in(s: &mut State, alloc: usize, free: &HashSet) -> (Vec, Vec) { + s.types.remove(&alloc); + s.resetting.remove(&alloc); + let mut mine: Vec = s.aside.remove(&alloc).unwrap_or_default(); + mine.extend(s.cur.remove(&alloc)); + mine.push(alloc); + mine.sort_unstable(); + mine.dedup(); + let mut made = Vec::new(); + let mut removed = Vec::new(); + for b in mine { + if s.backings.contains_key(&b) && !free.contains(&b) { + if let Some(backing) = s.backings.get_mut(&b) { + backing.retire_when_free = true; + } + continue; + } + if let Some(mut gone) = s.backings.remove(&b) { + for l in gone.users.drain() { + s.of_list.remove(&l); } - if b != alloc && free { + if gone.release_owner.is_none() && b != alloc { made.push(b); } + removed.push(gone); + } else if b != alloc { + made.push(b); } - made - }; - // (outside the lock: their Release comes back here) - for b in made { - drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); } + (made, removed) } -/// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a -/// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put -/// aside with its recordings and another one took its place. +pub unsafe fn forget(alloc: usize) { + let (made, removed, free) = loop { + let (mine, probes) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { + drop(g); + super::console_list::allocator_reset(alloc as *mut c_void); + return; + }; + namespace_probes(s, alloc) + }; + let free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if namespace_matches(s, alloc, &mine, &probes) { + let (made, removed) = forget_in(s, alloc, &free); + break (made, removed, free); + } + }; + // Native backing ownership also keys console UMA allocations. Free only backings whose + // exact generation was proved idle, and do it outside STATE because freeing can re-enter. + for raw in free { + super::console_list::allocator_reset(raw as *mut c_void); + } + for mut backing in removed { + let owner = backing.release_owner.take(); + drop(backing); + if let Some(owner) = owner { + super::real::release_retained_allocator(owner); + } + } + // (outside the lock: their Release comes back here) + for b in made { + drop(ID3D12CommandAllocator::from_raw(b as *mut c_void)); + } +} + +/// Reset every idle aside backing once. The namespace token and backing probes make a driver +/// callback, final Release, or newly recorded list invalidate the whole unlocked batch. +unsafe fn reclaim_idle_aside(alloc: *mut c_void) { + let a = alloc as usize; + let claim = loop { + let (mine, probes, free) = { + let g = STATE.lock().unwrap(); + let Some(s) = g.as_ref() else { return }; + if s.resetting.contains_key(&a) { return } + let (mine, probes) = namespace_probes(s, a); + let free = probes.iter().filter(|probe| probe.free()).map(|probe| probe.raw).collect::>(); + (mine, probes, free) + }; + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return }; + if !namespace_matches(s, a, &mine, &probes) { continue } + if s.resetting.contains_key(&a) { return } + let mut work = Vec::new(); + for raw in s.aside.get(&a).into_iter().flatten().copied() { + let Some(probe) = probes.iter().find(|probe| probe.raw == raw && free.contains(&raw) && !probe.already_reset) else { continue }; + let raw_ptr = raw as *mut c_void; + if let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw_ptr).cloned() { + work.push((probe.clone(), owner)); + } + } + if work.is_empty() { return } + let token = reserve_reset(s, a).unwrap(); + break IdleResetClaim { alloc: a, token, mine, probes, work }; + }; + + let IdleResetClaim { alloc, token, mine, probes, work } = claim; + let results = work.into_iter().map(|(probe, owner)| { + let ok = run_reset(owner.as_raw(), |raw| super::real::reset_pc_allocator(raw)) >= 0; + (probe, owner, ok) + }).collect::>(); + let successful = results.iter().filter(|(_, _, ok)| *ok).map(|(probe, _, _)| probe.clone()).collect::>(); + let mut retired = Vec::new(); + { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { + commit_idle_resets(s, alloc, token, &mine, &probes, &successful, &mut retired); + } + } + drop(retired); + drop(results); +} + +fn commit_idle_resets( + s: &mut State, + alloc: usize, + token: u64, + mine: &[usize], + probes: &[BackingProbe], + successful: &[BackingProbe], + retired: &mut Vec, +) -> bool { + let valid = s.resetting.get(&alloc) == Some(&token) && namespace_matches(s, alloc, mine, probes); + if valid { + for probe in successful { + if s.aside.get(&alloc).is_some_and(|aside| aside.contains(&probe.raw)) { + if let Some(backing) = s.backings.get_mut(&probe.raw) { + retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); + backing.already_reset = true; + } + } + } + } + cancel_reset(s, alloc, token); + valid +} + +/// Free spares owned by another title allocator of the same type. The backing snapshot lets the +/// caller ask the driver fences outside STATE, then reject a candidate whose use changed meanwhile. +fn shared_aside_probes(s: &State, alloc: usize, ty: i32) -> Vec<(usize, usize, Option)> { + s.aside.iter().filter(|(owner, _)| { + **owner != alloc && s.types.get(owner) == Some(&ty) && !s.resetting.contains_key(owner) + }).flat_map(|(&owner, aside)| { + aside.iter().copied().filter(move |&raw| raw != owner).map(move |raw| { + (owner, raw, s.backings.get(&raw).map(|backing| BackingProbe::new(raw, backing))) + }) + }).collect() +} + +/// Transfer one still-free shared spare into `alloc`'s namespace. A donor with a reset in progress +/// is skipped: its unlocked driver call may already target the candidate. +fn take_shared_aside( + s: &mut State, + alloc: usize, + ty: i32, + candidates: &[(usize, usize, Option)], + free: &HashSet, +) -> bool { + for (owner, raw, observed) in candidates { + if !free.contains(raw) + || s.types.get(owner) != Some(&ty) + || s.resetting.contains_key(owner) + || s.aside.get(owner).is_none_or(|aside| !aside.contains(raw)) + { + continue; + } + let stable = match (observed, s.backings.get(raw)) { + (Some(probe), Some(backing)) => probe.matches(backing), + (None, None) => true, + _ => false, + }; + if !stable { + continue; + } + let aside = s.aside.get_mut(owner).unwrap(); + aside.remove(aside.iter().position(|candidate| candidate == raw).unwrap()); + s.aside.entry(alloc).or_default().push(*raw); + return true; + } + false +} + +/// The title resets its allocator `alloc`. `None`: reset it as it is (nothing holds a +/// recording on it, or this is off). `Some(hr)`: done here – the PC allocator in use was put +/// aside with its recordings and another one took its place. pub unsafe fn title_reset(alloc: *mut c_void) -> Option { if !enabled() { return None; } - let mut g = STATE.lock().unwrap(); - let s = g.get_or_insert_with(State::default); - title_reset_in(s, alloc, |raw| super::real::reset_pc_allocator(raw)) -} - -/// The allocator transition, with the PC Reset supplied so failure/retry needs no GPU in tests. -unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMut(*mut c_void) -> HRESULT) -> Option { let a = alloc as usize; - let c = s.cur.get(&a).copied().unwrap_or(a); - if s.backings.get(&c).is_none_or(|b| b.free()) { - if let Some(b) = s.backings.get_mut(&c) { - b.marks.clear(); + let claim = loop { + let (mine, probes, shared) = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + if s.resetting.contains_key(&a) { + return Some(crate::util::E_FAIL); + } + let (mine, probes) = namespace_probes(s, a); + let shared = s.types.get(&a).map(|&ty| shared_aside_probes(s, a, ty)).unwrap_or_default(); + (mine, probes, shared) + }; + let mut free: HashSet<_> = probes.iter().filter(|probe| unsafe { probe.free() }).map(|probe| probe.raw).collect(); + free.extend(shared.iter().filter_map(|(_, raw, probe)| { + probe.as_ref().is_none_or(|probe| unsafe { probe.free() }).then_some(*raw) + })); + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return None }; + if !namespace_matches(s, a, &mine, &probes) { + continue; } - if c == a { - return None; + if s.resetting.contains_key(&a) { + return Some(crate::util::E_FAIL); } - return Some(reset(c as *mut c_void)); - } - let ty = *s.types.get(&a)?; - // one put aside earlier that nothing uses any more, or a new one - let reuse = s.aside.get(&a).and_then(|v| v.iter().copied().find(|f| s.backings.get(f).is_none_or(|b| b.free()))); - let next = match reuse { - Some(f) => { - // Keep ownership until Reset succeeds so a failure can be retried. - let hr = reset(f as *mut c_void); - if hr < 0 { - return Some(hr); + let current = s.cur.get(&a).copied().unwrap_or(a); + if !s.backings.contains_key(¤t) || free.contains(¤t) { + if current == a { + let retired = s.backings.get_mut(¤t) + .map(|backing| backing.marks.drain().map(|(_, (fence, _))| fence).collect::>()) + .unwrap_or_default(); + drop(g); + drop(retired); + drop(probes); + reclaim_idle_aside(alloc); + return None; } - s.aside.get_mut(&a).unwrap().retain(|&x| x != f); - if let Some(b) = s.backings.get_mut(&f) { - b.marks.clear(); + let raw = current as *mut c_void; + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + let needed = s.backings.get(¤t).is_none_or(|backing| !backing.already_reset); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: false, needed } }; + } + let Some(&ty) = s.types.get(&a) else { return Some(crate::util::E_FAIL) }; + if let Some(candidate) = s.aside.get(&a).and_then(|values| values.iter().copied().find(|raw| !s.backings.contains_key(raw) || free.contains(raw))) { + let raw = candidate as *mut c_void; + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&raw).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + let needed = s.backings.get(&candidate).is_none_or(|backing| !backing.already_reset); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Reset { owner, swap: true, needed } }; + } + if take_shared_aside(s, a, ty, &shared, &free) { + // Restart so the transferred candidate participates in this namespace's snapshot and + // reset token exactly like a spare it had always owned. + continue; + } + let Some(owner) = ID3D12CommandAllocator::from_raw_borrowed(&alloc).cloned() else { return Some(crate::util::E_FAIL) }; + let token = reserve_reset(s, a).unwrap(); + break ResetClaim { alloc: a, current, token, mine, probes, work: ResetWork::Create { owner, ty } }; + }; + + let ResetClaim { alloc, current, token, mine, probes, work } = claim; + match work { + ResetWork::Reset { owner, swap, needed } => { + let candidate = owner.as_raw() as usize; + let hr = if needed { run_reset(owner.as_raw(), |raw| super::real::reset_pc_allocator(raw)) } else { 0 }; + let mut retired = Vec::new(); + let result = { + let mut g = STATE.lock().unwrap(); + let Some(s) = g.as_mut() else { return Some(crate::util::E_FAIL) }; + if hr >= 0 && commit_reset(s, alloc, current, candidate, token, &mine, &probes, swap, false, &mut retired) { + hr + } else { + cancel_reset(s, alloc, token); + if hr < 0 { hr } else { crate::util::E_FAIL } + } + }; + drop(retired); + drop(owner); + if result >= 0 { + reclaim_idle_aside(alloc as *mut c_void); } - f + Some(result) } - None => { - let this = ID3D12CommandAllocator::from_raw_borrowed(&alloc)?; + ResetWork::Create { owner, ty } => { let mut dev: Option = None; - this.GetDevice(&mut dev).ok()?; - let made: ID3D12CommandAllocator = dev?.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).ok()?; + let made: Result = match owner.GetDevice(&mut dev) { + Err(error) => Err(error.code().0), + Ok(()) => match dev { + Some(dev) => dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE(ty)).map_err(|error| error.code().0), + None => Err(crate::util::E_FAIL), + }, + }; + let made = match made { + Ok(made) => made, + Err(error) => { + let mut g = STATE.lock().unwrap(); + if let Some(s) = g.as_mut() { cancel_reset(s, alloc, token); } + return Some(error); + } + }; let raw = made.into_raw(); - // (made through the title's device it is adopted already) if !super::real::is_adopted(raw) { super::real::adopt(raw, super::real::Kind::CommandAllocator); } - s.made += 1; - raw as usize + let mut retired = Vec::new(); + let committed = { + let mut g = STATE.lock().unwrap(); + g.as_mut().is_some_and(|s| commit_reset(s, alloc, current, raw as usize, token, &mine, &probes, true, true, &mut retired)) + }; + drop(retired); + drop(owner); + if committed { + reclaim_idle_aside(alloc as *mut c_void); + Some(0) + } else { + drop(ID3D12CommandAllocator::from_raw(raw)); + Some(crate::util::E_FAIL) + } } - }; - s.aside.entry(a).or_default().push(c); - s.cur.insert(a, next); + } +} + +fn commit_reset( + s: &mut State, + alloc: usize, + current: usize, + candidate: usize, + token: u64, + mine: &[usize], + probes: &[BackingProbe], + swap: bool, + created: bool, + retired: &mut Vec, +) -> bool { + if s.resetting.get(&alloc) != Some(&token) || !namespace_matches(s, alloc, mine, probes) { + cancel_reset(s, alloc, token); + return false; + } + if swap && !created { + let Some(position) = s.aside.get(&alloc).and_then(|values| values.iter().position(|raw| *raw == candidate)) else { + cancel_reset(s, alloc, token); + return false; + }; + s.aside.get_mut(&alloc).unwrap().remove(position); + } + if let Some(backing) = s.backings.get_mut(&candidate) { + retired.extend(backing.marks.drain().map(|(_, (fence, _))| fence)); + backing.already_reset = true; + } + if !swap { + cancel_reset(s, alloc, token); + return true; + } + s.aside.entry(alloc).or_default().push(current); + s.cur.insert(alloc, candidate); + if created { s.made += 1; } s.swaps += 1; + cancel_reset(s, alloc, token); if s.swaps.is_power_of_two() { let aside: usize = s.aside.values().map(|v| v.len()).sum(); crate::xlog_info!( @@ -324,7 +1354,7 @@ unsafe fn title_reset_in(s: &mut State, alloc: *mut c_void, mut reset: impl FnMu s.made ); } - Some(0) + true } #[cfg(test)] @@ -332,44 +1362,924 @@ mod tests { use super::*; #[test] - fn a_spare_whose_reset_fails_stays_available_for_retry() { + fn release_probe_transfers_only_the_logical_final_reference() { + use std::cell::Cell; + let refs = Cell::new(1u32); + let retained = Cell::new(0u32); + let (remaining, transferred) = release_with_probe( + || refs.set(refs.get() + 1), + || { + refs.set(refs.get() - 1); + refs.get() + }, + || { + retained.set(retained.get() + 1); + true + }, + ); + assert_eq!((remaining, transferred, refs.get(), retained.get()), (0, true, 1, 1)); + refs.set(refs.get() - 1); // the out-of-lock sweep releases the transferred probe + assert_eq!(refs.get(), 0); + + refs.set(2); + retained.set(0); + let (remaining, transferred) = release_with_probe( + || refs.set(refs.get() + 1), + || { + refs.set(refs.get() - 1); + refs.get() + }, + || { + retained.set(retained.get() + 1); + true + }, + ); + assert_eq!((remaining, transferred, refs.get(), retained.get()), (1, false, 1, 0)); + } + + #[test] + fn release_probe_retries_a_same_address_backing_replacement() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + static REPLACE: AtomicBool = AtomicBool::new(false); + static KEY: AtomicUsize = AtomicUsize::new(0); + #[repr(C)] + struct Object { vtable: *const usize, value: Cell, refs: Cell } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + if REPLACE.swap(false, Ordering::Relaxed) { + let gone = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let key = KEY.load(Ordering::Relaxed); + let gone = s.backings.remove(&key).unwrap(); + backing_mut(s, key); + gone + }; + drop(gone); + } + (*this.cast::()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let o = &*this.cast::(); + o.refs.set(o.refs.get() + 1); + o.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let o = &*this.cast::(); + o.refs.set(o.refs.get() - 1); + o.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + const SLOT: usize = size_of::(); + let mut fence_vtable = [unexpected_call as usize; size_of::() / SLOT]; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + fence_vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let allocator_vtable = [unexpected_call as usize, add_ref as usize, release as usize]; + let mut fence_object = Object { vtable: fence_vtable.as_ptr(), value: Cell::new(1), refs: Cell::new(1) }; + let mut allocator_object = Object { vtable: allocator_vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(2) }; + let fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut fence_object).cast()) }; + let root = unsafe { ID3D12CommandAllocator::from_raw(std::ptr::from_mut(&mut allocator_object).cast()) }; + let caller_probe = unsafe { ID3D12CommandAllocator::from_raw(root.as_raw()) }; + let key = root.as_raw() as usize; + let first_generation = { + let mut g = STATE.lock().unwrap(); + let backing = backing_mut(g.get_or_insert_with(State::default), key); + backing.marks.insert(7, (fence.clone(), 2)); + backing.generation + }; + KEY.store(key, Ordering::Relaxed); + REPLACE.store(true, Ordering::Relaxed); + let retained = unsafe { retain_release_probe(caller_probe.as_raw()) }; + if retained { std::mem::forget(caller_probe) } else { drop(caller_probe) } + let replacement = { + let mut g = STATE.lock().unwrap(); + g.as_mut().unwrap().backings.remove(&key).unwrap() + }; + assert!(!replacement.release_owner.is_some()); + assert_ne!(replacement.generation, first_generation); + drop(replacement); + drop(root); + drop(fence); + assert!(!retained, "the replacement must be probed before accepting the caller's reference"); + assert_eq!((allocator_object.refs.get(), fence_object.refs.get()), (0, 0)); + } + + #[test] + fn completion_queries_run_outside_allocator_state() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; + + static OUTSIDE: AtomicBool = AtomicBool::new(false); + static MUTATE: AtomicBool = AtomicBool::new(false); + static MUTATE_BACKING: AtomicUsize = AtomicUsize::new(0); + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell, + refs: Cell, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + let outside = STATE.try_lock().is_ok(); + OUTSIDE.store(outside, Ordering::Relaxed); + if outside && MUTATE.swap(false, Ordering::Relaxed) { + let mut g = STATE.lock().unwrap(); + if let Some(backing) = g + .as_mut() + .and_then(|s| s.backings.get_mut(&MUTATE_BACKING.load(Ordering::Relaxed))) + { + backing.submit_pins += 1; + } + } + (*this.cast::()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + f.refs.set(f.refs.get() + 1); + f.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + f.refs.set(f.refs.get() - 1); + f.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::(); + let mut vtable = [unexpected_call as usize; size_of::() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut object = Fence { vtable: vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }; + let fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut object).cast()) }; + let (list, lifetime) = (0x7ffe_6a01usize, 17u64); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.list_lifetimes.insert(list, lifetime); + s.recordings.insert(list, 3); + s.last_submit.insert(list, LastSubmit { queue: 0x81, fence: fence.clone(), value: 1, recording: 3 }); + } + + OUTSIDE.store(false, Ordering::Relaxed); + assert_eq!(unsafe { note_resubmits(0x81usize as *mut c_void, &[list as *mut c_void]) }, 1); + assert!(OUTSIDE.load(Ordering::Relaxed), "resubmit polling must not hold STATE"); + OUTSIDE.store(false, Ordering::Relaxed); + assert!(in_flight(list)); + assert!(OUTSIDE.load(Ordering::Relaxed), "in-flight polling must not hold STATE"); + object.value.set(1); + OUTSIDE.store(false, Ordering::Relaxed); + assert!(!in_flight(list)); + assert!(OUTSIDE.load(Ordering::Relaxed), "completed polling must not hold STATE"); + + let alloc = 0x7ffe_6a02usize; + { + let mut g = STATE.lock().unwrap(); + backing_mut(g.as_mut().unwrap(), alloc).marks.insert(0x81, (fence.clone(), 2)); + } + OUTSIDE.store(false, Ordering::Relaxed); + assert!(unsafe { allocator_in_flight(alloc) }); + assert!(OUTSIDE.load(Ordering::Relaxed), "allocator polling must not hold STATE"); + + object.value.set(2); + MUTATE_BACKING.store(alloc, Ordering::Relaxed); + MUTATE.store(true, Ordering::Relaxed); + OUTSIDE.store(false, Ordering::Relaxed); + assert!( + unsafe { allocator_in_flight(alloc) }, + "a state change during the unlocked probe must fail closed", + ); + assert!(OUTSIDE.load(Ordering::Relaxed), "allocator callback must be able to reenter STATE"); + + let backing = { + let mut g = STATE.lock().unwrap(); + g.as_mut().unwrap().backings.remove(&alloc).unwrap() + }; + drop(backing); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.last_submit.remove(&list); + s.recordings.remove(&list); + s.list_lifetimes.remove(&list); + } + drop(fence); + assert_eq!(object.refs.get(), 0); + } + + #[test] + fn submit_marking_calls_out_unlocked_and_revalidates_the_queue_marker() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + refs: Cell, + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + f.refs.set(f.refs.get() + 1); + f.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + f.refs.set(f.refs.get() - 1); + f.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::(); + let mut vtable = [unexpected_call as usize; size_of::() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut first_object = Fence { vtable: vtable.as_ptr(), refs: Cell::new(1) }; + let mut old_object = Fence { vtable: vtable.as_ptr(), refs: Cell::new(1) }; + let mut new_object = Fence { vtable: vtable.as_ptr(), refs: Cell::new(1) }; + let first_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut first_object).cast()) }; + let old_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut old_object).cast()) }; + let new_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut new_object).cast()) }; + + let (first_list, first_queue) = (0x7ffe_6b01usize, 0x7ffe_6b02usize); + let pending = begin_submit(&[first_list as *mut c_void]).unwrap().execution_possible(); + assert!(pending.finish_with_queue_ops( + first_queue, + || { + assert!(STATE.try_lock().is_ok(), "fence creation must run outside STATE"); + Some(first_fence.clone()) + }, + |_, value| { + assert!(STATE.try_lock().is_ok(), "queue Signal must run outside STATE"); + assert_eq!(value, 1); + true + }, + )); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.last_submit[&first_list].value, 1); + assert!(!s.submit_pins.contains_key(&(first_list, s.list_lifetimes[&first_list]))); + } + + let failed_list = 0x7ffe_6b05usize; + let failed = begin_submit(&[failed_list as *mut c_void]).unwrap().execution_possible(); + assert!(!failed.finish_with_queue_ops(first_queue, || unreachable!(), |_, value| { + assert_eq!(value, 2); + false + })); + let retried = begin_submit(&[failed_list as *mut c_void]).unwrap().execution_possible(); + assert!(retried.finish_with_queue_ops(first_queue, || unreachable!(), |_, value| { + assert_eq!(value, 3, "a failed Signal leaves a gap instead of colliding with a retry"); + true + })); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + let lifetime = s.list_lifetimes[&failed_list]; + assert_eq!(s.submit_pins.get(&(failed_list, lifetime)), Some(&1), "the failed submit stays pinned"); + assert_eq!(s.last_submit[&failed_list].value, 3); + } + + let (outer_list, inner_list) = (0x7ffe_6b06usize, 0x7ffe_6b07usize); + let outer = begin_submit(&[outer_list as *mut c_void]).unwrap().execution_possible(); + let inner = begin_submit(&[inner_list as *mut c_void]).unwrap().execution_possible(); + assert!(super::super::queue_submit::with(first_queue, || { + outer.finish_with_queue_ops(first_queue, || unreachable!(), |_, outer_value| { + assert_eq!(outer_value, 4); + assert!(super::super::queue_submit::with(first_queue, || { + inner.finish_with_queue_ops(first_queue, || unreachable!(), |_, inner_value| { + assert_eq!(inner_value, 5, "same-thread re-entry reserves a distinct value"); + true + }) + })); + true + }) + })); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!((s.last_submit[&outer_list].value, s.last_submit[&inner_list].value), (4, 5)); + } + + let (reused_list, reused_queue) = (0x7ffe_6b03usize, 0x7ffe_6b04usize); + let pending = begin_submit(&[reused_list as *mut c_void]).unwrap().execution_possible(); + assert!(!pending.finish_with_queue_ops( + reused_queue, + || Some(old_fence.clone()), + |_, value| { + assert!(STATE.try_lock().is_ok(), "queue invalidation can run while Signal is outside STATE"); + assert_eq!(value, 1); + STATE.lock().unwrap().as_mut().unwrap().fences.insert( + reused_queue, + Arc::new(QueueFence::new(new_fence.clone())), + ); + true + }, + ), "a replacement raw-address generation must not receive the old submit's mark"); + let (markers, submits) = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.last_submit.contains_key(&reused_list)); + let lifetime = s.list_lifetimes[&reused_list]; + assert_eq!(s.submit_pins.get(&(reused_list, lifetime)), Some(&1)); + assert_eq!(s.fences[&reused_queue].fence.as_raw(), new_fence.as_raw()); + s.submit_pins.remove(&(reused_list, lifetime)); + s.list_lifetimes.remove(&reused_list); + let markers = [s.fences.remove(&first_queue), s.fences.remove(&reused_queue)]; + let submits = [ + s.last_submit.remove(&first_list), + s.last_submit.remove(&failed_list), + s.last_submit.remove(&outer_list), + s.last_submit.remove(&inner_list), + ]; + let failed_lifetime = s.list_lifetimes.remove(&failed_list).unwrap(); + s.submit_pins.remove(&(failed_list, failed_lifetime)); + s.list_lifetimes.remove(&first_list); + s.list_lifetimes.remove(&outer_list); + s.list_lifetimes.remove(&inner_list); + (markers, submits) + }; + drop(markers); + drop(submits); + drop(first_fence); + drop(old_fence); + drop(new_fence); + assert_eq!((first_object.refs.get(), old_object.refs.get(), new_object.refs.get()), (0, 0, 0)); + } + + #[test] + fn submission_receipt_keeps_exact_marker_and_failure_is_untracked() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell, + refs: Cell, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + f.refs.set(f.refs.get() + 1); + f.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let f = &*this.cast::(); + f.refs.set(f.refs.get() - 1); + f.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::(); + let mut vtable = [unexpected_call as usize; size_of::() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut old_object = Fence { vtable: vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }; + let mut new_object = Fence { vtable: vtable.as_ptr(), value: Cell::new(1), refs: Cell::new(1) }; + let old_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut old_object).cast()) }; + let new_fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut new_object).cast()) }; + let (list, failed_list, queue) = (0x7ffe_6c01usize, 0x7ffe_6c02usize, 0x7ffe_6c03usize); + + let receipt = begin_submit(&[list as *mut c_void]) + .unwrap() + .execution_possible() + .finish_with_queue_ops_receipted(queue, || Some(old_fence.clone()), |_, value| value == 1) + .expect("the successful Signal has an exact receipt"); + assert!(!receipt.is_complete()); + + let old_marker = STATE.lock().unwrap().as_mut().unwrap().fences.insert( + queue, + Arc::new(QueueFence::new(new_fence.clone())), + ); + drop(old_marker); + assert!(!receipt.is_complete(), "a complete replacement marker cannot satisfy an old receipt"); + old_object.value.set(1); + assert!(receipt.is_complete()); + + let failed = begin_submit(&[failed_list as *mut c_void]).unwrap().execution_possible(); + assert!(failed + .finish_with_queue_ops_receipted(queue, || unreachable!(), |_, value| { + assert_eq!(value, 1); + false + }) + .is_none()); + let (marker, submit) = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let lifetime = s.list_lifetimes[&failed_list]; + assert_eq!(s.submit_pins.get(&(failed_list, lifetime)), Some(&1), "untracked execution remains pinned"); + s.submit_pins.remove(&(failed_list, lifetime)); + s.list_lifetimes.remove(&failed_list); + s.list_lifetimes.remove(&list); + (s.fences.remove(&queue), s.last_submit.remove(&list)) + }; + drop(marker); + drop(submit); + drop(receipt); + drop(old_fence); + drop(new_fence); + assert_eq!((old_object.refs.get(), new_object.refs.get()), (0, 0)); + } + + #[test] + fn released_namespace_keeps_busy_made_backing_until_retirement() { + let (alloc, made) = (0x7ffe_6100usize, 0x7ffe_6200usize); + { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.cur.insert(alloc, made); + s.backings.insert(made, Backing { submit_pins: 1, ..Default::default() }); + } + assert!(unsafe { allocator_in_flight(alloc) }); + unsafe { forget(alloc) }; + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(s.backings[&made].retire_when_free); + assert_eq!(s.backings[&made].submit_pins, 1); + assert!(!s.cur.contains_key(&alloc)); + s.backings.remove(&made); // synthetic raw has no COM reference to sweep + } + } + + #[test] + fn absent_free_made_backing_is_scheduled_for_release_once() { + let (alloc, made) = (0x7ffe_6300usize, 0x7ffe_6400usize); + let mut state = State::default(); + state.cur.insert(alloc, made); + state.aside.insert(alloc, vec![made, alloc, made]); + let (release, owners) = unsafe { forget_in(&mut state, alloc, &HashSet::new()) }; + assert_eq!(release, vec![made]); + assert!(owners.is_empty()); + assert!(!state.cur.contains_key(&alloc) && !state.aside.contains_key(&alloc)); + } + + #[test] + fn transferred_owner_is_released_once_outside_state_after_logical_forget() { + use std::cell::Cell; + + #[repr(C)] + struct FakeAllocator { + vtable: *const usize, + refs: Cell, + releases: Cell, + release_outside_state: Cell, + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let object = &*this.cast::(); + for _ in 0..10_000 { + if STATE.try_lock().is_ok() { + object.release_outside_state.set(true); + break; + } + std::thread::yield_now(); + } + object.releases.set(object.releases.get() + 1); + object.refs.set(object.refs.get() - 1); + object.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + let vtable = [unexpected_call as usize, unexpected_call as usize, release as usize]; + let mut object = FakeAllocator { + vtable: vtable.as_ptr(), refs: Cell::new(1), releases: Cell::new(0), release_outside_state: Cell::new(false), + }; + let raw = std::ptr::from_mut(&mut object).cast::(); + let owner = unsafe { ID3D12CommandAllocator::from_raw(raw) }; + { + let mut g = STATE.lock().unwrap(); + g.get_or_insert_with(State::default).backings.insert( + raw as usize, + Backing { submit_pins: 1, release_owner: Some(owner), ..Default::default() }, + ); + } + unsafe { forget(raw as usize) }; + { + let mut g = STATE.lock().unwrap(); + let backing = g.as_mut().unwrap().backings.get_mut(&(raw as usize)).unwrap(); + assert!(backing.retire_when_free); + backing.submit_pins = 0; + } + sweep_release_owners_with(drop, drop); + assert_eq!((object.refs.get(), object.releases.get()), (0, 1)); + assert!(object.release_outside_state.get()); + assert!(!STATE.lock().unwrap().as_ref().unwrap().backings.contains_key(&(raw as usize))); + } + + #[test] + fn execute_topology_counts_only_split_boundaries() { + assert_eq!(execute_topology(1), (0, 0)); + assert_eq!(execute_topology(4), (1, 3)); + } + + #[test] + fn reserved_submit_orders_prepare_arm_execute_and_finish() { + use std::cell::RefCell; + let calls = RefCell::new(Vec::new()); + let mut failed = false; + let submitted = reserve_and_execute_with( + &mut failed, + || { + calls.borrow_mut().push("begin"); + Some(1) + }, + || calls.borrow_mut().push("prepare"), + |begin| { + calls.borrow_mut().push("arm"); + begin + 1 + }, + || calls.borrow_mut().push("execute"), + |pending| { + calls.borrow_mut().push("finish-failed"); + assert_eq!(pending, 2); + false + }, + ); + assert!(submitted && !failed, "marker failure cannot undo a native execution"); + assert_eq!(*calls.borrow(), ["begin", "prepare", "arm", "execute", "finish-failed"]); + } + + #[test] + fn begin_failure_stops_later_chunks_and_publication() { + use std::cell::Cell; + let mut failed = false; + let executed = Cell::new(0); + let published = Cell::new(0); + for begin_succeeds in [true, false, true] { + let submitted = reserve_and_execute_with( + &mut failed, + || begin_succeeds.then_some(()), + || {}, + |()| (), + || executed.set(executed.get() + 1), + |_| true, + ); + if submitted { + published.set(published.get() + 1); + } + } + assert!(failed); + assert_eq!((executed.get(), published.get()), (1, 1)); + } + + #[test] + fn submit_reservation_keeps_pre_reset_attribution_across_queues() { + use std::cell::Cell; + use std::mem::{offset_of, size_of}; + + #[repr(C)] + struct Fence { + vtable: *const usize, + value: Cell, + refs: Cell, + } + unsafe extern "system" fn completed(this: *mut c_void) -> u64 { + (*this.cast::()).value.get() + } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let fence = &*this.cast::(); + fence.refs.set(fence.refs.get() + 1); + fence.refs.get() + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let fence = &*this.cast::(); + fence.refs.set(fence.refs.get() - 1); + fence.refs.get() + } + extern "system" fn unexpected_call() { std::process::abort(); } + + const SLOT: usize = size_of::(); + let mut vtable = [unexpected_call as usize; size_of::() / SLOT]; + vtable[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = completed as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.AddRef) / SLOT] = add_ref as usize; + vtable[offset_of!(ID3D12Fence_Vtbl, base__.base__.base__.base__.Release) / SLOT] = release as usize; + let mut fence_object = Fence { vtable: vtable.as_ptr(), value: Cell::new(0), refs: Cell::new(1) }; + let fence = unsafe { ID3D12Fence::from_raw(std::ptr::from_mut(&mut fence_object).cast()) }; + + let (alloc, next, list) = (0x7ffe_5100usize, 0x7ffe_5200usize, 0x7ffe_5300usize); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let first = begin_submit(&[list as *mut c_void, list as *mut c_void]).unwrap().execution_possible(); + let cross_queue = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + assert!(in_flight(list)); + let reset = std::thread::spawn(move || { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.aside.insert(alloc, vec![next]); + s.backings.insert(next, Backing::default()); + let (mine, probes) = namespace_probes(s, alloc); + let token = reserve_reset(s, alloc).unwrap(); + let mut retired = Vec::new(); + commit_reset(s, alloc, alloc, next, token, &mine, &probes, true, false, &mut retired) + }) + .join() + .unwrap(); + assert!(reset, "the reserved backing is put aside instead of Reset"); + assert_eq!(reset_list(list, alloc, -1, |backing| { + assert_eq!(backing, next); + 0 + }), 0); + let second = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + + first.finish_with_mark(0x71, &fence, 3); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.backings[&alloc].marks.get(&0x71).unwrap().1, 3); + assert!(!s.backings[&next].marks.contains_key(&0x71)); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&2)); + assert_eq!(s.last_submit[&list].recording, 1); + } + cross_queue.finish_with_mark(0x72, &fence, 4); + second.finish_with_mark(0x73, &fence, 5); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.backings[&alloc].marks.get(&0x71).unwrap().1, 3); + assert_eq!(s.backings[&alloc].marks.get(&0x72).unwrap().1, 4); + assert_eq!(s.backings[&next].marks.get(&0x73).unwrap().1, 5); + assert!(!s.submit_pins.contains_key(&(list, s.list_lifetimes[&list]))); + assert_eq!(s.last_submit[&list].recording, 2); + } + let released = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + forget_list(list); + created_on(list, next, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let reused_address = begin_submit(&[list as *mut c_void]).unwrap(); + released.finish_with_mark(0x74, &fence, 6); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.backings[&next].marks.get(&0x74).unwrap().1, 6); + assert!(!s.last_submit.contains_key(&list), "a late mark cannot resurrect a released list address"); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&1)); + } + drop(reused_address); + forget_list(list); + unsafe { forget(alloc) }; + drop(fence); + assert_eq!(fence_object.refs.get(), 0); + } + + #[test] + fn submit_reservation_drop_and_failure_are_fail_closed() { + let (alloc, list) = (0x7ffe_5400usize, 0x7ffe_5500usize); + created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + + let before_execute = begin_submit(&[list as *mut c_void, list as *mut c_void]).unwrap(); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&1), "duplicates reserve once"); + assert_eq!(s.backings[&alloc].submit_pins, 1); + } + drop(before_execute); + assert!(!in_flight(list), "a reservation abandoned before Execute is released"); + + let armed_for_execute = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + drop(armed_for_execute); + assert!(in_flight(list), "an armed execution stays pinned without a completion mark"); + let failed_finish = begin_submit(&[list as *mut c_void]).unwrap().execution_possible(); + assert!(!unsafe { failed_finish.finish(std::ptr::null_mut()) }); + { + let g = STATE.lock().unwrap(); + let s = g.as_ref().unwrap(); + assert_eq!(s.submit_pins.get(&(list, s.list_lifetimes[&list])), Some(&2)); + assert_eq!(s.backings[&alloc].submit_pins, 2); + } + + // Final list cleanup removes its recording hold but cannot make the backing reusable + // after execution became possible without a completion mark. + forget_list(list); + { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + assert!(!s.backings[&alloc].users.contains(&list)); + assert!(!s.submit_pins.keys().any(|&(p, _)| p == list), "a released address is not pinned against a later object"); + assert!(!unsafe { backing_free_for_test(&s.backings[&alloc]) }); + s.backings.get_mut(&alloc).unwrap().submit_pins = 0; + } + unsafe { forget(alloc) }; + } + + #[test] + fn reset_reservation_runs_unlocked_and_failed_attempt_keeps_the_spare() { let (alloc, spare, list) = (0x1000usize, 0x2000usize, 0x3000usize); let mut s = State::default(); s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); move_list(&mut s, list, alloc); s.aside.insert(alloc, vec![spare]); s.backings.insert(spare, Backing::default()); - let mut calls = Vec::new(); - - for _ in 0..2 { - let hr = unsafe { - title_reset_in(&mut s, alloc as *mut c_void, |raw| { - calls.push(raw as usize); - crate::util::E_FAIL - }) - }; - assert_eq!(hr, Some(crate::util::E_FAIL)); - assert_eq!(s.aside.get(&alloc), Some(&vec![spare]), "the failed candidate is still owned and reusable"); - assert!(!s.cur.contains_key(&alloc), "the current backing did not change"); - assert_eq!(s.of_list.get(&list), Some(&alloc)); - assert!(s.backings[&alloc].users.contains(&list), "the old recording is still held"); - assert_eq!((s.made, s.swaps), (0, 0)); - } - - let hr = unsafe { - title_reset_in(&mut s, alloc as *mut c_void, |raw| { - calls.push(raw as usize); - 0 - }) - }; - assert_eq!(hr, Some(0)); - assert_eq!(calls, vec![spare; 3], "all attempts used the same spare without creating another"); + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + let hr = run_reset(spare as *mut c_void, |raw| { + assert_eq!(raw as usize, spare); + crate::util::E_FAIL + }); + assert_eq!(hr, crate::util::E_FAIL); + cancel_reset(&mut s, alloc, token); + assert_eq!(s.aside.get(&alloc), Some(&vec![spare]), "the failed candidate is still owned and reusable"); + assert!(!s.cur.contains_key(&alloc), "the current backing did not change"); + + let token = reserve_reset(&mut s, alloc).unwrap(); + let mut retired = Vec::new(); + assert!(commit_reset(&mut s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut retired)); assert_eq!(s.cur.get(&alloc), Some(&spare)); assert_eq!(s.aside.get(&alloc), Some(&vec![alloc]), "only the successful reset switches backings"); assert_eq!(s.of_list.get(&list), Some(&alloc), "the earlier recording stays on its original backing"); assert_eq!((s.made, s.swaps), (0, 1)); } + #[test] + fn a_free_spare_from_another_allocator_is_transferred_safely() { + let (requester, donor, busy_owner, other_owner) = (0x1100usize, 0x2200usize, 0x3300usize, 0x4400usize); + let (spare, busy, other, list) = (0x2210usize, 0x3310usize, 0x4410usize, 0x9900usize); + let mut s = State::default(); + for alloc in [requester, donor, busy_owner] { + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + } + s.types.insert(other_owner, D3D12_COMMAND_LIST_TYPE_COMPUTE.0); + s.aside.insert(donor, vec![donor, spare]); + s.aside.insert(busy_owner, vec![busy]); + s.aside.insert(other_owner, vec![other]); + backing_mut(&mut s, spare); + move_list(&mut s, list, busy); + + let candidates = shared_aside_probes(&s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + assert!(candidates.iter().any(|&(owner, raw, _)| owner == donor && raw == spare)); + assert!(!candidates.iter().any(|&(_, raw, _)| raw == donor || raw == other)); + let free = candidates.iter().filter_map(|(_, raw, probe)| { + probe.as_ref().is_none_or(|probe| unsafe { probe.free() }).then_some(*raw) + }).collect(); + assert!(take_shared_aside(&mut s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0, &candidates, &free)); + assert_eq!(s.aside.get(&donor), Some(&vec![donor]), "the donor's own allocator stays in its namespace"); + assert_eq!(s.aside.get(&requester), Some(&vec![spare])); + + // A snapshot that was free cannot transfer a backing after a recording starts using it. + let raced = 0x2220usize; + s.aside.get_mut(&donor).unwrap().push(raced); + backing_mut(&mut s, raced); + let candidates = shared_aside_probes(&s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let free = HashSet::from([raced]); + move_list(&mut s, list + 1, raced); + assert!(!take_shared_aside(&mut s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0, &candidates, &free)); + assert!(s.aside[&donor].contains(&raced)); + + // Nor can a candidate be taken while its donor may already be resetting it unlocked. + let token = reserve_reset(&mut s, donor).unwrap(); + assert!(shared_aside_probes(&s, requester, D3D12_COMMAND_LIST_TYPE_DIRECT.0) + .iter().all(|(owner, _, _)| *owner != donor)); + cancel_reset(&mut s, donor, token); + } + + #[test] + fn retired_recording_keeps_lifetime_and_submit_pin_until_exact_reuse() { + let (list, old, next) = (0x7ffe_7601usize, 0x7ffe_7602usize, 0x7ffe_7603usize); + let mut s = State::default(); + move_list(&mut s, list, old); + s.recordings.insert(list, 4); + s.list_lifetimes.insert(list, 9); + s.submit_pins.insert((list, 9), 1); + s.backings.get_mut(&old).unwrap().submit_pins = 1; + let old_generation = s.backings[&old].generation; + + retire_recording_in(&mut s, list); + assert!(!s.of_list.contains_key(&list)); + assert!(!s.backings[&old].users.contains(&list)); + assert_eq!(s.recordings.get(&list), Some(&4)); + assert_eq!(s.list_lifetimes.get(&list), Some(&9)); + assert_eq!(s.submit_pins.get(&(list, 9)), Some(&1)); + assert_eq!(s.backings[&old].submit_pins, 1, "an in-flight submit still owns the old backing"); + + move_list(&mut s, list, next); + *s.recordings.get_mut(&list).unwrap() += 1; + assert_eq!(s.of_list.get(&list), Some(&next)); + assert!(s.backings[&next].users.contains(&list)); + assert_eq!(s.backings[&old].generation, old_generation, "reuse cannot replace the old backing generation"); + assert_eq!(s.recordings.get(&list), Some(&5)); + } + + #[test] + fn retired_list_stays_in_flight_and_old_token_cannot_unpin_reused_address() { + let (list, old, next) = (0x7ffe_7681usize, 0x7ffe_7682usize, 0x7ffe_7683usize); + created_on(list, old, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let old_submit = begin_submit(&[list as *mut c_void]).unwrap(); + retire_recording(list); + assert!(in_flight(list), "retirement keeps the exact pending submit alive"); + + forget_list(list); + created_on(list, next, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + let reused_submit = begin_submit(&[list as *mut c_void]).unwrap(); + drop(old_submit); + assert!(in_flight(list), "an old lifetime token cannot unpin the reused raw address"); + drop(reused_submit); + assert!(!in_flight(list)); + forget_list(list); + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + s.backings.remove(&old); + s.backings.remove(&next); + s.types.remove(&old); + s.types.remove(&next); + } + + #[test] + fn idle_reset_commit_is_once_only_and_rejects_concurrent_recording() { + let (alloc, spare, failed, list) = (0x7ffe_7701usize, 0x7ffe_7702usize, 0x7ffe_7703usize, 0x7ffe_7704usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare]); + backing_mut(&mut s, spare); + + let (mine, probes) = namespace_probes(&s, alloc); + let successful = vec![probes.iter().find(|probe| probe.raw == spare).unwrap().clone()]; + let token = reserve_reset(&mut s, alloc).unwrap(); + assert!(commit_idle_resets(&mut s, alloc, token, &mine, &probes, &successful, &mut Vec::new())); + assert!(s.backings[&spare].already_reset); + assert!(namespace_probes(&s, alloc).1.iter().find(|probe| probe.raw == spare).unwrap().already_reset, + "the next reclaim pass skips an unchanged backing"); + + s.aside.get_mut(&alloc).unwrap().push(failed); + backing_mut(&mut s, failed); + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + assert!(commit_idle_resets(&mut s, alloc, token, &mine, &probes, &[], &mut Vec::new())); + assert!(!s.backings[&failed].already_reset, "a failed driver Reset remains retryable"); + assert!(!s.resetting.contains_key(&alloc), "a failed idle batch releases its token"); + + let (mine, probes) = namespace_probes(&s, alloc); + let token = reserve_reset(&mut s, alloc).unwrap(); + move_list(&mut s, list, spare); + assert!(!commit_idle_resets(&mut s, alloc, token, &mine, &probes, &successful, &mut Vec::new()), + "a recording created during the unlocked Reset invalidates its exact claim"); + assert!(!s.backings[&spare].already_reset); + assert!(!s.resetting.contains_key(&alloc)); + } + + #[test] + fn reset_commit_rejects_reentrant_backing_mutation() { + let (alloc, spare, list) = (0x7ffe_7a10usize, 0x7ffe_7a20usize, 0x7ffe_7a30usize); + let (mine, probes, token) = { + let mut g = STATE.lock().unwrap(); + let s = g.get_or_insert_with(State::default); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + move_list(s, list, alloc); + s.aside.insert(alloc, vec![spare]); + backing_mut(s, spare); + let (mine, probes) = namespace_probes(s, alloc); + let token = reserve_reset(s, alloc).unwrap(); + (mine, probes, token) + }; + assert_eq!(run_reset(spare as *mut c_void, |_| { + let started = std::time::Instant::now(); + let mut state = loop { + if let Ok(state) = STATE.try_lock() { break state; } + assert!(started.elapsed() < std::time::Duration::from_secs(1), "driver Reset callback could not reenter allocator state"); + std::thread::yield_now(); + }; + state.as_mut().unwrap().backings.get_mut(&spare).unwrap().submit_pins += 1; + 0 + }), 0); + let (committed, token_released) = { + let mut g = STATE.lock().unwrap(); + let s = g.as_mut().unwrap(); + let committed = commit_reset(s, alloc, alloc, spare, token, &mine, &probes, true, false, &mut Vec::new()); + let token_released = !s.resetting.contains_key(&alloc); + s.of_list.remove(&list); + s.backings.remove(&alloc); + s.backings.remove(&spare); + s.aside.remove(&alloc); + s.types.remove(&alloc); + (committed, token_released) + }; + assert!(!committed, "state changed during the unlocked driver call must fail closed"); + assert!(token_released, "a rejected reset commit must release its operation token"); + } + + #[test] + fn final_release_cancels_reset_before_raw_namespace_reuse() { + let (alloc, spare, list) = (0x7ffe_7b10usize, 0x7ffe_7b20usize, 0x7ffe_7b30usize); + let mut s = State::default(); + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + move_list(&mut s, list, alloc); + s.aside.insert(alloc, vec![spare]); + backing_mut(&mut s, spare); + let (mine, probes) = namespace_probes(&s, alloc); + let old_token = reserve_reset(&mut s, alloc).unwrap(); + + let _ = unsafe { forget_in(&mut s, alloc, &HashSet::new()) }; + s.types.insert(alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + s.aside.insert(alloc, vec![spare]); + let new_token = reserve_reset(&mut s, alloc).unwrap(); + assert_ne!(old_token, new_token); + assert!(!commit_reset(&mut s, alloc, alloc, spare, old_token, &mine, &probes, true, false, &mut Vec::new())); + assert_eq!(s.resetting.get(&alloc), Some(&new_token), "a stale completion cannot cancel the replacement's claim"); + } + /// Final-release cleanup drops only the recording's hold: another live list and a pending /// GPU fence each still prevent reuse, then completion makes the backing reusable. #[test] @@ -417,7 +2327,7 @@ mod tests { let s = g.as_ref().unwrap(); !s.of_list.contains_key(&first) && s.of_list.get(&second) == Some(&alloc) && s.backings[&alloc].users == HashSet::from([second]) - && !unsafe { s.backings[&alloc].free() } + && !unsafe { backing_free_for_test(&s.backings[&alloc]) } }; super::super::list_x::on_release(second); super::super::list_x::on_release(first); // duplicate cleanup is harmless @@ -425,10 +2335,10 @@ mod tests { let g = STATE.lock().unwrap(); let s = g.as_ref().unwrap(); !s.of_list.contains_key(&second) && s.backings[&alloc].users.is_empty() - && s.backings[&alloc].marks.len() == 1 && !unsafe { s.backings[&alloc].free() } + && s.backings[&alloc].marks.len() == 1 && !unsafe { backing_free_for_test(&s.backings[&alloc]) } }; fence.value.set(7); - let reusable = unsafe { STATE.lock().unwrap().as_ref().unwrap().backings[&alloc].free() }; + let reusable = unsafe { backing_free_for_test(&STATE.lock().unwrap().as_ref().unwrap().backings[&alloc]) }; // Clean up the synthetic COM pointer before assertions, including on the old code. unsafe { forget(alloc) }; assert!(first_removed, "another live recording must remain while the released list goes"); @@ -528,6 +2438,9 @@ mod tests { let (alloc, list) = (ids.as_mut_ptr() as usize, ids.as_mut_ptr() as usize + 1); let queue = 0x10usize as *mut c_void; created_on(list, alloc, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + // A real first submission captures the list's exact address lifetime before it + // publishes LastSubmit. Seed that identity before constructing the synthetic submit. + drop(begin_submit(&[list as *mut c_void]).unwrap()); { let mut g = STATE.lock().unwrap(); let s = g.as_mut().unwrap(); diff --git a/crates/xcl/src/hle/d3d12x/bind.rs b/crates/xcl/src/hle/d3d12x/bind.rs index 3f31c48b43..4fa002a51f 100644 --- a/crates/xcl/src/hle/d3d12x/bind.rs +++ b/crates/xcl/src/hle/d3d12x/bind.rs @@ -29,11 +29,16 @@ struct State { /// untranslated pipeline – created with it – since SetGraphicsRootSignature binds nothing rs_gfx: usize, pso: usize, + /// Retained decision for `pso`; live classification is added by a later stage. + resolution: Option, allocator: usize, /// unified memory of this recording (io, argument tables) uma: Vec, /// where the next draw's io and argument table go (blocks in `uma`) arena: crate::gpu::uma::Arena, + /// the next dispatch's thread limits (`IO_THREAD_LIMIT`; a `DispatchX` with thread + /// dimensions), taken by its `bind_abi` + limits: [u32; 3], } static STATES: Mutex>> = Mutex::new(None); @@ -69,61 +74,104 @@ fn with(list: *mut c_void, f: impl FnOnce(&mut State) -> R) -> R { f(STATES.lock().unwrap().get_or_insert_with(HashMap::new).entry(list as usize).or_default()) } +fn native_backing(list: *mut c_void, allocator: usize) -> usize { + if allocator == 0 { + 0 + } else { + super::alloc_pool::recording_backing(list as usize) + .unwrap_or_else(|| super::alloc_pool::current(allocator)) + } +} + /// The list was created or reset onto `allocator` with `initial_pso`: the previous -/// recording's memory is the previous allocator's until that one is reset, and pipeline -/// and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. +/// recording's memory is the previous native backing's until that backing is reset, and +/// pipeline and root signature state reset per D3D12 `CreateCommandList` / `Reset` semantics. pub(super) fn reset(list: *mut c_void, allocator: usize, initial_pso: usize) { - let (old, blocks) = with(list, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let backing = native_backing(list, allocator); + let (old, blocks, old_resolution) = with(list, |s| { + let old = std::mem::replace(&mut s.allocator, backing); s.arena = Default::default(); s.pso = initial_pso; + let old_resolution = s.resolution.take(); s.layout = None; s.args.clear(); s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; - (old, std::mem::take(&mut s.uma)) + s.limits = [0; 3]; + (old, std::mem::take(&mut s.uma), old_resolution) }); console_list::hold_until_reset(old, blocks); + drop(old_resolution); } /// `ClearState(pso)`: resets pipeline and root-argument state back to creation defaults /// with `pso` bound, keeping the current recording's allocator and UMA arena intact. pub(super) fn clear_state(list: *mut c_void, pso: usize) { - with(list, |s| { + let old_resolution = with(list, |s| { s.pso = pso; + let old_resolution = s.resolution.take(); s.layout = None; s.args.clear(); s.layout_gfx = None; s.args_gfx.clear(); s.rs_gfx = 0; + old_resolution }); + drop(old_resolution); } -/// Carry bound pipeline and root-signature / root-argument state from `from` to `to` across a -/// deferred mid-list split (`to` records into `allocator` with its own fresh UMA arena while -/// `from` retains its previously allocated blocks until `allocator` resets). -pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { - let (layout, args, layout_gfx, args_gfx, rs_gfx, pso) = with(from, |s| { - (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso) +/// Allocation-bearing root state captured before a mid-list split commits. Preparation also +/// transfers the reserved destination's old UMA ownership, so installation cannot allocate. +pub(super) struct PreparedSplit { + to: usize, + allocator: usize, + layout: Option>, + args: Vec, + layout_gfx: Option>, + args_gfx: Vec, + rs_gfx: usize, + pso: usize, + resolution: Option, +} + +pub(super) fn prepare_split(from: *mut c_void, to: *mut c_void, allocator: usize) -> PreparedSplit { + let backing = native_backing(to, allocator); + let (layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution) = with(from, |s| { + (s.layout.clone(), s.args.clone(), s.layout_gfx.clone(), s.args_gfx.clone(), s.rs_gfx, s.pso, + s.resolution.clone()) }); let (old, blocks) = with(to, |s| { - let old = std::mem::replace(&mut s.allocator, allocator); + let old = std::mem::replace(&mut s.allocator, 0); s.arena = Default::default(); + (old, std::mem::take(&mut s.uma)) + }); + console_list::hold_until_reset(old, blocks); + PreparedSplit { to: to as usize, allocator: backing, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution } +} + +/// Install a preflighted split state without cloning or growing the state map. +pub(super) fn install_prepared_split(prepared: PreparedSplit) { + let PreparedSplit { to, allocator, layout, args, layout_gfx, args_gfx, rs_gfx, pso, resolution } = prepared; + let old_resolution = { + let mut states = STATES.lock().unwrap(); + let s = states.as_mut().and_then(|m| m.get_mut(&to)).expect("prepared split destination state"); + debug_assert_eq!(s.allocator, 0); + debug_assert!(s.uma.is_empty()); + s.allocator = allocator; s.layout = layout; s.args = args; s.layout_gfx = layout_gfx; s.args_gfx = args_gfx; s.rs_gfx = rs_gfx; s.pso = pso; - (old, std::mem::take(&mut s.uma)) - }); - console_list::hold_until_reset(old, blocks); + std::mem::replace(&mut s.resolution, resolution) + }; + drop(old_resolution); } -/// A submit is about to wait for the pipeline `this` has bound. -pub(super) fn want_bound(this: *mut c_void) { - super::pso_async::want(with(this, |s| s.pso)); +pub(super) fn inherit_for_split(from: *mut c_void, to: *mut c_void, allocator: usize) { + install_prepared_split(prepare_split(from, to, allocator)); } /// A put-off dispatch that could not be recorded. @@ -139,7 +187,10 @@ pub(super) fn pass_arena(from: *mut c_void, to: *mut c_void) { /// The list is gone. pub(super) fn forget(list: *mut c_void) { - if let Some(s) = STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) { + let removed = { + STATES.lock().unwrap().as_mut().and_then(|m| m.remove(&(list as usize))) + }; + if let Some(s) = removed { console_list::hold_until_reset(s.allocator, s.uma); } } @@ -189,6 +240,7 @@ fn put(list: *mut c_void, i: u32, offset: u32, bytes: &[u8]) { /// #34 SetGraphicsRootSignature (PC #30) pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args_gfx = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -199,16 +251,19 @@ pub(super) unsafe extern "system" fn set_graphics_root_signature(this: *mut c_vo /// #36 SetGraphicsRootDescriptorTable (PC #32) pub(super) unsafe extern "system" fn set_graphics_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put_in(this, true, i, 0, &(handle as u32).to_le_bytes()); } /// #38 SetGraphicsRoot32BitConstant (PC #34) pub(super) unsafe extern "system" fn set_graphics_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put_in(this, true, i, offset, &value.to_le_bytes()); } /// #40 SetGraphicsRoot32BitConstants (PC #36) pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); if !data.is_null() { let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put_in(this, true, i, offset, &bytes); @@ -218,6 +273,7 @@ pub(super) unsafe extern "system" fn set_graphics_root_constants(this: *mut c_vo /// #42 / #44 / #46 SetGraphicsRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #38 / /// #40 / #42) pub(super) unsafe extern "system" fn set_graphics_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); note_address(va); put_in(this, true, i, 0, &va.to_le_bytes()); } @@ -263,6 +319,18 @@ fn signature_dispatches(sig: usize) -> bool { DISPATCH_SIGNATURES.lock().unwrap().as_ref().is_some_and(|s| s.contains(&sig)) } +/// Command signatures made of one Dispatch argument, keyed to their stride. +static DISPATCH_ONLY: Mutex>> = Mutex::new(None); + +pub(super) fn note_dispatch_only_signature(sig: usize, stride: Option) { + let mut signatures = DISPATCH_ONLY.lock().unwrap(); + let signatures = signatures.get_or_insert_with(Default::default); + match stride { + Some(stride) => { signatures.insert(sig, stride); } + None => { signatures.remove(&sig); } + } +} + /// #59 ExecuteIndirect(signature, max count, arguments, offset, count buffer, offset): with a /// translated pipeline, on XCL's ABI with the kept root arguments (signatures that change root /// arguments themselves cannot be – skipped, logged) @@ -270,12 +338,16 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us type F = unsafe extern "system" fn(*mut c_void, usize, u32, usize, u64, usize, u64); let pc: F = std::mem::transmute(super::real::orig_fn(this, 59)); let raw_pso = with(this, |s| s.pso); - let unbuilt_compute = signature_dispatches(sig) && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); - if unbuilt_compute && super::list_x::defer(this, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { - return super::pso_async::need_by_submit(raw_pso); + let dispatches = signature_dispatches(sig); + let _detail = crate::stall::detail_span(if dispatches { crate::stall::StallKind::DetailDispatch } else { crate::stall::StallKind::DetailDraw }); + let unbuilt_compute = dispatches && super::pso_async::is_pending(raw_pso) && super::real::is_console_compute(raw_pso); + if unbuilt_compute && super::list_x::defer(this, raw_pso, super::list_x::Deferred::Indirect(sig, max, args, args_off, count_buf, count_off)) { + return; } - let pso = super::pso_async::resolve_wait(raw_pso); + let ((pso, bound_unbuilt), generation) = super::pso_async::resolve_wait_bound_and_pin_if_enabled(raw_pso); + super::list_x::record_native_generation(this as usize, generation); let (gfx, compute) = (super::real::is_translated_graphics(pso), super::real::is_translated_compute(pso)); + let args_off_title = args_off; let (args_off, count_off) = (args_off + super::real::buffer_delta(args), count_off + super::real::buffer_delta(count_buf)); if !gfx && !compute { // A pipeline still being built (or whose build failed): its stand-in draws nothing, and @@ -283,7 +355,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // call with that pair is invalid (debug layer 953, "the currently set Root Signature // doesn't match the currently set Pipeline State Object"; a retail title's world then // hung the GPU, 0x887a0006). Skipped, like a draw or dispatch of such a pipeline. - if super::pso_async::is_pending(raw_pso) { + if bound_unbuilt { count(DRAWS_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -312,7 +384,7 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us // A native PC compute pipeline is not one of these and still goes to the PC call. // (`CONSOLE_COMPUTE` holds the title's object, which for a shared stand-in differs from // the driver pipeline `resolve_wait` returned.) - if signature_dispatches(sig) && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { + if dispatches && (super::real::is_console_compute(raw_pso) || super::real::is_console_compute(pso)) { count(DISPATCHES_SKIPPED); static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -335,14 +407,51 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us return; } let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; + if compute && max == 1 && count_buf == 0 && DISPATCH_ONLY.lock().unwrap().as_ref().is_some_and(|m| m.contains_key(&sig)) { + let chained = indirect_address(args, args_off_title, args_off).map_or(Ok(false), |address| { + super::real::dispatch_chain::execute_indirect(list, pso, with(this, |s| s.allocator), address, + |root| bind_abi_with_root(this, list, pso, false, root)) + }); + match chained { + Ok(true) => { + count(DISPATCHES); + return; + } + Ok(false) => {} + Err(e) => { + count(DISPATCHES_SKIPPED); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: split ExecuteIndirect skipped: {e}"); + } + return; + } + } + } match bind_abi(this, list, pso, gfx) { Ok(()) => { if compute { + if super::real::pso_dispatch_remap(pso).is_some() { + match super::real::remap_fallback::whole(pso) { + Ok(fallback) => list.SetPipelineState(&fallback), + Err(e) => { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect remap fallback skipped: {e}"); + } + count(DISPATCHES_SKIPPED); + return; + } + } + } match super::real::dispatch_chain::whole(pso) { Ok(Some(whole)) => list.SetPipelineState(&whole), Ok(None) => {} Err(e) => { - crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: ExecuteIndirect whole compute PSO: {e}"); + } count(DISPATCHES_SKIPPED); return; } @@ -361,6 +470,17 @@ pub(super) unsafe extern "system" fn execute_indirect(this: *mut c_void, sig: us } } +unsafe fn indirect_address(resource: usize, title_offset: u64, pc_offset: u64) -> Option { + match super::real::console_buffer(resource) { + Some((base, size)) if title_offset.checked_add(12).is_some_and(|end| end <= size as u64) => { + super::real::uma_va_of(base + title_offset as usize) + } + Some(_) => None, + None => Some(ID3D12Resource::from_raw_borrowed(&(resource as *mut c_void))?.GetGPUVirtualAddress()) + .filter(|&address| address != 0).and_then(|address| address.checked_add(pc_offset)), + } +} + /// XCL's own buffer for `fresh_indirect_arguments` (device, buffer): COMMON between its uses static ARGUMENT_ORDER: Mutex> = Mutex::new(None); @@ -491,6 +611,7 @@ fn cpu_rect_expansion(pso: usize) -> bool { /// #12 DrawInstanced pub(super) unsafe extern "system" fn draw_instanced(this: *mut c_void, vertices: u32, instances: u32, first_vertex: u32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); DRAW_ARGS.with(|d| d.set((false, vertices, instances, first_vertex, 0))); if let Some(list) = graphics_bound(this) { if draw_rects(this, &list, vertices, instances, first_vertex, first_instance) { @@ -508,6 +629,7 @@ thread_local! { /// #13 DrawIndexedInstanced pub(super) unsafe extern "system" fn draw_indexed_instanced(this: *mut c_void, indices: u32, instances: u32, first_index: u32, base_vertex: i32, first_instance: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDraw); if let Some(list) = prepare_indexed_draw(this, indices, instances, first_index, base_vertex) { super::list_x::sync_title_buffers(this, Some((first_index, indices, base_vertex)), 0, 0, if first_instance != 0 { instances.max(2) } else { instances }); emit_prepared_indexed_draw(&list, indices, instances, first_index, base_vertex, first_instance); @@ -545,7 +667,7 @@ unsafe fn graphics_bound(this: *mut c_void) -> Option let list = ID3D12GraphicsCommandList::from_raw_borrowed(&this)?.clone(); let pso = with(this, |s| s.pso); // a pipeline still being built in the background is waited for (its stand-in draws nothing) - let real = super::pso_async::resolve_wait(pso); + let real = super::list_x::resolve_and_record_pipeline_wait(list.as_raw() as usize, pso); if !super::real::is_translated_graphics(real) { // A finished two-pass MS/GS pipeline is a PC mesh shader pipeline (MS+PS) registered in // TWO_PASS rather than TRANSLATED_GRAPHICS. Binding the title's graphics RS and issuing @@ -830,6 +952,7 @@ unsafe fn root_args_summary(this: *mut c_void, buffer_words: usize) -> String { /// #33 SetComputeRootSignature (PC #29) pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_void, rs: *mut c_void) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); let layout = console_list::layout_of(rs as usize); with(this, |s| { s.args = vec![0u8; layout.as_ref().map_or(0, |l| l.size as usize)]; @@ -839,16 +962,19 @@ pub(super) unsafe extern "system" fn set_compute_root_signature(this: *mut c_voi /// #35 SetComputeRootDescriptorTable (PC #31): the table's console address, 32 bits pub(super) unsafe extern "system" fn set_compute_root_table(this: *mut c_void, i: u32, handle: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put(this, i, 0, &(handle as u32).to_le_bytes()); } /// #37 SetComputeRoot32BitConstant (PC #33) pub(super) unsafe extern "system" fn set_compute_root_constant(this: *mut c_void, i: u32, value: u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); put(this, i, offset, &value.to_le_bytes()); } /// #39 SetComputeRoot32BitConstants (PC #35) pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_void, i: u32, n: u32, data: *const u32, offset: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); if !data.is_null() { let bytes: Vec = std::slice::from_raw_parts(data, n as usize).iter().flat_map(|w| w.to_le_bytes()).collect(); put(this, i, offset, &bytes); @@ -858,23 +984,61 @@ pub(super) unsafe extern "system" fn set_compute_root_constants(this: *mut c_voi /// #41 / #43 / #45 SetComputeRoot{ConstantBuffer,ShaderResource,UnorderedAccess}View (PC #37 / /// #39 / #41): the 64-bit GPU address pub(super) unsafe extern "system" fn set_compute_root_descriptor(this: *mut c_void, i: u32, va: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); note_address(va); put(this, i, 0, &va.to_le_bytes()); } /// #25 SetPipelineState: noted, then bound as on the PC pub(super) unsafe extern "system" fn set_pipeline_state(this: *mut c_void, pso: *mut c_void) { - with(this, |s| s.pso = pso as usize); + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); + set_tracked_pipeline_state(this, pso as usize); super::real::bind_pipeline(this, pso); } +fn set_tracked_pipeline_state(this: *mut c_void, pso: usize) { + let old_resolution = with(this, |s| { + s.pso = pso; + s.resolution.take() + }); + drop(old_resolution); +} + /// #14 Dispatch: with a translated pipeline, on XCL's ABI with the kept root arguments pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailDispatch); + dispatch_flags(this, x, y, z, 0); +} + +/// `DispatchX` flag: x, y, z are thread counts, not group counts; the console launches whole +/// groups and leaves the lanes past the count out of EXEC (0x8000, wave32, needs nothing here) +const DISPATCH_THREAD_DIMENSIONS: u32 = 0x20; +const MAX_DISPATCH_GROUPS: u32 = 65_535; + +fn valid_dispatch_grid(groups: [u32; 3]) -> bool { + groups.into_iter().all(|n| n <= MAX_DISPATCH_GROUPS) +} + +/// What a dispatch of `dims` with `flags` launches on pipeline `pso`: its groups and the thread +/// limits for `IO_THREAD_LIMIT` (0: that axis ends on a whole group). None: it cannot be run +/// as the console would (thread dimensions with a group shape not known). +fn dispatch_groups(pso: usize, dims: [u32; 3], flags: u32) -> Option<([u32; 3], [u32; 3])> { + if flags & DISPATCH_THREAD_DIMENSIONS == 0 { + return Some((dims, [0; 3])); + } + let threads = super::real::pso_threads(pso)?.map(|t| t.max(1)); + let groups = std::array::from_fn(|k| dims[k].div_ceil(threads[k])); + let limits = std::array::from_fn(|k| if dims[k] % threads[k] != 0 { dims[k] } else { 0 }); + Some((groups, limits)) +} + +/// `Dispatch` / `DispatchX(x, y, z, flags)`. +pub(super) unsafe fn dispatch_flags(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { let pso = with(this, |s| s.pso); - if super::pso_async::is_pending(pso) && super::list_x::defer(this, super::list_x::Deferred::Dispatch(x, y, z)) { - return super::pso_async::need_by_submit(pso); + if super::pso_async::is_pending(pso) && super::list_x::defer(this, pso, super::list_x::Deferred::Dispatch(x, y, z, flags)) { + return; } - let pso = super::pso_async::resolve_wait(pso); + let pso = super::list_x::resolve_and_record_pipeline_wait(this as usize, pso); let Some(list) = ID3D12GraphicsCommandList::from_raw_borrowed(&this) else { return }; if !super::real::is_translated_compute(pso) { // a console pipeline without a translation (including a background build that @@ -886,7 +1050,34 @@ pub(super) unsafe extern "system" fn dispatch(this: *mut c_void, x: u32, y: u32, count(DISPATCHES_SKIPPED); return; } - match translated_dispatch(this, list, pso, x, y, z) { + let Some((groups, limits)) = dispatch_groups(pso, [x, y, z], flags) else { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: DispatchX of {x}x{y}x{z} threads (flags {flags:#x}) with a pipeline whose group shape is not known ({pso:#x}) skipped"); + } + count(DISPATCHES_SKIPPED); + return; + }; + if !valid_dispatch_grid(groups) { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { + crate::xlog_warn!("D3D12.X: Dispatch of {}x{}x{} groups exceeds the PC limit of {MAX_DISPATCH_GROUPS} on one axis and was skipped", groups[0], groups[1], groups[2]); + } + count(DISPATCHES_SKIPPED); + return; + } + if flags != 0 { + // each kind of flags once: what titles pass, and what it launches + static SEEN: Mutex> = Mutex::new(Vec::new()); + let first = { let mut g = SEEN.lock().unwrap(); !g.contains(&flags) && { g.push(flags); true } }; + if first { + crate::xlog_info!("D3D12.X: DispatchX with flags {flags:#x}: {x}x{y}x{z} launched as {}x{}x{} groups (thread limits {limits:?})", groups[0], groups[1], groups[2]); + } + } + with(this, |s| s.limits = limits); + let done = translated_dispatch(this, list, pso, groups[0], groups[1], groups[2]); + with(this, |s| s.limits = [0; 3]); + match done { Ok(()) => count(DISPATCHES), Err(e) => { count(DISPATCHES_SKIPPED); @@ -1015,7 +1206,13 @@ unsafe fn translated_dispatch(this: *mut c_void, list: &ID3D12GraphicsCommandLis /// arguments the console's way – compute or graphics) and the argument table in unified /// memory, u1 res, u2… the memory windows; then the pipeline. unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool) -> Result<(), String> { - super::list_x::ensure_view_heap(this); + bind_abi_with_root(this, list, pso, gfx, 0) +} + +unsafe fn bind_abi_with_root( + this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usize, gfx: bool, root: usize, +) -> Result<(), String> { + let shared_view_bound = super::list_x::ensure_view_heap(this); let u = crate::gpu::uma::get().ok_or("no unified memory")?; let windows = super::real::uma_window_vas(); let first = *windows.first().ok_or("unified memory is not open on the GPU")?; @@ -1027,7 +1224,7 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi Ok(p as usize) }; // a pipeline still being built in the background is waited for - let real = super::pso_async::resolve_wait(pso); + let real = super::list_x::resolve_and_record_pipeline_wait(list.as_raw() as usize, pso); // a compute shader takes no more arguments from registers than it has (`inline_for`) let user_sgprs = if gfx { None } else { super::real::pso_user_sgprs(real) }; let inline = layout.as_ref().map_or(0, |l| if gfx { l.inline_gfx } else { console_list::inline_for(l, user_sgprs) } as usize).min(args.len()); @@ -1039,10 +1236,18 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi }; io.resize(crate::gpu::recomp::KERNEL_SGPRS, 0); io[crate::gpu::recomp::IO_UMA_BASE_HI] = (u.base() >> 32) as u32; + if !gfx { + for (k, l) in take_dispatch_limits(this).into_iter().enumerate() { + io[crate::gpu::recomp::IO_THREAD_LIMIT[k]] = l; + } + } let io_at = copy(&io.iter().flat_map(|w| w.to_le_bytes()).collect::>())?; let res_at = copy(&[0u8; 256])?; let va = |p: usize| super::real::uma_va_of(p).unwrap_or(first); - let rs = super::real::pso_root_signature(real).or_else(|| super::real::abi_rs_cached().map(|p| p as usize)).ok_or("no XCL ABI root signature")?; + let rs = (root != 0).then_some(root) + .or_else(|| super::real::pso_root_signature(real)) + .or_else(|| super::real::abi_rs_cached().map(|p| p as usize)) + .ok_or("no XCL ABI root signature")?; let rs = rs as *mut c_void; let rs = ID3D12RootSignature::from_raw_borrowed(&rs).ok_or("root signature")?; let views = [va(io_at), va(res_at)].into_iter().chain((0..4).map(|k| windows.get(k).copied().filter(|&v| v != 0).unwrap_or(first))); @@ -1057,12 +1262,21 @@ unsafe fn bind_abi(this: *mut c_void, list: &ID3D12GraphicsCommandList, pso: usi list.SetComputeRootUnorderedAccessView(k as u32, v); } } - let real = real as *mut c_void; - let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; - list.SetPipelineState(pc); + if root == 0 { + let real = real as *mut c_void; + let pc = ID3D12PipelineState::from_raw_borrowed(&real).ok_or("pipeline")?; + list.SetPipelineState(pc); + } + if shared_view_bound && super::vram::srv_tracking_enabled() { + super::list_x::note_shared_view_heap_use(this); + } Ok(()) } +fn take_dispatch_limits(list: *mut c_void) -> [u32; 3] { + with(list, |s| std::mem::take(&mut s.limits)) +} + #[cfg(test)] pub(super) fn last_draw_args() -> (bool, u32, u32, u32, i32) { DRAW_ARGS.with(|d| d.get()) @@ -1087,7 +1301,7 @@ pub(super) fn tracked_pso(list: *mut c_void) -> usize { mod tests { use super::super::{device_x, list_x, pso_async, real, title_list}; use super::*; - use std::sync::atomic::AtomicUsize; + use std::sync::atomic::{AtomicBool, AtomicUsize}; /// A pipeline with the rect list GS draws its rect lists whole: draw_rects leaves them alone. #[test] @@ -1356,6 +1570,118 @@ void main(uint t : SV_GroupIndex) { forget(list); } + fn probed_resolution(list: usize, original: usize, dropped: Arc) + -> pso_async::PipelineResolution { + pso_async::pipeline_resolution_for_test(original, move || { + assert!(STATES.try_lock().is_ok(), "pipeline resolution dropped under bind::STATES"); + dropped.store(true, Ordering::Release); + let _ = list; + }) + } + + #[test] + fn pipeline_resolution_replacements_drop_outside_state_lock() { + let cases: [fn(*mut c_void); 4] = [ + |list| clear_state(list, 0x7100_5001), + |list| reset(list, 0, 0x7100_5002), + |list| set_tracked_pipeline_state(list, 0x7100_5003), + forget, + ]; + for (n, replace) in cases.into_iter().enumerate() { + let list = (0x7100_5100usize + n) as *mut c_void; + let dropped = Arc::new(AtomicBool::new(false)); + let resolution = probed_resolution(list as usize, 0x7100_5200 + n, dropped.clone()); + with(list, |s| s.resolution = Some(resolution)); + replace(list); + assert!(dropped.load(Ordering::Acquire), "case {n} retained the replaced resolution"); + if n + 1 != cases.len() { + forget(list); + } + } + } + + #[test] + fn split_retains_the_exact_resolution_across_address_reuse() { + let from = 0x7100_6001usize as *mut c_void; + let to = 0x7100_6002usize as *mut c_void; + let original = 0x7100_6100usize; + let old = pso_async::pipeline_resolution_for_test(original, || {}); + let old_identity = old.identity_for_test(); + with(from, |s| { + s.pso = original; + s.resolution = Some(old); + }); + reset(to, 0, 0); + + let prepared = prepare_split(from, to, 0); + let replacement = pso_async::pipeline_resolution_for_test(original, || {}); + let replacement_identity = replacement.identity_for_test(); + assert_ne!(old_identity.1, replacement_identity.1); + with(from, |s| s.resolution = Some(replacement)); + install_prepared_split(prepared); + + assert_eq!(with(to, |s| s.resolution.as_ref().unwrap().identity_for_test()), old_identity, + "split state was redirected to the Pending now stored at the reused title address"); + assert_eq!(with(from, |s| s.resolution.as_ref().unwrap().identity_for_test()), replacement_identity); + forget(from); + forget(to); + } + + #[test] + fn split_preflight_transfers_destination_uma_before_install() { + let from = 0x7101_0001usize as *mut c_void; + let to = 0x7101_0002usize as *mut c_void; + let (old_alloc, new_alloc) = (0x7101_0100usize, 0x7101_0200usize); + let _ = console_list::take_pending_for_test(old_alloc); + seed_reset_state_for_test(from, 0x7101_0300, 0x7101_1000, vec![0x7101_4000]); + seed_reset_state_for_test(to, old_alloc, 0x7101_2000, vec![0x7101_5000, 0x7101_6000]); + + let prepared = prepare_split(from, to, new_alloc); + assert_eq!(reset_state_for_test(from), (0x7101_0300, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], vec![0x7101_4000])); + assert_eq!(reset_state_for_test(to), (0, 0x7101_2000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + + install_prepared_split(prepared); + assert_eq!(reset_state_for_test(to), (new_alloc, 0x7101_1000, vec![1, 2, 3, 4], vec![5, 6, 7, 8], Vec::new())); + assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7101_5000, 0x7101_6000]); + remove_state_for_test(from); + remove_state_for_test(to); + } + + #[test] + fn reset_keys_uma_to_the_lists_native_allocator_backing() { + let list = 0x7101_7001usize as *mut c_void; + let (logical, native, old_native, block) = (0x7101_7100usize, 0x7101_7200usize, 0x7101_7300usize, 0x7101_7400usize); + let _ = console_list::take_pending_for_test(old_native); + super::super::alloc_pool::created_on(list as usize, native, D3D12_COMMAND_LIST_TYPE_DIRECT.0); + seed_reset_state_for_test(list, old_native, 0, vec![block]); + + reset(list, logical, 0); + + assert_eq!(reset_state_for_test(list).0, native, + "UMA ownership follows the recording's native backing, not the title allocator"); + assert_eq!(console_list::take_pending_for_test(old_native), vec![block]); + remove_state_for_test(list); + super::super::alloc_pool::forget_list(list as usize); + unsafe { super::super::alloc_pool::forget(native); } + } + + #[test] + fn abandoned_split_preflight_keeps_old_uma_under_its_allocator() { + let from = 0x7102_0001usize as *mut c_void; + let to = 0x7102_0002usize as *mut c_void; + let old_alloc = 0x7102_0100usize; + let _ = console_list::take_pending_for_test(old_alloc); + seed_reset_state_for_test(from, 0x7102_0200, 0x7102_1000, Vec::new()); + seed_reset_state_for_test(to, old_alloc, 0x7102_2000, vec![0x7102_5000]); + + drop(prepare_split(from, to, 0x7102_0300)); + forget(to); + + assert_eq!(console_list::take_pending_for_test(old_alloc), vec![0x7102_5000]); + assert_eq!(reset_state_for_test(from).0, 0x7102_0200, "the active producer must remain untouched"); + remove_state_for_test(from); + } + #[repr(C)] struct FakeAdoptedList { vt: *const usize, @@ -1403,6 +1729,60 @@ void main(uint t : SV_GroupIndex) { (*(this as *const FakeAdoptedList)).execute_indirect_calls.fetch_add(1, Ordering::Relaxed); } + /// `DispatchX` with thread dimensions (flag 0x20, as the BVH builder's rehydration passes + /// use it): the console launches whole groups of the pipeline's `numthreads` and leaves + /// the lanes past the count out; without the flag the counts are groups. With the flag + /// and a group shape not known, nothing is launched (the counts as groups was the bug). + #[test] + fn dispatch_x_with_thread_dimensions_launches_whole_groups() { + let pso = 0x7300_0001usize; + real::register_threads_for_test(pso, [64, 1, 1]); + // 640 threads in groups of 64: 10 groups, the last one whole + assert_eq!(dispatch_groups(pso, [640, 1, 1], 0x20), Some(([10, 1, 1], [0, 0, 0]))); + // 100 threads: 2 groups, and the lanes past 100 to leave out + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x20), Some(([2, 1, 1], [100, 0, 0]))); + // the wave32 bit (0x8000) changes nothing here + assert_eq!(dispatch_groups(pso, [100, 1, 1], 0x8020), Some(([2, 1, 1], [100, 0, 0]))); + // a 2-D group shape + let pso2 = 0x7300_0002usize; + real::register_threads_for_test(pso2, [8, 8, 1]); + assert_eq!(dispatch_groups(pso2, [20, 16, 3], 0x20), Some(([3, 2, 3], [20, 0, 0]))); + // group counts (Dispatch, DispatchX without the flag) are launched as they are + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0), Some(([7, 2, 1], [0, 0, 0]))); + assert_eq!(dispatch_groups(pso, [7, 2, 1], 0x8000), Some(([7, 2, 1], [0, 0, 0]))); + // no threads: no groups + assert_eq!(dispatch_groups(pso, [0, 1, 1], 0x20), Some(([0, 1, 1], [0, 0, 0]))); + // thread dimensions on a pipeline whose group shape is not known: not launched + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0x20), None); + assert_eq!(dispatch_groups(0x7300_00FF, [100, 1, 1], 0), Some(([100, 1, 1], [0, 0, 0]))); + + let last = MAX_DISPATCH_GROUPS * 64; + let at_limit = dispatch_groups(pso, [last, 1, 1], 0x20).unwrap().0; + let past_limit = dispatch_groups(pso, [last + 1, 1, 1], 0x20).unwrap().0; + assert!(valid_dispatch_grid(at_limit)); + assert!(!valid_dispatch_grid(past_limit)); + for k in 0..3 { + let mut grid = [1; 3]; + grid[k] = MAX_DISPATCH_GROUPS; + assert!(valid_dispatch_grid(grid), "axis {k} at the D3D12 limit"); + grid[k] += 1; + assert!(!valid_dispatch_grid(grid), "axis {k} past the D3D12 limit"); + } + } + + #[test] + fn deferred_dispatch_limits_are_consumed_once_and_reset_with_the_list() { + let list = 0x7301_0001usize as *mut c_void; + with(list, |s| s.limits = [100, 17, 0]); + assert_eq!(take_dispatch_limits(list), [100, 17, 0]); + assert_eq!(take_dispatch_limits(list), [0; 3], "a later ordinary dispatch must not inherit deferred limits"); + + with(list, |s| s.limits = [9, 8, 7]); + reset(list, 0x7301_1000, 0); + assert_eq!(take_dispatch_limits(list), [0; 3], "Reset drops an unconsumed deferred dispatch state"); + forget(list); + } + #[test] fn async_compute_pso_success_and_failure_in_dispatch_and_execute_indirect() { let mut orig_vt = [0usize; 64]; diff --git a/crates/xcl/src/hle/d3d12x/build_queue.rs b/crates/xcl/src/hle/d3d12x/build_queue.rs new file mode 100644 index 0000000000..eb83a51efb --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/build_queue.rs @@ -0,0 +1,643 @@ +//! Priority queue shared by pipeline-preparation workers. +//! +//! PSO preparation uses worker bands so background preloads cannot occupy the workers reserved +//! for builds that the title will need soon. + +#![allow(dead_code)] // Some operations are seams for the following preparation changes. + +use std::cmp::Reverse; +use std::collections::{BinaryHeap, HashMap, VecDeque}; +use std::panic::{catch_unwind, AssertUnwindSafe}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Condvar, Mutex, Weak}; + +pub(super) type Work = Box; + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +#[repr(u8)] +pub(super) enum Priority { + Speculative, + Preload, + BoundSoon, + Foreground, +} + +impl Priority { + const COUNT: usize = 4; + + fn index(self) -> usize { + self as usize + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub(super) struct JobId(u64); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum JobStatus { + Queued, + Running, + Complete, + Cancelled, + Panicked, +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub(super) struct RankedPreloadSnapshot { + pub(super) submissions: u64, + pub(super) started: u64, + pub(super) promoted: u64, +} + +struct RankedPreloadCounters { + submissions: AtomicU64, + started: AtomicU64, + promoted: AtomicU64, +} + +impl RankedPreloadCounters { + const fn new() -> Self { + Self { + submissions: AtomicU64::new(0), + started: AtomicU64::new(0), + promoted: AtomicU64::new(0), + } + } + + fn snapshot(&self) -> RankedPreloadSnapshot { + RankedPreloadSnapshot { + submissions: self.submissions.load(Ordering::Relaxed), + started: self.started.load(Ordering::Relaxed), + promoted: self.promoted.load(Ordering::Relaxed), + } + } +} + +impl JobStatus { + fn terminal(self) -> bool { + matches!(self, Self::Complete | Self::Cancelled | Self::Panicked) + } +} + +struct Completion { + status: Mutex, + changed: Condvar, +} + +impl Completion { + fn new() -> Self { + Self { status: Mutex::new(JobStatus::Queued), changed: Condvar::new() } + } + + fn set(&self, status: JobStatus) { + *self.status.lock().unwrap_or_else(|e| e.into_inner()) = status; + self.changed.notify_all(); + } + + fn get(&self) -> JobStatus { + *self.status.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait(&self) -> JobStatus { + let mut status = self.status.lock().unwrap_or_else(|e| e.into_inner()); + while !status.terminal() { + status = self.changed.wait(status).unwrap_or_else(|e| e.into_inner()); + } + *status + } +} + +#[derive(Clone)] +pub(super) struct JobHandle { + id: JobId, + queue: Weak, + completion: Arc, +} + +impl JobHandle { + pub(super) fn id(&self) -> JobId { + self.id + } + + pub(super) fn status(&self) -> JobStatus { + self.completion.get() + } + + pub(super) fn wait(&self) -> JobStatus { + self.completion.wait() + } + + /// Raise this queued job to `priority`. Running and completed jobs cannot be promoted. + pub(super) fn promote(&self, priority: Priority) -> bool { + self.queue.upgrade().is_some_and(|q| q.promote(self.id, priority)) + } + + /// Cancel this job only if no worker has started it. + pub(super) fn cancel(&self) -> bool { + self.queue.upgrade().is_some_and(|q| q.cancel(self.id)) + } +} + +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] +struct Ticket { + id: JobId, + generation: u64, +} + +#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd)] +struct PreloadTicket { + unranked: bool, + rank: usize, + sequence: u64, + ticket: Ticket, +} + +struct Job { + priority: Priority, + preload_rank: Option, + generation: u64, + work: Work, + completion: Arc, +} + +struct State { + next_id: u64, + next_sequence: u64, + stopped: bool, + jobs: HashMap, + ready: [VecDeque; Priority::COUNT], + preload_ready: BinaryHeap>, +} + +impl State { + fn push(&mut self, priority: Priority, ticket: Ticket, preload_rank: Option) { + if priority == Priority::Preload { + self.next_sequence = self.next_sequence.checked_add(1).expect("build queue sequence overflow"); + self.preload_ready.push(Reverse(PreloadTicket { + unranked: preload_rank.is_none(), + rank: preload_rank.unwrap_or(0), + sequence: self.next_sequence, + ticket, + })); + } else { + self.ready[priority.index()].push_back(ticket); + } + } + + fn pop(&mut self, priority: Priority) -> Option { + if priority == Priority::Preload { + self.preload_ready.pop().map(|ticket| ticket.0.ticket) + } else { + self.ready[priority.index()].pop_front() + } + } +} + +struct Inner { + state: Mutex, + ranked_preloads: RankedPreloadCounters, + preload_changed: Condvar, + foreground_changed: Condvar, + all_changed: Condvar, +} + +impl Inner { + fn changed(&self, low: Priority, high: Priority) -> &Condvar { + if high <= Priority::Preload { + &self.preload_changed + } else if low >= Priority::BoundSoon { + &self.foreground_changed + } else { + &self.all_changed + } + } + + fn wake(&self, priority: Priority) { + if priority <= Priority::Preload { + self.preload_changed.notify_one(); + } else { + self.foreground_changed.notify_one(); + } + self.all_changed.notify_one(); + } + + fn promote(&self, id: JobId, priority: Priority) -> bool { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let Some(job) = state.jobs.get_mut(&id) else { return false }; + if priority <= job.priority { + return true; + } + let ranked_preload = job.priority == Priority::Preload && job.preload_rank.is_some(); + job.priority = priority; + job.generation += 1; + let ticket = Ticket { id, generation: job.generation }; + let preload_rank = job.preload_rank; + state.push(priority, ticket, preload_rank); + if ranked_preload { + self.ranked_preloads.promoted.fetch_add(1, Ordering::Relaxed); + } + self.wake(priority); + true + } + + fn cancel(&self, id: JobId) -> bool { + let job = self.state.lock().unwrap_or_else(|e| e.into_inner()).jobs.remove(&id); + if let Some(job) = job { + job.completion.set(JobStatus::Cancelled); + true + } else { + false + } + } + + fn take_ready(&self, state: &mut State, low: Priority, high: Priority) -> Option<(Work, Arc)> { + for priority in (low.index()..=high.index()).rev() { + let priority = match priority { + 0 => Priority::Speculative, + 1 => Priority::Preload, + 2 => Priority::BoundSoon, + _ => Priority::Foreground, + }; + while let Some(ticket) = state.pop(priority) { + let current = state.jobs.get(&ticket.id).is_some_and(|job| { + job.priority == priority && job.generation == ticket.generation + }); + if current { + let job = state.jobs.remove(&ticket.id).unwrap(); + if priority == Priority::Preload && job.preload_rank.is_some() { + self.ranked_preloads.started.fetch_add(1, Ordering::Relaxed); + } + job.completion.set(JobStatus::Running); + return Some((job.work, job.completion)); + } + } + } + None + } + + fn take(&self, wait: bool, low: Priority, high: Priority) -> Option<(Work, Arc)> { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let changed = self.changed(low, high); + loop { + if let Some(job) = self.take_ready(&mut state, low, high) { + return Some(job); + } + if state.stopped || !wait { + return None; + } + state = changed.wait(state).unwrap_or_else(|e| e.into_inner()); + } + } + + fn take_while(&self, low: Priority, high: Priority, keep_running: &mut impl FnMut() -> bool) -> Option<(Work, Arc)> { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let changed = self.changed(low, high); + loop { + if !keep_running() || state.stopped { + return None; + } + if let Some(job) = self.take_ready(&mut state, low, high) { + return Some(job); + } + state = changed.wait_timeout(state, std::time::Duration::from_millis(250)).unwrap_or_else(|e| e.into_inner()).0; + } + } + + fn shutdown(&self) { + let jobs = { + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.stopped { + return; + } + state.stopped = true; + for ready in &mut state.ready { + ready.clear(); + } + state.preload_ready.clear(); + std::mem::take(&mut state.jobs) + }; + for (_, job) in jobs { + job.completion.set(JobStatus::Cancelled); + } + self.preload_changed.notify_all(); + self.foreground_changed.notify_all(); + self.all_changed.notify_all(); + } +} + +pub(super) struct BuildQueue { + inner: Arc, +} + +impl BuildQueue { + pub(super) fn new() -> Self { + Self { + inner: Arc::new(Inner { + state: Mutex::new(State { + next_id: 0, + next_sequence: 0, + stopped: false, + jobs: HashMap::new(), + ready: std::array::from_fn(|_| VecDeque::new()), + preload_ready: BinaryHeap::new(), + }), + ranked_preloads: RankedPreloadCounters::new(), + preload_changed: Condvar::new(), + foreground_changed: Condvar::new(), + all_changed: Condvar::new(), + }), + } + } + + /// Add work to the queue. A stopped queue refuses it without running it. + pub(super) fn submit(&self, priority: Priority, work: Work) -> Option { + self.submit_ranked(priority, None, work) + } + + /// Add work, optionally ordered by an earlier-run rank within the Preload band only. + pub(super) fn submit_ranked(&self, priority: Priority, preload_rank: Option, work: Work) -> Option { + let completion = Arc::new(Completion::new()); + let mut state = self.inner.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.stopped { + return None; + } + state.next_id = state.next_id.checked_add(1).expect("build queue job ID overflow"); + let id = JobId(state.next_id); + let generation = 0; + let preload_rank = if priority == Priority::Preload { preload_rank } else { None }; + state.jobs.insert(id, Job { priority, preload_rank, generation, work, completion: completion.clone() }); + state.push(priority, Ticket { id, generation }, preload_rank); + if preload_rank.is_some() { + self.inner.ranked_preloads.submissions.fetch_add(1, Ordering::Relaxed); + } + drop(state); + self.inner.wake(priority); + Some(JobHandle { id, queue: Arc::downgrade(&self.inner), completion }) + } + + pub(super) fn worker(&self) -> Worker { + self.worker_between(Priority::Speculative, Priority::Foreground) + } + + pub(super) fn ranked_preload_stats(&self) -> RankedPreloadSnapshot { + self.inner.ranked_preloads.snapshot() + } + + pub(super) fn worker_between(&self, low: Priority, high: Priority) -> Worker { + Worker { inner: self.inner.clone(), low, high } + } + + /// Run one ready job on this thread, for callers that help drain a batch. + pub(super) fn try_run_one(&self) -> bool { + self.try_run_one_between(Priority::Speculative, Priority::Foreground) + } + + pub(super) fn try_run_one_between(&self, low: Priority, high: Priority) -> bool { + self.inner.take(false, low, high).is_some_and(|job| { + run(job); + true + }) + } + + pub(super) fn shutdown(&self) { + self.inner.shutdown(); + } +} + +impl Drop for BuildQueue { + fn drop(&mut self) { + self.inner.shutdown(); + } +} + +pub(super) struct Worker { + inner: Arc, + low: Priority, + high: Priority, +} + +impl Worker { + pub(super) fn run(self) { + while let Some(job) = self.inner.take(true, self.low, self.high) { + run(job); + } + } + + /// Run until `keep_running` closes, checking it while idle without stopping the queue. + pub(super) fn run_while(self, mut keep_running: impl FnMut() -> bool) { + while let Some(job) = self.inner.take_while(self.low, self.high, &mut keep_running) { + run(job); + } + } +} + +fn run((work, completion): (Work, Arc)) { + let status = if catch_unwind(AssertUnwindSafe(work)).is_ok() { JobStatus::Complete } else { JobStatus::Panicked }; + completion.set(status); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicBool, Ordering}; + + fn record(out: &Arc>>, value: u32) -> Work { + let out = out.clone(); + Box::new(move || out.lock().unwrap().push(value)) + } + + #[test] + fn highest_priority_runs_first_and_each_priority_is_fifo() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit(Priority::Speculative, record(&out, 1)).unwrap(); + q.submit(Priority::BoundSoon, record(&out, 2)).unwrap(); + q.submit(Priority::BoundSoon, record(&out, 3)).unwrap(); + q.submit(Priority::Foreground, record(&out, 4)).unwrap(); + q.submit(Priority::Preload, record(&out, 5)).unwrap(); + while q.try_run_one() {} + assert_eq!(*out.lock().unwrap(), [4, 2, 3, 5, 1]); + } + + #[test] + fn preload_jobs_run_in_earlier_first_use_order() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit_ranked(Priority::Preload, None, record(&out, 1)).unwrap(); + q.submit_ranked(Priority::Preload, Some(20), record(&out, 2)).unwrap(); + q.submit_ranked(Priority::Preload, Some(3), record(&out, 3)).unwrap(); + while q.try_run_one_between(Priority::Preload, Priority::Preload) {} + assert_eq!(*out.lock().unwrap(), [3, 2, 1]); + } + + #[test] + fn preload_rank_ties_and_unranked_jobs_are_fifo() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit_ranked(Priority::Preload, None, record(&out, 1)).unwrap(); + q.submit_ranked(Priority::Preload, Some(4), record(&out, 2)).unwrap(); + q.submit_ranked(Priority::Preload, Some(4), record(&out, 3)).unwrap(); + q.submit_ranked(Priority::Preload, None, record(&out, 4)).unwrap(); + while q.try_run_one_between(Priority::Preload, Priority::Preload) {} + assert_eq!(*out.lock().unwrap(), [2, 3, 1, 4]); + assert_eq!( + q.ranked_preload_stats(), + RankedPreloadSnapshot { submissions: 2, started: 2, promoted: 0 }, + ); + } + + #[test] + fn promoted_and_cancelled_ranked_tickets_go_stale() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + let promoted = q.submit_ranked(Priority::Preload, Some(0), record(&out, 1)).unwrap(); + let cancelled = q.submit_ranked(Priority::Preload, Some(1), record(&out, 2)).unwrap(); + q.submit_ranked(Priority::Preload, Some(2), record(&out, 3)).unwrap(); + assert!(promoted.promote(Priority::Foreground)); + assert!(cancelled.cancel()); + assert!(q.try_run_one_between(Priority::Preload, Priority::Preload)); + assert!(!q.try_run_one_between(Priority::Preload, Priority::Preload)); + assert!(q.try_run_one_between(Priority::Foreground, Priority::Foreground)); + assert_eq!(*out.lock().unwrap(), [3, 1]); + assert_eq!( + q.ranked_preload_stats(), + RankedPreloadSnapshot { submissions: 3, started: 1, promoted: 1 }, + ); + } + + #[test] + fn promotion_is_monotonic_and_joins_the_new_priority_fifo() { + let q = BuildQueue::new(); + let out = Arc::new(Mutex::new(Vec::new())); + q.submit(Priority::Foreground, record(&out, 1)).unwrap(); + let promoted = q.submit(Priority::Speculative, record(&out, 2)).unwrap(); + assert!(promoted.promote(Priority::Foreground)); + assert!(promoted.promote(Priority::Preload), "a lower request leaves it promoted"); + while q.try_run_one() {} + assert_eq!(*out.lock().unwrap(), [1, 2]); + } + + #[test] + fn foreground_worker_band_is_not_trapped_by_preload_work() { + let q = BuildQueue::new(); + let normal = q.worker_between(Priority::BoundSoon, Priority::Foreground); + let preload = q.worker_between(Priority::Speculative, Priority::Preload); + let normal_thread = std::thread::Builder::new().name("normal-band".into()).spawn(move || normal.run()).unwrap(); + let preload_thread = std::thread::Builder::new().name("preload-band".into()).spawn(move || preload.run()).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + for (priority, label) in [(Priority::Preload, "preload"), (Priority::Foreground, "foreground")] { + let tx = tx.clone(); + q.submit(priority, Box::new(move || { + tx.send((label, std::thread::current().name().unwrap().to_string())).unwrap(); + })).unwrap(); + } + let mut ran = vec![ + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(), + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(), + ]; + ran.sort_unstable(); + assert_eq!(ran, [("foreground", "normal-band".into()), ("preload", "preload-band".into())]); + q.shutdown(); + normal_thread.join().unwrap(); + preload_thread.join().unwrap(); + } + + #[test] + fn conditional_foreground_worker_retires_without_stopping_the_queue() { + let q = BuildQueue::new(); + let keep = Arc::new(AtomicBool::new(true)); + let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground); + let worker_keep = keep.clone(); + let thread = std::thread::spawn(move || worker.run_while(|| worker_keep.load(Ordering::Acquire))); + let preload = q.submit(Priority::Preload, Box::new(|| {})).unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + q.submit(Priority::Foreground, Box::new(move || tx.send(()).unwrap())).unwrap(); + rx.recv_timeout(std::time::Duration::from_secs(2)).unwrap(); + assert_eq!(preload.status(), JobStatus::Queued, "the replacement stays in its priority band"); + keep.store(false, Ordering::Release); + thread.join().unwrap(); + assert!(q.try_run_one_between(Priority::Preload, Priority::Preload), "retirement leaves the queue usable"); + } + + #[test] + fn promoted_preload_moves_to_the_foreground_worker_band() { + let q = BuildQueue::new(); + let ran = Arc::new(AtomicBool::new(false)); + let mark = ran.clone(); + let job = q.submit(Priority::Preload, Box::new(move || mark.store(true, Ordering::Release))).unwrap(); + assert!(job.promote(Priority::Foreground)); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(ran.load(Ordering::Acquire)); + } + + #[test] + fn job_ids_are_stable_and_not_reused() { + let q = BuildQueue::new(); + let a = q.submit(Priority::Preload, Box::new(|| {})).unwrap(); + let b = q.submit(Priority::Preload, Box::new(|| {})).unwrap(); + assert_ne!(a.id(), b.id()); + let id = a.id(); + assert!(a.cancel()); + assert_eq!(a.id(), id); + } + + #[test] + fn only_a_queued_job_can_be_cancelled() { + let q = BuildQueue::new(); + let cancelled = q.submit(Priority::Preload, Box::new(|| panic!("must not run"))).unwrap(); + assert!(cancelled.cancel()); + assert_eq!(cancelled.wait(), JobStatus::Cancelled); + + let running = Arc::new(AtomicBool::new(false)); + let finish = Arc::new((Mutex::new(false), Condvar::new())); + let (seen, gate) = (running.clone(), finish.clone()); + let handle = q.submit(Priority::Foreground, Box::new(move || { + seen.store(true, Ordering::Release); + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + })).unwrap(); + let worker = q.worker(); + let thread = std::thread::spawn(move || worker.run()); + while !running.load(Ordering::Acquire) { + std::thread::yield_now(); + } + assert_eq!(handle.status(), JobStatus::Running); + assert!(!handle.cancel()); + *finish.0.lock().unwrap() = true; + finish.1.notify_all(); + assert_eq!(handle.wait(), JobStatus::Complete); + q.shutdown(); + thread.join().unwrap(); + } + + #[test] + fn a_panicking_job_completes_and_the_worker_continues() { + let q = BuildQueue::new(); + let panicked = q.submit(Priority::Foreground, Box::new(|| panic!("expected"))).unwrap(); + let ran = Arc::new(AtomicBool::new(false)); + let mark = ran.clone(); + let after = q.submit(Priority::BoundSoon, Box::new(move || mark.store(true, Ordering::Release))).unwrap(); + assert!(q.try_run_one()); + assert_eq!(panicked.wait(), JobStatus::Panicked); + assert!(q.try_run_one()); + assert_eq!(after.wait(), JobStatus::Complete); + assert!(ran.load(Ordering::Acquire)); + } + + #[test] + fn shutdown_cancels_queued_work_and_wakes_workers() { + let q = BuildQueue::new(); + let a = q.submit(Priority::Foreground, Box::new(|| panic!("must not run"))).unwrap(); + let b = q.submit(Priority::Speculative, Box::new(|| panic!("must not run"))).unwrap(); + let worker = q.worker(); + q.shutdown(); + let thread = std::thread::spawn(move || worker.run()); + assert_eq!(a.wait(), JobStatus::Cancelled); + assert_eq!(b.wait(), JobStatus::Cancelled); + assert!(q.submit(Priority::Foreground, Box::new(|| {})).is_none()); + thread.join().unwrap(); + } +} diff --git a/crates/xcl/src/hle/d3d12x/console_heap.rs b/crates/xcl/src/hle/d3d12x/console_heap.rs index 4862abd84c..60a3136444 100644 --- a/crates/xcl/src/hle/d3d12x/console_heap.rs +++ b/crates/xcl/src/hle/d3d12x/console_heap.rs @@ -25,6 +25,7 @@ //! Without the shared heap (it could not be made) a heap keeps its own PC heap: SRV at 2k, //! UAV at 2k + 1. +use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; use windows::core::Interface; @@ -46,6 +47,7 @@ enum Memory { } struct Heap { + generation: u64, obj: usize, shadow: usize, n: u32, @@ -73,6 +75,100 @@ impl Heap { } static HEAPS: Mutex> = Mutex::new(Vec::new()); +static NEXT_HEAP_GENERATION: AtomicU64 = AtomicU64::new(0); +static HEAP_LIFETIMES: Mutex<()> = Mutex::new(()); + +pub(super) type HeapLifetimeGuard = std::sync::MutexGuard<'static, ()>; + +/// Exclude final descriptor-heap `Release` while an exact heap generation is turned into +/// strong native owners. This is separate from the descriptor-write gate: hooks keep that gate +/// across driver calls which may temporarily release a heap. +pub(super) fn lock_lifetime() -> Option { + super::vram::srv_tracking_enabled().then(|| HEAP_LIFETIMES.lock().unwrap()) +} + +/// Shared ranges being written by lock-free single-descriptor publication, and releases which +/// cannot return to the allocator until every overlapping write has finished. +#[derive(Default)] +struct PublishLeases { + active: Vec<(u32, u32)>, + deferred: Vec<(u32, u32)>, +} + +impl PublishLeases { + fn acquire(&mut self, first: u32, count: u32) { + self.active.push((first, count)); + } + + fn release_range(&mut self, free: &mut Vec<(u32, u32)>, first: u32, count: u32) { + let range = (first, count); + if self.active.iter().any(|&active| ranges_overlap(active, range)) { + self.deferred.push(range); + } else { + merge_release(free, first, count); + } + } + + fn finish(&mut self, free: &mut Vec<(u32, u32)>, range: (u32, u32)) { + self.finish_ranges(free, &[range]); + } + + fn finish_ranges(&mut self, free: &mut Vec<(u32, u32)>, ranges: &[(u32, u32)]) { + for &range in ranges { + if let Some(i) = self.active.iter().position(|&active| active == range) { + self.active.swap_remove(i); + } + } + let mut i = 0; + while i < self.deferred.len() { + let deferred = self.deferred[i]; + if self.active.iter().any(|&active| ranges_overlap(active, deferred)) { + i += 1; + } else { + self.deferred.swap_remove(i); + merge_release(free, deferred.0, deferred.1); + } + } + } +} + +fn ranges_overlap(a: (u32, u32), b: (u32, u32)) -> bool { + a.0 < b.0.saturating_add(b.1) && b.0 < a.0.saturating_add(a.1) +} + +struct PublishLease { + sampler: bool, + range: (u32, u32), +} + +struct PublishRangeLease { + sampler: bool, + ranges: Vec<(u32, u32)>, +} + +impl Drop for PublishRangeLease { + fn drop(&mut self) { + if self.sampler { + if let Some(global) = GLOBAL_SAMPLER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish_ranges(&mut global.free, &self.ranges); + } + } else if let Some(global) = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish_ranges(&mut global.free, &self.ranges); + } + } +} + +impl Drop for PublishLease { + fn drop(&mut self) { + if self.sampler { + if let Some(global) = GLOBAL_SAMPLER.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish(&mut global.free, self.range); + } + } else if let Some(global) = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + global.leases.finish(&mut global.free, self.range); + } + } +} /// The shader-visible PC heap of all console view heaps. struct Global { @@ -85,6 +181,7 @@ struct Global { next: u32, /// released ranges (first, count) free: Vec<(u32, u32)>, + leases: PublishLeases, } // D3D12 descriptor heaps and devices are free-threaded @@ -169,17 +266,20 @@ pub unsafe fn shared_heap(dev: &ID3D12Device) -> bool { } }; crate::xlog_info!("console descriptor heaps: one shader-visible PC heap of {cap} view descriptors for all of them"); - null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)); + let inc = dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + null_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, inc); + null_window_views(dev, heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, inc); *g = Some(Global { dev: dev.clone(), cpu: heap.GetCPUDescriptorHandleForHeapStart().ptr as u64, gpu: heap.GetGPUDescriptorHandleForHeapStart().ptr, - inc: dev.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV), + inc, heap, cap, - // the memory windows' raw UAVs (`set_window_views`) come first - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, + // the memory windows and their two out-of-range null UAVs come first + next: crate::gpu::recomp::MEM_NULL_STORE + 1, free: Vec::new(), + leases: PublishLeases::default(), }); } true @@ -210,6 +310,19 @@ unsafe fn null_views(dev: &ID3D12Device, cpu: u64, inc: u32) { } } +/// Null raw UAVs used by heap-window accessors for out-of-layout loads and stores. +unsafe fn null_window_views(dev: &ID3D12Device, cpu: u64, inc: u32) { + for idx in [crate::gpu::recomp::MEM_NULL_LOAD, crate::gpu::recomp::MEM_NULL_STORE] { + let at = D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + idx as u64 * inc as u64) as usize }; + dev.CreateUnorderedAccessView( + None::<&ID3D12Resource>, + None::<&ID3D12Resource>, + Some(&crate::gpu::recomp::runner::raw_window_uav(4)), + at, + ); + } +} + static WINDOW_VIEWS_FAILED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); /// Whether the memory windows could not be put in the shared heap (`set_window_views`): @@ -284,7 +397,7 @@ pub fn release_global(first: u32, count: u32) { return; } if let Some(s) = GLOBAL.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + s.leases.release_range(&mut s.free, first, count); } } @@ -376,35 +489,67 @@ pub fn register(obj: usize, n: u32, pc_cpu: u64, pc_gpu: u64, inc: u32, sampler: } else { Vec::new() }; - HEAPS.lock().unwrap().push(Heap { obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); + let generation = NEXT_HEAP_GENERATION.fetch_add(1, Ordering::Relaxed).wrapping_add(1); + HEAPS.lock().unwrap().push(Heap { generation, obj, shadow: p as usize, n, pc_cpu, pc_gpu, inc, sampler, pages, visible, memory }); true } /// The heap object was released for good: its slots go back to unified memory. pub fn unregister(obj: usize) { - let gone = { - let mut heaps = HEAPS.lock().unwrap(); - heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) - }; - if let Some(h) = gone { - for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { - if h.sampler { - release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); - } else { - release_global(f, page_descriptors(h.n, p as u32)); - } + if let Some(h) = take(obj) { + free(h); + } +} + +/// A heap removed by `take`; its backing storage remains live until `free`. +pub struct Taken(Heap); + +/// Stop finding a heap by object address without freeing memory the object may still use. +pub fn take(obj: usize) -> Option { + let heap = detach(obj)?; + super::vram::forget_srv_heap(heap.generation); + Some(Taken(heap)) +} + +fn detach(obj: usize) -> Option { + let mut heaps = HEAPS.lock().unwrap(); + heaps.iter().position(|h| h.obj == obj).map(|i| heaps.swap_remove(i)) +} + +pub(super) fn generation(obj: usize) -> Option { + HEAPS.lock().unwrap().iter().find(|heap| heap.obj == obj).map(|heap| heap.generation) +} + +/// Detach bookkeeping before the native object can die. The caller holds `HEAP_LIFETIMES`, so +/// cleanup must not wait for the descriptor-write gate (a reentrant temporary Release may hold +/// that gate while waiting here). +pub(super) fn take_after_release(obj: usize, generation: Option, lifetime: Option<&HeapLifetimeGuard>) -> Option { + let mut heaps = HEAPS.lock().unwrap(); + let heap = heaps.iter().position(|h| h.obj == obj && Some(h.generation) == generation).map(|i| heaps.swap_remove(i))?; + drop(heaps); + super::vram::forget_srv_heap_after_release(heap.generation, lifetime); + Some(Taken(heap)) +} + +/// Return a taken heap's slots and shadow memory after its native object is gone. +pub fn free(Taken(h): Taken) { + for (p, &f) in h.pages.iter().enumerate().filter(|&(_, &f)| f != UNMAPPED) { + if h.sampler { + release_global_sampler(f, sampler_page_descriptors(h.n, p as u32)); + } else { + release_global(f, page_descriptors(h.n, p as u32)); } - match h.memory { - Memory::Sparse => { - unsafe { super::sparse::free(h.shadow) }; - } - Memory::Uma => { - if let Some(u) = crate::gpu::uma::get() { - u.free(h.shadow); - } + } + match h.memory { + Memory::Sparse => { + unsafe { super::sparse::free(h.shadow) }; + } + Memory::Uma => { + if let Some(u) = crate::gpu::uma::get() { + u.free(h.shadow); } - Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } + Memory::Title => unsafe { crate::hle::kernelx::runtime_free(h.shadow, crate::hle::kernelx::D3D_DESCRIPTOR_HEAP) }, } } @@ -416,6 +561,7 @@ pub fn start(obj: usize) -> Option { /// A console slot: where its descriptor goes and its PC descriptors. #[derive(Clone, Copy, Debug)] pub struct Slot { + pub(super) generation: u64, pub at: usize, /// views: PC heap index of the SRV (the UAV is at + 1); samplers: of the sampler pub index: u32, @@ -429,6 +575,81 @@ pub struct Slot { pub shared_srv: u64, /// the slot's number in its heap pub k: u32, + /// slots from this one through the end of its heap + pub remaining: u32, +} + +/// Strong ownership and the exact handles of one view slot. Holding this value only proves CPU +/// object lifetime; a consumer must separately prove queue quiescence, take the descriptor-write +/// gate, and revalidate the tracked logical generation and words before mutating descriptors. +#[allow(dead_code)] +pub(super) struct ViewSlotLease { + pub pc_srv: u64, + pub shared_srv: u64, + pub index: u32, + _device: ID3D12Device, + _source_heap: ID3D12DescriptorHeap, + _shared_heap: Option, +} + +/// Lease the native objects behind one exact heap generation and slot. All arithmetic and both +/// CPU handles are checked while `HEAPS` (and, for a shared slot, `GLOBAL`) still identify that +/// generation. Driver calls happen only after allocator locks have been dropped. +#[allow(dead_code)] +pub(super) fn lease_view_slot(generation: u64, k: u32, pc_srv: u64, shared_srv: u64, index: u32) -> Option { + let _lifetime = lock_lifetime()?; + let (source_raw, shared_index) = { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| h.generation == generation && !h.sampler && k < h.n)?; + let local_index = k.checked_mul(2)?; + let expected_pc = h.pc_cpu.checked_add(local_index as u64 * h.inc as u64)?; + if expected_pc != pc_srv { + return None; + } + let shared_index = if h.pages.is_empty() { + if shared_srv != 0 || index != local_index { + return None; + } + None + } else { + let first = *h.pages.get((k / PAGE_SLOTS) as usize)?; + if first == UNMAPPED { + return None; + } + Some(first.checked_add(2 * (k % PAGE_SLOTS))?) + }; + (h.obj as *mut std::ffi::c_void, shared_index) + }; + let shared_raw = if let Some(expected_index) = shared_index { + let global = GLOBAL.lock().unwrap(); + let global = global.as_ref()?; + if expected_index.checked_add(1)? >= global.cap + || index != expected_index + || shared_srv != global.cpu.checked_add(expected_index as u64 * global.inc as u64)? + { + return None; + } + Some((global.dev.as_raw(), global.heap.as_raw())) + } else { + None + }; + // The lifetime gate prevents source final Release, and process-global heaps are never + // replaced. Invoke COM only after allocator mutexes have been dropped. + let source_heap = unsafe { ID3D12DescriptorHeap::from_raw_borrowed(&source_raw)?.clone() }; + // The strong source owner now prevents native final Release. Leave the non-reentrant gate + // before any fallible COM work so an error or unwind can drop that owner through our hooked + // Release without trying to reacquire a gate this thread still holds. + drop(_lifetime); + let (device, shared_heap) = if let Some((device_raw, heap_raw)) = shared_raw { + let device = unsafe { ID3D12Device::from_raw_borrowed(&device_raw)?.clone() }; + let heap = unsafe { ID3D12DescriptorHeap::from_raw_borrowed(&heap_raw)?.clone() }; + (device, Some(heap)) + } else { + let mut device = None; + unsafe { source_heap.GetDevice(&mut device).ok()? }; + (device?, None) + }; + Some(ViewSlotLease { pc_srv, shared_srv, index, _device: device, _source_heap: source_heap, _shared_heap: shared_heap }) } /// The slot behind a console CPU handle (None: not one of XCL's console heaps). A view slot @@ -448,7 +669,7 @@ pub fn slot(cpu: u64) -> Option { // shared heap must map overflowed slots to reserved zero-sampler slot 0 rather than // aliasing unrelated heap entries at local index `k`. let (index, shared_srv) = shared.unwrap_or_else(|| (sampler_unmapped_index(!h.pages.is_empty(), k), 0)); - return Some(Slot { at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k }); + return Some(Slot { generation: h.generation, at: h.shadow + (k * SAMPLER_SLOT) as usize, index, pc_srv: h.pc_cpu + (k * h.inc) as u64, pc_uav: 0, pc_gpu_uav: 0, sampler: true, shared_srv, k, remaining: h.n - k }); } let uav = ((2 * k + 1) * h.inc) as u64; let shared = page_of(h, k).and_then(|(first, k0)| { @@ -458,7 +679,7 @@ pub fn slot(cpu: u64) -> Option { Some((i, g.gpu + (i as u64 + 1) * g.inc as u64, g.cpu + i as u64 * g.inc as u64)) }); let (index, pc_gpu_uav, shared_srv) = shared.unwrap_or((2 * k, if h.pc_gpu == 0 { 0 } else { h.pc_gpu + uav }, 0)); - Some(Slot { at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k }) + Some(Slot { generation: h.generation, at: h.shadow + (k * SLOT) as usize, index, pc_srv: h.pc_cpu + (2 * k * h.inc) as u64, pc_uav: h.pc_cpu + uav, pc_gpu_uav, sampler: false, shared_srv, k, remaining: h.n - k }) } /// The view (or sampler) just made in slot `s` (its SRV, or with `uav` its UAV) goes to the shared heap. @@ -466,48 +687,138 @@ pub unsafe fn publish(s: &Slot, uav: bool) { if s.shared_srv == 0 { return; } - if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - 1, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); + // Keep the exact source heap generation alive and lease its shared destination before + // dropping HEAPS. A concurrent final Release can then detach its books, but cannot free the + // source object or recycle the shared index until CopyDescriptorsSimple returns. + let snapshot = (|| { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|h| { + h.generation == s.generation + && h.sampler == s.sampler + && s.k < h.n + && s.at == h.shadow + (s.k * h.slot_bytes()) as usize + })?; + let raw = h.obj as *mut std::ffi::c_void; + let source_owner = ID3D12DescriptorHeap::from_raw_borrowed(&raw)?.clone(); + if h.sampler { + let first = *h.pages.get((s.k / SAMPLER_PAGE_SLOTS) as usize)?; + if first == UNMAPPED || h.pc_cpu + (s.k * h.inc) as u64 != s.pc_srv { + return None; + } + let idx = first + s.k % SAMPLER_PAGE_SLOTS; + let mut globals = GLOBAL_SAMPLER.lock().unwrap(); + let global = globals.as_mut()?; + let dst = global.cpu + idx as u64 * global.inc as u64; + if dst != s.shared_srv { + return None; + } + global.leases.acquire(idx, 1); + Some((global.dev.clone(), source_owner, PublishLease { sampler: true, range: (idx, 1) }, dst, s.pc_srv, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)) + } else { + let first = *h.pages.get((s.k / PAGE_SLOTS) as usize)?; + let src = if uav { s.pc_uav } else { s.pc_srv }; + let expected_src = h.pc_cpu + (2 * s.k + uav as u32) as u64 * h.inc as u64; + if first == UNMAPPED || expected_src != src { + return None; + } + let idx = first + 2 * (s.k % PAGE_SLOTS) + uav as u32; + let mut globals = GLOBAL.lock().unwrap(); + let global = globals.as_mut()?; + let dst = global.cpu + idx as u64 * global.inc as u64; + if dst != s.shared_srv + uav as u64 * global.inc as u64 { + return None; + } + global.leases.acquire(idx, 1); + Some((global.dev.clone(), source_owner, PublishLease { sampler: false, range: (idx, 1) }, dst, src, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV)) } + })(); + let Some((dev, _source_owner, _lease, dst, src, ty)) = snapshot else { return; - } - if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - let (dst, src) = if uav { (s.shared_srv + g.inc as u64, s.pc_uav) } else { (s.shared_srv, s.pc_srv) }; - g.dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); - } + }; + dev.CopyDescriptorsSimple(1, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: dst as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, ty); } /// `n` view or sampler slots from `first` were copied (in the title's heap): they go to the shared heap, -/// a run per page (a heap's pages lie apart there). +/// a run per page (a heap's pages lie apart there), stopping at the title heap's end. pub unsafe fn publish_range(first: &Slot, n: u32) { - let page_slots = if first.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; - let step = if first.sampler { SAMPLER_SLOT } else { SLOT }; - let mut done = 0; - while done < n { - let s = if done == 0 { Some(*first) } else { slot((first.at + (done * step) as usize) as u64) }; - let Some(s) = s else { return }; - let run = (page_slots - s.k % page_slots).min(n - done); - if s.shared_srv != 0 { - if s.sampler { - if let Some(g) = GLOBAL_SAMPLER.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple( - run, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, - D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, - D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, - ); - } - } else if let Some(g) = GLOBAL.lock().unwrap().as_ref() { - g.dev.CopyDescriptorsSimple(2 * run, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.shared_srv as usize }, D3D12_CPU_DESCRIPTOR_HANDLE { ptr: s.pc_srv as usize }, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + if n == 0 || first.shared_srv == 0 { + return; + } + // Resolve every page and lease every destination while HEAPS prevents unregister from + // detaching this exact generation. The device calls then need none of the allocator locks. + let snapshot = (|| { + let mut heaps = HEAPS.lock().unwrap(); + let h = heaps.iter_mut().find(|h| { + h.generation == first.generation + && h.sampler == first.sampler + && first.k < h.n + && first.at == h.shadow + (first.k * h.slot_bytes()) as usize + })?; + let mul = if h.sampler { 1u32 } else { 2u32 }; + if h.pc_cpu + mul as u64 * first.k as u64 * h.inc as u64 != first.pc_srv { + return None; + } + let raw = h.obj as *mut std::ffi::c_void; + let source_owner = ID3D12DescriptorHeap::from_raw_borrowed(&raw)?.clone(); + let page_slots = if h.sampler { SAMPLER_PAGE_SLOTS } else { PAGE_SLOTS }; + let limit = n.min(first.remaining).min(h.n - first.k); + let mut runs = Vec::with_capacity(limit.div_ceil(page_slots) as usize); + let mut done = 0; + while done < limit { + let k = first.k + done; + let run = (page_slots - k % page_slots).min(limit - done); + let (page, k0) = if h.sampler { sampler_page_of(h, k)? } else { page_of(h, k)? }; + runs.push((page + mul * (k - k0), h.pc_cpu + mul as u64 * k as u64 * h.inc as u64, mul * run)); + done += run; + } + if h.sampler { + let mut globals = GLOBAL_SAMPLER.lock().unwrap(); + let global = globals.as_mut()?; + if global.cpu + runs.first()?.0 as u64 * global.inc as u64 != first.shared_srv { + return None; } + for &(at, _, count) in &runs { + global.leases.acquire(at, count); + } + Some(( + global.dev.clone(), + source_owner, + PublishRangeLease { sampler: true, ranges: runs.iter().map(|&(at, _, count)| (at, count)).collect() }, + global.cpu, + global.inc, + runs, + D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, + )) + } else { + let mut globals = GLOBAL.lock().unwrap(); + let global = globals.as_mut()?; + if global.cpu + runs.first()?.0 as u64 * global.inc as u64 != first.shared_srv { + return None; + } + for &(at, _, count) in &runs { + global.leases.acquire(at, count); + } + Some(( + global.dev.clone(), + source_owner, + PublishRangeLease { sampler: false, ranges: runs.iter().map(|&(at, _, count)| (at, count)).collect() }, + global.cpu, + global.inc, + runs, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, + )) } - done += run; + })(); + let Some((dev, _source_owner, _lease, cpu, inc, runs, ty)) = snapshot else { + return; + }; + for (at, src, count) in runs { + dev.CopyDescriptorsSimple( + count, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: (cpu + at as u64 * inc as u64) as usize }, + D3D12_CPU_DESCRIPTOR_HANDLE { ptr: src as usize }, + ty, + ); } } @@ -556,6 +867,19 @@ pub fn copy_words(src: &Slot, dst: &Slot) { } } +/// The tracking-only form of `copy_words`, retaining the exact source and destination bytes. +pub fn copy_words_captured(src: &Slot, dst: &Slot) -> ([u32; 8], [u32; 8]) { + let mut source = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping(src.at as *const u32, source.as_mut_ptr(), 8) }; + let mut destination = source; + if destination[3] >> 28 >= 8 { + destination[0] = dst.index; + } + write(dst, &destination); + note_resource(dst, resource_at(src.at).unwrap_or(0)); + (source, destination) +} + /// `XCL_TRACE_FRAME`: what the slots of each shader-visible view heap hold – images whose /// PC index is the slot's own (made or copied through the device) or another (copied by the /// title itself, as memory), buffers, empty. @@ -628,6 +952,38 @@ pub fn words_at(addr32: u32) -> Option<[u32; 8]> { Some(w) } +/// Exact console words currently in view slots identified by heap generation and slot number. +/// Build the generation index once so validating S tracked slots across H heaps is O(S + H), and +/// keep `HEAPS` held while reading so the backing storage cannot be freed underneath us. +pub(super) fn view_slot_words(slots: &[(u64, u32)]) -> Vec> { + let heaps = HEAPS.lock().unwrap(); + let by_generation: std::collections::HashMap<_, _> = heaps + .iter() + .filter(|heap| !heap.sampler) + .map(|heap| (heap.generation, heap)) + .collect(); + slots + .iter() + .map(|&(generation, k)| { + let h = by_generation.get(&generation).filter(|heap| k < heap.n)?; + let mut words = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping((h.shadow + (k * SLOT) as usize) as *const u32, words.as_mut_ptr(), 8) }; + Some(words) + }) + .collect() +} + +/// Exact console words currently in one view slot. The exact-generation heap lease used by a +/// caller keeps the native object and its backing allocation alive; `HEAPS` still verifies that +/// the allocation has not been detached before the point-in-time read. +pub(super) fn exact_view_slot_words(generation: u64, k: u32) -> Option<[u32; 8]> { + let heaps = HEAPS.lock().unwrap(); + let h = heaps.iter().find(|heap| heap.generation == generation && !heap.sampler && k < heap.n)?; + let mut words = [0u32; 8]; + unsafe { std::ptr::copy_nonoverlapping((h.shadow + (k * SLOT) as usize) as *const u32, words.as_mut_ptr(), 8) }; + Some(words) +} + // --------------------------------------------------------------------------------------- // Shared shader-visible PC sampler heap (`GLOBAL_SAMPLER`, up to D3D12's 2048 limit): // allows 16-byte S# descriptors copied via raw CPU `memcpy` between CPU-only and @@ -663,6 +1019,7 @@ struct GlobalSampler { cap: u32, next: u32, free: Vec<(u32, u32)>, + leases: PublishLeases, } unsafe impl Send for GlobalSampler {} @@ -726,6 +1083,7 @@ pub unsafe fn shared_sampler_heap(dev: &ID3D12Device) -> bool { // Reserve slot 0 as the immutable point-wrap zero sampler for empty/zeroed S# entries. next: 1, free: Vec::new(), + leases: PublishLeases::default(), }); } true @@ -761,7 +1119,7 @@ fn release_global_sampler(first: u32, count: u32) { return; } if let Some(s) = GLOBAL_SAMPLER.lock().unwrap().as_mut() { - merge_release(&mut s.free, first, count); + s.leases.release_range(&mut s.free, first, count); } } @@ -812,6 +1170,81 @@ mod tests { assert!(free.is_empty()); } + #[test] + fn exact_view_slot_lease_survives_detach_and_rejects_address_reuse() { + const CHILD: &str = "XCL_TEST_VIEW_SLOT_LEASE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::exact_view_slot_lease_survives_detach_and_rejects_address_reuse", "--nocapture"]) + .env(CHILD, "1").env("XCL_TEXTURE_BUDGET_EVICT", "1").output().unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; + static RELEASE_REENTERED: AtomicBool = AtomicBool::new(false); + #[repr(C)] + struct Object { vt: *const usize, refs: AtomicU32 } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*(this as *mut Object)).refs.fetch_add(1, Ordering::Relaxed) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + RELEASE_REENTERED.fetch_or(HEAP_LIFETIMES.try_lock().is_ok(), Ordering::Relaxed); + (*(this as *mut Object)).refs.fetch_sub(1, Ordering::Relaxed) - 1 + } + unsafe extern "system" fn get_device(_this: *mut c_void, _iid: *const windows::core::GUID, _out: *mut *mut c_void) -> windows::core::HRESULT { + windows::core::HRESULT(0x8000_4002u32 as i32) + } + let mut vt = [0usize; 8]; + vt[1] = add_ref as usize; + vt[2] = release as usize; + vt[7] = get_device as usize; + let mut device = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut global_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut source_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw((&mut device as *mut Object).cast()), + heap: ID3D12DescriptorHeap::from_raw((&mut global_heap as *mut Object).cast()), + cpu: 0x10_0000, gpu: 0x20_0000, inc: 32, cap: 128, next: 80, + free: Vec::new(), leases: PublishLeases::default(), + }); + HEAPS.lock().unwrap().push(Heap { + generation: 70, obj: &mut source_heap as *mut Object as usize, shadow: 0x5000, + n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, + pages: vec![64], visible: true, memory: Memory::Uma, + }); + let lease = lease_view_slot(70, 2, 0x30_0080, 0x10_0880, 68).expect("exact slot"); + assert_eq!((source_heap.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), device.refs.load(Ordering::Relaxed)), (2, 2, 2)); + assert!(lease_view_slot(70, 4, 0x30_0100, 0, 0).is_none(), "slot bound"); + assert!(lease_view_slot(70, 2, 0x30_0080, 0x10_0880, 69).is_none(), "shared index"); + + let lifetime = lock_lifetime(); + let Taken(old) = take_after_release(&mut source_heap as *mut Object as usize, Some(70), lifetime.as_ref()).unwrap(); + drop(lifetime); + HEAPS.lock().unwrap().push(Heap { generation: 71, pc_cpu: 0x40_0000, pages: vec![80], ..old }); + assert!(lease_view_slot(70, 2, 0x30_0080, 0x10_0880, 68).is_none(), "old generation at reused object address"); + let lifetime = lock_lifetime(); + assert!(take_after_release(&mut source_heap as *mut Object as usize, Some(70), lifetime.as_ref()).is_none()); + drop(lifetime); + assert!(HEAPS.lock().unwrap().iter().any(|heap| heap.generation == 71), "late cleanup must keep the replacement"); + assert_eq!((lease.pc_srv, lease.shared_srv, lease.index), (0x30_0080, 0x10_0880, 68)); + drop(lease); + assert_eq!((source_heap.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), device.refs.load(Ordering::Relaxed)), (1, 1, 1)); + HEAPS.lock().unwrap().clear(); + HEAPS.lock().unwrap().push(Heap { + generation: 72, obj: &mut source_heap as *mut Object as usize, shadow: 0x6000, + n: 1, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, + pages: Vec::new(), visible: true, memory: Memory::Uma, + }); + RELEASE_REENTERED.store(false, Ordering::Relaxed); + assert!(lease_view_slot(72, 0, 0x50_0000, 0, 0).is_none(), "GetDevice fails"); + assert!(RELEASE_REENTERED.load(Ordering::Relaxed), "failed lease must drop its owner outside the lifetime gate"); + HEAPS.lock().unwrap().clear(); + *GLOBAL.lock().unwrap() = None; + } + } + #[test] fn a_freed_range_at_the_cursor_continues_into_the_never_used_tail() { // the false-full shape: four freed slots end at the cursor and four more were never @@ -870,7 +1303,7 @@ mod tests { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, - next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), + next: crate::gpu::recomp::MEM_HEAP_BASE + crate::gpu::uma::MAX_HEAP_WINDOWS as u32, free: Vec::new(), leases: PublishLeases::default(), }); let window = (&mut resource as *mut _ as usize, 0x10000); assert!(set_window_views(&dev, &[window])); @@ -1062,7 +1495,7 @@ mod tests { *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev: ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void), heap: ID3D12DescriptorHeap::from_raw(&mut heap as *mut _ as *mut c_void), - cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x1000, inc: 32, cap: 17, next: 1, free: Vec::new(), leases: PublishLeases::default(), }); assert_eq!(reserve_global_sampler(4), Some(1)); assert_eq!(reserve_global_sampler(4), Some(5)); @@ -1121,12 +1554,12 @@ mod tests { *GLOBAL.lock().unwrap() = Some(Global { dev: dev.clone(), heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), - cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), + cpu: 0x1000, gpu: 0x2000, inc: 32, cap: 1024, next: 64, free: Vec::new(), leases: PublishLeases::default(), }); *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { dev, heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), - cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), + cpu: 0x4000, inc: 32, cap: 17, next: 1, free: Vec::new(), leases: PublishLeases::default(), }); if crate::gpu::uma::get().is_some() { assert!(register(0xC100, 16, 0x9000, 0, 16, true, true, true)); @@ -1148,8 +1581,8 @@ mod tests { assert_eq!(GLOBAL_SAMPLER.lock().unwrap().as_ref().unwrap().free, vec![(1, 8)]); } else { let mut heaps = HEAPS.lock().unwrap(); - heaps.push(Heap { obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); - heaps.push(Heap { obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 1, obj: 0xC100, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 2, obj: 0xC101, shadow: 0, n: 16, pc_cpu: 0, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); drop(heaps); assert!(!in_global(0xC100) && in_global_sampler(0xC100)); assert!(in_global(0xC101) && !in_global_sampler(0xC101)); @@ -1176,4 +1609,201 @@ mod tests { assert_eq!(sampler_own_index(&[], 0), 0); assert_eq!(sampler_own_index(&[], 42), 42); } + + #[test] + fn publish_range_stops_at_small_and_tail_heap_bounds() { + const CHILD: &str = "XCL_TEST_PUBLISH_BOUNDS_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_range_stops_at_small_and_tail_heap_bounds", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, Ordering}; + + static LOCKS_FREE: AtomicBool = AtomicBool::new(true); + static CALLS: Mutex> = Mutex::new(Vec::new()); + #[repr(C)] + struct Object { vt: *const usize } + unsafe extern "system" fn retain(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn copy_simple( + _this: *mut c_void, + n: u32, + dst: D3D12_CPU_DESCRIPTOR_HANDLE, + src: D3D12_CPU_DESCRIPTOR_HANDLE, + ty: D3D12_DESCRIPTOR_HEAP_TYPE, + ) { + LOCKS_FREE.fetch_and( + GLOBAL.try_lock().is_ok() && GLOBAL_SAMPLER.try_lock().is_ok() && HEAPS.try_lock().is_ok(), + Ordering::Relaxed, + ); + CALLS.lock().unwrap().push((n, dst.ptr as u64, src.ptr as u64, ty.0)); + } + + let mut vt = [0usize; 25]; + vt[1] = retain as usize; + vt[2] = retain as usize; + vt[24] = copy_simple as usize; + let (mut device, mut view_heap, mut sampler_heap) = + (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let (mut source4, mut source3, mut source260) = + (Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }, Object { vt: vt.as_ptr() }); + let view4 = vec![0u8; (4 * SLOT) as usize]; + let sampler3 = vec![0u8; (3 * SAMPLER_SLOT) as usize]; + let view260 = vec![0u8; (260 * SLOT) as usize]; + unsafe { + let dev = ID3D12Device::from_raw(&mut device as *mut _ as *mut c_void); + *GLOBAL.lock().unwrap() = Some(Global { + dev: dev.clone(), + heap: ID3D12DescriptorHeap::from_raw(&mut view_heap as *mut _ as *mut c_void), + cpu: 0x10_0000, + gpu: 0x18_0000, + inc: 32, + cap: 4096, + next: 64, + free: Vec::new(), + leases: PublishLeases::default(), + }); + *GLOBAL_SAMPLER.lock().unwrap() = Some(GlobalSampler { + dev, + heap: ID3D12DescriptorHeap::from_raw(&mut sampler_heap as *mut _ as *mut c_void), + cpu: 0x20_0000, + inc: 16, + cap: 256, + next: 1, + free: Vec::new(), + leases: PublishLeases::default(), + }); + { + let mut heaps = HEAPS.lock().unwrap(); + heaps.push(Heap { generation: 1, obj: &mut source4 as *mut Object as usize, shadow: view4.as_ptr() as usize, n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 2, obj: &mut source3 as *mut Object as usize, shadow: sampler3.as_ptr() as usize, n: 3, pc_cpu: 0x40_0000, pc_gpu: 0, inc: 16, sampler: true, pages: vec![UNMAPPED], visible: true, memory: Memory::Uma }); + heaps.push(Heap { generation: 3, obj: &mut source260 as *mut Object as usize, shadow: view260.as_ptr() as usize, n: 260, pc_cpu: 0x50_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![UNMAPPED; 2], visible: true, memory: Memory::Uma }); + } + let v1 = slot(view4.as_ptr() as u64 + SLOT as u64).unwrap(); + publish_range(&v1, 10); + let s1 = slot(sampler3.as_ptr() as u64 + SAMPLER_SLOT as u64).unwrap(); + publish_range(&s1, 10); + let v250 = slot(view260.as_ptr() as u64 + (250 * SLOT) as u64).unwrap(); + publish_range(&v250, 20); + HEAPS.lock().unwrap().clear(); + *GLOBAL_SAMPLER.lock().unwrap() = None; + *GLOBAL.lock().unwrap() = None; + } + assert!(LOCKS_FREE.load(Ordering::Relaxed), "descriptor copies must run without heap locks"); + assert_eq!( + *CALLS.lock().unwrap(), + vec![ + (6, 0x10_0000 + 66 * 32, 0x30_0000 + 2 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + (2, 0x20_0000 + 2 * 16, 0x40_0000 + 16, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER.0), + (12, 0x10_0000 + (72 + 500) * 32, 0x50_0000 + 500 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + (8, 0x10_0000 + 584 * 32, 0x50_0000 + 512 * 32, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV.0), + ] + ); + } + + #[test] + fn publish_calls_run_unlocked_and_hold_generation_and_ranges() { + const CHILD: &str = "XCL_TEST_SINGLE_PUBLISH_LEASE_CHILD"; + if std::env::var_os(CHILD).is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::console_heap::tests::publish_calls_run_unlocked_and_hold_generation_and_ranges", "--nocapture"]) + .env(CHILD, "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + return; + } + use std::ffi::c_void; + use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier, OnceLock}; + + static GATE: OnceLock<(Arc, Arc)> = OnceLock::new(); + static LOCKS_FREE: AtomicBool = AtomicBool::new(false); + static CALLS: AtomicUsize = AtomicUsize::new(0); + #[repr(C)] + struct Object { vt: *const usize, refs: AtomicU32 } + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + (*this.cast::()).refs.fetch_add(1, Ordering::Relaxed) + 1 + } + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + (*this.cast::()).refs.fetch_sub(1, Ordering::Relaxed) - 1 + } + unsafe extern "system" fn copy_simple(_this: *mut c_void, n: u32, dst: D3D12_CPU_DESCRIPTOR_HANDLE, src: D3D12_CPU_DESCRIPTOR_HANDLE, ty: D3D12_DESCRIPTOR_HEAP_TYPE) { + LOCKS_FREE.store(GLOBAL.try_lock().is_ok() && GLOBAL_SAMPLER.try_lock().is_ok() && HEAPS.try_lock().is_ok(), Ordering::Relaxed); + let call = CALLS.fetch_add(1, Ordering::Relaxed); + assert_eq!( + (n, dst.ptr, src.ptr, ty), + if call == 0 { + (1, 0x10_0000 + 64 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + } else { + (8, 0x10_0000 + 80 * 32, 0x30_0000, D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + }, + ); + let (entered, leave) = GATE.get().unwrap(); + entered.wait(); + leave.wait(); + } + let entered = Arc::new(Barrier::new(2)); + let leave = Arc::new(Barrier::new(2)); + GATE.set((entered.clone(), leave.clone())).ok(); + let mut vt = [0usize; 25]; + vt[1] = add_ref as usize; + vt[2] = release as usize; + vt[24] = copy_simple as usize; + let mut device = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut global_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let mut source_heap = Object { vt: vt.as_ptr(), refs: AtomicU32::new(1) }; + let shadow = vec![0u8; (4 * SLOT) as usize]; + unsafe { + *GLOBAL.lock().unwrap() = Some(Global { + dev: ID3D12Device::from_raw((&mut device as *mut Object).cast()), + heap: ID3D12DescriptorHeap::from_raw((&mut global_heap as *mut Object).cast()), + cpu: 0x10_0000, gpu: 0x18_0000, inc: 32, cap: 4096, next: 72, + free: Vec::new(), leases: PublishLeases::default(), + }); + HEAPS.lock().unwrap().push(Heap { + generation: 77, obj: &mut source_heap as *mut Object as usize, shadow: shadow.as_ptr() as usize, + n: 4, pc_cpu: 0x30_0000, pc_gpu: 0, inc: 32, sampler: false, pages: vec![64], visible: true, memory: Memory::Uma, + }); + let stale = slot(shadow.as_ptr() as u64).unwrap(); + let worker = std::thread::spawn(move || publish(&stale, false)); + entered.wait(); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 2, "source heap must stay owned during the device call"); + let Taken(old) = take(&mut source_heap as *mut Object as usize).unwrap(); + release_global(old.pages[0], page_descriptors(old.n, 0)); + assert_ne!(reserve_global(8), Some(64), "an in-flight destination range must not be recycled"); + HEAPS.lock().unwrap().push(Heap { generation: 78, pages: vec![80], ..old }); + leave.wait(); + worker.join().unwrap(); + assert!(LOCKS_FREE.load(Ordering::Relaxed)); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 1); + assert_eq!(reserve_global(8), Some(64), "deferred range must return when publication finishes"); + publish(&stale, false); + assert_eq!(CALLS.load(Ordering::Relaxed), 1, "a stale generation must not publish into its replacement"); + + GLOBAL.lock().unwrap().as_mut().unwrap().next = 88; + let stale_range = slot(shadow.as_ptr() as u64).unwrap(); + let worker = std::thread::spawn(move || publish_range(&stale_range, 4)); + entered.wait(); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 2, "range source heap must stay owned during the device call"); + let Taken(old) = take(&mut source_heap as *mut Object as usize).unwrap(); + release_global(old.pages[0], page_descriptors(old.n, 0)); + assert_ne!(reserve_global(8), Some(80), "an in-flight range destination must not be recycled"); + HEAPS.lock().unwrap().push(Heap { generation: 79, pages: vec![96], ..old }); + leave.wait(); + worker.join().unwrap(); + assert_eq!(source_heap.refs.load(Ordering::Relaxed), 1); + assert_eq!(reserve_global(8), Some(80), "deferred range must return when range publication finishes"); + publish_range(&stale_range, 4); + assert_eq!(CALLS.load(Ordering::Relaxed), 2, "a stale range generation must not publish into its replacement"); + HEAPS.lock().unwrap().clear(); + *GLOBAL.lock().unwrap() = None; + } + assert_eq!((device.refs.load(Ordering::Relaxed), global_heap.refs.load(Ordering::Relaxed), source_heap.refs.load(Ordering::Relaxed)), (0, 0, 1)); + } } diff --git a/crates/xcl/src/hle/d3d12x/console_list.rs b/crates/xcl/src/hle/d3d12x/console_list.rs index 7726419583..75a597eee0 100644 --- a/crates/xcl/src/hle/d3d12x/console_list.rs +++ b/crates/xcl/src/hle/d3d12x/console_list.rs @@ -435,7 +435,18 @@ unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, ps } with_list(obj, |st| new_chunk(obj, st)); let f: unsafe extern "system" fn(usize, *mut c_void, *mut c_void) -> HRESULT = std::mem::transmute(pc_vtable_call(pc, 10)); - f(pc, allocator, pc_pso(pso)) + // The adopted physical slot reaches real::cl_reset, which resolves and records the initial + // generation. Do not clear that capture again in this outer console wrapper. + forward_reset(pc, allocator, pso, |pc, allocator, pso| f(pc, allocator, pso)) +} + +unsafe fn forward_reset( + pc: usize, + allocator: *mut c_void, + pso: *mut c_void, + call: impl FnOnce(usize, *mut c_void, *mut c_void) -> HRESULT, +) -> HRESULT { + call(pc, allocator, pc_pso(pso)) } unsafe extern "system" fn cl_dispatch(this: *mut c_void, x: u32, y: u32, z: u32) { @@ -714,8 +725,10 @@ unsafe fn ensure_dispatch_heaps_with(list: &ID3D12GraphicsCommandList, bound: &m true } -unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Vec, has_sampler: &mut bool) { - if bound.len() >= 2 { return; } +unsafe fn ensure_dispatch_heaps( + list: &ID3D12GraphicsCommandList, bound: &mut Vec, has_sampler: &mut bool, shared_view_bound: bool, +) -> bool { + if bound.len() >= 2 { return shared_view_bound; } let mut dev: Option = None; let _ = list.GetDevice(&mut dev); let sampler = super::console_heap::global_sampler_heap().or_else(|| { @@ -727,7 +740,9 @@ unsafe fn ensure_dispatch_heaps(list: &ID3D12GraphicsCommandList, bound: &mut Ve Some(dev_raw) => (heap_on_device(view, dev_raw), heap_on_device(sampler, dev_raw)), None => (view, sampler), }; + let view_raw = view.as_ref().map(|h| h.as_raw() as usize); ensure_dispatch_heaps_with(list, bound, has_sampler, view, sampler); + shared_view_bound || view_raw.is_some_and(|view| bound.iter().any(|heap| heap.as_raw() as usize == view)) } /// Turn the recorded console commands into commands on the PC list and close it. @@ -748,7 +763,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } // the whole recording is replayed into the PC list here: its transitions of textures kept // in step are these - super::title_textures::list_reset(st.pc); + super::list_x::clear_texture_transitions(st.pc); super::dred::reset(st.pc as *mut c_void); let windows = super::real::uma_window_vas(); let va = |p: usize| super::real::uma_va_of(p).unwrap_or(uma_va); @@ -759,6 +774,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // tracked PC descriptor heaps bound on `list` (for `heap_windows` + `SAMPLER_HEAP_DIRECTLY_INDEXED`) let mut bound_heaps: Vec = Vec::new(); let mut has_sampler_heap = false; + let track_shared_view = super::vram::srv_tracking_enabled(); + let mut shared_view_bound = false; + let mut recording_uses_shared_view = false; let chunks: Vec> = st.chunks.iter().map(|(c, used)| c[..*used].chunks(4).map(|b| u32::from_le_bytes(b.try_into().unwrap())).collect()).collect(); 'chunks: for words in &chunks { let mut at = 0usize; @@ -786,11 +804,13 @@ pub unsafe fn close(obj: *mut c_void) -> Result { list.SetDescriptorHeaps(&[]); bound_heaps.clear(); has_sampler_heap = false; + shared_view_bound = false; } else { - let heaps = super::list_x::pc_heaps(n as u32, named.as_ptr()); + let (heaps, uses_shared_view) = super::list_x::pc_heaps_with_shared(n as u32, named.as_ptr()); list.SetDescriptorHeaps(&heaps); bound_heaps = heaps.into_iter().flatten().collect(); has_sampler_heap = bound_heaps.iter().any(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER); + shared_view_bound = uses_shared_view; } at += 2 + 2 * n; } else if w0 == TRANSITIONS_MARKER { @@ -805,7 +825,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // each barrier: type | flags, resource, subresource | before, after let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = b.chunks_exact(4).filter(|c| c[0] as u32 == 0).map(|c| (c[1] as usize, c[2] as u32, D3D12_RESOURCE_STATES(c[3] as u32 as i32))).collect(); - super::title_textures::note_transitions(st.pc, &t); + super::list_x::note_texture_transitions(st.pc, &t); } list.ResourceBarrier(std::slice::from_raw_parts(b.as_ptr() as *const D3D12_RESOURCE_BARRIER, n)); } @@ -881,7 +901,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { // a pipeline still being built in the background is waited for; if // the background translation failed, skip instead of binding XCL's // ABI root signature onto the stand-in - let real = super::pso_async::resolve_wait((*p).pc); + let real = super::list_x::resolve_and_record_pipeline_wait(st.pc, (*p).pc); if !super::real::is_translated_compute(real) { out.skipped_dispatches += 1; continue; @@ -903,7 +923,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { Some(r) => list.SetComputeRootSignature(r), None => list.SetComputeRootSignature(rs.as_ref().ok_or("no XCL ABI root signature")?), } - ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap); + shared_view_bound = ensure_dispatch_heaps(&list, &mut bound_heaps, &mut has_sampler_heap, shared_view_bound); list.SetComputeRootUnorderedAccessView(0, va(io_at)); list.SetComputeRootUnorderedAccessView(1, va(res_at)); for k in 0..4 { @@ -913,6 +933,7 @@ pub unsafe fn close(obj: *mut c_void) -> Result { let pc = ID3D12PipelineState::from_raw_borrowed(&raw).ok_or("PSO")?; list.SetPipelineState(pc); super::real::dispatch_chain::dispatch(&list, real, st.allocator, [x, y, z])?; + recording_uses_shared_view |= track_shared_view && shared_view_bound; out.dispatches += 1; } _ => out.skipped_dispatches += 1, @@ -958,6 +979,9 @@ pub unsafe fn close(obj: *mut c_void) -> Result { } } drop(guard); + if recording_uses_shared_view { + super::list_x::note_shared_view_heap_use(list.as_raw()); + } if std::env::var_os("XCL_CONSOLE_LISTS_LOG").is_some() { crate::xlog_info!( "console list: {} dispatches, {} skipped (PSO without a translation), {} barriers, {} clears, {} copies, {} skipped records", @@ -984,6 +1008,18 @@ fn bytemuck_u32(v: &[u32]) -> &[u8] { mod tests { use super::*; + #[test] + fn console_reset_preserves_the_physical_initial_generation_capture() { + let mut pins = vec![1u64]; + let hr = unsafe { forward_reset(0xC1, std::ptr::null_mut(), std::ptr::null_mut(), |_, _, _| { + pins.clear(); + pins.push(2); + S_OK + }) }; + assert_eq!(hr, S_OK); + assert_eq!(pins, [2], "the outer wrapper must not clear the physical Reset hook's new pin"); + } + #[test] fn layout_packs_parameters_in_order() { // RTS0 v2: consts b0 x19 | UAV u0 | UAV u1 | SRV t0 diff --git a/crates/xcl/src/hle/d3d12x/cpu_writes.rs b/crates/xcl/src/hle/d3d12x/cpu_writes.rs index 0b20bfbd6a..1d8f484f7d 100644 --- a/crates/xcl/src/hle/d3d12x/cpu_writes.rs +++ b/crates/xcl/src/hle/d3d12x/cpu_writes.rs @@ -34,6 +34,7 @@ struct Job { fence: ID3D12Fence, value: u64, writes: Vec, + done: Option>, } // SAFETY: the fence is a free-threaded COM object; the writes are plain data @@ -49,6 +50,16 @@ unsafe impl Send for QueueFence {} static FENCES: Mutex>> = Mutex::new(None); +/// Forget a retired queue's cached fence before its address can be reused. Submitted jobs own +/// fence clones, so extracting this entry cannot let their writes run early. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = { + let mut fences = FENCES.lock().unwrap(); + fences.as_mut().and_then(|fences| fences.remove(&id.raw())) + }; + drop(gone); +} + /// how long the worker waits for one submission before writing anyway (a removed device, a /// queue that never gets there) const WAIT_MS: u32 = 10_000; @@ -79,6 +90,9 @@ fn worker() -> &'static Mutex> { } } } + if let Some(done) = job.done { + let _ = done.send(()); + } } }); if let Err(e) = spawned { @@ -156,12 +170,34 @@ pub(super) fn writable(va: usize, bytes: usize) -> bool { && m.BaseAddress as usize + m.RegionSize >= va + bytes } -/// `writes` of lists just submitted to `queue`: done when the GPU has finished them. -pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { +/// Receipt published only after the worker has applied every deferred store in a submission. +pub(super) struct Completion(mpsc::Receiver<()>); + +impl Completion { + pub(super) fn wait(self) -> bool { + let _stall = crate::stall::span(crate::stall::StallKind::MemorySynchronization); + self.0.recv().is_ok() + } +} + +#[cfg(test)] +pub(super) fn completion_pair_for_test() -> (Completion, mpsc::Sender<()>) { + let (tx, rx) = mpsc::channel(); + (Completion(rx), tx) +} + +/// Schedule `writes` from lists just submitted to `queue` after the GPU has finished them. +unsafe fn schedule(queue: *mut c_void, writes: Vec, completion: bool) -> Option { if writes.is_empty() || queue.is_null() { - return; + return None; } - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return }; + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return None }; + let (done, receipt) = if completion { + let (tx, rx) = mpsc::channel(); + (Some(tx), Some(Completion(rx))) + } else { + (None, None) + }; let job = { let mut g = FENCES.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); @@ -170,22 +206,31 @@ pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { std::collections::hash_map::Entry::Vacant(v) => { let mut dev: Option = None; if q.GetDevice(&mut dev).is_err() { - return; + return None; } - let Some(dev) = dev else { return }; - let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return }; + let Some(dev) = dev else { return None }; + let Ok(fence) = dev.CreateFence::(0, D3D12_FENCE_FLAG_NONE) else { return None }; v.insert(QueueFence { fence, value: 0 }) } }; entry.value += 1; - if q.Signal(&entry.fence, entry.value).is_err() { - return; + if super::real::native_queue_signal(q, &entry.fence, entry.value).is_err() { + return None; } - Job { fence: entry.fence.clone(), value: entry.value, writes } + Job { fence: entry.fence.clone(), value: entry.value, writes, done } }; static FIRST: std::sync::Once = std::sync::Once::new(); FIRST.call_once(|| crate::xlog_info!("D3D12.X: bottom-of-pipe writes outside unified memory are done by the CPU after the GPU ({} in the first submission)", job.writes.len())); - let _ = worker().lock().unwrap().send(job); + worker().lock().unwrap().send(job).ok()?; + receipt +} + +pub(super) unsafe fn after(queue: *mut c_void, writes: Vec) { + let _ = schedule(queue, writes, false); +} + +pub(super) unsafe fn after_with_completion(queue: *mut c_void, writes: Vec) -> Option { + schedule(queue, writes, true) } #[cfg(test)] @@ -209,12 +254,8 @@ mod tests { let cell = Box::new([0u32; 2]); let va = cell.as_ptr() as usize; assert!(writable(va, 8)); - after(q.as_raw(), vec![Write::Immediate(va, vec![7, 9])]); - let t = std::time::Instant::now(); - while (*(va as *const AtomicU32)).load(Ordering::Acquire) != 7 { - assert!(t.elapsed().as_secs() < 5, "never written"); - std::thread::yield_now(); - } + let completion = after_with_completion(q.as_raw(), vec![Write::Immediate(va, vec![7, 9])]).expect("scheduled CPU write"); + assert!(completion.wait()); assert_eq!(*cell, [7, 9]); } } diff --git a/crates/xcl/src/hle/d3d12x/device_x.rs b/crates/xcl/src/hle/d3d12x/device_x.rs index 57c30e0ffe..511ae0ad4a 100644 --- a/crates/xcl/src/hle/d3d12x/device_x.rs +++ b/crates/xcl/src/hle/d3d12x/device_x.rs @@ -78,6 +78,7 @@ pub(super) unsafe extern "system" fn create_command_queue_x(this: *mut c_void, d let d = if desc.is_null() { [0; 4] } else { pc_queue_desc(desc.read_unaligned()) }; let hr = real::dev_create_command_queue(this, d.as_ptr() as usize, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::present::track_queue(*ppv as usize); super::list_x::on_queue_create(*ppv as usize, this as usize, D3D12_COMMAND_LIST_TYPE(d[0] as i32)); } hr @@ -88,6 +89,14 @@ pub(super) unsafe extern "system" fn create_command_allocator_x(this: *mut c_voi real::dev_create_command_allocator(this, pc_list_type(ty) as usize, riid, ppv) } +fn active_list_allocator(alloc: usize) -> usize { + active_list_allocator_with(alloc, super::alloc_pool::current) +} + +fn active_list_allocator_with(alloc: usize, current: impl FnOnce(usize) -> usize) -> usize { + current(alloc) +} + unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let dma = !riid.is_null() && guid_bytes(&*riid) == guid_bytes(&IID_XBOX_DMA_COMMAND_LIST); let riid = if dma { &IID_GRAPHICS_COMMAND_LIST as *const GUID } else { riid }; @@ -95,10 +104,12 @@ unsafe fn create_list(this: *mut c_void, node: u32, ty: u32, alloc: usize, pso: let hr = if super::console_list::enabled() { real::dev_create_command_list_x(this, node, ty, alloc, pso, riid, ppv) } else { - let resolved_pso = super::pso_async::resolve_for_bind(pso); - let hr = real::dev_create_command_list(this, node, ty, alloc, resolved_pso, riid, ppv); + let (resolved_pso, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); + let pc_alloc = active_list_allocator(alloc); + let hr = real::dev_create_command_list(this, node, ty, pc_alloc, resolved_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { - super::list_x::on_create(*ppv, alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::on_create_with_backing(*ppv, alloc, pc_alloc, pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::record_native_generation(*ppv as usize, generation); super::dred::reset(*ppv); if pso != 0 { super::dred::mark_pipeline(*ppv, pso, resolved_pso); @@ -1065,19 +1076,78 @@ pub(super) unsafe extern "system" fn get_custom_heap_properties_x(a: *mut c_void ret } +const MAX_ALIAS_LOGS: u64 = 16; +const MAX_ALIAS_TRACKED: usize = 16_384; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct PlacedDescSummary { + dim: u32, + width: u64, + height: u32, + format: u32, + flags: u32, +} + +impl PlacedDescSummary { + fn from_desc(x: &[u8; 0x38]) -> Self { + let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); + Self { + dim: u(0), + width: u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), + height: u(0x18), + format: u(0x20), + flags: u(0x30), + } + } +} + +impl std::fmt::Display for PlacedDescSummary { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "dimension {} {}x{} format {} flags {:#x}", self.dim, self.width, self.height, self.format, self.flags) + } +} + +fn record_alias_in( + seen: &mut Option>, + logged: &AtomicU64, + va: usize, + cur: PlacedDescSummary, + max_tracked: usize, +) -> Option { + if logged.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS { + *seen = None; + return None; + } + let m = seen.get_or_insert_with(std::collections::HashMap::new); + if let Some(slot) = m.get_mut(&va) { + let prev = std::mem::replace(slot, cur); + let prev_count = logged.fetch_add(1, Ordering::Relaxed); + if prev_count + 1 >= MAX_ALIAS_LOGS { + *seen = None; + } + return (prev_count < MAX_ALIAS_LOGS).then_some(prev); + } + if m.len() < max_tracked { + m.insert(va, cur); + } + None +} + /// Resources the title placed at an address an earlier one was placed at: on the console they /// share that memory (aliasing – transient render targets reuse it). Logged (first 16). fn note_alias(va: usize, x: &[u8; 0x38]) { - static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); + static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(None); static N: AtomicU64 = AtomicU64::new(0); - let u = |o: usize| u32::from_le_bytes(x[o..o + 4].try_into().unwrap()); - let what = format!("dimension {} {}x{} format {} flags {:#x}", u(0), u64::from_le_bytes(x[0x10..0x18].try_into().unwrap()), u(0x18), u(0x20), u(0x30)); - let mut g = SEEN.lock().unwrap(); - let m = g.get_or_insert_with(std::collections::HashMap::new); - if let Some(prev) = m.insert(va, what.clone()) { - if N.fetch_add(1, Ordering::Relaxed) < 16 { - crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({what}) – aliases an earlier resource there ({prev})"); - } + if N.load(Ordering::Relaxed) >= MAX_ALIAS_LOGS { + return; + } + let cur = PlacedDescSummary::from_desc(x); + let prev = { + let mut g = SEEN.lock().unwrap(); + record_alias_in(&mut g, &N, va, cur, MAX_ALIAS_TRACKED) + }; + if let Some(prev) = prev { + crate::xlog_info!("D3D12.X: CreatePlacedResourceX at {va:#x} ({cur}) – aliases an earlier resource there ({prev})"); } } @@ -1127,8 +1197,10 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void, if super::vram::gpu_owned(flags) { if let Some(hr) = super::vram::place(this, va as usize, &pc, state, clear, console_bytes, riid, ppv) { if hr >= 0 && !(*ppv).is_null() { - if let Some(bytes) = console_bytes { - super::title_textures::retire_overlapping(va as usize, bytes as usize); + if super::title_textures::register_gpu_owned(this, *ppv, va as usize, &x, D3D12_RESOURCE_STATES(state as i32)).is_err() { + if let Some(bytes) = console_bytes { + super::title_textures::retire_overlapping(va as usize, bytes as usize); + } } real::note_title_address(*ppv as usize, va as usize); } @@ -1259,6 +1331,10 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { super::bind::note_signature_dispatches(*ppv as usize, list.iter().any(|a| a[0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32)); + let stride = u32::from_le_bytes(pc[..4].try_into().unwrap()); + let dispatch_only = list.len() == 1 && list[0][0] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH.0 as u32 + && stride >= 12 && stride % 4 == 0; + super::bind::note_dispatch_only_signature(*ppv as usize, dispatch_only.then_some(stride)); } hr } @@ -1267,6 +1343,14 @@ pub(super) unsafe extern "system" fn create_command_signature_x(this: *mut c_voi mod tests { use super::*; + #[test] + fn new_command_lists_use_the_allocator_pools_active_backing() { + assert_eq!(active_list_allocator_with(0x1000, |alloc| { + assert_eq!(alloc, 0x1000); + 0x2000 + }), 0x2000); + } + #[test] fn console_types_and_descs_become_pc_ones() { assert_eq!(pc_list_type(XBOX_TYPE_DMA), D3D12_COMMAND_LIST_TYPE_COPY.0 as u32); @@ -1722,4 +1806,64 @@ mod tests { m.remove(&((luid.LowPart, luid.HighPart), 24)); } } + + fn placed_desc(dim: u32, width: u64, height: u32, format: u32, flags: u32) -> [u8; 0x38] { + let mut x = [0u8; 0x38]; + x[0..4].copy_from_slice(&dim.to_le_bytes()); + x[0x10..0x18].copy_from_slice(&width.to_le_bytes()); + x[0x18..0x1C].copy_from_slice(&height.to_le_bytes()); + x[0x20..0x24].copy_from_slice(&format.to_le_bytes()); + x[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + x + } + + #[test] + fn note_alias_logs_first_16_and_drops_table_after_cap() { + let first = PlacedDescSummary::from_desc(&placed_desc(3, 1920, 1080, 28, 0x5)); + assert_eq!(first.to_string(), "dimension 3 1920x1080 format 28 flags 0x5"); + + let mut seen = None; + let logged = AtomicU64::new(0); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, first, MAX_ALIAS_TRACKED), None); + let mut expected_prev = first; + for i in 1..=MAX_ALIAS_LOGS { + let next = PlacedDescSummary::from_desc(&placed_desc(3, 1920 + i, 1080, 28, i as u32)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, next, MAX_ALIAS_TRACKED), Some(expected_prev), "alias #{i}"); + expected_prev = next; + if i < MAX_ALIAS_LOGS { + assert!(seen.is_some(), "table stays active before cap (alias #{i})"); + } + } + assert!(seen.is_none(), "16th alias must drop the tracking table"); + let after = PlacedDescSummary::from_desc(&placed_desc(1, 4096, 1, 0, 0)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x1000, after, MAX_ALIAS_TRACKED), None); + assert_eq!(record_alias_in(&mut seen, &logged, 0x2000, after, MAX_ALIAS_TRACKED), None); + assert!(seen.is_none(), "calls after cap must not reallocate the tracking table"); + } + + #[test] + fn note_alias_bounds_tracked_entries_without_aliases() { + let mut seen = None; + let logged = AtomicU64::new(0); + let max_tracked = 8; + let d0 = PlacedDescSummary::from_desc(&placed_desc(3, 64, 64, 28, 1)); + for i in 0..(max_tracked + 5) { + assert_eq!(record_alias_in(&mut seen, &logged, 0x10000 + i * 0x1000, d0, max_tracked), None); + } + assert_eq!(seen.as_ref().unwrap().len(), max_tracked, "tracked VA count must stay bounded"); + let d1 = PlacedDescSummary::from_desc(&placed_desc(3, 128, 128, 28, 2)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x10000, d1, max_tracked), Some(d0), "aliasing a tracked entry still fires"); + assert_eq!(logged.load(Ordering::Relaxed), 1); + } + + #[test] + fn note_alias_short_circuits_when_cap_already_reached() { + let d0 = PlacedDescSummary::from_desc(&placed_desc(3, 32, 32, 28, 0)); + let mut seen = Some(std::collections::HashMap::from([(0x5000usize, d0)])); + let logged = AtomicU64::new(MAX_ALIAS_LOGS); + let d1 = PlacedDescSummary::from_desc(&placed_desc(3, 64, 64, 28, 4)); + assert_eq!(record_alias_in(&mut seen, &logged, 0x5000, d1, MAX_ALIAS_TRACKED), None); + assert!(seen.is_none(), "residual map must be freed once cap is reached"); + assert_eq!(logged.load(Ordering::Relaxed), MAX_ALIAS_LOGS); + } } diff --git a/crates/xcl/src/hle/d3d12x/fence_x.rs b/crates/xcl/src/hle/d3d12x/fence_x.rs index f67967345e..babd5744fb 100644 --- a/crates/xcl/src/hle/d3d12x/fence_x.rs +++ b/crates/xcl/src/hle/d3d12x/fence_x.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Foundation::HANDLE; use windows::Win32::Graphics::Direct3D12::ID3D12Fence; @@ -16,17 +16,137 @@ use windows_sys::Win32::System::Threading as th; #[repr(C, align(64))] struct Cell(AtomicU64); +/// Heap-isolated cell plus per-fence refresh lock (`true` = live, `false` = retired). +/// Keeping `Box` off the lock's cache line avoids false-sharing `monitorx`/`mwaitx` wakes. +struct CellMirror { + cell: Box, + refresh_lock: Mutex, +} + #[derive(Default)] struct Fence { - cell: Option<&'static Cell>, + cell: Option>, /// the highest value a queue was told to signal signalled: u64, /// the highest value a queue was told to wait for waited: u64, } -/// (fences are never freed: XCL holds a reference to each) -static FENCES: Mutex>> = Mutex::new(None); +#[derive(Default)] +struct State { + map: HashMap, + cells: Vec<(usize, Arc)>, +} + +/// (fences are never freed in production: XCL holds a reference to each) +struct FenceTable { + /// Keeps test-owned raw fence pointers alive across diagnostic COM calls. + summary_lifetime: Mutex<()>, + inner: Mutex, +} + +impl FenceTable { + fn new() -> Self { + Self { summary_lifetime: Mutex::new(()), inner: Mutex::new(State::default()) } + } + + fn refresh_one(fence: usize, mirror: &CellMirror) { + let live = mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()); + if !*live { + return; + } + if let Some(v) = unsafe { borrowed(fence, |f| f.GetCompletedValue()) } { + if super::title_textures::complete_fence_downloads(fence, v) { + mirror.cell.0.store(v, Ordering::Release); + } + } + } + + fn refresh(&self) { + let cells = self.inner.lock().unwrap_or_else(|e| e.into_inner()).cells.clone(); + for (p, mirror) in cells { + Self::refresh_one(p, &mirror); + } + } + + fn note_queue_signal(&self, fence: usize, value: u64) -> bool { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.signalled = f.signalled.max(value); + f.cell.is_some() + } + + fn note_queue_wait(&self, fence: usize, value: u64) { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let f = g.map.entry(fence).or_default(); + f.waited = f.waited.max(value); + } + + fn note_cpu_signal(&self, fence: usize) { + let mirror = self.inner.lock().unwrap_or_else(|e| e.into_inner()).map.get(&fence).and_then(|f| f.cell.clone()); + if let Some(mirror) = mirror { + Self::refresh_one(fence, &mirror); + } + } + + fn pending_summary(&self) -> String { + // Test teardown keeps this order: summary lifetime -> table -> per-cell refresh lock. + let _lifetime = self.summary_lifetime.lock().unwrap_or_else(|e| e.into_inner()); + let snap: Vec<(usize, u64, u64, bool)> = { + let g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.map.iter().map(|(&p, f)| (p, f.signalled, f.waited, f.cell.is_some())).collect() + }; + let mut parts = Vec::new(); + for (p, signalled, waited, has_cell) in snap { + let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); + if done < signalled || done < waited { + parts.push(format!("{p:#x}(done={done:#x}/sig={signalled:#x}/wait={waited:#x},cell={has_cell})")); + } + } + if parts.is_empty() { "none".into() } else { parts.join(", ") } + } + + fn completed_value_address_with(&self, this: *mut c_void, arm_fn: impl FnOnce(usize, u64)) -> *const u64 { + let key = this as usize; + let (mirror, pending) = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.map.get(&key).and_then(|f| f.cell.as_ref()) { + return m.cell.0.as_ptr(); + } + let m = Arc::new(CellMirror { cell: Box::new(Cell(AtomicU64::new(0))), refresh_lock: Mutex::new(true) }); + let pending = { + let f = g.map.entry(key).or_default(); + f.cell = Some(Arc::clone(&m)); + f.signalled + }; + g.cells.push((key, Arc::clone(&m))); + (m, pending) + }; + if pending > 0 { + arm_fn(key, pending); + } + Self::refresh_one(key, &mirror); + mirror.cell.0.as_ptr() + } + + #[cfg(test)] + fn forget_fence(&self, fence: usize) { + let _lifetime = self.summary_lifetime.lock().unwrap_or_else(|e| e.into_inner()); + let removed = { + let mut g = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + g.cells.retain(|(p, _)| *p != fence); + g.map.remove(&fence).and_then(|f| f.cell) + }; + if let Some(mirror) = removed { + *mirror.refresh_lock.lock().unwrap_or_else(|e| e.into_inner()) = false; + } + } +} + +fn table() -> &'static FenceTable { + static T: OnceLock = OnceLock::new(); + T.get_or_init(FenceTable::new) +} /// the event a completion sets (auto-reset); the first use starts the thread that follows it fn event() -> usize { @@ -35,7 +155,8 @@ fn event() -> usize { let e = th::CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) as usize; let spawned = std::thread::Builder::new().name("xcl-fences".into()).spawn(move || loop { th::WaitForSingleObject(e as _, th::INFINITE); - refresh(); + super::title_textures::poll_fence_downloads(); + table().refresh(); }); if let Err(err) = spawned { crate::xlog_error!("D3D12.X: no thread for the fences' completed values: {err}"); @@ -44,22 +165,15 @@ fn event() -> usize { }) } +pub(super) fn wake_event() -> HANDLE { + HANDLE(event() as *mut c_void) +} + unsafe fn borrowed(fence: usize, f: impl FnOnce(&ID3D12Fence) -> R) -> Option { let p = fence as *mut c_void; ID3D12Fence::from_raw_borrowed(&p).map(f) } -fn refresh() { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - for (&p, f) in g.iter().flatten() { - if let Some(c) = f.cell { - if let Some(v) = unsafe { borrowed(p, |f| f.GetCompletedValue()) } { - c.0.store(v, Ordering::Release); - } - } - } -} - unsafe fn arm(fence: usize, value: u64) { if let Some(Err(e)) = borrowed(fence, |f| f.SetEventOnCompletion(value, HANDLE(event() as *mut c_void))) { crate::xlog_warn!("D3D12.X: fence {fence:#x}: SetEventOnCompletion({value:#x}): {e}"); @@ -68,76 +182,35 @@ unsafe fn arm(fence: usize, value: u64) { /// A queue was told to signal `fence` (one of the title's) with `value`. pub(super) unsafe fn note_queue_signal(fence: usize, value: u64) { - let cell = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.signalled = f.signalled.max(value); - f.cell.is_some() - }; - if cell { + if table().note_queue_signal(fence, value) { arm(fence, value); } } /// A queue was told to wait for `fence` (one of the title's) to reach `value`. pub(super) fn note_queue_wait(fence: usize, value: u64) { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(fence).or_default(); - f.waited = f.waited.max(value); + table().note_queue_wait(fence, value); } /// The CPU signalled `fence`. pub(super) fn note_cpu_signal(fence: usize) { - let known = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.get(&fence).is_some_and(|f| f.cell.is_some())); - if known { - refresh(); - } + table().note_cpu_signal(fence); } /// Diagnostic summary of title fences whose completed value lags their signalled or waited value. pub(super) fn pending_summary() -> String { - let g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let mut parts = Vec::new(); - for (&p, f) in g.iter().flatten() { - let done = unsafe { borrowed(p, |f| f.GetCompletedValue()) }.unwrap_or(0); - if done < f.signalled || done < f.waited { - parts.push(format!("{p:#x}(done={done:#x}/sig={:#x}/wait={:#x},cell={})", f.signalled, f.waited, f.cell.is_some())); - } - } - if parts.is_empty() { - "none".into() - } else { - parts.join(", ") - } + table().pending_summary() } /// fence #12: the address of its completed value pub(super) unsafe extern "system" fn completed_value_address(this: *mut c_void) -> *const u64 { - let (cell, pending) = { - let mut g = FENCES.lock().unwrap_or_else(|e| e.into_inner()); - let f = g.get_or_insert_with(HashMap::new).entry(this as usize).or_default(); - match f.cell { - Some(c) => return c.0.as_ptr(), - None => { - let c: &'static Cell = Box::leak(Box::new(Cell(AtomicU64::new(0)))); - f.cell = Some(c); - (c, f.signalled) - } - } - }; - if pending > 0 { - arm(this as usize, pending); - } - refresh(); - cell.0.as_ptr() + table().completed_value_address_with(this, |f, v| arm(f, v)) } /// Remove a synthetic test fence from `FENCES` before it is dropped. #[cfg(test)] pub(super) fn forget_fence_for_test(fence: usize) { - if let Some(m) = FENCES.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - m.remove(&fence); - } + table().forget_fence(fence); } #[cfg(test)] @@ -183,4 +256,174 @@ mod tests { std::mem::forget(fence); // the map keeps its address } } + + struct Gate { + entered: Arc, + release: Arc, + } + + #[repr(C)] + struct MockFence { + vtable: *const usize, + val: AtomicU64, + calls: std::sync::atomic::AtomicUsize, + gate: Mutex>, + } + unsafe impl Send for MockFence {} + unsafe impl Sync for MockFence {} + + impl MockFence { + fn new(val: u64) -> Box { + use std::mem::{offset_of, size_of}; + unsafe extern "system" fn get_val(this: *mut c_void) -> u64 { + let f = &*this.cast::(); + f.calls.fetch_add(1, Ordering::AcqRel); + let v = f.val.load(Ordering::Acquire); + if let Some(g) = f.gate.lock().unwrap().take() { + g.entered.wait(); + g.release.wait(); + } + v + } + extern "system" fn unexpected() { std::process::abort(); } + const SLOT: usize = size_of::(); + const LEN: usize = size_of::() / SLOT; + static VT: OnceLock<[usize; LEN]> = OnceLock::new(); + let vt = VT.get_or_init(|| { + let mut t = [unexpected as usize; LEN]; + t[offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / SLOT] = get_val as usize; + t + }); + Box::new(Self { vtable: vt.as_ptr(), val: AtomicU64::new(val), calls: Default::default(), gate: Mutex::new(None) }) + } + fn as_ptr(&self) -> *mut c_void { std::ptr::from_ref(self) as *mut c_void } + fn arm_gate(&self) -> (Arc, Arc) { + let (e, r) = (Arc::new(std::sync::Barrier::new(2)), Arc::new(std::sync::Barrier::new(2))); + *self.gate.lock().unwrap() = Some(Gate { entered: e.clone(), release: r.clone() }); + (e, r) + } + } + + #[test] + fn refresh_and_pending_summary_do_not_block_concurrent_queue_and_cpu_signals() { + let table = Arc::new(FenceTable::new()); + let (a, b) = (MockFence::new(1), MockFence::new(2)); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _cell_a = table.completed_value_address_with(pa, |_, _| {}); + let cell_b = table.completed_value_address_with(pb, |_, _| {}); + assert!(table.note_queue_signal(pa as usize, 10)); + + // 1. refresh() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + b.val.store(4, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 4)); + table.note_queue_wait(pb as usize, 4); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 4); + release.wait(); + h1.join().unwrap(); + + // 2. pending_summary() must not hold global lock across GetCompletedValue(). + let (entered, release) = a.arm_gate(); + let t2 = Arc::clone(&table); + let h2 = std::thread::spawn(move || t2.pending_summary()); + entered.wait(); + b.val.store(7, Ordering::Release); + assert!(table.note_queue_signal(pb as usize, 7)); + table.note_queue_wait(pb as usize, 7); + table.note_cpu_signal(pb as usize); + assert_eq!(unsafe { (*(cell_b as *const AtomicU64)).load(Ordering::Acquire) }, 7); + release.wait(); + let summary = h2.join().unwrap(); + assert!(summary.contains("done=0x1/sig=0xa/"), "unexpected summary: {summary}"); + } + + #[test] + fn pending_summary_keeps_non_cell_fence_live_until_forget_returns() { + let table = Arc::new(FenceTable::new()); + let fence = MockFence::new(1); + let p = fence.as_ptr() as usize; + assert!(!table.note_queue_signal(p, 2), "the fence must not have a cell"); + let (entered, release) = fence.arm_gate(); + let summary_table = Arc::clone(&table); + let summary = std::thread::spawn(move || summary_table.pending_summary()); + entered.wait(); + + let (started_tx, started_rx) = std::sync::mpsc::channel(); + let (done_tx, done_rx) = std::sync::mpsc::channel(); + let forget_table = Arc::clone(&table); + let forget = std::thread::spawn(move || { + started_tx.send(()).unwrap(); + forget_table.forget_fence(p); + done_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + assert!(matches!(table.summary_lifetime.try_lock(), Err(std::sync::TryLockError::WouldBlock))); + assert!(matches!(done_rx.try_recv(), Err(std::sync::mpsc::TryRecvError::Empty)), "forget returned during the raw COM query"); + + release.wait(); + assert!(summary.join().unwrap().contains("done=0x1/sig=0x2/")); + forget.join().unwrap(); + done_rx.recv().unwrap(); + drop(fence); + } + + #[test] + fn note_cpu_signal_and_refresh_avoid_unrelated_and_non_cell_fences() { + let table = FenceTable::new(); + let (a, b) = (MockFence::new(3), MockFence::new(5)); + let non_cells: Vec> = (0..64).map(|i| MockFence::new(i)).collect(); + let (pa, pb) = (a.as_ptr(), b.as_ptr()); + let _ = table.completed_value_address_with(pa, |_, _| {}); + let _ = table.completed_value_address_with(pb, |_, _| {}); + for f in &non_cells { + assert!(!table.note_queue_signal(f.as_ptr() as usize, 10)); + table.note_queue_wait(f.as_ptr() as usize, 10); + } + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.note_cpu_signal(pb as usize); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (1, 1)); + assert!(non_cells.iter().all(|f| f.calls.load(Ordering::Acquire) == 0)); + + table.forget_fence(pa as usize); + a.calls.store(0, Ordering::Release); + b.calls.store(0, Ordering::Release); + table.refresh(); + assert_eq!((a.calls.load(Ordering::Acquire), b.calls.load(Ordering::Acquire)), (0, 1)); + } + + #[test] + fn per_cell_lock_prevents_stale_refresh_overwrite() { + let table = Arc::new(FenceTable::new()); + let a = MockFence::new(10); + let pa = a.as_ptr(); + let cell = table.completed_value_address_with(pa, |_, _| {}); + a.calls.store(0, Ordering::Release); + + let (entered, release) = a.arm_gate(); + let t1 = Arc::clone(&table); + let h1 = std::thread::spawn(move || t1.refresh()); + entered.wait(); + a.val.store(11, Ordering::Release); + let t2 = Arc::clone(&table); + let pa_addr = pa as usize; + let h2 = std::thread::spawn(move || t2.note_cpu_signal(pa_addr)); + std::thread::sleep(std::time::Duration::from_millis(20)); + assert_eq!(a.calls.load(Ordering::Acquire), 1, "note_cpu_signal must serialize behind in-flight refresh_lock"); + release.wait(); + h1.join().unwrap(); + h2.join().unwrap(); + assert_eq!(a.calls.load(Ordering::Acquire), 2); + assert_eq!(unsafe { (*(cell as *const AtomicU64)).load(Ordering::Acquire) }, 11); + } } diff --git a/crates/xcl/src/hle/d3d12x/frame.rs b/crates/xcl/src/hle/d3d12x/frame.rs index 38c073c0ec..c98fd55c2d 100644 --- a/crates/xcl/src/hle/d3d12x/frame.rs +++ b/crates/xcl/src/hle/d3d12x/frame.rs @@ -138,9 +138,9 @@ unsafe impl Send for Clock {} static CLOCK: Mutex> = Mutex::new(None); static NEXT_TOKEN: AtomicU64 = AtomicU64::new(1); /// (token, qpc of the origin it was issued at) -static ISSUED: Mutex> = Mutex::new(Vec::new()); +static ISSUED: Mutex> = Mutex::new(VecDeque::new()); /// (token, origin qpc, flip qpc) -static FLIPPED: Mutex> = Mutex::new(Vec::new()); +static FLIPPED: Mutex> = Mutex::new(VecDeque::new()); static LAST_ORIGIN: AtomicI64 = AtomicI64::new(0); /// qpc of the origins the clock released and no WaitFrameEventX has consumed yet (the origin /// semaphore counts up to ORIGIN_SEMAPHORE_MAX): each token gets its own frame's origin, not @@ -260,23 +260,115 @@ pub unsafe extern "system" fn set_frame_interval_x(_this: *mut std::ffi::c_void, S_FALSE } +// Writability and stack-handle fast paths adapted from PR #2692 by Decodere. +fn is_writable_protect(protect: u32) -> bool { + use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY, PAGE_READWRITE, PAGE_WRITECOPY}; + matches!(protect & 0xFF, PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) +} + +/// Fast-path working-set check for `[p, end)`: a definite answer for resident pages, otherwise +/// `None` so `writable` can inspect the virtual-memory regions without touching the pages. +fn resident_and_writable(p: usize, end: usize) -> Option { + use windows_sys::Win32::System::Memory::PAGE_GUARD; + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + const MAX_PAGES: usize = 16; + let first = p >> 12; + let pages = ((end - 1) >> 12) - first + 1; + if pages > MAX_PAGES { + return None; + } + let mut ws: [PSAPI_WORKING_SET_EX_INFORMATION; MAX_PAGES] = unsafe { std::mem::zeroed() }; + for (k, e) in ws[..pages].iter_mut().enumerate() { + e.VirtualAddress = ((first + k) << 12) as *mut std::ffi::c_void; + } + let size = (pages * std::mem::size_of::()) as u32; + if unsafe { K32QueryWorkingSetEx(GetCurrentProcess(), ws.as_mut_ptr() as *mut std::ffi::c_void, size) } == 0 { + return None; + } + let mut all_resident = true; + for e in &ws[..pages] { + let flags = unsafe { e.VirtualAttributes.Flags }; + let protect = ((flags >> 4) & 0x7FF) as u32; + if flags & 1 != 0 && protect != 0 { + if protect & PAGE_GUARD != 0 || !is_writable_protect(protect) { + return Some(false); + } + } else { + all_resident = false; + } + } + all_resident.then_some(true) +} + +/// Whether `[p, p + len)` is committed, unguarded and writable without touching any page. +fn writable(p: usize, len: usize) -> bool { + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD}; + if p == 0 || len == 0 || len > 256 << 20 { + return false; + } + let Some(end) = p.checked_add(len) else { return false }; + if let Some(ok) = resident_and_writable(p, end) { + return ok; + } + let mut cur = p; + while cur < end { + let mut mbi: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + let n = unsafe { VirtualQuery(cur as *const _, &mut mbi, std::mem::size_of::()) }; + if n == 0 || mbi.State != MEM_COMMIT || mbi.Protect & PAGE_GUARD != 0 || !is_writable_protect(mbi.Protect) { + return false; + } + let Some(next) = (mbi.BaseAddress as usize).checked_add(mbi.RegionSize) else { return false }; + if next <= cur { + return false; + } + cur = next; + } + true +} + +/// Stack-allocated ancillary handles (at most `MAXIMUM_WAIT_OBJECTS - 1`). +struct AncillaryHandles { + handles: [HANDLE; 63], + len: usize, +} + +impl std::ops::Deref for AncillaryHandles { + type Target = [HANDLE]; + fn deref(&self) -> &[HANDLE] { + &self.handles[..self.len] + } +} + +impl IntoIterator for AncillaryHandles { + type Item = HANDLE; + type IntoIter = std::iter::Take>; + fn into_iter(self) -> Self::IntoIter { + self.handles.into_iter().take(self.len) + } +} + /// the handles of an ancillary block `{ u32 count; HANDLE* list @8; i32* signaled @0x10 }` -unsafe fn ancillary(block: *const u8) -> Result, HRESULT> { +unsafe fn ancillary(block: *const u8) -> Result { + let mut out = AncillaryHandles { handles: [std::ptr::null_mut(); 63], len: 0 }; if block.is_null() { - return Ok(Vec::new()); + return Ok(out); } if !crate::gpu::shader::readable(block as usize, 16) { return Err(E_INVALIDARG); } let count = (block as *const u32).read_unaligned() as usize; if count == 0 { - return Ok(Vec::new()); + return Ok(out); } let list = (block.add(8) as *const usize).read_unaligned(); if count > 63 || !crate::gpu::shader::readable(list, count * 8) { return Err(E_INVALIDARG); } - Ok((0..count).map(|i| (list as *const HANDLE).add(i).read_unaligned()).collect()) + for (i, slot) in out.handles[..count].iter_mut().enumerate() { + *slot = (list as *const HANDLE).add(i).read_unaligned(); + } + out.len = count; + Ok(out) } unsafe fn note_signaled(block: *const u8, index: i32) { @@ -284,7 +376,7 @@ unsafe fn note_signaled(block: *const u8, index: i32) { return; } let out = (block.add(0x10) as *const usize).read_unaligned(); - if crate::gpu::shader::readable(out, 4) { + if writable(out, 4) { (out as *mut i32).write_unaligned(index); } } @@ -363,7 +455,7 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t trace_calls(format_args!("WaitFrameEventX(type {ty}, timeout {timeout_ms} ms, block {block:p}, flags {flags:#x}, token in {:#x})", if token.is_null() { 0 } else { *token })); let scheduled = with(|c| { ((ty as usize) < TYPES && c.kinds[ty as usize].scheduled) - .then(|| (c.kinds[ty as usize].internal as usize, Arc::clone(&c.kinds[ty as usize].extra))) + .then(|| (c.kinds[ty as usize].internal as usize, (interval_override() == Some(0)).then(|| Arc::clone(&c.kinds[ty as usize].extra)))) }); let Some((internal, scheduled_extra)) = scheduled else { return E_INVALIDARG }; let token_in = if token.is_null() { 0 } else { *token }; @@ -374,8 +466,7 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t Ok(h) => h, Err(e) => return e, }; - let uncapped = interval_override() == Some(0); - let (hr, index, origin_now) = if uncapped { + let (hr, index, origin_now) = if let Some(scheduled_extra) = scheduled_extra { for &h in &scheduled_extra.0 { if SetEvent(h) == 0 { ReleaseSemaphore(h, 1, std::ptr::null_mut()); @@ -402,16 +493,18 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t } (hr, index, Some(now)) } else { - let mut hs = vec![internal as HANDLE]; - hs.extend(extra); - let r = WaitForMultipleObjects(hs.len() as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms); + let mut hs = [std::ptr::null_mut(); 64]; + hs[0] = internal as HANDLE; + hs[1..1 + extra.len()].copy_from_slice(&extra); + let count = 1 + extra.len(); + let r = WaitForMultipleObjects(count as u32, hs.as_ptr(), (flags & WAIT_ALL != 0) as i32, timeout_ms); ACTIVITY[0].fetch_add(1, Ordering::Relaxed); if r == WAIT_TIMEOUT { ACTIVITY[1].fetch_add(1, Ordering::Relaxed); } let (hr, index) = if r == WAIT_TIMEOUT { (S_FALSE, -1) - } else if ((r - WAIT_OBJECT_0) as usize) < hs.len() { + } else if ((r - WAIT_OBJECT_0) as usize) < count { // -2: the frame event itself, else the index of the ancillary handle (S_OK, if r == WAIT_OBJECT_0 { -2 } else { (r - WAIT_OBJECT_0) as i32 - 1 }) } else { @@ -440,9 +533,9 @@ pub unsafe extern "system" fn wait_frame_event_x(_this: *mut std::ffi::c_void, t t = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed) & TOKEN_MASK; } if issued.len() >= KNOWN_TOKENS { - issued.remove(0); + issued.pop_front(); } - issued.push((t, origin)); + issued.push_back((t, origin)); if !token.is_null() { *token = t; } @@ -459,10 +552,9 @@ pub fn mark_flipped(token: u64) { // the frame's own origin (a token XCL did not issue: the latest origin) let origin = ISSUED.lock().unwrap().iter().rev().find(|e| e.0 == token).map(|e| e.1).unwrap_or_else(|| LAST_ORIGIN.load(Ordering::Relaxed)); let mut f = FLIPPED.lock().unwrap(); - f.push((token, origin, qpc())); - if f.len() > FLIPPED_KEEP { - let n = f.len() - FLIPPED_KEEP; - f.drain(..n); + f.push_back((token, origin, qpc())); + while f.len() > FLIPPED_KEEP { + f.pop_front(); } } @@ -623,6 +715,76 @@ mod tests { assert_eq!(effective_clock_interval_us(33333, Some(200)), Some(1000)); } + #[test] + fn note_signaled_requires_every_target_page_to_be_writable() { + use windows_sys::Win32::System::Memory::{ + VirtualAlloc, VirtualFree, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_GUARD, + PAGE_READONLY, PAGE_READWRITE, + }; + let block = |out: usize| { + let mut b = [0u8; 0x18]; + b[0x10..].copy_from_slice(&out.to_le_bytes()); + b + }; + unsafe { + assert!(!writable(0, 4) && !writable(usize::MAX - 1, 4)); + let base = VirtualAlloc(std::ptr::null(), 0x3000, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE) as *mut u8; + assert!(!base.is_null()); + let (ro, guard) = (base.add(0x1000), base.add(0x2000)); + (ro as *mut i32).write_unaligned(0x1234_5678); + let mut old = 0; + assert_ne!(VirtualProtect(ro as *const _, 0x1000, PAGE_READONLY, &mut old), 0); + assert_ne!(VirtualProtect(guard as *const _, 0x1000, PAGE_READWRITE | PAGE_GUARD, &mut old), 0); + assert!(writable(base as usize, 4)); + assert!(!writable(base as usize + 0xFFE, 4) && !writable(guard as usize, 4)); + note_signaled(block(ro as usize).as_ptr(), 9); + assert_eq!((ro as *const i32).read_unaligned(), 0x1234_5678); + note_signaled(block(base as usize).as_ptr(), 7); + assert_eq!((base as *const i32).read_unaligned(), 7); + let mut mbi: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + assert_ne!(VirtualQuery(guard as *const _, &mut mbi, std::mem::size_of_val(&mbi)), 0); + assert_ne!(mbi.Protect & PAGE_GUARD, 0, "validation consumed the guard page"); + assert_ne!(VirtualFree(base as *mut _, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn ancillary_stack_handles_preserve_boundaries_and_order() { + unsafe { + assert!(ancillary(std::ptr::null()).unwrap().is_empty()); + let mut block = [0u8; 0x18]; + let list: [HANDLE; 63] = std::array::from_fn(|i| ((i + 1) * 4) as HANDLE); + block[..4].copy_from_slice(&63u32.to_le_bytes()); + block[8..16].copy_from_slice(&(list.as_ptr() as usize).to_le_bytes()); + let got = ancillary(block.as_ptr()).unwrap(); + assert_eq!(&*got, &list); + assert_eq!(got.into_iter().collect::>(), list); + block[..4].copy_from_slice(&64u32.to_le_bytes()); + assert_eq!(ancillary(block.as_ptr()).err(), Some(E_INVALIDARG)); + } + } + + #[test] + fn frame_history_deques_evict_oldest_in_order() { + let mut issued = VecDeque::new(); + for i in 0..KNOWN_TOKENS + 10 { + if issued.len() >= KNOWN_TOKENS { + issued.pop_front(); + } + issued.push_back(i); + } + assert_eq!((issued.len(), issued.front(), issued.back()), (KNOWN_TOKENS, Some(&10), Some(&(KNOWN_TOKENS + 9)))); + + let mut flipped = VecDeque::new(); + for i in 0..FLIPPED_KEEP + 10 { + flipped.push_back(i); + while flipped.len() > FLIPPED_KEEP { + flipped.pop_front(); + } + } + assert_eq!((flipped.len(), flipped.front(), flipped.back()), (FLIPPED_KEEP, Some(&10), Some(&(FLIPPED_KEEP + 9)))); + } + #[test] fn console_intervals_and_deadlines() { assert!(interval_valid(16667, false) && interval_valid(16666 + 16, false) && interval_valid(33333, false)); diff --git a/crates/xcl/src/hle/d3d12x/late_release.rs b/crates/xcl/src/hle/d3d12x/late_release.rs index 18ddc684e7..2c5e07afd1 100644 --- a/crates/xcl/src/hle/d3d12x/late_release.rs +++ b/crates/xcl/src/hle/d3d12x/late_release.rs @@ -62,7 +62,7 @@ impl Held { self.fences.insert(key, (f, 0)); } let (fence, value) = self.fences.get_mut(&key).unwrap(); - if q.Signal(&*fence, *value + 1).is_err() { + if super::real::native_queue_signal(q, &*fence, *value + 1).is_err() { ok = false; break; } @@ -86,6 +86,16 @@ impl Held { static HELD: Mutex> = Mutex::new(None); +/// Remove cached state for a retired queue before its final owner can be released. Sealed +/// batches own their fence clones, so they remain gated. The removed fence drops unlocked. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = { + let mut held = HELD.lock().unwrap(); + held.as_mut().and_then(|held| held.fences.remove(&id.raw())) + }; + drop(gone); +} + /// Whether last releases are held (`XCL_LATE_RELEASE=0` turns it off). pub fn enabled() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -128,13 +138,7 @@ pub unsafe fn drain_known(seal_now: bool) { if HELD.lock().unwrap().as_ref().is_none_or(Held::is_empty) { return; } - let mut queues: Vec = Vec::new(); - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { - queues.push(q.clone()); - } - } + let mut queues = super::present::active_queues_held(); queues.extend(super::sparse::queue()); queues.extend(super::title_textures::upload_queues()); let gone = match HELD.lock().unwrap().as_mut() { diff --git a/crates/xcl/src/hle/d3d12x/list_x.rs b/crates/xcl/src/hle/d3d12x/list_x.rs index ee544dec22..d82c392607 100644 --- a/crates/xcl/src/hle/d3d12x/list_x.rs +++ b/crates/xcl/src/hle/d3d12x/list_x.rs @@ -17,11 +17,11 @@ //! go to that window's buffer (`real::uma_window_buffer`), which is in COMMON between them. //! An index buffer at such an address is given to the PC as the window buffer's GPU address. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::ffi::c_void; use std::mem::{transmute_copy, ManuallyDrop}; use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Condvar, LazyLock, Mutex, OnceLock}; +use std::sync::{Arc, Condvar, LazyLock, Mutex, OnceLock}; use std::time::{Duration, Instant}; use windows::core::Interface; @@ -62,9 +62,6 @@ const WAIT_TIMEOUT: Duration = Duration::from_secs(2); /// cleanly without prematurely breaking synchronization. Overridable via `XCL_GPU_WAIT_TIMEOUT_MS` /// for diagnostics. const GPU_WAIT_WATCHDOG_TIMEOUT: Duration = Duration::from_millis(5000); -/// Cap on tracked per-list written UMA ranges (for same-list write-then-wait detection). -const MAX_WRITTEN_RANGES: usize = 256; - fn wait_timeout() -> Duration { static T: OnceLock = OnceLock::new(); *T.get_or_init(|| { @@ -329,6 +326,7 @@ struct RenderTargets { struct Bindings { heaps: Vec, has_sampler_heap: bool, + shared_view_heap: bool, topology: Option, viewports: Vec, scissors: Vec, @@ -607,6 +605,122 @@ unsafe fn restore_bindings(this: *mut c_void, b: &Bindings, ty: D3D12_COMMAND_LI } } +/// Canonical half-open UMA ranges written by one command-list recording. +/// +/// Keys are starts and values are exclusive ends. Overlapping and adjacent ranges are merged, +/// so lookup examines at most the predecessor and successor around the requested address. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RecordedWrites { + ranges: BTreeMap, +} + +impl RecordedWrites { + fn insert(&mut self, va: u64, size: u64) { + if size == 0 { + return; + } + let mut start = va; + let mut end = va.saturating_add(size); + if end <= start { + return; + } + + if let Some((&previous_start, &previous_end)) = self.ranges.range(..=start).next_back() { + if previous_end >= start { + start = previous_start; + end = end.max(previous_end); + self.ranges.remove(&previous_start); + } + } + loop { + let next = self.ranges.range(start..).next().map(|(&s, &e)| (s, e)); + match next { + Some((next_start, next_end)) if next_start <= end => { + end = end.max(next_end); + self.ranges.remove(&next_start); + } + _ => break, + } + } + self.ranges.insert(start, end); + } + + fn overlaps(&self, va: u64, size: u64) -> bool { + if size == 0 { + return false; + } + let end = va.saturating_add(size); + if end <= va { + return false; + } + if self.ranges.range(..=va).next_back().is_some_and(|(_, &range_end)| range_end > va) { + return true; + } + self.ranges.range(va..).next().is_some_and(|(&range_start, _)| range_start < end) + } + + fn clear(&mut self) { + self.ranges.clear(); + } + + fn is_empty(&self) -> bool { + self.ranges.is_empty() + } + + fn extend(&mut self, other: &Self) { + for (&start, &end) in &other.ranges { + self.insert(start, end - start); + } + } +} + +/// When a recorded write becomes visible to later work. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum WriteProducer { + InSegmentGpu, + CpuAfterSegment, +} + +/// Exact written ranges kept separately for each visibility class. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +struct RecordedWriteProducers { + in_segment_gpu: RecordedWrites, + cpu_after_segment: RecordedWrites, +} + +impl RecordedWriteProducers { + fn ranges(&self, producer: WriteProducer) -> &RecordedWrites { + match producer { + WriteProducer::InSegmentGpu => &self.in_segment_gpu, + WriteProducer::CpuAfterSegment => &self.cpu_after_segment, + } + } + + fn ranges_mut(&mut self, producer: WriteProducer) -> &mut RecordedWrites { + match producer { + WriteProducer::InSegmentGpu => &mut self.in_segment_gpu, + WriteProducer::CpuAfterSegment => &mut self.cpu_after_segment, + } + } + + fn insert(&mut self, producer: WriteProducer, va: u64, size: u64) { + self.ranges_mut(producer).insert(va, size); + } + + fn overlaps(&self, producer: WriteProducer, va: u64, size: u64) -> bool { + self.ranges(producer).overlaps(va, size) + } + + fn clear(&mut self) { + self.in_segment_gpu.clear(); + self.cpu_after_segment.clear(); + } + + fn is_empty(&self) -> bool { + self.in_segment_gpu.is_empty() && self.cpu_after_segment.is_empty() + } +} + #[derive(Default)] struct ListState { allocator: usize, @@ -614,6 +728,8 @@ struct ListState { last_queue: Option, /// Title's currently bound PSO (before dynamic depth-bias override) bound_pso: usize, + /// Recipe-backed native generations referenced by this physical recording. + native_generations: Vec, /// Active `RSSetDepthBiasX` override (None = zero / disabled) depth_bias: Option, /// Last depth bias sent to `ID3D12GraphicsCommandList9::RSSetDepthBias` on this PC list @@ -628,15 +744,25 @@ struct ListState { /// Last `OMSetDepthBounds` values, restored after `KickoffX` depth_bounds: Option<(f32, f32)>, occlusion: Occlusion, - /// UMA address ranges written by this list since last Reset/KickoffX - written_ranges: Vec<(u64, u64)>, + /// Address ranges written by this list since last Reset/KickoffX, by visibility class. + written_ranges: RecordedWriteProducers, + /// Writes produced by this physical segment only (not cumulative across a split). + segment_write_producers: RecordedWriteProducers, /// Sparse-window `(va, bytes)` ranges written by memory ops (`Write32/64`, `Fill*`, /// `CopyMemoryToMemoryX`, timestamps) to copy back to the CPU view after execution. sparse_writes: Vec<(usize, usize)>, + /// Writes into title textures produced by this physical segment. + texture_writes: Vec, + /// Ordered state transitions of tracked textures in this physical segment. + texture_transitions: Vec, + /// A translated draw/dispatch in this physical segment successfully bound the shared view heap. + uses_shared_view_heap: bool, /// Non-timestamp 64-bit `(va, value)` writes recorded by `Write64BitValue{Bottom,Top}OfPipeX` /// so `ExecuteCommandLists` / `KickoffX` can signal per-address GPU fences for cross-queue /// `Wait64BitValueX` without blocking the submitter thread on the CPU. write64_signals: Vec<(u64, u64)>, + /// Causal dump token for this exact recording; absent unless scheduled dumps enabled tracing. + write64_trace: Option>>, /// External memory waits recorded on this list pending_waits: Vec, /// bottom-of-pipe writes into memory the GPU does not see (`cpu_writes`) @@ -657,23 +783,47 @@ struct ListState { /// A `Dispatch` or a dispatching `ExecuteIndirect` put off to the submit, with its arguments. pub(super) enum Deferred { - Dispatch(u32, u32, u32), + /// x, y, z and `DispatchX`'s flags (0 for `Dispatch`) + Dispatch(u32, u32, u32, u32), Indirect(usize, u32, usize, u64, usize, u64), } +/// Why a recording needs a physical command-list boundary. +pub(super) enum SegmentReason { + WaitAfterWrite64, + WaitAfterCpuWrite, + DeferredDispatch(Deferred), +} + +impl SegmentReason { + fn extra_segments(&self) -> usize { + match self { + Self::WaitAfterWrite64 | Self::WaitAfterCpuWrite => 1, + Self::DeferredDispatch(_) => 2, + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum WaitPlacement { + OrderedInSegment, + RecordHere, + SplitAfterCpuWrite, + SplitAfterWrite64, +} + impl ListState { - fn note_write(&mut self, va: u64, size: u64) { + fn pin_native_generation(&mut self, generation: super::pso_async::NativeGeneration) { + push_unique(&mut self.native_generations, generation, super::pso_async::NativeGeneration::same); + } + + fn note_write(&mut self, producer: WriteProducer, va: u64, size: u64) { if size == 0 { return; } - let end = va.saturating_add(size); - if self.written_ranges.len() < MAX_WRITTEN_RANGES { - self.written_ranges.push((va, end)); - } else if let Some(last) = self.written_ranges.last_mut() { - last.0 = last.0.min(va); - last.1 = last.1.max(end); - } - if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { + self.written_ranges.insert(producer, va, size); + self.segment_write_producers.insert(producer, va, size); + if producer == WriteProducer::InSegmentGpu && crate::gpu::uma::get().is_some_and(|u| u.is_sparse(va as usize)) { if self.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_add(1, Ordering::AcqRel); } @@ -705,36 +855,278 @@ impl ListState { } fn has_prior_write(&self, va: u64, size: u64) -> bool { - let end = va.saturating_add(size); - self.written_ranges.iter().any(|&(s, e)| va < e && s < end) + // GPU writes are already ordered before later commands in the same physical list. + self.written_ranges.overlaps(WriteProducer::InSegmentGpu, va, size) } - fn clear_waits(&mut self) { - if !self.pending_waits.is_empty() { - self.pending_waits.clear(); - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); + fn wait_placement(&self, va: u64, size: u64) -> WaitPlacement { + if self.written_ranges.overlaps(WriteProducer::CpuAfterSegment, va, size) { + WaitPlacement::SplitAfterCpuWrite + } else if self.has_prior_write(va, size) { + WaitPlacement::OrderedInSegment + } else if !self.write64_signals.is_empty() { + WaitPlacement::SplitAfterWrite64 + } else { + WaitPlacement::RecordHere } } + fn clear_waits(&mut self) { + self.pending_waits.clear(); + } + fn push_wait(&mut self, w: PendingWait) { - if self.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_add(1, Ordering::AcqRel); - } self.pending_waits.push(w); } } +/// Record that a successfully bound translated draw/dispatch can address the shared view heap. +/// Callers gate this with `srv_tracking_enabled` and the heap-binding result. +pub(super) fn note_shared_view_heap_use(list: *mut c_void) { + if list.is_null() { + return; + } + if let Some(state) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + state.uses_shared_view_heap = true; + } +} + +fn push_unique(items: &mut Vec, item: T, same: impl Fn(&T, &T) -> bool) { + if !items.iter().any(|old| same(old, &item)) { + items.push(item); + } +} + +fn propagate_bundle_shared_view_use(states: &mut HashMap, parent: usize, bundle: usize) { + if states.get(&bundle).is_some_and(|state| state.uses_shared_view_heap) { + states.entry(parent).or_default().uses_shared_view_heap = true; + } +} + +pub(super) fn record_native_generation(list: usize, generation: Option) { + if let Some(generation) = generation { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().pin_native_generation(generation); + } +} + +pub(super) fn resolve_and_record_pipeline(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); + record_native_generation(list, generation); + resolved +} + +pub(super) fn resolve_and_record_pipeline_lazy(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled_lazy(pso); + record_native_generation(list, generation); + resolved +} + +pub(super) fn resolve_and_record_pipeline_wait(list: usize, pso: usize) -> usize { + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled_wait(pso); + record_native_generation(list, generation); + resolved +} + +/// Snapshot bundle descriptor and PSO-generation use before the bundle may be reset. +pub(super) fn on_execute_bundle(parent: usize, bundle: usize) { + let track_descriptors = super::vram::srv_tracking_enabled(); + let track_generations = super::pso_async::rebuild_recipes_enabled(); + if !track_descriptors && !track_generations { + return; + } + let mut g = LISTS.lock().unwrap(); + let Some(m) = g.as_mut() else { return }; + let pins = if track_generations { + m.get(&bundle).map(|s| s.native_generations.clone()).unwrap_or_default() + } else { + Vec::new() + }; + if track_descriptors { + propagate_bundle_shared_view_use(m, parent, bundle); + } + if track_generations { + let parent = m.entry(parent).or_default(); + for pin in pins { + parent.pin_native_generation(pin); + } + } +} + +pub(super) unsafe extern "system" fn execute_bundle(this: *mut c_void, bundle: *mut c_void) { + on_execute_bundle(this as usize, bundle as usize); + pc::(this, 27)(this, bundle); +} + +/// Record immutable tracked-texture transitions on the physical segment that contains them. +pub(super) fn note_texture_transitions(list: usize, transitions: &[(usize, u32, D3D12_RESOURCE_STATES)]) { + let captured = super::title_textures::capture_transitions(transitions); + if captured.is_empty() { + return; + } + if let Some(state) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + state.texture_transitions.extend(captured); + } +} + +/// Discard transitions when a translated physical list is about to be recorded from the start. +pub(super) fn clear_texture_transitions(list: usize) { + if let Some(state) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { + state.texture_transitions.clear(); + } +} + +struct KickoffEffects { + waits: Vec, + sparse_writes: Vec<(usize, usize)>, + texture_writes: Vec, + texture_transitions: Vec, + uses_shared_view_heap: bool, + write64_signals: Vec<(u64, u64)>, + cpu_writes: Vec, + native_generations: Vec, +} + +fn take_kickoff_effects(state: &mut ListState) -> KickoffEffects { + let effects = KickoffEffects { + waits: std::mem::take(&mut state.pending_waits), + sparse_writes: state.clear_sparse_writes(), + texture_writes: std::mem::take(&mut state.texture_writes), + texture_transitions: std::mem::take(&mut state.texture_transitions), + uses_shared_view_heap: std::mem::take(&mut state.uses_shared_view_heap), + write64_signals: state.clear_write64_signals(), + cpu_writes: std::mem::take(&mut state.cpu_writes), + native_generations: std::mem::take(&mut state.native_generations), + }; + state.written_ranges.clear(); + state.segment_write_producers.clear(); + effects +} + +fn take_kickoff_effects_before_close(state: &mut ListState, has_fail_closed_standby: bool) -> Option { + (!has_fail_closed_standby).then(|| take_kickoff_effects(state)) +} + +fn restore_unique(destination: Option<&mut Vec>, pins: Vec, same: impl Fn(&T, &T) -> bool) -> Result<(), Vec> { + let Some(destination) = destination else { return Err(pins) }; + for pin in pins { + push_unique(destination, pin, &same); + } + Ok(()) +} + +fn restore_kickoff_native_generations(list: usize, pins: Vec) { + if pins.is_empty() { + return; + } + let mut lists = LISTS.lock().unwrap(); + let restored = restore_unique( + lists.as_mut().and_then(|lists| lists.get_mut(&list)).map(|state| &mut state.native_generations), + pins, + super::pso_async::NativeGeneration::same, + ); + drop(lists); + if let Err(pins) = restored { + super::pso_async::poison_native_generations(pins.iter()); + } +} + +fn settle_kickoff_standby( + standby: Option<(T, U)>, + reset_succeeded: bool, + return_spare: impl FnOnce(T, U), + fail_closed: impl FnOnce(T, U, bool), +) { + if let Some((wrapper, standby)) = standby { + if reset_succeeded { + return_spare(wrapper, standby); + } else { + fail_closed(wrapper, standby, false); + } + } +} + +/// Recording state that a PC Reset loses and the continuation segment must inherit. +struct SplitCarry { + allocator: usize, + last_queue: Option, + bound_pso: usize, + depth_bias: Option, + index_buffer: Option, + depth_bounds: Option<(f32, f32)>, + predication: Option, + pred_buf: Option, + pred_in_state: bool, + active_query: Option<(Query, D3D12_QUERY_TYPE)>, + ended_early: Vec, + written_ranges: RecordedWriteProducers, + bindings: Bindings, +} + +impl SplitCarry { + fn capture(state: &ListState) -> Option { + if state.allocator == 0 { + return None; + } + let active_query = state.occlusion.active.map(|(q, ty, _)| (q, ty)); + let mut ended_early = state.occlusion.ended_early.clone(); + ended_early.extend(active_query.map(|(q, _)| q)); + Some(Self { + allocator: state.allocator, + last_queue: state.last_queue, + bound_pso: state.bound_pso, + depth_bias: state.depth_bias, + index_buffer: state.index_buffer, + depth_bounds: state.depth_bounds, + predication: state.predication, + pred_buf: state.pred_buf.clone(), + pred_in_state: state.pred_in_state, + active_query, + ended_early, + written_ranges: state.written_ranges.clone(), + bindings: state.bindings.clone(), + }) + } + + fn continuation_state(&self, ty: D3D12_COMMAND_LIST_TYPE) -> ListState { + ListState { + allocator: self.allocator, + list_type: Some(ty), + last_queue: self.last_queue, + bound_pso: self.bound_pso, + depth_bias: self.depth_bias, + native_bias: DepthBias::ZERO, + pso_dirty: false, + using_fallback_pso: false, + index_buffer: self.index_buffer, + depth_bounds: self.depth_bounds, + occlusion: Occlusion { active: None, ended_early: self.ended_early.clone() }, + written_ranges: self.written_ranges.clone(), + pred_buf: self.pred_buf.clone(), + pred_in_state: false, + predication: self.predication, + bindings: self.bindings.clone(), + ..Default::default() + } + } + + fn commit_state(&self, state: &mut ListState) { + state.occlusion.end_active_early(); + state.pred_in_state = false; + } + +} + #[derive(Clone, Copy)] struct QueueInfo { queue: usize, + id: super::title_textures::WriterQueueId, device: usize, ty: D3D12_COMMAND_LIST_TYPE, } static LISTS: Mutex>> = Mutex::new(None); static LIVE_QUEUES: Mutex> = Mutex::new(Vec::new()); -/// Number of lists with at least one pending `Wait32/64BitValueX` (fast-path guard for ExecuteCommandLists). -static PENDING_WAIT_LISTS: AtomicUsize = AtomicUsize::new(0); +static NEXT_QUEUE_ID: AtomicU64 = AtomicU64::new(0); /// Number of lists with recorded sparse-window memory writes (fast-path guard for post-execute readback). static SPARSE_WRITE_LISTS: AtomicUsize = AtomicUsize::new(0); /// Number of lists with recorded non-timestamp `Write64BitValue*` signals (fast-path guard). @@ -744,6 +1136,212 @@ static DEPTH_BIAS_USED: AtomicBool = AtomicBool::new(false); /// Set once any list uses `SetPredicationBufferX` (fast-path guard for Close/Reset hooks). static PREDICATION_USED: AtomicBool = AtomicBool::new(false); +/// Immutable effects recorded by one physical command-list segment at submission planning time. +#[derive(Clone, Default)] +pub(super) struct SegmentEffects { + waits: Vec, + write_producers: RecordedWriteProducers, + write64_signals: Vec<(u64, u64)>, + sparse_writes: Vec<(usize, usize)>, + texture_writes: Vec, + texture_transitions: Vec, + uses_shared_view_heap: bool, + cpu_writes: Vec, + native_generations: Vec, +} + +impl SegmentEffects { + pub(super) fn producer_overlaps(&self, producer: WriteProducer, va: u64, size: u64) -> bool { + self.write_producers.overlaps(producer, va, size) + } +} + +/// One queue submission's physical lists and their effects, kept in matching chronological order. +pub(super) struct SubmissionPlan { + lists: Vec<*mut c_void>, + effects: Vec, + /// Exact recording tokens captured with `effects`; empty when causal dumps are disabled. + traces: Vec>>>, + /// Per-segment dependency on an earlier CPU-after-segment producer; empty on the no-wait fast path. + waits_after_cpu_write: Vec, + has_waits: bool, +} + +impl SubmissionPlan { + fn capture(lists: &[*mut c_void]) -> Self { + if lists.is_empty() { + return Self { lists: Vec::new(), effects: Vec::new(), traces: Vec::new(), waits_after_cpu_write: Vec::new(), has_waits: false }; + } + let g = LISTS.lock().unwrap(); + let effects: Vec = lists + .iter() + .map(|&list| { + g.as_ref() + .and_then(|m| m.get(&(list as usize))) + .map(|s| SegmentEffects { + waits: s.pending_waits.clone(), + write_producers: s.segment_write_producers.clone(), + write64_signals: s.write64_signals.clone(), + sparse_writes: s.sparse_writes.clone(), + texture_writes: s.texture_writes.clone(), + texture_transitions: s.texture_transitions.clone(), + uses_shared_view_heap: s.uses_shared_view_heap, + cpu_writes: s.cpu_writes.clone(), + native_generations: s.native_generations.clone(), + }) + .unwrap_or_default() + }) + .collect(); + let traces = if sync_state_tracing() { + lists + .iter() + .map(|&list| g.as_ref().and_then(|m| m.get(&(list as usize))).and_then(|s| s.write64_trace.clone())) + .collect() + } else { + Vec::new() + }; + drop(g); + let has_waits = effects.iter().any(|e| !e.waits.is_empty()); + let waits_after_cpu_write = if has_waits { + let mut prior_cpu_writes = RecordedWrites::default(); + effects + .iter() + .map(|effects| { + let depends = effects.waits.iter().any(|w| prior_cpu_writes.overlaps(w.va, w.width as u64)); + prior_cpu_writes.extend(effects.write_producers.ranges(WriteProducer::CpuAfterSegment)); + depends + }) + .collect() + } else { + Vec::new() + }; + Self { lists: lists.to_vec(), effects, traces, waits_after_cpu_write, has_waits } + } + + fn cpu_producer_overlaps(&self, waits: &[PendingWait], before: usize) -> bool { + self.effects[..before].iter().any(|e| { + waits.iter().any(|w| e.producer_overlaps(WriteProducer::CpuAfterSegment, w.va, w.width as u64)) + }) + } + + fn chunk_needs_cpu_completion(&self, start: usize, end: usize, external_waits: &[PendingWait]) -> bool { + self.effects[start..end].iter().any(|producer| { + self.effects[end..] + .iter() + .flat_map(|e| &e.waits) + .chain(external_waits) + .any(|w| producer.producer_overlaps(WriteProducer::CpuAfterSegment, w.va, w.width as u64)) + }) + } +} + +#[derive(Clone, Copy)] +pub(super) struct SubmissionChunk<'a> { + lists: &'a [*mut c_void], + effects: &'a [SegmentEffects], + traces: &'a [Option>>], + needs_cpu_completion: bool, +} + +impl<'a> SubmissionChunk<'a> { + pub(super) fn lists(self) -> &'a [*mut c_void] { + self.lists + } + + pub(super) fn needs_cpu_completion(self) -> bool { + self.needs_cpu_completion + } + + pub(super) fn uses_shared_view_heap(self) -> bool { + self.effects.iter().any(|effects| effects.uses_shared_view_heap) + } + + pub(super) fn native_generations(self) -> impl Clone + Iterator { + self.effects.iter().flat_map(|effects| effects.native_generations.iter()) + } + + pub(super) fn has_native_generations(self) -> bool { + self.effects.iter().any(|effects| !effects.native_generations.is_empty()) + } + + pub(super) unsafe fn submit_effects(self, queue: *mut c_void) -> Option { + // The immutable submission plan is now the production path, so record execution here + // after its caller has successfully submitted this exact chunk. The legacy + // `signal_write64_fences` path below remains useful to tests but is not reached by the + // title-facing submit path. + for trace in self.traces.iter().flatten() { + mark_trace(trace, ListEvent::Executed); + } + submit_segment_effects(queue, self.effects, self.needs_cpu_completion) + } +} + +/// Submit one exact title chunk, adding one shared retirement receipt when an opt-in recording +/// can read the shared view heap or owns native pipeline generation pins. The ordinary path stays +/// on `SubmissionGate::submit`, avoiding a marker, allocation or lock when neither applies. +pub(super) unsafe fn submit_title_chunk<'a>( + gate: &mut super::alloc_pool::SubmissionGate, + queue: *mut c_void, + lists: &[*mut c_void], + protect_shared_view: bool, + protect_native_generations: bool, + native_generations: impl Iterator, + prepare: impl FnOnce(), + execute: impl FnOnce(), +) -> bool { + if !protect_shared_view && !protect_native_generations { + return gate.submit(queue, lists, prepare, execute); + } + let mut epoch = None; + let submitted = gate.submit_receipted( + queue, + lists, + || { + if protect_shared_view { + epoch = Some(super::vram::reserve_shared_view_epoch()); + } + prepare(); + }, + execute, + ); + match submitted { + super::alloc_pool::ReceiptedSubmission::NotExecuted => { + if let Some(epoch) = epoch { + super::vram::cancel_shared_view_epoch(epoch); + } + false + } + super::alloc_pool::ReceiptedSubmission::Executed(receipt) => { + if protect_native_generations { + if protect_shared_view { + super::vram::attach_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + receipt.clone(), + ); + } + super::pso_async::retire_native_generations(receipt, native_generations); + } else if protect_shared_view { + super::vram::attach_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + receipt, + ); + } + true + } + super::alloc_pool::ReceiptedSubmission::ExecutedUntracked => { + if protect_shared_view { + super::vram::poison_shared_view_epoch( + epoch.expect("executed shared-view submission without an epoch"), + ); + } + if protect_native_generations { + super::pso_async::poison_native_generations(native_generations); + } + true + } + } +} + /// Record a newly created title command queue so `KickoffX` can find a compatible queue. pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) { if queue == 0 { @@ -751,7 +1349,16 @@ pub fn on_queue_create(queue: usize, device: usize, ty: D3D12_COMMAND_LIST_TYPE) } let mut g = LIVE_QUEUES.lock().unwrap(); g.retain(|q| q.queue != queue); - g.push(QueueInfo { queue, device, ty }); + g.push(QueueInfo { queue, id: new_queue_id(queue), device, ty }); +} + +fn new_queue_id(raw: usize) -> super::title_textures::WriterQueueId { + let generation = NEXT_QUEUE_ID.fetch_add(1, Ordering::Relaxed).wrapping_add(1).max(1); + super::title_textures::WriterQueueId { raw, generation } +} + +pub(super) fn queue_identity(raw: usize) -> Option { + LIVE_QUEUES.lock().unwrap().iter().find(|q| q.queue == raw).map(|q| q.id) } /// Remove a released command queue so `KickoffX` never submits to a dead queue. @@ -760,6 +1367,11 @@ pub(super) fn on_queue_release(queue: usize) { scratch.fences.remove(&queue); scratch.collect_released(); drop(scratch); + stop_queue_submissions(queue); +} + +/// Stop non-owning internal users (notably `KickoffX`) from selecting a retiring queue. +pub(super) fn stop_queue_submissions(queue: usize) { LIVE_QUEUES.lock().unwrap().retain(|q| q.queue != queue); if let Some(m) = LISTS.lock().unwrap().as_mut() { for s in m.values_mut() { @@ -770,6 +1382,46 @@ pub(super) fn on_queue_release(queue: usize) { } } +/// Remove every cached use of a retired raw queue address before it can be reused. This is later +/// than `on_queue_release`: the retirement marker has completed, so old sync edges are finished. +/// Cached COM fences are extracted and dropped after their locks are gone. +pub(super) fn forget_queue(id: super::present::QueueId) { + let queue = id.raw(); + let scratch_fences = { + let mut scratch = COPY_SCRATCH.lock().unwrap(); + let mut gone = Vec::new(); + if let Some((fence, _)) = scratch.fences.remove(&queue) { + gone.push(fence); + } + for allocation in scratch.active.values_mut() { + if let Some((fence, _)) = allocation.marks.remove(&queue) { + gone.push(fence); + } + } + for allocation in &mut scratch.released { + if let Some((fence, _)) = allocation.marks.remove(&queue) { + gone.push(fence); + } + } + gone + }; + drop(scratch_fences); + LIVE_QUEUES.lock().unwrap().retain(|info| info.queue != queue); + if let Some(lists) = LISTS.lock().unwrap().as_mut() { + for state in lists.values_mut() { + if state.last_queue == Some(queue) { + state.last_queue = None; + } + } + } + let removed_waits = SYNC_GRAPH.lock().unwrap().as_mut().map_or(0, |graph| graph.forget_queue(queue)); + if removed_waits != 0 { + ARMED_GPU_WAITS.fetch_sub(removed_waits, Ordering::AcqRel); + } + let internal_waits = INTERNAL_WAITS.lock().unwrap().as_mut().and_then(|waits| waits.remove(&queue)); + drop(internal_waits); +} + #[cfg(test)] thread_local! { /// Optional test interceptor for `try_native_depth_bias` so unit tests deterministically @@ -803,20 +1455,32 @@ unsafe fn try_native_depth_bias(list: *mut c_void, bias: DepthBias) -> bool { /// # Safety /// `list` must be null or a valid `ID3D12GraphicsCommandList` COM pointer. pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { + on_create_with_backing(list, alloc, alloc, pso, ty) +} + +/// Register the exact PC list owned by a console-shaped list. Its adopted Reset and final Release +/// use the normal hooks below, so this state has the same recording and object lifetime as `list`. +pub(super) unsafe fn on_console_list_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { + on_create(list, alloc, pso, ty) +} + +/// Record a newly created command list's logical title allocator and native recording backing. +/// +/// # Safety +/// `list` must be null or a valid `ID3D12GraphicsCommandList` COM pointer. +pub(super) unsafe fn on_create_with_backing(list: *mut c_void, alloc: usize, backing: usize, pso: usize, ty: D3D12_COMMAND_LIST_TYPE) { if list.is_null() { return; } let key = list as usize; // (of a list that was here before and whose release was not seen: the GPU may still use it) release_copy_scratch(key); + super::real::dispatch_chain::list_reset(key); let old = { let mut g = LISTS.lock().unwrap(); let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&key); if let Some(ref old) = old { - if !old.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -824,12 +1488,11 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C WRITE64_SIGNAL_LISTS.fetch_sub(1, Ordering::AcqRel); } } - super::alloc_pool::created_on(key, alloc, ty.0); + super::alloc_pool::created_on(key, backing, ty.0); m.insert(key, ListState { allocator: alloc, list_type: Some(ty), bound_pso: pso, ..Default::default() }); old }; drop(old); - super::title_textures::list_reset(key); // Dynamic-depth-bias PSOs ignore baked RasterizerState depth bias; seed the list with the // initial PSO's static bias if non-zero (CreateCommandList resets RSSetDepthBias to 0). if ty != D3D12_COMMAND_LIST_TYPE_BUNDLE && pso != 0 { @@ -845,14 +1508,12 @@ pub unsafe fn on_create(list: *mut c_void, alloc: usize, pso: usize, ty: D3D12_C /// Clean up all tracked state when a command list is released for good. pub(super) fn on_release(list: usize) { + trace_list(list, ListEvent::Released); super::alloc_pool::forget_list(list); release_copy_scratch(list); - super::title_textures::list_reset(list); + super::real::dispatch_chain::list_reset(list); let old = LISTS.lock().unwrap().as_mut().and_then(|m| m.remove(&list)); if let Some(old) = old { - if !old.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } if !old.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -870,18 +1531,23 @@ pub(super) fn on_release(list: usize) { /// Clear per-recording sync/write tracking on a split segment moved into `title_list`'s spare pool. pub(super) fn clear_segment_state(list: usize) { - super::title_textures::list_reset(list); + trace_list(list, ListEvent::Reset); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&list)) { s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.segment_write_producers.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); + s.texture_writes.clear(); + s.texture_transitions.clear(); + s.uses_shared_view_heap = false; s.cpu_writes.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); s.deferred = None; + s.native_generations.clear(); } } @@ -1006,7 +1672,7 @@ pub(super) unsafe fn note_queue_for_lists(queue: usize, lists: &[*mut c_void]) { } else { 0 }; - g.push(QueueInfo { queue, device: dev_raw, ty }); + g.push(QueueInfo { queue, id: new_queue_id(queue), device: dev_raw, ty }); } } } @@ -1029,8 +1695,13 @@ fn pick_queue(last_queue: Option, device: usize, ty: D3D12_COMMAND_LIST_T g.iter().rev().find(|info| info.ty == ty && (device == 0 || info.device == 0 || info.device == device)).map(|info| info.queue) } -fn note_write(list: usize, va: u64, size: u64) { - LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(va, size); +fn note_write(list: usize, producer: WriteProducer, va: u64, size: u64) { + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().note_write(producer, va, size); +} + +fn note_texture_write(list: usize, res: usize, subresource: u32) { + let Some(write) = super::title_textures::capture_gpu_write(res, subresource) else { return }; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(list).or_default().texture_writes.push(write); } // --------------------------------------------------------------------------------------- @@ -1123,6 +1794,9 @@ struct SyncCell { recorded_list_type: Option, /// Last queue the recording list was executed on (if known). recorded_last_queue: Option, + /// The PC list of the recording that set `recorded_max`, when, and what came to that + /// recording (the sync-state dump). + recorded_by: Option<(usize, Instant, Arc>)>, /// Highest value submitted via `queue.Signal(&fence, v)` or released on CPU. submitted_max: u64, /// Queue that issued the latest GPU `Signal` (`None` if released on CPU). @@ -1163,10 +1837,97 @@ impl SyncGraph { *s += 1; *s } + + fn forget_queue(&mut self, queue: usize) -> usize { + self.queue_seq.remove(&queue); + let mut armed = 0; + for cell in self.cells.values_mut() { + if cell.recorded_last_queue == Some(queue) { + cell.recorded_last_queue = None; + } + if cell.submitted_queue == Some(queue) { + cell.submitted_queue = None; + } + let before = cell.armed_waits.len(); + cell.armed_waits.retain(|wait| wait.waiting_queue != queue); + armed += before - cell.armed_waits.len(); + cell.submitted_signals.retain(|signal| signal.queue != queue); + } + for fence in self.title_fences.values_mut() { + fence.waits.retain(|&(_, waiting_queue, _)| waiting_queue != queue); + fence.signals.retain(|signal| signal.queue != queue); + } + armed + } } static SYNC_GRAPH: Mutex> = Mutex::new(None); static ARMED_GPU_WAITS: AtomicUsize = AtomicUsize::new(0); +static SYNC_STATE_TRACING: AtomicBool = AtomicBool::new(false); + +/// Enable recording-level causal detail only when at least one scheduled sync dump will use it. +pub fn enable_sync_state_tracing() { + SYNC_STATE_TRACING.store(true, Ordering::Release); +} + +#[inline] +fn sync_state_tracing() -> bool { + SYNC_STATE_TRACING.load(Ordering::Acquire) +} + +/// What became of a recording of a PC list that recorded a `Write64BitValue*`: when it was last +/// executed, and the Reset or Release that ended it (the sync-state dump; a cell recorded and +/// never submitted names its list). +#[derive(Default, Clone, Copy)] +struct ListTrace { + executed: Option, + reset: Option, + released: Option, +} + +#[derive(Clone, Copy)] +enum ListEvent { + Executed, + Reset, + Released, +} + +/// Notes `event` on the recording `list` has open, when it recorded a `Write64BitValue*`. A Reset +/// or a Release ends the recording: what comes to the list (or its address) after is another's. +fn trace_list(list: usize, event: ListEvent) { + if !sync_state_tracing() { + return; + } + let t = { + let mut g = LISTS.lock().unwrap(); + let Some(state) = g.as_mut().and_then(|m| m.get_mut(&list)) else { return }; + match event { + ListEvent::Executed => state.write64_trace.clone(), + ListEvent::Reset | ListEvent::Released => state.write64_trace.take(), + } + }; + if let Some(t) = t { + mark_trace(&t, event); + } +} + +fn mark_trace(trace: &Mutex, event: ListEvent) { + let mut trace = trace.lock().unwrap(); + let at = Some(Instant::now()); + match event { + ListEvent::Executed => trace.executed = at, + ListEvent::Reset => trace.reset = at, + ListEvent::Released => trace.released = at, + } +} + +/// `by ms ago (executed …, reset …, released …)`: each as its time after the +/// recording `t`, or `no` when it has not come to it. +fn recording_trace(list: usize, at: Instant, t: &Mutex) -> String { + let Ok(t) = t.try_lock().map(|t| *t) else { return format!("by {list:#x} {} ms ago", at.elapsed().as_millis()) }; + let after = |e: Option| e.map_or("no".to_string(), |e| format!("+{} ms", e.saturating_duration_since(at).as_millis())); + format!("by {list:#x} {} ms ago (executed {}, reset {}, released {})", at.elapsed().as_millis(), after(t.executed), after(t.reset), after(t.released)) +} static SYNC_WATCHDOG_WAKE: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new(); static QUEUE_IDS: Mutex> = Mutex::new(Vec::new()); @@ -1209,6 +1970,57 @@ fn internal_waits_summary() -> String { unmet.into_iter().map(|(q, s)| format!("q{}: {s}", queue_id(q))).collect::>().join(", ") } +/// The `Wait64BitValueX` cells not yet at their highest recorded value, or with armed GPU waits: +/// `rec` above `sub` with nothing armed is a list that writes the value, recorded and never +/// submitted (its submitting thread is held). `try_lock`: a dump can come while a submitting +/// thread holds the graph. (@GreemSC's diagnostic, from #2244's review.) +fn cells_behind_summary() -> String { + let mut parts = Vec::new(); + if let Ok(g) = SYNC_GRAPH.try_lock() { + for (&va, c) in g.iter().flat_map(|gr| gr.cells.iter()) { + let done = c.fence.as_ref().map_or(0, |f| unsafe { f.GetCompletedValue() }); + if c.armed_waits.is_empty() && done >= c.recorded_max { + continue; + } + // (the title can decommit the cell's page at any moment: a read that cannot fault) + let mut v = 0u64; + let mem = if unsafe { crate::hle::dstorage::read_own(va as usize, &mut v as *mut u64 as *mut u8, 8) } { format!("{v:#x}") } else { "unreadable".into() }; + let armed: Vec = c.armed_waits.iter().map(|a| format!("{:#x}@q{} {} ms", a.val, queue_id(a.waiting_queue), a.armed_at.elapsed().as_millis())).collect(); + parts.push(format!( + "{va:#x}: mem {mem} done {done:#x} sub {:#x}@q{:?} rec {:#x}{} cpu {:#x}{} armed [{}]", + c.submitted_max, + c.submitted_queue.map(queue_id), + c.recorded_max, + c.recorded_by.as_ref().map_or(String::new(), |(l, at, t)| format!(" {}", recording_trace(*l, *at, t))), + c.cpu_signaled_max, + if c.non_monotonic { " non-monotonic" } else { "" }, + armed.join(", ") + )); + } + } else { + parts.push("(sync graph locked)".into()); + } + if parts.is_empty() { + "none".into() + } else { + parts.join("; ") + } +} + +/// What the GPU wait watchdog logs at a time-out, logged on request (`XCL_THREAD_DUMP_AT`), so a +/// title that stops with no time-out shows whether a fence or a queue is behind, and which +/// `Wait64BitValueX` cells are behind what was recorded for them. On a thread of its own: a lock +/// the stall holds does not hold up the next thread dump. +pub fn log_sync_state(at: &str) { + let at = at.to_string(); + let _ = std::thread::Builder::new().name("xcl-sync-state".into()).spawn(move || { + crate::xlog_info!("D3D12.X: sync state at {at}: pending title ID3D12Fences: {}", super::fence_x::pending_summary()); + crate::xlog_info!("D3D12.X: sync state at {at}: XCL's own queue waits unmet: {}", internal_waits_summary()); + crate::xlog_info!("D3D12.X: sync state at {at}: {} GPU waits armed", ARMED_GPU_WAITS.load(Ordering::Acquire)); + crate::xlog_info!("D3D12.X: sync state at {at}: Wait64 cells behind: {}", cells_behind_summary()); + }); +} + fn queue_id(q: usize) -> usize { let mut g = QUEUE_IDS.lock().unwrap(); if let Some(pos) = g.iter().position(|&x| x == q) { @@ -1679,11 +2491,16 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { if value == 0 || !va.is_multiple_of(8) { return; } - let (lty, last_q) = { + let (lty, last_q, recording) = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); s.push_write64_signal(va, value); - (s.list_type, s.last_queue) + let recording = if sync_state_tracing() { + Some(s.write64_trace.get_or_insert_with(Default::default).clone()) + } else { + None + }; + (s.list_type, s.last_queue, recording) }; let rescue: Option<(ID3D12Fence, u64, u64)> = { let mut g = SYNC_GRAPH.lock().unwrap(); @@ -1708,6 +2525,7 @@ fn note_write64_recorded(list: *mut c_void, va: u64, value: u64) { } else { if value > cell.recorded_max { cell.recorded_max = value; + cell.recorded_by = recording.map(|recording| (list as usize, Instant::now(), recording)); if lty.is_some() { cell.recorded_list_type = lty; } @@ -1823,7 +2641,7 @@ unsafe fn signal_write64_pairs(queue: *mut c_void, pairs: &[(u64, u64)]) { match action { SignalAction::Skip => {} SignalAction::GpuSignal => { - if let Err(e) = q.Signal(&fence, val) { + if let Err(e) = super::real::native_queue_signal(q, &fence, val) { crate::xlog_warn!("D3D12.X: Write64 fence Signal({va:#x}, {val:#x}) failed ({e}) – signalling on CPU"); let _ = fence.Signal(val); } @@ -1857,6 +2675,9 @@ pub(super) unsafe fn signal_write64_fences(queue: *mut c_void, lists: &[*mut c_v if WRITE64_SIGNAL_LISTS.load(Ordering::Acquire) == 0 || queue.is_null() || lists.is_empty() { return; } + for &l in lists { + trace_list(l as usize, ListEvent::Executed); + } let pairs: Vec<(u64, u64)> = { let g = LISTS.lock().unwrap(); let Some(m) = g.as_ref() else { return }; @@ -1979,7 +2800,7 @@ unsafe fn try_gpu_wait(queue: *mut c_void, w: &PendingWait, list_writes: &[(u64, (pre_ok.0, pre_ok.1, pre_ok.2, wait_seq) }; - if let Err(e) = q.Wait(&fence, w.value) { + if let Err(e) = super::real::native_queue_wait(q, &fence, w.value) { let mut g = SYNC_GRAPH.lock().unwrap(); if let Some(cell) = g.as_mut().and_then(|gr| gr.cells.get_mut(&w.va)) { if let Some(pos) = cell.armed_waits.iter().rposition(|aw| aw.val == w.value && aw.waiting_queue == q_raw && aw.wait_seq == wait_seq) { @@ -2023,7 +2844,10 @@ unsafe fn wait_all_on(queue: *mut c_void, waits: &[PendingWait], list_writes: &[ GpuWaitOutcome::Handled | GpuWaitOutcome::CycleSkip => continue, GpuWaitOutcome::FallbackCpu => {} } - if !w.wait_until_satisfied(timeout) && once(&TIMEOUTS, 40) { + let memory_stall = crate::stall::span(crate::stall::StallKind::MemorySynchronization); + let satisfied = w.wait_until_satisfied(timeout); + drop(memory_stall); + if !satisfied && once(&TIMEOUTS, 40) { let cell_diag = { let g = SYNC_GRAPH.lock().unwrap(); g.as_ref().and_then(|gr| gr.cells.get(&w.va)).map(|c| (c.recorded_max, c.submitted_max, c.non_monotonic, c.recorded_list_type.map(|t| t.0))) @@ -2089,41 +2913,120 @@ pub(super) unsafe fn cpu_writes_after(queue: *mut c_void, lists: &[*mut c_void]) super::cpu_writes::after(queue, writes); } -/// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` -/// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. -/// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are -/// bridged to GPU-side `queue.Wait` without blocking the submitter thread on the CPU. -pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { - if lists.is_empty() || PENDING_WAIT_LISTS.load(Ordering::Acquire) == 0 { - submit(lists); - return; +/// Capture every mutable per-list effect once, before any part of this submission reaches the +/// driver. Resetting or re-recording a list after this point cannot change the returned plan. +pub(super) fn submission_plan(lists: &[*mut c_void]) -> SubmissionPlan { + SubmissionPlan::capture(lists) +} + +/// Publish the effects of an already-submitted chunk in the same order as the legacy consumers. +unsafe fn submit_segment_effects(queue: *mut c_void, effects: &[SegmentEffects], needs_cpu_completion: bool) -> Option { + let texture_writes: Vec<_> = effects.iter().flat_map(|e| e.texture_writes.iter().copied()).collect(); + let texture_transitions: Vec<_> = effects.iter().flat_map(|e| e.texture_transitions.iter().copied()).collect(); + super::title_textures::publish_submission_effects(queue_identity(queue as usize), &texture_writes, &texture_transitions); + let write64_signals: Vec<(u64, u64)> = effects.iter().flat_map(|e| e.write64_signals.iter().copied()).collect(); + signal_write64_pairs(queue, &write64_signals); + + let sparse_writes: Vec<(usize, usize)> = effects.iter().flat_map(|e| e.sparse_writes.iter().copied()).collect(); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { + super::sparse::readback_after_execute(q, &sparse_writes); + } } - let per_list: Vec<(Vec, Vec<(u64, u64)>)> = { - let g = LISTS.lock().unwrap(); - lists - .iter() - .map(|&l| { - g.as_ref() - .and_then(|m| m.get(&(l as usize))) - .map(|s| (s.pending_waits.clone(), s.write64_signals.clone())) - .unwrap_or_default() - }) - .collect() + + let cpu_writes: Vec = effects.iter().flat_map(|e| e.cpu_writes.iter().cloned()).collect(); + if needs_cpu_completion { + super::cpu_writes::after_with_completion(queue, cpu_writes) + } else { + super::cpu_writes::after(queue, cpu_writes); + None + } +} + +/// Execute a plan and retain completion receipts for its deferred CPU writes. +unsafe fn execute_submission_plan_with_completions( + queue: *mut c_void, + plan: &SubmissionPlan, + external_waits: &[PendingWait], + mut submit: impl FnMut(SubmissionChunk<'_>) -> (bool, Option), +) -> (Vec, bool) { + let chunk = |start, end| SubmissionChunk { + lists: &plan.lists[start..end], + effects: &plan.effects[start..end], + traces: if plan.traces.is_empty() { &[] } else { &plan.traces[start..end] }, + needs_cpu_completion: plan.chunk_needs_cpu_completion(start, end, external_waits), }; + if !plan.has_waits { + let (submitted, completion) = submit(chunk(0, plan.lists.len())); + return (completion.into_iter().collect(), submitted); + } + let mut completions = Vec::new(); let mut start = 0usize; - for (i, (waits, list_writes)) in per_list.iter().enumerate() { - if waits.is_empty() || waits.iter().all(|w| w.is_satisfied()) { + for (i, effects) in plan.effects.iter().enumerate() { + if effects.waits.is_empty() { + continue; + } + let after_cpu_write = plan.waits_after_cpu_write[i]; + if !after_cpu_write && effects.waits.iter().all(|w| w.is_satisfied()) { continue; } if i > start { - submit(&lists[start..i]); + let (submitted, completion) = submit(chunk(start, i)); + if !submitted { + return (completions, false); + } + completions.extend(completion); + } + if after_cpu_write { + for completion in completions.drain(..) { + let _ = completion.wait(); + } } - wait_all_on(queue, waits, list_writes); + wait_all_on(queue, &effects.waits, &effects.write64_signals); start = i; } - if start < lists.len() { - submit(&lists[start..]); + if start < plan.lists.len() { + let (submitted, completion) = submit(chunk(start, plan.lists.len())); + if !submitted { + return (completions, false); + } + completions.extend(completion); } + (completions, true) +} + +pub(super) unsafe fn execute_submission_plan_until_failure_on( + queue: *mut c_void, + plan: &SubmissionPlan, + submit: impl FnMut(SubmissionChunk<'_>) -> (bool, Option), +) -> (Vec, bool) { + execute_submission_plan_with_completions(queue, plan, &[], submit) +} + +/// Execute a plan for an ordinary queue submission, retaining deferred CPU-write receipts. +pub(super) unsafe fn execute_submission_plan_with_completions_on( + queue: *mut c_void, + plan: &SubmissionPlan, + mut submit: impl FnMut(SubmissionChunk<'_>) -> Option, +) -> Vec { + execute_submission_plan_with_completions(queue, plan, &[], |chunk| (true, submit(chunk))).0 +} + +/// Execute an immutable submission plan, splitting before an unsatisfied memory wait. +pub(super) unsafe fn execute_submission_plan_on(queue: *mut c_void, plan: &SubmissionPlan, mut submit: impl FnMut(SubmissionChunk<'_>)) { + let _ = execute_submission_plan_with_completions(queue, plan, &[], |chunk| { + submit(chunk); + (true, None) + }); +} + +/// Submit `lists` through `submit`, splitting the batch before any list whose `Wait32/64BitValueX` +/// condition is not yet satisfied so earlier lists in the same batch can run on the GPU first. +/// When `queue` is non-null, monotonic 64-bit waits backed by a recorded `Write64BitValue*` are +/// bridged to GPU-side `queue.Wait` without blocking the submitter thread on the CPU. +pub(super) unsafe fn execute_with_waits_on(queue: *mut c_void, lists: &[*mut c_void], mut submit: impl FnMut(&[*mut c_void])) { + let plan = submission_plan(lists); + execute_submission_plan_on(queue, &plan, |chunk| submit(chunk.lists())); } #[cfg(test)] @@ -2150,7 +3053,7 @@ pub(super) unsafe extern "system" fn copy_memory_x(this: *mut c_void, dst: u64, if d == s && dst < src + size && src < dst + size { return warn(&N, W, format_args!("{src:#x} → {dst:#x} ({size:#x} bytes) overlap")); } - note_write(this as usize, dst, size); + note_write(this as usize, WriteProducer::InSegmentGpu, dst, size); if d == s { // one window: one buffer cannot be in COPY_SOURCE and COPY_DEST at once (#958), so the // bytes go through a scratch buffer of the list @@ -2310,7 +3213,7 @@ pub(super) unsafe fn copy_scratch_submitted(queue: *mut c_void, lists: &[*mut c_ } let (fence, value) = cache.fences.get_mut(&key)?; let next = *value + 1; - q.Signal(&*fence, next).ok()?; + super::real::native_queue_signal(q, &*fence, next).ok()?; *value = next; Some((fence.clone(), next)) })(); @@ -2408,7 +3311,7 @@ unsafe fn fill(list: *mut c_void, va: u64, size: u64, pat: [u8; 16], unit: u64, let Some(src) = pattern_buffer(list, pat, size) else { return warn(&N, what, format_args!("no pattern buffer for {pat:x?}")); }; - note_write(list as usize, va, size); + note_write(list as usize, WriteProducer::InSegmentGpu, va, size); as_copy_dest(list, d, || copy_buffer_region(list, d, off, src, 0, size)); } @@ -2449,13 +3352,14 @@ unsafe fn write(list: *mut c_void, va: u64, words: &[u32], mode: D3D12_WRITEBUFF // the title's own memory: written by the CPU once the GPU is there if super::cpu_writes::writable(va as usize, n as usize) { if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { + s.note_write(WriteProducer::CpuAfterSegment, va, n); s.cpu_writes.push(super::cpu_writes::Write::Immediate(va as usize, words.to_vec())); return; } } return warn(&N, what, format_args!("{va:#x} is not in unified memory")); }; - note_write(list as usize, va, n); + note_write(list as usize, WriteProducer::InSegmentGpu, va, n); let params: Vec = words.iter().enumerate().map(|(i, &w)| D3D12_WRITEBUFFERIMMEDIATE_PARAMETER { Dest: at + 4 * i as u64, Value: w }).collect(); let modes = vec![mode; words.len()]; type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER, *const D3D12_WRITEBUFFERIMMEDIATE_MODE); @@ -2548,7 +3452,7 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { let i = NEXT_TIMESTAMP.fetch_add(1, Ordering::Relaxed) % TIMESTAMP_SLOTS; type Resolve = unsafe extern "system" fn(*mut c_void, usize, D3D12_QUERY_TYPE, u32, u32, usize, u64); if let Some((d, off)) = uma_dst { - note_write(list as usize, va, 8); + note_write(list as usize, WriteProducer::InSegmentGpu, va, 8); pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); as_copy_dest(list, d, || pc::(list, PC_RESOLVE_QUERY_DATA)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i, 1, d, off)); } else if let Some((rb, base)) = readback { @@ -2559,6 +3463,7 @@ unsafe fn timestamp(list: *mut c_void, va: u64, what: &str) { }; let rb_raw = rb.as_raw() as usize; let off = i as u64 * 8; + s.note_write(WriteProducer::CpuAfterSegment, va, 8); s.cpu_writes.push(super::cpu_writes::Write::ReadbackU64 { va: va as usize, src: base + off as usize, _buf: rb }); drop(g); pc::(list, PC_END_QUERY)(list, heap, D3D12_QUERY_TYPE_TIMESTAMP, i); @@ -2625,32 +3530,51 @@ pub(super) unsafe fn reset_stand_in(wrapper: *mut c_void, primary: *mut c_void, Some(spare as usize) } -/// Deferred mid-list split for `Wait32/64BitValueX` recorded after a `Write64BitValue*` in the -/// same command list: closes `list` (preserving its earlier `Write64` signals on segment N) and -/// opens/reuses a sibling PC command list on the same `ID3D12CommandAllocator` as segment N+1, -/// carrying all bound D3D12 + XCL root-argument state across the split. +/// Deferred mid-list split for `Wait32/64BitValueX` that depends on a producer in the current +/// recording. Closes `list` and opens/reuses a sibling PC list on the same allocator, carrying all +/// bound D3D12 + XCL root-argument state across the split. /// /// At `ExecuteCommandLists`, `title_list::push_segments` expands the wrapper into `[seg_0, seg_1, ...]` -/// and `execute_with_waits_on` submits `seg_0` + emits `queue.Signal` for its `Write64`s BEFORE -/// emitting `queue.Wait` for `seg_1`'s `Wait64`, preserving exact Xbox chronological order with -/// zero artificial GPU cycles. -unsafe fn try_split_for_wait(list: *mut c_void) -> Option<*mut c_void> { - static ENABLED: OnceLock = OnceLock::new(); - if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { - return None; - } - let next_pc = split(list, None)?; +/// Submission runs segment N's Write64 signal or deferred CPU store before segment N+1's wait. +unsafe fn try_split_for_wait(list: *mut c_void, placement: WaitPlacement) -> Option<*mut c_void> { + let (reason, why) = match placement { + WaitPlacement::SplitAfterCpuWrite => (SegmentReason::WaitAfterCpuWrite, "CPU-after-segment write"), + WaitPlacement::SplitAfterWrite64 => { + static ENABLED: OnceLock = OnceLock::new(); + if !*ENABLED.get_or_init(|| std::env::var("XCL_SPLIT_MIDLIST_WAIT").map_or(true, |v| v.trim() != "0")) { + return None; + } + (SegmentReason::WaitAfterWrite64, "Write64") + } + _ => return None, + }; + let next_pc = split_recording(list, reason)?; static SPLITS: AtomicU64 = AtomicU64::new(0); let n = SPLITS.fetch_add(1, Ordering::Relaxed) + 1; if n <= 4 || (n.is_power_of_two() && n <= 256) { - crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after Write64 (#{n})", list_type(next_pc).0); + crate::xlog_info!("D3D12.X: split command list (type {}) around mid-list Wait after {why} (#{n})", list_type(next_pc).0); } Some(next_pc) } +fn wait_target_after_split(list: *mut c_void, placement: WaitPlacement, continuation: Option<*mut c_void>) -> Option<*mut c_void> { + match (placement, continuation) { + (_, Some(next)) => Some(next), + (WaitPlacement::SplitAfterCpuWrite, None) => None, + (WaitPlacement::SplitAfterWrite64, None) => Some(list), + _ => Some(list), + } +} + /// Gives a dispatch whose pipeline is still being built a segment of its own, recorded at the submit. -pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { - if split(list, Some(what)).is_none() { +pub(super) unsafe fn defer(list: *mut c_void, pso: usize, what: Deferred) -> bool { + // A bounded bind records now and waits for the same bound. Deferring it only adds a segment; + // thousands of these exhausted command-list memory in a retail title with a 1 ms budget. + if !defer_pipeline_wait( + super::pso_async::waits_bounded(), + || super::pso_async::need_by_submit(pso), + || split_recording(list, SegmentReason::DeferredDispatch(what)).is_some(), + ) { return false; } static N: AtomicU64 = AtomicU64::new(0); @@ -2661,8 +3585,16 @@ pub(super) unsafe fn defer(list: *mut c_void, what: Deferred) -> bool { true } -/// Builds of a submit's put-off calls that go on without the commit headroom, as a title thread's own do: about what the title's threads had in the driver at once before. -const WANTED_AT_ONCE: usize = 4; +fn defer_pipeline_wait(waits_bounded: bool, demand: impl FnOnce(), split: impl FnOnce() -> bool) -> bool { + if waits_bounded { + return false; + } + // The split can allocate and reset native objects. Let the worker and its compiler/driver + // admission run concurrently with that preparation; a failed split waits for the same build + // immediately in the caller. + demand(); + split() +} /// Records the deferred dispatches of `wrapper`'s recording, waiting for their pipelines as a bind did. pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { @@ -2671,10 +3603,7 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { let Some(&first) = segs.first() else { return }; segs.retain(|&seg| seg == first || LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(seg as usize))).is_some_and(|s| s.deferred.is_some())); let mut last: Option<*mut c_void> = None; - for (i, &seg) in segs.iter().enumerate().skip(1) { - for &ahead in segs[i..].iter().take(WANTED_AT_ONCE) { - super::bind::want_bound(ahead); - } + for &seg in segs.iter().skip(1) { let Some((what, ty, heaps)) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(seg as usize))).and_then(|s| Some((s.deferred.take()?, s.list_type?, s.bindings.heaps.clone()))) else { continue; }; @@ -2707,16 +3636,52 @@ pub(super) unsafe fn record_deferred(wrapper: *mut c_void) { real::dispatch_chain::list_follows(last as usize, seg as usize); } match what { - Deferred::Dispatch(x, y, z) => super::bind::dispatch(seg, x, y, z), + Deferred::Dispatch(x, y, z, flags) => super::bind::dispatch_flags(seg, x, y, z, flags), Deferred::Indirect(sig, max, args, args_off, count_buf, count_off) => super::bind::execute_indirect(seg, sig, max, args, args_off, count_buf, count_off), } let ext = *(seg as *const usize); - pc:: i32>(seg, PC_CLOSE)(seg); + let hr = segment_close(wrapper, seg); real::preserve_vtable(seg, ext); + if hr < 0 { + // a recording the runtime refused is not submitted: the segment leaves the recording + // (a list whose Close failed is still open and cannot be reset), its call is dropped, + // and the next one does not follow it + static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CLOSE_ERR, "deferred call", format_args!("Close failed ({hr:#x}), the call is dropped")); + super::bind::dispatch_dropped(); + if let Some(last) = last { + super::bind::pass_arena(seg, last); + } + super::title_list::drop_segment(wrapper, seg); + continue; + } last = Some(seg); } } +/// (tests) What the next native Close of a put-off segment of this wrapper does instead +/// (`segment_close`; tests run in parallel, so it is the given wrapper's only). +#[cfg(test)] +type CloseHook = Box i32 + Send>; +#[cfg(test)] +static CLOSE_HOOK: Mutex> = Mutex::new(Vec::new()); + +/// The native Close of `wrapper`'s put-off segment `p`: its HRESULT. +unsafe fn segment_close(wrapper: *mut c_void, p: *mut c_void) -> i32 { + #[cfg(test)] + { + let hook = { + let mut g = CLOSE_HOOK.lock().unwrap(); + g.iter().position(|h| h.0 == wrapper as usize).map(|i| g.remove(i).1) + }; + if let Some(hook) = hook { + return hook(p); + } + } + let _ = wrapper; + pc:: i32>(p, PC_CLOSE)(p) +} + /// The allocator `list`'s put-off calls recorded on is reset once the GPU is done with them, so /// their split dispatches' scratch does not outlive them. unsafe fn reset_own_alloc(list: *mut c_void) { @@ -2729,58 +3694,94 @@ unsafe fn reset_own_alloc(list: *mut c_void) { } } -/// Ends `list`'s segment and opens the next; with `dispatch`, a closed segment for it comes between. -unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_void> { +/// Ends `list`'s segment and opens the next, carrying its recording state across the boundary. +pub(super) unsafe fn split_recording(list: *mut c_void, reason: SegmentReason) -> Option<*mut c_void> { let wrapper = super::title_list::wrapper_of(list)?; - if !super::title_list::can_split(wrapper, 1 + dispatch.is_some() as usize) { - return None; - } let ty = list_type(list); if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return None; } - let deferred = match dispatch { - Some(what) => { + let extra_segments = reason.extra_segments(); + let deferred_what = match reason { + SegmentReason::DeferredDispatch(what) => { // (a predicated call stays in its list) let plain = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(list as usize))).is_some_and(|s| s.allocator != 0 && s.predication.is_none()); if !plain { return None; } - Some((what, deferred_segment(wrapper, list, ty)?)) + Some(what) } - None => None, + SegmentReason::WaitAfterWrite64 | SegmentReason::WaitAfterCpuWrite => None, + }; + let carry = { + let g = LISTS.lock().unwrap(); + SplitCarry::capture(g.as_ref()?.get(&(list as usize))?)? + }; + let alloc = carry.allocator; + let bound_pso = carry.bound_pso; + let depth_bias = carry.depth_bias; + let index_buffer = carry.index_buffer; + let depth_bounds = carry.depth_bounds; + let predication = carry.predication; + let pred_buf = &carry.pred_buf; + let bindings = &carry.bindings; + + let (init_pso, init_generation) = if ty == D3D12_COMMAND_LIST_TYPE_COPY { + (0, None) + } else { + super::pso_async::resolve_and_pin_if_enabled_lazy(bound_pso) }; - let (alloc, last_queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, ended_early, written_ranges, bindings) = { + let dev = device_of(list)?; + let dev_raw = dev.as_raw() as usize; + if !super::title_list::prepare_split(wrapper, extra_segments) { + return None; + } + { let mut g = LISTS.lock().unwrap(); - let s = g.as_mut()?.get_mut(&(list as usize))?; - if s.allocator == 0 { + if g.get_or_insert_with(HashMap::new).try_reserve(extra_segments).is_err() { return None; } - let active_query = s.occlusion.end_active_early(); - let ended_early = std::mem::take(&mut s.occlusion.ended_early); - let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); - ( - s.allocator, - s.last_queue, - s.bound_pso, - s.depth_bias, - s.index_buffer, - s.depth_bounds, - s.predication, - s.pred_buf.clone(), - pred_in_state, - active_query, - ended_early, - s.written_ranges.clone(), - s.bindings.clone(), - ) + } + let next_pc = reserve_closed_segment(wrapper, &dev, ty)?; + let deferred = if let Some(what) = deferred_what { + match prepare_deferred_segment(wrapper, list, ty) { + Some(seg) => Some((seg, ListState { + list_type: Some(ty), + bindings: Bindings { + heaps: bindings.heaps.clone(), + has_sampler_heap: bindings.has_sampler_heap, + shared_view_heap: bindings.shared_view_heap, + ..Default::default() + }, + deferred: Some(what), + ..Default::default() + })), + None => { + super::title_list::put_spare(wrapper, next_pc); + return None; + } + } + } else { + None }; + let mut continuation_state = carry.continuation_state(ty); + if let Some(generation) = init_generation { + continuation_state.pin_native_generation(generation); + } + let next_bindings = super::bind::prepare_split(list, next_pc, alloc); + let deferred_bindings = deferred.as_ref().map(|(seg, _)| super::bind::prepare_split(list, *seg, alloc)); - if let Some(((h, i), qty)) = active_query { + // Commit starts here: all allocation is complete and the continuation exists closed. + { + let mut g = LISTS.lock().unwrap(); + let s = g.as_mut()?.get_mut(&(list as usize))?; + carry.commit_state(s); + } + if let Some(((h, i), qty)) = carry.active_query { pc::(list, PC_END_QUERY)(list, h, qty, i); } - if pred_in_state { - if let Some(ref pb) = pred_buf { + if carry.pred_in_state { + if let Some(pb) = pred_buf { transition(list, pb.as_raw() as usize, D3D12_RESOURCE_STATE_PREDICATION, D3D12_RESOURCE_STATE_COMMON); } } @@ -2789,42 +3790,23 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let close_hr = pc:: i32>(list, PC_CLOSE)(list); real::preserve_vtable(list, ext); if close_hr < 0 { + super::title_list::fail_closed(wrapper, list, next_pc, true); + if let Some((seg, _)) = deferred { + super::title_list::put_spare(wrapper, seg); + } static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); warn(&CLOSE_ERR, "mid-list split", format_args!("Close failed ({close_hr:#x})")); return None; } - - let init_pso = if ty == D3D12_COMMAND_LIST_TYPE_COPY { - 0 - } else { - super::pso_async::resolve(bound_pso) - }; - let dev = device_of(list)?; - let dev_raw = dev.as_raw() as usize; - - let mut next_pc: Option<*mut c_void> = None; - if let Some(spare) = super::title_list::pop_spare(wrapper) { - let ext_spare = *(spare as *const usize); - let reset_hr = super::alloc_pool::reset_list(spare as usize, alloc, ty.0, |pc_alloc| { - pc:: i32>(spare, PC_RESET)(spare, pc_alloc, init_pso) - }); - real::preserve_vtable(spare, ext_spare); - if reset_hr >= 0 { - reset_copy_scratch(spare); - next_pc = Some(spare); + if !reset_reserved_segment(next_pc, alloc, ty, init_pso) { + super::title_list::fail_closed(wrapper, list, next_pc, false); + if let Some((seg, _)) = deferred { + super::title_list::put_spare(wrapper, seg); } + static RESET_ERR: AtomicU64 = AtomicU64::new(0); + warn(&RESET_ERR, "mid-list split", format_args!("continuation Reset failed")); + return None; } - let next_pc = match next_pc { - Some(p) => p, - None => match real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(alloc), init_pso) { - Some(p) => p, - None => { - static CREATE_ERR: AtomicU64 = AtomicU64::new(0); - warn(&CREATE_ERR, "mid-list split", format_args!("CreateCommandList failed")); - return None; - } - }, - }; // the next segment is a recording of its own (reset or made here, not through `cl_reset`) super::dred::reset(next_pc); @@ -2837,9 +3819,6 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ let m = g.get_or_insert_with(HashMap::new); let old = m.remove(&(next_pc as usize)); if let Some(ref o) = old { - if !o.pending_waits.is_empty() { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - } if !o.sparse_writes.is_empty() { SPARSE_WRITE_LISTS.fetch_sub(1, Ordering::AcqRel); } @@ -2849,32 +3828,13 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } m.insert( next_pc as usize, - ListState { - allocator: alloc, - list_type: Some(ty), - last_queue, - bound_pso, - depth_bias, - native_bias: DepthBias::ZERO, - pso_dirty: false, - using_fallback_pso: false, - index_buffer, - depth_bounds, - occlusion: Occlusion { active: None, ended_early }, - written_ranges, - pred_buf: pred_buf.clone(), - pred_in_state: false, - predication, - bindings: bindings.clone(), - ..Default::default() - }, + continuation_state, ); old }; drop(old_next); - super::title_textures::list_reset(next_pc as usize); - super::bind::inherit_for_split(list, next_pc, alloc); - restore_bindings(next_pc, &bindings, ty); + super::bind::install_prepared_split(next_bindings); + restore_bindings(next_pc, bindings, ty); if ty == D3D12_COMMAND_LIST_TYPE_DIRECT { let info = if bound_pso != 0 { device_x::base_depth_bias_info(bound_pso) } else { None }; @@ -2913,7 +3873,7 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } } if ty != D3D12_COMMAND_LIST_TYPE_COPY { - if let (Some(op), Some(ref pb)) = (predication, pred_buf) { + if let (Some(op), Some(pb)) = (predication, pred_buf) { let pb_raw = pb.as_raw() as usize; transition(next_pc, pb_raw, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PREDICATION); pc::(next_pc, PC_SET_PREDICATION)(next_pc, pb_raw, 0, op); @@ -2923,29 +3883,92 @@ unsafe fn split(list: *mut c_void, dispatch: Option) -> Option<*mut c_ } } - if let Some((what, seg)) = deferred { + if let Some((seg, state)) = deferred { { let mut g = LISTS.lock().unwrap(); - let s = g.get_or_insert_with(HashMap::new).entry(seg as usize).or_default(); - s.list_type = Some(ty); - s.bindings.heaps = bindings.heaps.clone(); - s.deferred = Some(what); + g.get_or_insert_with(HashMap::new).insert(seg as usize, state); } - super::bind::inherit_for_split(list, seg, alloc); + super::bind::install_prepared_split(deferred_bindings.unwrap()); super::bind::pass_arena(list, next_pc); + super::title_list::push_segment(wrapper, seg); } super::title_list::activate_segment(wrapper, list, next_pc); Some(next_pc) } -/// A closed, empty segment of `wrapper`'s recording for a dispatch recorded at the submit, on the wrapper's own allocator. -unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { +/// Reserve a known-closed continuation without associating the producer's live allocator with a +/// second recording list. A new object is opened on a private allocator and immediately closed. +unsafe fn reserve_closed_segment( + wrapper: *mut c_void, + dev: &ID3D12Device, + ty: D3D12_COMMAND_LIST_TYPE, +) -> Option<*mut c_void> { + if let Some(spare) = super::title_list::pop_spare(wrapper) { + note_reserved_closed(spare as usize, ty); + return Some(spare); + } + // CreateCommandList1 produces exactly the allocator-free closed object the transaction + // needs. Keep the older path as a compatibility fallback for devices without ID3D12Device4. + #[cfg(test)] + let close_is_hooked = CLOSE_HOOK.lock().unwrap().iter().any(|h| h.0 == wrapper as usize); + #[cfg(not(test))] + let close_is_hooked = false; + if !close_is_hooked { + if let Some(made) = real::create_closed_pc_command_list(dev.as_raw(), ty) { + note_reserved_closed(made as usize, ty); + return Some(made); + } + } + let temp: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; + if !real::is_adopted(temp.as_raw()) { + real::adopt(temp.as_raw(), real::Kind::CommandAllocator); + } + let made = real::create_raw_pc_command_list(dev.as_raw(), ty, temp.as_raw() as usize, 0)?; + let ext = *(made as *const usize); + let hr = segment_close(wrapper, made); + real::preserve_vtable(made, ext); + if hr >= 0 { + note_reserved_closed(made as usize, ty); + Some(made) + } else { + static CLOSE_ERR: AtomicU64 = AtomicU64::new(0); + warn(&CLOSE_ERR, "put-off segment", format_args!("Close failed ({hr:#x})")); + pc:: u32>(made, 2)(made); + None + } +} + +/// A closed standby must not look recordable if its Reset as the continuation later fails. +fn note_reserved_closed(list: usize, ty: D3D12_COMMAND_LIST_TYPE) { + clear_segment_state(list); + let mut g = LISTS.lock().unwrap(); + let s = g.get_or_insert_with(HashMap::new).entry(list).or_default(); + s.allocator = 0; + s.list_type = Some(ty); +} + +unsafe fn reset_reserved_segment(list: *mut c_void, alloc: usize, ty: D3D12_COMMAND_LIST_TYPE, init_pso: usize) -> bool { + let ext = *(list as *const usize); + let hr = super::alloc_pool::reset_list(list as usize, alloc, ty.0, |pc_alloc| { + pc:: i32>(list, PC_RESET)(list, pc_alloc, init_pso) + }); + real::preserve_vtable(list, ext); + if hr >= 0 { + reset_copy_scratch(list); + true + } else { + false + } +} + +/// Prepare a closed, empty dispatch segment without publishing it into the recording. +unsafe fn prepare_deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { let dev = device_of(list)?; let mut segs = Vec::new(); super::title_list::push_segments(wrapper, &mut segs); let first = *segs.first()? as usize; let own = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&first)?.own_alloc.clone()); - let own = match own { + let _own = match own { Some(a) => a, None => { let a: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).ok()?; @@ -2956,23 +3979,7 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO a } }; - let own = own.as_raw() as usize; - let emptied = |p: &*mut c_void| { - let p = *p; - let ext = *(p as *const usize); - let hr = super::alloc_pool::reset_list(p as usize, own, ty.0, |pc_alloc| pc:: i32>(p, PC_RESET)(p, pc_alloc, 0)); - real::preserve_vtable(p, ext); - hr >= 0 - }; - let p = match super::title_list::pop_spare(wrapper).filter(emptied) { - Some(p) => p, - None => real::create_raw_pc_command_list(dev.as_raw(), ty, super::alloc_pool::current(own), 0)?, - }; - let ext = *(p as *const usize); - pc:: i32>(p, PC_CLOSE)(p); - real::preserve_vtable(p, ext); - super::title_list::push_segment(wrapper, p); - Some(p) + reserve_closed_segment(wrapper, &dev, ty) } /// Record a `Wait32BitValueX` or `Wait64BitValueX` memory wait on `list`. @@ -2980,8 +3987,9 @@ unsafe fn deferred_segment(wrapper: *mut c_void, list: *mut c_void, ty: D3D12_CO /// If an earlier write in the same open list already targeted an overlapping UMA range, the /// `COMMON -> COPY_DEST -> COMMON` barrier around that write already orders subsequent work /// on the GPU, so we do not stall before submission (which would deadlock waiting on our own -/// unsubmitted list). If this list already recorded a `Write64BitValue*` to a different cell, -/// we split into a new deferred PC segment so earlier `Write64` signals run BEFORE this wait. +/// unsubmitted list). An overlapping CPU-after-segment write must instead close the producer +/// segment and complete its deferred store before this wait is evaluated. A prior `Write64` to +/// another cell keeps its existing split so its signal runs before the wait. unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, value: u64, mask: u64, what: &str) { static N: AtomicU64 = AtomicU64::new(0); let n = width as u64; @@ -3001,19 +4009,28 @@ unsafe fn wait_memory(list: *mut c_void, va: u64, width: u8, comparison: u32, va if comparison == D3D12_COMPARISON_FUNC_NEVER.0 as u32 { return warn(&N, what, format_args!("NEVER comparison at {va:#x} (skipped to avoid hang)")); } - let need_split = { + let placement = { let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(list as usize).or_default(); - if s.has_prior_write(va, n) { - return; - } - if s.write64_signals.is_empty() { - s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64: false }); - return; + let placement = s.wait_placement(va, n); + match placement { + WaitPlacement::OrderedInSegment => return, + WaitPlacement::RecordHere => { + s.push_wait(PendingWait { va, width, comparison, value, mask, after_write64: false }); + return; + } + WaitPlacement::SplitAfterCpuWrite | WaitPlacement::SplitAfterWrite64 => placement, } - true }; - let target = if need_split { try_split_for_wait(list).unwrap_or(list) } else { list }; + let continuation = try_split_for_wait(list, placement); + let Some(target) = wait_target_after_split(list, placement, continuation) else { + static SPLIT_FAILED: AtomicU64 = AtomicU64::new(0); + return warn( + &SPLIT_FAILED, + what, + format_args!("could not create a segment boundary after the deferred CPU write; the dependent wait was not recorded"), + ); + }; let mut g = LISTS.lock().unwrap(); let s = g.get_or_insert_with(HashMap::new).entry(target as usize).or_default(); let after_write64 = !s.write64_signals.is_empty(); @@ -3064,8 +4081,8 @@ pub(super) unsafe extern "system" fn set_depth_bounds_x(this: *mut c_void, min: } /// command list #78 DispatchX(x, y, z, flags) -pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, _flags: u32) { - super::bind::dispatch(this, x, y, z); +pub(super) unsafe extern "system" fn dispatch_x(this: *mut c_void, x: u32, y: u32, z: u32, flags: u32) { + super::bind::dispatch_flags(this, x, y, z, flags); } /// command list #146 console compute/UAV barrier (used by `XboxBvhBuilder.dll` between BVH @@ -3158,12 +4175,22 @@ pub(super) unsafe fn before_close(list: *mut c_void) { /// Clear active predication state when `ID3D12GraphicsCommandList::Reset` resets a recording. pub(super) fn on_pc_reset(list: *mut c_void) { reset_copy_scratch(list); - if !PREDICATION_USED.load(Ordering::Acquire) || list.is_null() { + if list.is_null() { + return; + } + let clear_predication = PREDICATION_USED.load(Ordering::Acquire); + let clear_generations = super::pso_async::rebuild_recipes_enabled(); + if !clear_predication && !clear_generations { return; } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { - s.predication = None; - s.pred_in_state = false; + if clear_generations { + s.native_generations.clear(); + } + if clear_predication { + s.predication = None; + s.pred_in_state = false; + } } } @@ -3262,10 +4289,11 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { if ty == D3D12_COMMAND_LIST_TYPE_BUNDLE { return; } - let dev_raw = device_of(this).map_or(0, |d| d.as_raw() as usize); - let (alloc, queue, bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, waits, sparse_writes) = { - let mut g = LISTS.lock().unwrap(); - let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { + let dev = device_of(this); + let dev_raw = dev.as_ref().map_or(0, |d| d.as_raw() as usize); + let (alloc, queue) = { + let g = LISTS.lock().unwrap(); + let Some(s) = g.as_ref().and_then(|m| m.get(&(this as usize))) else { if once(&NO_QUEUE, 4) { crate::xlog_info!("D3D12.X: KickoffX – list allocator unknown, deferring to Close + ExecuteCommandLists"); } @@ -3283,22 +4311,41 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { } return; }; - let active_query = s.occlusion.end_active_early(); - let waits = if s.pending_waits.is_empty() { - Vec::new() - } else { - PENDING_WAIT_LISTS.fetch_sub(1, Ordering::AcqRel); - std::mem::take(&mut s.pending_waits) + (s.allocator, q) + }; + let Some(queue_pin) = super::present::pin_queue_for_internal_work(queue) else { + return warn(&ERR, "KickoffX", format_args!("selected queue is retiring; deferring to Close + ExecuteCommandLists")); + }; + let wrapper = super::title_list::wrapper_of(this); + let standby = if let Some(wrapper) = wrapper { + let Some(dev) = dev.as_ref() else { + return warn(&ERR, "KickoffX", format_args!("could not get the command-list device for fail-closed preflight")); }; - let sparse_writes = s.clear_sparse_writes(); - let write64_signals = s.clear_write64_signals(); - s.written_ranges.clear(); - let cpu_writes = std::mem::take(&mut s.cpu_writes); + if !super::title_list::prepare_fail_closed(wrapper) { + return warn(&ERR, "KickoffX", format_args!("could not reserve fail-closed bookkeeping")); + } + let Some(standby) = reserve_closed_segment(wrapper, dev, ty) else { + return warn(&ERR, "KickoffX", format_args!("could not reserve a closed standby")); + }; + Some((wrapper, standby)) + } else { + None + }; + let (bound_pso, depth_bias, index_buffer, depth_bounds, predication, pred_buf, pred_in_state, active_query, preclose_effects, current_trace) = { + let mut g = LISTS.lock().unwrap(); + let Some(s) = g.as_mut().and_then(|m| m.get_mut(&(this as usize))) else { + if let Some((wrapper, standby)) = standby { + super::title_list::put_spare(wrapper, standby); + } + return; + }; + let active_query = s.occlusion.end_active_early(); + let preclose_effects = take_kickoff_effects_before_close(s, standby.is_some()); let pred_in_state = std::mem::replace(&mut s.pred_in_state, false); let pred_buf = s.pred_buf.as_ref().map(|r| r.as_raw() as usize); - (s.allocator, q, s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, waits, (sparse_writes, write64_signals, cpu_writes)) + let current_trace = sync_state_tracing().then(|| s.write64_trace.clone()).flatten(); + (s.bound_pso, s.depth_bias, s.index_buffer, s.depth_bounds, s.predication, pred_buf, pred_in_state, active_query, preclose_effects, current_trace) }; - let (sparse_writes, write64_signals, cpu_writes) = sparse_writes; // End any active occlusion query before Close (PC forbids closing with an open query). if let Some(((h, i), qty)) = active_query { @@ -3314,55 +4361,117 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { let close_hr = pc:: i32>(this, PC_CLOSE)(this); real::preserve_vtable(this, ext); if close_hr < 0 { + if let Some(effects) = preclose_effects { + restore_kickoff_native_generations(this as usize, effects.native_generations); + } + if let Some((wrapper, standby)) = standby { + super::title_list::fail_closed(wrapper, this, standby, true); + } return warn(&ERR, "KickoffX", format_args!("Close failed ({close_hr:#x})")); } + let effects = match preclose_effects { + Some(effects) => effects, + None => LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(this as usize))).map(take_kickoff_effects).unwrap_or(KickoffEffects { + waits: Vec::new(), sparse_writes: Vec::new(), texture_writes: Vec::new(), texture_transitions: Vec::new(), uses_shared_view_heap: false, write64_signals: Vec::new(), cpu_writes: Vec::new(), native_generations: Vec::new(), + }), + }; + let KickoffEffects { + waits, sparse_writes, texture_writes, texture_transitions, uses_shared_view_heap, + write64_signals, cpu_writes, native_generations, + } = effects; if let Some(wrapper) = super::title_list::wrapper_of(this) { record_deferred(wrapper); } - let q_raw = queue as *mut c_void; - super::title_textures::refresh(q_raw); + let q_raw = queue_pin.as_raw(); + real::prepare_title_submission(q_raw); type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); let exec: ExecFn = transmute_copy(&real::orig_fn(q_raw, PC_QUEUE_EXECUTE_COMMAND_LISTS)); - // If this list was previously split mid-recording around a `Wait64`, flush all earlier closed + // If this list was previously split mid-recording around a memory wait, flush all earlier closed // segments in exact order before submitting `this`, then resume recording on `primary`. let kickoff_split = super::title_list::reclaim_for_kickoff(this); + let mut prior_cpu_completions = Vec::new(); + let mut wait_after_cpu_write = false; + let mut gate = super::alloc_pool::SubmissionGate::default(); + let track_shared_view_epochs = super::vram::srv_tracking_enabled(); + let track_native_generation_receipts = super::pso_async::rebuild_recipes_enabled(); if let Some((_, ref prior, _)) = kickoff_split { if !prior.is_empty() { - execute_with_waits_on(q_raw, prior, |chunk| { - exec(q_raw, chunk.len() as u32, chunk.as_ptr()); - copy_scratch_submitted(q_raw, chunk); - super::alloc_pool::executed(q_raw, chunk); - signal_write64_fences(q_raw, chunk); - readback_sparse_writes(q_raw, chunk); - cpu_writes_after(q_raw, chunk); + let plan = submission_plan(prior); + wait_after_cpu_write = plan.cpu_producer_overlaps(&waits, plan.effects.len()); + let mut submitted = Vec::with_capacity(prior.len()); + let (completions, _) = execute_submission_plan_with_completions(q_raw, &plan, &waits, |chunk| { + super::queue_submit::with(q_raw as usize, || { + let lists = chunk.lists(); + if !submit_title_chunk( + &mut gate, + q_raw, + lists, + track_shared_view_epochs && chunk.uses_shared_view_heap(), + track_native_generation_receipts && chunk.has_native_generations(), + chunk.native_generations(), + || {}, + || exec(q_raw, lists.len() as u32, lists.as_ptr()), + ) { + return (false, None); + } + submitted.extend_from_slice(lists); + copy_scratch_submitted(q_raw, lists); + (true, chunk.submit_effects(q_raw)) + }) }); - super::title_textures::submitted(prior); - for &p in prior { - super::title_textures::list_reset(p as usize); + prior_cpu_completions = completions; + for &p in &submitted { + if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(p as usize))) { + s.texture_transitions.clear(); + } } } } - - if !waits.is_empty() { + if !gate.failed() && !waits.is_empty() { + if wait_after_cpu_write { + for completion in prior_cpu_completions.drain(..) { + let _ = completion.wait(); + } + } wait_all_on(q_raw, &waits, &write64_signals); } let one = [this]; - exec(q_raw, 1, one.as_ptr()); - copy_scratch_submitted(q_raw, &one); - super::alloc_pool::executed(q_raw, &one); - signal_write64_pairs(q_raw, &write64_signals); - // what ran is in the textures' states; the list records anew after its Reset below - super::title_textures::submitted(&one); - super::title_textures::list_reset(this as usize); - if !sparse_writes.is_empty() { - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { - super::sparse::readback_after_execute(q, &sparse_writes); + let current_submitted = super::queue_submit::with(q_raw as usize, || { + let submitted = submit_title_chunk( + &mut gate, + q_raw, + &one, + track_shared_view_epochs && uses_shared_view_heap, + track_native_generation_receipts && !native_generations.is_empty(), + native_generations.iter(), + || {}, + || exec(q_raw, 1, one.as_ptr()), + ); + if submitted { + if let Some(trace) = ¤t_trace { + mark_trace(trace, ListEvent::Executed); + } + copy_scratch_submitted(q_raw, &one); + super::title_textures::publish_submission_effects(queue_identity(q_raw as usize), &texture_writes, &texture_transitions); + signal_write64_pairs(q_raw, &write64_signals); + if !sparse_writes.is_empty() { + if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&q_raw) { + super::sparse::readback_after_execute(q, &sparse_writes); + } + } + super::cpu_writes::after(q_raw, cpu_writes); + } + submitted + }); + if !current_submitted { + if once(&ERR, 8) { + crate::xlog_warn!("D3D12.X: KickoffX – could not reserve submission retirement state; resetting the unsubmitted recording"); } } - super::cpu_writes::after(q_raw, cpu_writes); + // Submitted or discarded, `this` starts a new recording in the common Reset tail. let target = if let Some((primary, _, reclaimed)) = kickoff_split { let (ended_early, pred_buf_obj, bindings_copy) = { @@ -3377,6 +4486,7 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { for seg in reclaimed { super::bind::reset(seg as *mut c_void, 0, 0); clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); } if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(primary as usize))) { s.allocator = alloc; @@ -3389,10 +4499,13 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { s.pred_in_state = false; s.occlusion = Occlusion { active: None, ended_early }; s.written_ranges.clear(); + s.segment_write_producers.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); + s.texture_writes.clear(); s.cpu_writes.clear(); + s.native_generations.clear(); s.bindings = bindings_copy; } primary @@ -3401,14 +4514,22 @@ pub unsafe extern "system" fn kickoff_x(this: *mut c_void) { }; let ext_closed = *(target as *const usize); - let init_pso = super::pso_async::resolve_for_bind(bound_pso); + let (init_pso, init_generation) = super::pso_async::resolve_and_pin_if_enabled(bound_pso); let reset_hr = super::alloc_pool::reset_list(target as usize, alloc, list_type(target).0, |pc_alloc| { pc:: i32>(target, PC_RESET)(target, pc_alloc, init_pso) }); real::preserve_vtable(target, ext_closed); + settle_kickoff_standby( + standby, + reset_hr >= 0, + |wrapper, standby| super::title_list::put_spare(wrapper, standby), + |wrapper, standby, producer_broken| super::title_list::fail_closed(wrapper, target, standby, producer_broken), + ); if reset_hr < 0 { return warn(&ERR, "KickoffX", format_args!("Reset after kickoff failed ({reset_hr:#x})")); } + record_native_generation(target as usize, init_generation); + trace_list(target as usize, ListEvent::Reset); reset_copy_scratch(target); let bindings = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(target as usize))).map(|s| s.bindings.clone()); if let Some(b) = bindings { @@ -3512,7 +4633,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b (if restore { Some(s.bound_pso) } else { None }, target != s.native_bias) }; if let Some(base) = need_restore_base { - let resolved = super::pso_async::resolve_for_bind(base); + let resolved = resolve_and_record_pipeline(this as usize, base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); } if !need_native_call { @@ -3556,7 +4677,7 @@ pub(super) unsafe extern "system" fn set_depth_bias_x(this: *mut c_void, depth_b } }; if let Some(base) = restore { - let resolved = super::pso_async::resolve_for_bind(base); + let resolved = resolve_and_record_pipeline(this as usize, base); pc::(this, PC_SET_PIPELINE_STATE)(this, resolved); } } @@ -3596,7 +4717,7 @@ pub(super) unsafe fn prepare_draw(list: *mut c_void) { } None => (bound_pso, false), }; - let resolved = super::pso_async::resolve_for_bind(target); + let resolved = resolve_and_record_pipeline(list as usize, target); pc::(list, PC_SET_PIPELINE_STATE)(list, resolved); if let Some(s) = LISTS.lock().unwrap().as_mut().and_then(|m| m.get_mut(&(list as usize))) { s.using_fallback_pso = is_fallback; @@ -3675,10 +4796,41 @@ unsafe fn gpu_va(list: *mut c_void, va: u64, bytes: usize, what: &str, mirror: b static MIRRORS: Mutex> = Mutex::new(Vec::new()); /// bytes of mirrors made (never freed) static MIRROR_BYTES: AtomicU64 = AtomicU64::new(0); +/// Append generation. Incremented while `MIRRORS` is locked, before publishing a new range, so a +/// lookup that observes it refreshes under that lock and cannot retain a stale negative result. +static MIRROR_GENERATION: AtomicU64 = AtomicU64::new(0); +std::thread_local! { + /// Mirrors are append-only. A full ordered snapshot answers both hits and authoritative misses + /// without the global lock until the append generation changes. + static MIRROR_LOOKUP: std::cell::RefCell<(u64, Vec<(u64, usize, usize)>)> = const { std::cell::RefCell::new((0, Vec::new())) }; +} + +fn mirror_in(ranges: &[(u64, usize, usize)], va: u64, bytes: usize) -> Option { + ranges.iter() + .find(|&&(start, len, _)| va >= start && va + bytes as u64 <= start + len as u64) + .map(|&(start, _, mirror)| mirror + (va - start) as usize) +} + +fn cached_mirror( + cache: &mut (u64, Vec<(u64, usize, usize)>), generation: u64, va: u64, bytes: usize, + refresh: impl FnOnce() -> Vec<(u64, usize, usize)>, +) -> Option { + if cache.0 != generation { + cache.1 = refresh(); + cache.0 = generation; + } + mirror_in(&cache.1, va, bytes) +} /// Where `[va, va + bytes)` is in a mirror, if it is in one. fn mirrored(va: u64, bytes: usize) -> Option { - MIRRORS.lock().unwrap().iter().find(|&&(s, l, _)| va >= s && va + bytes as u64 <= s + l as u64).map(|&(s, _, m)| m + (va - s) as usize) + let generation = MIRROR_GENERATION.load(Ordering::Acquire); + if generation == 0 { + return None; + } + MIRROR_LOOKUP.with(|cache| { + cached_mirror(&mut cache.borrow_mut(), generation, va, bytes, || MIRRORS.lock().unwrap().clone()) + }) } /// The mirror address of the title's buffer at `va`; its range's mirror is made (and filled @@ -3710,6 +4862,9 @@ unsafe fn mirror_of(va: u64, bytes: usize, what: &str) -> Option { None => u.alloc(len, 0x1_0000)? as usize, }; std::ptr::copy_nonoverlapping(start as *const u8, p as *mut u8, len); + // Invalidate cached misses before publishing while still holding the lock. A lookup that sees + // the new generation blocks on `g` until this range is present in the refreshed snapshot. + MIRROR_GENERATION.fetch_add(1, Ordering::Release); g.push((start, len, p)); let total = MIRROR_BYTES.fetch_add(len as u64, Ordering::Relaxed) + len as u64; if g.len() <= 8 || g.len().is_power_of_two() { @@ -3836,8 +4991,9 @@ fn default_bound_heaps(view: Option, sampler: Option, current: &[u /// (a console descriptor table may be copied via raw CPU memcpy from any heap); heaps that /// kept their own shader-visible PC heap bind themselves for their local indices. Heaps whose /// own PC backing was downgraded to CPU-only cannot be bound directly. -pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec> { +pub(super) unsafe fn pc_heaps_with_shared(n: u32, heaps: *const usize) -> (Vec>, bool) { let mut view_heap = super::console_heap::global_heap(); + let shared_view = view_heap.as_ref().map(|heap| heap.as_raw() as usize); let mut sampler_heap = ensure_global_sampler_heap(); let mut out = Vec::new(); for k in 0..n as usize { @@ -3859,16 +5015,17 @@ pub(super) unsafe fn pc_heaps(n: u32, heaps: *const usize) -> Vec bool { let view = if crate::gpu::recomp::pso::heap_windows() { super::console_heap::global_heap() } else { @@ -3878,23 +5035,28 @@ pub(super) unsafe fn ensure_view_heap(this: *mut c_void) { let view_raw = view.as_ref().map(|h| h.as_raw() as usize); let sampler_raw = sampler.as_ref().map(|h| h.as_raw() as usize); if view_raw.is_none() && sampler_raw.is_none() { - return; + return false; } let mut to_bind: Option> = None; + let mut shared_view_bound = false; with_bindings(this, |b| { if let Some((next, has_sampler)) = default_bound_heaps(view_raw, sampler_raw, &b.heaps, b.has_sampler_heap) { b.heaps = next.clone(); b.has_sampler_heap = has_sampler; + b.shared_view_heap |= view_raw.is_some_and(|view| next.contains(&view)); to_bind = Some(next); } + shared_view_bound = b.shared_view_heap; }); if let Some(raw) = to_bind { pc::(this, 28)(this, raw.len() as u32, raw.as_ptr()); } + shared_view_bound } /// console #32 SetDescriptorHeaps (PC #28) pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n: u32, heaps: *const usize) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBind); const PC_SET_DESCRIPTOR_HEAPS: usize = 28; let f = pc::(this, PC_SET_DESCRIPTOR_HEAPS); if heaps.is_null() || n == 0 { @@ -3903,6 +5065,7 @@ pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n with_bindings(this, |b| { b.heaps.clear(); b.has_sampler_heap = false; + b.shared_view_heap = false; }); return f(this, n, heaps); } @@ -3915,16 +5078,18 @@ pub(super) unsafe extern "system" fn set_descriptor_heaps_x(this: *mut c_void, n with_bindings(this, |b| { b.heaps = given; b.has_sampler_heap = has_sampler; + b.shared_view_heap = false; }); return f(this, n, heaps); } - let h = pc_heaps(n, heaps); + let (h, shared_view_heap) = pc_heaps_with_shared(n, heaps); let has_sampler = h.iter().any(|x| x.as_ref().is_some_and(|h| h.GetDesc().Type == D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER)); let raw: Vec = h.iter().map(|x| x.as_ref().map_or(0, |x| x.as_raw() as usize)).collect(); let kept = raw.clone(); with_bindings(this, |b| { b.heaps = kept; b.has_sampler_heap = has_sampler; + b.shared_view_heap = shared_view_heap; }); f(this, raw.len() as u32, raw.as_ptr()) } @@ -4059,7 +5224,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 // A failed native Reset leaves the old recording alive. Do not discard its tracked state or // transfer its allocations until the driver accepts the new recording. let ext = *(this as *const usize); - let resolved = super::pso_async::resolve_for_bind(pso); + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(pso); // (the PC allocator the title's allocator stands for now: `alloc_pool`) let ty = LISTS.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize))).and_then(|s| s.list_type).map_or(-1, |t| t.0); let hr = super::alloc_pool::reset_list(this as usize, alloc, ty, |pc_alloc| { @@ -4069,6 +5234,7 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 if hr < 0 { return hr; } + trace_list(this as usize, ListEvent::Reset); reset_copy_scratch(this); reset_own_alloc(this); @@ -4085,16 +5251,21 @@ pub(super) unsafe fn reset_pc(this: *mut c_void, alloc: usize, pso: usize) -> i3 s.depth_bounds = None; s.occlusion = Occlusion::default(); s.written_ranges.clear(); + s.segment_write_producers.clear(); s.clear_sparse_writes(); s.clear_write64_signals(); s.clear_waits(); + s.texture_writes.clear(); + s.texture_transitions.clear(); + s.uses_shared_view_heap = false; s.cpu_writes.clear(); + s.native_generations.clear(); s.predication = None; s.pred_in_state = false; s.bindings = Bindings::default(); s.list_type == Some(D3D12_COMMAND_LIST_TYPE_BUNDLE) }; - super::title_textures::list_reset(this as usize); + record_native_generation(this as usize, generation); super::bind::reset(this, alloc, pso); if !is_bundle && pso != 0 { if let Some((true, static_bias)) = device_x::base_depth_bias_info(pso) { @@ -4115,6 +5286,7 @@ const PC_STATES: u32 = 0x1 | 0x2 | 0x4 | 0x8 | 0x10 | 0x20 | 0x40 | 0x80 | 0x100 /// PC ones – state bits the PC does not know are dropped (logged: the console's own), a /// transition left with nothing to do goes, aliasing barriers name placed textures pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u32, barriers: *const [u32; 8]) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailBarrier); static N: AtomicU64 = AtomicU64::new(0); if barriers.is_null() || n == 0 { return; @@ -4191,7 +5363,7 @@ pub(super) unsafe extern "system" fn resource_barrier_x(this: *mut c_void, n: u3 if super::title_textures::any() { let t: Vec<(usize, u32, D3D12_RESOURCE_STATES)> = out.iter().filter(|b| b[0] == 0).map(|b| ((b[2] as u64 | (b[3] as u64) << 32) as usize, b[4], D3D12_RESOURCE_STATES(b[6] as i32))).collect(); - super::title_textures::note_transitions(this as usize, &t); + note_texture_transitions(this as usize, &t); } if !out.is_empty() { pc::(this, PC_RESOURCE_BARRIER)(this, out.len() as u32, out.as_ptr()); @@ -4212,6 +5384,7 @@ unsafe fn is_buffer(res: usize) -> bool { /// DMA list #9 Close: as on the PC; a failure is logged (the title stops on it) pub(super) unsafe extern "system" fn dma_close_x(this: *mut c_void) -> i32 { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailListLifecycle); let ext = *(this as *const usize); let hr = pc:: i32>(this, 9)(this); real::preserve_vtable(this, ext); @@ -4250,6 +5423,11 @@ fn note_gpu_write(what: &str, va: usize, n: u64) { } pub(super) unsafe extern "system" fn copy_buffer_region_x(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); + copy_buffer_region_inner(this, dst, dst_off, src, src_off, n) +} + +unsafe fn copy_buffer_region_inner(this: *mut c_void, dst: usize, dst_off: u64, src: usize, src_off: u64, n: u64) { if super::present::trace_frame() { if let Some(a) = real::title_address(dst) { note_gpu_write("CopyBufferRegion", a + dst_off as usize, n); @@ -4284,10 +5462,16 @@ unsafe fn trace_watched_copy(what: &str, dst: usize, src: usize) { /// CopyTextureRegion(dst, x, y, z, src, box) (PC #16; DMA list #12) pub(super) unsafe extern "system" fn copy_texture_region_x(this: *mut c_void, dst: *const D3D12_TEXTURE_COPY_LOCATION, x: u32, y: u32, z: u32, src: *const D3D12_TEXTURE_COPY_LOCATION, bx: *const D3D12_BOX) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); if let Some(d) = dst.as_ref() { let r: usize = transmute_copy(&d.pResource); super::present::note_use(r, super::present::USE_COPY); - super::title_textures::note_gpu_write(r); + let sub = if d.Type == D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX { + d.Anonymous.SubresourceIndex + } else { + D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + }; + note_texture_write(this as usize, r, sub); if super::present::trace_frame() { if let Some(va) = super::title_textures::address(r) { static N: AtomicU64 = AtomicU64::new(0); @@ -4411,6 +5595,7 @@ fn uav_clear_handles(gpu: Option, cpu: Option (gpu, cpu), UavClearHandles::Pc => (gpu, cpu), @@ -4463,6 +5648,7 @@ unsafe fn trace_resolve(what: &str, dst: usize, src: usize, format: i32, extra: /// command list #19 ResolveSubresource(dst, dst sub, src, src sub, format) (PC #19) pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, dst: usize, dst_sub: u32, src: usize, src_sub: u32, format: i32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); trace_resolve("ResolveSubresource", dst, src, format, ""); pc::(this, PC_RESOLVE_SUBRESOURCE)(this, dst, dst_sub, src, src_sub, format) @@ -4472,6 +5658,7 @@ pub(super) unsafe extern "system" fn resolve_subresource_x(this: *mut c_void, ds /// mode) (PC #64) #[allow(clippy::too_many_arguments)] pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_void, dst: usize, dst_sub: u32, x: u32, y: u32, src: usize, src_sub: u32, rect: *const windows::Win32::Foundation::RECT, format: i32, mode: i32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); if super::present::trace_frame() { trace_resolve("ResolveSubresourceRegion", dst, src, format, &format!(" mode {mode} at ({x}, {y}) rect {:?}", rect.as_ref().map(|r| (r.left, r.top, r.right, r.bottom)))); @@ -4482,8 +5669,9 @@ pub(super) unsafe extern "system" fn resolve_subresource_region_x(this: *mut c_v /// CopyResource(dst, src) (PC #17; DMA list #13): buffers placed below their console address /// are copied as their own bytes (the PC resources also hold what lies before them) pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usize, src: usize) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailCopy); super::present::note_use(dst, super::present::USE_COPY); - super::title_textures::note_gpu_write(dst); + note_texture_write(this as usize, dst, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES); if super::present::trace_frame() { trace_watched_copy("CopyResource", dst, src); } @@ -4492,7 +5680,7 @@ pub(super) unsafe extern "system" fn copy_resource_x(this: *mut c_void, dst: usi return pc::(this, PC_COPY_RESOURCE)(this, dst, src); } let n = real::console_buffer(dst).or(real::console_buffer(src)).map_or(0, |b| b.1 as u64); - copy_buffer_region_x(this, dst, 0, src, 0, n); + copy_buffer_region_inner(this, dst, 0, src, 0, n); } /// command list #28 BeginQuery(heap, type, index) (PC #52) @@ -4589,10 +5777,208 @@ pub(super) unsafe extern "system" fn resolve_query_data_x(this: *mut c_void, hea pc::(this, PC_WRITE_BUFFER_IMMEDIATE)(this, params.len() as u32, params.as_ptr(), modes.as_ptr()); } -#[cfg(test)] -mod tests { - use super::*; - use std::sync::Arc; +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + + #[test] + fn generation_capture_deduplicates_and_survives_recording_reset() { + let generation = Arc::new(()); + let mut recording = Vec::new(); + push_unique(&mut recording, generation.clone(), Arc::ptr_eq); + push_unique(&mut recording, generation.clone(), Arc::ptr_eq); + assert_eq!(recording.len(), 1); + + let submission_plan = recording.clone(); + recording.clear(); + drop(generation); + assert_eq!(Arc::strong_count(&submission_plan[0]), 1, "the immutable plan must own the submitted generation"); + } + + #[test] + fn close_failure_restores_exact_generation_carriers_or_returns_them_fail_closed() { + let generation = Arc::new(()); + let mut recording = vec![generation.clone()]; + restore_unique( + Some(&mut recording), + vec![generation.clone(), generation.clone()], + Arc::ptr_eq, + ).unwrap(); + assert_eq!(recording.len(), 1, "restoring a retryable recording duplicated its exact generation"); + + let stranded = restore_unique::>(None, vec![generation.clone()], Arc::ptr_eq).unwrap_err(); + assert_eq!(stranded.len(), 1, "a missing list state dropped its fail-closed carrier"); + assert!(Arc::ptr_eq(&stranded[0], &generation)); + } + + #[test] + fn bundle_snapshot_deduplicates_into_parent_recording() { + let generation = Arc::new(()); + let bundle = vec![generation.clone()]; + let mut parent = vec![generation]; + for pin in bundle { + push_unique(&mut parent, pin, Arc::ptr_eq); + } + assert_eq!(parent.len(), 1); + } + + #[test] + fn creation_keeps_logical_allocator_separate_from_recording_backing() { + let list = 0x7e57_a101usize as *mut c_void; + let (logical, backing) = (0x7e57_a110usize, 0x7e57_a120usize); + unsafe { on_create_with_backing(list, logical, backing, 0, D3D12_COMMAND_LIST_TYPE_DIRECT) }; + + let tracked = LISTS.lock().unwrap().as_ref().unwrap()[&(list as usize)].allocator; + assert_eq!(tracked, logical); + assert_eq!(super::super::alloc_pool::recording_backing_for_test(list as usize), Some(backing)); + + on_allocator_release(logical); + assert_eq!(LISTS.lock().unwrap().as_ref().unwrap()[&(list as usize)].allocator, 0); + assert_eq!(super::super::alloc_pool::recording_backing_for_test(list as usize), Some(backing)); + + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + super::super::alloc_pool::forget_list(list as usize); + } + + #[test] + fn mirror_snapshot_keeps_order_and_refreshes_only_on_miss() { + let first = (100, 100, 1_000); + let second = (150, 100, 2_000); + let mut cache = (0, Vec::new()); + assert_eq!(cached_mirror(&mut cache, 1, 220, 10, || vec![first, second]), Some(2_070)); + // The complete ordered snapshot was retained, not just the range found above: where the + // ranges overlap, lookup still chooses the first global entry without refreshing. + assert_eq!(cached_mirror(&mut cache, 1, 160, 10, || panic!("positive hit locked")), Some(1_060)); + assert_eq!(cached_mirror(&mut cache, 1, 400, 10, || panic!("unchanged miss locked")), None); + + let third = (500, 50, 3_000); + assert_eq!(cached_mirror(&mut cache, 2, 510, 10, || vec![first, second, third]), Some(3_010)); + assert_eq!(mirror_in(&cache.1, 550, 1), None, "ranges are half-open"); + } + + /// A recorded `Wait64` cell whose page the title decommitted, or made inaccessible, is listed + /// as unreadable by the sync-state dump, which does not fault on it. + #[test] + fn the_cells_behind_summary_reads_a_decommitted_or_protected_cell_without_faulting() { + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, VirtualProtect, MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE}; + unsafe { + let mem = VirtualAlloc(std::ptr::null(), 0x2000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize; + assert_ne!(mem, 0); + let (decommitted, protected) = (mem as u64, (mem + 0x1000) as u64); + *(decommitted as *mut u64) = 7; + *(protected as *mut u64) = 7; + { + let mut g = SYNC_GRAPH.lock().unwrap(); + let gr = g.get_or_insert_with(Default::default); + for va in [decommitted, protected] { + gr.cells.insert(va, SyncCell { recorded_max: 9, ..Default::default() }); + } + } + assert_ne!(VirtualFree(mem as *mut c_void, 0x1000, MEM_DECOMMIT), 0); + let mut old = 0; + assert_ne!(VirtualProtect((mem + 0x1000) as *const c_void, 0x1000, PAGE_NOACCESS, &mut old), 0); + // (other tests take the graph too: the summary only tries the lock) + let mut s = cells_behind_summary(); + for _ in 0..200 { + if !s.contains("(sync graph locked)") { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + s = cells_behind_summary(); + } + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&decommitted); + gr.cells.remove(&protected); + } + VirtualFree(mem as *mut c_void, 0, MEM_RELEASE); + assert!(s.contains(&format!("{decommitted:#x}: mem unreadable done 0x0")), "{s}"); + assert!(s.contains(&format!("{protected:#x}: mem unreadable done 0x0")), "{s}"); + } + } + + /// A cell recorded and never submitted names the list that recorded it, and what came to that + /// recording: here a Reset (which ends it: the Release after comes to none), and no execute. + /// A recording on the list after a Reset, or on a list made at its address after a Release, + /// is another one: its execute does not come to the cell. + #[test] + fn the_cells_behind_summary_names_the_recording_list_and_what_came_to_it() { + enable_sync_state_tracing(); + let cell = Box::new([AtomicU64::new(0), AtomicU64::new(0)]); + let va = &cell[0] as *const AtomicU64 as u64; + let other = &cell[1] as *const AtomicU64 as u64; + // (an address no real list has: the box's own) + let token = Box::new(0u64); + let list = &*token as *const u64 as usize; + let summary = || { + // (other tests take the graph too: the summary only tries the lock) + for _ in 0..200 { + let s = cells_behind_summary(); + if !s.contains("(sync graph locked)") { + return s; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + panic!("the sync graph stayed locked"); + }; + let entry_of = |va: u64, s: &str| s.split("; ").find(|p| p.starts_with(&format!("{va:#x}:"))).map(str::to_string).unwrap_or_else(|| panic!("{s}")); + let entry = |s: &str| entry_of(va, s); + + note_write64_recorded(list as *mut c_void, va, 0x619); + let s = entry(&summary()); + assert!(s.contains(&format!("rec 0x619 by {list:#x} ")), "{s}"); + assert!(s.contains("(executed no, reset no, released no)"), "{s}"); + trace_list(list, ListEvent::Reset); + on_release(list); + let s = entry(&summary()); + assert!(s.contains("(executed no, reset +"), "{s}"); + assert!(s.contains(", released no)"), "{s}"); + + // a Reset, an unrelated recording on the list, and its execute + note_write64_recorded(list as *mut c_void, va, 0x61a); + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, other, 1); + let lists = [list as *mut c_void]; + let plan = submission_plan(&lists); + unsafe { execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| drop(chunk.submit_effects(std::ptr::null_mut()))) }; + let s = summary(); + assert!(entry(&s).contains("rec 0x61a by "), "{s}"); + assert!(entry(&s).contains("(executed no, reset +"), "{s}"); + assert!(entry_of(other, &s).contains("(executed +"), "{s}"); + + // a new recording (after the Reset that ends the executed one), a Release, and a list at + // the same address that records and is executed + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, va, 0x61b); + on_release(list); + note_write64_recorded(list as *mut c_void, other, 2); + let plan = submission_plan(&lists); + unsafe { execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| drop(chunk.submit_effects(std::ptr::null_mut()))) }; + let s = summary(); + assert!(entry(&s).contains("rec 0x61b by "), "{s}"); + assert!(entry(&s).contains("(executed no, reset no, released +"), "{s}"); + assert!(entry_of(other, &s).contains("(executed +"), "{s}"); + + // Planning snapshots the exact generation. A Reset and new recording before publication + // must not redirect the old submission's Executed event to the new recording. + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, va, 0x61c); + let captured = submission_plan(&lists); + trace_list(list, ListEvent::Reset); + note_write64_recorded(list as *mut c_void, other, 3); + unsafe { execute_submission_plan_on(std::ptr::null_mut(), &captured, |chunk| drop(chunk.submit_effects(std::ptr::null_mut()))) }; + let s = summary(); + assert!(entry(&s).contains("rec 0x61c by "), "{s}"); + assert!(entry(&s).contains("(executed +") && entry(&s).contains(", reset +"), "{s}"); + assert!(entry_of(other, &s).contains("rec 0x3 by "), "{s}"); + assert!(entry_of(other, &s).contains("(executed no, reset no, released no)"), "{s}"); + + if let Some(gr) = SYNC_GRAPH.lock().unwrap().as_mut() { + gr.cells.remove(&va); + gr.cells.remove(&other); + } + on_release(list); + } /// An internal wait shows in the watchdog's summary while its fence is short of the value, /// and is gone from it once the fence gets there. @@ -4764,7 +6150,7 @@ mod tests { Format: DXGI_FORMAT_R32_UINT, }); s.depth_bounds = Some((0.25, 0.75)); - s.written_ranges.push((0x6000, 0x6010)); + s.written_ranges.insert(WriteProducer::InSegmentGpu, 0x6000, 0x10); } super::super::bind::seed_reset_state_for_test(list, 0x111, 0x222, vec![0x4444]); RESET_TEST_REPLACEMENT_VT.store(replacement as u64, Ordering::SeqCst); @@ -4782,7 +6168,7 @@ mod tests { assert!(s.pso_dirty && s.using_fallback_pso); assert_eq!(s.index_buffer.as_ref().unwrap().BufferLocation, 0x5000); assert_eq!(s.depth_bounds, Some((0.25, 0.75))); - assert_eq!(s.written_ranges, vec![(0x6000, 0x6010)]); + assert_eq!(s.written_ranges.in_segment_gpu.ranges, BTreeMap::from([(0x6000, 0x6010)])); } assert_eq!( super::super::bind::reset_state_for_test(list), @@ -4939,7 +6325,7 @@ mod tests { #[test] fn written_ranges_detect_same_list_overlap() { let mut s = ListState::default(); - s.note_write(0x1000, 8); + s.note_write(WriteProducer::InSegmentGpu, 0x1000, 8); assert!(s.has_prior_write(0x1000, 4)); assert!(s.has_prior_write(0x1004, 4)); assert!(s.has_prior_write(0x0FFC, 8)); @@ -4947,6 +6333,687 @@ mod tests { assert!(!s.has_prior_write(0x0FF8, 8)); } + #[test] + fn write_producer_ranges_keep_overlapping_kinds_separate() { + let mut s = ListState::default(); + s.note_write(WriteProducer::InSegmentGpu, 0x1000, 0x10); + s.note_write(WriteProducer::CpuAfterSegment, 0x1008, 0x10); + + assert!(s.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x1008, 8)); + assert!(!s.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x1010, 8)); + assert!(s.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x1010, 8)); + assert!(!s.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x1000, 8)); + assert!(s.has_prior_write(0x1008, 8)); + assert!(!s.has_prior_write(0x1010, 8), "deferred CPU writes do not change wait policy in this wave"); + } + + #[test] + fn wait_placement_distinguishes_cpu_gpu_and_write64_producers() { + let mut s = ListState::default(); + assert_eq!(s.wait_placement(0x1000, 8), WaitPlacement::RecordHere); + + s.note_write(WriteProducer::CpuAfterSegment, 0x2000, 8); + assert_eq!(s.wait_placement(0x1000, 8), WaitPlacement::RecordHere, "an unrelated CPU write does not split"); + assert_eq!(s.wait_placement(0x2000, 8), WaitPlacement::SplitAfterCpuWrite); + + s.note_write(WriteProducer::InSegmentGpu, 0x3000, 8); + assert_eq!(s.wait_placement(0x3000, 8), WaitPlacement::OrderedInSegment); + s.note_write(WriteProducer::CpuAfterSegment, 0x3004, 4); + assert_eq!(s.wait_placement(0x3000, 8), WaitPlacement::SplitAfterCpuWrite, "CPU completion wins for mixed overlapping producers"); + + s.write64_signals.push((0x4000, 1)); + assert_eq!(s.wait_placement(0x5000, 8), WaitPlacement::SplitAfterWrite64); + assert_eq!(s.wait_placement(0x3000, 4), WaitPlacement::OrderedInSegment, "GPU overlap keeps the existing Write64 behavior"); + } + + #[test] + fn failed_cpu_wait_split_never_reuses_the_producer_segment() { + let producer = 0x7ffe_1801usize as *mut c_void; + let continuation = 0x7ffe_1802usize as *mut c_void; + assert_eq!(wait_target_after_split(producer, WaitPlacement::SplitAfterCpuWrite, Some(continuation)), Some(continuation)); + assert_eq!(wait_target_after_split(producer, WaitPlacement::SplitAfterCpuWrite, None), None); + assert_eq!( + wait_target_after_split(producer, WaitPlacement::SplitAfterWrite64, None), + Some(producer), + "keep the existing Write64 fallback" + ); + } + + #[test] + fn recorded_writes_merge_ascending_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1008, 8); + writes.insert(0x1010, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018)])); + } + + #[test] + fn recorded_writes_merge_descending_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1010, 8); + writes.insert(0x1008, 8); + writes.insert(0x1000, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018)])); + } + + #[test] + fn recorded_writes_merge_adjacent_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 4); + writes.insert(0x1008, 4); + writes.insert(0x1004, 4); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x100c)])); + } + + #[test] + fn recorded_writes_merge_overlapping_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1008, 0x10); + writes.insert(0x1000, 0x10); + writes.insert(0x1004, 0x20); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1024)])); + } + + #[test] + fn recorded_writes_keep_disjoint_ranges() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1020, 8); + writes.insert(0x1040, 8); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1008), (0x1020, 0x1028), (0x1040, 0x1048)])); + } + + #[test] + fn recorded_writes_handle_thousands_in_reverse_order() { + let mut writes = RecordedWrites::default(); + for i in (0..4096u64).rev() { + writes.insert(0x1000 + i * 16, 8); + } + assert_eq!(writes.ranges.len(), 4096); + for i in 0..4096u64 { + let va = 0x1000 + i * 16; + assert!(writes.overlaps(va, 8)); + assert!(!writes.overlaps(va + 8, 8)); + } + } + + #[test] + fn recorded_writes_preserve_gaps_when_bridging_neighbors() { + let mut writes = RecordedWrites::default(); + writes.insert(0x1000, 8); + writes.insert(0x1010, 8); + writes.insert(0x1020, 8); + assert!(!writes.overlaps(0x1008, 8)); + assert!(!writes.overlaps(0x1018, 8)); + + writes.insert(0x1008, 8); + assert!(writes.overlaps(0x1008, 8)); + assert!(!writes.overlaps(0x1018, 8)); + assert_eq!(writes.ranges, BTreeMap::from([(0x1000, 0x1018), (0x1020, 0x1028)])); + } + + #[test] + fn submission_plan_preserves_segment_and_effect_order() { + let lists = [0x7ffe_1001usize as *mut c_void, 0x7ffe_1002usize as *mut c_void, 0x7ffe_1003usize as *mut c_void]; + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for (i, &list) in lists.iter().enumerate() { + m.insert( + list as usize, + ListState { + write64_signals: vec![(0x1000 + i as u64, 10 + i as u64)], + sparse_writes: vec![(0x2000 + i, 4 + i)], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x2500 + i, generation: 20 + i as u64, subresource: i as u32 }], + texture_transitions: vec![super::super::title_textures::Transition { + res: 0x2600 + i, + generation: 30 + i as u64, + subresource: i as u32, + after: D3D12_RESOURCE_STATE_COPY_DEST, + }], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x3000 + i, vec![i as u32])], + ..Default::default() + }, + ); + } + } + + let plan = SubmissionPlan::capture(&lists); + { + let mut g = LISTS.lock().unwrap(); + let m = g.as_mut().unwrap(); + for &list in &lists { + m.remove(&(list as usize)); + } + } + + assert_eq!(plan.lists, lists); + for (i, effects) in plan.effects.iter().enumerate() { + assert_eq!(effects.write64_signals, vec![(0x1000 + i as u64, 10 + i as u64)]); + assert_eq!(effects.sparse_writes, vec![(0x2000 + i, 4 + i)]); + assert_eq!(effects.texture_writes, vec![super::super::title_textures::GpuWrite { res: 0x2500 + i, generation: 20 + i as u64, subresource: i as u32 }]); + assert_eq!(effects.texture_transitions.iter().map(|t| t.res).collect::>(), vec![0x2600 + i]); + match effects.cpu_writes.as_slice() { + [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x3000 + i, &[i as u32][..])), + _ => panic!("unexpected CPU write snapshot"), + } + } + } + + #[test] + fn submission_plan_keeps_shared_view_use_after_rerecord() { + let list = 0x7ffe_1901usize as *mut c_void; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + list as usize, + ListState { uses_shared_view_heap: true, ..Default::default() }, + ); + let plan = SubmissionPlan::capture(&[list]); + LISTS.lock().unwrap().as_mut().unwrap().get_mut(&(list as usize)).unwrap().uses_shared_view_heap = false; + + let mut captured = false; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| captured = chunk.uses_shared_view_heap()); + } + assert!(captured, "the immutable plan owns the submitted recording's flag"); + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + + #[test] + fn console_replay_registers_the_physical_list_until_release() { + let pc = 0x7ffe_1981usize as *mut c_void; + assert!(!has_list_state(pc as usize)); + unsafe { on_console_list_create(pc, 0xa110, 0, D3D12_COMMAND_LIST_TYPE_COMPUTE) }; + note_shared_view_heap_use(pc); + + let plan = SubmissionPlan::capture(&[pc]); + let mut captured = false; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| captured = chunk.uses_shared_view_heap()); + } + assert!(captured, "the plan uses the physical PC list mapped at queue submission"); + + on_release(pc as usize); + assert!(!has_list_state(pc as usize), "the physical list's final Release removes its state"); + } + + #[test] + fn clearing_a_reused_segment_clears_shared_view_use() { + let list = 0x7ffe_1a01usize; + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert( + list, + ListState { uses_shared_view_heap: true, ..Default::default() }, + ); + clear_segment_state(list); + + let mut g = LISTS.lock().unwrap(); + assert!(!g.as_ref().unwrap()[&list].uses_shared_view_heap); + g.as_mut().unwrap().remove(&list); + } + + #[test] + fn kickoff_moves_shared_view_use_to_the_finished_segment() { + let mut state = ListState { uses_shared_view_heap: true, ..Default::default() }; + let effects = take_kickoff_effects(&mut state); + assert!(effects.uses_shared_view_heap); + assert!(!state.uses_shared_view_heap, "the continuing recording starts a new segment"); + assert!(!take_kickoff_effects(&mut state).uses_shared_view_heap); + } + + #[test] + fn execute_bundle_use_survives_bundle_reset() { + let (parent, bundle) = (0x7ffe_1b01usize, 0x7ffe_1b02usize); + let mut states = HashMap::from([ + (parent, ListState::default()), + (bundle, ListState { uses_shared_view_heap: true, ..Default::default() }), + ]); + propagate_bundle_shared_view_use(&mut states, parent, bundle); + states.get_mut(&bundle).unwrap().uses_shared_view_heap = false; + assert!(states[&parent].uses_shared_view_heap); + + propagate_bundle_shared_view_use(&mut states, parent, bundle); + assert!(states[&parent].uses_shared_view_heap, "executing an unused bundle cannot clear prior use"); + } + + #[test] + fn queue_identity_changes_when_a_raw_address_is_reused() { + let raw = 0x7ffe_1801usize; + on_queue_create(raw, 0x2000, D3D12_COMMAND_LIST_TYPE_DIRECT); + let first = queue_identity(raw).unwrap(); + on_queue_release(raw); + on_queue_create(raw, 0x2000, D3D12_COMMAND_LIST_TYPE_DIRECT); + let second = queue_identity(raw).unwrap(); + assert_eq!((first.raw, second.raw), (raw, raw)); + assert_ne!(first.generation, second.generation); + on_queue_release(raw); + } + + #[test] + fn submission_plan_is_isolated_from_reset_and_rerecord() { + let list = 0x7ffe_2001usize as *mut c_void; + let old_wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 4, mask: u64::MAX, after_write64: true }; + { + let mut g = LISTS.lock().unwrap(); + let mut state = ListState { + pending_waits: vec![old_wait], + write64_signals: vec![(0x4000, 4)], + sparse_writes: vec![(0x5000, 8)], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x5500, generation: 4, subresource: 2 }], + texture_transitions: vec![super::super::title_textures::Transition { + res: 0x5600, + generation: 4, + subresource: 2, + after: D3D12_RESOURCE_STATE_COPY_SOURCE, + }], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x6000, vec![4])], + ..Default::default() + }; + state.note_write(WriteProducer::InSegmentGpu, 0x4100, 8); + state.note_write(WriteProducer::CpuAfterSegment, 0x4200, 8); + g.get_or_insert_with(HashMap::new).insert(list as usize, state); + } + let plan = SubmissionPlan::capture(&[list]); + + { + let mut g = LISTS.lock().unwrap(); + let state = g.as_mut().unwrap().get_mut(&(list as usize)).unwrap(); + state.pending_waits = vec![PendingWait { value: 9, ..old_wait }]; + state.write64_signals = vec![(0x4000, 9)]; + state.sparse_writes = vec![(0x7000, 16)]; + state.texture_writes = vec![super::super::title_textures::GpuWrite { res: 0x7500, generation: 9, subresource: 3 }]; + state.texture_transitions = vec![super::super::title_textures::Transition { + res: 0x7600, + generation: 9, + subresource: 3, + after: D3D12_RESOURCE_STATE_RENDER_TARGET, + }]; + state.cpu_writes = vec![super::super::cpu_writes::Write::Immediate(0x8000, vec![9])]; + state.written_ranges.clear(); + state.segment_write_producers.clear(); + state.note_write(WriteProducer::CpuAfterSegment, 0x4300, 8); + } + + let effects = &plan.effects[0]; + assert_eq!(effects.waits, vec![old_wait]); + assert_eq!(effects.write64_signals, vec![(0x4000, 4)]); + assert_eq!(effects.sparse_writes, vec![(0x5000, 8)]); + assert_eq!(effects.texture_writes, vec![super::super::title_textures::GpuWrite { res: 0x5500, generation: 4, subresource: 2 }]); + assert_eq!(effects.texture_transitions, vec![super::super::title_textures::Transition { + res: 0x5600, + generation: 4, + subresource: 2, + after: D3D12_RESOURCE_STATE_COPY_SOURCE, + }]); + assert!(effects.producer_overlaps(WriteProducer::InSegmentGpu, 0x4100, 8)); + assert!(effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4200, 8)); + assert!(!effects.producer_overlaps(WriteProducer::CpuAfterSegment, 0x4300, 8)); + match effects.cpu_writes.as_slice() { + [super::super::cpu_writes::Write::Immediate(va, words)] => assert_eq!((*va, words.as_slice()), (0x6000, &[4][..])), + _ => panic!("unexpected CPU write snapshot"), + } + LISTS.lock().unwrap().as_mut().unwrap().remove(&(list as usize)); + } + + #[test] + fn submission_plan_prepares_prior_cpu_write_dependencies() { + let lists = [0x7ffe_2401usize as *mut c_void, 0x7ffe_2402usize as *mut c_void, 0x7ffe_2403usize as *mut c_void, 0x7ffe_2404usize as *mut c_void]; + let wait = |va| PendingWait { va, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + let mut states: Vec = (0..4).map(|_| ListState::default()).collect(); + states[0].note_write(WriteProducer::CpuAfterSegment, 0x1000, 8); + states[1].pending_waits.push(wait(0x1000)); + states[2].note_write(WriteProducer::CpuAfterSegment, 0x2000, 8); + states[2].pending_waits.push(wait(0x2000)); + states[3].pending_waits.push(wait(0x2000)); + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + for (&list, state) in lists.iter().zip(states) { + m.insert(list as usize, state); + } + } + let plan = SubmissionPlan::capture(&lists); + assert_eq!(plan.waits_after_cpu_write, vec![false, true, false, true], "same-segment producers must not satisfy their own wait"); + let mut g = LISTS.lock().unwrap(); + for list in lists { + g.as_mut().unwrap().remove(&(list as usize)); + } + } + + #[test] + fn empty_submission_plan_uses_the_lock_free_fast_path() { + let lists_guard = LISTS.lock().unwrap(); + let plan = SubmissionPlan::capture(&[]); + drop(lists_guard); + assert!(plan.lists.is_empty() && plan.effects.is_empty() && plan.waits_after_cpu_write.is_empty() && !plan.has_waits); + + let mut submitted = 0; + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| { + assert!(chunk.lists().is_empty()); + submitted += 1; + }); + } + assert_eq!(submitted, 1); + } + + #[test] + fn nonempty_no_wait_plan_loop_does_not_index_empty_dependencies() { + let list = 0x7ffe_2601usize as *mut c_void; + let mut plan = SubmissionPlan::capture(&[list]); + assert!(plan.waits_after_cpu_write.is_empty()); + // Exercise the loop independently of capture's no-wait early-return flag. + plan.has_waits = true; + let mut submitted = Vec::new(); + unsafe { + execute_submission_plan_on(std::ptr::null_mut(), &plan, |chunk| submitted.push(chunk.lists().to_vec())); + } + assert_eq!(submitted, vec![vec![list]]); + } + + #[test] + fn cpu_producer_completion_precedes_the_continuation_wait() { + let producer = 0x7ffe_2801usize as *mut c_void; + let continuation = 0x7ffe_2802usize as *mut c_void; + let cell = Box::new(AtomicU64::new(1)); + let va = &*cell as *const AtomicU64 as u64; + { + let mut g = LISTS.lock().unwrap(); + let m = g.get_or_insert_with(HashMap::new); + let mut first = ListState::default(); + first.note_write(WriteProducer::CpuAfterSegment, va, 8); + first.texture_transitions.push(super::super::title_textures::Transition { + res: 0x8100, + generation: 1, + subresource: 0, + after: D3D12_RESOURCE_STATE_COPY_SOURCE, + }); + m.insert(producer as usize, first); + m.insert( + continuation as usize, + ListState { + pending_waits: vec![PendingWait { + va, + width: 8, + comparison: D3D12_COMPARISON_FUNC_GREATER_EQUAL.0 as u32, + value: 1, + mask: u64::MAX, + after_write64: false, + }], + texture_transitions: vec![super::super::title_textures::Transition { + res: 0x8200, + generation: 1, + subresource: 0, + after: D3D12_RESOURCE_STATE_COPY_DEST, + }], + ..Default::default() + }, + ); + } + let plan = SubmissionPlan::capture(&[producer, continuation]); + { + let mut g = LISTS.lock().unwrap(); + let m = g.as_mut().unwrap(); + m.remove(&(producer as usize)); + m.remove(&(continuation as usize)); + } + assert!(plan.effects[0].producer_overlaps(WriteProducer::CpuAfterSegment, va, 8)); + assert!(!plan.effects[1].producer_overlaps(WriteProducer::CpuAfterSegment, va, 8)); + assert_eq!(plan.waits_after_cpu_write, vec![false, true]); + assert!(plan.chunk_needs_cpu_completion(0, 1, &[])); + assert!(!plan.chunk_needs_cpu_completion(1, 2, &[])); + let unrelated = PendingWait { va: va + 8, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + assert!(!SubmissionPlan { + lists: vec![producer], + effects: vec![plan.effects[0].clone()], + traces: Vec::new(), + waits_after_cpu_write: Vec::new(), + has_waits: false, + } + .chunk_needs_cpu_completion(0, 1, &[unrelated])); + + let completed = Arc::new(AtomicBool::new(false)); + let mut chunks = Vec::new(); + let mut transition_chunks = Vec::new(); + unsafe { + let leftovers = execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |chunk| { + let lists = chunk.lists().to_vec(); + chunks.push(lists.clone()); + transition_chunks.push(chunk.effects.iter().flat_map(|e| &e.texture_transitions).map(|t| t.res).collect::>()); + if lists == vec![producer] { + assert!(chunk.needs_cpu_completion()); + let (receipt, done) = super::super::cpu_writes::completion_pair_for_test(); + let completed = completed.clone(); + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(20)); + completed.store(true, Ordering::Release); + let _ = done.send(()); + }); + (true, Some(receipt)) + } else { + assert!(!chunk.needs_cpu_completion()); + assert!(completed.load(Ordering::Acquire), "the CPU producer must complete before the wait segment is submitted"); + (true, None) + } + }).0; + assert!(leftovers.is_empty()); + } + assert_eq!(chunks, vec![vec![producer], vec![continuation]]); + assert_eq!(transition_chunks, vec![vec![0x8100], vec![0x8200]], "wait splitting keeps transition effects with their physical segment"); + + let mut callbacks = 0; + let completed_all = unsafe { + execute_submission_plan_with_completions(std::ptr::null_mut(), &plan, &[], |_| { + callbacks += 1; + (false, None) + }) + .1 + }; + assert!(!completed_all); + assert_eq!(callbacks, 1, "a failed first chunk suppresses later waits and submissions"); + } + + #[test] + fn segment_reasons_keep_the_existing_segment_costs() { + assert_eq!(SegmentReason::WaitAfterWrite64.extra_segments(), 1); + assert_eq!(SegmentReason::WaitAfterCpuWrite.extra_segments(), 1); + let deferred = SegmentReason::DeferredDispatch(Deferred::Dispatch(1, 2, 3, 0x8020)); + let SegmentReason::DeferredDispatch(Deferred::Dispatch(x, y, z, flags)) = &deferred else { unreachable!() }; + assert_eq!((*x, *y, *z, *flags), (1, 2, 3, 0x8020), "deferred replay retains DispatchX flags"); + assert_eq!(deferred.extra_segments(), 2); + } + + #[test] + fn bounded_wait_skips_defer_and_unbounded_demand_precedes_split() { + let demanded = std::cell::Cell::new(0); + let mut splits = 0; + assert!(!defer_pipeline_wait(true, || demanded.set(demanded.get() + 1), || { splits += 1; true })); + assert_eq!(demanded.get(), 0); + assert_eq!(splits, 0); + assert!(defer_pipeline_wait(false, || demanded.set(demanded.get() + 1), || { + assert_eq!(demanded.get(), 1, "pipeline demand must be visible before split preparation"); + splits += 1; + true + })); + assert_eq!(demanded.get(), 1); + assert_eq!(splits, 1, "the default still defers to the submit"); + } + + #[test] + fn failed_split_preflight_does_not_consume_recording_state() { + let query = (0x7000, 2); + let mut state = ListState { pred_in_state: true, ..Default::default() }; + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + assert!(SplitCarry::capture(&state).is_none()); + assert!(state.pred_in_state); + assert!(state.occlusion.active.is_some()); + assert!(state.occlusion.ended_early.is_empty()); + } + + #[test] + fn reserved_closed_standby_cannot_kickoff_stale_recording_state() { + let list = 0x7ffe_2a01usize; + let wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + let mut state = ListState { + allocator: 0xa110, + list_type: Some(D3D12_COMMAND_LIST_TYPE_COMPUTE), + pending_waits: vec![wait], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x4800, generation: 2, subresource: 0 }], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x5000, vec![1])], + ..Default::default() + }; + state.segment_write_producers.insert(WriteProducer::CpuAfterSegment, 0x5000, 4); + LISTS.lock().unwrap().get_or_insert_with(HashMap::new).insert(list, state); + + note_reserved_closed(list, D3D12_COMMAND_LIST_TYPE_DIRECT); + + let mut g = LISTS.lock().unwrap(); + let state = &g.as_ref().unwrap()[&list]; + assert_eq!(state.allocator, 0, "KickoffX must take its allocator-unknown no-op path"); + assert_eq!(state.list_type, Some(D3D12_COMMAND_LIST_TYPE_DIRECT)); + assert!(state.pending_waits.is_empty() && state.texture_writes.is_empty() && state.cpu_writes.is_empty() && state.segment_write_producers.is_empty()); + g.as_mut().unwrap().remove(&list); + } + + #[test] + fn close_failure_keeps_effects_and_query_bookkeeping_on_the_producer() { + let query = (0x7100, 3); + let wait = PendingWait { va: 0xd440, width: 8, comparison: 7, value: 5, mask: u64::MAX, after_write64: false }; + let mut state = ListState { allocator: 0xa110, pending_waits: vec![wait], ..Default::default() }; + state.written_ranges.insert(WriteProducer::CpuAfterSegment, 0x3000, 8); + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + let carry = SplitCarry::capture(&state).unwrap(); + carry.commit_state(&mut state); + assert!(state.occlusion.active.is_none()); + assert_eq!(state.occlusion.ended_early, vec![query]); + assert_eq!(state.pending_waits.len(), 1); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x3000, 8)); + } + + #[test] + fn wrapper_kickoff_defers_effect_consumption_until_close_succeeds() { + let wait = PendingWait { va: 0x4000, width: 8, comparison: 7, value: 1, mask: u64::MAX, after_write64: false }; + let mut state = ListState { + pending_waits: vec![wait], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0x4800, generation: 3, subresource: 1 }], + cpu_writes: vec![super::super::cpu_writes::Write::Immediate(0x5000, vec![1])], + ..Default::default() + }; + state.note_write(WriteProducer::CpuAfterSegment, 0x5000, 4); + + assert!(take_kickoff_effects_before_close(&mut state, true).is_none()); + assert_eq!(state.pending_waits, vec![wait]); + assert_eq!(state.texture_writes.len(), 1); + assert_eq!(state.cpu_writes.len(), 1); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, 0x5000, 4)); + assert!(state.segment_write_producers.overlaps(WriteProducer::CpuAfterSegment, 0x5000, 4)); + + let effects = take_kickoff_effects_before_close(&mut state, false).unwrap(); + assert_eq!(effects.waits, vec![wait]); + assert_eq!(effects.texture_writes.len(), 1); + assert_eq!(effects.cpu_writes.len(), 1); + assert!(state.pending_waits.is_empty() && state.texture_writes.is_empty() && state.cpu_writes.is_empty()); + assert!(state.written_ranges.is_empty() && state.segment_write_producers.is_empty()); + } + + #[test] + fn kickoff_standby_ownership_settles_only_after_target_reset() { + use std::cell::Cell; + let returned = Cell::new(None); + let failed = Cell::new(None); + settle_kickoff_standby( + Some((0x7100usize, 0x7200usize)), + true, + |w, s| returned.set(Some((w, s))), + |w, s, producer_broken| failed.set(Some((w, s, producer_broken))), + ); + assert_eq!(returned.get(), Some((0x7100, 0x7200))); + assert_eq!(failed.get(), None); + + returned.set(None); + settle_kickoff_standby( + Some((0x7300usize, 0x7400usize)), + false, + |w, s| returned.set(Some((w, s))), + |w, s, producer_broken| failed.set(Some((w, s, producer_broken))), + ); + assert_eq!(returned.get(), None); + assert_eq!(failed.get(), Some((0x7300, 0x7400, false))); + + failed.set(None); + settle_kickoff_standby( + None::<(usize, usize)>, + false, + |w, s| returned.set(Some((w, s))), + |w, s, producer_broken| failed.set(Some((w, s, producer_broken))), + ); + assert_eq!(returned.get(), None); + assert_eq!(failed.get(), None); + } + + #[test] + fn split_carry_recreates_the_continuation_state() { + let query = (0x7100, 3); + let earlier_query = (0x7000, 2); + let mut state = ListState { + allocator: 0xa110, + list_type: Some(D3D12_COMMAND_LIST_TYPE_DIRECT), + last_queue: Some(0x9000), + bound_pso: 0xb220, + depth_bias: Some(DepthBias::new(-2.5, 0.25, 4.0)), + native_bias: DepthBias::new(-1.0, 1.0, 1.0), + pso_dirty: true, + using_fallback_pso: true, + index_buffer: Some(D3D12_INDEX_BUFFER_VIEW { BufferLocation: 0xc330, SizeInBytes: 24, Format: DXGI_FORMAT_R32_UINT }), + depth_bounds: Some((0.2, 0.8)), + pred_in_state: true, + predication: Some(D3D12_PREDICATION_OP_NOT_EQUAL_ZERO), + pending_waits: vec![PendingWait { va: 0xd440, width: 8, comparison: 7, value: 5, mask: u64::MAX, after_write64: false }], + write64_signals: vec![(0xe550, 6)], + sparse_writes: vec![(0xf660, 8)], + texture_writes: vec![super::super::title_textures::GpuWrite { res: 0xf770, generation: 5, subresource: 0 }], + bindings: Bindings { heaps: vec![0x1010, 0x2020], topology: Some(4), stencil: Some(9), ..Default::default() }, + ..Default::default() + }; + state.written_ranges.insert(WriteProducer::InSegmentGpu, 0x3000, 0x20); + state.occlusion.ended_early.push(earlier_query); + assert!(state.occlusion.begin(query, D3D12_QUERY_TYPE_OCCLUSION).is_none()); + + let carry = SplitCarry::capture(&state).unwrap(); + assert!(state.pred_in_state && state.occlusion.active.is_some(), "preflight must not mutate the producer"); + assert_eq!(state.occlusion.ended_early, vec![earlier_query]); + carry.commit_state(&mut state); + assert!(!state.pred_in_state && state.occlusion.active.is_none()); + assert_eq!(state.occlusion.ended_early, vec![earlier_query, query]); + state.bindings.heaps.clear(); + state.written_ranges.clear(); + let continued = carry.continuation_state(D3D12_COMMAND_LIST_TYPE_DIRECT); + + assert_eq!(carry.active_query, Some((query, D3D12_QUERY_TYPE_OCCLUSION))); + assert_eq!(continued.allocator, 0xa110); + assert_eq!(continued.last_queue, Some(0x9000)); + assert_eq!(continued.bound_pso, 0xb220); + assert_eq!(continued.depth_bias, Some(DepthBias::new(-2.5, 0.25, 4.0))); + assert_eq!(continued.native_bias, DepthBias::ZERO); + assert!(!continued.pso_dirty && !continued.using_fallback_pso); + assert_eq!(continued.index_buffer.as_ref().unwrap().BufferLocation, 0xc330); + assert_eq!(continued.depth_bounds, Some((0.2, 0.8))); + assert_eq!(continued.predication, Some(D3D12_PREDICATION_OP_NOT_EQUAL_ZERO)); + assert!(!continued.pred_in_state); + assert_eq!(continued.occlusion.ended_early, vec![earlier_query, query]); + assert_eq!(continued.bindings.heaps, vec![0x1010, 0x2020]); + assert_eq!(continued.bindings.topology, Some(4)); + assert_eq!(continued.bindings.stencil, Some(9)); + assert!(continued.written_ranges.overlaps(WriteProducer::InSegmentGpu, 0x3010, 4)); + assert!(continued.segment_write_producers.is_empty(), "a continuation has not produced the carried ranges"); + assert!(continued.pending_waits.is_empty() && continued.write64_signals.is_empty() && continued.sparse_writes.is_empty() && continued.texture_writes.is_empty()); + assert!(continued.cpu_writes.is_empty() && continued.deferred.is_none() && continued.own_alloc.is_none()); + assert_eq!(state.pending_waits.len(), 1, "effects remain on the closed segment"); + assert_eq!(state.write64_signals, vec![(0xe550, 6)]); + assert_eq!(state.sparse_writes, vec![(0xf660, 8)]); + assert_eq!(state.texture_writes.len(), 1); + assert!(state.segment_write_producers.overlaps(WriteProducer::InSegmentGpu, 0x3010, 4)); + } + #[test] fn execute_with_waits_splits_batches_before_unsatisfied_list() { // Use synthetic non-zero list pointers distinct from real COM objects. @@ -5023,6 +7090,44 @@ mod tests { assert_eq!(pick_queue(None, dev, D3D12_COMMAND_LIST_TYPE_DIRECT), None); } + #[test] + fn sync_graph_forgets_every_reference_to_a_retired_queue() { + let (gone, kept) = (0x9100usize, 0x9200usize); + let mut graph = SyncGraph::default(); + graph.queue_seq.insert(gone, 3); + graph.queue_seq.insert(kept, 4); + let mut cell = SyncCell { recorded_last_queue: Some(gone), submitted_queue: Some(gone), ..Default::default() }; + cell.armed_waits.push(ArmedGpuWait { + val: 1, + waiting_queue: gone, + waiting_queue_ty: 0, + wait_seq: 1, + armed_at: Instant::now(), + after_write64: false, + }); + cell.armed_waits.push(ArmedGpuWait { waiting_queue: kept, ..cell.armed_waits[0] }); + cell.submitted_signals.push(SubmittedSignal { val: 1, queue: gone, seq: 1 }); + cell.submitted_signals.push(SubmittedSignal { val: 2, queue: kept, seq: 2 }); + graph.cells.insert(0x1000, cell); + graph.title_fences.insert( + 0x2000, + TitleFenceSync { + waits: vec![(1, gone, 1), (2, kept, 2)], + signals: vec![SubmittedSignal { val: 1, queue: gone, seq: 1 }, SubmittedSignal { val: 2, queue: kept, seq: 2 }], + }, + ); + + assert_eq!(graph.forget_queue(gone), 1); + assert!(!graph.queue_seq.contains_key(&gone) && graph.queue_seq.contains_key(&kept)); + let cell = &graph.cells[&0x1000]; + assert_eq!((cell.recorded_last_queue, cell.submitted_queue), (None, None)); + assert_eq!(cell.armed_waits.iter().map(|wait| wait.waiting_queue).collect::>(), [kept]); + assert_eq!(cell.submitted_signals.iter().map(|signal| signal.queue).collect::>(), [kept]); + let title = &graph.title_fences[&0x2000]; + assert_eq!(title.waits.iter().map(|&(_, queue, _)| queue).collect::>(), [kept]); + assert_eq!(title.signals.iter().map(|signal| signal.queue).collect::>(), [kept]); + } + #[test] fn depth_bias_state_tracks_fallback_and_clear() { let l = 0x9000_0001usize as *mut c_void; @@ -5938,7 +8043,11 @@ mod tests { write64_bottom_x(list_ptr, bottom_va, 0, 0, BOTTOM_TIMESTAMPS); { let g = LISTS.lock().unwrap(); - assert_eq!(g.as_ref().unwrap()[&(list_ptr as usize)].cpu_writes.len(), 2); + let state = &g.as_ref().unwrap()[&(list_ptr as usize)]; + assert_eq!(state.cpu_writes.len(), 2); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, top_va, 8)); + assert!(state.written_ranges.overlaps(WriteProducer::CpuAfterSegment, bottom_va, 8)); + assert!(!state.written_ranges.overlaps(WriteProducer::InSegmentGpu, top_va, 8)); } // Restore the real vtable before closing and executing on the PC queue. @@ -7079,6 +9188,138 @@ mod tests { } } + /// A direct queue, its allocator and a title list wrapped as XCL wraps one, bound to `standin` + /// (None: no adapter). + unsafe fn put_off_rig(standin: usize) -> Option<(ID3D12Device, ID3D12CommandQueue, ID3D12CommandAllocator, *mut c_void, *mut c_void)> { + use super::super::{bind, title_list}; + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + use windows::Win32::Graphics::Dxgi::*; + let mut dev: Option = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + let warp = CreateDXGIFactory1::().and_then(|f| f.EnumWarpAdapter::()); + if warp.and_then(|w| D3D12CreateDevice(&w, D3D_FEATURE_LEVEL_11_0, &mut dev)).is_err() { + return None; + } + } + let dev = dev.unwrap(); + let ty = D3D12_COMMAND_LIST_TYPE_DIRECT; + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: ty, ..Default::default() }).unwrap(); + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let raw: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let pc0 = raw.into_raw(); + real::adopt(pc0, real::Kind::CommandList); + on_create(pc0, alloc.as_raw() as usize, 0, ty); + bind::reset(pc0, alloc.as_raw() as usize, standin); + let wrap = title_list::wrap(pc0); + Some((dev, queue, alloc, pc0, wrap)) + } + + /// A put-off call whose recording the driver refuses at the submit (its segment's Close + /// fails) is not submitted as it is: the segment goes out empty, the call is dropped, and the + /// rest of the submission runs (its fence is signalled, the device stays). + #[test] + fn a_put_off_call_whose_close_fails_is_not_submitted() { + use super::super::{bind, pso_async, title_list}; + use std::time::{Duration, Instant}; + unsafe { + let standin = 0x7E57_C105usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + pso_async::submit(standin, true, Box::new(|| { + let t = Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < Duration::from_secs(10) { + std::thread::sleep(Duration::from_millis(5)); + } + 0 + })); + let Some((dev, queue, _alloc, pc0, wrap)) = put_off_rig(standin) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + bind::dispatch(pc0, 1, 1, 1); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 3, "the dispatch was put off"); + + // the replay's recording fails in the runtime: a query begun and never ended + let mut heap: Option = None; + dev.CreateQueryHeap(&D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_OCCLUSION, Count: 1, NodeMask: 0 }, &mut heap).unwrap(); + let heap = heap.unwrap(); + let h = heap.as_raw() as usize; + static REFUSED: AtomicU32 = AtomicU32::new(0); + CLOSE_HOOK.lock().unwrap().push((wrap as usize, Box::new(move |p| { + pc::(p, PC_BEGIN_QUERY)(p, h, D3D12_QUERY_TYPE_OCCLUSION, 0); + let hr = pc:: i32>(p, PC_CLOSE)(p); + REFUSED.store(hr as u32, Ordering::Release); + hr + }))); + let close_fn: unsafe extern "system" fn(*mut c_void) -> i32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(9)); + assert_eq!(close_fn(wrap), 0); + BUILD.store(true, Ordering::Release); + record_deferred(wrap); + assert!(!CLOSE_HOOK.lock().unwrap().iter().any(|h| h.0 == wrap as usize), "the replay closed its segment"); + assert!((REFUSED.load(Ordering::Acquire) as i32) < 0, "the runtime refused the recording ({:#x})", REFUSED.load(Ordering::Acquire)); + // what the submit collects after the replay (`q_execute_command_lists`) + segs.clear(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 2, "the refused segment is not submitted"); + + let done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + type ExecFn = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let exec: ExecFn = std::mem::transmute(*(*(queue.as_raw() as *const *const usize)).add(PC_QUEUE_EXECUTE_COMMAND_LISTS)); + exec(queue.as_raw(), segs.len() as u32, segs.as_ptr()); + queue.Signal(&done, 1).unwrap(); + crate::gpu::fence::wait(&done, 1, &dev, None, 2000).expect("the submission runs"); + assert!(dev.GetDeviceRemovedReason().is_ok(), "the device stays"); + + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + let _ = pso_async::released(standin); + } + } + + /// A put-off segment that does not close when it is made is not used: the call waits in its + /// list instead of being put off. + #[test] + fn a_put_off_segment_that_does_not_close_is_not_used() { + use super::super::{bind, pso_async, title_list}; + unsafe { + let standin = 0x7E57_C106usize; + static BUILD: AtomicBool = AtomicBool::new(false); + BUILD.store(false, Ordering::Release); + pso_async::submit(standin, true, Box::new(|| { + let t = std::time::Instant::now(); + while !BUILD.load(Ordering::Acquire) && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + 0 + })); + let Some((_dev, _queue, _alloc, pc0, wrap)) = put_off_rig(standin) else { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + }; + CLOSE_HOOK.lock().unwrap().push((wrap as usize, Box::new(|p| { + pc:: i32>(p, PC_CLOSE)(p); + windows::Win32::Foundation::E_FAIL.0 + }))); + // (the call that is not put off waits for the build in the call; started here, after + // the device is made, so the build is still going when the call comes) + let ends = std::thread::spawn(|| { + std::thread::sleep(std::time::Duration::from_millis(300)); + BUILD.store(true, Ordering::Release); + }); + bind::dispatch(pc0, 1, 1, 1); + ends.join().unwrap(); + assert!(!CLOSE_HOOK.lock().unwrap().iter().any(|h| h.0 == wrap as usize), "the put-off segment was closed"); + let mut segs = Vec::new(); + assert!(title_list::push_segments(wrap, &mut segs)); + assert_eq!(segs.len(), 1, "nothing was put off"); + let rel_fn: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrap as *const *const usize)).add(2)); + rel_fn(wrap); + let _ = pso_async::released(standin); + } + } + /// Reproduces the exact intra-list fork-join pattern seen on retail compute queues: /// q_compute list O_c: Write64(cell_A, frame) -> Wait64(cell_B >= frame) -> Write64(cell_C, frame) /// q_direct list O_d: Wait64(cell_A >= frame) -> Write64(cell_B, frame) @@ -7315,7 +9556,7 @@ mod tests { #[test] fn uav_clear_handles_translate_console_slots() { use super::super::console_heap::Slot; - let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0 }); + let s = |pc_uav: u64, pc_gpu_uav: u64, sampler: bool| Some(Slot { generation: 0, at: 0x1000, index: 1, pc_srv: 0, pc_uav, pc_gpu_uav, sampler, shared_srv: 0, k: 0, remaining: 1 }); assert_eq!(uav_clear_handles(s(0x10, 0x5010, false), s(0x20, 0, false)), UavClearHandles::Console { gpu: 0x5010, cpu: 0x20 }); assert_eq!(uav_clear_handles(None, None), UavClearHandles::Pc); // a console slot beside a PC handle, a GPU slot of a heap that is not shader visible, diff --git a/crates/xcl/src/hle/d3d12x/memory_report.rs b/crates/xcl/src/hle/d3d12x/memory_report.rs new file mode 100644 index 0000000000..c80f950b41 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/memory_report.rs @@ -0,0 +1,197 @@ +//! Process and adapter memory against their budgets, split into XCL-owned parts (#2697). + +pub fn enabled() -> bool { + static ENABLED: std::sync::OnceLock = std::sync::OnceLock::new(); + *ENABLED.get_or_init(|| std::env::var_os("XCL_ACTIVITY").is_some()) +} + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Kind { + Video, + NonLocal, + Commit, +} + +#[derive(Clone, Debug, PartialEq)] +pub struct Part { + pub owner: &'static str, + pub kind: Kind, + pub bytes: u64, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Segment { + pub usage: u64, + pub budget: u64, +} + +#[derive(Clone, Debug, Default)] +pub struct Snapshot { + pub commit: Option, + pub local: Option, + pub non_local: Option, + pub parts: Vec, +} + +impl Snapshot { + pub fn counted(&self, kind: Kind) -> u64 { + self.parts.iter().filter(|p| p.kind == kind).fold(0, |bytes, p| bytes.saturating_add(p.bytes)) + } + + /// A negative remainder exposes aliasing, a stale sample, or a part charged to the wrong side. + pub fn other(&self, kind: Kind) -> Option { + let total = match kind { + Kind::Video => self.local?.usage, + Kind::NonLocal => self.non_local?.usage, + Kind::Commit => self.commit?, + }; + let difference = i128::from(total) - i128::from(self.counted(kind)); + Some(difference.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64) + } + + pub fn line(&self) -> String { + let mb = |b: u64| b >> 20; + let smb = |b: i64| b / (1 << 20); + let parts = |kind: Kind| { + let mut out: Vec = self.parts.iter().filter(|p| p.kind == kind) + .map(|p| format!("{} {}", p.owner, mb(p.bytes))).collect(); + if let Some(other) = self.other(kind) { + out.push(format!("other {}", smb(other))); + } + out.join(", ") + }; + let segment = |name: &str, value: Option, kind: Kind| match value { + Some(s) => format!("{name} {} of a {} budget ({})", mb(s.usage), mb(s.budget), parts(kind)), + None => format!("{name} unknown ({})", parts(kind)), + }; + let commit = match self.commit { + Some(bytes) => format!("commit {} ({})", mb(bytes), parts(Kind::Commit)), + None => format!("commit unknown ({})", parts(Kind::Commit)), + }; + format!("memory by owner (MB): {commit}; {}; {}", + segment("video memory", self.local, Kind::Video), + segment("non-local", self.non_local, Kind::NonLocal)) + } +} + +fn process_commit() -> Option { + unsafe { + use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; + let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); + c.cb = std::mem::size_of_val(&c) as u32; + (K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb) != 0) + .then(|| u64::try_from(c.PrivateUsage).unwrap_or(u64::MAX)) + } +} + +fn video_memory(raw: *mut std::ffi::c_void) -> (Option, Option) { + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::ID3D12Device; + use windows::Win32::Graphics::Dxgi::*; + let Some(dev) = (unsafe { ID3D12Device::from_raw_borrowed(&raw) }) else { return (None, None) }; + unsafe { + let Ok(factory) = CreateDXGIFactory1::() else { return (None, None) }; + let Ok(adapter) = factory.EnumAdapterByLuid::(dev.GetAdapterLuid()) else { return (None, None) }; + let query = |group| { + let mut i = DXGI_QUERY_VIDEO_MEMORY_INFO::default(); + adapter.QueryVideoMemoryInfo(0, group, &mut i).ok() + .map(|_| Segment { usage: i.CurrentUsage, budget: i.Budget }) + }; + (query(DXGI_MEMORY_SEGMENT_GROUP_LOCAL), query(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)) + } +} + +pub fn snapshot() -> Snapshot { + let raw = super::real::device_raw(); + let device = raw as usize; + let (pages, page_pools) = super::vram::page_bytes_for(device); + let arenas = super::vram::arena_bytes_for(device); + let (pools, mapped, retired, sparse_commit) = super::sparse::memory_bytes_for(device); + let (_, committed_textures) = super::title_textures::committed_bytes_for(device); + let (local, non_local) = video_memory(raw); + let uma = crate::gpu::uma::get().map_or(0, |u| u64::try_from(u.size()).unwrap_or(u64::MAX)); + let b = |n: usize| u64::try_from(n).unwrap_or(u64::MAX); + let parts = vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: uma }, + Part { owner: "sparse CPU copy", kind: Kind::Commit, bytes: b(sparse_commit) }, + Part { owner: "target pages", kind: Kind::Video, bytes: b(pages) }, + Part { owner: "target pools free", kind: Kind::Video, bytes: b(page_pools.saturating_sub(pages)) }, + Part { owner: "arenas", kind: Kind::Video, bytes: b(arenas) }, + Part { owner: "sparse tiles", kind: Kind::Video, bytes: b(mapped) }, + Part { owner: "sparse pools free", kind: Kind::Video, bytes: b(pools.saturating_sub(mapped)) }, + Part { owner: "sparse pools retired", kind: Kind::Video, bytes: b(retired) }, + Part { owner: "tracked committed sampled textures", kind: Kind::Video, bytes: committed_textures }, + ]; + Snapshot { commit: process_commit(), local, non_local, parts } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn remainder_and_partial_query_failure_are_explicit() { + const M: u64 = 1 << 20; + let s = Snapshot { + commit: Some(10_000 * M), + local: Some(Segment { usage: 9_000 * M, budget: 11_000 * M }), + non_local: None, + parts: vec![ + Part { owner: "UMA window", kind: Kind::Commit, bytes: 4_096 * M }, + Part { owner: "target pages", kind: Kind::Video, bytes: 5_000 * M }, + Part { owner: "upload staging", kind: Kind::NonLocal, bytes: 400 * M }, + ], + }; + assert_eq!(s.other(Kind::Video), Some(4_000 * M as i64)); + assert_eq!(s.other(Kind::NonLocal), None); + assert_eq!(s.line(), "memory by owner (MB): commit 10000 (UMA window 4096, other 5904); video memory 9000 of a 11000 budget (target pages 5000, other 4000); non-local unknown (upload staging 400)"); + let over = Snapshot { non_local: Some(Segment { usage: 300 * M, budget: 16_000 * M }), ..s }; + assert_eq!(over.other(Kind::NonLocal), Some(-(100 * M as i64))); + let unknown = Snapshot { commit: None, ..over }; + assert!(unknown.line().contains("commit unknown (UMA window 4096)")); + + let reverse = Snapshot { + local: None, + non_local: Some(Segment { usage: 700 * M, budget: 2_000 * M }), + ..unknown + }; + let line = reverse.line(); + assert!(line.contains("video memory unknown (target pages 5000)"), "{line}"); + assert!(line.contains("non-local 700 of a 2000 budget (upload staging 400, other 300)"), "{line}"); + } + + #[test] + fn signed_remainders_truncate_and_saturate() { + let tiny = Snapshot { + local: Some(Segment { usage: (1 << 20) - 1, budget: 1 << 20 }), + parts: vec![Part { owner: "one MiB", kind: Kind::Video, bytes: 1 << 20 }], + ..Default::default() + }; + assert_eq!(tiny.other(Kind::Video), Some(-1)); + assert!(tiny.line().contains("other 0"), "{}", tiny.line()); + + let large = Snapshot { + commit: Some(0), + parts: vec![ + Part { owner: "large", kind: Kind::Commit, bytes: u64::MAX }, + Part { owner: "saturated", kind: Kind::Commit, bytes: 1 }, + ], + ..Default::default() + }; + assert_eq!(large.counted(Kind::Commit), u64::MAX); + assert_eq!(large.other(Kind::Commit), Some(i64::MIN)); + } + + #[test] + fn device_snapshot_has_budget_and_all_owners() { + if super::super::backend() != super::super::Backend::Real { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let s = snapshot(); + assert!(s.local.expect("local video memory").budget > 0, "{}", s.line()); + assert!(s.commit.is_some()); + for owner in ["UMA window", "sparse CPU copy", "target pages", "target pools free", "arenas", "sparse tiles", "sparse pools free", "sparse pools retired", "tracked committed sampled textures"] { + assert!(s.parts.iter().any(|p| p.owner == owner), "{owner} missing: {}", s.line()); + } + } +} diff --git a/crates/xcl/src/hle/d3d12x/mod.rs b/crates/xcl/src/hle/d3d12x/mod.rs index 8886624632..def431dd49 100644 --- a/crates/xcl/src/hle/d3d12x/mod.rs +++ b/crates/xcl/src/hle/d3d12x/mod.rs @@ -10,6 +10,8 @@ #![allow(non_snake_case)] mod alloc_pool; +pub use alloc_pool::AllocatorSubmitStats; +mod build_queue; pub mod bind; pub mod console_heap; pub mod console_list; @@ -23,20 +25,27 @@ pub mod guard; mod late_release; pub mod layout; pub mod list_x; +pub mod memory_report; pub mod null; pub mod present; pub mod pso_async; +mod queue_submit; pub mod real; mod shader_cache_session; pub mod sparse; mod standin; pub mod title_list; pub mod title_textures; +mod used_journal; pub mod vram; use std::ffi::c_void; use std::sync::OnceLock; +pub fn allocator_submit_stats() -> AllocatorSubmitStats { + alloc_pool::submit_stats() +} + use crate::util::{HRESULT, S_OK}; /// data export: titles pass `&IID_ID3D12Device` to D3D12XboxCreateDevice / QueryInterface diff --git a/crates/xcl/src/hle/d3d12x/present.rs b/crates/xcl/src/hle/d3d12x/present.rs index d47e67841e..1bcc1d6368 100644 --- a/crates/xcl/src/hle/d3d12x/present.rs +++ b/crates/xcl/src/hle/d3d12x/present.rs @@ -19,7 +19,7 @@ use std::collections::HashMap; use std::ffi::c_void; use std::mem::ManuallyDrop; use std::sync::atomic::{AtomicBool, AtomicIsize, AtomicU64, Ordering}; -use std::sync::{Mutex, Once, OnceLock}; +use std::sync::{mpsc, Condvar, Mutex, Once, OnceLock}; use std::time::{Duration, Instant}; use windows::core::{Interface, HSTRING, PCSTR, PCWSTR}; @@ -289,12 +289,359 @@ unsafe fn backbuffer_like(res: usize) -> Option { ok.then_some(d) } -/// queues the title submitted work to (AddRef'd: they stay valid for `drain`) -static QUEUES: Mutex> = Mutex::new(Vec::new()); +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(super) struct QueueId { + raw: usize, + generation: u64, +} + +impl QueueId { + #[allow(dead_code)] // Used by queue-cache invalidation in a later unit. + pub(super) fn raw(self) -> usize { + self.raw + } +} + +#[derive(Clone)] +#[allow(dead_code)] // Stage B marker: read by the retirement worker in a later unit. +pub(super) struct QueueRetirementMark { + pub(super) fence: ID3D12Fence, + pub(super) value: u64, +} + +enum Retiring { + Preparing, + Mark(M), + Failed, +} + +enum QueueState { + Active, + Retiring(Retiring), +} + +struct QueueEntry { + id: QueueId, + owner: T, + state: QueueState, +} + +struct OwnedQueues { + entries: Vec>, + next_generation: u64, +} + +impl OwnedQueues { + const fn new() -> Self { + Self { entries: Vec::new(), next_generation: 1 } + } + + /// Add the first owner for `key`. `make` is not called for a duplicate, so no temporary + /// owner can be dropped while the registry lock is held. + fn ensure_with(&mut self, raw: usize, make: impl FnOnce() -> Option) -> Option { + if self.entries.iter().any(|entry| entry.id.raw == raw) { + return None; + } + let owner = make()?; + let id = QueueId { raw, generation: self.next_generation }; + self.next_generation = self.next_generation.wrapping_add(1).max(1); + self.entries.push(QueueEntry { id, owner, state: QueueState::Active }); + Some(id) + } + + fn snapshot(&self) -> Vec { + self.entries.iter().map(|entry| entry.owner.clone()).collect() + } + + fn active_snapshot(&self) -> Vec { + self.entries + .iter() + .filter(|entry| matches!(&entry.state, QueueState::Active)) + .map(|entry| entry.owner.clone()) + .collect() + } + + #[cfg(test)] + fn begin_retiring(&mut self, id: QueueId) -> bool { + let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return false }; + if !matches!(&entry.state, QueueState::Active) { + return false; + } + entry.state = QueueState::Retiring(Retiring::Preparing); + true + } + + fn begin_retiring_if(&mut self, raw: usize, ready: impl FnOnce(&T) -> bool) -> Option<(QueueId, T)> { + let entry = self.entries.iter_mut().find(|entry| entry.id.raw == raw && matches!(&entry.state, QueueState::Active))?; + if !ready(&entry.owner) { + return None; + } + entry.state = QueueState::Retiring(Retiring::Preparing); + Some((entry.id, entry.owner.clone())) + } + + fn mark_retiring(&mut self, id: QueueId, mark: M) -> Result<(), M> { + let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return Err(mark) }; + if !matches!(&entry.state, QueueState::Retiring(Retiring::Preparing)) { + return Err(mark); + } + entry.state = QueueState::Retiring(Retiring::Mark(mark)); + Ok(()) + } + + fn fail_retiring(&mut self, id: QueueId) -> bool { + let Some(entry) = self.entries.iter_mut().find(|entry| entry.id == id) else { return false }; + if !matches!(&entry.state, QueueState::Retiring(Retiring::Preparing)) { + return false; + } + entry.state = QueueState::Retiring(Retiring::Failed); + true + } + + /// Copy marks for completion checks after unlocking. + fn retirement_marks(&self) -> Vec<(QueueId, M)> + where + M: Clone, + { + self.entries + .iter() + .filter_map(|entry| match &entry.state { + QueueState::Retiring(Retiring::Mark(mark)) => Some((entry.id, mark.clone())), + _ => None, + }) + .collect() + } + + /// Remove entries whose marks were found complete outside the registry lock, and return + /// their owners for release after unlocking. + fn sweep(&mut self, completed: &[QueueId]) -> Vec<(QueueId, T, M)> { + let (mut kept, mut gone) = (Vec::with_capacity(self.entries.len()), Vec::new()); + for entry in std::mem::take(&mut self.entries) { + match entry { + QueueEntry { id, owner, state: QueueState::Retiring(Retiring::Mark(mark)) } if completed.contains(&id) => { + gone.push((id, owner, mark)); + } + entry => kept.push(entry), + } + } + self.entries = kept; + gone + } +} + +/// Queues the title submitted work to. One process-lifetime owner per raw queue, as before. +static QUEUES: Mutex> = Mutex::new(OwnedQueues::new()); +static QUEUE_STATE_CHANGED: Condvar = Condvar::new(); + +/// Keep the registry owner from queue creation onward, so non-owning users such as `KickoffX` +/// can pin it safely even before the title's first ordinary submission. +pub(super) unsafe fn track_queue(raw: usize) { + let mut queues = QUEUES.lock().unwrap(); + let _ = queues.ensure_with(raw, || ID3D12CommandQueue::from_raw_borrowed(&(raw as *mut c_void)).cloned()); +} + +/// Strong snapshot of the queues the title submitted work to. Every AddRef happens while the +/// registry is locked; callers own the returned references and drop them after the lock is gone. +pub fn known_queues_held() -> Vec { + QUEUES.lock().unwrap().snapshot() +} + +/// Strong snapshot of queues which can still accept internal signals/submissions. +pub(super) fn active_queues_held() -> Vec { + QUEUES.lock().unwrap().active_snapshot() +} + +pub(super) struct QueueCompletionSnapshot { + pub(super) active: Vec, + pub(super) retiring: Vec<(ID3D12Fence, u64)>, + pub(super) blocked: bool, +} + +/// Completion sources for work submitted before this instant. Active queue owners prevent their +/// retirement transition until callers signal them; installed retirement marks cover queues which +/// already transitioned. Preparing is allowed to install its mark; failed retirement has no +/// trustworthy completion source and makes the snapshot fail-closed. +pub(super) fn queue_completion_snapshot() -> QueueCompletionSnapshot { + let mut queues = QUEUES.lock().unwrap(); + while queues.entries.iter().any(|entry| matches!(&entry.state, QueueState::Retiring(Retiring::Preparing))) { + queues = QUEUE_STATE_CHANGED.wait(queues).unwrap(); + } + let mut out = QueueCompletionSnapshot { active: Vec::new(), retiring: Vec::new(), blocked: false }; + for entry in &queues.entries { + match &entry.state { + QueueState::Active => out.active.push(entry.owner.clone()), + QueueState::Retiring(Retiring::Mark(mark)) => out.retiring.push((mark.fence.clone(), mark.value)), + QueueState::Retiring(Retiring::Preparing | Retiring::Failed) => out.blocked = true, + } + } + out +} + +pub(super) fn queue_accepts_internal_work(raw: usize) -> bool { + QUEUES + .lock() + .unwrap() + .entries + .iter() + .find(|entry| entry.id.raw == raw) + .is_none_or(|entry| matches!(&entry.state, QueueState::Active)) +} + +pub(super) unsafe fn pin_queue_for_internal_work(raw: usize) -> Option { + let queues = QUEUES.lock().unwrap(); + if let Some(entry) = queues.entries.iter().find(|entry| entry.id.raw == raw) { + return matches!(&entry.state, QueueState::Active).then(|| entry.owner.clone()); + } + ID3D12CommandQueue::from_raw_borrowed(&(raw as *mut c_void)).cloned() +} + +#[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. +pub(super) unsafe fn begin_queue_retirement(raw: usize) -> Option<(QueueId, ID3D12CommandQueue)> { + let this = raw as *mut c_void; + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(this, 1)); + let release: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(super::real::orig_fn(this, 2)); + loop { + let mut queues = QUEUES.lock().unwrap(); + if !queues.entries.iter().any(|entry| entry.id.raw == raw && matches!(&entry.state, QueueState::Active)) { + return None; + } + let refs_with_probe = add_ref(this); + let retirement = queues.begin_retiring_if(raw, |_| refs_with_probe == 2); + drop(queues); + let refs = release(this); + if retirement.is_some() || refs != 1 { + return retirement; + } + // The last pre-transition snapshot dropped while the probe was held; retry because its + // hooked Release could not observe the registry-only count hidden by our probe. + } +} + +#[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. +pub(super) fn mark_queue_retirement(id: QueueId, mark: QueueRetirementMark) -> Result<(), QueueRetirementMark> { + let result = { + let mut queues = QUEUES.lock().unwrap(); + queues.mark_retiring(id, mark) + }; + QUEUE_STATE_CHANGED.notify_all(); + result +} + +#[allow(dead_code)] // Stage B API: wired to queue Release in a later unit. +pub(super) fn fail_queue_retirement(id: QueueId) -> bool { + let failed = QUEUES.lock().unwrap().fail_retiring(id); + QUEUE_STATE_CHANGED.notify_all(); + failed +} + +#[allow(dead_code)] // Stage B API: completion is checked and owners are released in a later unit. +pub(super) fn queue_retirement_marks() -> Vec<(QueueId, QueueRetirementMark)> { + QUEUES.lock().unwrap().retirement_marks() +} + +#[allow(dead_code)] // Stage B API: returned owners must be dropped after this function unlocks. +pub(super) fn sweep_queue_retirements(completed: &[QueueId]) -> Vec<(QueueId, ID3D12CommandQueue)> { + let retired = { + let mut queues = QUEUES.lock().unwrap(); + queues.sweep(completed) + }; + retired.into_iter().map(|(id, owner, mark)| { + drop(mark); + (id, owner) + }).collect() +} -/// The queues the title submitted work to. -pub fn known_queues() -> Vec { - QUEUES.lock().unwrap().clone() +fn quiesce_queue(raw: usize) { + super::list_x::stop_queue_submissions(raw); + let candidate = { + let mut candidate = CANDIDATE.lock().unwrap(); + candidate.is_some_and(|(queue, _)| queue == raw).then(|| candidate.take().unwrap().1) + }; + let presenter = { + let mut presenter = PRESENTER.lock().unwrap(); + presenter.as_ref().is_some_and(|p| p.queue == raw).then(|| presenter.take().unwrap()) + }; + if let Some(resource) = candidate { + unsafe { release(resource) }; + } + drop(presenter); +} + +/// Remove every cache keyed by this queue's raw address after its retirement mark completes and +/// before the final owner is released. No callee holds one subsystem lock while taking another. +#[allow(dead_code)] // Stage C seam: called by the retirement worker in a later unit. +pub(super) fn invalidate_queue_caches(id: QueueId) { + let raw = id.raw(); + quiesce_queue(raw); + super::list_x::forget_queue(id); + super::alloc_pool::forget_queue(id); + super::cpu_writes::forget_queue(id); + super::late_release::forget_queue(id); + super::sparse::forget_queue(id); + super::title_textures::forget_queue(id); + super::vram::forget_queue(id); +} + +fn retirement_worker() -> Option<&'static mpsc::Sender<()>> { + static WORKER: OnceLock>> = OnceLock::new(); + WORKER + .get_or_init(|| { + let (tx, rx) = mpsc::channel(); + std::thread::Builder::new() + .name("xcl-queue-retirement".to_string()) + .spawn(move || { + while rx.recv().is_ok() { + loop { + let marks = queue_retirement_marks(); + if marks.is_empty() { + break; + } + let completed: Vec<_> = marks + .iter() + .filter_map(|(id, mark)| (unsafe { mark.fence.GetCompletedValue() } >= mark.value).then_some(*id)) + .collect(); + drop(marks); + for (id, owner) in sweep_queue_retirements(&completed) { + invalidate_queue_caches(id); + drop(owner); + } + if completed.is_empty() { + std::thread::sleep(Duration::from_millis(10)); + } + } + } + }) + .ok() + .map(|_| tx) + }) + .as_ref() +} + +/// The hooked Release found that only the registry owner remains. Atomically verify that fact, +/// stop internal submissions, and place the final completion marker. Any marker failure pins the +/// registry owner permanently, so its raw address cannot be reused with stale cache state. +pub(super) unsafe fn retire_released_queue(raw: usize) { + let Some((id, queue)) = begin_queue_retirement(raw) else { return }; + quiesce_queue(raw); + let mark = (|| { + let mut dev: Option = None; + queue.GetDevice(&mut dev).ok()?; + let fence = dev?.CreateFence::(0, D3D12_FENCE_FLAG_NONE).ok()?; + super::real::native_queue_signal(&queue, &fence, 1).ok()?; + Some(QueueRetirementMark { fence, value: 1 }) + })(); + let Some(mark) = mark else { + let _ = fail_queue_retirement(id); + return; + }; + if let Err(mark) = mark_queue_retirement(id, mark) { + let _ = fail_queue_retirement(id); + drop(mark); + return; + } + if let Some(worker) = retirement_worker() { + let _ = worker.send(()); + } } static EXECUTES: AtomicU64 = AtomicU64::new(0); @@ -306,13 +653,7 @@ pub fn activity() -> (u64, u64) { pub unsafe fn note_execute(queue: *mut c_void, lists: &[*mut c_void]) { EXECUTES.fetch_add(1, Ordering::Relaxed); - { - let mut q = QUEUES.lock().unwrap(); - if !q.contains(&(queue as usize)) { - add_ref(queue as usize); - q.push(queue as usize); - } - } + track_queue(queue as usize); super::late_release::drain_known(false); if !enabled() || IN_PRESENT.with(|c| c.get()) || PRESENTX.load(Ordering::Relaxed) { return; @@ -423,10 +764,19 @@ impl FrameRate { /// While XCL compiles shaders (DXC, programs the disk cache did not have – the title draws /// nothing with those pipelines meanwhile: after an XCL update the screen stays black while -/// thousands recompile), the window's title says so: -/// "XCL – | N FPS | compiling shaders: N running, M done[, Q pipelines queued][, F failed]". -/// It stays 2 s after the last compile (compiles in the title's own calls come one by one), -/// then only the game name and presented frame rate remain. +/// thousands recompile) or the driver builds pipelines, the window's title says so +/// (`compiling_text`). It stays 2 s after the last compile (compiles in the title's own calls +/// come one by one), then only the game name and presented frame rate remain. +/// " | compiling shaders: DXC N running, M done | driver N building[ (W waiting for a +/// slot)], D done[, Q pipelines queued][, F failed]": `dxc` (running, done), `driver` builds +/// (running, waiting for a huge-compile slot, done; `real::driver_build_counts`). +fn compiling_text(title: &str, (running, done): (usize, usize), (building, waiting, built): (usize, usize, usize), queued: usize, failed: usize) -> String { + let waiting = if waiting > 0 { format!(" ({waiting} waiting for a slot)") } else { String::new() }; + let queued = if queued > 0 { format!(", {queued} pipelines queued") } else { String::new() }; + let failed = if failed > 0 { format!(", {failed} failed") } else { String::new() }; + format!("{title} | compiling shaders: DXC {running} running, {done} done | driver {building} building{waiting}, {built} done{queued}{failed}") +} + unsafe fn show_compiling(hwnd: HWND) { static SHOWN: Mutex<Option<String>> = Mutex::new(None); static LAST_ACTIVE: Mutex<Option<Instant>> = Mutex::new(None); @@ -439,8 +789,9 @@ unsafe fn show_compiling(hwnd: HWND) { .get_or_insert_with(|| FrameRate::new(now, presented)) .sample(now, presented); let (_, failed, queued) = super::pso_async::counts(); - let (running, done) = crate::gpu::recomp::dxc::compile_counts(); - let active = running > 0 || queued > 0; + let dxc = crate::gpu::recomp::dxc::compile_counts(); + let driver = super::real::driver_build_counts(); + let active = dxc.0 > 0 || driver.0 > 0 || driver.1 > 0 || queued > 0; let recent = { let mut last = LAST_ACTIVE.lock().unwrap(); if active { @@ -449,13 +800,7 @@ unsafe fn show_compiling(hwnd: HWND) { last.is_some_and(|t| t.elapsed() < Duration::from_secs(2)) }; let title = format!("XCL – {} | {fps:.1} FPS", window_name()); - let text = if recent { - let queued = if queued > 0 { format!(", {queued} pipelines queued") } else { String::new() }; - let failed = if failed > 0 { format!(", {failed} failed") } else { String::new() }; - format!("{title} | compiling shaders: {running} running, {done} done{queued}{failed}") - } else { - title - }; + let text = if recent { compiling_text(&title, dxc, driver, queued, failed) } else { title }; let mut shown = SHOWN.lock().unwrap(); if shown.as_deref() != Some(text.as_str()) { let _ = SetWindowTextW(hwnd, &HSTRING::from(text.as_str())); @@ -1037,6 +1382,7 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let Some((queue, res)) = *candidate else { return }; (queue, vec![(res, None)], guard) }; + let Some(_queue_pin) = pin_queue_for_internal_work(queue) else { return }; let resolved: Vec<(ID3D12Resource, D3D12_RESOURCE_DESC, [f32; 4])> = raw_planes .into_iter() .filter_map(|(res, rect)| { @@ -1198,18 +1544,22 @@ unsafe fn present_now(min_interval: Duration, frame: Option<(usize, Vec<(usize, let qraw = queue as *mut c_void; let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qraw) else { return }; let Ok(cl) = p.list.cast::<ID3D12CommandList>() else { return }; - q.ExecuteCommandLists(&[Some(cl)]); + super::real::native_queue_execute(q, &cl); p.copy_sources = resolved.into_iter().map(|(r, _, _)| r).collect(); p.dumps = dumps; p.value += 1; - if let Err(e) = q.Signal(&p.fence, p.value) { + if let Err(e) = super::real::native_queue_signal(q, &p.fence, p.value) { // The copy is already submitted. Without its signal, keep its resources and allocator. p.disabled = true; let e = fence::api_error(&p.dev, "Signal", e); crate::xlog_error!("present: submit copy: {e}"); return; } - if let Err(e) = sc.Present(0, DXGI_PRESENT(0)).ok() { + let presented = { + let _stall = crate::stall::span(crate::stall::StallKind::Present); + sc.Present(0, DXGI_PRESENT(0)).ok() + }; + if let Err(e) = presented { let e = fence::api_error(&p.dev, "Present", e); p.disabled = matches!(&e, FenceError::Removed(_)); crate::xlog_error!("present: {e}"); @@ -1473,6 +1823,115 @@ impl Drop for Presenter { mod tests { use super::*; + #[test] + fn owned_queue_registry_deduplicates_without_making_a_temporary_owner() { + let mut registry: OwnedQueues<std::sync::Arc<i32>, ()> = OwnedQueues::new(); + assert!(registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).is_some()); + assert!(registry.ensure_with(0xA, || -> Option<std::sync::Arc<i32>> { panic!("duplicate owner was made") }).is_none()); + assert!(registry.ensure_with(0xB, || Some(std::sync::Arc::new(2))).is_some()); + let values: Vec<_> = registry.snapshot().iter().map(|v| **v).collect(); + assert_eq!(values, [1, 2]); + } + + #[test] + fn owned_queue_snapshot_has_its_own_lifetime() { + let owner = std::sync::Arc::new(()); + let weak = std::sync::Arc::downgrade(&owner); + let mut registry: OwnedQueues<std::sync::Arc<()>, ()> = OwnedQueues::new(); + assert!(registry.ensure_with(0xA, || Some(owner)).is_some()); + let snapshot = registry.snapshot(); + drop(registry); + assert!(weak.upgrade().is_some(), "the snapshot did not keep its owner alive"); + drop(snapshot); + assert!(weak.upgrade().is_none(), "the caller did not release its snapshot owner"); + } + + #[test] + fn retiring_queue_stays_in_snapshots_until_its_mark_completes() { + let mut registry: OwnedQueues<std::sync::Arc<i32>, u64> = OwnedQueues::new(); + let owner = std::sync::Arc::new(1); + let weak = std::sync::Arc::downgrade(&owner); + let id = registry.ensure_with(0xA, || Some(owner)).unwrap(); + assert!(registry.begin_retiring(id)); + assert_eq!(registry.snapshot().iter().map(|v| **v).collect::<Vec<_>>(), [1]); + assert!(registry.retirement_marks().is_empty()); + assert!(registry.sweep(&[id]).is_empty(), "Preparing must remain pinned"); + assert!(registry.mark_retiring(id, 7).is_ok()); + assert_eq!(registry.retirement_marks(), [(id, 7)]); + assert!(registry.sweep(&[]).is_empty()); + assert_eq!(registry.snapshot().iter().map(|v| **v).collect::<Vec<_>>(), [1]); + let gone = registry.sweep(&[id]); + assert_eq!(gone.iter().map(|(gone_id, owner, mark)| (*gone_id, **owner, *mark)).collect::<Vec<_>>(), [(id, 1, 7)]); + assert!(registry.snapshot().is_empty()); + assert!(weak.upgrade().is_some(), "sweep dropped an owner instead of returning it"); + drop(gone); + assert!(weak.upgrade().is_none(), "the returned owner was not released by its caller"); + } + + #[test] + fn failed_retirement_is_permanently_pinned() { + let mut registry: OwnedQueues<std::sync::Arc<i32>, u64> = OwnedQueues::new(); + let id = registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + assert!(registry.begin_retiring(id)); + assert!(registry.fail_retiring(id)); + assert_eq!(registry.mark_retiring(id, 1), Err(1), "an uninstalled mark must be returned"); + assert!(!registry.begin_retiring(id)); + assert!(registry.retirement_marks().is_empty()); + assert!(registry.sweep(&[id]).is_empty()); + assert_eq!(registry.snapshot().iter().map(|v| **v).collect::<Vec<_>>(), [1]); + } + + #[test] + fn reused_raw_queue_gets_a_new_generation() { + let mut registry: OwnedQueues<std::sync::Arc<i32>, u64> = OwnedQueues::new(); + let old = registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + assert!(registry.begin_retiring(old)); + assert!(registry.mark_retiring(old, 1).is_ok()); + drop(registry.sweep(&[old])); + let new = registry.ensure_with(0xA, || Some(std::sync::Arc::new(2))).unwrap(); + assert_ne!(old, new); + assert!(!registry.begin_retiring(old), "a stale generation matched the reused address"); + assert!(registry.begin_retiring(new)); + } + + #[test] + fn held_submission_snapshot_delays_atomic_retirement() { + let mut registry: OwnedQueues<std::sync::Arc<i32>, u64> = OwnedQueues::new(); + let id = registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + let held = registry.active_snapshot(); + assert!(registry.begin_retiring_if(0xA, |owner| std::sync::Arc::strong_count(owner) == 1).is_none()); + assert_eq!(registry.active_snapshot().len(), 1, "failed preflight changed Active state"); + drop(held); + let (retiring, token) = registry + .begin_retiring_if(0xA, |owner| std::sync::Arc::strong_count(owner) == 1) + .expect("registry became sole owner"); + assert_eq!(retiring, id); + assert_eq!(*token, 1); + } + + #[test] + fn preparing_queue_is_visible_but_cannot_repopulate_submission_cache() { + let mut registry: OwnedQueues<std::sync::Arc<i32>, u64> = OwnedQueues::new(); + registry.ensure_with(0xA, || Some(std::sync::Arc::new(1))).unwrap(); + let (_, token) = registry.begin_retiring_if(0xA, |_| true).unwrap(); + assert_eq!(registry.snapshot().len(), 1, "retirement lost its diagnostic owner"); + assert!(registry.active_snapshot().is_empty(), "a post-transition producer acquired the queue"); + let mut cache = vec![0xA]; + cache.clear(); + cache.extend(registry.active_snapshot().into_iter().map(|_| 0xA)); + assert!(cache.is_empty(), "an inactive producer repopulated invalidated state"); + drop(token); + } + + #[test] + fn the_title_counts_dxc_compiles_and_driver_builds() { + assert_eq!( + compiling_text("XCL – t | 30.0 FPS", (0, 12), (2, 1, 40), 5, 0), + "XCL – t | 30.0 FPS | compiling shaders: DXC 0 running, 12 done | driver 2 building (1 waiting for a slot), 40 done, 5 pipelines queued" + ); + assert_eq!(compiling_text("t", (3, 4), (0, 0, 0), 0, 1), "t | compiling shaders: DXC 3 running, 4 done | driver 0 building, 0 done, 1 failed"); + } + #[test] fn present_ring_overlaps_previous_frame_and_drains_cleanly() { let mut ring = PresentRing::new(PRESENT_SLOTS); diff --git a/crates/xcl/src/hle/d3d12x/pso_async.rs b/crates/xcl/src/hle/d3d12x/pso_async.rs index 63d62a7df4..ee4777e063 100644 --- a/crates/xcl/src/hle/d3d12x/pso_async.rs +++ b/crates/xcl/src/hle/d3d12x/pso_async.rs @@ -7,39 +7,186 @@ //! for where it is used, a `Dispatch` at its submit (a skipped dispatch would corrupt what it computes). //! `XCL_ASYNC_PSO=0` builds every pipeline in the call, as before. -use std::collections::HashMap; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; +use std::collections::{HashMap, HashSet}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock, Weak}; + +use windows::core::Interface; +use windows::Win32::Graphics::Direct3D12::ID3D12PipelineState; + +use super::build_queue::{BuildQueue, JobHandle, JobStatus, Priority}; + +const QUEUE_IDLE: u8 = 0; +const QUEUE_ACTIVE: u8 = 1; +const QUEUE_DONE: u8 = 2; + +/// Process-lifetime ranked-preload outcomes; `started` means dequeued in the Preload band. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[serde(default)] +pub struct RankedPreloadStats { + pub submissions: u64, + pub started: u64, + pub promoted: u64, +} struct Pending { - /// the build, until a worker – or a bind that cannot wait for the queue – takes it - job: Mutex<Option<Job>>, - /// the build went to the workers (a lazy one goes on its first `resolve`) - sent: std::sync::atomic::AtomicBool, - /// the real pipeline state (raw pointer), 0 while building or when building failed - real: AtomicUsize, + build: Arc<Build>, /// the driver pipeline binds get till then (`shared`); 0: the stand-in is one itself driver: AtomicUsize, - done: Mutex<bool>, - cv: Condvar, compute: bool, /// of its shaders (`used`); 0 = none key: u64, /// it was used (`used::note` is told once) used: std::sync::atomic::AtomicBool, - /// the stand-in was released before the real pipeline was built - orphan: std::sync::atomic::AtomicBool, /// a bind waited for it longer than `wait_budget`: binds go on without it until it is built late: std::sync::atomic::AtomicBool, /// its dispatches may be left out while it is built (`image_only`): binds do not wait for it spared: std::sync::atomic::AtomicBool, +} + +/// A pipeline build independent of the title-visible stand-ins that requested it. +struct Build { + compute_key: Option<Arc<super::real::compute_build_key::ComputeBuildKey>>, + /// Immutable inputs for rebuilding this pipeline after its first job has been consumed. + #[allow(dead_code)] // retained for the later opt-in eviction/rebuild stage + recipe: Option<Recipe>, + /// the build, until a worker takes it + job: Mutex<Option<Job>>, + /// the build went to the workers (a lazy one goes on its first `resolve`) + sent: std::sync::atomic::AtomicBool, + /// Whether a title-visible stand-in owns this build, and its exact queued-count state. + tracked: AtomicBool, + queue_state: AtomicU8, + /// the real pipeline state (one owned raw pointer shared by all `Pending`s), 0 until built + /// or when building failed + real: AtomicUsize, + /// Last frame in which any owner resolved this build, for `XCL_ACTIVITY` retention ages. + last_use_frame: AtomicU64, + /// Frame in which `real` became retained; age never begins before the build completed. + completed_frame: AtomicU64, + /// This build already has one use record in the bounded eviction-candidate journal. + /// Touched only while recipe retention is enabled. + candidate_queued: AtomicBool, + /// Exact armed eviction visible before its native owners may be detached. Kept separate + /// from recipe state so coordinator locks never overlap the build/rebuild/generation chain. + eviction: Mutex<Option<EvictedBuildToken>>, + done: Mutex<bool>, + cv: Condvar, + /// every stand-in interested in this build was released before it finished + orphan: std::sync::atomic::AtomicBool, + /// Title-visible `Pending`s sharing this build. Changed while holding `done`. + owners: AtomicUsize, + /// One of the title's threads waits, or a recorded submit will wait, for this build. Polled + /// by DXC and driver admission. + wanted: AtomicBool, demand: Mutex<Demand>, + queued: Mutex<Option<JobHandle>>, +} + +const EVICTION_CANDIDATE_CAPACITY: usize = 1024; + +/// Bounded lock-free MPMC ring. Bind threads append weak identities, so an unconsumed record does +/// not retain a released pipeline; a future policy can drain a fixed number on a background thread +/// without scanning the title-visible registry. +struct CandidateSlot<T> { + sequence: AtomicUsize, + value: std::cell::UnsafeCell<std::mem::MaybeUninit<Weak<T>>>, +} + +unsafe impl<T: Send + Sync> Sync for CandidateSlot<T> {} + +struct CandidateQueue<T, const N: usize> { + enqueue: AtomicUsize, + dequeue: AtomicUsize, + slots: [CandidateSlot<T>; N], +} + +unsafe impl<T: Send + Sync, const N: usize> Sync for CandidateQueue<T, N> {} + +impl<T, const N: usize> CandidateQueue<T, N> { + fn new() -> Self { + // The sequence protocol needs distinct empty/full generations for each slot. At capacity + // one the producer can observe its just-published sequence as the next empty generation + // and overwrite an unread value. Signed sequence differences also require a half-range + // bound across counter wrap. + assert!(N > 1 && N.is_power_of_two() && N <= isize::MAX as usize); + Self { + enqueue: AtomicUsize::new(0), + dequeue: AtomicUsize::new(0), + slots: std::array::from_fn(|sequence| CandidateSlot { + sequence: AtomicUsize::new(sequence), + value: std::cell::UnsafeCell::new(std::mem::MaybeUninit::uninit()), + }), + } + } + + fn push(&self, value: Weak<T>) -> Result<(), Weak<T>> { + let mut position = self.enqueue.load(Ordering::Relaxed); + loop { + let slot = &self.slots[position & (N - 1)]; + let sequence = slot.sequence.load(Ordering::Acquire); + let difference = sequence.wrapping_sub(position) as isize; + if difference == 0 { + match self.enqueue.compare_exchange_weak( + position, position.wrapping_add(1), Ordering::Relaxed, Ordering::Relaxed, + ) { + Ok(_) => { + unsafe { (*slot.value.get()).write(value) }; + slot.sequence.store(position.wrapping_add(1), Ordering::Release); + return Ok(()); + } + Err(actual) => position = actual, + } + } else if difference < 0 { + return Err(value); + } else { + position = self.enqueue.load(Ordering::Relaxed); + } + } + } + + fn pop(&self) -> Option<Weak<T>> { + let mut position = self.dequeue.load(Ordering::Relaxed); + loop { + let slot = &self.slots[position & (N - 1)]; + let sequence = slot.sequence.load(Ordering::Acquire); + let difference = sequence.wrapping_sub(position.wrapping_add(1)) as isize; + if difference == 0 { + match self.dequeue.compare_exchange_weak( + position, position.wrapping_add(1), Ordering::Relaxed, Ordering::Relaxed, + ) { + Ok(_) => { + let value = unsafe { (*slot.value.get()).assume_init_read() }; + slot.sequence.store(position.wrapping_add(N), Ordering::Release); + return Some(value); + } + Err(actual) => position = actual, + } + } else if difference < 0 { + return None; + } else { + position = self.dequeue.load(Ordering::Relaxed); + } + } + } +} + +impl<T, const N: usize> Drop for CandidateQueue<T, N> { + fn drop(&mut self) { + while self.pop().is_some() {} + } +} + +type EvictionCandidateQueue = CandidateQueue<Build, EVICTION_CANDIDATE_CAPACITY>; + +fn eviction_candidates() -> &'static EvictionCandidateQueue { + static CANDIDATES: OnceLock<EvictionCandidateQueue> = OnceLock::new(); + CANDIDATES.get_or_init(EvictionCandidateQueue::new) } -/// Whether one of the title's threads waits for the pipeline, and the preload worker building it. +/// Submit demand and the preload worker building this pipeline. #[derive(Default)] struct Demand { - wanted: bool, /// a call put off to the submit needs it (`need_by_submit`) by_submit: bool, /// thread id of the preload worker (lowest priority) building it, 0 = none @@ -48,57 +195,175 @@ struct Demand { thread_local! { /// what this worker is building - static BUILDING: std::cell::RefCell<Option<Arc<Pending>>> = const { std::cell::RefCell::new(None) }; + static BUILDING: std::cell::RefCell<Option<Arc<Build>>> = const { std::cell::RefCell::new(None) }; + /// this is one of the workers reserved for low-priority preload builds + static PRELOAD_WORKER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// this thread serves the normal (`BoundSoon` through `Foreground`) worker band + static NORMAL_WORKER: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; } /// This thread is a worker and one of the title's threads waits for what it is building: the /// build must not stand back for the title's sake (`real::big_compile_turn`). pub(super) fn build_is_wanted() -> bool { - BUILDING.with(|b| b.borrow().as_ref().is_some_and(|p| p.demand.lock().unwrap().wanted)) + BUILDING.with(|b| b.borrow().as_ref().is_some_and(|build| build.wanted.load(Ordering::Acquire))) } /// Whether one of the title's threads waits for what this thread is doing, to be asked later and /// from another thread: a worker's build as `build_is_wanted`; a thread that is not XCL's is the /// title's own. pub fn wanted_here() -> crate::gpu::recomp::dxc::Wanted { - if let Some(p) = BUILDING.with(|b| b.borrow().clone()) { - return Box::new(move || p.demand.lock().unwrap().wanted); + if let Some(build) = BUILDING.with(|b| b.borrow().clone()) { + return Box::new(move || build.wanted.load(Ordering::Acquire)); } let own = crate::state::boot().is_some() && !std::thread::current().name().is_some_and(|n| n.starts_with("xcl-")); Box::new(move || own) } -/// A worker's build of `p` (`preload`: by one of the lowest-priority workers). -fn build(p: &Arc<Pending>, job: Job, preload: bool) { - use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_NORMAL}; - BUILDING.with(|b| *b.borrow_mut() = Some(p.clone())); +struct RunningBuild<'a> { + build: &'a Build, + preload: bool, +} + +impl Drop for RunningBuild<'_> { + fn drop(&mut self) { + if self.preload { + // (under the lock: `want` does not raise this thread after it) + let mut demand = self.build.demand.lock().unwrap(); + demand.preload_thread = 0; + if self.build.wanted.load(Ordering::Acquire) { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + } + } + } + BUILDING.with(|b| *b.borrow_mut() = None); + } +} + +struct RestoreBuilding(Option<Arc<Build>>); + +impl Drop for RestoreBuilding { + fn drop(&mut self) { + BUILDING.with(|b| *b.borrow_mut() = self.0.take()); + } +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> &str { + if let Some(message) = payload.downcast_ref::<&str>() { + message + } else if let Some(message) = payload.downcast_ref::<String>() { + message.as_str() + } else { + "unknown panic" + } +} + +/// Run a pipeline job without letting one bad shader strand every waiter on its shared build. +fn run_job(job: Job) -> usize { + match std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)) { + Ok(real) => real, + Err(payload) => { + crate::xlog_error!("D3D12.X: panic while building pipeline: {}", panic_message(payload.as_ref())); + 0 + } + } +} + +/// A worker's pipeline build (`preload`: by one of the lowest-priority workers). +fn run_build(build: &Arc<Build>, job: Job) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL}; + let preload = PRELOAD_WORKER.get(); + BUILDING.with(|b| *b.borrow_mut() = Some(build.clone())); if preload { - let mut d = p.demand.lock().unwrap(); + let mut d = build.demand.lock().unwrap(); d.preload_thread = unsafe { GetCurrentThreadId() }; - if d.wanted { + if build.wanted.load(Ordering::Acquire) { unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; } } - complete(p, job()); - if preload { - // (under the lock: `want` does not raise this thread after it) - let mut d = p.demand.lock().unwrap(); - d.preload_thread = 0; - if d.wanted { - unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST) }; + let real = { + let _running = RunningBuild { build, preload }; + run_job(job) + }; + complete(build, real); +} + +impl Build { + fn new(job: Job, sent: bool) -> Self { + Self::new_keyed(job, sent, None, None) + } + + fn new_keyed( + job: Job, + sent: bool, + compute_key: Option<Arc<super::real::compute_build_key::ComputeBuildKey>>, + recipe: Option<Recipe>, + ) -> Self { + Self { + compute_key, + recipe, + job: Mutex::new(Some(job)), + sent: std::sync::atomic::AtomicBool::new(sent), + tracked: AtomicBool::new(false), + queue_state: AtomicU8::new(QUEUE_IDLE), + real: AtomicUsize::new(0), + last_use_frame: AtomicU64::new(super::present::presents()), + completed_frame: AtomicU64::new(0), + candidate_queued: AtomicBool::new(false), + eviction: Mutex::new(None), + done: Mutex::new(false), + cv: Condvar::new(), + orphan: Default::default(), + owners: AtomicUsize::new(1), + wanted: AtomicBool::new(false), + demand: Default::default(), + queued: Mutex::new(None), } } - BUILDING.with(|b| *b.borrow_mut() = None); -} -impl Pending { - /// One of the title's threads is about to wait for it: the worker building it goes on now, - /// at a normal priority. + fn note_queued(&self) { + if self.tracked.load(Ordering::Acquire) { + // Publish the count before ACTIVE: completion may run as soon as the queue accepts + // the job and must never subtract an entry which has not been added yet. + QUEUED_BUILDS.fetch_add(1, Ordering::Relaxed); + if !mark_queued(&self.queue_state) { + QUEUED_BUILDS.fetch_sub(1, Ordering::Relaxed); + } + } + } + + fn finish_queued(&self) { + if mark_queue_done(&self.queue_state) { + QUEUED_BUILDS.fetch_sub(1, Ordering::Relaxed); + } + } + + fn promote(&self, priority: Priority) { + if let Some(job) = self.queued.lock().unwrap().as_ref() { + let _ = job.promote(priority); + } + } + + fn cancel_queued(&self) { + if let Some(job) = self.queued.lock().unwrap().take() { + let _ = job.cancel(); + } + } + + /// One of the title's threads waits or a recorded submit will wait for it: the worker + /// building it goes on now, at a normal priority. fn want(&self) { use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Threading::{OpenThread, SetThreadPriority, THREAD_PRIORITY_NORMAL, THREAD_SET_LIMITED_INFORMATION}; - let mut d = self.demand.lock().unwrap(); - if !std::mem::replace(&mut d.wanted, true) && d.preload_thread != 0 { + let newly_wanted = !self.wanted.swap(true, Ordering::AcqRel); + let _ = start_normal_workers(); + self.promote(Priority::Foreground); + if newly_wanted { + let d = self.demand.lock().unwrap(); + if d.preload_thread == 0 { + return; + } unsafe { let h = OpenThread(THREAD_SET_LIMITED_INFORMATION, 0, d.preload_thread); if !h.is_null() { @@ -108,457 +373,5632 @@ impl Pending { } } } +} + +fn mark_queued(state: &AtomicU8) -> bool { + state.compare_exchange(QUEUE_IDLE, QUEUE_ACTIVE, Ordering::AcqRel, Ordering::Acquire).is_ok() +} + +fn mark_queue_done(state: &AtomicU8) -> bool { + state.swap(QUEUE_DONE, Ordering::AcqRel) == QUEUE_ACTIVE +} +impl Pending { fn note_use(&self) { + if super::memory_report::enabled() { + self.build.last_use_frame.fetch_max(super::present::presents(), Ordering::Relaxed); + } if self.key != 0 && !self.used.swap(true, Ordering::Relaxed) { used::note(self.key); } } } -/// stand-in handed to the title → its real pipeline -static PENDING: Mutex<Option<HashMap<usize, Arc<Pending>>>> = Mutex::new(None); +const PENDING_SHARDS: usize = 64; -/// The build is done (`real`: its pipeline, 0 = failed). -fn complete(p: &Pending, real: usize) { - if real == 0 { - FAILED.fetch_add(1, Ordering::Relaxed); - } else { - BUILT.fetch_add(1, Ordering::Relaxed); +/// Title-visible stand-in address → its build. Bind resolution is called by every recording +/// thread, so unrelated pipelines must not queue on one process-wide map lock. +struct PendingRegistry<V> { + shards: [Mutex<Option<HashMap<usize, V>>>; PENDING_SHARDS], +} + +impl<V> PendingRegistry<V> { + const fn new() -> Self { + Self { shards: [const { Mutex::new(None) }; PENDING_SHARDS] } } - let orphan = { - let mut done = p.done.lock().unwrap(); - let orphan = p.orphan.load(Ordering::Acquire); - if !orphan { - p.real.store(real, Ordering::Release); - } - *done = true; - p.cv.notify_all(); - orphan - }; - // outside `done`: the Release override takes PENDING (`counts` takes PENDING, then `done`) - if orphan { - release(real); + + fn insert(&self, key: usize, value: V) -> Option<V> { + self.shards[pending_shard_index(key)].lock().unwrap().get_or_insert_with(HashMap::new).insert(key, value) } -} -static BUILT: AtomicUsize = AtomicUsize::new(0); -static FAILED: AtomicUsize = AtomicUsize::new(0); -/// binds waiting right now for a pipeline still being built (`title_held`) -static HELD: AtomicUsize = AtomicUsize::new(0); -/// The PC calls of the title's threads (`pc_call`): the ones going on, and how long the ones -/// that ended took since the last frame was shown. -struct PcCalls { - /// (id, when it began) - now: Vec<(u64, std::time::Instant)>, - /// the frames shown when `spent` began to count (`None` before the first observation) - frame: Option<u64>, - /// when the latest frame advance was first observed; calls that started earlier are clamped here - frame_since: Option<std::time::Instant>, - /// the time of the PC calls that ended since then - spent: std::time::Duration, + fn remove(&self, key: usize) -> Option<V> { + self.shards[pending_shard_index(key)].lock().unwrap().as_mut().and_then(|map| map.remove(&key)) + } } -impl PcCalls { - const fn new() -> Self { - Self { now: Vec::new(), frame: None, frame_since: None, spent: std::time::Duration::ZERO } +impl<V: Clone> PendingRegistry<V> { + fn get(&self, key: usize) -> Option<V> { + self.shards[pending_shard_index(key)].lock().unwrap().as_ref()?.get(&key).cloned() } +} - /// `frame` frames have been shown: the calls before the last of them are not this wait's. - fn at(&mut self, frame: u64, now: std::time::Instant) { - match self.frame { - None => self.frame = Some(frame), - Some(prev) if frame > prev => { - self.frame = Some(frame); - self.frame_since = Some(now); - self.spent = std::time::Duration::ZERO; - } - Some(_) => {} +#[inline] +fn pending_shard_index(key: usize) -> usize { + let mut mixed = (key >> 4).wrapping_mul(0x9E37_79B1); + mixed ^= mixed >> 16; + mixed & (PENDING_SHARDS - 1) +} + +static PENDING: PendingRegistry<Arc<Pending>> = PendingRegistry::new(); + +/// Equal compute requests share only while their build is in flight. Weak values neither retain +/// completed builds nor turn this into another PSO cache. +static IN_FLIGHT: Mutex<Option<HashMap<Arc<super::real::compute_build_key::ComputeBuildKey>, Weak<Build>>>> = Mutex::new(None); + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(default)] +pub struct ComputeCoalescingStats { + pub keyed_submissions: u64, + pub coalescing_hits: u64, + pub unique_keyed_builds: u64, + pub current_in_flight: usize, + pub peak_in_flight: usize, +} + +struct CoalescingCounters { + coalescing_hits: AtomicU64, + unique_keyed_builds: AtomicU64, + current_in_flight: AtomicUsize, + peak_in_flight: AtomicUsize, +} + +impl CoalescingCounters { + const fn new() -> Self { + Self { + coalescing_hits: AtomicU64::new(0), + unique_keyed_builds: AtomicU64::new(0), + current_in_flight: AtomicUsize::new(0), + peak_in_flight: AtomicUsize::new(0), } } - fn clamp(&self, since: std::time::Instant) -> std::time::Instant { - self.frame_since.map_or(since, |f| since.max(f)) + fn hit(&self) { + self.coalescing_hits.fetch_add(1, Ordering::Relaxed); } - fn begin(&mut self, id: u64, frame: u64, now: std::time::Instant) { - self.at(frame, now); - self.now.push((id, now)); + fn unique(&self) { + self.unique_keyed_builds.fetch_add(1, Ordering::Relaxed); + let current = self.current_in_flight.fetch_add(1, Ordering::Relaxed) + 1; + self.peak_in_flight.fetch_max(current, Ordering::Relaxed); } - fn end(&mut self, id: u64, frame: u64, now: std::time::Instant) { - self.at(frame, now); - if let Some(i) = self.now.iter().position(|c| c.0 == id) { - let (_, since) = self.now.swap_remove(i); - self.spent += now.saturating_duration_since(self.clamp(since)); + fn finished(&self, count: usize) { + if count != 0 { + self.current_in_flight.fetch_sub(count, Ordering::Relaxed); } } - /// Whether a call going on holds the title: the PC calls since the last frame, it included, - /// have taken `PC_CALL_HOLDS_AFTER`. - fn holds(&mut self, frame: u64, now: std::time::Instant) -> bool { - self.at(frame, now); - let spent = self.spent; - self.now.iter().any(|(_, since)| spent + now.saturating_duration_since(self.clamp(*since)) >= PC_CALL_HOLDS_AFTER) + fn snapshot(&self) -> ComputeCoalescingStats { + let coalescing_hits = self.coalescing_hits.load(Ordering::Relaxed); + let unique_keyed_builds = self.unique_keyed_builds.load(Ordering::Relaxed); + ComputeCoalescingStats { + keyed_submissions: coalescing_hits.saturating_add(unique_keyed_builds), + coalescing_hits, + unique_keyed_builds, + current_in_flight: self.current_in_flight.load(Ordering::Relaxed), + peak_in_flight: self.peak_in_flight.load(Ordering::Relaxed), + } } } -static PC_CALLS: Mutex<PcCalls> = Mutex::new(PcCalls::new()); -/// From this much time in PC calls since the last frame on, a PC call holds the title: the -/// console's calls return at once. -const PC_CALL_HOLDS_AFTER: std::time::Duration = std::time::Duration::from_millis(250); - -/// Whether one of the title's threads is held where a console title never waits: a bind is -/// waiting for a pipeline still being built, or a PC call is going on after such calls have -/// kept the title's threads for long (`pc_call`). `kernelx::Sleep` does not count that time. -pub fn title_held() -> bool { - HELD.load(Ordering::Acquire) != 0 || held_by_pc_call() -} +static COALESCING: CoalescingCounters = CoalescingCounters::new(); -fn held_by_pc_call() -> bool { - PC_CALLS.lock().unwrap().holds(super::present::presents(), std::time::Instant::now()) +pub fn compute_coalescing_stats() -> ComputeCoalescingStats { + COALESCING.snapshot() } -/// A call of the title into D3D12 that XCL or the PC's driver can keep for long where the -/// console's takes no time: a submission (XCL's uploads and tile mappings before the lists, the -/// driver's compiling in them), a texture's placement, a pipeline built in the call. While it -/// lasts the title is held (`title_held`), once the PC calls since the last frame shown, this -/// one included, have taken `PC_CALL_HOLDS_AFTER`: one long call, or many short ones in a row -/// (a retail title placed 16 384 textures in 29 s without a frame, 1 - 50 ms each). A title -/// that shows its frames is not held by its submissions. -pub struct PcCall(u64); - -pub fn pc_call() -> PcCall { - static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - let id = NEXT.fetch_add(1, Ordering::Relaxed); - PC_CALLS.lock().unwrap().begin(id, super::present::presents(), std::time::Instant::now()); - PcCall(id) +/// Unique completed native pipelines retained behind title-visible stand-ins, by frames since +/// their last use. Measurement only: command lists do not retain bound D3D12 objects, so these +/// ages are not evidence that a pipeline is safe to release. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct RetentionStats { + pub retained_reals: usize, + pub unused_60_frames: usize, + pub unused_600_frames: usize, + pub oldest_unused_frames: u64, } -impl Drop for PcCall { - fn drop(&mut self) { - PC_CALLS.lock().unwrap().end(self.0, super::present::presents(), std::time::Instant::now()); +fn retention_stats_from( + now: u64, + builds: impl IntoIterator<Item = (usize, usize, u64, u64)>, +) -> RetentionStats { + let mut seen = std::collections::HashSet::new(); + let mut stats = RetentionStats::default(); + for (identity, real, last_use, completed) in builds { + if real == 0 || !seen.insert(identity) { + continue; + } + let age = now.saturating_sub(last_use.max(completed)); + stats.retained_reals += 1; + stats.unused_60_frames += (age >= 60) as usize; + stats.unused_600_frames += (age >= 600) as usize; + stats.oldest_unused_frames = stats.oldest_unused_frames.max(age); } + stats } -/// Whether this thread is building a pipeline for `build` (a worker, not one of the title's). -pub(super) fn building_here() -> bool { - BUILDING.with(|b| b.borrow().is_some()) +/// Snapshot for the `XCL_ACTIVITY` thread. The registry locks are taken only by that observer; +/// bind-time tracking is a present counter load plus one relaxed atomic maximum. +pub fn retention_stats() -> RetentionStats { + if !super::memory_report::enabled() { + return RetentionStats::default(); + } + let mut builds = Vec::new(); + for shard in &PENDING.shards { + let entries = shard.lock().unwrap(); + builds.extend(entries.iter().flat_map(|map| map.values()).map(|pending| { + let build = &pending.build; + ( + Arc::as_ptr(build) as usize, + build.real.load(Ordering::Acquire), + build.last_use_frame.load(Ordering::Relaxed), + build.completed_frame.load(Ordering::Relaxed), + ) + })); + } + retention_stats_from(super::present::presents(), builds) } -/// A bind's wait for a pipeline still being built (`title_held`). -struct Held; - -impl Held { - fn new() -> Held { - HELD.fetch_add(1, Ordering::AcqRel); - Held - } +/// One point-in-time, pressure-ready resident selected off the bind thread. A future policy must +/// still recheck age and call `try_evict_current`, which serializes every ownership transition. +#[allow(dead_code)] +struct EvictionCandidate { + build: Arc<Build>, + last_use_frame: u64, + completed_frame: u64, + clear_queued_on_drop: bool, } -impl Drop for Held { +impl Drop for EvictionCandidate { fn drop(&mut self) { - HELD.fetch_sub(1, Ordering::AcqRel); + if self.clear_queued_on_drop { + self.build.candidate_queued.store(false, Ordering::Release); + } } } -pub fn enabled() -> bool { - std::env::var("XCL_ASYNC_PSO").map_or(true, |v| v != "0") -} - -/// Builds the real pipeline: its raw pointer, 0 = failed. -pub type Job = Box<dyn FnOnce() -> usize + Send>; - -/// pipelines a submit will wait for: the workers take these before their queue (`need_by_submit`) -static NEEDED: Mutex<std::collections::VecDeque<Arc<Pending>>> = Mutex::new(std::collections::VecDeque::new()); +impl EvictionCandidate { + fn try_requeue_on<const N: usize>(mut self, candidates: &CandidateQueue<Build, N>) -> Result<(), Self> { + if candidates.push(Arc::downgrade(&self.build)).is_err() { + return Err(self); + } + self.clear_queued_on_drop = false; + Ok(()) + } -fn next_needed() -> Option<Arc<Pending>> { - NEEDED.lock().unwrap().pop_front() -} + /// Return a deferred candidate to the bounded weak journal without opening a duplicate-record + /// window. If a crossing producer filled the freed slot, dropping this owner clears the flag + /// so a later bind can retry instead of leaving the build permanently marked as queued. + fn requeue_on<const N: usize>(self, candidates: &CandidateQueue<Build, N>) -> bool { + self.try_requeue_on(candidates).is_ok() + } -/// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. -fn drop_unstarted_job(p: &Pending) { - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - { - let mut done = p.done.lock().unwrap(); - *done = true; - p.cv.notify_all(); - } - drop(job); + fn into_held(mut self) -> HeldEvictionCandidate { + let build = Arc::downgrade(&self.build); + self.clear_queued_on_drop = false; + HeldEvictionCandidate { build } } } -type Work = Box<dyn FnOnce() + Send>; +/// A saturated observer must conserve the deduplicated identity without retaining the pipeline, +/// its rebuild recipe, or its native generation after the title releases them. +struct HeldEvictionCandidate { build: Weak<Build> } +enum HeldRequeue { Requeued, Held(HeldEvictionCandidate), Expired } -fn queue() -> &'static Mutex<mpsc::Sender<Work>> { - static Q: OnceLock<Mutex<mpsc::Sender<Work>>> = OnceLock::new(); - Q.get_or_init(|| { - let (tx, rx) = mpsc::channel::<Work>(); - let rx = Arc::new(Mutex::new(rx)); - // translation recurses deeply on big programs; DXC itself runs on its own pool - let n = crate::gpu::recomp::dxc::compile_threads(); - for k in 0..n { - let rx = rx.clone(); - let _ = std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || loop { - let next = rx.lock().unwrap().recv(); - let Ok(work) = next else { return }; - while let Some(p) = next_needed() { - build_queued(&p); - } - work(); - }); +impl HeldEvictionCandidate { + fn try_requeue_on<const N: usize>(self, candidates: &CandidateQueue<Build, N>) -> HeldRequeue { + if self.build.upgrade().is_none() { return HeldRequeue::Expired } + match candidates.push(self.build.clone()) { + Ok(()) => HeldRequeue::Requeued, + Err(_) => HeldRequeue::Held(self), } - Mutex::new(tx) - }) -} - -fn enqueue(p: Arc<Pending>) { - let _ = queue().lock().unwrap().send(Box::new(move || build_queued(&p))); + } } -fn build_queued(p: &Arc<Pending>) { - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - drop_unstarted_job(p); +/// Recipe-enabled binds append at most one weak identity per build. This path is reached only after +/// the existing `XCL_PSO_REBUILD_RECIPES` gate selected generation-aware resolution; ordinary +/// binds pay no candidate check, queue operation, registry scan, or allocation. +fn note_eviction_candidate_on<const N: usize>(build: &Arc<Build>, frame: u64, candidates: &CandidateQueue<Build, N>) { + build.last_use_frame.fetch_max(frame, Ordering::Relaxed); + if build.candidate_queued.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() { return; } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(p, job, false); + if candidates.push(Arc::downgrade(build)).is_err() { + build.candidate_queued.store(false, Ordering::Release); } } -/// The caller also drains its batch. Multiple workers can therefore build -/// different chains without ever waiting for a free worker to start a piece. -pub(super) fn build_pieces(jobs: Vec<Job>) -> Vec<usize> { - let count = jobs.len(); - let jobs = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::<Vec<_>>())); - let (send, recv) = mpsc::channel(); - let drain = move || loop { - let job = jobs.lock().unwrap().pop(); - let Some((i, job)) = job else { return }; - let _ = send.send((i, job())); - }; - // the helpers build for this worker's pipeline: the title waiting for it waits for them too - let parent = BUILDING.with(|b| b.borrow().clone()); - for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { - let (drain, parent) = (drain.clone(), parent.clone()); - let _ = queue().lock().unwrap().send(Box::new(move || { - let before = BUILDING.with(|b| b.replace(parent)); - drain(); - BUILDING.with(|b| *b.borrow_mut() = before); - })); +fn note_eviction_candidate(build: &Arc<Build>) { + note_eviction_candidate_on(build, super::present::presents(), eviction_candidates()); +} + +fn resident_candidate(build: &Arc<Build>) -> Option<EvictionCandidate> { + let done = build.done.lock().unwrap(); + if !*done || build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return None; } - drain(); - let mut results = vec![0; count]; - for (i, result) in recv.iter().take(count) { results[i] = result; } - results + let recipe = build.recipe.as_ref()?; + let rebuild = recipe.0.rebuild.lock().unwrap(); + if rebuild.active || rebuild.waiters != 0 { + return None; + } + let real = build.real.load(Ordering::Acquire); + if real == 0 { + return None; + } + let generation = recipe.0.generation.lock().unwrap(); + if generation.residency != Residency::Resident + || generation.resident.as_ref().is_none_or(|resident| resident.raw != real) + { + return None; + } + let last_use_frame = build.last_use_frame.load(Ordering::Relaxed); + let completed_frame = build.completed_frame.load(Ordering::Relaxed); + drop(generation); + drop(rebuild); + drop(done); + Some(EvictionCandidate { + build: build.clone(), last_use_frame, completed_frame, clear_queued_on_drop: true, + }) } -/// Release a pipeline state XCL owns (raw pointer, 0 = none). -pub fn release(p: usize) { - if p != 0 { - unsafe { drop(<windows::Win32::Graphics::Direct3D12::ID3D12PipelineState as windows::core::Interface>::from_raw(p as *mut std::ffi::c_void)) }; +/// Drain at most `limit` journal records on a background policy turn. The weak allocation identity +/// prevents a released stand-in address from turning an old record into a new pipeline. +#[allow(dead_code)] +fn drain_eviction_candidates_on<const N: usize>( + candidates: &CandidateQueue<Build, N>, limit: usize, +) -> Vec<EvictionCandidate> { + let mut selected = Vec::new(); + for _ in 0..limit { + let Some(build) = candidates.pop() else { break }; + let Some(build) = build.upgrade() else { continue }; + match resident_candidate(&build) { + Some(candidate) => selected.push(candidate), + None => { + // A released/orphaned/active/nonresident build is not actionable. Allow a later + // use after its state changes to journal it again. + build.candidate_queued.store(false, Ordering::Release); + } + } } + selected } -/// `standin` went to the title; `job` builds the real pipeline on a worker. -pub fn submit(standin: usize, compute: bool, job: Job) { - submit_as(standin, compute, job, true, 0); +#[allow(dead_code)] +fn drain_eviction_candidates(limit: usize) -> Vec<EvictionCandidate> { + drain_eviction_candidates_on(eviction_candidates(), limit) } -/// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get -/// their stand-in when made and are built when first used – the first bind of a graphics one -/// sends it to the workers, a compute one is built at its first bind. A retail game makes -/// ~51 000 pipelines in its first 30 s and uses few; each one built stays in the driver -/// (~400 KB), and the process ran out of commit. -pub fn lazy() -> bool { - static L: OnceLock<bool> = OnceLock::new(); - *L.get_or_init(|| enabled() && std::env::var("XCL_LAZY_PSO").map_or(true, |v| v != "0")) +#[derive(Clone, Copy)] +struct EvictionSelectionLimits { + max_scan: usize, + max_select: usize, + min_unused_frames: u64, + min_resident_frames: u64, } -/// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low -/// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). -pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { - submit_as(standin, compute, job, false, key); +/// One bounded, point-in-time policy candidate. Actual eviction must still call +/// `try_evict_current`, which revalidates every ownership transition. +#[allow(dead_code)] +struct SelectedEvictionCandidate { + candidate: EvictionCandidate, + unused_frames: u64, + resident_frames: u64, } -fn submit_as(standin: usize, compute: bool, job: Job, send: bool, key: u64) { - let p = Arc::new(Pending { - job: Mutex::new(Some(job)), - sent: std::sync::atomic::AtomicBool::new(send), - real: AtomicUsize::new(0), - driver: AtomicUsize::new(0), - done: Mutex::new(false), - cv: Condvar::new(), - compute, - key, - used: Default::default(), - orphan: Default::default(), - late: Default::default(), - spared: Default::default(), - demand: Default::default(), - }); - PENDING.lock().unwrap().get_or_insert_with(HashMap::new).insert(standin, p.clone()); - static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| { - crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); +/// Frame counters practically never wrap. If they do, treating pre-wrap timestamps as recent is +/// conservative: a policy pauses eviction instead of assigning an enormous, false age. +fn conservative_frame_age(now: u64, since: u64) -> u64 { + now.checked_sub(since).unwrap_or(0) +} + +fn partition_eviction_candidates( + candidates: Vec<EvictionCandidate>, now: u64, limits: EvictionSelectionLimits, +) -> (Vec<SelectedEvictionCandidate>, Vec<EvictionCandidate>) { + if limits.max_select == 0 { + return (Vec::new(), candidates); + } + let mut selected = Vec::new(); + let mut deferred = Vec::new(); + for candidate in candidates { + // A bind after the journal record was drained still updates this atomic while the + // candidate's dedup flag prevents another record. Use that latest point-in-time age, + // not the older snapshot captured by `resident_candidate`. + let last_use = candidate.build.last_use_frame.load(Ordering::Relaxed); + let completed = candidate.build.completed_frame.load(Ordering::Relaxed); + let unused_frames = conservative_frame_age(now, last_use); + let resident_frames = conservative_frame_age(now, completed); + if unused_frames >= limits.min_unused_frames && resident_frames >= limits.min_resident_frames { + selected.push(SelectedEvictionCandidate { candidate, unused_frames, resident_frames }); + } else { + deferred.push(candidate); + } + } + selected.sort_unstable_by(|a, b| { + b.unused_frames + .cmp(&a.unused_frames) + .then_with(|| b.resident_frames.cmp(&a.resident_frames)) + .then_with(|| { + (Arc::as_ptr(&a.candidate.build) as usize).cmp(&(Arc::as_ptr(&b.candidate.build) as usize)) + }) }); - if send { - enqueue(p); - } else if used::known(key) { - if let Some(q) = preload() { - q.list.lock().unwrap().push_back(p); - q.cv.notify_one(); + if selected.len() > limits.max_select { + deferred.extend(selected.drain(limits.max_select..).map(|selected| selected.candidate)); + } + (selected, deferred) +} + +/// Inspect and rank a bounded amount of journalled work on a future background policy turn. This +/// remains deliberately uncalled: pressure admission and the eviction/rehydration trigger are +/// separate stages. +#[allow(dead_code)] +fn select_eviction_candidates_on<const N: usize>( + candidates: &CandidateQueue<Build, N>, now: u64, limits: EvictionSelectionLimits, +) -> Vec<SelectedEvictionCandidate> { + if limits.max_scan == 0 || limits.max_select == 0 { + return Vec::new(); + } + let (selected, deferred) = + partition_eviction_candidates(drain_eviction_candidates_on(candidates, limits.max_scan), now, limits); + for candidate in deferred { + let _ = candidate.requeue_on(candidates); + } + selected +} + +#[allow(dead_code)] +fn select_eviction_candidates(limits: EvictionSelectionLimits) -> Vec<SelectedEvictionCandidate> { + select_eviction_candidates_on(eviction_candidates(), super::present::presents(), limits) +} + +/// Pure admission for a future background eviction/rehydration policy. It deliberately consumes +/// an explicit memory-report sample: sampling DXGI here would put adapter work on whichever thread +/// asked for a decision. Nothing constructs this state today, and its default remains disabled. +#[allow(dead_code)] +#[derive(Clone, Copy)] +struct PressureAdmissionConfig { + enabled: bool, + low_basis_points: u16, + high_basis_points: u16, + max_sample_age_turns: u64, + max_evictions_per_turn: usize, + rehydrate_backoff_turns: u64, + max_rehydrate_backoff_turns: u64, +} + +impl Default for PressureAdmissionConfig { + fn default() -> Self { + Self { + enabled: false, + low_basis_points: 7_500, + high_basis_points: 9_000, + max_sample_age_turns: 1, + max_evictions_per_turn: 1, + rehydrate_backoff_turns: 2, + max_rehydrate_backoff_turns: 64, } } } -/// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): -/// what `xcl shaders --precompile --used-only` builds. -pub fn earlier_used_keys() -> std::collections::HashSet<u64> { - used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) +#[allow(dead_code)] +#[derive(Clone, Copy)] +struct PressureSample { + observed_turn: u64, + segment: super::memory_report::Segment, } -/// The pipelines a title used, by a hash of their shaders, kept between runs -/// (`used-pipelines.txt` beside the DXIL cache, a key a line). -/// -/// A lazy pipeline is built at its first use: until then a graphics one draws nothing, and a -/// compute one is waited for on the title's thread. A retail title's first frames of its world -/// use hundreds of pipelines for the first time at once. The pipelines of an earlier run are -/// built while the title loads instead (`preload`): measured on a build that skips a dispatch -/// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without -/// this and 94 – 150 with it. -mod used { - use std::collections::HashSet; - use std::io::Write; - use std::sync::{Mutex, OnceLock, RwLock}; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum PressureMode { + #[default] + Idle, + Evicting, + Rehydrating, +} - struct Used { - earlier: RwLock<HashSet<u64>>, - now: Mutex<(HashSet<u64>, Option<std::fs::File>)>, +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct PressureDecision { + max_evictions: usize, + allow_rehydrate: bool, +} + +#[allow(dead_code)] +struct PressureAdmission { + config: PressureAdmissionConfig, + mode: PressureMode, + last_observed_turn: Option<u64>, + eviction_budget_turn: Option<u64>, + evictions_issued: usize, + retry_rehydrate_at: Option<u64>, + next_rehydrate_backoff: u64, +} + +const PRESSURE_MAX_TURN_HORIZON: u64 = u64::MAX / 2; + +/// Serial turns practically never differ by half their range. Treat a small wrapped difference as +/// forward progress so one wrap does not make every subsequent pressure sample permanently stale. +fn pressure_turn_after(turn: u64, previous: u64) -> bool { + let difference = turn.wrapping_sub(previous); + difference != 0 && difference <= PRESSURE_MAX_TURN_HORIZON +} + +#[allow(dead_code)] +impl PressureAdmission { + fn new(config: PressureAdmissionConfig) -> Option<Self> { + (config.low_basis_points < config.high_basis_points + && config.high_basis_points <= 10_000 + && config.max_sample_age_turns <= PRESSURE_MAX_TURN_HORIZON + && config.rehydrate_backoff_turns != 0 + && config.rehydrate_backoff_turns <= config.max_rehydrate_backoff_turns + && config.max_rehydrate_backoff_turns <= PRESSURE_MAX_TURN_HORIZON) + .then_some(Self { + next_rehydrate_backoff: config.rehydrate_backoff_turns, + config, + mode: PressureMode::Idle, + last_observed_turn: None, + eviction_budget_turn: None, + evictions_issued: 0, + retry_rehydrate_at: None, + }) + } + + fn decide(&mut self, now: u64, sample: Option<PressureSample>) -> PressureDecision { + if !self.config.enabled { + return PressureDecision::default(); + } + let Some(sample) = sample else { return PressureDecision::default() }; + if sample.segment.budget == 0 + || pressure_turn_after(sample.observed_turn, now) + || now.wrapping_sub(sample.observed_turn) > self.config.max_sample_age_turns + || self.last_observed_turn.is_some_and(|last| !pressure_turn_after(sample.observed_turn, last)) + { + return PressureDecision::default(); + } + self.last_observed_turn = Some(sample.observed_turn); + let usage = u128::from(sample.segment.usage) * 10_000; + let budget = u128::from(sample.segment.budget); + if usage >= budget * u128::from(self.config.high_basis_points) { + self.mode = PressureMode::Evicting; + } else if usage <= budget * u128::from(self.config.low_basis_points) + && self.mode == PressureMode::Evicting + { + self.mode = PressureMode::Rehydrating; + } + match self.mode { + PressureMode::Idle => PressureDecision::default(), + PressureMode::Evicting => { + if self.eviction_budget_turn != Some(now) { + self.eviction_budget_turn = Some(now); + self.evictions_issued = 0; + } + let max_evictions = self.config.max_evictions_per_turn.saturating_sub(self.evictions_issued); + self.evictions_issued += max_evictions; + PressureDecision { max_evictions, allow_rehydrate: false } + } + PressureMode::Rehydrating => PressureDecision { + max_evictions: 0, + allow_rehydrate: self.retry_rehydrate_at.is_none_or(|retry| { + now == retry || pressure_turn_after(now, retry) + }), + }, + } + } + + fn note_rehydrate_result(&mut self, now: u64, succeeded: bool) { + if self.mode != PressureMode::Rehydrating { + return; + } + if succeeded { + self.retry_rehydrate_at = None; + self.next_rehydrate_backoff = self.config.rehydrate_backoff_turns; + return; + } + let delay = self.next_rehydrate_backoff; + self.retry_rehydrate_at = Some(now.wrapping_add(delay)); + self.next_rehydrate_backoff = delay.saturating_mul(2).min(self.config.max_rehydrate_backoff_turns); + } + + fn note_rehydration_complete(&mut self) { + if self.mode == PressureMode::Rehydrating { + self.mode = PressureMode::Idle; + self.retry_rehydrate_at = None; + self.next_rehydrate_backoff = self.config.rehydrate_backoff_turns; + } + } +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct LedgerNativeGeneration { + id: u64, + identity: usize, +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum EvictedBuildState { + Reserved, + Evicted, + RehydrateQueued, + Restored, + Released, + Poisoned, +} + +impl EvictedBuildState { + fn terminal(self) -> bool { + matches!(self, Self::Restored | Self::Released | Self::Poisoned) + } +} + +#[allow(dead_code)] +#[derive(Clone)] +struct EvictedBuildToken { + ledger_generation: u64, + ledger_instance: u64, + slot: usize, + slot_generation: u64, + serial: u64, + build: Weak<Build>, + native: LedgerNativeGeneration, +} + +impl EvictedBuildToken { + fn exact(&self, other: &Self) -> bool { + self.ledger_generation == other.ledger_generation + && self.ledger_instance == other.ledger_instance + && self.slot == other.slot + && self.slot_generation == other.slot_generation + && self.serial == other.serial + && Weak::ptr_eq(&self.build, &other.build) + && self.native == other.native + } + + fn belongs_to(&self, build: &Build) -> bool { + std::ptr::eq(self.build.as_ptr(), build) + } +} + +#[allow(dead_code)] +impl Build { + fn eviction_token(&self) -> Option<EvictedBuildToken> { + self.eviction.lock().unwrap().clone() + } + + fn install_eviction_token(&self, token: &EvictedBuildToken) -> bool { + if !token.belongs_to(self) { + return false; + } + let mut installed = self.eviction.lock().unwrap(); + if installed.is_some() { + return false; + } + *installed = Some(token.clone()); + true + } + + fn clear_eviction_token(&self, token: &EvictedBuildToken) -> bool { + let mut installed = self.eviction.lock().unwrap(); + if installed.as_ref().is_none_or(|current| !current.exact(token)) { + return false; + } + *installed = None; + true + } +} + +struct EvictedBuildEntry { + token: EvictedBuildToken, + state: EvictedBuildState, +} + +struct EvictedBuildSlot { + generation: u64, + entry: Option<EvictedBuildEntry>, +} + +struct EvictedBuildLedgerInner<const N: usize> { + serial: u64, + exhausted: bool, + slots: [EvictedBuildSlot; N], +} + +/// A future eviction path must reserve and arm one exact record before detaching native owners. +/// This remains private and unconstructed; snapshots contain only weak identities and hold no +/// ledger lock while a later pressure worker inspects Build or D3D state. +#[allow(dead_code)] +struct EvictedBuildLedger<const N: usize> { + generation: u64, + instance: u64, + inner: Mutex<EvictedBuildLedgerInner<N>>, +} + +#[allow(dead_code)] +#[derive(Clone)] +struct EvictedBuildRecord { + token: EvictedBuildToken, + state: EvictedBuildState, +} + +static NEXT_EVICTED_LEDGER_INSTANCE: AtomicU64 = AtomicU64::new(1); + +fn allocate_evicted_ledger_instance(counter: &AtomicU64) -> Option<u64> { + let mut current = counter.load(Ordering::Relaxed); + loop { + let next = current.checked_add(1)?; + match counter.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => return Some(current), + Err(actual) => current = actual, + } + } +} + +#[allow(dead_code)] +impl<const N: usize> EvictedBuildLedger<N> { + fn new(generation: u64) -> Option<Self> { + if N == 0 || generation == 0 { + return None; + } + let instance = allocate_evicted_ledger_instance(&NEXT_EVICTED_LEDGER_INSTANCE)?; + Some(Self { + generation, + instance, + inner: Mutex::new(EvictedBuildLedgerInner { + serial: 0, + exhausted: false, + slots: std::array::from_fn(|_| EvictedBuildSlot { generation: 0, entry: None }), + }), + }) + } + + fn reserve<'a>( + &'a self, build: &Arc<Build>, native: LedgerNativeGeneration, + ) -> Option<EvictedBuildReservation<'a, N>> { + let mut inner = self.inner.lock().unwrap(); + if inner.exhausted { + return None; + } + let slot = inner.slots.iter().position(|slot| slot.entry.is_none())?; + let Some(serial) = inner.serial.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let Some(slot_generation) = inner.slots[slot].generation.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let token = EvictedBuildToken { + ledger_generation: self.generation, + ledger_instance: self.instance, + slot, + slot_generation, + serial, + build: Arc::downgrade(build), + native, + }; + inner.serial = serial; + inner.slots[slot].generation = slot_generation; + inner.slots[slot].entry = Some(EvictedBuildEntry { token: token.clone(), state: EvictedBuildState::Reserved }); + Some(EvictedBuildReservation { ledger: self, token, armed: false }) + } + + fn set_state(&self, token: &EvictedBuildToken, from: EvictedBuildState, to: EvictedBuildState) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if entry.state != from || !entry.token.exact(token) { + return false; + } + entry.state = to; + true + } + + fn rehydrate_queued(&self, token: &EvictedBuildToken) -> bool { + self.set_state(token, EvictedBuildState::Evicted, EvictedBuildState::RehydrateQueued) + } + + fn rehydrate_retry(&self, token: &EvictedBuildToken) -> bool { + self.set_state(token, EvictedBuildState::RehydrateQueued, EvictedBuildState::Evicted) + } + + fn state(&self, token: &EvictedBuildToken) -> Option<EvictedBuildState> { + let inner = self.inner.lock().unwrap(); + let entry = inner.slots.get(token.slot)?.entry.as_ref()?; + entry.token.exact(token).then_some(entry.state) + } + + fn finish(&self, token: &EvictedBuildToken, terminal: EvictedBuildState) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if !entry.token.exact(token) { + return false; + } + let allowed = match terminal { + EvictedBuildState::Restored => entry.state == EvictedBuildState::RehydrateQueued, + EvictedBuildState::Released | EvictedBuildState::Poisoned => { + matches!(entry.state, EvictedBuildState::Evicted | EvictedBuildState::RehydrateQueued) + } + _ => false, + }; + if !allowed { return false } + entry.state = terminal; + true + } + + fn retire(&self, token: &EvictedBuildToken) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(slot) = inner.slots.get_mut(token.slot) else { return false }; + if slot.entry.as_ref().is_none_or(|entry| !entry.state.terminal() || !entry.token.exact(token)) { + return false; + } + slot.entry = None; + true + } + + fn records(&self, limit: usize) -> Vec<EvictedBuildRecord> { + let mut inner = self.inner.lock().unwrap(); + let mut records = Vec::new(); + for slot in &mut inner.slots { + let Some(entry) = slot.entry.as_mut() else { continue }; + if !entry.state.terminal() && entry.token.build.strong_count() == 0 { + entry.state = EvictedBuildState::Released; + } + if records.len() == limit { + break; + } + records.push(EvictedBuildRecord { token: entry.token.clone(), state: entry.state }); + } + records + } +} + +#[allow(dead_code)] +struct EvictedBuildReservation<'a, const N: usize> { + ledger: &'a EvictedBuildLedger<N>, + token: EvictedBuildToken, + armed: bool, +} + +#[allow(dead_code)] +impl<const N: usize> EvictedBuildReservation<'_, N> { + /// Arm before native detachment. From this point, dropping either this guard or its returned + /// token cannot erase the fail-closed record; a failed detach must finish it as Poisoned. + fn arm_detach(mut self) -> Option<EvictedBuildToken> { + if !self.ledger.set_state(&self.token, EvictedBuildState::Reserved, EvictedBuildState::Evicted) { + return None; + } + self.armed = true; + Some(self.token.clone()) + } +} + +impl<const N: usize> Drop for EvictedBuildReservation<'_, N> { + fn drop(&mut self) { + if !self.armed { + let mut inner = self.ledger.inner.lock().unwrap(); + if let Some(slot) = inner.slots.get_mut(self.token.slot) { + if slot.entry.as_ref().is_some_and(|entry| { + entry.state == EvictedBuildState::Reserved && entry.token.exact(&self.token) + }) { + slot.entry = None; + } + } + } + } +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct PressureObservation { + mode: PressureMode, + scanned: usize, + eligible: usize, + deferred: usize, + discarded: usize, + requeue_saturated: usize, +} + +impl PressureObservation { + fn line(self) -> String { + format!( + "pipeline pressure observation: {:?}; {} scanned, {} eligible, {} deferred, {} discarded, {} requeue saturated", + self.mode, self.scanned, self.eligible, self.deferred, self.discarded, self.requeue_saturated, + ) + } +} + +struct PressureObserver { + admission: PressureAdmission, + limits: EvictionSelectionLimits, + held: Vec<HeldEvictionCandidate>, +} + +impl PressureObserver { + fn new(config: PressureAdmissionConfig, limits: EvictionSelectionLimits) -> Option<Self> { + PressureAdmission::new(config).map(|admission| Self { + admission, held: Vec::with_capacity(limits.max_scan), limits, + }) + } + + /// Observe and immediately requeue every actionable candidate. This deliberately cannot evict: + /// the diagnostic validates pressure admission and candidate flow without changing residency. + fn observe_on<const N: usize>( + &mut self, + candidates: &CandidateQueue<Build, N>, + turn: u64, + frame: u64, + sample: Option<PressureSample>, + ) -> PressureObservation { + self.observe_on_after_drain(candidates, turn, frame, sample, || {}) + } + + fn observe_on_after_drain<const N: usize>( + &mut self, + candidates: &CandidateQueue<Build, N>, + turn: u64, + frame: u64, + sample: Option<PressureSample>, + after_drain: impl FnOnce(), + ) -> PressureObservation { + let decision = self.admission.decide(turn, sample); + let mut observation = PressureObservation { mode: self.admission.mode, ..Default::default() }; + + // Conserve exact weak identities until this one-scan backlog returns to the journal. + let pending = std::mem::replace(&mut self.held, Vec::with_capacity(self.limits.max_scan)); + for candidate in pending { + match candidate.try_requeue_on(candidates) { + HeldRequeue::Requeued => {} + HeldRequeue::Held(candidate) => self.held.push(candidate), + HeldRequeue::Expired => observation.discarded += 1, + } + } + observation.requeue_saturated = self.held.len(); + if !self.held.is_empty() || decision.max_evictions == 0 { + return observation; + } + let limits = EvictionSelectionLimits { + max_scan: self.limits.max_scan.min(decision.max_evictions), + max_select: self.limits.max_select.min(decision.max_evictions), + ..self.limits + }; + let mut drained = Vec::new(); + let mut nonactionable = Vec::new(); + for _ in 0..limits.max_scan { + let Some(weak) = candidates.pop() else { break }; + observation.scanned += 1; + let Some(build) = weak.upgrade() else { + observation.discarded += 1; + continue; + }; + match resident_candidate(&build) { + Some(candidate) => drained.push(candidate), + None => nonactionable.push(HeldEvictionCandidate { build: weak }), + } + } + after_drain(); + let (selected, deferred) = partition_eviction_candidates(drained, frame, limits); + observation.eligible = selected.len(); + observation.deferred = deferred.len() + nonactionable.len(); + for candidate in selected.into_iter().map(|selected| selected.candidate).chain(deferred) { + if let Err(candidate) = candidate.try_requeue_on(candidates) { + self.held.push(candidate.into_held()); + } + } + for candidate in nonactionable { + match candidate.try_requeue_on(candidates) { + HeldRequeue::Requeued => {} + HeldRequeue::Held(candidate) => self.held.push(candidate), + HeldRequeue::Expired => observation.discarded += 1, + } + } + observation.requeue_saturated = self.held.len(); + observation + } +} + +fn pressure_observe_gate_value(value: Option<&str>) -> bool { value.is_some_and(|value| value.trim() == "1") } + +fn pressure_observer() -> Option<&'static Mutex<PressureObserver>> { + static OBSERVER: OnceLock<Option<Mutex<PressureObserver>>> = OnceLock::new(); + OBSERVER.get_or_init(|| { + let requested = std::env::var("XCL_PSO_PRESSURE_OBSERVE").ok(); + if !pressure_observe_gate_value(requested.as_deref()) || !rebuild_recipes_enabled() { + return None; + } + let config = PressureAdmissionConfig { + enabled: true, + max_sample_age_turns: 0, + max_evictions_per_turn: 8, + ..Default::default() + }; + let limits = EvictionSelectionLimits { + max_scan: 32, + max_select: 8, + min_unused_frames: 600, + min_resident_frames: 60, + }; + crate::xlog_info!( + "D3D12.X: XCL_PSO_PRESSURE_OBSERVE=1 - observing pipeline pressure only; pipelines are not evicted" + ); + PressureObserver::new(config, limits).map(Mutex::new) + }).as_ref() +} + +/// Called only by the existing activity observer after it has obtained and released the DXGI +/// memory snapshot. No title or submission thread samples the adapter or scans candidates. +pub(crate) fn observe_pressure_turn( + turn: u64, local: Option<super::memory_report::Segment>, +) -> Option<String> { + let observer = pressure_observer()?; + let sample = local.map(|segment| PressureSample { observed_turn: turn, segment }); + Some(observer.lock().unwrap().observe_on( + eviction_candidates(), turn, super::present::presents(), sample, + ).line()) +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydratePriority { Background, Foreground } + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydrateRequestReceipt { Refused, Queued { priority: RehydratePriority } } + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydrateCompletion { Reserved, Refused, Queued, Cancelled, Panicked, BuildFailed, Released, + Succeeded { replacement: LedgerNativeGeneration } } + +impl RehydrateCompletion { + fn terminal(self) -> bool { !matches!(self, Self::Reserved | Self::Queued) } +} + +#[allow(dead_code)] +#[derive(Clone)] +struct RehydrateAttemptToken { registry_instance: u64, slot: usize, slot_generation: u64, + serial: u64, attempt_generation: u64, evicted: EvictedBuildToken } + +mod rehydrate_success { + use super::*; + enum Authority { Current, Published } + pub(super) struct Proof { attempt: RehydrateAttemptToken, build: Weak<Build>, recipe: Recipe, + replacement: NativeGeneration, authority: Authority } + impl Proof { + pub(super) fn new(attempt: &RehydrateAttemptToken, build: &Arc<Build>, + replacement: &NativeGeneration) -> Option<Self> { + if !Weak::ptr_eq(&attempt.evicted.build, &Arc::downgrade(build)) { return None } + let recipe = build.recipe.as_ref()?; + let (current, residency) = recipe.pin_with_residency(build.real.load(Ordering::Acquire)); + (residency == Residency::Resident && current.as_ref().is_some_and(|current| current.same(replacement))).then(|| + Self { attempt: attempt.clone(), build: Arc::downgrade(build), recipe: recipe.clone(), + replacement: replacement.clone(), authority: Authority::Current }) + } + pub(super) fn published(attempt: &RehydrateAttemptToken, build: &Build, recipe: &Recipe, + replacement: &NativeGeneration) -> Option<Self> { + if attempt.evicted.build.as_ptr() != build as *const Build + || !Weak::ptr_eq(&replacement.recipe, &Arc::downgrade(&recipe.0)) + || build.recipe.as_ref().is_none_or(|owned| !Arc::ptr_eq(&owned.0, &recipe.0)) { return None } + let (current, residency) = recipe.pin_with_residency(replacement.raw()); + if residency != Residency::Resident || current.as_ref().is_none_or(|current| !current.same(replacement)) { return None } + Some(Self { attempt: attempt.clone(), build: attempt.evicted.build.clone(), recipe: recipe.clone(), + replacement: replacement.clone(), authority: Authority::Published }) + } + pub(super) fn valid_locked(&self, attempt: &RehydrateAttemptToken, build: &Arc<Build>) -> bool { + if !self.attempt.exact(attempt) { return false } + if !Weak::ptr_eq(&self.build, &Arc::downgrade(build)) { return false } + let Some(recipe) = build.recipe.as_ref() else { return false }; + Arc::ptr_eq(&recipe.0, &self.recipe.0) && match self.authority { + Authority::Current => recipe.0.resident_generation.load(Ordering::Acquire) == self.replacement.id(), + Authority::Published => Weak::ptr_eq(&self.replacement.recipe, &Arc::downgrade(&recipe.0)), + } + } + + pub(super) fn replacement(&self) -> LedgerNativeGeneration { self.replacement.ledger_identity() } + pub(super) fn pin(&self) -> NativeGeneration { self.replacement.clone() } + } +} + +impl RehydrateAttemptToken { + fn exact(&self, other: &Self) -> bool { + self.registry_instance == other.registry_instance + && self.slot == other.slot + && self.slot_generation == other.slot_generation + && self.serial == other.serial + && self.attempt_generation == other.attempt_generation + && self.evicted.exact(&other.evicted) + } +} + +struct RehydrateReceiptEntry { token: RehydrateAttemptToken, state: RehydrateCompletion, priority: RehydratePriority } +struct RehydrateReceiptSlot { generation: u64, entry: Option<RehydrateReceiptEntry> } +struct RehydrateReceiptInner<const N: usize> { serial: u64, exhausted: bool, slots: [RehydrateReceiptSlot; N] } + +/// Bounded truth about asynchronous rehydration attempts. Queue submission and pipeline building +/// happen outside this lock; accepting a queue request records only Queued, never success. +#[allow(dead_code)] +struct RehydrateReceiptRegistry<const N: usize> { instance: u64, inner: Mutex<RehydrateReceiptInner<N>> } + +#[allow(dead_code)] +#[derive(Clone)] +struct RehydrateReceiptRecord { token: RehydrateAttemptToken, state: RehydrateCompletion, priority: RehydratePriority } + +static NEXT_REHYDRATE_RECEIPT_INSTANCE: AtomicU64 = AtomicU64::new(1); + +#[allow(dead_code)] +impl<const N: usize> RehydrateReceiptRegistry<N> { + fn new() -> Option<Self> { + if N == 0 { return None } + let instance = allocate_evicted_ledger_instance(&NEXT_REHYDRATE_RECEIPT_INSTANCE)?; + Some(Self { instance, inner: Mutex::new(RehydrateReceiptInner { serial: 0, exhausted: false, + slots: std::array::from_fn(|_| RehydrateReceiptSlot { generation: 0, entry: None }) }) }) + } + + fn reserve<'a>(&'a self, evicted: &EvictedBuildToken) -> Option<RehydrateReceiptReservation<'a, N>> { + let mut inner = self.inner.lock().unwrap(); + self.reserve_locked(&mut inner, evicted) + } + + fn reserve_unique<'a>( + &'a self, evicted: &EvictedBuildToken, allow_new: bool, + ) -> Result<Option<RehydrateReceiptReservation<'a, N>>, RehydrateReceiptRecord> { + let mut inner = self.inner.lock().unwrap(); + if let Some(entry) = inner.slots.iter().filter_map(|slot| slot.entry.as_ref()) + .find(|entry| entry.token.evicted.exact(evicted)) { + return Err(RehydrateReceiptRecord { + token: entry.token.clone(), state: entry.state, priority: entry.priority, + }); + } + if !allow_new { return Ok(None) } + Ok(self.reserve_locked(&mut inner, evicted)) + } + + fn reserve_locked<'a>( + &'a self, inner: &mut RehydrateReceiptInner<N>, evicted: &EvictedBuildToken, + ) -> Option<RehydrateReceiptReservation<'a, N>> { + if inner.exhausted { return None } + let slot = inner.slots.iter().position(|slot| slot.entry.is_none())?; + let Some(serial) = inner.serial.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let Some(slot_generation) = inner.slots[slot].generation.checked_add(1) else { + inner.exhausted = true; + return None; + }; + let token = RehydrateAttemptToken { registry_instance: self.instance, slot, slot_generation, + serial, attempt_generation: serial, evicted: evicted.clone() }; + inner.serial = serial; + inner.slots[slot].generation = slot_generation; + inner.slots[slot].entry = Some(RehydrateReceiptEntry { + token: token.clone(), state: RehydrateCompletion::Reserved, priority: RehydratePriority::Background, + }); + Some(RehydrateReceiptReservation { registry: self, token, submitted: false }) + } + + fn publish(&self, token: &RehydrateAttemptToken, state: RehydrateCompletion) -> bool { + self.publish_checked(token, state) + } + + fn publish_checked(&self, token: &RehydrateAttemptToken, mut state: RehydrateCompletion) -> bool { + if !state.terminal() || matches!(state, RehydrateCompletion::Succeeded { .. }) { return false } + let live_build = token.evicted.build.upgrade(); + if live_build.is_none() { state = RehydrateCompletion::Released } + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if !entry.token.exact(token) { return false } + let allowed = match state { + RehydrateCompletion::Refused => matches!(entry.state, RehydrateCompletion::Reserved | RehydrateCompletion::Queued), + RehydrateCompletion::Released => matches!(entry.state, RehydrateCompletion::Reserved | RehydrateCompletion::Queued), + RehydrateCompletion::Cancelled | RehydrateCompletion::Panicked + | RehydrateCompletion::BuildFailed => entry.state == RehydrateCompletion::Queued, + RehydrateCompletion::Succeeded { replacement } => entry.state == RehydrateCompletion::Queued + && replacement != entry.token.evicted.native, + _ => false, + }; + if !allowed { return false } + entry.state = state; + true + } + + fn publish_success(&self, token: &RehydrateAttemptToken, proof: &rehydrate_success::Proof) -> bool { + let Some(build) = token.evicted.build.upgrade() else { + return self.publish(token, RehydrateCompletion::Released); + }; + let done = build.done.lock().unwrap(); + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + drop(done); + return self.publish(token, RehydrateCompletion::Released); + } + if !proof.valid_locked(token, &build) { + return false; + } + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + let replacement = proof.replacement(); + if entry.state != RehydrateCompletion::Queued || !entry.token.exact(token) + || replacement == entry.token.evicted.native { return false } + entry.state = RehydrateCompletion::Succeeded { replacement }; true + } + + fn accept(&self, token: &RehydrateAttemptToken, priority: RehydratePriority) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if entry.state != RehydrateCompletion::Reserved || !entry.token.exact(token) { return false } + entry.state = RehydrateCompletion::Queued; entry.priority = priority; true + } + + fn promote(&self, token: &RehydrateAttemptToken) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(entry) = inner.slots.get_mut(token.slot).and_then(|slot| slot.entry.as_mut()) else { return false }; + if entry.state != RehydrateCompletion::Queued || !entry.token.exact(token) { return false } + entry.priority = RehydratePriority::Foreground; true + } + + fn records(&self, limit: usize) -> Vec<RehydrateReceiptRecord> { + let mut inner = self.inner.lock().unwrap(); + let mut records = Vec::new(); + for slot in &mut inner.slots { + let Some(entry) = slot.entry.as_mut() else { continue }; + if !entry.state.terminal() && entry.token.evicted.build.strong_count() == 0 { + entry.state = RehydrateCompletion::Released; + } + if records.len() == limit { break } + records.push(RehydrateReceiptRecord { + token: entry.token.clone(), state: entry.state, priority: entry.priority, + }); + } + records + } + + fn retire(&self, token: &RehydrateAttemptToken) -> bool { + let mut inner = self.inner.lock().unwrap(); + let Some(slot) = inner.slots.get_mut(token.slot) else { return false }; + if slot.entry.as_ref().is_none_or(|entry| !entry.state.terminal() || !entry.token.exact(token)) { + return false; + } + slot.entry = None; + true + } +} + +#[allow(dead_code)] +struct RehydrateReceiptReservation<'a, const N: usize> { registry: &'a RehydrateReceiptRegistry<N>, + token: RehydrateAttemptToken, submitted: bool } + +#[allow(dead_code)] +impl<'a, const N: usize> RehydrateReceiptReservation<'a, N> { + fn refused(mut self) -> Option<(RehydrateRequestReceipt, RehydrateAttemptToken)> { + self.submitted = self.registry.publish(&self.token, RehydrateCompletion::Refused); + self.submitted.then(|| (RehydrateRequestReceipt::Refused, self.token.clone())) + } + + fn accepted(mut self, priority: RehydratePriority) -> Option<(RehydrateRequestReceipt, RehydrateQueuedReceipt<'a, N>)> { + if !self.registry.accept(&self.token, priority) { + return None; + } + self.submitted = true; + let token = self.token.clone(); + Some((RehydrateRequestReceipt::Queued { priority }, RehydrateQueuedReceipt { + registry: self.registry, token, completed: false, + })) + } + + fn accepted_token(mut self, priority: RehydratePriority) -> Option<RehydrateAttemptToken> { + if !self.registry.accept(&self.token, priority) { return None } + self.submitted = true; + Some(self.token.clone()) + } +} + +impl<const N: usize> Drop for RehydrateReceiptReservation<'_, N> { + fn drop(&mut self) { + if !self.submitted { + let mut inner = self.registry.inner.lock().unwrap(); + if let Some(slot) = inner.slots.get_mut(self.token.slot) { + if slot.entry.as_ref().is_some_and(|entry| { + entry.state == RehydrateCompletion::Reserved && entry.token.exact(&self.token) + }) { + slot.entry = None; + } + } + } + } +} + +#[allow(dead_code)] +struct RehydrateQueuedReceipt<'a, const N: usize> { registry: &'a RehydrateReceiptRegistry<N>, + token: RehydrateAttemptToken, completed: bool } + +#[allow(dead_code)] +impl<const N: usize> RehydrateQueuedReceipt<'_, N> { + fn replacement(&self, build: &Arc<Build>, replacement: &NativeGeneration) -> Option<rehydrate_success::Proof> { + rehydrate_success::Proof::new(&self.token, build, replacement) + } + + fn complete(mut self, completion: RehydrateCompletion) -> bool { + self.completed = self.registry.publish(&self.token, completion); + self.completed + } + + fn complete_success(mut self, proof: rehydrate_success::Proof) -> bool { + self.completed = self.registry.publish_success(&self.token, &proof); + self.completed + } +} + +impl<const N: usize> Drop for RehydrateQueuedReceipt<'_, N> { + fn drop(&mut self) { + if !self.completed { + let completion = if std::thread::panicking() { + RehydrateCompletion::Panicked + } else { + RehydrateCompletion::Cancelled + }; + let _ = self.registry.publish(&self.token, completion); + } + } +} + +#[allow(dead_code)] +#[derive(Clone)] +struct RestorationRetry { token: EvictedBuildToken } + +#[allow(dead_code)] +/// Private and unwired: composes exact eviction identity with one queue job and its strong result. +struct RestorationCoordinator<const E: usize, const R: usize> { + evicted: EvictedBuildLedger<E>, + receipts: Arc<RehydrateReceiptRegistry<R>>, + admission: Mutex<()>, + attempts: Mutex<Vec<Arc<RestorationAttempt>>>, + #[cfg(test)] + captured: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, + #[cfg(test)] + before_rebuild: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, + #[cfg(test)] + before_classified_request: Arc<Mutex<Option<Box<dyn FnOnce() + Send>>>>, +} + +/// An exact ledger record installed on its build before native detachment can begin. Dropping an +/// uncommitted preparation clears only that record and poisons its ledger slot; committing leaves +/// both visible for a later restoration request. +#[allow(dead_code)] +struct InstalledEviction<'a, const E: usize, const R: usize> { + coordinator: &'a RestorationCoordinator<E, R>, + build: Arc<Build>, + token: Option<EvictedBuildToken>, +} + +#[allow(dead_code)] +impl<const E: usize, const R: usize> InstalledEviction<'_, E, R> { + fn token(&self) -> &EvictedBuildToken { + self.token.as_ref().expect("committed eviction preparation") + } + + /// Consume only after exact generation revalidation and native detachment have succeeded. + fn commit(mut self) -> EvictedBuildToken { + self.token.take().expect("committed eviction preparation") + } + + fn cleanup(&mut self) { + let Some(token) = self.token.take() else { return }; + let _ = self.build.clear_eviction_token(&token); + let _ = self.coordinator.evicted.finish(&token, EvictedBuildState::Poisoned); + let _ = self.coordinator.evicted.retire(&token); + } +} + +impl<const E: usize, const R: usize> Drop for InstalledEviction<'_, E, R> { + fn drop(&mut self) { + self.cleanup(); + } +} + +struct RestorationAttempt { + token: RehydrateAttemptToken, + job: Mutex<Option<JobHandle>>, + submitted: Condvar, + foreground: AtomicBool, + outcome: Mutex<Option<RestorationOutcome>>, +} + +#[allow(dead_code)] +enum RestorationOutcome { + Failed(RehydrateCompletion), + Succeeded(NativeGeneration), +} + +#[derive(Clone)] +#[allow(dead_code)] +struct RestorationTicket<const R: usize> { + receipts: Arc<RehydrateReceiptRegistry<R>>, + attempt: Arc<RestorationAttempt>, +} + +#[allow(dead_code)] +enum RestorationQueue<'a, const E: usize, const R: usize> { + Queued(RestorationQueued<'a, E, R>), + Existing, + Promoted, +} + +#[allow(dead_code)] +struct RestorationQueued<'a, const E: usize, const R: usize> { + coordinator: &'a RestorationCoordinator<E, R>, + receipt: RehydrateQueuedReceipt<'a, R>, +} + +#[allow(dead_code)] +impl<const E: usize, const R: usize> RestorationCoordinator<E, R> { + fn new(generation: u64) -> Option<Self> { + Some(Self { + evicted: EvictedBuildLedger::new(generation)?, + receipts: Arc::new(RehydrateReceiptRegistry::new()?), + admission: Mutex::new(()), + attempts: Mutex::new(Vec::new()), + #[cfg(test)] + captured: Arc::new(Mutex::new(None)), + #[cfg(test)] + before_rebuild: Arc::new(Mutex::new(None)), + #[cfg(test)] + before_classified_request: Arc::new(Mutex::new(None)), + }) + } + + fn reserve_eviction<'a>( + &'a self, build: &Arc<Build>, native: LedgerNativeGeneration, + ) -> Option<EvictedBuildReservation<'a, E>> { + self.evicted.reserve(build, native) + } + + /// Arm the exact ledger record, then publish it on the build. A future eviction path must + /// perform its state-chain revalidation and detach only while holding the returned guard. + fn install_eviction<'a>( + &'a self, build: &Arc<Build>, native: LedgerNativeGeneration, + ) -> Option<InstalledEviction<'a, E, R>> { + let token = self.reserve_eviction(build, native)?.arm_detach()?; + if !build.install_eviction_token(&token) { + let _ = self.evicted.finish(&token, EvictedBuildState::Poisoned); + let _ = self.evicted.retire(&token); + return None; + } + Some(InstalledEviction { coordinator: self, build: build.clone(), token: Some(token) }) + } + + fn refuse_rehydrate(&self, evicted: &EvictedBuildToken) -> bool { + match self.receipts.reserve_unique(evicted, true) { + Ok(Some(reservation)) => reservation.refused().is_some(), + Ok(None) | Err(_) => false, + } + } + + fn queue_rehydrate( + &self, evicted: &EvictedBuildToken, priority: RehydratePriority, background_ready: bool, + ) -> Option<RestorationQueue<'_, E, R>> { + let allow_new = priority == RehydratePriority::Foreground || background_ready; + let reservation = match self.receipts.reserve_unique(evicted, allow_new) { + Err(record) => { + if !record.state.terminal() && priority == RehydratePriority::Foreground + && record.priority != RehydratePriority::Foreground { + return self.receipts.promote(&record.token).then_some(RestorationQueue::Promoted); + } + return Some(RestorationQueue::Existing); + } + Ok(Some(reservation)) => reservation, + Ok(None) => return None, + }; + let (_, receipt) = reservation.accepted(priority)?; + if !self.evicted.rehydrate_queued(evicted) { + drop(receipt); + return None; + } + Some(RestorationQueue::Queued(RestorationQueued { coordinator: self, receipt })) + } + + /// Snapshot receipt state first, then mutate the exact eviction record, then retire the + /// receipt. No two policy locks overlap, and a stale token can never touch a reused slot. + fn reconcile(&self, limit: usize) -> usize { + let attempts = self.attempts.lock().unwrap().clone(); + for attempt in &attempts { + if attempt.outcome.lock().unwrap().is_some() { continue } + let status = attempt.job.lock().unwrap().as_ref().map(JobHandle::status); + let completion = match status { + Some(JobStatus::Cancelled) => Some(RehydrateCompletion::Cancelled), + Some(JobStatus::Panicked) => Some(RehydrateCompletion::Panicked), + _ => None, + }; + if let Some(completion) = completion { + let _ = self.receipts.publish(&attempt.token, completion); + } + } + let records = self.receipts.records(limit); + let mut reconciled = 0; + for record in records.into_iter().filter(|record| record.state.terminal()) { + let token = &record.token.evicted; + let ok = match record.state { + RehydrateCompletion::Refused => self.evicted.rehydrate_retry(token) + || self.evicted.state(token) == Some(EvictedBuildState::Evicted), + RehydrateCompletion::Cancelled | RehydrateCompletion::Panicked | RehydrateCompletion::BuildFailed => { + self.evicted.rehydrate_retry(token) || self.evicted.state(token) == Some(EvictedBuildState::Evicted) + } + RehydrateCompletion::Released => self.evicted.finish(token, EvictedBuildState::Released) + || self.evicted.state(token) == Some(EvictedBuildState::Released), + RehydrateCompletion::Succeeded { .. } => self.evicted.finish(token, EvictedBuildState::Restored) + || self.evicted.state(token) == Some(EvictedBuildState::Restored), + _ => false, + }; + if !ok && self.evicted.state(token).is_some_and(|state| !state.terminal()) { + let _ = self.evicted.finish(token, EvictedBuildState::Poisoned); + } + if self.receipts.retire(&record.token) { reconciled += 1 } + // Receipt, build, and ledger locks never overlap. Exact matching makes this safe + // after address or bounded-slot reuse, and retryable failures remain nonterminal. + if self.evicted.state(token).is_some_and(EvictedBuildState::terminal) { + if let Some(build) = token.build.upgrade() { + let _ = build.clear_eviction_token(token); + } + let _ = self.evicted.retire(token); + } + } + let removed = { + let mut attempts = self.attempts.lock().unwrap(); + let (active, removed) = std::mem::take(&mut *attempts).into_iter().partition(|attempt| { + attempt.outcome.lock().unwrap().is_none() + && attempt.job.lock().unwrap().as_ref().is_none_or(|job| { + matches!(job.status(), JobStatus::Queued | JobStatus::Running) + }) + }); + *attempts = active; + removed + }; + drop(removed); // NativeGeneration/COM destruction can re-enter pipeline bookkeeping. + reconciled + } + + fn retries(&self, limit: usize) -> Vec<RestorationRetry> { + self.evicted.records(limit).into_iter().filter_map(|record| { + (record.state == EvictedBuildState::Evicted).then_some(RestorationRetry { token: record.token }) + }).collect() + } + + /// Private queue seam for a later bind integration. Submission never invokes the work inline; + /// foreground demand uses the normal worker band, while an exact queued background attempt is + /// promoted through its retained `JobHandle`. + fn request_exact_on( + &self, evicted: &EvictedBuildToken, priority: RehydratePriority, q: &BuildQueue, + ) -> Option<RestorationTicket<R>> { + let build = evicted.build.upgrade()?; + let admission = self.admission.lock().unwrap(); + if let Some(attempt) = self.attempts.lock().unwrap().iter() + .find(|attempt| attempt.token.evicted.exact(evicted)).cloned() { + drop(admission); + if priority == RehydratePriority::Foreground { + attempt.foreground.store(true, Ordering::Release); + if let Some(job) = attempt.job.lock().unwrap().as_ref() { + let _ = job.promote(Priority::Foreground); + } + let _ = self.receipts.promote(&attempt.token); + } + return Some(RestorationTicket { receipts: self.receipts.clone(), attempt }); + } + let receipt = match self.receipts.reserve_unique(evicted, true) { + Ok(Some(receipt)) => receipt, + Err(_) => return None, + Ok(None) => return None, + }; + let token = receipt.accepted_token(priority)?; + let attempt = Arc::new(RestorationAttempt { + token: token.clone(), job: Mutex::new(None), submitted: Condvar::new(), + foreground: AtomicBool::new(priority == RehydratePriority::Foreground), outcome: Mutex::new(None), + }); + self.attempts.lock().unwrap().push(attempt.clone()); + drop(admission); + if !self.evicted.rehydrate_queued(evicted) { + let _ = self.receipts.publish(&token, RehydrateCompletion::Cancelled); + *attempt.outcome.lock().unwrap() = Some(RestorationOutcome::Failed(RehydrateCompletion::Cancelled)); + attempt.submitted.notify_all(); + return Some(RestorationTicket { receipts: self.receipts.clone(), attempt }); + } + let reservation = match reserve_rehydrate_on(&build) { + Ok(reservation) => reservation, + Err(result) => { + let completion = if result == RehydrateRequest::Abandoned { + RehydrateCompletion::Released + } else { + RehydrateCompletion::Cancelled + }; + let _ = self.receipts.publish(&token, completion); + *attempt.outcome.lock().unwrap() = Some(RestorationOutcome::Failed(completion)); + attempt.submitted.notify_all(); + return Some(RestorationTicket { receipts: self.receipts.clone(), attempt }); + } + }; + let worker_attempt = attempt.clone(); + let receipts = self.receipts.clone(); + let queued_build = build.clone(); + #[cfg(test)] + let captured = self.captured.clone(); + #[cfg(test)] + let before_rebuild = self.before_rebuild.clone(); + let queue_priority = if attempt.foreground.load(Ordering::Acquire) { + Priority::Foreground + } else { + Priority::Speculative + }; + let job = q.submit(queue_priority, Box::new(move || { + #[cfg(test)] + if let Some(before_rebuild) = before_rebuild.lock().unwrap().take() { before_rebuild() } + let recipe = reservation.recipe.clone(); + let (result, proof) = rebuild_reserved_pinned(&queued_build, &recipe, Some(&token)); + drop(reservation); + #[cfg(test)] + if let Some(captured) = captured.lock().unwrap().take() { captured() } + let outcome = match (result, proof) { + (RebuildResult::Published { .. }, Some(proof)) => { + let pin = proof.pin(); + if receipts.publish_success(&token, &proof) { RestorationOutcome::Succeeded(pin) } + else { RestorationOutcome::Failed(RehydrateCompletion::Released) } + } + (RebuildResult::Published { .. }, None) => RestorationOutcome::Failed(RehydrateCompletion::BuildFailed), + (RebuildResult::Failed, _) => RestorationOutcome::Failed(RehydrateCompletion::BuildFailed), + (RebuildResult::Abandoned, _) => RestorationOutcome::Failed(RehydrateCompletion::Released), + (RebuildResult::NotReady, _) => RestorationOutcome::Failed(RehydrateCompletion::Cancelled), + }; + if let RestorationOutcome::Failed(completion) = &outcome { + let _ = receipts.publish(&token, *completion); + } + *worker_attempt.outcome.lock().unwrap() = Some(outcome); + })); + match job { + Some(job) => { + *attempt.job.lock().unwrap() = Some(job.clone()); + if attempt.foreground.load(Ordering::Acquire) { let _ = job.promote(Priority::Foreground); } + attempt.submitted.notify_all(); + } + None => { + let _ = self.receipts.publish(&attempt.token, RehydrateCompletion::Refused); + *attempt.outcome.lock().unwrap() = Some(RestorationOutcome::Failed(RehydrateCompletion::Refused)); + attempt.submitted.notify_all(); + } + } + Some(RestorationTicket { receipts: self.receipts.clone(), attempt }) + } + + fn request_foreground(&self, evicted: &EvictedBuildToken) -> Option<RestorationTicket<R>> { + if !start_normal_workers() { return None } + self.request_exact_on(evicted, RehydratePriority::Foreground, queue()) + } +} + +#[allow(dead_code)] +impl<const R: usize> RestorationTicket<R> { + fn token(&self) -> &RehydrateAttemptToken { &self.attempt.token } + + /// Waits only on this queue job, with no Build, recipe, ledger, list, or coordinator lock. + fn wait_and_take_pin(&self) -> Result<NativeGeneration, RehydrateCompletion> { + let mut job = self.attempt.job.lock().unwrap(); + while job.is_none() && self.attempt.outcome.lock().unwrap().is_none() { + job = self.attempt.submitted.wait(job).unwrap(); + } + let queued = job.clone(); + drop(job); + let status = queued.map(|job| job.wait()); + let outcome = self.attempt.outcome.lock().unwrap(); + match outcome.as_ref() { + Some(RestorationOutcome::Succeeded(pin)) => Ok(pin.clone()), + Some(RestorationOutcome::Failed(completion)) => Err(*completion), + None => { + let completion = match status { + Some(JobStatus::Panicked) => RehydrateCompletion::Panicked, + Some(JobStatus::Cancelled) => RehydrateCompletion::Cancelled, + _ => RehydrateCompletion::Cancelled, + }; + drop(outcome); + let _ = self.receipts.publish(&self.attempt.token, completion); + Err(completion) + } + } + } +} + +#[allow(dead_code)] +impl<const E: usize, const R: usize> RestorationQueued<'_, E, R> { + fn token(&self) -> &RehydrateAttemptToken { &self.receipt.token } + fn replacement(&self, build: &Arc<Build>, replacement: &NativeGeneration) -> Option<rehydrate_success::Proof> { + self.receipt.replacement(build, replacement) + } + fn promote(&self) -> bool { self.coordinator.receipts.promote(&self.receipt.token) } + fn complete(self, completion: RehydrateCompletion) -> bool { self.receipt.complete(completion) } + fn complete_success(self, proof: rehydrate_success::Proof) -> bool { self.receipt.complete_success(proof) } +} + +fn forget_in_flight(build: &Arc<Build>) { + let Some(key) = &build.compute_key else { return }; + let mut registry = IN_FLIGHT.lock().unwrap(); + let Some(builds) = registry.as_mut() else { return }; + if builds.get(key.as_ref()).is_some_and(|weak| Weak::ptr_eq(weak, &Arc::downgrade(build))) { + builds.remove(key.as_ref()); + COALESCING.finished(1); + } +} + +/// The build is done (`real`: its pipeline, 0 = failed). +fn complete(build: &Arc<Build>, real: usize) { + if real == 0 { + FAILED.fetch_add(1, Ordering::Relaxed); + } else { + BUILT.fetch_add(1, Ordering::Relaxed); + build.completed_frame.store(super::present::presents(), Ordering::Relaxed); + } + let (orphan, replaced_generation) = { + let mut done = build.done.lock().unwrap(); + let orphan = build.orphan.load(Ordering::Acquire); + let mut replaced_generation = None; + if !orphan { + if real != 0 { + if let Some(recipe) = &build.recipe { + replaced_generation = recipe.publish(real).1; + } + } else if let Some(recipe) = &build.recipe { + recipe.mark_failed(); + } + build.real.store(real, Ordering::Release); + } + *done = true; + build.finish_queued(); + build.cv.notify_all(); + (orphan, replaced_generation) + }; + // outside `done`: a pipeline Release override can re-enter pipeline bookkeeping + drop(replaced_generation); + if orphan { + release(real); + } + forget_in_flight(build); +} + +/// Result shared by callers that requested the same overlapping recipe rebuild. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RebuildResult { + NotReady, + Failed, + Abandoned, + Published { generation: u64 }, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RebuildRequest { + Queued, + Coalesced, + NotReady, + Abandoned, + Unavailable, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum RehydrateRequest { + Queued, + Coalesced, + NotReady, + Abandoned, + Resident, + Unavailable, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum EvictResult { + Evicted { generation: u64 }, + NotReady, + Active, + Abandoned, + Unavailable, + NotResident, +} + +/// Detach both owners of the current native generation. This remains deliberately uncalled until +/// a policy and a nonblocking rehydration path choose the correctness/performance tradeoff after +/// eviction. Exact recording and receipt pins independently keep the detached generation alive. +#[allow(dead_code)] +fn try_evict_current(build: &Build) -> EvictResult { + let done = build.done.lock().unwrap(); + if !*done { + return EvictResult::NotReady; + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return EvictResult::Abandoned; + } + let Some(recipe) = build.recipe.as_ref() else { return EvictResult::Unavailable }; + // Keep the rebuild turn reserved through the raw-owner swap. Every rebuild reservation takes + // this lock, and publication takes `done`, so neither transition can cross this one. + let rebuild = recipe.0.rebuild.lock().unwrap(); + if rebuild.active || rebuild.waiters != 0 { + return EvictResult::Active; + } + let raw = build.real.load(Ordering::Acquire); + if raw == 0 { + return EvictResult::NotResident; + } + let Some(generation) = recipe.detach_current(raw) else { return EvictResult::NotResident }; + let generation_id = generation.id(); + let old_raw = build.real.swap(0, Ordering::AcqRel); + debug_assert_eq!(old_raw, raw); + drop(rebuild); + drop(done); + + // COM Release can re-enter pipeline bookkeeping. Drop both owners outside every state lock; + // an exact recording/receipt pin is another Arc to `generation` and survives independently. + drop(generation); + release(old_raw); + EvictResult::Evicted { generation: generation_id } +} + +/// Build and atomically publish one replacement generation. This remains deliberately uncalled +/// until submitted recording pins are retained to exact GPU retirement receipts: publication is +/// safe, but a policy must not make an old generation reclaimable while the GPU can still use it. +#[allow(dead_code)] +fn rebuild_once(build: &Build) -> Option<RebuildResult> { + let recipe = build.recipe.as_ref()?; + { + let done = build.done.lock().unwrap(); + if !*done { + return Some(RebuildResult::NotReady); + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return Some(RebuildResult::Abandoned); + } + } + match recipe.begin_rebuild() { + RebuildTurn::Follower(result) => return Some(result), + RebuildTurn::Leader => {} + } + + Some(rebuild_reserved(build, recipe)) +} + +/// Run an attempt which already owns the recipe's rebuild turn. +fn rebuild_reserved(build: &Build, recipe: &Recipe) -> RebuildResult { + rebuild_reserved_pinned(build, recipe, None).0 +} + +/// The exact published generation is retained before `Build.done` is released, so a later +/// eviction cannot invalidate a successful foreground restoration before its waiter pins it. +fn rebuild_reserved_pinned( + build: &Build, recipe: &Recipe, attempt: Option<&RehydrateAttemptToken>, +) -> (RebuildResult, Option<rehydrate_success::Proof>) { + // A queued request can lose its last title-visible owner before a worker starts it. The queued + // Arc keeps this state alive only so the attempt can retire; it must not revive the pipeline. + { + let done = build.done.lock().unwrap(); + if !*done || build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + drop(done); + recipe.finish_rebuild(RebuildResult::Abandoned); + return (RebuildResult::Abandoned, None); + } + } + + // Do expensive driver work without Build.done or the recipe state held. Binds keep using the + // current immutable generation throughout the rebuild. + let raw = run_job(recipe.initial_job()); + let mut replaced_generation = None; + let mut replaced_raw = 0; + let mut published = None; + let result = if raw == 0 { + RebuildResult::Failed + } else { + let _done = build.done.lock().unwrap(); + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + RebuildResult::Abandoned + } else { + let (generation, replaced) = recipe.publish(raw); + published = attempt.and_then(|attempt| rehydrate_success::Proof::published(attempt, build, recipe, &generation)); + replaced_generation = replaced; + replaced_raw = build.real.swap(raw, Ordering::AcqRel); + build.completed_frame.store(super::present::presents(), Ordering::Relaxed); + RebuildResult::Published { generation: generation.id() } + } + }; + + // Publish the result before COM Release, which can re-enter pipeline bookkeeping. Never drop + // either old owner under Build.done or while this attempt is still blocking followers. + recipe.finish_rebuild(result); + drop(replaced_generation); + if matches!(result, RebuildResult::Published { .. }) { + release(replaced_raw); + } else if raw != 0 { + release(raw); + } + (result, published) +} +static BUILT: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); +static QUEUED_BUILDS: AtomicUsize = AtomicUsize::new(0); +/// binds waiting right now for a pipeline still being built (`title_held`) +static HELD: AtomicUsize = AtomicUsize::new(0); + +/// The PC calls of the title's threads (`pc_call`): the ones going on, and how long the ones +/// that ended took since the last frame was shown. +struct PcCalls { + /// (id, when it began) + now: Vec<(u64, std::time::Instant)>, + /// the frames shown when `spent` began to count (`None` before the first observation) + frame: Option<u64>, + /// when the latest frame advance was first observed; calls that started earlier are clamped here + frame_since: Option<std::time::Instant>, + /// the time of the PC calls that ended since then + spent: std::time::Duration, +} + +impl PcCalls { + const fn new() -> Self { + Self { now: Vec::new(), frame: None, frame_since: None, spent: std::time::Duration::ZERO } + } + + /// `frame` frames have been shown: the calls before the last of them are not this wait's. + fn at(&mut self, frame: u64, now: std::time::Instant) { + match self.frame { + None => self.frame = Some(frame), + Some(prev) if frame > prev => { + self.frame = Some(frame); + self.frame_since = Some(now); + self.spent = std::time::Duration::ZERO; + } + Some(_) => {} + } + } + + fn clamp(&self, since: std::time::Instant) -> std::time::Instant { + self.frame_since.map_or(since, |f| since.max(f)) + } + + fn begin(&mut self, id: u64, frame: u64, now: std::time::Instant) { + self.at(frame, now); + self.now.push((id, now)); + } + + fn end(&mut self, id: u64, frame: u64, now: std::time::Instant) { + self.at(frame, now); + if let Some(i) = self.now.iter().position(|c| c.0 == id) { + let (_, since) = self.now.swap_remove(i); + self.spent += now.saturating_duration_since(self.clamp(since)); + } + } + + /// Whether a call going on holds the title: the PC calls since the last frame, it included, + /// have taken `PC_CALL_HOLDS_AFTER`. + fn holds(&mut self, frame: u64, now: std::time::Instant) -> bool { + self.at(frame, now); + let spent = self.spent; + self.now.iter().any(|(_, since)| spent + now.saturating_duration_since(self.clamp(*since)) >= PC_CALL_HOLDS_AFTER) + } +} + +static PC_CALLS: Mutex<PcCalls> = Mutex::new(PcCalls::new()); +/// From this much time in PC calls since the last frame on, a PC call holds the title: the +/// console's calls return at once. +const PC_CALL_HOLDS_AFTER: std::time::Duration = std::time::Duration::from_millis(250); + +/// Whether one of the title's threads is held where a console title never waits: a bind is +/// waiting for a pipeline still being built, or a PC call is going on after such calls have +/// kept the title's threads for long (`pc_call`). `kernelx::Sleep` does not count that time. +pub fn title_held() -> bool { + HELD.load(Ordering::Acquire) != 0 || held_by_pc_call() +} + +fn held_by_pc_call() -> bool { + PC_CALLS.lock().unwrap().holds(super::present::presents(), std::time::Instant::now()) +} + +/// A call of the title into D3D12 that XCL or the PC's driver can keep for long where the +/// console's takes no time: a submission (XCL's uploads and tile mappings before the lists, the +/// driver's compiling in them), a texture's placement, a pipeline built in the call. While it +/// lasts the title is held (`title_held`), once the PC calls since the last frame shown, this +/// one included, have taken `PC_CALL_HOLDS_AFTER`: one long call, or many short ones in a row +/// (a retail title placed 16 384 textures in 29 s without a frame, 1 - 50 ms each). A title +/// that shows its frames is not held by its submissions. +pub struct PcCall(u64); + +pub fn pc_call() -> PcCall { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = NEXT.fetch_add(1, Ordering::Relaxed); + PC_CALLS.lock().unwrap().begin(id, super::present::presents(), std::time::Instant::now()); + PcCall(id) +} + +impl Drop for PcCall { + fn drop(&mut self) { + PC_CALLS.lock().unwrap().end(self.0, super::present::presents(), std::time::Instant::now()); + } +} + +/// Whether this thread is building a pipeline for `build` (a worker, not one of the title's). +pub(super) fn building_here() -> bool { + BUILDING.with(|b| b.borrow().is_some()) +} + +/// A bind's wait for a pipeline still being built (`title_held`). +struct Held; + +impl Held { + fn new() -> Held { + HELD.fetch_add(1, Ordering::AcqRel); + Held + } +} + +impl Drop for Held { + fn drop(&mut self) { + HELD.fetch_sub(1, Ordering::AcqRel); + } +} + +pub fn enabled() -> bool { + std::env::var("XCL_ASYNC_PSO").map_or(true, |v| v != "0") +} + +fn recipe_gate_value(value: Option<&str>) -> bool { + value.is_some_and(|value| value.trim() == "1") +} + +/// Whether background builds retain their immutable inputs after the initial one-shot job. +/// This is preparation for a future eviction policy only; it does not rebuild or evict PSOs. +pub(super) fn rebuild_recipes_enabled() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let value = std::env::var("XCL_PSO_REBUILD_RECIPES").ok(); + let on = recipe_gate_value(value.as_deref()); + if on { + crate::xlog_info!("D3D12.X: XCL_PSO_REBUILD_RECIPES=1 - retaining pipeline rebuild inputs only; pipelines are not evicted or rebuilt"); + } + on + }) +} + +/// Builds the real pipeline: its raw pointer, 0 = failed. +pub type Job = Box<dyn FnOnce() -> usize + Send>; + +struct Generation<T> { + id: u64, + raw: usize, + _owner: T, +} + +struct GenerationSlot<T> { + next: u64, + resident: Option<Arc<Generation<T>>>, + residency: Residency, +} + +impl<T> Default for GenerationSlot<T> { + fn default() -> Self { Self { next: 0, resident: None, residency: Residency::Rebuilding } } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum Residency { + Resident, + Evicted, + Rebuilding, + Failed, +} + +impl<T> GenerationSlot<T> { + fn publish(&mut self, raw: usize, owner: T) -> (Arc<Generation<T>>, Option<Arc<Generation<T>>>) { + self.next = self.next.checked_add(1).expect("pipeline generation id exhausted"); + let generation = Arc::new(Generation { id: self.next, raw, _owner: owner }); + let replaced = self.resident.replace(generation.clone()); + self.residency = Residency::Resident; + (generation, replaced) + } + + fn pin(&self, raw: usize) -> Option<Arc<Generation<T>>> { + self.resident.as_ref().filter(|generation| generation.raw == raw).cloned() + } + + fn mark_rebuilding(&mut self) -> Residency { + let previous = self.residency; + self.residency = Residency::Rebuilding; + previous + } + + fn finish_rebuild(&mut self, result: RebuildResult, previous: Option<Residency>) { + self.residency = if self.resident.is_some() { + Residency::Resident + } else { + match result { + RebuildResult::Failed => Residency::Failed, + RebuildResult::Abandoned | RebuildResult::NotReady => match previous { + Some(Residency::Evicted) => Residency::Evicted, + Some(Residency::Failed) => Residency::Failed, + _ => Residency::Failed, + }, + RebuildResult::Published { .. } => Residency::Failed, + } + }; + } + + fn detach(&mut self, raw: usize) -> Option<Arc<Generation<T>>> { + if self.residency != Residency::Resident || self.resident.as_ref()?.raw != raw { + return None; + } + self.residency = Residency::Evicted; + self.resident.take() + } +} + +struct RecipeInner { + build: Box<dyn Fn() -> usize + Send + Sync>, + generation: Mutex<GenerationSlot<ID3D12PipelineState>>, + resident_generation: AtomicU64, + rebuild: Mutex<RebuildState>, + rebuild_done: Condvar, +} + +#[derive(Default)] +struct RebuildState { + active: bool, + completed: u64, + waiters: usize, + last: Option<RebuildResult>, + from: Option<Residency>, +} + +#[derive(Debug)] +enum RebuildTurn { + Leader, + Follower(RebuildResult), +} + +/// One immutable native pipeline generation. Its strong owner keeps the exact object alive even +/// after the title releases its stand-in or a later rebuild publishes the same raw address. +#[derive(Clone)] +pub(super) struct NativeGeneration { + generation: Arc<Generation<ID3D12PipelineState>>, + recipe: Weak<RecipeInner>, +} + +impl NativeGeneration { + #[allow(dead_code)] // consumed by the later retirement diagnostics stage + pub(super) fn id(&self) -> u64 { self.generation.id } + #[allow(dead_code)] // exposed to focused generation-capture tests + pub(super) fn raw(&self) -> usize { self.generation.raw } + pub(super) fn same(&self, other: &Self) -> bool { Arc::ptr_eq(&self.generation, &other.generation) } + // The owner allocation, rather than `raw`, distinguishes ABA reuse by a later generation. + fn identity(&self) -> usize { Arc::as_ptr(&self.generation) as usize } + #[allow(dead_code)] + fn ledger_identity(&self) -> LedgerNativeGeneration { + LedgerNativeGeneration { id: self.id(), identity: self.identity() } + } +} + +struct GenerationRetirements<G, R> { + pending: Vec<(R, Vec<G>)>, + poisoned: Vec<G>, + poisoned_identities: Option<HashSet<usize>>, +} + +impl<G, R> GenerationRetirements<G, R> { + const fn new() -> Self { + Self { pending: Vec::new(), poisoned: Vec::new(), poisoned_identities: None } + } + + fn sweep(&mut self, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec<G>)> { + let mut retired = Vec::new(); + let mut i = 0; + while i < self.pending.len() { + if complete(&self.pending[i].0) { + retired.push(self.pending.swap_remove(i)); + } else { + i += 1; + } + } + retired + } + + fn retire_pending(&mut self, receipt: R, pins: Vec<G>, complete: impl Fn(&R) -> bool) -> Vec<(R, Vec<G>)> { + if !pins.is_empty() { + self.pending.push((receipt, pins)); + } + self.sweep(complete) + } + + fn poison(&mut self, pins: Vec<G>, identity: impl Fn(&G) -> usize) { + let identities = self.poisoned_identities.get_or_insert_with(HashSet::new); + for pin in pins { + if identities.insert(identity(&pin)) { + self.poisoned.push(pin); + } + } + } +} + +fn dedup_generations<G>(pins: impl Iterator<Item = G>, identity: impl Fn(&G) -> usize) -> Vec<G> { + let mut unique = Vec::new(); + let mut identities = HashSet::new(); + for pin in pins { + if identities.insert(identity(&pin)) { + unique.push(pin); + } + } + unique +} + +static RETIRING_GENERATIONS: Mutex<GenerationRetirements<NativeGeneration, super::alloc_pool::SubmissionReceipt>> = + Mutex::new(GenerationRetirements::new()); + +/// Keep the exact native generations used by one executed title submission until its strong +/// queue receipt completes. Completed batches are swept whenever another pinned batch arrives. +pub(super) fn retire_native_generations<'a>( + receipt: super::alloc_pool::SubmissionReceipt, + pins: impl Iterator<Item = &'a NativeGeneration>, +) { + if receipt.is_complete() { + return; + } + let pins = dedup_generations(pins.cloned(), NativeGeneration::identity); + if pins.is_empty() { + return; + } + let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); + let retired = retiring.retire_pending(receipt, pins, super::alloc_pool::SubmissionReceipt::is_complete); + drop(retiring); + drop(retired); +} + +/// Native execution began but no exact retirement marker could be recorded. Retain every exact +/// generation permanently: dropping any of them could free a pipeline still referenced by GPU work. +pub(super) fn poison_native_generations<'a>(pins: impl Iterator<Item = &'a NativeGeneration>) { + let pins = dedup_generations(pins.cloned(), NativeGeneration::identity); + if pins.is_empty() { + return; + } + let mut retiring = RETIRING_GENERATIONS.lock().unwrap(); + let retired = retiring.sweep(super::alloc_pool::SubmissionReceipt::is_complete); + retiring.poison(pins, NativeGeneration::identity); + drop(retiring); + drop(retired); +} + +/// Rebuildable immutable inputs for one pipeline. The first build and any later rebuild use the +/// same operation; retaining it does not by itself schedule or run more work. Its existing opt-in +/// allocation also owns the native generation, so ordinary one-shot builds allocate no new state. +#[derive(Clone)] +pub(super) struct Recipe(Arc<RecipeInner>); + +impl Recipe { + pub(super) fn new(build: impl Fn() -> usize + Send + Sync + 'static) -> Self { + Self(Arc::new(RecipeInner { + build: Box::new(build), + generation: Mutex::new(GenerationSlot::default()), + resident_generation: AtomicU64::new(0), + rebuild: Mutex::new(RebuildState::default()), + rebuild_done: Condvar::new(), + })) + } + + fn run(&self) -> usize { + (self.0.build)() + } + + /// Publish before `Build.real` becomes visible. The returned generation owns one independent + /// COM reference; the raw result remains the existing `Build.real` owner. + fn publish(&self, raw: usize) -> (NativeGeneration, Option<NativeGeneration>) { + let p = raw as *mut std::ffi::c_void; + let owner = unsafe { ID3D12PipelineState::from_raw_borrowed(&p) }.expect("non-null pipeline result").clone(); + let mut slot = self.0.generation.lock().unwrap(); + let (generation, replaced) = slot.publish(raw, owner); + self.0.resident_generation.store(generation.id, Ordering::Release); + drop(slot); + let wrap = |generation| NativeGeneration { generation, recipe: Arc::downgrade(&self.0) }; + (wrap(generation), replaced.map(wrap)) + } + + fn pin_with_residency(&self, raw: usize) -> (Option<NativeGeneration>, Residency) { + let generation = self.0.generation.lock().unwrap(); + (generation.pin(raw).map(|generation| NativeGeneration { + generation, recipe: Arc::downgrade(&self.0), + }), generation.residency) + } + + fn mark_failed(&self) { + let mut generation = self.0.generation.lock().unwrap(); + if generation.resident.is_none() { + generation.residency = Residency::Failed; + self.0.resident_generation.store(0, Ordering::Release); + } + } + + fn detach_current(&self, raw: usize) -> Option<NativeGeneration> { + let mut slot = self.0.generation.lock().unwrap(); + let detached = slot.detach(raw).map(|generation| NativeGeneration { + generation, recipe: Arc::downgrade(&self.0), + }); + if detached.is_some() { self.0.resident_generation.store(0, Ordering::Release) } + drop(slot); + detached + } + + fn initial_job(&self) -> Job { + let recipe = self.clone(); + Box::new(move || recipe.run()) + } + + fn begin_rebuild(&self) -> RebuildTurn { + let mut state = self.0.rebuild.lock().unwrap(); + loop { + if !state.active && state.waiters == 0 { + state.active = true; + state.from = Some(self.0.generation.lock().unwrap().mark_rebuilding()); + return RebuildTurn::Leader; + } + if state.active { + let completed = state.completed; + state.waiters += 1; + while state.completed == completed { + state = self.0.rebuild_done.wait(state).unwrap(); + } + let result = state.last.expect("completed rebuild without a result"); + state.waiters -= 1; + if state.waiters == 0 { + self.0.rebuild_done.notify_all(); + } + return RebuildTurn::Follower(result); + } + // Followers of the completed attempt must consume `last` before another leader can + // overwrite it. A request arriving during this drain starts (or joins) the next one. + state = self.0.rebuild_done.wait(state).unwrap(); + } + } + + /// Reserve one asynchronous attempt without waiting for an attempt already in flight. + fn reserve_rebuild(&self) -> bool { + let mut state = self.0.rebuild.lock().unwrap(); + if state.active || state.waiters != 0 { + return false; + } + state.active = true; + state.from = Some(self.0.generation.lock().unwrap().mark_rebuilding()); + true + } + + /// Reserve a build only when no native generation is resident. Failed attempts are retryable; + /// a live current generation is never replaced by this path. + fn reserve_rehydrate(&self) -> Result<u64, RehydrateRequest> { + let mut state = self.0.rebuild.lock().unwrap(); + if state.active || state.waiters != 0 { + return Err(RehydrateRequest::Coalesced); + } + let mut generation = self.0.generation.lock().unwrap(); + if !matches!(generation.residency, Residency::Evicted | Residency::Failed) || generation.resident.is_some() { + return Err(RehydrateRequest::Resident); + } + let turn = state.completed; + state.active = true; + state.from = Some(generation.mark_rebuilding()); + Ok(turn) + } + + fn finish_rebuild(&self, result: RebuildResult) { + let mut state = self.0.rebuild.lock().unwrap(); + self.0.generation.lock().unwrap().finish_rebuild(result, state.from.take()); + state.last = Some(result); + state.active = false; + state.completed = state.completed.checked_add(1).expect("pipeline rebuild serial exhausted"); + self.0.rebuild_done.notify_all(); + } + + /// A queued reservation was refused or discarded before it ran. Restore its retryable state + /// and wake any synchronous follower which joined it. + fn cancel_reserved_rebuild(&self, turn: u64) { + let mut state = self.0.rebuild.lock().unwrap(); + if !state.active || state.completed != turn { + return; + } + self.0.generation.lock().unwrap().finish_rebuild(RebuildResult::NotReady, state.from.take()); + state.last = Some(RebuildResult::NotReady); + state.active = false; + state.completed = state.completed.checked_add(1).expect("pipeline rebuild serial exhausted"); + self.0.rebuild_done.notify_all(); + } +} + +/// Own one exact accepted rehydration turn until its queued closure completes. Queue refusal, +/// cancellation, shutdown, or an unwind drops the closure and restores a retryable residency; +/// its completed serial prevents an old guard from cancelling a newer turn. +struct RehydrateReservation { + recipe: Recipe, + turn: u64, +} + +impl Drop for RehydrateReservation { + fn drop(&mut self) { + self.recipe.cancel_reserved_rebuild(self.turn); + } +} + +/// Drop an unstarted orphaned job outside all locks and wake any concurrent waiter. +fn drop_unstarted_job(build: &Arc<Build>) { + let job = build.job.lock().unwrap().take(); + if let Some(job) = job { + build.cancel_queued(); + { + let mut done = build.done.lock().unwrap(); + *done = true; + build.finish_queued(); + build.cv.notify_all(); + } + drop(job); + forget_in_flight(build); + } +} + +fn queue() -> &'static BuildQueue { + static Q: OnceLock<BuildQueue> = OnceLock::new(); + Q.get_or_init(BuildQueue::new) +} + +pub fn ranked_preload_stats() -> RankedPreloadStats { + let snapshot = queue().ranked_preload_stats(); + RankedPreloadStats { + submissions: snapshot.submissions, + started: snapshot.started, + promoted: snapshot.promoted, + } +} + +fn start_normal_workers() -> bool { + static STARTED: OnceLock<bool> = OnceLock::new(); + *STARTED.get_or_init(|| { + let q = queue(); + // translation recurses deeply on big programs; DXC itself runs on its own pool + let n = crate::gpu::recomp::dxc::compile_threads(); + let mut started = 0; + for k in 0..n { + let worker = q.worker_between(Priority::BoundSoon, Priority::Foreground); + if std::thread::Builder::new().name(format!("xcl-pso-{k}")).stack_size(64 << 20).spawn(move || { + NORMAL_WORKER.set(true); + worker.run(); + }).is_ok() { + started += 1; + } + } + started != 0 + }) +} + +/// Normal workers waiting for a huge driver-compile slot, and bounded replacements serving their +/// priority band. Preload workers have their own band and do not need foreground replacements. +static PARKED_NORMAL: AtomicUsize = AtomicUsize::new(0); +static NORMAL_HELPERS: AtomicUsize = AtomicUsize::new(0); +static NORMAL_HELPERS_STARTED: AtomicUsize = AtomicUsize::new(0); + +/// A normal pipeline worker is about to wait for a huge driver-compile slot. A bounded helper +/// serves its queue until workers return; calls from title and preload threads do nothing. +pub(super) fn parked_for_big_compile() -> ParkedWorker { + if !NORMAL_WORKER.get() { + return ParkedWorker(false); + } + let parked = PARKED_NORMAL.fetch_add(1, Ordering::AcqRel) + 1; + let most = parked.min(crate::gpu::recomp::dxc::compile_threads()); + let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire); + while helpers < most { + match NORMAL_HELPERS.compare_exchange(helpers, helpers + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => { + spawn_normal_helper(helpers); + break; + } + Err(now) => helpers = now, + } + } + ParkedWorker(true) +} + +pub(super) struct ParkedWorker(bool); + +impl Drop for ParkedWorker { + fn drop(&mut self) { + if self.0 { + PARKED_NORMAL.fetch_sub(1, Ordering::AcqRel); + } + } +} + +fn spawn_normal_helper(k: usize) { + let worker = queue().worker_between(Priority::BoundSoon, Priority::Foreground); + let n = NORMAL_HELPERS_STARTED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: a pipeline worker waits for a huge compile slot – a helper serves its queue meanwhile ({n} helpers so far)"); + } + let spawned = std::thread::Builder::new().name(format!("xcl-pso-h{k}")).stack_size(64 << 20).spawn(move || { + NORMAL_WORKER.set(true); + let mut retired = false; + worker.run_while(|| { + retired = retire_normal_helper(); + !retired + }); + if !retired { + NORMAL_HELPERS.fetch_sub(1, Ordering::AcqRel); + } + }); + if spawned.is_err() { + NORMAL_HELPERS.fetch_sub(1, Ordering::AcqRel); + } +} + +/// Reserve this helper's retirement once more helpers exist than parked normal workers. +fn retire_normal_helper() -> bool { + let mut helpers = NORMAL_HELPERS.load(Ordering::Acquire); + while helpers > PARKED_NORMAL.load(Ordering::Acquire) { + match NORMAL_HELPERS.compare_exchange(helpers, helpers - 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return true, + Err(now) => helpers = now, + } + } + false +} + +fn start_preload_workers() -> bool { + static STARTED: OnceLock<bool> = OnceLock::new(); + *STARTED.get_or_init(|| { + let q = queue(); + let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); + let mut started = 0; + for k in 0..n { + let worker = q.worker_between(Priority::Speculative, Priority::Preload); + if std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { + unsafe { + use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; + SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); + } + PRELOAD_WORKER.set(true); + worker.run(); + }).is_ok() { + started += 1; + } + } + started != 0 + }) +} + +fn run_reserved_rebuild(build: Arc<Build>, recipe: Recipe) { + use windows_sys::Win32::System::Threading::{GetCurrentThread, GetCurrentThreadId, SetThreadPriority, THREAD_PRIORITY_NORMAL}; + let preload = PRELOAD_WORKER.get(); + BUILDING.with(|b| *b.borrow_mut() = Some(build.clone())); + if preload { + let mut demand = build.demand.lock().unwrap(); + demand.preload_thread = unsafe { GetCurrentThreadId() }; + if build.wanted.load(Ordering::Acquire) { + unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL) }; + } + } + let _running = RunningBuild { build: &build, preload }; + let _ = rebuild_reserved(&build, &recipe); +} + +fn run_reserved_rehydrate(build: Arc<Build>, reservation: RehydrateReservation) { + let recipe = reservation.recipe.clone(); + run_reserved_rebuild(build, recipe); + // `rebuild_reserved` completed the turn. Drop is intentionally still armed so an unwind or a + // future early return cannot strand Rebuilding; it observes inactive after normal completion. + drop(reservation); +} + +fn reserve_rehydrate_on(build: &Arc<Build>) -> Result<RehydrateReservation, RehydrateRequest> { + let done = build.done.lock().unwrap(); + if !*done { return Err(RehydrateRequest::NotReady) } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return Err(RehydrateRequest::Abandoned); + } + if build.real.load(Ordering::Acquire) != 0 { return Err(RehydrateRequest::Resident) } + let Some(recipe) = build.recipe.clone() else { return Err(RehydrateRequest::Unavailable) }; + let turn = recipe.reserve_rehydrate()?; + Ok(RehydrateReservation { recipe, turn }) +} + +fn request_rebuild_on(build: Arc<Build>, q: &BuildQueue) -> RebuildRequest { + let recipe = { + let done = build.done.lock().unwrap(); + if !*done { + return RebuildRequest::NotReady; + } + if build.owners.load(Ordering::Acquire) == 0 || build.orphan.load(Ordering::Acquire) { + return RebuildRequest::Abandoned; + } + let Some(recipe) = build.recipe.clone() else { return RebuildRequest::Unavailable }; + if !recipe.reserve_rebuild() { + return RebuildRequest::Coalesced; + } + recipe + }; + let failed_recipe = recipe.clone(); + if q.submit(Priority::Speculative, Box::new(move || run_reserved_rebuild(build, recipe))).is_none() { + failed_recipe.finish_rebuild(RebuildResult::Failed); + return RebuildRequest::Unavailable; + } + RebuildRequest::Queued +} + +fn request_rehydrate_on(build: Arc<Build>, q: &BuildQueue) -> RehydrateRequest { + let reservation = match reserve_rehydrate_on(&build) { + Ok(reservation) => reservation, + Err(result) => return result, + }; + if q.submit(Priority::Speculative, Box::new(move || run_reserved_rehydrate(build, reservation))).is_none() { + // The refused work is dropped by `submit`, restoring Evicted/Failed before it returns. + return RehydrateRequest::Unavailable; + } + RehydrateRequest::Queued +} + +/// Queue one low-priority replacement build. This is intentionally uncalled until an eviction +/// policy has selected a pipeline; requesting never waits for driver work on the title thread. +#[allow(dead_code)] +fn request_rebuild(pso: usize) -> RebuildRequest { + let Some(pending) = entry(pso) else { return RebuildRequest::Unavailable }; + if !start_preload_workers() { + return RebuildRequest::Unavailable; + } + request_rebuild_on(pending.build.clone(), queue()) +} + +/// Queue low-priority reconstruction only for an absent recipe-backed generation. This is an +/// uncalled foundation: an eviction policy must decide when absence is acceptable before any bind +/// path may trigger it. +#[allow(dead_code)] +fn request_rehydrate(pso: usize) -> RehydrateRequest { + let Some(pending) = entry(pso) else { return RehydrateRequest::Unavailable }; + if !start_preload_workers() { + return RehydrateRequest::Unavailable; + } + request_rehydrate_on(pending.build.clone(), queue()) +} + +fn submit_job(q: &BuildQueue, build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: Option<usize>) -> Option<JobHandle> { + let queued_build = build.clone(); + q.submit_ranked(priority, preload_rank, Box::new(move || { + let on_preload_worker = PRELOAD_WORKER.get(); + let built = build_queued(&queued_build); + if built && preload && on_preload_worker { + static DONE: AtomicUsize = AtomicUsize::new(0); + let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); + } + } + queued_build.queued.lock().unwrap().take(); + })) +} + +#[cfg(test)] +fn enqueue_on(q: &BuildQueue, build: &Arc<Build>, priority: Priority, preload: bool) { + *build.queued.lock().unwrap() = submit_job(q, build, priority, preload, None); +} + +fn schedule(build: &Arc<Build>, priority: Priority, preload: bool, preload_rank: Option<usize>) { + if preload { + if !start_preload_workers() { + return; + } + } else if !start_normal_workers() { + fail_unrunnable_build(build); + return; + } + let mut queued = build.queued.lock().unwrap(); + let mut refused = false; + if !build.sent.swap(true, Ordering::AcqRel) { + let priority = if build.wanted.load(Ordering::Acquire) || build.demand.lock().unwrap().by_submit { + Priority::Foreground + } else { + priority + }; + *queued = submit_job(queue(), build, priority, preload, preload_rank); + if queued.is_some() { + build.note_queued(); + } else { + refused = true; + } + } + drop(queued); + if refused { + fail_unrunnable_build(build); + } +} + +/// No normal worker can run this job, or its queue refused it. Fail instead of leaving title +/// waiters asleep on work which cannot make progress. +fn fail_unrunnable_build(build: &Arc<Build>) { + build.cancel_queued(); + let job = build.job.lock().unwrap().take(); + if let Some(job) = job { + drop(job); + complete(build, 0); + } +} + +fn build_queued(build: &Arc<Build>) -> bool { + // (released by the title meanwhile) + if build.orphan.load(Ordering::Acquire) { + drop_unstarted_job(build); + return false; + } + // (None: an orphaned build was dropped before this queued work ran) + let job = build.job.lock().unwrap().take(); + if let Some(job) = job { + run_build(build, job); + true + } else { + false + } +} + +/// The caller also drains its batch. Multiple workers can therefore build +/// different chains without ever waiting for a free worker to start a piece. +pub(super) fn build_pieces(jobs: Vec<Job>) -> Vec<usize> { + let count = jobs.len(); + let jobs = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::<Vec<_>>())); + let (send, recv) = mpsc::channel(); + let drain = move || loop { + let job = jobs.lock().unwrap().pop(); + let Some((i, job)) = job else { return }; + let _ = send.send((i, run_job(job))); + }; + // the helpers build for this worker's pipeline: the title waiting for it waits for them too + let parent = BUILDING.with(|b| b.borrow().clone()); + let _ = start_normal_workers(); + for _ in 1..count.min(crate::gpu::recomp::dxc::compile_threads()) { + let (drain, parent) = (drain.clone(), parent.clone()); + let _ = queue().submit(Priority::BoundSoon, Box::new(move || { + let before = BUILDING.with(|b| b.replace(parent)); + let _restore = RestoreBuilding(before); + drain(); + })); + } + drain(); + let mut results = vec![0; count]; + for (i, result) in recv.iter().take(count) { results[i] = result; } + results +} + +/// Run one demanded auxiliary pipeline build on the foreground worker queue and wait for it. +/// Unlike `build_pieces`, the caller never drains or executes the job itself. +pub(super) fn build_foreground(job: Job) -> usize { + let build = Arc::new(Build::new(job, false)); + build.want(); + schedule(&build, Priority::Foreground, false, None); + let _held = Held::new(); + let _stall = crate::stall::span(crate::stall::StallKind::PipelineWait); + let mut done = build.done.lock().unwrap(); + while !*done { + done = build.cv.wait(done).unwrap(); + } + build.real.load(Ordering::Acquire) +} + +/// Release a pipeline state XCL owns (raw pointer, 0 = none). +pub fn release(p: usize) { + if p != 0 { + unsafe { drop(<windows::Win32::Graphics::Direct3D12::ID3D12PipelineState as windows::core::Interface>::from_raw(p as *mut std::ffi::c_void)) }; + } +} + +/// `standin` went to the title; `job` builds the real pipeline on a worker. +pub fn submit(standin: usize, compute: bool, job: Job) { + submit_keyed(standin, compute, job, None); +} + +pub(super) fn submit_keyed( + standin: usize, + compute: bool, + job: Job, + compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, +) { + submit_as(standin, compute, job, None, true, 0, compute_key); +} + +/// Lazy pipeline creation (`XCL_LAZY_PSO=0`: off): a title's pipelines with console shaders get +/// their stand-in when made and are built when first used – the first bind of a graphics one +/// sends it to the workers, a compute one is built at its first bind. A retail game makes +/// ~51 000 pipelines in its first 30 s and uses few; each one built stays in the driver +/// (~400 KB), and the process ran out of commit. +pub fn lazy() -> bool { + static L: OnceLock<bool> = OnceLock::new(); + *L.get_or_init(|| enabled() && std::env::var("XCL_LAZY_PSO").map_or(true, |v| v != "0")) +} + +/// `submit`, sent to the workers only on its first `resolve` (`lazy`) – or now, at a low +/// priority, when an earlier run used a pipeline of these shaders (`key`, 0 = none; `used`). +pub fn submit_lazy(standin: usize, compute: bool, job: Job, key: u64) { + submit_lazy_keyed(standin, compute, job, key, None); +} + +pub(super) fn submit_lazy_keyed( + standin: usize, + compute: bool, + job: Job, + key: u64, + compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, +) { + submit_as(standin, compute, job, None, false, key, compute_key); +} + +pub(super) fn submit_recipe_keyed( + standin: usize, + compute: bool, + recipe: Recipe, + send: bool, + key: u64, + compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, +) { + let job = recipe.initial_job(); + submit_as(standin, compute, job, Some(recipe), send, key, compute_key); +} + +fn submit_as( + standin: usize, + compute: bool, + job: Job, + recipe: Option<Recipe>, + send: bool, + key: u64, + compute_key: Option<super::real::compute_build_key::ComputeBuildKey>, +) { + debug_assert!(compute || compute_key.is_none()); + let build = if let Some(compute_key) = compute_key { + let mut registry = IN_FLIGHT.lock().unwrap(); + let builds = registry.get_or_insert_with(HashMap::new); + let before = builds.len(); + builds.retain(|_, build| build.strong_count() != 0); + COALESCING.finished(before - builds.len()); + if let Some(build) = builds.get(&compute_key).and_then(Weak::upgrade) { + let done = build.done.lock().unwrap(); + if !*done && !build.orphan.load(Ordering::Acquire) { + build.owners.fetch_add(1, Ordering::Relaxed); + drop(done); + COALESCING.hit(); + build + } else { + if builds.remove(&compute_key).is_some() { + COALESCING.finished(1); + } + let compute_key = Arc::new(compute_key); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()), recipe)); + builds.insert(compute_key, Arc::downgrade(&build)); + COALESCING.unique(); + build + } + } else { + let compute_key = Arc::new(compute_key); + let build = Arc::new(Build::new_keyed(job, false, Some(compute_key.clone()), recipe)); + builds.insert(compute_key, Arc::downgrade(&build)); + COALESCING.unique(); + build + } + } else { + Arc::new(Build::new_keyed(job, false, None, recipe)) + }; + let p = Arc::new(Pending { + build: build.clone(), + driver: AtomicUsize::new(0), + compute, + key, + used: Default::default(), + late: Default::default(), + spared: Default::default(), + }); + build.tracked.store(true, Ordering::Release); + PENDING.insert(standin, p.clone()); + static ONCE: std::sync::Once = std::sync::Once::new(); + ONCE.call_once(|| { + crate::xlog_info!("D3D12.X: pipelines whose shaders are not compiled yet get a stand-in and are built in the background"); + }); + if send { + schedule(&build, Priority::BoundSoon, false, None); + } else if let Some(rank) = used::rank(key).filter(|_| preload_enabled()) { + schedule(&build, Priority::Preload, true, Some(rank)); + } +} + +/// The keys of the pipelines earlier runs used (`used-pipelines.txt` beside the DXIL cache): +/// what `xcl shaders --precompile --used-only` builds. +pub fn earlier_used_keys() -> std::collections::HashSet<u64> { + used::parse(&std::fs::read_to_string(crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt")).unwrap_or_default()) +} + +/// Ask the used-pipeline writer to finish without ever joining it unboundedly. +pub fn shutdown_used() { + used::shutdown(std::time::Duration::from_millis(500)); +} + +/// Best effort at process termination: only the one writer touches the append handle, and a +/// loader-lock-blocked writer cannot hold termination longer than `timeout`. +pub fn flush_used_bounded(timeout: std::time::Duration) { + used::shutdown(timeout); +} + +/// The pipelines a title used, by a hash of their shaders, kept between runs +/// (`used-pipelines.txt` beside the DXIL cache, a key a line). +/// +/// A lazy pipeline is built at its first use: until then a graphics one draws nothing, and a +/// compute one is waited for on the title's thread. A retail title's first frames of its world +/// use hundreds of pipelines for the first time at once. The pipelines of an earlier run are +/// built while the title loads instead (`preload`): measured on a build that skips a dispatch +/// instead of waiting for its pipeline, ~2 170 dispatches were skipped in those frames without +/// this and 94 – 150 with it. +mod used { + use std::collections::{HashMap, HashSet}; + use std::sync::{OnceLock, RwLock}; + use std::time::Duration; + + use super::super::used_journal::Journal; + + struct Used { + earlier: RwLock<HashMap<u64, usize>>, + now: Journal, + } + + static U: OnceLock<Used> = OnceLock::new(); + + /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). + pub fn parse(text: &str) -> HashSet<u64> { + parse_ranked(text).into_keys().collect() + } + + /// First occurrence order of the valid, nonzero keys in a `used-pipelines.txt`. + pub fn parse_ranked(text: &str) -> HashMap<u64, usize> { + let mut ranked = HashMap::new(); + for key in text.lines().filter_map(|line| u64::from_str_radix(line.trim(), 16).ok()).filter(|&key| key != 0) { + let rank = ranked.len(); + ranked.entry(key).or_insert(rank); + } + ranked + } + + fn get() -> &'static Used { + U.get_or_init(|| { + // (a test neither reads nor writes the user's file) + if cfg!(test) { + return Used { earlier: RwLock::new(HashMap::new()), now: Journal::memory(HashSet::new()) }; + } + let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); + let earlier = parse_ranked(&std::fs::read_to_string(&path).unwrap_or_default()); + if !earlier.is_empty() { + crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); + } + let now = Journal::file(path, earlier.keys().copied().collect()); + Used { now, earlier: RwLock::new(earlier) } + }) + } + + pub fn shutdown(timeout: Duration) { + if let Some(used) = U.get() { + let _ = used.now.shutdown_bounded(timeout); + } + } + + /// First-use rank when an earlier run used a pipeline of these shaders. + pub fn rank(key: u64) -> Option<usize> { + (key != 0).then(|| get().earlier.read().unwrap().get(&key).copied()).flatten() + } + + /// A pipeline of these shaders is used now: kept for the next run. + pub fn note(key: u64) { + if key == 0 { + return; + } + get().now.note(key); + } + + /// (tests) This run used a pipeline of these shaders. + #[cfg(test)] + pub fn noted(key: u64) -> bool { + get().now.contains(key) + } + + #[cfg(test)] + pub fn earlier_run_used(key: u64) { + let mut earlier = get().earlier.write().unwrap(); + let rank = earlier.len(); + earlier.entry(key).or_insert(rank); + } +} + +/// Build pipelines from an earlier run in the preload worker band (`XCL_PSO_PRELOAD=0`: off). +fn preload_enabled() -> bool { + static ENABLED: OnceLock<bool> = OnceLock::new(); + *ENABLED.get_or_init(|| !std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0")) +} + +#[cfg(test)] +mod used_tests { + use super::*; + + #[repr(C)] + struct RebuildFakePso { + vtable: *const usize, + refs: AtomicUsize, + } + + unsafe extern "system" fn rebuild_fake_add_ref(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut RebuildFakePso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + + unsafe extern "system" fn rebuild_fake_release(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut RebuildFakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + thread_local! { static RESTORE_REENTER_ATTEMPTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } + + unsafe extern "system" fn rebuild_reenter_release(this: *mut std::ffi::c_void) -> u32 { + let remaining = rebuild_fake_release(this); + if remaining == 0 { + RESTORE_REENTER_ATTEMPTS.with(|address| if address.get() != 0 { assert!( + (&*(address.get() as *const Mutex<Vec<Arc<RestorationAttempt>>>)).try_lock().is_ok(), + "final native drop ran under the attempts lock", + ) }); + } + remaining + } + + fn pressure_config() -> PressureAdmissionConfig { + PressureAdmissionConfig { + enabled: true, + low_basis_points: 7_000, + high_basis_points: 9_000, + max_sample_age_turns: 1, + max_evictions_per_turn: 3, + rehydrate_backoff_turns: 2, + max_rehydrate_backoff_turns: 8, + } + } + + fn pressure_sample(turn: u64, usage: u64) -> PressureSample { + PressureSample { + observed_turn: turn, + segment: super::super::memory_report::Segment { usage, budget: 100 }, + } + } + + fn ledger_build() -> Arc<Build> { + Arc::new(Build::new(Box::new(|| 0), false)) + } + + fn ledger_native(id: u64) -> LedgerNativeGeneration { + LedgerNativeGeneration { id, identity: id as usize + 0x1000 } + } + + #[test] + fn pressure_admission_rejects_ambiguous_serial_horizons() { + let mut config = pressure_config(); + config.max_sample_age_turns = PRESSURE_MAX_TURN_HORIZON; + config.rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + config.max_rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + assert!(PressureAdmission::new(config).is_some(), "the exact serial horizon was rejected"); + + let ambiguous = PRESSURE_MAX_TURN_HORIZON + 1; + let mut sample_age = pressure_config(); + sample_age.max_sample_age_turns = ambiguous; + assert!(PressureAdmission::new(sample_age).is_none()); + let mut initial_backoff = pressure_config(); + initial_backoff.rehydrate_backoff_turns = ambiguous; + initial_backoff.max_rehydrate_backoff_turns = ambiguous; + assert!(PressureAdmission::new(initial_backoff).is_none()); + let mut maximum_backoff = pressure_config(); + maximum_backoff.max_rehydrate_backoff_turns = ambiguous; + assert!(PressureAdmission::new(maximum_backoff).is_none()); + } + + #[test] + fn pressure_admission_maximum_cooldown_does_not_appear_expired() { + let mut config = pressure_config(); + config.max_sample_age_turns = PRESSURE_MAX_TURN_HORIZON; + config.rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + config.max_rehydrate_backoff_turns = PRESSURE_MAX_TURN_HORIZON; + let mut state = PressureAdmission::new(config).unwrap(); + assert_eq!(state.decide(0, Some(pressure_sample(0, 95))).max_evictions, 3); + assert!(state.decide(1, Some(pressure_sample(1, 60))).allow_rehydrate); + state.note_rehydrate_result(1, false); + assert!(!state.decide(2, Some(pressure_sample(2, 60))).allow_rehydrate, + "a maximum unambiguous cooldown appeared immediately expired"); + assert!(!state.decide(PRESSURE_MAX_TURN_HORIZON, + Some(pressure_sample(PRESSURE_MAX_TURN_HORIZON, 60))).allow_rehydrate); + let retry = PRESSURE_MAX_TURN_HORIZON + 1; + assert!(state.decide(retry, Some(pressure_sample(retry, 60))).allow_rehydrate); + } + + #[test] + fn pressure_admission_hysteresis_bounds_each_eviction_turn() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(1, Some(pressure_sample(1, 85))), PressureDecision::default()); + assert_eq!(state.decide(2, Some(pressure_sample(2, 90))).max_evictions, 3); + assert_eq!(state.decide(3, Some(pressure_sample(3, 85))).max_evictions, 3, + "falling below the high watermark churned the policy"); + assert!(state.decide(4, Some(pressure_sample(4, 70))).allow_rehydrate); + assert!(state.decide(5, Some(pressure_sample(5, 85))).allow_rehydrate, + "rising above the low watermark churned the policy"); + assert_eq!(state.decide(6, Some(pressure_sample(6, 90))).max_evictions, 3); + } + + #[test] + fn pressure_admission_shares_one_eviction_budget_within_a_turn() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(10, Some(pressure_sample(9, 95))).max_evictions, 3); + assert_eq!(state.decide(10, Some(pressure_sample(10, 95))).max_evictions, 0, + "a second fresh sample replenished the same policy turn"); + assert_eq!(state.decide(11, Some(pressure_sample(11, 95))).max_evictions, 3, + "a new policy turn did not replenish its bounded allowance"); + } + + #[test] + fn pressure_admission_rejects_missing_invalid_and_stale_samples() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(1, Some(pressure_sample(1, 95))).max_evictions, 3); + assert_eq!(state.decide(2, None), PressureDecision::default()); + assert_eq!(state.decide(2, Some(pressure_sample(1, 95))), PressureDecision::default()); + assert_eq!(state.decide(4, Some(pressure_sample(2, 50))), PressureDecision::default()); + let invalid = PressureSample { + observed_turn: 4, + segment: super::super::memory_report::Segment { usage: 95, budget: 0 }, + }; + assert_eq!(state.decide(4, Some(invalid)), PressureDecision::default()); + assert_eq!(state.decide(5, Some(pressure_sample(5, 85))).max_evictions, 3, + "an unusable sample changed pressure state"); + + let mut disabled = PressureAdmission::new(PressureAdmissionConfig::default()).unwrap(); + assert_eq!(disabled.decide(1, Some(pressure_sample(1, 100))), PressureDecision::default()); + } + + #[test] + fn pressure_admission_freshness_is_conservative_across_turn_wrap() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(u64::MAX, Some(pressure_sample(0, 95))), PressureDecision::default(), + "a post-wrap sample was accepted before its turn"); + assert_eq!(state.decide(u64::MAX, Some(pressure_sample(u64::MAX, 95))).max_evictions, 3); + assert_eq!(state.decide(0, Some(pressure_sample(0, 95))).max_evictions, 3, + "turn wrap did not advance the sample and eviction budget"); + assert_eq!(state.decide(0, Some(pressure_sample(u64::MAX, 95))), PressureDecision::default(), + "a pre-wrap sample was accepted twice"); + assert_eq!(state.decide(2, Some(pressure_sample(0, 95))), PressureDecision::default(), + "a wrapped sample older than the configured age was accepted"); + + let mut recovery = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(recovery.decide(u64::MAX - 2, Some(pressure_sample(u64::MAX - 2, 95))).max_evictions, 3); + assert!(recovery.decide(u64::MAX - 1, Some(pressure_sample(u64::MAX - 1, 60))).allow_rehydrate); + recovery.note_rehydrate_result(u64::MAX - 1, false); + assert!(!recovery.decide(u64::MAX, Some(pressure_sample(u64::MAX, 60))).allow_rehydrate); + assert!(recovery.decide(0, Some(pressure_sample(0, 60))).allow_rehydrate, + "rehydration backoff did not expire across turn wrap"); + } + + #[test] + fn pressure_admission_backs_off_failures_and_resets_after_recovery() { + let mut state = PressureAdmission::new(pressure_config()).unwrap(); + assert_eq!(state.decide(1, Some(pressure_sample(1, 95))).max_evictions, 3); + assert!(state.decide(2, Some(pressure_sample(2, 60))).allow_rehydrate); + state.note_rehydrate_result(2, false); + assert!(!state.decide(3, Some(pressure_sample(3, 60))).allow_rehydrate); + assert!(state.decide(4, Some(pressure_sample(4, 60))).allow_rehydrate); + state.note_rehydrate_result(4, false); + assert!(!state.decide(7, Some(pressure_sample(7, 60))).allow_rehydrate); + assert!(state.decide(8, Some(pressure_sample(8, 60))).allow_rehydrate); + state.note_rehydrate_result(8, true); + assert!(state.decide(9, Some(pressure_sample(9, 60))).allow_rehydrate); + state.note_rehydrate_result(9, false); + assert!(!state.decide(10, Some(pressure_sample(10, 60))).allow_rehydrate, + "a successful recovery did not reset the failure backoff"); + assert!(state.decide(11, Some(pressure_sample(11, 60))).allow_rehydrate); + state.note_rehydration_complete(); + assert_eq!(state.decide(12, Some(pressure_sample(12, 60))), PressureDecision::default()); + } + + #[test] + fn evicted_ledger_reserves_before_detach_and_stays_bounded() { + let ledger = EvictedBuildLedger::<2>::new(7).unwrap(); + let builds = [ledger_build(), ledger_build(), ledger_build()]; + drop(ledger.reserve(&builds[0], ledger_native(1)).unwrap()); + assert!(ledger.records(2).is_empty(), "a pre-detach reservation drop stayed live"); + + let first = ledger.reserve(&builds[0], ledger_native(1)).unwrap().arm_detach().unwrap(); + let second = ledger.reserve(&builds[1], ledger_native(2)).unwrap().arm_detach().unwrap(); + assert!(ledger.reserve(&builds[2], ledger_native(3)).is_none(), "a full ledger admitted a detach"); + assert_eq!(ledger.records(1).len(), 1, "enumeration ignored its bound"); + let failed = first.clone(); + drop(first); + assert_eq!(ledger.records(2).len(), 2, "dropping an armed token erased detached state"); + assert!(ledger.finish(&failed, EvictedBuildState::Poisoned)); + assert_eq!(ledger.records(2)[0].state, EvictedBuildState::Poisoned); + assert!(ledger.finish(&second, EvictedBuildState::Released)); + } + + #[test] + fn evicted_ledger_instance_identity_prevents_cross_ledger_mutation() { + let first = EvictedBuildLedger::<1>::new(7).unwrap(); + let second = EvictedBuildLedger::<1>::new(7).unwrap(); + let build = ledger_build(); + let native = ledger_native(3); + let first_token = first.reserve(&build, native).unwrap().arm_detach().unwrap(); + let second_token = second.reserve(&build, native).unwrap().arm_detach().unwrap(); + assert_ne!(first_token.ledger_instance, second_token.ledger_instance); + assert!(!second.rehydrate_queued(&first_token), "a token crossed identical caller generations"); + assert_eq!(second.records(1)[0].state, EvictedBuildState::Evicted); + assert!(second.rehydrate_queued(&second_token)); + } + + #[test] + fn evicted_ledger_rejects_stale_identity_and_out_of_order_terminal() { + let ledger = EvictedBuildLedger::<1>::new(9).unwrap(); + let first_build = ledger_build(); + let first = ledger.reserve(&first_build, ledger_native(4)).unwrap().arm_detach().unwrap(); + let mut wrong_native = first.clone(); + wrong_native.native = ledger_native(5); + assert!(!ledger.rehydrate_queued(&wrong_native)); + let mut wrong_ledger = first.clone(); + wrong_ledger.ledger_generation += 1; + assert!(!ledger.rehydrate_queued(&wrong_ledger)); + assert!(!ledger.finish(&first, EvictedBuildState::Restored), + "an evicted build was restored before rehydration queued"); + assert!(ledger.rehydrate_queued(&first)); + assert!(ledger.finish(&first, EvictedBuildState::Restored)); + assert!(!ledger.finish(&first, EvictedBuildState::Released), "a terminal state changed out of order"); + assert!(ledger.retire(&first)); + + let second_build = ledger_build(); + let second = ledger.reserve(&second_build, ledger_native(5)).unwrap().arm_detach().unwrap(); + assert_eq!(first.slot, second.slot); + assert_ne!(first.slot_generation, second.slot_generation); + assert!(!ledger.finish(&first, EvictedBuildState::Poisoned), "a stale token mutated a reused slot"); + assert_eq!(ledger.records(1)[0].state, EvictedBuildState::Evicted); + assert!(ledger.rehydrate_queued(&second)); + assert!(ledger.finish(&second, EvictedBuildState::Poisoned)); + assert!(ledger.retire(&second)); + + let third = ledger.reserve(&second_build, ledger_native(6)).unwrap().arm_detach().unwrap(); + assert!(ledger.rehydrate_queued(&third)); + assert!(ledger.finish(&third, EvictedBuildState::Released)); + } + + #[test] + fn evicted_ledger_retires_expired_weak_build_identity() { + let ledger = EvictedBuildLedger::<1>::new(11).unwrap(); + let build = ledger_build(); + let token = ledger.reserve(&build, ledger_native(6)).unwrap().arm_detach().unwrap(); + drop(build); + assert_eq!(ledger.records(1)[0].state, EvictedBuildState::Released); + + let replacement = ledger_build(); + let mut reused_address = token.clone(); + reused_address.build = Arc::downgrade(&replacement); + assert!(!ledger.retire(&reused_address), "a different allocation identity retired the entry"); + assert!(ledger.retire(&token)); + } + + #[test] + fn evicted_ledger_counter_overflow_fails_closed() { + let build = ledger_build(); + let serial = EvictedBuildLedger::<1>::new(13).unwrap(); + serial.inner.lock().unwrap().serial = u64::MAX; + assert!(serial.reserve(&build, ledger_native(7)).is_none()); + assert!(serial.inner.lock().unwrap().exhausted); + + let generation = EvictedBuildLedger::<1>::new(14).unwrap(); + generation.inner.lock().unwrap().slots[0].generation = u64::MAX; + assert!(generation.reserve(&build, ledger_native(8)).is_none()); + assert!(generation.inner.lock().unwrap().exhausted); + + let instance = AtomicU64::new(u64::MAX - 1); + assert_eq!(allocate_evicted_ledger_instance(&instance), Some(u64::MAX - 1)); + assert_eq!(allocate_evicted_ledger_instance(&instance), None); + } + + fn receipt_evicted(build: &Arc<Build>, id: u64) -> EvictedBuildToken { + EvictedBuildLedger::<1>::new(id + 100).unwrap() + .reserve(build, ledger_native(id)).unwrap().arm_detach().unwrap() + } + + fn coordinated_evicted<const E: usize, const R: usize>( + coordinator: &RestorationCoordinator<E, R>, build: &Arc<Build>, id: u64, + ) -> EvictedBuildToken { + coordinator.reserve_eviction(build, ledger_native(id)).unwrap().arm_detach().unwrap() + } + + #[test] + fn rehydrate_receipts_separate_request_from_completion() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 20); + let registry = RehydrateReceiptRegistry::<3>::new().unwrap(); + let (request, refused) = registry.reserve(&evicted).unwrap().refused().unwrap(); + assert_eq!(request, RehydrateRequestReceipt::Refused); + assert_eq!(registry.records(3)[0].state, RehydrateCompletion::Refused); assert!(registry.retire(&refused)); + let (request, queued) = registry.reserve(&evicted).unwrap() + .accepted(RehydratePriority::Background).unwrap(); + assert_eq!(request, RehydrateRequestReceipt::Queued { priority: RehydratePriority::Background }); + let queued_token = queued.token.clone(); + assert_eq!(registry.records(3)[0].state, RehydrateCompletion::Queued, + "queue acceptance was treated as successful completion"); + assert!(registry.promote(&queued_token)); + assert_eq!(registry.records(3)[0].priority, RehydratePriority::Foreground); + drop(queued); + assert_eq!(registry.records(3)[0].state, RehydrateCompletion::Cancelled); + } + + #[test] + fn rehydrate_receipts_report_panic_failure_and_release() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 21); + let registry = RehydrateReceiptRegistry::<4>::new().unwrap(); + let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let (_, _queued) = registry.reserve(&evicted).unwrap() + .accepted(RehydratePriority::Foreground).unwrap(); + panic!("queued build panic"); + })); + assert!(panic_result.is_err()); assert_eq!(registry.records(4)[0].state, RehydrateCompletion::Panicked); + let (_, failed) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + assert!(failed.complete(RehydrateCompletion::BuildFailed)); + let (_, released) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + assert!(released.complete(RehydrateCompletion::Released)); + } + + #[test] + fn rehydrate_receipts_reject_duplicate_stale_and_release_races() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 23); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let reservation = registry.reserve(&evicted).unwrap(); + assert!(!registry.publish(&reservation.token, RehydrateCompletion::BuildFailed), + "a completion published before queue acceptance"); + let (_, success) = reservation.accepted(RehydratePriority::Background).unwrap(); + let old = success.token.clone(); + assert!(!registry.publish(&old, RehydrateCompletion::Succeeded { replacement: evicted.native }), + "the evicted native generation was reported as its own replacement"); + assert!(success.complete(RehydrateCompletion::BuildFailed)); + assert!(!registry.publish(&old, RehydrateCompletion::BuildFailed), "a duplicate completion mutated state"); + assert!(registry.retire(&old)); + let (_, racing) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + let current = racing.token.clone(); + assert_ne!(old.attempt_generation, current.attempt_generation); + assert!(!registry.publish(&old, RehydrateCompletion::Panicked), "a stale attempt mutated its replacement"); + let replacement_build = ledger_build(); + let mut reused = current.clone(); + reused.evicted.build = Arc::downgrade(&replacement_build); + assert!(!registry.publish(&reused, RehydrateCompletion::BuildFailed), + "a different build allocation completed the current attempt"); + assert!(registry.publish(¤t, RehydrateCompletion::Released)); + assert!(!racing.complete(RehydrateCompletion::Succeeded { replacement: ledger_native(25) }), + "success won after release completed the attempt"); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); + } + + #[test] + fn rehydrate_success_requires_exact_current_build_generation_and_liveness() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let job = build.job.lock().unwrap().take().unwrap(); complete(&build, job()); + let replacement = recipe.pin_with_residency(raw).0.unwrap(); let evicted = receipt_evicted(&build, 27); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let (_, success) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + assert!(success.replacement(&ledger_build(), &replacement).is_none(), "another build proved replacement"); + assert!(!registry.publish(&success.token, RehydrateCompletion::Succeeded { replacement: ledger_native(99) }), + "a forged native identity bypassed replacement proof"); + let mut foreign = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; let foreign_raw = &mut foreign as *mut RebuildFakePso as usize; + let foreign_recipe = Recipe::new(move || foreign_raw); + let foreign_build = Arc::new(Build::new_keyed(foreign_recipe.initial_job(), false, None, Some(foreign_recipe.clone()))); + let foreign_job = foreign_build.job.lock().unwrap().take().unwrap(); complete(&foreign_build, foreign_job()); + let foreign_pin = foreign_recipe.pin_with_residency(foreign_raw).0.unwrap(); + assert!(rehydrate_success::Proof::published(&success.token, &build, &recipe, &foreign_pin).is_none(), + "same-number generation from another recipe proved success"); + let proof = success.replacement(&build, &replacement).unwrap(); let token = success.token.clone(); + let mut newer_native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let newer_raw = &mut newer_native as *mut RebuildFakePso as usize; + let (newer, replaced) = recipe.publish(newer_raw); let old_raw = build.real.swap(newer_raw, Ordering::AcqRel); + release(old_raw); drop(replaced); + assert!(rehydrate_success::Proof::published(&success.token, &build, &recipe, &replacement).is_none(), + "an older generation was relabeled as the published replacement"); + assert!(!success.complete_success(proof), "generation A completed after B became current"); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Cancelled); assert!(registry.retire(&token)); + let (_, success) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + let proof = success.replacement(&build, &newer).unwrap(); let token = success.token.clone(); + assert!(success.complete_success(proof)); + assert_eq!(registry.records(1)[0].state, + RehydrateCompletion::Succeeded { replacement: newer.ledger_identity() }); + assert!(registry.retire(&token)); + let (_, expired) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + let proof = expired.replacement(&build, &newer).unwrap(); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(build); release(raw_owner); + assert!(expired.complete_success(proof)); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); + drop(replacement); drop(newer); drop(recipe); assert_eq!(native.refs.load(Ordering::Relaxed), 0); + assert_eq!(newer_native.refs.load(Ordering::Relaxed), 0); + let foreign_owner = foreign_build.real.swap(0, Ordering::AcqRel); drop(foreign_pin); drop(foreign_build); + release(foreign_owner); drop(foreign_recipe); + assert_eq!(foreign.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn rehydrate_guard_drop_resolves_expired_build_as_released() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 28); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let (_, queued) = registry.reserve(&evicted).unwrap().accepted(RehydratePriority::Background).unwrap(); + drop(build); + drop(queued); + assert_eq!(registry.records(1)[0].state, RehydrateCompletion::Released); + } + + #[test] + fn rehydrate_receipt_capacity_and_counters_fail_before_queue() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 26); + let registry = RehydrateReceiptRegistry::<1>::new().unwrap(); + let reservation = registry.reserve(&evicted).unwrap(); + assert!(registry.reserve(&evicted).is_none()); + drop(reservation); assert!(registry.records(1).is_empty()); + registry.inner.lock().unwrap().serial = u64::MAX; + assert!(registry.reserve(&evicted).is_none()); + assert!(registry.inner.lock().unwrap().exhausted); + let generation = RehydrateReceiptRegistry::<1>::new().unwrap(); + generation.inner.lock().unwrap().slots[0].generation = u64::MAX; + assert!(generation.reserve(&evicted).is_none()); + assert!(generation.inner.lock().unwrap().exhausted); + } + + #[test] + fn restoration_coordinator_refusal_and_full_ledger_retry() { + let coordinator = RestorationCoordinator::<1, 2>::new(301).unwrap(); + let build = ledger_build(); + let reserved = coordinator.reserve_eviction(&build, ledger_native(40)).unwrap(); + assert!(coordinator.reserve_eviction(&ledger_build(), ledger_native(41)).is_none()); + drop(reserved); + let evicted = coordinated_evicted(&coordinator, &build, 40); + assert!(coordinator.refuse_rehydrate(&evicted)); + assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + assert!(coordinator.retries(1)[0].token.exact(&evicted)); + } + + #[test] + fn installed_eviction_is_visible_before_detach_commit() { + let coordinator = RestorationCoordinator::<1, 1>::new(308).unwrap(); + let build = ledger_build(); + let installed = coordinator.install_eviction(&build, ledger_native(50)).unwrap(); + let visible = build.eviction_token().expect("armed eviction was not installed"); + assert!(visible.exact(installed.token())); + assert_eq!(coordinator.evicted.state(&visible), Some(EvictedBuildState::Evicted)); + + let committed = installed.commit(); + assert!(build.eviction_token().is_some_and(|token| token.exact(&committed))); + assert!(build.clear_eviction_token(&committed)); + assert!(coordinator.evicted.finish(&committed, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&committed)); + } + + #[test] + fn failed_eviction_revalidation_clears_and_retires_installation() { + let coordinator = RestorationCoordinator::<1, 1>::new(309).unwrap(); + let build = ledger_build(); + { + let installed = coordinator.install_eviction(&build, ledger_native(51)).unwrap(); + assert!(build.eviction_token().is_some_and(|token| token.exact(installed.token()))); + // A future eviction path drops the guard when exact generation revalidation fails. + } + assert!(build.eviction_token().is_none()); + assert!(coordinator.evicted.records(1).is_empty()); + } + + #[test] + fn stale_eviction_token_cannot_clear_reused_installation() { + let coordinator = RestorationCoordinator::<1, 1>::new(310).unwrap(); + let build = ledger_build(); + let first = coordinator.install_eviction(&build, ledger_native(52)).unwrap().commit(); + assert!(build.clear_eviction_token(&first)); + assert!(coordinator.evicted.finish(&first, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&first)); + + let second = coordinator.install_eviction(&build, ledger_native(53)).unwrap().commit(); + assert_eq!(first.slot, second.slot); + assert_ne!(first.slot_generation, second.slot_generation); + assert!(!build.clear_eviction_token(&first)); + assert!(build.eviction_token().is_some_and(|token| token.exact(&second))); + assert!(build.clear_eviction_token(&second)); + assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&second)); + } + + #[test] + fn rehydrate_registry_atomically_returns_existing_before_readiness() { + let build = ledger_build(); let evicted = receipt_evicted(&build, 49); + let registry = RehydrateReceiptRegistry::<2>::new().unwrap(); + let reservation = match registry.reserve_unique(&evicted, true) { + Ok(Some(reservation)) => reservation, _ => panic!("initial unique reservation failed"), + }; + let existing = match registry.reserve_unique(&evicted, true) { + Err(existing) => existing, _ => panic!("duplicate reservation was admitted"), + }; + assert!(existing.token.evicted.exact(&evicted)); + assert!(matches!(registry.reserve_unique(&evicted, false), Err(existing) + if existing.token.evicted.exact(&evicted))); + drop(reservation); + assert!(matches!(registry.reserve_unique(&evicted, false), Ok(None))); + } + + #[test] + fn restoration_coordinator_maps_failures_and_foreground_deduplicates() { + let coordinator = RestorationCoordinator::<1, 2>::new(302).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 42); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => panic!("first request was not queued"), + }; + assert!(matches!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, false), + Some(RestorationQueue::Existing)), "backoff hid an already-live attempt"); + assert!(matches!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false), + Some(RestorationQueue::Promoted))); + assert!(matches!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false), + Some(RestorationQueue::Existing))); + assert_eq!(coordinator.receipts.records(2).len(), 1); + assert_eq!(coordinator.receipts.records(2)[0].priority, RehydratePriority::Foreground); + drop(queued); assert_eq!(coordinator.reconcile(2), 1); + assert!(coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, false).is_none()); + for completion in [RehydrateCompletion::Panicked, RehydrateCompletion::BuildFailed] { + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + assert!(queued.complete(completion)); assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + let panic_result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + panic!("restoration worker panic"); + })); + assert!(panic_result.is_err()); assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + + #[test] + fn restoration_coordinator_atomically_deduplicates_concurrent_queues() { + let coordinator = RestorationCoordinator::<1, 2>::new(306).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 47); + let barrier = std::sync::Barrier::new(3); + let queued = AtomicUsize::new(0); + let existing = AtomicUsize::new(0); + std::thread::scope(|scope| { + for _ in 0..2 { + scope.spawn(|| { + barrier.wait(); + match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(receipt) => { + queued.fetch_add(1, Ordering::Relaxed); + assert!(receipt.complete(RehydrateCompletion::BuildFailed)); + } + RestorationQueue::Existing => { existing.fetch_add(1, Ordering::Relaxed); } + RestorationQueue::Promoted => panic!("background request promoted"), + } + }); + } + barrier.wait(); + }); + assert_eq!((queued.load(Ordering::Relaxed), existing.load(Ordering::Relaxed)), (1, 1)); + assert_eq!(coordinator.receipts.records(2).len(), 1); + assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + + #[test] + fn restoration_coordinator_atomically_orders_queue_against_refusal() { + let coordinator = RestorationCoordinator::<1, 2>::new(307).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 48); + let barrier = std::sync::Barrier::new(3); + let admitted = AtomicUsize::new(0); + std::thread::scope(|scope| { + scope.spawn(|| { + barrier.wait(); + match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(receipt) => { + admitted.fetch_add(1, Ordering::Relaxed); + assert!(receipt.complete(RehydrateCompletion::BuildFailed)); + } + RestorationQueue::Existing => {} + RestorationQueue::Promoted => unreachable!(), + } + }); + scope.spawn(|| { + barrier.wait(); + if coordinator.refuse_rehydrate(&evicted) { + admitted.fetch_add(1, Ordering::Relaxed); + } + }); + barrier.wait(); + }); + assert_eq!(admitted.load(Ordering::Relaxed), 1); + assert_eq!(coordinator.receipts.records(2).len(), 1); + assert_eq!(coordinator.reconcile(2), 1); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::Evicted)); + } + + #[test] + fn restoration_coordinator_release_race_is_terminal_and_idempotent() { + let coordinator = RestorationCoordinator::<1, 1>::new(303).unwrap(); + let build = ledger_build(); let evicted = coordinated_evicted(&coordinator, &build, 43); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + drop(build); drop(queued); + assert_eq!(coordinator.reconcile(1), 1); + assert_eq!(coordinator.evicted.state(&evicted), None); + assert_eq!(coordinator.reconcile(1), 0); + assert!(coordinator.retries(1).is_empty()); + } + + #[test] + fn restoration_coordinator_release_clears_installation_and_reuses_capacity() { + let coordinator = RestorationCoordinator::<1, 1>::new(303).unwrap(); + let build = ledger_build(); + let evicted = coordinator.install_eviction(&build, ledger_native(43)).unwrap().commit(); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + assert!(queued.complete(RehydrateCompletion::Released)); + assert_eq!(coordinator.reconcile(1), 1); + assert!(build.eviction_token().is_none()); + assert_eq!(coordinator.evicted.state(&evicted), None); + drop(coordinator.install_eviction(&build, ledger_native(44)).expect("terminal slot was not reusable")); + assert_eq!(coordinator.reconcile(1), 0); + assert!(coordinator.retries(1).is_empty()); + } + + #[test] + fn restoration_coordinator_stale_terminal_cannot_clear_reused_installation() { + let coordinator = RestorationCoordinator::<1, 1>::new(305).unwrap(); + let build = ledger_build(); + let first = coordinator.install_eviction(&build, ledger_native(45)).unwrap().commit(); + let queued = match coordinator.queue_rehydrate(&first, RehydratePriority::Background, true).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + assert!(queued.complete(RehydrateCompletion::Released)); + assert_eq!(coordinator.reconcile(1), 1); + let second = coordinator.install_eviction(&build, ledger_native(46)).unwrap().commit(); + assert_eq!(first.slot, second.slot); + assert_ne!(first.slot_generation, second.slot_generation); + assert!(coordinator.receipts.reserve(&first).unwrap().refused().is_some()); + assert_eq!(coordinator.reconcile(1), 1); + assert_eq!(coordinator.evicted.state(&second), Some(EvictedBuildState::Evicted), + "a stale receipt poisoned a reused eviction slot"); + assert!(build.eviction_token().is_some_and(|token| token.exact(&second)), + "a stale terminal receipt cleared the replacement installation"); + assert!(build.clear_eviction_token(&second)); + assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&second)); + assert_eq!(coordinator.reconcile(1), 0); + } + + #[test] + fn restoration_coordinator_exact_success_restores_after_receipt() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let job = build.job.lock().unwrap().take().unwrap(); complete(&build, job()); + let replacement = recipe.pin_with_residency(raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, 1>::new(304).unwrap(); + let evicted = coordinator.install_eviction(&build, ledger_native(44)).unwrap().commit(); + let queued = match coordinator.queue_rehydrate(&evicted, RehydratePriority::Foreground, false).unwrap() { + RestorationQueue::Queued(queued) => queued, _ => unreachable!(), + }; + let proof = queued.replacement(&build, &replacement).unwrap(); + assert!(queued.complete_success(proof)); + assert_eq!(coordinator.evicted.state(&evicted), Some(EvictedBuildState::RehydrateQueued)); + assert_eq!(coordinator.reconcile(1), 1); + assert!(build.eviction_token().is_none()); + assert_eq!(coordinator.evicted.state(&evicted), None); + drop(coordinator.install_eviction(&build, ledger_native(45)).expect("restored slot was not reusable")); + assert_eq!(coordinator.reconcile(1), 0); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(build); release(raw_owner); drop(replacement); drop(recipe); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn exact_restoration_promotes_without_inline_work_and_transfers_its_pin() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let replacement_vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_reenter_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: replacement_vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let calls = Arc::new(AtomicUsize::new(0)); + let build_next = next.clone(); let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + build_next.load(Ordering::Acquire) + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let first_pin = recipe.pin_with_residency(first_raw).0.unwrap(); + let coordinator = RestorationCoordinator::<2, 2>::new(401).unwrap(); + let evicted = coordinator.reserve_eviction(&build, first_pin.ledger_identity()).unwrap().arm_detach().unwrap(); + drop(first_pin); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + let (captured_tx, captured_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + *coordinator.captured.lock().unwrap() = Some(Box::new(move || { + captured_tx.send(()).unwrap(); continue_rx.recv().unwrap(); + })); + + let q = BuildQueue::new(); + let background = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &q).unwrap(); + assert_eq!(calls.load(Ordering::Relaxed), 1, "request ran driver work inline"); + let foreground = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &q).unwrap(); + assert!(background.token().exact(foreground.token()), "foreground demand did not coalesce exactly"); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + std::thread::scope(|scope| { + let worker = scope.spawn(|| q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + captured_rx.recv().unwrap(); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 2 }); + continue_tx.send(()).unwrap(); + assert!(worker.join().unwrap()); + }); + let pin = foreground.wait_and_take_pin().unwrap(); + assert_eq!((pin.raw(), pin.id(), calls.load(Ordering::Relaxed)), (replacement_raw, 2, 2)); + assert_eq!(pin.raw(), replacement_raw, "a second detach invalidated the handed-off generation"); + + drop(background); drop(foreground); drop(pin); + RESTORE_REENTER_ATTEMPTS.with(|address| address.set(&coordinator.attempts as *const _ as usize)); + assert_eq!(coordinator.reconcile(2), 1); + RESTORE_REENTER_ATTEMPTS.with(|address| address.set(0)); + drop(coordinator); drop(build); drop(recipe); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn exact_restoration_tickets_report_every_terminal_and_do_not_reuse_attempts() { + let recipe = Recipe::new(|| 0); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let coordinator = RestorationCoordinator::<1, 1>::new(402).unwrap(); + let evicted = coordinated_evicted(&coordinator, &build, 60); + + let refused = BuildQueue::new(); refused.shutdown(); + let refused = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &refused).unwrap(); + assert!(matches!(refused.wait_and_take_pin(), Err(RehydrateCompletion::Refused))); assert_eq!(coordinator.reconcile(1), 1); + let cancelled = BuildQueue::new(); + let first = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &cancelled).unwrap(); + let first_token = first.token().clone(); cancelled.shutdown(); + assert!(matches!(first.wait_and_take_pin(), Err(RehydrateCompletion::Cancelled))); assert_eq!(coordinator.reconcile(1), 1); + let failed = BuildQueue::new(); + let second = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &failed).unwrap(); + assert!(!first_token.exact(second.token())); assert!(failed.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(second.wait_and_take_pin(), Err(RehydrateCompletion::BuildFailed))); assert_eq!(coordinator.reconcile(1), 1); + *coordinator.before_rebuild.lock().unwrap() = Some(Box::new(|| panic!("restoration panic"))); + let panicked = BuildQueue::new(); + let panic_ticket = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &panicked).unwrap(); + assert!(panicked.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(panic_ticket.wait_and_take_pin(), Err(RehydrateCompletion::Panicked))); assert_eq!(coordinator.reconcile(1), 1); + let retry_q = BuildQueue::new(); + let retry = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &retry_q).unwrap(); + assert!(retry_q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(retry.wait_and_take_pin(), Err(RehydrateCompletion::BuildFailed))); assert_eq!(coordinator.reconcile(1), 1); + let released_q = BuildQueue::new(); + let released = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, &released_q).unwrap(); + build.owners.store(0, Ordering::Release); + assert!(released_q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(matches!(released.wait_and_take_pin(), Err(RehydrateCompletion::Released))); assert_eq!(coordinator.reconcile(1), 1); + } + + fn structured_pending(build: Arc<Build>, compute: bool) -> Arc<Pending> { + Arc::new(Pending { + build, + driver: AtomicUsize::new(0), + compute, + key: 0, + used: AtomicBool::new(false), + late: AtomicBool::new(false), + spared: AtomicBool::new(false), + }) + } + + #[test] + fn dormant_restoration_coordinator_has_one_stable_identity() { + let first = pipeline_restoration_coordinator() as *const _; + let second = pipeline_restoration_coordinator() as *const _; + assert_eq!(first, second); + assert!(PIPELINE_RESTORATION_EVICTIONS > 0 && PIPELINE_RESOLUTION_RECEIPTS > 0); + + let original = 0x7E57_D010usize; + let pending = structured_pending(Arc::new(Build::new(Box::new(|| { + panic!("dormant classification ran initial driver work inline") + }), false)), false); + PENDING.insert(original, pending.clone()); + let resolution = begin_pipeline_resolution(original).expect("registered pipeline"); + assert_eq!(resolution.identity_for_test(), (original, Arc::as_ptr(&pending) as usize)); + assert!(Arc::ptr_eq(&PENDING.remove(original).unwrap(), &pending)); + } + + #[test] + fn restoration_coordinator_reuses_its_bounded_eviction_capacity() { + let coordinator = RestorationCoordinator::<2, PIPELINE_RESOLUTION_RECEIPTS>::new(510).unwrap(); + let first_build = ledger_build(); + let second_build = ledger_build(); + let third_build = ledger_build(); + let first = coordinator.install_eviction(&first_build, ledger_native(70)).unwrap().commit(); + let second = coordinator.install_eviction(&second_build, ledger_native(71)).unwrap().commit(); + assert!(coordinator.install_eviction(&third_build, ledger_native(72)).is_none()); + + assert!(first_build.clear_eviction_token(&first)); + assert!(coordinator.evicted.finish(&first, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&first)); + drop(coordinator.install_eviction(&third_build, ledger_native(72)) + .expect("retired bounded slot was not reusable")); + + assert!(second_build.clear_eviction_token(&second)); + assert!(coordinator.evicted.finish(&second, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&second)); + assert!(coordinator.evicted.records(2).is_empty()); + } + + #[test] + fn dormant_resolution_maps_queue_shutdown_without_inline_driver_work() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + raw + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let pin = recipe.pin_with_residency(raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, PIPELINE_RESOLUTION_RECEIPTS>::new(511).unwrap(); + let evicted = coordinator.install_eviction(&build, pin.ledger_identity()).unwrap().commit(); + drop(pin); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + let pending = structured_pending(build.clone(), false); + let q = BuildQueue::new(); + q.shutdown(); + + let resolution = begin_pipeline_resolution_on(0x7E57_D011, &pending, &coordinator, &q); + assert_eq!(calls.load(Ordering::Relaxed), 1, "classification ran driver work inline"); + assert!(matches!(resolution.0.wait_exact(), Err(StructuredResolveFailure::Refused))); + assert_eq!(coordinator.reconcile(1), 1); + + assert!(build.clear_eviction_token(&evicted)); + assert!(coordinator.evicted.finish(&evicted, EvictedBuildState::Poisoned)); + assert!(coordinator.evicted.retire(&evicted)); + drop(resolution); drop(pending); drop(build); drop(recipe); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn structured_resolve_retains_pending_across_title_address_reuse() { + let original = 0x7E57_D001usize; + let old = structured_pending(Arc::new(Build::new(Box::new(|| 0), false)), false); + let coordinator = RestorationCoordinator::<1, 1>::new(501).unwrap(); + let q = BuildQueue::new(); + let outcome = classify_structured_on(original, &old, &coordinator, &q); + let replacement = structured_pending(Arc::new(Build::new(Box::new(|| 0), false)), true); + PENDING.insert(original, replacement.clone()); + + match outcome { + StructuredResolve::Initial { original: retained_original, pending, fallback, bound_unbuilt } => { + assert_eq!((retained_original, fallback, bound_unbuilt), (original, original, true)); + assert!(Arc::ptr_eq(&pending, &old), "address reuse redirected a retained decision"); + assert!(!Arc::ptr_eq(&pending, &replacement)); + } + _ => panic!("unfinished build was not classified as initial"), + } + assert!(Arc::ptr_eq(&PENDING.remove(original).unwrap(), &replacement)); + } + + #[test] + fn structured_resolve_fails_closed_without_exact_eviction_record() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + let pending = structured_pending(build.clone(), false); + let coordinator = RestorationCoordinator::<1, 1>::new(502).unwrap(); + let outcome = classify_structured_on(0x7E57_D002, &pending, &coordinator, &BuildQueue::new()); + assert!(matches!(outcome, StructuredResolve::Terminal { + failure: StructuredResolveFailure::MissingEvictionRecord, .. + })); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + drop(pending); drop(build); drop(recipe); + } + + #[test] + fn structured_resolve_keeps_exact_pin_during_speculative_rebuild() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + assert!(matches!(recipe.begin_rebuild(), RebuildTurn::Leader)); + let pending = structured_pending(build.clone(), false); + let coordinator = RestorationCoordinator::<1, 1>::new(504).unwrap(); + let outcome = classify_structured_on(0x7E57_D004, &pending, &coordinator, &BuildQueue::new()); + let StructuredResolve::Ready { raw: chosen, pin: Some(pin), .. } = outcome else { + panic!("a rebuilding replacement hid the current exact generation") + }; + assert_eq!((chosen, pin.raw()), (raw, raw)); + recipe.finish_rebuild(RebuildResult::Failed); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(pin); drop(pending); drop(build); drop(recipe); release(raw_owner); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn structured_resolve_promotes_exact_background_without_inline_driver_work() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let calls = Arc::new(AtomicUsize::new(0)); + let build_next = next.clone(); let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + build_next.load(Ordering::Acquire) + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let pin = recipe.pin_with_residency(first_raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, 1>::new(503).unwrap(); + let evicted = coordinator.install_eviction(&build, pin.ledger_identity()).unwrap().commit(); + drop(pin); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + let pending = structured_pending(build.clone(), false); + let q = BuildQueue::new(); + let background = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &q).unwrap(); + let outcome = classify_structured_on(0x7E57_D003, &pending, &coordinator, &q); + let StructuredResolve::Restoring { ticket, .. } = &outcome else { panic!("eviction did not classify as restoring") }; + assert!(background.token().exact(ticket.token()), "foreground classification did not coalesce exactly"); + assert_eq!(calls.load(Ordering::Relaxed), 1, "classification ran driver work inline"); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload), "attempt was not promoted"); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + let resolved = outcome.wait_exact().unwrap().unwrap(); + assert_eq!((resolved.raw, resolved.bound_unbuilt, calls.load(Ordering::Relaxed)), + (replacement_raw, false, 2)); + assert!(resolved.pin.is_some()); + + drop(resolved); drop(outcome); drop(background); + assert_eq!(coordinator.reconcile(1), 1); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(pending); drop(build); drop(recipe); release(raw_owner); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn structured_resolve_prefers_publication_over_stale_cancelled_request() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); complete(&build, initial()); + let pin = recipe.pin_with_residency(first_raw).0.unwrap(); + let coordinator = RestorationCoordinator::<1, 2>::new(505).unwrap(); + let evicted = coordinator.install_eviction(&build, pin.ledger_identity()).unwrap().commit(); + drop(pin); assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + let pending = structured_pending(build.clone(), false); let q = BuildQueue::new(); + let background = coordinator.request_exact_on(&evicted, RehydratePriority::Background, &q).unwrap(); + let (seen_tx, seen_rx) = mpsc::channel(); let (continue_tx, continue_rx) = mpsc::channel(); + *coordinator.before_classified_request.lock().unwrap() = Some(Box::new(move || { + seen_tx.send(()).unwrap(); continue_rx.recv().unwrap(); + })); + std::thread::scope(|scope| { + let classifier = scope.spawn(|| classify_structured_on(0x7E57_D005, &pending, &coordinator, &q)); + seen_rx.recv().unwrap(); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Preload)); + drop(background.wait_and_take_pin().unwrap()); drop(background); + assert_eq!(coordinator.reconcile(1), 1); + continue_tx.send(()).unwrap(); + let outcome = classifier.join().unwrap(); + assert!(matches!(outcome, StructuredResolve::Ready { raw, pin: Some(_), .. } if raw == replacement_raw), + "stale cancelled request hid a concurrently published generation"); + drop(outcome); + }); + assert_eq!(coordinator.reconcile(2), 1, "stale request was not retired"); + let raw_owner = build.real.swap(0, Ordering::AcqRel); + drop(pending); drop(build); drop(recipe); release(raw_owner); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn pressure_observer_bounds_inspection_and_requeues_every_resident() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = [ + RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }, + RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }, + RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }, + ]; + let mut builds = Vec::new(); + let mut recipes = Vec::new(); + for value in &mut native { + let raw = value as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed( + recipe.initial_job(), false, None, Some(recipe.clone()), + )); + let job = build.job.lock().unwrap().take().unwrap(); + complete(&build, job()); + builds.push(build); + recipes.push(recipe); + } + let queue = CandidateQueue::<Build, 4>::new(); + for (build, last_use) in builds.iter().zip([99, 10, 20]) { + build.completed_frame.store(0, Ordering::Relaxed); + note_eviction_candidate_on(build, last_use, &queue); + } + + let config = PressureAdmissionConfig { + enabled: true, + max_sample_age_turns: 1, + max_evictions_per_turn: 2, + ..PressureAdmissionConfig::default() + }; + let limits = EvictionSelectionLimits { + max_scan: 3, max_select: 2, min_unused_frames: 10, min_resident_frames: 0, + }; + let mut observer = PressureObserver::new(config, limits).unwrap(); + let positions = || ( + queue.enqueue.load(Ordering::Relaxed), queue.dequeue.load(Ordering::Relaxed), + ); + + let before = positions(); + let mut disabled = PressureObserver::new(PressureAdmissionConfig::default(), limits).unwrap(); + assert_eq!(disabled.observe_on(&queue, 7, 100, Some(pressure_sample(7, 100))), PressureObservation::default()); + assert_eq!(positions(), before, "a disabled observer touched the candidate journal"); + assert_eq!(observer.observe_on(&queue, 8, 100, None), PressureObservation::default()); + assert_eq!(positions(), before, "a missing sample touched the candidate journal"); + let stale = PressureSample { + observed_turn: 7, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + assert_eq!(observer.observe_on(&queue, 9, 100, Some(stale)), PressureObservation::default()); + assert_eq!(positions(), before, "a stale sample touched the candidate journal"); + + let high = PressureSample { + observed_turn: 9, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + let observed = observer.observe_on(&queue, 10, 100, Some(high)); + assert_eq!(observed, PressureObservation { + mode: PressureMode::Evicting, + scanned: 2, + eligible: 1, + deferred: 1, + discarded: 0, + requeue_saturated: 0, + }); + assert!(builds.iter().all(|build| build.real.load(Ordering::Acquire) != 0)); + assert!(builds.iter().all(|build| build.candidate_queued.load(Ordering::Acquire))); + + let same_turn = PressureSample { + observed_turn: 10, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + assert_eq!(observer.observe_on(&queue, 10, 100, Some(same_turn)), PressureObservation { + mode: PressureMode::Evicting, ..Default::default() + }, "a second sample replenished the same observation turn"); + + // Deterministically model producers consuming every freed slot between drain and requeue. + // The observer must retain exact candidates instead of clearing their queued identity. + let fillers: Vec<_> = (0..3).map(|_| Arc::new(Build::new(Box::new(|| 0), false))).collect(); + let next = PressureSample { + observed_turn: 11, + segment: super::super::memory_report::Segment { usage: 95, budget: 100 }, + }; + let saturated = observer.observe_on_after_drain(&queue, 11, 100, Some(next), || { + for filler in &fillers { + assert!(queue.push(Arc::downgrade(filler)).is_ok()); + } + }); + assert_eq!(saturated, PressureObservation { + mode: PressureMode::Evicting, + scanned: 2, + eligible: 2, + deferred: 0, + discarded: 0, + requeue_saturated: 2, + }); + assert_eq!(observer.held.len(), 2); + assert!(observer.held.iter().all(|candidate| candidate.build.upgrade() + .is_some_and(|build| build.candidate_queued.load(Ordering::Acquire)))); + let blocked = observer.observe_on(&queue, 12, 100, None); + assert_eq!(blocked.requeue_saturated, 2); + assert_eq!(blocked.scanned, 0, "a saturated conservation backlog allowed another drain"); + let crossing = observer.held[0].build.upgrade().unwrap(); + let crossing_recipe = crossing.recipe.as_ref().unwrap().clone(); + assert!(matches!(crossing_recipe.begin_rebuild(), RebuildTurn::Leader)); + let before_crossing_bind = positions(); + note_eviction_candidate_on(&crossing, 100, &queue); + assert_eq!(positions(), before_crossing_bind, "a crossing bind duplicated the held identity"); + + let mut seen = HashSet::new(); + for _ in 0..2 { + let build = queue.pop().unwrap().upgrade().unwrap(); + if builds.iter().any(|expected| Arc::ptr_eq(expected, &build)) { + assert!(seen.insert(Arc::as_ptr(&build) as usize)); + } + } + let recovered = observer.observe_on(&queue, 13, 100, None); + assert_eq!(recovered.requeue_saturated, 0); + assert!(observer.held.is_empty()); + crossing_recipe.finish_rebuild(RebuildResult::Failed); + drop(crossing); + drop(crossing_recipe); + for _ in 0..4 { + let build = queue.pop().unwrap().upgrade().unwrap(); + if builds.iter().any(|expected| Arc::ptr_eq(expected, &build)) { + assert!(seen.insert(Arc::as_ptr(&build) as usize), "observation duplicated a journal record"); + } + } + assert_eq!(seen.len(), 3); + assert!(queue.pop().is_none()); + for build in &builds { + build.candidate_queued.store(false, Ordering::Release); + } + + let finals: Vec<_> = builds.iter().map(|build| build.real.swap(0, Ordering::AcqRel)).collect(); + drop(builds); + drop(recipes); + for raw in finals { + release(raw); + } + assert!(native.iter().all(|value| value.refs.load(Ordering::Relaxed) == 0)); + } + + #[test] + fn saturated_pressure_backlog_does_not_retain_a_released_native_pipeline() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed( + recipe.initial_job(), false, None, Some(recipe.clone()), + )); + let job = build.job.lock().unwrap().take().unwrap(); + complete(&build, job()); + let queue = CandidateQueue::<Build, 2>::new(); + note_eviction_candidate_on(&build, 0, &queue); + let fillers = [Arc::new(Build::new(Box::new(|| 0), false)), + Arc::new(Build::new(Box::new(|| 0), false))]; + let config = PressureAdmissionConfig { + enabled: true, max_evictions_per_turn: 1, ..PressureAdmissionConfig::default() + }; + let mut observer = PressureObserver::new(config, EvictionSelectionLimits { + max_scan: 1, max_select: 1, min_unused_frames: 0, min_resident_frames: 0, + }).unwrap(); + let saturated = observer.observe_on_after_drain(&queue, 1, 1, Some(pressure_sample(1, 100)), || { + for filler in &fillers { + assert!(queue.push(Arc::downgrade(filler)).is_ok()); + } + }); + assert_eq!(saturated.requeue_saturated, 1); + assert_eq!(observer.held.len(), 1); + + build.owners.store(0, Ordering::Release); + release(build.real.swap(0, Ordering::AcqRel)); + drop(build); + drop(recipe); + assert_eq!(native.refs.load(Ordering::Relaxed), 0, "weak backlog retained the native generation"); + assert!(observer.held[0].build.upgrade().is_none()); + let expired = observer.observe_on(&queue, 2, 1, None); + assert_eq!((expired.requeue_saturated, expired.discarded), (0, 1)); + assert!(observer.held.is_empty(), "an expired weak identity remained backlogged"); + } + + #[test] + fn pressure_observer_reports_every_popped_invalid_record() { + let queue = CandidateQueue::<Build, 4>::new(); + let dead = Arc::new(Build::new(Box::new(|| 0), false)); + assert!(queue.push(Arc::downgrade(&dead)).is_ok()); + drop(dead); + let nonresident = Arc::new(Build::new(Box::new(|| 0), false)); nonresident.candidate_queued.store(true, Ordering::Release); + assert!(queue.push(Arc::downgrade(&nonresident)).is_ok()); + let config = PressureAdmissionConfig { + enabled: true, max_evictions_per_turn: 2, ..PressureAdmissionConfig::default() + }; + let mut observer = PressureObserver::new(config, EvictionSelectionLimits { + max_scan: 2, max_select: 2, min_unused_frames: 0, min_resident_frames: 0, + }).unwrap(); + assert_eq!(observer.observe_on(&queue, 1, 1, Some(pressure_sample(1, 100))), PressureObservation { + mode: PressureMode::Evicting, + scanned: 2, + eligible: 0, + deferred: 1, + discarded: 1, + requeue_saturated: 0, + }); + assert!(queue.pop().unwrap().upgrade().is_some()); + } + + #[test] + fn rebuild_recipe_gate_requires_exact_one() { + assert!(recipe_gate_value(Some("1"))); + assert!(recipe_gate_value(Some(" 1\t"))); + assert!(pressure_observe_gate_value(Some(" 1\t"))); + for value in [None, Some(""), Some("0"), Some("true"), Some("2")] { + assert!(!recipe_gate_value(value)); + assert!(!pressure_observe_gate_value(value)); + } + } + + #[test] + fn eviction_candidate_ring_is_bounded_reusable_and_does_not_retain_builds() { + assert!(std::panic::catch_unwind(CandidateQueue::<usize, 0>::new).is_err()); + assert!(std::panic::catch_unwind(CandidateQueue::<usize, 1>::new).is_err()); + let queue = CandidateQueue::<usize, 2>::new(); + let first = Arc::new(1usize); + let second = Arc::new(2usize); + let third = Arc::new(3usize); + assert!(queue.push(Arc::downgrade(&first)).is_ok()); + assert!(queue.push(Arc::downgrade(&second)).is_ok()); + assert!(queue.push(Arc::downgrade(&third)).is_err(), "a full candidate ring accepted an unbounded record"); + assert_eq!(*queue.pop().unwrap().upgrade().unwrap(), 1); + assert!(queue.push(Arc::downgrade(&third)).is_ok(), "a drained ring slot was not reusable"); + assert_eq!(*queue.pop().unwrap().upgrade().unwrap(), 2); + assert_eq!(*queue.pop().unwrap().upgrade().unwrap(), 3); + assert!(queue.pop().is_none()); + + let builds = CandidateQueue::<Build, 2>::new(); + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let weak = Arc::downgrade(&build); + note_eviction_candidate_on(&build, 7, &builds); + drop(build); + assert!(weak.upgrade().is_none(), "an unconsumed candidate retained a released build"); + assert!(builds.pop().unwrap().upgrade().is_none(), "a released build record changed identity"); + } + + #[test] + fn eviction_candidate_ring_mpmc_delivers_every_weak_once() { + const COUNT: usize = 512; + let queue = CandidateQueue::<usize, 64>::new(); + let values: Vec<_> = (0..COUNT).map(Arc::new).collect(); + let seen: Vec<_> = (0..COUNT).map(|_| AtomicUsize::new(0)).collect(); + let consumed = AtomicUsize::new(0); + std::thread::scope(|scope| { + for producer in 0..4 { + let queue = &queue; + let values = &values; + scope.spawn(move || { + for index in (producer..COUNT).step_by(4) { + let mut value = Arc::downgrade(&values[index]); + loop { + match queue.push(value) { + Ok(()) => break, + Err(returned) => { + value = returned; + std::thread::yield_now(); + } + } + } + } + }); + } + for _ in 0..4 { + let queue = &queue; + let seen = &seen; + let consumed = &consumed; + scope.spawn(move || loop { + if consumed.load(Ordering::Acquire) == COUNT { + break; + } + let Some(value) = queue.pop() else { + std::thread::yield_now(); + continue; + }; + let index = *value.upgrade().expect("payload died while retained by the test"); + seen[index].fetch_add(1, Ordering::Relaxed); + consumed.fetch_add(1, Ordering::Release); + }); + } + }); + assert_eq!(consumed.load(Ordering::Relaxed), COUNT); + assert!(seen.iter().all(|count| count.load(Ordering::Relaxed) == 1), "a payload was lost or delivered twice"); + assert!(values.iter().all(|value| Arc::weak_count(value) == 0), "a queued Weak payload was not dropped exactly once"); + assert!(queue.pop().is_none()); + } + + #[test] + fn eviction_candidates_deduplicate_bound_drain_and_filter_ineligible_builds() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut second = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let second_raw = &mut second as *mut RebuildFakePso as usize; + let first_recipe = Recipe::new(move || first_raw); + let second_recipe = Recipe::new(move || second_raw); + let first_build = Arc::new(Build::new_keyed( + first_recipe.initial_job(), false, None, Some(first_recipe.clone()), + )); + let second_build = Arc::new(Build::new_keyed( + second_recipe.initial_job(), false, None, Some(second_recipe.clone()), + )); + let first_job = first_build.job.lock().unwrap().take().unwrap(); + let second_job = second_build.job.lock().unwrap().take().unwrap(); + complete(&first_build, first_job()); + complete(&second_build, second_job()); + let queue = CandidateQueue::<Build, 4>::new(); + + // Ordinary/default resolution bookkeeping does not touch the opt-in candidate journal. + let pending = Pending { + build: first_build.clone(), driver: AtomicUsize::new(0), compute: false, key: 0, + used: AtomicBool::new(false), late: AtomicBool::new(false), spared: AtomicBool::new(false), + }; + pending.note_use(); + assert!(!first_build.candidate_queued.load(Ordering::Acquire)); + + note_eviction_candidate_on(&first_build, 10, &queue); + note_eviction_candidate_on(&first_build, 30, &queue); + note_eviction_candidate_on(&second_build, 20, &queue); + let limits = EvictionSelectionLimits { + max_scan: 2, max_select: 1, min_unused_frames: 0, min_resident_frames: 0, + }; + let selected = select_eviction_candidates_on(&queue, 100, limits); + assert_eq!(selected.len(), 1); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &second_build)); + assert_eq!(selected[0].unused_frames, 80); + assert_eq!(drain_eviction_candidates_on(&queue, 0).len(), 0, "a zero budget inspected work"); + drop(selected); + let selected = select_eviction_candidates_on(&queue, 100, limits); + assert_eq!(selected.len(), 1); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &first_build)); + drop(selected); + + let recent_limits = EvictionSelectionLimits { + max_scan: 2, max_select: 1, min_unused_frames: 10, min_resident_frames: 0, + }; + note_eviction_candidate_on(&first_build, 95, &queue); + for _ in 0..3 { + assert!(select_eviction_candidates_on(&queue, 100, recent_limits).is_empty()); + assert!(first_build.candidate_queued.load(Ordering::Acquire)); + } + let selected = select_eviction_candidates_on(&queue, 105, recent_limits); + assert_eq!(selected.len(), 1, "a deferred candidate required another bind to reappear"); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &first_build)); + assert!(queue.pop().is_none(), "repeated deferral duplicated a candidate record"); + drop(selected); + + assert!(matches!(first_recipe.begin_rebuild(), RebuildTurn::Leader)); + note_eviction_candidate_on(&first_build, 40, &queue); + assert!(select_eviction_candidates_on(&queue, 100, limits).is_empty(), "an active rebuild became evictable"); + first_recipe.finish_rebuild(RebuildResult::Failed); + first_build.owners.store(0, Ordering::Release); + note_eviction_candidate_on(&first_build, 50, &queue); + assert!(select_eviction_candidates_on(&queue, 100, limits).is_empty(), "a released build became evictable"); + + drop(pending); + let first_final = first_build.real.swap(0, Ordering::AcqRel); + let second_final = second_build.real.swap(0, Ordering::AcqRel); + drop(first_build); + drop(second_build); + drop(first_recipe); + drop(second_recipe); + release(first_final); + release(second_final); + assert_eq!((first.refs.load(Ordering::Relaxed), second.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn eviction_candidate_policy_uses_latest_age_and_orders_oldest_first() { + let make = |last_use, completed| { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + build.last_use_frame.store(last_use, Ordering::Relaxed); + build.completed_frame.store(completed, Ordering::Relaxed); + build.candidate_queued.store(true, Ordering::Release); + EvictionCandidate { + build, last_use_frame: last_use, completed_frame: completed, + clear_queued_on_drop: true, + } + }; + let oldest = make(10, 5); + let next = make(20, 1); + let recent = make(95, 0); + let young_resident = make(1, 95); + let wrapped = make(u64::MAX, 0); + let oldest_build = oldest.build.clone(); + let next_build = next.build.clone(); + let limits = EvictionSelectionLimits { + max_scan: 4, max_select: 2, min_unused_frames: 10, min_resident_frames: 20, + }; + + let (selected, _) = + partition_eviction_candidates(vec![recent, next, wrapped, young_resident, oldest], 100, limits); + assert_eq!(selected.len(), 2); + assert!(Arc::ptr_eq(&selected[0].candidate.build, &oldest_build)); + assert_eq!((selected[0].unused_frames, selected[0].resident_frames), (90, 95)); + assert!(Arc::ptr_eq(&selected[1].candidate.build, &next_build)); + + // A use after background drain is still visible through the Build atomic, even though the + // candidate's dedup flag prevents a second journal record while this owner exists. + let used_after_drain = make(30, 1); + used_after_drain.build.last_use_frame.store(99, Ordering::Relaxed); + assert!(partition_eviction_candidates(vec![used_after_drain], 100, limits).0.is_empty()); + assert_eq!(conservative_frame_age(3, u64::MAX), 0, "frame wrap assigned a false old age"); + } + + #[test] + fn eviction_candidate_requeue_full_clears_the_dedup_flag() { + let queue = CandidateQueue::<Build, 2>::new(); + let retained = [ + Arc::new(Build::new(Box::new(|| 0), false)), + Arc::new(Build::new(Box::new(|| 0), false)), + ]; + assert!(queue.push(Arc::downgrade(&retained[0])).is_ok()); + assert!(queue.push(Arc::downgrade(&retained[1])).is_ok()); + + let build = Arc::new(Build::new(Box::new(|| 0), false)); + build.candidate_queued.store(true, Ordering::Release); + let candidate = EvictionCandidate { + build: build.clone(), last_use_frame: 0, completed_frame: 0, + clear_queued_on_drop: true, + }; + assert!(!candidate.requeue_on(&queue)); + assert!(!build.candidate_queued.load(Ordering::Acquire)); + } + + #[test] + fn build_retains_a_reusable_recipe_after_its_initial_job_is_consumed() { + let calls = Arc::new(AtomicUsize::new(0)); + let recipe_calls = calls.clone(); + let recipe = Recipe::new(move || { + recipe_calls.fetch_add(1, Ordering::Relaxed) + 0x5100 + }); + let build = Build::new_keyed(recipe.initial_job(), false, None, Some(recipe)); + + let initial = build.job.lock().unwrap().take().unwrap(); + assert_eq!(initial(), 0x5100); + assert!(build.job.lock().unwrap().is_none()); + assert_eq!(build.recipe.as_ref().unwrap().run(), 0x5101); + assert_eq!(calls.load(Ordering::Relaxed), 2); + } + + #[test] + fn native_generation_slot_pins_exact_aba_owner_and_ids_publications() { + struct Owner(Arc<AtomicUsize>); + impl Drop for Owner { + fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let mut slot = GenerationSlot::default(); + let (first, replaced) = slot.publish(0x7E57_ABA0, Owner(drops.clone())); + assert!(replaced.is_none()); + let pinned = slot.pin(0x7E57_ABA0).unwrap(); + assert_eq!(first.id, 1); + let (second, replaced) = slot.publish(0x7E57_ABA0, Owner(drops.clone())); + assert_eq!(second.id, 2); + assert!(!Arc::ptr_eq(&pinned, &second), "a reused raw address aliased its older generation"); + let unique = dedup_generations( + [first.clone(), first.clone(), second.clone(), second.clone()].into_iter(), + |generation| Arc::as_ptr(generation) as usize, + ); + assert_eq!(unique.len(), 2, "a reused raw address collapsed distinct generations"); + drop(unique); + drop(first); + drop(replaced); + assert_eq!(drops.load(Ordering::Relaxed), 0, "the old generation died while a pin held it"); + drop(pinned); + assert_eq!(drops.load(Ordering::Relaxed), 1); + drop(second); + drop(slot); + assert_eq!(drops.load(Ordering::Relaxed), 2); + } + + #[derive(Clone)] + struct FakeReceipt { + fence: Arc<AtomicU64>, + value: u64, + } + + fn fake_receipt_complete(receipt: &FakeReceipt) -> bool { + receipt.fence.load(Ordering::Relaxed) >= receipt.value + } + + #[test] + fn generation_retirement_deduplicates_and_uses_the_exact_receipt_owner() { + let generation = Arc::new(()); + let pins = dedup_generations( + [generation.clone(), generation.clone()].into_iter(), + |generation| Arc::as_ptr(generation) as usize, + ); + assert_eq!(pins.len(), 1); + + let old_fence = Arc::new(AtomicU64::new(0)); + let replacement_fence = Arc::new(AtomicU64::new(99)); + let mut retiring = GenerationRetirements::new(); + drop(retiring.retire_pending( + FakeReceipt { fence: old_fence.clone(), value: 7 }, + pins, + fake_receipt_complete, + )); + drop(retiring.sweep(fake_receipt_complete)); + assert_eq!(retiring.pending.len(), 1, "a replacement queue generation retired an old receipt"); + assert_eq!(Arc::strong_count(&generation), 2, "the in-flight batch did not retain its generation"); + + old_fence.store(7, Ordering::Relaxed); + drop(retiring.sweep(fake_receipt_complete)); + assert!(retiring.pending.is_empty()); + assert_eq!(Arc::strong_count(&generation), 1); + assert_eq!(replacement_fence.load(Ordering::Relaxed), 99); + + drop(retiring.retire_pending( + FakeReceipt { fence: old_fence, value: 7 }, + vec![generation.clone()], + fake_receipt_complete, + )); + assert!(retiring.pending.is_empty(), "an already-complete receipt retained a final batch"); + } + + #[test] + fn untracked_generation_pins_are_never_swept() { + let generation = Arc::new(()); + let weak = Arc::downgrade(&generation); + let pins = dedup_generations( + [generation.clone(), generation.clone()].into_iter(), + |generation| Arc::as_ptr(generation) as usize, + ); + let mut retiring = GenerationRetirements::<Arc<()>, FakeReceipt>::new(); + retiring.poison(pins, |generation| Arc::as_ptr(generation) as usize); + retiring.poison(vec![generation.clone()], |generation| Arc::as_ptr(generation) as usize); + assert_eq!(retiring.poisoned.len(), 1, "a later poison duplicated an existing generation"); + drop(generation); + + drop(retiring.sweep(fake_receipt_complete)); + assert!(weak.upgrade().is_some(), "sweeping tracked receipts released an untracked generation"); + assert_eq!(retiring.poisoned.len(), 1); + } + + #[test] + fn newly_completed_batch_is_returned_for_drop_after_unlock() { + struct DropPin(Arc<AtomicUsize>); + impl Drop for DropPin { + fn drop(&mut self) { self.0.fetch_add(1, Ordering::Relaxed); } + } + + let drops = Arc::new(AtomicUsize::new(0)); + let fence = Arc::new(AtomicU64::new(1)); + let mut retiring = GenerationRetirements::new(); + let retired = retiring.retire_pending( + FakeReceipt { fence, value: 1 }, + vec![DropPin(drops.clone())], + fake_receipt_complete, + ); + + assert!(retiring.pending.is_empty()); + assert_eq!(drops.load(Ordering::Relaxed), 0, "the manager dropped a pin while it was borrowed mutably"); + drop(retired); + assert_eq!(drops.load(Ordering::Relaxed), 1); + } + + #[test] + fn concurrent_generation_publications_are_monotonic() { + let slot = Arc::new(Mutex::new(GenerationSlot::default())); + std::thread::scope(|scope| { + for thread in 0..4usize { + let slot = slot.clone(); + scope.spawn(move || { + for k in 0..100usize { + let (_, replaced) = slot.lock().unwrap().publish(thread * 100 + k + 1, ()); + drop(replaced); + } + }); + } + }); + let slot = slot.lock().unwrap(); + assert_eq!(slot.next, 400); + assert_eq!(slot.resident.as_ref().unwrap().id, 400); + } + + #[test] + fn overlapping_recipe_rebuild_requests_share_one_result() { + let recipe = Recipe::new(|| 0); + assert!(matches!(recipe.begin_rebuild(), RebuildTurn::Leader)); + let follower_recipe = recipe.clone(); + let follower = std::thread::spawn(move || follower_recipe.begin_rebuild()); + let started = std::time::Instant::now(); + loop { + if recipe.0.rebuild.lock().unwrap().waiters == 1 { + break; + } + assert!(started.elapsed() < std::time::Duration::from_secs(2), "follower did not join the active rebuild"); + std::thread::yield_now(); + } + let result = RebuildResult::Published { generation: 7 }; + recipe.finish_rebuild(result); + assert!(matches!(follower.join().unwrap(), RebuildTurn::Follower(r) if r == result)); + assert_eq!(recipe.0.rebuild.lock().unwrap().completed, 1); + } + + #[test] + fn next_leader_waits_for_prior_followers_to_consume_their_result() { + let recipe = Recipe::new(|| 0); + let first = RebuildResult::Published { generation: 11 }; + { + // Deterministically model a completed attempt whose notified follower has not yet + // reacquired the mutex. `last` must remain immutable until that waiter drains. + let mut state = recipe.0.rebuild.lock().unwrap(); + state.completed = 1; + state.last = Some(first); + state.waiters = 1; + } + let next_recipe = recipe.clone(); + let (leader_tx, leader_rx) = mpsc::channel(); + let next = std::thread::spawn(move || leader_tx.send(next_recipe.begin_rebuild()).unwrap()); + assert!(leader_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), "a new leader crossed an undrained prior follower"); + + let consumed = { + let mut state = recipe.0.rebuild.lock().unwrap(); + let result = state.last.unwrap(); + state.waiters = 0; + recipe.0.rebuild_done.notify_all(); + result + }; + assert_eq!(consumed, first); + assert!(matches!(leader_rx.recv().unwrap(), RebuildTurn::Leader)); + recipe.finish_rebuild(RebuildResult::Published { generation: 12 }); + next.join().unwrap(); + } + + #[test] + fn failed_rebuild_keeps_current_generation_and_success_replaces_it() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut second = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let second_raw = &mut second as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + assert_eq!((build.real.load(Ordering::Acquire), first.refs.load(Ordering::Relaxed)), (first_raw, 2)); + + next.store(0, Ordering::Release); + assert_eq!(rebuild_once(&build), Some(RebuildResult::Failed)); + assert_eq!(build.real.load(Ordering::Acquire), first_raw); + assert_eq!(recipe.pin_with_residency(first_raw).0.unwrap().id(), 1); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Resident); + + next.store(second_raw, Ordering::Release); + assert_eq!(rebuild_once(&build), Some(RebuildResult::Published { generation: 2 })); + assert_eq!(build.real.load(Ordering::Acquire), second_raw); + assert_eq!(first.refs.load(Ordering::Relaxed), 0, "both superseded owners release outside publication locks"); + assert_eq!(second.refs.load(Ordering::Relaxed), 2); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + assert_eq!(second.refs.load(Ordering::Relaxed), 1); + release(final_raw); + assert_eq!(second.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_detaches_both_native_owners_but_an_exact_pin_survives() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + let pin = recipe.pin_with_residency(raw).0.expect("resident generation"); + + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + assert_eq!(build.real.load(Ordering::Acquire), 0); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Evicted); + assert!(recipe.pin_with_residency(raw).0.is_none(), "evicted generation remained current"); + assert_eq!(native.refs.load(Ordering::Relaxed), 1, "the exact pin did not retain the native object"); + assert_eq!(try_evict_current(&build), EvictResult::NotResident, "repeated eviction detached another owner"); + + drop(pin); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_between_resolution_and_pinning_falls_back_from_the_stale_raw() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let standin = 0x7E57_C154usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + // Deterministically interleave eviction in the real resolver's gap: it observed `raw`, + // but has not yet taken Build.done and converted that observation into an exact pin. + let resolved = resolve_pending(&pending, standin); + let bound_unbuilt = pending.bound_unbuilt(standin, resolved); + assert_eq!((resolved, bound_unbuilt), (raw, false)); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + assert_eq!(native.refs.load(Ordering::Relaxed), 0, "eviction did not release both unpinned owners"); + + let (chosen, pin, stale_fallback) = pin_resolved(standin, &pending, resolved, bound_unbuilt); + assert_eq!(chosen, standin, "pin validation returned the freed pre-eviction raw pointer"); + assert!(pin.is_none()); + assert!(stale_fallback, "ExecuteIndirect must treat an eviction fallback as unbuilt"); + assert_eq!(released(standin), 0); + } + + #[test] + fn steady_evicted_compute_resolution_remains_fail_closed_as_unbuilt() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let standin = 0x7E57_C155usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, bound_unbuilt), (standin, true)); + assert!(pin.is_none()); + assert_eq!(released(standin), 0); + drop(pending); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_refuses_an_active_rebuild_and_restores_resident_state_on_failure() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let recipe = Recipe::new(move || raw); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + + assert!(matches!(recipe.begin_rebuild(), RebuildTurn::Leader)); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Rebuilding); + assert_eq!(try_evict_current(&build), EvictResult::Active); + assert_eq!(build.real.load(Ordering::Acquire), raw); + recipe.finish_rebuild(RebuildResult::Failed); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Resident); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + release(final_raw); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn eviction_refuses_a_build_after_its_last_title_owner_releases() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut native = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut native as *mut RebuildFakePso as usize; + let standin = 0x7E57_C153usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + let final_raw = released(standin); + assert_eq!(try_evict_current(&pending.build), EvictResult::Abandoned); + release(final_raw); + drop(pending); + assert_eq!(native.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn failed_initial_recipe_has_no_evictable_residency() { + let standin = 0x7E57_C156usize; + let recipe = Recipe::new(|| 0); + submit_recipe_keyed(standin, true, recipe.clone(), false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Failed); + assert_eq!(try_evict_current(&pending.build), EvictResult::NotResident); + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, bound_unbuilt), (standin, false), "a real build failure changed to transient-unbuilt"); + assert!(pin.is_none()); + assert_eq!(released(standin), 0); + } + + #[test] + fn release_during_rebuild_abandons_and_releases_the_new_raw() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let block = Arc::new((Mutex::new((false, false)), Condvar::new())); + let build_block = block.clone(); + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || { + let mut state = build_block.0.lock().unwrap(); + if state.0 { + state.1 = true; + build_block.1.notify_all(); + while state.0 { + state = build_block.1.wait(state).unwrap(); + } + } + build_next.load(Ordering::Acquire) + }); + let standin = 0x7E57_C150usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + + next.store(replacement_raw, Ordering::Release); + block.0.lock().unwrap().0 = true; + let rebuilding = pending.build.clone(); + let thread = std::thread::spawn(move || rebuild_once(&rebuilding)); + { + let mut state = block.0.lock().unwrap(); + while !state.1 { + state = block.1.wait(state).unwrap(); + } + } + let old_raw = released(standin); + release(old_raw); + { + let mut state = block.0.lock().unwrap(); + state.0 = false; + block.1.notify_all(); + } + assert_eq!(thread.join().unwrap(), Some(RebuildResult::Abandoned)); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 0, "an abandoned new raw leaked"); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn async_rebuild_requests_coalesce_without_running_on_the_requester() { + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + 0 + }); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + let q = BuildQueue::new(); + + assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Queued); + assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Coalesced); + assert_eq!(calls.load(Ordering::Relaxed), 1, "requesting performed driver work"); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(build.recipe.as_ref().unwrap().0.rebuild.lock().unwrap().completed, 1); + } + + #[test] + fn async_rebuild_released_before_start_does_not_run_or_resurrect() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + first_raw + }); + let standin = 0x7E57_C151usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + let q = BuildQueue::new(); + assert_eq!(request_rebuild_on(pending.build.clone(), &q), RebuildRequest::Queued); + + let current = released(standin); + release(current); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 1, "orphaned queued request ran its recipe"); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0, "queued work resurrected a released build"); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn async_rebuild_failure_keeps_current_generation() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + next.store(0, Ordering::Release); + let q = BuildQueue::new(); + + assert_eq!(request_rebuild_on(build.clone(), &q), RebuildRequest::Queued); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(build.real.load(Ordering::Acquire), first_raw); + assert_eq!(recipe.pin_with_residency(first_raw).0.unwrap().id(), 1); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + release(final_raw); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn async_rebuild_released_while_worker_runs_abandons_replacement() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let block = Arc::new((Mutex::new((false, false)), Condvar::new())); + let build_block = block.clone(); + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || { + if build_next.load(Ordering::Acquire) == replacement_raw { + let mut state = build_block.0.lock().unwrap(); + state.0 = true; + build_block.1.notify_all(); + while !state.1 { state = build_block.1.wait(state).unwrap(); } + } + build_next.load(Ordering::Acquire) + }); + let standin = 0x7E57_C152usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + next.store(replacement_raw, Ordering::Release); + let q = Arc::new(BuildQueue::new()); + assert_eq!(request_rebuild_on(pending.build.clone(), &q), RebuildRequest::Queued); + let worker_q = q.clone(); + let worker = std::thread::spawn(move || worker_q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + { + let mut state = block.0.lock().unwrap(); + while !state.0 { state = block.1.wait(state).unwrap(); } + } + let old = released(standin); + release(old); + block.0.lock().unwrap().1 = true; + block.1.notify_all(); + assert!(worker.join().unwrap()); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 0); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn async_rehydrate_coalesces_stays_unbuilt_until_worker_publication() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let standin = 0x7E57_C157usize; + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + build_next.load(Ordering::Acquire) + }); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + let q = BuildQueue::new(); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Resident); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + next.store(replacement_raw, Ordering::Release); + + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Queued); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Coalesced); + assert_eq!(calls.load(Ordering::Relaxed), 1, "requester performed driver work"); + let ((chosen, unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, unbuilt), (standin, true)); + assert!(pin.is_none()); + + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 2); + assert_eq!(pending.build.real.load(Ordering::Acquire), replacement_raw); + assert_eq!(pending.build.recipe.as_ref().unwrap().0.generation.lock().unwrap().residency, Residency::Resident); + let ((chosen, unbuilt), pin) = resolve_wait_bound_and_pin(standin); + assert_eq!((chosen, unbuilt), (replacement_raw, false)); + drop(pin); + + let final_raw = released(standin); + release(final_raw); + drop(pending); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn refused_cancelled_and_failed_rehydrate_remain_retryable() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let next = Arc::new(AtomicUsize::new(first_raw)); + let build_next = next.clone(); + let recipe = Recipe::new(move || build_next.load(Ordering::Acquire)); + let build = Arc::new(Build::new_keyed(recipe.initial_job(), false, None, Some(recipe.clone()))); + let initial = build.job.lock().unwrap().take().unwrap(); + complete(&build, initial()); + assert_eq!(try_evict_current(&build), EvictResult::Evicted { generation: 1 }); + + let refused = BuildQueue::new(); + refused.shutdown(); + assert_eq!(request_rehydrate_on(build.clone(), &refused), RehydrateRequest::Unavailable); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Evicted); + let cancelled = BuildQueue::new(); + assert_eq!(request_rehydrate_on(build.clone(), &cancelled), RehydrateRequest::Queued); + cancelled.shutdown(); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Evicted); + + next.store(0, Ordering::Release); + let failed = BuildQueue::new(); + assert_eq!(request_rehydrate_on(build.clone(), &failed), RehydrateRequest::Queued); + assert!(failed.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Failed); + next.store(replacement_raw, Ordering::Release); + let retry = BuildQueue::new(); + assert_eq!(request_rehydrate_on(build.clone(), &retry), RehydrateRequest::Queued); + assert!(retry.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(build.real.load(Ordering::Acquire), replacement_raw); + + let final_raw = build.real.swap(0, Ordering::AcqRel); + drop(build); + drop(recipe); + release(final_raw); + assert_eq!((first.refs.load(Ordering::Relaxed), replacement.refs.load(Ordering::Relaxed)), (0, 0)); + } + + #[test] + fn completed_rehydrate_guard_cannot_cancel_a_newer_turn() { + let recipe = Recipe::new(|| 0); + recipe.mark_failed(); + let first_turn = recipe.reserve_rehydrate().unwrap(); + let old = RehydrateReservation { recipe: recipe.clone(), turn: first_turn }; + recipe.finish_rebuild(RebuildResult::Failed); + + let second_turn = recipe.reserve_rehydrate().unwrap(); + let new = RehydrateReservation { recipe: recipe.clone(), turn: second_turn }; + assert_eq!((first_turn, second_turn), (0, 1)); + drop(old); + { + let state = recipe.0.rebuild.lock().unwrap(); + assert!(state.active, "old guard cancelled the newer reservation"); + assert_eq!(state.completed, second_turn); + } + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Rebuilding); + + drop(new); + let state = recipe.0.rebuild.lock().unwrap(); + assert!(!state.active); + assert_eq!(state.completed, second_turn + 1); + drop(state); + assert_eq!(recipe.0.generation.lock().unwrap().residency, Residency::Failed); + } + + #[test] + fn rehydrate_released_before_worker_does_not_run_or_resurrect() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let standin = 0x7E57_C158usize; + let recipe = Recipe::new(move || { + build_calls.fetch_add(1, Ordering::Relaxed); + first_raw + }); + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + let q = BuildQueue::new(); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Queued); + + assert_eq!(released(standin), 0); + assert!(q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + assert_eq!(calls.load(Ordering::Relaxed), 1, "released rehydration ran its recipe"); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn rehydrate_released_during_worker_abandons_new_raw() { + let vtable = [0usize, rebuild_fake_add_ref as usize, rebuild_fake_release as usize]; + let mut first = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let mut replacement = RebuildFakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let first_raw = &mut first as *mut RebuildFakePso as usize; + let replacement_raw = &mut replacement as *mut RebuildFakePso as usize; + let calls = Arc::new(AtomicUsize::new(0)); + let build_calls = calls.clone(); + let block = Arc::new((Mutex::new((false, false)), Condvar::new())); + let build_block = block.clone(); + let recipe = Recipe::new(move || { + if build_calls.fetch_add(1, Ordering::Relaxed) != 0 { + let mut state = build_block.0.lock().unwrap(); + state.0 = true; + build_block.1.notify_all(); + while !state.1 { state = build_block.1.wait(state).unwrap(); } + replacement_raw + } else { + first_raw + } + }); + let standin = 0x7E57_C159usize; + submit_recipe_keyed(standin, false, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let initial = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, initial()); + assert_eq!(try_evict_current(&pending.build), EvictResult::Evicted { generation: 1 }); + let q = Arc::new(BuildQueue::new()); + assert_eq!(request_rehydrate_on(pending.build.clone(), &q), RehydrateRequest::Queued); + let worker_q = q.clone(); + let worker = std::thread::spawn(move || worker_q.try_run_one_between(Priority::Speculative, Priority::Speculative)); + { + let mut state = block.0.lock().unwrap(); + while !state.0 { state = block.1.wait(state).unwrap(); } + } + assert_eq!(released(standin), 0); + block.0.lock().unwrap().1 = true; + block.1.notify_all(); + assert!(worker.join().unwrap()); + assert_eq!(pending.build.real.load(Ordering::Acquire), 0); + assert_eq!(replacement.refs.load(Ordering::Relaxed), 0); + drop(pending); + assert_eq!(first.refs.load(Ordering::Relaxed), 0); + } + + #[test] + fn capture_preserves_lazy_for_bind_wait_and_identity_choices() { + let standin = 0x7E57_C130usize; + let real = 0x7E57_C131usize; + let (go_tx, go_rx) = mpsc::channel(); + let (started_tx, started_rx) = mpsc::channel(); + submit_lazy(standin, true, Box::new(move || { + started_tx.send(()).unwrap(); + go_rx.recv().unwrap(); + real + }), 0); + + let (lazy, lazy_pin) = resolve_and_pin_mode(standin, ResolveMode::Lazy); + assert_eq!(lazy, standin); + assert!(lazy_pin.is_none()); + let (identity, identity_pin) = resolve_and_pin_if_enabled_identity(standin); + assert_eq!(identity, standin); + assert!(identity_pin.is_none()); + started_rx.recv().unwrap(); + let (result_tx, result_rx) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| result_tx.send(resolve_and_pin_mode(standin, ResolveMode::ForBind).0).unwrap()); + assert!(result_rx.recv_timeout(std::time::Duration::from_millis(10)).is_err(), "for-bind compute resolution must still wait"); + go_tx.send(()).unwrap(); + }); + assert_eq!(result_rx.recv().unwrap(), real); + assert_eq!(resolve_and_pin_mode(standin, ResolveMode::Wait).0, real); + assert_eq!(released(standin), real); + } + + #[test] + fn capture_never_resolves_against_a_reused_pending_address() { + let standin = 0x7E57_C138usize; + let old_real = 0x7E57_C139usize; + submit_lazy(standin, false, Box::new(move || old_real), 0); + let old = entry(standin).unwrap(); + let job = old.build.job.lock().unwrap().take().unwrap(); + complete(&old.build, job()); + let removed = PENDING.remove(standin).unwrap(); + + submit_lazy(standin, false, Box::new(|| 0x7E57_C13Ausize), 0); + let (chosen, pin) = resolve_and_pin_pending(standin, &old, ResolveMode::Lazy); + assert_eq!(chosen, old_real, "selection must use the retained Pending, not its reused map slot"); + assert!(pin.is_none()); + + assert_eq!(released(standin), 0); + drop(removed); + drop(old); + } + + #[test] + fn bound_wait_capture_pins_the_exact_published_generation() { + #[repr(C)] + struct FakePso { vtable: *const usize, refs: AtomicUsize } + unsafe extern "system" fn add_ref(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut FakePso)).refs.fetch_add(1, Ordering::Relaxed) as u32 + 1 + } + unsafe extern "system" fn release(this: *mut std::ffi::c_void) -> u32 { + (*(this as *mut FakePso)).refs.fetch_sub(1, Ordering::Relaxed) as u32 - 1 + } + + let vtable = [0usize, add_ref as usize, release as usize]; + let mut fake = FakePso { vtable: vtable.as_ptr(), refs: AtomicUsize::new(1) }; + let raw = &mut fake as *mut FakePso as usize; + let standin = 0x7E57_C140usize; + let recipe = Recipe::new(move || raw); + submit_recipe_keyed(standin, true, recipe, false, 0, None); + let pending = entry(standin).unwrap(); + let job = pending.build.job.lock().unwrap().take().unwrap(); + complete(&pending.build, job()); + + let ((chosen, bound_unbuilt), pin) = resolve_wait_bound_and_pin(standin); + let pin = pin.expect("published recipe generation must be captured"); + assert_eq!((chosen, bound_unbuilt, pin.raw(), pin.id()), (raw, false, raw, 1)); + assert_eq!(fake.refs.load(Ordering::Relaxed), 2, "generation pin shares the recipe's exact COM owner"); + + drop(pin); + assert_eq!(released(standin), raw); + drop(pending); + assert_eq!(unsafe { release(raw as *mut std::ffi::c_void) }, 0); + } + + #[test] + fn a_panicking_pipeline_job_completes_failed_and_wakes_its_waiter() { + let build = Arc::new(Build::new(Box::new(|| panic!("simulated pipeline panic")), false)); + let waiting = build.clone(); + let (tx, rx) = mpsc::channel(); + let waiter = std::thread::spawn(move || { + let (done, _) = waiting + .cv + .wait_timeout_while(waiting.done.lock().unwrap(), std::time::Duration::from_secs(5), |done| !*done) + .unwrap(); + tx.send((*done, waiting.real.load(Ordering::Acquire))).unwrap(); + }); + + let job = build.job.lock().unwrap().take().unwrap(); + run_build(&build, job); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(5)), Ok((true, 0))); + waiter.join().unwrap(); + assert!(BUILDING.with(|building| building.borrow().is_none()), "panicking build left worker-local demand installed"); + + let next = Arc::new(Build::new(Box::new(|| 0x5151), false)); + let job = next.job.lock().unwrap().take().unwrap(); + run_build(&next, job); + assert_eq!(next.real.load(Ordering::Acquire), 0x5151, "the worker path did not survive a prior panic"); + + let refused = Arc::new(Build::new(Box::new(|| 0x6161), false)); + fail_unrunnable_build(&refused); + assert!(*refused.done.lock().unwrap(), "worker-start/submission failure did not complete the build"); + assert!(refused.job.lock().unwrap().is_none()); + assert_eq!(refused.real.load(Ordering::Acquire), 0); + + assert_eq!( + build_pieces(vec![Box::new(|| 0x11), Box::new(|| panic!("simulated piece panic")), Box::new(|| 0x33)]), + [0x11, 0, 0x33], + "one failed split piece stranded or discarded its sibling results" + ); + } + + #[test] + fn pending_registry_routes_exact_lifetimes_across_independent_shards() { + let registry = Arc::new(PendingRegistry::new()); + let keys: Vec<_> = (0..256).map(|i| 0x7E00_0000usize + i * 0x10).collect(); + let used: std::collections::HashSet<_> = keys.iter().map(|&key| pending_shard_index(key)).collect(); + assert!(used.len() >= PENDING_SHARDS / 2, "sequential aligned handles reached only {} shards", used.len()); + + std::thread::scope(|scope| { + for chunk in keys.chunks(32) { + let registry = registry.clone(); + scope.spawn(move || { + for &key in chunk { + assert_eq!(registry.insert(key, key ^ 0x55AA), None); + assert_eq!(registry.get(key), Some(key ^ 0x55AA)); + assert_eq!(registry.remove(key), Some(key ^ 0x55AA)); + assert_eq!(registry.get(key), None); + } + }); + } + }); + + let reused = 0x7E57_F000usize; + assert_eq!(registry.insert(reused, 1), None); + assert_eq!(registry.insert(reused, 2), Some(1), "replacement did not return the exact old address entry"); + assert_eq!(registry.remove(reused), Some(2)); + assert_eq!(registry.remove(reused), None); + } + + #[test] + fn a_busy_pending_shard_does_not_hold_an_unrelated_lookup() { + let registry = Arc::new(PendingRegistry::new()); + let first = 0x7E10_0000usize; + let second = (first + 0x10..).step_by(0x10).find(|&key| pending_shard_index(key) != pending_shard_index(first)).unwrap(); + registry.insert(second, 7usize); + + let held = registry.shards[pending_shard_index(first)].lock().unwrap(); + let (tx, rx) = mpsc::channel(); + let other = registry.clone(); + let thread = std::thread::spawn(move || tx.send(other.get(second)).unwrap()); + assert_eq!(rx.recv_timeout(std::time::Duration::from_secs(2)), Ok(Some(7))); + drop(held); + thread.join().unwrap(); + } + + #[test] + fn queued_count_state_is_once_only_and_completion_wins_races() { + let state = AtomicU8::new(QUEUE_IDLE); + assert!(mark_queued(&state)); + assert!(!mark_queued(&state)); + assert!(mark_queue_done(&state)); + assert!(!mark_queue_done(&state)); + assert!(!mark_queued(&state)); + + let completed_first = AtomicU8::new(QUEUE_IDLE); + assert!(!mark_queue_done(&completed_first)); + assert!(!mark_queued(&completed_first)); + + let build = Build::new(Box::new(|| 0), false); + build.note_queued(); + assert_eq!(build.queue_state.load(Ordering::Relaxed), QUEUE_IDLE, "auxiliary builds are not reported as title pipelines"); + build.tracked.store(true, Ordering::Release); + build.note_queued(); + assert_eq!(build.queue_state.load(Ordering::Relaxed), QUEUE_ACTIVE); + build.finish_queued(); + assert_eq!(build.queue_state.load(Ordering::Relaxed), QUEUE_DONE); + } + + #[test] + fn demanded_auxiliary_build_runs_on_a_worker() { + let caller = std::thread::current().id(); + assert_eq!(build_foreground(Box::new(move || { + assert_ne!(std::thread::current().id(), caller); + 0x7E57_C0DE + })), 0x7E57_C0DE); + } + + #[test] + fn coalescing_counter_math_tracks_lifetime_current_and_peak() { + let counters = CoalescingCounters::new(); + counters.unique(); + counters.hit(); + counters.unique(); + counters.finished(1); + assert_eq!( + counters.snapshot(), + ComputeCoalescingStats { + keyed_submissions: 3, + coalescing_hits: 1, + unique_keyed_builds: 2, + current_in_flight: 1, + peak_in_flight: 2, + } + ); + counters.finished(1); + assert_eq!(counters.snapshot().current_in_flight, 0); + assert_eq!(counters.snapshot().peak_in_flight, 2); + } + + #[test] + fn retention_age_counts_unique_reals_from_completion_or_last_use() { + let stats = retention_stats_from(1_000, [ + (1, 0x101, 200, 300), + (1, 0x101, 200, 300), // another stand-in sharing build 1 + (2, 0x202, 100, 995), + (3, 0, 0, 0), // failed or incomplete + (4, 0x404, 0, 0), + ]); + assert_eq!(stats, RetentionStats { + retained_reals: 3, + unused_60_frames: 2, + unused_600_frames: 2, + oldest_unused_frames: 1_000, + }); + } + + fn compute_key(tag: u8) -> super::super::real::compute_build_key::ComputeBuildKey { + super::super::real::compute_build_key::ComputeBuildKey::capture( + 1, + &windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC::default(), + [tag].into(), + false, + ) + } + + fn submit_compute(standin: usize, tag: u8, job: Job) { + submit_lazy_keyed(standin, true, job, 0, Some(compute_key(tag))); + } + + #[test] + fn coalesced_compute_owners_retain_the_winning_recipe() { + let standins = [0x7E57_C091usize, 0x7E57_C092]; + let winner = Recipe::new(|| 0xC091); + let duplicate = Recipe::new(|| panic!("duplicate recipe ran")); + submit_recipe_keyed(standins[0], true, winner, false, 0, Some(compute_key(0x91))); + submit_recipe_keyed(standins[1], true, duplicate, false, 0, Some(compute_key(0x91))); + + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build)); + assert_eq!(a.build.recipe.as_ref().unwrap().run(), 0xC091); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0); + } + + #[test] + fn concurrent_equal_compute_submissions_run_one_job() { + let standins = [0x7E57_C101usize, 0x7E57_C102]; + let gate = Arc::new(std::sync::Barrier::new(3)); + let runs = Arc::new(AtomicUsize::new(0)); + let threads: Vec<_> = standins.iter().map(|&standin| { + let (gate, runs) = (gate.clone(), runs.clone()); + std::thread::spawn(move || { + gate.wait(); + submit_compute(standin, 0xC1, Box::new(move || { + runs.fetch_add(1, Ordering::Relaxed); + 0xC101 + })); + }) + }).collect(); + gate.wait(); + for thread in threads { thread.join().unwrap() } + + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build)); + assert_eq!(resolve_wait_for(standins[0], None), 0xC101); + assert_eq!(resolve_wait_for(standins[1], None), 0xC101); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(released(standins[0]), 0, "the shared COM owner stays with the other stand-in"); + assert_eq!(released(standins[1]), 0xC101, "the last stand-in releases the one owned reference"); + } + + #[test] + fn bound_state_follows_the_choice_from_a_shared_build() { + let standins = [0x7E57_C111usize, 0x7E57_C112]; + let drivers = [0x7E57_D111usize, 0x7E57_D112]; + let (started_tx, started_rx) = mpsc::channel(); + let (finish_tx, finish_rx) = mpsc::channel::<()>(); + submit_compute(standins[0], 0xE6, Box::new(move || { + started_tx.send(()).unwrap(); + finish_rx.recv().unwrap(); + 0xC111 + })); + submit_compute(standins[1], 0xE6, Box::new(|| panic!("duplicate shared build ran"))); + for (&standin, &driver) in standins.iter().zip(&drivers) { + shared(standin, driver); + image_only(standin); + } + + let before = standins.map(|standin| resolve_wait_bound_for(standin, None)); + assert_eq!(before, [(drivers[0], true), (drivers[1], true)]); + started_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker did not start the build"); + finish_tx.send(()).unwrap(); + let start = std::time::Instant::now(); + while is_pending(standins[0]) && start.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!is_pending(standins[0]), "shared build did not finish"); + for ((&standin, &driver), &(bound, _)) in standins.iter().zip(&drivers).zip(&before) { + let pending = entry(standin).unwrap(); + assert!(pending.bound_unbuilt(standin, bound), "the earlier driver stand-in stays unbuilt"); + assert_eq!(resolve_wait_bound_for(standin, None), (0xC111, false)); + assert_ne!(driver, 0xC111); + } + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC111); } - /// The keys in a `used-pipelines.txt` (lines that are not a hexadecimal key are passed over). - pub fn parse(text: &str) -> HashSet<u64> { - text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).filter(|&k| k != 0).collect() + #[test] + fn a_failed_builds_permanent_stand_in_is_not_unbuilt() { + let standin = 0x7E57_C121usize; + let driver = 0x7E57_D121usize; + submit_lazy(standin, true, Box::new(|| 0), 0); + shared(standin, driver); + assert_eq!(resolve_wait_bound_for(standin, None), (driver, false)); + assert_eq!(resolve_wait_bound_for(0x7E57_C122, None), (0x7E57_C122, false)); + assert_eq!(released(standin), 0); } - fn get() -> &'static Used { - static U: OnceLock<Used> = OnceLock::new(); - U.get_or_init(|| { - // (a test neither reads nor writes the user's file) - if cfg!(test) { - return Used { earlier: RwLock::new(HashSet::new()), now: Mutex::new((HashSet::new(), None)) }; - } - let path = crate::gpu::recomp::dxc::cache_dir().join("used-pipelines.txt"); - let earlier = parse(&std::fs::read_to_string(&path).unwrap_or_default()); - if !earlier.is_empty() { - crate::xlog_info!("D3D12.X: the pipelines of {} shader sets an earlier run used are built ahead of their first use", earlier.len()); - } - if let Some(dir) = path.parent() { - let _ = std::fs::create_dir_all(dir); - } - let file = std::fs::OpenOptions::new().create(true).append(true).open(&path).ok(); - Used { now: Mutex::new((earlier.clone(), file)), earlier: RwLock::new(earlier) } - }) + #[test] + fn no_budget_wait_runs_a_shared_build_on_a_wanted_worker() { + let standins = [0x7E57_C701usize, 0x7E57_C702]; + let (started_tx, started_rx) = mpsc::channel(); + let (finish_tx, finish_rx) = mpsc::channel::<()>(); + submit_compute(standins[0], 0xC7, Box::new(move || { + started_tx.send((std::thread::current().name().map(str::to_owned), build_is_wanted(), wanted_here()())).unwrap(); + let _ = finish_rx.recv(); + 0xC701 + })); + submit_compute(standins[1], 0xC7, Box::new(|| panic!("duplicate shared build ran"))); + let (a, b) = (entry(standins[0]).unwrap(), entry(standins[1]).unwrap()); + assert!(Arc::ptr_eq(&a.build, &b.build), "equal compute requests share one Build"); + + let (result_tx, result_rx) = mpsc::channel(); + let waiters: Vec<_> = standins.iter().map(|&standin| { + let result_tx = result_tx.clone(); + std::thread::spawn(move || result_tx.send((standin, resolve_wait_for(standin, None))).unwrap()) + }).collect(); + drop(result_tx); + let (thread, wanted, wanted_probe) = started_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker did not start the build"); + assert!(thread.as_deref().is_some_and(|name| name.starts_with("xcl-pso-")), "build ran on caller {thread:?}"); + assert!(wanted && wanted_probe, "the worker did not observe foreground demand"); + assert!(matches!(result_rx.try_recv(), Err(mpsc::TryRecvError::Empty)), "a caller returned before the build finished"); + + finish_tx.send(()).unwrap(); + let mut results: Vec<_> = result_rx.iter().collect(); + results.sort_unstable(); + for waiter in waiters { waiter.join().unwrap(); } + assert_eq!(results, [(standins[0], 0xC701), (standins[1], 0xC701)]); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC701); } - /// An earlier run used a pipeline of these shaders. - pub fn known(key: u64) -> bool { - key != 0 && get().earlier.read().unwrap().contains(&key) + #[test] + fn unequal_compute_keys_keep_separate_builds() { + let standins = [0x7E57_C201usize, 0x7E57_C202]; + submit_compute(standins[0], 0xC2, Box::new(|| 0)); + submit_compute(standins[1], 0xC3, Box::new(|| 0)); + assert!(!Arc::ptr_eq(&entry(standins[0]).unwrap().build, &entry(standins[1]).unwrap().build)); + assert_eq!((released(standins[0]), released(standins[1])), (0, 0)); } - /// A pipeline of these shaders is used now: kept for the next run. - pub fn note(key: u64) { - if key == 0 { - return; + #[test] + fn failed_coalesced_build_wakes_every_waiter() { + let standins = [0x7E57_C301usize, 0x7E57_C302]; + let runs = Arc::new(AtomicUsize::new(0)); + for &standin in &standins { + let runs = runs.clone(); + submit_compute(standin, 0xC4, Box::new(move || { + runs.fetch_add(1, Ordering::Relaxed); + 0 + })); } - let mut g = get().now.lock().unwrap(); - if g.0.insert(key) { - if let Some(f) = g.1.as_mut() { - let _ = writeln!(f, "{key:016x}"); - } + let threads: Vec<_> = standins.iter().map(|&standin| { + std::thread::spawn(move || resolve_wait_for(standin, None)) + }).collect(); + for (thread, standin) in threads.into_iter().zip(standins) { + assert_eq!(thread.join().unwrap(), standin); } + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!((released(standins[0]), released(standins[1])), (0, 0)); } - /// (tests) This run used a pipeline of these shaders. - #[cfg(test)] - pub fn noted(key: u64) -> bool { - get().now.lock().unwrap().0.contains(&key) + #[test] + fn coalesced_preload_is_promoted_once_for_both_pending_owners() { + let standins = [0x7E57_C401usize, 0x7E57_C402]; + submit_compute(standins[0], 0xC5, Box::new(|| 0xC401)); + submit_compute(standins[1], 0xC5, Box::new(|| panic!("duplicate job ran"))); + let build = entry(standins[0]).unwrap().build.clone(); + assert!(Arc::ptr_eq(&build, &entry(standins[1]).unwrap().build)); + let q = BuildQueue::new(); + enqueue_on(&q, &build, Priority::Preload, true); + entry(standins[1]).unwrap().build.promote(Priority::Foreground); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert_eq!(build.real.load(Ordering::Acquire), 0xC401); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC401); } - #[cfg(test)] - pub fn earlier_run_used(key: u64) { - get().earlier.write().unwrap().insert(key); + #[test] + fn submit_demand_is_shared_by_coalesced_stand_ins() { + let standins = [0x7E57_C411usize, 0x7E57_C412]; + let (wanted_tx, wanted_rx) = mpsc::channel(); + let (go_tx, go_rx) = mpsc::channel(); + submit_compute(standins[0], 0xD7, Box::new(move || { + wanted_tx.send(build_is_wanted()).unwrap(); + go_rx.recv().unwrap(); + 0xC411 + })); + submit_compute(standins[1], 0xD7, Box::new(|| panic!("duplicate job ran"))); + let build = entry(standins[0]).unwrap().build.clone(); + assert!(Arc::ptr_eq(&build, &entry(standins[1]).unwrap().build)); + + need_by_submit(standins[1]); + assert!(build.wanted.load(Ordering::Acquire)); + assert!(wanted_rx.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker builds it")); + go_tx.send(()).unwrap(); + assert_eq!(resolve_wait_for(standins[0], None), 0xC411); + assert_eq!(resolve_wait_for(standins[1], None), 0xC411); + assert_eq!(released(standins[0]), 0); + assert_eq!(released(standins[1]), 0xC411); } -} -/// The workers that build the pipelines of an earlier run ahead of their first use -/// (`XCL_PSO_PRELOAD=0`: off). Apart from the ones a bind sends to (`queue`) and at the lowest -/// priority: a pipeline that is bound is not held up by the ones made ahead (whoever takes -/// `job` first builds it), and the title's own threads are not either. -struct Preload { - list: Mutex<std::collections::VecDeque<Arc<Pending>>>, - cv: Condvar, -} + #[test] + fn releasing_one_waiter_does_not_orphan_shared_build() { + let standins = [0x7E57_C501usize, 0x7E57_C502]; + let runs = Arc::new(AtomicUsize::new(0)); + let count = runs.clone(); + submit_compute(standins[0], 0xC6, Box::new(move || { + count.fetch_add(1, Ordering::Relaxed); + 0xC501 + })); + submit_compute(standins[1], 0xC6, Box::new(|| panic!("duplicate job ran"))); + let build = entry(standins[1]).unwrap().build.clone(); + assert_eq!(released(standins[0]), 0); + assert!(!build.orphan.load(Ordering::Acquire)); + assert!(build.job.lock().unwrap().is_some()); + assert_eq!(resolve_wait_for(standins[1], None), 0xC501); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(released(standins[1]), 0xC501); + } -fn preload() -> Option<&'static Preload> { - static Q: OnceLock<Option<Preload>> = OnceLock::new(); - static STARTED: std::sync::Once = std::sync::Once::new(); - let q = Q - .get_or_init(|| { - if std::env::var("XCL_PSO_PRELOAD").is_ok_and(|v| v.trim() == "0") { - return None; + #[test] + fn build_completion_reaches_all_owners() { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let waiter_build = build.clone(); + assert!(Arc::ptr_eq(&build, &waiter_build)); + let waiter = std::thread::spawn(move || { + let mut done = waiter_build.done.lock().unwrap(); + while !*done { + done = waiter_build.cv.wait(done).unwrap(); } - Some(Preload { list: Mutex::new(Default::default()), cv: Condvar::new() }) - }) - .as_ref()?; - STARTED.call_once(|| { - let n = (crate::gpu::recomp::dxc::compile_threads() / 4).clamp(2, 4); - for k in 0..n { - let _ = std::thread::Builder::new().name(format!("xcl-pso-pre-{k}")).stack_size(64 << 20).spawn(move || { - unsafe { - use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_LOWEST}; - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST); - } - static DONE: AtomicUsize = AtomicUsize::new(0); - loop { - let p = { - let mut g = q.list.lock().unwrap(); - loop { - if let Some(p) = g.pop_front() { - break p; - } - g = q.cv.wait(g).unwrap(); - } - }; - // (released by the title meanwhile) - if p.orphan.load(Ordering::Acquire) { - drop_unstarted_job(&p); - continue; - } - // (None: a bind took it and builds it itself) - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - build(&p, job, true); - let n = DONE.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} pipelines built ahead of their first use"); - } - } - } - }); - } - }); - Some(q) -} + waiter_build.real.load(Ordering::Acquire) + }); -#[cfg(test)] -mod used_tests { - use super::*; + complete(&build, 0xB017_D001); + assert_eq!(waiter.join().unwrap(), 0xB017_D001); + assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D001); + } + + #[test] + fn wanted_preload_moves_to_foreground_and_builds_once() { + let q = BuildQueue::new(); + let runs = Arc::new(AtomicUsize::new(0)); + let count = runs.clone(); + let build = Arc::new(Build::new(Box::new(move || { + count.fetch_add(1, Ordering::Relaxed); + 0xB017_D002 + }), true)); + enqueue_on(&q, &build, Priority::Preload, true); + + build.want(); + assert!(!q.try_run_one_between(Priority::Speculative, Priority::Preload)); + assert!(q.try_run_one_between(Priority::BoundSoon, Priority::Foreground)); + assert!(!q.try_run_one()); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D002); + } + + #[test] + fn caller_can_steal_a_queued_build_without_running_it_twice() { + let q = BuildQueue::new(); + let runs = Arc::new(AtomicUsize::new(0)); + let count = runs.clone(); + let build = Arc::new(Build::new(Box::new(move || { + count.fetch_add(1, Ordering::Relaxed); + 0xB017_D003 + }), true)); + enqueue_on(&q, &build, Priority::BoundSoon, false); + + let job = build.job.lock().unwrap().take().unwrap(); + build.cancel_queued(); + complete(&build, job()); + assert!(!q.try_run_one()); + assert_eq!(runs.load(Ordering::Relaxed), 1); + assert_eq!(build.real.swap(0, Ordering::AcqRel), 0xB017_D003); + } /// A PC call that has kept one of the title's threads for long holds the title, a short one /// does not, and the hold ends with the call. @@ -713,6 +6153,37 @@ mod used_tests { } } + #[test] + fn a_build_a_submit_needs_is_wanted_from_record_time() { + let standin = 0x7E57_B006usize; + let (started_tx, started) = mpsc::channel(); + submit(standin, true, Box::new(move || { + started_tx.send(()).unwrap(); + let t = std::time::Instant::now(); + while !build_is_wanted() && t.elapsed() < std::time::Duration::from_secs(10) { + std::thread::sleep(std::time::Duration::from_millis(1)); + } + if build_is_wanted() { 0x5757 } else { 0 } + })); + started.recv_timeout(std::time::Duration::from_secs(10)).expect("a worker did not start the build"); + need_by_submit(standin); + assert_eq!(resolve_wait_for(standin, None), 0x5757, "record-time demand did not reach the running build"); + assert_eq!(released(standin), 0x5757); + } + + #[test] + fn binding_a_completed_compute_pipeline_neither_relooks_it_up_nor_requests_work() { + let standin = 0x7E57_B00Ausize; + submit(standin, true, Box::new(|| 0x5455)); + let p = entry(standin).unwrap(); + drop(p.build.cv.wait_while(p.build.done.lock().unwrap(), |done| !*done).unwrap()); + + assert_eq!(resolve_for_bind(standin), 0x5455); + assert_eq!(resolve_wait_for(standin, None), 0x5455); + assert!(!p.build.wanted.load(Ordering::Acquire)); + assert_eq!(released(standin), 0x5455); + } + /// A bind waits for a pipeline still being built no longer than its budget and goes on with /// the stand-in; later binds do not wait for it again; once built it is the real one. #[test] @@ -737,6 +6208,26 @@ mod used_tests { let _ = released(standin); } + /// DXC admission probes demand while holding its own queue lock: submit demand is published + /// through the atomic wanted signal, so the probe cannot take this build's demand lock. + #[test] + fn submit_demand_wanted_probe_is_lock_free() { + let build = Arc::new(Build::new(Box::new(|| 0), false)); + let before = BUILDING.with(|building| building.replace(Some(build.clone()))); + let _restore = RestoreBuilding(before); + let wanted = wanted_here(); + build.demand.lock().unwrap().by_submit = true; + build.want(); + assert!(wanted(), "submit demand reaches DXC and driver admission"); + + let demand = build.demand.lock().unwrap(); + let (tx, rx) = mpsc::channel(); + let thread = std::thread::spawn(move || tx.send(wanted()).unwrap()); + assert!(rx.recv_timeout(std::time::Duration::from_secs(2)).expect("wanted probe took the demand lock")); + drop(demand); + thread.join().unwrap(); + } + /// A compile a worker's build starts is wanted once a bind waits for the build – asked from /// another thread, as the DXC workers do; a thread that builds nothing (no title runs here) /// wants nothing. @@ -787,6 +6278,15 @@ mod used_tests { assert!(keys.contains(&0xff) && keys.contains(&0x1a2b)); } + #[test] + fn used_file_ranks_follow_unique_valid_first_occurrences() { + let ranks = used::parse_ranked("10\nnot a key\n10\n0\n 20 \ninvalid\n30\n20\n"); + assert_eq!(ranks.len(), 3); + assert_eq!(ranks.get(&0x10), Some(&0)); + assert_eq!(ranks.get(&0x20), Some(&1)); + assert_eq!(ranks.get(&0x30), Some(&2)); + } + /// A lazy pipeline of shaders an earlier run used is built without a bind; another one is /// built only at its first use, and that use is kept for the next run. #[test] @@ -812,6 +6312,58 @@ mod used_tests { static WORKER_SATURATION_LOCK: Mutex<()> = Mutex::new(()); + /// Normal workers parked at the huge-driver-compile gate leave their priority band live, and + /// the bounded replacement workers retire after the gate opens. + #[test] + fn parked_normal_workers_leave_the_queue_to_bounded_helpers() { + let _sat = WORKER_SATURATION_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use std::time::{Duration, Instant}; + + struct OpenGate(Arc<(Mutex<bool>, Condvar)>); + impl Drop for OpenGate { + fn drop(&mut self) { + *self.0 .0.lock().unwrap() = true; + self.0 .1.notify_all(); + } + } + + let outside = parked_for_big_compile(); + assert!(!outside.0, "a title/test thread must not start a replacement"); + drop(outside); + + start_normal_workers(); + let n = crate::gpu::recomp::dxc::compile_threads(); + let (started_tx, started_rx) = mpsc::channel(); + let gate = Arc::new((Mutex::new(false), Condvar::new())); + let open = OpenGate(gate.clone()); + for _ in 0..n { + let (tx, gate) = (started_tx.clone(), gate.clone()); + queue().submit(Priority::Foreground, Box::new(move || { + let _parked = parked_for_big_compile(); + tx.send(()).unwrap(); + let mut open = gate.0.lock().unwrap(); + while !*open { + open = gate.1.wait(open).unwrap(); + } + })).unwrap(); + } + for _ in 0..n { + started_rx.recv_timeout(Duration::from_secs(10)).expect("every blocker parked"); + } + assert!(NORMAL_HELPERS.load(Ordering::Acquire) <= n, "replacement count is bounded by the normal pool"); + let (ran_tx, ran_rx) = mpsc::channel(); + queue().submit(Priority::Foreground, Box::new(move || ran_tx.send(()).unwrap())).unwrap(); + ran_rx.recv_timeout(Duration::from_secs(10)).expect("a replacement served the queue"); + drop(open); + + let deadline = Instant::now() + Duration::from_secs(10); + while (PARKED_NORMAL.load(Ordering::Acquire) != 0 || NORMAL_HELPERS.load(Ordering::Acquire) != 0) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + assert_eq!(PARKED_NORMAL.load(Ordering::Acquire), 0); + assert_eq!(NORMAL_HELPERS.load(Ordering::Acquire), 0, "replacement workers retired"); + } + /// A queued normal worker job whose stand-in was released before a worker starts it is /// skipped as orphaned instead of entering the compiler. #[test] @@ -1025,7 +6577,7 @@ mod used_tests { } fn entry(pso: usize) -> Option<Arc<Pending>> { - PENDING.lock().unwrap().as_ref()?.get(&pso).cloned() + PENDING.get(pso) } impl Pending { @@ -1036,6 +6588,13 @@ impl Pending { d => d, } } + + /// `bound` was this pending pipeline's stand-in before its build finished successfully. + /// A failed build keeps its stand-in permanently, so that is a finished pipeline choice. + fn bound_unbuilt(&self, pso: usize, bound: usize) -> bool { + let done = self.build.done.lock().unwrap(); + bound == self.stand(pso) && !(*done && self.build.real.load(Ordering::Acquire) == 0) + } } /// Stand-in `standin` is no driver object (`standin::shell`): binds get `driver` in its place. @@ -1050,81 +6609,111 @@ pub fn shared(standin: usize, driver: usize) { /// pipeline (`pso` itself when it is one). pub fn resolve(pso: usize) -> usize { let Some(p) = entry(pso) else { return pso }; + resolve_pending(&p, pso) +} + +fn resolve_pending(p: &Pending, pso: usize) -> usize { p.note_use(); - match p.real.load(Ordering::Acquire) { + match p.build.real.load(Ordering::Acquire) { 0 => { // a lazy one is wanted now: to the workers let stand = p.stand(pso); - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p); - } + schedule(&p.build, Priority::BoundSoon, false, None); + p.build.promote(Priority::Foreground); stand } r => r, } } -/// `resolve`, waiting for a pipeline still being built – built here if no worker has started -/// it yet (a queue of a title's hundreds of pipelines must not hold up the one it binds now). +/// `resolve`, waiting for a pipeline still being built on a foreground worker. pub fn resolve_wait(pso: usize) -> usize { resolve_wait_for(pso, wait_budget()) } +/// The pipeline to bind and whether that exact choice was a stand-in for an unfinished build. +/// The answer stays true if a successful build ends after this bind chose its stand-in. +pub fn resolve_wait_bound(pso: usize) -> (usize, bool) { + resolve_wait_bound_for(pso, wait_budget()) +} + /// `resolve_wait`, waiting at most `budget` (None: until the pipeline is built). fn resolve_wait_for(pso: usize, budget: Option<std::time::Duration>) -> usize { let Some(p) = entry(pso) else { return pso }; p.note_use(); - if p.spared.load(Ordering::Acquire) { - return resolve_spared(&p, pso); - } - // (the title's thread is held from here until the pipeline is built or the budget is over) - let _held = (!*p.done.lock().unwrap()).then(Held::new); - if let Some(budget) = budget { - return resolve_within(&p, pso, budget); - } - let job = p.job.lock().unwrap().take(); - if let Some(job) = job { - complete(&p, job()); - } - p.want(); - let mut done = p.done.lock().unwrap(); - while !*done { - done = p.cv.wait(done).unwrap(); - } - match p.real.load(Ordering::Acquire) { - 0 => p.stand(pso), - r => r, + resolve_wait_pending(&p, pso, budget) +} + +fn resolve_wait_bound_for(pso: usize, budget: Option<std::time::Duration>) -> (usize, bool) { + let Some(p) = entry(pso) else { return (pso, false) }; + p.note_use(); + let bound = resolve_wait_pending(&p, pso, budget); + (bound, p.bound_unbuilt(pso, bound)) +} + +fn resolve_wait_pending(p: &Arc<Pending>, pso: usize, budget: Option<std::time::Duration>) -> usize { + if let real @ 1.. = p.build.real.load(Ordering::Acquire) { + return real; } + let bound = if p.spared.load(Ordering::Acquire) { + resolve_spared(p, pso) + } else { + // (the title's thread is held from here until the pipeline is built or the budget is over) + let waiting = !*p.build.done.lock().unwrap(); + let _held = waiting.then(Held::new); + let _stall = waiting.then(|| crate::stall::span(crate::stall::StallKind::PipelineWait)).flatten(); + if let Some(budget) = budget { + resolve_within(p, pso, budget) + } else { + // Mark it wanted before an unsent build is queued: the worker and its DXC/driver + // admission see demand from their first instruction. An already queued build is + // promoted by `want`. + p.build.want(); + schedule(&p.build, Priority::Foreground, false, None); + let mut done = p.build.done.lock().unwrap(); + while !*done { + done = p.build.cv.wait(done).unwrap(); + } + match p.build.real.load(Ordering::Acquire) { + 0 => p.stand(pso), + r => r, + } + } + }; + bound } /// How long a bind waits for a pipeline still being built (`XCL_PSO_WAIT_MS`; unset or 0: until -/// it is built). A retail game builds compute programs on its own threads: the driver takes up to -/// 30 s for the biggest translated ones, and the title's watchdog ends it when its main thread -/// has been held 30 s. +/// it is built). A retail game's foreground worker can spend over 30 s in the driver on the +/// biggest translated programs; the waiting title thread remains held for that time. fn wait_budget() -> Option<std::time::Duration> { static B: OnceLock<Option<std::time::Duration>> = OnceLock::new(); *B.get_or_init(|| std::env::var("XCL_PSO_WAIT_MS").ok().and_then(|v| v.trim().parse::<u64>().ok()).filter(|&ms| ms > 0).map(std::time::Duration::from_millis)) } +/// Whether binds have an explicit time bound. A dispatch is then recorded immediately instead of +/// deferred to the submit, where it would only wait for the same bound. +pub(super) fn waits_bounded() -> bool { + wait_budget().is_some() +} + /// `resolve_wait` for at most `budget`: the build goes to the workers (not this thread), and a /// pipeline not built by then is `late` – it and later binds of it get the stand-in (their /// dispatches are skipped) until a worker has built it. fn resolve_within(p: &Arc<Pending>, pso: usize, budget: std::time::Duration) -> usize { - let built = |p: &Pending| match p.real.load(Ordering::Acquire) { + let built = |p: &Pending| match p.build.real.load(Ordering::Acquire) { 0 => p.stand(pso), r => r, }; - if *p.done.lock().unwrap() { + if *p.build.done.lock().unwrap() { return built(p); } - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p.clone()); - } + schedule(&p.build, Priority::BoundSoon, false, None); if p.late.load(Ordering::Acquire) { return p.stand(pso); } - p.want(); - let (done, _) = p.cv.wait_timeout_while(p.done.lock().unwrap(), budget, |d| !*d).unwrap(); + p.build.want(); + let (done, _) = p.build.cv.wait_timeout_while(p.build.done.lock().unwrap(), budget, |d| !*d).unwrap(); if *done { return built(p); } @@ -1163,12 +6752,10 @@ pub fn image_only(standin: usize) { /// else the stand-in, with the build sent to the workers. Nobody waits, so the build is not /// `wanted`: a big one takes its turn among the driver's compiles and waits for free commit. fn resolve_spared(p: &Arc<Pending>, pso: usize) -> usize { - match p.real.load(Ordering::Acquire) { + match p.build.real.load(Ordering::Acquire) { 0 => { - if !p.sent.swap(true, Ordering::AcqRel) { - enqueue(p.clone()); - } - if !*p.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { + schedule(&p.build, Priority::BoundSoon, false, None); + if !*p.build.done.lock().unwrap() && !p.late.swap(true, Ordering::AcqRel) { static N: AtomicUsize = AtomicUsize::new(0); let n = N.fetch_add(1, Ordering::Relaxed); if n < 16 || n.is_power_of_two() { @@ -1184,52 +6771,431 @@ fn resolve_spared(p: &Arc<Pending>, pso: usize) -> usize { /// For binding: compute pipelines are waited for, graphics ones are not. pub fn resolve_for_bind(pso: usize) -> usize { match entry(pso) { - Some(p) if p.compute => resolve_wait(pso), - Some(_) => resolve(pso), + Some(p) if p.compute => { + p.note_use(); + resolve_wait_pending(&p, pso, wait_budget()) + } + Some(p) => resolve_pending(&p, pso), None => pso, } } +/// Resolve and strongly pin the exact recipe-backed native generation as one operation. The +/// generation is chosen while holding `Build.done`, the same lock that publishes it and that +/// `released` uses before giving up the original raw owner. Ordinary one-shot builds keep their +/// existing resolution path and return no generation pin. +pub(super) fn resolve_and_pin_for_bind(pso: usize) -> (usize, Option<NativeGeneration>) { + resolve_and_pin_mode(pso, ResolveMode::ForBind) +} + +#[derive(Clone, Copy)] +enum ResolveMode { Lazy, Wait, ForBind } + +/// One retained resolver decision. This is private and unwired: a later list integration can +/// classify without waiting, retain the original `Pending` across title-address reuse, and wait +/// only when correctness-critical emission consumes an exact restoration ticket. +#[allow(dead_code)] +#[derive(Clone)] +enum StructuredResolve<const R: usize> { + Ready { + original: usize, + raw: usize, + pin: Option<NativeGeneration>, + }, + Initial { + original: usize, + pending: Arc<Pending>, + fallback: usize, + bound_unbuilt: bool, + }, + Restoring { + original: usize, + pending: Arc<Pending>, + fallback: usize, + ticket: RestorationTicket<R>, + }, + Terminal { + original: usize, + pending: Arc<Pending>, + fallback: usize, + failure: StructuredResolveFailure, + }, +} + +const PIPELINE_RESTORATION_EVICTIONS: usize = 1024; +const PIPELINE_RESOLUTION_RECEIPTS: usize = 1024; +type PipelineRestorationCoordinator = + RestorationCoordinator<PIPELINE_RESTORATION_EVICTIONS, PIPELINE_RESOLUTION_RECEIPTS>; + +/// One dormant coordinator identity for the later live classification stage. Merely obtaining it +/// neither starts workers nor enables eviction; no production caller classifies through it yet. +fn pipeline_restoration_coordinator() -> &'static PipelineRestorationCoordinator { + static COORDINATOR: OnceLock<PipelineRestorationCoordinator> = OnceLock::new(); + COORDINATOR.get_or_init(|| { + PipelineRestorationCoordinator::new(1).expect("nonzero pipeline restoration capacities") + }) +} + +/// Opaque retained resolver decision carried by command-list state. Live callers do not make +/// these yet; the later classification stage supplies them without exposing coordinator types. +#[allow(dead_code)] +#[derive(Clone)] +pub(super) struct PipelineResolution(StructuredResolve<PIPELINE_RESOLUTION_RECEIPTS>); + +/// Wrap one nonblocking decision without exposing coordinator or receipt types to command-list +/// state. This does not start workers and never runs a queued driver build on the caller. +fn begin_pipeline_resolution_on<const E: usize>( + original: usize, + pending: &Arc<Pending>, + coordinator: &RestorationCoordinator<E, PIPELINE_RESOLUTION_RECEIPTS>, + q: &BuildQueue, +) -> PipelineResolution { + PipelineResolution(classify_structured_on(original, pending, coordinator, q)) +} + +/// Dormant live-queue seam for the later bind integration. There are intentionally no production +/// callers yet; worker startup, state installation, and emission waits remain separate stages. +#[allow(dead_code)] +fn begin_pipeline_resolution(original: usize) -> Option<PipelineResolution> { + let pending = entry(original)?; + Some(begin_pipeline_resolution_on( + original, + &pending, + pipeline_restoration_coordinator(), + queue(), + )) +} + +#[cfg(test)] +struct PipelineResolutionDropProbe(Option<Box<dyn FnOnce() + Send>>); + +#[cfg(test)] +impl Drop for PipelineResolutionDropProbe { + fn drop(&mut self) { + if let Some(on_drop) = self.0.take() { + on_drop(); + } + } +} + +#[cfg(test)] +pub(super) fn pipeline_resolution_for_test( + original: usize, + on_drop: impl FnOnce() + Send + 'static, +) -> PipelineResolution { + let probe = PipelineResolutionDropProbe(Some(Box::new(on_drop))); + let build = Arc::new(Build::new(Box::new(move || { + let _keep = &probe; + 0 + }), false)); + let pending = Arc::new(Pending { + build, + driver: AtomicUsize::new(0), + compute: false, + key: 0, + used: AtomicBool::new(false), + late: AtomicBool::new(false), + spared: AtomicBool::new(false), + }); + PipelineResolution(StructuredResolve::Initial { + original, + pending, + fallback: original, + bound_unbuilt: true, + }) +} + +#[cfg(test)] +impl PipelineResolution { + pub(super) fn identity_for_test(&self) -> (usize, usize) { + match &self.0 { + StructuredResolve::Initial { original, pending, .. } + | StructuredResolve::Restoring { original, pending, .. } + | StructuredResolve::Terminal { original, pending, .. } => { + (*original, Arc::as_ptr(pending) as usize) + } + StructuredResolve::Ready { original, .. } => (*original, 0), + } + } +} + +#[allow(dead_code)] +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum StructuredResolveFailure { + MissingEvictionRecord, + RestorationUnavailable, + Refused, + Cancelled, + Panicked, + BuildFailed, + Released, +} + +#[allow(dead_code)] +struct StructuredResolvedPipeline { + raw: usize, + pin: Option<NativeGeneration>, + bound_unbuilt: bool, +} + +#[allow(dead_code)] +impl<const R: usize> StructuredResolve<R> { + /// Never waits. An initial build or restoration returns only the retained Pending's fallback. + fn nonblocking(&self) -> StructuredResolvedPipeline { + match self { + Self::Ready { raw, pin, .. } => StructuredResolvedPipeline { + raw: *raw, pin: pin.clone(), bound_unbuilt: false, + }, + Self::Initial { fallback, bound_unbuilt, .. } => StructuredResolvedPipeline { + raw: *fallback, pin: None, bound_unbuilt: *bound_unbuilt, + }, + Self::Restoring { fallback, .. } | Self::Terminal { fallback, .. } => { + StructuredResolvedPipeline { raw: *fallback, pin: None, bound_unbuilt: true } + } + } + } + + /// Wait only for an already-classified exact restoration. Initial cold-build policy remains + /// with the existing resolver until the later call-site integration stage. + fn wait_exact(&self) -> Result<Option<StructuredResolvedPipeline>, StructuredResolveFailure> { + match self { + Self::Ready { raw, pin, .. } => Ok(Some(StructuredResolvedPipeline { + raw: *raw, pin: pin.clone(), bound_unbuilt: false, + })), + Self::Initial { .. } => Ok(None), + Self::Restoring { ticket, .. } => ticket.wait_and_take_pin() + .map(|pin| Some(StructuredResolvedPipeline { raw: pin.raw(), pin: Some(pin), bound_unbuilt: false })) + .map_err(StructuredResolveFailure::from), + Self::Terminal { failure, .. } => Err(*failure), + } + } +} + +impl From<RehydrateCompletion> for StructuredResolveFailure { + fn from(completion: RehydrateCompletion) -> Self { + match completion { + RehydrateCompletion::Refused => Self::Refused, + RehydrateCompletion::Cancelled => Self::Cancelled, + RehydrateCompletion::Panicked => Self::Panicked, + RehydrateCompletion::BuildFailed => Self::BuildFailed, + RehydrateCompletion::Released => Self::Released, + RehydrateCompletion::Reserved | RehydrateCompletion::Queued + | RehydrateCompletion::Succeeded { .. } => Self::RestorationUnavailable, + } + } +} + +/// Classify one retained Pending without running driver work or waiting. The caller supplies the +/// private coordinator and queue so this foundation neither creates a live policy singleton nor +/// starts workers. No Build, recipe, registry, coordinator, or queue lock overlaps submission. +#[allow(dead_code)] +fn classify_structured_on<const E: usize, const R: usize>( + original: usize, + pending: &Arc<Pending>, + coordinator: &RestorationCoordinator<E, R>, + q: &BuildQueue, +) -> StructuredResolve<R> { + enum Snapshot { + Ready(usize, Option<NativeGeneration>), + Initial(usize, bool), + Restore(usize), + } + let snapshot = || { + let done = pending.build.done.lock().unwrap(); + let raw = pending.build.real.load(Ordering::Acquire); + let fallback = pending.stand(original); + if !*done { + return Snapshot::Initial(fallback, true); + } + let Some(recipe) = pending.build.recipe.as_ref() else { + // A one-shot Build has no independent native pin. Leave its current resolution to + // the existing resolver instead of carrying an ownerless raw pointer across release. + return Snapshot::Initial(fallback, false); + }; + let (pin, residency) = recipe.pin_with_residency(raw); + match (pin, residency) { + // A speculative replacement may mark the recipe Rebuilding while the old exact + // resident generation remains published and fully usable. + (Some(pin), Residency::Resident | Residency::Rebuilding) => Snapshot::Ready(raw, Some(pin)), + (None, Residency::Evicted | Residency::Rebuilding) => Snapshot::Restore(fallback), + (None, Residency::Failed) => Snapshot::Initial(fallback, false), + _ => Snapshot::Restore(fallback), + } + }; + let fallback = match snapshot() { + Snapshot::Ready(raw, pin) => return StructuredResolve::Ready { original, raw, pin }, + Snapshot::Initial(fallback, bound_unbuilt) => return StructuredResolve::Initial { + original, pending: pending.clone(), fallback, bound_unbuilt, + }, + Snapshot::Restore(fallback) => fallback, + }; + let Some(evicted) = pending.build.eviction_token() else { + // Terminal reconciliation clears the token after publication. Reclassify once so that + // race returns the new exact resident pin instead of a false missing-record failure. + return match snapshot() { + Snapshot::Ready(raw, pin) => StructuredResolve::Ready { original, raw, pin }, + Snapshot::Initial(fallback, bound_unbuilt) => StructuredResolve::Initial { + original, pending: pending.clone(), fallback, bound_unbuilt, + }, + Snapshot::Restore(fallback) => StructuredResolve::Terminal { + original, pending: pending.clone(), fallback, + failure: StructuredResolveFailure::MissingEvictionRecord, + }, + }; + }; + #[cfg(test)] + let before_request = coordinator.before_classified_request.lock().unwrap().take(); + #[cfg(test)] + if let Some(before_request) = before_request { + before_request(); + } + let requested = coordinator.request_exact_on(&evicted, RehydratePriority::Foreground, q); + // Success may publish and reconcile after the token snapshot but before this request. Its + // exact current pin wins over the stale request's Cancelled terminal state. + if let Snapshot::Ready(raw, pin) = snapshot() { + return StructuredResolve::Ready { original, raw, pin }; + } + match requested { + Some(ticket) => StructuredResolve::Restoring { + original, pending: pending.clone(), fallback, ticket, + }, + None => StructuredResolve::Terminal { + original, pending: pending.clone(), fallback, + failure: StructuredResolveFailure::RestorationUnavailable, + }, + } +} + +fn resolve_and_pin_mode(pso: usize, mode: ResolveMode) -> (usize, Option<NativeGeneration>) { + let Some(p) = entry(pso) else { return (pso, None) }; + resolve_and_pin_pending(pso, &p, mode) +} + +fn resolve_and_pin_pending(pso: usize, p: &Arc<Pending>, mode: ResolveMode) -> (usize, Option<NativeGeneration>) { + // Resolve directly against this retained Pending: a concurrent release/address reuse cannot + // make selection consult a new registry entry while validation still uses the old recipe. + let resolved = match mode { + ResolveMode::Lazy => resolve_pending(p, pso), + ResolveMode::Wait => { + p.note_use(); + resolve_wait_pending(p, pso, wait_budget()) + } + ResolveMode::ForBind if p.compute => { + p.note_use(); + resolve_wait_pending(p, pso, wait_budget()) + } + ResolveMode::ForBind => resolve_pending(p, pso), + }; + let bound_unbuilt = p.bound_unbuilt(pso, resolved); + let (resolved, generation, _) = pin_resolved(pso, p, resolved, bound_unbuilt); + (resolved, generation) +} + +fn pin_resolved(pso: usize, p: &Pending, resolved: usize, bound_unbuilt: bool) -> (usize, Option<NativeGeneration>, bool) { + let Some(recipe) = p.build.recipe.as_ref() else { return (resolved, None, false) }; + note_eviction_candidate(&p.build); + let _done = p.build.done.lock().unwrap(); + let current = p.build.real.load(Ordering::Acquire); + if current == resolved { + let (generation, residency) = recipe.pin_with_residency(resolved); + let unavailable = generation.is_none() && matches!(residency, Residency::Evicted | Residency::Rebuilding); + return (resolved, generation, unavailable); + } + // Preserve a resolver's deliberate stand-in choice. If an eventual rebuild replaced a + // native generation between resolution and this lock, select and pin the current publication. + // Eviction can instead leave no publication: fail closed to the retained stand-in, never the + // ownerless raw pointer which resolution observed before it took this lock. + if bound_unbuilt { + return (resolved, None, false); + } + let (generation, residency) = recipe.pin_with_residency(current); + match generation { + Some(generation) => (current, Some(generation), false), + None => { + let stand = p.stand(pso); + let unavailable = resolved != stand || matches!(residency, Residency::Evicted | Residency::Rebuilding); + (stand, None, unavailable) + } + } +} + +/// Preserve the ordinary resolver exactly unless recipe rebuilding was explicitly enabled. +pub(super) fn resolve_and_pin_if_enabled(pso: usize) -> (usize, Option<NativeGeneration>) { + if rebuild_recipes_enabled() { resolve_and_pin_for_bind(pso) } else { (resolve_for_bind(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_lazy(pso: usize) -> (usize, Option<NativeGeneration>) { + if rebuild_recipes_enabled() { resolve_and_pin_mode(pso, ResolveMode::Lazy) } else { (resolve(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_wait(pso: usize) -> (usize, Option<NativeGeneration>) { + if rebuild_recipes_enabled() { resolve_and_pin_mode(pso, ResolveMode::Wait) } else { (resolve_wait(pso), None) } +} + +pub(super) fn resolve_and_pin_if_enabled_identity(pso: usize) -> (usize, Option<NativeGeneration>) { + (pso, None) +} + +pub(super) fn resolve_wait_bound_and_pin_if_enabled(pso: usize) -> ((usize, bool), Option<NativeGeneration>) { + if !rebuild_recipes_enabled() { + return (resolve_wait_bound(pso), None); + } + resolve_wait_bound_and_pin(pso) +} + +fn resolve_wait_bound_and_pin(pso: usize) -> ((usize, bool), Option<NativeGeneration>) { + let Some(p) = entry(pso) else { return ((pso, false), None) }; + p.note_use(); + let bound = resolve_wait_pending(&p, pso, wait_budget()); + let choice = (bound, p.bound_unbuilt(pso, bound)); + let (resolved, generation, stale_fallback) = pin_resolved(pso, &p, choice.0, choice.1); + ((resolved, choice.1 || stale_fallback), generation) +} + /// The title released stand-in `pso` for good: forget it (its address may come back for -/// another object) and return its real pipeline to release (0: none, or still being built – -/// the worker's result is then released when it arrives). +/// another object) and return its real pipeline to release when this is its last owner +/// (0: another `Pending` owns the build, none, or still being built – the worker's result is +/// then released when its last owner is gone). pub fn released(pso: usize) -> usize { - let Some(p) = PENDING.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)) else { return 0 }; + let Some(p) = PENDING.remove(pso) else { return 0 }; + let mut orphaned = false; { - let done = p.done.lock().unwrap(); + let done = p.build.done.lock().unwrap(); + let owners = p.build.owners.fetch_sub(1, Ordering::Relaxed) - 1; if *done { - return p.real.swap(0, Ordering::AcqRel); + return if owners == 0 { p.build.real.swap(0, Ordering::AcqRel) } else { 0 }; + } + if owners == 0 { + // the worker stores its result into a Build nobody will read: mark it orphaned + p.build.orphan.store(true, Ordering::Release); + p.build.finish_queued(); + orphaned = true; } - // the worker stores its result into a Pending nobody will read: mark it orphaned - p.orphan.store(true, Ordering::Release); } - drop_unstarted_job(&p); + if orphaned { + forget_in_flight(&p.build); + drop_unstarted_job(&p.build); + } 0 } /// `pso` is a stand-in whose real pipeline is still being built. pub fn is_pending(pso: usize) -> bool { - entry(pso).is_some_and(|p| !*p.done.lock().unwrap()) -} - -/// One of the title's threads is about to wait for `pso`. -pub fn want(pso: usize) { - if let Some(p) = entry(pso) { - p.want(); - } + entry(pso).is_some_and(|p| !*p.build.done.lock().unwrap()) } -/// A call with `pso` was put off to the submit: its build goes before the workers' queue. +/// A call with `pso` was put off to the submit, which will wait for it: its shared build is +/// wanted from record time and goes before the workers' queue. pub fn need_by_submit(pso: usize) { let Some(p) = entry(pso) else { return }; - if !std::mem::replace(&mut p.demand.lock().unwrap().by_submit, true) { - NEEDED.lock().unwrap().push_back(p); - let _ = queue().lock().unwrap().send(Box::new(|| ())); + p.build.want(); + let first = !std::mem::replace(&mut p.build.demand.lock().unwrap().by_submit, true); + if first { + schedule(&p.build, Priority::BoundSoon, false, None); } } /// (built in the background, failed, still building) pub fn counts() -> (usize, usize, usize) { - let pending = PENDING.lock().unwrap().as_ref().map_or(0, |m| m.values().filter(|p| !*p.done.lock().unwrap()).count()); - (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), pending) + (BUILT.load(Ordering::Relaxed), FAILED.load(Ordering::Relaxed), QUEUED_BUILDS.load(Ordering::Relaxed)) } diff --git a/crates/xcl/src/hle/d3d12x/queue_submit.rs b/crates/xcl/src/hle/d3d12x/queue_submit.rs new file mode 100644 index 0000000000..060160a828 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/queue_submit.rs @@ -0,0 +1,226 @@ +//! Per-command-queue ordering for title and XCL submissions. +//! +//! XCL sometimes issues setup work from inside a title queue call. The lease is therefore +//! re-entrant on one thread, but excludes another thread until the whole ordered operation ends. + +use std::collections::HashMap; +use std::sync::{Arc, Condvar, Mutex, OnceLock, RwLock}; +use std::thread::ThreadId; + +#[derive(Default)] +struct State { + owner: Option<ThreadId>, + depth: usize, + #[cfg(test)] + waiters: usize, +} + +#[derive(Default)] +struct Lease { + state: Mutex<State>, + changed: Condvar, +} + +impl Lease { + fn enter(self: &Arc<Self>) -> Guard { + let me = std::thread::current().id(); + let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner()); + let _stall = state.owner.is_some_and(|owner| owner != me) + .then(|| crate::stall::span(crate::stall::StallKind::LockContention)) + .flatten(); + while state.owner.is_some_and(|owner| owner != me) { + #[cfg(test)] + { + state.waiters += 1; + } + state = self.changed.wait(state).unwrap_or_else(|e| e.into_inner()); + #[cfg(test)] + { + state.waiters -= 1; + } + } + state.owner = Some(me); + state.depth += 1; + drop(state); + Guard(Arc::clone(self)) + } +} + +struct Guard(Arc<Lease>); + +impl Drop for Guard { + fn drop(&mut self) { + let mut state = self.0.state.lock().unwrap_or_else(|e| e.into_inner()); + debug_assert_eq!(state.owner, Some(std::thread::current().id())); + debug_assert!(state.depth > 0); + state.depth -= 1; + if state.depth == 0 { + state.owner = None; + self.0.changed.notify_one(); + } + } +} + +fn leases() -> &'static RwLock<HashMap<usize, Arc<Lease>>> { + static LEASES: OnceLock<RwLock<HashMap<usize, Arc<Lease>>>> = OnceLock::new(); + LEASES.get_or_init(|| RwLock::new(HashMap::new())) +} + +fn lease(queue: usize) -> Arc<Lease> { + if let Some(lease) = leases().read().unwrap_or_else(|e| e.into_inner()).get(&queue).cloned() { + return lease; + } + let mut leases = leases().write().unwrap_or_else(|e| e.into_inner()); + Arc::clone(leases.entry(queue).or_default()) +} + +/// Start a new raw-address generation before the newly created queue is returned to its caller. +pub(super) fn created(queue: usize) { + if queue != 0 { + leases().write().unwrap_or_else(|e| e.into_inner()).insert(queue, Arc::new(Lease::default())); + } +} + +/// Run one ordered queue operation. Calls made recursively by XCL setup work retain the same turn. +pub(super) fn with<R>(queue: usize, f: impl FnOnce() -> R) -> R { + if queue == 0 { + return f(); + } + let _guard = lease(queue).enter(); + f() +} + +/// Forward Release and discard the raw-address lease after a final native release. Pointer +/// identity prevents a newly created generation at the same address from being removed. +pub(super) fn release(queue: usize, f: impl FnOnce() -> u32) -> u32 { + let old = leases().read().unwrap_or_else(|e| e.into_inner()).get(&queue).cloned(); + let n = f(); + if n == 0 { + let mut leases = leases().write().unwrap_or_else(|e| e.into_inner()); + if old.as_ref().is_some_and(|old| leases.get(&queue).is_some_and(|current| Arc::ptr_eq(old, current))) { + leases.remove(&queue); + } + } + n +} + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::c_void; + use std::sync::mpsc; + use std::sync::atomic::{AtomicU64, Ordering}; + use std::time::Duration; + use windows::core::Interface; + use windows::Win32::Graphics::Direct3D12::{ID3D12CommandQueue, ID3D12Fence}; + + static NATIVE_SIGNAL: AtomicU64 = AtomicU64::new(0); + static WRAPPER_SIGNAL: AtomicU64 = AtomicU64::new(0); + + unsafe extern "system" fn fake_native_signal(_: *mut c_void, _: *mut c_void, value: u64) -> i32 { + NATIVE_SIGNAL.store(value, Ordering::Relaxed); + 0 + } + + unsafe extern "system" fn fake_shifted_wrapper(_: *mut c_void, _: *mut c_void, value: u64) -> i32 { + WRAPPER_SIGNAL.store(value, Ordering::Relaxed); + 0 + } + + #[test] + fn same_queue_is_reentrant_but_excludes_another_thread() { + let queue = 0x5151_0001; + let (entered_tx, entered_rx) = mpsc::channel(); + let (leave_tx, leave_rx) = mpsc::channel(); + let first = std::thread::spawn(move || { + with(queue, || { + with(queue, || entered_tx.send(()).unwrap()); + leave_rx.recv().unwrap(); + }); + }); + entered_rx.recv().unwrap(); + let (ready_tx, ready_rx) = mpsc::channel(); + let (second_tx, second_rx) = mpsc::channel(); + let second = std::thread::spawn(move || { + ready_tx.send(()).unwrap(); + with(queue, || second_tx.send(()).unwrap()) + }); + ready_rx.recv().unwrap(); + let start = std::time::Instant::now(); + while old_waiter_count(queue) == 0 && start.elapsed() < Duration::from_secs(1) { + std::thread::yield_now(); + } + assert_eq!(old_waiter_count(queue), 1, "the second thread reached the held lease"); + assert!(second_rx.try_recv().is_err()); + leave_tx.send(()).unwrap(); + second_rx.recv_timeout(Duration::from_secs(1)).unwrap(); + first.join().unwrap(); + second.join().unwrap(); + release(queue, || 0); + } + + #[test] + fn different_queues_do_not_share_a_turn() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (leave_tx, leave_rx) = mpsc::channel(); + let first = std::thread::spawn(move || with(0x5151_0002, || { + entered_tx.send(()).unwrap(); + leave_rx.recv().unwrap(); + })); + entered_rx.recv().unwrap(); + with(0x5151_0003, || {}); + leave_tx.send(()).unwrap(); + first.join().unwrap(); + release(0x5151_0002, || 0); + release(0x5151_0003, || 0); + } + + #[test] + fn an_old_final_release_does_not_remove_a_reused_address() { + let queue = 0x5151_0004; + created(queue); + let old = lease(queue); + let n = release(queue, || { + created(queue); + 0 + }); + assert_eq!(n, 0); + assert!(!Arc::ptr_eq(&old, &lease(queue))); + release(queue, || 0); + } + + #[test] + fn internal_signal_reenters_the_lease_and_uses_the_native_slot() { + NATIVE_SIGNAL.store(0, Ordering::Relaxed); + WRAPPER_SIGNAL.store(0, Ordering::Relaxed); + let mut original = vec![0usize; 16]; + original[14] = fake_native_signal as usize; + let mut extended = vec![0usize; 17]; + extended[0] = original.as_ptr() as usize; + extended[15] = fake_shifted_wrapper as usize; // ext[14], as a shifted title layout sees it + let ext = unsafe { extended.as_mut_ptr().add(1) }; + struct Registered(usize); + impl Drop for Registered { + fn drop(&mut self) { super::super::real::register_test_queue_vtable(self.0, false); } + } + super::super::real::register_test_queue_vtable(ext as usize, true); + let _registered = Registered(ext as usize); + let mut queue_object = [ext as usize]; + let mut fence_object = [0usize]; + let queue_raw = queue_object.as_mut_ptr() as *mut c_void; + let fence_raw = fence_object.as_mut_ptr() as *mut c_void; + let queue = unsafe { ID3D12CommandQueue::from_raw_borrowed(&queue_raw).unwrap() }; + let fence = unsafe { ID3D12Fence::from_raw_borrowed(&fence_raw).unwrap() }; + + with(queue_raw as usize, || unsafe { + super::super::real::native_queue_signal(queue, fence, 0x5151).unwrap(); + }); + assert_eq!(NATIVE_SIGNAL.load(Ordering::Relaxed), 0x5151); + assert_eq!(WRAPPER_SIGNAL.load(Ordering::Relaxed), 0, "the adopted title wrapper must be bypassed"); + release(queue_raw as usize, || 0); + } + + fn old_waiter_count(queue: usize) -> usize { + lease(queue).state.lock().unwrap_or_else(|e| e.into_inner()).waiters + } +} diff --git a/crates/xcl/src/hle/d3d12x/real.rs b/crates/xcl/src/hle/d3d12x/real.rs index 76f31d4daf..cd74273f58 100644 --- a/crates/xcl/src/hle/d3d12x/real.rs +++ b/crates/xcl/src/hle/d3d12x/real.rs @@ -20,8 +20,8 @@ use std::collections::{BTreeSet, HashMap, HashSet}; use std::ffi::c_void; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; -use std::sync::{Mutex, OnceLock}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicUsize, Ordering}; +use std::sync::{Arc, LazyLock, Mutex, OnceLock}; use serde::Serialize; use windows::core::{Interface, PCSTR}; @@ -60,6 +60,44 @@ pub enum Kind { StateObject, } +#[cfg(test)] +mod slot_cache_tests { + use super::*; + + #[test] + fn cached_hot_methods_keep_one_nonzero_slot_across_interface_versions() { + let families: [(&str, &[&str]); 5] = [ + ( + "ID3D12GraphicsCommandList", + &[ + "Close", + "Reset", + "ClearState", + "DrawInstanced", + "DrawIndexedInstanced", + "SetPipelineState", + "OMSetRenderTargets", + "ClearRenderTargetView", + "ExecuteIndirect", + ], + ), + ("ID3D12Resource", &["Map", "Unmap", "WriteToSubresource"]), + ("ID3D12CommandQueue", &["ExecuteCommandLists"]), + ("ID3D12CommandAllocator", &["Reset"]), + ("ID3D12Fence", &["Signal"]), + ]; + for (base, methods) in families { + let versions = layout::chain(base); + assert!(!versions.is_empty(), "{base}"); + for method in methods { + let slots: BTreeSet<_> = versions.iter().filter_map(|iface| layout::slot(iface, method)).collect(); + assert_eq!(slots.len(), 1, "{base}::{method} at {slots:?}"); + assert_ne!(slots.first(), Some(&0), "slot zero is the cache's empty value"); + } + } + } +} + impl Kind { pub fn base(self) -> &'static str { match self { @@ -130,24 +168,135 @@ pub struct D3d12Stats { /// DXIL cache and compiler statistics. #[serde(default)] pub dxil_cache: crate::gpu::recomp::dxc::CacheStats, + /// Native title `ExecuteCommandLists` chunks timed while `XCL_GPU_TIMING=1`. These are CPU + /// durations inside the native call, not GPU execution or completion time. + #[serde(default)] + pub submissions: u64, + #[serde(default)] + pub slowest_submission_ms: f64, + #[serde(default)] + pub slowest_submission_lists: usize, + #[serde(default)] + pub submission_total_ns: u64, + #[serde(default)] + pub submission_mean_ms: f64, + #[serde(default)] + pub submission_p95_upper_ms: f64, + #[serde(default)] + pub submission_p99_upper_ms: f64, + /// Counts in base-2 nanosecond buckets. Bucket zero includes zero and one nanosecond. + #[serde(default)] + pub submission_histogram_log2_ns: Vec<u64>, } static ADAPTER: Mutex<String> = Mutex::new(String::new()); +static ADAPTER_VENDOR: AtomicU32 = AtomicU32::new(0x1414); static UNKNOWN_IIDS: Mutex<BTreeSet<String>> = Mutex::new(BTreeSet::new()); static FALLBACK_PSO: AtomicU64 = AtomicU64::new(0); static FAILED_PSO: AtomicU64 = AtomicU64::new(0); static FALLBACK_RS: AtomicU64 = AtomicU64::new(0); static TRANSLATED_PSO: AtomicU64 = AtomicU64::new(0); static TRANSLATE_ERRORS: Mutex<Vec<String>> = Mutex::new(Vec::new()); -/// XCL shader ABI root signature on the backend device (raw, kept for the process lifetime) + +#[derive(Clone, Copy)] +struct SubmissionTiming { + submissions: u64, + total_ns: u64, + slowest_ns: u64, + slowest_lists: usize, + histogram: [u64; crate::stall::HISTOGRAM_BUCKETS], +} + +impl Default for SubmissionTiming { + fn default() -> Self { + Self { + submissions: 0, + total_ns: 0, + slowest_ns: 0, + slowest_lists: 0, + histogram: [0; crate::stall::HISTOGRAM_BUCKETS], + } + } +} + +impl SubmissionTiming { + fn record(&mut self, ns: u64, lists: usize) { + self.submissions = self.submissions.saturating_add(1); + self.total_ns = self.total_ns.saturating_add(ns); + let bucket = submission_histogram_bucket(ns); + self.histogram[bucket] = self.histogram[bucket].saturating_add(1); + if ns > self.slowest_ns { + self.slowest_ns = ns; + self.slowest_lists = lists; + } + } + + fn percentile_upper_ns(&self, percentile: u64) -> u64 { + if self.submissions == 0 { return 0 } + let target = ((self.submissions as u128 * percentile as u128 + 99) / 100) as u64; + let mut cumulative = 0u64; + let bucket = self.histogram.iter().position(|count| { + cumulative = cumulative.saturating_add(*count); + cumulative >= target + }).unwrap_or(self.histogram.len() - 1); + if bucket + 1 >= u64::BITS as usize { u64::MAX } else { (1u64 << (bucket + 1)) - 1 } + } +} + +const fn submission_histogram_bucket(ns: u64) -> usize { + if ns == 0 { 0 } else { (u64::BITS - 1 - ns.leading_zeros()) as usize } +} + +static SUBMISSION_TIMING: Mutex<SubmissionTiming> = Mutex::new(SubmissionTiming { + submissions: 0, + total_ns: 0, + slowest_ns: 0, + slowest_lists: 0, + histogram: [0; crate::stall::HISTOGRAM_BUCKETS], +}); + +fn gpu_timing_on_value(value: Option<&str>) -> bool { + value == Some("1") +} + +fn gpu_timing_on() -> bool { + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| gpu_timing_on_value(std::env::var("XCL_GPU_TIMING").ok().as_deref())) +} + +fn slow_submission_us_value(value: Option<&str>) -> u64 { + value.and_then(|value| value.parse::<u64>().ok()).unwrap_or(50).saturating_mul(1_000) +} + +fn slow_submission_us() -> u64 { + static US: OnceLock<u64> = OnceLock::new(); + *US.get_or_init(|| slow_submission_us_value(std::env::var("XCL_GPU_TIMING_MS").ok().as_deref())) +} + +fn note_submission_timing(elapsed: std::time::Duration, lists: usize, queue: *mut c_void) { + let ns = elapsed.as_nanos().min(u64::MAX as u128) as u64; + if let Ok(mut timing) = SUBMISSION_TIMING.lock() { + timing.record(ns, lists); + } + let us = ns / 1_000; + if us >= slow_submission_us() { + crate::xlog_warn!("ExecuteCommandLists: {us} µs of CPU time for {lists} list(s), queue {queue:p}"); + } +} + +/// XCL shader ABI root signature on the primary backend device (raw, kept for the process lifetime) static ABI_RS: AtomicUsize = AtomicUsize::new(0); +static ABI_RS_DEV: AtomicUsize = AtomicUsize::new(0); +static ABI_RS_BY_DEV: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); /// XCL's shader ABI root signature, once a translated pipeline created it. pub fn abi_rs_cached() -> Option<*mut c_void> { - match ABI_RS.load(Ordering::Acquire) { - 0 => None, - p => Some(p as *mut c_void), + let dev = device_raw() as usize; + let primary = ABI_RS.load(Ordering::Acquire); + if primary != 0 && (dev == 0 || ABI_RS_DEV.load(Ordering::Acquire) == dev) { + return Some(primary as *mut c_void); } + ABI_RS_BY_DEV.lock().unwrap().as_ref()?.get(&dev).map(|&p| p as *mut c_void) } thread_local! { @@ -160,10 +309,7 @@ thread_local! { /// Root signature of the pipelines built from translated console shaders (bind it, then the /// XCL ABI root UAVs io / res / mem, to draw with them). pub fn abi_root_signature() -> Option<ID3D12RootSignature> { - let raw = ABI_RS.load(Ordering::Acquire) as *mut c_void; - if raw.is_null() { - return None; - } + let raw = abi_rs_cached()?; unsafe { ID3D12RootSignature::from_raw_borrowed(&raw).cloned() } } /// Each UMA window as one D3D12 buffer (placed in a heap opened over the process memory): @@ -265,8 +411,9 @@ unsafe fn check_uma_import(device: &ID3D12Device, u: &crate::gpu::uma::Uma, bufs } let run = || -> Result<Vec<u32>, String> { list.Close().map_err(|e| format!("check not run: Close: {e}"))?; - queue.ExecuteCommandLists(&[Some(list.cast::<ID3D12CommandList>().map_err(|e| e.to_string())?)]); - queue.Signal(&fence, 1).map_err(|e| format!("check not run: Signal: {e}"))?; + let list = list.cast::<ID3D12CommandList>().map_err(|e| e.to_string())?; + native_queue_execute(&queue, &list); + native_queue_signal(&queue, &fence, 1).map_err(|e| format!("check not run: Signal: {e}"))?; crate::gpu::fence::wait(&fence, 1, device, None, 2000).map_err(|e| format!("check not run: {e}"))?; let mut m = std::ptr::null_mut(); readback.Map(0, None, Some(&mut m)).map_err(|e| format!("check not run: Map: {e}"))?; @@ -387,6 +534,7 @@ pub fn stats() -> D3d12Stats { }) .unwrap_or_default(); let (presents, boundaries) = super::present::counters(); + let submission_timing = SUBMISSION_TIMING.lock().map(|timing| *timing).unwrap_or_default(); D3d12Stats { backend: format!("{:?}", super::backend()).to_lowercase(), adapter: ADAPTER.lock().map(|a| a.clone()).unwrap_or_default(), @@ -410,6 +558,16 @@ pub fn stats() -> D3d12Stats { translation_errors: TRANSLATE_ERRORS.lock().map(|e| e.clone()).unwrap_or_default(), background_pipelines: super::pso_async::counts(), dxil_cache: crate::gpu::recomp::dxc::cache_stats(), + submissions: submission_timing.submissions, + slowest_submission_ms: submission_timing.slowest_ns as f64 / 1_000_000.0, + slowest_submission_lists: submission_timing.slowest_lists, + submission_total_ns: submission_timing.total_ns, + submission_mean_ms: if submission_timing.submissions == 0 { 0.0 } else { + submission_timing.total_ns as f64 / submission_timing.submissions as f64 / 1_000_000.0 + }, + submission_p95_upper_ms: submission_timing.percentile_upper_ns(95) as f64 / 1_000_000.0, + submission_p99_upper_ms: submission_timing.percentile_upper_ns(99) as f64 / 1_000_000.0, + submission_histogram_log2_ns: submission_timing.histogram.into(), } } @@ -513,6 +671,7 @@ pub fn init() -> Result<String, String> { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| format!("DXGI: {e}"))?; let mut device: Option<ID3D12Device> = None; let mut name = String::new(); + let mut vendor = 0x1414; // WARP is Microsoft's adapter let sel = crate::gpu::adapter::Selector::from_env_or(&cfg.d3d12_adapter); if sel != crate::gpu::adapter::Selector::Warp { let mut list = crate::gpu::adapter::candidates(&factory, &sel); @@ -523,6 +682,7 @@ pub fn init() -> Result<String, String> { for (adapter, desc) in list { if let Ok(dev) = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0) { device = Some(dev); + vendor = desc.VendorId; name = format!("{} ({} MiB VRAM)", crate::gpu::adapter::name(&desc), desc.DedicatedVideoMemory >> 20); break; } @@ -538,6 +698,8 @@ pub fn init() -> Result<String, String> { d } }; + driver_cache::note_vendor(vendor); + ADAPTER_VENDOR.store(vendor, Ordering::Release); if debug { // the debug layer's messages into XCL's log (they otherwise go to a debugger only) if let Ok(q) = device.cast::<ID3D12InfoQueue1>() { @@ -634,6 +796,83 @@ pub unsafe fn orig_fn(this: *mut c_void, slot: usize) -> usize { *orig.add(slot) } +/// `slot_of(this, method)`, looked up once for this call site. COM interface versions append +/// methods, so one method keeps its slot throughout the interface family served by a hook. +macro_rules! slot { + ($this:expr, $method:literal) => {{ + static SLOT: AtomicUsize = AtomicUsize::new(0); + cached_slot(&SLOT, $this, $method) + }}; +} + +unsafe fn cached_slot(cache: &AtomicUsize, this: *mut c_void, method: &str) -> usize { + match cache.load(Ordering::Relaxed) { + 0 => { + let slot = slot_of(this, method); + cache.store(slot, Ordering::Relaxed); + slot + } + slot => slot, + } +} + +unsafe fn native_queue_fn(queue: *mut c_void, slot: usize) -> usize { + let table = vt(queue); + if is_ext(table as usize) { orig_fn(queue, slot) } else { *table.add(slot) } +} + +/// Submit XCL's own list through the PC queue slot, never through the title-facing wrapper. +/// The queue lease makes this one ordered operation, and is re-entrant when a title submit is +/// already publishing its effects. +pub(crate) unsafe fn native_queue_execute(queue: &ID3D12CommandQueue, list: &ID3D12CommandList) { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); + let f = native_queue_fn(raw, 10); + super::queue_submit::with(raw as usize, || { + let f: F = std::mem::transmute(f); + let list = list.as_raw(); + f(raw, 1, &list); + }); +} + +/// Signal through the PC queue slot. Console queue layouts remap public slots 14+, so an +/// internal COM call on an adopted queue is not a reliable way to reach native Signal. +pub(crate) unsafe fn native_queue_signal(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> windows::core::Result<()> { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let f = native_queue_fn(raw, 14); + super::queue_submit::with(raw as usize, || { + let f: F = std::mem::transmute(f); + windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + }) +} + +/// Wait through the PC queue slot, bypassing the title's shifted queue layout. +pub(crate) unsafe fn native_queue_wait(queue: &ID3D12CommandQueue, fence: &ID3D12Fence, value: u64) -> windows::core::Result<()> { + let raw = queue.as_raw(); + type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT; + let f = native_queue_fn(raw, 15); + super::queue_submit::with(raw as usize, || { + let f: F = std::mem::transmute(f); + windows::core::HRESULT(f(raw, fence.as_raw(), value)).ok() + }) +} + +pub(crate) unsafe fn native_fence_completed(fence: &ID3D12Fence) -> u64 { + let raw = fence.as_raw(); + let slot = std::mem::offset_of!(ID3D12Fence_Vtbl, GetCompletedValue) / std::mem::size_of::<usize>(); + type F = unsafe extern "system" fn(*mut c_void) -> u64; + let f: F = std::mem::transmute(if is_ext(vt(raw) as usize) { orig_fn(raw, slot) } else { *vt(raw).add(slot) }); + f(raw) +} + +#[cfg(test)] +pub(super) fn register_test_queue_vtable(ext: usize, add: bool) { + let mut tables = EXTS.lock().unwrap(); + let tables = tables.get_or_insert_with(HashSet::new); + if add { tables.insert(ext); } else { tables.remove(&ext); } +} + fn module_of(addr: usize) -> usize { use windows_sys::Win32::System::LibraryLoader::{ GetModuleHandleExW, GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, @@ -1006,6 +1245,7 @@ fn console_slots(kind: Kind) -> Vec<(usize, usize)> { (44, b::set_graphics_root_descriptor as usize), (46, b::set_graphics_root_descriptor as usize), (26, l::resource_barrier_x as usize), + (27, l::execute_bundle as usize), (25, b::set_pipeline_state as usize), (33, b::set_compute_root_signature as usize), (35, b::set_compute_root_table as usize), @@ -1582,7 +1822,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v // the PC's Map only on a resource it can map: on a reserved one or one without CPU pages it is // an invalid call (debug layer 824 / 822) that the runtime answers with E_INVALIDARG let hr = if pc_can_map(this) { - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Map"))); + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void, *mut *mut c_void) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Map"))); f(this, sub, range, data) } else { E_INVALIDARG @@ -1613,7 +1853,7 @@ unsafe extern "system" fn res_map(this: *mut c_void, sub: u32, range: *const c_v /// Every console resource is CPU-visible memory, a PC texture only in a CPU-visible heap. unsafe extern "system" fn res_write_to_subresource(this: *mut c_void, sub: u32, dst_box: *const D3D12_BOX, data: *const c_void, row_pitch: u32, depth_pitch: u32) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void, u32, *const D3D12_BOX, *const c_void, u32, u32) -> HRESULT; - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "WriteToSubresource"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "WriteToSubresource"))); let hr = f(this, sub, dst_box, data, row_pitch, depth_pitch); static CALLS: AtomicU64 = AtomicU64::new(0); static FAILED: AtomicU64 = AtomicU64::new(0); @@ -1650,12 +1890,16 @@ unsafe extern "system" fn res_unmap(this: *mut c_void, sub: u32, range: *const c if UNMAPPABLE.lock().unwrap().as_ref().is_some_and(|s| s.contains(&(this as usize))) { return; } - let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot_of(this, "Unmap"))); + let f: unsafe extern "system" fn(*mut c_void, u32, *const c_void) = std::mem::transmute(orig_fn(this, slot!(this, "Unmap"))); f(this, sub, range) } unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + // When opt-in SRV tracking is active, exclude a future resource lease before the native + // object can die. This is not the descriptor-write gate: descriptor hooks keep that across + // driver calls which may make a temporary, non-final Release here. + let mut tracked_srv_lifetime = super::vram::lock_tracked_srv_lifetime(); // The last reference: kept until the queues are past the work in flight (`late_release`). // (Two last-but-one releases at once can miss each other here; the object then goes at // once, as before.) @@ -1674,6 +1918,15 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { f(this) }; if n == 0 { + // Remove lease candidates while Release is still serialized, then leave the lifetime + // gate before the independent sparse/page/arena cleanup locks below. Do not wait for the + // global descriptor-write gate here: an unrelated hook may hold it while a driver call + // makes a temporary Release that waits for this lifetime gate. Any lease already returned + // owns a strong resource reference and therefore prevents this logical zero. + super::vram::forget_tracked_after_resource_release( + this as usize, tracked_srv_lifetime.as_ref(), + ); + drop(tracked_srv_lifetime.take()); if let Some(s) = UNMAPPABLE.lock().unwrap().as_mut() { s.remove(&(this as usize)); } @@ -1690,7 +1943,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { m.remove(&(this as usize)); } super::sparse::forget_buffer(this as usize); - super::vram::forget(this as usize); + super::vram::forget_resource_backing_after_release(this as usize); super::title_textures::forget(this as usize); let gone = UMA_BUFFERS.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))); if let (Some((p, _, true)), Some(u)) = (gone, crate::gpu::uma::get()) { @@ -1701,6 +1954,7 @@ unsafe extern "system" fn res_release(this: *mut c_void) -> u32 { } } } + drop(tracked_srv_lifetime.take()); if held { super::late_release::hold(this as usize); } @@ -1844,6 +2098,10 @@ fn forget_pso(pso: usize) { if let Some(m) = PSO_USER_SGPRS.lock().unwrap().as_mut() { m.remove(&pso); } + if let Some(m) = PSO_DISPATCH_REMAP.lock().unwrap().as_mut() { + m.remove(&pso); + } + remap_fallback::forget(pso); super::device_x::forget_base(pso); // the compute pass goes with the last user of its entry (`Drop for TwoPassPso`) let gone = TWO_PASS.lock().unwrap().as_mut().and_then(|m| m.remove(&pso)); @@ -1922,22 +2180,26 @@ fn note_buffer_view() { /// (`desc::cbv_words`; unified memory, anything else gets an empty V#). No PC CBV: translated /// shaders read buffers through `mem`. unsafe extern "system" fn dev_create_cbv_x(this: *mut c_void, desc: *const D3D12_CONSTANT_BUFFER_VIEW_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let Some(slot) = super::console_heap::slot(cpu).filter(|s| !s.sampler) else { let f: unsafe extern "system" fn(*mut c_void, *const D3D12_CONSTANT_BUFFER_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 17)); return f(this, desc, cpu); }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); let (va, size) = desc.as_ref().map_or((0, 0), |d| (d.BufferLocation, d.SizeInBytes)); let in_uma = crate::gpu::uma::get().is_some_and(|u| u.contains(va as usize)); if !in_uma { note_buffer_view(); } let (va, size) = if in_uma { (va, size) } else { (0, 0) }; + super::vram::clear_tracked_srv(&slot); super::console_heap::write(&slot, &crate::gpu::desc::cbv_words(va, size)); } /// #22 CreateSampler: the PC sampler at the slot's index, the S# in XCL ABI form (word 3 /// [11:0] = sampler heap index; the state lives in the PC sampler). pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, desc: *const D3D12_SAMPLER_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *const D3D12_SAMPLER_DESC, u64) = std::mem::transmute(orig_fn(this, 22)); let Some(slot) = super::console_heap::slot(cpu).filter(|s| s.sampler) else { return f(this, desc, cpu) }; f(this, desc, slot.pc_srv); @@ -1948,21 +2210,31 @@ pub(super) unsafe extern "system" fn dev_create_sampler_x(this: *mut c_void, des /// Copy `n` console slots from `src` to `dst` (both in console heaps of one kind): the PC /// descriptors (2 per view slot) and the slots. False: not two console ranges. unsafe fn copy_console_slots(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) -> bool { - use super::console_heap::{copy_words, slot, SAMPLER_SLOT, SLOT}; + use super::console_heap::{copy_words, copy_words_captured, slot, SAMPLER_SLOT, SLOT}; let (Some(d0), Some(s0)) = (slot(dst), slot(src)) else { return false }; if d0.sampler != s0.sampler { return false; } + let _tracked_write_lock = (!d0.sampler).then(super::vram::lock_tracked_srv_write).flatten(); + let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; let ty = pc_heap_type(ty); let f: unsafe extern "system" fn(*mut c_void, u32, u64, u64, u32) = std::mem::transmute(orig_fn(this, 24)); f(this, if d0.sampler { n } else { 2 * n }, d0.pc_srv, s0.pc_srv, ty); super::console_heap::publish_range(&d0, n); - let step = if d0.sampler { SAMPLER_SLOT } else { SLOT } as u64; + let mut tracked_copies = (!d0.sampler && super::vram::srv_tracking_enabled()).then(Vec::new); for k in 0..n as u64 { if let (Some(d), Some(s)) = (slot(dst + k * step), slot(src + k * step)) { - copy_words(&s, &d); + if let Some(copies) = tracked_copies.as_mut() { + let (source_words, destination_words) = copy_words_captured(&s, &d); + copies.push((s, d, source_words, destination_words)); + } else { + copy_words(&s, &d); + } } } + if let Some(copies) = tracked_copies { + super::vram::copy_tracked_srvs(this as usize, &copies); + } true } @@ -1985,6 +2257,7 @@ fn note_mixed_copy() { /// #24 CopyDescriptorsSimple(n, dst, src, type) unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u32, dst: u64, src: u64, ty: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptorsSimple", n, dst, src); if copy_console_slots(this, n, dst, src, ty) { @@ -2001,6 +2274,7 @@ unsafe extern "system" fn dev_copy_descriptors_simple_x(this: *mut c_void, n: u3 /// #23 CopyDescriptors(dst ranges, src ranges, type): range by range over console slots. #[allow(clippy::too_many_arguments)] unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dsts: *const u64, dsizes: *const u32, ns: u32, srcs: *const u64, ssizes: *const u32, ty: u32) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let ty = pc_heap_type(ty); note_copy_call("CopyDescriptors", nd, if dsts.is_null() { 0 } else { *dsts }, if srcs.is_null() { 0 } else { *srcs }); use super::console_heap::{slot, SAMPLER_SLOT, SLOT}; @@ -2031,16 +2305,44 @@ unsafe extern "system" fn dev_copy_descriptors_x(this: *mut c_void, nd: u32, dst } } -/// descriptor heap Release (every caller): a console heap's slots go with it -unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { +/// Remove address-keyed state before a last native Release can expose that address for reuse. +/// A simultaneous Release can make the probe miss the last reference; the post-free `take` +/// prevents stale state from leaking but cannot protect a replacement already at the address. +unsafe fn release_taking_first<T>(this: *mut c_void, mut take: impl FnMut() -> T, after: impl FnOnce(T)) -> u32 { + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let take_first = add_ref(this) == 2; + let taken = take_first.then(&mut take); + // Drop the temporary probe reference, then the caller's reference. + f(this); let n = f(this); if n == 0 { - super::console_heap::unregister(this as usize); + after(match taken { + Some(taken) => taken, + None => take(), + }); } n } +/// descriptor heap Release (every caller): a console heap's slots go with it +unsafe extern "system" fn heap_release(this: *mut c_void) -> u32 { + let lifetime = super::console_heap::lock_lifetime(); + if lifetime.is_none() { + return release_taking_first(this, || super::console_heap::take(this as usize), |h| h.into_iter().for_each(super::console_heap::free)); + } + let generation = lifetime.as_ref().and_then(|_| super::console_heap::generation(this as usize)); + let mut taken = None; + let n = release_taking_first( + this, + || super::console_heap::take_after_release(this as usize, generation, lifetime.as_ref()), + |h| taken = h, + ); + drop(lifetime); + taken.into_iter().for_each(super::console_heap::free); + n +} + /// Default UAV dimension for a texture resource when `CreateUnorderedAccessView` receives a NULL desc. fn default_uav_dimension(rd: &D3D12_RESOURCE_DESC) -> D3D12_UAV_DIMENSION { match rd.Dimension { @@ -2088,6 +2390,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( desc: *const D3D12_UNORDERED_ACCESS_VIEW_DESC, cpu: u64, ) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); if let Some(r) = ID3D12Resource::from_raw_borrowed(&res) { let rd = r.GetDesc(); let is_tex = rd.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER; @@ -2132,6 +2435,7 @@ unsafe extern "system" fn dev_create_uav_checked_x( /// #21 CreateDepthStencilView: the console's view formats as the PC's (`pc_view_format`). unsafe extern "system" fn dev_create_dsv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_DEPTH_STENCIL_VIEW_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_DEPTH_STENCIL_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 21)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2223,6 +2527,7 @@ fn pc_srv(rd: &D3D12_RESOURCE_DESC, v: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) } unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, desc: *const D3D12_SHADER_RESOURCE_VIEW_DESC, cpu: u64) { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *const D3D12_SHADER_RESOURCE_VIEW_DESC, u64) = std::mem::transmute(orig_fn(this, 18)); let mut copy = desc.as_ref().copied(); if let Some(c) = copy.as_mut() { @@ -2241,6 +2546,8 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } let desc = copy.as_ref().map_or(desc, |c| c as *const _); let Some(slot) = super::console_heap::slot(cpu) else { return f(this, res, desc, cpu) }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); // Raytracing acceleration structure SRV (pResource == NULL, Location == console GPU VA): // translated shaders read BVH nodes from UMA (`bvh_intersect`), never from a PC DXR SRV, // so write the RDNA2 BVH descriptor directly and skip forwarding the console VA to PC. @@ -2280,6 +2587,9 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } super::console_heap::publish(&slot, false); super::console_heap::note_resource(&slot, res as usize); + if !res.is_null() && super::memory_report::enabled() { + super::vram::note_srv(res as usize, desc.as_ref()); + } if super::present::trace_frame() && super::title_textures::address(res as usize).is_some() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 24 { @@ -2311,7 +2621,10 @@ unsafe extern "system" fn dev_create_srv_x(this: *mut c_void, res: *mut c_void, } let rdesc = r.GetDesc(); match srv_tsharp_from_desc(slot.index, &rdesc, desc.as_ref()) { - Some(t) => super::console_heap::write(&slot, &t), + Some(t) => { + super::console_heap::write(&slot, &t); + super::vram::track_srv(this as usize, res as usize, &slot, desc.as_ref().copied(), t); + } None => { note_buffer_view(); super::console_heap::write(&slot, &[0; 8]); @@ -2377,7 +2690,10 @@ unsafe extern "system" fn dev_create_srv_at_x(this: *mut c_void, rdesc: *const u let va = (view.add(0x28) as *const u64).read_unaligned(); let v = (view as *const D3D12_SHADER_RESOURCE_VIEW_DESC).read_unaligned(); if v.ViewDimension == D3D12_SRV_DIMENSION_BUFFER { + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); let Some(slot) = super::console_heap::slot(cpu) else { return }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); @@ -2394,8 +2710,11 @@ unsafe extern "system" fn dev_create_uav_at_x(this: *mut c_void, rdesc: *const u } let va = (view.add(0x28) as *const u64).read_unaligned(); let v = (view as *const D3D12_UNORDERED_ACCESS_VIEW_DESC).read_unaligned(); + let _detail = crate::stall::detail_span(crate::stall::StallKind::DetailViewDescriptor); if v.ViewDimension == D3D12_UAV_DIMENSION_BUFFER { let Some(slot) = super::console_heap::slot(cpu) else { return }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); let b = &v.Anonymous.Buffer; let raw = b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; let words = buffer_words_at(va, v.Format, b.FirstElement, b.NumElements, b.StructureByteStride, raw); @@ -2651,6 +2970,8 @@ unsafe extern "system" fn dev_create_uav_x(this: *mut c_void, res: *mut c_void, } }; let Some(slot) = super::console_heap::slot(cpu) else { return pc_uav(cpu) }; + let _tracked_write_lock = super::vram::lock_tracked_srv_write(); + super::vram::clear_tracked_srv(&slot); pc_uav(slot.pc_uav); super::console_heap::publish(&slot, true); super::console_heap::note_resource(&slot, res as usize); @@ -2832,9 +3153,11 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro } pub(super) unsafe extern "system" fn dev_create_command_list_x(this: *mut c_void, mask: usize, ty: usize, alloc: usize, pso: usize, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - let pc_pso = super::console_list::pc_pso(pso as *mut c_void) as usize; + let (pc_pso, generation) = super::pso_async::resolve_and_pin_if_enabled_identity(super::console_list::pc_pso(pso as *mut c_void) as usize); let hr = dev_create_command_list(this, mask, ty, alloc, pc_pso, riid, ppv); if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { + super::list_x::on_console_list_create(*ppv, alloc, pc_pso, D3D12_COMMAND_LIST_TYPE(ty as i32)); + super::list_x::record_native_generation(*ppv as usize, generation); *ppv = super::console_list::create_with_allocator(*ppv, alloc as *mut c_void); } hr @@ -2852,6 +3175,41 @@ unsafe extern "system" fn dev_create_compute_pso_x(this: *mut c_void, desc: *con hr } +unsafe extern "system" fn dev_make_resident(this: *mut c_void, n: u32, objects: *const *mut c_void) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "MakeResident"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, n, objects) +} + +unsafe extern "system" fn dev_evict(this: *mut c_void, n: u32, objects: *const *mut c_void) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "Evict"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, n, objects) +} + +unsafe extern "system" fn dev_set_residency_priority(this: *mut c_void, n: u32, objects: *const *mut c_void, priorities: *const D3D12_RESIDENCY_PRIORITY) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void, *const D3D12_RESIDENCY_PRIORITY) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetResidencyPriority"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, n, objects, priorities) +} + +unsafe extern "system" fn dev_enqueue_make_resident( + this: *mut c_void, + flags: D3D12_RESIDENCY_FLAGS, + n: u32, + objects: *const *mut c_void, + fence: *mut c_void, + value: u64, +) -> HRESULT { + type F = unsafe extern "system" fn(*mut c_void, D3D12_RESIDENCY_FLAGS, u32, *const *mut c_void, *mut c_void, u64) -> HRESULT; + let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "EnqueueMakeResident"))); + let _stall = crate::stall::span(crate::stall::StallKind::Residency); + f(this, flags, n, objects, fence, value) +} + fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { let mut v: Vec<(&'static str, usize)> = vec![("QueryInterface", qi_override as usize)]; match kind { @@ -2869,11 +3227,15 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("CreateHeap", dev_create_heap as usize), ("CreatePlacedResource", dev_create_placed_resource as usize), ("CreateReservedResource", dev_create_reserved_resource as usize), + ("MakeResident", dev_make_resident as usize), + ("Evict", dev_evict as usize), ("CreateFence", dev_create_fence as usize), ("CreateQueryHeap", dev_create_query_heap as usize), ("CreateCommandSignature", dev_create_command_signature as usize), ("CreatePipelineLibrary", dev_create_pipeline_library as usize), + ("SetResidencyPriority", dev_set_residency_priority as usize), ("CreatePipelineState", dev_create_pipeline_state as usize), + ("EnqueueMakeResident", dev_enqueue_make_resident as usize), ("CreateCommandList1", dev_create_command_list1 as usize), ("CreateCommittedResource1", dev_create_committed_resource1 as usize), ("CreateHeap1", dev_create_heap1 as usize), @@ -2892,6 +3254,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { ("DrawInstanced", cl_draw_instanced as usize), ("DrawIndexedInstanced", cl_draw_indexed_instanced as usize), ("SetPipelineState", cl_set_pipeline_state as usize), + ("ExecuteBundle", cl_execute_bundle as usize), ("SetMarker", cl_set_marker as usize), ("OMSetRenderTargets", cl_om_set_render_targets as usize), ("ClearRenderTargetView", cl_clear_rtv as usize), @@ -2913,7 +3276,7 @@ fn overrides(kind: Kind) -> Vec<(&'static str, usize)> { Kind::PipelineState => v.push(("Release", pso_release as usize)), Kind::DescriptorHeap => v.push(("Release", heap_release as usize)), Kind::Heap => v.push(("Release", mem_heap_release as usize)), - Kind::Fence => v.push(("Signal", fence_signal as usize)), + Kind::Fence => v.extend_from_slice(&[("GetCompletedValue", fence_completed as usize), ("Signal", fence_signal as usize)]), _ => {} } v @@ -2965,9 +3328,10 @@ macro_rules! as_usize { /// command list's vtable pointer on Close; adopt the runtime's new state vtable so /// subsequent Reset and console calls dispatch through the current native table. unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); super::list_x::before_close(this); let ext = *(this as *const usize); - let f: RefFn = std::mem::transmute(orig_fn(this, slot_of(this, "Close"))); + let f: RefFn = std::mem::transmute(orig_fn(this, slot!(this, "Close"))); let hr = f(this) as HRESULT; preserve_vtable(this, ext); if hr < 0 { @@ -2979,14 +3343,17 @@ unsafe extern "system" fn cl_close(this: *mut c_void) -> HRESULT { /// Reset (PC path): re-adopt the runtime's new open-state vtable if Reset replaced it. unsafe extern "system" fn cl_reset(this: *mut c_void, allocator: *mut c_void, initial_state: *mut c_void) -> HRESULT { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); let ext = *(this as *const usize); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, *mut c_void) -> HRESULT = - std::mem::transmute(orig_fn(this, slot_of(this, "Reset"))); - let resolved = super::pso_async::resolve_for_bind(initial_state as usize) as *mut c_void; + std::mem::transmute(orig_fn(this, slot!(this, "Reset"))); + let (resolved, generation) = super::pso_async::resolve_and_pin_if_enabled(initial_state as usize); + let resolved = resolved as *mut c_void; let hr = f(this, allocator, resolved); preserve_vtable(this, ext); if hr >= 0 { super::list_x::on_pc_reset(this); + super::list_x::record_native_generation(this as usize, generation); super::dred::reset(this); if !initial_state.is_null() { super::dred::mark_pipeline(this, initial_state as usize, resolved as usize); @@ -3151,6 +3518,9 @@ macro_rules! creator { } if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() { adopt(*ppv, $kind); + if $kind == Kind::CommandQueue { + super::queue_submit::created(*ppv as usize); + } } hr } @@ -3190,6 +3560,31 @@ pub(super) unsafe fn create_raw_pc_command_list( }; (hr >= 0 && !out.is_null()).then_some(out) } + +/// Create a raw adopted PC command list already closed and without an allocator. Split +/// preparation can reserve this while the producer still records; it is Reset onto the title's +/// allocator only after that producer has closed. +pub(super) unsafe fn create_closed_pc_command_list(dev: *mut c_void, ty: D3D12_COMMAND_LIST_TYPE) -> Option<*mut c_void> { + if dev.is_null() { + return None; + } + let iid = layout::parse_guid(layout::find("ID3D12GraphicsCommandList")?.iid); + let mut out = std::ptr::null_mut(); + let hr = if is_ext(vt(dev) as usize) { + dev_create_command_list1(dev, 0, ty.0 as usize, D3D12_COMMAND_LIST_FLAG_NONE.0 as usize, &iid, &mut out) + } else { + let dev4 = ID3D12Device::from_raw_borrowed(&dev)?.cast::<ID3D12Device4>().ok()?; + match dev4.CreateCommandList1::<ID3D12GraphicsCommandList>(0, ty, D3D12_COMMAND_LIST_FLAG_NONE) { + Ok(list) => { + out = list.into_raw(); + adopt(out, Kind::CommandList); + 0 + } + Err(e) => e.code().0, + } + }; + (hr >= 0 && !out.is_null()).then_some(out) +} creator!(dev_create_descriptor_heap, "CreateDescriptorHeap", Kind::DescriptorHeap, [a1]); creator!(dev_create_committed_resource, "CreateCommittedResource", Kind::Resource, [a1, a2, a3, a4, a5]); creator!(dev_create_committed_resource1, "CreateCommittedResource1", Kind::Resource, [a1, a2, a3, a4, a5, a6]); @@ -3540,19 +3935,19 @@ fn heap_block(heap: usize) -> Option<(usize, bool)> { /// ID3D12Heap::Release: its block of unified memory goes with it. unsafe extern "system" fn mem_heap_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); - if n == 0 { - let gone = HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block); - if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { - if u.is_sparse(p) { - super::sparse::free(p); - } else { - u.free(p); + release_taking_first( + this, + || HEAP_UMA.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))).and_then(|e| e.block), + |gone| { + if let (Some(p), Some(u)) = (gone, crate::gpu::uma::get()) { + if u.is_sparse(p) { + super::sparse::free(p); + } else { + u.free(p); + } } - } - } - n + }, + ) } creator!(dev_create_fence_pc, "CreateFence", Kind::Fence, [a1, a2]); @@ -3797,12 +4192,87 @@ pub fn switch_form_retries() -> u64 { SWITCH_FORM_RETRIES.load(Ordering::Relaxed) } +/// Driver pipeline builds for the window title: every `Create*PipelineState` call XCL makes +/// (`driver_pso`, on a worker or on a title thread) while it runs and once done, and the huge ones +/// waiting for their slot (`driver_compile_identified`). A call given a driver blob of an earlier +/// build (`BLOB_SUPPLIED`) is a load, not a build, and is not counted. +struct DriverBuilds { + building: AtomicUsize, + waiting: AtomicUsize, + done: AtomicUsize, +} + +static DRIVER_BUILDS: DriverBuilds = DriverBuilds::new(); + +thread_local! { + /// this thread's driver call is given a driver blob (`driver_compile_identified`) + static BLOB_SUPPLIED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +struct BlobSupplied(bool); + +impl BlobSupplied { + fn set(supplied: bool) -> Self { + Self(BLOB_SUPPLIED.with(|b| b.replace(supplied))) + } +} + +impl Drop for BlobSupplied { + fn drop(&mut self) { + BLOB_SUPPLIED.with(|b| b.set(self.0)); + } +} + +/// One counted build or wait: undone when dropped (a build also counts as done then). +struct Counted<'a>(&'a AtomicUsize, Option<&'a AtomicUsize>); + +impl Drop for Counted<'_> { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::Relaxed); + if let Some(done) = self.1 { + done.fetch_add(1, Ordering::Relaxed); + } + } +} + +impl DriverBuilds { + const fn new() -> Self { + Self { building: AtomicUsize::new(0), waiting: AtomicUsize::new(0), done: AtomicUsize::new(0) } + } + + fn building(&self) -> Counted<'_> { + self.building.fetch_add(1, Ordering::Relaxed); + Counted(&self.building, Some(&self.done)) + } + + fn waiting(&self) -> Counted<'_> { + self.waiting.fetch_add(1, Ordering::Relaxed); + Counted(&self.waiting, None) + } + + fn counts(&self) -> (usize, usize, usize) { + (self.building.load(Ordering::Relaxed), self.waiting.load(Ordering::Relaxed), self.done.load(Ordering::Relaxed)) + } +} + +/// Driver pipeline builds (running now, waiting for a huge-compile slot, done so far), for the +/// window title. +pub fn driver_build_counts() -> (usize, usize, usize) { + DRIVER_BUILDS.counts() +} + /// A driver pipeline call; E_OUTOFMEMORY while this thread translates with heap windows is /// noted for `with_switch_fallback`. unsafe fn driver_pso(f: PsoFn, this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { + let _build = (!BLOB_SUPPLIED.with(|b| b.get())).then(|| DRIVER_BUILDS.building()); let heap = crate::gpu::recomp::pso::mem_windows() & crate::gpu::recomp::HEAP_WINDOWS != 0; let injected = heap && INJECTED_OOM.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |n| n.checked_sub(1)).is_ok(); - let hr = if injected { E_OUTOFMEMORY } else { f(this, desc, riid, ppv) }; + let hr = if injected { + E_OUTOFMEMORY + } else { + let _stall = crate::stall::span(crate::stall::StallKind::DriverCompile); + f(this, desc, riid, ppv) + }; if hr == E_OUTOFMEMORY && heap { HEAP_WINDOW_OOM.with(|o| o.set(true)); } @@ -3882,14 +4352,45 @@ fn note_pso_rs(pso: *mut c_void, rs: *mut c_void) { } } -/// user SGPRs of the console CS of a translated compute pipeline -static PSO_USER_SGPRS: Mutex<Option<HashMap<usize, u32>>> = Mutex::new(None); +/// user SGPRs and the console's `numthreads` of the console CS of a translated compute pipeline +static PSO_USER_SGPRS: Mutex<Option<HashMap<usize, (u32, [u32; 3])>>> = Mutex::new(None); +static PSO_DISPATCH_REMAP: Mutex<Option<HashMap<usize, (u32, u32)>>> = Mutex::new(None); /// How many user SGPRs the console compute shader of a translated pipeline has (None: not /// known). What is above the driver's four holds root arguments (`console_list::inline_for`). pub fn pso_user_sgprs(pso: usize) -> Option<u32> { let pso = super::pso_async::resolve(pso); - PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).copied() + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.0) +} + +/// The console's group shape (`numthreads`) of a translated compute pipeline (None: not known). +pub fn pso_threads(pso: usize) -> Option<[u32; 3]> { + let pso = super::pso_async::resolve(pso); + PSO_USER_SGPRS.lock().unwrap().as_ref()?.get(&pso).map(|e| e.1) +} + +/// (tests) A translated compute pipeline with this console group shape. +#[cfg(test)] +pub(crate) fn register_threads_for_test(pso: usize, threads: [u32; 3]) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(pso, (0, threads)); +} + +pub fn pso_dispatch_remap(pso: usize) -> Option<(u32, u32)> { + let pso = super::pso_async::resolve(pso); + PSO_DISPATCH_REMAP.lock().unwrap().as_ref()?.get(&pso).copied() +} + +fn note_pso_dispatch_remap(pso: *mut c_void, remap: Option<(u32, u32)>) { + if pso.is_null() { + return; + } + let mut guard = PSO_DISPATCH_REMAP.lock().unwrap(); + let map = guard.get_or_insert_with(HashMap::new); + if let Some(remap) = remap { + map.insert(pso as usize, remap); + } else { + map.remove(&(pso as usize)); + } } /// The root signature a translated pipeline state was created with. @@ -3898,15 +4399,15 @@ pub fn pso_root_signature(pso: usize) -> Option<usize> { PSO_RS.lock().unwrap().as_ref()?.get(&pso).copied() } -/// ABI root signatures with static samplers, by sampler set (owned here, never released). -static ABI_RS_SAMPLERS: Mutex<Option<HashMap<Vec<u32>, usize>>> = Mutex::new(None); +/// ABI root signatures with static samplers, by device and sampler set (owned here, never released). +static ABI_RS_SAMPLERS: Mutex<Option<HashMap<(usize, Vec<u32>), usize>>> = Mutex::new(None); /// The XCL ABI root signature with a pipeline's static samplers (the plain one without). unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::StaticSampler]) -> Option<*mut c_void> { if samplers.is_empty() { return abi_rs_raw(this); } - let key: Vec<u32> = samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect(); + let key = (this as usize, samplers.iter().flat_map(|(w, c)| w.iter().copied().chain([*c as u32])).collect::<Vec<_>>()); let mut g = ABI_RS_SAMPLERS.lock().unwrap(); let map = g.get_or_insert_with(HashMap::new); if let Some(&rs) = map.get(&key) { @@ -3926,23 +4427,28 @@ unsafe fn abi_rs_for(this: *mut c_void, samplers: &[crate::gpu::recomp::pso::Sta } } -/// XCL ABI root signature, created once on the backend device. +/// XCL ABI root signature, created once per backend device. unsafe fn abi_rs_raw(this: *mut c_void) -> Option<*mut c_void> { + let dev_raw = this as usize; let cur = ABI_RS.load(Ordering::Acquire); - if cur != 0 { + if cur != 0 && ABI_RS_DEV.load(Ordering::Acquire) == dev_raw { return Some(cur as *mut c_void); } + let mut roots = ABI_RS_BY_DEV.lock().unwrap(); + if let Some(&cached) = roots.as_ref().and_then(|m| m.get(&dev_raw)) { + return Some(cached as *mut c_void); + } let dev = ID3D12Device::from_raw_borrowed(&this)?; match crate::gpu::recomp::pso::abi_root_signature(dev, true) { Ok(rs) => { let raw = rs.into_raw(); - match ABI_RS.compare_exchange(0, raw as usize, Ordering::AcqRel, Ordering::Acquire) { - Ok(_) => Some(raw), - Err(other) => { - drop(ID3D12RootSignature::from_raw(raw)); - Some(other as *mut c_void) - } + if ABI_RS.load(Ordering::Acquire) == 0 { + ABI_RS_DEV.store(dev_raw, Ordering::Release); + ABI_RS.store(raw as usize, Ordering::Release); + } else { + roots.get_or_insert_with(HashMap::new).insert(dev_raw, raw as usize); } + Some(raw) } Err(e) => { note_translation_error(format!("XCL ABI root signature: {e}")); @@ -4020,6 +4526,23 @@ impl Drop for SlotGuard { } static BIG_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 0, wanted_most: 0 }; +const AMD_MEDIUM_COMPUTE: usize = 128 << 10; +const MEDIUM_COMPUTE_END: usize = 256 << 10; +static MEDIUM_COMPILES: LazyLock<Slots> = LazyLock::new(|| { + let (default_most, default_wanted_most) = medium_pso_defaults(total_physical_ram()); + let most = env_count(std::env::var("XCL_MEDIUM_PSO_CONCURRENCY").ok().as_deref(), default_most, 1, 64); + Slots { + n: Mutex::new(0), + cv: std::sync::Condvar::new(), + most, + wanted_most: env_count( + std::env::var("XCL_MEDIUM_PSO_WANTED_CONCURRENCY").ok().as_deref(), + default_wanted_most.max(most), + most, + 64, + ), + } +}); const GIANT_DRIVER_COMPILE: usize = 4 << 20; static GIANT_COMPILES: Slots = Slots { n: Mutex::new(0), cv: std::sync::Condvar::new(), most: 1, wanted_most: 1 }; @@ -4027,11 +4550,32 @@ fn compile_slots(bytes: usize) -> &'static Slots { if bytes >= GIANT_DRIVER_COMPILE { &GIANT_COMPILES } else { &BIG_COMPILES } } +fn total_physical_ram() -> Option<u64> { + use windows_sys::Win32::System::SystemInformation::{GlobalMemoryStatusEx, MEMORYSTATUSEX}; + let mut m: MEMORYSTATUSEX = unsafe { std::mem::zeroed() }; + m.dwLength = std::mem::size_of::<MEMORYSTATUSEX>() as u32; + (unsafe { GlobalMemoryStatusEx(&mut m) } != 0).then_some(m.ullTotalPhys) +} + +fn medium_pso_defaults(total_phys: Option<u64>) -> (usize, usize) { + if total_phys.is_some_and(|n| n < 32u64 << 30) { (2, 3) } else { (3, 4) } +} + +/// AMD's compiler takes tens of seconds and over 1 GiB per cold 128–256 KiB compute PSO. +/// Keep that AMD-only class separate from the existing >=256 KiB gate: graphics and other +/// vendors retain their current parallelism, while a multi-minute huge compile cannot block it. +fn medium_compute_compile(kind: &str, bytes: usize, huge_bytes: usize, vendor: u32) -> bool { + vendor == 0x1002 + && (kind == "compute" || kind == "compute retry") + && bytes >= AMD_MEDIUM_COMPUTE + && bytes < huge_bytes.min(MEDIUM_COMPUTE_END) +} + /// A driver compile of `bytes` of DXIL through `build`: a huge one on an `xcl-pso*` worker /// waits for its slot first (`big_compile_turn`; not a title thread's, nor one the title waits /// for). Logs its time, size and whether it was gated. fn driver_compile<R>(kind: &str, bytes: usize, gate: bool, build: impl FnOnce() -> R) -> R { - driver_compile_identified(kind, bytes, gate, None, build).0 + driver_compile_identified(kind, bytes, gate, None, false, build).0 } /// `XCL_PSO_TRACE=1`: every driver compile is logged, not only huge ones. @@ -4040,28 +4584,49 @@ fn pso_trace() -> bool { *V.get_or_init(|| std::env::var("XCL_PSO_TRACE").is_ok_and(|v| v.trim() == "1")) } -/// `driver_compile`, with the console record's hash (`fnv64` of the shader container, as in -/// `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. +/// `driver_compile`, with the optional console record hash (`fnv64` of the shader container, +/// as in `[SHADER]` lines and `xcl shaders --measure-pso`) and whether a driver blob was supplied. /// Also returns the time spent in the driver alone (not waiting for a slot). -fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Option<(u64, bool)>, build: impl FnOnce() -> R) -> (R, std::time::Duration) { - let huge = gate && bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); +fn driver_compile_identified<R>(kind: &str, bytes: usize, gate: bool, record: Option<u64>, cached: bool, build: impl FnOnce() -> R) -> (R, std::time::Duration) { + let huge_bytes = huge_pso_bytes(); + let worker = std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let medium = gate && worker && medium_compute_compile(kind, bytes, huge_bytes, ADAPTER_VENDOR.load(Ordering::Acquire)); + let huge = gate && worker && bytes >= huge_bytes; + let gated = medium || huge; let waited = std::time::Instant::now(); - let _slot = huge.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let gate_stall = gated.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); + let _slot = gated.then(|| { + let _waiting = DRIVER_BUILDS.waiting(); + let slots = if medium { &*MEDIUM_COMPILES } else { compile_slots(bytes) }; + big_compile_turn(slots, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) + }); + drop(gate_stall); let waited = waited.elapsed(); static SEQUENCE: AtomicU64 = AtomicU64::new(0); let sequence = SEQUENCE.fetch_add(1, Ordering::Relaxed) + 1; - let log = pso_trace() || bytes >= huge_pso_bytes(); + let log = pso_trace() || bytes >= huge_bytes || medium; if log { - let record = record.map_or_else(String::new, |(hash, cached)| { - format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }) - }); + let record = record.map_or_else( + || if cached { ", driver blob supplied".to_string() } else { String::new() }, + |hash| format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }), + ); crate::xlog_info!("D3D12.X: driver compile start #{sequence}: {kind} PSO, {bytes} B DXIL{record}"); } let started = std::time::Instant::now(); + let _blob = BlobSupplied::set(cached); let r = build(); let took = started.elapsed(); if log { - crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_pso_bytes(), huge, waited)); + crate::xlog_info!("D3D12.X: driver compile finish #{sequence}: {kind} PSO, {bytes} B DXIL, {} ms{}", took.as_millis(), gate_note(bytes >= huge_bytes || medium, gated, waited)); + } else if took >= std::time::Duration::from_secs(1) { + // a slow one below the huge size, logged without XCL_PSO_TRACE too (a title thread's + // graphics pipelines took 2 - 5 s each, unlogged) + let record = record.map_or_else( + || if cached { ", driver blob supplied".to_string() } else { String::new() }, + |hash| format!(", record {hash:016x}, driver blob {}", if cached { "supplied" } else { "absent" }), + ); + let thread = std::thread::current().name().unwrap_or("title").to_string(); + crate::xlog_info!("D3D12.X: slow driver compile #{sequence}: {kind} PSO, {bytes} B DXIL{record}, {} ms on {thread}", took.as_millis()); } (r, took) } @@ -4091,6 +4656,7 @@ fn gate_compute_driver_compile(has_cached_blob: bool) -> bool { fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wanted: impl Fn() -> bool) -> SlotGuard { const LOOK: std::time::Duration = std::time::Duration::from_millis(50); let mut n = slots.n.lock().unwrap(); + let mut parked = None; loop { let is_wanted = wanted(); let cap = if is_wanted { slots.wanted_most() } else { slots.most() }; @@ -4098,6 +4664,9 @@ fn big_compile_turn(slots: &'static Slots, commit_free: impl Fn() -> bool, wante *n += 1; return SlotGuard(slots); } + if parked.is_none() { + parked = Some(super::pso_async::parked_for_big_compile()); + } n = slots.cv.wait_timeout(n, LOOK).unwrap().0; } } @@ -4223,12 +4792,73 @@ mod big_compile_tests { assert!(gate_note(true, false, ms).contains("ungated here")); } + #[test] + fn driver_builds_count_while_running_and_once_done() { + let b = DriverBuilds::new(); + { + let _one = b.building(); + let _two = b.building(); + let _wait = b.waiting(); + assert_eq!(b.counts(), (2, 1, 0)); + } + assert_eq!(b.counts(), (0, 0, 2), "a wait is not a build"); + } + + unsafe extern "system" fn counting_driver(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + // the global counter: other tests' builds can run too, so at least this one + if DRIVER_BUILDS.counts().0 >= 1 { S_OK } else { S_FALSE } + } + + unsafe extern "system" fn blob_driver(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { + if BLOB_SUPPLIED.with(|b| b.get()) { S_OK } else { S_FALSE } + } + + #[test] + fn every_driver_call_is_counted_and_a_blob_load_is_not() { + let done = DRIVER_BUILDS.counts().2; + let call = |f: PsoFn| unsafe { driver_pso(f, std::ptr::null_mut(), std::ptr::null(), std::ptr::null(), std::ptr::null_mut()) }; + assert_eq!(call(counting_driver), S_OK, "counted while in the driver"); + assert!(DRIVER_BUILDS.counts().2 > done); + // a compile given a driver blob reaches the driver as a load; a cold one does not + assert_eq!(driver_compile_identified("test", 1, false, Some(1), true, || call(blob_driver)).0, S_OK); + assert_eq!(driver_compile_identified("test", 1, false, Some(1), false, || call(blob_driver)).0, S_FALSE); + assert_eq!(driver_compile_identified("two-pass test", 1, false, None, true, || call(blob_driver)).0, S_OK, + "a cache hit without a console record is still a driver-blob load"); + let _ = std::panic::catch_unwind(|| driver_compile_identified("panic test", 1, false, None, true, || panic!("driver panic"))); + assert!(!BLOB_SUPPLIED.with(|b| b.get()), "reset after the call"); + } + #[test] fn giant_driver_compiles_have_their_own_lane() { assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE - 1), &BIG_COMPILES)); assert!(std::ptr::eq(compile_slots(GIANT_DRIVER_COMPILE), &GIANT_COMPILES)); } + #[test] + fn medium_compute_class_is_amd_only_and_respects_the_huge_override() { + let amd = 0x1002; + let nvidia = 0x10de; + assert!(!medium_compute_compile("compute", AMD_MEDIUM_COMPUTE - 1, 256 << 10, amd)); + assert!(medium_compute_compile("compute", AMD_MEDIUM_COMPUTE, 256 << 10, amd)); + assert!(medium_compute_compile("compute retry", 217 << 10, 256 << 10, amd)); + assert!(!medium_compute_compile("compute", MEDIUM_COMPUTE_END, 256 << 10, amd)); + assert!(!medium_compute_compile("graphics", 180 << 10, 256 << 10, amd)); + assert!(!medium_compute_compile("compute", 180 << 10, 256 << 10, nvidia)); + assert!(!medium_compute_compile("compute", 180 << 10, 128 << 10, amd), + "a lower XCL_HUGE_PSO_BYTES routes this size through the existing huge lane"); + assert!(!std::ptr::eq(&*MEDIUM_COMPILES, &BIG_COMPILES), + "medium compute must not occupy the existing huge slot"); + } + + #[test] + fn medium_compute_concurrency_scales_down_below_32_gib() { + assert_eq!(medium_pso_defaults(Some(16u64 << 30)), (2, 3)); + assert_eq!(medium_pso_defaults(Some((32u64 << 30) - 1)), (2, 3)); + assert_eq!(medium_pso_defaults(Some(32u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(Some(64u64 << 30)), (3, 4)); + assert_eq!(medium_pso_defaults(None), (3, 4)); + } + #[test] fn only_a_cold_compute_compile_takes_a_slot() { assert!(!gate_compute_driver_compile(true), "the cached-blob attempt bypasses the gate"); @@ -4344,7 +4974,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const let record = crate::gpu::shader::fnv64(cs); let warm = compiled.dispatch_chain.as_ref().and_then(|_| { let rs = abi_rs_for(this, &compiled.samplers)?; - let result = compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::CachedWhole); + let result = compute_container(this, f, d, rs, &dxil, &compiled.samplers, record, riid, ppv, ComputeBuild::CachedWhole); (result.0 >= 0).then_some((rs, result)) }); if let Some(plan) = compiled.dispatch_chain.filter(|_| warm.is_none()) { @@ -4352,8 +4982,8 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const LAST_COMPUTE_RS.with(|c| c.set(rs)); note_pso_rs(*ppv, rs as *mut c_void); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } note_translated_compute(0, ppv); TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); @@ -4364,7 +4994,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const Some(hit) => hit, None => { let Some(rs) = abi_rs_for(this, &compiled.samplers) else { return Some(Err(())) }; - (rs, compute_container(this, f, d, rs, &dxil, record, riid, ppv, ComputeBuild::Whole)) + (rs, compute_container(this, f, d, rs, &dxil, &compiled.samplers, record, riid, ppv, ComputeBuild::Whole)) } }; LAST_COMPUTE_RS.with(|c| c.set(rs as usize)); @@ -4379,7 +5009,7 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const crate::xlog_warn!( "D3D12.X: the driver refused the compute PSO of record {record:016x} ({} B DXIL, driver cache {}) with {hr:#x} after {} ms in the driver: its dispatches are skipped", dxil.len(), - driver_cache::name(&dxil, d.Flags.0), + driver_cache::name_for_root_node(&dxil, d.Flags.0, false, &compiled.samplers, d.NodeMask), in_driver.as_millis() ); } @@ -4389,9 +5019,12 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); note_pso_rs(*ppv, rs); super::dred::label(*ppv as usize, &[("cs", Some(cs))]); - if let Some(n) = crate::gpu::recomp::pso::compute_user_sgprs(cs) { - PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, n); + if let Some(i) = crate::gpu::recomp::pso::compute_interface(cs) { + PSO_USER_SGPRS.lock().unwrap().get_or_insert_with(HashMap::new).insert(*ppv as usize, (i.user_sgprs, i.threads)); } + note_pso_dispatch_remap(*ppv, compiled.dispatch_remap); + remap_fallback::note(*ppv as usize, this, f, rs as usize, &compiled.samplers, d.Flags, d.NodeMask, record, cs, + wave32_only(this), crate::gpu::recomp::pso::mem_windows(), compiled.dispatch_remap.is_some()); note_translated_compute(hr, ppv); crate::xlog_info!( "D3D12.X: compute PSO with the translated console CS ({} B DXIL, {} ms{})", @@ -4404,6 +5037,82 @@ unsafe fn translated_compute_pso_once(this: *mut c_void, f: PsoFn, desc: *const pub(super) mod dispatch_chain; pub(crate) use dispatch_chain::log_counts as log_dispatch_chain_counts; +pub(crate) use dispatch_chain::earlier_indirect_used as earlier_indirect_split_records; +pub(crate) use dispatch_chain::flush_indirect_used as flush_indirect_split_records; +pub(crate) use dispatch_chain::shutdown_indirect_used as shutdown_indirect_split_records; + +pub(super) mod remap_fallback { + use super::*; + use std::sync::{Arc, LazyLock}; + + struct Fallback { + device: ID3D12Device, + create: PsoFn, + signature: ID3D12RootSignature, + samplers: Vec<crate::gpu::recomp::pso::StaticSampler>, + flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, + record: u64, + cs: Vec<u8>, + split_wave64: bool, + windows: u32, + whole: dispatch_chain::WholeBuild<ID3D12PipelineState>, + } + + static FALLBACKS: LazyLock<Mutex<HashMap<usize, Arc<Fallback>>>> = LazyLock::new(Default::default); + + pub(super) fn compile_error_hr(err: &str) -> HRESULT { + if crate::gpu::recomp::dxc::is_oom_error(err) { E_OUTOFMEMORY } else { E_INVALIDARG } + } + + pub(super) unsafe fn note(pso: usize, this: *mut c_void, create: PsoFn, rs: usize, + samplers: &[crate::gpu::recomp::pso::StaticSampler], flags: D3D12_PIPELINE_STATE_FLAGS, + node: u32, record: u64, cs: &[u8], split_wave64: bool, windows: u32, remapped: bool) { + if remapped && pso != 0 { + let Some(device) = ID3D12Device::from_raw_borrowed(&this) else { return }; + let raw_rs = rs as *mut c_void; + let Some(signature) = ID3D12RootSignature::from_raw_borrowed(&raw_rs) else { return }; + let old = FALLBACKS.lock().unwrap().insert(pso, Arc::new(Fallback { + device: device.clone(), create, signature: signature.clone(), samplers: samplers.to_vec(), flags, node, record, + cs: cs.to_vec(), split_wave64, windows, + whole: dispatch_chain::WholeBuild::new(), + })); + drop(old); + } + } + + pub(in crate::hle::d3d12x) unsafe fn whole(pso: usize) -> Result<ID3D12PipelineState, String> { + let pso = super::super::pso_async::resolve(pso); + let fb = FALLBACKS.lock().unwrap().get(&pso).cloned().ok_or("no remap fallback")?; + fb.whole.get_or_build(std::time::Instant::now(), || { + let status = Arc::new(std::sync::atomic::AtomicI32::new(E_INVALIDARG)); + let (job_fb, job_status) = (fb.clone(), status.clone()); + let raw = super::super::pso_async::build_foreground(Box::new(move || unsafe { + let dxil = match crate::gpu::recomp::pso::console_dxil_noremap(&job_fb.cs, job_fb.split_wave64, job_fb.windows) { + Ok(dxil) => dxil, + Err(e) => { + job_status.store(compile_error_hr(&e), Ordering::Release); + return 0 + } + }; + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: job_fb.node, Flags: job_fb.flags, ..Default::default() }; + let mut raw = std::ptr::null_mut(); + let (hr, _, _) = compute_container(job_fb.device.as_raw(), job_fb.create, &desc, + job_fb.signature.as_raw(), &dxil, &job_fb.samplers, job_fb.record, + &pc_iid(Kind::PipelineState), &mut raw, ComputeBuild::Whole); + job_status.store(hr, Ordering::Release); + if hr >= 0 { raw as usize } else { 0 } + })); + if raw != 0 { Ok(ID3D12PipelineState::from_raw(raw as *mut c_void)) } + else { Err(status.load(Ordering::Acquire)) } + }).map_err(|hr| format!("un-remapped compute pipeline ({hr:#x})")) + } + + pub(super) fn forget(pso: usize) { + let gone = FALLBACKS.lock().unwrap().remove(&pso); + drop(gone); + } +} #[derive(Clone, Copy, PartialEq)] enum ComputeBuild { @@ -4412,25 +5121,36 @@ enum ComputeBuild { // through to building the pieces, whose cold build is cheaper. CachedWhole, // The chain root signature has a separate on-disk namespace. - Chain, + DirectChain, + IndirectChain, } unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPELINE_STATE_DESC, rs: *mut c_void, - dxil: &[u8], record: u64, riid: *const GUID, ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { + dxil: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], record: u64, riid: *const GUID, + ppv: *mut *mut c_void, mode: ComputeBuild) -> (HRESULT, std::time::Duration, bool) { let mut copy: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::ptr::read(d); copy.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs); copy.CS = bytecode(dxil); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); // A program built again gets the driver's own result of its first build: a retail title // made 14 big compute pipelines twice while loading, 13 - 30 s each the second time. - let key = compute_blob_key(dxil, rs as usize, copy.Flags.0); + let key = compute_blob_key_for(dxil, rs as usize, copy.Flags.0, copy.NodeMask); let mut cached = compute_blob(key); // … and one built in an earlier run gets the blob kept on disk then (`driver_cache`) - let disk = driver_cache::path_for(dxil, copy.Flags.0, mode == ComputeBuild::Chain); + let disk = match mode { + ComputeBuild::DirectChain => driver_cache::path_for_chain_root_node( + dxil, copy.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, copy.NodeMask), + ComputeBuild::IndirectChain => driver_cache::path_for_chain_root_node( + dxil, copy.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, copy.NodeMask), + _ => driver_cache::path_for_root_node(dxil, copy.Flags.0, false, samplers, copy.NodeMask), + }; let from_disk = cached.is_none(); + let mut loaded = None; if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + loaded = disk.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } + let rejected_generation = cached.clone(); if let Some(b) = &cached { copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } else if mode == ComputeBuild::CachedWhole { @@ -4441,14 +5161,18 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL "compute", dxil.len(), gate_compute_driver_compile(cached.is_some()), - Some((record, cached.is_some())), + Some(record), + cached.is_some(), || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); + let mut persist_took = in_driver; if hr < 0 && cached.is_some() { // a blob the driver does not take (another root signature at the same address…): compiled - forget_compute_blob(key); + if let Some(expected) = rejected_generation.as_ref() { + forget_compute_blob_if(key, expected); + } if from_disk { - driver_cache::note(false, disk.as_deref()); + driver_cache::note(false, loaded.take()); } if mode == ComputeBuild::CachedWhole { return (hr, in_driver, false); @@ -4458,20 +5182,21 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL "compute retry", dxil.len(), gate_compute_driver_compile(false), - Some((record, false)), + Some(record), + false, || finish_pso(this, f, © as *const _ as *const c_void, riid, ppv), ); hr = retried; in_driver += took; + persist_took = took; } let reused = hr >= 0 && cached.is_some() && copy.CachedPSO.CachedBlobSizeInBytes != 0; if hr >= 0 && !reused { - keep_compute_blob(key, *ppv, dxil.len()); - if let (Some(p), Some(b)) = (disk.as_deref(), compute_blob(key)) { - driver_cache::keep(p, &b, in_driver); - } + keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, key, dxil.len(), disk.as_deref(), persist_took, + || read_pso_cached_blob(*ppv)); } else if reused && from_disk { - driver_cache::note(true, None); + COMPUTE_BLOBS.admit(key, cached.as_ref().unwrap().clone(), COMPUTE_BLOBS_MAX); + driver_cache::note(true, loaded.take()); } (hr, in_driver, reused) } @@ -4485,27 +5210,100 @@ unsafe fn compute_container(this: *mut c_void, f: PsoFn, d: &D3D12_COMPUTE_PIPEL /// again. A blob whose build took `KEEP` or longer is written under the hash of its DXIL and /// its flags (`<DXIL cache>\driver\`) and read when a later run has none in memory; the /// driver refuses the blob of another driver, adapter or root signature (the file is dropped -/// and the program compiled as before). `XCL_PSO_DISK_CACHE=0`: off. +/// and the program compiled as before). Off by default on AMD; `XCL_PSO_DISK_CACHE=1` forces +/// it on, and `XCL_PSO_DISK_CACHE=0` turns it off everywhere. pub(crate) mod driver_cache { + use crate::gpu::recomp::pso::StaticSampler; + use std::io::Read; + use std::os::windows::fs::OpenOptionsExt; + use std::os::windows::io::AsRawHandle; use std::path::{Path, PathBuf}; - use std::sync::atomic::{AtomicU64, Ordering}; + use std::sync::{Arc, Mutex}; + use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; /// builds shorter than this are not worth a file const KEEP: std::time::Duration = std::time::Duration::from_millis(250); static HITS: AtomicU64 = AtomicU64::new(0); static STALE: AtomicU64 = AtomicU64::new(0); static STORED: AtomicU64 = AtomicU64::new(0); + static REFERENCE_BLOBS: AtomicBool = AtomicBool::new(false); + static ACTIVE_KEEPS: Mutex<Option<std::collections::HashSet<PathBuf>>> = Mutex::new(None); + + /// Split pipelines with different root ABIs cannot share a persisted driver blob. + #[allow(dead_code)] + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum ChainRoot { + DirectConstants, + IndirectCbv, + } + + /// AMD's cached-PSO blobs name entries in the driver's own cache instead of containing + /// self-sufficient code. They are not safe to carry across runs unless explicitly enabled. + pub fn note_vendor(vendor: u32) { + let references = reference_blob_vendor(vendor); + let was = REFERENCE_BLOBS.fetch_or(references, Ordering::Relaxed); + if references && !was && !enabled() { + crate::xlog_info!("D3D12.X: driver-blob disk cache off on AMD (XCL_PSO_DISK_CACHE=1: force on)"); + } + } + + fn reference_blob_vendor(vendor: u32) -> bool { + vendor == 0x1002 + } /// The file of the pipeline made from `dxil` with `flags`. + #[cfg(test)] pub fn name(dxil: &[u8], flags: i32) -> String { name_for(dxil, flags, false) } - /// Like [`name`], using `.chain.pso` for pipelines built with the dispatch chain's root - /// signature (`dispatch_chain`). + /// The legacy empty-sampler name, using `.chain.pso` for the dispatch-chain root signature. + #[cfg(test)] pub fn name_for(dxil: &[u8], flags: i32, chained: bool) -> String { + name_for_root(dxil, flags, chained, &[]) + } + + /// The cache file for a pipeline whose fixed ABI root-signature layout has these ordered + /// static samplers. Empty samplers retain the existing name and cache compatibility. + pub fn name_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler]) -> String { + name_for_root_node(dxil, flags, chained, samplers, 0) + } + + /// Include the linked-adapter node in persisted driver state. Node zero keeps legacy names. + pub fn name_for_root_node(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler], node_mask: u32) -> String { let ext = if chained { "chain.pso" } else { "pso" }; - format!("{:016x}-{:x}-{:x}.{ext}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags) + name_for_root_node_with_ext(dxil, flags, samplers, node_mask, ext) + } + + /// The direct split ABI retains `.chain.pso`; the indirect-only CBV ABI has a separate + /// namespace so a driver blob can never be offered with the wrong root signature. + #[allow(dead_code)] + pub fn name_for_chain_root_node( + dxil: &[u8], flags: i32, root: ChainRoot, samplers: &[StaticSampler], node_mask: u32, + ) -> String { + let ext = match root { + ChainRoot::DirectConstants => "chain.pso", + ChainRoot::IndirectCbv => "indirect-chain.pso", + }; + name_for_root_node_with_ext(dxil, flags, samplers, node_mask, ext) + } + + fn name_for_root_node_with_ext( + dxil: &[u8], flags: i32, samplers: &[StaticSampler], node_mask: u32, ext: &str, + ) -> String { + let mut base = format!("{:016x}-{:x}-{:x}", crate::gpu::shader::fnv64(dxil), dxil.len(), flags); + if node_mask != 0 { + base += &format!("-n{node_mask:x}"); + } + if samplers.is_empty() { + return format!("{base}.{ext}"); + } + let bytes: Vec<u8> = samplers + .iter() + .flat_map(|(words, compare)| words.iter().copied().chain([u32::from(*compare)])) + .flat_map(u32::to_le_bytes) + .collect(); + format!("{base}-{:016x}-{:x}.{ext}", crate::gpu::shader::fnv64(&bytes), samplers.len()) } /// The file of a translated graphics pipeline keyed by its full state + shader digest. @@ -4513,37 +5311,131 @@ pub(crate) mod driver_cache { format!("gfx-{hash:016x}-{bytes:x}.pso") } + fn env_setting() -> Option<bool> { + static ON: std::sync::OnceLock<Option<bool>> = std::sync::OnceLock::new(); + *ON.get_or_init(|| configured(std::env::var("XCL_PSO_DISK_CACHE").ok().as_deref())) + } + + fn configured(value: Option<&str>) -> Option<bool> { + value.map(|v| v.trim() != "0") + } + + fn enabled_with(setting: Option<bool>, reference_blobs: bool) -> bool { + setting.unwrap_or(!reference_blobs) + } + fn enabled() -> bool { - static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var("XCL_PSO_DISK_CACHE").map_or(true, |v| v.trim() != "0")) + enabled_with(env_setting(), REFERENCE_BLOBS.load(Ordering::Relaxed)) } + #[cfg(test)] pub fn path(dxil: &[u8], flags: i32) -> Option<PathBuf> { path_for(dxil, flags, false) } + #[cfg(test)] pub fn path_for(dxil: &[u8], flags: i32, chained: bool) -> Option<PathBuf> { enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for(dxil, flags, chained))) } - pub fn graphics_path(hash: u64, bytes: usize) -> Option<PathBuf> { - enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) + pub fn path_for_root(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler]) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root(dxil, flags, chained, samplers))) } - pub fn load(p: &Path) -> Option<Vec<u8>> { - std::fs::read(p).ok().filter(|b| !b.is_empty()) + pub fn path_for_root_node(dxil: &[u8], flags: i32, chained: bool, samplers: &[StaticSampler], node_mask: u32) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(name_for_root_node(dxil, flags, chained, samplers, node_mask))) } - /// A pipeline was made from a kept blob (`ok`), or the driver refused the blob: dropped. - pub fn note(ok: bool, p: Option<&Path>) { + pub fn path_for_chain_root_node( + dxil: &[u8], flags: i32, root: ChainRoot, samplers: &[StaticSampler], node_mask: u32, + ) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver") + .join(name_for_chain_root_node(dxil, flags, root, samplers, node_mask))) + } + + pub fn graphics_path(hash: u64, bytes: usize) -> Option<PathBuf> { + enabled().then(|| crate::gpu::recomp::dxc::cache_dir().join("driver").join(graphics_name(hash, bytes))) + } + + /// Bytes read from one exact cache-file generation. Keeping its handle open lets a later + /// refusal dispose that file object without touching a replacement at the same pathname. + pub struct LoadedBlob { + bytes: Arc<Vec<u8>>, + /// `None` when the blob was readable but the cache entry could not be opened for deletion. + file: Option<std::fs::File>, + } + + impl LoadedBlob { + #[cfg(test)] + fn bytes(&self) -> &[u8] { &self.bytes } + pub fn shared(&self) -> Arc<Vec<u8>> { self.bytes.clone() } + + /// Remove the exact file object that supplied these bytes. If that operation is not + /// available, leave the stale entry rather than remove a pathname that may name another + /// process's newer replacement. + pub fn invalidate(self) -> bool { + use windows_sys::Win32::Storage::FileSystem::{ + SetFileInformationByHandle, + }; + let Some(file) = self.file else { return false }; + let handle = file.as_raw_handle() as windows_sys::Win32::Foundation::HANDLE; + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + set_disposition_with(|class, info, size| unsafe { + SetFileInformationByHandle(handle, class, info, size) != 0 + }) + } + } + + /// Prefer immediate POSIX unlinking, but filesystems which do not implement the extended + /// disposition class can still mark this exact open file object for deletion on close. + fn set_disposition_with(mut set: impl FnMut(i32, *const std::ffi::c_void, u32) -> bool) -> bool { + use windows_sys::Win32::Storage::FileSystem::{ + FileDispositionInfo, FileDispositionInfoEx, + FILE_DISPOSITION_FLAG_DELETE, FILE_DISPOSITION_FLAG_POSIX_SEMANTICS, + FILE_DISPOSITION_INFO, FILE_DISPOSITION_INFO_EX, + }; + let ex = FILE_DISPOSITION_INFO_EX { Flags: FILE_DISPOSITION_FLAG_DELETE | FILE_DISPOSITION_FLAG_POSIX_SEMANTICS }; + if set(FileDispositionInfoEx, (&ex as *const FILE_DISPOSITION_INFO_EX).cast(), std::mem::size_of_val(&ex) as u32) { + return true; + } + let basic = FILE_DISPOSITION_INFO { DeleteFile: true }; + set(FileDispositionInfo, (&basic as *const FILE_DISPOSITION_INFO).cast(), std::mem::size_of_val(&basic) as u32) + } + + pub fn load(p: &Path) -> Option<LoadedBlob> { + use windows_sys::Win32::Foundation::GENERIC_READ; + use windows_sys::Win32::Storage::FileSystem::{ + DELETE, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, + }; + let open = |access| { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::OpenOptions::new() + .read(true) + .access_mode(access) + .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(p) + }; + let (mut file, invalidatable) = open(GENERIC_READ | DELETE).map(|f| (f, true)) + .or_else(|_| open(GENERIC_READ).map(|f| (f, false))).ok()?; + let mut bytes = Vec::new(); + { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + file.read_to_end(&mut bytes).ok()?; + } + (!bytes.is_empty()).then(|| LoadedBlob { bytes: Arc::new(bytes), file: invalidatable.then_some(file) }) + } + + /// A pipeline was made from a kept blob (`ok`), or the driver refused that exact blob: dropped. + pub fn note(ok: bool, loaded: Option<LoadedBlob>) { if ok { let n = HITS.fetch_add(1, Ordering::Relaxed) + 1; if n.is_power_of_two() { crate::xlog_info!("D3D12.X: {n} compute pipelines made from the driver's blob of an earlier run (kept on disk)"); } } else { - if let Some(p) = p { - let _ = std::fs::remove_file(p); + if let Some(loaded) = loaded { + let _ = loaded.invalidate(); } if STALE.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_info!("D3D12.X: a driver blob kept on disk was refused (another driver or adapter?) – such pipelines are compiled again"); @@ -4559,7 +5451,11 @@ pub(crate) mod driver_cache { fn create_staging_file_with(p: &Path, next: &AtomicU64) -> std::io::Result<(PathBuf, std::fs::File)> { loop { let tmp = p.with_extension(format!("tmp{}-{}", std::process::id(), next.fetch_add(1, Ordering::Relaxed))); - match std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) { + let opened = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp) + }; + match opened { Ok(file) => return Ok((tmp, file)), // A prior process with this PID may have left a file behind. It is not ours. Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, @@ -4578,34 +5474,196 @@ pub(crate) mod driver_cache { let _ = std::fs::create_dir_all(dir); } let Ok((tmp, mut file)) = create_staging_file(p) else { return false }; - let written = file.write_all(bytes).is_ok(); + let written = { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + file.write_all(bytes).is_ok() + }; drop(file); - let ok = written && std::fs::rename(&tmp, p).is_ok(); + let ok = written && { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); + std::fs::rename(&tmp, p).is_ok() + }; if !ok { + let _stall = crate::stall::span(crate::stall::StallKind::CacheIo); let _ = std::fs::remove_file(&tmp); } ok } - /// Keep `blob`, of a build that took `took`, for the next run. - pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) { - if took >= KEEP && write(p, blob) { - let n = STORED.fetch_add(1, Ordering::Relaxed) + 1; - if n.is_power_of_two() { - crate::xlog_info!("D3D12.X: {n} driver blobs kept on disk for the next run (this one: {} ms, {} KB)", took.as_millis(), blob.len() >> 10); + /// Exclusive publication turn for one pathname within this process. Different in-memory + /// identities can share a disk key (notably compute root-signature pointers), so reserve the + /// pathname before capturing bytes as well as reserving the in-memory key. + pub(super) struct KeepTurn(PathBuf, std::time::Duration); + + impl KeepTurn { + pub(super) fn new(p: &Path, took: std::time::Duration) -> Option<Self> { + if took < KEEP { + return None; + } + let mut active = ACTIVE_KEEPS.lock().unwrap(); + active.get_or_insert_with(std::collections::HashSet::new).insert(p.to_owned()).then(|| Self(p.to_owned(), took)) + } + + pub(super) fn store(&self, blob: &[u8]) -> bool { + if write(&self.0, blob) { + let n = STORED.fetch_add(1, Ordering::Relaxed) + 1; + if n.is_power_of_two() { + crate::xlog_info!("D3D12.X: {n} driver blobs kept on disk for the next run (this one: {} ms, {} KB)", self.1.as_millis(), blob.len() >> 10); + } + true + } else { + false } } } + impl Drop for KeepTurn { + fn drop(&mut self) { + if let Some(active) = ACTIVE_KEEPS.lock().unwrap().as_mut() { + active.remove(&self.0); + } + } + } + + /// Keep `blob`, of a build that took `took`, for the next run. + #[cfg(test)] + pub fn keep(p: &Path, blob: &[u8], took: std::time::Duration) -> bool { + if let Some(turn) = KeepTurn::new(p, took) { + turn.store(blob) + } else { + false + } + } + #[cfg(test)] mod tests { use super::*; + fn load_bytes(p: &Path) -> Option<Vec<u8>> { + load(p).map(|b| b.bytes().to_vec()) + } + struct Directory(PathBuf); impl Drop for Directory { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } + #[test] + fn a_slow_blob_is_saved_after_the_memory_cache_fills() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-full-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("late.pso"); + let cache = DriverBlobs::new(); + keep_driver_blob(&cache, 4, 1u64, COMPUTE_BLOB_MIN_DXIL, None, KEEP, || Some(b"full".to_vec())); + keep_driver_blob(&cache, 4, 2u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || Some(b"late".to_vec())); + let guard = cache.blobs.lock().unwrap(); + let (map, total) = guard.as_ref().unwrap(); + assert_eq!((map.len(), *total), (1, 4)); + assert_eq!(map[&1].as_slice(), b"full"); + drop(guard); + assert_eq!(load_bytes(&path).as_deref(), Some(b"late".as_slice())); + } + + #[test] + fn concurrent_same_key_builders_publish_only_the_reserved_result() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + use std::sync::atomic::{AtomicUsize, Ordering}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("same.pso"); + let cache = Arc::new(DriverBlobs::new()); + let entered = Arc::new(std::sync::Barrier::new(2)); + let release = Arc::new(std::sync::Barrier::new(2)); + let reads = Arc::new(AtomicUsize::new(0)); + let worker = { + let (cache, entered, release, reads, path) = (cache.clone(), entered.clone(), release.clone(), reads.clone(), path.clone()); + std::thread::spawn(move || keep_driver_blob(&cache, 0, 7u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || { + reads.fetch_add(1, Ordering::Relaxed); + entered.wait(); + release.wait(); + Some(b"reserved".to_vec()) + })) + }; + entered.wait(); + keep_driver_blob(&cache, 0, 7u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP * 2, || { + reads.fetch_add(1, Ordering::Relaxed); + Some(b"duplicate".to_vec()) + }); + release.wait(); + worker.join().unwrap(); + assert_eq!(reads.load(Ordering::Relaxed), 1); + assert_eq!(load_bytes(&path).as_deref(), Some(b"reserved".as_slice())); + // The cap refused RAM admission, but a later duplicate still cannot replace the + // generation whose own duration and bytes were published. + keep_driver_blob(&cache, 0, 7u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP * 3, + || Some(b"later".to_vec())); + assert_eq!(load_bytes(&path).as_deref(), Some(b"reserved".as_slice())); + } + + #[test] + fn different_memory_keys_cannot_race_the_same_disk_path() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-path-race-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("shared.pso"); + let cache = Arc::new(DriverBlobs::new()); + let entered = Arc::new(std::sync::Barrier::new(2)); + let release = Arc::new(std::sync::Barrier::new(2)); + let worker = { + let (cache, entered, release, path) = (cache.clone(), entered.clone(), release.clone(), path.clone()); + std::thread::spawn(move || keep_driver_blob(&cache, 0, 1u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || { + entered.wait(); + release.wait(); + Some(b"path owner".to_vec()) + })) + }; + entered.wait(); + keep_driver_blob(&cache, 0, 2u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, + || Some(b"contender".to_vec())); + release.wait(); + worker.join().unwrap(); + assert_eq!(load_bytes(&path).as_deref(), Some(b"path owner".as_slice())); + } + + #[test] + fn capture_failure_can_retry_and_rejection_can_replace_the_generation() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-retry-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("retry.pso"); + let cache = DriverBlobs::new(); + keep_driver_blob(&cache, 0, 9u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || None); + keep_driver_blob(&cache, 0, 9u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || Some(b"old".to_vec())); + assert_eq!(load_bytes(&path).as_deref(), Some(b"old".as_slice())); + cache.forget(9); + keep_driver_blob(&cache, 0, 9u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP, || Some(b"fresh".to_vec())); + assert_eq!(load_bytes(&path).as_deref(), Some(b"fresh".as_slice())); + } + + #[test] + fn a_duplicate_duration_is_not_charged_to_an_existing_blob() { + use super::super::{keep_driver_blob, DriverBlobs, COMPUTE_BLOB_MIN_DXIL}; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-duration-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let path = dir.join("duration.pso"); + let cache = DriverBlobs::new(); + keep_driver_blob(&cache, 16, 3u64, COMPUTE_BLOB_MIN_DXIL, None, KEEP, || Some(b"first".to_vec())); + keep_driver_blob(&cache, 16, 3u64, COMPUTE_BLOB_MIN_DXIL, Some(&path), KEEP * 2, + || panic!("an existing blob must not be recaptured")); + assert!(!path.exists(), "another builder's duration must not persist the first builder's bytes"); + } + #[test] fn a_file_is_named_after_its_dxil_and_flags() { assert_eq!(name(b"abc", 0), name(b"abc", 0)); @@ -4618,24 +5676,142 @@ pub(crate) mod driver_cache { assert!(name_for(&[0u8; 0x1234], 2, true).ends_with("-1234-2.chain.pso")); } + #[test] + fn static_sampler_root_signatures_have_distinct_compatible_names() { + let wrap = ([0, 0, 0, 0], false); + let clamp_u = ([2, 0, 0, 0], false); + let comparison = (wrap.0, true); + let file = |chained, samplers: &[StaticSampler]| name_for_root(b"same dxil", 0, chained, samplers); + + assert_eq!(file(false, &[]), name_for(b"same dxil", 0, false), "empty sampler cache compatibility"); + assert_eq!(file(true, &[]), name_for(b"same dxil", 0, true), "empty chain cache compatibility"); + assert_ne!(file(false, &[]), file(false, &[wrap])); + assert_ne!(file(false, &[wrap]), file(false, &[clamp_u])); + assert_ne!(file(false, &[wrap]), file(false, &[comparison])); + assert_ne!(file(false, &[wrap, clamp_u]), file(false, &[clamp_u, wrap])); + assert_ne!(file(false, &[wrap]), file(true, &[wrap])); + } + + #[test] + fn linked_adapter_nodes_have_distinct_compatible_names() { + let legacy = name_for_root(b"same dxil", 3, false, &[]); + assert_eq!(legacy, name_for_root_node(b"same dxil", 3, false, &[], 0)); + assert_ne!(legacy, name_for_root_node(b"same dxil", 3, false, &[], 2)); + assert_ne!( + name_for_root_node(b"same dxil", 3, false, &[], 1), + name_for_root_node(b"same dxil", 3, false, &[], 2) + ); + } + + #[test] + fn direct_and_indirect_chain_roots_have_distinct_compatible_names() { + let direct = name_for_chain_root_node(b"same dxil", 3, ChainRoot::DirectConstants, &[], 0); + assert_eq!(direct, name_for_root_node(b"same dxil", 3, true, &[], 0)); + assert_ne!(direct, name_for_chain_root_node(b"same dxil", 3, ChainRoot::IndirectCbv, &[], 0)); + assert!(name_for_chain_root_node(b"same dxil", 3, ChainRoot::IndirectCbv, &[], 0) + .ends_with(".indirect-chain.pso")); + } + + #[test] + fn disk_blobs_default_off_only_for_amd_and_can_be_overridden() { + assert!(reference_blob_vendor(0x1002)); + assert!(!reference_blob_vendor(0x10de)); // NVIDIA + assert!(!reference_blob_vendor(0x8086)); // Intel + assert!(!reference_blob_vendor(0x1414)); // WARP + + assert!(!enabled_with(None, true)); + assert!(enabled_with(None, false)); + assert!(enabled_with(configured(Some("1")), true)); + assert!(!enabled_with(configured(Some(" 0 ")), false)); + assert_eq!(configured(None), None); + } + #[test] fn a_kept_blob_is_read_back_and_a_refused_one_is_dropped() { let dir = std::env::temp_dir().join(format!("xcl-driver-cache-test-{}", std::process::id())); let p = dir.join("driver").join(name(b"program", 0)); - assert_eq!(load(&p), None, "nothing kept yet"); + assert_eq!(load_bytes(&p), None, "nothing kept yet"); assert!(!write(&p, &[]), "an empty blob is not kept"); keep(&p, &[1, 2, 3], std::time::Duration::from_millis(10)); - assert_eq!(load(&p), None, "a build of milliseconds is not kept"); + assert_eq!(load_bytes(&p), None, "a build of milliseconds is not kept"); keep(&p, &[1, 2, 3], std::time::Duration::from_secs(1)); - assert_eq!(load(&p).as_deref(), Some(&[1u8, 2, 3][..])); + assert_eq!(load_bytes(&p).as_deref(), Some(&[1u8, 2, 3][..])); // no half file under the temporary name assert_eq!(std::fs::read_dir(p.parent().unwrap()).unwrap().count(), 1); // the driver took the blob: it stays; it refused it: gone, the program is compiled again - note(true, Some(&p)); + note(true, load(&p)); assert!(p.exists()); - note(false, Some(&p)); - assert_eq!(load(&p), None); + note(false, load(&p)); + assert_eq!(load_bytes(&p), None); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn an_older_process_cannot_remove_a_replacement_blob() { + const CHILD: &str = "XCL_DRIVER_CACHE_REPLACEMENT_CHILD"; + let bytes = b"same bytes in both generations"; + if let Some(path) = std::env::var_os(CHILD) { + assert!(write(&PathBuf::from(path), bytes), "replace the still-open old generation directly"); + return; + } + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-replace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let p = dir.join("program.pso"); + // Identical bytes make pathname/content comparisons unable to distinguish the two + // generations: the open file object is the identity that must protect the second. + assert!(write(&p, bytes)); + let delayed_reader = load(&p).unwrap(); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "hle::d3d12x::real::driver_cache::tests::an_older_process_cannot_remove_a_replacement_blob", "--nocapture"]) + .env(CHILD, &p) + .output() + .unwrap(); + assert!( + output.status.success(), + "replacement process failed:\n{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + assert!(delayed_reader.invalidate(), "the old generation can be disposed through its handle"); + assert_eq!(load_bytes(&p).as_deref(), Some(bytes.as_slice())); + } + + #[test] + fn a_blob_without_delete_access_fails_closed() { + let loaded = LoadedBlob { bytes: Arc::new(vec![1]), file: None }; + assert!(!loaded.invalidate()); + } + + #[test] + fn unsupported_posix_disposition_falls_back_to_exact_handle_deletion() { + use windows_sys::Win32::Storage::FileSystem::{FileDispositionInfo, FileDispositionInfoEx}; + let mut classes = Vec::new(); + assert!(set_disposition_with(|class, _, _| { + classes.push(class); + class == FileDispositionInfo + })); + assert_eq!(classes, [FileDispositionInfoEx, FileDispositionInfo]); + } + + #[test] + fn a_cache_symlink_never_disposes_its_target() { + use std::os::windows::fs::symlink_file; + let dir = std::env::temp_dir().join(format!("xcl-driver-cache-link-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir(&dir).unwrap(); + let _directory = Directory(dir.clone()); + let target = dir.join("outside.pso"); + let link = dir.join("cache.pso"); + std::fs::write(&target, b"not the cache entry").unwrap(); + if symlink_file(&target, &link).is_err() { + return; // creating symlinks can require Developer Mode or an elevated token + } + if let Some(loaded) = load(&link) { + let _ = loaded.invalidate(); + } + assert_eq!(std::fs::read(&target).unwrap(), b"not the cache entry"); } #[test] @@ -4649,11 +5825,11 @@ pub(crate) mod driver_cache { let (_other_tmp, mut other) = create_staging_file(&p).unwrap(); let complete = b"complete second blob"; assert!(write(&p, complete)); - assert_eq!(load(&p).as_deref(), Some(complete.as_slice())); + assert_eq!(load_bytes(&p).as_deref(), Some(complete.as_slice())); // Resuming the older writer must not change a file already published by this // invocation, even when the older payload is shorter than the newer one. other.write_all(b"old").unwrap(); - assert_eq!(load(&p).as_deref(), Some(complete.as_slice()), "published bytes must not alias another writer's staging file"); + assert_eq!(load_bytes(&p).as_deref(), Some(complete.as_slice()), "published bytes must not alias another writer's staging file"); } #[test] @@ -4672,36 +5848,145 @@ pub(crate) mod driver_cache { file.write_all(b"ours").unwrap(); drop(file); std::fs::rename(&tmp, &p).unwrap(); - assert_eq!(load(&p).as_deref(), Some(b"ours".as_slice())); + assert_eq!(load_bytes(&p).as_deref(), Some(b"ours".as_slice())); assert_eq!(std::fs::read(&occupied).unwrap(), b"not ours"); } } } +/// A bounded set of driver blobs plus capture/publication ownership for duplicate builders. +struct DriverBlobs<K> { + blobs: Mutex<Option<(HashMap<K, std::sync::Arc<Vec<u8>>>, usize)>>, + keeping: Mutex<Option<(HashSet<K>, HashMap<K, std::sync::Weak<Vec<u8>>>)>>, +} + +impl<K: Copy + Eq + std::hash::Hash> DriverBlobs<K> { + const fn new() -> Self { + Self { blobs: Mutex::new(None), keeping: Mutex::new(None) } + } + + fn get(&self, key: K) -> Option<std::sync::Arc<Vec<u8>>> { + self.blobs.lock().unwrap().as_ref().and_then(|(map, _)| map.get(&key).cloned()) + } + + fn reserve(&self, key: K) -> bool { + let blobs = self.blobs.lock().unwrap(); + if blobs.as_ref().is_some_and(|(map, _)| map.contains_key(&key)) { + return false; + } + let mut guard = self.keeping.lock().unwrap(); + let (active, persisted) = guard.get_or_insert_with(|| (HashSet::new(), HashMap::new())); + !persisted.contains_key(&key) && active.insert(key) + } + + /// Admit the exact disk generation accepted by the driver without copying it. Holding both + /// locks excludes a builder reservation between the presence check and insertion. + fn admit(&self, key: K, blob: std::sync::Arc<Vec<u8>>, limit: usize) -> bool { + let mut blobs = self.blobs.lock().unwrap(); + let mut keeping = self.keeping.lock().unwrap(); + let (active, persisted) = keeping.get_or_insert_with(|| (HashSet::new(), HashMap::new())); + if active.contains(&key) { + return false; + } + let (map, total) = blobs.get_or_insert_with(|| (HashMap::new(), 0)); + if map.contains_key(&key) || blob.len() > limit.saturating_sub(*total) { + return false; + } + *total += blob.len(); + persisted.insert(key, std::sync::Arc::downgrade(&blob)); + map.insert(key, blob); + true + } + + fn finish(&self, key: K, blob: Option<std::sync::Arc<Vec<u8>>>, limit: usize, persisted: bool) { + let mut generation = None; + if let Some(blob) = blob { + let mut guard = self.blobs.lock().unwrap(); + let (map, total) = guard.get_or_insert_with(|| (HashMap::new(), 0)); + if !map.contains_key(&key) && blob.len() <= limit.saturating_sub(*total) { + *total += blob.len(); + map.insert(key, blob); + generation = map.get(&key).map(std::sync::Arc::downgrade); + } + } + let mut guard = self.keeping.lock().unwrap(); + let (active, stored) = guard.as_mut().unwrap(); + active.remove(&key); + if persisted { + stored.insert(key, generation.unwrap_or_default()); + } + } + + /// Remove only the generation that a rejected lookup actually used. A builder may have + /// published a replacement under the same key while that driver call was in flight. + fn forget_if(&self, key: K, expected: &std::sync::Arc<Vec<u8>>) -> bool { + let removed = if let Some((map, total)) = self.blobs.lock().unwrap().as_mut() { + if map.get(&key).is_some_and(|blob| std::sync::Arc::ptr_eq(blob, expected)) { + let blob = map.remove(&key).unwrap(); + *total -= blob.len(); + true + } else { + false + } + } else { + false + }; + if removed { + if let Some((_, persisted)) = self.keeping.lock().unwrap().as_mut() { + if persisted.get(&key).and_then(std::sync::Weak::upgrade) + .is_some_and(|blob| std::sync::Arc::ptr_eq(&blob, expected)) + { + persisted.remove(&key); + } + } + } + removed + } + + #[cfg_attr(not(test), allow(dead_code))] + fn forget(&self, key: K) { + if let Some((map, total)) = self.blobs.lock().unwrap().as_mut() { + if let Some(blob) = map.remove(&key) { + *total -= blob.len(); + } + } + if let Some((_, persisted)) = self.keeping.lock().unwrap().as_mut() { + persisted.remove(&key); + } + } +} + /// The driver's compiled form of translated compute programs (`GetCachedBlob`), /// by (DXIL hash, root signature, flags), up to `COMPUTE_BLOBS_MAX` bytes in all. -static COMPUTE_BLOBS: Mutex<Option<(HashMap<(u64, usize, i32), std::sync::Arc<Vec<u8>>>, usize)>> = Mutex::new(None); +static COMPUTE_BLOBS: DriverBlobs<(u64, usize, i32)> = DriverBlobs::new(); const COMPUTE_BLOBS_MAX: usize = 512 << 20; /// smaller programs compile in milliseconds: not kept const COMPUTE_BLOB_MIN_DXIL: usize = 16 << 10; +#[cfg_attr(not(test), allow(dead_code))] fn compute_blob_key(dxil: &[u8], rs: usize, flags: i32) -> (u64, usize, i32) { + compute_blob_key_for(dxil, rs, flags, 0) +} + +fn compute_blob_key_for(dxil: &[u8], rs: usize, flags: i32, node_mask: u32) -> (u64, usize, i32) { use std::hash::{Hash, Hasher}; let mut h = std::collections::hash_map::DefaultHasher::new(); dxil.hash(&mut h); + node_mask.hash(&mut h); (h.finish(), rs, flags) } fn compute_blob(key: (u64, usize, i32)) -> Option<std::sync::Arc<Vec<u8>>> { - COMPUTE_BLOBS.lock().unwrap().as_ref().and_then(|(m, _)| m.get(&key).cloned()) + COMPUTE_BLOBS.get(key) } +#[cfg_attr(not(test), allow(dead_code))] fn forget_compute_blob(key: (u64, usize, i32)) { - if let Some((m, total)) = COMPUTE_BLOBS.lock().unwrap().as_mut() { - if let Some(b) = m.remove(&key) { - *total -= b.len(); - } - } + COMPUTE_BLOBS.forget(key); +} + +fn forget_compute_blob_if(key: (u64, usize, i32), expected: &std::sync::Arc<Vec<u8>>) -> bool { + COMPUTE_BLOBS.forget_if(key, expected) } #[cfg(test)] @@ -4759,22 +6044,98 @@ mod compute_blob_tests { let dxil = vec![7u8; 1000]; let key = super::compute_blob_key(&dxil, 0x1000, 0); assert_eq!(key, super::compute_blob_key(&dxil.clone(), 0x1000, 0)); + assert_eq!(key, super::compute_blob_key_for(&dxil, 0x1000, 0, 0)); + assert_ne!(key, super::compute_blob_key_for(&dxil, 0x1000, 0, 2)); assert_ne!(key, super::compute_blob_key(&dxil, 0x2000, 0)); assert_ne!(key, super::compute_blob_key(&dxil, 0x1000, 1)); let mut other = dxil.clone(); other[999] = 8; assert_ne!(key, super::compute_blob_key(&other, 0x1000, 0)); { - let mut g = super::COMPUTE_BLOBS.lock().unwrap(); + let mut g = super::COMPUTE_BLOBS.blobs.lock().unwrap(); let (m, total) = g.get_or_insert_with(|| (super::HashMap::new(), 0)); m.insert(key, std::sync::Arc::new(vec![1, 2, 3])); *total += 3; } assert_eq!(super::compute_blob(key).as_deref().map(|v| v.len()), Some(3)); - let before = super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1; + let before = super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1; super::forget_compute_blob(key); assert!(super::compute_blob(key).is_none()); - assert_eq!(super::COMPUTE_BLOBS.lock().unwrap().as_ref().unwrap().1, before - 3); + assert_eq!(super::COMPUTE_BLOBS.blobs.lock().unwrap().as_ref().unwrap().1, before - 3); + } + + #[test] + fn delayed_rejection_cannot_remove_a_replacement_generation() { + let cache = std::sync::Arc::new(super::DriverBlobs::new()); + assert!(cache.reserve(7u64)); + cache.finish(7, Some(std::sync::Arc::new(b"old".to_vec())), 32, false); + let old = cache.get(7).unwrap(); + let release = std::sync::Arc::new(std::sync::Barrier::new(2)); + let worker = { + let (cache, release, old) = (cache.clone(), release.clone(), old.clone()); + std::thread::spawn(move || { + release.wait(); + cache.forget_if(7, &old) + }) + }; + + // Another rejection removes the old value and a builder publishes its replacement + // before the delayed driver call reports its result. + cache.forget(7); + assert!(cache.reserve(7)); + let fresh = std::sync::Arc::new(b"fresh".to_vec()); + cache.finish(7, Some(fresh.clone()), 32, false); + release.wait(); + assert!(!worker.join().unwrap()); + assert!(std::sync::Arc::ptr_eq(&cache.get(7).unwrap(), &fresh)); + assert!(cache.forget_if(7, &fresh), "the exact generation remains invalidatable"); + } + + #[test] + fn concurrent_disk_admission_counts_one_exact_generation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + let cache = std::sync::Arc::new(super::DriverBlobs::new()); + let blob = std::sync::Arc::new(b"accepted".to_vec()); + let barrier = std::sync::Arc::new(std::sync::Barrier::new(9)); + let admitted = std::sync::Arc::new(AtomicUsize::new(0)); + let threads: Vec<_> = (0..8).map(|_| { + let (cache, blob, barrier, admitted) = + (cache.clone(), blob.clone(), barrier.clone(), admitted.clone()); + std::thread::spawn(move || { + barrier.wait(); + if cache.admit(11u64, blob, 32) { + admitted.fetch_add(1, Ordering::Relaxed); + } + }) + }).collect(); + barrier.wait(); + for thread in threads { + thread.join().unwrap(); + } + + assert_eq!(admitted.load(Ordering::Relaxed), 1); + let accepted = cache.get(11).unwrap(); + assert!(std::sync::Arc::ptr_eq(&accepted, &blob)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, blob.len()); + let other = std::sync::Arc::new(b"other".to_vec()); + assert!(!cache.forget_if(11, &other)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, blob.len()); + assert!(cache.forget_if(11, &accepted)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, 0); + assert!(cache.reserve(11), "exact invalidation also releases persisted ownership"); + cache.finish(11, None, 32, false); + } + + #[test] + fn active_builder_wins_over_disk_admission() { + let cache = super::DriverBlobs::new(); + assert!(cache.reserve(5u64)); + assert!(!cache.admit(5, std::sync::Arc::new(b"disk".to_vec()), 32)); + let built = std::sync::Arc::new(b"built".to_vec()); + cache.finish(5, Some(built.clone()), 32, false); + let kept = cache.get(5).unwrap(); + assert!(std::sync::Arc::ptr_eq(&kept, &built)); + assert_eq!(cache.blobs.lock().unwrap().as_ref().unwrap().1, built.len()); } } @@ -4801,51 +6162,41 @@ unsafe fn read_pso_cached_blob(pso: *mut c_void) -> Option<Vec<u8>> { (!bytes.is_empty()).then_some(bytes) } -/// The driver's blob of the PSO just built (works on both adopted title PSOs and raw PC compute -/// passes owned by `TwoPassPso`). -unsafe fn keep_compute_blob(key: (u64, usize, i32), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || compute_blob(key).is_some() { +/// Offer the exact result and duration of one successful build to the bounded RAM cache and, +/// when slow, the disk cache. One same-key owner captures and publishes at a time: another +/// completed builder cannot charge its duration to these bytes or overwrite them afterward. +fn keep_driver_blob<K: Copy + Eq + std::hash::Hash>( + cache: &DriverBlobs<K>, limit: usize, key: K, dxil_len: usize, + disk: Option<&std::path::Path>, took: std::time::Duration, read: impl FnOnce() -> Option<Vec<u8>>, +) { + if dxil_len < COMPUTE_BLOB_MIN_DXIL || !cache.reserve(key) { return; } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = COMPUTE_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > COMPUTE_BLOBS_MAX { + let keep_turn = disk.and_then(|path| driver_cache::KeepTurn::new(path, took)); + let Some(bytes) = read().filter(|bytes| !bytes.is_empty()) else { + cache.finish(key, None, limit, false); return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); + }; + let blob = std::sync::Arc::new(bytes); + // Publish to disk before exposing the blob through RAM: a concurrent consumer cannot reject + // this generation while its staging file is being renamed into place. + let persisted = keep_turn.as_ref().is_some_and(|turn| turn.store(&blob)); + cache.finish(key, Some(blob), limit, persisted); } /// The driver's compiled form of translated graphics pipelines (`GetCachedBlob`), -/// keyed by `(full_state_and_shader_hash, total_dxil_bytes)`, up to `GRAPHICS_BLOBS_MAX`. -static GRAPHICS_BLOBS: Mutex<Option<(HashMap<(u64, usize), std::sync::Arc<Vec<u8>>>, usize)>> = Mutex::new(None); +/// keyed by `(full_state_and_shader_hash, total_dxil_bytes, effective_root_signature)`, up to +/// `GRAPHICS_BLOBS_MAX`. The root address scopes RAM entries to the device; persisted paths are +/// already adapter-scoped and encode the root's static-sampler ABI in the state hash. +static GRAPHICS_BLOBS: DriverBlobs<(u64, usize, usize)> = DriverBlobs::new(); const GRAPHICS_BLOBS_MAX: usize = 256 << 20; -fn graphics_blob(key: (u64, usize)) -> Option<std::sync::Arc<Vec<u8>>> { - GRAPHICS_BLOBS.lock().unwrap().as_ref().and_then(|(m, _)| m.get(&key).cloned()) +fn graphics_blob(key: (u64, usize, usize)) -> Option<std::sync::Arc<Vec<u8>>> { + GRAPHICS_BLOBS.get(key) } -fn forget_graphics_blob(key: (u64, usize)) { - if let Some((m, total)) = GRAPHICS_BLOBS.lock().unwrap().as_mut() { - if let Some(b) = m.remove(&key) { - *total -= b.len(); - } - } -} - -unsafe fn keep_graphics_blob(key: (u64, usize), pso: *mut c_void, dxil_len: usize) { - if dxil_len < COMPUTE_BLOB_MIN_DXIL || pso.is_null() || graphics_blob(key).is_some() { - return; - } - let Some(bytes) = read_pso_cached_blob(pso) else { return }; - let mut g = GRAPHICS_BLOBS.lock().unwrap(); - let (m, total) = g.get_or_insert_with(|| (HashMap::new(), 0)); - if bytes.is_empty() || *total + bytes.len() > GRAPHICS_BLOBS_MAX { - return; - } - *total += bytes.len(); - m.insert(key, std::sync::Arc::new(bytes)); +fn forget_graphics_blob_if(key: (u64, usize, usize), expected: &std::sync::Arc<Vec<u8>>) -> bool { + GRAPHICS_BLOBS.forget_if(key, expected) } /// Deterministic FNV-1a digest of every field in a translated PC graphics PSO (shaders, static @@ -4855,7 +6206,7 @@ unsafe fn graphics_blob_key( copy: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, - rect_gs: Option<&[u8]>, + gs_dxil: Option<&[u8]>, samplers: &[crate::gpu::recomp::pso::StaticSampler], ) -> (u64, usize) { let mut h = 0xcbf2_9ce4_8422_2325u64; @@ -4877,7 +6228,7 @@ unsafe fn graphics_blob_key( } else { feed_u64(&mut h, 0); } - if let Some(gs) = rect_gs { + if let Some(gs) = gs_dxil { feed_u64(&mut h, crate::gpu::shader::fnv64(gs)); feed_u64(&mut h, gs.len() as u64); } else { @@ -4962,10 +6313,19 @@ unsafe fn graphics_blob_key( feed_u32(&mut h, copy.SampleDesc.Quality); feed_u32(&mut h, copy.NodeMask); feed_u32(&mut h, copy.Flags.0 as u32); - let total_bytes = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + rect_gs.map_or(0, <[u8]>::len); + let total_bytes = vs_dxil.len() + ps_dxil.map_or(0, <[u8]>::len) + gs_dxil.map_or(0, <[u8]>::len); (h, total_bytes) } +/// Stream-output declarations contain pointer-backed arrays that are not represented in the +/// graphics blob key. Keep those PSOs out of this cache rather than aliasing distinct layouts. +fn graphics_blob_cacheable(requested: bool, desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, gs_readable: bool) -> bool { + requested + && desc.StreamOutput.NumEntries == 0 + && desc.StreamOutput.NumStrides == 0 + && (desc.GS.BytecodeLength == 0 || gs_readable) +} + #[cfg(test)] mod graphics_blob_tests { use super::*; @@ -4991,6 +6351,22 @@ mod graphics_blob_tests { } } + #[test] + fn graphics_blob_cache_skips_pointer_backed_stream_output() { + let mut d = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + assert!(graphics_blob_cacheable(true, &d, false)); + assert!(!graphics_blob_cacheable(false, &d, false)); + d.StreamOutput.NumEntries = 1; + assert!(!graphics_blob_cacheable(true, &d, false)); + d.StreamOutput.NumEntries = 0; + d.StreamOutput.NumStrides = 1; + assert!(!graphics_blob_cacheable(true, &d, false)); + d.StreamOutput.NumStrides = 0; + d.GS.BytecodeLength = 4; + assert!(!graphics_blob_cacheable(true, &d, false), "an unreadable native GS has no safe key"); + assert!(graphics_blob_cacheable(true, &d, true)); + } + #[test] fn graphics_blob_key_ignores_struct_padding_bytes() { unsafe { @@ -5053,7 +6429,7 @@ mod graphics_blob_tests { |label, has_cached, f| { let hr = f(); attempts.push((label.to_string(), has_cached, hr)); - (hr, std::time::Duration::from_millis(1)) + (hr, std::time::Duration::from_millis(if has_cached { 300 } else { 2 })) }, |c| { // Driver rejects the stale CachedPSO, and accepts the fresh compile with rect GS intact. @@ -5070,6 +6446,8 @@ mod graphics_blob_tests { assert_eq!(stale_evicted, 1); assert!(!build.reused); assert!(build.cache_eligible, "fresh compile with rect GS intact should be cached"); + assert_eq!(build.built_in_driver, std::time::Duration::from_millis(2), + "a rejected cache lookup must not make a fast fresh build eligible for persistence"); assert!(!copy.GS.pShaderBytecode.is_null(), "stale cached blob must not strip rect GS"); assert!(copy.CachedPSO.pCachedBlob.is_null()); assert_eq!(attempts.len(), 2); @@ -5131,11 +6509,75 @@ mod graphics_blob_tests { assert!(!build.cache_eligible); assert!(!copy.GS.pShaderBytecode.is_null()); } + + #[test] + fn native_stream_drops_stale_cache_before_rect_gs_fallback() { + let mut with_gs = StreamOut::default(); + with_gs.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, b"vs"); + with_gs.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, b"gs"); + let mut without_gs = StreamOut::default(); + without_gs.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, b"vs"); + let mut stale = 0; + let mut attempts = Vec::new(); + let build = create_graphics_stream_cached( + &with_gs, + Some(&without_gs), + Some(b"stale blob"), + || stale += 1, + |_, cached, stream| { + let subs = stream_subobjects(&stream.0).unwrap(); + let gs = subs.iter().any(|(ty, _)| *ty == 5); + let has_blob = subs.iter().any(|(ty, _)| *ty == 19); + attempts.push((cached, has_blob, gs)); + let hr = if cached || gs { E_INVALIDARG } else { S_OK }; + (hr, std::time::Duration::from_millis(1)) + }, + ); + assert_eq!(build.hr, S_OK); + assert_eq!(stale, 1); + assert_eq!(attempts, [(true, true, true), (false, false, true), (false, false, false)]); + assert!(!build.cache_eligible, "the no-GS fallback has a different identity"); + assert!(!build.used_rect_gs); + } + + #[test] + fn native_stream_retries_only_cached_blob_refusals() { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, b"vs"); + for failure in [E_OUTOFMEMORY, 0x887a_0005u32 as i32, 0x8000_4005u32 as i32] { + let (mut calls, mut evictions) = (0, 0); + let build = create_graphics_stream_cached( + &stream, + None, + Some(b"blob"), + || evictions += 1, + |_, _, _| { calls += 1; (failure, std::time::Duration::ZERO) }, + ); + assert_eq!(build.hr, failure); + assert_eq!((calls, evictions), (1, 0), "{failure:#x} is not evidence of a stale blob"); + } + + for stale in [E_INVALIDARG, 0x887e_0001u32 as i32, 0x887e_0002u32 as i32] { + let (mut calls, mut evictions) = (0, 0); + let build = create_graphics_stream_cached( + &stream, + None, + Some(b"blob"), + || evictions += 1, + |_, cached, _| { + calls += 1; + (if cached { stale } else { E_OUTOFMEMORY }, std::time::Duration::ZERO) + }, + ); + assert_eq!(build.hr, E_OUTOFMEMORY, "the final retry HRESULT is preserved"); + assert_eq!((calls, evictions), (2, 1)); + } + } } struct GraphicsPsoBuild { hr: HRESULT, - in_driver: std::time::Duration, + built_in_driver: std::time::Duration, reused: bool, cache_eligible: bool, } @@ -5154,7 +6596,7 @@ fn create_graphics_pso_cached( // discarded first so the uncached retry compiles with `copy.GS` intact. let (hr, in_driver) = run("graphics", true, &mut || create(copy)); if hr >= 0 { - return GraphicsPsoBuild { hr, in_driver, reused: true, cache_eligible: false }; + return GraphicsPsoBuild { hr, built_in_driver: in_driver, reused: true, cache_eligible: false }; } on_stale_cache(); copy.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); @@ -5162,7 +6604,7 @@ fn create_graphics_pso_cached( let dropped_rect_gs = rect_gs && copy.GS.pShaderBytecode.is_null(); return GraphicsPsoBuild { hr: retried, - in_driver: in_driver + took, + built_in_driver: took, reused: false, cache_eligible: retried >= 0 && !dropped_rect_gs, }; @@ -5171,17 +6613,17 @@ fn create_graphics_pso_cached( let dropped_rect_gs = rect_gs && copy.GS.pShaderBytecode.is_null(); GraphicsPsoBuild { hr, - in_driver, + built_in_driver: in_driver, reused: false, cache_eligible: hr >= 0 && !dropped_rect_gs, } } -unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { - with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv)) +unsafe fn translated_graphics_pso(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, cacheable: bool) -> Option<HRESULT> { + with_switch_fallback(|| translated_graphics_pso_once(this, f, desc, riid, ppv, cacheable)) } -unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { +unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, cacheable: bool) -> Option<HRESULT> { use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; if !crate::gpu::shader::readable(desc as usize, std::mem::size_of::<D3D12_GRAPHICS_PIPELINE_STATE_DESC>()) { return None; @@ -5254,35 +6696,42 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const if debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash) { copy.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; } - let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + rect_gs.as_ref().map_or(0, Vec::len); - let gkey = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), rect_gs.as_deref(), &samplers); - let mut cached = graphics_blob(gkey); - let disk = driver_cache::graphics_path(gkey.0, gkey.1); + let final_gs = shader_bytes(©.GS); + let bytes = vs_dxil.len() + ps_dxil.as_ref().map_or(0, Vec::len) + final_gs.map_or(0, <[u8]>::len); + let disk_key = graphics_blob_key(©, &vs_dxil, ps_dxil.as_deref(), final_gs, &samplers); + let gkey = (disk_key.0, disk_key.1, rs as usize); + let cacheable = graphics_blob_cacheable(cacheable, ©, final_gs.is_some()); + let mut cached = cacheable.then(|| graphics_blob(gkey)).flatten(); + let disk = cacheable.then(|| driver_cache::graphics_path(disk_key.0, disk_key.1)).flatten(); let from_disk = cached.is_none(); + let mut loaded = None; if from_disk { - cached = disk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + loaded = disk.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); } + let rejected_generation = cached.clone(); let build = create_graphics_pso_cached( &mut copy, cached.as_deref().map(Vec::as_slice), rect_gs.is_some(), || { - forget_graphics_blob(gkey); + if let Some(expected) = rejected_generation.as_ref() { + forget_graphics_blob_if(gkey, expected); + } if from_disk { - driver_cache::note(false, disk.as_deref()); + driver_cache::note(false, loaded.take()); } }, - |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some((ps_hash, has_cached)), f), + |label, has_cached, f| driver_compile_identified(label, bytes, gate_compute_driver_compile(has_cached), Some(ps_hash), has_cached, f), |c| finish_pso(this, f, c as *const _ as *const c_void, riid, ppv), ); let hr = build.hr; - if build.cache_eligible { - keep_graphics_blob(gkey, *ppv, bytes); - if let (Some(p), Some(b)) = (disk.as_deref(), graphics_blob(gkey)) { - driver_cache::keep(p, &b, build.in_driver); - } + if cacheable && build.cache_eligible { + keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, gkey, bytes, disk.as_deref(), build.built_in_driver, + || read_pso_cached_blob(*ppv)); } else if build.reused && from_disk { - driver_cache::note(true, None); + GRAPHICS_BLOBS.admit(gkey, cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX); + driver_cache::note(true, loaded.take()); } if hr < 0 { note_translation_error(format!( @@ -5363,39 +6812,46 @@ unsafe fn translated_graphics_pso_once(this: *mut c_void, f: PsoFn, desc: *const // non-blocking pipeline creation (see `pso_async`) // --------------------------------------------------------------------------------------- +pub(in crate::hle::d3d12x) mod compute_build_key; + /// A pipeline description that owns what it points to (shader blobs, input layout and its /// semantic names), so a worker can build the pipeline after the title's memory is gone. -/// The root signature pointer is kept as is (the translated paths replace it). +/// The title's borrowed root signature is cleared; translated paths install XCL's ABI signature. #[allow(dead_code)] // the vectors only keep the copies alive enum OwnedDesc { - Compute(Box<D3D12_COMPUTE_PIPELINE_STATE_DESC>, Vec<Vec<u8>>), - Graphics(Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC>, Vec<Vec<u8>>, Vec<D3D12_INPUT_ELEMENT_DESC>, Vec<std::ffi::CString>), - Stream(Box<[usize; 2]>, Vec<u8>, Vec<Vec<u8>>), + Compute(Box<D3D12_COMPUTE_PIPELINE_STATE_DESC>, Vec<Arc<[u8]>>), + Graphics(Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC>, Vec<Arc<[u8]>>, Vec<D3D12_INPUT_ELEMENT_DESC>, Vec<std::ffi::CString>), + Stream(Box<[usize; 2]>, Vec<u8>, Vec<Arc<[u8]>>), } unsafe impl Send for OwnedDesc {} +// Every pointer in an `OwnedDesc` refers to immutable backing storage owned by the same value. +// The translated builders only read it, so one retained recipe may safely be shared. +unsafe impl Sync for OwnedDesc {} /// A hash of a pipeline's shaders in their order (never 0): what `pso_async` knows a used /// pipeline by in the next run. -pub(crate) fn shaders_key(blobs: &[Vec<u8>]) -> u64 { +pub(crate) fn shaders_key<T: AsRef<[u8]>>(blobs: &[T]) -> u64 { let mut h = 0xcbf2_9ce4_8422_2325u64; for b in blobs { - h = (h ^ crate::gpu::shader::fnv64(b)).wrapping_mul(0x0000_0100_0000_01b3); + h = (h ^ crate::gpu::shader::fnv64(b.as_ref())).wrapping_mul(0x0000_0100_0000_01b3); } h | 1 } #[cfg(test)] mod shaders_key_tests { + use std::sync::Arc; + #[test] fn a_key_follows_the_shaders_and_their_order_and_is_never_zero() { - let (a, b) = (vec![1u8, 2, 3], vec![4u8, 5]); + let (a, b): (Arc<[u8]>, Arc<[u8]>) = ([1u8, 2, 3].into(), [4u8, 5].into()); let key = super::shaders_key(&[a.clone(), b.clone()]); assert_eq!(key, super::shaders_key(&[a.clone(), b.clone()])); assert_ne!(key, super::shaders_key(&[b.clone(), a.clone()])); assert_ne!(key, super::shaders_key(&[a.clone()])); - assert_ne!(key, super::shaders_key(&[a, vec![4u8, 6]])); - assert_ne!(super::shaders_key(&[]), 0); + assert_ne!(key, super::shaders_key(&[a, [4u8, 6].into()])); + assert_ne!(super::shaders_key(&[] as &[Arc<[u8]>]), 0); } } @@ -5418,9 +6874,9 @@ impl OwnedDesc { } /// Copy a shader blob into `blobs` and point `b` at the copy. -unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec<Vec<u8>>) { +unsafe fn own_shader(b: &mut D3D12_SHADER_BYTECODE, blobs: &mut Vec<Arc<[u8]>>) { if let Some(bytes) = shader_bytes(b) { - blobs.push(bytes.to_vec()); + blobs.push(bytes.into()); let v = blobs.last().unwrap(); *b = bytecode(v); } else { @@ -5432,6 +6888,8 @@ unsafe fn own_compute(desc: *const c_void) -> Option<OwnedDesc> { let mut d: Box<D3D12_COMPUTE_PIPELINE_STATE_DESC> = Box::new(std::ptr::read(desc as *const D3D12_COMPUTE_PIPELINE_STATE_DESC)); let mut blobs = Vec::new(); own_shader(&mut d.CS, &mut blobs); + // Console translation installs its ABI root signature. Do not retain the title's borrowed one. + d.pRootSignature = std::mem::ManuallyDrop::new(None); d.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); Some(OwnedDesc::Compute(d, blobs)) } @@ -5439,13 +6897,18 @@ unsafe fn own_compute(desc: *const c_void) -> Option<OwnedDesc> { /// None with stream output (not copied; such pipelines are built in the call). unsafe fn own_graphics(desc: *const c_void) -> Option<OwnedDesc> { let mut d: Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC> = Box::new(std::ptr::read(desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC)); - if d.StreamOutput.NumEntries > 0 { + if d.StreamOutput.NumEntries > 0 || d.StreamOutput.NumStrides > 0 { return None; } + // Counts are zero, so the pointers are semantically unused; clear them rather than retain + // borrowed title addresses in an object declared safe to share and possibly reuse. + d.StreamOutput = D3D12_STREAM_OUTPUT_DESC::default(); let mut blobs = Vec::new(); for b in [&mut d.VS, &mut d.PS, &mut d.DS, &mut d.HS, &mut d.GS] { own_shader(b, &mut blobs); } + // Console translation installs its ABI root signature. Do not retain the title's borrowed one. + d.pRootSignature = std::mem::ManuallyDrop::new(None); let n = d.InputLayout.NumElements as usize; let mut elems = Vec::new(); let mut names = Vec::new(); @@ -5473,7 +6936,7 @@ unsafe fn own_stream(desc: *const c_void) -> Option<OwnedDesc> { return None; } let mut buf = std::slice::from_raw_parts(base as *const u8, size).to_vec(); - let mut blobs: Vec<Vec<u8>> = Vec::new(); + let mut blobs: Vec<Arc<[u8]>> = Vec::new(); let mut off = 0usize; while off + 8 <= size { let ty = u32::from_le_bytes(buf[off..off + 4].try_into().ok()?); @@ -5485,12 +6948,14 @@ unsafe fn own_stream(desc: *const c_void) -> Option<OwnedDesc> { } let word = |buf: &[u8], k: usize| u64::from_le_bytes(buf[at + 8 * k..at + 8 * k + 8].try_into().unwrap()); match ty { + // Translated streams install XCL's ABI root signature. + 0 => buf[at..end].fill(0), 1..=6 | 24 | 25 => { let (p, n) = (word(&buf, 0) as usize, word(&buf, 1) as usize); if p == 0 || n == 0 { buf[at..at + 16].fill(0); } else if crate::gpu::shader::readable(p, n) { - blobs.push(std::slice::from_raw_parts(p as *const u8, n).to_vec()); + blobs.push(std::slice::from_raw_parts(p as *const u8, n).into()); buf[at..at + 8].copy_from_slice(&(blobs.last().unwrap().as_ptr() as u64).to_le_bytes()); } else { return None; @@ -5506,11 +6971,44 @@ unsafe fn own_stream(desc: *const c_void) -> Option<OwnedDesc> { Some(OwnedDesc::Stream(d, buf, blobs)) } -/// Raw pointers a worker needs (the device lives for the process). +#[cfg(test)] +mod owned_desc_tests { + use super::*; + + #[test] + fn graphics_recipe_rejects_buffer_strides_without_declarations() { + let stride = 16u32; + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.StreamOutput.pBufferStrides = &stride; + desc.StreamOutput.NumStrides = 1; + desc.StreamOutput.NumEntries = 0; + assert!(unsafe { own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()) }.is_none()); + } + + #[test] + fn graphics_recipe_clears_unused_stream_output_pointers() { + let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC::default(); + desc.StreamOutput.pSODeclaration = std::ptr::NonNull::dangling().as_ptr(); + desc.StreamOutput.pBufferStrides = std::ptr::NonNull::dangling().as_ptr(); + let Some(OwnedDesc::Graphics(owned, ..)) = (unsafe { + own_graphics((&desc as *const D3D12_GRAPHICS_PIPELINE_STATE_DESC).cast()) + }) else { + panic!("zero-count stream output must be accepted") + }; + assert!(owned.StreamOutput.pSODeclaration.is_null()); + assert!(owned.StreamOutput.pBufferStrides.is_null()); + } +} + +/// Raw pointers a one-shot worker needs (the existing process-lifetime device invariant). #[derive(Clone, Copy)] -struct Dev(usize, usize); +struct Dev(usize, PsoFn); unsafe impl Send for Dev {} +/// A gated rebuild recipe owns a device reference independently of the title's references. +#[derive(Clone)] +struct RecipeDev(ID3D12Device, PsoFn); + /// The stand-in for a pipeline with dummy shaders (draws / computes nothing). unsafe fn standin_graphics(this: *mut c_void, f: PsoFn, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let d = dummy(); @@ -5629,22 +7127,31 @@ unsafe fn go_background( } return None; } - let dev = Dev(this as usize, f as usize); + let dev = Dev(this as usize, f); let key = owned.shaders_key(); + let build_key = match &owned { + OwnedDesc::Compute(desc, shaders) => shaders.first().map(|shader| { + compute_build_key::ComputeBuildKey::capture(this as usize, desc, shader.clone(), wave32_only(this)) + }), + _ => None, + }; // a big compute program that writes nothing but images: binds can go on without it let image_only = compute && super::pso_async::image_skip() && matches!(&owned, OwnedDesc::Compute(_, b) if b.first().is_some_and(|b| crate::gpu::effects::big_and_image_only(b))); - let job: super::pso_async::Job = Box::new(move || { - let mut out: *mut c_void = std::ptr::null_mut(); - if unsafe { build(dev, &owned, &mut out) } && !out.is_null() { - out as usize + let lazy = super::pso_async::lazy(); + if super::pso_async::rebuild_recipes_enabled() { + let recipe_dev = RecipeDev(ID3D12Device::from_raw_borrowed(&this)?.clone(), f); + let recipe = super::pso_async::Recipe::new(move || { + let dev = Dev(recipe_dev.0.as_raw() as usize, recipe_dev.1); + run_owned_build(dev, &owned, build) + }); + super::pso_async::submit_recipe_keyed(*ppv as usize, compute, recipe, !lazy, if lazy { key } else { 0 }, build_key); + } else { + let job: super::pso_async::Job = Box::new(move || run_owned_build(dev, &owned, build)); + if lazy { + super::pso_async::submit_lazy_keyed(*ppv as usize, compute, job, key, build_key); } else { - 0 + super::pso_async::submit_keyed(*ppv as usize, compute, job, build_key); } - }); - if super::pso_async::lazy() { - super::pso_async::submit_lazy(*ppv as usize, compute, job, key); - } else { - super::pso_async::submit(*ppv as usize, compute, job); } if driver != 0 { super::pso_async::shared(*ppv as usize, driver); @@ -5655,35 +7162,48 @@ unsafe fn go_background( Some(hr) } +fn run_owned_build(dev: Dev, owned: &OwnedDesc, build: unsafe fn(Dev, &OwnedDesc, *mut *mut c_void) -> bool) -> usize { + let mut out: *mut c_void = std::ptr::null_mut(); + if unsafe { build(dev, owned, &mut out) } && !out.is_null() { out as usize } else { 0 } +} + unsafe fn build_graphics(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_graphics_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out), Some(hr) if hr >= 0) + matches!(translated_graphics_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out, true), Some(hr) if hr >= 0) +} + +unsafe fn build_graphics_uncacheable(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { + let iid = pc_iid(Kind::PipelineState); + matches!(translated_graphics_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out, false), Some(hr) if hr >= 0) } unsafe fn build_compute(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_compute_pso(dev.0 as *mut c_void, std::mem::transmute::<usize, PsoFn>(dev.1), d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) + matches!(translated_compute_pso(dev.0 as *mut c_void, dev.1, d.ptr(), &iid, out), Some(Ok(hr)) if hr >= 0) } unsafe fn build_stream(dev: Dev, d: &OwnedDesc, out: *mut *mut c_void) -> bool { let iid = pc_iid(Kind::PipelineState); - matches!(translated_mesh_stream(dev.0 as *mut c_void, d.ptr(), &iid, out), Some(hr) if hr >= 0) + let this = dev.0 as *mut c_void; + let hr = translated_mesh_stream(this, d.ptr(), &iid, out).or_else(|| translated_graphics_stream(this, d.ptr(), &iid, out)); + matches!(hr, Some(hr) if hr >= 0) } pub(super) unsafe extern "system" fn dev_create_graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { - graphics_pso(this, desc, riid, ppv, false) + graphics_pso(this, desc, riid, ppv, false, true) } /// `dev_create_graphics_pso`; `stream`: the desc is a pipeline stream's (`stream_pipeline`). -unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool) -> HRESULT { +unsafe fn graphics_pso(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void, stream: bool, cacheable: bool) -> HRESULT { super::null::capture_graphics_desc(desc as *const u8); let f: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateGraphicsPipelineState"))); - let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv)) } else { (translated_graphics_pso(this, f, desc, riid, ppv), false) }; + let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_pso(this, f, desc, riid, ppv, cacheable)) } else { (translated_graphics_pso(this, f, desc, riid, ppv, cacheable), false) }; if missed { - if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, graphics_key, build_graphics)) { + let build = if cacheable { build_graphics } else { build_graphics_uncacheable }; + if let Some(hr) = own_graphics(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_graphics, graphics_key, build)) { return hr; } - if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv) { + if let Some(hr) = translated_graphics_pso(this, f, desc, riid, ppv, cacheable) { return hr; } } else if let Some(hr) = translated { @@ -5832,7 +7352,7 @@ const SHADER_SUBOBJECTS: [D3D12_PIPELINE_STATE_SUBOBJECT_TYPE; 8] = [ /// A pipeline state stream being written: subobjects aligned as D3D12 expects /// (type, payload at 4 or 8, size rounded to 8). -#[derive(Default)] +#[derive(Clone, Default)] struct StreamOut(Vec<u8>, usize); impl StreamOut { @@ -5878,24 +7398,48 @@ fn stream_subobjects(buf: &[u8]) -> Option<Vec<(u32, &[u8])>> { /// The stream's subobjects up to the first of a type XCL does not know (logged): a console /// shader in front of it must still be found. -fn known_subobjects(buf: &[u8]) -> Vec<(u32, &[u8])> { +// Checked parsing and extended rasterizer projection adapted from PR #2621 by Decodere. +fn known_subobjects_checked(buf: &[u8]) -> (Vec<(u32, &[u8])>, bool) { let mut out = Vec::new(); let mut off = 0usize; - while off + 8 <= buf.len() { + loop { + if off == buf.len() { + return (out, true); + } + let Some(header) = off.checked_add(8) else { return (out, false) }; + if header > buf.len() { + return (out, false); + } let ty = u32::from_le_bytes(buf[off..off + 4].try_into().unwrap()); let Some((psize, palign)) = super::null::subobject_payload(ty) else { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 4 { crate::xlog_warn!("D3D12.X: pipeline stream: unknown subobject type {ty} at {off:#x} of {:#x} - the rest is not read", buf.len()); } - break; + return (out, false); }; let poff = if palign == 8 { 8 } else { 4 }; - let Some(p) = buf.get(off + poff..off + poff + psize) else { break }; + let Some(start) = off.checked_add(poff) else { return (out, false) }; + let Some(end) = start.checked_add(psize) else { return (out, false) }; + let Some(p) = buf.get(start..end) else { return (out, false) }; out.push((ty, p)); - off += (poff + psize + 7) & !7; + let Some(next) = end.checked_add(7).map(|n| n & !7) else { return (out, false) }; + if next > buf.len() { + return (out, false); + } + off = next; } - out +} + +fn known_subobjects(buf: &[u8]) -> Vec<(u32, &[u8])> { + known_subobjects_checked(buf).0 +} + +fn stream_node_mask(subobjects: &[(u32, &[u8])]) -> u32 { + subobjects + .iter() + .find(|(ty, payload)| *ty == D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK.0 as u32 && payload.len() >= 4) + .map_or(0, |(_, payload)| u32::from_le_bytes(payload[..4].try_into().unwrap())) } unsafe fn payload_shader<'a>(p: &[u8]) -> Option<&'a [u8]> { @@ -5968,7 +7512,7 @@ fn passthrough_mesh_stream_accepts_a_triangle_driver_blob() { } } -#[allow(dead_code)] // Consumed by the stacked driver-cache integration. +#[allow(dead_code)] // Two-pass identities are consumed by the next stacked cache stage. mod two_pass_identity; /// The console PS of a two-pass pipeline (a PC PS passes as it is). @@ -5985,15 +7529,23 @@ fn two_pass_ps(ps: Option<&[u8]>, split_wave64: bool) -> Result<(Option<Vec<u8>> /// Create the mesh pipeline (`stream`, RS and shaders already in it) and the compute pass; /// the title gets the mesh pipeline state. #[allow(clippy::too_many_arguments)] -unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { +unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu::recomp::pso::TwoPass, mesh_rs: *mut c_void, node_mask: u32, kind: &'static str, riid: *const GUID, ppv: *mut *mut c_void) -> HRESULT { let Some(rs) = abi_rs_for(this, &tp.samplers) else { return E_INVALIDARG }; let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); let desc: [usize; 2] = [stream.0.len(), stream.0.as_ptr() as usize]; // the mesh pass and its compute pass: one turn for both let bytes = stream.shader_bytes() + tp.cs.len(); - let gate = bytes >= huge_pso_bytes() && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); + let huge_bytes = huge_pso_bytes(); + let medium = bytes < huge_bytes + && medium_compute_compile("compute", tp.cs.len(), huge_bytes, ADAPTER_VENDOR.load(Ordering::Acquire)); + let gate = (bytes >= huge_bytes || medium) && std::thread::current().name().is_some_and(|n| n.starts_with("xcl-pso")); let waited = std::time::Instant::now(); - let _slot = gate.then(|| big_compile_turn(compile_slots(bytes), || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted)); + let gate_stall = gate.then(|| crate::stall::span(crate::stall::StallKind::DriverCompileGate)).flatten(); + let _slot = gate.then(|| { + let slots = if medium { &*MEDIUM_COMPILES } else { compile_slots(bytes) }; + big_compile_turn(slots, || big_compile_commit_free(big_compile_headroom(bytes)), super::pso_async::build_is_wanted) + }); + drop(gate_stall); if gate { crate::xlog_info!("D3D12.X: two-pass {kind} PSO ({bytes} B DXIL) gated, waited {} ms", waited.elapsed().as_millis()); } @@ -6005,46 +7557,53 @@ unsafe fn finish_two_pass(this: *mut c_void, stream: &StreamOut, tp: crate::gpu: let mesh_pso = *ppv; let fc: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreateComputePipelineState"))); let mut cdesc = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + cdesc.NodeMask = node_mask; cdesc.pRootSignature = std::mem::transmute::<*mut c_void, std::mem::ManuallyDrop<Option<ID3D12RootSignature>>>(rs); cdesc.CS = bytecode(&tp.cs); // Reuse the compiled driver blob of the compute pass across all `(MS/GS, PS)` pipelines that // share `tp.cs` (in memory and on disk), matching `translated_compute_pso_once`. - let ckey = compute_blob_key(&tp.cs, rs as usize, 0); + let ckey = compute_blob_key_for(&tp.cs, rs as usize, 0, node_mask); let mut ccached = compute_blob(ckey); - let cdisk = driver_cache::path(&tp.cs, 0); + let cdisk = driver_cache::path_for_root_node(&tp.cs, 0, false, &tp.samplers, node_mask); let cfrom_disk = ccached.is_none(); + let mut cloaded = None; if cfrom_disk { - ccached = cdisk.as_deref().and_then(driver_cache::load).map(std::sync::Arc::new); + cloaded = cdisk.as_deref().and_then(driver_cache::load); + ccached = cloaded.as_ref().map(driver_cache::LoadedBlob::shared); } + let rejected_cgeneration = ccached.clone(); if let Some(b) = &ccached { cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: b.as_ptr() as *const c_void, CachedBlobSizeInBytes: b.len() }; } let iid = pc_iid(Kind::PipelineState); let mut compute: *mut c_void = std::ptr::null_mut(); - let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, || { + let (mut hc, mut cin_driver) = driver_compile_identified("compute pass", tp.cs.len(), false, None, ccached.is_some(), || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); + let mut cpersist_took = cin_driver; if hc < 0 && ccached.is_some() { - forget_compute_blob(ckey); + if let Some(expected) = rejected_cgeneration.as_ref() { + forget_compute_blob_if(ckey, expected); + } if cfrom_disk { - driver_cache::note(false, cdisk.as_deref()); + driver_cache::note(false, cloaded.take()); } cdesc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); compute = std::ptr::null_mut(); - let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, || { + let (retried, took) = driver_compile_identified("compute pass retry", tp.cs.len(), false, None, false, || { driver_pso(fc, this, &cdesc as *const _ as *const c_void, &iid, &mut compute) }); hc = retried; cin_driver += took; + cpersist_took = took; } let creused = hc >= 0 && ccached.is_some() && cdesc.CachedPSO.CachedBlobSizeInBytes != 0; if hc >= 0 && !creused && !compute.is_null() { - keep_compute_blob(ckey, compute, tp.cs.len()); - if let (Some(p), Some(b)) = (cdisk.as_deref(), compute_blob(ckey)) { - driver_cache::keep(p, &b, cin_driver); - } + keep_driver_blob(&COMPUTE_BLOBS, COMPUTE_BLOBS_MAX, ckey, tp.cs.len(), cdisk.as_deref(), cpersist_took, + || read_pso_cached_blob(compute)); } else if creused && cfrom_disk { - driver_cache::note(true, None); + COMPUTE_BLOBS.admit(ckey, ccached.as_ref().unwrap().clone(), COMPUTE_BLOBS_MAX); + driver_cache::note(true, cloaded.take()); } drop(_slot); if hc < 0 || compute.is_null() { @@ -6163,7 +7722,8 @@ unsafe fn translated_mesh_stream_once(this: *mut c_void, desc: *const c_void, ri out.raw(*ty, payload, palign == 8); } } - let hr = finish_two_pass(this, &out, tp, rs, "MS", riid, ppv); + let node_mask = stream_node_mask(&subs); + let hr = finish_two_pass(this, &out, tp, rs, node_mask, "MS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("ms", Some(ms)), ("ps", console_ps)]); } @@ -6238,7 +7798,7 @@ unsafe fn translated_gs_pso(this: *mut c_void, d: &D3D12_GRAPHICS_PIPELINE_STATE if d.Flags.0 != 0 { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_FLAGS, &d.Flags); } - let hr = finish_two_pass(this, &out, tp, rs, "GS", riid, ppv); + let hr = finish_two_pass(this, &out, tp, rs, d.NodeMask, "GS", riid, ppv); if hr >= 0 { super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("gs", Some(gs)), ("ps", shader_bytes(&d.PS))]); } @@ -6322,11 +7882,15 @@ unsafe fn fallback_stream(desc: *const u8) -> Option<(Vec<u8>, [usize; 2])> { const RECT_LIST_TYPE: i32 = 19; /// `create(copy)`, and once more without the generated rect list GS (`rect_gs`) when the driver -/// refuses the pipeline with it: each rect is then drawn as the triangle of its three vertices, +/// refuses the pipeline with E_INVALIDARG: each rect is then drawn as the triangle of its three vertices, /// as without the GS, rather than not at all (the untranslated fallback's dummy shaders). +fn rejected_rect_list_gs(hr: HRESULT, rect_gs: bool) -> bool { + rect_gs && hr == E_INVALIDARG +} + fn retry_without_rect_gs(copy: &mut D3D12_GRAPHICS_PIPELINE_STATE_DESC, rect_gs: bool, mut create: impl FnMut(&D3D12_GRAPHICS_PIPELINE_STATE_DESC) -> HRESULT) -> HRESULT { let hr = create(copy); - if hr >= 0 || !rect_gs { + if !rejected_rect_list_gs(hr, rect_gs) { return hr; } note_translation_error(format!("the driver rejected the PSO with the rect list GS ({hr:#x}): rect list drawn as triangles")); @@ -6628,12 +8192,34 @@ mod pso_blend_and_tsharp_tests { } enum StreamPipeline { - Graphics(Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC>), + Graphics(Box<D3D12_GRAPHICS_PIPELINE_STATE_DESC>, bool), + GraphicsStream, Compute(Box<D3D12_COMPUTE_PIPELINE_STATE_DESC>), /// neither with console shaders (or not readable) Unknown, } +unsafe fn read_sub<T>(p: &[u8]) -> T { + let mut d: T = std::mem::zeroed(); + put(&mut d, p); + d +} + +fn depth_bias_is_exact_i32(b: f32) -> bool { + b.is_finite() && b >= i32::MIN as f32 && b < 2147483648.0 && b.fract() == 0.0 +} + +unsafe fn stream_needs_extended_rasterizer(subs: &[(u32, &[u8])]) -> bool { + subs.iter().any(|&(ty, p)| match ty { + 27 => !depth_bias_is_exact_i32(read_sub::<D3D12_RASTERIZER_DESC1>(p).DepthBias), + 28 => { + let d: D3D12_RASTERIZER_DESC2 = read_sub(p); + !depth_bias_is_exact_i32(d.DepthBias) || d.LineRasterizationMode != D3D12_LINE_RASTERIZATION_MODE_ALIASED + } + _ => false, + }) +} + /// A pipeline stream with a console VS (+ PS / GS) or CS as the plain pipeline desc, which is /// translated like any other (`dev_create_graphics_pso`). The stream itself must not reach the /// driver: AMD's shader compiler fails on the console's stripped DXIL and takes the device with @@ -6648,7 +8234,10 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if !crate::gpu::shader::readable(base, size) { return StreamPipeline::Unknown; } - let subs = known_subobjects(std::slice::from_raw_parts(base as *const u8, size)); + let (subs, cacheable) = known_subobjects_checked(std::slice::from_raw_parts(base as *const u8, size)); + if subobjects_have_unreadable_shader(&subs) { + return StreamPipeline::Unknown; + } let console = |ty: u32| subs.iter().find(|s| s.0 == ty).and_then(|s| payload_shader(s.1)).is_some_and(is_console); if console(6) { let mut c: D3D12_COMPUTE_PIPELINE_STATE_DESC = std::mem::zeroed(); @@ -6657,6 +8246,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { 0 => put(&mut c.pRootSignature, p), 6 => put(&mut c.CS, p), 18 => put(&mut c.NodeMask, p), + 20 => put(&mut c.Flags, p), _ => {} } } @@ -6665,6 +8255,11 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { if !console(1) { return StreamPipeline::Unknown; } + // Unknown/truncated suffixes retain Stage 1's conservative projected, uncacheable path: + // rewriting cannot preserve bytes whose layout is unknown. Console GS needs its two-pass path. + if cacheable && !console(5) && stream_needs_extended_rasterizer(&subs) { + return StreamPipeline::GraphicsStream; + } let mut g: D3D12_GRAPHICS_PIPELINE_STATE_DESC = std::mem::zeroed(); // what a stream leaves out has the PC's defaults g.SampleMask = u32::MAX; @@ -6740,8 +8335,7 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { BackFace: face(&d.BackFace), }; } - 27 | 28 => { - // RASTERIZER1 / 2: fill, cull, winding, depth bias (float), clamp, slope, depth clip + 27 => { let mut d: D3D12_RASTERIZER_DESC1 = std::mem::zeroed(); put(&mut d, p); g.RasterizerState = D3D12_RASTERIZER_DESC { @@ -6752,23 +8346,254 @@ unsafe fn stream_pipeline(desc: *const c_void) -> StreamPipeline { DepthBiasClamp: d.DepthBiasClamp, SlopeScaledDepthBias: d.SlopeScaledDepthBias, DepthClipEnable: d.DepthClipEnable, + MultisampleEnable: d.MultisampleEnable, + AntialiasedLineEnable: d.AntialiasedLineEnable, + ForcedSampleCount: d.ForcedSampleCount, + ConservativeRaster: d.ConservativeRaster, + }; + } + 28 => { + let mut d: D3D12_RASTERIZER_DESC2 = std::mem::zeroed(); + put(&mut d, p); + g.RasterizerState = D3D12_RASTERIZER_DESC { + FillMode: d.FillMode, + CullMode: d.CullMode, + FrontCounterClockwise: d.FrontCounterClockwise, + DepthBias: d.DepthBias as i32, + DepthBiasClamp: d.DepthBiasClamp, + SlopeScaledDepthBias: d.SlopeScaledDepthBias, + DepthClipEnable: d.DepthClipEnable, + ForcedSampleCount: d.ForcedSampleCount, + ConservativeRaster: d.ConservativeRaster, ..Default::default() }; } - _ => {} - } + _ => {} + } + } + // D3D12 pipeline state streams default DepthEnable to FALSE when no depth-stencil + // subobject is supplied and DSVFormat is DXGI_FORMAT_UNKNOWN (0). + if !has_depth_stencil && g.DSVFormat.0 == 0 { + g.DepthStencilState.DepthEnable = false.into(); + } + // a rect list stays one for translated_graphics_pso, which gives it its GS (untranslated, it + // becomes the PC's in graphics_pso) + if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { + pc_topology_type(&mut g); + } + StreamPipeline::Graphics(Box::new(g), cacheable) +} + +unsafe fn patch_sub<T>(out: &mut StreamOut, ty: D3D12_PIPELINE_STATE_SUBOBJECT_TYPE, payload: &[u8], f: impl FnOnce(&mut T)) { + let mut v: T = std::ptr::read_unaligned(payload.as_ptr() as *const T); + f(&mut v); + out.put(ty, &v); +} + +/// Native stream translation adapted from PR #2621 by Decodere. +unsafe fn rewrite_graphics_stream( + subs: &[(u32, &[u8])], rs: *mut c_void, vs_dxil: &[u8], ps_dxil: Option<&[u8]>, rect_gs: Option<&[u8]>, no_stencil: bool, no_cull: bool, +) -> StreamOut { + let mut out = StreamOut::default(); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, &(rs as usize)); + out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, vs_dxil); + if let Some(ps) = ps_dxil { out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, ps); } + if let Some(gs) = rect_gs { out.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_GS, gs); } + let (mut rt_count, mut rt_formats) = (0u32, [windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(0); 8]); + if let Some((_, p)) = subs.iter().find(|(ty, p)| *ty == 15 && p.len() >= 36) { + for (k, ch) in p[..32].chunks_exact(4).enumerate() { + rt_formats[k] = windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(super::device_x::pc_target_format(u32::from_le_bytes(ch.try_into().unwrap())) as i32); + } + rt_count = u32::from_le_bytes(p[32..36].try_into().unwrap()); + } + let default_topo = if subs.iter().any(|(ty, p)| *ty == 4 && payload_shader(p).is_some()) { D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH } else { D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE }; + let (mut saw_topology, mut saw_rasterizer) = (false, false); + for &(ty, payload) in subs { + if matches!(ty, 0 | 1 | 2 | 19) || (ty == 5 && rect_gs.is_some()) { continue; } + if matches!(ty, 10 | 27 | 28) { saw_rasterizer = true; } + let (_, palign) = super::null::subobject_payload(ty).unwrap_or((0, 4)); + match ty { + 8 if payload.len() >= std::mem::size_of::<D3D12_BLEND_DESC>() => patch_sub::<D3D12_BLEND_DESC>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_BLEND, payload, |b| sanitize_integer_rt_blend(b, rt_count, &rt_formats)), + 10 if no_cull && payload.len() >= std::mem::size_of::<D3D12_RASTERIZER_DESC>() => patch_sub::<D3D12_RASTERIZER_DESC>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, payload, |r| r.CullMode = D3D12_CULL_MODE_NONE), + 27 if no_cull && payload.len() >= std::mem::size_of::<D3D12_RASTERIZER_DESC1>() => patch_sub::<D3D12_RASTERIZER_DESC1>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1, payload, |r| r.CullMode = D3D12_CULL_MODE_NONE), + 28 if no_cull && payload.len() >= std::mem::size_of::<D3D12_RASTERIZER_DESC2>() => patch_sub::<D3D12_RASTERIZER_DESC2>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER2, payload, |r| r.CullMode = D3D12_CULL_MODE_NONE), + 11 if no_stencil && payload.len() >= std::mem::size_of::<D3D12_DEPTH_STENCIL_DESC>() => patch_sub::<D3D12_DEPTH_STENCIL_DESC>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL, payload, |d| d.StencilEnable = false.into()), + 21 if no_stencil && payload.len() >= std::mem::size_of::<D3D12_DEPTH_STENCIL_DESC1>() => patch_sub::<D3D12_DEPTH_STENCIL_DESC1>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL1, payload, |d| d.StencilEnable = false.into()), + 26 if no_stencil && payload.len() >= std::mem::size_of::<D3D12_DEPTH_STENCIL_DESC2>() => patch_sub::<D3D12_DEPTH_STENCIL_DESC2>(&mut out, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL2, payload, |d| d.StencilEnable = false.into()), + 14 if payload.len() >= 4 => { + saw_topology = true; + let t = i32::from_le_bytes(payload[0..4].try_into().unwrap()); + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &if (1..=4).contains(&t) { D3D12_PRIMITIVE_TOPOLOGY_TYPE(t) } else { default_topo }); + } + 15 if payload.len() >= 32 => { + let mut p = payload.to_vec(); + for ch in p[..32].chunks_exact_mut(4) { + let f = super::device_x::pc_target_format(u32::from_le_bytes(ch.try_into().unwrap())); + ch.copy_from_slice(&f.to_le_bytes()); + } + out.raw(15, &p, false); + } + 16 if payload.len() >= 4 => out.raw(16, &super::device_x::pc_view_format(u32::from_le_bytes(payload[0..4].try_into().unwrap())).to_le_bytes(), false), + _ => out.raw(ty, payload, palign == 8), + } + } + if !saw_topology { out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY, &default_topo); } + if no_cull && !saw_rasterizer { + out.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER, &D3D12_RASTERIZER_DESC { + FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_NONE, DepthClipEnable: true.into(), ..Default::default() + }); + } + out +} + +struct GraphicsStreamBuild { + hr: HRESULT, + built_in_driver: std::time::Duration, + reused: bool, + cache_eligible: bool, + used_rect_gs: bool, +} + +/// HRESULTs documented for a cached pipeline made by another adapter or driver, plus the +/// invalid-argument result D3D12Core returns for an otherwise unreadable cached blob. +fn stale_cached_pso_refusal(hr: HRESULT) -> bool { + matches!(hr as u32, 0x8007_0057 | 0x887e_0001 | 0x887e_0002) +} + +fn create_graphics_stream_cached( + stream: &StreamOut, + without_rect_gs: Option<&StreamOut>, + cached: Option<&[u8]>, + mut on_stale_cache: impl FnMut(), + mut run: impl FnMut(&str, bool, &StreamOut) -> (HRESULT, std::time::Duration), +) -> GraphicsStreamBuild { + if let Some(blob) = cached { + let mut with_cache = stream.clone(); + with_cache.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: blob.as_ptr() as *const c_void, + CachedBlobSizeInBytes: blob.len(), + }); + let (hr, took) = run("graphics stream", true, &with_cache); + if hr >= 0 { + return GraphicsStreamBuild { hr, built_in_driver: took, reused: true, cache_eligible: false, used_rect_gs: without_rect_gs.is_some() }; + } + if !stale_cached_pso_refusal(hr) { + return GraphicsStreamBuild { hr, built_in_driver: took, reused: false, cache_eligible: false, used_rect_gs: without_rect_gs.is_some() }; + } + // A cached blob describes the stream including its rect-list GS. Discard it before + // deciding whether the driver objects to that GS rather than to the stale blob. + on_stale_cache(); + } + let label = if cached.is_some() { "graphics stream retry" } else { "graphics stream" }; + let (hr, took) = run(label, false, stream); + if rejected_rect_list_gs(hr, without_rect_gs.is_some()) { + note_translation_error(format!("the driver rejected the graphics stream with the rect list GS ({hr:#x}): rect list drawn as triangles")); + let (fallback, fallback_took) = run("graphics stream without rect GS", false, without_rect_gs.unwrap()); + return GraphicsStreamBuild { + hr: fallback, + built_in_driver: fallback_took, + reused: false, + // The fallback is a different pipeline and must never replace the with-GS key. + cache_eligible: false, + used_rect_gs: false, + }; + } + GraphicsStreamBuild { + hr, + built_in_driver: took, + reused: false, + cache_eligible: hr >= 0, + used_rect_gs: without_rect_gs.is_some(), + } +} + +unsafe fn translated_graphics_stream(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { + with_switch_fallback(|| translated_graphics_stream_once(this, desc, riid, ppv)) +} + +unsafe fn translated_graphics_stream_once(this: *mut c_void, desc: *const c_void, riid: *const GUID, ppv: *mut *mut c_void) -> Option<HRESULT> { + use crate::gpu::recomp::pso::{console_to_dxil_for, is_console, Stage}; + if !crate::gpu::shader::readable(desc as usize, 16) { return None; } + let (size, base) = (*(desc as *const usize), *((desc as usize + 8) as *const usize)); + if !crate::gpu::shader::readable(base, size) { return None; } + let (subs, cacheable) = known_subobjects_checked(std::slice::from_raw_parts(base as *const u8, size)); + if !cacheable { return None; } + if subobjects_have_unreadable_shader(&subs) { return Some(E_INVALIDARG); } + let vs = subs.iter().find(|s| s.0 == 1).and_then(|s| payload_shader(s.1)).filter(|b| is_console(b))?; + if subs.iter().any(|s| matches!(s.0, 3 | 4) && payload_shader(s.1).is_some()) { + note_translation_error("graphics stream with HS/DS – not supported yet".into()); + return Some(E_INVALIDARG); + } + if super::pso_async::lazy() && crate::gpu::recomp::dxc::defer() { return None; } + let split = graphics_wave32(this); + let vs_c = match console_to_dxil_for(vs, Stage::Vertex, 0, split) { Ok(b) => b, Err(e) => { note_translation_error(format!("VS: {e}")); return Some(E_INVALIDARG); } }; + let mut samplers = vs_c.samplers; + let console_ps = subs.iter().find(|s| s.0 == 2).and_then(|s| payload_shader(s.1)); + let ps_dxil = match console_ps { + Some(p) if is_console(p) => match console_to_dxil_for(p, Stage::Pixel, samplers.len() as u32, split) { + Ok(b) => { samplers.extend(b.samplers); Some(b.dxil) } + Err(e) => { note_translation_error(format!("PS: {e}")); return Some(E_INVALIDARG); } + }, + Some(p) => Some(p.to_vec()), + None => None, + }; + let is_rect = subs.iter().find(|s| s.0 == 14 && s.1.len() >= 4).is_some_and(|s| i32::from_le_bytes(s.1[0..4].try_into().unwrap()) == RECT_LIST_TYPE); + let rect_gs = if is_rect && !subs.iter().any(|s| s.0 == 5 && payload_shader(s.1).is_some()) { rect_list_gs(vs, console_ps).map_err(|e| note_translation_error(format!("rect list drawn as triangles: {e}"))).ok() } else { None }; + let Some(rs) = abi_rs_for(this, &samplers) else { return Some(E_INVALIDARG) }; + let ps_hash = console_ps.map_or(0, crate::gpu::shader::fnv64); + let (no_stencil, no_cull) = (debug_pso_switch("XCL_DEBUG_NO_STENCIL", ps_hash), debug_pso_switch("XCL_DEBUG_NO_CULL", ps_hash)); + let fs: PsoFn = std::mem::transmute(orig_fn(this, slot_of(this, "CreatePipelineState"))); + let stream = rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), rect_gs.as_deref(), no_stencil, no_cull); + let without_rect_gs = rect_gs.as_ref().map(|_| rewrite_graphics_stream(&subs, rs, &vs_c.dxil, ps_dxil.as_deref(), None, no_stencil, no_cull)); + let disk_key = two_pass_identity::graphics_stream_key(&stream.0, &samplers, crate::gpu::recomp::pso::mem_windows()); + let key = disk_key.map(|(hash, bytes)| (hash, bytes, rs as usize)); + let mut cached = key.and_then(graphics_blob); + let disk = disk_key.and_then(|k| driver_cache::graphics_path(k.0, k.1)); + let from_disk = key.is_some() && cached.is_none(); + let mut loaded = None; + if from_disk { + loaded = disk.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); + } + let submit = |label: &str, has_cached: bool, out: &StreamOut| { + let d = [out.0.len(), out.0.as_ptr() as usize]; + driver_compile_identified(label, out.shader_bytes(), gate_compute_driver_compile(has_cached), Some(ps_hash), has_cached, + || finish_pso(this, fs, d.as_ptr() as *const c_void, riid, ppv)) + }; + let rejected_generation = cached.clone(); + let build = create_graphics_stream_cached( + &stream, + without_rect_gs.as_ref(), + cached.as_deref().map(Vec::as_slice), + || { + if let (Some(k), Some(expected)) = (key, rejected_generation.as_ref()) { + forget_graphics_blob_if(k, expected); + } + if from_disk { driver_cache::note(false, loaded.take()); } + }, + submit, + ); + let hr = build.hr; + if let Some(k) = key.filter(|_| build.cache_eligible) { + keep_driver_blob(&GRAPHICS_BLOBS, GRAPHICS_BLOBS_MAX, k, stream.shader_bytes(), disk.as_deref(), build.built_in_driver, + || read_pso_cached_blob(*ppv)); + } else if build.reused && from_disk { + GRAPHICS_BLOBS.admit(key.unwrap(), cached.as_ref().unwrap().clone(), GRAPHICS_BLOBS_MAX); + driver_cache::note(true, loaded.take()); } - // D3D12 pipeline state streams default DepthEnable to FALSE when no depth-stencil - // subobject is supplied and DSVFormat is DXGI_FORMAT_UNKNOWN (0). - if !has_depth_stencil && g.DSVFormat.0 == 0 { - g.DepthStencilState.DepthEnable = false.into(); + if hr < 0 { + note_translation_error(format!("the driver rejected the graphics stream with the translated shaders ({hr:#x})")); + return Some(hr); } - // a rect list stays one for translated_graphics_pso, which gives it its GS (untranslated, it - // becomes the PC's in graphics_pso) - if g.PrimitiveTopologyType.0 != RECT_LIST_TYPE { - pc_topology_type(&mut g); + let n = TRANSLATED_PSO.fetch_add(1, Ordering::Relaxed); + if !ppv.is_null() && !(*ppv).is_null() { + note_pso_rs(*ppv, rs); + super::dred::label(*ppv as usize, &[("vs", Some(vs)), ("ps", console_ps)]); + TRANSLATED_GRAPHICS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); + if build.used_rect_gs { RECT_LIST_GS.lock().unwrap().get_or_insert_with(HashSet::new).insert(*ppv as usize); } } - StreamPipeline::Graphics(Box::new(g)) + if n < 5 || n % 1000 == 0 { crate::xlog_info!("D3D12.X: graphics stream PSO from translated console shaders (#{})", n + 1); } + Some(hr) } /// The bytes of a stream payload as a desc field (no references counted: the desc only borrows). @@ -6777,8 +8602,8 @@ unsafe fn put<T>(to: &mut T, from: &[u8]) { std::ptr::copy_nonoverlapping(from.as_ptr(), to as *mut T as *mut u8, n); } -/// True when a pipeline stream carries a shader subobject whose non-null, non-empty bytecode -/// pointer is not readable (handing it to D3D12Core would access-violate instead of failing). +/// True when a pipeline stream carries a shader subobject whose non-empty bytecode has a null or +/// unreadable pointer (handing it to D3D12Core would access-violate instead of failing). unsafe fn stream_has_unreadable_shader(desc: *const c_void) -> bool { if !crate::gpu::shader::readable(desc as usize, 16) { return false; @@ -6788,11 +8613,15 @@ unsafe fn stream_has_unreadable_shader(desc: *const c_void) -> bool { return false; } let buf = std::slice::from_raw_parts(base as *const u8, size); - known_subobjects(buf).into_iter().any(|(ty, p)| { + subobjects_have_unreadable_shader(&known_subobjects(buf)) +} + +fn subobjects_have_unreadable_shader(subs: &[(u32, &[u8])]) -> bool { + subs.iter().any(|(ty, p)| { matches!(ty, 1..=6 | 24 | 25) && p.len() >= 16 && { let ptr = u64::from_le_bytes(p[0..8].try_into().unwrap()) as usize; let len = u64::from_le_bytes(p[8..16].try_into().unwrap()) as usize; - ptr != 0 && len != 0 && !crate::gpu::shader::readable(ptr, len) + (ptr == 0 && len != 0) || (ptr != 0 && len != 0 && !crate::gpu::shader::readable(ptr, len)) } }) } @@ -6812,7 +8641,17 @@ pub(super) unsafe extern "system" fn dev_create_pipeline_state(this: *mut c_void return hr; } match stream_pipeline(desc) { - StreamPipeline::Graphics(d) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true), + StreamPipeline::Graphics(d, cacheable) => return graphics_pso(this, &*d as *const _ as *const c_void, riid, ppv, true, cacheable), + StreamPipeline::GraphicsStream => { + let (translated, missed) = if super::pso_async::enabled() { attempt(|| translated_graphics_stream(this, desc, riid, ppv)) } else { (translated_graphics_stream(this, desc, riid, ppv), false) }; + if missed { + if let Some(hr) = own_stream(desc).and_then(|o| go_background(this, f, desc, riid, ppv, false, o, standin_stream, stream_key, build_stream)) { + return hr; + } + return translated_graphics_stream(this, desc, riid, ppv).unwrap_or(E_INVALIDARG); + } + return translated.unwrap_or(E_INVALIDARG); + } StreamPipeline::Compute(d) => return dev_create_compute_pso(this, &*d as *const _ as *const c_void, riid, ppv), StreamPipeline::Unknown => {} } @@ -6878,6 +8717,7 @@ unsafe extern "system" fn dev_create_root_signature(this: *mut c_void, mask: u32 // --------------------------------------------------------------------------------------- unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, desc: *const c_void, handle: usize) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailViewDescriptor); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, *const c_void, usize); let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "CreateRenderTargetView"))); // a view in a console-only format, or of a target made R8G8B8A8 (`device_x::pc_resource_desc`) @@ -6900,8 +8740,9 @@ unsafe extern "system" fn dev_create_rtv(this: *mut c_void, res: *mut c_void, de /// ClearRenderTargetView: as on the PC (`XCL_TRACE_FRAME`: the colours logged) unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *const [f32; 4], n: u32, rects: *const c_void) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailCopy); type F = unsafe extern "system" fn(*mut c_void, usize, *const [f32; 4], u32, *const c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearRenderTargetView"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearRenderTargetView"))); if super::present::trace_frame() { static N: AtomicU64 = AtomicU64::new(0); if N.fetch_add(1, Ordering::Relaxed) < 16 { @@ -6915,8 +8756,9 @@ unsafe extern "system" fn cl_clear_rtv(this: *mut c_void, rtv: usize, color: *co } unsafe extern "system" fn cl_om_set_render_targets(this: *mut c_void, n: u32, rtvs: *const usize, single: i32, dsv: *const usize) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailBind); type F = unsafe extern "system" fn(*mut c_void, u32, *const usize, i32, *const usize); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "OMSetRenderTargets"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "OMSetRenderTargets"))); f(this, n, rtvs, single, dsv); super::list_x::note_render_targets(this, n, rtvs, single, dsv); if super::present::trace_frame() { @@ -6947,13 +8789,20 @@ pub(super) unsafe fn bind_pipeline(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_set_pipeline_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "SetPipelineState"))); - let bound = super::pso_async::resolve(pso as usize); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "SetPipelineState"))); + let bound = super::list_x::resolve_and_record_pipeline_lazy(this as usize, pso as usize); f(this, bound as *mut c_void); super::dred::mark_pipeline(this, pso as usize, bound); super::list_x::on_set_pipeline_state(this, pso as usize); } +unsafe extern "system" fn cl_execute_bundle(this: *mut c_void, bundle: *mut c_void) { + type F = unsafe extern "system" fn(*mut c_void, *mut c_void); + super::list_x::on_execute_bundle(this as usize, bundle as usize); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteBundle"))); + f(this, bundle); +} + /// The title's markers are counted for `XCL_DRED=1`'s pipeline labels (`dred`). unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: *const c_void, size: u32) { type F = unsafe extern "system" fn(*mut c_void, u32, *const c_void, u32); @@ -6964,8 +8813,8 @@ unsafe extern "system" fn cl_set_marker(this: *mut c_void, metadata: u32, data: unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ClearState"))); - let bound = super::pso_async::resolve_for_bind(pso as usize); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ClearState"))); + let bound = super::list_x::resolve_and_record_pipeline(this as usize, pso as usize); f(this, bound as *mut c_void); if !pso.is_null() { super::dred::mark_pipeline(this, pso as usize, bound); @@ -6977,14 +8826,14 @@ unsafe extern "system" fn cl_clear_state(this: *mut c_void, pso: *mut c_void) { unsafe extern "system" fn cl_draw_instanced(this: *mut c_void, vcount: u32, icount: u32, sv: u32, si: u32) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, u32); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DrawInstanced"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "DrawInstanced"))); f(this, vcount, icount, sv, si); } unsafe extern "system" fn cl_draw_indexed_instanced(this: *mut c_void, icount: u32, inst: u32, si: u32, bv: i32, sinst: u32) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, u32, u32, u32, i32, u32); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "DrawIndexedInstanced"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "DrawIndexedInstanced"))); f(this, icount, inst, si, bv, sinst); } @@ -7000,33 +8849,70 @@ unsafe extern "system" fn cl_execute_indirect( ) { super::list_x::prepare_draw(this); type F = unsafe extern "system" fn(*mut c_void, *mut c_void, u32, *mut c_void, u64, *mut c_void, u64); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteIndirect"))); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteIndirect"))); f(this, sig, max_count, arg_buf, arg_off, cnt_buf, cnt_off); } +/// The last reference: what XCL keeps by the list's address goes before the runtime frees it, +/// as a list created on another thread can get the address at once. (Two last-but-one releases +/// at once miss each other here; the list's state then goes after it, as before.) unsafe extern "system" fn cl_release(this: *mut c_void) -> u32 { - let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); + let add: RefFn = std::mem::transmute(orig_fn(this, 1)); + let f: RefFn = std::mem::transmute(orig_fn(this, 2)); + let last = add(this) == 2; + f(this); + if last { + forget_command_list(this); + } let n = f(this); - if n == 0 { - super::list_x::on_release(this as usize); - super::bind::forget(this); - super::dred::forget_list(this); + if n == 0 && !last { + forget_command_list(this); } n } +fn forget_command_list(list: *mut c_void) { + super::list_x::on_release(list as usize); + super::bind::forget(list); + super::dred::forget_list(list); +} + unsafe extern "system" fn q_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); + let n = super::queue_submit::release(this as usize, || f(this)); if n == 0 { super::list_x::on_queue_release(this as usize); + } else if n == 1 { + super::present::retire_released_queue(this as usize); } n } +thread_local! { + static RETAINED_ALLOC_RELEASE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +pub(super) fn release_retained_allocator(owner: ID3D12CommandAllocator) { + let raw = owner.as_raw() as usize; + RETAINED_ALLOC_RELEASE.with(|active| { + let old = active.replace(raw); + debug_assert_eq!(old, 0); + drop(owner); + active.set(old); + }); +} + unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { let f: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 2)); - let n = f(this); + if RETAINED_ALLOC_RELEASE.with(|active| active.get() == this as usize) { + return f(this); + } + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(orig_fn(this, 1)); + let (n, _) = super::alloc_pool::release_with_probe( + || { add_ref(this); }, + || f(this), + || super::alloc_pool::retain_release_probe(this), + ); if n == 0 { dispatch_chain::allocator_reset(this as usize); super::alloc_pool::forget(this as usize); @@ -7038,23 +8924,24 @@ unsafe extern "system" fn alloc_release(this: *mut c_void) -> u32 { /// Reset the (adopted) PC allocator `raw` itself. pub(super) unsafe fn reset_pc_allocator(raw: *mut c_void) -> HRESULT { type F = unsafe extern "system" fn(*mut c_void) -> HRESULT; - let f: F = std::mem::transmute(orig_fn(raw, slot_of(raw, "Reset"))); + let f: F = std::mem::transmute(orig_fn(raw, slot!(raw, "Reset"))); let hr = f(raw); - if hr >= 0 { dispatch_chain::allocator_reset(raw as usize); } + if hr >= 0 { + dispatch_chain::allocator_reset(raw as usize); + // The GPU is done with allocations owned by this exact native backing. + super::console_list::allocator_reset(raw); + } hr } unsafe extern "system" fn alloc_reset(this: *mut c_void) -> HRESULT { - // (lists may still hold recordings on it that the title submits again: `alloc_pool`) - let hr = match super::alloc_pool::title_reset(this) { + let _detail = crate::stall::detail_span_if(!super::title_textures::is_own_work(), crate::stall::StallKind::DetailListLifecycle); + // Lists may still hold recordings on it that the title submits again (`alloc_pool`). UMA + // follows each native backing and is released only when reset_pc_allocator resets that one. + match super::alloc_pool::title_reset(this) { Some(hr) => hr, None => reset_pc_allocator(this), - }; - if hr >= 0 { - // the GPU is done with what lists recorded from this allocator used - super::console_list::allocator_reset(this); } - hr } // --------------------------------------------------------------------------------------- @@ -7133,24 +9020,43 @@ unsafe fn queue_dispatch(slot: usize, this: *mut c_void, a1: usize, a2: usize, a let older = if shifted && slot >= 16 { slot - 2 } else if shifted { usize::MAX } else { slot }; let pc = |s: usize| orig_fn(this, s); match older { - // Signal / Wait take a fence: anything else is not one of them - 14 | 15 if is_fence(a1) => { - if older == 14 { + // Signal takes a fence: prepare outside the turn, then validate/insert atomically with it. + 14 if is_fence(a1) => loop { + let prepared = super::title_textures::prepare_downloads(this); + let attempt = super::queue_submit::with(this as usize, || { + let downloads = match super::title_textures::submit_prepared_downloads(this, prepared) { + Ok(downloads) => downloads, + Err(super::title_textures::SubmitDownloadsError::Stale) => return Err(None), + Err(super::title_textures::SubmitDownloadsError::Failed(error)) => return Err(Some(error)), + }; super::list_x::break_cycles_before_title_signal(this as usize, a1, a2 as u64); - } - let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(if older == 14 { PC_SIGNAL } else { PC_WAIT })); - let hr = f(this, a1, a2); - if hr >= 0 { - if older == 14 { + super::title_textures::tie_downloads(a1 as *mut c_void, a2 as u64, downloads); + let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_SIGNAL)); + let hr = f(this, a1, a2); + if hr >= 0 { super::fence_x::note_queue_signal(a1, a2 as u64); super::list_x::note_title_queue_signal(this as usize, a1, a2 as u64); - } else { - super::fence_x::note_queue_wait(a1, a2 as u64); - super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } + Ok(hr as u32 as usize) + }); + match attempt { + Ok(hr) => break hr, + Err(None) => continue, + Err(Some(error)) => { + crate::xlog_warn!("D3D12.X: {error}; title queue Signal not submitted"); + break crate::util::E_FAIL as u32 as usize; + } + } + }, + 15 if is_fence(a1) => super::queue_submit::with(this as usize, || { + let f: unsafe extern "system" fn(*mut c_void, usize, usize) -> i32 = std::mem::transmute(pc(PC_WAIT)); + let hr = f(this, a1, a2); + if hr >= 0 { + super::fence_x::note_queue_wait(a1, a2 as u64); + super::list_x::note_title_queue_wait(this as usize, a1, a2 as u64); } hr as u32 as usize - } + }), 16 => { let f: unsafe extern "system" fn(*mut c_void, usize) -> i32 = std::mem::transmute(pc(PC_TIMESTAMP_FREQUENCY)); f(this, a1) as u32 as usize @@ -7230,20 +9136,41 @@ queue_slots!(14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, /// nothing left Fortnite's render fences pending: its render thread waited, textures were /// never released, and the garbage collector ended the game after 10 s.) unsafe extern "system" fn q_signal_x(this: *mut c_void, fence: *mut c_void, value: u64, _flags: u32) -> HRESULT { + loop { + let prepared = super::title_textures::prepare_downloads(this); + match super::queue_submit::with(this as usize, || q_signal_x_serialized(this, fence, value, prepared)) { + Ok(hr) => return hr, + Err(super::title_textures::SubmitDownloadsError::Stale) => continue, + Err(super::title_textures::SubmitDownloadsError::Failed(error)) => { + crate::xlog_warn!("D3D12.X: {error}; title queue SignalX not submitted"); + return crate::util::E_FAIL; + } + } + } +} + +unsafe fn q_signal_x_serialized(this: *mut c_void, fence: *mut c_void, value: u64, prepared: super::title_textures::PreparedDownloads) -> Result<HRESULT, super::title_textures::SubmitDownloadsError> { const PC_SIGNAL: usize = 14; + let downloads = super::title_textures::submit_prepared_downloads(this, prepared)?; super::list_x::break_cycles_before_title_signal(this as usize, fence as usize, value); + super::title_textures::tie_downloads(fence, value, downloads); let f: unsafe extern "system" fn(*mut c_void, *mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, PC_SIGNAL)); let hr = f(this, fence, value); if hr >= 0 { super::fence_x::note_queue_signal(fence as usize, value); super::list_x::note_title_queue_signal(this as usize, fence as usize, value); } - hr + Ok(hr) } /// Fence::Signal (CPU) +unsafe extern "system" fn fence_completed(this: *mut c_void) -> u64 { + let f: unsafe extern "system" fn(*mut c_void) -> u64 = std::mem::transmute(orig_fn(this, slot_of(this, "GetCompletedValue"))); + super::title_textures::safe_fence_value(this as usize, f(this)) +} + unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT { - let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot_of(this, "Signal"))); + let f: unsafe extern "system" fn(*mut c_void, u64) -> HRESULT = std::mem::transmute(orig_fn(this, slot!(this, "Signal"))); let hr = f(this, value); super::fence_x::note_cpu_signal(this as usize); hr @@ -7251,18 +9178,25 @@ unsafe extern "system" fn fence_signal(this: *mut c_void, value: u64) -> HRESULT unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lists: *const *mut c_void) { type F = unsafe extern "system" fn(*mut c_void, u32, *const *mut c_void); - let f: F = std::mem::transmute(orig_fn(this, slot_of(this, "ExecuteCommandLists"))); - if n == 0 || lists.is_null() { - f(this, n, lists); + let f: F = std::mem::transmute(orig_fn(this, slot!(this, "ExecuteCommandLists"))); + // Internal XCL submits (`sparse` uploads/readbacks, `title_textures` uploads, tile zeroing) + // run inside `own_work()` — sometimes while holding internal locks (`sparse::STATE`, + // `vram::PAGES`). Forwarding them through the native slot, in the queue's ordered turn, skips + // `present::note_execute` -> `late_release::drain_known` -> `vram::recycle_ready`, preventing + // re-entrant lock self-deadlocks and keeping internal queues out of `present::QUEUES`. + if n == 0 || lists.is_null() || super::title_textures::is_own_work() { + super::queue_submit::with(this as usize, || f(this, n, lists)); stop_if_device_removed(); return; } + crate::stall::note_submitter(); // from here to the end: XCL's uploads and tile mappings before the lists, then the driver's // own work in the submission. Where that takes long, it is not the title's time // (`pso_async::title_held`) let _in_pc = super::pso_async::pc_call(); + let mut preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); // textures in title memory the CPU wrote since: uploaded again first - super::title_textures::refresh(this); + prepare_title_submission(this); // console-shaped lists run as the PC lists they were translated into (split title lists expand // into all of their recorded PC segments in exact chronological order) let mut mapped: Vec<*mut c_void> = Vec::with_capacity(n as usize); @@ -7270,26 +9204,76 @@ unsafe extern "system" fn q_execute_command_lists(this: *mut c_void, n: u32, lis if let Some(pc) = super::console_list::pc_list(l) { mapped.push(pc); } else { + // Deferred recording can wait for a pipeline. Keep that time solely in PipelineWait. + drop(preparation_stall); super::list_x::record_deferred(l); + preparation_stall = crate::stall::span(crate::stall::StallKind::SubmitPreparation); if !super::title_list::push_segments(l, &mut mapped) { mapped.push(l); } } } super::list_x::note_queue_for_lists(this as usize, &mapped); - super::list_x::execute_with_waits_on(this, &mapped, |chunk| { - let _ = super::alloc_pool::note_resubmits(this, chunk); - f(this, chunk.len() as u32, chunk.as_ptr()); - super::list_x::copy_scratch_submitted(this, chunk); - super::alloc_pool::executed(this, chunk); - super::list_x::signal_write64_fences(this, chunk); - super::list_x::readback_sparse_writes(this, chunk); - super::list_x::cpu_writes_after(this, chunk); + let plan = super::list_x::submission_plan(&mapped); + drop(preparation_stall); + let mut chunks = 0usize; + let mut gate = super::alloc_pool::SubmissionGate::default(); + let mut submitted = Vec::with_capacity(mapped.len()); + let track_shared_view_epochs = super::vram::srv_tracking_enabled(); + let track_native_generation_receipts = super::pso_async::rebuild_recipes_enabled(); + let _ = super::list_x::execute_submission_plan_until_failure_on(this, &plan, |chunk| { + super::queue_submit::with(this as usize, || { + let lists = chunk.lists(); + if !super::list_x::submit_title_chunk( + &mut gate, + this, + lists, + track_shared_view_epochs && chunk.uses_shared_view_heap(), + track_native_generation_receipts && chunk.has_native_generations(), + chunk.native_generations(), + || { + let _ = super::alloc_pool::note_resubmits(this, lists); + }, + || { + let started = gpu_timing_on().then(std::time::Instant::now); + f(this, lists.len() as u32, lists.as_ptr()); + if let Some(started) = started { + note_submission_timing(started.elapsed(), lists.len(), this); + } + }, + ) { + return (false, None); + } + chunks += 1; + submitted.extend_from_slice(lists); + super::list_x::copy_scratch_submitted(this, lists); + (true, chunk.submit_effects(this)) + }) }); - // the next uploads into textures kept in step start from the states these lists leave - super::title_textures::submitted(&mapped); - super::present::note_execute(this, &mapped); + super::alloc_pool::note_execute_call(chunks); + super::present::note_execute(this, &submitted); + stop_if_device_removed(); +} + +/// Complete correctness-critical uploads before any native title list executes. The D3D12 +/// submission API is void, so returning after preparation failure would silently lose the +/// title's exact submission; an unorderable failure must end the title instead. +pub(super) unsafe fn prepare_title_submission(queue: *mut c_void) { + use super::sparse::PreparationOutcome; + let outcome = super::title_textures::refresh(queue); + if outcome == PreparationOutcome::Ready { + return; + } stop_if_device_removed(); + let reason = match outcome { + PreparationOutcome::RetryRequired => "sparse upload preparation still failed after bounded retries", + PreparationOutcome::ExecutedUntracked => "a sparse upload executed without a retirement signal", + PreparationOutcome::Ready => unreachable!(), + }; + let message = format!("{reason} – the title is stopped before its GPU submission"); + crate::xlog_error!("{message}"); + crate::report::write_final(Some(message)); + end_title(0x8000_4005); } /// Wait (up to 10 s) until the GPU has finished the work submitted to the queues console code @@ -7302,13 +9286,11 @@ pub fn drain_gpu() { unsafe { // a fence per queue (they finish in any order) let mut fences = Vec::new(); - for q in super::present::known_queues() { - let qr = q as *mut c_void; - let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&qr) else { continue }; + for q in super::present::active_queues_held() { let submit = || { let f: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE) .map_err(|e| fence::api_error(dev, "CreateFence", e))?; - q.Signal(&f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; + native_queue_signal(&q, &f, 1).map_err(|e| fence::api_error(dev, "Signal", e))?; Ok(f) }; match submit() { @@ -7364,6 +9346,46 @@ unsafe fn report_dred_lists(head: *const D3D12_AUTO_BREADCRUMB_NODE, mut report: } } +#[cfg(test)] +mod submission_timing_tests { + use super::*; + + #[test] + fn submission_timing_keeps_exact_total_histogram_and_slowest_sample() { + let mut timing = SubmissionTiming::default(); + timing.record(0, 2); + timing.record(1, 9); + timing.record(2, 3); + timing.record(3, 5); + timing.record(8, 4); + assert_eq!((timing.submissions, timing.total_ns, timing.slowest_ns, timing.slowest_lists), (5, 14, 8, 4)); + assert_eq!((timing.histogram[0], timing.histogram[1], timing.histogram[3]), (2, 2, 1)); + assert_eq!((timing.percentile_upper_ns(95), timing.percentile_upper_ns(99)), (15, 15)); + } + + #[test] + fn submission_timing_saturates_totals_and_uses_bounded_last_bucket() { + let mut timing = SubmissionTiming { submissions: u64::MAX, total_ns: u64::MAX, ..Default::default() }; + timing.record(u64::MAX, 7); + assert_eq!((timing.submissions, timing.total_ns, timing.slowest_ns), (u64::MAX, u64::MAX, u64::MAX)); + assert_eq!(timing.histogram[crate::stall::HISTOGRAM_BUCKETS - 1], 1); + assert_eq!(timing.percentile_upper_ns(99), u64::MAX); + } + + #[test] + fn submission_warning_threshold_is_bounded_and_defaults() { + assert!(gpu_timing_on_value(Some("1"))); + for value in [None, Some(""), Some("0"), Some("true"), Some(" 1")] { + assert!(!gpu_timing_on_value(value)); + } + assert_eq!(slow_submission_us_value(None), 50_000); + assert_eq!(slow_submission_us_value(Some("bad")), 50_000); + assert_eq!(slow_submission_us_value(Some("0")), 0); + assert_eq!(slow_submission_us_value(Some("17")), 17_000); + assert_eq!(slow_submission_us_value(Some("18446744073709551615")), u64::MAX); + } +} + #[cfg(test)] mod dred_tests { use super::*; @@ -7500,6 +9522,17 @@ mod rect_list_pso_tests { REFUSED ); assert!(n == 1 && !copy.GS.pShaderBytecode.is_null()); + + for rejected in [E_OUTOFMEMORY, 0x887A_0005u32 as i32, 0x8000_4005u32 as i32] { + let mut copy = with_gs(&gs); + let mut n = 0; + assert_eq!(retry_without_rect_gs(&mut copy, true, |_| { n += 1; rejected }), rejected); + assert_eq!(n, 1, "{rejected:#x} must not be treated as a rect-GS rejection"); + } + let mut copy = with_gs(&gs); + let mut n = 0; + assert_eq!(retry_without_rect_gs(&mut copy, true, |_| { n += 1; if n == 1 { E_INVALIDARG } else { E_OUTOFMEMORY } }), E_OUTOFMEMORY); + assert_eq!(n, 2, "the retry's HRESULT is returned unchanged"); } /// `has_rect_list_gs`: a pipeline made with the rect list GS, not one made again without it @@ -7626,6 +9659,21 @@ mod cache_report_tests { crate::gpu::recomp::dxc::CacheStats::default() ); } + + #[test] + fn reports_without_submission_distribution_still_deserialize() { + let mut old = serde_json::to_value(D3d12Stats::default()).unwrap(); + let old = old.as_object_mut().unwrap(); + for field in [ + "submission_total_ns", "submission_mean_ms", "submission_p95_upper_ms", + "submission_p99_upper_ms", "submission_histogram_log2_ns", + ] { + old.remove(field); + } + let decoded: D3d12Stats = serde_json::from_value(serde_json::Value::Object(old.clone())).unwrap(); + assert_eq!(decoded.submission_total_ns, 0); + assert!(decoded.submission_histogram_log2_ns.is_empty()); + } } #[cfg(test)] @@ -7941,6 +9989,79 @@ mod queue_tests { assert!(NEWER_LIST_SLOTS.contains(&(129, 127)), "DispatchMesh must map to newer slot #129"); assert!(!NEWER_LIST_SLOTS.iter().any(|&(newer, _)| newer == 128), "newer slot #128 must not map to DispatchMesh"); } + + #[test] + fn own_work_execute_command_lists_bypasses_note_execute_and_drain() { + use std::sync::atomic::{AtomicUsize, Ordering}; + + static CALLED: AtomicUsize = AtomicUsize::new(0); + unsafe extern "system" fn fake_qi(_this: *mut c_void, _iid: *const GUID, out: *mut *mut c_void) -> HRESULT { + if !out.is_null() { + *out = std::ptr::null_mut(); + } + -2147467262 // E_NOINTERFACE + } + unsafe extern "system" fn fake_ref(_this: *mut c_void) -> u32 { 1 } + unsafe extern "system" fn fake_noop(_this: *mut c_void) {} + unsafe extern "system" fn fake_execute(_this: *mut c_void, n: u32, _lists: *const *mut c_void) { + CALLED.fetch_add(n as usize, Ordering::SeqCst); + } + + let iface = layout::find("ID3D12CommandQueue").expect("ID3D12CommandQueue layout"); + let exec_slot = layout::slot(iface, "ExecuteCommandLists").expect("ExecuteCommandLists slot"); + let n = iface.methods.len(); + let mut fake_vtbl = vec![fake_noop as usize; n + 1]; + fake_vtbl[0] = fake_qi as usize; + fake_vtbl[1] = fake_ref as usize; + fake_vtbl[2] = fake_ref as usize; + fake_vtbl[exec_slot] = fake_execute as usize; + fake_vtbl[n] = 0; + let orig = fake_vtbl.as_ptr() as usize; + + struct ClassCleanup(usize); + impl Drop for ClassCleanup { + fn drop(&mut self) { + let mut exts = Vec::new(); + CLASSES.lock().unwrap().retain(|c| { + if c.orig == self.0 { + exts.push(c.ext); + false + } else { + true + } + }); + if let Some(set) = EXTS.lock().unwrap().as_mut() { + for e in exts { + set.remove(&e); + } + } + } + } + let _cleanup = ClassCleanup(orig); + + let mut obj = orig; + let obj_ptr = &mut obj as *mut usize as *mut c_void; + struct LeaseCleanup(usize); + impl Drop for LeaseCleanup { + fn drop(&mut self) { + crate::hle::d3d12x::queue_submit::release(self.0, || 0); + } + } + let _lease_cleanup = LeaseCleanup(obj_ptr as usize); + let ext = unsafe { class_for(obj_ptr, orig, Kind::CommandQueue) }; + unsafe { *(obj_ptr as *mut usize) = ext; } + + let mut dummy_list = std::ptr::null_mut::<c_void>(); + let activity_before = crate::hle::d3d12x::present::activity(); + let before_called = CALLED.load(Ordering::SeqCst); + unsafe { + crate::hle::d3d12x::title_textures::own_work(|| { + q_execute_command_lists(obj_ptr, 1, &mut dummy_list as *mut *mut c_void); + }); + } + assert_eq!(CALLED.load(Ordering::SeqCst), before_called + 1, "original ExecuteCommandLists must still run"); + assert_eq!(crate::hle::d3d12x::present::activity(), activity_before, "own_work submit must bypass present::note_execute"); + } } #[cfg(test)] @@ -8238,6 +10359,183 @@ mod map_tests { } } + #[test] + fn known_stream_suffix_controls_cacheability() { + let console_vs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &console_vs); + let (subs, cacheable) = known_subobjects_checked(&stream.0); + assert!(cacheable); + assert_eq!(subs.len(), 1); + + let mut unknown = stream.0.clone(); + unknown.extend_from_slice(&999u32.to_le_bytes()); + unknown.extend_from_slice(&0u32.to_le_bytes()); + let (subs, cacheable) = known_subobjects_checked(&unknown); + assert!(!cacheable, "an unknown suffix must not share a projected-desc cache entry"); + assert_eq!(subs.len(), 1, "the known prefix remains usable"); + let desc = [unknown.len(), unknown.as_ptr() as usize]; + assert!(matches!(unsafe { stream_pipeline(desc.as_ptr() as *const c_void) }, StreamPipeline::Graphics(_, false))); + + let mut truncated_header = stream.0.clone(); + truncated_header.extend_from_slice(&[1, 2, 3, 4]); + assert!(!known_subobjects_checked(&truncated_header).1); + let mut truncated_payload = stream.0.clone(); + truncated_payload.pop(); + assert!(!known_subobjects_checked(&truncated_payload).1); + } + + #[test] + fn pipeline_stream_node_mask_defaults_and_round_trips() { + assert_eq!(stream_node_mask(&[]), 0); + let mut stream = StreamOut::default(); + stream.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_NODE_MASK, &4u32); + assert_eq!(stream_node_mask(&stream_subobjects(&stream.0).unwrap()), 4); + } + + #[test] + fn stream_pipeline_projects_legacy_rasterizer_fields() { + let console_vs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let parse = |ty: u32, raster: &[u8]| -> (D3D12_RASTERIZER_DESC, bool) { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &console_vs); + stream.raw(ty, raster, false); + let desc = [stream.0.len(), stream.0.as_ptr() as usize]; + match unsafe { stream_pipeline(desc.as_ptr() as *const c_void) } { + StreamPipeline::Graphics(g, cacheable) => (g.RasterizerState, cacheable), + _ => panic!("expected graphics stream pipeline"), + } + }; + let bytes = |p: *const u8, n| unsafe { std::slice::from_raw_parts(p, n) }; + + let r1 = D3D12_RASTERIZER_DESC1 { + FillMode: D3D12_FILL_MODE_WIREFRAME, + CullMode: D3D12_CULL_MODE_FRONT, + FrontCounterClockwise: true.into(), + DepthBias: 7.0, + DepthBiasClamp: 2.5, + SlopeScaledDepthBias: 1.5, + DepthClipEnable: false.into(), + MultisampleEnable: true.into(), + AntialiasedLineEnable: true.into(), + ForcedSampleCount: 4, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + }; + let (got, cacheable) = parse(27, bytes(&r1 as *const _ as *const u8, std::mem::size_of_val(&r1))); + assert!(cacheable); + assert_eq!((got.FillMode, got.CullMode, got.DepthBias), (r1.FillMode, r1.CullMode, 7)); + assert!(got.MultisampleEnable.as_bool() && got.AntialiasedLineEnable.as_bool()); + assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (4, r1.ConservativeRaster)); + + let r2 = D3D12_RASTERIZER_DESC2 { + FillMode: D3D12_FILL_MODE_SOLID, + CullMode: D3D12_CULL_MODE_NONE, + FrontCounterClockwise: false.into(), + DepthBias: -3.0, + DepthBiasClamp: 3.5, + SlopeScaledDepthBias: -0.5, + DepthClipEnable: true.into(), + LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_ALIASED, + ForcedSampleCount: 8, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + }; + let (got, cacheable) = parse(28, bytes(&r2 as *const _ as *const u8, std::mem::size_of_val(&r2))); + assert!(cacheable); + assert_eq!((got.FillMode, got.CullMode, got.DepthBias), (r2.FillMode, r2.CullMode, -3)); + assert!(!got.MultisampleEnable.as_bool() && !got.AntialiasedLineEnable.as_bool()); + assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (8, r2.ConservativeRaster)); + } + + #[test] + fn extended_rasterizer_state_stays_in_native_stream() { + let vs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let parse = |stream: &StreamOut| unsafe { + stream_pipeline([stream.0.len(), stream.0.as_ptr() as usize].as_ptr() as *const c_void) + }; + let make = |ty, payload: &[u8]| { + let mut stream = StreamOut::default(); + stream.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + stream.raw(ty, payload, false); + stream + }; + let bytes = |p: *const u8, n| unsafe { std::slice::from_raw_parts(p, n) }; + + let r1 = D3D12_RASTERIZER_DESC1 { DepthBias: 1.5, FillMode: D3D12_FILL_MODE_SOLID, CullMode: D3D12_CULL_MODE_BACK, ..Default::default() }; + let s1 = make(27, bytes(&r1 as *const _ as *const u8, std::mem::size_of_val(&r1))); + assert!(matches!(parse(&s1), StreamPipeline::GraphicsStream)); + + let r2_fractional = D3D12_RASTERIZER_DESC2 { DepthBias: -2.25, LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_ALIASED, ..Default::default() }; + let s2_fractional = make(28, bytes(&r2_fractional as *const _ as *const u8, std::mem::size_of_val(&r2_fractional))); + assert!(matches!(parse(&s2_fractional), StreamPipeline::GraphicsStream)); + + let r2 = D3D12_RASTERIZER_DESC2 { + DepthBias: -2.0, + FillMode: D3D12_FILL_MODE_WIREFRAME, + CullMode: D3D12_CULL_MODE_FRONT, + LineRasterizationMode: D3D12_LINE_RASTERIZATION_MODE_QUADRILATERAL_NARROW, + ForcedSampleCount: 4, + ConservativeRaster: D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON, + ..Default::default() + }; + let mut s2 = make(28, bytes(&r2 as *const _ as *const u8, std::mem::size_of_val(&r2))); + s2.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO, &D3D12_CACHED_PIPELINE_STATE { + pCachedBlob: vs.as_ptr() as *const c_void, CachedBlobSizeInBytes: vs.len(), + }); + assert!(matches!(parse(&s2), StreamPipeline::GraphicsStream)); + + let (subs, cacheable) = known_subobjects_checked(&s2.0); + assert!(cacheable); + let rewritten = unsafe { rewrite_graphics_stream(&subs, 0x1234usize as *mut c_void, b"PC VS", None, None, false, false) }; + let rewritten = stream_subobjects(&rewritten.0).expect("valid rewritten stream"); + assert!(rewritten.iter().all(|(ty, _)| *ty != 19), "cached PSO is never copied"); + assert_eq!(u64::from_le_bytes(rewritten.iter().find(|(ty, _)| *ty == 0).unwrap().1[..8].try_into().unwrap()), 0x1234); + assert_eq!(unsafe { payload_shader(rewritten.iter().find(|(ty, _)| *ty == 1).unwrap().1) }, Some(&b"PC VS"[..])); + let got: D3D12_RASTERIZER_DESC2 = unsafe { read_sub(rewritten.iter().find(|(ty, _)| *ty == 28).unwrap().1) }; + assert_eq!(got.DepthBias, -2.0); + assert_eq!(got.LineRasterizationMode, D3D12_LINE_RASTERIZATION_MODE_QUADRILATERAL_NARROW); + assert_eq!((got.ForcedSampleCount, got.ConservativeRaster), (4, D3D12_CONSERVATIVE_RASTERIZATION_MODE_ON)); + + let vi = D3D12_VIEW_INSTANCING_DESC { ViewInstanceCount: 1, ..Default::default() }; + let vi_only = make(22, bytes(&vi as *const _ as *const u8, std::mem::size_of_val(&vi))); + assert!(matches!(parse(&vi_only), StreamPipeline::Graphics(_, true)), "VIEW_INSTANCING remains Stage 3"); + + let mut unknown = s1.0.clone(); + unknown.extend_from_slice(&999u32.to_le_bytes()); + unknown.extend_from_slice(&0u32.to_le_bytes()); + let desc = [unknown.len(), unknown.as_ptr() as usize]; + assert!(matches!(unsafe { stream_pipeline(desc.as_ptr() as *const c_void) }, StreamPipeline::Graphics(_, false)), + "an unknown suffix retains Stage 1's uncacheable projected path"); + + for ty in [2, 5] { + let mut unreadable = StreamOut::default(); + unreadable.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + unreadable.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE(ty), &D3D12_SHADER_BYTECODE { + pShaderBytecode: 0x1000usize as *const c_void, BytecodeLength: 64, + }); + unreadable.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RASTERIZER1, &r1); + let desc = [unreadable.0.len(), unreadable.0.as_ptr() as usize]; + assert!(unsafe { stream_has_unreadable_shader(desc.as_ptr() as *const c_void) }); + assert!(matches!(parse(&unreadable), StreamPipeline::Unknown), "unreadable shader type {ty} must fail closed"); + } + let mut null_ps = StreamOut::default(); + null_ps.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + null_ps.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PS, &D3D12_SHADER_BYTECODE { + pShaderBytecode: std::ptr::null(), BytecodeLength: 64, + }); + let desc = [null_ps.0.len(), null_ps.0.as_ptr() as usize]; + assert!(unsafe { stream_has_unreadable_shader(desc.as_ptr() as *const c_void) }); + assert!(matches!(parse(&null_ps), StreamPipeline::Unknown)); + } + #[test] fn stream_pipeline_defaults_depth_enable_from_dsv_format() { let console_vs = crate::gpu::xbox::tests::sample( @@ -8280,7 +10578,7 @@ mod map_tests { } let desc = StreamDesc { size: stream.len(), ptr: stream.as_ptr() as usize }; match unsafe { stream_pipeline(&desc as *const _ as *const c_void) } { - StreamPipeline::Graphics(g) => *g, + StreamPipeline::Graphics(g, _) => *g, _ => panic!("expected graphics stream pipeline"), } }; @@ -8294,6 +10592,49 @@ mod map_tests { assert!(parse(None, Some(true)).DepthStencilState.DepthEnable.as_bool()); assert!(!parse(Some(40), Some(false)).DepthStencilState.DepthEnable.as_bool()); } + + /// A console compute stream's FLAGS subobject reaches the projected descriptor: + /// `dev_create_compute_pso` uses it for the driver's own cache key the same way a + /// legacy desc's flags are used (#2607). + #[test] + fn a_compute_stream_keeps_its_flags_subobject() { + let console_cs = crate::gpu::xbox::tests::sample( + 1, + &[crate::gpu::xbox::tests::fssm(&crate::gpu::xbox::tests::CODE, &[])], + ); + let parse = |flags: Option<u32>| -> D3D12_COMPUTE_PIPELINE_STATE_DESC { + let mut stream = Vec::new(); + let mut cs_bc = [0u8; 16]; + cs_bc[0..8].copy_from_slice(&(console_cs.as_ptr() as usize).to_le_bytes()); + cs_bc[8..16].copy_from_slice(&console_cs.len().to_le_bytes()); + stream.extend_from_slice(&6u32.to_le_bytes()); + stream.extend_from_slice(&0u32.to_le_bytes()); + stream.extend_from_slice(&cs_bc); + while stream.len() % 8 != 0 { + stream.push(0); + } + if let Some(f) = flags { + stream.extend_from_slice(&20u32.to_le_bytes()); + stream.extend_from_slice(&f.to_le_bytes()); + while stream.len() % 8 != 0 { + stream.push(0); + } + } + #[repr(C)] + struct StreamDesc { + size: usize, + ptr: usize, + } + let desc = StreamDesc { size: stream.len(), ptr: stream.as_ptr() as usize }; + match unsafe { stream_pipeline(&desc as *const _ as *const c_void) } { + StreamPipeline::Compute(c) => *c, + _ => panic!("expected compute stream pipeline"), + } + }; + assert_eq!(parse(None).Flags.0, 0); + assert_eq!(parse(Some(1)).Flags.0, 1, "the FLAGS subobject must reach the projected compute desc"); + assert_eq!(parse(Some(3)).Flags.0, 3); + } } #[cfg(test)] @@ -8353,12 +10694,27 @@ mod mesh_stream_tests { let owned = own_stream(d_valid.as_ptr() as *const c_void).expect("valid stream"); let OwnedDesc::Stream(_, buf, blobs) = owned else { panic!("expected Stream") }; assert_eq!(blobs.len(), 1); - assert_eq!(blobs[0], shader); + assert_eq!(&*blobs[0], shader.as_slice()); let rebased = u64::from_le_bytes(buf[8..16].try_into().unwrap()) as usize; assert_eq!(rebased, blobs[0].as_ptr() as usize); assert_ne!(rebased, shader.as_ptr() as usize); assert_eq!(&buf[32..48], &[0u8; 16], "zero-len shader entry cleared"); assert_eq!(&buf[56..72], &[0u8; 16], "cached PSO cleared"); + + // A retained stream must not extend the title's root-signature lifetime. Translation + // replaces it, while the shader payload remains rebased to recipe-owned bytes. + let mut rooted = [0u8; 40]; + rooted[0..4].copy_from_slice(&0u32.to_le_bytes()); + rooted[8..16].copy_from_slice(&0xDEAD_BEEFu64.to_le_bytes()); + rooted[16..20].copy_from_slice(&25u32.to_le_bytes()); + rooted[24..32].copy_from_slice(&(shader.as_ptr() as u64).to_le_bytes()); + rooted[32..40].copy_from_slice(&(shader.len() as u64).to_le_bytes()); + let rooted_desc = [rooted.len(), rooted.as_ptr() as usize]; + let OwnedDesc::Stream(_, rooted_buf, rooted_blobs) = own_stream(rooted_desc.as_ptr().cast()).unwrap() else { + panic!("expected Stream") + }; + assert_eq!(&rooted_buf[8..16], &[0; 8]); + assert_eq!(u64::from_le_bytes(rooted_buf[24..32].try_into().unwrap()) as usize, rooted_blobs[0].as_ptr() as usize); } } @@ -8399,17 +10755,18 @@ mod mesh_stream_tests { // Unique synthetic sampler key so we never touch global ABI_RS or real sampler caches. let sampler: crate::gpu::recomp::pso::StaticSampler = ([0x55AA_1968, 0xCAFE_1968, 0xBEEF_1968, 0x0001_1968], true); - let key: Vec<u32> = sampler.0.iter().copied().chain([1u32]).collect(); + let key = (this as usize, sampler.0.iter().copied().chain([1u32]).collect::<Vec<_>>()); + let other_key = (0x0D15_71C7usize, key.1.clone()); struct Cleanup { ext: usize, - key: Vec<u32>, + keys: Vec<(usize, Vec<u32>)>, } impl Drop for Cleanup { fn drop(&mut self) { CLASSES.lock().unwrap().retain(|c| c.ext != self.ext); if let Some(m) = ABI_RS_SAMPLERS.lock().unwrap().as_mut() { - m.remove(&self.key); + for key in &self.keys { m.remove(key); } } } } @@ -8421,8 +10778,15 @@ mod mesh_stream_tests { public: iface.methods.len(), scanned: iface.methods.len(), }); - ABI_RS_SAMPLERS.lock().unwrap().get_or_insert_with(HashMap::new).insert(key.clone(), 0x1234_5678); - let _cleanup = Cleanup { ext: ext_vtbl, key }; + { + let mut roots = ABI_RS_SAMPLERS.lock().unwrap(); + let roots = roots.get_or_insert_with(HashMap::new); + roots.insert(key.clone(), 0x1234_5678); + roots.insert(other_key.clone(), 0x8765_4321); + } + assert_eq!(unsafe { abi_rs_for(this, &[sampler]) }, Some(0x1234_5678 as *mut c_void)); + assert_eq!(unsafe { abi_rs_for(other_key.0 as *mut c_void, &[sampler]) }, Some(0x8765_4321 as *mut c_void)); + let _cleanup = Cleanup { ext: ext_vtbl, keys: vec![key, other_key] }; let make_tp = || crate::gpu::recomp::pso::TwoPass { cs: vec![0; 16], @@ -8437,12 +10801,12 @@ mod mesh_stream_tests { unsafe { // Case 1: driver returns S_OK but leaves *ppv == null let mut out: *mut c_void = std::ptr::null_mut(); - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, &mut out); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, 0, "MS", &iid, &mut out); assert_eq!(hr, E_INVALIDARG); assert!(out.is_null()); // Case 2: caller passes ppv == null - let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, "MS", &iid, std::ptr::null_mut()); + let hr = finish_two_pass(this, &stream, make_tp(), 0x1234_5678 as *mut c_void, 0, "MS", &iid, std::ptr::null_mut()); assert_eq!(hr, E_INVALIDARG); } } @@ -8976,3 +11340,180 @@ void main() { } } +#[cfg(test)] +mod list_release_tests { + use super::*; + + #[repr(C)] + struct FakeList { + vtable: usize, + refs: u32, + } + + const ALLOC: usize = 0x7E57_A130; + const PSO: usize = 0x7E57_D002; + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let l = &mut *(this as *mut FakeList); + l.refs += 1; + l.refs + } + + // the runtime frees the list, and a list created on another thread gets its address at once + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let l = &mut *(this as *mut FakeList); + l.refs -= 1; + if l.refs == 0 { + super::super::bind::reset(this, ALLOC, PSO); + super::super::alloc_pool::created_on(this as usize, ALLOC, 0); + } + l.refs + } + + #[test] + fn a_new_list_at_a_released_lists_address_keeps_its_state() { + let pc = [0, add_ref as usize, release as usize]; + let ext = [pc.as_ptr() as usize, 0]; + let mut list = FakeList { vtable: ext.as_ptr() as usize + 8, refs: 2 }; + let this = &mut list as *mut FakeList as *mut c_void; + super::super::bind::reset(this, ALLOC + 0x10, PSO + 0x10); + let (kept, n) = unsafe { + assert_eq!(cl_release(this), 1); + (super::super::bind::tracked_pso(this), cl_release(this)) + }; + let pso = super::super::bind::tracked_pso(this); + let backing = super::super::alloc_pool::recording_backing_for_test(this as usize); + super::super::bind::forget(this); + super::super::alloc_pool::forget_list(this as usize); + assert_eq!(kept, PSO + 0x10, "another reference is left"); + assert_eq!(n, 0); + assert_eq!(pso, PSO, "the new list's bind state"); + assert_eq!(backing, Some(ALLOC), "the new list's allocator"); + } +} + +#[cfg(test)] +mod heap_release_order_tests { + use super::*; + + #[repr(C)] + struct FakeHeap { + vtable: *const usize, + refs: u32, + scripted: bool, + releases: u32, + freed: fn(usize), + ext_vtable: [usize; 4], + orig_vtable: [usize; 3], + } + + std::thread_local! { + static EVENTS: std::cell::RefCell<Vec<&'static str>> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn event(name: &'static str) { + EVENTS.with(|events| events.borrow_mut().push(name)); + } + + unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 { + let heap = &mut *(this as *mut FakeHeap); + if heap.scripted { + 3 // Make the helper take its compatibility path deterministically. + } else { + heap.refs += 1; + heap.refs + } + } + + unsafe extern "system" fn release(this: *mut c_void) -> u32 { + let heap = &mut *(this as *mut FakeHeap); + if heap.scripted { + heap.releases += 1; + if heap.releases == 2 { + (heap.freed)(this as usize); + 0 + } else { + 2 + } + } else { + heap.refs -= 1; + if heap.refs == 0 { + (heap.freed)(this as usize); + } + heap.refs + } + } + + fn fake(refs: u32, scripted: bool, freed: fn(usize)) -> *mut FakeHeap { + let heap = Box::into_raw(Box::new(FakeHeap { + vtable: std::ptr::null(), + refs, + scripted, + releases: 0, + freed, + ext_vtable: [0; 4], + orig_vtable: [0; 3], + })); + unsafe { + (*heap).orig_vtable[1] = add_ref as usize; + (*heap).orig_vtable[2] = release as usize; + (*heap).ext_vtable[0] = (*heap).orig_vtable.as_ptr() as usize; + (*heap).ext_vtable[2] = add_ref as usize; + (*heap).ext_vtable[3] = release as usize; + (*heap).vtable = (*heap).ext_vtable.as_ptr().add(1); + } + heap + } + + fn note_freed(_: usize) { + event("freed"); + } + + #[test] + fn last_release_takes_before_free_and_frees_afterward() { + EVENTS.with(|events| events.borrow_mut().clear()); + let heap = fake(2, false, note_freed); + unsafe { + assert_eq!(release_taking_first(heap.cast(), || event("take"), |()| event("after")), 1); + assert!(EVENTS.with(|events| events.borrow().is_empty()), "a non-final release keeps the state"); + assert_eq!(release_taking_first(heap.cast(), || event("take"), |()| event("after")), 0); + drop(Box::from_raw(heap)); + } + assert_eq!(EVENTS.with(|events| events.borrow().clone()), ["take", "freed", "after"]); + } + + #[test] + fn missed_probe_takes_once_after_final_release() { + EVENTS.with(|events| events.borrow_mut().clear()); + let heap = fake(0, true, note_freed); + unsafe { + assert_eq!(release_taking_first(heap.cast(), || event("take"), |()| event("after")), 0); + drop(Box::from_raw(heap)); + } + assert_eq!( + EVENTS.with(|events| events.borrow().clone()), + ["freed", "take", "after"], + "the compatibility fallback cannot close the post-free address-reuse window" + ); + } + + #[test] + fn memory_heap_release_keeps_replacement_at_reused_address() { + fn replace(addr: usize) { + let replacement = HeapUma { size: 0x2_0000, align: 0x1_0000, prefer_coherent: false, cpu_readback: false, block: None }; + HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(addr, replacement); + } + + let heap = fake(1, false, replace); + let addr = heap as usize; + let old = HeapUma { size: 0x1_0000, align: 0x1_0000, prefer_coherent: false, cpu_readback: false, block: None }; + HEAP_UMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(addr, old); + unsafe { + assert_eq!(mem_heap_release(heap.cast()), 0); + drop(Box::from_raw(heap)); + } + let kept = HEAP_UMA.lock().unwrap().as_mut().and_then(|heaps| heaps.remove(&addr)); + assert_eq!(kept.map(|heap| heap.size), Some(0x2_0000), "the final Release must not remove replacement bookkeeping"); + } +} + diff --git a/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs new file mode 100644 index 0000000000..c35b505bfe --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/real/compute_build_key.rs @@ -0,0 +1,254 @@ +use std::{ + hash::{Hash, Hasher}, + sync::Arc, +}; + +use windows::Win32::Graphics::Direct3D12::D3D12_COMPUTE_PIPELINE_STATE_DESC; + +use crate::gpu::recomp::pso::ComputePolicyKey; + +/// The translated compute root-signature layout. A version change must change this tag. +const COMPUTE_ABI_SCHEMA: u32 = 1; + +/// Canonical identity of a requested compute build, before translation begins. +/// +/// `device` is safe identity, rather than an unretained COM pointer: the real backend owns its +/// device reference for the process lifetime. The ABI static-sampler set is transitively and +/// collision-freely identified by the complete shader bytes, translation policy, and sampler +/// base; those bytes also identify the program's intrinsic wave mode. The title root signature +/// and cached PSO are intentionally absent: translation replaces both before calling the PC driver. +#[derive(Clone, Debug)] +pub(in crate::hle::d3d12x) struct ComputeBuildKey { + device: usize, + node_mask: u32, + flags: i32, + shader: Arc<[u8]>, + shader_digest: u64, + shader_len: usize, + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + abi_schema: u32, + static_sampler_base: u32, +} + +impl PartialEq for ComputeBuildKey { + fn eq(&self, other: &Self) -> bool { + self.device == other.device + && self.node_mask == other.node_mask + && self.flags == other.flags + && self.windows == other.windows + && self.split_wave64 == other.split_wave64 + && self.policy == other.policy + && self.abi_schema == other.abi_schema + && self.static_sampler_base == other.static_sampler_base + && self.shader_digest == other.shader_digest + && self.shader_len == other.shader_len + && self.shader == other.shader + } +} + +impl Eq for ComputeBuildKey {} + +impl Hash for ComputeBuildKey { + fn hash<H: Hasher>(&self, state: &mut H) { + self.device.hash(state); + self.node_mask.hash(state); + self.flags.hash(state); + self.windows.hash(state); + self.split_wave64.hash(state); + self.policy.hash(state); + self.abi_schema.hash(state); + self.static_sampler_base.hash(state); + self.shader_digest.hash(state); + self.shader_len.hash(state); + } +} + +impl ComputeBuildKey { + pub(in crate::hle::d3d12x) fn capture( + device: usize, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + shader: Arc<[u8]>, + split_wave64: bool, + ) -> Self { + Self::from_descriptor( + device, + desc, + shader, + crate::gpu::recomp::pso::mem_windows(), + split_wave64, + crate::gpu::recomp::pso::compute_policy_key(), + ) + } + + fn from_descriptor( + device: usize, + desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, + shader: Arc<[u8]>, + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + ) -> Self { + Self::from_parts(device, desc.NodeMask, desc.Flags.0, shader, windows, split_wave64, policy) + } + + fn from_parts( + device: usize, + node_mask: u32, + flags: i32, + shader: Arc<[u8]>, + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + ) -> Self { + debug_assert_ne!(device, 0); + let shader_digest = crate::gpu::shader::fnv64(&shader); + Self::from_parts_with_digest( + device, node_mask, flags, shader, shader_digest, windows, split_wave64, policy, + ) + } + + fn from_parts_with_digest( + device: usize, + node_mask: u32, + flags: i32, + shader: Arc<[u8]>, + shader_digest: u64, + windows: u32, + split_wave64: bool, + policy: ComputePolicyKey, + ) -> Self { + let shader_len = shader.len(); + Self { + device, + node_mask, + flags, + shader, + shader_digest, + shader_len, + windows, + split_wave64, + policy, + abi_schema: COMPUTE_ABI_SCHEMA, + static_sampler_base: 0, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::hash_map::DefaultHasher; + + fn hash(key: &ComputeBuildKey) -> u64 { + let mut hasher = DefaultHasher::new(); + key.hash(&mut hasher); + hasher.finish() + } + + fn policy() -> ComputePolicyKey { + ComputePolicyKey { + direct: false, + structured: true, + precise_x64_masks: true, + wave64_spin: true, + safe_barrier: true, + direct_compact: None, + direct_compact_nest: None, + direct_piece_limit: 0, + per_lane: false, + disabled_dxil_optimizations: 0, + } + } + + fn key() -> ComputeBuildKey { + ComputeBuildKey::from_parts(1, 2, 3, [4, 5].into(), 6, false, policy()) + } + + #[test] + fn every_compute_build_input_splits_the_key() { + let base = key(); + macro_rules! different { + ($field:ident, $value:expr) => {{ + let mut other = base.clone(); + other.$field = $value; + assert_ne!(base, other, stringify!($field)); + assert_ne!(hash(&base), hash(&other), stringify!($field)); + }}; + } + different!(device, 9); + different!(node_mask, 9); + different!(flags, 9); + different!(windows, 9); + different!(split_wave64, true); + different!(abi_schema, 9); + different!(static_sampler_base, 9); + + let mutate_policy = |f: fn(&mut ComputePolicyKey)| { + let mut other = base.clone(); + f(&mut other.policy); + assert_ne!(base, other); + assert_ne!(hash(&base), hash(&other)); + }; + mutate_policy(|p| p.direct = true); + mutate_policy(|p| p.structured = false); + mutate_policy(|p| p.precise_x64_masks = false); + mutate_policy(|p| p.wave64_spin = false); + mutate_policy(|p| p.safe_barrier = false); + mutate_policy(|p| p.direct_compact = Some(true)); + mutate_policy(|p| p.direct_compact_nest = Some("outer".into())); + mutate_policy(|p| p.direct_piece_limit = 1); + mutate_policy(|p| p.per_lane = true); + mutate_policy(|p| p.disabled_dxil_optimizations = 1); + + let other = ComputeBuildKey::from_parts(1, 2, 3, [4, 6].into(), 6, false, policy()); + assert_ne!(base, other, "shader"); + assert_ne!(hash(&base), hash(&other), "shader"); + } + + #[test] + fn equal_keys_have_equal_hashes() { + assert_eq!(hash(&key()), hash(&key())); + } + + #[test] + fn shader_identity_compares_all_bytes_after_a_digest_collision() { + let base = key(); + let other = ComputeBuildKey::from_parts_with_digest( + 1, 2, 3, [5, 4].into(), base.shader_digest, 6, false, policy(), + ); + assert_eq!(hash(&base), hash(&other)); + assert_ne!(base, other); + } + + #[test] + fn descriptor_padding_is_not_part_of_the_key() { + let mut a = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + let mut b = D3D12_COMPUTE_PIPELINE_STATE_DESC::default(); + a.NodeMask = 7; + b.NodeMask = 7; + a.Flags = windows::Win32::Graphics::Direct3D12::D3D12_PIPELINE_STATE_FLAGS(1); + b.Flags = windows::Win32::Graphics::Direct3D12::D3D12_PIPELINE_STATE_FLAGS(1); + let padding = std::mem::offset_of!(D3D12_COMPUTE_PIPELINE_STATE_DESC, NodeMask) + + std::mem::size_of::<u32>(); + let padding_end = std::mem::offset_of!(D3D12_COMPUTE_PIPELINE_STATE_DESC, CachedPSO); + assert!(padding_end > padding); + unsafe { + std::ptr::write_bytes((&mut b as *mut _ as *mut u8).add(padding), 0xa5, padding_end - padding); + } + assert_eq!( + ComputeBuildKey::from_descriptor(1, &a, [2, 3].into(), 4, false, policy()), + ComputeBuildKey::from_descriptor(1, &b, [2, 3].into(), 4, false, policy()), + ); + } + + #[test] + fn build_key_shares_the_owned_shader_allocation() { + let shader: Arc<[u8]> = [7, 8, 9].into(); + let pointer = shader.as_ptr(); + let key = ComputeBuildKey::from_parts(1, 0, 0, shader.clone(), 1, false, policy()); + assert_eq!(key.shader.as_ptr(), pointer); + assert_eq!(Arc::strong_count(&shader), 2); + } +} diff --git a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs index 6fa76b4cbf..e980ee6ca3 100644 --- a/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs +++ b/crates/xcl/src/hle/d3d12x/real/dispatch_chain.rs @@ -1,8 +1,10 @@ //! PSOs for a split compute entry. The first piece is the real PSO returned //! to the caller. Other pieces and the lazily built whole form belong to it. use super::*; +use super::super::used_journal::Journal; use crate::gpu::{dxil::kernel::DispatchChain, recomp::pso}; -use std::sync::{Arc, LazyLock, OnceLock}; +use std::collections::HashSet; +use std::sync::{Arc, LazyLock, OnceLock, Weak}; static PROGRAMS: AtomicU64 = AtomicU64::new(0); static PIECES: AtomicU64 = AtomicU64::new(0); @@ -14,6 +16,63 @@ static LIVE: AtomicU64 = AtomicU64::new(0); static PEAK: AtomicU64 = AtomicU64::new(0); static WANTED: AtomicU64 = AtomicU64::new(0); +struct IndirectUsed { + now: Journal, +} + +static INDIRECT_USED: OnceLock<IndirectUsed> = OnceLock::new(); +static EARLIER_INDIRECT_USED: LazyLock<HashSet<u64>> = LazyLock::new(|| { + if cfg!(test) { + HashSet::new() + } else { + parse_used(&std::fs::read_to_string(indirect_used_path()).unwrap_or_default()) + } +}); + +fn parse_used(text: &str) -> HashSet<u64> { + text.lines() + .filter_map(|line| u64::from_str_radix(line.trim(), 16).ok()) + .filter(|&record| record != 0) + .collect() +} + +fn indirect_used_path() -> std::path::PathBuf { + crate::gpu::recomp::dxc::cache_dir().join("used-indirect-split.txt") +} + +fn indirect_used() -> &'static IndirectUsed { + INDIRECT_USED.get_or_init(|| { + if cfg!(test) { + return IndirectUsed { now: Journal::memory(HashSet::new()) }; + } + let path = indirect_used_path(); + let now = Journal::file(path, EARLIER_INDIRECT_USED.clone()); + IndirectUsed { now } + }) +} + +fn note_indirect_use(chain: &Chain) { + if !chain.indirect_noted.swap(true, Ordering::Relaxed) { + indirect_used().now.note(chain.builder.record); + } +} + +pub(crate) fn earlier_indirect_used() -> HashSet<u64> { + EARLIER_INDIRECT_USED.clone() +} + +pub(crate) fn shutdown_indirect_used(timeout: std::time::Duration) { + if let Some(used) = INDIRECT_USED.get() { + let _ = used.now.shutdown_bounded(timeout); + } +} + +pub(crate) fn flush_indirect_used(timeout: std::time::Duration) { + if let Some(used) = INDIRECT_USED.get() { + let _ = used.now.flush_bounded(timeout); + } +} + pub(crate) fn log_counts() { let mib = |a: &AtomicU64| a.load(Ordering::Relaxed) >> 20; crate::xlog_info!("compute split: {} programs split, {} pieces built, {} chained dispatches issued in {} slabs; scratch {} MiB (most {}, largest dispatch {} in one slab)", @@ -33,52 +92,245 @@ struct PipelineBuilder { device: ID3D12Device, create: PsoFn, signature: ID3D12RootSignature, + samplers: Vec<pso::StaticSampler>, flags: D3D12_PIPELINE_STATE_FLAGS, node: u32, record: u64, + mode: ComputeBuild, } impl PipelineBuilder { - unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Option<ID3D12PipelineState> { + unsafe fn pipeline(&self, dxil: &[u8], iid: &GUID) -> Result<ID3D12PipelineState, HRESULT> { let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { NodeMask: self.node, Flags: self.flags, ..Default::default() }; let mut raw = std::ptr::null_mut(); let (hr, _, _) = compute_container(self.device.as_raw(), self.create, &desc, self.signature.as_raw(), - dxil, self.record, iid, &mut raw, ComputeBuild::Chain); - (hr >= 0 && !raw.is_null()).then(|| ID3D12PipelineState::from_raw(raw)) + dxil, &self.samplers, self.record, iid, &mut raw, self.mode); + if hr >= 0 && !raw.is_null() { Ok(ID3D12PipelineState::from_raw(raw)) } else { Err(hr) } + } +} + +/// One exact chain's whole-form outcome. The owning `Chain` fixes device, DXIL, root signature, +/// flags and node; releasing/recreating the pipeline gets a fresh outcome. +pub(super) struct WholeBuild<T> { + result: OnceLock<Result<T, HRESULT>>, + retry_at: Mutex<Option<std::time::Instant>>, +} + +impl<T: Clone> WholeBuild<T> { + pub(super) fn new() -> Self { + Self { result: OnceLock::new(), retry_at: Mutex::new(None) } + } + + pub(super) fn get_or_build(&self, now: std::time::Instant, build: impl FnOnce() -> Result<T, HRESULT>) -> Result<T, HRESULT> { + if let Some(result) = self.result.get() { + return result.clone(); + } + let mut retry_at = self.retry_at.lock().unwrap(); + if let Some(result) = self.result.get() { + return result.clone(); + } + if retry_at.is_some_and(|at| now < at) { + return Err(crate::util::E_OUTOFMEMORY); + } + match build() { + Err(hr) if hr == crate::util::E_OUTOFMEMORY => { + *retry_at = Some(now + WHOLE_RETRY); + Err(hr) + } + result => { + let _ = self.result.set(result.clone()); + result + } + } + } + + fn ready(&self) -> Option<Result<T, HRESULT>> { + self.result.get().cloned() } } +/// A transient whole-form OOM is retried after memory has had time to drain. +const WHOLE_RETRY: std::time::Duration = std::time::Duration::from_secs(10); + struct Chain { builder: Arc<PipelineBuilder>, tail: Vec<ID3D12PipelineState>, words: u32, whole_code: Vec<u8>, - whole: OnceLock<ID3D12PipelineState>, - build_whole: Mutex<()>, + whole: WholeBuild<ID3D12PipelineState>, + plan: Weak<DispatchChain>, + indirect: IndirectBuild, + indirect_noted: AtomicBool, +} + +struct IndirectChain { + signature: ID3D12RootSignature, + whole: ID3D12PipelineState, + pieces: Vec<ID3D12PipelineState>, + _charge: IndirectCharge, +} + +struct IndirectCharge(usize); + +impl Drop for IndirectCharge { + fn drop(&mut self) { + INDIRECT_VARIANT_SOURCE.fetch_sub(self.0, Ordering::AcqRel); + } +} + +struct IndirectBuild { + requested: AtomicBool, + result: OnceLock<Result<Arc<IndirectChain>, HRESULT>>, +} + +impl IndirectBuild { + fn new() -> Self { + Self { requested: AtomicBool::new(false), result: OnceLock::new() } + } } impl Chain { unsafe fn whole(&self) -> Result<ID3D12PipelineState, String> { - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let _guard = self.build_whole.lock().unwrap(); - if let Some(p) = self.whole.get() { return Ok(p.clone()); } - let p = self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState)).ok_or("whole compute pipeline")?; - let _ = self.whole.set(p.clone()); - Ok(p) + self.whole + .get_or_build(std::time::Instant::now(), || self.builder.pipeline(&self.whole_code, &pc_iid(Kind::PipelineState))) + .map_err(|hr| if hr == crate::util::E_OUTOFMEMORY { "whole compute pipeline: out of memory".into() } else { format!("whole compute pipeline ({hr:#x})") }) } } static CHAINS: LazyLock<Mutex<HashMap<usize, Arc<Chain>>>> = LazyLock::new(Default::default); +/// Shared for the process lifetime so chains with a common piece also share its driver blob. +static SIGNATURES: LazyLock<Mutex<HashMap<(usize, bool, Vec<u32>), ID3D12RootSignature>>> = LazyLock::new(Default::default); + +fn sampler_key(samplers: &[pso::StaticSampler]) -> Vec<u32> { + samplers.iter().flat_map(|(words, comparison)| words.iter().copied().chain([*comparison as u32])).collect() +} + +const INDIRECT_PLAN_BYTES: usize = 64 << 20; +const INDIRECT_VARIANT_BYTES: usize = 64 << 20; +static INDIRECT_VARIANT_SOURCE: AtomicUsize = AtomicUsize::new(0); + +fn reserve_indirect_source(used: &AtomicUsize, bytes: usize, limit: usize) -> bool { + used.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| { + current.checked_add(bytes).filter(|&next| next <= limit) + }).is_ok() +} + +#[derive(Default)] +struct PlanCache { + bytes: usize, + plans: std::collections::VecDeque<(usize, Arc<DispatchChain>)>, +} + +impl PlanCache { + fn insert(&mut self, plan: Arc<DispatchChain>, limit: usize) { + let key = Arc::as_ptr(&plan) as usize; + if let Some(at) = self.plans.iter().position(|p| p.0 == key) { + self.plans.remove(at); + } else { + self.bytes = self.bytes.saturating_add(plan.pieces.iter().map(Vec::capacity).sum::<usize>()); + } + self.plans.push_back((key, plan)); + while self.bytes > limit { + let Some((_, old)) = self.plans.pop_front() else { break }; + self.bytes = self.bytes.saturating_sub(old.pieces.iter().map(Vec::capacity).sum::<usize>()); + } + } +} + +fn retain_indirect_plan(plan: Arc<DispatchChain>) { + static PLANS: LazyLock<Mutex<PlanCache>> = LazyLock::new(Default::default); + PLANS.lock().unwrap().insert(plan, INDIRECT_PLAN_BYTES); +} + +fn build_indirect(chain: &Arc<Chain>) -> Result<Arc<IndirectChain>, HRESULT> { + let plan = chain.plan.upgrade().ok_or(E_INVALIDARG)?; + let source_bytes = plan.pieces.iter().map(Vec::len).sum::<usize>().saturating_add(chain.whole_code.len()); + if !reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, source_bytes, INDIRECT_VARIANT_BYTES) { + return Err(E_OUTOFMEMORY); + } + let charge = IndirectCharge(source_bytes); + let signature = unsafe { signature_for(&chain.builder.device, &chain.builder.samplers, true) }.ok_or(E_INVALIDARG)?; + let builder = Arc::new(PipelineBuilder { + device: chain.builder.device.clone(), + create: chain.builder.create, + signature: signature.clone(), + samplers: chain.builder.samplers.clone(), + flags: chain.builder.flags, + node: chain.builder.node, + record: chain.builder.record, + mode: ComputeBuild::IndirectChain, + }); + // These variants are speculative: the ready direct whole form remains correct. Keep their + // cold driver compiles on this one low-impact lane instead of fanning out across PSO workers. + let mut pieces = Vec::with_capacity(plan.pieces.len()); + for code in &plan.pieces { + pieces.push(unsafe { builder.pipeline(code, &pc_iid(Kind::PipelineState))? }); + } + let whole = unsafe { builder.pipeline(&chain.whole_code, &pc_iid(Kind::PipelineState))? }; + Ok(Arc::new(IndirectChain { signature, whole, pieces, _charge: charge })) +} + +fn indirect_blobs_present(chain: &Chain, plan: &DispatchChain) -> bool { + plan.pieces.iter().map(Vec::as_slice).chain([chain.whole_code.as_slice()]).all(|dxil| { + super::driver_cache::path_for_chain_root_node( + dxil, + chain.builder.flags.0, + super::driver_cache::ChainRoot::IndirectCbv, + &chain.builder.samplers, + chain.builder.node, + ) + .and_then(|path| std::fs::metadata(path).ok()) + .is_some_and(|metadata| metadata.len() != 0) + }) +} + +fn request_indirect(chain: &Arc<Chain>) { + if chain.indirect.requested.swap(true, Ordering::AcqRel) { + return; + } + static BUILDS: LazyLock<Option<std::sync::mpsc::Sender<Weak<Chain>>>> = LazyLock::new(|| { + let (tx, rx) = std::sync::mpsc::channel::<Weak<Chain>>(); + std::thread::Builder::new().name("xcl-pso-chain-indirect".into()).stack_size(64 << 20).spawn(move || { + while let Ok(weak) = rx.recv() { + let Some(chain) = weak.upgrade() else { continue }; + let result = build_indirect(&chain); + let _ = chain.indirect.result.set(result); + } + }).ok().map(|_| tx) + }); + if BUILDS.as_ref().is_none_or(|queue| queue.send(Arc::downgrade(chain)).is_err()) { + chain.indirect.requested.store(false, Ordering::Release); + } +} + +unsafe fn signature_for(dev: &ID3D12Device, samplers: &[pso::StaticSampler], indirect: bool) -> Option<ID3D12RootSignature> { + let key = (dev.as_raw() as usize, indirect, sampler_key(samplers)); + if let Some(signature) = SIGNATURES.lock().unwrap().get(&key).cloned() { + return Some(signature); + } + let created = match if indirect { + pso::dispatch_chain_indirect_root_signature(dev, samplers) + } else { + pso::dispatch_chain_root_signature(dev, samplers) + } { + Ok(signature) => signature, + Err(e) => { + note_translation_error(format!("dispatch-chain root signature: {e}")); + return None; + } + }; + Some(SIGNATURES.lock().unwrap().entry(key).or_insert(created).clone()) +} pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUTE_PIPELINE_STATE_DESC, iid: *const GUID, result: *mut *mut c_void, record: u64, whole: &[u8], samplers: &[pso::StaticSampler], plan: Arc<DispatchChain>) -> Option<usize> { if result.is_null() || iid.is_null() || plan.pieces.len() < 2 { return None; } let dev = ID3D12Device::from_raw_borrowed(&this)?; - let signature = pso::dispatch_chain_root_signature(dev, samplers).ok()?; + let signature = signature_for(dev, samplers, false)?; let rs = signature.as_raw() as usize; - let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, - flags: desc.Flags, node: desc.NodeMask, record }); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create, signature, samplers: samplers.to_vec(), + flags: desc.Flags, node: desc.NodeMask, record, mode: ComputeBuild::DirectChain }); let jobs = (0..plan.pieces.len()).map(|i| { let plan = plan.clone(); let builder = builder.clone(); @@ -91,7 +343,14 @@ pub(super) unsafe fn build(this: *mut c_void, create: PsoFn, desc: &D3D12_COMPUT let mut pieces = built.into_iter().collect::<Option<Vec<_>>>()?.into_iter(); let first = pieces.next()?; let chain = Arc::new(Chain { builder, tail: pieces.collect(), words: plan.dwords_per_group, - whole_code: whole.to_vec(), whole: OnceLock::new(), build_whole: Mutex::new(()) }); + whole_code: whole.to_vec(), whole: WholeBuild::new(), plan: Arc::downgrade(&plan), + indirect: IndirectBuild::new(), indirect_noted: AtomicBool::new(false) }); + retain_indirect_plan(plan.clone()); + // Initialize the journal on this preparation worker, never on the first recording call. + let _ = indirect_used(); + if EARLIER_INDIRECT_USED.contains(&record) && indirect_blobs_present(&chain, &plan) { + request_indirect(&chain); + } PROGRAMS.fetch_add(1, Ordering::Relaxed); PIECES.fetch_add(plan.pieces.len() as u64, Ordering::Relaxed); *result = first.into_raw(); @@ -122,18 +381,53 @@ impl Drop for Scratch { struct Recording { scratch: Arc<Scratch>, + /// Keep the title-visible direct first piece alive while this recording may still execute. + /// Indirect execution uses its separate CBV-compatible duplicates. first: ID3D12PipelineState, chain: Arc<Chain>, + _indirect_commands: Option<Arc<CommandStorage>>, } static RECORDINGS: LazyLock<Mutex<HashMap<usize, Vec<Arc<Recording>>>>> = LazyLock::new(Default::default); /// list → the allocator it records on and the scratch its chains share: they are dispatched one /// after another, with a barrier between them (the recordings keep it alive) static SHARED: LazyLock<Mutex<HashMap<usize, (usize, std::sync::Weak<Scratch>)>>> = LazyLock::new(Default::default); +/// One recording list reuses indirect commands at offset zero. Buffer state transitions are +/// resource-wide, so storage is deliberately never shared across lists. +static COMMANDS: LazyLock<Mutex<HashMap<usize, (usize, Weak<CommandStorage>)>>> = LazyLock::new(Default::default); + +struct CommandStorage { + buffer: ID3D12Resource, + bytes: u64, +} + +const COMMAND_STORAGE_BYTES: u64 = 64 << 10; + +fn command_storage_bytes(bytes: u64) -> u64 { + bytes.max(COMMAND_STORAGE_BYTES).next_multiple_of(COMMAND_STORAGE_BYTES) +} + +unsafe fn commands_for( + dev: &ID3D12Device, list: usize, allocator: usize, bytes: u64, +) -> Option<Arc<CommandStorage>> { + { + let commands = COMMANDS.lock().unwrap(); + if let Some((_, storage)) = commands.get(&list).filter(|entry| entry.0 == allocator) { + if let Some(storage) = storage.upgrade().filter(|storage| storage.bytes >= bytes) { + return Some(storage); + } + } + } + let size = command_storage_bytes(bytes); + let storage = Arc::new(CommandStorage { buffer: pso::chain_commands_storage(dev, size)?, bytes: size }); + COMMANDS.lock().unwrap().insert(list, (allocator, Arc::downgrade(&storage))); + Some(storage) +} /// `list` begins another recording, which the GPU may run beside the last one. pub(in crate::hle::d3d12x) fn list_reset(list: usize) { SHARED.lock().unwrap().remove(&list); + COMMANDS.lock().unwrap().remove(&list); } /// `to` records right after `from` on the same allocator: its chains go on in `from`'s scratch. @@ -199,13 +493,41 @@ unsafe fn scratch_buffer(dev: &ID3D12Device, bytes: u64) -> Option<ID3D12Resourc resource } +fn remapped_grid(mut grid: [u32; 3], remap: Option<(u32, u32)>) -> Option<[u32; 3]> { + if grid.into_iter().any(|n| n > 65_535) { + return None; + } + if let Some((ratio, dim)) = remap { + let count = grid.get_mut(dim as usize)?; + let scaled = count.checked_mul(ratio)?; + // D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION (an SDK macro, not in windows-rs). + if scaled > 65_535 { + return None; + } + *count = scaled; + } + Some(grid) +} + /// Called with the original six ABI views bound. The extended signature is /// common to every piece and the whole fallback. Choose before recording any /// part of the dispatch, including when scratch allocation fails. pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, grid: [u32; 3]) -> Result<(), String> { + if grid.into_iter().any(|n| n > 65_535) { + return Err("dispatch group count exceeds 65535 on one axis".into()); + } let [x, y, z] = grid; let chain = CHAINS.lock().unwrap().get(&pso).cloned(); - let Some(chain) = chain else { list.Dispatch(x, y, z); return Ok(()) }; + let Some(chain) = chain else { + match remapped_grid(grid, super::pso_dispatch_remap(pso)) { + Some([x, y, z]) => list.Dispatch(x, y, z), + None => { + list.SetPipelineState(&super::remap_fallback::whole(pso)?); + list.Dispatch(x, y, z); + } + } + return Ok(()) + }; if grid.contains(&0) { return Ok(()); } // A title Reset can switch to a different PC allocator while this // recording is still submitted on the old one. Retain by backing. @@ -225,7 +547,7 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, return Ok(()); }; let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); - let held = Arc::new(Recording { scratch, first, chain }); + let held = Arc::new(Recording { scratch, first, chain, _indirect_commands: None }); RECORDINGS.lock().unwrap().entry(allocator).or_default().push(held.clone()); DISPATCHES.fetch_add(1, Ordering::Relaxed); SLABS.fetch_add(slabs.len() as u64, Ordering::Relaxed); @@ -233,12 +555,185 @@ pub(in crate::hle::d3d12x) unsafe fn dispatch(list: &ID3D12GraphicsCommandList, Ok(()) } +fn indirect_rounds() -> u32 { + static ROUNDS: OnceLock<u32> = OnceLock::new(); + *ROUNDS.get_or_init(|| std::env::var("XCL_SPLIT_INDIRECT_ROUNDS").ok().and_then(|v| v.trim().parse().ok()) + .filter(|&n| n > 0).unwrap_or(16u32).min(1024)) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum IndirectReadiness { + Run, + Request, + Fallback, + Fail(HRESULT), +} + +fn indirect_readiness( + whole: Option<Result<(), HRESULT>>, + indirect: Option<Result<(), HRESULT>>, +) -> IndirectReadiness { + match (whole, indirect) { + (_, Some(Ok(()))) => IndirectReadiness::Run, + (Some(Err(hr)), _) => IndirectReadiness::Fail(hr), + (Some(Ok(())), None) => IndirectReadiness::Request, + _ => IndirectReadiness::Fallback, + } +} + +/// Run one Dispatch-only indirect command through an existing split chain. A complete indirect +/// set is independent of the direct whole-form build. Otherwise preserve the synchronous fallback; +/// the slicer writes either bounded piece commands or the whole-form command, never a partial chain. +pub(in crate::hle::d3d12x) unsafe fn execute_indirect( + list: &ID3D12GraphicsCommandList, pso: usize, allocator: usize, args: u64, + bind: impl FnOnce(usize) -> Result<(), String>, +) -> Result<bool, String> { + let Some(chain) = CHAINS.lock().unwrap().get(&pso).cloned() else { return Ok(false) }; + note_indirect_use(&chain); + let whole = chain.whole.ready().map(|result| result.map(|_| ())); + let indirect = chain.indirect.result.get().map(|result| match result { + Ok(_) => Ok(()), + Err(hr) => Err(*hr), + }); + match indirect_readiness(whole, indirect) { + IndirectReadiness::Run => {} + IndirectReadiness::Request => { + request_indirect(&chain); + return Ok(false); + } + IndirectReadiness::Fallback => return Ok(false), + IndirectReadiness::Fail(hr) => return Err(format!("whole compute pipeline ({hr:#x})")), + }; + let Some(Ok(indirect)) = chain.indirect.result.get() else { unreachable!() }; + let indirect = indirect.clone(); + let allocator = if super::super::alloc_pool::enabled() { + super::super::alloc_pool::recording_backing(list.as_raw() as usize).unwrap_or(0) + } else { allocator }; + if allocator == 0 || list.GetType() == D3D12_COMMAND_LIST_TYPE_BUNDLE { return Ok(false); } + let group = u64::from(chain.words) * 4; + let Some((scratch, _)) = scratch_for(&chain.builder.device, list.as_raw() as usize, allocator, scratch_budget(), group) else { + return Ok(false); + }; + let signature = pso::dispatch_command_signature(&chain.builder.device)?; + let rounds = indirect_rounds(); + let command_bytes = pso::chain_tail_offset(rounds) + 12; + let commands = commands_for( + &chain.builder.device, list.as_raw() as usize, allocator, command_bytes, + ).ok_or("no command buffer for split ExecuteIndirect")?; + let first = ID3D12PipelineState::from_raw_borrowed(&(pso as *mut c_void)).ok_or("first compute piece")?.clone(); + pso::record_indirect_slicer(list, args, rounds, (scratch.bytes / group).max(1), &commands.buffer)?; + let bound = bind(indirect.signature.as_raw() as usize); + if bound.is_ok() { + list.SetPipelineState(&indirect.whole); + list.ExecuteIndirect(&signature, 1, &commands.buffer, + pso::chain_tail_offset(rounds), None::<&ID3D12Resource>, 0); + pso::record_dispatch_chain_indirect(list, &signature, &commands.buffer, rounds, &scratch.buffer, + indirect.pieces.iter()); + } + pso::restore_indirect_commands(list, &commands.buffer); + RECORDINGS.lock().unwrap().entry(allocator).or_default().push(Arc::new(Recording { + scratch, first, chain, _indirect_commands: Some(commands), + })); + bound?; + Ok(true) +} + #[cfg(test)] mod tests { - use super::{scratch_bytes, LEAST}; + use super::*; + + #[test] + fn indirect_used_records_parse_unique_nonzero_hex() { + assert_eq!(parse_used("1\n0000000000000002\ninvalid\n0\n1\n"), [1, 2].into()); + } + + #[test] + fn ready_indirect_set_does_not_wait_for_direct_whole() { + assert_eq!(indirect_readiness(None, Some(Ok(()))), IndirectReadiness::Run); + assert_eq!( + indirect_readiness(Some(Err(E_INVALIDARG)), Some(Ok(()))), + IndirectReadiness::Run, + ); + assert_eq!(indirect_readiness(Some(Ok(())), None), IndirectReadiness::Request); + assert_eq!(indirect_readiness(None, None), IndirectReadiness::Fallback); + assert_eq!( + indirect_readiness(Some(Ok(())), Some(Err(E_INVALIDARG))), + IndirectReadiness::Fallback, + ); + assert_eq!( + indirect_readiness(Some(Err(E_INVALIDARG)), Some(Err(E_OUTOFMEMORY))), + IndirectReadiness::Fail(E_INVALIDARG), + ); + } const MB: u64 = 1 << 20; + #[test] + fn indirect_command_storage_covers_the_fixed_recording_at_64k_granularity() { + assert_eq!(command_storage_bytes(12), 64 << 10); + assert_eq!(command_storage_bytes((64 << 10) + 1), 128 << 10); + assert!(command_storage_bytes(pso::chain_tail_offset(1024) + 12) + >= pso::chain_tail_offset(1024) + 12); + } + + #[test] + fn retained_indirect_plans_are_deduplicated_and_bounded() { + let plan = |byte: u8| Arc::new(DispatchChain { + pieces: vec![vec![byte; 40], vec![byte; 40]], + dwords_per_group: 4, + }); + let (first, second) = (plan(1), plan(2)); + let first_weak = Arc::downgrade(&first); + let mut cache = PlanCache::default(); + cache.insert(first.clone(), 100); + cache.insert(first, 100); + assert_eq!((cache.plans.len(), cache.bytes), (1, 80)); + cache.insert(second, 100); + assert_eq!((cache.plans.len(), cache.bytes), (1, 80)); + assert!(first_weak.upgrade().is_none(), "the oldest plan was released at the cap"); + } + + #[test] + fn indirect_variant_source_admission_never_exceeds_its_cap() { + let used = AtomicUsize::new(0); + assert!(reserve_indirect_source(&used, 60, 100)); + assert!(!reserve_indirect_source(&used, 41, 100)); + assert_eq!(used.load(Ordering::Relaxed), 60); + assert!(reserve_indirect_source(&used, 40, 100)); + assert_eq!(used.load(Ordering::Relaxed), 100); + } + + #[test] + fn signature_identity_includes_sampler_words_order_and_comparison() { + let a = ([1, 2, 3, 4], false); + let b = ([5, 6, 7, 8], true); + assert_eq!(sampler_key(&[a, b]), sampler_key(&[a, b])); + assert_ne!(sampler_key(&[a, b]), sampler_key(&[b, a])); + assert_ne!(sampler_key(&[a]), sampler_key(&[([1, 2, 3, 4], true)])); + } + + #[test] + fn remapped_grid_scales_only_its_dimension_and_refuses_overflow() { + assert_eq!(remapped_grid([3, 5, 7], Some((4, 1))), Some([3, 20, 7])); + assert_eq!(remapped_grid([3, 5, 7], None), Some([3, 5, 7])); + assert_eq!(remapped_grid([65_535, 1, 1], None), Some([65_535, 1, 1])); + assert_eq!(remapped_grid([65_536, 1, 1], None), None); + assert_eq!(remapped_grid([1, 65_536, 1], None), None); + assert_eq!(remapped_grid([1, 1, 65_536], None), None); + assert_eq!(remapped_grid([32_768, 1, 1], Some((2, 0))), None); + assert_eq!(remapped_grid([u32::MAX, 1, 1], Some((2, 0))), None); + assert_eq!(remapped_grid([1, 1, 1], Some((2, 3))), None); + } + + #[test] + fn released_pipeline_does_not_lend_its_remap_to_address_reuse() { + let pso = 0x7E57_6400usize; + super::super::note_pso_dispatch_remap(pso as *mut c_void, Some((4, 0))); + assert_eq!(super::super::pso_dispatch_remap(pso), Some((4, 0))); + super::super::forget_pso_for_test(pso); + assert_eq!(super::super::pso_dispatch_remap(pso), None); + } + #[test] fn a_list_recorded_after_another_goes_on_in_its_scratch() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -284,4 +779,97 @@ mod tests { assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, None, 400 * MB, 384 * MB), (9 * MB, true)); assert_eq!(scratch_bytes(9 * MB, 9 * MB, 4 * MB, Some(MB), 400 * MB, 384 * MB), (9 * MB, true)); } + + #[test] + fn a_non_oom_whole_failure_is_final_only_for_that_chain() { + let at = std::time::Instant::now(); + let whole: WholeBuild<u32> = WholeBuild::new(); + let mut calls = 0; + assert_eq!(whole.get_or_build(at, || { calls += 1; Err(crate::util::E_FAIL) }), Err(crate::util::E_FAIL)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY, || { calls += 1; Ok(7) }), Err(crate::util::E_FAIL)); + assert_eq!(calls, 1, "the same immutable chain does not repeat a deterministic driver failure"); + + let rebuilt: WholeBuild<u32> = WholeBuild::new(); + assert_eq!(rebuilt.get_or_build(at, || Ok(7)), Ok(7), "a new chain after policy/cache changes still builds"); + } + + #[test] + fn a_whole_oom_is_throttled_then_retried() { + let at = std::time::Instant::now(); + let whole: WholeBuild<u32> = WholeBuild::new(); + let mut calls = 0; + assert_eq!(whole.get_or_build(at, || { calls += 1; Err(crate::util::E_OUTOFMEMORY) }), Err(crate::util::E_OUTOFMEMORY)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY / 2, || { calls += 1; Ok(7) }), Err(crate::util::E_OUTOFMEMORY)); + assert_eq!(calls, 1, "calls during the cooldown do not enter the driver"); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY, || { calls += 1; Ok(7) }), Ok(7)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY * 2, || { calls += 1; Ok(8) }), Ok(7)); + assert_eq!(calls, 2, "the successful retry is retained"); + } + + #[test] + fn failed_binding_keeps_indirect_commands_until_allocator_reset() { + use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; + unsafe extern "system" fn never(_: *mut c_void, _: *const c_void, _: *const GUID, _: *mut *mut c_void) -> HRESULT { E_INVALIDARG } + unsafe { + let mut dev = None; + if D3D12CreateDevice(None, D3D_FEATURE_LEVEL_11_0, &mut dev).is_err() { + return crate::gpu::recomp::runner::skip_test("no GPU"); + } + let dev = dev.unwrap(); + let Ok(dxil) = crate::gpu::recomp::dxc::compile("[numthreads(1,1,1)] void main() {}", "main", "cs_6_0", &[]) else { + return crate::gpu::recomp::runner::skip_test("no DXC"); + }; + let rs = pso::dispatch_chain_root_signature(&dev, &[]).unwrap(); + let desc = D3D12_COMPUTE_PIPELINE_STATE_DESC { pRootSignature: std::mem::transmute_copy(&rs), + CS: D3D12_SHADER_BYTECODE { pShaderBytecode: dxil.as_ptr().cast(), BytecodeLength: dxil.len() }, ..Default::default() }; + let first: ID3D12PipelineState = dev.CreateComputePipelineState(&desc).unwrap(); + let whole = WholeBuild::new(); + whole.get_or_build(std::time::Instant::now(), || Ok(first.clone())).unwrap(); + let builder = Arc::new(PipelineBuilder { device: dev.clone(), create: never, signature: rs.clone(), samplers: Vec::new(), + flags: D3D12_PIPELINE_STATE_FLAG_NONE, node: 0, record: 0, mode: ComputeBuild::DirectChain }); + let key = first.as_raw() as usize; + let plan = Arc::new(DispatchChain { pieces: vec![dxil.clone(), dxil.clone()], dwords_per_group: 4 }); + assert!(reserve_indirect_source(&INDIRECT_VARIANT_SOURCE, 1, INDIRECT_VARIANT_BYTES)); + let indirect = Arc::new(IndirectChain { signature: rs.clone(), whole: first.clone(), + pieces: vec![first.clone(), first.clone()], _charge: IndirectCharge(1) }); + let indirect_build = IndirectBuild::new(); + indirect_build.requested.store(true, Ordering::Relaxed); + indirect_build.result.set(Ok(indirect)).unwrap_or_else(|_| unreachable!()); + CHAINS.lock().unwrap().insert(key, Arc::new(Chain { builder, tail: vec![first.clone()], words: 4, + whole_code: Vec::new(), whole, plan: Arc::downgrade(&plan), indirect: indirect_build, + indirect_noted: AtomicBool::new(false) })); + let ty = D3D12_COMMAND_LIST_TYPE_COMPUTE; + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(ty).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, ty, &alloc, None).unwrap(); + let (raw_list, allocator) = (list.as_raw() as usize, alloc.as_raw() as usize); + super::super::super::alloc_pool::created_on(raw_list, allocator, ty.0); + let args = pso::chain_commands_buffer(&dev, 1).unwrap(); + assert_eq!(execute_indirect(&list, key, allocator, args.GetGPUVirtualAddress(), |_| Err("bind failed".into())), Err("bind failed".into())); + let recorded = RECORDINGS.lock().unwrap().get(&allocator).unwrap()[0]._indirect_commands.clone().unwrap(); + let reused = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); + assert!(Arc::ptr_eq(&recorded, &reused)); + list_reset(raw_list); + let next_recording = commands_for(&dev, raw_list, allocator, pso::chain_tail_offset(1) + 12).unwrap(); + assert!(!Arc::ptr_eq(&recorded, &next_recording)); + list.Close().unwrap(); + allocator_reset(allocator); + list_reset(raw_list); + forget(key); + super::super::super::alloc_pool::forget_list(raw_list); + } + } + + #[test] + fn remap_compile_oom_retries_but_deterministic_failure_is_final() { + let at = std::time::Instant::now(); + let oom = super::super::remap_fallback::compile_error_hr("DXC: E_OUTOFMEMORY (0x8007000E)"); + let whole: WholeBuild<u32> = WholeBuild::new(); + assert_eq!(whole.get_or_build(at, || Err(oom)), Err(crate::util::E_OUTOFMEMORY)); + assert_eq!(whole.get_or_build(at + WHOLE_RETRY, || Ok(7)), Ok(7)); + + let compile = super::super::remap_fallback::compile_error_hr("dxc: invalid operation"); + let deterministic: WholeBuild<u32> = WholeBuild::new(); + assert_eq!(deterministic.get_or_build(at, || Err(compile)), Err(crate::util::E_INVALIDARG)); + assert_eq!(deterministic.get_or_build(at + WHOLE_RETRY, || Ok(8)), Err(crate::util::E_INVALIDARG)); + } } diff --git a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs index 6ca0572281..3bfe808dde 100644 --- a/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs +++ b/crates/xcl/src/hle/d3d12x/real/two_pass_identity.rs @@ -4,6 +4,8 @@ use windows::Win32::Graphics::Direct3D12::*; /// Bump on any change to two-pass cache key fields or ABI root-signature layout to invalidate stale disk entries. const TWO_PASS_CACHE_SCHEMA: u32 = 2; +/// Native extended graphics streams have a separate identity namespace from two-pass streams. +const GRAPHICS_STREAM_CACHE_SCHEMA: u32 = 1; /// ABI root signature layout tag for two-pass pipelines (`graphics = true`: 6 root UAVs + directly indexed heaps + IA flag). const TWO_PASS_ABI_RS_TAG: u32 = 0x5253_0001; @@ -176,7 +178,10 @@ unsafe fn hash_depth_stencil(h: &mut Fnv64, ty: u32, p: &[u8]) -> Option<()> { /// Canonical cache key `(hash, total_shader_bytes)` for a two-pass mesh/PS pipeline stream, /// hashing referenced shader bytecodes and normalized fixed-function state (never pointers or /// struct padding). Shader pointers in the stream must refer to live shader bytecode. Returns `None` if an unsupported, duplicate, or unknown subobject is active. -pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> Option<(u64, usize)> { +unsafe fn stream_key( + stream: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], schema: u32, + kind: u32, driver_id: u64, mem_windows: u32, +) -> Option<(u64, usize)> { let mut subs = stream_subobjects(stream)?; let total = subs.iter().map(|(ty, payload)| { let (_, align) = super::super::null::subobject_payload(*ty).unwrap(); @@ -190,12 +195,12 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp return None; } let mut h = Fnv64::new(); - h.u32(TWO_PASS_CACHE_SCHEMA); - h.u32(1); // stream kind + h.u32(schema); + h.u32(kind); h.u32(TWO_PASS_ABI_RS_TAG); h.u32(mem_windows); h.u64(driver_id); - samplers_hash_into(&mut h, ps_samplers); + samplers_hash_into(&mut h, samplers); let mut shader_bytes = 0usize; for (ty, payload) in subs { match ty { @@ -237,6 +242,16 @@ pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gp Some((h.finish(), shader_bytes)) } +pub(super) unsafe fn two_pass_stream_key(stream: &[u8], ps_samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> Option<(u64, usize)> { + stream_key(stream, ps_samplers, TWO_PASS_CACHE_SCHEMA, 1, driver_id, mem_windows) +} + +/// Canonical identity for a translated native graphics stream. The distinct schema/kind prevents +/// its driver blobs from aliasing either legacy graphics descriptors or two-pass mesh streams. +pub(super) unsafe fn graphics_stream_key(stream: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], mem_windows: u32) -> Option<(u64, usize)> { + stream_key(stream, samplers, GRAPHICS_STREAM_CACHE_SCHEMA, 3, 0, mem_windows) +} + pub(super) fn two_pass_cs_key(cs: &[u8], samplers: &[crate::gpu::recomp::pso::StaticSampler], driver_id: u64, mem_windows: u32) -> u64 { let mut h = Fnv64::new(); h.u32(TWO_PASS_CACHE_SCHEMA); @@ -333,6 +348,29 @@ mod tests { } } + #[test] + fn graphics_stream_key_is_canonical_distinct_and_pointer_free() { + let vs = [1u8, 2, 3, 4]; + let mut a = StreamOut::default(); + a.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + a.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &7u32); + let mut b = StreamOut::default(); + b.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_MASK, &7u32); + b.shader(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VS, &vs); + unsafe { + let ga = graphics_stream_key(&a.0, &[], 1).unwrap(); + assert_eq!(ga, graphics_stream_key(&b.0, &[], 1).unwrap()); + assert_ne!(ga, two_pass_stream_key(&a.0, &[], 0, 1).unwrap()); + assert_ne!(ga, graphics_stream_key(&a.0, &[([1, 2, 3, 4], false)], 1).unwrap()); + + let mut pointer = StreamOut(a.0.clone(), a.1); + pointer.put(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT, &D3D12_INPUT_LAYOUT_DESC { + pInputElementDescs: 0x1234 as *const _, NumElements: 1, + }); + assert_eq!(graphics_stream_key(&pointer.0, &[], 1), None); + } + } + #[test] fn two_pass_keys_cover_mem_windows_invalid_counts_and_duplicates() { let mut s = StreamOut::default(); diff --git a/crates/xcl/src/hle/d3d12x/sparse.rs b/crates/xcl/src/hle/d3d12x/sparse.rs index b7560f861e..1772d490ed 100644 --- a/crates/xcl/src/hle/d3d12x/sparse.rs +++ b/crates/xcl/src/hle/d3d12x/sparse.rs @@ -20,7 +20,7 @@ use std::collections::{BTreeMap, HashMap, VecDeque}; use std::ffi::c_void; use std::hash::{BuildHasherDefault, Hasher}; use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use windows::core::Interface; use windows::Win32::Foundation::{CloseHandle, HANDLE}; @@ -32,8 +32,11 @@ use windows_sys::Win32::System::Memory::{ }; const TILE: usize = 0x1_0000; -/// tiles of a video-memory pool heap (64 MiB) -const POOL_TILES: u32 = 1024; +/// tiles of a video-memory pool heap (4 MiB). A heap goes back only when every tile of it is +/// free (`State::retire_free_pools`), and a title frees its tiles in runs spread over all its +/// heaps: with heaps of 64 MiB a retail title's world load unmapped 1.5 GB of its 4.6 GB of +/// tiles and 3 of 78 heaps went back (0.2 GB); with heaps of 4 MiB 1.25 GB went back. +const POOL_TILES: u32 = 64; /// tiles decommitted while no title work was submitted that stay mapped (`State::parked`) before /// they are unmapped together: 256 MB of video memory const PARKED_MAX: usize = 4096; @@ -89,13 +92,15 @@ struct TileEntry { pool: (u32, u32), /// bit `i` set => 4 KiB page `i` of this 64 KiB tile is uncommitted (a hole) holes: u16, + /// bit `i` set => the title gave page `i` a protection other than writable + not_rw: u16, /// per-4 KiB-page hashes of the 64-byte chunks last sent to the GPU (`None` = all zero) sent: [Option<Box<[u64; CHUNKS]>>; PAGES_PER_TILE], } impl TileEntry { fn with_holes(pool: (u32, u32), holes: u16) -> Self { - Self { pool, holes, sent: std::array::from_fn(|_| None) } + Self { pool, holes, not_rw: 0, sent: std::array::from_fn(|_| None) } } } @@ -197,1557 +202,5096 @@ struct UploadSlot { fence_val: u64, } -struct RetiredTiles { - tiles: Vec<(u32, u32)>, - /// Fence marks on `self.queue` and every known title queue (`None` = signal failed, keep held). - marks: Option<Vec<(ID3D12Fence, u64)>>, +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum SubmitResult { + Submitted, + NotSubmitted, + Unordered, } -struct State { +enum UploadStep { + Done(PreparationOutcome), + Wait(WaitTicket), +} + +enum BeginSlot { + Ready(usize), + Wait(WaitTicket), + RetryRequired, +} + +#[derive(Clone, Copy)] +enum WaitKind { + Slot { index: usize, next_slot: usize, fence: u64 }, + Ring { front: (u64, u64), write: u64, submitted: u64, free: u64 }, +} + +struct WaitTicket { + state_generation: u64, + mapping_epoch: u64, dev: ID3D12Device, - queue: ID3D12CommandQueue, fence: ID3D12Fence, - value: u64, - /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) - event: HANDLE, - /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU - rb_fence: ID3D12Fence, - rb_value: u64, - /// (window start, reserved buffer) of each sparse window - windows: Vec<(usize, ID3D12Resource)>, - /// video-memory pool heaps (None: given back, its index free for the next one) - pools: Vec<Option<ID3D12Heap>>, - free: Vec<(u32, u32)>, - /// pools all of whose tiles came free: released once the GPU is past `value` and a moment - /// went by (titles' queues may still read what was mapped there) - retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, - /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes - mapped: FxHashMap<usize, TileEntry>, - /// pool tiles also used by placed buffers (not freed while they are) - pinned: FxHashMap<(u32, u32), u32>, - /// tile address → pool tile of tiles decommitted since the last title submit, still mapped - /// in their window: unmapped together (`flush_parked`) before the next submit, when the free - /// list runs out, or past `PARKED_MAX`; a commit there before that takes its tile back with - /// no new mapping. (A retail title moving physical pages one at a time while it loads - /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` - /// took ~0.15 ms.) - parked: FxHashMap<usize, (u32, u32)>, - /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` - quarantined: VecDeque<RetiredTiles>, - /// per-title-queue fences used to mark in-flight GPU work (`note_queue`) - queue_fences: FxHashMap<usize, (ID3D12CommandQueue, ID3D12Fence, u64)>, - /// placed buffers → the pool tiles they use - buffers: FxHashMap<usize, Vec<(u32, u32)>>, - /// reused tiles / decommitted partial pages to clear: (address, bytes) - to_zero: Vec<(usize, usize)>, - /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) - staging: Option<(ID3D12Resource, *mut u8)>, - /// monotonic ring-buffer write/submitted/retired byte cursors - ring_write: u64, - ring_submitted: u64, - ring_free: u64, - /// submitted ring chunks awaiting GPU completion: `(fence_val, ring_end_pos)` - inflight: VecDeque<(u64, u64)>, - /// dedicated 1 MiB pre-zeroed buffer for tile/hole clears (zero staging bandwidth) - zero_buf: Option<ID3D12Resource>, - /// ring of async upload command allocators + lists - slots: Vec<UploadSlot>, - next_slot: usize, - /// dedicated readback staging buffer + command allocator / list - readback: Option<(ID3D12Resource, *mut u8)>, - rb_alloc: ID3D12CommandAllocator, - rb_list: ID3D12GraphicsCommandList, - rb_last_fence: u64, - /// the fence value each title queue last waited for - waited: FxHashMap<usize, u64>, - /// `mapped` as sorted (start, end) runs (None: to be made again) - runs: Option<Vec<(usize, usize)>>, - /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) - scratch_runs: Vec<(usize, usize)>, + target: u64, + kind: WaitKind, } -impl Drop for State { - fn drop(&mut self) { - if !self.event.is_invalid() { - unsafe { - let _ = CloseHandle(self.event); - } - } - } -} +/// Sources which can require one CPU page to be considered by a future immutable upload plan. +/// Multiple sources collapse into one page owner without losing why the page must be revisited. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +struct WorkReasons(u8); -const K0: u64 = 0x9E37_79B9_7F4A_7C15; -const K1: u64 = 0xBF58_476D_1CE4_E5B9; -const K2: u64 = 0x94D0_49BB_1331_11EB; -const K3: u64 = 0x243F_6A88_85A3_08D3; +impl WorkReasons { + const ZERO: Self = Self(1); + const RETRY: Self = Self(2); + const DIRTY: Self = Self(4); -/// 4-way parallel hash over 8 `u64` words (64 bytes): breaks serial multiply latency chain. -#[inline(always)] -const fn hash_words(w: [u64; 8]) -> u64 { - let a = (w[0] ^ K3).wrapping_mul(K0) ^ w[4].wrapping_mul(K1); - let b = (w[1] ^ K0).wrapping_mul(K1) ^ w[5].wrapping_mul(K2); - let c = (w[2] ^ K1).wrapping_mul(K2) ^ w[6].wrapping_mul(K3); - let d = (w[3] ^ K2).wrapping_mul(K3) ^ w[7].wrapping_mul(K0); - let h = a.rotate_left(27).wrapping_add(b.rotate_left(13)) ^ c.rotate_left(41).wrapping_add(d.rotate_left(53)); - h.wrapping_mul(K0) ^ (h >> 32) + fn insert(&mut self, other: Self) { self.0 |= other.0; } } -const ZERO_HASH: u64 = hash_words([0; 8]); -const ZERO_HASHES: [u64; CHUNKS] = [ZERO_HASH; CHUNKS]; +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +struct WorkClaimToken { + state_generation: u64, + serial: u64, +} -#[inline(always)] -fn read_chunk_words(c: &[u8]) -> [u64; 8] { - debug_assert_eq!(c.len(), CHUNK); - let p = c.as_ptr() as *const [u8; 8]; - unsafe { - [ - u64::from_le_bytes(p.add(0).read_unaligned()), - u64::from_le_bytes(p.add(1).read_unaligned()), - u64::from_le_bytes(p.add(2).read_unaligned()), - u64::from_le_bytes(p.add(3).read_unaligned()), - u64::from_le_bytes(p.add(4).read_unaligned()), - u64::from_le_bytes(p.add(5).read_unaligned()), - u64::from_le_bytes(p.add(6).read_unaligned()), - u64::from_le_bytes(p.add(7).read_unaligned()), - ] - } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum WorkClaimResolution { + Committed, + Restored, + AlreadyFinished, + StaleGeneration, } -/// hash of 64 bytes -#[inline(always)] -fn chunk_hash(c: &[u8]) -> u64 { - hash_words(read_chunk_words(c)) +struct ClaimedWork { + token: WorkClaimToken, + pages: Vec<(usize, WorkReasons)>, } -#[inline(always)] -fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { - match out.last_mut() { - Some(last) if last.0 + last.1 == addr => last.1 += len, - _ => out.push((addr, len)), - } +/// Inert foundation for splitting sparse planning from its serialized commit phase. Work added +/// while a page is owned stays journalled for a later claim; cancelling an older claim merges its +/// exact reasons back without rewinding or duplicating a newer claim. Tokens include the sparse +/// state generation, so a late completion from replaced state cannot modify the replacement. +#[allow(dead_code)] +struct WorkClaimLedger { + state_generation: u64, + next_serial: u64, + available: BTreeMap<usize, WorkReasons>, + owners: BTreeMap<usize, u64>, + claims: BTreeMap<u64, Vec<(usize, WorkReasons)>>, } -/// Scan a 4 KiB page at `pg`, appending any changed 64-byte chunk runs directly to `out` -/// (zero per-page heap allocation; skips allocating `slot` completely when a fresh zero page -/// is still all zeros). -#[inline] -fn scan_page(page: &[u8], pg: usize, slot: &mut Option<Box<[u64; CHUNKS]>>, out: &mut Vec<(usize, usize)>) { - if let Some(sent) = slot.as_deref_mut() { - for (k, c) in page.chunks_exact(CHUNK).enumerate() { - let h = chunk_hash(c); - if h == sent[k] { +#[allow(dead_code)] +impl WorkClaimLedger { + fn new(state_generation: u64) -> Self { + Self { + state_generation, + next_serial: 0, + available: BTreeMap::new(), + owners: BTreeMap::new(), + claims: BTreeMap::new(), + } + } + + fn add_pages(&mut self, pages: impl IntoIterator<Item = usize>, reason: WorkReasons) { + for page in pages { + self.available.entry(page & !(PAGE - 1)).or_default().insert(reason); + } + } + + fn add_zero_ranges(&mut self, ranges: &[(usize, usize)]) { + for &(start, bytes) in ranges { + if bytes == 0 { continue; } - sent[k] = h; - push_run(out, pg + k * CHUNK, CHUNK); + let end = start.saturating_add(bytes); + let mut page = start & !(PAGE - 1); + while page < end { + self.available.entry(page).or_default().insert(WorkReasons::ZERO); + let Some(next) = page.checked_add(PAGE) else { break }; + page = next; + } } - return; } - // Page has never had non-zero data sent: skip zero chunks with a cheap OR-reduction and - // allocate the hash array only if at least one chunk is non-zero. - let mut chunks = page.chunks_exact(CHUNK).enumerate(); - while let Some((k, c)) = chunks.next() { - let w = read_chunk_words(c); - if (w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) == 0 { - continue; + + fn add_retry_pages(&mut self, pages: impl IntoIterator<Item = usize>) { + self.add_pages(pages, WorkReasons::RETRY); + } + + fn add_dirty_pages(&mut self, pages: impl IntoIterator<Item = usize>) { + self.add_pages(pages, WorkReasons::DIRTY); + } + + /// Claim at most `limit` pages in address order. A page has one owner even when zero, retry, + /// and fresh dirty work overlap; reasons added after this snapshot remain for the next claim. + fn claim(&mut self, limit: usize) -> Option<ClaimedWork> { + if limit == 0 { + return None; } - let h = hash_words(w); - if h == ZERO_HASH { - continue; + let pages: Vec<_> = self.available + .iter() + .filter(|(page, _)| !self.owners.contains_key(page)) + .take(limit) + .map(|(&page, &reasons)| (page, reasons)) + .collect(); + if pages.is_empty() { + return None; } - let sent = slot.insert(Box::new(ZERO_HASHES)); - sent[k] = h; - push_run(out, pg + k * CHUNK, CHUNK); - for (k2, c2) in chunks { - let h2 = chunk_hash(c2); - if h2 == ZERO_HASH { + self.next_serial = self.next_serial.checked_add(1).expect("sparse work claim serial exhausted"); + let serial = self.next_serial; + for &(page, _) in &pages { + self.available.remove(&page); + self.owners.insert(page, serial); + } + self.claims.insert(serial, pages.clone()); + Some(ClaimedWork { + token: WorkClaimToken { state_generation: self.state_generation, serial }, + pages, + }) + } + + fn commit(&mut self, token: WorkClaimToken) -> WorkClaimResolution { + self.finish(token, false) + } + + fn restore(&mut self, token: WorkClaimToken) -> WorkClaimResolution { + self.finish(token, true) + } + + fn cancel(&mut self, token: WorkClaimToken) -> WorkClaimResolution { + self.restore(token) + } + + fn finish(&mut self, token: WorkClaimToken, restore: bool) -> WorkClaimResolution { + if token.state_generation != self.state_generation { + return WorkClaimResolution::StaleGeneration; + } + let Some(pages) = self.claims.remove(&token.serial) else { + return WorkClaimResolution::AlreadyFinished; + }; + for (page, reasons) in pages { + if self.owners.get(&page) != Some(&token.serial) { continue; } - sent[k2] = h2; - push_run(out, pg + k2 * CHUNK, CHUNK); + self.owners.remove(&page); + if restore { + self.available.entry(page).or_default().insert(reasons); + } } - break; + if restore { WorkClaimResolution::Restored } else { WorkClaimResolution::Committed } } -} -/// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent` -/// (updated to the page's chunks). -pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usize)> { - let mut out: Vec<(usize, usize)> = Vec::new(); - for (k, c) in page.chunks_exact(CHUNK).enumerate() { - let h = chunk_hash(c); - if h == sent[k] { - continue; - } - sent[k] = h; - push_run(&mut out, k * CHUNK, CHUNK); + fn replace_generation(&mut self, state_generation: u64) { + self.state_generation = state_generation; + self.available.clear(); + self.owners.clear(); + self.claims.clear(); } - out } -/// Plan a contiguous sub-allocation `(aligned_pos, chunk_len)` inside a ring buffer of `cap` -/// bytes starting at monotonic cursor `ring_write`, keeping each chunk `<= cap / 2` and -/// avoiding mid-copy wrap-around without wasting large tail gaps. -#[inline] -fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { - let mut chunk = want.min(cap / 2); - let mut aligned = (ring_write + (RING_ALIGN as u64 - 1)) & !(RING_ALIGN as u64 - 1); - let off = (aligned as usize) % cap; - if off + chunk > cap { - let tail = cap - off; - if tail >= PAGE { - chunk = tail; - } else { - aligned += tail as u64; - } - } - (aligned, chunk) +/// Identity of one future sparse batch while it crosses planning and queue acceptance. `lease` +/// changes on takeover, so an old owner cannot publish or discard the new owner's batch. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct ClaimFrontierToken { + state_generation: u64, + epoch: u64, + lease: u64, + owner: u64, } -// D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock -unsafe impl Send for State {} +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ClaimFrontierState { + Pending, + Accepted, + Receipted(u64), + Obsolete, +} -static STATE: Mutex<Option<State>> = Mutex::new(None); +#[allow(dead_code)] +struct ClaimFrontierRecord { + lease: u64, + owner: u64, + state: ClaimFrontierState, + prefix_fence: Option<u64>, +} -/// The state's queue again, outside `STATE` (`queue`). `STATE` is held around D3D12 calls (an -/// upload's allocator `Reset` in `begin_slot`), and `late_release` asks for the queue from a -/// resource's last `Release`, which D3D12 can make inside a call of its own on another thread -/// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. -static QUEUE: Mutex<Option<ID3D12CommandQueue>> = Mutex::new(None); +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum ClaimFrontierAction { + Ready { through: u64, required_fence: Option<u64> }, + Progress(ClaimFrontierToken), + TakeOver(ClaimFrontierToken), + WaitForReceipt(ClaimFrontierToken), +} -/// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` -pub fn pool_bytes() -> (usize, usize) { - let g = lock_state(); - let Some(s) = g.as_ref() else { return (0, 0) }; - let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE; - (pools, pools.saturating_sub(s.free.len() * TILE)) +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum ClaimFrontierError { + StaleGeneration, + UnknownEpoch, + StaleToken, + WrongState, + Fence, + Exhausted, } -/// commits before the device existed: the pages committed, as disjoint page ranges (start → -/// end) merged with their neighbours, so a commit or decommit costs O(log n) and not a scan of -/// every page committed so far. Like `committed` / `decommitted` with a state, a range counts -/// every page it touches; `init` commits them once the windows exist. -static EARLY: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); -/// The pages `[a, a + n)` touches, as `[start, end)`. -fn page_span(a: usize, n: usize) -> (usize, usize) { - (a & !(PAGE - 1), a.saturating_add(n).saturating_add(PAGE - 1) & !(PAGE - 1)) +/// Inert coordination model for future asynchronous sparse planning. Every observed epoch remains +/// visible until it is receipted or explicitly consumed as obsolete; a foreground queue therefore +/// cannot mistake work owned by another planner for an empty journal. There are no callers yet. +#[allow(dead_code)] +struct ClaimFrontier { + state_generation: u64, + next_epoch: u64, + next_lease: u64, + retired_through: u64, + records: BTreeMap<u64, ClaimFrontierRecord>, } -/// Add the pages `[a, b)` to `early`, merged with the ranges they overlap or touch. -fn early_add(early: &mut BTreeMap<usize, usize>, mut a: usize, mut b: usize) { - if a >= b { - return; +#[allow(dead_code)] +impl ClaimFrontier { + fn new(state_generation: u64) -> Self { + Self { + state_generation, + next_epoch: 0, + next_lease: 0, + retired_through: 0, + records: BTreeMap::new(), + } } - if let Some((&s, &e)) = early.range(..=a).next_back() { - if e >= a { - a = s; - b = b.max(e); - early.remove(&s); + + fn claim(&mut self, owner: u64) -> Result<ClaimFrontierToken, ClaimFrontierError> { + let epoch = self.next_epoch.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let lease = self.next_lease.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let token = ClaimFrontierToken { state_generation: self.state_generation, epoch, lease, owner }; + self.records.insert(epoch, ClaimFrontierRecord { + lease, + owner, + state: ClaimFrontierState::Pending, + prefix_fence: None, + }); + self.next_epoch = epoch; + self.next_lease = lease; + Ok(token) + } + + fn observe( + &self, state_generation: u64, through: u64, requester: u64, + ) -> Result<ClaimFrontierAction, ClaimFrontierError> { + if state_generation != self.state_generation { + return Err(ClaimFrontierError::StaleGeneration); + } + if through > self.next_epoch { + return Err(ClaimFrontierError::UnknownEpoch); + } + if through <= self.retired_through { + let required_fence = (through != 0) + .then(|| self.records.get(&through).and_then(|record| record.prefix_fence)) + .flatten(); + return Ok(ClaimFrontierAction::Ready { through, required_fence }); } + let epoch = self.retired_through.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let record = self.records.get(&epoch).ok_or(ClaimFrontierError::UnknownEpoch)?; + let token = ClaimFrontierToken { + state_generation: self.state_generation, + epoch, + lease: record.lease, + owner: record.owner, + }; + Ok(match record.state { + ClaimFrontierState::Pending if record.owner == requester => ClaimFrontierAction::Progress(token), + ClaimFrontierState::Pending => ClaimFrontierAction::TakeOver(token), + ClaimFrontierState::Accepted => ClaimFrontierAction::WaitForReceipt(token), + ClaimFrontierState::Receipted(_) | ClaimFrontierState::Obsolete => unreachable!("terminal frontier did not advance"), + }) } - loop { - let Some((s, e)) = early.range(a..=b).next().map(|(&s, &e)| (s, e)) else { break }; - b = b.max(e); - early.remove(&s); + + fn take_over( + &mut self, token: ClaimFrontierToken, owner: u64, + ) -> Result<ClaimFrontierToken, ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Pending)?; + let lease = self.next_lease.checked_add(1).ok_or(ClaimFrontierError::Exhausted)?; + let record = self.records.get_mut(&token.epoch).unwrap(); + record.lease = lease; + record.owner = owner; + self.next_lease = lease; + Ok(ClaimFrontierToken { state_generation: self.state_generation, epoch: token.epoch, lease, owner }) } - early.insert(a, b); -} -/// Take the pages `[a, b)` out of `early`; a range that overlaps it keeps the rest. -fn early_remove(early: &mut BTreeMap<usize, usize>, a: usize, b: usize) { - if a >= b { - return; + fn accept(&mut self, token: ClaimFrontierToken) -> Result<(), ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Pending)?; + self.records.get_mut(&token.epoch).unwrap().state = ClaimFrontierState::Accepted; + Ok(()) } - if let Some((&s, &e)) = early.range(..a).next_back() { - if e > a { - early.insert(s, a); - if e > b { - early.insert(b, e); - return; - } + + fn receipt(&mut self, token: ClaimFrontierToken, fence: u64) -> Result<(), ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Accepted)?; + if fence == 0 { + return Err(ClaimFrontierError::Fence); } + self.records.get_mut(&token.epoch).unwrap().state = ClaimFrontierState::Receipted(fence); + self.advance(); + Ok(()) } - loop { - let Some((s, e)) = early.range(a..b).next().map(|(&s, &e)| (s, e)) else { break }; - early.remove(&s); - if e > b { - early.insert(b, e); - break; + + fn consume_obsolete(&mut self, token: ClaimFrontierToken) -> Result<(), ClaimFrontierError> { + self.validate(token, ClaimFrontierState::Pending)?; + self.records.get_mut(&token.epoch).unwrap().state = ClaimFrontierState::Obsolete; + self.advance(); + Ok(()) + } + + fn validate( + &self, token: ClaimFrontierToken, expected: ClaimFrontierState, + ) -> Result<(), ClaimFrontierError> { + if token.state_generation != self.state_generation { + return Err(ClaimFrontierError::StaleGeneration); + } + let record = self.records.get(&token.epoch).ok_or(ClaimFrontierError::StaleToken)?; + if record.lease != token.lease || record.owner != token.owner { + return Err(ClaimFrontierError::StaleToken); + } + if record.state != expected { + return Err(ClaimFrontierError::WrongState); + } + Ok(()) + } + + fn advance(&mut self) { + let mut prefix_fence = if self.retired_through == 0 { + 0 + } else { + self.records[&self.retired_through].prefix_fence.unwrap_or(0) + }; + loop { + let Some(next) = self.retired_through.checked_add(1) else { return }; + let Some(record) = self.records.get_mut(&next) else { return }; + match record.state { + ClaimFrontierState::Receipted(fence) => prefix_fence = prefix_fence.max(fence), + ClaimFrontierState::Obsolete => {} + ClaimFrontierState::Pending | ClaimFrontierState::Accepted => return, + } + record.prefix_fence = (prefix_fence != 0).then_some(prefix_fence); + self.retired_through = next; } } } -/// generation counter incremented whenever the set of mapped tiles changes (for watch_ranges cache) -static MAPPED_GEN: AtomicU64 = AtomicU64::new(0); -/// Generation counter of `mapped_ranges()` (changes only when tiles are mapped or unmapped). -pub fn mapped_gen() -> u64 { - MAPPED_GEN.load(Ordering::Acquire) +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum SparseBatchError { + StaleGeneration, + Fence, + Poisoned, + Unsealed, + Exhausted, + Corrupt, + Frontier(ClaimFrontierError), } -fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_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, - Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, - ..Default::default() - } +/// One atomic owner for work claims and their visibility frontier. This remains inert: no live +/// sparse state, command list, queue or fence uses it yet. Keeping both ledgers under one mutex is +/// what makes a lease rotation revoke the old planner without restoring or duplicating its work. +#[allow(dead_code)] +struct SparseBatchLedger { + work: WorkClaimLedger, + frontier: ClaimFrontier, + fence: Option<SparseFenceIdentity>, + bindings: BTreeMap<u64, WorkClaimToken>, + poisoned: bool, } -/// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each -/// sparse window in `gpu::uma` (empty: no sparse windows). -pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { - let Some(u) = crate::gpu::uma::get() else { return Vec::new() }; - let mut out = Vec::new(); - let mut windows = Vec::new(); - for k in 0..u.shader_windows() { - if !u.is_sparse_window(k) { - continue; +#[allow(dead_code)] +impl SparseBatchLedger { + fn new(state_generation: u64) -> Self { + Self { + work: WorkClaimLedger::new(state_generation), + frontier: ClaimFrontier::new(state_generation), + fence: None, + bindings: BTreeMap::new(), + poisoned: false, } - let (base, size) = u.window(k); - let mut r: Option<ID3D12Resource> = None; - if let Err(e) = dev.CreateReservedResource(&buffer_desc(size as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut r) { - crate::xlog_warn!("sparse window {k}: CreateReservedResource: {e}"); - return Vec::new(); - } - let Some(r) = r else { return Vec::new() }; - out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); - windows.push((base, r)); } - if out.is_empty() { - return out; + + fn check(&self, state_generation: u64) -> Result<(), SparseBatchError> { + if state_generation != self.work.state_generation { + return Err(SparseBatchError::StaleGeneration); + } + if self.poisoned { + return Err(SparseBatchError::Poisoned); + } + Ok(()) } - let made = (|| -> windows::core::Result<State> { - let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; - let mut slots = Vec::with_capacity(UPLOAD_SLOTS); - for _ in 0..UPLOAD_SLOTS { - let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; - list.Close()?; - let _ = list.SetName(windows::core::w!("xcl sparse upload list")); - let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); - slots.push(UploadSlot { alloc, list, fence_val: 0 }); + + fn seal( + &mut self, state_generation: u64, owner: u64, limit: usize, + ) -> Result<Option<(ClaimFrontierToken, Vec<(usize, WorkReasons)>)>, SparseBatchError> { + self.check(state_generation)?; + if self.work.next_serial == u64::MAX { + return Err(SparseBatchError::Exhausted); } - let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; - rb_list.Close()?; - let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); - let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); - let _ = queue.SetName(windows::core::w!("xcl sparse queue")); - Ok(State { - dev: dev.clone(), - queue, - fence, - value: 0, - event, - rb_fence, - rb_value: 0, - windows, - pools: Vec::new(), - free: Vec::new(), - retired: Vec::new(), - mapped: FxHashMap::default(), - pinned: FxHashMap::default(), - parked: FxHashMap::default(), - quarantined: VecDeque::new(), - queue_fences: FxHashMap::default(), - buffers: FxHashMap::default(), - to_zero: Vec::new(), - staging: None, - ring_write: 0, - ring_submitted: 0, - ring_free: 0, - inflight: VecDeque::new(), - zero_buf: None, - slots, - next_slot: 0, - readback: None, - rb_alloc, - rb_list, - rb_last_fence: 0, - waited: FxHashMap::default(), - runs: None, - scratch_runs: Vec::new(), - }) - })(); - match made { - Ok(s) => { - crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); - // a state this replaces (the windows set up again) goes after the lock: the release of - // its last buffers reaches `forget_buffer`, which takes the lock (#344) - // (the queue first: `queue()` never answers with one older than the state's) - let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); - let old = STATE.lock().unwrap().replace(s); - drop(old); - drop(old_queue); - for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { - committed(a, b - a); + let Some(claimed) = self.work.claim(limit) else { return Ok(None) }; + let token = match self.frontier.claim(owner) { + Ok(token) => token, + Err(error) => { + let _ = self.work.restore(claimed.token); + return Err(SparseBatchError::Frontier(error)); } - out + }; + self.bindings.insert(token.epoch, claimed.token); + Ok(Some((token, claimed.pages))) + } + + fn pages(&self, token: ClaimFrontierToken) -> Result<Vec<(usize, WorkReasons)>, SparseBatchError> { + self.check(token.state_generation)?; + self.frontier.validate(token, ClaimFrontierState::Pending).map_err(SparseBatchError::Frontier)?; + let work = self.bindings.get(&token.epoch).ok_or(SparseBatchError::Corrupt)?; + self.work.claims.get(&work.serial).cloned().ok_or(SparseBatchError::Corrupt) + } + + fn take_over( + &mut self, token: ClaimFrontierToken, owner: u64, + ) -> Result<(ClaimFrontierToken, Vec<(usize, WorkReasons)>), SparseBatchError> { + let pages = self.pages(token)?; + let token = self.frontier.take_over(token, owner).map_err(SparseBatchError::Frontier)?; + Ok((token, pages)) + } + + fn observe( + &self, state_generation: u64, through: u64, requester: u64, + ) -> Result<ClaimFrontierAction, SparseBatchError> { + self.check(state_generation)?; + if !self.work.available.is_empty() { + return Err(SparseBatchError::Unsealed); } - Err(e) => { - crate::xlog_warn!("sparse windows: {e}"); - Vec::new() + self.frontier.observe(state_generation, through, requester).map_err(SparseBatchError::Frontier) + } + + fn through(&self, state_generation: u64) -> Result<u64, SparseBatchError> { + self.check(state_generation)?; + if !self.work.available.is_empty() { + return Err(SparseBatchError::Unsealed); } + Ok(self.frontier.next_epoch) } -} -impl State { - #[inline] - fn window_index(&self, a: usize) -> Option<usize> { - self.windows.iter().position(|(b, _)| a >= *b && a < *b + crate::gpu::uma::WINDOW) + fn accept(&mut self, token: ClaimFrontierToken) -> Result<WorkClaimToken, SparseBatchError> { + self.check(token.state_generation)?; + let work = self.binding(token, ClaimFrontierState::Pending)?; + self.frontier.accept(token).map_err(SparseBatchError::Frontier)?; + Ok(work) } - unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { - self.drain_quarantined(); - if self.free.is_empty() && self.flush_parked() { - self.drain_quarantined(); - } - if let Some(t) = self.free.pop() { - return Some((t, true)); + fn receipt(&mut self, token: ClaimFrontierToken, fence: u64) -> Result<(), SparseBatchError> { + self.check(token.state_generation)?; + if fence == 0 { + return Err(SparseBatchError::Frontier(ClaimFrontierError::Fence)); } - // a pool retired a moment ago (its last tile came free) is taken back before a new - // 64 MB heap is made: freeing and allocating a tile in turn made a new pool each time, - // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are - // (zeroed), so this is no less safe than reusing a tile of a pool in use. - if let Some((heap, _, _)) = self.retired.pop() { - let h = self.add_pool(heap); - return Some(((h, 0), true)); + let work = self.binding(token, ClaimFrontierState::Accepted)?; + if self.work.commit(work) != WorkClaimResolution::Committed { + self.poisoned = true; + return Err(SparseBatchError::Corrupt); } - let desc = D3D12_HEAP_DESC { - SizeInBytes: POOL_TILES as u64 * TILE as u64, - Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, - Alignment: 0, - Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, - }; - let mut heap: Option<ID3D12Heap> = None; - if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { - crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); - return None; + if let Err(error) = self.frontier.receipt(token, fence) { + self.poisoned = true; + return Err(SparseBatchError::Frontier(error)); } - let heap = heap?; - let h = self.add_pool(heap); - Some(((h, 0), false)) - } - - /// `heap` becomes a pool (in a given-back pool's index if there is one); its tiles but the - /// first, which the caller takes, go to the free list. - fn add_pool(&mut self, heap: ID3D12Heap) -> u32 { - let h = match self.pools.iter().position(|p| p.is_none()) { - Some(i) => { - self.pools[i] = Some(heap); - i as u32 - } - None => { - self.pools.push(Some(heap)); - self.pools.len() as u32 - 1 - } - }; - self.free.extend((1..POOL_TILES).rev().map(|t| (h, t))); - h + self.bindings.remove(&token.epoch); + Ok(()) } - /// Pools whose every tile is free again go (64 MB of video memory each – and as much of the - /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for - /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. - fn retire_free_pools(&mut self) { - let now = std::time::Instant::now(); - let done = unsafe { self.fence.GetCompletedValue() }; - self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); - if self.free.len() < POOL_TILES as usize { - return; + fn obsolete(&mut self, token: ClaimFrontierToken) -> Result<(), SparseBatchError> { + self.check(token.state_generation)?; + let work = self.binding(token, ClaimFrontierState::Pending)?; + if self.work.commit(work) != WorkClaimResolution::Committed { + self.poisoned = true; + return Err(SparseBatchError::Corrupt); } - let mut count = vec![0u32; self.pools.len()]; - for &(h, _) in &self.free { - count[h as usize] += 1; + if let Err(error) = self.frontier.consume_obsolete(token) { + self.poisoned = true; + return Err(SparseBatchError::Frontier(error)); } - let gone: Vec<usize> = (0..count.len()).filter(|&h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); - if gone.is_empty() { - return; + self.bindings.remove(&token.epoch); + Ok(()) + } + + fn poison_exact( + &mut self, token: ClaimFrontierToken, work: WorkClaimToken, + ) -> Result<(), SparseBatchError> { + if token.state_generation != self.work.state_generation || work.state_generation != token.state_generation { + return Err(SparseBatchError::StaleGeneration); } - self.free.retain(|&(h, _)| !gone.contains(&(h as usize))); - for h in gone { - if let Some(heap) = self.pools[h].take() { - self.retired.push((heap, self.value, now)); - } + let resolution = self.work.commit(work); + if !matches!(resolution, WorkClaimResolution::Committed | WorkClaimResolution::AlreadyFinished) { + return Err(SparseBatchError::Corrupt); } + if self.bindings.get(&token.epoch) == Some(&work) { self.bindings.remove(&token.epoch); } + self.poisoned = true; + Ok(()) } - /// Map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles, - /// batched per pool heap with contiguous runs merged into single regions. - unsafe fn map_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) { - if tiles.is_empty() { - return; + fn binding( + &self, token: ClaimFrontierToken, state: ClaimFrontierState, + ) -> Result<WorkClaimToken, SparseBatchError> { + self.frontier.validate(token, state).map_err(SparseBatchError::Frontier)?; + let work = *self.bindings.get(&token.epoch).ok_or(SparseBatchError::Corrupt)?; + self.work.claims.contains_key(&work.serial).then_some(work).ok_or(SparseBatchError::Corrupt) + } + + fn replace_generation( + &mut self, current: u64, replacement: u64, fence_allocation: Option<u64>, + ) -> Result<(), SparseBatchError> { + if current != self.work.state_generation { + return Err(SparseBatchError::StaleGeneration); } - let mut by_heap: FxHashMap<u32, Vec<(u32, u32)>> = FxHashMap::default(); - for &(a, (h, t)) in tiles { - by_heap.entry(h).or_default().push((((a - res_base) / TILE) as u32, t)); + // Generations are identities, not labels: reuse could resurrect an old epoch/lease tuple. + if replacement <= current { + return Err(SparseBatchError::StaleGeneration); } - for (h, mut pairs) in by_heap { - pairs.sort_unstable_by_key(|&(x, _)| x); - let mut coords: Vec<D3D12_TILED_RESOURCE_COORDINATE> = Vec::with_capacity(pairs.len()); - let mut regions: Vec<D3D12_TILE_REGION_SIZE> = Vec::with_capacity(pairs.len()); - let mut flags: Vec<D3D12_TILE_RANGE_FLAGS> = Vec::with_capacity(pairs.len()); - let mut offsets: Vec<u32> = Vec::with_capacity(pairs.len()); - let mut counts: Vec<u32> = Vec::with_capacity(pairs.len()); - let mut i = 0; - while i < pairs.len() { - let (x0, t0) = pairs[i]; - let mut run = 1u32; - while i + (run as usize) < pairs.len() { - let (nx, nt) = pairs[i + run as usize]; - if nx == x0 + run && nt == t0 + run { - run += 1; - } else { - break; - } - } - coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); - regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); - flags.push(D3D12_TILE_RANGE_FLAG_NONE); - offsets.push(t0); - counts.push(run); - i += run as usize; + self.fence = match (self.fence, fence_allocation) { + (None, None) => None, + (Some(fence), Some(allocation)) if allocation > fence.allocation => { + Some(SparseFenceIdentity { state_generation: replacement, allocation }) } - self.queue.UpdateTileMappings( - res, - coords.len() as u32, - Some(coords.as_ptr()), - Some(regions.as_ptr()), - self.pools[h as usize].as_ref().expect("a pool tile of a live pool"), - flags.len() as u32, - Some(flags.as_ptr()), - Some(offsets.as_ptr()), - Some(counts.as_ptr()), - D3D12_TILE_MAPPING_FLAG_NONE, - ); - } + _ => return Err(SparseBatchError::Fence), + }; + self.work.replace_generation(replacement); + self.frontier = ClaimFrontier::new(replacement); + self.bindings.clear(); + self.poisoned = false; + Ok(()) } +} - unsafe fn unmap_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) { - if tiles.is_empty() { +#[derive(Clone)] +#[allow(dead_code)] +struct SparseBatches { + ledger: Arc<Mutex<SparseBatchLedger>>, + state_generation: u64, +} + +#[allow(dead_code)] +impl SparseBatches { + fn new(state_generation: u64) -> Self { + Self { ledger: Arc::new(Mutex::new(SparseBatchLedger::new(state_generation))), state_generation } + } + + fn with_fence(state_generation: u64, fence_allocation: u64) -> Option<Self> { + if state_generation == 0 || fence_allocation == 0 { return None } + let batches = Self::new(state_generation); + batches.ledger.lock().unwrap().fence = Some(SparseFenceIdentity { state_generation, allocation: fence_allocation }); + Some(batches) + } + + fn add_pages(&self, pages: impl IntoIterator<Item = usize>, reason: WorkReasons) -> bool { + // Iterator code is caller code: finish it before taking the non-reentrant ledger mutex. + let mut pages: Vec<_> = pages.into_iter().map(|page| page & !(PAGE - 1)).collect(); + pages.sort_unstable(); + pages.dedup(); + let mut ledger = self.ledger.lock().unwrap(); + if ledger.check(self.state_generation).is_err() { return false } + ledger.work.add_pages(pages, reason); + true + } + + fn add_dirty_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { + self.add_pages(pages, WorkReasons::DIRTY) + } + + fn add_retry_pages(&self, pages: impl IntoIterator<Item = usize>) -> bool { + self.add_pages(pages, WorkReasons::RETRY) + } + + fn add_zero_ranges(&self, ranges: &[(usize, usize)]) -> bool { + let mut ledger = self.ledger.lock().unwrap(); + if ledger.check(self.state_generation).is_err() { return false } + ledger.work.add_zero_ranges(ranges); + true + } + + fn seal(&self, owner: u64, limit: usize) -> Result<Option<SparseBatchLease>, SparseBatchError> { + let result = self.ledger.lock().unwrap().seal(self.state_generation, owner, limit)?; + Ok(result.map(|(token, pages)| SparseBatchLease { ledger: self.ledger.clone(), token, pages })) + } + + fn observe(&self, through: u64, requester: u64) -> Result<ClaimFrontierAction, SparseBatchError> { + self.ledger.lock().unwrap().observe(self.state_generation, through, requester) + } + + fn ready_receipt(&self, through: u64, requester: u64) -> Result<SparseReadyReceipt, ForegroundWaitError> { + let ledger = self.ledger.lock().unwrap(); + let fence = ledger.fence.ok_or(ForegroundWaitError::Fence)?; + match ledger.observe(self.state_generation, through, requester).map_err(ForegroundWaitError::Batch)? { + ClaimFrontierAction::Ready { through, required_fence } => Ok(SparseReadyReceipt { + state_generation: self.state_generation, fence, through, required_fence, + }), + _ => Err(ForegroundWaitError::NotReady), + } + } + + fn through(&self) -> Result<u64, SparseBatchError> { + self.ledger.lock().unwrap().through(self.state_generation) + } + + fn take_over( + &self, token: ClaimFrontierToken, owner: u64, + ) -> Result<SparseBatchLease, SparseBatchError> { + let (token, pages) = self.ledger.lock().unwrap().take_over(token, owner)?; + Ok(SparseBatchLease { ledger: self.ledger.clone(), token, pages }) + } + + fn replace_generation(&self, replacement: u64) -> Result<Self, SparseBatchError> { + self.ledger.lock().unwrap().replace_generation(self.state_generation, replacement, None)?; + Ok(Self { ledger: self.ledger.clone(), state_generation: replacement }) + } + + fn replace_generation_with_fence( + &self, replacement: u64, fence_allocation: u64, + ) -> Result<Self, SparseBatchError> { + self.ledger.lock().unwrap().replace_generation( + self.state_generation, replacement, Some(fence_allocation), + )?; + Ok(Self { ledger: self.ledger.clone(), state_generation: replacement }) + } +} + +#[allow(dead_code)] +struct SparseBatchLease { + ledger: Arc<Mutex<SparseBatchLedger>>, + token: ClaimFrontierToken, + pages: Vec<(usize, WorkReasons)>, +} + +#[allow(dead_code)] +impl SparseBatchLease { + fn pages(&self) -> &[(usize, WorkReasons)] { &self.pages } + + fn take_over(&self, owner: u64) -> Result<Self, SparseBatchError> { + let (token, pages) = self.ledger.lock().unwrap().take_over(self.token, owner)?; + Ok(Self { ledger: self.ledger.clone(), token, pages }) + } + + fn accept(self) -> Result<AcceptedSparseBatch, SparseBatchError> { + let work = self.ledger.lock().unwrap().accept(self.token)?; + Ok(AcceptedSparseBatch { ledger: self.ledger.clone(), token: Some((self.token, work)) }) + } + + fn obsolete(self) -> Result<(), SparseBatchError> { + self.ledger.lock().unwrap().obsolete(self.token) + } +} + +/// Accepted work is fail-closed: losing its owner consumes the claim and poisons the generation. +#[allow(dead_code)] +struct AcceptedSparseBatch { + ledger: Arc<Mutex<SparseBatchLedger>>, + token: Option<(ClaimFrontierToken, WorkClaimToken)>, +} + +#[allow(dead_code)] +impl AcceptedSparseBatch { + fn receipt(mut self, fence: u64) -> Result<(), SparseBatchError> { + let result = self.ledger.lock().unwrap().receipt(self.token.unwrap().0, fence); + if result.is_ok() { self.token.take(); } + result + } +} + +impl Drop for AcceptedSparseBatch { + fn drop(&mut self) { + if let Some((token, work)) = self.token.take() { + let _ = self.ledger.lock().unwrap().poison_exact(token, work); + } + } +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +#[allow(dead_code)] +struct SparseFenceIdentity { + state_generation: u64, allocation: u64, +} + +#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)] +#[allow(dead_code)] +struct TitleQueueIdentity { + raw: usize, generation: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct SparseReadyReceipt { + state_generation: u64, fence: SparseFenceIdentity, through: u64, required_fence: Option<u64>, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct ForegroundWaitToken { + state_generation: u64, fence: SparseFenceIdentity, queue: TitleQueueIdentity, serial: u64, value: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum ForegroundWaitState { Reserved, Accepted } + +struct ForegroundWaitRecord { + fence: SparseFenceIdentity, installed: u64, + pending: Option<(ForegroundWaitToken, ForegroundWaitState)>, uncertain: bool, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum ForegroundWaitError { + StaleGeneration, Fence, Queue, NotReady, Pending(ForegroundWaitToken), + Uncertain, StaleToken, Exhausted, + Batch(SparseBatchError), +} + +#[allow(dead_code)] +enum ForegroundWaitDecision { + NoWait { through: u64 }, Installed { through: u64, value: u64 }, + Reserve(ForegroundWaitReservation), +} + +#[allow(dead_code)] +struct ForegroundWaitLedger { + state_generation: u64, fence: SparseFenceIdentity, + next_queue_generation: u64, next_serial: u64, + queues: BTreeMap<usize, u64>, + waits: BTreeMap<TitleQueueIdentity, ForegroundWaitRecord>, +} + +#[allow(dead_code)] +impl ForegroundWaitLedger { + fn new(state_generation: u64, fence_allocation: u64) -> Option<Self> { + if state_generation == 0 || fence_allocation == 0 { return None } + Some(Self { + state_generation, + fence: SparseFenceIdentity { state_generation, allocation: fence_allocation }, + next_queue_generation: 0, + next_serial: 0, + queues: BTreeMap::new(), + waits: BTreeMap::new(), + }) + } + + fn register_queue(&mut self, raw: usize) -> Result<TitleQueueIdentity, ForegroundWaitError> { + if raw == 0 { return Err(ForegroundWaitError::Queue) } + if let Some(&generation) = self.queues.get(&raw) { + return Ok(TitleQueueIdentity { raw, generation }); + } + let generation = self.next_queue_generation.checked_add(1).ok_or(ForegroundWaitError::Exhausted)?; + self.next_queue_generation = generation; + self.queues.insert(raw, generation); + Ok(TitleQueueIdentity { raw, generation }) + } + + fn retire_queue(&mut self, queue: TitleQueueIdentity) -> Result<(), ForegroundWaitError> { + if self.queues.get(&queue.raw) != Some(&queue.generation) { return Err(ForegroundWaitError::Queue) } + self.queues.remove(&queue.raw); + self.waits.remove(&queue); + Ok(()) + } + + fn reserve( + &mut self, queue: TitleQueueIdentity, ready: SparseReadyReceipt, + ) -> Result<ForegroundWaitDecision, ForegroundWaitError> { + if ready.state_generation != self.state_generation { return Err(ForegroundWaitError::StaleGeneration) } + if ready.fence != self.fence { return Err(ForegroundWaitError::Fence) } + if self.queues.get(&queue.raw) != Some(&queue.generation) { return Err(ForegroundWaitError::Queue) } + if let Some(record) = self.waits.get(&queue) { + if record.fence != ready.fence { return Err(ForegroundWaitError::Fence) } + if record.uncertain { return Err(ForegroundWaitError::Uncertain) } + if let Some((token, _)) = record.pending { return Err(ForegroundWaitError::Pending(token)) } + } + let Some(value) = ready.required_fence else { return Ok(ForegroundWaitDecision::NoWait { through: ready.through }) }; + if value == 0 { return Err(ForegroundWaitError::Fence) } + let record = self.waits.entry(queue).or_insert(ForegroundWaitRecord { + fence: ready.fence, + installed: 0, + pending: None, + uncertain: false, + }); + if record.installed >= value { return Ok(ForegroundWaitDecision::Installed { through: ready.through, value }) } + let serial = self.next_serial.checked_add(1).ok_or(ForegroundWaitError::Exhausted)?; + self.next_serial = serial; + let token = ForegroundWaitToken { state_generation: self.state_generation, fence: ready.fence, queue, serial, value }; + record.pending = Some((token, ForegroundWaitState::Reserved)); + Ok(ForegroundWaitDecision::Reserve(ForegroundWaitReservation { + ledger: None, + token: Some(token), + through: ready.through, + })) + } + + fn transition( + &mut self, token: ForegroundWaitToken, expected: ForegroundWaitState, + replacement: Option<ForegroundWaitState>, + ) -> Result<(), ForegroundWaitError> { + if token.state_generation != self.state_generation { return Err(ForegroundWaitError::StaleGeneration) } + if token.fence != self.fence { return Err(ForegroundWaitError::Fence) } + if self.queues.get(&token.queue.raw) != Some(&token.queue.generation) { + return Err(ForegroundWaitError::Queue); + } + let record = self.waits.get_mut(&token.queue).ok_or(ForegroundWaitError::StaleToken)?; + if record.pending != Some((token, expected)) { return Err(ForegroundWaitError::StaleToken) } + record.pending = replacement.map(|state| (token, state)); + Ok(()) + } + + fn publish(&mut self, token: ForegroundWaitToken) -> Result<(), ForegroundWaitError> { + self.transition(token, ForegroundWaitState::Accepted, None)?; + self.waits.get_mut(&token.queue).unwrap().installed = token.value; + Ok(()) + } + + fn uncertain(&mut self, token: ForegroundWaitToken) { + if self.transition(token, ForegroundWaitState::Accepted, None).is_ok() { + self.waits.get_mut(&token.queue).unwrap().uncertain = true; + } + } + + fn replace_generation( + &mut self, current: u64, replacement: u64, fence_allocation: u64, + ) -> Result<(), ForegroundWaitError> { + if current != self.state_generation || replacement <= current { + return Err(ForegroundWaitError::StaleGeneration); + } + if fence_allocation <= self.fence.allocation { return Err(ForegroundWaitError::Fence) } + self.state_generation = replacement; + self.fence = SparseFenceIdentity { state_generation: replacement, allocation: fence_allocation }; + self.waits.clear(); + Ok(()) + } +} + +#[derive(Clone)] +#[allow(dead_code)] +struct ForegroundWaits(Arc<Mutex<ForegroundWaitLedger>>); + +#[allow(dead_code)] +impl ForegroundWaits { + fn new(state_generation: u64, fence_allocation: u64) -> Option<Self> { + Some(Self(Arc::new(Mutex::new(ForegroundWaitLedger::new(state_generation, fence_allocation)?)))) + } + + fn register_queue(&self, raw: usize) -> Result<TitleQueueIdentity, ForegroundWaitError> { + self.0.lock().unwrap().register_queue(raw) + } + + fn fence(&self) -> SparseFenceIdentity { self.0.lock().unwrap().fence } + + fn retire_queue(&self, queue: TitleQueueIdentity) -> Result<(), ForegroundWaitError> { + self.0.lock().unwrap().retire_queue(queue) + } + + fn replace_generation( + &self, current: u64, replacement: u64, fence_allocation: u64, + ) -> Result<(), ForegroundWaitError> { + self.0.lock().unwrap().replace_generation(current, replacement, fence_allocation) + } + + fn reserve( + &self, queue: TitleQueueIdentity, ready: SparseReadyReceipt, + ) -> Result<ForegroundWaitDecision, ForegroundWaitError> { + let result = self.0.lock().unwrap().reserve(queue, ready)?; + Ok(match result { + ForegroundWaitDecision::Reserve(mut reservation) => { + reservation.ledger = Some(self.0.clone()); + ForegroundWaitDecision::Reserve(reservation) + } + ready => ready, + }) + } +} + +#[allow(dead_code)] +struct ForegroundWaitReservation { + ledger: Option<Arc<Mutex<ForegroundWaitLedger>>>, token: Option<ForegroundWaitToken>, through: u64, +} + +#[allow(dead_code)] +impl ForegroundWaitReservation { + fn arm(mut self) -> Result<AcceptedForegroundWait, ForegroundWaitError> { + let token = self.token.unwrap(); + self.ledger.as_ref().unwrap().lock().unwrap().transition( + token, ForegroundWaitState::Reserved, Some(ForegroundWaitState::Accepted), + )?; + self.token.take(); + Ok(AcceptedForegroundWait { ledger: self.ledger.take().unwrap(), token: Some(token), through: self.through }) + } +} + +impl Drop for ForegroundWaitReservation { + fn drop(&mut self) { + if let (Some(ledger), Some(token)) = (&self.ledger, self.token.take()) { + let _ = ledger.lock().unwrap().transition(token, ForegroundWaitState::Reserved, None); + } + } +} + +#[allow(dead_code)] +struct AcceptedForegroundWait { + ledger: Arc<Mutex<ForegroundWaitLedger>>, token: Option<ForegroundWaitToken>, through: u64, +} + +#[allow(dead_code)] +impl AcceptedForegroundWait { + fn publish(mut self) -> Result<(u64, u64), ForegroundWaitError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().publish(token)?; + self.token.take(); + Ok((self.through, token.value)) + } + + fn rollback(mut self) -> Result<(), ForegroundWaitError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().transition(token, ForegroundWaitState::Accepted, None)?; + self.token.take(); + Ok(()) + } +} + +impl Drop for AcceptedForegroundWait { + fn drop(&mut self) { + if let Some(token) = self.token.take() { self.ledger.lock().unwrap().uncertain(token) } + } +} + +/// Point-in-time identities needed to prove that planning and a later serialized upload commit +/// still refer to the same sparse page. `source` names the observed CPU page by chunk hash rather +/// than retaining a raw pointer across the unlocked interval. Title writes are outside sparse +/// state/upload exclusion, so a future commit must own or revalidate the bytes it actually copies. +#[derive(Clone, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadPageObservation { + page: usize, + pool: (u32, u32), + hole: bool, + sent: Option<[u64; CHUNKS]>, + source: [u64; CHUNKS], +} + +#[derive(Clone, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct PlannedUploadPage { + page: usize, + tile: usize, + pool: (u32, u32), + reasons: WorkReasons, + zero: bool, + dirty: bool, + dirty_ranges: Vec<(usize, usize)>, + sent: Option<[u64; CHUNKS]>, + source: [u64; CHUNKS], +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadPlanInvalid { + StateGeneration, + MappingEpoch, + MissingPage, + Mapping, + SentHashes, + SourceHashes, +} +/// Private owned stand-in for a future mapped staging allocation. Keeping the copied bytes here +/// makes it impossible for the record/execute callback to retain a borrowed title-memory view. +#[allow(dead_code)] +struct OwnedUploadStaging { + range: UploadRingRange, + bytes: Box<[u8]>, +} + +fn build_upload_pages( + claimed: &[(usize, WorkReasons)], mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, +) -> Option<Vec<PlannedUploadPage>> { + let mut pages = Vec::with_capacity(claimed.len()); + for &(page, reasons) in claimed { + let observation = observe(page)?; + if observation.page != page || observation.hole { return None } + let dirty = reasons.0 & (WorkReasons::DIRTY.0 | WorkReasons::RETRY.0) != 0; + let mut dirty_ranges = Vec::new(); + if dirty { + let sent = observation.sent.as_ref().unwrap_or(&ZERO_HASHES); + for (chunk, (&source, &previous)) in observation.source.iter().zip(sent).enumerate() { + if source != previous { push_run(&mut dirty_ranges, page + chunk * CHUNK, CHUNK) } + } + } + pages.push(PlannedUploadPage { + page, + tile: page & !(TILE - 1), + pool: observation.pool, + reasons, + zero: reasons.0 & WorkReasons::ZERO.0 != 0, + dirty, + dirty_ranges, + sent: observation.sent, + source: observation.source, + }); + } + Some(pages) +} + +fn validate_upload_pages( + pages: &[PlannedUploadPage], mut observe: impl FnMut(usize) -> Option<UploadPageObservation>, +) -> Result<(), UploadPlanInvalid> { + for planned in pages { + let current = observe(planned.page).ok_or(UploadPlanInvalid::MissingPage)?; + if current.page != planned.page + || current.page & !(TILE - 1) != planned.tile + || current.pool != planned.pool + || current.hole + { + return Err(UploadPlanInvalid::Mapping); + } + if current.sent != planned.sent { return Err(UploadPlanInvalid::SentHashes) } + if current.source != planned.source { return Err(UploadPlanInvalid::SourceHashes) } + } + Ok(()) +} + +#[derive(Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum CoordinatedSparseUploadError<C, E, S> { + Invalid(UploadPlanInvalid), + Reserve(UploadReservationError), + Copy(C), + StagingSize, + Prepare(E), + Accept(SparseBatchError), + Signal(S), + PublishReservation(UploadReservationError), + PublishBatch(SparseBatchError), +} + +/// New inert composition path: the plan owns a revocable batch lease rather than an independently +/// restoring work guard. Dropping before acceptance leaves the batch visible for foreground help. +#[allow(dead_code)] +struct CoordinatedSparseUploadPlan { + lease: Option<SparseBatchLease>, + state_generation: u64, + mapping_epoch: u64, + pages: Vec<PlannedUploadPage>, +} + +#[allow(dead_code)] +impl CoordinatedSparseUploadPlan { + fn build( + lease: SparseBatchLease, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + ) -> Option<Self> { + if lease.token.state_generation != state_generation { return None } + let pages = build_upload_pages(lease.pages(), observe)?; + Some(Self { lease: Some(lease), state_generation, mapping_epoch, pages }) + } + + fn validate( + &self, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + ) -> Result<(), UploadPlanInvalid> { + if state_generation != self.state_generation { return Err(UploadPlanInvalid::StateGeneration) } + if mapping_epoch != self.mapping_epoch { return Err(UploadPlanInvalid::MappingEpoch) } + validate_upload_pages(&self.pages, observe) + } + + fn commit_reserved<C, E, S>( + mut self, + state_generation: u64, + mapping_epoch: u64, + observe: impl FnMut(usize) -> Option<UploadPageObservation>, + reservations: &UploadReservations, + slot: usize, + bytes: usize, + copy: impl FnOnce(UploadRingRange, &[PlannedUploadPage]) -> Result<Vec<u8>, C>, + prepare: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]) -> Result<(), E>, + execute: impl FnOnce(&OwnedUploadStaging, &[PlannedUploadPage]), + signal: impl FnOnce() -> Result<u64, S>, + ) -> Result<UploadSubmissionReceipt, CoordinatedSparseUploadError<C, E, S>> { + self.validate(state_generation, mapping_epoch, observe) + .map_err(CoordinatedSparseUploadError::Invalid)?; + let reservation = reservations.reserve_for(state_generation, slot, bytes) + .map_err(CoordinatedSparseUploadError::Reserve)?; + let range = reservation.range(); + let copied = copy(range, &self.pages).map_err(CoordinatedSparseUploadError::Copy)?; + if copied.len() != bytes { return Err(CoordinatedSparseUploadError::StagingSize) } + let staging = OwnedUploadStaging { range, bytes: copied.into_boxed_slice() }; + prepare(&staging, &self.pages).map_err(CoordinatedSparseUploadError::Prepare)?; + + let batch = self.lease.take().expect("finished coordinated sparse upload plan").accept() + .map_err(CoordinatedSparseUploadError::Accept)?; + let accepted = AcceptedCoordinatedUpload::new(reservation, batch); + execute(&staging, &self.pages); + let fence = signal().map_err(CoordinatedSparseUploadError::Signal)?; + match accepted.publish(fence) { + Ok(receipt) => Ok(receipt), + Err(CoordinatedPublishError::Reservation(error)) => { + Err(CoordinatedSparseUploadError::PublishReservation(error)) + } + Err(CoordinatedPublishError::Batch(error)) => Err(CoordinatedSparseUploadError::PublishBatch(error)), + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadReservationToken { + state_generation: u64, + serial: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadRingRange { + start: u64, + end: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +struct UploadSubmissionReceipt { + token: UploadReservationToken, + fence: u64, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadReservationState { + Reserved, + Submitted { fence: u64, retired: bool }, + Cancelled, + Poisoned, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[allow(dead_code)] +enum UploadReservationError { + Poisoned, + StaleGeneration, + Slot, + SlotBusy, + Empty, + TooLarge, + Full, + Exhausted, + Missing, + State, + Fence, +} + +struct UploadReservationRecord { + slot: usize, + range: UploadRingRange, + state: UploadReservationState, +} + +/// Inert ownership model for a later short upload commit phase. Ring positions only advance; +/// cancellation leaves a retired interval in the ordered ledger instead of rewinding across a +/// newer reservation. Submitted intervals become reusable only after their exact fence retires and +/// every older interval has retired. A failed ordering signal poisons the whole generation. +#[allow(dead_code)] +struct UploadReservationLedger { + state_generation: u64, + capacity: u64, + alignment: u64, + next_serial: u64, + cursor: u64, + reclaimed: u64, + poisoned: bool, + slots: Vec<Option<u64>>, + order: VecDeque<u64>, + records: BTreeMap<u64, UploadReservationRecord>, +} + +#[allow(dead_code)] +impl UploadReservationLedger { + fn new(state_generation: u64, slots: usize, capacity: usize, alignment: usize) -> Self { + assert!(slots > 0); + assert!(capacity > 0); + assert!(alignment > 0 && alignment.is_power_of_two() && capacity % alignment == 0); + Self { + state_generation, + capacity: capacity as u64, + alignment: alignment as u64, + next_serial: 0, + cursor: 0, + reclaimed: 0, + poisoned: false, + slots: vec![None; slots], + order: VecDeque::new(), + records: BTreeMap::new(), + } + } + + fn reserve( + &mut self, state_generation: u64, slot: usize, bytes: usize, + ) -> Result<(UploadReservationToken, UploadRingRange), UploadReservationError> { + if state_generation != self.state_generation { + return Err(UploadReservationError::StaleGeneration); + } + if self.poisoned { + return Err(UploadReservationError::Poisoned); + } + let owner = self.slots.get(slot).ok_or(UploadReservationError::Slot)?; + if owner.is_some() { + return Err(UploadReservationError::SlotBusy); + } + if bytes == 0 { + return Err(UploadReservationError::Empty); + } + if bytes as u64 > self.capacity { + return Err(UploadReservationError::TooLarge); + } + let (cursor, reclaimed) = if self.order.is_empty() { + let offset = self.cursor % self.capacity; + let boundary = if offset == 0 { + self.cursor + } else { + self.cursor.checked_add(self.capacity - offset).ok_or(UploadReservationError::Exhausted)? + }; + (boundary, boundary) + } else { + (self.cursor, self.reclaimed) + }; + let mask = self.alignment - 1; + let mut start = cursor.checked_add(mask).ok_or(UploadReservationError::Exhausted)? & !mask; + let offset = start % self.capacity; + if offset.checked_add(bytes as u64).ok_or(UploadReservationError::Exhausted)? > self.capacity { + start = start.checked_add(self.capacity - offset).ok_or(UploadReservationError::Exhausted)?; + } + let end = start.checked_add(bytes as u64).ok_or(UploadReservationError::Exhausted)?; + if end.checked_sub(reclaimed).ok_or(UploadReservationError::Exhausted)? > self.capacity { + return Err(UploadReservationError::Full); + } + let serial = self.next_serial.checked_add(1).ok_or(UploadReservationError::Exhausted)?; + self.next_serial = serial; + self.cursor = end; + self.reclaimed = reclaimed; + self.slots[slot] = Some(serial); + let range = UploadRingRange { start, end }; + self.order.push_back(serial); + self.records.insert(serial, UploadReservationRecord { slot, range, state: UploadReservationState::Reserved }); + Ok((UploadReservationToken { state_generation, serial }, range)) + } + + fn submit(&mut self, token: UploadReservationToken, fence: u64) -> Result<(), UploadReservationError> { + let record = self.record_mut(token)?; + if record.state != UploadReservationState::Reserved || fence == 0 { + return Err(UploadReservationError::State); + } + record.state = UploadReservationState::Submitted { fence, retired: false }; + Ok(()) + } + + fn complete(&mut self, receipt: UploadSubmissionReceipt) -> Result<u64, UploadReservationError> { + let record = self.record_mut(receipt.token)?; + match record.state { + UploadReservationState::Submitted { fence: expected, retired: false } if expected == receipt.fence => { + record.state = UploadReservationState::Submitted { fence: receipt.fence, retired: true }; + let slot = record.slot; + self.slots[slot] = None; + Ok(self.reclaim()) + } + UploadReservationState::Submitted { fence: expected, .. } if expected != receipt.fence => { + Err(UploadReservationError::Fence) + } + _ => Err(UploadReservationError::State), + } + } + + fn cancel(&mut self, token: UploadReservationToken) -> Result<u64, UploadReservationError> { + let record = self.record_mut(token)?; + if record.state != UploadReservationState::Reserved { + return Err(UploadReservationError::State); + } + record.state = UploadReservationState::Cancelled; + let slot = record.slot; + self.slots[slot] = None; + Ok(self.reclaim()) + } + + fn poison(&mut self, token: UploadReservationToken) -> Result<(), UploadReservationError> { + let record = self.record_mut(token)?; + if record.state != UploadReservationState::Reserved { + return Err(UploadReservationError::State); + } + record.state = UploadReservationState::Poisoned; + self.poisoned = true; + Ok(()) + } + + /// Fail closed even after submission publication: no slot or ring byte in this generation may + /// be reused when the matching batch receipt could not be published. + fn poison_generation(&mut self, token: UploadReservationToken) { + if token.state_generation != self.state_generation { return } + if let Some(record) = self.records.get_mut(&token.serial) { + if matches!(record.state, UploadReservationState::Reserved | UploadReservationState::Submitted { .. }) { + record.state = UploadReservationState::Poisoned; + } + } + self.poisoned = true; + } + + fn record_mut( + &mut self, token: UploadReservationToken, + ) -> Result<&mut UploadReservationRecord, UploadReservationError> { + if token.state_generation != self.state_generation { + return Err(UploadReservationError::StaleGeneration); + } + self.records.get_mut(&token.serial).ok_or(UploadReservationError::Missing) + } + + fn reclaim(&mut self) -> u64 { + while let Some(&serial) = self.order.front() { + let retired = self.records.get(&serial).is_some_and(|record| match record.state { + UploadReservationState::Cancelled => true, + UploadReservationState::Submitted { retired, .. } => retired, + UploadReservationState::Reserved | UploadReservationState::Poisoned => false, + }); + if !retired { + break; + } + let record = self.records.remove(&serial).unwrap(); + self.reclaimed = record.range.end; + self.order.pop_front(); + } + self.reclaimed + } +} + +#[derive(Clone)] +#[allow(dead_code)] +struct UploadReservations(Arc<Mutex<UploadReservationLedger>>); + +#[allow(dead_code)] +impl UploadReservations { + fn new(state_generation: u64, slots: usize, capacity: usize, alignment: usize) -> Self { + Self(Arc::new(Mutex::new(UploadReservationLedger::new(state_generation, slots, capacity, alignment)))) + } + + fn reserve(&self, slot: usize, bytes: usize) -> Result<UploadReservation, UploadReservationError> { + let mut ledger = self.0.lock().unwrap(); + let generation = ledger.state_generation; + let (token, range) = ledger.reserve(generation, slot, bytes)?; + Ok(UploadReservation { ledger: self.0.clone(), token: Some(token), range }) + } + + fn reserve_for( + &self, state_generation: u64, slot: usize, bytes: usize, + ) -> Result<UploadReservation, UploadReservationError> { + let (token, range) = self.0.lock().unwrap().reserve(state_generation, slot, bytes)?; + Ok(UploadReservation { ledger: self.0.clone(), token: Some(token), range }) + } + + fn complete(&self, receipt: UploadSubmissionReceipt) -> Result<u64, UploadReservationError> { + self.0.lock().unwrap().complete(receipt) + } +} + +#[allow(dead_code)] +struct UploadReservation { + ledger: Arc<Mutex<UploadReservationLedger>>, + token: Option<UploadReservationToken>, + range: UploadRingRange, +} + +#[allow(dead_code)] +impl UploadReservation { + fn range(&self) -> UploadRingRange { self.range } + + fn submit(mut self, fence: u64) -> Result<UploadSubmissionReceipt, UploadReservationError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().submit(token, fence)?; + self.token.take(); + Ok(UploadSubmissionReceipt { token, fence }) + } + + fn poison(mut self) -> Result<(), UploadReservationError> { + let token = self.token.unwrap(); + self.ledger.lock().unwrap().poison(token)?; + self.token.take(); + Ok(()) + } + + /// Publish after execute acceptance. Publication failure is fail-closed: the exact record and + /// its entire generation are poisoned instead of being cancelled by this guard's destructor. + fn publish_after_accept(mut self, fence: u64) -> Result<UploadSubmissionReceipt, UploadReservationError> { + let token = self.token.take().expect("finished upload reservation"); + let mut ledger = self.ledger.lock().unwrap(); + if fence == 0 { + let _ = ledger.poison(token); + return Err(UploadReservationError::State); + } + match ledger.submit(token, fence) { + Ok(()) => Ok(UploadSubmissionReceipt { token, fence }), + Err(error) => { + let _ = ledger.poison(token); + Err(error) + } + } + } +} + +impl Drop for UploadReservation { + fn drop(&mut self) { + if let Some(token) = self.token.take() { + let _ = self.ledger.lock().unwrap().cancel(token); + } + } +} + +enum CoordinatedPublishError { + Reservation(UploadReservationError), + Batch(SparseBatchError), +} + +/// Own both accepted ledgers. Any exit before both receipts are published poisons both generation +/// domains, including the narrow boundary after reservation submission but before frontier receipt. +struct AcceptedCoordinatedUpload { + reservation: Option<UploadReservation>, + reservation_token: UploadReservationToken, + reservation_ledger: Arc<Mutex<UploadReservationLedger>>, + batch: Option<AcceptedSparseBatch>, + batch_token: ClaimFrontierToken, + batch_ledger: Arc<Mutex<SparseBatchLedger>>, + armed: bool, +} + +impl AcceptedCoordinatedUpload { + fn new(reservation: UploadReservation, batch: AcceptedSparseBatch) -> Self { + Self { + reservation_token: reservation.token.unwrap(), + reservation_ledger: reservation.ledger.clone(), + batch_token: batch.token.unwrap().0, + batch_ledger: batch.ledger.clone(), + reservation: Some(reservation), + batch: Some(batch), + armed: true, + } + } + + fn publish(mut self, fence: u64) -> Result<UploadSubmissionReceipt, CoordinatedPublishError> { + let receipt = self.reservation.take().unwrap().publish_after_accept(fence) + .map_err(CoordinatedPublishError::Reservation)?; + self.batch.take().unwrap().receipt(fence).map_err(CoordinatedPublishError::Batch)?; + self.armed = false; + Ok(receipt) + } +} + +impl Drop for AcceptedCoordinatedUpload { + fn drop(&mut self) { + if !self.armed { return } + if let Some(reservation) = self.reservation.take() { let _ = reservation.poison(); } + if let Some(batch) = self.batch.take() { drop(batch); } + self.reservation_ledger.lock().unwrap().poison_generation(self.reservation_token); + let mut batches = self.batch_ledger.lock().unwrap(); + if batches.work.state_generation == self.batch_token.state_generation { batches.poisoned = true } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) enum PreparationOutcome { + Ready, + RetryRequired, + ExecutedUntracked, +} + +impl From<SubmitResult> for PreparationOutcome { + fn from(result: SubmitResult) -> Self { + match result { + SubmitResult::Submitted => Self::Ready, + SubmitResult::NotSubmitted => Self::RetryRequired, + SubmitResult::Unordered => Self::ExecutedUntracked, + } + } +} + +struct RetiredTiles { + tiles: Vec<(u32, u32)>, + /// Fence marks on `self.queue` and every known title queue (`None` = signal failed, keep held). + marks: Option<Vec<(ID3D12Fence, u64)>>, +} + +struct State { + generation: u64, + mapping_epoch: u64, + dev: ID3D12Device, + queue: ID3D12CommandQueue, + fence: ID3D12Fence, + value: u64, + /// reusable auto-reset Win32 event for fence waits (no per-wait CreateEventW/CloseHandle) + event: HANDLE, + /// fence signalled on title queues so `queue` waits before copying GPU writes back to CPU + rb_fence: ID3D12Fence, + rb_value: u64, + /// (window start, reserved buffer) of each sparse window + windows: Vec<(usize, ID3D12Resource)>, + /// video-memory pool heaps (None: given back, its index free for the next one) + pools: Vec<Option<ID3D12Heap>>, + free: Vec<(u32, u32)>, + /// pools all of whose tiles came free: released once the GPU is past `value` and a moment + /// went by (titles' queues may still read what was mapped there) + retired: Vec<(ID3D12Heap, u64, std::time::Instant)>, + /// tile address → pool tile + uncommitted page hole mask + per-page sent chunk hashes + mapped: FxHashMap<usize, TileEntry>, + /// pool tiles also used by placed buffers (not freed while they are) + pinned: FxHashMap<(u32, u32), u32>, + /// tile address → pool tile of tiles decommitted since the last title submit, still mapped + /// in their window: unmapped together (`flush_parked`) before the next submit, when the free + /// list runs out, or past `PARKED_MAX`; a commit there before that takes its tile back with + /// no new mapping. (A retail title moving physical pages one at a time while it loads + /// decommits and commits again thousands of tiles a second, and each `UpdateTileMappings` + /// took ~0.15 ms.) + parked: FxHashMap<usize, (u32, u32)>, + /// unmapped parked pool tiles awaiting `self.queue` and in-flight title queues before entering `free` + quarantined: VecDeque<RetiredTiles>, + /// per-title-queue fences used to mark in-flight GPU work; raw keys are removed only by + /// exact-generation queue retirement before that queue's address can be reused + queue_fences: FxHashMap<usize, (ID3D12Fence, u64)>, + /// placed buffers → the pool tiles they use + buffers: FxHashMap<usize, Vec<(u32, u32)>>, + /// reused tiles / decommitted partial pages to clear: (address, bytes) + to_zero: Vec<(usize, usize)>, + /// ring-buffered upload staging heap (`STAGING` bytes, persistently mapped) + staging: Option<(ID3D12Resource, *mut u8)>, + /// monotonic ring-buffer write/submitted/retired byte cursors + ring_write: u64, + ring_submitted: u64, + ring_free: u64, + /// submitted ring chunks awaiting GPU completion: `(fence_val, ring_end_pos)` + inflight: VecDeque<(u64, u64)>, + /// false after ExecuteCommandLists succeeded but its ordering Signal failed: no upload + /// allocator or staging byte may be reused because completion can no longer be proved. + uploads_ordered: bool, + /// dedicated 1 MiB pre-zeroed buffer for tile/hole clears (zero staging bandwidth) + zero_buf: Option<ID3D12Resource>, + /// ring of async upload command allocators + lists + slots: Vec<UploadSlot>, + next_slot: usize, + /// dedicated readback staging buffer + command allocator / list + readback: Option<(ID3D12Resource, *mut u8)>, + rb_alloc: ID3D12CommandAllocator, + rb_list: ID3D12GraphicsCommandList, + rb_last_fence: u64, + /// the fence value each title queue last waited for + waited: FxHashMap<usize, u64>, + /// `mapped` as sorted (start, end) runs (None: to be made again) + runs: Option<Vec<(usize, usize)>>, + /// reusable buffer for dirty runs in `before_execute` (avoids per-submit heap alloc) + scratch_runs: Vec<(usize, usize)>, + /// Dirty CPU pages whose write-watch bits were reset before an upload failed. + retry_pages: Vec<usize>, +} + +impl Drop for State { + fn drop(&mut self) { + if !self.event.is_invalid() { + unsafe { + let _ = CloseHandle(self.event); + } + } + } +} + +const K0: u64 = 0x9E37_79B9_7F4A_7C15; +const K1: u64 = 0xBF58_476D_1CE4_E5B9; +const K2: u64 = 0x94D0_49BB_1331_11EB; +const K3: u64 = 0x243F_6A88_85A3_08D3; + +/// 4-way parallel hash over 8 `u64` words (64 bytes): breaks serial multiply latency chain. +#[inline(always)] +const fn hash_words(w: [u64; 8]) -> u64 { + let a = (w[0] ^ K3).wrapping_mul(K0) ^ w[4].wrapping_mul(K1); + let b = (w[1] ^ K0).wrapping_mul(K1) ^ w[5].wrapping_mul(K2); + let c = (w[2] ^ K1).wrapping_mul(K2) ^ w[6].wrapping_mul(K3); + let d = (w[3] ^ K2).wrapping_mul(K3) ^ w[7].wrapping_mul(K0); + let h = a.rotate_left(27).wrapping_add(b.rotate_left(13)) ^ c.rotate_left(41).wrapping_add(d.rotate_left(53)); + h.wrapping_mul(K0) ^ (h >> 32) +} + +const ZERO_HASH: u64 = hash_words([0; 8]); +const ZERO_HASHES: [u64; CHUNKS] = [ZERO_HASH; CHUNKS]; + +#[inline(always)] +fn read_chunk_words(c: &[u8]) -> [u64; 8] { + debug_assert_eq!(c.len(), CHUNK); + let p = c.as_ptr() as *const [u8; 8]; + unsafe { + [ + u64::from_le_bytes(p.add(0).read_unaligned()), + u64::from_le_bytes(p.add(1).read_unaligned()), + u64::from_le_bytes(p.add(2).read_unaligned()), + u64::from_le_bytes(p.add(3).read_unaligned()), + u64::from_le_bytes(p.add(4).read_unaligned()), + u64::from_le_bytes(p.add(5).read_unaligned()), + u64::from_le_bytes(p.add(6).read_unaligned()), + u64::from_le_bytes(p.add(7).read_unaligned()), + ] + } +} + +/// hash of 64 bytes +#[inline(always)] +fn chunk_hash(c: &[u8]) -> u64 { + hash_words(read_chunk_words(c)) +} + +#[inline(always)] +fn push_run(out: &mut Vec<(usize, usize)>, addr: usize, len: usize) { + match out.last_mut() { + Some(last) if last.0 + last.1 == addr => last.1 += len, + _ => out.push((addr, len)), + } +} + +/// Land GPU bytes in one CPU page, 64-byte chunk by chunk. A chunk still matching `sent` has +/// no newer CPU write and may be replaced; a changed chunk keeps its CPU bytes and its old hash, +/// so the next write-watch look uploads it. The hash check and copy are not atomic against a +/// concurrent CPU store: callers rely on the title's fence discipline to exclude stores to the +/// same chunk while its synchronous copy-back lands. +fn land_page(slot: &mut Option<Box<[u64; CHUNKS]>>, page: &mut [u8], at: usize, src: &[u8]) { + debug_assert_eq!(page.len(), PAGE); + debug_assert!(at + src.len() <= page.len()); + let sent = slot.get_or_insert_with(|| Box::new(ZERO_HASHES)); + let end = at + src.len(); + let mut offset = at; + while offset < end { + let chunk = offset / CHUNK; + let chunk_start = chunk * CHUNK; + let copy_end = ((chunk + 1) * CHUNK).min(end); + if chunk_hash(&page[chunk_start..chunk_start + CHUNK]) == sent[chunk] { + let source = offset - at; + page[offset..copy_end].copy_from_slice(&src[source..source + copy_end - offset]); + sent[chunk] = chunk_hash(&page[chunk_start..chunk_start + CHUNK]); + } + offset = copy_end; + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct HashUpdate { + at: usize, + hash: u64, +} + +const MAX_BATCH_HASH_UPDATES: usize = STAGING / CHUNK; + +/// One synchronously-recorded dirty upload batch. The slot, ring rollback point, and unpublished +/// hash plan move together so a failed submission cannot publish bytes that have no fence receipt. +struct PreparedDirtyBatch { + slot: usize, + ring_start: u64, + updates: Vec<HashUpdate>, +} + +impl PreparedDirtyBatch { + fn new(slot: usize, ring_start: u64) -> Self { + Self { slot, ring_start, updates: Vec::new() } + } + + fn reopen(mut self, slot: usize, ring_start: u64) -> Self { + debug_assert!(self.updates.is_empty()); + self.slot = slot; + self.ring_start = ring_start; + self + } + + fn hash_plan_would_overflow(&self, bytes: usize) -> bool { + batch_hash_plan_would_overflow(self.updates.len(), bytes) + } + + fn append_hashes(&mut self, at: usize, bytes: &[u8]) { + append_hash_updates(at, bytes, &mut self.updates); + } + + fn clear_after_submit(&mut self) { + self.updates.clear(); + } +} + +fn batch_hash_plan_would_overflow(current: usize, bytes: usize) -> bool { + bytes / CHUNK > MAX_BATCH_HASH_UPDATES.saturating_sub(current) +} + +/// Plan changed 64-byte chunk runs in a 4 KiB page without publishing their hashes. The hashes +/// become `sent` only after the corresponding upload has a durable queue-fence receipt. +/// This keeps the fresh-zero-page fast path allocation-free. +#[inline] +fn scan_page( + page: &[u8], + pg: usize, + slot: &Option<Box<[u64; CHUNKS]>>, + out: &mut Vec<(usize, usize)>, +) { + if let Some(sent) = slot.as_deref() { + for (k, c) in page.chunks_exact(CHUNK).enumerate() { + let h = chunk_hash(c); + if h == sent[k] { + continue; + } + push_run(out, pg + k * CHUNK, CHUNK); + } + return; + } + // Page has never had non-zero data sent: skip zero chunks with a cheap OR-reduction and + // allocate the hash array only if at least one chunk is non-zero. + let mut chunks = page.chunks_exact(CHUNK).enumerate(); + while let Some((k, c)) = chunks.next() { + let w = read_chunk_words(c); + if (w[0] | w[1] | w[2] | w[3] | w[4] | w[5] | w[6] | w[7]) == 0 { + continue; + } + let h = hash_words(w); + if h == ZERO_HASH { + continue; + } + push_run(out, pg + k * CHUNK, CHUNK); + for (k2, c2) in chunks { + let h2 = chunk_hash(c2); + if h2 == ZERO_HASH { + continue; + } + push_run(out, pg + k2 * CHUNK, CHUNK); + } + break; + } +} + +fn append_hash_updates(at: usize, bytes: &[u8], updates: &mut Vec<HashUpdate>) { + debug_assert_eq!(at % CHUNK, 0); + debug_assert_eq!(bytes.len() % CHUNK, 0); + debug_assert!(updates.len() + bytes.len() / CHUNK <= MAX_BATCH_HASH_UPDATES); + updates.extend(bytes.chunks_exact(CHUNK).enumerate().map(|(i, chunk)| HashUpdate { + at: at + i * CHUNK, + hash: chunk_hash(chunk), + })); +} + +fn publish_hash_updates(mapped: &mut FxHashMap<usize, TileEntry>, updates: &[HashUpdate]) { + for update in updates { + let tile = update.at & !(TILE - 1); + let Some(entry) = mapped.get_mut(&tile) else { continue }; + let page = update.at & !(PAGE - 1); + let index = (page - tile) / PAGE; + let chunk = (update.at - page) / CHUNK; + if entry.holes & (1u16 << index) != 0 { + continue; + } + if update.hash == ZERO_HASH && entry.sent[index].is_none() { + continue; + } + entry.sent[index].get_or_insert_with(|| Box::new(ZERO_HASHES))[chunk] = update.hash; + } +} + +/// The byte ranges (offset, length) of `page` whose 64-byte chunks differ from `sent` +/// (updated to the page's chunks). +pub fn changed_chunks(page: &[u8], sent: &mut [u64; CHUNKS]) -> Vec<(usize, usize)> { + let mut out: Vec<(usize, usize)> = Vec::new(); + for (k, c) in page.chunks_exact(CHUNK).enumerate() { + let h = chunk_hash(c); + if h == sent[k] { + continue; + } + sent[k] = h; + push_run(&mut out, k * CHUNK, CHUNK); + } + out +} + +/// Plan a contiguous sub-allocation `(aligned_pos, chunk_len)` inside a ring buffer of `cap` +/// bytes starting at monotonic cursor `ring_write`, keeping each chunk `<= cap / 2` and +/// avoiding mid-copy wrap-around without wasting large tail gaps. +#[inline] +fn plan_ring_chunk(ring_write: u64, want: usize, cap: usize) -> (u64, usize) { + let mut chunk = want.min(cap / 2); + let mut aligned = (ring_write + (RING_ALIGN as u64 - 1)) & !(RING_ALIGN as u64 - 1); + let off = (aligned as usize) % cap; + if off + chunk > cap { + let tail = cap - off; + if tail >= PAGE { + chunk = tail; + } else { + aligned += tail as u64; + } + } + (aligned, chunk) +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct PreparedDirtyCopy { + ring_start: u64, + staging_offset: usize, + window_offset: usize, + bytes: usize, +} + +/// Bound one dirty copy to both its sparse window and its contiguous staging-ring allocation. +/// Keeping this arithmetic pure lets planning and recording use exactly the same split points. +fn prepare_dirty_copy( + at: usize, + remaining: usize, + window_base: usize, + window_size: usize, + ring_write: u64, + staging_cap: usize, +) -> PreparedDirtyCopy { + debug_assert!(at >= window_base && at < window_base + window_size); + let to_window_end = window_base + window_size - at; + let (ring_start, bytes) = plan_ring_chunk(ring_write, remaining.min(to_window_end), staging_cap); + PreparedDirtyCopy { + ring_start, + staging_offset: ring_start as usize % staging_cap, + window_offset: at - window_base, + bytes, + } +} + +// D3D12 objects are free-threaded; staging pointers and event handle are only used under STATE lock +unsafe impl Send for State {} + +static STATE: Mutex<Option<State>> = Mutex::new(None); +static NEXT_STATE_GENERATION: AtomicU64 = AtomicU64::new(1); + +/// Serialize mutation of upload slots, staging cursors and retry journals. Fence waits release this +/// gate while a shared generation lifetime keeps their exact native backing. Lock order is +/// `WAIT_GATES` → `UPLOAD_STATE_LIFETIME` (shared) → `UPLOAD_GATE` → `STATE`; +/// initialization takes `PLACEMENT` then the lifetime lock exclusively before `UPLOAD_GATE`. +static UPLOAD_GATE: Mutex<()> = Mutex::new(()); + +/// A waiter keeps its exact `State` generation and all of that generation's native backing alive +/// while `UPLOAD_GATE` is released. Other uploaders take shared ownership and can cross the wait; +/// setup takes exclusive ownership before `UPLOAD_GATE` and cannot replace `STATE` meanwhile. +static UPLOAD_STATE_LIFETIME: std::sync::RwLock<()> = std::sync::RwLock::new(()); + +type UploadGuard = std::sync::MutexGuard<'static, ()>; + +#[derive(Clone, Copy, Default)] +struct UploadGateTimes { + wait_us: u64, + hold_us: u64, + released_us: u64, +} + +struct UploadGateTiming { + enabled: bool, + held_since: Option<std::time::Instant>, + times: UploadGateTimes, +} + +impl UploadGateTiming { + fn acquire(enabled: bool) -> (Option<UploadGuard>, Self) { + let waiting = enabled.then(std::time::Instant::now); + let guard = UPLOAD_GATE.lock().unwrap(); + let acquired = enabled.then(std::time::Instant::now); + let wait_us = waiting.zip(acquired).map_or(0, |(waiting, acquired)| acquired.duration_since(waiting).as_micros() as u64); + (Some(guard), Self { enabled, held_since: acquired, times: UploadGateTimes { wait_us, ..Default::default() } }) + } + + fn with_released<T>(&mut self, guard: &mut Option<UploadGuard>, wait: impl FnOnce() -> T) -> T { + let released = self.enabled.then(std::time::Instant::now); + if let (Some(held_since), Some(released)) = (self.held_since.take(), released) { + self.times.hold_us = self.times.hold_us.wrapping_add(released.duration_since(held_since).as_micros() as u64); + } + drop(guard.take()); + let result = wait(); + *guard = Some(UPLOAD_GATE.lock().unwrap()); + let acquired = self.enabled.then(std::time::Instant::now); + if let (Some(released), Some(acquired)) = (released, acquired) { + self.times.released_us = self.times.released_us.wrapping_add(acquired.duration_since(released).as_micros() as u64); + } + self.held_since = acquired; + result + } + + fn finish(mut self) -> UploadGateTimes { + if let Some(held_since) = self.held_since.take() { + self.times.hold_us = self.times.hold_us.wrapping_add(held_since.elapsed().as_micros() as u64); + } + self.times + } +} + +/// A placement may release `STATE` while the driver creates its reserved resource. Keep sparse +/// state replacement and another placement from crossing that exact-state transaction. +static PLACEMENT: Mutex<()> = Mutex::new(()); + +/// Serializes sparse preparation through wait enqueue for one title queue. Without this, a +/// concurrent submission could observe a reserved `waited` value and execute before the thread +/// which reserved it has called the native queue `Wait`. +static WAIT_GATES: Mutex<FxHashMap<usize, Arc<Mutex<()>>>> = Mutex::new(FxHashMap::with_hasher(BuildHasherDefault::new())); + +/// The state's queue again, outside `STATE` (`queue`). `STATE` is held around D3D12 calls (an +/// upload's allocator `Reset` in `begin_slot`), and `late_release` asks for the queue from a +/// resource's last `Release`, which D3D12 can make inside a call of its own on another thread +/// (a list's `Reset`, with `XCL_DRED=1` on every start): the two then waited for each other. +static QUEUE: Mutex<Option<ID3D12CommandQueue>> = Mutex::new(None); + +fn remove_queue_fence<F>(fences: &mut FxHashMap<usize, (F, u64)>, raw: usize) -> Option<(F, u64)> { + fences.remove(&raw) +} + +fn initial_quarantine_marks<F: Clone>(own: (F, u64), retiring: &[(F, u64)], blocked: bool) -> Option<Vec<(F, u64)>> { + (!blocked).then(|| std::iter::once(own).chain(retiring.iter().cloned()).collect()) +} + +/// Remove raw queue-address state before a retired queue's final owner is released. Retired tile +/// batches own fence clones independently; the cached fence drops after unlocking. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = { + let mut state = STATE.lock().unwrap(); + state.as_mut().and_then(|state| { + state.waited.remove(&id.raw()); + remove_queue_fence(&mut state.queue_fences, id.raw()) + }) + }; + let gate = WAIT_GATES.lock().unwrap().remove(&id.raw()); + drop(gone); + drop(gate); +} + +/// (bytes of video memory in pool heaps, of those mapped) – `XCL_ACTIVITY` +pub fn pool_bytes() -> (usize, usize) { + let g = lock_state(); + let Some(s) = g.as_ref() else { return (0, 0) }; + let pools = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize * TILE; + (pools, pools.saturating_sub(s.free.len() * TILE)) +} + +/// Active pool bytes, occupied tile bytes, retired pool bytes, and committed CPU page bytes for +/// `device`, from one state lock so a pool moving to the retired list cannot be counted twice. +pub(super) fn memory_bytes_for(device: usize) -> (usize, usize, usize, usize) { + let g = lock_state(); + let Some(s) = g.as_ref() else { return (0, 0, 0, 0) }; + memory_byte_counts( + device, + s.dev.as_raw() as usize, + s.pools.iter().filter(|p| p.is_some()).count(), + s.free.len(), + s.retired.len(), + s.mapped.values().map(|e| e.holes), + ) +} + +fn memory_byte_counts( + device: usize, + owner: usize, + active_pools: usize, + free_tiles: usize, + retired_pools: usize, + mapped_holes: impl Iterator<Item = u16>, +) -> (usize, usize, usize, usize) { + if device != owner { + return (0, 0, 0, 0); + } + let pool_bytes = (POOL_TILES as usize).saturating_mul(TILE); + let pools = active_pools.saturating_mul(pool_bytes); + let occupied = pools.saturating_sub(free_tiles.saturating_mul(TILE)); + let retired = retired_pools.saturating_mul(pool_bytes); + let committed = mapped_holes.fold(0usize, |bytes, holes| { + let pages = PAGES_PER_TILE.saturating_sub(holes.count_ones() as usize); + bytes.saturating_add(pages.saturating_mul(PAGE)) + }); + (pools, occupied, retired, committed) +} +/// commits before the device existed: the pages committed, as disjoint page ranges (start → +/// end) merged with their neighbours, so a commit or decommit costs O(log n) and not a scan of +/// every page committed so far. Like `committed` / `decommitted` with a state, a range counts +/// every page it touches; `init` commits them once the windows exist. +static EARLY: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); +/// Before the sparse device exists: pages the title protected other than writable. Commits clear +/// these ranges, and `init` replays what remains after the early commits. +static EARLY_NOT_RW: Mutex<BTreeMap<usize, usize>> = Mutex::new(BTreeMap::new()); + +fn early_protection(early: &mut BTreeMap<usize, usize>, a: usize, n: usize, writable: bool) { + let (start, end) = page_span(a, n); + if writable { + early_remove(early, start, end); + } else { + early_add(early, start, end); + } +} + +/// The pages `[a, a + n)` touches, as `[start, end)`. +fn page_span(a: usize, n: usize) -> (usize, usize) { + (a & !(PAGE - 1), a.saturating_add(n).saturating_add(PAGE - 1) & !(PAGE - 1)) +} + +/// Add the pages `[a, b)` to `early`, merged with the ranges they overlap or touch. +fn early_add(early: &mut BTreeMap<usize, usize>, mut a: usize, mut b: usize) { + if a >= b { + return; + } + if let Some((&s, &e)) = early.range(..=a).next_back() { + if e >= a { + a = s; + b = b.max(e); + early.remove(&s); + } + } + loop { + let Some((s, e)) = early.range(a..=b).next().map(|(&s, &e)| (s, e)) else { break }; + b = b.max(e); + early.remove(&s); + } + early.insert(a, b); +} + +/// Take the pages `[a, b)` out of `early`; a range that overlaps it keeps the rest. +fn early_remove(early: &mut BTreeMap<usize, usize>, a: usize, b: usize) { + if a >= b { + return; + } + if let Some((&s, &e)) = early.range(..a).next_back() { + if e > a { + early.insert(s, a); + if e > b { + early.insert(b, e); + return; + } + } + } + loop { + let Some((s, e)) = early.range(a..b).next().map(|(&s, &e)| (s, e)) else { break }; + early.remove(&s); + if e > b { + early.insert(b, e); + break; + } + } +} +/// generation counter incremented whenever the set of mapped tiles changes (for watch_ranges cache) +static MAPPED_GEN: AtomicU64 = AtomicU64::new(0); + +/// Generation counter of `mapped_ranges()` (changes only when tiles are mapped or unmapped). +pub fn mapped_gen() -> u64 { + MAPPED_GEN.load(Ordering::Acquire) +} + +fn buffer_desc(bytes: u64) -> D3D12_RESOURCE_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, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + } +} + +/// The sparse windows' buffers on `dev`: `(window_index, buffer_raw, gpu_va)` for each +/// sparse window in `gpu::uma` (empty: no sparse windows). +pub unsafe fn init(dev: &ID3D12Device) -> Vec<(usize, usize, u64)> { + let Some(u) = crate::gpu::uma::get() else { return Vec::new() }; + let mut out = Vec::new(); + let mut windows = Vec::new(); + for k in 0..u.shader_windows() { + if !u.is_sparse_window(k) { + continue; + } + let (base, size) = u.window(k); + let mut r: Option<ID3D12Resource> = None; + if let Err(e) = dev.CreateReservedResource(&buffer_desc(size as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut r) { + crate::xlog_warn!("sparse window {k}: CreateReservedResource: {e}"); + return Vec::new(); + } + let Some(r) = r else { return Vec::new() }; + out.push((k, r.clone().into_raw() as usize, r.GetGPUVirtualAddress())); + windows.push((base, r)); + } + if out.is_empty() { + return out; + } + let made = (|| -> windows::core::Result<State> { + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default())?; + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let rb_fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; + let event = windows::Win32::System::Threading::CreateEventW(None, false, false, None)?; + let mut slots = Vec::with_capacity(UPLOAD_SLOTS); + for _ in 0..UPLOAD_SLOTS { + let alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None)?; + list.Close()?; + let _ = list.SetName(windows::core::w!("xcl sparse upload list")); + let _ = alloc.SetName(windows::core::w!("xcl sparse upload allocator")); + slots.push(UploadSlot { alloc, list, fence_val: 0 }); + } + let rb_alloc: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None)?; + rb_list.Close()?; + let _ = rb_list.SetName(windows::core::w!("xcl sparse readback list")); + let _ = rb_alloc.SetName(windows::core::w!("xcl sparse readback allocator")); + let _ = queue.SetName(windows::core::w!("xcl sparse queue")); + Ok(State { + generation: NEXT_STATE_GENERATION.fetch_add(1, Ordering::Relaxed), + mapping_epoch: 0, + dev: dev.clone(), + queue, + fence, + value: 0, + event, + rb_fence, + rb_value: 0, + windows, + pools: Vec::new(), + free: Vec::new(), + retired: Vec::new(), + mapped: FxHashMap::default(), + pinned: FxHashMap::default(), + parked: FxHashMap::default(), + quarantined: VecDeque::new(), + queue_fences: FxHashMap::default(), + buffers: FxHashMap::default(), + to_zero: Vec::new(), + staging: None, + ring_write: 0, + ring_submitted: 0, + ring_free: 0, + inflight: VecDeque::new(), + uploads_ordered: true, + zero_buf: None, + slots, + next_slot: 0, + readback: None, + rb_alloc, + rb_list, + rb_last_fence: 0, + waited: FxHashMap::default(), + runs: None, + scratch_runs: Vec::new(), + retry_pages: Vec::new(), + }) + })(); + match made { + Ok(s) => { + crate::xlog_info!("D3D12.X: {} sparse window(s) for the title's own memory (tiled buffers on video memory)", out.len()); + // a state this replaces (the windows set up again) goes after the lock: the release of + // its last buffers reaches `forget_buffer`, which takes the lock (#344) + // (the queue first: `queue()` never answers with one older than the state's) + let _placement = PLACEMENT.lock().unwrap(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.write().unwrap(); + let _uploads = UPLOAD_GATE.lock().unwrap(); + let old_queue = QUEUE.lock().unwrap().replace(s.queue.clone()); + let mut state = STATE.lock().unwrap(); + let old = state.replace(s); + let s = state.as_mut().unwrap(); + for (a, b) in std::mem::take(&mut *EARLY.lock().unwrap()) { + s.commit_range(a, b - a); + } + for (a, b) in std::mem::take(&mut *EARLY_NOT_RW.lock().unwrap()) { + mark_protection(&mut s.mapped, a, b - a, false); + } + drop(state); + if old.as_ref().is_some_and(|state| !state.uploads_ordered) { + // ExecuteCommandLists was accepted but no fence can prove when its allocator, + // staging source, or destination windows become unused. Keep that generation + // alive until process exit rather than release memory the GPU may still touch. + crate::xlog_warn!("sparse: retaining an unordered upload generation after its queue Signal failed"); + std::mem::forget(old); + } else { + drop(old); + } + drop(old_queue); + out + } + Err(e) => { + crate::xlog_warn!("sparse windows: {e}"); + Vec::new() + } + } +} + +impl State { + #[inline] + fn window_index(&self, a: usize) -> Option<usize> { + self.windows.iter().position(|(b, _)| a >= *b && a < *b + crate::gpu::uma::WINDOW) + } + + unsafe fn take_tile(&mut self) -> Option<((u32, u32), bool)> { + self.drain_quarantined(); + if self.free.is_empty() && self.flush_parked() { + self.drain_quarantined(); + } + if let Some(t) = self.free.pop() { + return Some((t, true)); + } + // a pool retired a moment ago (its last tile came free) is taken back before a new + // heap is made: freeing and allocating a tile in turn made a new pool each time, + // up to 18 GB of retired heaps in 2 s (#913). Its tiles are reused as freed tiles are + // (zeroed), so this is no less safe than reusing a tile of a pool in use. + if let Some((heap, _, _)) = self.retired.pop() { + let h = self.add_pool(heap); + return Some(((h, 0), true)); + } + let desc = D3D12_HEAP_DESC { + SizeInBytes: POOL_TILES as u64 * TILE as u64, + Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, + Alignment: 0, + Flags: D3D12_HEAP_FLAG_DENY_RT_DS_TEXTURES | D3D12_HEAP_FLAG_DENY_NON_RT_DS_TEXTURES, + }; + let mut heap: Option<ID3D12Heap> = None; + if let Err(e) = super::title_textures::own_work(|| self.dev.CreateHeap(&desc, &mut heap)) { + crate::xlog_warn!("sparse windows: no video memory for more tiles ({e})"); + return None; + } + let heap = heap?; + let h = self.add_pool(heap); + Some(((h, 0), false)) + } + + /// `heap` becomes a pool (in a given-back pool's index if there is one); its tiles but the + /// first, which the caller takes, go to the free list. + fn add_pool(&mut self, heap: ID3D12Heap) -> u32 { + let h = match self.pools.iter().position(|p| p.is_none()) { + Some(i) => { + self.pools[i] = Some(heap); + i as u32 + } + None => { + self.pools.push(Some(heap)); + self.pools.len() as u32 - 1 + } + }; + self.free.extend((1..POOL_TILES).rev().map(|t| (h, t))); + h + } + + /// Pools whose every tile is free again go (their video memory – and as much of the + /// system's commit: a retail game's homes of physical pages left 0.75 GB of pools for + /// 0.29 GB of tiles in use). Call after their tiles are unmapped and signalled. + fn retire_free_pools_with(&mut self, done: u64) { + let now = std::time::Instant::now(); + self.retired.retain(|(_, v, at)| !(done >= *v && now.duration_since(*at).as_secs() >= 2)); + if self.free.len() < POOL_TILES as usize { + return; + } + let mut count = vec![0u32; self.pools.len()]; + for &(h, _) in &self.free { + count[h as usize] += 1; + } + // (a flag a pool: a title's world load frees hundreds of pools' worth of tiles at once) + let gone: Vec<bool> = (0..count.len()).map(|h| count[h] == POOL_TILES && self.pools[h].is_some()).collect(); + if !gone.contains(&true) { + return; + } + self.free.retain(|&(h, _)| !gone[h as usize]); + for h in (0..gone.len()).filter(|&h| gone[h]) { + if let Some(heap) = self.pools[h].take() { + self.retired.push((heap, self.value, now)); + } + } + } + + fn retire_free_pools(&mut self) { + self.retire_free_pools_with(unsafe { self.fence.GetCompletedValue() }); + } + + /// Map `tiles` (tile addresses) of `res` (starting at `res_base`) onto pool tiles, + /// batched per pool heap with contiguous runs merged into single regions. + unsafe fn map_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[(usize, (u32, u32))]) { + if tiles.is_empty() { + return; + } + let mut by_heap: FxHashMap<u32, Vec<(u32, u32)>> = FxHashMap::default(); + for &(a, (h, t)) in tiles { + by_heap.entry(h).or_default().push((((a - res_base) / TILE) as u32, t)); + } + for (h, mut pairs) in by_heap { + pairs.sort_unstable_by_key(|&(x, _)| x); + let mut coords: Vec<D3D12_TILED_RESOURCE_COORDINATE> = Vec::with_capacity(pairs.len()); + let mut regions: Vec<D3D12_TILE_REGION_SIZE> = Vec::with_capacity(pairs.len()); + let mut flags: Vec<D3D12_TILE_RANGE_FLAGS> = Vec::with_capacity(pairs.len()); + let mut offsets: Vec<u32> = Vec::with_capacity(pairs.len()); + let mut counts: Vec<u32> = Vec::with_capacity(pairs.len()); + let mut i = 0; + while i < pairs.len() { + let (x0, t0) = pairs[i]; + let mut run = 1u32; + while i + (run as usize) < pairs.len() { + let (nx, nt) = pairs[i + run as usize]; + if nx == x0 + run && nt == t0 + run { + run += 1; + } else { + break; + } + } + coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); + regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); + flags.push(D3D12_TILE_RANGE_FLAG_NONE); + offsets.push(t0); + counts.push(run); + i += run as usize; + } + self.queue.UpdateTileMappings( + res, + coords.len() as u32, + Some(coords.as_ptr()), + Some(regions.as_ptr()), + self.pools[h as usize].as_ref().expect("a pool tile of a live pool"), + flags.len() as u32, + Some(flags.as_ptr()), + Some(offsets.as_ptr()), + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + } + + unsafe fn unmap_tiles(&self, res: &ID3D12Resource, res_base: usize, tiles: &[usize]) { + if tiles.is_empty() { + return; + } + let mut xs: Vec<u32> = tiles.iter().map(|&a| ((a - res_base) / TILE) as u32).collect(); + xs.sort_unstable(); + let mut coords: Vec<D3D12_TILED_RESOURCE_COORDINATE> = Vec::with_capacity(xs.len()); + let mut regions: Vec<D3D12_TILE_REGION_SIZE> = Vec::with_capacity(xs.len()); + let mut flags: Vec<D3D12_TILE_RANGE_FLAGS> = Vec::with_capacity(xs.len()); + let mut counts: Vec<u32> = Vec::with_capacity(xs.len()); + let mut i = 0; + while i < xs.len() { + let x0 = xs[i]; + let mut run = 1u32; + while i + (run as usize) < xs.len() && xs[i + run as usize] == x0 + run { + run += 1; + } + coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); + regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); + flags.push(D3D12_TILE_RANGE_FLAG_NULL); + counts.push(run); + i += run as usize; + } + self.queue.UpdateTileMappings( + res, + coords.len() as u32, + Some(coords.as_ptr()), + Some(regions.as_ptr()), + None, + flags.len() as u32, + Some(flags.as_ptr()), + None, + Some(counts.as_ptr()), + D3D12_TILE_MAPPING_FLAG_NONE, + ); + } + + /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_state` supplies + /// the initial `(holes, untrusted protection)` masks for each newly mapped 64 KiB tile. + unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_state: impl FnMut(usize) -> (u16, u16)) { + if n == 0 { + return; + } + let first = a & !(TILE - 1); + let end = a.saturating_add(n); + let mut new: Vec<(usize, (u32, u32))> = Vec::new(); + let mut unparked = false; + let mut t = first; + while t < end { + if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { + // still mapped there: no new mapping, what it held is cleared + if let Some(tile) = self.parked.remove(&t) { + let (holes, not_rw) = initial_state(t); + let mut entry = TileEntry::with_holes(tile, holes); + entry.not_rw = not_rw; + self.mapped.insert(t, entry); + self.runs = None; + self.to_zero.push((t, TILE)); + unparked = true; + } else { + let Some((tile, reused)) = self.take_tile() else { break }; + let (holes, not_rw) = initial_state(t); + let mut entry = TileEntry::with_holes(tile, holes); + entry.not_rw = not_rw; + self.mapped.insert(t, entry); + self.runs = None; + if reused { + self.to_zero.push((t, TILE)); + } + new.push((t, tile)); + } + } + match t.checked_add(TILE) { + Some(next) => t = next, + None => break, + } + } + if new.is_empty() { + if unparked { + MAPPED_GEN.fetch_add(1, Ordering::Release); + } + return; + } + MAPPED_GEN.fetch_add(1, Ordering::Release); + // per window + let mut by_window: FxHashMap<usize, Vec<(usize, (u32, u32))>> = FxHashMap::default(); + for x in new { + if let Some(wi) = self.window_index(x.0) { + by_window.entry(wi).or_default().push(x); + } + } + for (wi, tiles) in by_window { + let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); + self.map_tiles(&r, b, &tiles); + } + self.signal(); + } + + #[inline] + unsafe fn signal(&mut self) { + self.value += 1; + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + } + + #[inline] + unsafe fn wait_for(&self, target: u64) -> bool { + self.wait_for_ms(target, 5000) + } + + unsafe fn wait_for_ms(&self, target: u64, timeout_ms: u32) -> bool { + if target == 0 || self.fence.GetCompletedValue() >= target { + return true; + } + let _ = self.fence.SetEventOnCompletion(target, self.event); + let wait_stall = crate::stall::span(crate::stall::StallKind::GpuWait); + windows::Win32::System::Threading::WaitForSingleObject(self.event, timeout_ms); + drop(wait_stall); + if self.fence.GetCompletedValue() < target { + crate::xlog_warn!("sparse: the queue has not reached fence value {target} after {timeout_ms} ms (at {})", self.fence.GetCompletedValue()); + return false; + } + true + } + + #[inline] + unsafe fn reclaim_ring(&mut self) { + if self.inflight.is_empty() { return; } - let mut xs: Vec<u32> = tiles.iter().map(|&a| ((a - res_base) / TILE) as u32).collect(); - xs.sort_unstable(); - let mut coords: Vec<D3D12_TILED_RESOURCE_COORDINATE> = Vec::with_capacity(xs.len()); - let mut regions: Vec<D3D12_TILE_REGION_SIZE> = Vec::with_capacity(xs.len()); - let mut flags: Vec<D3D12_TILE_RANGE_FLAGS> = Vec::with_capacity(xs.len()); - let mut counts: Vec<u32> = Vec::with_capacity(xs.len()); - let mut i = 0; - while i < xs.len() { - let x0 = xs[i]; - let mut run = 1u32; - while i + (run as usize) < xs.len() && xs[i + run as usize] == x0 + run { - run += 1; + let completed = self.fence.GetCompletedValue(); + while let Some(&(fv, end_pos)) = self.inflight.front() { + if fv <= completed { + self.ring_free = end_pos; + self.inflight.pop_front(); + } else { + break; + } + } + } + + /// Acquire the next upload command slot, or return a ticket to wait for without `STATE`. + unsafe fn begin_slot(&mut self) -> BeginSlot { + let next_slot = self.next_slot; + let completed = self.fence.GetCompletedValue(); + let mut waiting = None; + let mut ready = None; + for offset in 0..self.slots.len() { + let idx = (next_slot + offset) % self.slots.len(); + let fv = self.slots[idx].fence_val; + if fv == 0 || fv <= completed { + ready = Some(idx); + break; + } + if waiting.is_none_or(|(_, earliest)| fv < earliest) { + waiting = Some((idx, fv)); + } + } + let Some(idx) = ready else { + let (idx, fv) = waiting.expect("sparse upload slots are not empty"); + return BeginSlot::Wait(self.wait_ticket(fv, WaitKind::Slot { index: idx, next_slot, fence: fv })); + }; + let slot = &self.slots[idx]; + if slot.alloc.Reset().is_err() || slot.list.Reset(&slot.alloc, None).is_err() { + return BeginSlot::RetryRequired; + } + self.next_slot = (idx + 1) % self.slots.len(); + BeginSlot::Ready(idx) + } + + fn wait_ticket(&self, target: u64, kind: WaitKind) -> WaitTicket { + WaitTicket { + state_generation: self.generation, + mapping_epoch: self.mapping_epoch, + dev: self.dev.clone(), + fence: self.fence.clone(), + target, + kind, + } + } + + fn wait_ticket_owns_upload(&self, ticket: &WaitTicket) -> bool { + if !self.wait_ticket_generation(ticket) { + return false; + } + match ticket.kind { + WaitKind::Slot { index, next_slot, fence } => { + self.next_slot == next_slot && self.slots.get(index).is_some_and(|slot| slot.fence_val == fence) + } + WaitKind::Ring { front, write, submitted, free } => { + self.inflight.front().copied() == Some(front) + && self.ring_write == write && self.ring_submitted == submitted && self.ring_free == free + } + } + } + + fn wait_ticket_generation(&self, ticket: &WaitTicket) -> bool { + self.generation == ticket.state_generation + && self.fence.as_raw() == ticket.fence.as_raw() + && self.uploads_ordered + } + + fn wait_ticket_valid(&self, ticket: &WaitTicket) -> bool { + self.mapping_epoch == ticket.mapping_epoch && self.wait_ticket_owns_upload(ticket) + } + + /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work + /// via `queue.Wait(&self.fence, self.value)`). + unsafe fn submit_slot(&mut self, idx: usize) -> SubmitResult { + if self.slots[idx].list.Close().is_err() { + return SubmitResult::NotSubmitted; + } + let Ok(l) = self.slots[idx].list.cast::<ID3D12CommandList>() else { + return SubmitResult::NotSubmitted; + }; + super::title_textures::own_work(|| { + super::real::native_queue_execute(&self.queue, &l); + }); + let value = self.value + 1; + if super::real::native_queue_signal(&self.queue, &self.fence, value).is_err() { + self.uploads_ordered = false; + self.slots[idx].fence_val = u64::MAX; + return SubmitResult::Unordered; + } + self.value = value; + self.slots[idx].fence_val = value; + if self.ring_write > self.ring_submitted { + self.inflight.push_back((value, self.ring_write)); + self.ring_submitted = self.ring_write; + } + SubmitResult::Submitted + } + + unsafe fn staging_ptr(&mut self) -> Option<*mut u8> { + if self.staging.is_none() { + let mut r: Option<ID3D12Resource> = None; + let mut d = buffer_desc(STAGING as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + self.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &d, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut r, + ) + .ok()?; + let r = r?; + let mut p = std::ptr::null_mut(); + r.Map(0, None, Some(&mut p)).ok()?; + self.staging = Some((r, p as *mut u8)); + } + self.staging.as_ref().map(|&(_, p)| p) + } + + unsafe fn ensure_zero_buf(&mut self) -> bool { + if self.zero_buf.is_none() { + let mut r: Option<ID3D12Resource> = None; + let mut d = buffer_desc(ZERO_BUF as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + if self + .dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &d, + D3D12_RESOURCE_STATE_GENERIC_READ, + None, + &mut r, + ) + .is_err() + { + return false; + } + let Some(r) = r else { return false }; + let mut p = std::ptr::null_mut(); + if r.Map(0, None, Some(&mut p)).is_err() { + return false; + } + std::ptr::write_bytes(p as *mut u8, 0, ZERO_BUF); + r.Unmap(0, None); + self.zero_buf = Some(r); + } + true + } + + unsafe fn readback_buf(&mut self) -> Option<(ID3D12Resource, *mut u8)> { + if self.readback.is_none() { + let mut r: Option<ID3D12Resource> = None; + let mut d = buffer_desc(READBACK_STAGING as u64); + d.Flags = D3D12_RESOURCE_FLAG_NONE; + self.dev + .CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &d, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut r, + ) + .ok()?; + let r = r?; + let mut p = std::ptr::null_mut(); + r.Map(0, None, Some(&mut p)).ok()?; + self.readback = Some((r, p as *mut u8)); + } + self.readback.clone() + } + + /// Clear `sent` hashes for every page overlapping `[a, a + n)`. + fn clear_sent_range(&mut self, a: usize, n: usize) { + let mut pg = a & !(PAGE - 1); + let end = a + n; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = self.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + entry.sent[(p - t) / PAGE] = None; + p += PAGE; + } + } + pg = tile_end; + } + } + + fn publish_hashes(&mut self, updates: &[HashUpdate]) { + publish_hash_updates(&mut self.mapped, updates); + } + + /// Submit one exact dirty batch. Until submission succeeds its ring bytes and hash plan are + /// provisional; a close/cast failure rolls the ring cursor back to this batch's start. + unsafe fn submit_dirty_batch( + &mut self, + mut batch: PreparedDirtyBatch, + reclaim: bool, + ) -> Result<PreparedDirtyBatch, PreparationOutcome> { + match self.submit_slot(batch.slot) { + SubmitResult::Submitted => { + self.publish_hashes(&batch.updates); + batch.clear_after_submit(); + if reclaim { + self.reclaim_ring(); + } + Ok(batch) + } + SubmitResult::NotSubmitted => { + self.ring_write = batch.ring_start; + Err(PreparationOutcome::RetryRequired) + } + SubmitResult::Unordered => Err(PreparationOutcome::ExecutedUntracked), + } + } + + /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh + /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. + unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { + let Some((rb, p)) = self.readback_buf() else { return }; + let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) + let mut used = 0usize; + let mut open = false; + let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| -> bool { + if *open { + *open = false; + let Ok(()) = s.rb_list.Close() else { return false }; + let Ok(l) = s.rb_list.cast::<ID3D12CommandList>() else { return false }; + super::title_textures::own_work(|| { + super::real::native_queue_execute(&s.queue, &l); + }); + s.signal(); + s.rb_last_fence = s.value; + if !s.wait_for(s.value) { + pending.clear(); + *used = 0; + return false; + } + s.reclaim_ring(); + } + for &(dst, off, len) in pending.iter() { + // copy only committed (non-hole) bytes + let mut at = dst; + let mut src_off = off; + let end = dst + len; + while at < end { + let pg = at & !(PAGE - 1); + let t = pg & !(TILE - 1); + let idx = (pg - t) / PAGE; + let step = (pg + PAGE).min(end) - at; + if let Some(entry) = s.mapped.get_mut(&t) { + if entry.holes & (1u16 << idx) == 0 { + let page = std::slice::from_raw_parts_mut(pg as *mut u8, PAGE); + let source = std::slice::from_raw_parts(p.add(src_off), step); + land_page(&mut entry.sent[idx], page, at - pg, source); + } + } + at += step; + src_off += step; + } + } + pending.clear(); + *used = 0; + true + }; + for &(a, n) in ranges { + if n == 0 { + continue; + } + let mut done = 0usize; + while done < n { + let cur = a + done; + let tile = cur & !(TILE - 1); + let Some(wi) = self.window_index(cur) else { break }; + let b = self.windows[wi].0; + let to_tile_end = (tile + TILE) - cur; + if !self.mapped.contains_key(&tile) { + done += (n - done).min(to_tile_end); + continue; + } + if used == READBACK_STAGING { + if !flush_and_copy(self, &mut open, &mut pending, &mut used, p) { + return; + } + } + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); + if !open { + if !self.wait_for(self.rb_last_fence) || self.rb_alloc.Reset().is_err() || self.rb_list.Reset(&self.rb_alloc, None).is_err() { + return; + } + open = true; + } + self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); + pending.push((cur, used, chunk)); + used += chunk; + done += chunk; + } + } + if open { + let _ = flush_and_copy(self, &mut open, &mut pending, &mut used, p); + } + } + + /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` + /// (zero staging ring bytes consumed, zero CPU stall). + unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) -> UploadStep { + if runs.is_empty() { + return UploadStep::Done(PreparationOutcome::Ready); + } + if !self.uploads_ordered { + return UploadStep::Done(PreparationOutcome::ExecutedUntracked); + } + if !self.ensure_zero_buf() { + return UploadStep::Done(PreparationOutcome::RetryRequired); + } + let slot_idx = match self.begin_slot() { + BeginSlot::Ready(index) => index, + BeginSlot::Wait(ticket) => return UploadStep::Wait(ticket), + BeginSlot::RetryRequired => return UploadStep::Done(PreparationOutcome::RetryRequired), + }; + let mut last_wi: Option<usize> = None; + let zero_buf = self.zero_buf.as_ref().unwrap(); + let list = &self.slots[slot_idx].list; + for &(a, n) in runs { + let mut done = 0usize; + while done < n { + let cur = a + done; + let wi = match last_wi { + Some(i) if cur >= self.windows[i].0 && cur < self.windows[i].0 + crate::gpu::uma::WINDOW => i, + _ => match self.window_index(cur) { + Some(i) => { + last_wi = Some(i); + i + } + None => break, + }, + }; + let b = self.windows[wi].0; + let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; + let chunk = (n - done).min(ZERO_BUF).min(to_win_end); + list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, zero_buf, 0, chunk as u64); + done += chunk; } - coords.push(D3D12_TILED_RESOURCE_COORDINATE { X: x0, ..Default::default() }); - regions.push(D3D12_TILE_REGION_SIZE { NumTiles: run, UseBox: false.into(), ..Default::default() }); - flags.push(D3D12_TILE_RANGE_FLAG_NULL); - counts.push(run); - i += run as usize; } - self.queue.UpdateTileMappings( - res, - coords.len() as u32, - Some(coords.as_ptr()), - Some(regions.as_ptr()), - None, - flags.len() as u32, - Some(flags.as_ptr()), - None, - Some(counts.as_ptr()), - D3D12_TILE_MAPPING_FLAG_NONE, - ); + UploadStep::Done(self.submit_slot(slot_idx).into()) + } + + /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via + /// the 64 MiB ring staging buffer (zero CPU stall on the common path). + unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) -> UploadStep { + self.upload_dirty_with_timeout(runs, 5000) + } + + unsafe fn upload_dirty_with_timeout(&mut self, runs: &[(usize, usize)], _wait_ms: u32) -> UploadStep { + if runs.is_empty() { + return UploadStep::Done(PreparationOutcome::Ready); + } + if !self.uploads_ordered { + return UploadStep::Done(PreparationOutcome::ExecutedUntracked); + } + let Some(p) = self.staging_ptr() else { + return UploadStep::Done(PreparationOutcome::RetryRequired); + }; + let mut batch: Option<PreparedDirtyBatch> = None; + let mut recycled_batch: Option<PreparedDirtyBatch> = None; + let mut last_wi: Option<usize> = None; + for &(a, n) in runs { + let mut done = 0usize; + while done < n { + let cur = a + done; + let wi = match last_wi { + Some(i) if cur >= self.windows[i].0 && cur < self.windows[i].0 + crate::gpu::uma::WINDOW => i, + _ => match self.window_index(cur) { + Some(i) => { + last_wi = Some(i); + i + } + None => { + if let Some(batch) = batch { + self.ring_write = batch.ring_start; + } + return UploadStep::Done(PreparationOutcome::RetryRequired); + } + }, + }; + let b = self.windows[wi].0; + let copy = prepare_dirty_copy( + cur, + n - done, + b, + crate::gpu::uma::WINDOW, + self.ring_write, + STAGING, + ); + if (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { + self.reclaim_ring(); + if (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { + if let Some(ready) = batch.take() { + match self.submit_dirty_batch(ready, true) { + Ok(recycled) => recycled_batch = Some(recycled), + Err(outcome) => return UploadStep::Done(outcome), + } + } + while (copy.ring_start + copy.bytes as u64).saturating_sub(self.ring_free) > STAGING as u64 { + let Some(&(fv, _)) = self.inflight.front() else { + crate::xlog_warn!("sparse: the staging ring is full without a retirement fence; the unsubmitted CPU writes will be retried"); + return UploadStep::Done(PreparationOutcome::RetryRequired); + }; + return UploadStep::Wait(self.wait_ticket( + fv, + WaitKind::Ring { + front: *self.inflight.front().unwrap(), + write: self.ring_write, + submitted: self.ring_submitted, + free: self.ring_free, + }, + )); + } + } + } + if batch.as_ref().is_some_and(|batch| batch.hash_plan_would_overflow(copy.bytes)) { + match self.submit_dirty_batch(batch.take().unwrap(), true) { + Ok(recycled) => recycled_batch = Some(recycled), + Err(outcome) => return UploadStep::Done(outcome), + } + } + let slot_idx = match batch.as_ref() { + Some(batch) => batch.slot, + None => { + let idx = match self.begin_slot() { + BeginSlot::Ready(index) => index, + BeginSlot::Wait(ticket) => return UploadStep::Wait(ticket), + BeginSlot::RetryRequired => return UploadStep::Done(PreparationOutcome::RetryRequired), + }; + batch = Some(match recycled_batch.take() { + Some(recycled) => recycled.reopen(idx, self.ring_write), + None => PreparedDirtyBatch::new(idx, self.ring_write), + }); + idx + } + }; + std::ptr::copy_nonoverlapping(cur as *const u8, p.add(copy.staging_offset), copy.bytes); + batch.as_mut().unwrap().append_hashes( + cur, + std::slice::from_raw_parts(p.add(copy.staging_offset), copy.bytes), + ); + let staging_res = &self.staging.as_ref().unwrap().0; + self.slots[slot_idx].list.CopyBufferRegion( + &self.windows[wi].1, + copy.window_offset as u64, + staging_res, + copy.staging_offset as u64, + copy.bytes as u64, + ); + self.ring_write = copy.ring_start + copy.bytes as u64; + done += copy.bytes; + } + } + if let Some(batch) = batch { + if let Err(outcome) = self.submit_dirty_batch(batch, false) { + return UploadStep::Done(outcome); + } + } + UploadStep::Done(PreparationOutcome::Ready) + } +} + +/// Allocate a zeroed, write-watched block in the sparse VRAM windows (never straddling a +/// 4 GiB window boundary when `size <= 4 GiB`). Commits the CPU pages and maps VRAM tiles +/// (or queues them until the D3D12 device exists). Returns `(address, rounded_size)`. +pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc(size, align)?; + if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { + u.sparse_release(addr); + return None; + } + committed(addr, rounded); + Some((addr, rounded)) +} + +/// Allocate a zeroed, write-watched block strictly inside sparse window `window` (e.g. +/// window 0 for 32-bit-addressed descriptor heaps). Returns `(address, rounded_size)`. +pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usize, usize)> { + let u = crate::gpu::uma::get()?; + let (addr, rounded) = u.sparse_alloc_in(window, size, align)?; + if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { + u.sparse_release(addr); + return None; + } + committed(addr, rounded); + Some((addr, rounded)) +} + +/// Release a sparse allocation from `alloc` / `alloc_in` (false: not a sparse allocation). +pub unsafe fn free(p: usize) -> bool { + let Some(u) = crate::gpu::uma::get() else { return false }; + if !u.is_sparse(p) { + return false; + } + // decommitted before the address goes back: once released, another thread may get it, + // commit it and write there + let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; + decommitted(start, len); + VirtualFree(p as *mut c_void, len, MEM_DECOMMIT); + u.sparse_release(p).is_some() +} + +/// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, +/// `FillMemoryWith32BitValueX`, `CopyMemoryToMemoryX`) back to their CPU view so CPU reads +/// and spin-waits see the GPU writes without clobbering `sent` hashes. +/// The queue tile mappings go out on, once there is one. Answered without `STATE` (`QUEUE`): +/// a caller may be inside a D3D12 call that a holder of `STATE` waits for. +pub fn queue() -> Option<ID3D12CommandQueue> { + QUEUE.lock().unwrap().clone() +} + +pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { + if ranges.is_empty() { + return; + } + let measure = super::memory_report::enabled(); + let (mut uploads, timing) = UploadGateTiming::acquire(measure); + readback_after_execute_locked(queue, ranges); + let times = timing.finish(); + drop(uploads.take()); + if measure { + note_readback_gate(times); + } +} + +unsafe fn readback_after_execute_locked(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); + if filtered.is_empty() { + return; + } + filtered.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); + for (a, n) in filtered { + match merged.last_mut() { + Some(last) if a <= last.0.saturating_add(last.1) => { + let end = (last.0 + last.1).max(a + n); + last.1 = end - last.0; + } + _ => merged.push((a, n)), + } + } + s.rb_value += 1; + let v = s.rb_value; + if super::real::native_queue_signal(queue, &s.rb_fence, v).is_ok() { + let _ = super::real::native_queue_wait(&s.queue, &s.rb_fence, v); + super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + } + s.readback_ranges(&merged); +} + +/// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with +/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending +/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then +/// copies the range back from VRAM into CPU memory. +pub unsafe fn readback_now(va: usize, len: usize) { + if len == 0 { + return; + } + let measure = super::memory_report::enabled(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (mut uploads, mut timing) = UploadGateTiming::acquire(measure); + readback_now_locked(va, len, &mut uploads, &mut timing); + let times = timing.finish(); + drop(uploads.take()); + drop(_upload_lifetime); + if measure { + note_readback_gate(times); + } +} + +unsafe fn readback_now_locked( + va: usize, len: usize, uploads: &mut Option<UploadGuard>, timing: &mut UploadGateTiming, +) { + 'prepare: loop { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return }; + if s.window_index(va).is_none() { + return; + } + let zeroed = std::mem::take(&mut s.to_zero); + if !zeroed.is_empty() { + for &(a, n) in &zeroed { + s.clear_sent_range(a, n); + } + match s.upload_zeros(&zeroed) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + // Publish the clear retry journal before another uploader can take the gate. It + // may consume it while this thread waits; after reacquiring, restart from state. + s.to_zero.extend(zeroed); + drop(g); + if !timing.with_released(uploads, || wait_upload_released(ticket)) { return } + continue 'prepare; + } + UploadStep::Done(_) => { + s.to_zero.extend(zeroed); + return; + } + } + } + // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` + let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); + let mut pg = va & !(PAGE - 1); + let end = va + len; + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = (t + TILE).min(end); + if let Some(entry) = s.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + let idx = (p - t) / PAGE; + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); + scan_page(bytes, p, &entry.sent[idx], &mut dirty_runs); + } + p += PAGE; + } + } + pg = tile_end; + } + if !dirty_runs.is_empty() { + match s.upload_dirty(&dirty_runs) { + UploadStep::Done(PreparationOutcome::Ready) => {} + UploadStep::Wait(ticket) => { + // Dirty bytes were only observed, not removed from a journal. Another uploader + // may send them while this thread waits; restart and rescan current hashes. + drop(g); + if !timing.with_released(uploads, || wait_upload_released(ticket)) { return } + continue 'prepare; + } + UploadStep::Done(_) => return, + } } + s.readback_ranges(&[(va, len)]); + return; + } +} - /// tiles of `[a, a + n)` get video memory (mapped in their window); `initial_holes` supplies - /// the initial 16-bit hole mask for each newly mapped 64 KiB tile. - unsafe fn ensure_mapped(&mut self, a: usize, n: usize, mut initial_holes: impl FnMut(usize) -> u16) { - if n == 0 { - return; +/// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that +/// lie outside the range are not committed (holes); the range's pages are. +pub unsafe fn committed(a: usize, n: usize) { + committed_with_protection(a, n, true); +} + +/// `committed`, recording the protection established by the same successful commit without an +/// interval in which an affirmative writability query can observe the new page incorrectly. +pub unsafe fn committed_with_protection(a: usize, n: usize, writable: bool) { + if n == 0 { + return; + } + let mut g = lock_state(); + let Some(s) = g.as_mut() else { + let (start, end) = page_span(a, n); + early_add(&mut EARLY.lock().unwrap(), start, end); + if writable { + early_remove(&mut EARLY_NOT_RW.lock().unwrap(), start, end); + } else { + early_add(&mut EARLY_NOT_RW.lock().unwrap(), start, end); } - let first = a & !(TILE - 1); + return; + }; + s.commit_range_with_protection(a, n, writable); +} + +/// The title decommitted `[a, a + n)`: tiles whose pages are all uncommitted (whether in one +/// full-tile decommit or incrementally via sub-tile decommits) give their video memory back +/// (unless a placed buffer still pins the pool tile). +pub unsafe fn decommitted(a: usize, n: usize) { + if n == 0 { + return; + } + let mut g = lock_state(); + let Some(s) = g.as_mut() else { + let (start, end) = page_span(a, n); + early_remove(&mut EARLY.lock().unwrap(), start, end); + return; + }; + s.decommit_range(a, n); +} + +impl State { + /// `committed` with the state locked + unsafe fn commit_range(&mut self, a: usize, n: usize) { + self.commit_range_with_protection(a, n, true); + } + + unsafe fn commit_range_with_protection(&mut self, a: usize, n: usize, writable: bool) { + self.ensure_mapped(a, n, |_| (0xFFFF, 0)); + let mut pg = a & !(PAGE - 1); let end = a.saturating_add(n); - let mut new: Vec<(usize, (u32, u32))> = Vec::new(); - let mut unparked = false; - let mut t = first; - while t < end { - if !self.mapped.contains_key(&t) && self.window_index(t).is_some() { - // still mapped there: no new mapping, what it held is cleared - if let Some(tile) = self.parked.remove(&t) { - self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); - self.runs = None; - self.to_zero.push((t, TILE)); - unparked = true; - } else { - let Some((tile, reused)) = self.take_tile() else { break }; - self.mapped.insert(t, TileEntry::with_holes(tile, initial_holes(t))); - self.runs = None; - if reused { - self.to_zero.push((t, TILE)); + while pg < end { + let t = pg & !(TILE - 1); + let tile_end = t.saturating_add(TILE).min(end); + if let Some(entry) = self.mapped.get_mut(&t) { + let mut p = pg; + while p < tile_end { + let bit = 1u16 << ((p - t) / PAGE); + entry.holes &= !bit; + if writable { + entry.not_rw &= !bit; + } else { + entry.not_rw |= bit; } - new.push((t, tile)); + p += PAGE; } } + if tile_end <= pg { + break; + } + pg = tile_end; + } + self.mapping_epoch = self.mapping_epoch.wrapping_add(1); + } + + /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps + /// them and frees their pool tiles) + unsafe fn decommit_range(&mut self, a: usize, n: usize) { + let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); + let mut t = a & !(TILE - 1); + let end = a.saturating_add(n); + while t < end { + if let Some(e) = self.mapped.get(&t) { + pools.push((t, e.pool)); + } match t.checked_add(TILE) { Some(next) => t = next, None => break, } } - if new.is_empty() { - if unparked { - MAPPED_GEN.fetch_add(1, Ordering::Release); - } + let tiles = decommit_tiles(&mut self.mapped, &self.pinned, &mut Vec::new(), &mut self.to_zero, a, n); + self.mapping_epoch = self.mapping_epoch.wrapping_add(1); + if tiles.is_empty() { return; } + self.runs = None; + for &t in &tiles { + if let Ok(i) = pools.binary_search_by_key(&t, |p| p.0) { + self.parked.insert(t, pools[i].1); + } + } MAPPED_GEN.fetch_add(1, Ordering::Release); - // per window - let mut by_window: FxHashMap<usize, Vec<(usize, (u32, u32))>> = FxHashMap::default(); - for x in new { - if let Some(wi) = self.window_index(x.0) { - by_window.entry(wi).or_default().push(x); + if self.parked.len() >= PARKED_MAX && self.flush_parked() { + self.drain_quarantined(); + self.retire_free_pools(); + } + } + + /// a pool tile no window maps, none is parked on and no buffer uses goes back to the free list + fn release_if_unused(&mut self, tile: (u32, u32)) { + if !self.pinned.contains_key(&tile) + && !self.mapped.values().any(|e| e.pool == tile) + && !self.parked.values().any(|&p| p == tile) + && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) + { + self.free.push(tile); + } + } + + unsafe fn quarantine_tiles_for( + &mut self, + tiles: Vec<(u32, u32)>, + queues: &[ID3D12CommandQueue], + retiring: &[(ID3D12Fence, u64)], + blocked: bool, + ) { + if tiles.is_empty() { + return; + } + let mut marks = initial_quarantine_marks((self.fence.clone(), self.value), retiring, blocked).unwrap_or_default(); + let mut ok = !blocked; + let mut seen = Vec::with_capacity(queues.len()); + marks.reserve(queues.len()); + for q in queues.iter().filter(|_| ok) { + let key = q.as_raw() as usize; + if key == self.queue.as_raw() as usize || seen.contains(&key) { + continue; + } + let mut qdev: Option<ID3D12Device> = None; + if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { + continue; + } + seen.push(key); + let entry = match self.queue_fences.entry(key) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => match self.dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => entry.insert((fence, 0)), + Err(_) => { + ok = false; + break; + } + }, + }; + let next = entry.1 + 1; + if super::real::native_queue_signal(&q, &entry.0, next).is_ok() { + entry.1 = next; + marks.push((entry.0.clone(), next)); + } else { + ok = false; + break; } } - for (wi, tiles) in by_window { + self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); + } + + unsafe fn drain_quarantined_with(&mut self, mut completed: impl FnMut(&ID3D12Fence) -> u64) -> bool { + let mut freed = false; + while let Some(front) = self.quarantined.front() { + let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| completed(f) >= *v)); + if !ready { + break; + } + let batch = self.quarantined.pop_front().unwrap(); + for tile in batch.tiles { + if !self.pinned.contains_key(&tile) { + self.free.push(tile); + freed = true; + } + } + } + freed + } + + unsafe fn drain_quarantined(&mut self) -> bool { + self.drain_quarantined_with(|fence| fence.GetCompletedValue()) + } + + /// The parked tiles unmapped from their windows (one call per window) and their unpinned + /// pool tiles quarantined behind `self.queue` and every known title queue's completion fence. + /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless + /// they take a tile right away. + unsafe fn flush_parked(&mut self) -> bool { + self.flush_parked_with(None) + } + + unsafe fn flush_parked_with(&mut self, extra: Option<&ID3D12CommandQueue>) -> bool { + if self.parked.is_empty() { + return false; + } + let mut completion = super::present::queue_completion_snapshot(); + if let Some(queue) = extra.filter(|queue| { + super::present::queue_accepts_internal_work(queue.as_raw() as usize) + && !completion.active.iter().any(|active| active.as_raw() == queue.as_raw()) + }) { + completion.active.push(queue.clone()); + } + self.flush_parked_for(&completion.active, &completion.retiring, completion.blocked) + } + + unsafe fn flush_parked_for( + &mut self, + queues: &[ID3D12CommandQueue], + retiring: &[(ID3D12Fence, u64)], + blocked: bool, + ) -> bool { + if self.parked.is_empty() { + return false; + } + let mut by_window: FxHashMap<usize, Vec<usize>> = FxHashMap::default(); + let mut tiles: Vec<(u32, u32)> = Vec::new(); + for (t, tile) in std::mem::take(&mut self.parked) { + if let Some(wi) = self.window_index(t) { + by_window.entry(wi).or_default().push(t); + } + if !self.pinned.contains_key(&tile) { + tiles.push(tile); + } + } + for (wi, ts) in by_window { let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); - self.map_tiles(&r, b, &tiles); + self.unmap_tiles(&r, b, &ts); } + self.mapping_epoch = self.mapping_epoch.wrapping_add(1); self.signal(); + self.quarantine_tiles_for(tiles, queues, retiring, blocked); + true + } +} + +/// Whether `[p, p + n)` lies in a sparse window and every page is recorded as committed and +/// writable. False means the caller must ask Windows; this cache only supplies affirmative +/// answers, avoiding `VirtualQuery` walking a multi-gigabyte sparse reservation. +pub fn known_writable(p: usize, n: usize) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + if n == 0 || !crate::gpu::uma::get().is_some_and(|u| u.is_sparse(p) && u.is_sparse(end - 1)) { + return false; + } + { + let state = STATE.lock().unwrap(); + let Some(state) = state.as_ref() else { return false }; + if !recorded_committed(&state.mapped, p, end) { + return false; + } + } + resident_pages_writable(p, end) +} + +/// Every page touched by `[p, end)` has video-memory backing, is committed, and has not been +/// given a non-writable protection. Check one 64 KiB tile at a time while holding `STATE`. +fn recorded_committed(mapped: &FxHashMap<usize, TileEntry>, p: usize, end: usize) -> bool { + let mut tile = p & !(TILE - 1); + while tile < end { + let first = (p.max(tile) - tile) / PAGE; + let tile_end = tile.saturating_add(TILE).min(end); + let last = (tile_end - 1 - tile) / PAGE; + let pages = last - first + 1; + let mask = ((((1u32 << pages) - 1) << first) & u16::MAX as u32) as u16; + if !mapped.get(&tile).is_some_and(|entry| (entry.holes | entry.not_rw) & mask == 0) { + return false; + } + if tile_end <= tile { + return false; + } + tile = tile_end; + } + true +} + +/// Record a successful protection change in a sparse window. `writable` means a writable +/// protection without PAGE_GUARD. Before device creation, retain page ranges for `init` replay. +pub fn protection_changed(a: usize, n: usize, writable: bool) { + let Some(end) = a.checked_add(n) else { return }; + let Some(uma) = crate::gpu::uma::get() else { return }; + let mut state = STATE.lock().unwrap(); + for k in 0..uma.shader_windows() { + if !uma.is_sparse_window(k) { + continue; + } + let (base, size) = uma.window(k); + let (start, stop) = (a.max(base), end.min(base.saturating_add(size))); + if start >= stop { + continue; + } + match state.as_mut() { + Some(state) => mark_protection(&mut state.mapped, start, stop - start, writable), + None => early_protection(&mut EARLY_NOT_RW.lock().unwrap(), start, stop - start, writable), + } + } +} + +fn mark_protection(mapped: &mut FxHashMap<usize, TileEntry>, a: usize, n: usize, writable: bool) { + let end = a.saturating_add(n); + let mut tile = a & !(TILE - 1); + while tile < end { + let first = (a.max(tile) - tile) / PAGE; + let tile_end = tile.saturating_add(TILE).min(end); + let last = (tile_end - 1 - tile) / PAGE; + let pages = last - first + 1; + let mask = ((((1u32 << pages) - 1) << first) & u16::MAX as u32) as u16; + if let Some(entry) = mapped.get_mut(&tile) { + if writable { + entry.not_rw &= !mask; + } else { + entry.not_rw |= mask; + } + } + if tile_end <= tile { + break; + } + tile = tile_end; + } +} + +/// No resident page in `[p, end)` has a non-writable or guard protection. Nonresident pages are +/// judged by the protection record above; this query inspects metadata without touching pages. +fn resident_pages_writable(p: usize, end: usize) -> bool { + use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION}; + const BATCH: usize = 64; + const WRITABLE: usize = 0x04 | 0x08 | 0x40 | 0x80; + let (first, last) = (p >> 12, (end - 1) >> 12); + let mut entries: [PSAPI_WORKING_SET_EX_INFORMATION; BATCH] = unsafe { std::mem::zeroed() }; + let mut page = first; + while page <= last { + let count = (last - page + 1).min(BATCH); + for (i, entry) in entries[..count].iter_mut().enumerate() { + *entry = unsafe { std::mem::zeroed() }; + entry.VirtualAddress = ((page + i) << 12) as *mut c_void; + } + let bytes = (count * std::mem::size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32; + if unsafe { + K32QueryWorkingSetEx( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + entries.as_mut_ptr() as *mut c_void, + bytes, + ) + } == 0 + { + return false; + } + if entries[..count].iter().any(|entry| { + let flags = unsafe { entry.VirtualAttributes.Flags }; + let protection = (flags >> 4) & 0x7FF; + flags & 1 != 0 && (protection & WRITABLE == 0 || protection & PAGE_GUARD as usize != 0) + }) { + return false; + } + page += count; + } + true +} + +/// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write +/// has to reach the GPU. +pub fn mapped_ranges() -> Vec<(usize, usize)> { + let mut g = lock_state(); + let Some(s) = g.as_mut() else { return Vec::new() }; + if s.runs.is_none() { + let mut tiles: Vec<usize> = s.mapped.keys().copied().collect(); + tiles.sort_unstable(); + let mut runs: Vec<(usize, usize)> = Vec::new(); + for t in tiles { + match runs.last_mut() { + Some(last) if last.1 == t => last.1 = t + TILE, + _ => runs.push((t, t + TILE)), + } + } + s.runs = Some(runs); + } + s.runs.clone().unwrap_or_default() +} + +const LOOK_FIELDS: usize = 19; +const ACTIVE_US: usize = 0; +const REFRESH_WAIT_US: usize = 1; +const WATCH_US: usize = 2; +const PAGES: usize = 3; +const LOOKS: usize = 4; +const WATCHED: usize = 5; +const RANGES: usize = 6; +const QUEUE_WAIT_US: usize = 7; +const MAINTENANCE_US: usize = 8; +const SCAN_US: usize = 9; +const UPLOAD_US: usize = 10; +const RUNS: usize = 11; +const TRANSFER_BYTES: usize = 12; +const UPLOAD_WAIT_US: usize = 13; +const SUBMIT_GATE_WAIT_US: usize = 14; +const SUBMIT_GATE_HOLD_US: usize = 15; +const READBACK_GATE_WAIT_US: usize = 16; +const READBACK_GATE_HOLD_US: usize = 17; +const READBACK_GATE_RELEASED_US: usize = 18; + +/// One complete `XCL_ACTIVITY` look. It is built without shared updates, then published once so +/// the reporting thread cannot split one look across adjacent intervals. +#[derive(Default)] +pub(super) struct LookSample([u64; LOOK_FIELDS]); + +impl LookSample { + pub(super) fn add(&mut self, field: usize, value: u64) { + self.0[field] = self.0[field].wrapping_add(value); } - #[inline] - unsafe fn signal(&mut self) { - self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + pub(super) fn add_time(&mut self, field: usize, value: std::time::Duration) { + self.add(field, value.as_micros() as u64); } +} - #[inline] - unsafe fn wait_for(&self, target: u64) { - if target == 0 || self.fence.GetCompletedValue() >= target { - return; - } - let _ = self.fence.SetEventOnCompletion(target, self.event); - windows::Win32::System::Threading::WaitForSingleObject(self.event, 5000); - if self.fence.GetCompletedValue() < target { - crate::xlog_warn!("sparse: the queue has not reached fence value {target} after 5 s (at {})", self.fence.GetCompletedValue()); - } +/// Cumulative complete looks. Disabled title submission never locks or updates this mutex. +static LOOK: Mutex<[u64; LOOK_FIELDS]> = Mutex::new([0; LOOK_FIELDS]); + +fn merge_look(total: &mut [u64; LOOK_FIELDS], sample: [u64; LOOK_FIELDS]) { + for (total, value) in total.iter_mut().zip(sample) { + *total = total.wrapping_add(value); } +} - #[inline] - unsafe fn reclaim_ring(&mut self) { - if self.inflight.is_empty() { - return; - } - let completed = self.fence.GetCompletedValue(); - while let Some(&(fv, end_pos)) = self.inflight.front() { - if fv <= completed { - self.ring_free = end_pos; - self.inflight.pop_front(); - } else { - break; - } - } +fn add_gate_times(sample: &mut [u64; LOOK_FIELDS], wait: usize, hold: usize, released: Option<usize>, times: UploadGateTimes) { + sample[wait] = sample[wait].wrapping_add(times.wait_us); + sample[hold] = sample[hold].wrapping_add(times.hold_us); + if let Some(released) = released { + sample[released] = sample[released].wrapping_add(times.released_us); } +} - /// Acquire the next upload command slot, waiting only if that slot's previous submission is - /// still executing on the GPU, then reset its allocator and list. - unsafe fn begin_slot(&mut self) -> usize { - let idx = self.next_slot; - self.next_slot = (self.next_slot + 1) % self.slots.len(); - let fv = self.slots[idx].fence_val; - if fv > 0 && self.fence.GetCompletedValue() < fv { - self.wait_for(fv); - self.reclaim_ring(); - } - let slot = &self.slots[idx]; - let _ = slot.alloc.Reset(); - let _ = slot.list.Reset(&slot.alloc, None); - idx +fn note_readback_gate(times: UploadGateTimes) { + let mut total = LOOK.lock().unwrap(); + add_gate_times( + &mut total, READBACK_GATE_WAIT_US, READBACK_GATE_HOLD_US, Some(READBACK_GATE_RELEASED_US), times, + ); +} + +pub(super) fn note_watch(sample: &mut LookSample, t: std::time::Duration, pages: usize, watched: usize, ranges: usize) { + sample.add_time(WATCH_US, t); + sample.add(PAGES, pages as u64); + sample.add(WATCHED, watched as u64); + sample.add(RANGES, ranges as u64); +} + +pub(super) fn note_look(mut sample: LookSample, active: std::time::Duration, refresh_wait: std::time::Duration) { + sample.add_time(ACTIVE_US, active); + sample.add_time(REFRESH_WAIT_US, refresh_wait); + sample.add(LOOKS, 1); + let mut total = LOOK.lock().unwrap(); + merge_look(&mut total, sample.0); +} + +pub fn look_counters() -> [u64; LOOK_FIELDS] { + *LOOK.lock().unwrap() +} + +pub fn look_delta(now: [u64; LOOK_FIELDS], before: [u64; LOOK_FIELDS]) -> [u64; LOOK_FIELDS] { + std::array::from_fn(|i| now[i].wrapping_sub(before[i])) +} + +/// Active foreground elapsed time and serialization wait before title submits in one interval. +pub fn look_line(d: [u64; LOOK_FIELDS], secs: u64) -> String { + let [ + active, refresh_wait, watch, pages, looks, watched, ranges, queue_wait, maintenance, scan, upload, + runs, transfer_bytes, upload_wait, submit_gate_wait, submit_gate_hold, readback_gate_wait, + readback_gate_hold, readback_gate_released, + ] = d; + let ms = |us: u64| us / 1000; + let sparse = queue_wait.saturating_add(maintenance).saturating_add(scan).saturating_add(upload).saturating_add(upload_wait); + format!( + "looks before submits ({secs} s): {looks} looks did {} ms active work ({:.1} % of the time) after {} ms waiting for the refresh turn: write-watch {} ms ({:.1} MB in {:.1} ranges/look, {pages} pages written); sparse queue wait/fence+state/scan/upload/ownership wait {}/{}/{}/{}/{} ms ({runs} runs, {:.1} MB zero/dirty bytes); upload gate submit wait/hold {}/{} ms, readback wait/hold/released wait+reacquire {}/{}/{} ms; other active work {} ms", + ms(active), + active as f64 / (secs.max(1) * 10_000) as f64, + ms(refresh_wait), + ms(watch), + watched as f64 / looks.max(1) as f64 / (1 << 20) as f64, + ranges as f64 / looks.max(1) as f64, + ms(queue_wait), + ms(maintenance), + ms(scan), + ms(upload), + ms(upload_wait), + transfer_bytes as f64 / (1 << 20) as f64, + ms(submit_gate_wait), + ms(submit_gate_hold), + ms(readback_gate_wait), + ms(readback_gate_hold), + ms(readback_gate_released), + ms(active.saturating_sub(watch.saturating_add(sparse))) + ) +} + +fn poll_unique<F>(mut fences: Vec<F>, key: impl Fn(&F) -> usize, mut completed: impl FnMut(&F) -> u64) -> Vec<(F, u64)> { + fences.sort_unstable_by_key(&key); + fences.dedup_by(|a, b| key(a) == key(b)); + fences.into_iter().map(|fence| { + let value = completed(&fence); + (fence, value) + }).collect() +} + +fn observed_completion<F>(observed: &[(F, u64)], fence: &F, same: impl Fn(&F, &F) -> bool) -> u64 { + observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) +} + +fn reserve_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64) -> bool { + if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { + return false; } + waited.insert(queue, value); + true +} - /// Close and submit upload slot `idx` asynchronously (NO CPU wait — callers order GPU work - /// via `queue.Wait(&self.fence, self.value)`). - unsafe fn submit_slot(&mut self, idx: usize) { - let closed = self.slots[idx].list.Close().is_ok(); - if closed { - if let Ok(l) = self.slots[idx].list.cast::<ID3D12CommandList>() { - super::title_textures::own_work(|| { - self.queue.ExecuteCommandLists(&[Some(l)]); - }); +fn retry_journal(outcome: PreparationOutcome, mut deferred: Vec<usize>, runs: &[(usize, usize)]) -> Vec<usize> { + if outcome != PreparationOutcome::Ready { + for &(a, n) in runs { + let mut pg = a & !(PAGE - 1); + let end = a.saturating_add(n); + while pg < end { + deferred.push(pg); + pg += PAGE; } } - self.signal(); - self.slots[idx].fence_val = self.value; - if self.ring_write > self.ring_submitted { - self.inflight.push_back((self.value, self.ring_write)); - self.ring_submitted = self.ring_write; - } } + deferred.sort_unstable(); + deferred.dedup(); + deferred +} - unsafe fn staging_ptr(&mut self) -> Option<*mut u8> { - if self.staging.is_none() { - let mut r: Option<ID3D12Resource> = None; - let mut d = buffer_desc(STAGING as u64); - d.Flags = D3D12_RESOURCE_FLAG_NONE; - self.dev - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &d, - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - &mut r, - ) - .ok()?; - let r = r?; - let mut p = std::ptr::null_mut(); - r.Map(0, None, Some(&mut p)).ok()?; - self.staging = Some((r, p as *mut u8)); - } - self.staging.as_ref().map(|&(_, p)| p) +fn remember_metric_runs(seen: &mut BTreeMap<usize, usize>, runs: &[(usize, usize)]) { + for &(a, n) in runs { + early_add(seen, a, a.saturating_add(n)); } +} - unsafe fn ensure_zero_buf(&mut self) -> bool { - if self.zero_buf.is_none() { - let mut r: Option<ID3D12Resource> = None; - let mut d = buffer_desc(ZERO_BUF as u64); - d.Flags = D3D12_RESOURCE_FLAG_NONE; - if self - .dev - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &d, - D3D12_RESOURCE_STATE_GENERIC_READ, - None, - &mut r, - ) - .is_err() - { - return false; +fn note_transfer_metrics( + sample: Option<&mut LookSample>, seen: Option<&(BTreeMap<usize, usize>, BTreeMap<usize, usize>)>, +) { + let (Some(sample), Some((zero, dirty))) = (sample, seen) else { return }; + sample.add(RUNS, (zero.len() + dirty.len()) as u64); + let bytes = zero.iter().chain(dirty).fold(0usize, |sum, (&a, &b)| sum.saturating_add(b.saturating_sub(a))); + sample.add(TRANSFER_BYTES, bytes as u64); +} + +fn rollback_queue_wait(waited: &mut FxHashMap<usize, u64>, queue: usize, value: u64, previous: Option<u64>) { + if waited.get(&queue) != Some(&value) { + return; + } + match previous { + Some(previous) => { waited.insert(queue, previous); } + None => { waited.remove(&queue); } + } +} + +/// Wait with both `STATE` and `UPLOAD_GATE` released. The caller's shared generation lease keeps +/// every old-state allocator, list, staging byte and destination alive. Only an exact ticket may +/// retire ring storage; a crossing uploader otherwise makes the caller rebuild from current state. +unsafe fn wait_upload_released(ticket: WaitTicket) -> bool { + loop { + match crate::gpu::fence::wait(&ticket.fence, ticket.target, &ticket.dev, None, 5000) { + Ok(()) => break, + Err(crate::gpu::fence::FenceError::Timeout(_)) => { + crate::xlog_warn!("sparse: upload retirement fence {} is still pending; STATE remains released", ticket.target); } - let Some(r) = r else { return false }; - let mut p = std::ptr::null_mut(); - if r.Map(0, None, Some(&mut p)).is_err() { + Err(e) => { + crate::xlog_warn!("sparse: upload retirement fence {} failed: {e}", ticket.target); return false; } - std::ptr::write_bytes(p as *mut u8, 0, ZERO_BUF); - r.Unmap(0, None); - self.zero_buf = Some(r); - } - true - } - - unsafe fn readback_buf(&mut self) -> Option<(ID3D12Resource, *mut u8)> { - if self.readback.is_none() { - let mut r: Option<ID3D12Resource> = None; - let mut d = buffer_desc(READBACK_STAGING as u64); - d.Flags = D3D12_RESOURCE_FLAG_NONE; - self.dev - .CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, - D3D12_HEAP_FLAG_NONE, - &d, - D3D12_RESOURCE_STATE_COPY_DEST, - None, - &mut r, - ) - .ok()?; - let r = r?; - let mut p = std::ptr::null_mut(); - r.Map(0, None, Some(&mut p)).ok()?; - self.readback = Some((r, p as *mut u8)); } - self.readback.clone() } - - /// Clear `sent` hashes for every page overlapping `[a, a + n)`. - fn clear_sent_range(&mut self, a: usize, n: usize) { - let mut pg = a & !(PAGE - 1); - let end = a + n; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = self.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - entry.sent[(p - t) / PAGE] = None; - p += PAGE; + let proceed = { + let mut g = lock_state(); + match g.as_mut() { + None => false, + Some(s) if s.generation != ticket.state_generation || s.fence.as_raw() != ticket.fence.as_raw() => { + // The caller's shared lifetime makes replacement impossible. Fail closed if a + // future teardown path violates that protocol. + false + } + Some(s) if !s.uploads_ordered => false, + Some(s) => { + // Another uploader can retire/reuse this slot or ring range after the waited + // target completes. That invalidates exact ownership but not the completed fence; + // loop on current state. Reclaim only if neither it nor a remap crossed this ticket. + if s.wait_ticket_valid(&ticket) { + s.reclaim_ring(); } + true } - pg = tile_end; } + }; + drop(ticket); + proceed +} + +/// Snapshot strong fence owners under `STATE`, then query them without it. A batch or a higher +/// mark added while polling is checked against the same observation; a new fence has no +/// observation and therefore remains quarantined. +unsafe fn poll_retirement_fences() -> Vec<(ID3D12Fence, u64)> { + let fences = { + let g = lock_state(); + let Some(s) = g.as_ref() else { return Vec::new() }; + std::iter::once(s.fence.clone()) + .chain(s.quarantined.iter().flat_map(|batch| batch.marks.iter().flatten().map(|(fence, _)| fence.clone()))) + .collect() + }; + poll_unique(fences, |fence| fence.as_raw() as usize, |fence| fence.GetCompletedValue()) +} + +/// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB +/// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video +/// memory, and `queue` GPU-waits for that and for new tile mappings. +pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize, mut look: Option<&mut LookSample>) -> PreparationOutcome { + let q = queue.as_raw() as usize; + let t0 = look.is_some().then(std::time::Instant::now); + let queue_gate = WAIT_GATES.lock().unwrap().entry(q).or_default().clone(); + let _queue_serial = queue_gate.lock().unwrap(); + let _upload_lifetime = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (mut uploads, mut timing) = UploadGateTiming::acquire(look.is_some()); + let t_gated = t0.map(|_| std::time::Instant::now()); + if let (Some(sample), Some(t0), Some(t_gated)) = (look.as_deref_mut(), t0, t_gated) { + sample.add_time(QUEUE_WAIT_US, t_gated.duration_since(t0)); } + let outcome = before_execute_locked(queue, dirty, page, q, t0, &mut look, &mut uploads, &mut timing); + let times = timing.finish(); + drop(uploads.take()); + if let Some(sample) = look.as_deref_mut() { + add_gate_times(&mut sample.0, SUBMIT_GATE_WAIT_US, SUBMIT_GATE_HOLD_US, None, times); + } + outcome +} - /// Update `sent` hashes for all 64-byte chunks overlapping `[va, va + len)` so the CPU - /// copy-back we just wrote to `va` is not re-uploaded by the next `before_execute`. - unsafe fn sync_sent_range(&mut self, va: usize, len: usize) { - if len == 0 { - return; - } - let mut pg = va & !(PAGE - 1); - let end = va + len; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = self.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - let idx = (p - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); - let sent = entry.sent[idx].get_or_insert_with(|| Box::new(ZERO_HASHES)); - let lo = va.saturating_sub(p) / CHUNK; - let hi = (end.min(p + PAGE) - p).div_ceil(CHUNK).min(CHUNKS); - for k in lo..hi { - sent[k] = chunk_hash(&bytes[k * CHUNK..(k + 1) * CHUNK]); - } - } - p += PAGE; - } - } - pg = tile_end; +unsafe fn before_execute_locked( + queue: &ID3D12CommandQueue, + dirty: &[usize], + page: usize, + q: usize, + t0: Option<std::time::Instant>, + look: &mut Option<&mut LookSample>, + uploads: &mut Option<UploadGuard>, + timing: &mut UploadGateTiming, +) -> PreparationOutcome { + let mut metric_runs = look.is_some().then(|| (BTreeMap::new(), BTreeMap::new())); + 'prepare: loop { + let t_started = t0.map(|_| std::time::Instant::now()); + let observed = poll_retirement_fences(); + let mut g = lock_state(); + let Some(s) = g.as_mut() else { + if let (Some(sample), Some(t_started)) = (look.as_deref_mut(), t_started) { + sample.add_time(MAINTENANCE_US, t_started.elapsed()); } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; + }; + // the title's work sees what was decommitted unmapped, as it was + let flushed = s.flush_parked_with(Some(queue)); + let drained = s.drain_quarantined_with(|fence| { + observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) + }); + if flushed || drained { + let sparse_done = observed_completion(&observed, &s.fence, |known, current| known.as_raw() == current.as_raw()); + s.retire_free_pools_with(sparse_done); } - - /// Copy `ranges` (address, bytes) from sparse VRAM back into the CPU view and refresh - /// `sent` hashes. Caller has already ordered `self.queue` after any GPU writes if needed. - unsafe fn readback_ranges(&mut self, ranges: &[(usize, usize)]) { - let Some((rb, p)) = self.readback_buf() else { return }; - let mut pending: Vec<(usize, usize, usize)> = Vec::new(); // (va, rb_off, chunk) - let mut used = 0usize; - let mut open = false; - let flush_and_copy = |s: &mut State, open: &mut bool, pending: &mut Vec<(usize, usize, usize)>, used: &mut usize, p: *mut u8| { - if *open { - *open = false; - if s.rb_list.Close().is_ok() { - if let Ok(l) = s.rb_list.cast::<ID3D12CommandList>() { - super::title_textures::own_work(|| { - s.queue.ExecuteCommandLists(&[Some(l)]); - }); - } - } - s.signal(); - s.rb_last_fence = s.value; - s.wait_for(s.value); - s.reclaim_ring(); + let t_maintained = t0.map(|_| std::time::Instant::now()); + let zero_runs = std::mem::take(&mut s.to_zero); + for &(a, n) in &zero_runs { + s.clear_sent_range(a, n); + } + let mut dirty_runs = std::mem::take(&mut s.scratch_runs); + dirty_runs.clear(); + let mut deferred = Vec::new(); + let retry_pages = std::mem::take(&mut s.retry_pages); + if retry_pages.is_empty() { + let mut i = 0; + while i < dirty.len() { + let a = dirty[i]; + let mut n = page; + i += 1; + while i < dirty.len() && dirty[i] == a + n { + n += page; + i += 1; } - for &(dst, off, len) in pending.iter() { - // copy only committed (non-hole) bytes - let mut at = dst; - let mut src_off = off; - let end = dst + len; - while at < end { - let pg = at & !(PAGE - 1); - let t = pg & !(TILE - 1); + let mut pg = a & !(PAGE - 1); + while pg < a + n { + let t = pg & !(TILE - 1); + if let Some(entry) = s.mapped.get_mut(&t) { let idx = (pg - t) / PAGE; - let step = (pg + PAGE).min(end) - at; - if s.mapped.get(&t).is_some_and(|e| e.holes & (1u16 << idx) == 0) { - std::ptr::copy_nonoverlapping(p.add(src_off), at as *mut u8, step); + if entry.holes & (1u16 << idx) == 0 { + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); } - at += step; - src_off += step; - } - s.sync_sent_range(dst, len); - } - pending.clear(); - *used = 0; - }; - for &(a, n) in ranges { - if n == 0 { - continue; - } - let mut done = 0usize; - while done < n { - let cur = a + done; - let tile = cur & !(TILE - 1); - let Some(wi) = self.window_index(cur) else { break }; - let b = self.windows[wi].0; - let to_tile_end = (tile + TILE) - cur; - if !self.mapped.contains_key(&tile) { - done += (n - done).min(to_tile_end); - continue; - } - if used == READBACK_STAGING { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); - } - let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; - let chunk = (n - done).min(READBACK_STAGING - used).min(to_tile_end).min(to_win_end); - if !open { - self.wait_for(self.rb_last_fence); - let _ = self.rb_alloc.Reset(); - let _ = self.rb_list.Reset(&self.rb_alloc, None); - open = true; } - self.rb_list.CopyBufferRegion(&rb, used as u64, &self.windows[wi].1, (cur - b) as u64, chunk as u64); - pending.push((cur, used, chunk)); - used += chunk; - done += chunk; + pg += PAGE; } } - if open { - flush_and_copy(self, &mut open, &mut pending, &mut used, p); + } else { + let mut pages = retry_pages; + let prior = pages.clone(); + pages.extend(dirty.iter().flat_map(|&a| (a..a.saturating_add(page)).step_by(PAGE))); + pages.sort_unstable(); + pages.dedup(); + for pg in pages { + let t = pg & !(TILE - 1); + let Some(entry) = s.mapped.get_mut(&t) else { + if prior.binary_search(&pg).is_ok() { deferred.push(pg) } + continue; + }; + let idx = (pg - t) / PAGE; + if entry.holes & (1u16 << idx) != 0 { + if prior.binary_search(&pg).is_ok() { deferred.push(pg) } + continue; + } + let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); + scan_page(bytes, pg, &entry.sent[idx], &mut dirty_runs); } } - - /// Asynchronously zero `runs` (address, bytes) in sparse VRAM using the pre-zeroed `zero_buf` - /// (zero staging ring bytes consumed, zero CPU stall). - unsafe fn upload_zeros(&mut self, runs: &[(usize, usize)]) { - if runs.is_empty() || !self.ensure_zero_buf() { - return; - } - let slot_idx = self.begin_slot(); - let mut last_wi: Option<usize> = None; - let zero_buf = self.zero_buf.as_ref().unwrap(); - let list = &self.slots[slot_idx].list; - for &(a, n) in runs { - let mut done = 0usize; - while done < n { - let cur = a + done; - let wi = match last_wi { - Some(i) if cur >= self.windows[i].0 && cur < self.windows[i].0 + crate::gpu::uma::WINDOW => i, - _ => match self.window_index(cur) { - Some(i) => { - last_wi = Some(i); - i - } - None => break, - }, - }; - let b = self.windows[wi].0; - let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; - let chunk = (n - done).min(ZERO_BUF).min(to_win_end); - list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, zero_buf, 0, chunk as u64); - done += chunk; + let t_scanned = t0.map(|_| std::time::Instant::now()); + // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. + let mut outcome = PreparationOutcome::Ready; + let mut upload_wait = None; + if !zero_runs.is_empty() { + match s.upload_zeros(&zero_runs) { + UploadStep::Done(done) => outcome = done, + UploadStep::Wait(ticket) => { + outcome = PreparationOutcome::RetryRequired; + upload_wait = Some(ticket); } } - self.submit_slot(slot_idx); + if outcome != PreparationOutcome::Ready { + s.to_zero.extend(zero_runs.iter().copied()); + } } - - /// Asynchronously copy `runs` (address, bytes) from the CPU view into sparse VRAM tiles via - /// the 64 MiB ring staging buffer (zero CPU stall on the common path). - unsafe fn upload_dirty(&mut self, runs: &[(usize, usize)]) { - if runs.is_empty() { - return; + if outcome == PreparationOutcome::Ready && !dirty_runs.is_empty() { + match s.upload_dirty(&dirty_runs) { + UploadStep::Done(done) => outcome = done, + UploadStep::Wait(ticket) => { + outcome = PreparationOutcome::RetryRequired; + upload_wait = Some(ticket); + } } - let Some(p) = self.staging_ptr() else { return }; - let mut open_slot: Option<usize> = None; - let mut last_wi: Option<usize> = None; - for &(a, n) in runs { - let mut done = 0usize; - while done < n { - let cur = a + done; - let wi = match last_wi { - Some(i) if cur >= self.windows[i].0 && cur < self.windows[i].0 + crate::gpu::uma::WINDOW => i, - _ => match self.window_index(cur) { - Some(i) => { - last_wi = Some(i); - i - } - None => break, - }, - }; - let b = self.windows[wi].0; - let to_win_end = (b + crate::gpu::uma::WINDOW) - cur; - let (aligned, chunk) = plan_ring_chunk(self.ring_write, (n - done).min(to_win_end), STAGING); - if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - self.reclaim_ring(); - if (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - if let Some(slot_idx) = open_slot.take() { - self.submit_slot(slot_idx); - self.reclaim_ring(); - } - while (aligned + chunk as u64).saturating_sub(self.ring_free) > STAGING as u64 { - let Some(&(fv, _)) = self.inflight.front() else { break }; - self.wait_for(fv); - self.reclaim_ring(); - } - } - } - let slot_idx = match open_slot { - Some(idx) => idx, - None => { - let idx = self.begin_slot(); - open_slot = Some(idx); - idx - } - }; - let dst_off = (aligned as usize) % STAGING; - std::ptr::copy_nonoverlapping(cur as *const u8, p.add(dst_off), chunk); - let staging_res = &self.staging.as_ref().unwrap().0; - self.slots[slot_idx].list.CopyBufferRegion(&self.windows[wi].1, (cur - b) as u64, staging_res, dst_off as u64, chunk as u64); - self.ring_write = aligned + chunk as u64; - done += chunk; + } + s.retry_pages = retry_journal(outcome, deferred, &dirty_runs); + if let Some((zero, dirty)) = metric_runs.as_mut() { + remember_metric_runs(zero, &zero_runs); + remember_metric_runs(dirty, &dirty_runs); + } + if let (Some(sample), Some(t_started), Some(t_maintained), Some(t_scanned)) = + (look.as_deref_mut(), t_started, t_maintained, t_scanned) + { + let t_uploaded = std::time::Instant::now(); + sample.add_time(MAINTENANCE_US, t_maintained.duration_since(t_started)); + sample.add_time(SCAN_US, t_scanned.duration_since(t_maintained)); + sample.add_time(UPLOAD_US, t_uploaded.duration_since(t_scanned)); + } + dirty_runs.clear(); + s.scratch_runs = dirty_runs; + if let Some(ticket) = upload_wait { + // `to_zero` and `retry_pages` were restored above before ownership is released. Another + // queue may consume either journal; reacquisition is included in UPLOAD_WAIT_US and the + // next iteration always rebuilds its plan from current state. + drop(g); + drop(observed); + let wait_started = t0.map(|_| std::time::Instant::now()); + if !timing.with_released(uploads, || wait_upload_released(ticket)) { + if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { + sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::RetryRequired; } - if let Some(slot_idx) = open_slot { - self.submit_slot(slot_idx); + if let (Some(sample), Some(wait_started)) = (look.as_deref_mut(), wait_started) { + sample.add_time(UPLOAD_WAIT_US, wait_started.elapsed()); + } + continue 'prepare; + } + if outcome != PreparationOutcome::Ready { + drop(g); + drop(observed); + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return outcome; + } + let value = s.value; + let previous = s.waited.get(&q).copied(); + let wait = reserve_queue_wait(&mut s.waited, q, value).then(|| (s.fence.clone(), value, previous)); + drop(g); + drop(observed); + if let Some((fence, value, previous)) = wait { + if super::real::native_queue_wait(queue, &fence, value).is_err() { + let mut g = lock_state(); + if let Some(s) = g.as_mut().filter(|s| s.fence.as_raw() == fence.as_raw() && s.waited.get(&q) == Some(&value)) { + rollback_queue_wait(&mut s.waited, q, value, previous); + } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::RetryRequired; } + super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &fence, value); + } + note_transfer_metrics(look.as_deref_mut(), metric_runs.as_ref()); + return PreparationOutcome::Ready; } } -/// Allocate a zeroed, write-watched block in the sparse VRAM windows (never straddling a -/// 4 GiB window boundary when `size <= 4 GiB`). Commits the CPU pages and maps VRAM tiles -/// (or queues them until the D3D12 device exists). Returns `(address, rounded_size)`. -pub unsafe fn alloc(size: usize, align: usize) -> Option<(usize, usize)> { - let u = crate::gpu::uma::get()?; - let (addr, rounded) = u.sparse_alloc(size, align)?; - if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { - u.sparse_release(addr); +/// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC +/// description): a reserved resource over the window's tiles there, starting at the 64 KiB +/// below `va` (returned: its distance from there). +pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { + let _placement = PLACEMENT.lock().unwrap(); + place_buffer_in( + &STATE, + &FORGOTTEN, + va, + desc, + state, + |d| { + let hr = super::real::dev_create_reserved_resource(this, d as *const _ as usize, state as usize, 0, riid, ppv); + (hr >= 0 && !ppv.is_null() && !(*ppv).is_null()).then_some((hr, *ppv)) + }, + |raw| { + if !ppv.is_null() && *ppv == raw { + *ppv = std::ptr::null_mut(); + } + drop(ID3D12Resource::from_raw(raw)); + }, + ) +} + +unsafe fn place_buffer_in( + state_lock: &Mutex<Option<State>>, + forgotten: &Mutex<Vec<usize>>, + va: usize, + desc: &D3D12_RESOURCE_DESC, + state: u32, + create: impl FnOnce(&D3D12_RESOURCE_DESC) -> Option<(crate::util::HRESULT, *mut c_void)>, + on_abort: impl FnOnce(*mut c_void), +) -> Option<(crate::util::HRESULT, usize)> { + let start = va & !(TILE - 1); + let delta = va - start; + let bytes = desc.Width as usize; + if bytes == 0 { return None; } - committed(addr, rounded); - Some((addr, rounded)) + let end = va.checked_add(bytes)?.checked_sub(1)?; + let generation = { + let g = lock_state_in(state_lock, forgotten); + let s = g.as_ref()?; + s.window_index(start)?; + s.window_index(end)?; + s.fence.clone() + }; + let mut d = *desc; + d.Width = (delta + bytes) as u64; + d.Alignment = 0; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + // Reserved buffers only accept NONE or ALLOW_UNORDERED_ACCESS (strip console flags and ALLOW_CROSS_ADAPTER). + d.Flags &= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { + d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + } + // Driver creation may call back into a release path which needs `STATE`. Revalidate the + // strongly owned fence generation before publishing the resulting resource. + let (hr, raw) = create(&d)?; + let mut g = lock_state_in(state_lock, forgotten); + let valid = g.as_ref().is_some_and(|s| { + s.fence.as_raw() == generation.as_raw() && s.window_index(start).is_some() && s.window_index(end).is_some() + }); + let Some(res) = valid.then(|| ID3D12Resource::from_raw_borrowed(&raw).cloned()).flatten() else { + drop(g); + drop(generation); + on_abort(raw); + return None; + }; + let s = g.as_mut().unwrap(); + // its tiles: the window's video memory at the same addresses; probe actual OS commitment + // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes + s.ensure_mapped(start, delta + bytes, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); + s.mapping_epoch = s.mapping_epoch.wrapping_add(1); + let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); + s.map_tiles(&res, start, &tiles); + if s.buffers.contains_key(&(raw as usize)) { + forget_in(s, raw as usize); + } + for &(_, tile) in &tiles { + *s.pinned.entry(tile).or_default() += 1; + } + s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); + s.signal(); + drop(g); + drop(res); + drop(generation); + Some((hr, delta)) } -/// Allocate a zeroed, write-watched block strictly inside sparse window `window` (e.g. -/// window 0 for 32-bit-addressed descriptor heaps). Returns `(address, rounded_size)`. -pub unsafe fn alloc_in(window: usize, size: usize, align: usize) -> Option<(usize, usize)> { - let u = crate::gpu::uma::get()?; - let (addr, rounded) = u.sparse_alloc_in(window, size, align)?; - if VirtualAlloc(addr as *const c_void, rounded, MEM_COMMIT, PAGE_READWRITE).is_null() { - u.sparse_release(addr); - return None; +/// Placed buffers released while `STATE` was held, let go by the next `lock_state`. Held only +/// to push or take, never across a call out. +static FORGOTTEN: Mutex<Vec<usize>> = Mutex::new(Vec::new()); + +/// `STATE`, with the buffers released while it was held let go first. +fn lock_state() -> std::sync::MutexGuard<'static, Option<State>> { + lock_state_in(&STATE, &FORGOTTEN) +} + +fn lock_state_in<'a>(state: &'a Mutex<Option<State>>, forgotten: &Mutex<Vec<usize>>) -> std::sync::MutexGuard<'a, Option<State>> { + let mut g = state.lock().unwrap(); + forget_released_in(&mut g, forgotten); + g +} + +fn forget_released_in(g: &mut Option<State>, forgotten: &Mutex<Vec<usize>>) { + let gone = std::mem::take(&mut *forgotten.lock().unwrap()); + let Some(s) = g.as_mut() else { return }; + for res in gone { + forget_in(s, res); } - committed(addr, rounded); - Some((addr, rounded)) } -/// Release a sparse allocation from `alloc` / `alloc_in` (false: not a sparse allocation). -pub unsafe fn free(p: usize) -> bool { - let Some(u) = crate::gpu::uma::get() else { return false }; - if !u.is_sparse(p) { - return false; +/// A placed buffer is gone: its tiles are not pinned by it any more. This runs from the +/// resource's last Release, which D3D12 can make while it holds a lock of its own (in a title's +/// command list Reset), and `before_execute` calls D3D12 with `STATE` held: waiting for `STATE` +/// here deadlocked the two threads. So it does not wait: with `STATE` held, the holder's next +/// `lock_state` lets the buffer go. +pub fn forget_buffer(res: usize) { + forget_buffer_in(&STATE, &FORGOTTEN, res); +} + +fn forget_buffer_in(state: &Mutex<Option<State>>, forgotten: &Mutex<Vec<usize>>, res: usize) { + forgotten.lock().unwrap().push(res); + match state.try_lock() { + Ok(mut g) => forget_released_in(&mut g, forgotten), + Err(std::sync::TryLockError::WouldBlock) => {} + Err(e) => panic!("sparse state: {e}"), } - // decommitted before the address goes back: once released, another thread may get it, - // commit it and write there - let Some((start, len)) = u.sparse_reservation(p).filter(|&(start, _)| start == p) else { return false }; - decommitted(start, len); - VirtualFree(p as *mut c_void, len, MEM_DECOMMIT); - u.sparse_release(p).is_some() } -/// After `queue.ExecuteCommandLists`: copy GPU-written sparse ranges (e.g. `Write32/64`, -/// `FillMemoryWith32BitValueX`, `CopyMemoryToMemoryX`) back to their CPU view so CPU reads -/// and spin-waits see the GPU writes without clobbering `sent` hashes. -/// The queue tile mappings go out on, once there is one. Answered without `STATE` (`QUEUE`): -/// a caller may be inside a D3D12 call that a holder of `STATE` waits for. -pub fn queue() -> Option<ID3D12CommandQueue> { - QUEUE.lock().unwrap().clone() +fn forget_in(s: &mut State, res: usize) { + let Some(tiles) = s.buffers.remove(&res) else { return }; + for tile in tiles { + if let Some(c) = s.pinned.get_mut(&tile) { + *c -= 1; + if *c == 0 { + s.pinned.remove(&tile); + s.release_if_unused(tile); + } + } + } } -pub unsafe fn readback_after_execute(queue: &ID3D12CommandQueue, ranges: &[(usize, usize)]) { - if ranges.is_empty() { - return; +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn activity_look_line_splits_foreground_costs() { + let line = look_line([ + 830_000, + 120_000, + 610_000, + 4_800, + 240, + 240 * 1_641 << 20, + 240 * 69, + 10_000, + 30_000, + 40_000, + 40_000, + 90, + 96 << 20, + 20_000, + 5_000, + 105_000, + 3_000, + 70_000, + 12_000, + ], 2); + assert!(line.contains("240 looks did 830 ms active work (41.5 % of the time) after 120 ms waiting"), "{line}"); + assert!(line.contains("write-watch 610 ms (1641.0 MB in 69.0 ranges/look, 4800 pages written)"), "{line}"); + assert!(line.contains("sparse queue wait/fence+state/scan/upload/ownership wait 10/30/40/40/20 ms (90 runs, 96.0 MB zero/dirty bytes)"), "{line}"); + assert!(line.contains("upload gate submit wait/hold 5/105 ms, readback wait/hold/released wait+reacquire 3/70/12 ms; other active work 80 ms"), "{line}"); + let idle = look_line([0; LOOK_FIELDS], 2); + assert!(idle.contains("0 looks did 0 ms active work (0.0 % of the time) after 0 ms waiting"), "{idle}"); + assert!(idle.contains("0.0 MB in 0.0 ranges/look"), "{idle}"); } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); - let mut filtered: Vec<(usize, usize)> = ranges.iter().copied().filter(|&(a, n)| n > 0 && s.window_index(a).is_some()).collect(); - if filtered.is_empty() { - return; + + #[test] + fn activity_look_counter_delta_survives_wrap() { + assert_eq!(look_delta([0; LOOK_FIELDS], [u64::MAX; LOOK_FIELDS]), [1; LOOK_FIELDS]); } - filtered.sort_unstable(); - let mut merged: Vec<(usize, usize)> = Vec::with_capacity(filtered.len()); - for (a, n) in filtered { - match merged.last_mut() { - Some(last) if a <= last.0.saturating_add(last.1) => { - let end = (last.0 + last.1).max(a + n); - last.1 = end - last.0; - } - _ => merged.push((a, n)), + + #[test] + fn upload_gate_times_accumulate_into_distinct_submit_and_readback_fields() { + let mut sample = [0; LOOK_FIELDS]; + add_gate_times( + &mut sample, + SUBMIT_GATE_WAIT_US, + SUBMIT_GATE_HOLD_US, + None, + UploadGateTimes { wait_us: 11, hold_us: 22, released_us: 33 }, + ); + add_gate_times( + &mut sample, + READBACK_GATE_WAIT_US, + READBACK_GATE_HOLD_US, + Some(READBACK_GATE_RELEASED_US), + UploadGateTimes { wait_us: 44, hold_us: 55, released_us: 66 }, + ); + assert_eq!(sample[SUBMIT_GATE_WAIT_US], 11); + assert_eq!(sample[SUBMIT_GATE_HOLD_US], 22); + assert_eq!(sample[READBACK_GATE_WAIT_US], 44); + assert_eq!(sample[READBACK_GATE_HOLD_US], 55); + assert_eq!(sample[READBACK_GATE_RELEASED_US], 66); + } + + #[test] + fn retried_upload_ranges_are_counted_once() { + let mut zero = BTreeMap::new(); + let mut dirty = BTreeMap::new(); + remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); + remember_metric_runs(&mut zero, &[(0x1000, 0x1000)]); + remember_metric_runs(&mut dirty, &[(0x4000, 0x1000)]); + remember_metric_runs(&mut dirty, &[(0x4000, 0x2000)]); + let mut sample = LookSample::default(); + note_transfer_metrics(Some(&mut sample), Some(&(zero, dirty))); + assert_eq!(sample.0[RUNS], 2); + assert_eq!(sample.0[TRANSFER_BYTES], 0x3000); + } + + #[test] + fn activity_look_publishes_one_complete_sample() { + let mut total = [10; LOOK_FIELDS]; + let sample = std::array::from_fn(|i| i as u64); + merge_look(&mut total, sample); + assert_eq!(total, std::array::from_fn(|i| 10 + i as u64)); + merge_look(&mut total, std::array::from_fn(|i| u64::MAX - 9 - i as u64)); + assert_eq!(total, [0; LOOK_FIELDS]); + } + + #[test] + fn writable_record_requires_every_touched_page_and_tracks_protection() { + let mut mapped = FxHashMap::default(); + let (t0, t1) = (0x10_0000usize, 0x11_0000usize); + mapped.insert(t0, TileEntry::with_holes((0, 1), 0)); + mapped.insert(t1, TileEntry::with_holes((0, 2), 1 << 2)); + + assert!(recorded_committed(&mapped, t0, t0 + TILE)); + assert!(recorded_committed(&mapped, t0 + 0x800, t1 + 2 * PAGE)); + assert!(!recorded_committed(&mapped, t1 + 2 * PAGE, t1 + 2 * PAGE + 1)); + assert!(!recorded_committed(&mapped, t1 + TILE - 8, t1 + TILE + 8)); + + mark_protection(&mut mapped, t0 + 5 * PAGE + 16, 8, false); + assert!(!recorded_committed(&mapped, t0 + 5 * PAGE, t0 + 5 * PAGE + 1)); + assert!(recorded_committed(&mapped, t0 + 6 * PAGE, t0 + TILE)); + mark_protection(&mut mapped, t0 + 5 * PAGE, PAGE, true); + assert!(recorded_committed(&mapped, t0, t0 + TILE)); + } + + #[test] + fn early_protection_ranges_merge_split_and_commit_clears_them() { + let base = 0x20_0000usize; + let mut protected = BTreeMap::new(); + early_protection(&mut protected, base + PAGE + 16, 8, false); + early_protection(&mut protected, base + 3 * PAGE, 3 * PAGE, false); + early_protection(&mut protected, base + 5 * PAGE, PAGE, true); + assert_eq!(protected.into_iter().collect::<Vec<_>>(), [(base + PAGE, base + 2 * PAGE), (base + 3 * PAGE, base + 5 * PAGE)]); + + let mut protected = BTreeMap::from([(base, base + 4 * PAGE)]); + early_remove(&mut protected, base + PAGE, base + 3 * PAGE); + assert_eq!(protected.into_iter().collect::<Vec<_>>(), [(base, base + PAGE), (base + 3 * PAGE, base + 4 * PAGE)]); + } + + #[test] + fn working_set_check_rejects_resident_read_only_pages_without_touching_cold_pages() { + use windows_sys::Win32::System::Memory::{MEM_RELEASE, MEM_RESERVE, PAGE_READONLY}; + unsafe { + let base = VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) as usize; + assert_ne!(base, 0); + assert!(!VirtualAlloc(base as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + assert!(!VirtualAlloc((base + PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READONLY).is_null()); + assert!(!VirtualAlloc((base + 2 * PAGE) as *const c_void, PAGE, MEM_COMMIT, PAGE_READWRITE).is_null()); + std::ptr::write_volatile(base as *mut u8, 1); + assert_eq!(std::ptr::read_volatile((base + PAGE) as *const u8), 0); + assert!(resident_pages_writable(base, base + PAGE)); + assert!(!resident_pages_writable(base + PAGE, base + 2 * PAGE)); + assert!(resident_pages_writable(base + 2 * PAGE, base + 3 * PAGE)); + + let mut cold: windows_sys::Win32::System::ProcessStatus::PSAPI_WORKING_SET_EX_INFORMATION = std::mem::zeroed(); + cold.VirtualAddress = (base + 2 * PAGE) as *mut c_void; + assert_ne!( + windows_sys::Win32::System::ProcessStatus::K32QueryWorkingSetEx( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + &mut cold as *mut _ as *mut c_void, + std::mem::size_of_val(&cold) as u32, + ), + 0 + ); + assert_eq!(cold.VirtualAttributes.Flags & 1, 0, "the metadata query paged memory in"); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); } } - s.rb_value += 1; - let v = s.rb_value; - if queue.Signal(&s.rb_fence, v).is_ok() { - let _ = s.queue.Wait(&s.rb_fence, v); - super::list_x::note_internal_wait(s.queue.as_raw() as usize, "sparse readback behind a title queue", &s.rb_fence, v); + + #[test] + fn memory_counts_committed_pages_and_separates_devices_and_retired_pools() { + let holes = [0xFFFE, 0xFFF0].into_iter(); // one committed page, then four + let (pools, occupied, retired, committed) = memory_byte_counts(7, 7, 1, 60, 1, holes); + assert_eq!(pools, POOL_TILES as usize * TILE); + assert_eq!(occupied, 4 * TILE, "occupied video tiles are independent of CPU page commitment"); + assert_eq!(retired, POOL_TILES as usize * TILE, "the retired pool is not also active"); + assert_eq!(committed, 5 * PAGE, "holes in a 64 KiB tile do not consume CPU commit"); + assert_eq!(memory_byte_counts(8, 7, 1, 60, 1, [0].into_iter()), (0, 0, 0, 0)); + } + + /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for + /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be + /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). + #[test] + fn the_queue_is_answered_while_the_state_is_locked() { + let held = STATE.lock().unwrap(); + let (tx, rx) = std::sync::mpsc::channel(); + let asked = std::thread::spawn(move || { + let _ = queue(); + let _ = tx.send(()); + }); + let answered = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); + drop(held); + asked.join().unwrap(); + assert!(answered, "queue() waited for the sparse state's lock"); + } + + #[test] + fn exact_retirement_forgets_cache_but_inflight_batch_keeps_its_fence() { + use std::sync::Arc; + let old = Arc::new(7u32); + let mut fences = FxHashMap::default(); + fences.insert(0xA, (old.clone(), 3)); + let batch_mark = fences[&0xA].0.clone(); + + assert!(fences.contains_key(&0xA), "marker failure must leave the cache pinned"); + let gone = remove_queue_fence(&mut fences, 0xA).expect("exact retirement callback"); + assert!(fences.is_empty() && Arc::ptr_eq(&gone.0, &batch_mark)); + drop(gone); + drop(old); + assert_eq!(Arc::strong_count(&batch_mark), 1, "cache removal invalidated an in-flight batch mark"); + + let replacement = Arc::new(9u32); + fences.insert(0xA, (replacement.clone(), 1)); + assert!(!Arc::ptr_eq(&batch_mark, &fences[&0xA].0), "reused raw address kept the retired generation's fence"); + } + + #[test] + fn retirement_fence_poll_is_unlocked_and_new_requirements_fail_closed() { + use std::sync::{atomic::{AtomicU64, AtomicUsize, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(1)); + let late = Arc::new(AtomicU64::new(9)); + let state = Mutex::new(vec![first.clone(), first.clone()]); + let polls = AtomicUsize::new(0); + + let snapshot = state.lock().unwrap().clone(); + let observed = poll_unique(snapshot, |fence| Arc::as_ptr(fence) as usize, |fence| { + assert!(state.try_lock().is_ok(), "completion polling held sparse state"); + state.lock().unwrap().push(late.clone()); + polls.fetch_add(1, Ordering::Relaxed); + fence.load(Ordering::Relaxed) + }); + + assert_eq!(polls.load(Ordering::Relaxed), 1, "the same fence is queried once"); + assert_eq!(observed_completion(&observed, &first, Arc::ptr_eq), 1); + assert!(observed_completion(&observed, &first, Arc::ptr_eq) < 2, "a higher mark added during polling remains held"); + assert_eq!(observed_completion(&observed, &late, Arc::ptr_eq), 0, "a newly added fence remains held"); } - s.readback_ranges(&merged); -} -/// Synchronize `[va, va + len)` in a sparse window for a CPU read (`ID3D12Resource::Map` with -/// a non-empty read range, or `Map(0, NULL)` on a sparse readback resource): flushes pending -/// tile clears and unsubmitted CPU-changed chunks first so CPU writes are preserved, then -/// copies the range back from VRAM into CPU memory. -pub unsafe fn readback_now(va: usize, len: usize) { - if len == 0 { - return; + #[test] + fn title_queue_wait_reservation_is_monotonic_and_per_queue() { + let mut waited = FxHashMap::default(); + assert!(!reserve_queue_wait(&mut waited, 1, 0)); + assert!(reserve_queue_wait(&mut waited, 1, 4)); + assert!(!reserve_queue_wait(&mut waited, 1, 4)); + assert!(!reserve_queue_wait(&mut waited, 1, 3)); + assert!(reserve_queue_wait(&mut waited, 2, 3)); + assert!(reserve_queue_wait(&mut waited, 1, 5)); + assert_eq!(waited, FxHashMap::from_iter([(1, 5), (2, 3)])); } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - if s.window_index(va).is_none() { - return; + + #[test] + fn failed_write_watch_pages_survive_until_a_ready_retry() { + let runs = [(0x1040, PAGE), (0x2000, CHUNK)]; + assert_eq!(retry_journal(PreparationOutcome::RetryRequired, vec![], &runs), [0x1000, 0x2000]); + assert!(retry_journal(PreparationOutcome::Ready, vec![], &runs).is_empty()); + assert_eq!(retry_journal(PreparationOutcome::ExecutedUntracked, vec![0x3000], &runs), [0x1000, 0x2000, 0x3000]); } - let zeroed = std::mem::take(&mut s.to_zero); - if !zeroed.is_empty() { - for &(a, n) in &zeroed { - s.clear_sent_range(a, n); - } - s.upload_zeros(&zeroed); + + #[test] + fn late_claim_completion_cannot_change_a_newer_owner() { + let mut ledger = WorkClaimLedger::new(11); + ledger.add_dirty_pages([0x8000]); + let old = ledger.claim(1).unwrap(); + assert_eq!(ledger.commit(old.token), WorkClaimResolution::Committed); + + ledger.add_retry_pages([0x8000]); + let newer = ledger.claim(1).unwrap(); + assert_eq!(ledger.restore(old.token), WorkClaimResolution::AlreadyFinished); + assert_eq!(ledger.owners.get(&0x8000), Some(&newer.token.serial)); + assert_eq!(ledger.commit(newer.token), WorkClaimResolution::Committed); + assert!(ledger.available.is_empty()); } - // Preserve any unsubmitted CPU writes on pages overlapping `[va, va + len)` - let mut dirty_runs: Vec<(usize, usize)> = Vec::new(); - let mut pg = va & !(PAGE - 1); - let end = va + len; - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = (t + TILE).min(end); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - let idx = (p - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(p as *const u8, PAGE); - scan_page(bytes, p, &mut entry.sent[idx], &mut dirty_runs); - } - p += PAGE; - } - } - pg = tile_end; + + #[test] + fn foreground_queue_cannot_pass_or_steal_an_unreceipted_claim() { + let mut frontier = ClaimFrontier::new(23); + let planner = frontier.claim(100).unwrap(); + assert_eq!( + frontier.observe(23, planner.epoch, 200), + Ok(ClaimFrontierAction::TakeOver(planner)), + "another queue mistook pending planner work for an empty frontier", + ); + + let helper = frontier.take_over(planner, 200).unwrap(); + assert_eq!(frontier.accept(planner), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.receipt(planner, 7), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.consume_obsolete(planner), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.take_over(planner, 300), Err(ClaimFrontierError::StaleToken)); + assert_eq!(frontier.observe(23, helper.epoch, 200), Ok(ClaimFrontierAction::Progress(helper))); + + frontier.accept(helper).unwrap(); + assert_eq!(frontier.take_over(helper, 100), Err(ClaimFrontierError::WrongState)); + assert_eq!(frontier.consume_obsolete(helper), Err(ClaimFrontierError::WrongState)); + assert_eq!( + frontier.observe(23, helper.epoch, 100), + Ok(ClaimFrontierAction::WaitForReceipt(helper)), + "accepted GPU work was exposed for retry", + ); + frontier.receipt(helper, 7).unwrap(); + assert_eq!( + frontier.observe(23, helper.epoch, 100), + Ok(ClaimFrontierAction::Ready { through: helper.epoch, required_fence: Some(7) }), + ); } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + + #[test] + fn receipts_and_obsolete_holes_advance_only_a_contiguous_frontier() { + let mut frontier = ClaimFrontier::new(29); + let first = frontier.claim(1).unwrap(); + let second = frontier.claim(2).unwrap(); + let hole = frontier.claim(3).unwrap(); + frontier.accept(first).unwrap(); + frontier.accept(second).unwrap(); + frontier.receipt(second, 11).unwrap(); + frontier.consume_obsolete(hole).unwrap(); + + assert_eq!(frontier.retired_through, 0, "out-of-order terminal work crossed the first claim"); + assert_eq!( + frontier.observe(29, hole.epoch, 9), + Ok(ClaimFrontierAction::WaitForReceipt(first)), + ); + frontier.receipt(first, 8).unwrap(); + assert_eq!(frontier.retired_through, hole.epoch, "an obsolete hole left the frontier stuck"); + assert_eq!( + frontier.observe(29, hole.epoch, 9), + Ok(ClaimFrontierAction::Ready { through: hole.epoch, required_fence: Some(11) }), + ); + assert_eq!( + frontier.observe(29, first.epoch, 9), + Ok(ClaimFrontierAction::Ready { through: first.epoch, required_fence: Some(8) }), + "an older observer unnecessarily inherited a newer fence", + ); } - s.readback_ranges(&[(va, len)]); -} -/// The title committed `[a, a + n)` in a sparse window. The pages of tiles mapped for it that -/// lie outside the range are not committed (holes); the range's pages are. -pub unsafe fn committed(a: usize, n: usize) { - if n == 0 { - return; + #[test] + fn frontier_rejects_wrong_generations_unknown_epochs_and_invalid_receipts() { + let mut frontier = ClaimFrontier::new(31); + let token = frontier.claim(4).unwrap(); + assert_eq!(frontier.observe(30, token.epoch, 4), Err(ClaimFrontierError::StaleGeneration)); + assert_eq!(frontier.observe(31, token.epoch + 1, 4), Err(ClaimFrontierError::UnknownEpoch)); + assert_eq!(frontier.receipt(token, 1), Err(ClaimFrontierError::WrongState)); + frontier.accept(token).unwrap(); + assert_eq!(frontier.receipt(token, 0), Err(ClaimFrontierError::Fence)); + assert_eq!(frontier.observe(31, 0, 4), Ok(ClaimFrontierAction::Ready { through: 0, required_fence: None })); + + let stale_generation = ClaimFrontierToken { state_generation: 32, ..token }; + assert_eq!(frontier.receipt(stale_generation, 1), Err(ClaimFrontierError::StaleGeneration)); } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { - let (start, end) = page_span(a, n); - early_add(&mut EARLY.lock().unwrap(), start, end); - return; - }; - s.commit_range(a, n); -} -/// The title decommitted `[a, a + n)`: tiles whose pages are all uncommitted (whether in one -/// full-tile decommit or incrementally via sub-tile decommits) give their video memory back -/// (unless a placed buffer still pins the pool tile). -pub unsafe fn decommitted(a: usize, n: usize) { - if n == 0 { - return; + #[test] + fn frontier_epoch_and_lease_overflow_fail_without_partial_publication() { + let mut epoch = ClaimFrontier::new(37); + epoch.next_epoch = u64::MAX; + assert_eq!(epoch.claim(1), Err(ClaimFrontierError::Exhausted)); + assert!(epoch.records.is_empty()); + + let mut lease = ClaimFrontier::new(41); + lease.next_lease = u64::MAX; + assert_eq!(lease.claim(1), Err(ClaimFrontierError::Exhausted)); + assert_eq!(lease.next_epoch, 0); + assert!(lease.records.is_empty()); + + let mut takeover = ClaimFrontier::new(43); + let token = takeover.claim(1).unwrap(); + takeover.next_lease = u64::MAX; + assert_eq!(takeover.take_over(token, 2), Err(ClaimFrontierError::Exhausted)); + assert_eq!(takeover.observe(43, token.epoch, 1), Ok(ClaimFrontierAction::Progress(token))); } - let mut g = lock_state(); - let Some(s) = g.as_mut() else { - let (start, end) = page_span(a, n); - early_remove(&mut EARLY.lock().unwrap(), start, end); - return; - }; - s.decommit_range(a, n); -} -impl State { - /// `committed` with the state locked - unsafe fn commit_range(&mut self, a: usize, n: usize) { - self.ensure_mapped(a, n, |_| 0xFFFF); - let mut pg = a & !(PAGE - 1); - let end = a.saturating_add(n); - while pg < end { - let t = pg & !(TILE - 1); - let tile_end = t.saturating_add(TILE).min(end); - if let Some(entry) = self.mapped.get_mut(&t) { - let mut p = pg; - while p < tile_end { - entry.holes &= !(1u16 << ((p - t) / PAGE)); - p += PAGE; - } - } - if tile_end <= pg { - break; - } - pg = tile_end; - } + #[test] + fn work_claim_ledger_merges_orders_and_restores_exact_out_of_order_work() { + let mut ledger = WorkClaimLedger::new(7); + ledger.add_zero_ranges(&[(0x3000, 2 * PAGE)]); + ledger.add_retry_pages([0x3001, 0x1000, 0x1000]); + ledger.add_dirty_pages([0x4000, 0x6001, 0x6000]); + + let first = ledger.claim(2).unwrap(); + assert_eq!(first.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x1000, WorkReasons::RETRY.0), + (0x3000, WorkReasons::ZERO.0 | WorkReasons::RETRY.0), + ]); + let second = ledger.claim(8).unwrap(); + assert_eq!(second.pages.iter().map(|(page, reasons)| (*page, reasons.0)).collect::<Vec<_>>(), [ + (0x4000, WorkReasons::ZERO.0 | WorkReasons::DIRTY.0), + (0x6000, WorkReasons::DIRTY.0), + ]); + + ledger.add_dirty_pages([0x1000]); + assert!(ledger.claim(1).is_none(), "new work escaped an older owner of the same page"); + assert_eq!(ledger.cancel(second.token), WorkClaimResolution::Restored); + let out_of_order = ledger.claim(1).unwrap(); + assert_eq!(out_of_order.pages[0].0, 0x4000); + assert_eq!(ledger.commit(first.token), WorkClaimResolution::Committed); + let later = ledger.claim(1).unwrap(); + assert_eq!(later.pages, [(0x1000, WorkReasons::DIRTY)]); + assert_eq!(ledger.commit(later.token), WorkClaimResolution::Committed); + assert_eq!(ledger.cancel(out_of_order.token), WorkClaimResolution::Restored); + let restored = ledger.claim(8).unwrap(); + assert_eq!(restored.pages.iter().map(|(page, _)| *page).collect::<Vec<_>>(), [0x4000, 0x6000]); } - /// `decommitted` with the state locked: the tiles that go are parked (`flush_parked` unmaps - /// them and frees their pool tiles) - unsafe fn decommit_range(&mut self, a: usize, n: usize) { - let mut pools: Vec<(usize, (u32, u32))> = Vec::new(); - let mut t = a & !(TILE - 1); - let end = a.saturating_add(n); - while t < end { - if let Some(e) = self.mapped.get(&t) { - pools.push((t, e.pool)); - } - match t.checked_add(TILE) { - Some(next) => t = next, - None => break, - } - } - let tiles = decommit_tiles(&mut self.mapped, &self.pinned, &mut Vec::new(), &mut self.to_zero, a, n); - if tiles.is_empty() { - return; - } - self.runs = None; - for &t in &tiles { - if let Ok(i) = pools.binary_search_by_key(&t, |p| p.0) { - self.parked.insert(t, pools[i].1); - } - } - MAPPED_GEN.fetch_add(1, Ordering::Release); - if self.parked.len() >= PARKED_MAX && self.flush_parked() { - self.drain_quarantined(); - self.retire_free_pools(); - } + #[test] + fn replaced_sparse_batch_handles_reject_stale_additions() { + let batches = SparseBatches::new(17); + let stale_clone = batches.clone(); + let current = batches.replace_generation(18).unwrap(); + assert!(!batches.add_dirty_pages([0xC000])); + assert!(!stale_clone.add_retry_pages([0xD000])); + assert!(matches!(batches.seal(1, 1), Err(SparseBatchError::StaleGeneration))); + assert!(matches!(stale_clone.replace_generation(19), Err(SparseBatchError::StaleGeneration))); + assert!(current.add_dirty_pages([0xB000])); + assert_eq!(current.seal(1, 1).unwrap().unwrap().pages()[0].0, 0xB000); } - /// a pool tile no window maps, none is parked on and no buffer uses goes back to the free list - fn release_if_unused(&mut self, tile: (u32, u32)) { - if !self.pinned.contains_key(&tile) - && !self.mapped.values().any(|e| e.pool == tile) - && !self.parked.values().any(|&p| p == tile) - && !self.quarantined.iter().any(|b| b.tiles.contains(&tile)) - { - self.free.push(tile); - } + #[test] + fn sparse_batch_takeover_revokes_without_restoring_or_duplicating_work() { + let batches = SparseBatches::new(47); + assert!(batches.add_dirty_pages([0x1_1000])); + let old = batches.seal(1, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + assert_eq!(old.pages()[0].0, 0x1_1000); + + let replacement = old.take_over(2).unwrap(); + assert!(matches!( + old.obsolete(), + Err(SparseBatchError::Frontier(ClaimFrontierError::StaleToken)), + )); + assert_eq!(replacement.pages()[0].0, 0x1_1000); + replacement.accept().unwrap().receipt(5).unwrap(); + assert_eq!( + batches.observe(through, 9), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(5) }), + "the revoked owner restored or duplicated its work", + ); + assert!(batches.seal(3, 1).unwrap().is_none()); } - unsafe fn note_queue(&mut self, q: &ID3D12CommandQueue) -> bool { - let key = q.as_raw() as usize; - if self.queue_fences.contains_key(&key) { - return true; - } - // Ignore queues belonging to a different device (e.g. isolated unit tests). - let mut qdev: Option<ID3D12Device> = None; - if q.GetDevice(&mut qdev).is_err() || qdev.as_ref().is_none_or(|d| d.as_raw() != self.dev.as_raw()) { - return true; - } - match self.dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) { - Ok(fence) => { - self.queue_fences.insert(key, (q.clone(), fence, 0)); - true - } - Err(_) => false, - } + #[test] + fn dropped_pending_batch_remains_visible_for_foreground_takeover() { + let batches = SparseBatches::new(53); + assert!(batches.add_dirty_pages([0x2_1000])); + let abandoned = batches.seal(10, 1).unwrap().unwrap(); + let token = abandoned.token; + let through = batches.through().unwrap(); + drop(abandoned); + assert_eq!(batches.observe(through, 20), Ok(ClaimFrontierAction::TakeOver(token))); + + let foreground = batches.take_over(token, 20).unwrap(); + foreground.accept().unwrap().receipt(7).unwrap(); + assert_eq!( + batches.observe(through, 20), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(7) }), + ); } - unsafe fn sync_known_queues(&mut self) -> bool { - let mut ok = true; - for raw in super::present::known_queues() { - if !self.queue_fences.contains_key(&raw) { - let ptr = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&ptr) { - ok &= self.note_queue(q); - } - } - } - ok + #[test] + fn sparse_batch_producers_are_collected_before_locking() { + use std::sync::atomic::{AtomicBool, Ordering}; + let batches = SparseBatches::new(57); + let unlocked = AtomicBool::new(false); + let ledger = batches.ledger.clone(); + let pages = std::iter::once_with(|| { unlocked.store(ledger.try_lock().is_ok(), Ordering::Relaxed); 0x2_2001 }); + assert!(batches.add_dirty_pages(pages)); + assert!(unlocked.load(Ordering::Relaxed), "a producer iterator ran under the batch lock"); + assert_eq!(batches.seal(1, 1).unwrap().unwrap().pages()[0].0, 0x2_2000); } - unsafe fn quarantine_tiles(&mut self, tiles: Vec<(u32, u32)>) { - if tiles.is_empty() { - return; - } - let mut ok = self.sync_known_queues(); - let mut marks = Vec::with_capacity(1 + self.queue_fences.len()); - marks.push((self.fence.clone(), self.value)); - if ok { - for (q, fence, val) in self.queue_fences.values_mut() { - let next = *val + 1; - if q.Signal(&*fence, next).is_ok() { - *val = next; - marks.push((fence.clone(), next)); - } else { - ok = false; - break; - } - } - } - self.quarantined.push_back(RetiredTiles { tiles, marks: ok.then_some(marks) }); + #[test] + fn sparse_batch_ready_requires_new_reasons_to_be_sealed() { + let batches = SparseBatches::new(59); + assert!(batches.add_dirty_pages([0x3_1000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let first_epoch = batches.through().unwrap(); + assert!(batches.add_dirty_pages([0x3_1001])); + assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); + assert_eq!(batches.observe(first_epoch, 2), Err(SparseBatchError::Unsealed)); + + first.accept().unwrap().receipt(8).unwrap(); + assert_eq!(batches.through(), Err(SparseBatchError::Unsealed)); + let successor = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + assert!(through > first_epoch); + successor.obsolete().unwrap(); + assert_eq!( + batches.observe(through, 2), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(8) }), + ); } - unsafe fn drain_quarantined(&mut self) -> bool { - let mut freed = false; - while let Some(front) = self.quarantined.front() { - let ready = front.marks.as_ref().is_some_and(|marks| marks.iter().all(|(f, v)| f.GetCompletedValue() >= *v)); - if !ready { - break; - } - let batch = self.quarantined.pop_front().unwrap(); - for tile in batch.tiles { - if !self.pinned.contains_key(&tile) { - self.free.push(tile); - freed = true; - } - } - } - freed + #[test] + fn sparse_batch_receipts_are_contiguous_and_acceptance_is_fail_closed() { + let batches = SparseBatches::new(61); + assert!(batches.add_dirty_pages([0x4_1000, 0x4_2000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let second = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first_token = first.token; + let first = first.accept().unwrap(); + let second = second.accept().unwrap(); + second.receipt(11).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + first.receipt(8).unwrap(); + assert_eq!( + batches.observe(through, 3), + Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) }), + ); + + assert!(batches.add_dirty_pages([0x4_3000])); + let accepted = batches.seal(4, 1).unwrap().unwrap().accept().unwrap(); + let accepted_token = accepted.token.unwrap().0; + assert!(matches!( + batches.take_over(accepted_token, 5), + Err(SparseBatchError::Frontier(ClaimFrontierError::WrongState)), + )); + drop(accepted); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let current = batches.replace_generation(62).unwrap(); + assert_eq!(batches.through(), Err(SparseBatchError::StaleGeneration)); + assert!(matches!(current.replace_generation(61), Err(SparseBatchError::StaleGeneration))); + assert!(matches!(current.take_over(accepted_token, 6), Err(SparseBatchError::StaleGeneration))); + assert!(current.add_dirty_pages([0x5_1000])); + let stale = current.seal(6, 1).unwrap().unwrap(); + let replacement = current.replace_generation(63).unwrap(); + assert_eq!(stale.obsolete(), Err(SparseBatchError::StaleGeneration)); + assert_eq!(replacement.through(), Ok(0)); + assert!(matches!(SparseBatches::new(u64::MAX).replace_generation(0), Err(SparseBatchError::StaleGeneration))); } - /// The parked tiles unmapped from their windows (one call per window) and their unpinned - /// pool tiles quarantined behind `self.queue` and every known title queue's completion fence. - /// Pools left all free are not retired here: callers do that (`retire_free_pools`) unless - /// they take a tile right away. - unsafe fn flush_parked(&mut self) -> bool { - if self.parked.is_empty() { - return false; - } - let mut by_window: FxHashMap<usize, Vec<usize>> = FxHashMap::default(); - let mut tiles: Vec<(u32, u32)> = Vec::new(); - for (t, tile) in std::mem::take(&mut self.parked) { - if let Some(wi) = self.window_index(t) { - by_window.entry(wi).or_default().push(t); - } - if !self.pinned.contains_key(&tile) { - tiles.push(tile); - } - } - for (wi, ts) in by_window { - let (b, r) = (self.windows[wi].0, self.windows[wi].1.clone()); - self.unmap_tiles(&r, b, &ts); - } - self.signal(); - self.quarantine_tiles(tiles); - true + fn wait_ready(fence: SparseFenceIdentity, through: u64, value: Option<u64>) -> SparseReadyReceipt { + SparseReadyReceipt { state_generation: fence.state_generation, fence, through, required_fence: value } } -} -/// The sparse windows' tiles with video memory as sorted (start, end) runs: where a CPU write -/// has to reach the GPU. -pub fn mapped_ranges() -> Vec<(usize, usize)> { - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return Vec::new() }; - if s.runs.is_none() { - let mut tiles: Vec<usize> = s.mapped.keys().copied().collect(); - tiles.sort_unstable(); - let mut runs: Vec<(usize, usize)> = Vec::new(); - for t in tiles { - match runs.last_mut() { - Some(last) if last.1 == t => last.1 = t + TILE, - _ => runs.push((t, t + TILE)), - } - } - s.runs = Some(runs); + fn wait_reservation(decision: ForegroundWaitDecision) -> ForegroundWaitReservation { + match decision { ForegroundWaitDecision::Reserve(reservation) => reservation, _ => panic!("wait not reserved") } + } + + #[test] + fn foreground_wait_pairs_out_of_order_frontier_with_exact_fence() { + let batches = SparseBatches::with_fence(101, 501).unwrap(); + assert!(batches.add_dirty_pages([0x6_1000, 0x6_2000])); + let first = batches.seal(1, 1).unwrap().unwrap(); + let first_token = first.token; + let second = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first = first.accept().unwrap(); + second.accept().unwrap().receipt(11).unwrap(); + let waits = ForegroundWaits::new(101, 501).unwrap(); + let queue = waits.register_queue(0xA).unwrap(); + assert_eq!(waits.register_queue(0xA), Ok(queue)); + assert_eq!(batches.ready_receipt(through, 3), Err(ForegroundWaitError::NotReady)); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + first.receipt(8).unwrap(); + + let ready = batches.ready_receipt(through, 3).unwrap(); + let wrong = SparseReadyReceipt { fence: SparseFenceIdentity { allocation: 502, ..ready.fence }, ..ready }; + assert!(matches!(waits.reserve(queue, wrong), Err(ForegroundWaitError::Fence))); + let reservation = wait_reservation(waits.reserve(queue, ready).unwrap()); + assert_eq!(reservation.arm().unwrap().publish(), Ok((through, 11))); + assert!(matches!(waits.reserve(queue, ready), Ok(ForegroundWaitDecision::Installed { through: t, value: 11 }) if t == through)); + assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), through + 1, None)), + Ok(ForegroundWaitDecision::NoWait { through: t }) if t == through + 1)); + + let other = SparseBatches::with_fence(101, 502).unwrap(); + let other_waits = ForegroundWaits::new(101, 502).unwrap(); + let other_queue = other_waits.register_queue(0xE).unwrap(); + assert!(matches!(other.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(_)))); + assert!(matches!(other_waits.reserve(other_queue, ready), Err(ForegroundWaitError::Fence))); + + assert!(matches!(batches.replace_generation_with_fence(102, 501), Err(SparseBatchError::Fence))); + let stale = batches.clone(); + let batches = batches.replace_generation_with_fence(102, 503).unwrap(); + assert_eq!(batches.ledger.lock().unwrap().fence.unwrap().allocation, 503); + assert_eq!(stale.ready_receipt(through, 3), Err(ForegroundWaitError::Batch(SparseBatchError::StaleGeneration))) } - s.runs.clone().unwrap_or_default() -} -/// time spent and pages found by the write-watch scans (`refresh_once`), for the timing line -static WATCH: [AtomicU64; 2] = [AtomicU64::new(0), AtomicU64::new(0)]; -/// [lock wait, chunk scan, upload] in µs, runs uploaded -static PHASES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + #[test] + fn foreground_wait_rollbacks_are_exact_and_queue_reuse_is_stale() { + let waits = ForegroundWaits::new(103, 601).unwrap(); + let fence = waits.fence(); + let queue = waits.register_queue(0xB).unwrap(); + let ready = wait_ready(fence, 1, Some(5)); + let abandoned = wait_reservation(waits.reserve(queue, ready).unwrap()); + let stale = abandoned.token.unwrap(); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == stale)); + assert!(matches!(waits.reserve(queue, wait_ready(fence, 0, None)), Err(ForegroundWaitError::Pending(_)))); + drop(abandoned); + + let accepted = wait_reservation(waits.reserve(queue, wait_ready(fence, 2, Some(6))).unwrap()).arm().unwrap(); + let accepted_token = accepted.token.unwrap(); + accepted.rollback().unwrap(); + let newer = wait_reservation(waits.reserve(queue, wait_ready(fence, 3, Some(7))).unwrap()); + assert_eq!(waits.0.lock().unwrap().transition(accepted_token, ForegroundWaitState::Accepted, None), + Err(ForegroundWaitError::StaleToken)); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Pending(token)) if token == newer.token.unwrap())); + drop(newer); + waits.retire_queue(queue).unwrap(); + let replacement = waits.register_queue(0xB).unwrap(); + assert!(replacement.generation > queue.generation); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Queue))); + assert!(matches!(waits.reserve(replacement, ready), Ok(ForegroundWaitDecision::Reserve(_)))); + } -pub fn note_watch(t: std::time::Duration, pages: usize) { - WATCH[0].fetch_add(t.as_micros() as u64, Ordering::Relaxed); - WATCH[1].fetch_add(pages as u64, Ordering::Relaxed); -} + #[test] + fn foreground_wait_unpublished_acceptance_fails_closed() { + let waits = ForegroundWaits::new(107, 701).unwrap(); + let queue = waits.register_queue(0xC).unwrap(); + let ready = wait_ready(waits.fence(), 1, Some(9)); + let accepted = wait_reservation(waits.reserve(queue, ready).unwrap()).arm().unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || { + let _accepted = accepted; + panic!("after native wait acceptance"); + })); + assert!(result.is_err()); + assert!(matches!(waits.reserve(queue, ready), Err(ForegroundWaitError::Uncertain))); + assert!(matches!(waits.reserve(queue, wait_ready(waits.fence(), 0, None)), Err(ForegroundWaitError::Uncertain))); + } -/// Before the title's ExecuteCommandLists on `queue`: the pages the CPU wrote (`dirty`, 4 KiB -/// pages from the write-watch, sorted) and the reused tiles are copied asynchronously into video -/// memory, and `queue` GPU-waits for that and for new tile mappings. -pub unsafe fn before_execute(queue: &ID3D12CommandQueue, dirty: &[usize], page: usize) { - let t0 = std::time::Instant::now(); - let mut g = lock_state(); - let Some(s) = g.as_mut() else { return }; - s.note_queue(queue); - // the title's work sees what was decommitted unmapped, as it was - let flushed = s.flush_parked(); - let drained = s.drain_quarantined(); - if flushed || drained { - s.retire_free_pools(); + #[test] + fn foreground_wait_generation_replacement_rejects_old_guards_and_fences() { + let waits = ForegroundWaits::new(109, 801).unwrap(); + let queue = waits.register_queue(0xD).unwrap(); + let old_fence = waits.fence(); + let old_ready = wait_ready(old_fence, 1, Some(3)); + let old = wait_reservation(waits.reserve(queue, old_ready).unwrap()); + waits.replace_generation(109, 110, 802).unwrap(); + drop(old); + assert!(matches!(waits.reserve(queue, old_ready), Err(ForegroundWaitError::StaleGeneration))); + assert_eq!(waits.replace_generation(110, 109, 803), Err(ForegroundWaitError::StaleGeneration)); + assert_eq!(waits.replace_generation(110, 111, 801), Err(ForegroundWaitError::Fence)); + let current = wait_ready(waits.fence(), 1, Some(4)); + assert!(matches!(waits.reserve(queue, current), Ok(ForegroundWaitDecision::Reserve(_)))); + } + + fn upload_observation(page: usize, pool: (u32, u32), source_word: u64) -> UploadPageObservation { + let mut source = ZERO_HASHES; + source[1] = source_word; + source[2] = source_word; + UploadPageObservation { page, pool, hole: false, sent: Some(ZERO_HASHES), source } } - let t_locked = std::time::Instant::now(); - PHASES[0].fetch_add((t_locked - t0).as_micros() as u64, Ordering::Relaxed); - let zero_runs = std::mem::take(&mut s.to_zero); - for &(a, n) in &zero_runs { - s.clear_sent_range(a, n); + + fn coordinated_upload_fixture( + owner: u64, + ) -> (SparseBatches, CoordinatedSparseUploadPlan, UploadPageObservation, ClaimFrontierToken) { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x2_1000])); + let lease = batches.seal(owner, 1).unwrap().unwrap(); + let token = lease.token; + let observation = upload_observation(0x2_1000, (4, 9), 0xA5); + let plan = CoordinatedSparseUploadPlan::build(lease, 71, 7, |_| Some(observation.clone())).unwrap(); + (batches, plan, observation, token) } - let mut dirty_runs = std::mem::take(&mut s.scratch_runs); - dirty_runs.clear(); - let mut i = 0; - while i < dirty.len() { - let a = dirty[i]; - let mut n = page; - i += 1; - while i < dirty.len() && dirty[i] == a + n { - n += page; - i += 1; - } - // only what has video memory (committed tiles of a sparse window) - let mut x = a; - while x < a + n { - let t = x & !(TILE - 1); - let end = (t + TILE).min(a + n); - if let Some(entry) = s.mapped.get_mut(&t) { - let mut pg = x & !(PAGE - 1); - while pg < end { - let idx = (pg - t) / PAGE; - if entry.holes & (1u16 << idx) == 0 { - let bytes = std::slice::from_raw_parts(pg as *const u8, PAGE); - scan_page(bytes, pg, &mut entry.sent[idx], &mut dirty_runs); - } - pg += PAGE; - } - } - x = end; - } + + fn commit_coordinated( + plan: CoordinatedSparseUploadPlan, observation: &UploadPageObservation, + reservations: &UploadReservations, slot: usize, fence: u64, + ) -> Result<UploadSubmissionReceipt, CoordinatedSparseUploadError<(), (), ()>> { + plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), reservations, slot, 64, + |_, _| Ok(vec![0; 64]), |_, _| Ok(()), |_, _| {}, || Ok(fence), + ) } - let t_scanned = std::time::Instant::now(); - PHASES[1].fetch_add((t_scanned - t_locked).as_micros() as u64, Ordering::Relaxed); - PHASES[3].fetch_add((zero_runs.len() + dirty_runs.len()) as u64, Ordering::Relaxed); - // Submit tile clears before CPU writes so overlapping CopyBufferRegion destinations have no WAW hazard. - if !zero_runs.is_empty() { - s.upload_zeros(&zero_runs); + + #[test] + fn shared_upload_page_builder_preserves_intent_order_and_dirty_ranges() { + let claimed = [ + (0x1_1000, WorkReasons(WorkReasons::ZERO.0 | WorkReasons::DIRTY.0)), + (0x1_2000, WorkReasons::RETRY), + ]; + let first = upload_observation(0x1_1000, (2, 3), 0x91); + let second = upload_observation(0x1_2000, (2, 3), ZERO_HASH); + let pages = build_upload_pages(&claimed, |page| match page { + 0x1_1000 => Some(first.clone()), + 0x1_2000 => Some(second.clone()), + _ => None, + }).unwrap(); + + assert_eq!(pages.iter().map(|page| page.page).collect::<Vec<_>>(), [0x1_1000, 0x1_2000]); + assert!(pages[0].zero && pages[0].dirty); + assert_eq!(pages[0].dirty_ranges, [(0x1_1000 + CHUNK, 2 * CHUNK)]); + assert!(!pages[1].zero && pages[1].dirty); + assert!(pages[1].dirty_ranges.is_empty(), "retry intent was lost when no chunks changed"); + assert!(build_upload_pages(&claimed, |page| { + (page == 0x1_1000).then(|| first.clone()) + }).is_none()); } - if !dirty_runs.is_empty() { - s.upload_dirty(&dirty_runs); + + #[test] + fn coordinated_plan_revalidates_every_sparse_page_identity() { + let (_, plan, observation, _) = coordinated_upload_fixture(1); + assert_eq!(plan.validate(72, 7, |_| Some(observation.clone())), Err(UploadPlanInvalid::StateGeneration)); + assert_eq!(plan.validate(71, 8, |_| Some(observation.clone())), Err(UploadPlanInvalid::MappingEpoch)); + assert_eq!(plan.validate(71, 7, |_| None), Err(UploadPlanInvalid::MissingPage)); + + let mut remapped = observation.clone(); + remapped.page += TILE; + assert_eq!(plan.validate(71, 7, |_| Some(remapped.clone())), Err(UploadPlanInvalid::Mapping)); + let mut repooled = observation.clone(); + repooled.pool.1 += 1; + assert_eq!(plan.validate(71, 7, |_| Some(repooled.clone())), Err(UploadPlanInvalid::Mapping)); + let mut hole = observation.clone(); + hole.hole = true; + assert_eq!(plan.validate(71, 7, |_| Some(hole.clone())), Err(UploadPlanInvalid::Mapping)); + let mut resent = observation.clone(); + resent.sent.as_mut().unwrap()[3] ^= 1; + assert_eq!(plan.validate(71, 7, |_| Some(resent.clone())), Err(UploadPlanInvalid::SentHashes)); + let mut rewritten = observation.clone(); + rewritten.source[3] ^= 1; + assert_eq!(plan.validate(71, 7, |_| Some(rewritten.clone())), Err(UploadPlanInvalid::SourceHashes)); } - PHASES[2].fetch_add(t_scanned.elapsed().as_micros() as u64, Ordering::Relaxed); - { - static CALLS: AtomicU64 = AtomicU64::new(0); - static BYTES: AtomicU64 = AtomicU64::new(0); - static MICROS: AtomicU64 = AtomicU64::new(0); - let bytes: usize = zero_runs.iter().chain(dirty_runs.iter()).map(|r| r.1).sum(); - let n = CALLS.fetch_add(1, Ordering::Relaxed) + 1; - let b = BYTES.fetch_add(bytes as u64, Ordering::Relaxed) + bytes as u64; - let us = MICROS.fetch_add(t0.elapsed().as_micros() as u64, Ordering::Relaxed) + t0.elapsed().as_micros() as u64; - if n.is_power_of_two() && n >= 16 { - crate::xlog_info!("sparse windows: {n} submits, {} MB of CPU writes uploaded, {} ms spent, {} tiles mapped", b >> 20, us / 1000, s.mapped.len()); - let ms = |x: &AtomicU64| x.load(Ordering::Relaxed) / 1000; - crate::xlog_info!( - "sparse windows timing: write-watch {} ms ({} dirty pages), lock wait {} ms, chunk scan {} ms, upload {} ms ({} runs)", - ms(&WATCH[0]), - WATCH[1].load(Ordering::Relaxed), - ms(&PHASES[0]), - ms(&PHASES[1]), - ms(&PHASES[2]), - PHASES[3].load(Ordering::Relaxed) + + #[test] + fn coordinated_preaccept_unwind_cancels_reservation_and_leaves_batch_visible() { + for panic_at in ["copy", "prepare"] { + let (batches, plan, observation, token) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| -> Result<Vec<u8>, ()> { + if panic_at == "copy" { panic!("copy panicked") } + Ok(vec![0; 64]) + }, + |_, _| -> Result<(), ()> { + if panic_at == "prepare" { panic!("prepare panicked") } + Ok(()) + }, + |_, _| {}, || Ok::<_, ()>(9), + ); + })); + assert!(result.is_err()); + assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); + let ledger = reservations.0.lock().unwrap(); + assert!(!ledger.poisoned && ledger.records.is_empty()); + assert!(ledger.slots.iter().all(Option::is_none)); + } + } + + #[test] + fn coordinated_commit_orders_callbacks_and_owns_copied_staging() { + let (_, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let calls = std::cell::RefCell::new(Vec::new()); + let receipt = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 4, + |range, pages| { + calls.borrow_mut().push("copy"); + assert_eq!(range, UploadRingRange { start: 0, end: 4 }); + assert_eq!(pages[0].page, observation.page); + Ok::<_, ()>(vec![1, 2, 3, 4]) + }, + |staging, _| { + calls.borrow_mut().push("prepare"); + assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); + Ok::<_, ()>(()) + }, + |staging, _| { + calls.borrow_mut().push("execute"); + assert_eq!(&*staging.bytes, &[1, 2, 3, 4]); + }, + || { calls.borrow_mut().push("signal"); Ok::<_, ()>(9) }, + ).unwrap(); + assert_eq!(&*calls.borrow(), &["copy", "prepare", "execute", "signal"]); + assert_eq!(reservations.complete(receipt), Ok(4)); + } + + #[test] + fn coordinated_plan_preaccept_failures_stay_visible_and_takeover_revokes() { + for failure in ["validate", "reservation generation", "reserve", "copy", "size", "prepare"] { + let (batches, plan, observation, token) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(if failure == "reservation generation" { 72 } else { 71 }, 1, 256, 64); + let occupied = (failure == "reserve").then(|| reservations.reserve(0, 64).unwrap()); + let result = plan.commit_reserved( + if failure == "validate" { 72 } else { 71 }, 7, |_| Some(observation.clone()), + &reservations, 0, 64, + |_, _| if failure == "copy" { Err("copy") } else { Ok(vec![0; if failure == "size" { 63 } else { 64 }]) }, + |_, _| if failure == "prepare" { Err("prepare") } else { Ok(()) }, + |_, _| {}, || Ok::<_, &'static str>(9), ); + let expected = match failure { + "validate" => matches!(result, Err(CoordinatedSparseUploadError::Invalid(UploadPlanInvalid::StateGeneration))), + "reservation generation" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::StaleGeneration))), + "reserve" => matches!(result, Err(CoordinatedSparseUploadError::Reserve(UploadReservationError::SlotBusy))), + "copy" => matches!(result, Err(CoordinatedSparseUploadError::Copy("copy"))), + "size" => matches!(result, Err(CoordinatedSparseUploadError::StagingSize)), + _ => matches!(result, Err(CoordinatedSparseUploadError::Prepare("prepare"))), + }; + assert!(expected, "wrong {failure} boundary result"); + assert_eq!(batches.observe(1, 9), Ok(ClaimFrontierAction::TakeOver(token))); + assert!(!reservations.0.lock().unwrap().poisoned); + drop(occupied); } + + let (batches, stale, observation, token) = coordinated_upload_fixture(1); + let replacement = batches.take_over(token, 2).unwrap(); + let result = commit_coordinated(stale, &observation, &UploadReservations::new(71, 1, 256, 64), 0, 9); + assert!(matches!(result, Err(CoordinatedSparseUploadError::Accept( + SparseBatchError::Frontier(ClaimFrontierError::StaleToken) + )))); + assert_eq!(replacement.pages()[0].0, 0x2_1000); } - dirty_runs.clear(); - s.scratch_runs = dirty_runs; - let q = queue.as_raw() as usize; - if s.value > 0 && s.waited.get(&q).copied().unwrap_or(0) < s.value { - let _ = queue.Wait(&s.fence, s.value); - super::list_x::note_internal_wait(q, "sparse uploads and tile mappings", &s.fence, s.value); - s.waited.insert(q, s.value); + + #[test] + fn coordinated_submit_then_panic_poisons_both_generations() { + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let submitted = std::cell::Cell::new(false); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _ = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), + |_, _| { submitted.set(true); panic!("execute panicked after submit") }, + || Ok::<_, ()>(9), + ); + })); + assert!(result.is_err() && submitted.get()); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + let result = plan.commit_reserved( + 71, 7, |_| Some(observation.clone()), &reservations, 0, 64, + |_, _| Ok::<_, ()>(vec![0; 64]), |_, _| Ok::<_, ()>(()), |_, _| {}, || Err::<u64, _>("signal"), + ); + assert!(matches!(result, Err(CoordinatedSparseUploadError::Signal("signal")))); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); + + let (batches, plan, observation, _) = coordinated_upload_fixture(1); + let reservations = UploadReservations::new(71, 1, 256, 64); + assert!(matches!(commit_coordinated(plan, &observation, &reservations, 0, 0), + Err(CoordinatedSparseUploadError::PublishReservation(UploadReservationError::State)))); + assert!(reservations.0.lock().unwrap().poisoned); + assert_eq!(batches.through(), Err(SparseBatchError::Poisoned)); } -} -/// A buffer the title places at `va` in a sparse window (`bytes` long, `desc` the PC -/// description): a reserved resource over the window's tiles there, starting at the 64 KiB -/// below `va` (returned: its distance from there). -pub unsafe fn place_buffer(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, state: u32, riid: *const windows_sys::core::GUID, ppv: *mut *mut c_void) -> Option<(crate::util::HRESULT, usize)> { - let mut g = lock_state(); - let s = g.as_mut()?; - let start = va & !(TILE - 1); - let delta = va - start; - let bytes = desc.Width as usize; - if bytes == 0 { - return None; + #[test] + fn coordinated_frontier_publication_failure_quarantines_submitted_reservation() { + let (batches, plan, _, _) = coordinated_upload_fixture(1); + let lease = plan.lease.unwrap(); + let batch = lease.accept().unwrap(); + let reservations = UploadReservations::new(71, 1, 256, 64); + let reservation = reservations.reserve(0, 64).unwrap(); + let mut accepted = AcceptedCoordinatedUpload::new(reservation, batch); + let receipt = accepted.reservation.take().unwrap().publish_after_accept(13).unwrap(); + accepted.batch_ledger.lock().unwrap().bindings.remove(&accepted.batch_token.epoch); + assert_eq!(accepted.batch.take().unwrap().receipt(13), Err(SparseBatchError::Corrupt)); + drop(accepted); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert_eq!(ledger.records[&receipt.token.serial].state, UploadReservationState::Poisoned); + drop(ledger); + let ledger = batches.ledger.lock().unwrap(); + assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); + assert!(ledger.bindings.is_empty()); } - s.window_index(start)?; - s.window_index(va.checked_add(bytes)?.checked_sub(1)?)?; - let mut d = *desc; - d.Width = (delta + bytes) as u64; - d.Alignment = 0; - d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; - // Reserved buffers only accept NONE or ALLOW_UNORDERED_ACCESS (strip console flags and ALLOW_CROSS_ADAPTER). - d.Flags &= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; - if state & (D3D12_RESOURCE_STATE_UNORDERED_ACCESS.0 as u32 | D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE.0 as u32) != 0 { - d.Flags |= D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + + #[test] + fn a_prior_poison_does_not_leave_later_accepted_work_owned() { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x3_1000, 0x3_2000])); + let first = batches.seal(1, 1).unwrap().unwrap().accept().unwrap(); + let second = batches.seal(2, 1).unwrap().unwrap().accept().unwrap(); + let reservations = UploadReservations::new(71, 2, 256, 64); + let first = AcceptedCoordinatedUpload::new(reservations.reserve(0, 64).unwrap(), first); + let second = AcceptedCoordinatedUpload::new(reservations.reserve(1, 64).unwrap(), second); + drop(first); + assert!(matches!(second.publish(17), Err(CoordinatedPublishError::Batch(SparseBatchError::Poisoned)))); + let ledger = batches.ledger.lock().unwrap(); + assert!(ledger.poisoned && ledger.work.claims.is_empty() && ledger.work.owners.is_empty()); + assert!(ledger.bindings.is_empty()); + drop(ledger); + let reservations = reservations.0.lock().unwrap(); + assert!(reservations.poisoned && reservations.records.values().all(|r| r.state == UploadReservationState::Poisoned)); } - let hr = super::real::dev_create_reserved_resource(this, &d as *const _ as usize, state as usize, 0, riid, ppv); - if hr < 0 || ppv.is_null() || (*ppv).is_null() { - return None; + + #[test] + fn coordinated_receipts_publish_exact_out_of_order_fence_prefix() { + let batches = SparseBatches::new(71); + assert!(batches.add_dirty_pages([0x2_1000, 0x2_2000])); + let observation = |page| upload_observation(page, (4, 9), 0xA5); + let first_lease = batches.seal(1, 1).unwrap().unwrap(); + let first_token = first_lease.token; + let second_lease = batches.seal(2, 1).unwrap().unwrap(); + let through = batches.through().unwrap(); + let first = CoordinatedSparseUploadPlan::build(first_lease, 71, 7, |page| Some(observation(page))).unwrap(); + let second = CoordinatedSparseUploadPlan::build(second_lease, 71, 7, |page| Some(observation(page))).unwrap(); + let reservations = UploadReservations::new(71, 2, 256, 64); + let second_receipt = commit_coordinated(second, &observation(0x2_2000), &reservations, 1, 11).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::WaitForReceipt(first_token))); + let first_receipt = commit_coordinated(first, &observation(0x2_1000), &reservations, 0, 8).unwrap(); + assert_eq!(batches.observe(through, 3), Ok(ClaimFrontierAction::Ready { through, required_fence: Some(11) })); + assert_eq!(reservations.complete(first_receipt), Ok(0)); + assert_eq!(reservations.complete(second_receipt), Ok(128)); } - // its tiles: the window's video memory at the same addresses; probe actual OS commitment - // so uncommitted pages (e.g. [start, va) or reserved tails) stay marked as holes - s.ensure_mapped(start, delta + bytes, |t| query_tile_holes(t)); - let tiles: Vec<(usize, (u32, u32))> = (start..va + bytes).step_by(TILE).filter_map(|t| s.mapped.get(&t).map(|e| (t, e.pool))).collect(); - let raw = *ppv; - let res = ID3D12Resource::from_raw_borrowed(&raw)?.clone(); - s.map_tiles(&res, start, &tiles); - for &(_, tile) in &tiles { - *s.pinned.entry(tile).or_default() += 1; + + #[test] + fn upload_reservations_reclaim_only_a_contiguous_retired_prefix() { + let reservations = UploadReservations::new(41, 2, 256, 64); + let first = reservations.reserve(0, 80).unwrap(); + let second = reservations.reserve(1, 80).unwrap(); + assert_eq!(first.range(), UploadRingRange { start: 0, end: 80 }); + assert_eq!(second.range(), UploadRingRange { start: 128, end: 208 }); + let first = first.submit(5).unwrap(); + let second = second.submit(6).unwrap(); + + assert_eq!(reservations.complete(second), Ok(0), "later retirement crossed an older owner"); + assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Full))); + assert_eq!(reservations.complete(first), Ok(208)); + + let wrapped = reservations.reserve(1, 64).unwrap(); + assert_eq!(wrapped.range(), UploadRingRange { start: 256, end: 320 }); + assert_eq!(wrapped.submit(7).and_then(|receipt| reservations.complete(receipt)), Ok(320)); } - s.buffers.insert(raw as usize, tiles.iter().map(|x| x.1).collect()); - s.signal(); - Some((hr, delta)) -} -/// Placed buffers released while `STATE` was held, let go by the next `lock_state`. Held only -/// to push or take, never across a call out. -static FORGOTTEN: Mutex<Vec<usize>> = Mutex::new(Vec::new()); + #[test] + fn an_empty_ring_discards_tail_padding_before_a_full_capacity_reservation() { + let reservations = UploadReservations::new(42, 1, 256, 64); + drop(reservations.reserve(0, 64).unwrap()); + { + let ledger = reservations.0.lock().unwrap(); + assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); + } -/// `STATE`, with the buffers released while it was held let go first. -fn lock_state() -> std::sync::MutexGuard<'static, Option<State>> { - let mut g = STATE.lock().unwrap(); - forget_released(&mut g); - g -} + let full = reservations.reserve(0, 256).unwrap(); + assert_eq!(full.range(), UploadRingRange { start: 256, end: 512 }); + let ledger = reservations.0.lock().unwrap(); + assert_eq!((ledger.cursor, ledger.reclaimed), (512, 256)); + } -fn forget_released(g: &mut Option<State>) { - let gone = std::mem::take(&mut *FORGOTTEN.lock().unwrap()); - let Some(s) = g.as_mut() else { return }; - for res in gone { - forget_in(s, res); + #[test] + fn failed_empty_ring_reservation_does_not_publish_boundary_normalization() { + let mut ledger = UploadReservationLedger::new(42, 1, 256, 64); + let token = ledger.reserve(42, 0, 64).unwrap().0; + assert_eq!(ledger.cancel(token), Ok(64)); + ledger.next_serial = u64::MAX; + + assert!(matches!(ledger.reserve(42, 0, 256), Err(UploadReservationError::Exhausted))); + assert_eq!((ledger.cursor, ledger.reclaimed), (64, 64)); + assert_eq!(ledger.next_serial, u64::MAX); + assert!(ledger.order.is_empty()); + assert!(ledger.records.is_empty()); + assert!(ledger.slots[0].is_none()); } -} -/// A placed buffer is gone: its tiles are not pinned by it any more. This runs from the -/// resource's last Release, which D3D12 can make while it holds a lock of its own (in a title's -/// command list Reset), and `before_execute` calls D3D12 with `STATE` held: waiting for `STATE` -/// here deadlocked the two threads. So it does not wait: with `STATE` held, the holder's next -/// `lock_state` lets the buffer go. -pub fn forget_buffer(res: usize) { - FORGOTTEN.lock().unwrap().push(res); - match STATE.try_lock() { - Ok(mut g) => forget_released(&mut g), - Err(std::sync::TryLockError::WouldBlock) => {} - Err(e) => panic!("sparse state: {e}"), + #[test] + fn cancelling_an_older_reservation_never_rewinds_newer_ring_work() { + let reservations = UploadReservations::new(43, 3, 512, 64); + let first = reservations.reserve(0, 64).unwrap(); + let middle = reservations.reserve(1, 64).unwrap(); + let third = reservations.reserve(2, 64).unwrap(); + let middle_token = middle.token.unwrap(); + drop(middle); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 0); + + let later = reservations.reserve(1, 64).unwrap(); + assert!(later.range().start >= third.range().end, "a cancellation rewound across newer work"); + drop(first); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 128); + assert_eq!(reservations.0.lock().unwrap().cancel(middle_token), Err(UploadReservationError::Missing)); + + let third = third.submit(8).unwrap(); + assert_eq!(reservations.complete(UploadSubmissionReceipt { fence: 9, ..third }), Err(UploadReservationError::Fence)); + assert_eq!(reservations.complete(third), Ok(192)); + drop(later); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 256); } -} -fn forget_in(s: &mut State, res: usize) { - let Some(tiles) = s.buffers.remove(&res) else { return }; - for tile in tiles { - if let Some(c) = s.pinned.get_mut(&tile) { - *c -= 1; - if *c == 0 { - s.pinned.remove(&tile); - s.release_if_unused(tile); - } - } + #[test] + fn dropped_reservation_cancels_exactly_it_and_signal_failure_poisons_reuse() { + let reservations = UploadReservations::new(47, 2, 256, 64); + let abandoned = reservations.reserve(0, 64).unwrap(); + let stale = abandoned.token.unwrap(); + drop(abandoned); + assert_eq!(reservations.0.lock().unwrap().reclaimed, 64); + assert_eq!(reservations.0.lock().unwrap().cancel(stale), Err(UploadReservationError::Missing)); + + let poisoned = reservations.reserve(0, 64).unwrap(); + poisoned.poison().unwrap(); + let ledger = reservations.0.lock().unwrap(); + assert!(ledger.poisoned); + assert_eq!(ledger.slots[0], Some(2), "poison released an allocator with untracked GPU work"); + drop(ledger); + assert!(matches!(reservations.reserve(1, 64), Err(UploadReservationError::Poisoned))); } -} -#[cfg(test)] -mod tests { - use super::*; + #[test] + fn upload_reservation_bounds_generation_and_monotonic_overflow_fail_closed() { + let mut ledger = UploadReservationLedger::new(53, 1, 256, 64); + assert!(matches!(ledger.reserve(52, 0, 64), Err(UploadReservationError::StaleGeneration))); + assert!(matches!(ledger.reserve(53, 1, 0), Err(UploadReservationError::Slot))); + assert!(matches!(ledger.reserve(53, 0, 0), Err(UploadReservationError::Empty))); + assert!(matches!(ledger.reserve(53, 0, 257), Err(UploadReservationError::TooLarge))); + + ledger.cursor = u64::MAX - 31; + assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); + ledger.cursor = 0; + ledger.next_serial = u64::MAX; + assert!(matches!(ledger.reserve(53, 0, 64), Err(UploadReservationError::Exhausted))); + assert!(ledger.records.is_empty()); + assert!(ledger.order.is_empty()); + assert!(ledger.slots[0].is_none()); + } - /// `queue()` answers while the state's lock is held: a resource's last `Release` asks for - /// it (`late_release::drain_known`) from inside a D3D12 call that the lock's holder can be - /// waiting for (a list's `Reset` against an upload's allocator `Reset`, with `XCL_DRED=1`). #[test] - fn the_queue_is_answered_while_the_state_is_locked() { - let held = STATE.lock().unwrap(); - let (tx, rx) = std::sync::mpsc::channel(); - let asked = std::thread::spawn(move || { - let _ = queue(); - let _ = tx.send(()); - }); - let answered = rx.recv_timeout(std::time::Duration::from_secs(5)).is_ok(); - drop(held); - asked.join().unwrap(); - assert!(answered, "queue() waited for the sparse state's lock"); + fn a_failed_title_queue_wait_rolls_back_only_its_reservation() { + let mut waited = FxHashMap::from_iter([(1, 4), (2, 7)]); + assert!(reserve_queue_wait(&mut waited, 1, 5)); + rollback_queue_wait(&mut waited, 1, 5, Some(4)); + assert_eq!(waited, FxHashMap::from_iter([(1, 4), (2, 7)])); + rollback_queue_wait(&mut waited, 1, 9, None); + assert_eq!(waited.get(&1), Some(&4), "a stale failure changed a newer reservation"); + } + + #[test] + fn quarantine_uses_installed_retirement_marks_and_fails_closed_without_one() { + use std::sync::Arc; + let own = Arc::new(1u32); + let retired = Arc::new(2u32); + let marks = initial_quarantine_marks((own.clone(), 3), &[(retired.clone(), 4)], false).unwrap(); + assert_eq!(marks.iter().map(|(_, value)| *value).collect::<Vec<_>>(), [3, 4]); + drop(retired); + assert_eq!(Arc::strong_count(&marks[1].0), 1, "batch did not own the retirement marker"); + assert!(initial_quarantine_marks((own, 3), &[(marks[1].0.clone(), 4)], true).is_none(), "Preparing/Failed reused tiles without a completion source"); } /// A block freed on one thread while another allocates: its address goes back to the @@ -1811,7 +5355,7 @@ mod tests { /// Freeing the last tile in use of a pool and taking a tile again takes the retired pool - /// back, not a new 64 MB heap each time (#913: 288 pools, 18 GB asked of a 12 GB card). + /// back, not a new heap each time (#913: 288 pools of 64 MB, 18 GB asked of a 12 GB card). #[test] fn a_pool_retired_a_moment_ago_is_taken_back() { use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0; @@ -1833,6 +5377,8 @@ mod tests { let rb_list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &rb_alloc, None).expect("rb_list"); rb_list.Close().expect("rb_list close"); let mut s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -1856,6 +5402,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -1866,6 +5413,7 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; let (first, reused) = s.take_tile().expect("a tile from a new pool"); @@ -1884,6 +5432,38 @@ mod tests { } } + /// A title frees its tiles in runs spread over all its pools: the pools of the freed runs go + /// back. With pools of 64 MiB none of these did (every pool kept the tiles still in use). + #[test] + fn pools_of_freed_runs_go_back() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + // 192 MiB of tiles, taken in order as a title's first commits take them + const TILES: usize = 3072; + let tiles: Vec<(u32, u32)> = (0..TILES).map(|_| s.take_tile().expect("a tile").0).collect(); + let made = s.pools.iter().filter(|p| p.is_some()).count(); + assert_eq!(made * POOL_TILES as usize, TILES, "the tiles fill whole pools"); + // of every 64 MiB the title keeps the first 4 MiB and frees the rest + let (mut kept, mut freed) = (0, 0); + for (i, &t) in tiles.iter().enumerate() { + if i % 1024 < 64 { + kept += 1; + } else { + s.free.push(t); + freed += 1; + } + } + s.retire_free_pools(); + let left = s.pools.iter().filter(|p| p.is_some()).count() * POOL_TILES as usize; + assert_eq!(s.free.len() + s.retired.len() * POOL_TILES as usize, freed, "every freed tile is free or its pool retired"); + assert!(left <= kept * 2, "{left} tiles of video memory stay in pools for {kept} tiles in use ({} MiB for {} MiB)", left * TILE >> 20, kept * TILE >> 20); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + #[test] fn aligned_tile_addresses_spread_across_hash_buckets() { use std::hash::BuildHasher; @@ -1917,30 +5497,153 @@ mod tests { assert_eq!(changed_chunks(&page, &mut sent), vec![(192, 128)]); } - /// `scan_page` skips allocating a hash box on all-zero pages, allocates on the first write, - /// and coalesces adjacent dirty chunks across consecutive pages. #[test] - fn scan_page_lazy_alloc_and_coalesce() { + fn clean_chunks_take_gpu_copy_back_bytes() { + let mut page = vec![0x11u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let mut slot = Some(sent); + let gpu = vec![0x22u8; 2 * CHUNK]; + + land_page(&mut slot, &mut page, CHUNK, &gpu); + + assert!(page[..CHUNK].iter().all(|&byte| byte == 0x11)); + assert!(page[CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22)); + assert!(changed_chunks(&page, slot.as_deref_mut().unwrap()).is_empty(), "landed bytes were left dirty"); + } + + #[test] + fn dirty_chunks_survive_gpu_copy_back_and_upload_next() { + let mut page = vec![0x11u8; PAGE]; + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(&page, &mut sent); + let old_dirty_hash = sent[1]; + let mut slot = Some(sent); + page[CHUNK..2 * CHUNK].fill(0x33); + let gpu = vec![0x22u8; 2 * CHUNK]; + + land_page(&mut slot, &mut page, CHUNK, &gpu); + + assert!(page[CHUNK..2 * CHUNK].iter().all(|&byte| byte == 0x33), "copy-back overwrote newer CPU bytes"); + assert_eq!(slot.as_ref().unwrap()[1], old_dirty_hash, "dirty chunk lost its last-sent hash"); + assert!(page[2 * CHUNK..3 * CHUNK].iter().all(|&byte| byte == 0x22), "clean neighbour did not land"); + assert_eq!(changed_chunks(&page, slot.as_deref_mut().unwrap()), vec![(CHUNK, CHUNK)]); + } + + /// `scan_page` leaves published hashes unchanged, skips allocation for zero pages, and + /// coalesces adjacent dirty chunks. + #[test] + fn scan_page_plans_without_publishing_and_coalesces() { let mut page = vec![0u8; PAGE]; - let mut slot: Option<Box<[u64; CHUNKS]>> = None; + let slot: Option<Box<[u64; CHUNKS]>> = None; let mut out = Vec::new(); - scan_page(&page, 0x1_0000, &mut slot, &mut out); + scan_page(&page, 0x1_0000, &slot, &mut out); assert!(slot.is_none(), "all-zero page must not allocate hash box"); assert!(out.is_empty()); page[PAGE - 64] = 0xAA; - scan_page(&page, 0x1_0000, &mut slot, &mut out); - assert!(slot.is_some()); + scan_page(&page, 0x1_0000, &slot, &mut out); + assert!(slot.is_none(), "planning must not publish a last-sent hash"); assert_eq!(out, vec![(0x1_0FC0, 64)]); // Adjacent chunk at the start of the next page coalesces into a single run. let mut next = vec![0u8; PAGE]; next[0] = 0xBB; - let mut next_slot: Option<Box<[u64; CHUNKS]>> = None; - scan_page(&next, 0x1_1000, &mut next_slot, &mut out); + let next_slot: Option<Box<[u64; CHUNKS]>> = None; + scan_page(&next, 0x1_1000, &next_slot, &mut out); assert_eq!(out, vec![(0x1_0FC0, 128)]); } + #[test] + fn hash_plan_is_published_only_when_applied() { + let base = 0x2_0000; + let mut mapped = FxHashMap::default(); + mapped.insert(base, TileEntry::with_holes((0, 0), 0)); + let mut prefix = Vec::new(); + append_hash_updates(base + CHUNK, &[1; CHUNK], &mut prefix); + let mut suffix = Vec::new(); + append_hash_updates(base + PAGE + 2 * CHUNK, &[2; CHUNK], &mut suffix); + assert!(mapped[&base].sent[0].is_none()); + assert!(mapped[&base].sent[1].is_none()); + publish_hash_updates(&mut mapped, &prefix); + assert_eq!(mapped[&base].sent[0].as_ref().unwrap()[1], chunk_hash(&[1; CHUNK])); + assert!(mapped[&base].sent[1].is_none(), "an unacknowledged suffix was published"); + publish_hash_updates(&mut mapped, &suffix); + assert_eq!(mapped[&base].sent[1].as_ref().unwrap()[2], chunk_hash(&[2; CHUNK])); + } + + #[test] + fn cpu_write_after_planning_is_dirty_after_receipt_publication() { + let base = 0x3_0000; + let mut mapped = FxHashMap::default(); + mapped.insert(base, TileEntry::with_holes((0, 0), 0)); + let mut page = vec![0u8; PAGE]; + page[0] = 1; + let staged = page[..CHUNK].to_vec(); + let mut planned = Vec::new(); + append_hash_updates(base, &staged, &mut planned); + page[0] = 2; + publish_hash_updates(&mut mapped, &planned); + + let mut runs = Vec::new(); + scan_page(&page, base, &mapped[&base].sent[0], &mut runs); + assert_eq!(runs, [(base, CHUNK)]); + } + + #[test] + fn batch_hash_plan_is_bounded_by_staging() { + assert_eq!(MAX_BATCH_HASH_UPDATES, STAGING / CHUNK); + assert_eq!(MAX_BATCH_HASH_UPDATES * std::mem::size_of::<HashUpdate>(), STAGING / 4); + assert!(!batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES - 1, CHUNK)); + assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES, CHUNK)); + assert!(batch_hash_plan_would_overflow(MAX_BATCH_HASH_UPDATES / 2 + 1, STAGING / 2)); + } + + #[test] + fn prepared_dirty_batch_keeps_exact_hash_plan_and_rollback_point() { + let mut batch = PreparedDirtyBatch::new(3, 0x12_3400); + let bytes = [0xA5; 2 * CHUNK]; + batch.append_hashes(0x20_0000, &bytes); + assert_eq!(batch.slot, 3); + assert_eq!(batch.ring_start, 0x12_3400); + assert_eq!(batch.updates.len(), 2); + assert_eq!(batch.updates[0], HashUpdate { at: 0x20_0000, hash: chunk_hash(&bytes[..CHUNK]) }); + assert_eq!(batch.updates[1], HashUpdate { at: 0x20_0000 + CHUNK, hash: chunk_hash(&bytes[CHUNK..]) }); + assert!(!batch.hash_plan_would_overflow(CHUNK)); + + let storage = batch.updates.as_ptr(); + let capacity = batch.updates.capacity(); + for index in 0..3 { + batch.clear_after_submit(); + batch = batch.reopen(4 + index, 0x20_0000 + index as u64 * PAGE as u64); + batch.append_hashes(0x30_0000, &bytes); + assert_eq!(batch.updates.as_ptr(), storage, "batch {index} replaced its hash-plan allocation"); + assert_eq!(batch.updates.capacity(), capacity); + } + } + + #[test] + fn prepared_dirty_copy_splits_at_windows_and_ring_wrap() { + let window = 4 * PAGE; + let base = 0x10_0000; + let first = prepare_dirty_copy(base + window - CHUNK, 2 * CHUNK, base, window, 0, 8 * PAGE); + assert_eq!(first, PreparedDirtyCopy { + ring_start: 0, + staging_offset: 0, + window_offset: window - CHUNK, + bytes: CHUNK, + }); + let second = prepare_dirty_copy(base + window, CHUNK, base + window, window, CHUNK as u64, 8 * PAGE); + assert_eq!(second.window_offset, 0); + assert_eq!(second.bytes, CHUNK); + + let cap = 8 * PAGE; + let wrapped = prepare_dirty_copy(base, PAGE, base, window, (cap - 512) as u64, cap); + assert_eq!(wrapped.ring_start, cap as u64); + assert_eq!(wrapped.staging_offset, 0); + assert_eq!(wrapped.bytes, PAGE); + } + /// Ring-buffer planner keeps every chunk contiguous, 64-byte aligned, <= cap/2, and splits /// cleanly across the end of the ring buffer without wrapping mid-copy. #[test] @@ -2004,7 +5707,7 @@ mod tests { } /// Mapping tiles for a placed buffer over partially-committed/reserved memory must preserve - /// uncommitted hole bits so `readback_ranges` / `sync_sent_range` do not access-violate, + /// uncommitted hole bits so `readback_ranges` does not access-violate, /// and later commits clear those hole bits so subsequent writes scan cleanly. #[test] fn ensure_mapped_with_query_holes_skips_uncommitted_pages_on_readback() { @@ -2041,6 +5744,8 @@ mod tests { rb_list.Close().expect("rb_list close"); let mut s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -2064,6 +5769,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -2074,10 +5780,14 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; // Mirrors `place_buffer`: map both tiles probing real OS page commitment. - s.ensure_mapped(base, 2 * TILE, |t| query_tile_holes(t)); + s.ensure_mapped(base, 2 * TILE, |t| { + let holes = query_tile_holes(t); + (holes, !holes) + }); assert_eq!(s.mapped[&base].holes, 0xFF0F, "uncommitted prefix and suffix pages must stay holes"); assert_eq!(s.mapped[&(base + TILE)].holes, 0xFFFF, "fully reserved tile must have all 16 holes set"); @@ -2096,7 +5806,7 @@ mod tests { *(base as *mut u8) = 0x5A; let mut dirty = Vec::new(); let page0 = std::slice::from_raw_parts(base as *const u8, PAGE); - scan_page(page0, base, &mut entry.sent[0], &mut dirty); + scan_page(page0, base, &entry.sent[0], &mut dirty); assert_eq!(dirty, vec![(base, CHUNK)]); s.wait_for(s.value); @@ -2138,6 +5848,8 @@ mod tests { rb_list.Close().expect("rb_list close"); let mut s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -2161,6 +5873,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -2171,12 +5884,15 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; s.commit_range(base, TILE); let tile = s.mapped[&base].pool; let v = s.value; assert!(v > 0, "a new tile is mapped"); + mark_protection(&mut s.mapped, base + PAGE, PAGE, false); + assert_eq!(s.mapped[&base].not_rw, 1 << 1); // decommitted: parked, still mapped, nothing sent to the GPU s.decommit_range(base, TILE); @@ -2193,10 +5909,19 @@ mod tests { s.commit_range(base, TILE); assert_eq!(s.mapped[&base].pool, tile); assert_eq!(s.mapped[&base].holes, 0); + assert_eq!(s.mapped[&base].not_rw, 0, "recommitted pages use their commit protection"); assert!(s.parked.is_empty()); assert_eq!(s.to_zero, vec![(base, TILE)]); assert_eq!(s.value, v, "no tile mapping changed"); assert!(mapped_gen() > gen, "readers of `mapped` see it changed"); + mark_protection(&mut s.mapped, base + 2 * PAGE, PAGE, false); + s.decommit_range(base + 2 * PAGE, PAGE); + s.commit_range(base + 2 * PAGE, PAGE); + assert_eq!(s.mapped[&base].not_rw, 0, "a partially recommitted page is writable again"); + s.decommit_range(base + 3 * PAGE, PAGE); + s.commit_range_with_protection(base + 3 * PAGE, PAGE, false); + assert_eq!(s.mapped[&base].not_rw, 1 << 3, "commit and protection publish as one record update"); + s.commit_range(base + 3 * PAGE, PAGE); // decommitted and flushed (as before a submit): unmapped and free once unmap fence completes s.decommit_range(base, TILE); @@ -2263,6 +5988,8 @@ mod tests { rb_list.Close().expect("rb_list close"); let s = State { + generation: 1, + mapping_epoch: 0, dev, queue, fence, @@ -2286,6 +6013,7 @@ mod tests { ring_submitted: 0, ring_free: 0, inflight: VecDeque::new(), + uploads_ordered: true, zero_buf: None, slots: Vec::new(), next_slot: 0, @@ -2296,10 +6024,266 @@ mod tests { waited: FxHashMap::default(), runs: None, scratch_runs: Vec::new(), + retry_pages: Vec::new(), }; (base, s) } + unsafe fn add_upload_slot(s: &mut State, fence_val: u64, close: bool) { + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("upload allocator"); + let list: ID3D12GraphicsCommandList = s.dev + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None) + .expect("upload list"); + if close { + list.Close().expect("upload list close"); + } + s.slots.push(UploadSlot { alloc, list, fence_val }); + } + + #[test] + fn begin_slot_skips_a_busy_head_for_a_ready_slot() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + add_upload_slot(&mut s, 9, true); + add_upload_slot(&mut s, 0, true); + + assert!(matches!(s.begin_slot(), BeginSlot::Ready(1))); + assert_eq!(s.next_slot, 0); + s.slots[1].list.Close().expect("selected list close"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn begin_slot_waits_for_the_earliest_busy_slot_without_advancing() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + add_upload_slot(&mut s, 9, true); + add_upload_slot(&mut s, 7, true); + add_upload_slot(&mut s, 8, true); + let ticket = match s.begin_slot() { + BeginSlot::Wait(ticket) => ticket, + _ => panic!("all busy slots did not return a retirement ticket"), + }; + + assert_eq!(s.next_slot, 0); + assert_eq!(ticket.target, 7); + assert!(matches!(ticket.kind, WaitKind::Slot { index: 1, next_slot: 0, fence: 7 })); + assert!(s.wait_ticket_owns_upload(&ticket)); + s.slots[1].fence_val = 10; + assert!(!s.wait_ticket_owns_upload(&ticket), "a changed selected slot accepted its old ticket"); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn begin_slot_reset_failure_does_not_open_or_advance_a_slot() { + use windows_sys::Win32::System::Memory::MEM_RELEASE; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + add_upload_slot(&mut s, 0, false); + + assert!(matches!(s.begin_slot(), BeginSlot::RetryRequired)); + assert_eq!(s.next_slot, 0); + + s.slots[0].list.Close().expect("failed selected list close"); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn upload_wait_releases_and_reacquires_its_ownership_gate() { + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let (mut guard, mut timing) = UploadGateTiming::acquire(false); + let worker = std::thread::spawn(move || { + let _crossing_uploader = UPLOAD_GATE.lock().unwrap(); + acquired_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }); + let released = timing.with_released(&mut guard, || { + let acquired = acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).is_ok(); + release_tx.send(()).unwrap(); + worker.join().unwrap(); + acquired + }); + assert!(released, "another uploader could not cross the fence wait"); + assert!(UPLOAD_GATE.try_lock().is_err(), "the process upload gate was not reacquired"); + let times = timing.finish(); + assert_eq!((times.wait_us, times.hold_us, times.released_us), (0, 0, 0), "disabled timing read the clock"); + drop(guard); + } + + #[test] + fn replacement_waits_for_every_upload_generation_reader() { + let _placement = PLACEMENT.lock().unwrap(); + let lower_target = UPLOAD_STATE_LIFETIME.read().unwrap(); + let higher_target = UPLOAD_STATE_LIFETIME.read().unwrap(); + let (acquired_tx, acquired_rx) = std::sync::mpsc::channel(); + let replacement = std::thread::spawn(move || { + let _exclusive = UPLOAD_STATE_LIFETIME.write().unwrap(); + acquired_tx.send(()).unwrap(); + }); + + assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err()); + drop(lower_target); + assert!(acquired_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "replacement passed the lower target while a higher upload was still in flight"); + drop(higher_target); + acquired_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("replacement stayed blocked after every upload reader retired"); + replacement.join().unwrap(); + } + + #[test] + fn a_stalled_upload_ring_yields_without_publishing_hashes() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(1); + assert_eq!(VirtualAlloc(base as *mut c_void, TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + std::ptr::write_bytes(base as *mut u8, 0x5a, PAGE); + s.commit_range(base, TILE); + s.wait_for(s.value); + let page = std::slice::from_raw_parts(base as *const u8, PAGE); + let mut sent = Box::new(ZERO_HASHES); + changed_chunks(page, &mut sent); + s.mapped.get_mut(&base).unwrap().sent[0] = Some(sent); + let before = *s.mapped[&base].sent[0].as_ref().unwrap().clone(); + + s.ring_write = STAGING as u64; + s.ring_submitted = STAGING as u64; + s.ring_free = 0; + s.inflight.push_back((s.value + 1, STAGING as u64)); + let ticket = match s.upload_dirty_with_timeout(&[(base + CHUNK, 2 * CHUNK)], 20) { + UploadStep::Wait(ticket) => ticket, + UploadStep::Done(_) => panic!("a full ring did not return its retirement ticket"), + }; + assert_eq!(ticket.target, s.value + 1); + assert!(s.wait_ticket_valid(&ticket)); + s.mapping_epoch += 1; + assert!(!s.wait_ticket_valid(&ticket), "a remapped destination accepted an old upload ticket"); + assert!(s.wait_ticket_generation(&ticket), "a remap invalidated the live state generation"); + let after = s.mapped[&base].sent[0].as_ref().unwrap(); + assert_eq!(after.as_ref(), &before, "a failed upload changed the published hash state"); + + let alloc = s.dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = s.dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &alloc, None).unwrap(); + list.Close().unwrap(); + s.slots.push(UploadSlot { alloc, list, fence_val: s.value + 1 }); + s.next_slot = 0; + let before_slot = s.next_slot; + let ticket = match s.begin_slot() { + BeginSlot::Wait(ticket) => ticket, + _ => panic!("a busy slot did not return its retirement ticket"), + }; + assert_eq!(s.next_slot, before_slot, "a busy slot advanced before its fence completed"); + assert!(matches!(ticket.kind, WaitKind::Slot { index: 0, next_slot: 0, .. })); + assert!(s.wait_ticket_owns_upload(&ticket)); + s.slots[0].fence_val += 1; + assert!(!s.wait_ticket_owns_upload(&ticket), "a reused slot accepted its predecessor ticket"); + assert!(s.wait_ticket_generation(&ticket), "safe slot reuse invalidated the live generation"); + s.generation += 1; + assert!(!s.wait_ticket_owns_upload(&ticket), "a replacement state accepted an old upload ticket"); + s.uploads_ordered = false; + assert!(matches!( + s.upload_dirty_with_timeout(&[(base + CHUNK, CHUNK)], 20), + UploadStep::Done(PreparationOutcome::ExecutedUntracked) + )); + + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + + #[test] + fn placement_create_is_unlocked_drains_releases_and_rejects_a_new_generation() { + use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE}; + + unsafe { + let (base, mut s) = test_state_with_reserved(2); + assert_eq!(VirtualAlloc(base as *mut c_void, 2 * TILE, MEM_COMMIT, PAGE_READWRITE) as usize, base); + s.commit_range(base, 2 * TILE); + s.wait_for(s.value); + let old_tile = s.mapped[&base].pool; + let new_tile = s.mapped[&(base + TILE)].pool; + + let mut placed: Option<ID3D12Resource> = None; + s.dev.CreateReservedResource(&buffer_desc(TILE as u64), D3D12_RESOURCE_STATE_COMMON, None, &mut placed) + .expect("placed resource"); + let placed = placed.unwrap(); + let ptr = placed.as_raw() as usize; + s.buffers.insert(ptr, vec![old_tile]); + s.pinned.insert(old_tile, 1); + + let state = Mutex::new(Some(s)); + let forgotten = Mutex::new(Vec::new()); + let desc = buffer_desc(TILE as u64); + let returned = placed.clone().into_raw(); + let mut unlocked = false; + let result = place_buffer_in( + &state, + &forgotten, + base + TILE, + &desc, + 0, + |_| { + unlocked = state.try_lock().is_ok(); + forget_buffer_in(&state, &forgotten, ptr); + forgotten.lock().unwrap().push(ptr); + Some((0, returned)) + }, + |_| panic!("same-generation placement aborted"), + ); + assert_eq!(result, Some((0, 0))); + assert!(unlocked, "resource creation held sparse STATE"); + { + let g = lock_state_in(&state, &forgotten); + let s = g.as_ref().unwrap(); + assert_eq!(s.buffers.get(&ptr), Some(&vec![new_tile])); + assert!(!s.pinned.contains_key(&old_tile)); + assert_eq!(s.pinned.get(&new_tile), Some(&1)); + } + + let original_fence = state.lock().unwrap().as_ref().unwrap().fence.clone(); + let replacement = state.lock().unwrap().as_ref().unwrap().dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let returned2 = placed.clone().into_raw(); + let mut aborted = false; + let result = place_buffer_in( + &state, + &forgotten, + base + TILE, + &desc, + 0, + |_| { + state.lock().unwrap().as_mut().unwrap().fence = replacement; + Some((0, returned2)) + }, + |raw| { + aborted = true; + drop(ID3D12Resource::from_raw(raw)); + }, + ); + assert!(result.is_none() && aborted, "a replacement state accepted the old generation's resource"); + state.lock().unwrap().as_mut().unwrap().fence = original_fence; + + drop(ID3D12Resource::from_raw(returned)); + let s = state.lock().unwrap().take().unwrap(); + s.wait_for(s.value); + drop(s); + assert_ne!(VirtualFree(base as *mut c_void, 0, MEM_RELEASE), 0); + } + } + /// `flush_parked` must keep unmapped pool tiles out of `free` (and `take_tile` must not reuse /// them) while the sparse queue's unmap fence is still in flight on the GPU. #[test] @@ -2345,7 +6329,6 @@ mod tests { unsafe { let (base, mut s) = test_state_with_reserved(2); let title_q: ID3D12CommandQueue = s.dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).expect("title queue"); - assert!(s.note_queue(&title_q)); s.commit_range(base, TILE); let tile = s.mapped[&base].pool; @@ -2357,7 +6340,7 @@ mod tests { s.decommit_range(base, TILE); s.free.clear(); - assert!(s.flush_parked()); + assert!(s.flush_parked_for(std::slice::from_ref(&title_q), &[], false)); // Even after `s.queue` finishes `unmap_tiles`, `title_q` is still gated behind `title_gate`. s.wait_for(s.value); diff --git a/crates/xcl/src/hle/d3d12x/title_list.rs b/crates/xcl/src/hle/d3d12x/title_list.rs index a41e5643fc..55004fa291 100644 --- a/crates/xcl/src/hle/d3d12x/title_list.rs +++ b/crates/xcl/src/hle/d3d12x/title_list.rs @@ -50,6 +50,12 @@ struct SegmentBook { /// finished primary's last submit, and the PC does not let a list be submitted again before /// that (#1452, debug layer id 553). A console does. first: Option<usize>, + /// Closed object that receives calls after an unrecoverable split failure, until Reset. + failed: Option<usize>, + /// The identity-bearing primary returned a failed Close and can never be Reset again. + primary_broken: bool, + /// Non-primary lists whose failed Close permanently forbids Reset/reuse. + unresettable: Vec<usize>, } /// Wrapper address -> split segment book (populated lazily only for lists that split). @@ -145,6 +151,10 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { hr } +fn recover_failed_with<T>(failed: usize, in_flight: bool, reuse: impl FnOnce(usize) -> Option<T>, replace: impl FnOnce() -> Option<T>) -> Option<T> { + if in_flight { replace() } else { reuse(failed) } +} + /// #10 Reset(allocator, initial_pso): resets the primary PC list (`F_PRIMARY`) via `list_x::reset_pc` /// (calling directly rather than through the dual-dispatch vtable thunk so console state always /// resets even though this wrapper sits in `xcl.exe`), restores `F_BACKING = F_PRIMARY`, and moves @@ -154,13 +164,33 @@ unsafe extern "system" fn close(this: *mut c_void) -> HRESULT { pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: usize) -> HRESULT { let primary = *((this as usize + F_PRIMARY) as *const *mut c_void); let adopted = super::real::is_adopted(primary); - let stand_in = if adopted && super::alloc_pool::in_flight(primary as usize) { + let (failed, primary_broken, first) = SEGMENTS + .lock() + .unwrap() + .as_ref() + .and_then(|m| m.get(&(this as usize))) + .map_or((None, false, None), |b| (b.failed, b.primary_broken, b.first)); + let stand_in = if let Some(failed) = failed { + recover_failed_with( + failed, + super::alloc_pool::in_flight(failed), + |failed| (super::list_x::reset_pc(failed as *mut c_void, alloc, pso) >= 0).then_some(failed), + || super::list_x::reset_stand_in(this, primary, alloc, pso), + ) + } else if primary_broken { + match first.filter(|&p| !super::alloc_pool::in_flight(p)) { + Some(first) => (super::list_x::reset_pc(first as *mut c_void, alloc, pso) >= 0).then_some(first), + None => super::list_x::reset_stand_in(this, primary, alloc, pso), + } + } else if adopted && super::alloc_pool::in_flight(primary as usize) { super::list_x::reset_stand_in(this, primary, alloc, pso) } else { None }; let hr = if stand_in.is_some() { 0 + } else if failed.is_some() || primary_broken { + 0x8000_4005u32 as HRESULT } else if adopted { super::list_x::reset_pc(primary, alloc, pso) } else { @@ -176,7 +206,8 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: if stand_in.is_some() || m.contains_key(&(this as usize)) { let b = m.entry(this as usize).or_default(); let mut old = std::mem::take(&mut b.extra_active); - old.extend(std::mem::replace(&mut b.first, stand_in)); + old.extend(std::mem::replace(&mut b.first, stand_in).filter(|first| Some(*first) != stand_in)); + old.extend(b.failed.take().filter(|failed| Some(*failed) != stand_in)); b.spares.extend(old.iter().copied()); old } else { @@ -194,6 +225,11 @@ pub(super) unsafe extern "system" fn reset(this: *mut c_void, alloc: usize, pso: for seg in moved { super::bind::reset(seg as *mut c_void, 0, 0); super::list_x::clear_segment_state(seg); + super::alloc_pool::retire_recording(seg); + } + if stand_in.is_some() { + super::bind::reset(primary, 0, 0); + super::alloc_pool::retire_recording(primary as usize); } } *((this as usize + F_RING_AT) as *mut usize) = 0; @@ -252,6 +288,10 @@ pub fn push_segments(list: *mut c_void, out: &mut Vec<*mut c_void>) -> bool { }; let sg = SEGMENTS.lock().unwrap(); let book = sg.as_ref().and_then(|m| m.get(&(list as usize))); + if let Some(failed) = book.and_then(|b| b.failed) { + out.push(failed as *mut c_void); + return true; + } out.push(book.and_then(|b| b.first).map_or(primary, |f| f as *mut c_void)); if let Some(book) = book { for &seg in &book.extra_active { @@ -274,7 +314,43 @@ pub(super) fn can_split(wrapper: *mut c_void, n: usize) -> bool { let sg = SEGMENTS.lock().unwrap(); sg.as_ref() .and_then(|m| m.get(&(wrapper as usize))) - .is_none_or(|b| b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) + .is_none_or(|b| b.failed.is_none() && b.extra_active.len() + n <= MAX_EXTRA_SEGMENTS) +} + +/// Reserve every bookkeeping slot a split will publish, before its producer is closed. +pub(super) fn prepare_split(wrapper: *mut c_void, n: usize) -> bool { + let mut sg = SEGMENTS.lock().unwrap(); + let m = sg.get_or_insert_with(HashMap::new); + if m.try_reserve(1).is_err() { + return false; + } + let b = m.entry(wrapper as usize).or_default(); + if b.failed.is_some() + || b.extra_active.len() + n > MAX_EXTRA_SEGMENTS + || b.extra_active.try_reserve(n).is_err() + || b.spares.try_reserve(n).is_err() + || b.unresettable.try_reserve(1).is_err() + { + return false; + } + let mut wg = WRAPPER_OF.lock().unwrap(); + wg.get_or_insert_with(HashMap::new).try_reserve(1).is_ok() +} + +/// Reserve only the bookkeeping a fail-closed transition or successful standby return needs. +/// Unlike a recording split, this does not consume physical-segment capacity. +pub(super) fn prepare_fail_closed(wrapper: *mut c_void) -> bool { + let mut sg = SEGMENTS.lock().unwrap(); + let m = sg.get_or_insert_with(HashMap::new); + if m.try_reserve(1).is_err() { + return false; + } + let b = m.entry(wrapper as usize).or_default(); + if b.failed.is_some() || b.spares.try_reserve(1).is_err() || b.unresettable.try_reserve(1).is_err() { + return false; + } + let mut wg = WRAPPER_OF.lock().unwrap(); + wg.get_or_insert_with(HashMap::new).try_reserve(1).is_ok() } /// Pop a previously created closed extra PC command list from `wrapper`'s spare pool for reuse @@ -288,10 +364,21 @@ pub(super) fn pop_spare(wrapper: *mut c_void) -> Option<*mut c_void> { /// Give back to `wrapper`'s spare pool a closed PC command list that did not become a segment. pub(super) fn put_spare(wrapper: *mut c_void, pc: *mut c_void) { + super::alloc_pool::retire_recording(pc as usize); let mut sg = SEGMENTS.lock().unwrap(); sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().spares.push(pc as usize); } +/// Take segment `pc` out of `wrapper`'s recording, so it is not submitted. Its failed Close left +/// it open, so quarantine it until wrapper destruction rather than treating it as a closed spare. +pub(super) fn drop_segment(wrapper: *mut c_void, pc: *mut c_void) { + let mut sg = SEGMENTS.lock().unwrap(); + if let Some(b) = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize))) { + b.extra_active.retain(|&p| p != pc as usize); + b.unresettable.push(pc as usize); + } +} + /// Add the closed segment `pc` to `wrapper`'s recording, after the ones it has. pub(super) fn push_segment(wrapper: *mut c_void, pc: *mut c_void) { SEGMENTS.lock().unwrap().get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default().extra_active.push(pc as usize); @@ -314,6 +401,30 @@ pub(super) unsafe fn activate_segment(wrapper: *mut c_void, old_pc: *mut c_void, m.insert(new_pc as usize, wrapper as usize); } +/// Route a terminally failed recording to a known-closed object until the title Resets it. +pub(super) unsafe fn fail_closed(wrapper: *mut c_void, old_pc: *mut c_void, closed_pc: *mut c_void, producer_broken: bool) { + *((wrapper as usize + F_BACKING) as *mut usize) = closed_pc as usize; + let mut sg = SEGMENTS.lock().unwrap(); + let b = sg.get_or_insert_with(HashMap::new).entry(wrapper as usize).or_default(); + b.failed = Some(closed_pc as usize); + if producer_broken { + if old_pc as usize == *((wrapper as usize + F_PRIMARY) as *const usize) { + b.primary_broken = true; + } else { + b.extra_active.retain(|&p| p != old_pc as usize); + if b.first == Some(old_pc as usize) { + b.first = None; + } + b.unresettable.push(old_pc as usize); + } + } + drop(sg); + let mut wg = WRAPPER_OF.lock().unwrap(); + let m = wg.get_or_insert_with(HashMap::new); + m.remove(&(old_pc as usize)); + m.insert(closed_pc as usize, wrapper as usize); +} + /// For `KickoffX` on an already-split list: returns `(primary, prior_closed_segments, extra_to_reclaim)` /// when `active_pc != primary`, switches `F_BACKING` back to `primary`, and moves all extra /// segments (including `active_pc`) into `spares` so recording resumes cleanly on `primary`. @@ -322,6 +433,9 @@ pub(super) unsafe fn reclaim_for_kickoff(active_pc: *mut c_void) -> Option<(*mut let wrapper = wrapper_of(active_pc)?; let mut sg = SEGMENTS.lock().unwrap(); let book = sg.as_mut().and_then(|m| m.get_mut(&(wrapper as usize)))?; + if book.failed.is_some() { + return None; + } let primary = book.first.map_or_else(|| *((wrapper as usize + F_PRIMARY) as *const *mut c_void), |f| f as *mut c_void); if primary == active_pc { return None; @@ -405,14 +519,14 @@ unsafe extern "system" fn release(this: *mut c_void) -> u32 { if let Some(m) = wg.as_mut() { m.remove(&(pc as usize)); if let Some(ref b) = book { - for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()) { + for &seg in b.extra_active.iter().chain(b.spares.iter()).chain(b.first.iter()).chain(b.failed.iter()).chain(b.unresettable.iter()) { m.remove(&seg); } } } } if let Some(b) = book { - for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first) { + for seg in b.extra_active.into_iter().chain(b.spares.into_iter()).chain(b.first).chain(b.failed).chain(b.unresettable) { let raw = seg as *mut c_void; super::bind::forget(raw); let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(pc_slot(raw, 2)); @@ -453,6 +567,101 @@ mod tests { this as u64 + a + 10 * b + 100 * c + 1000 * d } + #[test] + fn split_limit_counts_every_physical_extra_segment() { + let wrapper = 0x7ffe_3001usize as *mut c_void; + { + let mut sg = SEGMENTS.lock().unwrap(); + sg.get_or_insert_with(HashMap::new).insert( + wrapper as usize, + SegmentBook { extra_active: (0..MAX_EXTRA_SEGMENTS - 1).map(|i| 0x8000 + i).collect(), ..Default::default() }, + ); + } + assert!(can_split(wrapper, 1)); + assert!(!can_split(wrapper, 2), "a deferred dispatch needs two physical segments"); + assert!(!prepare_split(wrapper, 2)); + assert_eq!(SEGMENTS.lock().unwrap().as_ref().unwrap()[&(wrapper as usize)].extra_active.len(), MAX_EXTRA_SEGMENTS - 1); + assert!(prepare_split(wrapper, 1)); + push_segment(wrapper, 0x9000usize as *mut c_void); + assert!(!can_split(wrapper, 1)); + assert!(can_split(wrapper, 0)); + assert!(prepare_fail_closed(wrapper), "Kickoff standby does not consume segment capacity"); + SEGMENTS.lock().unwrap().as_mut().unwrap().get_mut(&(wrapper as usize)).unwrap().failed = Some(0x9100); + assert!(!prepare_fail_closed(wrapper), "an already failed recording cannot preflight again"); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); + } + + #[test] + fn failed_primary_routes_submission_and_calls_to_closed_standby() { + let mut vt = vec![0usize; LIST_SLOTS]; + vt[0] = fake_qi as usize; + vt[1] = fake_add_ref as usize; + vt[2] = fake_release as usize; + let primary = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + let standby = Box::into_raw(Box::new(Fake { vt: vt.as_ptr(), refs: 1 })); + unsafe { + let wrapper = wrap(primary as *mut c_void); + fail_closed(wrapper, primary as *mut c_void, standby as *mut c_void, true); + assert_eq!(*((wrapper as usize + F_BACKING) as *const usize), standby as usize); + assert!(!can_split(wrapper, 1)); + let mut submitted = Vec::new(); + assert!(push_segments(wrapper, &mut submitted)); + assert_eq!(submitted, vec![standby as *mut c_void]); + { + let books = SEGMENTS.lock().unwrap(); + let book = &books.as_ref().unwrap()[&(wrapper as usize)]; + assert!(book.primary_broken); + assert_eq!(book.failed, Some(standby as usize)); + } + + let rel: unsafe extern "system" fn(*mut c_void) -> u32 = std::mem::transmute(*(*(wrapper as *const *const usize)).add(2)); + assert_eq!(rel(wrapper), 0); + drop(Box::from_raw(primary)); + drop(Box::from_raw(standby)); + } + } + + #[test] + fn failed_continuation_reset_keeps_the_closed_producer_reusable() { + let producer = 0x7ffe_4002usize as *mut c_void; + let standby = 0x7ffe_4003usize as *mut c_void; + let mut object = vec![0usize; OBJECT_BYTES / std::mem::size_of::<usize>()]; + let wrapper = object.as_mut_ptr() as *mut c_void; + unsafe { + *((wrapper as usize + F_PRIMARY) as *mut usize) = producer as usize; + fail_closed(wrapper, producer, standby, false); + } + let books = SEGMENTS.lock().unwrap(); + let book = &books.as_ref().unwrap()[&(wrapper as usize)]; + assert_eq!(book.failed, Some(standby as usize)); + assert!(!book.primary_broken); + assert!(book.unresettable.is_empty()); + drop(books); + SEGMENTS.lock().unwrap().as_mut().unwrap().remove(&(wrapper as usize)); + WRAPPER_OF.lock().unwrap().as_mut().unwrap().remove(&(standby as usize)); + } + + #[test] + fn in_flight_failed_standby_is_replaced_instead_of_reused() { + use std::cell::Cell; + let reused = Cell::new(false); + let replaced = Cell::new(false); + let selected = recover_failed_with( + 0x7100, + true, + |_| { + reused.set(true); + Some(0x7100) + }, + || { + replaced.set(true); + Some(0x7200) + }, + ); + assert_eq!(selected, Some(0x7200)); + assert!(!reused.get() && replaced.get()); + } + /// The SDK's inline writers check `write < end` (or `write + n <= end`): never room here. #[test] fn console_list_objects_have_no_room_and_forward_to_the_pc_list() { diff --git a/crates/xcl/src/hle/d3d12x/title_textures.rs b/crates/xcl/src/hle/d3d12x/title_textures.rs index 6d97bc6e4e..d521acf720 100644 --- a/crates/xcl/src/hle/d3d12x/title_textures.rs +++ b/crates/xcl/src/hle/d3d12x/title_textures.rs @@ -16,13 +16,12 @@ //! address) are not seen; the title's own GPU work on the texture goes to the PC texture. //! //! A copy starts and ends in the state the title's submitted work left the texture in: its -//! transitions of these textures are noted per PC command list as they are recorded -//! (`note_transitions`) and applied, in submission order, when the list is submitted -//! (`submitted`) – per subresource once a transition names one. +//! transitions of these textures are captured in each physical command-list segment's immutable +//! submission effects and applied in submission order – per subresource once one is named. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::ffi::c_void; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex}; use windows::core::Interface; @@ -38,11 +37,35 @@ extern "system" { fn GetWriteWatch(flags: u32, base: *const c_void, size: usize, addresses: *mut *mut c_void, count: *mut usize, granularity: *mut u32) -> u32; } -/// (device, address its bytes are read from, layout, states) of an upload -type Upload = (usize, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>); +/// (device, address its bytes are read from, layout, states, registration generation) of an upload +type Upload = (usize, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>, u64); + +/// One incarnation of a title command queue. The raw address alone can be reused after release. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct WriterQueueId { + pub(super) raw: usize, + pub(super) generation: u64, +} + +/// A GPU write captured while a physical command-list segment is recorded. Its registration +/// generation prevents a late/replayed segment from marking a new object at a reused address. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct GpuWrite { + pub(super) res: usize, + pub(super) generation: u64, + pub(super) subresource: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct GpuWriter { + epoch: u64, + queue: WriterQueueId, +} struct Entry { device: usize, + /// PC allocation size of a committed resource (zero for placed resources and test entries) + committed_bytes: u64, /// the title's address of the texture va: usize, /// where its bytes are read and its CPU writes watched: `va`, or – for a texture in a GPU @@ -61,12 +84,18 @@ struct Entry { /// the title's GPU work wrote it (CopyTextureRegion into it): its CPU view is stale from /// then on and no longer uploaded gpu_written: bool, + /// Last submitted GPU writer: one for the whole resource while uniform, otherwise one per + /// subresource in D3D12 order. Empty until a tracked write is submitted. + gpu_writers: Vec<Option<GpuWriter>>, + /// CPU memory is the source of this texture and must be watched/uploaded. False for a + /// GPU-owned UAV/render target retained only for future coherency readback. + cpu_backed: bool, /// backed by shared `vram::Pages` tiles (overlapping placements share video memory) placed: bool, /// tiles were unmapped after a different-range placement superseded this texture unmapped: bool, - /// monotonic registration order (newest wins when uncovering shadowed textures) - seq: u64, + /// monotonic registration generation (newest wins when uncovering shadowed textures) + generation: u64, } /// textures waiting for their first upload @@ -86,7 +115,7 @@ struct Table { shadowed_by_va: BTreeMap<(usize, usize), usize>, /// Largest byte span currently in `shadowed` (bounds range queries) max_shadowed_size: usize, - next_seq: u64, + next_generation: u64, } impl Table { @@ -97,7 +126,7 @@ impl Table { shadowed: BTreeMap::new(), shadowed_by_va: BTreeMap::new(), max_shadowed_size: 0, - next_seq: 0, + next_generation: 0, } } @@ -219,8 +248,8 @@ impl Table { } } } - self.next_seq += 1; - entry.seq = self.next_seq; + self.next_generation = self.next_generation.wrapping_add(1).max(1); + entry.generation = self.next_generation; if entry.pending { pending_delta += 1; } @@ -247,7 +276,7 @@ impl Table { let mut cands: Vec<(u64, usize, usize, usize)> = self .shadowed_overlaps(va, end) .into_iter() - .filter_map(|(sva, sres, send)| self.shadowed.get(&sres).map(|e| (e.seq, sres, sva, send))) + .filter_map(|(sva, sres, send)| self.shadowed.get(&sres).map(|e| (e.generation, sres, sva, send))) .collect(); cands.sort_unstable_by(|a, b| b.0.cmp(&a.0)); let mut to_remap = Vec::new(); @@ -282,6 +311,11 @@ impl Table { by_res.get_mut(&res).or_else(|| shadowed.get_mut(&res)) } + fn committed_bytes_for(&self, device: usize) -> (usize, u64) { + self.by_res.values().chain(self.shadowed.values()).filter(|e| e.device == device && !e.placed) + .fold((0usize, 0u64), |(n, bytes), e| (n.saturating_add(1), bytes.saturating_add(e.committed_bytes))) + } + fn overlapping(&self, va: usize, len: usize) -> Vec<(usize, usize)> { self.active_overlaps(va, va.saturating_add(len)).into_iter().take(4).map(|(ova, ores, _)| (ores, ova)).collect() } @@ -311,6 +345,7 @@ static TEXTURES: Mutex<Table> = Mutex::new(Table::new()); static REFRESH: Mutex<()> = Mutex::new(()); static TEXTURES_GEN: AtomicU64 = AtomicU64::new(0); static TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +static CPU_TEXTURES_LEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); /// cached `watch_ranges` keyed by `(sparse::mapped_gen, TEXTURES_GEN, graphics_reservations_gen)` static WATCH_CACHE: Mutex<Option<((u64, u64, u64), Arc<Vec<(usize, usize)>>)>> = Mutex::new(None); /// the queue uploads go to, per device @@ -319,7 +354,27 @@ static UPLOADS: AtomicU64 = AtomicU64::new(0); /// Number of textures kept in title memory and uploads done so far. pub fn counts() -> (usize, u64) { - (TEXTURES.lock().unwrap().by_res.len(), UPLOADS.load(Ordering::Relaxed)) + (TEXTURES_LEN.load(Ordering::Relaxed), UPLOADS.load(Ordering::Relaxed)) +} + +/// Sampled textures tracked for CPU coherency on `device` that use committed resources: count and +/// their PC allocation bytes. This deliberately excludes untracked render/depth/UAV fallbacks. +/// Shadowed resources remain live and are included once until the title releases them. +pub(super) fn committed_bytes_for(device: usize) -> (usize, u64) { + TEXTURES.lock().unwrap().committed_bytes_for(device) +} + +unsafe fn committed_allocation_bytes(device: *mut c_void, resource: *mut c_void, placed: bool) -> u64 { + if placed || !super::memory_report::enabled() { return 0 } + let Some(dev) = ID3D12Device::from_raw_borrowed(&device) else { return 0 }; + let Some(res) = ID3D12Resource::from_raw_borrowed(&resource) else { return 0 }; + let bytes = dev.GetResourceAllocationInfo(0, &[res.GetDesc()]).SizeInBytes; + if bytes == u64::MAX { 0 } else { bytes } +} + +fn update_lengths(t: &Table) { + TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + CPU_TEXTURES_LEN.store(t.by_res.values().filter(|e| e.cpu_backed).count(), Ordering::Relaxed); } /// Whether a non-depth render target / UAV texture is small enough to be a CPU-filled glyph or UI @@ -376,8 +431,10 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, } } let in_gpu_view = crate::hle::kernelx::mirrors::source(va).is_some(); + let placed = super::vram::is_placed_texture(res as usize); let e = Entry { device: device as usize, + committed_bytes: committed_allocation_bytes(device, res, placed), va, src, in_gpu_view, @@ -385,15 +442,97 @@ pub(super) unsafe fn register(device: *mut c_void, res: *mut c_void, va: usize, states: vec![state], pending: true, gpu_written: false, - placed: super::vram::is_placed_texture(res as usize), + gpu_writers: Vec::new(), + cpu_backed: true, + placed, + unmapped: false, + generation: 0, + }; + let to_unmap = { + let mut t = TEXTURES.lock().unwrap(); + let (delta, unmap_ptrs) = t.insert(res as usize, e); + adjust_pending(delta); + update_lengths(&t); + clone_resources(&unmap_ptrs) + }; + for r in &to_unmap { + super::vram::unmap_superseded(r); + } + TEXTURES_GEN.fetch_add(1, Ordering::Release); + Ok(()) +} + +/// Validate and retain the console layout of a GPU-owned UAV/render target. Depth/stencil, +/// MSAA, format-promoted resources, and multiple texel planes are deliberately unsupported: +/// their PC bytes cannot be tiled back into the console layout without conversion/metadata. +fn gpu_owned_layout(desc: &[u8; 0x38], pc: &D3D12_RESOURCE_DESC) -> Result<xg::Texture, String> { + let u = |o: usize| u32::from_le_bytes(desc[o..o + 4].try_into().unwrap()); + let flags = u(0x30); + if flags & 2 != 0 || flags & 5 == 0 { + return Err("not a supported colour render target / UAV".into()); + } + if (pc.Flags.0 as u32) & 5 == 0 { + return Err("not GPU-writable on the PC".into()); + } + if u(0x24) != 1 || pc.SampleDesc.Count != 1 { + return Err("a multisampled texture".into()); + } + if u(0x20) != pc.Format.0 as u32 { + return Err("a console format promoted on the PC".into()); + } + if u(0) != pc.Dimension.0 as u32 || u64::from_le_bytes(desc[0x10..0x18].try_into().unwrap()) != pc.Width || u(0x18) != pc.Height { + return Err("a PC resource shape different from its console layout".into()); + } + let tex = xg::Texture::new(desc).map_err(|hr| format!("layout {hr:#x}"))?; + let surfaces = tex.planes.iter().filter(|p| matches!(&p.kind, xg::PlaneKind::Surface(_))).count(); + let s = tex.texels().filter(|_| surfaces == 1).ok_or("not exactly one supported texel plane")?; + let layers = if s.depth > 0 { s.depth } else { s.array }; + if s.chain.levels.is_empty() + || pc.MipLevels as usize != s.chain.levels.len() + || pc.DepthOrArraySize as u32 != layers + || tex.size() == 0 + || usize::try_from(tex.size()).is_err() + { + return Err("console and PC subresources differ".into()); + } + Ok(tex) +} + +/// Register metadata for a successfully created GPU-owned placement. No COM reference is kept; +/// the resource's final Release removes this generation before its raw address can be reused. +pub(super) unsafe fn register_gpu_owned( + device: *mut c_void, + res: *mut c_void, + va: usize, + desc: &[u8; 0x38], + state: D3D12_RESOURCE_STATES, +) -> Result<(), String> { + let resource = ID3D12Resource::from_raw_borrowed(&res).ok_or("no resource")?; + let tex = gpu_owned_layout(desc, &resource.GetDesc())?; + let size = usize::try_from(tex.size()).map_err(|_| "texture size does not fit the title address space")?; + va.checked_add(size).ok_or("texture address range overflows")?; + let src = mirror_source(va); + let e = Entry { + device: device as usize, + committed_bytes: 0, + va, + src, + in_gpu_view: crate::hle::kernelx::mirrors::source(va).is_some(), + tex: Arc::new(tex), + states: vec![state], + pending: false, + gpu_written: true, + gpu_writers: Vec::new(), + cpu_backed: false, + placed: true, unmapped: false, - seq: 0, + generation: 0, }; let to_unmap = { let mut t = TEXTURES.lock().unwrap(); let (delta, unmap_ptrs) = t.insert(res as usize, e); adjust_pending(delta); - TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + update_lengths(&t); clone_resources(&unmap_ptrs) }; for r in &to_unmap { @@ -442,7 +581,7 @@ fn recheck_gpu_view_sources() { /// `e`'s source again (a texture in a GPU view): when it changed, `e` reads the new one and is /// uploaded at the next submit. Whether it changed. fn recheck_source(e: &mut Entry) -> bool { - if !e.in_gpu_view { + if !e.cpu_backed || !e.in_gpu_view { return false; } let src = mirror_source(e.va); @@ -457,13 +596,9 @@ fn recheck_source(e: &mut Entry) -> bool { true } -/// The title's GPU work writes texture `res` (a copy into it): on the console the memory then -/// holds what the GPU wrote; here the CPU's view of it is stale, so it is not uploaded again -/// (a CPU write elsewhere on its pages – a neighbour, an allocator's header – would upload the -/// stale view over the copy: Fortnite's font atlas is zeros in memory, its glyphs are copied in -/// by the GPU). The first upload, if still pending, stays: it runs before the title's submit -/// that copies. -pub fn note_gpu_write(res: usize) { +/// Prepare a recorded GPU write and capture the current registration generation. Lazy level +/// mappings must exist before submission; provenance itself is published only after submission. +pub(super) fn capture_gpu_write(res: usize, subresource: u32) -> Option<GpuWrite> { if super::vram::level_pages() { // (a texture whose levels get their pages one by one: all of them before the GPU's write) let p = res as *mut c_void; @@ -473,23 +608,65 @@ pub fn note_gpu_write(res: usize) { } } } - let mut marked = false; + let t = TEXTURES.lock().unwrap(); + let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?; + Some(GpuWrite { res, generation: e.generation, subresource }) +} + +/// Publish writes from command-list segments that the native submission gate accepted. On the +/// console their memory now belongs to the GPU result, so its stale CPU view is not uploaded. +#[cfg(test)] +pub(super) fn publish_gpu_writes(queue: WriterQueueId, writes: &[GpuWrite]) { + publish_submission_effects(Some(queue), writes, &[]); +} + +/// Atomically publish a submitted chunk's GPU writers and ordered state transitions. +pub(super) fn publish_submission_effects(queue: Option<WriterQueueId>, writes: &[GpuWrite], transitions: &[Transition]) { + if writes.is_empty() && transitions.is_empty() { + return; + } + let mut newly_written = Vec::new(); { let mut t = TEXTURES.lock().unwrap(); - if let Some(e) = t.get_mut(res) { - if !e.gpu_written { - e.gpu_written = true; - GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); - marked = true; + if let Some(queue) = queue { + for &write in writes { + let Some(e) = t.get_mut(write.res).filter(|e| e.generation == write.generation) else { continue }; + let n = subresource_count(&e.tex); + if write.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES && !(n <= 1 && write.subresource == 0) && write.subresource as usize >= n { + continue; + } + let epoch = NEXT_GPU_EPOCH.fetch_add(1, Ordering::Relaxed) + 1; + let writer = GpuWriter { epoch, queue }; + apply_gpu_writer(&mut e.gpu_writers, n, write.subresource, writer); + if !e.gpu_written { + e.gpu_written = true; + GPU_WRITTEN.fetch_add(1, Ordering::Relaxed); + newly_written.push(write.res); + } + } + } + for &transition in transitions { + let Some(e) = t.get_mut(transition.res).filter(|e| e.generation == transition.generation) else { continue }; + let n = subresource_count(&e.tex); + if transition.subresource != D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES + && !(n <= 1 && transition.subresource == 0) + && transition.subresource as usize >= n + { + continue; } + apply_transition(&mut e.states, n, transition.subresource, transition.after); } } - if marked { - STREAM_RECHECK.lock().unwrap().remove(&res); + if !newly_written.is_empty() { + let mut recheck = STREAM_RECHECK.lock().unwrap(); + for res in newly_written { + recheck.remove(&res); + } } } static GPU_WRITTEN: AtomicU64 = AtomicU64::new(0); +static NEXT_GPU_EPOCH: AtomicU64 = AtomicU64::new(0); /// The textures kept in step whose memory `[va, va + len)` overlaps (PC texture, its address). pub fn overlapping(va: usize, len: usize) -> Vec<(usize, usize)> { @@ -524,7 +701,7 @@ pub(super) unsafe fn retire_overlapping(va: usize, len: usize) { unmap_ptrs.extend(u3); } adjust_pending(delta); - TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + update_lengths(&t); (retired, clone_resources(&unmap_ptrs)) }; for r in &to_unmap { @@ -543,7 +720,7 @@ pub fn forget(res: usize) { let mut t = TEXTURES.lock().unwrap(); let (removed, delta, remap_ptrs) = t.remove(res); adjust_pending(delta); - TEXTURES_LEN.store(t.by_res.len(), Ordering::Relaxed); + update_lengths(&t); (removed, unsafe { clone_resources(&remap_ptrs) }) }; for r in &to_remap { @@ -566,67 +743,58 @@ pub fn address(res: usize) -> Option<usize> { t.by_res.get(&res).or_else(|| t.shadowed.get(&res)).map(|e| e.va) } -/// (texture, subresource or ALL_SUBRESOURCES, state after) of a transition the title recorded -type Transition = (usize, u32, D3D12_RESOURCE_STATES); - -/// PC command list → the transitions of textures kept in step it recorded since it was made or -/// last reset, in order. They apply when the list is submitted – each time: a closed list may -/// run again. -static LIST_NOTES: Mutex<BTreeMap<usize, Vec<Transition>>> = Mutex::new(BTreeMap::new()); +/// A recorded transition of a tracked texture. The registration generation keeps a captured +/// command-list effect from applying to a new resource at a reused COM address. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) struct Transition { + pub(super) res: usize, + pub(super) generation: u64, + pub(super) subresource: u32, + pub(super) after: D3D12_RESOURCE_STATES, +} /// Whether any texture is kept in step (callers skip collecting transitions otherwise). pub fn any() -> bool { TEXTURES_LEN.load(Ordering::Relaxed) != 0 } -/// The title recorded `transitions` on PC list `list`: those of textures kept in step are noted -/// for when the list is submitted. -pub fn note_transitions(list: usize, transitions: &[Transition]) { +/// Capture the transitions of textures currently kept in step while a physical segment records. +pub(super) fn capture_transitions(transitions: &[(usize, u32, D3D12_RESOURCE_STATES)]) -> Vec<Transition> { if !any() || transitions.is_empty() { - return; - } - let kept: Vec<Transition> = { - let t = TEXTURES.lock().unwrap(); - transitions.iter().filter(|(r, _, _)| t.by_res.contains_key(r) || t.shadowed.contains_key(r)).copied().collect() - }; - if !kept.is_empty() { - LIST_NOTES.lock().unwrap().entry(list).or_default().extend(kept); + return Vec::new(); } + let t = TEXTURES.lock().unwrap(); + transitions + .iter() + .filter_map(|&(res, subresource, after)| { + let e = t.by_res.get(&res).or_else(|| t.shadowed.get(&res))?; + Some(Transition { res, generation: e.generation, subresource, after }) + }) + .collect() } -/// PC list `list` starts a new recording (made, reset, released): its noted transitions go. -pub fn list_reset(list: usize) { - let mut g = LIST_NOTES.lock().unwrap(); - if !g.is_empty() { - g.remove(&list); - } +/// Subresources of a texture kept in step (as `subresources` makes them). +fn subresource_count(tex: &xg::Texture) -> usize { + tex.texels().map_or(1, |s| s.array as usize * s.chain.levels.len()) } -/// The PC lists `lists` were submitted, in this order: the textures kept in step are in the -/// states their transitions leave them in. -pub fn submitted(lists: &[*mut c_void]) { - let notes: Vec<Transition> = { - let g = LIST_NOTES.lock().unwrap(); - if g.is_empty() { - return; - } - lists.iter().filter_map(|&l| g.get(&(l as usize))).flatten().copied().collect() - }; - if notes.is_empty() { +/// Apply one writer to all subresources or one known subresource. The representation mirrors +/// `states`: one value while uniform, one per subresource while they differ. +fn apply_gpu_writer(writers: &mut Vec<Option<GpuWriter>>, n: usize, sub: u32, writer: GpuWriter) { + if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES || (n <= 1 && sub == 0) { + *writers = vec![Some(writer)]; return; } - let mut t = TEXTURES.lock().unwrap(); - for (res, sub, after) in notes { - if let Some(e) = t.get_mut(res) { - let n = subresource_count(&e.tex); - apply_transition(&mut e.states, n, sub, after); - } + let k = sub as usize; + if writers.is_empty() { + *writers = vec![None; n]; + } else if writers.len() != n { + *writers = vec![writers[0]; n]; + } + writers[k] = Some(writer); + if writers.iter().all(|&w| w == Some(writer)) { + writers.truncate(1); } -} - -/// Subresources of a texture kept in step (as `subresources` makes them). -fn subresource_count(tex: &xg::Texture) -> usize { - tex.texels().map_or(1, |s| s.array as usize * s.chain.levels.len()) } /// `states` (one for all `n` subresources, or one each) after a transition of subresource `sub` @@ -677,7 +845,14 @@ fn cached_watch_ranges(u: &crate::gpu::uma::Uma) -> Arc<Vec<(usize, usize)>> { // write-watched regions) only when the set of textures, tiles, or reservations changed. let mut regions = u.watch_regions(); regions.extend(crate::hle::kernelx::graphics_reservations()); - let mut wanted: Vec<(usize, usize)> = TEXTURES.lock().unwrap().by_res.values().map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)).collect(); + let mut wanted: Vec<(usize, usize)> = TEXTURES + .lock() + .unwrap() + .by_res + .values() + .filter(|e| e.cpu_backed) + .map(|e| (e.src & !0xFFF, (e.src + e.tex.size() as usize + 0xFFF) & !0xFFF)) + .collect(); wanted.extend(super::sparse::mapped_ranges()); let computed = Arc::new(watch_ranges(®ions, wanted)); *WATCH_CACHE.lock().unwrap() = Some((key, Arc::clone(&computed))); @@ -699,13 +874,21 @@ pub(super) fn is_own_work() -> bool { /// Before the title's GPU work: textures whose memory the CPU wrote since the last look are /// uploaded again. -pub(super) unsafe fn refresh(queue: *mut c_void) { +pub(super) unsafe fn refresh(queue: *mut c_void) -> super::sparse::PreparationOutcome { // the uploads' own ExecuteCommandLists come back here if BUSY.with(|b| b.get()) { - return; + return super::sparse::PreparationOutcome::Ready; } + let measure = super::memory_report::enabled(); + let wait_t0 = measure.then(std::time::Instant::now); let _refresh = REFRESH.lock().unwrap(); - own_work(|| refresh_once(queue)); + let active_t0 = measure.then(std::time::Instant::now); + let mut look = measure.then(super::sparse::LookSample::default); + let outcome = own_work(|| refresh_once(queue, look.as_mut())); + if let (Some(wait_t0), Some(active_t0), Some(look)) = (wait_t0, active_t0, look) { + super::sparse::note_look(look, active_t0.elapsed(), active_t0.duration_since(wait_t0)); + } + outcome } /// The pages of `[base, base + size)` written since the last look, added to `dirty` and reset @@ -728,16 +911,16 @@ unsafe fn take_written(base: usize, size: usize, buf: &mut [*mut c_void], dirty: } } -unsafe fn refresh_once(queue: *mut c_void) { - let Some(u) = crate::gpu::uma::get() else { return }; +unsafe fn refresh_once(queue: *mut c_void, mut look: Option<&mut super::sparse::LookSample>) -> super::sparse::PreparationOutcome { + let Some(u) = crate::gpu::uma::get() else { return super::sparse::PreparationOutcome::Ready }; let sparse = u.has_sparse(); - if !sparse && TEXTURES_LEN.load(Ordering::Relaxed) == 0 { - return; + if !sparse && CPU_TEXTURES_LEN.load(Ordering::Relaxed) == 0 { + return super::sparse::PreparationOutcome::Ready; } recheck_gpu_view_sources(); - let watch_t0 = std::time::Instant::now(); let mut page = 0x1000u32; let ranges = cached_watch_ranges(u); + let watch_t0 = look.is_some().then(std::time::Instant::now); let dirty_len = DIRTY_BUF.with(|dcell| { let mut dirty = dcell.borrow_mut(); dirty.clear(); @@ -753,7 +936,15 @@ unsafe fn refresh_once(queue: *mut c_void) { dirty.sort_unstable(); dirty.len() }); - super::sparse::note_watch(watch_t0.elapsed(), dirty_len); + if let (Some(sample), Some(watch_t0)) = (look.as_deref_mut(), watch_t0) { + super::sparse::note_watch( + sample, + watch_t0.elapsed(), + dirty_len, + ranges.iter().fold(0usize, |bytes, range| bytes.saturating_add(range.1)), + ranges.len(), + ); + } if super::present::trace_frame() { // every 600th look: what the CPU's view of a few textures holds now (does the title's // data reach the address at all, and is the texture still kept in step?) @@ -772,7 +963,7 @@ unsafe fn refresh_once(queue: *mut c_void) { }; let (mut with, mut without) = (0, 0); let mut shown = 0; - for e in t.by_res.values() { + for e in t.by_res.values().filter(|e| e.cpu_backed) { let c = content(e); if c > 0 { with += 1 } else { without += 1 } if c > 0 && shown < 4 { @@ -785,11 +976,23 @@ unsafe fn refresh_once(queue: *mut c_void) { } // the title's own memory: what the CPU wrote goes to its video memory first if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) { - DIRTY_BUF.with(|dcell| { + let outcome = DIRTY_BUF.with(|dcell| { let dirty = dcell.borrow(); - super::sparse::before_execute(q, &dirty, page as usize); - super::vram::before_execute(q); + let mut outcome = super::sparse::PreparationOutcome::RetryRequired; + for _ in 0..3 { + outcome = super::sparse::before_execute(q, &dirty, page as usize, look.as_deref_mut()); + if outcome != super::sparse::PreparationOutcome::RetryRequired { + break; + } + super::real::stop_if_device_removed(); + std::thread::yield_now(); + } + outcome }); + if outcome != super::sparse::PreparationOutcome::Ready { + return outcome; + } + super::vram::before_execute(q); } let recheck_frame = { let (p, b) = super::present::counters(); @@ -797,7 +1000,7 @@ unsafe fn refresh_once(queue: *mut c_void) { }; recheck_streamed_unwatched(&ranges, recheck_frame); if dirty_len == 0 && PENDING.load(Ordering::Relaxed) == 0 { - return; + return super::sparse::PreparationOutcome::Ready; } // textures made since the last submit and those with a written page; a reference each // while they are uploaded @@ -807,6 +1010,9 @@ unsafe fn refresh_once(queue: *mut c_void) { t.by_res .iter_mut() .filter(|(_, e)| { + if !e.cpu_backed { + return false; + } if e.pending { return true; } @@ -822,12 +1028,14 @@ unsafe fn refresh_once(queue: *mut c_void) { PENDING.fetch_sub(1, Ordering::Relaxed); } let p = res as *mut c_void; - ID3D12Resource::from_raw_borrowed(&p).map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone()))) + ID3D12Resource::from_raw_borrowed(&p) + .map(|r| (r.clone(), (e.device, e.src, Arc::clone(&e.tex), e.states.clone(), e.generation))) }) .collect() }); seed_stream_recheck(&todo, &ranges, recheck_frame); - upload_all(todo); + upload_all(todo, ID3D12CommandQueue::from_raw_borrowed(&queue)); + super::sparse::PreparationOutcome::Ready } /// texture → `content_hash` of its memory at its last upload @@ -944,7 +1152,7 @@ unsafe fn seed_stream_recheck(todo: &[(ID3D12Resource, Upload)], watched: &[(usi return; } let mut seeded = Vec::new(); - for (r, (_, src, tex, _)) in todo { + for (r, (_, src, tex, _, _)) in todo { let size = tex.size() as usize; if size == 0 || range_is_fully_watched(*src, size, watched) { continue; @@ -1087,8 +1295,146 @@ fn batch_fits(picked_count: usize, picked_bytes: usize, batch_dev: usize, next_d && picked_bytes.saturating_add(next_bytes) <= BATCH_BYTES) } +struct QueueUploads { + fence: ID3D12Fence, + value: u64, + in_flight: std::collections::VecDeque<(u64, texture::InFlight)>, + bytes: u64, +} + +unsafe impl Send for QueueUploads {} + +type QueueUploadState = Arc<Mutex<Option<QueueUploads>>>; + +/// Queue-local serialization for upload retirement. The registry is held only long enough to +/// acquire a strong state lease; driver calls and waits on one title queue do not block another. +static ON_QUEUE: Mutex<BTreeMap<usize, QueueUploadState>> = Mutex::new(BTreeMap::new()); + +fn queue_upload_state(key: usize) -> QueueUploadState { + Arc::clone( + ON_QUEUE + .lock() + .unwrap() + .entry(key) + .or_insert_with(|| Arc::new(Mutex::new(None))), + ) +} + +/// Drop completed uploads cached for a retired title queue after releasing the cache lock. +pub(super) fn forget_queue(id: super::present::QueueId) { + let gone = ON_QUEUE.lock().unwrap().remove(&id.raw()); + drop(gone); +} + +const IN_FLIGHT_BYTES: u64 = 512 << 20; + +unsafe fn title_queue_for(dev: &ID3D12Device, title: Option<&ID3D12CommandQueue>) -> Option<ID3D12CommandQueue> { + let q = title?; + if !super::present::queue_accepts_internal_work(q.as_raw() as usize) { + return None; + } + if q.GetDesc().Type != D3D12_COMMAND_LIST_TYPE_DIRECT { + return None; + } + let mut qd: Option<ID3D12Device> = None; + q.GetDevice(&mut qd).ok()?; + (qd?.as_raw() == dev.as_raw()).then(|| q.clone()) +} + +unsafe fn reclaim(dev: &ID3D12Device, q: &mut QueueUploads, cap: u64, wait_ms: u32) -> Vec<texture::InFlight> { + let mut retired = Vec::new(); + let done = q.fence.GetCompletedValue(); + while q.in_flight.front().is_some_and(|&(v, _)| v <= done) { + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes -= f.bytes; + retired.push(f); + } + while q.bytes > cap { + let Some(&(v, _)) = q.in_flight.front() else { break }; + if crate::gpu::fence::wait(&q.fence, v, dev, None, wait_ms).is_err() { + break; + } + let (_, f) = q.in_flight.pop_front().unwrap(); + q.bytes -= f.bytes; + retired.push(f); + } + retired +} + +unsafe fn submit_on_title_queue( + dev: &ID3D12Device, + queue: &ID3D12CommandQueue, + batch: &[texture::UploadBatchItem], + zero_mips: &[Vec<bool>], +) -> Result<Vec<(usize, String)>, String> { + // The textures' tile mappings made since the title queue last waited for them (a texture + // made on another thread after `refresh_once`'s wait, or its levels mapped just now by + // `map_levels_with_texels`): a copy into a tile still unmapped is a copy-engine page fault + // on NVIDIA (`DmaPageFaultWrite`), as the upload queue's own path already waits for. + super::vram::before_execute(queue); + let (failed, f) = texture::submit_batch_with_zero_mips(dev, queue, batch, zero_mips)?; + let Some(f) = f else { return Ok(failed) }; + let key = queue.as_raw() as usize; + let state = queue_upload_state(key); + let mut slot = state.lock().unwrap(); + if slot.is_none() { + match dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE) { + Ok(fence) => { + *slot = Some(QueueUploads { fence, value: 0, in_flight: std::collections::VecDeque::new(), bytes: 0 }); + } + Err(e) => { + drop(slot); + texture::drop_after_wait(f, texture::wait(dev, queue))?; + return Err(e.to_string()); + } + } + } + let q = slot.as_mut().unwrap(); + q.value += 1; + if let Err(e) = super::real::native_queue_signal(queue, &q.fence, q.value) { + q.value -= 1; + drop(slot); + texture::drop_after_wait(f, texture::wait(dev, queue))?; + return Err(e.to_string()); + } + q.bytes += f.bytes; + let v = q.value; + q.in_flight.push_back((v, f)); + let retired = reclaim(dev, q, IN_FLIGHT_BYTES, 10_000); + drop(slot); + drop(retired); + Ok(failed) +} + +/// A preparation worker failed before this exact batch could be submitted. A texture still at the +/// captured registration generation is made pending again; a replacement, removal, GPU writer, or +/// non-CPU-backed entry owns its own state and must not be changed by the stale work item. +fn requeue_failed_preparation(picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>, u64)]) { + let keys: Vec<_> = picked.iter().map(|(resource, _, _, _, generation)| (resource.as_raw() as usize, *generation)).collect(); + let mut table = TEXTURES.lock().unwrap(); + let added = requeue_generations(&mut table, &keys); + if !added.is_empty() { + PENDING.fetch_add(added.len(), Ordering::Relaxed); + } + drop(table); + let mut content = LAST_CONTENT.lock().unwrap(); + for resource in added { content.remove(&resource); } +} + +fn requeue_generations(table: &mut Table, keys: &[(usize, u64)]) -> Vec<usize> { + let mut added = Vec::new(); + for &(resource, generation) in keys { + let Some(entry) = table.by_res.get_mut(&resource) else { continue }; + if entry.generation == generation && entry.cpu_backed && !entry.gpu_written && !entry.pending { + entry.pending = true; + added.push(resource); + } + } + added +} + /// The uploads `todo`, in batches of up to `BATCH_BYTES` and `BATCH_ITEMS` (one list and one wait each). -unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { +unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>, title: Option<&ID3D12CommandQueue>) { static N: AtomicU64 = AtomicU64::new(0); let warn = |e: &str| { if N.fetch_add(1, Ordering::Relaxed) < 4 { @@ -1100,11 +1446,11 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { let mut picked = Vec::new(); let mut bytes = 0usize; let mut device = 0usize; - while let Some((_, (dev, _, tex, _))) = todo.peek() { + while let Some((_, (dev, _, tex, _, _))) = todo.peek() { if !batch_fits(picked.len(), bytes, device, *dev, tex.size() as usize) { break; } - let (r, (dev, va, tex, states)) = todo.next().unwrap(); + let (r, (dev, va, tex, states, generation)) = todo.next().unwrap(); // The same bytes as at this texture's last upload: nothing to do. The write watch is // per page and a title writes next to its textures (and rewrites what it wrote): a // retail title's video planes and UI targets went up again for every submit, ~25 MB @@ -1121,25 +1467,43 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { } device = dev; bytes += tex.size() as usize; - picked.push((r, va, tex, states)); + picked.push((r, va, tex, states, generation)); } if picked.is_empty() { continue; } - let subs = subresources_of_all(&picked, bytes); + let Some(subs) = subresources_of_all(&picked, bytes) else { + requeue_failed_preparation(&picked); + warn("a texture preparation worker stopped; the batch will be retried"); + continue; + }; let mut batch = Vec::with_capacity(picked.len()); - for ((r, va, _, states), subs) in picked.into_iter().zip(subs) { + let mut zero_mips = Vec::new(); + let level_pages = super::vram::level_pages(); + for ((r, va, _, states, _), subs) in picked.into_iter().zip(subs) { if super::present::trace_frame() { note_content(va, &r, &subs); } - if super::vram::level_pages() { + if level_pages { // (the queue waits for these mappings before the copies: `vram::before_execute` below) - map_levels_with_texels(&r, &subs); + zero_mips.push(map_levels_with_texels(&r, &subs)); } batch.push((r, subs, states)); } let d = device as *mut c_void; let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { continue }; + if let Some(tq) = title_queue_for(dev, title) { + match own_work(|| submit_on_title_queue(dev, &tq, &batch, &zero_mips)) { + Ok(failed) => { + for (_, e) in failed { + warn(&e); + } + UPLOADS.fetch_add(batch.len() as u64, Ordering::Relaxed); + } + Err(e) => warn(&e), + } + continue; + } let queue = match upload_queue(dev, device) { Ok(q) => q, Err(e) => { @@ -1149,7 +1513,7 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { }; match own_work(|| { super::vram::before_execute(&queue); - texture::upload_batch(dev, &queue, &batch) + texture::upload_batch_with_zero_mips(dev, &queue, &batch, &zero_mips) }) { Ok(failed) => { for (_, e) in failed { @@ -1164,17 +1528,18 @@ unsafe fn upload_all(todo: Vec<(ID3D12Resource, Upload)>) { /// (`vram::level_pages`) Before an upload of title texture `r`: its levels with texels in `subs` /// (its subresources as they go up) get their video memory pages if they have none - a texture -/// placed with lazy levels; any other: nothing to do. A level of zeros has no texels: a streamed -/// texture's larger levels before the title has memory behind them (read as zeros, -/// `read_committed`). It keeps no pages, reads as zeros as it would with them, and its copy goes -/// to tiles that are not mapped, which drops it (tiled resources tier 2). -unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) { +/// placed with lazy levels. Return a mask of zero levels so their copies can share staging. +/// A level of zeros needs no new pages. Its copy still clears any existing tiles, including a +/// previously streamed level or tiles mapped for other levels in the same packed tail. +unsafe fn map_levels_with_texels(r: &ID3D12Resource, subs: &[Subresource]) -> Vec<bool> { if !super::vram::has_lazy_levels(r.as_raw() as usize) { - return; + return Vec::new(); } // (one slice: its subresources are its levels) - let present: Vec<u32> = subs.iter().enumerate().filter(|(_, s)| !all_zero(&s.data)).map(|(i, _)| i as u32).collect(); + let zero: Vec<bool> = subs.iter().map(|s| all_zero(&s.data)).collect(); + let present: Vec<u32> = zero.iter().enumerate().filter_map(|(i, &zero)| (!zero).then_some(i as u32)).collect(); super::vram::map_levels(r, Some(&present)); + zero } /// Whether every byte of `b` is zero (eight at a time: gigabytes a second where it is). @@ -1261,7 +1626,8 @@ pub unsafe fn probe_gpu_content(res: usize) { list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, srv)]); list.Close().map_err(|e| e.to_string())?; - queue.ExecuteCommandLists(&[Some(list.cast().map_err(|e| e.to_string())?)]); + let list = list.cast().map_err(|e| e.to_string())?; + super::real::native_queue_execute(&queue, &list); texture::wait(dev, &queue)?; let mut p: *mut c_void = std::ptr::null_mut(); rb.Map(0, None, Some(&mut p)).map_err(|e| e.to_string())?; @@ -1309,11 +1675,11 @@ unsafe fn upload_queue(dev: &ID3D12Device, device: usize) -> Result<ID3D12Comman } /// Ranges closer than this are scanned as one. A write-watch call costs ~3.5 µs however little it -/// covers, while one call over 2 GiB of committed pages takes ~1.3 ms (measured on Windows 11): a -/// retail game's intro video had its submitting thread at 42 % in GetWriteWatch with a 1 MiB gap -/// (thousands of calls before each submit over its mapped sparse tiles). The pages of a gap are -/// reported as written too; the uploads keep to what they track. -const WATCH_GAP: usize = 64 << 20; +/// covers, while 2 GiB of committed pages took 0.8–1.3 ms on Windows 11: an extra call breaks even +/// with scanning roughly 5–9 MiB of gap. Eight MiB still joins the 1 MiB-spaced sparse ranges that +/// otherwise made thousands of calls per submit, without scanning up to 64 MiB of unrelated pages +/// between ranges. Gap pages may be reported too; uploads still keep to the ranges they track. +const WATCH_GAP: usize = 8 << 20; /// The parts of `wanted` (start, end) inside `regions` (base, size), merged (gaps under /// `WATCH_GAP` too) and sorted, as (base, size) – each within one region (a write-watch call @@ -1413,16 +1779,94 @@ unsafe fn read_committed(at: usize, len: usize) -> Vec<u8> { /// Batches of at least this many bytes are detiled on several threads (`subresources_of_all`) const PARALLEL_BYTES: usize = 1 << 20; +struct DetileJob { + index: usize, + va: usize, + tex: Arc<xg::Texture>, + done: std::sync::mpsc::Sender<(usize, Option<Vec<Subresource>>)>, +} + +struct DetilePool { + jobs: std::sync::mpsc::Sender<DetileJob>, + workers: usize, +} + +fn detile_pool() -> &'static DetilePool { + static POOL: std::sync::OnceLock<DetilePool> = std::sync::OnceLock::new(); + POOL.get_or_init(|| { + let wanted = std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8); + let (jobs, receive) = std::sync::mpsc::channel::<DetileJob>(); + let receive = Arc::new(Mutex::new(receive)); + let mut workers = 0; + for k in 0..wanted { + let receive = Arc::clone(&receive); + let made = std::thread::Builder::new().name(format!("xcl-detile-{k}")).spawn(move || loop { + let job = { + let receive = receive.lock().unwrap_or_else(|e| e.into_inner()); + receive.recv() + }; + let Ok(job) = job else { break }; + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| unsafe { + subresources(job.va, &job.tex) + })) + .ok(); + let _ = job.done.send((job.index, result)); + }); + if made.is_ok() { + workers += 1; + } + } + DetilePool { jobs, workers } + }) +} + /// `subresources` of every texture of a batch (`bytes` of them), in order: on several threads -/// when the batch is big. They were read and detiled one after another in the title's own -/// submit – most of a retail game's render thread while it streamed textures the CPU writes. -unsafe fn subresources_of_all(picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>)], bytes: usize) -> Vec<Vec<Subresource>> { - let picked: Vec<(usize, &xg::Texture)> = picked.iter().map(|(_, va, tex, _)| (*va, &**tex)).collect(); - let threads = if bytes < PARALLEL_BYTES { 1 } else { std::thread::available_parallelism().map_or(1, |n| n.get() / 2).clamp(1, 8) }; - subresources_on(&picked, threads) +/// when the batch is big. Process-lifetime workers avoid creating and joining up to eight OS +/// threads in every title submit. None means a worker or its queue stopped; the caller retries the +/// exact registration generation rather than uploading an incomplete texture. +unsafe fn subresources_of_all( + picked: &[(ID3D12Resource, usize, Arc<xg::Texture>, Vec<D3D12_RESOURCE_STATES>, u64)], + bytes: usize, +) -> Option<Vec<Vec<Subresource>>> { + let work: Vec<_> = picked.iter().map(|(_, va, tex, _, _)| (*va, Arc::clone(tex))).collect(); + pooled_subresources(&work, bytes) +} + +unsafe fn pooled_subresources(picked: &[(usize, Arc<xg::Texture>)], bytes: usize) -> Option<Vec<Vec<Subresource>>> { + if bytes < PARALLEL_BYTES || picked.len() <= 1 { + return Some(picked.iter().map(|(va, tex)| subresources(*va, tex)).collect()); + } + let pool = detile_pool(); + if pool.workers == 0 { + return None; + } + let (done, results) = std::sync::mpsc::channel(); + for (index, (va, tex)) in picked.iter().enumerate() { + if pool.jobs.send(DetileJob { index, va: *va, tex: Arc::clone(tex), done: done.clone() }).is_err() { + return None; + } + } + drop(done); + ordered_subresources(picked.len(), results) +} + +fn ordered_subresources( + count: usize, + results: impl IntoIterator<Item = (usize, Option<Vec<Subresource>>)>, +) -> Option<Vec<Vec<Subresource>>> { + let mut out: Vec<Option<Vec<Subresource>>> = (0..count).map(|_| None).collect(); + let mut failed = false; + for (index, result) in results { + match (out.get_mut(index), result) { + (Some(slot), Some(result)) if slot.is_none() => *slot = Some(result), + _ => failed = true, + } + } + (!failed).then(|| out.into_iter().collect()).flatten() } /// `subresources` of each (address, texture), in order, on up to `threads` threads. +#[cfg(test)] unsafe fn subresources_on(picked: &[(usize, &xg::Texture)], threads: usize) -> Vec<Vec<Subresource>> { let threads = threads.min(picked.len()); if threads <= 1 { @@ -1483,72 +1927,1074 @@ unsafe fn subresources(va: usize, tex: &xg::Texture) -> Vec<Subresource> { out } +/// The bounded part of a mapped D3D12 readback buffer which holds one subresource. +/// `width`, `height`, and `depth` are texels (not format blocks); `size` bounds all reads. +#[derive(Clone, Copy, Debug)] +#[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. +pub(super) struct ReadbackFootprint { + pub offset: usize, + pub size: usize, + pub row_pitch: usize, + pub width: u32, + pub height: u32, + pub depth: u32, + pub format: u32, +} -#[cfg(test)] -mod tests { - use super::*; +#[derive(Debug, PartialEq, Eq)] +#[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. +pub(super) enum ReverseLayoutError { + UnsupportedLayout, + Format, + Subresource, + Dimensions, + RowPitch, + Footprint, + Destination, +} - /// A texture is left out only when its memory hashes as at its own last upload, and a - /// texture that was forgotten (released, or its address registered again) is uploaded again. - #[test] - fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() { - let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); - let mut mem = vec![0u8; 3 << 20]; - mem[5] = 1; - let h = content_hash(&mem); - assert!(!same_as_last_upload(a, h), "the first upload is not left out"); - assert!(same_as_last_upload(a, h), "the same bytes again: left out"); - assert!(!same_as_last_upload(b, h), "another texture over the same bytes has its own first upload"); - // one byte anywhere, also in the tail that is not a whole 32-byte step - for at in [0usize, 31, 32, (3 << 20) - 1] { - let mut m = mem.clone(); - m[at] ^= 0x80; - assert_ne!(content_hash(&m), h, "byte {at} changed"); +/// Put one exact PC readback footprint back into its XG-tiled subresource. This is deliberately +/// pure: callers own both byte slices, and no resource, queue, title address, or COM object is +/// touched. Metadata planes and format conversions are not reconstructible and fail closed. +#[allow(dead_code)] // Stage 3 seam; queue/readback activation is a later change. +pub(super) fn reverse_layout_subresource( + tex: &xg::Texture, + format: u32, + subresource: u32, + footprint: ReadbackFootprint, + readback: &[u8], + console: &mut [u8], +) -> Result<(), ReverseLayoutError> { + if tex.main != 0 || tex.planes.len() != 1 { + return Err(ReverseLayoutError::UnsupportedLayout); + } + let (surface, plane_offset) = tex.plane_surface(0).ok_or(ReverseLayoutError::UnsupportedLayout)?; + let (elem_log2, side) = xg::element(format).ok_or(ReverseLayoutError::Format)?; + if footprint.format != format || surface.bpe != 1u32 << elem_log2 || surface.side != side { + return Err(ReverseLayoutError::Format); + } + let mips = surface.chain.levels.len(); + let (mip, slice) = if surface.depth > 0 { + let mip = usize::try_from(subresource).map_err(|_| ReverseLayoutError::Subresource)?; + if mip >= mips { + return Err(ReverseLayoutError::Subresource); } - mem[(3 << 20) - 1] = 9; - let h2 = content_hash(&mem); - assert!(!same_as_last_upload(a, h2), "changed memory is uploaded"); - assert!(same_as_last_upload(a, h2)); - // the length is part of the content: a prefix of zeros is not the whole - assert_ne!(content_hash(&[0u8; 64]), content_hash(&[0u8; 96])); - forget(a); - assert!(!same_as_last_upload(a, h2), "forgotten: its next upload is a first one"); - forget(a); - forget(b); + (mip, None) + } else { + let total = mips.checked_mul(surface.array as usize).ok_or(ReverseLayoutError::Subresource)?; + let sub = usize::try_from(subresource).map_err(|_| ReverseLayoutError::Subresource)?; + if sub >= total { + return Err(ReverseLayoutError::Subresource); + } + (sub % mips, Some(sub / mips)) + }; + let level = &surface.chain.levels[mip]; + let width = (surface.width >> mip).max(1); + let height = (surface.height >> mip).max(1); + let depth = if surface.depth > 0 { (surface.depth >> mip).max(1) } else { 1 }; + if footprint.width != width || footprint.height != height || footprint.depth != depth { + return Err(ReverseLayoutError::Dimensions); } + let row_bytes = level.width.checked_mul(surface.bpe as usize).ok_or(ReverseLayoutError::Footprint)?; + if level.width != (width as usize).div_ceil(side as usize) + || level.height != (height as usize).div_ceil(side as usize) + || level.depth != depth as usize + { + return Err(ReverseLayoutError::UnsupportedLayout); + } + if footprint.row_pitch < row_bytes || footprint.row_pitch % 256 != 0 || footprint.offset % 512 != 0 { + return Err(ReverseLayoutError::RowPitch); + } + let slice_pitch = footprint.row_pitch.checked_mul(level.height).ok_or(ReverseLayoutError::Footprint)?; + let last_slice = slice_pitch.checked_mul(level.depth.saturating_sub(1)).ok_or(ReverseLayoutError::Footprint)?; + let last_row = footprint.row_pitch.checked_mul(level.height.saturating_sub(1)).ok_or(ReverseLayoutError::Footprint)?; + let used = last_slice.checked_add(last_row).and_then(|n| n.checked_add(row_bytes)).ok_or(ReverseLayoutError::Footprint)?; + let footprint_end = footprint.offset.checked_add(footprint.size).ok_or(ReverseLayoutError::Footprint)?; + if used > footprint.size || footprint_end > readback.len() { + return Err(ReverseLayoutError::Footprint); + } + let console_size = usize::try_from(tex.size()).map_err(|_| ReverseLayoutError::Destination)?; + if console.len() < console_size { + return Err(ReverseLayoutError::Destination); + } + let linear_size = row_bytes + .checked_mul(level.height) + .and_then(|n| n.checked_mul(level.depth)) + .ok_or(ReverseLayoutError::Footprint)?; + let mut linear = Vec::new(); + linear.try_reserve_exact(linear_size).map_err(|_| ReverseLayoutError::Footprint)?; + linear.resize(linear_size, 0); + for z in 0..level.depth { + for y in 0..level.height { + let from = footprint.offset + z * slice_pitch + y * footprint.row_pitch; + let to = (z * level.height + y) * row_bytes; + linear[to..to + row_bytes].copy_from_slice(&readback[from..from + row_bytes]); + } + } + let plane_at = usize::try_from(plane_offset).map_err(|_| ReverseLayoutError::Destination)?; + if let Some(slice) = slice { + let at = plane_at + .checked_add(slice.checked_mul(surface.chain.slice_bytes).ok_or(ReverseLayoutError::Destination)?) + .ok_or(ReverseLayoutError::Destination)?; + let end = at.checked_add(surface.chain.slice_bytes).ok_or(ReverseLayoutError::Destination)?; + let dst = console.get_mut(at..end).ok_or(ReverseLayoutError::Destination)?; + surface.chain.tile_level(dst, mip, slice, &linear); + } else { + let bytes = usize::try_from(surface.size()).map_err(|_| ReverseLayoutError::Destination)?; + let end = plane_at.checked_add(bytes).ok_or(ReverseLayoutError::Destination)?; + let dst = console.get_mut(plane_at..end).ok_or(ReverseLayoutError::Destination)?; + surface.chain.tile_volume(dst, mip, &linear); + } + Ok(()) +} - /// Real uploads, dirty-page detection and a source changing after registration: - /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. - #[test] - fn gpu_mirror_upload_follows_cpu_writes_and_later_mapping_changes() { - use crate::hle::kernelx; - use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; - use windows_sys::Win32::System::Memory as mem; +#[derive(Clone, Copy, Debug)] +#[allow(dead_code)] +pub(super) struct DownloadSubresource { + pub subresource: u32, + pub state: D3D12_RESOURCE_STATES, + pub footprint: ReadbackFootprint, +} - let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); - if super::super::backend() != super::super::Backend::Real { - crate::gpu::recomp::runner::skip_test("no GPU"); - return; - } - // Larger than all four UMA windows together. These public allocations - // must use the watched Windows fallback, reserving space rather than RAM. - const SIZE: usize = 24usize << 30; - const OFFSET: usize = 0x2_0000; - const PAGE: usize = 0x1_0000; - struct Reservation(usize); - impl Drop for Reservation { - fn drop(&mut self) { - unsafe { kernelx::VirtualFree(self.0 as *mut c_void, 0, mem::MEM_RELEASE); } - } +/// Validate driver footprints against the immutable XG layout and explicit tracked states. +/// The driver may add only the required D3D row/placement alignment, never enlarge the work. +fn validate_download_layout( + tex: &xg::Texture, + desc: &D3D12_RESOURCE_DESC, + format: u32, + selected: &[(u32, D3D12_RESOURCE_STATES)], + driver: &[(D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u32, u64)], +) -> Result<(Vec<DownloadSubresource>, usize), String> { + let surface = tex.texels().ok_or("no texel surface")?; + let (elem_log2, side) = xg::element(format).ok_or("unsupported texture format")?; + if tex.main != 0 + || tex.planes.len() != 1 + || surface.bpe != 1u32 << elem_log2 + || surface.side != side + || desc.Dimension.0 as u32 != tex.dimension() + || desc.SampleDesc.Count != 1 + || desc.SampleDesc.Quality != 0 + || desc.Format.0 as u32 != format + { + return Err("unsupported metadata, samples, or format conversion".into()); + } + let mips = surface.chain.levels.len(); + let layers = if surface.depth > 0 { surface.depth } else { surface.array }; + if desc.Width != surface.width as u64 + || desc.Height != surface.height + || desc.DepthOrArraySize as u32 != layers + || desc.MipLevels as usize != mips + || selected.is_empty() + || selected.len() != driver.len() + { + return Err("resource shape or selection differs from the retained layout".into()); + } + let subresources = if surface.depth > 0 { mips } else { mips.checked_mul(surface.array as usize).ok_or("subresource count overflow")? }; + let mut seen = Vec::new(); + seen.try_reserve_exact(subresources).map_err(|_| "cannot allocate download selection")?; + seen.resize(subresources, false); + let mut out = Vec::new(); + out.try_reserve_exact(selected.len()).map_err(|_| "cannot allocate download layout")?; + let mut total = 0usize; + for (&(subresource, state), &(placed, rows, driver_row_bytes)) in selected.iter().zip(driver) { + if state.0 < 0 { + return Err("invalid tracked resource state".into()); } - struct RegisteredTexture(usize); - impl Drop for RegisteredTexture { - fn drop(&mut self) { forget(self.0); } + let sub = subresource as usize; + let (mip, depth) = if surface.depth > 0 { + if sub >= mips { return Err("subresource out of range".into()) } + (sub, (surface.depth >> sub).max(1)) + } else { + let count = mips.checked_mul(surface.array as usize).ok_or("subresource count overflow")?; + if sub >= count { return Err("subresource out of range".into()) } + (sub % mips, 1) + }; + if std::mem::replace(&mut seen[sub], true) { return Err("duplicate subresource".into()) } + let level = &surface.chain.levels[mip]; + let width = (surface.width >> mip).max(1); + let height = (surface.height >> mip).max(1); + let row_bytes = level.width.checked_mul(surface.bpe as usize).ok_or("row size overflow")?; + let expected_pitch = row_bytes.checked_next_multiple_of(256).ok_or("row pitch overflow")?; + let expected_offset = total.checked_next_multiple_of(512).ok_or("footprint offset overflow")?; + if placed.Offset != expected_offset as u64 + || placed.Footprint.Format.0 as u32 != format + || placed.Footprint.Width != width + || placed.Footprint.Height != height + || placed.Footprint.Depth != depth + || placed.Footprint.RowPitch as usize != expected_pitch + || rows as usize != level.height + || driver_row_bytes != row_bytes as u64 + || level.depth != depth as usize + { + return Err("driver footprint differs from the exact subresource".into()); } - struct PhysicalPage { id: usize, at: usize } - impl Drop for PhysicalPage { - fn drop(&mut self) { + let slice_pitch = expected_pitch.checked_mul(level.height).ok_or("slice pitch overflow")?; + let used = slice_pitch + .checked_mul(level.depth.saturating_sub(1)) + .and_then(|n| n.checked_add(expected_pitch.checked_mul(level.height.saturating_sub(1))?)) + .and_then(|n| n.checked_add(row_bytes)) + .ok_or("footprint size overflow")?; + total = expected_offset.checked_add(used).ok_or("download size overflow")?; + out.push(DownloadSubresource { + subresource, + state, + footprint: ReadbackFootprint { offset: expected_offset, size: used, row_pitch: expected_pitch, width, height, depth, format }, + }); + } + Ok((out, total)) +} + +struct DownloadObjects { + _source: ID3D12Resource, + readback: ID3D12Resource, + _allocator: ID3D12CommandAllocator, + list: ID3D12CommandList, + _queue: ID3D12CommandQueue, + _fence_hold: ID3D12Fence, +} + +/// A closed command list and every object it may reference. The caller must hold its state/order +/// serialization from the supplied state snapshot until `submit` inserts this list immediately +/// after the writers represented by that snapshot; otherwise the recorded barriers are stale. +#[allow(dead_code)] +pub(super) struct TextureDownloadPlan { + device: ID3D12Device, + queue_type: D3D12_COMMAND_LIST_TYPE, + tex: Arc<xg::Texture>, + source: ID3D12Resource, + readback: ID3D12Resource, + allocator: ID3D12CommandAllocator, + list: ID3D12CommandList, + fence: ID3D12Fence, + footprints: Vec<DownloadSubresource>, + bytes: usize, +} + +#[allow(dead_code)] +pub(super) struct SubmittedDownload { + pub ticket: PendingDownload, + /// `Some` means Execute had no reportable result and the following Signal failed. The ticket + /// can never be mapped and deliberately retains/leaks its objects rather than releasing them. + pub signal_error: Option<String>, +} + +#[allow(dead_code)] +pub(super) struct PendingDownload { + tex: Arc<xg::Texture>, + objects: Option<DownloadObjects>, + fence: ID3D12Fence, + fence_value: Option<u64>, + footprints: Vec<DownloadSubresource>, + bytes: usize, +} + +impl Drop for PendingDownload { + fn drop(&mut self) { + let done = self.fence_value.is_some_and(|v| { + let got = unsafe { super::real::native_fence_completed(&self.fence) }; + got != u64::MAX && got >= v + }); + if !done { + if let Some(objects) = self.objects.take() { + std::mem::forget(objects); + } + } + } +} + +#[allow(dead_code)] +impl PendingDownload { + pub fn is_complete(&self) -> bool { + self.fence_value.is_some_and(|v| { + let got = unsafe { super::real::native_fence_completed(&self.fence) }; + got != u64::MAX && got >= v + }) + } + + /// Copy the mapped readback only after the submission fence is observed. No wait is done. + pub unsafe fn readback_bytes(&self) -> Result<Option<Vec<u8>>, String> { + if !self.is_complete() { + return Ok(None); + } + let objects = self.objects.as_ref().ok_or("download objects unavailable")?; + let mut bytes = Vec::new(); + bytes.try_reserve_exact(self.bytes).map_err(|_| "cannot allocate completed texture download")?; + let mut p = std::ptr::null_mut(); + objects + .readback + .Map(0, Some(&D3D12_RANGE { Begin: 0, End: self.bytes }), Some(&mut p)) + .map_err(|e| e.to_string())?; + if p.is_null() { + objects.readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + return Err("readback Map returned no address".into()); + } + bytes.extend_from_slice(std::slice::from_raw_parts(p as *const u8, self.bytes)); + objects.readback.Unmap(0, Some(&D3D12_RANGE { Begin: 0, End: 0 })); + Ok(Some(bytes)) + } + + pub fn footprints(&self) -> &[DownloadSubresource] { &self.footprints } + pub fn layout(&self) -> &xg::Texture { &self.tex } + + fn arm(&self, event: windows::Win32::Foundation::HANDLE) { + if let Some(value) = self.fence_value { unsafe { let _ = self.fence.SetEventOnCompletion(value, event); } } + } +} + +#[allow(dead_code)] +impl TextureDownloadPlan { + /// Execute the already-closed list at the caller's serialized queue position. Ownership is + /// transferred to the pending ticket before Execute because ExecuteCommandLists has no status. + pub unsafe fn submit(self, queue: &ID3D12CommandQueue) -> Result<SubmittedDownload, String> { + let mut queue_device: Option<ID3D12Device> = None; + queue.GetDevice(&mut queue_device).map_err(|e| e.to_string())?; + if queue.GetDesc().Type != self.queue_type + || queue_device.as_ref().is_none_or(|d| d.as_raw() != self.device.as_raw()) + { + return Err("texture download queue type or source device differs from its plan".into()); + } + let mut pending = PendingDownload { + tex: self.tex, + objects: Some(DownloadObjects { + _source: self.source, + readback: self.readback, + _allocator: self.allocator, + list: self.list, + _queue: queue.clone(), + _fence_hold: self.fence.clone(), + }), + fence: self.fence, + fence_value: None, + footprints: self.footprints, + bytes: self.bytes, + }; + let list = pending.objects.as_ref().unwrap().list.clone(); + super::real::native_queue_execute(queue, &list); + let signal_error = match super::real::native_queue_signal(queue, &pending.fence, 1) { + Ok(()) => { pending.fence_value = Some(1); None } + Err(e) => Some(e.to_string()), + }; + Ok(SubmittedDownload { ticket: pending, signal_error }) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct DownloadWrite { subresource: u32, state: D3D12_RESOURCE_STATES, writer: GpuWriter } + +pub(super) struct ReadyDownload { res: usize, generation: u64, target: usize, format: u32, writes: Vec<DownloadWrite>, ticket: PendingDownload } + +struct FenceDownloads { fence: ID3D12Fence, value: u64, downloads: Vec<Option<ReadyDownload>> } + +#[derive(Default)] +struct FenceDownloadState { + batches: Vec<FenceDownloads>, + /// A detached fence is being published outside this mutex. Its mirrored completion must + /// remain hidden until the owner restores any work which could not be published. + processing: BTreeSet<usize>, + /// Ties which have claimed a fence but have not installed their batch yet. Native polling, + /// event arming, and reservation bookkeeping stay outside this mutex during that interval. + tying: BTreeMap<usize, usize>, +} + +impl FenceDownloadState { + /// Register an installer. True means this is the first pending work for this fence and must + /// ensure that a safe baseline exists. Production fences are AddRef-retained for the process + /// lifetime, so their raw addresses cannot be reused while this state matters. + fn begin_tie(&mut self, fence: usize) -> bool { + let initialize_safe = !self.processing.contains(&fence) + && !self.tying.contains_key(&fence) + && !self.batches.iter().any(|batch| batch.fence.as_raw() as usize == fence); + *self.tying.entry(fence).or_insert(0) += 1; + initialize_safe + } + + fn finish_tie(&mut self, fence: usize) { + let count = self.tying.get_mut(&fence).expect("finishing an unregistered texture download tie"); + *count -= 1; + if *count == 0 { self.tying.remove(&fence); } + } + + fn tie_in_progress(&self, fence: usize) -> bool { + self.tying.contains_key(&fence) + } + + fn begin_processing(&mut self, fence: usize) -> bool { + !self.tie_in_progress(fence) && self.processing.insert(fence) + } + + fn any_pending(&self) -> bool { + !self.batches.is_empty() || !self.processing.is_empty() || !self.tying.is_empty() + } +} + +static FENCE_DOWNLOADS: Mutex<FenceDownloadState> = Mutex::new(FenceDownloadState { + batches: Vec::new(), + processing: BTreeSet::new(), + tying: BTreeMap::new(), +}); +static DOWNLOADS_PENDING: AtomicBool = AtomicBool::new(false); +static SCHEDULED_DOWNLOADS: Mutex<BTreeSet<(usize, u64, u64, u32, u64)>> = Mutex::new(BTreeSet::new()); +static SAFE_FENCE_VALUES: Mutex<BTreeMap<usize, u64>> = Mutex::new(BTreeMap::new()); + +fn ensure_safe_baseline(values: &mut BTreeMap<usize, u64>, fence: usize) { + values.entry(fence).or_insert(0); +} + +fn note_safe_value(values: &mut BTreeMap<usize, u64>, fence: usize, value: u64) { + values.entry(fence).and_modify(|safe| *safe = (*safe).max(value)).or_insert(value); +} + +fn writer_at(entry: &Entry, subresource: usize) -> Option<GpuWriter> { + match entry.gpu_writers.as_slice() { + [] => None, [writer] => *writer, writers => writers.get(subresource).copied().flatten(), + } +} + +fn download_writes(res: usize, entry: &Entry, queue: WriterQueueId) -> Vec<DownloadWrite> { + let n = subresource_count(&entry.tex); + let scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + (0..n).filter_map(|subresource| { + let writer = writer_at(entry, subresource)?; + (writer.queue == queue && !scheduled.contains(&(res, entry.generation, writer.queue.generation, subresource as u32, writer.epoch))) + .then(|| DownloadWrite { subresource: subresource as u32, state: if entry.states.len() == n { entry.states[subresource] } else { entry.states[0] }, writer }) + }).collect() +} + +struct DownloadSnapshot { res: usize, generation: u64, target: usize, format: u32, tex: Arc<xg::Texture>, device: ID3D12Device, source: ID3D12Resource, writes: Vec<DownloadWrite>, plan: Option<TextureDownloadPlan> } + +pub(super) struct PreparedDownloads { id: WriterQueueId, snapshots: Vec<DownloadSnapshot> } + +pub(super) enum SubmitDownloadsError { Stale, Failed(String) } + +fn download_current(entry: &Entry, generation: u64, target: usize, writes: &[DownloadWrite]) -> bool { + entry.generation == generation && entry.src == target && writes.iter().all(|w| writer_at(entry, w.subresource as usize) == Some(w.writer)) +} + +/// Build readback lists outside the queue turn. The state is validated again at insertion. +/// Writes owned by another queue are left for a signal on that exact queue. +pub(super) unsafe fn prepare_downloads(queue: *mut c_void) -> PreparedDownloads { + let id = super::list_x::queue_identity(queue as usize).unwrap_or(WriterQueueId { raw: queue as usize, generation: 0 }); + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return PreparedDownloads { id, snapshots: Vec::new() } }; + let queue_type = q.GetDesc().Type; + if !download_queue_type_supported(queue_type) { return PreparedDownloads { id, snapshots: Vec::new() } } + let candidates: Vec<DownloadSnapshot> = { + let table = TEXTURES.lock().unwrap(); + table.by_res.iter().filter_map(|(&res, entry)| { + let writes = download_writes(res, entry, id); + if writes.is_empty() { return None } + let source = ID3D12Resource::from_raw_borrowed(&(res as *mut c_void))?.clone(); + let device = ID3D12Device::from_raw_borrowed(&(entry.device as *mut c_void))?.clone(); + Some(DownloadSnapshot { res, generation: entry.generation, target: entry.src, format: source.GetDesc().Format.0 as u32, + tex: Arc::clone(&entry.tex), device, source, writes, plan: None }) + }).collect() + }; + let mut snapshots = Vec::new(); + for mut snapshot in candidates { + let selected: Vec<_> = snapshot.writes.iter().map(|w| (w.subresource, w.state)).collect(); + let Ok(plan) = prepare_texture_download(&snapshot.device, &snapshot.source, queue_type, Arc::clone(&snapshot.tex), snapshot.format, &selected) else { continue }; + snapshot.plan = Some(plan); + snapshots.push(snapshot); + } + PreparedDownloads { id, snapshots } +} + +/// Validate and insert prepared lists while the caller owns `queue`'s turn. A stale snapshot +/// submits nothing, so the caller can rebuild outside the turn and retry. +pub(super) unsafe fn submit_prepared_downloads(queue: *mut c_void, prepared: PreparedDownloads) -> Result<Vec<ReadyDownload>, SubmitDownloadsError> { + if prepared.snapshots.is_empty() { return Ok(Vec::new()) } + if super::list_x::queue_identity(queue as usize) != Some(prepared.id) { return Err(SubmitDownloadsError::Stale) } + let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&queue) else { return Ok(Vec::new()) }; + let table = TEXTURES.lock().unwrap(); + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + let valid = prepared.snapshots.iter().all(|snapshot| { + table.by_res.get(&snapshot.res).is_some_and(|entry| { + entry.generation == snapshot.generation + && entry.src == snapshot.target + && snapshot.writes.iter().all(|w| { + !scheduled.contains(&(snapshot.res, snapshot.generation, w.writer.queue.generation, w.subresource, w.writer.epoch)) + && + writer_at(entry, w.subresource as usize) == Some(w.writer) + && (if entry.states.len() == subresource_count(&entry.tex) { + entry.states[w.subresource as usize] + } else { + entry.states[0] + }) == w.state + }) + }) + }); + if !valid { return Err(SubmitDownloadsError::Stale) } + let keys: Vec<_> = prepared.snapshots.iter().flat_map(|snapshot| snapshot.writes.iter().map(|write| { + (snapshot.res, snapshot.generation, write.writer.queue.generation, write.subresource, write.writer.epoch) + })).collect(); + for &key in &keys { scheduled.insert(key); } + drop(scheduled); + drop(table); + let mut ready = Vec::new(); + for snapshot in prepared.snapshots { + let submitted = match snapshot.plan.unwrap().submit(q) { + Ok(submitted) => submitted, + Err(error) => { rollback_reservations(&keys); return Err(SubmitDownloadsError::Failed(error)) } + }; + if let Some(error) = submitted.signal_error { rollback_reservations(&keys); return Err(SubmitDownloadsError::Failed(format!("texture download completion signal failed: {error}"))) } + ready.push(ReadyDownload { res: snapshot.res, generation: snapshot.generation, target: snapshot.target, format: snapshot.format, writes: snapshot.writes, ticket: submitted.ticket }); + } + Ok(ready) +} + +fn rollback_reservations(keys: &[(usize, u64, u64, u32, u64)]) { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for key in keys { scheduled.remove(key); } +} + +/// Tie already-submitted readbacks to the title fence queued immediately after them. +pub(super) unsafe fn tie_downloads(fence: *mut c_void, value: u64, downloads: Vec<ReadyDownload>) { + if downloads.is_empty() { return } + let Some(fence) = ID3D12Fence::from_raw_borrowed(&fence).cloned() else { return }; + let key = fence.as_raw() as usize; + { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + if state.begin_tie(key) { + ensure_safe_baseline(&mut SAFE_FENCE_VALUES.lock().unwrap(), key); + } + DOWNLOADS_PENDING.store(true, Ordering::Release); + } + let event = super::fence_x::wake_event(); + for download in &downloads { download.ticket.arm(event); } + { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for download in &downloads { for write in &download.writes { + scheduled.insert((download.res, download.generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); + } } + } + { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + state.batches.push(FenceDownloads { fence: fence.clone(), value, downloads: downloads.into_iter().map(Some).collect() }); + state.finish_tie(key); + DOWNLOADS_PENDING.store(true, Ordering::Release); + } + let _ = fence.SetEventOnCompletion(value, event); +} + +fn publish_download(download: &ReadyDownload) -> Result<bool, String> { + let Some(readback) = (unsafe { download.ticket.readback_bytes()? }) else { return Ok(false) }; + let size = usize::try_from(download.ticket.layout().size()).map_err(|_| "texture download destination is too large")?; + let current = unsafe { title_bytes(download.target, size) }; + let mut console = Vec::new(); + console.try_reserve_exact(size).map_err(|_| "cannot allocate texture download destination")?; + console.extend_from_slice(¤t); + for (write, footprint) in download.writes.iter().zip(download.ticket.footprints()) { + reverse_layout_subresource(download.ticket.layout(), download.format, write.subresource, footprint.footprint, &readback, &mut console) + .map_err(|e| format!("cannot reverse texture download layout: {e:?}"))?; + } + let mut table = TEXTURES.lock().unwrap(); + let Some(entry) = table.by_res.get_mut(&download.res) else { return Ok(true) }; + if !download_current(entry, download.generation, download.target, &download.writes) { return Ok(true) } + if !unsafe { write_changed_pages(download.target, ¤t, &console) } { return Ok(false) } + let n = subresource_count(&entry.tex); + if entry.gpu_writers.len() != n { + entry.gpu_writers = vec![entry.gpu_writers.first().copied().flatten(); n]; + } + for write in &download.writes { + let slot = &mut entry.gpu_writers[write.subresource as usize]; + if *slot == Some(write.writer) { *slot = None; } + } + if entry.gpu_writers.iter().all(Option::is_none) { + entry.gpu_writers.clear(); + entry.gpu_written = false; + } + Ok(true) +} + +/// Write changed 4 KiB pages without faulting if the title concurrently unmaps one. Every +/// changed page must be committed and writable; otherwise its fence remains hidden and retries. +unsafe fn write_changed_pages(at: usize, old: &[u8], new: &[u8]) -> bool { + use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; + use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_GUARD}; + use windows_sys::Win32::System::Threading::GetCurrentProcess; + if old.len() != new.len() { return false } + let mut offset = 0; + while offset < new.len() { + let end = (((at + offset) & !4095) + 4096).saturating_sub(at).min(new.len()); + if old[offset..end] == new[offset..end] { offset = end; continue } + let address = at + offset; + let mut info: MEMORY_BASIC_INFORMATION = std::mem::zeroed(); + if VirtualQuery(address as *const c_void, &mut info, std::mem::size_of_val(&info)) == 0 + || info.State != MEM_COMMIT + || info.Protect & 0xCC == 0 + || info.Protect & PAGE_GUARD != 0 + || (info.BaseAddress as usize).saturating_add(info.RegionSize) < at + end + { + return false; + } + let mut written = 0; + if WriteProcessMemory(GetCurrentProcess(), address as *const c_void, new[offset..end].as_ptr() as *const c_void, end - offset, &mut written) == 0 + || written != end - offset { + return false; + } + offset = end; + } + true +} + +fn unschedule(download: &ReadyDownload) { + unschedule_writes(download.res, download.generation, &download.writes); +} + +fn unschedule_writes(res: usize, generation: u64, writes: &[DownloadWrite]) { + let mut scheduled = SCHEDULED_DOWNLOADS.lock().unwrap(); + for write in writes { scheduled.remove(&(res, generation, write.writer.queue.generation, write.subresource, write.writer.epoch)); } +} + +fn batch_ready(blocked: &mut bool, target: u64, completed: u64) -> bool { + if *blocked || target > completed { *blocked = true; false } else { true } +} + +fn take_matching<T>(values: &mut Vec<T>, mut matches: impl FnMut(&T) -> bool) -> Vec<T> { + let mut taken = Vec::new(); + let mut kept = Vec::with_capacity(values.len()); + for value in values.drain(..) { + if matches(&value) { taken.push(value) } else { kept.push(value) } + } + *values = kept; + taken +} + +/// Put detached older work before work tied to the same fence while it was being processed. +fn restore_before_matching<T>(values: &mut Vec<T>, mut older: Vec<T>, matches: impl FnMut(&T) -> bool) { + older.extend(take_matching(values, matches)); + values.extend(older); +} + +fn matching_through<T>(values: &[T], completed: u64, mut target: impl FnMut(&T) -> Option<u64>) -> bool { + values.iter().any(|value| target(value).is_some_and(|target| target <= completed)) +} + +/// Apply every completed download through `value`. False withholds the title's mirrored fence +/// value until a transiently unavailable readback or destination can be retried. +pub(super) fn complete_fence_downloads(fence: usize, value: u64) -> bool { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return true } + let mut batches = { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + if !state.begin_processing(fence) { + return false; + } + let batches = take_matching(&mut state.batches, |batch| batch.fence.as_raw() as usize == fence); + if batches.is_empty() { + state.processing.remove(&fence); + note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value); + return true; + } + batches + }; + let mut ok = true; + let mut blocked = false; + for batch in &mut batches { + if !batch_ready(&mut blocked, batch.value, value) { ok &= batch.value > value; continue } + for download in &mut batch.downloads { + let Some(ready) = download.as_ref() else { continue }; + match publish_download(ready) { + Ok(true) => { + unschedule(ready); + *download = None; + } + Ok(false) => { + ok = false; + blocked = true; + } + Err(error) => { + crate::xlog_warn!("D3D12.X: {error}; holding title fence {fence:#x} at {value:#x}"); + ok = false; + blocked = true; + } + } + } + blocked |= batch.downloads.iter().any(Option::is_some); + } + batches.retain(|batch| batch.downloads.iter().any(Option::is_some)); + { + let mut state = FENCE_DOWNLOADS.lock().unwrap(); + // A tie which arrived while this fence was detached was not in `batches`. If the caller's + // completed value already covers it, this pass cannot expose that value until another pass + // publishes the arrival. Check while holding the same lock which accepts new ties. + ok &= !matching_through(&state.batches, value, |batch| { + (batch.fence.as_raw() as usize == fence).then_some(batch.value) + }); + ok &= !state.tie_in_progress(fence); + restore_before_matching(&mut state.batches, batches, |batch| batch.fence.as_raw() as usize == fence); + state.processing.remove(&fence); + if ok { + note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, value); + } + DOWNLOADS_PENDING.store(state.any_pending(), Ordering::Release); + } + ok +} + +pub(super) fn safe_fence_value(fence: usize, native: u64) -> u64 { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { + note_safe_value(&mut SAFE_FENCE_VALUES.lock().unwrap(), fence, native); + return native; + } + if native != u64::MAX && complete_fence_downloads(fence, native) { + native + } else { + SAFE_FENCE_VALUES.lock().unwrap().get(&fence).copied().unwrap_or(0) + } +} + +/// Poll pending title fences even when a title never requested a completed-value mirror. +pub(super) fn poll_fence_downloads() { + if !DOWNLOADS_PENDING.load(Ordering::Acquire) { return } + let pending: Vec<_> = { + let state = FENCE_DOWNLOADS.lock().unwrap(); + state.batches.iter().map(|batch| batch.fence.clone()).collect() + }; + for fence in pending { + let value = unsafe { super::real::native_fence_completed(&fence) }; + if value != u64::MAX { + let _ = complete_fence_downloads(fence.as_raw() as usize, value); + } + } +} + +fn download_queue_type_supported(ty: D3D12_COMMAND_LIST_TYPE) -> bool { + matches!(ty, D3D12_COMMAND_LIST_TYPE_DIRECT | D3D12_COMMAND_LIST_TYPE_COMPUTE) +} + +/// Build but do not submit a download. Preparation performs no global lookup or queue operation. +#[allow(dead_code)] +pub(super) unsafe fn prepare_texture_download( + dev: &ID3D12Device, + source: &ID3D12Resource, + queue_type: D3D12_COMMAND_LIST_TYPE, + tex: Arc<xg::Texture>, + format: u32, + selected: &[(u32, D3D12_RESOURCE_STATES)], +) -> Result<TextureDownloadPlan, String> { + if !download_queue_type_supported(queue_type) { + return Err("texture download requires a direct or compute queue".into()); + } + let mut source_device: Option<ID3D12Device> = None; + source.GetDevice(&mut source_device).map_err(|e| e.to_string())?; + if source_device.as_ref().is_none_or(|d| d.as_raw() != dev.as_raw()) { + return Err("texture download source belongs to another device".into()); + } + let desc = source.GetDesc(); + let mut queried = Vec::new(); + queried.try_reserve_exact(selected.len()).map_err(|_| "cannot allocate driver footprints")?; + let mut base = 0u64; + for &(subresource, _) in selected { + let mut fp = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let (mut rows, mut row_bytes, mut ignored_total) = (0u32, 0u64, 0u64); + dev.GetCopyableFootprints(&desc, subresource, 1, base, Some(&mut fp), Some(&mut rows), Some(&mut row_bytes), Some(&mut ignored_total)); + queried.push((fp, rows, row_bytes)); + let pitch = fp.Footprint.RowPitch as u64; + let slice_pitch = pitch.checked_mul(rows as u64).ok_or("driver footprint overflow")?; + base = fp.Offset + .checked_add(slice_pitch.checked_mul(fp.Footprint.Depth.saturating_sub(1) as u64).ok_or("driver footprint overflow")?) + .and_then(|n| n.checked_add(pitch.checked_mul(rows.saturating_sub(1) as u64)?)) + .and_then(|n| n.checked_add(row_bytes)) + .ok_or("driver footprint overflow")?; + } + let (footprints, bytes) = validate_download_layout(&tex, &desc, format, selected, &queried)?; + let allocator = dev.CreateCommandAllocator(queue_type).map_err(|e| e.to_string())?; + let graphics: ID3D12GraphicsCommandList = dev.CreateCommandList(0, queue_type, &allocator, None).map_err(|e| e.to_string())?; + let mut readback = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, + D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, + Width: bytes as u64, + Height: 1, + DepthOrArraySize: 1, + MipLevels: 1, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, + ..Default::default() + }, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut readback, + ).map_err(|e| e.to_string())?; + let readback = readback.ok_or("no readback resource")?; + let barrier = |subresource, before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { + pResource: std::mem::transmute_copy(source), Subresource: subresource, StateBefore: before, StateAfter: after, + }) }, + }; + for sub in &footprints { + if sub.state != D3D12_RESOURCE_STATE_COPY_SOURCE { + graphics.ResourceBarrier(&[barrier(sub.subresource, sub.state, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + } + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: sub.footprint.offset as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32), Width: sub.footprint.width, Height: sub.footprint.height, Depth: sub.footprint.depth, RowPitch: sub.footprint.row_pitch as u32 }, + } } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(source), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: sub.subresource } }; + graphics.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + if sub.state != D3D12_RESOURCE_STATE_COPY_SOURCE { + graphics.ResourceBarrier(&[barrier(sub.subresource, D3D12_RESOURCE_STATE_COPY_SOURCE, sub.state)]); + } + } + graphics.Close().map_err(|e| e.to_string())?; + let list: ID3D12CommandList = graphics.cast().map_err(|e| e.to_string())?; + let fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).map_err(|e| e.to_string())?; + Ok(TextureDownloadPlan { device: dev.clone(), queue_type, tex, source: source.clone(), readback, allocator, list, fence, footprints, bytes }) +} + + +#[cfg(test)] +mod tests { + use super::*; + + /// A texture is left out only when its memory hashes as at its own last upload, and a + /// texture that was forgotten (released, or its address registered again) is uploaded again. + #[test] + fn a_texture_with_unchanged_memory_is_left_out_until_it_is_forgotten() { + let (a, b) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); + let mut mem = vec![0u8; 3 << 20]; + mem[5] = 1; + let h = content_hash(&mem); + assert!(!same_as_last_upload(a, h), "the first upload is not left out"); + assert!(same_as_last_upload(a, h), "the same bytes again: left out"); + assert!(!same_as_last_upload(b, h), "another texture over the same bytes has its own first upload"); + // one byte anywhere, also in the tail that is not a whole 32-byte step + for at in [0usize, 31, 32, (3 << 20) - 1] { + let mut m = mem.clone(); + m[at] ^= 0x80; + assert_ne!(content_hash(&m), h, "byte {at} changed"); + } + mem[(3 << 20) - 1] = 9; + let h2 = content_hash(&mem); + assert!(!same_as_last_upload(a, h2), "changed memory is uploaded"); + assert!(same_as_last_upload(a, h2)); + // the length is part of the content: a prefix of zeros is not the whole + assert_ne!(content_hash(&[0u8; 64]), content_hash(&[0u8; 96])); + forget(a); + assert!(!same_as_last_upload(a, h2), "forgotten: its next upload is a first one"); + forget(a); + forget(b); + } + + unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec<u8> { + own_work(|| { + let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); + let mut total = 0; + dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); + let mut readback = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, + D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, + ).unwrap(); + let readback: ID3D12Resource = readback.unwrap(); + let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); + let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); + let barrier = |before, after| D3D12_RESOURCE_BARRIER { + Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, + Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, + ..Default::default() + }; + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; + let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; + list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); + list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); + list.Close().unwrap(); + queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); + let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Signal(&fence, 1).unwrap(); + crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); + let mut data = std::ptr::null_mut(); + readback.Map(0, None, Some(&mut data)).unwrap(); + let mut out = Vec::with_capacity(64 * 64); + for y in 0..64 { + out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); + } + readback.Unmap(0, None); + out + }) + } + + #[test] + fn gpu_uploads_on_the_title_queue_run_before_its_later_work_and_are_released() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let compute: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_COMPUTE, ..Default::default() }).unwrap(); + assert!(title_queue_for(dev, Some(&queue)).is_some()); + assert!(title_queue_for(dev, Some(&compute)).is_none()); + assert!(title_queue_for(dev, None).is_none()); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let upload = |value: u8| { + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![value; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); + }; + for value in [0x21, 0xC4] { + upload(value); + assert_eq!(read_r8(dev, &queue, &texture), vec![value; 64 * 64], "the title queue's next work sees the upload"); + } + upload(0x5E); + { + let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); + let mut slot = state.lock().unwrap(); + let q = slot.as_mut().unwrap(); + assert_eq!(q.value, 3); + let retired = reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0, "over the cap the oldest uploads are waited for and released"); + assert!(q.fence.GetCompletedValue() >= 3); + drop(slot); + drop(retired); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x5E; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + /// An upload on the title's queue waits there for the texture page mappings made before it, + /// as one on XCL's upload queue does: without the wait its copy can run into tiles whose + /// mapping has not run yet (a copy-engine write page fault on NVIDIA). + #[test] + fn gpu_a_title_queue_upload_waits_for_the_page_mappings_before_it() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let Some(mapped) = super::super::vram::note_mapping_for_test(dev) else { + crate::gpu::recomp::runner::skip_test("no texture pages on this device"); + return; + }; + let key = queue.as_raw() as usize; + assert!(super::super::vram::waited_for_test(raw_device as usize, key) < mapped); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x3C; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); + assert_eq!( + super::super::vram::waited_for_test(raw_device as usize, key), + mapped, + "the title queue's upload must wait for the page mappings made before it" + ); + assert_eq!(read_r8(dev, &queue, &texture), vec![0x3C; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + #[test] + fn gpu_an_upload_still_running_is_kept_when_its_wait_times_out() { + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); + let _guard = TEST_LOCK.lock().unwrap(); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + unsafe { + let raw_device = super::super::real::device_raw(); + let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); + let queue: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let gate: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + queue.Wait(&gate, 1).unwrap(); + let mut texture = None; + dev.CreateCommittedResource( + &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }, D3D12_HEAP_FLAG_NONE, + &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 64, Height: 64, DepthOrArraySize: 1, MipLevels: 1, Format: DXGI_FORMAT_R8_UNORM, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, ..Default::default() }, + D3D12_RESOURCE_STATE_COMMON, None, &mut texture, + ).unwrap(); + let texture: ID3D12Resource = texture.unwrap(); + let key = queue.as_raw() as usize; + let subs = vec![Subresource { depth: 1, rows: 64, row_bytes: 64, data: vec![0x77; 64 * 64] }]; + own_work(|| submit_on_title_queue(dev, &queue, &[(texture.clone(), subs, vec![D3D12_RESOURCE_STATE_COMMON])], &[])).unwrap(); + { + let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); + let mut slot = state.lock().unwrap(); + let q = slot.as_mut().unwrap(); + let retired = reclaim(dev, q, 0, 50); + assert_eq!(q.in_flight.len(), 1, "a batch the GPU has not run stays in flight when its wait times out"); + assert!(q.bytes > 0); + drop(slot); + drop(retired); + } + gate.Signal(1).unwrap(); + { + let state = ON_QUEUE.lock().unwrap().get(&key).unwrap().clone(); + let mut slot = state.lock().unwrap(); + let q = slot.as_mut().unwrap(); + let retired = reclaim(dev, q, 0, 10_000); + assert!(q.in_flight.is_empty() && q.bytes == 0); + drop(slot); + drop(retired); + } + assert_eq!(read_r8(dev, &queue, &texture), vec![0x77; 64 * 64]); + ON_QUEUE.lock().unwrap().remove(&key); + } + } + + /// Real uploads, dirty-page detection and a source changing after registration: + /// bookkeeping alone cannot show that the bytes the GPU sees follow the mirror. + #[test] + fn gpu_mirror_upload_follows_cpu_writes_and_later_mapping_changes() { + use crate::hle::kernelx; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8_UNORM, DXGI_SAMPLE_DESC}; + use windows_sys::Win32::System::Memory as mem; + + let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + if super::super::backend() != super::super::Backend::Real { + crate::gpu::recomp::runner::skip_test("no GPU"); + return; + } + // Larger than all four UMA windows together. These public allocations + // must use the watched Windows fallback, reserving space rather than RAM. + const SIZE: usize = 24usize << 30; + const OFFSET: usize = 0x2_0000; + const PAGE: usize = 0x1_0000; + struct Reservation(usize); + impl Drop for Reservation { + fn drop(&mut self) { + unsafe { kernelx::VirtualFree(self.0 as *mut c_void, 0, mem::MEM_RELEASE); } + } + } + struct RegisteredTexture(usize); + impl Drop for RegisteredTexture { + fn drop(&mut self) { forget(self.0); } + } + struct PhysicalPage { id: usize, at: usize } + impl Drop for PhysicalPage { + fn drop(&mut self) { unsafe { if kernelx::physical_page_at(self.at) { kernelx::MapTitlePhysicalPages(self.at as *mut c_void, 1, 0, 4, std::ptr::null_mut()); @@ -1565,45 +3011,6 @@ mod tests { assert!(kernelx::in_graphics_reservation(at), "fallback must be write-watched"); reservation } - unsafe fn read_r8(dev: &ID3D12Device, queue: &ID3D12CommandQueue, texture: &ID3D12Resource) -> Vec<u8> { - own_work(|| { - let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); - let mut total = 0; - dev.GetCopyableFootprints(&texture.GetDesc(), 0, 1, 0, Some(&mut footprint), None, None, Some(&mut total)); - let mut readback = None; - dev.CreateCommittedResource( - &D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }, D3D12_HEAP_FLAG_NONE, - &D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: total, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }, - D3D12_RESOURCE_STATE_COPY_DEST, None, &mut readback, - ).unwrap(); - let readback: ID3D12Resource = readback.unwrap(); - let allocator: ID3D12CommandAllocator = dev.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap(); - let list: ID3D12GraphicsCommandList = dev.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap(); - let barrier = |before, after| D3D12_RESOURCE_BARRIER { - Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION, - Anonymous: D3D12_RESOURCE_BARRIER_0 { Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER { pResource: std::mem::transmute_copy(texture), Subresource: 0, StateBefore: before, StateAfter: after }) }, - ..Default::default() - }; - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - let dst = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(&readback), Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint } }; - let src = D3D12_TEXTURE_COPY_LOCATION { pResource: std::mem::transmute_copy(texture), Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: 0 } }; - list.CopyTextureRegion(&dst, 0, 0, 0, &src, None); - list.ResourceBarrier(&[barrier(D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]); - list.Close().unwrap(); - queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]); - let fence: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); - queue.Signal(&fence, 1).unwrap(); - crate::gpu::fence::wait(&fence, 1, dev, None, 5_000).unwrap(); - let mut data = std::ptr::null_mut(); - readback.Map(0, None, Some(&mut data)).unwrap(); - let mut out = Vec::with_capacity(64 * 64); - for y in 0..64 { - out.extend_from_slice(std::slice::from_raw_parts((data as *const u8).add(footprint.Offset as usize + y * footprint.Footprint.RowPitch as usize), 64)); - } - readback.Unmap(0, None); - out - }) - } unsafe { let raw_device = super::super::real::device_raw(); let dev = ID3D12Device::from_raw_borrowed(&raw_device).unwrap(); @@ -1683,7 +3090,7 @@ mod tests { d[0x24..0x28].copy_from_slice(&1u32.to_le_bytes()); d[0x2C..0x30].copy_from_slice(&0x105u32.to_le_bytes()); let tex = Arc::new(xg::Texture::new(&d).unwrap()); - let mut e = Entry { device: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, placed: false, unmapped: false, seq: 0 }; + let mut e = Entry { device: 0, committed_bytes: 0, va: at, src: mirror_source(at), in_gpu_view: true, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }; assert_eq!(e.src, cpu + 0x2_0000); assert!(!recheck_source(&mut e), "nothing changed yet"); assert_eq!(kernelx::MapTitlePhysicalPages(at as *mut c_void, 1, 0, 4, pages.as_mut_ptr()) as usize, at); @@ -1741,6 +3148,44 @@ mod tests { const ALL: u32 = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; static TEST_LOCK: Mutex<()> = Mutex::new(()); + #[test] + fn gpu_owned_metadata_accepts_exact_colour_layouts_only() { + let desc = console_desc(3, 64, 64, 2, 3, 28, 0x105); + let with_flags = |mut d: [u8; 0x38], flags: u32| { + d[0x30..0x34].copy_from_slice(&flags.to_le_bytes()); + d + }; + let pc = |d: &[u8; 0x38]| unsafe { + std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(d).as_ptr() as *const D3D12_RESOURCE_DESC) + }; + + let uav = with_flags(desc, 4); + let tex = gpu_owned_layout(&uav, &pc(&uav)).expect("single-plane UAV layout"); + assert_eq!(subresource_count(&tex), 6); + + let rt = with_flags(console_desc(3, 128, 128, 1, 1, 28, 0x105), 1); + let tex = gpu_owned_layout(&rt, &pc(&rt)).expect("render target with non-texel CMASK metadata"); + assert_eq!(tex.planes.len(), 2); + assert_eq!(subresource_count(&tex), 1); + + let depth = with_flags(desc, 2); + assert!(gpu_owned_layout(&depth, &pc(&depth)).is_err()); + let msaa = { + let mut d = with_flags(desc, 1); + d[0x24..0x28].copy_from_slice(&4u32.to_le_bytes()); + d + }; + assert!(gpu_owned_layout(&msaa, &pc(&msaa)).is_err()); + let promoted = with_flags(console_desc(3, 64, 64, 1, 1, 67, 0x105), 1); + assert_ne!(u32::from_le_bytes(promoted[0x20..0x24].try_into().unwrap()), pc(&promoted).Format.0 as u32); + assert!(gpu_owned_layout(&promoted, &pc(&promoted)).is_err()); + let planar = with_flags(console_desc(3, 64, 64, 1, 1, 45, 0x105), 1); + assert!(gpu_owned_layout(&planar, &pc(&planar)).is_err()); + let mut wrong_shape = pc(&uav); + wrong_shape.MipLevels -= 1; + assert!(gpu_owned_layout(&uav, &wrong_shape).is_err()); + } + /// One state while every subresource has it, one each while they differ. #[test] fn transitions_per_subresource_and_back_to_one_state() { @@ -1762,6 +3207,159 @@ mod tests { assert_eq!(one, vec![D3D12_RESOURCE_STATE_COPY_SOURCE]); } + #[test] + fn submitted_gpu_writes_keep_generation_queue_epoch_and_subresource() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 2, 3, 28, 0x105)).unwrap()); + let res = 0x7E57_1000_1000usize; + let entry = |tex: &Arc<xg::Texture>| Entry { + device: 0, + committed_bytes: 0, + va: 0x7E57_1000_0000, + src: 0x7E57_1000_0000, + in_gpu_view: false, + tex: Arc::clone(tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: false, + unmapped: false, + generation: 0, + }; + let generation = { + let mut t = TEXTURES.lock().unwrap(); + t.insert(res, entry(&tex)); + t.by_res[&res].generation + }; + let first = GpuWrite { res, generation, subresource: 2 }; + let q1 = WriterQueueId { raw: 0x1000, generation: 7 }; + publish_gpu_writes(q1, &[first]); + let first_epoch = { + let t = TEXTURES.lock().unwrap(); + let e = &t.by_res[&res]; + assert!(e.gpu_written); + assert_eq!(e.gpu_writers.len(), 6); + assert!(e.gpu_writers.iter().enumerate().all(|(i, w)| (i == 2) == w.is_some())); + let w = e.gpu_writers[2].unwrap(); + assert_eq!(w.queue, q1); + w.epoch + }; + + let q2 = WriterQueueId { raw: 0x2000, generation: 9 }; + publish_gpu_writes(q2, &[GpuWrite { res, generation, subresource: 4 }]); + { + let t = TEXTURES.lock().unwrap(); + let e = &t.by_res[&res]; + assert_eq!(e.gpu_writers[2].unwrap().queue, q1); + let last = e.gpu_writers[4].unwrap(); + assert_eq!(last.queue, q2); + assert!(last.epoch > first_epoch); + let q1_writes = download_writes(res, e, q1); + let q2_writes = download_writes(res, e, q2); + assert_eq!(q1_writes.iter().map(|w| w.subresource).collect::<Vec<_>>(), [2]); + assert_eq!(q2_writes.iter().map(|w| w.subresource).collect::<Vec<_>>(), [4]); + let key = (res, generation, q1.generation, 2, first_epoch); + SCHEDULED_DOWNLOADS.lock().unwrap().insert(key); + assert!(download_writes(res, e, q1).is_empty(), "an in-flight epoch is not downloaded twice"); + SCHEDULED_DOWNLOADS.lock().unwrap().remove(&key); + } + + let stale = download_writes(res, &TEXTURES.lock().unwrap().by_res[&res], q1); + let key = (res, generation, q1.generation, 2, first_epoch); + SCHEDULED_DOWNLOADS.lock().unwrap().insert(key); + publish_gpu_writes(q2, &[GpuWrite { res, generation, subresource: 2 }]); + assert!(!download_current(&TEXTURES.lock().unwrap().by_res[&res], generation, 0x7E57_1000_0000, &stale)); + unschedule_writes(res, generation, &stale); + assert!(!SCHEDULED_DOWNLOADS.lock().unwrap().contains(&key)); + + // Reusing the resource address creates another registration generation: a captured + // effect from the old object must not mark it. + { + let mut t = TEXTURES.lock().unwrap(); + t.remove(res); + t.insert(res, entry(&tex)); + assert_ne!(t.by_res[&res].generation, generation); + } + publish_gpu_writes(q1, &[first]); + assert!(!TEXTURES.lock().unwrap().by_res[&res].gpu_written); + TEXTURES.lock().unwrap().remove(res); + } + + #[test] + fn fence_download_batches_preserve_insertion_order() { + let mut blocked = false; + assert!(!batch_ready(&mut blocked, 20, 10)); + assert!(!batch_ready(&mut blocked, 5, 10), "later eligible batch passed an earlier one"); + blocked = true; + assert!(!batch_ready(&mut blocked, 10, 10), "later batch passed an incomplete one"); + } + + #[test] + fn detached_fence_batches_return_before_concurrent_arrivals() { + let mut batches = vec![(1, "old-a"), (2, "other-a"), (1, "old-b")]; + let mut detached = take_matching(&mut batches, |batch| batch.0 == 1); + assert_eq!(detached, [(1, "old-a"), (1, "old-b")]); + assert_eq!(batches, [(2, "other-a")]); + + // The first old batch completed while detached; two newer batches were tied meanwhile. + detached.remove(0); + batches.extend([(1, "new-a"), (2, "other-b"), (1, "new-b")]); + restore_before_matching(&mut batches, detached, |batch| batch.0 == 1); + assert_eq!( + batches.iter().filter(|batch| batch.0 == 1).map(|batch| batch.1).collect::<Vec<_>>(), + ["old-b", "new-a", "new-b"], + "an unresolved older download must keep later fence work hidden", + ); + assert_eq!( + batches.iter().filter(|batch| batch.0 == 2).map(|batch| batch.1).collect::<Vec<_>>(), + ["other-a", "other-b"], + "processing one fence must preserve another fence's order", + ); + } + + #[test] + fn concurrent_arrival_through_completed_value_withholds_visibility() { + let arrivals = [(2, 4), (1, 11), (2, 7)]; + let for_fence_one = |batch: &(usize, u64)| (batch.0 == 1).then_some(batch.1); + assert!(!matching_through(&arrivals, 10, for_fence_one), "a future arrival does not hide value 10"); + + let arrivals = [(2, 4), (1, 11), (1, 10)]; + assert!( + matching_through(&arrivals, 10, for_fence_one), + "a concurrent arrival covered by value 10 must be published before value 10 is visible", + ); + } + + #[test] + fn in_progress_tie_withholds_fence_processing() { + let mut state = FenceDownloadState::default(); + let mut safe = BTreeMap::from([(7, 99)]); + if state.begin_tie(7) { ensure_safe_baseline(&mut safe, 7); } + assert_eq!(safe[&7], 99, "first pending work preserves the last exposed completion"); + if state.begin_tie(7) { note_safe_value(&mut safe, 7, 123); } + assert_eq!(safe[&7], 99, "another installer must not advance the safe baseline"); + assert!(state.any_pending()); + assert!(!state.begin_processing(7), "completion must not pass a partially installed tie"); + state.finish_tie(7); + assert!(!state.begin_processing(7), "every installer must finish before completion starts"); + state.finish_tie(7); + assert!(state.begin_processing(7)); + + assert!(FenceDownloadState::default().begin_tie(8)); + ensure_safe_baseline(&mut safe, 8); + assert_eq!(safe[&8], 0, "a fence never exposed before starts from the conservative baseline"); + } + + #[test] + fn download_reservation_rollback_clears_every_key() { + let keys = [(0xBAD0, 1, 2, 3, 4), (0xBAD1, 5, 6, 7, 8)]; + SCHEDULED_DOWNLOADS.lock().unwrap().extend(keys); + rollback_reservations(&keys); + assert!(keys.iter().all(|key| !SCHEDULED_DOWNLOADS.lock().unwrap().contains(key))); + } + /// A texture kept in step: the title's transitions count once their list is submitted, in /// submission order, each time it is; a Reset forgets them; other resources are not noted. #[test] @@ -1780,37 +3378,31 @@ mod tests { let tex = Arc::new(xg::Texture::new(&d).unwrap()); assert_eq!(subresource_count(&tex), 6); // fake resource / list keys, never dereferenced: GPU-written, so no refresh uploads it - let (res, other, l1, l2) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize, 0x7E57_0000_3000usize, 0x7E57_0000_4000usize); - TEXTURES.lock().unwrap().insert(res, Entry { device: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, placed: false, unmapped: false, seq: 0 }); + let (res, other) = (0x7E57_0000_1000usize, 0x7E57_0000_2000usize); + TEXTURES.lock().unwrap().insert(res, Entry { device: 0, committed_bytes: 0, va: 0x7E57_0000_0000, src: 0x7E57_0000_0000, in_gpu_view: false, tex, states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, gpu_writers: Vec::new(), cpu_backed: true, placed: false, unmapped: false, generation: 0 }); TEXTURES_LEN.fetch_add(1, Ordering::Relaxed); let states = || TEXTURES.lock().unwrap().by_res.get(&res).unwrap().states.clone(); - let (p1, p2) = (l1 as *mut c_void, l2 as *mut c_void); - - note_transitions(l1, &[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); - assert_eq!(LIST_NOTES.lock().unwrap().get(&l1).map(|v| v.len()), Some(2), "only the texture kept in step is noted"); + let e1 = capture_transitions(&[(res, ALL, SRV), (other, ALL, D3D12_RESOURCE_STATE_RENDER_TARGET), (res, 4, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + assert_eq!(e1.len(), 2, "only the texture kept in step is captured"); assert_eq!(states(), vec![D3D12_RESOURCE_STATE_COMMON], "recorded, not run yet"); - note_transitions(l2, &[(res, 4, SRV), (res, 0, D3D12_RESOURCE_STATE_COPY_DEST)]); - submitted(&[p1]); + let e2 = capture_transitions(&[(res, 4, SRV), (res, 0, D3D12_RESOURCE_STATE_COPY_DEST)]); + publish_submission_effects(None, &[], &e1); let mut want = vec![SRV; 6]; want[4] = D3D12_RESOURCE_STATE_COPY_SOURCE; assert_eq!(states(), want); - submitted(&[p2]); + publish_submission_effects(None, &[], &e2); want[4] = SRV; want[0] = D3D12_RESOURCE_STATE_COPY_DEST; assert_eq!(states(), want); // l1 runs again (a closed list may): its transitions again, after l2's - submitted(&[p2, p1]); + publish_submission_effects(None, &[], &e2); + publish_submission_effects(None, &[], &e1); assert_eq!(states(), { let mut w = vec![SRV; 6]; w[4] = D3D12_RESOURCE_STATE_COPY_SOURCE; w }); - list_reset(l1); - list_reset(l2); - submitted(&[p1, p2]); - assert_eq!(states()[4], D3D12_RESOURCE_STATE_COPY_SOURCE, "a reset list has nothing to apply"); forget(res); - assert!(LIST_NOTES.lock().unwrap().get(&l1).is_none()); } /// The title's bytes are used where they are when all of them are readable, and read with the @@ -1845,7 +3437,7 @@ mod tests { assert_eq!(watch_ranges(®ions, wanted), vec![(0x11000, 0xF000), (0x40000, 0x10000)]); // ranges a gap of under WATCH_GAP apart: one scan; further apart: two let wanted = vec![(0x1000_0000, 0x1000_1000), (0x1008_0000, 0x1008_1000), (0x1100_0000, 0x1100_1000), (0x1800_0000, 0x1800_1000)]; - assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x100_1000), (0x1800_0000, 0x1000)]); + assert_eq!(watch_ranges(®ions, wanted), vec![(0x1000_0000, 0x8_1000), (0x1100_0000, 0x1000), (0x1800_0000, 0x1000)]); // a merged range over two regions: a piece in each, whatever order the regions come in let regions = [(0x40000, 0x10000), (0x10000, 0x10000)]; assert_eq!(watch_ranges(®ions, vec![(0x18000, 0x48000)]), vec![(0x18000, 0x8000), (0x40000, 0x8000)]); @@ -1854,6 +3446,47 @@ mod tests { assert_eq!(watch_ranges(®ions, vec![(0x1000_0000, 0x1000_1000), (0x2008_0000, 0x2009_0000)]), vec![(0x2008_0000, 0x1_0000)]); } + #[test] + fn watch_ranges_merge_at_the_gap_limit_and_split_past_it() { + let base = 0x1000_0000usize; + let regions = [(base, 4 * WATCH_GAP)]; + let first = (base, base + 0x1000); + let at_limit = (first.1 + WATCH_GAP, first.1 + WATCH_GAP + 0x1000); + assert_eq!(watch_ranges(®ions, vec![at_limit, first]), vec![(base, 2 * 0x1000 + WATCH_GAP)]); + + let past_limit = (first.1 + WATCH_GAP + 1, first.1 + WATCH_GAP + 0x1001); + assert_eq!(watch_ranges(®ions, vec![past_limit, first]), vec![(base, 0x1000), (past_limit.0, 0x1000)]); + } + + #[test] + fn watch_ranges_are_sorted_disjoint_in_region_and_cover_every_wanted_part() { + let regions = [(0x4000_0000usize, 0x100_0000usize), (0x1000_0000, 0x200_0000), (0x8000_0000, 0x20_0000)]; + let wanted = vec![ + (0x0FFF_F000, 0x1000_2000), + (0x1008_0000, 0x1008_1000), + (0x11FF_F000, 0x1200_1000), + (0x4000_8000, 0x4000_A000), + (0x40FF_F000, 0x4100_1000), + (0x8008_0000, 0x8008_1000), + (0xA000_0000, 0xA000_1000), + ]; + let ranges = watch_ranges(®ions, wanted.clone()); + + assert!(ranges.windows(2).all(|w| w[0].0 + w[0].1 <= w[1].0), "ranges must be sorted and disjoint: {ranges:x?}"); + for &(base, size) in &ranges { + let end = base + size; + assert!(size > 0 && regions.iter().any(|&(rbase, rsize)| rbase <= base && end <= rbase + rsize), "range {base:#x}..{end:#x} is outside one allocation"); + } + for &(start, end) in &wanted { + for &(rbase, rsize) in ®ions { + let (lo, hi) = (start.max(rbase), end.min(rbase + rsize)); + if lo < hi { + assert!(ranges.iter().any(|&(base, size)| base <= lo && hi <= base + size), "wanted part {lo:#x}..{hi:#x} is not covered"); + } + } + } + } + /// The textures of a batch detiled on several threads come back as on one: complete and in /// order (2D with mips and slices, 3D, BC7, a tiny one; more textures than threads). #[test] @@ -1867,19 +3500,61 @@ mod tests { console_desc(3, 128, 32, 3, 2, 28, 0x105), console_desc(3, 64, 64, 1, 1, 28, 0x105), ]; - let textures: Vec<xg::Texture> = descs.iter().map(|d| xg::Texture::new(d).unwrap()).collect(); + let textures: Vec<Arc<xg::Texture>> = descs.iter().map(|d| Arc::new(xg::Texture::new(d).unwrap())).collect(); // each texture's console memory: distinct bytes per texture let mems: Vec<Vec<u8>> = textures.iter().enumerate().map(|(t, x)| (0..x.size() as usize).map(|i| (i * 7 + t * 61) as u8).collect()).collect(); - let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, x)).collect(); + let picked: Vec<(usize, &xg::Texture)> = mems.iter().zip(&textures).map(|(m, x)| (m.as_ptr() as usize, &**x)).collect(); unsafe { let one = subresources_on(&picked, 1); assert!(one.iter().all(|s| !s.is_empty()), "a texture gave no subresources"); for threads in [2, 3, 8] { assert!(subresources_on(&picked, threads) == one, "{threads} threads differ from one"); } + let pooled: Vec<_> = picked.iter().zip(&textures).map(|(&(va, _), tex)| (va, Arc::clone(tex))).collect(); + assert_eq!(pooled_subresources(&pooled, usize::MAX), Some(one), "persistent workers preserve order and content"); } } + #[test] + fn failed_preparation_requeues_only_the_exact_cpu_generation() { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 4, 4, 1, 1, 28, 0x105)).unwrap()); + let entry = |generation, gpu_written| Entry { + device: 0, + committed_bytes: 0, + va: 0x1000, + src: 0x1000, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written, + gpu_writers: Vec::new(), + cpu_backed: true, + placed: false, + unmapped: false, + generation, + }; + let mut table = Table::new(); + table.by_res.insert(1, entry(7, false)); + table.by_res.insert(2, entry(8, false)); + table.by_res.insert(3, entry(9, true)); + + assert_eq!(requeue_generations(&mut table, &[(1, 7), (2, 7), (3, 9), (4, 1)]), [1]); + assert!(table.by_res[&1].pending); + assert!(!table.by_res[&2].pending, "a replacement generation owns its own pending state"); + assert!(!table.by_res[&3].pending, "GPU-written content must not be overwritten by a retry"); + } + + #[test] + fn preparation_results_fail_closed_on_worker_loss() { + assert!(ordered_subresources(2, [(1, Some(Vec::new())), (0, Some(Vec::new()))]).is_some()); + assert!(ordered_subresources(2, [(0, Some(Vec::new()))]).is_none(), "a missing worker result must fail the batch"); + assert!( + ordered_subresources(2, [(0, Some(Vec::new())), (1, None)]).is_none(), + "a caught worker panic must fail the batch", + ); + } + #[test] fn small_cpu_filled_target_accepts_wide_glyph_atlas_and_rejects_large_or_depth() { assert!(is_small_cpu_filled_target(2048, 128, 1, 0x300005), "2048x128 R8 glyph atlas must sync"); @@ -1905,6 +3580,219 @@ mod tests { d } + #[test] + fn committed_sampled_bytes_follow_device_shadowing_and_release() { + const M: u64 = 1 << 20; + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let entry = |device, va, committed_bytes, placed| Entry { + device, + committed_bytes, + va, + src: va, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: false, + gpu_writers: Vec::new(), + cpu_backed: true, + placed, + unmapped: false, + generation: 0, + }; + let mut table = Table::new(); + table.insert(1, entry(7, 0x10_0000, 3 * M, false)); + table.insert(2, entry(7, 0x10_2000, 2 * M, false)); // shadows 1, which remains live + table.insert(3, entry(7, 0x20_0000, 8 * M, true)); // shared pages, not committed + table.insert(4, entry(8, 0x30_0000, 11 * M, false)); + assert_eq!(table.committed_bytes_for(7), (2, 5 * M)); + assert_eq!(table.committed_bytes_for(8), (1, 11 * M)); + assert!(table.remove(2).0); + assert_eq!(table.committed_bytes_for(7), (1, 3 * M), "the uncovered sampled texture is counted once"); + assert!(table.remove(1).0); + assert_eq!(table.committed_bytes_for(7), (0, 0), "logical release removes the partial diagnostic owner"); + } + + fn readback_for(tex: &xg::Texture, format: u32, subresource: u32) -> (ReadbackFootprint, Vec<u8>, Vec<u8>) { + let s = tex.texels().unwrap(); + let mips = s.chain.levels.len(); + let mip = subresource as usize % mips; + let l = &s.chain.levels[mip]; + let (w, h) = ((s.width >> mip).max(1), (s.height >> mip).max(1)); + let depth = if s.depth > 0 { (s.depth >> mip).max(1) } else { 1 }; + let row_bytes = l.width * s.bpe as usize; + let row_pitch = row_bytes.next_multiple_of(256); + let slice_pitch = row_pitch * l.height; + let size = slice_pitch * (l.depth - 1) + row_pitch * (l.height - 1) + row_bytes; + let mut readback = vec![0xE7; 512 + size + 31]; + let mut linear = vec![0; row_bytes * l.height * l.depth]; + for z in 0..l.depth { + for y in 0..l.height { + for x in 0..row_bytes { + let v = (z * 71 + y * 17 + x * 3 + 5) as u8; + readback[512 + z * slice_pitch + y * row_pitch + x] = v; + linear[(z * l.height + y) * row_bytes + x] = v; + } + } + } + (ReadbackFootprint { offset: 512, size, row_pitch, width: w, height: h, depth, format }, readback, linear) + } + + fn driver_download_layout( + tex: &xg::Texture, + format: u32, + selected: &[(u32, D3D12_RESOURCE_STATES)], + ) -> Vec<(D3D12_PLACED_SUBRESOURCE_FOOTPRINT, u32, u64)> { + let s = tex.texels().unwrap(); + let mips = s.chain.levels.len(); + let mut end = 0usize; + selected + .iter() + .map(|&(sub, _)| { + let mip = if s.depth > 0 { sub as usize } else { sub as usize % mips }; + let l = &s.chain.levels[mip]; + let row_bytes = l.width * s.bpe as usize; + let pitch = row_bytes.next_multiple_of(256); + let offset = end.next_multiple_of(512); + end = offset + pitch * l.height * (l.depth - 1) + pitch * (l.height - 1) + row_bytes; + ( + D3D12_PLACED_SUBRESOURCE_FOOTPRINT { + Offset: offset as u64, + Footprint: D3D12_SUBRESOURCE_FOOTPRINT { + Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT(format as i32), + Width: (s.width >> mip).max(1), + Height: (s.height >> mip).max(1), + Depth: if s.depth > 0 { (s.depth >> mip).max(1) } else { 1 }, + RowPitch: pitch as u32, + }, + }, + l.height as u32, + row_bytes as u64, + ) + }) + .collect() + } + + #[test] + fn download_plans_use_writer_capable_queue_types() { + assert!(download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_DIRECT)); + assert!(download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_COMPUTE)); + assert!(!download_queue_type_supported(D3D12_COMMAND_LIST_TYPE_COPY)); + } + + #[test] + fn download_layout_preserves_explicit_states_and_bounds_array_and_volume_footprints() { + let array_desc = console_desc(3, 17, 9, 2, 3, 28, 0x105); + let array = xg::Texture::new(&array_desc).unwrap(); + let desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&array_desc).as_ptr() as *const _) }; + let selected = [(0, D3D12_RESOURCE_STATE_COMMON), (5, D3D12_RESOURCE_STATE_UNORDERED_ACCESS)]; + let driver = driver_download_layout(&array, 28, &selected); + let (layout, bytes) = validate_download_layout(&array, &desc, 28, &selected, &driver).unwrap(); + assert_eq!(layout.iter().map(|s| (s.subresource, s.state)).collect::<Vec<_>>(), selected); + assert_eq!(bytes, layout.last().unwrap().footprint.offset + layout.last().unwrap().footprint.size); + + let volume_desc = console_desc(4, 32, 16, 8, 4, 28, 0x105); + let volume = xg::Texture::new(&volume_desc).unwrap(); + let desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&volume_desc).as_ptr() as *const _) }; + let selected = [(0, D3D12_RESOURCE_STATE_UNORDERED_ACCESS), (2, D3D12_RESOURCE_STATE_COPY_SOURCE)]; + let driver = driver_download_layout(&volume, 28, &selected); + let (layout, _) = validate_download_layout(&volume, &desc, 28, &selected, &driver).unwrap(); + assert!(layout[1].footprint.offset >= layout[0].footprint.offset + layout[0].footprint.size); + assert_eq!((layout[1].footprint.width, layout[1].footprint.height, layout[1].footprint.depth), (8, 4, 2)); + } + + #[test] + fn download_layout_rejects_stale_or_driver_enlarged_selections() { + let bytes = console_desc(3, 16, 8, 2, 2, 28, 0x105); + let tex = xg::Texture::new(&bytes).unwrap(); + let desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&bytes).as_ptr() as *const _) }; + let selected = [(0, D3D12_RESOURCE_STATE_COMMON), (3, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + let exact = driver_download_layout(&tex, 28, &selected); + let mut bad = exact.clone(); + bad[1].0.Footprint.RowPitch += 256; + assert!(validate_download_layout(&tex, &desc, 28, &selected, &bad).is_err()); + let mut bad = exact.clone(); + bad[0].2 += 4; + assert!(validate_download_layout(&tex, &desc, 28, &selected, &bad).is_err()); + let duplicate = [(0, D3D12_RESOURCE_STATE_COMMON), (0, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + assert!(validate_download_layout(&tex, &desc, 28, &duplicate, &driver_download_layout(&tex, 28, &duplicate)).is_err()); + let invalid_state = [(0, D3D12_RESOURCE_STATES(-1))]; + assert!(validate_download_layout(&tex, &desc, 28, &invalid_state, &driver_download_layout(&tex, 28, &invalid_state)).is_err()); + assert!(validate_download_layout(&tex, &desc, 28, &selected[..1], &exact).is_err()); + let mut wrong_dimension = desc; + wrong_dimension.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE1D; + assert!(validate_download_layout(&tex, &wrong_dimension, 28, &selected, &exact).is_err()); + + let rgba = xg::Texture::new(&console_desc(3, 4, 4, 1, 1, 28, 0x105)).unwrap(); + let bc = console_desc(3, 4, 4, 1, 1, 77, 0x105); // both rows are 16 bytes; block side differs + let bc_desc: D3D12_RESOURCE_DESC = unsafe { std::ptr::read_unaligned(super::super::device_x::pc_resource_desc(&bc).as_ptr() as *const _) }; + let one = [(0, D3D12_RESOURCE_STATE_RENDER_TARGET)]; + assert!(validate_download_layout(&rgba, &bc_desc, 77, &one, &driver_download_layout(&rgba, 77, &one)).is_err()); + let mut rt = console_desc(3, 16, 8, 1, 1, 28, 0x105); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let rt = xg::Texture::new(&rt).unwrap(); + assert!(validate_download_layout(&rt, &desc, 28, &one, &driver_download_layout(&rt, 28, &one)).is_err()); + } + + #[test] + fn reverse_layout_tiles_an_edge_array_mip_without_touching_guards() { + let tex = xg::Texture::new(&console_desc(3, 17, 9, 2, 3, 28, 0x105)).unwrap(); + let sub = 5; // array slice 1, mip 2 + let (fp, readback, linear) = readback_for(&tex, 28, sub); + let size = tex.size() as usize; + let mut console = vec![0xCD; size + 37]; + reverse_layout_subresource(&tex, 28, sub, fp, &readback, &mut console).unwrap(); + + let s = tex.texels().unwrap(); + let slice = &console[s.chain.slice_bytes..2 * s.chain.slice_bytes]; + assert_eq!(s.chain.detile_level(slice, 2, 1), linear); + assert!(console[size..].iter().all(|&b| b == 0xCD), "destination guard changed"); + assert!(readback[..512].iter().all(|&b| b == 0xE7)); + assert!(readback[512 + fp.size..].iter().all(|&b| b == 0xE7)); + } + + #[test] + fn reverse_layout_handles_volume_depth_and_block_geometry() { + let volume = xg::Texture::new(&console_desc(4, 32, 16, 8, 4, 28, 0x105)).unwrap(); + let (fp, readback, linear) = readback_for(&volume, 28, 2); + assert_eq!((fp.width, fp.height, fp.depth), (8, 4, 2)); + let mut console = vec![0u8; volume.size() as usize]; + reverse_layout_subresource(&volume, 28, 2, fp, &readback, &mut console).unwrap(); + assert_eq!(volume.texels().unwrap().chain.detile_volume(&console, 2), linear); + + let blocks = xg::Texture::new(&console_desc(3, 10, 9, 1, 1, 71, 0x105)).unwrap(); + let (fp, readback, linear) = readback_for(&blocks, 71, 0); + assert_eq!((fp.width, fp.height, fp.depth), (10, 9, 1)); + assert_eq!(blocks.texels().unwrap().chain.levels[0].width, 3); + let mut console = vec![0u8; blocks.size() as usize]; + reverse_layout_subresource(&blocks, 71, 0, fp, &readback, &mut console).unwrap(); + assert_eq!(blocks.texels().unwrap().chain.detile_level(&console, 0, 0), linear); + } + + #[test] + fn reverse_layout_rejects_metadata_malformed_footprints_and_truncation() { + let tex = xg::Texture::new(&console_desc(3, 16, 8, 1, 1, 28, 0x105)).unwrap(); + let (fp, readback, _) = readback_for(&tex, 28, 0); + let mut console = vec![0u8; tex.size() as usize]; + let call = |f: ReadbackFootprint, src: &[u8], dst: &mut [u8]| reverse_layout_subresource(&tex, 28, 0, f, src, dst); + assert_eq!(call(ReadbackFootprint { format: 87, ..fp }, &readback, &mut console), Err(ReverseLayoutError::Format)); + assert_eq!(reverse_layout_subresource(&tex, 28, 1, fp, &readback, &mut console), Err(ReverseLayoutError::Subresource)); + assert_eq!(call(ReadbackFootprint { width: 15, ..fp }, &readback, &mut console), Err(ReverseLayoutError::Dimensions)); + assert_eq!(call(ReadbackFootprint { row_pitch: 255, ..fp }, &readback, &mut console), Err(ReverseLayoutError::RowPitch)); + assert_eq!(call(ReadbackFootprint { offset: 1, ..fp }, &readback, &mut console), Err(ReverseLayoutError::RowPitch)); + assert_eq!(call(ReadbackFootprint { size: fp.size - 1, ..fp }, &readback, &mut console), Err(ReverseLayoutError::Footprint)); + assert_eq!(call(fp, &readback[..512 + fp.size - 1], &mut console), Err(ReverseLayoutError::Footprint)); + assert_eq!(call(fp, &readback, &mut console[..tex.size() as usize - 1]), Err(ReverseLayoutError::Destination)); + let overflow = ReadbackFootprint { offset: usize::MAX & !511, ..fp }; + assert_eq!(call(overflow, &readback, &mut console), Err(ReverseLayoutError::Footprint)); + + let mut rt = console_desc(3, 16, 8, 1, 1, 28, 0x105); + rt[0x30..0x34].copy_from_slice(&1u32.to_le_bytes()); + let rt = xg::Texture::new(&rt).unwrap(); + let mut rt_console = vec![0u8; rt.size() as usize]; + assert_eq!(reverse_layout_subresource(&rt, 28, 0, fp, &readback, &mut rt_console), Err(ReverseLayoutError::UnsupportedLayout)); + } + /// Overlapping textures shadow earlier ones so dead placements never re-upload over shared /// `vram::Pages` tiles; different-range overlaps request unmapping while exact same-range /// overlaps stay mapped; releasing a newer placement reactivates uncovered older ones. @@ -1915,6 +3803,7 @@ mod tests { assert_eq!((tex_16k.size(), tex_64k.size()), (0x4000, 0x1_0000)); let entry = |va: usize, tex: &Arc<xg::Texture>, pending: bool, placed: bool| Entry { device: 0, + committed_bytes: 0, va, src: va, in_gpu_view: false, @@ -1922,9 +3811,11 @@ mod tests { states: vec![D3D12_RESOURCE_STATE_COMMON], pending, gpu_written: false, + gpu_writers: Vec::new(), + cpu_backed: true, placed, unmapped: false, - seq: 0, + generation: 0, }; let mut tbl = Table::new(); // Two adjacent placed 16 KiB textures + one placed 64 KiB texture after them. @@ -2313,6 +4204,41 @@ mod tests { assert_ne!(hm, he, "end-slice write must change fingerprint"); } + #[test] + fn gpu_owned_alias_generations_restore_the_previous_address_owner() { + let tex = Arc::new(xg::Texture::new(&console_desc(3, 64, 64, 1, 1, 28, 0x105)).unwrap()); + let entry = |cpu_backed: bool| Entry { + device: 0, + committed_bytes: 0, + va: 0x20_0000, + src: 0x20_0000, + in_gpu_view: false, + tex: Arc::clone(&tex), + states: vec![D3D12_RESOURCE_STATE_COMMON], + pending: false, + gpu_written: !cpu_backed, + gpu_writers: Vec::new(), + cpu_backed, + placed: !cpu_backed, + unmapped: false, + generation: 0, + }; + let mut t = Table::new(); + t.insert(1, entry(true)); + let cpu_generation = t.by_res[&1].generation; + t.insert(2, entry(false)); + let first_gpu_generation = t.by_res[&2].generation; + assert!(t.shadowed.contains_key(&1)); + t.insert(3, entry(false)); + assert!(t.shadowed.contains_key(&2)); + assert!(t.by_res[&3].generation > first_gpu_generation && first_gpu_generation > cpu_generation); + + t.remove(3); + assert!(t.by_res.contains_key(&2), "the previous exact-range GPU alias returns"); + t.remove(2); + assert!(t.by_res.get(&1).is_some_and(|e| e.cpu_backed && e.generation == cpu_generation)); + } + #[test] fn stream_recheck_schedule_catches_late_writes_and_resets_milestones() { let desc = console_desc(3, 256, 256, 1, 1, 28, 0x109); // 256 KiB RGBA8 @@ -2325,6 +4251,7 @@ mod tests { let e_stream = Entry { device: 0, + committed_bytes: 0, va, src: va, in_gpu_view: false, @@ -2332,12 +4259,15 @@ mod tests { states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: false, + gpu_writers: Vec::new(), + cpu_backed: true, placed: false, unmapped: false, - seq: 0, + generation: 0, }; let e_gpu = Entry { device: 0, + committed_bytes: 0, va: va + size, src: va, in_gpu_view: false, @@ -2345,9 +4275,11 @@ mod tests { states: vec![D3D12_RESOURCE_STATE_COMMON], pending: false, gpu_written: true, + gpu_writers: Vec::new(), + cpu_backed: true, placed: false, unmapped: false, - seq: 0, + generation: 0, }; { let mut t = TEXTURES.lock().unwrap(); @@ -2404,7 +4336,8 @@ mod tests { /// first upload, then pages for those levels only and their texels right, zeros where there /// are none. With memory under the largest level too, a texture placed there again (as a /// title does) takes that level's pages - the others are shared - and holds all of it. A - /// texture the GPU writes gets the pages of all its levels. + /// texture the GPU writes gets the pages of all its levels. A mapped level also clears when + /// the CPU's next upload sources zeros from shared staging. #[test] fn a_placed_texture_gets_the_pages_of_a_level_with_its_texels() { let _vram_guard = super::super::vram::VRAM_TEST_LOCK.lock().unwrap(); @@ -2527,9 +4460,27 @@ mod tests { } // what the GPU writes needs pages under all of the texture: the first one's mip 0 gets // the pages of its address, which hold what the second one's upload put there - note_gpu_write(small.as_raw() as usize); + let write = capture_gpu_write(small.as_raw() as usize, ALL).unwrap(); + publish_gpu_writes(WriterQueueId { raw: queue.as_raw() as usize, generation: 1 }, &[write]); assert_eq!(dev_pages() - p0, (all as usize) << 16, "the same pages"); assert!(read_sub(&small, 0) == want[0].data, "a GPU-written texture has pages under all its levels"); + std::ptr::write_bytes((at + top) as *mut u8, 0, size - top); + let cpu = std::slice::from_raw_parts_mut(at as *mut u8, chain.slice_bytes); + chain.tile_level(cpu, 10, 0, &vec![0u8; want[10].data.len()]); + // The synthetic allocation here is not write-watched. Queue the normal batch update. + { + let mut t = TEXTURES.lock().unwrap(); + let e = t.by_res.get_mut(&(full.as_raw() as usize)).unwrap(); + assert!(!e.pending, "the preceding refresh uploaded this texture"); + e.pending = true; + adjust_pending(1); + } + refresh(queue.as_raw()); + assert_eq!(dev_pages() - p0, (all as usize) << 16, "clearing a level keeps its backing"); + assert!(read_sub(&full, 0).iter().all(|&b| b == 0), "the previously streamed level was cleared"); + assert!(read_sub(&full, 10).iter().all(|&b| b == 0), "a small level sharing the zero span was cleared"); + assert!(read_sub(&full, 1) == want[1].data, "a nonzero mip kept its texels"); + assert!(read_sub(&full, 9) == want[9].data, "the small level's neighbour kept its texels"); super::super::vram::LEVEL_PAGES_FOR_TEST.store(false, Ordering::Relaxed); drop((small, full)); VirtualFree(at as *mut c_void, 0, MEM_RELEASE); @@ -2630,4 +4581,28 @@ mod tests { // Different device always starts a new batch. assert!(!batch_fits(1, 4096, 1, 2, 4096)); } + + #[test] + fn title_queue_upload_states_are_leased_and_serialized_per_queue() { + let _guard = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let (first_key, second_key) = (0x7ffe_7100usize, 0x7ffe_7200usize); + ON_QUEUE.lock().unwrap().remove(&first_key); + ON_QUEUE.lock().unwrap().remove(&second_key); + + let first = queue_upload_state(first_key); + let second = queue_upload_state(second_key); + let first_guard = first.lock().unwrap(); + assert!(ON_QUEUE.try_lock().is_ok(), "one queue must not hold the upload registry"); + assert!(second.try_lock().is_ok(), "one queue must not serialize another queue's uploads"); + + let removed = ON_QUEUE.lock().unwrap().remove(&first_key).unwrap(); + assert!(Arc::ptr_eq(&first, &removed), "registry removal returns the leased generation"); + let replacement = queue_upload_state(first_key); + assert!(!Arc::ptr_eq(&first, &replacement), "raw-address reuse gets a fresh queue-local state"); + + drop(first_guard); + drop(removed); + ON_QUEUE.lock().unwrap().remove(&first_key); + ON_QUEUE.lock().unwrap().remove(&second_key); + } } diff --git a/crates/xcl/src/hle/d3d12x/used_journal.rs b/crates/xcl/src/hle/d3d12x/used_journal.rs new file mode 100644 index 0000000000..685b0a0e28 --- /dev/null +++ b/crates/xcl/src/hle/d3d12x/used_journal.rs @@ -0,0 +1,445 @@ +//! Ordered background append journal for `used-pipelines.txt`. + +use std::collections::HashSet; +use std::fmt::Write as _; +use std::io::Write; +use std::path::PathBuf; +use std::sync::{Arc, Condvar, Mutex}; +use std::time::{Duration, Instant}; + +const COALESCE: Duration = Duration::from_millis(25); +const FULL_BATCH: usize = 64; + +trait Sink: Send { + fn append(&mut self, bytes: &[u8]) -> bool; +} + +struct FileSink { + path: PathBuf, + file: Option<std::fs::File>, +} + +impl Sink for FileSink { + fn append(&mut self, bytes: &[u8]) -> bool { + if self.file.is_none() { + if let Some(dir) = self.path.parent() { + let _ = std::fs::create_dir_all(dir); + } + self.file = std::fs::OpenOptions::new().create(true).append(true).open(&self.path).ok(); + } + let ok = self.file.as_mut().is_some_and(|file| file.write_all(bytes).and_then(|_| file.flush()).is_ok()); + if !ok { + self.file = None; + } + ok + } +} + +#[derive(Clone)] +struct Batch { + end_seq: u64, + keys: Arc<[u64]>, +} + +struct State { + seen: HashSet<u64>, + pending: Vec<(u64, u64)>, + in_flight: Option<Batch>, + fallback_path: Option<PathBuf>, + fallback_writing: bool, + next_seq: u64, + completed_seq: u64, + flush_now: bool, + closed: bool, + stopped: bool, +} + +struct Shared { + state: Mutex<State>, + wake: Condvar, + completed: Condvar, +} + +/// A single writer owns the append handle. Producers only touch `Shared::state`; the batch being +/// written stays there until it succeeds, so a later producer can never hide or overtake it. +pub(super) struct Journal { + shared: Arc<Shared>, +} + +impl Journal { + pub(super) fn file(path: PathBuf, seen: HashSet<u64>) -> Self { + Self::with_sink(seen, Box::new(FileSink { path: path.clone(), file: None }), COALESCE, Some(path)) + } + + pub(super) fn memory(seen: HashSet<u64>) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + fallback_path: None, + fallback_writing: false, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: true, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + Self { shared } + } + + fn with_sink(seen: HashSet<u64>, sink: Box<dyn Sink>, coalesce: Duration, fallback_path: Option<PathBuf>) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + fallback_path, + fallback_writing: false, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: false, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + let worker = shared.clone(); + if std::thread::Builder::new().name("xcl-pso-used".into()).spawn(move || writer(worker, sink, coalesce)).is_err() { + shared.state.lock().unwrap().stopped = true; + } + Self { shared } + } + + #[cfg(test)] + fn stopped_file(path: PathBuf, seen: HashSet<u64>) -> Self { + let shared = Arc::new(Shared { + state: Mutex::new(State { + seen, + pending: Vec::new(), + in_flight: None, + fallback_path: Some(path), + fallback_writing: false, + next_seq: 0, + completed_seq: 0, + flush_now: false, + closed: false, + stopped: true, + }), + wake: Condvar::new(), + completed: Condvar::new(), + }); + Self { shared } + } + + pub(super) fn note(&self, key: u64) { + if key == 0 { + return; + } + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if state.closed || !state.seen.insert(key) { + return; + } + // An in-memory journal still deduplicates. A file journal retains keys for the bounded + // shutdown fallback when its worker could not start. + if state.stopped && state.fallback_path.is_none() { + return; + } + state.next_seq += 1; + let seq = state.next_seq; + state.pending.push((seq, key)); + if state.pending.len() == 1 || state.pending.len() == FULL_BATCH { + self.shared.wake.notify_one(); + } + } + + #[cfg(test)] + pub(super) fn contains(&self, key: u64) -> bool { self.shared.state.lock().unwrap_or_else(|e| e.into_inner()).seen.contains(&key) } + + pub(super) fn flush_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, false) } + + pub(super) fn shutdown_bounded(&self, timeout: Duration) -> bool { self.wait_bounded(timeout, true) } + + fn wait_bounded(&self, timeout: Duration, close: bool) -> bool { + let deadline = Instant::now() + timeout; + let mut state = loop { + match self.shared.state.try_lock() { + Ok(state) => break state, + Err(std::sync::TryLockError::Poisoned(e)) => break e.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => { + if Instant::now() >= deadline { + return false; + } + std::thread::yield_now(); + } + } + }; + if close { + state.closed = true; + } + let target = state.next_seq; + state.flush_now = true; + self.shared.wake.notify_one(); + while (state.completed_seq < target || close && !state.stopped) && !state.stopped { + let Some(left) = deadline.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (next, waited) = self.shared.completed.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()); + state = next; + if waited.timed_out() { + break; + } + } + let complete = state.completed_seq >= target && (!close || state.stopped); + drop(state); + complete || self.append_after_worker_stopped() + } + + /// A failed spawn (or a worker panic) has dropped its sink, so this is the only writer. Keep + /// the bind path memory-only and persist its ordered backlog at an explicit flush boundary. + fn append_after_worker_stopped(&self) -> bool { + let (path, end_seq, interrupted_append, keys) = { + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if !state.stopped || state.fallback_writing { + return false; + } + let Some(path) = state.fallback_path.clone() else { return false }; + let mut entries = Vec::new(); + let interrupted_append = state.in_flight.is_some(); + if let Some(batch) = &state.in_flight { + entries.extend(batch.keys.iter().copied().map(|key| (batch.end_seq, key))); + } + entries.extend(state.pending.iter().copied()); + let Some(end_seq) = entries.last().map(|entry| entry.0) else { return true }; + state.fallback_writing = true; + (path, end_seq, interrupted_append, entries.into_iter().map(|(_, key)| key).collect::<Vec<_>>()) + }; + + // A stopped worker may have left a partial hexadecimal line. The marker makes that + // fragment invalid before the complete records are retried without rejecting old files + // that used shorter hexadecimal keys. + let mut bytes = String::new(); + if interrupted_append { + bytes.push_str("!\n"); + } + bytes.reserve(keys.len() * 17); + for key in keys { + let _ = writeln!(bytes, "{key:016x}"); + } + let written = (FileSink { path, file: None }).append(bytes.as_bytes()); + + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + state.fallback_writing = false; + if written && state.stopped { + state.in_flight = state.in_flight.take().filter(|batch| batch.end_seq > end_seq); + state.pending.retain(|(seq, _)| *seq > end_seq); + state.completed_seq = state.completed_seq.max(end_seq); + self.shared.completed.notify_all(); + } + written && state.completed_seq >= end_seq + } +} + +impl Drop for Journal { + fn drop(&mut self) { + let _ = self.shutdown_bounded(Duration::from_millis(100)); + } +} + +struct Stopped { + shared: Arc<Shared>, + sink: Option<Box<dyn Sink>>, +} + +impl Drop for Stopped { + fn drop(&mut self) { + // Publish `stopped` only after the worker's append handle is gone. The fallback can then + // open the path without ever overlapping the worker, including during panic unwinding. + drop(self.sink.take()); + let mut state = self.shared.state.lock().unwrap_or_else(|e| e.into_inner()); + state.stopped = true; + self.shared.completed.notify_all(); + } +} + +fn writer(shared: Arc<Shared>, sink: Box<dyn Sink>, coalesce: Duration) { + let mut stopped = Stopped { shared: shared.clone(), sink: Some(sink) }; + let mut bytes = String::new(); + let mut retrying = false; + loop { + let batch = { + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + while state.in_flight.is_none() && state.pending.is_empty() && !state.closed { + state = shared.wake.wait(state).unwrap_or_else(|e| e.into_inner()); + } + if state.in_flight.is_none() && !state.pending.is_empty() && !coalesce.is_zero() && !state.flush_now && !state.closed { + let until = Instant::now() + coalesce; + while state.pending.len() < FULL_BATCH && !state.flush_now && !state.closed { + let Some(left) = until.checked_duration_since(Instant::now()).filter(|d| !d.is_zero()) else { break }; + let (next, waited) = shared.wake.wait_timeout(state, left).unwrap_or_else(|e| e.into_inner()); + state = next; + if waited.timed_out() { + break; + } + } + } + state.flush_now = false; + if state.in_flight.is_none() && !state.pending.is_empty() { + let pending = std::mem::take(&mut state.pending); + let end_seq = pending.last().unwrap().0; + state.in_flight = Some(Batch { end_seq, keys: pending.into_iter().map(|(_, key)| key).collect() }); + } + let Some(batch) = state.in_flight.clone() else { + if state.closed { break } else { continue }; + }; + batch + }; + + bytes.clear(); + if retrying { + // `write_all` may have appended an arbitrary prefix before reporting failure. Make + // that fragment invalid so replay cannot rank a torn hexadecimal prefix as a key. + bytes.push_str("!\n"); + } + bytes.reserve(batch.keys.len() * 17); + for key in batch.keys.iter() { + let _ = writeln!(bytes, "{key:016x}"); + } + let written = stopped.sink.as_mut().unwrap().append(bytes.as_bytes()); + retrying = !written; + let mut state = shared.state.lock().unwrap_or_else(|e| e.into_inner()); + if written { + if state.in_flight.as_ref().is_some_and(|current| current.end_seq == batch.end_seq) { + state.in_flight = None; + state.completed_seq = state.completed_seq.max(batch.end_seq); + shared.completed.notify_all(); + } + } else { + let (next, _) = shared.wake.wait_timeout(state, coalesce.max(Duration::from_millis(1))).unwrap_or_else(|e| e.into_inner()); + drop(next); + } + } + drop(stopped); +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc; + + struct Blocking { + first: bool, + entered: mpsc::Sender<()>, + release: mpsc::Receiver<()>, + output: Arc<Mutex<Vec<u8>>>, + } + + impl Sink for Blocking { + fn append(&mut self, bytes: &[u8]) -> bool { + if self.first { + self.first = false; + self.entered.send(()).unwrap(); + self.release.recv().unwrap(); + } + self.output.lock().unwrap().extend_from_slice(bytes); + true + } + } + + #[test] + fn flush_waits_for_the_shared_in_flight_batch_and_later_producers() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let output = Arc::new(Mutex::new(Vec::new())); + let journal = Arc::new(Journal::with_sink( + HashSet::new(), + Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: output.clone() }), + Duration::ZERO, + None, + )); + journal.note(1); + entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not take the first batch"); + journal.note(2); + let waiter = journal.clone(); + let (flushed_tx, flushed_rx) = mpsc::channel(); + std::thread::spawn(move || flushed_tx.send(waiter.flush_bounded(Duration::from_secs(2))).unwrap()); + assert!(matches!(flushed_rx.recv_timeout(Duration::from_millis(20)), Err(mpsc::RecvTimeoutError::Timeout))); + release_tx.send(()).unwrap(); + assert!(flushed_rx.recv_timeout(Duration::from_secs(2)).unwrap()); + assert_eq!(String::from_utf8(output.lock().unwrap().clone()).unwrap(), "0000000000000001\n0000000000000002\n"); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + struct FailOnce { + failed: bool, + output: Arc<Mutex<Vec<u8>>>, + } + + impl Sink for FailOnce { + fn append(&mut self, bytes: &[u8]) -> bool { + if !self.failed { + self.failed = true; + self.output.lock().unwrap().extend_from_slice(&bytes[..8.min(bytes.len())]); + return false; + } + self.output.lock().unwrap().extend_from_slice(bytes); + true + } + } + + #[test] + fn failed_batch_is_retried_before_later_keys() { + let output = Arc::new(Mutex::new(Vec::new())); + let journal = Journal::with_sink( + HashSet::new(), + Box::new(FailOnce { failed: false, output: output.clone() }), + Duration::from_millis(1), + None, + ); + journal.note(0xdead_beef_0000_0003); + journal.note(0xdead_beef_0000_0004); + assert!(journal.flush_bounded(Duration::from_secs(2))); + journal.note(0xdead_beef_0000_0005); + assert!(journal.flush_bounded(Duration::from_secs(2))); + let text = String::from_utf8(output.lock().unwrap().clone()).unwrap(); + let keys: Vec<u64> = text.lines().filter_map(|line| u64::from_str_radix(line, 16).ok()).filter(|&key| key != 0).collect(); + assert_eq!(keys, [0xdead_beef_0000_0003, 0xdead_beef_0000_0004, 0xdead_beef_0000_0005]); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + #[test] + fn shutdown_is_bounded_when_the_only_writer_is_blocked() { + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let journal = Journal::with_sink( + HashSet::new(), + Box::new(Blocking { first: true, entered: entered_tx, release: release_rx, output: Arc::new(Mutex::new(Vec::new())) }), + Duration::ZERO, + None, + ); + journal.note(6); + entered_rx.recv_timeout(Duration::from_secs(2)).expect("writer did not block"); + let start = Instant::now(); + assert!(!journal.shutdown_bounded(Duration::from_millis(20))); + assert!(start.elapsed() < Duration::from_millis(500), "bounded shutdown waited {:?}", start.elapsed()); + release_tx.send(()).unwrap(); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + } + + #[test] + fn worker_start_failure_defers_ordered_unique_writes_until_shutdown() { + let path = std::env::temp_dir().join(format!("xcl-used-no-worker-{}.txt", std::process::id())); + let _ = std::fs::remove_file(&path); + let journal = Journal::stopped_file(path.clone(), [7].into()); + journal.note(8); + journal.note(7); + journal.note(9); + journal.note(8); + assert!(!path.exists(), "the producer performed file I/O"); + assert!(journal.shutdown_bounded(Duration::from_secs(2))); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "0000000000000008\n0000000000000009\n"); + let _ = std::fs::remove_file(path); + } +} diff --git a/crates/xcl/src/hle/d3d12x/vram.rs b/crates/xcl/src/hle/d3d12x/vram.rs index ea49ce6b89..921e9596cd 100644 --- a/crates/xcl/src/hle/d3d12x/vram.rs +++ b/crates/xcl/src/hle/d3d12x/vram.rs @@ -23,9 +23,9 @@ //! driver does not make reserved: D32S8, MSAA): heaps of the placement's size, shared by //! placements inside them, let go 2 s after their last resource (256 MiB ones: 2.8 GB of D32S8). -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::ffi::c_void; -use std::sync::Mutex; +use std::sync::{Arc, Mutex, OnceLock}; use windows::core::Interface; use windows::Win32::Graphics::Direct3D12::*; @@ -108,6 +108,9 @@ impl<H: Clone> Arenas<H> { } fn bytes(&self) -> usize { self.list.iter().map(|a| a.size).sum() } + fn bytes_for(&self, dev: usize) -> usize { + self.list.iter().filter(|a| a.dev == dev).fold(0, |bytes, a| bytes.saturating_add(a.size)) + } } // D3D12 heaps are free-threaded @@ -123,14 +126,609 @@ static MADE_BYTES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsi pub fn arena_bytes() -> (usize, usize) { (ARENAS.lock().unwrap().bytes(), MADE_BYTES.load(std::sync::atomic::Ordering::Relaxed)) } + +pub(super) fn arena_bytes_for(device: usize) -> usize { + ARENAS.lock().unwrap().bytes_for(device) +} static PLACED_TEXTURES: Mutex<Option<HashSet<usize>>> = Mutex::new(None); +/// `XCL_TEXTURE_BUDGET_EVICT=1`: retain CPU-side identities for live texture SRVs. This is +/// preparation only: recorded command lists can still name older descriptor contents, so these +/// records do not make descriptor replacement or texture eviction GPU-safe. +#[inline] +pub(super) fn srv_tracking_enabled() -> bool { + #[cfg(test)] + if SRV_TRACKING_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) { + return true; + } + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| { + let on = std::env::var("XCL_TEXTURE_BUDGET_EVICT").is_ok_and(|v| v.trim() == "1"); + if on { + crate::xlog_info!("D3D12.X: XCL_TEXTURE_BUDGET_EVICT=1 - tracking live texture SRV metadata only; texture mappings and descriptors are unchanged"); + } + on + }) +} + +#[cfg(test)] +static SRV_TRACKING_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) struct SharedViewEpoch(u64); + +enum EpochRetirement<R> { + Reserved, + Receipt(R), + Poisoned, +} + +struct SharedViewEpochs<R> { + next: u64, + poisoned: bool, + pending: Vec<(SharedViewEpoch, EpochRetirement<R>)>, +} + +impl<R> SharedViewEpochs<R> { + const fn new() -> Self { + Self { next: 0, poisoned: false, pending: Vec::new() } + } + + fn reserve(&mut self) -> SharedViewEpoch { + self.next = self.next.checked_add(1).expect("shared view heap epoch overflow"); + let epoch = SharedViewEpoch(self.next); + self.pending.push((epoch, EpochRetirement::Reserved)); + epoch + } + + fn cancel(&mut self, epoch: SharedViewEpoch) { + match self.pending.iter().position(|entry| entry.0 == epoch) { + Some(i) if matches!(self.pending[i].1, EpochRetirement::Reserved) => { + self.pending.remove(i); + } + _ => self.poisoned = true, + } + } + + fn attach(&mut self, epoch: SharedViewEpoch, receipt: R) { + match self.pending.iter_mut().find(|entry| entry.0 == epoch) { + Some((_, state @ EpochRetirement::Reserved)) => *state = EpochRetirement::Receipt(receipt), + _ => self.poisoned = true, + } + } + + fn poison(&mut self, epoch: SharedViewEpoch) { + match self.pending.iter_mut().find(|entry| entry.0 == epoch) { + Some((_, state @ EpochRetirement::Reserved)) => *state = EpochRetirement::Poisoned, + _ => self.poisoned = true, + } + } + + fn sweep(&mut self, complete: impl Fn(&R) -> bool) { + self.pending.retain(|(_, state)| !matches!(state, EpochRetirement::Receipt(receipt) if complete(receipt))); + } + + fn quiescent(&mut self, complete: impl Fn(&R) -> bool) -> bool { + self.sweep(complete); + !self.poisoned && self.pending.is_empty() + } +} + +fn with_quiescent_epochs<R, T>( + tracking_enabled: bool, + epochs: &Mutex<SharedViewEpochs<R>>, + complete: impl Fn(&R) -> bool, + mutation: impl FnOnce() -> T, +) -> Option<T> { + if !tracking_enabled { + return None; + } + let mut epochs = epochs.lock().unwrap(); + if !epochs.quiescent(complete) { + return None; + } + let result = mutation(); + drop(epochs); + Some(result) +} + +static SHARED_VIEW_EPOCHS: Mutex<SharedViewEpochs<super::alloc_pool::SubmissionReceipt>> = + Mutex::new(SharedViewEpochs::new()); + +pub(super) fn reserve_shared_view_epoch() -> SharedViewEpoch { + let mut epochs = SHARED_VIEW_EPOCHS.lock().unwrap(); + epochs.sweep(super::alloc_pool::SubmissionReceipt::is_complete); + epochs.reserve() +} + +pub(super) fn cancel_shared_view_epoch(epoch: SharedViewEpoch) { + SHARED_VIEW_EPOCHS.lock().unwrap().cancel(epoch); +} + +pub(super) fn attach_shared_view_epoch(epoch: SharedViewEpoch, receipt: super::alloc_pool::SubmissionReceipt) { + SHARED_VIEW_EPOCHS.lock().unwrap().attach(epoch, receipt); +} + +pub(super) fn poison_shared_view_epoch(epoch: SharedViewEpoch) { + SHARED_VIEW_EPOCHS.lock().unwrap().poison(epoch); +} + +/// Run a descriptor mutation only while every tracked shared-view submission is retired, holding +/// the epoch lock until the mutation ends so a new reservation cannot cross the check. This lock +/// is outermost: the closure may take descriptor backing/tracker locks, but must not submit GPU +/// work or call anything that reserves another shared-view epoch. +/// +/// A missing post-execute receipt permanently returns `None`, so an untracked submission (or a +/// reused queue address) can never be mistaken for quiescence. +#[allow(dead_code)] // consumed by the later descriptor-rewrite stage +pub(super) fn with_quiescent_shared_view_heap<T>(mutation: impl FnOnce() -> T) -> Option<T> { + with_quiescent_epochs( + srv_tracking_enabled(), &SHARED_VIEW_EPOCHS, super::alloc_pool::SubmissionReceipt::is_complete, mutation, + ) +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub(super) struct SrvSlot { + heap_generation: u64, + slot: u32, +} + +impl SrvSlot { + fn of(slot: &super::console_heap::Slot) -> Self { + Self { heap_generation: slot.generation, slot: slot.k } + } +} + +/// Numeric COM identities are never dereferenced here. Resource and heap lifetime hooks remove +/// them; a later descriptor-generation design must still prove queue-fence safety before use. +#[derive(Clone, Copy)] +#[cfg_attr(not(test), allow(dead_code))] +struct TrackedSrv { + generation: u64, + device: usize, + resource: usize, + pc_srv: u64, + shared_srv: u64, + index: u32, + desc: Option<D3D12_SHADER_RESOURCE_VIEW_DESC>, + /// Exact XCL ABI descriptor bytes written for this logical generation. Only shared-heap slots + /// are tracked: their global word-0 index makes an unhooked raw overwrite observable. + words: [u32; 8], +} + +#[derive(Default)] +struct TrackedSrvs { + next_generation: u64, + by_slot: HashMap<SrvSlot, TrackedSrv>, +} + +impl TrackedSrvs { + fn write(&mut self, slot: SrvSlot, entry: Option<TrackedSrv>) { + self.by_slot.remove(&slot); + if let Some(mut entry) = entry { + self.next_generation = self.next_generation.wrapping_add(1).max(1); + entry.generation = self.next_generation; + self.by_slot.insert(slot, entry); + } + } + + fn copy_range( + &mut self, + device: usize, + copies: &[(SrvSlot, u64, u64, u32, SrvSlot, bool, [u32; 8], [u32; 8])], + ) { + let sources: Vec<_> = copies.iter().map(|(src, _, _, _, _, track_source, ..)| + track_source.then(|| self.by_slot.get(src).copied()).flatten()).collect(); + for ((_, pc_srv, shared_srv, index, dst, _, source_words, destination_words), source) in copies.iter().zip(sources) { + let entry = source.filter(|entry| entry.words == *source_words).map(|mut entry| { + entry.device = device; + entry.pc_srv = *pc_srv; + entry.shared_srv = *shared_srv; + entry.index = *index; + entry.words = *destination_words; + entry + }); + self.write(*dst, entry); + } + } + + fn forget_heap(&mut self, generation: u64) { + self.by_slot.retain(|slot, _| slot.heap_generation != generation); + } + + fn forget_resource(&mut self, resource: usize) { + self.by_slot.retain(|_, entry| entry.resource != resource); + } + + /// Apply raw-memory observations made without this lock. A concurrent tracked overwrite has + /// another logical generation and is omitted from this snapshot rather than judged against + /// words observed for its predecessor. + fn reconcile_observed(&mut self, observed: &[(SrvSlot, u64, Option<[u32; 8]>)]) -> Vec<(SrvSlot, TrackedSrv)> { + let mut snapshot = Vec::new(); + for &(slot, generation, words) in observed { + let Some(entry) = self.by_slot.get(&slot).copied().filter(|entry| entry.generation == generation) else { continue }; + if words == Some(entry.words) { + snapshot.push((slot, entry)); + } else { + self.by_slot.remove(&slot); + } + } + snapshot + } +} + +static TRACKED_SRVS: Mutex<Option<TrackedSrvs>> = Mutex::new(None); +static TRACKED_SRV_WRITES: Mutex<()> = Mutex::new(()); +static TRACKED_SRV_LIFETIMES: Mutex<()> = Mutex::new(()); + +pub(super) type TrackedSrvWriteGuard = std::sync::MutexGuard<'static, ()>; +pub(super) type TrackedSrvLifetimeGuard = std::sync::MutexGuard<'static, ()>; + +/// Serialize an entire hooked descriptor mutation while tracking is enabled. Operation tokens +/// alone order hook starts, not native/console writes that complete in the opposite order. +pub(super) fn lock_tracked_srv_write() -> Option<TrackedSrvWriteGuard> { + srv_tracking_enabled().then(|| TRACKED_SRV_WRITES.lock().unwrap()) +} + +/// Exclude final native resource Release while a tracked entry is turned into a strong owner. +/// This is deliberately distinct from `TRACKED_SRV_WRITES`: descriptor hooks hold the write gate +/// across driver calls which may make a temporary, non-final resource Release. +pub(super) fn lock_tracked_srv_lifetime() -> Option<TrackedSrvLifetimeGuard> { + srv_tracking_enabled().then(|| TRACKED_SRV_LIFETIMES.lock().unwrap()) +} + +/// Record the descriptor currently in `slot`. `None` clears an SRV overwritten by another view. +pub(super) fn track_srv( + device: usize, + resource: usize, + slot: &super::console_heap::Slot, + desc: Option<D3D12_SHADER_RESOURCE_VIEW_DESC>, + words: [u32; 8], +) { + if !srv_tracking_enabled() || slot.shared_srv == 0 { + return; + } + let texture_view = desc.is_none_or(|v| { + v.ViewDimension != D3D12_SRV_DIMENSION_BUFFER && v.ViewDimension != D3D12_SRV_DIMENSION_RAYTRACING_ACCELERATION_STRUCTURE + }); + let entry = (resource != 0 && texture_view && is_placed_texture(resource)).then_some(TrackedSrv { + generation: 0, + device, + resource, + pc_srv: slot.pc_srv, + shared_srv: slot.shared_srv, + index: slot.index, + desc, + words, + }); + TRACKED_SRVS.lock().unwrap().get_or_insert_with(Default::default).write(SrvSlot::of(slot), entry); +} + +pub(super) fn clear_tracked_srv(slot: &super::console_heap::Slot) { + if srv_tracking_enabled() { + TRACKED_SRVS.lock().unwrap().get_or_insert_with(Default::default).write(SrvSlot::of(slot), None); + } +} + +pub(super) fn copy_tracked_srvs( + device: usize, + copies: &[(super::console_heap::Slot, super::console_heap::Slot, [u32; 8], [u32; 8])], +) { + if !srv_tracking_enabled() || copies.is_empty() { + return; + } + let copies: Vec<_> = copies + .iter() + .map(|(src, dst, source_words, destination_words)| + (SrvSlot::of(src), dst.pc_srv, dst.shared_srv, dst.index, SrvSlot::of(dst), + src.shared_srv != 0 && dst.shared_srv != 0, *source_words, *destination_words)) + .collect(); + TRACKED_SRVS.lock().unwrap().get_or_insert_with(Default::default).copy_range(device, &copies); +} + +pub(super) fn forget_srv_heap(generation: u64) { + if !srv_tracking_enabled() { + return; + } + let _write = lock_tracked_srv_write(); + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_heap(generation); + } +} + +/// Remove candidates for a descriptor heap that reached final native `Release`, while the heap +/// lifetime gate still excludes snapshots. Do not take `TRACKED_SRV_WRITES`: a descriptor hook +/// may hold it across a driver call which reenters a temporary heap Release. +pub(super) fn forget_srv_heap_after_release( + generation: u64, lifetime: Option<&super::console_heap::HeapLifetimeGuard>, +) { + debug_assert!(!srv_tracking_enabled() || lifetime.is_some()); + if lifetime.is_some() { + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_heap(generation); + } + } +} + +fn forget_tracked_srvs_locked(resource: usize) { + if let Some(tracked) = TRACKED_SRVS.lock().unwrap().as_mut() { + tracked.forget_resource(resource); + } +} + +#[cfg(test)] +fn forget_tracked_srvs(resource: usize) { + if !srv_tracking_enabled() { + return; + } + let _write = lock_tracked_srv_write(); + forget_tracked_srvs_locked(resource); +} + +/// Clone an owner for one exact tracked resource while final `Release` is excluded. The tracker +/// mutex makes the snapshot coherent; this does not take the descriptor-write gate. A later +/// mutator must take that gate and revalidate the logical generation, as well as lease the exact +/// heap generation, before using `pc_srv` or `shared_srv`. +#[allow(dead_code)] // consumed by the later descriptor-rewrite stage +fn lease_tracked_srv_resource(slot: SrvSlot, generation: u64) -> Option<(TrackedSrv, ID3D12Resource, super::console_heap::ViewSlotLease)> { + let (entry, resource) = lease_tracked_srv_resource_with(slot, generation, |resource| { + let raw = resource as *mut std::ffi::c_void; + unsafe { ID3D12Resource::from_raw_borrowed(&raw).cloned() } + })?; + let heap = super::console_heap::lease_view_slot( + slot.heap_generation, slot.slot, entry.pc_srv, entry.shared_srv, entry.index, + )?; + Some((entry, resource, heap)) +} + +fn lease_tracked_srv_resource_with<T>( + slot: SrvSlot, generation: u64, lease: impl FnOnce(usize) -> Option<T>, +) -> Option<(TrackedSrv, T)> { + if !srv_tracking_enabled() { + return None; + } + let _lifetime = TRACKED_SRV_LIFETIMES.lock().unwrap(); + let entry = TRACKED_SRVS + .lock() + .unwrap() + .as_ref()? + .by_slot + .get(&slot) + .copied() + .filter(|entry| entry.generation == generation)?; + let owner = lease(entry.resource)?; + Some((entry, owner)) +} + +/// Execute one point-in-time mutation of an exact tracked SRV generation. Queue quiescence is +/// held outermost so no new shared-view submission can cross the mutation. Strong resource and +/// heap owners are acquired before `WRITE`, then the tracker generation and all eight console +/// words are revalidated immediately before `mutate` runs. The tracker mutex is not held across +/// `mutate`; `WRITE` is, so the closure must call only unhooked descriptor operations and must not +/// submit work or reserve another shared-view epoch. +/// +/// Title code can write console descriptor memory without using a hook. Such a write can race +/// after the point-in-time word check, so this primitive deliberately promises no stronger +/// atomicity than the title's descriptor-lifetime rules. A mismatch fails closed and forgets only +/// the stale generation. Strong owners are dropped after `WRITE` and the tracker lock are gone. +#[allow(dead_code)] // consumed by the later descriptor-rewrite policy +fn with_exact_tracked_srv_mutation<T>( + slot: SrvSlot, + generation: u64, + mutate: impl FnOnce(&TrackedSrv, &ID3D12Resource, &super::console_heap::ViewSlotLease) -> T, +) -> Option<T> { + with_exact_tracked_srv_mutation_on( + slot, + generation, + lease_tracked_srv_resource, + |slot| super::console_heap::exact_view_slot_words(slot.heap_generation, slot.slot), + mutate, + ) +} + +fn with_exact_tracked_srv_mutation_on<T, Resource, Heap>( + slot: SrvSlot, + generation: u64, + lease: impl FnOnce(SrvSlot, u64) -> Option<(TrackedSrv, Resource, Heap)>, + observe_words: impl FnOnce(SrvSlot) -> Option<[u32; 8]>, + mutate: impl FnOnce(&TrackedSrv, &Resource, &Heap) -> T, +) -> Option<T> { + with_quiescent_shared_view_heap(|| { + let (snapshot, resource, heap) = lease(slot, generation)?; + let result = { + let _write = lock_tracked_srv_write()?; + let valid = { + let mut tracked = TRACKED_SRVS.lock().unwrap(); + let current = tracked.as_mut()?.by_slot.get(&slot).copied()?; + if current.generation != generation { + return None; + } + // This is TRACKED_SRVS -> HEAPS. Final heap cleanup drops HEAPS before taking + // TRACKED_SRVS, and descriptor-hook lookups also take them sequentially, so there + // is no nested inverse while the exact words are observed. + if observe_words(slot) != Some(current.words) { + tracked.as_mut()?.by_slot.remove(&slot); + return None; + } + // The generation identifies the complete immutable tracker snapshot. Drop this + // mutex before the supplied operation; WRITE keeps hooked mutations excluded. + current + }; + debug_assert_eq!(valid.generation, snapshot.generation); + Some(mutate(&valid, &resource, &heap)) + }; + // `resource` and `heap` drop here, after the tracker and WRITE guards above. + result + }) + .flatten() +} + +/// One exact tracked descriptor and the native owners which make its resource and heap safe to +/// use during a batch mutation. +#[allow(dead_code)] // consumed by the later descriptor-rewrite policy +struct ExactSrvMutation<'a, Resource, Heap> { + entry: TrackedSrv, + resource: &'a Resource, + heap: &'a Heap, +} + +/// Execute one point-in-time mutation of a batch of tracked SRV generations. One quiescent epoch +/// and one descriptor-write exclusion cover the whole batch; missing leases and stale candidates +/// fail closed independently, in the caller's deterministic order. The operation is not called if +/// no candidate survives revalidation. The supplied operation has the same restrictions as +/// `with_exact_tracked_srv_mutation`: it must use only unhooked descriptor operations and must not +/// submit work or reserve another shared-view epoch. +/// +/// Raw title descriptor writes remain outside XCL's exclusion. All eight words are observed under +/// `WRITE` immediately before the operation, but title code can still race after that point; a +/// future policy must obey the title's descriptor-lifetime rules. +#[allow(dead_code)] // consumed by the later descriptor-rewrite policy +fn with_exact_tracked_srv_mutations<T>( + candidates: &[(SrvSlot, u64)], + mutate: impl FnOnce(&[ExactSrvMutation<'_, ID3D12Resource, super::console_heap::ViewSlotLease>]) -> T, +) -> Option<T> { + with_exact_tracked_srv_mutations_on( + candidates, + lease_tracked_srv_resource, + |slots| super::console_heap::view_slot_words(slots), + mutate, + ) +} + +fn with_exact_tracked_srv_mutations_on<T, Resource, Heap>( + candidates: &[(SrvSlot, u64)], + mut lease: impl FnMut(SrvSlot, u64) -> Option<(TrackedSrv, Resource, Heap)>, + observe_words: impl FnOnce(&[(u64, u32)]) -> Vec<Option<[u32; 8]>>, + mutate: impl FnOnce(&[ExactSrvMutation<Resource, Heap>]) -> T, +) -> Option<T> { + if !srv_tracking_enabled() { + return None; + } + let mut seen = HashSet::new(); + let candidates: Vec<_> = candidates.iter().copied().filter(|candidate| seen.insert(*candidate)).collect(); + if candidates.is_empty() { + return None; + } + with_quiescent_shared_view_heap(|| { + let leased: Vec<_> = candidates + .into_iter() + .filter_map(|(slot, generation)| lease(slot, generation).map(|(snapshot, resource, heap)| { + (slot, generation, snapshot, resource, heap) + })) + .collect(); + if leased.is_empty() { + return None; + } + let slots: Vec<_> = leased.iter().map(|(slot, ..)| (slot.heap_generation, slot.slot)).collect(); + + // `leased` owns every native object and was declared before `write`: unwind therefore + // drops the later-declared guard first, even for candidates rejected below. + let mut valid = Vec::with_capacity(leased.len()); + let write = lock_tracked_srv_write()?; + let observed = observe_words(&slots); + let mut validated = Vec::with_capacity(leased.len()); + { + let mut tracked = TRACKED_SRVS.lock().unwrap(); + let tracked = tracked.as_mut()?; + for (i, (slot, generation, snapshot, ..)) in leased.iter().enumerate() { + let Some(current) = tracked.by_slot.get(slot).copied() else { + validated.push(None); + continue; + }; + if current.generation != *generation { + validated.push(None); + continue; + } + let words = observed.get(i).copied().flatten(); + if words != Some(current.words) { + // `current` was read under this mutex and still names the requested exact + // generation, so removal cannot erase a concurrent replacement. + tracked.by_slot.remove(slot); + validated.push(None); + continue; + } + debug_assert_eq!(snapshot.generation, current.generation); + validated.push(Some(current)); + } + } + for ((_, _, _, resource, heap), entry) in leased.iter().zip(validated) { + if let Some(entry) = entry { + valid.push(ExactSrvMutation { entry, resource, heap }); + } + } + if valid.is_empty() { + drop(write); + drop(valid); + drop(leased); + return None; + } + let result = mutate(&valid); + drop(write); + drop(valid); + drop(leased); + Some(result) + }) + .flatten() +} + +/// An exact, on-demand snapshot for a future residency consumer. It is deliberately not on the +/// submit path: scanning every live SRV there would turn descriptor count into foreground cost. +/// A consumer must still capture descriptor generations with recorded lists and queue fences; +/// title code can raw-write descriptor memory immediately after this point-in-time snapshot. +#[allow(dead_code)] +fn reconciled_tracked_srvs() -> Vec<(SrvSlot, TrackedSrv)> { + if !srv_tracking_enabled() { + return Vec::new(); + } + let candidates: Vec<_> = TRACKED_SRVS + .lock() + .unwrap() + .as_ref() + .map(|tracked| tracked.by_slot.iter().map(|(&slot, entry)| (slot, entry.generation)).collect()) + .unwrap_or_default(); + let slots: Vec<_> = candidates.iter().map(|(slot, _)| (slot.heap_generation, slot.slot)).collect(); + let words = super::console_heap::view_slot_words(&slots); + let observed: Vec<_> = candidates + .into_iter() + .zip(words) + .map(|((slot, generation), words)| (slot, generation, words)) + .collect(); + TRACKED_SRVS.lock().unwrap().as_mut().map_or_else(Vec::new, |tracked| tracked.reconcile_observed(&observed)) +} + /// A texture backed by one of the aliasable D3D12 heaps. pub(super) fn is_placed_texture(resource: usize) -> bool { PLACED_TEXTURES.lock().unwrap().as_ref().is_some_and(|textures| textures.contains(&resource)) } +#[cfg(test)] pub(super) fn forget(resource: usize) { + forget_tracked_srvs(resource); + forget_resource_backing(resource); +} + +/// Remove descriptor records after native final `Release`, while the caller still holds the +/// lifetime gate acquired before that call. Do not acquire the descriptor-write gate here: an +/// unrelated hook may hold it across a driver call whose temporary resource Release waits on the +/// lifetime gate. The tracker mutex makes removal atomic with lease snapshots. A future descriptor +/// transaction must take the write gate and revalidate the exact generation and descriptor words; +/// a same-resource descriptor hook concurrent with final Release is invalid object lifetime use. +/// Once this returns no new resource lease can start, so the caller may drop the lifetime gate +/// before doing unrelated sparse/page/arena cleanup. +pub(super) fn forget_tracked_after_resource_release( + resource: usize, lifetime: Option<&TrackedSrvLifetimeGuard>, +) { + debug_assert!(!srv_tracking_enabled() || lifetime.is_some()); + if lifetime.is_some() { + forget_tracked_srvs_locked(resource); + } +} + +pub(super) fn forget_resource_backing_after_release(resource: usize) { + forget_resource_backing(resource); +} + +fn forget_resource_backing(resource: usize) { let placed = PLACED_TEXTURES.lock().unwrap().as_mut().is_some_and(|textures| textures.remove(&resource)); if placed { forget_pages(resource); @@ -233,6 +831,8 @@ struct Target { used_extra: Vec<(usize, usize)>, /// its levels get their pages one by one (`map_levels`); None: all of it has pages levels: Option<Levels>, + /// virtual, resident, and SRV-sampled texel accounting for sampled placed textures (`None` for GPU-owned targets) + texels: Option<TexelMeta>, } /// The tiles of a texture whose levels get video memory when an upload first has texels for @@ -242,6 +842,8 @@ struct Target { struct Levels { /// (the group's first subresource, its first tile in the resource, its tiles, mapped) groups: Vec<(u32, u32, u32, bool)>, + /// Physical-page keys owned by each mapped group. + group_tiles: Vec<(Vec<usize>, Vec<(usize, usize)>)>, /// the texture's levels (the last group's go up to here) mips: u32, } @@ -264,7 +866,8 @@ impl Levels { } next = g.1.checked_add(g.2)?; } - (next == total && !groups.is_empty()).then_some(Levels { groups, mips }) + let group_tiles = vec![(Vec::new(), Vec::new()); groups.len()]; + (next == total && !groups.is_empty()).then_some(Levels { groups, group_tiles, mips }) } /// The levels of group `k`. @@ -278,6 +881,12 @@ impl Levels { } } +fn take_level_tiles(levels: Option<&mut Levels>) -> Vec<(Vec<usize>, Vec<(usize, usize)>)> { + levels + .map(|levels| levels.group_tiles.iter_mut().map(std::mem::take).collect()) + .unwrap_or_default() +} + /// `XCL_TEXTURE_LEVEL_PAGES=1` (off by default): a sampled 2D texture of one slice on the /// shared pages gets the pages of a level when an upload first has texels for it. A retail game /// places its streamed textures at full size and maps memory under their levels as it loads @@ -313,6 +922,221 @@ fn level_stats() -> (u64, u64, u64, u64) { (l(0), l(1), l(2), l(3)) } +/// Snapshot of placed sampled-texture residency and SRV mip coverage (`XCL_ACTIVITY`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct TexelStats { + pub sampled_textures: u64, + pub srv_textures: u64, + pub total_texels: u64, + pub resident_texels: u64, + pub srv_sampled_texels: u64, +} + +static TEXEL_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + +pub fn texel_stats() -> TexelStats { + let l = |k: usize| TEXEL_STATS[k].load(std::sync::atomic::Ordering::Relaxed); + TexelStats { + sampled_textures: l(0), + srv_textures: l(1), + total_texels: l(2), + resident_texels: l(3), + srv_sampled_texels: l(4), + } +} + +fn mip_texels(width: u64, height: u32, depth: u16, dim: i32, mip: u32) -> u64 { + let shift = mip.min(63); + let w = (width >> shift).max(1); + let slices = (depth as u64).max(1); + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + let h = ((height as u64) >> shift).max(1); + let d = ((depth as u64) >> shift).max(1); + w.saturating_mul(h).saturating_mul(d) + } else if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D.0 { + w.saturating_mul(slices) + } else { + let h = ((height as u64) >> shift).max(1); + w.saturating_mul(h).saturating_mul(slices) + } +} + +fn range_texels(width: u64, height: u32, depth: u16, dim: i32, mips: std::ops::Range<u32>) -> u64 { + mips.fold(0u64, |acc, m| acc.saturating_add(mip_texels(width, height, depth, dim, m))) +} + +fn srv_mip_range(res_mips: u32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> std::ops::Range<u32> { + let Some(v) = desc else { return 0..res_mips }; + // SAFETY: each branch reads only the union field named by `v.ViewDimension`. + let (most_detailed, mip_levels, min_lod_clamp) = unsafe { + match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D => { + let s = &v.Anonymous.Texture1D; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => { + let s = &v.Anonymous.Texture1DArray; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE2D => { + let s = &v.Anonymous.Texture2D; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE2DMS | D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY => (0, 1, 0.0), + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + let s = &v.Anonymous.Texture2DArray; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURE3D => { + let s = &v.Anonymous.Texture3D; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURECUBE => { + let s = &v.Anonymous.TextureCube; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => { + let s = &v.Anonymous.TextureCubeArray; + (s.MostDetailedMip, s.MipLevels, s.ResourceMinLODClamp) + } + _ => return 0..0, + } + }; + let end = if mip_levels == 0 || mip_levels == u32::MAX { + res_mips + } else { + most_detailed.saturating_add(mip_levels).min(res_mips) + }; + let clamp_mip = if min_lod_clamp.is_finite() && min_lod_clamp > 0.0 { + min_lod_clamp.floor() as u32 + } else { + 0 + }; + let start = most_detailed.max(clamp_mip).min(end); + start..end +} + +fn srv_slice_range(res_slices: u32, dim: i32, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> std::ops::Range<u32> { + if dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + return 0..1; + } + let limit = res_slices.max(1); + let Some(v) = desc else { return 0..limit }; + // SAFETY: each branch reads only the union field named by `v.ViewDimension`. + let (first, count) = unsafe { + match v.ViewDimension { + D3D12_SRV_DIMENSION_TEXTURE1D | D3D12_SRV_DIMENSION_TEXTURE2D | D3D12_SRV_DIMENSION_TEXTURE2DMS => (0, 1), + D3D12_SRV_DIMENSION_TEXTURE1DARRAY => { + let s = &v.Anonymous.Texture1DArray; + (s.FirstArraySlice, s.ArraySize) + } + D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { + let s = &v.Anonymous.Texture2DArray; + (s.FirstArraySlice, s.ArraySize) + } + D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY => { + let s = &v.Anonymous.Texture2DMSArray; + (s.FirstArraySlice, s.ArraySize) + } + D3D12_SRV_DIMENSION_TEXTURECUBE => (0, 6), + D3D12_SRV_DIMENSION_TEXTURECUBEARRAY => { + let s = &v.Anonymous.TextureCubeArray; + (s.First2DArrayFace, s.NumCubes.saturating_mul(6)) + } + D3D12_SRV_DIMENSION_TEXTURE3D => (0, 1), + _ => return 0..0, + } + }; + let start = first.min(limit); + start..first.saturating_add(count).min(limit) +} + +/// Add `new` to sorted, disjoint half-open ranges and return how many indices were new. +fn union_range(ranges: &mut Vec<std::ops::Range<u32>>, new: std::ops::Range<u32>) -> u32 { + if new.is_empty() { + return 0; + } + let before = ranges.iter().map(|r| r.end - r.start).sum::<u32>(); + let first = ranges.partition_point(|range| range.end < new.start); + let mut end = first; + let mut merged = new; + while end < ranges.len() && ranges[end].start <= merged.end { + merged.start = merged.start.min(ranges[end].start); + merged.end = merged.end.max(ranges[end].end); + end += 1; + } + if first == end { + ranges.insert(first, merged); + } else { + ranges[first] = merged; + ranges.drain(first + 1..end); + } + let after = ranges.iter().map(|r| r.end - r.start).sum::<u32>(); + after - before +} + +struct TexelMeta { + width: u64, + height: u32, + depth: u16, + mips: u16, + dim: i32, + total_texels: u64, + resident_texels: u64, + srv_slices: Vec<Vec<std::ops::Range<u32>>>, + srv_sampled_texels: u64, +} + +impl TexelMeta { + fn from_desc(desc: &D3D12_RESOURCE_DESC, resident: bool) -> Self { + let mips = desc.MipLevels.max(1); + let total_texels = range_texels(desc.Width, desc.Height, desc.DepthOrArraySize, desc.Dimension.0, 0..mips as u32); + TexelMeta { + width: desc.Width, + height: desc.Height, + depth: desc.DepthOrArraySize, + mips, + dim: desc.Dimension.0, + total_texels, + resident_texels: if resident { total_texels } else { 0 }, + srv_slices: vec![Vec::new(); mips as usize], + srv_sampled_texels: 0, + } + } + + fn record_srv(&mut self, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> (bool, u64) { + let first_srv = self.srv_sampled_texels == 0; + let mips = srv_mip_range(self.mips as u32, desc); + let slices = srv_slice_range(self.depth as u32, self.dim, desc); + let mut added = 0u64; + for mip in mips { + let new_slices = union_range(&mut self.srv_slices[mip as usize], slices.clone()) as u64; + if new_slices == 0 { + continue; + } + let per_slice = if self.dim == D3D12_RESOURCE_DIMENSION_TEXTURE3D.0 { + mip_texels(self.width, self.height, self.depth, self.dim, mip) + } else { + mip_texels(self.width, self.height, 1, self.dim, mip) + }; + added = added.saturating_add(per_slice.saturating_mul(new_slices)); + } + self.srv_sampled_texels = self.srv_sampled_texels.saturating_add(added); + (first_srv && added != 0, added) + } +} + +fn record_texel_insert(texels: &Option<TexelMeta>) { + let Some(tm) = texels.as_ref() else { return }; + TEXEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if tm.total_texels > 0 { + TEXEL_STATS[2].fetch_add(tm.total_texels, std::sync::atomic::Ordering::Relaxed); + } + if tm.resident_texels > 0 { + TEXEL_STATS[3].fetch_add(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); + } +} + impl Levels { /// Its tiles that have pages. fn mapped_tiles(&self) -> u64 { @@ -348,6 +1172,9 @@ struct TilePool { free_by_heap: Vec<Vec<u32>>, /// Whether `free_by_heap[h]` must be sorted descending before popping. dirty_sort: Vec<bool>, + /// Fresh-allocation packing class for heap `h`. Shared address pages may give either class + /// live owners here, so this is never proof that a heap is safe to evict. + heap_evictable: Vec<bool>, /// Total free tiles currently available across all heaps. free_total: usize, /// Tiles given back, reusable after `COOL`. @@ -359,42 +1186,46 @@ impl TilePool { TilePool { free_by_heap: Vec::new(), dirty_sort: Vec::new(), + heap_evictable: Vec::new(), free_total: 0, cooling: std::collections::VecDeque::new(), } } - fn add_heap_at(&mut self, slot: u32, pool_pages: u32) { + fn add_heap_at(&mut self, slot: u32, pool_pages: u32, evictable: bool) { let idx = slot as usize; if idx >= self.free_by_heap.len() { self.free_by_heap.resize_with(idx + 1, Vec::new); self.dirty_sort.resize(idx + 1, false); + self.heap_evictable.resize(idx + 1, false); } debug_assert!(self.free_by_heap[idx].is_empty()); self.free_by_heap[idx] = (0..pool_pages).rev().collect(); self.dirty_sort[idx] = false; + self.heap_evictable[idx] = evictable; self.free_total += pool_pages as usize; } /// Reclaim completely empty cooled heaps (`free_by_heap[h].len() == pool_pages`), keeping up - /// to `keep_spare` empty heaps warm so steady-state streaming never thrashes `CreateHeap`. + /// to `keep_spare` empty heaps of each class warm so steady-state streaming never thrashes `CreateHeap`. /// Returns the reclaimed heap indices so the caller can drop their `ID3D12Heap`s. fn reclaim_empty_heaps(&mut self, keep_spare: usize, pool_pages: u32) -> Vec<u32> { let full = pool_pages as usize; - let mut empty: Vec<usize> = self - .free_by_heap - .iter() - .enumerate() - .filter_map(|(h, tiles)| (tiles.len() == full).then_some(h)) - .collect(); - if empty.len() <= keep_spare { - return Vec::new(); - } - let mut reclaimed = Vec::with_capacity(empty.len() - keep_spare); - for h in empty.drain(keep_spare..) { + let mut kept = [0usize; 2]; + let mut reclaimed = Vec::new(); + for h in 0..self.free_by_heap.len() { + if self.free_by_heap[h].len() != full { + continue; + } + let class = self.heap_evictable[h] as usize; + if kept[class] < keep_spare { + kept[class] += 1; + continue; + } self.free_by_heap[h].clear(); self.free_by_heap[h].shrink_to_fit(); self.dirty_sort[h] = false; + self.heap_evictable[h] = false; self.free_total -= full; reclaimed.push(h as u32); } @@ -430,16 +1261,19 @@ impl TilePool { } } - /// Pick the pool heap to take up to `rem` tiles from: + /// Pick a pool heap in the requested allocation class to take up to `rem` tiles from: /// 1. `preferred` if it fits all `rem` tiles (keeps partial-overlap placements on 1 heap), /// 2. otherwise best-fit heap with `len >= rem` (fits the whole texture in 1 heap without /// splitting fuller pools), /// 3. otherwise the heap with the most free tiles (minimizing distinct heaps touched). - fn pick_heap(&self, rem: usize, preferred: Option<u32>) -> Option<usize> { + fn pick_heap(&self, rem: usize, preferred: Option<u32>, evictable: bool) -> Option<usize> { if self.free_total == 0 { return None; } - if let Some(p) = preferred.map(|h| h as usize).filter(|&h| h < self.free_by_heap.len()) { + if let Some(p) = preferred + .map(|h| h as usize) + .filter(|&h| h < self.free_by_heap.len() && self.heap_evictable.get(h).copied() == Some(evictable)) + { if self.free_by_heap[p].len() >= rem { return Some(p); } @@ -447,6 +1281,9 @@ impl TilePool { let mut best_fit: Option<(usize, usize)> = None; let mut largest: Option<(usize, usize)> = None; for (h, tiles) in self.free_by_heap.iter().enumerate() { + if self.heap_evictable.get(h).copied() != Some(evictable) { + continue; + } let len = tiles.len(); if len == 0 { continue; @@ -462,13 +1299,14 @@ impl TilePool { best_fit.or(largest).map(|(h, _)| h) } - /// Allocate `count` tiles, preferring a single heap and ascending contiguous offsets. - /// `make_heap` allocates a new backing pool heap of `pool_pages` tiles when `free_total == 0`. - /// On failure, any tiles already taken are returned untouched. + /// Allocate `count` tiles in one allocation class, preferring a single heap and ascending + /// contiguous offsets. `make_heap` allocates a new backing pool heap when the class has no + /// free tiles. On failure, any tiles already taken are returned untouched. fn take_batch( &mut self, count: usize, preferred: Option<u32>, + evictable: bool, now: std::time::Instant, pool_pages: u32, mut make_heap: impl FnMut() -> Option<u32>, @@ -480,14 +1318,14 @@ impl TilePool { let mut out = Vec::with_capacity(count); while out.len() < count { let rem = count - out.len(); - let h = match self.pick_heap(rem, preferred) { + let h = match self.pick_heap(rem, preferred, evictable) { Some(h) => h, None => { let Some(new_h) = make_heap() else { self.return_tiles(&out); return None; }; - self.add_heap_at(new_h, pool_pages); + self.add_heap_at(new_h, pool_pages, evictable); new_h as usize } }; @@ -579,6 +1417,21 @@ fn keep_spare_pools() -> usize { }) } +/// A superseded texture whose NULL mapping is held until work submitted before it has finished. +struct HeldUnmap { + res: ID3D12Resource, + total: u32, + used: Vec<usize>, + used_extra: Vec<(usize, usize)>, + level_tiles: Vec<(Vec<usize>, Vec<(usize, usize)>)>, + /// Completion marks for every relevant title or upload queue. + marks: Vec<(ID3D12Fence, u64)>, +} + +fn all_marks_complete<F>(marks: &[(F, u64)], mut completed: impl FnMut(&F) -> u64) -> bool { + marks.iter().all(|(fence, value)| completed(fence) >= *value) +} + /// The title's pages of video memory for tiled textures (see the module's comment). struct Pages { queue: ID3D12CommandQueue, @@ -600,6 +1453,10 @@ struct Pages { targets: std::collections::HashMap<usize, Target>, /// queue → the fence value it last waited for waited: std::collections::HashMap<usize, u64>, + /// queue → reusable completion fence and its last signalled value + unmap_fences: std::collections::HashMap<usize, (ID3D12Fence, u64)>, + /// Superseded mappings waiting for all pre-existing queue work to finish. + held_unmaps: Vec<HeldUnmap>, /// cached `reservable()` answers for `(DXGI_FORMAT, SampleCount)` on this device reservable_cache: std::collections::HashMap<(i32, u32), bool>, /// reusable scratch buffers for `map()` @@ -615,6 +1472,19 @@ unsafe impl Send for Pages {} /// device raw pointer → its pages (None inside: tiled tier < 2 on this device) static PAGES: Mutex<std::collections::BTreeMap<usize, Option<Pages>>> = Mutex::new(std::collections::BTreeMap::new()); +fn wait_gates() -> &'static Mutex<HashMap<usize, Arc<Mutex<()>>>> { + static GATES: OnceLock<Mutex<HashMap<usize, Arc<Mutex<()>>>>> = OnceLock::new(); + GATES.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn reserve_page_wait(waited: &mut HashMap<usize, u64>, queue: usize, value: u64) -> bool { + if value == 0 || waited.get(&queue).copied().unwrap_or(0) >= value { + return false; + } + waited.insert(queue, value); + true +} + impl Pages { unsafe fn new(dev: &ID3D12Device) -> Option<Pages> { let mut o = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); @@ -640,6 +1510,8 @@ impl Pages { idle: std::collections::VecDeque::new(), targets: std::collections::HashMap::new(), waited: std::collections::HashMap::new(), + unmap_fences: std::collections::HashMap::new(), + held_unmaps: Vec::new(), reservable_cache: std::collections::HashMap::new(), scratch_heaps: Vec::new(), scratch_flags: Vec::new(), @@ -719,7 +1591,7 @@ impl Pages { ); } self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); } /// Unmap every tile of `res` (`D3D12_TILE_RANGE_FLAG_NULL`) so its unshared tiles can return @@ -744,7 +1616,91 @@ impl Pages { D3D12_TILE_MAPPING_FLAG_NONE, ); self.value += 1; - let _ = self.queue.Signal(&self.fence, self.value); + let _ = super::real::native_queue_signal(&self.queue, &self.fence, self.value); + } + + /// Mark work submitted so far on every active queue. Retirement marks cover queues which + /// stopped accepting signals before this snapshot. Failure is closed: the mapping stays live. + unsafe fn mark_unmap( + &mut self, + dev: &ID3D12Device, + queues: &[ID3D12CommandQueue], + retiring: &[(ID3D12Fence, u64)], + blocked: bool, + ) -> Option<(Vec<(ID3D12Fence, u64)>, Vec<(ID3D12CommandQueue, ID3D12Fence, u64)>)> { + if blocked { + return None; + } + let mut marks = Vec::with_capacity(retiring.len() + queues.len()); + let mut signals = Vec::with_capacity(queues.len()); + for (fence, value) in retiring { + let mut fence_dev: Option<ID3D12Device> = None; + fence.GetDevice(&mut fence_dev).ok()?; + if fence_dev.as_ref().is_some_and(|owner| owner.as_raw() == dev.as_raw()) { + marks.push((fence.clone(), *value)); + } + } + let mut seen = HashSet::new(); + for queue in queues { + let key = queue.as_raw() as usize; + if !seen.insert(key) { + continue; + } + let mut queue_dev: Option<ID3D12Device> = None; + if queue.GetDevice(&mut queue_dev).is_err() || queue_dev.as_ref().is_none_or(|d| d.as_raw() != dev.as_raw()) { + continue; + } + let entry = match self.unmap_fences.entry(key) { + std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(), + std::collections::hash_map::Entry::Vacant(entry) => { + let fence = dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok()?; + entry.insert((fence, 0)) + } + }; + let next = entry.1 + 1; + entry.1 = next; + marks.push((entry.0.clone(), next)); + signals.push((queue.clone(), entry.0.clone(), next)); + } + Some((marks, signals)) + } + + /// Strong fence owners to poll without holding `PAGES`. + fn held_unmap_fences(&self) -> Vec<ID3D12Fence> { + self.held_unmaps.iter().flat_map(|held| held.marks.iter().map(|(fence, _)| fence.clone())).collect() + } + + /// Submit completed NULL mappings and return their resource owners for release after unlock. + unsafe fn release_held_unmaps( + &mut self, + now: std::time::Instant, + mut completed: impl FnMut(&ID3D12Fence) -> u64, + ) -> Vec<ID3D12Resource> { + let mut done = Vec::new(); + for held in std::mem::take(&mut self.held_unmaps) { + if all_marks_complete(&held.marks, &mut completed) { + let key = held.res.as_raw() as usize; + if let Some(levels) = self.targets.get_mut(&key).and_then(|target| target.levels.as_mut()) { + LEVEL_STATS[2].fetch_sub(levels.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); + levels.groups.iter_mut().for_each(|group| group.3 = false); + } + if let Some(tm) = self.targets.get_mut(&key).and_then(|target| target.texels.as_mut()) { + if tm.resident_texels > 0 { + TEXEL_STATS[3].fetch_sub(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); + tm.resident_texels = 0; + } + } + self.unmap(&held.res, held.total); + self.release_tiles(held.used, held.used_extra, now, true); + for (used, used_extra) in held.level_tiles { + self.release_tiles(used, used_extra, now, true); + } + done.push(held.res); + } else { + self.held_unmaps.push(held); + } + } + done } fn release_tiles(&mut self, used: Vec<usize>, used_extra: Vec<(usize, usize)>, now: std::time::Instant, immediate_cool: bool) { @@ -782,12 +1738,15 @@ impl Pages { /// Acquire/share all `total` tiles for `res` at `va` and map them on the `Pages` queue. unsafe fn bind(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option<u64>, total: u32) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { - self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize) + self.bind_range(dev, res, va, console_bytes, total, 0, 0..total as usize, false) } /// `bind` for the tiles `range` of the resource's `total`, which start at subresource `sub`. #[allow(clippy::too_many_arguments)] - unsafe fn bind_range(&mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, console_bytes: Option<u64>, total: u32, sub: u32, range: std::ops::Range<usize>) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { + unsafe fn bind_range( + &mut self, dev: &ID3D12Device, res: &ID3D12Resource, va: usize, + console_bytes: Option<u64>, total: u32, sub: u32, range: std::ops::Range<usize>, evictable: bool, + ) -> Option<(Vec<usize>, Vec<(usize, usize)>)> { let (first, own) = (total > 0).then(|| owned_pages(va, console_bytes, total as usize)).flatten()?; let now = std::time::Instant::now(); self.sweep(now); @@ -809,7 +1768,7 @@ impl Pages { let pools = &mut self.pools; let pool = &mut self.pool; - let fresh = pool.take_batch(missing, preferred, now, POOL_PAGES, || { + let fresh = pool.take_batch(missing, preferred, evictable, now, POOL_PAGES, || { let heap = alloc_pool_heap(dev)?; Some(pools.push_heap(heap)) })?; @@ -859,6 +1818,20 @@ impl Pages { } } +/// Poll a snapshot without `PAGES`; a held unmap added meanwhile has no observation and stays held. +unsafe fn held_unmap_completions(dev_key: usize) -> Vec<(ID3D12Fence, u64)> { + let mut fences = { + let pages = PAGES.lock().unwrap(); + pages.get(&dev_key).and_then(Option::as_ref).map(Pages::held_unmap_fences).unwrap_or_default() + }; + fences.sort_unstable_by_key(|fence| fence.as_raw() as usize); + fences.dedup_by_key(|fence| fence.as_raw() as usize); + fences.into_iter().map(|fence| { + let value = fence.GetCompletedValue(); + (fence, value) + }).collect() +} + /// The ranges of one UpdateTileMappings call for pool heap `heap` over a resource whose overall /// tile i goes to `tiles[i]`: (mapped, tile offset in the heap, count) – runs of consecutive /// tiles of the heap, and skipped runs for tiles of other heaps. @@ -1003,6 +1976,7 @@ unsafe fn place_on_pages( dev.GetResourceTiling(res, Some(&mut total), None, None, None, 0, std::ptr::null_mut()); None }; + let texels = (!require_aligned && super::memory_report::enabled()).then(|| TexelMeta::from_desc(desc, levels.is_none())); let bound = { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { @@ -1010,10 +1984,12 @@ unsafe fn place_on_pages( // nothing mapped yet: a level gets its pages with its first texels (`map_levels`) LEVEL_STATS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_add(total as u64, std::sync::atomic::Ordering::Relaxed); - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels }); + record_texel_insert(&texels); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used: Vec::new(), used_extra: Vec::new(), levels, texels }); true } else if let Some((used, used_extra)) = pages.bind(dev, res, va, console_bytes, total) { - pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None }); + record_texel_insert(&texels); + pages.targets.insert(raw as usize, Target { va, console_bytes, total, mapped: true, used, used_extra, levels: None, texels }); true } else { false @@ -1031,29 +2007,52 @@ unsafe fn place_on_pages( Some(hr) } -/// Unmap a placed texture superseded by a placement with a different address range, returning its -/// unshared tiles (`extra_pages` and unshared tail pages) to the cooling pool immediately. +/// Hold a superseded texture's mapping until work submitted before this call has finished. +/// Polling completion on the CPU avoids a dependency from the mapping queue back to a title queue, +/// which may itself already be waiting for later mapping work. pub(super) unsafe fn unmap_superseded(res: &ID3D12Resource) { + let mut dev: Option<ID3D12Device> = None; + if res.GetDevice(&mut dev).is_err() { + return; + } + let Some(dev) = dev else { return }; + let dev_key = dev.as_raw() as usize; + let observed = held_unmap_completions(dev_key); + let mut completion = super::present::queue_completion_snapshot(); + completion.active.extend(super::title_textures::upload_queues()); let key = res.as_raw() as usize; - let mut g = PAGES.lock().unwrap(); - let now = std::time::Instant::now(); - for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.get_mut(&key) else { continue }; - if !t.mapped { + let (done, signals) = { + let mut g = PAGES.lock().unwrap(); + let Some(Some(pages)) = g.get_mut(&dev_key) else { return }; + if !pages.targets.get(&key).is_some_and(|target| target.mapped) { return; } - let total = t.total; - let used = std::mem::take(&mut t.used); - let used_extra = std::mem::take(&mut t.used_extra); - t.mapped = false; - if let Some(l) = t.levels.as_mut() { - LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); - l.groups.iter_mut().for_each(|g| g.3 = false); + let Some((marks, signals)) = pages.mark_unmap(&dev, &completion.active, &completion.retiring, completion.blocked) else { + crate::xlog_warn!("D3D12.X: could not guard a superseded texture unmap; keeping its mapping"); + return; + }; + let Some(target) = pages.targets.get_mut(&key) else { return }; + let held = HeldUnmap { + res: res.clone(), + total: target.total, + used: std::mem::take(&mut target.used), + used_extra: std::mem::take(&mut target.used_extra), + level_tiles: take_level_tiles(target.levels.as_mut()), + marks, + }; + target.mapped = false; + pages.held_unmaps.push(held); + let done = pages.release_held_unmaps(std::time::Instant::now(), |fence| { + observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) + }); + (done, signals) + }; + for (queue, fence, value) in signals { + if super::real::native_queue_signal(&queue, &fence, value).is_err() { + crate::xlog_warn!("D3D12.X: could not signal a superseded texture unmap marker; keeping its mapping"); } - pages.unmap(res, total); - pages.release_tiles(used, used_extra, now, true); - return; } + drop(done); } /// Re-map a previously unmapped placed texture when the newer placement shadowing it is released. @@ -1072,6 +2071,26 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { if mapped { return true; } + // A deferred unmap never changed the resource's tiles. Cancel it and restore their ownership. + if let Some(index) = pages.held_unmaps.iter().position(|held| held.res.as_raw() as usize == key) { + let held = pages.held_unmaps.swap_remove(index); + if let Some(target) = pages.targets.get_mut(&key) { + target.used = held.used; + target.used_extra = held.used_extra; + if let Some(levels) = target.levels.as_mut().filter(|levels| levels.group_tiles.len() == held.level_tiles.len()) { + levels.group_tiles = held.level_tiles; + } else { + for (used, used_extra) in held.level_tiles { + target.used.extend(used); + target.used_extra.extend(used_extra); + } + } + target.mapped = true; + } + drop(g); + drop(held.res); + return true; + } // (lazy levels: they get their pages again with their next texels) if let Some(t) = pages.targets.get_mut(&key).filter(|t| t.levels.is_some()) { t.mapped = true; @@ -1084,6 +2103,12 @@ pub(super) unsafe fn remap_if_unmapped(res: &ID3D12Resource) -> bool { t.used = used; t.used_extra = used_extra; t.mapped = true; + if let Some(tm) = t.texels.as_mut() { + if tm.resident_texels == 0 && tm.total_texels > 0 { + tm.resident_texels = tm.total_texels; + TEXEL_STATS[3].fetch_add(tm.total_texels, std::sync::atomic::Ordering::Relaxed); + } + } } true } @@ -1093,14 +2118,30 @@ fn forget_pages(resource: usize) { let mut g = PAGES.lock().unwrap(); let now = std::time::Instant::now(); for pages in g.values_mut().flatten() { - let Some(t) = pages.targets.remove(&resource) else { continue }; + let Some(mut t) = pages.targets.remove(&resource) else { continue }; if let Some(l) = &t.levels { LEVEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[1].fetch_sub(t.total as u64, std::sync::atomic::Ordering::Relaxed); LEVEL_STATS[2].fetch_sub(l.mapped_tiles(), std::sync::atomic::Ordering::Relaxed); } + if let Some(tm) = &t.texels { + TEXEL_STATS[0].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + if tm.srv_sampled_texels != 0 { + TEXEL_STATS[1].fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + TEXEL_STATS[4].fetch_sub(tm.srv_sampled_texels, std::sync::atomic::Ordering::Relaxed); + } + if tm.total_texels > 0 { + TEXEL_STATS[2].fetch_sub(tm.total_texels, std::sync::atomic::Ordering::Relaxed); + } + if tm.resident_texels > 0 { + TEXEL_STATS[3].fetch_sub(tm.resident_texels, std::sync::atomic::Ordering::Relaxed); + } + } if t.mapped { pages.release_tiles(t.used, t.used_extra, now, false); + for (used, used_extra) in take_level_tiles(t.levels.as_mut()) { + pages.release_tiles(used, used_extra, now, false); + } } return; } @@ -1132,6 +2173,17 @@ impl<H, F: Clone> RetireQueue<H, F> { Vec::new() } + /// Strong owners of every fence whose completion can change a sweep decision. The caller + /// polls them after dropping the retirement-state lock, then rechecks the current batches. + fn completion_fences(&self) -> Vec<F> { + let mut fences: Vec<_> = self.fences.values().map(|(fence, _)| fence.clone()).collect(); + for batch in &self.batches { + fences.extend(batch.unmap_mark.as_ref().map(|(fence, _)| fence.clone())); + fences.extend(batch.marks.iter().map(|(fence, _)| fence.clone())); + } + fences + } + /// Reap completed batches and prune dead-queue fences once completed; caller drops outside locks. fn sweep_with(&mut self, live_queues: &HashSet<usize>, mut completed: impl FnMut(&F) -> u64) -> (Vec<RetiringBatch<H, F>>, Vec<F>) { let (mut done, mut kept) = (Vec::new(), Vec::new()); @@ -1143,13 +2195,56 @@ impl<H, F: Clone> RetireQueue<H, F> { let pruned = stale.into_iter().filter_map(|k| self.fences.remove(&k).map(|(f, _)| f)).collect(); (done, pruned) } + + /// In-flight batches own their marks; only the address-keyed reusable fence is removed. + fn forget_queue(&mut self, queue: usize) -> Option<F> { + self.fences.remove(&queue).map(|(fence, _)| fence) + } +} + +fn observed_completion<F>(observed: &[(F, u64)], fence: &F, mut same: impl FnMut(&F, &F) -> bool) -> u64 { + observed.iter().find_map(|(known, value)| same(known, fence).then_some(*value)).unwrap_or(0) } unsafe impl Send for RetireQueue<ID3D12Heap, ID3D12Fence> {} -static RETIRE: Mutex<Option<std::collections::HashMap<usize, RetireQueue<ID3D12Heap, ID3D12Fence>>>> = Mutex::new(None); +type DeviceRetire = std::sync::Arc<Mutex<RetireQueue<ID3D12Heap, ID3D12Fence>>>; + +/// Per-device retirement states. The registry is held only while acquiring a strong state lease; +/// fence creation, queue signaling, polling, and COM destruction never hold it. +static RETIRE: Mutex<Option<std::collections::HashMap<usize, DeviceRetire>>> = Mutex::new(None); static RETIRING_BATCHES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); +fn device_retire_state(dev_key: usize) -> DeviceRetire { + RETIRE + .lock() + .unwrap() + .get_or_insert_with(std::collections::HashMap::new) + .entry(dev_key) + .or_insert_with(|| std::sync::Arc::new(Mutex::new(RetireQueue::new()))) + .clone() +} + +/// Remove raw queue-address state before a retired queue's final owner can be released. Fence +/// objects are extracted from both locks and dropped afterward; retirement batches keep clones. +pub(super) fn forget_queue(id: super::present::QueueId) { + let queue = id.raw(); + let page_fences = { + let mut pages = PAGES.lock().unwrap(); + pages.values_mut().flatten().filter_map(|pages| { + pages.waited.remove(&queue); + pages.unmap_fences.remove(&queue) + }).collect::<Vec<_>>() + }; + let wait_gate = wait_gates().lock().unwrap().remove(&queue); + let states: Vec<_> = RETIRE.lock().unwrap().as_ref().into_iter().flat_map(|devices| devices.values().cloned()).collect(); + let gone: Vec<_> = states + .iter() + .filter_map(|state| state.lock().unwrap().forget_queue(queue)) + .collect(); + drop((page_fences, gone, wait_gate)); +} + /// Collect all known live command queues belonging to `dev_key` (deduplicated by raw ptr). unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueue>) -> Vec<(usize, ID3D12CommandQueue)> { let (mut seen, mut out) = (HashSet::new(), Vec::new()); @@ -1160,9 +2255,8 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu out.push((key, q)); } }; - for raw in super::present::known_queues() { - let raw = raw as *mut c_void; - if let Some(q) = ID3D12CommandQueue::from_raw_borrowed(&raw) { add(q.clone()); } + for q in super::present::active_queues_held() { + add(q); } for q in extra.into_iter().cloned().chain(super::title_textures::upload_queues()).chain(super::sparse::queue()) { add(q); @@ -1175,17 +2269,36 @@ unsafe fn collect_device_queues(dev_key: usize, extra: Option<&ID3D12CommandQueu unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_reclaimed: Vec<ID3D12Heap>, unmap_mark: Option<(ID3D12Fence, u64)>, extra_queue: Option<&ID3D12CommandQueue>) { let queues = collect_device_queues(dev_key, extra_queue); let live_keys: HashSet<usize> = queues.iter().map(|&(k, _)| k).collect(); - let _drop_outside_locks = { - let mut guard = RETIRE.lock().unwrap(); - let map = guard.get_or_insert_with(std::collections::HashMap::new); - if newly_reclaimed.is_empty() && !map.contains_key(&dev_key) { return; } - let rq = map.entry(dev_key).or_insert_with(RetireQueue::new); + let state = if newly_reclaimed.is_empty() { + let registry = RETIRE.lock().unwrap(); + let Some(state) = registry.as_ref().and_then(|map| map.get(&dev_key)).cloned() else { return }; + state + } else { + device_retire_state(dev_key) + }; + let (immediate, mut probes) = { + let mut rq = state.lock().unwrap(); let before = rq.batches.len(); - let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| q.Signal(f, v).is_ok()); - let (done, pruned) = rq.sweep_with(&live_keys, |f| f.GetCompletedValue()); - RETIRING_BATCHES.fetch_add(rq.batches.len().wrapping_sub(before), std::sync::atomic::Ordering::AcqRel); - (immediate, done, pruned) + let immediate = rq.retire_with(newly_reclaimed, unmap_mark, &queues, || dev.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAG_NONE).ok(), |q, f, v| super::real::native_queue_signal(q, f, v).is_ok()); + RETIRING_BATCHES.fetch_add(rq.batches.len() - before, std::sync::atomic::Ordering::AcqRel); + (immediate, rq.completion_fences()) + }; + // Deduplication and every COM call/drop happen without RETIRE held. The strong snapshots keep + // raw addresses from being reused while results are identified by their exact fence object. + probes.sort_unstable_by_key(|fence| fence.as_raw() as usize); + probes.dedup_by_key(|fence| fence.as_raw() as usize); + let observed: Vec<_> = probes.into_iter().map(|fence| { + let completed = fence.GetCompletedValue(); + (fence, completed) + }).collect(); + let (done, pruned) = { + let mut rq = state.lock().unwrap(); + rq.sweep_with(&live_keys, |fence| { + observed_completion(&observed, fence, |known, current| known.as_raw() == current.as_raw()) + }) }; + RETIRING_BATCHES.fetch_sub(done.len(), std::sync::atomic::Ordering::AcqRel); + drop((immediate, done, pruned, observed)); } /// Before GPU work on `queue`: have it wait for every tile mapping made so far on its device, @@ -1193,6 +2306,9 @@ unsafe fn retire_heaps_and_sweep(dev: &ID3D12Device, dev_key: usize, newly_recla /// per second per device) retire completely empty 64 MiB VRAM pool heaps and idle arenas behind /// per-queue GPU fence signals across all live queues on the device. pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { + let queue_key = queue.as_raw() as usize; + let wait_gate = wait_gates().lock().unwrap().entry(queue_key).or_default().clone(); + let _queue_serial = wait_gate.lock().unwrap(); let mut dev: Option<ID3D12Device> = None; if queue.GetDevice(&mut dev).is_err() { return; @@ -1200,17 +2316,21 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { let Some(dev) = dev else { return }; let dev_key = dev.as_raw() as usize; let now = std::time::Instant::now(); + let unmap_completions = held_unmap_completions(dev_key); let mut newly_reclaimed = Vec::new(); let mut do_reclaim = false; let mut unmap_mark: Option<(ID3D12Fence, u64)> = None; + let mut completed_unmaps = Vec::new(); + let mut wait = None; { let mut g = PAGES.lock().unwrap(); if let Some(Some(pages)) = g.get_mut(&dev_key) { - let key = queue.as_raw() as usize; - if pages.waited.get(&key).copied().unwrap_or(0) < pages.value { - let _ = queue.Wait(&pages.fence, pages.value); - super::list_x::note_internal_wait(key, "texture page mappings", &pages.fence, pages.value); - pages.waited.insert(key, pages.value); + completed_unmaps = pages.release_held_unmaps(now, |fence| { + observed_completion(&unmap_completions, fence, |known, current| known.as_raw() == current.as_raw()) + }); + let value = pages.value; + if reserve_page_wait(&mut pages.waited, queue_key, value) { + wait = Some((pages.fence.clone(), value)); } if now.duration_since(pages.last_reclaim) >= std::time::Duration::from_secs(1) { pages.last_reclaim = now; @@ -1222,19 +2342,70 @@ pub(super) unsafe fn before_execute(queue: &ID3D12CommandQueue) { } } } + if let Some((fence, value)) = wait { + let _ = super::real::native_queue_wait(queue, &fence, value); + super::list_x::note_internal_wait(queue_key, "texture page mappings", &fence, value); + } if do_reclaim { newly_reclaimed.extend(ARENAS.lock().unwrap().sweep_dropped_for(dev_key, now)); } if do_reclaim || !newly_reclaimed.is_empty() || RETIRING_BATCHES.load(std::sync::atomic::Ordering::Acquire) > 0 { retire_heaps_and_sweep(&dev, dev_key, newly_reclaimed, unmap_mark, Some(queue)); } + drop(completed_unmaps); } #[cfg(test)] pub(super) static VRAM_TEST_LOCK: Mutex<()> = Mutex::new(()); +/// A tile mapping on `dev`'s page queue, as `map` leaves it (the fence advanced and signalled +/// there): the value a queue must wait for before work that uses the pages. None: no pages on +/// this device (no tiled resources). +#[cfg(test)] +pub(super) unsafe fn note_mapping_for_test(dev: &ID3D12Device) -> Option<u64> { + let mut g = PAGES.lock().unwrap(); + let pages = g.entry(dev.as_raw() as usize).or_insert_with(|| Pages::new(dev)).as_mut()?; + pages.value += 1; + super::real::native_queue_signal(&pages.queue, &pages.fence, pages.value).ok()?; + Some(pages.value) +} + +/// The page mapping value `queue` was last made to wait for on `dev` (`before_execute`). +#[cfg(test)] +pub(super) fn waited_for_test(dev: usize, queue: usize) -> u64 { + let g = PAGES.lock().unwrap(); + g.get(&dev).and_then(|p| p.as_ref()).and_then(|p| p.waited.get(&queue).copied()).unwrap_or(0) +} + /// Tile identities of one mapped resource: title pages, then extra pages. /// A device-wide byte count also falls when unrelated idle pages are swept. +#[cfg(test)] +fn target_page_keys(target: &Target) -> (Vec<usize>, Vec<(usize, usize)>) { + let mut used = target.used.clone(); + let mut extra = target.used_extra.clone(); + if let Some(levels) = &target.levels { + for (level_used, level_extra) in &levels.group_tiles { + used.extend(level_used); + extra.extend(level_extra); + } + } + (used, extra) +} + +#[cfg(test)] +fn target_tiles(pages: &Pages, target: &Target) -> Option<(Vec<Tile>, Vec<Tile>)> { + let (used, extra) = target_page_keys(target); + let used = used + .iter() + .map(|key| pages.pages.get(key).map(|page| page.tile)) + .collect::<Option<Vec<_>>>()?; + let extra = extra + .iter() + .map(|key| pages.extra_pages.get(key).map(|page| page.tile)) + .collect::<Option<Vec<_>>>()?; + (used.len() + extra.len() == target.total as usize).then_some((used, extra)) +} + #[cfg(test)] pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u32, u32)>, Vec<(u32, u32)>)> { let g = PAGES.lock().unwrap(); @@ -1243,16 +2414,21 @@ pub(super) fn mapped_tiles_for(device: usize, resource: usize) -> Option<(Vec<(u if !target.mapped { return None; } - let used = target.used.iter().map(|key| p.pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - let extra = target.used_extra.iter().map(|key| p.extra_pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - (used.len() + extra.len() == target.total as usize).then_some((used, extra)) + target_tiles(p, target) } -#[cfg(test)] pub(super) fn page_bytes_for(device: usize) -> (usize, usize) { let g = PAGES.lock().unwrap(); let Some(Some(p)) = g.get(&device) else { return (0, 0) }; - ((p.pages.len() + p.extra_pages.len()) * PAGE, p.pools.len() * POOL_PAGES as usize * PAGE) + let pages = p.pages.len().saturating_add(p.extra_pages.len()).saturating_mul(PAGE); + let pools = p.pools.len().saturating_mul(POOL_PAGES as usize).saturating_mul(PAGE); + (pages, pools) +} + +#[cfg(test)] +fn held_unmaps_for(device: usize) -> usize { + let g = PAGES.lock().unwrap(); + g.get(&device).and_then(Option::as_ref).map_or(0, |pages| pages.held_unmaps.len()) } /// Pool/tile identities used by one mapped resource: title pages, then extra pages. @@ -1263,9 +2439,7 @@ pub(super) fn tile_mappings_for(device: usize, resource: usize) -> Option<(Vec<( let p = g.get(&device)?.as_ref()?; let target = p.targets.get(&resource)?; if !target.mapped { return None; } - let used = target.used.iter().map(|key| p.pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - let extra = target.used_extra.iter().map(|key| p.extra_pages.get(key).map(|page| page.tile)).collect::<Option<Vec<_>>>()?; - (used.len() + extra.len() == target.total as usize).then_some((used, extra)) + target_tiles(p, target) } /// (bytes of pages in use by tiled textures, bytes of pool heaps) – `XCL_ACTIVITY` @@ -1335,12 +2509,20 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> let Some(dev) = ID3D12Device::from_raw_borrowed(&d) else { return Vec::new() }; let mut fresh = Vec::new(); for (k, sub, first, n, levels) in todo { - let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize) else { continue }; + let Some((used, used_extra)) = pages.bind_range(dev, res, va, console_bytes, total, sub, first as usize..(first + n) as usize, false) else { continue }; let Some(t) = pages.targets.get_mut(&key) else { return fresh }; - t.used.extend(used); - t.used_extra.extend(used_extra); if let Some(l) = t.levels.as_mut() { l.groups[k].3 = true; + l.group_tiles[k].0.extend(used); + l.group_tiles[k].1.extend(used_extra); + } + if let Some(tm) = t.texels.as_mut() { + let added = range_texels(tm.width, tm.height, tm.depth, tm.dim, levels.clone()); + let delta = tm.total_texels.saturating_sub(tm.resident_texels).min(added); + if delta > 0 { + tm.resident_texels += delta; + TEXEL_STATS[3].fetch_add(delta, std::sync::atomic::Ordering::Relaxed); + } } LEVEL_STATS[2].fetch_add(n as u64, std::sync::atomic::Ordering::Relaxed); let groups = LEVEL_STATS[3].fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; @@ -1355,6 +2537,26 @@ pub(super) unsafe fn map_levels(res: &ID3D12Resource, levels: Option<&[u32]>) -> Vec::new() } +/// Record which mip levels of placed sampled texture `resource` an SRV can sample. +pub(super) fn note_srv(resource: usize, desc: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) { + if !super::memory_report::enabled() || resource == 0 || !is_placed_texture(resource) { + return; + } + let mut g = PAGES.lock().unwrap(); + for pages in g.values_mut().flatten() { + let Some(t) = pages.targets.get_mut(&resource) else { continue }; + let Some(tm) = t.texels.as_mut() else { return }; + let (first_srv, added) = tm.record_srv(desc); + if first_srv { + TEXEL_STATS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + if added > 0 { + TEXEL_STATS[4].fetch_add(added, std::sync::atomic::Ordering::Relaxed); + } + return; + } +} + /// Whether `resource` is a texture whose levels get their pages one by one (`map_levels`). pub(super) fn has_lazy_levels(resource: usize) -> bool { PAGES.lock().unwrap().values().flatten().any(|p| p.targets.get(&resource).is_some_and(|t| t.levels.is_some())) @@ -1420,6 +2622,673 @@ pub unsafe fn place(this: *mut c_void, va: usize, desc: &D3D12_RESOURCE_DESC, st #[cfg(test)] mod tests { use super::*; + + #[derive(Clone)] + struct FakeReceipt { + fence: Arc<std::sync::atomic::AtomicU64>, + value: u64, + } + + fn fake_complete(receipt: &FakeReceipt) -> bool { + receipt.fence.load(std::sync::atomic::Ordering::Relaxed) >= receipt.value + } + + #[test] + fn shared_view_epochs_cancel_retire_and_remain_monotonic() { + let mut epochs = SharedViewEpochs::new(); + let cancelled = epochs.reserve(); + let retiring = epochs.reserve(); + assert!(cancelled.0 < retiring.0); + epochs.cancel(cancelled); + + let fence = Arc::new(std::sync::atomic::AtomicU64::new(0)); + epochs.attach(retiring, FakeReceipt { fence: Arc::clone(&fence), value: 3 }); + assert!(!epochs.quiescent(fake_complete)); + fence.store(3, std::sync::atomic::Ordering::Relaxed); + assert!(epochs.quiescent(fake_complete)); + assert!(epochs.reserve().0 > retiring.0, "retirement never reuses an epoch identity"); + } + + #[test] + fn reused_queue_address_cannot_retire_an_old_epoch() { + let mut epochs = SharedViewEpochs::new(); + let old_epoch = epochs.reserve(); + let old_generation_fence = Arc::new(std::sync::atomic::AtomicU64::new(0)); + epochs.attach(old_epoch, FakeReceipt { fence: Arc::clone(&old_generation_fence), value: 7 }); + + // A new queue generation at the same numeric address owns another fence. Its progress + // cannot satisfy the strong fence owner retained by the old epoch's receipt. + let replacement_generation_fence = Arc::new(std::sync::atomic::AtomicU64::new(99)); + assert_eq!(replacement_generation_fence.load(std::sync::atomic::Ordering::Relaxed), 99); + assert!(!epochs.quiescent(fake_complete)); + old_generation_fence.store(7, std::sync::atomic::Ordering::Relaxed); + assert!(epochs.quiescent(fake_complete)); + } + + #[test] + fn untracked_shared_view_epoch_never_becomes_quiescent() { + let mut epochs = SharedViewEpochs::<FakeReceipt>::new(); + let epoch = epochs.reserve(); + epochs.poison(epoch); + assert!(!epochs.quiescent(fake_complete)); + } + + #[test] + fn disabled_tracking_cannot_authorize_descriptor_mutation() { + let epochs = Mutex::new(SharedViewEpochs::<FakeReceipt>::new()); + let mut ran = false; + assert!(with_quiescent_epochs(false, &epochs, fake_complete, || ran = true).is_none()); + assert!(!ran); + } + + #[test] + fn quiescent_mutation_excludes_new_reservations() { + let epochs = Arc::new(Mutex::new(SharedViewEpochs::<FakeReceipt>::new())); + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (release_tx, release_rx) = std::sync::mpsc::channel(); + let mutation_epochs = Arc::clone(&epochs); + let mutation = std::thread::spawn(move || { + with_quiescent_epochs(true, &mutation_epochs, fake_complete, || { + entered_tx.send(()).unwrap(); + release_rx.recv().unwrap(); + }) + }); + entered_rx.recv().unwrap(); + + let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); + let (reserved_tx, reserved_rx) = std::sync::mpsc::channel(); + let reserve_epochs = Arc::clone(&epochs); + let reserve = std::thread::spawn(move || { + attempted_tx.send(()).unwrap(); + let epoch = reserve_epochs.lock().unwrap().reserve(); + reserved_tx.send(epoch).unwrap(); + }); + attempted_rx.recv().unwrap(); + assert!(reserved_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err()); + release_tx.send(()).unwrap(); + assert!(mutation.join().unwrap().is_some()); + assert_eq!(reserved_rx.recv().unwrap(), SharedViewEpoch(1)); + reserve.join().unwrap(); + } + + fn tracked_entry(resource: usize, pc_srv: u64) -> TrackedSrv { + let mut words = [0u32; 8]; + words[0] = pc_srv as u32; + words[1] = resource as u32; + words[3] = 9 << 28; + TrackedSrv { + generation: 0, device: 7, resource, pc_srv, shared_srv: pc_srv + 1, + index: pc_srv as u32, desc: Some(D3D12_SHADER_RESOURCE_VIEW_DESC::default()), words, + } + } + + fn srv_slot(heap_generation: u64, slot: u32) -> SrvSlot { + SrvSlot { heap_generation, slot } + } + + struct MutationOwner(Arc<std::sync::atomic::AtomicUsize>); + + impl Drop for MutationOwner { + fn drop(&mut self) { + assert!(TRACKED_SRV_WRITES.try_lock().is_ok(), "strong owner dropped under WRITE"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "strong owner dropped under tracker lock"); + self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + + struct UnwindMutationOwner { + drops: Arc<std::sync::atomic::AtomicUsize>, + unlocked: Arc<std::sync::atomic::AtomicUsize>, + } + + impl Drop for UnwindMutationOwner { + fn drop(&mut self) { + use std::sync::TryLockError; + let available = |mutex: &'static Mutex<()>| match mutex.try_lock() { + Ok(guard) => { drop(guard); true } + Err(TryLockError::Poisoned(error)) => { drop(error.into_inner()); true } + Err(TryLockError::WouldBlock) => false, + }; + let write = available(&TRACKED_SRV_WRITES) as usize; + let tracker = match TRACKED_SRVS.try_lock() { + Ok(guard) => { drop(guard); true } + Err(TryLockError::Poisoned(error)) => { drop(error.into_inner()); true } + Err(TryLockError::WouldBlock) => false, + } as usize; + self.unlocked.fetch_or(write | tracker << 1, std::sync::atomic::Ordering::Relaxed); + self.drops.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + } + + fn begin_mutation_test(entry: TrackedSrv, slot: SrvSlot) -> (u64, [u32; 8]) { + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(entry)); + let current = tracked.by_slot[&slot]; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + (current.generation, current.words) + } + + fn end_mutation_test() { + TRACKED_SRVS.lock().unwrap().take(); + *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn exact_srv_mutation_revalidates_then_drops_owners_outside_inner_locks() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(60, 2); + let (generation, words) = begin_mutation_test(tracked_entry(0x6010, 0xA0), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| Some((snapshot, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops)))), + |_| Some(words), + |entry, _, _| { + assert_eq!(entry.resource, 0x6010); + assert!(SHARED_VIEW_EPOCHS.try_lock().is_err(), "epoch was not held outermost"); + assert!(TRACKED_SRV_WRITES.try_lock().is_err(), "WRITE was not held for mutation"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "tracker lock crossed mutation"); + 17 + }, + ); + assert_eq!(result, Some(17)); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + end_mutation_test(); + } + + #[test] + fn exact_srv_mutation_rejects_a_changed_generation_without_removing_it() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(61, 1); + let (generation, words) = begin_mutation_test(tracked_entry(0x6110, 0xA4), slot); + let old = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| { + // Model a hooked overwrite after the owners were acquired but before WRITE. + TRACKED_SRVS.lock().unwrap().as_mut().unwrap().write(slot, Some(tracked_entry(0x6120, 0xA4))); + Some((old, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops)))) + }, + |_| Some(words), + |_, _, _| panic!("stale mutation ran"), + ); + assert_eq!(result, None); + let newer = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + assert_ne!(newer.generation, generation); + assert_eq!(newer.resource, 0x6120); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + end_mutation_test(); + } + + #[test] + fn exact_srv_mutation_forgets_raw_mismatch_or_missing_heap_backing() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + for missing in [false, true] { + let slot = srv_slot(62 + missing as u64, 0); + let (generation, words) = begin_mutation_test(tracked_entry(0x6210, 0xA8), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut changed = words; + changed[5] ^= 1; + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| Some((snapshot, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops)))), + |_| (!missing).then_some(changed), + |_, _, _| panic!("invalid raw descriptor mutation ran"), + ); + assert_eq!(result, None); + assert!(!TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot.contains_key(&slot)); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + end_mutation_test(); + } + } + + #[test] + fn exact_srv_mutation_fails_closed_when_resource_or_heap_lease_is_gone() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(64, 0); + let (generation, _) = begin_mutation_test(tracked_entry(0x6410, 0xAC), slot); + let result = with_exact_tracked_srv_mutation_on( + slot, + generation, + |_, _| None::<(TrackedSrv, (), ())>, + |_| panic!("observed words without strong owners"), + |_, _, _| panic!("mutation ran without strong owners"), + ); + assert_eq!(result, None); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot.contains_key(&slot)); + end_mutation_test(); + } + + #[test] + fn exact_srv_batch_deduplicates_and_revalidates_mixed_candidates_once() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + *SHARED_VIEW_EPOCHS.lock().unwrap() = SharedViewEpochs::new(); + let (a, b, c, d, e) = ( + srv_slot(70, 0), srv_slot(70, 1), srv_slot(70, 2), srv_slot(70, 3), srv_slot(70, 4), + ); + let mut tracked = TrackedSrvs::default(); + for (slot, resource, pc) in [(a, 0xA010, 0xB0), (b, 0xB010, 0xB4), (c, 0xC010, 0xB8), (d, 0xD010, 0xBC), (e, 0xE010, 0xC0)] { + tracked.write(slot, Some(tracked_entry(resource, pc))); + } + let old_b = tracked.by_slot[&b]; + let snapshots = tracked.by_slot.clone(); + tracked.write(b, Some(tracked_entry(0xB020, 0xB4))); + let newer_b = tracked.by_slot[&b]; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let candidates = [ + (a, snapshots[&a].generation), + (a, snapshots[&a].generation), + (b, old_b.generation), + (c, snapshots[&c].generation), + (d, snapshots[&d].generation), + (e, snapshots[&e].generation), + ]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut lease_calls = Vec::new(); + let mut observations = 0; + let result = with_exact_tracked_srv_mutations_on( + &candidates, + |slot, generation| { + assert!(SHARED_VIEW_EPOCHS.try_lock().is_err(), "lease escaped the batch epoch"); + assert!(TRACKED_SRV_WRITES.try_lock().is_ok(), "WRITE was taken while leasing owners"); + lease_calls.push((slot, generation)); + (slot != d).then(|| { + let snapshot = snapshots[&slot]; + (snapshot, MutationOwner(Arc::clone(&drops)), MutationOwner(Arc::clone(&drops))) + }) + }, + |slots| { + observations += 1; + assert!(TRACKED_SRV_WRITES.try_lock().is_err(), "raw words were observed outside WRITE"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "tracker lock crossed raw observation"); + assert_eq!(slots, &[(70, 0), (70, 1), (70, 2), (70, 4)]); + let mut changed_c = snapshots[&c].words; + changed_c[6] ^= 1; + vec![Some(snapshots[&a].words), Some(old_b.words), Some(changed_c), Some(snapshots[&e].words)] + }, + |valid| { + assert!(SHARED_VIEW_EPOCHS.try_lock().is_err(), "batch mutation escaped its epoch"); + assert!(TRACKED_SRV_WRITES.try_lock().is_err(), "batch mutation escaped WRITE"); + assert!(TRACKED_SRVS.try_lock().is_ok(), "tracker lock crossed batch mutation"); + assert_eq!(valid.iter().map(|entry| entry.entry.resource).collect::<Vec<_>>(), vec![0xA010, 0xE010]); + // Touch both strong-owner references: the batch exposes only validated owners. + assert!(valid.iter().all(|entry| Arc::ptr_eq(&entry.resource.0, &entry.heap.0))); + 29 + }, + ); + assert_eq!(result, Some(29)); + assert_eq!(lease_calls, vec![ + (a, snapshots[&a].generation), (b, old_b.generation), (c, snapshots[&c].generation), + (d, snapshots[&d].generation), (e, snapshots[&e].generation), + ]); + assert_eq!(observations, 1, "batch observed raw words more than once"); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 8, "strong owners did not drop after the batch"); + { + let tracked = TRACKED_SRVS.lock().unwrap(); + let tracked = tracked.as_ref().unwrap(); + assert_eq!(tracked.by_slot[&b].generation, newer_b.generation, "stale generation removed its replacement"); + assert!(!tracked.by_slot.contains_key(&c), "raw mismatch remained tracked"); + assert!(tracked.by_slot.contains_key(&d), "missing lease removed a still-current candidate"); + } + end_mutation_test(); + } + + #[test] + fn exact_srv_batch_empty_or_tracking_disabled_does_no_work() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + if !srv_tracking_enabled() { + let candidate = [(srv_slot(80, 0), 1)]; + assert_eq!(with_exact_tracked_srv_mutations_on( + &candidate, + |_, _| panic!("tracking-disabled batch leased an owner"), + |_| panic!("tracking-disabled batch observed words"), + |_: &[ExactSrvMutation<'_, (), ()>]| panic!("tracking-disabled batch mutated"), + ), None); + } + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + assert_eq!(with_exact_tracked_srv_mutations_on( + &[], + |_, _| panic!("empty batch leased an owner"), + |_| panic!("empty batch observed words"), + |_: &[ExactSrvMutation<'_, (), ()>]| panic!("empty batch mutated"), + ), None); + let slot = srv_slot(81, 0); + let (generation, _) = begin_mutation_test(tracked_entry(0x8110, 0xD0), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + assert_eq!(with_exact_tracked_srv_mutations_on( + &[(slot, generation)], + |_, _| Some((snapshot, (), ())), + |_| vec![None], + |_: &[ExactSrvMutation<'_, (), ()>]| panic!("all-stale batch mutated"), + ), None); + assert!(!TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot.contains_key(&slot)); + end_mutation_test(); + } + + #[test] + fn exact_srv_batch_unwind_drops_guards_before_strong_owners() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let slot = srv_slot(82, 0); + let (generation, words) = begin_mutation_test(tracked_entry(0x8210, 0xD4), slot); + let snapshot = TRACKED_SRVS.lock().unwrap().as_ref().unwrap().by_slot[&slot]; + let drops = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let unlocked = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + with_exact_tracked_srv_mutations_on( + &[(slot, generation)], + |_, _| Some(( + snapshot, + UnwindMutationOwner { drops: Arc::clone(&drops), unlocked: Arc::clone(&unlocked) }, + UnwindMutationOwner { drops: Arc::clone(&drops), unlocked: Arc::clone(&unlocked) }, + )), + |_| vec![Some(words)], + |_| -> () { panic!("test batch unwind") }, + ) + })); + assert!(outcome.is_err()); + assert_eq!(drops.load(std::sync::atomic::Ordering::Relaxed), 2); + assert_eq!(unlocked.load(std::sync::atomic::Ordering::Relaxed), 3, + "strong owners unwound before WRITE or tracker lock"); + TRACKED_SRV_WRITES.clear_poison(); + SHARED_VIEW_EPOCHS.clear_poison(); + end_mutation_test(); + } + + #[test] + fn tracked_srv_copy_requires_exact_source_words() { + let mut tracked = TrackedSrvs::default(); + let (source, copied, raw_changed) = (srv_slot(1, 0), srv_slot(2, 0), srv_slot(2, 1)); + tracked.write(source, Some(tracked_entry(10, 100))); + let source_words = tracked.by_slot[&source].words; + let mut copied_words = source_words; + copied_words[0] = 21; + tracked.copy_range(8, &[(source, 201, 202, 21, copied, true, source_words, copied_words)]); + assert_eq!(tracked.by_slot[&copied].resource, 10); + + let mut changed_words = source_words; + changed_words[1] ^= 1; + tracked.copy_range(8, &[(source, 301, 302, 31, raw_changed, true, changed_words, copied_words)]); + assert!(!tracked.by_slot.contains_key(&raw_changed)); + tracked.write(raw_changed, Some(tracked_entry(30, 300))); + tracked.copy_range(8, &[(source, 301, 302, 31, raw_changed, false, source_words, copied_words)]); + assert!(!tracked.by_slot.contains_key(&raw_changed), "an untrackable source clears the destination"); + } + + #[test] + fn tracked_srv_reconciliation_invalidates_same_index_word_change() { + let mut tracked = TrackedSrvs::default(); + let slot = srv_slot(1, 0); + tracked.write(slot, Some(tracked_entry(10, 100))); + let generation = tracked.by_slot[&slot].generation; + let mut changed = tracked.by_slot[&slot].words; + changed[1] ^= 1; + assert_eq!(changed[0], tracked.by_slot[&slot].words[0], "the PC descriptor index is unchanged"); + assert!(tracked.reconcile_observed(&[(slot, generation, Some(changed))]).is_empty()); + assert!(tracked.by_slot.is_empty(), "all eight console words identify the logical descriptor"); + } + + #[test] + fn tracked_srv_reconciliation_rejects_cross_heap_local_index_collision() { + let mut tracked = TrackedSrvs::default(); + let (source, destination) = (srv_slot(1, 3), srv_slot(2, 3)); + tracked.write(source, Some(tracked_entry(10, 6))); + tracked.write(destination, Some(tracked_entry(20, 6))); + let generation = tracked.by_slot[&destination].generation; + let copied_words = tracked.by_slot[&source].words; + assert_eq!(copied_words[0], tracked.by_slot[&destination].words[0], "fallback heaps repeat local index 2*k"); + assert!(tracked.reconcile_observed(&[(destination, generation, Some(copied_words))]).is_empty()); + assert!(!tracked.by_slot.contains_key(&destination)); + assert!(tracked.by_slot.contains_key(&source)); + } + + #[test] + fn tracked_srv_reconciliation_does_not_remove_a_newer_generation() { + let mut tracked = TrackedSrvs::default(); + let slot = srv_slot(1, 4); + tracked.write(slot, Some(tracked_entry(10, 8))); + let observed_generation = tracked.by_slot[&slot].generation; + tracked.write(slot, Some(tracked_entry(20, 8))); + let stale_words = tracked_entry(10, 8).words; + assert!(tracked.reconcile_observed(&[(slot, observed_generation, Some(stale_words))]).is_empty()); + assert_eq!(tracked.by_slot[&slot].resource, 20); + } + + #[test] + fn tracked_srv_global_cleanup_hooks_are_gated_and_exact() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + PLACED_TEXTURES.lock().unwrap().get_or_insert_with(HashSet::new).extend([10, 20]); + let (heap_40, heap_41) = (srv_slot(40, 0), srv_slot(41, 0)); + let mut tracked = TrackedSrvs::default(); + tracked.write(heap_40, Some(tracked_entry(10, 100))); + tracked.write(heap_41, Some(tracked_entry(20, 200))); + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + forget_srv_heap(40); + forget(20); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().is_some_and(|tracked| tracked.by_slot.is_empty())); + PLACED_TEXTURES.lock().unwrap().as_mut().unwrap().remove(&10); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn tracked_srv_lease_excludes_final_release_and_locked_cleanup() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let slot = srv_slot(52, 3); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(tracked_entry(0x5210, 0x80))); + let generation = tracked.by_slot[&slot].generation; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (entered_tx, entered_rx) = std::sync::mpsc::channel(); + let (continue_tx, continue_rx) = std::sync::mpsc::channel(); + let lease = std::thread::spawn(move || { + lease_tracked_srv_resource_with(slot, generation, |resource| { + entered_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + Some(resource) + }) + .map(|(entry, owner)| (entry.resource, owner)) + }); + entered_rx.recv().unwrap(); + + let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); + let (released_tx, released_rx) = std::sync::mpsc::channel(); + let release = std::thread::spawn(move || { + attempted_tx.send(()).unwrap(); + let _lifetime = lock_tracked_srv_lifetime(); + released_tx.send(()).unwrap(); + }); + attempted_rx.recv().unwrap(); + assert!(released_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "final Release crossed a resource lease in progress"); + continue_tx.send(()).unwrap(); + assert_eq!(lease.join().unwrap(), Some((0x5210, 0x5210))); + released_rx.recv().unwrap(); + release.join().unwrap(); + + let lifetime = lock_tracked_srv_lifetime(); + forget_tracked_after_resource_release(0x5210, lifetime.as_ref()); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().is_some_and(|tracked| tracked.by_slot.is_empty())); + drop(lifetime); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn descriptor_write_allows_nonfinal_release_before_concurrent_lease() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let slot = srv_slot(53, 2); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(tracked_entry(0x5310, 0x84))); + let generation = tracked.by_slot[&slot].generation; + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (release_entered_tx, release_entered_rx) = std::sync::mpsc::channel(); + let (finish_release_tx, finish_release_rx) = std::sync::mpsc::channel(); + let (drop_write_tx, drop_write_rx) = std::sync::mpsc::channel(); + let hook = std::thread::spawn(move || { + let _write = lock_tracked_srv_write(); + // Model a driver temporary Release reentering while a descriptor hook holds WRITE. + // A non-final Release takes only LIFETIME, then returns to the hook. + let lifetime = lock_tracked_srv_lifetime(); + release_entered_tx.send(()).unwrap(); + finish_release_rx.recv().unwrap(); + drop(lifetime); + drop_write_rx.recv().unwrap(); + }); + release_entered_rx.recv().unwrap(); + + let (attempted_tx, attempted_rx) = std::sync::mpsc::channel(); + let (leased_tx, leased_rx) = std::sync::mpsc::channel(); + let lease = std::thread::spawn(move || { + attempted_tx.send(()).unwrap(); + let leased = lease_tracked_srv_resource_with(slot, generation, Some) + .map(|(entry, owner)| (entry.resource, owner)); + leased_tx.send(leased).unwrap(); + }); + attempted_rx.recv().unwrap(); + assert!(leased_rx.recv_timeout(std::time::Duration::from_millis(50)).is_err(), + "a lease crossed the resource Release lifetime gate"); + finish_release_tx.send(()).unwrap(); + assert_eq!(leased_rx.recv().unwrap(), Some((0x5310, 0x5310)), + "lease acquisition waited for the descriptor-write gate and deadlocked the hook"); + lease.join().unwrap(); + drop_write_tx.send(()).unwrap(); + hook.join().unwrap(); + + let lifetime = lock_tracked_srv_lifetime(); + forget_tracked_after_resource_release(0x5310, lifetime.as_ref()); + drop(lifetime); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn descriptor_heap_final_cleanup_does_not_invert_reentrant_write_order() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let slot = srv_slot(55, 0); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot, Some(tracked_entry(0x5510, 0x90))); + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (held_tx, held_rx) = std::sync::mpsc::channel(); + let (clean_tx, clean_rx) = std::sync::mpsc::channel(); + let (cleaned_tx, cleaned_rx) = std::sync::mpsc::channel(); + let final_release = std::thread::spawn(move || { + let lifetime = super::super::console_heap::lock_lifetime(); + held_tx.send(()).unwrap(); + clean_rx.recv().unwrap(); + forget_srv_heap_after_release(55, lifetime.as_ref()); + cleaned_tx.send(()).unwrap(); + drop(lifetime); + }); + held_rx.recv().unwrap(); + let (write_tx, write_rx) = std::sync::mpsc::channel(); + let (drop_tx, drop_rx) = std::sync::mpsc::channel(); + let hook = std::thread::spawn(move || { + let _write = lock_tracked_srv_write(); + write_tx.send(()).unwrap(); + let lifetime = super::super::console_heap::lock_lifetime(); + drop(lifetime); + drop_rx.recv().unwrap(); + }); + write_rx.recv().unwrap(); + clean_tx.send(()).unwrap(); + cleaned_rx.recv_timeout(std::time::Duration::from_secs(1)).expect("final cleanup must not wait for WRITE"); + final_release.join().unwrap(); + drop_tx.send(()).unwrap(); + hook.join().unwrap(); + assert!(TRACKED_SRVS.lock().unwrap().as_ref().is_some_and(|tracked| tracked.by_slot.is_empty())); + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn final_release_cleanup_does_not_wait_for_unrelated_descriptor_write() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + SRV_TRACKING_FOR_TEST.store(true, std::sync::atomic::Ordering::Relaxed); + let (slot_a, slot_b) = (srv_slot(54, 0), srv_slot(54, 1)); + let mut tracked = TrackedSrvs::default(); + tracked.write(slot_a, Some(tracked_entry(0x5410, 0x88))); + tracked.write(slot_b, Some(tracked_entry(0x5420, 0x8c))); + *TRACKED_SRVS.lock().unwrap() = Some(tracked); + + let (lifetime_held_tx, lifetime_held_rx) = std::sync::mpsc::channel(); + let (clean_tx, clean_rx) = std::sync::mpsc::channel(); + let (cleaned_tx, cleaned_rx) = std::sync::mpsc::channel(); + let final_release = std::thread::spawn(move || { + let lifetime = lock_tracked_srv_lifetime(); + lifetime_held_tx.send(()).unwrap(); + clean_rx.recv().unwrap(); + forget_tracked_after_resource_release(0x5410, lifetime.as_ref()); + cleaned_tx.send(()).unwrap(); + drop(lifetime); + }); + lifetime_held_rx.recv().unwrap(); + + let (write_held_tx, write_held_rx) = std::sync::mpsc::channel(); + let (release_attempted_tx, release_attempted_rx) = std::sync::mpsc::channel(); + let (release_returned_tx, release_returned_rx) = std::sync::mpsc::channel(); + let (drop_write_tx, drop_write_rx) = std::sync::mpsc::channel(); + let unrelated_hook = std::thread::spawn(move || { + let _write = lock_tracked_srv_write(); + write_held_tx.send(()).unwrap(); + // Model resource B's driver call making a temporary Release while WRITE is held. + release_attempted_tx.send(()).unwrap(); + let lifetime = lock_tracked_srv_lifetime(); + release_returned_tx.send(()).unwrap(); + drop(lifetime); + drop_write_rx.recv().unwrap(); + }); + write_held_rx.recv().unwrap(); + release_attempted_rx.recv().unwrap(); + + clean_tx.send(()).unwrap(); + cleaned_rx.recv_timeout(std::time::Duration::from_secs(1)).expect( + "resource A final cleanup waited for WRITE while resource B Release waited for LIFETIME", + ); + final_release.join().unwrap(); + release_returned_rx.recv().unwrap(); + drop_write_tx.send(()).unwrap(); + unrelated_hook.join().unwrap(); + + { + let tracked = TRACKED_SRVS.lock().unwrap(); + let tracked = tracked.as_ref().unwrap(); + assert!(!tracked.by_slot.contains_key(&slot_a)); + assert_eq!(tracked.by_slot[&slot_b].resource, 0x5420); + } + TRACKED_SRVS.lock().unwrap().take(); + SRV_TRACKING_FOR_TEST.store(false, std::sync::atomic::Ordering::Relaxed); + } + + #[test] + fn title_queue_mapping_wait_reservation_is_monotonic_and_per_queue() { + let mut waited = HashMap::new(); + assert!(!reserve_page_wait(&mut waited, 1, 0)); + assert!(reserve_page_wait(&mut waited, 1, 4)); + assert!(!reserve_page_wait(&mut waited, 1, 4)); + assert!(!reserve_page_wait(&mut waited, 1, 3)); + assert!(reserve_page_wait(&mut waited, 2, 3)); + assert!(reserve_page_wait(&mut waited, 1, 5)); + assert_eq!(waited, HashMap::from([(1, 5), (2, 3)])); + } use std::time::{Duration, Instant}; const MIB: usize = 1 << 20; @@ -1448,6 +3317,72 @@ mod tests { assert_eq!(Levels::new(&[], None, 0, 1), None); } + #[test] + fn level_tile_owners_round_trip_through_a_deferred_unmap() { + let mut levels = Levels::new(&[(0, 2), (2, 1)], None, 3, 2).unwrap(); + levels.group_tiles[0] = (vec![0x1000, 0x2000], vec![(0x3000, 0)]); + levels.group_tiles[1] = (vec![0x4000], Vec::new()); + let expected = levels.group_tiles.clone(); + + let held = take_level_tiles(Some(&mut levels)); + assert_eq!(held, expected); + assert!(levels.group_tiles.iter().all(|(used, extra)| used.is_empty() && extra.is_empty())); + + levels.group_tiles = held; + assert_eq!(levels.group_tiles, expected, "cancelling a deferred unmap restores every group owner"); + } + + #[test] + fn resource_release_takes_every_level_group_owner() { + let mut levels = Levels::new(&[(0, 1), (1, 1)], Some((2, 1)), 3, 4).unwrap(); + levels.group_tiles[0].0.push(0x1000); + levels.group_tiles[1].1.push((0x2000, 1)); + levels.group_tiles[2].0.push(0x3000); + + let released = take_level_tiles(Some(&mut levels)); + let used: Vec<_> = released.iter().flat_map(|owners| owners.0.iter().copied()).collect(); + let extra: Vec<_> = released.iter().flat_map(|owners| owners.1.iter().copied()).collect(); + assert_eq!(used, [0x1000, 0x3000]); + assert_eq!(extra, [(0x2000, 1)]); + assert!(levels.group_tiles.iter().all(|(used, extra)| used.is_empty() && extra.is_empty())); + } + + #[test] + fn test_mapping_observation_includes_level_group_owners() { + let mut levels = Levels::new(&[(0, 1)], Some((1, 1)), 2, 2).unwrap(); + levels.group_tiles[0].0.push(0x1000); + levels.group_tiles[1].1.push((0x2000, 1)); + let target = Target { + va: 0x1000, + console_bytes: None, + total: 2, + mapped: true, + used: Vec::new(), + used_extra: Vec::new(), + levels: Some(levels), + texels: None, + }; + + assert_eq!(target_page_keys(&target), (vec![0x1000], vec![(0x2000, 1)])); + } + + #[test] + fn shared_page_identity_is_the_title_address_not_allocation_class() { + let mut pages = HashMap::new(); + for _evictable in [false, true] { + pages + .entry(0x1000) + .and_modify(|page: &mut Page| page.users += 1) + .or_insert(Page { tile: (0, 1), users: 1, idle_since: None }); + } + + // Both policies share one page. `heap_evictable` is only a packing hint for fresh tiles; + // future eviction must inspect live page owners rather than trusting the heap class. + assert_eq!(pages.len(), 1); + assert_eq!(pages[&0x1000].users, 2); + assert_eq!(pages[&0x1000].tile, (0, 1)); + } + #[test] fn packed_console_3d_mip_tails_use_the_detile_upload_path() { fn desc( @@ -1509,7 +3444,7 @@ mod tests { const P: u32 = 64; let mut live: Vec<Vec<Tile>> = Vec::new(); for _ in 0..100 { - live.push(pool.take_batch(P as usize, None, t0, P, &mut make).unwrap()); + live.push(pool.take_batch(P as usize, None, false, t0, P, &mut make).unwrap()); } assert_eq!(heaps_made.get(), 100); assert_eq!(pool.free_total, 0); @@ -1529,7 +3464,7 @@ mod tests { // - yield 1 single contiguous tile range (0..32) per texture! let t1 = t0 + COOL + Duration::from_millis(1); for _ in 0..100 { - let alloc = pool.take_batch(32, None, t1, P, &mut make).unwrap(); + let alloc = pool.take_batch(32, None, false, t1, P, &mut make).unwrap(); assert_eq!(alloc.len(), 32); let h0 = alloc[0].0; assert!(alloc.iter().all(|&(h, _)| h == h0), "texture scattered across multiple heaps"); @@ -1545,18 +3480,54 @@ mod tests { pool.push_cooling((3, t), t1); } let t2 = t1 + COOL + Duration::from_millis(1); - let pref = pool.take_batch(8, Some(7), t2, P, &mut make).unwrap(); + let pref = pool.take_batch(8, Some(7), false, t2, P, &mut make).unwrap(); assert!(pref.iter().all(|&(h, _)| h == 7), "preferred heap should be chosen"); assert_eq!(heap_ranges_trimmed(7, &pref), [(true, 10, 8)]); // Rollback on OOM: requesting more tiles than available when make_heap fails returns every // popped tile cleanly so free_total is preserved. assert_eq!(pool.free_total, 8); - let fail = pool.take_batch(16, None, t2, P, || None); + let fail = pool.take_batch(16, None, false, t2, P, || None); assert!(fail.is_none()); assert_eq!(pool.free_total, 8, "OOM rollback must return all popped tiles"); } + #[test] + fn tile_pool_keeps_evictable_and_pinned_tiles_in_separate_heaps() { + let t0 = Instant::now(); + let mut pool = TilePool::new(); + let next_slot = std::cell::Cell::new(0u32); + let mut alloc_slot = || { + let slot = next_slot.get(); + next_slot.set(slot + 1); + Some(slot) + }; + + const P: u32 = 64; + let evictable = pool.take_batch(32, None, true, t0, P, &mut alloc_slot).unwrap(); + let pinned = pool.take_batch(32, None, false, t0, P, &mut alloc_slot).unwrap(); + let evictable_again = pool.take_batch(32, None, true, t0, P, &mut alloc_slot).unwrap(); + + assert!(evictable.iter().chain(&evictable_again).all(|&(h, _)| h == evictable[0].0)); + assert!(pinned.iter().all(|&(h, _)| h == pinned[0].0)); + assert_ne!(evictable[0].0, pinned[0].0, "allocation classes must not share a pool heap"); + } + + #[test] + fn tile_pool_keeps_one_warm_spare_for_each_allocation_class() { + const P: u32 = 64; + let mut pool = TilePool::new(); + pool.add_heap_at(0, P, false); + pool.add_heap_at(1, P, false); + pool.add_heap_at(2, P, true); + pool.add_heap_at(3, P, true); + + assert_eq!(pool.reclaim_empty_heaps(1, P), [1, 3]); + assert_eq!(pool.free_total, 2 * P as usize); + assert_eq!(pool.pick_heap(P as usize, None, false), Some(0)); + assert_eq!(pool.pick_heap(P as usize, None, true), Some(2)); + } + /// Empty cooled pool heaps (above the warm spare count) are reclaimed cleanly back to VRAM and /// their slot indices can be reused without growing the heap table. #[test] @@ -1574,10 +3545,10 @@ mod tests { }; const P: u32 = 64; - let h0 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); - let h1 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); - let h2 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); - let h3 = pool.take_batch(P as usize, None, t0, P, &mut alloc_slot).unwrap(); + let h0 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); + let h1 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); + let h2 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); + let h3 = pool.take_batch(P as usize, None, false, t0, P, &mut alloc_slot).unwrap(); assert_eq!(next_slot.get(), 4); assert_eq!(pool.free_total, 0); @@ -1602,13 +3573,13 @@ mod tests { free_slots.borrow_mut().extend(reclaimed); // First 64-tile allocation reuses warm spare heap 1 (no new heap allocated). - let reuse_spare = pool.take_batch(P as usize, None, t1, P, &mut alloc_slot).unwrap(); + let reuse_spare = pool.take_batch(P as usize, None, false, t1, P, &mut alloc_slot).unwrap(); assert!(reuse_spare.iter().all(|&(h, _)| h == 1)); assert_eq!(free_slots.borrow().len(), 2); // Next 64-tile allocation consumes heap 0's 63 free tiles plus 1 tile from reclaimed slot 3 // without advancing `next_slot`. - let reuse_slot = pool.take_batch(P as usize, None, t1, P, &mut alloc_slot).unwrap(); + let reuse_slot = pool.take_batch(P as usize, None, false, t1, P, &mut alloc_slot).unwrap(); assert_eq!(reuse_slot.iter().filter(|&&(h, _)| h == 0).count(), 63); assert_eq!(reuse_slot.iter().filter(|&&(h, _)| h == 3).count(), 1); assert_eq!(next_slot.get(), 4); @@ -1695,6 +3666,100 @@ mod tests { assert_eq!(rq.retire_with(vec![303], None, &[] as &[(usize, usize)], mk, |_, _, _| true), vec![303]); } + #[test] + fn deferred_unmap_requires_every_queue_mark() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(0)); + let second = Arc::new(AtomicU64::new(0)); + let marks = [(first.clone(), 2), (second.clone(), 1)]; + assert!(!all_marks_complete(&marks, |fence| fence.load(Ordering::SeqCst))); + first.store(2, Ordering::SeqCst); + assert!(!all_marks_complete(&marks, |fence| fence.load(Ordering::SeqCst)), "one completed queue must not release the mapping"); + second.store(1, Ordering::SeqCst); + assert!(all_marks_complete(&marks, |fence| fence.load(Ordering::SeqCst))); + } + + #[test] + fn retirement_completion_poll_is_unlocked_and_new_marks_fail_closed() { + use std::sync::{atomic::{AtomicU64, Ordering}, Arc}; + let first = Arc::new(AtomicU64::new(1)); + let late = Arc::new(AtomicU64::new(0)); + let state = Mutex::new(RetireQueue::<u32, Arc<AtomicU64>>::new()); + { + let mut rq = state.lock().unwrap(); + rq.fences.insert(1, (first.clone(), 1)); + rq.batches.push(RetiringBatch { heaps: vec![101], unmap_mark: None, marks: vec![(first.clone(), 1)] }); + } + + let probes = state.lock().unwrap().completion_fences(); + let mut inserted = false; + let observed: Vec<_> = probes.into_iter().map(|fence| { + assert!(state.try_lock().is_ok(), "completion polling held retirement state"); + if !inserted { + inserted = true; + state.lock().unwrap().batches.extend([ + RetiringBatch { heaps: vec![202], unmap_mark: None, marks: vec![(first.clone(), 2)] }, + RetiringBatch { heaps: vec![303], unmap_mark: None, marks: vec![(late.clone(), 1)] }, + ]); + } + let completed = fence.load(Ordering::SeqCst); + (fence, completed) + }).collect(); + + let (done, pruned) = state.lock().unwrap().sweep_with(&HashSet::from([1]), |fence| { + observed_completion(&observed, fence, Arc::ptr_eq) + }); + assert_eq!(done.iter().flat_map(|batch| &batch.heaps).copied().collect::<Vec<_>>(), [101]); + assert!(pruned.is_empty()); + let rq = state.lock().unwrap(); + assert_eq!(rq.batches.len(), 2); + assert_eq!(rq.batches[0].heaps, [202], "a higher requirement added during the poll must be tested against the observed value"); + assert_eq!(rq.batches[1].heaps, [303], "a new fence added during the poll had no observation and must remain retired"); + } + + #[test] + fn device_retirement_state_is_leased_outside_the_registry() { + let _guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + let (first_key, second_key) = (0x7ffe_7600usize, 0x7ffe_7700usize); + { + let mut registry = RETIRE.lock().unwrap(); + let map = registry.get_or_insert_with(std::collections::HashMap::new); + map.remove(&first_key); + map.remove(&second_key); + } + + let first = device_retire_state(first_key); + let second = device_retire_state(second_key); + let first_guard = first.lock().unwrap(); + assert!(RETIRE.try_lock().is_ok(), "one device's driver turn must not hold the retirement registry"); + assert!(second.try_lock().is_ok(), "one device must not serialize another device's retirement work"); + + let removed = RETIRE.lock().unwrap().as_mut().unwrap().remove(&first_key).unwrap(); + assert!(std::sync::Arc::ptr_eq(&first, &removed)); + let replacement = device_retire_state(first_key); + assert!(!std::sync::Arc::ptr_eq(&first, &replacement), "a removed device key gets a fresh state while old work retains its lease"); + + drop(first_guard); + drop(removed); + let mut registry = RETIRE.lock().unwrap(); + registry.as_mut().unwrap().remove(&first_key); + registry.as_mut().unwrap().remove(&second_key); + } + + #[test] + fn forgetting_queue_cache_preserves_inflight_batch_marks() { + use std::sync::{atomic::AtomicU64, Arc}; + let mut rq = RetireQueue::<u32, Arc<AtomicU64>>::new(); + assert!(rq + .retire_with(vec![101], None, &[(7, 7usize)], || Some(Arc::new(AtomicU64::new(0))), |_, _, _| true) + .is_empty()); + let cached = rq.fences[&7].0.clone(); + let gone = rq.forget_queue(7).expect("cached queue fence"); + assert!(Arc::ptr_eq(&gone, &cached) && !rq.fences.contains_key(&7)); + assert_eq!(rq.batches.len(), 1); + assert!(Arc::strong_count(&cached) >= 3, "the in-flight batch lost its own fence clone"); + } + #[test] fn gpu_retire_queue_holds_heap_until_blocked_queue_passes_mark() { let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); @@ -1731,6 +3796,87 @@ mod tests { } } + #[test] + fn superseded_texture_waits_for_every_title_queue() { + let _vram_guard = VRAM_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + use windows::core::Interface; + use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_SAMPLE_DESC}; + unsafe { + let Ok(dev) = crate::gpu::agility::create_device(None, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0) else { + return crate::gpu::recomp::runner::skip_test("no GPU"); + }; + super::super::real::adopt(dev.as_raw(), super::super::real::Kind::Device); + let first: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let second: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + let polling: ID3D12CommandQueue = dev.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC::default()).unwrap(); + super::super::present::note_execute(first.as_raw(), &[]); + super::super::present::note_execute(second.as_raw(), &[]); + let gate_first: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + let gate_second: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + first.Wait(&gate_first, 1).unwrap(); + second.Wait(&gate_second, 1).unwrap(); + + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 512, + Height: 512, + DepthOrArraySize: 1, + MipLevels: 1, + Format: DXGI_FORMAT_R8G8B8A8_UNORM, + SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, + ..Default::default() + }; + let riid = &ID3D12Resource::IID as *const windows::core::GUID as *const windows_sys::core::GUID; + let mut raw = std::ptr::null_mut(); + let hr = place_pages(dev.as_raw(), 0x7_1000_0000, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), None, riid, &mut raw); + if hr.is_none_or(|hr| hr < 0) || raw.is_null() { + return crate::gpu::recomp::runner::skip_test("reserved texture unavailable"); + } + let resource = ID3D12Resource::from_raw(raw); + let dev_key = dev.as_raw() as usize; + let bytes = page_bytes_for(dev_key).0; + assert!(bytes >= 16 * PAGE); + + unmap_superseded(&resource); + before_execute(&polling); + assert_eq!(held_unmaps_for(dev_key), 1); + assert_eq!(page_bytes_for(dev_key).0, bytes, "blocked queues must keep the physical tiles live"); + + gate_first.Signal(1).unwrap(); + let first_done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + first.Signal(&first_done, 1).unwrap(); + first_done.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + before_execute(&polling); + assert_eq!(held_unmaps_for(dev_key), 1, "the second queue still owns prior work"); + + gate_second.Signal(1).unwrap(); + let second_done: ID3D12Fence = dev.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap(); + second.Signal(&second_done, 1).unwrap(); + second_done.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap(); + before_execute(&polling); + assert_eq!(held_unmaps_for(dev_key), 0); + assert!(page_bytes_for(dev_key).0 < bytes, "tiles return only after every queue completes"); + + let mut remap_raw = std::ptr::null_mut(); + let remap_hr = place_pages(dev.as_raw(), 0x7_2000_0000, &desc, D3D12_RESOURCE_STATE_COMMON.0 as u32, std::ptr::null(), None, riid, &mut remap_raw); + assert!(remap_hr.is_some_and(|hr| hr >= 0) && !remap_raw.is_null()); + let remapped = ID3D12Resource::from_raw(remap_raw); + let remap_bytes = page_bytes_for(dev_key).0; + first.Wait(&gate_first, 2).unwrap(); + second.Wait(&gate_second, 2).unwrap(); + unmap_superseded(&remapped); + assert_eq!(held_unmaps_for(dev_key), 1); + assert!(remap_if_unmapped(&remapped)); + assert_eq!(held_unmaps_for(dev_key), 0, "remapping cancels the deferred unmap"); + assert_eq!(page_bytes_for(dev_key).0, remap_bytes, "cancellation preserves the original tiles"); + gate_first.Signal(2).unwrap(); + gate_second.Signal(2).unwrap(); + drop(remapped); + drop(resource); + } + } + #[test] fn canonical_va_aliases_unmapped_gpu_view_but_preserves_committed_override() { use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READWRITE}; @@ -2174,4 +4320,125 @@ mod tests { assert!(new_calls < old_calls); } } + + #[test] + fn mip_texels_and_range_for_2d_array_3d_and_1d() { + assert_eq!(mip_texels(64, 32, 1, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 0), 64 * 32); + assert_eq!(mip_texels(64, 32, 1, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 1), 32 * 16); + assert_eq!(mip_texels(64, 32, 6, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 2), 16 * 8 * 6); + assert_eq!(mip_texels(64, 32, 8, D3D12_RESOURCE_DIMENSION_TEXTURE3D.0, 2), 16 * 8 * 2); + assert_eq!(mip_texels(64, 1, 4, D3D12_RESOURCE_DIMENSION_TEXTURE1D.0, 3), 8 * 4); + assert_eq!(range_texels(4, 4, 1, D3D12_RESOURCE_DIMENSION_TEXTURE2D.0, 0..3), 16 + 4 + 1); + } + + #[test] + fn srv_mip_range_respects_most_detailed_mip_levels_and_min_lod_clamp() { + assert_eq!(srv_mip_range(5, None), 0..5); + let srv_2d = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { + MostDetailedMip: 1, + MipLevels: 3, + PlaneSlice: 0, + ResourceMinLODClamp: 2.75, + }, + }, + ..Default::default() + }; + assert_eq!(srv_mip_range(6, Some(&srv_2d)), 2..4); + + let srv_all = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 2, + MipLevels: u32::MAX, + FirstArraySlice: 0, + ArraySize: 2, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + ..Default::default() + }; + assert_eq!(srv_mip_range(5, Some(&srv_all)), 2..5); + } + + #[test] + fn texel_meta_unions_overlapping_srv_ranges_without_double_counting() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 8, + Height: 8, + DepthOrArraySize: 1, + MipLevels: 4, + ..Default::default() + }; + let mut tm = TexelMeta::from_desc(&desc, false); + assert_eq!(tm.total_texels, 64 + 16 + 4 + 1); + assert_eq!(tm.resident_texels, 0); + + let srv_low = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 1, MipLevels: 2, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&srv_low)), (true, 16 + 4)); + + let srv_all = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2D: D3D12_TEX2D_SRV { MostDetailedMip: 0, MipLevels: 4, PlaneSlice: 0, ResourceMinLODClamp: 0.0 }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&srv_all)), (false, 64 + 1)); + assert_eq!(tm.record_srv(Some(&srv_all)), (false, 0)); + assert_eq!(tm.srv_sampled_texels, tm.total_texels); + } + + #[test] + fn texel_meta_unions_array_slices_without_counting_the_whole_mip() { + let desc = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + Width: 64, + Height: 64, + DepthOrArraySize: 6, + MipLevels: 1, + ..Default::default() + }; + let mut tm = TexelMeta::from_desc(&desc, false); + let view = |first| D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DARRAY, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DArray: D3D12_TEX2D_ARRAY_SRV { + MostDetailedMip: 0, + MipLevels: 1, + FirstArraySlice: first, + ArraySize: 1, + PlaneSlice: 0, + ResourceMinLODClamp: 0.0, + }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&view(0))), (true, 4096)); + assert_eq!(tm.record_srv(Some(&view(0))), (false, 0)); + assert_eq!(tm.record_srv(Some(&view(1))), (false, 4096)); + assert_eq!(tm.srv_sampled_texels, 8192); + assert_eq!(tm.total_texels, 6 * 4096); + + let ms = D3D12_SHADER_RESOURCE_VIEW_DESC { + ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2DMSARRAY, + Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 { + Texture2DMSArray: D3D12_TEX2DMS_ARRAY_SRV { FirstArraySlice: 4, ArraySize: 1 }, + }, + ..Default::default() + }; + assert_eq!(tm.record_srv(Some(&ms)), (false, 4096)); + assert_eq!(tm.srv_sampled_texels, 3 * 4096); + } } diff --git a/crates/xcl/src/hle/dstorage.rs b/crates/xcl/src/hle/dstorage.rs index 2ae4fe1b66..2a9d878708 100644 --- a/crates/xcl/src/hle/dstorage.rs +++ b/crates/xcl/src/hle/dstorage.rs @@ -18,7 +18,8 @@ //! * queue: QueryInterface, AddRef, Release, EnqueueRequest, EnqueueStatus(array, index), //! EnqueueSignal(fence, value), Submit, CancelRequestsWithTag(mask, value), Close, //! GetErrorEvent, RetrieveErrorRecord (0x290 bytes), Query (0x1C: the desc, then empty -//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then 6 more, +//! slots u16 @0x18 and requests until the automatic submit u16 @0x1A), then the X1 +//! EnqueueSetEvent(handle) method and 5 more, //! * file: QueryInterface, AddRef, Release, Close, GetHandle, 2 unknown, GetId, then 4 more; //! status array: QueryInterface, AddRef, Release, IsComplete(index), GetHResult(index), //! then 5 more. @@ -26,8 +27,9 @@ //! Each queue has a worker thread: submitted requests run in order (file reads through the //! VFS like the title's own, memory copies, zlib, BCPack where `hle::bcpack` rebuilds the //! blocks of the mode), a status entry gets the first failure of the requests since the -//! previous one, a signal sets the fence from the CPU. Methods not listed are logged and -//! answer E_NOTIMPL; BCPack BC2 and modes above 7, and the hardware swizzle, are refused. +//! previous one, a signal sets the fence from the CPU, and an event signals a Win32 waiter. +//! Unlisted methods log and answer E_NOTIMPL. BCPack BC2, modes above 7, and the hardware +//! swizzle are refused. #![allow(non_snake_case)] @@ -36,7 +38,7 @@ mod parallel; use std::ffi::c_void; use std::os::windows::fs::FileExt; -use std::os::windows::io::AsRawHandle; +use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering}; use std::sync::{mpsc, Arc, Condvar, Mutex, OnceLock}; @@ -45,7 +47,7 @@ use serde::{Deserialize, Serialize}; use windows_sys::core::GUID; use windows_sys::Win32::Foundation::{CloseHandle, DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE}; use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT}; -use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent}; +use windows_sys::Win32::System::Threading::{CreateEventW, GetCurrentProcess, ResetEvent, SetEvent, EVENT_MODIFY_STATE}; use crate::util::{HRESULT, S_OK}; @@ -803,7 +805,7 @@ unsafe fn snapshot_page_array(ptr: u64, offset: u16, byte_len: u32) -> Result<Ve Ok(pages) } -unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { +pub(crate) unsafe fn read_own(at: usize, out: *mut u8, len: usize) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut done = 0usize; @@ -817,6 +819,9 @@ fn writable(p: usize, n: usize) -> bool { if crate::gpu::uma::get().is_some_and(|u| u.in_committed_window(p, n)) { return true; } + if crate::hle::d3d12x::sparse::known_writable(p, n) { + return true; + } let mut at = p; while at < end { let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; @@ -1033,6 +1038,7 @@ enum Entry { Status(Arc<StatusInner>, u32), /// a fence (one reference held) and the value it gets Signal(FenceRef, u64), + SetEvent(OwnedHandle), #[cfg(test)] /// Test-only barrier to hold the worker deterministically while testing submitted-batch cancellation. Gate(Arc<std::sync::Barrier>), @@ -1106,6 +1112,7 @@ impl QueueInner { if batch.is_empty() { return; } + let _stall = crate::stall::span(crate::stall::StallKind::DirectStorage); if w.is_none() { let (tx, rx) = mpsc::channel::<Vec<Entry>>(); let q = Arc::clone(self); @@ -1196,6 +1203,9 @@ impl QueueInner { Entry::Signal(fence, value) => unsafe { fence.signal(value); }, + Entry::SetEvent(event) => unsafe { + SetEvent(event.as_raw_handle()); + }, #[cfg(test)] Entry::Gate(b) => { b.wait(); @@ -1273,6 +1283,7 @@ fn queue_vtbl() -> &'static [usize] { queue_get_error_event as usize, queue_retrieve_error_record as usize, queue_query as usize, + queue_enqueue_set_event as usize, // IDStorageQueueX1 ], 18, ) @@ -1438,6 +1449,19 @@ unsafe extern "system" fn queue_enqueue_signal(p: *mut c_void, fence: *mut c_voi q.enqueue(Entry::Signal(FenceRef(fence as usize), value)); } +unsafe extern "system" fn queue_enqueue_set_event(p: *mut c_void, event: HANDLE) { + let q = queue(p); + if q.closed.load(Ordering::Acquire) || event.is_null() { + return; + } + // Retain a separate handle until the marker reaches the worker or is discarded. + let mut duplicate = std::ptr::null_mut(); + let me = GetCurrentProcess(); + if DuplicateHandle(me, event, me, &mut duplicate, EVENT_MODIFY_STATE, 0, 0) != 0 { + q.enqueue(Entry::SetEvent(OwnedHandle::from_raw_handle(duplicate))); + } +} + unsafe extern "system" fn queue_submit(p: *mut c_void) { let q = queue(p); if !q.closed.load(Ordering::Acquire) { @@ -1492,6 +1516,7 @@ unsafe extern "system" fn queue_close(p: *mut c_void) { // after `Close()` returns (including for concurrent `Close()` callers). let (lock, cvar) = &q.worker_active; let mut active = lock.lock().unwrap(); + let _stall = if *active { crate::stall::span(crate::stall::StallKind::DirectStorage) } else { None }; while *active { active = cvar.wait(active).unwrap(); } diff --git a/crates/xcl/src/hle/dstorage/parallel_tests.rs b/crates/xcl/src/hle/dstorage/parallel_tests.rs index 5d5214e4fb..23632eb1eb 100644 --- a/crates/xcl/src/hle/dstorage/parallel_tests.rs +++ b/crates/xcl/src/hle/dstorage/parallel_tests.rs @@ -2,11 +2,14 @@ use super::super::*; use super::*; use std::io::Write; use std::os::windows::ffi::OsStrExt; +use std::os::windows::io::{FromRawHandle, OwnedHandle}; use std::panic::{self, AssertUnwindSafe}; use std::path::PathBuf; use std::ptr::null_mut; use std::thread; use std::time::{Duration, Instant}; +use windows_sys::Win32::Foundation::{WAIT_OBJECT_0, WAIT_TIMEOUT}; +use windows_sys::Win32::System::Threading::WaitForSingleObject; const TIMEOUT: Duration = Duration::from_secs(5); const TEST_BUDGET: usize = 1024 * 1024; @@ -109,11 +112,15 @@ struct TestQueue(*mut c_void); impl TestQueue { fn new(pool: Option<Arc<DecompressPool>>, hook: Option<TestHook>) -> Self { + Self::with_desc(64, &IID_QUEUE, pool, hook) + } + + fn with_desc(capacity: u16, iid: &GUID, pool: Option<Arc<DecompressPool>>, hook: Option<TestHook>) -> Self { let mut desc = [0; 0x18]; - desc[8..10].copy_from_slice(&64u16.to_le_bytes()); + desc[8..10].copy_from_slice(&capacity.to_le_bytes()); let mut raw = null_mut(); assert_eq!( - unsafe { factory_create_queue(null_mut(), desc.as_ptr(), &IID_QUEUE, &mut raw) }, + unsafe { factory_create_queue(null_mut(), desc.as_ptr(), iid, &mut raw) }, S_OK ); let queue = Self(raw); @@ -137,6 +144,14 @@ impl TestQueue { unsafe { queue_enqueue_status(self.0, status.0, slot) }; } + fn enqueue_set_event(&self, event: &OwnedHandle) { + unsafe { + let vtable = *(self.0 as *const *const usize); + let enqueue: unsafe extern "system" fn(*mut c_void, HANDLE) = std::mem::transmute(*vtable.add(12)); + enqueue(self.0, event.as_raw_handle()); + } + } + fn submit(&self) { unsafe { queue_submit(self.0) }; } @@ -262,6 +277,89 @@ fn await_later_preparation(events: &mpsc::Receiver<TestEvent>) { } } +fn completion_event() -> OwnedHandle { + let event = unsafe { CreateEventW(null_mut(), 1, 0, null_mut()) }; + assert!(!event.is_null()); + unsafe { OwnedHandle::from_raw_handle(event) } +} + +#[test] +fn completion_event_auto_submits_a_half_full_sequential_queue() { + with_deadline(|| { + let payload = vec![0x7b; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0x5d; payload.len()]; + let queue = TestQueue::with_desc(6, &IID_QUEUE_X1, None, None); + let status = TestStatus::new(1); + let event = completion_event(); + unsafe { queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)) }; + queue.status(&status, 0); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); + queue.enqueue_set_event(&event); + + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(status.result(0), S_OK); + assert_eq!(output, payload); + }); +} + +#[test] +fn completion_event_waits_for_parallel_retirement_and_keeps_its_handle() { + with_deadline(|| { + let payload = vec![0x4d; 48 * 1024]; + let file = TestFile::compressed(&[&payload]); + let mut output = vec![0; payload.len()]; + let mut failed = vec![0x72; payload.len()]; + let pool = test_pool(2, TEST_BUDGET); + let (gate, milestones, release) = gated_hook(TestEvent::BeforeDecode(1)); + let last_retired = Arc::new(AtomicU64::new(0)); + let retired = Arc::clone(&last_retired); + let hook = Arc::new(move |event| { + if let TestEvent::Retired(seq) = event { + retired.store(seq, Ordering::Release); + } + gate(event); + }); + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, Some(pool), Some(hook)); + let status = TestStatus::new(1); + let event = completion_event(); + let observer = event.try_clone().unwrap(); + + let mut short = file.request(0, failed.as_mut_ptr() as usize, 2); + short[0x30..0x34].copy_from_slice(&(file.chunks[0].1 + 1).to_le_bytes()); + unsafe { + queue.enqueue(&file.request(0, output.as_mut_ptr() as usize, 1)); + queue.enqueue(&short); + } + queue.enqueue_set_event(&event); + queue.status(&status, 0); + queue.submit(); + + assert_eq!(receive(&milestones), TestEvent::BeforeDecode(1)); + let early_wait = unsafe { WaitForSingleObject(observer.as_raw_handle(), 0) }; + drop(event); + release.send(()).unwrap(); + assert_eq!(early_wait, WAIT_TIMEOUT); + assert_eq!(unsafe { WaitForSingleObject(observer.as_raw_handle(), 2_000) }, WAIT_OBJECT_0); + assert_eq!(last_retired.load(Ordering::Acquire), 2); + assert_eq!(status.wait(0), E_END_OF_FILE); + assert_eq!(output, payload); + assert!(failed.iter().all(|&byte| byte == 0x72)); + }); +} + +#[test] +fn completion_event_close_discards_the_pending_marker() { + let queue = TestQueue::with_desc(64, &IID_QUEUE_X1, None, None); + let event = completion_event(); + queue.enqueue_set_event(&event); + assert_eq!(queue.inner().pending.lock().unwrap().entries.len(), 1); + unsafe { queue_close(queue.0) }; + + assert!(queue.inner().pending.lock().unwrap().entries.is_empty()); + assert_eq!(unsafe { WaitForSingleObject(event.as_raw_handle(), 0) }, WAIT_TIMEOUT); +} + #[test] fn parallel_out_of_order_completion_retires_fifo() { with_deadline(|| { diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 4144a1144e..f752450bad 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -244,13 +244,31 @@ const MEM_64K_PAGES: u32 = 0x2040_0000; /// Commit `[a, a + n)` of a sparse window (the title's reservations there) and give it video /// memory (`d3d12x::sparse`). unsafe fn commit_sparse(a: usize, n: usize, p: u32) -> *mut c_void { - let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, sanitize_protect(p)); + let protection = sanitize_protect(p); + let q = mem::VirtualAlloc(a as *const c_void, n, mem::MEM_COMMIT, protection); if !q.is_null() { - crate::hle::d3d12x::sparse::committed(q as usize, n); + crate::hle::d3d12x::sparse::committed_with_protection(q as usize, n, read_write(protection)); } q } +/// A writable protection without PAGE_GUARD. +fn read_write(protection: u32) -> bool { + matches!(protection & 0xFF, 0x04 | 0x08 | 0x40 | 0x80) && protection & 0x100 == 0 +} + +fn own_process(process: HANDLE) -> bool { + if process == unsafe { thr::GetCurrentProcess() } { + return true; + } + let id = unsafe { thr::GetProcessId(process) }; + id != 0 && id == unsafe { thr::GetCurrentProcessId() } +} + +unsafe fn note_protection(addr: *const c_void, size: usize, protection: u32) { + crate::hle::d3d12x::sparse::protection_changed(addr as usize, size, read_write(protection)); +} + pub unsafe extern "system" fn VirtualAlloc(addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { if let Some(q) = placeholders::alloc(addr, size, t, sanitize_protect(p)) { trace_mem("VirtualAlloc (placeholder)", addr as usize, size, t as u64, p, q as usize); @@ -477,7 +495,7 @@ pub unsafe extern "system" fn VirtualFree(addr: *mut c_void, size: usize, t: u32 } pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, size: usize, t: u32) -> BOOL { - if proc_ == thr::GetCurrentProcess() { + if own_process(proc_) { let a = addr as usize; if crate::gpu::uma::get().is_some_and(|u| u.is_sparse(a) || u.contains(a)) || (t & 0x8000 != 0 && in_graphics_reservation(a)) @@ -489,15 +507,37 @@ pub unsafe extern "system" fn VirtualFreeEx(proc_: HANDLE, addr: *mut c_void, si } pub unsafe extern "system" fn VirtualAllocEx(proc_: HANDLE, addr: *const c_void, size: usize, t: u32, p: u32) -> *mut c_void { + if own_process(proc_) { + return VirtualAlloc(addr, size, t, p); + } mem::VirtualAllocEx(proc_, addr, size, sanitize_alloc_type(t), sanitize_protect(p)) } pub unsafe extern "system" fn VirtualProtect(addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { - mem::VirtualProtect(addr, size, sanitize_protect(p), old) + let protection = sanitize_protect(p); + let writable = read_write(protection); + if !writable { + note_protection(addr, size, protection); + } + let ok = mem::VirtualProtect(addr, size, protection, old); + if ok != 0 && writable { + note_protection(addr, size, protection); + } + ok } pub unsafe extern "system" fn VirtualProtectEx(proc_: HANDLE, addr: *const c_void, size: usize, p: u32, old: *mut u32) -> BOOL { - mem::VirtualProtectEx(proc_, addr, size, sanitize_protect(p), old) + let protection = sanitize_protect(p); + let own = own_process(proc_); + let writable = read_write(protection); + if own && !writable { + note_protection(addr, size, protection); + } + let ok = mem::VirtualProtectEx(proc_, addr, size, protection, old); + if ok != 0 && own && writable { + note_protection(addr, size, protection); + } + ok } /// XALLOC_ATTRIBUTES bit fields. diff --git a/crates/xcl/src/hle/opus.rs b/crates/xcl/src/hle/opus.rs index ac9c01313f..8ef3045ad7 100644 --- a/crates/xcl/src/hle/opus.rs +++ b/crates/xcl/src/hle/opus.rs @@ -266,8 +266,9 @@ pub fn parse_packet(packet: &[u8], multistream: bool) -> Option<PacketInfo> { } /// Parse one RFC 6716 Appendix B self-delimited Opus packet starting at `data[*pos..]` and -/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet. -fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { +/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet, reusing `out`. +fn split_self_delimited_into(data: &[u8], pos: &mut usize, out: &mut Vec<u8>) -> Option<()> { + out.clear(); let toc = *data.get(*pos)?; *pos += 1; let code = toc & 0x03; @@ -279,10 +280,10 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { let end = pos.checked_add(len)?; let payload = data.get(*pos..end)?; *pos = end; - let mut out = Vec::with_capacity(1 + len); + out.reserve(1 + len); out.push(toc); out.extend_from_slice(payload); - Some(out) + Some(()) } 1 => { let len = read_frame_len(data, pos)?; @@ -290,10 +291,10 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { let end = pos.checked_add(total)?; let payload = data.get(*pos..end)?; *pos = end; - let mut out = Vec::with_capacity(1 + total); + out.reserve(1 + total); out.push(toc); out.extend_from_slice(payload); - Some(out) + Some(()) } 2 => { let len1 = read_frame_len(data, pos)?; @@ -302,11 +303,11 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { let end = pos.checked_add(total)?; let payload = data.get(*pos..end)?; *pos = end; - let mut out = Vec::with_capacity(3 + total); + out.reserve(3 + total); out.push(toc); - write_frame_len(len1, &mut out)?; + write_frame_len(len1, out)?; out.extend_from_slice(payload); - Some(out) + Some(()) } 3 => { let fcb = *data.get(*pos)?; @@ -332,7 +333,6 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { } } let pad_hdr = &data[pad_hdr_start..*pos]; - let mut out = Vec::new(); out.push(toc); out.push(fcb); out.extend_from_slice(pad_hdr); @@ -342,7 +342,7 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { for i in 0..count { let flen = read_frame_len(data, pos)?; if i + 1 < count { - write_frame_len(flen, &mut out)?; + write_frame_len(flen, out)?; } sum = sum.checked_add(flen)?; } @@ -355,12 +355,52 @@ fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { let body = data.get(*pos..end)?; *pos = end; out.extend_from_slice(body); - Some(out) + Some(()) } _ => unreachable!(), } } +/// Parse one RFC 6716 Appendix B self-delimited Opus packet starting at `data[*pos..]` and +/// convert it into a standard (non-self-delimited) RFC 6716 Opus packet. +fn split_self_delimited(data: &[u8], pos: &mut usize) -> Option<Vec<u8>> { + let mut out = Vec::new(); + split_self_delimited_into(data, pos, &mut out)?; + Some(out) +} + +/// Split an RFC 7845 multistream packet into `sub_pkts` (length `stream_count - 1`, reused in place) +/// and return the trailing standard sub-packet slice. Validates all `stream_count` sub-packets +/// before returning `Some` so decoders never consume a partially valid packet. +fn split_multistream_into<'a>( + packet: &'a [u8], + stream_count: usize, + sub_pkts: &mut [Vec<u8>], +) -> Option<&'a [u8]> { + if stream_count == 0 || sub_pkts.len() != stream_count - 1 { + return None; + } + if packet.len() < stream_count.checked_mul(2)? - 1 { + return None; + } + let mut pos = 0usize; + let mut duration_48k = None; + for sub in sub_pkts.iter_mut() { + split_self_delimited_into(packet, &mut pos, sub)?; + let info = parse_packet(sub, false)?; + if duration_48k.is_some_and(|duration| duration != info.total_samples_48k) { + return None; + } + duration_48k = Some(info.total_samples_48k); + } + let last = packet.get(pos..)?; + let info = parse_packet(last, false)?; + if duration_48k.is_some_and(|duration| duration != info.total_samples_48k) { + return None; + } + Some(last) +} + /// Split an RFC 7845 multistream packet into `stream_count` standard single-stream packets. pub fn split_multistream_packet<'a>(packet: &'a [u8], stream_count: usize) -> Option<Vec<Cow<'a, [u8]>>> { if stream_count == 0 { @@ -1289,21 +1329,8 @@ impl MftDecoder { if cur_len > 0 && !ptr.is_null() { let bytes = std::slice::from_raw_parts(ptr, cur_len as usize); match self.output_fmt { - OutputSampleFormat::Pcm16 => { - let n = bytes.len() / 2; - out.reserve(n); - for chunk in bytes.chunks_exact(2) { - out.push(i16::from_le_bytes([chunk[0], chunk[1]])); - } - } - OutputSampleFormat::Float32 => { - let n = bytes.len() / 4; - out.reserve(n); - for chunk in bytes.chunks_exact(4) { - let f = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); - out.push(f32_to_i16(f)); - } - } + OutputSampleFormat::Pcm16 => append_pcm16_le(bytes, out), + OutputSampleFormat::Float32 => append_f32_le(bytes, out), } } let _ = buf.Unlock(); @@ -1311,6 +1338,105 @@ impl MftDecoder { } } +const _: () = assert!(cfg!(target_endian = "little")); + +/// Bulk-append little-endian signed 16-bit PCM bytes, ignoring a trailing odd byte. +fn append_pcm16_le(bytes: &[u8], out: &mut Vec<i16>) { + let n = bytes.len() / 2; + if n == 0 { + return; + } + let old = out.len(); + out.reserve(n); + // SAFETY: XCL targets little-endian x64, `reserve` provides `n` writable elements, the byte + // copy needs no source alignment, and safe borrowing keeps the input separate from `out`. + unsafe { + std::ptr::copy_nonoverlapping(bytes.as_ptr(), out.as_mut_ptr().add(old).cast::<u8>(), n * 2); + out.set_len(old + n); + } +} + +/// Append little-endian float PCM as clamped i16, ignoring a trailing partial sample. +fn append_f32_le(bytes: &[u8], out: &mut Vec<i16>) { + let chunks = bytes.as_chunks::<4>().0; + out.reserve(chunks.len()); + for &chunk in chunks { + out.push(f32_to_i16(f32::from_le_bytes(chunk))); + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ChannelSrc { + Silence, + Mono(usize), + Coupled { stream: usize, chan: usize }, +} + +/// Precompute RFC 7845 channel sources defensively; `255` and out-of-range entries map to silence. +fn build_channel_map(mapping: &[u8], stream_count: usize, coupled_count: usize) -> Vec<ChannelSrc> { + let coupled = coupled_count.min(stream_count); + let coupled_channels = coupled.saturating_mul(2); + mapping + .iter() + .map(|&idx| { + if idx == 255 { + return ChannelSrc::Silence; + } + let idx = usize::from(idx); + if idx < coupled_channels { + ChannelSrc::Coupled { stream: idx / 2, chan: idx % 2 } + } else { + let stream = coupled + (idx - coupled_channels); + if stream < stream_count { + ChannelSrc::Mono(stream) + } else { + ChannelSrc::Silence + } + } + }) + .collect() +} + +/// Interleave per-stream decoded PCM into `out`, clamping `max_frames` to the shortest referenced stream. +fn interleave_streams( + sub_pcm: &[Vec<i16>], + channel_map: &[ChannelSrc], + max_frames: usize, + out: &mut Vec<i16>, +) -> usize { + if channel_map.is_empty() || max_frames == 0 { + return 0; + } + let mut frames = max_frames; + for &src in channel_map { + match src { + ChannelSrc::Silence => {} + ChannelSrc::Mono(s) => { + frames = frames.min(sub_pcm.get(s).map_or(0, Vec::len)); + } + ChannelSrc::Coupled { stream, chan } => { + let avail = if chan < 2 { sub_pcm.get(stream).map_or(0, |b| b.len() / 2) } else { 0 }; + frames = frames.min(avail); + } + } + } + if frames == 0 { + return 0; + } + out.reserve(frames.saturating_mul(channel_map.len())); + for f in 0..frames { + for &src in channel_map { + let sample = match src { + ChannelSrc::Silence => 0i16, + ChannelSrc::Mono(s) => sub_pcm[s][f], + ChannelSrc::Coupled { stream, chan } => sub_pcm[stream][f * 2 + chan], + }; + out.push(sample); + } + } + frames +} + /// Stateful RFC 6716 / RFC 7845 Opus decoder (1–8 channels) backed by `MSOpusDecoder.dll`. /// /// `MSOpusDecoder.dll` registers `ThreadingModel = Both` (free-threaded); access is serialized @@ -1325,6 +1451,9 @@ pub struct Decoder { pre_skip: u16, pre_skip_left: usize, output_gain_scale: f32, + channel_map: Vec<ChannelSrc>, + sub_pkts: Vec<Vec<u8>>, + sub_pcm: Vec<Vec<i16>>, } // SAFETY: MSOpusDecoder.dll is ThreadingModel=Both (MTA-safe) and Decoder requires &mut self. @@ -1360,6 +1489,16 @@ impl Decoder { let output_rate = streams[0].output_rate(); let pre_skip_scaled = ((head.pre_skip as u64 * output_rate as u64) / 48_000) as usize; let output_gain_scale = gain_scale(head.output_gain); + let (channel_map, sub_pkts, sub_pcm) = if multistream { + let sc = streams.len(); + ( + build_channel_map(&head.mapping, sc, usize::from(head.coupled_count)), + vec![Vec::new(); sc.saturating_sub(1)], + vec![Vec::new(); sc], + ) + } else { + (Vec::new(), Vec::new(), Vec::new()) + }; Ok(Self { streams, @@ -1371,6 +1510,9 @@ impl Decoder { pre_skip: head.pre_skip, pre_skip_left: pre_skip_scaled, output_gain_scale, + channel_map, + sub_pkts, + sub_pcm, }) } @@ -1405,45 +1547,27 @@ impl Decoder { fn decode_packet_pcm(&mut self, packet: &[u8], out: &mut Vec<i16>) -> Result<(), String> { let start = out.len(); - let ch = self.channels as usize; if !self.multistream { self.streams[0].decode_packet(packet, out)?; } else { - let subs = split_multistream_packet(packet, self.streams.len()) + let stream_count = self.streams.len(); + let last = split_multistream_into(packet, stream_count, &mut self.sub_pkts) .ok_or_else(|| "invalid RFC 7845 multistream Opus packet".to_string())?; - let mut decoded: Vec<Vec<i16>> = Vec::with_capacity(self.streams.len()); + let coupled = usize::from(self.coupled_count); let mut frames = usize::MAX; - for (i, sub) in subs.iter().enumerate() { - let mut buf = Vec::new(); - let n = self.streams[i].decode_packet(sub, &mut buf)?; - frames = frames.min(n); - decoded.push(buf); + for i in 0..stream_count { + let sub: &[u8] = if i + 1 < stream_count { &self.sub_pkts[i] } else { last }; + let pcm = &mut self.sub_pcm[i]; + pcm.clear(); + let n = self.streams[i].decode_packet(sub, pcm)?; + let expected_ch = if i < coupled { 2 } else { 1 }; + frames = frames.min(n).min(pcm.len() / expected_ch); } if frames == usize::MAX { frames = 0; } - // Map decoded stream channels to output channels per RFC 7845 mapping table. - let coupled = self.coupled_count as usize; - out.reserve(frames * ch); - for f in 0..frames { - for &idx in &self.mapping { - let sample = if idx == 255 { - 0i16 - } else { - let idx = idx as usize; - if idx < coupled * 2 { - let s = idx / 2; - let c = idx % 2; - decoded[s][f * 2 + c] - } else { - let s = coupled + (idx - coupled * 2); - decoded[s][f] - } - }; - out.push(sample); - } - } + interleave_streams(&self.sub_pcm, &self.channel_map, frames, out); } // Apply RFC 7845 output gain if non-zero. @@ -1476,7 +1600,9 @@ impl Decoder { if packets.is_empty() { return Err("buffer contains no valid RFC 6716 Opus packets".to_string()); } - let mut out = Vec::new(); + // An MFT can defer output from an earlier call. Size only at a fresh decoder boundary; + // otherwise old output could make this buffer's packet-duration estimate an undercount. + let stream_boundary = self.streams.iter().all(|stream| stream.timestamp_100ns() == 0); let timing = timing.filter(|t| { // Reuse the voice's configured MFTs only at a decoder stream boundary // and when the Ogg headers describe the same channel layout and gain. @@ -1485,8 +1611,13 @@ impl Decoder { && t.head.coupled_count == self.coupled_count && t.head.mapping == self.mapping && gain_scale(t.head.output_gain) == self.output_gain_scale - && self.streams.iter().all(|s| s.timestamp_100ns() == 0) + && stream_boundary }); + let capacity = stream_boundary + .then(|| expected_buffer_samples(&packets, timing.as_ref(), self.output_rate, self.channels, self.multistream)) + .flatten() + .unwrap_or(0); + let mut out = Vec::with_capacity(capacity); if let Some(timing) = timing { for pkt in &packets { let start = out.len(); @@ -1510,6 +1641,30 @@ impl Decoder { } } +/// Bound speculative allocation even when a caller presents an enormous packet sequence. +const MAX_PREALLOC_SAMPLES: usize = 16 << 20; + +/// Exact decoded sample count for valid packets at the supported output rates. Multistream +/// decoding validates that every substream has this leading stream's duration before producing +/// output; Ogg timing already accumulated the same per-packet durations while parsing pages. +fn expected_buffer_samples( + packets: &[Cow<'_, [u8]>], + timing: Option<&OggTiming>, + output_rate: u32, + channels: u16, + multistream: bool, +) -> Option<usize> { + let samples_48k = match timing { + Some(timing) => timing.decoded_48k, + None => packets.iter().try_fold(0u64, |total, packet| { + let packet = parse_packet(packet, multistream)?; + Some(total.saturating_add(u64::from(packet.total_samples_48k))) + })?, + }; + let frames = u128::from(samples_48k).saturating_mul(u128::from(output_rate)) / 48_000; + Some(frames.saturating_mul(u128::from(channels)).min(MAX_PREALLOC_SAMPLES as u128) as usize) +} + fn gain_scale(gain: i16) -> f32 { 10.0f32.powf(f32::from(gain) / (20.0 * 256.0)) } @@ -2030,6 +2185,7 @@ pub(crate) mod tests { let mut dec = Decoder::new(1, 48_000, MONO_HYBRID_20MS_HEAD).unwrap(); let pcm = dec.decode_buffer(&block, 2048).unwrap(); assert_eq!(pcm.len(), 5 * 960 - 312); + assert_eq!(pcm.capacity(), 5 * 960, "decode_buffer reserves the full decoded timeline once"); // Flush resets pre-skip and decoder state cleanly dec.flush(); @@ -2046,4 +2202,210 @@ pub(crate) mod tests { assert!(d24.decode_packet(&[0xFB, 0], &mut out24).is_err()); assert_eq!(d24.decode_packet(MONO_HYBRID_20MS[1], &mut out24).unwrap(), 480); } + + #[test] + fn decoded_output_preallocation_is_exact_and_bounded() { + let mono: Vec<Cow<'_, [u8]>> = MONO_HYBRID_20MS.iter().map(|&packet| Cow::Borrowed(packet)).collect(); + assert_eq!(expected_buffer_samples(&mono, None, 48_000, 1, false), Some(5 * 960)); + assert_eq!(expected_buffer_samples(&mono, None, 24_000, 1, false), Some(5 * 480)); + + let stereo = [Cow::Borrowed(STEREO_CELT_20MS[0])]; + assert_eq!(expected_buffer_samples(&stereo, None, 48_000, 2, false), Some(960 * 2)); + + // Six equal-duration substreams: sizing reads the leading self-delimited TOC, while + // split_multistream_into validates every substream has that duration before decoding. + let multistream: &[u8] = &[ + 0xFC, 0x02, 0x11, 0x22, + 0xF1, 0x02, 0x11, 0x22, 0x33, 0x44, + 0xF2, 0x02, 0x03, 0x11, 0x22, 0x33, 0x44, 0x55, + 0xF3, 0xC2, 0x02, 0x01, 0x02, 0xAA, 0xBB, 0xCC, 0x00, 0x00, + 0xF3, 0x02, 0x02, 0x11, 0x22, 0x33, 0x44, + 0xF8, 0x99, 0x88, + ]; + let packets = [Cow::Borrowed(multistream)]; + assert_eq!(expected_buffer_samples(&packets, None, 48_000, 6, true), Some(960 * 6)); + + let timing = OggTiming { + head: parse_opus_head(&build_opus_head(2, 48_000, 312, 0)).unwrap(), + decoded_48k: 1920, + end_48k: 1724, + }; + assert_eq!(expected_buffer_samples(&[], Some(&timing), 24_000, 2, false), Some(960 * 2)); + let huge = OggTiming { decoded_48k: u64::MAX, end_48k: u64::MAX, ..timing }; + assert_eq!(expected_buffer_samples(&[], Some(&huge), u32::MAX, u16::MAX, true), Some(MAX_PREALLOC_SAMPLES)); + assert_eq!(expected_buffer_samples(&[Cow::Borrowed(&[0xFB, 0])], None, 48_000, 1, false), None); + } + + #[test] + fn split_self_delimited_into_reuses_buffer_and_matches_owned_split() { + // 6-stream packet exercising self-delimited codes 0, 1, 2, 3-VBR-padded, 3-CBR + standard tail. + let synthetic: &[u8] = &[ + 0xFC, 0x02, 0x11, 0x22, // code 0 + 0xF1, 0x02, 0x11, 0x22, 0x33, 0x44, // code 1: two 10 ms frames + 0xF2, 0x02, 0x03, 0x11, 0x22, 0x33, 0x44, 0x55, // code 2: two 10 ms frames + 0xF3, 0xC2, 0x02, 0x01, 0x02, 0xAA, 0xBB, 0xCC, 0x00, 0x00, // code 3 VBR + pad + 0xF3, 0x02, 0x02, 0x11, 0x22, 0x33, 0x44, // code 3 CBR + 0xF8, 0x99, 0x88, // standard tail + ]; + let owned = split_multistream_packet(synthetic, 6).unwrap(); + let mut sub_pkts = vec![Vec::new(); 5]; + let last = split_multistream_into(synthetic, 6, &mut sub_pkts).unwrap(); + for i in 0..5 { + assert_eq!(sub_pkts[i].as_slice(), owned[i].as_ref()); + } + assert_eq!(last, owned[5].as_ref()); + + // Real 5.1 packets: warm up on the larger packet [0], then verify zero reallocation on [1]. + let mut sub51 = vec![Vec::new(); 3]; + let last0 = split_multistream_into(SURROUND51_20MS[0], 4, &mut sub51).unwrap(); + let owned0 = split_multistream_packet(SURROUND51_20MS[0], 4).unwrap(); + for i in 0..3 { + assert_eq!(sub51[i].as_slice(), owned0[i].as_ref()); + } + assert_eq!(last0, owned0[3].as_ref()); + let before: Vec<(usize, usize)> = sub51.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + + let last1 = split_multistream_into(SURROUND51_20MS[1], 4, &mut sub51).unwrap(); + let owned1 = split_multistream_packet(SURROUND51_20MS[1], 4).unwrap(); + for i in 0..3 { + assert_eq!(sub51[i].as_slice(), owned1[i].as_ref()); + } + assert_eq!(last1, owned1[3].as_ref()); + let after: Vec<(usize, usize)> = sub51.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + assert_eq!(before, after, "reused sub_pkts buffers must not reallocate"); + + // Edge cases: 1-stream, 0-stream, wrong scratch len, short packet, invalid tail. + let mut empty_subs: Vec<Vec<u8>> = Vec::new(); + assert_eq!(split_multistream_into(MONO_HYBRID_20MS[0], 1, &mut empty_subs), Some(MONO_HYBRID_20MS[0])); + assert!(split_multistream_into(MONO_HYBRID_20MS[0], 0, &mut empty_subs).is_none()); + assert!(split_multistream_into(SURROUND51_20MS[0], 4, &mut empty_subs).is_none()); + assert!(split_multistream_into(&[0xFC, 0x00, 0xFC], 4, &mut sub51).is_none()); + let bad_tail = [0xFC, 0x02, 0xFF, 0xFE, 0xFC, 0x02, 0xFF, 0xFE, 0x78, 0x02, 0xFF, 0xFE, 0xFB, 0x00]; + assert!(split_multistream_into(&bad_tail, 4, &mut sub51).is_none()); + let mismatched_duration = [0xFD, 0x01, 0xAA, 0xBB, 0xFC, 0xCC]; + let mut one_sub = vec![Vec::new()]; + assert!(split_multistream_packet(&mismatched_duration, 2).is_some(), "each sub-packet is valid by itself"); + assert!(split_multistream_into(&mismatched_duration, 2, &mut one_sub).is_none(), "all sub-streams must describe the same duration"); + } + + #[test] + fn pcm_output_append_matches_scalar_for_unaligned_and_partial_input() { + let samples = [i16::MIN, -32767, -1, 0, 1, 12345, i16::MAX]; + let mut raw = vec![0xEEu8]; + for sample in samples { + raw.extend_from_slice(&sample.to_le_bytes()); + } + raw.push(0xAA); + for bytes in [&[][..], &[0x7F], &raw[1..1 + samples.len() * 2], &raw[1..], &raw[..raw.len() - 1]] { + let mut got = vec![1234, -5678]; + append_pcm16_le(bytes, &mut got); + let mut want = vec![1234, -5678]; + want.extend(bytes.as_chunks::<2>().0.iter().copied().map(i16::from_le_bytes)); + assert_eq!(got, want); + } + + let floats = [0.0f32, 0.5, -0.5, 1.0, -1.0, 2.5, -2.5, f32::NAN, f32::INFINITY, f32::NEG_INFINITY]; + let mut float_bytes = vec![0xDDu8]; + for sample in floats { + float_bytes.extend_from_slice(&sample.to_le_bytes()); + } + float_bytes.extend_from_slice(&[0x11, 0x22]); + for bytes in [&[][..], &[1, 2, 3], &float_bytes[1..]] { + let mut got = vec![42]; + append_f32_le(bytes, &mut got); + let mut want = vec![42]; + want.extend(bytes.as_chunks::<4>().0.iter().copied().map(|b| f32_to_i16(f32::from_le_bytes(b)))); + assert_eq!(got, want); + } + } + + #[test] + fn interleave_channel_map_clamps_short_stream_without_panic() { + let map = build_channel_map(&[0, 4, 1, 2, 3, 5, 255, 99], 4, 2); + assert_eq!( + map, + vec![ + ChannelSrc::Coupled { stream: 0, chan: 0 }, + ChannelSrc::Mono(2), + ChannelSrc::Coupled { stream: 0, chan: 1 }, + ChannelSrc::Coupled { stream: 1, chan: 0 }, + ChannelSrc::Coupled { stream: 1, chan: 1 }, + ChannelSrc::Mono(3), + ChannelSrc::Silence, + ChannelSrc::Silence, + ], + ); + // Defensive clamp if coupled_count exceeds stream_count. + assert_eq!( + build_channel_map(&[0, 1, 2], 1, 3), + vec![ + ChannelSrc::Coupled { stream: 0, chan: 0 }, + ChannelSrc::Coupled { stream: 0, chan: 1 }, + ChannelSrc::Silence, + ], + ); + + let full = vec![ + vec![10, 20, 11, 21], + vec![30, 40, 31, 41], + vec![50, 51], + vec![60, 61], + ]; + let map51 = build_channel_map(&[0, 4, 1, 2, 3, 5, 255], 4, 2); + let mut out = Vec::new(); + assert_eq!(interleave_streams(&full, &map51, 2, &mut out), 2); + assert_eq!(out, vec![10, 50, 20, 30, 40, 60, 0, 11, 51, 21, 31, 41, 61, 0]); + + // Short coupled stream (3 samples -> 1 complete stereo frame) clamps instead of panicking. + let short_coupled = vec![vec![10, 20, 99], vec![30, 40, 31, 41], vec![50, 51], vec![60, 61]]; + out.clear(); + assert_eq!(interleave_streams(&short_coupled, &map51, 4, &mut out), 1); + assert_eq!(out, vec![10, 50, 20, 30, 40, 60, 0]); + + // Out-of-bounds stream or channel entries yield 0 frames without panicking. + out.clear(); + assert_eq!(interleave_streams(&full, &[ChannelSrc::Mono(99)], 2, &mut out), 0); + assert_eq!(interleave_streams(&full, &[ChannelSrc::Coupled { stream: 0, chan: 2 }], 2, &mut out), 0); + assert!(out.is_empty()); + } + + #[test] + fn multistream_scratch_reuse_and_atomic_validation() { + if !is_available() { + eprintln!("skipping: MSOpusDecoder.dll not available"); + return; + } + // Atomic validation: valid streams 0..2 + invalid stream 3 must fail without advancing any stream. + let mut dec51 = Decoder::new(6, 48_000, SURROUND51_20MS_HEAD).unwrap(); + let bad_tail = [0xFC, 0x02, 0xFF, 0xFE, 0xFC, 0x02, 0xFF, 0xFE, 0x78, 0x02, 0xFF, 0xFE, 0xFB, 0x00]; + let mut pcm51 = Vec::new(); + assert!(dec51.decode_packet(&bad_tail, &mut pcm51).is_err()); + assert!(pcm51.is_empty()); + assert!(dec51.streams.iter().all(|s| s.timestamp_100ns() == 0)); + + let mut dec3 = Decoder::new(3, 48_000, &build_opus_head(3, 48_000, 0, 0)).unwrap(); + let mismatched_duration = [0xFD, 0x01, 0xAA, 0xBB, 0xFC, 0xCC]; + let mut pcm3 = Vec::new(); + assert!(dec3.decode_packet(&mismatched_duration, &mut pcm3).is_err()); + assert!(pcm3.is_empty()); + assert!(dec3.streams.iter().all(|s| s.timestamp_100ns() == 0), "duration mismatch is rejected before any sub-decoder advances"); + + // Scratch reuse across multistream packets: zero reallocations on packet 1 after packet 0 warm-up. + assert_eq!(dec51.decode_packet(SURROUND51_20MS[0], &mut pcm51).unwrap(), 960 - 312); + let pkt_ptrs: Vec<(usize, usize)> = dec51.sub_pkts.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + let pcm_ptrs: Vec<(usize, usize)> = dec51.sub_pcm.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect(); + assert!(pkt_ptrs.iter().all(|&(_, c)| c > 0) && pcm_ptrs.iter().all(|&(_, c)| c > 0)); + assert_eq!(dec51.decode_packet(SURROUND51_20MS[1], &mut pcm51).unwrap(), 960); + assert_eq!(pkt_ptrs, dec51.sub_pkts.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect::<Vec<_>>()); + assert_eq!(pcm_ptrs, dec51.sub_pcm.iter().map(|v| (v.as_ptr() as usize, v.capacity())).collect::<Vec<_>>()); + + // Defensive OOB clamp if a coupled sub-stream outputs mono (half the expected samples). + let mut dec_short = Decoder::new(6, 48_000, SURROUND51_20MS_HEAD).unwrap(); + let ud = build_opus_head(1, 48_000, 0, 0); + dec_short.streams[0] = SingleStreamDecoder::new(1, 48_000, Some(&ud)).unwrap(); + let mut short_out = Vec::new(); + assert_eq!(dec_short.decode_packet(SURROUND51_20MS[0], &mut short_out).unwrap(), 480 - 312); + assert_eq!(short_out.len(), (480 - 312) * 6); + + } } diff --git a/crates/xcl/src/hle/xaudio2.rs b/crates/xcl/src/hle/xaudio2.rs index fae020df15..6474efde5e 100644 --- a/crates/xcl/src/hle/xaudio2.rs +++ b/crates/xcl/src/hle/xaudio2.rs @@ -505,11 +505,56 @@ pub fn silent_buffer(i: &XmaInfo, b: &XAudio2Buffer, silence: *const u8, max_byt // Decoded voice state (Opus & XMA1/XMA2) & IXAudio2VoiceCallback wrapper // --------------------------------------------------------------------------------------- +const _: () = assert!(cfg!(target_endian = "little")); + /// Owned decoded PCM16 buffer kept alive at a stable heap address until `OnBufferEnd` -/// or `DestroyVoice`. +/// or `DestroyVoice`. Empty when backed by the shared read-only `silence()` mapping. struct DecodedBuffer { orig_context: usize, - _pcm: Box<[u8]>, + _pcm: Vec<i16>, +} + +/// Prepare decoded little-endian PCM16 samples for zero-copy XAudio2 submission. +/// Returns `None` when fewer than one complete frame was decoded so the caller falls back +/// to shared silence. +fn prepare_decoded_pcm(mut samples: Vec<i16>, channels: u16, orig_buf: &XAudio2Buffer) -> Option<(XAudio2Buffer, Vec<i16>)> { + let ch = channels.max(1) as usize; + let max_frames = (XAUDIO2_MAX_BUFFER_BYTES as usize) / (ch * 2); + let total_frames = (samples.len() / ch).min(max_frames); + if total_frames == 0 { + return None; + } + samples.truncate(total_frames * ch); + let mut nb = *orig_buf; + clamp_regions(&mut nb, total_frames as u32); + nb.audio_bytes = (samples.len() * 2) as u32; + Some((nb, samples)) +} + +const OWNED_SILENCE_BYTES: usize = 64 * 1024; + +fn prepare_fallback_silence( + info: &XmaInfo, + orig_buf: &XAudio2Buffer, + shared: *const u8, +) -> Option<(XAudio2Buffer, Vec<i16>)> { + if !shared.is_null() { + return Some((silent_buffer(info, orig_buf, shared, SILENCE_BYTES), Vec::new())); + } + + // Keep decoding failures recoverable when the large shared mapping cannot be allocated. + // This is deliberately bounded: a missing 32 MiB mapping must not turn one submission into + // a comparably large per-buffer allocation. + let mut nb = silent_buffer(info, orig_buf, std::ptr::null(), OWNED_SILENCE_BYTES); + let samples = nb.audio_bytes as usize / std::mem::size_of::<i16>(); + if samples == 0 { + return None; + } + let mut pcm = Vec::new(); + pcm.try_reserve_exact(samples).ok()?; + pcm.resize(samples, 0); + nb.audio_data = pcm.as_ptr() as *const u8; + Some((nb, pcm)) } enum VoiceDecoder { @@ -664,10 +709,50 @@ static DECODED_CALLBACK_VTBL: VoiceCallbackVtbl = VoiceCallbackVtbl { // the system engine and in-place vtable patches // --------------------------------------------------------------------------------------- +const FAST_ORIG_CAP: usize = 32; + +struct FastOriginals { + len: AtomicUsize, + entries: [(AtomicUsize, AtomicUsize, AtomicUsize); FAST_ORIG_CAP], +} + +impl FastOriginals { + const fn new() -> Self { + Self { + len: AtomicUsize::new(0), + entries: [const { (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)) }; FAST_ORIG_CAP], + } + } + + fn push(&self, idx: usize, vt: usize, slot: usize, orig: usize) { + if idx < FAST_ORIG_CAP { + let (ev, es, ef) = &self.entries[idx]; + ev.store(vt, Ordering::Relaxed); + es.store(slot, Ordering::Relaxed); + ef.store(orig, Ordering::Relaxed); + self.len.store(idx + 1, Ordering::Release); + } + } + + fn lookup(&self, vt: usize, slot: usize) -> Result<Option<usize>, ()> { + let n = self.len.load(Ordering::Acquire); + for (ev, es, ef) in &self.entries[..n] { + if ev.load(Ordering::Relaxed) == vt && es.load(Ordering::Relaxed) == slot { + return Ok(Some(ef.load(Ordering::Relaxed))); + } + } + if n < FAST_ORIG_CAP { Ok(None) } else { Err(()) } + } +} + /// Originals of patched slots: (vtable address, slot) → function. static ORIGINALS: Mutex<Vec<(usize, usize, usize)>> = Mutex::new(Vec::new()); +/// Lock-free mirror of the first `FAST_ORIG_CAP` entries of `ORIGINALS`. +static FAST_ORIGINALS: FastOriginals = FastOriginals::new(); /// Live silent voices (voice pointer → info). static XMA: Mutex<Option<HashMap<usize, XmaInfo>>> = Mutex::new(None); +/// Count of live silent voices (fast path for plain PCM and decoded voices). +static SILENT_LIVE_COUNT: AtomicUsize = AtomicUsize::new(0); /// Live decoded voices (Opus & XMA1/XMA2: voice pointer → handle). static DECODED_VOICES: Mutex<Option<HashMap<usize, DecodedVoiceHandle>>> = Mutex::new(None); /// Count of live decoded voices (fast path for plain PCM voices). @@ -695,7 +780,9 @@ unsafe fn patch(obj: *mut c_void, slot: usize, hook: usize) { crate::xlog_error!("XAudio2: cannot make vtable {vt:p} writable (slot {slot})"); return; } + let idx = g.len(); g.push((vt as usize, slot, cur)); + FAST_ORIGINALS.push(idx, vt as usize, slot, cur); p.write(hook); VirtualProtect(p as *const c_void, 8, old, &mut old); } @@ -703,7 +790,19 @@ unsafe fn patch(obj: *mut c_void, slot: usize, hook: usize) { /// The original implementation of `slot` for `obj`'s class. unsafe fn original(obj: *mut c_void, slot: usize) -> Option<usize> { let vt = vtable(obj) as usize; - ORIGINALS.lock().unwrap().iter().find(|&&(v, s, _)| v == vt && s == slot).map(|&(_, _, f)| f) + lookup_original(&FAST_ORIGINALS, &ORIGINALS, vt, slot) +} + +fn lookup_original( + fast: &FastOriginals, + slow: &Mutex<Vec<(usize, usize, usize)>>, + vt: usize, + slot: usize, +) -> Option<usize> { + match fast.lookup(vt, slot) { + Ok(hit) => hit, + Err(()) => slow.lock().unwrap().iter().find(|&&(v, s, _)| v == vt && s == slot).map(|&(_, _, f)| f), + } } fn system_create() -> Option<(Option<CreateWithVersionFn>, Option<CreateFn>)> { @@ -931,7 +1030,12 @@ unsafe extern "system" fn create_source_voice( patch_source_voice(voice); SOURCE_VOICES.fetch_add(1, Ordering::Relaxed); if let Some(i) = silent { - XMA.lock().unwrap().get_or_insert_with(HashMap::new).insert(voice as usize, i); + { + let mut g = XMA.lock().unwrap(); + if g.get_or_insert_with(HashMap::new).insert(voice as usize, i).is_none() { + SILENT_LIVE_COUNT.fetch_add(1, Ordering::Release); + } + } SILENT_VOICES.fetch_add(1, Ordering::Relaxed); if is_xma(tag) && XMA_VOICES.fetch_add(1, Ordering::Relaxed) == 0 { crate::xlog_warn!( @@ -997,9 +1101,23 @@ unsafe extern "system" fn create_mastering_voice( } fn silence() -> *const u8 { - use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_COMMIT, MEM_RESERVE, PAGE_READONLY}; - static P: OnceLock<usize> = OnceLock::new(); - *P.get_or_init(|| unsafe { VirtualAlloc(std::ptr::null(), SILENCE_BYTES, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY) as usize }) as *const u8 + use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_READONLY}; + static P: AtomicUsize = AtomicUsize::new(0); + let cached = P.load(Ordering::Acquire); + if cached != 0 { + return cached as *const u8; + } + let allocated = unsafe { VirtualAlloc(std::ptr::null(), SILENCE_BYTES, MEM_COMMIT | MEM_RESERVE, PAGE_READONLY) as usize }; + if allocated == 0 { + return std::ptr::null(); + } + match P.compare_exchange(0, allocated, Ordering::Release, Ordering::Acquire) { + Ok(_) => allocated as *const u8, + Err(winner) => { + unsafe { VirtualFree(allocated as *mut c_void, 0, MEM_RELEASE) }; + winner as *const u8 + } + } } unsafe fn submit_decoded_buffer( @@ -1040,47 +1158,48 @@ unsafe fn submit_decoded_buffer( } }; - let mut nb = orig_buf; - let pcm_bytes: Box<[u8]> = match decoded_pcm { - Ok(samples) if !samples.is_empty() => { - let total_frames = (samples.len() / state.channels.max(1) as usize) as u32; - clamp_regions(&mut nb, total_frames); - let mut bytes = Vec::with_capacity(samples.len() * 2); - for s in samples { - bytes.extend_from_slice(&s.to_le_bytes()); - } + let prepared = match decoded_pcm { + Ok(samples) => match prepare_decoded_pcm(samples, state.channels, &orig_buf) { + Some(p) => Ok(p), + None => Err(None), + }, + Err(e) => Err(Some(e)), + }; + let (mut nb, pcm) = match prepared { + Ok(p) => { if is_xma_voice { XMA_BUFFERS_DECODED.fetch_add(1, Ordering::Relaxed); } else { OPUS_BUFFERS_DECODED.fetch_add(1, Ordering::Relaxed); } - bytes.into_boxed_slice() + p } - res => { + Err(err) => { let err_counter = if is_xma_voice { &XMA_DECODE_ERRORS } else { &OPUS_DECODE_ERRORS }; let codec_name = if is_xma_voice { "XMA" } else { "Opus" }; let prev = err_counter.fetch_add(1, Ordering::Relaxed); if prev == 0 { - match res { - Err(e) => crate::xlog_warn!("XAudio2: {codec_name} decode error ({e}) – substituting silence"), - Ok(_) => crate::xlog_warn!("XAudio2: {codec_name} buffer decoded 0 samples – substituting silence"), + match err { + Some(e) => crate::xlog_warn!("XAudio2: {codec_name} decode error ({e}) – substituting silence"), + None => crate::xlog_warn!("XAudio2: {codec_name} buffer decoded 0 complete frames – substituting silence"), } } - let sb = silent_buffer(&fallback_info, &orig_buf, std::ptr::null(), SILENCE_BYTES); - nb = sb; + let Some(fallback) = prepare_fallback_silence(&fallback_info, &orig_buf, silence()) else { + return E_FAIL; + }; SILENCED.fetch_add(1, Ordering::Relaxed); - vec![0u8; sb.audio_bytes as usize].into_boxed_slice() + fallback } }; - let pcm_ptr = pcm_bytes.as_ptr(); - let pcm_len = pcm_bytes.len() as u32; - let boxed = Box::new(DecodedBuffer { orig_context: orig_buf.context as usize, _pcm: pcm_bytes }); + let boxed = Box::new(DecodedBuffer { orig_context: orig_buf.context as usize, _pcm: pcm }); + if !boxed._pcm.is_empty() { + nb.audio_data = boxed._pcm.as_ptr() as *const u8; + nb.audio_bytes = (boxed._pcm.len() * 2) as u32; + } let token = &*boxed as *const DecodedBuffer as usize; state.live_buffers.lock().unwrap().insert(token, boxed); - nb.audio_data = pcm_ptr; - nb.audio_bytes = pcm_len; nb.context = token as *mut c_void; let hr = orig(this, &nb, std::ptr::null()); @@ -1103,7 +1222,11 @@ unsafe extern "system" fn submit_source_buffer(this: *mut c_void, buf: *const XA return submit_decoded_buffer(this, orig, &state, buf.read_unaligned()); } } - let info = XMA.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()); + let info = if SILENT_LIVE_COUNT.load(Ordering::Acquire) != 0 { + XMA.lock().unwrap().as_ref().and_then(|m| m.get(&(this as usize)).copied()) + } else { + None + }; match info { Some(i) if !buf.is_null() => { let s = silence(); @@ -1159,8 +1282,11 @@ unsafe extern "system" fn get_state(this: *mut c_void, state_out: *mut XAudio2Vo unsafe extern "system" fn destroy_voice(this: *mut c_void) { let Some(orig) = original(this, VOICE_DESTROY) else { return }; let orig: DestroyVoiceFn = std::mem::transmute(orig); - if let Some(m) = XMA.lock().unwrap().as_mut() { - m.remove(&(this as usize)); + if SILENT_LIVE_COUNT.load(Ordering::Acquire) != 0 { + let mut g = XMA.lock().unwrap(); + if g.as_mut().and_then(|m| m.remove(&(this as usize))).is_some() { + SILENT_LIVE_COUNT.fetch_sub(1, Ordering::Release); + } } let decoded_handle = if DECODED_LIVE_COUNT.load(Ordering::Acquire) != 0 { DECODED_VOICES.lock().unwrap().as_mut().and_then(|m| m.remove(&(this as usize))) @@ -1786,4 +1912,60 @@ mod tests { assert_eq!(flush(guard.voice), S_OK); } } + + #[test] + fn prepare_decoded_pcm_is_zero_copy_and_whole_frame_clamped() { + let orig = buffer(16, 0, 10, 0, 0, 0); + // Empty and < 1 full frame return None so caller falls back to shared silence. + assert!(prepare_decoded_pcm(Vec::new(), 2, &orig).is_none()); + assert!(prepare_decoded_pcm(vec![0x1234i16], 2, &orig).is_none()); + + // 5 samples for 2 channels -> 2 complete frames (4 samples, 8 bytes), zero copy. + let samples = vec![0x1234i16, -1i16, 0x0055i16, 0x7FFFi16, 0x1111i16]; + let orig_ptr = samples.as_ptr(); + let (nb, out) = prepare_decoded_pcm(samples, 2, &orig).expect("2 whole frames"); + assert_eq!(out.as_ptr(), orig_ptr, "PCM Vec<i16> must not reallocate or copy"); + assert_eq!((out.len(), { nb.audio_bytes }, { nb.play_length }), (4, 8, 2)); + let bytes = unsafe { std::slice::from_raw_parts(out.as_ptr() as *const u8, out.len() * 2) }; + assert_eq!(&bytes[..4], &[0x34, 0x12, 0xFF, 0xFF]); + } + + #[test] + fn fast_originals_serves_entries_lock_free_and_respects_overflow() { + let fast = FastOriginals::new(); + let slow = Mutex::new(Vec::new()); + assert_eq!(fast.lookup(0x1000, 1), Ok(None)); + for i in 0..FAST_ORIG_CAP { + let entry = (0x1000 + i * 8, i % 4, 0x9000 + i); + slow.lock().unwrap().push(entry); + fast.push(i, entry.0, entry.1, entry.2); + } + assert_eq!(fast.lookup(0x1000, 0), Ok(Some(0x9000))); + assert_eq!(fast.lookup(0x1000 + (FAST_ORIG_CAP - 1) * 8, (FAST_ORIG_CAP - 1) % 4), Ok(Some(0x9000 + FAST_ORIG_CAP - 1))); + assert_eq!(fast.lookup(0xDEAD, 0), Err(())); + + // The 33rd entry cannot be mirrored. Exercise the exact production helper and + // verify it consults the isolated slow registry only after fast-table saturation. + let overflow = (0xDEAD, 7, 0xBEEF); + slow.lock().unwrap().push(overflow); + assert_eq!(lookup_original(&fast, &slow, overflow.0, overflow.1), Some(overflow.2)); + assert_eq!(lookup_original(&fast, &slow, 0xBAD, 7), None); + } + + #[test] + fn decode_fallback_uses_shared_or_bounded_owned_silence() { + let info = XmaInfo { channels: 2, rate: 48_000, samples_encoded: 48_000, bytes_per_block: 0x1000, block_count: 1, ..Default::default() }; + let orig = buffer(0x1000, 0, 480, 0, 0, 0); + let shared = 0x4000 as *const u8; + let (nb, pcm) = prepare_fallback_silence(&info, &orig, shared).expect("shared silence"); + assert!(pcm.is_empty() && pcm.capacity() == 0); + assert_eq!(({ nb.audio_data }, { nb.audio_bytes }), (shared, 480 * 4)); + + let huge = buffer(0x1000, 0, u32::MAX, 0, 0, 0); + let (nb, pcm) = prepare_fallback_silence(&info, &huge, std::ptr::null()).expect("owned silence"); + assert_eq!(nb.audio_bytes as usize, OWNED_SILENCE_BYTES); + assert_eq!(pcm.len() * std::mem::size_of::<i16>(), OWNED_SILENCE_BYTES); + assert_eq!({ nb.audio_data }, pcm.as_ptr() as *const u8); + assert!(pcm.iter().all(|&sample| sample == 0)); + } } diff --git a/crates/xcl/src/hle/xg.rs b/crates/xcl/src/hle/xg.rs index 0eec7dc16e..be12ded2ab 100644 --- a/crates/xcl/src/hle/xg.rs +++ b/crates/xcl/src/hle/xg.rs @@ -132,6 +132,8 @@ fn micro(e: u32) -> (usize, usize) { } impl Texture { + pub(crate) fn dimension(&self) -> u32 { self.dimension } + /// From a D3D12_RESOURCE_DESC (0x38 bytes) as the console's. pub fn new(d: &[u8; 0x38]) -> Result<Texture, HRESULT> { Self::with_pipes(d, crate::gpu::texture::console_pipes()) diff --git a/crates/xcl/src/host.rs b/crates/xcl/src/host.rs index 444333d891..a848b88194 100644 --- a/crates/xcl/src/host.rs +++ b/crates/xcl/src/host.rs @@ -31,6 +31,13 @@ pub fn host_main(boot_path: &Path) -> i32 { boot.config.title_memory_mb, boot.config.title_memory ); + if std::env::var_os("XCL_STALL_TRACE_DETAIL").is_some() { + crate::stall::enable_detail(); + crate::xlog_info!("detailed stall attribution enabled (XCL_STALL_TRACE_DETAIL)"); + } else if std::env::var_os("XCL_STALL_TRACE").is_some() { + crate::stall::enable(); + crate::xlog_info!("stall attribution enabled (XCL_STALL_TRACE)"); + } if std::env::var_os("XCL_UMA_MB").is_none() && boot.config.uma_mb != 0 { std::env::set_var("XCL_UMA_MB", boot.config.uma_mb.to_string()); @@ -41,7 +48,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::hle::d3d12x::real::log_dispatch_chain_counts(); }); // `XCL_ACTIVITY=1`: every 2 s what the title did since (a timeline of where it stops) - if std::env::var_os("XCL_ACTIVITY").is_some() { + if crate::hle::d3d12x::memory_report::enabled() { let _ = std::thread::Builder::new().name("xcl-activity".into()).spawn(|| { let snap = || { let (p, e) = crate::hle::d3d12x::present::activity(); @@ -51,6 +58,8 @@ pub fn host_main(boot_path: &Path) -> i32 { [p, e, d, x, f[0], f[1], f[2], f[3], r, b >> 20, fail] }; let mut last = snap(); + let mut last_looks = crate::hle::d3d12x::sparse::look_counters(); + let mut pressure_turn = 0u64; loop { std::thread::sleep(std::time::Duration::from_secs(2)); let now = snap(); @@ -59,22 +68,27 @@ pub fn host_main(boot_path: &Path) -> i32 { "activity (2 s): {} presents, {} submits, {} draws, {} dispatches, {} frame-event waits ({} timed out), {} frame statistics ({} not flipped); DirectStorage {} requests, {} MB, {} failed", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9], d[10] ); + let looks = crate::hle::d3d12x::sparse::look_counters(); + crate::xlog_info!("{}", crate::hle::d3d12x::sparse::look_line( + crate::hle::d3d12x::sparse::look_delta(looks, last_looks), 2, + )); + last_looks = looks; // where the memory is: the process's commit, video memory, and XCL's parts of it - let private = unsafe { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX}; - let mut c: PROCESS_MEMORY_COUNTERS_EX = std::mem::zeroed(); - c.cb = std::mem::size_of_val(&c) as u32; - K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut c as *mut _ as *mut _, c.cb); - c.PrivateUsage - }; - let (local, non_local) = crate::hle::d3d12x::real::video_memory().unwrap_or((0, 0)); + let owner = crate::hle::d3d12x::memory_report::snapshot(); + pressure_turn = pressure_turn.wrapping_add(1); + if let Some(line) = crate::hle::d3d12x::pso_async::observe_pressure_turn(pressure_turn, owner.local) { + crate::xlog_info!("{line}"); + } + let private = owner.commit.unwrap_or(0); + let local = owner.local.map_or(0, |s| s.usage); + let non_local = owner.non_local.map_or(0, |s| s.usage); let (arenas, arenas_made) = crate::hle::d3d12x::vram::arena_bytes(); let (pools, pools_mapped) = crate::hle::d3d12x::sparse::pool_bytes(); let (pages, page_pools) = crate::hle::d3d12x::vram::page_bytes(); let mb = |b: u64| b >> 20; crate::xlog_info!( "memory: {} MB committed by the process; video memory {} MB local, {} MB non-local; target pages {} MB (pools {} MB); arenas {} MB in use, {} MB made; sparse pools {} MB ({} MB mapped)", - mb(private as u64), + mb(private), mb(local), mb(non_local), mb(pages as u64), @@ -84,13 +98,40 @@ pub fn host_main(boot_path: &Path) -> i32 { mb(pools as u64), mb(pools_mapped as u64) ); + crate::xlog_info!("{}", owner.line()); + let pso = crate::hle::d3d12x::pso_async::retention_stats(); + crate::xlog_info!( + "pipeline retention: {} completed background PSOs behind stand-ins; {} unused for 60+ frames, {} for 600+ frames; oldest {} frames", + pso.retained_reals, + pso.unused_60_frames, + pso.unused_600_frames, + pso.oldest_unused_frames + ); + let ts = crate::hle::d3d12x::vram::texel_stats(); + if ts.sampled_textures > 0 { + let pct = if ts.total_texels > 0 { ts.resident_texels.saturating_mul(100) / ts.total_texels } else { 0 }; + let mtex = |n: u64| n as f64 / 1_000_000.0; + crate::xlog_info!( + "texture residency: {} sampled ({} with SRV); texels {:.1}M resident / {:.1}M srv-sampled / {:.1}M virtual ({}% resident)", + ts.sampled_textures, + ts.srv_textures, + mtex(ts.resident_texels), + mtex(ts.srv_sampled_texels), + mtex(ts.total_texels), + pct + ); + } last = now; } }); } - // `XCL_THREAD_DUMP_AT=s1,s2…`: where every thread is at those seconds (a stalled title) + // `XCL_THREAD_DUMP_AT=s1,s2…`: where every thread is at those seconds (a stalled title), and + // which title fences and XCL queue waits are behind then if let Ok(v) = std::env::var("XCL_THREAD_DUMP_AT") { let at: Vec<f64> = v.split(',').filter_map(|s| s.trim().parse().ok()).collect(); + if !at.is_empty() { + crate::hle::d3d12x::list_x::enable_sync_state_tracing(); + } let _ = std::thread::Builder::new().name("xcl-thread-dump".into()).spawn(move || { let t0 = std::time::Instant::now(); for s in at { @@ -99,6 +140,7 @@ pub fn host_main(boot_path: &Path) -> i32 { std::thread::sleep(std::time::Duration::from_secs_f64(left)); } crate::eh::dump_threads(); + crate::hle::d3d12x::list_x::log_sync_state(&format!("{s} s")); } }); } @@ -111,6 +153,8 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("XCL_RUN_SECONDS: {secs} s – ending the title ({shown} frames shown, {presented} PresentX calls)"); crate::report::write_final(None); crate::log::flush(); + crate::hle::d3d12x::pso_async::shutdown_used(); + crate::hle::d3d12x::real::shutdown_indirect_split_records(std::time::Duration::from_millis(500)); crate::hle::d3d12x::real::end_title(0); }); } @@ -155,5 +199,7 @@ pub fn host_main(boot_path: &Path) -> i32 { crate::xlog_info!("game entry point returned code {code}"); crate::report::write_final(None); crate::log::flush(); + crate::hle::d3d12x::pso_async::shutdown_used(); + crate::hle::d3d12x::real::shutdown_indirect_split_records(std::time::Duration::from_millis(500)); code as i32 } diff --git a/crates/xcl/src/lib.rs b/crates/xcl/src/lib.rs index b6bc0d2ec8..df5aada1b7 100644 --- a/crates/xcl/src/lib.rs +++ b/crates/xcl/src/lib.rs @@ -30,6 +30,7 @@ mod rpf_probe; pub mod shaders; #[cfg(test)] mod source_hash; +pub mod stall; pub mod state; pub mod stubs; pub mod tls; diff --git a/crates/xcl/src/modules.rs b/crates/xcl/src/modules.rs index 7aa418fc92..785642dfe3 100644 --- a/crates/xcl/src/modules.rs +++ b/crates/xcl/src/modules.rs @@ -31,7 +31,7 @@ pub struct MappedModule { impl MappedModule { pub fn contains(&self, addr: usize) -> bool { - addr >= self.base && addr < self.base + self.size + addr.checked_sub(self.base).is_some_and(|off| off < self.size) } } @@ -39,41 +39,113 @@ static MAPPED: RwLock<Vec<Arc<MappedModule>>> = RwLock::new(Vec::new()); static MAIN: RwLock<Option<Arc<MappedModule>>> = RwLock::new(None); const MAX_RANGES: usize = 512; -static RANGE_BASE: [AtomicUsize; MAX_RANGES] = [const { AtomicUsize::new(0) }; MAX_RANGES]; -static RANGE_SIZE: [AtomicUsize; MAX_RANGES] = [const { AtomicUsize::new(0) }; MAX_RANGES]; -static RANGE_COUNT: AtomicUsize = AtomicUsize::new(0); -pub fn register_mapped(m: Arc<MappedModule>) { - let i = RANGE_COUNT.fetch_add(1, Ordering::AcqRel); - if i < MAX_RANGES { - RANGE_SIZE[i].store(m.size, Ordering::Release); - RANGE_BASE[i].store(m.base, Ordering::Release); +#[repr(C)] +struct RangeEntry { + base: AtomicUsize, + size: AtomicUsize, +} + +struct RangeTable { + count: AtomicUsize, + min_addr: AtomicUsize, + max_inclusive: AtomicUsize, + overflow_warned: AtomicBool, + entries: [RangeEntry; MAX_RANGES], +} + +impl RangeTable { + const fn new() -> Self { + Self { + count: AtomicUsize::new(0), + min_addr: AtomicUsize::new(usize::MAX), + max_inclusive: AtomicUsize::new(0), + overflow_warned: AtomicBool::new(false), + entries: [const { RangeEntry { base: AtomicUsize::new(0), size: AtomicUsize::new(0) } }; MAX_RANGES], + } + } + + fn insert(&self, base: usize, size: usize) -> bool { + if base == 0 || size == 0 { + return false; + } + let n = self.count.load(Ordering::Relaxed); + if n >= MAX_RANGES { + return !self.overflow_warned.swap(true, Ordering::Relaxed); + } + self.entries[n].size.store(size, Ordering::Relaxed); + self.entries[n].base.store(base, Ordering::Relaxed); + self.min_addr.fetch_min(base, Ordering::Relaxed); + self.max_inclusive.fetch_max(base.saturating_add(size - 1), Ordering::Relaxed); + self.count.store(n + 1, Ordering::Release); + false + } + + fn remove(&self, base: usize) { + if base == 0 { + return; + } + let n = self.count.load(Ordering::Relaxed); + for entry in &self.entries[..n] { + if entry.base.load(Ordering::Relaxed) == base { + entry.base.store(0, Ordering::Release); + } + } + } + + fn lookup(&self, addr: usize) -> Option<usize> { + let n = self.count.load(Ordering::Acquire); + if n == 0 { + return None; + } + let lo = self.min_addr.load(Ordering::Relaxed); + let hi = self.max_inclusive.load(Ordering::Relaxed); + if addr < lo || addr > hi { + return None; + } + for entry in &self.entries[..n] { + let b = entry.base.load(Ordering::Acquire); + if b != 0 && addr >= b { + let s = entry.size.load(Ordering::Relaxed); + if addr - b < s { + return Some(b); + } + } + } + None + } +} + +static RANGES: RangeTable = RangeTable::new(); + +fn register_mapped_with(m: Arc<MappedModule>, after_range: impl FnOnce()) { + let warn_overflow = { + let mut g = MAPPED.write().unwrap(); + let warn = RANGES.insert(m.base, m.size); + after_range(); + g.push(m); + warn + }; + if warn_overflow { + crate::xlog_warn!("modules: lock-free range table full ({MAX_RANGES} entries); subsequent modules are not tracked in RANGES"); } - MAPPED.write().unwrap().push(m); +} + +pub fn register_mapped(m: Arc<MappedModule>) { + register_mapped_with(m, || {}); } /// The image at `base` failed to load: it is no longer found (by name, base, address), so a /// later load maps it again – as Windows' loader unloads a DLL that failed. pub fn unregister_mapped(base: usize) { - MAPPED.write().unwrap().retain(|m| m.base != base); - for i in 0..RANGE_COUNT.load(Ordering::Acquire).min(MAX_RANGES) { - if RANGE_BASE[i].load(Ordering::Acquire) == base { - RANGE_BASE[i].store(0, Ordering::Release); - } - } + let mut g = MAPPED.write().unwrap(); + g.retain(|m| m.base != base); + RANGES.remove(base); } /// Lock-free: base of the mapped image containing `addr`. pub fn image_base_for_addr(addr: usize) -> Option<usize> { - let n = RANGE_COUNT.load(Ordering::Acquire).min(MAX_RANGES); - for i in 0..n { - let b = RANGE_BASE[i].load(Ordering::Acquire); - let s = RANGE_SIZE[i].load(Ordering::Acquire); - if b != 0 && addr >= b && addr < b + s { - return Some(b); - } - } - None + RANGES.lookup(addr) } pub fn mapped_modules() -> Vec<Arc<MappedModule>> { @@ -202,4 +274,159 @@ mod tests { let _ = describe_address(addr); } } + + fn fake_module(name: &str, base: usize, size: usize) -> Arc<MappedModule> { + Arc::new(MappedModule { + name: name.to_string(), + path: PathBuf::from(name), + base, + size, + entry_rva: 0, + is_dll: true, + exports: OwnedExports::default(), + tls_callbacks: Mutex::new(Vec::new()), + no_thread_calls: AtomicBool::new(false), + initialized: AtomicBool::new(true), + stack_reserve: 0, + }) + } + + #[test] + fn contains_and_range_table_handle_overflow_and_envelope_boundaries() { + let hi_base = usize::MAX - 0xFFF; + let m = fake_module("high.dll", hi_base, 0x2000); + assert!(m.contains(usize::MAX) && m.contains(hi_base) && !m.contains(hi_base - 1)); + + let t = RangeTable::new(); + assert_eq!(t.lookup(0x1_4000_0000), None); + assert!(!t.insert(0, 0x1000) && !t.insert(0x1_4000_0000, 0)); + assert_eq!((t.count.load(Ordering::Relaxed), t.min_addr.load(Ordering::Relaxed)), (0, usize::MAX)); + + assert!(!t.insert(0x1_4000_0000, 0x1000)); + assert!(!t.insert(0x1_5000_0000, 0x2000)); + assert_eq!(t.lookup(0x1_3FFF_FFFF), None); + assert_eq!(t.lookup(0x1_4000_0000), Some(0x1_4000_0000)); + assert_eq!(t.lookup(0x1_4000_0FFF), Some(0x1_4000_0000)); + assert_eq!(t.lookup(0x1_4000_1000), None); + assert_eq!(t.lookup(0x1_5000_1FFF), Some(0x1_5000_0000)); + assert_eq!(t.lookup(0x1_5000_2000), None); + + t.remove(0); + t.remove(0x1_4000_0000); + assert_eq!((t.lookup(0x1_4000_0100), t.lookup(0x1_5000_0100)), (None, Some(0x1_5000_0000))); + + assert!(!t.insert(hi_base, 0x2000)); + assert_eq!((t.lookup(usize::MAX), t.lookup(hi_base), t.lookup(hi_base - 1)), (Some(hi_base), Some(hi_base), None)); + + let full = RangeTable::new(); + for k in 0..MAX_RANGES { assert!(!full.insert(0x2_0000_0000 + k * 0x10000, 0x1000)); } + assert!(full.insert(0x3_0000_0000, 0x1000)); + assert!(!full.insert(0x3_0001_0000, 0x1000)); + assert_eq!(full.count.load(Ordering::Relaxed), MAX_RANGES); + } + + #[test] + fn concurrent_register_and_unregister_leave_no_zombie_ranges() { + struct UnregGuard(Vec<usize>); + impl Drop for UnregGuard { + fn drop(&mut self) { for &b in &self.0 { unregister_mapped(b); } } + } + let origin = 0x0000_6ABC_0000_0000usize; + let bases: Vec<usize> = (0..13).map(|k| origin + k * 0x10_0000).collect(); + let _guard = UnregGuard(bases.clone()); + register_mapped(fake_module("sib.dll", bases[0], 0x4000)); + + let stop = Arc::new(AtomicBool::new(false)); + let readers: Vec<_> = (0..2).map(|_| { + let (stop, b0, probes) = (Arc::clone(&stop), bases[0], bases.clone()); + std::thread::spawn(move || { + while !stop.load(Ordering::Relaxed) { + assert_eq!(image_base_for_addr(b0 + 0x100), Some(b0)); + for &b in &probes[1..] { let _ = image_base_for_addr(b + 0x100); } + assert_eq!(image_base_for_addr(0x0000_7FFF_DEAD_0000), None); + } + }) + }).collect(); + let writers: Vec<_> = [1..=6, 7..=12].into_iter().map(|range| { + let bases = bases.clone(); + std::thread::spawn(move || { + for k in range { + register_mapped(fake_module(&format!("tmp{k}.dll"), bases[k], 0x2000)); + assert_eq!(image_base_for_addr(bases[k] + 0x40), Some(bases[k])); + unregister_mapped(bases[k]); + } + }) + }).collect(); + for w in writers { w.join().unwrap(); } + stop.store(true, Ordering::Relaxed); + for r in readers { r.join().unwrap(); } + assert_eq!(image_base_for_addr(bases[0] + 0x100), Some(bases[0])); + for &b in &bases[1..] { + assert_eq!(image_base_for_addr(b + 0x100), None); + assert!(find_mapped_by_base(b).is_none()); + } + + if !cfg!(debug_assertions) { + let (t, old_b, old_s) = (RangeTable::new(), [const { AtomicUsize::new(0) }; 32], [const { AtomicUsize::new(0) }; 32]); + for k in 0..32usize { + let b = 0x1_4000_0000 + k * 0x100_0000; + t.insert(b, 0x80_0000); + old_b[k].store(b, Ordering::Relaxed); + old_s[k].store(0x80_0000, Ordering::Relaxed); + } + let probe = std::hint::black_box(0x7FF9_1234_5678usize); + let n_iters = 200_000u32; + let t0 = std::time::Instant::now(); + let mut old_hits = 0u32; + for _ in 0..n_iters { + let mut hit = false; + for i in 0..32 { + let (b, s) = (old_b[i].load(Ordering::Acquire), old_s[i].load(Ordering::Acquire)); + if b != 0 && probe >= b && probe < b.wrapping_add(s) { hit = true; break; } + } + old_hits += u32::from(std::hint::black_box(hit)); + } + let old_ns = t0.elapsed().as_nanos() as f64 / n_iters as f64; + let t1 = std::time::Instant::now(); + let mut new_hits = 0u32; + for _ in 0..n_iters { new_hits += u32::from(std::hint::black_box(t.lookup(probe).is_some())); } + let new_ns = t1.elapsed().as_nanos() as f64 / n_iters as f64; + assert_eq!((old_hits, new_hits), (0, 0)); + println!("MODULES_BENCH_NS out_of_envelope_32: before={old_ns:.2} after={new_ns:.2}"); + } + } + + #[test] + fn same_base_unregister_waits_for_registration_publication() { + use std::sync::mpsc; + use std::time::Duration; + + let base = 0x0000_6ABD_0000_0000usize; + unregister_mapped(base); + let (published_tx, published_rx) = mpsc::channel(); + let (continue_tx, continue_rx) = mpsc::channel(); + let register = std::thread::spawn(move || { + register_mapped_with(fake_module("same-base.dll", base, 0x4000), || { + published_tx.send(()).unwrap(); + continue_rx.recv().unwrap(); + }); + }); + published_rx.recv().unwrap(); + + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + let unregister = std::thread::spawn(move || { + started_tx.send(()).unwrap(); + unregister_mapped(base); + done_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(50)).is_err(), "unregister passed the in-flight registration's write lock"); + continue_tx.send(()).unwrap(); + register.join().unwrap(); + unregister.join().unwrap(); + + assert!(find_mapped_by_base(base).is_none()); + assert_eq!(image_base_for_addr(base + 0x100), None); + } } diff --git a/crates/xcl/src/report.rs b/crates/xcl/src/report.rs index 45b886e103..45aa5584ab 100644 --- a/crates/xcl/src/report.rs +++ b/crates/xcl/src/report.rs @@ -11,6 +11,9 @@ use serde::{Deserialize, Serialize}; use crate::resolver::{self, Source}; +pub const STALL_SUMMARY_VERSION: u32 = 1; +pub const PREPARATION_SUMMARY_VERSION: u32 = 3; + #[derive(Debug, Serialize, Deserialize, Default)] pub struct StubCall { pub dll: String, @@ -40,6 +43,114 @@ pub struct VfsInfo { pub whiteouts: Vec<String>, } +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct StallAggregate { + #[serde(default)] + pub kind: String, + #[serde(default)] + pub count: u64, + #[serde(default)] + pub total_ns: u64, + #[serde(default)] + pub max_ns: u64, + /// Index N counts durations from 2^N through 2^(N+1)-1 nanoseconds; bucket zero + /// also contains zero-duration spans. + #[serde(default)] + pub histogram_log2_ns: Vec<u64>, +} + +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct StallEvent { + #[serde(default)] + pub sequence: u64, + #[serde(default)] + pub kind: String, + #[serde(default)] + pub started_ns: u64, + #[serde(default)] + pub duration_ns: u64, +} + +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct StallSummary { + #[serde(default)] + pub version: u32, + #[serde(default)] + pub aggregates: Vec<StallAggregate>, + #[serde(default)] + pub slow_events: Vec<StallEvent>, +} + +fn stall_kind_name(kind: crate::stall::StallKind) -> &'static str { + use crate::stall::StallKind; + match kind { + StallKind::ShaderTranslation => "shader_translation", + StallKind::DxcQueue => "dxc_queue", + StallKind::DxcCompile => "dxc_compile", + StallKind::PipelineWait => "pipeline_wait", + StallKind::DriverCompileGate => "driver_compile_gate", + StallKind::DriverCompile => "driver_compile", + StallKind::SubmitPreparation => "submit_preparation", + StallKind::MemorySynchronization => "memory_synchronization", + StallKind::Residency => "residency", + StallKind::CacheIo => "cache_io", + StallKind::LockContention => "lock_contention", + StallKind::GpuWait => "gpu_wait", + StallKind::Present => "present", + StallKind::DirectStorage => "direct_storage", + StallKind::DetailDraw => "detail_draw", + StallKind::DetailDispatch => "detail_dispatch", + StallKind::DetailBind => "detail_bind", + StallKind::DetailViewDescriptor => "detail_view_descriptor", + StallKind::DetailBarrier => "detail_barrier", + StallKind::DetailCopy => "detail_copy", + StallKind::DetailListLifecycle => "detail_list_lifecycle", + } +} + +impl From<crate::stall::Snapshot> for StallSummary { + fn from(snapshot: crate::stall::Snapshot) -> Self { + let slow_skip = snapshot.slow_spans.len().saturating_sub(crate::stall::SLOW_SPAN_CAPACITY); + Self { + version: STALL_SUMMARY_VERSION, + aggregates: snapshot + .aggregates + .into_iter() + .map(|a| StallAggregate { + kind: stall_kind_name(a.kind).into(), + count: a.count, + total_ns: a.total_ns, + max_ns: a.max_ns, + histogram_log2_ns: a.histogram.into(), + }) + .collect(), + slow_events: snapshot + .slow_spans + .into_iter() + .skip(slow_skip) + .map(|s| StallEvent { + sequence: s.sequence, + kind: stall_kind_name(s.kind).into(), + started_ns: s.started_ns, + duration_ns: s.duration_ns, + }) + .collect(), + } + } +} + +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +pub struct PreparationSummary { + #[serde(default)] + pub version: u32, + #[serde(default)] + pub compute_build_coalescing: crate::hle::d3d12x::pso_async::ComputeCoalescingStats, + #[serde(default)] + pub ranked_preloads: crate::hle::d3d12x::pso_async::RankedPreloadStats, + #[serde(default)] + pub allocator_submits: crate::hle::d3d12x::AllocatorSubmitStats, +} + #[derive(Debug, Serialize, Deserialize, Default)] pub struct Report { pub xcl_version: String, @@ -65,6 +176,9 @@ pub struct Report { /// none was loaded) #[serde(default)] pub dxc: crate::gpu::recomp::dxc::Toolchain, + /// Versioned preparation-plane counters. Optional so reports from older XCL builds load. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preparation: Option<PreparationSummary>, /// D3D12.X backend: adapter, interface layouts, unknown IIDs, fallbacks, presented frames #[serde(default)] pub d3d12: crate::hle::d3d12x::real::D3d12Stats, @@ -79,6 +193,10 @@ pub struct Report { /// `XCL_DSTORAGE_BCPACK_FILL` #[serde(default)] pub dstorage: crate::hle::dstorage::DStorageStats, + /// Coarse runtime timings when `XCL_STALL_TRACE` was enabled. The events contain only + /// categories and monotonic times, never title paths, shader contents, or pipeline keys. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub stalls: Option<StallSummary>, pub notes: Vec<String>, } @@ -142,10 +260,17 @@ pub fn build() -> Report { vfs, shaders: crate::gpu::shader::stats(), dxc: crate::gpu::recomp::dxc::toolchain(), + preparation: Some(PreparationSummary { + version: PREPARATION_SUMMARY_VERSION, + compute_build_coalescing: crate::hle::d3d12x::pso_async::compute_coalescing_stats(), + ranked_preloads: crate::hle::d3d12x::pso_async::ranked_preload_stats(), + allocator_submits: crate::hle::d3d12x::allocator_submit_stats(), + }), d3d12: crate::hle::d3d12x::real::stats(), audio: crate::hle::xaudio2::stats(), xgameruntime: crate::hle::xgameruntime::api::stats(), dstorage: crate::hle::dstorage::stats(), + stalls: crate::stall::snapshot().map(Into::into), notes: vec![ "D3D12.X methods missing on PC show up in called_stubs as '<Interface>::#slot (not on PC)'.".into(), "Console-format shaders are replaced (fallback_pipelines) until the RDNA2 recompiler is finished.".into(), @@ -197,6 +322,123 @@ pub fn load(path: &std::path::Path) -> Option<Report> { mod tests { use super::*; + #[test] + fn old_reports_without_a_stall_summary_still_deserialize() { + let old = serde_json::to_value(Report::default()).unwrap(); + assert!(old.get("stalls").is_none(), "an absent summary is not serialized"); + assert!(old.get("preparation").is_none(), "an absent preparation summary is not serialized"); + let report: Report = serde_json::from_value(old).unwrap(); + assert!(report.stalls.is_none()); + assert!(report.preparation.is_none()); + } + + #[test] + fn preparation_summary_has_a_versioned_stable_json_shape() { + let summary = PreparationSummary { + version: PREPARATION_SUMMARY_VERSION, + compute_build_coalescing: crate::hle::d3d12x::pso_async::ComputeCoalescingStats { + keyed_submissions: 12, + coalescing_hits: 5, + unique_keyed_builds: 7, + current_in_flight: 3, + peak_in_flight: 6, + }, + ranked_preloads: crate::hle::d3d12x::pso_async::RankedPreloadStats { + submissions: 19, + started: 13, + promoted: 4, + }, + allocator_submits: crate::hle::d3d12x::AllocatorSubmitStats { + outer_execute_calls: 11, + chunks: 14, + multi_chunk_calls: 2, + forced_wait_boundaries: 3, + lists_marked: 37, + backing_mark_writes: 23, + signal_attempts: 14, + signal_failures: 1, + state_lock_wait_ns: 101, + state_lock_hold_ns: 202, + }, + }; + let json = serde_json::to_value(summary).unwrap(); + assert_eq!(json["version"], PREPARATION_SUMMARY_VERSION); + assert_eq!(json["compute_build_coalescing"]["keyed_submissions"], 12); + assert_eq!(json["compute_build_coalescing"]["coalescing_hits"], 5); + assert_eq!(json["compute_build_coalescing"]["unique_keyed_builds"], 7); + assert_eq!(json["compute_build_coalescing"]["current_in_flight"], 3); + assert_eq!(json["compute_build_coalescing"]["peak_in_flight"], 6); + assert_eq!(json["ranked_preloads"]["submissions"], 19); + assert_eq!(json["ranked_preloads"]["started"], 13); + assert_eq!(json["ranked_preloads"]["promoted"], 4); + assert_eq!(json["allocator_submits"]["outer_execute_calls"], 11); + assert_eq!(json["allocator_submits"]["state_lock_hold_ns"], 202); + + let mut version_two = json; + version_two["version"] = 2.into(); + version_two.as_object_mut().unwrap().remove("allocator_submits"); + let loaded: PreparationSummary = serde_json::from_value(version_two.clone()).unwrap(); + assert_eq!(loaded.allocator_submits, Default::default()); + + let mut version_one = version_two; + version_one["version"] = 1.into(); + version_one.as_object_mut().unwrap().remove("ranked_preloads"); + let loaded: PreparationSummary = serde_json::from_value(version_one).unwrap(); + assert_eq!(loaded.ranked_preloads, Default::default()); + } + + #[test] + fn a_stall_snapshot_has_a_versioned_stable_json_shape() { + let mut histogram = [0; crate::stall::HISTOGRAM_BUCKETS]; + histogram[10] = 2; + let summary = StallSummary::from(crate::stall::Snapshot { + aggregates: vec![crate::stall::AggregateSnapshot { + kind: crate::stall::StallKind::DxcCompile, + count: 2, + total_ns: 2500, + max_ns: 1476, + histogram, + }], + slow_spans: vec![crate::stall::SlowSpan { + sequence: 7, + kind: crate::stall::StallKind::GpuWait, + started_ns: 100, + duration_ns: 50_000_000, + }], + }); + let json = serde_json::to_value(summary).unwrap(); + + assert_eq!(json["version"], STALL_SUMMARY_VERSION); + assert_eq!(json["aggregates"][0]["kind"], "dxc_compile"); + assert_eq!(json["aggregates"][0]["count"], 2); + assert_eq!(json["aggregates"][0]["histogram_log2_ns"][10], 2); + assert_eq!(json["aggregates"][0]["histogram_log2_ns"].as_array().unwrap().len(), crate::stall::HISTOGRAM_BUCKETS); + assert_eq!(json["slow_events"][0]["kind"], "gpu_wait"); + assert_eq!(json["slow_events"][0]["sequence"], 7); + assert_eq!(json["slow_events"][0]["duration_ns"], 50_000_000); + } + + #[test] + fn missing_fields_in_a_stall_summary_take_safe_defaults() { + let summary: StallSummary = serde_json::from_str(r#"{"version":1}"#).unwrap(); + assert_eq!(summary, StallSummary { version: 1, aggregates: Vec::new(), slow_events: Vec::new() }); + } + + #[test] + fn a_stall_summary_keeps_only_the_newest_bounded_events() { + let slow_spans = (0..crate::stall::SLOW_SPAN_CAPACITY + 2) + .map(|sequence| crate::stall::SlowSpan { + sequence: sequence as u64, + kind: crate::stall::StallKind::GpuWait, + started_ns: sequence as u64, + duration_ns: crate::stall::SLOW_SPAN_NS, + }) + .collect(); + let summary = StallSummary::from(crate::stall::Snapshot { aggregates: Vec::new(), slow_spans }); + assert_eq!(summary.slow_events.len(), crate::stall::SLOW_SPAN_CAPACITY); + assert_eq!(summary.slow_events[0].sequence, 2); + } + #[test] fn a_crash_is_kept_while_another_thread_writes_the_report() { let (held, wait_held) = std::sync::mpsc::channel(); diff --git a/crates/xcl/src/shaders.rs b/crates/xcl/src/shaders.rs index 0cd2ed7b3a..562eb04dc5 100644 --- a/crates/xcl/src/shaders.rs +++ b/crates/xcl/src/shaders.rs @@ -8,7 +8,7 @@ use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::Mutex; use crate::gpu::{dxbc, pack, rdna2, recomp, shader, xbox}; @@ -914,12 +914,7 @@ pub fn run(path: &Path, args: &[String]) -> i32 { return 2; } }; - // the runtime's memory windows: from the descriptor heap with `XCL_HEAP_WINDOWS=1` - // (`pso::mem_windows`), as `--precompile` - let runtime_windows = || { - let windows = opts.windows; - if windows > 1 && recomp::pso::heap_windows() { windows | recomp::HEAP_WINDOWS } else { windows } - }; + let runtime_windows = || runtime_windows(opts.windows); let top = opts.top; let json = opts.json; let compile = opts.compile; @@ -979,9 +974,14 @@ pub fn run(path: &Path, args: &[String]) -> i32 { if opts.precompile { // `--used-only`: only the compute programs whose pipelines an earlier run of a title used let used = opts.used_only.then(crate::hle::d3d12x::pso_async::earlier_used_keys); + let indirect = (opts.used_only && opts.pipelines) + .then(crate::hle::d3d12x::real::earlier_indirect_split_records); // the runtime's key: heap windows with `XCL_HEAP_WINDOWS=1` (`pso::mem_windows`) let windows = runtime_windows(); - return precompile(&input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, used.as_ref(), t0); + return precompile( + &input, opts.limit, windows, opts.split, opts.only.as_deref(), opts.pipelines, + used.as_ref(), indirect.as_ref(), t0, + ); } if opts.direct { return direct_sweep(&input, &opts, t0); @@ -991,6 +991,11 @@ pub fn run(path: &Path, args: &[String]) -> i32 { print(path, &what, agg, top, json, t0, compile) } +/// The runtime's memory windows, as the offline commands key and translate programs. +fn runtime_windows(windows: u32) -> u32 { + recomp::pso::windows_for(windows) +} + #[cfg(test)] fn parse_record_hash(s: &str) -> Result<u64, String> { crate::cli::parse_hex_u64_str(s) @@ -1092,7 +1097,7 @@ fn export_hlsl(input: &Input, dir: &Path, min_kb: usize, count: usize, windows: println!( "{written} program(s) written to {} (split wave64: {split}, {} windows{}, {failures} failure(s))", dir.display(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" } ); if written == wanted { 0 } else { @@ -1141,7 +1146,7 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl unsafe { dev9.ShaderCacheControl(cache_kinds, D3D12_SHADER_CACHE_CONTROL_FLAG_DISABLE) } .map_err(|e| Unavailable(format!("cannot disable the driver cache (Windows Developer Mode is required): {e}")))?; let split = split.unwrap_or_else(|| recomp::pso::split_wave64_forced() || recomp::pso::wave32_only_for_device(&pipeline.dev)); - let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split).map_err(|e| Failed(format!("{name}: {e}")))?; + let (translation, profile) = recomp::pso::console_translation(&blob, recomp::pso::Stage::Compute, 0, windows, split, false).map_err(|e| Failed(format!("{name}: {e}")))?; let dxc_start = std::time::Instant::now(); let dxil = recomp::dxc::compile(&translation.hlsl, "main", profile, &[]).map_err(|e| Failed(format!("DXC: {e}")))?; let dxc_ms = dxc_start.elapsed().as_millis(); @@ -1185,16 +1190,15 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl } /// `--precompile`: translate every VS / PS / MS / CS program and compile it into the DXIL cache -/// (`recomp::dxc::cache_dir()`), the same HLSL the runtime will ask for, so a title does not -/// wait for DXC on first use. Resumable: cached programs are skipped. GS halves need their -/// pipeline partner and are left to the runtime. -/// The cache key is the HLSL, so the options are the runtime's: `windows` memory windows as a -/// title's unified memory has (`pso::mem_windows`, 4; `--windows 1` for a title without it), -/// and the split wave64 form when this machine's GPU (`XCL_ADAPTER`) runs only 32-lane waves -/// (`pso::wave32_only_for_device`). Before, the programs were translated with one window and -/// no split form, so a title asked for other HLSL and compiled everything again. Still -/// different at run time: a PS's static samplers after its VS's (sampler base 0 here) and the -/// mesh pass-through, which the runtime builds for its pixel shader. +/// (`recomp::dxc::cache_dir()`), matching the runtime path so a title does not translate or run +/// DXC on first use. CS and standalone VS / PS variants also warm the runtime's `translated/v2` +/// cache (including the direct graphics backend). Resumable: cached programs are skipped. GS +/// halves need their pipeline partner and are left to the runtime. +/// The options are the runtime's: `windows` memory windows as a title's unified memory has +/// (`pso::mem_windows`, 4; `--windows 1` for a title without it), and the split wave64 form when +/// this machine's GPU (`XCL_ADAPTER`) runs 32-lane waves. Still different at run time: a paired +/// PS follows its VS's static samplers (only sampler base 0 can be known here), and the mesh +/// pass-through is built with its pixel shader. /// `--pipelines`: each compute program's pipeline made on the GPU as a title's would be (XCL's /// ABI root signature with its static samplers). Save the driver's compiled blob in the same /// cache the runtime reads at startup. Nothing runs on the GPU. @@ -1204,15 +1208,26 @@ fn measure_pso_result(input: &Input, hash: u64, repeat: usize, windows: u32, spl /// (the > 8 MB HLSL programs DXC compiles at `-O0`, #1269). struct Pipelines { dev: windows::Win32::Graphics::Direct3D12::ID3D12Device, - signatures: Mutex<std::collections::HashMap<(bool, Vec<u32>), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, + signatures: Mutex<std::collections::HashMap<(PipelineRoot, Vec<u32>), windows::Win32::Graphics::Direct3D12::ID3D12RootSignature>>, made: AtomicUsize, refused: AtomicUsize, reused: AtomicUsize, + /// Successful uncached native creations (as distinct from accepted saved blobs). + created: AtomicUsize, + /// What durable artifact, if any, each successful uncached creation produced. + persistence: PersistenceCounters, + persistence_warned: AtomicBool, + /// pipelines an OS-backed claim proves another process is already building + elsewhere: AtomicUsize, split_programs: AtomicUsize, split_pieces: AtomicUsize, + indirect_programs: AtomicUsize, /// programs over `max_dxil` with no blob yet, and their DXIL bytes capped: AtomicUsize, capped_bytes: AtomicUsize, + /// intra-process builds keyed by full pipeline cache identity, so duplicate threads wait + /// rather than entering the driver together when the disk claim is unavailable + inflight: (Mutex<InflightBuilds>, std::sync::Condvar), /// driver compiles running and the most at once (`XCL_PIPELINE_THREADS`, 4): each of the /// biggest takes ~1.5 GB in the driver – fifteen at once took 24 GB running: (Mutex<usize>, std::sync::Condvar), @@ -1223,6 +1238,475 @@ struct Pipelines { cache_dir: Option<PathBuf>, } +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +enum PersistenceOutcome { + Saved, + BlobUnavailable, + Disabled, + WriteFailed, +} + +#[derive(Default)] +struct PersistenceCounters { + saved: AtomicUsize, + blob_unavailable: AtomicUsize, + disabled: AtomicUsize, + write_failed: AtomicUsize, +} + +#[derive(Debug, Default, Eq, PartialEq)] +struct PersistenceSnapshot { + saved: usize, + blob_unavailable: usize, + disabled: usize, + write_failed: usize, +} + +impl PersistenceCounters { + fn note(&self, outcome: PersistenceOutcome) { + let counter = match outcome { + PersistenceOutcome::Saved => &self.saved, + PersistenceOutcome::BlobUnavailable => &self.blob_unavailable, + PersistenceOutcome::Disabled => &self.disabled, + PersistenceOutcome::WriteFailed => &self.write_failed, + }; + counter.fetch_add(1, Ordering::Relaxed); + } + + fn snapshot(&self) -> PersistenceSnapshot { + PersistenceSnapshot { + saved: self.saved.load(Ordering::Relaxed), + blob_unavailable: self.blob_unavailable.load(Ordering::Relaxed), + disabled: self.disabled.load(Ordering::Relaxed), + write_failed: self.write_failed.load(Ordering::Relaxed), + } + } +} + +impl PersistenceSnapshot { + fn total(&self) -> usize { + self.saved + self.blob_unavailable + self.disabled + self.write_failed + } +} + +fn record_fresh_creation( + outcome: Option<PersistenceOutcome>, created: &AtomicUsize, persistence: &PersistenceCounters, +) { + let Some(outcome) = outcome else { return }; + created.fetch_add(1, Ordering::Relaxed); + persistence.note(outcome); +} + +#[cfg(test)] +mod pipeline_persistence_tests { + use super::{ + record_fresh_creation, PersistenceCounters, PersistenceOutcome, PersistenceSnapshot, + }; + use std::sync::atomic::{AtomicUsize, Ordering}; + + #[test] + fn every_fresh_creation_has_one_persistence_outcome() { + let created = AtomicUsize::new(0); + let counters = PersistenceCounters::default(); + record_fresh_creation(None, &created, &counters); + assert_eq!( + created.load(Ordering::Relaxed), + 0, + "a failed native creation has no persistence outcome", + ); + for outcome in [ + PersistenceOutcome::Saved, + PersistenceOutcome::BlobUnavailable, + PersistenceOutcome::Disabled, + PersistenceOutcome::WriteFailed, + PersistenceOutcome::WriteFailed, + ] { + record_fresh_creation(Some(outcome), &created, &counters); + } + let snapshot = counters.snapshot(); + assert_eq!(snapshot, PersistenceSnapshot { + saved: 1, + blob_unavailable: 1, + disabled: 1, + write_failed: 2, + }); + assert_eq!(snapshot.total(), 5); + assert_eq!(snapshot.total(), created.load(Ordering::Relaxed)); + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +enum PipelineRoot { + Whole, + DirectChain, + IndirectChain, +} + +fn split_piece_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { + if prewarm_indirect { + &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain] + } else { + &[PipelineRoot::DirectChain] + } +} + +fn split_whole_roots(prewarm_indirect: bool) -> &'static [PipelineRoot] { + if prewarm_indirect { + &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain] + } else { + &[] + } +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct PipelineCacheIdentity { + dxil_len: usize, + dxil_hash_a: u64, + dxil_hash_b: u64, + flags: i32, + node_mask: u32, + root: PipelineRoot, + sampler_words: Vec<u32>, + cache_path: Option<PathBuf>, +} + +impl PipelineCacheIdentity { + fn new( + dxil: &[u8], + flags: i32, + node_mask: u32, + root: PipelineRoot, + sampler_words: Vec<u32>, + cache_path: Option<PathBuf>, + ) -> Self { + let mut alt = 0x9e37_79b9_7f4a_7c15u64; + for &byte in dxil { + alt ^= u64::from(byte); + alt = alt.wrapping_mul(0xbf58_476d_1ce4_e5b9); + } + Self { + dxil_len: dxil.len(), + dxil_hash_a: shader::fnv64(dxil), + dxil_hash_b: alt, + flags, + node_mask, + root, + sampler_words, + cache_path, + } + } +} + +#[derive(Default)] +struct InflightBuilds { + active: HashSet<PipelineCacheIdentity>, +} + +struct InflightGuard<'a> { + state: &'a (Mutex<InflightBuilds>, std::sync::Condvar), + id: PipelineCacheIdentity, +} + +impl<'a> InflightGuard<'a> { + fn enter(state: &'a (Mutex<InflightBuilds>, std::sync::Condvar), id: PipelineCacheIdentity) -> Self { + let mut builds = state.0.lock().unwrap_or_else(|e| e.into_inner()); + while builds.active.contains(&id) { + builds = state.1.wait(builds).unwrap_or_else(|e| e.into_inner()); + } + builds.active.insert(id.clone()); + Self { state, id } + } +} + +impl Drop for InflightGuard<'_> { + fn drop(&mut self) { + let mut builds = self.state.0.lock().unwrap_or_else(|e| e.into_inner()); + builds.active.remove(&self.id); + self.state.1.notify_all(); + } +} + +#[cfg(test)] +mod inflight_build_tests { + use super::{InflightBuilds, InflightGuard, PipelineCacheIdentity, PipelineRoot}; + use std::path::PathBuf; + use std::sync::{mpsc, Condvar, Mutex}; + use std::time::Duration; + + fn identity(dxil: &[u8], flags: i32, node: u32, root: PipelineRoot, samplers: &[u32], path: &str) -> PipelineCacheIdentity { + PipelineCacheIdentity::new(dxil, flags, node, root, samplers.to_vec(), Some(PathBuf::from(path))) + } + + #[test] + fn identity_covers_every_pipeline_input() { + let base = identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 2], "a.pso"); + assert_eq!(base, identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abd", 0, 0, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 1, 0, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 2, PipelineRoot::Whole, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::DirectChain, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::IndirectChain, &[1, 2], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 3], "a.pso")); + assert_ne!(base, identity(b"abc", 0, 0, PipelineRoot::Whole, &[1, 2], "b.pso")); + assert_ne!(base, PipelineCacheIdentity::new(b"abc", 0, 0, PipelineRoot::Whole, vec![1, 2], None)); + } + + #[test] + fn indirect_selection_adds_indirect_pieces_without_changing_direct_pieces() { + assert_eq!(super::split_piece_roots(false), &[PipelineRoot::DirectChain]); + assert_eq!(super::split_piece_roots(true), &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain]); + assert!(super::split_whole_roots(false).is_empty()); + assert_eq!( + super::split_whole_roots(true), + &[PipelineRoot::DirectChain, PipelineRoot::IndirectChain], + ); + } + + #[test] + fn same_build_waits_while_distinct_builds_and_failures_can_proceed() { + let state = (Mutex::new(InflightBuilds::default()), Condvar::new()); + let base = identity(b"program", 0, 0, PipelineRoot::Whole, &[], "same.pso"); + let other = identity(b"other", 0, 0, PipelineRoot::Whole, &[], "other.pso"); + let first = InflightGuard::enter(&state, base.clone()); + drop(InflightGuard::enter(&state, other)); + + let (started_tx, started_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + std::thread::scope(|scope| { + scope.spawn(|| { + started_tx.send(()).unwrap(); + let _same = InflightGuard::enter(&state, base.clone()); + done_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(20)).is_err(), "same pipeline did not wait"); + drop(first); + done_rx.recv_timeout(Duration::from_secs(1)).expect("waiter stayed blocked"); + }); + + let retry = identity(b"retry", 0, 0, PipelineRoot::Whole, &[], "retry.pso"); + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _failed = InflightGuard::enter(&state, retry.clone()); + panic!("simulated build failure"); + })); + assert!(panicked.is_err()); + drop(InflightGuard::enter(&state, retry)); + assert!(state.0.lock().unwrap_or_else(|e| e.into_inner()).active.is_empty()); + } +} + +enum ClaimAcquire { + Acquired(Claim), + HeldElsewhere, + Unavailable(std::io::Error), +} + +/// Exclusive cross-process ownership of one driver-cache build (`<blob>.claim`). The kernel +/// deletes the file when the handle closes, including after forced process termination. +struct Claim { + _file: std::fs::File, +} + +fn claim_path_for(blob: &Path) -> PathBuf { + let mut name = blob.as_os_str().to_owned(); + name.push(".claim"); + PathBuf::from(name) +} + +impl Claim { + fn acquire(blob: &Path) -> ClaimAcquire { + use std::os::windows::fs::OpenOptionsExt; + use windows_sys::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, GENERIC_READ, GENERIC_WRITE}; + use windows_sys::Win32::Storage::FileSystem::{DELETE, FILE_ATTRIBUTE_TEMPORARY, FILE_FLAG_DELETE_ON_CLOSE}; + + let path = claim_path_for(blob); + if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) { + if let Err(e) = std::fs::create_dir_all(dir) { + return ClaimAcquire::Unavailable(e); + } + } + // OPEN_ALWAYS adopts an unlocked orphan from the old create/delete protocol. DELETE is + // required to apply FILE_FLAG_DELETE_ON_CLOSE to that existing file. + let open = || { + std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .access_mode(GENERIC_READ | GENERIC_WRITE | DELETE) + .share_mode(0) + .attributes(FILE_ATTRIBUTE_TEMPORARY) + .custom_flags(FILE_FLAG_DELETE_ON_CLOSE) + .open(&path) + }; + for attempt in 0..4 { + match open() { + Ok(file) => return ClaimAcquire::Acquired(Claim { _file: file }), + Err(e) if e.raw_os_error() == Some(ERROR_SHARING_VIOLATION as i32) => return ClaimAcquire::HeldElsewhere, + // A just-closed delete-on-close handle can leave a brief delete-pending window. + Err(e) if e.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) && attempt < 3 => { + std::thread::sleep(std::time::Duration::from_millis(2)); + } + Err(e) => return ClaimAcquire::Unavailable(e), + } + } + unreachable!("claim acquisition loop always returns") + } +} + +struct RunningPermit<'a> { + state: &'a (Mutex<usize>, std::sync::Condvar), +} + +impl<'a> RunningPermit<'a> { + fn enter(state: &'a (Mutex<usize>, std::sync::Condvar), most: usize) -> Self { + let mut running = state.0.lock().unwrap_or_else(|e| e.into_inner()); + while *running >= most { + running = state.1.wait(running).unwrap_or_else(|e| e.into_inner()); + } + *running += 1; + Self { state } + } +} + +impl Drop for RunningPermit<'_> { + fn drop(&mut self) { + let mut running = self.state.0.lock().unwrap_or_else(|e| e.into_inner()); + *running = running.saturating_sub(1); + self.state.1.notify_one(); + } +} + +#[cfg(test)] +mod running_permit_tests { + use super::RunningPermit; + use std::sync::{mpsc, Condvar, Mutex}; + use std::time::Duration; + + #[test] + fn unwind_releases_the_slot_and_wakes_a_waiter() { + let state = (Mutex::new(0usize), Condvar::new()); + let (started_tx, started_rx) = mpsc::channel(); + let (acquired_tx, acquired_rx) = mpsc::channel(); + std::thread::scope(|scope| { + let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let _permit = RunningPermit::enter(&state, 1); + scope.spawn(|| { + started_tx.send(()).unwrap(); + let _waiting = RunningPermit::enter(&state, 1); + acquired_tx.send(()).unwrap(); + }); + started_rx.recv().unwrap(); + panic!("simulated driver panic"); + })); + assert!(panicked.is_err()); + acquired_rx.recv_timeout(Duration::from_secs(1)).expect("waiter stayed blocked after unwind"); + }); + assert_eq!(*state.0.lock().unwrap_or_else(|e| e.into_inner()), 0); + } +} + +#[cfg(test)] +mod pipeline_claim_tests { + use super::{claim_path_for, Claim, ClaimAcquire}; + use std::io::{BufRead, BufReader, Write}; + use std::path::PathBuf; + use std::time::{Duration, SystemTime, UNIX_EPOCH}; + + struct TempDir(PathBuf); + impl TempDir { + fn new(prefix: &str) -> Self { + let nonce = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos(); + let path = std::env::temp_dir().join(format!("{prefix}-{}-{nonce}", std::process::id())); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } + } + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + struct ChildGuard(std::process::Child); + impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + + #[test] + fn claim_child_role_entrypoint() { + if std::env::var("XCL_CLAIM_TEST_ROLE").as_deref() != Ok("hold") { + return; + } + let blob = PathBuf::from(std::env::var("XCL_CLAIM_TEST_BLOB").expect("blob path")); + let _claim = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + ClaimAcquire::HeldElsewhere => panic!("unexpected contention in child"), + ClaimAcquire::Unavailable(e) => panic!("claim unavailable in child: {e}"), + }; + println!("LOCKED"); + std::io::stdout().flush().unwrap(); + std::thread::sleep(Duration::from_secs(60)); + } + + #[test] + fn claims_are_exclusive_adopt_orphans_and_report_filesystem_errors() { + let dir = TempDir::new("xcl-claim"); + let blob = dir.0.join("nested").join("one.pso"); + let first = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + _ => panic!("first claim must succeed"), + }; + assert!(claim_path_for(&blob).is_file()); + assert!(matches!(Claim::acquire(&blob), ClaimAcquire::HeldElsewhere)); + assert!(matches!(Claim::acquire(&dir.0.join("two.pso")), ClaimAcquire::Acquired(_))); + drop(first); + assert!(!claim_path_for(&blob).exists()); + + std::fs::write(claim_path_for(&blob), b"orphan from old protocol").unwrap(); + let adopted = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + _ => panic!("unlocked orphan must be adopted"), + }; + drop(adopted); + assert!(!claim_path_for(&blob).exists()); + + let file = dir.0.join("not-a-directory"); + std::fs::write(&file, b"x").unwrap(); + assert!(matches!(Claim::acquire(&file.join("bad.pso")), ClaimAcquire::Unavailable(_))); + } + + #[test] + fn forced_process_termination_releases_a_claim_immediately() { + let dir = TempDir::new("xcl-claim-kill"); + let blob = dir.0.join("driver").join("killed.pso"); + let mut child = ChildGuard(std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shaders::pipeline_claim_tests::claim_child_role_entrypoint", "--nocapture"]) + .env("XCL_CLAIM_TEST_ROLE", "hold") + .env("XCL_CLAIM_TEST_BLOB", &blob) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) + .spawn() + .unwrap()); + let mut lines = BufReader::new(child.0.stdout.take().unwrap()).lines(); + let ready = lines.by_ref().any(|line| line.is_ok_and(|line| line.trim() == "LOCKED")); + assert!(ready, "child did not acquire claim"); + assert!(matches!(Claim::acquire(&blob), ClaimAcquire::HeldElsewhere)); + + child.0.kill().unwrap(); + let _ = child.0.wait(); + assert!(!claim_path_for(&blob).exists()); + let recovered = match Claim::acquire(&blob) { + ClaimAcquire::Acquired(claim) => claim, + _ => panic!("terminated owner's claim must be free"), + }; + drop(recovered); + assert!(!claim_path_for(&blob).exists()); + } +} + /// `XCL_PIPELINE_MAX_KB`: the KiB of DXIL `--pipelines` still compiles (default 8 MiB; 0: no /// cap). Above it sit the programs whose driver compile takes tens of minutes and gigabytes — /// the > 8 MB HLSL programs DXC compiles at `-O0` (#1269) — and they hang the pass. @@ -1273,7 +1757,7 @@ mod pipeline_cap_tests { pipelines.max_dxil = dxil.len() - 1; let start = Instant::now(); - pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![] }, Some(path.clone())); + pipelines.make_with_cache_path(&recomp::pso::Compiled { dispatch_chain: None, dxil: dxil.clone(), samplers: vec![], dispatch_remap: None }, Some(path.clone())); let elapsed = start.elapsed(); let capped = pipelines.capped.load(Ordering::Relaxed); let made = pipelines.made.load(Ordering::Relaxed); @@ -1354,6 +1838,7 @@ mod pipeline_cap_tests { })), dxil: whole.clone(), samplers: vec![], + dispatch_remap: None, }; pipelines.max_dxil = max_piece; @@ -1417,8 +1902,9 @@ impl Pipelines { unsafe { let factory: IDXGIFactory6 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).map_err(|e| e.to_string())?; let sel = crate::gpu::adapter::Selector::from_env_or("auto"); - let (adapter, _) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; + let (adapter, desc) = crate::gpu::adapter::candidates(&factory, &sel).into_iter().next().ok_or_else(|| crate::gpu::adapter::no_match(&factory, &sel))?; let dev = crate::gpu::agility::create_device(&adapter, D3D_FEATURE_LEVEL_12_0).map_err(|e| e.to_string())?; + crate::hle::d3d12x::real::driver_cache::note_vendor(desc.VendorId); let most = std::env::var("XCL_PIPELINE_THREADS").ok().and_then(|v| v.parse().ok()).unwrap_or(4usize).max(1); let max_dxil = pipeline_cap_kb(std::env::var("XCL_PIPELINE_MAX_KB").ok().as_deref()).saturating_mul(1024); Ok(Pipelines { @@ -1427,10 +1913,16 @@ impl Pipelines { made: AtomicUsize::new(0), refused: AtomicUsize::new(0), reused: AtomicUsize::new(0), + created: AtomicUsize::new(0), + persistence: PersistenceCounters::default(), + persistence_warned: AtomicBool::new(false), + elsewhere: AtomicUsize::new(0), split_programs: AtomicUsize::new(0), split_pieces: AtomicUsize::new(0), + indirect_programs: AtomicUsize::new(0), capped: AtomicUsize::new(0), capped_bytes: AtomicUsize::new(0), + inflight: (Mutex::new(InflightBuilds::default()), std::sync::Condvar::new()), running: (Mutex::new(0), std::sync::Condvar::new()), most, max_dxil, @@ -1445,49 +1937,70 @@ impl Pipelines { /// dispatch-chain root signature (`.chain.pso`) as the runtime does (`dispatch_chain::build`), /// instead of the unsplit whole container. fn make(&self, c: &recomp::pso::Compiled) { - self.make_with_cache_path(c, None); + self.make_selected(c, false, None); } + #[cfg(test)] fn make_with_cache_path(&self, c: &recomp::pso::Compiled, path_override: Option<PathBuf>) { + self.make_selected(c, false, path_override); + } + + fn make_selected(&self, c: &recomp::pso::Compiled, prewarm_indirect: bool, path_override: Option<PathBuf>) { if path_override.is_none() { if let Some(chain) = c.dispatch_chain.as_deref().filter(|chain| chain.pieces.len() >= 2) { self.split_programs.fetch_add(1, Ordering::Relaxed); self.split_pieces.fetch_add(chain.pieces.len(), Ordering::Relaxed); - let workers = chain.pieces.len().min(self.most); - if workers <= 1 { - for piece in &chain.pieces { - self.make_one(piece, &c.samplers, true, None); + for &root in split_piece_roots(prewarm_indirect) { + self.make_chain_pieces(&chain.pieces, &c.samplers, root); + } + if prewarm_indirect { + self.indirect_programs.fetch_add(1, Ordering::Relaxed); + for &root in split_whole_roots(true) { + self.make_one(&c.dxil, &c.samplers, root, None); } - } else { - let next = AtomicUsize::new(0); - std::thread::scope(|s| { - for _ in 0..workers { - s.spawn(|| loop { - let i = next.fetch_add(1, Ordering::Relaxed); - let Some(piece) = chain.pieces.get(i) else { break }; - self.make_one(piece, &c.samplers, true, None); - }); - } - }); } return; } } - self.make_one(&c.dxil, &c.samplers, false, path_override); + self.make_one(&c.dxil, &c.samplers, PipelineRoot::Whole, path_override); + } + + fn make_chain_pieces(&self, pieces: &[Vec<u8>], samplers: &[recomp::pso::StaticSampler], root: PipelineRoot) { + let workers = pieces.len().min(self.most); + if workers <= 1 { + for piece in pieces { + self.make_one(piece, samplers, root, None); + } + } else { + let next = AtomicUsize::new(0); + std::thread::scope(|s| { + for _ in 0..workers { + s.spawn(|| loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some(piece) = pieces.get(i) else { break }; + self.make_one(piece, samplers, root, None); + }); + } + }); + } } - fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], chained: bool, path_override: Option<PathBuf>) { + fn make_one(&self, dxil: &[u8], samplers: &[recomp::pso::StaticSampler], root: PipelineRoot, path_override: Option<PathBuf>) { use windows::Win32::Graphics::Direct3D12::*; - let key: (bool, Vec<u32>) = (chained, samplers.iter().flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])).collect()); + let sampler_words: Vec<u32> = samplers + .iter() + .flat_map(|(w, cmp)| w.iter().copied().chain([*cmp as u32])) + .collect(); + let key = (root, sampler_words.clone()); let rs = { let mut g = self.signatures.lock().unwrap(); match g.get(&key) { Some(rs) => rs.clone(), None => { - let created = if chained { - recomp::pso::dispatch_chain_root_signature(&self.dev, samplers) - } else { - recomp::pso::abi_root_signature_with(&self.dev, true, samplers) + let created = match root { + PipelineRoot::Whole => recomp::pso::abi_root_signature_with(&self.dev, true, samplers), + PipelineRoot::DirectChain => recomp::pso::dispatch_chain_root_signature(&self.dev, samplers), + PipelineRoot::IndirectChain => recomp::pso::dispatch_chain_indirect_root_signature(&self.dev, samplers), }; match created { Ok(rs) => { @@ -1511,11 +2024,28 @@ impl Pipelines { let path = path_override.or_else(|| { #[cfg(test)] if let Some(dir) = self.cache_dir.as_deref() { - return Some(dir.join(driver_cache::name_for(dxil, desc.Flags.0, chained))); + return Some(dir.join(match root { + PipelineRoot::Whole => driver_cache::name_for_root(dxil, desc.Flags.0, false, samplers), + PipelineRoot::DirectChain => driver_cache::name_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, desc.NodeMask, + ), + PipelineRoot::IndirectChain => driver_cache::name_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, desc.NodeMask, + ), + })); + } + match root { + PipelineRoot::Whole => driver_cache::path_for_root(dxil, desc.Flags.0, false, samplers), + PipelineRoot::DirectChain => driver_cache::path_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::DirectConstants, samplers, desc.NodeMask, + ), + PipelineRoot::IndirectChain => driver_cache::path_for_chain_root_node( + dxil, desc.Flags.0, driver_cache::ChainRoot::IndirectCbv, samplers, desc.NodeMask, + ), } - driver_cache::path_for(dxil, desc.Flags.0, chained) }); - let cached = path.as_deref().and_then(driver_cache::load); + let mut loaded = path.as_deref().and_then(driver_cache::load); + let mut cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); let over_cap = self.max_dxil != 0 && dxil.len() > self.max_dxil; // over the cap and no blob from an earlier run: the driver's compile of this one takes // tens of minutes and gigabytes; the pass finishes without it, and the runtime builds it @@ -1526,13 +2056,41 @@ impl Pipelines { drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); return; } - { - let mut n = self.running.0.lock().unwrap(); - while *n >= self.most { - n = self.running.1.wait(n).unwrap(); + let identity = PipelineCacheIdentity::new(dxil, desc.Flags.0, desc.NodeMask, root, sampler_words, path.clone()); + let _inflight = InflightGuard::enter(&self.inflight, identity); + // A valid blob may be used by many processes, but validation itself can fall through to + // a full driver compile when the blob is stale. Claim before either path so only one + // process can validate/rebuild/remove this exact cache entry at a time. + let _claim = match path.as_deref() { + Some(path) => match Claim::acquire(path) { + ClaimAcquire::Acquired(claim) => Some(claim), + ClaimAcquire::HeldElsewhere => { + self.elsewhere.fetch_add(1, Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; + } + ClaimAcquire::Unavailable(e) => { + static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + if !WARNED.swap(true, Ordering::Relaxed) { + crate::xlog_warn!("Shader preparation: cannot coordinate claim for {}: {e}; building locally", path.display()); + } + None + } + }, + None => None, + }; + if _claim.is_some() { + // The previous owner can publish and close between our first lookup and OPEN_ALWAYS. + loaded = path.as_deref().and_then(driver_cache::load); + cached = loaded.as_ref().map(driver_cache::LoadedBlob::shared); + if cached.is_none() && over_cap { + self.capped.fetch_add(1, Ordering::Relaxed); + self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); + drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); + return; } - *n += 1; } + let _permit = RunningPermit::enter(&self.running, self.most); let from_cache = cached.as_ref().and_then(|bytes| { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE { pCachedBlob: bytes.as_ptr().cast(), CachedBlobSizeInBytes: bytes.len() }; // a driver that cannot use the blob may compile from the DXIL itself and still @@ -1543,12 +2101,12 @@ impl Pipelines { }); // A stale blob is not a usable cache hit. Do not let its presence bypass the offline // size cap and start the expensive uncached driver compile. - if cached.is_some() && from_cache.is_none() && over_cap { - if let Some(path) = path.as_deref() { - let _ = std::fs::remove_file(path); + if cached.is_some() && from_cache.is_none() { + if let Some(loaded) = loaded.take() { + let _ = loaded.invalidate(); } - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); + } + if cached.is_some() && from_cache.is_none() && over_cap { self.capped.fetch_add(1, Ordering::Relaxed); self.capped_bytes.fetch_add(dxil.len(), Ordering::Relaxed); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); @@ -1560,19 +2118,35 @@ impl Pipelines { } else { desc.CachedPSO = D3D12_CACHED_PIPELINE_STATE::default(); let pso = unsafe { self.dev.CreateComputePipelineState::<ID3D12PipelineState>(&desc) }; - if let (Some(path), Ok(pso)) = (path.as_deref(), &pso) { - if let Ok(blob) = unsafe { pso.GetCachedBlob() } { - let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>(); - let len = unsafe { blob.GetBufferSize() }; - if !bytes.is_null() && len != 0 { - driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }); + let persistence = pso.as_ref().ok().map(|pso| match path.as_deref() { + None => PersistenceOutcome::Disabled, + Some(path) => match unsafe { pso.GetCachedBlob() } { + Ok(blob) => { + let bytes = unsafe { blob.GetBufferPointer() }.cast::<u8>(); + let len = unsafe { blob.GetBufferSize() }; + if bytes.is_null() || len == 0 { + PersistenceOutcome::BlobUnavailable + } else if driver_cache::write(path, unsafe { std::slice::from_raw_parts(bytes, len) }) { + PersistenceOutcome::Saved + } else { + PersistenceOutcome::WriteFailed + } + } + Err(_) => PersistenceOutcome::BlobUnavailable, + }, + }); + record_fresh_creation(persistence, &self.created, &self.persistence); + if let Some(outcome) = persistence { + if matches!(outcome, PersistenceOutcome::BlobUnavailable | PersistenceOutcome::WriteFailed) + && !self.persistence_warned.swap(true, Ordering::Relaxed) + { + if let Some(path) = path.as_deref() { + crate::xlog_warn!("Shader preparation: failed to persist driver blob {}; this pipeline will be rebuilt on the next run", path.display()); } } } pso }; - *self.running.0.lock().unwrap() -= 1; - self.running.1.notify_one(); drop(std::mem::ManuallyDrop::into_inner(desc.pRootSignature)); let done = match r { Ok(_) => self.made.fetch_add(1, Ordering::Relaxed) + 1, @@ -1590,7 +2164,28 @@ fn used_compute(blob: &[u8], used: &std::collections::HashSet<u64>) -> bool { used.contains(&crate::hle::d3d12x::real::shaders_key(&[blob.to_vec()])) } -fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, only: Option<&str>, pipelines: bool, used: Option<&std::collections::HashSet<u64>>, t0: std::time::Instant) -> i32 { +fn used_indirect_split(blob: &[u8], used: &std::collections::HashSet<u64>) -> bool { + used.contains(&crate::gpu::shader::fnv64(blob)) +} + +/// Standalone graphics variants whose runtime cache keys can be known without a pipeline pairing. +/// Runtime selection also uses the first hardware stage of the first matching FSSM (4: VS, 5: PS). +fn standalone_graphics_variants(blob: &[u8], sh: &xbox::XboxShader, split: bool, windows: u32) -> Vec<(recomp::pso::Stage, u32, bool, u32)> { + [(recomp::pso::Stage::Vertex, 4), (recomp::pso::Stage::Pixel, 5)] + .into_iter() + .filter(|&(stage, hw)| { + let Some(f) = sh.fssm.iter().find(|f| f.stages.first().is_some_and(|s| s.hw == hw)) else { return false }; + matches!((recomp::interface(blob, sh, f), stage), (Some(recomp::Mode::Vertex(_)), recomp::pso::Stage::Vertex) | (Some(recomp::Mode::Pixel(_)), recomp::pso::Stage::Pixel)) + }) + .map(|(stage, _)| (stage, 0, split, windows)) + .collect() +} + +fn precompile( + input: &Input, limit: usize, windows: u32, split: Option<bool>, only: Option<&str>, pipelines: bool, + used: Option<&std::collections::HashSet<u64>>, indirect: Option<&std::collections::HashSet<u64>>, + t0: std::time::Instant, +) -> i32 { let pipelines = if pipelines { match Pipelines::new() { Ok(p) => Some(p), @@ -1611,6 +2206,9 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on if let Some(u) = used { println!("--used-only: {} pipelines earlier runs used (used-pipelines.txt); compute programs of other pipelines are passed over", u.len()); } + if let Some(i) = indirect { + println!("--used-only: {} split programs earlier runs dispatched indirectly get direct and indirect pieces/whole", i.len()); + } // the compiles run on the DXC pool; these threads translate and keep it fed let threads = recomp::dxc::compile_threads() + 2; // no title runs: only a little commit is kept free besides the compiles @@ -1623,7 +2221,7 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on "precompiling {n} shaders into {} ({} compile threads; {} memory windows{}{})", recomp::dxc::cache_dir().display(), recomp::dxc::compile_threads(), - windows & !recomp::HEAP_WINDOWS, + windows & !(recomp::HEAP_WINDOWS | recomp::HEAP_FLAT), if windows & recomp::HEAP_WINDOWS != 0 { " from the descriptor heap" } else { "" }, if split { ", split wave64 for a GPU with 32-lane waves" } else { "" } ); @@ -1652,7 +2250,11 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on match recomp::pso::console_to_dxil_in(&blob, recomp::pso::Stage::Compute, 0, split, windows) { Ok(c) => { if let Some(p) = pipelines { - p.make(&c); + if indirect.is_some_and(|i| used_indirect_split(&blob, i)) { + p.make_selected(&c, true, None); + } else { + p.make(&c); + } } compiled.fetch_add(1, Ordering::Relaxed) } @@ -1670,11 +2272,22 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on } continue; } + for (stage, sampler_base, split, windows) in standalone_graphics_variants(&blob, &sh, graphics_split, windows) { + match recomp::pso::console_to_dxil_in(&blob, stage, sampler_base, split, windows) { + Ok(_) => compiled.fetch_add(1, Ordering::Relaxed), + Err(e) => { + let mut g = errors.lock().unwrap(); + if g.len() < 10 { + g.push(format!("{name}: {}", e.lines().find(|l| l.contains("error")).unwrap_or(e.lines().next().unwrap_or("")))); + } + failed.fetch_add(1, Ordering::Relaxed) + } + }; + } for f in &sh.fssm { let Some(mode) = recomp::interface(&blob, &sh, f) else { continue }; let jobs: Vec<(&str, Option<String>)> = match &mode { - recomp::Mode::Vertex(_) => vec![("vs_6_6", None)], - recomp::Mode::Pixel(_) => vec![("ps_6_6", None)], + recomp::Mode::Vertex(_) | recomp::Mode::Pixel(_) => continue, recomp::Mode::Compute(_) => vec![("cs_6_6", None)], recomp::Mode::Mesh(ms) => vec![("cs_6_6", None), ("ms_6_6", Some(recomp::mesh_passthrough(ms)))], _ => { @@ -1728,10 +2341,32 @@ fn precompile(input: &Input, limit: usize, windows: u32, split: Option<bool>, on if let Some(p) = pipelines { println!("pipelines made on the GPU {}, refused {}", p.made.load(Ordering::Relaxed), p.refused.load(Ordering::Relaxed)); println!("pipelines loaded from the driver cache {}", p.reused.load(Ordering::Relaxed)); + let created = p.created.load(Ordering::Relaxed); + let persistence = p.persistence.snapshot(); + println!( + "fresh GPU pipeline creations {created}: driver blobs saved {}, unavailable {}, persistence disabled {}, cache writes failed {}", + persistence.saved, persistence.blob_unavailable, persistence.disabled, persistence.write_failed, + ); + debug_assert_eq!(persistence.total(), created); + debug_assert_eq!( + created + p.reused.load(Ordering::Relaxed), + p.made.load(Ordering::Relaxed), + ); + if persistence.write_failed != 0 { + println!("pipeline driver-cache writes failed {}", persistence.write_failed); + } + let elsewhere = p.elsewhere.load(Ordering::Relaxed); + if elsewhere != 0 { + println!("pipelines left to another preparation process {elsewhere}"); + } let split_programs = p.split_programs.load(Ordering::Relaxed); if split_programs != 0 { println!("split compute programs: {} ({} pieces)", split_programs, p.split_pieces.load(Ordering::Relaxed)); } + let indirect_programs = p.indirect_programs.load(Ordering::Relaxed); + if indirect_programs != 0 { + println!("indirect split programs (direct and indirect pieces/whole): {indirect_programs}"); + } let capped = p.capped.load(Ordering::Relaxed); if capped != 0 { println!("pipelines over the {} MiB DXIL cap, left to the runtime: {} ({} MiB of DXIL; XCL_PIPELINE_MAX_KB)", p.max_dxil >> 20, capped, p.capped_bytes.load(Ordering::Relaxed) >> 20); @@ -2070,6 +2705,30 @@ fn print(path: &Path, what: &str, agg: Agg, top: usize, json: bool, t0: std::tim #[cfg(test)] mod tests { + /// Offline commands and the runtime must use the same cache identity. Environment switches + /// are process-global (`OnceLock`), so exercise each setting in a fresh test process. + #[test] + fn precompile_windows_are_the_runtimes() { + use crate::gpu::recomp::{pso, HEAP_FLAT, HEAP_WINDOWS}; + const RUN: &str = "XCL_TEST_PRECOMPILE_WINDOWS"; + if let Ok(want) = std::env::var(RUN) { + assert_eq!(super::runtime_windows(4), pso::windows_for(4)); + assert_eq!(super::runtime_windows(4), want.parse::<u32>().unwrap()); + return; + } + for (flat, want) in [("1", 4 | HEAP_WINDOWS | HEAP_FLAT), ("0", 4 | HEAP_WINDOWS)] { + let out = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "shaders::tests::precompile_windows_are_the_runtimes", "--nocapture"]) + .env(RUN, want.to_string()) + .env("XCL_HEAP_WINDOWS", "1") + .env("XCL_HEAP_FLAT", flat) + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success() && stdout.contains("1 passed"), "XCL_HEAP_FLAT={flat}: {stdout}\n{}", String::from_utf8_lossy(&out.stderr)); + } + } + /// `--used-only` keeps a compute program exactly when the runtime noted its pipeline: the /// key of a pipeline of that one shader, as `real::shaders_key` makes it. #[test] @@ -2083,6 +2742,9 @@ mod tests { ", crate::hle::d3d12x::real::shaders_key(&[b.clone()])); let keys: std::collections::HashSet<u64> = text.lines().filter_map(|l| u64::from_str_radix(l.trim(), 16).ok()).collect(); assert!(super::used_compute(&b, &keys)); + let indirect: std::collections::HashSet<u64> = [crate::gpu::shader::fnv64(&a)].into(); + assert!(super::used_indirect_split(&a, &indirect)); + assert!(!super::used_indirect_split(&b, &indirect)); } use super::*; @@ -2096,6 +2758,27 @@ mod tests { sample(5, &[compute]) } + #[test] + fn graphics_precompile_variants_match_runtime_stage_and_key_inputs() { + let vs_blob = sample(1, &[fssm(&CODE, &[(4, 0)]), fssm(&CODE, &[(4, 0)])]); + let ps_blob = sample(0, &[fssm(&CODE, &[(5, 1)])]); + let vs = xbox::parse(&vs_blob).unwrap(); + let ps = xbox::parse(&ps_blob).unwrap(); + assert_eq!( + standalone_graphics_variants(&vs_blob, &vs, true, 4 | recomp::HEAP_WINDOWS), + vec![(recomp::pso::Stage::Vertex, 0, true, 4 | recomp::HEAP_WINDOWS)], + "duplicate FSSMs still warm the one runtime-selected VS key", + ); + assert_eq!( + standalone_graphics_variants(&ps_blob, &ps, false, 1), + vec![(recomp::pso::Stage::Pixel, 0, false, 1)], + "the PS key keeps the exact split/windows and the only knowable sampler base", + ); + let es_blob = sample(1, &[fssm(&CODE, &[(3, 0), (4, 0)])]); + let es = xbox::parse(&es_blob).unwrap(); + assert!(standalone_graphics_variants(&es_blob, &es, false, 1).is_empty(), "runtime only classifies the first hardware stage"); + } + #[test] fn record_hash_is_strict_hex() { assert_eq!(parse_record_hash("0x0123aB").unwrap(), 0x123AB); diff --git a/crates/xcl/src/stall.rs b/crates/xcl/src/stall.rs new file mode 100644 index 0000000000..219ce60ba4 --- /dev/null +++ b/crates/xcl/src/stall.rs @@ -0,0 +1,391 @@ +//! Opt-in attribution of time spent in coarse runtime operations. +//! +//! A disabled span is one relaxed atomic load. In particular, it does not read the clock, allocate, +//! lock, or update a counter. High-frequency command-recording spans have a separate detail switch, +//! so enabling coarse attribution does not turn them on. + +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering}; +use std::sync::{Mutex, OnceLock}; +use std::time::Instant; + +pub const HISTOGRAM_BUCKETS: usize = 64; +pub const SLOW_SPAN_CAPACITY: usize = 128; +pub const SLOW_SPAN_NS: u64 = 50_000_000; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +pub enum StallKind { + ShaderTranslation, + DxcQueue, + DxcCompile, + PipelineWait, + DriverCompileGate, + DriverCompile, + SubmitPreparation, + MemorySynchronization, + Residency, + CacheIo, + LockContention, + GpuWait, + Present, + DirectStorage, + DetailDraw, + DetailDispatch, + DetailBind, + DetailViewDescriptor, + DetailBarrier, + DetailCopy, + DetailListLifecycle, +} + +impl StallKind { + pub const ALL: [Self; 21] = [ + Self::ShaderTranslation, + Self::DxcQueue, + Self::DxcCompile, + Self::PipelineWait, + Self::DriverCompileGate, + Self::DriverCompile, + Self::SubmitPreparation, + Self::MemorySynchronization, + Self::Residency, + Self::CacheIo, + Self::LockContention, + Self::GpuWait, + Self::Present, + Self::DirectStorage, + Self::DetailDraw, + Self::DetailDispatch, + Self::DetailBind, + Self::DetailViewDescriptor, + Self::DetailBarrier, + Self::DetailCopy, + Self::DetailListLifecycle, + ]; + + const fn index(self) -> usize { + self as usize + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AggregateSnapshot { + pub kind: StallKind, + pub count: u64, + pub total_ns: u64, + pub max_ns: u64, + /// Duration counts in base-2 nanosecond buckets. Bucket zero also contains zero-duration spans. + pub histogram: [u64; HISTOGRAM_BUCKETS], +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct SlowSpan { + pub sequence: u64, + pub kind: StallKind, + pub started_ns: u64, + pub duration_ns: u64, +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct Snapshot { + pub aggregates: Vec<AggregateSnapshot>, + pub slow_spans: Vec<SlowSpan>, +} + +struct Aggregate { + count: AtomicU64, + total_ns: AtomicU64, + max_ns: AtomicU64, + histogram: [AtomicU64; HISTOGRAM_BUCKETS], +} + +impl Aggregate { + const fn new() -> Self { + Self { + count: AtomicU64::new(0), + total_ns: AtomicU64::new(0), + max_ns: AtomicU64::new(0), + histogram: [const { AtomicU64::new(0) }; HISTOGRAM_BUCKETS], + } + } + + fn record(&self, duration_ns: u64) { + self.count.fetch_add(1, Ordering::Relaxed); + self.total_ns.fetch_add(duration_ns, Ordering::Relaxed); + self.max_ns.fetch_max(duration_ns, Ordering::Relaxed); + self.histogram[histogram_bucket(duration_ns)].fetch_add(1, Ordering::Relaxed); + } + + fn snapshot(&self, kind: StallKind) -> AggregateSnapshot { + AggregateSnapshot { + kind, + count: self.count.load(Ordering::Relaxed), + total_ns: self.total_ns.load(Ordering::Relaxed), + max_ns: self.max_ns.load(Ordering::Relaxed), + histogram: std::array::from_fn(|i| self.histogram[i].load(Ordering::Relaxed)), + } + } +} + +const fn histogram_bucket(duration_ns: u64) -> usize { + if duration_ns == 0 { 0 } else { (u64::BITS - 1 - duration_ns.leading_zeros()) as usize } +} + +struct SlowSpans { + next_sequence: u64, + spans: VecDeque<SlowSpan>, +} + +struct Recorder { + enabled: AtomicBool, + detail_enabled: AtomicBool, + /// First title thread observed submitting command lists; zero until then. + submitter: AtomicU32, + aggregates: [Aggregate; StallKind::ALL.len()], + slow_spans: Mutex<SlowSpans>, +} + +trait Clock: Sync { + fn now_ns(&self) -> u64; +} + +impl Recorder { + const fn new() -> Self { + Self { + enabled: AtomicBool::new(false), + detail_enabled: AtomicBool::new(false), + submitter: AtomicU32::new(0), + aggregates: [const { Aggregate::new() }; StallKind::ALL.len()], + slow_spans: Mutex::new(SlowSpans { next_sequence: 0, spans: VecDeque::new() }), + } + } + + fn enable(&self) { + self.enabled.store(true, Ordering::Relaxed); + } + + fn enable_detail(&self) { + self.enable(); + self.detail_enabled.store(true, Ordering::Relaxed); + } + + fn note_submitter(&self, thread: u32) { + let _ = self.submitter.compare_exchange(0, thread, Ordering::Relaxed, Ordering::Relaxed); + } + + #[inline] + fn start_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock) -> Option<Span<'a>> { + if !self.enabled.load(Ordering::Relaxed) { + return None; + } + Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) + } + + #[inline] + fn start_detail_with<'a>(&'a self, kind: StallKind, clock: &'a dyn Clock, thread: u32) -> Option<Span<'a>> { + if !self.detail_enabled.load(Ordering::Relaxed) || self.submitter.load(Ordering::Relaxed) != thread { + return None; + } + Some(Span { recorder: self, kind, started_ns: clock.now_ns(), clock, finished: false }) + } + + fn record(&self, kind: StallKind, started_ns: u64, duration_ns: u64) { + self.aggregates[kind.index()].record(duration_ns); + if duration_ns < SLOW_SPAN_NS { + return; + } + let mut slow = self.slow_spans.lock().unwrap_or_else(|e| e.into_inner()); + let span = SlowSpan { + sequence: slow.next_sequence, + kind, + started_ns, + duration_ns, + }; + slow.next_sequence = slow.next_sequence.wrapping_add(1); + if slow.spans.len() == SLOW_SPAN_CAPACITY { + slow.spans.pop_front(); + } + slow.spans.push_back(span); + } + + fn snapshot(&self) -> Snapshot { + let aggregates = StallKind::ALL.iter().map(|&kind| self.aggregates[kind.index()].snapshot(kind)).collect(); + let slow_spans = self.slow_spans.lock().unwrap_or_else(|e| e.into_inner()).spans.iter().copied().collect(); + Snapshot { aggregates, slow_spans } + } +} + +pub struct Span<'a> { + recorder: &'a Recorder, + kind: StallKind, + started_ns: u64, + clock: &'a dyn Clock, + finished: bool, +} + +impl Drop for Span<'_> { + fn drop(&mut self) { + if !self.finished { + self.finished = true; + self.recorder.record(self.kind, self.started_ns, self.clock.now_ns().saturating_sub(self.started_ns)); + } + } +} + +static RECORDER: Recorder = Recorder::new(); +static CLOCK: SystemClock = SystemClock; + +pub fn enable() { + RECORDER.enable(); +} + +pub fn enable_detail() { + RECORDER.enable_detail(); +} + +/// Mark the first title thread that submits command lists as the thread detailed spans describe. +pub fn note_submitter() { + RECORDER.note_submitter(current_thread()); +} + +#[inline] +pub fn span(kind: StallKind) -> Option<Span<'static>> { + RECORDER.start_with(kind, &CLOCK) +} + +/// A high-frequency command-recording span, enabled only by `XCL_STALL_TRACE_DETAIL`. +#[inline] +pub fn detail_span(kind: StallKind) -> Option<Span<'static>> { + if !RECORDER.detail_enabled.load(Ordering::Relaxed) { + return None; + } + RECORDER.start_detail_with(kind, &CLOCK, current_thread()) +} + +/// Like [`detail_span`], without even consulting the detail switch when `on` is false. +#[inline] +pub fn detail_span_if(on: bool, kind: StallKind) -> Option<Span<'static>> { + on.then(|| detail_span(kind)).flatten() +} + +pub fn snapshot() -> Option<Snapshot> { + RECORDER.enabled.load(Ordering::Relaxed).then(|| RECORDER.snapshot()) +} + +struct SystemClock; + +fn current_thread() -> u32 { + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } +} + +impl Clock for SystemClock { + fn now_ns(&self) -> u64 { + static ORIGIN: OnceLock<Instant> = OnceLock::new(); + ORIGIN.get_or_init(Instant::now).elapsed().as_nanos().min(u64::MAX as u128) as u64 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::atomic::{AtomicU64, AtomicUsize}; + + struct TestClock { + now: AtomicU64, + calls: AtomicUsize, + } + + impl TestClock { + fn new(now: u64) -> Self { + Self { now: AtomicU64::new(now), calls: AtomicUsize::new(0) } + } + } + + impl Clock for TestClock { + fn now_ns(&self) -> u64 { + self.calls.fetch_add(1, Ordering::Relaxed); + self.now.load(Ordering::Relaxed) + } + } + + #[test] + fn disabled_span_does_not_read_the_clock_or_record() { + let recorder = Recorder::new(); + let clock = TestClock::new(10); + assert!(recorder.start_with(StallKind::DxcCompile, &clock).is_none()); + assert_eq!(clock.calls.load(Ordering::Relaxed), 0); + assert_eq!(recorder.snapshot().aggregates[StallKind::DxcCompile.index()].count, 0); + } + + #[test] + fn coarse_tracing_does_not_enable_detail_spans() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(10); + recorder.note_submitter(7); + assert!(recorder.start_detail_with(StallKind::DetailDraw, &clock, 7).is_none()); + assert_eq!(clock.calls.load(Ordering::Relaxed), 0); + + recorder.enable_detail(); + assert!(recorder.start_detail_with(StallKind::DetailDraw, &clock, 8).is_none()); + let span = recorder.start_detail_with(StallKind::DetailDraw, &clock, 7).unwrap(); + clock.now.store(42, Ordering::Relaxed); + drop(span); + let aggregate = &recorder.snapshot().aggregates[StallKind::DetailDraw.index()]; + assert_eq!((aggregate.count, aggregate.total_ns), (1, 32)); + } + + #[test] + fn descriptor_detail_is_attributed_only_to_the_submitter() { + let recorder = Recorder::new(); + recorder.enable_detail(); + recorder.note_submitter(7); + let clock = TestClock::new(100); + assert!(recorder.start_detail_with(StallKind::DetailViewDescriptor, &clock, 8).is_none()); + let span = recorder.start_detail_with(StallKind::DetailViewDescriptor, &clock, 7).unwrap(); + clock.now.store(145, Ordering::Relaxed); + drop(span); + let aggregate = &recorder.snapshot().aggregates[StallKind::DetailViewDescriptor.index()]; + assert_eq!((aggregate.count, aggregate.total_ns), (1, 45)); + } + + #[test] + fn a_span_updates_its_aggregate_and_log2_bucket() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(10); + let span = recorder.start_with(StallKind::PipelineWait, &clock).unwrap(); + clock.now.store(10 + 1024, Ordering::Relaxed); + drop(span); + + let aggregate = &recorder.snapshot().aggregates[StallKind::PipelineWait.index()]; + assert_eq!((aggregate.count, aggregate.total_ns, aggregate.max_ns), (1, 1024, 1024)); + assert_eq!(aggregate.histogram[10], 1); + assert_eq!(aggregate.histogram.iter().sum::<u64>(), 1); + assert_eq!(clock.calls.load(Ordering::Relaxed), 2); + } + + #[test] + fn only_slow_spans_enter_the_bounded_ring() { + let recorder = Recorder::new(); + recorder.enable(); + let clock = TestClock::new(0); + for i in 0..SLOW_SPAN_CAPACITY + 3 { + clock.now.store(i as u64, Ordering::Relaxed); + let span = recorder.start_with(StallKind::GpuWait, &clock).unwrap(); + clock.now.store(i as u64 + SLOW_SPAN_NS, Ordering::Relaxed); + drop(span); + } + clock.now.store(1_000_000_000, Ordering::Relaxed); + let fast = recorder.start_with(StallKind::Present, &clock).unwrap(); + clock.now.store(1_000_000_001, Ordering::Relaxed); + drop(fast); + + let snapshot = recorder.snapshot(); + assert_eq!(snapshot.slow_spans.len(), SLOW_SPAN_CAPACITY); + assert_eq!(snapshot.slow_spans[0].sequence, 3); + assert!(snapshot.slow_spans.iter().all(|span| span.kind == StallKind::GpuWait)); + assert_eq!(snapshot.aggregates[StallKind::Present.index()].count, 1); + } +} diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 new file mode 100644 index 0000000000..cee046af68 --- /dev/null +++ b/scripts/perf-compare.ps1 @@ -0,0 +1,488 @@ +# Compare two version-1 perf-run artifact folders without changing either one. Concise text goes +# to the host; the success stream is one machine-readable JSON document. +param( + [Parameter(Mandatory = $true)][string]$Baseline, + [Parameter(Mandatory = $true)][string]$Candidate +) +$ErrorActionPreference = 'Stop' + +function Read-Json([string]$Path) { + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "missing artifact: $Path" } + try { + return Get-Content -LiteralPath $Path -Raw -Encoding utf8 | ConvertFrom-Json + } catch { + throw "invalid JSON in $($Path): $($_.Exception.Message)" + } +} + +function Has-Property($Object, [string]$Name) { + return $null -ne $Object -and $null -ne $Object.PSObject.Properties[$Name] +} + +function Require-Same-Property($Before, $After, [string]$Name, [string]$Description) { + $beforeHas = Has-Property $Before $Name + $afterHas = Has-Property $After $Name + if ($beforeHas -ne $afterHas) { throw "$Description differs; runs are incomparable" } + if ($beforeHas) { + $beforeValue = $Before.$Name | ConvertTo-Json -Compress -Depth 6 + $afterValue = $After.$Name | ConvertTo-Json -Compress -Depth 6 + if ($beforeValue -ne $afterValue) { throw "$Description differs; runs are incomparable" } + } +} + +function Read-Manifest([string]$Root, [string]$Side) { + $manifest = Read-Json (Join-Path $Root 'manifest.json') + if ($manifest.schema -ne 'xcl-perf-run' -or [int]$manifest.version -ne 1) { + throw "$Side has unsupported manifest schema/version" + } + if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { + throw "$Side is not a clean release run" + } + if (Has-Property $manifest.build 'cargo_features') { + $features = @($manifest.build.cargo_features) + [string[]]$canonical = @($features | ForEach-Object { [string]$_ }) + [Array]::Sort($canonical, [StringComparer]::Ordinal) + $seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + $malformedFeature = $false + foreach ($feature in $features) { + if ([string]::IsNullOrWhiteSpace([string]$feature) -or -not $seen.Add([string]$feature)) { + $malformedFeature = $true + } + } + if ($malformedFeature -or ($features -join ',') -cne ($canonical -join ',')) { + throw "$Side has malformed Cargo features" + } + } + if (Has-Property $manifest.build 'executable_sha256') { + if ([string]$manifest.build.executable_sha256 -cnotmatch '^[0-9a-f]{64}$') { + throw "$Side has malformed executable identity" + } + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.commit) -or -not (Has-Property $manifest 'environment')) { + throw "$Side manifest is missing commit/environment" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id)) { + throw "$Side has no workload_id" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id_algorithm) -or + -not (Has-Property $manifest 'workload_id_version') -or ([int]$manifest.workload_id_version -lt 1)) { + throw "$Side has no valid workload identity algorithm/version" + } + $labels = @($manifest.run_order) + if ($labels.Count -ne 2 -or $labels[0] -ne 'xcl-cold' -or $labels[1] -ne 'xcl-warm') { + throw "$Side run_order must be xcl-cold, xcl-warm" + } + $runs = @($manifest.runs) + if ($runs.Count -ne 2) { throw "$Side must contain exactly two run records" } + for ($i = 0; $i -lt 2; $i++) { + if ([int]$runs[$i].order -ne $i + 1 -or $runs[$i].cache_state -ne $labels[$i]) { + throw "$Side run record $($i + 1) does not match run_order" + } + if (-not (Has-Property $runs[$i] 'duration_requested_seconds') -or $null -eq $runs[$i].duration_requested_seconds) { + throw "$Side run record $($i + 1) has no requested duration" + } + } + return $manifest +} + +function Read-Stalls([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) + if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { + return [ordered]@{ status = 'missing_report'; aggregates = @{} } + } + $json = Read-Json $report + if (-not (Has-Property $json 'stalls') -or $null -eq $json.stalls) { + return [ordered]@{ status = 'missing_stalls'; aggregates = @{} } + } + if ([int]$json.stalls.version -ne 1) { throw "unsupported stall summary in $report" } + $aggregates = @{} + foreach ($aggregate in @($json.stalls.aggregates)) { + $kind = [string]$aggregate.kind + if ([string]::IsNullOrWhiteSpace($kind) -or $aggregates.ContainsKey($kind)) { + throw "invalid or duplicate stall kind in $report" + } + $aggregates[$kind] = $aggregate + } + return [ordered]@{ status = 'present'; aggregates = $aggregates } +} + +function Read-Nonnegative-Integer($Object, [string]$Name, [string]$Context) { + if (-not (Has-Property $Object $Name) -or $null -eq $Object.$Name -or + $Object.$Name -is [bool] -or $Object.$Name -is [string]) { + throw "malformed $Context counter: $Name" + } + try { $value = [decimal]$Object.$Name } catch { throw "malformed $Context counter: $Name" } + if ($value -lt 0 -or $value -ne [decimal]::Truncate($value) -or + $value -gt [decimal][uint64]::MaxValue) { + throw "malformed $Context counter: $Name" + } + return $value +} + +function Read-Nonnegative-Number($Object, [string]$Name, [string]$Context) { + if (-not (Has-Property $Object $Name) -or $null -eq $Object.$Name -or + $Object.$Name -is [bool] -or $Object.$Name -is [string]) { + throw "malformed $Context value: $Name" + } + try { $value = [decimal]$Object.$Name } catch { throw "malformed $Context value: $Name" } + if ($value -lt 0) { throw "malformed $Context value: $Name" } + return $value +} + +function Read-SubmissionTiming([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) + if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { + return [ordered]@{ status = 'missing_report'; counters = $null; histogram_log2_ns = $null } + } + $json = Read-Json $report + if (-not (Has-Property $json 'd3d12') -or $null -eq $json.d3d12) { + return [ordered]@{ status = 'missing_d3d12'; counters = $null; histogram_log2_ns = $null } + } + $legacyNames = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists') + $extendedNames = @('submission_total_ns', 'submission_mean_ms', 'submission_p95_upper_ms', + 'submission_p99_upper_ms', 'submission_histogram_log2_ns') + $present = @($legacyNames | Where-Object { (Has-Property $json.d3d12 $_) -and $null -ne $json.d3d12.$_ }) + $extendedPresent = @($extendedNames | Where-Object { (Has-Property $json.d3d12 $_) -and $null -ne $json.d3d12.$_ }) + if ($present.Count -eq 0) { + if ($extendedPresent.Count -ne 0) { throw "incomplete submission timing in $report" } + return [ordered]@{ status = 'missing_metrics'; counters = $null; histogram_log2_ns = $null } + } + if ($present.Count -ne $legacyNames.Count) { throw "incomplete submission timing in $report" } + $counters = [ordered]@{ + submissions = Read-Nonnegative-Integer $json.d3d12 'submissions' "submission timing in $report" + slowest_submission_ms = Read-Nonnegative-Number $json.d3d12 'slowest_submission_ms' "submission timing in $report" + slowest_submission_lists = Read-Nonnegative-Integer $json.d3d12 'slowest_submission_lists' "submission timing in $report" + } + if ($extendedPresent.Count -eq 0) { + return [ordered]@{ status = 'present_legacy'; counters = $counters; histogram_log2_ns = $null } + } + if ($extendedPresent.Count -ne $extendedNames.Count) { throw "incomplete extended submission timing in $report" } + $counters['submission_total_ns'] = Read-Nonnegative-Integer $json.d3d12 'submission_total_ns' "submission timing in $report" + $counters['submission_mean_ms'] = Read-Nonnegative-Number $json.d3d12 'submission_mean_ms' "submission timing in $report" + $counters['submission_p95_upper_ms'] = Read-Nonnegative-Number $json.d3d12 'submission_p95_upper_ms' "submission timing in $report" + $counters['submission_p99_upper_ms'] = Read-Nonnegative-Number $json.d3d12 'submission_p99_upper_ms' "submission timing in $report" + $histogram = @($json.d3d12.submission_histogram_log2_ns) + if ($histogram.Count -ne 64) { throw "malformed submission timing histogram in $report" } + $histogram = @($histogram | ForEach-Object { + $value = [pscustomobject]@{ value = $_ } + Read-Nonnegative-Integer $value 'value' "submission timing histogram in $report" + }) + $histogramCount = [decimal]0 + foreach ($count in $histogram) { $histogramCount += $count } + if ($histogramCount -ne $counters.submissions) { throw "submission timing histogram count differs in $report" } + return [ordered]@{ status = 'present'; counters = $counters; histogram_log2_ns = $histogram } +} + +function Read-Preparation([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $report = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'report.json')) + if (-not (Test-Path -LiteralPath $report -PathType Leaf)) { + return [ordered]@{ status = 'missing_report'; counters = $null; ranked_status = 'missing_report'; ranked = $null; allocator_status = 'missing_report'; allocator = $null } + } + $json = Read-Json $report + if (-not (Has-Property $json 'preparation') -or $null -eq $json.preparation) { + return [ordered]@{ status = 'missing_preparation'; counters = $null; ranked_status = 'missing_preparation'; ranked = $null; allocator_status = 'missing_preparation'; allocator = $null } + } + $summary = $json.preparation + $version = Read-Nonnegative-Integer $summary 'version' 'preparation version' + if ($version -eq 0) { throw "malformed preparation version in $report" } + if ($version -ne 1 -and $version -ne 2 -and $version -ne 3) { + return [ordered]@{ status = 'unsupported_version'; counters = $null; ranked_status = 'unsupported_version'; ranked = $null; allocator_status = 'unsupported_version'; allocator = $null } + } + if (-not (Has-Property $summary 'compute_build_coalescing') -or + $null -eq $summary.compute_build_coalescing) { + throw "malformed preparation counters in $report" + } + $raw = $summary.compute_build_coalescing + $counters = [ordered]@{} + foreach ($name in @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', + 'current_in_flight', 'peak_in_flight')) { + $counters[$name] = Read-Nonnegative-Integer $raw $name "preparation in $report" + } + if ($version -eq 1) { + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'not_in_version'; ranked = $null; allocator_status = 'not_in_version'; allocator = $null } + } + if (-not (Has-Property $summary 'ranked_preloads') -or $null -eq $summary.ranked_preloads) { + throw "malformed ranked preload counters in $report" + } + $ranked = [ordered]@{} + foreach ($name in @('submissions', 'started', 'promoted')) { + $ranked[$name] = Read-Nonnegative-Integer $summary.ranked_preloads $name "ranked preloads in $report" + } + if ($version -eq 2) { + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked; allocator_status = 'not_in_version'; allocator = $null } + } + if (-not (Has-Property $summary 'allocator_submits') -or $null -eq $summary.allocator_submits) { + throw "malformed allocator submit counters in $report" + } + $allocator = [ordered]@{} + foreach ($name in @('outer_execute_calls', 'chunks', 'multi_chunk_calls', 'forced_wait_boundaries', + 'lists_marked', 'backing_mark_writes', 'signal_attempts', 'signal_failures', + 'state_lock_wait_ns', 'state_lock_hold_ns')) { + $allocator[$name] = Read-Nonnegative-Integer $summary.allocator_submits $name "allocator submits in $report" + } + return [ordered]@{ status = 'present'; counters = $counters; ranked_status = 'present'; ranked = $ranked; allocator_status = 'present'; allocator = $allocator } +} + +function Read-SparseUploadGate([string]$Root, [int]$Order, [string]$Label) { + $mode = $Label.Substring(4) + $log = Join-Path $Root (Join-Path 'runs' (Join-Path ('{0:d2}-{1}' -f $Order, $mode) 'xcl.log')) + if (-not (Test-Path -LiteralPath $log -PathType Leaf)) { + return [ordered]@{ status = 'missing_log'; counters = $null } + } + $text = Get-Content -LiteralPath $log -Raw -Encoding utf8 + $marker = 'upload gate submit wait/hold' + $pattern = 'upload gate submit wait/hold (?<submit_wait>\d+)/(?<submit_hold>\d+) ms, readback wait/hold/released wait\+reacquire (?<readback_wait>\d+)/(?<readback_hold>\d+)/(?<readback_released>\d+) ms' + $matches = [regex]::Matches($text, $pattern) + $markers = [regex]::Matches($text, [regex]::Escape($marker)) + if ($matches.Count -ne $markers.Count) { + throw "malformed sparse upload-gate metrics in $log" + } + if ($matches.Count -eq 0) { + return [ordered]@{ status = 'missing_metrics'; counters = $null } + } + $counters = [ordered]@{ + submit_wait_ms = [decimal]0 + submit_hold_ms = [decimal]0 + readback_wait_ms = [decimal]0 + readback_hold_ms = [decimal]0 + readback_released_wait_reacquire_ms = [decimal]0 + } + foreach ($match in $matches) { + $counters.submit_wait_ms += [decimal]$match.Groups['submit_wait'].Value + $counters.submit_hold_ms += [decimal]$match.Groups['submit_hold'].Value + $counters.readback_wait_ms += [decimal]$match.Groups['readback_wait'].Value + $counters.readback_hold_ms += [decimal]$match.Groups['readback_hold'].Value + $counters.readback_released_wait_reacquire_ms += [decimal]$match.Groups['readback_released'].Value + } + return [ordered]@{ status = 'present'; counters = $counters } +} + +function Number-Or-Null($Object, [string]$Name) { + if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } + return [long]$Object.$Name +} + +function Delta-Or-Null($Before, $After) { + if ($null -eq $Before -or $null -eq $After) { return $null } + return [long]$After - [long]$Before +} + +function Counter-Delta-Or-Null($Before, $After) { + if ($null -eq $Before -or $null -eq $After) { return $null } + return [decimal]$After - [decimal]$Before +} + +function Compare-Counters($Before, $After, [string[]]$Names) { + $delta = [ordered]@{} + foreach ($name in $Names) { + $delta[$name] = Counter-Delta-Or-Null $Before.$name $After.$name + } + return [ordered]@{ baseline = $Before; candidate = $After; delta = $delta } +} + +function Bool-Or-Null($Object, [string]$Name) { + if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } + return [bool]$Object.$Name +} + +function Aggregate-Or-Null($Aggregate) { + if ($null -eq $Aggregate) { return $null } + return [ordered]@{ + count = Number-Or-Null $Aggregate 'count' + total_ns = Number-Or-Null $Aggregate 'total_ns' + max_ns = Number-Or-Null $Aggregate 'max_ns' + histogram_log2_ns = @($Aggregate.histogram_log2_ns | ForEach-Object { [long]$_ }) + } +} + +function Compare-Aggregates($BeforeSet, $AfterSet) { + $kinds = @($BeforeSet.Keys) + @($AfterSet.Keys) | Sort-Object -Unique + $out = @() + foreach ($kind in $kinds) { + $beforeRaw = if ($BeforeSet.ContainsKey($kind)) { $BeforeSet[$kind] } else { $null } + $afterRaw = if ($AfterSet.ContainsKey($kind)) { $AfterSet[$kind] } else { $null } + $before = Aggregate-Or-Null $beforeRaw + $after = Aggregate-Or-Null $afterRaw + $histogramDelta = $null + if ($null -ne $before -and $null -ne $after -and $before.histogram_log2_ns.Count -eq $after.histogram_log2_ns.Count) { + $histogramDelta = for ($i = 0; $i -lt $before.histogram_log2_ns.Count; $i++) { + $after.histogram_log2_ns[$i] - $before.histogram_log2_ns[$i] + } + } + $out += [ordered]@{ + kind = $kind + baseline = $before + candidate = $after + delta = [ordered]@{ + count = Delta-Or-Null $before.count $after.count + total_ns = Delta-Or-Null $before.total_ns $after.total_ns + max_ns = Delta-Or-Null $before.max_ns $after.max_ns + histogram_log2_ns = $histogramDelta + } + } + } + return $out +} + +function Display-Value($Value, [string]$Suffix) { + if ($null -eq $Value) { return 'missing' } + return "$Value$Suffix" +} + +$baselineRoot = [IO.Path]::GetFullPath($Baseline) +$candidateRoot = [IO.Path]::GetFullPath($Candidate) +$beforeManifest = Read-Manifest $baselineRoot 'baseline' +$afterManifest = Read-Manifest $candidateRoot 'candidate' + +if ($beforeManifest.workload_id -cne $afterManifest.workload_id) { throw 'workload_id differs; runs are incomparable' } +if ($beforeManifest.workload_id_algorithm -cne $afterManifest.workload_id_algorithm) { + throw 'workload identity algorithm differs; runs are incomparable' +} +if ([int]$beforeManifest.workload_id_version -ne [int]$afterManifest.workload_id_version) { + throw 'workload identity version differs; runs are incomparable' +} +if ((@($beforeManifest.run_order) -join ',') -ne (@($afterManifest.run_order) -join ',')) { throw 'run order differs; runs are incomparable' } +Require-Same-Property $beforeManifest $afterManifest 'system' 'system information' +if (($beforeManifest.environment | ConvertTo-Json -Compress -Depth 6) -ne ($afterManifest.environment | ConvertTo-Json -Compress -Depth 6)) { + throw 'runtime environment differs; runs are incomparable' +} + +$comparisons = @() +for ($i = 0; $i -lt 2; $i++) { + $beforeRun = @($beforeManifest.runs)[$i] + $afterRun = @($afterManifest.runs)[$i] + Require-Same-Property $beforeRun $afterRun 'gpu' "$($beforeRun.cache_state) GPU" + Require-Same-Property $beforeRun $afterRun 'gpu_driver' "$($beforeRun.cache_state) GPU driver" + if ([long]$beforeRun.duration_requested_seconds -ne [long]$afterRun.duration_requested_seconds) { + throw "$($beforeRun.cache_state) requested duration differs; runs are incomparable" + } + $beforeDuration = Number-Or-Null $beforeRun 'duration_actual_ms' + $afterDuration = Number-Or-Null $afterRun 'duration_actual_ms' + $beforeStalls = Read-Stalls $baselineRoot ($i + 1) $beforeRun.cache_state + $afterStalls = Read-Stalls $candidateRoot ($i + 1) $afterRun.cache_state + $stalls = @(Compare-Aggregates $beforeStalls.aggregates $afterStalls.aggregates) + $beforePreparation = Read-Preparation $baselineRoot ($i + 1) $beforeRun.cache_state + $afterPreparation = Read-Preparation $candidateRoot ($i + 1) $afterRun.cache_state + $coalescingNames = @('keyed_submissions', 'coalescing_hits', 'unique_keyed_builds', 'current_in_flight', 'peak_in_flight') + $coalescing = Compare-Counters $beforePreparation.counters $afterPreparation.counters $coalescingNames + $rankedPreloads = Compare-Counters $beforePreparation.ranked $afterPreparation.ranked @('submissions', 'started', 'promoted') + $allocatorNames = @('outer_execute_calls', 'chunks', 'multi_chunk_calls', 'forced_wait_boundaries', + 'lists_marked', 'backing_mark_writes', 'signal_attempts', 'signal_failures', + 'state_lock_wait_ns', 'state_lock_hold_ns') + $allocatorSubmits = Compare-Counters $beforePreparation.allocator $afterPreparation.allocator $allocatorNames + $beforeSparseGate = Read-SparseUploadGate $baselineRoot ($i + 1) $beforeRun.cache_state + $afterSparseGate = Read-SparseUploadGate $candidateRoot ($i + 1) $afterRun.cache_state + $sparseGateNames = @('submit_wait_ms', 'submit_hold_ms', 'readback_wait_ms', 'readback_hold_ms', + 'readback_released_wait_reacquire_ms') + $sparseUploadGate = Compare-Counters $beforeSparseGate.counters $afterSparseGate.counters $sparseGateNames + $beforeSubmissionTiming = Read-SubmissionTiming $baselineRoot ($i + 1) $beforeRun.cache_state + $afterSubmissionTiming = Read-SubmissionTiming $candidateRoot ($i + 1) $afterRun.cache_state + $submissionTimingNames = @('submissions', 'slowest_submission_ms', 'slowest_submission_lists', + 'submission_total_ns', 'submission_mean_ms', 'submission_p95_upper_ms', 'submission_p99_upper_ms') + $submissionTiming = Compare-Counters $beforeSubmissionTiming.counters $afterSubmissionTiming.counters $submissionTimingNames + + $comparison = [ordered]@{ + label = $beforeRun.cache_state + duration_ms = [ordered]@{ + baseline = $beforeDuration + candidate = $afterDuration + delta = Delta-Or-Null $beforeDuration $afterDuration + } + exit_code = [ordered]@{ + baseline = Number-Or-Null $beforeRun 'exit_code' + candidate = Number-Or-Null $afterRun 'exit_code' + } + timed_out = [ordered]@{ + baseline = Bool-Or-Null $beforeRun 'timed_out' + candidate = Bool-Or-Null $afterRun 'timed_out' + } + stalls_status = [ordered]@{ baseline = $beforeStalls.status; candidate = $afterStalls.status } + stalls = $stalls + preparation_status = [ordered]@{ + baseline = $beforePreparation.status + candidate = $afterPreparation.status + } + compute_build_coalescing = $coalescing + ranked_preloads_status = [ordered]@{ + baseline = $beforePreparation.ranked_status + candidate = $afterPreparation.ranked_status + } + ranked_preloads = $rankedPreloads + allocator_submits_status = [ordered]@{ + baseline = $beforePreparation.allocator_status + candidate = $afterPreparation.allocator_status + } + allocator_submits = $allocatorSubmits + sparse_upload_gate_status = [ordered]@{ + baseline = $beforeSparseGate.status + candidate = $afterSparseGate.status + } + sparse_upload_gate = $sparseUploadGate + submission_timing_status = [ordered]@{ + baseline = $beforeSubmissionTiming.status + candidate = $afterSubmissionTiming.status + } + submission_timing = $submissionTiming + submission_timing_histogram_log2_ns = [ordered]@{ + baseline = $beforeSubmissionTiming.histogram_log2_ns + candidate = $afterSubmissionTiming.histogram_log2_ns + } + } + $comparisons += $comparison + + Write-Host "$($comparison.label): duration $(Display-Value $beforeDuration ' ms') -> $(Display-Value $afterDuration ' ms'); delta $(Display-Value $comparison.duration_ms.delta ' ms')" + Write-Host " exit: $(Display-Value $comparison.exit_code.baseline '') -> $(Display-Value $comparison.exit_code.candidate ''); timeout: $(Display-Value $comparison.timed_out.baseline '') -> $(Display-Value $comparison.timed_out.candidate '')" + if ($stalls.Count -eq 0) { + Write-Host " stalls: missing/empty (baseline $($beforeStalls.status), candidate $($afterStalls.status))" + } else { + foreach ($stall in $stalls) { + Write-Host " stall $($stall.kind): total $(Display-Value $stall.baseline.total_ns ' ns') -> $(Display-Value $stall.candidate.total_ns ' ns'); count $(Display-Value $stall.baseline.count '') -> $(Display-Value $stall.candidate.count ''); max $(Display-Value $stall.baseline.max_ns ' ns') -> $(Display-Value $stall.candidate.max_ns ' ns')" + } + } + Write-Host " preparation: $($beforePreparation.status) -> $($afterPreparation.status)" + if ($beforePreparation.status -eq 'present' -or $afterPreparation.status -eq 'present') { + foreach ($name in $coalescing.delta.Keys) { + Write-Host " $($name): $(Display-Value $coalescing.baseline.$name '') -> $(Display-Value $coalescing.candidate.$name ''); delta $(Display-Value $coalescing.delta.$name '')" + } + } + Write-Host " ranked preloads: $($beforePreparation.ranked_status) -> $($afterPreparation.ranked_status)" + if ($beforePreparation.ranked_status -eq 'present' -or $afterPreparation.ranked_status -eq 'present') { + foreach ($name in $rankedPreloads.delta.Keys) { + Write-Host " $($name): $(Display-Value $rankedPreloads.baseline.$name '') -> $(Display-Value $rankedPreloads.candidate.$name ''); delta $(Display-Value $rankedPreloads.delta.$name '')" + } + } + Write-Host " allocator submits: $($beforePreparation.allocator_status) -> $($afterPreparation.allocator_status)" + if ($beforePreparation.allocator_status -eq 'present' -or $afterPreparation.allocator_status -eq 'present') { + foreach ($name in $allocatorSubmits.delta.Keys) { + Write-Host " $($name): $(Display-Value $allocatorSubmits.baseline.$name '') -> $(Display-Value $allocatorSubmits.candidate.$name ''); delta $(Display-Value $allocatorSubmits.delta.$name '')" + } + } + Write-Host " sparse upload gate: $($beforeSparseGate.status) -> $($afterSparseGate.status)" + if ($beforeSparseGate.status -eq 'present' -or $afterSparseGate.status -eq 'present') { + foreach ($name in $sparseUploadGate.delta.Keys) { + Write-Host " $($name): $(Display-Value $sparseUploadGate.baseline.$name ' ms') -> $(Display-Value $sparseUploadGate.candidate.$name ' ms'); delta $(Display-Value $sparseUploadGate.delta.$name ' ms')" + } + } + Write-Host " submission timing: $($beforeSubmissionTiming.status) -> $($afterSubmissionTiming.status)" + if ($beforeSubmissionTiming.status -like 'present*' -or $afterSubmissionTiming.status -like 'present*') { + foreach ($name in $submissionTiming.delta.Keys) { + $suffix = if ($name -like '*_ms') { ' ms' } elseif ($name -eq 'submission_total_ns') { ' ns' } else { '' } + Write-Host " $($name): $(Display-Value $submissionTiming.baseline.$name $suffix) -> $(Display-Value $submissionTiming.candidate.$name $suffix); delta $(Display-Value $submissionTiming.delta.$name $suffix)" + } + } +} + +[ordered]@{ + schema = 'xcl-perf-comparison' + version = 1 + workload_id = $beforeManifest.workload_id + workload_id_algorithm = $beforeManifest.workload_id_algorithm + workload_id_version = [int]$beforeManifest.workload_id_version + run_order = @($beforeManifest.run_order) + baseline = [ordered]@{ commit = $beforeManifest.commit; path = $baselineRoot; build = $beforeManifest.build } + candidate = [ordered]@{ commit = $afterManifest.commit; path = $candidateRoot; build = $afterManifest.build } + runs = $comparisons +} | ConvertTo-Json -Depth 12 diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 new file mode 100644 index 0000000000..c64607bcf3 --- /dev/null +++ b/scripts/perf-compare.tests.ps1 @@ -0,0 +1,350 @@ +$ErrorActionPreference = 'Stop' +$tool = Join-Path $PSScriptRoot 'perf-compare.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-compare-test-' + [guid]::NewGuid()) +$baseline = Join-Path $fixture 'baseline' +$candidate = Join-Path $fixture 'candidate' + +function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs, + [string[]]$CargoFeatures = @(), [string]$ExecutableSha256 = ('0' * 64)) { + $null = New-Item -ItemType Directory -Path (Join-Path $Root 'runs\01-cold'), (Join-Path $Root 'runs\02-warm') -Force + $manifest = [ordered]@{ + schema = 'xcl-perf-run' + version = 1 + commit = $Commit + dirty = $false + build = [ordered]@{ + profile = 'release' + cargo_features = @($CargoFeatures) + target_dir_kind = 'repository-default' + executable_sha256 = $ExecutableSha256 + } + workload_id = 'same-workload' + workload_id_algorithm = 'sha256-relative-path-length-mtime-utc-ticks' + workload_id_version = 1 + run_order = @('xcl-cold', 'xcl-warm') + environment = [ordered]@{ XCL_PRESS_AT = '20:A' } + runs = @( + [ordered]@{ order = 1; cache_state = 'xcl-cold'; duration_requested_seconds = 60; duration_actual_ms = $ColdMs; exit_code = 0; timed_out = $false }, + [ordered]@{ order = 2; cache_state = 'xcl-warm'; duration_requested_seconds = 60; duration_actual_ms = $WarmMs; exit_code = $null; timed_out = $true } + ) + } + $manifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $Root 'manifest.json') -Encoding utf8 +} + +function Write-Report([string]$Path, [int]$Count, [long]$Total, [long]$Maximum, + $Preparation = $null, [int]$PreparationVersion = 1, $RankedPreloads = $null, + $AllocatorSubmits = $null, $SubmissionTiming = $null, [switch]$ExtraKind) { + $aggregates = @( + [ordered]@{ kind = 'dxc_compile'; count = $Count; total_ns = $Total; max_ns = $Maximum; histogram_log2_ns = @(0, $Count) } + ) + if ($ExtraKind) { + $aggregates += [ordered]@{ kind = 'gpu_wait'; count = 1; total_ns = 9; max_ns = 9; histogram_log2_ns = @(0, 0, 0, 1) } + } + $report = [ordered]@{ stalls = [ordered]@{ version = 1; aggregates = $aggregates; slow_events = @() } } + if ($null -ne $SubmissionTiming) { $report['d3d12'] = $SubmissionTiming } + if ($null -ne $Preparation) { + $report['preparation'] = [ordered]@{ + version = $PreparationVersion + compute_build_coalescing = $Preparation + } + if ($null -ne $RankedPreloads) { + $report['preparation']['ranked_preloads'] = $RankedPreloads + } + if ($null -ne $AllocatorSubmits) { + $report['preparation']['allocator_submits'] = $AllocatorSubmits + } + } + $report | + ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $Path -Encoding utf8 +} + +try { + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 @('mimalloc-allocator') ('1' * 64) + $beforePreparation = [ordered]@{ keyed_submissions = 12; coalescing_hits = 5; unique_keyed_builds = 7; current_in_flight = 0; peak_in_flight = 3 } + $afterPreparation = [ordered]@{ keyed_submissions = 10; coalescing_hits = 6; unique_keyed_builds = 4; current_in_flight = 1; peak_in_flight = 5 } + $beforeRanked = [ordered]@{ submissions = 20; started = 15; promoted = 3 } + $afterRanked = [ordered]@{ submissions = 24; started = 20; promoted = 2 } + $beforeAllocator = [ordered]@{ outer_execute_calls = 10; chunks = 13; multi_chunk_calls = 2; forced_wait_boundaries = 3; lists_marked = 40; backing_mark_writes = 20; signal_attempts = 13; signal_failures = 1; state_lock_wait_ns = 100; state_lock_hold_ns = 500 } + $afterAllocator = [ordered]@{ outer_execute_calls = 12; chunks = 14; multi_chunk_calls = 1; forced_wait_boundaries = 2; lists_marked = 44; backing_mark_writes = 22; signal_attempts = 14; signal_failures = 0; state_lock_wait_ns = 80; state_lock_hold_ns = 450 } + $beforeHistogram = @(0) * 64 + $beforeHistogram[20] = 20 + $afterHistogram = @(0) * 64 + $afterHistogram[19] = 18 + $afterHistogram[21] = 6 + $beforeSubmissionTiming = [ordered]@{ + submissions = 20; slowest_submission_ms = 3.5; slowest_submission_lists = 4 + submission_total_ns = 20000000; submission_mean_ms = 1.0 + submission_p95_upper_ms = 2.097151; submission_p99_upper_ms = 2.097151 + submission_histogram_log2_ns = $beforeHistogram + } + $afterSubmissionTiming = [ordered]@{ + submissions = 24; slowest_submission_ms = 2.25; slowest_submission_lists = 3 + submission_total_ns = 18000000; submission_mean_ms = 0.75 + submission_p95_upper_ms = 4.194303; submission_p99_upper_ms = 4.194303 + submission_histogram_log2_ns = $afterHistogram + } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 3 $beforeRanked $beforeAllocator $beforeSubmissionTiming + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind + [ordered]@{ d3d12 = [ordered]@{} } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\report.json') -Encoding utf8 + @( + '[00:00:02] upload gate submit wait/hold 1/2 ms, readback wait/hold/released wait+reacquire 3/4/5 ms; other active work 6 ms' + '[00:00:04] upload gate submit wait/hold 10/20 ms, readback wait/hold/released wait+reacquire 30/40/50 ms; other active work 60 ms' + ) | Set-Content -LiteralPath (Join-Path $baseline 'runs\01-cold\xcl.log') -Encoding utf8 + '[00:00:02] upload gate submit wait/hold 7/9 ms, readback wait/hold/released wait+reacquire 11/13/15 ms; other active work 17 ms' | + Set-Content -LiteralPath (Join-Path $candidate 'runs\01-cold\xcl.log') -Encoding utf8 + '[00:00:02] sparse queue wait/fence+state/scan/upload/ownership wait 1/2/3/4/5 ms' | + Set-Content -LiteralPath (Join-Path $baseline 'runs\02-warm\xcl.log') -Encoding utf8 + + $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($json.schema -ne 'xcl-perf-comparison' -or $json.version -ne 1) { throw 'wrong output schema' } + if ($json.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or + $json.workload_id_version -ne 1) { throw 'workload identity contract is missing from output' } + if (@($json.baseline.build.cargo_features).Count -ne 0 -or + (@($json.candidate.build.cargo_features) -join ',') -ne 'mimalloc-allocator' -or + $json.candidate.build.executable_sha256 -ne ('1' * 64)) { + throw 'different build variants were refused or not exposed in comparison output' + } + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.build.cargo_features = @('zeta', 'alpha') + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed Cargo features' } + if (-not $refused) { throw 'noncanonical build features were not refused' } + Write-Fixture $candidate 'candidate-commit' 850 0 @('mimalloc-allocator') ('1' * 64) + if ($json.runs[0].duration_ms.delta -ne -150) { throw 'cold duration delta is wrong' } + if ($json.runs[1].duration_ms.delta -ne 0) { throw 'zero durations were not compared as raw values' } + if ($json.runs[1].exit_code.candidate -ne $null -or $json.runs[1].timed_out.candidate -ne $true) { throw 'missing exit/timeout was not preserved' } + $dxc = $json.runs[0].stalls | Where-Object { $_.kind -eq 'dxc_compile' } + if ($dxc.delta.total_ns -ne -20 -or $dxc.delta.count -ne 1 -or $dxc.delta.max_ns -ne -30) { throw 'stall deltas are wrong' } + $gpu = $json.runs[0].stalls | Where-Object { $_.kind -eq 'gpu_wait' } + if ($null -ne $gpu.baseline -or $gpu.candidate.total_ns -ne 9 -or $null -ne $gpu.delta.total_ns) { throw 'one-sided stall data was not labelled missing' } + if ($json.runs[1].stalls_status.baseline -ne 'missing_stalls' -or $json.runs[1].stalls_status.candidate -ne 'missing_report') { throw 'missing report/stalls states are wrong' } + $preparation = $json.runs[0].compute_build_coalescing + if ($preparation.baseline.keyed_submissions -ne 12 -or $preparation.candidate.keyed_submissions -ne 10 -or + $preparation.baseline.coalescing_hits -ne 5 -or $preparation.candidate.coalescing_hits -ne 6 -or + $preparation.baseline.unique_keyed_builds -ne 7 -or $preparation.candidate.unique_keyed_builds -ne 4 -or + $preparation.baseline.current_in_flight -ne 0 -or $preparation.candidate.current_in_flight -ne 1 -or + $preparation.baseline.peak_in_flight -ne 3 -or $preparation.candidate.peak_in_flight -ne 5 -or + $preparation.delta.keyed_submissions -ne -2 -or $preparation.delta.coalescing_hits -ne 1 -or + $preparation.delta.unique_keyed_builds -ne -3 -or $preparation.delta.current_in_flight -ne 1 -or + $preparation.delta.peak_in_flight -ne 2) { throw 'preparation counters or deltas are wrong' } + $ranked = $json.runs[0].ranked_preloads + if ($json.runs[0].ranked_preloads_status.baseline -ne 'present' -or + $json.runs[0].ranked_preloads_status.candidate -ne 'present' -or + $ranked.baseline.submissions -ne 20 -or $ranked.candidate.submissions -ne 24 -or + $ranked.baseline.started -ne 15 -or $ranked.candidate.started -ne 20 -or + $ranked.baseline.promoted -ne 3 -or $ranked.candidate.promoted -ne 2 -or + $ranked.delta.submissions -ne 4 -or $ranked.delta.started -ne 5 -or + $ranked.delta.promoted -ne -1) { throw 'ranked preload counters, status, or deltas are wrong' } + $allocator = $json.runs[0].allocator_submits + if ($json.runs[0].allocator_submits_status.baseline -ne 'present' -or + $json.runs[0].allocator_submits_status.candidate -ne 'present' -or + $allocator.baseline.outer_execute_calls -ne 10 -or $allocator.candidate.outer_execute_calls -ne 12 -or + $allocator.delta.chunks -ne 1 -or $allocator.delta.multi_chunk_calls -ne -1 -or + $allocator.delta.lists_marked -ne 4 -or $allocator.delta.backing_mark_writes -ne 2 -or + $allocator.delta.state_lock_hold_ns -ne -50) { + throw 'allocator submit counters, status, or deltas are wrong' + } + if ($json.runs[1].preparation_status.baseline -ne 'missing_preparation' -or + $json.runs[1].preparation_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].compute_build_coalescing.delta.keyed_submissions -or + $json.runs[1].ranked_preloads_status.baseline -ne 'missing_preparation' -or + $json.runs[1].ranked_preloads_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].ranked_preloads.delta.submissions -or + $json.runs[1].allocator_submits_status.baseline -ne 'missing_preparation' -or + $json.runs[1].allocator_submits_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].allocator_submits.delta.chunks) { + throw 'missing preparation data was treated as zero' + } + $gate = $json.runs[0].sparse_upload_gate + if ($json.runs[0].sparse_upload_gate_status.baseline -ne 'present' -or + $json.runs[0].sparse_upload_gate_status.candidate -ne 'present' -or + $gate.baseline.submit_wait_ms -ne 11 -or $gate.baseline.submit_hold_ms -ne 22 -or + $gate.baseline.readback_wait_ms -ne 33 -or $gate.baseline.readback_hold_ms -ne 44 -or + $gate.baseline.readback_released_wait_reacquire_ms -ne 55 -or + $gate.candidate.submit_wait_ms -ne 7 -or $gate.delta.submit_wait_ms -ne -4 -or + $gate.delta.readback_released_wait_reacquire_ms -ne -40) { + throw 'sparse upload-gate counters or deltas are wrong' + } + if ($json.runs[1].sparse_upload_gate_status.baseline -ne 'missing_metrics' -or + $json.runs[1].sparse_upload_gate_status.candidate -ne 'missing_log' -or + $null -ne $json.runs[1].sparse_upload_gate.delta.submit_wait_ms) { + throw 'missing sparse upload-gate metrics were treated as zero' + } + $timing = $json.runs[0].submission_timing + if ($json.runs[0].submission_timing_status.baseline -ne 'present' -or + $json.runs[0].submission_timing_status.candidate -ne 'present' -or + $timing.baseline.submissions -ne 20 -or $timing.candidate.submissions -ne 24 -or + $timing.delta.submissions -ne 4 -or $timing.delta.slowest_submission_ms -ne -1.25 -or + $timing.delta.slowest_submission_lists -ne -1 -or $timing.delta.submission_total_ns -ne -2000000 -or + $timing.delta.submission_mean_ms -ne -0.25 -or $timing.delta.submission_p95_upper_ms -ne 2.097152 -or + $json.runs[0].submission_timing_histogram_log2_ns.baseline[20] -ne 20 -or + $json.runs[0].submission_timing_histogram_log2_ns.candidate[21] -ne 6) { + throw 'submission timing counters, status, or deltas are wrong' + } + if ($json.runs[1].submission_timing_status.baseline -ne 'missing_metrics' -or + $json.runs[1].submission_timing_status.candidate -ne 'missing_report' -or + $null -ne $json.runs[1].submission_timing.delta.submissions) { + throw 'missing submission timing was treated as zero' + } + $legacySubmissionTiming = [ordered]@{ submissions = 24; slowest_submission_ms = 2.25; slowest_submission_lists = 3 } + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $legacySubmissionTiming -ExtraKind + $legacy = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($legacy.runs[0].submission_timing_status.candidate -ne 'present_legacy' -or + $legacy.runs[0].submission_timing.delta.submissions -ne 4 -or + $null -ne $legacy.runs[0].submission_timing.delta.submission_total_ns -or + $null -ne $legacy.runs[0].submission_timing_histogram_log2_ns.candidate) { + throw 'legacy submission timing was not preserved explicitly' + } + $badTimingPath = Join-Path $candidate 'runs\01-cold\report.json' + Write-Report $badTimingPath 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind + $badTiming = Get-Content -LiteralPath $badTimingPath -Raw -Encoding utf8 | ConvertFrom-Json + $badTiming.d3d12.submission_histogram_log2_ns[0] = 1 + $badTiming | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badTimingPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'histogram count differs' } + if (-not $refused) { throw 'a submission histogram with the wrong count was not refused' } + [ordered]@{ d3d12 = [ordered]@{ submission_total_ns = 1 } } | + ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badTimingPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'incomplete submission timing' } + if (-not $refused) { throw 'orphaned extended submission timing was not refused' } + Write-Report $badTimingPath 3 80 40 $afterPreparation 3 $afterRanked $afterAllocator $afterSubmissionTiming -ExtraKind + $badGateLog = Join-Path $candidate 'runs\02-warm\xcl.log' + 'upload gate submit wait/hold malformed' | Set-Content -LiteralPath $badGateLog -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed sparse upload-gate metrics' } + Remove-Item -LiteralPath $badGateLog + if (-not $refused) { throw 'a malformed sparse upload-gate activity line was not refused' } + if (($json | ConvertTo-Json -Depth 12) -match '"(percent|percentage|ratio|significance|significant)"\s*:') { + throw 'output invented a derived significance metric' + } + + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation -ExtraKind + $versionOne = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($versionOne.runs[0].preparation_status.baseline -ne 'present' -or + $versionOne.runs[0].compute_build_coalescing.candidate.coalescing_hits -ne 6 -or + $versionOne.runs[0].ranked_preloads_status.baseline -ne 'not_in_version' -or + $versionOne.runs[0].ranked_preloads_status.candidate -ne 'not_in_version' -or + $versionOne.runs[0].allocator_submits_status.baseline -ne 'not_in_version' -or + $versionOne.runs[0].allocator_submits_status.candidate -ne 'not_in_version' -or + $null -ne $versionOne.runs[0].ranked_preloads.delta.started) { + throw 'version 1 preparation support regressed' + } + Write-Report (Join-Path $baseline 'runs\01-cold\report.json') 2 100 70 $beforePreparation 2 $beforeRanked + Write-Report (Join-Path $candidate 'runs\01-cold\report.json') 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + + Write-Report (Join-Path $candidate 'runs\02-warm\report.json') 1 1 1 $afterPreparation 4 + $unsupported = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($unsupported.runs[0].allocator_submits_status.baseline -ne 'not_in_version' -or + $unsupported.runs[0].allocator_submits_status.candidate -ne 'not_in_version' -or + $unsupported.runs[1].preparation_status.candidate -ne 'unsupported_version' -or + $unsupported.runs[1].ranked_preloads_status.candidate -ne 'unsupported_version' -or + $unsupported.runs[1].allocator_submits_status.candidate -ne 'unsupported_version' -or + $null -ne $unsupported.runs[1].compute_build_coalescing.candidate -or + $null -ne $unsupported.runs[1].ranked_preloads.candidate -or + $null -ne $unsupported.runs[1].allocator_submits.candidate) { + throw 'unsupported preparation version was not preserved as a state' + } + + $badReportPath = Join-Path $candidate 'runs\01-cold\report.json' + Write-Report $badReportPath 3 80 40 $afterPreparation 2 -ExtraKind + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed ranked preload' } + if (-not $refused) { throw 'missing version 2 ranked preload counters were not refused' } + + Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + $badReport = Get-Content -LiteralPath $badReportPath -Raw -Encoding utf8 | ConvertFrom-Json + $badReport.preparation.ranked_preloads.promoted = -1 + $badReport | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badReportPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed ranked preloads' } + if (-not $refused) { throw 'a malformed ranked preload counter was not refused' } + + Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + $badReport = Get-Content -LiteralPath $badReportPath -Raw -Encoding utf8 | ConvertFrom-Json + $badReport.preparation.compute_build_coalescing.coalescing_hits = -1 + $badReport | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $badReportPath -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed preparation' } + if (-not $refused) { throw 'a malformed preparation counter was not refused' } + Write-Report $badReportPath 3 80 40 $afterPreparation 3 $afterRanked -ExtraKind + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'malformed allocator submit' } + if (-not $refused) { throw 'missing version 3 allocator submit counters were not refused' } + Write-Report $badReportPath 3 80 40 $afterPreparation 2 $afterRanked -ExtraKind + + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id = 'other-workload' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload_id differs' } + if (-not $refused) { throw 'different workloads were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id_algorithm = 'other-algorithm' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload identity algorithm differs' } + if (-not $refused) { throw 'different workload identity algorithms were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id_version = 2 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload identity version differs' } + if (-not $refused) { throw 'different workload identity versions were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[1].cache_state = 'xcl-cold' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'does not match run_order' } + if (-not $refused) { throw 'mismatched run labels were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.version = 2 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'unsupported manifest schema/version' } + if (-not $refused) { throw 'an unsupported manifest schema was not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest | Add-Member -NotePropertyName system -NotePropertyValue ([pscustomobject]@{ cpu = 'only candidate recorded this' }) + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'system information differs' } + if (-not $refused) { throw 'system information present on only one side was not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $baselineManifest = Get-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $baselineManifest.runs[0] | Add-Member -NotePropertyName gpu -NotePropertyValue 'GPU A' + $candidateManifest.runs[0] | Add-Member -NotePropertyName gpu -NotePropertyValue 'GPU B' + $baselineManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Encoding utf8 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-cold GPU differs' } + if (-not $refused) { throw 'different GPUs were not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[1] | Add-Member -NotePropertyName gpu_driver -NotePropertyValue 'only candidate recorded this' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-warm GPU driver differs' } + if (-not $refused) { throw 'GPU driver present on only one side was not refused' } + + Write-Host 'perf-compare tests: all assertions passed' +} finally { + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } +} diff --git a/scripts/perf-run.ps1 b/scripts/perf-run.ps1 new file mode 100644 index 0000000000..9c5aa3fe99 --- /dev/null +++ b/scripts/perf-run.ps1 @@ -0,0 +1,306 @@ +# Reproducible paired runtime measurement: an XCL-cold run followed by an XCL-warm run +# against the same ephemeral XCL data and DXIL cache. The GPU driver's own cache is not +# controlled and is named as such in the manifest. +param( + [Parameter(Mandatory = $true)][string]$Game, + [Parameter(Mandatory = $true)][string]$OutDir, + [int]$Seconds = 120, + [string[]]$CargoFeatures = @(), + [string]$CargoTargetDir +) +$ErrorActionPreference = 'Stop' + +if ($Seconds -lt 1) { throw '-Seconds must be at least 1' } +if (-not (Test-Path -LiteralPath $Game -PathType Container)) { throw "game folder not found: $Game" } +$gamePath = [IO.Path]::GetFullPath($Game) +$root = Split-Path $PSScriptRoot -Parent +$workloadAlgorithm = 'sha256-relative-path-length-mtime-utc-ticks' +$workloadAlgorithmVersion = 1 + +function Get-CanonicalCargoFeatures([string[]]$Values) { + $features = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal) + foreach ($value in @($Values)) { + foreach ($feature in @($value -split '[,\s]+')) { + if ([string]::IsNullOrWhiteSpace($feature)) { continue } + if ($feature.StartsWith('-')) { throw "invalid Cargo feature: $feature" } + $null = $features.Add($feature) + } + } + [string[]]$canonical = @($features) + [Array]::Sort($canonical, [StringComparer]::Ordinal) + return $canonical +} + +$cargoFeaturesCanonical = @(Get-CanonicalCargoFeatures $CargoFeatures) + +function Read-InventoryRecords([string]$Path) { + $separators = [char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + $prefix = $Path.TrimEnd($separators) + [IO.Path]::DirectorySeparatorChar + $byPath = @{} + try { + foreach ($file in Get-ChildItem -LiteralPath $Path -Recurse -Force -File -ErrorAction Stop) { + $full = [IO.Path]::GetFullPath($file.FullName) + if (-not $full.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { + throw "inventory path escaped the game folder" + } + $info = New-Object IO.FileInfo $full + $info.Refresh() + if (-not $info.Exists) { throw "file disappeared during inventory: $($file.Name)" } + $relative = $full.Substring($prefix.Length).Replace([IO.Path]::DirectorySeparatorChar, '/') + if ($byPath.ContainsKey($relative)) { throw "duplicate relative inventory path: $relative" } + $length = $info.Length.ToString([Globalization.CultureInfo]::InvariantCulture) + $ticks = $info.LastWriteTimeUtc.Ticks.ToString([Globalization.CultureInfo]::InvariantCulture) + $byPath[$relative] = '{0}:{1}|{2}|{3}' -f $relative.Length, $relative, $length, $ticks + } + } catch { + throw "cannot create a complete game metadata inventory: $($_.Exception.Message)" + } + if ($byPath.Count -eq 0) { throw 'cannot fingerprint an empty game folder' } + [string[]]$paths = @($byPath.Keys) + [Array]::Sort($paths, [StringComparer]::Ordinal) + return @($paths | ForEach-Object { $byPath[$_] }) +} + +function Get-WorkloadIdentity([string]$Path) { + $first = @(Read-InventoryRecords $Path) + $second = @(Read-InventoryRecords $Path) + if ($first.Count -ne $second.Count) { throw 'game metadata inventory changed while it was read' } + for ($i = 0; $i -lt $first.Count; $i++) { + if ($first[$i] -cne $second[$i]) { throw 'game metadata inventory changed while it was read' } + } + $bytes = [Text.Encoding]::UTF8.GetBytes([string]::Join([char]10, [string[]]$first)) + $sha = [Security.Cryptography.SHA256]::Create() + try { + $id = -join ($sha.ComputeHash($bytes) | ForEach-Object { $_.ToString('x2') }) + } finally { + $sha.Dispose() + } + return [ordered]@{ algorithm = $workloadAlgorithm; version = $workloadAlgorithmVersion; id = $id } +} + +$workloadIdentity = Get-WorkloadIdentity $gamePath + +function Run-Git([string[]]$Arguments) { + $out = @(& git.exe -C $root @Arguments) + if ($LASTEXITCODE -ne 0) { throw "git $($Arguments -join ' ') failed with exit code $LASTEXITCODE" } + return $out +} + +$commit = ((Run-Git -Arguments @('rev-parse', 'HEAD')) -join '').Trim() +$dirtyLines = @(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')) +if ($dirtyLines.Count -ne 0) { throw 'perf-run requires a clean worktree so the executable names an exact commit' } + +if (Test-Path -LiteralPath $OutDir) { + if (@(Get-ChildItem -LiteralPath $OutDir -Force).Count -ne 0) { throw "output folder is not empty: $OutDir" } +} else { + $null = New-Item -ItemType Directory -Path $OutDir +} +$outPath = [IO.Path]::GetFullPath($OutDir) + +$cargoTargetKind = 'repository-default' +$cargoTargetPath = Join-Path $root 'target' +if (-not [string]::IsNullOrWhiteSpace($CargoTargetDir)) { + $cargoTargetKind = 'explicit' + $cargoTargetPath = if ([IO.Path]::IsPathRooted($CargoTargetDir)) { + [IO.Path]::GetFullPath($CargoTargetDir) + } else { + [IO.Path]::GetFullPath((Join-Path $root $CargoTargetDir)) + } +} +[string[]]$cargoArguments = @('build', '--locked', '--release', '-p', 'xcl') +if ($cargoFeaturesCanonical.Count -ne 0) { + $cargoArguments += '--features=' + [string]::Join(',', $cargoFeaturesCanonical) +} +$cargoArguments += '--target-dir', $cargoTargetPath + +Push-Location $root +try { + & cargo @cargoArguments + if ($LASTEXITCODE -ne 0) { throw "release build failed with exit code $LASTEXITCODE" } +} finally { + Pop-Location +} +if (@(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')).Count -ne 0) { + throw 'the worktree changed during the release build' +} + +$xcl = Join-Path $cargoTargetPath 'release\xcl.exe' +# Test scripts use a command file after still exercising the clean-tree and release-build steps. +if ($env:XCL_PERF_RUN_TESTING -eq '1' -and $env:XCL_PERF_RUN_TEST_XCL) { + $xcl = $env:XCL_PERF_RUN_TEST_XCL +} +if (-not (Test-Path -LiteralPath $xcl)) { throw "release build did not produce $xcl" } +$xclSha256 = (Get-FileHash -LiteralPath $xcl -Algorithm SHA256).Hash.ToLowerInvariant() + +$cacheId = [guid]::NewGuid().ToString('n') +$cacheRoot = Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$cacheId") +$dataRoot = Join-Path $cacheRoot 'data' +$dxilCache = Join-Path $cacheRoot 'dxil' +$null = New-Item -ItemType Directory -Path $dataRoot +$null = New-Item -ItemType Directory -Path $dxilCache + +$environmentNames = @( + 'XCL_ACTIVITY', 'XCL_ADAPTER', 'XCL_DEVICE_TYPE', 'XCL_DIRECT_DXIL', + 'XCL_DXC_THREADS', 'XCL_FRAME_INTERVAL_US', 'XCL_HEAP_WINDOWS', + 'XCL_GPU_TIMING', 'XCL_GPU_TIMING_MS', 'XCL_LAZY_PSO', 'XCL_NETWORK', 'XCL_PRESS_AT', 'XCL_PSO_PRELOAD', + 'XCL_REQUIRE_GPU', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE' +) +$changedNames = @('XCL_ACTIVITY', 'XCL_DATA_ROOT', 'XCL_DXIL_CACHE', 'XCL_GPU_TIMING', 'XCL_GPU_TIMING_MS', + 'XCL_NETWORK', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE') +$savedEnvironment = @{} +foreach ($name in $changedNames) { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') +} + +function Video-Driver([string]$Adapter) { + try { + $controllers = @(Get-CimInstance Win32_VideoController) + $controller = $controllers | Where-Object { + $Adapter -and ($Adapter.Contains($_.Name) -or $_.Name.Contains($Adapter)) + } | Select-Object -First 1 + if (-not $controller) { $controller = $controllers | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1 } + return $controller.DriverVersion + } catch { + return $null + } +} + +function Invoke-PerfRun([string]$Mode, [int]$Order) { + $runName = '{0:d2}-{1}' -f $Order, $Mode + $artifactDir = Join-Path (Join-Path $outPath 'runs') $runName + $null = New-Item -ItemType Directory -Path $artifactDir -Force + + $psi = New-Object System.Diagnostics.ProcessStartInfo + if ($xcl -match '\.(cmd|bat)$') { + $psi.FileName = 'cmd.exe' + $psi.Arguments = '/d /c ""' + $xcl + '" run "' + $gamePath + '""' + } else { + $psi.FileName = $xcl + $psi.Arguments = 'run "' + $gamePath + '"' + } + $psi.WorkingDirectory = $root + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.StandardOutputEncoding = [Text.Encoding]::UTF8 + $psi.StandardErrorEncoding = [Text.Encoding]::UTF8 + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $psi + $watch = [Diagnostics.Stopwatch]::StartNew() + $null = $process.Start() + $stdoutTask = $process.StandardOutput.ReadToEndAsync() + $stderrTask = $process.StandardError.ReadToEndAsync() + $timedOut = -not $process.WaitForExit(($Seconds + 120) * 1000) + if ($timedOut -and -not $process.HasExited) { $process.Kill() } + $process.WaitForExit() + $watch.Stop() + $stdout = $stdoutTask.Result + $null = $stderrTask.Result + + $logLine = ($stdout -split '\r?\n' | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1) + if (-not $logLine) { throw "XCL printed no log path during the $Mode run" } + $log = ($logLine -replace '^Log:\s+', '').Trim() + if (-not (Test-Path -LiteralPath $log)) { throw "XCL's $Mode log does not exist: $log" } + Copy-Item -LiteralPath $log -Destination (Join-Path $artifactDir 'xcl.log') + + $sourceReport = Join-Path (Split-Path $log -Parent) 'report.json' + $reportArtifact = $null + $adapter = $null + if (Test-Path -LiteralPath $sourceReport) { + $reportArtifact = 'report.json' + Copy-Item -LiteralPath $sourceReport -Destination (Join-Path $artifactDir $reportArtifact) + try { + $adapter = ((Get-Content -LiteralPath $sourceReport -Raw -Encoding utf8 | ConvertFrom-Json).d3d12.adapter -replace '\s*\([^()]*VRAM\)$', '') + } catch { } + } + + return [ordered]@{ + order = $Order + cache_state = "xcl-$Mode" + duration_requested_seconds = $Seconds + duration_actual_ms = $watch.ElapsedMilliseconds + exit_code = if ($timedOut) { $null } else { $process.ExitCode } + timed_out = $timedOut + gpu = $adapter + gpu_driver = Video-Driver $adapter + artifacts = [ordered]@{ log = 'xcl.log'; report = $reportArtifact } + } +} + +try { + $env:XCL_DATA_ROOT = $dataRoot + $env:XCL_DXIL_CACHE = $dxilCache + $env:XCL_NETWORK = '0' + $env:XCL_RUN_SECONDS = "$Seconds" + $env:XCL_ACTIVITY = '1' + $env:XCL_GPU_TIMING = '1' + $env:XCL_GPU_TIMING_MS = '50' + $env:XCL_STALL_TRACE = '1' + + $recordedEnvironment = [ordered]@{} + foreach ($name in $environmentNames) { + $recordedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') + } + + $runs = @() + $runs += Invoke-PerfRun 'cold' 1 + $runs += Invoke-PerfRun 'warm' 2 + + $cpu = $null + $windows = $null + try { $cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name } catch { } + try { + $os = Get-CimInstance Win32_OperatingSystem + $windows = "$($os.Caption) $($os.Version) build $($os.BuildNumber)" + } catch { } + $rust = (& rustc -Vv) -join [Environment]::NewLine + if ($LASTEXITCODE -ne 0) { throw 'rustc -Vv failed' } + $verifiedWorkloadIdentity = Get-WorkloadIdentity $gamePath + if ($verifiedWorkloadIdentity.id -ne $workloadIdentity.id) { + throw 'game metadata inventory changed during the performance runs' + } + + $manifest = [ordered]@{ + schema = 'xcl-perf-run' + version = 1 + commit = $commit + dirty = $false + build = [ordered]@{ + profile = 'release' + command = 'cargo ' + [string]::Join(' ', $cargoArguments) + arguments = @($cargoArguments) + cargo_features = $cargoFeaturesCanonical + target_dir_kind = $cargoTargetKind + executable_sha256 = $xclSha256 + } + workload_id = $workloadIdentity.id + workload_id_algorithm = $workloadIdentity.algorithm + workload_id_version = $workloadIdentity.version + run_order = @('xcl-cold', 'xcl-warm') + system = [ordered]@{ cpu = $cpu; windows = $windows; rust = $rust } + environment = $recordedEnvironment + cache = [ordered]@{ + identity = $cacheId + xcl_data = 'fresh for cold; same ephemeral directory reused for warm' + dxil = 'fresh for cold; same ephemeral directory reused for warm' + driver = 'uncontrolled' + } + runs = $runs + } + $manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $outPath 'manifest.json') -Encoding utf8 + Write-Host "Performance artifacts: $outPath" +} finally { + foreach ($name in $changedNames) { + $old = $savedEnvironment[$name] + if ($null -eq $old) { + Remove-Item -Path "Env:$name" -ErrorAction SilentlyContinue + } else { + Set-Item -Path "Env:$name" -Value $old + } + } + if (Test-Path -LiteralPath $cacheRoot) { + Remove-Item -LiteralPath $cacheRoot -Recurse -Force + } +} diff --git a/scripts/perf-run.tests.ps1 b/scripts/perf-run.tests.ps1 new file mode 100644 index 0000000000..986ddb05db --- /dev/null +++ b/scripts/perf-run.tests.ps1 @@ -0,0 +1,164 @@ +# Run on Windows with powershell.exe or pwsh.exe. Uses a clean temporary repository and mock +# cargo/XCL commands; no game executable is run. +$ErrorActionPreference = 'Stop' +$runnerSource = Join-Path $PSScriptRoot 'perf-run.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-run-test-' + [guid]::NewGuid()) +$repo = Join-Path $fixture 'repo' +$scripts = Join-Path $repo 'scripts' +$game = Join-Path $fixture 'Mock Game' +$out = Join-Path $fixture 'artifacts' +$otherGame = Join-Path (Join-Path $fixture 'other-build') 'Mock Game' +$otherOut = Join-Path $fixture 'other-artifacts' +$featureOut = Join-Path $fixture 'feature-artifacts' +$featureTarget = Join-Path $fixture 'feature target' +$bin = Join-Path $fixture 'bin' +$userData = Join-Path $fixture 'user-data' +$userDxil = Join-Path $fixture 'user-dxil' +$cargoMarker = Join-Path $fixture 'cargo.txt' +$mockXcl = Join-Path $bin 'mock-xcl.cmd' +$oldPath = $env:PATH +$oldTest = $env:XCL_PERF_RUN_TESTING +$oldTestXcl = $env:XCL_PERF_RUN_TEST_XCL +$oldData = $env:XCL_DATA_ROOT +$oldDxil = $env:XCL_DXIL_CACHE +$oldPress = $env:XCL_PRESS_AT +$oldGpuTiming = $env:XCL_GPU_TIMING +$oldGpuTimingMs = $env:XCL_GPU_TIMING_MS + +try { + $null = New-Item -ItemType Directory -Path $scripts, $game, $bin, $userData, $userDxil + Copy-Item -LiteralPath $runnerSource -Destination (Join-Path $scripts 'perf-run.ps1') + 'target/' | Set-Content -LiteralPath (Join-Path $repo '.gitignore') -Encoding Ascii + 'not copied' | Set-Content -LiteralPath (Join-Path $game 'game-data.bin') -Encoding Ascii + 'keep' | Set-Content -LiteralPath (Join-Path $userData 'sentinel.txt') -Encoding Ascii + 'keep' | Set-Content -LiteralPath (Join-Path $userDxil 'sentinel.txt') -Encoding Ascii + + @' +@echo off +echo %* > "%MOCK_CARGO_MARKER%" +exit /b 0 +'@ | Set-Content -LiteralPath (Join-Path $bin 'cargo.cmd') -Encoding Ascii + @' +@echo off +echo rustc 1.test +echo host: x86_64-pc-windows-msvc +exit /b 0 +'@ | Set-Content -LiteralPath (Join-Path $bin 'rustc.cmd') -Encoding Ascii + @' +@echo off +set STATE=warm +if not exist "%XCL_DXIL_CACHE%\seen" set STATE=cold +if exist "%XCL_DXIL_CACHE%\seen" goto marker_done +echo seen>"%XCL_DXIL_CACHE%\seen" +:marker_done +if not exist "%XCL_DATA_ROOT%\MockTitle\logs" mkdir "%XCL_DATA_ROOT%\MockTitle\logs" +echo cache=%STATE%>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" +echo gpu_timing=%XCL_GPU_TIMING% threshold=%XCL_GPU_TIMING_MS%>>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" +echo {"d3d12":{"adapter":"Mock GPU","submissions":2,"slowest_submission_ms":1.5,"slowest_submission_lists":3}}>"%XCL_DATA_ROOT%\MockTitle\logs\report.json" +echo Log: %XCL_DATA_ROOT%\MockTitle\logs\xcl.log +exit /b 0 +'@ | Set-Content -LiteralPath $mockXcl -Encoding Ascii + + & git.exe -C $repo init | Out-Null + & git.exe -C $repo add . + & git.exe -C $repo -c user.name='XCL test' -c user.email='xcl-test@example.invalid' -c commit.gpgsign=false commit -m fixture | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'could not create clean fixture repository' } + + $env:PATH = $bin + [IO.Path]::PathSeparator + $oldPath + $env:MOCK_CARGO_MARKER = $cargoMarker + $env:XCL_PERF_RUN_TESTING = '1' + $env:XCL_PERF_RUN_TEST_XCL = $mockXcl + $env:XCL_DATA_ROOT = $userData + $env:XCL_DXIL_CACHE = $userDxil + $env:XCL_PRESS_AT = '20:A,24:A' + $env:XCL_GPU_TIMING = 'caller-value' + $env:XCL_GPU_TIMING_MS = '999' + + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $out -Seconds 2 + if ($LASTEXITCODE -ne 0) { throw "perf-run.ps1 exited with $LASTEXITCODE" } + + $manifest = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $manifestRaw = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 + if ($manifest.schema -ne 'xcl-perf-run' -or $manifest.version -ne 1) { throw 'wrong manifest schema/version' } + if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { throw 'build identity was not recorded' } + if (($manifest.run_order -join ',') -ne 'xcl-cold,xcl-warm') { throw 'run order was not cold then warm' } + if ($manifest.cache.driver -ne 'uncontrolled') { throw 'driver cache was not labelled uncontrolled' } + if ($manifest.environment.XCL_PRESS_AT -ne '20:A,24:A') { throw 'input schedule was not recorded' } + if ($manifest.environment.XCL_GPU_TIMING -ne '1' -or $manifest.environment.XCL_GPU_TIMING_MS -ne '50') { + throw 'submission timing settings were not forced and recorded' + } + if ($manifest.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or + $manifest.workload_id_version -ne 1) { throw 'workload identity algorithm/version was not recorded' } + if ($manifest.workload_id -notmatch '^[0-9a-f]{64}$') { throw 'workload identity is not a full SHA-256 value' } + if ($manifestRaw.Contains($game) -or $manifestRaw.Contains('game-data.bin')) { + throw 'workload inventory details leaked into the manifest' + } + if ($manifest.runs.Count -ne 2 -or $manifest.runs[0].cache_state -ne 'xcl-cold' -or $manifest.runs[1].cache_state -ne 'xcl-warm') { throw 'run records are incomplete' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'cache=cold') { throw 'cold run did not start with a fresh DXIL cache' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\02-warm\xcl.log') -Raw) -notmatch 'cache=warm') { throw 'warm run did not reuse the cold cache' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'gpu_timing=1 threshold=50') { + throw 'submission timing settings were not passed to XCL' + } + if (-not (Test-Path -LiteralPath (Join-Path $out 'runs\01-cold\report.json')) -or -not (Test-Path -LiteralPath (Join-Path $out 'runs\02-warm\report.json'))) { throw 'reports were not preserved' } + $timing = (Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\report.json') -Raw -Encoding utf8 | ConvertFrom-Json).d3d12 + if ($timing.submissions -ne 2 -or $timing.slowest_submission_ms -ne 1.5 -or $timing.slowest_submission_lists -ne 3) { + throw 'submission timing fields were not preserved' + } + $artifactFiles = @(Get-ChildItem -LiteralPath $out -Recurse -File) + $unexpectedArtifacts = @($artifactFiles | Where-Object { $_.Name -notin @('manifest.json', 'xcl.log', 'report.json') }) + if ($artifactFiles.Count -ne 5 -or $unexpectedArtifacts.Count -ne 0) { throw 'the artifact folder contains something other than logs, reports, and the manifest' } + if ($env:XCL_DATA_ROOT -ne $userData -or $env:XCL_DXIL_CACHE -ne $userDxil -or + $env:XCL_GPU_TIMING -ne 'caller-value' -or $env:XCL_GPU_TIMING_MS -ne '999') { + throw 'the caller environment was not restored' + } + if (-not (Test-Path -LiteralPath (Join-Path $userData 'sentinel.txt')) -or -not (Test-Path -LiteralPath (Join-Path $userDxil 'sentinel.txt'))) { throw 'a user cache was touched' } + if (Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$($manifest.cache.identity)"))) { throw 'the ephemeral cache was not removed' } + if ((Get-Content -LiteralPath $cargoMarker -Raw) -notmatch 'build --locked --release -p xcl') { throw 'release build command was not run' } + + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $featureOut -Seconds 2 ` + -CargoFeatures @('zeta,alpha', 'alpha') -CargoTargetDir $featureTarget + if ($LASTEXITCODE -ne 0) { throw "feature perf-run.ps1 exited with $LASTEXITCODE" } + $featureManifest = Get-Content -LiteralPath (Join-Path $featureOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ((@($featureManifest.build.cargo_features) -join ',') -ne 'alpha,zeta' -or + $featureManifest.build.target_dir_kind -ne 'explicit' -or + $featureManifest.build.executable_sha256 -notmatch '^[0-9a-f]{64}$') { + throw 'the canonical Cargo build variant was not recorded' + } + $cargoInvocation = Get-Content -LiteralPath $cargoMarker -Raw + if ($cargoInvocation -notmatch '--features=alpha,zeta' -or + $cargoInvocation -notmatch '--target-dir' -or + $cargoInvocation -notmatch ([regex]::Escape($featureTarget))) { + throw 'Cargo features/target directory were not passed as canonical arguments' + } + + $null = New-Item -ItemType Directory -Path $otherGame -Force + 'a different title build with the same folder leaf' | Set-Content -LiteralPath (Join-Path $otherGame 'game-data.bin') -Encoding Ascii + & (Join-Path $scripts 'perf-run.ps1') -Game $otherGame -OutDir $otherOut -Seconds 2 + if ($LASTEXITCODE -ne 0) { throw "second perf-run.ps1 exited with $LASTEXITCODE" } + $otherManifest = Get-Content -LiteralPath (Join-Path $otherOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ($otherManifest.workload_id -eq $manifest.workload_id) { + throw 'different builds with the same folder leaf received the same workload identity' + } + + Add-Content -LiteralPath (Join-Path $repo '.gitignore') -Value '# dirty' + $refused = $false + try { + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir (Join-Path $fixture 'dirty-out') -Seconds 2 + } catch { + $refused = $_.Exception.Message -match 'clean worktree' + } + if (-not $refused) { throw 'a dirty worktree was not refused' } + + Write-Host 'perf-run tests: all assertions passed' +} finally { + $env:PATH = $oldPath + $env:XCL_PERF_RUN_TESTING = $oldTest + $env:XCL_PERF_RUN_TEST_XCL = $oldTestXcl + $env:XCL_DATA_ROOT = $oldData + $env:XCL_DXIL_CACHE = $oldDxil + $env:XCL_PRESS_AT = $oldPress + $env:XCL_GPU_TIMING = $oldGpuTiming + $env:XCL_GPU_TIMING_MS = $oldGpuTimingMs + Remove-Item Env:MOCK_CARGO_MARKER -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } +}