merge.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. //! What the CPU wrote, put in without what the card wrote.
  2. //!
  3. //! The host layer brings results of shaders back to title memory, and sends
  4. //! pieces of title memory up again (64 KiB at a time) when the title changed
  5. //! some of them. What goes up therefore holds results of the recorded frame.
  6. //! Shaders that give out places with atomics give other places in every run:
  7. //! the recorded results put over a replay's own leave lists and what points
  8. //! into them of two different frames. So where a copy brings memory of the
  9. //! CPU to a buffer the card writes, words the card has written since the
  10. //! start of the frame (which are not what was last put there) stay.
  11. use windows::Win32::Graphics::Direct3D::Fxc::D3DCompile;
  12. use windows::Win32::Graphics::Direct3D::ID3DBlob;
  13. use super::*;
  14. const SOURCE: &str = r#"
  15. #define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0), UAV(u1), UAV(u2)"
  16. cbuffer C : register(b0) { uint words; uint call; };
  17. ByteAddressBuffer from : register(t0);
  18. RWByteAddressBuffer to : register(u0);
  19. RWByteAddressBuffer base : register(u1);
  20. // For each call: words put, words of the card's left that were to get
  21. // another value, and of those the ones that were to get back what stood
  22. // there before the card wrote.
  23. RWByteAddressBuffer counts : register(u2);
  24. [RootSignature(RS)]
  25. [numthreads(64, 1, 1)]
  26. void main(uint3 id : SV_DispatchThreadID) {
  27. if (id.x >= words) return;
  28. uint at = id.x * 4;
  29. uint v = from.Load(at), now = to.Load(at), was = base.Load(at), n;
  30. if (now != was) {
  31. if (v == now) return;
  32. counts.InterlockedAdd(call * 12 + 4, 1, n);
  33. if (v == was) counts.InterlockedAdd(call * 12 + 8, 1, n);
  34. return;
  35. }
  36. if (v == now) return;
  37. counts.InterlockedAdd(call * 12, 1, n);
  38. to.Store(at, v);
  39. base.Store(at, v);
  40. }
  41. "#;
  42. pub(super) struct Merger {
  43. root: ID3D12RootSignature,
  44. pso: ID3D12PipelineState,
  45. /// For each buffer: what was last put there (at first, what it held at
  46. /// the frame's start).
  47. pub(super) bases: HashMap<u32, ID3D12Resource>,
  48. pub(super) counts: ID3D12Resource,
  49. /// The merges recorded: buffer, offset, length (in `CALLS` at the most).
  50. pub(super) calls: std::cell::RefCell<Vec<(u32, u64, u64)>>,
  51. }
  52. const CALLS: u64 = 1 << 16;
  53. impl Player {
  54. /// The copy of a piece of a card buffer's CPU side to it: its source's
  55. /// address, then the buffer, offset, 0 and length.
  56. pub(super) fn merged_copy(&self, c: &Cmd) -> Option<(u64, (u32, u64, u64, u64))> {
  57. let Cmd::CopyBuffer {
  58. dst,
  59. dst_at,
  60. src,
  61. src_at,
  62. len,
  63. } = c
  64. else {
  65. return None;
  66. };
  67. if !self.merging
  68. || !self.pairs(*src, *dst)
  69. || dst_at != src_at
  70. || dst_at % 4 != 0
  71. || len % 4 != 0
  72. {
  73. return None;
  74. }
  75. self.merger.as_ref()?.bases.get(dst)?;
  76. let from = self.objects.get(src)?.va + src_at;
  77. Some((from, (*dst, *dst_at, 0, *len)))
  78. }
  79. /// Whether `src` is the CPU's side of card buffer `dst`.
  80. fn pairs(&self, src: u32, dst: u32) -> bool {
  81. let (Some(a), Some(b)) = (self.objects.get(&src), self.objects.get(&dst)) else {
  82. return false;
  83. };
  84. let (a, b) = (
  85. &self.frame.resources[a.index],
  86. &self.frame.resources[b.index],
  87. );
  88. let cpu =
  89. matches!(&a.place, Place::Committed { props, .. } if gpu::seen(props) == Seen::Cached);
  90. cpu && b.name.ends_with("on the card")
  91. && a.desc.width == b.desc.width
  92. && self.card_writes.contains(&dst)
  93. }
  94. /// Records merges: (buffer, offset in it, offset from `from`, length).
  95. ///
  96. /// # Safety
  97. /// An open list; `from` is the address of memory that holds the bytes.
  98. pub(super) unsafe fn merge_all(
  99. &self,
  100. list: &ID3D12GraphicsCommandList,
  101. from: u64,
  102. all: &[(u32, u64, u64, u64)],
  103. ) {
  104. let Some(m) = &self.merger else { return };
  105. // SAFETY: the caller's; live buffers.
  106. unsafe {
  107. list.SetComputeRootSignature(&m.root);
  108. list.SetPipelineState(&m.pso);
  109. for (id, at, source, len) in all {
  110. let (Some(o), Some(base)) = (self.objects.get(id), m.bases.get(id)) else {
  111. continue;
  112. };
  113. let base = base.GetGPUVirtualAddress();
  114. // At most 65,535 groups in a dispatch.
  115. const MOST: u64 = 8 << 20;
  116. let mut done = 0;
  117. while done < *len {
  118. let n = MOST.min(len - done);
  119. let words = (n / 4) as u32;
  120. let mut calls = m.calls.borrow_mut();
  121. let call = (calls.len() as u64).min(CALLS - 1) as u32;
  122. if calls.len() < CALLS as usize {
  123. calls.push((*id, at + done, n));
  124. }
  125. drop(calls);
  126. list.SetComputeRoot32BitConstants(0, 2, [words, call].as_ptr().cast(), 0);
  127. list.SetComputeRootUnorderedAccessView(4, m.counts.GetGPUVirtualAddress());
  128. list.SetComputeRootShaderResourceView(1, from + source + done);
  129. list.SetComputeRootUnorderedAccessView(2, o.va + at + done);
  130. list.SetComputeRootUnorderedAccessView(3, base + at + done);
  131. list.Dispatch(words.div_ceil(64), 1, 1);
  132. done += n;
  133. }
  134. }
  135. }
  136. }
  137. /// Switches merging on or off; makes what it needs at first.
  138. pub(super) fn set_merging(&mut self, on: bool) -> Result<()> {
  139. self.merging = on;
  140. if let Some(m) = &self.merger {
  141. m.calls.borrow_mut().clear();
  142. }
  143. if !on || self.merger.is_some() {
  144. return Ok(());
  145. }
  146. let mut code: Option<ID3DBlob> = None;
  147. // SAFETY: the source and names live through the call; the blob's own
  148. // bytes.
  149. let (root, pso) = unsafe {
  150. D3DCompile(
  151. SOURCE.as_ptr().cast(),
  152. SOURCE.len(),
  153. None,
  154. None,
  155. None,
  156. windows::core::s!("main"),
  157. windows::core::s!("cs_5_1"),
  158. 0,
  159. 0,
  160. &mut code,
  161. None,
  162. )?;
  163. let code = code.context("no merge shader")?;
  164. let bytes = std::slice::from_raw_parts(
  165. code.GetBufferPointer().cast::<u8>(),
  166. code.GetBufferSize(),
  167. );
  168. let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?;
  169. let pso =
  170. self.device
  171. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  172. pRootSignature: std::mem::transmute_copy(&root),
  173. CS: D3D12_SHADER_BYTECODE {
  174. pShaderBytecode: bytes.as_ptr().cast(),
  175. BytecodeLength: bytes.len(),
  176. },
  177. ..Default::default()
  178. })?;
  179. (root, pso)
  180. };
  181. let mut ids: HashSet<u32> = HashSet::new();
  182. for c in self.commands.iter().flatten() {
  183. if let Cmd::CopyBuffer { dst, src, .. } = c
  184. && self.pairs(*src, *dst)
  185. {
  186. ids.insert(*dst);
  187. }
  188. }
  189. ids.extend(
  190. self.delta_parts
  191. .iter()
  192. .flatten()
  193. .map(|(d, _)| d.res)
  194. .filter(|id| self.card_writes.contains(id)),
  195. );
  196. let mut bases = HashMap::new();
  197. let mut total = 0;
  198. for id in ids {
  199. if !self.masters.iter().any(|m| m.0 == id) {
  200. continue;
  201. }
  202. let size = self.frame.resources[self.objects[&id].index].desc.width;
  203. let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  204. bases.insert(
  205. id,
  206. gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, size, flags)?.0,
  207. );
  208. total += size;
  209. }
  210. let masters: HashMap<u32, ID3D12Resource> = self.masters.iter().cloned().collect();
  211. self.worker.run(|list| {
  212. for (id, base) in &bases {
  213. // SAFETY: an open list; live buffers of one size.
  214. unsafe { list.CopyResource(base, &masters[id]) };
  215. }
  216. })?;
  217. tracing::info!(
  218. buffers = bases.len(),
  219. mb = total >> 20,
  220. "bases of merged copies"
  221. );
  222. let flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
  223. let counts = gpu::buffer(&self.device, D3D12_HEAP_TYPE_DEFAULT, CALLS * 12, flags)?.0;
  224. self.merger = Some(Merger {
  225. root,
  226. pso,
  227. bases,
  228. counts,
  229. calls: Default::default(),
  230. });
  231. Ok(())
  232. }
  233. /// What the merges of the last run (of `loops`, which add up) found.
  234. pub(super) fn merge_notes(&mut self, loops: u32) -> Result<Vec<String>> {
  235. let Some(m) = &self.merger else {
  236. return Ok(Vec::new());
  237. };
  238. let (counts, calls) = (m.counts.clone(), m.calls.borrow().clone());
  239. let (back, data) = gpu::buffer(
  240. &self.device,
  241. D3D12_HEAP_TYPE_READBACK,
  242. CALLS * 12,
  243. D3D12_RESOURCE_FLAG_NONE,
  244. )?;
  245. self.worker.run(|list| {
  246. // SAFETY: an open list; live buffers.
  247. unsafe { list.CopyBufferRegion(&back, 0, &counts, 0, CALLS * 12) };
  248. })?;
  249. // SAFETY: the mapping; the copy into it has run.
  250. let all = unsafe { std::slice::from_raw_parts(data.cast::<u32>(), CALLS as usize * 3) };
  251. let each = |k: usize| {
  252. all.iter()
  253. .skip(k)
  254. .step_by(3)
  255. .map(|&n| u64::from(n))
  256. .sum::<u64>()
  257. / u64::from(loops.max(1))
  258. };
  259. let mut out = vec![format!(
  260. "{} copies of what the CPU wrote to memory the card writes: {} words put; {} left as the card wrote them in this run, where other values were to go ({} of them the values from before the card wrote)",
  261. calls.len(),
  262. each(0),
  263. each(1),
  264. each(2)
  265. )];
  266. let mut worst: Vec<(u32, usize)> = (0..calls.len())
  267. .map(|i| (all[i * 3 + 2], i))
  268. .filter(|w| w.0 > 0)
  269. .collect();
  270. worst.sort_by(|a, b| b.0.cmp(&a.0));
  271. for (n, i) in worst.into_iter().take(8) {
  272. let (id, at, len) = calls[i];
  273. out.push(format!(
  274. " values from before the card wrote: {} words, {} +{at:#x} {len:#x} bytes",
  275. n / loops.max(1),
  276. self.called(id)
  277. ));
  278. }
  279. Ok(out)
  280. }
  281. }