texture.rs 65 KB

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