shadow.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. //! Host copies of title buffers (decision 0007, step 3 and "Copies of title
  2. //! memory"). Title buffers are title memory, which the host GPU cannot
  3. //! read, so a buffer a draw uses gets a persistent host buffer of its size
  4. //! on first use (system memory shaders may also write), and the ranges each
  5. //! submission reads (vertex, index and constant data, buffer views) are
  6. //! brought up to date from title memory before it runs: the 64 KiB pages
  7. //! the title wrote since they were last copied ([`crate::watch`]: write
  8. //! watching, or read-only guards on physical-page views), all of it where
  9. //! neither works. A title GPU address inside the buffer is the same offset
  10. //! in its copy. Ranges shaders write go back to title memory after the
  11. //! submission ([`Shadow::gpu_writes`]).
  12. //!
  13. //! shortcut: only the ranges draws are known to read are brought up to
  14. //! date (vertex and index buffer views, constant buffers in tables, root
  15. //! descriptors, buffer views in tables); buffers read through directly
  16. //! indexed heaps keep what their first use copied.
  17. use std::collections::BTreeMap;
  18. use std::sync::atomic::{AtomicU8, Ordering};
  19. use std::sync::{Arc, Mutex};
  20. use windows::Win32::Graphics::Direct3D12::ID3D12Resource;
  21. use crate::host::{HostList, host};
  22. use crate::watch::PAGE;
  23. /// A title buffer's host copy.
  24. pub(crate) struct Shadow {
  25. pub(crate) buffer: ID3D12Resource,
  26. data: *mut u8,
  27. gpu: u64,
  28. /// Where the title buffer starts and how long it is.
  29. start: u64,
  30. len: u64,
  31. /// Per page of title memory from `start`'s on: the write-watch asking
  32. /// after which it was last copied (0: never).
  33. copied: Mutex<Vec<u64>>,
  34. /// Whether the memory is write-watched: unknown, yes, no.
  35. watched: AtomicU8,
  36. /// Ranges shaders of a submission not yet copied back may be writing:
  37. /// title memory there is older than the copy.
  38. pending: Mutex<Vec<(usize, usize)>>,
  39. /// The copy's bytes before the submission ran, from an offset on,
  40. /// covering the ranges its shaders write: what the GPU wrote differs.
  41. before: Mutex<Option<(usize, Vec<u8>)>>,
  42. }
  43. /// Snapshot memory kept for reuse (already touched, so no page faults).
  44. static POOL: Mutex<Vec<Vec<u8>>> = Mutex::new(Vec::new());
  45. /// An empty buffer with room for `n` bytes, from the pool if it has one.
  46. fn pooled(n: usize) -> Vec<u8> {
  47. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  48. let fit = pool
  49. .iter()
  50. .enumerate()
  51. .filter(|(_, v)| v.capacity() >= n)
  52. .min_by_key(|(_, v)| v.capacity())
  53. .map(|(i, _)| i);
  54. let mut v = match fit {
  55. Some(i) => pool.swap_remove(i),
  56. None => Vec::with_capacity(n),
  57. };
  58. v.clear();
  59. v
  60. }
  61. /// Returns a snapshot buffer to the pool (at most 8 kept, the largest).
  62. fn give_back(v: Vec<u8>) {
  63. let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner());
  64. pool.push(v);
  65. if pool.len() > 8 {
  66. pool.sort_by_key(|v| std::cmp::Reverse(v.capacity()));
  67. pool.truncate(8);
  68. }
  69. }
  70. const NOT_WATCHED: u8 = 2;
  71. // SAFETY: D3D12 resources are free-threaded; `data` is a persistent mapping
  72. // written only on the submitting thread.
  73. unsafe impl Send for Shadow {}
  74. // SAFETY: as above.
  75. unsafe impl Sync for Shadow {}
  76. impl Shadow {
  77. /// The host GPU address of a title address inside the buffer.
  78. pub(crate) fn gpu(&self, address: u64) -> u64 {
  79. self.gpu + (address - self.start)
  80. }
  81. /// Bytes from a title address to the buffer's end.
  82. pub(crate) fn left(&self, address: u64) -> u64 {
  83. (self.start + self.len).saturating_sub(address)
  84. }
  85. /// Offset of a title address from the buffer's start.
  86. pub(crate) fn offset(&self, address: u64) -> u64 {
  87. address - self.start
  88. }
  89. /// Brings `len` bytes at `address` up to date when `list` is submitted,
  90. /// and keeps the copy alive until the list is reset.
  91. pub(crate) fn refresh(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
  92. let len = len.min(self.start + self.len - address);
  93. list.defer_refresh(self, address as usize, len as usize);
  94. }
  95. fn new(buffer: ID3D12Resource, data: *mut u8, gpu: u64, start: u64, len: u64) -> Shadow {
  96. let pages = (start + len).div_ceil(PAGE as u64) - start / PAGE as u64;
  97. Shadow {
  98. buffer,
  99. data,
  100. gpu,
  101. start,
  102. len,
  103. copied: Mutex::new(vec![0; pages as usize]),
  104. watched: AtomicU8::new(0),
  105. pending: Mutex::default(),
  106. before: Mutex::default(),
  107. }
  108. }
  109. /// `[address, address + len)` cut to the buffer, as offsets in the copy.
  110. fn inside(&self, address: usize, len: usize) -> (usize, usize) {
  111. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  112. let from = address.clamp(start, end);
  113. (from - start, (address + len).clamp(from, end) - start)
  114. }
  115. /// Shaders of `list` may write `[address, address + len)` of the copy
  116. /// (unordered access): after the list's submission has run, the range
  117. /// is copied back into title memory, where the title reads it; until
  118. /// then no refresh copies title memory over it. Call after the
  119. /// [`Shadow::refresh`] that gives the shaders the title's data.
  120. ///
  121. /// shortcut: what shaders wrote is found by keeping the range's bytes
  122. /// before the submission (a copy per declared range and submission);
  123. /// a GPU-side dirty mask would save that if big ranges make it slow.
  124. pub(crate) fn gpu_writes(self: &Arc<Self>, list: &HostList, address: u64, len: u64) {
  125. let len = len.min(self.left(address));
  126. list.defer_gpu_write(self, address as usize, len as usize);
  127. }
  128. /// At submission, after the range's refresh: a submitted list's shaders
  129. /// write this range. Its bytes are kept to tell later what the GPU wrote:
  130. /// one snapshot per copy and submission, grown to cover every range the
  131. /// submission declares (the world declares overlapping views of its
  132. /// 174 MB heap dozens of times), in reused memory (fresh snapshots cost
  133. /// ~2.3 million page faults per world frame).
  134. pub(crate) fn writing(&self, address: usize, len: usize) {
  135. self.pending
  136. .lock()
  137. .unwrap_or_else(|e| e.into_inner())
  138. .push((address, address + len));
  139. let (from, to) = self.inside(address, len);
  140. // SAFETY: inside the mapping.
  141. let host = |a: usize, b: usize| unsafe { std::slice::from_raw_parts(self.data.add(a), b - a) };
  142. let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner());
  143. let (start, end) = match &*before {
  144. Some((at, bytes)) => ((*at).min(from), (at + bytes.len()).max(to)),
  145. None => (from, to),
  146. };
  147. if let Some((at, bytes)) = &*before
  148. && (*at, at + bytes.len()) == (start, end)
  149. {
  150. return;
  151. }
  152. // Parts newly covered from the copy, the rest as it was taken.
  153. let mut grown = pooled(end - start);
  154. match before.take() {
  155. Some((at, bytes)) => {
  156. grown.extend_from_slice(host(start, at));
  157. grown.extend_from_slice(&bytes);
  158. grown.extend_from_slice(host(at + bytes.len(), end));
  159. give_back(bytes);
  160. }
  161. None => grown.extend_from_slice(host(start, end)),
  162. }
  163. *before = Some((start, grown));
  164. }
  165. /// After the submission ran: copies the bytes its shaders wrote back
  166. /// into title memory (unmapped pages left alone), and only those: the
  167. /// title's threads write the same buffers while the GPU runs (its
  168. /// command memory shares the big GPU heap with what shaders write), and
  169. /// putting back the copy's older bytes there broke the title's own
  170. /// records (a fence list read as -1, title+0x4e9b54a). Returns the bytes
  171. /// written.
  172. pub(crate) fn copy_back(&self, address: usize, len: usize) -> usize {
  173. let mut snapshot = self.before.lock().unwrap_or_else(|e| e.into_inner());
  174. let mut written = 0;
  175. let (from, to) = self.inside(address, len);
  176. let start = self.start as usize;
  177. if let Some((taken, before)) = &*snapshot
  178. && *taken <= from
  179. && to <= taken + before.len()
  180. && from < to
  181. {
  182. let before = &before[from - taken..to - taken];
  183. // By 64 KiB piece: the copy compared with its bytes before the
  184. // submission, title memory read only where the GPU wrote.
  185. const PIECE: usize = 64 << 10;
  186. let mut title = vec![0u8; PIECE];
  187. let mut synced = Vec::new();
  188. let mut at = from;
  189. while at < to {
  190. let n = (PIECE - (start + at) % PIECE).min(to - at);
  191. // SAFETY: inside the mapping; only the submitting thread
  192. // writes it.
  193. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) };
  194. let old = &before[at - from..at - from + n];
  195. let title = &mut title[..n];
  196. if host != old && crate::host::read_into((start + at) as *const u8, title) {
  197. // Title memory with the GPU's bytes put in; the copy
  198. // takes the title's bytes in turn.
  199. let mut changed = false;
  200. for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) {
  201. if *h != *o && *t != *h {
  202. *t = *h;
  203. changed = true;
  204. }
  205. *h = *t;
  206. }
  207. if changed {
  208. crate::watch::writing(start + at, n);
  209. crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
  210. written += n;
  211. }
  212. synced.push((start + at) / PAGE);
  213. }
  214. at += n;
  215. }
  216. // Pages made equal to title memory are current in the copy, so
  217. // our own write is not taken for the title's; others keep what
  218. // they had (a title write there shows at the next refresh).
  219. let (first, last) = ((start + from).div_ceil(PAGE), (start + to) / PAGE);
  220. if first < last
  221. && !synced.is_empty()
  222. && self.watched.load(Ordering::Relaxed) != NOT_WATCHED
  223. && let Some((now, _)) = crate::watch::writes(first * PAGE, last * PAGE, true)
  224. {
  225. let base = start / PAGE;
  226. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  227. for page in synced.into_iter().filter(|p| (first..last).contains(p)) {
  228. copied[page - base] = now;
  229. }
  230. }
  231. }
  232. // Every submitted step that declared the range is done with it (one
  233. // submission runs at a time), and the snapshot with the last range.
  234. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  235. pending.retain(|&r| r != (address, address + len));
  236. if pending.is_empty()
  237. && let Some((_, bytes)) = snapshot.take()
  238. {
  239. give_back(bytes);
  240. }
  241. written
  242. }
  243. /// At submission: copies what changed of `[address, address + len)`
  244. /// since it was last copied (all of it if the memory is not
  245. /// write-watched). Returns the bytes copied.
  246. pub(crate) fn update(&self, address: usize, len: usize) -> usize {
  247. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  248. let (from, to) = (address.max(start), (address + len).min(end));
  249. if from >= to {
  250. return 0;
  251. }
  252. let mut busy: Vec<(usize, usize)> = self
  253. .pending
  254. .lock()
  255. .unwrap_or_else(|e| e.into_inner())
  256. .iter()
  257. .copied()
  258. .filter(|&(a, e)| a < to && e > from)
  259. .collect();
  260. if !busy.is_empty() {
  261. // Around ranges shaders are writing: the gaps, each as below
  262. // (in the world most submissions have such ranges; copying the
  263. // gaps whole cost ~1 s per frame).
  264. busy.sort_unstable();
  265. let (mut at, mut bytes) = (from, 0);
  266. for (a, e) in busy {
  267. if a > at {
  268. bytes += self.update_free(at, a);
  269. }
  270. at = at.max(e);
  271. }
  272. if at < to {
  273. bytes += self.update_free(at, to);
  274. }
  275. return bytes;
  276. }
  277. self.update_free(from, to)
  278. }
  279. /// [`Shadow::update`] of `[from, to)` (inside the buffer) where no
  280. /// shader writes.
  281. fn update_free(&self, from: usize, to: usize) -> usize {
  282. if self.watched.load(Ordering::Relaxed) != NOT_WATCHED {
  283. if let Some((now, written)) = crate::watch::writes(from, to, true) {
  284. self.watched.store(1, Ordering::Relaxed);
  285. let copied = self.copy_stale(from, to, now, &written);
  286. #[cfg(feature = "diagnostics")]
  287. {
  288. use crate::copystat::{C, add};
  289. add(C::Checked, (to - from) as u64);
  290. add(C::Unchanged, (to - from).saturating_sub(copied) as u64);
  291. }
  292. return copied;
  293. }
  294. self.watched.store(NOT_WATCHED, Ordering::Relaxed);
  295. }
  296. self.copy(from, to);
  297. to - from
  298. }
  299. /// Copies the pages of `[from, to)` written after their last copy
  300. /// (`written`: last writes by page, in page order; `now`: this
  301. /// asking), whole pages within the buffer.
  302. fn copy_stale(&self, from: usize, to: usize, now: u64, written: &[(usize, u64)]) -> usize {
  303. let base = self.start as usize / PAGE;
  304. let mut copied = self.copied.lock().unwrap_or_else(|e| e.into_inner());
  305. let mut writes = written.iter().peekable();
  306. let (mut bytes, mut run) = (0, None);
  307. let last = (to - 1) / PAGE;
  308. for page in from / PAGE..=last {
  309. let write = match writes.peek() {
  310. Some(&&(p, w)) if p == page => {
  311. writes.next();
  312. w
  313. }
  314. _ => 0,
  315. };
  316. let at = &mut copied[page - base];
  317. if *at == 0 || write > *at {
  318. // A page only partly in the range is copied in part: it
  319. // stays stale for the rest.
  320. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  321. if (page * PAGE).max(start) >= from && ((page + 1) * PAGE).min(end) <= to {
  322. *at = now;
  323. }
  324. run.get_or_insert(page);
  325. } else if let Some(first) = run.take() {
  326. bytes += self.copy((first * PAGE).max(from), (page * PAGE).min(to));
  327. }
  328. }
  329. // Cut to the range: next to it shaders may be writing the copy.
  330. if let Some(first) = run {
  331. bytes += self.copy((first * PAGE).max(from), ((last + 1) * PAGE).min(to));
  332. }
  333. bytes
  334. }
  335. /// Copies title memory `[from, to)`, cut to the buffer, into the copy.
  336. fn copy(&self, from: usize, to: usize) -> usize {
  337. let (start, end) = (self.start as usize, (self.start + self.len) as usize);
  338. let (from, to) = (from.max(start), to.min(end));
  339. // SAFETY: inside the mapping (`from` and `to` are within the buffer).
  340. let at = unsafe { self.data.add(from - start) };
  341. crate::host::copy_mapped(at, from as *const u8, to - from, false);
  342. to - from
  343. }
  344. }
  345. struct Entry {
  346. end: u64,
  347. shadow: Option<Arc<Shadow>>,
  348. }
  349. /// Title buffers by (start address, resource), with their copy once made.
  350. static BUFFERS: Mutex<BTreeMap<(u64, usize), Entry>> = Mutex::new(BTreeMap::new());
  351. fn buffers() -> std::sync::MutexGuard<'static, BTreeMap<(u64, usize), Entry>> {
  352. BUFFERS.lock().unwrap_or_else(|e| e.into_inner())
  353. }
  354. /// A title buffer exists at `start` (`len` bytes).
  355. pub(crate) fn register(resource: usize, start: u64, len: u64) {
  356. buffers().insert(
  357. (start, resource),
  358. Entry {
  359. end: start + len,
  360. shadow: None,
  361. },
  362. );
  363. }
  364. /// The title released it; lists that still hold its copy keep it alive.
  365. pub(crate) fn unregister(resource: usize, start: u64) {
  366. buffers().remove(&(start, resource));
  367. }
  368. /// The copy of the innermost title buffer holding `[address, address +
  369. /// len)`, made on first use.
  370. pub(crate) fn find(address: u64, len: u64) -> Option<Arc<Shadow>> {
  371. let end = address.checked_add(len.max(1))?;
  372. let mut map = buffers();
  373. let key = map
  374. .range(..=(address, usize::MAX))
  375. .rev()
  376. .take(64)
  377. .find(|(_, e)| e.end >= end)
  378. .map(|(k, _)| *k);
  379. let Some(key) = key else {
  380. drop(map);
  381. return loose(address, end);
  382. };
  383. let entry = map.get_mut(&key)?;
  384. if entry.shadow.is_none() {
  385. let len = entry.end - key.0;
  386. // Rounded up so that views ending in the buffer's last 256 bytes fit.
  387. // Shaders write some buffers (unordered access), so not upload memory.
  388. let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(1 << 16))?;
  389. crate::host::name(&buffer, || format!("title buffer {:#x}+{len:#x}", key.0));
  390. // SAFETY: a live buffer.
  391. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  392. if len >= 16 << 20 {
  393. tracing::info!(
  394. start = format_args!("{:#x}", key.0),
  395. len,
  396. "large buffer copied to the host"
  397. );
  398. } else {
  399. tracing::debug!(
  400. start = format_args!("{:#x}", key.0),
  401. len,
  402. "buffer copied to the host"
  403. );
  404. }
  405. entry.shadow = Some(Arc::new(Shadow::new(buffer, data, gpu, key.0, len)));
  406. }
  407. entry.shadow.clone()
  408. }
  409. /// Titles also use memory outside any buffer object as GPU memory (Grand
  410. /// Theft Auto VI's interface vertices, from its own allocator). Such memory
  411. /// gets copies of the aligned windows it touches.
  412. /// shortcut: copies of windows are never freed; key them to the title's
  413. /// allocations if memory use grows.
  414. const WINDOW: u64 = 4 << 20;
  415. /// Copies of title memory outside buffers, by (start, length).
  416. static LOOSE: Mutex<BTreeMap<(u64, u64), Arc<Shadow>>> = Mutex::new(BTreeMap::new());
  417. fn loose(address: u64, end: u64) -> Option<Arc<Shadow>> {
  418. let start = address & !(WINDOW - 1);
  419. let len = end.next_multiple_of(WINDOW) - start;
  420. let mut map = LOOSE.lock().unwrap_or_else(|e| e.into_inner());
  421. if let Some(shadow) = map.get(&(start, len)) {
  422. return Some(shadow.clone());
  423. }
  424. let (buffer, data) = host()?.shared_buffer(len)?;
  425. crate::host::name(&buffer, || format!("title memory {start:#x}+{len:#x}"));
  426. // SAFETY: a live buffer.
  427. let gpu = unsafe { buffer.GetGPUVirtualAddress() };
  428. tracing::debug!(
  429. start = format_args!("{start:#x}"),
  430. len,
  431. "loose memory copied to the host"
  432. );
  433. let shadow = Arc::new(Shadow::new(buffer, data, gpu, start, len));
  434. map.insert((start, len), shadow.clone());
  435. Some(shadow)
  436. }
  437. /// For device-removed reports: the copy of title memory whose host range
  438. /// starts closest below host GPU address `va`, and where `va` is in it.
  439. pub(crate) fn near(va: u64) -> String {
  440. let mut all: Vec<(u64, u64, u64)> = buffers()
  441. .values()
  442. .filter_map(|e| e.shadow.as_deref().map(|s| (s.gpu, s.start, s.len)))
  443. .collect();
  444. all.extend(
  445. LOOSE
  446. .lock()
  447. .unwrap_or_else(|e| e.into_inner())
  448. .values()
  449. .map(|s| (s.gpu, s.start, s.len)),
  450. );
  451. let below = all.iter().filter(|c| c.0 <= va).max();
  452. let above = all.iter().filter(|c| c.0 > va).min();
  453. let mut text = match below {
  454. Some(&(gpu, start, len)) => format!(
  455. "; the nearest title memory copy below it: {start:#x}+{len:#x} at host {gpu:#x}, offset {:#x}",
  456. va - gpu
  457. ),
  458. None => "; no title memory copy below it".into(),
  459. };
  460. if let Some(&(gpu, start, len)) = above {
  461. text.push_str(&format!(
  462. "; the nearest above: {start:#x}+{len:#x} at host {gpu:#x} ({} copies in all)",
  463. all.len()
  464. ));
  465. }
  466. text
  467. }