host.rs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871
  1. //! Host descriptor heaps behind the title's shader-visible heaps (decision
  2. //! 0007, step 3). Translated shaders index the heaps directly at the
  3. //! title's descriptor positions, so each host heap keeps the title heap's
  4. //! order: slot `i` is made from what the title wrote at slot `i`, when it
  5. //! writes it (view creation and descriptor copies) and again when a draw
  6. //! reads it through a table and finds the slot changed.
  7. use std::sync::Mutex;
  8. use windows::Win32::Graphics::Direct3D12::*;
  9. use windows::Win32::Graphics::Dxgi::Common::*;
  10. use super::{VIEW_TAG, View, view_at};
  11. use crate::host::host;
  12. pub(crate) struct HostHeap {
  13. pub(crate) heap: ID3D12DescriptorHeap,
  14. cpu: usize,
  15. step: u32,
  16. /// Slots mirroring the title's; view heaps have [`DYNAMIC`] more.
  17. count: u32,
  18. sampler: bool,
  19. /// The record (view index and generation) each slot was last made from.
  20. made: Mutex<Vec<u64>>,
  21. /// The host resource each slot views, held while the slot does: shaders
  22. /// index heaps directly, so a slot the title has not rewritten since it
  23. /// released the resource may still be read, and a freed host resource
  24. /// read there is a GPU page fault (the console reads stale memory).
  25. kept: Mutex<Vec<Option<ID3D12Resource>>>,
  26. /// Where the search for free dynamic slots starts, and which are taken
  27. /// (by lists not yet reset).
  28. next: Mutex<(u32, Vec<bool>)>,
  29. }
  30. /// Host heaps' GPU ranges (start, bytes, bytes per slot, sampler), for
  31. /// device-removed reports: a shader indexing a heap past its end faults.
  32. static GPU_RANGES: Mutex<Vec<(u64, u64, u64, bool)>> = Mutex::new(Vec::new());
  33. /// For device-removed reports: where host GPU address `va` lies against
  34. /// the host descriptor heaps.
  35. pub(crate) fn near_heaps(va: u64) -> String {
  36. let ranges = GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner());
  37. let mut text = String::new();
  38. for &(start, bytes, step, sampler) in ranges.iter() {
  39. let kind = if sampler { "sampler" } else { "view" };
  40. let place = if va < start {
  41. format!("{:#x} below", start - va)
  42. } else if va < start + bytes {
  43. format!("inside, slot {}", (va - start) / step)
  44. } else {
  45. format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step)
  46. };
  47. text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}"));
  48. }
  49. text
  50. }
  51. /// The host's limit for shader-visible view heaps on resource binding
  52. /// tiers 1 and 2; tier 3 hardware may take more.
  53. const PORTABLE_VIEWS: u32 = 1_000_000;
  54. /// Slots past the title's in a view heap, for tables a draw needs made
  55. /// afresh (constant buffers copied per draw). A list holds the slots it
  56. /// took until it is reset (its submissions have run) or released.
  57. const DYNAMIC: u32 = 1 << 16;
  58. impl HostHeap {
  59. pub(crate) fn new(sampler: bool, count: u32) -> Option<Self> {
  60. let host = host()?;
  61. let kind = if sampler {
  62. D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER
  63. } else {
  64. D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV
  65. };
  66. let make = |count: u32| -> windows::core::Result<ID3D12DescriptorHeap> {
  67. // SAFETY: plain heap creation.
  68. unsafe {
  69. host.device
  70. .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  71. Type: kind,
  72. NumDescriptors: count,
  73. Flags: D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE,
  74. NodeMask: 0,
  75. })
  76. }
  77. };
  78. let extra = if sampler { 0 } else { DYNAMIC };
  79. let (heap, count) = match make(count + extra) {
  80. Ok(heap) => (heap, count),
  81. Err(e) if !sampler && count + extra > PORTABLE_VIEWS => {
  82. // shortcut: descriptors past the host's limit are left out;
  83. // a title that reaches them needs remapping.
  84. tracing::warn!(error = %e, count, "host view heap capped at {PORTABLE_VIEWS}");
  85. (make(PORTABLE_VIEWS).ok()?, PORTABLE_VIEWS - extra)
  86. }
  87. Err(e) => {
  88. tracing::warn!(error = %e, count, sampler, "no host descriptor heap");
  89. return None;
  90. }
  91. };
  92. // SAFETY: a live heap.
  93. let (cpu, step) = unsafe {
  94. (
  95. heap.GetCPUDescriptorHandleForHeapStart().ptr,
  96. host.device.GetDescriptorHandleIncrementSize(kind),
  97. )
  98. };
  99. tracing::debug!(count, sampler, "host descriptor heap");
  100. // SAFETY: a live shader-visible heap.
  101. let gpu = unsafe { heap.GetGPUDescriptorHandleForHeapStart().ptr };
  102. GPU_RANGES.lock().unwrap_or_else(|e| e.into_inner()).push((
  103. gpu,
  104. u64::from(count + extra) * u64::from(step),
  105. u64::from(step),
  106. sampler,
  107. ));
  108. let h = HostHeap {
  109. heap,
  110. cpu,
  111. step,
  112. count,
  113. sampler,
  114. made: Mutex::new(vec![0; count as usize]),
  115. kept: Mutex::new(vec![None; (count + extra) as usize]),
  116. next: Mutex::new((0, vec![false; DYNAMIC as usize])),
  117. };
  118. // A slot never written is undefined: shaders reading one (a slot
  119. // the title wrote in a way we do not know, or a table entry no
  120. // used-resource entry names) read a wild address. Every slot starts
  121. // null instead.
  122. let started = std::time::Instant::now();
  123. if let Err(e) = h.fill_null(kind, count + extra) {
  124. tracing::warn!(error = %e, "host descriptor heap not made null");
  125. }
  126. tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null");
  127. Some(h)
  128. }
  129. /// Makes the first `total` slots null: one null slot in a CPU-side heap,
  130. /// doubled by copies to a block, the block copied over the heap.
  131. fn fill_null(&self, kind: D3D12_DESCRIPTOR_HEAP_TYPE, total: u32) -> windows::core::Result<()> {
  132. const BLOCK: u32 = 1 << 16;
  133. let Some(host) = host() else { return Ok(()) };
  134. // SAFETY: plain heap creation and copies inside live heaps.
  135. unsafe {
  136. let block: ID3D12DescriptorHeap =
  137. host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC {
  138. Type: kind,
  139. NumDescriptors: BLOCK,
  140. ..Default::default()
  141. })?;
  142. let start = block.GetCPUDescriptorHandleForHeapStart();
  143. let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE {
  144. ptr: start.ptr + (i * self.step) as usize,
  145. };
  146. if self.sampler {
  147. null_sampler(start);
  148. } else {
  149. null_view(start);
  150. }
  151. let mut filled = 1;
  152. while filled < BLOCK {
  153. let n = filled.min(BLOCK - filled);
  154. host.device.CopyDescriptorsSimple(n, at(filled), start, kind);
  155. filled += n;
  156. }
  157. let mut done = 0;
  158. while done < total {
  159. let n = BLOCK.min(total - done);
  160. host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind);
  161. done += n;
  162. }
  163. }
  164. Ok(())
  165. }
  166. /// A plain point sampler at slot `index`, for sampler slots without a
  167. /// view.
  168. fn null_sampler(&self, index: u32) {
  169. null_sampler(self.cpu(index));
  170. }
  171. }
  172. /// A plain point sampler at `at`.
  173. fn null_sampler(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  174. let Some(host) = host() else { return };
  175. let desc = D3D12_SAMPLER_DESC {
  176. Filter: D3D12_FILTER_MIN_MAG_MIP_POINT,
  177. AddressU: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  178. AddressV: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  179. AddressW: D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
  180. MaxAnisotropy: 1,
  181. ComparisonFunc: D3D12_COMPARISON_FUNC_NEVER,
  182. ..Default::default()
  183. };
  184. // SAFETY: a slot of a sampler heap of ours.
  185. unsafe { host.device.CreateSampler(&desc, at) };
  186. }
  187. impl HostHeap {
  188. /// `n` consecutive free dynamic slots (view heaps only), taken until
  189. /// [`HostHeap::release`]: the first's index.
  190. pub(crate) fn dynamic(&self, n: u32) -> Option<u32> {
  191. if self.sampler || n == 0 || n > DYNAMIC {
  192. return None;
  193. }
  194. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  195. let (next, taken) = &mut *guard;
  196. let n = n as usize;
  197. // Search from `next` on, then from the start.
  198. let starts = (*next as usize..DYNAMIC as usize).chain(0..*next as usize);
  199. let mut run = 0;
  200. let mut found = None;
  201. let mut last = usize::MAX;
  202. for at in starts {
  203. // A run cannot wrap past the end.
  204. if at != last.wrapping_add(1) {
  205. run = 0;
  206. }
  207. last = at;
  208. run = if taken[at] { 0 } else { run + 1 };
  209. if run == n {
  210. found = Some(at + 1 - n);
  211. break;
  212. }
  213. }
  214. let Some(first) = found else {
  215. static ONCE: std::sync::Once = std::sync::Once::new();
  216. ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made"));
  217. return None;
  218. };
  219. taken[first..first + n].fill(true);
  220. *next = ((first + n) % DYNAMIC as usize) as u32;
  221. Some(self.count + first as u32)
  222. }
  223. /// The title slots this heap has host slots for; fewer than the title's
  224. /// when the host caps its size.
  225. pub(crate) fn count(&self) -> u32 {
  226. self.count
  227. }
  228. /// Gives back `n` dynamic slots from `first` (an index [`dynamic`]
  229. /// returned).
  230. ///
  231. /// [`dynamic`]: HostHeap::dynamic
  232. pub(crate) fn release(&self, first: u32, n: u32) {
  233. let Some(at) = first.checked_sub(self.count) else {
  234. return;
  235. };
  236. let mut guard = self.next.lock().unwrap_or_else(|e| e.into_inner());
  237. let end = (at + n).min(DYNAMIC) as usize;
  238. if let Some(slots) = guard.1.get_mut(at as usize..end) {
  239. slots.fill(false);
  240. }
  241. }
  242. /// Makes slot `index` (a dynamic one) from `view`; a null view if the
  243. /// host cannot.
  244. pub(crate) fn make_at(&self, index: u32, view: &View) {
  245. let kept = make(view, self.cpu(index));
  246. if kept.is_none() {
  247. null_for(view, self.cpu(index));
  248. }
  249. self.keep(index, kept.flatten());
  250. }
  251. /// Makes slot `index` read nothing: a null view, or a plain sampler.
  252. pub(crate) fn make_null(&self, index: u32) {
  253. if self.sampler {
  254. self.null_sampler(index);
  255. } else {
  256. null_view(self.cpu(index));
  257. }
  258. self.keep(index, None);
  259. }
  260. /// Slot `index` now views `resource` (or nothing of the host's).
  261. fn keep(&self, index: u32, resource: Option<ID3D12Resource>) {
  262. let mut kept = self.kept.lock().unwrap_or_else(|e| e.into_inner());
  263. if let Some(slot) = kept.get_mut(index as usize) {
  264. *slot = resource;
  265. }
  266. }
  267. /// Makes slot `index` (a dynamic one) a constant buffer view of host
  268. /// memory (the list's own, which it holds).
  269. pub(crate) fn constant_at(&self, index: u32, gpu: u64, size: u32) {
  270. self.keep(index, None);
  271. let Some(host) = host() else { return };
  272. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  273. BufferLocation: gpu,
  274. SizeInBytes: size.next_multiple_of(256),
  275. };
  276. // SAFETY: a slot of our heap; the memory is the caller's.
  277. unsafe {
  278. host.device
  279. .CreateConstantBufferView(Some(&desc), self.cpu(index))
  280. };
  281. }
  282. fn cpu(&self, index: u32) -> D3D12_CPU_DESCRIPTOR_HANDLE {
  283. D3D12_CPU_DESCRIPTOR_HANDLE {
  284. ptr: self.cpu + index as usize * self.step as usize,
  285. }
  286. }
  287. /// Makes host slot `index` from the record the title has at `handle`
  288. /// if it changed since, and returns the view recorded there. Buffer
  289. /// views are made only for draws (`for_draw`), which also copy their
  290. /// data: a host copy of a buffer is made on first use.
  291. pub(crate) fn mirror(&self, index: u32, handle: u64, for_draw: bool) -> Option<View> {
  292. if index >= self.count {
  293. // Diagnostic (NVIDIA heap cap): the highest title slot past the
  294. // host heap seen so far.
  295. static HIGHEST: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  296. if HIGHEST.fetch_max(index, std::sync::atomic::Ordering::Relaxed) < index {
  297. tracing::warn!(
  298. index,
  299. count = self.count,
  300. for_draw,
  301. "title slot past the host heap"
  302. );
  303. }
  304. return None;
  305. }
  306. // SAFETY: the handle is a descriptor slot in title memory.
  307. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  308. // Generations start at 1, so a made slot's key is never 0.
  309. let key = u64::from(generation) << 32 | u64::from(i);
  310. let mut made = self.made.lock().unwrap_or_else(|e| e.into_inner());
  311. let view = (tag == VIEW_TAG).then(|| view_at(i, generation)).flatten();
  312. let Some(view) = view else {
  313. // Not a view of ours (never written, or of a resource the
  314. // title released): nothing to read.
  315. if made[index as usize] != 0 {
  316. made[index as usize] = 0;
  317. self.make_null(index);
  318. }
  319. return None;
  320. };
  321. if made[index as usize] != key {
  322. let later = !for_draw && view.is_buffer();
  323. made[index as usize] = if later { 0 } else { key };
  324. let kept = if later {
  325. None
  326. } else {
  327. make(&view, self.cpu(index))
  328. };
  329. if kept.is_none() && !self.sampler {
  330. null_for(&view, self.cpu(index));
  331. }
  332. self.keep(index, kept.flatten());
  333. }
  334. Some(view)
  335. }
  336. /// The view host slot `index` was made from, in a few words, with the
  337. /// title and host addresses of a buffer view (diagnostics). "null" for
  338. /// a slot never made or left null.
  339. #[cfg(feature = "diagnostics")]
  340. pub(crate) fn describe_slot(&self, index: u32) -> Option<String> {
  341. let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?;
  342. if key == 0 {
  343. return Some("null".into());
  344. }
  345. let view = view_at(key as u32, (key >> 32) as u32)?;
  346. let mut text: String = format!("{view:?}").chars().take(120).collect();
  347. if let Some((address, len)) = buffer_range(&view) {
  348. let host = crate::shadow::find(address, len.max(1)).map(|s| s.gpu(address));
  349. text.push_str(&format!(" title {address:#x}+{len:#x} host {host:#x?}"));
  350. }
  351. Some(text)
  352. }
  353. }
  354. /// Logs `what` the first time it happens.
  355. macro_rules! once {
  356. ($($arg:tt)*) => {{
  357. static ONCE: std::sync::Once = std::sync::Once::new();
  358. ONCE.call_once(|| tracing::warn!($($arg)*));
  359. }};
  360. }
  361. /// A view description from its words, with the format as the host has it.
  362. fn srv_desc(words: &[u32; 10]) -> D3D12_SHADER_RESOURCE_VIEW_DESC {
  363. let mut words = *words;
  364. words[0] = crate::resource::pc_format(words[0]);
  365. // SAFETY: 40 bytes in the host's layout.
  366. unsafe {
  367. std::ptr::from_ref(&words)
  368. .cast::<D3D12_SHADER_RESOURCE_VIEW_DESC>()
  369. .read_unaligned()
  370. }
  371. }
  372. fn uav_desc(words: &[u32; 10]) -> D3D12_UNORDERED_ACCESS_VIEW_DESC {
  373. let mut words = *words;
  374. words[0] = crate::resource::pc_format(words[0]);
  375. // SAFETY: 40 bytes in the host's layout.
  376. unsafe {
  377. std::ptr::from_ref(&words)
  378. .cast::<D3D12_UNORDERED_ACCESS_VIEW_DESC>()
  379. .read_unaligned()
  380. }
  381. }
  382. /// A buffer view of title memory at `address` on its host copy: the first
  383. /// element moves by the copy's offset.
  384. /// Bytes per element of a buffer view.
  385. fn element_size(desc: &D3D12_SHADER_RESOURCE_VIEW_DESC) -> u64 {
  386. // SAFETY: a buffer view's union member.
  387. let buffer = unsafe { desc.Anonymous.Buffer };
  388. if buffer.StructureByteStride > 0 {
  389. u64::from(buffer.StructureByteStride)
  390. } else if buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0 {
  391. 4
  392. } else {
  393. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  394. }
  395. }
  396. /// The title memory a buffer shader or unordered access view reads: its
  397. /// address and length.
  398. pub(crate) fn buffer_range(view: &View) -> Option<(u64, u64)> {
  399. let (base, words): (u64, &[u32; 10]) = match view {
  400. View::Shader(r, Some(desc)) => (
  401. crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64,
  402. desc,
  403. ),
  404. View::Placed(false, resource, desc) if resource[0] == 1 => (
  405. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  406. desc[..10].try_into().ok()?,
  407. ),
  408. View::Unordered(r, _, Some(desc)) => {
  409. let base = crate::resource::buffer_bytes(*r as crate::object::This)?.0 as u64;
  410. return unordered_range(base, desc);
  411. }
  412. View::Placed(true, resource, desc) if resource[0] == 1 => {
  413. let base = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  414. return unordered_range(base, desc[..10].try_into().ok()?);
  415. }
  416. _ => return None,
  417. };
  418. let desc = srv_desc(words);
  419. let element = element_size(&desc);
  420. // SAFETY: a buffer view's union member.
  421. let buffer = unsafe { desc.Anonymous.Buffer };
  422. Some((
  423. base + buffer.FirstElement * element,
  424. u64::from(buffer.NumElements) * element,
  425. ))
  426. }
  427. /// [`buffer_range`] of an unordered access view of memory at `base`.
  428. fn unordered_range(base: u64, words: &[u32; 10]) -> Option<(u64, u64)> {
  429. let desc = uav_desc(words);
  430. // SAFETY: a buffer view's union member.
  431. let buffer = unsafe { desc.Anonymous.Buffer };
  432. let element = if buffer.StructureByteStride > 0 {
  433. u64::from(buffer.StructureByteStride)
  434. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  435. 4
  436. } else {
  437. crate::resource::element(desc.Format.0 as u32)?.0
  438. };
  439. Some((
  440. base + buffer.FirstElement * element,
  441. u64::from(buffer.NumElements) * element,
  442. ))
  443. }
  444. /// The host resource a slot made by [`make`] views, if any.
  445. type Kept = Option<ID3D12Resource>;
  446. fn buffer_srv(
  447. address: u64,
  448. len: u64,
  449. mut desc: D3D12_SHADER_RESOURCE_VIEW_DESC,
  450. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  451. ) -> Option<Kept> {
  452. let shadow = crate::shadow::find(address, len)?;
  453. let element = element_size(&desc);
  454. // SAFETY: a buffer view's union member.
  455. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  456. let offset = shadow.offset(address);
  457. if element == 0 || offset % element != 0 {
  458. once!(
  459. offset,
  460. element,
  461. "buffer view not on an element of its host copy"
  462. );
  463. return None;
  464. }
  465. buffer.FirstElement += offset / element;
  466. let host = host()?;
  467. // SAFETY: a live buffer and a slot of our heap.
  468. unsafe {
  469. host.device
  470. .CreateShaderResourceView(&shadow.buffer, Some(&desc), at)
  471. };
  472. Some(Some(shadow.buffer.clone()))
  473. }
  474. /// An unordered access view of title buffer memory at `address` (`len`
  475. /// bytes) on its host copy, as [`buffer_srv`]; false if the copy cannot be
  476. /// written by shaders (upload memory).
  477. /// shortcut: what shaders write stays in the host copy; title memory (and
  478. /// so the CPU, and copies run on the CPU) does not see it.
  479. fn buffer_uav(
  480. address: u64,
  481. len: u64,
  482. mut desc: D3D12_UNORDERED_ACCESS_VIEW_DESC,
  483. at: D3D12_CPU_DESCRIPTOR_HANDLE,
  484. ) -> Option<Kept> {
  485. let shadow = crate::shadow::find(address, len)?;
  486. // SAFETY: a live buffer.
  487. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  488. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  489. once!("unordered access to a buffer whose host copy shaders cannot write");
  490. return None;
  491. }
  492. // SAFETY: a buffer view's union member.
  493. let buffer = unsafe { &mut desc.Anonymous.Buffer };
  494. let element = if buffer.StructureByteStride > 0 {
  495. u64::from(buffer.StructureByteStride)
  496. } else if buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0 {
  497. 4
  498. } else {
  499. crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes)
  500. };
  501. let offset = shadow.offset(address);
  502. if element == 0 || offset % element != 0 {
  503. once!(offset, element, "unordered buffer view not on an element of its host copy");
  504. return None;
  505. }
  506. buffer.FirstElement += offset / element;
  507. buffer.CounterOffsetInBytes = 0;
  508. let host = host()?;
  509. // SAFETY: a live buffer and a slot of our heap.
  510. unsafe {
  511. host.device
  512. .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at)
  513. };
  514. Some(Some(shadow.buffer.clone()))
  515. }
  516. /// Whether the host can make a shader (or unordered access) view of
  517. /// `texture` in `format` (none: the texture's own). The console allows any
  518. /// view; the host refuses (and removes the device for) views without the
  519. /// resource's permission, of typed depth, and in another format than a
  520. /// typed resource's. A view of a typed texture in another format of its
  521. /// family takes the texture's format.
  522. /// shortcut: such a view (sRGB of UNORM, say) reads without its
  523. /// conversion; cast with castable formats if colors come out wrong.
  524. fn fits(texture: &ID3D12Resource, mut format: Option<&mut DXGI_FORMAT>, unordered: bool) -> bool {
  525. use crate::resource::{DEPTH_FORMATS, family};
  526. // SAFETY: a live resource.
  527. let d = unsafe { texture.GetDesc() };
  528. let allowed = if unordered {
  529. d.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0
  530. } else {
  531. d.Flags.0 & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE.0 == 0
  532. };
  533. let own = d.Format.0 as u32;
  534. if !allowed || DEPTH_FORMATS.iter().any(|&(typed, _)| typed == own) {
  535. once!(
  536. unordered,
  537. format = own,
  538. flags = d.Flags.0,
  539. "view the host does not allow"
  540. );
  541. return false;
  542. }
  543. // Every family has more than one format, its typeless one first.
  544. let typeless = family(own) == own && family(own + 1) == own;
  545. if let Some(format) = format.as_deref_mut()
  546. && unordered
  547. && let Some(&(_, linear)) = crate::resource::SRGB
  548. .iter()
  549. .find(|&&(s, _)| s == format.0 as u32)
  550. {
  551. format.0 = linear as i32;
  552. }
  553. let view = format.as_ref().map_or(0, |f| f.0 as u32);
  554. if view == 0 {
  555. return !typeless;
  556. }
  557. if family(view) != family(own) {
  558. once!(view, own, "view format of another family");
  559. return false;
  560. }
  561. if let Some(format) = format
  562. && !typeless
  563. {
  564. *format = d.Format;
  565. }
  566. true
  567. }
  568. /// Makes the host descriptor for `view` at `at`: the host resource it
  569. /// views, or `None` if it cannot.
  570. fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<Kept> {
  571. let host = host()?;
  572. let device = &host.device;
  573. match view {
  574. &View::Constant(address, size) => {
  575. let shadow = crate::shadow::find(address, u64::from(size))?;
  576. let gpu = shadow.gpu(address);
  577. if gpu % 256 != 0 {
  578. once!(
  579. address = format_args!("{address:#x}"),
  580. "constant buffer not 256-byte aligned on the host"
  581. );
  582. return None;
  583. }
  584. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC {
  585. BufferLocation: gpu,
  586. SizeInBytes: size.next_multiple_of(256),
  587. };
  588. // SAFETY: a slot of our heap; the range lies in the host copy.
  589. unsafe { device.CreateConstantBufferView(Some(&desc), at) };
  590. Some(Some(shadow.buffer.clone()))
  591. }
  592. View::Shader(resource, desc) => {
  593. let resource = *resource as crate::object::This;
  594. if let Some(texture) = crate::resource::host_resource(resource) {
  595. let mut desc = desc.as_ref().map(srv_desc);
  596. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), false) {
  597. return None;
  598. }
  599. // SAFETY: a live texture and a slot of our heap.
  600. unsafe {
  601. device.CreateShaderResourceView(
  602. texture,
  603. desc.as_ref().map(std::ptr::from_ref),
  604. at,
  605. )
  606. };
  607. Some(Some(texture.clone()))
  608. } else if let (Some((data, len)), Some(desc)) =
  609. (crate::resource::buffer_bytes(resource), desc)
  610. {
  611. buffer_srv(data as u64, len, srv_desc(desc), at)
  612. } else {
  613. None
  614. }
  615. }
  616. View::Unordered(resource, _counter, desc) => {
  617. let resource = *resource as crate::object::This;
  618. let Some(texture) = crate::resource::host_resource(resource) else {
  619. return match (crate::resource::buffer_bytes(resource), desc) {
  620. (Some((data, len)), Some(desc)) => {
  621. buffer_uav(data as u64, len, uav_desc(desc), at)
  622. }
  623. _ => None,
  624. };
  625. };
  626. let mut desc = desc.as_ref().map(uav_desc);
  627. if !fits(texture, desc.as_mut().map(|d| &mut d.Format), true) {
  628. return None;
  629. }
  630. // SAFETY: a live texture and a slot of our heap.
  631. unsafe {
  632. device.CreateUnorderedAccessView(
  633. texture,
  634. None::<&ID3D12Resource>,
  635. desc.as_ref().map(std::ptr::from_ref),
  636. at,
  637. )
  638. };
  639. Some(Some(texture.clone()))
  640. }
  641. View::Sampler(words) => {
  642. // SAFETY: 13 words in the host's layout.
  643. let desc = unsafe {
  644. std::ptr::from_ref(words)
  645. .cast::<D3D12_SAMPLER_DESC>()
  646. .read_unaligned()
  647. };
  648. // SAFETY: a slot of our sampler heap.
  649. unsafe { device.CreateSampler(&desc, at) };
  650. Some(None)
  651. }
  652. View::ConsoleSampler(words) => {
  653. let desc = crate::sampler::console(words);
  654. // SAFETY: a slot of our sampler heap.
  655. unsafe { device.CreateSampler(&desc, at) };
  656. Some(None)
  657. }
  658. View::Placed(unordered, resource, desc) => {
  659. if let Some(view) = placed_texture(view) {
  660. return make(&view, at);
  661. }
  662. const BUFFER: u32 = 1;
  663. if resource[0] != BUFFER {
  664. // shortcut: unordered access to a texture the title placed
  665. // itself is not mirrored; give it a resource as shader
  666. // views of such textures get when a dispatch writes one.
  667. once!(dimension = resource[0], "placed unordered texture view not mirrored");
  668. return None;
  669. }
  670. // The resource description's width, after the alignment.
  671. let len = u64::from(resource[4]) | u64::from(resource[5]) << 32;
  672. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  673. let words: &[u32; 10] = desc[..10].try_into().unwrap_or(&[0; 10]);
  674. if *unordered {
  675. buffer_uav(address, len, uav_desc(words), at)
  676. } else {
  677. buffer_srv(address, len, srv_desc(words), at)
  678. }
  679. }
  680. }
  681. }
  682. /// A shader view of a texture the title placed in memory itself, as a view
  683. /// of the resource made for that memory (on first use).
  684. pub(crate) fn placed_texture(view: &View) -> Option<View> {
  685. const BUFFER: u32 = 1;
  686. let View::Placed(false, resource, desc) = view else {
  687. return None;
  688. };
  689. if resource[0] == BUFFER {
  690. return None;
  691. }
  692. let address = u64::from(desc[10]) | u64::from(desc[11]) << 32;
  693. let texture = crate::resource::texture_at(address, resource)?;
  694. Some(View::Shader(texture as usize, desc[..10].try_into().ok()))
  695. }
  696. /// A null view of the kind `view` is, for a slot whose view the host
  697. /// cannot make: unordered access (to a buffer or a 2D texture) or a shader
  698. /// view. Writes to it are dropped, reads give zeros.
  699. fn null_for(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  700. let Some(host) = host() else { return };
  701. let is_buffer = |r: &usize| crate::resource::buffer_bytes(*r as crate::object::This).is_some();
  702. let buffer = match view {
  703. View::Unordered(r, _, desc) => is_buffer(r) || desc.is_some_and(|d| d[1] == 1),
  704. View::Placed(true, resource, _) => resource[0] == 1,
  705. // Shader views of buffers read nothing through a null buffer view:
  706. // a null 2D view where the shader expects a buffer is a mismatch
  707. // the hardware does not survive in general (GPU-based validation
  708. // reports it).
  709. View::Shader(r, desc) if is_buffer(r) || desc.is_some_and(|d| d[1] == 1) => {
  710. return null_buffer_view(at);
  711. }
  712. View::Placed(false, resource, _) if resource[0] == 1 => return null_buffer_view(at),
  713. // Textures: a null view of the title's dimension (1D, arrays, 3D,
  714. // cubes), not always 2D.
  715. View::Shader(_, Some(desc)) => return null_like(desc, at),
  716. View::Placed(false, _, desc) => {
  717. return null_like(desc[..10].try_into().unwrap_or(&[0; 10]), at);
  718. }
  719. View::Constant(..) => {
  720. let desc = D3D12_CONSTANT_BUFFER_VIEW_DESC::default();
  721. // SAFETY: a slot of our heap; a zero location makes a null view.
  722. return unsafe { host.device.CreateConstantBufferView(Some(&desc), at) };
  723. }
  724. _ => return null_view(at),
  725. };
  726. let desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
  727. Format: DXGI_FORMAT_R32_UINT,
  728. ViewDimension: if buffer {
  729. D3D12_UAV_DIMENSION_BUFFER
  730. } else {
  731. D3D12_UAV_DIMENSION_TEXTURE2D
  732. },
  733. ..Default::default()
  734. };
  735. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  736. unsafe {
  737. host.device.CreateUnorderedAccessView(
  738. None::<&ID3D12Resource>,
  739. None::<&ID3D12Resource>,
  740. Some(&desc),
  741. at,
  742. )
  743. };
  744. }
  745. /// A buffer view that reads zeros (raw, as translated shaders mostly read
  746. /// buffers).
  747. fn null_buffer_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  748. let Some(host) = host() else { return };
  749. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  750. Format: DXGI_FORMAT_R32_TYPELESS,
  751. ViewDimension: D3D12_SRV_DIMENSION_BUFFER,
  752. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  753. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  754. Buffer: D3D12_BUFFER_SRV {
  755. NumElements: 1,
  756. Flags: D3D12_BUFFER_SRV_FLAG_RAW,
  757. ..Default::default()
  758. },
  759. },
  760. };
  761. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  762. unsafe {
  763. host.device
  764. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  765. };
  766. }
  767. /// A texture view that reads zeros with the dimension (and mip and array
  768. /// counts) of the title's description `words`; 2D if it names none.
  769. fn null_like(words: &[u32; 10], at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  770. const TEXTURES: std::ops::RangeInclusive<u32> = 2..=10;
  771. if !TEXTURES.contains(&words[1]) {
  772. return null_view(at);
  773. }
  774. let Some(host) = host() else { return };
  775. // One mip, one slice or cube, plane 0: fields a null view still checks.
  776. let mut w = [0u32; 10];
  777. w[1] = words[1];
  778. match words[1] {
  779. 6 => {}
  780. 7 => w[5] = 1,
  781. 3 | 5 | 10 => (w[5], w[7]) = (1, 1),
  782. _ => w[5] = 1,
  783. }
  784. let mut desc = srv_desc(&w);
  785. desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
  786. desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  787. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  788. unsafe {
  789. host.device
  790. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  791. };
  792. }
  793. /// A view that reads zeros, for slots whose view the host cannot make.
  794. fn null_view(at: D3D12_CPU_DESCRIPTOR_HANDLE) {
  795. let Some(host) = host() else { return };
  796. let desc = D3D12_SHADER_RESOURCE_VIEW_DESC {
  797. Format: DXGI_FORMAT_R8G8B8A8_UNORM,
  798. ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D,
  799. Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING,
  800. Anonymous: D3D12_SHADER_RESOURCE_VIEW_DESC_0 {
  801. Texture2D: D3D12_TEX2D_SRV {
  802. MipLevels: 1,
  803. ..Default::default()
  804. },
  805. },
  806. };
  807. // SAFETY: a slot of our heap; a null resource is allowed with a desc.
  808. unsafe {
  809. host.device
  810. .CreateShaderResourceView(None::<&ID3D12Resource>, Some(&desc), at)
  811. };
  812. }
  813. #[cfg(test)]
  814. mod tests {
  815. use super::*;
  816. /// Dynamic slots stay taken until given back, and runs do not wrap.
  817. #[test]
  818. fn dynamic_slots_are_held_until_released() {
  819. let Some(heap) = HostHeap::new(false, 4) else {
  820. return; // no host GPU
  821. };
  822. let a = heap.dynamic(DYNAMIC - 100).unwrap();
  823. let b = heap.dynamic(60).unwrap();
  824. assert_eq!((a, b), (4, 4 + DYNAMIC - 100));
  825. // 40 left at the end: 50 do not fit until something is given back.
  826. assert_eq!(heap.dynamic(50), None);
  827. heap.release(a, 50);
  828. assert_eq!(heap.dynamic(50), Some(4));
  829. assert_eq!(heap.dynamic(40), Some(4 + DYNAMIC - 40));
  830. }
  831. }