memory.rs 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304
  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. #[cfg(feature = "diagnostics")]
  177. trace: trace::Trace,
  178. }
  179. /// Since the last report.
  180. #[derive(Default)]
  181. struct Stats {
  182. from: Option<(std::time::Instant, u64)>,
  183. uses: [u64; 2],
  184. faults: u64,
  185. unknown: u64,
  186. back: u64,
  187. /// Pages looked at, bytes that changed, packed structures sent.
  188. looked: u64,
  189. changed: u64,
  190. packed: u64,
  191. packed_bytes: u64,
  192. gone: u64,
  193. /// Pages that came for an address in constants, a written view, another
  194. /// view, a structure named in upload memory.
  195. came: [u64; 4],
  196. micros: u64,
  197. }
  198. // SAFETY: the mappings are of memory the struct owns; all access is under
  199. // the mutex.
  200. unsafe impl Send for Memory {}
  201. static MEMORY: Mutex<Option<Memory>> = Mutex::new(None);
  202. /// What a draw binds.
  203. pub(crate) struct Ready {
  204. pub(crate) directory: u64,
  205. pub(crate) faults: u64,
  206. /// The view heap slot of the null view; copy `n`'s view is `n` further.
  207. pub(crate) base: u32,
  208. }
  209. impl Memory {
  210. fn new() -> Option<Memory> {
  211. let host = host()?;
  212. let bytes = u64::from(MEMORY_PAGES) * 8;
  213. // Zeroed, and watched for writes as the title's memory is.
  214. let entries = crate::upload::reserve(bytes as usize)?;
  215. let directory = crate::shadow::by_address(entries as u64, bytes)?;
  216. crate::host::name(&directory.buffer, || "title memory by address: directory".into());
  217. let (faults, data) = host.shared_buffer(u64::from(MEMORY_FAULTS) * 4)?;
  218. crate::host::name(&faults, || "title memory by address: faults".into());
  219. // SAFETY: a fresh mapping of at least that many bytes.
  220. unsafe { std::ptr::write_bytes(data, 0, MEMORY_FAULTS as usize * 4) };
  221. // SAFETY: a live buffer.
  222. let gpu = unsafe { faults.GetGPUVirtualAddress() };
  223. tracing::info!("title memory by address: a shader reads or writes through raw addresses");
  224. Some(Memory {
  225. directory: (entries as *mut u32, directory),
  226. faults: (faults, data.cast::<u32>(), gpu),
  227. copies: Vec::new(),
  228. numbers: HashMap::new(),
  229. arenas: Vec::new(),
  230. pages: HashMap::new(),
  231. order: Vec::new(),
  232. sweep: 0,
  233. windows: 0,
  234. packed: HashMap::new(),
  235. packed_order: Vec::new(),
  236. packed_sweep: 0,
  237. free: Vec::new(),
  238. open: Default::default(),
  239. faulted: 0,
  240. heaps: HashMap::new(),
  241. frame: u64::MAX,
  242. refused: Default::default(),
  243. stats: Stats::default(),
  244. #[cfg(feature = "diagnostics")]
  245. dump: Default::default(),
  246. #[cfg(feature = "diagnostics")]
  247. trace: Default::default(),
  248. })
  249. }
  250. /// The directory's entry of `page`.
  251. fn entry(&self, page: u64) -> *mut u32 {
  252. debug_assert!(page < u64::from(MEMORY_PAGES));
  253. // SAFETY: inside the directory.
  254. unsafe { self.directory.0.add(page as usize * 2) }
  255. }
  256. /// The place in `copies` of the copy that holds `page`, if one does.
  257. fn copy_of(&self, page: u64) -> Option<usize> {
  258. if page >= u64::from(MEMORY_PAGES) {
  259. return None;
  260. }
  261. // SAFETY: an entry of the directory.
  262. ((unsafe { self.entry(page).read() } & !MEMORY_READ_ONLY) as usize).checked_sub(1)
  263. }
  264. /// Whether `page` can be given a place: in the directory, not turned down
  265. /// this frame, and the title's GPU memory. (A shader's pointer, or a
  266. /// constant taken for an address, may be anything.)
  267. fn possible(&mut self, page: u64) -> bool {
  268. // Not the last entry: addresses past the directory read it, and it
  269. // stays empty.
  270. if page < 0x1_0000 || page >= u64::from(MEMORY_PAGES) - 1 || self.refused.contains(&page) {
  271. return false;
  272. }
  273. let at = (page * PAGE) as usize;
  274. let ours = crate::texture::committed(at as *const u8, PAGE as usize)
  275. && crate::watch::writes(at, at + PAGE as usize, true).is_some();
  276. if !ours {
  277. self.refused.insert(page);
  278. self.stats.unknown += 1;
  279. }
  280. ours
  281. }
  282. /// Gives a copy a number, if one is left.
  283. fn number(&mut self, shadow: Arc<Shadow>) -> Option<usize> {
  284. let key = Arc::as_ptr(&shadow) as usize;
  285. if let Some(&n) = self.numbers.get(&key) {
  286. return Some(n);
  287. }
  288. if self.copies.len() >= COPIES as usize {
  289. static ONCE: std::sync::Once = std::sync::Once::new();
  290. ONCE.call_once(|| tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros"));
  291. return None;
  292. }
  293. // SAFETY: a live buffer.
  294. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  295. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  296. return None;
  297. }
  298. self.copies.push(shadow);
  299. let n = self.copies.len() - 1;
  300. self.numbers.insert(key, n);
  301. Some(n)
  302. }
  303. /// Gives `page` a place, if it has none and the memory is the title's;
  304. /// whether it has one then.
  305. fn map(&mut self, page: u64) -> bool {
  306. if self.copy_of(page).is_some() {
  307. return true;
  308. }
  309. if !self.possible(page) {
  310. return false;
  311. }
  312. let start = page * PAGE;
  313. if crate::shadow::in_buffer(start, PAGE).is_some() {
  314. let Some(shadow) = crate::shadow::find(start, PAGE) else {
  315. return false;
  316. };
  317. let fresh = !self.numbers.contains_key(&(Arc::as_ptr(&shadow) as usize));
  318. let Some(n) = self.number(shadow.clone()) else {
  319. return false;
  320. };
  321. // Every page the copy holds whole, not only the one asked for.
  322. // shortcut: a page of a title buffer inside this one that has a
  323. // copy of its own is given this copy too.
  324. if fresh {
  325. let (first, len) = shadow.span();
  326. let mut at = first.next_multiple_of(PAGE);
  327. while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 {
  328. let entry = self.entry(at / PAGE);
  329. // SAFETY: an entry of the directory.
  330. if unsafe { entry.read() } == 0 {
  331. close(entry, n, at - first);
  332. }
  333. at += PAGE;
  334. }
  335. }
  336. // SAFETY: as above.
  337. if unsafe { self.entry(page).read() } == 0 {
  338. close(self.entry(page), n, start - shadow.span().0);
  339. }
  340. return true;
  341. }
  342. // Small title buffers in it: what the builder stores in them comes
  343. // back, so title memory itself.
  344. if self.windows < WINDOWS && crate::shadow::small_buffer_in(start, PAGE, BACK) {
  345. if let Some(shadow) = crate::shadow::by_address(start, PAGE)
  346. && let Some(n) = self.number(shadow)
  347. {
  348. self.windows += 1;
  349. fill(self.entry(page), n, 0);
  350. return true;
  351. }
  352. return false;
  353. }
  354. if self.pages.len() >= MOST {
  355. static ONCE: std::sync::Once = std::sync::Once::new();
  356. ONCE.call_once(|| tracing::warn!(MOST, "title memory by address: no more pages are taken; others read zeros"));
  357. return false;
  358. }
  359. if let Some((copy, at)) = self.free.pop() {
  360. self.hold(page, at, copy);
  361. return true;
  362. }
  363. if !self.another() {
  364. return false;
  365. }
  366. let Some((copy, at)) = self.free.pop() else {
  367. return false;
  368. };
  369. self.hold(page, at, copy);
  370. true
  371. }
  372. /// Another arena's pages.
  373. fn another(&mut self) -> bool {
  374. let Some(at) = crate::upload::reserve(ARENA as usize) else {
  375. return false;
  376. };
  377. let Some(n) = crate::shadow::by_address(at as u64, ARENA).and_then(|s| self.number(s)) else {
  378. return false;
  379. };
  380. self.arenas.push((n, at));
  381. // The lowest first.
  382. self.free.extend((0..(ARENA / PAGE) as usize).rev().map(|i| (n, at + i * PAGE as usize)));
  383. true
  384. }
  385. /// `page` is held at `at` in the arena that is `copy`.
  386. fn hold(&mut self, page: u64, at: usize, copy: usize) {
  387. self.pages.insert(page, Held { at, copy, taken: 0, looked: u64::MAX, born: self.frame, owners: 0, theirs: false });
  388. self.order.push(page);
  389. fill(self.entry(page), copy, at as u64 - self.copies[copy].span().0);
  390. }
  391. /// The packed structure at `address` is gone: the pages it alone had are
  392. /// given back.
  393. fn gone(&mut self, address: u64) {
  394. let Some(packed) = self.packed.remove(&address) else { return };
  395. for page in address / PAGE..=(address + packed.len - 1) / PAGE {
  396. let Some(held) = self.pages.get_mut(&page) else { continue };
  397. held.owners = held.owners.saturating_sub(1);
  398. if held.owners == 0 && held.theirs {
  399. self.free.push((held.copy, held.at));
  400. self.pages.remove(&page);
  401. // SAFETY: an entry of the directory, under the mutex.
  402. unsafe { self.entry(page).write_volatile(0) };
  403. }
  404. }
  405. self.stats.gone += 1;
  406. }
  407. /// Whether the packed structure at `address` is still in title memory.
  408. fn there(&self, address: u64) -> bool {
  409. let mut header = [0u8; 8];
  410. crate::texture::committed(address as *const u8, 8) && {
  411. crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false);
  412. self.packed.get(&address).is_some_and(|p| p.header == u64::from_le_bytes(header))
  413. }
  414. }
  415. /// Looks at some of the pages and packed structures again.
  416. fn look_again(&mut self) {
  417. for _ in 0..self.order.len().div_ceil(SWEEP) {
  418. self.sweep = (self.sweep + 1) % self.order.len();
  419. let page = self.order[self.sweep];
  420. if self.pages.contains_key(&page) {
  421. self.bring(page, page + 1);
  422. } else {
  423. self.order.swap_remove(self.sweep);
  424. if self.order.is_empty() {
  425. break;
  426. }
  427. }
  428. }
  429. for _ in 0..self.packed_order.len().div_ceil(SWEEP) {
  430. self.packed_sweep = (self.packed_sweep + 1) % self.packed_order.len();
  431. let address = self.packed_order[self.packed_sweep];
  432. if !self.packed.contains_key(&address) {
  433. self.packed_order.swap_remove(self.packed_sweep);
  434. if self.packed_order.is_empty() {
  435. break;
  436. }
  437. } else if !self.there(address) {
  438. self.gone(address);
  439. }
  440. }
  441. }
  442. /// A dispatch of the builder was given `address` to write: if it is in a
  443. /// title buffer's copy, stores by address reach that from here on.
  444. fn opens(&mut self, address: u64) {
  445. let Some(n) = self.map(address / PAGE).then(|| self.copy_of(address / PAGE)).flatten() else {
  446. return;
  447. };
  448. if self.pages.contains_key(&(address / PAGE)) || !self.open.insert(n) {
  449. return;
  450. }
  451. // (Its pages hold what the CPU writes beside the builder's scratch.)
  452. self.copies[n].keep_stores();
  453. let (first, len) = self.copies[n].span();
  454. tracing::info!(
  455. start = format_args!("{first:#x}"),
  456. len,
  457. "title memory by address: the structure builder may store in a title buffer"
  458. );
  459. for page in first.div_ceil(PAGE)..(first + len) / PAGE {
  460. if self.copy_of(page) == Some(n) {
  461. fill(self.entry(page), n, page * PAGE - first);
  462. }
  463. }
  464. }
  465. /// [`Memory::map`] of the pages of `[address, address + len)`, up to the
  466. /// first that is not the title's, and what the title wrote there since
  467. /// they were taken goes into the arenas.
  468. fn ready(&mut self, address: u64, len: u64) {
  469. let first = address / PAGE;
  470. let mut end = first;
  471. while end * PAGE < address + len && self.map(end) {
  472. end += 1;
  473. }
  474. self.bring(first, end);
  475. }
  476. /// Takes the pages `[first, end)` that are in arenas from title memory
  477. /// where it wrote them.
  478. fn bring(&mut self, first: u64, end: u64) {
  479. // Once a frame: the builder names the same pages list after list.
  480. let frame = self.frame;
  481. if !(first..end).any(|page| self.pages.get(&page).is_some_and(|h| h.looked != frame)) {
  482. return;
  483. }
  484. let started = std::time::Instant::now();
  485. let answer = crate::watch::writes((first * PAGE) as usize, (end * PAGE) as usize, true);
  486. for page in first..end {
  487. let Some(held) = self.pages.get_mut(&page) else {
  488. continue;
  489. };
  490. if held.looked == frame {
  491. continue;
  492. }
  493. held.looked = frame;
  494. self.stats.looked += 1;
  495. let wrote = answer
  496. .as_ref()
  497. .map(|(_, w)| w.binary_search_by_key(&(page as usize), |w| w.0).map_or(0, |i| w[i].1));
  498. let now = answer.as_ref().map_or(1, |a| a.0);
  499. let stale = held.taken == 0 || wrote.is_none_or(|w| w > held.taken);
  500. if !stale {
  501. continue;
  502. }
  503. let never = std::mem::replace(&mut held.taken, now.max(1)) == 0;
  504. let shadow = &self.copies[held.copy];
  505. let base = held.at - shadow.span().0 as usize;
  506. let mut title = [0u8; PIECE];
  507. for piece in (0..PAGE as usize).step_by(PIECE) {
  508. let from = (page * PAGE) as usize + piece;
  509. // (Pages that are not there read as zeros.)
  510. crate::host::copy_mapped(title.as_mut_ptr(), from as *const u8, PIECE, false);
  511. // SAFETY: a page of an arena of ours, under the mutex.
  512. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + piece) as *mut u8, PIECE) };
  513. self.stats.changed += merge(&title, ours, never) as u64 * 4;
  514. }
  515. if never {
  516. shadow.resend(base, base + PAGE as usize);
  517. }
  518. }
  519. self.stats.micros += started.elapsed().as_micros() as u64;
  520. }
  521. /// The bytes of a packed structure title memory has at `address` by now,
  522. /// and its first two dwords.
  523. fn packed_at(&self, address: u64) -> Option<(u64, u64)> {
  524. if address & 0xFF != 0 {
  525. return None;
  526. }
  527. let mut header = [0u8; 8];
  528. crate::host::copy_mapped(header.as_mut_ptr(), address as *const u8, 8, false);
  529. let header = u64::from_le_bytes(header);
  530. Some((packed_len(header)?, header))
  531. }
  532. /// At the submission of a list whose builder dispatch was given `address`
  533. /// outside buffers, in the order of its copies: what title memory has
  534. /// there now goes up. When the dispatch is recorded it may not be there
  535. /// yet: the title's queue waits for its streaming. (Nothing is asked of
  536. /// the write watch here: the submission's asking stands.)
  537. fn land(&mut self, address: u64) {
  538. let page = address / PAGE;
  539. if !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize) {
  540. return;
  541. }
  542. let Some((len, header)) = self.packed_at(address) else {
  543. // Anything else: what came since its page was first taken.
  544. for page in page..=(address + VIEW - 1) / PAGE {
  545. if self.pages.get(&page).is_some_and(|h| h.born + YOUNG >= self.frame) {
  546. self.take(page, 0, PAGE as usize, false);
  547. }
  548. }
  549. return;
  550. };
  551. if let Some(known) = self.packed.get_mut(&address) {
  552. let soon = known.frame + AGAIN >= self.frame;
  553. known.frame = self.frame;
  554. if known.header == header && soon {
  555. return;
  556. }
  557. if known.header != header {
  558. self.gone(address);
  559. }
  560. }
  561. let last = (address + len - 1) / PAGE;
  562. if !self.packed.contains_key(&address) {
  563. self.packed.insert(address, Packed { frame: self.frame, len, header });
  564. self.packed_order.push(address);
  565. for page in page..=last {
  566. let new = self.copy_of(page).is_none();
  567. if new && !self.place(page) {
  568. continue;
  569. }
  570. if let Some(held) = self.pages.get_mut(&page) {
  571. held.owners += 1;
  572. held.theirs |= new;
  573. }
  574. }
  575. self.stats.packed_bytes += len;
  576. }
  577. for page in page..=last {
  578. let from = address.max(page * PAGE) - page * PAGE;
  579. let to = (address + len).min((page + 1) * PAGE) - page * PAGE;
  580. self.take(page, from as usize, to as usize, true);
  581. }
  582. self.stats.packed += 1;
  583. }
  584. /// A place in an arena for a page of committed title memory, at a
  585. /// submission: only one there is already (the list brings up the arenas
  586. /// it knew when it was recorded).
  587. fn place(&mut self, page: u64) -> bool {
  588. if page < 0x1_0000
  589. || page >= u64::from(MEMORY_PAGES) - 1
  590. || !crate::texture::committed((page * PAGE) as *const u8, PAGE as usize)
  591. || crate::shadow::in_buffer(page * PAGE, PAGE).is_some()
  592. {
  593. return false;
  594. }
  595. let Some((copy, at)) = self.free.pop() else {
  596. return false;
  597. };
  598. self.hold(page, at, copy);
  599. crate::watch::wrote(self.entry(page) as usize, 8);
  600. self.take(page, 0, PAGE as usize, true);
  601. true
  602. }
  603. /// Bytes `from..to` of `page` from title memory into its arena's page, at
  604. /// a submission; `whole`: sent whether they differ from those last taken
  605. /// or not.
  606. fn take(&mut self, page: u64, from: usize, to: usize, whole: bool) {
  607. let Some(held) = self.pages.get(&page) else { return };
  608. let shadow = &self.copies[held.copy];
  609. let base = held.at - shadow.span().0 as usize;
  610. let mut title = [0u8; PIECE];
  611. let mut at = from;
  612. while at < to {
  613. let n = (PIECE - at % PIECE).min(to - at);
  614. crate::host::copy_mapped(title.as_mut_ptr(), (page as usize * PAGE as usize + at) as *const u8, n, false);
  615. // SAFETY: a page of an arena of ours, under the mutex.
  616. let ours = unsafe { std::slice::from_raw_parts_mut((held.at + at) as *mut u8, n) };
  617. if *ours != title[..n] {
  618. ours.copy_from_slice(&title[..n]);
  619. crate::watch::wrote(held.at + at, n);
  620. }
  621. at += n;
  622. }
  623. if whole {
  624. shadow.resend(base + from, base + to);
  625. }
  626. }
  627. /// The pages shaders found empty since the last frame.
  628. fn take_faults(&mut self) {
  629. let mut pages = Vec::new();
  630. for i in 1..MEMORY_FAULTS as usize {
  631. // SAFETY: inside the faults' mapping; the GPU may be writing,
  632. // a number missed now is written again next frame.
  633. let at = unsafe { self.faults.1.add(i) };
  634. // SAFETY: as above.
  635. let page = unsafe { at.read_volatile() };
  636. if page != 0 {
  637. pages.push(u64::from(page));
  638. // SAFETY: as above.
  639. unsafe { at.write_volatile(0) };
  640. }
  641. }
  642. if pages.is_empty() {
  643. return;
  644. }
  645. pages.sort_unstable();
  646. let mut made = 0;
  647. for &page in &pages {
  648. if made < FAULTS && self.faulted < FAULTS_ALL && self.copy_of(page).is_none() && self.map(page) {
  649. made += 1;
  650. self.faulted += 1;
  651. self.bring(page, page + 1);
  652. }
  653. }
  654. self.stats.faults += pages.len() as u64;
  655. // Each is an access that read 0 or was dropped.
  656. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  657. let said = SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  658. if said < 40 || said.is_multiple_of(100) {
  659. let some: Vec<String> = pages
  660. .iter()
  661. .step_by(pages.len().div_ceil(12))
  662. .map(|&p| format!("{:#x}", p * PAGE))
  663. .collect();
  664. tracing::warn!(
  665. frame = self.frame,
  666. pages = pages.len(),
  667. made,
  668. held = self.pages.len(),
  669. ?some,
  670. "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"
  671. );
  672. }
  673. }
  674. /// The structures named in a list's upload memory around `address`
  675. /// (instances of a top-level build: a structure's address is their last
  676. /// 8 bytes): the first page of each.
  677. fn named_in_upload(&mut self, address: u64) {
  678. let Some((from, len)) = crate::upload::block(address as usize) else {
  679. return;
  680. };
  681. // SAFETY: the block is handed out and stays mapped; the title wrote
  682. // it before it recorded the dispatch.
  683. let words = unsafe { std::slice::from_raw_parts(from as *const u64, len / 8) };
  684. let mut seen = std::collections::HashSet::new();
  685. for &word in words {
  686. if word & 0xFF == 0 && (1 << 32..1 << 37).contains(&word) && seen.insert(word / PAGE) && self.map(word / PAGE) {
  687. let page = word / PAGE;
  688. self.bring(page, page + 1);
  689. }
  690. }
  691. }
  692. /// A small title buffer whose results come back, if its pages are
  693. /// windows of title memory itself (or a copy of the buffer's own).
  694. fn small(&mut self, list: &HostList, start: u64, len: u64) {
  695. let mut at = start;
  696. while at < start + len {
  697. let page = at / PAGE;
  698. let n = ((page + 1) * PAGE).min(start + len) - at;
  699. self.map(page);
  700. if let Some(k) = self.copy_of(page)
  701. && !self.pages.contains_key(&page)
  702. {
  703. self.copies[k].refresh(list, at, n);
  704. self.copies[k].gpu_writes(list, at, n);
  705. self.stats.back += 1;
  706. }
  707. at += n;
  708. }
  709. }
  710. /// Every copy is brought up to date when `list` is submitted, after what
  711. /// it deferred so far (once until a copy of the title's intervenes).
  712. fn bring_up(&self, list: &HostList) {
  713. let (start, len) = self.directory.1.span();
  714. self.directory.1.refresh(list, start, len);
  715. for shadow in &self.copies {
  716. let (start, len) = shadow.span();
  717. shadow.refresh(list, start, len);
  718. }
  719. }
  720. /// Every ten seconds or so, what was used.
  721. fn report(&mut self) {
  722. let now = std::time::Instant::now();
  723. let (since, frame) = *self.stats.from.get_or_insert((now, self.frame));
  724. if now.duration_since(since).as_secs_f64() < 10.0 {
  725. return;
  726. }
  727. let frames = self.frame.wrapping_sub(frame).max(1) as f64;
  728. let s = std::mem::take(&mut self.stats);
  729. tracing::info!(
  730. "title memory by address: {} pages ({} MB) in {} arenas, {} copies in all; per frame {:.0} dispatches that read, {:.0} that build, \
  731. {:.1} pages that had no copy, {:.1} pages turned down, {:.1} results brought back; {:.0} pages looked at, {:.1} KB changed, \
  732. {:.1} packed structures ({} there), {:.2} ms; {} windows; since the last line {} KB of packed structures came and {} of them went, \
  733. and pages for constants {}, views written {}, others {}, upload memory {}, faults in all {}",
  734. self.pages.len(),
  735. (self.pages.len() as u64 * PAGE) >> 20,
  736. self.arenas.len(),
  737. self.copies.len(),
  738. s.uses[0] as f64 / frames,
  739. s.uses[1] as f64 / frames,
  740. s.faults as f64 / frames,
  741. s.unknown as f64 / frames,
  742. s.back as f64 / frames,
  743. s.looked as f64 / frames,
  744. s.changed as f64 / 1024.0 / frames,
  745. s.packed as f64 / frames,
  746. self.packed.len(),
  747. s.micros as f64 / 1000.0 / frames,
  748. self.windows,
  749. s.packed_bytes >> 10,
  750. s.gone,
  751. s.came[0],
  752. s.came[1],
  753. s.came[2],
  754. s.came[3],
  755. self.faulted
  756. );
  757. self.stats.from = Some((now, self.frame));
  758. }
  759. }
  760. /// A list with this key ([`HostList::used`]) asks the builder for sizes.
  761. const SIZES: usize = usize::MAX - (9 << 33);
  762. /// Whether a submission that asks for the sizes of structures is waited for,
  763. /// and landed, before the title goes on (`VICTORY_BVH_SIZES_WAIT=1`; off).
  764. ///
  765. /// Off: it does not help. In run light-15, with it, 33 of 154 copies had the
  766. /// slot's old size still (all of them recorded one frame after the size was
  767. /// asked for) against 53 of 230 in light-11, 48 of 275 dynamic structures
  768. /// were good, and the title asks in every frame, so every frame waits (109 ms
  769. /// against 90). The title reads the slot before our submission of the asking
  770. /// list is through, or reads it for another purpose; not known.
  771. ///
  772. /// The title asks for a new structure's compacted size (a program of one
  773. /// thread stores it into a small buffer), reads it a frame or two later
  774. /// without looking whether it is there, takes memory of that size and copies
  775. /// the structure into it. With submissions that land up to two frames late it
  776. /// read what the slot held before, some other structure's size, and the copy
  777. /// wrote over its neighbours: of 230 such copies of run light-11, 99 were
  778. /// asked for two frames earlier and landed in that frame, none of those with
  779. /// the right size.
  780. fn sizes_wait() -> bool {
  781. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  782. *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_SIZES_WAIT").is_some_and(|v| v == "1"))
  783. }
  784. /// Whether a dispatch of the builder is its program of a structure's size:
  785. /// one thread, the structure's address and what to store (1: the compacted
  786. /// size) as constants, a small title buffer to store into.
  787. fn asks_size(written: &[u64], constants: &[u32], threads: Option<[u32; 3]>) -> bool {
  788. threads == Some([1, 1, 1])
  789. && matches!(*constants, [_, hi, 1..=3, ..] if (1..0x20).contains(&hi))
  790. && written.first().is_some_and(|&at| crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK))
  791. }
  792. /// Whether one of `lists` asks for sizes.
  793. pub(crate) fn asked_sizes<'a>(lists: impl Iterator<Item = &'a HostList>) -> bool {
  794. let mut lists = lists;
  795. let asked = sizes_wait() && lists.any(|l| l.used(SIZES));
  796. if asked {
  797. static TIMES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  798. let n = TIMES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  799. if n.is_power_of_two() || n.is_multiple_of(100) {
  800. tracing::info!(n, frame = crate::frame::current(), "submissions that ask for structures' sizes, waited for");
  801. }
  802. }
  803. asked
  804. }
  805. /// [`fill`] of a page stores by address do not reach.
  806. fn close(entry: *mut u32, n: usize, offset: u64) {
  807. fill(entry, n | MEMORY_READ_ONLY as usize, offset);
  808. }
  809. /// The offset first: a shader that sees the number sees it too.
  810. fn fill(entry: *mut u32, n: usize, offset: u64) {
  811. // SAFETY: an entry of the directory, under the mutex.
  812. unsafe {
  813. entry.add(1).write_volatile(offset as u32);
  814. entry.write_volatile(n as u32 + 1);
  815. }
  816. }
  817. /// The bytes of a packed structure whose first two dwords these are: the
  818. /// version (6) with the marks of a bottom level and of one that is packed,
  819. /// and its size unpacked in 64-byte nodes.
  820. fn packed_len(header: u64) -> Option<u64> {
  821. let (version, nodes) = (header as u32, header >> 32);
  822. let marks = version >> 16;
  823. // The header counts its nodes of 64 bytes without the last one: the
  824. // builder's own program of a structure's size stores one more.
  825. let len = (nodes + 1) * 64;
  826. (version & 0xFFFF == 6 && marks & 0x8100 == 0x8100 && nodes > 0 && len <= PACKED).then_some(len)
  827. }
  828. /// Puts what `title` holds into `ours` (what was last taken): the dwords that
  829. /// differ. How many.
  830. fn merge(title: &[u8; PIECE], ours: &mut [u8], never: bool) -> usize {
  831. if never {
  832. ours.copy_from_slice(title);
  833. return PIECE / 4;
  834. }
  835. if ours == title {
  836. return 0;
  837. }
  838. let mut changed = 0;
  839. for (t, o) in title.chunks_exact(4).zip(ours.chunks_exact_mut(4)) {
  840. if t != o {
  841. o.copy_from_slice(t);
  842. changed += 1;
  843. }
  844. }
  845. changed
  846. }
  847. /// Before a draw whose shader reads title memory by address: what its
  848. /// root arguments name is made ready (`addresses`: its root views, of them
  849. /// `written` those it writes; `constants`: its root constants, see the
  850. /// module), every numbered copy
  851. /// has its view in `heap`'s run and is brought up to date when `list` is
  852. /// submitted. None if the host cannot hold it; the draw is then dropped.
  853. pub(crate) fn ready(
  854. list: &HostList,
  855. heap: &HostHeap,
  856. addresses: &[u64],
  857. written: &[u64],
  858. constants: &[u32],
  859. use_: Use,
  860. threads: Option<[u32; 3]>,
  861. ) -> Option<Ready> {
  862. let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner());
  863. if guard.is_none() {
  864. *guard = Memory::new();
  865. }
  866. let m = guard.as_mut()?;
  867. let frame = crate::frame::current();
  868. if m.frame != frame {
  869. m.frame = frame;
  870. m.refused.clear();
  871. m.take_faults();
  872. m.look_again();
  873. m.report();
  874. #[cfg(feature = "diagnostics")]
  875. m.trace.look(frame);
  876. }
  877. #[cfg(feature = "diagnostics")]
  878. if use_ != Use::Reads {
  879. m.trace.dispatch(frame, list, addresses, written, constants, threads);
  880. }
  881. let builds = use_ != Use::Reads;
  882. if builds && sizes_wait() && asks_size(written, constants, threads) {
  883. list.first_use(SIZES);
  884. }
  885. while builds && m.free.len() < SPARE && m.pages.len() + m.free.len() < MOST && m.another() {}
  886. m.stats.uses[usize::from(builds)] += 1;
  887. // Once per list and page named: the builder dispatches hundreds of times
  888. // a frame with the same arguments.
  889. const READ: usize = usize::MAX - 0x6d;
  890. let named = |kind: usize, at: u64| list.first_use(usize::MAX - (kind << 26) - (at / PAGE) as usize);
  891. // A title address in two constants (low dword, then bits 32 to 39), or
  892. // in one in 256-byte units (the builder's alone). A constant that only
  893. // looks like one names memory nothing reads; one that is not the title's
  894. // memory is refused.
  895. let held = |m: &Memory| m.pages.len() as u64;
  896. let before = held(m);
  897. for (i, &c) in constants.iter().enumerate() {
  898. if let Some(&high) = constants.get(i + 1)
  899. && (1..=0x1F).contains(&high)
  900. && c >= 0x1_0000
  901. {
  902. let at = u64::from(c) | u64::from(high) << 32;
  903. if named(1, at) {
  904. m.ready(at, 1);
  905. }
  906. }
  907. if builds && (0x0100_0000..0x2000_0000).contains(&c) {
  908. let at = u64::from(c) << 8;
  909. if named(1, at) {
  910. m.ready(at, 1);
  911. }
  912. }
  913. }
  914. let mut came = [held(m) - before, 0, 0, 0];
  915. for &at in addresses.iter().filter(|&&a| a >= 1 << 32) {
  916. // (Several structures to a page.)
  917. let mut packed = false;
  918. if builds
  919. && list.first_use(usize::MAX - (3 << 33) - (at >> 8) as usize)
  920. && crate::shadow::in_buffer(at, 1).is_none()
  921. && m.possible(at / PAGE)
  922. {
  923. // What it needs, as far as it is known now; the rest when the
  924. // list is submitted ([`Memory::land`]).
  925. if let Some((len, _)) = m.packed_at(at) {
  926. packed = true;
  927. for page in at / PAGE..=(at + len - 1) / PAGE {
  928. let new = m.copy_of(page).is_none();
  929. if m.map(page)
  930. && new
  931. && let Some(held) = m.pages.get_mut(&page)
  932. {
  933. held.theirs = true;
  934. }
  935. }
  936. m.bring(at / PAGE, (at + len - 1) / PAGE + 1);
  937. }
  938. list.defer_host(move || {
  939. if let Some(m) = MEMORY.lock().unwrap_or_else(|e| e.into_inner()).as_mut() {
  940. m.land(at);
  941. }
  942. });
  943. m.bring_up(list);
  944. }
  945. if builds && written.contains(&at) && list.first_use(usize::MAX - (4 << 33) - (at >> 2 & 0x7FFF_FFFF) as usize) {
  946. if let Some((start, len)) = crate::shadow::in_buffer(at, 1)
  947. && len <= BACK
  948. && use_ == (Use::Builds { back: true })
  949. && list.first_use(usize::MAX - (5 << 33) - (start >> 2 & 0x7FFF_FFFF) as usize)
  950. {
  951. m.small(list, start, len);
  952. }
  953. m.opens(at);
  954. if !packed && crate::shadow::in_buffer(at, 1).is_none() {
  955. #[cfg(feature = "diagnostics")]
  956. {
  957. let built = m.dump.built.entry(at).or_insert((frame, frame, 0));
  958. (built.1, built.2) = (frame, built.2 + 1);
  959. }
  960. let before = held(m);
  961. m.ready(at, BUILT);
  962. came[1] += held(m).saturating_sub(before);
  963. }
  964. }
  965. if packed || !named(2, at) {
  966. continue;
  967. }
  968. let before = held(m);
  969. match crate::shadow::in_buffer(at, 1) {
  970. Some(_) => {
  971. m.ready(at, 1);
  972. m.named_in_upload(at);
  973. came[3] += held(m).saturating_sub(before);
  974. }
  975. None => {
  976. m.ready(at, if builds { VIEW } else { PAGE });
  977. came[2] += held(m).saturating_sub(before);
  978. }
  979. }
  980. }
  981. for (sum, n) in m.stats.came.iter_mut().zip(came) {
  982. *sum += n;
  983. }
  984. let key = std::ptr::from_ref(heap) as usize;
  985. let (base, made) = match m.heaps.get(&key) {
  986. Some(&run) => run,
  987. None => {
  988. // Held for the heap's life: not given back with a list's slots.
  989. let base = heap.dynamic(COPIES + 1)?;
  990. // Every slot of the run: a number shows no view of another kind.
  991. for n in 0..=COPIES {
  992. heap.null_raw_uav_at(base + n);
  993. }
  994. (base, 0)
  995. }
  996. };
  997. for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) {
  998. let (_, len) = shadow.span();
  999. heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len);
  1000. }
  1001. m.heaps.insert(key, (base, m.copies.len() as u32));
  1002. // Every copy by every list that has come to by-address memory, whoever
  1003. // numbered it: an arena another list made while this one was being
  1004. // recorded was brought up to date by that list's submission alone, which
  1005. // may run after this one's (structures unpacked from zeros, and then
  1006. // written over by the arena's first upload: in frames that stream much in
  1007. // half of them, run light-8).
  1008. let first_read = list.first_use(READ);
  1009. if list.first_use(usize::MAX - (6 << 33) - m.copies.len()) {
  1010. m.bring_up(list);
  1011. }
  1012. if first_read {
  1013. list.keep(&m.faults.0);
  1014. #[cfg(feature = "diagnostics")]
  1015. m.dump(list, addresses);
  1016. }
  1017. #[cfg(feature = "diagnostics")]
  1018. if use_ == Use::Reads {
  1019. m.dump.walked(addresses);
  1020. }
  1021. let directory = &m.directory.1;
  1022. Some(Ready {
  1023. directory: directory.gpu(directory.span().0),
  1024. faults: m.faults.2,
  1025. base,
  1026. })
  1027. }
  1028. /// `VICTORY_BVH_TRACE=1`: the sizes the builder is asked for (its program of
  1029. /// one thread that stores a structure's compacted size) and when title memory
  1030. /// has them, and the copies to a place of that size.
  1031. #[cfg(feature = "diagnostics")]
  1032. mod trace {
  1033. use super::*;
  1034. #[derive(Default)]
  1035. pub(super) struct Trace {
  1036. /// Frame, where the size goes, the structure, what title memory had.
  1037. asked: Vec<(u64, u64, u64, u64)>,
  1038. /// By structure, what its size was when last seen to change.
  1039. sizes: HashMap<u64, (u64, u64)>,
  1040. said: u32,
  1041. }
  1042. fn on() -> bool {
  1043. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1044. *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_TRACE").is_some_and(|v| v == "1"))
  1045. }
  1046. fn value(at: u64) -> u64 {
  1047. let mut b = [0u8; 8];
  1048. crate::host::copy_mapped(b.as_mut_ptr(), at as *const u8, 8, false);
  1049. u64::from_le_bytes(b)
  1050. }
  1051. impl Trace {
  1052. fn say(&mut self, text: String) {
  1053. self.said += 1;
  1054. if self.said < 6000 {
  1055. tracing::info!("bvh trace: {text}");
  1056. }
  1057. }
  1058. pub(super) fn look(&mut self, frame: u64) {
  1059. if !on() {
  1060. return;
  1061. }
  1062. let mut gone = Vec::new();
  1063. for i in 0..self.asked.len() {
  1064. let (then, at, structure, was) = self.asked[i];
  1065. let now = value(at);
  1066. if now != was {
  1067. self.sizes.insert(structure, (now, frame));
  1068. gone.push(i);
  1069. self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: {was:#x} -> {now:#x}"));
  1070. } else if frame > then + 60 {
  1071. gone.push(i);
  1072. self.say(format!("frame {frame}: size of {structure:#x} at {at:#x} asked in {then}: still {was:#x}"));
  1073. }
  1074. }
  1075. for i in gone.into_iter().rev() {
  1076. self.asked.swap_remove(i);
  1077. }
  1078. }
  1079. pub(super) fn dispatch(
  1080. &mut self,
  1081. frame: u64,
  1082. list: &HostList,
  1083. addresses: &[u64],
  1084. written: &[u64],
  1085. constants: &[u32],
  1086. threads: Option<[u32; 3]>,
  1087. ) {
  1088. if !on() {
  1089. return;
  1090. }
  1091. let _ = addresses;
  1092. let list = std::ptr::from_ref(list) as usize & 0xFFFF_FFFF;
  1093. if threads == Some([1, 1, 1])
  1094. && let [lo, hi, mode, ..] = *constants
  1095. && (1..=3).contains(&mode)
  1096. && hi < 0x20
  1097. && let Some(&at) = written.first()
  1098. && crate::shadow::in_buffer(at, 1).is_some_and(|b| b.1 <= BACK)
  1099. {
  1100. let structure = u64::from(lo) | u64::from(hi) << 32;
  1101. let was = value(at);
  1102. self.say(format!("frame {frame} list {list:x}: asks mode {mode} of {structure:#x} to {at:#x}, there {was:#x}"));
  1103. if mode == 1 {
  1104. self.asked.push((frame, at, structure, was));
  1105. }
  1106. } else if threads == Some([32, 1, 1])
  1107. && let [from, to] = *written
  1108. && [from, to].iter().all(|&a| a >= 1 << 32 && crate::shadow::in_buffer(a, 1).is_none())
  1109. {
  1110. let known = self.sizes.get(&from).copied();
  1111. self.say(format!("frame {frame} list {list:x}: copies {from:#x} to {to:#x} constants {:x?}, its size was {known:x?}", &constants[..constants.len().min(4)]));
  1112. }
  1113. }
  1114. }
  1115. }
  1116. /// `VICTORY_MEMORY_DUMP=<folder>`: when a file `go` appears there, the arenas
  1117. /// as the card holds them are copied out and written (`arena-<n>.bin`), with
  1118. /// `pages.txt` (title page, arena, offset) and the structures the walking
  1119. /// programs were given: to look at the structures offline.
  1120. #[cfg(feature = "diagnostics")]
  1121. mod dump {
  1122. use super::*;
  1123. #[derive(Default)]
  1124. pub(super) struct Dump {
  1125. walked: std::collections::BTreeSet<u64>,
  1126. /// Views the builder was given to write outside buffers: the first
  1127. /// and the last frame, how often.
  1128. pub(super) built: std::collections::BTreeMap<u64, (u64, u64, u64)>,
  1129. /// The frame it is written at, and the copies.
  1130. due: Option<(u64, Vec<(ID3D12Resource, usize)>)>,
  1131. done: bool,
  1132. }
  1133. impl Dump {
  1134. pub(super) fn walked(&mut self, addresses: &[u64]) {
  1135. if !self.done && self.walked.len() < 64 {
  1136. self.walked.extend(addresses);
  1137. }
  1138. }
  1139. }
  1140. fn folder() -> Option<&'static std::path::PathBuf> {
  1141. static FOLDER: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();
  1142. FOLDER.get_or_init(|| std::env::var_os("VICTORY_MEMORY_DUMP").map(Into::into)).as_ref()
  1143. }
  1144. fn turn(buffer: &ID3D12Resource, before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> D3D12_RESOURCE_BARRIER {
  1145. D3D12_RESOURCE_BARRIER {
  1146. Type: D3D12_RESOURCE_BARRIER_TYPE_TRANSITION,
  1147. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  1148. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  1149. Transition: std::mem::ManuallyDrop::new(D3D12_RESOURCE_TRANSITION_BARRIER {
  1150. // SAFETY: the same pointer, not counted; the barrier is
  1151. // used while the buffer lives.
  1152. pResource: unsafe { std::mem::transmute_copy(buffer) },
  1153. Subresource: D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
  1154. StateBefore: before,
  1155. StateAfter: after,
  1156. }),
  1157. },
  1158. }
  1159. }
  1160. impl Memory {
  1161. /// At a list's first use: the copies are recorded into it.
  1162. pub(super) fn dump(&mut self, list: &HostList, _: &[u64]) {
  1163. let Some(folder) = folder() else { return };
  1164. if let Some((due, _)) = &self.dump.due {
  1165. if self.frame < *due {
  1166. return;
  1167. }
  1168. let copies = self.dump.due.take().map(|d| d.1).unwrap_or_default();
  1169. let mut text = String::new();
  1170. for a in &self.dump.walked {
  1171. text += &format!("walked {a:#x}\n");
  1172. }
  1173. for (a, (first, last, n)) in &self.dump.built {
  1174. text += &format!("built {a:#x} {first} {last} {n}\n");
  1175. }
  1176. for (a, p) in &self.packed {
  1177. text += &format!("packed {a:#x} {} {}\n", p.len, p.frame);
  1178. }
  1179. text += &format!("frame {}\n", self.frame);
  1180. for (page, held) in &self.pages {
  1181. let arena = self.arenas.iter().position(|a| a.0 == held.copy).unwrap_or(usize::MAX);
  1182. let at = held.at - self.arenas[arena].1;
  1183. text += &format!("{:#x} {arena} {at:#x}\n", page * PAGE);
  1184. }
  1185. let _ = std::fs::write(folder.join("pages.txt"), text);
  1186. for (n, (_, data)) in copies.iter().enumerate() {
  1187. // SAFETY: a mapping of an arena's bytes; the copies ran
  1188. // frames ago.
  1189. let bytes = unsafe { std::slice::from_raw_parts(*data as *const u8, ARENA as usize) };
  1190. let _ = std::fs::write(folder.join(format!("arena-{n}.bin")), bytes);
  1191. }
  1192. tracing::info!(arenas = copies.len(), "title memory by address: the arenas are written out");
  1193. return;
  1194. }
  1195. if self.dump.done || !folder.join("go").exists() {
  1196. return;
  1197. }
  1198. self.dump.done = true;
  1199. let Some(host) = host() else { return };
  1200. let mut copies = Vec::new();
  1201. for &(n, _) in &self.arenas {
  1202. let buffer = &self.copies[n].buffer;
  1203. let Some((to, data)) = host.shared_buffer(ARENA) else { break };
  1204. // SAFETY: an open list; live buffers of those sizes. The list
  1205. // has not used the arena yet.
  1206. unsafe {
  1207. list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE)]);
  1208. list.list.CopyBufferRegion(&to, 0, buffer, 0, ARENA);
  1209. list.list.ResourceBarrier(&[turn(buffer, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON)]);
  1210. }
  1211. list.keep(&to);
  1212. copies.push((to, data as usize));
  1213. }
  1214. self.dump.due = Some((self.frame + 12, copies));
  1215. }
  1216. }
  1217. }
  1218. #[cfg(test)]
  1219. mod tests {
  1220. use super::*;
  1221. #[test]
  1222. fn a_piece_takes_what_changed() {
  1223. let mut title = [7u8; PIECE];
  1224. let mut ours = vec![0u8; PIECE];
  1225. assert_eq!(merge(&title, &mut ours, true), PIECE / 4);
  1226. assert_eq!(ours, title);
  1227. assert_eq!(merge(&title, &mut ours, false), 0);
  1228. // A dword of it.
  1229. title[41] = 8;
  1230. assert_eq!(merge(&title, &mut ours, false), 1);
  1231. assert_eq!(ours, title);
  1232. }
  1233. #[test]
  1234. fn a_packed_structure_is_known_by_its_header() {
  1235. let header = |version: u32, nodes: u32| u64::from(version) | u64::from(nodes) << 32;
  1236. assert_eq!(packed_len(header(0x8102_0006, 0x9a1a)), Some(0x9a1b * 64));
  1237. // Unpacked, a top level, another version, no size, too big.
  1238. assert_eq!(packed_len(header(0x8002_0006, 0x9a1a)), None);
  1239. assert_eq!(packed_len(header(0x0000_0006, 5)), None);
  1240. assert_eq!(packed_len(header(0x8102_0007, 5)), None);
  1241. assert_eq!(packed_len(header(0x8102_0006, 0)), None);
  1242. assert_eq!(packed_len(header(0x8102_0006, 1 << 21)), None);
  1243. }
  1244. }