pool.rs 18 KB

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