picked.rs 15 KB

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