upload.rs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178
  1. //! Memory `allocate_upload` (`list.rs`) hands out: the title's CPU writes
  2. //! it and its shaders read it at the same address (the structure builder's
  3. //! instance descriptions lie there).
  4. //!
  5. //! The console's GPU addresses have 40 bits, and a translated shader that
  6. //! reads by address has no more (`victory_shader`'s `Lower::memory`): memory
  7. //! from the process heap lies above 2^40 and was read at another address, as
  8. //! zeros. So this memory is taken in blocks of 64 KiB out of arenas in
  9. //! [4 GiB, 2^37), as upstream VIctory 0f637570 and 6d021fe3 place it (there
  10. //! an allocation of its own each). An arena is a title buffer to the host
  11. //! copies ([`crate::shadow`]) and lives as long as the process: the directory
  12. //! of memory by address ([`crate::memory`]) keeps the copy it found at an
  13. //! address for good, so the same addresses must stay the same copy.
  14. //! `VICTORY_UPLOAD_LOW=0`: from the process heap, as before.
  15. use std::sync::{Mutex, OnceLock};
  16. /// What blocks are cut on: a page of the directory of memory by address.
  17. const BLOCK: usize = 64 << 10;
  18. /// An arena's size, if one request does not need more.
  19. const ARENA: usize = 4 << 20;
  20. struct Arena {
  21. at: usize,
  22. /// Per block whether it is handed out.
  23. taken: Vec<bool>,
  24. }
  25. static ARENAS: Mutex<Vec<Arena>> = Mutex::new(Vec::new());
  26. /// Upload memory of one request, zeroed, given back when dropped.
  27. pub(crate) struct Upload(Kind);
  28. enum Kind {
  29. /// Address, bytes.
  30. Low(usize, usize),
  31. Heap(Vec<u8>),
  32. }
  33. fn low() -> bool {
  34. static ON: OnceLock<bool> = OnceLock::new();
  35. *ON.get_or_init(|| std::env::var_os("VICTORY_UPLOAD_LOW").is_none_or(|v| v != "0"))
  36. }
  37. /// The first place of `n` free blocks side by side.
  38. fn gap(taken: &[bool], n: usize) -> Option<usize> {
  39. let mut free = 0;
  40. for (i, &t) in taken.iter().enumerate() {
  41. free = if t { 0 } else { free + 1 };
  42. if free == n {
  43. return Some(i + 1 - n);
  44. }
  45. }
  46. None
  47. }
  48. /// Fresh zeroed memory in [4 GiB, 2^37) (where the directory of memory by
  49. /// address reaches, `MEMORY_PAGES`), write-watched as the title's own
  50. /// pools are (copies then take only written pages).
  51. pub(crate) fn reserve(len: usize) -> Option<usize> {
  52. use windows_sys::Win32::System::Memory::{
  53. MEM_ADDRESS_REQUIREMENTS, MEM_COMMIT, MEM_EXTENDED_PARAMETER, MEM_RESERVE, MemExtendedParameterAddressRequirements,
  54. PAGE_READWRITE, VirtualAlloc2,
  55. };
  56. const MEM_WRITE_WATCH: u32 = 0x20_0000;
  57. let mut requirements = MEM_ADDRESS_REQUIREMENTS {
  58. LowestStartingAddress: (1usize << 32) as *mut _,
  59. HighestEndingAddress: ((1usize << 37) - 1) as *mut _,
  60. Alignment: 0,
  61. };
  62. let mut parameter = MEM_EXTENDED_PARAMETER::default();
  63. parameter.Anonymous1._bitfield = MemExtendedParameterAddressRequirements as u64;
  64. parameter.Anonymous2.Pointer = (&raw mut requirements).cast();
  65. // SAFETY: a fresh allocation; the parameter points at `requirements`,
  66. // which outlives the call.
  67. let at = unsafe {
  68. VirtualAlloc2(
  69. std::ptr::null_mut(),
  70. std::ptr::null(),
  71. len,
  72. MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH,
  73. PAGE_READWRITE,
  74. &mut parameter,
  75. 1,
  76. )
  77. } as usize;
  78. (at != 0).then_some(at)
  79. }
  80. impl Upload {
  81. pub(crate) fn new(len: usize) -> Option<Upload> {
  82. if !low() {
  83. return Some(Upload(Kind::Heap(vec![0; len])));
  84. }
  85. let n = len.max(1).div_ceil(BLOCK);
  86. let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner());
  87. let found = arenas.iter().enumerate().find_map(|(a, arena)| Some((a, gap(&arena.taken, n)?)));
  88. let (a, first) = match found {
  89. Some(place) => place,
  90. None => {
  91. let blocks = n.max(ARENA / BLOCK);
  92. let at = reserve(blocks * BLOCK)?;
  93. crate::shadow::register(at, at as u64, (blocks * BLOCK) as u64);
  94. tracing::info!(at = format_args!("{at:#x}"), bytes = blocks * BLOCK, "memory for lists' uploads, where shaders reach it by address");
  95. arenas.push(Arena { at, taken: vec![false; blocks] });
  96. (arenas.len() - 1, 0)
  97. }
  98. };
  99. let arena = &mut arenas[a];
  100. arena.taken[first..first + n].fill(true);
  101. let at = arena.at + first * BLOCK;
  102. // SAFETY: the blocks are the arena's and nobody else's now.
  103. unsafe { std::ptr::write_bytes(at as *mut u8, 0, len) };
  104. Some(Upload(Kind::Low(at, len)))
  105. }
  106. pub(crate) fn start(&mut self) -> *mut u8 {
  107. match &mut self.0 {
  108. Kind::Low(at, _) => *at as *mut u8,
  109. Kind::Heap(block) => block.as_mut_ptr(),
  110. }
  111. }
  112. }
  113. impl Drop for Upload {
  114. fn drop(&mut self) {
  115. let Kind::Low(at, len) = self.0 else { return };
  116. let mut arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner());
  117. if let Some(arena) = arenas.iter_mut().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&at)) {
  118. let first = (at - arena.at) / BLOCK;
  119. arena.taken[first..first + len.max(1).div_ceil(BLOCK)].fill(false);
  120. }
  121. }
  122. }
  123. /// The block handed out that holds `address`: its start and bytes (whole
  124. /// [`BLOCK`]s).
  125. pub(crate) fn block(address: usize) -> Option<(usize, usize)> {
  126. let arenas = ARENAS.lock().unwrap_or_else(|e| e.into_inner());
  127. let arena = arenas.iter().find(|a| (a.at..a.at + a.taken.len() * BLOCK).contains(&address))?;
  128. let first = (address - arena.at) / BLOCK;
  129. let n = arena.taken[first..].iter().take_while(|t| **t).count();
  130. (n > 0).then_some((arena.at + first * BLOCK, n * BLOCK))
  131. }
  132. #[cfg(test)]
  133. mod tests {
  134. use super::*;
  135. #[test]
  136. fn blocks_lie_below_40_bits_and_are_used_again_zeroed() {
  137. let mut a = Upload::new(100).unwrap();
  138. let mut b = Upload::new(BLOCK + 1).unwrap();
  139. let (pa, pb) = (a.start(), b.start());
  140. assert!((pa as usize) >= 1 << 32 && (pb as usize) + 2 * BLOCK <= 1 << 40);
  141. assert!((pa as usize).is_multiple_of(BLOCK) && pa != pb);
  142. // SAFETY: 100 bytes were handed out.
  143. unsafe { pa.write_bytes(0xab, 100) };
  144. drop(a);
  145. // The lowest free place (another test may have taken it meanwhile;
  146. // zeroed either way).
  147. let mut c = Upload::new(100).unwrap();
  148. // SAFETY: as above.
  149. assert!(unsafe { std::slice::from_raw_parts(c.start(), 100) }.iter().all(|&x| x == 0));
  150. // More than an arena.
  151. let mut d = Upload::new(ARENA + 1).unwrap();
  152. // SAFETY: the bytes were handed out.
  153. unsafe { d.start().add(ARENA).write(1) };
  154. drop(b);
  155. }
  156. #[test]
  157. fn a_gap_is_blocks_side_by_side() {
  158. assert_eq!(gap(&[true, false, true, false, false, true], 1), Some(1));
  159. assert_eq!(gap(&[true, false, true, false, false, true], 2), Some(3));
  160. assert_eq!(gap(&[true, false, true, false, false, true], 3), None);
  161. }
  162. }