texture.rs 79 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782
  1. //! Texture contents the title writes itself (decision 0007, "Texture
  2. //! memory"): streamed pages, layout-library copies, movie frames, glyph
  3. //! atlases. Such a texture lives in console memory in its tiled layout;
  4. //! before a submission samples its host copy, the memory is detiled into a
  5. //! staging buffer when its content changed, and the staging buffer is
  6. //! copied into the host texture.
  7. //!
  8. //! "Changed" means a page of the memory was written since the last detiling
  9. //! ([`crate::watch`]), in write-watched memory; in physical-page views,
  10. //! which cannot be watched, a content hash of the whole memory at every
  11. //! submission that samples it.
  12. //!
  13. //! shortcut: a change detiles the whole texture, not the pages written.
  14. //! Only textures read through descriptor tables are brought up to date
  15. //! (directly indexed views are not known per draw); plane 0 is uploaded
  16. //! (every mip and array slice), depth and stencil planes are not.
  17. use std::collections::HashMap;
  18. use std::sync::{Arc, Mutex};
  19. use windows::Win32::Graphics::Direct3D12::*;
  20. use crate::host::{HostList, host};
  21. use crate::object::This;
  22. macro_rules! once {
  23. ($($arg:tt)*) => {{
  24. static ONCE: std::sync::Once = std::sync::Once::new();
  25. ONCE.call_once(|| tracing::warn!($($arg)*));
  26. }};
  27. }
  28. /// A texture's upload state: the staging buffer laid out as the host
  29. /// texture's subresources, and what was last detiled.
  30. pub(crate) struct Staging {
  31. /// A buffer of its own, or the block [`Staging::piece`] is part of.
  32. buffer: ID3D12Resource,
  33. /// Where in `buffer` it begins (the footprints count from there).
  34. base: u64,
  35. /// Back in the pool with the last list that names it.
  36. _piece: Option<crate::pool::StagingPiece>,
  37. /// Its bytes.
  38. #[cfg(feature = "diagnostics")]
  39. size: u64,
  40. data: *mut u8,
  41. footprints: Vec<D3D12_PLACED_SUBRESOURCE_FOOTPRINT>,
  42. rows: Vec<u32>,
  43. layout: victory_formats::texture::Layout,
  44. /// Mips per array slice.
  45. mips: u32,
  46. /// The staging buffer's bytes (counted in `STAGED` while it lives).
  47. bytes: u64,
  48. memory: *const u8,
  49. last: Mutex<Last>,
  50. /// Whether the staging buffer was detiled since a submitted list last
  51. /// uploaded it, and whether one has uploaded it at all: a list records
  52. /// the upload only then. (Every list that sampled a title texture
  53. /// uploaded all of it again, changed or not: 5,411 subresource copies
  54. /// of 1,120 textures in one frame of run 18.)
  55. dirty: std::sync::atomic::AtomicBool,
  56. uploaded: std::sync::atomic::AtomicBool,
  57. /// When a list last recorded a use of it (`crate::host::moment`).
  58. used: std::sync::atomic::AtomicU64,
  59. /// Levels on demand (`crate::tiles`): the texture's host copy was made
  60. /// without memory of its own when the staging buffer was made.
  61. on_demand: bool,
  62. /// For such a texture: the levels that were the title's at the last
  63. /// detiling (a bit a level; the staging buffer holds zeros for the
  64. /// others), and what that was judged by ([`Staging::judgement`]).
  65. detiled: std::sync::atomic::AtomicU32,
  66. judged: [std::sync::atomic::AtomicU64; 2],
  67. /// For such a texture: when an upload last left a held level without
  68. /// tiles (`crate::host::moment`, never 0; 0: none did). The upload is
  69. /// recorded again about a second later if the card has room by then
  70. /// ([`upload`]).
  71. waiting: std::sync::atomic::AtomicU64,
  72. }
  73. /// What a texture's staging buffer holds: the hash of the memory detiled
  74. /// (memory not watched), or the write-watch asking it was detiled after.
  75. #[derive(Default)]
  76. struct Last {
  77. hash: Option<blake3::Hash>,
  78. asked: u64,
  79. /// The frame a partly mapped texture was last read in.
  80. partial: Option<u64>,
  81. /// Until this frame a guarded texture is hashed at every check: its
  82. /// first checks, and after the hash found a change the guard had not
  83. /// seen ([`hot_textures`]). 0: not checked under the guard yet.
  84. hot_until: u64,
  85. }
  86. /// Frames a guarded texture is hashed at every check from its first check,
  87. /// and after the hash found a change the guard did not see.
  88. const HOT_FRAMES: u64 = 64;
  89. /// Whether a guarded texture whose memory the hash found changed although
  90. /// the guard saw no write is hashed at every check for a while
  91. /// ([`HOT_FRAMES`]), not every eighth frame. A title that writes such a
  92. /// texture through another view of its pages (the guard sees none of it)
  93. /// every frame, a video's frames in a ring of three, showed each one up
  94. /// to eight frames late and in turns: the boot logo video and the loading
  95. /// animation flickered between old and new pictures (fx-flicker run 1441:
  96. /// the presented picture cycled through three, a new one every eight
  97. /// frames). A texture also starts hot, for the ones written that way from
  98. /// the start (the six-star screen of the first seconds, which the hash
  99. /// never caught changing). `VICTORY_TEXTURE_HOT=0`: every eighth frame
  100. /// only, as before.
  101. fn hot_textures() -> bool {
  102. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  103. *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_HOT").is_none_or(|v| v != "0"))
  104. }
  105. // SAFETY: the staging mapping is written only at submission, under
  106. // `last`'s lock; the title memory is only read.
  107. unsafe impl Send for Staging {}
  108. // SAFETY: as above.
  109. unsafe impl Sync for Staging {}
  110. static STAGING: Mutex<Option<HashMap<usize, Arc<Staging>>>> = Mutex::new(None);
  111. /// The buffer a texture the host writes is copied through into the texture
  112. /// of a view the title placed in its memory in another format
  113. /// ([`alias`]): every level of every layer as each of the two formats lays
  114. /// it out for a copy (the same bytes: the texels are as wide), the written
  115. /// texture's layout first.
  116. struct Through {
  117. buffer: ID3D12Resource,
  118. parts: Vec<(
  119. D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  120. D3D12_PLACED_SUBRESOURCE_FOOTPRINT,
  121. )>,
  122. }
  123. /// The most levels times layers [`alias`] copies (a cube of nine levels).
  124. const ALIAS_PARTS: u32 = 54;
  125. // SAFETY: a device-local buffer only lists record copies with.
  126. unsafe impl Send for Through {}
  127. // SAFETY: as above.
  128. unsafe impl Sync for Through {}
  129. /// The copy buffers of [`alias`], by the placed view's texture.
  130. static THROUGH: Mutex<Option<HashMap<usize, Arc<Through>>>> = Mutex::new(None);
  131. /// Brings `placed`, the texture of a view the title placed in the memory
  132. /// of `source` in another format (`crate::resource::alias_of`), up to date
  133. /// with what the host wrote to `source`: the texels of every level and
  134. /// layer are copied as they are, through a buffer (the host copies between
  135. /// two formats of one texel width in no other way). Recorded the first time
  136. /// the list reads the view
  137. /// and again whenever the list used `source` in another way since (wrote
  138. /// it, or read it itself). Leaves `placed` in the copy destination state,
  139. /// as [`upload`] does. False if the copy cannot be made: the caller fills
  140. /// the texture from title memory, as before.
  141. pub(crate) fn alias(list: &HostList, placed: This, source: This) -> bool {
  142. const TARGET_OR_UNORDERED: u32 = 0x4 | 0x8;
  143. const COPY_DEST: u32 = 0x400;
  144. const COPY_SOURCE: u32 = 0x800;
  145. let (Some(to), Some(from)) = (
  146. crate::resource::host_resource(placed),
  147. crate::resource::host_resource(source),
  148. ) else {
  149. return false;
  150. };
  151. let Some(host) = host() else { return false };
  152. let through = {
  153. let mut map = THROUGH.lock().unwrap_or_else(|e| e.into_inner());
  154. let map = map.get_or_insert_with(HashMap::new);
  155. match map.get(&(placed as usize)) {
  156. Some(through) => through.clone(),
  157. None => {
  158. // SAFETY: live textures.
  159. let (of_from, of_to) = unsafe { (from.GetDesc(), to.GetDesc()) };
  160. // Levels times layers (a volume's slices are one part).
  161. let count = |d: &D3D12_RESOURCE_DESC| {
  162. let layers = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
  163. 1
  164. } else {
  165. u32::from(d.DepthOrArraySize)
  166. };
  167. u32::from(d.MipLevels) * layers
  168. };
  169. let parts = count(&of_from);
  170. if parts == 0 || parts > ALIAS_PARTS || parts != count(&of_to) {
  171. return false;
  172. }
  173. let mut rows = [(); 2]
  174. .map(|()| vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); parts as usize]);
  175. let mut bytes = [0u64; 2];
  176. // SAFETY: plain queries; the out pointers are ours and
  177. // hold `parts` layouts each.
  178. unsafe {
  179. host.device.GetCopyableFootprints(
  180. &of_from,
  181. 0,
  182. parts,
  183. 0,
  184. Some(rows[0].as_mut_ptr()),
  185. None,
  186. None,
  187. Some(&mut bytes[0]),
  188. );
  189. host.device.GetCopyableFootprints(
  190. &of_to,
  191. 0,
  192. parts,
  193. 0,
  194. Some(rows[1].as_mut_ptr()),
  195. None,
  196. None,
  197. Some(&mut bytes[1]),
  198. );
  199. }
  200. let alike = rows[0].iter().zip(&rows[1]).all(|(a, b)| {
  201. let (fa, fb) = (a.Footprint, b.Footprint);
  202. a.Offset == b.Offset
  203. && (fa.Width, fa.Height, fa.Depth, fa.RowPitch)
  204. == (fb.Width, fb.Height, fb.Depth, fb.RowPitch)
  205. });
  206. if bytes[0] == 0 || bytes[0] != bytes[1] || !alike {
  207. return false;
  208. }
  209. let Some(buffer) = host.uav_buffer(bytes[0]) else {
  210. return false;
  211. };
  212. crate::host::name(&buffer, || {
  213. format!(
  214. "alias copy {}x{} f{} to f{}",
  215. of_from.Width, of_from.Height, of_from.Format.0, of_to.Format.0
  216. )
  217. });
  218. tracing::info!(
  219. view = ?placed,
  220. texture = ?source,
  221. width = of_from.Width,
  222. height = of_from.Height,
  223. parts,
  224. written_as = of_from.Format.0,
  225. read_as = of_to.Format.0,
  226. "a view placed in the memory of a texture the host writes, in another format: read from that texture by a copy on the host"
  227. );
  228. let [of_written, of_read] = rows;
  229. let through = Arc::new(Through {
  230. buffer,
  231. parts: of_written.into_iter().zip(of_read).collect(),
  232. });
  233. map.insert(placed as usize, through.clone());
  234. through
  235. }
  236. }
  237. };
  238. let first = list.first_use(placed as usize);
  239. // The source's first use in the list records nothing (its prelude
  240. // brings it to the state); a use in another way since the last copy
  241. // shows as a change of state.
  242. let before = list.transition(source, COPY_SOURCE).map(|(texture, before)| {
  243. let state = crate::host::legal_state(texture, COPY_SOURCE);
  244. let barrier = crate::host::transition(
  245. texture,
  246. D3D12_RESOURCE_STATES(before as i32),
  247. D3D12_RESOURCE_STATES(state as i32),
  248. );
  249. // SAFETY: an open list and a live texture.
  250. unsafe { list.list.ResourceBarrier(&[barrier]) };
  251. before
  252. });
  253. if !first && before.is_none() {
  254. return true;
  255. }
  256. card_writes(list, placed, to, None);
  257. crate::list::ensure_state(list, placed, COPY_DEST);
  258. let part = |texture: &ID3D12Resource, index: usize| D3D12_TEXTURE_COPY_LOCATION {
  259. // SAFETY: a borrowed pointer the location never releases.
  260. pResource: unsafe { std::mem::transmute_copy(texture) },
  261. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  262. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  263. SubresourceIndex: index as u32,
  264. },
  265. };
  266. let rows = |row: &D3D12_PLACED_SUBRESOURCE_FOOTPRINT| D3D12_TEXTURE_COPY_LOCATION {
  267. // SAFETY: as above.
  268. pResource: unsafe { std::mem::transmute_copy(&through.buffer) },
  269. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  270. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  271. PlacedFootprint: *row,
  272. },
  273. };
  274. let (common, read, written) = (
  275. D3D12_RESOURCE_STATE_COMMON,
  276. D3D12_RESOURCE_STATE_COPY_SOURCE,
  277. D3D12_RESOURCE_STATE_COPY_DEST,
  278. );
  279. #[cfg(feature = "diagnostics")]
  280. list.note_op(|| format!("alias copy of {source:?} into {placed:?}"));
  281. // SAFETY: an open list and live resources; the buffer is as big as
  282. // the footprints and rests in the common state between copies.
  283. unsafe {
  284. list.list
  285. .ResourceBarrier(&[crate::host::transition(&through.buffer, common, written)]);
  286. for (index, (of_written, _)) in through.parts.iter().enumerate() {
  287. list.list
  288. .CopyTextureRegion(&rows(of_written), 0, 0, 0, &part(from, index), None);
  289. }
  290. list.list
  291. .ResourceBarrier(&[crate::host::transition(&through.buffer, written, read)]);
  292. for (index, (_, of_read)) in through.parts.iter().enumerate() {
  293. list.list
  294. .CopyTextureRegion(&part(to, index), 0, 0, 0, &rows(of_read), None);
  295. }
  296. list.list
  297. .ResourceBarrier(&[crate::host::transition(&through.buffer, read, common)]);
  298. }
  299. list.keep(&through.buffer);
  300. // A draw that also writes the source (a view of it handled before
  301. // this one) needs it in that state again; the next read of the alias
  302. // then copies once more, as it must after a write.
  303. if let Some(before) = before
  304. && before & TARGET_OR_UNORDERED != 0
  305. {
  306. crate::list::ensure_state(list, source, before);
  307. }
  308. true
  309. }
  310. /// Whether a texture refresh that finds the runtime remapping title memory
  311. /// goes on without waiting for it (`VICTORY_TEXTURE_NO_WAIT=1`; off by
  312. /// default).
  313. ///
  314. /// A texture whose memory is all mapped is read in place, under a lock
  315. /// the runtime takes alone while it changes a mapping
  316. /// (`crate::watch::title_memory_reading`), so that no page goes away under
  317. /// the read. While the world streams in the runtime remaps all the time,
  318. /// and each of the frame's 150-360 refreshes waited for it: runs 99-101
  319. /// have 4, 15 and 16 frame lines with over 300 ms of "textures", up to
  320. /// 3,708 ms, and on every one of them the wait for this lock is the whole
  321. /// of it (1,345 of 1,381 ms; 3,630 of 3,708; the write-watch askings 3-12
  322. /// ms, the texture's own lock 0).
  323. ///
  324. /// With the switch the refresh asks for the lock without waiting. If the
  325. /// runtime has it, the texture is read through the kernel instead, which
  326. /// needs no lock: it fails if a page is not there, and then the texture is
  327. /// left as it is and read at its next refresh, a frame later. A read
  328. /// through the kernel costs about 0.6 ms a megabyte against 0.3 in place.
  329. ///
  330. /// What changes for the picture: a texture that arrives while the runtime
  331. /// is remapping may show a frame later. It never shows partly read.
  332. fn no_wait() -> bool {
  333. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  334. *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_NO_WAIT").is_some_and(|v| v == "1"))
  335. }
  336. /// Since the last frame-rate line, with [`no_wait`]: refreshes that read
  337. /// through the kernel because title memory was being remapped, and those
  338. /// left for the next refresh because a page was not there.
  339. pub(crate) static UNLOCKED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  340. /// Since the last frame-rate line, of texture refreshes on every thread, in
  341. /// microseconds: waiting for the texture's own lock (another thread is
  342. /// refreshing the same texture), asking the write watch and the guards,
  343. /// waiting for title memory to hold still (the lock the runtime takes
  344. /// alone while it remaps, `crate::watch::title_memory_reading`), and the
  345. /// refreshes in all.
  346. ///
  347. /// While the world streams in, the frame line's "textures" is seconds a
  348. /// frame in some runs and tenths in others for the same megabytes (2,566
  349. /// ms for 110 MB in run 93, 314 ms for 132 MB in run 91; before these
  350. /// counters, runs 81, 83, 85 and 94 each had lines of 1.5-2.9 s), and the
  351. /// submitting thread is not running while it lasts (run 93: 240-310 ms of
  352. /// its own time a frame beside 1,100-1,800 ms of "textures"): it waits.
  353. /// These say for what.
  354. pub(crate) static REFRESH_WAITS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  355. /// `f`'s result, its time added to [`REFRESH_WAITS`]' place `slot`.
  356. fn waited<T>(slot: usize, f: impl FnOnce() -> T) -> T {
  357. let started = std::time::Instant::now();
  358. let out = f();
  359. REFRESH_WAITS[slot].fetch_add(started.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
  360. out
  361. }
  362. thread_local! {
  363. /// Room to read a texture's memory into: one buffer per submitting
  364. /// thread. Each texture kept its own, a second copy in memory of every
  365. /// write-watched or partly mapped texture ever sampled, for the run.
  366. static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
  367. }
  368. /// Calls `f` with `size` bytes of this thread's read buffer (their
  369. /// contents are whatever the last texture left).
  370. fn with_read<R>(size: usize, f: impl FnOnce(&mut [u8]) -> R) -> R {
  371. READ.with(|read| {
  372. let mut read = read.borrow_mut();
  373. if read.len() < size {
  374. read.resize(size, 0);
  375. }
  376. f(&mut read[..size])
  377. })
  378. }
  379. /// Whether a texture all of whose memory is mapped is read through the
  380. /// kernel's copy instead of in place (`VICTORY_TEXTURE_COPY=1`; off by
  381. /// default). Round 3 of the memory work read every such texture that way
  382. /// to be safe from pages taken away under the read; it cost 0.6 ms per MB
  383. /// against 0.3 in place (90-105 ms a frame while the world streams in, runs
  384. /// 72 and 73, against 20-40), and both runs with it lost the graphics
  385. /// device, for a reason not found. The read in place is safe now for
  386. /// another reason (`crate::watch::title_memory_reading`); this switch is
  387. /// left to tell whether the copy was what lost the device.
  388. fn through_copy() -> bool {
  389. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  390. *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_COPY").is_some_and(|v| v == "1"))
  391. }
  392. /// Calls `f` with the `size` bytes of title memory at `memory`, read
  393. /// through the kernel into this thread's read buffer; pages that are not
  394. /// there read as zeros. The bytes are those a read in place would see.
  395. fn with_title<R>(memory: *const u8, size: usize, f: impl FnOnce(&[u8]) -> R) -> R {
  396. with_read(size, |read| {
  397. crate::host::copy_mapped(read.as_mut_ptr(), memory, size, false);
  398. f(read)
  399. })
  400. }
  401. /// Staging buffers alive (also those only a list still holds) and their
  402. /// bytes.
  403. static STAGED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  404. impl Drop for Staging {
  405. fn drop(&mut self) {
  406. use std::sync::atomic::Ordering::Relaxed;
  407. STAGED[0].fetch_sub(1, Relaxed);
  408. STAGED[1].fetch_sub(self.bytes, Relaxed);
  409. }
  410. }
  411. /// For the memory line: staging buffers alive, their bytes, and how many
  412. /// of them their texture still has (the others wait for a list's reset).
  413. #[cfg(feature = "diagnostics")]
  414. pub(crate) fn memory() -> [u64; 3] {
  415. use std::sync::atomic::Ordering::Relaxed;
  416. let kept = STAGING
  417. .lock()
  418. .unwrap_or_else(|e| e.into_inner())
  419. .as_ref()
  420. .map_or(0, |map| map.len() as u64);
  421. [STAGED[0].load(Relaxed), STAGED[1].load(Relaxed), kept]
  422. }
  423. /// Staging buffers let go as idle since the start, and their bytes.
  424. static LET_GO: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2];
  425. /// For the memory line: staging buffers let go as idle, and their bytes.
  426. #[cfg(feature = "diagnostics")]
  427. pub(crate) fn let_go() -> [u64; 2] {
  428. use std::sync::atomic::Ordering::Relaxed;
  429. [LET_GO[0].load(Relaxed), LET_GO[1].load(Relaxed)]
  430. }
  431. /// Lets go of the staging buffers no list recorded a use of for `IDLE_MS`
  432. /// and `IDLE_FRAMES` frames and no list holds: a staging buffer is system memory the size of its
  433. /// texture, kept so that an unchanged texture is not uploaded again, and
  434. /// those of textures no longer sampled were kept for the run (2,246 of
  435. /// them, 2.1 GB, at the end of run 24). The next list that samples such a
  436. /// texture makes a staging buffer anew, detiles and uploads once more.
  437. /// Called before a submission starts, by the thread that submits.
  438. pub(crate) fn let_go_idle() {
  439. use std::sync::atomic::Ordering::Relaxed;
  440. const IDLE_FRAMES: u64 = 4;
  441. let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  442. let Some(map) = map.as_mut() else {
  443. return;
  444. };
  445. if map.is_empty() {
  446. return;
  447. }
  448. let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram());
  449. // A list that recorded an upload or a check holds the staging until it
  450. // is reset: one only the table holds is named by no list, recorded or
  451. // running.
  452. let (mut went, mut bytes) = (0u64, 0u64);
  453. map.retain(|_, s| {
  454. let keep = Arc::strong_count(s) > 1
  455. || !crate::host::long_ago(s.used.load(Relaxed), idle_ms, IDLE_FRAMES);
  456. if !keep {
  457. LET_GO[0].fetch_add(1, Relaxed);
  458. LET_GO[1].fetch_add(s.bytes, Relaxed);
  459. went += 1;
  460. bytes += s.bytes;
  461. }
  462. keep
  463. });
  464. if went > 0 {
  465. crate::host::trail(|| format!("sweep: {went} staging buffers of textures let go ({} KiB), held by no list", bytes >> 10));
  466. }
  467. }
  468. /// Textures the host GPU wrote by a copy or resolve: their contents are on
  469. /// the host, not in title memory, which stays as it was.
  470. static HOST_WRITTEN: Mutex<Option<std::collections::HashSet<usize>>> = Mutex::new(None);
  471. /// A host copy or resolve writes `resource`.
  472. pub(crate) fn host_written(resource: This) {
  473. let new = {
  474. let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
  475. set.get_or_insert_with(Default::default).insert(resource as usize)
  476. };
  477. // Diagnostics (run 177): where its title memory is, for placed views
  478. // the title reads that memory through ([`placed_in_host_written`]).
  479. if new && let Some((at, desc)) = crate::resource::texture_memory(resource) {
  480. // SAFETY: 56 bytes in the description's layout.
  481. let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() };
  482. let bytes = crate::resource::placed_bytes(&words).unwrap_or(0);
  483. if !at.is_null() && bytes > 0 {
  484. HOST_WRITTEN_AT
  485. .lock()
  486. .unwrap_or_else(|e| e.into_inner())
  487. .insert(at as u64, (bytes, words[4], words[6], words[7], words[8], resource as usize));
  488. }
  489. }
  490. }
  491. /// The title memory of textures the host copied into, by address: bytes
  492. /// and description words 4, 6, 7 and 8 (width, height, layers and levels,
  493. /// format).
  494. static HOST_WRITTEN_AT: Mutex<std::collections::BTreeMap<u64, (u64, u32, u32, u32, u32, usize)>> =
  495. Mutex::new(std::collections::BTreeMap::new());
  496. /// A texture the title placed at `address` (description words `desc`) was
  497. /// made: says so once if it lies in the memory of a texture the host
  498. /// copied into ([`host_written`]). Its own host copy is filled from title
  499. /// memory, which the copy never reached: the copied texels are on the
  500. /// card in the other texture, where no shader that reads this view finds
  501. /// them.
  502. pub(crate) fn placed_in_host_written(address: u64, desc: &[u32; 14]) {
  503. let hit = {
  504. let map = HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner());
  505. map.range(..=address)
  506. .next_back()
  507. .filter(|(at, d)| address < **at + d.0)
  508. .map(|(at, d)| (*at, *d))
  509. };
  510. if let Some((at, (bytes, width, height, layers_levels, format, _))) = hit {
  511. static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  512. if SAID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 200 {
  513. tracing::warn!(
  514. view_address = format_args!("{address:#x}"),
  515. view_offset = address - at,
  516. view_width = desc[4],
  517. view_height = desc[6],
  518. view_layers_levels = format_args!("{:#x}", desc[7]),
  519. view_format = desc[8],
  520. copied_address = format_args!("{at:#x}"),
  521. copied_bytes = bytes,
  522. copied_width = width,
  523. copied_height = height,
  524. copied_layers_levels = format_args!("{layers_levels:#x}"),
  525. copied_format = format,
  526. "HERO LEAD: a placed texture view lies in the memory of a texture the host copied into: it is filled from title memory, which the copy never reached"
  527. );
  528. }
  529. }
  530. }
  531. /// Whether the host GPU wrote `resource` by a copy or resolve
  532. /// ([`host_written`]): its host copy cannot be made again from title
  533. /// memory.
  534. pub(crate) fn host_wrote(resource: usize) -> bool {
  535. HOST_WRITTEN
  536. .lock()
  537. .unwrap_or_else(|e| e.into_inner())
  538. .as_ref()
  539. .is_some_and(|set| set.contains(&resource))
  540. }
  541. /// The title released a resource.
  542. pub(crate) fn forget(resource: usize) {
  543. let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  544. if let Some(map) = map.as_mut() {
  545. map.remove(&resource);
  546. }
  547. let mut set = HOST_WRITTEN.lock().unwrap_or_else(|e| e.into_inner());
  548. if let Some(set) = set.as_mut() {
  549. set.remove(&resource);
  550. }
  551. // Its memory may be given to other textures now (run 177: most of the
  552. // "HERO LEAD" lines were views in memory a released texture had held).
  553. HOST_WRITTEN_AT.lock().unwrap_or_else(|e| e.into_inner()).retain(|_, d| d.5 != resource);
  554. let mut through = THROUGH.lock().unwrap_or_else(|e| e.into_inner());
  555. if let Some(through) = through.as_mut() {
  556. through.remove(&resource);
  557. }
  558. }
  559. /// Whether `resource`'s host copy takes its contents from title memory:
  560. /// a texture the host GPU does not render to or write.
  561. pub(crate) fn title_written(texture: &ID3D12Resource) -> bool {
  562. const TARGET_DEPTH_UNORDERED: i32 = 0x7;
  563. // SAFETY: a live resource.
  564. unsafe { texture.GetDesc() }.Flags.0 & TARGET_DEPTH_UNORDERED == 0
  565. }
  566. /// Records, once per list, the copy of `resource`'s staging buffer into
  567. /// its host copy, and the detiling that refreshes the staging buffer at
  568. /// submission if the memory changed. Leaves the texture in the copy
  569. /// destination state.
  570. pub(crate) fn upload(list: &HostList, resource: This, texture: &ID3D12Resource) {
  571. let host_written = HOST_WRITTEN
  572. .lock()
  573. .unwrap_or_else(|e| e.into_inner())
  574. .as_ref()
  575. .is_some_and(|set| set.contains(&(resource as usize)));
  576. // shortcut: a texture the host copied into keeps the host's contents
  577. // even if the title later writes its memory too.
  578. if host_written || !list.first_use(resource as usize) {
  579. return;
  580. }
  581. let Some(staging) = staging(resource, texture) else {
  582. return;
  583. };
  584. use std::sync::atomic::Ordering::Relaxed;
  585. staging.used.store(crate::host::moment(), Relaxed);
  586. // Levels on demand: a view of the texture now starts at another
  587. // level, or another texture now starts inside its span, with no byte
  588. // of its memory changed. The levels are judged anew: detiled again at
  589. // this list's submission, and uploaded by this list.
  590. if staging.on_demand && staging.judgement() != staging.judged() {
  591. staging.forget();
  592. staging.dirty.store(true, Relaxed);
  593. }
  594. // Levels on demand: the last upload left a held level without tiles
  595. // (the card had no room, or no heap could be had), and nothing else
  596. // would record an upload again until the title writes the texture: the
  597. // level stayed empty, the texture blurred or black. Asked again about
  598. // once a second, and only when the card has room; the staging buffer
  599. // still holds the level's bytes.
  600. if staging.on_demand {
  601. let since = staging.waiting.load(Relaxed);
  602. if since != 0 && crate::host::long_ago(since, 1000, 2) {
  603. if crate::resource::room_lately() {
  604. staging.waiting.store(0, Relaxed);
  605. staging.dirty.store(true, Relaxed);
  606. crate::tiles::STATS[10].fetch_add(1, Relaxed);
  607. } else {
  608. staging.waiting.store(crate::host::moment().max(1), Relaxed);
  609. }
  610. }
  611. }
  612. // The host texture has the staging buffer's contents: only the check
  613. // at submission is left, and what it finds changed the next list that
  614. // samples the texture uploads (a frame late where every list of the
  615. // frame was recorded before that check).
  616. if staging.uploaded.load(Relaxed) && !staging.dirty.load(Relaxed) {
  617. #[cfg(feature = "diagnostics")]
  618. crate::copystat::add(crate::copystat::C::TexSkipped, 1);
  619. list.defer_texture(staging);
  620. return;
  621. }
  622. #[cfg(feature = "diagnostics")]
  623. crate::copystat::add(crate::copystat::C::TexUploads, 1);
  624. const COPY_DEST: u32 = 0x400;
  625. // A texture cut from a block may lie where another did: what the card
  626. // holds of that one is done with before the first upload into this one.
  627. if crate::pool::on() && !staging.uploaded.load(Relaxed) {
  628. let aliasing = D3D12_RESOURCE_BARRIER {
  629. Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
  630. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  631. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  632. Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
  633. pResourceBefore: std::mem::ManuallyDrop::new(None),
  634. // SAFETY: a borrowed pointer the barrier never releases.
  635. pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
  636. }),
  637. },
  638. };
  639. // SAFETY: an open list and a live texture.
  640. unsafe { list.list.ResourceBarrier(&[aliasing]) };
  641. }
  642. crate::list::ensure_state(list, resource, COPY_DEST);
  643. // The staging buffer lives as long as `staging`, which the deferred
  644. // refresh below holds until the list is reset.
  645. for (i, footprint) in staging.footprints.iter().enumerate() {
  646. #[cfg(feature = "diagnostics")]
  647. {
  648. let f = footprint.Footprint;
  649. // SAFETY: live resources.
  650. let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) };
  651. let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
  652. list.note_read(
  653. || {
  654. format!(
  655. "texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
  656. d.Width,
  657. d.Height,
  658. d.DepthOrArraySize,
  659. d.Format.0,
  660. d.MipLevels,
  661. staging.footprints.len(),
  662. staging.size,
  663. staging.base + footprint.Offset,
  664. f.Width,
  665. f.Height,
  666. f.Depth,
  667. f.RowPitch
  668. )
  669. },
  670. (gpu + staging.base + footprint.Offset, len),
  671. );
  672. }
  673. let to = D3D12_TEXTURE_COPY_LOCATION {
  674. // SAFETY: a borrowed pointer the location never releases.
  675. pResource: unsafe { std::mem::transmute_copy(texture) },
  676. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  677. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  678. SubresourceIndex: i as u32,
  679. },
  680. };
  681. let from = D3D12_TEXTURE_COPY_LOCATION {
  682. // SAFETY: as above.
  683. pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
  684. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  685. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
  686. PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
  687. Offset: staging.base + footprint.Offset,
  688. ..*footprint
  689. },
  690. },
  691. };
  692. // SAFETY: an open list; both locations name live resources.
  693. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  694. }
  695. // When the list is submitted, its copy takes what the staging buffer
  696. // holds by then: noted before the check below, which sets `dirty`
  697. // again if it detiles (the next list then uploads once more).
  698. {
  699. let staging = staging.clone();
  700. list.defer_host(move || {
  701. staging.uploaded.store(true, Relaxed);
  702. staging.dirty.store(false, Relaxed);
  703. });
  704. }
  705. // Levels on demand (`crate::tiles`): after the check below, in the
  706. // order of this list's steps, and before the list is executed, the
  707. // levels the staging buffer holds as the title's are given the card's
  708. // memory if they have none. The list copies every level, so each one
  709. // given here is written whole by it (the rest are copies into no
  710. // memory, which the card drops).
  711. let on_demand = if staging.on_demand { crate::resource::host_tiled(resource) } else { None };
  712. let Some(on_demand) = on_demand else {
  713. // Once per submission however many of its lists sample the texture.
  714. list.defer_texture(staging);
  715. return;
  716. };
  717. list.defer_texture(staging.clone());
  718. list.defer_host(move || {
  719. let waiting = on_demand.uploaded(staging.detiled.load(Relaxed), staging.memory as u64);
  720. staging.waiting.store(if waiting { crate::host::moment().max(1) } else { 0 }, Relaxed);
  721. // A texture picked by index has no staging buffer after this
  722. // upload: its slots are made due again by the texture pass.
  723. if waiting {
  724. crate::descriptor::host::levels_waiting(staging.memory as u64);
  725. }
  726. });
  727. }
  728. /// Levels on demand: the levels a list claimed for its zeros
  729. /// (`crate::tiles::Tiled::claim`), held by the list's submission-time
  730. /// step. A list that is reset without having been submitted gives the
  731. /// claim up, or the next list that writes those levels would send no zeros
  732. /// and what its write does not cover would be what the tiles' last owner
  733. /// left.
  734. struct Claimed {
  735. on_demand: crate::resource::OnDemand,
  736. fresh: u32,
  737. ran: std::sync::atomic::AtomicBool,
  738. }
  739. impl Drop for Claimed {
  740. fn drop(&mut self) {
  741. if self.fresh != 0
  742. && !*self.ran.get_mut()
  743. && let Some(tiled) = self.on_demand.tiled()
  744. {
  745. tiled.unclaim(self.fresh);
  746. }
  747. }
  748. }
  749. /// Levels on demand (`crate::tiles`): the card itself is about to write
  750. /// title texture `resource` in `list` (a copy or a resolve into level
  751. /// `level`, or into every level). If its host copy `texture` was made
  752. /// without memory, the levels written get theirs when the list is
  753. /// submitted, ahead of it on the queue; the ones that have none yet are
  754. /// first written with zeros, here in the same list, so that what the
  755. /// card's write does not cover is not what the tiles' last owner left.
  756. /// To be called before the list is brought to the state of that write.
  757. /// shortcut: two lists that write the same new level, submitted in the
  758. /// other order than recorded, lose the first one's write under the zeros
  759. /// of the other; so does an upload recorded and not yet submitted.
  760. pub(crate) fn card_writes(list: &HostList, resource: This, texture: &ID3D12Resource, level: Option<u32>) {
  761. let Some(on_demand) = crate::resource::host_tiled(resource) else {
  762. return;
  763. };
  764. let Some(tiled) = on_demand.tiled() else {
  765. return;
  766. };
  767. let levels = match level {
  768. Some(level) => tiled.with_level(level),
  769. None => tiled.every_level(),
  770. };
  771. if levels == 0 {
  772. return;
  773. }
  774. let fresh = tiled.claim(levels);
  775. // Of them, the ones whose zeros could not be recorded.
  776. let mut unzeroed = if host().is_none() { fresh } else { 0 };
  777. if fresh != 0
  778. && let Some(host) = host()
  779. {
  780. const COPY_DEST: u32 = 0x400;
  781. crate::list::ensure_state(list, resource, COPY_DEST);
  782. // SAFETY: a live resource.
  783. let d = unsafe { texture.GetDesc() };
  784. for level in (0..u32::from(d.MipLevels).min(32)).filter(|&level| fresh & (1u32 << level) != 0) {
  785. let mut footprint = D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default();
  786. let mut bytes = 0u64;
  787. // SAFETY: outputs for one subresource.
  788. unsafe {
  789. host.device
  790. .GetCopyableFootprints(&d, level, 1, 0, Some(&mut footprint), None, None, Some(&mut bytes));
  791. }
  792. let Some((buffer, data)) = list.upload(host, bytes) else {
  793. // (With the levels that share its tiles, if it is one of
  794. // the small ones.)
  795. unzeroed |= tiled.with_level(level);
  796. continue;
  797. };
  798. // SAFETY: a mapped buffer of `bytes` bytes, just made.
  799. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
  800. let to = D3D12_TEXTURE_COPY_LOCATION {
  801. // SAFETY: a borrowed pointer the location never releases.
  802. pResource: unsafe { std::mem::transmute_copy(texture) },
  803. Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
  804. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: level },
  805. };
  806. let from = D3D12_TEXTURE_COPY_LOCATION {
  807. // SAFETY: as above; the list holds the buffer until it is reset.
  808. pResource: unsafe { std::mem::transmute_copy(&buffer) },
  809. Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
  810. Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint },
  811. };
  812. // SAFETY: an open list; both locations name live resources.
  813. unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
  814. }
  815. }
  816. // A new level without its zeros gets no tiles from this list: the
  817. // card's write into it is lost (the level reads zeros, as before the
  818. // write), which is less wrong than a part write over what the tiles'
  819. // last owner left. The next list that writes it claims it again.
  820. unzeroed &= fresh;
  821. if unzeroed != 0 {
  822. tiled.unclaim(unzeroed);
  823. }
  824. let levels = levels & !unzeroed;
  825. if levels == 0 {
  826. return;
  827. }
  828. let memory = crate::resource::texture_memory(resource).map_or(0, |(memory, _)| memory as u64);
  829. let step = Claimed {
  830. on_demand,
  831. fresh: fresh & !unzeroed,
  832. ran: std::sync::atomic::AtomicBool::new(false),
  833. };
  834. list.defer_host(move || {
  835. step.ran.store(true, std::sync::atomic::Ordering::Relaxed);
  836. step.on_demand.card_wrote(levels, memory);
  837. });
  838. }
  839. impl Staging {
  840. /// Levels on demand: what says, beside the mapping, which levels of
  841. /// the texture are the title's now. First the lowest level a live view
  842. /// of the texture shows (0 without a view that says): the title's own
  843. /// word, a texture it holds from level 3 on is viewed from level 3.
  844. /// Then where the next texture placed in this one's span starts, in
  845. /// bytes from this one's start (`u64::MAX`: none does): for a texture
  846. /// viewed from level 0 although a neighbour sits where its large
  847. /// levels would be.
  848. fn judgement(&self) -> [u64; 2] {
  849. let start = self.memory as u64;
  850. let first = crate::descriptor::host::first_viewed(start).map_or(0, u64::from);
  851. let limit = crate::descriptor::host::next_start(start, start.saturating_add(self.layout.size))
  852. .map_or(u64::MAX, |at| at - start);
  853. [first, limit]
  854. }
  855. /// What [`Staging::judgement`] said at the last detiling.
  856. fn judged(&self) -> [u64; 2] {
  857. use std::sync::atomic::Ordering::Relaxed;
  858. [self.judged[0].load(Relaxed), self.judged[1].load(Relaxed)]
  859. }
  860. /// Levels on demand: the levels that are the title's now, a bit a
  861. /// level. A level is held if no view starts above it, its bytes end
  862. /// before the next texture starts, and all of them are mapped. The
  863. /// smallest levels share the texture's first block and are held
  864. /// together. (The console layout: that block first, then the other
  865. /// levels from the smallest up, level 0 last:
  866. /// `victory_formats::texture::Layout`.) A texture this cannot tell
  867. /// the levels of holds them all.
  868. fn held_levels(&self, [first, limit]: [u64; 2]) -> u32 {
  869. let mips = &self.layout.mips;
  870. if self.layout.slices != 1 || mips.is_empty() || mips.len() > 32 {
  871. return u32::MAX;
  872. }
  873. let tail = (self.layout.first_tail_mip as usize).min(mips.len());
  874. let there = |from: u64, to: u64| {
  875. to > from && to <= limit && committed(self.memory.wrapping_add(from as usize), (to - from) as usize)
  876. };
  877. let mut held = 0u32;
  878. for (level, m) in mips.iter().enumerate().take(tail) {
  879. let end = if level == 0 { self.layout.slice_size } else { mips[level - 1].offset };
  880. if level as u64 >= first && there(m.offset, end) {
  881. held |= 1 << level;
  882. }
  883. }
  884. if tail < mips.len() && there(0, self.layout.alignment.min(self.layout.slice_size)) {
  885. for level in tail..mips.len() {
  886. if level as u64 >= first {
  887. held |= 1 << level;
  888. }
  889. }
  890. }
  891. held
  892. }
  893. /// Forgets what the staging buffer was last filled from: the next
  894. /// refresh detiles anew, whether the memory changed or not.
  895. fn forget(&self) {
  896. *self.last.lock().unwrap_or_else(|e| e.into_inner()) = Last::default();
  897. }
  898. /// The title memory the texture is read from: address and bytes.
  899. pub(crate) fn memory(&self) -> (usize, usize) {
  900. (self.memory as usize, self.layout.size as usize)
  901. }
  902. /// Detiles the texture memory into the staging buffer if it changed
  903. /// since the last time (and is mapped at all).
  904. pub(crate) fn refresh(&self) {
  905. use std::sync::atomic::Ordering::Relaxed;
  906. let started = std::time::Instant::now();
  907. let read = self.refresh_now();
  908. let preparing = &crate::host::PREPARING;
  909. preparing[2].fetch_add(started.elapsed().as_micros() as u64, Relaxed);
  910. preparing[3].fetch_add(read as u64, Relaxed);
  911. }
  912. /// Returns the bytes of title memory read.
  913. fn refresh_now(&self) -> usize {
  914. let whole = std::time::Instant::now();
  915. let read = self.refresh_timed();
  916. REFRESH_WAITS[3].fetch_add(whole.elapsed().as_micros() as u64, std::sync::atomic::Ordering::Relaxed);
  917. read
  918. }
  919. fn refresh_timed(&self) -> usize {
  920. let size = self.layout.size as usize;
  921. let start = self.memory as usize;
  922. let mut last = waited(0, || self.last.lock().unwrap_or_else(|e| e.into_inner()));
  923. let last = &mut *last;
  924. if let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, false)) {
  925. if last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked) {
  926. return 0;
  927. }
  928. last.asked = now;
  929. // Read through the copy, which stands unmapped pages: memory of
  930. // big pools is too slow to ask page by page.
  931. with_read(size, |read| {
  932. crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
  933. self.detile(read);
  934. });
  935. #[cfg(feature = "diagnostics")]
  936. crate::copystat::add(crate::copystat::C::TexWatched, size as u64);
  937. return size;
  938. }
  939. // View memory has no write-watch, and a texture there was hashed
  940. // whole at every check: 229 MB and 51 ms a frame in a gameplay view
  941. // where two textures change (run 58). It is guarded now, as buffers
  942. // in view memory are: a write of the title's to it faults once and
  943. // is noted, a mapping is announced by the runtime. While neither
  944. // happened the texture is as it was. What the guard cannot see (a
  945. // write to the same pages through another view) is still found by
  946. // the hash, which is taken every eighth frame only, by the
  947. // texture's address, so the textures take turns.
  948. // `VICTORY_TEXTURE_GUARD=0` hashes at every check, as before.
  949. static GUARD: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  950. // The guard saw no write: a change the hash finds came another way.
  951. let mut blind = false;
  952. if *GUARD.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_GUARD").is_none_or(|v| v != "0"))
  953. && let Some((now, written)) = waited(1, || crate::watch::writes(start, start + size, true))
  954. {
  955. const HASH_EVERY: u64 = 8;
  956. let unwritten = last.asked != 0 && written.iter().all(|&(_, w)| w <= last.asked);
  957. last.asked = now;
  958. let frame = crate::frame::current();
  959. let turn = frame
  960. .wrapping_add((start >> 16) as u64)
  961. .is_multiple_of(HASH_EVERY);
  962. // A texture starts hot: one written that way from its first
  963. // frames on changes before the hash has ever caught it.
  964. if last.hot_until == 0 {
  965. last.hot_until = frame + HOT_FRAMES;
  966. }
  967. let hot = hot_textures() && frame < last.hot_until;
  968. if unwritten && !turn && !hot {
  969. return 0;
  970. }
  971. blind = unwritten;
  972. }
  973. // A change the guard did not see: hashed at every check for a while.
  974. let found_blind = |last: &mut Last| {
  975. if blind && hot_textures() {
  976. last.hot_until = crate::frame::current() + HOT_FRAMES;
  977. #[cfg(feature = "diagnostics")]
  978. crate::copystat::add(crate::copystat::C::TexHot, 1);
  979. }
  980. };
  981. // From here on the texture's memory may be read in place. Held until
  982. // that read is done: the runtime changes what title memory shows
  983. // only with this taken alone, so what `committed` finds mapped
  984. // stays mapped (see `crate::watch::title_memory_reading`; without
  985. // it a page went between the asking and the read in runs 71 and
  986. // 74).
  987. let _mapped = if no_wait() {
  988. // Not waited for: while the runtime remaps title memory the
  989. // texture is read through the kernel instead, whole or not at
  990. // all (`no_wait`).
  991. let Some(mapped) = crate::watch::title_memory_reading_now() else {
  992. return self.refresh_unlocked(last, size);
  993. };
  994. mapped
  995. } else {
  996. waited(2, crate::watch::title_memory_reading)
  997. };
  998. if !committed(self.memory, size) {
  999. // Partly mapped: a streamed texture with only some mips' pages
  1000. // there, the usual state while it streams in. Read through the
  1001. // copy, which stands unmapped pages (zeros), and upload what
  1002. // is there; nothing at all mapped changes nothing.
  1003. // shortcut: read again at most every 30 frames (reading around
  1004. // unmapped pages is slow, and nothing tells us when pages
  1005. // arrive): a mip that streams in shows up to 30 frames late.
  1006. let frame = crate::frame::current();
  1007. if last.partial.is_some_and(|at| frame < at + 30) {
  1008. return 0;
  1009. }
  1010. last.partial = Some(frame);
  1011. #[cfg(feature = "diagnostics")]
  1012. crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
  1013. let changed = with_read(size, |read| {
  1014. crate::host::copy_mapped(read.as_mut_ptr(), self.memory, size, false);
  1015. let hash = blake3::hash(read);
  1016. if last.hash == Some(hash) {
  1017. return false;
  1018. }
  1019. last.hash = Some(hash);
  1020. if read.iter().all(|&b| b == 0) {
  1021. return false;
  1022. }
  1023. self.detile(read);
  1024. true
  1025. });
  1026. #[cfg(feature = "diagnostics")]
  1027. if changed {
  1028. crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
  1029. }
  1030. if changed {
  1031. found_blind(last);
  1032. }
  1033. return size;
  1034. }
  1035. if through_copy() {
  1036. return with_title(self.memory, size, |tiled| {
  1037. let hash = blake3::hash(tiled);
  1038. #[cfg(feature = "diagnostics")]
  1039. crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
  1040. if last.hash == Some(hash) {
  1041. return size;
  1042. }
  1043. last.hash = Some(hash);
  1044. found_blind(last);
  1045. self.detile(tiled);
  1046. #[cfg(feature = "diagnostics")]
  1047. crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
  1048. size
  1049. });
  1050. }
  1051. // SAFETY: committed memory of the texture's layout size, and it
  1052. // stays committed while `_mapped` is held.
  1053. let tiled = unsafe { std::slice::from_raw_parts(self.memory, size) };
  1054. let hash = blake3::hash(tiled);
  1055. #[cfg(feature = "diagnostics")]
  1056. crate::copystat::add(crate::copystat::C::TexHashed, size as u64);
  1057. if last.hash == Some(hash) {
  1058. return size;
  1059. }
  1060. last.hash = Some(hash);
  1061. found_blind(last);
  1062. self.detile(tiled);
  1063. #[cfg(feature = "diagnostics")]
  1064. crate::copystat::add(crate::copystat::C::TexChanged, size as u64);
  1065. size
  1066. }
  1067. /// A refresh while the runtime is remapping title memory ([`no_wait`]):
  1068. /// the texture is read through the kernel, which fails if a page of it
  1069. /// is not there at this moment. Then nothing is taken and the texture
  1070. /// is looked at again at its next refresh (what was learnt about writes
  1071. /// to it is forgotten, so that it is not passed over as unwritten).
  1072. /// Returns the bytes read.
  1073. fn refresh_unlocked(&self, last: &mut Last, size: usize) -> usize {
  1074. use std::sync::atomic::Ordering::Relaxed;
  1075. let read = with_read(size, |read| {
  1076. if !crate::host::read_into(self.memory, read) {
  1077. return false;
  1078. }
  1079. let hash = blake3::hash(read);
  1080. if last.hash != Some(hash) {
  1081. last.hash = Some(hash);
  1082. self.detile(read);
  1083. }
  1084. true
  1085. });
  1086. if read {
  1087. UNLOCKED[0].fetch_add(1, Relaxed);
  1088. size
  1089. } else {
  1090. UNLOCKED[1].fetch_add(1, Relaxed);
  1091. last.asked = 0;
  1092. 0
  1093. }
  1094. }
  1095. /// Detiles `tiled` (the texture's memory) into the staging buffer.
  1096. fn detile(&self, tiled: &[u8]) {
  1097. self.dirty.store(true, std::sync::atomic::Ordering::Relaxed);
  1098. // Levels on demand: which levels are the title's is judged here,
  1099. // once, for what the staging buffer holds from now on. The step
  1100. // that gives levels their memory goes by this answer.
  1101. let held = if self.on_demand {
  1102. use std::sync::atomic::Ordering::Relaxed;
  1103. let judged = self.judgement();
  1104. self.judged[0].store(judged[0], Relaxed);
  1105. self.judged[1].store(judged[1], Relaxed);
  1106. let held = self.held_levels(judged);
  1107. self.detiled.store(held, Relaxed);
  1108. held
  1109. } else {
  1110. u32::MAX
  1111. };
  1112. #[cfg(feature = "diagnostics")]
  1113. if tiled.iter().all(|&b| b == 0) {
  1114. tracing::debug!(
  1115. memory = ?self.memory,
  1116. desc = ?self.layout.desc,
  1117. "a sampled texture's memory is all zero (not streamed yet, or a failed BCPack read)"
  1118. );
  1119. }
  1120. for (i, (footprint, &rows)) in self.footprints.iter().zip(&self.rows).enumerate() {
  1121. let (mip, slice) = (i as u32 % self.mips, i as u32 / self.mips);
  1122. let f = footprint.Footprint;
  1123. let pitch = f.RowPitch as usize;
  1124. let len = pitch * rows as usize * f.Depth as usize;
  1125. // SAFETY: the subresource's part of the mapped staging buffer.
  1126. let linear = unsafe {
  1127. std::slice::from_raw_parts_mut(self.data.add(footprint.Offset as usize), len)
  1128. };
  1129. if mip < 32 && held & (1 << mip) == 0 {
  1130. // Not the title's: zeros, not what lies in that memory.
  1131. linear.fill(0);
  1132. continue;
  1133. }
  1134. if let Err(e) =
  1135. self.layout
  1136. .detile(tiled, mip, slice, linear, pitch, pitch * rows as usize)
  1137. {
  1138. tracing::warn!(?e, mip, slice, "texture not detiled");
  1139. return;
  1140. }
  1141. }
  1142. }
  1143. }
  1144. /// Lets go of a title texture's staging buffer (lists that recorded an
  1145. /// upload from it hold it until they have run); the next upload makes one
  1146. /// anew.
  1147. pub(crate) fn unstage(resource: This) {
  1148. let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  1149. if let Some(map) = map.as_mut() {
  1150. map.remove(&(resource as usize));
  1151. }
  1152. }
  1153. /// Where a staged title texture's memory is: address and bytes.
  1154. pub(crate) fn staged_memory(resource: This) -> Option<(u64, u64)> {
  1155. let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  1156. let (at, len) = map.as_ref()?.get(&(resource as usize))?.memory();
  1157. Some((at as u64, len as u64))
  1158. }
  1159. /// A fingerprint of the title memory `[at, at + len)`, never 0: of all of
  1160. /// it up to 48 KiB, else of 16 KiB at its start, its middle and its end
  1161. /// (a texture streams in whole mips; the small ones lie first). Read
  1162. /// through the kernel, so pages not there count as zeros.
  1163. pub(crate) fn fingerprint(at: u64, len: u64) -> u64 {
  1164. const WINDOW: usize = 16 << 10;
  1165. thread_local! {
  1166. static READ: std::cell::RefCell<Vec<u8>> = const { std::cell::RefCell::new(Vec::new()) };
  1167. }
  1168. let len = len as usize;
  1169. let mut hasher = blake3::Hasher::new();
  1170. READ.with(|read| {
  1171. let mut read = read.borrow_mut();
  1172. read.resize(3 * WINDOW, 0);
  1173. let mut take = |from: usize, bytes: usize| {
  1174. read[..bytes].fill(0);
  1175. crate::host::copy_mapped(read.as_mut_ptr(), (at as usize + from) as *const u8, bytes, false);
  1176. hasher.update(&read[..bytes]);
  1177. };
  1178. if len <= 3 * WINDOW {
  1179. take(0, len);
  1180. } else {
  1181. take(0, WINDOW);
  1182. take((len / 2) & !0xfff, WINDOW);
  1183. take(len - WINDOW, WINDOW);
  1184. }
  1185. });
  1186. let hash = hasher.finalize();
  1187. let mut first = [0u8; 8];
  1188. first.copy_from_slice(&hash.as_bytes()[..8]);
  1189. u64::from_le_bytes(first) | 1
  1190. }
  1191. /// Whether a title texture has a staging buffer: a list recorded its
  1192. /// upload, and the lists that sample it check it at submission.
  1193. /// For the frame listing: whether a list has uploaded `resource`'s staging
  1194. /// buffer, and whether it was detiled since. None: it has none.
  1195. #[cfg(feature = "diagnostics")]
  1196. pub(crate) fn staged_state(resource: This) -> Option<(bool, bool)> {
  1197. use std::sync::atomic::Ordering::Relaxed;
  1198. let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  1199. let staging = map.as_ref()?.get(&(resource as usize))?;
  1200. Some((staging.uploaded.load(Relaxed), staging.dirty.load(Relaxed)))
  1201. }
  1202. pub(crate) fn is_staged(resource: This) -> bool {
  1203. let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  1204. map.as_ref().is_some_and(|map| map.contains_key(&(resource as usize)))
  1205. }
  1206. /// The bytes of a title texture's memory, and whether all of it is mapped,
  1207. /// if the texture has been staged for upload.
  1208. pub(crate) fn staged(resource: This) -> Option<(u64, bool)> {
  1209. let s = {
  1210. let map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  1211. map.as_ref()?.get(&(resource as usize))?.clone()
  1212. };
  1213. let size = s.layout.size as usize;
  1214. Some((size as u64, committed(s.memory, size)))
  1215. }
  1216. /// Whether `[at, at + len)` is committed memory (streamed textures may be
  1217. /// unmapped until their pages arrive).
  1218. pub(crate) fn committed(at: *const u8, len: usize) -> bool {
  1219. if by_query() {
  1220. return committed_by_query(at, len);
  1221. }
  1222. if len == 0 {
  1223. return true;
  1224. }
  1225. let (there, of) = readable(at as usize, len, true);
  1226. there == of
  1227. }
  1228. /// Whether the two questions above and below are put to `VirtualQuery`, as
  1229. /// they were (`VICTORY_COMMITTED_QUERY=1`). `VirtualQuery` answers with the
  1230. /// length of the run of pages in the same state, which it finds by walking
  1231. /// the page tables to the run's end: 8.8 ms for one question in the title's
  1232. /// 1.1 GB block (round 6). The pass over the heap's views asks three or
  1233. /// more of them for every texture slot that is due, 3,000 slots a frame
  1234. /// when the card has no room (run 75): that pass then ran 208-264 ms, and
  1235. /// while it ran the submitting thread's write-watch askings waited behind
  1236. /// the walks (run 76: 8-22 askings a frame of 6-21 ms each, 46-172 ms).
  1237. fn by_query() -> bool {
  1238. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1239. *ON.get_or_init(|| std::env::var_os("VICTORY_COMMITTED_QUERY").is_some_and(|v| v == "1"))
  1240. }
  1241. /// Of the kernel's pages that hold `[at, at + len)` (`len > 0`): how many
  1242. /// can be read, and how many there are; with `all`, it stops at the first
  1243. /// that cannot. One question to the kernel for up to 256 pages at once
  1244. /// (`QueryWorkingSetEx`: the state of each page asked about, no walk); a
  1245. /// page not in the working set may still be there (never touched, or
  1246. /// trimmed), and a one-byte read through the kernel says.
  1247. /// A page that is committed and may not be read counts as not there, which
  1248. /// is what the callers ask for: they read or write the memory next.
  1249. fn readable(at: usize, len: usize, all: bool) -> (usize, usize) {
  1250. use windows_sys::Win32::System::ProcessStatus::{K32QueryWorkingSetEx, PSAPI_WORKING_SET_EX_INFORMATION};
  1251. use windows_sys::Win32::System::Threading::GetCurrentProcess;
  1252. const KERNEL_PAGE: usize = 4096;
  1253. let (first, last) = (at / KERNEL_PAGE, at.saturating_add(len - 1) / KERNEL_PAGE);
  1254. let of = last - first + 1;
  1255. let mut there = 0;
  1256. // SAFETY: plain data.
  1257. let mut info: [PSAPI_WORKING_SET_EX_INFORMATION; 256] = unsafe { std::mem::zeroed() };
  1258. let mut page = first;
  1259. while page <= last {
  1260. let n = (last - page + 1).min(info.len());
  1261. for (i, entry) in info[..n].iter_mut().enumerate() {
  1262. entry.VirtualAddress = ((page + i) * KERNEL_PAGE) as *mut _;
  1263. }
  1264. // SAFETY: `n` entries of the size given; our own process.
  1265. let asked = unsafe {
  1266. K32QueryWorkingSetEx(
  1267. GetCurrentProcess(),
  1268. info.as_mut_ptr().cast(),
  1269. (n * size_of::<PSAPI_WORKING_SET_EX_INFORMATION>()) as u32,
  1270. )
  1271. } != 0;
  1272. for (i, entry) in info[..n].iter().enumerate() {
  1273. // Bit 0 of the answer: the page is in the working set.
  1274. // SAFETY: plain data the query filled in.
  1275. let valid = asked && unsafe { entry.VirtualAttributes.Flags } & 1 != 0;
  1276. let mut byte = [0u8];
  1277. if valid || crate::host::read_into(((page + i) * KERNEL_PAGE) as *const u8, &mut byte) {
  1278. there += 1;
  1279. } else if all {
  1280. return (there, of);
  1281. }
  1282. }
  1283. page += n;
  1284. }
  1285. (there, of)
  1286. }
  1287. fn committed_by_query(at: *const u8, len: usize) -> bool {
  1288. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
  1289. let mut p = at as usize;
  1290. let end = p + len;
  1291. while p < end {
  1292. // SAFETY: plain data filled in by the query.
  1293. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1294. // SAFETY: a valid out pointer of the right size.
  1295. let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
  1296. if n == 0 || info.State != MEM_COMMIT {
  1297. return false;
  1298. }
  1299. p = info.BaseAddress as usize + info.RegionSize;
  1300. }
  1301. true
  1302. }
  1303. /// How many bytes of `[at, at + len)` are committed memory: all of a
  1304. /// texture that is there, some of one streaming in (its smaller mips lie
  1305. /// at the start of its memory, and their pages are mapped first), none of
  1306. /// one not there. With neither the first nor the last page committed the
  1307. /// answer is none without a look at the pages between (two queries for the
  1308. /// slots whose texture is away, which are asked again and again).
  1309. pub(crate) fn mapped_bytes(at: *const u8, len: usize) -> u64 {
  1310. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, VirtualQuery};
  1311. if len == 0 {
  1312. return 0;
  1313. }
  1314. let start = at as usize;
  1315. let end = start.saturating_add(len);
  1316. // Streamed textures lie in views of physical pages, of which the runtime
  1317. // knows which are there: one look, where the host was asked for every
  1318. // 64 KiB of the texture (and once more for each that is not there).
  1319. // `VICTORY_MAPPED_BY_VIEWS=0`: the host is asked, as before.
  1320. static BY_VIEWS: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1321. if *BY_VIEWS.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_VIEWS").is_none_or(|v| v != "0"))
  1322. && let Some(there) = crate::inplace::shown_bytes(start, len)
  1323. {
  1324. return there;
  1325. }
  1326. if !committed(at, 1) && !committed((end - 1) as *const u8, 1) {
  1327. return 0;
  1328. }
  1329. if !by_query() {
  1330. static BY_PAGE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  1331. if *BY_PAGE.get_or_init(|| std::env::var_os("VICTORY_MAPPED_BY_PAGE").is_some_and(|v| v == "1")) {
  1332. // By page, without the walk: whole pages, cut to the range.
  1333. let (there, _) = readable(start, len, false);
  1334. return (there as u64 * 4096).min(len as u64);
  1335. }
  1336. // By 64 KiB block, one page asked of each: the title's memory is
  1337. // mapped in blocks of that size (the console's page), and the
  1338. // answer is a measure of how much of a texture has arrived, not a
  1339. // promise that every byte can be read (the upload reads through the
  1340. // kernel). By page, a texture half there cost a failed kernel read
  1341. // for each of its missing pages, every frame it stayed due: 1,663
  1342. // textures "uploaded in part" kept the pass over the heap's views at
  1343. // 90-160 ms a frame (run 81). `VICTORY_MAPPED_BY_PAGE=1`: by page.
  1344. const BLOCK: usize = 64 << 10;
  1345. let mut there = 0u64;
  1346. let mut block = start & !(BLOCK - 1);
  1347. while block < end {
  1348. let (lo, hi) = (block.max(start), block.saturating_add(BLOCK).min(end));
  1349. if readable(lo, 1, true).0 == 1 {
  1350. there += (hi - lo) as u64;
  1351. }
  1352. block = block.saturating_add(BLOCK);
  1353. }
  1354. return there;
  1355. }
  1356. let (mut p, mut there) = (start, 0u64);
  1357. while p < end {
  1358. // SAFETY: plain data filled in by the query.
  1359. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
  1360. // SAFETY: a valid out pointer of the right size.
  1361. let n = unsafe { VirtualQuery(p as *const _, &mut info, size_of_val(&info)) };
  1362. let next = (info.BaseAddress as usize).saturating_add(info.RegionSize).min(end);
  1363. if n == 0 || next <= p {
  1364. break;
  1365. }
  1366. if info.State == MEM_COMMIT {
  1367. there += (next - p) as u64;
  1368. }
  1369. p = next;
  1370. }
  1371. there
  1372. }
  1373. /// The staging state of a title texture, made on first use.
  1374. fn staging(resource: This, texture: &ID3D12Resource) -> Option<Arc<Staging>> {
  1375. // Asked before the table is locked: the sweep lets go of a staging
  1376. // buffer with its texture's host side locked, in that order.
  1377. let on_demand = crate::resource::host_tiled(resource).is_some();
  1378. let mut map = STAGING.lock().unwrap_or_else(|e| e.into_inner());
  1379. let map = map.get_or_insert_with(HashMap::new);
  1380. if let Some(s) = map.get(&(resource as usize)) {
  1381. return Some(s.clone());
  1382. }
  1383. let (memory, desc) = crate::resource::texture_memory(resource)?;
  1384. let Some(layout) = crate::resource::texture_layout(&desc).map(|t| t.planes[0].layout.clone())
  1385. else {
  1386. once!(
  1387. ?desc,
  1388. "texture contents without a console layout not uploaded"
  1389. );
  1390. return None;
  1391. };
  1392. if layout.desc.swizzle.xor() {
  1393. once!(?desc, "texture contents in an XOR mode not uploaded");
  1394. return None;
  1395. }
  1396. let host = host()?;
  1397. // SAFETY: a live resource.
  1398. let d = unsafe { texture.GetDesc() };
  1399. let count = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D {
  1400. u32::from(d.MipLevels)
  1401. } else {
  1402. u32::from(d.MipLevels) * u32::from(d.DepthOrArraySize)
  1403. };
  1404. let mut footprints = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); count as usize];
  1405. let mut rows = vec![0u32; count as usize];
  1406. let mut total = 0;
  1407. // SAFETY: outputs for `count` subresources.
  1408. unsafe {
  1409. host.device.GetCopyableFootprints(
  1410. &d,
  1411. 0,
  1412. count,
  1413. 0,
  1414. Some(footprints.as_mut_ptr()),
  1415. Some(rows.as_mut_ptr()),
  1416. None,
  1417. Some(&mut total),
  1418. );
  1419. }
  1420. let (piece, buffer, base, data) = match crate::pool::staging(host, total) {
  1421. Some((piece, buffer, base, data)) => (Some(piece), buffer, base, data),
  1422. None => {
  1423. let (buffer, data) = host.upload_buffer(total)?;
  1424. crate::host::name(&buffer, || {
  1425. format!(
  1426. "staging of {resource:?} {}x{}x{} f{}",
  1427. d.Width, d.Height, d.DepthOrArraySize, d.Format.0
  1428. )
  1429. });
  1430. (None, buffer, 0, data)
  1431. }
  1432. };
  1433. tracing::debug!(?desc, total, "texture contents uploaded from title memory");
  1434. STAGED[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  1435. STAGED[1].fetch_add(total, std::sync::atomic::Ordering::Relaxed);
  1436. let s = Arc::new(Staging {
  1437. buffer,
  1438. base,
  1439. _piece: piece,
  1440. #[cfg(feature = "diagnostics")]
  1441. size: total,
  1442. data,
  1443. footprints,
  1444. rows,
  1445. layout,
  1446. mips: u32::from(d.MipLevels),
  1447. bytes: total,
  1448. memory,
  1449. last: Mutex::default(),
  1450. dirty: std::sync::atomic::AtomicBool::new(true),
  1451. uploaded: std::sync::atomic::AtomicBool::new(false),
  1452. used: std::sync::atomic::AtomicU64::new(crate::host::moment()),
  1453. on_demand,
  1454. detiled: std::sync::atomic::AtomicU32::new(0),
  1455. judged: [const { std::sync::atomic::AtomicU64::new(0) }; 2],
  1456. waiting: std::sync::atomic::AtomicU64::new(0),
  1457. });
  1458. map.insert(resource as usize, s.clone());
  1459. Some(s)
  1460. }
  1461. #[cfg(test)]
  1462. mod title_memory_tests {
  1463. use super::with_title;
  1464. /// Title memory whose tail is reserved and not committed reads through
  1465. /// the copy as its bytes and then zeros, without a fault; so does
  1466. /// memory a page of which is taken away between two reads, and the
  1467. /// zeros are zeros whatever the read buffer held before.
  1468. #[test]
  1469. fn an_uncommitted_tail_reads_as_zeros() {
  1470. use windows_sys::Win32::System::Memory::*;
  1471. const HEAD: usize = 0xb_0000;
  1472. const SIZE: usize = 0x20_0000;
  1473. // SAFETY: a private reservation of our own; only committed pages
  1474. // are written in place, and nothing else reads them in place.
  1475. unsafe {
  1476. // The read buffer holds something else first.
  1477. let other = vec![0x77u8; SIZE];
  1478. with_title(other.as_ptr(), SIZE, |bytes| assert!(bytes.iter().all(|&b| b == 0x77)));
  1479. let base = VirtualAlloc(std::ptr::null(), SIZE, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  1480. assert!(!base.is_null());
  1481. assert_eq!(VirtualAlloc(base.cast(), HEAD, MEM_COMMIT, PAGE_READWRITE), base.cast());
  1482. base.write_bytes(0x5a, HEAD);
  1483. with_title(base, SIZE, |bytes| {
  1484. assert!(bytes[..HEAD].iter().all(|&b| b == 0x5a), "what is mapped");
  1485. assert!(bytes[HEAD..].iter().all(|&b| b == 0), "what is not: zeros");
  1486. });
  1487. // The title takes a page in the middle away: zeros from then
  1488. // on, the rest as before.
  1489. assert_ne!(VirtualFree(base.add(0x4_0000).cast(), 0x1_0000, MEM_DECOMMIT), 0);
  1490. with_title(base, SIZE, |bytes| {
  1491. assert!(bytes[..0x4_0000].iter().all(|&b| b == 0x5a));
  1492. assert!(bytes[0x4_0000..0x5_0000].iter().all(|&b| b == 0));
  1493. assert!(bytes[0x5_0000..HEAD].iter().all(|&b| b == 0x5a));
  1494. assert!(bytes[HEAD..].iter().all(|&b| b == 0));
  1495. });
  1496. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  1497. }
  1498. }
  1499. /// The texture both device-loss runs named last (16 texels wide, 4 or 8
  1500. /// high, format 10, layout 0x100, console flags 0x300000; its memory
  1501. /// began 0x300 into a page in run 73 and 0x700 in run 72, and here also
  1502. /// 0xf00, so that a page line runs through it): what the detiling is
  1503. /// given and what it writes are the same read in place and read through
  1504. /// the copy, and the rows it writes end where the staging buffer the
  1505. /// host sizes for it ends (896 bytes for 4 rows of 128 bytes 256 apart,
  1506. /// 1,920 for 8).
  1507. #[test]
  1508. fn the_small_texture_of_runs_72_and_73_detiles_the_same_both_ways() {
  1509. use windows_sys::Win32::System::Memory::*;
  1510. for (height, within) in [(4u32, 0x300usize), (8, 0x700), (4, 0xf00), (8, 0xf00)] {
  1511. // The description as the log printed it, word for word.
  1512. let words: [u32; 14] = [3, 0, 0, 0, 16, 0, height, 65537, 10, 1, 0, 256, 3_145_728, 0];
  1513. // SAFETY: fourteen words are a resource description (56 bytes,
  1514. // plain numbers).
  1515. let desc: crate::resource::ResourceDesc = unsafe { std::mem::transmute(words) };
  1516. let layout = crate::resource::texture_layout(&desc)
  1517. .expect("a console layout")
  1518. .planes[0]
  1519. .layout
  1520. .clone();
  1521. let size = layout.size as usize;
  1522. let (row, pitch) = (16 * 8, 256usize);
  1523. assert!(size >= row * height as usize, "the layout holds every texel");
  1524. // Committed pages and a reserved one after them; the texture
  1525. // begins `within` bytes into the first, as the title placed it.
  1526. // SAFETY: our own reservation; the committed part is written
  1527. // and read in place, by this thread alone.
  1528. unsafe {
  1529. let pages = size.div_ceil(4096) + 1;
  1530. let base = VirtualAlloc(std::ptr::null(), (pages + 1) * 4096, MEM_RESERVE, PAGE_NOACCESS).cast::<u8>();
  1531. assert!(!base.is_null());
  1532. assert_eq!(VirtualAlloc(base.cast(), pages * 4096, MEM_COMMIT, PAGE_READWRITE), base.cast());
  1533. for i in 0..pages * 4096 {
  1534. base.add(i).write((i * 7 + i / 251) as u8);
  1535. }
  1536. let memory = base.add(within);
  1537. let in_place = std::slice::from_raw_parts(memory, size);
  1538. // The bytes: the same in place and through the copy.
  1539. with_title(memory, size, |copied| assert_eq!(copied, in_place));
  1540. // What the detiling writes: the same, and inside the bytes
  1541. // the host's staging buffer for this texture has.
  1542. let staged = (height as usize - 1) * pitch + row;
  1543. assert_eq!(staged, if height == 4 { 896 } else { 1920 });
  1544. let detile = |tiled: &[u8]| {
  1545. // The slice `Staging::detile` hands over: whole rows.
  1546. let mut linear = vec![0xeeu8; pitch * height as usize];
  1547. layout
  1548. .detile(tiled, 0, 0, &mut linear, pitch, pitch * height as usize)
  1549. .expect("detiled");
  1550. linear
  1551. };
  1552. let direct = detile(in_place);
  1553. let through = with_title(memory, size, |copied| detile(copied));
  1554. assert_eq!(direct, through);
  1555. for y in 0..height as usize {
  1556. assert!(direct[y * pitch..][..row].iter().any(|&b| b != 0xee), "row {y} written");
  1557. assert!(direct[y * pitch + row..(y + 1) * pitch].iter().all(|&b| b == 0xee), "nothing past row {y}");
  1558. }
  1559. // A buffer of exactly the staged bytes is enough.
  1560. let mut exact = vec![0u8; staged];
  1561. layout
  1562. .detile(in_place, 0, 0, &mut exact, pitch, pitch * height as usize)
  1563. .expect("the staging buffer's bytes are enough");
  1564. assert_ne!(VirtualFree(base.cast(), 0, MEM_RELEASE), 0);
  1565. }
  1566. }
  1567. }
  1568. }
  1569. /// How long this PC's card takes to make the allocations a staged texture needs, for
  1570. /// `cargo test -p victory-gpu allocation_costs -- --ignored --nocapture`.
  1571. #[cfg(test)]
  1572. mod allocation_costs {
  1573. use windows::Win32::Graphics::Direct3D12::*;
  1574. use windows::Win32::Graphics::Dxgi::Common::*;
  1575. fn texture(size: u32) -> D3D12_RESOURCE_DESC {
  1576. D3D12_RESOURCE_DESC {
  1577. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  1578. Width: u64::from(size),
  1579. Height: size,
  1580. DepthOrArraySize: 1,
  1581. MipLevels: 0,
  1582. Format: DXGI_FORMAT_BC7_UNORM,
  1583. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  1584. ..Default::default()
  1585. }
  1586. }
  1587. fn buffer(size: u64) -> D3D12_RESOURCE_DESC {
  1588. D3D12_RESOURCE_DESC {
  1589. Dimension: D3D12_RESOURCE_DIMENSION_BUFFER,
  1590. Width: size,
  1591. Height: 1,
  1592. DepthOrArraySize: 1,
  1593. MipLevels: 1,
  1594. SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  1595. Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR,
  1596. ..Default::default()
  1597. }
  1598. }
  1599. fn committed(device: &ID3D12Device, kind: D3D12_HEAP_TYPE, flags: D3D12_HEAP_FLAGS, desc: &D3D12_RESOURCE_DESC) -> ID3D12Resource {
  1600. let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() };
  1601. let state = if kind == D3D12_HEAP_TYPE_UPLOAD { D3D12_RESOURCE_STATE_GENERIC_READ } else { D3D12_RESOURCE_STATE_COMMON };
  1602. let mut out = None;
  1603. // SAFETY: plain creation.
  1604. unsafe { device.CreateCommittedResource(&heap, flags, desc, state, None, &mut out) }.expect("committed");
  1605. out.unwrap()
  1606. }
  1607. fn timed(what: &str, n: usize, threads: usize, make: &(dyn Fn(usize) -> ID3D12Resource + Sync)) {
  1608. let began = std::time::Instant::now();
  1609. let all: Vec<_> = std::thread::scope(|s| {
  1610. (0..threads)
  1611. .map(|t| s.spawn(move || (t..n).step_by(threads).map(make).collect::<Vec<_>>()))
  1612. .collect::<Vec<_>>()
  1613. .into_iter()
  1614. .flat_map(|h| h.join().unwrap())
  1615. .collect()
  1616. });
  1617. let took = began.elapsed().as_secs_f64() * 1e3;
  1618. println!("{what}, {threads} thread(s): {n} in {took:.1} ms, {:.0} us each", took * 1e3 / n as f64);
  1619. drop(all);
  1620. }
  1621. /// What a look at how much of a texture is there costs: by questions to
  1622. /// the host, and by the runtime's record of its views.
  1623. #[test]
  1624. #[ignore = "a measurement, not a check"]
  1625. fn look_costs() {
  1626. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
  1627. const BLOCK: usize = 64 << 10;
  1628. for (name, blocks, there) in [("350 KB, all there", 6, 6), ("22 MB, all there", 350, 350), ("22 MB, 1 MB there", 350, 16)] {
  1629. let make = || {
  1630. // SAFETY: a reservation of our own, of which the first part
  1631. // is committed and touched.
  1632. unsafe {
  1633. let at = VirtualAlloc(std::ptr::null(), blocks * BLOCK, MEM_RESERVE, PAGE_READWRITE);
  1634. VirtualAlloc(at, there * BLOCK, MEM_COMMIT, PAGE_READWRITE);
  1635. std::ptr::write_bytes(at.cast::<u8>(), 1, there * BLOCK);
  1636. at as usize
  1637. }
  1638. };
  1639. let (asked, noted) = (make(), make());
  1640. for block in 0..there {
  1641. crate::title_memory_view(noted + block * BLOCK, BLOCK, 9, 0);
  1642. }
  1643. for (how, at) in [("asking the host", asked), ("by the views", noted)] {
  1644. const N: u32 = 200;
  1645. let began = std::time::Instant::now();
  1646. for _ in 0..N {
  1647. assert_eq!(super::mapped_bytes(at as *const u8, blocks * BLOCK), (there * BLOCK) as u64);
  1648. }
  1649. println!("{name}, {how}: {:.1} us a look", began.elapsed().as_secs_f64() * 1e6 / f64::from(N));
  1650. }
  1651. crate::inplace::views_gone(noted, blocks * BLOCK);
  1652. }
  1653. }
  1654. #[test]
  1655. #[ignore = "a measurement, not a check"]
  1656. fn allocation_costs() {
  1657. let Some(host) = crate::host::host() else { return };
  1658. let device = &host.device;
  1659. let not_zeroed = D3D12_HEAP_FLAG_CREATE_NOT_ZEROED;
  1660. const N: usize = 1000;
  1661. for size in [128u32, 512, 1024] {
  1662. let (t, b) = (texture(size), buffer(u64::from(size * size) * 4 / 3 + 65536));
  1663. println!("-- BC7 {size}x{size}");
  1664. for threads in [1, 4, 8] {
  1665. timed("texture committed", N, threads, &|_| committed(device, D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_FLAG_NONE, &t));
  1666. timed("texture committed not zeroed", N, threads, &|_| committed(device, D3D12_HEAP_TYPE_DEFAULT, not_zeroed, &t));
  1667. let mapped = |flags| {
  1668. let b = &b;
  1669. move |_| {
  1670. let r = committed(device, D3D12_HEAP_TYPE_UPLOAD, flags, b);
  1671. let mut data = std::ptr::null_mut();
  1672. // SAFETY: a live upload buffer.
  1673. unsafe { r.Map(0, None, Some(&mut data)) }.unwrap();
  1674. // SAFETY: the first byte of the mapping (its first touch).
  1675. unsafe { data.cast::<u8>().write_volatile(1) };
  1676. r
  1677. }
  1678. };
  1679. timed("staging committed and mapped", N, threads, &mapped(D3D12_HEAP_FLAG_NONE));
  1680. timed("staging committed and mapped, not zeroed", N, threads, &mapped(not_zeroed));
  1681. }
  1682. // SAFETY: plain query.
  1683. let info = unsafe { device.GetResourceAllocationInfo(0, &[t]) };
  1684. let per_heap = ((64u64 << 20) / info.SizeInBytes).max(1) as usize;
  1685. let heaps: Vec<ID3D12Heap> = (0..N.div_ceil(per_heap))
  1686. .map(|_| {
  1687. let desc = D3D12_HEAP_DESC {
  1688. SizeInBytes: per_heap as u64 * info.SizeInBytes,
  1689. Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
  1690. Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | not_zeroed,
  1691. ..Default::default()
  1692. };
  1693. let mut heap = None;
  1694. // SAFETY: plain creation.
  1695. unsafe { device.CreateHeap(&desc, &mut heap) }.expect("heap");
  1696. heap.unwrap()
  1697. })
  1698. .collect();
  1699. let place = |i: usize| {
  1700. let mut out: Option<ID3D12Resource> = None;
  1701. let at = (i % per_heap) as u64 * info.SizeInBytes;
  1702. // SAFETY: a part of a live heap no other texture has.
  1703. unsafe { device.CreatePlacedResource(&heaps[i / per_heap], at, &t, D3D12_RESOURCE_STATE_COMMON, None, &mut out) }.expect("placed");
  1704. out.unwrap()
  1705. };
  1706. timed("texture placed in 64 MB heaps", N, 1, &place);
  1707. timed("texture placed in 64 MB heaps", N, 8, &place);
  1708. }
  1709. }
  1710. }