memory.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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. //! The copies are the ones every other access uses ([`crate::shadow`]: a
  8. //! title buffer's copy, or the 4 MiB window of memory outside buffers), so
  9. //! a root view and a raw address reach the same host bytes. This module
  10. //! keeps what a shader needs to find them:
  11. //!
  12. //! - the **directory**: per 64 KiB page of title address space the number
  13. //! of the copy that holds the page (0: none) and the page's byte offset
  14. //! in it; one buffer for all lists, entries only ever go from empty to
  15. //! filled;
  16. //! - per view heap a run of slots with a raw unordered access view of each
  17. //! numbered copy (slot 0 of the run: a null view, for pages without a
  18. //! copy);
  19. //! - the **faults**: the page numbers shaders found empty, read back here
  20. //! once a frame, so the copies exist from the next frame on. A pointer a
  21. //! shader takes out of memory cannot be known before it runs; the
  22. //! addresses a dispatch is given as root views are made ready before it.
  23. //!
  24. //! **A page that is not there when a shader touches it is a lost access**:
  25. //! the read gives 0, the store is dropped, and the fault note only helps
  26. //! the next frame. For the structure builder that is the same as a dropped
  27. //! stage, so before a dispatch the host makes ready everything it can see
  28. //! the dispatch name: the whole copy around each root view, around each
  29. //! pair of root constants that is a title address and around each root
  30. //! constant that is one in 256-byte units (the builder passes structures
  31. //! all three ways), and the 4 MiB after each (a structure may cross a
  32. //! window's end).
  33. //! shortcut: what a stage reaches only through pointers it reads out of
  34. //! memory (InitHeaders' table of structure addresses, LoadInstances'
  35. //! instance records) is not made ready unless something else named it;
  36. //! the fault count in the log says whether that happens. The whole answer
  37. //! is the extent of the title's allocation around an address, which the
  38. //! memory module of the layer knows and this one does not ask yet.
  39. //!
  40. //! shortcut: a copy that is numbered is kept for the rest of the run, and
  41. //! there are at most [`COPIES`] of them (4 MiB windows mostly: 4 GiB at
  42. //! most). Every list with such a shader brings all numbered copies up to
  43. //! date. A dispatch that can store through raw addresses declares the
  44. //! copies it names as written (the bytes are compared afterwards, as for
  45. //! any unordered access view); what a stage stores through pointers it
  46. //! reads out of memory is declared if a stage of the same list names the
  47. //! copy, and otherwise stays in the host's copy until one does. A
  48. //! dirty-page mask written by the shader would bound both.
  49. use std::collections::HashMap;
  50. use std::sync::{Arc, Mutex};
  51. use victory_shader::emit::{MEMORY_FAULTS, MEMORY_PAGES};
  52. use windows::Win32::Graphics::Direct3D12::*;
  53. use crate::descriptor::host::HostHeap;
  54. use crate::host::{HostList, host};
  55. use crate::shadow::Shadow;
  56. /// Copies that can be numbered (the run of heap slots is one longer). A
  57. /// listed frame of the opening cutscene names about 50 windows.
  58. const COPIES: u32 = 1023;
  59. /// A window of memory outside buffers (`shadow.rs`).
  60. const CELL: u64 = 4 << 20;
  61. /// A directory page.
  62. const PAGE: u64 = 1 << 16;
  63. struct Memory {
  64. /// Buffer, its mapping, its GPU address.
  65. directory: (ID3D12Resource, *mut u32, u64),
  66. faults: (ID3D12Resource, *mut u32, u64),
  67. /// Copy `n` is `copies[n - 1]`.
  68. copies: Vec<Arc<Shadow>>,
  69. /// Per host view heap (by address): the first slot of its run, and how
  70. /// many copies have their view there.
  71. heaps: HashMap<usize, (u32, u32)>,
  72. /// The frame the faults were last read in.
  73. frame: u64,
  74. /// Pages asked for this frame that are not the title's memory.
  75. refused: std::collections::HashSet<u64>,
  76. }
  77. // SAFETY: the mappings are of buffers the struct owns; all access is under
  78. // the mutex.
  79. unsafe impl Send for Memory {}
  80. static MEMORY: Mutex<Option<Memory>> = Mutex::new(None);
  81. /// What a draw binds.
  82. pub(crate) struct Ready {
  83. pub(crate) directory: u64,
  84. pub(crate) faults: u64,
  85. /// The view heap slot of the null view; copy `n`'s view is `n` further.
  86. pub(crate) base: u32,
  87. }
  88. impl Memory {
  89. fn new() -> Option<Memory> {
  90. let host = host()?;
  91. let make = |dwords: u64, what: &str| {
  92. let (buffer, data) = host.shared_buffer(dwords * 4)?;
  93. crate::host::name(&buffer, || format!("title memory by address: {what}"));
  94. // SAFETY: a fresh mapping of at least that many bytes.
  95. unsafe { std::ptr::write_bytes(data, 0, (dwords * 4) as usize) };
  96. // SAFETY: a live buffer.
  97. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  98. Some((buffer, data.cast::<u32>(), gpu))
  99. };
  100. tracing::info!("title memory by address: a shader reads or writes through raw addresses");
  101. Some(Memory {
  102. directory: make(u64::from(MEMORY_PAGES) * 2, "directory")?,
  103. faults: make(u64::from(MEMORY_FAULTS), "faults")?,
  104. copies: Vec::new(),
  105. heaps: HashMap::new(),
  106. frame: u64::MAX,
  107. refused: Default::default(),
  108. })
  109. }
  110. /// Gives the page of `address` its copy, if it has none and the memory
  111. /// is the title's; the place of its copy in `copies`.
  112. fn map(&mut self, address: u64) -> Option<usize> {
  113. self.make(address);
  114. let page = address / PAGE;
  115. if page >= u64::from(MEMORY_PAGES) - 1 {
  116. return None;
  117. }
  118. // SAFETY: inside the directory's mapping.
  119. let number = unsafe { self.directory.1.add(page as usize * 2).read() };
  120. (number as usize).checked_sub(1)
  121. }
  122. fn make(&mut self, address: u64) {
  123. let page = address / PAGE;
  124. // The last entry stays empty: addresses past the directory read it.
  125. if page >= u64::from(MEMORY_PAGES) - 1 {
  126. return;
  127. }
  128. // SAFETY: inside the directory's mapping.
  129. let entry = unsafe { self.directory.1.add(page as usize * 2) };
  130. // SAFETY: as above.
  131. if unsafe { entry.read() } != 0 {
  132. return;
  133. }
  134. let start = page * PAGE;
  135. // A shader's pointer, or a constant taken for an address, may be
  136. // anything: only memory the title has.
  137. if self.refused.contains(&page) {
  138. return;
  139. }
  140. if !crate::texture::committed(start as *const u8, PAGE as usize) {
  141. self.refused.insert(page);
  142. return;
  143. }
  144. // The copy a root view at that address would get; a buffer that
  145. // ends inside the page is passed over for what holds all of it.
  146. let whole = |s: &Arc<Shadow>| s.offset_in(start).is_some_and(|_| s.left(start) >= PAGE);
  147. let Some(shadow) = crate::shadow::find(start, 1)
  148. .filter(whole)
  149. .or_else(|| crate::shadow::find(start, PAGE).filter(whole))
  150. else {
  151. return;
  152. };
  153. // SAFETY: a live buffer.
  154. let flags = unsafe { shadow.buffer.GetDesc() }.Flags;
  155. if flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 == 0 {
  156. return;
  157. }
  158. let n = match self.copies.iter().position(|c| Arc::ptr_eq(c, &shadow)) {
  159. Some(n) => n,
  160. None if self.copies.len() < COPIES as usize => {
  161. self.copies.push(shadow.clone());
  162. let n = self.copies.len() - 1;
  163. // Every page the copy holds whole, not only the one asked
  164. // for: a structure is more than 64 KiB.
  165. // shortcut: a page of a title buffer inside this one that
  166. // has a copy of its own is given this copy too.
  167. let (first, len) = shadow.span();
  168. let mut at = first.next_multiple_of(PAGE);
  169. while at + PAGE <= first + len && at / PAGE < u64::from(MEMORY_PAGES) - 1 {
  170. // SAFETY: inside the directory's mapping.
  171. let other = unsafe { self.directory.1.add((at / PAGE) as usize * 2) };
  172. // SAFETY: as above; the offset first, as below.
  173. unsafe {
  174. if other.read() == 0 {
  175. other.add(1).write_volatile((at - first) as u32);
  176. other.write_volatile(n as u32 + 1);
  177. }
  178. }
  179. at += PAGE;
  180. }
  181. n
  182. }
  183. None => {
  184. static ONCE: std::sync::Once = std::sync::Once::new();
  185. ONCE.call_once(|| {
  186. tracing::warn!(COPIES, "title memory by address: no number left for another copy; its pages read zeros")
  187. });
  188. return;
  189. }
  190. };
  191. let offset = shadow.offset_in(start).unwrap_or(0);
  192. // The offset first: a shader that sees the number sees it too.
  193. // SAFETY: inside the directory's mapping.
  194. unsafe {
  195. entry.add(1).write_volatile(offset as u32);
  196. entry.write_volatile(n as u32 + 1);
  197. }
  198. }
  199. /// The pages shaders found empty since the last frame.
  200. fn take_faults(&mut self) {
  201. let mut pages = Vec::new();
  202. for i in 1..MEMORY_FAULTS as usize {
  203. // SAFETY: inside the faults' mapping; the GPU may be writing,
  204. // a number missed now is written again next frame.
  205. let at = unsafe { self.faults.1.add(i) };
  206. // SAFETY: as above.
  207. let page = unsafe { at.read_volatile() };
  208. if page != 0 {
  209. pages.push(page);
  210. // SAFETY: as above.
  211. unsafe { at.write_volatile(0) };
  212. }
  213. }
  214. if !pages.is_empty() {
  215. // Each is an access that read 0 or was dropped.
  216. static SAID: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
  217. if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 50 {
  218. tracing::warn!(
  219. pages = pages.len(),
  220. first = format_args!("{:#x}", u64::from(pages[0]) * PAGE),
  221. "title memory by address: shaders touched pages that had no copy (those accesses read 0 or were dropped); the copies are made now"
  222. );
  223. }
  224. }
  225. for page in pages {
  226. self.map(u64::from(page) * PAGE);
  227. }
  228. }
  229. /// What a dispatch names: the copy around `address` and the 4 MiB
  230. /// after it; their places in `copies`.
  231. fn name(&mut self, address: u64, named: &mut Vec<usize>) {
  232. for at in [address, (address & !(CELL - 1)) + CELL] {
  233. if let Some(n) = self.map(at)
  234. && !named.contains(&n)
  235. {
  236. named.push(n);
  237. }
  238. }
  239. }
  240. }
  241. /// Before a draw whose shader reads title memory by address: what its
  242. /// root arguments name gets its copies (`addresses`: its root views;
  243. /// `constants`: its root constants, see the module), every numbered copy
  244. /// has its view in `heap`'s run and is brought up to date when `list` is
  245. /// submitted (and, with `writes`, the named ones copied back after). None if the host
  246. /// cannot hold it; the draw is then dropped.
  247. pub(crate) fn ready(
  248. list: &HostList,
  249. heap: &HostHeap,
  250. addresses: &[u64],
  251. constants: &[u32],
  252. writes: bool,
  253. ) -> Option<Ready> {
  254. let mut guard = MEMORY.lock().unwrap_or_else(|e| e.into_inner());
  255. if guard.is_none() {
  256. *guard = Memory::new();
  257. }
  258. let m = guard.as_mut()?;
  259. let frame = crate::frame::current();
  260. if m.frame != frame {
  261. m.frame = frame;
  262. m.refused.clear();
  263. m.take_faults();
  264. }
  265. let numbered = m.copies.len();
  266. let mut named = Vec::new();
  267. for &address in addresses {
  268. m.name(address, &mut named);
  269. }
  270. // A title address in two constants (low dword, then bits 32 to 39), or
  271. // in one in 256-byte units. A constant that only looks like one names
  272. // memory nothing reads; one that is not the title's memory is refused.
  273. for (i, &c) in constants.iter().enumerate() {
  274. if let Some(&high) = constants.get(i + 1)
  275. && (1..=0xFF).contains(&high)
  276. && c >= 0x1_0000
  277. {
  278. m.name(u64::from(c) | u64::from(high) << 32, &mut named);
  279. }
  280. if c >= 0x0100_0000 {
  281. m.name(u64::from(c) << 8, &mut named);
  282. }
  283. }
  284. let key = std::ptr::from_ref(heap) as usize;
  285. let (base, made) = match m.heaps.get(&key) {
  286. Some(&run) => run,
  287. None => {
  288. // Held for the heap's life: not given back with a list's slots.
  289. let base = heap.dynamic(COPIES + 1)?;
  290. heap.null_raw_uav_at(base);
  291. (base, 0)
  292. }
  293. };
  294. for (n, shadow) in m.copies.iter().enumerate().skip(made as usize) {
  295. let (_, len) = shadow.span();
  296. heap.raw_uav_at(base + 1 + n as u32, &shadow.buffer, 0, len);
  297. }
  298. m.heaps.insert(key, (base, m.copies.len() as u32));
  299. // Once per list, and for copies numbered since: the builder alone
  300. // dispatches hundreds of times a frame.
  301. // shortcut: a copy another list numbers meanwhile is brought up to date
  302. // by that list's submission, which may run after this one's.
  303. const READ: usize = usize::MAX - 0x6d;
  304. const WRITE: usize = usize::MAX - 0x1_0000;
  305. let first_read = list.first_use(READ);
  306. for (n, shadow) in m.copies.iter().enumerate() {
  307. let (start, len) = shadow.span();
  308. if first_read || n >= numbered {
  309. shadow.refresh(list, start, len);
  310. }
  311. if writes && named.contains(&n) && list.first_use(WRITE - n) {
  312. #[cfg(feature = "diagnostics")]
  313. crate::host::wide_write(start, len, 1);
  314. shadow.gpu_writes(list, start, len);
  315. }
  316. }
  317. if first_read {
  318. list.keep(&m.directory.0);
  319. list.keep(&m.faults.0);
  320. }
  321. Some(Ready {
  322. directory: m.directory.2,
  323. faults: m.faults.2,
  324. base,
  325. })
  326. }