list.rs 92 KB

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