descriptor.rs 54 KB

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