texture.rs 83 KB

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