descriptor.rs 44 KB

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