queue.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. //! Command queues. Submitted lists run on the host GPU and are waited for,
  2. //! so fence signals complete at once.
  3. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  4. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
  5. use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, QUEUE, S_OK, Table, This, guid};
  6. use crate::resource::PAGEABLE_IIDS;
  7. const QUEUE_IIDS: [Iid; 4] = [
  8. guid(
  9. 0x0ec870a6,
  10. 0x5d7e,
  11. 0x4c22,
  12. [0x8c, 0xfc, 0x5b, 0xaa, 0xe0, 0x76, 0x16, 0xed],
  13. ),
  14. PAGEABLE_IIDS[0],
  15. PAGEABLE_IIDS[1],
  16. PAGEABLE_IIDS[2],
  17. ];
  18. #[repr(C)]
  19. #[derive(Debug, Clone, Copy)]
  20. pub(crate) struct QueueDesc {
  21. kind: u32,
  22. priority: i32,
  23. flags: u32,
  24. nodes: u32,
  25. }
  26. /// The title reads the list type right after the header.
  27. #[repr(C)]
  28. struct Queue {
  29. object: Object,
  30. kind: u32,
  31. desc: QueueDesc,
  32. }
  33. const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
  34. fn queue<'a>(this: This) -> &'a Queue {
  35. // SAFETY: called from queue methods only.
  36. unsafe { &*this.cast::<Queue>() }
  37. }
  38. pub(crate) extern "system" fn create(
  39. _: This,
  40. desc: *const QueueDesc,
  41. iid: *const Iid,
  42. out: *mut This,
  43. ) -> HRESULT {
  44. // SAFETY: the title passes a description (null is tolerated).
  45. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  46. return E_INVALIDARG;
  47. };
  48. tracing::debug!(?desc, "command queue");
  49. let queue = Box::new(Queue {
  50. object: if crate::device::newer() {
  51. Object::new(&NEWER_FUNCTIONS)
  52. } else {
  53. Object::new(&FUNCTIONS)
  54. },
  55. kind: desc.kind,
  56. desc,
  57. });
  58. object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
  59. }
  60. /// The console's queue description: an engine or pipe and a queue on it
  61. /// in place of PC's priority and node mask.
  62. #[repr(C)]
  63. #[derive(Debug, Clone, Copy)]
  64. pub(crate) struct QueueDescX {
  65. kind: u32,
  66. flags: u32,
  67. engine_or_pipe: u32,
  68. queue: u32,
  69. }
  70. /// Device method `CreateCommandQueueX`. The host picks engines itself, so
  71. /// the queue is created as on PC.
  72. pub(crate) extern "system" fn create_x(
  73. this: This,
  74. desc: *const QueueDescX,
  75. iid: *const Iid,
  76. out: *mut This,
  77. ) -> HRESULT {
  78. // SAFETY: the title passes a description (null is tolerated).
  79. let Some(&x) = (unsafe { desc.as_ref() }) else {
  80. return E_INVALIDARG;
  81. };
  82. tracing::debug!(desc = ?x, "console command queue");
  83. let desc = QueueDesc {
  84. kind: x.kind,
  85. priority: 0,
  86. flags: x.flags,
  87. nodes: 1,
  88. };
  89. create(this, &desc, iid, out)
  90. }
  91. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  92. object::answer(
  93. QUEUE,
  94. iid,
  95. object::is(iid, &QUEUE_IIDS).then_some(this),
  96. out,
  97. )
  98. }
  99. extern "system" fn release(this: This) -> u32 {
  100. object::release_boxed::<Queue>(this)
  101. }
  102. /// Runs the lists' host lists and waits for them (decision 0007).
  103. extern "system" fn execute(_: This, count: u32, lists: *const This) {
  104. if lists.is_null() {
  105. return;
  106. }
  107. #[cfg(windows)]
  108. if let Some(host) = crate::host::host() {
  109. // SAFETY: the title passes `count` lists.
  110. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
  111. let host_lists: Vec<_> = lists
  112. .iter()
  113. .filter_map(|&l| crate::list::host_list(l))
  114. .collect();
  115. host.execute(&host_lists);
  116. return;
  117. }
  118. static ONCE: AtomicBool = AtomicBool::new(false);
  119. if !ONCE.swap(true, Ordering::Relaxed) {
  120. tracing::warn!(count, "command lists submitted; no host GPU runs them");
  121. }
  122. }
  123. /// The start of a present plane: frame token, then the plane's resources.
  124. #[repr(C)]
  125. pub(crate) struct Plane {
  126. token: u64,
  127. count: u32,
  128. resources: *const This,
  129. }
  130. /// Submission tagged with the frame it belongs to `(count, lists, frame
  131. /// token, flags)`; frames are paced elsewhere, so it runs as a plain one.
  132. extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) {
  133. execute(this, count, lists);
  134. }
  135. /// Signal with sync settings for the top and bottom of the pipe; our
  136. /// submissions are complete when they return, so it signals at once.
  137. extern "system" fn signal2_x(
  138. this: This,
  139. fence: This,
  140. value: u64,
  141. _bottom: *const u8,
  142. _top: *const u8,
  143. ) -> HRESULT {
  144. signal(this, fence, value)
  145. }
  146. /// Markers and events only matter to profilers.
  147. extern "system" fn marker(_: This) {}
  148. extern "system" fn signal(_: This, fence: This, value: u64) -> HRESULT {
  149. if fence.is_null() {
  150. return E_INVALIDARG;
  151. }
  152. crate::fence::signal(fence, value)
  153. }
  154. /// Nothing runs on the queue, so waiting for a fence never blocks it.
  155. extern "system" fn wait(_: This, fence: This, _value: u64) -> HRESULT {
  156. if fence.is_null() { E_INVALIDARG } else { S_OK }
  157. }
  158. /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
  159. extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
  160. if out.is_null() {
  161. return E_INVALIDARG;
  162. }
  163. // SAFETY: checked non-null.
  164. unsafe { out.write(TIMESTAMP_FREQUENCY) };
  165. S_OK
  166. }
  167. const TIMESTAMP_FREQUENCY: u64 = 100_000_000;
  168. /// What a list's bottom-of-pipe write stores when the list has run.
  169. #[derive(Debug, Clone, Copy)]
  170. pub(crate) enum Written {
  171. Value(u64),
  172. /// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the
  173. /// process started (our GPU work is done on the CPU's timeline).
  174. GpuTimestamp,
  175. /// The CPU's performance counter.
  176. SystemTimestamp,
  177. }
  178. impl Written {
  179. /// Stores the low `bytes` (4 or 8) of the value at `at`.
  180. pub(crate) fn write(self, at: *mut u8, bytes: usize) {
  181. let value = match self {
  182. Written::Value(v) => v,
  183. Written::GpuTimestamp => {
  184. static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
  185. let elapsed = START.get_or_init(std::time::Instant::now).elapsed();
  186. (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64
  187. }
  188. Written::SystemTimestamp => system_timestamp(),
  189. };
  190. // SAFETY: the title names writable GPU memory (unified with ours).
  191. unsafe {
  192. if bytes == 4 {
  193. at.cast::<u32>().write_unaligned(value as u32);
  194. } else {
  195. at.cast::<u64>().write_unaligned(value);
  196. }
  197. }
  198. }
  199. }
  200. fn system_timestamp() -> u64 {
  201. #[cfg(windows)]
  202. {
  203. let mut count = 0;
  204. // SAFETY: a valid out pointer.
  205. unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) };
  206. count as u64
  207. }
  208. #[cfg(not(windows))]
  209. 0
  210. }
  211. /// Frames presented so far.
  212. static FRAMES: AtomicU64 = AtomicU64::new(0);
  213. #[cfg(feature = "diagnostics")]
  214. pub(crate) fn presented() -> u64 {
  215. FRAMES.load(Ordering::Relaxed)
  216. }
  217. /// Shows the first plane's first resource in our window.
  218. ///
  219. /// shortcut: one plane, no scaling or placement, the source expected in
  220. /// the common state.
  221. extern "system" fn present(
  222. _: This,
  223. planes: u32,
  224. plane_parameters: *const Plane,
  225. _parameters: *const u8,
  226. ) -> HRESULT {
  227. let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
  228. if frame.is_power_of_two() {
  229. let (draws, dispatches) = crate::list::take_counts();
  230. #[cfg(windows)]
  231. let (drawn, dispatched) = {
  232. static DRAWN: AtomicU64 = AtomicU64::new(0);
  233. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  234. let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed);
  235. (
  236. since(&DRAWN, crate::draw::drawn()),
  237. since(&DISPATCHED, crate::draw::dispatched()),
  238. )
  239. };
  240. #[cfg(not(windows))]
  241. let (drawn, dispatched) = (0, 0);
  242. tracing::info!(
  243. frame,
  244. draws,
  245. drawn,
  246. dispatches,
  247. dispatched,
  248. "frame presented (since the last line: draws and dispatches, and those run on the host)"
  249. );
  250. #[cfg(windows)]
  251. if frame >= 256 {
  252. let (hits, misses) = crate::shader_cache::counts();
  253. tracing::info!(hits, misses, "shaders from the cache and translated so far");
  254. }
  255. }
  256. #[cfg(all(windows, feature = "diagnostics"))]
  257. if crate::capture::listed(frame) {
  258. crate::capture::dump_targets(frame);
  259. }
  260. #[cfg(windows)]
  261. if planes > 0
  262. // SAFETY: the title passes `planes` plane descriptions.
  263. && let Some(plane) = unsafe { plane_parameters.as_ref() }
  264. && plane.count > 0
  265. && !plane.resources.is_null()
  266. // SAFETY: the plane lists `count` resources.
  267. && let resource = unsafe { *plane.resources }
  268. && let Some(texture) = crate::resource::host_resource(resource)
  269. && let Some(host) = crate::host::host()
  270. {
  271. const COPY_SOURCE: u32 = 0x800;
  272. let state = crate::resource::host_transition(resource, COPY_SOURCE)
  273. .map_or(COPY_SOURCE, |(_, before)| before);
  274. let shown = host.present(texture, state, frame);
  275. crate::resource::host_transition(resource, state);
  276. #[cfg(feature = "diagnostics")]
  277. blinks(frame, resource, state, shown);
  278. #[cfg(not(feature = "diagnostics"))]
  279. let _ = shown;
  280. }
  281. #[cfg(not(windows))]
  282. let _ = (planes, plane_parameters);
  283. S_OK
  284. }
  285. /// Diagnostics: logs a presented frame that is black after one that was
  286. /// not, with what was presented and how many draws ran since.
  287. #[cfg(all(windows, feature = "diagnostics"))]
  288. fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) {
  289. static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0));
  290. let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
  291. let drawn = crate::draw::drawn();
  292. let black = shown.unwrap_or(false);
  293. let draws = crate::draw::take_frame();
  294. if black && !last.0 {
  295. last.2 += 1;
  296. tracing::warn!(
  297. frame,
  298. resource = ?resource,
  299. state = format_args!("{state:#x}"),
  300. draws = drawn - last.1,
  301. copied = shown.is_some(),
  302. black_frames = last.2,
  303. levels = ?crate::capture::recent_levels(),
  304. "a black frame after a frame that was not"
  305. );
  306. for d in draws {
  307. tracing::warn!("black frame {frame}: {d}");
  308. }
  309. AFTER.store(frame + 6, Ordering::Relaxed);
  310. }
  311. // Six frames on: the levels around it (a fade or a single drop).
  312. static AFTER: AtomicU64 = AtomicU64::new(0);
  313. if AFTER.load(Ordering::Relaxed) == frame {
  314. tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame");
  315. }
  316. *last = (black, drawn, last.2);
  317. }
  318. /// A run of destination pages: how they are mapped (0 pool pages from
  319. /// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are)
  320. /// and how many.
  321. #[repr(C)]
  322. pub(crate) struct PageRange {
  323. kind: u32,
  324. start: u32,
  325. count: u32,
  326. }
  327. /// The ranges mapped from a destination address on.
  328. #[repr(C)]
  329. pub(crate) struct PageBatch {
  330. destination: u64,
  331. count: u32,
  332. ranges: *const PageRange,
  333. }
  334. /// Bytes per mapped page.
  335. const PAGE: u64 = 64 << 10;
  336. /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps
  337. /// pages of a pool (memory the title mapped physical pages into) at the
  338. /// batches' addresses. Grand Theft Auto VI streams textures into pool pages
  339. /// and maps them into its tiled heap this way (title+0xf2c470, ranges of
  340. /// one constant page or of unmapped pages). Done at once: every earlier
  341. /// submission has run.
  342. extern "system" fn copy_page_mappings(
  343. _: This,
  344. count: u32,
  345. batches: *const PageBatch,
  346. pool: u64,
  347. pool_pages: u32,
  348. _flags: u32,
  349. ) -> HRESULT {
  350. let Some(map) = crate::resource::page_mapper() else {
  351. return E_INVALIDARG;
  352. };
  353. if batches.is_null() && count > 0 {
  354. return E_INVALIDARG;
  355. }
  356. let batches = (count > 0).then(|| {
  357. // SAFETY: the title passes `count` batches.
  358. unsafe { std::slice::from_raw_parts(batches, count as usize) }
  359. });
  360. let mut ok = true;
  361. for b in batches.into_iter().flatten() {
  362. if b.ranges.is_null() {
  363. continue;
  364. }
  365. // SAFETY: each batch holds `count` ranges.
  366. let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
  367. let mut at = b.destination;
  368. for r in ranges {
  369. let len = u64::from(r.count) * PAGE;
  370. let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages);
  371. let source = pool + u64::from(r.start) * PAGE;
  372. ok &= match r.kind {
  373. 0 if inside(r.count) => map(at, source, len),
  374. 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)),
  375. 2 => map(at, 0, len),
  376. 3 => true,
  377. _ => false,
  378. };
  379. at += len;
  380. }
  381. }
  382. if !ok {
  383. static ONCE: std::sync::Once = std::sync::Once::new();
  384. ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
  385. }
  386. S_OK
  387. }
  388. extern "system" fn desc(this: This, out: *mut QueueDesc) {
  389. if !out.is_null() {
  390. // SAFETY: checked non-null; the title passes room for a description.
  391. unsafe { out.write(queue(this).desc) };
  392. }
  393. }
  394. /// The queue methods by their slot in older titles' queues (the 2020-era
  395. /// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC,
  396. /// then console ones).
  397. const METHODS: [(usize, *const ()); 15] = [
  398. (0, query as *const ()),
  399. (2, release as *const ()),
  400. (7, object::parent_device as *const ()), // 0x38
  401. (10, execute as *const ()), // 0x50
  402. (11, marker as *const ()), // 0x58 set marker
  403. (12, marker as *const ()), // 0x60 begin event
  404. (13, marker as *const ()), // 0x68 end event
  405. (14, signal as *const ()), // 0x70
  406. (15, wait as *const ()), // 0x78
  407. (16, timestamp_frequency as *const ()), // 0x80
  408. (26, desc as *const ()), // 0xd0
  409. (29, copy_page_mappings as *const ()), // 0xe8 page mapping batch
  410. (30, present as *const ()), // 0xf0
  411. (33, execute_x as *const ()), // 0x108
  412. (32, signal2_x as *const ()), // 0x100
  413. ];
  414. /// Newer titles' queues have two more methods before Signal, which moved
  415. /// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as
  416. /// starting exactly at 0x70, the methods before it kept in place).
  417. /// Inferred from Grand Theft Auto VI's calls: Signal 0x80 `(fence,
  418. /// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume
  419. /// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count,
  420. /// lists, token, flags)` (title+0x24821dd).
  421. const fn newer_slot(slot: usize) -> usize {
  422. if slot >= 14 { slot + 2 } else { slot }
  423. }
  424. const fn queue_table(newer: bool) -> [*const (); 36] {
  425. let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>());
  426. let mut i = 0;
  427. while i < METHODS.len() {
  428. let (slot, method) = METHODS[i];
  429. f[if newer { newer_slot(slot) } else { slot }] = method;
  430. i += 1;
  431. }
  432. f
  433. }
  434. static FUNCTIONS: Table<36> = Table(queue_table(false));
  435. static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true));
  436. #[cfg(test)]
  437. mod tests {
  438. use super::*;
  439. use crate::object::slot;
  440. /// Where a queue's signal is: newer layouts have it two slots later.
  441. /// Another test may switch layouts while this one runs, so the queue's
  442. /// own table decides.
  443. fn signal_slot(q: This) -> usize {
  444. // SAFETY: one of our queues; its first field is the table.
  445. let table = unsafe { *q.cast::<*const *const ()>() };
  446. if table == NEWER_FUNCTIONS.0.as_ptr() {
  447. 0x80
  448. } else {
  449. 0x70
  450. }
  451. }
  452. #[test]
  453. fn queue_signals_complete_at_once() {
  454. let null = std::ptr::null();
  455. let desc = QueueDesc {
  456. kind: 0,
  457. priority: 0,
  458. flags: 0,
  459. nodes: 0,
  460. };
  461. let mut q = null;
  462. assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
  463. // SAFETY: the title reads the type at +0x10.
  464. assert_eq!(unsafe { q.cast::<u8>().add(0x10).cast::<u32>().read() }, 0);
  465. let mut fence = null;
  466. let fence_iid = &crate::fence::FENCE_IIDS[0];
  467. assert_eq!(
  468. crate::fence::create(null, 0, 0, fence_iid, &mut fence),
  469. S_OK
  470. );
  471. let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q));
  472. assert_eq!(signal(q, fence, 7), S_OK);
  473. assert_eq!(
  474. slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
  475. 7
  476. );
  477. assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
  478. }
  479. /// Grand Theft Auto VI's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`.
  480. #[test]
  481. fn console_queues_are_created_as_on_pc() {
  482. let null = std::ptr::null();
  483. let desc = QueueDescX {
  484. kind: 2,
  485. flags: 0,
  486. engine_or_pipe: 1,
  487. queue: 0,
  488. };
  489. let mut q = null;
  490. assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
  491. assert_eq!(queue(q).desc.kind, 2);
  492. let none = std::ptr::null();
  493. assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG);
  494. }
  495. #[test]
  496. fn newer_queues_have_their_methods_two_slots_later() {
  497. let (old, new) = (queue_table(false), queue_table(true));
  498. assert_eq!(old[10], new[10]); // submission stays at 0x50
  499. assert_eq!(old[14], new[16]); // signal 0x70 → 0x80
  500. assert_eq!(old[30], new[32]); // present 0xf0 → 0x100
  501. assert_eq!(new[35], execute_x as *const ()); // 0x118
  502. }
  503. #[test]
  504. fn timestamps_and_values_are_written() {
  505. let mut at = [0u64; 2];
  506. Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4);
  507. assert_eq!(at[0], 2);
  508. Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
  509. let first = at[1];
  510. std::thread::sleep(std::time::Duration::from_millis(2));
  511. Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
  512. assert!(at[1] > first);
  513. }
  514. }