host.rs 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053
  1. //! The host GPU: one D3D12 device and direct queue (decision 0007), and a
  2. //! window to present on.
  3. //!
  4. //! shortcut: every submission is waited for, so CPU and GPU never overlap;
  5. //! overlap them with per-submission fences once more than clears run.
  6. use std::sync::atomic::{AtomicU32, Ordering};
  7. use std::sync::{Mutex, OnceLock};
  8. use windows::Win32::Foundation::{HANDLE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  9. use windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_12_0;
  10. use windows::Win32::Graphics::Direct3D12::*;
  11. use windows::Win32::Graphics::Dxgi::Common::*;
  12. use windows::Win32::Graphics::Dxgi::*;
  13. use windows::Win32::System::LibraryLoader::GetModuleHandleW;
  14. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  15. use windows::Win32::UI::WindowsAndMessaging::*;
  16. use windows::core::{Interface, PCWSTR, w};
  17. /// Resource states without the console's own bits (compression hints from
  18. /// bit 25 up), which the host rejects.
  19. pub(crate) fn pc_state(state: u32) -> u32 {
  20. state & 0x01ff_ffff
  21. }
  22. /// A console state as a host texture state: PC bits only, and none of the
  23. /// buffer-only ones the console allows on textures (vertex, constant and
  24. /// index buffer, stream out, indirect arguments, as in "generic read").
  25. pub(crate) fn texture_state(state: u32) -> u32 {
  26. const BUFFER_ONLY: u32 = 0x1 | 0x2 | 0x100 | 0x200;
  27. pc_state(state) & !BUFFER_ONLY
  28. }
  29. /// Render target views live only until their command is recorded, so a
  30. /// ring of host descriptors is enough.
  31. const RTV_RING: u32 = 1024;
  32. pub(crate) struct Host {
  33. pub(crate) device: ID3D12Device,
  34. queue: ID3D12CommandQueue,
  35. fence: ID3D12Fence,
  36. /// The last value signalled on `fence`, behind the submission lock.
  37. submitted: Mutex<u64>,
  38. event: HANDLE,
  39. rtvs: ID3D12DescriptorHeap,
  40. rtv_size: u32,
  41. /// A ring of depth views, used as `rtvs`.
  42. dsvs: ID3D12DescriptorHeap,
  43. dsv_size: u32,
  44. next_dsv: AtomicU32,
  45. /// With `VICTORY_D3D12_DEBUG` set (diagnostics builds): the debug
  46. /// layer's messages.
  47. messages: Option<ID3D12InfoQueue>,
  48. next_rtv: AtomicU32,
  49. presenter: Mutex<Option<Presenter>>,
  50. }
  51. // SAFETY: D3D12 devices, queues, fences and descriptor heaps are
  52. // free-threaded; the event handle is only waited on under `submitted`.
  53. unsafe impl Send for Host {}
  54. // SAFETY: as above.
  55. unsafe impl Sync for Host {}
  56. /// Time spent in submissions since the last frame-rate line, in
  57. /// microseconds: preparing them on the CPU (title memory copies, texture
  58. /// detiling), then waiting for the GPU.
  59. static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] =
  60. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  61. /// After submissions: shader-written ranges compared and copied back into
  62. /// title memory (microseconds, bytes that differed), since the last
  63. /// frame-rate line.
  64. static COPY_BACK: [std::sync::atomic::AtomicU64; 2] =
  65. [std::sync::atomic::AtomicU64::new(0), std::sync::atomic::AtomicU64::new(0)];
  66. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  67. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  68. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  69. std::sync::atomic::AtomicU64::new(0),
  70. std::sync::atomic::AtomicU64::new(0),
  71. std::sync::atomic::AtomicU64::new(0),
  72. std::sync::atomic::AtomicU64::new(0),
  73. ];
  74. /// What the runtime does when the host GPU fails for good: report it like a
  75. /// crash and end the run. The console has no such state, and carrying on
  76. /// draws nothing at seconds per frame.
  77. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  78. /// Sets what a host GPU failure does (the runtime's crash report).
  79. pub fn on_failure(report: fn(&str) -> !) {
  80. let _ = ON_FAILURE.set(report);
  81. }
  82. /// Ends the run on a host GPU failure: what failed, the removal reason and
  83. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  84. /// diagnostics build names the command).
  85. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  86. let mut text = what.to_string();
  87. if let Some(host) = host() {
  88. // SAFETY: a plain query.
  89. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  90. text.push_str(&format!("; device removed: {e}"));
  91. }
  92. match host.log_messages() {
  93. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  94. None if host.messages.is_none() => text.push_str(
  95. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  96. ),
  97. None => {}
  98. }
  99. }
  100. tracing::error!("{text}");
  101. match ON_FAILURE.get() {
  102. Some(report) => report(&text),
  103. None => std::process::abort(),
  104. }
  105. }
  106. /// The host GPU, created on first use; `None` without one (a run then
  107. /// behaves as before: nothing executes).
  108. pub(crate) fn host() -> Option<&'static Host> {
  109. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  110. HOST.get_or_init(|| match create() {
  111. Ok(host) => Some(host),
  112. Err(e) => {
  113. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  114. None
  115. }
  116. })
  117. .as_ref()
  118. }
  119. fn create() -> windows::core::Result<Host> {
  120. // SAFETY: plain D3D12 object creation with valid descriptions.
  121. unsafe {
  122. // The debug layer only in builds with diagnostics.
  123. let debug =
  124. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  125. if debug {
  126. let mut layer: Option<ID3D12Debug> = None;
  127. match D3D12GetDebugInterface(&mut layer) {
  128. Ok(()) => layer.iter().for_each(|l| l.EnableDebugLayer()),
  129. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  130. }
  131. // GPU-based validation (`VICTORY_D3D12_GBV`): out-of-range
  132. // descriptor heap indices and the like become messages naming
  133. // the command instead of page faults. Without state tracking
  134. // (directly indexed textures are not transitioned).
  135. if std::env::var_os("VICTORY_D3D12_GBV").is_some()
  136. && let Some(l) = &layer
  137. {
  138. if let Ok(d1) = l.cast::<ID3D12Debug1>() {
  139. d1.SetEnableGPUBasedValidation(true);
  140. }
  141. if let Ok(d2) = l.cast::<ID3D12Debug2>() {
  142. d2.SetGPUBasedValidationFlags(
  143. D3D12_GPU_BASED_VALIDATION_FLAGS_DISABLE_STATE_TRACKING,
  144. );
  145. }
  146. tracing::info!("GPU-based validation on");
  147. }
  148. }
  149. // Diagnostics: device-removed data (the command that faulted, the
  150. // faulting address), read when the device is removed.
  151. if dred_on() {
  152. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  153. if D3D12GetDebugInterface(&mut dred).is_ok()
  154. && let Some(dred) = dred
  155. {
  156. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  157. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  158. }
  159. }
  160. let mut device: Option<ID3D12Device> = None;
  161. // Diagnostics: the software adapter, on which a shader's wild access
  162. // is an access violation in this process (a crash report with the
  163. // address and instruction) instead of a GPU fault and driver reset.
  164. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  165. let adapter = warp_adapter()?;
  166. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  167. tracing::info!("host device on the software adapter (WARP)");
  168. } else {
  169. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  170. }
  171. let device = device.ok_or_else(windows::core::Error::empty)?;
  172. let messages = debug
  173. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  174. .flatten();
  175. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  176. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  177. ..Default::default()
  178. })?;
  179. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  180. let event = CreateEventW(None, false, false, None)?;
  181. let rtvs: ID3D12DescriptorHeap =
  182. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  183. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  184. NumDescriptors: RTV_RING,
  185. ..Default::default()
  186. })?;
  187. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  188. let dsvs: ID3D12DescriptorHeap =
  189. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  190. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  191. NumDescriptors: RTV_RING,
  192. ..Default::default()
  193. })?;
  194. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  195. tracing::info!("host D3D12 device ready");
  196. Ok(Host {
  197. device,
  198. queue,
  199. fence,
  200. submitted: Mutex::new(0),
  201. event,
  202. rtvs,
  203. rtv_size,
  204. dsvs,
  205. dsv_size,
  206. next_dsv: AtomicU32::new(0),
  207. messages,
  208. next_rtv: AtomicU32::new(0),
  209. presenter: Mutex::new(None),
  210. })
  211. }
  212. }
  213. /// DXGI may return hardware for `EnumWarpAdapter` (notably under Proton).
  214. /// Reject it before creating a device in diagnostics' software-only mode.
  215. fn warp_adapter() -> windows::core::Result<IDXGIAdapter> {
  216. // SAFETY: plain DXGI adapter queries.
  217. unsafe {
  218. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  219. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  220. let desc = adapter.cast::<IDXGIAdapter1>()?.GetDesc1()?;
  221. if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 {
  222. tracing::warn!(
  223. vendor = format_args!("{:#x}", desc.VendorId),
  224. flags = format_args!("{:#x}", desc.Flags),
  225. "DXGI did not identify the WARP adapter as software; refusing device"
  226. );
  227. return Err(windows::core::Error::from_hresult(
  228. windows::Win32::Foundation::E_FAIL,
  229. ));
  230. }
  231. Ok(adapter)
  232. }
  233. }
  234. #[cfg(test)]
  235. mod tests {
  236. use super::*;
  237. #[test]
  238. fn warp_adapter_accepts_only_software() {
  239. // This probes DXGI without creating a D3D12 device or running a title.
  240. // SAFETY: plain DXGI adapter queries.
  241. let raw = unsafe {
  242. let Ok(factory) = CreateDXGIFactory2::<IDXGIFactory4>(DXGI_CREATE_FACTORY_FLAGS(0))
  243. else {
  244. return;
  245. };
  246. factory.EnumWarpAdapter::<IDXGIAdapter>()
  247. };
  248. let Ok(raw) = raw else { return };
  249. let desc = unsafe { raw.cast::<IDXGIAdapter1>().unwrap().GetDesc1().unwrap() };
  250. eprintln!(
  251. "EnumWarpAdapter: vendor={:#x}, flags={:#x}",
  252. desc.VendorId, desc.Flags
  253. );
  254. assert_eq!(
  255. warp_adapter().is_ok(),
  256. desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0,
  257. );
  258. }
  259. }
  260. /// A host command list and its allocator, always used together.
  261. pub(crate) struct HostList {
  262. allocator: ID3D12CommandAllocator,
  263. pub(crate) list: ID3D12GraphicsCommandList,
  264. /// Work for submission time, in recorded order.
  265. deferred: Mutex<Deferred>,
  266. /// Upload memory for data the list's draws make (expanded vertices),
  267. /// reused after a reset.
  268. scratch: Mutex<Scratch>,
  269. /// Host texture states the list assumes, by host copy: at its start and
  270. /// at its end. Lists are recorded on many threads and run in submission
  271. /// order, so the transitions from a texture's real state are made at
  272. /// submission, in `prelude`. Holding the copies keeps every texture the
  273. /// list names alive until it is reset, even if the title releases the
  274. /// resource first.
  275. states: Mutex<States>,
  276. /// The list that runs those transitions just before this one.
  277. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
  278. /// The pipelines the list binds, for reports of slow submissions.
  279. pipelines: Mutex<std::collections::BTreeSet<String>>,
  280. /// The work its indirect executions may still do (`indirect`): a
  281. /// shader-writable word, zeroed when the list is submitted.
  282. budget: OnceLock<Option<(ID3D12Resource, usize)>>,
  283. /// The texts of the markers `note_op` set, in order (for device-removed
  284. /// data without marker texts), with the host GPU range a copy reads.
  285. #[cfg(feature = "diagnostics")]
  286. notes: Mutex<Vec<Note>>,
  287. /// With `VICTORY_GPU_TIMING`: a GPU timestamp before each noted command
  288. /// and at the end, and where they are read back.
  289. #[cfg(feature = "diagnostics")]
  290. stamps: OnceLock<Option<(ID3D12QueryHeap, ID3D12Resource)>>,
  291. }
  292. /// Timestamps per list (diagnostics); commands past them are not timed.
  293. #[cfg(feature = "diagnostics")]
  294. const STAMPS: u32 = 4096;
  295. /// A marker's text and the host range its command reads (diagnostics).
  296. #[cfg(feature = "diagnostics")]
  297. type Note = (String, Option<(u64, u64)>);
  298. type States = std::collections::HashMap<
  299. usize,
  300. (u32, u32, std::sync::Arc<crate::resource::HostTexture>),
  301. >;
  302. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  303. /// builds).
  304. pub(crate) fn dred_on() -> bool {
  305. static ON: OnceLock<bool> = OnceLock::new();
  306. *ON.get_or_init(|| {
  307. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  308. })
  309. }
  310. /// Whether each list of a submission runs and is timed on its own, slow
  311. /// ones logged with their commands (`VICTORY_GPU_TIMING`, diagnostics
  312. /// builds; the commands are noted with `VICTORY_D3D12_DRED` on).
  313. #[cfg(feature = "diagnostics")]
  314. fn timing() -> bool {
  315. static ON: OnceLock<bool> = OnceLock::new();
  316. *ON.get_or_init(|| std::env::var_os("VICTORY_GPU_TIMING").is_some())
  317. }
  318. /// Names a host object for the device-removed report, which names the
  319. /// allocations a page fault hit (only with device-removed data on).
  320. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  321. if dred_on()
  322. && let Ok(object) = object.cast::<ID3D12Object>()
  323. {
  324. // SAFETY: a plain call on a live object.
  325. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  326. }
  327. }
  328. /// Upload chunks handed out front to back: the chunks, the one in use and
  329. /// the bytes used in it.
  330. #[derive(Default)]
  331. struct Scratch {
  332. chunks: Vec<(ID3D12Resource, usize, u64)>,
  333. current: usize,
  334. used: u64,
  335. }
  336. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  337. unsafe impl Send for Scratch {}
  338. const SCRATCH_CHUNK: u64 = 4 << 20;
  339. /// One piece of submission-time work, in recorded order.
  340. enum Step {
  341. /// A copy into title memory (destination, source, bytes): the title's
  342. /// buffer copies, which later refreshes must see.
  343. Copy(usize, usize, usize),
  344. /// A copy of title memory into the list's own upload memory.
  345. Fill(usize, usize, usize),
  346. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  347. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  348. /// intervenes.
  349. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  350. /// Work that may write title memory.
  351. Run(Box<dyn Fn() + Send>),
  352. /// Work that writes host memory only.
  353. Host(Box<dyn Fn() + Send>),
  354. /// Shaders write a range (address, bytes) of a buffer's host copy.
  355. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  356. /// Brings a texture's staging buffer up to date: once per submission,
  357. /// whichever lists sample it, until a `Copy` or `Run` intervenes.
  358. Texture(std::sync::Arc<crate::texture::Staging>),
  359. }
  360. /// What a list does on the CPU when it is submitted: copies between host
  361. /// memory regions (title buffers, upload buffers and buffer copies), and
  362. /// the upload buffers its GPU commands read, kept until the list is reset.
  363. #[derive(Default)]
  364. struct Deferred {
  365. /// Destination, source, bytes.
  366. copies: Vec<Step>,
  367. uploads: Vec<ID3D12Resource>,
  368. /// Host objects the list's commands name (pipelines, root signatures,
  369. /// descriptor heaps): the title may release its objects before it
  370. /// submits the list.
  371. kept: Vec<windows::core::IUnknown>,
  372. /// Buffer ranges refreshed since the last title copy (host copy,
  373. /// address, bytes): refreshing them again would find the same bytes.
  374. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  375. /// Textures whose contents the list brings up to date.
  376. textures: std::collections::HashSet<usize>,
  377. /// Bottom-of-pipe writes, done once the list has run: address, what,
  378. /// bytes.
  379. writes: Vec<(usize, crate::queue::Written, usize)>,
  380. /// Whether a step zeroes the indirect-work budget.
  381. budget_zeroed: bool,
  382. }
  383. impl Host {
  384. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  385. /// mesh shaders need both); logged once.
  386. pub(crate) fn mesh_shaders(&self) -> bool {
  387. static MESH: OnceLock<bool> = OnceLock::new();
  388. *MESH.get_or_init(|| {
  389. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  390. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  391. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  392. };
  393. // SAFETY: each query writes its own structure of the given size.
  394. let ok = unsafe {
  395. self.device
  396. .CheckFeatureSupport(
  397. D3D12_FEATURE_D3D12_OPTIONS7,
  398. (&raw mut options).cast(),
  399. size_of_val(&options) as u32,
  400. )
  401. .is_ok()
  402. && self
  403. .device
  404. .CheckFeatureSupport(
  405. D3D12_FEATURE_SHADER_MODEL,
  406. (&raw mut model).cast(),
  407. size_of_val(&model) as u32,
  408. )
  409. .is_ok()
  410. };
  411. let mesh = ok
  412. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  413. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  414. tracing::info!(mesh, "host mesh shader support");
  415. mesh
  416. })
  417. }
  418. /// A new list, open for recording.
  419. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  420. // SAFETY: plain object creation.
  421. unsafe {
  422. let allocator: ID3D12CommandAllocator = self
  423. .device
  424. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  425. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  426. 0,
  427. D3D12_COMMAND_LIST_TYPE_DIRECT,
  428. &allocator,
  429. None,
  430. )?;
  431. let prelude_allocator: ID3D12CommandAllocator = self
  432. .device
  433. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  434. let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  435. 0,
  436. D3D12_COMMAND_LIST_TYPE_DIRECT,
  437. &prelude_allocator,
  438. None,
  439. )?;
  440. prelude.Close()?;
  441. Ok(HostList {
  442. allocator,
  443. list,
  444. deferred: Mutex::default(),
  445. scratch: Mutex::default(),
  446. states: Mutex::default(),
  447. prelude: (prelude_allocator, prelude),
  448. pipelines: Mutex::default(),
  449. budget: OnceLock::new(),
  450. #[cfg(feature = "diagnostics")]
  451. notes: Mutex::default(),
  452. #[cfg(feature = "diagnostics")]
  453. stamps: OnceLock::new(),
  454. })
  455. }
  456. }
  457. /// Runs closed lists and waits for them.
  458. pub(crate) fn execute(&self, runs: &[&HostList]) {
  459. // One submission at a time from preparation to copy-back: snapshots
  460. // and the ranges shaders write are per host copy, not per submission.
  461. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  462. let started = std::time::Instant::now();
  463. #[cfg(feature = "diagnostics")]
  464. crate::copystat::add(crate::copystat::C::Submissions, 1);
  465. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  466. // Where each run's lists start in `lists`.
  467. let mut firsts = Vec::with_capacity(runs.len());
  468. let mut batch = Batch::default();
  469. for list in runs {
  470. list.run_deferred(&mut batch);
  471. firsts.push(lists.len());
  472. if let Some(prelude) = list.prelude() {
  473. lists.push(Some(prelude));
  474. }
  475. lists.push(list.list.cast().ok());
  476. }
  477. batch.flush();
  478. let prepared = std::time::Instant::now();
  479. // Diagnostics: each list on its own, timed (`VICTORY_GPU_TIMING`).
  480. #[cfg(feature = "diagnostics")]
  481. let groups: Vec<&[Option<ID3D12CommandList>]> = if timing() {
  482. firsts
  483. .iter()
  484. .zip(firsts.iter().skip(1).chain([&lists.len()]))
  485. .map(|(&a, &b)| &lists[a..b])
  486. .collect()
  487. } else {
  488. vec![&lists[..]]
  489. };
  490. #[cfg(not(feature = "diagnostics"))]
  491. let groups = [&lists[..]];
  492. for (i, group) in groups.iter().enumerate() {
  493. *submitted += 1;
  494. let started = std::time::Instant::now();
  495. // SAFETY: closed lists; the fence and event are ours.
  496. unsafe {
  497. self.queue.ExecuteCommandLists(group);
  498. let waited = self
  499. .queue
  500. .Signal(&self.fence, *submitted)
  501. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  502. match waited {
  503. Ok(()) => {
  504. WaitForSingleObject(self.event, INFINITE);
  505. }
  506. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  507. }
  508. }
  509. #[cfg(feature = "diagnostics")]
  510. if groups.len() > 1 && started.elapsed() > std::time::Duration::from_millis(50) {
  511. // SAFETY: a plain query.
  512. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1);
  513. let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len();
  514. tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list");
  515. for (ms, op) in runs[i].slowest(frequency, 6) {
  516. tracing::warn!("slow list command, {ms:.1} ms: {op}");
  517. }
  518. }
  519. let _ = (i, started);
  520. }
  521. let _ = &firsts;
  522. let gpu = prepared.elapsed();
  523. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  524. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  525. // The host resets a device whose submission runs for about 2 s.
  526. if gpu > std::time::Duration::from_millis(250) {
  527. let pipelines: std::collections::BTreeSet<String> = runs
  528. .iter()
  529. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  530. .collect();
  531. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  532. }
  533. // SAFETY: a plain query.
  534. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  535. fail(format_args!(
  536. "host GPU device removed after a submission of {} lists{}{}",
  537. runs.len(),
  538. self.removal_data(runs),
  539. last_notes(runs)
  540. ));
  541. }
  542. // What shaders wrote goes back before the bottom-of-pipe writes,
  543. // which tell the title the GPU is done; each range once per
  544. // submission, however many dispatches declared it (the world's
  545. // passes declare the same big ranges dozens of times).
  546. let copying = std::time::Instant::now();
  547. // One list's lock at a time: a submission may name a list twice.
  548. let mut back: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)> = Vec::new();
  549. for list in runs {
  550. for step in &list.deferred().copies {
  551. if let Step::GpuWrite(shadow, address, len) = step
  552. && !back
  553. .iter()
  554. .any(|(s, a, l)| std::sync::Arc::ptr_eq(s, shadow) && (*a, *l) == (*address, *len))
  555. {
  556. back.push((shadow.clone(), *address, *len));
  557. }
  558. }
  559. }
  560. for (shadow, address, len) in &back {
  561. let (address, len) = (*address, *len);
  562. let written = shadow.copy_back(address, len);
  563. COPY_BACK[1].fetch_add(written as u64, Ordering::Relaxed);
  564. }
  565. COPY_BACK[0].fetch_add(copying.elapsed().as_micros() as u64, Ordering::Relaxed);
  566. for list in runs {
  567. for &(at, what, bytes) in &list.deferred().writes {
  568. what.write(at as *mut u8, bytes);
  569. }
  570. }
  571. self.log_messages();
  572. }
  573. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  574. /// it lies in (by the names we give them) or the title memory copy just
  575. /// below it; for each list that did not finish, the command it stopped
  576. /// at and what the draws and dispatches in flight there run (or, in
  577. /// lists that never started, the pipelines they bind).
  578. fn removal_data(&self, runs: &[&HostList]) -> String {
  579. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  580. return String::new();
  581. };
  582. let mut text = String::new();
  583. let mut fault_va = None;
  584. // SAFETY: the outputs are the runtime's, valid while the device
  585. // lives; nodes are walked as linked, histories have their counts.
  586. unsafe {
  587. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  588. && fault.PageFaultVA != 0
  589. {
  590. let va = fault.PageFaultVA;
  591. fault_va = Some(va);
  592. text.push_str(&format!("; page fault at {va:#x}"));
  593. for (what, head) in [
  594. ("inside", fault.pHeadExistingAllocationNode),
  595. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  596. ] {
  597. let mut names = Vec::new();
  598. let mut node = head;
  599. while let Some(n) = node.as_ref()
  600. && names.len() < 8
  601. {
  602. let name = if n.ObjectNameW.is_null() {
  603. "unnamed".to_owned()
  604. } else {
  605. n.ObjectNameW.to_string().unwrap_or_default()
  606. };
  607. names.push(format!("{name} (type {})", n.AllocationType.0));
  608. node = n.pNext;
  609. }
  610. if !names.is_empty() {
  611. text.push_str(&format!("; {what} {names:?}"));
  612. }
  613. }
  614. text.push_str(&crate::shadow::near(va));
  615. text.push_str(&crate::descriptor::host::near_heaps(va));
  616. }
  617. // The plain output: the extended one (with marker texts) came
  618. // back without stopped lists on this host.
  619. let crumbs = match dred.GetAutoBreadcrumbsOutput() {
  620. Ok(crumbs) => crumbs,
  621. Err(e) => {
  622. text.push_str(&format!("; no breadcrumbs ({e})"));
  623. return text;
  624. }
  625. };
  626. // Every list's progress (done/count), in the runtime's order.
  627. let mut progress = Vec::new();
  628. let mut node = crumbs.pHeadAutoBreadcrumbNode;
  629. while let Some(p) = node.as_ref() {
  630. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  631. let ours = p.pCommandList.as_ref().map(|l| l.as_raw());
  632. let index = runs.iter().position(|r| Some(r.list.as_raw()) == ours);
  633. progress.push(format!("{done}/{} {index:?}", p.BreadcrumbCount));
  634. node = p.pNext;
  635. }
  636. text.push_str(&format!("; breadcrumbs (done/count, list) {progress:?}"));
  637. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  638. while let Some(p) = plain.as_ref() {
  639. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  640. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  641. let history =
  642. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  643. text.push_str(&format!(
  644. "; a list stopped at command {done} of {} (op {})",
  645. p.BreadcrumbCount, history[done as usize].0
  646. ));
  647. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  648. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  649. // The k-th marker command is the k-th note.
  650. #[cfg(feature = "diagnostics")]
  651. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  652. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  653. history
  654. .iter()
  655. .enumerate()
  656. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  657. .zip(notes.iter())
  658. .map(|((at, _), (note, range))| {
  659. let place = fault_va.zip(*range).map(|(va, r)| fault_in(va, r));
  660. (at as u32, format!("{note}{}", place.unwrap_or_default()))
  661. })
  662. .collect()
  663. });
  664. #[cfg(not(feature = "diagnostics"))]
  665. let markers: Vec<(u32, String)> = Vec::new();
  666. #[cfg(not(feature = "diagnostics"))]
  667. let _ = fault_va;
  668. if done > 0 {
  669. text.push_str(&in_flight(history, &markers, done as usize));
  670. } else if let Some(r) = run {
  671. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  672. text.push_str(&format!(", its pipelines {pipelines:?}"));
  673. }
  674. }
  675. plain = p.pNext;
  676. }
  677. }
  678. text
  679. }
  680. /// Moves the debug layer's messages into our log; returns the first
  681. /// error among them.
  682. pub(crate) fn log_messages(&self) -> Option<String> {
  683. let Some(queue) = &self.messages else {
  684. return None;
  685. };
  686. let mut first_error = None;
  687. // SAFETY: each message is read into a buffer of the size the queue
  688. // reports, then the queue is emptied.
  689. unsafe {
  690. for i in 0..queue.GetNumStoredMessages() {
  691. let mut size = 0;
  692. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  693. continue;
  694. }
  695. let mut buffer = vec![0u64; size.div_ceil(8)];
  696. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  697. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  698. let m = &*message;
  699. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  700. let text = String::from_utf8_lossy(text);
  701. let text = text.trim_end_matches('\0');
  702. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  703. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  704. first_error = Some(text.to_owned());
  705. }
  706. }
  707. }
  708. queue.ClearStoredMessages();
  709. }
  710. first_error
  711. }
  712. /// A host render target view of `resource`, valid until it is recorded.
  713. pub(crate) fn rtv(
  714. &self,
  715. resource: &ID3D12Resource,
  716. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  717. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  718. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  719. // SAFETY: a slot of our heap and a live resource.
  720. unsafe {
  721. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  722. handle.ptr += (slot * self.rtv_size) as usize;
  723. self.device
  724. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  725. handle
  726. }
  727. }
  728. /// A host depth view of `resource`, valid until it is recorded.
  729. pub(crate) fn dsv(
  730. &self,
  731. resource: &ID3D12Resource,
  732. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  733. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  734. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  735. // SAFETY: a slot of our heap and a live resource.
  736. unsafe {
  737. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  738. handle.ptr += (slot * self.dsv_size) as usize;
  739. self.device
  740. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  741. handle
  742. }
  743. }
  744. }
  745. impl HostList {
  746. /// The timestamp heap and its read-back buffer (diagnostics, timing on).
  747. #[cfg(feature = "diagnostics")]
  748. fn stamps(&self) -> Option<&(ID3D12QueryHeap, ID3D12Resource)> {
  749. if !timing() {
  750. return None;
  751. }
  752. self.stamps
  753. .get_or_init(|| {
  754. let device = &host()?.device;
  755. let mut heap: Option<ID3D12QueryHeap> = None;
  756. let mut back: Option<ID3D12Resource> = None;
  757. let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() };
  758. let desc = D3D12_RESOURCE_DESC {
  759. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  760. Width: u64::from(STAMPS) * 8,
  761. Height: 1,
  762. DepthOrArraySize: 1,
  763. MipLevels: 1,
  764. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  765. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  766. ..Default::default()
  767. };
  768. // SAFETY: plain object creation.
  769. unsafe {
  770. device
  771. .CreateQueryHeap(
  772. &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: STAMPS, NodeMask: 0 },
  773. &mut heap,
  774. )
  775. .ok()?;
  776. device
  777. .CreateCommittedResource(
  778. &readback,
  779. D3D12_HEAP_FLAG_NONE,
  780. &desc,
  781. D3D12_RESOURCE_STATE_COPY_DEST,
  782. None,
  783. &mut back,
  784. )
  785. .ok()?;
  786. }
  787. Some((heap?, back?))
  788. })
  789. .as_ref()
  790. }
  791. /// The noted commands that took longest on the GPU, longest first, as
  792. /// (milliseconds, text) (diagnostics, timing on, after the list ran).
  793. #[cfg(feature = "diagnostics")]
  794. fn slowest(&self, frequency: u64, n: usize) -> Vec<(f64, String)> {
  795. let notes = self.notes.lock().unwrap_or_else(|e| e.into_inner());
  796. let (Some((_, back)), count) = (self.stamps(), notes.len().min(STAMPS as usize - 1)) else {
  797. return Vec::new();
  798. };
  799. let mut data = std::ptr::null_mut();
  800. let range = D3D12_RANGE { Begin: 0, End: (count + 1) * 8 };
  801. // SAFETY: a read-back buffer the finished list resolved into.
  802. let stamps: Vec<u64> = unsafe {
  803. if back.Map(0, Some(&range), Some(&mut data)).is_err() {
  804. return Vec::new();
  805. }
  806. let s = std::slice::from_raw_parts(data.cast::<u64>(), count + 1).to_vec();
  807. back.Unmap(0, None);
  808. s
  809. };
  810. let mut times: Vec<(f64, String)> = (0..count)
  811. .map(|i| {
  812. let ticks = stamps[i + 1].saturating_sub(stamps[i]);
  813. (ticks as f64 * 1e3 / frequency.max(1) as f64, notes[i].0.chars().take(300).collect())
  814. })
  815. .collect();
  816. times.sort_by(|a, b| b.0.total_cmp(&a.0));
  817. times.truncate(n);
  818. times
  819. }
  820. pub(crate) fn close(&self) {
  821. #[cfg(feature = "diagnostics")]
  822. if let Some((heap, back)) = self.stamps() {
  823. let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1);
  824. // SAFETY: an open list, our heap and read-back buffer.
  825. unsafe {
  826. self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count);
  827. self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0);
  828. }
  829. }
  830. // SAFETY: our list.
  831. if let Err(e) = unsafe { self.list.Close() } {
  832. fail(format_args!(
  833. "a host command list did not close ({e}): a command recorded into it was invalid"
  834. ));
  835. }
  836. }
  837. /// Only after the list's last submission finished (every one is waited
  838. /// for).
  839. pub(crate) fn reset(&self) {
  840. *self.deferred() = Deferred::default();
  841. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  842. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  843. #[cfg(feature = "diagnostics")]
  844. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  845. {
  846. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  847. (scratch.current, scratch.used) = (0, 0);
  848. }
  849. // SAFETY: the list is not executing.
  850. let reset = unsafe {
  851. self.allocator
  852. .Reset()
  853. .and_then(|()| self.list.Reset(&self.allocator, None))
  854. };
  855. if let Err(e) = reset {
  856. fail(format_args!("a host command list did not reset ({e})"));
  857. }
  858. }
  859. /// Moves a title texture's host copy to `wanted` (a host state) in this
  860. /// list: the host texture and the state it leaves, if that is a change.
  861. /// The list's first use of a texture records nothing: its prelude brings
  862. /// the texture there at submission.
  863. pub(crate) fn transition(
  864. &self,
  865. resource: crate::object::This,
  866. wanted: u32,
  867. ) -> Option<(&'static ID3D12Resource, u32)> {
  868. let texture = crate::resource::host_resource(resource)?;
  869. let copy = crate::resource::host_copy(resource)?;
  870. let wanted = legal_state(texture, wanted);
  871. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  872. match states.entry(std::sync::Arc::as_ptr(&copy) as usize) {
  873. std::collections::hash_map::Entry::Vacant(v) => {
  874. v.insert((wanted, wanted, copy));
  875. None
  876. }
  877. std::collections::hash_map::Entry::Occupied(mut o) => {
  878. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  879. (before != wanted).then_some((texture, before))
  880. }
  881. }
  882. }
  883. /// At submission: the list that moves each texture this list uses from
  884. /// its real state to the one the list starts with; the textures' real
  885. /// states become those the list ends with.
  886. fn prelude(&self) -> Option<ID3D12CommandList> {
  887. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  888. let barriers: Vec<D3D12_RESOURCE_BARRIER> = states
  889. .values()
  890. .filter_map(|(first, last, copy)| {
  891. let real = copy.state.swap(*last, Ordering::Relaxed);
  892. (real != *first).then(|| {
  893. transition(
  894. &copy.texture,
  895. D3D12_RESOURCE_STATES(real as i32),
  896. D3D12_RESOURCE_STATES(*first as i32),
  897. )
  898. })
  899. })
  900. .collect();
  901. if barriers.is_empty() {
  902. return None;
  903. }
  904. let (allocator, list) = &self.prelude;
  905. // SAFETY: the prelude is not executing (every submission is waited
  906. // for); the textures are live.
  907. let recorded = unsafe {
  908. allocator.Reset().and_then(|()| {
  909. list.Reset(allocator, None)?;
  910. list.ResourceBarrier(&barriers);
  911. list.Close()
  912. })
  913. };
  914. if let Err(e) = recorded {
  915. fail(format_args!("a host state prelude did not record ({e})"));
  916. }
  917. list.cast().ok()
  918. }
  919. /// Notes what the command about to be recorded does, as a marker
  920. /// command whose text the list keeps (diagnostics, with device-removed
  921. /// data on): the report pairs the breadcrumbs' marker commands with the
  922. /// texts in order and names the commands a fault stopped among.
  923. #[cfg(feature = "diagnostics")]
  924. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  925. self.note(what, None);
  926. }
  927. /// As [`HostList::note_op`], for a copy that reads the host GPU range
  928. /// `(address, bytes)`: the report places the faulting address in it.
  929. #[cfg(feature = "diagnostics")]
  930. pub(crate) fn note_read(&self, what: impl FnOnce() -> String, range: (u64, u64)) {
  931. self.note(what, Some(range));
  932. }
  933. #[cfg(feature = "diagnostics")]
  934. fn note(&self, what: impl FnOnce() -> String, range: Option<(u64, u64)>) {
  935. if dred_on() {
  936. let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32;
  937. if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 {
  938. // SAFETY: an open list and our query heap.
  939. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) };
  940. }
  941. let what = what();
  942. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  943. const UNICODE: u32 = 0;
  944. // SAFETY: an open list; the marker is copied when recorded.
  945. unsafe {
  946. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  947. };
  948. self.notes
  949. .lock()
  950. .unwrap_or_else(|e| e.into_inner())
  951. .push((what, range));
  952. }
  953. }
  954. /// Notes a pipeline the list binds.
  955. pub(crate) fn used_pipeline(&self, name: &str) {
  956. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  957. if !pipelines.contains(name) {
  958. pipelines.insert(name.to_owned());
  959. }
  960. }
  961. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  962. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  963. }
  964. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  965. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  966. let mut deferred = self.deferred();
  967. deferred
  968. .copies
  969. .push(Step::Copy(dst as usize, src as usize, len));
  970. deferred.refreshed.clear();
  971. }
  972. /// Copies `len` bytes of title memory at `src` into the list's upload
  973. /// memory at `dst` when the list is submitted.
  974. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  975. self.deferred()
  976. .copies
  977. .push(Step::Fill(dst as usize, src as usize, len));
  978. }
  979. /// Brings `[address, address + len)` of a buffer's host copy up to date
  980. /// when the list is submitted (once per range until a title copy
  981. /// intervenes), keeping the copy alive until the list is reset.
  982. pub(crate) fn defer_refresh(
  983. &self,
  984. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  985. address: usize,
  986. len: usize,
  987. ) {
  988. let mut deferred = self.deferred();
  989. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  990. if deferred.refreshed.insert(key) {
  991. deferred
  992. .copies
  993. .push(Step::Refresh(shadow.clone(), address, len));
  994. }
  995. }
  996. /// Shaders of the list write `[address, address + len)` of a buffer's
  997. /// host copy: copied back into title memory once the list has run.
  998. pub(crate) fn defer_gpu_write(
  999. &self,
  1000. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  1001. address: usize,
  1002. len: usize,
  1003. ) {
  1004. self.deferred()
  1005. .copies
  1006. .push(Step::GpuWrite(shadow.clone(), address, len));
  1007. }
  1008. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  1009. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  1010. self.deferred().writes.push((dst as usize, what, bytes));
  1011. }
  1012. /// A mapped upload buffer of `size` bytes, alive until the list is
  1013. /// reset.
  1014. ///
  1015. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  1016. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  1017. let (buffer, data) = host.upload_buffer(size)?;
  1018. name(&buffer, || format!("list upload {size:#x}"));
  1019. self.deferred().uploads.push(buffer.clone());
  1020. Some((buffer, data))
  1021. }
  1022. /// `len` bytes of upload memory (256-byte aligned) until the list is
  1023. /// reset: the host GPU address and the CPU pointer.
  1024. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  1025. let host = host()?;
  1026. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  1027. let len = len.max(1).next_multiple_of(256);
  1028. if len > SCRATCH_CHUNK {
  1029. let (buffer, data) = host.upload_buffer(len)?;
  1030. name(&buffer, || format!("list scratch {len:#x}"));
  1031. // SAFETY: a live buffer.
  1032. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1033. self.deferred().uploads.push(buffer);
  1034. return Some((gpu, data));
  1035. }
  1036. if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() {
  1037. (s.current, s.used) = (s.current + 1, 0);
  1038. }
  1039. if s.current == s.chunks.len() {
  1040. let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?;
  1041. name(&buffer, || "list scratch".into());
  1042. // SAFETY: a live buffer.
  1043. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  1044. s.chunks.push((buffer, data as usize, gpu));
  1045. s.used = 0;
  1046. }
  1047. let (_, data, gpu) = s.chunks[s.current];
  1048. let at = s.used;
  1049. s.used += len;
  1050. Some((gpu + at, (data + at as usize) as *mut u8))
  1051. }
  1052. /// The host address of the list's indirect-work budget, zeroed at each
  1053. /// submission of the list from the first use after a reset on.
  1054. pub(crate) fn budget(&self) -> Option<u64> {
  1055. let (buffer, data) = self
  1056. .budget
  1057. .get_or_init(|| {
  1058. let (b, d) = host()?.shared_buffer(256)?;
  1059. Some((b, d as usize))
  1060. })
  1061. .as_ref()?;
  1062. let mut deferred = self.deferred();
  1063. if !deferred.budget_zeroed {
  1064. deferred.budget_zeroed = true;
  1065. let at = *data;
  1066. // SAFETY: the list's own mapped word, written before it runs.
  1067. deferred
  1068. .copies
  1069. .push(Step::Host(Box::new(move || unsafe { (at as *mut u32).write_volatile(0) })));
  1070. }
  1071. // SAFETY: a live buffer.
  1072. Some(unsafe { buffer.GetGPUVirtualAddress() })
  1073. }
  1074. /// Keeps `object` alive until the list is reset.
  1075. pub(crate) fn keep(&self, object: &impl Interface) {
  1076. if let Ok(object) = object.cast::<windows::core::IUnknown>() {
  1077. self.deferred().kept.push(object);
  1078. }
  1079. }
  1080. /// Whether this is the first time since the reset that the list asks
  1081. /// about `key` (a texture to bring up to date).
  1082. pub(crate) fn first_use(&self, key: usize) -> bool {
  1083. self.deferred().textures.insert(key)
  1084. }
  1085. /// Runs `work` when the list is submitted, in order with its copies.
  1086. /// `work` may write title memory (refreshes after it copy again).
  1087. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  1088. self.deferred().copies.push(Step::Run(Box::new(work)));
  1089. self.deferred().refreshed.clear();
  1090. }
  1091. /// As [`HostList::defer`], for work that writes only host memory.
  1092. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  1093. self.deferred().copies.push(Step::Host(Box::new(work)));
  1094. }
  1095. /// Brings a texture's staging buffer up to date when the list is
  1096. /// submitted, keeping it alive until the list is reset.
  1097. pub(crate) fn defer_texture(&self, staging: std::sync::Arc<crate::texture::Staging>) {
  1098. self.deferred().copies.push(Step::Texture(staging));
  1099. }
  1100. /// Runs the list's submission-time steps; refreshes go into `batch`
  1101. /// (the title's big buffers, a 174 MB one among them, are read by most
  1102. /// lists of a submission, through many ranges).
  1103. fn run_deferred(&self, batch: &mut Batch) {
  1104. #[cfg(feature = "diagnostics")]
  1105. use crate::copystat::{C, add};
  1106. for step in &self.deferred().copies {
  1107. let started = std::time::Instant::now();
  1108. let copied = match step {
  1109. &Step::Copy(dst, src, len) => {
  1110. #[cfg(feature = "diagnostics")]
  1111. {
  1112. add(C::Copies, 1);
  1113. add(C::CopyBytes, len as u64);
  1114. }
  1115. batch.title_written();
  1116. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  1117. len
  1118. }
  1119. &Step::Fill(dst, src, len) => {
  1120. #[cfg(feature = "diagnostics")]
  1121. {
  1122. add(C::Copies, 1);
  1123. add(C::CopyBytes, len as u64);
  1124. }
  1125. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  1126. len
  1127. }
  1128. Step::Refresh(shadow, address, len) => {
  1129. #[cfg(feature = "diagnostics")]
  1130. {
  1131. add(C::Refreshes, 1);
  1132. add(C::RefreshBytes, *len as u64);
  1133. }
  1134. batch.add(shadow, *address, *len);
  1135. continue;
  1136. }
  1137. Step::Run(work) | Step::Host(work) => {
  1138. if matches!(step, Step::Run(_)) {
  1139. batch.title_written();
  1140. }
  1141. work();
  1142. #[cfg(feature = "diagnostics")]
  1143. {
  1144. add(C::Runs, 1);
  1145. add(C::RunUs, started.elapsed().as_micros() as u64);
  1146. }
  1147. continue;
  1148. }
  1149. Step::GpuWrite(shadow, address, len) => {
  1150. // The shaders start from the title's data.
  1151. batch.flush();
  1152. shadow.writing(*address, *len);
  1153. continue;
  1154. }
  1155. Step::Texture(staging) => {
  1156. if batch.texture_due(staging) {
  1157. staging.refresh();
  1158. }
  1159. continue;
  1160. }
  1161. };
  1162. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  1163. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  1164. }
  1165. }
  1166. }
  1167. /// A submission's refreshes not done yet, merged per buffer copy into the
  1168. /// range that covers them: done before a step that writes title memory or
  1169. /// gives a range to shaders, and before the lists run.
  1170. ///
  1171. /// Also the textures brought up to date in the submission so far: most
  1172. /// lists of a world submission sample the same textures, and a texture in
  1173. /// physical-page memory is hashed whole each time it is checked. Checked
  1174. /// once, it is checked again only after a step that writes title memory.
  1175. #[derive(Default)]
  1176. struct Batch {
  1177. refreshes: Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>,
  1178. /// Staging buffers (by address) refreshed since the last title write.
  1179. textures: std::collections::HashSet<usize>,
  1180. }
  1181. impl Batch {
  1182. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  1183. let end = address + len;
  1184. match self
  1185. .refreshes
  1186. .iter_mut()
  1187. .find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow))
  1188. {
  1189. Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)),
  1190. None => self.refreshes.push((shadow.clone(), address, end)),
  1191. }
  1192. }
  1193. /// Whether `staging` is still to be refreshed in this submission (and
  1194. /// notes it refreshed).
  1195. fn texture_due<T>(&mut self, staging: &std::sync::Arc<T>) -> bool {
  1196. self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize)
  1197. }
  1198. /// Before a step that writes title memory: pending refreshes are done
  1199. /// first, and textures are checked again after it.
  1200. fn title_written(&mut self) {
  1201. self.flush();
  1202. self.textures.clear();
  1203. }
  1204. fn flush(&mut self) {
  1205. for (shadow, from, to) in self.refreshes.drain(..) {
  1206. let started = std::time::Instant::now();
  1207. let copied = shadow.update(from, to - from);
  1208. let us = started.elapsed().as_micros() as u64;
  1209. #[cfg(feature = "diagnostics")]
  1210. crate::copystat::range(from, to - from, us, 0);
  1211. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  1212. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  1213. }
  1214. }
  1215. }
  1216. /// Copies title memory at submission. The ranges were checked against their
  1217. /// resources when recorded, but the title may since have unmapped pages of
  1218. /// them (tiled memory, page mappings), which read as zeros here; a title
  1219. /// destination (`title_dst`) that is not all mapped is left alone.
  1220. ///
  1221. /// The source is read through the kernel (`ReadProcessMemory`), which
  1222. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  1223. /// cost about 2 ms per copy in the title's big pools (it walks the page
  1224. /// tables to the region's end), which made copies run at 100-200 MB/s.
  1225. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  1226. #[cfg(feature = "diagnostics")]
  1227. match crate::copystat::mode() {
  1228. 1 => {
  1229. // SAFETY: timing only: the caller vouches for the source.
  1230. unsafe { std::ptr::copy(src, dst, len) };
  1231. return;
  1232. }
  1233. 2 => return,
  1234. _ => {}
  1235. }
  1236. if len == 0 || title_dst && !crate::texture::committed(dst, len) {
  1237. return;
  1238. }
  1239. if title_dst {
  1240. // The kernel writes the destination: it must not be guarded.
  1241. crate::watch::writing(dst as usize, len);
  1242. }
  1243. #[cfg(feature = "diagnostics")]
  1244. let moved = std::time::Instant::now();
  1245. let whole = read(src, dst, len);
  1246. #[cfg(feature = "diagnostics")]
  1247. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  1248. if whole {
  1249. return;
  1250. }
  1251. #[cfg(feature = "diagnostics")]
  1252. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  1253. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  1254. // that fails), zeros for what cannot be read.
  1255. for_pieces(src as usize, len, 64 << 10, |at, n| {
  1256. let to = dst.wrapping_add(at - src as usize);
  1257. if !read(at as *const u8, to, n) {
  1258. for_pieces(at, n, 4 << 10, |at, n| {
  1259. let to = dst.wrapping_add(at - src as usize);
  1260. if !read(at as *const u8, to, n) {
  1261. #[cfg(feature = "diagnostics")]
  1262. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  1263. // SAFETY: inside the destination, which is mapped.
  1264. unsafe { to.write_bytes(0, n) };
  1265. }
  1266. });
  1267. }
  1268. });
  1269. }
  1270. /// Reads title memory at `src` into `dst`; false if a page of it is not
  1271. /// readable.
  1272. pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
  1273. read(src, dst.as_mut_ptr(), dst.len())
  1274. }
  1275. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  1276. /// readable.
  1277. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  1278. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  1279. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  1280. let mut done = 0;
  1281. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  1282. // kernel checks the source.
  1283. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  1284. }
  1285. /// Copies host memory into title memory after a submission (what shaders
  1286. /// wrote), leaving pages that are not mapped alone.
  1287. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  1288. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  1289. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  1290. let write = |at: usize, n: usize| {
  1291. let from = src.wrapping_add(at - dst as usize);
  1292. let mut done = 0;
  1293. // SAFETY: the source is our mapped host copy; the kernel checks the
  1294. // destination.
  1295. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  1296. };
  1297. if len == 0 || write(dst as usize, len) {
  1298. return;
  1299. }
  1300. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  1301. if !write(at, n) {
  1302. for_pieces(at, n, 4 << 10, |at, n| {
  1303. write(at, n);
  1304. });
  1305. }
  1306. });
  1307. }
  1308. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  1309. /// `step`.
  1310. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  1311. let end = start + len;
  1312. let mut at = start;
  1313. while at < end {
  1314. let next = ((at / step + 1) * step).min(end);
  1315. f(at, next - at);
  1316. at = next;
  1317. }
  1318. }
  1319. impl Host {
  1320. /// A buffer in the upload heap, mapped for writing.
  1321. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  1322. let heap = D3D12_HEAP_PROPERTIES {
  1323. Type: D3D12_HEAP_TYPE_UPLOAD,
  1324. ..Default::default()
  1325. };
  1326. let desc = D3D12_RESOURCE_DESC {
  1327. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1328. Width: size.max(1),
  1329. Height: 1,
  1330. DepthOrArraySize: 1,
  1331. MipLevels: 1,
  1332. SampleDesc: DXGI_SAMPLE_DESC {
  1333. Count: 1,
  1334. Quality: 0,
  1335. },
  1336. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1337. ..Default::default()
  1338. };
  1339. let mut buffer: Option<ID3D12Resource> = None;
  1340. let mut data = std::ptr::null_mut();
  1341. // SAFETY: plain creation and mapping of an upload buffer.
  1342. let made = unsafe {
  1343. self.device
  1344. .CreateCommittedResource(
  1345. &heap,
  1346. D3D12_HEAP_FLAG_NONE,
  1347. &desc,
  1348. D3D12_RESOURCE_STATE_GENERIC_READ,
  1349. None,
  1350. &mut buffer,
  1351. )
  1352. .and_then(|()| {
  1353. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  1354. b.Map(0, None, Some(&mut data))
  1355. })
  1356. };
  1357. match made {
  1358. Ok(()) => Some((buffer?, data.cast())),
  1359. Err(e) => {
  1360. tracing::warn!(error = %e, size, "no upload buffer");
  1361. None
  1362. }
  1363. }
  1364. }
  1365. }
  1366. /// The swap chain formats a presented texture can be copied into: its own
  1367. /// family's.
  1368. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  1369. Some(match format.0 {
  1370. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  1371. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  1372. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  1373. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  1374. _ => return None,
  1375. })
  1376. }
  1377. const BUFFERS: u32 = 2;
  1378. struct Presenter {
  1379. swap_chain: IDXGISwapChain3,
  1380. width: u32,
  1381. height: u32,
  1382. format: DXGI_FORMAT,
  1383. copy: HostList,
  1384. hwnd: HWND,
  1385. meter: Meter,
  1386. }
  1387. /// The frame rate, shown in the window's caption every second and logged
  1388. /// every few seconds.
  1389. struct Meter {
  1390. since: std::time::Instant,
  1391. frames: u32,
  1392. #[cfg(feature = "diagnostics")]
  1393. copy_stats_frames: u64,
  1394. drawn: u64,
  1395. logged: std::time::Instant,
  1396. /// The caption the window had, once read.
  1397. caption: Option<Vec<u16>>,
  1398. }
  1399. impl Meter {
  1400. fn new() -> Self {
  1401. let now = std::time::Instant::now();
  1402. Meter {
  1403. since: now,
  1404. frames: 0,
  1405. #[cfg(feature = "diagnostics")]
  1406. copy_stats_frames: 0,
  1407. drawn: crate::draw::drawn(),
  1408. logged: now,
  1409. caption: None,
  1410. }
  1411. }
  1412. /// Counts a presented frame.
  1413. fn frame(&mut self, hwnd: HWND) {
  1414. #[cfg(feature = "diagnostics")]
  1415. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  1416. self.frames += 1;
  1417. #[cfg(feature = "diagnostics")]
  1418. {
  1419. self.copy_stats_frames += 1;
  1420. }
  1421. let elapsed = self.since.elapsed();
  1422. if elapsed < std::time::Duration::from_secs(1) {
  1423. return;
  1424. }
  1425. let drawn = crate::draw::drawn();
  1426. let frames = f64::from(self.frames);
  1427. let fps = frames / elapsed.as_secs_f64();
  1428. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  1429. let draws = (drawn - self.drawn) as f64 / frames;
  1430. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  1431. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  1432. let [cpu, gpu] = [0, 1].map(|i| {
  1433. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  1434. });
  1435. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  1436. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  1437. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  1438. });
  1439. let [back_ms, back_mb] = [0, 1].map(|i| {
  1440. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  1441. });
  1442. let dropped = crate::draw::take_dropped() as f64 / frames;
  1443. let indirect = crate::list::take_indirect() as f64 / frames;
  1444. // Over the same frames as the counts above.
  1445. #[cfg(feature = "diagnostics")]
  1446. let drops = crate::pipeline::take_drops();
  1447. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  1448. self.logged = std::time::Instant::now();
  1449. tracing::info!(
  1450. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  1451. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  1452. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  1453. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  1454. {indirect:.0} indirect",
  1455. making = crate::pipeline::making()
  1456. );
  1457. #[cfg(feature = "diagnostics")]
  1458. {
  1459. crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
  1460. for (why, n) in drops.iter().take(40) {
  1461. tracing::info!(
  1462. "dropped {:.1}/frame without a host pipeline: {why}",
  1463. *n as f64 / frames
  1464. );
  1465. }
  1466. }
  1467. }
  1468. if self.caption.is_none() {
  1469. // The window's own text, read without a message.
  1470. let mut buffer = vec![0u16; 512];
  1471. // SAFETY: a window handle and a buffer of that length.
  1472. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  1473. buffer.truncate(n.max(0) as usize);
  1474. self.caption = Some(buffer);
  1475. }
  1476. let Some(caption) = &self.caption else { return };
  1477. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  1478. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  1479. text.push(0);
  1480. // Setting the text waits for the window's thread (a title thread,
  1481. // which may not pump for a while), so a thread of ours does it and
  1482. // presenting never waits; it takes the newest text when free.
  1483. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  1484. static SETTER: std::sync::Once = std::sync::Once::new();
  1485. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  1486. SETTER.call_once(|| {
  1487. let _ = std::thread::Builder::new()
  1488. .name("victory-caption".into())
  1489. .spawn(|| {
  1490. loop {
  1491. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  1492. match next {
  1493. // SAFETY: a window handle and a NUL-terminated text.
  1494. Some((hwnd, text)) => unsafe {
  1495. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  1496. },
  1497. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  1498. }
  1499. }
  1500. });
  1501. });
  1502. }
  1503. }
  1504. impl Host {
  1505. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  1506. /// as frame `frame` (saved if captures are on). `None` if nothing was
  1507. /// shown; else, in diagnostics builds, whether the frame was black.
  1508. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  1509. // SAFETY: a live resource.
  1510. let desc = unsafe { texture.GetDesc() };
  1511. let Some(format) = swap_format(desc.Format) else {
  1512. tracing::warn!(format = desc.Format.0, "cannot present this format");
  1513. return None;
  1514. };
  1515. let (width, height) = (desc.Width as u32, desc.Height);
  1516. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  1517. if presenter.is_none() {
  1518. *presenter = match self.presenter(width, height, format) {
  1519. Ok(p) => Some(p),
  1520. Err(e) => {
  1521. tracing::warn!(error = %e, "no swap chain");
  1522. return None;
  1523. }
  1524. };
  1525. }
  1526. let p = presenter.as_mut()?;
  1527. if (p.width, p.height, p.format) != (width, height, format) {
  1528. // SAFETY: no back buffer is held; every submission was waited for.
  1529. let resized = unsafe {
  1530. p.swap_chain
  1531. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  1532. };
  1533. match resized {
  1534. Ok(()) => (p.width, p.height, p.format) = (width, height, format),
  1535. Err(e) => {
  1536. tracing::warn!(error = %e, width, height, "swap chain not resized");
  1537. return None;
  1538. }
  1539. }
  1540. }
  1541. let state = D3D12_RESOURCE_STATES(state as i32);
  1542. // SAFETY: our swap chain, list and a live source texture.
  1543. unsafe {
  1544. let index = p.swap_chain.GetCurrentBackBufferIndex();
  1545. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  1546. return None;
  1547. };
  1548. p.copy.reset();
  1549. let list = &p.copy.list;
  1550. list.ResourceBarrier(&[
  1551. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  1552. transition(
  1553. &back,
  1554. D3D12_RESOURCE_STATE_PRESENT,
  1555. D3D12_RESOURCE_STATE_COPY_DEST,
  1556. ),
  1557. ]);
  1558. list.CopyResource(&back, texture);
  1559. #[cfg(feature = "diagnostics")]
  1560. let capture = crate::capture::wanted(frame)
  1561. .then(|| crate::capture::read_back(&self.device, list, texture))
  1562. .flatten();
  1563. #[cfg(feature = "diagnostics")]
  1564. let probe = crate::capture::probe(&self.device, list, texture);
  1565. #[cfg(not(feature = "diagnostics"))]
  1566. let _ = frame;
  1567. list.ResourceBarrier(&[
  1568. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  1569. transition(
  1570. &back,
  1571. D3D12_RESOURCE_STATE_COPY_DEST,
  1572. D3D12_RESOURCE_STATE_PRESENT,
  1573. ),
  1574. ]);
  1575. p.copy.close();
  1576. self.execute(&[&p.copy]);
  1577. #[cfg(feature = "diagnostics")]
  1578. if let Some((buffer, footprint)) = capture {
  1579. crate::capture::save_read_back(frame, &buffer, &footprint);
  1580. }
  1581. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  1582. p.meter.frame(p.hwnd);
  1583. #[cfg(feature = "diagnostics")]
  1584. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  1585. #[cfg(not(feature = "diagnostics"))]
  1586. Some(false)
  1587. }
  1588. }
  1589. fn presenter(
  1590. &self,
  1591. width: u32,
  1592. height: u32,
  1593. format: DXGI_FORMAT,
  1594. ) -> windows::core::Result<Presenter> {
  1595. let hwnd = match title_window() {
  1596. Some(hwnd) => hwnd,
  1597. None => window(width, height)?,
  1598. };
  1599. // SAFETY: plain object creation for our window.
  1600. unsafe {
  1601. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  1602. let desc = DXGI_SWAP_CHAIN_DESC1 {
  1603. Width: width,
  1604. Height: height,
  1605. Format: format,
  1606. SampleDesc: DXGI_SAMPLE_DESC {
  1607. Count: 1,
  1608. Quality: 0,
  1609. },
  1610. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  1611. BufferCount: BUFFERS,
  1612. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  1613. ..Default::default()
  1614. };
  1615. let swap_chain = factory
  1616. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  1617. .cast::<IDXGISwapChain3>()?;
  1618. let copy = self.new_list()?;
  1619. copy.close();
  1620. tracing::info!(width, height, format = format.0, "presenting to a window");
  1621. Ok(Presenter {
  1622. swap_chain,
  1623. width,
  1624. height,
  1625. format,
  1626. copy,
  1627. hwnd,
  1628. meter: Meter::new(),
  1629. })
  1630. }
  1631. }
  1632. }
  1633. /// A visible top-level window of this process: the one the title made, if
  1634. /// it made one.
  1635. fn title_window() -> Option<HWND> {
  1636. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  1637. let mut process = 0;
  1638. // SAFETY: a window handle from the enumeration; `found` is ours.
  1639. unsafe {
  1640. GetWindowThreadProcessId(hwnd, Some(&mut process));
  1641. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  1642. && IsWindowVisible(hwnd).as_bool()
  1643. {
  1644. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  1645. return false.into();
  1646. }
  1647. }
  1648. true.into()
  1649. }
  1650. let mut found: Option<HWND> = None;
  1651. // SAFETY: the callback only writes `found`, which outlives the call.
  1652. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  1653. found
  1654. }
  1655. /// `state` without the bits the host texture's flags forbid: the console
  1656. /// lets the title name states its own resources allow (unordered access on
  1657. /// a depth target, whose host copy cannot have both).
  1658. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  1659. // SAFETY: a plain query.
  1660. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  1661. }
  1662. /// [`legal_state`] for a texture with resource flags `flags`.
  1663. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  1664. // (flag, set or clear forbids, state bits): render target, unordered
  1665. // access, depth, denied shader resource.
  1666. const FORBIDDEN: [(u32, bool, u32); 4] = [
  1667. (0x1, false, 0x4),
  1668. (0x4, false, 0x8),
  1669. (0x2, false, 0x10 | 0x20),
  1670. (0x8, true, 0x40 | 0x80),
  1671. ];
  1672. FORBIDDEN
  1673. .iter()
  1674. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  1675. .fold(state, |s, &(_, _, bits)| s & !bits)
  1676. }
  1677. impl Host {
  1678. /// A buffer in system memory that the CPU maps (write-back, so reading
  1679. /// it is fast too) and shaders read and write: for host copies of title
  1680. /// memory that shaders write, which upload memory cannot be. Starts in
  1681. /// the common state (buffers move out of it implicitly).
  1682. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  1683. let heap = D3D12_HEAP_PROPERTIES {
  1684. Type: D3D12_HEAP_TYPE_CUSTOM,
  1685. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  1686. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  1687. ..Default::default()
  1688. };
  1689. let desc = D3D12_RESOURCE_DESC {
  1690. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1691. Width: size.max(1),
  1692. Height: 1,
  1693. DepthOrArraySize: 1,
  1694. MipLevels: 1,
  1695. SampleDesc: DXGI_SAMPLE_DESC {
  1696. Count: 1,
  1697. Quality: 0,
  1698. },
  1699. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1700. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  1701. ..Default::default()
  1702. };
  1703. let mut buffer: Option<ID3D12Resource> = None;
  1704. let mut data = std::ptr::null_mut();
  1705. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  1706. let made = unsafe {
  1707. self.device
  1708. .CreateCommittedResource(
  1709. &heap,
  1710. D3D12_HEAP_FLAG_NONE,
  1711. &desc,
  1712. D3D12_RESOURCE_STATE_COMMON,
  1713. None,
  1714. &mut buffer,
  1715. )
  1716. .and_then(|()| {
  1717. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  1718. b.Map(0, None, Some(&mut data))
  1719. })
  1720. };
  1721. match made {
  1722. Ok(()) => Some((buffer?, data.cast())),
  1723. Err(e) => {
  1724. tracing::warn!(error = %e, size, "no shared buffer");
  1725. None
  1726. }
  1727. }
  1728. }
  1729. }
  1730. /// For adapters without device-removed data (the software one): the last
  1731. /// commands each list of the failed submission noted (diagnostics, with
  1732. /// `VICTORY_D3D12_DRED`).
  1733. fn last_notes(runs: &[&HostList]) -> String {
  1734. #[cfg(feature = "diagnostics")]
  1735. {
  1736. let mut text = String::new();
  1737. for (i, r) in runs.iter().enumerate() {
  1738. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  1739. for (n, _) in notes.iter().rev().take(6).rev() {
  1740. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  1741. }
  1742. }
  1743. text
  1744. }
  1745. #[cfg(not(feature = "diagnostics"))]
  1746. {
  1747. let _ = runs;
  1748. String::new()
  1749. }
  1750. }
  1751. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  1752. /// command reads (diagnostics).
  1753. #[cfg(feature = "diagnostics")]
  1754. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  1755. let end = start + bytes;
  1756. if va < start {
  1757. format!(" (fault {:#x} below its source)", start - va)
  1758. } else if va < end {
  1759. format!(" (fault at source +{:#x})", va - start)
  1760. } else {
  1761. format!(" (fault {:#x} past its source's end)", va - end)
  1762. }
  1763. }
  1764. /// The commands that may have been running where a list stopped at
  1765. /// command `done`: those between the barriers around it (work between
  1766. /// barriers overlaps on the GPU), by kind, and what the markers just
  1767. /// before them say (`HostList::note_op`: diagnostics builds with
  1768. /// device-removed data on).
  1769. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  1770. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  1771. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  1772. let to = history[done..]
  1773. .iter()
  1774. .position(barrier)
  1775. .map_or(history.len(), |b| (done + b).max(done + 1));
  1776. let mut text = format!(", commands {from}..{to} between its barriers:");
  1777. let mut shown = 0;
  1778. for i in from..to {
  1779. let op = history[i];
  1780. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  1781. continue;
  1782. }
  1783. shown += 1;
  1784. let marker = i
  1785. .checked_sub(1)
  1786. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  1787. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  1788. .map_or("no marker", |(_, s)| s.as_str());
  1789. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  1790. }
  1791. text
  1792. }
  1793. pub(crate) fn transition(
  1794. resource: &ID3D12Resource,
  1795. before: D3D12_RESOURCE_STATES,
  1796. after: D3D12_RESOURCE_STATES,
  1797. ) -> D3D12_RESOURCE_BARRIER {
  1798. D3D12_RESOURCE_BARRIER {
  1799. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  1800. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  1801. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  1802. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  1803. // SAFETY: a borrowed pointer; the barrier never releases it.
  1804. pResource: unsafe { std::mem::transmute_copy(resource) },
  1805. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  1806. StateBefore: before,
  1807. StateAfter: after,
  1808. }),
  1809. },
  1810. }
  1811. }
  1812. /// A window of the given client size, owned by its own message thread.
  1813. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  1814. let (sender, receiver) = std::sync::mpsc::channel();
  1815. std::thread::Builder::new()
  1816. .name("victory-window".into())
  1817. .spawn(move || {
  1818. let made = make_window(width, height);
  1819. let ok = made.is_ok();
  1820. let _ = sender.send(made.map(|h| h.0 as usize));
  1821. if ok {
  1822. pump();
  1823. }
  1824. })
  1825. .map_err(|_| windows::core::Error::empty())?;
  1826. let hwnd = receiver
  1827. .recv()
  1828. .map_err(|_| windows::core::Error::empty())??;
  1829. Ok(HWND(hwnd as *mut _))
  1830. }
  1831. extern "system" fn window_proc(
  1832. hwnd: HWND,
  1833. message: u32,
  1834. wparam: WPARAM,
  1835. lparam: LPARAM,
  1836. ) -> LRESULT {
  1837. // SAFETY: the default handling for our window.
  1838. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  1839. }
  1840. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  1841. const CLASS: PCWSTR = w!("VIctory");
  1842. // SAFETY: registers our class once and creates a window of it.
  1843. unsafe {
  1844. let instance = GetModuleHandleW(None)?;
  1845. let class = WNDCLASSEXW {
  1846. cbSize: size_of::<WNDCLASSEXW>() as u32,
  1847. lpfnWndProc: Some(window_proc),
  1848. hInstance: instance.into(),
  1849. lpszClassName: CLASS,
  1850. hCursor: LoadCursorW(None, IDC_ARROW)?,
  1851. ..Default::default()
  1852. };
  1853. RegisterClassExW(&class);
  1854. let mut rect = RECT {
  1855. left: 0,
  1856. top: 0,
  1857. right: width as i32,
  1858. bottom: height as i32,
  1859. };
  1860. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  1861. CreateWindowExW(
  1862. WINDOW_EX_STYLE(0),
  1863. CLASS,
  1864. w!("VIctory"),
  1865. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  1866. CW_USEDEFAULT,
  1867. CW_USEDEFAULT,
  1868. rect.right - rect.left,
  1869. rect.bottom - rect.top,
  1870. None,
  1871. None,
  1872. Some(instance.into()),
  1873. None,
  1874. )
  1875. }
  1876. }
  1877. fn pump() {
  1878. let mut message = MSG::default();
  1879. // SAFETY: the standard message loop of this thread's window.
  1880. unsafe {
  1881. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  1882. let _ = TranslateMessage(&message);
  1883. DispatchMessageW(&message);
  1884. }
  1885. }
  1886. }
  1887. #[cfg(test)]
  1888. mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file
  1889. use super::Batch;
  1890. use std::sync::Arc;
  1891. #[test]
  1892. fn a_texture_is_checked_once_per_submission() {
  1893. let mut batch = Batch::default();
  1894. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  1895. // The first list sampling each texture checks it ...
  1896. assert!(batch.texture_due(&a));
  1897. assert!(batch.texture_due(&b));
  1898. // ... later lists of the same submission do not.
  1899. assert!(!batch.texture_due(&a));
  1900. assert!(!batch.texture_due(&a.clone()));
  1901. assert!(!batch.texture_due(&b));
  1902. }
  1903. #[test]
  1904. fn title_writes_make_textures_due_again() {
  1905. let mut batch = Batch::default();
  1906. let a = Arc::new(1u32);
  1907. assert!(batch.texture_due(&a));
  1908. assert!(!batch.texture_due(&a));
  1909. // A copy into title memory or work that may write it may have
  1910. // changed the texture's memory.
  1911. batch.title_written();
  1912. assert!(batch.texture_due(&a));
  1913. assert!(!batch.texture_due(&a));
  1914. // A fresh submission starts over.
  1915. let mut next = Batch::default();
  1916. assert!(next.texture_due(&a));
  1917. }
  1918. /// The hashing a submission does for textures in physical-page memory,
  1919. /// with every list checking the textures it samples (before) and with
  1920. /// each checked once (after). Run with
  1921. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  1922. #[test]
  1923. #[ignore = "benchmark"]
  1924. fn texture_checks_per_submission() {
  1925. const TEXTURES: usize = 48;
  1926. const SIZE: usize = 4 << 20;
  1927. const LISTS: usize = 12;
  1928. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  1929. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  1930. .collect();
  1931. let submit = |dedupe: bool| {
  1932. let mut batch = Batch::default();
  1933. let mut hashed = 0usize;
  1934. let started = std::time::Instant::now();
  1935. for _ in 0..LISTS {
  1936. for t in &textures {
  1937. if !dedupe || batch.texture_due(t) {
  1938. std::hint::black_box(blake3::hash(t));
  1939. hashed += 1;
  1940. }
  1941. }
  1942. }
  1943. (started.elapsed(), hashed)
  1944. };
  1945. submit(false); // warm up
  1946. let (before, n_before) = submit(false);
  1947. let (after, n_after) = submit(true);
  1948. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  1949. println!(
  1950. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  1951. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  1952. SIZE >> 20,
  1953. before.as_secs_f64() / after.as_secs_f64()
  1954. );
  1955. }
  1956. }