card_steps.rs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. //! Steps of a submission that read title memory flights in the air may
  2. //! still write, done on the card in the flights' order instead of on the
  3. //! CPU after a wait for them (`VICTORY_CARD_STEPS`, see [`stage`]).
  4. use std::sync::Arc;
  5. use super::*;
  6. use crate::shadow::Shadow;
  7. /// The stage (`VICTORY_CARD_STEPS`; off by default): `1` constant buffers
  8. /// of descriptor tables (`Step::Fill` with a slot of its own), `2` the
  9. /// title's buffer copies (`Step::Copy`) too, with the steps of the same
  10. /// submission that depend on them. Only with the relay's second stage
  11. /// (`relay_exact`).
  12. ///
  13. /// Why: eleven dispatches a frame (the skinning passes, in two early
  14. /// submissions) write through a view of the title's whole 174 MB heap, at
  15. /// places they read out of job records in buffers: no bound of what they
  16. /// write is known before they ran (frame capture replay2: 17af15c4015cb4b6,
  17. /// 55679a0547649d0b, 89d08e561897d4e5, fdd56d97a806bcca and three more,
  18. /// all through one view at offset 5920 of the title's bindless table). The
  19. /// title's ring of constants lies in the same heap. One constant buffer of
  20. /// 480 bytes and one copy of 20 KiB a frame, at a new place of the ring
  21. /// each time, waited for these passes to land: 25-30 ms of a 105 ms frame,
  22. /// the submitting thread standing (run record-1; with `VICTORY_FILL_TITLE=1`
  23. /// in run relaycopy-1 the copy alone took over the wait).
  24. ///
  25. /// What is done: a list of ours goes to the card in front of the
  26. /// submission's lists, in the same call. It copies the bytes read from the
  27. /// host copy that the flights write into a buffer of ours, and from there
  28. /// to the destination's host copy (a copy), or the fill's descriptor slot
  29. /// is pointed at that buffer (a fill; the slot is the fill's alone, the
  30. /// root signatures say such descriptors are volatile, and the list that
  31. /// names it has not gone to the card).
  32. ///
  33. /// Why that is the value the CPU would have read after the wait. After the
  34. /// wait title memory holds, for every byte read, what the title wrote, or
  35. /// what the last of the flights that wrote it wrote (the landings put it
  36. /// there, in order). The host copy on the card holds the same when our list
  37. /// runs: every flight that may write one of these bytes writes this same
  38. /// host copy ([`holder`]: a write through another host copy, a read-back
  39. /// or a value written behind a flight there, and the old wait is taken),
  40. /// they are all ahead of our list on the queue, and the title's own bytes
  41. /// are brought up to date by a refresh step of our list, which is prepared
  42. /// like any other list's (also under flights' declared writes:
  43. /// `stale_under_flights`, which settles if it cannot). Nothing of this
  44. /// submission writes these bytes earlier than our list: the steps are done
  45. /// in front of all its lists in either case, and among themselves in the
  46. /// order they stand in wherever one depends on another: [`plan`] takes
  47. /// every copy and fill of the submission that writes what a taken one
  48. /// reads or writes, or reads what a taken one writes. Every draw that
  49. /// reads a buffer view of the heap relies on the same refresh and the same
  50. /// order; what is new is only that a constant buffer and a copy do too.
  51. /// Where a page is not mapped the host copy may hold other bytes than the
  52. /// CPU's copy would have left: refused.
  53. ///
  54. /// For a copy's destination our list declares a shader write, exactly the
  55. /// bytes copied, after a refresh of them: from there on it is what any
  56. /// shader's write is. The relay compares, and puts what changed into title
  57. /// memory before the title is told anything of this flight (its
  58. /// bottom-of-pipe writes and fences come after, in order); CPU steps of
  59. /// later submissions that read it find it declared and wait, or are done
  60. /// here. Refused: a step of the submission that cannot be taken (a texture,
  61. /// vertices expanded, a fill of memory of another kind) reads the
  62. /// destination behind the copy, or a refresh brings another host copy of it
  63. /// up to date ([`plan`], [`elsewhere`]). While such a copy is in the air a
  64. /// submission that refreshes another host copy of its destination, or
  65. /// reads it in a step that is not checked otherwise, waits for it
  66. /// ([`copied_read`]); with the copy done on the CPU it was there at once.
  67. ///
  68. /// What stage 2 does not see: code of ours that reads title memory away
  69. /// from a submission's steps (the pass over textures picked by index, while
  70. /// a list is recorded). With the CPU's copy such a read of the destination
  71. /// found the bytes at once; now it finds them when the flight has landed.
  72. /// The landing tells the guards (`crate::watch::landing`), so a texture
  73. /// made from older bytes is made again. This is why stage 2 is its own.
  74. pub(super) fn stage() -> u32 {
  75. static STAGE: OnceLock<u32> = OnceLock::new();
  76. *STAGE.get_or_init(|| match std::env::var("VICTORY_CARD_STEPS").ok().as_deref() {
  77. Some("1") => 1,
  78. Some("2") => 2,
  79. _ => 0,
  80. })
  81. }
  82. /// The bytes of our buffer between reading and writing: what one submission
  83. /// may do this way (each place read once, however many fills take it).
  84. const BETWEEN: u64 = 4 << 20;
  85. /// The most steps of a submission done this way.
  86. const MOST: usize = 4096;
  87. /// How a fill's bytes get where its list reads them, if the card brings
  88. /// them.
  89. #[derive(Clone)]
  90. pub(super) enum FillTo {
  91. /// A descriptor slot that shows the fill's memory, and nothing else does
  92. /// (title heap, slot): it is made to show our buffer instead.
  93. Slot(usize, u32),
  94. /// A buffer the card can write, filled from its beginning.
  95. Buffer(ID3D12Resource),
  96. }
  97. /// Title memory something in the air writes: the host copy it goes through
  98. /// (`None`: none, the bytes reach title memory when the flight lands), from,
  99. /// to, and whether it is the destination of a copy done here.
  100. pub(super) struct Writer {
  101. shadow: Option<Arc<Shadow>>,
  102. from: usize,
  103. to: usize,
  104. copy: bool,
  105. }
  106. /// What `items` of the line write.
  107. pub(super) fn writers(items: &[Late]) -> Vec<Writer> {
  108. let mut out = Vec::new();
  109. for item in items {
  110. match item {
  111. Late::Run(flight) => {
  112. for (shadow, ranges) in &flight.back {
  113. out.extend(ranges.iter().map(|&(from, to)| Writer {
  114. shadow: Some(shadow.clone()),
  115. from,
  116. to,
  117. copy: false,
  118. }));
  119. }
  120. for &i in &flight.order {
  121. for &(_, at, [row, rows, pitch]) in &flight.lists[i].host().deferred().backs {
  122. out.push(Writer {
  123. shadow: None,
  124. from: at,
  125. to: at + rows.saturating_sub(1) * pitch + row,
  126. copy: false,
  127. });
  128. }
  129. }
  130. out.extend(flight.own.iter().flat_map(Taken::copied));
  131. }
  132. Late::Write(at, _, bytes) => out.push(Writer {
  133. shadow: None,
  134. from: *at,
  135. to: *at + *bytes,
  136. copy: false,
  137. }),
  138. Late::Signal(..) => {}
  139. }
  140. }
  141. out
  142. }
  143. /// The destinations of copies done here that have not landed.
  144. pub(super) fn copies(line: &Line) -> Vec<Writer> {
  145. if stage() < 2 {
  146. return Vec::new();
  147. }
  148. let flying = line.line.iter().filter_map(|l| match l {
  149. Late::Run(flight) => flight.own.as_ref(),
  150. _ => None,
  151. });
  152. let landing = line.landing.iter().filter(|w| w.copy).map(|w| Writer {
  153. shadow: w.shadow.clone(),
  154. ..*w
  155. });
  156. flying.flat_map(Taken::copied).chain(landing).collect()
  157. }
  158. /// Whether `runs` refresh another host copy of a destination in `copies`,
  159. /// or read it in a step that flights are not waited for otherwise
  160. /// (`Step::Host`): that reads title memory, where the copy is not yet.
  161. pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool {
  162. if copies.is_empty() {
  163. return false;
  164. }
  165. runs.iter().any(|list| {
  166. list.deferred().copies.iter().any(|step| match step {
  167. Step::Refresh(shadow, at, len) => copies
  168. .iter()
  169. .any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))),
  170. Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to),
  171. _ => false,
  172. })
  173. })
  174. }
  175. /// What a step of a submission does to title memory, as the plan sees it.
  176. /// `asked`: flights in the air stop it from being done on the CPU now.
  177. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  178. enum Does {
  179. Copy { dst: usize, src: usize, len: usize, asked: bool },
  180. /// `to`: its memory can be given the bytes on the card.
  181. Fill { src: usize, len: usize, asked: bool, to: bool },
  182. /// Another read on the CPU (a texture, vertices expanded).
  183. Read { from: usize, to: usize, asked: bool },
  184. /// A refresh of a host copy (named by its address).
  185. Refresh { shadow: usize, from: usize, to: usize },
  186. /// A copy that its list does on the card ([`place`]).
  187. Placed { dst: usize, src: usize, len: usize },
  188. /// Anything, anywhere.
  189. Run,
  190. }
  191. fn meet(a: (usize, usize), b: (usize, usize)) -> bool {
  192. a.0 < b.1 && b.0 < a.1
  193. }
  194. /// The bytes `d` reads and writes as a copy or a fill (empty ranges for
  195. /// what it does not).
  196. fn reads_writes(d: &Does) -> Option<((usize, usize), (usize, usize))> {
  197. match *d {
  198. Does::Copy { dst, src, len, .. } => Some(((src, src + len), (dst, dst + len))),
  199. Does::Fill { src, len, .. } => Some(((src, src + len), (0, 0))),
  200. _ => None,
  201. }
  202. }
  203. fn touched(ranges: &[(usize, usize)], r: (usize, usize)) -> bool {
  204. touches(ranges, r.0, r.1)
  205. }
  206. /// The steps of `does` (by place) to be done on the card, in order, each
  207. /// with its level; or why not. All that are asked for, and every copy and
  208. /// fill that is in the way of one that is done there: it writes what that
  209. /// one reads or writes, or reads what it writes, whichever comes first. So
  210. /// what is left on the CPU writes none of their bytes, and reads of them
  211. /// only what a taken copy has not been told to write yet: bytes a step
  212. /// ahead of it reads, in title memory as it is.
  213. ///
  214. /// Steps of a level are done together, every read before every write; a
  215. /// step that writes what an earlier one reads or writes, or reads what it
  216. /// writes, is of a higher level. Our list does them level by level.
  217. fn plan(does: &[Does], stage: u32) -> Result<Vec<(usize, u32)>, &'static str> {
  218. let takes = |d: &Does| match *d {
  219. Does::Copy { .. } if stage < 2 => Err("a buffer copy (VICTORY_CARD_STEPS=2 does it on the card)"),
  220. Does::Fill { to: false, .. } => Err("a fill of memory the card cannot be given the bytes of"),
  221. _ => Ok(()),
  222. };
  223. let mut taken = vec![false; does.len()];
  224. let (mut read, mut written) = (Vec::new(), Vec::new());
  225. let mut more = Vec::new();
  226. for (i, d) in does.iter().enumerate() {
  227. match *d {
  228. Does::Run => return Err("a step of ours runs"),
  229. Does::Read { asked: true, .. } => return Err("a texture reads it"),
  230. Does::Copy { asked: true, .. } | Does::Fill { asked: true, .. } => more.push(i),
  231. _ => {}
  232. }
  233. }
  234. while !more.is_empty() {
  235. for i in std::mem::take(&mut more) {
  236. takes(&does[i])?;
  237. taken[i] = true;
  238. if let Some((r, w)) = reads_writes(&does[i]) {
  239. if w.0 < w.1 && meet(r, w) {
  240. return Err("a copy onto itself");
  241. }
  242. join_ranges(&mut read, [r]);
  243. join_ranges(&mut written, [w]);
  244. }
  245. }
  246. if taken.iter().filter(|t| **t).count() > MOST {
  247. return Err("too many steps depend on it");
  248. }
  249. for (i, d) in does.iter().enumerate() {
  250. // A fill that cannot be taken is looked at below.
  251. if taken[i] || matches!(d, Does::Fill { to: false, .. }) {
  252. continue;
  253. }
  254. if let Some((r, w)) = reads_writes(d)
  255. && (touched(&written, r) || touched(&written, w) || touched(&read, w))
  256. {
  257. more.push(i);
  258. }
  259. }
  260. }
  261. // A copy at its place in a list comes after what is done in front of all
  262. // of them.
  263. for d in does {
  264. if let Does::Placed { dst, src, len } = *d
  265. && (touched(&read, (dst, dst + len)) || touched(&written, (dst, dst + len)) || touched(&written, (src, src + len)))
  266. {
  267. return Err("a copy at its place in a list writes what it reads, or reads or writes what it writes");
  268. }
  269. }
  270. let order: Vec<usize> = (0..does.len()).filter(|&i| taken[i]).collect();
  271. // What stays on the CPU and reads what an earlier taken copy writes
  272. // would read it too early.
  273. let mut behind: Vec<(usize, usize)> = Vec::new();
  274. for (i, d) in does.iter().enumerate() {
  275. if taken[i] {
  276. if let Some((_, w)) = reads_writes(d) {
  277. join_ranges(&mut behind, [w]);
  278. }
  279. continue;
  280. }
  281. match *d {
  282. Does::Read { from, to, .. } if touched(&behind, (from, to)) => {
  283. return Err("a texture or expanded vertices read what it writes");
  284. }
  285. Does::Fill { src, len, .. } if touched(&behind, (src, src + len)) => {
  286. return Err("a fill of memory the card cannot be given the bytes of reads what it writes");
  287. }
  288. _ => {}
  289. }
  290. }
  291. let mut out: Vec<(usize, u32)> = Vec::with_capacity(order.len());
  292. // The copies among them, which alone put others behind them or have to
  293. // stand behind others.
  294. let mut copies: Vec<usize> = Vec::new();
  295. for &i in &order {
  296. let Some((r, w)) = reads_writes(&does[i]) else {
  297. continue;
  298. };
  299. let writes = w.0 < w.1;
  300. let mut level = 0;
  301. // Behind what writes what this reads or writes, and, if this
  302. // writes, behind what reads it.
  303. let ahead: Box<dyn Iterator<Item = usize>> =
  304. if writes { Box::new(0..out.len()) } else { Box::new(copies.iter().copied()) };
  305. for k in ahead {
  306. let (j, at): (usize, u32) = out[k];
  307. let Some((jr, jw)) = reads_writes(&does[j]) else {
  308. continue;
  309. };
  310. if at >= level && (meet(jw, r) || meet(jw, w) || meet(jr, w)) {
  311. level = at + 1;
  312. }
  313. }
  314. if writes {
  315. copies.push(out.len());
  316. }
  317. out.push((i, level));
  318. }
  319. Ok(out)
  320. }
  321. /// Whether a refresh of `does` brings a host copy other than `shadow` up to
  322. /// date in `[from, to)`.
  323. fn elsewhere(does: &[Does], shadow: usize, from: usize, to: usize) -> bool {
  324. does.iter().any(|d| match *d {
  325. Does::Refresh { shadow: s, from: a, to: b } => s != shadow && meet((a, b), (from, to)),
  326. _ => false,
  327. })
  328. }
  329. /// The host copy that holds `[from, to)` on the card once what `writers`
  330. /// write is there: the one they all write it through, or without any the
  331. /// one shaders would be given.
  332. fn holder(writers: &[Writer], from: usize, to: usize) -> Result<Arc<Shadow>, &'static str> {
  333. let mut found: Option<&Arc<Shadow>> = None;
  334. for w in writers.iter().filter(|w| meet((w.from, w.to), (from, to))) {
  335. match (&w.shadow, found) {
  336. (None, _) => return Err("a read-back or a value behind a flight is written there"),
  337. (Some(s), Some(f)) if !Arc::ptr_eq(s, f) => return Err("flights write it through two host copies"),
  338. (Some(s), _) => found = Some(s),
  339. }
  340. }
  341. let shadow = match found {
  342. Some(s) => s.clone(),
  343. None => crate::shadow::find(from as u64, (to - from) as u64).ok_or("no host copy of it")?,
  344. };
  345. let (start, len) = shadow.span();
  346. if shadow.in_place() || (from as u64) < start || to as u64 > start + len {
  347. return Err("no host copy holds all of it");
  348. }
  349. Ok(shadow)
  350. }
  351. /// Whether every page of `[from, to)` can be read (through the kernel:
  352. /// asking Windows walks the page tables, milliseconds in the title's heap).
  353. fn mapped(from: usize, to: usize) -> bool {
  354. let mut bytes = vec![0u8; to - from];
  355. read_into(from as *const u8, &mut bytes)
  356. }
  357. /// A step done on the card.
  358. struct Op {
  359. from: (Arc<Shadow>, usize),
  360. len: usize,
  361. /// Its place in the buffer between.
  362. at: u64,
  363. level: u32,
  364. to: To,
  365. }
  366. enum To {
  367. /// A host copy, and the title address.
  368. Copy(Arc<Shadow>, usize),
  369. /// A descriptor slot (title heap, slot).
  370. Slot(usize, u32),
  371. /// A buffer's beginning.
  372. Buffer(ID3D12Resource),
  373. }
  374. /// Records a level of what [`stage`] describes into `list` (open): `reads`
  375. /// are copied into `between` (source, offset in it, offset in `between`,
  376. /// bytes), then `writes` out of it (destination, offset in it, offset in
  377. /// `between`, bytes). `between` is left readable as constants (and must be
  378. /// so, unless this is the `first` level), the others in the common state,
  379. /// as the submission's lists expect them.
  380. fn record(
  381. first: bool,
  382. list: &ID3D12GraphicsCommandList,
  383. between: &ID3D12Resource,
  384. reads: &[(&ID3D12Resource, u64, u64, u64)],
  385. writes: &[(&ID3D12Resource, u64, u64, u64)],
  386. ) {
  387. let common = D3D12_RESOURCE_STATE_COMMON;
  388. let (source, dest) = (D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST);
  389. let mut sources: Vec<&ID3D12Resource> = Vec::new();
  390. let mut dests: Vec<&ID3D12Resource> = Vec::new();
  391. for (all, list) in [(reads, &mut sources), (writes, &mut dests)] {
  392. for &(buffer, ..) in all {
  393. if !list.iter().any(|b| b.as_raw() == buffer.as_raw()) {
  394. list.push(buffer);
  395. }
  396. }
  397. }
  398. let both = |b: &ID3D12Resource| dests.iter().any(|d| d.as_raw() == b.as_raw());
  399. let constants = source | D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
  400. let mut barriers = vec![transition(between, dest, constants)];
  401. barriers.extend(sources.iter().map(|b| transition(b, source, if both(b) { dest } else { common })));
  402. let done: Vec<D3D12_RESOURCE_BARRIER> = dests.iter().map(|b| transition(b, dest, common)).collect();
  403. // SAFETY: an open list; live buffers, and the callers' ranges lie in
  404. // them. The buffers start in the common state (the list is the first of
  405. // its call) and are promoted by their first use.
  406. unsafe {
  407. if first {
  408. // What earlier lists' shaders wrote, first.
  409. list.ResourceBarrier(&[D3D12_RESOURCE_BARRIER {
  410. Type: D3D12_RESOURCE_BARRIER_TYPE_UAV,
  411. Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
  412. Anonymous: D3D12_RESOURCE_BARRIER_0 {
  413. UAV: std::mem::ManuallyDrop::new(D3D12_RESOURCE_UAV_BARRIER {
  414. pResource: std::mem::ManuallyDrop::new(None),
  415. }),
  416. },
  417. }]);
  418. } else {
  419. list.ResourceBarrier(&[transition(between, constants, dest)]);
  420. }
  421. for &(buffer, offset, at, len) in reads {
  422. list.CopyBufferRegion(between, at, buffer, offset, len);
  423. }
  424. list.ResourceBarrier(&barriers);
  425. for &(buffer, offset, at, len) in writes {
  426. list.CopyBufferRegion(buffer, offset, between, at, len);
  427. }
  428. if !done.is_empty() {
  429. list.ResourceBarrier(&done);
  430. }
  431. }
  432. }
  433. /// The list in front of a submission's, and its buffer ([`BETWEEN`] bytes).
  434. struct Own {
  435. list: HostList,
  436. between: ID3D12Resource,
  437. }
  438. // SAFETY: D3D12 objects are free-threaded, and the list is touched by one
  439. // thread at a time (the submitting one until it is sent, then the one that
  440. // lands it, then nobody until it is taken out of `POOL`).
  441. unsafe impl Send for Own {}
  442. /// Those that have landed: closed, their steps dropped.
  443. static POOL: Mutex<Vec<Own>> = Mutex::new(Vec::new());
  444. /// Since the last frame-rate line: fills and copies done on the card, their
  445. /// bytes, and submissions that waited instead, refused by a check.
  446. static DONE: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  447. /// What [`Host::card_steps`] took off a submission: the list that does it,
  448. /// for the submission to run first, and the steps the CPU leaves out (their
  449. /// list by address, their place in it).
  450. pub(super) struct Taken {
  451. own: Own,
  452. steps: std::collections::HashSet<(usize, usize)>,
  453. copied: Vec<(Arc<Shadow>, usize, usize)>,
  454. }
  455. impl Taken {
  456. pub(super) fn list(&self) -> &HostList {
  457. &self.own.list
  458. }
  459. /// Whether step `i` of `list` is done by this.
  460. pub(super) fn takes(&self, list: &HostList, i: usize) -> bool {
  461. self.steps.contains(&(std::ptr::from_ref(list) as usize, i))
  462. }
  463. fn copied(&self) -> impl Iterator<Item = Writer> {
  464. self.copied.iter().map(|(shadow, from, to)| Writer {
  465. shadow: Some(shadow.clone()),
  466. from: *from,
  467. to: *to,
  468. copy: true,
  469. })
  470. }
  471. /// The submission has run and landed: the list and its buffer are free.
  472. pub(super) fn landed(self) {
  473. // The host copies its steps held go; its commands stay until the
  474. // next use resets it.
  475. drop(std::mem::take(&mut *self.own.list.deferred()));
  476. POOL.lock().unwrap_or_else(|e| e.into_inner()).push(self.own);
  477. }
  478. }
  479. impl Host {
  480. /// With flights in the air: if what keeps `runs` from being prepared
  481. /// now is reads of title memory that can all be done on the card
  482. /// ([`stage`]), the list that does them. `None` if nothing is in the
  483. /// way or the old wait is due. Under the submission lock.
  484. pub(super) fn card_steps(&self, runs: &[&HostList]) -> Option<Taken> {
  485. if stage() == 0 || !relay_exact() {
  486. return None;
  487. }
  488. let (written, copies) = {
  489. let line = line();
  490. if line.written.is_empty() {
  491. return None;
  492. }
  493. (line.written.clone(), copies(&line))
  494. };
  495. blocked_by(&written, runs, false)?;
  496. let taken = if copied_read(&copies, runs) {
  497. Err("a copy done on the card is read through another host copy")
  498. } else {
  499. self.take_steps(&written, runs)
  500. };
  501. match taken {
  502. Ok(taken) => taken,
  503. Err(why) => {
  504. DONE[3].fetch_add(1, Ordering::Relaxed);
  505. #[cfg(feature = "diagnostics")]
  506. refused(why);
  507. let _ = why;
  508. None
  509. }
  510. }
  511. }
  512. fn take_steps(&self, written: &[(usize, usize)], runs: &[&HostList]) -> Result<Option<Taken>, &'static str> {
  513. let mut does = Vec::new();
  514. // Where the fills' bytes go.
  515. let mut fills = std::collections::HashMap::new();
  516. // Which step each is. One list's lock at a time: a submission may
  517. // name a list twice.
  518. let mut steps = Vec::new();
  519. for list in runs {
  520. for (i, step) in list.deferred().copies.iter().enumerate() {
  521. does.push(match step {
  522. &Step::Copy(dst, src, len) => Does::Copy {
  523. dst,
  524. src,
  525. len,
  526. asked: copy_blocked(written, dst, src, len).is_some(),
  527. },
  528. Step::Fill(_, src, len, to) => Does::Fill {
  529. src: *src,
  530. len: *len,
  531. asked: read_blocked(written, *src, *len),
  532. to: {
  533. if let Some(to) = to {
  534. fills.insert(does.len(), to.clone());
  535. }
  536. to.is_some()
  537. },
  538. },
  539. Step::Texture(staging) => {
  540. let (at, len) = staging.memory();
  541. Does::Read {
  542. from: at,
  543. to: at + len,
  544. asked: touches(written, at, at + len),
  545. }
  546. }
  547. &Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
  548. Step::Refresh(shadow, at, len) => Does::Refresh {
  549. shadow: Arc::as_ptr(shadow) as usize,
  550. from: *at,
  551. to: *at + *len,
  552. },
  553. Step::Run(_) => Does::Run,
  554. Step::Placed(p) => Does::Placed { dst: p.dst, src: p.src, len: p.len },
  555. Step::GpuWrite(..) | Step::Host(..) => continue,
  556. });
  557. steps.push((std::ptr::from_ref::<HostList>(list) as usize, i));
  558. }
  559. }
  560. let chosen = plan(&does, stage())?;
  561. if chosen.is_empty() {
  562. return Ok(None);
  563. }
  564. let mut writers = {
  565. let line = line();
  566. let mut all = writers(&line.line);
  567. all.extend(line.landing.iter().map(|w| Writer {
  568. shadow: w.shadow.clone(),
  569. ..*w
  570. }));
  571. all
  572. };
  573. let mut ops: Vec<Op> = Vec::with_capacity(chosen.len());
  574. // The places read (host copy, address, bytes, level): where in the
  575. // buffer between their bytes are.
  576. let mut places = std::collections::HashMap::new();
  577. let mut end = 0u64;
  578. for &(i, level) in &chosen {
  579. let Some(((src, _), (dst, _))) = reads_writes(&does[i]) else {
  580. continue;
  581. };
  582. let (Does::Copy { len, .. } | Does::Fill { len, .. }) = does[i] else {
  583. continue;
  584. };
  585. if len == 0 {
  586. return Err("nothing to read");
  587. }
  588. let from = holder(&writers, src, src + len)?;
  589. let place = (Arc::as_ptr(&from) as usize, src, len, level);
  590. let at = match places.get(&place) {
  591. Some(&at) => at,
  592. None => {
  593. if end + len as u64 > BETWEEN {
  594. return Err("too much at once");
  595. }
  596. if !mapped(src, src + len) {
  597. return Err("not all of what it reads is mapped");
  598. }
  599. let at = end;
  600. end = (end + len as u64).next_multiple_of(256);
  601. places.insert(place, at);
  602. at
  603. }
  604. };
  605. let to = match does[i] {
  606. Does::Copy { .. } => {
  607. let to = holder(&writers, dst, dst + len)?;
  608. if elsewhere(&does, Arc::as_ptr(&to) as usize, dst, dst + len) {
  609. return Err("another host copy of what it writes is read");
  610. }
  611. if !mapped(dst, dst + len) {
  612. return Err("not all of what it writes is mapped");
  613. }
  614. // What the steps behind it read of it is in that host
  615. // copy, or nowhere.
  616. writers.push(Writer {
  617. shadow: Some(to.clone()),
  618. from: dst,
  619. to: dst + len,
  620. copy: true,
  621. });
  622. To::Copy(to, dst)
  623. }
  624. _ => match fills.get(&i) {
  625. Some(FillTo::Slot(heap, index)) => To::Slot(*heap, *index),
  626. Some(FillTo::Buffer(buffer)) => To::Buffer(buffer.clone()),
  627. None => continue,
  628. },
  629. };
  630. ops.push(Op {
  631. from: (from, src),
  632. len,
  633. at,
  634. level,
  635. to,
  636. });
  637. }
  638. let Some(own) = self.own_list() else {
  639. return Err("no host list or buffer for it");
  640. };
  641. // First every refresh, then the writes: the bytes compared with are
  642. // the title's.
  643. for op in &ops {
  644. op.from.0.refresh(&own.list, op.from.1 as u64, op.len as u64);
  645. if let To::Copy(to, dst) = &op.to {
  646. to.refresh(&own.list, *dst as u64, op.len as u64);
  647. }
  648. }
  649. let mut copied = Vec::new();
  650. for op in &ops {
  651. if let To::Copy(to, dst) = &op.to {
  652. to.gpu_writes(&own.list, *dst as u64, op.len as u64);
  653. copied.push((to.clone(), *dst, *dst + op.len));
  654. }
  655. }
  656. #[cfg(feature = "diagnostics")]
  657. own.list.note_op(|| format!("{} copies of title memory done on the card, {end} bytes (VICTORY_CARD_STEPS)", ops.len()));
  658. let levels = ops.iter().map(|op| op.level).max().unwrap_or(0);
  659. for level in 0..=levels {
  660. let mut reads = Vec::new();
  661. let mut writes = Vec::new();
  662. for op in ops.iter().filter(|op| op.level == level) {
  663. let len = op.len as u64;
  664. let read = (&op.from.0.buffer, op.from.0.offset(op.from.1 as u64), op.at, len);
  665. // (Each place once.)
  666. if places.remove(&(Arc::as_ptr(&op.from.0) as usize, op.from.1, op.len, level)).is_some() {
  667. reads.push(read);
  668. }
  669. match &op.to {
  670. To::Copy(to, dst) => writes.push((&to.buffer, to.offset(*dst as u64), op.at, len)),
  671. To::Buffer(buffer) => writes.push((buffer, 0, op.at, len)),
  672. To::Slot(..) => {}
  673. }
  674. }
  675. record(level == 0, &own.list.list, &own.between, &reads, &writes);
  676. }
  677. own.list.close();
  678. // SAFETY: a live buffer.
  679. let gpu = unsafe { own.between.GetGPUVirtualAddress() };
  680. for op in &ops {
  681. DONE[2].fetch_add(op.len as u64, Ordering::Relaxed);
  682. match &op.to {
  683. To::Slot(heap, index) => {
  684. DONE[0].fetch_add(1, Ordering::Relaxed);
  685. // (A heap that is gone: nothing can read the slot.)
  686. crate::descriptor::constant_slot(*heap, *index, &own.between, gpu + op.at, op.len as u32);
  687. }
  688. To::Buffer(_) => {
  689. DONE[0].fetch_add(1, Ordering::Relaxed);
  690. }
  691. To::Copy(..) => {
  692. DONE[1].fetch_add(1, Ordering::Relaxed);
  693. }
  694. }
  695. #[cfg(feature = "diagnostics")]
  696. noted(op);
  697. }
  698. Ok(Some(Taken {
  699. own,
  700. steps: chosen.iter().map(|&(i, _)| steps[i]).collect(),
  701. copied,
  702. }))
  703. }
  704. /// A list of ours open for recording, and its buffer.
  705. fn own_list(&self) -> Option<Own> {
  706. let pooled = POOL.lock().unwrap_or_else(|e| e.into_inner()).pop();
  707. if let Some(own) = pooled {
  708. own.list.reset();
  709. return Some(own);
  710. }
  711. let between = self.uav_buffer(BETWEEN)?;
  712. name(&between, || "copies of title memory on the card".into());
  713. let list = self.new_list().ok()?;
  714. Some(Own { list, between })
  715. }
  716. }
  717. /// Diagnostics: the copies and fills done on the card since the last
  718. /// frame-rate line, by bytes, host copy read and host copy written (start
  719. /// and length; zeros for a fill): how many, and the last title addresses.
  720. #[cfg(feature = "diagnostics")]
  721. type Noted = std::collections::HashMap<(usize, (u64, u64), (u64, u64)), (u64, usize, usize)>;
  722. #[cfg(feature = "diagnostics")]
  723. static NOTED: Mutex<Option<Noted>> = Mutex::new(None);
  724. #[cfg(feature = "diagnostics")]
  725. fn noted(op: &Op) {
  726. let (to, dst) = match &op.to {
  727. To::Copy(to, dst) => (to.span(), *dst),
  728. To::Slot(..) | To::Buffer(_) => ((0, 0), 0),
  729. };
  730. let mut noted = NOTED.lock().unwrap_or_else(|e| e.into_inner());
  731. let e = noted.get_or_insert_with(Default::default).entry((op.len, op.from.0.span(), to)).or_default();
  732. *e = (e.0 + 1, op.from.1, dst);
  733. }
  734. /// For the frame-rate line.
  735. pub(super) fn log(frames: f64) {
  736. if stage() == 0 {
  737. return;
  738. }
  739. let d: Vec<f64> = DONE.iter().map(|d| d.swap(0, Ordering::Relaxed) as f64 / frames).collect();
  740. tracing::info!(
  741. "steps done on the card instead of waiting for flights, per frame (VICTORY_CARD_STEPS={}): {:.2} fills, {:.2} buffer \
  742. copies, {:.1} KB; {:.2} submissions refused and waited",
  743. stage(),
  744. d[0],
  745. d[1],
  746. d[2] / 1024.0,
  747. d[3],
  748. );
  749. #[cfg(feature = "diagnostics")]
  750. {
  751. let noted = NOTED.lock().unwrap_or_else(|e| e.into_inner()).take().unwrap_or_default();
  752. let mut noted: Vec<_> = noted.into_iter().collect();
  753. noted.sort_unstable_by_key(|(_, e)| std::cmp::Reverse(e.0));
  754. for ((len, from, to), (n, src, dst)) in noted.into_iter().take(5) {
  755. let n = n as f64 / frames;
  756. if to.1 == 0 {
  757. tracing::info!("done on the card, per frame: {n:.2} fills of {len:#x} bytes from the host copy of {:#x}+{:#x} (last {src:#x})", from.0, from.1);
  758. } else {
  759. tracing::info!(
  760. "done on the card, per frame: {n:.2} copies of {len:#x} bytes from the host copy of {:#x}+{:#x} (last {src:#x}) \
  761. to that of {:#x}+{:#x} (last {dst:#x})",
  762. from.0,
  763. from.1,
  764. to.0,
  765. to.1
  766. );
  767. }
  768. }
  769. }
  770. }
  771. #[cfg(test)]
  772. mod tests {
  773. use super::*;
  774. fn copy(dst: usize, src: usize, len: usize, asked: bool) -> Does {
  775. Does::Copy { dst, src, len, asked }
  776. }
  777. fn fill(src: usize, len: usize, asked: bool) -> Does {
  778. Does::Fill { src, len, asked, to: true }
  779. }
  780. fn stuck(src: usize, len: usize) -> Does {
  781. Does::Fill { src, len, asked: false, to: false }
  782. }
  783. /// What is done on the card, as (place, level), in stage 2.
  784. fn planned(does: &[Does]) -> Vec<(usize, u32)> {
  785. plan(does, 2).unwrap()
  786. }
  787. /// Only what is asked for is taken, all of it, and a step that stands
  788. /// in none of their ways stays where it is.
  789. #[test]
  790. fn steps_apart_from_one_another_are_taken() {
  791. let does = [
  792. copy(1000, 5000, 100, false),
  793. fill(2000, 64, true),
  794. Does::Refresh { shadow: 1, from: 0, to: 9000 },
  795. copy(3000, 6000, 100, true),
  796. fill(1000, 64, false),
  797. Does::Read { from: 3100, to: 4000, asked: false },
  798. stuck(3100, 5),
  799. ];
  800. assert_eq!(planned(&does), [(1, 0), (3, 0)]);
  801. // Two fills of the same bytes.
  802. assert_eq!(plan(&[fill(0, 64, true), fill(32, 64, true)], 1), Ok(vec![(0, 0), (1, 0)]));
  803. assert_eq!(plan(&[fill(0, 64, false)], 1), Ok(vec![]));
  804. // Ends that touch are apart.
  805. let does = [
  806. copy(1000, 5000, 100, true),
  807. copy(900, 9000, 100, false),
  808. copy(1100, 9000, 5, false),
  809. copy(4900, 9000, 100, false),
  810. ];
  811. assert_eq!(planned(&does), [(0, 0)]);
  812. }
  813. /// What depends on a taken step, or it on it, is taken too, on the level
  814. /// the order of the steps asks for.
  815. #[test]
  816. fn steps_that_depend_on_one_another_are_taken_in_order() {
  817. let taken = copy(1000, 5000, 100, true);
  818. // Reads what it writes, behind and ahead of it.
  819. assert_eq!(planned(&[taken, fill(1099, 64, false)]), [(0, 0), (1, 1)]);
  820. assert_eq!(planned(&[fill(1099, 64, false), taken]), [(0, 0), (1, 1)]);
  821. assert_eq!(planned(&[taken, copy(7000, 1050, 10, false)]), [(0, 0), (1, 1)]);
  822. // Writes what it reads, and what it writes.
  823. assert_eq!(planned(&[copy(5099, 9000, 1, false), taken]), [(0, 0), (1, 1)]);
  824. assert_eq!(planned(&[taken, copy(5099, 9000, 1, false)]), [(0, 0), (1, 1)]);
  825. assert_eq!(planned(&[taken, copy(999, 9000, 2, false)]), [(0, 0), (1, 1)]);
  826. // The same list twice.
  827. assert_eq!(planned(&[taken, taken]), [(0, 0), (1, 1)]);
  828. // A chain, with steps apart from it in between, and two fills of one
  829. // copy on one level.
  830. let does = [
  831. copy(8000, 7000, 50, false),
  832. taken,
  833. copy(2000, 1010, 20, false),
  834. fill(90_000, 10, false),
  835. fill(2000, 20, false),
  836. fill(2010, 20, true),
  837. copy(1000, 2005, 5, false),
  838. fill(1000, 100, false),
  839. ];
  840. assert_eq!(planned(&does), [(1, 0), (2, 1), (4, 2), (5, 2), (6, 2), (7, 3)]);
  841. // A fill is in nobody's way.
  842. assert_eq!(planned(&[taken, fill(5000, 100, false)]), [(0, 0)]);
  843. // A copy ahead that a taken one only shares its source with.
  844. assert_eq!(planned(&[copy(7000, 5000, 10, false), taken]), [(1, 0)]);
  845. }
  846. /// Whatever the steps, done level by level (in a level every read
  847. /// before every write) they read and leave what they read and leave one
  848. /// after the other, the CPU's steps ahead of all of them.
  849. #[test]
  850. fn levels_do_what_the_order_does() {
  851. let mut seed = 12345u32;
  852. let mut random = move |n: u32| {
  853. seed = seed.wrapping_mul(1_103_515_245).wrapping_add(12345);
  854. (seed >> 16) % n
  855. };
  856. let (mut done, mut refused) = (0, 0);
  857. for _ in 0..4000 {
  858. let does: Vec<Does> = (0..2 + random(9))
  859. .map(|_| {
  860. let (at, other, len) = (random(60) as usize, random(60) as usize, 1 + random(8) as usize);
  861. let asked = random(4) == 0;
  862. match random(8) {
  863. 0..4 => copy(at, other, len, asked),
  864. 4..6 => fill(at, len, asked),
  865. 6 => stuck(at, len),
  866. _ => Does::Read { from: at, to: at + len, asked: false },
  867. }
  868. })
  869. .collect();
  870. let Ok(chosen) = plan(&does, 2) else {
  871. refused += 1;
  872. continue;
  873. };
  874. done += 1;
  875. let start: Vec<u32> = (0..80).collect();
  876. // One after the other: what each reads, and what is left.
  877. let mut memory = start.clone();
  878. let mut wanted = Vec::new();
  879. for d in &does {
  880. let (from, to) = match *d {
  881. Does::Read { from, to, .. } => (from, to),
  882. _ => reads_writes(d).unwrap().0,
  883. };
  884. wanted.push(memory[from..to].to_vec());
  885. if let Does::Copy { dst, src, len, .. } = *d {
  886. memory.copy_within(src..src + len, dst);
  887. }
  888. }
  889. // The CPU's, then the card's.
  890. let mut cpu = start.clone();
  891. let taken = |i: usize| chosen.iter().any(|c| c.0 == i);
  892. for (i, d) in does.iter().enumerate().filter(|&(i, _)| !taken(i)) {
  893. let (from, to) = match *d {
  894. Does::Read { from, to, .. } => (from, to),
  895. _ => reads_writes(d).unwrap().0,
  896. };
  897. assert_eq!(cpu[from..to], wanted[i][..], "step {i} of {does:?}");
  898. if let Does::Copy { dst, src, len, .. } = *d {
  899. cpu.copy_within(src..src + len, dst);
  900. }
  901. }
  902. let mut card = cpu.clone();
  903. for level in 0..=chosen.iter().map(|c| c.1).max().unwrap_or(0) {
  904. let of: Vec<usize> = chosen.iter().filter(|c| c.1 == level).map(|c| c.0).collect();
  905. let before = card.clone();
  906. for i in of {
  907. let ((from, to), (dst, _)) = reads_writes(&does[i]).unwrap();
  908. assert_eq!(before[from..to], wanted[i][..], "step {i} of {does:?}: {chosen:?}");
  909. if matches!(does[i], Does::Copy { .. }) {
  910. card[dst..dst + to - from].copy_from_slice(&before[from..to]);
  911. }
  912. }
  913. }
  914. assert_eq!(card, memory, "{does:?}: {chosen:?}");
  915. }
  916. assert!(done > 500 && refused > 100, "{done} {refused}");
  917. }
  918. /// What cannot be done on the card refuses the lot, where it stands in
  919. /// the way.
  920. #[test]
  921. fn steps_in_the_way_are_refused() {
  922. let taken = copy(1000, 5000, 100, true);
  923. assert!(plan(&[taken, Does::Run], 2).is_err());
  924. // A texture that itself waits for flights; a fill that cannot be
  925. // taken but waits.
  926. assert!(plan(&[taken, Does::Read { from: 1, to: 2, asked: true }], 2).is_err());
  927. assert!(plan(&[Does::Fill { src: 1, len: 1, asked: true, to: false }], 2).is_err());
  928. // Reads on the CPU of what it writes: behind it, not ahead of it.
  929. for read in [Does::Read { from: 900, to: 1001, asked: false }, stuck(1050, 3)] {
  930. assert!(plan(&[taken, read], 2).is_err(), "{read:?} behind");
  931. assert_eq!(planned(&[read, taken]), [(1, 0)], "{read:?} ahead");
  932. }
  933. // Also of what is taken along.
  934. assert!(plan(&[taken, copy(3000, 1000, 10, false), stuck(3005, 1)], 2).is_err());
  935. // Into itself, and copies without stage 2.
  936. assert!(plan(&[copy(1000, 1050, 100, true)], 2).is_err());
  937. assert!(plan(&[taken], 1).is_err());
  938. assert!(plan(&[fill(1000, 4, true), copy(1000, 5000, 100, false)], 1).is_err());
  939. }
  940. #[test]
  941. fn a_refresh_of_another_host_copy_is_seen() {
  942. let does = [Does::Refresh { shadow: 7, from: 100, to: 200 }];
  943. assert!(!elsewhere(&does, 7, 100, 200));
  944. assert!(elsewhere(&does, 8, 199, 300));
  945. assert!(!elsewhere(&does, 8, 200, 300));
  946. }
  947. /// A value written behind a flight, or a read-back, is in no host copy
  948. /// before it lands.
  949. #[test]
  950. fn what_no_host_copy_holds_is_refused() {
  951. let writers = [Writer { shadow: None, from: 100, to: 108, copy: false }];
  952. assert!(holder(&writers, 104, 120).is_err());
  953. }
  954. /// Reads are all before writes, between two buffers and within one, and
  955. /// the buffers are usable in the lists that follow in the same call.
  956. #[test]
  957. fn the_card_copies_what_is_recorded() {
  958. let Some(host) = host() else {
  959. return; // no host GPU
  960. };
  961. let (a, a_data) = host.shared_buffer(1 << 16).unwrap();
  962. let (b, b_data) = host.shared_buffer(1 << 16).unwrap();
  963. // SAFETY: mappings of 64 KiB.
  964. let (a_bytes, b_bytes) =
  965. unsafe { (std::slice::from_raw_parts_mut(a_data, 1 << 16), std::slice::from_raw_parts_mut(b_data, 1 << 16)) };
  966. for (i, (x, y)) in a_bytes.iter_mut().zip(b_bytes.iter_mut()).enumerate() {
  967. (*x, *y) = (i as u8 ^ (i >> 8) as u8, 0xee);
  968. }
  969. let was = a_bytes.to_vec();
  970. let own = host.own_list().unwrap();
  971. // Within `a` (there and back), from `a` to `b`, and a read alone.
  972. record(
  973. true,
  974. &own.list.list,
  975. &own.between,
  976. &[(&a, 33, 0, 100), (&a, 2000, 256, 100), (&a, 5001, 512, 7), (&a, 9, 1024, 4)],
  977. &[(&a, 2000, 0, 100), (&a, 33, 256, 100), (&b, 77, 512, 7)],
  978. );
  979. // A level behind it, of what it wrote.
  980. record(false, &own.list.list, &own.between, &[(&b, 77, 2048, 7)], &[(&b, 1077, 2048, 7)]);
  981. own.list.close();
  982. // A list behind it that uses the buffers in other ways.
  983. let next = host.new_list().unwrap();
  984. let (out, out_data) = host.shared_buffer(1 << 16).unwrap();
  985. // SAFETY: an open list; live buffers.
  986. unsafe {
  987. next.list.CopyBufferRegion(&out, 0, &own.between, 1024, 4);
  988. next.list.CopyBufferRegion(&b, 4096, &a, 33, 100);
  989. }
  990. next.close();
  991. host.execute(&[&own.list, &next]);
  992. // With the debug layer (`VICTORY_D3D12_DEBUG=1`, diagnostics).
  993. assert_eq!(host.log_messages(), None);
  994. assert_eq!(a_bytes[2000..2100], was[33..133]);
  995. assert_eq!(a_bytes[33..133], was[2000..2100]);
  996. assert_eq!(b_bytes[77..84], was[5001..5008]);
  997. assert_eq!(b_bytes[1077..1084], was[5001..5008]);
  998. assert_eq!(b_bytes[4096..4196], was[2000..2100]);
  999. // SAFETY: a mapping of 64 KiB.
  1000. assert_eq!(unsafe { std::slice::from_raw_parts(out_data, 4) }, &was[9..13]);
  1001. assert!(b_bytes[..77].iter().all(|&x| x == 0xee));
  1002. a_bytes[2000..2100].copy_from_slice(&was[2000..2100]);
  1003. a_bytes[33..133].copy_from_slice(&was[33..133]);
  1004. assert_eq!(a_bytes, &was[..]);
  1005. // As the landing does: its next use records anew.
  1006. POOL.lock().unwrap().push(own);
  1007. let own = host.own_list().unwrap();
  1008. own.list.close();
  1009. }
  1010. /// The whole way, in a process of its own with the relay on:
  1011. /// `VICTORY_RELAY=2 VICTORY_CARD_STEPS=2 cargo test -p victory-gpu --lib
  1012. /// card_steps -- --ignored --test-threads=1`. A flight's list writes
  1013. /// part of what the next submission's copy reads, the title wrote the
  1014. /// rest; the copy is done on the card behind the flight, and a second
  1015. /// one reads what the first wrote. Title memory ends as on the CPU.
  1016. #[test]
  1017. #[ignore = "wants VICTORY_RELAY=2 VICTORY_CARD_STEPS=2 and a process of its own"]
  1018. fn a_copy_behind_a_flight_reads_what_the_flight_wrote() {
  1019. use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc};
  1020. const LEN: usize = 4 << 20;
  1021. // Without it (`TEST_UNWATCHED=1`) the title's bytes cannot be put in
  1022. // under a flight's writes: the flights that declared them are waited
  1023. // for.
  1024. let write_watch = if std::env::var_os("TEST_UNWATCHED").is_some() { 0 } else { 0x20_0000 };
  1025. let Some(host) = host() else {
  1026. return;
  1027. };
  1028. assert!(relay_exact() && stage() == 2, "set VICTORY_RELAY=2 VICTORY_CARD_STEPS=2");
  1029. // Two title buffers: in the first a copy within it, from it into the
  1030. // second, and back.
  1031. let (title, start) = {
  1032. // SAFETY: memory of our own, never freed.
  1033. let base = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | write_watch, PAGE_READWRITE) }.cast::<u8>();
  1034. assert!(!base.is_null());
  1035. // SAFETY: `LEN` bytes just committed.
  1036. (unsafe { std::slice::from_raw_parts_mut(base, LEN) }, base as usize)
  1037. };
  1038. const HALF: usize = LEN / 2;
  1039. crate::shadow::register(0x1111, start as u64, HALF as u64);
  1040. crate::shadow::register(0x2222, (start + HALF) as u64, HALF as u64);
  1041. let first = crate::shadow::find(start as u64, 64).unwrap();
  1042. let (slow_from, slow_to) = (host.uav_buffer(64 << 20).unwrap(), host.uav_buffer(64 << 20).unwrap());
  1043. let before = DONE[1].load(Ordering::Relaxed);
  1044. let mut lists = Vec::new();
  1045. for round in 0..8usize {
  1046. // The title writes; then a "shader" of a flight writes 300 bytes
  1047. // of what the copy reads, behind some work.
  1048. let seed = |i: usize| (i * 7 + round * 13 + i / 251) as u8;
  1049. for (i, b) in title[4000..6000].iter_mut().enumerate() {
  1050. *b = seed(i);
  1051. }
  1052. let (upload, data) = host.upload_buffer(4096).unwrap();
  1053. for i in 0..300 {
  1054. // SAFETY: inside the mapping.
  1055. unsafe { data.add(i).write(0x80 | (round * 31 + i) as u8) };
  1056. }
  1057. let a = host.new_list().unwrap();
  1058. first.refresh(&a, start as u64, HALF as u64);
  1059. first.gpu_writes(&a, start as u64, HALF as u64);
  1060. // SAFETY: an open list; live buffers.
  1061. unsafe {
  1062. for _ in 0..24 {
  1063. a.list.CopyBufferRegion(&slow_to, 0, &slow_from, 0, 64 << 20);
  1064. }
  1065. a.list.CopyBufferRegion(&first.buffer, 4500, &upload, 0, 300);
  1066. a.list
  1067. .ResourceBarrier(&[transition(&first.buffer, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON)]);
  1068. }
  1069. a.close();
  1070. host.execute_own(&a);
  1071. // With the flight in the air, beside what it writes.
  1072. for (i, b) in title[5300..5400].iter_mut().enumerate() {
  1073. *b = seed(1300 + i) ^ 0x5c;
  1074. }
  1075. // Thousands of runs of bytes of its own.
  1076. for b in title[1_700_000..1_708_000].iter_mut().step_by(2) {
  1077. *b = 1 + round as u8;
  1078. }
  1079. // Into the second buffer, and within the first.
  1080. let b = host.new_list().unwrap();
  1081. b.defer_copy((start + HALF + 100) as *mut u8, (start + 4001) as *const u8, 1500);
  1082. b.defer_copy((start + 900_001) as *mut u8, (start + 4400) as *const u8, 777);
  1083. b.defer_copy((start + HALF + 10_000) as *mut u8, (start + 1_700_000) as *const u8, 8000);
  1084. // What depends on them: a copy of the first copy, upload memory
  1085. // filled from that, and the first one's bytes copied over.
  1086. b.defer_copy((start + 1_500_000) as *mut u8, (start + HALF + 600) as *const u8, 700);
  1087. let (staging, staged) = b.upload(host, 4096).unwrap();
  1088. b.defer_fill_buffer(&staging, staged, (start + 1_500_100) as *const u8, 500);
  1089. b.defer_copy((start + HALF + 300) as *mut u8, (start + 8000) as *const u8, 64);
  1090. b.close();
  1091. host.execute_own(&b);
  1092. // What the first wrote, read by the next submission.
  1093. let c = host.new_list().unwrap();
  1094. c.defer_copy((start + 1_200_000) as *mut u8, (start + HALF + 100) as *const u8, 1500);
  1095. c.close();
  1096. let number = host.execute_own(&c);
  1097. settle_now(WHY_SYNC);
  1098. assert!(FINISHED.load(Ordering::Acquire) >= number);
  1099. let wanted: Vec<u8> = (0..2000)
  1100. .map(|i| match i {
  1101. 500..800 => 0x80 | (round * 31 + i - 500) as u8,
  1102. 1300..1400 => seed(i) ^ 0x5c,
  1103. _ => seed(i),
  1104. })
  1105. .collect();
  1106. assert!(title[4000..6000] == wanted[..], "what the flight wrote, round {round}");
  1107. // (The copy over the first one's bytes came last.)
  1108. let mut over = wanted[1..1501].to_vec();
  1109. over[200..264].fill(0);
  1110. assert!(title[HALF + 100..HALF + 1600] == over[..], "the copy to the other buffer, round {round}");
  1111. assert!(title[1_500_000..1_500_700] == wanted[501..1201], "the copy behind a copy, round {round}");
  1112. // SAFETY: the mapping, which the flight wrote and has landed.
  1113. let staged = unsafe { std::slice::from_raw_parts(staged, 500) };
  1114. assert!(staged == &wanted[601..1101], "the fill behind it, round {round}");
  1115. assert!(title[900_001..900_778] == wanted[400..1177], "the copy within the buffer, round {round}");
  1116. assert!(title[1_200_000..1_201_500] == over[..], "the copy of the copy, round {round}");
  1117. assert!(title[HALF..HALF + 100].iter().all(|&x| x == 0));
  1118. assert!(title[HALF + 1600..HALF + 10_000].iter().all(|&x| x == 0));
  1119. assert!(title[HALF + 18_000..].iter().all(|&x| x == 0));
  1120. let runs = &title[HALF + 10_000..HALF + 18_000];
  1121. assert!(runs.chunks(2).all(|b| b == [1 + round as u8, 0]), "the runs, round {round}");
  1122. a.keep(&upload);
  1123. lists.extend([a, b, c]);
  1124. }
  1125. assert_eq!(host.log_messages(), None);
  1126. let done = DONE[1].load(Ordering::Relaxed) - before;
  1127. eprintln!("{done} of 48 copies were done on the card, {} submissions waited", DONE[3].load(Ordering::Relaxed));
  1128. eprintln!("settles for title memory under shader writes: {}", LATE_STATS[WHY_STALE].load(Ordering::Relaxed));
  1129. assert!(done >= 20, "only {done} copies were done on the card");
  1130. }
  1131. }