send.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. const SCATTER: &str = r#"
  30. #define RS "RootConstants(num32BitConstants=2, b0), SRV(t0), UAV(u0)"
  31. cbuffer Part : register(b0) { uint at; uint count; };
  32. ByteAddressBuffer pairs : register(t0);
  33. RWByteAddressBuffer card : register(u0);
  34. [RootSignature(RS)]
  35. [numthreads(64, 1, 1)]
  36. void main(uint3 id : SV_DispatchThreadID) {
  37. if (id.x >= count) return;
  38. uint2 p = pairs.Load2(at + id.x * 8u);
  39. card.Store(p.x, p.y);
  40. }
  41. "#;
  42. struct Pass {
  43. root: ID3D12RootSignature,
  44. pso: ID3D12PipelineState,
  45. }
  46. fn pass(host: &Host) -> Option<&'static Pass> {
  47. static PASS: OnceLock<Option<Pass>> = OnceLock::new();
  48. PASS.get_or_init(|| {
  49. let code = compile(SCATTER, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
  50. // SAFETY: the code lives through the calls; the root signature is
  51. // inside it.
  52. unsafe {
  53. let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
  54. let pso: ID3D12PipelineState = host
  55. .device
  56. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  57. pRootSignature: std::mem::transmute_copy(&root),
  58. CS: D3D12_SHADER_BYTECODE {
  59. pShaderBytecode: code.as_ptr().cast(),
  60. BytecodeLength: code.len(),
  61. },
  62. ..Default::default()
  63. })
  64. .ok()?;
  65. name(&pso, || "victory: changed words sent to the card".into());
  66. Some(Pass { root, pso })
  67. }
  68. })
  69. .as_ref()
  70. }
  71. /// Memory a submission's sends come from, mapped.
  72. pub(super) struct Memory {
  73. buffer: ID3D12Resource,
  74. data: usize,
  75. size: u64,
  76. }
  77. // SAFETY: a D3D12 object (free-threaded) and its mapping, with one owner.
  78. unsafe impl Send for Memory {}
  79. /// What submissions that have run gave back.
  80. static SPARE: Mutex<Vec<Memory>> = Mutex::new(Vec::new());
  81. /// At most this much is kept (of the card's memory, with [`on_card`]).
  82. fn kept() -> u64 {
  83. if on_card() { 256 << 20 } else { 768 << 20 }
  84. }
  85. /// Whether the memory lies in the card's memory, written by the CPU through
  86. /// the bus (`VICTORY_SEND_BAR=1`): the copies on the card's drawing queue, which
  87. /// nothing overlaps, then cross no bus. In a captured frame they took 5.4 ms of
  88. /// the card's 30 (342 copies), and take 0.4 this way; but filling it takes the
  89. /// submitting thread 8-9 ms a frame instead of 3 (73-93 MB, run card-3 against
  90. /// card-1), so it is a loss while the card waits for that thread: off by
  91. /// default.
  92. fn on_card() -> bool {
  93. static ON: OnceLock<bool> = OnceLock::new();
  94. *ON.get_or_init(|| std::env::var_os("VICTORY_SEND_BAR").is_some_and(|v| v == "1"))
  95. }
  96. fn memory(host: &Host, size: u64) -> Option<Memory> {
  97. {
  98. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  99. let fit = spare.iter().enumerate().filter(|(_, m)| m.size >= size).min_by_key(|(_, m)| m.size).map(|(i, _)| i);
  100. if let Some(i) = fit {
  101. return Some(spare.swap_remove(i));
  102. }
  103. }
  104. let size = size.next_multiple_of(8 << 20);
  105. let mapped = if on_card() { host.mapped_card_buffer(size, false) } else { None };
  106. let (buffer, data) = match mapped {
  107. Some(made) => made,
  108. None => host.upload_buffer(size)?,
  109. };
  110. name(&buffer, || "bytes a submission sends up".into());
  111. Some(Memory {
  112. buffer,
  113. data: data as usize,
  114. size,
  115. })
  116. }
  117. /// The submission has run.
  118. pub(super) fn give_back(memory: Memory) {
  119. let mut spare = SPARE.lock().unwrap_or_else(|e| e.into_inner());
  120. spare.push(memory);
  121. spare.sort_by_key(|m| std::cmp::Reverse(m.size));
  122. while spare.iter().map(|m| m.size).sum::<u64>() > kept() {
  123. spare.remove(0);
  124. }
  125. }
  126. /// Since the last frame-rate line: bytes copied, runs copied, words stored,
  127. /// microseconds of taking them out of the CPU sides.
  128. pub(super) static STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  129. /// One copy's sends: ranges copied (offset in the copy, in the memory,
  130. /// bytes), and its pairs (where in the memory, how many).
  131. struct Copy {
  132. runs: Vec<(usize, u64, usize)>,
  133. pairs: (u64, u32),
  134. }
  135. /// Where a submission's bytes are taken to.
  136. pub(super) struct Own {
  137. memory: Memory,
  138. copies: Vec<Copy>,
  139. }
  140. /// Takes what `dirty` sends up out of the CPU sides.
  141. pub(super) fn take(host: &Host, dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)]) -> Option<Own> {
  142. let began = std::time::Instant::now();
  143. pass(host)?;
  144. // Runs of whole words of the copy: only those are pairs. (A byte beside
  145. // them in a word may be the card's.)
  146. let short = |&(a, b): &(usize, usize)| b - a <= SHORT && a % 4 == 0 && b % 4 == 0;
  147. let mut at = 0u64;
  148. let mut copies = Vec::with_capacity(dirty.len());
  149. for (_, ranges) in dirty {
  150. let mut runs = Vec::new();
  151. for &(a, b) in ranges.iter().filter(|r| !short(r)) {
  152. runs.push((a, at, b - a));
  153. at += ((b - a) as u64).next_multiple_of(16);
  154. }
  155. let words: usize = ranges.iter().filter(|r| short(r)).map(|r| (r.1 - r.0) / 4).sum();
  156. copies.push(Copy { runs, pairs: (at, words as u32) });
  157. at += (words as u64 * 8).next_multiple_of(16);
  158. }
  159. if at == 0 {
  160. return None;
  161. }
  162. let memory = memory(host, at)?;
  163. let mut moves: Vec<(usize, usize, usize)> = Vec::new();
  164. for ((shadow, ranges), copy) in dirty.iter().zip(&copies) {
  165. let from = shadow.card_data() as usize;
  166. moves.extend(copy.runs.iter().map(|&(a, to, n)| (from + a, memory.data + to as usize, n)));
  167. let mut to = (memory.data + copy.pairs.0 as usize) as *mut [u32; 2];
  168. for &(a, b) in ranges.iter().filter(|r| short(r)) {
  169. for offset in (a..b).step_by(4) {
  170. // SAFETY: inside the copy's mapping (its CPU side, which
  171. // this thread alone writes in these ranges) and inside the
  172. // memory, which has room for every pair.
  173. unsafe {
  174. let word = ((from + offset) as *const u32).read_unaligned();
  175. to.write([offset as u32, word]);
  176. to = to.add(1);
  177. }
  178. }
  179. }
  180. }
  181. STATS[0].fetch_add(moves.iter().map(|m| m.2 as u64).sum(), Ordering::Relaxed);
  182. STATS[1].fetch_add(moves.len() as u64, Ordering::Relaxed);
  183. STATS[2].fetch_add(copies.iter().map(|c| u64::from(c.pairs.1)).sum(), Ordering::Relaxed);
  184. crate::shadow::copy_all(moves);
  185. STATS[3].fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
  186. Some(Own { memory, copies })
  187. }
  188. impl Own {
  189. /// Records the sends into `list`; the copies that `looked` says are in
  190. /// `COPY_DEST`, the others in the common state. Those with a "before" are
  191. /// left readable by compute shaders.
  192. ///
  193. /// # Safety
  194. /// An open list of ours, whose compute state is set anew behind this.
  195. pub(super) unsafe fn record(
  196. &self,
  197. host: &Host,
  198. list: &ID3D12GraphicsCommandList,
  199. dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)],
  200. looked: impl Fn(&Shadow) -> bool,
  201. ) {
  202. let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE;
  203. let write = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
  204. let dest = D3D12_RESOURCE_STATE_COPY_DEST;
  205. let (mut first, mut last) = (Vec::new(), Vec::new());
  206. for ((shadow, _), copy) in dirty.iter().zip(&self.copies) {
  207. for &(a, from, n) in &copy.runs {
  208. // SAFETY: the caller's; live buffers, ranges inside them.
  209. unsafe { list.CopyBufferRegion(&shadow.buffer, a as u64, &self.memory.buffer, from, n as u64) };
  210. }
  211. let mut state = (looked(shadow) || !copy.runs.is_empty()).then_some(dest);
  212. if copy.pairs.1 > 0 {
  213. if let Some(was) = state {
  214. first.push(transition(&shadow.buffer, was, write));
  215. }
  216. state = Some(write);
  217. }
  218. let hashed = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some());
  219. if let Some(was) = state
  220. && hashed
  221. && (!copy.runs.is_empty() || copy.pairs.1 > 0)
  222. {
  223. last.push(transition(&shadow.buffer, was, read));
  224. }
  225. }
  226. // SAFETY: the caller's; live objects.
  227. unsafe {
  228. if !first.is_empty() {
  229. list.ResourceBarrier(&first);
  230. }
  231. if let Some(pass) = pass(host)
  232. && self.copies.iter().any(|c| c.pairs.1 > 0)
  233. {
  234. list.SetComputeRootSignature(&pass.root);
  235. list.SetPipelineState(&pass.pso);
  236. list.SetComputeRootShaderResourceView(1, self.memory.buffer.GetGPUVirtualAddress());
  237. for ((shadow, _), copy) in dirty.iter().zip(&self.copies).filter(|(_, c)| c.pairs.1 > 0) {
  238. list.SetComputeRootUnorderedAccessView(2, shadow.buffer.GetGPUVirtualAddress());
  239. const MOST: u32 = 64 * D3D12_CS_DISPATCH_MAX_THREAD_GROUPS_PER_DIMENSION;
  240. let (at, words) = copy.pairs;
  241. let mut done = 0;
  242. while done < words {
  243. let n = (words - done).min(MOST);
  244. let constants = [at as u32 + done * 8, n];
  245. list.SetComputeRoot32BitConstants(0, 2, constants.as_ptr().cast(), 0);
  246. list.Dispatch(n.div_ceil(64), 1, 1);
  247. done += n;
  248. }
  249. }
  250. }
  251. if !last.is_empty() {
  252. list.ResourceBarrier(&last);
  253. }
  254. }
  255. }
  256. /// The memory, to be kept until the submission has run.
  257. pub(super) fn memory(self) -> Memory {
  258. self.memory
  259. }
  260. }