Add a fenced D3D12 resource retention probe

This commit is contained in:
ghptc
2026-11-28 16:41:57 -03:00
parent 923e38cc8c
commit 60bd360edf
3 changed files with 485 additions and 0 deletions

View File

@ -0,0 +1,278 @@
//! Independent D3D12 copy workload. See docs/research/resource-retention.md.
use std::io::{self, Write};
use std::time::{Duration, Instant};
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
use windows::Win32::Graphics::Direct3D12::*;
use windows::Win32::Graphics::Dxgi::Common::*;
use windows::Win32::Graphics::Dxgi::*;
use windows::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
use windows::core::Interface;
const BATCH: usize = 32 << 20;
const WAVES: usize = 4;
struct Event(HANDLE);
impl Drop for Event {
fn drop(&mut self) {
// SAFETY: this object owns the event.
let _ = unsafe { CloseHandle(self.0) };
}
}
fn buffer(
device: &ID3D12Device,
heap: D3D12_HEAP_TYPE,
size: usize,
state: D3D12_RESOURCE_STATES,
) -> anyhow::Result<ID3D12Resource> {
let mut resource = None;
// SAFETY: one subresource, valid heap/state pair, initialized out pointer.
unsafe {
device.CreateCommittedResource(
&D3D12_HEAP_PROPERTIES {
Type: heap,
CreationNodeMask: 1,
VisibleNodeMask: 1,
..Default::default()
},
D3D12_HEAP_FLAG_NONE,
&D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
Width: size as u64,
Height: 1,
DepthOrArraySize: 1,
MipLevels: 1,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
..Default::default()
},
state,
None,
&mut resource,
)?;
}
resource.ok_or_else(|| anyhow::anyhow!("missing buffer"))
}
fn sample(
adapter: &IDXGIAdapter3,
phase: &str,
wave: usize,
transient_bytes: usize,
fixed: usize,
sync: bool,
) -> anyhow::Result<()> {
let usage = |segment| {
let mut info = DXGI_QUERY_VIDEO_MEMORY_INFO::default();
// SAFETY: query on node zero of the selected adapter.
unsafe { adapter.QueryVideoMemoryInfo(0, segment, &mut info) }
.map(|_| info.CurrentUsage.to_string())
.unwrap_or_else(|_| "NA".into())
};
println!(
"SAMPLE {phase} {wave} {transient_bytes} {fixed} {} {}",
usage(DXGI_MEMORY_SEGMENT_GROUP_LOCAL),
usage(DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL)
);
if sync {
io::stdout().flush()?;
let mut ack = String::new();
io::stdin().read_line(&mut ack)?;
anyhow::ensure!(ack.trim() == "next", "phase observer disconnected");
}
Ok(())
}
fn main() -> anyhow::Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
let mode = args.first().map(String::as_str).unwrap_or("");
let sync = args.iter().skip(1).any(|v| v == "--sync");
let small = args.iter().skip(1).any(|v| v == "--small");
let size = if small { 64 << 10 } else { 4 << 20 };
let slots = BATCH / size;
anyhow::ensure!(
matches!(mode, "release" | "reuse" | "hold")
&& args.len() == 1 + usize::from(sync) + usize::from(small),
"usage: resource_retention <release|reuse|hold> [--small] [--sync]"
);
// SAFETY: each copy submission completes before its allocator, mappings or buffers are reused.
unsafe {
let factory: IDXGIFactory1 = CreateDXGIFactory1()?;
let mut i = 0;
let (adapter, device) = loop {
let adapter = factory.EnumAdapters1(i)?;
i += 1;
let desc = adapter.GetDesc1()?;
let mut device: Option<ID3D12Device> = None;
if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0
&& D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device).is_ok()
{
let end = desc
.Description
.iter()
.position(|v| *v == 0)
.unwrap_or(desc.Description.len());
println!(
"ADAPTER {}",
String::from_utf16_lossy(&desc.Description[..end])
);
break (adapter.cast::<IDXGIAdapter3>()?, device.unwrap());
}
};
let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
Type: D3D12_COMMAND_LIST_TYPE_COPY,
..Default::default()
})?;
let allocator: ID3D12CommandAllocator =
device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?;
let list: ID3D12GraphicsCommandList =
device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?;
list.Close()?;
let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
let signal = Event(CreateEventW(None, false, false, None)?);
sample(&adapter, "device", 0, 0, 0, sync)?;
let upload = buffer(
&device,
D3D12_HEAP_TYPE_UPLOAD,
BATCH,
D3D12_RESOURCE_STATE_GENERIC_READ,
)?;
let back = buffer(
&device,
D3D12_HEAP_TYPE_READBACK,
BATCH,
D3D12_RESOURCE_STATE_COPY_DEST,
)?;
let mut live = Vec::new();
let mut creates = 0;
let mut elapsed = Duration::ZERO;
let full = D3D12_RANGE {
Begin: 0,
End: BATCH,
};
let empty = D3D12_RANGE::default();
for wave in 1..=WAVES {
let start = Instant::now();
if mode != "reuse" || live.is_empty() {
for _ in 0..slots {
live.push(buffer(
&device,
D3D12_HEAP_TYPE_DEFAULT,
size,
D3D12_RESOURCE_STATE_COMMON,
)?);
creates += 1;
}
}
let allocated = start.elapsed();
let destinations = &live[live.len() - slots..];
let word = |i: usize| (i as u32).wrapping_mul(2654435761) ^ wave as u32;
let mut ptr = std::ptr::null_mut();
upload.Map(0, Some(&empty), Some(&mut ptr))?;
for (i, dst) in std::slice::from_raw_parts_mut(ptr.cast::<u32>(), BATCH / 4)
.iter_mut()
.enumerate()
{
*dst = word(i);
}
upload.Unmap(0, Some(&full));
let uploaded = start.elapsed();
let mut copies = [[Duration::ZERO; 3]; 2];
// Buffers decay to COMMON between ExecuteCommandLists calls on a copy queue.
for (pass, times) in copies.iter_mut().enumerate() {
let record = Instant::now();
allocator.Reset()?;
list.Reset(&allocator, None)?;
for (i, dst) in destinations.iter().enumerate() {
let offset = (i * size) as u64;
if pass == 0 {
list.CopyBufferRegion(dst, 0, &upload, offset, size as u64);
} else {
list.CopyBufferRegion(&back, offset, dst, 0, size as u64);
}
}
list.Close()?;
let executable = list.cast()?;
times[0] = record.elapsed();
let submit = Instant::now();
queue.ExecuteCommandLists(&[Some(executable)]);
let value = (2 * wave - 1 + pass) as u64;
queue.Signal(&fence, value)?;
times[1] = submit.elapsed();
let wait = Instant::now();
fence.SetEventOnCompletion(value, signal.0)?;
anyhow::ensure!(
WaitForSingleObject(signal.0, 3000) == WAIT_OBJECT_0
&& fence.GetCompletedValue() == value,
"fence {value} failed"
);
times[2] = wait.elapsed();
}
let verify = Instant::now();
back.Map(0, Some(&full), Some(&mut ptr))?;
let mismatch = std::slice::from_raw_parts(ptr.cast::<u32>(), BATCH / 4)
.iter()
.enumerate()
.position(|(i, &v)| v != word(i));
back.Unmap(0, Some(&empty));
anyhow::ensure!(
mismatch.is_none(),
"wave {wave}, first wrong word {mismatch:?}"
);
let verified = verify.elapsed();
elapsed += start.elapsed();
println!(
"TIMING {wave} {} {} {} {} {} {} {} {} {}",
allocated.as_micros(),
(uploaded - allocated).as_micros(),
copies[0][0].as_micros(),
copies[0][1].as_micros(),
copies[0][2].as_micros(),
copies[1][0].as_micros(),
copies[1][1].as_micros(),
copies[1][2].as_micros(),
verified.as_micros()
);
sample(
&adapter,
"verified",
wave,
live.len() * size,
2 * BATCH,
sync,
)?;
let start = Instant::now();
if mode == "release" {
live.clear();
}
elapsed += start.elapsed();
sample(
&adapter,
"between",
wave,
live.len() * size,
2 * BATCH,
sync,
)?;
}
drop((live, upload, back));
sample(&adapter, "released", WAVES, 0, 0, sync)?;
std::thread::sleep(Duration::from_secs(1));
sample(&adapter, "idle", WAVES, 0, 0, sync)?;
device.GetDeviceRemovedReason()?;
drop((list, allocator, queue, fence, signal, device));
sample(&adapter, "device_dropped", WAVES, 0, 0, sync)?;
println!(
"RESULT {mode} {creates} {} {} {}",
2 * WAVES,
BATCH * WAVES,
elapsed.as_micros()
);
}
Ok(())
}

View File

@ -0,0 +1,42 @@
# D3D12 resource lifetime and Linux reclaim
The `resource_retention` example submits generated buffer copies and checks every word on readback. It runs without a renderer, a window, or game files. Each process executes four 32 MiB waves and verifies 128 MiB after eight fences. Each fence wait has a three-second timeout. The example logs separate times for allocation, upload, command recording, submission and signal, fence completion, and readback verification.
## Run the resource lifetime control
Build with the workspace's Windows toolchain. On Linux, use the same MSVC target with `cargo xwin build`.
```sh
cargo build --locked --release -p victory-gpu --example resource_retention
```
Start a fresh process for each mode. Use `--small` to compare 64 KiB default buffers with the default 4 MiB buffers. The modes have the same upload, copy and verification work.
| Mode | Default buffer lifetime | Maximum requested default buffer bytes |
| --- | --- | ---: |
| `release` | Create and release a set each wave | 32 MiB |
| `reuse` | Reuse one set after its fence completes | 32 MiB |
| `hold` | Retain every set through the final wave | 128 MiB |
All modes also retain one 32 MiB upload buffer and one 32 MiB readback buffer until all waves finish. The probe records requested live bytes at device initialization, after each verified readback, between waves, after buffer release, after one second idle, and after dropping the device. Local and nonlocal DXGI usage come from the same adapter on which the probe creates its device. A DXGI query failure prints `NA`.
## Observe the Linux cgroup and NVIDIA clients
Use an isolated Wine or Proton prefix, a bounded dedicated cgroup v2 service, and the NVIDIA adapter UUID from `nvidia-smi`. The example takes the first nonsoftware adapter that can create a D3D12 feature-level 12.0 device. Check the printed adapter and the per-client IDs against the intended GPU. A private prefix keeps unrelated Wine processes outside the measurements.
```sh
python3 scripts/sample_resource_retention.py \
/path/to/wine /path/to/resource_retention.exe release GPU-UUID phases.jsonl
```
The observer uses the probe's `--sync` handshake to hold application state while sampling NVIDIA clients by Linux PID and cgroup membership. Give each run a fresh output filename. Use the service's supervisor to terminate the entire process group if a child or driver call hangs.
Compare requested live bytes with DXGI and per-client driver readings from the same phase. Per-client VRAM includes runtime and device allocations and can use different units and accounting from DXGI. Cgroup charge includes the Wine and observer processes, file cache and kernel memory. It can move independently of both device counters. Releasing the resources, idling with the device present, dropping the device and exiting are separate checkpoints.
## Compare a cgroup soft limit
Pass `--cache-file` to add a fixed 224 MiB clean, disk-backed file read to the same D3D12 workload. Use a new file for each fresh service and make its pages cold before the service reads them. An already cached file can be charged elsewhere. The observer reads 96 MiB before the first wave and schedules a 32 MiB read alongside each wave. It records when each read starts and ends, along with cgroup counter snapshots around the wave. The caller supplies the service limits.
Within a comparison, keep the mode, buffer size, readback checks, driver, file-read schedule, hard limit and swap policy fixed. Use a watermarked treatment and a control with enough headroom for the bounded cache. Verify that the treatment has overlapping file reads, positive direct-reclaim counters and `memory.high` events during completed waves. Review the wave boundaries because the cache read may finish after verification. Reverse the treatment order on repeat. Preserve the console log and raw telemetry and record any non-engaging or incomplete runs separately.
Use the application timeline to compare where elapsed time changes. The Linux observer's monotonic timestamps bracket launch of each wave and receipt of its timing line. The first bracket also includes creating the fixed transfer buffers. The in-process timings give subphase durations. Cgroup counters cover all tasks in the service, so identifying a reclaiming thread requires per-task tracing. Use PSI totals to measure stall time and `memory.events` to count events. Check hard-limit, swap and OOM counters separately. [Linux cgroup v2 memory interface](https://docs.kernel.org/admin-guide/cgroup-v2.html#memory-interface-files) · [DXGI video memory accounting](https://learn.microsoft.com/windows/win32/api/dxgi1_4/nf-dxgi1_4-idxgiadapter3-queryvideomemoryinfo)

View File

@ -0,0 +1,165 @@
"""Run the Windows probe under Wine, sampling each quiescent phase in its cgroup."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import os
from pathlib import Path
import stat
import subprocess
import time
import xml.etree.ElementTree as ET
MIB = 1 << 20
CACHE_PRIME = 96 * MIB
CACHE_PER_WAVE = 32 * MIB
WAVES = 4
TIMING_FIELDS = (
"allocation", "upload", "record_upload", "submit_upload", "fence_upload",
"record_readback", "submit_readback", "fence_readback", "verify",
)
def counters(path):
return {key: int(value) for key, value in (line.split() for line in path.read_text().splitlines())}
def memory(group):
start = time.monotonic_ns()
service_bytes = int((group / "memory.current").read_text())
peak = int((group / "memory.peak").read_text())
swap = int((group / "memory.swap.current").read_text())
stat_values = counters(group / "memory.stat")
events = counters(group / "memory.events")
pressure = (group / "memory.pressure").read_text().splitlines()
return dict(counters_start_ns=start, monotonic_ns=time.monotonic_ns(),
service_bytes=service_bytes, service_peak_bytes=peak, swap_bytes=swap,
stat={k: stat_values.get(k) for k in ("anon", "file", "shmem", "pgscan_direct", "pgsteal_direct",
"workingset_refault_anon", "workingset_refault_file")},
events=events,
psi_us={row[0]: int(row[-1].split("=")[1]) for line in pressure if (row := line.split())})
def snapshot(group, gpu, pid):
root = ET.fromstring(subprocess.check_output(["nvidia-smi", "-i", gpu, "-q", "-x"], timeout=3))
adapter = root.find("gpu")
if adapter is None or adapter.findtext("uuid") != gpu:
raise ValueError("expected the selected NVIDIA GPU UUID")
clients = adapter.findall("./processes/process_info")
service_pids = set((group / "cgroup.procs").read_text().split())
def mib(value):
if value is None or value == "N/A":
return None
amount, unit = value.split()
if unit != "MiB":
raise ValueError(value)
return int(amount)
service_clients = {c.findtext("pid"): mib(c.findtext("used_memory")) for c in clients
if c.findtext("pid") in service_pids}
return dict(wine_launcher_pid=pid, client_vram_MiB=service_clients,
device_vram_MiB=mib(adapter.findtext("fb_memory_usage/used")), **memory(group))
def read_cache(cache, destination, size):
start = time.monotonic_ns()
for _ in range(size // MIB):
if cache.readinto(destination) != len(destination):
raise ValueError("short read from the pressure fixture")
return dict(start_ns=start, end_ns=time.monotonic_ns(), bytes=size)
def run(wine, exe, mode, gpu, output, small, cache_file, destination):
path = next(s[3:] for s in Path("/proc/self/cgroup").read_text().splitlines() if s.startswith("0::"))
group = Path("/sys/fs/cgroup") / path.lstrip("/")
# The soft and hard limits and a fresh private prefix belong to the calling service.
if (group / "memory.max").read_text().strip() == "max" or not os.environ.get("WINEPREFIX"):
raise RuntimeError("run in a bounded service with a private WINEPREFIX")
phases = [("device", 0), *((p, w) for w in range(1, WAVES + 1) for p in ("verified", "between")),
("released", WAVES), ("idle", WAVES), ("device_dropped", WAVES)]
size = 64 << 10 if small else 4 << 20
slots = (32 << 20) // size
with output.open("x", buffering=1) as log, ThreadPoolExecutor(max_workers=1) as reader, subprocess.Popen(
[wine, str(exe.resolve()), mode, "--sync", *(["--small"] if small else [])], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
text=True, bufsize=1,
) as child:
seen = 0
timed_waves = 0
result = None
active = None
try:
for line in child.stdout:
received_ns = time.monotonic_ns()
print(line, end="", flush=True)
if line.startswith("TIMING "):
finished = memory(group)
_, wave, *times = line.split()
timed_waves += 1
if int(wave) != timed_waves or len(times) != len(TIMING_FIELDS) or active is None:
raise ValueError(f"unexpected timing record for wave {wave}")
before, cache_read, ack_ns = active
timing = dict(zip(TIMING_FIELDS, map(int, times), strict=True))
print(json.dumps(dict(phase="timing", wave=int(wave), timing_us=timing, before=before,
ack_ns=ack_ns, timing_received_ns=received_ns, after=finished,
cache=cache_read.result(timeout=3) if cache_read else None)),
file=log)
active = None
if line.startswith("SAMPLE "):
_, phase, wave, live, fixed, local, shared = line.split()
if seen >= len(phases) or phases[seen] != (phase, int(wave)):
raise ValueError(f"unexpected phase {phase}/{wave}")
row = snapshot(group, gpu, child.pid)
row.update(phase=phase, wave=int(wave), transient_bytes=int(live), transfer_bytes=int(fixed),
dxgi_local=None if local == "NA" else int(local),
dxgi_nonlocal=None if shared == "NA" else int(shared))
print(json.dumps(row), file=log)
if phase == "device" and cache_file:
prime = read_cache(cache_file, destination, CACHE_PRIME)
print(json.dumps(dict(phase="cache_primed", cache=prime, **memory(group))), file=log)
if phase == "device" or (phase == "between" and int(wave) < WAVES):
before = memory(group)
cache_read = reader.submit(read_cache, cache_file, destination, CACHE_PER_WAVE) if cache_file else None
active = (before, cache_read, time.monotonic_ns())
if phase == "verified" and (active is not None or timed_waves != int(wave)):
raise ValueError(f"missing timing record for wave {wave}")
child.stdin.write("next\n")
child.stdin.flush()
seen += 1
if line.startswith("RESULT "):
_, actual_mode, creates, fences, checked, micros = line.split()
if (actual_mode, int(creates), int(fences), int(checked)) != (
mode, slots if mode == "reuse" else WAVES * slots, 2 * WAVES, 128 * MIB):
raise ValueError("workload totals differ")
result = dict(mode=mode, buffer_bytes=size, creates=int(creates), fences=int(fences), checked_bytes=int(checked),
workload_us=int(micros))
if child.wait(timeout=3) or result is None or seen != len(phases):
raise RuntimeError("incomplete workload")
print(json.dumps(dict(phase="exit", **result, **snapshot(group, gpu, child.pid))), file=log)
finally:
if child.poll() is None:
child.kill()
def main(args):
cache_file = args.pop("cache_file")
if cache_file is None:
run(**args, cache_file=None, destination=None)
return
with cache_file.open("rb", buffering=0) as cache:
info = os.fstat(cache.fileno())
if not stat.S_ISREG(info.st_mode) or info.st_size != CACHE_PRIME + CACHE_PER_WAVE * WAVES:
raise ValueError("use a regular 224 MiB private disk-backed pressure fixture")
os.posix_fadvise(cache.fileno(), 0, 0, os.POSIX_FADV_RANDOM)
run(**args, cache_file=cache, destination=bytearray(MIB))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("wine")
parser.add_argument("exe", type=Path)
parser.add_argument("mode", choices=("release", "reuse", "hold"))
parser.add_argument("gpu", help="NVIDIA GPU UUID selected by the D3D12 probe")
parser.add_argument("output", type=Path)
parser.add_argument("--small", action="store_true", help="use 64 KiB transient buffers")
parser.add_argument("--cache-file", type=Path, help="read a cold 224 MiB private disk-backed file during the workload")
main(vars(parser.parse_args()))