awake.rs 9.9 KB

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