upcheck.rs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  1. //! Diagnostics (`VICTORY_UPCOPY_CHECK=1`; off by default): whether what goes
  2. //! up to a copy in the card's memory is older than what the card holds.
  3. //!
  4. //! What every send up rests on: outside ranges shaders may be writing, and
  5. //! but for what the title wrote since, a copy's CPU side holds what its card
  6. //! side holds. Two looks at that, both on the card:
  7. //!
  8. //! - **at each send**: a refresh tells what the CPU's side held before
  9. //! ([`note`]) and what it took. Ahead of the send, in its place on the
  10. //! queue, the card's words are compared with the former. A word the title
  11. //! did not change (both are equal) and the card holds another value of is
  12. //! one the send puts an older value over;
  13. //! - **at rest**: every few seconds, when the flights were settled for the
  14. //! sweep and nothing is in the air, every copy is compared whole with its
  15. //! CPU side. A word that differs is one a later send would undo. The log
  16. //! line says which buffers, what stands on the card, on the CPU's side and
  17. //! in title memory, and whether the range was declared as written at all
  18. //! (if not: a shader writes through a view nobody declared) and fetched
  19. //! lately (if so: what came down was not what the card ended with).
  20. //!
  21. //! The looks cost memory and time (the bytes sent twice more, and each
  22. //! copy read over the bus at rest): the check is not for runs that are timed.
  23. use std::collections::{BTreeMap, HashMap};
  24. use windows::Win32::Foundation::CloseHandle;
  25. use super::*;
  26. use crate::shadow::Shadow;
  27. pub(crate) fn on() -> bool {
  28. static ON: OnceLock<bool> = OnceLock::new();
  29. *ON.get_or_init(|| std::env::var_os("VICTORY_UPCOPY_CHECK").is_some_and(|v| v == "1"))
  30. }
  31. /// One dispatch looks at up to a piece: `words` words of the card's buffer
  32. /// from `at`, beside `was` (what the CPU's side held when both were known to
  33. /// be alike) and `new` (what the title has there now). Where the two are
  34. /// equal and the card's word is another one, it is counted, and the first
  35. /// found is kept: its offset, the card's value, the CPU's.
  36. const SOURCE: &str = r#"
  37. #define RS "RootConstants(num32BitConstants=5, b0), SRV(t0), SRV(t1), UAV(u0)"
  38. cbuffer Look : register(b0) { uint at; uint words; uint was; uint now; uint found_at; };
  39. ByteAddressBuffer card : register(t0);
  40. ByteAddressBuffer cpu : register(t1);
  41. RWByteAddressBuffer found : register(u0);
  42. [RootSignature(RS)]
  43. [numthreads(64, 1, 1)]
  44. void main(uint3 id : SV_DispatchThreadID) {
  45. if (id.x >= words) return;
  46. uint k = id.x * 4u, n;
  47. uint c = card.Load(at + k), w = cpu.Load(was + k);
  48. if (c == w || cpu.Load(now + k) != w) return;
  49. found.InterlockedAdd(found_at, 1u, n);
  50. if (n == 0u) found.Store3(found_at + 4u, uint3(at + k, c, w));
  51. }
  52. "#;
  53. /// Bytes of an answer.
  54. const ANSWER: u64 = 16;
  55. const PIECE: usize = 64 << 10;
  56. struct Pass {
  57. root: ID3D12RootSignature,
  58. pso: ID3D12PipelineState,
  59. }
  60. fn pass(host: &Host) -> Option<&'static Pass> {
  61. static PASS: OnceLock<Option<Pass>> = OnceLock::new();
  62. PASS.get_or_init(|| {
  63. let code = compile(SOURCE, windows::core::s!("main"), windows::core::s!("cs_5_1")).ok()?;
  64. // SAFETY: the code lives through the calls; the root signature is
  65. // inside it.
  66. unsafe {
  67. let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).ok()?;
  68. let pso: ID3D12PipelineState = host
  69. .device
  70. .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
  71. pRootSignature: std::mem::transmute_copy(&root),
  72. CS: D3D12_SHADER_BYTECODE {
  73. pShaderBytecode: code.as_ptr().cast(),
  74. BytecodeLength: code.len(),
  75. },
  76. ..Default::default()
  77. })
  78. .ok()?;
  79. Some(Pass { root, pso })
  80. }
  81. })
  82. .as_ref()
  83. }
  84. /// A piece a refresh took: its offset in the copy, what the CPU's side held
  85. /// and what it holds now.
  86. pub(crate) struct Taken {
  87. at: usize,
  88. was: Vec<u8>,
  89. new: Vec<u8>,
  90. }
  91. /// Refreshes since the last send, per copy (by its number).
  92. static NOTED: Mutex<BTreeMap<u64, Vec<Taken>>> = Mutex::new(BTreeMap::new());
  93. /// At most this much is looked at per submission.
  94. const MOST: usize = 128 << 20;
  95. /// Offsets `[at, at + was.len())` of `copy`'s CPU side held `was` and hold
  96. /// `new` from here on. (Whole words: a word only partly in it is left out.)
  97. pub(crate) fn note(copy: u64, at: usize, was: &[u8], new: &[u8]) {
  98. let skip = at.wrapping_neg() & 3;
  99. let n = was.len().min(new.len()).saturating_sub(skip) & !3;
  100. if n == 0 {
  101. return;
  102. }
  103. let at = at + skip;
  104. let (mut was, new) = (was[skip..skip + n].to_vec(), new[skip..skip + n].to_vec());
  105. let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner());
  106. let noted = noted.entry(copy).or_default();
  107. // What was noted before in this submission has not gone up yet: the card
  108. // knows what stood there before that. And what it took is not what goes
  109. // up where this took it again.
  110. for t in noted.iter_mut() {
  111. let (a, b) = (at.max(t.at), (at + n).min(t.at + t.was.len()));
  112. if a < b {
  113. was[a - at..b - at].copy_from_slice(&t.was[a - t.at..b - t.at]);
  114. t.new[a - t.at..b - t.at].copy_from_slice(&new[a - at..b - at]);
  115. }
  116. }
  117. noted.push(Taken { at, was, new });
  118. }
  119. /// A submission's look at what it sends up, until it has run.
  120. pub(super) struct Looks {
  121. found: (ID3D12Resource, usize),
  122. _bytes: ID3D12Resource,
  123. /// Per answer: the copy, and the bytes looked at.
  124. of: Vec<(std::sync::Arc<Shadow>, usize)>,
  125. }
  126. /// Per copy, since the last line: sends looked at, their bytes, words an
  127. /// older value went over, and the first few of them.
  128. #[derive(Default)]
  129. struct Stale {
  130. looked: u64,
  131. bytes: u64,
  132. sends: u64,
  133. words: u64,
  134. some: Vec<String>,
  135. }
  136. static STALE: Mutex<BTreeMap<(u64, u64), Stale>> = Mutex::new(BTreeMap::new());
  137. /// Records the looks at what `dirty` sends up into `list`, ahead of the
  138. /// sends.
  139. pub(super) fn record(
  140. host: &Host,
  141. list: &ID3D12GraphicsCommandList,
  142. dirty: &[(std::sync::Arc<Shadow>, Vec<(usize, usize)>)],
  143. ) -> Option<Looks> {
  144. let mut noted = std::mem::take(&mut *NOTED.lock().unwrap_or_else(|e| e.into_inner()));
  145. let mut all: Vec<(std::sync::Arc<Shadow>, Taken)> = Vec::new();
  146. let mut total = 0;
  147. for (shadow, _) in dirty {
  148. for taken in noted.remove(&shadow.id()).unwrap_or_default() {
  149. total += 2 * taken.was.len();
  150. if total <= MOST {
  151. all.push((shadow.clone(), taken));
  152. }
  153. }
  154. }
  155. if all.is_empty() {
  156. return None;
  157. }
  158. let pass = pass(host)?;
  159. let (bytes, to) = host.shared_buffer(total.min(MOST) as u64)?;
  160. let size = (all.len() as u64 * ANSWER).next_multiple_of(256);
  161. let (found, answers) = host.shared_buffer(size)?;
  162. // SAFETY: mappings of the sizes asked for; an open list, whose compute
  163. // state is set whole by what follows; live buffers, the ranges in them.
  164. unsafe {
  165. std::ptr::write_bytes(answers, 0, size as usize);
  166. list.SetComputeRootSignature(&pass.root);
  167. list.SetPipelineState(&pass.pso);
  168. list.SetComputeRootShaderResourceView(2, bytes.GetGPUVirtualAddress());
  169. list.SetComputeRootUnorderedAccessView(3, found.GetGPUVirtualAddress());
  170. let mut at = 0usize;
  171. for (i, (shadow, taken)) in all.iter().enumerate() {
  172. let n = taken.was.len();
  173. std::ptr::copy_nonoverlapping(taken.was.as_ptr(), to.add(at), n);
  174. std::ptr::copy_nonoverlapping(taken.new.as_ptr(), to.add(at + n), n);
  175. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  176. let constants = [taken.at as u32, (n / 4) as u32, at as u32, (at + n) as u32, (i as u64 * ANSWER) as u32];
  177. list.SetComputeRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0);
  178. list.Dispatch((n / 4).div_ceil(64) as u32, 1, 1);
  179. at += 2 * n;
  180. }
  181. // The sends come after the looks.
  182. let mut seen = std::collections::HashSet::new();
  183. let done: Vec<D3D12_RESOURCE_BARRIER> = all
  184. .iter()
  185. .filter(|(s, _)| seen.insert(std::sync::Arc::as_ptr(s) as usize))
  186. .map(|(s, _)| transition(&s.buffer, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COPY_DEST))
  187. .collect();
  188. list.ResourceBarrier(&done);
  189. }
  190. Some(Looks {
  191. found: (found, answers as usize),
  192. _bytes: bytes,
  193. of: all.into_iter().map(|(s, t)| (s, t.was.len())).collect(),
  194. })
  195. }
  196. impl Looks {
  197. /// Whether `shadow` was looked at: it is left in `COPY_DEST`.
  198. pub(super) fn hold(&self, shadow: &Shadow) -> bool {
  199. self.of.iter().any(|(s, _)| s.id() == shadow.id())
  200. }
  201. /// The submission has run: what it found is counted.
  202. pub(super) fn read(self) {
  203. // SAFETY: the mapping holds an answer for each; the card has run.
  204. let answers = unsafe { std::slice::from_raw_parts(self.found.1 as *const [u32; 4], self.of.len()) };
  205. let mut stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
  206. for ((shadow, bytes), &[words, at, card, cpu]) in self.of.iter().zip(answers) {
  207. let (start, len) = shadow.span();
  208. let e = stale.entry((start, len)).or_default();
  209. e.looked += 1;
  210. e.bytes += *bytes as u64;
  211. if words > 0 {
  212. e.sends += 1;
  213. e.words += u64::from(words);
  214. if e.some.len() < 4 {
  215. e.some.push(format!("{words} words from +{at:#x} (card {card:#x}, sent {cpu:#x}; {})", known(shadow.id(), at as usize)));
  216. }
  217. }
  218. }
  219. line(&mut stale);
  220. }
  221. }
  222. /// Once a second: what was found since.
  223. fn line(stale: &mut BTreeMap<(u64, u64), Stale>) {
  224. static SAID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  225. let now = now_ms();
  226. let said = SAID.load(Ordering::Relaxed);
  227. if now < said + 1000 || SAID.compare_exchange(said, now, Ordering::Relaxed, Ordering::Relaxed).is_err() {
  228. return;
  229. }
  230. let all = std::mem::take(stale);
  231. let sum = |f: fn(&Stale) -> u64| all.values().map(f).sum::<u64>();
  232. tracing::info!(
  233. frame = crate::frame::current(),
  234. "up-copy check: {} pieces ({} KB) sent up again in {} buffers; {} of them put an older value over {} words the card had written",
  235. sum(|s| s.looked),
  236. sum(|s| s.bytes) >> 10,
  237. all.len(),
  238. sum(|s| s.sends),
  239. sum(|s| s.words),
  240. );
  241. let mut worst: Vec<_> = all.into_iter().filter(|(_, s)| s.words > 0).collect();
  242. worst.sort_by_key(|(_, s)| std::cmp::Reverse(s.words));
  243. for ((start, len), s) in worst.into_iter().take(12) {
  244. tracing::warn!(
  245. "up-copy check: older values sent up to {start:#x}+{len:#x}: {} words in {} pieces: {}",
  246. s.words,
  247. s.sends,
  248. s.some.join(", ")
  249. );
  250. }
  251. }
  252. /// Of a copy: the ranges shaders were declared to write (joined), and the
  253. /// frame each piece was last fetched in.
  254. #[derive(Default)]
  255. struct Known {
  256. declared: Vec<(usize, usize)>,
  257. fetched: HashMap<usize, u64>,
  258. }
  259. static KNOWN: Mutex<BTreeMap<u64, Known>> = Mutex::new(BTreeMap::new());
  260. /// Offsets `[from, to)` of a copy were declared as written.
  261. pub(super) fn declared(copy: u64, from: usize, to: usize) {
  262. let mut known = KNOWN.lock().unwrap_or_else(|e| e.into_inner());
  263. let known = known.entry(copy).or_default();
  264. if !known.declared.iter().any(|r| r.0 <= from && to <= r.1) {
  265. join_ranges(&mut known.declared, [(from, to)]);
  266. }
  267. }
  268. /// A piece from offset `at` on of a copy was fetched.
  269. pub(super) fn fetched(copy: u64, at: usize) {
  270. let mut known = KNOWN.lock().unwrap_or_else(|e| e.into_inner());
  271. known.entry(copy).or_default().fetched.insert(at / PIECE, crate::frame::current());
  272. }
  273. fn known(copy: u64, at: usize) -> String {
  274. let all = KNOWN.lock().unwrap_or_else(|e| e.into_inner());
  275. let Some(known) = all.get(&copy) else {
  276. return "no shader was declared to write the buffer".into();
  277. };
  278. if !touches(&known.declared, at, at + 4) {
  279. return "never declared as written there".into();
  280. }
  281. // (Fetched pieces begin where title memory's do; the copy may begin
  282. // inside one.)
  283. let last = [at / PIECE, (at / PIECE).saturating_sub(1)].iter().filter_map(|p| known.fetched.get(p)).max().copied();
  284. match last {
  285. Some(frame) => format!("declared; last fetched {} frames ago", crate::frame::current().saturating_sub(frame)),
  286. None => "declared; never fetched".into(),
  287. }
  288. }
  289. /// Reads of title memory through one copy while a flight in the air may
  290. /// write it through another: (reader, writer) by their spans: how often, and
  291. /// the last range they share.
  292. type Crossed = BTreeMap<((u64, u64), (u64, u64)), (u64, usize, usize)>;
  293. static CROSSED: Mutex<(u64, Crossed)> = Mutex::new((0, BTreeMap::new()));
  294. /// Flights are in the air and `runs` are about to be prepared: which
  295. /// refreshes of theirs read title memory that a flight may be writing through
  296. /// another copy of it. Such a refresh takes what was there before the flight
  297. /// (nothing waits for it), and no later one knows that it was too early but
  298. /// for the landing's own write.
  299. pub(super) fn reads(runs: &[&HostList]) {
  300. let mut writes: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new();
  301. let mut all = Vec::new();
  302. for item in &super::line().line {
  303. if let Late::Run(flight) = item {
  304. for (shadow, ranges) in &flight.back {
  305. writes.extend(ranges.iter().map(|&(a, b)| (shadow.clone(), a, b)));
  306. join_ranges(&mut all, ranges.iter().copied());
  307. }
  308. }
  309. }
  310. if writes.is_empty() {
  311. return;
  312. }
  313. let mut crossed = CROSSED.lock().unwrap_or_else(|e| e.into_inner());
  314. for list in runs {
  315. for step in &list.deferred().copies {
  316. let Step::Refresh(shadow, at, len) = step else {
  317. continue;
  318. };
  319. let (from, to) = (*at, *at + *len);
  320. if !touches(&all, from, to) {
  321. continue;
  322. }
  323. for (writer, a, b) in &writes {
  324. if *a < to && from < *b && !std::sync::Arc::ptr_eq(writer, shadow) {
  325. let e = crossed.1.entry((shadow.span(), writer.span())).or_default();
  326. *e = (e.0 + 1, (*a).max(from), (*b).min(to));
  327. }
  328. }
  329. }
  330. }
  331. let now = now_ms();
  332. if now < crossed.0 + 4000 {
  333. return;
  334. }
  335. crossed.0 = now;
  336. let mut all: Vec<_> = std::mem::take(&mut crossed.1).into_iter().collect();
  337. all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
  338. for (((r, rn), (w, wn)), (n, a, b)) in all.into_iter().take(12) {
  339. tracing::warn!(
  340. "up-copy check: {n} refreshes of {r:#x}+{rn:#x} read title memory that flights in the air may write through {w:#x}+{wn:#x} (the last at {a:#x}..{b:#x})"
  341. );
  342. }
  343. }
  344. /// The title's buffer copies that are out of their place in a submission:
  345. /// by what is wrong, bytes and destination: how often, the last source, and
  346. /// (for shader writes) how much was declared.
  347. type Misplaced = BTreeMap<(&'static str, usize, usize), (u64, usize, usize)>;
  348. static MISPLACED: Mutex<(u64, Misplaced)> = Mutex::new((0, BTreeMap::new()));
  349. /// A submission is about to be prepared: its title buffer copies are done on
  350. /// the CPU then, all of them before the first of its draws runs. Where that
  351. /// is not the order of its lists: what an earlier draw of it reads of the
  352. /// destination, or shaders of it write there, or an earlier copy of it put
  353. /// there for what lies between; and a source that shaders of it write first.
  354. pub(super) fn order(runs: &[&HostList]) {
  355. let (mut read, mut written, mut copied): (Vec<(usize, usize)>, Vec<(usize, usize)>, Vec<(usize, usize)>) =
  356. (Vec::new(), Vec::new(), Vec::new());
  357. let meets = |all: &[(usize, usize)], from: usize, to: usize| all.iter().rev().find(|r| r.0 < to && from < r.1).copied();
  358. let mut misplaced = MISPLACED.lock().unwrap_or_else(|e| e.into_inner());
  359. for list in runs {
  360. for step in &list.deferred().copies {
  361. match step {
  362. Step::Refresh(_, at, len) => read.push((*at, *at + *len)),
  363. Step::GpuWrite(_, at, len) => written.push((*at, *at + *len)),
  364. &Step::Copy(dst, src, len) => {
  365. let mut say = |what: &'static str, range: (usize, usize)| {
  366. let e = misplaced.1.entry((what, len, dst)).or_default();
  367. *e = (e.0 + 1, src, range.1 - range.0);
  368. };
  369. if let Some(r) = meets(&written, src, src + len) {
  370. say("its source is declared written earlier in the submission", r);
  371. }
  372. if let Some(r) = meets(&written, dst, dst + len) {
  373. say("its destination is declared written earlier in the submission", r);
  374. }
  375. if let Some(r) = meets(&copied, dst, dst + len) {
  376. say("its destination is copied to earlier in the submission", r);
  377. } else if let Some(r) = meets(&read, dst, dst + len) {
  378. say("its destination is read earlier in the submission", r);
  379. }
  380. copied.push((dst, dst + len));
  381. }
  382. _ => {}
  383. }
  384. }
  385. }
  386. let now = now_ms();
  387. if now < misplaced.0 + 4000 {
  388. return;
  389. }
  390. misplaced.0 = now;
  391. let mut all: Vec<_> = std::mem::take(&mut misplaced.1).into_iter().collect();
  392. all.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
  393. let mut kinds: BTreeMap<&str, (u64, u64)> = BTreeMap::new();
  394. for ((what, len, _), (n, ..)) in &all {
  395. let e = kinds.entry(what).or_default();
  396. *e = (e.0 + n, e.1 + n * *len as u64);
  397. }
  398. for (what, (n, bytes)) in kinds {
  399. tracing::warn!("up-copy check, copies out of place: {n} ({bytes} bytes): {what}");
  400. }
  401. for ((what, len, dst), (n, src, declared)) in all.into_iter().take(16) {
  402. tracing::warn!("up-copy check, a copy out of place: {n} times {len:#x} bytes from {src:#x} to {dst:#x}: {what} ({declared:#x} bytes there)");
  403. }
  404. }
  405. /// A run of words that differ at rest.
  406. struct Differs {
  407. shadow: std::sync::Arc<Shadow>,
  408. at: usize,
  409. len: usize,
  410. words: u32,
  411. }
  412. /// Nothing is in the air, and nothing is sent meanwhile (the submission
  413. /// lock is held): compares every copy in the card's memory with its CPU
  414. /// side, every few seconds.
  415. pub(super) fn at_rest(host: &Host) {
  416. static LAST: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
  417. let now = now_ms();
  418. if now < LAST.load(Ordering::Relaxed) + 4000 {
  419. return;
  420. }
  421. let began = std::time::Instant::now();
  422. if look(host).is_none() {
  423. tracing::warn!("up-copy check: the look at rest could not be made");
  424. }
  425. tracing::info!(ms = began.elapsed().as_millis(), "up-copy check: the look at rest is done");
  426. LAST.store(now_ms(), Ordering::Relaxed);
  427. }
  428. /// Sends `list` (recorded by `f`) and waits for it.
  429. fn run(host: &Host, f: impl FnOnce(&ID3D12GraphicsCommandList)) -> Option<()> {
  430. let (allocator, list) = host.make_prelude()?;
  431. // SAFETY: objects of our own, waited for before they go.
  432. unsafe {
  433. allocator.Reset().ok()?;
  434. list.Reset(&allocator, None).ok()?;
  435. f(&list);
  436. list.Close().ok()?;
  437. let fence: ID3D12Fence = host.device.CreateFence(0, D3D12_FENCE_FLAG_NONE).ok()?;
  438. let event = CreateEventW(None, false, false, None).ok()?;
  439. host.queue.ExecuteCommandLists(&[Some(list.cast().ok()?)]);
  440. let done = host.queue.Signal(&fence, 1).and_then(|()| fence.SetEventOnCompletion(1, event));
  441. if done.is_ok() {
  442. WaitForSingleObject(event, INFINITE);
  443. }
  444. let _ = CloseHandle(event);
  445. done.ok()
  446. }
  447. }
  448. /// The words that differ.
  449. fn look(host: &Host) -> Option<u64> {
  450. let pass = pass(host)?;
  451. let copies = crate::shadow::carded_copies();
  452. // (copy, offset, bytes)
  453. let mut pieces: Vec<(std::sync::Arc<Shadow>, usize, usize)> = Vec::new();
  454. for shadow in &copies {
  455. // What has not gone up yet differs rightly.
  456. let dirty = shadow.card_dirty_now();
  457. let len = shadow.span().1 as usize & !3;
  458. for at in (0..len).step_by(PIECE) {
  459. let n = PIECE.min(len - at);
  460. if !dirty.iter().any(|&(a, b)| a < at + n && b > at) {
  461. pieces.push((shadow.clone(), at, n));
  462. }
  463. }
  464. }
  465. if pieces.is_empty() {
  466. return Some(0);
  467. }
  468. let size = (pieces.len() as u64 * ANSWER).next_multiple_of(256);
  469. let (found, answers) = host.shared_buffer(size)?;
  470. // SAFETY: a mapping of that size.
  471. unsafe { std::ptr::write_bytes(answers, 0, size as usize) };
  472. run(host, |list| {
  473. // SAFETY: an open list; live buffers (held by `pieces`).
  474. unsafe {
  475. list.SetComputeRootSignature(&pass.root);
  476. list.SetPipelineState(&pass.pso);
  477. list.SetComputeRootUnorderedAccessView(3, found.GetGPUVirtualAddress());
  478. let mut bound = 0;
  479. for (i, (shadow, at, n)) in pieces.iter().enumerate() {
  480. let Some((staging, ..)) = shadow.card_sides() else {
  481. continue;
  482. };
  483. if bound != shadow.id() {
  484. bound = shadow.id();
  485. list.SetComputeRootShaderResourceView(1, shadow.buffer.GetGPUVirtualAddress());
  486. list.SetComputeRootShaderResourceView(2, staging.GetGPUVirtualAddress());
  487. }
  488. let at = *at as u32;
  489. let constants = [at, (*n / 4) as u32, at, at, (i as u64 * ANSWER) as u32];
  490. list.SetComputeRoot32BitConstants(0, 5, constants.as_ptr().cast(), 0);
  491. list.Dispatch((*n / 4).div_ceil(64) as u32, 1, 1);
  492. }
  493. }
  494. })?;
  495. // SAFETY: the mapping holds an answer for each; the card has run.
  496. let answers = unsafe { std::slice::from_raw_parts(answers as *const [u32; 4], pieces.len()) };
  497. let differs: Vec<Differs> = pieces
  498. .iter()
  499. .zip(answers)
  500. .filter(|(_, a)| a[0] > 0)
  501. .map(|((shadow, at, len), a)| Differs {
  502. shadow: shadow.clone(),
  503. at: *at,
  504. len: *len,
  505. words: a[0],
  506. })
  507. .collect();
  508. let bytes: u64 = pieces.iter().map(|p| p.2 as u64).sum();
  509. let words: u64 = differs.iter().map(|d| u64::from(d.words)).sum();
  510. tracing::info!(
  511. frame = crate::frame::current(),
  512. "up-copy check at rest: {} copies, {} MB; {words} words in {} pieces of them differ from the CPU's side",
  513. copies.len(),
  514. bytes >> 20,
  515. differs.len()
  516. );
  517. if differs.is_empty() {
  518. return Some(0);
  519. }
  520. // Per copy, what stands where, of a few pieces.
  521. const SHOWN: usize = 64;
  522. let shown = &differs[..differs.len().min(SHOWN)];
  523. let (held, data) = host.shared_buffer((SHOWN * PIECE) as u64)?;
  524. run(host, |list| {
  525. for (i, d) in shown.iter().enumerate() {
  526. // SAFETY: an open list; live buffers, the ranges in them.
  527. unsafe { list.CopyBufferRegion(&held, (i * PIECE) as u64, &d.shadow.buffer, d.at as u64, d.len as u64) };
  528. }
  529. })?;
  530. let mut by: BTreeMap<(u64, u64), (u64, usize, Vec<String>)> = BTreeMap::new();
  531. for d in &differs {
  532. let e = by.entry(d.shadow.span()).or_default();
  533. e.0 += u64::from(d.words);
  534. e.1 += 1;
  535. }
  536. for (i, d) in shown.iter().enumerate() {
  537. let (start, _) = d.shadow.span();
  538. // SAFETY: the mapping; the copy into it has run.
  539. let card = unsafe { std::slice::from_raw_parts(data.add(i * PIECE).cast_const(), d.len) };
  540. let cpu = d.shadow.card_held(d.at, d.len);
  541. let mut title = vec![0u8; d.len];
  542. let mapped = read_into((start as usize + d.at) as *const u8, &mut title);
  543. // Of the words that differ: title memory holds the CPU side's
  544. // value, the card's, another one.
  545. let (mut as_cpu, mut as_card, mut other) = (0, 0, 0);
  546. let mut first = None;
  547. let (mut low, mut high) = (usize::MAX, 0);
  548. for at in (0..d.len & !3).step_by(4) {
  549. let word = |b: &[u8]| u32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]);
  550. let (c, h, t) = (word(card), word(&cpu), word(&title));
  551. if c == h {
  552. continue;
  553. }
  554. (low, high) = (low.min(at), at);
  555. first.get_or_insert((at, c, h, t));
  556. if t == h {
  557. as_cpu += 1;
  558. } else if t == c {
  559. as_card += 1;
  560. } else {
  561. other += 1;
  562. }
  563. }
  564. let Some((at, c, h, t)) = first else {
  565. continue;
  566. };
  567. if let Some(e) = by.get_mut(&d.shadow.span())
  568. && e.2.len() < 6
  569. {
  570. e.2.push(format!(
  571. "{} words in +{:#x}..{:#x} (title memory: {as_cpu} as the CPU's side, {as_card} as the card, {other} neither{}; first: \
  572. card {c:#x}, CPU {h:#x}, title {t:#x}; {})",
  573. d.words,
  574. d.at + low,
  575. d.at + high + 4,
  576. if mapped { "" } else { ", not all mapped" },
  577. known(d.shadow.id(), d.at + at)
  578. ));
  579. }
  580. }
  581. let mut by: Vec<_> = by.into_iter().collect();
  582. by.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
  583. for ((start, len), (words, pieces, some)) in by.into_iter().take(16) {
  584. tracing::warn!(
  585. "up-copy check at rest: {start:#x}+{len:#x}: {words} words in {pieces} pieces are not the CPU side's: {}",
  586. some.join("; ")
  587. );
  588. }
  589. Some(words)
  590. }
  591. #[cfg(test)]
  592. mod tests {
  593. use super::*;
  594. #[test]
  595. fn notes_are_cut_to_whole_words() {
  596. // Bytes 5..18 of a copy: the words at 8 and 12.
  597. let (was, new): (Vec<u8>, Vec<u8>) = ((5..18).collect(), (105..118).collect());
  598. note(u64::MAX, 5, &was, &new);
  599. let noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()).remove(&u64::MAX).expect("noted");
  600. let [t] = &noted[..] else { panic!("one piece") };
  601. assert_eq!((t.at, &t.was[..], &t.new[..]), (8, &was[3..11], &new[3..11]));
  602. }
  603. /// The tests below want processes of their own with the relay on: each
  604. /// `VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_UPCOPY_CHECK=1 cargo
  605. /// test -p victory-gpu --lib upcheck -- --ignored --test-threads=1
  606. /// <name>`.
  607. const LEN: usize = 4 << 20;
  608. /// Title memory of our own (write-watched, or a view of a section, which
  609. /// is guarded), and the card copy of the title buffer it is.
  610. fn title(resource: usize, view: bool) -> (&'static mut [u8], usize, std::sync::Arc<Shadow>) {
  611. let all = title_of(resource, view, LEN);
  612. assert!(all.2.carded(), "the copy is in the card's memory");
  613. all
  614. }
  615. fn title_of(resource: usize, view: bool, len: usize) -> (&'static mut [u8], usize, std::sync::Arc<Shadow>) {
  616. use windows_sys::Win32::System::Memory::{
  617. CreateFileMappingW, FILE_MAP_WRITE, MEM_COMMIT, MEM_RESERVE, MapViewOfFile, PAGE_READWRITE, VirtualAlloc,
  618. };
  619. const WRITE_WATCH: u32 = 0x20_0000;
  620. // SAFETY: memory of our own, never freed.
  621. let base = unsafe {
  622. if view {
  623. let section = CreateFileMappingW(-1isize as _, std::ptr::null(), PAGE_READWRITE, 0, len as u32, std::ptr::null());
  624. assert!(!section.is_null());
  625. MapViewOfFile(section, FILE_MAP_WRITE, 0, 0, len).Value.cast::<u8>()
  626. } else {
  627. VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT | WRITE_WATCH, PAGE_READWRITE).cast::<u8>()
  628. }
  629. };
  630. assert!(!base.is_null());
  631. crate::shadow::register(resource, base as u64, len as u64);
  632. let shadow = crate::shadow::find(base as u64, 64).expect("a copy");
  633. assert!(super::super::relay_exact() && super::super::relay_copy(), "set VICTORY_RELAY=2 VICTORY_RELAY_COPY=1");
  634. // SAFETY: `len` bytes just committed.
  635. (unsafe { std::slice::from_raw_parts_mut(base, len) }, base as usize, shadow)
  636. }
  637. /// Work for the card that takes some milliseconds.
  638. struct Slow(ID3D12Resource, ID3D12Resource);
  639. impl Slow {
  640. fn new(host: &Host) -> Slow {
  641. Slow(host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap())
  642. }
  643. fn record(&self, list: &HostList, times: usize) {
  644. // SAFETY: an open list; live buffers.
  645. unsafe {
  646. for _ in 0..times {
  647. list.list.CopyBufferRegion(&self.1, 0, &self.0, 0, 64 << 20);
  648. list.list.ResourceBarrier(&[
  649. transition(&self.1, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON),
  650. ]);
  651. }
  652. }
  653. }
  654. }
  655. /// A shader's stand-in: `bytes` go to offset `at` of the copy.
  656. fn write(host: &Host, list: &HostList, shadow: &Shadow, at: usize, bytes: &[u8]) {
  657. let (upload, data) = host.upload_buffer(bytes.len() as u64).unwrap();
  658. // SAFETY: the mapping; an open list and live buffers.
  659. unsafe {
  660. std::ptr::copy_nonoverlapping(bytes.as_ptr(), data, bytes.len());
  661. list.list.CopyBufferRegion(&shadow.buffer, at as u64, &upload, 0, bytes.len() as u64);
  662. list.list
  663. .ResourceBarrier(&[transition(&shadow.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]);
  664. }
  665. list.keep(&upload);
  666. }
  667. /// What the card's side holds, nothing being in the air.
  668. fn card(host: &Host, shadow: &Shadow) -> Vec<u8> {
  669. let (held, data) = host.shared_buffer(LEN as u64).unwrap();
  670. // SAFETY: an open list; live buffers.
  671. run(host, |list| unsafe { list.CopyBufferRegion(&held, 0, &shadow.buffer, 0, LEN as u64) }).unwrap();
  672. // SAFETY: the mapping; the copy has run.
  673. unsafe { std::slice::from_raw_parts(data, LEN) }.to_vec()
  674. }
  675. /// (e) of the list in `Host::relay_card_back`'s fetch: a flight's result
  676. /// is fetched while the next flight is at the same bytes, which ends with
  677. /// what it found. Without `VICTORY_FETCH_CHECK` title memory keeps what
  678. /// was in between, and the next refresh of the 64 KiB sends it up.
  679. #[test]
  680. #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
  681. fn a_result_caught_in_between_is_put_right() {
  682. let Some(host) = host() else {
  683. return;
  684. };
  685. let (title, start, shadow) = title(0x3333, false);
  686. let slow = Slow::new(host);
  687. let (mut wrong, mut undone) = (0, 0);
  688. let mut lists = Vec::new();
  689. const ROUNDS: usize = 12;
  690. for round in 0..ROUNDS {
  691. let result: Vec<u8> = (0..256).map(|i| (round * 17 + i + 1) as u8).collect();
  692. let between = vec![0u8; 256];
  693. let a = host.new_list().unwrap();
  694. shadow.refresh(&a, start as u64, LEN as u64);
  695. shadow.gpu_writes(&a, start as u64, LEN as u64);
  696. write(host, &a, &shadow, 1024, &result);
  697. a.close();
  698. let b = host.new_list().unwrap();
  699. shadow.gpu_writes(&b, start as u64, LEN as u64);
  700. write(host, &b, &shadow, 1024, &between);
  701. slow.record(&b, 60);
  702. write(host, &b, &shadow, 1024, &result);
  703. b.close();
  704. host.execute_own(&a);
  705. host.execute_own(&b);
  706. settle_now(WHY_SYNC);
  707. wrong += usize::from(title[1024..1280] != result[..]);
  708. // The title writes beside it: the refresh takes the 64 KiB.
  709. title[4096] = round as u8 + 1;
  710. let c = host.new_list().unwrap();
  711. shadow.refresh(&c, start as u64, LEN as u64);
  712. c.close();
  713. host.execute_own(&c);
  714. settle_now(WHY_SYNC);
  715. let holds = card(host, &shadow);
  716. assert_eq!(holds[4096], round as u8 + 1, "the title's write is on the card");
  717. undone += usize::from(holds[1024..1280] != result[..]);
  718. lists.extend([a, b, c]);
  719. }
  720. eprintln!(
  721. "{wrong} of {ROUNDS} results wrong in title memory, {undone} undone on the card; pieces checked, suspect, put right: {:?}",
  722. super::torn::STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect::<Vec<_>>()
  723. );
  724. assert_eq!(look(host), Some(0));
  725. assert_eq!((wrong, undone), (0, 0), "without VICTORY_FETCH_CHECK=1 most are wrong");
  726. }
  727. /// What nobody declared: a shader writes a piece through a view that was
  728. /// not known. The title writes another byte of the piece: it goes up
  729. /// whole, with title memory's older bytes, and the check says so.
  730. #[test]
  731. #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_UPCOPY_CHECK=1 and a process of its own"]
  732. fn the_check_finds_an_undeclared_write_undone() {
  733. let Some(host) = host() else {
  734. return;
  735. };
  736. assert!(on(), "set VICTORY_UPCOPY_CHECK=1");
  737. let (title, start, shadow) = title(0x4444, false);
  738. let a = host.new_list().unwrap();
  739. shadow.refresh(&a, start as u64, LEN as u64);
  740. shadow.gpu_writes(&a, start as u64, 1 << 16);
  741. write(host, &a, &shadow, (5 << 16) + 512, &[0x77; 64]);
  742. a.close();
  743. host.execute_own(&a);
  744. settle_now(WHY_SYNC);
  745. assert_eq!(card(host, &shadow)[(5 << 16) + 512], 0x77);
  746. assert!(title[(5 << 16) + 512] == 0, "it never comes back");
  747. assert_eq!(look(host), Some(16), "the look at rest finds it");
  748. title[(5 << 16) + 9000] = 1;
  749. let b = host.new_list().unwrap();
  750. shadow.refresh(&b, start as u64, LEN as u64);
  751. b.close();
  752. host.execute_own(&b);
  753. settle_now(WHY_SYNC);
  754. let undone = card(host, &shadow)[(5 << 16) + 512] == 0;
  755. let stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
  756. let found = stale.get(&shadow.span()).map_or(0, |s| s.words);
  757. eprintln!("undone on the card: {undone}; the check found {found} words");
  758. assert_eq!((undone, found), (true, 16));
  759. }
  760. /// A shader that writes through views it picks: its buffer is found when
  761. /// it comes to it in turn, and what it writes from then on is landed.
  762. #[test]
  763. #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 VICTORY_PICKED_WRITES=1 VICTORY_PICKED_MB=1 and a process of its own"]
  764. fn writes_through_picked_views_come_back() {
  765. let Some(host) = host() else {
  766. return;
  767. };
  768. assert!(crate::picked::on(), "set VICTORY_PICKED_WRITES=1");
  769. let (title, start, shadow) = title(0x6666, true);
  770. crate::picked::shown(vec![(shadow.clone(), start as u64, (start + LEN) as u64)], true);
  771. let at = (37 << 16) + 512;
  772. let mut lists = Vec::new();
  773. let mut back = Vec::new();
  774. for round in 0..12u8 {
  775. // Turns go by frames.
  776. crate::frame::test_advance();
  777. title[(37 << 16) + 9000] = round + 1;
  778. let list = host.new_list().unwrap();
  779. shadow.refresh(&list, start as u64, LEN as u64);
  780. crate::picked::runs_in(&list);
  781. write(host, &list, &shadow, at, &[0x40 + round; 64]);
  782. list.close();
  783. host.execute_own(&list);
  784. settle_now(WHY_SYNC);
  785. back.push(title[at..at + 64] == [0x40 + round; 64]);
  786. // The title's own write beside it is on the card, and the
  787. // shader's stays, once its buffer is known.
  788. let next = host.new_list().unwrap();
  789. shadow.refresh(&next, start as u64, LEN as u64);
  790. next.close();
  791. host.execute_own(&next);
  792. settle_now(WHY_SYNC);
  793. if *back.last().unwrap() {
  794. let holds = card(host, &shadow);
  795. assert_eq!((holds[(37 << 16) + 9000], holds[at]), (round + 1, 0x40 + round));
  796. assert_eq!(look(host), Some(0));
  797. }
  798. lists.extend([list, next]);
  799. }
  800. eprintln!("came back, by round: {back:?}");
  801. let first = back.iter().position(|b| *b).expect("it is found");
  802. assert!(first <= 6 && back[first..].iter().all(|b| *b), "{back:?}");
  803. }
  804. /// The title copies another value to the same bytes in each of three
  805. /// submissions, and each has a draw (a copy here) that reads them. The
  806. /// card is busy meanwhile, so all three are prepared before the first
  807. /// runs: each must read its own.
  808. fn each_reads_its_own(len: usize, resource: usize, carded: bool) {
  809. let Some(host) = host() else {
  810. return;
  811. };
  812. let (title, start, shadow) = title_of(resource, true, len);
  813. assert_eq!(shadow.carded(), carded, "where the copy is");
  814. let slow = Slow::new(host);
  815. let (out, out_data) = host.shared_buffer(1 << 16).unwrap();
  816. let mut lists = Vec::new();
  817. const AT: usize = 8192;
  818. // All there once.
  819. let all = host.new_list().unwrap();
  820. shadow.refresh(&all, start as u64, len as u64);
  821. all.close();
  822. host.execute_own(&all);
  823. settle_now(WHY_SYNC);
  824. lists.push(all);
  825. let mut wrong = Vec::new();
  826. for round in 0..6u8 {
  827. for v in 0..3u8 {
  828. title[65_536 + usize::from(v) * 256..][..256].fill(round * 16 + v + 1);
  829. }
  830. let busy = host.new_list().unwrap();
  831. slow.record(&busy, 40);
  832. busy.close();
  833. host.execute_own(&busy);
  834. lists.push(busy);
  835. for v in 0..3usize {
  836. let list = host.new_list().unwrap();
  837. list.defer_copy((start + AT) as *mut u8, (start + 65_536 + v * 256) as *const u8, 256);
  838. shadow.refresh(&list, (start + AT) as u64, 256);
  839. // SAFETY: an open list; live buffers.
  840. unsafe {
  841. list.list.CopyBufferRegion(&out, (v * 256) as u64, &shadow.buffer, AT as u64, 256);
  842. }
  843. list.close();
  844. host.execute_own(&list);
  845. lists.push(list);
  846. }
  847. settle_now(WHY_SYNC);
  848. // SAFETY: a mapping of 64 KiB; the copies into it have run.
  849. let read = unsafe { std::slice::from_raw_parts(out_data, 768) };
  850. for v in 0..3u8 {
  851. let got = read[usize::from(v) * 256];
  852. if got != round * 16 + v + 1 {
  853. wrong.push((round, v, got - round * 16));
  854. }
  855. }
  856. }
  857. eprintln!("read another submission's value (round, submission, whose + 1): {wrong:?}");
  858. let stale = STALE.lock().unwrap_or_else(|e| e.into_inner());
  859. let found = stale.get(&shadow.span()).map_or(0, |s| s.words);
  860. eprintln!("the check at sends found {found} words");
  861. assert!(wrong.is_empty());
  862. assert_eq!(found, 0);
  863. // With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics).
  864. assert_eq!(host.log_messages(), None);
  865. }
  866. #[test]
  867. #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
  868. fn each_submission_reads_its_own_copy_on_the_card() {
  869. each_reads_its_own(LEN, 0x7777, true);
  870. }
  871. #[test]
  872. #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
  873. fn each_submission_reads_its_own_copy_in_pc_memory() {
  874. each_reads_its_own(256 << 10, 0x8888, std::env::var_os("VICTORY_CARD_ALL").is_some_and(|v| v == "1"));
  875. }
  876. /// Declared writes beside the title's own, in the same 64 KiB pieces and
  877. /// dword by dword, flights landing while later ones are in the air: in
  878. /// the end title memory and the card hold what each wrote last. (A byte
  879. /// is written by flights or by the title, not both at a time.)
  880. #[test]
  881. #[ignore = "wants VICTORY_RELAY=2 VICTORY_RELAY_COPY=1 and a process of its own"]
  882. fn declared_writes_beside_the_titles_own_stay() {
  883. let Some(host) = host() else {
  884. return;
  885. };
  886. for view in [false, true] {
  887. beside(host, 0x5555 + usize::from(view), view);
  888. }
  889. }
  890. fn beside(host: &Host, resource: usize, view: bool) {
  891. let (title, start, shadow) = title(resource, view);
  892. let slow = Slow::new(host);
  893. // A small generator: the runs are the same each time.
  894. let mut seed = 0x1234_5678_9abc_def1u64;
  895. let mut next = move |n: usize| {
  896. seed ^= seed << 13;
  897. seed ^= seed >> 7;
  898. seed ^= seed << 17;
  899. (seed >> 11) as usize % n
  900. };
  901. // What memory should hold: pieces 0..8 are used, words of them by
  902. // turns the title's (even) and the shaders' (odd).
  903. const USED: usize = 8 << 16;
  904. let mut model = vec![0u8; USED];
  905. let mut lists = Vec::new();
  906. for round in 0..800usize {
  907. // The title writes some of its words, flights in the air or not.
  908. for _ in 0..next(24) {
  909. let at = next(USED / 8) * 8;
  910. let value = ((round as u32) << 8 | next(256) as u32).to_le_bytes();
  911. title[at..at + 4].copy_from_slice(&value);
  912. model[at..at + 4].copy_from_slice(&value);
  913. }
  914. // A submission: reads all or a part, writes a declared part.
  915. let list = host.new_list().unwrap();
  916. let (from, to) = match next(4) {
  917. 0 => (0, LEN),
  918. 1 => {
  919. let a = next(8) << 16;
  920. (a, a + (1 << 16))
  921. }
  922. _ => {
  923. let a = next(USED - 4096) & !255;
  924. (a, a + 256 * (1 + next(16)))
  925. }
  926. };
  927. shadow.refresh(&list, (start + from) as u64, (to - from) as u64);
  928. if next(5) > 0 {
  929. shadow.gpu_writes(&list, (start + from) as u64, (to - from) as u64);
  930. if next(3) == 0 {
  931. slow.record(&list, 1 + next(3));
  932. }
  933. for _ in 0..1 + next(6) {
  934. let words = (to.min(USED) - from) / 8;
  935. let at = from + next(words) * 8 + 4;
  936. // Now and then something in between first.
  937. if next(4) == 0 {
  938. write(host, &list, &shadow, at, &[0xEE; 4]);
  939. slow.record(&list, 1);
  940. }
  941. let value = if next(3) == 0 { [7, 7, 7, 7] } else { (0x8000_0000 | (round as u32) << 8 | next(256) as u32).to_le_bytes() };
  942. write(host, &list, &shadow, at, &value);
  943. model[at..at + 4].copy_from_slice(&value);
  944. }
  945. }
  946. list.close();
  947. host.execute_own(&list);
  948. lists.push(list);
  949. if round % 40 == 39 {
  950. // Everything refreshed, landed and looked at.
  951. let all = host.new_list().unwrap();
  952. shadow.refresh(&all, start as u64, LEN as u64);
  953. all.close();
  954. host.execute_own(&all);
  955. settle_now(WHY_SYNC);
  956. let all = host.new_list().unwrap();
  957. shadow.refresh(&all, start as u64, LEN as u64);
  958. all.close();
  959. host.execute_own(&all);
  960. settle_now(WHY_SYNC);
  961. lists.push(all);
  962. assert_eq!(look(host), Some(0), "round {round}: the card's side is the CPU's side");
  963. let holds = card(host, &shadow);
  964. let wrong = |held: &[u8]| (0..USED / 4).filter(|w| held[w * 4..w * 4 + 4] != model[w * 4..w * 4 + 4]).collect::<Vec<_>>();
  965. let (on_card, in_title) = (wrong(&holds), wrong(title));
  966. assert!(
  967. on_card.is_empty() && in_title.is_empty(),
  968. "round {round}: words {on_card:x?} on the card and {in_title:x?} in title memory are not what was written last"
  969. );
  970. assert_eq!(host.log_messages(), None);
  971. }
  972. }
  973. }
  974. }