host.rs 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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. /// Of the preparing: title memory copies (microseconds, bytes) and texture
  62. /// refreshes (microseconds, bytes hashed), since the last frame-rate line.
  63. pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [
  64. std::sync::atomic::AtomicU64::new(0),
  65. std::sync::atomic::AtomicU64::new(0),
  66. std::sync::atomic::AtomicU64::new(0),
  67. std::sync::atomic::AtomicU64::new(0),
  68. ];
  69. /// What the runtime does when the host GPU fails for good: report it like a
  70. /// crash and end the run. The console has no such state, and carrying on
  71. /// draws nothing at seconds per frame.
  72. static ON_FAILURE: OnceLock<fn(&str) -> !> = OnceLock::new();
  73. /// Sets what a host GPU failure does (the runtime's crash report).
  74. pub fn on_failure(report: fn(&str) -> !) {
  75. let _ = ON_FAILURE.set(report);
  76. }
  77. /// Ends the run on a host GPU failure: what failed, the removal reason and
  78. /// the debug layer's first error, if any (`VICTORY_D3D12_DEBUG=1` in a
  79. /// diagnostics build names the command).
  80. pub(crate) fn fail(what: std::fmt::Arguments) -> ! {
  81. let mut text = what.to_string();
  82. if let Some(host) = host() {
  83. // SAFETY: a plain query.
  84. if let Err(e) = unsafe { host.device.GetDeviceRemovedReason() } {
  85. text.push_str(&format!("; device removed: {e}"));
  86. }
  87. match host.log_messages() {
  88. Some(first) => text.push_str(&format!("; debug layer: {first}")),
  89. None if host.messages.is_none() => text.push_str(
  90. "; a diagnostics build with VICTORY_D3D12_DEBUG=1 names the command",
  91. ),
  92. None => {}
  93. }
  94. }
  95. tracing::error!("{text}");
  96. match ON_FAILURE.get() {
  97. Some(report) => report(&text),
  98. None => std::process::abort(),
  99. }
  100. }
  101. /// The host GPU, created on first use; `None` without one (a run then
  102. /// behaves as before: nothing executes).
  103. pub(crate) fn host() -> Option<&'static Host> {
  104. static HOST: OnceLock<Option<Host>> = OnceLock::new();
  105. HOST.get_or_init(|| match create() {
  106. Ok(host) => Some(host),
  107. Err(e) => {
  108. tracing::warn!(error = %e, "no host D3D12 device; command lists will not run");
  109. None
  110. }
  111. })
  112. .as_ref()
  113. }
  114. fn create() -> windows::core::Result<Host> {
  115. // SAFETY: plain D3D12 object creation with valid descriptions.
  116. unsafe {
  117. // The debug layer only in builds with diagnostics.
  118. let debug =
  119. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DEBUG").is_some();
  120. if debug {
  121. let mut layer: Option<ID3D12Debug> = None;
  122. match D3D12GetDebugInterface(&mut layer) {
  123. Ok(()) => layer.into_iter().for_each(|l| l.EnableDebugLayer()),
  124. Err(e) => tracing::warn!(error = %e, "no D3D12 debug layer"),
  125. }
  126. }
  127. // Diagnostics: device-removed data (the command that faulted, the
  128. // faulting address), read when the device is removed.
  129. if dred_on() {
  130. let mut dred: Option<ID3D12DeviceRemovedExtendedDataSettings> = None;
  131. if D3D12GetDebugInterface(&mut dred).is_ok()
  132. && let Some(dred) = dred
  133. {
  134. dred.SetAutoBreadcrumbsEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  135. dred.SetPageFaultEnablement(D3D12_DRED_ENABLEMENT_FORCED_ON);
  136. }
  137. }
  138. let mut device: Option<ID3D12Device> = None;
  139. // Diagnostics: the software adapter, on which a shader's wild access
  140. // is an access violation in this process (a crash report with the
  141. // address and instruction) instead of a GPU fault and driver reset.
  142. if cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_WARP").is_some() {
  143. let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  144. let adapter: IDXGIAdapter = factory.EnumWarpAdapter()?;
  145. D3D12CreateDevice(&adapter, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  146. tracing::info!("host device on the software adapter (WARP)");
  147. } else {
  148. D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?;
  149. }
  150. let device = device.ok_or_else(windows::core::Error::empty)?;
  151. let messages = debug
  152. .then(|| device.cast::<ID3D12InfoQueue>().ok())
  153. .flatten();
  154. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  155. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  156. ..Default::default()
  157. })?;
  158. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  159. let event = CreateEventW(None, false, false, None)?;
  160. let rtvs: ID3D12DescriptorHeap =
  161. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  162. Type: D3D12_DESCRIPTOR_HEAP_TYPE_RTV,
  163. NumDescriptors: RTV_RING,
  164. ..Default::default()
  165. })?;
  166. let rtv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  167. let dsvs: ID3D12DescriptorHeap =
  168. device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  169. Type: D3D12_DESCRIPTOR_HEAP_TYPE_DSV,
  170. NumDescriptors: RTV_RING,
  171. ..Default::default()
  172. })?;
  173. let dsv_size = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
  174. tracing::info!("host D3D12 device ready");
  175. Ok(Host {
  176. device,
  177. queue,
  178. fence,
  179. submitted: Mutex::new(0),
  180. event,
  181. rtvs,
  182. rtv_size,
  183. dsvs,
  184. dsv_size,
  185. next_dsv: AtomicU32::new(0),
  186. messages,
  187. next_rtv: AtomicU32::new(0),
  188. presenter: Mutex::new(None),
  189. })
  190. }
  191. }
  192. /// A host command list and its allocator, always used together.
  193. pub(crate) struct HostList {
  194. allocator: ID3D12CommandAllocator,
  195. pub(crate) list: ID3D12GraphicsCommandList,
  196. /// Work for submission time, in recorded order.
  197. deferred: Mutex<Deferred>,
  198. /// Upload memory for data the list's draws make (expanded vertices),
  199. /// reused after a reset.
  200. scratch: Mutex<Scratch>,
  201. /// Host texture states the list assumes, by title resource: at its
  202. /// start and at its end. Lists are recorded on many threads and run in
  203. /// submission order, so the transitions from a texture's real state are
  204. /// made at submission, in `prelude`.
  205. states: Mutex<std::collections::HashMap<usize, (u32, u32)>>,
  206. /// The list that runs those transitions just before this one.
  207. prelude: (ID3D12CommandAllocator, ID3D12GraphicsCommandList),
  208. /// The pipelines the list binds, for reports of slow submissions.
  209. pipelines: Mutex<std::collections::BTreeSet<String>>,
  210. /// The texts of the markers `note_op` set, in order (for device-removed
  211. /// data without marker texts).
  212. #[cfg(feature = "diagnostics")]
  213. notes: Mutex<Vec<String>>,
  214. }
  215. /// Whether device-removed data is on (`VICTORY_D3D12_DRED`, diagnostics
  216. /// builds).
  217. pub(crate) fn dred_on() -> bool {
  218. static ON: OnceLock<bool> = OnceLock::new();
  219. *ON.get_or_init(|| {
  220. cfg!(feature = "diagnostics") && std::env::var_os("VICTORY_D3D12_DRED").is_some()
  221. })
  222. }
  223. /// Names a host object for the device-removed report, which names the
  224. /// allocations a page fault hit (only with device-removed data on).
  225. pub(crate) fn name(object: &impl Interface, text: impl FnOnce() -> String) {
  226. if dred_on()
  227. && let Ok(object) = object.cast::<ID3D12Object>()
  228. {
  229. // SAFETY: a plain call on a live object.
  230. let _ = unsafe { object.SetName(&windows::core::HSTRING::from(text())) };
  231. }
  232. }
  233. /// Upload chunks handed out front to back: the chunks, the one in use and
  234. /// the bytes used in it.
  235. #[derive(Default)]
  236. struct Scratch {
  237. chunks: Vec<(ID3D12Resource, usize, u64)>,
  238. current: usize,
  239. used: u64,
  240. }
  241. // SAFETY: the chunk pointers are persistent mappings of upload buffers.
  242. unsafe impl Send for Scratch {}
  243. const SCRATCH_CHUNK: u64 = 4 << 20;
  244. /// One piece of submission-time work, in recorded order.
  245. enum Step {
  246. /// A copy into title memory (destination, source, bytes): the title's
  247. /// buffer copies, which later refreshes must see.
  248. Copy(usize, usize, usize),
  249. /// A copy of title memory into the list's own upload memory.
  250. Fill(usize, usize, usize),
  251. /// Brings a range (address, bytes) of a buffer's host copy up to date:
  252. /// once per submission, whichever lists ask, until a `Copy` or `Run`
  253. /// intervenes.
  254. Refresh(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  255. /// Work that may write title memory.
  256. Run(Box<dyn Fn() + Send>),
  257. /// Work that writes host memory only.
  258. Host(Box<dyn Fn() + Send>),
  259. /// Shaders write a range (address, bytes) of a buffer's host copy.
  260. GpuWrite(std::sync::Arc<crate::shadow::Shadow>, usize, usize),
  261. }
  262. /// What a list does on the CPU when it is submitted: copies between host
  263. /// memory regions (title buffers, upload buffers and buffer copies), and
  264. /// the upload buffers its GPU commands read, kept until the list is reset.
  265. #[derive(Default)]
  266. struct Deferred {
  267. /// Destination, source, bytes.
  268. copies: Vec<Step>,
  269. uploads: Vec<ID3D12Resource>,
  270. /// Buffer ranges refreshed since the last title copy (host copy,
  271. /// address, bytes): refreshing them again would find the same bytes.
  272. refreshed: std::collections::HashSet<(usize, usize, usize)>,
  273. /// Textures whose contents the list brings up to date.
  274. textures: std::collections::HashSet<usize>,
  275. /// Bottom-of-pipe writes, done once the list has run: address, what,
  276. /// bytes.
  277. writes: Vec<(usize, crate::queue::Written, usize)>,
  278. }
  279. impl Host {
  280. /// Whether the host runs mesh shaders at shader model 6.6 (translated
  281. /// mesh shaders need both); logged once.
  282. pub(crate) fn mesh_shaders(&self) -> bool {
  283. static MESH: OnceLock<bool> = OnceLock::new();
  284. *MESH.get_or_init(|| {
  285. let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS7::default();
  286. let mut model = D3D12_FEATURE_DATA_SHADER_MODEL {
  287. HighestShaderModel: D3D_SHADER_MODEL_6_6,
  288. };
  289. // SAFETY: each query writes its own structure of the given size.
  290. let ok = unsafe {
  291. self.device
  292. .CheckFeatureSupport(
  293. D3D12_FEATURE_D3D12_OPTIONS7,
  294. (&raw mut options).cast(),
  295. size_of_val(&options) as u32,
  296. )
  297. .is_ok()
  298. && self
  299. .device
  300. .CheckFeatureSupport(
  301. D3D12_FEATURE_SHADER_MODEL,
  302. (&raw mut model).cast(),
  303. size_of_val(&model) as u32,
  304. )
  305. .is_ok()
  306. };
  307. let mesh = ok
  308. && options.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED
  309. && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0;
  310. tracing::info!(mesh, "host mesh shader support");
  311. mesh
  312. })
  313. }
  314. /// A new list, open for recording.
  315. pub(crate) fn new_list(&self) -> windows::core::Result<HostList> {
  316. // SAFETY: plain object creation.
  317. unsafe {
  318. let allocator: ID3D12CommandAllocator = self
  319. .device
  320. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  321. let list: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  322. 0,
  323. D3D12_COMMAND_LIST_TYPE_DIRECT,
  324. &allocator,
  325. None,
  326. )?;
  327. let prelude_allocator: ID3D12CommandAllocator = self
  328. .device
  329. .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?;
  330. let prelude: ID3D12GraphicsCommandList = self.device.CreateCommandList(
  331. 0,
  332. D3D12_COMMAND_LIST_TYPE_DIRECT,
  333. &prelude_allocator,
  334. None,
  335. )?;
  336. prelude.Close()?;
  337. Ok(HostList {
  338. allocator,
  339. list,
  340. deferred: Mutex::default(),
  341. scratch: Mutex::default(),
  342. states: Mutex::default(),
  343. prelude: (prelude_allocator, prelude),
  344. pipelines: Mutex::default(),
  345. #[cfg(feature = "diagnostics")]
  346. notes: Mutex::default(),
  347. })
  348. }
  349. }
  350. /// Runs closed lists and waits for them.
  351. pub(crate) fn execute(&self, runs: &[&HostList]) {
  352. let started = std::time::Instant::now();
  353. #[cfg(feature = "diagnostics")]
  354. crate::copystat::add(crate::copystat::C::Submissions, 1);
  355. let mut lists: Vec<Option<ID3D12CommandList>> = Vec::with_capacity(2 * runs.len());
  356. let mut batch = Batch::default();
  357. for list in runs {
  358. list.run_deferred(&mut batch);
  359. if let Some(prelude) = list.prelude() {
  360. lists.push(Some(prelude));
  361. }
  362. lists.push(list.list.cast().ok());
  363. }
  364. batch.flush();
  365. let mut submitted = self.submitted.lock().unwrap_or_else(|e| e.into_inner());
  366. *submitted += 1;
  367. let prepared = std::time::Instant::now();
  368. // SAFETY: closed lists; the fence and event are ours.
  369. unsafe {
  370. self.queue.ExecuteCommandLists(&lists);
  371. let waited = self
  372. .queue
  373. .Signal(&self.fence, *submitted)
  374. .and_then(|()| self.fence.SetEventOnCompletion(*submitted, self.event));
  375. match waited {
  376. Ok(()) => {
  377. WaitForSingleObject(self.event, INFINITE);
  378. }
  379. Err(e) => tracing::warn!(error = %e, "host submission not waited for"),
  380. }
  381. }
  382. let gpu = prepared.elapsed();
  383. SUBMISSION_US[0].fetch_add((prepared - started).as_micros() as u64, Ordering::Relaxed);
  384. SUBMISSION_US[1].fetch_add(gpu.as_micros() as u64, Ordering::Relaxed);
  385. // The host resets a device whose submission runs for about 2 s.
  386. if gpu > std::time::Duration::from_millis(250) {
  387. let pipelines: std::collections::BTreeSet<String> = runs
  388. .iter()
  389. .flat_map(|l| l.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clone())
  390. .collect();
  391. tracing::warn!(ms = gpu.as_millis(), lists = runs.len(), ?pipelines, "slow host submission");
  392. }
  393. // SAFETY: a plain query.
  394. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() {
  395. fail(format_args!(
  396. "host GPU device removed after a submission of {} lists{}{}",
  397. runs.len(),
  398. self.removal_data(runs),
  399. last_notes(runs)
  400. ));
  401. }
  402. for list in runs {
  403. let deferred = list.deferred();
  404. // Before the bottom-of-pipe writes, which tell the title the
  405. // GPU is done.
  406. for step in &deferred.copies {
  407. if let Step::GpuWrite(shadow, address, len) = step {
  408. shadow.copy_back(*address, *len);
  409. }
  410. }
  411. for &(at, what, bytes) in &deferred.writes {
  412. what.write(at as *mut u8, bytes);
  413. }
  414. }
  415. self.log_messages();
  416. }
  417. /// With `VICTORY_D3D12_DRED`: the faulting address and the allocations
  418. /// it lies in (by the names we give them) or the title memory copy just
  419. /// below it; for each list that did not finish, the command it stopped
  420. /// at and what the draws and dispatches in flight there run (or, in
  421. /// lists that never started, the pipelines they bind).
  422. fn removal_data(&self, runs: &[&HostList]) -> String {
  423. let Ok(dred) = self.device.cast::<ID3D12DeviceRemovedExtendedData1>() else {
  424. return String::new();
  425. };
  426. let mut text = String::new();
  427. // SAFETY: the outputs are the runtime's, valid while the device
  428. // lives; nodes are walked as linked, histories have their counts.
  429. unsafe {
  430. if let Ok(fault) = dred.GetPageFaultAllocationOutput1()
  431. && fault.PageFaultVA != 0
  432. {
  433. let va = fault.PageFaultVA;
  434. text.push_str(&format!("; page fault at {va:#x}"));
  435. for (what, head) in [
  436. ("inside", fault.pHeadExistingAllocationNode),
  437. ("inside freed", fault.pHeadRecentFreedAllocationNode),
  438. ] {
  439. let mut names = Vec::new();
  440. let mut node = head;
  441. while let Some(n) = node.as_ref()
  442. && names.len() < 8
  443. {
  444. let name = if n.ObjectNameW.is_null() {
  445. "unnamed".to_owned()
  446. } else {
  447. n.ObjectNameW.to_string().unwrap_or_default()
  448. };
  449. names.push(format!("{name} (type {})", n.AllocationType.0));
  450. node = n.pNext;
  451. }
  452. if !names.is_empty() {
  453. text.push_str(&format!("; {what} {names:?}"));
  454. }
  455. }
  456. text.push_str(&crate::shadow::near(va));
  457. }
  458. // The plain output: the extended one (with marker texts) came
  459. // back without stopped lists on this host.
  460. let Ok(crumbs) = dred.GetAutoBreadcrumbsOutput() else {
  461. return text;
  462. };
  463. let mut plain = crumbs.pHeadAutoBreadcrumbNode;
  464. while let Some(p) = plain.as_ref() {
  465. let done = p.pLastBreadcrumbValue.as_ref().copied().unwrap_or(0);
  466. if done < p.BreadcrumbCount && !p.pCommandHistory.is_null() {
  467. let history =
  468. std::slice::from_raw_parts(p.pCommandHistory, p.BreadcrumbCount as usize);
  469. text.push_str(&format!(
  470. "; a list stopped at command {done} of {} (op {})",
  471. p.BreadcrumbCount, history[done as usize].0
  472. ));
  473. let list = p.pCommandList.as_ref().map(|l| l.as_raw());
  474. let run = runs.iter().find(|r| Some(r.list.as_raw()) == list);
  475. // The k-th marker command is the k-th note.
  476. #[cfg(feature = "diagnostics")]
  477. let markers: Vec<(u32, String)> = run.map_or_else(Vec::new, |r| {
  478. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  479. history
  480. .iter()
  481. .enumerate()
  482. .filter(|(_, op)| **op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  483. .zip(notes.iter())
  484. .map(|((at, _), note)| (at as u32, note.clone()))
  485. .collect()
  486. });
  487. #[cfg(not(feature = "diagnostics"))]
  488. let markers: Vec<(u32, String)> = Vec::new();
  489. if done > 0 {
  490. text.push_str(&in_flight(history, &markers, done as usize));
  491. } else if let Some(r) = run {
  492. let pipelines = r.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  493. text.push_str(&format!(", its pipelines {pipelines:?}"));
  494. }
  495. }
  496. plain = p.pNext;
  497. }
  498. }
  499. text
  500. }
  501. /// Moves the debug layer's messages into our log; returns the first
  502. /// error among them.
  503. pub(crate) fn log_messages(&self) -> Option<String> {
  504. let Some(queue) = &self.messages else {
  505. return None;
  506. };
  507. let mut first_error = None;
  508. // SAFETY: each message is read into a buffer of the size the queue
  509. // reports, then the queue is emptied.
  510. unsafe {
  511. for i in 0..queue.GetNumStoredMessages() {
  512. let mut size = 0;
  513. if queue.GetMessage(i, None, &mut size).is_err() || size == 0 {
  514. continue;
  515. }
  516. let mut buffer = vec![0u64; size.div_ceil(8)];
  517. let message = buffer.as_mut_ptr().cast::<D3D12_MESSAGE>();
  518. if queue.GetMessage(i, Some(message), &mut size).is_ok() {
  519. let m = &*message;
  520. let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength);
  521. let text = String::from_utf8_lossy(text);
  522. let text = text.trim_end_matches('\0');
  523. tracing::warn!(id = m.ID.0, severity = m.Severity.0, "D3D12: {text}");
  524. if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() {
  525. first_error = Some(text.to_owned());
  526. }
  527. }
  528. }
  529. queue.ClearStoredMessages();
  530. }
  531. first_error
  532. }
  533. /// A host render target view of `resource`, valid until it is recorded.
  534. pub(crate) fn rtv(
  535. &self,
  536. resource: &ID3D12Resource,
  537. desc: Option<&D3D12_RENDER_TARGET_VIEW_DESC>,
  538. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  539. let slot = self.next_rtv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  540. // SAFETY: a slot of our heap and a live resource.
  541. unsafe {
  542. let mut handle = self.rtvs.GetCPUDescriptorHandleForHeapStart();
  543. handle.ptr += (slot * self.rtv_size) as usize;
  544. self.device
  545. .CreateRenderTargetView(resource, desc.map(|d| d as *const _), handle);
  546. handle
  547. }
  548. }
  549. /// A host depth view of `resource`, valid until it is recorded.
  550. pub(crate) fn dsv(
  551. &self,
  552. resource: &ID3D12Resource,
  553. desc: Option<&D3D12_DEPTH_STENCIL_VIEW_DESC>,
  554. ) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  555. let slot = self.next_dsv.fetch_add(1, Ordering::Relaxed) % RTV_RING;
  556. // SAFETY: a slot of our heap and a live resource.
  557. unsafe {
  558. let mut handle = self.dsvs.GetCPUDescriptorHandleForHeapStart();
  559. handle.ptr += (slot * self.dsv_size) as usize;
  560. self.device
  561. .CreateDepthStencilView(resource, desc.map(|d| d as *const _), handle);
  562. handle
  563. }
  564. }
  565. }
  566. impl HostList {
  567. pub(crate) fn close(&self) {
  568. // SAFETY: our list.
  569. if let Err(e) = unsafe { self.list.Close() } {
  570. fail(format_args!(
  571. "a host command list did not close ({e}): a command recorded into it was invalid"
  572. ));
  573. }
  574. }
  575. /// Only after the list's last submission finished (every one is waited
  576. /// for).
  577. pub(crate) fn reset(&self) {
  578. *self.deferred() = Deferred::default();
  579. self.states.lock().unwrap_or_else(|e| e.into_inner()).clear();
  580. self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear();
  581. #[cfg(feature = "diagnostics")]
  582. self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear();
  583. {
  584. let mut scratch = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  585. (scratch.current, scratch.used) = (0, 0);
  586. }
  587. // SAFETY: the list is not executing.
  588. let reset = unsafe {
  589. self.allocator
  590. .Reset()
  591. .and_then(|()| self.list.Reset(&self.allocator, None))
  592. };
  593. if let Err(e) = reset {
  594. fail(format_args!("a host command list did not reset ({e})"));
  595. }
  596. }
  597. /// Moves a title texture's host copy to `wanted` (a host state) in this
  598. /// list: the host texture and the state it leaves, if that is a change.
  599. /// The list's first use of a texture records nothing: its prelude brings
  600. /// the texture there at submission.
  601. pub(crate) fn transition(
  602. &self,
  603. resource: crate::object::This,
  604. wanted: u32,
  605. ) -> Option<(&'static ID3D12Resource, u32)> {
  606. let texture = crate::resource::host_resource(resource)?;
  607. let wanted = legal_state(texture, wanted);
  608. let mut states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  609. match states.entry(resource as usize) {
  610. std::collections::hash_map::Entry::Vacant(v) => {
  611. v.insert((wanted, wanted));
  612. None
  613. }
  614. std::collections::hash_map::Entry::Occupied(mut o) => {
  615. let before = std::mem::replace(&mut o.get_mut().1, wanted);
  616. (before != wanted).then_some((texture, before))
  617. }
  618. }
  619. }
  620. /// At submission: the list that moves each texture this list uses from
  621. /// its real state to the one the list starts with; the textures' real
  622. /// states become those the list ends with.
  623. fn prelude(&self) -> Option<ID3D12CommandList> {
  624. let states = self.states.lock().unwrap_or_else(|e| e.into_inner());
  625. let barriers: Vec<D3D12_RESOURCE_BARRIER> = states
  626. .iter()
  627. .filter_map(|(&resource, &(first, last))| {
  628. let resource = resource as crate::object::This;
  629. let texture = crate::resource::host_resource(resource)?;
  630. let real = crate::resource::swap_host_state(resource, last);
  631. (real != first).then(|| {
  632. transition(
  633. texture,
  634. D3D12_RESOURCE_STATES(real as i32),
  635. D3D12_RESOURCE_STATES(first as i32),
  636. )
  637. })
  638. })
  639. .collect();
  640. if barriers.is_empty() {
  641. return None;
  642. }
  643. let (allocator, list) = &self.prelude;
  644. // SAFETY: the prelude is not executing (every submission is waited
  645. // for); the textures are live.
  646. let recorded = unsafe {
  647. allocator.Reset().and_then(|()| {
  648. list.Reset(allocator, None)?;
  649. list.ResourceBarrier(&barriers);
  650. list.Close()
  651. })
  652. };
  653. if let Err(e) = recorded {
  654. fail(format_args!("a host state prelude did not record ({e})"));
  655. }
  656. list.cast().ok()
  657. }
  658. /// Notes what the command about to be recorded does, as a marker
  659. /// command whose text the list keeps (diagnostics, with device-removed
  660. /// data on): the report pairs the breadcrumbs' marker commands with the
  661. /// texts in order and names the commands a fault stopped among.
  662. #[cfg(feature = "diagnostics")]
  663. pub(crate) fn note_op(&self, what: impl FnOnce() -> String) {
  664. if dred_on() {
  665. let what = what();
  666. let text: Vec<u16> = what.encode_utf16().chain([0]).collect();
  667. const UNICODE: u32 = 0;
  668. // SAFETY: an open list; the marker is copied when recorded.
  669. unsafe {
  670. self.list.SetMarker(UNICODE, Some(text.as_ptr().cast()), 2 * text.len() as u32)
  671. };
  672. self.notes.lock().unwrap_or_else(|e| e.into_inner()).push(what);
  673. }
  674. }
  675. /// Notes a pipeline the list binds.
  676. pub(crate) fn used_pipeline(&self, name: &str) {
  677. let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner());
  678. if !pipelines.contains(name) {
  679. pipelines.insert(name.to_owned());
  680. }
  681. }
  682. fn deferred(&self) -> std::sync::MutexGuard<'_, Deferred> {
  683. self.deferred.lock().unwrap_or_else(|e| e.into_inner())
  684. }
  685. /// Copies `len` bytes from `src` to `dst` when the list is submitted.
  686. pub(crate) fn defer_copy(&self, dst: *mut u8, src: *const u8, len: usize) {
  687. let mut deferred = self.deferred();
  688. deferred
  689. .copies
  690. .push(Step::Copy(dst as usize, src as usize, len));
  691. deferred.refreshed.clear();
  692. }
  693. /// Copies `len` bytes of title memory at `src` into the list's upload
  694. /// memory at `dst` when the list is submitted.
  695. pub(crate) fn defer_fill(&self, dst: *mut u8, src: *const u8, len: usize) {
  696. self.deferred()
  697. .copies
  698. .push(Step::Fill(dst as usize, src as usize, len));
  699. }
  700. /// Brings `[address, address + len)` of a buffer's host copy up to date
  701. /// when the list is submitted (once per range until a title copy
  702. /// intervenes), keeping the copy alive until the list is reset.
  703. pub(crate) fn defer_refresh(
  704. &self,
  705. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  706. address: usize,
  707. len: usize,
  708. ) {
  709. let mut deferred = self.deferred();
  710. let key = (std::sync::Arc::as_ptr(shadow) as usize, address, len);
  711. if deferred.refreshed.insert(key) {
  712. deferred
  713. .copies
  714. .push(Step::Refresh(shadow.clone(), address, len));
  715. }
  716. }
  717. /// Shaders of the list write `[address, address + len)` of a buffer's
  718. /// host copy: copied back into title memory once the list has run.
  719. pub(crate) fn defer_gpu_write(
  720. &self,
  721. shadow: &std::sync::Arc<crate::shadow::Shadow>,
  722. address: usize,
  723. len: usize,
  724. ) {
  725. self.deferred()
  726. .copies
  727. .push(Step::GpuWrite(shadow.clone(), address, len));
  728. }
  729. /// Stores `what` (`bytes` of it) at `dst` once the list has run.
  730. pub(crate) fn defer_write(&self, dst: *mut u8, what: crate::queue::Written, bytes: usize) {
  731. self.deferred().writes.push((dst as usize, what, bytes));
  732. }
  733. /// A mapped upload buffer of `size` bytes, alive until the list is
  734. /// reset.
  735. ///
  736. /// shortcut: one buffer per copy; pool them once uploads are frequent.
  737. pub(crate) fn upload(&self, host: &Host, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  738. let (buffer, data) = host.upload_buffer(size)?;
  739. self.deferred().uploads.push(buffer.clone());
  740. Some((buffer, data))
  741. }
  742. /// `len` bytes of upload memory (256-byte aligned) until the list is
  743. /// reset: the host GPU address and the CPU pointer.
  744. pub(crate) fn scratch(&self, len: u64) -> Option<(u64, *mut u8)> {
  745. let host = host()?;
  746. let mut s = self.scratch.lock().unwrap_or_else(|e| e.into_inner());
  747. let len = len.max(1).next_multiple_of(256);
  748. if len > SCRATCH_CHUNK {
  749. let (buffer, data) = host.upload_buffer(len)?;
  750. name(&buffer, || format!("list scratch {len:#x}"));
  751. // SAFETY: a live buffer.
  752. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  753. self.deferred().uploads.push(buffer);
  754. return Some((gpu, data));
  755. }
  756. if s.used + len > SCRATCH_CHUNK && s.current < s.chunks.len() {
  757. (s.current, s.used) = (s.current + 1, 0);
  758. }
  759. if s.current == s.chunks.len() {
  760. let (buffer, data) = host.upload_buffer(SCRATCH_CHUNK)?;
  761. name(&buffer, || "list scratch".into());
  762. // SAFETY: a live buffer.
  763. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  764. s.chunks.push((buffer, data as usize, gpu));
  765. s.used = 0;
  766. }
  767. let (_, data, gpu) = s.chunks[s.current];
  768. let at = s.used;
  769. s.used += len;
  770. Some((gpu + at, (data + at as usize) as *mut u8))
  771. }
  772. /// Whether this is the first time since the reset that the list asks
  773. /// about `key` (a texture to bring up to date).
  774. pub(crate) fn first_use(&self, key: usize) -> bool {
  775. self.deferred().textures.insert(key)
  776. }
  777. /// Runs `work` when the list is submitted, in order with its copies.
  778. /// `work` may write title memory (refreshes after it copy again).
  779. pub(crate) fn defer(&self, work: impl Fn() + Send + 'static) {
  780. self.deferred().copies.push(Step::Run(Box::new(work)));
  781. self.deferred().refreshed.clear();
  782. }
  783. /// As [`HostList::defer`], for work that writes only host memory.
  784. pub(crate) fn defer_host(&self, work: impl Fn() + Send + 'static) {
  785. self.deferred().copies.push(Step::Host(Box::new(work)));
  786. }
  787. /// Runs the list's submission-time steps; refreshes go into `batch`
  788. /// (the title's big buffers, a 174 MB one among them, are read by most
  789. /// lists of a submission, through many ranges).
  790. fn run_deferred(&self, batch: &mut Batch) {
  791. #[cfg(feature = "diagnostics")]
  792. use crate::copystat::{C, add};
  793. for step in &self.deferred().copies {
  794. let started = std::time::Instant::now();
  795. let copied = match step {
  796. &Step::Copy(dst, src, len) => {
  797. #[cfg(feature = "diagnostics")]
  798. {
  799. add(C::Copies, 1);
  800. add(C::CopyBytes, len as u64);
  801. }
  802. batch.flush();
  803. copy_mapped(dst as *mut u8, src as *const u8, len, true);
  804. len
  805. }
  806. &Step::Fill(dst, src, len) => {
  807. #[cfg(feature = "diagnostics")]
  808. {
  809. add(C::Copies, 1);
  810. add(C::CopyBytes, len as u64);
  811. }
  812. copy_mapped(dst as *mut u8, src as *const u8, len, false);
  813. len
  814. }
  815. Step::Refresh(shadow, address, len) => {
  816. #[cfg(feature = "diagnostics")]
  817. {
  818. add(C::Refreshes, 1);
  819. add(C::RefreshBytes, *len as u64);
  820. }
  821. batch.add(shadow, *address, *len);
  822. continue;
  823. }
  824. Step::Run(work) | Step::Host(work) => {
  825. if matches!(step, Step::Run(_)) {
  826. batch.flush();
  827. }
  828. work();
  829. #[cfg(feature = "diagnostics")]
  830. {
  831. add(C::Runs, 1);
  832. add(C::RunUs, started.elapsed().as_micros() as u64);
  833. }
  834. continue;
  835. }
  836. Step::GpuWrite(shadow, address, len) => {
  837. // The shaders start from the title's data.
  838. batch.flush();
  839. shadow.writing(*address, *len);
  840. continue;
  841. }
  842. };
  843. PREPARING[0].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
  844. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  845. }
  846. }
  847. }
  848. /// A submission's refreshes not done yet, merged per buffer copy into the
  849. /// range that covers them: done before a step that writes title memory or
  850. /// gives a range to shaders, and before the lists run.
  851. #[derive(Default)]
  852. struct Batch(Vec<(std::sync::Arc<crate::shadow::Shadow>, usize, usize)>);
  853. impl Batch {
  854. fn add(&mut self, shadow: &std::sync::Arc<crate::shadow::Shadow>, address: usize, len: usize) {
  855. let end = address + len;
  856. match self.0.iter_mut().find(|(s, ..)| std::sync::Arc::ptr_eq(s, shadow)) {
  857. Some((_, from, to)) => (*from, *to) = ((*from).min(address), (*to).max(end)),
  858. None => self.0.push((shadow.clone(), address, end)),
  859. }
  860. }
  861. fn flush(&mut self) {
  862. for (shadow, from, to) in self.0.drain(..) {
  863. let started = std::time::Instant::now();
  864. let copied = shadow.update(from, to - from);
  865. let us = started.elapsed().as_micros() as u64;
  866. #[cfg(feature = "diagnostics")]
  867. crate::copystat::range(from, to - from, us, 0);
  868. PREPARING[0].fetch_add(us, Ordering::Relaxed);
  869. PREPARING[1].fetch_add(copied as u64, Ordering::Relaxed);
  870. }
  871. }
  872. }
  873. /// Copies title memory at submission. The ranges were checked against their
  874. /// resources when recorded, but the title may since have unmapped pages of
  875. /// them (tiled memory, page mappings), which read as zeros here; a title
  876. /// destination (`title_dst`) that is not all mapped is left alone.
  877. ///
  878. /// The source is read through the kernel (`ReadProcessMemory`), which
  879. /// reports an unmapped page instead of faulting. Asking `VirtualQuery` first
  880. /// cost about 2 ms per copy in the title's big pools (it walks the page
  881. /// tables to the region's end), which made copies run at 100-200 MB/s.
  882. pub(crate) fn copy_mapped(dst: *mut u8, src: *const u8, len: usize, title_dst: bool) {
  883. #[cfg(feature = "diagnostics")]
  884. match crate::copystat::mode() {
  885. 1 => {
  886. // SAFETY: timing only: the caller vouches for the source.
  887. unsafe { std::ptr::copy(src, dst, len) };
  888. return;
  889. }
  890. 2 => return,
  891. _ => {}
  892. }
  893. if len == 0 || title_dst && !crate::texture::committed(dst, len) {
  894. return;
  895. }
  896. if title_dst {
  897. // The kernel writes the destination: it must not be guarded.
  898. crate::watch::writing(dst as usize, len);
  899. }
  900. #[cfg(feature = "diagnostics")]
  901. let moved = std::time::Instant::now();
  902. let whole = read(src, dst, len);
  903. #[cfg(feature = "diagnostics")]
  904. crate::copystat::add(crate::copystat::C::MoveUs, moved.elapsed().as_micros() as u64);
  905. if whole {
  906. return;
  907. }
  908. #[cfg(feature = "diagnostics")]
  909. crate::copystat::add(crate::copystat::C::Fallbacks, 1);
  910. // Something is unmapped: page by page (64 KiB, then 4 KiB in a piece
  911. // that fails), zeros for what cannot be read.
  912. for_pieces(src as usize, len, 64 << 10, |at, n| {
  913. let to = dst.wrapping_add(at - src as usize);
  914. if !read(at as *const u8, to, n) {
  915. for_pieces(at, n, 4 << 10, |at, n| {
  916. let to = dst.wrapping_add(at - src as usize);
  917. if !read(at as *const u8, to, n) {
  918. #[cfg(feature = "diagnostics")]
  919. crate::copystat::add(crate::copystat::C::Unmapped, n as u64);
  920. // SAFETY: inside the destination, which is mapped.
  921. unsafe { to.write_bytes(0, n) };
  922. }
  923. });
  924. }
  925. });
  926. }
  927. /// Copies `len` bytes from `src` to `dst` unless a source page is not
  928. /// readable.
  929. fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
  930. use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
  931. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  932. let mut done = 0;
  933. // SAFETY: the destination is mapped writable memory of `len` bytes; the
  934. // kernel checks the source.
  935. unsafe { ReadProcessMemory(GetCurrentProcess(), src.cast(), dst.cast(), len, &mut done) != 0 }
  936. }
  937. /// Copies host memory into title memory after a submission (what shaders
  938. /// wrote), leaving pages that are not mapped alone.
  939. pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
  940. use windows_sys::Win32::System::Diagnostics::Debug::WriteProcessMemory;
  941. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  942. let write = |at: usize, n: usize| {
  943. let from = src.wrapping_add(at - dst as usize);
  944. let mut done = 0;
  945. // SAFETY: the source is our mapped host copy; the kernel checks the
  946. // destination.
  947. unsafe { WriteProcessMemory(GetCurrentProcess(), at as _, from.cast(), n, &mut done) != 0 }
  948. };
  949. if len == 0 || write(dst as usize, len) {
  950. return;
  951. }
  952. for_pieces(dst as usize, len, 64 << 10, |at, n| {
  953. if !write(at, n) {
  954. for_pieces(at, n, 4 << 10, |at, n| {
  955. write(at, n);
  956. });
  957. }
  958. });
  959. }
  960. /// Calls `f` with the pieces of `[start, start + len)` cut at multiples of
  961. /// `step`.
  962. fn for_pieces(start: usize, len: usize, step: usize, mut f: impl FnMut(usize, usize)) {
  963. let end = start + len;
  964. let mut at = start;
  965. while at < end {
  966. let next = ((at / step + 1) * step).min(end);
  967. f(at, next - at);
  968. at = next;
  969. }
  970. }
  971. impl Host {
  972. /// A buffer in the upload heap, mapped for writing.
  973. pub(crate) fn upload_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  974. let heap = D3D12_HEAP_PROPERTIES {
  975. Type: D3D12_HEAP_TYPE_UPLOAD,
  976. ..Default::default()
  977. };
  978. let desc = D3D12_RESOURCE_DESC {
  979. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  980. Width: size.max(1),
  981. Height: 1,
  982. DepthOrArraySize: 1,
  983. MipLevels: 1,
  984. SampleDesc: DXGI_SAMPLE_DESC {
  985. Count: 1,
  986. Quality: 0,
  987. },
  988. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  989. ..Default::default()
  990. };
  991. let mut buffer: Option<ID3D12Resource> = None;
  992. let mut data = std::ptr::null_mut();
  993. // SAFETY: plain creation and mapping of an upload buffer.
  994. let made = unsafe {
  995. self.device
  996. .CreateCommittedResource(
  997. &heap,
  998. D3D12_HEAP_FLAG_NONE,
  999. &desc,
  1000. D3D12_RESOURCE_STATE_GENERIC_READ,
  1001. None,
  1002. &mut buffer,
  1003. )
  1004. .and_then(|()| {
  1005. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  1006. b.Map(0, None, Some(&mut data))
  1007. })
  1008. };
  1009. match made {
  1010. Ok(()) => Some((buffer?, data.cast())),
  1011. Err(e) => {
  1012. tracing::warn!(error = %e, size, "no upload buffer");
  1013. None
  1014. }
  1015. }
  1016. }
  1017. }
  1018. /// The swap chain formats a presented texture can be copied into: its own
  1019. /// family's.
  1020. fn swap_format(format: DXGI_FORMAT) -> Option<DXGI_FORMAT> {
  1021. Some(match format.0 {
  1022. 27..=32 => DXGI_FORMAT_R8G8B8A8_UNORM,
  1023. 87 | 90 | 91 => DXGI_FORMAT_B8G8R8A8_UNORM,
  1024. 23..=25 => DXGI_FORMAT_R10G10B10A2_UNORM,
  1025. 9..=14 => DXGI_FORMAT_R16G16B16A16_FLOAT,
  1026. _ => return None,
  1027. })
  1028. }
  1029. const BUFFERS: u32 = 2;
  1030. struct Presenter {
  1031. swap_chain: IDXGISwapChain3,
  1032. width: u32,
  1033. height: u32,
  1034. format: DXGI_FORMAT,
  1035. copy: HostList,
  1036. hwnd: HWND,
  1037. meter: Meter,
  1038. }
  1039. /// The frame rate, shown in the window's caption every second and logged
  1040. /// every few seconds.
  1041. struct Meter {
  1042. since: std::time::Instant,
  1043. frames: u32,
  1044. drawn: u64,
  1045. logged: std::time::Instant,
  1046. /// The caption the window had, once read.
  1047. caption: Option<Vec<u16>>,
  1048. }
  1049. impl Meter {
  1050. fn new() -> Self {
  1051. let now = std::time::Instant::now();
  1052. Meter {
  1053. since: now,
  1054. frames: 0,
  1055. drawn: crate::draw::drawn(),
  1056. logged: now,
  1057. caption: None,
  1058. }
  1059. }
  1060. /// Counts a presented frame.
  1061. fn frame(&mut self, hwnd: HWND) {
  1062. #[cfg(feature = "diagnostics")]
  1063. tracing::debug!(target: "victory_gpu::frame", token = crate::frame::current(), "present");
  1064. self.frames += 1;
  1065. let elapsed = self.since.elapsed();
  1066. if elapsed < std::time::Duration::from_secs(1) {
  1067. return;
  1068. }
  1069. let drawn = crate::draw::drawn();
  1070. let frames = f64::from(self.frames);
  1071. let fps = frames / elapsed.as_secs_f64();
  1072. let ms = elapsed.as_secs_f64() * 1000.0 / frames;
  1073. let draws = (drawn - self.drawn) as f64 / frames;
  1074. (self.since, self.frames, self.drawn) = (std::time::Instant::now(), 0, drawn);
  1075. // Of a frame, ms preparing submissions and ms waiting for the GPU.
  1076. let [cpu, gpu] = [0, 1].map(|i| {
  1077. SUBMISSION_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames
  1078. });
  1079. let [copy_ms, copy_mb, texture_ms, texture_mb] = [0, 1, 2, 3].map(|i| {
  1080. let scale = if i % 2 == 0 { 1e3 } else { 1e6 };
  1081. PREPARING[i].swap(0, Ordering::Relaxed) as f64 / scale / frames
  1082. });
  1083. if self.logged.elapsed() >= std::time::Duration::from_secs(5) {
  1084. self.logged = std::time::Instant::now();
  1085. tracing::info!(
  1086. "{fps:.1} fps, {ms:.1} ms/frame ({cpu:.1} preparing: copies {copy_ms:.1} ms \
  1087. {copy_mb:.1} MB, textures {texture_ms:.1} ms {texture_mb:.1} MB; {gpu:.1} on the \
  1088. GPU), {draws:.0} draws/frame"
  1089. );
  1090. #[cfg(feature = "diagnostics")]
  1091. crate::copystat::log(frames);
  1092. }
  1093. if self.caption.is_none() {
  1094. // The window's own text, read without a message.
  1095. let mut buffer = vec![0u16; 512];
  1096. // SAFETY: a window handle and a buffer of that length.
  1097. let n = unsafe { InternalGetWindowText(hwnd, &mut buffer) };
  1098. buffer.truncate(n.max(0) as usize);
  1099. self.caption = Some(buffer);
  1100. }
  1101. let Some(caption) = &self.caption else { return };
  1102. let text = format!(" | VIctory {fps:.0} fps {ms:.1} ms/frame {draws:.0} draws/frame");
  1103. let mut text: Vec<u16> = caption.iter().copied().chain(text.encode_utf16()).collect();
  1104. text.push(0);
  1105. // Setting the text waits for the window's thread (a title thread,
  1106. // which may not pump for a while), so a thread of ours does it and
  1107. // presenting never waits; it takes the newest text when free.
  1108. static PENDING: Mutex<Option<(usize, Vec<u16>)>> = Mutex::new(None);
  1109. static SETTER: std::sync::Once = std::sync::Once::new();
  1110. *PENDING.lock().unwrap_or_else(|e| e.into_inner()) = Some((hwnd.0 as usize, text));
  1111. SETTER.call_once(|| {
  1112. let _ = std::thread::Builder::new()
  1113. .name("victory-caption".into())
  1114. .spawn(|| {
  1115. loop {
  1116. let next = PENDING.lock().unwrap_or_else(|e| e.into_inner()).take();
  1117. match next {
  1118. // SAFETY: a window handle and a NUL-terminated text.
  1119. Some((hwnd, text)) => unsafe {
  1120. let _ = SetWindowTextW(HWND(hwnd as *mut _), PCWSTR(text.as_ptr()));
  1121. },
  1122. None => std::thread::sleep(std::time::Duration::from_millis(100)),
  1123. }
  1124. }
  1125. });
  1126. });
  1127. }
  1128. }
  1129. impl Host {
  1130. /// Shows `texture`, which is in `state` (a host state) and stays in it,
  1131. /// as frame `frame` (saved if captures are on). `None` if nothing was
  1132. /// shown; else, in diagnostics builds, whether the frame was black.
  1133. pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option<bool> {
  1134. // SAFETY: a live resource.
  1135. let desc = unsafe { texture.GetDesc() };
  1136. let Some(format) = swap_format(desc.Format) else {
  1137. tracing::warn!(format = desc.Format.0, "cannot present this format");
  1138. return None;
  1139. };
  1140. let (width, height) = (desc.Width as u32, desc.Height);
  1141. let mut presenter = self.presenter.lock().unwrap_or_else(|e| e.into_inner());
  1142. if presenter.is_none() {
  1143. *presenter = match self.presenter(width, height, format) {
  1144. Ok(p) => Some(p),
  1145. Err(e) => {
  1146. tracing::warn!(error = %e, "no swap chain");
  1147. return None;
  1148. }
  1149. };
  1150. }
  1151. let p = presenter.as_mut()?;
  1152. if (p.width, p.height, p.format) != (width, height, format) {
  1153. // SAFETY: no back buffer is held; every submission was waited for.
  1154. let resized = unsafe {
  1155. p.swap_chain
  1156. .ResizeBuffers(BUFFERS, width, height, format, DXGI_SWAP_CHAIN_FLAG(0))
  1157. };
  1158. match resized {
  1159. Ok(()) => (p.width, p.height, p.format) = (width, height, format),
  1160. Err(e) => {
  1161. tracing::warn!(error = %e, width, height, "swap chain not resized");
  1162. return None;
  1163. }
  1164. }
  1165. }
  1166. let state = D3D12_RESOURCE_STATES(state as i32);
  1167. // SAFETY: our swap chain, list and a live source texture.
  1168. unsafe {
  1169. let index = p.swap_chain.GetCurrentBackBufferIndex();
  1170. let Ok(back) = p.swap_chain.GetBuffer::<ID3D12Resource>(index) else {
  1171. return None;
  1172. };
  1173. p.copy.reset();
  1174. let list = &p.copy.list;
  1175. list.ResourceBarrier(&[
  1176. transition(texture, state, D3D12_RESOURCE_STATE_COPY_SOURCE),
  1177. transition(
  1178. &back,
  1179. D3D12_RESOURCE_STATE_PRESENT,
  1180. D3D12_RESOURCE_STATE_COPY_DEST,
  1181. ),
  1182. ]);
  1183. list.CopyResource(&back, texture);
  1184. #[cfg(feature = "diagnostics")]
  1185. let capture = crate::capture::wanted(frame)
  1186. .then(|| crate::capture::read_back(&self.device, list, texture))
  1187. .flatten();
  1188. #[cfg(feature = "diagnostics")]
  1189. let probe = crate::capture::probe(&self.device, list, texture);
  1190. #[cfg(not(feature = "diagnostics"))]
  1191. let _ = frame;
  1192. list.ResourceBarrier(&[
  1193. transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, state),
  1194. transition(
  1195. &back,
  1196. D3D12_RESOURCE_STATE_COPY_DEST,
  1197. D3D12_RESOURCE_STATE_PRESENT,
  1198. ),
  1199. ]);
  1200. p.copy.close();
  1201. self.execute(&[&p.copy]);
  1202. #[cfg(feature = "diagnostics")]
  1203. if let Some((buffer, footprint)) = capture {
  1204. crate::capture::save_read_back(frame, &buffer, &footprint);
  1205. }
  1206. let _ = p.swap_chain.Present(0, DXGI_PRESENT(0));
  1207. p.meter.frame(p.hwnd);
  1208. #[cfg(feature = "diagnostics")]
  1209. return Some(probe.is_some_and(|b| crate::capture::black(&b)));
  1210. #[cfg(not(feature = "diagnostics"))]
  1211. Some(false)
  1212. }
  1213. }
  1214. fn presenter(
  1215. &self,
  1216. width: u32,
  1217. height: u32,
  1218. format: DXGI_FORMAT,
  1219. ) -> windows::core::Result<Presenter> {
  1220. let hwnd = match title_window() {
  1221. Some(hwnd) => hwnd,
  1222. None => window(width, height)?,
  1223. };
  1224. // SAFETY: plain object creation for our window.
  1225. unsafe {
  1226. let factory: IDXGIFactory2 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?;
  1227. let desc = DXGI_SWAP_CHAIN_DESC1 {
  1228. Width: width,
  1229. Height: height,
  1230. Format: format,
  1231. SampleDesc: DXGI_SAMPLE_DESC {
  1232. Count: 1,
  1233. Quality: 0,
  1234. },
  1235. BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,
  1236. BufferCount: BUFFERS,
  1237. SwapEffect: DXGI_SWAP_EFFECT_FLIP_DISCARD,
  1238. ..Default::default()
  1239. };
  1240. let swap_chain = factory
  1241. .CreateSwapChainForHwnd(&self.queue, hwnd, &desc, None, None)?
  1242. .cast::<IDXGISwapChain3>()?;
  1243. let copy = self.new_list()?;
  1244. copy.close();
  1245. tracing::info!(width, height, format = format.0, "presenting to a window");
  1246. Ok(Presenter {
  1247. swap_chain,
  1248. width,
  1249. height,
  1250. format,
  1251. copy,
  1252. hwnd,
  1253. meter: Meter::new(),
  1254. })
  1255. }
  1256. }
  1257. }
  1258. /// A visible top-level window of this process: the one the title made, if
  1259. /// it made one.
  1260. fn title_window() -> Option<HWND> {
  1261. extern "system" fn visit(hwnd: HWND, found: LPARAM) -> windows::core::BOOL {
  1262. let mut process = 0;
  1263. // SAFETY: a window handle from the enumeration; `found` is ours.
  1264. unsafe {
  1265. GetWindowThreadProcessId(hwnd, Some(&mut process));
  1266. if process == windows::Win32::System::Threading::GetCurrentProcessId()
  1267. && IsWindowVisible(hwnd).as_bool()
  1268. {
  1269. *(found.0 as *mut Option<HWND>) = Some(hwnd);
  1270. return false.into();
  1271. }
  1272. }
  1273. true.into()
  1274. }
  1275. let mut found: Option<HWND> = None;
  1276. // SAFETY: the callback only writes `found`, which outlives the call.
  1277. let _ = unsafe { EnumWindows(Some(visit), LPARAM(&raw mut found as isize)) };
  1278. found
  1279. }
  1280. /// `state` without the bits the host texture's flags forbid: the console
  1281. /// lets the title name states its own resources allow (unordered access on
  1282. /// a depth target, whose host copy cannot have both).
  1283. pub(crate) fn legal_state(texture: &ID3D12Resource, state: u32) -> u32 {
  1284. // SAFETY: a plain query.
  1285. legal_for(unsafe { texture.GetDesc() }.Flags.0 as u32, state)
  1286. }
  1287. /// [`legal_state`] for a texture with resource flags `flags`.
  1288. pub(crate) fn legal_for(flags: u32, state: u32) -> u32 {
  1289. // (flag, set or clear forbids, state bits): render target, unordered
  1290. // access, depth, denied shader resource.
  1291. const FORBIDDEN: [(u32, bool, u32); 4] = [
  1292. (0x1, false, 0x4),
  1293. (0x4, false, 0x8),
  1294. (0x2, false, 0x10 | 0x20),
  1295. (0x8, true, 0x40 | 0x80),
  1296. ];
  1297. FORBIDDEN
  1298. .iter()
  1299. .filter(|&&(flag, deny, _)| (flags & flag != 0) == deny)
  1300. .fold(state, |s, &(_, _, bits)| s & !bits)
  1301. }
  1302. impl Host {
  1303. /// A buffer in system memory that the CPU maps (write-back, so reading
  1304. /// it is fast too) and shaders read and write: for host copies of title
  1305. /// memory that shaders write, which upload memory cannot be. Starts in
  1306. /// the common state (buffers move out of it implicitly).
  1307. pub(crate) fn shared_buffer(&self, size: u64) -> Option<(ID3D12Resource, *mut u8)> {
  1308. let heap = D3D12_HEAP_PROPERTIES {
  1309. Type: D3D12_HEAP_TYPE_CUSTOM,
  1310. CPUPageProperty: D3D12_CPU_PAGE_PROPERTY_WRITE_BACK,
  1311. MemoryPoolPreference: D3D12_MEMORY_POOL_L0,
  1312. ..Default::default()
  1313. };
  1314. let desc = D3D12_RESOURCE_DESC {
  1315. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1316. Width: size.max(1),
  1317. Height: 1,
  1318. DepthOrArraySize: 1,
  1319. MipLevels: 1,
  1320. SampleDesc: DXGI_SAMPLE_DESC {
  1321. Count: 1,
  1322. Quality: 0,
  1323. },
  1324. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1325. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  1326. ..Default::default()
  1327. };
  1328. let mut buffer: Option<ID3D12Resource> = None;
  1329. let mut data = std::ptr::null_mut();
  1330. // SAFETY: plain creation and mapping of a CPU-visible buffer.
  1331. let made = unsafe {
  1332. self.device
  1333. .CreateCommittedResource(
  1334. &heap,
  1335. D3D12_HEAP_FLAG_NONE,
  1336. &desc,
  1337. D3D12_RESOURCE_STATE_COMMON,
  1338. None,
  1339. &mut buffer,
  1340. )
  1341. .and_then(|()| {
  1342. let b = buffer.as_ref().ok_or_else(windows::core::Error::empty)?;
  1343. b.Map(0, None, Some(&mut data))
  1344. })
  1345. };
  1346. match made {
  1347. Ok(()) => Some((buffer?, data.cast())),
  1348. Err(e) => {
  1349. tracing::warn!(error = %e, size, "no shared buffer");
  1350. None
  1351. }
  1352. }
  1353. }
  1354. }
  1355. /// For adapters without device-removed data (the software one): the last
  1356. /// commands each list of the failed submission noted (diagnostics, with
  1357. /// `VICTORY_D3D12_DRED`).
  1358. fn last_notes(runs: &[&HostList]) -> String {
  1359. #[cfg(feature = "diagnostics")]
  1360. {
  1361. let mut text = String::new();
  1362. for (i, r) in runs.iter().enumerate() {
  1363. let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner());
  1364. for n in notes.iter().rev().take(6).rev() {
  1365. text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len()));
  1366. }
  1367. }
  1368. text
  1369. }
  1370. #[cfg(not(feature = "diagnostics"))]
  1371. {
  1372. let _ = runs;
  1373. String::new()
  1374. }
  1375. }
  1376. /// The commands that may have been running where a list stopped at
  1377. /// command `done`: those between the barriers around it (work between
  1378. /// barriers overlaps on the GPU), by kind, and what the markers just
  1379. /// before them say (`HostList::note_op`: diagnostics builds with
  1380. /// device-removed data on).
  1381. fn in_flight(history: &[D3D12_AUTO_BREADCRUMB_OP], markers: &[(u32, String)], done: usize) -> String {
  1382. let barrier = |op: &D3D12_AUTO_BREADCRUMB_OP| *op == D3D12_AUTO_BREADCRUMB_OP_RESOURCEBARRIER;
  1383. let from = history[..done].iter().rposition(barrier).map_or(0, |b| b + 1);
  1384. let to = history[done..]
  1385. .iter()
  1386. .position(barrier)
  1387. .map_or(history.len(), |b| (done + b).max(done + 1));
  1388. let mut text = format!(", commands {from}..{to} between its barriers:");
  1389. let mut shown = 0;
  1390. for i in from..to {
  1391. let op = history[i];
  1392. if op == D3D12_AUTO_BREADCRUMB_OP_SETMARKER || shown == 12 {
  1393. continue;
  1394. }
  1395. shown += 1;
  1396. let marker = i
  1397. .checked_sub(1)
  1398. .filter(|&m| history[m] == D3D12_AUTO_BREADCRUMB_OP_SETMARKER)
  1399. .and_then(|m| markers.iter().find(|(at, _)| *at as usize == m))
  1400. .map_or("no marker", |(_, s)| s.as_str());
  1401. text.push_str(&format!("; command {i} (op {}): {marker}", op.0));
  1402. }
  1403. text
  1404. }
  1405. pub(crate) fn transition(
  1406. resource: &ID3D12Resource,
  1407. before: D3D12_RESOURCE_STATES,
  1408. after: D3D12_RESOURCE_STATES,
  1409. ) -> D3D12_RESOURCE_BARRIER {
  1410. D3D12_RESOURCE_BARRIER {
  1411. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  1412. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  1413. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  1414. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  1415. // SAFETY: a borrowed pointer; the barrier never releases it.
  1416. pResource: unsafe { std::mem::transmute_copy(resource) },
  1417. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  1418. StateBefore: before,
  1419. StateAfter: after,
  1420. }),
  1421. },
  1422. }
  1423. }
  1424. /// A window of the given client size, owned by its own message thread.
  1425. fn window(width: u32, height: u32) -> windows::core::Result<HWND> {
  1426. let (sender, receiver) = std::sync::mpsc::channel();
  1427. std::thread::Builder::new()
  1428. .name("victory-window".into())
  1429. .spawn(move || {
  1430. let made = make_window(width, height);
  1431. let ok = made.is_ok();
  1432. let _ = sender.send(made.map(|h| h.0 as usize));
  1433. if ok {
  1434. pump();
  1435. }
  1436. })
  1437. .map_err(|_| windows::core::Error::empty())?;
  1438. let hwnd = receiver
  1439. .recv()
  1440. .map_err(|_| windows::core::Error::empty())??;
  1441. Ok(HWND(hwnd as *mut _))
  1442. }
  1443. extern "system" fn window_proc(
  1444. hwnd: HWND,
  1445. message: u32,
  1446. wparam: WPARAM,
  1447. lparam: LPARAM,
  1448. ) -> LRESULT {
  1449. // SAFETY: the default handling for our window.
  1450. unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
  1451. }
  1452. fn make_window(width: u32, height: u32) -> windows::core::Result<HWND> {
  1453. const CLASS: PCWSTR = w!("VIctory");
  1454. // SAFETY: registers our class once and creates a window of it.
  1455. unsafe {
  1456. let instance = GetModuleHandleW(None)?;
  1457. let class = WNDCLASSEXW {
  1458. cbSize: size_of::<WNDCLASSEXW>() as u32,
  1459. lpfnWndProc: Some(window_proc),
  1460. hInstance: instance.into(),
  1461. lpszClassName: CLASS,
  1462. hCursor: LoadCursorW(None, IDC_ARROW)?,
  1463. ..Default::default()
  1464. };
  1465. RegisterClassExW(&class);
  1466. let mut rect = RECT {
  1467. left: 0,
  1468. top: 0,
  1469. right: width as i32,
  1470. bottom: height as i32,
  1471. };
  1472. AdjustWindowRect(&mut rect, WS_OVERLAPPEDWINDOW, false)?;
  1473. CreateWindowExW(
  1474. WINDOW_EX_STYLE(0),
  1475. CLASS,
  1476. w!("VIctory"),
  1477. WS_OVERLAPPEDWINDOW | WS_VISIBLE,
  1478. CW_USEDEFAULT,
  1479. CW_USEDEFAULT,
  1480. rect.right - rect.left,
  1481. rect.bottom - rect.top,
  1482. None,
  1483. None,
  1484. Some(instance.into()),
  1485. None,
  1486. )
  1487. }
  1488. }
  1489. fn pump() {
  1490. let mut message = MSG::default();
  1491. // SAFETY: the standard message loop of this thread's window.
  1492. unsafe {
  1493. while GetMessageW(&mut message, None, 0, 0).as_bool() {
  1494. let _ = TranslateMessage(&message);
  1495. DispatchMessageW(&message);
  1496. }
  1497. }
  1498. }