list.rs 91 KB

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