pool.rs 16 KB

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