pool.rs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735
  1. //! Host memory for the textures the title fills, and for their staging
  2. //! buffers, cut from blocks made once.
  3. //!
  4. //! Each such texture had an allocation of its own and its staging buffer
  5. //! another. On an RX 7900 XTX an allocation takes about 310 microseconds
  6. //! whatever its size, on one thread (`texture::allocation_costs`), and a
  7. //! texture cut from a block 6: the pass that makes the textures shaders
  8. //! pick by index (`draw.rs` `heap_textures`) got through 350-500 of the
  9. //! 24,000 queued when the world loads in each of its 250 ms turns, some
  10. //! forty seconds of a world without its textures.
  11. //! `VICTORY_TEXTURE_POOL=0` makes every one an allocation of its own again.
  12. //!
  13. //! A piece given back is used again only two seconds later (nothing the card
  14. //! was told before that is still running: Windows resets a card that takes
  15. //! that long over one submission), and by then no list names it (the owners' rule, as for allocations of their own): a
  16. //! texture's piece comes back when the last reference to the host texture
  17. //! goes (an object of ours the texture holds says so), a staging buffer's
  18. //! when the last list that recorded its copy is reset.
  19. use std::collections::{BTreeMap, VecDeque};
  20. use std::ffi::c_void;
  21. use std::sync::Mutex;
  22. use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering};
  23. use windows::Win32::Graphics::Direct3D12::*;
  24. use windows::core::{GUID, HRESULT, IUnknown, Interface};
  25. /// Bytes of a block; pieces of more than half of one are not pooled (with
  26. /// blocks made ahead, [`ahead`]: of more than one).
  27. const BLOCK: u64 = 64 << 20;
  28. /// Blocks with nothing in them that are kept.
  29. const SPARE: usize = 2;
  30. /// The same while the card has room ([`room`]): 4 GiB of them.
  31. const SPARE_KEPT: usize = 64;
  32. /// The same of blocks of staging buffers, which are the PC's memory: run
  33. /// crash-1 held 5.2 GB of them.
  34. const STAGING_KEPT: usize = 8;
  35. /// How many are kept now.
  36. static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
  37. /// Sets how many empty blocks stay, by the card's memory (budget and use):
  38. /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`].
  39. /// Asked once a second.
  40. pub(crate) fn room(memory: Option<[u64; 4]>) {
  41. let pressure = crate::residency::pressured();
  42. let limit = spares(memory, crate::host::keep_freed() && !pressure);
  43. SPARES.store(limit, Ordering::Relaxed);
  44. let tick = now();
  45. // A full pool can become idle while another subsystem needs the VRAM.
  46. // A busy allocator observes the new limit on its next allocation or tick.
  47. if let Ok(mut pool) = TEXTURES.try_lock() {
  48. pool.reclaim(tick, limit, true);
  49. }
  50. if let Ok(mut pool) = STAGING.try_lock() {
  51. pool.reclaim(tick, if pressure { 0 } else { limit }, true);
  52. }
  53. }
  54. fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize {
  55. match memory {
  56. Some([budget, used, ..]) if keep && u128::from(used) * 100 < u128::from(budget) * 85 => SPARE_KEPT,
  57. _ => SPARE,
  58. }
  59. }
  60. /// Milliseconds until a piece given back is used again. (It was three
  61. /// frames, a tenth of a second while the title shows a loading screen at 30
  62. /// a second, with up to 18 submissions in the air.)
  63. const REST: u64 = 2500;
  64. fn now() -> u64 {
  65. crate::host::now_ms()
  66. }
  67. pub(crate) fn on() -> bool {
  68. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  69. *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0"))
  70. }
  71. /// How many blocks of textures are made ahead, so that one has been there
  72. /// for a while when its first piece is taken (`VICTORY_RIPE_BLOCKS`, 12;
  73. /// 0: none, and new blocks are used at once, as before).
  74. ///
  75. /// A page fault of lists already on the card, in a texture made the same
  76. /// tenth of a second as the first piece of a block made for it, lost the
  77. /// device in runs n08 and n11 (2026-11-25): the title gives a slot that
  78. /// those lists read by index a new texture. Why the card does not have the
  79. /// new block's addresses yet is not known (n11 waited for `MakeResident`;
  80. /// `indirect::tests::new_blocks_under_readers` never loses it). A block that
  81. /// every submission begun before its making has left behind ([`Ripe`]) has
  82. /// no such lists: pieces are cut from those first.
  83. fn ahead() -> usize {
  84. static AHEAD: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
  85. *AHEAD.get_or_init(|| std::env::var("VICTORY_RIPE_BLOCKS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12))
  86. }
  87. /// Submissions begun and finished ([`crate::host::submissions`]), and how
  88. /// many blocks to make ahead (0: every block is ripe at once).
  89. #[derive(Clone, Copy)]
  90. struct Ripe {
  91. started: u64,
  92. finished: u64,
  93. ahead: usize,
  94. }
  95. impl Ripe {
  96. const ALL: Ripe = Ripe { started: 0, finished: 0, ahead: 0 };
  97. fn now() -> Ripe {
  98. let (started, finished) = crate::host::submissions();
  99. // Not more than are kept ([`room`]): they would go and be made again.
  100. Ripe { started, finished, ahead: ahead().min(SPARES.load(Ordering::Relaxed)) }
  101. }
  102. fn is<B>(self, block: &Block<B>) -> bool {
  103. self.ahead == 0 || block.made <= self.finished
  104. }
  105. }
  106. /// Pieces cut from blocks that were not ripe, for want of a ripe one.
  107. static UNRIPE: AtomicU64 = AtomicU64::new(0);
  108. /// The free ranges of a block: start and length, never two that touch.
  109. struct Ranges(BTreeMap<u64, u64>);
  110. impl Ranges {
  111. fn new(size: u64) -> Ranges {
  112. Ranges(BTreeMap::from([(0, size)]))
  113. }
  114. /// The lowest place for `len` bytes at a multiple of `align`.
  115. fn take(&mut self, len: u64, align: u64) -> Option<u64> {
  116. let (start, size, at) = self.0.iter().find_map(|(&start, &size)| {
  117. let at = start.next_multiple_of(align);
  118. (at + len <= start + size).then_some((start, size, at))
  119. })?;
  120. self.0.remove(&start);
  121. if at > start {
  122. self.0.insert(start, at - start);
  123. }
  124. if at + len < start + size {
  125. self.0.insert(at + len, start + size - at - len);
  126. }
  127. Some(at)
  128. }
  129. fn give(&mut self, mut start: u64, mut len: u64) {
  130. if let Some((&before, &size)) = self.0.range(..start).next_back()
  131. && before + size == start
  132. {
  133. self.0.remove(&before);
  134. (start, len) = (before, len + size);
  135. }
  136. if let Some(size) = self.0.remove(&(start + len)) {
  137. len += size;
  138. }
  139. self.0.insert(start, len);
  140. }
  141. fn whole(&self, size: u64) -> bool {
  142. self.0.get(&0) == Some(&size)
  143. }
  144. }
  145. /// A part of a block.
  146. #[derive(Clone, Copy, Debug, PartialEq)]
  147. pub(crate) struct Piece {
  148. block: usize,
  149. start: u64,
  150. len: u64,
  151. }
  152. struct Block<B> {
  153. memory: B,
  154. free: Ranges,
  155. /// The end of the highest piece ever taken: above it the memory is as
  156. /// it was made (zeros).
  157. used_to: u64,
  158. /// The newest submission begun when it was made ([`Ripe`]).
  159. made: u64,
  160. /// When that was (ms).
  161. #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
  162. since: u64,
  163. }
  164. struct Pool<B> {
  165. /// `None`: a block let go, its place to be used again.
  166. blocks: Vec<Option<Block<B>>>,
  167. /// Pieces given back, and when each may be used again.
  168. resting: VecDeque<(u64, Piece)>,
  169. /// The empty blocks it was last told to keep, and the most it keeps.
  170. spare: usize,
  171. most: usize,
  172. retry_growth_at: u64,
  173. }
  174. impl<B: Clone> Pool<B> {
  175. const fn new(most: usize) -> Pool<B> {
  176. Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most, retry_growth_at: 0 }
  177. }
  178. /// A piece of `len` bytes and the memory it lies in, and whether that
  179. /// part was ever used before; `make` makes a block when none has room.
  180. fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnMut() -> Option<B>) -> Option<(Piece, B, bool)> {
  181. self.take_ripe(len, align, now, Ripe::ALL, make)
  182. }
  183. /// The same from a block that is ripe, if one has room; `make` makes one
  184. /// ahead too, when few are empty.
  185. fn take_ripe(
  186. &mut self,
  187. len: u64,
  188. align: u64,
  189. now: u64,
  190. ripe: Ripe,
  191. mut make: impl FnMut() -> Option<B>,
  192. ) -> Option<(Piece, B, bool)> {
  193. // With blocks made ahead, what would be an allocation of its own (and
  194. // new when the card first reads it) lies in one of those too.
  195. if len == 0 || len > if ripe.ahead > 0 { BLOCK } else { BLOCK / 2 } {
  196. return None;
  197. }
  198. self.rested(now);
  199. let mut found = None;
  200. for (i, block) in self.blocks.iter_mut().enumerate() {
  201. if let Some(block) = block
  202. && ripe.is(block)
  203. && let Some(start) = block.free.take(len, align)
  204. {
  205. found = Some((i, start));
  206. break;
  207. }
  208. }
  209. if found.is_none() && ripe.ahead > 0 {
  210. // The one that has been there the longest.
  211. let mut unripe: Vec<(u64, usize)> =
  212. self.blocks.iter().enumerate().filter_map(|(i, b)| Some((b.as_ref()?.made, i))).collect();
  213. unripe.sort_unstable();
  214. found = unripe.into_iter().find_map(|(_, i)| Some((i, self.blocks[i].as_mut()?.free.take(len, align)?)));
  215. }
  216. // A failed 64 MiB block must not trigger another driver call for each
  217. // small texture. Existing free ranges remain usable during backoff.
  218. let (i, start) = match found {
  219. Some(found) => found,
  220. None => {
  221. let memory = self.grow(now, &mut make)?;
  222. let i = self.add(memory, ripe.started);
  223. (i, self.blocks[i].as_mut()?.free.take(len, align)?)
  224. }
  225. };
  226. if ripe.ahead > 0 {
  227. if !ripe.is(self.blocks[i].as_ref()?) {
  228. let n = UNRIPE.fetch_add(1, Ordering::Relaxed) + 1;
  229. if n.is_power_of_two() {
  230. tracing::info!("textures cut from blocks made while lists ran that still run: {n}");
  231. }
  232. }
  233. let empty = self.blocks.iter().flatten().filter(|b| b.free.whole(BLOCK)).count();
  234. if empty < ripe.ahead
  235. && let Some(memory) = self.grow(now, &mut make)
  236. {
  237. self.add(memory, ripe.started);
  238. }
  239. }
  240. let block = self.blocks[i].as_mut()?;
  241. let again = start < block.used_to;
  242. block.used_to = block.used_to.max(start + len);
  243. Some((Piece { block: i, start, len }, block.memory.clone(), again))
  244. }
  245. fn grow(&mut self, now: u64, make: &mut impl FnMut() -> Option<B>) -> Option<B> {
  246. if now < self.retry_growth_at {
  247. return None;
  248. }
  249. let block = make();
  250. if block.is_none() {
  251. self.retry_growth_at = now.saturating_add(500);
  252. }
  253. block
  254. }
  255. fn add(&mut self, memory: B, made: u64) -> usize {
  256. let i = match self.blocks.iter().position(Option::is_none) {
  257. Some(i) => i,
  258. None => {
  259. self.blocks.push(None);
  260. self.blocks.len() - 1
  261. }
  262. };
  263. self.blocks[i] = Some(Block { memory, free: Ranges::new(BLOCK), used_to: 0, made, since: crate::host::now_ms() });
  264. i
  265. }
  266. fn give(&mut self, piece: Piece, now: u64) {
  267. self.resting.push_back((now + REST, piece));
  268. }
  269. /// Makes the pieces that rested long enough free, and lets go of empty
  270. /// blocks past [`SPARE`].
  271. fn rested(&mut self, now: u64) {
  272. self.reclaim(now, SPARES.load(Ordering::Relaxed), false);
  273. }
  274. fn reclaim(&mut self, now: u64, limit: usize, sweep: bool) {
  275. let mut any = false;
  276. while let Some(&(ready, piece)) = self.resting.front()
  277. && ready <= now
  278. {
  279. self.resting.pop_front();
  280. if let Some(block) = self.blocks[piece.block].as_mut() {
  281. block.free.give(piece.start, piece.len);
  282. any |= block.free.whole(BLOCK);
  283. }
  284. }
  285. // (Without a piece given back too, once there is less room.)
  286. let most = limit.min(self.most);
  287. let previous = std::mem::replace(&mut self.spare, most);
  288. if sweep || any || most < previous {
  289. let mut spare = 0;
  290. for block in &mut self.blocks {
  291. if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
  292. spare += 1;
  293. if spare > most {
  294. *block = None;
  295. }
  296. }
  297. }
  298. }
  299. }
  300. fn blocks(&self) -> usize {
  301. self.blocks.iter().flatten().count()
  302. }
  303. }
  304. /// A mapped upload buffer's memory.
  305. #[derive(Clone)]
  306. struct Upload(ID3D12Resource, *mut u8);
  307. // SAFETY: the mapping is written by the owners of its pieces, each its own.
  308. unsafe impl Send for Upload {}
  309. static TEXTURES: Mutex<Pool<ID3D12Heap>> = Mutex::new(Pool::new(SPARE_KEPT));
  310. static STAGING: Mutex<Pool<Upload>> = Mutex::new(Pool::new(STAGING_KEPT));
  311. fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
  312. m.lock().unwrap_or_else(|e| e.into_inner())
  313. }
  314. /// Bytes of the pieces textures hold now.
  315. static HELD: AtomicU64 = AtomicU64::new(0);
  316. /// Bytes of the texture blocks no texture holds: the card's memory in use
  317. /// by us that new textures take first.
  318. pub(crate) fn texture_room() -> u64 {
  319. (lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed))
  320. }
  321. /// For the memory line: blocks of textures and of staging buffers, in MiB.
  322. #[cfg(feature = "diagnostics")]
  323. pub(crate) fn memory() -> [u64; 2] {
  324. [lock(&TEXTURES).blocks() as u64 * (BLOCK >> 20), lock(&STAGING).blocks() as u64 * (BLOCK >> 20)]
  325. }
  326. /// Part of a block of mapped upload memory, back in the pool when dropped.
  327. pub(crate) struct StagingPiece(Piece);
  328. impl Drop for StagingPiece {
  329. fn drop(&mut self) {
  330. lock(&STAGING).give(self.0, now());
  331. }
  332. }
  333. /// `bytes` of upload memory, all zeros: the buffer it lies in, where in
  334. /// that buffer, and its mapping. `None`: not pooled.
  335. pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> {
  336. if !on() {
  337. return None;
  338. }
  339. // Copies from a buffer begin at multiples of 512.
  340. let bytes = bytes.next_multiple_of(512);
  341. let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
  342. let (buffer, data) = host.upload_buffer(BLOCK)?;
  343. crate::host::name(&buffer, || "staging of textures (a block)".into());
  344. Some(Upload(buffer, data))
  345. })?;
  346. let owned = StagingPiece(piece);
  347. // SAFETY: the piece lies in the block's mapping.
  348. let data = unsafe { memory.1.add(piece.start as usize) };
  349. if again {
  350. // What is not detiled into it (an unmapped texture) uploads zeros,
  351. // as from a buffer of its own.
  352. // SAFETY: the piece is ours alone.
  353. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
  354. }
  355. Some((owned, memory.0, piece.start, data))
  356. }
  357. /// An object the host texture holds and releases when it goes: its piece
  358. /// is free then.
  359. #[repr(C)]
  360. struct Reclaim {
  361. methods: &'static [*const (); 3],
  362. references: AtomicU32,
  363. piece: Piece,
  364. }
  365. struct Methods([*const (); 3]);
  366. // SAFETY: function addresses only.
  367. unsafe impl Sync for Methods {}
  368. static RECLAIM: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]);
  369. unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
  370. const E_NOINTERFACE: HRESULT = HRESULT(0x8000_4002_u32 as i32);
  371. // SAFETY: COM's arguments.
  372. unsafe {
  373. if out.is_null() {
  374. return HRESULT(0x8000_4003_u32 as i32);
  375. }
  376. if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) {
  377. add_ref(this);
  378. *out = this;
  379. return HRESULT(0);
  380. }
  381. *out = std::ptr::null_mut();
  382. }
  383. E_NOINTERFACE
  384. }
  385. unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
  386. // SAFETY: one of ours, alive while a reference to it is.
  387. unsafe { (*this.cast::<Reclaim>()).references.fetch_add(1, Ordering::Relaxed) + 1 }
  388. }
  389. unsafe extern "system" fn release(this: *mut c_void) -> u32 {
  390. // SAFETY: as above; the last reference frees the box it was made as.
  391. unsafe {
  392. let left = (*this.cast::<Reclaim>()).references.fetch_sub(1, Ordering::AcqRel) - 1;
  393. if left == 0 {
  394. let gone = Box::from_raw(this.cast::<Reclaim>());
  395. HELD.fetch_sub(gone.piece.len, Ordering::Relaxed);
  396. lock(&TEXTURES).give(gone.piece, now());
  397. }
  398. left
  399. }
  400. }
  401. /// Textures made in the last second ([`fresh`]), and when.
  402. static RECENT: Mutex<VecDeque<(usize, u64)>> = Mutex::new(VecDeque::new());
  403. /// Whether `texture` was made in a block in the last second.
  404. pub(crate) fn fresh(texture: &ID3D12Resource) -> bool {
  405. let raw = texture.as_raw() as usize;
  406. let since = now().saturating_sub(1000);
  407. RECENT.lock().unwrap_or_else(|e| e.into_inner()).iter().rev().take_while(|r| r.1 >= since).any(|r| r.0 == raw)
  408. }
  409. fn made_now(texture: &ID3D12Resource) {
  410. let now = now();
  411. let mut recent = RECENT.lock().unwrap_or_else(|e| e.into_inner());
  412. while recent.front().is_some_and(|r| r.1 + 1000 < now) {
  413. recent.pop_front();
  414. }
  415. recent.push_back((texture.as_raw() as usize, now));
  416. }
  417. /// Makes `texture` give `piece` back when the last reference to it goes.
  418. fn give_back_with(texture: &ID3D12Resource, piece: Piece) {
  419. const KEY: GUID = GUID::from_u128(0x6f0e2f0c_5a59_4b1e_9a3f_7f4d2c9be713);
  420. let made = Box::into_raw(Box::new(Reclaim { methods: &RECLAIM.0, references: AtomicU32::new(1), piece }));
  421. // SAFETY: a COM object of ours with one reference, which this takes and
  422. // drops at the end; the texture takes its own.
  423. unsafe {
  424. let object = IUnknown::from_raw(made.cast());
  425. if texture.SetPrivateDataInterface(&KEY, &object).is_err() {
  426. // Never given back: the piece stays taken, nothing is reused
  427. // under a texture that may be alive.
  428. std::mem::forget(object);
  429. }
  430. }
  431. }
  432. /// A texture of `desc` (no target, depth or unordered access) in a block;
  433. /// `None`: not pooled, or the host refused.
  434. ///
  435. /// # Safety
  436. /// `desc` is a valid description.
  437. pub(crate) unsafe fn texture(
  438. device: &ID3D12Device,
  439. desc: *const D3D12_RESOURCE_DESC,
  440. state: D3D12_RESOURCE_STATES,
  441. ) -> Option<ID3D12Resource> {
  442. if !on() {
  443. return None;
  444. }
  445. // Small textures lie at multiples of 4 KiB where the host allows it
  446. // (the top mip is 64 KiB at most): 64 KiB each otherwise.
  447. // SAFETY: the caller's description.
  448. let mut d = unsafe { *desc };
  449. d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT);
  450. // SAFETY: plain queries.
  451. let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
  452. if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment {
  453. d.Alignment = 0;
  454. info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
  455. }
  456. if info.SizeInBytes == u64::MAX {
  457. return None;
  458. }
  459. #[cfg_attr(not(feature = "diagnostics"), allow(unused_variables))]
  460. let (piece, heap, again) = lock(&TEXTURES).take_ripe(info.SizeInBytes, info.Alignment.max(1), now(), Ripe::now(), || {
  461. let desc = D3D12_HEAP_DESC {
  462. SizeInBytes: BLOCK,
  463. Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
  464. Alignment: 0,
  465. Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(),
  466. };
  467. let mut heap: Option<ID3D12Heap> = None;
  468. // SAFETY: plain creation.
  469. if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
  470. crate::residency::allocation_error(&e);
  471. tracing::warn!(error = %e, "no block of texture memory");
  472. }
  473. if let Some(h) = &heap
  474. && let Err(e) = crate::host::resident(device, h).and_then(|()| crate::host::mapped(device))
  475. {
  476. tracing::warn!(error = %e, "a block of texture memory is not resident");
  477. return None;
  478. }
  479. heap
  480. })?;
  481. let mut made: Option<ID3D12Resource> = None;
  482. // SAFETY: the piece is no one else's; the heap lives while a piece of
  483. // it is taken.
  484. let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) };
  485. match (result, made) {
  486. (Ok(()), Some(made)) => {
  487. HELD.fetch_add(piece.len, Ordering::Relaxed);
  488. give_back_with(&made, piece);
  489. made_now(&made);
  490. #[cfg(feature = "diagnostics")]
  491. {
  492. crate::book::made(&made, || "a texture in a block".into());
  493. crate::book::block(&heap, &made, piece.start, BLOCK);
  494. crate::book::note(made.as_raw() as usize, || {
  495. let block = lock(&TEXTURES).blocks.get(piece.block).and_then(Option::as_ref).map(|b| (b.made, b.since));
  496. let (submission, since) = block.unwrap_or_default();
  497. format!(
  498. "; piece {:#x}+{:#x} of block {} {:#x} made {:.1} s before it at submission {submission}, used before: {again}, made at submissions {:?}",
  499. piece.start,
  500. piece.len,
  501. piece.block,
  502. heap.as_raw() as usize,
  503. now().saturating_sub(since) as f64 / 1e3,
  504. crate::host::submissions()
  505. )
  506. });
  507. }
  508. Some(made)
  509. }
  510. _ => {
  511. lock(&TEXTURES).give(piece, now());
  512. None
  513. }
  514. }
  515. }
  516. #[cfg(test)]
  517. mod tests {
  518. use super::*;
  519. #[test]
  520. fn ranges_are_cut_aligned_and_join_again() {
  521. let mut r = Ranges::new(1024);
  522. assert_eq!(r.take(100, 64), Some(0));
  523. assert_eq!(r.take(100, 64), Some(128));
  524. assert_eq!(r.take(28, 4), Some(100));
  525. assert_eq!(r.take(2000, 4), None);
  526. r.give(128, 100);
  527. r.give(0, 100);
  528. assert!(!r.whole(1024));
  529. r.give(100, 28);
  530. assert!(r.whole(1024));
  531. }
  532. #[test]
  533. fn empty_blocks_stay_while_the_card_has_room() {
  534. assert_eq!(spares(Some([100, 84, 0, 0]), true), SPARE_KEPT);
  535. assert_eq!(spares(Some([100, 85, 0, 0]), true), SPARE);
  536. assert_eq!(spares(Some([100, 10, 0, 0]), false), SPARE);
  537. assert_eq!(spares(None, true), SPARE);
  538. }
  539. #[test]
  540. fn a_failed_block_is_not_retried_for_each_small_upload() {
  541. let mut pool: Pool<u32> = Pool::new(2);
  542. let calls = std::cell::Cell::new(0);
  543. let refuse = || { calls.set(calls.get() + 1); None };
  544. for size in [704008, 179720, 179720, 24080, 48648, 524288, 89616, 351760] {
  545. assert!(pool.take(size, 512, 12, refuse).is_none());
  546. }
  547. assert_eq!(calls.get(), 1);
  548. assert!(pool.take(24080, 512, 1012, || Some(1)).is_some());
  549. }
  550. #[test]
  551. fn budget_tick_reclaims_idle_blocks_without_reusing_live_or_resting_pieces() {
  552. let mut pool = Pool::new(STAGING_KEPT);
  553. let (held, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(1)).unwrap();
  554. let (resting, _, _) = pool.take(BLOCK / 2, 1, 0, || Some(2)).unwrap();
  555. pool.give(resting, 0);
  556. for i in 0..12 {
  557. pool.add(i, 0);
  558. }
  559. pool.reclaim(0, SPARE_KEPT, true);
  560. assert_eq!(pool.blocks(), STAGING_KEPT + 1);
  561. pool.reclaim(REST - 1, SPARE, true);
  562. assert_eq!(pool.blocks(), SPARE + 1);
  563. assert_eq!(pool.resting.len(), 1);
  564. pool.reclaim(REST, 0, true);
  565. assert_eq!(pool.blocks(), 1);
  566. assert!(pool.resting.is_empty());
  567. pool.give(held, REST);
  568. pool.reclaim(2 * REST, 0, true);
  569. assert_eq!(pool.blocks(), 0);
  570. }
  571. #[test]
  572. fn pieces_never_overlap_and_rest_before_they_are_used_again() {
  573. let mut pool: Pool<u32> = Pool::new(SPARE);
  574. let made = std::cell::Cell::new(0);
  575. let make = || {
  576. made.set(made.get() + 1);
  577. Some(made.get())
  578. };
  579. let mut taken: Vec<Piece> = Vec::new();
  580. for i in 0..500u64 {
  581. let (p, _, again) = pool.take(65536 * (1 + i % 7), 65536, 0, make).unwrap();
  582. assert!(!again);
  583. assert!(taken.iter().all(|q| q.block != p.block || p.start + p.len <= q.start || q.start + q.len <= p.start));
  584. taken.push(p);
  585. }
  586. let blocks = pool.blocks();
  587. assert!(blocks >= 2);
  588. // Given back at 10: not used again before 10 + REST.
  589. let first = taken[0];
  590. pool.give(first, 10);
  591. let (p, _, _) = pool.take(first.len, 65536, 10 + REST - 1, make).unwrap();
  592. assert_ne!((p.block, p.start), (first.block, first.start));
  593. let (q, _, again) = pool.take(first.len, 65536, 10 + REST, make).unwrap();
  594. assert_eq!((q.block, q.start, again), (first.block, first.start, true));
  595. // Everything back: the empty blocks past the spare ones go.
  596. for p in taken.drain(1..).chain([p, q]) {
  597. pool.give(p, 20);
  598. }
  599. pool.rested(20 + REST);
  600. assert_eq!(pool.blocks(), blocks.min(SPARE));
  601. // Too big for a block, and a block that cannot be made.
  602. assert!(pool.take(BLOCK, 65536, 30, make).is_none());
  603. let mut none: Pool<u32> = Pool::new(SPARE);
  604. assert!(none.take(65536, 65536, 0, || None).is_none());
  605. }
  606. #[test]
  607. fn pieces_come_from_blocks_older_than_the_lists_that_run() {
  608. let mut pool: Pool<u64> = Pool::new(SPARE_KEPT);
  609. let made = std::cell::Cell::new(0);
  610. let make = || {
  611. made.set(made.get() + 1);
  612. Some(made.get())
  613. };
  614. let at = |started, finished| Ripe { started, finished, ahead: 2 };
  615. let take = |pool: &mut Pool<u64>, ripe| pool.take_ripe(BLOCK / 2, 65536, 0, ripe, make).unwrap().1;
  616. // Nothing runs: at once, and two are made ahead, one a time.
  617. assert_eq!(take(&mut pool, at(0, 0)), 1);
  618. assert_eq!(made.get(), 2);
  619. assert_eq!(take(&mut pool, at(0, 0)), 1);
  620. assert_eq!(made.get(), 3);
  621. // 4 is made while submission 5 runs.
  622. assert_eq!(take(&mut pool, at(5, 4)), 2);
  623. assert_eq!(made.get(), 4);
  624. assert_eq!(take(&mut pool, at(5, 4)), 2);
  625. assert_eq!(take(&mut pool, at(6, 4)), 3);
  626. assert_eq!(take(&mut pool, at(6, 4)), 3);
  627. // None is ripe: the oldest; it is ripe once 5 has finished.
  628. assert_eq!(take(&mut pool, at(7, 4)), 4);
  629. assert_eq!(take(&mut pool, at(7, 5)), 4);
  630. // A whole block's worth too.
  631. assert_eq!(pool.take_ripe(BLOCK, 65536, 0, at(8, 7), make).unwrap().1, 5);
  632. // Off: the first with room, whatever its age, none ahead.
  633. let n = made.get();
  634. assert_eq!(pool.take(BLOCK / 2, 65536, 0, make).unwrap().1, 6);
  635. assert_eq!(made.get(), n);
  636. assert!(pool.take(BLOCK, 65536, 0, make).is_none());
  637. }
  638. /// A pooled texture's piece comes back when its last reference goes, not
  639. /// before; its staging piece begins as zeros.
  640. #[test]
  641. fn a_texture_gives_its_piece_back_when_it_goes() {
  642. let Some(host) = crate::host::host() else { return };
  643. let desc = D3D12_RESOURCE_DESC {
  644. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  645. Width: 256,
  646. Height: 256,
  647. DepthOrArraySize: 1,
  648. MipLevels: 1,
  649. Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
  650. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  651. ..Default::default()
  652. };
  653. // SAFETY: a valid description.
  654. let Some(t) = (unsafe { texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }) else { return };
  655. assert_eq!(crate::host::references(&t), 1, "what the texture holds is no reference to it");
  656. let resting = || lock(&TEXTURES).resting.len();
  657. let before = resting();
  658. let other = t.clone();
  659. drop(t);
  660. assert_eq!(resting(), before);
  661. drop(other);
  662. assert_eq!(resting(), before + 1);
  663. // SAFETY: the piece's mapping, 4096 bytes of it ours.
  664. unsafe {
  665. let (piece, _, at, data) = staging(host, 4096).unwrap();
  666. assert!(at.is_multiple_of(512));
  667. std::ptr::write_bytes(data, 0xAB, 4096);
  668. drop(piece);
  669. lock(&STAGING).rested(u64::MAX);
  670. let (_piece, _, _, data) = staging(host, 4096).unwrap();
  671. assert!((0..4096).all(|i| *data.add(i) == 0));
  672. // SAFETY: plain query.
  673. assert!(host.device.GetDeviceRemovedReason().is_ok());
  674. }
  675. }
  676. }