memory.rs 41 KB

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