awake.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. //! Keeps the card's clocks up between submissions (`VICTORY_CARD_AWAKE=1`; off
  2. //! by default). The card stands idle half of every frame, some thirty times for
  3. //! a millisecond or two each, while the CPU prepares the next submission. The
  4. //! driver takes that for a light load and lowers the clocks, and what comes
  5. //! next starts slow: a captured frame whose lists take 30 ms sent in one go
  6. //! takes 38-40 ms with waits of 1.2-2.4 ms between its submissions
  7. //! (`victory replay --pace`).
  8. //!
  9. //! One group of 64 threads counts on a compute queue, over and
  10. //! over: it takes one or two of the card's few thousand wave slots, and the
  11. //! card is never idle. Nothing is sent once no submission has gone out for a
  12. //! while (a menu at 30 fps, a minimized window).
  13. use std::sync::OnceLock;
  14. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
  15. use std::time::Duration;
  16. use windows::Win32::Foundation::CloseHandle;
  17. use windows::Win32::Graphics::Direct3D12::*;
  18. use windows::Win32::System::Threading::{CreateEventW, INFINITE, WaitForSingleObject};
  19. use windows::core::Interface;
  20. /// About 2 ms at full clocks: 500 sends a second.
  21. const COUNT: &str = r#"
  22. #define RS "UAV(u0)"
  23. RWByteAddressBuffer sum : register(u0);
  24. [RootSignature(RS)]
  25. [numthreads(64, 1, 1)]
  26. void main(uint3 id : SV_DispatchThreadID) {
  27. uint x = id.x;
  28. [loop] for (uint i = 0; i < 400000u; i++) x = x * 1664525u + 1013904223u;
  29. sum.Store(id.x * 4u, x);
  30. }
  31. "#;
  32. /// Quiet this long after the last submission.
  33. const QUIET_MS: u64 = 250;
  34. fn now_ms() -> u64 {
  35. static START: OnceLock<std::time::Instant> = OnceLock::new();
  36. START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64
  37. }
  38. /// When a submission was last sent ([`now_ms`] plus one; 0: never).
  39. static LAST: AtomicU64 = AtomicU64::new(0);
  40. fn wanted() -> bool {
  41. let (last, now) = (LAST.load(Ordering::Relaxed), now_ms());
  42. last != 0 && now + 1 < last + QUIET_MS && (mode() != Mode::ByTurns || now / TURN_MS % 2 == 1)
  43. }
  44. /// With `VICTORY_CARD_AWAKE=turns`: this long on, this long off.
  45. const TURN_MS: u64 = 20_000;
  46. #[derive(Clone, Copy, PartialEq)]
  47. enum Mode {
  48. Off,
  49. On,
  50. /// On and off by turns, to compare the two in one run (the log says when).
  51. ByTurns,
  52. }
  53. fn mode() -> Mode {
  54. static MODE: OnceLock<Mode> = OnceLock::new();
  55. *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_AWAKE").as_deref() {
  56. Ok("1") => Mode::On,
  57. Ok("turns") => Mode::ByTurns,
  58. _ => Mode::Off,
  59. })
  60. }
  61. /// A submission of the title's goes to `device`'s drawing queue.
  62. pub(super) fn sent(device: &ID3D12Device) {
  63. if mode() == Mode::Off {
  64. return;
  65. }
  66. let now = now_ms();
  67. let before = LAST.swap(now + 1, Ordering::Relaxed);
  68. if mode() == Mode::ByTurns && before.saturating_sub(1) / TURN_MS != now / TURN_MS {
  69. tracing::info!(on = now / TURN_MS % 2 == 1, "the card is kept awake, by turns");
  70. }
  71. static STARTED: std::sync::Once = std::sync::Once::new();
  72. STARTED.call_once(|| {
  73. // Runs as long as the process does.
  74. std::mem::forget(start(device, wanted));
  75. });
  76. }
  77. /// The thread that keeps the card busy; it ends when this is dropped.
  78. pub(crate) struct Awake {
  79. stop: std::sync::Arc<AtomicBool>,
  80. thread: Option<std::thread::JoinHandle<()>>,
  81. }
  82. impl Drop for Awake {
  83. fn drop(&mut self) {
  84. self.stop.store(true, Ordering::Relaxed);
  85. if let Some(thread) = self.thread.take() {
  86. let _ = thread.join();
  87. }
  88. }
  89. }
  90. /// Keeps the card of `device` busy while `wanted`.
  91. pub(crate) fn start(device: &ID3D12Device, wanted: impl Fn() -> bool + Send + 'static) -> Option<Awake> {
  92. let stop = std::sync::Arc::new(AtomicBool::new(false));
  93. let (device, ended) = (device.clone(), stop.clone());
  94. let thread = std::thread::Builder::new()
  95. .name("victory-card-awake".into())
  96. .spawn(move || {
  97. if let Err(e) = run(&device, &wanted, &ended) {
  98. tracing::warn!(error = %e, "the card is not kept awake");
  99. }
  100. })
  101. .ok()?;
  102. Some(Awake {
  103. stop,
  104. thread: Some(thread),
  105. })
  106. }
  107. fn run(device: &ID3D12Device, wanted: &dyn Fn() -> bool, stop: &AtomicBool) -> windows::core::Result<()> {
  108. let code = super::compile(COUNT, windows::core::s!("main"), windows::core::s!("cs_5_1"))?;
  109. // SAFETY: plain object creation; the code lives through the calls, the
  110. // root signature is inside it. Two closed lists, sent in turn, whose
  111. // objects live until what was sent last has run.
  112. unsafe {
  113. let root: ID3D12RootSignature = device.CreateRootSignature(0, &code)?;
  114. let pso: ID3D12PipelineState = device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  115. pRootSignature: std::mem::transmute_copy(&root),
  116. CS: D3D12_SHADER_BYTECODE {
  117. pShaderBytecode: code.as_ptr().cast(),
  118. BytecodeLength: code.len(),
  119. },
  120. ..Default::default()
  121. })?;
  122. let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  123. Type: D3D12_COMMAND_LIST_TYPE_COMPUTE,
  124. Priority: D3D12_COMMAND_QUEUE_PRIORITY_NORMAL.0,
  125. ..Default::default()
  126. })?;
  127. let mut sum: Option<ID3D12Resource> = None;
  128. device.CreateCommittedResource(
  129. &D3D12_HEAP_PROPERTIES {
  130. Type: D3D12_HEAP_TYPE_DEFAULT,
  131. ..Default::default()
  132. },
  133. D3D12_HEAP_FLAG_NONE,
  134. &D3D12_RESOURCE_DESC {
  135. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  136. Width: 256,
  137. Height: 1,
  138. DepthOrArraySize: 1,
  139. MipLevels: 1,
  140. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  141. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  142. Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS,
  143. ..Default::default()
  144. },
  145. D3D12_RESOURCE_STATE_COMMON,
  146. None,
  147. &mut sum,
  148. )?;
  149. let sum = sum.ok_or_else(windows::core::Error::empty)?;
  150. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE)?;
  151. let mut lists = Vec::new();
  152. for _ in 0..2 {
  153. let list: ID3D12GraphicsCommandList =
  154. device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, &allocator, &pso)?;
  155. list.SetComputeRootSignature(&root);
  156. list.SetComputeRootUnorderedAccessView(0, sum.GetGPUVirtualAddress());
  157. list.Dispatch(1, 1, 1);
  158. list.Close()?;
  159. lists.push(Some(list.cast::<ID3D12CommandList>()?));
  160. }
  161. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?;
  162. let event = CreateEventW(None, false, false, None)?;
  163. let mut value = 0u64;
  164. let mut result = Ok(());
  165. while !stop.load(Ordering::Relaxed) && result.is_ok() {
  166. if !wanted() {
  167. std::thread::sleep(Duration::from_millis(2));
  168. continue;
  169. }
  170. // Never more than two on the way.
  171. if value >= 2 && fence.GetCompletedValue() + 2 <= value {
  172. result = fence.SetEventOnCompletion(value - 1, event);
  173. if result.is_ok() {
  174. WaitForSingleObject(event, 1000);
  175. result = device.GetDeviceRemovedReason();
  176. }
  177. continue;
  178. }
  179. queue.ExecuteCommandLists(&lists[(value % 2) as usize..][..1]);
  180. value += 1;
  181. result = queue.Signal(&fence, value);
  182. }
  183. if result.is_ok() && fence.GetCompletedValue() < value && fence.SetEventOnCompletion(value, event).is_ok() {
  184. WaitForSingleObject(event, INFINITE);
  185. }
  186. let _ = CloseHandle(event);
  187. result
  188. }
  189. }
  190. #[cfg(test)]
  191. mod tests {
  192. use super::*;
  193. /// Card memory the CPU maps holds what the CPU wrote, with the card kept
  194. /// awake meanwhile; the thread ends when it is let go.
  195. #[test]
  196. fn mapped_card_memory_is_written_by_the_cpu_and_read_by_the_card() {
  197. let Some(host) = crate::host::host() else {
  198. return;
  199. };
  200. let awake = start(&host.device, || true);
  201. assert!(awake.is_some());
  202. let Some((buffer, data)) = host.mapped_card_buffer(4096, true) else {
  203. return;
  204. };
  205. let (seen, back) = host.shared_buffer(4096).unwrap();
  206. // SAFETY: mappings of 4096 bytes; a list, a queue and a fence of the
  207. // test's own, and nothing is read before the copy has run.
  208. let read = unsafe {
  209. for i in 0..4096 {
  210. data.add(i).write((i * 7 + i / 251) as u8);
  211. }
  212. let device = &host.device;
  213. let queue: ID3D12CommandQueue = device
  214. .CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC {
  215. Type: D3D12_COMMAND_LIST_TYPE_DIRECT,
  216. ..Default::default()
  217. })
  218. .unwrap();
  219. let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).unwrap();
  220. let list: ID3D12GraphicsCommandList =
  221. device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).unwrap();
  222. list.CopyBufferRegion(&seen, 0, &buffer, 0, 4096);
  223. list.Close().unwrap();
  224. queue.ExecuteCommandLists(&[Some(list.cast().unwrap())]);
  225. let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE).unwrap();
  226. queue.Signal(&fence, 1).unwrap();
  227. // No event: returns when the fence is there.
  228. fence.SetEventOnCompletion(1, windows::Win32::Foundation::HANDLE::default()).unwrap();
  229. std::slice::from_raw_parts(back, 4096).to_vec()
  230. };
  231. assert!(read.iter().enumerate().all(|(i, &b)| b == (i * 7 + i / 251) as u8));
  232. drop(awake);
  233. }
  234. }