list.rs 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287
  1. //! Command allocators and command lists.
  2. //!
  3. //! The title's inlined code writes packets into a list only while its put
  4. //! pointer is below a limit, and calls the list's method otherwise. Our
  5. //! lists keep the pointer and every limit at zero, so every command reaches
  6. //! the table as a call.
  7. //!
  8. //! Each list records onto a host command list as its methods are called
  9. //! (decision 0007); draw state lives in `crate::draw`. Methods not
  10. //! written yet log once with their caller, so a run lists what to do next.
  11. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  12. use std::mem::offset_of;
  13. use crate::object::{
  14. self, ALLOCATOR, E_INVALIDARG, HRESULT, Iid, LIST, Object, S_OK, Table, This, guid,
  15. };
  16. use crate::queue::Written;
  17. use crate::resource::PAGEABLE_IIDS;
  18. const ALLOCATOR_IIDS: [Iid; 4] = [
  19. guid(
  20. 0x6102dee4,
  21. 0xaf59,
  22. 0x4b09,
  23. [0xb9, 0x99, 0xb4, 0x4d, 0x73, 0xf0, 0x9b, 0x24],
  24. ),
  25. PAGEABLE_IIDS[0],
  26. PAGEABLE_IIDS[1],
  27. PAGEABLE_IIDS[2],
  28. ];
  29. /// The list interfaces up to `ID3D12GraphicsCommandList6` (the table has
  30. /// all their slots): those whose ids are the same as on PC, the console's
  31. /// own List5 and List6 (the title asks for List6), then the
  32. /// device child's.
  33. const LIST_IIDS: [Iid; 10] = [
  34. guid(
  35. 0x7116d91c,
  36. 0xe7e4,
  37. 0x47ce,
  38. [0xb8, 0xc6, 0xec, 0x81, 0x68, 0xf4, 0x37, 0xe5],
  39. ),
  40. guid(
  41. 0x5b160d0f,
  42. 0xac1b,
  43. 0x4185,
  44. [0x8b, 0xa8, 0xb3, 0xae, 0x42, 0xa5, 0xa4, 0x55],
  45. ),
  46. guid(
  47. 0x553103fb,
  48. 0x1fe7,
  49. 0x4557,
  50. [0xbb, 0x38, 0x94, 0x6d, 0x7d, 0x0e, 0x7c, 0xa7],
  51. ),
  52. guid(
  53. 0x38c3e585,
  54. 0xff17,
  55. 0x412c,
  56. [0x91, 0x50, 0x4f, 0xc6, 0xf9, 0xd7, 0x2a, 0x28],
  57. ),
  58. guid(
  59. 0x6fda83a7,
  60. 0xb84c,
  61. 0x4e38,
  62. [0x9a, 0xc8, 0xc7, 0xbd, 0x22, 0x01, 0x6b, 0x3d],
  63. ),
  64. guid(
  65. 0x8754318e,
  66. 0xd3a9,
  67. 0x4541,
  68. [0x98, 0xcf, 0x64, 0x5b, 0x50, 0xdc, 0x48, 0x74],
  69. ),
  70. guid(
  71. 0x55050859,
  72. 0x4024,
  73. 0x474c,
  74. [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
  75. ),
  76. guid(
  77. 0xc3827890,
  78. 0x4024,
  79. 0x474c,
  80. [0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74],
  81. ),
  82. PAGEABLE_IIDS[1],
  83. PAGEABLE_IIDS[2],
  84. ];
  85. #[repr(C)]
  86. struct Allocator {
  87. object: Object,
  88. kind: u32,
  89. }
  90. /// The layout the title's inlined code reads.
  91. #[repr(C)]
  92. struct List {
  93. object: Object,
  94. kind: u32,
  95. /// The put pointer, then the plain, draw, API and unbiased API limits:
  96. /// all zero, so every inline check fails.
  97. put: [u64; 5],
  98. reserved: [u32; 64],
  99. /// State the inline code keeps for building packets; unused by us.
  100. graphics_root_headers: [u32; 128],
  101. compute_root_headers: [u32; 128],
  102. pipeline_shadow: [u32; 8],
  103. /// Newer titles' lists are larger: the title's state flush
  104. /// (title+0x32786) copies a pipeline's 32 bytes to +0x544..+0x564 and
  105. /// tests +0x548, so its layout runs past 0x560. Its size is unknown;
  106. /// this keeps our fields clear of whatever the title writes there.
  107. newer: [u32; 256],
  108. /// Ours, after the console layout: memory handed out by
  109. /// [`allocate_upload`], kept until the list is reset; the host list the
  110. /// calls record into (decision 0007), and the draw state the title set.
  111. uploads: std::sync::Mutex<Vec<Vec<u8>>>,
  112. #[cfg(windows)]
  113. host: Option<crate::host::HostList>,
  114. #[cfg(windows)]
  115. state: std::sync::Mutex<crate::draw::State>,
  116. /// The parts of the recording before `host`, in order, each closed: the
  117. /// list is cut at its waits for memory values ([`cut`]).
  118. #[cfg(windows)]
  119. earlier: Vec<Part>,
  120. /// The waits recorded before the first work of `host`: the queue stands
  121. /// at them before it runs `host`.
  122. #[cfg(windows)]
  123. gate: Vec<ValueWait>,
  124. }
  125. /// One part of a title list cut at its waits: the waits the queue stands
  126. /// at, then the host list that runs once they are met.
  127. #[cfg(windows)]
  128. struct Part {
  129. waits: Vec<ValueWait>,
  130. host: crate::host::HostList,
  131. }
  132. const _: () = assert!(offset_of!(List, put) == 0x18);
  133. const _: () = assert!(offset_of!(List, pipeline_shadow) + 32 == 0x560);
  134. /// Runs `f` with the host list and draw state of a title list, if there
  135. /// is a host GPU.
  136. #[cfg(windows)]
  137. fn with_state(this: This, f: impl FnOnce(&crate::host::HostList, &mut crate::draw::State)) {
  138. let Some(list) = host_list(this) else { return };
  139. #[cfg(feature = "diagnostics")]
  140. let started = std::time::Instant::now();
  141. // SAFETY: the title passes one of our lists.
  142. let state = unsafe { &(*this.cast::<List>()).state };
  143. f(list, &mut state.lock().unwrap_or_else(|e| e.into_inner()));
  144. #[cfg(feature = "diagnostics")]
  145. crate::copystat::recorded(started);
  146. }
  147. /// The submission of `lists` has run: each gives its descriptor tables'
  148. /// slots back ([`crate::draw::State::tables_done`]). A list cut at waits
  149. /// keeps them: its state goes with its last part.
  150. #[cfg(windows)]
  151. pub(crate) fn tables_done(lists: &[This]) {
  152. for &this in lists {
  153. if this.is_null() {
  154. continue;
  155. }
  156. // SAFETY: the title passes our lists.
  157. let list = unsafe { &*this.cast::<List>() };
  158. if list.earlier.is_empty() {
  159. list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done();
  160. }
  161. }
  162. }
  163. /// The host list behind a title list, if there is a host GPU.
  164. #[cfg(windows)]
  165. pub(crate) fn host_list<'a>(this: This) -> Option<&'a crate::host::HostList> {
  166. if this.is_null() {
  167. return None;
  168. }
  169. // SAFETY: the title passes one of our lists.
  170. unsafe { (*this.cast::<List>()).host.as_ref() }
  171. }
  172. /// The host side of a submitted list, taken from it: a queue that waits
  173. /// for a fence runs it later, and the title may reset the list meanwhile.
  174. /// With it go the upload memory and the dynamic descriptor slots its
  175. /// commands name, kept until it has run.
  176. #[cfg(windows)]
  177. pub(crate) struct Detached {
  178. host: crate::host::HostList,
  179. _uploads: Vec<Vec<u8>>,
  180. _state: crate::draw::State,
  181. }
  182. #[cfg(windows)]
  183. impl Detached {
  184. pub(crate) fn host(&self) -> &crate::host::HostList {
  185. &self.host
  186. }
  187. }
  188. /// A host list that has run and waits to be used again, and the bytes of
  189. /// upload memory it keeps.
  190. #[cfg(windows)]
  191. struct Idle(crate::host::HostList, u64);
  192. // SAFETY: D3D12 objects are free-threaded, and an idle list is touched by
  193. // nobody until it is taken out again.
  194. #[cfg(windows)]
  195. unsafe impl Send for Idle {}
  196. /// Host lists that have run, reset and ready to record: the host side of
  197. /// a list a queue held, or of a part of a list cut at a wait, is taken
  198. /// from the title's list at its submission, and the title's list needs
  199. /// another. Each was made new and thrown away after its run: a hundred a
  200. /// frame in gameplay, each two command allocators and two lists, and for
  201. /// four in ten a budget and an argument buffer (run 61: "104 host lists
  202. /// made 21.2 ms" a frame, and the graphics kernel's time to free them).
  203. #[cfg(windows)]
  204. static IDLE: std::sync::Mutex<(Vec<Idle>, u64)> = std::sync::Mutex::new((Vec::new(), 0));
  205. /// The most host lists kept idle, and the most upload memory they may keep
  206. /// between them (a list keeps scratch chunks over a reset only while lists
  207. /// do not share them, `VICTORY_SCRATCH_POOL=0`).
  208. #[cfg(windows)]
  209. const IDLE_MOST: (usize, u64) = (128, 256 << 20);
  210. /// Whether host lists that have run are used again (on by default;
  211. /// `VICTORY_LIST_POOL=0`: each is made new and thrown away, as before).
  212. #[cfg(windows)]
  213. fn pools() -> bool {
  214. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  215. *ON.get_or_init(|| std::env::var_os("VICTORY_LIST_POOL").is_none_or(|v| v != "0"))
  216. }
  217. /// A host list open for recording: one that has run, as a title's list is
  218. /// after its reset, or a new one.
  219. #[cfg(windows)]
  220. fn fresh_list() -> Option<crate::host::HostList> {
  221. let idle = {
  222. let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
  223. let taken = idle.0.pop();
  224. if let Some(Idle(_, bytes)) = &taken {
  225. idle.1 -= bytes;
  226. }
  227. taken
  228. };
  229. match idle {
  230. Some(Idle(list, _)) => Some(list),
  231. None => crate::host::host().and_then(|h| h.new_list().ok()),
  232. }
  233. }
  234. /// The host sides of lists whose submission has run (submissions are
  235. /// waited for; `ran` names the ones it ran, by their place in `lists`):
  236. /// what they held is let go, as before, and the host lists are reset and
  237. /// kept for [`fresh_list`].
  238. #[cfg(windows)]
  239. pub(crate) fn recycle(lists: Vec<Detached>, ran: &[usize]) {
  240. if !pools() {
  241. return;
  242. }
  243. for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() {
  244. // The descriptor slots and the upload memory its commands named.
  245. drop(_state);
  246. drop(_uploads);
  247. if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 {
  248. continue;
  249. }
  250. // As the title's reset does: what the list kept for its commands
  251. // goes, its allocators stay.
  252. host.reset();
  253. let bytes = host.scratch_kept();
  254. let mut idle = IDLE.lock().unwrap_or_else(|e| e.into_inner());
  255. if idle.0.len() < IDLE_MOST.0 && idle.1 + bytes <= IDLE_MOST.1 {
  256. idle.0.push(Idle(host, bytes));
  257. idle.1 += bytes;
  258. }
  259. }
  260. }
  261. /// A wait for a memory value recorded into list `this`, with waits cut
  262. /// into lists (`crate::queue::cuts`). On the console the queue runs the
  263. /// list up to the wait, stands there until the value is in memory, and
  264. /// runs on; the list's bottom-of-pipe writes before the wait are done by
  265. /// then, and other queues may be waiting for exactly those. So the
  266. /// recording is cut here: the host list so far is closed and kept as a
  267. /// part of its own ([`Part`]), the title's calls record into a new host
  268. /// list from here on, and the wait stands before that one. A submission
  269. /// then gives the queue the parts in order ([`detach_parts`]).
  270. ///
  271. /// A wait before any work (the first call after a reset, or a wait right
  272. /// after another) cuts nothing: it joins the waits before the current
  273. /// host list.
  274. /// shortcut: a bottom-of-pipe write is done when its part has run, not at
  275. /// its place in the part: a queue waiting for it starts later than on the
  276. /// console, never earlier, and nothing can wait for itself that way (a
  277. /// part has no wait after its first work).
  278. #[cfg(windows)]
  279. fn cut(this: This, wait: ValueWait) {
  280. if this.is_null() {
  281. return;
  282. }
  283. // SAFETY: the title passes one of our lists; a list is recorded by one
  284. // thread at a time and is not submitted while it records.
  285. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  286. let Some(current) = list.host.as_ref() else {
  287. return;
  288. };
  289. if current.untouched() {
  290. list.gate.push(wait);
  291. return;
  292. }
  293. let Some(fresh) = fresh_list() else {
  294. // shortcut: without a new host list the wait stands before the part
  295. // it was recorded in.
  296. static ONCE: std::sync::Once = std::sync::Once::new();
  297. ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start"));
  298. list.gate.push(wait);
  299. return;
  300. };
  301. current.close();
  302. static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  303. if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
  304. tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value");
  305. }
  306. if let Some(done) = list.host.replace(fresh) {
  307. let waits = std::mem::replace(&mut list.gate, vec![wait]);
  308. list.earlier.push(Part { waits, host: done });
  309. }
  310. // What the title set so far, on the new host list.
  311. if let Some(host) = list.host.as_ref() {
  312. list.state
  313. .lock()
  314. .unwrap_or_else(|e| e.into_inner())
  315. .replay(host);
  316. }
  317. }
  318. /// Whether list `this` recorded a wait for a memory value (with waits cut
  319. /// into lists).
  320. #[cfg(windows)]
  321. pub(crate) fn cut_list(this: This) -> bool {
  322. if this.is_null() {
  323. return false;
  324. }
  325. // SAFETY: one of our lists, closed and submitted: nothing records
  326. // into it.
  327. let list = unsafe { &*this.cast::<List>() };
  328. !list.earlier.is_empty() || !list.gate.is_empty()
  329. }
  330. /// What a queue is given for submitted lists that were cut at their waits:
  331. /// the waits it stands at, the host lists it runs once they are met, and
  332. /// the order those run in.
  333. #[cfg(windows)]
  334. pub(crate) type Parts = Vec<(Vec<ValueWait>, Vec<Detached>, Vec<usize>)>;
  335. /// Takes the host sides of the submitted `lists`, part by part ([`cut`]),
  336. /// and leaves each list a new, closed host list for its next reset, as
  337. /// [`detach`] does. What comes back is in the order the queue runs it: a
  338. /// new entry starts at every part that has waits; host lists without
  339. /// waits join the entry before them. The list's upload memory and draw
  340. /// state (its dynamic descriptor slots) go with its last part, which runs
  341. /// last.
  342. /// shortcut: a list the submission names a second time runs again only if
  343. /// it has one part and that part is in the entry being filled; otherwise
  344. /// the second naming is dropped (logged once).
  345. #[cfg(windows)]
  346. pub(crate) fn detach_parts(lists: &[This]) -> Parts {
  347. let mut parts: Parts = vec![(Vec::new(), Vec::new(), Vec::new())];
  348. // The lists taken: where its one host list is (entry, place), or none
  349. // for a list of several parts.
  350. let mut seen: Vec<(This, Option<(usize, usize)>)> = Vec::new();
  351. for &this in lists {
  352. if this.is_null() {
  353. continue;
  354. }
  355. if let Some(&(_, at)) = seen.iter().find(|(t, _)| *t == this) {
  356. match at {
  357. Some((entry, place)) if entry + 1 == parts.len() => parts[entry].2.push(place),
  358. _ => {
  359. static ONCE: std::sync::Once = std::sync::Once::new();
  360. ONCE.call_once(|| {
  361. tracing::warn!("a list named twice by a submission that waits for memory values runs once")
  362. });
  363. }
  364. }
  365. continue;
  366. }
  367. let Some(fresh) = fresh_list() else {
  368. continue;
  369. };
  370. // A new host list is open; the title's next call on its list is a
  371. // reset, which wants it closed.
  372. fresh.close();
  373. // SAFETY: one of our lists, closed and submitted: nothing records
  374. // into it until the title resets it.
  375. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  376. let Some(host) = list.host.replace(fresh) else {
  377. continue;
  378. };
  379. let earlier = std::mem::take(&mut list.earlier);
  380. let gate = std::mem::take(&mut list.gate);
  381. let uploads = std::mem::take(&mut *list.uploads.lock().unwrap_or_else(|e| e.into_inner()));
  382. let state = std::mem::take(&mut *list.state.lock().unwrap_or_else(|e| e.into_inner()));
  383. let single = earlier.is_empty() && gate.is_empty();
  384. let mut pieces: Vec<(Vec<ValueWait>, Detached)> = earlier
  385. .into_iter()
  386. .map(|part| {
  387. (
  388. part.waits,
  389. Detached {
  390. host: part.host,
  391. _uploads: Vec::new(),
  392. _state: Default::default(),
  393. },
  394. )
  395. })
  396. .collect();
  397. pieces.push((
  398. gate,
  399. Detached {
  400. host,
  401. _uploads: uploads,
  402. _state: state,
  403. },
  404. ));
  405. let mut last = None;
  406. for (waits, detached) in pieces {
  407. if !waits.is_empty() {
  408. parts.push((waits, Vec::new(), Vec::new()));
  409. }
  410. let entry = parts.len() - 1;
  411. let (_, taken, order) = &mut parts[entry];
  412. let place = taken.len();
  413. order.push(place);
  414. taken.push(detached);
  415. last = Some((entry, place));
  416. }
  417. seen.push((this, if single { last } else { None }));
  418. }
  419. // (The first entry is empty if the first list begins with a wait.)
  420. parts.retain(|(_, taken, _)| !taken.is_empty());
  421. parts
  422. }
  423. /// Takes the host sides of submitted lists (each once, however often the
  424. /// submission names it) and leaves each list a new, closed host list for
  425. /// its next reset: what was taken, and which of them run in what order.
  426. #[cfg(windows)]
  427. pub(crate) fn detach(lists: &[This]) -> (Vec<Detached>, Vec<usize>) {
  428. let mut taken: Vec<(This, Detached)> = Vec::new();
  429. let mut order = Vec::new();
  430. for &this in lists {
  431. if this.is_null() {
  432. continue;
  433. }
  434. if let Some(i) = taken.iter().position(|(t, _)| *t == this) {
  435. order.push(i);
  436. continue;
  437. }
  438. let Some(fresh) = fresh_list() else {
  439. continue;
  440. };
  441. // A new host list is open; the title's next call on its list is a
  442. // reset, which wants it closed.
  443. fresh.close();
  444. let list = this.cast_mut().cast::<List>();
  445. // SAFETY: one of our lists, closed and submitted: nothing records
  446. // into it until the title resets it.
  447. let (host, uploads, state) = unsafe {
  448. let Some(host) = (*list).host.replace(fresh) else {
  449. continue;
  450. };
  451. let uploads =
  452. std::mem::take(&mut *(*list).uploads.lock().unwrap_or_else(|e| e.into_inner()));
  453. let state =
  454. std::mem::take(&mut *(*list).state.lock().unwrap_or_else(|e| e.into_inner()));
  455. (host, uploads, state)
  456. };
  457. order.push(taken.len());
  458. taken.push((
  459. this,
  460. Detached {
  461. host,
  462. _uploads: uploads,
  463. _state: state,
  464. },
  465. ));
  466. }
  467. (taken.into_iter().map(|(_, d)| d).collect(), order)
  468. }
  469. pub(crate) extern "system" fn create_allocator(
  470. _: This,
  471. kind: u32,
  472. iid: *const Iid,
  473. out: *mut This,
  474. ) -> HRESULT {
  475. let allocator = Box::new(Allocator {
  476. object: Object::new(&ALLOCATOR_FUNCTIONS),
  477. kind,
  478. });
  479. object::hand_out(ALLOCATOR, allocator, iid, &ALLOCATOR_IIDS, out)
  480. }
  481. /// Lists start open, as in D3D12.
  482. pub(crate) extern "system" fn create_list(
  483. _: This,
  484. _nodes: u32,
  485. kind: u32,
  486. allocator: This,
  487. pipeline: This,
  488. iid: *const Iid,
  489. out: *mut This,
  490. ) -> HRESULT {
  491. new_list(kind, allocator, pipeline, iid, out)
  492. }
  493. /// The console's list creation: type, flags, node mask and barrier batch
  494. /// size in a description.
  495. #[repr(C)]
  496. #[derive(Debug)]
  497. pub(crate) struct ListDesc {
  498. kind: u32,
  499. flags: u32,
  500. nodes: u32,
  501. barrier_batch: u32,
  502. }
  503. pub(crate) extern "system" fn create_list_x(
  504. _: This,
  505. desc: *const ListDesc,
  506. allocator: This,
  507. pipeline: This,
  508. iid: *const Iid,
  509. out: *mut This,
  510. ) -> HRESULT {
  511. // SAFETY: the title passes a description (null is tolerated).
  512. let Some(desc) = (unsafe { desc.as_ref() }) else {
  513. return E_INVALIDARG;
  514. };
  515. tracing::debug!(?desc, "console command list");
  516. new_list(desc.kind, allocator, pipeline, iid, out)
  517. }
  518. /// `pipeline` is the list's initial pipeline (null: none), bound until the
  519. /// title sets another, as after a reset.
  520. fn new_list(
  521. kind: u32,
  522. allocator: This,
  523. pipeline: This,
  524. iid: *const Iid,
  525. out: *mut This,
  526. ) -> HRESULT {
  527. if allocator.is_null() {
  528. return E_INVALIDARG;
  529. }
  530. tracing::debug!(kind, "command list");
  531. let list = Box::new(List {
  532. object: if crate::device::newer() {
  533. Object::new(&NEWER_LIST_FUNCTIONS)
  534. } else {
  535. Object::new(&LIST_FUNCTIONS)
  536. },
  537. kind,
  538. put: [0; 5],
  539. reserved: [0; 64],
  540. graphics_root_headers: [0; 128],
  541. compute_root_headers: [0; 128],
  542. pipeline_shadow: [0; 8],
  543. newer: [0; 256],
  544. uploads: Default::default(),
  545. #[cfg(windows)]
  546. host: crate::host::host().and_then(|h| match h.new_list() {
  547. Ok(list) => Some(list),
  548. Err(e) => {
  549. tracing::warn!(error = %e, "no host command list");
  550. None
  551. }
  552. }),
  553. #[cfg(windows)]
  554. state: {
  555. let mut state = crate::draw::State::default();
  556. state.set_pipeline(pipeline);
  557. std::sync::Mutex::new(state)
  558. },
  559. #[cfg(windows)]
  560. earlier: Vec::new(),
  561. #[cfg(windows)]
  562. gate: Vec::new(),
  563. });
  564. #[cfg(not(windows))]
  565. let _ = pipeline;
  566. object::hand_out(LIST, list, iid, &LIST_IIDS, out)
  567. }
  568. extern "system" fn allocator_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  569. let found = object::is(iid, &ALLOCATOR_IIDS).then_some(this);
  570. object::answer(ALLOCATOR, iid, found, out)
  571. }
  572. extern "system" fn allocator_release(this: This) -> u32 {
  573. object::release_boxed::<Allocator>(this)
  574. }
  575. /// Nothing is recorded, so there is nothing to free.
  576. extern "system" fn allocator_reset(_: This) -> HRESULT {
  577. S_OK
  578. }
  579. extern "system" fn list_query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  580. object::answer(LIST, iid, object::is(iid, &LIST_IIDS).then_some(this), out)
  581. }
  582. extern "system" fn list_release(this: This) -> u32 {
  583. object::release_boxed::<List>(this)
  584. }
  585. extern "system" fn list_type(this: This) -> u32 {
  586. // SAFETY: `this` is one of our lists.
  587. unsafe { (*this.cast::<List>()).kind }
  588. }
  589. extern "system" fn close(this: This) -> HRESULT {
  590. #[cfg(windows)]
  591. if let Some(host) = host_list(this) {
  592. host.close();
  593. }
  594. S_OK
  595. }
  596. extern "system" fn reset(this: This, allocator: This, pipeline: This) -> HRESULT {
  597. if allocator.is_null() {
  598. return E_INVALIDARG;
  599. }
  600. // A wait recorded and never submitted goes with the recording.
  601. VALUE_WAITS
  602. .lock()
  603. .unwrap_or_else(|e| e.into_inner())
  604. .retain(|&(list, _)| list != this as usize);
  605. // Every submission of the list has run (submissions are waited for).
  606. // SAFETY: the title passes one of our lists.
  607. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  608. uploads.lock().unwrap_or_else(|e| e.into_inner()).clear();
  609. // The parts of a recording that was cut and never submitted go with it
  610. // (a submission takes the parts it runs).
  611. #[cfg(windows)]
  612. {
  613. // SAFETY: the title passes one of our lists, and neither records
  614. // into it nor submits it during its reset.
  615. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  616. list.earlier.clear();
  617. list.gate.clear();
  618. }
  619. #[cfg(windows)]
  620. with_state(this, |host, state| {
  621. host.reset();
  622. state.reset(pipeline);
  623. });
  624. #[cfg(not(windows))]
  625. let _ = (this, pipeline);
  626. S_OK
  627. }
  628. /// A resource barrier as titles pass it: type, flags, then a resource and
  629. /// either a subresource and two states (transition) or a second resource
  630. /// (aliasing). The same layout as the host's.
  631. #[repr(C)]
  632. #[derive(Clone, Copy)]
  633. pub(crate) struct Barrier {
  634. kind: u32,
  635. flags: u32,
  636. first: This,
  637. second: u64,
  638. last: u64,
  639. }
  640. /// The barrier on host resources, or `None` if it names a resource the host
  641. /// GPU does not have (buffers so far).
  642. #[cfg(windows)]
  643. fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
  644. use windows::core::Interface;
  645. let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
  646. match b.kind {
  647. 0 => {
  648. // A split barrier's first half: its second half transitions.
  649. const BEGIN_ONLY: u32 = 1;
  650. if b.flags & BEGIN_ONLY != 0 {
  651. return None;
  652. }
  653. // shortcut: whole resources, from the state the list tracked
  654. // (`HostList::transition`); subresources are not told apart.
  655. let wanted = crate::host::texture_state(b.last as u32);
  656. let (texture, before) = list.transition(b.first, wanted)?;
  657. Some(Barrier {
  658. kind: 0,
  659. flags: 0,
  660. first: texture.as_raw().cast_const().cast(),
  661. second: 0xffff_ffff | (u64::from(before) << 32),
  662. last: u64::from(crate::host::legal_state(texture, wanted)),
  663. })
  664. }
  665. 1 => Some(Barrier {
  666. first: if b.first.is_null() {
  667. b.first
  668. } else {
  669. host(b.first)?
  670. },
  671. second: if b.second == 0 {
  672. 0
  673. } else {
  674. host(b.second as This)? as u64
  675. },
  676. ..*b
  677. }),
  678. 2 => Some(Barrier {
  679. first: if b.first.is_null() {
  680. b.first
  681. } else {
  682. // A depth texture's unordered access is its colour twin's
  683. // (the host gives the depth texture none): the barrier is
  684. // on the texture shaders write.
  685. match crate::resource::twin_resource(b.first) {
  686. Some(twin) => twin.as_raw().cast_const().cast(),
  687. None => host(b.first)?,
  688. }
  689. },
  690. ..*b
  691. }),
  692. _ => None,
  693. }
  694. }
  695. /// An unordered access barrier on every resource: earlier shader writes
  696. /// finish before later work reads or writes.
  697. const UAV_BARRIER: Barrier = Barrier {
  698. kind: 2,
  699. flags: 0,
  700. first: std::ptr::null(),
  701. second: 0,
  702. last: 0,
  703. };
  704. /// Returns the console's barrier "actions" (none).
  705. extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
  706. #[cfg(windows)]
  707. if let Some(list) = host_list(this)
  708. && !barriers.is_null()
  709. {
  710. if count > 0 {
  711. with_state(this, |_, state| state.synced());
  712. }
  713. // SAFETY: the title passes `count` barriers.
  714. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
  715. let mut host: Vec<Barrier> = barriers
  716. .iter()
  717. .filter_map(|b| host_barrier(list, b))
  718. .collect();
  719. // Buffers have host copies, not resources the barrier can name:
  720. // a barrier on one waits for every shader write before it.
  721. if barriers.iter().any(|b| {
  722. b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
  723. }) {
  724. host.push(UAV_BARRIER);
  725. #[cfg(feature = "diagnostics")]
  726. crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1);
  727. }
  728. if !host.is_empty() {
  729. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  730. const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
  731. // SAFETY: the same layout; borrowed resource pointers, never
  732. // released through this slice.
  733. let host = unsafe {
  734. std::slice::from_raw_parts(
  735. host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
  736. host.len(),
  737. )
  738. };
  739. // SAFETY: an open list and live resources.
  740. unsafe { list.list.ResourceBarrier(host) };
  741. }
  742. }
  743. 0
  744. }
  745. /// Moves a title texture's host copy to `state` in the list, if needed.
  746. #[cfg(windows)]
  747. pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
  748. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  749. if let Some((texture, before)) = list.transition(resource, state) {
  750. let state = crate::host::legal_state(texture, state);
  751. let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
  752. // SAFETY: an open list and a live texture.
  753. unsafe { list.list.ResourceBarrier(&[barrier]) };
  754. }
  755. }
  756. #[cfg(windows)]
  757. const COPY_DEST: u32 = 0x400;
  758. #[cfg(windows)]
  759. const COPY_SOURCE: u32 = 0x800;
  760. /// `len` bytes at `offset` of a title buffer, if they are inside it.
  761. #[cfg(windows)]
  762. fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
  763. let (data, size) = crate::resource::buffer_bytes(buffer)?;
  764. let end = offset.checked_add(len)?;
  765. if end > size {
  766. tracing::warn!(offset, len, size, "copy outside its buffer");
  767. return None;
  768. }
  769. // SAFETY: inside the buffer, checked above.
  770. Some(unsafe { data.add(offset as usize) })
  771. }
  772. /// Buffer to buffer: both are host memory, copied at submission.
  773. extern "system" fn copy_buffer_region(
  774. this: This,
  775. dst: This,
  776. dst_offset: u64,
  777. src: This,
  778. src_offset: u64,
  779. len: u64,
  780. ) {
  781. #[cfg(windows)]
  782. if let Some(list) = host_list(this)
  783. && let Some(to) = buffer_range(dst, dst_offset, len)
  784. && let Some(from) = buffer_range(src, src_offset, len)
  785. {
  786. list.defer_copy(to, from, len as usize);
  787. }
  788. #[cfg(not(windows))]
  789. let _ = (this, dst, dst_offset, src, src_offset, len);
  790. }
  791. /// Whether one of two resources is a target in a stand-in format and the
  792. /// other is not ([`crate::resource::target_format`]): their texels differ
  793. /// in size, so the host cannot copy between them (logged once).
  794. #[cfg(windows)]
  795. fn unlike(dst: This, src: This) -> bool {
  796. let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src);
  797. if unlike {
  798. static ONCE: std::sync::Once = std::sync::Once::new();
  799. ONCE.call_once(|| {
  800. tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped")
  801. });
  802. }
  803. unlike
  804. }
  805. extern "system" fn copy_resource(this: This, dst: This, src: This) {
  806. #[cfg(windows)]
  807. {
  808. let Some(list) = host_list(this) else {
  809. return;
  810. };
  811. if let (Some(to), Some(from)) = (
  812. crate::resource::host_resource(dst),
  813. crate::resource::host_resource(src),
  814. ) {
  815. if unlike(dst, src) {
  816. return;
  817. }
  818. // A source the title fills itself is uploaded first (upstream
  819. // PR #671): a copy read whatever the host texture held.
  820. if crate::texture::title_written(from) {
  821. crate::texture::upload(list, src, from);
  822. }
  823. // Depth textures shaders also write: what they wrote, first.
  824. list.twin_use(dst, false, true);
  825. list.twin_use(src, false, false);
  826. // A destination made level by level gets its levels' memory
  827. // ahead of this list (`crate::tiles`).
  828. crate::texture::card_writes(list, dst, to, None);
  829. ensure_state(list, dst, COPY_DEST);
  830. ensure_state(list, src, COPY_SOURCE);
  831. crate::texture::host_written(dst);
  832. #[cfg(feature = "diagnostics")]
  833. list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
  834. // SAFETY: an open list and live textures.
  835. unsafe { list.list.CopyResource(to, from) };
  836. } else if let (Some((to, a)), Some((from, b))) = (
  837. crate::resource::buffer_bytes(dst),
  838. crate::resource::buffer_bytes(src),
  839. ) {
  840. list.defer_copy(to, from, a.min(b) as usize);
  841. }
  842. }
  843. #[cfg(not(windows))]
  844. let _ = (this, dst, src);
  845. }
  846. extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
  847. copy_resource(this, dst, src);
  848. }
  849. /// A copy location as titles pass it, laid out as the host's: a resource,
  850. /// then a subresource index (type 0) or a placed footprint (type 1).
  851. #[repr(C)]
  852. #[derive(Clone, Copy)]
  853. pub(crate) struct CopyLocation {
  854. resource: This,
  855. kind: u32,
  856. footprint: crate::resource::PlacedFootprint,
  857. }
  858. /// Texture to texture on the GPU; buffer to texture through an upload
  859. /// buffer filled at submission. Texture to buffer (read back) is not done
  860. /// yet.
  861. extern "system" fn copy_texture_region(
  862. this: This,
  863. dst: *const CopyLocation,
  864. x: u32,
  865. y: u32,
  866. z: u32,
  867. src: *const CopyLocation,
  868. source_box: *const [u32; 6],
  869. ) {
  870. #[cfg(windows)]
  871. {
  872. use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
  873. use windows::core::Interface;
  874. const FOOTPRINT: u32 = 1;
  875. // SAFETY: the title passes both locations (null is tolerated).
  876. let (Some(list), Some(&dst), Some(&src)) =
  877. (host_list(this), unsafe { dst.as_ref() }, unsafe {
  878. src.as_ref()
  879. })
  880. else {
  881. return;
  882. };
  883. let Some(to) = crate::resource::host_resource(dst.resource) else {
  884. // Texture to buffer: a read back. The list copies the texels
  885. // into a host buffer of ours; once it has run they go to the
  886. // title's buffer (`HostList::defer_read_back`).
  887. // The title reads two tiny float targets back every frame (5x1
  888. // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer
  889. // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as
  890. // before.
  891. static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  892. let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  893. let made = read_back(list, dst, x, y, z, src, source_box);
  894. if n <= 16 || n.is_multiple_of(4096) || made.is_err() {
  895. static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  896. if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 {
  897. return;
  898. }
  899. let source = crate::resource::host_resource(src.resource).map(|r| {
  900. // SAFETY: a live resource.
  901. let d = unsafe { r.GetDesc() };
  902. format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels)
  903. });
  904. tracing::info!(
  905. copies = n,
  906. made = ?made,
  907. source = ?source,
  908. source_kind = src.kind,
  909. destination_kind = dst.kind,
  910. destination_offset = dst.footprint.offset,
  911. destination_bytes = ?dst.footprint.bytes(),
  912. "a texture to buffer copy (a read back)"
  913. );
  914. }
  915. return;
  916. };
  917. if unlike(dst.resource, src.resource) {
  918. return;
  919. }
  920. let mut from = src;
  921. let _upload; // keeps the source alive while this call records it
  922. #[cfg(feature = "diagnostics")]
  923. let mut read = None;
  924. if src.kind == FOOTPRINT {
  925. let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
  926. return;
  927. };
  928. let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
  929. return;
  930. };
  931. let Some((buffer, staging)) = list.upload(host, bytes) else {
  932. return;
  933. };
  934. // The list owns this mapped D3D12 upload buffer. Wine can report
  935. // its address as MEM_FREE, so use the host-upload path.
  936. list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
  937. from.resource = buffer.as_raw().cast_const().cast();
  938. from.footprint.offset = 0;
  939. #[cfg(feature = "diagnostics")]
  940. {
  941. // SAFETY: a live buffer.
  942. read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
  943. }
  944. _upload = buffer;
  945. } else {
  946. let Some(texture) = crate::resource::host_resource(src.resource) else {
  947. return;
  948. };
  949. list.twin_use(src.resource, false, false);
  950. if crate::texture::title_written(texture) {
  951. crate::texture::upload(list, src.resource, texture);
  952. }
  953. ensure_state(list, src.resource, COPY_SOURCE);
  954. from.resource = texture.as_raw().cast_const().cast();
  955. }
  956. // A depth texture shaders also write: what they wrote, first (the
  957. // source above too).
  958. list.twin_use(dst.resource, false, true);
  959. // A destination made level by level gets the level's memory ahead
  960. // of this list (`crate::tiles`): the title's bake copies each level
  961. // of its result into a block-compressed texture of that kind, and
  962. // a copy into a level without memory is dropped.
  963. crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32));
  964. ensure_state(list, dst.resource, COPY_DEST);
  965. crate::texture::host_written(dst.resource);
  966. let mut to_location = dst;
  967. to_location.resource = to.as_raw().cast_const().cast();
  968. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  969. #[cfg(feature = "diagnostics")]
  970. {
  971. let text = || {
  972. // SAFETY: a live texture; the box is the title's or null.
  973. let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
  974. format!(
  975. "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
  976. dst.resource,
  977. d.Width,
  978. d.Height,
  979. d.Format.0,
  980. dst.kind,
  981. src.resource,
  982. src.kind,
  983. (src.kind == FOOTPRINT).then_some(src.footprint)
  984. )
  985. };
  986. match read {
  987. Some(range) => list.note_read(text, range),
  988. None => list.note_op(text),
  989. }
  990. }
  991. const _: () =
  992. assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
  993. // SAFETY: an open list; both locations in the host's layout, naming
  994. // live resources; the box is the title's (same layout).
  995. unsafe {
  996. list.list.CopyTextureRegion(
  997. (&raw const to_location).cast(),
  998. x,
  999. y,
  1000. z,
  1001. (&raw const from).cast(),
  1002. host_box,
  1003. )
  1004. };
  1005. }
  1006. #[cfg(not(windows))]
  1007. let _ = (this, dst, x, y, z, src, source_box);
  1008. }
  1009. /// Records a texture to buffer copy (a read back) of [`copy_texture_region`]
  1010. /// into `list`, or says why not.
  1011. #[cfg(windows)]
  1012. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1013. fn read_back(
  1014. list: &crate::host::HostList,
  1015. dst: CopyLocation,
  1016. x: u32,
  1017. y: u32,
  1018. z: u32,
  1019. src: CopyLocation,
  1020. source_box: *const [u32; 6],
  1021. ) -> Result<(), &'static str> {
  1022. use windows::Win32::Graphics::Direct3D12::D3D12_BOX;
  1023. use windows::core::Interface;
  1024. const FOOTPRINT: u32 = 1;
  1025. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1026. if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) {
  1027. return Err("switched off");
  1028. }
  1029. if dst.kind != FOOTPRINT || src.kind == FOOTPRINT {
  1030. return Err("not a texture subresource into a placed footprint");
  1031. }
  1032. if (x, y, z) != (0, 0, 0) {
  1033. return Err("a destination corner other than the footprint's");
  1034. }
  1035. let host = crate::host::host().ok_or("no host")?;
  1036. let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?;
  1037. // The title's buffer holds every row at its own pitch.
  1038. let bytes = pitch * (rows - 1) + row;
  1039. let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?;
  1040. let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?;
  1041. let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?;
  1042. // As a texture source of any copy: what shaders wrote to a depth twin
  1043. // and what the title wrote itself first, then the state.
  1044. list.twin_use(src.resource, false, false);
  1045. if crate::texture::title_written(texture) {
  1046. crate::texture::upload(list, src.resource, texture);
  1047. }
  1048. ensure_state(list, src.resource, COPY_SOURCE);
  1049. let mut from = src;
  1050. from.resource = texture.as_raw().cast_const().cast();
  1051. let mut to = dst;
  1052. to.resource = buffer.as_raw().cast_const().cast();
  1053. to.footprint = footprint;
  1054. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  1055. #[cfg(feature = "diagnostics")]
  1056. list.note_op(|| {
  1057. format!(
  1058. "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes",
  1059. src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset
  1060. )
  1061. });
  1062. // SAFETY: an open list; both locations in the host's layout (asserted
  1063. // in `copy_texture_region`), naming a live texture and our buffer, which
  1064. // the list keeps until it is reset; the box is the title's.
  1065. unsafe {
  1066. list.list
  1067. .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box)
  1068. };
  1069. list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]);
  1070. Ok(())
  1071. }
  1072. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1073. extern "system" fn copy_texture_region_x(
  1074. this: This,
  1075. dst: *const CopyLocation,
  1076. x: u32,
  1077. y: u32,
  1078. z: u32,
  1079. src: *const CopyLocation,
  1080. source_box: *const [u32; 6],
  1081. _flags: u32,
  1082. ) {
  1083. copy_texture_region(this, dst, x, y, z, src, source_box);
  1084. }
  1085. extern "system" fn resolve(
  1086. this: This,
  1087. dst: This,
  1088. dst_sub: u32,
  1089. src: This,
  1090. src_sub: u32,
  1091. format: u32,
  1092. ) {
  1093. #[cfg(windows)]
  1094. if let Some(list) = host_list(this)
  1095. && let (Some(to), Some(from)) = (
  1096. crate::resource::host_resource(dst),
  1097. crate::resource::host_resource(src),
  1098. )
  1099. {
  1100. use windows::Win32::Foundation::RECT;
  1101. use windows::Win32::Graphics::Direct3D12::{
  1102. D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
  1103. };
  1104. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  1105. use windows::core::Interface;
  1106. const RESOLVE_DEST: u32 = 0x1000;
  1107. const RESOLVE_SOURCE: u32 = 0x2000;
  1108. if unlike(dst, src) {
  1109. return;
  1110. }
  1111. // Depth textures shaders also write: what they wrote, first.
  1112. list.twin_use(dst, false, true);
  1113. list.twin_use(src, false, false);
  1114. // As for a copy (`crate::tiles`).
  1115. crate::texture::card_writes(list, dst, to, Some(dst_sub));
  1116. ensure_state(list, dst, RESOLVE_DEST);
  1117. ensure_state(list, src, RESOLVE_SOURCE);
  1118. crate::texture::host_written(dst);
  1119. #[cfg(feature = "diagnostics")]
  1120. list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
  1121. // SAFETY: an open list and live textures; the region is inside both.
  1122. unsafe {
  1123. let (a, b) = (to.GetDesc(), from.GetDesc());
  1124. let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) };
  1125. if (a.Width, a.Height) == (b.Width, b.Height) {
  1126. list.list
  1127. .ResolveSubresource(to, dst_sub, from, src_sub, format);
  1128. } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
  1129. // The console clips a larger source to the destination.
  1130. let rect = RECT {
  1131. left: 0,
  1132. top: 0,
  1133. right: a.Width.min(b.Width) as i32,
  1134. bottom: a.Height.min(b.Height) as i32,
  1135. };
  1136. list1.ResolveSubresourceRegion(
  1137. to,
  1138. dst_sub,
  1139. 0,
  1140. 0,
  1141. from,
  1142. src_sub,
  1143. Some(&rect),
  1144. format,
  1145. D3D12_RESOLVE_MODE_AVERAGE,
  1146. );
  1147. }
  1148. }
  1149. }
  1150. #[cfg(not(windows))]
  1151. let _ = (this, dst, dst_sub, src, src_sub, format);
  1152. }
  1153. #[repr(C)]
  1154. pub(crate) struct Rect {
  1155. left: i32,
  1156. top: i32,
  1157. right: i32,
  1158. bottom: i32,
  1159. }
  1160. extern "system" fn clear_rtv(
  1161. this: This,
  1162. handle: u64,
  1163. color: *const [f32; 4],
  1164. count: u32,
  1165. rects: *const Rect,
  1166. ) {
  1167. #[cfg(windows)]
  1168. {
  1169. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
  1170. else {
  1171. return;
  1172. };
  1173. let (Some(texture), Some(host)) = (
  1174. crate::resource::host_resource(record.resource),
  1175. crate::host::host(),
  1176. ) else {
  1177. return;
  1178. };
  1179. // SAFETY: the title passes four floats (null is tolerated).
  1180. let Some(color) = (unsafe { color.as_ref() }) else {
  1181. return;
  1182. };
  1183. let rects = (count > 0 && !rects.is_null()).then(|| {
  1184. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1185. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1186. });
  1187. const RENDER_TARGET: u32 = 0x4;
  1188. let rtv = host.rtv(Some(texture), record.desc().as_ref());
  1189. // SAFETY: an open list, a fresh view of a live texture.
  1190. unsafe {
  1191. if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
  1192. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  1193. list.list.ResourceBarrier(&[crate::host::transition(
  1194. texture,
  1195. State(before as i32),
  1196. State(RENDER_TARGET as i32),
  1197. )]);
  1198. }
  1199. list.list.ClearRenderTargetView(rtv, color, rects);
  1200. }
  1201. }
  1202. #[cfg(not(windows))]
  1203. let _ = (this, handle, color, count, rects);
  1204. }
  1205. /// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
  1206. /// flags: 1 depth, 2 stencil.
  1207. extern "system" fn clear_dsv(
  1208. this: This,
  1209. handle: u64,
  1210. flags: u32,
  1211. depth: f32,
  1212. stencil: u8,
  1213. count: u32,
  1214. rects: *const Rect,
  1215. ) {
  1216. #[cfg(windows)]
  1217. {
  1218. use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
  1219. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
  1220. else {
  1221. return;
  1222. };
  1223. let (Some(texture), Some(host)) = (
  1224. crate::resource::host_resource(record.resource),
  1225. crate::host::host(),
  1226. ) else {
  1227. return;
  1228. };
  1229. let rects = (count > 0 && !rects.is_null()).then(|| {
  1230. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1231. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1232. });
  1233. const DEPTH_WRITE: u32 = 0x10;
  1234. // A depth texture shaders also write: what they wrote, first (the
  1235. // clear may be of one slice or of some rectangles).
  1236. list.twin_use(record.resource, false, true);
  1237. ensure_state(list, record.resource, DEPTH_WRITE);
  1238. if crate::resource::depth_and_unordered(record.resource) {
  1239. crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1240. }
  1241. let dsv = host.dsv(texture, record.depth_desc().as_ref());
  1242. // SAFETY: an open list, a fresh view of a live texture.
  1243. unsafe {
  1244. list.list
  1245. .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
  1246. };
  1247. }
  1248. #[cfg(not(windows))]
  1249. let _ = (this, handle, flags, depth, stencil, count, rects);
  1250. }
  1251. /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
  1252. /// are title memory, copied at submission like buffer copies (if mapped).
  1253. extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
  1254. #[cfg(windows)]
  1255. if let Some(list) = host_list(this)
  1256. && dst != 0
  1257. && src != 0
  1258. {
  1259. let len = len as usize;
  1260. list.defer(move || {
  1261. if crate::texture::committed(src as *const u8, len)
  1262. && crate::texture::committed(dst as *const u8, len)
  1263. {
  1264. // SAFETY: both ranges are committed title memory.
  1265. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
  1266. }
  1267. });
  1268. }
  1269. #[cfg(not(windows))]
  1270. let _ = (this, dst, src, len);
  1271. }
  1272. /// `DriverHintX(feature, value)`: no hints for the host.
  1273. extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
  1274. 0
  1275. }
  1276. /// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
  1277. /// host has no use for (the ray-tracing builder dispatches this way).
  1278. extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
  1279. #[cfg(windows)]
  1280. state::dispatch(this, x, y, z);
  1281. #[cfg(not(windows))]
  1282. {
  1283. let _ = (this, x, y, z);
  1284. count_dispatch();
  1285. }
  1286. }
  1287. /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
  1288. /// resolved.
  1289. extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
  1290. /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
  1291. /// each query's result into the buffer once the list has run. Timestamps
  1292. /// (type 2) are the GPU clock then; occlusion counts (0) say a million
  1293. /// samples passed and binary occlusion (1) visible, so nothing is culled
  1294. /// by a query.
  1295. /// shortcut: no query runs on the host GPU; results are plausible values,
  1296. /// not measured ones (time spans come out as the submission's length).
  1297. extern "system" fn resolve_queries(
  1298. this: This,
  1299. _heap: This,
  1300. kind: u32,
  1301. _first: u32,
  1302. count: u32,
  1303. buffer: This,
  1304. offset: u64,
  1305. ) {
  1306. const OCCLUSION: u32 = 0;
  1307. const BINARY: u32 = 1;
  1308. const TIMESTAMP: u32 = 2;
  1309. const PIPELINE_STATISTICS: u32 = 3;
  1310. let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
  1311. return;
  1312. };
  1313. let (what, bytes) = match kind {
  1314. OCCLUSION => (Written::Value(1 << 20), 8),
  1315. BINARY => (Written::Value(1), 8),
  1316. TIMESTAMP => (Written::GpuTimestamp, 8),
  1317. PIPELINE_STATISTICS => (Written::Value(0), 88),
  1318. _ => (Written::Value(0), 16),
  1319. };
  1320. let Some(end) = offset.checked_add(u64::from(count) * bytes) else {
  1321. return;
  1322. };
  1323. if end > size {
  1324. return;
  1325. }
  1326. for i in 0..u64::from(count) {
  1327. // Wider results are written as 8-byte pieces.
  1328. for piece in 0..bytes / 8 {
  1329. // SAFETY: inside the buffer, checked above.
  1330. let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
  1331. let what = if piece == 0 { what } else { Written::Value(0) };
  1332. defer_write(this, at as u64, what, 8);
  1333. }
  1334. }
  1335. }
  1336. /// IUnknown 3, object 4, device child 1, allocator 2.
  1337. static ALLOCATOR_FUNCTIONS: Table<24> = {
  1338. let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
  1339. f[0] = allocator_query as *const ();
  1340. f[2] = allocator_release as *const ();
  1341. f[7] = object::parent_device as *const (); // 0x38
  1342. f[8] = allocator_reset as *const (); // 0x40
  1343. f[9] = object::ignore as *const (); // 0x48 allocation callback
  1344. Table(f)
  1345. };
  1346. extern "system" fn set_pipeline(this: This, pipeline: This) {
  1347. crate::pipeline::bound(pipeline);
  1348. #[cfg(windows)]
  1349. with_state(this, |_, state| state.set_pipeline(pipeline));
  1350. #[cfg(not(windows))]
  1351. let _ = this;
  1352. }
  1353. /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
  1354. /// bottom of the pipe `(flags, control, address, size)`. The host orders
  1355. /// nothing between dispatches by itself: what shaders wrote is waited for
  1356. /// here as at the title's barriers (the ray-tracing structure builder has
  1357. /// no other wait between its stages).
  1358. /// (Arguments may be what earlier shaders wrote from here on:
  1359. /// `State::synced`.)
  1360. extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size: u64) {
  1361. #[cfg(windows)]
  1362. {
  1363. with_state(this, |_, state| state.synced());
  1364. if let Some(list) = host_list(this) {
  1365. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1366. #[cfg(feature = "diagnostics")]
  1367. {
  1368. // The shapes of the title's calls, each once.
  1369. static SEEN: std::sync::Mutex<Vec<(u32, u32, bool)>> = std::sync::Mutex::new(Vec::new());
  1370. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1371. let shape = (flags, control, address == 0);
  1372. if seen.len() < 64 && !seen.contains(&shape) {
  1373. seen.push(shape);
  1374. tracing::info!(
  1375. flags = format_args!("{flags:#x}"),
  1376. control = format_args!("{control:#x}"),
  1377. address = format_args!("{address:#x}"),
  1378. size = format_args!("{size:#x}"),
  1379. "a pipeline sync"
  1380. );
  1381. }
  1382. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1383. }
  1384. // SAFETY: the same layout; no resource named.
  1385. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1386. // SAFETY: an open list.
  1387. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1388. }
  1389. }
  1390. let _ = (this, flags, control, address, size);
  1391. }
  1392. /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
  1393. /// tune the console's command memory.
  1394. extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  1395. reset(this, allocator, pipeline)
  1396. }
  1397. /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
  1398. /// owns until it is reset, which the CPU writes and the GPU reads at the
  1399. /// same address; null on failure. The title's BVH builder puts
  1400. /// its instance descriptions there (and wrote through our old
  1401. /// `E_NOTIMPL` as a pointer).
  1402. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  1403. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  1404. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  1405. return std::ptr::null_mut();
  1406. };
  1407. if this.is_null() || !align.is_power_of_two() {
  1408. return std::ptr::null_mut();
  1409. }
  1410. let mut block = vec![0u8; len];
  1411. let start = block.as_mut_ptr();
  1412. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  1413. let at = unsafe { start.add(start.align_offset(align)) };
  1414. // SAFETY: the title passes one of our lists.
  1415. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  1416. // Moving the vector keeps its heap block where it is.
  1417. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
  1418. at
  1419. }
  1420. /// Draw state the host has no use for (root signatures: ours come with
  1421. /// the pipeline; depth order and shading rate hints): any arguments,
  1422. /// nothing returned.
  1423. extern "system" fn ignored_state(_: This) {}
  1424. /// The title's draw state (decision 0007, step 3), kept for its draws or
  1425. /// set on the host list at once. Without a host GPU these do nothing.
  1426. #[cfg(windows)]
  1427. mod state {
  1428. use super::{This, with_state};
  1429. use crate::draw::{IndexView, VertexView};
  1430. use windows::Win32::Foundation::RECT;
  1431. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  1432. /// `count` items at `items`, or none.
  1433. fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
  1434. if items.is_null() || count == 0 {
  1435. return &[];
  1436. }
  1437. // SAFETY: the title passes `count` items.
  1438. unsafe { std::slice::from_raw_parts(items, count as usize) }
  1439. }
  1440. pub(super) extern "system" fn topology(this: This, topology: u32) {
  1441. with_state(this, |list, s| s.set_topology(list, topology));
  1442. }
  1443. pub(super) extern "system" fn viewports(
  1444. this: This,
  1445. count: u32,
  1446. viewports: *const D3D12_VIEWPORT,
  1447. ) {
  1448. // (Through the draw state, which keeps them for the host list
  1449. // that continues this one after a cut: `State::replay`.)
  1450. with_state(this, |list, s| s.set_viewports(list, items(viewports, count)));
  1451. }
  1452. pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
  1453. with_state(this, |list, s| s.set_scissors(list, items(rects, count)));
  1454. }
  1455. pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  1456. with_state(this, |list, s| {
  1457. // SAFETY: the title passes four floats or null.
  1458. s.set_blend_factor(list, unsafe { factor.as_ref() })
  1459. });
  1460. }
  1461. pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
  1462. with_state(this, |list, s| s.set_stencil_ref(list, reference));
  1463. }
  1464. pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) {
  1465. with_state(this, |list, s| s.set_depth_bounds(list, min, max));
  1466. }
  1467. pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
  1468. with_state(this, |_, s| s.set_heaps(items(heaps, count)));
  1469. }
  1470. pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
  1471. with_state(this, |_, s| s.set_table(true, slot, handle));
  1472. }
  1473. pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
  1474. with_state(this, |_, s| s.set_table(false, slot, handle));
  1475. }
  1476. pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
  1477. with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
  1478. }
  1479. pub(super) extern "system" fn graphics_constant(
  1480. this: This,
  1481. slot: u32,
  1482. value: u32,
  1483. offset: u32,
  1484. ) {
  1485. with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
  1486. }
  1487. pub(super) extern "system" fn compute_constants(
  1488. this: This,
  1489. slot: u32,
  1490. count: u32,
  1491. values: *const u32,
  1492. offset: u32,
  1493. ) {
  1494. with_state(this, |_, s| {
  1495. s.set_constants(true, slot, items(values, count), offset)
  1496. });
  1497. }
  1498. pub(super) extern "system" fn graphics_constants(
  1499. this: This,
  1500. slot: u32,
  1501. count: u32,
  1502. values: *const u32,
  1503. offset: u32,
  1504. ) {
  1505. with_state(this, |_, s| {
  1506. s.set_constants(false, slot, items(values, count), offset)
  1507. });
  1508. }
  1509. /// Root constant buffer, shader resource and unordered access views.
  1510. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
  1511. with_state(this, |_, s| s.set_view(true, slot, address));
  1512. }
  1513. pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
  1514. with_state(this, |_, s| s.set_view(false, slot, address));
  1515. }
  1516. pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
  1517. // SAFETY: the title passes a view or null.
  1518. with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
  1519. }
  1520. pub(super) extern "system" fn vertex_buffers(
  1521. this: This,
  1522. start: u32,
  1523. count: u32,
  1524. views: *const VertexView,
  1525. ) {
  1526. with_state(this, |_, s| {
  1527. if views.is_null() {
  1528. s.clear_vertex_buffers(start, count);
  1529. } else {
  1530. s.set_vertex_buffers(start, items(views, count));
  1531. }
  1532. });
  1533. }
  1534. /// `(count, handles, one range, depth)`: with one range, the handles
  1535. /// follow the first at the render target view size (128 bytes).
  1536. pub(super) extern "system" fn targets(
  1537. this: This,
  1538. count: u32,
  1539. handles: *const u64,
  1540. one_range: i32,
  1541. depth: *const u64,
  1542. ) {
  1543. let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
  1544. // SAFETY: the title passes the first handle.
  1545. let first = unsafe { *handles };
  1546. (0..u64::from(count)).map(|i| first + 128 * i).collect()
  1547. } else {
  1548. items(handles, count).to_vec()
  1549. };
  1550. // SAFETY: the title passes a handle or null.
  1551. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  1552. with_state(this, |list, s| s.set_targets(list, &handles, depth));
  1553. }
  1554. pub(super) extern "system" fn draw(
  1555. this: This,
  1556. vertices: u32,
  1557. instances: u32,
  1558. first: u32,
  1559. first_instance: u32,
  1560. ) {
  1561. super::count_draw();
  1562. with_state(this, |list, s| {
  1563. s.draw(list, vertices, instances, first, first_instance)
  1564. });
  1565. }
  1566. pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
  1567. super::count_dispatch();
  1568. with_state(this, |list, s| s.dispatch(list, x, y, z));
  1569. }
  1570. /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
  1571. /// programs take `x` groups only.
  1572. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
  1573. super::count_draw();
  1574. if y * z != 1 {
  1575. static ONCE: std::sync::Once = std::sync::Once::new();
  1576. ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
  1577. }
  1578. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1579. }
  1580. /// `DispatchMeshX(x, flags, indirect arguments, payload)`.
  1581. /// shortcut: dispatches whose group count is in GPU memory (indirect)
  1582. /// are dropped; make them ExecuteIndirect when the title uses them.
  1583. pub(super) extern "system" fn dispatch_mesh_x(
  1584. this: This,
  1585. x: u32,
  1586. _flags: u64,
  1587. indirect: u64,
  1588. _payload: u64,
  1589. ) {
  1590. super::count_draw();
  1591. if indirect != 0 {
  1592. static ONCE: std::sync::Once = std::sync::Once::new();
  1593. ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
  1594. return;
  1595. }
  1596. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1597. }
  1598. pub(super) extern "system" fn draw_indexed(
  1599. this: This,
  1600. indices: u32,
  1601. instances: u32,
  1602. first: u32,
  1603. base: i32,
  1604. first_instance: u32,
  1605. ) {
  1606. super::count_draw();
  1607. with_state(this, |list, s| {
  1608. s.draw_indexed(list, indices, instances, first, base, first_instance)
  1609. });
  1610. }
  1611. }
  1612. /// Without a host GPU every draw state call is ignored.
  1613. #[cfg(not(windows))]
  1614. mod state {
  1615. pub(super) use super::dispatch;
  1616. pub(super) use super::draw;
  1617. pub(super) use super::draw as draw_indexed;
  1618. pub(super) use super::draw as dispatch_mesh;
  1619. pub(super) use super::draw as dispatch_mesh_x;
  1620. pub(super) use super::ignored_state as blend_factor;
  1621. pub(super) use super::ignored_state as compute_constant;
  1622. pub(super) use super::ignored_state as compute_constants;
  1623. pub(super) use super::ignored_state as compute_table;
  1624. pub(super) use super::ignored_state as compute_view;
  1625. pub(super) use super::ignored_state as graphics_constant;
  1626. pub(super) use super::ignored_state as graphics_constants;
  1627. pub(super) use super::ignored_state as graphics_table;
  1628. pub(super) use super::ignored_state as graphics_view;
  1629. pub(super) use super::ignored_state as heaps;
  1630. pub(super) use super::ignored_state as index_buffer;
  1631. pub(super) use super::ignored_state as scissors;
  1632. pub(super) use super::ignored_state as stencil_ref;
  1633. pub(super) use super::ignored_state as depth_bounds;
  1634. pub(super) use super::ignored_state as targets;
  1635. pub(super) use super::ignored_state as topology;
  1636. pub(super) use super::ignored_state as vertex_buffers;
  1637. pub(super) use super::ignored_state as viewports;
  1638. }
  1639. fn count_draw() {
  1640. DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1641. }
  1642. /// Draws of the kinds the host does not run yet (indirect, mesh), and
  1643. /// dispatches, counted per frame for the log.
  1644. /// shortcut: dropped until their shaders translate (decision 0007).
  1645. #[cfg(not(windows))]
  1646. extern "system" fn draw(_: This) {
  1647. count_draw();
  1648. }
  1649. /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
  1650. /// offset)`. The title's signatures (title+0x2479466, 2026-11-24)
  1651. /// hold one argument each: draw (stride 16), indexed draw (20), dispatch
  1652. /// (12), mesh dispatch (12), and the console's single-pass dispatch, type
  1653. /// 105 (stride 12: the three group counts; its flags live in the
  1654. /// signature, the title passes none), run as a plain dispatch. They run
  1655. /// through the host's indirect execution (`State::execute_indirect`).
  1656. /// shortcut: signatures that change root arguments are dropped (logged
  1657. /// once per signature).
  1658. extern "system" fn execute_indirect(
  1659. this: This,
  1660. signature: This,
  1661. max: u32,
  1662. arguments: This,
  1663. offset: u64,
  1664. count: This,
  1665. count_offset: u64,
  1666. ) {
  1667. count_draw();
  1668. let Some((stride, args)) = crate::signature::layout(signature) else {
  1669. return;
  1670. };
  1671. let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
  1672. let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
  1673. let mut ran = false;
  1674. #[cfg(windows)]
  1675. if let ([[kind, ..]], Some(address)) = (args, address)
  1676. && (count.is_null() || counter.is_some())
  1677. {
  1678. const DISPATCH: u32 = 2;
  1679. const DISPATCH_SINGLE: u32 = 105;
  1680. let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
  1681. with_state(this, |list, s| {
  1682. ran = s.execute_indirect(list, (kind, stride, max), address, counter);
  1683. });
  1684. } else {
  1685. #[cfg(all(windows, feature = "diagnostics"))]
  1686. crate::pipeline::note_why(format!(
  1687. "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
  1688. address.is_some(),
  1689. count.is_null() || counter.is_some()
  1690. ));
  1691. }
  1692. if ran {
  1693. return;
  1694. }
  1695. INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1696. static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  1697. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1698. if !seen.contains(&(signature as usize)) {
  1699. seen.push(signature as usize);
  1700. tracing::info!(
  1701. stride,
  1702. ?args,
  1703. max,
  1704. address = ?address.map(|a| format!("{a:#x}")),
  1705. counted = !count.is_null(),
  1706. "indirect execution dropped (first time for this signature)"
  1707. );
  1708. }
  1709. }
  1710. /// Indirect executions dropped since the last call.
  1711. pub(crate) fn take_indirect() -> u64 {
  1712. INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
  1713. }
  1714. static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1715. fn count_dispatch() {
  1716. DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1717. }
  1718. #[cfg(not(windows))]
  1719. extern "system" fn dispatch(_: This) {
  1720. count_dispatch();
  1721. }
  1722. static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1723. static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1724. /// Draws (any kind, mesh and indirect included) and compute dispatches
  1725. /// recorded since the last call.
  1726. pub(crate) fn take_counts() -> (u64, u64) {
  1727. use std::sync::atomic::Ordering::Relaxed;
  1728. (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
  1729. }
  1730. /// A GPU wait for a memory value: the list's commands after it run when
  1731. /// the 32 or 64 bits at `address` compare as asked with `reference`.
  1732. #[derive(Clone, Copy, Debug)]
  1733. pub(crate) struct ValueWait {
  1734. address: u64,
  1735. comparison: u32,
  1736. reference: u64,
  1737. wide: bool,
  1738. }
  1739. impl ValueWait {
  1740. /// Whether the memory holds what is waited for now.
  1741. /// shortcut: the comparison codes are taken to be the comparison
  1742. /// functions' (1 never .. 8 always, value against reference); one not
  1743. /// known counts as met, and so does memory that is not mapped.
  1744. ///
  1745. /// The value is read through the kernel, which reports memory that is
  1746. /// not there instead of faulting (as the copies of title memory are
  1747. /// read, `crate::host::copy_mapped`). Asking Windows first whether the
  1748. /// memory is committed (`VirtualQuery`) walks the page tables to the
  1749. /// end of the region: the title keeps these values in a 1.1 GB
  1750. /// allocation (0xd00000000), where one question took about 8 ms, and a
  1751. /// queue asks at every submission and every signal, for each queue that
  1752. /// stands at a wait (the title has five queues). That was
  1753. /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs
  1754. /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at
  1755. /// that thread in run 49 found it in this question).
  1756. /// `VICTORY_WAIT_ASK=1` asks first, as before.
  1757. pub(crate) fn met(&self) -> bool {
  1758. #[cfg(all(windows, feature = "diagnostics"))]
  1759. let started = std::time::Instant::now();
  1760. let met = self.holds();
  1761. #[cfg(all(windows, feature = "diagnostics"))]
  1762. {
  1763. use crate::copystat::{C, add};
  1764. add(C::WaitChecks, 1);
  1765. add(C::WaitCheckNs, started.elapsed().as_nanos() as u64);
  1766. }
  1767. met
  1768. }
  1769. fn holds(&self) -> bool {
  1770. let bytes = if self.wide { 8 } else { 4 };
  1771. if self.address == 0 {
  1772. return true;
  1773. }
  1774. static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1775. if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1"))
  1776. && !crate::texture::committed(self.address as *const u8, bytes)
  1777. {
  1778. return true;
  1779. }
  1780. // The low `bytes` bytes; the rest stays zero.
  1781. let mut raw = [0u8; 8];
  1782. if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) {
  1783. return true;
  1784. }
  1785. self.holds_for(u64::from_le_bytes(raw))
  1786. }
  1787. /// Where the value waited for is: address and bytes.
  1788. #[cfg(windows)]
  1789. pub(crate) fn place(&self) -> (usize, usize) {
  1790. (self.address as usize, if self.wide { 8 } else { 4 })
  1791. }
  1792. /// Whether the wait is met with `value` at its address (its low half
  1793. /// for a 32-bit wait).
  1794. pub(crate) fn holds_for(&self, value: u64) -> bool {
  1795. let (value, reference) = if self.wide {
  1796. (value, self.reference)
  1797. } else {
  1798. (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF)
  1799. };
  1800. match self.comparison {
  1801. 1 => false,
  1802. 2 => value < reference,
  1803. 3 => value == reference,
  1804. 4 => value <= reference,
  1805. 5 => value > reference,
  1806. 6 => value != reference,
  1807. 7 => value >= reference,
  1808. _ => true,
  1809. }
  1810. }
  1811. }
  1812. /// The waits lists recorded since their last reset, by list.
  1813. static VALUE_WAITS: std::sync::Mutex<Vec<(usize, ValueWait)>> = std::sync::Mutex::new(Vec::new());
  1814. /// The waits of the submitted `lists` that are not met yet (taken from
  1815. /// them): what the console's GPU would stop at. The title orders work
  1816. /// between its queues this way (the title: the compute queue's
  1817. /// lighting passes wait for a value the graphics queue's depth pass writes
  1818. /// at the bottom of the pipe; run at once, they read a cleared depth
  1819. /// buffer and nothing was lit).
  1820. /// shortcut: a wait holds its whole list (and submission) back, not only
  1821. /// the commands after it.
  1822. pub(crate) fn unmet_waits(lists: &[This]) -> Vec<ValueWait> {
  1823. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1824. let mut unmet = Vec::new();
  1825. waits.retain(|&(list, wait)| {
  1826. if !lists.iter().any(|&l| l as usize == list) {
  1827. return true;
  1828. }
  1829. if !wait.met() {
  1830. unmet.push(wait);
  1831. }
  1832. false
  1833. });
  1834. unmet
  1835. }
  1836. /// The waits each of the submitted `lists` recorded (taken from them),
  1837. /// met or not, at the list's first place in the submission.
  1838. #[cfg(windows)]
  1839. pub(crate) fn waits_by_list(lists: &[This]) -> Vec<Vec<ValueWait>> {
  1840. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1841. let mut by = vec![Vec::new(); lists.len()];
  1842. waits.retain(|&(list, wait)| {
  1843. match lists.iter().position(|&l| l as usize == list) {
  1844. Some(i) => {
  1845. by[i].push(wait);
  1846. false
  1847. }
  1848. None => true,
  1849. }
  1850. });
  1851. by
  1852. }
  1853. fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) {
  1854. let wait = ValueWait {
  1855. address,
  1856. comparison,
  1857. reference,
  1858. wide,
  1859. };
  1860. static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1861. if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 {
  1862. tracing::info!(
  1863. address = format_args!("{address:#x}"),
  1864. comparison,
  1865. reference,
  1866. wide,
  1867. met = wait.met(),
  1868. "a list waits for a memory value"
  1869. );
  1870. }
  1871. #[cfg(all(windows, feature = "diagnostics"))]
  1872. if let Some(host) = host_list(this) {
  1873. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1874. format!(
  1875. "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}",
  1876. wait.met()
  1877. )
  1878. });
  1879. }
  1880. // The list is cut here, and the wait stands before what follows.
  1881. #[cfg(windows)]
  1882. if crate::queue::cuts() {
  1883. cut(this, wait);
  1884. return;
  1885. }
  1886. VALUE_WAITS
  1887. .lock()
  1888. .unwrap_or_else(|e| e.into_inner())
  1889. .push((this as usize, wait));
  1890. }
  1891. extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) {
  1892. wait_for(this, address, comparison, reference, false);
  1893. }
  1894. extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) {
  1895. wait_for(this, address, comparison, reference, true);
  1896. }
  1897. /// The enhanced barriers `(group count, groups)`: buffer, texture and
  1898. /// global barriers with layouts instead of states. Every host use of a
  1899. /// title texture (clears, copies) moves its host copy to the state it needs
  1900. /// first, so only their ordering matters: one barrier on every shader
  1901. /// write (the title's buffer barriers order compute passes).
  1902. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  1903. // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`.
  1904. #[cfg(all(windows, feature = "diagnostics"))]
  1905. if count > 0 {
  1906. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1907. if crate::copystat::barrier_test() & 1 != 0 {
  1908. return;
  1909. }
  1910. }
  1911. #[cfg(windows)]
  1912. if count > 0
  1913. && let Some(list) = host_list(this)
  1914. {
  1915. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1916. with_state(this, |_, state| state.synced());
  1917. // SAFETY: the same layout; no resource named.
  1918. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1919. // SAFETY: an open list.
  1920. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1921. }
  1922. #[cfg(not(windows))]
  1923. let _ = (this, count);
  1924. }
  1925. /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
  1926. /// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
  1927. /// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
  1928. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
  1929. defer_write(this, address, Written::Value(u64::from(value)), 4);
  1930. value_written(this, address, u64::from(value));
  1931. }
  1932. extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
  1933. const GPU_TIMESTAMP: u32 = 1;
  1934. const SYSTEM_TIMESTAMP: u32 = 2;
  1935. let what = match flags {
  1936. GPU_TIMESTAMP => Written::GpuTimestamp,
  1937. SYSTEM_TIMESTAMP => Written::SystemTimestamp,
  1938. _ => Written::Value(value),
  1939. };
  1940. defer_write(this, address, what, 8);
  1941. if let Written::Value(value) = what {
  1942. value_written(this, address, value);
  1943. }
  1944. }
  1945. /// The title wrote a value at the bottom of the pipe (not a timestamp, not
  1946. /// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1`
  1947. /// the host list is cut right behind it, so that the value is stored when
  1948. /// the card has run the list up to there, as on the console, and not when
  1949. /// the whole list has run. Lists of other queues wait for these values
  1950. /// (the title: the compute list that builds the depth pyramid
  1951. /// waits for one, and the meshlet culling of the same frame reads that
  1952. /// pyramid). Off by default: every such write then ends a host list, and
  1953. /// each part is a submission of its own.
  1954. fn value_written(this: This, address: u64, value: u64) {
  1955. #[cfg(windows)]
  1956. {
  1957. if address == 0 || this.is_null() {
  1958. return;
  1959. }
  1960. #[cfg(not(feature = "diagnostics"))]
  1961. let _ = value;
  1962. #[cfg(feature = "diagnostics")]
  1963. if let Some(host) = host_list(this) {
  1964. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1965. format!("WRITE VALUE at {address:#x} value {value:#x}")
  1966. });
  1967. }
  1968. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1969. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1"))
  1970. || !crate::queue::cuts()
  1971. {
  1972. return;
  1973. }
  1974. // SAFETY: the title passes one of our lists; a list is recorded by
  1975. // one thread at a time and is not submitted while it records.
  1976. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  1977. let Some(current) = list.host.as_ref() else {
  1978. return;
  1979. };
  1980. let Some(fresh) = fresh_list() else {
  1981. return;
  1982. };
  1983. current.close();
  1984. if let Some(done) = list.host.replace(fresh) {
  1985. // The part so far keeps its waits; nothing stands before the
  1986. // next one but this part itself.
  1987. let waits = std::mem::take(&mut list.gate);
  1988. list.earlier.push(Part { waits, host: done });
  1989. }
  1990. if let Some(host) = list.host.as_ref() {
  1991. list.state
  1992. .lock()
  1993. .unwrap_or_else(|e| e.into_inner())
  1994. .replay(host);
  1995. }
  1996. }
  1997. #[cfg(not(windows))]
  1998. let _ = (this, address, value);
  1999. }
  2000. fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
  2001. if address == 0 {
  2002. return;
  2003. }
  2004. #[cfg(windows)]
  2005. if let Some(list) = host_list(this) {
  2006. list.defer_write(address as *mut u8, what, bytes);
  2007. return;
  2008. }
  2009. let _ = this;
  2010. // Without a host GPU nothing runs later: write now.
  2011. what.write(address as *mut u8, bytes);
  2012. }
  2013. /// The list methods by their slot in older titles' lists (the 2020-era
  2014. /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
  2015. /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
  2016. /// + 13): 140 slots.
  2017. const METHODS: [(usize, *const ()); 52] = [
  2018. (0, list_query as *const ()),
  2019. (2, list_release as *const ()),
  2020. (7, object::parent_device as *const ()), // 0x38
  2021. (8, list_type as *const ()), // 0x40
  2022. (9, close as *const ()), // 0x48
  2023. (10, reset as *const ()), // 0x50
  2024. (12, state::draw as *const ()), // 0x60 instanced
  2025. (13, state::draw_indexed as *const ()), // 0x68 indexed
  2026. (14, state::dispatch as *const ()), // 0x70
  2027. (15, copy_buffer_region as *const ()), // 0x78
  2028. (16, copy_texture_region as *const ()), // 0x80
  2029. (17, copy_resource as *const ()), // 0x88
  2030. (19, resolve as *const ()), // 0x98
  2031. (20, state::topology as *const ()), // 0xa0
  2032. (21, state::viewports as *const ()), // 0xa8
  2033. (22, state::scissors as *const ()), // 0xb0
  2034. (23, state::blend_factor as *const ()), // 0xb8
  2035. (24, state::stencil_ref as *const ()), // 0xc0
  2036. (25, set_pipeline as *const ()), // 0xc8
  2037. (26, barrier as *const ()), // 0xd0
  2038. (32, state::heaps as *const ()), // 0x100
  2039. (33, ignored_state as *const ()), // 0x108 compute root signature
  2040. (34, ignored_state as *const ()), // 0x110 graphics root signature
  2041. (35, state::compute_table as *const ()), // 0x118
  2042. (36, state::graphics_table as *const ()), // 0x120
  2043. (37, state::compute_constant as *const ()), // 0x128
  2044. (38, state::graphics_constant as *const ()), // 0x130
  2045. (39, state::compute_constants as *const ()), // 0x138
  2046. (40, state::graphics_constants as *const ()), // 0x140
  2047. (41, state::compute_view as *const ()), // 0x148 CBV
  2048. (42, state::graphics_view as *const ()), // 0x150 CBV
  2049. (43, state::compute_view as *const ()), // 0x158 SRV
  2050. (44, state::graphics_view as *const ()), // 0x160 SRV
  2051. (45, state::compute_view as *const ()), // 0x168 UAV
  2052. (46, state::graphics_view as *const ()), // 0x170 UAV
  2053. (47, state::index_buffer as *const ()), // 0x178
  2054. (48, state::vertex_buffers as *const ()), // 0x180
  2055. (50, state::targets as *const ()), // 0x190
  2056. (51, clear_dsv as *const ()), // 0x198
  2057. (52, clear_rtv as *const ()), // 0x1a0
  2058. (59, execute_indirect as *const ()), // 0x1d8 indirect
  2059. (60, copy_memory as *const ()), // 0x1e0
  2060. (68, state::depth_bounds as *const ()), // 0x220 depth bounds
  2061. (69, write32 as *const ()), // 0x228
  2062. (70, write64 as *const ()), // 0x230
  2063. (71, wait_value as *const ()), // 0x238, 32 bits
  2064. (72, wait_value64 as *const ()), // 0x240, 64 bits
  2065. (73, ignored_state as *const ()), // 0x248 pixel shader depth order
  2066. (83, copy_texture_region_x as *const ()), // 0x298
  2067. (84, copy_resource_x as *const ()), // 0x2a0
  2068. (124, ignored_state as *const ()), // 0x3e0 shading rate
  2069. (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
  2070. ];
  2071. /// The rest of [`METHODS`], kept apart only to stay readable.
  2072. const MORE_METHODS: [(usize, *const ()); 9] = [
  2073. (28, query_mark as *const ()), // 0xe0 BeginQuery
  2074. (29, query_mark as *const ()), // 0xe8 EndQuery
  2075. (30, resolve_queries as *const ()), // 0xf0
  2076. (78, dispatch_x as *const ()), // 0x270
  2077. (98, state::dispatch_mesh_x as *const ()), // 0x310
  2078. (99, driver_hint as *const ()), // 0x318
  2079. // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
  2080. (129, sync as *const ()),
  2081. (130, sync as *const ()),
  2082. (137, reset_x as *const ()), // 0x448
  2083. ];
  2084. /// Newer titles' lists have two more methods in the console part of the
  2085. /// base list, after the clears (0x198/0x1a0 as before) and before
  2086. /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
  2087. /// on is two later (taken here as starting exactly at 0x1d8). Inferred from
  2088. /// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
  2089. /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
  2090. /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
  2091. const fn newer_slot(slot: usize) -> usize {
  2092. if slot >= 59 { slot + 2 } else { slot }
  2093. }
  2094. /// Methods only newer titles' lists have. 0x490: the enhanced barrier
  2095. /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
  2096. /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
  2097. /// called from the title's state flush with its result unused.
  2098. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it
  2099. /// matters.
  2100. const NEWER_METHODS: [(usize, *const ()); 3] = [
  2101. (142, ignored_state as *const ()),
  2102. (146, barrier_groups as *const ()),
  2103. (148, allocate_upload as *const ()),
  2104. ];
  2105. const fn list_table(newer: bool) -> [*const (); 160] {
  2106. let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
  2107. let mut i = 0;
  2108. while i < METHODS.len() + MORE_METHODS.len() {
  2109. let (slot, method) = if i < METHODS.len() {
  2110. METHODS[i]
  2111. } else {
  2112. MORE_METHODS[i - METHODS.len()]
  2113. };
  2114. f[if newer { newer_slot(slot) } else { slot }] = method;
  2115. i += 1;
  2116. }
  2117. let mut i = 0;
  2118. while newer && i < NEWER_METHODS.len() {
  2119. f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
  2120. i += 1;
  2121. }
  2122. f
  2123. }
  2124. /// Every slot up to the limit exists and logs, for the methods newer
  2125. /// titles add.
  2126. static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
  2127. static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
  2128. #[cfg(test)]
  2129. mod tests {
  2130. use super::*;
  2131. use crate::object::slot;
  2132. #[test]
  2133. fn every_inline_command_falls_back_to_the_table() {
  2134. let null = std::ptr::null();
  2135. let mut allocator = null;
  2136. assert_eq!(
  2137. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2138. S_OK
  2139. );
  2140. let mut list = null;
  2141. let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
  2142. assert_eq!(hr, S_OK);
  2143. // What the title's inline draw checks: put < draw limit.
  2144. // SAFETY: the list is 0x560 bytes.
  2145. let (put, draw_limit, api_limit) = unsafe {
  2146. let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
  2147. (at(0x18), at(0x28), at(0x30))
  2148. };
  2149. assert!(put >= draw_limit && put >= api_limit);
  2150. // The console's ID3D12GraphicsCommandList6, as the title asks.
  2151. let mut same = null;
  2152. assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
  2153. assert_eq!(same, list);
  2154. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
  2155. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
  2156. assert_eq!(
  2157. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
  2158. S_OK
  2159. );
  2160. // List-owned upload memory: aligned, writable, gone at reset.
  2161. let p = allocate_upload(list, 40, 0x100);
  2162. assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
  2163. // SAFETY: 40 bytes were handed out.
  2164. unsafe { p.write_bytes(0xab, 40) };
  2165. assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
  2166. assert_eq!(reset(list, allocator, null), S_OK);
  2167. // SAFETY: the list is ours.
  2168. assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
  2169. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2170. assert_eq!(release(list), 0);
  2171. assert_eq!(release(allocator), 0);
  2172. }
  2173. /// An offset near `u64::MAX` must not overflow and write outside the
  2174. /// query destination buffer.
  2175. #[test]
  2176. fn resolve_queries_rejects_overflowing_offset() {
  2177. let null = std::ptr::null();
  2178. let mut allocator = null;
  2179. assert_eq!(
  2180. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2181. S_OK
  2182. );
  2183. let mut list = null;
  2184. assert_eq!(
  2185. create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list),
  2186. S_OK
  2187. );
  2188. let buffer = crate::resource::test_buffer(64);
  2189. // Used to overflow `offset + count * 8` (panic in debug, wrap in release).
  2190. resolve_queries(list, null, 0, 0, 2, buffer, u64::MAX - 8);
  2191. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2192. for object in [buffer, list, allocator] {
  2193. assert_eq!(release(object), 0);
  2194. }
  2195. }
  2196. }