descriptor.rs 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204
  1. //! Descriptor heaps: zeroed memory, with handles that are plain addresses
  2. //! (CPU and GPU alike, as on the console).
  3. //!
  4. //! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's
  5. //! image and sampler descriptors, so a title that copies descriptors itself
  6. //! moves whole ones. Render target and depth views are ours alone; 128 bytes
  7. //! leaves room for whatever stride a title assumes.
  8. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  9. use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid};
  10. use crate::resource::{Memory, PAGEABLE_IIDS};
  11. #[cfg(windows)]
  12. pub(crate) mod host;
  13. const HEAP_IIDS: [Iid; 4] = [
  14. guid(
  15. 0x8efb471d,
  16. 0x616c,
  17. 0x4f49,
  18. [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51],
  19. ),
  20. PAGEABLE_IIDS[0],
  21. PAGEABLE_IIDS[1],
  22. PAGEABLE_IIDS[2],
  23. ];
  24. #[repr(C)]
  25. #[derive(Debug, Clone, Copy)]
  26. pub(crate) struct HeapDesc {
  27. kind: u32,
  28. count: u32,
  29. flags: u32,
  30. nodes: u32,
  31. }
  32. /// Newer titles (the title) pass the description followed by
  33. /// memory of their own for the descriptors: an address and its size in
  34. /// bytes, or a null address to have the heap allocate (inferred from the
  35. /// title's call sites; older titles pass the plain description).
  36. #[repr(C)]
  37. #[derive(Debug, Clone, Copy)]
  38. struct Placement {
  39. address: u64,
  40. size: u64,
  41. }
  42. #[repr(C)]
  43. pub(crate) struct Heap {
  44. object: Object,
  45. desc: HeapDesc,
  46. /// The first descriptor: in `memory`, or in the title's own memory.
  47. pub(crate) start: u64,
  48. memory: Option<Memory>,
  49. /// Shader-visible view and sampler heaps get a host heap with the same
  50. /// descriptor order when a draw first uses them (decision 0007, step
  51. /// 3); slots written before wait in `pending`.
  52. #[cfg(windows)]
  53. host: std::sync::OnceLock<Option<host::HostHeap>>,
  54. #[cfg(windows)]
  55. pending: std::sync::Mutex<Vec<u32>>,
  56. }
  57. pub(crate) fn heap<'a>(this: This) -> &'a Heap {
  58. // SAFETY: called from descriptor heap methods only.
  59. unsafe { &*this.cast::<Heap>() }
  60. }
  61. impl Heap {
  62. /// Whether this is a sampler heap.
  63. pub(crate) fn samplers(&self) -> bool {
  64. self.desc.kind == SAMPLERS
  65. }
  66. /// The host heap, made on first use from what the title wrote so far.
  67. /// Made late because a host view heap the size of the title's
  68. /// costs over 100 MB of commit, which its boot needs for its page pool.
  69. #[cfg(windows)]
  70. pub(crate) fn host(&self) -> Option<&host::HostHeap> {
  71. if let Some(h) = self.host.get() {
  72. return h.as_ref();
  73. }
  74. if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS)
  75. {
  76. return None;
  77. }
  78. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  79. // A recorder can take the fast path as soon as the OnceLock is
  80. // initialized. Publish only after replaying the queued writes.
  81. self.host
  82. .get_or_init(|| {
  83. let step = u64::from(increment(self.desc.kind)?);
  84. let h = host::HostHeap::new(self.samplers(), self.desc.count)?;
  85. for i in pending.drain(..) {
  86. h.mirror(i, self.start + u64::from(i) * step, false);
  87. }
  88. Some(h)
  89. })
  90. .as_ref()
  91. }
  92. /// The handle of descriptor `index` of this heap.
  93. #[cfg(windows)]
  94. pub(crate) fn handle(&self, index: u32) -> Option<u64> {
  95. let step = u64::from(increment(self.desc.kind)?);
  96. (index < self.desc.count).then(|| self.start + u64::from(index) * step)
  97. }
  98. /// The descriptor index of `handle` in this heap, if it lies in it.
  99. pub(crate) fn index(&self, handle: u64) -> Option<u32> {
  100. let step = u64::from(increment(self.desc.kind)?);
  101. let at = handle.checked_sub(self.start)?;
  102. let index = at / step;
  103. (index < u64::from(self.desc.count)).then_some(index as u32)
  104. }
  105. }
  106. const VIEWS_KIND: u32 = 0;
  107. const SAMPLERS: u32 = 1;
  108. const SHADER_VISIBLE: u32 = 1;
  109. /// Shader-visible heaps by address range, for mirroring descriptor writes:
  110. /// start, end, heap.
  111. #[cfg(windows)]
  112. static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new());
  113. /// The shader-visible heap holding `handle`, and the descriptor's index.
  114. #[cfg(windows)]
  115. fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> {
  116. let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  117. let &(_, _, at) = heaps
  118. .iter()
  119. .find(|&&(start, end, _)| (start..end).contains(&handle))?;
  120. // SAFETY: registered heaps are live (removed when dropped).
  121. let heap = unsafe { &*(at as *const Heap) };
  122. Some((heap, heap.index(handle)?))
  123. }
  124. /// Makes the host descriptor for what the title wrote at `handle`, if it
  125. /// is in a shader-visible heap.
  126. #[cfg(windows)]
  127. fn mirror(handle: u64) {
  128. let Some((heap, index)) = shader_slot(handle) else {
  129. return;
  130. };
  131. let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner());
  132. match heap.host.get() {
  133. None => pending.push(index),
  134. Some(host) => {
  135. drop(pending);
  136. if let Some(host) = host {
  137. host.mirror(index, handle, false);
  138. }
  139. }
  140. }
  141. }
  142. /// Gives back dynamic slots of the host heap behind the title heap at
  143. /// `heap`, if that heap still exists.
  144. #[cfg(windows)]
  145. pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
  146. let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  147. if heaps.iter().any(|&(_, _, h)| h == heap)
  148. // SAFETY: registered heaps are live (removed when dropped).
  149. && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
  150. {
  151. host.release(first, n);
  152. }
  153. }
  154. /// Makes dynamic slot `index` of the host heap behind the title heap at
  155. /// `heap`, if that heap still exists, the constant buffer view of `size`
  156. /// bytes at `gpu`.
  157. #[cfg(windows)]
  158. pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) {
  159. let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  160. if heaps.iter().any(|&(_, _, h)| h == heap)
  161. // SAFETY: registered heaps are live (removed when dropped).
  162. && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
  163. {
  164. host.constant_at(index, gpu, size);
  165. }
  166. }
  167. #[cfg(windows)]
  168. impl Drop for Heap {
  169. fn drop(&mut self) {
  170. let at = std::ptr::from_ref::<Heap>(self) as usize;
  171. let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  172. heaps.retain(|&(_, _, h)| h != at);
  173. }
  174. }
  175. /// Bytes per descriptor, by heap type (views, samplers, render targets,
  176. /// depth).
  177. fn increment(kind: u32) -> Option<u32> {
  178. [32, 16, 128, 128].get(kind as usize).copied()
  179. }
  180. /// Device method.
  181. pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 {
  182. increment(kind).unwrap_or(0)
  183. }
  184. /// What our render target views hold: the resource and the view
  185. /// description, turned into a host view when a command uses them.
  186. #[repr(C)]
  187. #[derive(Clone, Copy)]
  188. pub(crate) struct RtvRecord {
  189. tag: u32,
  190. described: u32,
  191. pub(crate) resource: This,
  192. desc: [u32; 6],
  193. }
  194. const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV");
  195. const _: () = assert!(size_of::<RtvRecord>() <= 112);
  196. impl RtvRecord {
  197. /// The view description in the host's type (the same layout).
  198. #[cfg(windows)]
  199. pub(crate) fn desc(
  200. &self,
  201. ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> {
  202. const TEXTURE_2D: u32 = 4;
  203. self.host_desc(TEXTURE_2D)
  204. }
  205. /// The depth view description in the host's type (the same layout).
  206. #[cfg(windows)]
  207. pub(crate) fn depth_desc(
  208. &self,
  209. ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC> {
  210. const TEXTURE_2D: u32 = 3;
  211. self.host_desc(TEXTURE_2D)
  212. }
  213. /// The description words as a host type, the format as the host has it.
  214. /// Without one, a typeless host copy gets a 2D view (`dimension`) in
  215. /// the title's format, which the host needs spelled out.
  216. #[cfg(windows)]
  217. fn host_desc<T>(&self, dimension: u32) -> Option<T> {
  218. assert!(size_of::<T>() <= size_of::<[u32; 6]>());
  219. let mut words = if self.described != 0 {
  220. self.desc
  221. } else {
  222. [
  223. crate::resource::view_format(self.resource)?,
  224. dimension,
  225. 0,
  226. 0,
  227. 0,
  228. 0,
  229. ]
  230. };
  231. // A target or depth view: of a target, in its stand-in format.
  232. words[0] = crate::resource::target_format(crate::resource::pc_format(words[0]));
  233. // SAFETY: both host view descriptions are 24 bytes in this layout.
  234. Some(unsafe { (&raw const words).cast::<T>().read_unaligned() })
  235. }
  236. }
  237. /// Device method: records the view at `handle` (descriptor memory).
  238. pub(crate) extern "system" fn create_rtv(
  239. _: This,
  240. resource: This,
  241. desc: *const [u32; 6],
  242. handle: u64,
  243. ) {
  244. if handle == 0 {
  245. return;
  246. }
  247. // SAFETY: the title passes a description or null.
  248. let described = unsafe { desc.as_ref() };
  249. let record = RtvRecord {
  250. tag: RTV_TAG,
  251. described: u32::from(described.is_some()),
  252. resource,
  253. desc: described.copied().unwrap_or_default(),
  254. };
  255. // SAFETY: the handle is a descriptor slot, at least 112 bytes.
  256. unsafe { (handle as *mut RtvRecord).write_unaligned(record) };
  257. }
  258. /// Device method: a depth view, recorded as render target views are.
  259. pub(crate) extern "system" fn create_dsv(
  260. this: This,
  261. resource: This,
  262. desc: *const [u32; 6],
  263. handle: u64,
  264. ) {
  265. create_rtv(this, resource, desc, handle);
  266. if handle != 0 {
  267. // SAFETY: just written by `create_rtv`.
  268. unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) };
  269. }
  270. }
  271. const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV");
  272. /// A shader view or sampler as the title described it (descriptions in the
  273. /// host's layout, kept as words), for the host to build its own from.
  274. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
  275. pub(crate) enum View {
  276. /// Constant buffer: GPU address and size.
  277. Constant(u64, u32),
  278. /// Shader resource: resource, description (none: the resource's own).
  279. Shader(usize, Option<[u32; 10]>),
  280. /// Unordered access: resource, counter resource, description.
  281. Unordered(usize, usize, Option<[u32; 10]>),
  282. Sampler([u32; 13]),
  283. /// The console's own sampler description: flags, filters per axis,
  284. /// addressing, LOD and anisotropy settings, border color, then
  285. /// console-only tuning words.
  286. ConsoleSampler([u32; 27]),
  287. /// A view of memory without a resource object: whether it is unordered
  288. /// access, the resource description, then the view's (the plain one
  289. /// followed by the memory address and console fields).
  290. Placed(bool, [u32; 14], [u32; 16]),
  291. }
  292. impl View {
  293. /// Whether the view reads buffer memory (constant buffers, buffer views
  294. /// of resources or of memory) or memory the title placed a texture in:
  295. /// such views get host slots only for draws.
  296. #[cfg(windows)]
  297. fn is_buffer(&self) -> bool {
  298. match self {
  299. View::Constant(..) | View::Placed(..) => true,
  300. View::Shader(r, _) | View::Unordered(r, _, _) => {
  301. crate::resource::buffer_bytes(*r as This).is_some()
  302. }
  303. View::Sampler(_) | View::ConsoleSampler(_) => false,
  304. }
  305. }
  306. }
  307. /// Every distinct view in use; a descriptor holds a tag, an index into it
  308. /// and the entry's generation, which survive titles copying descriptors as
  309. /// bytes. A view of a resource lives as long as the resource: when the
  310. /// title releases it, its entries are freed for reuse under a new
  311. /// generation, so descriptors (and host slots made from them) naming the
  312. /// old one go stale instead of naming whatever is made at the same address
  313. /// next.
  314. ///
  315. /// Views without a resource object have nothing that releases them, and a
  316. /// title copies descriptors as bytes, so nothing says when the last
  317. /// descriptor naming an entry is gone: such entries were kept for the run.
  318. /// The title writes some 14,000 constant buffer views a frame,
  319. /// each at the address its constants have that frame: 2,450,139 entries
  320. /// after four minutes of play, 1,047 MB with the index, and 11,000 more
  321. /// every second (run 65). So the two kinds that carry an address are not
  322. /// entries any more: their records name them whole ([`constant_words`],
  323. /// [`placed_words`]), and the table holds only what is bounded: views of
  324. /// resource objects (freed with the resource), samplers (as many as there
  325. /// are sampler states), and the shapes of placed views (their descriptions
  326. /// without the address: as many as the title has kinds of textures and
  327. /// buffers, however often it moves them).
  328. /// `VICTORY_VIEW_INLINE=0`: every view is an entry, as before.
  329. struct Views {
  330. /// Each entry's view and generation.
  331. list: Vec<(View, u32)>,
  332. index: std::collections::BTreeMap<View, u32>,
  333. /// Entries naming each resource.
  334. by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
  335. free: Vec<u32>,
  336. /// The shapes of views of placed memory, and where each is.
  337. shapes: Vec<Shape>,
  338. shape_index: std::collections::BTreeMap<Shape, u32>,
  339. }
  340. static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
  341. list: Vec::new(),
  342. index: std::collections::BTreeMap::new(),
  343. by_resource: std::collections::BTreeMap::new(),
  344. free: Vec::new(),
  345. shapes: Vec::new(),
  346. shape_index: std::collections::BTreeMap::new(),
  347. });
  348. const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
  349. /// A record is the tag and two words, `i` and `generation` (the host keeps
  350. /// them as one 64-bit key per slot). The top two bits of `generation` say
  351. /// what the other 62 bits are: 0, entry `i` of the table at that
  352. /// generation; [`CONSTANT`], a constant buffer view, whole; [`PLACED`], a
  353. /// view of placed memory: its address and the number of its shape.
  354. const KIND_SHIFT: u32 = 30;
  355. /// Table generations stay below the kind bits (and above 0).
  356. const GENERATIONS: u32 = (1 << KIND_SHIFT) - 1;
  357. const CONSTANT: u32 = 1;
  358. const PLACED: u32 = 2;
  359. /// Bits of a constant buffer view's address in its record: any address a
  360. /// program can have. The 15 bits above them are its size.
  361. const CONSTANT_ADDRESS_BITS: u32 = 47;
  362. /// Bits of a placed view's address in its record: placed memory is title
  363. /// memory, which lies below 1 TiB. The 22 bits above them number its shape.
  364. const PLACED_ADDRESS_BITS: u32 = 40;
  365. const SHAPES: usize = 1 << (62 - PLACED_ADDRESS_BITS);
  366. /// A view of placed memory without its address: whether it is unordered
  367. /// access, the resource description, and the view's words but the two that
  368. /// hold the address (10 and 11).
  369. type Shape = (bool, [u32; 14], [u32; 14]);
  370. /// Whether constant buffer views and views of placed memory are named whole
  371. /// in their records ([`Views`]). On by default; `VICTORY_VIEW_INLINE=0`
  372. /// makes every view a table entry, as before.
  373. fn inline() -> bool {
  374. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  375. *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_INLINE").is_none_or(|v| v != "0"))
  376. }
  377. /// Views named whole in their records since the start: constant buffer
  378. /// views, views of placed memory (for the memory line).
  379. static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  380. /// The two record words of the 62 bits `payload` of kind `kind`.
  381. fn kind_words(kind: u32, payload: u64) -> [u32; 2] {
  382. [payload as u32, kind << KIND_SHIFT | (payload >> 32) as u32]
  383. }
  384. /// The 62 bits two record words carry beside their kind.
  385. fn payload(i: u32, generation: u32) -> u64 {
  386. u64::from(generation & GENERATIONS) << 32 | u64::from(i)
  387. }
  388. /// The record words that name the constant buffer view of `size` bytes at
  389. /// `address` whole; `None` if they cannot: an address past 47 bits, or a
  390. /// size of 16 KiB or more that is no multiple of 256 or reaches 4 MiB (the
  391. /// size has 15 bits: bytes below 16 KiB, else units of 256 bytes). Such a
  392. /// view is a table entry.
  393. fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> {
  394. if address >> CONSTANT_ADDRESS_BITS != 0 {
  395. return None;
  396. }
  397. let code = if size < 1 << 14 {
  398. u64::from(size)
  399. } else if size.is_multiple_of(256) && size >> 8 < 1 << 14 {
  400. 1 << 14 | u64::from(size >> 8)
  401. } else {
  402. return None;
  403. };
  404. Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address))
  405. }
  406. /// The constant buffer view [`constant_words`] named.
  407. fn constant_of(i: u32, generation: u32) -> View {
  408. let payload = payload(i, generation);
  409. let code = (payload >> CONSTANT_ADDRESS_BITS) as u32;
  410. let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 };
  411. View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size)
  412. }
  413. /// A placed view's shape and its address.
  414. fn shape_of(unordered: bool, resource: &[u32; 14], desc: &[u32; 16]) -> (Shape, u64) {
  415. let mut rest = [0u32; 14];
  416. rest[..10].copy_from_slice(&desc[..10]);
  417. rest[10..].copy_from_slice(&desc[12..]);
  418. (
  419. (unordered, *resource, rest),
  420. u64::from(desc[10]) | u64::from(desc[11]) << 32,
  421. )
  422. }
  423. /// The record words that name the view of placed memory at `address` with
  424. /// shape number `shape`.
  425. fn placed_words(shape: u32, address: u64) -> [u32; 2] {
  426. kind_words(PLACED, u64::from(shape) << PLACED_ADDRESS_BITS | address)
  427. }
  428. impl Views {
  429. /// The number of `shape`, a new one if it is not there yet; `None` when
  430. /// the shapes are full (the view is then a table entry).
  431. fn shape(&mut self, shape: Shape) -> Option<u32> {
  432. if let Some(&at) = self.shape_index.get(&shape) {
  433. return Some(at);
  434. }
  435. if self.shapes.len() >= SHAPES {
  436. return None;
  437. }
  438. let at = self.shapes.len() as u32;
  439. self.shapes.push(shape);
  440. self.shape_index.insert(shape, at);
  441. Some(at)
  442. }
  443. /// The view of placed memory [`placed_words`] named.
  444. fn placed_of(&self, i: u32, generation: u32) -> Option<View> {
  445. let payload = payload(i, generation);
  446. let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1);
  447. let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?;
  448. let mut desc = [0u32; 16];
  449. desc[..10].copy_from_slice(&rest[..10]);
  450. (desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
  451. desc[12..].copy_from_slice(&rest[10..]);
  452. Some(View::Placed(unordered, resource, desc))
  453. }
  454. /// The record words of `view` as a table entry: its entry (a new or a
  455. /// freed one if the view is not there yet) and that entry's generation.
  456. fn entry(&mut self, view: View) -> [u32; 2] {
  457. let i = match self.index.get(&view) {
  458. Some(&i) => i,
  459. None => {
  460. let i = match self.free.pop() {
  461. Some(i) => {
  462. self.list[i as usize].0 = view.clone();
  463. i
  464. }
  465. None => {
  466. self.list.push((view.clone(), 1));
  467. self.list.len() as u32 - 1
  468. }
  469. };
  470. for r in view.resources().into_iter().filter(|&r| r != 0) {
  471. self.by_resource.entry(r).or_default().push(i);
  472. }
  473. self.index.insert(view, i);
  474. i
  475. }
  476. };
  477. [i, self.list[i as usize].1]
  478. }
  479. }
  480. /// The two words that name `view` in a record: the view itself where its
  481. /// kind allows ([`Views`]), else its table entry.
  482. fn words_for(view: View) -> [u32; 2] {
  483. use std::sync::atomic::Ordering::Relaxed;
  484. if inline() {
  485. match &view {
  486. View::Constant(address, size) => {
  487. if let Some(words) = constant_words(*address, *size) {
  488. NAMED_WHOLE[0].fetch_add(1, Relaxed);
  489. return words;
  490. }
  491. }
  492. View::Placed(unordered, resource, desc) => {
  493. let (shape, address) = shape_of(*unordered, resource, desc);
  494. if address >> PLACED_ADDRESS_BITS == 0 {
  495. let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  496. if let Some(shape) = views.shape(shape) {
  497. NAMED_WHOLE[1].fetch_add(1, Relaxed);
  498. return placed_words(shape, address);
  499. }
  500. }
  501. }
  502. _ => {}
  503. }
  504. }
  505. VIEWS.lock().unwrap_or_else(|e| e.into_inner()).entry(view)
  506. }
  507. /// For the memory line: the distinct views kept ([`Views`]), those of them
  508. /// free for reuse, and the bytes the table and its index hold for them (an
  509. /// estimate: an entry of the table, and one of the index with its share of
  510. /// a tree node; the shapes likewise); then the entries that are constant
  511. /// buffer views and views of placed memory (those that did not fit a
  512. /// record, or all of them with `VICTORY_VIEW_INLINE=0`), the shapes of
  513. /// placed views kept, and the views named whole in their records since the
  514. /// start: constant buffer views, views of placed memory.
  515. #[cfg(all(windows, feature = "diagnostics"))]
  516. pub(crate) fn views_kept() -> [u64; 8] {
  517. use std::sync::atomic::Ordering::Relaxed;
  518. let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  519. let each = size_of::<(View, u32)>() as u64;
  520. let shape = size_of::<Shape>() as u64;
  521. let (mut constants, mut placed) = (0, 0);
  522. for (view, _) in &views.list {
  523. match view {
  524. View::Constant(..) => constants += 1,
  525. View::Placed(..) => placed += 1,
  526. _ => {}
  527. }
  528. }
  529. [
  530. views.list.len() as u64,
  531. views.free.len() as u64,
  532. views.list.capacity() as u64 * each
  533. + views.index.len() as u64 * each * 3 / 2
  534. + views.shapes.capacity() as u64 * shape
  535. + views.shape_index.len() as u64 * shape * 3 / 2,
  536. constants,
  537. placed,
  538. views.shapes.len() as u64,
  539. NAMED_WHOLE[0].load(Relaxed),
  540. NAMED_WHOLE[1].load(Relaxed),
  541. ]
  542. }
  543. impl View {
  544. /// The resource objects the view names.
  545. fn resources(&self) -> [usize; 2] {
  546. match *self {
  547. View::Shader(r, _) => [r, 0],
  548. View::Unordered(r, counter, _) => [r, counter],
  549. _ => [0, 0],
  550. }
  551. }
  552. /// The texture object the view is of, if that texture has no host copy
  553. /// yet (`crate::resource::host_waits`): a slot written with such a
  554. /// view is left null until the texture is first used.
  555. #[cfg(windows)]
  556. fn waiting_texture(&self) -> Option<usize> {
  557. match *self {
  558. View::Shader(r, _) | View::Unordered(r, _, _)
  559. if crate::resource::host_waits(r as This) =>
  560. {
  561. Some(r)
  562. }
  563. _ => None,
  564. }
  565. }
  566. }
  567. /// Title slots (their handles) written with a view of a texture object
  568. /// that had no host copy then, by texture. A title texture gets its host
  569. /// copy on first use (`resource.rs` `Hosted`), and the title
  570. /// writes each texture's views into its view heap when it creates the
  571. /// texture: making those host slots would make every host copy at once.
  572. /// They are made when the texture is: translated shaders index the heap
  573. /// directly, so a slot is not always made again by the draw that reads it.
  574. #[cfg(windows)]
  575. static WAITING: std::sync::Mutex<std::collections::BTreeMap<usize, Vec<u64>>> =
  576. std::sync::Mutex::new(std::collections::BTreeMap::new());
  577. /// Textures given their host copy since [`make_waiting`] last ran.
  578. #[cfg(windows)]
  579. static MADE_LATE: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  580. /// Title texture `resource` was given its host copy (called under that
  581. /// texture's own lock: nothing else is locked here).
  582. #[cfg(windows)]
  583. pub(crate) fn texture_made(resource: usize) {
  584. MADE_LATE
  585. .lock()
  586. .unwrap_or_else(|e| e.into_inner())
  587. .push(resource);
  588. }
  589. /// The slot at `handle` was written with a view of texture `resource`,
  590. /// which has no host copy: it waits for one.
  591. #[cfg(windows)]
  592. fn wait_for(resource: usize, handle: u64) {
  593. /// A texture with more slots waiting than this is in use for all we
  594. /// know (its views are being copied about): its host copy is made.
  595. const MOST: usize = 64;
  596. let many = {
  597. let mut waiting = WAITING.lock().unwrap_or_else(|e| e.into_inner());
  598. let slots = waiting.entry(resource).or_default();
  599. if !slots.contains(&handle) {
  600. slots.push(handle);
  601. }
  602. slots.len() > MOST
  603. };
  604. if many {
  605. // Makes it, and notes it made.
  606. let _ = crate::resource::host_copy(resource as This);
  607. } else if !crate::resource::host_waits(resource as This) {
  608. // Made by another thread since the slot was looked at: that making
  609. // may have been taken by `make_waiting` before this slot was noted.
  610. texture_made(resource);
  611. }
  612. }
  613. /// Makes the host slots that waited for a texture's host copy, for the
  614. /// textures made since the last call. Called before a submission runs, by
  615. /// the thread that submits: a slot is read when a list runs.
  616. #[cfg(windows)]
  617. pub(crate) fn make_waiting() {
  618. let made = std::mem::take(&mut *MADE_LATE.lock().unwrap_or_else(|e| e.into_inner()));
  619. for resource in made {
  620. let handles = WAITING
  621. .lock()
  622. .unwrap_or_else(|e| e.into_inner())
  623. .remove(&resource);
  624. for handle in handles.into_iter().flatten() {
  625. // Only if the slot still holds a view of that texture: the
  626. // title may have written it since (and a view of another
  627. // texture without a host copy must go on waiting).
  628. // (Looked up first: the handle is read only while its heap is
  629. // there.)
  630. let Some((heap, index)) = shader_slot(handle) else {
  631. continue;
  632. };
  633. let same = match view(handle) {
  634. Some(View::Shader(r, _) | View::Unordered(r, _, _)) => r == resource,
  635. _ => false,
  636. };
  637. if same && let Some(Some(host)) = heap.host.get() {
  638. host.mirror(index, handle, true);
  639. }
  640. }
  641. }
  642. }
  643. fn record(handle: u64, view: View) {
  644. if handle == 0 {
  645. return;
  646. }
  647. let [i, generation] = words_for(view);
  648. // SAFETY: the handle is a descriptor slot, at least 16 bytes.
  649. unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
  650. #[cfg(windows)]
  651. mirror(handle);
  652. }
  653. /// The title released `resource`: the views naming it go stale.
  654. pub(crate) fn forget(resource: usize) {
  655. #[cfg(windows)]
  656. WAITING
  657. .lock()
  658. .unwrap_or_else(|e| e.into_inner())
  659. .remove(&resource);
  660. let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  661. let Some(entries) = views.by_resource.remove(&resource) else {
  662. return;
  663. };
  664. for i in entries {
  665. let (view, generation) = views.list[i as usize].clone();
  666. // Entries freed through a view's other resource may hold another
  667. // view by now.
  668. if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) {
  669. continue;
  670. }
  671. views.index.remove(&view);
  672. // (Below the bits that say a record is no table entry.)
  673. views.list[i as usize].1 = ((generation + 1) & GENERATIONS).max(1);
  674. // The view's other resource (a counter) keeps a stale entry, which
  675. // `forget` of that resource skips.
  676. views.free.push(i);
  677. }
  678. }
  679. /// The view the record words `i` and `generation` name: the one they hold
  680. /// whole, or the view of entry `i` if `generation` is still its own.
  681. fn view_at(i: u32, generation: u32) -> Option<View> {
  682. match generation >> KIND_SHIFT {
  683. 0 => {
  684. let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  685. let (view, current) = views.list.get(i as usize)?;
  686. (*current == generation).then(|| view.clone())
  687. }
  688. CONSTANT => Some(constant_of(i, generation)),
  689. PLACED => VIEWS.lock().unwrap_or_else(|e| e.into_inner()).placed_of(i, generation),
  690. _ => None,
  691. }
  692. }
  693. /// The view recorded at `handle`, if one is (and its resource is alive).
  694. pub(crate) fn view(handle: u64) -> Option<View> {
  695. if handle == 0 {
  696. return None;
  697. }
  698. // SAFETY: the handle is a descriptor slot the title passes back.
  699. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  700. if tag != VIEW_TAG {
  701. return None;
  702. }
  703. view_at(i, generation)
  704. }
  705. /// A description of `N` words, if the title passes one.
  706. fn words<const N: usize>(desc: *const [u32; N]) -> Option<[u32; N]> {
  707. // SAFETY: the title passes a description or null.
  708. (!desc.is_null()).then(|| unsafe { desc.read_unaligned() })
  709. }
  710. /// Device method.
  711. pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) {
  712. if let Some([lo, hi, size, _]) = words(desc) {
  713. let address = u64::from(lo) | u64::from(hi) << 32;
  714. record(handle, View::Constant(address, size));
  715. }
  716. }
  717. /// Device method.
  718. pub(crate) extern "system" fn create_srv(
  719. _: This,
  720. resource: This,
  721. desc: *const [u32; 10],
  722. handle: u64,
  723. ) {
  724. record(handle, View::Shader(resource as usize, words(desc)));
  725. }
  726. /// Device method.
  727. pub(crate) extern "system" fn create_uav(
  728. _: This,
  729. resource: This,
  730. counter: This,
  731. desc: *const [u32; 10],
  732. handle: u64,
  733. ) {
  734. let view = View::Unordered(resource as usize, counter as usize, words(desc));
  735. record(handle, view);
  736. }
  737. /// Device methods 0x230 and 0x238: shader resource and unordered access
  738. /// views of memory the title placed itself, `(resource desc, view desc,
  739. /// handle)`.
  740. pub(crate) extern "system" fn create_placed_srv(
  741. _: This,
  742. resource: *const [u32; 14],
  743. desc: *const [u32; 16],
  744. handle: u64,
  745. ) {
  746. if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
  747. record(handle, View::Placed(false, resource, desc));
  748. }
  749. }
  750. pub(crate) extern "system" fn create_placed_uav(
  751. _: This,
  752. resource: *const [u32; 14],
  753. desc: *const [u32; 16],
  754. handle: u64,
  755. ) {
  756. if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
  757. record(handle, View::Placed(true, resource, desc));
  758. }
  759. }
  760. /// Device method.
  761. pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) {
  762. if let Some(desc) = words(desc) {
  763. record(handle, View::Sampler(desc));
  764. }
  765. }
  766. /// Device method 0x1e8.
  767. pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) {
  768. if let Some(desc) = words(desc) {
  769. record(handle, View::ConsoleSampler(desc));
  770. }
  771. }
  772. /// Device method: `count` descriptors of `kind` from `src` to `dst`.
  773. pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) {
  774. let step = u64::from(increment(kind).unwrap_or(0));
  775. let len = u64::from(count) * step;
  776. if dst != 0 && src != 0 {
  777. // SAFETY: both ranges are descriptor slots the title owns.
  778. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) };
  779. #[cfg(windows)]
  780. for i in 0..u64::from(count) {
  781. mirror(dst + i * step);
  782. }
  783. }
  784. }
  785. /// Device method: ranges of descriptors (start and count each) gathered
  786. /// from the sources and scattered to the destinations, in order.
  787. #[allow(clippy::too_many_arguments)] // the method's own arguments
  788. pub(crate) extern "system" fn copy(
  789. _: This,
  790. dst_ranges: u32,
  791. dst_starts: *const u64,
  792. dst_sizes: *const u32,
  793. src_ranges: u32,
  794. src_starts: *const u64,
  795. src_sizes: *const u32,
  796. kind: u32,
  797. ) {
  798. let Some(step) = increment(kind) else {
  799. return;
  800. };
  801. // Each range as (start, count); a null size array means one descriptor
  802. // per range.
  803. let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> {
  804. (0..n as usize)
  805. .map(|i| {
  806. // SAFETY: the title passes `n` starts and sizes (or null sizes).
  807. unsafe {
  808. (
  809. *starts.add(i),
  810. if sizes.is_null() { 1 } else { *sizes.add(i) },
  811. )
  812. }
  813. })
  814. .collect()
  815. };
  816. if dst_starts.is_null() || src_starts.is_null() {
  817. return;
  818. }
  819. let src = ranges(src_ranges, src_starts, src_sizes);
  820. let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter();
  821. let (mut to, mut room) = dst.next().unwrap_or((0, 0));
  822. for (mut from, mut left) in src {
  823. while left > 0 {
  824. while room == 0 {
  825. let Some(next) = dst.next() else { return };
  826. (to, room) = next;
  827. }
  828. let n = left.min(room);
  829. copy_simple(std::ptr::null(), n, to, from, kind);
  830. let bytes = u64::from(n) * u64::from(step);
  831. (to, from, room, left) = (to + bytes, from + bytes, room - n, left - n);
  832. }
  833. }
  834. }
  835. /// The view recorded at `handle`, if one is.
  836. pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> {
  837. tagged_record(handle, RTV_TAG)
  838. }
  839. /// The depth view recorded at `handle`, if one is.
  840. pub(crate) fn dsv_record(handle: u64) -> Option<RtvRecord> {
  841. tagged_record(handle, DSV_TAG)
  842. }
  843. fn tagged_record(handle: u64, tag: u32) -> Option<RtvRecord> {
  844. if handle == 0 {
  845. return None;
  846. }
  847. // SAFETY: the handle is a descriptor slot the title passes back.
  848. let record = unsafe { (handle as *const RtvRecord).read_unaligned() };
  849. (record.tag == tag).then_some(record)
  850. }
  851. /// Device method.
  852. pub(crate) extern "system" fn create_heap(
  853. _: This,
  854. desc_ptr: *const HeapDesc,
  855. iid: *const Iid,
  856. out: *mut This,
  857. ) -> HRESULT {
  858. // SAFETY: the title passes a description (null is tolerated).
  859. let Some(&desc) = (unsafe { desc_ptr.as_ref() }) else {
  860. return E_INVALIDARG;
  861. };
  862. let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1)))
  863. else {
  864. return E_INVALIDARG;
  865. };
  866. // SAFETY: read only as a hint: a title that passes the plain
  867. // description has its own stack or data after it.
  868. let placement = unsafe { desc_ptr.add(1).cast::<Placement>().read_unaligned() };
  869. // shortcut: a placement is recognised by its size matching the count,
  870. // since the plain and extended descriptions share the slot and the
  871. // interface version; find the flag that tells them apart if a title
  872. // trips over this.
  873. let placed = placement.address != 0 && placement.size == size;
  874. tracing::debug!(?desc, placed, "descriptor heap");
  875. let (start, memory) = if placed {
  876. (placement.address, None)
  877. } else {
  878. match Memory::zeroed(size, 64) {
  879. Ok(memory) => (memory.address(), Some(memory)),
  880. Err(hr) => return hr,
  881. }
  882. };
  883. let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS);
  884. let heap = Box::new(Heap {
  885. object: Object::new(&FUNCTIONS),
  886. desc,
  887. start,
  888. memory,
  889. #[cfg(windows)]
  890. host: std::sync::OnceLock::new(),
  891. #[cfg(windows)]
  892. pending: Default::default(),
  893. });
  894. #[cfg(windows)]
  895. if visible {
  896. let at = std::ptr::from_ref::<Heap>(&heap) as usize;
  897. let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  898. heaps.push((start, start + size, at));
  899. }
  900. #[cfg(not(windows))]
  901. let _ = visible;
  902. object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out)
  903. }
  904. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  905. let found = object::is(iid, &HEAP_IIDS).then_some(this);
  906. object::answer(DESCRIPTOR_HEAP, iid, found, out)
  907. }
  908. extern "system" fn release(this: This) -> u32 {
  909. object::release_boxed::<Heap>(this)
  910. }
  911. extern "system" fn desc(this: This, out: *mut HeapDesc) {
  912. if !out.is_null() {
  913. // SAFETY: checked non-null; the title passes room for a description.
  914. unsafe { out.write(heap(this).desc) };
  915. }
  916. }
  917. /// The same address for the CPU and the GPU start.
  918. extern "system" fn start(this: This) -> u64 {
  919. heap(this).start
  920. }
  921. /// IUnknown 3, object 4, device child 1, heap 3.
  922. static FUNCTIONS: Table<24> = {
  923. let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 24>());
  924. f[0] = query as *const ();
  925. f[2] = release as *const ();
  926. f[7] = object::parent_device as *const (); // 0x38
  927. f[8] = desc as *const (); // 0x40
  928. f[9] = start as *const (); // 0x48 CPU
  929. f[10] = start as *const (); // 0x50 GPU
  930. Table(f)
  931. };
  932. #[cfg(test)]
  933. mod tests {
  934. use super::*;
  935. use crate::object::{S_OK, slot};
  936. /// What newer titles pass; tests use it throughout, so that reading the
  937. /// placement stays inside the value.
  938. #[repr(C)]
  939. struct Extended(HeapDesc, Placement);
  940. fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT {
  941. let extended = Extended(desc, placement);
  942. create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out)
  943. }
  944. #[test]
  945. fn heaps_hold_count_descriptors_from_their_start() {
  946. let null = std::ptr::null();
  947. let desc = HeapDesc {
  948. kind: 0,
  949. count: 1000,
  950. flags: 1,
  951. nodes: 0,
  952. };
  953. let none = Placement {
  954. address: 0,
  955. size: 0,
  956. };
  957. let mut h = null;
  958. assert_eq!(create(desc, none, &mut h), S_OK);
  959. let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h);
  960. assert_eq!(cpu % 64, 0);
  961. assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu);
  962. assert_eq!(increment_size(null, 0), 32);
  963. // SAFETY: the heap holds 1000 descriptors of 32 bytes.
  964. unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) };
  965. assert_eq!(increment_size(null, 9), 0);
  966. let bad = HeapDesc { kind: 9, ..desc };
  967. assert_eq!(create(bad, none, &mut h), E_INVALIDARG);
  968. }
  969. #[test]
  970. fn views_survive_copies() {
  971. let null = std::ptr::null();
  972. let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots
  973. let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64;
  974. let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3));
  975. create_cbv(null, &[0x1000, 1, 256, 0], s0);
  976. assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256)));
  977. create_srv(null, null, std::ptr::null(), s1);
  978. assert_eq!(view(s1), Some(View::Shader(0, None)));
  979. // The same view twice is one entry.
  980. create_srv(null, null, std::ptr::null(), s2);
  981. // SAFETY: both slots are in `heap`.
  982. assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe {
  983. *(s2 as *const [u32; 3])
  984. });
  985. // Two ranges of one into one range of two.
  986. let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]);
  987. copy(
  988. null,
  989. 1,
  990. dst.as_ptr(),
  991. dst_n.as_ptr(),
  992. 2,
  993. src.as_ptr(),
  994. src_n.as_ptr(),
  995. 0,
  996. );
  997. assert_eq!(view(s2), view(s0));
  998. assert_eq!(view(s3), view(s1));
  999. assert_eq!(view(at(0) + 8), None);
  1000. heap[0] = 0;
  1001. }
  1002. /// Constant buffer views are named whole in their records: any address
  1003. /// a program can have, any size below 16 KiB, multiples of 256 bytes
  1004. /// up to 4 MiB; what does not fit says so.
  1005. #[test]
  1006. fn constant_views_fit_their_records() {
  1007. let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1;
  1008. for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] {
  1009. for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] {
  1010. let [i, generation] = constant_words(address, size).expect("fits");
  1011. assert_eq!(generation >> KIND_SHIFT, CONSTANT);
  1012. assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}");
  1013. }
  1014. }
  1015. assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits");
  1016. assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256");
  1017. assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB");
  1018. // Different views never share their words.
  1019. assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512));
  1020. assert_ne!(constant_words(0x1000, 256), constant_words(0x1100, 256));
  1021. assert_ne!(constant_words(0x1000, 1 << 14), constant_words(0x1000, 64));
  1022. }
  1023. /// The leak of run 65: a title that writes constant buffer views and
  1024. /// views of placed memory at ever new addresses adds nothing to the
  1025. /// table; one shape stands for all the placed views alike.
  1026. #[test]
  1027. fn views_at_new_addresses_add_no_entries() {
  1028. if !inline() {
  1029. return;
  1030. }
  1031. let null = std::ptr::null();
  1032. let slots = [0u64; 4];
  1033. let at = slots.as_ptr() as u64;
  1034. // A resource description and a view no other test uses.
  1035. let resource: [u32; 14] = std::array::from_fn(|k| 0x5ee0_0000 + k as u32);
  1036. let mut desc: [u32; 16] = std::array::from_fn(|k| 0x7a70_0000 + k as u32);
  1037. let mine = |v: &View| match v {
  1038. View::Constant(address, _) => (0x6_0000_0000..0x6_1000_0000).contains(address),
  1039. View::Placed(_, r, _) => *r == resource,
  1040. _ => false,
  1041. };
  1042. let entries = || VIEWS.lock().unwrap().list.iter().filter(|(v, _)| mine(v)).count();
  1043. let shapes = || VIEWS.lock().unwrap().shapes.iter().filter(|s| s.1 == resource).count();
  1044. for n in 0..20_000u64 {
  1045. let address = 0x6_0000_0000 + n * 0x100;
  1046. create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at);
  1047. assert_eq!(view(at), Some(View::Constant(address, 512)));
  1048. let placed = 0xd_4940_0000 + n * 0x1_0000;
  1049. (desc[10], desc[11]) = (placed as u32, (placed >> 32) as u32);
  1050. create_placed_srv(null, &resource, &desc, at);
  1051. assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
  1052. }
  1053. assert_eq!(entries(), 0, "no table entries");
  1054. assert_eq!(shapes(), 1, "one shape for 20,000 placed views");
  1055. // The same shape, unordered: another shape.
  1056. create_placed_uav(null, &resource, &desc, at);
  1057. assert_eq!(view(at), Some(View::Placed(true, resource, desc)));
  1058. assert_eq!(shapes(), 2);
  1059. // Placed memory past 1 TiB (not title memory) is a table entry.
  1060. (desc[10], desc[11]) = (0, 0x100);
  1061. create_placed_srv(null, &resource, &desc, at);
  1062. assert_eq!(view(at), Some(View::Placed(false, resource, desc)));
  1063. assert_eq!(entries(), 1);
  1064. // A record's words are the same for the same view (the host knows
  1065. // a slot's view by them), and differ with the address.
  1066. // SAFETY: both handles are slots of 32 bytes above.
  1067. let words = |handle: u64| unsafe { *(handle as *const [u32; 3]) };
  1068. let other = [0u64; 4];
  1069. create_cbv(null, &[0x40, 6, 512, 0], at);
  1070. create_cbv(null, &[0x40, 6, 512, 0], other.as_ptr() as u64);
  1071. assert_eq!(words(at), words(other.as_ptr() as u64));
  1072. create_cbv(null, &[0x140, 6, 512, 0], other.as_ptr() as u64);
  1073. assert_ne!(words(at), words(other.as_ptr() as u64));
  1074. }
  1075. /// A released resource's views go stale; the same view of a new
  1076. /// resource at the same address is a new record.
  1077. #[test]
  1078. fn views_die_with_their_resource() {
  1079. let null = std::ptr::null();
  1080. let slots = [0u64; 2 * 4];
  1081. let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32);
  1082. let resource = 0x7777_0000usize as This;
  1083. create_srv(null, resource, std::ptr::null(), a);
  1084. assert_eq!(view(a), Some(View::Shader(0x7777_0000, None)));
  1085. forget(0x7777_0000);
  1086. assert_eq!(view(a), None, "stale after release");
  1087. create_srv(null, resource, std::ptr::null(), b);
  1088. assert_eq!(view(b), Some(View::Shader(0x7777_0000, None)));
  1089. // SAFETY: both slots are in `slots`.
  1090. let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) };
  1091. assert_ne!(old, new, "a new generation");
  1092. }
  1093. /// The title places its shader-visible heap in its own memory
  1094. /// and checks that the heap starts there.
  1095. #[test]
  1096. fn placed_heaps_start_at_the_title_memory() {
  1097. let mut memory = vec![0u8; 64 * 32];
  1098. let address = memory.as_mut_ptr() as u64;
  1099. let desc = HeapDesc {
  1100. kind: 0,
  1101. count: 64,
  1102. flags: 1,
  1103. nodes: 1,
  1104. };
  1105. let mut h = std::ptr::null();
  1106. assert_eq!(
  1107. create(
  1108. desc,
  1109. Placement {
  1110. address,
  1111. size: 64 * 32
  1112. },
  1113. &mut h
  1114. ),
  1115. S_OK
  1116. );
  1117. assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
  1118. assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), address);
  1119. // A size that does not match the count is not a placement.
  1120. assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK);
  1121. assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
  1122. }
  1123. }