list.rs 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314
  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. crate::pipeline::bound(pipeline);
  625. #[cfg(not(windows))]
  626. let _ = this;
  627. S_OK
  628. }
  629. /// A resource barrier as titles pass it: type, flags, then a resource and
  630. /// either a subresource and two states (transition) or a second resource
  631. /// (aliasing). The same layout as the host's.
  632. #[repr(C)]
  633. #[derive(Clone, Copy)]
  634. pub(crate) struct Barrier {
  635. kind: u32,
  636. flags: u32,
  637. first: This,
  638. second: u64,
  639. last: u64,
  640. }
  641. /// The barrier on host resources, or `None` if it names a resource the host
  642. /// GPU does not have (buffers so far).
  643. #[cfg(windows)]
  644. fn host_barrier(list: &crate::host::HostList, b: &Barrier) -> Option<Barrier> {
  645. use windows::core::Interface;
  646. let host = |r: This| crate::resource::host_resource(r).map(|h| h.as_raw().cast_const().cast());
  647. match b.kind {
  648. 0 => {
  649. // A split barrier's first half: its second half transitions.
  650. const BEGIN_ONLY: u32 = 1;
  651. if b.flags & BEGIN_ONLY != 0 {
  652. return None;
  653. }
  654. // shortcut: whole resources, from the state the list tracked
  655. // (`HostList::transition`); subresources are not told apart.
  656. let wanted = crate::host::texture_state(b.last as u32);
  657. let (texture, before) = list.transition(b.first, wanted)?;
  658. Some(Barrier {
  659. kind: 0,
  660. flags: 0,
  661. first: texture.as_raw().cast_const().cast(),
  662. second: 0xffff_ffff | (u64::from(before) << 32),
  663. last: u64::from(crate::host::legal_state(texture, wanted)),
  664. })
  665. }
  666. 1 => Some(Barrier {
  667. first: if b.first.is_null() {
  668. b.first
  669. } else {
  670. host(b.first)?
  671. },
  672. second: if b.second == 0 {
  673. 0
  674. } else {
  675. host(b.second as This)? as u64
  676. },
  677. ..*b
  678. }),
  679. 2 => Some(Barrier {
  680. first: if b.first.is_null() {
  681. b.first
  682. } else {
  683. // A depth texture's unordered access is its colour twin's
  684. // (the host gives the depth texture none): the barrier is
  685. // on the texture shaders write.
  686. match crate::resource::twin_resource(b.first) {
  687. Some(twin) => twin.as_raw().cast_const().cast(),
  688. None => host(b.first)?,
  689. }
  690. },
  691. ..*b
  692. }),
  693. _ => None,
  694. }
  695. }
  696. /// An unordered access barrier on every resource: earlier shader writes
  697. /// finish before later work reads or writes.
  698. const UAV_BARRIER: Barrier = Barrier {
  699. kind: 2,
  700. flags: 0,
  701. first: std::ptr::null(),
  702. second: 0,
  703. last: 0,
  704. };
  705. /// Returns the console's barrier "actions" (none).
  706. extern "system" fn barrier(this: This, count: u32, barriers: *const Barrier) -> u32 {
  707. #[cfg(windows)]
  708. if let Some(list) = host_list(this)
  709. && !barriers.is_null()
  710. {
  711. if count > 0 {
  712. with_state(this, |_, state| state.synced());
  713. }
  714. // SAFETY: the title passes `count` barriers.
  715. let barriers = unsafe { std::slice::from_raw_parts(barriers, count as usize) };
  716. let mut host: Vec<Barrier> = barriers
  717. .iter()
  718. .filter_map(|b| host_barrier(list, b))
  719. .collect();
  720. // Buffers have host copies, not resources the barrier can name:
  721. // a barrier on one waits for every shader write before it.
  722. if barriers.iter().any(|b| {
  723. b.kind != 1 && !b.first.is_null() && crate::resource::buffer_bytes(b.first).is_some()
  724. }) {
  725. host.push(UAV_BARRIER);
  726. #[cfg(feature = "diagnostics")]
  727. crate::copystat::add(crate::copystat::C::WaitsForBuffers, 1);
  728. }
  729. if !host.is_empty() {
  730. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  731. const _: () = assert!(size_of::<Barrier>() == size_of::<D3D12_RESOURCE_BARRIER>());
  732. // SAFETY: the same layout; borrowed resource pointers, never
  733. // released through this slice.
  734. let host = unsafe {
  735. std::slice::from_raw_parts(
  736. host.as_ptr().cast::<D3D12_RESOURCE_BARRIER>(),
  737. host.len(),
  738. )
  739. };
  740. // SAFETY: an open list and live resources.
  741. unsafe { list.list.ResourceBarrier(host) };
  742. }
  743. }
  744. 0
  745. }
  746. /// Moves a title texture's host copy to `state` in the list, if needed.
  747. #[cfg(windows)]
  748. pub(crate) fn ensure_state(list: &crate::host::HostList, resource: This, state: u32) {
  749. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  750. if let Some((texture, before)) = list.transition(resource, state) {
  751. let state = crate::host::legal_state(texture, state);
  752. let barrier = crate::host::transition(texture, State(before as i32), State(state as i32));
  753. // SAFETY: an open list and a live texture.
  754. unsafe { list.list.ResourceBarrier(&[barrier]) };
  755. }
  756. }
  757. #[cfg(windows)]
  758. const COPY_DEST: u32 = 0x400;
  759. #[cfg(windows)]
  760. const COPY_SOURCE: u32 = 0x800;
  761. /// `len` bytes at `offset` of a title buffer, if they are inside it.
  762. #[cfg(windows)]
  763. fn buffer_range(buffer: This, offset: u64, len: u64) -> Option<*mut u8> {
  764. let (data, size) = crate::resource::buffer_bytes(buffer)?;
  765. let end = offset.checked_add(len)?;
  766. if end > size {
  767. tracing::warn!(offset, len, size, "copy outside its buffer");
  768. return None;
  769. }
  770. // SAFETY: inside the buffer, checked above.
  771. Some(unsafe { data.add(offset as usize) })
  772. }
  773. /// A copy of title memory that `list` records: on the card at its place in
  774. /// the list ([`crate::host::HostList::place_copy`]), or at submission.
  775. #[cfg(windows)]
  776. fn buffer_copy(this: This, list: &crate::host::HostList, to: *mut u8, from: *const u8, len: usize) {
  777. if len == 0 {
  778. return;
  779. }
  780. if list.place_copy(to as usize, from as usize, len) {
  781. with_state(this, |_, state| state.copied());
  782. } else {
  783. list.defer_copy(to, from, len);
  784. }
  785. }
  786. /// Buffer to buffer: both are host memory, copied at submission.
  787. extern "system" fn copy_buffer_region(
  788. this: This,
  789. dst: This,
  790. dst_offset: u64,
  791. src: This,
  792. src_offset: u64,
  793. len: u64,
  794. ) {
  795. #[cfg(windows)]
  796. if let Some(list) = host_list(this)
  797. && let Some(to) = buffer_range(dst, dst_offset, len)
  798. && let Some(from) = buffer_range(src, src_offset, len)
  799. {
  800. buffer_copy(this, list, to, from, len as usize);
  801. }
  802. #[cfg(not(windows))]
  803. let _ = (this, dst, dst_offset, src, src_offset, len);
  804. }
  805. /// Whether one of two resources is a target in a stand-in format and the
  806. /// other is not ([`crate::resource::target_format`]): their texels differ
  807. /// in size, so the host cannot copy between them (logged once).
  808. #[cfg(windows)]
  809. fn unlike(dst: This, src: This) -> bool {
  810. let unlike = crate::resource::stands_in(dst) != crate::resource::stands_in(src);
  811. if unlike {
  812. static ONCE: std::sync::Once = std::sync::Once::new();
  813. ONCE.call_once(|| {
  814. tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped")
  815. });
  816. }
  817. unlike
  818. }
  819. extern "system" fn copy_resource(this: This, dst: This, src: This) {
  820. #[cfg(windows)]
  821. {
  822. let Some(list) = host_list(this) else {
  823. return;
  824. };
  825. if let (Some(to), Some(from)) = (
  826. crate::resource::host_resource(dst),
  827. crate::resource::host_resource(src),
  828. ) {
  829. if unlike(dst, src) {
  830. return;
  831. }
  832. // A source the title fills itself is uploaded first (upstream
  833. // PR #671): a copy read whatever the host texture held.
  834. if crate::texture::title_written(from) {
  835. crate::texture::upload(list, src, from);
  836. }
  837. // Depth textures shaders also write: what they wrote, first.
  838. list.twin_use(dst, false, true);
  839. list.twin_use(src, false, false);
  840. // A destination made level by level gets its levels' memory
  841. // ahead of this list (`crate::tiles`).
  842. crate::texture::card_writes(list, dst, to, None);
  843. ensure_state(list, dst, COPY_DEST);
  844. ensure_state(list, src, COPY_SOURCE);
  845. crate::texture::host_written(dst);
  846. #[cfg(feature = "diagnostics")]
  847. list.note_op(|| format!("copy resource {src:?} to {dst:?}"));
  848. // SAFETY: an open list and live textures.
  849. unsafe { list.list.CopyResource(to, from) };
  850. } else if let (Some((to, a)), Some((from, b))) = (
  851. crate::resource::buffer_bytes(dst),
  852. crate::resource::buffer_bytes(src),
  853. ) {
  854. buffer_copy(this, list, to, from, a.min(b) as usize);
  855. }
  856. }
  857. #[cfg(not(windows))]
  858. let _ = (this, dst, src);
  859. }
  860. extern "system" fn copy_resource_x(this: This, dst: This, src: This, _flags: u32) {
  861. copy_resource(this, dst, src);
  862. }
  863. /// A copy location as titles pass it, laid out as the host's: a resource,
  864. /// then a subresource index (type 0) or a placed footprint (type 1).
  865. #[repr(C)]
  866. #[derive(Clone, Copy)]
  867. pub(crate) struct CopyLocation {
  868. resource: This,
  869. kind: u32,
  870. footprint: crate::resource::PlacedFootprint,
  871. }
  872. /// Texture to texture on the GPU; buffer to texture through an upload
  873. /// buffer filled at submission. Texture to buffer (read back) is not done
  874. /// yet.
  875. extern "system" fn copy_texture_region(
  876. this: This,
  877. dst: *const CopyLocation,
  878. x: u32,
  879. y: u32,
  880. z: u32,
  881. src: *const CopyLocation,
  882. source_box: *const [u32; 6],
  883. ) {
  884. #[cfg(windows)]
  885. {
  886. use windows::Win32::Graphics::Direct3D12::{D3D12_BOX, D3D12_TEXTURE_COPY_LOCATION};
  887. use windows::core::Interface;
  888. const FOOTPRINT: u32 = 1;
  889. // SAFETY: the title passes both locations (null is tolerated).
  890. let (Some(list), Some(&dst), Some(&src)) =
  891. (host_list(this), unsafe { dst.as_ref() }, unsafe {
  892. src.as_ref()
  893. })
  894. else {
  895. return;
  896. };
  897. let Some(to) = crate::resource::host_resource(dst.resource) else {
  898. // Texture to buffer: a read back. The list copies the texels
  899. // into a host buffer of ours; once it has run they go to the
  900. // title's buffer (`HostList::defer_read_back`).
  901. // The title reads two tiny float targets back every frame (5x1
  902. // and 1x1 RGBA32F, 80 and 16 bytes: run 90), and read a buffer
  903. // nobody wrote. `VICTORY_READ_BACK=0` leaves them unmade, as
  904. // before.
  905. static COUNT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  906. let n = COUNT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
  907. let made = read_back(list, dst, x, y, z, src, source_box);
  908. if n <= 16 || n.is_multiple_of(4096) || made.is_err() {
  909. static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  910. if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 {
  911. return;
  912. }
  913. let source = crate::resource::host_resource(src.resource).map(|r| {
  914. // SAFETY: a live resource.
  915. let d = unsafe { r.GetDesc() };
  916. format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels)
  917. });
  918. tracing::info!(
  919. copies = n,
  920. made = ?made,
  921. source = ?source,
  922. source_kind = src.kind,
  923. destination_kind = dst.kind,
  924. destination_offset = dst.footprint.offset,
  925. destination_bytes = ?dst.footprint.bytes(),
  926. "a texture to buffer copy (a read back)"
  927. );
  928. }
  929. return;
  930. };
  931. if unlike(dst.resource, src.resource) {
  932. return;
  933. }
  934. let mut from = src;
  935. let _upload; // keeps the source alive while this call records it
  936. #[cfg(feature = "diagnostics")]
  937. let mut read = None;
  938. if src.kind == FOOTPRINT {
  939. let (Some(host), Some(bytes)) = (crate::host::host(), src.footprint.bytes()) else {
  940. return;
  941. };
  942. let Some(data) = buffer_range(src.resource, src.footprint.offset, bytes) else {
  943. return;
  944. };
  945. let buffer = match list.place_source(data as usize, bytes as usize) {
  946. // What shaders wrote to it, at this place of the list.
  947. Some(buffer) => buffer,
  948. None => {
  949. let Some((buffer, staging)) = list.upload(host, bytes) else {
  950. return;
  951. };
  952. // The list owns this mapped D3D12 upload buffer. Wine can
  953. // report its address as MEM_FREE, so use the host-upload
  954. // path.
  955. list.defer_fill_buffer(&buffer, staging, data, bytes as usize);
  956. buffer
  957. }
  958. };
  959. from.resource = buffer.as_raw().cast_const().cast();
  960. from.footprint.offset = 0;
  961. #[cfg(feature = "diagnostics")]
  962. {
  963. // SAFETY: a live buffer.
  964. read = Some((unsafe { buffer.GetGPUVirtualAddress() }, bytes));
  965. }
  966. _upload = buffer;
  967. } else {
  968. let Some(texture) = crate::resource::host_resource(src.resource) else {
  969. return;
  970. };
  971. list.twin_use(src.resource, false, false);
  972. if crate::texture::title_written(texture) {
  973. crate::texture::upload(list, src.resource, texture);
  974. }
  975. ensure_state(list, src.resource, COPY_SOURCE);
  976. from.resource = texture.as_raw().cast_const().cast();
  977. }
  978. // A depth texture shaders also write: what they wrote, first (the
  979. // source above too).
  980. list.twin_use(dst.resource, false, true);
  981. // A destination made level by level gets the level's memory ahead
  982. // of this list (`crate::tiles`): the title's bake copies each level
  983. // of its result into a block-compressed texture of that kind, and
  984. // a copy into a level without memory is dropped.
  985. crate::texture::card_writes(list, dst.resource, to, Some(dst.footprint.offset as u32));
  986. ensure_state(list, dst.resource, COPY_DEST);
  987. crate::texture::host_written(dst.resource);
  988. let mut to_location = dst;
  989. to_location.resource = to.as_raw().cast_const().cast();
  990. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  991. #[cfg(feature = "diagnostics")]
  992. {
  993. let text = || {
  994. // SAFETY: a live texture; the box is the title's or null.
  995. let (d, b) = unsafe { (to.GetDesc(), host_box.map(|b| *b)) };
  996. format!(
  997. "copy to {:?} {}x{} f{} sub/kind {} at {x},{y},{z} from {:?} kind {} footprint {:?} box {b:?}",
  998. dst.resource,
  999. d.Width,
  1000. d.Height,
  1001. d.Format.0,
  1002. dst.kind,
  1003. src.resource,
  1004. src.kind,
  1005. (src.kind == FOOTPRINT).then_some(src.footprint)
  1006. )
  1007. };
  1008. match read {
  1009. Some(range) => list.note_read(text, range),
  1010. None => list.note_op(text),
  1011. }
  1012. }
  1013. const _: () =
  1014. assert!(size_of::<CopyLocation>() == size_of::<D3D12_TEXTURE_COPY_LOCATION>());
  1015. // SAFETY: an open list; both locations in the host's layout, naming
  1016. // live resources; the box is the title's (same layout).
  1017. unsafe {
  1018. list.list.CopyTextureRegion(
  1019. (&raw const to_location).cast(),
  1020. x,
  1021. y,
  1022. z,
  1023. (&raw const from).cast(),
  1024. host_box,
  1025. )
  1026. };
  1027. }
  1028. #[cfg(not(windows))]
  1029. let _ = (this, dst, x, y, z, src, source_box);
  1030. }
  1031. /// Records a texture to buffer copy (a read back) of [`copy_texture_region`]
  1032. /// into `list`, or says why not.
  1033. #[cfg(windows)]
  1034. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1035. fn read_back(
  1036. list: &crate::host::HostList,
  1037. dst: CopyLocation,
  1038. x: u32,
  1039. y: u32,
  1040. z: u32,
  1041. src: CopyLocation,
  1042. source_box: *const [u32; 6],
  1043. ) -> Result<(), &'static str> {
  1044. use windows::Win32::Graphics::Direct3D12::D3D12_BOX;
  1045. use windows::core::Interface;
  1046. const FOOTPRINT: u32 = 1;
  1047. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1048. if !*ON.get_or_init(|| std::env::var_os("VICTORY_READ_BACK").is_none_or(|v| v != "0")) {
  1049. return Err("switched off");
  1050. }
  1051. if dst.kind != FOOTPRINT || src.kind == FOOTPRINT {
  1052. return Err("not a texture subresource into a placed footprint");
  1053. }
  1054. if (x, y, z) != (0, 0, 0) {
  1055. return Err("a destination corner other than the footprint's");
  1056. }
  1057. let host = crate::host::host().ok_or("no host")?;
  1058. let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?;
  1059. // The title's buffer holds every row at its own pitch.
  1060. let bytes = pitch * (rows - 1) + row;
  1061. let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?;
  1062. let texture = crate::resource::host_resource(src.resource).ok_or("no host texture")?;
  1063. let buffer = host.read_back_buffer(size).ok_or("no read-back buffer")?;
  1064. // As a texture source of any copy: what shaders wrote to a depth twin
  1065. // and what the title wrote itself first, then the state.
  1066. list.twin_use(src.resource, false, false);
  1067. if crate::texture::title_written(texture) {
  1068. crate::texture::upload(list, src.resource, texture);
  1069. }
  1070. ensure_state(list, src.resource, COPY_SOURCE);
  1071. let mut from = src;
  1072. from.resource = texture.as_raw().cast_const().cast();
  1073. let mut to = dst;
  1074. to.resource = buffer.as_raw().cast_const().cast();
  1075. to.footprint = footprint;
  1076. let host_box = (!source_box.is_null()).then(|| source_box.cast::<D3D12_BOX>());
  1077. #[cfg(feature = "diagnostics")]
  1078. list.note_op(|| {
  1079. format!(
  1080. "read back of {:?} sub {} into buffer {:?}+{:#x}: {rows} rows of {row} bytes",
  1081. src.resource, src.footprint.offset as u32, dst.resource, dst.footprint.offset
  1082. )
  1083. });
  1084. // SAFETY: an open list; both locations in the host's layout (asserted
  1085. // in `copy_texture_region`), naming a live texture and our buffer, which
  1086. // the list keeps until it is reset; the box is the title's.
  1087. unsafe {
  1088. list.list
  1089. .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box)
  1090. };
  1091. list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]);
  1092. Ok(())
  1093. }
  1094. #[allow(clippy::too_many_arguments)] // the method's own arguments
  1095. extern "system" fn copy_texture_region_x(
  1096. this: This,
  1097. dst: *const CopyLocation,
  1098. x: u32,
  1099. y: u32,
  1100. z: u32,
  1101. src: *const CopyLocation,
  1102. source_box: *const [u32; 6],
  1103. _flags: u32,
  1104. ) {
  1105. copy_texture_region(this, dst, x, y, z, src, source_box);
  1106. }
  1107. extern "system" fn resolve(
  1108. this: This,
  1109. dst: This,
  1110. dst_sub: u32,
  1111. src: This,
  1112. src_sub: u32,
  1113. format: u32,
  1114. ) {
  1115. #[cfg(windows)]
  1116. if let Some(list) = host_list(this)
  1117. && let (Some(to), Some(from)) = (
  1118. crate::resource::host_resource(dst),
  1119. crate::resource::host_resource(src),
  1120. )
  1121. {
  1122. use windows::Win32::Foundation::RECT;
  1123. use windows::Win32::Graphics::Direct3D12::{
  1124. D3D12_RESOLVE_MODE_AVERAGE, ID3D12GraphicsCommandList1,
  1125. };
  1126. use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT;
  1127. use windows::core::Interface;
  1128. const RESOLVE_DEST: u32 = 0x1000;
  1129. const RESOLVE_SOURCE: u32 = 0x2000;
  1130. if unlike(dst, src) {
  1131. return;
  1132. }
  1133. // Depth textures shaders also write: what they wrote, first.
  1134. list.twin_use(dst, false, true);
  1135. list.twin_use(src, false, false);
  1136. // As for a copy (`crate::tiles`).
  1137. crate::texture::card_writes(list, dst, to, Some(dst_sub));
  1138. ensure_state(list, dst, RESOLVE_DEST);
  1139. ensure_state(list, src, RESOLVE_SOURCE);
  1140. crate::texture::host_written(dst);
  1141. #[cfg(feature = "diagnostics")]
  1142. list.note_op(|| format!("resolve {src:?} to {dst:?} format {format}"));
  1143. // SAFETY: an open list and live textures; the region is inside both.
  1144. unsafe {
  1145. let (a, b) = (to.GetDesc(), from.GetDesc());
  1146. let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) };
  1147. if (a.Width, a.Height) == (b.Width, b.Height) {
  1148. list.list
  1149. .ResolveSubresource(to, dst_sub, from, src_sub, format);
  1150. } else if let Ok(list1) = list.list.cast::<ID3D12GraphicsCommandList1>() {
  1151. // The console clips a larger source to the destination.
  1152. let rect = RECT {
  1153. left: 0,
  1154. top: 0,
  1155. right: a.Width.min(b.Width) as i32,
  1156. bottom: a.Height.min(b.Height) as i32,
  1157. };
  1158. list1.ResolveSubresourceRegion(
  1159. to,
  1160. dst_sub,
  1161. 0,
  1162. 0,
  1163. from,
  1164. src_sub,
  1165. Some(&rect),
  1166. format,
  1167. D3D12_RESOLVE_MODE_AVERAGE,
  1168. );
  1169. }
  1170. }
  1171. }
  1172. #[cfg(not(windows))]
  1173. let _ = (this, dst, dst_sub, src, src_sub, format);
  1174. }
  1175. #[repr(C)]
  1176. pub(crate) struct Rect {
  1177. left: i32,
  1178. top: i32,
  1179. right: i32,
  1180. bottom: i32,
  1181. }
  1182. extern "system" fn clear_rtv(
  1183. this: This,
  1184. handle: u64,
  1185. color: *const [f32; 4],
  1186. count: u32,
  1187. rects: *const Rect,
  1188. ) {
  1189. #[cfg(windows)]
  1190. {
  1191. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::rtv_record(handle))
  1192. else {
  1193. return;
  1194. };
  1195. let (Some(texture), Some(host)) = (
  1196. crate::resource::host_resource(record.resource),
  1197. crate::host::host(),
  1198. ) else {
  1199. return;
  1200. };
  1201. // SAFETY: the title passes four floats (null is tolerated).
  1202. let Some(color) = (unsafe { color.as_ref() }) else {
  1203. return;
  1204. };
  1205. let rects = (count > 0 && !rects.is_null()).then(|| {
  1206. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1207. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1208. });
  1209. const RENDER_TARGET: u32 = 0x4;
  1210. let rtv = host.rtv(Some(texture), record.desc().as_ref());
  1211. // SAFETY: an open list, a fresh view of a live texture.
  1212. unsafe {
  1213. if let Some((_, before)) = list.transition(record.resource, RENDER_TARGET) {
  1214. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_STATES as State;
  1215. list.list.ResourceBarrier(&[crate::host::transition(
  1216. texture,
  1217. State(before as i32),
  1218. State(RENDER_TARGET as i32),
  1219. )]);
  1220. }
  1221. list.list.ClearRenderTargetView(rtv, color, rects);
  1222. }
  1223. }
  1224. #[cfg(not(windows))]
  1225. let _ = (this, handle, color, count, rects);
  1226. }
  1227. /// `ClearDepthStencilView(handle, flags, depth, stencil, count, rects)`;
  1228. /// flags: 1 depth, 2 stencil.
  1229. extern "system" fn clear_dsv(
  1230. this: This,
  1231. handle: u64,
  1232. flags: u32,
  1233. depth: f32,
  1234. stencil: u8,
  1235. count: u32,
  1236. rects: *const Rect,
  1237. ) {
  1238. #[cfg(windows)]
  1239. {
  1240. use windows::Win32::Graphics::Direct3D12::D3D12_CLEAR_FLAGS;
  1241. let (Some(list), Some(record)) = (host_list(this), crate::descriptor::dsv_record(handle))
  1242. else {
  1243. return;
  1244. };
  1245. let (Some(texture), Some(host)) = (
  1246. crate::resource::host_resource(record.resource),
  1247. crate::host::host(),
  1248. ) else {
  1249. return;
  1250. };
  1251. let rects = (count > 0 && !rects.is_null()).then(|| {
  1252. // SAFETY: the title passes `count` rectangles, laid out as the host's.
  1253. unsafe { std::slice::from_raw_parts(rects.cast(), count as usize) }
  1254. });
  1255. const DEPTH_WRITE: u32 = 0x10;
  1256. // A depth texture shaders also write: what they wrote, first (the
  1257. // clear may be of one slice or of some rectangles).
  1258. list.twin_use(record.resource, false, true);
  1259. ensure_state(list, record.resource, DEPTH_WRITE);
  1260. if crate::resource::depth_and_unordered(record.resource) {
  1261. crate::resource::DEPTH_UNORDERED[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1262. }
  1263. let dsv = host.dsv(texture, record.depth_desc().as_ref());
  1264. // SAFETY: an open list, a fresh view of a live texture.
  1265. unsafe {
  1266. list.list
  1267. .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects)
  1268. };
  1269. }
  1270. #[cfg(not(windows))]
  1271. let _ = (this, handle, flags, depth, stencil, count, rects);
  1272. }
  1273. /// `CopyMemoryToMemoryX(destination, source, size, flags)`: GPU addresses
  1274. /// are title memory, copied at submission like buffer copies (if mapped).
  1275. extern "system" fn copy_memory(this: This, dst: u64, src: u64, len: u64, _flags: u32) {
  1276. #[cfg(windows)]
  1277. if let Some(list) = host_list(this)
  1278. && dst != 0
  1279. && src != 0
  1280. {
  1281. let len = len as usize;
  1282. if list.place_copy(dst as usize, src as usize, len) {
  1283. with_state(this, |_, state| state.copied());
  1284. return;
  1285. }
  1286. list.defer(move || {
  1287. if crate::texture::committed(src as *const u8, len)
  1288. && crate::texture::committed(dst as *const u8, len)
  1289. {
  1290. // SAFETY: both ranges are committed title memory.
  1291. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len) };
  1292. }
  1293. });
  1294. }
  1295. #[cfg(not(windows))]
  1296. let _ = (this, dst, src, len);
  1297. }
  1298. /// `DriverHintX(feature, value)`: no hints for the host.
  1299. extern "system" fn driver_hint(_: This, _feature: u64, _value: u64) -> u64 {
  1300. 0
  1301. }
  1302. /// `DispatchX(x, y, z, flags)`: a dispatch with console flags, which the
  1303. /// host has no use for (the ray-tracing builder dispatches this way).
  1304. extern "system" fn dispatch_x(this: This, x: u32, y: u32, z: u32, _flags: u32) {
  1305. #[cfg(windows)]
  1306. state::dispatch(this, x, y, z);
  1307. #[cfg(not(windows))]
  1308. {
  1309. let _ = (this, x, y, z);
  1310. count_dispatch();
  1311. }
  1312. }
  1313. /// `BeginQuery`/`EndQuery(heap, type, index)`: queries are answered when
  1314. /// resolved.
  1315. extern "system" fn query_mark(_: This, _heap: This, _kind: u32, _index: u32) {}
  1316. /// `ResolveQueryData(heap, type, first, count, buffer, offset)`: writes
  1317. /// each query's result into the buffer once the list has run. Timestamps
  1318. /// (type 2) are the GPU clock then; occlusion counts (0) say a million
  1319. /// samples passed and binary occlusion (1) visible, so nothing is culled
  1320. /// by a query.
  1321. /// shortcut: no query runs on the host GPU; results are plausible values,
  1322. /// not measured ones (time spans come out as the submission's length).
  1323. extern "system" fn resolve_queries(
  1324. this: This,
  1325. _heap: This,
  1326. kind: u32,
  1327. _first: u32,
  1328. count: u32,
  1329. buffer: This,
  1330. offset: u64,
  1331. ) {
  1332. const OCCLUSION: u32 = 0;
  1333. const BINARY: u32 = 1;
  1334. const TIMESTAMP: u32 = 2;
  1335. const PIPELINE_STATISTICS: u32 = 3;
  1336. let Some((data, size)) = crate::resource::buffer_bytes(buffer) else {
  1337. return;
  1338. };
  1339. let (what, bytes) = match kind {
  1340. OCCLUSION => (Written::Value(1 << 20), 8),
  1341. BINARY => (Written::Value(1), 8),
  1342. TIMESTAMP => (Written::GpuTimestamp, 8),
  1343. PIPELINE_STATISTICS => (Written::Value(0), 88),
  1344. _ => (Written::Value(0), 16),
  1345. };
  1346. let Some(end) = offset.checked_add(u64::from(count) * bytes) else {
  1347. return;
  1348. };
  1349. if end > size {
  1350. return;
  1351. }
  1352. for i in 0..u64::from(count) {
  1353. // Wider results are written as 8-byte pieces.
  1354. for piece in 0..bytes / 8 {
  1355. // SAFETY: inside the buffer, checked above.
  1356. let at = unsafe { data.add((offset + i * bytes + piece * 8) as usize) };
  1357. let what = if piece == 0 { what } else { Written::Value(0) };
  1358. defer_write(this, at as u64, what, 8);
  1359. }
  1360. }
  1361. }
  1362. /// IUnknown 3, object 4, device child 1, allocator 2.
  1363. static ALLOCATOR_FUNCTIONS: Table<24> = {
  1364. let mut f = object::d3d12_object(object::missing_table::<ALLOCATOR, 24>());
  1365. f[0] = allocator_query as *const ();
  1366. f[2] = allocator_release as *const ();
  1367. f[7] = object::parent_device as *const (); // 0x38
  1368. f[8] = allocator_reset as *const (); // 0x40
  1369. f[9] = object::ignore as *const (); // 0x48 allocation callback
  1370. Table(f)
  1371. };
  1372. extern "system" fn set_pipeline(this: This, pipeline: This) {
  1373. crate::pipeline::bound(pipeline);
  1374. #[cfg(windows)]
  1375. with_state(this, |_, state| state.set_pipeline(pipeline));
  1376. #[cfg(not(windows))]
  1377. let _ = this;
  1378. }
  1379. /// Pipeline syncs: waits for earlier work and cache flushes, at the top or
  1380. /// bottom of the pipe `(flags, control, address, size)`. The host orders
  1381. /// nothing between dispatches by itself: what shaders wrote is waited for
  1382. /// here as at the title's barriers (the ray-tracing structure builder has
  1383. /// no other wait between its stages).
  1384. /// (Arguments may be what earlier shaders wrote from here on:
  1385. /// `State::synced`.)
  1386. extern "system" fn sync(this: This, flags: u32, control: u32, address: u64, size: u64) {
  1387. #[cfg(windows)]
  1388. {
  1389. with_state(this, |_, state| state.synced());
  1390. if let Some(list) = host_list(this) {
  1391. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1392. #[cfg(feature = "diagnostics")]
  1393. {
  1394. // The shapes of the title's calls, each once.
  1395. static SEEN: std::sync::Mutex<Vec<(u32, u32, bool)>> = std::sync::Mutex::new(Vec::new());
  1396. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1397. let shape = (flags, control, address == 0);
  1398. if seen.len() < 64 && !seen.contains(&shape) {
  1399. seen.push(shape);
  1400. tracing::info!(
  1401. flags = format_args!("{flags:#x}"),
  1402. control = format_args!("{control:#x}"),
  1403. address = format_args!("{address:#x}"),
  1404. size = format_args!("{size:#x}"),
  1405. "a pipeline sync"
  1406. );
  1407. }
  1408. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1409. }
  1410. // SAFETY: the same layout; no resource named.
  1411. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1412. // SAFETY: an open list.
  1413. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1414. }
  1415. }
  1416. let _ = (this, flags, control, address, size);
  1417. }
  1418. /// Reset with console flags `(allocator, pipeline, flags)`; the flags only
  1419. /// tune the console's command memory.
  1420. extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: u32) -> HRESULT {
  1421. reset(this, allocator, pipeline)
  1422. }
  1423. /// Newer lists' 0x4a0 `(size, alignment) -> pointer`: memory the list
  1424. /// owns until it is reset, which the CPU writes and the GPU reads at the
  1425. /// same address; null on failure. The title's BVH builder puts
  1426. /// its instance descriptions there (and wrote through our old
  1427. /// `E_NOTIMPL` as a pointer).
  1428. extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 {
  1429. let align = usize::try_from(alignment).unwrap_or(0).max(16);
  1430. let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else {
  1431. return std::ptr::null_mut();
  1432. };
  1433. if this.is_null() || !align.is_power_of_two() {
  1434. return std::ptr::null_mut();
  1435. }
  1436. let mut block = vec![0u8; len];
  1437. let start = block.as_mut_ptr();
  1438. // SAFETY: the offset is below `align`, so `size` bytes fit after it.
  1439. let at = unsafe { start.add(start.align_offset(align)) };
  1440. // SAFETY: the title passes one of our lists.
  1441. let uploads = unsafe { &(*this.cast::<List>()).uploads };
  1442. // Moving the vector keeps its heap block where it is.
  1443. uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block);
  1444. at
  1445. }
  1446. /// Draw state the host has no use for (root signatures: ours come with
  1447. /// the pipeline; depth order and shading rate hints): any arguments,
  1448. /// nothing returned.
  1449. extern "system" fn ignored_state(_: This) {}
  1450. /// The title's draw state (decision 0007, step 3), kept for its draws or
  1451. /// set on the host list at once. Without a host GPU these do nothing.
  1452. #[cfg(windows)]
  1453. mod state {
  1454. use super::{This, with_state};
  1455. use crate::draw::{IndexView, VertexView};
  1456. use windows::Win32::Foundation::RECT;
  1457. use windows::Win32::Graphics::Direct3D12::D3D12_VIEWPORT;
  1458. /// `count` items at `items`, or none.
  1459. fn items<'a, T>(items: *const T, count: u32) -> &'a [T] {
  1460. if items.is_null() || count == 0 {
  1461. return &[];
  1462. }
  1463. // SAFETY: the title passes `count` items.
  1464. unsafe { std::slice::from_raw_parts(items, count as usize) }
  1465. }
  1466. pub(super) extern "system" fn topology(this: This, topology: u32) {
  1467. with_state(this, |list, s| s.set_topology(list, topology));
  1468. }
  1469. pub(super) extern "system" fn viewports(
  1470. this: This,
  1471. count: u32,
  1472. viewports: *const D3D12_VIEWPORT,
  1473. ) {
  1474. // (Through the draw state, which keeps them for the host list
  1475. // that continues this one after a cut: `State::replay`.)
  1476. with_state(this, |list, s| s.set_viewports(list, items(viewports, count)));
  1477. }
  1478. pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) {
  1479. with_state(this, |list, s| s.set_scissors(list, items(rects, count)));
  1480. }
  1481. pub(super) extern "system" fn blend_factor(this: This, factor: *const [f32; 4]) {
  1482. with_state(this, |list, s| {
  1483. // SAFETY: the title passes four floats or null.
  1484. s.set_blend_factor(list, unsafe { factor.as_ref() })
  1485. });
  1486. }
  1487. pub(super) extern "system" fn stencil_ref(this: This, reference: u32) {
  1488. with_state(this, |list, s| s.set_stencil_ref(list, reference));
  1489. }
  1490. pub(super) extern "system" fn depth_bounds(this: This, min: f32, max: f32) {
  1491. with_state(this, |list, s| s.set_depth_bounds(list, min, max));
  1492. }
  1493. pub(super) extern "system" fn heaps(this: This, count: u32, heaps: *const This) {
  1494. with_state(this, |_, s| s.set_heaps(items(heaps, count)));
  1495. }
  1496. pub(super) extern "system" fn compute_table(this: This, slot: u32, handle: u64) {
  1497. with_state(this, |_, s| s.set_table(true, slot, handle));
  1498. }
  1499. pub(super) extern "system" fn graphics_table(this: This, slot: u32, handle: u64) {
  1500. with_state(this, |_, s| s.set_table(false, slot, handle));
  1501. }
  1502. pub(super) extern "system" fn compute_constant(this: This, slot: u32, value: u32, offset: u32) {
  1503. with_state(this, |_, s| s.set_constants(true, slot, &[value], offset));
  1504. }
  1505. pub(super) extern "system" fn graphics_constant(
  1506. this: This,
  1507. slot: u32,
  1508. value: u32,
  1509. offset: u32,
  1510. ) {
  1511. with_state(this, |_, s| s.set_constants(false, slot, &[value], offset));
  1512. }
  1513. pub(super) extern "system" fn compute_constants(
  1514. this: This,
  1515. slot: u32,
  1516. count: u32,
  1517. values: *const u32,
  1518. offset: u32,
  1519. ) {
  1520. with_state(this, |_, s| {
  1521. s.set_constants(true, slot, items(values, count), offset)
  1522. });
  1523. }
  1524. pub(super) extern "system" fn graphics_constants(
  1525. this: This,
  1526. slot: u32,
  1527. count: u32,
  1528. values: *const u32,
  1529. offset: u32,
  1530. ) {
  1531. with_state(this, |_, s| {
  1532. s.set_constants(false, slot, items(values, count), offset)
  1533. });
  1534. }
  1535. /// Root constant buffer, shader resource and unordered access views.
  1536. pub(super) extern "system" fn compute_view(this: This, slot: u32, address: u64) {
  1537. with_state(this, |_, s| s.set_view(true, slot, address));
  1538. }
  1539. pub(super) extern "system" fn graphics_view(this: This, slot: u32, address: u64) {
  1540. with_state(this, |_, s| s.set_view(false, slot, address));
  1541. }
  1542. pub(super) extern "system" fn index_buffer(this: This, view: *const IndexView) {
  1543. // SAFETY: the title passes a view or null.
  1544. with_state(this, |_, s| s.set_index_buffer(unsafe { view.as_ref() }));
  1545. }
  1546. pub(super) extern "system" fn vertex_buffers(
  1547. this: This,
  1548. start: u32,
  1549. count: u32,
  1550. views: *const VertexView,
  1551. ) {
  1552. with_state(this, |_, s| {
  1553. if views.is_null() {
  1554. s.clear_vertex_buffers(start, count);
  1555. } else {
  1556. s.set_vertex_buffers(start, items(views, count));
  1557. }
  1558. });
  1559. }
  1560. /// `(count, handles, one range, depth)`: with one range, the handles
  1561. /// follow the first at the render target view size (128 bytes).
  1562. pub(super) extern "system" fn targets(
  1563. this: This,
  1564. count: u32,
  1565. handles: *const u64,
  1566. one_range: i32,
  1567. depth: *const u64,
  1568. ) {
  1569. let handles: Vec<u64> = if one_range != 0 && !handles.is_null() {
  1570. // SAFETY: the title passes the first handle.
  1571. let first = unsafe { *handles };
  1572. (0..u64::from(count)).map(|i| first + 128 * i).collect()
  1573. } else {
  1574. items(handles, count).to_vec()
  1575. };
  1576. // SAFETY: the title passes a handle or null.
  1577. let depth = unsafe { depth.as_ref() }.copied().unwrap_or(0);
  1578. with_state(this, |list, s| s.set_targets(list, &handles, depth));
  1579. }
  1580. pub(super) extern "system" fn draw(
  1581. this: This,
  1582. vertices: u32,
  1583. instances: u32,
  1584. first: u32,
  1585. first_instance: u32,
  1586. ) {
  1587. super::count_draw();
  1588. with_state(this, |list, s| {
  1589. s.draw(list, vertices, instances, first, first_instance)
  1590. });
  1591. }
  1592. pub(super) extern "system" fn dispatch(this: This, x: u32, y: u32, z: u32) {
  1593. super::count_dispatch();
  1594. with_state(this, |list, s| s.dispatch(list, x, y, z));
  1595. }
  1596. /// `DispatchMesh(x, y, z)` (the PC method of List6); the title's mesh
  1597. /// programs take `x` groups only.
  1598. pub(super) extern "system" fn dispatch_mesh(this: This, x: u32, y: u32, z: u32) {
  1599. super::count_draw();
  1600. if y * z != 1 {
  1601. static ONCE: std::sync::Once = std::sync::Once::new();
  1602. ONCE.call_once(|| tracing::warn!(x, y, z, "a mesh dispatch with y or z groups"));
  1603. }
  1604. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1605. }
  1606. /// `DispatchMeshX(x, flags, indirect arguments, payload)`.
  1607. /// shortcut: dispatches whose group count is in GPU memory (indirect)
  1608. /// are dropped; make them ExecuteIndirect when the title uses them.
  1609. pub(super) extern "system" fn dispatch_mesh_x(
  1610. this: This,
  1611. x: u32,
  1612. _flags: u64,
  1613. indirect: u64,
  1614. _payload: u64,
  1615. ) {
  1616. super::count_draw();
  1617. if indirect != 0 {
  1618. static ONCE: std::sync::Once = std::sync::Once::new();
  1619. ONCE.call_once(|| tracing::warn!("indirect mesh dispatches dropped"));
  1620. return;
  1621. }
  1622. with_state(this, |list, s| s.dispatch_mesh(list, x));
  1623. }
  1624. pub(super) extern "system" fn draw_indexed(
  1625. this: This,
  1626. indices: u32,
  1627. instances: u32,
  1628. first: u32,
  1629. base: i32,
  1630. first_instance: u32,
  1631. ) {
  1632. super::count_draw();
  1633. with_state(this, |list, s| {
  1634. s.draw_indexed(list, indices, instances, first, base, first_instance)
  1635. });
  1636. }
  1637. }
  1638. /// Without a host GPU every draw state call is ignored.
  1639. #[cfg(not(windows))]
  1640. mod state {
  1641. pub(super) use super::dispatch;
  1642. pub(super) use super::draw;
  1643. pub(super) use super::draw as draw_indexed;
  1644. pub(super) use super::draw as dispatch_mesh;
  1645. pub(super) use super::draw as dispatch_mesh_x;
  1646. pub(super) use super::ignored_state as blend_factor;
  1647. pub(super) use super::ignored_state as compute_constant;
  1648. pub(super) use super::ignored_state as compute_constants;
  1649. pub(super) use super::ignored_state as compute_table;
  1650. pub(super) use super::ignored_state as compute_view;
  1651. pub(super) use super::ignored_state as graphics_constant;
  1652. pub(super) use super::ignored_state as graphics_constants;
  1653. pub(super) use super::ignored_state as graphics_table;
  1654. pub(super) use super::ignored_state as graphics_view;
  1655. pub(super) use super::ignored_state as heaps;
  1656. pub(super) use super::ignored_state as index_buffer;
  1657. pub(super) use super::ignored_state as scissors;
  1658. pub(super) use super::ignored_state as stencil_ref;
  1659. pub(super) use super::ignored_state as depth_bounds;
  1660. pub(super) use super::ignored_state as targets;
  1661. pub(super) use super::ignored_state as topology;
  1662. pub(super) use super::ignored_state as vertex_buffers;
  1663. pub(super) use super::ignored_state as viewports;
  1664. }
  1665. fn count_draw() {
  1666. DRAWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1667. }
  1668. /// Draws of the kinds the host does not run yet (indirect, mesh), and
  1669. /// dispatches, counted per frame for the log.
  1670. /// shortcut: dropped until their shaders translate (decision 0007).
  1671. #[cfg(not(windows))]
  1672. extern "system" fn draw(_: This) {
  1673. count_draw();
  1674. }
  1675. /// `ExecuteIndirect(signature, max count, arguments, offset, count buffer,
  1676. /// offset)`. The title's signatures (title+0x2479466, 2026-11-24)
  1677. /// hold one argument each: draw (stride 16), indexed draw (20), dispatch
  1678. /// (12), mesh dispatch (12), and the console's single-pass dispatch, type
  1679. /// 105 (stride 12: the three group counts; its flags live in the
  1680. /// signature, the title passes none), run as a plain dispatch. They run
  1681. /// through the host's indirect execution (`State::execute_indirect`).
  1682. /// shortcut: signatures that change root arguments are dropped (logged
  1683. /// once per signature).
  1684. extern "system" fn execute_indirect(
  1685. this: This,
  1686. signature: This,
  1687. max: u32,
  1688. arguments: This,
  1689. offset: u64,
  1690. count: This,
  1691. count_offset: u64,
  1692. ) {
  1693. count_draw();
  1694. let Some((stride, args)) = crate::signature::layout(signature) else {
  1695. return;
  1696. };
  1697. let address = crate::resource::buffer_bytes(arguments).map(|(p, _)| p as u64 + offset);
  1698. let counter = crate::resource::buffer_bytes(count).map(|(p, _)| p as u64 + count_offset);
  1699. let mut ran = false;
  1700. #[cfg(windows)]
  1701. if let ([[kind, ..]], Some(address)) = (args, address)
  1702. && (count.is_null() || counter.is_some())
  1703. {
  1704. const DISPATCH: u32 = 2;
  1705. const DISPATCH_SINGLE: u32 = 105;
  1706. let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind };
  1707. with_state(this, |list, s| {
  1708. ran = s.execute_indirect(list, (kind, stride, max), address, counter);
  1709. });
  1710. } else {
  1711. #[cfg(all(windows, feature = "diagnostics"))]
  1712. crate::pipeline::note_why(format!(
  1713. "indirect signature {args:?}: arguments in a buffer {}, count in a buffer {}",
  1714. address.is_some(),
  1715. count.is_null() || counter.is_some()
  1716. ));
  1717. }
  1718. if ran {
  1719. return;
  1720. }
  1721. INDIRECT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1722. static SEEN: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
  1723. let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
  1724. if !seen.contains(&(signature as usize)) {
  1725. seen.push(signature as usize);
  1726. tracing::info!(
  1727. stride,
  1728. ?args,
  1729. max,
  1730. address = ?address.map(|a| format!("{a:#x}")),
  1731. counted = !count.is_null(),
  1732. "indirect execution dropped (first time for this signature)"
  1733. );
  1734. }
  1735. }
  1736. /// Indirect executions dropped since the last call.
  1737. pub(crate) fn take_indirect() -> u64 {
  1738. INDIRECT.swap(0, std::sync::atomic::Ordering::Relaxed)
  1739. }
  1740. static INDIRECT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1741. fn count_dispatch() {
  1742. DISPATCHES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1743. }
  1744. #[cfg(not(windows))]
  1745. extern "system" fn dispatch(_: This) {
  1746. count_dispatch();
  1747. }
  1748. static DRAWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1749. static DISPATCHES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1750. /// Draws (any kind, mesh and indirect included) and compute dispatches
  1751. /// recorded since the last call.
  1752. pub(crate) fn take_counts() -> (u64, u64) {
  1753. use std::sync::atomic::Ordering::Relaxed;
  1754. (DRAWS.swap(0, Relaxed), DISPATCHES.swap(0, Relaxed))
  1755. }
  1756. /// A GPU wait for a memory value: the list's commands after it run when
  1757. /// the 32 or 64 bits at `address` compare as asked with `reference`.
  1758. #[derive(Clone, Copy, Debug)]
  1759. pub(crate) struct ValueWait {
  1760. address: u64,
  1761. comparison: u32,
  1762. reference: u64,
  1763. wide: bool,
  1764. }
  1765. impl ValueWait {
  1766. /// Whether the memory holds what is waited for now.
  1767. /// shortcut: the comparison codes are taken to be the comparison
  1768. /// functions' (1 never .. 8 always, value against reference); one not
  1769. /// known counts as met, and so does memory that is not mapped.
  1770. ///
  1771. /// The value is read through the kernel, which reports memory that is
  1772. /// not there instead of faulting (as the copies of title memory are
  1773. /// read, `crate::host::copy_mapped`). Asking Windows first whether the
  1774. /// memory is committed (`VirtualQuery`) walks the page tables to the
  1775. /// end of the region: the title keeps these values in a 1.1 GB
  1776. /// allocation (0xd00000000), where one question took about 8 ms, and a
  1777. /// queue asks at every submission and every signal, for each queue that
  1778. /// stands at a wait (the title has five queues). That was
  1779. /// 1.0-2.2 s of every cutscene frame on the thread that submits (runs
  1780. /// 36-49: "between its submissions ... kernel"; 47 of 110 looks at
  1781. /// that thread in run 49 found it in this question).
  1782. /// `VICTORY_WAIT_ASK=1` asks first, as before.
  1783. pub(crate) fn met(&self) -> bool {
  1784. #[cfg(all(windows, feature = "diagnostics"))]
  1785. let started = std::time::Instant::now();
  1786. let met = self.holds();
  1787. #[cfg(all(windows, feature = "diagnostics"))]
  1788. {
  1789. use crate::copystat::{C, add};
  1790. add(C::WaitChecks, 1);
  1791. add(C::WaitCheckNs, started.elapsed().as_nanos() as u64);
  1792. }
  1793. met
  1794. }
  1795. fn holds(&self) -> bool {
  1796. let bytes = if self.wide { 8 } else { 4 };
  1797. if self.address == 0 {
  1798. return true;
  1799. }
  1800. static ASK: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1801. if *ASK.get_or_init(|| std::env::var_os("VICTORY_WAIT_ASK").is_some_and(|v| v == "1"))
  1802. && !crate::texture::committed(self.address as *const u8, bytes)
  1803. {
  1804. return true;
  1805. }
  1806. // The low `bytes` bytes; the rest stays zero.
  1807. let mut raw = [0u8; 8];
  1808. if !crate::host::read_into(self.address as *const u8, &mut raw[..bytes]) {
  1809. return true;
  1810. }
  1811. self.holds_for(u64::from_le_bytes(raw))
  1812. }
  1813. /// Where the value waited for is: address and bytes.
  1814. #[cfg(windows)]
  1815. pub(crate) fn place(&self) -> (usize, usize) {
  1816. (self.address as usize, if self.wide { 8 } else { 4 })
  1817. }
  1818. /// Whether the wait is met with `value` at its address (its low half
  1819. /// for a 32-bit wait).
  1820. pub(crate) fn holds_for(&self, value: u64) -> bool {
  1821. let (value, reference) = if self.wide {
  1822. (value, self.reference)
  1823. } else {
  1824. (value & 0xFFFF_FFFF, self.reference & 0xFFFF_FFFF)
  1825. };
  1826. match self.comparison {
  1827. 1 => false,
  1828. 2 => value < reference,
  1829. 3 => value == reference,
  1830. 4 => value <= reference,
  1831. 5 => value > reference,
  1832. 6 => value != reference,
  1833. 7 => value >= reference,
  1834. _ => true,
  1835. }
  1836. }
  1837. }
  1838. /// The waits lists recorded since their last reset, by list.
  1839. static VALUE_WAITS: std::sync::Mutex<Vec<(usize, ValueWait)>> = std::sync::Mutex::new(Vec::new());
  1840. /// The waits of the submitted `lists` that are not met yet (taken from
  1841. /// them): what the console's GPU would stop at. The title orders work
  1842. /// between its queues this way (the title: the compute queue's
  1843. /// lighting passes wait for a value the graphics queue's depth pass writes
  1844. /// at the bottom of the pipe; run at once, they read a cleared depth
  1845. /// buffer and nothing was lit).
  1846. /// shortcut: a wait holds its whole list (and submission) back, not only
  1847. /// the commands after it.
  1848. pub(crate) fn unmet_waits(lists: &[This]) -> Vec<ValueWait> {
  1849. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1850. let mut unmet = Vec::new();
  1851. waits.retain(|&(list, wait)| {
  1852. if !lists.iter().any(|&l| l as usize == list) {
  1853. return true;
  1854. }
  1855. if !wait.met() {
  1856. unmet.push(wait);
  1857. }
  1858. false
  1859. });
  1860. unmet
  1861. }
  1862. /// The waits each of the submitted `lists` recorded (taken from them),
  1863. /// met or not, at the list's first place in the submission.
  1864. #[cfg(windows)]
  1865. pub(crate) fn waits_by_list(lists: &[This]) -> Vec<Vec<ValueWait>> {
  1866. let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner());
  1867. let mut by = vec![Vec::new(); lists.len()];
  1868. waits.retain(|&(list, wait)| {
  1869. match lists.iter().position(|&l| l as usize == list) {
  1870. Some(i) => {
  1871. by[i].push(wait);
  1872. false
  1873. }
  1874. None => true,
  1875. }
  1876. });
  1877. by
  1878. }
  1879. fn wait_for(this: This, address: u64, comparison: u32, reference: u64, wide: bool) {
  1880. let wait = ValueWait {
  1881. address,
  1882. comparison,
  1883. reference,
  1884. wide,
  1885. };
  1886. static SEEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  1887. if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 12 {
  1888. tracing::info!(
  1889. address = format_args!("{address:#x}"),
  1890. comparison,
  1891. reference,
  1892. wide,
  1893. met = wait.met(),
  1894. "a list waits for a memory value"
  1895. );
  1896. }
  1897. #[cfg(all(windows, feature = "diagnostics"))]
  1898. if let Some(host) = host_list(this) {
  1899. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1900. format!(
  1901. "WAIT VALUE at {address:#x} comparison {comparison} reference {reference:#x} wide {wide} met {}",
  1902. wait.met()
  1903. )
  1904. });
  1905. }
  1906. // The list is cut here, and the wait stands before what follows.
  1907. #[cfg(windows)]
  1908. if crate::queue::cuts() {
  1909. cut(this, wait);
  1910. return;
  1911. }
  1912. VALUE_WAITS
  1913. .lock()
  1914. .unwrap_or_else(|e| e.into_inner())
  1915. .push((this as usize, wait));
  1916. }
  1917. extern "system" fn wait_value(this: This, address: u64, comparison: u32, reference: u64) {
  1918. wait_for(this, address, comparison, reference, false);
  1919. }
  1920. extern "system" fn wait_value64(this: This, address: u64, comparison: u32, reference: u64) {
  1921. wait_for(this, address, comparison, reference, true);
  1922. }
  1923. /// The enhanced barriers `(group count, groups)`: buffer, texture and
  1924. /// global barriers with layouts instead of states. Every host use of a
  1925. /// title texture (clears, copies) moves its host copy to the state it needs
  1926. /// first, so only their ordering matters: one barrier on every shader
  1927. /// write (the title's buffer barriers order compute passes).
  1928. extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) {
  1929. // Diagnostics: counted, and left out under `VICTORY_BARRIER_TEST=groups`.
  1930. #[cfg(all(windows, feature = "diagnostics"))]
  1931. if count > 0 {
  1932. crate::copystat::add(crate::copystat::C::WaitsForGroups, 1);
  1933. if crate::copystat::barrier_test() & 1 != 0 {
  1934. return;
  1935. }
  1936. }
  1937. #[cfg(windows)]
  1938. if count > 0
  1939. && let Some(list) = host_list(this)
  1940. {
  1941. use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER;
  1942. with_state(this, |_, state| state.synced());
  1943. // SAFETY: the same layout; no resource named.
  1944. let barrier = unsafe { std::mem::transmute::<Barrier, D3D12_RESOURCE_BARRIER>(UAV_BARRIER) };
  1945. // SAFETY: an open list.
  1946. unsafe { list.list.ResourceBarrier(&[barrier]) };
  1947. }
  1948. #[cfg(not(windows))]
  1949. let _ = (this, count);
  1950. }
  1951. /// The bottom-of-pipe value writes `(address, value, flush, flags)`, 32 and
  1952. /// 64 bits: done when the list has run, as the GPU would. Flag 1 writes the
  1953. /// GPU timestamp instead (64-bit form), flag 2 the system timestamp.
  1954. extern "system" fn write32(this: This, address: u64, value: u32, _flush: u32, _flags: u32) {
  1955. defer_write(this, address, Written::Value(u64::from(value)), 4);
  1956. value_written(this, address, u64::from(value));
  1957. }
  1958. extern "system" fn write64(this: This, address: u64, value: u64, _flush: u32, flags: u32) {
  1959. const GPU_TIMESTAMP: u32 = 1;
  1960. const SYSTEM_TIMESTAMP: u32 = 2;
  1961. let what = match flags {
  1962. GPU_TIMESTAMP => Written::GpuTimestamp,
  1963. SYSTEM_TIMESTAMP => Written::SystemTimestamp,
  1964. _ => Written::Value(value),
  1965. };
  1966. defer_write(this, address, what, 8);
  1967. if let Written::Value(value) = what {
  1968. value_written(this, address, value);
  1969. }
  1970. }
  1971. /// The title wrote a value at the bottom of the pipe (not a timestamp, not
  1972. /// a query result): listed (diagnostics), and with `VICTORY_CUT_WRITES=1`
  1973. /// the host list is cut right behind it, so that the value is stored when
  1974. /// the card has run the list up to there, as on the console, and not when
  1975. /// the whole list has run. Lists of other queues wait for these values
  1976. /// (the title: the compute list that builds the depth pyramid
  1977. /// waits for one, and the meshlet culling of the same frame reads that
  1978. /// pyramid). Off by default: every such write then ends a host list, and
  1979. /// each part is a submission of its own.
  1980. fn value_written(this: This, address: u64, value: u64) {
  1981. #[cfg(windows)]
  1982. {
  1983. if address == 0 || this.is_null() {
  1984. return;
  1985. }
  1986. #[cfg(not(feature = "diagnostics"))]
  1987. let _ = value;
  1988. #[cfg(feature = "diagnostics")]
  1989. if let Some(host) = host_list(this) {
  1990. crate::capture::op(std::ptr::from_ref(host) as usize, || {
  1991. format!("WRITE VALUE at {address:#x} value {value:#x}")
  1992. });
  1993. }
  1994. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1995. if !*ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WRITES").is_some_and(|v| v == "1"))
  1996. || !crate::queue::cuts()
  1997. {
  1998. return;
  1999. }
  2000. // SAFETY: the title passes one of our lists; a list is recorded by
  2001. // one thread at a time and is not submitted while it records.
  2002. let list = unsafe { &mut *this.cast_mut().cast::<List>() };
  2003. let Some(current) = list.host.as_ref() else {
  2004. return;
  2005. };
  2006. let Some(fresh) = fresh_list() else {
  2007. return;
  2008. };
  2009. current.close();
  2010. if let Some(done) = list.host.replace(fresh) {
  2011. // The part so far keeps its waits; nothing stands before the
  2012. // next one but this part itself.
  2013. let waits = std::mem::take(&mut list.gate);
  2014. list.earlier.push(Part { waits, host: done });
  2015. }
  2016. if let Some(host) = list.host.as_ref() {
  2017. list.state
  2018. .lock()
  2019. .unwrap_or_else(|e| e.into_inner())
  2020. .replay(host);
  2021. }
  2022. }
  2023. #[cfg(not(windows))]
  2024. let _ = (this, address, value);
  2025. }
  2026. fn defer_write(this: This, address: u64, what: Written, bytes: usize) {
  2027. if address == 0 {
  2028. return;
  2029. }
  2030. #[cfg(windows)]
  2031. if let Some(list) = host_list(this) {
  2032. list.defer_write(address as *mut u8, what, bytes);
  2033. return;
  2034. }
  2035. let _ = this;
  2036. // Without a host GPU nothing runs later: write now.
  2037. what.write(address as *mut u8, bytes);
  2038. }
  2039. /// The list methods by their slot in older titles' lists (the 2020-era
  2040. /// layout): IUnknown 3, object 4, device child 1, list 1, graphics list 96
  2041. /// (59 as on PC, then console ones), then versions 1-6 (6 + 1 + 1 + 11 + 3
  2042. /// + 13): 140 slots.
  2043. const METHODS: [(usize, *const ()); 52] = [
  2044. (0, list_query as *const ()),
  2045. (2, list_release as *const ()),
  2046. (7, object::parent_device as *const ()), // 0x38
  2047. (8, list_type as *const ()), // 0x40
  2048. (9, close as *const ()), // 0x48
  2049. (10, reset as *const ()), // 0x50
  2050. (12, state::draw as *const ()), // 0x60 instanced
  2051. (13, state::draw_indexed as *const ()), // 0x68 indexed
  2052. (14, state::dispatch as *const ()), // 0x70
  2053. (15, copy_buffer_region as *const ()), // 0x78
  2054. (16, copy_texture_region as *const ()), // 0x80
  2055. (17, copy_resource as *const ()), // 0x88
  2056. (19, resolve as *const ()), // 0x98
  2057. (20, state::topology as *const ()), // 0xa0
  2058. (21, state::viewports as *const ()), // 0xa8
  2059. (22, state::scissors as *const ()), // 0xb0
  2060. (23, state::blend_factor as *const ()), // 0xb8
  2061. (24, state::stencil_ref as *const ()), // 0xc0
  2062. (25, set_pipeline as *const ()), // 0xc8
  2063. (26, barrier as *const ()), // 0xd0
  2064. (32, state::heaps as *const ()), // 0x100
  2065. (33, ignored_state as *const ()), // 0x108 compute root signature
  2066. (34, ignored_state as *const ()), // 0x110 graphics root signature
  2067. (35, state::compute_table as *const ()), // 0x118
  2068. (36, state::graphics_table as *const ()), // 0x120
  2069. (37, state::compute_constant as *const ()), // 0x128
  2070. (38, state::graphics_constant as *const ()), // 0x130
  2071. (39, state::compute_constants as *const ()), // 0x138
  2072. (40, state::graphics_constants as *const ()), // 0x140
  2073. (41, state::compute_view as *const ()), // 0x148 CBV
  2074. (42, state::graphics_view as *const ()), // 0x150 CBV
  2075. (43, state::compute_view as *const ()), // 0x158 SRV
  2076. (44, state::graphics_view as *const ()), // 0x160 SRV
  2077. (45, state::compute_view as *const ()), // 0x168 UAV
  2078. (46, state::graphics_view as *const ()), // 0x170 UAV
  2079. (47, state::index_buffer as *const ()), // 0x178
  2080. (48, state::vertex_buffers as *const ()), // 0x180
  2081. (50, state::targets as *const ()), // 0x190
  2082. (51, clear_dsv as *const ()), // 0x198
  2083. (52, clear_rtv as *const ()), // 0x1a0
  2084. (59, execute_indirect as *const ()), // 0x1d8 indirect
  2085. (60, copy_memory as *const ()), // 0x1e0
  2086. (68, state::depth_bounds as *const ()), // 0x220 depth bounds
  2087. (69, write32 as *const ()), // 0x228
  2088. (70, write64 as *const ()), // 0x230
  2089. (71, wait_value as *const ()), // 0x238, 32 bits
  2090. (72, wait_value64 as *const ()), // 0x240, 64 bits
  2091. (73, ignored_state as *const ()), // 0x248 pixel shader depth order
  2092. (83, copy_texture_region_x as *const ()), // 0x298
  2093. (84, copy_resource_x as *const ()), // 0x2a0
  2094. (124, ignored_state as *const ()), // 0x3e0 shading rate
  2095. (127, state::dispatch_mesh as *const ()), // 0x3f8 mesh dispatch
  2096. ];
  2097. /// The rest of [`METHODS`], kept apart only to stay readable.
  2098. const MORE_METHODS: [(usize, *const ()); 9] = [
  2099. (28, query_mark as *const ()), // 0xe0 BeginQuery
  2100. (29, query_mark as *const ()), // 0xe8 EndQuery
  2101. (30, resolve_queries as *const ()), // 0xf0
  2102. (78, dispatch_x as *const ()), // 0x270
  2103. (98, state::dispatch_mesh_x as *const ()), // 0x310
  2104. (99, driver_hint as *const ()), // 0x318
  2105. // Pipeline syncs at the top and bottom of the pipe, 0x408 and 0x410.
  2106. (129, sync as *const ()),
  2107. (130, sync as *const ()),
  2108. (137, reset_x as *const ()), // 0x448
  2109. ];
  2110. /// Newer titles' lists have two more methods in the console part of the
  2111. /// base list, after the clears (0x198/0x1a0 as before) and before
  2112. /// ExecuteIndirect, which moved from 0x1d8 to 0x1e8: every slot from 0x1d8
  2113. /// on is two later (taken here as starting exactly at 0x1d8). Inferred from
  2114. /// The title's call shapes: ExecuteIndirect 0x1e8, bottom-of-pipe
  2115. /// writes 0x238/0x240, waits 0x248/0x250, depth bounds 0x230, shading rate
  2116. /// 0x3f0/0x400, syncs 0x418/0x420, ResetX 0x458 (asserts on failure).
  2117. const fn newer_slot(slot: usize) -> usize {
  2118. if slot >= 59 { slot + 2 } else { slot }
  2119. }
  2120. /// Methods only newer titles' lists have. 0x490: the enhanced barrier
  2121. /// `(group count, groups)`, with 16-byte groups `(type, count, barriers)`
  2122. /// and 40-byte buffer barriers (title+0x95e0 builds them). 0x470 `(u64)`,
  2123. /// called from the title's state flush with its result unused.
  2124. /// shortcut: 0x470's purpose is unknown; ignored until a title shows it
  2125. /// matters.
  2126. const NEWER_METHODS: [(usize, *const ()); 3] = [
  2127. (142, ignored_state as *const ()),
  2128. (146, barrier_groups as *const ()),
  2129. (148, allocate_upload as *const ()),
  2130. ];
  2131. const fn list_table(newer: bool) -> [*const (); 160] {
  2132. let mut f = object::d3d12_object(object::missing_table::<LIST, 160>());
  2133. let mut i = 0;
  2134. while i < METHODS.len() + MORE_METHODS.len() {
  2135. let (slot, method) = if i < METHODS.len() {
  2136. METHODS[i]
  2137. } else {
  2138. MORE_METHODS[i - METHODS.len()]
  2139. };
  2140. f[if newer { newer_slot(slot) } else { slot }] = method;
  2141. i += 1;
  2142. }
  2143. let mut i = 0;
  2144. while newer && i < NEWER_METHODS.len() {
  2145. f[NEWER_METHODS[i].0] = NEWER_METHODS[i].1;
  2146. i += 1;
  2147. }
  2148. f
  2149. }
  2150. /// Every slot up to the limit exists and logs, for the methods newer
  2151. /// titles add.
  2152. static LIST_FUNCTIONS: Table<160> = Table(list_table(false));
  2153. static NEWER_LIST_FUNCTIONS: Table<160> = Table(list_table(true));
  2154. #[cfg(test)]
  2155. mod tests {
  2156. use super::*;
  2157. use crate::object::slot;
  2158. #[test]
  2159. fn every_inline_command_falls_back_to_the_table() {
  2160. let null = std::ptr::null();
  2161. let mut allocator = null;
  2162. assert_eq!(
  2163. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2164. S_OK
  2165. );
  2166. let mut list = null;
  2167. let hr = create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list);
  2168. assert_eq!(hr, S_OK);
  2169. // What the title's inline draw checks: put < draw limit.
  2170. // SAFETY: the list is 0x560 bytes.
  2171. let (put, draw_limit, api_limit) = unsafe {
  2172. let at = |o: usize| list.cast::<u8>().add(o).cast::<u64>().read();
  2173. (at(0x18), at(0x28), at(0x30))
  2174. };
  2175. assert!(put >= draw_limit && put >= api_limit);
  2176. // The console's ID3D12GraphicsCommandList6, as the title asks.
  2177. let mut same = null;
  2178. assert_eq!(list_query(list, &LIST_IIDS[7], &mut same), S_OK);
  2179. assert_eq!(same, list);
  2180. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x10)(list), 1);
  2181. assert_eq!(slot::<extern "system" fn(This) -> u32>(list, 0x40)(list), 0);
  2182. assert_eq!(
  2183. slot::<extern "system" fn(This) -> HRESULT>(list, 0x48)(list),
  2184. S_OK
  2185. );
  2186. // List-owned upload memory: aligned, writable, gone at reset.
  2187. let p = allocate_upload(list, 40, 0x100);
  2188. assert!(!p.is_null() && (p as usize).is_multiple_of(0x100));
  2189. // SAFETY: 40 bytes were handed out.
  2190. unsafe { p.write_bytes(0xab, 40) };
  2191. assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two");
  2192. assert_eq!(reset(list, allocator, null), S_OK);
  2193. // SAFETY: the list is ours.
  2194. assert!(unsafe { &(*list.cast::<List>()).uploads }.lock().unwrap().is_empty());
  2195. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2196. assert_eq!(release(list), 0);
  2197. assert_eq!(release(allocator), 0);
  2198. }
  2199. /// An offset near `u64::MAX` must not overflow and write outside the
  2200. /// query destination buffer.
  2201. #[test]
  2202. fn resolve_queries_rejects_overflowing_offset() {
  2203. let null = std::ptr::null();
  2204. let mut allocator = null;
  2205. assert_eq!(
  2206. create_allocator(null, 0, &ALLOCATOR_IIDS[0], &mut allocator),
  2207. S_OK
  2208. );
  2209. let mut list = null;
  2210. assert_eq!(
  2211. create_list(null, 0, 0, allocator, null, &LIST_IIDS[1], &mut list),
  2212. S_OK
  2213. );
  2214. let buffer = crate::resource::test_buffer(64);
  2215. // Used to overflow `offset + count * 8` (panic in debug, wrap in release).
  2216. resolve_queries(list, null, 0, 0, 2, buffer, u64::MAX - 8);
  2217. let release = |o: This| slot::<extern "system" fn(This) -> u32>(o, 0x10)(o);
  2218. for object in [buffer, list, allocator] {
  2219. assert_eq!(release(object), 0);
  2220. }
  2221. }
  2222. }