memory.rs 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  1. //! Title memory by address, for translated shaders that read and write
  2. //! through raw 40-bit addresses (`victory_shader::emit::SLOT_MEMORY`: the
  3. //! console's ray-tracing structure builder and the programs that walk its
  4. //! structures; the structures themselves lie in plain title memory, in no
  5. //! buffer object).
  6. //!
  7. //! A 64 KiB page in a title buffer that holds all of it is in that buffer's
  8. //! copy ([`crate::shadow`]), which every other access uses. A page outside
  9. //! buffers has a page of its own in an **arena**: memory of ours with a copy
  10. //! on the card ([`crate::shadow::by_address`]). The streamed structures lie
  11. //! anywhere between other data (6.6 GB of title memory in 4 MiB windows, run
  12. //! light-1; 8 GB in windows of 256 KiB, light-2), so a page is what is kept.
  13. //!
  14. //! This module keeps what a shader needs to find the pages:
  15. //!
  16. //! - the **directory**: per 64 KiB page of title address space the number
  17. //! of the copy that holds the page (0: none) and the page's byte offset
  18. //! in it; one for all lists, entries only ever go from empty to filled.
  19. //! The CPU writes it in memory of its own and shaders read a copy of that
  20. //! on the card, brought up to date as title memory is (over the bus, every
  21. //! step of every ray waited for it);
  22. //! - per view heap a run of slots with a raw unordered access view of each
  23. //! numbered copy (slot 0 of the run: a null view, for pages without a
  24. //! copy);
  25. //! - the **faults**: the page numbers shaders found empty, read back here
  26. //! once a frame, so the pages are there from the next frame on. A pointer a
  27. //! shader takes out of memory cannot be known before it runs.
  28. //!
  29. //! **A page that is not there when a shader touches it is a lost access**:
  30. //! the read gives 0, the store is dropped, and the fault note only helps
  31. //! the next frame. For the structure builder that is the same as a dropped
  32. //! stage, so before one of its dispatches the host makes ready what it can
  33. //! see the dispatch name:
  34. //!
  35. //! - 256 KiB from each root view outside buffers, and where title memory has a
  36. //! packed ("dehydrated") structure there, all of it: the title ships its
  37. //! structures packed, and the builder's rehydration stages unpack each in
  38. //! place once it is streamed in;
  39. //! - 4 MiB from each unordered access view outside buffers (structures built);
  40. //! - the page of each pair of root constants that is a title address and of
  41. //! each root constant that is one in 256-byte units;
  42. //! - the first page of every structure a list's upload memory names
  43. //! (a top-level build's instances).
  44. //!
  45. //! **What comes back to title memory**: what the builder stores in title
  46. //! buffers of at most [`BACK`] bytes it names (the sizes the title reads to
  47. //! make a structure smaller). Structures and scratch memory stay on the card
  48. //! (the first whole run of the builder wrote garbage over the title's
  49. //! objects). So an arena's page is the only place a structure is whole, and
  50. //! title memory must not go over it: of a page the title wrote only the
  51. //! dwords that changed since they were last taken go up. A packed structure
  52. //! goes up whole when the builder comes to it, whatever is known of it: the
  53. //! same bytes streamed in again do not differ from those last taken, and the
  54. //! card holds them unpacked (run light-3: a quarter of the structures
  55. //! unpacked a second time, into garbage all over their neighbours).
  56. //!
  57. //! **Stores are bounded**: a structure the builder misreads makes it store
  58. //! anywhere. Pages of title buffers take its stores only once one of its
  59. //! dispatches was given that buffer as an unordered access view (its scratch
  60. //! memory, its results); what else a store reaches is an arena's.
  61. //!
  62. //! A packed structure is gone when title memory has no header of it any more
  63. //! (looked at over [`SWEEP`] frames); the pages it alone has are given back.
  64. //!
  65. //! shortcut: a page held for anything else is kept for the rest of the run.
  66. //! shortcut: pages a list does not name are looked at again in turn, over
  67. //! [`SWEEP`] frames.
  68. use std::collections::HashMap;
  69. use std::sync::{Arc, Mutex};
  70. use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES, MEMORY_READ_ONLY};
  71. use windows::Win32::Graphics::Direct3D12::*;
  72. use crate::descriptor::host::HostHeap;
  73. use crate::host::{HostList, host};
  74. use crate::shadow::Shadow;
  75. /// Copies that can be numbered (the run of heap slots is one longer).
  76. const COPIES: u32 = (1 << 12) - 1;
  77. /// A directory page.
  78. const PAGE: u64 = 1 << 16;
  79. /// An arena's bytes.
  80. const ARENA: u64 = 64 << 20;
  81. /// What is compared at a time.
  82. const PIECE: usize = 4096;
  83. /// Pages held, at most (3 GiB).
  84. const MOST: usize = 3 << 14;
  85. /// Pages of title memory with small title buffers in them, at most.
  86. const WINDOWS: usize = 512;
  87. /// The biggest packed structure taken for one.
  88. const PACKED: u64 = 64 << 20;
  89. /// For so many frames what a page holds may still be on its way.
  90. const YOUNG: u64 = 4;
  91. /// Free pages there are, at least, when a list is recorded.
  92. const SPARE: usize = 1024;
  93. /// A packed structure not named for so many frames is another one.
  94. const AGAIN: u64 = 8;
  95. /// From a root view; from one that is written (a structure being built).
  96. const VIEW: u64 = 256 << 10;
  97. const BUILT: u64 = 4 << 20;
  98. /// The biggest title buffer whose builder results come back.
  99. const BACK: u64 = 256 << 10;
  100. /// Pages taken from the faults, of one frame and in all, at most: a ray in a
  101. /// structure that is not right goes anywhere, and 2,048 a frame took all the
  102. /// pages there are in the first seconds (run light-4).
  103. const FAULTS: usize = 128;
  104. const FAULTS_ALL: usize = 2048;
  105. /// Frames over which every page is looked at once.
  106. const SWEEP: usize = 128;
  107. /// What a draw or dispatch does with title memory by address.
  108. #[derive(Clone, Copy, PartialEq)]
  109. pub(crate) enum Use {
  110. Reads,
  111. /// Stores by address, as the structure builder; `back`: its results in
  112. /// small title buffers come back.
  113. Builds { back: bool },
  114. }
  115. /// A page of title memory in an arena.
  116. struct Held {
  117. /// Where in the arena's memory, and the arena's place in `copies`.
  118. at: usize,
  119. copy: usize,
  120. /// The write-watch asking after which it was last taken (0: never).
  121. taken: u64,
  122. /// The frame it was last looked at in, and the one it came in.
  123. looked: u64,
  124. born: u64,
  125. /// Packed structures that have bytes in it, and whether it is held for
  126. /// them alone.
  127. owners: u32,
  128. theirs: bool,
  129. }
  130. /// A packed structure the builder came to.
  131. struct Packed {
  132. /// The frame it last did.
  133. frame: u64,
  134. len: u64,
  135. /// Its first two dwords in title memory.
  136. header: u64,
  137. }
  138. struct Memory {
  139. /// The CPU's entries (number, offset), and the copy shaders read.
  140. directory: (*mut u32, Arc<Shadow>),
  141. faults: (ID3D12Resource, *mut u32, u64),
  142. /// Copy `n` is `copies[n - 1]`.
  143. copies: Vec<Arc<Shadow>>,
  144. /// Places of title buffers' copies among `copies`.
  145. numbers: HashMap<usize, usize>,
  146. /// Arenas: place in `copies`, address.
  147. arenas: Vec<(usize, usize)>,
  148. /// By title page.
  149. pages: HashMap<u64, Held>,
  150. /// Their numbers in the order they came, and where the sweep is.
  151. order: Vec<u64>,
  152. sweep: usize,
  153. /// Windows of title memory itself ([`Memory::map`]).
  154. windows: usize,
  155. /// Packed structures the builder came to: the frame it last did.
  156. packed: HashMap<u64, Packed>,
  157. /// Their addresses in the order they came, and where the sweep is.
  158. packed_order: Vec<u64>,
  159. packed_sweep: usize,
  160. /// Places of pages that are free: the copy, the address in the arena.
  161. free: Vec<(usize, usize)>,
  162. /// Copies of title buffers the builder may store in.
  163. open: std::collections::HashSet<usize>,
  164. /// Pages taken from faults.
  165. faulted: usize,
  166. /// Per host view heap (by address): the first slot of its run, and how
  167. /// many copies have their view there.
  168. heaps: HashMap<usize, (u32, u32)>,
  169. /// The frame the faults were last read in.
  170. frame: u64,
  171. /// Pages asked for this frame that are not the title's memory.
  172. refused: std::collections::HashSet<u64>,
  173. stats: Stats,
  174. #[cfg(feature = "diagnostics")]
  175. dump: dump::Dump,
  176. }
  177. /// Since the last report.
  178. #[derive(Default)]
  179. struct Stats {
  180. from: Option<(std::time::Instant, u64)>,
  181. uses: [u64; 2],
  182. faults: u64,
  183. unknown: u64,
  184. back: u64,
  185. /// Pages looked at, bytes that changed, packed structures sent.
  186. looked: u64,
  187. changed: u64,
  188. packed: u64,
  189. packed_bytes: u64,
  190. gone: u64,
  191. /// Pages that came for an address in constants, a written view, another
  192. /// view, a structure named in upload memory.
  193. came: [u64; 4],
  194. micros: u64,
  195. }
  196. // SAFETY: the mappings are of memory the struct owns; all access is under
  197. // the mutex.
  198. unsafe impl Send for Memory {}
  199. static MEMORY: Mutex<Option<Memory>> = Mutex::new(None);
  200. /// What a draw binds.
  201. pub(crate) struct Ready {
  202. pub(crate) directory: u64,
  203. pub(crate) faults: u64,
  204. /// The view heap slot of the null view; copy `n`'s view is `n` further.
  205. pub(crate) base: u32,
  206. }
  207. impl Memory {
  208. fn new() -> Option<Memory> {
  209. let host = host()?;
  210. let bytes = u64::from(MEMORY_PAGES) * 8;
  211. // Zeroed, and watched for writes as the title's memory is.
  212. let entries = crate::upload::reserve(bytes as usize)?;
  213. let directory = crate::shadow::by_address(entries as u64, bytes)?;
  214. crate::host::name(&directory.buffer, || "title memory by address: directory".into());
  215. let (faults, data) = host.shared_buffer(u64::from(MEMORY_FAULTS) * 4)?;
  216. crate::host::name(&faults, || "title memory by address: faults".into());
  217. // SAFETY: a fresh mapping of at least that many bytes.
  218. unsafe { std::ptr::write_bytes(data, 0, MEMORY_FAULTS as usize * 4) };
  219. // SAFETY: a live buffer.
  220. let gpu = unsafe { faults.GetGPUVirtualAddress() };
  221. tracing::info!("title memory by address: a shader reads or writes through raw addresses");
  222. Some(Memory {
  223. directory: (entries as *mut u32, directory),
  224. faults: (faults, data.cast::<u32>(), gpu),
  225. copies: Vec::new(),
  226. numbers: HashMap::new(),
  227. arenas: Vec::new(),
  228. pages: HashMap::new(),
  229. order: Vec::new(),
  230. sweep: 0,
  231. windows: 0,
  232. packed: HashMap::new(),
  233. packed_order: Vec::new(),
  234. packed_sweep: 0,
  235. free: Vec::new(),
  236. open: Default::default(),
  237. faulted: 0,
  238. heaps: HashMap::new(),
  239. frame: u64::MAX,
  240. refused: Default::default(),
  241. stats: Stats::default(),
  242. #[cfg(feature = "diagnostics")]
  243. dump: Default::default(),
  244. })
  245. }
  246. /// The directory's entry of `page`.
  247. fn entry(&self, page: u64) -> *mut u32 {
  248. debug_assert!(page < u64::from(MEMORY_PAGES));
  249. // SAFETY: inside the directory.
  250. unsafe { self.directory.0.add(page as usize * 2) }
  251. }
  252. /// The place in `copies` of the copy that holds `page`, if one does.
  253. fn copy_of(&self, page: u64) -> Option<usize> {
  254. if page >= u64::from(MEMORY_PAGES) {
  255. return None;
  256. }
  257. // SAFETY: an entry of the directory.
  258. ((unsafe { self.entry(page).read() } & !MEMORY_READ_ONLY) as usize).checked_sub(1)
  259. }
  260. /// Whether `page` can be given a place: in the directory, not turned down
  261. /// this frame, and the title's GPU memory. (A shader's pointer, or a
  262. /// constant taken for an address, may be anything.)
  263. fn possible(&mut self, page: u64) -> bool {
  264. // Not the last entry: addresses past the directory read it, and it
  265. // stays empty.
  266. if page < 0x1_0000 || page >= u64::from(MEMORY_PAGES) - 1 || self.refused.contains(&page) {
  267. return false;
  268. }
  269. let at = (page * PAGE) as usize;
  270. let ours = crate::texture::committed(at as *const u8, PAGE as usize)
  271. && crate::watch::writes(at, at + PAGE as usize, true).is_some();
  272. if !ours {
  273. self.refused.insert(page);
  274. self.stats.unknown += 1;
  275. }
  276. ours
  277. }
  278. /// Gives a copy a number, if one is left.
  279. fn number(&mut self, shadow: Arc<Shadow>) -> Option<usize> {
  280. let key = Arc::as_ptr(&shadow) as usize;
  281. if let Some(&n) = self.numbers.get(&key) {
  282. return Some(n);
  283. }
  284. if self.copies.len() >= COPIES as usize {
  285. static ONCE: std::sync::Once = std::sync::Once::new();
  286. ONCE.call_once(|| tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros"));
  287. return None;
  288. }
  289. // SAFETY: a live buffer.
  290. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  291. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  292. return None;
  293. }
  294. self.copies.push(shadow);
  295. let n = self.copies.len() - 1;
  296. self.numbers.insert(key, n);
  297. Some(n)
  298. }
  299. /// Gives `page` a place, if it has none and the memory is the title's;
  300. /// whether it has one then.
  301. fn map(&mut self, page: u64) -> bool {
  302. if self.copy_of(page).is_some() {
  303. return true;
  304. }
  305. if !self.possible(page) {
  306. return false;
  307. }
  308. let start = page * PAGE;
  309. if crate::shadow::in_buffer(start, PAGE).is_some() {
  310. let Some(shadow) = crate::shadow::find(start, PAGE) else {
  311. return false;
  312. };
  313. let fresh = !self.numbers.contains_key(&(Arc::as_ptr(&shadow) as usize));
  314. let Some(n) = self.number(shadow.clone()) else {
  315. return false;
  316. };
  317. // Every page the copy holds whole, not only the one asked for.
  318. // shortcut: a page of a title buffer inside this one that has a
  319. // copy of its own is given this copy too.
  320. if fresh {
  321. let (first, len) = shadow.span();
  322. let mut at = first.next_multiple_of(PAGE);
  323. while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 {
  324. let entry = self.entry(at / PAGE);
  325. // SAFETY: an entry of the directory.
  326. if unsafe { entry.read() } == 0 {
  327. close(entry, n, at - first);
  328. }
  329. at += PAGE;
  330. }
  331. }
  332. // SAFETY: as above.
  333. if unsafe { self.entry(page).read() } == 0 {
  334. close(self.entry(page), n, start - shadow.span().0);
  335. }
  336. return true;
  337. }
  338. // Small title buffers in it: what the builder stores in them comes
  339. // back, so title memory itself.
  340. if self.windows < WINDOWS && crate::shadow::small_buffer_in(start, PAGE, BACK) {
  341. if let Some(shadow) = crate::shadow::by_address(start, PAGE)
  342. && let Some(n) = self.number(shadow)
  343. {
  344. self.windows += 1;
  345. fill(self.entry(page), n, 0);
  346. return true;
  347. }
  348. return false;
  349. }
  350. if self.pages.len() >= MOST {
  351. static ONCE: std::sync::Once = std::sync::Once::new();
  352. ONCE.call_once(|| tracing::warn!(MOST, "title memory by address: no more pages are taken; others read zeros"));
  353. return false;
  354. }
  355. if let Some((copy, at)) = self.free.pop() {
  356. self.hold(page, at, copy);
  357. return true;
  358. }
  359. if !self.another() {
  360. return false;
  361. }
  362. let Some((copy, at)) = self.free.pop() else {
  363. return false;
  364. };
  365. self.hold(page, at, copy);
  366. true
  367. }
  368. /// Another arena's pages.
  369. fn another(&mut self) -> bool {
  370. let Some(at) = crate::upload::reserve(ARENA as usize) else {
  371. return false;
  372. };
  373. let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else {
  374. return false;
  375. };
  376. self.arenas.push((n, at));
  377. // The lowest first.
  378. self.free.extend((0..(ARENA / PAGE) as usize).rev().map(|i| (n, at + i * PAGE as usize)));
  379. true
  380. }
  381. /// `page` is held at `at` in the arena that is `copy`.
  382. fn hold(&mut self, page: u64, at: usize, copy: usize) {
  383. self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, born: self.frame, owners: 0, theirs: false });
  384. self.order.push(page);
  385. fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0);
  386. }
  387. /// The packed structure at `address` is gone: the pages it alone had are
  388. /// given back.
  389. fn gone(&mut self, address: u64) {
  390. let Some(packed) = self.packed.remove(&address) else { return };
  391. for page in address / PAGE..=(address + packed.len - 1) / PAGE {
  392. let Some(held) = self.pages.get_mut(&page) else { continue };
  393. held.owners = held.owners.saturating_sub(1);
  394. if held.owners == 0 && held.theirs {
  395. self.free.push((held.copy, held.at));
  396. self.pages.remove(&page);
  397. // SAFETY: an entry of the directory, under the mutex.
  398. unsafe { self.entry(page).write_volatile(0) };
  399. }
  400. }
  401. self.stats.gone += 1;
  402. }
  403. /// Whether the packed structure at `address` is still in title memory.
  404. fn there(&self, address: u64) -> bool {
  405. let mut header = [0u8; 8];
  406. crate::texture::committed(address as *const u8, 8) && {
  407. crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false);
  408. self.packed.get(&address).is_some_and(|p| p.header == u64::from_le_bytes(header))
  409. }
  410. }
  411. /// Looks at some of the pages and packed structures again.
  412. fn look_again(&mut self) {
  413. for _ in 0..self.order.len().div_ceil(SWEEP) {
  414. self.sweep = (self.sweep + 1) % self.order.len();
  415. let page = self.order[self.sweep];
  416. if self.pages.contains_key(&page) {
  417. self.bring(page, page + 1);
  418. } else {
  419. self.order.swap_remove(self.sweep);
  420. if self.order.is_empty() {
  421. break;
  422. }
  423. }
  424. }
  425. for _ in 0..self.packed_order.len().div_ceil(SWEEP) {
  426. self.packed_sweep = (self.packed_sweep + 1) % self.packed_order.len();
  427. let address = self.packed_order[self.packed_sweep];
  428. if !self.packed.contains_key(&address) {
  429. self.packed_order.swap_remove(self.packed_sweep);
  430. if self.packed_order.is_empty() {
  431. break;
  432. }
  433. } else if !self.there(address) {
  434. self.gone(address);
  435. }
  436. }
  437. }
  438. /// A dispatch of the builder was given `address` to write: if it is in a
  439. /// title buffer's copy, stores by address reach that from here on.
  440. fn opens(&mut self, address: u64) {
  441. let Some(n) = self.map(address / PAGE).then(|| self.copy_of(address / PAGE)).flatten() else {
  442. return;
  443. };
  444. if self.pages.contains_key(&(address / PAGE)) || !self.open.insert(n) {
  445. return;
  446. }
  447. // (Its pages hold what the CPU writes beside the builder's scratch.)
  448. self.copies[n].keep_stores();
  449. let (first, len) = self.copies[n].span();
  450. tracing::info!(
  451. start = format_args!("{first:#x}"),
  452. len,
  453. "title memory by address: the structure builder may store in a title buffer"
  454. );
  455. for page in first.div_ceil(PAGE)..(first + len) / PAGE {
  456. if self.copy_of(page) == Some(n) {
  457. fill(self.entry(page), n, page * PAGE - first);
  458. }
  459. }
  460. }
  461. /// [`Memory::map`] of the pages of `[address, address + len)`, up to the
  462. /// first that is not the title's, and what the title wrote there since
  463. /// they were taken goes into the arenas.
  464. fn ready(&mut self, address: u64, len: u64) {
  465. let first = address / PAGE;
  466. let mut end = first;
  467. while end * PAGE < address + len && self.map(end) {
  468. end += 1;
  469. }
  470. self.bring(first, end);
  471. }
  472. /// Takes the pages `[first, end)` that are in arenas from title memory
  473. /// where it wrote them.
  474. fn bring(&mut self, first: u64, end: u64) {
  475. // Once a frame: the builder names the same pages list after list.
  476. let frame = self.frame;
  477. if !(first..end).any(|page| self.pages.get(&page).is_some_and(|h| h.looked != frame)) {
  478. return;
  479. }
  480. let started = std::time::Instant::now();
  481. let answer = crate::watch::writes((first * PAGE) as usize, (end * PAGE) as usize, true);
  482. for page in first..end {
  483. let Some(held) = self.pages.get_mut(&page) else {
  484. continue;
  485. };
  486. if held.looked == frame {
  487. continue;
  488. }
  489. held.looked = frame;
  490. self.stats.looked += 1;
  491. let wrote = answer
  492. .as_ref()
  493. .map(|(_, w)| w.binary_search_by_key(&(page as usize), |w| w.0).map_or(0, |i| w[i].1));
  494. let now = answer.as_ref().map_or(1, |a| a.0);
  495. let stale = held.taken == 0 || wrote.is_none_or(|w| w > held.taken);
  496. if !stale {
  497. continue;
  498. }
  499. let never = std::mem::replace(&mut held.taken, now.max(1)) == 0;
  500. let shadow = &self.copies[held.copy];
  501. let base = held.at - shadow.span().0 as usize;
  502. let mut title = [0u8; PIECE];
  503. for piece in (0..PAGE as usize).step_by(PIECE) {
  504. let from = (page * PAGE) as usize + piece;
  505. // (Pages that are not there read as zeros.)
  506. crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false);
  507. // SAFETY: a page of an arena of ours, under the mutex.
  508. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) };
  509. self.stats.changed += merge(&title, ours, never) as u64 * 4;
  510. }
  511. if never {
  512. shadow.resend(base, base + PAGE as usize);
  513. }
  514. }
  515. self.stats.micros += started.elapsed().as_micros() as u64;
  516. }
  517. /// The bytes of a packed structure title memory has at `address` by now,
  518. /// and its first two dwords.
  519. fn packed_at(&self, address: u64) -> Option<(u64, u64)> {
  520. if address & 0xFF != 0 {
  521. return None;
  522. }
  523. let mut header = [0u8; 8];
  524. crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false);
  525. let header = u64::from_le_bytes(header);
  526. Some((packed_len(header)?, header))
  527. }
  528. /// At the submission of a list whose builder dispatch was given `address`
  529. /// outside buffers, in the order of its copies: what title memory has
  530. /// there now goes up. When the dispatch is recorded it may not be there
  531. /// yet: the title's queue waits for its streaming. (Nothing is asked of
  532. /// the write watch here: the submission's asking stands.)
  533. fn land(&mut self, address: u64) {
  534. let page = address / PAGE;
  535. if !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize) {
  536. return;
  537. }
  538. let Some((len, header)) = self.packed_at(address) else {
  539. // Anything else: what came since its page was first taken.
  540. for page in page..=(address + VIEW - 1) / PAGE {
  541. if self.pages.get(&page).is_some_and(|h| h.born + YOUNG >= self.frame) {
  542. self.take(page, 0, PAGE as usize, false);
  543. }
  544. }
  545. return;
  546. };
  547. if let Some(known) = self.packed.get_mut(&address) {
  548. let soon = known.frame + AGAIN >= self.frame;
  549. known.frame = self.frame;
  550. if known.header == header && soon {
  551. return;
  552. }
  553. if known.header != header {
  554. self.gone(address);
  555. }
  556. }
  557. let last = (address + len - 1) / PAGE;
  558. if !self.packed.contains_key(&address) {
  559. self.packed.insert(address, Packed { frame: self.frame, len, header });
  560. self.packed_order.push(address);
  561. for page in page..=last {
  562. let new = self.copy_of(page).is_none();
  563. if new && !self.place(page) {
  564. continue;
  565. }
  566. if let Some(held) = self.pages.get_mut(&page) {
  567. held.owners += 1;
  568. held.theirs |= new;
  569. }
  570. }
  571. self.stats.packed_bytes += len;
  572. }
  573. for page in page..=last {
  574. let from = address.max(page * PAGE) - page * PAGE;
  575. let to = (address + len).min((page + 1) * PAGE) - page * PAGE;
  576. self.take(page, from as usize, to as usize, true);
  577. }
  578. self.stats.packed += 1;
  579. }
  580. /// A place in an arena for a page of committed title memory, at a
  581. /// submission: only one there is already (the list brings up the arenas
  582. /// it knew when it was recorded).
  583. fn place(&mut self, page: u64) -> bool {
  584. if page < 0x1_0000
  585. || page >= u64::from(MEMORY_PAGES) - 1
  586. || !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize)
  587. || crate::shadow::in_buffer(page * PAGE, PAGE).is_some()
  588. {
  589. return false;
  590. }
  591. let Some((copy, at)) = self.free.pop() else {
  592. return false;
  593. };
  594. self.hold(page, at, copy);
  595. crate::watch::wrote(self.entry(page) as usize, 8);
  596. self.take(page, 0, PAGE as usize, true);
  597. true
  598. }
  599. /// Bytes `from..to` of `page` from title memory into its arena's page, at
  600. /// a submission; `whole`: sent whether they differ from those last taken
  601. /// or not.
  602. fn take(&mut self, page: u64, from: usize, to: usize, whole: bool) {
  603. let Some(held) = self.pages.get(&page) else { return };
  604. let shadow = &self.copies[held.copy];
  605. let base = held.at - shadow.span().0 as usize;
  606. let mut title = [0u8; PIECE];
  607. let mut at = from;
  608. while at < to {
  609. let n = (PIECE - at % PIECE).min(to - at);
  610. crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false);
  611. // SAFETY: a page of an arena of ours, under the mutex.
  612. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) };
  613. if *ours != title[..n] {
  614. ours.copy_from_slice(&title[..n]);
  615. crate::watch::wrote(held.at + at, n);
  616. }
  617. at += n;
  618. }
  619. if whole {
  620. shadow.resend(base + from, base + to);
  621. }
  622. }
  623. /// The pages shaders found empty since the last frame.
  624. fn take_faults(&mut self) {
  625. let mut pages = Vec::new();
  626. for i in 1..MEMORY_FAULTS as usize {
  627. // SAFETY: inside the faults' mapping; the GPU may be writing,
  628. // a number missed now is written again next frame.
  629. let at = unsafe { self.faults.1.add(i) };
  630. // SAFETY: as above.
  631. let page = unsafe { at.read_volatile() };
  632. if page != 0 {
  633. pages.push(u64::from(page));
  634. // SAFETY: as above.
  635. unsafe { at.write_volatile(0) };
  636. }
  637. }
  638. if pages.is_empty() {
  639. return;
  640. }
  641. pages.sort_unstable();
  642. let mut made = 0;
  643. for &page in &pages {
  644. if made < FAULTS && self.faulted < FAULTS_ALL && self.copy_of(page).is_none() && self.map(page) {
  645. made += 1;
  646. self.faulted += 1;
  647. self.bring(page, page + 1);
  648. }
  649. }
  650. self.stats.faults += pages.len() as u64;
  651. // Each is an access that read 0 or was dropped.
  652. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  653. let said = SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  654. if said < 40 || said.is_multiple_of(100) {
  655. let some: Vec<String> = pages
  656. .iter()
  657. .step_by(pages.len().div_ceil(12))
  658. .map(|&p| format!("{:#x}", p * PAGE))
  659. .collect();
  660. tracing::warn!(
  661. frame = self.frame,
  662. pages = pages.len(),
  663. made,
  664. held = self.pages.len(),
  665. ?some,
  666. "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); those that are the title's are there now"
  667. );
  668. }
  669. }
  670. /// The structures named in a list's upload memory around `address`
  671. /// (instances of a top-level build: a structure's address is their last
  672. /// 8 bytes): the first page of each.
  673. fn named_in_upload(&mut self, address: u64) {
  674. let Some((from, len)) = crate::upload::block(address as usize) else {
  675. return;
  676. };
  677. // SAFETY: the block is handed out and stays mapped; the title wrote
  678. // it before it recorded the dispatch.
  679. let words = unsafe { std::slice::from_raw_parts(from as *const u64, len / 8) };
  680. let mut seen = std::collections::HashSet::new();
  681. for &word in words {
  682. if word & 0xFF == 0 && (1 << 32..1 << 37).contains(&word) && seen.insert(word / PAGE) && self.map(word / PAGE) {
  683. let page = word / PAGE;
  684. self.bring(page, page + 1);
  685. }
  686. }
  687. }
  688. /// A small title buffer whose results come back, if its pages are
  689. /// windows of title memory itself (or a copy of the buffer's own).
  690. fn small(&mut self, list: &HostList, start: u64, len: u64) {
  691. let mut at = start;
  692. while at < start + len {
  693. let page = at / PAGE;
  694. let n = ((page + 1) * PAGE).min(start + len) - at;
  695. self.map(page);
  696. if let Some(k) = self.copy_of(page)
  697. && !self.pages.contains_key(&page)
  698. {
  699. self.copies[k].refresh(list, at, n);
  700. self.copies[k].gpu_writes(list, at, n);
  701. self.stats.back += 1;
  702. }
  703. at += n;
  704. }
  705. }
  706. /// Every copy is brought up to date when `list` is submitted, after what
  707. /// it deferred so far (once until a copy of the title's intervenes).
  708. fn bring_up(&self, list: &HostList) {
  709. let (start, len) = self.directory.1.span();
  710. self.directory.1.refresh(list, start, len);
  711. for shadow in &self.copies {
  712. let (start, len) = shadow.span();
  713. shadow.refresh(list, start, len);
  714. }
  715. }
  716. /// Every ten seconds or so, what was used.
  717. fn report(&mut self) {
  718. let now = std::time::Instant::now();
  719. let (since, frame) = *self.stats.from.get_or_insert((now, self.frame));
  720. if now.duration_since(since).as_secs_f64() < 10.0 {
  721. return;
  722. }
  723. let frames = self.frame.wrapping_sub(frame).max(1) as f64;
  724. let s = std::mem::take(&mut self.stats);
  725. tracing::info!(
  726. "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \
  727. {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \
  728. {:.1} packed structures ({} there), {:.2} ms; {} windows; since the last line {} KB of packed structures came and {} of them went, \
  729. and pages for constants {}, views written {}, others {}, upload memory {}, faults in all {}",
  730. self.pages.len(),
  731. (self.pages.len() as u64 * PAGE) >> 20,
  732. self.arenas.len(),
  733. self.copies.len(),
  734. s.uses[0] as f64 / frames,
  735. s.uses[1] as f64 / frames,
  736. s.faults as f64 / frames,
  737. s.unknown as f64 / frames,
  738. s.back as f64 / frames,
  739. s.looked as f64 / frames,
  740. s.changed as f64 / 1024.0 / frames,
  741. s.packed as f64 / frames,
  742. self.packed.len(),
  743. s.micros as f64 / 1000.0 / frames,
  744. self.windows,
  745. s.packed_bytes >> 10,
  746. s.gone,
  747. s.came[0],
  748. s.came[1],
  749. s.came[2],
  750. s.came[3],
  751. self.faulted
  752. );
  753. self.stats.from = Some((now, self.frame));
  754. }
  755. }
  756. /// [`fill`] of a page stores by address do not reach.
  757. fn close(entry: *mut u32, n: usize, offset: u64) {
  758. fill(entry, n | MEMORY_READ_ONLY as usize, offset);
  759. }
  760. /// The offset first: a shader that sees the number sees it too.
  761. fn fill(entry: *mut u32, n: usize, offset: u64) {
  762. // SAFETY: an entry of the directory, under the mutex.
  763. unsafe {
  764. entry.add(1).write_volatile(offset as u32);
  765. entry.write_volatile(n as u32 + 1);
  766. }
  767. }
  768. /// The bytes of a packed structure whose first two dwords these are: the
  769. /// version (6) with the marks of a bottom level and of one that is packed,
  770. /// and its size unpacked in 64-byte nodes.
  771. fn packed_len(header: u64) -> Option<u64> {
  772. let (version, nodes) = (header as u32, header >> 32);
  773. let marks = version >> 16;
  774. (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && nodes * 64 <= PACKED).then_some(nodes * 64)
  775. }
  776. /// Puts what `title` holds into `ours` (what was last taken): the dwords that
  777. /// differ. How many.
  778. fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize {
  779. if never {
  780. ours.copy_from_slice(title);
  781. return PIECE / 4;
  782. }
  783. if ours == title {
  784. return 0;
  785. }
  786. let mut changed = 0;
  787. for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) {
  788. if t != o {
  789. o.copy_from_slice(t);
  790. changed += 1;
  791. }
  792. }
  793. changed
  794. }
  795. /// Before a draw whose shader reads title memory by address: what its
  796. /// root arguments name is made ready (`addresses`: its root views, of them
  797. /// `written` those it writes; `constants`: its root constants, see the
  798. /// module), every numbered copy
  799. /// has its view in `heap`'s run and is brought up to date when `list` is
  800. /// submitted. None if the host cannot hold it; the draw is then dropped.
  801. pub(crate) fn ready(
  802. list: &HostList,
  803. heap: &HostHeap,
  804. addresses: &[u64],
  805. written: &[u64],
  806. constants: &[u32],
  807. use_: Use,
  808. ) -> Option<Ready> {
  809. let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner());
  810. if guard.is_none() {
  811. *guard = Memory::new();
  812. }
  813. let m = guard.as_mut()?;
  814. let frame = crate::frame::current();
  815. if m.frame != frame {
  816. m.frame = frame;
  817. m.refused.clear();
  818. m.take_faults();
  819. m.look_again();
  820. m.report();
  821. }
  822. let builds = use_ != Use::Reads;
  823. while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {}
  824. m.stats.uses[usize::from(builds)] += 1;
  825. // Once per list and page named: the builder dispatches hundreds of times
  826. // a frame with the same arguments.
  827. const READ: usize = usize::MAX - 0x6d;
  828. let named = |kind: usize, at: u64| list.first_use(usize::MAX - (kind << 26) - (at / PAGE) as usize);
  829. // A title address in two constants (low dword, then bits 32 to 39), or
  830. // in one in 256-byte units (the builder's alone). A constant that only
  831. // looks like one names memory nothing reads; one that is not the title's
  832. // memory is refused.
  833. let held = |m: &Memory| m.pages.len() as u64;
  834. let before = held(m);
  835. for (i, &c) in constants.iter().enumerate() {
  836. if let Some(&high) = constants.get(i + 1)
  837. && (1..=0x1F).contains(&high)
  838. && c >= 0x1_0000
  839. {
  840. let at = u64::from(c) | u64::from(high) << 32;
  841. if named(1, at) {
  842. m.ready(at, 1);
  843. }
  844. }
  845. if builds && (0x0100_0000..0x2000_0000).contains(&c) {
  846. let at = u64::from(c) << 8;
  847. if named(1, at) {
  848. m.ready(at, 1);
  849. }
  850. }
  851. }
  852. let mut came = [held(m) - before, 0, 0, 0];
  853. for &at in addresses.iter().filter(|&&a| a >= 1 << 32) {
  854. // (Several structures to a page.)
  855. let mut packed = false;
  856. if builds
  857. && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize)
  858. && crate::shadow::in_buffer(at, 1).is_none()
  859. && m.possible(at / PAGE)
  860. {
  861. // What it needs, as far as it is known now; the rest when the
  862. // list is submitted ([`Memory::land`]).
  863. if let Some((len, _)) = m.packed_at(at) {
  864. packed = true;
  865. for page in at / PAGE..=(at + len - 1) / PAGE {
  866. let new = m.copy_of(page).is_none();
  867. if m.map(page)
  868. && new
  869. && let Some(held) = m.pages.get_mut(&page)
  870. {
  871. held.theirs = true;
  872. }
  873. }
  874. m.bring(at / PAGE, (at + len - 1) / PAGE + 1);
  875. }
  876. list.defer_host(move || {
  877. if let Some(m) = MEMORY.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
  878. m.land(at);
  879. }
  880. });
  881. m.bring_up(list);
  882. }
  883. if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) {
  884. if let Some((start, len)) = crate::shadow::in_buffer(at, 1)
  885. && len <= BACK
  886. && use_ == (Use::Builds { back: true })
  887. && list.first_use(usize::MAX - (5 << 33) - (start >> 2 & 0x7FFF_FFFF) as usize)
  888. {
  889. m.small(list, start, len);
  890. }
  891. m.opens(at);
  892. if !packed && crate::shadow::in_buffer(at, 1).is_none() {
  893. #[cfg(feature = "diagnostics")]
  894. {
  895. let built = m.dump.built.entry(at).or_insert((frame, frame, 0));
  896. (built.1, built.2) = (frame, built.2 + 1);
  897. }
  898. let before = held(m);
  899. m.ready(at, BUILT);
  900. came[1] += held(m).saturating_sub(before);
  901. }
  902. }
  903. if packed || !named(2, at) {
  904. continue;
  905. }
  906. let before = held(m);
  907. match crate::shadow::in_buffer(at, 1) {
  908. Some(_) => {
  909. m.ready(at, 1);
  910. m.named_in_upload(at);
  911. came[3] += held(m).saturating_sub(before);
  912. }
  913. None => {
  914. m.ready(at, if builds { VIEW } else { PAGE });
  915. came[2] += held(m).saturating_sub(before);
  916. }
  917. }
  918. }
  919. for (sum, n) in m.stats.came.iter_mut().zip(came) {
  920. *sum += n;
  921. }
  922. let key = std::ptr::from_ref(heap) as usize;
  923. let (base, made) = match m.heaps.get(&key) {
  924. Some(&run) => run,
  925. None => {
  926. // Held for the heap's life: not given back with a list's slots.
  927. let base = heap.dynamic(COPIES + 1)?;
  928. // Every slot of the run: a number shows no view of another kind.
  929. for n in 0..=COPIES {
  930. heap.null_raw_uav_at(base + n);
  931. }
  932. (base, 0)
  933. }
  934. };
  935. for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) {
  936. let (_, len) = shadow.span();
  937. heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len);
  938. }
  939. m.heaps.insert(key, (base, m.copies.len() as u32));
  940. // Every copy by every list that has come to by-address memory, whoever
  941. // numbered it: an arena another list made while this one was being
  942. // recorded was brought up to date by that list's submission alone, which
  943. // may run after this one's (structures unpacked from zeros, and then
  944. // written over by the arena's first upload: in frames that stream much in
  945. // half of them, run light-8).
  946. let first_read = list.first_use(READ);
  947. if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) {
  948. m.bring_up(list);
  949. }
  950. if first_read {
  951. list.keep(&m.faults.0);
  952. #[cfg(feature = "diagnostics")]
  953. m.dump(list, addresses);
  954. }
  955. #[cfg(feature = "diagnostics")]
  956. if use_ == Use::Reads {
  957. m.dump.walked(addresses);
  958. }
  959. let directory = &m.directory.1;
  960. Some(Ready {
  961. directory: directory.gpu(directory.span().0),
  962. faults: m.faults.2,
  963. base,
  964. })
  965. }
  966. /// `VICTORY_MEMORY_DUMP=<folder>`: when a file `go` appears there, the arenas
  967. /// as the card holds them are copied out and written (`arena-<n>.bin`), with
  968. /// `pages.txt` (title page, arena, offset) and the structures the walking
  969. /// programs were given: to look at the structures offline.
  970. #[cfg(feature = "diagnostics")]
  971. mod dump {
  972. use super::*;
  973. #[derive(Default)]
  974. pub(super) struct Dump {
  975. walked: std::collections::BTreeSet<u64>,
  976. /// Views the builder was given to write outside buffers: the first
  977. /// and the last frame, how often.
  978. pub(super) built: std::collections::BTreeMap<u64, (u64, u64, u64)>,
  979. /// The frame it is written at, and the copies.
  980. due: Option<(u64, Vec<(ID3D12Resource, usize)>)>,
  981. done: bool,
  982. }
  983. impl Dump {
  984. pub(super) fn walked(&mut self, addresses: &[u64]) {
  985. if !self.done && self.walked.len() < 64 {
  986. self.walked.extend(addresses);
  987. }
  988. }
  989. }
  990. fn folder() -> Option<&'static std::path::PathBuf> {
  991. static FOLDER: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
  992. FOLDER.get_or_init(|| std::env::var_os("VICTORY_MEMORY_DUMP").map(Into::into)).as_ref()
  993. }
  994. fn turn(buffer: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
  995. D3D12_RESOURCE_BARRIER {
  996. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  997. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  998. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  999. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  1000. // SAFETY: the same pointer, not counted; the barrier is
  1001. // used while the buffer lives.
  1002. pResource: unsafe { std::mem::transmute_copy(buffer) },
  1003. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  1004. StateBefore: before,
  1005. StateAfter: after,
  1006. }),
  1007. },
  1008. }
  1009. }
  1010. impl Memory {
  1011. /// At a list's first use: the copies are recorded into it.
  1012. pub(super) fn dump(&mut self, list: &HostList, _: &[u64]) {
  1013. let Some(folder) = folder() else { return };
  1014. if let Some((due, _)) = &self.dump.due {
  1015. if self.frame < *due {
  1016. return;
  1017. }
  1018. let copies = self.dump.due.take().map(|d| d.1).unwrap_or_default();
  1019. let mut text = String::new();
  1020. for a in &self.dump.walked {
  1021. text += &format!("walked {a:#x}\n");
  1022. }
  1023. for (a, (first, last, n)) in &self.dump.built {
  1024. text += &format!("built {a:#x} {first} {last} {n}\n");
  1025. }
  1026. for (a, p) in &self.packed {
  1027. text += &format!("packed {a:#x} {} {}\n", p.len, p.frame);
  1028. }
  1029. text += &format!("frame {}\n", self.frame);
  1030. for (page, held) in &self.pages {
  1031. let arena = self.arenas.iter().position(|a| a.0 == held.copy).unwrap_or(usize::MAX);
  1032. let at = held.at - self.arenas[arena].1;
  1033. text += &format!("{:#x} {arena} {at:#x}\n", page * PAGE);
  1034. }
  1035. let _ = std::fs::write(folder.join("pages.txt"), text);
  1036. for (n, (_, data)) in copies.iter().enumerate() {
  1037. // SAFETY: a mapping of an arena's bytes; the copies ran
  1038. // frames ago.
  1039. let bytes = unsafe { std::slice::from_raw_parts(*data as *const u8, ARENA as usize) };
  1040. let _ = std::fs::write(folder.join(format!("arena-{n}.bin")), bytes);
  1041. }
  1042. tracing::info!(arenas = copies.len(), "title memory by address: the arenas are written out");
  1043. return;
  1044. }
  1045. if self.dump.done || !folder.join("go").exists() {
  1046. return;
  1047. }
  1048. self.dump.done = true;
  1049. let Some(host) = host() else { return };
  1050. let mut copies = Vec::new();
  1051. for &(n, _) in &self.arenas {
  1052. let buffer = &self.copies[n].buffer;
  1053. let Some((to, data)) = host.shared_buffer(ARENA) else { break };
  1054. // SAFETY: an open list; live buffers of those sizes. The list
  1055. // has not used the arena yet.
  1056. unsafe {
  1057. list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1058. list.list.CopyBufferRegion(&to, 0, buffer, 0, ARENA);
  1059. list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
  1060. }
  1061. list.keep(&to);
  1062. copies.push((to, data as usize));
  1063. }
  1064. self.dump.due = Some((self.frame + 12, copies));
  1065. }
  1066. }
  1067. }
  1068. #[cfg(test)]
  1069. mod tests {
  1070. use super::*;
  1071. #[test]
  1072. fn a_piece_takes_what_changed() {
  1073. let mut title = [7u8; PIECE];
  1074. let mut ours = vec![0u8; PIECE];
  1075. assert_eq!(merge(&title, &mut ours, true), PIECE / 4);
  1076. assert_eq!(ours, title);
  1077. assert_eq!(merge(&title, &mut ours, false), 0);
  1078. // A dword of it.
  1079. title[41] = 8;
  1080. assert_eq!(merge(&title, &mut ours, false), 1);
  1081. assert_eq!(ours, title);
  1082. }
  1083. #[test]
  1084. fn a_packed_structure_is_known_by_its_header() {
  1085. let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32;
  1086. assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1a * 64));
  1087. // Unpacked, a top level, another version, no size, too big.
  1088. assert_eq!(packed_len(header(0x8002_0006, 0x9a1a)), None);
  1089. assert_eq!(packed_len(header(0x0000_0006, 5)), None);
  1090. assert_eq!(packed_len(header(0x8102_0007, 5)), None);
  1091. assert_eq!(packed_len(header(0x8102_0006, 0)), None);
  1092. assert_eq!(packed_len(header(0x8102_0006, 1 << 21)), None);
  1093. }
  1094. }