victory-gta6: this fork's changes on top of VIctory main (ffe310e)
World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI (Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README describes the state, the changes and the credits. Based on VIctory by Marvisak and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as a reference. No game files are included. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
45c6e80601
commit
6fa814fba5
61 files changed
+32259
-1274
No files matched your search
@@ -109,6 +109,15 @@ impl GraphicsState {
|
||||
// pipeline uses the plain description); bring it back
|
||||
// with a stream if a title enables it.
|
||||
let d = data.cast::<D3D12_DEPTH_STENCIL_DESC1>().read_unaligned();
|
||||
if d.DepthBoundsTestEnable.as_bool() {
|
||||
static SEEN: std::sync::atomic::AtomicU64 =
|
||||
std::sync::atomic::AtomicU64::new(0);
|
||||
if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
|
||||
tracing::warn!(
|
||||
"a pipeline enables the depth bounds test, which its host pipeline leaves out: its draws pass at every depth"
|
||||
);
|
||||
}
|
||||
}
|
||||
self.depth = D3D12_DEPTH_STENCIL_DESC {
|
||||
DepthEnable: d.DepthEnable,
|
||||
DepthWriteMask: d.DepthWriteMask,
|
||||
@@ -156,7 +165,9 @@ impl GraphicsState {
|
||||
15 => {
|
||||
self.targets = data.cast::<D3D12_RT_FORMAT_ARRAY>().read_unaligned();
|
||||
for f in &mut self.targets.RTFormats {
|
||||
f.0 = crate::resource::pc_format(f.0 as u32) as i32;
|
||||
f.0 = crate::resource::target_format(crate::resource::pc_format(
|
||||
f.0 as u32,
|
||||
)) as i32;
|
||||
}
|
||||
}
|
||||
16 => {
|
||||
@@ -243,6 +254,17 @@ pub(crate) struct Input {
|
||||
const RECTANGLES: i32 = 19;
|
||||
const QUADS: i32 = 32;
|
||||
|
||||
/// Whether the title's root SRVs are bound as one-view tables of the
|
||||
/// buffer's host copy, whose reads past its end return zeros, rather than
|
||||
/// as root descriptors, which have no size: a mesh shader's vertex fetch
|
||||
/// has no record limit, and a read past the copy reaches whatever the host
|
||||
/// placed after it (memory it has freed: the device is removed, upstream
|
||||
/// PR #493). `VICTORY_ROOT_SRV_DIRECT=1` goes back to root descriptors.
|
||||
pub(crate) fn bounded_root_srvs() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_ROOT_SRV_DIRECT").is_none())
|
||||
}
|
||||
|
||||
/// One stage of a host pipeline and where its bindings go.
|
||||
pub(crate) struct Stage {
|
||||
pub(crate) shader: Arc<Shader>,
|
||||
@@ -251,6 +273,9 @@ pub(crate) struct Stage {
|
||||
/// Root parameters of its root views: (title root parameter, ours).
|
||||
pub(crate) root_cbvs: Vec<(u8, u32)>,
|
||||
pub(crate) root_srvs: Vec<(u8, u32)>,
|
||||
/// Root UAVs: one-view tables like the SRVs (or root descriptors with
|
||||
/// `VICTORY_ROOT_SRV_DIRECT=1`).
|
||||
pub(crate) root_uavs: Vec<(u8, u32)>,
|
||||
}
|
||||
|
||||
impl Stage {
|
||||
@@ -273,8 +298,15 @@ pub(crate) struct HostPipeline {
|
||||
/// The vertex buffer slots it reads (bit per slot).
|
||||
pub(crate) slots: u32,
|
||||
pub(crate) inputs: Vec<Input>,
|
||||
/// Has the geometry stage that completes the console's rectangles
|
||||
/// (`victory_shader::emit::rect_list_gs`): its rectangle draws go out
|
||||
/// as the title gives them, three vertices a rectangle.
|
||||
pub(crate) rects: bool,
|
||||
/// Its shaders, for reports of slow submissions.
|
||||
pub(crate) name: String,
|
||||
/// Its depth, stencil, cull and blend state in short, for the frame
|
||||
/// listing (empty for compute).
|
||||
pub(crate) state: String,
|
||||
}
|
||||
|
||||
/// Logs a pipeline that gets no host pipeline, once per reason.
|
||||
@@ -292,6 +324,9 @@ impl HostPipeline {
|
||||
/// A host pipeline for vertex and pixel shaders with the graphics
|
||||
/// state `g`, or for one compute shader.
|
||||
pub(crate) fn new(shaders: &[Arc<Shader>], g: Option<&GraphicsState>) -> Option<HostPipeline> {
|
||||
// For the report when the host device is removed: what this thread
|
||||
// has in the library from here on.
|
||||
super::library::label(format!("{shaders:?}"));
|
||||
let find = |stage| shaders.iter().find(|s| s.stage == stage);
|
||||
let compute = match shaders {
|
||||
[cs] if cs.stage == "compute" => Some(cs),
|
||||
@@ -330,6 +365,9 @@ impl HostPipeline {
|
||||
|
||||
// The root signature the translated shaders' bindings define.
|
||||
let mut params: Vec<D3D12_ROOT_PARAMETER1> = Vec::new();
|
||||
// The ranges table parameters point at, alive until the root
|
||||
// signature is made.
|
||||
let mut ranges: Vec<Box<D3D12_DESCRIPTOR_RANGE1>> = Vec::new();
|
||||
let mut samplers = Vec::new();
|
||||
let mut bound = Vec::new();
|
||||
for &(shader, visibility) in &stages {
|
||||
@@ -339,6 +377,7 @@ impl HostPipeline {
|
||||
user_data: None,
|
||||
root_cbvs: Vec::new(),
|
||||
root_srvs: Vec::new(),
|
||||
root_uavs: Vec::new(),
|
||||
};
|
||||
let dwords = t.user_data_dwords();
|
||||
if dwords > 0 {
|
||||
@@ -366,8 +405,55 @@ impl HostPipeline {
|
||||
D3D12_ROOT_PARAMETER_TYPE_SRV,
|
||||
&mut stage.root_srvs,
|
||||
),
|
||||
(
|
||||
&t.root_uavs,
|
||||
D3D12_ROOT_PARAMETER_TYPE_UAV,
|
||||
&mut stage.root_uavs,
|
||||
),
|
||||
] {
|
||||
for &slot in slots {
|
||||
let uav = kind == D3D12_ROOT_PARAMETER_TYPE_UAV;
|
||||
// Ours, not the title's, stay root descriptors: the
|
||||
// table of strides, the directory of title memory by
|
||||
// address and its fault notes.
|
||||
let ours = if uav {
|
||||
slot == victory_shader::emit::SLOT_FAULTS
|
||||
} else {
|
||||
slot == victory_shader::emit::SLOT_STRIDES
|
||||
|| slot == victory_shader::emit::SLOT_MEMORY
|
||||
};
|
||||
if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() {
|
||||
// A one-view table: the view's size bounds the
|
||||
// reads (and a root UAV's writes), which a root
|
||||
// descriptor leaves unbounded.
|
||||
// (Our own table of strides stays a descriptor.)
|
||||
ranges.push(Box::new(D3D12_DESCRIPTOR_RANGE1 {
|
||||
RangeType: if uav {
|
||||
D3D12_DESCRIPTOR_RANGE_TYPE_UAV
|
||||
} else {
|
||||
D3D12_DESCRIPTOR_RANGE_TYPE_SRV
|
||||
},
|
||||
NumDescriptors: 1,
|
||||
BaseShaderRegister: u32::from(slot),
|
||||
RegisterSpace: ROOT_CBV_SPACE,
|
||||
Flags: D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE
|
||||
| D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE,
|
||||
OffsetInDescriptorsFromTableStart: 0,
|
||||
}));
|
||||
let range: *const D3D12_DESCRIPTOR_RANGE1 = &**ranges.last()?;
|
||||
out.push((slot, params.len() as u32));
|
||||
params.push(D3D12_ROOT_PARAMETER1 {
|
||||
ParameterType: D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE,
|
||||
Anonymous: D3D12_ROOT_PARAMETER1_0 {
|
||||
DescriptorTable: D3D12_ROOT_DESCRIPTOR_TABLE1 {
|
||||
NumDescriptorRanges: 1,
|
||||
pDescriptorRanges: range,
|
||||
},
|
||||
},
|
||||
ShaderVisibility: visibility,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
out.push((slot, params.len() as u32));
|
||||
params.push(D3D12_ROOT_PARAMETER1 {
|
||||
ParameterType: kind,
|
||||
@@ -451,6 +537,8 @@ impl HostPipeline {
|
||||
name: format!("{shaders:?}"),
|
||||
slots: 0,
|
||||
inputs: Vec::new(),
|
||||
rects: false,
|
||||
state: String::new(),
|
||||
});
|
||||
}
|
||||
let Some(g) = g else {
|
||||
@@ -458,8 +546,12 @@ impl HostPipeline {
|
||||
};
|
||||
let state = g.describe();
|
||||
if mesh.is_some() {
|
||||
// "triangles": the stream names its topology since it did not
|
||||
// load from the library without one (see `mesh_pipeline`); a
|
||||
// new name keeps such entries, stored before, from being
|
||||
// looked up again.
|
||||
let name = super::library::name(
|
||||
"mesh",
|
||||
"mesh triangles",
|
||||
&root_blob,
|
||||
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
|
||||
&state,
|
||||
@@ -483,14 +575,35 @@ impl HostPipeline {
|
||||
name: format!("{shaders:?}"),
|
||||
slots: 0,
|
||||
inputs: Vec::new(),
|
||||
rects: false,
|
||||
state: String::new(),
|
||||
});
|
||||
}
|
||||
|
||||
let desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
// A pipeline the title makes for rectangles gets a geometry stage
|
||||
// that completes each one from the three vertices the vertex
|
||||
// shader made. Without it (refused here or by the host) the draws
|
||||
// fall back on what `draw` does for rectangles.
|
||||
let mut rect_gs = None;
|
||||
if g.topology.0 == RECTANGLES {
|
||||
let ps = stages.get(1).and_then(|(s, _)| s.translated());
|
||||
let vs = &stages[0].0.translated()?.host.dxil;
|
||||
match victory_shader::emit::rect_list_gs(vs, ps.map(|t| &t.host.dxil[..])) {
|
||||
Ok(gs) => rect_gs = Some(gs),
|
||||
Err(e) => tracing::warn!(error = %e, ?shaders, "no rectangle geometry stage"),
|
||||
}
|
||||
}
|
||||
let mut desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC {
|
||||
// SAFETY: a borrowed pointer the description never releases.
|
||||
pRootSignature: unsafe { std::mem::transmute_copy(&root) },
|
||||
VS: code(0),
|
||||
PS: code(1),
|
||||
GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| {
|
||||
D3D12_SHADER_BYTECODE {
|
||||
pShaderBytecode: gs.as_ptr().cast(),
|
||||
BytecodeLength: gs.len(),
|
||||
}
|
||||
}),
|
||||
BlendState: g.blend,
|
||||
SampleMask: g.sample_mask,
|
||||
RasterizerState: g.rasterizer,
|
||||
@@ -512,19 +625,40 @@ impl HostPipeline {
|
||||
SampleDesc: g.samples,
|
||||
..Default::default()
|
||||
};
|
||||
let name = super::library::name(
|
||||
"graphics",
|
||||
&root_blob,
|
||||
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
|
||||
&state,
|
||||
);
|
||||
let made = super::library::pipeline(
|
||||
&name,
|
||||
// SAFETY: the description points at live data.
|
||||
|library, name| unsafe { library.LoadGraphicsPipeline(name, &desc) },
|
||||
// SAFETY: as above.
|
||||
|| unsafe { host.device.CreateGraphicsPipelineState(&desc) },
|
||||
);
|
||||
// A pipeline with the geometry stage has a name of its own in the
|
||||
// library; the others keep theirs.
|
||||
let name = |gs: Option<&Vec<u8>>| match gs {
|
||||
Some(gs) => super::library::name(
|
||||
"graphics rectangles",
|
||||
&root_blob,
|
||||
&[&code_bytes(&code(0)), &code_bytes(&code(1)), &gs[..]],
|
||||
&state,
|
||||
),
|
||||
None => super::library::name(
|
||||
"graphics",
|
||||
&root_blob,
|
||||
&[&code_bytes(&code(0)), &code_bytes(&code(1))],
|
||||
&state,
|
||||
),
|
||||
};
|
||||
let make = |desc: &D3D12_GRAPHICS_PIPELINE_STATE_DESC, name: &str| {
|
||||
super::library::pipeline(
|
||||
name,
|
||||
// SAFETY: the description points at live data.
|
||||
|library, name| unsafe { library.LoadGraphicsPipeline(name, desc) },
|
||||
// SAFETY: as above.
|
||||
|| unsafe { host.device.CreateGraphicsPipelineState(desc) },
|
||||
)
|
||||
};
|
||||
let mut made = make(&desc, &name(rect_gs.as_ref()));
|
||||
if made.is_err() && rect_gs.is_some() {
|
||||
// The host refused the geometry stage: once more without it.
|
||||
tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage");
|
||||
host.log_messages();
|
||||
desc.GS = D3D12_SHADER_BYTECODE::default();
|
||||
rect_gs = None;
|
||||
made = make(&desc, &name(None));
|
||||
}
|
||||
let pso = match made {
|
||||
Ok(pso) => pso,
|
||||
Err(e) => {
|
||||
@@ -553,12 +687,49 @@ impl HostPipeline {
|
||||
name: format!("{shaders:?}"),
|
||||
slots: g.slots(),
|
||||
inputs: g.elements(),
|
||||
rects: rect_gs.is_some(),
|
||||
state: {
|
||||
let (d, r, b) = (&g.depth, &g.rasterizer, &g.blend.RenderTarget[0]);
|
||||
let face = |f: &D3D12_DEPTH_STENCILOP_DESC| {
|
||||
format!(
|
||||
"fail {} depth-fail {} pass {} func {}",
|
||||
f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"depth {} write {} func {}; stencil {} read {:#x} write {:#x} front [{}] back [{}]; cull {} front-ccw {}; blend {} src {} dst {} op {} mask {:#x}",
|
||||
d.DepthEnable.as_bool(),
|
||||
d.DepthWriteMask.0,
|
||||
d.DepthFunc.0,
|
||||
d.StencilEnable.as_bool(),
|
||||
d.StencilReadMask,
|
||||
d.StencilWriteMask,
|
||||
face(&d.FrontFace),
|
||||
face(&d.BackFace),
|
||||
r.CullMode.0,
|
||||
r.FrontCounterClockwise.as_bool(),
|
||||
b.BlendEnable.as_bool(),
|
||||
b.SrcBlend.0,
|
||||
b.DestBlend.0,
|
||||
b.BlendOp.0,
|
||||
b.RenderTargetWriteMask
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A mesh pipeline from the title's graphics state: the pipeline-state
|
||||
/// stream form (no input layout or topology).
|
||||
/// stream form (no input layout).
|
||||
///
|
||||
/// The stream names a triangle topology, which D3D12 does not need for a
|
||||
/// mesh shader: without it the pipeline library refuses to load a stored
|
||||
/// pipeline with the very stream it was made from (`E_INVALIDARG`; debug
|
||||
/// layer message 972, "does not match the one used to create the PSO"), so
|
||||
/// every mesh pipeline was compiled again, and its store then refused (970,
|
||||
/// "already exists"). The translation makes triangle mesh shaders only
|
||||
/// (`mesh_prologue` refuses others), and the debug layer wants the two to
|
||||
/// agree (1323).
|
||||
fn mesh_pipeline(
|
||||
device: &ID3D12Device,
|
||||
root: &ID3D12RootSignature,
|
||||
@@ -583,6 +754,7 @@ fn mesh_pipeline(
|
||||
targets: Sub<D3D12_RT_FORMAT_ARRAY>,
|
||||
dsv: Sub<DXGI_FORMAT>,
|
||||
samples: Sub<DXGI_SAMPLE_DESC>,
|
||||
topology: Sub<D3D12_PRIMITIVE_TOPOLOGY_TYPE>,
|
||||
}
|
||||
let mut stream = Stream {
|
||||
root: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE, root.as_raw()),
|
||||
@@ -595,6 +767,10 @@ fn mesh_pipeline(
|
||||
targets: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS, g.targets),
|
||||
dsv: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT, g.depth_format),
|
||||
samples: Sub(D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_SAMPLE_DESC, g.samples),
|
||||
topology: Sub(
|
||||
D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_PRIMITIVE_TOPOLOGY,
|
||||
D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE,
|
||||
),
|
||||
};
|
||||
let desc = D3D12_PIPELINE_STATE_STREAM_DESC {
|
||||
SizeInBytes: size_of::<Stream>(),
|
||||
@@ -665,3 +841,84 @@ fn root_signature(
|
||||
Ok((device.CreateRootSignature(0, bytes)?, bytes.to_vec()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A triangle mesh shader of our own and a pixel shader for it.
|
||||
const MS: &str = "struct V { float4 p : SV_Position; };
|
||||
[outputtopology(\"triangle\")] [numthreads(1, 1, 1)]
|
||||
void main(out vertices V v[3], out indices uint3 t[1]) {
|
||||
SetMeshOutputCounts(3, 1);
|
||||
v[0].p = float4(0, 0, 0, 1);
|
||||
v[1].p = float4(1, 0, 0, 1);
|
||||
v[2].p = float4(0, 1, 0, 1);
|
||||
t[0] = uint3(0, 1, 2);
|
||||
}";
|
||||
const PS: &str = "float4 main() : SV_Target { return 1; }";
|
||||
|
||||
/// The PC `dxc.exe` (`VICTORY_PC_DXC`, else the newest Windows SDK's).
|
||||
fn dxc() -> Option<PathBuf> {
|
||||
let dxc = match std::env::var_os("VICTORY_PC_DXC") {
|
||||
Some(p) => PathBuf::from(p),
|
||||
None => victory_shader::emit::validator::Validator::default_path()?
|
||||
.with_file_name("dxc.exe"),
|
||||
};
|
||||
dxc.exists().then_some(dxc)
|
||||
}
|
||||
|
||||
fn compile(dxc: &Path, dir: &Path, src: &str, profile: &str) -> Vec<u8> {
|
||||
let (hlsl, out) = (
|
||||
dir.join(format!("{profile}.hlsl")),
|
||||
dir.join(format!("{profile}.dxil")),
|
||||
);
|
||||
std::fs::write(&hlsl, src).unwrap();
|
||||
let status = std::process::Command::new(dxc)
|
||||
.args(["-nologo", "-T", profile, "-E", "main", "-Fo"])
|
||||
.arg(&out)
|
||||
.arg(&hlsl)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "dxc failed for {profile}");
|
||||
std::fs::read(out).unwrap()
|
||||
}
|
||||
|
||||
fn code(bytes: &[u8]) -> D3D12_SHADER_BYTECODE {
|
||||
D3D12_SHADER_BYTECODE {
|
||||
pShaderBytecode: bytes.as_ptr().cast(),
|
||||
BytecodeLength: bytes.len(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A mesh pipeline made once is loaded from the library the next time,
|
||||
/// not compiled again (a stream without a topology never loads).
|
||||
#[test]
|
||||
fn a_mesh_pipeline_loads_from_the_library() {
|
||||
let Some(host) = host() else {
|
||||
return; // no host GPU here
|
||||
};
|
||||
let Some(dxc) = dxc() else {
|
||||
eprintln!("no PC dxc.exe; skipped");
|
||||
return;
|
||||
};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let ms = compile(&dxc, dir.path(), MS, "ms_6_5");
|
||||
let ps = compile(&dxc, dir.path(), PS, "ps_6_5");
|
||||
let (root, root_blob) = root_signature(&host.device, &[], &[], false).unwrap();
|
||||
let mut g = GraphicsState::default();
|
||||
g.targets.NumRenderTargets = 1;
|
||||
g.targets.RTFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe());
|
||||
mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made");
|
||||
let loaded = super::super::library::LOADED.load(Ordering::Relaxed);
|
||||
mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, &name).expect("made again");
|
||||
assert!(
|
||||
super::super::library::LOADED.load(Ordering::Relaxed) > loaded,
|
||||
"the mesh pipeline was compiled again instead of loaded from the library"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,45 @@
|
||||
//! graphics state); the next run hands those to the workers at
|
||||
//! creation, during loading.
|
||||
//!
|
||||
//! All library calls are serialised: the interface does not promise that
|
||||
//! stores, loads and serialising may overlap.
|
||||
//! Library calls overlap: the host documents the library as safe to use
|
||||
//! from several threads ("The pipeline library is thread-safe to use, and
|
||||
//! will internally synchronize as necessary", `CreatePipelineLibrary`,
|
||||
//! Thread Safety), with one exception kept here: two loads of the same
|
||||
//! pipeline are made one after the other ([`same_name`]). Under one lock of
|
||||
//! ours for every call, the eight workers made pipelines one at a time:
|
||||
//! 87 to 96 of 110 looks at each worker found it waiting for that lock
|
||||
//! (run 49), and an earlier run's 2,300 pipelines, all in the library, were
|
||||
//! still being loaded 46 s into the opening cutscene.
|
||||
//! `VICTORY_LIBRARY_LOCK=1`: one call at a time, as before.
|
||||
//!
|
||||
//! The library's file is mapped, not read into memory ([`Blob`]): the host
|
||||
//! keeps pointing into the bytes it was made from for as long as it lives,
|
||||
//! and read into a buffer they were 1,352 MB of the process's own memory
|
||||
//! for the whole run (run 60), all of it in physical memory. Mapped, the
|
||||
//! pages are the file's: only those the host reads are in memory, and the
|
||||
//! system can drop them without writing them anywhere. A save writes the
|
||||
//! new library through a mapping of the new file in the same way (a buffer
|
||||
//! of the library's size was made, filled and written out at each save).
|
||||
//! `VICTORY_LIBRARY_MAP=0`: read and written through buffers, as before.
|
||||
//!
|
||||
//! The mapped file's handle stays open for as long as the mapping lives
|
||||
//! ([`holds`]). A save renames the new library over the file this run has
|
||||
//! mapped, and with the handle closed Windows then gives up the old file's
|
||||
//! contents: every page of the mapping that is not in memory at that
|
||||
//! moment, or leaves memory later (the trim below, or Windows taking pages
|
||||
//! back), reads as zeros from then on. The host's library reads such pages
|
||||
//! as stored pipelines; the driver, handed a pipeline of zeros, removes the
|
||||
//! device with DXGI_ERROR_DRIVER_INTERNAL_ERROR (runs 72, 73 and 82, each
|
||||
//! within 5 ms of the first library call after a save and a trim; and the
|
||||
//! library run 77 saved from such pages was refused by run 78). Measured
|
||||
//! with a 64 MB file written past the system's cache, mapped and replaced:
|
||||
//! 16,352 of 16,384 pages read zeros with the handle closed, none with it
|
||||
//! open (the test below). `VICTORY_LIBRARY_HANDLE=0`: closed, as before.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, OnceLock};
|
||||
use std::sync::{Mutex, MutexGuard, OnceLock, RwLock};
|
||||
|
||||
use windows::Win32::Graphics::Direct3D12::*;
|
||||
use windows::core::{HSTRING, Interface, PCWSTR};
|
||||
@@ -35,64 +67,430 @@ pub fn use_pipeline_cache(dir: PathBuf) {
|
||||
pub(crate) static MADE: AtomicU64 = AtomicU64::new(0);
|
||||
pub(crate) static LOADED: AtomicU64 = AtomicU64::new(0);
|
||||
pub(crate) static EARLY: AtomicU64 = AtomicU64::new(0);
|
||||
/// For the memory lines: the bytes of the library's file, kept in memory
|
||||
/// while the library lives, and the bytes the last save wrote (a buffer of
|
||||
/// that size is made, filled and written every time pipelines were added,
|
||||
/// at most every 20 s).
|
||||
pub(crate) static BLOB: AtomicU64 = AtomicU64::new(0);
|
||||
pub(crate) static SAVED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// Whether the library's file is mapped ([`Blob`]) and saved through a
|
||||
/// mapping. On by default; `VICTORY_LIBRARY_MAP=0` uses buffers, as before.
|
||||
fn mapped() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_MAP").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Whether the mapped library file's handle is kept open while it is
|
||||
/// mapped (see the module's notes: without it a save in the same run turns
|
||||
/// the mapping's pages into zeros as they leave memory). On by default;
|
||||
/// `VICTORY_LIBRARY_HANDLE=0` closes it after mapping, as before.
|
||||
fn holds() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_HANDLE").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// A whole file mapped into memory: read-only (the library's file) or
|
||||
/// writable (the file a save fills). Unmapped when dropped.
|
||||
struct Mapped {
|
||||
at: windows_sys::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS,
|
||||
len: usize,
|
||||
/// The file, for a mapping made by [`Mapped::open`] ([`holds`]): open
|
||||
/// until after the view is unmapped, so that the file a rename took
|
||||
/// the name from keeps its contents for the view.
|
||||
_file: Option<std::fs::File>,
|
||||
}
|
||||
|
||||
impl Mapped {
|
||||
/// Maps `file` (`len` bytes, not zero) for reading, or for reading and
|
||||
/// writing.
|
||||
fn map(file: &std::fs::File, len: usize, write: bool) -> Option<Mapped> {
|
||||
use std::os::windows::io::AsRawHandle;
|
||||
use windows_sys::Win32::Foundation::CloseHandle;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE,
|
||||
};
|
||||
if len == 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: a file we hold open; the view keeps the file's pages
|
||||
// after the mapping object and the file are closed.
|
||||
let at = unsafe {
|
||||
let mapping = CreateFileMappingW(
|
||||
file.as_raw_handle(),
|
||||
std::ptr::null(),
|
||||
if write { PAGE_READWRITE } else { PAGE_READONLY },
|
||||
0,
|
||||
0,
|
||||
std::ptr::null(),
|
||||
);
|
||||
if mapping.is_null() {
|
||||
return None;
|
||||
}
|
||||
let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0);
|
||||
CloseHandle(mapping);
|
||||
at
|
||||
};
|
||||
(!at.Value.is_null()).then_some(Mapped { at, len, _file: None })
|
||||
}
|
||||
|
||||
/// The file at `path`, mapped for reading; `None` if it is not there,
|
||||
/// is empty or cannot be mapped.
|
||||
fn open(path: &std::path::Path) -> Option<Mapped> {
|
||||
Mapped::open_holding(path, holds())
|
||||
}
|
||||
|
||||
/// As [`Mapped::open`]; `hold` says whether the file stays open with
|
||||
/// the mapping.
|
||||
fn open_holding(path: &std::path::Path, hold: bool) -> Option<Mapped> {
|
||||
// Opened as the standard library opens a file to read: others may
|
||||
// read, write, rename and delete it meanwhile, so a save still
|
||||
// renames the new library over this one.
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let len = usize::try_from(file.metadata().ok()?.len()).ok()?;
|
||||
let mut mapped = Mapped::map(&file, len, false)?;
|
||||
if hold {
|
||||
mapped._file = Some(file);
|
||||
}
|
||||
Some(mapped)
|
||||
}
|
||||
|
||||
/// A new file of `len` bytes at `path` (replacing what is there),
|
||||
/// mapped for writing.
|
||||
fn create(path: &std::path::Path, len: usize) -> Option<Mapped> {
|
||||
let file = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(path)
|
||||
.ok()?;
|
||||
file.set_len(len as u64).ok()?;
|
||||
Mapped::map(&file, len, true)
|
||||
}
|
||||
|
||||
fn bytes(&self) -> &[u8] {
|
||||
// SAFETY: the view holds `len` readable bytes until dropped.
|
||||
unsafe { std::slice::from_raw_parts(self.at.Value.cast(), self.len) }
|
||||
}
|
||||
|
||||
/// Only for a view made by [`Mapped::create`].
|
||||
fn bytes_mut(&mut self) -> &mut [u8] {
|
||||
// SAFETY: a writable view of `len` bytes, ours alone.
|
||||
unsafe { std::slice::from_raw_parts_mut(self.at.Value.cast(), self.len) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Mapped {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: our view.
|
||||
unsafe { windows_sys::Win32::System::Memory::UnmapViewOfFile(self.at) };
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes a library is made from: the host reads them for as long as
|
||||
/// the library lives, so they are kept beside it.
|
||||
enum Blob {
|
||||
/// No file (an empty library).
|
||||
None,
|
||||
/// The file read into memory (`VICTORY_LIBRARY_MAP=0`, tests, or a file
|
||||
/// that could not be mapped).
|
||||
Held(Vec<u8>),
|
||||
/// The file itself, mapped.
|
||||
Mapped(Mapped),
|
||||
}
|
||||
|
||||
impl Blob {
|
||||
/// The library file in `dir`: a library a save left beside it
|
||||
/// ([`NEXT_FILE`]) takes its place first.
|
||||
fn of(dir: &std::path::Path) -> Blob {
|
||||
let path = dir.join(LIBRARY_FILE);
|
||||
let next = dir.join(NEXT_FILE);
|
||||
if next.exists() && std::fs::rename(&next, &path).is_err() {
|
||||
tracing::warn!("the host pipeline library saved last could not take the old one's place");
|
||||
}
|
||||
if mapped()
|
||||
&& let Some(file) = Mapped::open(&path)
|
||||
{
|
||||
return Blob::Mapped(file);
|
||||
}
|
||||
match std::fs::read(&path) {
|
||||
Ok(bytes) if !bytes.is_empty() => Blob::Held(bytes),
|
||||
_ => Blob::None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(&self) -> &[u8] {
|
||||
match self {
|
||||
Blob::None => &[],
|
||||
Blob::Held(bytes) => bytes,
|
||||
Blob::Mapped(file) => file.bytes(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mapped library file's view (address, bytes; 0: not mapped), when a
|
||||
/// pipeline was last loaded from the library (`crate::host::now_ms`), and
|
||||
/// whether the view's pages were let go since ([`trim`]).
|
||||
static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
|
||||
static LOADED_AT: AtomicU64 = AtomicU64::new(0);
|
||||
static TRIMMED: AtomicBool = AtomicBool::new(false);
|
||||
/// The bytes of the view let go so far, for the memory line.
|
||||
pub(crate) static TRIMMED_BYTES: AtomicU64 = AtomicU64::new(0);
|
||||
/// When the view's pages were last let go (`crate::host::now_ms`), and how
|
||||
/// often and when a save of this run last renamed a new library over the
|
||||
/// mapped file: for [`removal_note`].
|
||||
static TRIMMED_AT: AtomicU64 = AtomicU64::new(0);
|
||||
static REPLACED: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
|
||||
|
||||
/// The library calls running now: thread, what (load, make, store,
|
||||
/// serialise), the pipeline, and since when (`crate::host::now_us`).
|
||||
static CALLS: Mutex<Vec<(u32, &'static str, String, u64)>> = Mutex::new(Vec::new());
|
||||
|
||||
thread_local! {
|
||||
/// The pipeline this thread is making (its shaders), for [`CALLS`].
|
||||
static LABEL: std::cell::RefCell<String> = const { std::cell::RefCell::new(String::new()) };
|
||||
}
|
||||
|
||||
/// Names the pipeline this thread makes next.
|
||||
pub(crate) fn label(text: String) {
|
||||
LABEL.with(|l| *l.borrow_mut() = text);
|
||||
}
|
||||
|
||||
/// A library call of this thread, listed in [`CALLS`] until dropped.
|
||||
struct Call(u32, u64);
|
||||
|
||||
fn call(what: &'static str, name: &str) -> Call {
|
||||
let (thread, since) = (crate::host::thread_id(), crate::host::now_us());
|
||||
let label = LABEL.with(|l| l.borrow().clone());
|
||||
CALLS
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.push((thread, what, format!("{name} {label}"), since));
|
||||
Call(thread, since)
|
||||
}
|
||||
|
||||
impl Drop for Call {
|
||||
fn drop(&mut self) {
|
||||
CALLS
|
||||
.lock()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
.retain(|c| (c.0, c.3) != (self.0, self.1));
|
||||
}
|
||||
}
|
||||
|
||||
/// For the report when the host device is removed: the library calls
|
||||
/// running at that moment, whether this run replaced the mapped file and
|
||||
/// let its pages go, and how many pages of the mapping read as zeros now.
|
||||
/// A library holds no page of zeros (the 259 MB one of run 83 has no run of
|
||||
/// 2,048 zero bytes): each such page is one whose contents were lost (see
|
||||
/// the module's notes), and a pipeline stored there is what the driver was
|
||||
/// handed.
|
||||
pub(crate) fn removal_note() -> String {
|
||||
use std::fmt::Write;
|
||||
let now = crate::host::now_us();
|
||||
let mut text = String::from("pipeline library: ");
|
||||
{
|
||||
let calls = CALLS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if calls.is_empty() {
|
||||
text.push_str("no call running");
|
||||
}
|
||||
for (i, (thread, what, name, since)) in calls.iter().enumerate() {
|
||||
let _ = write!(
|
||||
text,
|
||||
"{}{what} of {name} running for {:.1} ms on thread {thread}",
|
||||
if i == 0 { "" } else { ", " },
|
||||
now.saturating_sub(*since) as f64 / 1000.0
|
||||
);
|
||||
}
|
||||
}
|
||||
let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed));
|
||||
if at == 0 {
|
||||
text.push_str("; its file is not mapped");
|
||||
return text;
|
||||
}
|
||||
let ago = |ms: u64| crate::host::now_ms().saturating_sub(ms) as f64 / 1000.0;
|
||||
let _ = write!(
|
||||
text,
|
||||
"; its file is mapped ({len} bytes), the handle {}",
|
||||
if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" }
|
||||
);
|
||||
match REPLACED[0].load(Ordering::Relaxed) {
|
||||
0 => text.push_str("; this run has not replaced the file"),
|
||||
n => {
|
||||
let _ = write!(
|
||||
text,
|
||||
"; this run replaced the file under the mapping {n} times, last {:.1} s ago",
|
||||
ago(REPLACED[1].load(Ordering::Relaxed))
|
||||
);
|
||||
}
|
||||
}
|
||||
if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 {
|
||||
let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed)));
|
||||
}
|
||||
// Within two seconds: pages not in memory come from the disk.
|
||||
let started = std::time::Instant::now();
|
||||
// SAFETY: the view lives as long as the library, which is never dropped.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(at as *const u8, len) };
|
||||
let (mut zero, mut looked, mut first) = (0u64, 0u64, None);
|
||||
for (n, page) in bytes.chunks(4096).enumerate() {
|
||||
if n % 4096 == 0 && started.elapsed() > std::time::Duration::from_secs(2) {
|
||||
break;
|
||||
}
|
||||
looked += 1;
|
||||
if page.iter().all(|&b| b == 0) {
|
||||
zero += 1;
|
||||
if first.is_none() {
|
||||
first = Some(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now");
|
||||
if let Some(first) = first {
|
||||
let _ = write!(text, " (the first is page {first}): the library's contents were lost there");
|
||||
}
|
||||
text
|
||||
}
|
||||
|
||||
/// Lets the mapped library file's pages go from the process's memory once
|
||||
/// no pipeline has been loaded for ten seconds. The host reads nearly the
|
||||
/// whole file while the early pipelines load (run 65: all 1,490 MB of it
|
||||
/// were in the process's memory a minute in, and 1,300 MB still at the
|
||||
/// end, on a PC with 2 GB free); after that it reads the file again only
|
||||
/// when a new pipeline loads. Pages let go stay in Windows' file cache
|
||||
/// while nothing else wants the memory, and come back on the next read.
|
||||
/// Called once a second by the sweep; does its work on a thread of its own
|
||||
/// (hundreds of thousands of pages), once after each burst of loads.
|
||||
/// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them.
|
||||
pub(crate) fn trim() {
|
||||
const QUIET_MS: u64 = 10_000;
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed));
|
||||
if at == 0
|
||||
|| TRIMMED.load(Ordering::Relaxed)
|
||||
|| crate::host::now_ms() < LOADED_AT.load(Ordering::Relaxed) + QUIET_MS
|
||||
|| !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0"))
|
||||
|| TRIMMED.swap(true, Ordering::Relaxed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let work = move || {
|
||||
// SAFETY: the view lives as long as the library, which is never
|
||||
// dropped. Unlocking pages that are not locked fails, as expected,
|
||||
// and takes them out of the working set: the documented way to let
|
||||
// pages of a mapped file go.
|
||||
unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) };
|
||||
TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed);
|
||||
TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
|
||||
crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)"));
|
||||
};
|
||||
if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() {
|
||||
TRIMMED.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
struct Library {
|
||||
library: ID3D12PipelineLibrary1,
|
||||
/// The blob the library was made from: it must outlive the library.
|
||||
_blob: Vec<u8>,
|
||||
_blob: Blob,
|
||||
/// Pipelines stored since the last save.
|
||||
added: u64,
|
||||
added: AtomicU64,
|
||||
/// Stores share it and a save takes it alone: the size the library
|
||||
/// asks for must still be its size when it is written out.
|
||||
saving: RwLock<()>,
|
||||
}
|
||||
|
||||
// SAFETY: D3D12 objects are free-threaded; every call is made under the
|
||||
// mutex that holds the library.
|
||||
// SAFETY: D3D12 objects are free-threaded, and the library synchronises
|
||||
// its own calls (see the module's notes); what it does not, two loads of
|
||||
// one name, is serialised by `same_name`.
|
||||
unsafe impl Send for Library {}
|
||||
// SAFETY: as above; the other fields are an atomic and a lock.
|
||||
unsafe impl Sync for Library {}
|
||||
|
||||
/// Held by a load of the pipeline named `name`: loads of the same name
|
||||
/// wait for each other (the host's one exception to the library's thread
|
||||
/// safety: such a load may change that pipeline's entry). Names share 64
|
||||
/// locks, so two different names seldom wait.
|
||||
fn same_name(name: &str) -> MutexGuard<'static, ()> {
|
||||
static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64];
|
||||
let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b)));
|
||||
LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
/// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before.
|
||||
fn one_call() -> Option<MutexGuard<'static, ()>> {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
static CALLING: Mutex<()> = Mutex::new(());
|
||||
ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_LOCK").is_some_and(|v| v == "1"))
|
||||
.then(|| CALLING.lock().unwrap_or_else(|e| e.into_inner()))
|
||||
}
|
||||
|
||||
const LIBRARY_FILE: &str = "host-pipelines.bin";
|
||||
/// A saved library that could not replace [`LIBRARY_FILE`] while this run
|
||||
/// had it mapped (a system that refuses to replace a mapped file): the next
|
||||
/// start renames it over the library first ([`Blob::of`]).
|
||||
const NEXT_FILE: &str = "host-pipelines.next";
|
||||
const EARLY_FILE: &str = "early-pipelines.txt";
|
||||
/// Title pipelines listed for an early start, at most.
|
||||
const EARLY_MAX: usize = 8192;
|
||||
|
||||
fn library() -> Option<&'static Mutex<Library>> {
|
||||
static LIBRARY: OnceLock<Option<Mutex<Library>>> = OnceLock::new();
|
||||
fn library() -> Option<&'static Library> {
|
||||
static LIBRARY: OnceLock<Option<Library>> = OnceLock::new();
|
||||
LIBRARY
|
||||
.get_or_init(|| {
|
||||
let device = crate::host::host()?.device.cast::<ID3D12Device1>().ok()?;
|
||||
let blob = DIR
|
||||
.get()
|
||||
.and_then(|d| std::fs::read(d.join(LIBRARY_FILE)).ok())
|
||||
.unwrap_or_default();
|
||||
let blob = DIR.get().map_or(Blob::None, |d| Blob::of(d));
|
||||
let library = open(&device, blob);
|
||||
if library.is_none() {
|
||||
tracing::warn!("no host pipeline library: pipelines are not kept");
|
||||
}
|
||||
library.map(Mutex::new)
|
||||
library
|
||||
})
|
||||
.as_ref()
|
||||
}
|
||||
|
||||
/// The library in `blob`, or an empty one if the host rejects the blob (an
|
||||
/// adapter or driver change, damage).
|
||||
fn open(device: &ID3D12Device1, blob: Vec<u8>) -> Option<Library> {
|
||||
fn open(device: &ID3D12Device1, blob: Blob) -> Option<Library> {
|
||||
let make = |bytes: &[u8]| -> windows::core::Result<ID3D12PipelineLibrary1> {
|
||||
// SAFETY: the bytes outlive the library (kept beside it).
|
||||
unsafe {
|
||||
device.CreatePipelineLibrary::<ID3D12PipelineLibrary>(bytes)?.cast()
|
||||
}
|
||||
};
|
||||
if !blob.is_empty() {
|
||||
match make(&blob) {
|
||||
if !blob.bytes().is_empty() {
|
||||
match make(blob.bytes()) {
|
||||
Ok(library) => {
|
||||
tracing::info!(bytes = blob.len(), "host pipeline library loaded");
|
||||
return Some(Library { library, _blob: blob, added: 0 });
|
||||
let bytes = blob.bytes().len();
|
||||
BLOB.store(bytes as u64, Ordering::Relaxed);
|
||||
tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded");
|
||||
if let Blob::Mapped(file) = &blob {
|
||||
VIEW[1].store(file.len, Ordering::Relaxed);
|
||||
VIEW[0].store(file.at.Value as usize, Ordering::Relaxed);
|
||||
LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
|
||||
}
|
||||
return Some(Library {
|
||||
library,
|
||||
_blob: blob,
|
||||
added: AtomicU64::new(0),
|
||||
saving: RwLock::new(()),
|
||||
});
|
||||
}
|
||||
Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"),
|
||||
}
|
||||
} else {
|
||||
tracing::info!("no host pipeline library yet; starting an empty one");
|
||||
}
|
||||
// The rejected bytes are let go (a mapped file is unmapped) before the
|
||||
// empty library is made: nothing reads them any more.
|
||||
drop(blob);
|
||||
let library = make(&[]).ok()?;
|
||||
Some(Library { library, _blob: Vec::new(), added: 0 })
|
||||
Some(Library {
|
||||
library,
|
||||
_blob: Blob::None,
|
||||
added: AtomicU64::new(0),
|
||||
saving: RwLock::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
/// A pipeline's name in the library: the hash of what its host
|
||||
@@ -118,18 +516,47 @@ pub(crate) fn pipeline(
|
||||
MADE.fetch_add(1, Ordering::Relaxed);
|
||||
return create();
|
||||
};
|
||||
if let Ok(pso) = load(&library.lock().unwrap_or_else(|e| e.into_inner()).library, PCWSTR(wide.as_ptr())) {
|
||||
LOADED.fetch_add(1, Ordering::Relaxed);
|
||||
return Ok(pso);
|
||||
}
|
||||
// Compiled outside the lock: compiles take up to seconds.
|
||||
let pso = create()?;
|
||||
let began = std::time::Instant::now();
|
||||
let loaded = {
|
||||
let _all = one_call();
|
||||
let _one = same_name(name);
|
||||
let _call = call("load", name);
|
||||
load(&library.library, PCWSTR(wide.as_ptr()))
|
||||
};
|
||||
// The load read the library's file (see `trim`).
|
||||
LOADED_AT.store(crate::host::now_ms(), Ordering::Relaxed);
|
||||
TRIMMED.store(false, Ordering::Relaxed);
|
||||
let refused = match loaded {
|
||||
Ok(pso) => {
|
||||
LOADED.fetch_add(1, Ordering::Relaxed);
|
||||
crate::host::trail(|| {
|
||||
let label = LABEL.with(|l| l.borrow().clone());
|
||||
format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3)
|
||||
});
|
||||
return Ok(pso);
|
||||
}
|
||||
Err(e) => e,
|
||||
};
|
||||
// Compiled outside any lock: compiles take up to seconds.
|
||||
let pso = {
|
||||
let _call = call("make", name);
|
||||
create()?
|
||||
};
|
||||
MADE.fetch_add(1, Ordering::Relaxed);
|
||||
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
|
||||
crate::host::trail(|| {
|
||||
let label = LABEL.with(|l| l.borrow().clone());
|
||||
format!(
|
||||
"pipeline library: made {label} in {:.1} ms (the library did not load it: {refused})",
|
||||
began.elapsed().as_secs_f64() * 1e3
|
||||
)
|
||||
});
|
||||
let _all = one_call();
|
||||
let _stores = library.saving.read().unwrap_or_else(|e| e.into_inner());
|
||||
let _call = call("store", name);
|
||||
// SAFETY: a live pipeline; a name already stored (a description that
|
||||
// differs) is refused, which leaves the library as it was.
|
||||
if unsafe { l.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
|
||||
l.added += 1;
|
||||
if unsafe { library.library.StorePipeline(PCWSTR(wide.as_ptr()), &pso) }.is_ok() {
|
||||
library.added.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok(pso)
|
||||
}
|
||||
@@ -147,34 +574,60 @@ pub(crate) fn save(now: bool) {
|
||||
}
|
||||
*last = Some(std::time::Instant::now());
|
||||
}
|
||||
let blob = {
|
||||
let mut l = library.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if l.added == 0 && !USED_CHANGED.swap(false, Ordering::Relaxed) {
|
||||
if let Err(e) = std::fs::create_dir_all(dir) {
|
||||
tracing::warn!(error = %e, "host pipeline library not saved");
|
||||
return;
|
||||
}
|
||||
let tmp = dir.join(LIBRARY_FILE).with_extension("tmp");
|
||||
// The bytes of the library written to `tmp`; 0 when no pipeline was
|
||||
// added: the library on disk is then what it was, and only the early
|
||||
// list is written (a title pipeline first drawn with wrote all 1,352 MB
|
||||
// of the library again: run 60's second save).
|
||||
let bytes = {
|
||||
let _all = one_call();
|
||||
// No store between asking the size and writing; loads go on.
|
||||
let _alone = library.saving.write().unwrap_or_else(|e| e.into_inner());
|
||||
let added = library.added.load(Ordering::Relaxed);
|
||||
if !USED_CHANGED.swap(false, Ordering::Relaxed) && added == 0 {
|
||||
return;
|
||||
}
|
||||
// SAFETY: a buffer of the size the library asks for.
|
||||
let bytes = unsafe {
|
||||
let mut bytes = vec![0u8; l.library.GetSerializedSize()];
|
||||
l.library.Serialize(&mut bytes).map(|()| bytes)
|
||||
};
|
||||
match bytes {
|
||||
Ok(bytes) => {
|
||||
l.added = 0;
|
||||
bytes
|
||||
}
|
||||
Err(e) => {
|
||||
if added == 0 {
|
||||
0
|
||||
} else {
|
||||
// SAFETY: a plain query.
|
||||
let size = unsafe { library.library.GetSerializedSize() };
|
||||
let _call = call("serialise", "the whole library");
|
||||
if let Err(e) = serialise(&library.library, &tmp, size) {
|
||||
tracing::warn!(error = %e, "host pipeline library not serialised");
|
||||
let _ = std::fs::remove_file(&tmp);
|
||||
return;
|
||||
}
|
||||
library.added.store(0, Ordering::Relaxed);
|
||||
SAVED.store(size as u64, Ordering::Relaxed);
|
||||
size
|
||||
}
|
||||
};
|
||||
let used: Vec<String> = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect();
|
||||
let written = std::fs::create_dir_all(dir)
|
||||
.and_then(|()| write_atomically(&dir.join(LIBRARY_FILE), &blob))
|
||||
let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) };
|
||||
if bytes > 0 && library_written.is_ok() {
|
||||
// In place unless the system refused and the new one waits beside it.
|
||||
let in_place = !dir.join(NEXT_FILE).exists();
|
||||
if in_place && VIEW[0].load(Ordering::Relaxed) != 0 {
|
||||
REPLACED[1].store(crate::host::now_ms(), Ordering::Relaxed);
|
||||
REPLACED[0].fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
crate::host::trail(|| {
|
||||
format!(
|
||||
"pipeline library: saved {bytes} bytes, {}",
|
||||
if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" }
|
||||
)
|
||||
});
|
||||
}
|
||||
let written = library_written
|
||||
.and_then(|()| write_atomically(&dir.join(EARLY_FILE), used.join("\n").as_bytes()));
|
||||
match written {
|
||||
Ok(()) => tracing::info!(
|
||||
bytes = blob.len(),
|
||||
bytes,
|
||||
early = used.len(),
|
||||
made = MADE.load(Ordering::Relaxed),
|
||||
loaded = LOADED.load(Ordering::Relaxed),
|
||||
@@ -185,6 +638,35 @@ pub(crate) fn save(now: bool) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the library's `size` serialised bytes to the file `tmp`: through
|
||||
/// a mapping of that file, so that the bytes are the file's pages and not
|
||||
/// 1.3 GB more of the process's own memory for the seconds a save takes;
|
||||
/// through a buffer where the file cannot be mapped (and with
|
||||
/// `VICTORY_LIBRARY_MAP=0`).
|
||||
fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> {
|
||||
let failed = |e: windows::core::Error| std::io::Error::other(e.to_string());
|
||||
if mapped()
|
||||
&& let Some(mut file) = Mapped::create(tmp, size)
|
||||
{
|
||||
// SAFETY: a buffer of the size the library asks for.
|
||||
return unsafe { library.Serialize(file.bytes_mut()) }.map_err(failed);
|
||||
}
|
||||
let mut bytes = vec![0u8; size];
|
||||
// SAFETY: a buffer of the size the library asks for.
|
||||
unsafe { library.Serialize(&mut bytes) }.map_err(failed)?;
|
||||
std::fs::write(tmp, &bytes)
|
||||
}
|
||||
|
||||
/// Renames the written library `tmp` over the library's file in `dir`. This
|
||||
/// run may have that file mapped: Windows 11 replaces a mapped file, and
|
||||
/// the mapping goes on reading the old one for as long as a handle on it
|
||||
/// is open ([`holds`]; with none, only the pages in memory at that moment
|
||||
/// stay: the rest read as zeros). Where a system refuses, the new library
|
||||
/// is left beside it as [`NEXT_FILE`] for the next start.
|
||||
fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> {
|
||||
std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE)))
|
||||
}
|
||||
|
||||
/// Writes `bytes` to a temporary file beside `path`, then renames it over
|
||||
/// `path`: a reader never sees a part.
|
||||
fn write_atomically(path: &std::path::Path, bytes: &[u8]) -> std::io::Result<()> {
|
||||
@@ -246,9 +728,111 @@ mod tests {
|
||||
let Some(device) = crate::host::host().and_then(|h| h.device.cast::<ID3D12Device1>().ok()) else {
|
||||
return; // no host GPU here
|
||||
};
|
||||
let library = open(&device, b"not a pipeline library".repeat(16)).expect("an empty library");
|
||||
let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library");
|
||||
// SAFETY: a plain query on a live library.
|
||||
assert!(unsafe { library.library.GetSerializedSize() } > 0);
|
||||
assert!(library._blob.is_empty());
|
||||
assert!(matches!(library._blob, Blob::None));
|
||||
}
|
||||
|
||||
/// A mapped file reads as the file's bytes, a file written through a
|
||||
/// mapping holds what was written, and the library's file can be
|
||||
/// replaced while it is mapped (or the new one waits as the next).
|
||||
#[test]
|
||||
fn the_library_file_is_mapped_and_replaced() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(LIBRARY_FILE);
|
||||
assert!(matches!(Blob::of(dir.path()), Blob::None), "no file yet");
|
||||
std::fs::write(&path, b"").unwrap();
|
||||
assert!(matches!(Blob::of(dir.path()), Blob::None), "an empty file");
|
||||
let old: Vec<u8> = (0..200_000u32).map(|i| i as u8).collect();
|
||||
std::fs::write(&path, &old).unwrap();
|
||||
let blob = Blob::of(dir.path());
|
||||
assert!(matches!(blob, Blob::Mapped(_)) || !mapped());
|
||||
assert_eq!(blob.bytes(), &old[..]);
|
||||
// A save while the old file is mapped.
|
||||
let tmp = path.with_extension("tmp");
|
||||
let new: Vec<u8> = (0..300_000u32).map(|i| (i * 7) as u8).collect();
|
||||
{
|
||||
let mut file = Mapped::create(&tmp, new.len()).expect("a new file, mapped");
|
||||
file.bytes_mut().copy_from_slice(&new);
|
||||
}
|
||||
assert_eq!(std::fs::read(&tmp).unwrap(), new);
|
||||
replace_library(dir.path(), &tmp).unwrap();
|
||||
assert!(!tmp.exists());
|
||||
// The mapping still reads the old library.
|
||||
assert_eq!(blob.bytes(), &old[..]);
|
||||
drop(blob);
|
||||
// The next start reads the new one, wherever the save left it.
|
||||
assert_eq!(Blob::of(dir.path()).bytes(), &new[..]);
|
||||
assert!(!dir.path().join(NEXT_FILE).exists());
|
||||
}
|
||||
|
||||
/// The bytes at `at` of the pattern the test below writes.
|
||||
fn pattern(at: usize, out: &mut [u8]) {
|
||||
for (i, word) in out.chunks_exact_mut(4).enumerate() {
|
||||
let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1);
|
||||
word.copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
/// A file of `len` bytes (whole MiB) of [`pattern`], written past the
|
||||
/// system's cache: none of its pages is in memory afterwards. False
|
||||
/// where the folder's file system does not take such writes.
|
||||
fn write_uncached(path: &std::path::Path, len: usize) -> bool {
|
||||
use std::io::Write;
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
// FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH
|
||||
const UNCACHED: u32 = 0x2000_0000 | 0x8000_0000;
|
||||
const CHUNK: usize = 1 << 20;
|
||||
let Ok(mut file) = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.custom_flags(UNCACHED)
|
||||
.open(path)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
// Such writes want a buffer on a sector boundary.
|
||||
let mut store = vec![0u8; CHUNK + 4096];
|
||||
let start = store.as_ptr().align_offset(4096);
|
||||
for at in (0..len).step_by(CHUNK) {
|
||||
let chunk = &mut store[start..start + CHUNK];
|
||||
pattern(at, chunk);
|
||||
if file.write_all(chunk).is_err() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The device loss of runs 72, 73 and 82: the library's file is
|
||||
/// replaced while it is mapped, and pages of the mapping that were not
|
||||
/// in memory then are read afterwards (in the runs: pages the trim let
|
||||
/// go and Windows gave to something else). With the file's handle kept
|
||||
/// open they still read as the old file. (With it closed, as before,
|
||||
/// all but the first few read as zeros on the PC this was found on.)
|
||||
#[test]
|
||||
fn a_replaced_library_file_still_reads_from_the_disk() {
|
||||
const LEN: usize = 8 << 20;
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(LIBRARY_FILE);
|
||||
if !write_uncached(&path, LEN) {
|
||||
return; // no uncached writes here: nothing to show
|
||||
}
|
||||
let mapped = Mapped::open_holding(&path, true).expect("the file, mapped");
|
||||
// A save: the new library, renamed over the mapped one.
|
||||
let tmp = path.with_extension("tmp");
|
||||
{
|
||||
let mut file = Mapped::create(&tmp, LEN).expect("a new file, mapped");
|
||||
file.bytes_mut().fill(0xEE);
|
||||
}
|
||||
replace_library(dir.path(), &tmp).unwrap();
|
||||
// Every page of the old mapping, read for the first time now.
|
||||
let mut expected = vec![0u8; 4096];
|
||||
for (page, bytes) in mapped.bytes().chunks(4096).enumerate() {
|
||||
pattern(page * 4096, &mut expected);
|
||||
assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,8 @@
|
||||
//! guess; a pass the title runs only once and whose pipeline takes longer
|
||||
//! is lost.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -27,7 +28,7 @@ use super::host::{GraphicsState, HostPipeline};
|
||||
pub(crate) struct Pending {
|
||||
shaders: Vec<Arc<Shader>>,
|
||||
pub(crate) graphics: Option<Box<GraphicsState>>,
|
||||
queued: AtomicBool,
|
||||
queue_state: AtomicU8,
|
||||
made: OnceLock<Option<HostPipeline>>,
|
||||
/// What identifies it across runs (shader containers and state), and
|
||||
/// whether a draw has used it yet.
|
||||
@@ -52,7 +53,7 @@ impl Pending {
|
||||
Pending {
|
||||
shaders,
|
||||
graphics,
|
||||
queued: AtomicBool::new(false),
|
||||
queue_state: AtomicU8::new(NOT_QUEUED),
|
||||
made: OnceLock::new(),
|
||||
key: key.finalize().to_hex()[..32].to_owned(),
|
||||
used: AtomicBool::new(false),
|
||||
@@ -109,22 +110,25 @@ pub(crate) fn waiting() -> u64 {
|
||||
/// queues it on first use.
|
||||
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
|
||||
if p.made.get().is_none() {
|
||||
start(p);
|
||||
start(p, REQUESTED);
|
||||
wait(p, crate::frame::current());
|
||||
}
|
||||
let made = p.made.get()?.as_ref();
|
||||
if made.is_some() && !p.used.swap(true, Ordering::Relaxed) {
|
||||
// Also one that could not be made (a shader that does not translate):
|
||||
// the next run then finds that out while loading, like the others,
|
||||
// instead of in the world's frames, where each first use of such a
|
||||
// pipeline waits on the frame's budget for nothing.
|
||||
if !p.used.swap(true, Ordering::Relaxed) {
|
||||
super::library::note_used(&p.key);
|
||||
}
|
||||
made
|
||||
}
|
||||
|
||||
/// Queues `p` for the workers, once.
|
||||
fn start(p: &Arc<Pending>) {
|
||||
if !p.queued.swap(true, Ordering::Relaxed) {
|
||||
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
queue(p.clone());
|
||||
}
|
||||
/// Makes `p` on this thread if it is not made yet (waiting for a worker
|
||||
/// that is making it); whether it has a host pipeline.
|
||||
pub(crate) fn now(p: &Arc<Pending>) -> bool {
|
||||
p.make();
|
||||
p.made.get().is_some_and(|made| made.is_some())
|
||||
}
|
||||
|
||||
/// At the title's creation of a pipeline: starts it at once if an earlier
|
||||
@@ -132,18 +136,43 @@ fn start(p: &Arc<Pending>) {
|
||||
pub(crate) fn early(p: &Arc<Pending>) {
|
||||
if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
|
||||
super::library::EARLY.fetch_add(1, Ordering::Relaxed);
|
||||
start(p);
|
||||
start(p, EARLY);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the frame's budget is one for all threads together: a thread
|
||||
/// that waits takes what is left of it and gives back what it did not
|
||||
/// use. Counted only when a wait had ended, the budget was one per thread:
|
||||
/// each of the title's five recording threads began its first wait of a
|
||||
/// frame with nothing counted yet and waited the whole half second, 2.5 s
|
||||
/// of waiting in every frame in which pipelines were being made (runs
|
||||
/// 34-49: "2504 ms waiting for pipelines" in each such frame).
|
||||
/// On by default; `VICTORY_PIPELINE_WAIT_SHARED=0` counts as before.
|
||||
fn shared_budget() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_PIPELINE_WAIT_SHARED").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Waits for `p` while frame `frame` has budget left.
|
||||
fn wait(p: &Pending, frame: u64) {
|
||||
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
|
||||
static WAITED_US: AtomicU64 = AtomicU64::new(0);
|
||||
if FRAME.swap(frame, Ordering::Relaxed) != frame {
|
||||
WAITED_US.store(0, Ordering::Relaxed);
|
||||
// The frame the budget belongs to, and what was waited of it (or is
|
||||
// taken by a thread waiting now).
|
||||
static SPENT: Mutex<(u64, Duration)> = Mutex::new((u64::MAX, Duration::ZERO));
|
||||
let shared = shared_budget();
|
||||
let left = {
|
||||
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if spent.0 != frame {
|
||||
*spent = (frame, Duration::ZERO);
|
||||
}
|
||||
let left = BUDGET.saturating_sub(spent.1);
|
||||
if shared {
|
||||
spent.1 += left;
|
||||
}
|
||||
left
|
||||
};
|
||||
if left.is_zero() {
|
||||
return;
|
||||
}
|
||||
let left = BUDGET.saturating_sub(Duration::from_micros(WAITED_US.load(Ordering::Relaxed)));
|
||||
let started = Instant::now();
|
||||
let (lock, done) = &DONE;
|
||||
let mut held = lock.lock().unwrap_or_else(|e| e.into_inner());
|
||||
@@ -154,22 +183,115 @@ fn wait(p: &Pending, frame: u64) {
|
||||
}
|
||||
held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0;
|
||||
}
|
||||
WAITED_US.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
|
||||
drop(held);
|
||||
let waited = started.elapsed().min(left);
|
||||
{
|
||||
let mut spent = SPENT.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// A frame that began meanwhile has its own budget.
|
||||
if spent.0 == frame {
|
||||
if shared {
|
||||
spent.1 = spent.1.saturating_sub(left - waited);
|
||||
} else {
|
||||
spent.1 += waited;
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "diagnostics")]
|
||||
crate::copystat::add(
|
||||
crate::copystat::C::PipelineWaitUs,
|
||||
started.elapsed().as_micros() as u64,
|
||||
);
|
||||
}
|
||||
|
||||
/// Hands `p` to the workers (half the logical processors, 2 to 8), started
|
||||
/// on first use.
|
||||
fn queue(p: Arc<Pending>) {
|
||||
static SENDER: OnceLock<std::sync::mpsc::Sender<Arc<Pending>>> = OnceLock::new();
|
||||
let sender = SENDER.get_or_init(|| {
|
||||
let (sender, receiver) = std::sync::mpsc::channel::<Arc<Pending>>();
|
||||
let receiver = Arc::new(Mutex::new(receiver));
|
||||
const NOT_QUEUED: u8 = 0;
|
||||
const EARLY: u8 = 1;
|
||||
const REQUESTED: u8 = 2;
|
||||
const MAKING: u8 = 3;
|
||||
|
||||
struct Queue {
|
||||
early: VecDeque<Arc<Pending>>,
|
||||
requested: VecDeque<Arc<Pending>>,
|
||||
}
|
||||
|
||||
impl Queue {
|
||||
const fn new() -> Self {
|
||||
Self {
|
||||
early: VecDeque::new(),
|
||||
requested: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues an unrequested pipeline or promotes one queued at creation.
|
||||
/// Returns whether it is new to the queue, or `None` if nothing changed.
|
||||
fn push(&mut self, p: &Arc<Pending>, priority: u8) -> Option<bool> {
|
||||
let prev = p.queue_state.load(Ordering::Relaxed);
|
||||
if prev >= priority {
|
||||
return None;
|
||||
}
|
||||
p.queue_state.store(priority, Ordering::Relaxed);
|
||||
if priority == REQUESTED {
|
||||
self.requested.push_back(p.clone());
|
||||
} else {
|
||||
self.early.push_back(p.clone());
|
||||
}
|
||||
Some(prev == NOT_QUEUED)
|
||||
}
|
||||
|
||||
fn pop(&mut self) -> Option<Arc<Pending>> {
|
||||
let p = self.requested.pop_front().or_else(|| {
|
||||
// An early entry can have been promoted and claimed already.
|
||||
std::iter::from_fn(|| self.early.pop_front())
|
||||
.find(|p| p.queue_state.load(Ordering::Relaxed) == EARLY)
|
||||
})?;
|
||||
p.queue_state.store(MAKING, Ordering::Relaxed);
|
||||
Some(p)
|
||||
}
|
||||
}
|
||||
|
||||
static QUEUE: Mutex<Queue> = Mutex::new(Queue::new());
|
||||
static AVAILABLE: Condvar = Condvar::new();
|
||||
|
||||
/// Start or promote work for a draw without waiting behind the entire early
|
||||
/// list. Queue changes and worker claims happen under the same lock.
|
||||
fn start(p: &Arc<Pending>, priority: u8) {
|
||||
if p.queue_state.load(Ordering::Relaxed) >= priority {
|
||||
return;
|
||||
}
|
||||
if !workers() {
|
||||
if p.queue_state.swap(MAKING, Ordering::Relaxed) == NOT_QUEUED {
|
||||
p.make();
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(new) = queue.push(p, priority) {
|
||||
if new {
|
||||
PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
}
|
||||
AVAILABLE.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
fn next() -> Arc<Pending> {
|
||||
let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
loop {
|
||||
if let Some(p) = queue.pop() {
|
||||
return p;
|
||||
}
|
||||
queue = AVAILABLE.wait(queue).unwrap_or_else(|e| e.into_inner());
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the workers (half the logical processors, 2 to 8) on first use.
|
||||
fn workers() -> bool {
|
||||
static RUNNING: OnceLock<bool> = OnceLock::new();
|
||||
*RUNNING.get_or_init(|| {
|
||||
let mut running = false;
|
||||
let workers = std::thread::available_parallelism().map_or(2, |n| (n.get() / 2).clamp(2, 8));
|
||||
for i in 0..workers {
|
||||
let receiver = receiver.clone();
|
||||
let spawned = std::thread::Builder::new()
|
||||
.name(format!("victory-pipelines-{i}"))
|
||||
.spawn(move || {
|
||||
.spawn(|| {
|
||||
// Below the title's own threads (loading, recording).
|
||||
// SAFETY: a plain call on our own thread.
|
||||
unsafe {
|
||||
@@ -177,9 +299,7 @@ fn queue(p: Arc<Pending>) {
|
||||
let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);
|
||||
}
|
||||
loop {
|
||||
let next = receiver.lock().unwrap_or_else(|e| e.into_inner()).recv();
|
||||
let Ok(p) = next else { return };
|
||||
p.make();
|
||||
next().make();
|
||||
if WAITING.fetch_sub(1, Ordering::Relaxed) == 1 {
|
||||
drained();
|
||||
} else {
|
||||
@@ -189,15 +309,12 @@ fn queue(p: Arc<Pending>) {
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
tracing::warn!(error = %e, "no pipeline worker");
|
||||
} else {
|
||||
running = true;
|
||||
}
|
||||
}
|
||||
sender
|
||||
});
|
||||
if let Err(e) = sender.send(p) {
|
||||
// No worker: made here instead.
|
||||
e.0.make();
|
||||
WAITING.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
running
|
||||
})
|
||||
}
|
||||
|
||||
/// The most pipelines waiting at once since the workers last ran out.
|
||||
@@ -228,11 +345,31 @@ mod tests {
|
||||
fn first_use_is_made_by_a_worker() {
|
||||
let p = Arc::new(Pending::new(Vec::new(), None));
|
||||
assert!(ready(&p).is_none());
|
||||
assert!(p.queued.load(Ordering::Relaxed));
|
||||
assert_ne!(p.queue_state.load(Ordering::Relaxed), NOT_QUEUED);
|
||||
let started = Instant::now();
|
||||
while p.made.get().is_none() && started.elapsed() < Duration::from_secs(10) {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(matches!(p.made.get(), Some(None)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn draws_promote_early_pipelines_without_claiming_them_twice() {
|
||||
let earlier = Arc::new(Pending::new(Vec::new(), None));
|
||||
let promoted = Arc::new(Pending::new(Vec::new(), None));
|
||||
let requested = Arc::new(Pending::new(Vec::new(), None));
|
||||
let mut queue = Queue::new();
|
||||
|
||||
assert_eq!(queue.push(&earlier, EARLY), Some(true));
|
||||
assert_eq!(queue.push(&promoted, EARLY), Some(true));
|
||||
assert_eq!(queue.push(&requested, REQUESTED), Some(true));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), Some(false));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &requested));
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &promoted));
|
||||
assert_eq!(queue.push(&promoted, REQUESTED), None);
|
||||
assert!(Arc::ptr_eq(&queue.pop().unwrap(), &earlier));
|
||||
assert!(queue.pop().is_none());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user