descriptor.rs 69 KB

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