descriptor.rs 61 KB

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