fence.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. //! Fences: a 64-bit value and the events waiting for it. Nothing runs on a
  2. //! GPU yet, so only signals (the title's, later our queues') move one.
  3. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  4. use std::ffi::c_void;
  5. use std::sync::Mutex;
  6. use std::sync::atomic::{AtomicU64, Ordering};
  7. use crate::object::{self, E_NOTIMPL, FENCE, HRESULT, Iid, Object, S_OK, Table, This, guid};
  8. use crate::resource::PAGEABLE_IIDS;
  9. pub(crate) const FENCE_IIDS: [Iid; 5] = [
  10. guid(
  11. 0x0a753dcf,
  12. 0xc4d8,
  13. 0x4b91,
  14. [0xad, 0xf6, 0xbe, 0x5a, 0x60, 0xd9, 0x5a, 0x76],
  15. ),
  16. // ID3D12Fence1.
  17. guid(
  18. 0x433685fe,
  19. 0xe22b,
  20. 0x4ca0,
  21. [0xa8, 0xdb, 0xb5, 0xb4, 0xf4, 0xdd, 0x0e, 0x4a],
  22. ),
  23. PAGEABLE_IIDS[0],
  24. PAGEABLE_IIDS[1],
  25. PAGEABLE_IIDS[2],
  26. ];
  27. #[repr(C)]
  28. struct Fence {
  29. object: Object,
  30. /// Titles also read it straight from memory, at the fence's GPU
  31. /// address.
  32. value: AtomicU64,
  33. flags: u32,
  34. /// Events to set once the value reaches theirs (handles as integers).
  35. waiters: Mutex<Vec<(u64, usize)>>,
  36. }
  37. fn fence<'a>(this: This) -> &'a Fence {
  38. // SAFETY: called from fence methods only.
  39. unsafe { &*this.cast::<Fence>() }
  40. }
  41. pub(crate) extern "system" fn create(
  42. _: This,
  43. initial: u64,
  44. flags: u32,
  45. iid: *const Iid,
  46. out: *mut This,
  47. ) -> HRESULT {
  48. tracing::debug!(initial, flags, "fence");
  49. let fence = Box::new(Fence {
  50. object: Object::new(&FUNCTIONS),
  51. value: AtomicU64::new(initial),
  52. flags,
  53. waiters: Mutex::new(Vec::new()),
  54. });
  55. object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out)
  56. }
  57. fn set_event(event: usize) {
  58. #[cfg(windows)]
  59. // SAFETY: the title passed an event handle.
  60. unsafe {
  61. windows_sys::Win32::System::Threading::SetEvent(event as *mut c_void)
  62. };
  63. #[cfg(not(windows))]
  64. let _ = event;
  65. }
  66. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  67. object::answer(
  68. FENCE,
  69. iid,
  70. object::is(iid, &FENCE_IIDS).then_some(this),
  71. out,
  72. )
  73. }
  74. extern "system" fn release(this: This) -> u32 {
  75. object::release_boxed::<Fence>(this)
  76. }
  77. pub(crate) extern "system" fn completed(this: This) -> u64 {
  78. fence(this).value.load(Ordering::Acquire)
  79. }
  80. /// The title's `GetCompletedValue`.
  81. extern "system" fn completed_called(this: This) -> u64 {
  82. let value = completed(this);
  83. #[cfg(all(windows, feature = "diagnostics"))]
  84. crate::timeline::polled(this as usize, value);
  85. value
  86. }
  87. extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c_void) -> HRESULT {
  88. let fence = fence(this);
  89. let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
  90. if fence.value.load(Ordering::Acquire) >= value {
  91. if !event.is_null() {
  92. set_event(event as usize);
  93. }
  94. return S_OK;
  95. }
  96. #[cfg(all(windows, feature = "diagnostics"))]
  97. crate::timeline::told("an event asked for", this as usize, value);
  98. if event.is_null() {
  99. // With submissions sent to the card and not waited for
  100. // (`crate::host::late`) the signal may be behind them: they are
  101. // settled, which sets it.
  102. #[cfg(windows)]
  103. if crate::host::late() {
  104. drop(waiters);
  105. crate::queue::before_sync();
  106. crate::host::settle_for_fence();
  107. if fence.value.load(Ordering::Acquire) >= value {
  108. return S_OK;
  109. }
  110. tracing::warn!(value, "blocking fence wait not implemented");
  111. return E_NOTIMPL;
  112. }
  113. // shortcut: a null event means "block until reached"; nothing can
  114. // reach it while no GPU work runs, so fail instead of hanging.
  115. tracing::warn!(value, "blocking fence wait not implemented");
  116. return E_NOTIMPL;
  117. }
  118. waiters.push((value, event as usize));
  119. S_OK
  120. }
  121. /// Moves the fence to `value` and sets the events that waited for it.
  122. pub(crate) fn set(this: This, value: u64) {
  123. let fence = fence(this);
  124. #[cfg(all(windows, feature = "diagnostics"))]
  125. crate::timeline::told("a fence set", this as usize, value);
  126. let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner());
  127. fence.value.store(value, Ordering::Release);
  128. waiters.retain(|&(wanted, event)| {
  129. let reached = wanted <= value;
  130. if reached {
  131. set_event(event);
  132. }
  133. !reached
  134. });
  135. }
  136. pub(crate) extern "system" fn signal(this: This, value: u64) -> HRESULT {
  137. let _called = crate::timeline::span("a fence set");
  138. set(this, value);
  139. // A queue may have waited for it: what it held runs now.
  140. #[cfg(windows)]
  141. crate::queue::release_held(false);
  142. S_OK
  143. }
  144. extern "system" fn creation_flags(this: This) -> u32 {
  145. fence(this).flags
  146. }
  147. /// Where the value lives (GPU addresses are CPU addresses).
  148. extern "system" fn gpu_address(this: This) -> u64 {
  149. (&raw const fence(this).value) as u64
  150. }
  151. /// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console
  152. /// one among them).
  153. static FUNCTIONS: Table<24> = {
  154. let mut f = object::d3d12_object(object::missing_table::<FENCE, 24>());
  155. f[0] = query as *const ();
  156. f[2] = release as *const ();
  157. f[7] = object::parent_device as *const (); // 0x38
  158. f[8] = completed_called as *const (); // 0x40
  159. f[9] = set_event_on_completion as *const (); // 0x48
  160. f[10] = signal as *const (); // 0x50
  161. f[11] = creation_flags as *const (); // 0x58
  162. f[12] = gpu_address as *const (); // 0x60
  163. Table(f)
  164. };
  165. #[cfg(test)]
  166. mod tests {
  167. use super::*;
  168. use crate::object::slot;
  169. #[cfg(windows)]
  170. #[test]
  171. fn signals_set_waiting_events() {
  172. use windows_sys::Win32::Foundation::{CloseHandle, WAIT_OBJECT_0};
  173. use windows_sys::Win32::System::Threading::{CreateEventW, WaitForSingleObject};
  174. let mut f = std::ptr::null();
  175. assert_eq!(create(std::ptr::null(), 1, 0, &FENCE_IIDS[0], &mut f), S_OK);
  176. assert_eq!(slot::<extern "system" fn(This) -> u64>(f, 0x40)(f), 1);
  177. // SAFETY: plain auto-reset event.
  178. let event = unsafe { CreateEventW(std::ptr::null(), 0, 0, std::ptr::null()) };
  179. assert!(!event.is_null());
  180. let wait = slot::<extern "system" fn(This, u64, *mut c_void) -> HRESULT>(f, 0x48);
  181. let signal = slot::<extern "system" fn(This, u64) -> HRESULT>(f, 0x50);
  182. assert_eq!(wait(f, 5, event), S_OK);
  183. // SAFETY: a valid event.
  184. assert_ne!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
  185. assert_eq!(signal(f, 5), S_OK);
  186. // SAFETY: as above.
  187. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
  188. assert_eq!(wait(f, 5, event), S_OK, "already reached");
  189. // SAFETY: as above.
  190. assert_eq!(unsafe { WaitForSingleObject(event, 0) }, WAIT_OBJECT_0);
  191. assert_eq!(wait(f, 9, std::ptr::null_mut()), E_NOTIMPL);
  192. // The title reads the value at the fence's address.
  193. let at = slot::<extern "system" fn(This) -> u64>(f, 0x60)(f);
  194. // SAFETY: the fence's value.
  195. assert_eq!(unsafe { *(at as *const u64) }, 5);
  196. // SAFETY: ours.
  197. unsafe { CloseHandle(event) };
  198. assert_eq!(slot::<extern "system" fn(This) -> u32>(f, 0x10)(f), 0);
  199. }
  200. #[test]
  201. fn fence1_interface_is_created_and_queried() {
  202. const FENCE1_IID: Iid = guid(
  203. 0x433685fe,
  204. 0xe22b,
  205. 0x4ca0,
  206. [0xa8, 0xdb, 0xb5, 0xb4, 0xf4, 0xdd, 0x0e, 0x4a],
  207. );
  208. type Query = extern "system" fn(This, *const Iid, *mut This) -> HRESULT;
  209. type Flags = extern "system" fn(This) -> u32;
  210. type Release = extern "system" fn(This) -> u32;
  211. // Direct creation as ID3D12Fence1, and GetCreationFlags at slot 0x58.
  212. let mut f1 = std::ptr::null();
  213. assert_eq!(create(std::ptr::null(), 3, 0x5, &FENCE1_IID, &mut f1), S_OK);
  214. assert!(!f1.is_null());
  215. assert_eq!(slot::<Flags>(f1, 0x58)(f1), 0x5);
  216. assert_eq!(slot::<Release>(f1, 0x10)(f1), 0);
  217. // QueryInterface from ID3D12Fence to ID3D12Fence1 returns the same object.
  218. let mut f = std::ptr::null();
  219. assert_eq!(
  220. create(std::ptr::null(), 0, 0x2, &FENCE_IIDS[0], &mut f),
  221. S_OK
  222. );
  223. let mut queried = std::ptr::null();
  224. assert_eq!(slot::<Query>(f, 0x00)(f, &FENCE1_IID, &mut queried), S_OK);
  225. assert_eq!(queried, f);
  226. assert_eq!(slot::<Flags>(queried, 0x58)(queried), 0x2);
  227. assert_eq!(slot::<Release>(queried, 0x10)(queried), 1);
  228. assert_eq!(slot::<Release>(f, 0x10)(f), 0);
  229. }
  230. }