picked.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. //! Buffers shaders write through views they pick from the heap by an index
  2. //! they compute (`VICTORY_PICKED_WRITES=1`; off by default).
  3. //!
  4. //! Which views a draw or dispatch writes through is known from its tables
  5. //! and root parameters, and their ranges are declared: what is written there
  6. //! comes back to title memory (`Shadow::gpu_writes`). A view picked by an
  7. //! index out of a buffer, per lane, names any of the heap's. What was
  8. //! written through one stayed on the card: title memory, and the title's own
  9. //! copies and textures made from it, never saw it, and a refresh of its 64
  10. //! KiB put title memory's older bytes over it. (Captures replay1 and
  11. //! replay2: `[compute 82a2ad6d07417d36]` writes 4.6 MB a frame of a 24 MB
  12. //! buffer so.) To declare all such a shader could write would be 987 MB of
  13. //! 573 buffers for every list that runs one.
  14. //!
  15. //! Two things make it small. The compare on the card says what changed since
  16. //! the last time it looked, whoever wrote it and whenever: looking now and
  17. //! then misses no buffer, it only finds it later. And a buffer that was
  18. //! written so once is written so again. So with a submission that has a
  19. //! shader that stores through a picked view ([`stores_picked`])
  20. //!
  21. //! - the buffers found written that way ([`found`]) are declared: compared
  22. //! and landed with the submission, as any declared write;
  23. //! - of the others that the heap shows unordered views of the next [`slice`]
  24. //! in turn, once a frame, is compared, and nothing else: at 32 MB all of
  25. //! them in some 30 frames. Where something changed that nobody declared,
  26. //! the buffer is one of the first kind from then on.
  27. //!
  28. //! What is found late is not landed late: the title may have other things in
  29. //! that memory by then. It goes to title memory with the next declared write
  30. //! to its 64 KiB. So what is written once, into a buffer not found yet, stays
  31. //! on the card as before.
  32. //!
  33. //! The declarations are the submission's, made when its refreshes are done
  34. //! (`Host::submit`): no refresh of it finds a range closed on their account.
  35. //!
  36. //! Only copies in the card's memory: for those in the PC's, a declared range
  37. //! is a snapshot and a compare on the CPU. (They hold 55 MB of the 987.)
  38. //!
  39. //! What it costs: the hashing of the slice and of the buffers found, and
  40. //! what changed of the latter coming back. What else changes: a step on the
  41. //! CPU that reads a buffer found waits for the flight, as it should always
  42. //! have done.
  43. use std::collections::{BTreeMap, BTreeSet};
  44. use std::sync::atomic::{AtomicU8, AtomicU64, Ordering::Relaxed};
  45. use std::sync::{Arc, Mutex, OnceLock, Weak};
  46. use crate::host::HostList;
  47. use crate::shadow::Shadow;
  48. pub(crate) fn on() -> bool {
  49. static ON: OnceLock<bool> = OnceLock::new();
  50. *ON.get_or_init(|| std::env::var_os("VICTORY_PICKED_WRITES").is_some_and(|v| v == "1"))
  51. }
  52. /// Bytes looked at in turn per frame (`VICTORY_PICKED_MB`).
  53. fn slice() -> u64 {
  54. static SLICE: OnceLock<u64> = OnceLock::new();
  55. *SLICE.get_or_init(|| {
  56. let mb = std::env::var("VICTORY_PICKED_MB").ok().and_then(|v| v.trim().parse::<u64>().ok());
  57. mb.unwrap_or(32) << 20
  58. })
  59. }
  60. /// A list's key for [`HostList::first_use`]: it runs such a shader (no title
  61. /// resource is there).
  62. const KEY: usize = usize::MAX - 0x7a;
  63. /// `list` runs a shader that stores through a picked view.
  64. pub(crate) fn runs_in(list: &HostList) {
  65. list.first_use(KEY);
  66. }
  67. /// [`crate::pipeline::Translated::picks`]: not asked yet, asked, the answers.
  68. const UNKNOWN: u8 = 0;
  69. const ASKED: u8 = 1;
  70. const NO: u8 = 2;
  71. const YES: u8 = 3;
  72. /// Whether `shader`, which stores to buffers, does so through a view it
  73. /// picks. Tracing its descriptors takes some 50 ms, so a thread of ours does
  74. /// it when the shader is first bound, and it is "no" until then: what it
  75. /// writes is found some frames later in any case. (Of the 25,904 programs of
  76. /// the title 2,923 store and have the view heap among their parameters; 37
  77. /// compute programs store through views they pick.)
  78. pub(crate) fn picks(shader: &Arc<crate::pipeline::Shader>, known: &AtomicU8) -> bool {
  79. match known.load(Relaxed) {
  80. YES => true,
  81. UNKNOWN => {
  82. if known.compare_exchange(UNKNOWN, ASKED, Relaxed, Relaxed).is_ok() {
  83. ask(shader.clone());
  84. }
  85. false
  86. }
  87. _ => false,
  88. }
  89. }
  90. fn ask(shader: Arc<crate::pipeline::Shader>) {
  91. use std::sync::mpsc::{Sender, channel};
  92. static ASKS: OnceLock<Mutex<Sender<Arc<crate::pipeline::Shader>>>> = OnceLock::new();
  93. let asks = ASKS.get_or_init(|| {
  94. let (send, asks) = channel::<Arc<crate::pipeline::Shader>>();
  95. let _ = std::thread::Builder::new().name("victory-picked".into()).spawn(move || {
  96. use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL};
  97. // SAFETY: this thread's own.
  98. unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL) };
  99. for shader in asks {
  100. let yes = shader.programs().is_none_or(|all| all.iter().any(stores_picked));
  101. if yes {
  102. tracing::info!(hash = %shader.hash, "a shader stores through views it picks from the heap (VICTORY_PICKED_WRITES=1)");
  103. }
  104. if let Some(t) = shader.translated() {
  105. t.picks.store(if yes { YES } else { NO }, Relaxed);
  106. }
  107. }
  108. });
  109. Mutex::new(send)
  110. });
  111. let _ = asks.lock().unwrap_or_else(|e| e.into_inner()).send(shader);
  112. }
  113. /// Whether the code of `program` stores to a buffer through a descriptor
  114. /// that its tables do not name: loaded from the view heap, or from a table at
  115. /// an offset it computes (programs with the view heap among their parameters). Yes where that cannot be told.
  116. fn stores_picked(program: &victory_shader::NativeProgram) -> bool {
  117. use victory_shader::HwStage;
  118. use victory_shader::gfx10::Fields;
  119. use victory_shader::native::RootType;
  120. use victory_shader::resource::{Role, Source};
  121. // (The programs that are translated.)
  122. if !matches!(program.stage, HwStage::Vs | HwStage::Ps | HwStage::Cs | HwStage::Ms) {
  123. return false;
  124. }
  125. let heap = |param: usize| program.layout.get(param).is_some_and(|p| p.root == RootType::ResourceHeap);
  126. if !(0..program.layout.len()).any(heap) {
  127. return false;
  128. }
  129. let Ok(p) = victory_shader::spill::build(program) else {
  130. return true;
  131. };
  132. // The structure is what takes time, and only per-lane descriptors need
  133. // it.
  134. let plain = victory_shader::resource::track(&p, &program.layout, program.stage, None);
  135. let res = plain.or_else(|_| {
  136. let st = victory_shader::structure::structure(&p);
  137. victory_shader::resource::track(&p, &program.layout, program.stage, st.as_ref().ok())
  138. });
  139. let Ok(res) = res else {
  140. return true;
  141. };
  142. res.descriptors.iter().filter(|d| d.role == Role::Resource).any(|d| {
  143. let inst = &p.blocks[d.site.0].insts[d.site.1];
  144. let stores = matches!(inst.fields, Fields::Buffer { .. }) && (inst.name().contains("store") || inst.name().contains("atomic"));
  145. stores
  146. && d.source.leaves().into_iter().any(|s| match s {
  147. Source::Loaded { load, .. } | Source::Fetched { load, .. } => res
  148. .scalar
  149. .iter()
  150. .find(|(site, _)| site == load)
  151. .is_some_and(|(_, a)| heap(a.param) || a.dynamic.is_some()),
  152. _ => false,
  153. })
  154. })
  155. }
  156. /// A buffer the heap shows unordered views of: title addresses, from the
  157. /// first to the last.
  158. struct Shown {
  159. copy: Weak<Shadow>,
  160. from: u64,
  161. to: u64,
  162. }
  163. #[derive(Default)]
  164. struct State {
  165. shown: BTreeMap<u64, Shown>,
  166. /// The copies (by number) found written through picked views.
  167. found: BTreeSet<u64>,
  168. /// Where the next slice begins: copy, offset from its first address.
  169. next: (u64, u64),
  170. /// The frame of the last slice.
  171. frame: u64,
  172. }
  173. static STATE: Mutex<Option<State>> = Mutex::new(None);
  174. impl State {
  175. /// The ranges of the next `most` bytes in turn, at most all once.
  176. fn turn(&mut self, most: u64) -> Vec<(u64, u64, u64)> {
  177. let mut out: Vec<(u64, u64, u64)> = Vec::new();
  178. let mut left = most;
  179. // (The one it begins in may come twice: its end first.)
  180. for _ in 0..=self.shown.len() {
  181. let (copy, offset) = self.next;
  182. let Some((&id, s)) = self.shown.range(copy..).next().or_else(|| self.shown.iter().next()) else {
  183. break;
  184. };
  185. let offset = if id == copy { offset } else { 0 };
  186. let len = s.to - s.from;
  187. let n = len.saturating_sub(offset).min(left);
  188. if n > 0 && !self.found.contains(&id) {
  189. if out.iter().any(|r| r.0 == id) {
  190. break;
  191. }
  192. out.push((id, s.from + offset, n));
  193. left -= n;
  194. if offset + n < len {
  195. self.next = (id, offset + n);
  196. break;
  197. }
  198. }
  199. self.next = (id + 1, 0);
  200. if left == 0 {
  201. break;
  202. }
  203. }
  204. out
  205. }
  206. }
  207. /// The pass over the heap's buffer views (`crate::draw`): the unordered ones
  208. /// it looked at (copy, from, to); `all` if those are all there are.
  209. pub(crate) fn shown(views: Vec<(Arc<Shadow>, u64, u64)>, all: bool) {
  210. let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
  211. let state = state.get_or_insert_with(State::default);
  212. if all {
  213. state.shown.clear();
  214. }
  215. for (copy, from, to) in views.into_iter().filter(|v| v.0.carded() && v.1 < v.2) {
  216. let e = state.shown.entry(copy.id()).or_insert_with(|| Shown {
  217. copy: Arc::downgrade(&copy),
  218. from,
  219. to,
  220. });
  221. (e.from, e.to) = (e.from.min(from), e.to.max(to));
  222. }
  223. }
  224. /// A range of a copy: title address and bytes.
  225. pub(crate) type Range = (Arc<Shadow>, usize, usize);
  226. /// What is done with a submission.
  227. #[derive(Default)]
  228. pub(crate) struct Ranges {
  229. /// To be declared.
  230. pub(crate) written: Vec<Range>,
  231. /// To be compared only.
  232. pub(crate) looked: Vec<Range>,
  233. }
  234. /// Of a submission that is about to go to the card, its refreshes done: what
  235. /// is to be declared and looked at, if one of its lists runs a shader that
  236. /// stores through a picked view.
  237. pub(crate) fn declare(runs: &[&HostList]) -> Ranges {
  238. if !on() || !runs.iter().any(|list| list.used(KEY)) {
  239. return Ranges::default();
  240. }
  241. let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
  242. let Some(state) = state.as_mut() else {
  243. return Ranges::default();
  244. };
  245. let frame = crate::frame::current();
  246. let written: Vec<(u64, u64, u64)> =
  247. state.found.iter().filter_map(|id| state.shown.get(id).map(|s| (*id, s.from, s.to - s.from))).collect();
  248. let mut looked = Vec::new();
  249. if state.frame != frame {
  250. state.frame = frame;
  251. looked = state.turn(slice());
  252. }
  253. let of = |ranges: Vec<(u64, u64, u64)>, count: usize| -> Vec<Range> {
  254. COUNTS[count].fetch_add(ranges.iter().map(|r| r.2).sum(), Relaxed);
  255. ranges
  256. .into_iter()
  257. .filter_map(|(id, at, len)| Some((state.shown.get(&id)?.copy.upgrade()?, at as usize, len as usize)))
  258. .collect()
  259. };
  260. Ranges { written: of(written, 0), looked: of(looked, 1) }
  261. }
  262. /// The compare found a piece changed (it begins at offset `at` of `copy`)
  263. /// where it only looked: something wrote it through a view nobody declared.
  264. pub(crate) fn found(copy: &Arc<Shadow>, at: usize) {
  265. let mut state = STATE.lock().unwrap_or_else(|e| e.into_inner());
  266. if state.get_or_insert_with(State::default).found.insert(copy.id()) {
  267. let (start, len) = copy.span();
  268. tracing::info!(
  269. "a buffer is written through views picked from the heap: {start:#x}+{len:#x} (first seen at +{at:#x}; VICTORY_PICKED_WRITES=1): \
  270. declared with every submission that may write it from here on"
  271. );
  272. }
  273. }
  274. /// Since the last frame-rate line: bytes declared, and bytes looked at.
  275. static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];
  276. /// For the frame-rate line.
  277. pub(crate) fn log(frames: f64) {
  278. if !on() {
  279. return;
  280. }
  281. let [declared, looked] = [0, 1].map(|i| COUNTS[i].swap(0, Relaxed) as f64 / frames / (1 << 20) as f64);
  282. let state = STATE.lock().unwrap_or_else(|e| e.into_inner());
  283. let (shown, found) = state.as_ref().map_or((0, 0), |s| (s.shown.len(), s.found.len()));
  284. tracing::info!(
  285. "views picked from the heap, per frame (VICTORY_PICKED_WRITES=1): {declared:.1} MB declared for them, {looked:.1} MB \
  286. looked at in turn; unordered views of {shown} buffers on the card, {found} of them found written"
  287. );
  288. }
  289. /// Declared writes, per copy, and those of `picked`.
  290. pub(crate) fn with(mut back: Vec<(Arc<Shadow>, Vec<(usize, usize)>)>, picked: &[Range]) -> Vec<(Arc<Shadow>, Vec<(usize, usize)>)> {
  291. for (copy, at, len) in picked {
  292. let range = (*at, *at + *len);
  293. match back.iter_mut().find(|b| Arc::ptr_eq(&b.0, copy)) {
  294. Some((_, ranges)) if ranges.contains(&range) => {}
  295. Some((_, ranges)) => ranges.push(range),
  296. None => back.push((copy.clone(), vec![range])),
  297. }
  298. }
  299. back
  300. }
  301. #[cfg(test)]
  302. mod tests {
  303. use super::*;
  304. fn state(sizes: &[u64]) -> State {
  305. let mut state = State::default();
  306. for (i, &n) in sizes.iter().enumerate() {
  307. let from = (i as u64 + 1) << 32;
  308. state.shown.insert(i as u64 * 3 + 2, Shown { copy: Weak::new(), from, to: from + n });
  309. }
  310. state
  311. }
  312. /// Every byte in turn, none left out, whatever the slice.
  313. #[test]
  314. fn all_buffers_are_looked_at_in_turn() {
  315. let sizes = [100u64, 7, 1000, 1, 350];
  316. let total: u64 = sizes.iter().sum();
  317. for most in [1u64, 10, 99, 350, 1000, 5000] {
  318. let mut s = state(&sizes);
  319. let mut seen = std::collections::BTreeMap::<u64, u64>::new();
  320. // (A turn ends with the list: it may take one more.)
  321. let turns = total.div_ceil(most) + sizes.len() as u64 + 1;
  322. for _ in 0..turns {
  323. let turn = s.turn(most);
  324. assert!(turn.iter().map(|r| r.2).sum::<u64>() <= most);
  325. for (id, at, n) in turn {
  326. let from = s.shown[&id].from;
  327. for b in at - from..at - from + n.min(2000) {
  328. *seen.entry(id << 32 | b).or_default() += 1;
  329. }
  330. }
  331. }
  332. assert_eq!(seen.len() as u64, total, "slices of {most}");
  333. }
  334. }
  335. #[test]
  336. fn what_was_found_has_no_turn() {
  337. let mut s = state(&[64, 64, 64]);
  338. s.found.insert(5);
  339. let turn = s.turn(1000);
  340. assert_eq!(turn.iter().map(|r| r.0).collect::<Vec<_>>(), [2, 8]);
  341. assert!(state(&[]).turn(10).is_empty());
  342. let mut all = state(&[64]);
  343. all.found.insert(2);
  344. assert!(all.turn(10).is_empty());
  345. }
  346. }