descriptor.rs 64 KB

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