descriptor.rs 70 KB

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