pool.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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.
  26. const BLOCK: u64 = 64 << 20;
  27. /// Blocks with nothing in them that are kept.
  28. const SPARE: usize = 2;
  29. /// The same while the card has room ([`room`]): 4 GiB of them.
  30. const SPARE_KEPT: usize = 64;
  31. /// The same of blocks of staging buffers, which are the PC's memory: run
  32. /// crash-1 held 5.2 GB of them.
  33. const STAGING_KEPT: usize = 8;
  34. /// How many are kept now.
  35. static SPARES: AtomicUsize = AtomicUsize::new(SPARE);
  36. /// Sets how many empty blocks stay, by the card's memory (budget and use):
  37. /// [`SPARE_KEPT`] below 85 % ([`crate::host::keep_freed`]), else [`SPARE`].
  38. /// Asked once a second.
  39. pub(crate) fn room(memory: Option<[u64; 4]>) {
  40. SPARES.store(spares(memory, crate::host::keep_freed()), Ordering::Relaxed);
  41. }
  42. fn spares(memory: Option<[u64; 4]>, keep: bool) -> usize {
  43. match memory {
  44. Some([budget, used, ..]) if keep && u128::from(used) * 100 < u128::from(budget) * 85 => SPARE_KEPT,
  45. _ => SPARE,
  46. }
  47. }
  48. /// Milliseconds until a piece given back is used again. (It was three
  49. /// frames, a tenth of a second while the title shows a loading screen at 30
  50. /// a second, with up to 18 submissions in the air.)
  51. const REST: u64 = 2500;
  52. fn now() -> u64 {
  53. crate::host::now_ms()
  54. }
  55. pub(crate) fn on() -> bool {
  56. static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
  57. *ON.get_or_init(|| std::env::var_os("VICTORY_TEXTURE_POOL").is_none_or(|v| v != "0"))
  58. }
  59. /// The free ranges of a block: start and length, never two that touch.
  60. struct Ranges(BTreeMap<u64, u64>);
  61. impl Ranges {
  62. fn new(size: u64) -> Ranges {
  63. Ranges(BTreeMap::from([(0, size)]))
  64. }
  65. /// The lowest place for `len` bytes at a multiple of `align`.
  66. fn take(&mut self, len: u64, align: u64) -> Option<u64> {
  67. let (start, size, at) = self.0.iter().find_map(|(&start, &size)| {
  68. let at = start.next_multiple_of(align);
  69. (at + len <= start + size).then_some((start, size, at))
  70. })?;
  71. self.0.remove(&start);
  72. if at > start {
  73. self.0.insert(start, at - start);
  74. }
  75. if at + len < start + size {
  76. self.0.insert(at + len, start + size - at - len);
  77. }
  78. Some(at)
  79. }
  80. fn give(&mut self, mut start: u64, mut len: u64) {
  81. if let Some((&before, &size)) = self.0.range(..start).next_back()
  82. && before + size == start
  83. {
  84. self.0.remove(&before);
  85. (start, len) = (before, len + size);
  86. }
  87. if let Some(size) = self.0.remove(&(start + len)) {
  88. len += size;
  89. }
  90. self.0.insert(start, len);
  91. }
  92. fn whole(&self, size: u64) -> bool {
  93. self.0.get(&0) == Some(&size)
  94. }
  95. }
  96. /// A part of a block.
  97. #[derive(Clone, Copy, Debug, PartialEq)]
  98. pub(crate) struct Piece {
  99. block: usize,
  100. start: u64,
  101. len: u64,
  102. }
  103. struct Block<B> {
  104. memory: B,
  105. free: Ranges,
  106. /// The end of the highest piece ever taken: above it the memory is as
  107. /// it was made (zeros).
  108. used_to: u64,
  109. }
  110. struct Pool<B> {
  111. /// `None`: a block let go, its place to be used again.
  112. blocks: Vec<Option<Block<B>>>,
  113. /// Pieces given back, and when each may be used again.
  114. resting: VecDeque<(u64, Piece)>,
  115. /// The empty blocks it was last told to keep, and the most it keeps.
  116. spare: usize,
  117. most: usize,
  118. }
  119. impl<B: Clone> Pool<B> {
  120. const fn new(most: usize) -> Pool<B> {
  121. Pool { blocks: Vec::new(), resting: VecDeque::new(), spare: 0, most }
  122. }
  123. /// A piece of `len` bytes and the memory it lies in, and whether that
  124. /// part was ever used before; `make` makes a block when none has room.
  125. fn take(&mut self, len: u64, align: u64, now: u64, make: impl FnOnce() -> Option<B>) -> Option<(Piece, B, bool)> {
  126. if len == 0 || len > BLOCK / 2 {
  127. return None;
  128. }
  129. self.rested(now);
  130. let mut found = None;
  131. for (i, block) in self.blocks.iter_mut().enumerate() {
  132. if let Some(block) = block
  133. && let Some(start) = block.free.take(len, align)
  134. {
  135. found = Some((i, start));
  136. break;
  137. }
  138. }
  139. let (i, start) = match found {
  140. Some(found) => found,
  141. None => {
  142. let mut block = Block { memory: make()?, free: Ranges::new(BLOCK), used_to: 0 };
  143. let start = block.free.take(len, align)?;
  144. let i = match self.blocks.iter().position(Option::is_none) {
  145. Some(i) => i,
  146. None => {
  147. self.blocks.push(None);
  148. self.blocks.len() - 1
  149. }
  150. };
  151. self.blocks[i] = Some(block);
  152. (i, start)
  153. }
  154. };
  155. let block = self.blocks[i].as_mut()?;
  156. let again = start < block.used_to;
  157. block.used_to = block.used_to.max(start + len);
  158. Some((Piece { block: i, start, len }, block.memory.clone(), again))
  159. }
  160. fn give(&mut self, piece: Piece, now: u64) {
  161. self.resting.push_back((now + REST, piece));
  162. }
  163. /// Makes the pieces that rested long enough free, and lets go of empty
  164. /// blocks past [`SPARE`].
  165. fn rested(&mut self, now: u64) {
  166. let mut any = false;
  167. while let Some(&(ready, piece)) = self.resting.front()
  168. && ready <= now
  169. {
  170. self.resting.pop_front();
  171. if let Some(block) = self.blocks[piece.block].as_mut() {
  172. block.free.give(piece.start, piece.len);
  173. any |= block.free.whole(BLOCK);
  174. }
  175. }
  176. // (Without a piece given back too, once there is less room.)
  177. let most = SPARES.load(Ordering::Relaxed).min(self.most);
  178. if any || most < self.spare {
  179. self.spare = most;
  180. let mut spare = 0;
  181. for block in &mut self.blocks {
  182. if block.as_ref().is_some_and(|b| b.free.whole(BLOCK)) {
  183. spare += 1;
  184. if spare > most {
  185. *block = None;
  186. }
  187. }
  188. }
  189. }
  190. }
  191. fn blocks(&self) -> usize {
  192. self.blocks.iter().flatten().count()
  193. }
  194. }
  195. /// A mapped upload buffer's memory.
  196. #[derive(Clone)]
  197. struct Upload(ID3D12Resource, *mut u8);
  198. // SAFETY: the mapping is written by the owners of its pieces, each its own.
  199. unsafe impl Send for Upload {}
  200. static TEXTURES: Mutex<Pool<ID3D12Heap>> = Mutex::new(Pool::new(SPARE_KEPT));
  201. static STAGING: Mutex<Pool<Upload>> = Mutex::new(Pool::new(STAGING_KEPT));
  202. fn lock<T>(m: &'static Mutex<T>) -> std::sync::MutexGuard<'static, T> {
  203. m.lock().unwrap_or_else(|e| e.into_inner())
  204. }
  205. /// Bytes of the pieces textures hold now.
  206. static HELD: AtomicU64 = AtomicU64::new(0);
  207. /// Bytes of the texture blocks no texture holds: the card's memory in use
  208. /// by us that new textures take first.
  209. pub(crate) fn texture_room() -> u64 {
  210. (lock(&TEXTURES).blocks() as u64 * BLOCK).saturating_sub(HELD.load(Ordering::Relaxed))
  211. }
  212. /// For the memory line: blocks of textures and of staging buffers, in MiB.
  213. #[cfg(feature = "diagnostics")]
  214. pub(crate) fn memory() -> [u64; 2] {
  215. [lock(&TEXTURES).blocks() as u64 * (BLOCK >> 20), lock(&STAGING).blocks() as u64 * (BLOCK >> 20)]
  216. }
  217. /// Part of a block of mapped upload memory, back in the pool when dropped.
  218. pub(crate) struct StagingPiece(Piece);
  219. impl Drop for StagingPiece {
  220. fn drop(&mut self) {
  221. lock(&STAGING).give(self.0, now());
  222. }
  223. }
  224. /// `bytes` of upload memory, all zeros: the buffer it lies in, where in
  225. /// that buffer, and its mapping. `None`: not pooled.
  226. pub(crate) fn staging(host: &crate::host::Host, bytes: u64) -> Option<(StagingPiece, ID3D12Resource, u64, *mut u8)> {
  227. if !on() {
  228. return None;
  229. }
  230. // Copies from a buffer begin at multiples of 512.
  231. let bytes = bytes.next_multiple_of(512);
  232. let (piece, memory, again) = lock(&STAGING).take(bytes, 512, now(), || {
  233. let (buffer, data) = host.upload_buffer(BLOCK)?;
  234. crate::host::name(&buffer, || "staging of textures (a block)".into());
  235. Some(Upload(buffer, data))
  236. })?;
  237. let owned = StagingPiece(piece);
  238. // SAFETY: the piece lies in the block's mapping.
  239. let data = unsafe { memory.1.add(piece.start as usize) };
  240. if again {
  241. // What is not detiled into it (an unmapped texture) uploads zeros,
  242. // as from a buffer of its own.
  243. // SAFETY: the piece is ours alone.
  244. unsafe { std::ptr::write_bytes(data, 0, bytes as usize) };
  245. }
  246. Some((owned, memory.0, piece.start, data))
  247. }
  248. /// An object the host texture holds and releases when it goes: its piece
  249. /// is free then.
  250. #[repr(C)]
  251. struct Reclaim {
  252. methods: &'static [*const (); 3],
  253. references: AtomicU32,
  254. piece: Piece,
  255. }
  256. struct Methods([*const (); 3]);
  257. // SAFETY: function addresses only.
  258. unsafe impl Sync for Methods {}
  259. static RECLAIM: Methods = Methods([query as *const (), add_ref as *const (), release as *const ()]);
  260. unsafe extern "system" fn query(this: *mut c_void, iid: *const GUID, out: *mut *mut c_void) -> HRESULT {
  261. const E_NOINTERFACE: HRESULT = HRESULT(0x8000_4002_u32 as i32);
  262. // SAFETY: COM's arguments.
  263. unsafe {
  264. if out.is_null() {
  265. return HRESULT(0x8000_4003_u32 as i32);
  266. }
  267. if iid.as_ref().is_some_and(|iid| *iid == IUnknown::IID) {
  268. add_ref(this);
  269. *out = this;
  270. return HRESULT(0);
  271. }
  272. *out = std::ptr::null_mut();
  273. }
  274. E_NOINTERFACE
  275. }
  276. unsafe extern "system" fn add_ref(this: *mut c_void) -> u32 {
  277. // SAFETY: one of ours, alive while a reference to it is.
  278. unsafe { (*this.cast::<Reclaim>()).references.fetch_add(1, Ordering::Relaxed) + 1 }
  279. }
  280. unsafe extern "system" fn release(this: *mut c_void) -> u32 {
  281. // SAFETY: as above; the last reference frees the box it was made as.
  282. unsafe {
  283. let left = (*this.cast::<Reclaim>()).references.fetch_sub(1, Ordering::AcqRel) - 1;
  284. if left == 0 {
  285. let gone = Box::from_raw(this.cast::<Reclaim>());
  286. HELD.fetch_sub(gone.piece.len, Ordering::Relaxed);
  287. lock(&TEXTURES).give(gone.piece, now());
  288. }
  289. left
  290. }
  291. }
  292. /// Makes `texture` give `piece` back when the last reference to it goes.
  293. fn give_back_with(texture: &ID3D12Resource, piece: Piece) {
  294. const KEY: GUID = GUID::from_u128(0x6f0e2f0c_5a59_4b1e_9a3f_7f4d2c9be713);
  295. let made = Box::into_raw(Box::new(Reclaim { methods: &RECLAIM.0, references: AtomicU32::new(1), piece }));
  296. // SAFETY: a COM object of ours with one reference, which this takes and
  297. // drops at the end; the texture takes its own.
  298. unsafe {
  299. let object = IUnknown::from_raw(made.cast());
  300. if texture.SetPrivateDataInterface(&KEY, &object).is_err() {
  301. // Never given back: the piece stays taken, nothing is reused
  302. // under a texture that may be alive.
  303. std::mem::forget(object);
  304. }
  305. }
  306. }
  307. /// A texture of `desc` (no target, depth or unordered access) in a block;
  308. /// `None`: not pooled, or the host refused.
  309. ///
  310. /// # Safety
  311. /// `desc` is a valid description.
  312. pub(crate) unsafe fn texture(
  313. device: &ID3D12Device,
  314. desc: *const D3D12_RESOURCE_DESC,
  315. state: D3D12_RESOURCE_STATES,
  316. ) -> Option<ID3D12Resource> {
  317. if !on() {
  318. return None;
  319. }
  320. // Small textures lie at multiples of 4 KiB where the host allows it
  321. // (the top mip is 64 KiB at most): 64 KiB each otherwise.
  322. // SAFETY: the caller's description.
  323. let mut d = unsafe { *desc };
  324. d.Alignment = u64::from(D3D12_SMALL_RESOURCE_PLACEMENT_ALIGNMENT);
  325. // SAFETY: plain queries.
  326. let mut info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
  327. if info.SizeInBytes == u64::MAX || info.Alignment != d.Alignment {
  328. d.Alignment = 0;
  329. info = unsafe { device.GetResourceAllocationInfo(0, &[d]) };
  330. }
  331. if info.SizeInBytes == u64::MAX {
  332. return None;
  333. }
  334. let (piece, heap, _) = lock(&TEXTURES).take(info.SizeInBytes, info.Alignment.max(1), now(), || {
  335. let desc = D3D12_HEAP_DESC {
  336. SizeInBytes: BLOCK,
  337. Properties: D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() },
  338. Alignment: 0,
  339. Flags: D3D12_HEAP_FLAG_ALLOW_ONLY_NON_RT_DS_TEXTURES | crate::host::not_resident(),
  340. };
  341. let mut heap: Option<ID3D12Heap> = None;
  342. // SAFETY: plain creation.
  343. if let Err(e) = unsafe { device.CreateHeap(&desc, &mut heap) } {
  344. tracing::warn!(error = %e, "no block of texture memory");
  345. }
  346. if let Some(h) = &heap
  347. && let Err(e) = crate::host::resident(device, h)
  348. {
  349. tracing::warn!(error = %e, "a block of texture memory is not resident");
  350. return None;
  351. }
  352. heap
  353. })?;
  354. let mut made: Option<ID3D12Resource> = None;
  355. // SAFETY: the piece is no one else's; the heap lives while a piece of
  356. // it is taken.
  357. let result = unsafe { device.CreatePlacedResource(&heap, piece.start, &d, state, None, &mut made) };
  358. match (result, made) {
  359. (Ok(()), Some(made)) => {
  360. HELD.fetch_add(piece.len, Ordering::Relaxed);
  361. give_back_with(&made, piece);
  362. #[cfg(feature = "diagnostics")]
  363. {
  364. crate::book::made(&made, || "a texture in a block".into());
  365. crate::book::block(&heap, &made, piece.start, BLOCK);
  366. }
  367. Some(made)
  368. }
  369. _ => {
  370. lock(&TEXTURES).give(piece, now());
  371. None
  372. }
  373. }
  374. }
  375. #[cfg(test)]
  376. mod tests {
  377. use super::*;
  378. #[test]
  379. fn ranges_are_cut_aligned_and_join_again() {
  380. let mut r = Ranges::new(1024);
  381. assert_eq!(r.take(100, 64), Some(0));
  382. assert_eq!(r.take(100, 64), Some(128));
  383. assert_eq!(r.take(28, 4), Some(100));
  384. assert_eq!(r.take(2000, 4), None);
  385. r.give(128, 100);
  386. r.give(0, 100);
  387. assert!(!r.whole(1024));
  388. r.give(100, 28);
  389. assert!(r.whole(1024));
  390. }
  391. #[test]
  392. fn empty_blocks_stay_while_the_card_has_room() {
  393. assert_eq!(spares(Some([100, 84, 0, 0]), true), SPARE_KEPT);
  394. assert_eq!(spares(Some([100, 85, 0, 0]), true), SPARE);
  395. assert_eq!(spares(Some([100, 10, 0, 0]), false), SPARE);
  396. assert_eq!(spares(None, true), SPARE);
  397. }
  398. #[test]
  399. fn pieces_never_overlap_and_rest_before_they_are_used_again() {
  400. let mut pool: Pool<u32> = Pool::new(SPARE);
  401. let made = std::cell::Cell::new(0);
  402. let make = || {
  403. made.set(made.get() + 1);
  404. Some(made.get())
  405. };
  406. let mut taken: Vec<Piece> = Vec::new();
  407. for i in 0..500u64 {
  408. let (p, _, again) = pool.take(65536 * (1 + i % 7), 65536, 0, make).unwrap();
  409. assert!(!again);
  410. assert!(taken.iter().all(|q| q.block != p.block || p.start + p.len <= q.start || q.start + q.len <= p.start));
  411. taken.push(p);
  412. }
  413. let blocks = pool.blocks();
  414. assert!(blocks >= 2);
  415. // Given back at 10: not used again before 10 + REST.
  416. let first = taken[0];
  417. pool.give(first, 10);
  418. let (p, _, _) = pool.take(first.len, 65536, 10 + REST - 1, make).unwrap();
  419. assert_ne!((p.block, p.start), (first.block, first.start));
  420. let (q, _, again) = pool.take(first.len, 65536, 10 + REST, make).unwrap();
  421. assert_eq!((q.block, q.start, again), (first.block, first.start, true));
  422. // Everything back: the empty blocks past the spare ones go.
  423. for p in taken.drain(1..).chain([p, q]) {
  424. pool.give(p, 20);
  425. }
  426. pool.rested(20 + REST);
  427. assert_eq!(pool.blocks(), blocks.min(SPARE));
  428. // Too big for a block, and a block that cannot be made.
  429. assert!(pool.take(BLOCK, 65536, 30, make).is_none());
  430. let mut none: Pool<u32> = Pool::new(SPARE);
  431. assert!(none.take(65536, 65536, 0, || None).is_none());
  432. }
  433. /// A pooled texture's piece comes back when its last reference goes, not
  434. /// before; its staging piece begins as zeros.
  435. #[test]
  436. fn a_texture_gives_its_piece_back_when_it_goes() {
  437. let Some(host) = crate::host::host() else { return };
  438. let desc = D3D12_RESOURCE_DESC {
  439. Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D,
  440. Width: 256,
  441. Height: 256,
  442. DepthOrArraySize: 1,
  443. MipLevels: 1,
  444. Format: windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8G8B8A8_UNORM,
  445. SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
  446. ..Default::default()
  447. };
  448. // SAFETY: a valid description.
  449. let Some(t) = (unsafe { texture(&host.device, &desc, D3D12_RESOURCE_STATE_COMMON) }) else { return };
  450. assert_eq!(crate::host::references(&t), 1, "what the texture holds is no reference to it");
  451. let resting = || lock(&TEXTURES).resting.len();
  452. let before = resting();
  453. let other = t.clone();
  454. drop(t);
  455. assert_eq!(resting(), before);
  456. drop(other);
  457. assert_eq!(resting(), before + 1);
  458. // SAFETY: the piece's mapping, 4096 bytes of it ours.
  459. unsafe {
  460. let (piece, _, at, data) = staging(host, 4096).unwrap();
  461. assert!(at.is_multiple_of(512));
  462. std::ptr::write_bytes(data, 0xAB, 4096);
  463. drop(piece);
  464. lock(&STAGING).rested(u64::MAX);
  465. let (_piece, _, _, data) = staging(host, 4096).unwrap();
  466. assert!((0..4096).all(|i| *data.add(i) == 0));
  467. // SAFETY: plain query.
  468. assert!(host.device.GetDeviceRemovedReason().is_ok());
  469. }
  470. }
  471. }