host.rs 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045
  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. drawn: u64,
  1393. logged: std::time::Instant,
  1394. /// The caption the window had, once read.
  1395. caption: Option<Vec<u16>>,
  1396. }
  1397. impl Meter {
  1398. fn new() -> Self {
  1399. let now = std::time::Instant::now();
  1400. Meter {
  1401. since: now,
  1402. frames: 0,
  1403. drawn: crate::draw::drawn(),
  1404. logged: now,
  1405. caption: None,
  1406. }
  1407. }
  1408. /// Counts a presented frame.
  1409. fn frame(&mut self, hwnd: HWND) {
  1410. #[cfg(feature = "diagnostics")]
  1411. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  1412. self.frames += 1;
  1413. let elapsed = self.since.elapsed();
  1414. if elapsed < std::time::Duration::from_secs(1) {
  1415. return;
  1416. }
  1417. let drawn = crate::draw::drawn();
  1418. let frames = f64::from(self.frames);
  1419. let fps = frames / elapsed.as_secs_f64();
  1420. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  1421. let draws = (drawn - self.drawn) as f64 / frames;
  1422. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  1423. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  1424. let [cpu, gpu] = [0, 1].map(|i| {
  1425. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  1426. });
  1427. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  1428. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  1429. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  1430. });
  1431. let [back_ms, back_mb] = [0, 1].map(|i| {
  1432. COPY_BACK[i].swap(0, Ordering::Relaxed) as f64 / [1e3, 1e6][i] / frames
  1433. });
  1434. let dropped = crate::draw::take_dropped() as f64 / frames;
  1435. let indirect = crate::list::take_indirect() as f64 / frames;
  1436. // Over the same frames as the counts above.
  1437. #[cfg(feature = "diagnostics")]
  1438. let drops = crate::pipeline::take_drops();
  1439. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  1440. self.logged = std::time::Instant::now();
  1441. tracing::info!(
  1442. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  1443. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  1444. GPU; {back_ms:.1} copying back {back_mb:.1} MB), {draws:.0} draws/frame, \
  1445. dropped {dropped:.0} without a host pipeline ({making} being made) and \
  1446. {indirect:.0} indirect",
  1447. making = crate::pipeline::making()
  1448. );
  1449. #[cfg(feature = "diagnostics")]
  1450. {
  1451. crate::copystat::log(frames);
  1452. for (why, n) in drops.iter().take(40) {
  1453. tracing::info!(
  1454. "dropped {:.1}/frame without a host pipeline: {why}",
  1455. *n as f64 / frames
  1456. );
  1457. }
  1458. }
  1459. }
  1460. if self.caption.is_none() {
  1461. // The window's own text, read without a message.
  1462. let mut buffer = vec![0u16; 512];
  1463. // SAFETY: a window handle and a buffer of that length.
  1464. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  1465. buffer.truncate(n.max(0) as usize);
  1466. self.caption = Some(buffer);
  1467. }
  1468. let Some(caption) = &self.caption else { return };
  1469. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  1470. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  1471. text.push(0);
  1472. // Setting the text waits for the window's thread (a title thread,
  1473. // which may not pump for a while), so a thread of ours does it and
  1474. // presenting never waits; it takes the newest text when free.
  1475. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  1476. static SETTER: std::sync::Once = std::sync::Once::new();
  1477. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  1478. SETTER.call_once(|| {
  1479. let _ = std::thread::Builder::new()
  1480. .name("victory-caption".into())
  1481. .spawn(|| {
  1482. loop {
  1483. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  1484. match next {
  1485. // SAFETY: a window handle and a NUL-terminated text.
  1486. Some((hwnd, text)) => unsafe {
  1487. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  1488. },
  1489. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  1490. }
  1491. }
  1492. });
  1493. });
  1494. }
  1495. }
  1496. impl Host {
  1497. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  1498. /// as frame `frame` (saved if captures are on). `None` if nothing was
  1499. /// shown; else, in diagnostics builds, whether the frame was black.
  1500. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  1501. // SAFETY: a live resource.
  1502. let desc = unsafe { texture.GetDesc() };
  1503. let Some(format) = swap_format(desc.Format) else {
  1504. tracing::warn!(format = desc.Format.0, "cannot present this format");
  1505. return None;
  1506. };
  1507. let (width, height) = (desc.Width as u32, desc.Height);
  1508. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  1509. if presenter.is_none() {
  1510. *presenter = match self.presenter(width, height, format) {
  1511. Ok(p) => Some(p),
  1512. Err(e) => {
  1513. tracing::warn!(error = %e, "no swap chain");
  1514. return None;
  1515. }
  1516. };
  1517. }
  1518. let p = presenter.as_mut()?;
  1519. if (p.width, p.height, p.format) != (width, height, format) {
  1520. // SAFETY: no back buffer is held; every submission was waited for.
  1521. let resized = unsafe {
  1522. p.swap_chain
  1523. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  1524. };
  1525. match resized {
  1526. Ok(()) => (p.width, p.height, p.format) = (width, height, format),
  1527. Err(e) => {
  1528. tracing::warn!(error = %e, width, height, "swap chain not resized");
  1529. return None;
  1530. }
  1531. }
  1532. }
  1533. let state = D3D12_RESOURCE_STATES(state as i32);
  1534. // SAFETY: our swap chain, list and a live source texture.
  1535. unsafe {
  1536. let index = p.swap_chain.GetCurrentBackBufferIndex();
  1537. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  1538. return None;
  1539. };
  1540. p.copy.reset();
  1541. let list = &p.copy.list;
  1542. list.ResourceBarrier(&[
  1543. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  1544. transition(
  1545. &back,
  1546. D3D12_RESOURCE_STATE_PRESENT,
  1547. D3D12_RESOURCE_STATE_COPY_DEST,
  1548. ),
  1549. ]);
  1550. list.CopyResource(&back, texture);
  1551. #[cfg(feature = "diagnostics")]
  1552. let capture = crate::capture::wanted(frame)
  1553. .then(|| crate::capture::read_back(&self.device, list, texture))
  1554. .flatten();
  1555. #[cfg(feature = "diagnostics")]
  1556. let probe = crate::capture::probe(&self.device, list, texture);
  1557. #[cfg(not(feature = "diagnostics"))]
  1558. let _ = frame;
  1559. list.ResourceBarrier(&[
  1560. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  1561. transition(
  1562. &back,
  1563. D3D12_RESOURCE_STATE_COPY_DEST,
  1564. D3D12_RESOURCE_STATE_PRESENT,
  1565. ),
  1566. ]);
  1567. p.copy.close();
  1568. self.execute(&[&p.copy]);
  1569. #[cfg(feature = "diagnostics")]
  1570. if let Some((buffer, footprint)) = capture {
  1571. crate::capture::save_read_back(frame, &buffer, &footprint);
  1572. }
  1573. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  1574. p.meter.frame(p.hwnd);
  1575. #[cfg(feature = "diagnostics")]
  1576. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  1577. #[cfg(not(feature = "diagnostics"))]
  1578. Some(false)
  1579. }
  1580. }
  1581. fn presenter(
  1582. &self,
  1583. width: u32,
  1584. height: u32,
  1585. format: DXGI_FORMAT,
  1586. ) -> windows::core::Result<Presenter> {
  1587. let hwnd = match title_window() {
  1588. Some(hwnd) => hwnd,
  1589. None => window(width, height)?,
  1590. };
  1591. // SAFETY: plain object creation for our window.
  1592. unsafe {
  1593. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  1594. let desc = DXGI_SWAP_CHAIN_DESC1 {
  1595. Width: width,
  1596. Height: height,
  1597. Format: format,
  1598. SampleDesc: DXGI_SAMPLE_DESC {
  1599. Count: 1,
  1600. Quality: 0,
  1601. },
  1602. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  1603. BufferCount: BUFFERS,
  1604. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  1605. ..Default::default()
  1606. };
  1607. let swap_chain = factory
  1608. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  1609. .cast::<IDXGISwapChain3>()?;
  1610. let copy = self.new_list()?;
  1611. copy.close();
  1612. tracing::info!(width, height, format = format.0, "presenting to a window");
  1613. Ok(Presenter {
  1614. swap_chain,
  1615. width,
  1616. height,
  1617. format,
  1618. copy,
  1619. hwnd,
  1620. meter: Meter::new(),
  1621. })
  1622. }
  1623. }
  1624. }
  1625. /// A visible top-level window of this process: the one the title made, if
  1626. /// it made one.
  1627. fn title_window() -> Option<HWND> {
  1628. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  1629. let mut process = 0;
  1630. // SAFETY: a window handle from the enumeration; `found` is ours.
  1631. unsafe {
  1632. GetWindowThreadProcessId(hwnd, Some(&mut process));
  1633. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  1634. && IsWindowVisible(hwnd).as_bool()
  1635. {
  1636. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  1637. return false.into();
  1638. }
  1639. }
  1640. true.into()
  1641. }
  1642. let mut found: Option<HWND> = None;
  1643. // SAFETY: the callback only writes `found`, which outlives the call.
  1644. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  1645. found
  1646. }
  1647. /// `state` without the bits the host texture's flags forbid: the console
  1648. /// lets the title name states its own resources allow (unordered access on
  1649. /// a depth target, whose host copy cannot have both).
  1650. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  1651. // SAFETY: a plain query.
  1652. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  1653. }
  1654. /// [`legal_state`] for a texture with resource flags `flags`.
  1655. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  1656. // (flag, set or clear forbids, state bits): render target, unordered
  1657. // access, depth, denied shader resource.
  1658. const FORBIDDEN: [(u32, bool, u32); 4] = [
  1659. (0x1, false, 0x4),
  1660. (0x4, false, 0x8),
  1661. (0x2, false, 0x10 | 0x20),
  1662. (0x8, true, 0x40 | 0x80),
  1663. ];
  1664. FORBIDDEN
  1665. .iter()
  1666. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  1667. .fold(state, |s, &(_, _, bits)| s & !bits)
  1668. }
  1669. impl Host {
  1670. /// A buffer in system memory that the CPU maps (write-back, so reading
  1671. /// it is fast too) and shaders read and write: for host copies of title
  1672. /// memory that shaders write, which upload memory cannot be. Starts in
  1673. /// the common state (buffers move out of it implicitly).
  1674. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  1675. let heap = D3D12_HEAP_PROPERTIES {
  1676. Type: D3D12_HEAP_TYPE_CUSTOM,
  1677. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  1678. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  1679. ..Default::default()
  1680. };
  1681. let desc = D3D12_RESOURCE_DESC {
  1682. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1683. Width: size.max(1),
  1684. Height: 1,
  1685. DepthOrArraySize: 1,
  1686. MipLevels: 1,
  1687. SampleDesc: DXGI_SAMPLE_DESC {
  1688. Count: 1,
  1689. Quality: 0,
  1690. },
  1691. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1692. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  1693. ..Default::default()
  1694. };
  1695. let mut buffer: Option<ID3D12Resource> = None;
  1696. let mut data = std::ptr::null_mut();
  1697. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  1698. let made = unsafe {
  1699. self.device
  1700. .CreateCommittedResource(
  1701. &heap,
  1702. D3D12_HEAP_FLAG_NONE,
  1703. &desc,
  1704. D3D12_RESOURCE_STATE_COMMON,
  1705. None,
  1706. &mut buffer,
  1707. )
  1708. .and_then(|()| {
  1709. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  1710. b.Map(0, None, Some(&mut data))
  1711. })
  1712. };
  1713. match made {
  1714. Ok(()) => Some((buffer?, data.cast())),
  1715. Err(e) => {
  1716. tracing::warn!(error = %e, size, "no shared buffer");
  1717. None
  1718. }
  1719. }
  1720. }
  1721. }
  1722. /// For adapters without device-removed data (the software one): the last
  1723. /// commands each list of the failed submission noted (diagnostics, with
  1724. /// `VICTORY_D3D12_DRED`).
  1725. fn last_notes(runs: &[&HostList]) -> String {
  1726. #[cfg(feature = "diagnostics")]
  1727. {
  1728. let mut text = String::new();
  1729. for (i, r) in runs.iter().enumerate() {
  1730. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  1731. for (n, _) in notes.iter().rev().take(6).rev() {
  1732. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  1733. }
  1734. }
  1735. text
  1736. }
  1737. #[cfg(not(feature = "diagnostics"))]
  1738. {
  1739. let _ = runs;
  1740. String::new()
  1741. }
  1742. }
  1743. /// Where the faulting address `va` lies against a range `(start, bytes)` a
  1744. /// command reads (diagnostics).
  1745. #[cfg(feature = "diagnostics")]
  1746. fn fault_in(va: u64, (start, bytes): (u64, u64)) -> String {
  1747. let end = start + bytes;
  1748. if va < start {
  1749. format!(" (fault {:#x} below its source)", start - va)
  1750. } else if va < end {
  1751. format!(" (fault at source +{:#x})", va - start)
  1752. } else {
  1753. format!(" (fault {:#x} past its source's end)", va - end)
  1754. }
  1755. }
  1756. /// The commands that may have been running where a list stopped at
  1757. /// command `done`: those between the barriers around it (work between
  1758. /// barriers overlaps on the GPU), by kind, and what the markers just
  1759. /// before them say (`HostList::note_op`: diagnostics builds with
  1760. /// device-removed data on).
  1761. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  1762. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  1763. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  1764. let to = history[done..]
  1765. .iter()
  1766. .position(barrier)
  1767. .map_or(history.len(), |b| (done + b).max(done + 1));
  1768. let mut text = format!(", commands {from}..{to} between its barriers:");
  1769. let mut shown = 0;
  1770. for i in from..to {
  1771. let op = history[i];
  1772. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  1773. continue;
  1774. }
  1775. shown += 1;
  1776. let marker = i
  1777. .checked_sub(1)
  1778. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  1779. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  1780. .map_or("no marker", |(_, s)| s.as_str());
  1781. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  1782. }
  1783. text
  1784. }
  1785. pub(crate) fn transition(
  1786. resource: &ID3D12Resource,
  1787. before: D3D12_RESOURCE_STATES,
  1788. after: D3D12_RESOURCE_STATES,
  1789. ) -> D3D12_RESOURCE_BARRIER {
  1790. D3D12_RESOURCE_BARRIER {
  1791. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  1792. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  1793. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  1794. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  1795. // SAFETY: a borrowed pointer; the barrier never releases it.
  1796. pResource: unsafe { std::mem::transmute_copy(resource) },
  1797. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  1798. StateBefore: before,
  1799. StateAfter: after,
  1800. }),
  1801. },
  1802. }
  1803. }
  1804. /// A window of the given client size, owned by its own message thread.
  1805. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  1806. let (sender, receiver) = std::sync::mpsc::channel();
  1807. std::thread::Builder::new()
  1808. .name("victory-window".into())
  1809. .spawn(move || {
  1810. let made = make_window(width, height);
  1811. let ok = made.is_ok();
  1812. let _ = sender.send(made.map(|h| h.0 as usize));
  1813. if ok {
  1814. pump();
  1815. }
  1816. })
  1817. .map_err(|_| windows::core::Error::empty())?;
  1818. let hwnd = receiver
  1819. .recv()
  1820. .map_err(|_| windows::core::Error::empty())??;
  1821. Ok(HWND(hwnd as *mut _))
  1822. }
  1823. extern "system" fn window_proc(
  1824. hwnd: HWND,
  1825. message: u32,
  1826. wparam: WPARAM,
  1827. lparam: LPARAM,
  1828. ) -> LRESULT {
  1829. // SAFETY: the default handling for our window.
  1830. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  1831. }
  1832. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  1833. const CLASS: PCWSTR = w!("VIctory");
  1834. // SAFETY: registers our class once and creates a window of it.
  1835. unsafe {
  1836. let instance = GetModuleHandleW(None)?;
  1837. let class = WNDCLASSEXW {
  1838. cbSize: size_of::<WNDCLASSEXW>() as u32,
  1839. lpfnWndProc: Some(window_proc),
  1840. hInstance: instance.into(),
  1841. lpszClassName: CLASS,
  1842. hCursor: LoadCursorW(None, IDC_ARROW)?,
  1843. ..Default::default()
  1844. };
  1845. RegisterClassExW(&class);
  1846. let mut rect = RECT {
  1847. left: 0,
  1848. top: 0,
  1849. right: width as i32,
  1850. bottom: height as i32,
  1851. };
  1852. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  1853. CreateWindowExW(
  1854. WINDOW_EX_STYLE(0),
  1855. CLASS,
  1856. w!("VIctory"),
  1857. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  1858. CW_USEDEFAULT,
  1859. CW_USEDEFAULT,
  1860. rect.right - rect.left,
  1861. rect.bottom - rect.top,
  1862. None,
  1863. None,
  1864. Some(instance.into()),
  1865. None,
  1866. )
  1867. }
  1868. }
  1869. fn pump() {
  1870. let mut message = MSG::default();
  1871. // SAFETY: the standard message loop of this thread's window.
  1872. unsafe {
  1873. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  1874. let _ = TranslateMessage(&message);
  1875. DispatchMessageW(&message);
  1876. }
  1877. }
  1878. }
  1879. #[cfg(test)]
  1880. mod tests {
  1881. use super::Batch;
  1882. use std::sync::Arc;
  1883. #[test]
  1884. fn a_texture_is_checked_once_per_submission() {
  1885. let mut batch = Batch::default();
  1886. let (a, b) = (Arc::new([0u8; 16]), Arc::new([0u8; 16]));
  1887. // The first list sampling each texture checks it ...
  1888. assert!(batch.texture_due(&a));
  1889. assert!(batch.texture_due(&b));
  1890. // ... later lists of the same submission do not.
  1891. assert!(!batch.texture_due(&a));
  1892. assert!(!batch.texture_due(&a.clone()));
  1893. assert!(!batch.texture_due(&b));
  1894. }
  1895. #[test]
  1896. fn title_writes_make_textures_due_again() {
  1897. let mut batch = Batch::default();
  1898. let a = Arc::new(1u32);
  1899. assert!(batch.texture_due(&a));
  1900. assert!(!batch.texture_due(&a));
  1901. // A copy into title memory or work that may write it may have
  1902. // changed the texture's memory.
  1903. batch.title_written();
  1904. assert!(batch.texture_due(&a));
  1905. assert!(!batch.texture_due(&a));
  1906. // A fresh submission starts over.
  1907. let mut next = Batch::default();
  1908. assert!(next.texture_due(&a));
  1909. }
  1910. /// The hashing a submission does for textures in physical-page memory,
  1911. /// with every list checking the textures it samples (before) and with
  1912. /// each checked once (after). Run with
  1913. /// `cargo test --release -p victory-gpu -- --ignored --nocapture texture_checks`.
  1914. #[test]
  1915. #[ignore = "benchmark"]
  1916. fn texture_checks_per_submission() {
  1917. const TEXTURES: usize = 48;
  1918. const SIZE: usize = 4 << 20;
  1919. const LISTS: usize = 12;
  1920. let textures: Vec<Arc<Vec<u8>>> = (0..TEXTURES)
  1921. .map(|t| Arc::new((0..SIZE).map(|i| (i * 31 + t) as u8).collect()))
  1922. .collect();
  1923. let submit = |dedupe: bool| {
  1924. let mut batch = Batch::default();
  1925. let mut hashed = 0usize;
  1926. let started = std::time::Instant::now();
  1927. for _ in 0..LISTS {
  1928. for t in &textures {
  1929. if !dedupe || batch.texture_due(t) {
  1930. std::hint::black_box(blake3::hash(t));
  1931. hashed += 1;
  1932. }
  1933. }
  1934. }
  1935. (started.elapsed(), hashed)
  1936. };
  1937. submit(false); // warm up
  1938. let (before, n_before) = submit(false);
  1939. let (after, n_after) = submit(true);
  1940. assert_eq!((n_before, n_after), (TEXTURES * LISTS, TEXTURES));
  1941. println!(
  1942. "{LISTS} lists sampling {TEXTURES} textures of {} MiB: \
  1943. before {n_before} hashes in {before:?}, after {n_after} in {after:?} ({:.1}x)",
  1944. SIZE >> 20,
  1945. before.as_secs_f64() / after.as_secs_f64()
  1946. );
  1947. }
  1948. }