descriptor.rs 58 KB

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