queue.rs 47 KB

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