queue.rs 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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. /// What the queue was given after a wait for a fence that had not been
  33. /// reached, in order; it runs when the fence gets there.
  34. #[cfg(windows)]
  35. held: std::sync::Mutex<Vec<Held>>,
  36. }
  37. const _: () = assert!(std::mem::offset_of!(Queue, kind) == 0x10);
  38. /// One thing a waiting queue holds back.
  39. #[cfg(windows)]
  40. enum Held {
  41. /// The queue waits for the fence (its address) to reach the value.
  42. Wait(usize, u64),
  43. /// A list of the next submission waits for a memory value.
  44. Value(crate::list::ValueWait),
  45. /// A submission: the lists' host sides, taken from the title's lists
  46. /// (which it may reset meanwhile), and the order they run in.
  47. Run(Vec<crate::list::Detached>, Vec<usize>),
  48. /// A signal of the queue's, due after what it holds before it.
  49. Signal(usize, u64),
  50. }
  51. /// The queues that hold something (their addresses).
  52. #[cfg(windows)]
  53. static WAITING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  54. #[cfg(windows)]
  55. fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
  56. mutex.lock().unwrap_or_else(|e| e.into_inner())
  57. }
  58. /// Whether queues wait for fences. `VICTORY_QUEUE_WAIT=0`: they do not,
  59. /// and every submission runs when it is made (as before).
  60. #[cfg(windows)]
  61. fn waits() -> bool {
  62. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  63. *ON.get_or_init(|| std::env::var_os("VICTORY_QUEUE_WAIT").is_none_or(|v| v != "0"))
  64. }
  65. /// Whether a submission is held list by list: the lists before the first
  66. /// one whose wait for a memory value is not met run at once, and each list
  67. /// that waits is held with the lists after it, behind its own waits.
  68. /// Holding a submission whole made the title's queues wait for each other:
  69. /// a graphics submission was held for a value a compute list writes, and
  70. /// that compute list for a value an earlier list of the same graphics
  71. /// submission writes. Nothing moved until the present forced it, and the
  72. /// title reached its present only after waiting about 2.5 s, every frame
  73. /// (runs 27-30: 2.4-2.9 s from the last submission to the present call,
  74. /// 13-32 ms before waits were honoured; the frame's main graphics
  75. /// submissions, 88 lists, ran forced, the compute lists before them).
  76. /// On by default; `VICTORY_SPLIT_WAITS=0` holds whole submissions, as
  77. /// before.
  78. #[cfg(windows)]
  79. fn split() -> bool {
  80. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  81. *ON.get_or_init(|| std::env::var_os("VICTORY_SPLIT_WAITS").is_none_or(|v| v != "0"))
  82. }
  83. /// Whether a list is cut into host lists at its waits for memory values
  84. /// (`crate::list::cut`), and a queue runs a submission part by part: it
  85. /// stands at each wait until the value is in memory, with everything
  86. /// recorded before the wait run and its bottom-of-pipe writes done, as on
  87. /// the console. Held list by list ([`split`]) a wait still held its whole
  88. /// list: the title's lists are chains of jobs, each behind a wait for a
  89. /// value another queue's list writes in the middle of its own chain
  90. /// (frame 858 of run 33: a compute list of 433 commands with 13 waits;
  91. /// graphics lists of the form "341 dispatches, wait, draws"), so two lists
  92. /// each waited for a write behind the other's wait and only the present
  93. /// moved them, in the wrong order.
  94. /// On by default where waits are honoured list by list;
  95. /// `VICTORY_CUT_WAITS=0` holds whole lists, as before.
  96. #[cfg(windows)]
  97. pub(crate) fn cuts() -> bool {
  98. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  99. waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0"))
  100. }
  101. /// Whether a present runs what queues still hold (on by default: a wait
  102. /// is not kept across frames). `VICTORY_WAIT_FORCE=0` keeps it held: for
  103. /// finding out whether the title's waits reach across its presents; a
  104. /// wait nothing ever meets then stops the title for good.
  105. #[cfg(windows)]
  106. fn forces() -> bool {
  107. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  108. *ON.get_or_init(|| std::env::var_os("VICTORY_WAIT_FORCE").is_none_or(|v| v != "0"))
  109. }
  110. /// A submission to a queue whose lists are cut at their waits ([`cuts`]).
  111. /// The lists before the first one that waits run at once if the queue
  112. /// holds nothing; the rest goes behind what the queue holds, part by part
  113. /// (`crate::list::detach_parts`): the waits of a part, then its host
  114. /// lists. [`release_held`] runs the queue's line as far as the values are
  115. /// there, now and whenever a submission has run.
  116. #[cfg(windows)]
  117. fn submit_cut(this: This, lists: &[This]) {
  118. let Some(host) = crate::host::host() else {
  119. return;
  120. };
  121. let first = if lock(&queue(this).held).is_empty() {
  122. lists
  123. .iter()
  124. .position(|&l| crate::list::cut_list(l))
  125. .unwrap_or(lists.len())
  126. } else {
  127. 0
  128. };
  129. #[cfg(feature = "diagnostics")]
  130. crate::capture::op(this as usize, || {
  131. let named: Vec<String> = lists
  132. .iter()
  133. .map(|&l| match crate::list::host_list(l) {
  134. Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
  135. None => format!("title {l:?}"),
  136. })
  137. .collect();
  138. format!(
  139. "SUBMIT queue kind {:?} held {} lists {named:?} (the first {first} run at once, the rest part by part)",
  140. Some(queue(this).kind),
  141. first < lists.len()
  142. )
  143. });
  144. if first > 0 && crate::host::late() {
  145. // Sent to the card and not waited for: their host sides are taken
  146. // from the title's lists (which it may reset before they have run)
  147. // and come back, with their tables' slots, when they are settled.
  148. let (taken, order) = crate::list::detach(&lists[..first]);
  149. host.execute_late(taken, order);
  150. } else if first > 0 {
  151. let now: Vec<_> = lists[..first]
  152. .iter()
  153. .filter_map(|&l| crate::list::host_list(l))
  154. .collect();
  155. host.execute(&now);
  156. // They have run: their descriptor tables' slots are free again, as
  157. // on the path without cuts ([`execute`]). This path replaced that
  158. // one without the call, so the lists that run at once kept their
  159. // slots until the title's reset and the ring ran out as before
  160. // (run 45: 3,143 of 15,942 tables refused in one frame).
  161. crate::list::tables_done(&lists[..first]);
  162. }
  163. if first < lists.len() {
  164. let parts = crate::list::detach_parts(&lists[first..]);
  165. static SEEN: AtomicU64 = AtomicU64::new(0);
  166. if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
  167. tracing::info!(
  168. kind = queue(this).kind,
  169. lists = lists.len(),
  170. run_at_once = first,
  171. parts = parts.len(),
  172. waits = parts.iter().map(|p| p.0.len()).sum::<usize>(),
  173. "a submission is given to its queue part by part (its lists wait for memory values)"
  174. );
  175. }
  176. {
  177. let mut held = lock(&queue(this).held);
  178. for (waits, taken, order) in parts {
  179. held.extend(waits.into_iter().map(Held::Value));
  180. held.push(Held::Run(taken, order));
  181. }
  182. }
  183. let mut waiting = lock(&WAITING);
  184. if !waiting.contains(&(this as usize)) {
  185. waiting.push(this as usize);
  186. }
  187. }
  188. // What ran may be what another queue waits for, and what was just
  189. // given to the queue may be free to run already.
  190. release_held(false);
  191. }
  192. /// A submission to a queue that honours waits, list by list ([`split`]).
  193. /// shortcut: a wait still holds its whole list, not only the commands
  194. /// after it; and lists named twice among those held stay in one piece.
  195. #[cfg(windows)]
  196. fn submit_split(this: This, lists: &[This]) {
  197. let Some(host) = crate::host::host() else {
  198. return;
  199. };
  200. let by = crate::list::waits_by_list(lists);
  201. // Behind what the queue already holds, nothing runs now.
  202. let cut = if lock(&queue(this).held).is_empty() {
  203. (0..lists.len())
  204. .find(|&i| by[i].iter().any(|w| !w.met()))
  205. .unwrap_or(lists.len())
  206. } else {
  207. 0
  208. };
  209. #[cfg(feature = "diagnostics")]
  210. crate::capture::op(this as usize, || {
  211. let named: Vec<String> = lists
  212. .iter()
  213. .map(|&l| match crate::list::host_list(l) {
  214. Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
  215. None => format!("title {l:?}"),
  216. })
  217. .collect();
  218. format!(
  219. "SUBMIT queue kind {:?} held {} lists {named:?} (the first {cut} run at once)",
  220. Some(queue(this).kind),
  221. cut < lists.len()
  222. )
  223. });
  224. if cut > 0 {
  225. let now: Vec<_> = lists[..cut]
  226. .iter()
  227. .filter_map(|&l| crate::list::host_list(l))
  228. .collect();
  229. host.execute(&now);
  230. }
  231. if cut < lists.len() {
  232. static SEEN: AtomicU64 = AtomicU64::new(0);
  233. if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
  234. tracing::info!(
  235. kind = queue(this).kind,
  236. lists = lists.len(),
  237. run_at_once = cut,
  238. waits = ?by[cut],
  239. "lists of a submission are held for a memory value"
  240. );
  241. }
  242. let rest = &lists[cut..];
  243. // A list's host side can be taken once.
  244. let twice = rest.iter().enumerate().any(|(i, l)| rest[..i].contains(l));
  245. let mut pieces: Vec<Held> = Vec::new();
  246. let mut from = cut;
  247. while from < lists.len() {
  248. // Up to the next list that waits for anything (met or not: it
  249. // is looked at again when its turn comes).
  250. let to = if twice {
  251. lists.len()
  252. } else {
  253. (from + 1..lists.len())
  254. .find(|&i| !by[i].is_empty())
  255. .unwrap_or(lists.len())
  256. };
  257. let waits: Vec<crate::list::ValueWait> = by[from..to].concat();
  258. pieces.extend(waits.into_iter().map(Held::Value));
  259. let (taken, order) = crate::list::detach(&lists[from..to]);
  260. pieces.push(Held::Run(taken, order));
  261. from = to;
  262. }
  263. lock(&queue(this).held).extend(pieces);
  264. let mut waiting = lock(&WAITING);
  265. if !waiting.contains(&(this as usize)) {
  266. waiting.push(this as usize);
  267. }
  268. }
  269. // What ran may be what another queue waits for, and what was just held
  270. // may be free to run already.
  271. release_held(false);
  272. }
  273. /// Adds `what()` to what the queue holds, if it holds anything (it waits
  274. /// for a fence): whether it was added.
  275. #[cfg(windows)]
  276. fn hold(this: This, what: impl FnOnce() -> Held) -> bool {
  277. if this.is_null() {
  278. return false;
  279. }
  280. let mut held = lock(&queue(this).held);
  281. if held.is_empty() {
  282. return false;
  283. }
  284. held.push(what());
  285. true
  286. }
  287. /// Runs what waiting queues hold as far as their fences have been reached
  288. /// (`all`: all of it), each queue's in the order it was given. Called
  289. /// where a fence may have moved: after a signal and after a submission (a
  290. /// list's bottom-of-pipe write may be into a fence), never from inside
  291. /// one.
  292. #[cfg(windows)]
  293. pub(crate) fn release_held(all: bool) {
  294. // One caller at a time, so a queue's submissions keep their order.
  295. static RELEASING: std::sync::Mutex<()> = std::sync::Mutex::new(());
  296. if lock(&WAITING).is_empty() {
  297. return;
  298. }
  299. let _one = lock(&RELEASING);
  300. loop {
  301. let queues = lock(&WAITING).clone();
  302. let mut moved = false;
  303. for q in queues {
  304. // SAFETY: a live queue: one released is taken off the list.
  305. let held = unsafe { &(*(q as *const Queue)).held };
  306. let mut held = lock(held);
  307. loop {
  308. match held.first() {
  309. None => break,
  310. Some(&Held::Wait(fence, value))
  311. if !all && crate::fence::completed(fence as This) < value =>
  312. {
  313. break;
  314. }
  315. Some(Held::Value(wait)) if !all && !value_met(wait) => break,
  316. Some(_) => {}
  317. }
  318. match held.remove(0) {
  319. Held::Wait(..) => {}
  320. Held::Value(wait) => {
  321. // Passed at a present without being met: what the
  322. // queue stood at.
  323. if all && !value_met(&wait) {
  324. static SEEN: AtomicU64 = AtomicU64::new(0);
  325. if SEEN.fetch_add(1, Ordering::Relaxed) < 16 {
  326. tracing::warn!(
  327. queue = format_args!("{q:#x}"),
  328. ?wait,
  329. "a wait for a memory value was not met at a present: the queue runs on"
  330. );
  331. }
  332. }
  333. }
  334. Held::Run(lists, order) => {
  335. #[cfg(feature = "diagnostics")]
  336. crate::capture::op(q, || {
  337. format!(
  338. "RUN held submission of {} lists (forced {all})",
  339. order.len()
  340. )
  341. });
  342. // Diagnostics: the part behind this one stands at
  343. // waits that are met already, so the two could have
  344. // been one host submission (one wait for the card,
  345. // each range shaders write compared once).
  346. #[cfg(feature = "diagnostics")]
  347. {
  348. let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count();
  349. if waits > 0
  350. && matches!(held.get(waits), Some(Held::Run(..)))
  351. && held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met()))
  352. {
  353. crate::copystat::add(crate::copystat::C::PartsTogether, 1);
  354. }
  355. }
  356. if crate::host::late()
  357. && let Some(host) = crate::host::host()
  358. {
  359. // Not waited for: the host keeps the lists
  360. // until they are settled.
  361. host.execute_late(lists, order);
  362. } else {
  363. let ran = {
  364. let runs: Vec<&crate::host::HostList> =
  365. order.iter().map(|&i| lists[i].host()).collect();
  366. match crate::host::host() {
  367. Some(host) => {
  368. host.execute(&runs);
  369. true
  370. }
  371. None => false,
  372. }
  373. };
  374. // They have run: their host lists are used again.
  375. if ran {
  376. crate::list::recycle(lists, &order);
  377. }
  378. }
  379. if all {
  380. #[cfg(feature = "diagnostics")]
  381. crate::copystat::add(crate::copystat::C::Forced, 1);
  382. static ONCE: AtomicBool = AtomicBool::new(false);
  383. if !ONCE.swap(true, Ordering::Relaxed) {
  384. tracing::warn!(
  385. "a queue still held a submission at a present: its fence was not reached"
  386. );
  387. }
  388. }
  389. }
  390. // Behind what was sent to the card and not waited
  391. // for, if anything was.
  392. Held::Signal(fence, value) => {
  393. if !crate::host::late_signal(fence, value) {
  394. crate::fence::set(fence as This, value);
  395. }
  396. }
  397. }
  398. moved = true;
  399. }
  400. if held.is_empty() {
  401. lock(&WAITING).retain(|&w| w != q);
  402. }
  403. }
  404. if !moved {
  405. break;
  406. }
  407. }
  408. }
  409. /// Whether a queue may pass `wait`: memory holds the value, or, with
  410. /// submissions sent to the card without a wait (`crate::host::late`), it
  411. /// will once those in the air have run.
  412. #[cfg(windows)]
  413. fn value_met(wait: &crate::list::ValueWait) -> bool {
  414. wait.met() || (crate::host::late() && crate::host::late_met(wait))
  415. }
  416. fn queue<'a>(this: This) -> &'a Queue {
  417. // SAFETY: called from queue methods only.
  418. unsafe { &*this.cast::<Queue>() }
  419. }
  420. pub(crate) extern "system" fn create(
  421. _: This,
  422. desc: *const QueueDesc,
  423. iid: *const Iid,
  424. out: *mut This,
  425. ) -> HRESULT {
  426. // SAFETY: the title passes a description (null is tolerated).
  427. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  428. return E_INVALIDARG;
  429. };
  430. tracing::debug!(?desc, "command queue");
  431. let queue = Box::new(Queue {
  432. object: if crate::device::newer() {
  433. Object::new(&NEWER_FUNCTIONS)
  434. } else {
  435. Object::new(&FUNCTIONS)
  436. },
  437. kind: desc.kind,
  438. desc,
  439. #[cfg(windows)]
  440. held: Default::default(),
  441. });
  442. object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
  443. }
  444. /// The console's queue description: an engine or pipe and a queue on it
  445. /// in place of PC's priority and node mask.
  446. #[repr(C)]
  447. #[derive(Debug, Clone, Copy)]
  448. pub(crate) struct QueueDescX {
  449. kind: u32,
  450. flags: u32,
  451. engine_or_pipe: u32,
  452. queue: u32,
  453. }
  454. /// Device method `CreateCommandQueueX`. The host picks engines itself, so
  455. /// the queue is created as on PC.
  456. pub(crate) extern "system" fn create_x(
  457. this: This,
  458. desc: *const QueueDescX,
  459. iid: *const Iid,
  460. out: *mut This,
  461. ) -> HRESULT {
  462. // SAFETY: the title passes a description (null is tolerated).
  463. let Some(&x) = (unsafe { desc.as_ref() }) else {
  464. return E_INVALIDARG;
  465. };
  466. tracing::debug!(desc = ?x, "console command queue");
  467. let desc = QueueDesc {
  468. kind: x.kind,
  469. priority: 0,
  470. flags: x.flags,
  471. nodes: 1,
  472. };
  473. create(this, &desc, iid, out)
  474. }
  475. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  476. object::answer(
  477. QUEUE,
  478. iid,
  479. object::is(iid, &QUEUE_IIDS).then_some(this),
  480. out,
  481. )
  482. }
  483. extern "system" fn release(this: This) -> u32 {
  484. let left = object::release_boxed::<Queue>(this);
  485. #[cfg(windows)]
  486. if left == 0 {
  487. lock(&WAITING).retain(|&q| q != this as usize);
  488. }
  489. left
  490. }
  491. /// Runs the lists' host lists and waits for them (decision 0007). A queue
  492. /// that waits for a fence keeps them until the fence is reached.
  493. extern "system" fn execute(this: This, count: u32, lists: *const This) {
  494. if lists.is_null() {
  495. return;
  496. }
  497. #[cfg(windows)]
  498. if let Some(host) = crate::host::host() {
  499. // SAFETY: the title passes `count` lists.
  500. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
  501. if cuts() && !this.is_null() {
  502. submit_cut(this, lists);
  503. return;
  504. }
  505. if waits() && split() && !this.is_null() {
  506. submit_split(this, lists);
  507. return;
  508. }
  509. // A list that waits for a memory value not there yet: the queue
  510. // holds the submission, as it does behind a fence.
  511. if waits() && !this.is_null() {
  512. let unmet = crate::list::unmet_waits(lists);
  513. if !unmet.is_empty() {
  514. static SEEN: AtomicU64 = AtomicU64::new(0);
  515. if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
  516. tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value");
  517. }
  518. lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value));
  519. let mut waiting = lock(&WAITING);
  520. if !waiting.contains(&(this as usize)) {
  521. waiting.push(this as usize);
  522. }
  523. }
  524. }
  525. let kept = hold(this, || {
  526. let (taken, order) = crate::list::detach(lists);
  527. Held::Run(taken, order)
  528. });
  529. // Diagnostics: the order submissions are made in, next to the
  530. // commands of the frame's `ops` file (which are in recording order).
  531. #[cfg(feature = "diagnostics")]
  532. crate::capture::op(this as usize, || {
  533. let kind = (!this.is_null()).then(|| queue(this).kind);
  534. // The lists as the frame's other lines name them (their host sides).
  535. let named: Vec<String> = lists
  536. .iter()
  537. .map(|&l| match crate::list::host_list(l) {
  538. Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
  539. None => format!("title {l:?}"),
  540. })
  541. .collect();
  542. format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}")
  543. });
  544. if kept {
  545. return;
  546. }
  547. let host_lists: Vec<_> = lists
  548. .iter()
  549. .filter_map(|&l| crate::list::host_list(l))
  550. .collect();
  551. host.execute(&host_lists);
  552. crate::list::tables_done(lists);
  553. // What the lists wrote at the bottom of the pipe may be a fence
  554. // another queue waits for.
  555. release_held(false);
  556. return;
  557. }
  558. let _ = this;
  559. static ONCE: AtomicBool = AtomicBool::new(false);
  560. if !ONCE.swap(true, Ordering::Relaxed) {
  561. tracing::warn!(count, "command lists submitted; no host GPU runs them");
  562. }
  563. }
  564. /// The start of a present plane: frame token, then the plane's resources.
  565. #[repr(C)]
  566. pub(crate) struct Plane {
  567. token: u64,
  568. count: u32,
  569. resources: *const This,
  570. }
  571. /// Submission tagged with the frame it belongs to `(count, lists, frame
  572. /// token, flags)`; frames are paced elsewhere, so it runs as a plain one.
  573. extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) {
  574. execute(this, count, lists);
  575. }
  576. /// Signal with sync settings for the top and bottom of the pipe; our
  577. /// submissions are complete when they return, so it signals at once.
  578. extern "system" fn signal2_x(
  579. this: This,
  580. fence: This,
  581. value: u64,
  582. _bottom: *const u8,
  583. _top: *const u8,
  584. ) -> HRESULT {
  585. signal(this, fence, value)
  586. }
  587. /// Markers and events only matter to profilers.
  588. extern "system" fn marker(_: This) {}
  589. extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT {
  590. if fence.is_null() {
  591. return E_INVALIDARG;
  592. }
  593. // A queue that waits signals after what it holds.
  594. #[cfg(windows)]
  595. if hold(this, || Held::Signal(fence as usize, value)) {
  596. return S_OK;
  597. }
  598. // Behind the submissions sent to the card and not waited for: the
  599. // fence is set when they are settled.
  600. #[cfg(windows)]
  601. if crate::host::late_signal(fence as usize, value) {
  602. return S_OK;
  603. }
  604. let _ = this;
  605. crate::fence::signal(fence, value)
  606. }
  607. /// From here on the queue runs nothing it is given until `fence` reaches
  608. /// `value`: how the console orders work between queues (the title's
  609. /// compute queue waits for the depth the graphics queue draws). Our
  610. /// submissions run when they are made, so a wait for a value already
  611. /// reached is nothing; otherwise what the queue is given next is held
  612. /// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the
  613. /// fence there.
  614. extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
  615. if fence.is_null() {
  616. return E_INVALIDARG;
  617. }
  618. #[cfg(windows)]
  619. if !this.is_null() {
  620. let now = crate::fence::completed(fence);
  621. // Whether the title uses this at all (the first calls).
  622. {
  623. static CALLS: AtomicU64 = AtomicU64::new(0);
  624. if CALLS.fetch_add(1, Ordering::Relaxed) < 8 {
  625. tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence");
  626. }
  627. }
  628. #[cfg(feature = "diagnostics")]
  629. crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind));
  630. let behind = {
  631. let mut held = lock(&queue(this).held);
  632. let behind = !held.is_empty() || now < value;
  633. if behind && waits() {
  634. held.push(Held::Wait(fence as usize, value));
  635. }
  636. behind
  637. };
  638. if behind {
  639. static SEEN: AtomicU64 = AtomicU64::new(0);
  640. if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
  641. tracing::info!(
  642. kind = queue(this).kind,
  643. now,
  644. value,
  645. held = waits(),
  646. "a queue waits for a fence not reached yet"
  647. );
  648. }
  649. }
  650. if behind && waits() {
  651. {
  652. let mut waiting = lock(&WAITING);
  653. if !waiting.contains(&(this as usize)) {
  654. waiting.push(this as usize);
  655. }
  656. }
  657. // The fence may have got there meanwhile.
  658. release_held(false);
  659. }
  660. }
  661. let _ = (this, value);
  662. S_OK
  663. }
  664. /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
  665. extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
  666. if out.is_null() {
  667. return E_INVALIDARG;
  668. }
  669. // SAFETY: checked non-null.
  670. unsafe { out.write(TIMESTAMP_FREQUENCY) };
  671. S_OK
  672. }
  673. const TIMESTAMP_FREQUENCY: u64 = 100_000_000;
  674. /// What a list's bottom-of-pipe write stores when the list has run.
  675. #[derive(Debug, Clone, Copy)]
  676. pub(crate) enum Written {
  677. Value(u64),
  678. /// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the
  679. /// process started (our GPU work is done on the CPU's timeline).
  680. GpuTimestamp,
  681. /// The CPU's performance counter.
  682. SystemTimestamp,
  683. }
  684. impl Written {
  685. /// Stores the low `bytes` (4 or 8) of the value at `at`.
  686. pub(crate) fn write(self, at: *mut u8, bytes: usize) {
  687. let value = match self {
  688. Written::Value(v) => v,
  689. Written::GpuTimestamp => {
  690. static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
  691. let elapsed = START.get_or_init(std::time::Instant::now).elapsed();
  692. let now = (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64;
  693. #[cfg(all(windows, feature = "diagnostics"))]
  694. crate::host::spans::stamped(at as usize, now);
  695. as_loaded(now, at as usize, gpu_load())
  696. }
  697. Written::SystemTimestamp => system_timestamp(),
  698. };
  699. // SAFETY: the title names writable GPU memory (unified with ours).
  700. unsafe {
  701. if bytes == 4 {
  702. at.cast::<u32>().write_unaligned(value as u32);
  703. } else {
  704. at.cast::<u64>().write_unaligned(value);
  705. }
  706. }
  707. }
  708. }
  709. /// What the title's GPU time is made to look like, in ticks
  710. /// (`VICTORY_GPU_LOAD_MS`; unset: as it is).
  711. ///
  712. /// The title asks for four GPU timestamps a frame, in pairs of 16 bytes, the
  713. /// start in the second eight and the end in the first. All of them are written
  714. /// when the frame's last submissions land, within microseconds, so every pair
  715. /// says the card did nothing.
  716. fn gpu_load() -> u64 {
  717. static LOAD: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  718. *LOAD.get_or_init(|| {
  719. let ms = std::env::var("VICTORY_GPU_LOAD_MS").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0);
  720. ms * (TIMESTAMP_FREQUENCY / 1000)
  721. })
  722. }
  723. /// The timestamp written at `at` when the clock says `now`, if a pair's start
  724. /// is to lie `load` ticks before its end.
  725. fn as_loaded(now: u64, at: usize, load: u64) -> u64 {
  726. if at & 8 != 0 {
  727. now.saturating_sub(load).max(1)
  728. } else {
  729. now
  730. }
  731. }
  732. fn system_timestamp() -> u64 {
  733. #[cfg(windows)]
  734. {
  735. let mut count = 0;
  736. // SAFETY: a valid out pointer.
  737. unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) };
  738. count as u64
  739. }
  740. #[cfg(not(windows))]
  741. 0
  742. }
  743. /// Frames presented so far.
  744. static FRAMES: AtomicU64 = AtomicU64::new(0);
  745. #[cfg(feature = "diagnostics")]
  746. pub(crate) fn presented() -> u64 {
  747. FRAMES.load(Ordering::Relaxed)
  748. }
  749. /// Shows the first plane's first resource in our window.
  750. ///
  751. /// shortcut: one plane, no scaling or placement, the source expected in
  752. /// the common state.
  753. extern "system" fn present(
  754. _: This,
  755. planes: u32,
  756. plane_parameters: *const Plane,
  757. _parameters: *const u8,
  758. ) -> HRESULT {
  759. #[cfg(all(windows, feature = "diagnostics"))]
  760. crate::copystat::present_begins();
  761. // Submissions sent to the card and not waited for are settled first,
  762. // and what that frees runs in its own order, before anything is forced.
  763. #[cfg(windows)]
  764. if crate::host::late() && !crate::host::late_free_present() {
  765. crate::host::settle_for_present();
  766. release_held(false);
  767. crate::host::settle_for_present();
  768. } else if crate::host::late() {
  769. // The present is sent ahead too: what waits for a value a flight
  770. // will write runs behind that flight, and nothing is settled here.
  771. release_held(false);
  772. }
  773. // shortcut: what a queue still holds at a present runs now, whatever
  774. // its fence: a wait is not kept across frames.
  775. #[cfg(windows)]
  776. release_held(forces());
  777. let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
  778. if frame.is_power_of_two() {
  779. let (draws, dispatches) = crate::list::take_counts();
  780. #[cfg(windows)]
  781. let (drawn, dispatched) = {
  782. static DRAWN: AtomicU64 = AtomicU64::new(0);
  783. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  784. let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed);
  785. (
  786. since(&DRAWN, crate::draw::drawn()),
  787. since(&DISPATCHED, crate::draw::dispatched()),
  788. )
  789. };
  790. #[cfg(not(windows))]
  791. let (drawn, dispatched) = (0, 0);
  792. tracing::info!(
  793. frame,
  794. draws,
  795. drawn,
  796. dispatches,
  797. dispatched,
  798. "frame presented (since the last line: draws and dispatches, and those run on the host)"
  799. );
  800. #[cfg(windows)]
  801. if frame >= 256 {
  802. let (hits, misses) = crate::shader_cache::counts();
  803. tracing::info!(hits, misses, "shaders from the cache and translated so far");
  804. }
  805. }
  806. #[cfg(all(windows, feature = "diagnostics"))]
  807. {
  808. crate::capture::frame_drew(frame, crate::draw::drawn());
  809. if crate::capture::listed(frame) {
  810. crate::capture::dump_targets(frame);
  811. }
  812. }
  813. #[cfg(windows)]
  814. if planes > 0
  815. // SAFETY: the title passes `planes` plane descriptions.
  816. && let Some(plane) = unsafe { plane_parameters.as_ref() }
  817. && plane.count > 0
  818. && !plane.resources.is_null()
  819. // SAFETY: the plane lists `count` resources.
  820. && let resource = unsafe { *plane.resources }
  821. && let Some(texture) = crate::resource::host_resource(resource)
  822. && let Some(host) = crate::host::host()
  823. {
  824. const COPY_SOURCE: u32 = 0x800;
  825. let state = crate::resource::host_transition(resource, COPY_SOURCE)
  826. .map_or(COPY_SOURCE, |(_, before)| before);
  827. let shown = host.present(texture, state, frame);
  828. crate::resource::host_transition(resource, state);
  829. #[cfg(feature = "diagnostics")]
  830. blinks(frame, resource, state, shown);
  831. #[cfg(not(feature = "diagnostics"))]
  832. let _ = shown;
  833. }
  834. #[cfg(not(windows))]
  835. let _ = (planes, plane_parameters);
  836. S_OK
  837. }
  838. /// Diagnostics: logs a presented frame that is black after one that was
  839. /// not, with what was presented and how many draws ran since.
  840. #[cfg(all(windows, feature = "diagnostics"))]
  841. fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) {
  842. static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0));
  843. let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
  844. let drawn = crate::draw::drawn();
  845. let black = shown.unwrap_or(false);
  846. let draws = crate::draw::take_frame();
  847. if black && !last.0 {
  848. last.2 += 1;
  849. tracing::warn!(
  850. frame,
  851. resource = ?resource,
  852. state = format_args!("{state:#x}"),
  853. draws = drawn - last.1,
  854. copied = shown.is_some(),
  855. black_frames = last.2,
  856. levels = ?crate::capture::recent_levels(),
  857. "a black frame after a frame that was not"
  858. );
  859. for d in draws {
  860. tracing::warn!("black frame {frame}: {d}");
  861. }
  862. AFTER.store(frame + 6, Ordering::Relaxed);
  863. }
  864. // Six frames on: the levels around it (a fade or a single drop).
  865. static AFTER: AtomicU64 = AtomicU64::new(0);
  866. if AFTER.load(Ordering::Relaxed) == frame {
  867. tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame");
  868. }
  869. *last = (black, drawn, last.2);
  870. }
  871. /// A run of destination pages: how they are mapped (0 pool pages from
  872. /// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are)
  873. /// and how many.
  874. #[repr(C)]
  875. pub(crate) struct PageRange {
  876. kind: u32,
  877. start: u32,
  878. count: u32,
  879. }
  880. /// The ranges mapped from a destination address on.
  881. #[repr(C)]
  882. pub(crate) struct PageBatch {
  883. destination: u64,
  884. count: u32,
  885. ranges: *const PageRange,
  886. }
  887. /// Bytes per mapped page.
  888. const PAGE: u64 = 64 << 10;
  889. /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps
  890. /// pages of a pool (memory the title mapped physical pages into) at the
  891. /// batches' addresses. The title streams textures into pool pages
  892. /// and maps them into its tiled heap this way (title+0xf2c470, ranges of
  893. /// one constant page or of unmapped pages). Done at once: every earlier
  894. /// submission has run.
  895. extern "system" fn copy_page_mappings(
  896. _: This,
  897. count: u32,
  898. batches: *const PageBatch,
  899. pool: u64,
  900. pool_pages: u32,
  901. _flags: u32,
  902. ) -> HRESULT {
  903. let Some(map) = crate::resource::page_mapper() else {
  904. return E_INVALIDARG;
  905. };
  906. if batches.is_null() && count > 0 {
  907. return E_INVALIDARG;
  908. }
  909. let batches = (count > 0).then(|| {
  910. // SAFETY: the title passes `count` batches.
  911. unsafe { std::slice::from_raw_parts(batches, count as usize) }
  912. });
  913. let mut ok = true;
  914. let many = crate::resource::many_page_mapper();
  915. let mut gathered: Vec<(u64, u64, u64)> = Vec::new();
  916. let mut map = |to: u64, from: u64, len: u64| match many {
  917. Some(_) => {
  918. gathered.push((to, from, len));
  919. true
  920. }
  921. None => map(to, from, len),
  922. };
  923. for b in batches.into_iter().flatten() {
  924. if b.ranges.is_null() {
  925. continue;
  926. }
  927. // SAFETY: each batch holds `count` ranges.
  928. let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
  929. let mut at = b.destination;
  930. for r in ranges {
  931. let len = u64::from(r.count) * PAGE;
  932. let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages);
  933. let source = pool + u64::from(r.start) * PAGE;
  934. ok &= match r.kind {
  935. 0 if inside(r.count) => map(at, source, len),
  936. 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)),
  937. 2 => map(at, 0, len),
  938. 3 => true,
  939. _ => false,
  940. };
  941. at += len;
  942. }
  943. }
  944. if let Some(many) = many {
  945. ok &= many(&gathered);
  946. }
  947. if !ok {
  948. static ONCE: std::sync::Once = std::sync::Once::new();
  949. ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
  950. }
  951. S_OK
  952. }
  953. extern "system" fn desc(this: This, out: *mut QueueDesc) {
  954. if !out.is_null() {
  955. // SAFETY: checked non-null; the title passes room for a description.
  956. unsafe { out.write(queue(this).desc) };
  957. }
  958. }
  959. /// The queue methods by their slot in older titles' queues (the 2020-era
  960. /// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC,
  961. /// then console ones).
  962. const METHODS: [(usize, *const ()); 15] = [
  963. (0, query as *const ()),
  964. (2, release as *const ()),
  965. (7, object::parent_device as *const ()), // 0x38
  966. (10, execute as *const ()), // 0x50
  967. (11, marker as *const ()), // 0x58 set marker
  968. (12, marker as *const ()), // 0x60 begin event
  969. (13, marker as *const ()), // 0x68 end event
  970. (14, signal as *const ()), // 0x70
  971. (15, wait as *const ()), // 0x78
  972. (16, timestamp_frequency as *const ()), // 0x80
  973. (26, desc as *const ()), // 0xd0
  974. (29, copy_page_mappings as *const ()), // 0xe8 page mapping batch
  975. (30, present as *const ()), // 0xf0
  976. (33, execute_x as *const ()), // 0x108
  977. (32, signal2_x as *const ()), // 0x100
  978. ];
  979. /// Newer titles' queues have two more methods before Signal, which moved
  980. /// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as
  981. /// starting exactly at 0x70, the methods before it kept in place).
  982. /// Inferred from the title's calls: Signal 0x80 `(fence,
  983. /// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume
  984. /// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count,
  985. /// lists, token, flags)` (title+0x24821dd).
  986. const fn newer_slot(slot: usize) -> usize {
  987. if slot >= 14 { slot + 2 } else { slot }
  988. }
  989. const fn queue_table(newer: bool) -> [*const (); 36] {
  990. let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>());
  991. let mut i = 0;
  992. while i < METHODS.len() {
  993. let (slot, method) = METHODS[i];
  994. f[if newer { newer_slot(slot) } else { slot }] = method;
  995. i += 1;
  996. }
  997. f
  998. }
  999. static FUNCTIONS: Table<36> = Table(queue_table(false));
  1000. static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true));
  1001. #[cfg(test)]
  1002. mod tests {
  1003. use super::*;
  1004. use crate::object::slot;
  1005. /// Where a queue's signal is: newer layouts have it two slots later.
  1006. /// Another test may switch layouts while this one runs, so the queue's
  1007. /// own table decides.
  1008. fn signal_slot(q: This) -> usize {
  1009. // SAFETY: one of our queues; its first field is the table.
  1010. let table = unsafe { *q.cast::<*const *const ()>() };
  1011. if table == NEWER_FUNCTIONS.0.as_ptr() {
  1012. 0x80
  1013. } else {
  1014. 0x70
  1015. }
  1016. }
  1017. #[test]
  1018. fn queue_signals_complete_at_once() {
  1019. let null = std::ptr::null();
  1020. let desc = QueueDesc {
  1021. kind: 0,
  1022. priority: 0,
  1023. flags: 0,
  1024. nodes: 0,
  1025. };
  1026. let mut q = null;
  1027. assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
  1028. // SAFETY: the title reads the type at +0x10.
  1029. assert_eq!(unsafe { q.cast::<u8>().add(0x10).cast::<u32>().read() }, 0);
  1030. let mut fence = null;
  1031. let fence_iid = &crate::fence::FENCE_IIDS[0];
  1032. assert_eq!(
  1033. crate::fence::create(null, 0, 0, fence_iid, &mut fence),
  1034. S_OK
  1035. );
  1036. let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q));
  1037. assert_eq!(signal(q, fence, 7), S_OK);
  1038. assert_eq!(
  1039. slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
  1040. 7
  1041. );
  1042. assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
  1043. }
  1044. /// The title's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`.
  1045. #[test]
  1046. fn console_queues_are_created_as_on_pc() {
  1047. let null = std::ptr::null();
  1048. let desc = QueueDescX {
  1049. kind: 2,
  1050. flags: 0,
  1051. engine_or_pipe: 1,
  1052. queue: 0,
  1053. };
  1054. let mut q = null;
  1055. assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
  1056. assert_eq!(queue(q).desc.kind, 2);
  1057. let none = std::ptr::null();
  1058. assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG);
  1059. }
  1060. #[test]
  1061. fn newer_queues_have_their_methods_two_slots_later() {
  1062. let (old, new) = (queue_table(false), queue_table(true));
  1063. assert_eq!(old[10], new[10]); // submission stays at 0x50
  1064. assert_eq!(old[14], new[16]); // signal 0x70 → 0x80
  1065. assert_eq!(old[30], new[32]); // present 0xf0 → 0x100
  1066. assert_eq!(new[35], execute_x as *const ()); // 0x118
  1067. }
  1068. #[test]
  1069. fn a_pair_of_timestamps_shows_the_load_it_is_given() {
  1070. let (start, end) = (0xd0419_6698, 0xd0419_6690);
  1071. assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000);
  1072. assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000);
  1073. assert_eq!(as_loaded(5, start, 100), 1);
  1074. }
  1075. #[test]
  1076. fn timestamps_and_values_are_written() {
  1077. let mut at = [0u64; 2];
  1078. Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4);
  1079. assert_eq!(at[0], 2);
  1080. Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
  1081. let first = at[1];
  1082. std::thread::sleep(std::time::Duration::from_millis(2));
  1083. Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
  1084. assert!(at[1] > first);
  1085. }
  1086. }