send.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. //! What goes up to copies in the card's memory goes up as it was when its
  2. //! submission was prepared (`VICTORY_SEND_OWN`, on by default; `0`: as
  3. //! before).
  4. //!
  5. //! The sends were copies out of the copies' CPU sides, which the card makes
  6. //! when it comes to the submission. By then later submissions are prepared
  7. //! (two frames of them with `VICTORY_RELAY`), and their refreshes have
  8. //! written the same CPU sides: the earlier submission's shaders then read a
  9. //! later one's bytes. For what the title's CPU writes that is as on the
  10. //! console (it does not write what the card still reads). But the title's
  11. //! own buffer copies are commands in its lists, and those are done by us
  12. //! when a submission is prepared: "a value to a buffer, a draw that reads
  13. //! it" in one submission and the same with another value in the next is
  14. //! ordinary, and both draws read the second value.
  15. //!
  16. //! So each submission's bytes are taken out of the CPU sides into memory of
  17. //! the submission's own when they are taken from the dirty lists, and the
  18. //! card copies them from there. Runs of a few words, which a refresh that
  19. //! sends only what changed makes many of, go as pairs of offset and value,
  20. //! stored by one dispatch per copy; the others as a copy each.
  21. use super::*;
  22. use crate::shadow::Shadow;
  23. pub(super) fn own() -> bool {
  24. static ON: OnceLock<bool> = OnceLock::new();
  25. *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_OWN").is_none_or(|v| v != "0"))
  26. }
  27. /// Runs up to this many bytes go as pairs.
  28. const SHORT: usize = 256;
  29. /// Whether a run of `len` bytes at offset `at` of a copy goes as pairs.
  30. fn short(at: usize, len: usize) -> bool {
  31. len <= SHORT && at % 4 == 0 && len % 4 == 0
  32. }
  33. /// Whether a run of `len` bytes at offset `at` of a copy in the card's memory
  34. /// is no copy command of its own, but pairs of one dispatch.
  35. pub(crate) fn goes_as_words(at: usize, len: usize) -> bool {
  36. own() && short(at, len)
  37. }
  38. /// Whether the title's bytes that go in under flights' writes
  39. /// (`Shadow::merge_under_writes`) go in by whole words
  40. /// (`VICTORY_UNDER_WORDS=0`: by the bytes that changed, as before).
  41. ///
  42. /// By bytes nearly every run (a float's three low bytes) was a copy command
  43. /// of its own, and a submission with more than 4,096 of them stood until the
  44. /// flights had landed: 4 to 14 ms of a steady frame (session play-1125-0203:
  45. /// "more changed runs than a submission sends up"), for some 20 KB. Whole
  46. /// words are pairs of one dispatch, and are not counted.
  47. ///
  48. /// A word is taken to be the title's or the shaders', not shared: where the
  49. /// title changed a byte of a word of which a flight's shader writes another
  50. /// byte, that byte is as it was before the flight. The landing rests on the
  51. /// same ([`crate::shadow::exact_back`]).
  52. pub(crate) fn words_under() -> bool {
  53. static ON: OnceLock<bool> = OnceLock::new();
  54. *ON.get_or_init(|| own() && std::env::var_os("VICTORY_UNDER_WORDS").is_none_or(|v| v != "0"))
  55. }
  56. const SCATTER: &str = r#"
  57. #define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)"
  58. cbuffer Part : register(b0) { uint at; uint count; };
  59. ByteAddressBuffer pairs : register(t0);
  60. RWByteAddressBuffer card : register(u0);
  61. [RootSignature(RS)]
  62. [numthreads(64, 1, 1)]
  63. void main(uint3 id : SV_DispatchThreadID) {
  64. if (id.x >= count) return;
  65. uint2 p = pairs.Load2(at + id.x * 8u);
  66. card.Store(p.x, p.y);
  67. }
  68. "#;
  69. struct Pass {
  70. root: ID3D12RootSignature,
  71. pso: ID3D12PipelineState,
  72. }
  73. fn pass(host: &Host) -> Option<&'static Pass> {
  74. static PASS: OnceLock<Option<Pass>> = OnceLock::new();
  75. PASS.get_or_init(|| {
  76. let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
  77. // SAFETY: the code lives through the calls; the root signature is
  78. // inside it.
  79. unsafe {
  80. let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
  81. let pso: ID3D12PipelineState = host
  82. .device
  83. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  84. pRootSignature: std::mem::transmute_copy(&root),
  85. CS: D3D12_SHADER_BYTECODE {
  86. pShaderBytecode: code.as_ptr().cast(),
  87. BytecodeLength: code.len(),
  88. },
  89. ..Default::default()
  90. })
  91. .ok()?;
  92. name(&pso, || "victory: changed words sent to the card".into());
  93. Some(Pass { root, pso })
  94. }
  95. })
  96. .as_ref()
  97. }
  98. /// Memory a submission's sends come from, mapped.
  99. pub(super) struct Memory {
  100. buffer: ID3D12Resource,
  101. data: usize,
  102. size: u64,
  103. }
  104. // SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner.
  105. unsafe impl Send for Memory {}
  106. /// What submissions that have run gave back.
  107. static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new());
  108. /// At most this much is kept.
  109. const KEPT: u64 = 768 << 20;
  110. fn memory(host: &Host, size: u64) -> Option<Memory> {
  111. {
  112. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  113. let fit = spare.iter().enumerate().filter(|(_, m)| m.size >= size).min_by_key(|(_, m)| m.size).map(|(i, _)| i);
  114. if let Some(i) = fit {
  115. return Some(spare.swap_remove(i));
  116. }
  117. }
  118. // By doubles, so that the next of about this size finds it: what
  119. // submissions send differs from frame to frame.
  120. let size = size.max(8 << 20).next_power_of_two();
  121. let (buffer, data) = host.upload_buffer(size)?;
  122. name(&buffer, || "bytes a submission sends up".into());
  123. Some(Memory {
  124. buffer,
  125. data: data as usize,
  126. size,
  127. })
  128. }
  129. /// The submission has run.
  130. pub(super) fn give_back(memory: Memory) {
  131. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  132. spare.push(memory);
  133. spare.sort_by_key(|m| std::cmp::Reverse(m.size));
  134. while spare.iter().map(|m| m.size).sum::<u64>() > KEPT {
  135. spare.remove(0);
  136. }
  137. }
  138. /// Since the last frame-rate line: bytes copied, runs copied, words stored,
  139. /// microseconds of taking them out of the CPU sides.
  140. pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  141. /// One copy's sends: ranges copied (offset in the copy, in the memory,
  142. /// bytes), and its pairs (where in the memory, how many).
  143. struct Copy {
  144. runs: Vec<(usize, u64, usize)>,
  145. pairs: (u64, u32),
  146. }
  147. /// Where a submission's bytes are taken to.
  148. pub(super) struct Own {
  149. memory: Memory,
  150. copies: Vec<Copy>,
  151. }
  152. /// Takes what `dirty` sends up out of the CPU sides.
  153. pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
  154. let began = std::time::Instant::now();
  155. pass(host)?;
  156. // Runs of whole words of the copy: only those are pairs. (A byte beside
  157. // them in a word may be the card's.)
  158. let short = |&(a, b): &(usize, usize)| short(a, b - a);
  159. let mut at = 0u64;
  160. let mut copies = Vec::with_capacity(dirty.len());
  161. for (_, ranges) in dirty {
  162. let mut runs = Vec::new();
  163. for &(a, b) in ranges.iter().filter(|r| !short(r)) {
  164. runs.push((a, at, b - a));
  165. at += ((b - a) as u64).next_multiple_of(16);
  166. }
  167. let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
  168. copies.push(Copy { runs, pairs: (at, words as u32) });
  169. at += (words as u64 * 8).next_multiple_of(16);
  170. }
  171. if at == 0 {
  172. return None;
  173. }
  174. let memory = memory(host, at)?;
  175. let mut moves: Vec<(usize, usize, usize)> = Vec::new();
  176. for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
  177. let from = shadow.card_data() as usize;
  178. moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
  179. let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2];
  180. for &(a, b) in ranges.iter().filter(|r| short(r)) {
  181. for offset in (a..b).step_by(4) {
  182. // SAFETY: inside the copy's mapping (its CPU side, which
  183. // this thread alone writes in these ranges) and inside the
  184. // memory, which has room for every pair.
  185. unsafe {
  186. let word = ((from + offset) as *const u32).read_unaligned();
  187. to.write([offset as u32, word]);
  188. to = to.add(1);
  189. }
  190. }
  191. }
  192. }
  193. STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
  194. STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
  195. STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
  196. crate::shadow::copy_all(moves);
  197. STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
  198. Some(Own { memory, copies })
  199. }
  200. impl Own {
  201. /// Records the sends into `list`; the copies that `looked` says are in
  202. /// `COPY_DEST`, the others in the common state. Those with a "before" are
  203. /// left readable by compute shaders.
  204. ///
  205. /// # Safety
  206. /// An open list of ours, whose compute state is set anew behind this.
  207. pub(super) unsafe fn record(
  208. &self,
  209. host: &Host,
  210. list: &ID3D12GraphicsCommandList,
  211. dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)],
  212. looked: impl Fn(&Shadow) -> bool,
  213. ) {
  214. let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  215. let write = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  216. let dest = D3D12_RESOURCE_STATE_COPY_DEST;
  217. let (mut first, mut last) = (Vec::new(), Vec::new());
  218. for ((shadow, _), copy) in dirty.iter().zip(&self.copies) {
  219. for &(a, from, n) in &copy.runs {
  220. // SAFETY: the caller's; live buffers, ranges inside them.
  221. unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) };
  222. }
  223. let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest);
  224. if copy.pairs.1 > 0 {
  225. if let Some(was) = state {
  226. first.push(transition(&shadow.buffer, was, write));
  227. }
  228. state = Some(write);
  229. }
  230. let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  231. if let Some(was) = state
  232. && hashed
  233. && (!copy.runs.is_empty() || copy.pairs.1 > 0)
  234. {
  235. last.push(transition(&shadow.buffer, was, read));
  236. }
  237. }
  238. // SAFETY: the caller's; live objects.
  239. unsafe {
  240. if !first.is_empty() {
  241. list.ResourceBarrier(&first);
  242. }
  243. if let Some(pass) = pass(host)
  244. && self.copies.iter().any(|c| c.pairs.1 > 0)
  245. {
  246. list.SetComputeRootSignature(&pass.root);
  247. list.SetPipelineState(&pass.pso);
  248. list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress());
  249. for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) {
  250. list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress());
  251. const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  252. let (at, words) = copy.pairs;
  253. let mut done = 0;
  254. while done < words {
  255. let n = (words - done).min(MOST);
  256. let constants = [at as u32 + done * 8, n];
  257. list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0);
  258. list.Dispatch(n.div_ceil(64), 1, 1);
  259. done += n;
  260. }
  261. }
  262. }
  263. if !last.is_empty() {
  264. list.ResourceBarrier(&last);
  265. }
  266. }
  267. }
  268. /// The memory, to be kept until the submission has run.
  269. pub(super) fn memory(self) -> Memory {
  270. self.memory
  271. }
  272. }