host.rs 71 KB

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