texture.rs 98 KB

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