//! The host GPU: one D3D12 device and direct queue (decision 0007), and a //! window to present on. //! //! shortcut: every submission is waited for, so CPU and GPU never overlap; //! overlap them with per-submission fences once more than clears run. use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Mutex, OnceLock}; use windows::Win32::Foundation::{ HANDLE, HWND, LPARAM, LRESULT, RECT, WAIT_FAILED, WAIT_OBJECT_0, WPARAM, }; 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::LibraryLoader::GetModuleHandleW; use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject}; use windows::Win32::UI::WindowsAndMessaging::*; use windows::core::{Interface, PCWSTR, w}; /// Resource states without the console's own bits (compression hints from /// bit 25 up), which the host rejects. pub(crate) fn pc_state(state: u32) -> u32 { state & 0x01ff_ffff } /// A console state as a host texture state: PC bits only, and none of the /// buffer-only ones the console allows on textures (vertex, constant and /// index buffer, stream out, indirect arguments, as in "generic read"). pub(crate) fn texture_state(state: u32) -> u32 { const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200; pc_state(state) & !BUFFER_ONLY } /// Render target views live only until their command is recorded, so a /// ring of host descriptors is enough. const RTV_RING: u32 = 1024; pub(crate) struct Host { pub(crate) device: ID3D12Device, queue: ID3D12CommandQueue, fence: ID3D12Fence, /// The last value signalled on `fence`, behind the submission lock. submitted: Mutex, event: HANDLE, rtvs: ID3D12DescriptorHeap, rtv_size: u32, /// A ring of depth views, used as `rtvs`. dsvs: ID3D12DescriptorHeap, dsv_size: u32, next_dsv: AtomicU32, /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug /// layer's messages. messages: Option, next_rtv: AtomicU32, presenter: Mutex>, } // SAFETY: D3D12 devices, queues, fences and descriptor heaps are // free-threaded; the event handle is only waited on under `submitted`. unsafe impl Send for Host {} // SAFETY: as above. unsafe impl Sync for Host {} /// Time spent in submissions since the last frame-rate line, in /// microseconds: preparing them on the CPU (title memory copies, texture /// detiling), then waiting for the GPU. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; /// After submissions: shader-written ranges compared and copied back into /// title memory (microseconds, bytes that differed), since the last /// frame-rate line. pub(crate) static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)]; /// Numbers the submissions: which one declared a range a host copy's /// shaders may write (an asynchronous write-back must not take a later /// submission's range for an earlier one's). static NEXT_SUBMISSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); /// Of the preparing: title memory copies (microseconds, bytes) and texture /// refreshes (microseconds, bytes hashed), since the last frame-rate line. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0), ]; /// What the runtime does when the host GPU fails for good: report it like a /// crash and end the run. The console has no such state, and carrying on /// draws nothing at seconds per frame. static ON_FAILURE: OnceLock !> = OnceLock::new(); /// Sets what a host GPU failure does (the runtime's crash report). pub fn on_failure(report: fn(&str) -> !) { let _ = ON_FAILURE.set(report); } /// Ends the run on a host GPU failure: what failed, the removal reason and /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a /// diagnostics build names the command). pub(crate) fn fail(what: std::fmt::Arguments) -> ! { let mut text = what.to_string(); if let Some(host) = host() { // SAFETY: a plain query. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } { text.push_str(&format!("; device removed: {e}")); } match host.log_messages() { Some(first) => text.push_str(&format!("; debug layer: {first}")), None if host.messages.is_none() => text.push_str( "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command", ), None => {} } } tracing::error!("{text}"); match ON_FAILURE.get() { Some(report) => report(&text), None => std::process::abort(), } } /// The host GPU, created on first use; `None` without one (a run then /// behaves as before: nothing executes). pub(crate) fn host() -> Option<&'static Host> { static HOST: OnceLock> = OnceLock::new(); HOST.get_or_init(|| match create() { Ok(host) => Some(host), Err(e) => { tracing::warn!(error = %e, "no host D3D12 device; command lists will not run"); None } }) .as_ref() } fn create() -> windows::core::Result { // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. let debug = cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some(); if debug { let mut layer: Option = None; match D3D12GetDebugInterface(&mut layer) { Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()), Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"), } // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range // descriptor heap indices and the like become messages naming // the command instead of page faults. Without state tracking // (directly indexed textures are not transitioned). if std::env::var_os("VICTORY_D3D12_GBV").is_some() && let Some(l) = &layer { if let Ok(d1) = l.cast::() { d1.SetEnableGPUBasedValidation(true); } if let Ok(d2) = l.cast::() { d2.SetGPUBasedValidationFlags( D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING, ); } tracing::info!("GPU-based validation on"); } } // Diagnostics: device-removed data (the command that faulted, the // faulting address), read when the device is removed. if dred_on() { let mut dred: Option = None; if D3D12GetDebugInterface(&mut dred).is_ok() && let Some(dred) = dred { dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON); } } let mut device: Option = None; // Diagnostics: the software adapter, on which a shader's wild access // is an access violation in this process (a crash report with the // address and instruction) instead of a GPU fault and driver reset. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() { let adapter = warp_adapter()?; D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?; tracing::info!("host device on the software adapter (WARP)"); } else { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } let device = device.ok_or_else(windows::core::Error::empty)?; let messages = debug .then(|| device.cast::().ok()) .flatten(); let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = CreateEventW(None, false, false, None)?; let rtvs: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: RTV_RING, ..Default::default() })?; let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); let dsvs: ID3D12DescriptorHeap = device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: RTV_RING, ..Default::default() })?; let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); tracing::info!("host D3D12 device ready"); Ok(Host { device, queue, fence, submitted: Mutex::new(0), event, rtvs, rtv_size, dsvs, dsv_size, next_dsv: AtomicU32::new(0), messages, next_rtv: AtomicU32::new(0), presenter: Mutex::new(None), }) } } /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton). /// Reject it before creating a device in diagnostics' software-only mode. fn warp_adapter() -> windows::core::Result { // SAFETY: plain DXGI adapter queries. unsafe { let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?; let desc = adapter.cast::()?.GetDesc1()?; if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { tracing::warn!( vendor = format_args!("{:#x}", desc.VendorId), flags = format_args!("{:#x}", desc.Flags), "DXGI did not identify the WARP adapter as software; refusing device" ); return Err(windows::core::Error::from_hresult( windows::Win32::Foundation::E_FAIL, )); } Ok(adapter) } } #[cfg(test)] mod tests { use super::*; #[test] fn list_scratch_reclaims_chunks_unused_by_two_recordings() { let Some(host) = host() else { return }; let list = host.new_list().unwrap(); let finish = || { list.close(); host.execute(&[&list]); list.reset(); }; let chunk_count = || list.scratch.lock().unwrap().chunks.len(); assert!(list.scratch(u64::MAX).is_none()); let first = list.scratch(SCRATCH_CHUNK).unwrap(); let second = list.scratch(SCRATCH_CHUNK).unwrap(); let third = list.scratch(SCRATCH_CHUNK).unwrap(); finish(); assert_eq!(chunk_count(), 3); assert_eq!(list.scratch(1).unwrap(), first); finish(); assert_eq!(chunk_count(), 3); // An alternating workload should get its existing mappings back. assert_eq!(list.scratch(SCRATCH_CHUNK).unwrap(), first); assert_eq!(list.scratch(SCRATCH_CHUNK).unwrap(), second); assert_eq!(list.scratch(SCRATCH_CHUNK).unwrap(), third); finish(); for expected in [3, 1] { assert_eq!(list.scratch(1).unwrap(), first); finish(); assert_eq!(chunk_count(), expected); } // Large dedicated uploads do not keep the scratch cache warm. list.scratch(SCRATCH_CHUNK + 1).unwrap(); finish(); assert_eq!(chunk_count(), 1); finish(); assert_eq!(chunk_count(), 0); list.scratch(1).unwrap(); list.close(); } #[test] fn failed_scratch_growth_leaves_room_for_a_smaller_request() { let Some(host) = host() else { return }; let mut scratch = Scratch::default(); let remaining = 256; let occupied = SCRATCH_CHUNK - remaining; let (buffer, mapped) = host.upload_buffer(SCRATCH_CHUNK).unwrap(); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; assert_eq!( scratch.reserve(occupied, || Some(ScratchChunk { _buffer: buffer, mapped: mapped as usize, gpu, })), Some((gpu, mapped)) ); assert!(scratch.reserve(2 * remaining, || None).is_none()); let (tail_gpu, tail_mapped) = scratch .reserve(remaining, || panic!("the existing buffer still has room")) .unwrap(); assert_eq!(tail_gpu, gpu + occupied); assert_eq!(tail_mapped, mapped.wrapping_add(occupied as usize)); } #[test] fn retired_scratch_is_reused_across_lists_within_the_shared_budget() { let Some(host) = host() else { return }; let idle = ScratchPool::default(); let mut first = Scratch::default(); let mut addresses = Vec::new(); for _ in 0..=IDLE_SCRATCH_LIMIT { addresses.push( first .reserve(SCRATCH_CHUNK, || { let (buffer, mapped) = host.upload_buffer(SCRATCH_CHUNK)?; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; Some(ScratchChunk { _buffer: buffer, mapped: mapped as usize, gpu, }) }) .unwrap(), ); } first.reset(&idle); first.reset(&idle); assert!(idle.take().is_none()); first.reset(&idle); assert!(first.chunks.is_empty()); let mut second = Scratch::default(); for address in addresses.into_iter().take(IDLE_SCRATCH_LIMIT).rev() { assert_eq!(second.reserve(SCRATCH_CHUNK, || idle.take()), Some(address)); } assert!(idle.take().is_none()); } #[test] fn warp_adapter_accepts_only_software() { // This probes DXGI without creating a D3D12 device or running a title. // SAFETY: plain DXGI adapter queries. let raw = unsafe { let Ok(factory) = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) else { return; }; factory.EnumWarpAdapter::() }; let Ok(raw) = raw else { return }; // SAFETY: EnumWarpAdapter returns a DXGI adapter, which implements // IDXGIAdapter1; `raw` owns that interface. let desc = unsafe { raw.cast::().unwrap().GetDesc1().unwrap() }; eprintln!( "EnumWarpAdapter: vendor={:#x}, flags={:#x}", desc.VendorId, desc.Flags ); assert_eq!( warp_adapter().is_ok(), desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0, ); } } /// A host command list and its allocator, always used together. pub(crate) struct HostList { allocator: ID3D12CommandAllocator, pub(crate) list: ID3D12GraphicsCommandList, /// Work for submission time, in recorded order. deferred: Mutex, /// Upload memory for data the list's draws make (expanded vertices), /// reused after a reset. scratch: Mutex, /// Host texture states the list assumes, by host copy: at its start and /// at its end. Lists are recorded on many threads and run in submission /// order, so the transitions from a texture's real state are made at /// submission, in `prelude`. Holding the copies keeps every texture the /// list names alive until it is reset, even if the title releases the /// resource first. states: Mutex, /// The list that runs those transitions just before this one. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList), /// The pipelines the list binds, for reports of slow submissions. pipelines: Mutex>, /// The work its indirect executions may still do (`indirect`): a /// shader-writable word, zeroed when the list is submitted. budget: OnceLock>, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] notes: Mutex>, /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command /// and at the end, and where they are read back. #[cfg(feature = "diagnostics")] stamps: OnceLock>, } /// Timestamps per list (diagnostics); commands past them are not timed. #[cfg(feature = "diagnostics")] const STAMPS: u32 = 4096; /// A marker's text and the host range its command reads (diagnostics). #[cfg(feature = "diagnostics")] type Note = (String, Option<(u64, u64)>); type States = std::collections::HashMap< usize, (u32, u32, std::sync::Arc), >; /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics /// builds). pub(crate) fn dred_on() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| { cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some() }) } /// Whether each list of a submission runs and is timed on its own, slow /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics /// builds; the commands are noted with `VICTORY_D3D12_DRED` on). #[cfg(feature = "diagnostics")] fn timing() -> bool { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some()) } /// Names a host object for the device-removed report, which names the /// allocations a page fault hit (only with device-removed data on). pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) { if dred_on() && let Ok(object) = object.cast::() { // SAFETY: a plain call on a live object. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) }; } } struct ScratchChunk { _buffer: ID3D12Resource, mapped: usize, gpu: u64, } /// Idle reusable scratch for the process-wide host device. A chunk enters the /// pool after a fenced list reset. Dedicated upload buffers bypass it. #[derive(Default)] struct ScratchPool(Mutex>); static IDLE_SCRATCH: ScratchPool = ScratchPool(Mutex::new(Vec::new())); impl ScratchPool { fn take(&self) -> Option { self.0.lock().unwrap_or_else(|e| e.into_inner()).pop() } fn recycle(&self, chunks: &mut impl Iterator) { let mut idle = self.0.lock().unwrap_or_else(|e| e.into_inner()); let free = IDLE_SCRATCH_LIMIT - idle.len(); idle.extend(chunks.take(free)); } } /// Upload chunks handed out front to back: the chunks, the one in use and /// the bytes used in it. #[derive(Default)] struct Scratch { chunks: Vec, current: usize, used: u64, previous_chunks: usize, } impl Scratch { fn reserve( &mut self, len: u64, allocate: impl FnOnce() -> Option, ) -> Option<(u64, *mut u8)> { let (current, used) = if self.used + len > SCRATCH_CHUNK { (self.current + 1, 0) } else { (self.current, self.used) }; if current == self.chunks.len() { self.chunks.push(allocate()?); } let chunk = &self.chunks[current]; // A failed allocation leaves room in the previous chunk available // to smaller requests recorded later in this list. (self.current, self.used) = (current, used + len); Some((chunk.gpu + used, (chunk.mapped + used as usize) as *mut u8)) } fn reset(&mut self, idle: &ScratchPool) { let used_chunks = self.current + usize::from(self.used != 0); // Keep the peak of the last two recordings, so a single small // recording does not cause allocations on the following one. let keep = used_chunks.max(self.previous_chunks); if keep < self.chunks.len() { idle.recycle(&mut self.chunks.drain(keep..)); } self.previous_chunks = used_chunks; (self.current, self.used) = (0, 0); } } // SAFETY: the chunk pointers are persistent mappings of upload buffers. unsafe impl Send for Scratch {} const SCRATCH_CHUNK: u64 = 4 << 20; // The host keeps at most 4 MiB of idle upload scratch across all lists. const IDLE_SCRATCH_LIMIT: usize = ((4 << 20) / SCRATCH_CHUNK) as usize; /// One piece of submission-time work, in recorded order. enum Step { /// A copy into title memory (destination, source, bytes): the title's /// buffer copies, which later refreshes must see. Copy(usize, usize, usize), /// A copy of title memory into the list's own upload memory. Fill(usize, usize, usize), /// Brings a range (address, bytes) of a buffer's host copy up to date: /// once per submission, whichever lists ask, until a `Copy` or `Run` /// intervenes. Refresh(std::sync::Arc, usize, usize), /// Work that may write title memory. Run(Box), /// Work that writes host memory only. Host(Box), /// Shaders write a range (address, bytes) of a buffer's host copy. GpuWrite(std::sync::Arc, usize, usize), /// Brings a texture's staging buffer up to date: once per submission, /// whichever lists sample it, until a `Copy` or `Run` intervenes. Texture(std::sync::Arc), } /// What a list does on the CPU when it is submitted: copies between host /// memory regions (title buffers, upload buffers and buffer copies), and /// the upload buffers its GPU commands read, kept until the list is reset. #[derive(Default)] struct Deferred { /// Destination, source, bytes. copies: Vec, uploads: Vec, /// Host objects the list's commands name (pipelines, root signatures, /// descriptor heaps): the title may release its objects before it /// submits the list. kept: Vec, /// Buffer ranges refreshed since the last title copy (host copy, /// address, bytes): refreshing them again would find the same bytes. refreshed: std::collections::HashSet<(usize, usize, usize)>, /// Textures whose contents the list brings up to date. textures: std::collections::HashSet, /// Bottom-of-pipe writes, done once the list has run: address, what, /// bytes. writes: Vec<(usize, crate::queue::Written, usize)>, /// Whether a step zeroes the indirect-work budget. budget_zeroed: bool, } impl Host { /// Whether the host runs mesh shaders at shader model 6.6 (translated /// mesh shaders need both); logged once. pub(crate) fn mesh_shaders(&self) -> bool { static MESH: OnceLock = OnceLock::new(); *MESH.get_or_init(|| { let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default(); let mut model = D3D12_FEATURE_DATA_SHADER_MODEL { HighestShaderModel: D3D_SHADER_MODEL_6_6, }; // SAFETY: each query writes its own structure of the given size. let ok = unsafe { self.device .CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS7, (&raw mut options).cast(), size_of_val(&options) as u32, ) .is_ok() && self .device .CheckFeatureSupport( D3D12_FEATURE_SHADER_MODEL, (&raw mut model).cast(), size_of_val(&model) as u32, ) .is_ok() }; let mesh = ok && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0; tracing::info!(mesh, "host mesh shader support"); mesh }) } /// The wave sizes the host runs (D3D12 options 1), which translated /// compute shaders that declare the console's wave size must fit; /// logged once. Unknown (the query fails): any. pub(crate) fn target(&self) -> victory_shader::emit::Target { static TARGET: OnceLock = OnceLock::new(); *TARGET.get_or_init(|| { let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS1::default(); // SAFETY: the query writes the structure of the given size. let ok = unsafe { self.device .CheckFeatureSupport( D3D12_FEATURE_D3D12_OPTIONS1, (&raw mut options).cast(), size_of_val(&options) as u32, ) .is_ok() }; let target = if ok && options.WaveOps.as_bool() && options.WaveLaneCountMin > 0 { victory_shader::emit::Target { lanes_min: options.WaveLaneCountMin, lanes_max: options.WaveLaneCountMax, } } else { victory_shader::emit::Target::ANY }; tracing::info!( lanes_min = target.lanes_min, lanes_max = target.lanes_max, "host wave sizes" ); if !target.runs(64) { tracing::warn!( "the host has no 64-lane waves: console wave64 compute programs that need \ their whole wave run as two 32-lane waves where there is a form for \ them; the rest do not translate, and their dispatches are dropped" ); } target }) } /// A new list, open for recording. pub(crate) fn new_list(&self) -> windows::core::Result { // SAFETY: plain object creation. unsafe { let allocator: ID3D12CommandAllocator = self .device .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; let list: ID3D12GraphicsCommandList = self.device.CreateCommandList( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None, )?; let prelude_allocator: ID3D12CommandAllocator = self .device .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList( 0, D3D12_COMMAND_LIST_TYPE_DIRECT, &prelude_allocator, None, )?; prelude.Close()?; Ok(HostList { allocator, list, deferred: Mutex::default(), scratch: Mutex::default(), states: Mutex::default(), prelude: (prelude_allocator, prelude), pipelines: Mutex::default(), budget: OnceLock::new(), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] stamps: OnceLock::new(), }) } } /// Runs closed lists and waits for them. pub(crate) fn execute(&self, runs: &[&HostList]) { // One submission at a time from preparation to copy-back: snapshots // and the ranges shaders write are per host copy, not per submission. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner()); let started = std::time::Instant::now(); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Submissions, 1); let mut lists: Vec> = Vec::with_capacity(2 * runs.len()); // Where each run's lists start in `lists`. let mut firsts = Vec::with_capacity(runs.len()); let mut batch = Batch::default(); let submission = NEXT_SUBMISSION.fetch_add(1, Ordering::Relaxed); for list in runs { list.run_deferred(&mut batch, submission); firsts.push(lists.len()); if let Some(prelude) = list.prelude() { lists.push(Some(prelude)); } lists.push(list.list.cast().ok()); } batch.flush(); let prepared = std::time::Instant::now(); // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`). #[cfg(feature = "diagnostics")] let groups: Vec<&[Option]> = if timing() { firsts .iter() .zip(firsts.iter().skip(1).chain([&lists.len()])) .map(|(&a, &b)| &lists[a..b]) .collect() } else { vec![&lists[..]] }; #[cfg(not(feature = "diagnostics"))] let groups = [&lists[..]]; for (i, group) in groups.iter().enumerate() { *submitted += 1; let started = std::time::Instant::now(); // SAFETY: closed lists; the fence and event are ours. let waited = unsafe { self.queue.ExecuteCommandLists(group); self.queue .Signal(&self.fence, *submitted) .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event)) .map_err(|e| e.to_string()) .and_then(|()| match WaitForSingleObject(self.event, INFINITE) { WAIT_OBJECT_0 => Ok(()), WAIT_FAILED => Err(windows::core::Error::from_thread().to_string()), status => Err(format!("unexpected fence wait status {:#x}", status.0)), }) }; if let Err(e) = waited { // Callers may reset lists or read GPU output as soon as we return. fail(format_args!( "host GPU fence wait failed for value {} in a submission of {} lists ({e}){}{}", *submitted, runs.len(), self.removal_data(runs), last_notes(runs) )); } #[cfg(feature = "diagnostics")] if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); for (ms, op) in runs[i].slowest(frequency, 6) { tracing::warn!("slow list command, {ms:.1} ms: {op}"); } } let _ = (i, started); } let _ = &firsts; let gpu = prepared.elapsed(); SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed); SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed); // The host resets a device whose submission runs for about 2 s. if gpu > std::time::Duration::from_millis(250) { let pipelines: std::collections::BTreeSet = runs .iter() .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone()) .collect(); tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission"); } // SAFETY: a plain query. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { fail(format_args!( "host GPU device removed after a submission of {} lists{}{}", runs.len(), self.removal_data(runs), last_notes(runs) )); } // What shaders wrote goes back before the bottom-of-pipe writes, // which tell the title the GPU is done; each range once per // submission, however many dispatches declared it (the world's // passes declare the same big ranges dozens of times). let copying = std::time::Instant::now(); // One list's lock at a time: a submission may name a list twice. let mut back: Vec<(std::sync::Arc, usize, usize)> = Vec::new(); for list in runs { for step in &list.deferred().copies { if let Step::GpuWrite(shadow, address, len) = step && !back .iter() .any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len)) { back.push((shadow.clone(), *address, *len)); } } } // `VICTORY_ASYNC_WRITEBACK=1`: the copy-back and the writes go to the // queue's worker (idea from ivall/xcl#562), so the title gets this // thread back to prepare its next submission. The ranges are held // inaccessible to the title until the job has put the GPU's bytes // back, and a later submission's snapshot of the same copy waits for // it (`Shadow::writing`). let mut worker = crate::writeback::enabled().then(crate::writeback::Job::new); if let Some(job) = &mut worker { for (shadow, address, len) in &back { shadow.write_back(*address, *len, submission, job.done()); job.blocks .extend(crate::watch::back_begin(&job.done(), *address, *len)); job.copies.push((shadow.clone(), *address, *len, submission)); } for list in runs { job.writes .extend(list.deferred().writes.iter().copied()); } let job = worker.take().expect("the job"); if !job.copies.is_empty() || !job.writes.is_empty() { crate::writeback::submit(job); } } else { for (shadow, address, len) in &back { let (address, len) = (*address, *len); let written = shadow.copy_back(address, len, submission); COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed); } COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed); for list in runs { for &(at, what, bytes) in &list.deferred().writes { what.write(at as *mut u8, bytes); } } } self.log_messages(); } /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations /// it lies in (by the names we give them) or the title memory copy just /// below it; for each list that did not finish, the command it stopped /// at and what the draws and dispatches in flight there run (or, in /// lists that never started, the pipelines they bind). fn removal_data(&self, runs: &[&HostList]) -> String { let Ok(dred) = self.device.cast::() else { return String::new(); }; let mut text = String::new(); let mut fault_va = None; // SAFETY: the outputs are the runtime's, valid while the device // lives; nodes are walked as linked, histories have their counts. unsafe { if let Ok(fault) = dred.GetPageFaultAllocationOutput1() && fault.PageFaultVA != 0 { let va = fault.PageFaultVA; fault_va = Some(va); text.push_str(&format!("; page fault at {va:#x}")); for (what, head) in [ ("inside", fault.pHeadExistingAllocationNode), ("inside freed", fault.pHeadRecentFreedAllocationNode), ] { let mut names = Vec::new(); let mut node = head; while let Some(n) = node.as_ref() && names.len() < 8 { let name = if n.ObjectNameW.is_null() { "unnamed".to_owned() } else { n.ObjectNameW.to_string().unwrap_or_default() }; names.push(format!("{name} (type {})", n.AllocationType.0)); node = n.pNext; } if !names.is_empty() { text.push_str(&format!("; {what} {names:?}")); } } text.push_str(&crate::shadow::near(va)); text.push_str(&crate::descriptor::host::near_heaps(va)); } // The plain output: the extended one (with marker texts) came // back without stopped lists on this host. let crumbs = match dred.GetAutoBreadcrumbsOutput() { Ok(crumbs) => crumbs, Err(e) => { text.push_str(&format!("; no breadcrumbs ({e})")); return text; } }; // Every list's progress (done/count), in the runtime's order. let mut progress = Vec::new(); let mut node = crumbs.pHeadAutoBreadcrumbNode; while let Some(p) = node.as_ref() { let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); let ours = p.pCommandList.as_ref().map(|l| l.as_raw()); let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours); progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount)); node = p.pNext; } text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}")); let mut plain = crumbs.pHeadAutoBreadcrumbNode; while let Some(p) = plain.as_ref() { let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0); if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() { let history = std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize); text.push_str(&format!( "; a list stopped at command {done} of {} (op {})", p.BreadcrumbCount, history[done as usize].0 )); let list = p.pCommandList.as_ref().map(|l| l.as_raw()); let run = runs.iter().find(|r| Some(r.list.as_raw()) == list); // The k-th marker command is the k-th note. #[cfg(feature = "diagnostics")] let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); history .iter() .enumerate() .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) .zip(notes.iter()) .map(|((at, _), (note, range))| { let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r)); (at as u32, format!("{note}{}", place.unwrap_or_default())) }) .collect() }); #[cfg(not(feature = "diagnostics"))] let markers: Vec<(u32, String)> = Vec::new(); #[cfg(not(feature = "diagnostics"))] let _ = fault_va; if done > 0 { text.push_str(&in_flight(history, &markers, done as usize)); } else if let Some(r) = run { let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner()); text.push_str(&format!(", its pipelines {pipelines:?}")); } } plain = p.pNext; } } text } /// Moves the debug layer's messages into our log; returns the first /// error among them. pub(crate) fn log_messages(&self) -> Option { let Some(queue) = &self.messages else { return None; }; let mut first_error = None; // SAFETY: each message is read into a buffer of the size the queue // reports, then the queue is emptied. unsafe { for i in 0..queue.GetNumStoredMessages() { let mut size = 0; if queue.GetMessage(i, None, &mut size).is_err() || size == 0 { continue; } let mut buffer = vec![0u64; size.div_ceil(8)]; let message = buffer.as_mut_ptr().cast::(); if queue.GetMessage(i, Some(message), &mut size).is_ok() { let m = &*message; let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); let text = String::from_utf8_lossy(text); let text = text.trim_end_matches('\0'); tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}"); if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { first_error = Some(text.to_owned()); } } } queue.ClearStoredMessages(); } first_error } /// A host render target view of `resource`, valid until it is recorded, /// or `None` if the host resource lacks `ALLOW_RENDER_TARGET`. pub(crate) fn rtv( &self, resource: &ID3D12Resource, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, ) -> Option { // SAFETY: a live resource. let flags = unsafe { resource.GetDesc() }.Flags; if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET.0 == 0 { return None; } let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; // SAFETY: a slot of our heap and a live resource. unsafe { let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); handle.ptr += (slot * self.rtv_size) as usize; self.device .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle); Some(handle) } } /// A render target view that discards what is written to it, in `desc`'s /// format (R8G8B8A8_UNORM without one), valid until it is recorded. It /// holds the place of a target the host cannot render to, so the targets /// after it keep their slots. pub(crate) fn null_rtv( &self, desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>, ) -> D3D12_CPU_DESCRIPTOR_HANDLE { // A null descriptor must be one a real resource could use: forwarding a // format the adapter cannot render to breaks that contract, and some // drivers reject a descriptor that does. let desc = desc .filter(|d| d.Format != DXGI_FORMAT_UNKNOWN && self.renders(d.Format)) .copied() .unwrap_or(D3D12_RENDER_TARGET_VIEW_DESC { Format: DXGI_FORMAT_R8G8B8A8_UNORM, ViewDimension: D3D12_RTV_DIMENSION_TEXTURE2D, ..Default::default() }); let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING; // SAFETY: a slot of our heap; a null resource with a description. unsafe { let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart(); handle.ptr += (slot * self.rtv_size) as usize; self.device .CreateRenderTargetView(None::<&ID3D12Resource>, Some(&desc), handle); handle } } /// Whether the adapter offers `format` as a render target, the use a null /// render-target descriptor stands in for. fn renders(&self, format: DXGI_FORMAT) -> bool { let mut support = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: format, ..Default::default() }; // SAFETY: plain feature query into our struct. let queried = unsafe { self.device.CheckFeatureSupport( D3D12_FEATURE_FORMAT_SUPPORT, (&raw mut support).cast(), size_of::() as u32, ) }; queried.is_ok() && support.Support1.0 as u32 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET.0 as u32 != 0 } /// A host depth view of `resource`, valid until it is recorded. pub(crate) fn dsv( &self, resource: &ID3D12Resource, desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>, ) -> D3D12_CPU_DESCRIPTOR_HANDLE { let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING; // SAFETY: a slot of our heap and a live resource. unsafe { let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart(); handle.ptr += (slot * self.dsv_size) as usize; self.device .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle); handle } } } impl HostList { /// The timestamp heap and its read-back buffer (diagnostics, timing on). #[cfg(feature = "diagnostics")] fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> { if !timing() { return None; } self.stamps .get_or_init(|| { let device = &host()?.device; let mut heap: Option = None; let mut back: Option = None; let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(STAMPS) * 8, Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; // SAFETY: plain object creation. unsafe { device .CreateQueryHeap( &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 }, &mut heap, ) .ok()?; device .CreateCommittedResource( &readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back, ) .ok()?; } Some((heap?, back?)) }) .as_ref() } /// The noted commands that took longest on the GPU, longest first, as /// (milliseconds, text) (diagnostics, timing on, after the list ran). #[cfg(feature = "diagnostics")] fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> { let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner()); let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else { return Vec::new(); }; let mut data = std::ptr::null_mut(); let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 }; // SAFETY: a read-back buffer the finished list resolved into. let stamps: Vec = unsafe { if back.Map(0, Some(&range), Some(&mut data)).is_err() { return Vec::new(); } let s = std::slice::from_raw_parts(data.cast::(), count + 1).to_vec(); back.Unmap(0, None); s }; let mut times: Vec<(f64, String)> = (0..count) .map(|i| { let ticks = stamps[i + 1].saturating_sub(stamps[i]); (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect()) }) .collect(); times.sort_by(|a, b| b.0.total_cmp(&a.0)); times.truncate(n); times } pub(crate) fn close(&self) { #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); // SAFETY: an open list, our heap and read-back buffer. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); } } // SAFETY: our list. if let Err(e) = unsafe { self.list.Close() } { fail(format_args!( "a host command list did not close ({e}): a command recorded into it was invalid" )); } } /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { *self.deferred() = Deferred::default(); self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); // SAFETY: the list is not executing. let reset = unsafe { self.allocator .Reset() .and_then(|()| self.list.Reset(&self.allocator, None)) }; if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } self.scratch .lock() .unwrap_or_else(|e| e.into_inner()) .reset(&IDLE_SCRATCH); } /// Moves a title texture's host copy to `wanted` (a host state) in this /// list: the host texture and the state it leaves, if that is a change. /// The list's first use of a texture records nothing: its prelude brings /// the texture there at submission. pub(crate) fn transition( &self, resource: crate::object::This, wanted: u32, ) -> Option<(&'static ID3D12Resource, u32)> { let texture = crate::resource::host_resource(resource)?; let copy = crate::resource::host_copy(resource)?; let wanted = legal_state(texture, wanted); let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner()); match states.entry(std::sync::Arc::as_ptr(©) as usize) { std::collections::hash_map::Entry::Vacant(v) => { v.insert((wanted, wanted, copy)); None } std::collections::hash_map::Entry::Occupied(mut o) => { let before = std::mem::replace(&mut o.get_mut().1, wanted); (before != wanted).then_some((texture, before)) } } } /// At submission: the list that moves each texture this list uses from /// its real state to the one the list starts with; the textures' real /// states become those the list ends with. fn prelude(&self) -> Option { let states = self.states.lock().unwrap_or_else(|e| e.into_inner()); let barriers: Vec = states .values() .filter_map(|(first, last, copy)| { let real = copy.state.swap(*last, Ordering::Relaxed); (real != *first).then(|| { transition( ©.texture, D3D12_RESOURCE_STATES(real as i32), D3D12_RESOURCE_STATES(*first as i32), ) }) }) .collect(); if barriers.is_empty() { return None; } let (allocator, list) = &self.prelude; // SAFETY: the prelude is not executing (every submission is waited // for); the textures are live. let recorded = unsafe { allocator.Reset().and_then(|()| { list.Reset(allocator, None)?; list.ResourceBarrier(&barriers); list.Close() }) }; if let Err(e) = recorded { fail(format_args!("a host state prelude did not record ({e})")); } list.cast().ok() } /// Notes what the command about to be recorded does, as a marker /// command whose text the list keeps (diagnostics, with device-removed /// data on): the report pairs the breadcrumbs' marker commands with the /// texts in order and names the commands a fault stopped among. #[cfg(feature = "diagnostics")] pub(crate) fn note_op(&self, what: impl FnOnce() -> String) { self.note(what, None); } /// As [`HostList::note_op`], for a copy that reads the host GPU range /// `(address, bytes)`: the report places the faulting address in it. #[cfg(feature = "diagnostics")] pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) { self.note(what, Some(range)); } #[cfg(feature = "diagnostics")] fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) { if dred_on() { let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { // SAFETY: an open list and our query heap. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; } let what = what(); let text: Vec = what.encode_utf16().chain([0]).collect(); const UNICODE: u32 = 0; // SAFETY: an open list; the marker is copied when recorded. unsafe { self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32) }; self.notes .lock() .unwrap_or_else(|e| e.into_inner()) .push((what, range)); } } /// Notes a pipeline the list binds. pub(crate) fn used_pipeline(&self, name: &str) { let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); if !pipelines.contains(name) { pipelines.insert(name.to_owned()); } } fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> { self.deferred.lock().unwrap_or_else(|e| e.into_inner()) } /// Copies `len` bytes from `src` to `dst` when the list is submitted. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) { let mut deferred = self.deferred(); deferred .copies .push(Step::Copy(dst as usize, src as usize, len)); deferred.refreshed.clear(); } /// Copies `len` bytes of title memory at `src` into the list's upload /// memory at `dst` when the list is submitted. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) { self.deferred() .copies .push(Step::Fill(dst as usize, src as usize, len)); } /// Copies `len` bytes of title memory at `src` into `dst` (mapped inside /// `upload`) when the list is submitted, keeping `upload` alive until the /// list is reset. pub(crate) fn defer_fill_upload( &self, upload: ID3D12Resource, dst: *mut u8, src: *const u8, len: usize, ) { let mut d = self.deferred(); d.uploads.push(upload); d.copies.push(Step::Fill(dst as usize, src as usize, len)); } /// Brings `[address, address + len)` of a buffer's host copy up to date /// when the list is submitted (once per range until a title copy /// intervenes), keeping the copy alive until the list is reset. pub(crate) fn defer_refresh( &self, shadow: &std::sync::Arc, address: usize, len: usize, ) { let mut deferred = self.deferred(); let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len); if deferred.refreshed.insert(key) { deferred .copies .push(Step::Refresh(shadow.clone(), address, len)); } } /// Shaders of the list write `[address, address + len)` of a buffer's /// host copy: copied back into title memory once the list has run. pub(crate) fn defer_gpu_write( &self, shadow: &std::sync::Arc, address: usize, len: usize, ) { self.deferred() .copies .push(Step::GpuWrite(shadow.clone(), address, len)); } /// Stores `what` (`bytes` of it) at `dst` once the list has run. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) { self.deferred().writes.push((dst as usize, what, bytes)); } /// A mapped upload buffer of `size` bytes, alive until the list is /// reset. /// /// shortcut: one buffer per copy; pool them once uploads are frequent. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let (buffer, data) = host.upload_buffer(size)?; name(&buffer, || format!("list upload {size:#x}")); self.deferred().uploads.push(buffer.clone()); Some((buffer, data)) } /// `len` bytes of upload memory (256-byte aligned) until the list is /// reset: the host GPU address and the CPU pointer. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> { let len = len.max(1).checked_next_multiple_of(256)?; let host = host()?; if len > SCRATCH_CHUNK { let (buffer, data) = host.upload_buffer(len)?; name(&buffer, || format!("list scratch {len:#x}")); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; self.deferred().uploads.push(buffer); return Some((gpu, data)); } let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner()); scratch.reserve(len, || { if let Some(chunk) = IDLE_SCRATCH.take() { return Some(chunk); } let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?; name(&buffer, || "list scratch".into()); // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() }; Some(ScratchChunk { _buffer: buffer, mapped: data as usize, gpu, }) }) } /// The host address of the list's indirect-work budget, zeroed at each /// submission of the list from the first use after a reset on. pub(crate) fn budget(&self) -> Option { let (buffer, data) = self .budget .get_or_init(|| { let (b, d) = host()?.shared_buffer(256)?; Some((b, d as usize)) }) .as_ref()?; let mut deferred = self.deferred(); if !deferred.budget_zeroed { deferred.budget_zeroed = true; let at = *data; // SAFETY: the list's own mapped word, written before it runs. deferred .copies .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) }))); } // SAFETY: a live buffer. Some(unsafe { buffer.GetGPUVirtualAddress() }) } /// Keeps `object` alive until the list is reset. pub(crate) fn keep(&self, object: &impl Interface) { if let Ok(object) = object.cast::() { self.deferred().kept.push(object); } } /// Whether this is the first time since the reset that the list asks /// about `key` (a texture to bring up to date). pub(crate) fn first_use(&self, key: usize) -> bool { self.deferred().textures.insert(key) } /// Runs `work` when the list is submitted, in order with its copies. /// `work` may write title memory (refreshes after it copy again). pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Run(Box::new(work))); self.deferred().refreshed.clear(); } /// As [`HostList::defer`], for work that writes only host memory. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) { self.deferred().copies.push(Step::Host(Box::new(work))); } /// Brings a texture's staging buffer up to date when the list is /// submitted, keeping it alive until the list is reset. pub(crate) fn defer_texture(&self, staging: std::sync::Arc) { self.deferred().copies.push(Step::Texture(staging)); } /// Runs the list's submission-time steps; refreshes go into `batch` /// (the title's big buffers, a 174 MB one among them, are read by most /// lists of a submission, through many ranges). fn run_deferred(&self, batch: &mut Batch, submission: u64) { #[cfg(feature = "diagnostics")] use crate::copystat::{C, add}; for step in &self.deferred().copies { let started = std::time::Instant::now(); let copied = match step { &Step::Copy(dst, src, len) => { #[cfg(feature = "diagnostics")] { add(C::Copies, 1); add(C::CopyBytes, len as u64); } batch.title_written(); copy_mapped(dst as *mut u8, src as *const u8, len, true); len } &Step::Fill(dst, src, len) => { #[cfg(feature = "diagnostics")] { add(C::Copies, 1); add(C::CopyBytes, len as u64); } copy_mapped(dst as *mut u8, src as *const u8, len, false); len } Step::Refresh(shadow, address, len) => { #[cfg(feature = "diagnostics")] { add(C::Refreshes, 1); add(C::RefreshBytes, *len as u64); } batch.add(shadow, *address, *len); continue; } Step::Run(work) | Step::Host(work) => { if matches!(step, Step::Run(_)) { batch.title_written(); } work(); #[cfg(feature = "diagnostics")] { add(C::Runs, 1); add(C::RunUs, started.elapsed().as_micros() as u64); } continue; } Step::GpuWrite(shadow, address, len) => { // The shaders start from the title's data. batch.flush(); shadow.writing(*address, *len, submission); continue; } Step::Texture(staging) => { if batch.texture_due(staging) { staging.refresh(); } continue; } }; PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); } } } /// A submission's refreshes not done yet, per buffer copy, merged where /// they share or touch a 64 KiB page: done before a step that writes title /// memory or gives a range to shaders, and before the lists run. Ranges /// pages apart stay apart: one range covering a big buffer's low and high /// ends would have its untouched middle checked (and its stale pages /// copied) too. /// /// Also the textures brought up to date in the submission so far: most /// lists of a world submission sample the same textures, and a texture in /// physical-page memory is hashed whole each time it is checked. Checked /// once, it is checked again only after a step that writes title memory. #[derive(Default)] struct Batch { /// Per copy, `[from, to)` ranges in the order they came. refreshes: Vec<(std::sync::Arc, Ranges)>, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } /// `[from, to)` ranges of title memory. type Ranges = Vec<(usize, usize)>; /// Sorts `[from, to)` ranges and merges those whose `page`-sized pages /// overlap or touch; empty ranges go. fn coalesce_ranges(ranges: &mut Ranges, page: usize) { ranges.retain(|&(from, to)| from < to); ranges.sort_unstable(); let mut merged: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); for &(from, to) in ranges.iter() { match merged.last_mut() { Some((_, end)) if from / page <= end.div_ceil(page) => *end = (*end).max(to), _ => merged.push((from, to)), } } *ranges = merged; } impl Batch { fn add(&mut self, shadow: &std::sync::Arc, address: usize, len: usize) { if len == 0 { return; } let range = (address, address.saturating_add(len)); match self .refreshes .iter_mut() .find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { Some((_, ranges)) => ranges.push(range), None => self.refreshes.push((shadow.clone(), vec![range])), } } /// Whether `staging` is still to be refreshed in this submission (and /// notes it refreshed). fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) } /// Before a step that writes title memory: pending refreshes are done /// first, and textures are checked again after it. fn title_written(&mut self) { self.flush(); self.textures.clear(); } fn flush(&mut self) { for (shadow, mut ranges) in self.refreshes.drain(..) { coalesce_ranges(&mut ranges, crate::watch::PAGE); for (from, to) in ranges { let started = std::time::Instant::now(); let copied = shadow.update(from, to - from); let us = started.elapsed().as_micros() as u64; #[cfg(feature = "diagnostics")] crate::copystat::range(from, to - from, us, 0); PREPARING[0].fetch_add(us, Ordering::Relaxed); PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed); } } } } /// Copies title memory at submission. The ranges were checked against their /// resources when recorded, but the title may since have unmapped pages of /// them (tiled memory, page mappings), which read as zeros here; a title /// destination (`title_dst`) that is not all mapped is left alone. /// /// The source is read through the kernel (`ReadProcessMemory`), which /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first /// cost about 2 ms per copy in the title's big pools (it walks the page /// tables to the region's end), which made copies run at 100-200 MB/s. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) { #[cfg(feature = "diagnostics")] match crate::copystat::mode() { 1 => { // SAFETY: timing only: the caller vouches for the source. unsafe { std::ptr::copy(src, dst, len) }; return; } 2 => return, _ => {} } if len == 0 || title_dst && !crate::texture::committed(dst, len) { return; } if title_dst { // The kernel writes the destination: it must not be guarded. crate::watch::writing(dst as usize, len); } #[cfg(feature = "diagnostics")] let moved = std::time::Instant::now(); let (whole, done) = read_partial(src, dst, len); #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64); if whole { return; } #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Fallbacks, 1); let done = done.min(len); // Something is unmapped at or after `src + done`: walk VirtualQuery regions // for the remaining tail so large committed spans take one ReadProcessMemory // each and unmapped holes are zeroed in one memset, falling back to // 64 KiB -> 4 KiB pieces if a concurrent unmap races between VirtualQuery // and ReadProcessMemory. for_regions(src as usize + done, len - done, |at, n, committed| { let to = dst.wrapping_add(at - src as usize); if !committed { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Unmapped, n as u64); // SAFETY: inside the destination, which is mapped. unsafe { to.write_bytes(0, n) }; } else if !read(at as *const u8, to, n) { copy_pieces(dst, src, at, n); } }); } /// Piece-by-piece fallback (64 KiB, then 4 KiB) for `[start, start + len)`. fn copy_pieces(dst: *mut u8, src: *const u8, start: usize, len: usize) { for_pieces(start, len, 64 << 10, |at, n| { let to = dst.wrapping_add(at - src as usize); if !read(at as *const u8, to, n) { for_pieces(at, n, 4 << 10, |at, n| { let to = dst.wrapping_add(at - src as usize); if !read(at as *const u8, to, n) { #[cfg(feature = "diagnostics")] crate::copystat::add(crate::copystat::C::Unmapped, n as u64); // SAFETY: inside the destination, which is mapped. unsafe { to.write_bytes(0, n) }; } }); } }); } /// Reads title memory at `src` into `dst`; false if a page of it is not /// readable. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { read(src, dst.as_mut_ptr(), dst.len()) } /// Copies `len` bytes from `src` to `dst` unless a source page is not /// readable. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool { read_partial(src, dst, len).0 } /// Copies up to `len` bytes from `src` to `dst`, returning `(ok, bytes_read)`. /// On a partial copy (`ok == false`), the first `bytes_read` bytes are already /// written into `dst`. fn read_partial(src: *const u8, dst: *mut u8, len: usize) -> (bool, usize) { use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut done = 0; // SAFETY: the destination is mapped writable memory of `len` bytes; the // kernel checks the source. let ok = unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }; (ok, done) } /// Copies host memory into title memory after a submission (what shaders /// wrote), leaving pages that are not mapped alone. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) { use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory; use windows_sys::Win32::System::Threading::GetCurrentProcess; let write_partial = |at: usize, n: usize| { let from = src.wrapping_add(at - dst as usize); let mut done = 0; // SAFETY: the source is our mapped host copy; the kernel checks the // destination. let ok = unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }; (ok, done) }; if len == 0 { return; } let (ok, done) = write_partial(dst as usize, len); if ok { return; } let done = done.min(len); for_regions(dst as usize + done, len - done, |at, n, committed| { if committed && !write_partial(at, n).0 { for_pieces(at, n, 64 << 10, |at, n| { if !write_partial(at, n).0 { for_pieces(at, n, 4 << 10, |at, n| { // Wine does not write into write-watched pages not // written since they were committed // (ERROR_PARTIAL_COPY), but reads into them. The // kernel checks this destination as well. if !write_partial(at, n).0 { read(src.wrapping_add(at - dst as usize), at as *mut u8, n); } }); } }); } }); } /// Walks `[start, start + len)` in `VirtualQuery` regions, passing `(at, n, /// committed)` where `committed` is true for `MEM_COMMIT` regions that are /// neither `PAGE_NOACCESS` nor `PAGE_GUARD`. fn for_regions(start: usize, len: usize, mut f: impl FnMut(usize, usize, bool)) { use windows_sys::Win32::System::Memory::{ MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery, }; let end = start + len; let mut at = start; while at < end { let mut mbi = std::mem::MaybeUninit::::uninit(); // SAFETY: `mbi` has the exact size `VirtualQuery` expects. let queried = unsafe { VirtualQuery( at as *const _, mbi.as_mut_ptr(), std::mem::size_of::(), ) }; if queried == 0 { f(at, end - at, true); break; } // SAFETY: `VirtualQuery` returned non-zero, initializing `mbi`. let mbi = unsafe { mbi.assume_init() }; let region_end = (mbi.BaseAddress as usize).saturating_add(mbi.RegionSize); if region_end <= at { f(at, end - at, true); break; } let next = region_end.min(end); let committed = mbi.State == MEM_COMMIT && (mbi.Protect & PAGE_GUARD) == 0 && (mbi.Protect & 0xff) != PAGE_NOACCESS; f(at, next - at, committed); at = next; } } /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of /// `step`. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) { let end = start + len; let mut at = start; while at < end { let next = ((at / step + 1) * step).min(end); f(at, next - at); at = next; } } impl Host { /// A buffer in the upload heap, mapped for writing. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_UPLOAD, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: size.max(1), Height: 1, DepthOrArraySize: 1, MipLevels: 1, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; let mut buffer: Option = None; let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping of an upload buffer. let made = unsafe { self.device .CreateCommittedResource( &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, None, &mut buffer, ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; b.Map(0, None, Some(&mut data)) }) }; match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { tracing::warn!(error = %e, size, "no upload buffer"); None } } } } /// The swap chain formats a presented texture can be copied into: its own /// family's. fn swap_format(format: DXGI_FORMAT) -> Option { Some(match format.0 { 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM, 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM, 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM, 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT, _ => return None, }) } const BUFFERS: u32 = 2; struct Presenter { swap_chain: IDXGISwapChain3, width: u32, height: u32, format: DXGI_FORMAT, copy: HostList, hwnd: HWND, meter: Meter, } /// The frame rate, shown in the window's caption every second and logged /// every few seconds. struct Meter { since: std::time::Instant, frames: u32, #[cfg(feature = "diagnostics")] copy_stats_frames: u64, drawn: u64, logged: std::time::Instant, /// The caption the window had, once read. caption: Option>, } impl Meter { fn new() -> Self { let now = std::time::Instant::now(); Meter { since: now, frames: 0, #[cfg(feature = "diagnostics")] copy_stats_frames: 0, drawn: crate::draw::drawn(), logged: now, caption: None, } } /// Counts a presented frame. fn frame(&mut self, hwnd: HWND) { #[cfg(feature = "diagnostics")] tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present"); self.frames += 1; #[cfg(feature = "diagnostics")] { self.copy_stats_frames += 1; } let elapsed = self.since.elapsed(); if elapsed < std::time::Duration::from_secs(1) { return; } let drawn = crate::draw::drawn(); let frames = f64::from(self.frames); let fps = frames / elapsed.as_secs_f64(); let ms = elapsed.as_secs_f64() * 1000.0 / frames; let draws = (drawn - self.drawn) as f64 / frames; (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn); // Of a frame, ms preparing submissions and ms waiting for the GPU. let [cpu, gpu] = [0, 1].map(|i| { SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames }); let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| { let scale = if i % 2 == 0 { 1e3 } else { 1e6 }; PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames }); let [back_ms, back_mb] = [0, 1].map(|i| { COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames }); let dropped = crate::draw::take_dropped() as f64 / frames; let indirect = crate::list::take_indirect() as f64 / frames; // Over the same frames as the counts above. #[cfg(feature = "diagnostics")] let drops = crate::pipeline::take_drops(); if self.logged.elapsed() >= std::time::Duration::from_secs(5) { self.logged = std::time::Instant::now(); tracing::info!( "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \ {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \ GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \ dropped {dropped:.0} without a host pipeline ({making} being made) and \ {indirect:.0} indirect", making = crate::pipeline::making() ); #[cfg(feature = "diagnostics")] { crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64); for (why, n) in drops.iter().take(40) { tracing::info!( "dropped {:.1}/frame without a host pipeline: {why}", *n as f64 / frames ); } } } if self.caption.is_none() { // The window's own text, read without a message. let mut buffer = vec![0u16; 512]; // SAFETY: a window handle and a buffer of that length. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) }; buffer.truncate(n.max(0) as usize); self.caption = Some(buffer); } let Some(caption) = &self.caption else { return }; let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame"); let mut text: Vec = caption.iter().copied().chain(text.encode_utf16()).collect(); text.push(0); // Setting the text waits for the window's thread (a title thread, // which may not pump for a while), so a thread of ours does it and // presenting never waits; it takes the newest text when free. static PENDING: Mutex)>> = Mutex::new(None); static SETTER: std::sync::Once = std::sync::Once::new(); *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text)); SETTER.call_once(|| { let _ = std::thread::Builder::new() .name("victory-caption".into()) .spawn(|| { loop { let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take(); match next { // SAFETY: a window handle and a NUL-terminated text. Some((hwnd, text)) => unsafe { let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr())); }, None => std::thread::sleep(std::time::Duration::from_millis(100)), } } }); }); } } impl Host { /// Shows `texture`, which is in `state` (a host state) and stays in it, /// as frame `frame` (saved if captures are on). `None` if nothing was /// shown; else, in diagnostics builds, whether the frame was black. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; let Some(format) = swap_format(desc.Format) else { tracing::warn!(format = desc.Format.0, "cannot present this format"); return None; }; let (width, height) = (desc.Width as u32, desc.Height); let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner()); if presenter.is_none() { *presenter = match self.presenter(width, height, format) { Ok(p) => Some(p), Err(e) => { tracing::warn!(error = %e, "no swap chain"); return None; } }; } let p = presenter.as_mut()?; if (p.width, p.height, p.format) != (width, height, format) { // SAFETY: no back buffer is held; every submission was waited for. let resized = unsafe { p.swap_chain .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0)) }; match resized { Ok(()) => (p.width, p.height, p.format) = (width, height, format), Err(e) => { tracing::warn!(error = %e, width, height, "swap chain not resized"); return None; } } } let state = D3D12_RESOURCE_STATES(state as i32); // SAFETY: our swap chain, list and a live source texture. unsafe { let index = p.swap_chain.GetCurrentBackBufferIndex(); let Ok(back) = p.swap_chain.GetBuffer::(index) else { return None; }; p.copy.reset(); let list = &p.copy.list; list.ResourceBarrier(&[ transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE), transition( &back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST, ), ]); list.CopyResource(&back, texture); #[cfg(feature = "diagnostics")] let capture = crate::capture::wanted(frame) .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] let probe = crate::capture::probe(&self.device, list, texture); #[cfg(not(feature = "diagnostics"))] let _ = frame; list.ResourceBarrier(&[ transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state), transition( &back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT, ), ]); p.copy.close(); self.execute(&[&p.copy]); #[cfg(feature = "diagnostics")] if let Some((buffer, footprint)) = capture { crate::capture::save_read_back(frame, &buffer, &footprint); } let _ = p.swap_chain.Present(0, DXGI_PRESENT(0)); p.meter.frame(p.hwnd); #[cfg(feature = "diagnostics")] return Some(probe.is_some_and(|b| crate::capture::black(&b))); #[cfg(not(feature = "diagnostics"))] Some(false) } } fn presenter( &self, width: u32, height: u32, format: DXGI_FORMAT, ) -> windows::core::Result { let hwnd = match title_window() { Some(hwnd) => hwnd, None => window(width, height)?, }; // SAFETY: plain object creation for our window. unsafe { let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?; let desc = DXGI_SWAP_CHAIN_DESC1 { Width: width, Height: height, Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, BufferCount: BUFFERS, SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD, ..Default::default() }; let swap_chain = factory .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)? .cast::()?; let copy = self.new_list()?; copy.close(); tracing::info!(width, height, format = format.0, "presenting to a window"); Ok(Presenter { swap_chain, width, height, format, copy, hwnd, meter: Meter::new(), }) } } } /// A visible top-level window of this process: the one the title made, if /// it made one. fn title_window() -> Option { extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL { let mut process = 0; // SAFETY: a window handle from the enumeration; `found` is ours. unsafe { GetWindowThreadProcessId(hwnd, Some(&mut process)); if process == windows::Win32::System::Threading::GetCurrentProcessId() && IsWindowVisible(hwnd).as_bool() { *(found.0 as *mut Option) = Some(hwnd); return false.into(); } } true.into() } let mut found: Option = None; // SAFETY: the callback only writes `found`, which outlives the call. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) }; found } /// `state` without the bits the host texture's flags forbid: the console /// lets the title name states its own resources allow (unordered access on /// a depth target, whose host copy cannot have both). pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 { // SAFETY: a plain query. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state) } /// [`legal_state`] for a texture with resource flags `flags`. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 { // (flag, set or clear forbids, state bits): render target, unordered // access, depth, denied shader resource. const FORBIDDEN: [(u32, bool, u32); 4] = [ (0x1, false, 0x4), (0x4, false, 0x8), (0x2, false, 0x10 | 0x20), (0x8, true, 0x40 | 0x80), ]; FORBIDDEN .iter() .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny) .fold(state, |s, &(_, _, bits)| s & !bits) } impl Host { /// A buffer in system memory that the CPU maps (write-back, so reading /// it is fast too) and shaders read and write: for host copies of title /// memory that shaders write, which upload memory cannot be. Starts in /// the common state (buffers move out of it implicitly). pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> { let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_CUSTOM, CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK, MemoryPoolPreference: D3D12_MEMORY_POOL_L0, ..Default::default() }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: size.max(1), 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() }; let mut buffer: Option = None; let mut data = std::ptr::null_mut(); // SAFETY: plain creation and mapping of a CPU-visible buffer. let made = unsafe { self.device .CreateCommittedResource( &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer, ) .and_then(|()| { let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?; b.Map(0, None, Some(&mut data)) }) }; match made { Ok(()) => Some((buffer?, data.cast())), Err(e) => { tracing::warn!(error = %e, size, "no shared buffer"); None } } } } /// For adapters without device-removed data (the software one): the last /// commands each list of the failed submission noted (diagnostics, with /// `VICTORY_D3D12_DRED`). fn last_notes(runs: &[&HostList]) -> String { #[cfg(feature = "diagnostics")] { let mut text = String::new(); for (i, r) in runs.iter().enumerate() { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); for (n, _) in notes.iter().rev().take(6).rev() { text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); } } text } #[cfg(not(feature = "diagnostics"))] { let _ = runs; String::new() } } /// Where the faulting address `va` lies against a range `(start, bytes)` a /// command reads (diagnostics). #[cfg(feature = "diagnostics")] fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String { let end = start + bytes; if va < start { format!(" (fault {:#x} below its source)", start - va) } else if va < end { format!(" (fault at source +{:#x})", va - start) } else { format!(" (fault {:#x} past its source's end)", va - end) } } /// The commands that may have been running where a list stopped at /// command `done`: those between the barriers around it (work between /// barriers overlaps on the GPU), by kind, and what the markers just /// before them say (`HostList::note_op`: diagnostics builds with /// device-removed data on). fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String { let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER; let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1); let to = history[done..] .iter() .position(barrier) .map_or(history.len(), |b| (done + b).max(done + 1)); let mut text = format!(", commands {from}..{to} between its barriers:"); let mut shown = 0; for i in from..to { let op = history[i]; if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 { continue; } shown += 1; let marker = i .checked_sub(1) .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER) .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m)) .map_or("no marker", |(_, s)| s.as_str()); text.push_str(&format!("; command {i} (op {}): {marker}", op.0)); } text } pub(crate) fn transition( resource: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES, ) -> D3D12_RESOURCE_BARRIER { 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 { // SAFETY: a borrowed pointer; the barrier never releases it. pResource: unsafe { std::mem::transmute_copy(resource) }, Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, StateBefore: before, StateAfter: after, }), }, } } /// A window of the given client size, owned by its own message thread. fn window(width: u32, height: u32) -> windows::core::Result { let (sender, receiver) = std::sync::mpsc::channel(); std::thread::Builder::new() .name("victory-window".into()) .spawn(move || { let made = make_window(width, height); let ok = made.is_ok(); let _ = sender.send(made.map(|h| h.0 as usize)); if ok { pump(); } }) .map_err(|_| windows::core::Error::empty())?; let hwnd = receiver .recv() .map_err(|_| windows::core::Error::empty())??; Ok(HWND(hwnd as *mut _)) } extern "system" fn window_proc( hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM, ) -> LRESULT { // SAFETY: the default handling for our window. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) } } fn make_window(width: u32, height: u32) -> windows::core::Result { const CLASS: PCWSTR = w!("VIctory"); // SAFETY: registers our class once and creates a window of it. unsafe { let instance = GetModuleHandleW(None)?; let class = WNDCLASSEXW { cbSize: size_of::() as u32, lpfnWndProc: Some(window_proc), hInstance: instance.into(), lpszClassName: CLASS, hCursor: LoadCursorW(None, IDC_ARROW)?, ..Default::default() }; RegisterClassExW(&class); let mut rect = RECT { left: 0, top: 0, right: width as i32, bottom: height as i32, }; AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?; CreateWindowExW( WINDOW_EX_STYLE(0), CLASS, w!("VIctory"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, CW_USEDEFAULT, CW_USEDEFAULT, rect.right - rect.left, rect.bottom - rect.top, None, None, Some(instance.into()), None, ) } } fn pump() { let mut message = MSG::default(); // SAFETY: the standard message loop of this thread's window. unsafe { while GetMessageW(&mut message, None, 0, 0).as_bool() { let _ = TranslateMessage(&message); DispatchMessageW(&message); } } } #[cfg(test)] mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::{Batch, coalesce_ranges}; use std::sync::Arc; const PAGE: usize = crate::watch::PAGE; fn coalesced(mut ranges: Vec<(usize, usize)>) -> Vec<(usize, usize)> { coalesce_ranges(&mut ranges, PAGE); ranges } #[test] fn empty_ranges_are_dropped() { assert_eq!(coalesced(vec![]), []); assert_eq!(coalesced(vec![(5, 5), (PAGE, PAGE)]), []); assert_eq!(coalesced(vec![(10, 10), (20, 30)]), [(20, 30)]); } #[test] fn ranges_in_one_page_merge() { assert_eq!(coalesced(vec![(100, 200), (10, 20), (150, 400)]), [(10, 400)]); // Nested and repeated. assert_eq!(coalesced(vec![(0, PAGE), (8, 16), (0, PAGE)]), [(0, PAGE)]); } #[test] fn ranges_in_touching_pages_merge() { // Ends in page 0, starts in page 1. assert_eq!(coalesced(vec![(PAGE + 8, PAGE + 16), (0, 8)]), [(0, PAGE + 16)]); // Ends exactly at page 1's start, starts in page 1. assert_eq!(coalesced(vec![(0, PAGE), (PAGE + 100, 2 * PAGE)]), [(0, 2 * PAGE)]); // A chain of ranges each in the page after the last. let chain: Vec<_> = (0..8).map(|p| (p * PAGE + 10, p * PAGE + 20)).collect(); assert_eq!(coalesced(chain), [(10, 7 * PAGE + 20)]); } #[test] fn ranges_pages_apart_stay_apart() { // A whole untouched page between them. assert_eq!(coalesced(vec![(2 * PAGE, 2 * PAGE + 1), (0, 1)]), [(0, 1), (2 * PAGE, 2 * PAGE + 1)]); // The low and high ends of a 256 MiB buffer. let (low, high) = (1 << 30, (1 << 30) + (256 << 20) - 64); assert_eq!( coalesced(vec![(high, high + 64), (low, low + 64), (low + 32, low + 128)]), [(low, low + 128), (high, high + 64)] ); } #[test] fn ranges_at_the_top_of_the_address_space_do_not_overflow() { let top = usize::MAX; assert_eq!(coalesced(vec![(top - 8, top), (top - 100, top - 50)]), [(top - 100, top)]); } #[test] fn a_texture_is_checked_once_per_submission() { let mut batch = Batch::default(); let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16])); // The first list sampling each texture checks it ... assert!(batch.texture_due(&a)); assert!(batch.texture_due(&b)); // ... later lists of the same submission do not. assert!(!batch.texture_due(&a)); assert!(!batch.texture_due(&a.clone())); assert!(!batch.texture_due(&b)); } #[test] fn title_writes_make_textures_due_again() { let mut batch = Batch::default(); let a = Arc::new(1u32); assert!(batch.texture_due(&a)); assert!(!batch.texture_due(&a)); // A copy into title memory or work that may write it may have // changed the texture's memory. batch.title_written(); assert!(batch.texture_due(&a)); assert!(!batch.texture_due(&a)); // A fresh submission starts over. let mut next = Batch::default(); assert!(next.texture_due(&a)); } /// The hashing a submission does for textures in physical-page memory, /// with every list checking the textures it samples (before) and with /// each checked once (after). Run with /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`. #[test] #[ignore = "benchmark"] fn texture_checks_per_submission() { const TEXTURES: usize = 48; const SIZE: usize = 4 << 20; const LISTS: usize = 12; let textures: Vec>> = (0..TEXTURES) .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect())) .collect(); let submit = |dedupe: bool| { let mut batch = Batch::default(); let mut hashed = 0usize; let started = std::time::Instant::now(); for _ in 0..LISTS { for t in &textures { if !dedupe || batch.texture_due(t) { std::hint::black_box(blake3::hash(t)); hashed += 1; } } } (started.elapsed(), hashed) }; submit(false); // warm up let (before, n_before) = submit(false); let (after, n_after) = submit(true); assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES)); println!( "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \ before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)", SIZE >> 20, before.as_secs_f64() / after.as_secs_f64() ); } /// `copy_mapped` and `write_mapped` handle committed regions interleaved /// with reserved (unmapped) holes: committed bytes round-trip and holes /// read as zero / are skipped on write. #[test] fn copy_mapped_and_write_mapped_handle_holes_across_regions() { use windows_sys::Win32::System::Memory::{ MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, }; const TOTAL: usize = 2 << 20; const CHUNK: usize = 512 << 10; // SAFETY: reserving a 2 MiB private virtual range. let base = unsafe { VirtualAlloc(std::ptr::null(), TOTAL, MEM_RESERVE, PAGE_NOACCESS) }; assert!(!base.is_null()); let base = base.cast::(); // SAFETY: committing two 512 KiB slices at 0 and 1 MiB and filling them. unsafe { assert!(!VirtualAlloc(base.cast(), CHUNK, MEM_COMMIT, PAGE_READWRITE).is_null()); assert!( !VirtualAlloc(base.add(2 * CHUNK).cast(), CHUNK, MEM_COMMIT, PAGE_READWRITE) .is_null() ); base.write_bytes(0x3C, CHUNK); base.add(2 * CHUNK).write_bytes(0x5A, CHUNK); } // Pre-dirty destination so we verify holes are explicitly zeroed. let mut dst = vec![0xAAu8; TOTAL]; super::copy_mapped(dst.as_mut_ptr(), base, TOTAL, false); assert!(dst[..CHUNK].iter().all(|&b| b == 0x3C)); assert!(dst[CHUNK..2 * CHUNK].iter().all(|&b| b == 0)); assert!(dst[2 * CHUNK..3 * CHUNK].iter().all(|&b| b == 0x5A)); assert!(dst[3 * CHUNK..].iter().all(|&b| b == 0)); // write_mapped writes both committed regions and skips both holes. let mut src = vec![0xEEu8; TOTAL]; src[..CHUNK].fill(0x71); src[2 * CHUNK..3 * CHUNK].fill(0x92); super::write_mapped(base, src.as_ptr(), TOTAL); // SAFETY: both slices are committed and readable; then release the reservation. unsafe { assert!(std::slice::from_raw_parts(base, CHUNK).iter().all(|&b| b == 0x71)); assert!( std::slice::from_raw_parts(base.add(2 * CHUNK), CHUNK) .iter() .all(|&b| b == 0x92) ); VirtualFree(base.cast(), 0, MEM_RELEASE); } } /// Compares the old 64 KiB piece fallback against the `VirtualQuery` /// region fallback on 64 MiB ranges with small (4 KiB) and large (32 MiB) /// unmapped holes. Run with /// `cargo test --release -p victory-gpu -- --ignored --nocapture copy_mapped_hole`. #[test] #[ignore = "benchmark"] fn copy_mapped_hole_benchmark() { use windows_sys::Win32::System::Memory::{ MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, }; const TOTAL: usize = 64 << 20; const RUNS: usize = 16; for (label, hole_at, hole_len) in [ ("4 KiB hole at 32 MiB", 32 << 20, 4 << 10), ("32 MiB hole at 16 MiB", 16 << 20, 32 << 20), ] { // SAFETY: reserving a 64 MiB private range. let base = unsafe { VirtualAlloc(std::ptr::null(), TOTAL, MEM_RESERVE, PAGE_NOACCESS) }; assert!(!base.is_null()); let base = base.cast::(); // SAFETY: committing two slices around the hole and initializing them. unsafe { assert!(!VirtualAlloc(base.cast(), hole_at, MEM_COMMIT, PAGE_READWRITE).is_null()); assert!( !VirtualAlloc( base.add(hole_at + hole_len).cast(), TOTAL - hole_at - hole_len, MEM_COMMIT, PAGE_READWRITE, ) .is_null() ); base.write_bytes(0x11, hole_at); base.add(hole_at + hole_len) .write_bytes(0x22, TOTAL - hole_at - hole_len); } let mut dst = vec![0u8; TOTAL]; // Warm up both paths. super::copy_pieces(dst.as_mut_ptr(), base, base as usize, TOTAL); super::copy_mapped(dst.as_mut_ptr(), base, TOTAL, false); let t0 = std::time::Instant::now(); for _ in 0..RUNS { // Old path: initial failing read + full 64 KiB/4 KiB piece fallback. let _ = super::read(base, dst.as_mut_ptr(), TOTAL); super::copy_pieces(dst.as_mut_ptr(), base, base as usize, TOTAL); } let old = t0.elapsed(); let t1 = std::time::Instant::now(); for _ in 0..RUNS { super::copy_mapped(dst.as_mut_ptr(), base, TOTAL, false); } let new = t1.elapsed(); // SAFETY: releasing the reservation. unsafe { VirtualFree(base.cast(), 0, MEM_RELEASE) }; println!( "64 MiB ({label}, {RUNS} runs): old={old:?}, new={new:?} ({:.2}x)", old.as_secs_f64() / new.as_secs_f64() ); } } }