memory.rs 13 KB

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