queue.rs 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259
  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. /// Submissions the title made that the host has not begun ([`behind`]).
  427. #[cfg(windows)]
  428. pub(crate) fn queued() -> u64 {
  429. behind::queued()
  430. }
  431. /// For the frame-rate line.
  432. #[cfg(windows)]
  433. pub(crate) fn behind_line(frames: f64) {
  434. if behind::on() {
  435. behind::line(frames);
  436. }
  437. }
  438. /// Whether a queue may pass `wait`: memory holds the value, or, with
  439. /// submissions sent to the card without a wait (`crate::host::late`), it
  440. /// will once those in the air have run.
  441. #[cfg(windows)]
  442. fn value_met(wait: &crate::list::ValueWait) -> bool {
  443. wait.met() || (crate::host::late() && crate::host::late_met(wait))
  444. }
  445. fn queue<'a>(this: This) -> &'a Queue {
  446. // SAFETY: called from queue methods only.
  447. unsafe { &*this.cast::<Queue>() }
  448. }
  449. pub(crate) extern "system" fn create(
  450. _: This,
  451. desc: *const QueueDesc,
  452. iid: *const Iid,
  453. out: *mut This,
  454. ) -> HRESULT {
  455. // SAFETY: the title passes a description (null is tolerated).
  456. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  457. return E_INVALIDARG;
  458. };
  459. tracing::debug!(?desc, "command queue");
  460. let queue = Box::new(Queue {
  461. object: if crate::device::newer() {
  462. Object::new(&NEWER_FUNCTIONS)
  463. } else {
  464. Object::new(&FUNCTIONS)
  465. },
  466. kind: desc.kind,
  467. desc,
  468. #[cfg(windows)]
  469. held: Default::default(),
  470. });
  471. object::hand_out(QUEUE, queue, iid, &QUEUE_IIDS, out)
  472. }
  473. /// The console's queue description: an engine or pipe and a queue on it
  474. /// in place of PC's priority and node mask.
  475. #[repr(C)]
  476. #[derive(Debug, Clone, Copy)]
  477. pub(crate) struct QueueDescX {
  478. kind: u32,
  479. flags: u32,
  480. engine_or_pipe: u32,
  481. queue: u32,
  482. }
  483. /// Device method `CreateCommandQueueX`. The host picks engines itself, so
  484. /// the queue is created as on PC.
  485. pub(crate) extern "system" fn create_x(
  486. this: This,
  487. desc: *const QueueDescX,
  488. iid: *const Iid,
  489. out: *mut This,
  490. ) -> HRESULT {
  491. // SAFETY: the title passes a description (null is tolerated).
  492. let Some(&x) = (unsafe { desc.as_ref() }) else {
  493. return E_INVALIDARG;
  494. };
  495. tracing::debug!(desc = ?x, "console command queue");
  496. let desc = QueueDesc {
  497. kind: x.kind,
  498. priority: 0,
  499. flags: x.flags,
  500. nodes: 1,
  501. };
  502. create(this, &desc, iid, out)
  503. }
  504. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  505. object::answer(
  506. QUEUE,
  507. iid,
  508. object::is(iid, &QUEUE_IIDS).then_some(this),
  509. out,
  510. )
  511. }
  512. extern "system" fn release(this: This) -> u32 {
  513. let left = object::release_boxed::<Queue>(this);
  514. #[cfg(windows)]
  515. if left == 0 {
  516. lock(&WAITING).retain(|&q| q != this as usize);
  517. }
  518. left
  519. }
  520. /// Runs the lists' host lists and waits for them (decision 0007). A queue
  521. /// that waits for a fence keeps them until the fence is reached.
  522. extern "system" fn execute(this: This, count: u32, lists: *const This) {
  523. if lists.is_null() {
  524. return;
  525. }
  526. let _called = crate::timeline::span("the title's ExecuteCommandLists");
  527. #[cfg(all(windows, feature = "diagnostics"))]
  528. crate::timeline::title_thread();
  529. #[cfg(windows)]
  530. if let Some(host) = crate::host::host() {
  531. // SAFETY: the title passes `count` lists.
  532. let lists = unsafe { std::slice::from_raw_parts(lists, count as usize) };
  533. if behind::on() && !this.is_null() {
  534. behind::submit(this, lists);
  535. return;
  536. }
  537. if cuts() && !this.is_null() {
  538. submit_cut(this, lists);
  539. return;
  540. }
  541. if waits() && split() && !this.is_null() {
  542. submit_split(this, lists);
  543. return;
  544. }
  545. // A list that waits for a memory value not there yet: the queue
  546. // holds the submission, as it does behind a fence.
  547. if waits() && !this.is_null() {
  548. let unmet = crate::list::unmet_waits(lists);
  549. if !unmet.is_empty() {
  550. static SEEN: AtomicU64 = AtomicU64::new(0);
  551. if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
  552. tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value");
  553. }
  554. lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value));
  555. let mut waiting = lock(&WAITING);
  556. if !waiting.contains(&(this as usize)) {
  557. waiting.push(this as usize);
  558. }
  559. }
  560. }
  561. let kept = hold(this, || {
  562. let (taken, order) = crate::list::detach(lists);
  563. Held::Run(taken, order)
  564. });
  565. // Diagnostics: the order submissions are made in, next to the
  566. // commands of the frame's `ops` file (which are in recording order).
  567. #[cfg(feature = "diagnostics")]
  568. crate::capture::op(this as usize, || {
  569. let kind = (!this.is_null()).then(|| queue(this).kind);
  570. // The lists as the frame's other lines name them (their host sides).
  571. let named: Vec<String> = lists
  572. .iter()
  573. .map(|&l| match crate::list::host_list(l) {
  574. Some(h) => format!("{:#x}", std::ptr::from_ref(h) as usize),
  575. None => format!("title {l:?}"),
  576. })
  577. .collect();
  578. format!("SUBMIT queue kind {kind:?} held {kept} lists {named:?}")
  579. });
  580. if kept {
  581. return;
  582. }
  583. let host_lists: Vec<_> = lists
  584. .iter()
  585. .filter_map(|&l| crate::list::host_list(l))
  586. .collect();
  587. host.execute(&host_lists);
  588. crate::list::tables_done(lists);
  589. // What the lists wrote at the bottom of the pipe may be a fence
  590. // another queue waits for.
  591. release_held(false);
  592. return;
  593. }
  594. let _ = this;
  595. static ONCE: AtomicBool = AtomicBool::new(false);
  596. if !ONCE.swap(true, Ordering::Relaxed) {
  597. tracing::warn!(count, "command lists submitted; no host GPU runs them");
  598. }
  599. }
  600. /// The start of a present plane: frame token, then the plane's resources.
  601. #[repr(C)]
  602. pub(crate) struct Plane {
  603. token: u64,
  604. count: u32,
  605. resources: *const This,
  606. }
  607. /// Submission tagged with the frame it belongs to `(count, lists, frame
  608. /// token, flags)`; frames are paced elsewhere, so it runs as a plain one.
  609. extern "system" fn execute_x(this: This, count: u32, lists: *const This, _token: u64, _flags: u32) {
  610. execute(this, count, lists);
  611. }
  612. /// Signal with sync settings for the top and bottom of the pipe; our
  613. /// submissions are complete when they return, so it signals at once.
  614. extern "system" fn signal2_x(
  615. this: This,
  616. fence: This,
  617. value: u64,
  618. _bottom: *const u8,
  619. _top: *const u8,
  620. ) -> HRESULT {
  621. signal(this, fence, value)
  622. }
  623. /// Markers and events only matter to profilers.
  624. extern "system" fn marker(_: This) {}
  625. extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT {
  626. if fence.is_null() {
  627. return E_INVALIDARG;
  628. }
  629. let _called = crate::timeline::span("the title's queue Signal");
  630. #[cfg(windows)]
  631. if behind::on() && !this.is_null() {
  632. behind::signal(this, fence, value);
  633. return S_OK;
  634. }
  635. // A queue that waits signals after what it holds.
  636. #[cfg(windows)]
  637. if hold(this, || Held::Signal(fence as usize, value)) {
  638. return S_OK;
  639. }
  640. // Behind the submissions sent to the card and not waited for: the
  641. // fence is set when they are settled.
  642. #[cfg(windows)]
  643. if crate::host::late_signal(fence as usize, value) {
  644. return S_OK;
  645. }
  646. let _ = this;
  647. crate::fence::signal(fence, value)
  648. }
  649. /// From here on the queue runs nothing it is given until `fence` reaches
  650. /// `value`: how the console orders work between queues (the title's
  651. /// compute queue waits for the depth the graphics queue draws). Our
  652. /// submissions run when they are made, so a wait for a value already
  653. /// reached is nothing; otherwise what the queue is given next is held
  654. /// ([`Held`]) until a signal or a list's bottom-of-pipe write gets the
  655. /// fence there.
  656. extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT {
  657. if fence.is_null() {
  658. return E_INVALIDARG;
  659. }
  660. let _called = crate::timeline::span("the title's queue Wait");
  661. #[cfg(windows)]
  662. if !this.is_null() {
  663. let now = crate::fence::completed(fence);
  664. // Whether the title uses this at all (the first calls).
  665. {
  666. static CALLS: AtomicU64 = AtomicU64::new(0);
  667. if CALLS.fetch_add(1, Ordering::Relaxed) < 8 {
  668. tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence");
  669. }
  670. }
  671. #[cfg(feature = "diagnostics")]
  672. crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind));
  673. if behind::on() && waits() {
  674. behind::wait(this, fence, value);
  675. return S_OK;
  676. }
  677. let behind = {
  678. let mut held = lock(&queue(this).held);
  679. let behind = !held.is_empty() || now < value;
  680. if behind && waits() {
  681. held.push(Held::Wait(fence as usize, value));
  682. }
  683. behind
  684. };
  685. if behind {
  686. static SEEN: AtomicU64 = AtomicU64::new(0);
  687. if SEEN.fetch_add(1, Ordering::Relaxed) < 8 {
  688. tracing::info!(
  689. kind = queue(this).kind,
  690. now,
  691. value,
  692. held = waits(),
  693. "a queue waits for a fence not reached yet"
  694. );
  695. }
  696. }
  697. if behind && waits() {
  698. {
  699. let mut waiting = lock(&WAITING);
  700. if !waiting.contains(&(this as usize)) {
  701. waiting.push(this as usize);
  702. }
  703. }
  704. // The fence may have got there meanwhile.
  705. release_held(false);
  706. }
  707. }
  708. let _ = (this, value);
  709. S_OK
  710. }
  711. /// Ticks per second of GPU timestamps (see [`Written::GpuTimestamp`]).
  712. extern "system" fn timestamp_frequency(_: This, out: *mut u64) -> HRESULT {
  713. if out.is_null() {
  714. return E_INVALIDARG;
  715. }
  716. // SAFETY: checked non-null.
  717. unsafe { out.write(TIMESTAMP_FREQUENCY) };
  718. S_OK
  719. }
  720. const TIMESTAMP_FREQUENCY: u64 = 100_000_000;
  721. /// What a list's bottom-of-pipe write stores when the list has run.
  722. #[derive(Debug, Clone, Copy)]
  723. pub(crate) enum Written {
  724. Value(u64),
  725. /// The GPU clock: [`TIMESTAMP_FREQUENCY`] ticks per second since the
  726. /// process started (our GPU work is done on the CPU's timeline).
  727. GpuTimestamp,
  728. /// The CPU's performance counter.
  729. SystemTimestamp,
  730. }
  731. impl Written {
  732. /// Stores the low `bytes` (4 or 8) of the value at `at`.
  733. pub(crate) fn write(self, at: *mut u8, bytes: usize) {
  734. let value = match self {
  735. Written::Value(v) => v,
  736. Written::GpuTimestamp => {
  737. static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
  738. let elapsed = START.get_or_init(std::time::Instant::now).elapsed();
  739. let now = (elapsed.as_nanos() / (1_000_000_000 / u128::from(TIMESTAMP_FREQUENCY))) as u64;
  740. #[cfg(all(windows, feature = "diagnostics"))]
  741. crate::host::spans::stamped(at as usize, now);
  742. as_loaded(now, at as usize, gpu_load())
  743. }
  744. Written::SystemTimestamp => system_timestamp(),
  745. };
  746. #[cfg(all(windows, feature = "diagnostics"))]
  747. crate::timeline::told("written when its list had run", at as usize, value);
  748. // SAFETY: the title names writable GPU memory (unified with ours).
  749. unsafe {
  750. if bytes == 4 {
  751. at.cast::<u32>().write_unaligned(value as u32);
  752. } else {
  753. at.cast::<u64>().write_unaligned(value);
  754. }
  755. }
  756. }
  757. }
  758. /// What the title's GPU time is made to look like, in ticks
  759. /// (`VICTORY_GPU_LOAD_MS`; unset: as it is).
  760. ///
  761. /// The title asks for four GPU timestamps a frame, in pairs of 16 bytes, the
  762. /// start in the second eight and the end in the first. All of them are written
  763. /// when the frame's last submissions land, within microseconds, so every pair
  764. /// says the card did nothing.
  765. fn gpu_load() -> u64 {
  766. static LOAD: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  767. *LOAD.get_or_init(|| {
  768. let ms = std::env::var("VICTORY_GPU_LOAD_MS").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0);
  769. ms * (TIMESTAMP_FREQUENCY / 1000)
  770. })
  771. }
  772. /// The timestamp written at `at` when the clock says `now`, if a pair's start
  773. /// is to lie `load` ticks before its end.
  774. fn as_loaded(now: u64, at: usize, load: u64) -> u64 {
  775. if at & 8 != 0 {
  776. now.saturating_sub(load).max(1)
  777. } else {
  778. now
  779. }
  780. }
  781. fn system_timestamp() -> u64 {
  782. #[cfg(windows)]
  783. {
  784. let mut count = 0;
  785. // SAFETY: a valid out pointer.
  786. unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut count) };
  787. count as u64
  788. }
  789. #[cfg(not(windows))]
  790. 0
  791. }
  792. /// Frames presented so far.
  793. static FRAMES: AtomicU64 = AtomicU64::new(0);
  794. #[cfg(feature = "diagnostics")]
  795. pub(crate) fn presented() -> u64 {
  796. FRAMES.load(Ordering::Relaxed)
  797. }
  798. /// Shows the first plane's first resource in our window.
  799. ///
  800. /// shortcut: one plane, no scaling or placement, the source expected in
  801. /// the common state.
  802. extern "system" fn present(
  803. this: This,
  804. planes: u32,
  805. plane_parameters: *const Plane,
  806. _parameters: *const u8,
  807. ) -> HRESULT {
  808. #[cfg(not(windows))]
  809. let _ = this;
  810. #[cfg(all(windows, feature = "diagnostics"))]
  811. crate::copystat::present_begins();
  812. let called = crate::timeline::span("the title's Present");
  813. #[cfg(all(windows, feature = "diagnostics"))]
  814. crate::timeline::title_thread();
  815. // Submissions sent to the card and not waited for are settled first,
  816. // and what that frees runs in its own order, before anything is forced.
  817. #[cfg(windows)]
  818. if behind::on() {
  819. // The present goes into the line of what the queues were given.
  820. } else if crate::host::late() && !crate::host::late_free_present() {
  821. crate::host::settle_for_present();
  822. release_held(false);
  823. crate::host::settle_for_present();
  824. } else if crate::host::late() {
  825. // The present is sent ahead too: what waits for a value a flight
  826. // will write runs behind that flight, and nothing is settled here.
  827. release_held(false);
  828. }
  829. // shortcut: what a queue still holds at a present runs now, whatever
  830. // its fence: a wait is not kept across frames.
  831. #[cfg(windows)]
  832. if !behind::on() {
  833. release_held(forces());
  834. }
  835. let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1;
  836. if frame.is_power_of_two() {
  837. let (draws, dispatches) = crate::list::take_counts();
  838. #[cfg(windows)]
  839. let (drawn, dispatched) = {
  840. static DRAWN: AtomicU64 = AtomicU64::new(0);
  841. static DISPATCHED: AtomicU64 = AtomicU64::new(0);
  842. let since = |last: &AtomicU64, now: u64| now - last.swap(now, Ordering::Relaxed);
  843. (
  844. since(&DRAWN, crate::draw::drawn()),
  845. since(&DISPATCHED, crate::draw::dispatched()),
  846. )
  847. };
  848. #[cfg(not(windows))]
  849. let (drawn, dispatched) = (0, 0);
  850. tracing::info!(
  851. frame,
  852. draws,
  853. drawn,
  854. dispatches,
  855. dispatched,
  856. "frame presented (since the last line: draws and dispatches, and those run on the host)"
  857. );
  858. #[cfg(windows)]
  859. if frame >= 256 {
  860. let (hits, misses) = crate::shader_cache::counts();
  861. tracing::info!(hits, misses, "shaders from the cache and translated so far");
  862. }
  863. }
  864. #[cfg(all(windows, feature = "diagnostics"))]
  865. {
  866. crate::capture::frame_drew(frame, crate::draw::drawn());
  867. if crate::capture::listed(frame) {
  868. before_sync();
  869. crate::capture::dump_targets(frame);
  870. }
  871. }
  872. #[cfg(windows)]
  873. if behind::on() && !this.is_null() {
  874. const COPY_SOURCE: u32 = 0x800;
  875. let texture = if planes > 0
  876. // SAFETY: the title passes `planes` plane descriptions.
  877. && let Some(plane) = unsafe { plane_parameters.as_ref() }
  878. && plane.count > 0
  879. && !plane.resources.is_null()
  880. {
  881. // SAFETY: the plane lists `count` resources.
  882. let resource = unsafe { *plane.resources };
  883. // The state the lists recorded so far leave it in (the next
  884. // frame's, recorded before this is shown, go on from there).
  885. crate::resource::host_copy(resource).map(|copy| {
  886. let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before);
  887. crate::resource::host_transition(resource, state);
  888. (resource as usize, copy, state)
  889. })
  890. } else {
  891. None
  892. };
  893. let resource = texture.as_ref().map_or(0, |t| t.0);
  894. behind::present(this, texture.map(|(_, copy, state)| (copy, state)), Shown { frame, resource });
  895. called.end();
  896. #[cfg(feature = "diagnostics")]
  897. frame_ends();
  898. return S_OK;
  899. }
  900. #[cfg(windows)]
  901. if planes > 0
  902. // SAFETY: the title passes `planes` plane descriptions.
  903. && let Some(plane) = unsafe { plane_parameters.as_ref() }
  904. && plane.count > 0
  905. && !plane.resources.is_null()
  906. // SAFETY: the plane lists `count` resources.
  907. && let resource = unsafe { *plane.resources }
  908. && let Some(texture) = crate::resource::host_resource(resource)
  909. && let Some(host) = crate::host::host()
  910. {
  911. const COPY_SOURCE: u32 = 0x800;
  912. let state = crate::resource::host_transition(resource, COPY_SOURCE)
  913. .map_or(COPY_SOURCE, |(_, before)| before);
  914. show(texture, state, Shown { frame, resource: resource as usize });
  915. crate::resource::host_transition(resource, state);
  916. let _ = host;
  917. }
  918. #[cfg(not(windows))]
  919. let _ = (planes, plane_parameters);
  920. called.end();
  921. #[cfg(all(windows, feature = "diagnostics"))]
  922. frame_ends();
  923. S_OK
  924. }
  925. /// Diagnostics: the title's present is over.
  926. #[cfg(all(windows, feature = "diagnostics"))]
  927. fn frame_ends() {
  928. crate::timeline::presented();
  929. crate::ab::presented(|switch, was, will| {
  930. if switch == "VICTORY_ASYNC_SUBMIT" && was && !will {
  931. behind::leave();
  932. }
  933. });
  934. }
  935. /// The frame a present shows, and the title's resource it shows.
  936. #[cfg(windows)]
  937. #[derive(Clone, Copy)]
  938. struct Shown {
  939. frame: u64,
  940. resource: usize,
  941. }
  942. /// Shows `texture`, in host state `state`, in our window.
  943. #[cfg(windows)]
  944. fn show(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32, what: Shown) {
  945. let Some(host) = crate::host::host() else {
  946. return;
  947. };
  948. let shown = host.present(texture, state, what.frame);
  949. #[cfg(feature = "diagnostics")]
  950. blinks(what.frame, what.resource as This, state, shown);
  951. #[cfg(not(feature = "diagnostics"))]
  952. let _ = (shown, what.resource);
  953. }
  954. /// Diagnostics: logs a presented frame that is black after one that was
  955. /// not, with what was presented and how many draws ran since.
  956. #[cfg(all(windows, feature = "diagnostics"))]
  957. fn blinks(frame: u64, resource: This, state: u32, shown: Option<bool>) {
  958. static LAST: std::sync::Mutex<(bool, u64, u64)> = std::sync::Mutex::new((false, 0, 0));
  959. let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner());
  960. let drawn = crate::draw::drawn();
  961. let black = shown.unwrap_or(false);
  962. let draws = crate::draw::take_frame();
  963. if black && !last.0 {
  964. last.2 += 1;
  965. tracing::warn!(
  966. frame,
  967. resource = ?resource,
  968. state = format_args!("{state:#x}"),
  969. draws = drawn - last.1,
  970. copied = shown.is_some(),
  971. black_frames = last.2,
  972. levels = ?crate::capture::recent_levels(),
  973. "a black frame after a frame that was not"
  974. );
  975. for d in draws {
  976. tracing::warn!("black frame {frame}: {d}");
  977. }
  978. AFTER.store(frame + 6, Ordering::Relaxed);
  979. }
  980. // Six frames on: the levels around it (a fade or a single drop).
  981. static AFTER: AtomicU64 = AtomicU64::new(0);
  982. if AFTER.load(Ordering::Relaxed) == frame {
  983. tracing::warn!(frame, levels = ?crate::capture::recent_levels(), "levels after the black frame");
  984. }
  985. *last = (black, drawn, last.2);
  986. }
  987. /// A run of destination pages: how they are mapped (0 pool pages from
  988. /// `start` on, 1 pool page `start` each, 2 unmapped, 3 left as they are)
  989. /// and how many.
  990. #[repr(C)]
  991. pub(crate) struct PageRange {
  992. kind: u32,
  993. start: u32,
  994. count: u32,
  995. }
  996. /// The ranges mapped from a destination address on.
  997. #[repr(C)]
  998. pub(crate) struct PageBatch {
  999. destination: u64,
  1000. count: u32,
  1001. ranges: *const PageRange,
  1002. }
  1003. /// Bytes per mapped page.
  1004. const PAGE: u64 = 64 << 10;
  1005. /// `CopyPageMappingsBatchX(count, batches, pool, pool pages, flags)`: maps
  1006. /// pages of a pool (memory the title mapped physical pages into) at the
  1007. /// batches' addresses. The title streams textures into pool pages
  1008. /// and maps them into its tiled heap this way (title+0xf2c470, ranges of
  1009. /// one constant page or of unmapped pages). Done at once: every earlier
  1010. /// submission has run.
  1011. extern "system" fn copy_page_mappings(
  1012. _: This,
  1013. count: u32,
  1014. batches: *const PageBatch,
  1015. pool: u64,
  1016. pool_pages: u32,
  1017. _flags: u32,
  1018. ) -> HRESULT {
  1019. let Some(map) = crate::resource::page_mapper() else {
  1020. return E_INVALIDARG;
  1021. };
  1022. if batches.is_null() && count > 0 {
  1023. return E_INVALIDARG;
  1024. }
  1025. let _called = crate::timeline::span("the title's CopyPageMappings");
  1026. let batches = (count > 0).then(|| {
  1027. // SAFETY: the title passes `count` batches.
  1028. unsafe { std::slice::from_raw_parts(batches, count as usize) }
  1029. });
  1030. let mut ok = true;
  1031. let many = crate::resource::many_page_mapper();
  1032. let mut gathered: Vec<(u64, u64, u64)> = Vec::new();
  1033. let mut map = |to: u64, from: u64, len: u64| match many {
  1034. Some(_) => {
  1035. gathered.push((to, from, len));
  1036. true
  1037. }
  1038. None => map(to, from, len),
  1039. };
  1040. for b in batches.into_iter().flatten() {
  1041. if b.ranges.is_null() {
  1042. continue;
  1043. }
  1044. // SAFETY: each batch holds `count` ranges.
  1045. let ranges = unsafe { std::slice::from_raw_parts(b.ranges, b.count as usize) };
  1046. let mut at = b.destination;
  1047. for r in ranges {
  1048. let len = u64::from(r.count) * PAGE;
  1049. let inside = |pages: u32| r.start.checked_add(pages).is_some_and(|e| e <= pool_pages);
  1050. let source = pool + u64::from(r.start) * PAGE;
  1051. ok &= match r.kind {
  1052. 0 if inside(r.count) => map(at, source, len),
  1053. 1 if inside(1) => (0..u64::from(r.count)).all(|k| map(at + k * PAGE, source, PAGE)),
  1054. 2 => map(at, 0, len),
  1055. 3 => true,
  1056. _ => false,
  1057. };
  1058. at += len;
  1059. }
  1060. }
  1061. if let Some(many) = many {
  1062. ok &= many(&gathered);
  1063. }
  1064. if !ok {
  1065. static ONCE: std::sync::Once = std::sync::Once::new();
  1066. ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed"));
  1067. }
  1068. S_OK
  1069. }
  1070. extern "system" fn desc(this: This, out: *mut QueueDesc) {
  1071. if !out.is_null() {
  1072. // SAFETY: checked non-null; the title passes room for a description.
  1073. unsafe { out.write(queue(this).desc) };
  1074. }
  1075. }
  1076. /// The queue methods by their slot in older titles' queues (the 2020-era
  1077. /// layout): IUnknown 3, object 4, device child 1, queue 26 (12 as on PC,
  1078. /// then console ones).
  1079. const METHODS: [(usize, *const ()); 15] = [
  1080. (0, query as *const ()),
  1081. (2, release as *const ()),
  1082. (7, object::parent_device as *const ()), // 0x38
  1083. (10, execute as *const ()), // 0x50
  1084. (11, marker as *const ()), // 0x58 set marker
  1085. (12, marker as *const ()), // 0x60 begin event
  1086. (13, marker as *const ()), // 0x68 end event
  1087. (14, signal as *const ()), // 0x70
  1088. (15, wait as *const ()), // 0x78
  1089. (16, timestamp_frequency as *const ()), // 0x80
  1090. (26, desc as *const ()), // 0xd0
  1091. (29, copy_page_mappings as *const ()), // 0xe8 page mapping batch
  1092. (30, present as *const ()), // 0xf0
  1093. (33, execute_x as *const ()), // 0x108
  1094. (32, signal2_x as *const ()), // 0x100
  1095. ];
  1096. /// Newer titles' queues have two more methods before Signal, which moved
  1097. /// from 0x70 to 0x80: every slot from 0x70 on is two later (taken here as
  1098. /// starting exactly at 0x70, the methods before it kept in place).
  1099. /// Inferred from the title's calls: Signal 0x80 `(fence,
  1100. /// value)`, timestamp frequency 0x90 (title+0x24841a6), suspend and resume
  1101. /// 0xb8/0xc0, PresentX 0x100, the frame-token submission 0x118 `(count,
  1102. /// lists, token, flags)` (title+0x24821dd).
  1103. const fn newer_slot(slot: usize) -> usize {
  1104. if slot >= 14 { slot + 2 } else { slot }
  1105. }
  1106. const fn queue_table(newer: bool) -> [*const (); 36] {
  1107. let mut f = object::d3d12_object(object::missing_table::<QUEUE, 36>());
  1108. let mut i = 0;
  1109. while i < METHODS.len() {
  1110. let (slot, method) = METHODS[i];
  1111. f[if newer { newer_slot(slot) } else { slot }] = method;
  1112. i += 1;
  1113. }
  1114. f
  1115. }
  1116. static FUNCTIONS: Table<36> = Table(queue_table(false));
  1117. static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true));
  1118. #[cfg(test)]
  1119. mod tests {
  1120. use super::*;
  1121. use crate::object::slot;
  1122. /// Where a queue's signal is: newer layouts have it two slots later.
  1123. /// Another test may switch layouts while this one runs, so the queue's
  1124. /// own table decides.
  1125. fn signal_slot(q: This) -> usize {
  1126. // SAFETY: one of our queues; its first field is the table.
  1127. let table = unsafe { *q.cast::<*const *const ()>() };
  1128. if table == NEWER_FUNCTIONS.0.as_ptr() {
  1129. 0x80
  1130. } else {
  1131. 0x70
  1132. }
  1133. }
  1134. #[test]
  1135. fn queue_signals_complete_at_once() {
  1136. let null = std::ptr::null();
  1137. let desc = QueueDesc {
  1138. kind: 0,
  1139. priority: 0,
  1140. flags: 0,
  1141. nodes: 0,
  1142. };
  1143. let mut q = null;
  1144. assert_eq!(create(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
  1145. // SAFETY: the title reads the type at +0x10.
  1146. assert_eq!(unsafe { q.cast::<u8>().add(0x10).cast::<u32>().read() }, 0);
  1147. let mut fence = null;
  1148. let fence_iid = &crate::fence::FENCE_IIDS[0];
  1149. assert_eq!(
  1150. crate::fence::create(null, 0, 0, fence_iid, &mut fence),
  1151. S_OK
  1152. );
  1153. let signal = slot::<extern "system" fn(This, This, u64) -> HRESULT>(q, signal_slot(q));
  1154. assert_eq!(signal(q, fence, 7), S_OK);
  1155. assert_eq!(
  1156. slot::<extern "system" fn(This) -> u64>(fence, 0x40)(fence),
  1157. 7
  1158. );
  1159. assert_eq!(slot::<extern "system" fn(This) -> u32>(q, 0x10)(q), 0);
  1160. }
  1161. /// The title's compute queue: `{COMPUTE, 0, pipe 1, queue 0}`.
  1162. #[test]
  1163. fn console_queues_are_created_as_on_pc() {
  1164. let null = std::ptr::null();
  1165. let desc = QueueDescX {
  1166. kind: 2,
  1167. flags: 0,
  1168. engine_or_pipe: 1,
  1169. queue: 0,
  1170. };
  1171. let mut q = null;
  1172. assert_eq!(create_x(null, &desc, &QUEUE_IIDS[0], &mut q), S_OK);
  1173. assert_eq!(queue(q).desc.kind, 2);
  1174. let none = std::ptr::null();
  1175. assert_eq!(create_x(null, none, &QUEUE_IIDS[0], &mut q), E_INVALIDARG);
  1176. }
  1177. #[test]
  1178. fn newer_queues_have_their_methods_two_slots_later() {
  1179. let (old, new) = (queue_table(false), queue_table(true));
  1180. assert_eq!(old[10], new[10]); // submission stays at 0x50
  1181. assert_eq!(old[14], new[16]); // signal 0x70 → 0x80
  1182. assert_eq!(old[30], new[32]); // present 0xf0 → 0x100
  1183. assert_eq!(new[35], execute_x as *const ()); // 0x118
  1184. }
  1185. #[test]
  1186. fn a_pair_of_timestamps_shows_the_load_it_is_given() {
  1187. let (start, end) = (0xd0419_6698, 0xd0419_6690);
  1188. assert_eq!(as_loaded(5_000_000, end, 4_000_000) - as_loaded(5_000_000, start, 4_000_000), 4_000_000);
  1189. assert_eq!(as_loaded(5_000_000, start, 0), 5_000_000);
  1190. assert_eq!(as_loaded(5, start, 100), 1);
  1191. }
  1192. #[test]
  1193. fn timestamps_and_values_are_written() {
  1194. let mut at = [0u64; 2];
  1195. Written::Value(0x1_0000_0002).write(at.as_mut_ptr().cast(), 4);
  1196. assert_eq!(at[0], 2);
  1197. Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
  1198. let first = at[1];
  1199. std::thread::sleep(std::time::Duration::from_millis(2));
  1200. Written::GpuTimestamp.write(at[1..].as_mut_ptr().cast(), 8);
  1201. assert!(at[1] > first);
  1202. }
  1203. }