diff --git a/README.md b/README.md index ed1955ec..10809e18 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,49 @@ Tested on one machine: Windows 11, Intel i7-14700KF, NVIDIA RTX 4070 12 GB, ### Newest (2026-11-25, later the same day) +**Update, 2026-11-25 afternoon: what a frame is made of, measured, and two +changes that hold.** First rooms, about 3,850 draws a frame: 104 ms a frame +(9.6 frames a second) with the set below, from about 120 ms in the +morning. Still far from the console's 33 ms. +- How the title paces itself (new meters in `fence.rs` and + `console_insn.rs`): it never asks for an event. Each frame begins with + one small submission and a signal, and a title thread then waits for + that fence value by reading it in memory with `monitorx` / `mwaitx` + (AMD-only: about 280,000 emulated exceptions a second on an Intel + processor, all from this wait). The value is set when the layer has + finished the whole frame before. So a frame is the time the layer needs + for one frame's burst of submissions plus about 20 ms of the title's + own; putting presents behind the line, or giving the title's threads + more processors, changes nothing (both measured). +- Two walls stand side by side and both are full: the layer's submit + thread (about 95 ms of a 120 ms frame in the morning) and the card + (about 102 ms busy, by a timestamp pair around every host list: + `cardmeter.rs`). Taking time off one alone moved the frame by 0 to 7 %. +- `VICTORY_JOIN_PARTS=1` (off by default): the title's lists wait for + memory values, which cut its ~15 submissions a frame into ~29 parts; + parts that follow one another now go to the host as one submission + (9 a frame), the same lists in the same order. About 6 %. +- `VICTORY_BACK_OWN_VIEW=1` (off by default): what shaders wrote goes + back into title view memory through a view of the layer's own, so the + copy that wrote it is not read in again. About 9 % (submit thread 93 -> + 81 ms a frame, 104 -> 80 MB a frame checked). A CORRECTION: an earlier + run seemed to show washed-out frames with this switch; the same frames + turn up in about 6 of 21 runs with no switch at all (cause not known), + and `VICTORY_BACK_OWN_CHECK=1` counted 0 stores gone astray in 1.36 + million. +- Where the card's time goes now (`VICTORY_CARD_METER_PIPELINES=1`, a + table by pipeline): no pass is large. About 82 ms of the title's lists + are spread over ~3,400 pipeline bindings a frame; ~2,400 of the + indirect commands still get a clamp pass of the layer's with draw + windows on (960 are compute dispatches; about 1,000 are mesh records + the title keeps scattered through a 100 MB argument buffer, which a + window of records at one step cannot serve). +- Measured and found to give nothing (switches left in, off): + `VICTORY_REFRESH_ONCE`, `VICTORY_ASYNC_PRESENT`, `VICTORY_VIEW_KNOWN`, + `VICTORY_SPREAD`, `VICTORY_QUEUE2=3`, `VICTORY_WINDOW_JUMP`. Each has an + `=alt` form (twenty seconds on, twenty off, each change said in the + log) so that one run measures both in the same scene. + **Update, the same night: the first room now renders right on the test machine** (walls, textures, people, lamps), at 190 to 450 ms a frame (2 to 5 frames a second): the picture work has caught up, the frame rate has not. diff --git a/apps/victory/src/main.rs b/apps/victory/src/main.rs index ead9f7c8..51b4b4c4 100644 --- a/apps/victory/src/main.rs +++ b/apps/victory/src/main.rs @@ -162,11 +162,17 @@ fn main() -> Result<()> { warm, } => { // `VICTORY_VIEW_LIMIT=`: translate as on a host whose view heap is capped - if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT").ok().and_then(|v| v.parse().ok()) { + if let Some(n) = std::env::var("VICTORY_VIEW_LIMIT") + .ok() + .and_then(|v| v.parse().ok()) + { victory_shader::emit::set_view_heap_limit(n); } // `VICTORY_HOST_WAVE=32`: translate as for a GPU whose waves are at most 32 lanes - if let Some(n) = std::env::var("VICTORY_HOST_WAVE").ok().and_then(|v| v.parse().ok()) { + if let Some(n) = std::env::var("VICTORY_HOST_WAVE") + .ok() + .and_then(|v| v.parse().ok()) + { victory_shader::emit::set_host_max_wave(n); } if let Some(file) = warm { diff --git a/apps/victory/src/translate.rs b/apps/victory/src/translate.rs index 2e12ae9c..c7b269ff 100644 --- a/apps/victory/src/translate.rs +++ b/apps/victory/src/translate.rs @@ -183,11 +183,17 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> } } } - anyhow::ensure!(!wanted.is_empty(), "no 16-digit shader hash in {}", file.display()); + anyhow::ensure!( + !wanted.is_empty(), + "no 16-digit shader hash in {}", + file.display() + ); } // `VICTORY_WARM_SECONDS=`: stop taking new shaders after n seconds // (what is done stays in the cache; the next warm-up goes on from there). - let limit = std::env::var("VICTORY_WARM_SECONDS").ok().and_then(|v| v.trim().parse::().ok()); + let limit = std::env::var("VICTORY_WARM_SECONDS") + .ok() + .and_then(|v| v.trim().parse::().ok()); let cfg = victory_core::Config::load()?; victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?); let paths = crate::default_paths(paths)?; @@ -196,7 +202,10 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> let done = Mutex::new(HashSet::new()); let counts = [const { AtomicUsize::new(0) }; 5]; for root in &paths { - for entry in walkdir::WalkDir::new(root).into_iter().filter_map(Result::ok) { + for entry in walkdir::WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + { // Past the deadline the workers break out at once: walking and // opening the rest of the assets would only scan for nothing. if limit.is_some_and(|n| began.elapsed().as_secs() >= n) { @@ -227,7 +236,10 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> } let n = counts[4].fetch_add(1, Ordering::Relaxed) + 1; if n.is_multiple_of(1000) { - println!("warm-up {n} shaders so far, {:.0} s", began.elapsed().as_secs_f64()); + println!( + "warm-up {n} shaders so far, {:.0} s", + began.elapsed().as_secs_f64() + ); } let which = match victory_hle::modules::d3d12x::warm_shader(&bytes) { Ok(true) => 0, @@ -242,8 +254,16 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> } } let [translated, there, failed] = [0, 1, 2].map(|i| counts[i].load(Ordering::Relaxed)); - let asked = if all { "all".to_owned() } else { wanted.len().to_string() }; - let stopped = if counts[3].load(Ordering::Relaxed) > 0 { " (stopped at the time limit)" } else { "" }; + let asked = if all { + "all".to_owned() + } else { + wanted.len().to_string() + }; + let stopped = if counts[3].load(Ordering::Relaxed) > 0 { + " (stopped at the time limit)" + } else { + "" + }; println!( "warm-up {asked} hashes asked, {} found: {translated} translated now, {there} in the cache already, {failed} do not translate; {:.1} s on {threads} threads{stopped}", translated + there + failed, @@ -252,6 +272,10 @@ pub fn warm(paths: Vec, file: &Path, jobs: Option) -> Result<()> Ok(()) } +/// `translate --warm `: the containers whose hash the file names are +/// translated into the run's shader cache, on `jobs` threads; nothing is +/// made on the GPU. A run of the title then finds them there instead of +/// translating each at its first use. pub fn run( paths: Vec, validate: bool, diff --git a/crates/victory-formats/src/xma.rs b/crates/victory-formats/src/xma.rs index e6ca9315..589c5edd 100644 --- a/crates/victory-formats/src/xma.rs +++ b/crates/victory-formats/src/xma.rs @@ -151,7 +151,8 @@ fn next_frame(data: &[u8], start: usize, end: usize) -> Option { let mut end = end; if end.is_multiple_of(PACKET_BITS) || (last && end / PACKET_BITS == index) { // The next frame begins in the next packet of this stream. - let next = (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; + let next = + (end - 1) / PACKET_BITS + 1 + packet(data, (end - 1) / PACKET_BITS)?.skip as usize; let header = packet(data, next)?; end = next * PACKET_BITS + HEADER_BITS + header.first_frame_bit as usize; } @@ -248,10 +249,20 @@ fn codes() -> &'static Codes { scale: pairs(&SCALE, -60), scale_rl: pairs(&SCALE_RL, 0), coef: [ - Vlc::new(COEF0_SYMS.iter().zip(COEF0_LENS).map(|(&s, l)| (s as i32, l))), + Vlc::new( + COEF0_SYMS + .iter() + .zip(COEF0_LENS) + .map(|(&s, l)| (s as i32, l)), + ), pairs(&COEF1, 0), ], - vec4: Vlc::new(VEC4_SYMS.iter().zip(VEC4_LENS).map(|(&s, l)| (s as i32 - 1, l))), + vec4: Vlc::new( + VEC4_SYMS + .iter() + .zip(VEC4_LENS) + .map(|(&s, l)| (s as i32 - 1, l)), + ), vec2: pairs(&VEC2, -1), vec1: pairs(&VEC1, 0), } @@ -757,7 +768,11 @@ impl Decoder { ch.scale_factors = target; if ch.reuse_sf { let from = ch.saved_scale_factors[ch.scale_factor_idx]; - for (sf, &offset) in ch.saved_scale_factors[target].iter_mut().zip(&sf_offsets).take(self.num_bands) { + for (sf, &offset) in ch.saved_scale_factors[target] + .iter_mut() + .zip(&sf_offsets) + .take(self.num_bands) + { *sf = from[offset]; } } @@ -890,7 +905,11 @@ impl Decoder { } quant += 31; } - quant_step += if negative { -(quant + step) } else { quant + step }; + quant_step += if negative { + -(quant + step) + } else { + quant + step + }; } if self.channels_for_cur_subframe == 1 { self.ch[self.channel_indexes[0]].quant_step = quant_step; @@ -933,13 +952,21 @@ impl Decoder { let sf = ch.saved_scale_factors[ch.scale_factors]; for band in 0..self.num_bands { let end = sfb[band + 1].min(subframe_len); - let exp = ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; + let exp = + ch.quant_step - (ch.max_scale_factor - sf[band]) * ch.scale_factor_step; let quant = 10f32.powf(exp as f32 / 20.0); - for (t, &c) in tmp[sfb[band]..end].iter_mut().zip(&ch.coeffs[sfb[band]..end]) { + for (t, &c) in tmp[sfb[band]..end] + .iter_mut() + .zip(&ch.coeffs[sfb[band]..end]) + { *t = c * quant; } } - imdct_half(&tmp[..subframe_len], &mut ch.out[at..at + subframe_len], scale); + imdct_half( + &tmp[..subframe_len], + &mut ch.out[at..at + subframe_len], + scale, + ); } } else { for i in 0..self.channels_for_cur_subframe { @@ -956,7 +983,10 @@ impl Decoder { start += (winlen - subframe_len) / 2; winlen = subframe_len; } - window_overlap(&mut ch.out[start..start + winlen], &windows()[log2(winlen) as usize - 7]); + window_overlap( + &mut ch.out[start..start + winlen], + &windows()[log2(winlen) as usize - 7], + ); ch.prev_block_len = subframe_len; } @@ -1057,7 +1087,9 @@ mod tests { -(input .iter() .enumerate() - .map(|(k, &x)| x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos()) + .map(|(k, &x)| { + x as f64 * (std::f64::consts::PI / n as f64 * t * (k as f64 + 0.5)).cos() + }) .sum::() as f32) }) .collect() @@ -1109,7 +1141,12 @@ mod tests { } } for i in n..5 * n { - assert!((out[i] - signal[i]).abs() < 1e-3, "{i}: {} vs {}", out[i], signal[i]); + assert!( + (out[i] - signal[i]).abs() < 1e-3, + "{i}: {} vs {}", + out[i], + signal[i] + ); } } diff --git a/crates/victory-formats/src/xma/tables.rs b/crates/victory-formats/src/xma/tables.rs index bf8fc43f..7a789933 100644 --- a/crates/victory-formats/src/xma/tables.rs +++ b/crates/victory-formats/src/xma/tables.rs @@ -4,407 +4,871 @@ //! (symbol, code length) in canonical code order. pub(super) const CRITICAL_FREQ: [u16; 28] = [ - 100, 200, 300, 400, 510, 630, 770, 920, - 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, - 3700, 4400, 5300, 6400, 7700, 9500, 12000, 15500, - 20675, 28575, 41375, 63875, + 100, 200, 300, 400, 510, 630, 770, 920, 1080, 1270, 1480, 1720, 2000, 2320, 2700, 3150, 3700, + 4400, 5300, 6400, 7700, 9500, 12000, 15500, 20675, 28575, 41375, 63875, ]; pub(super) const SCALE: [(u16, u8); 121] = [ - (58, 5), (64, 6), (66, 7), (65, 7), (62, 5), (63, 6), (68, 9), (69, 10), - (54, 15), (19, 19), (20, 19), (21, 19), (22, 19), (23, 19), (24, 19), (25, 19), - (26, 19), (27, 19), (28, 19), (29, 19), (30, 19), (31, 19), (32, 19), (33, 19), - (34, 19), (17, 19), (36, 19), (37, 19), (38, 19), (39, 19), (40, 19), (41, 19), - (42, 19), (43, 19), (44, 19), (45, 19), (46, 19), (47, 19), (48, 19), (49, 19), - (50, 19), (51, 19), (52, 19), (15, 19), (16, 19), (14, 19), (13, 19), (12, 19), - (11, 19), (10, 19), (0, 19), (9, 19), (8, 19), (7, 19), (6, 19), (5, 19), - (4, 19), (55, 13), (70, 13), (3, 19), (2, 19), (1, 19), (35, 19), (71, 19), - (72, 19), (73, 19), (74, 19), (75, 19), (76, 19), (77, 19), (78, 19), (79, 19), - (80, 19), (81, 19), (82, 19), (83, 19), (84, 19), (85, 19), (86, 19), (87, 19), - (88, 19), (89, 19), (90, 19), (91, 19), (92, 19), (93, 19), (94, 19), (95, 19), - (96, 19), (97, 19), (98, 19), (99, 19), (100, 19), (101, 19), (102, 19), (103, 19), - (104, 19), (105, 19), (106, 19), (107, 19), (108, 19), (109, 19), (110, 19), (111, 19), - (112, 19), (113, 19), (114, 19), (115, 19), (116, 19), (117, 19), (118, 19), (119, 19), - (120, 19), (18, 18), (53, 16), (56, 11), (57, 8), (67, 7), (61, 3), (59, 2), + (58, 5), + (64, 6), + (66, 7), + (65, 7), + (62, 5), + (63, 6), + (68, 9), + (69, 10), + (54, 15), + (19, 19), + (20, 19), + (21, 19), + (22, 19), + (23, 19), + (24, 19), + (25, 19), + (26, 19), + (27, 19), + (28, 19), + (29, 19), + (30, 19), + (31, 19), + (32, 19), + (33, 19), + (34, 19), + (17, 19), + (36, 19), + (37, 19), + (38, 19), + (39, 19), + (40, 19), + (41, 19), + (42, 19), + (43, 19), + (44, 19), + (45, 19), + (46, 19), + (47, 19), + (48, 19), + (49, 19), + (50, 19), + (51, 19), + (52, 19), + (15, 19), + (16, 19), + (14, 19), + (13, 19), + (12, 19), + (11, 19), + (10, 19), + (0, 19), + (9, 19), + (8, 19), + (7, 19), + (6, 19), + (5, 19), + (4, 19), + (55, 13), + (70, 13), + (3, 19), + (2, 19), + (1, 19), + (35, 19), + (71, 19), + (72, 19), + (73, 19), + (74, 19), + (75, 19), + (76, 19), + (77, 19), + (78, 19), + (79, 19), + (80, 19), + (81, 19), + (82, 19), + (83, 19), + (84, 19), + (85, 19), + (86, 19), + (87, 19), + (88, 19), + (89, 19), + (90, 19), + (91, 19), + (92, 19), + (93, 19), + (94, 19), + (95, 19), + (96, 19), + (97, 19), + (98, 19), + (99, 19), + (100, 19), + (101, 19), + (102, 19), + (103, 19), + (104, 19), + (105, 19), + (106, 19), + (107, 19), + (108, 19), + (109, 19), + (110, 19), + (111, 19), + (112, 19), + (113, 19), + (114, 19), + (115, 19), + (116, 19), + (117, 19), + (118, 19), + (119, 19), + (120, 19), + (18, 18), + (53, 16), + (56, 11), + (57, 8), + (67, 7), + (61, 3), + (59, 2), (60, 1), ]; pub(super) const SCALE_RL: [(u16, u8); 120] = [ - (103, 7), (80, 11), (60, 11), (18, 10), (56, 10), (21, 12), (90, 12), (58, 11), - (27, 11), (69, 12), (84, 15), (48, 15), (86, 14), (47, 13), (19, 10), (32, 9), - (78, 6), (5, 5), (28, 4), (53, 5), (9, 7), (31, 8), (38, 8), (10, 7), - (88, 11), (25, 12), (105, 12), (118, 11), (23, 12), (82, 14), (98, 16), (110, 16), - (108, 15), (93, 13), (68, 10), (72, 12), (97, 12), (81, 12), (42, 12), (64, 8), - (4, 4), (1, 2), (7, 6), (14, 7), (0, 9), (55, 9), (61, 9), (117, 10), - (24, 12), (44, 12), (67, 12), (70, 16), (99, 18), (96, 21), (95, 21), (2, 21), - (77, 21), (52, 21), (111, 21), (102, 20), (101, 17), (46, 15), (73, 15), (109, 15), - (51, 14), (92, 14), (30, 7), (11, 7), (66, 7), (15, 8), (16, 8), (116, 9), - (65, 9), (57, 10), (59, 10), (115, 9), (12, 7), (35, 9), (17, 9), (41, 9), - (20, 11), (91, 11), (26, 12), (75, 15), (45, 15), (107, 14), (83, 14), (100, 15), - (89, 15), (43, 11), (62, 9), (37, 9), (104, 8), (6, 5), (39, 8), (40, 9), - (34, 9), (79, 7), (8, 6), (63, 6), (87, 12), (94, 14), (49, 14), (50, 13), - (22, 11), (119, 10), (33, 9), (36, 9), (113, 11), (106, 12), (112, 13), (71, 15), - (85, 15), (74, 14), (76, 10), (114, 7), (29, 5), (54, 6), (13, 6), (3, 2), + (103, 7), + (80, 11), + (60, 11), + (18, 10), + (56, 10), + (21, 12), + (90, 12), + (58, 11), + (27, 11), + (69, 12), + (84, 15), + (48, 15), + (86, 14), + (47, 13), + (19, 10), + (32, 9), + (78, 6), + (5, 5), + (28, 4), + (53, 5), + (9, 7), + (31, 8), + (38, 8), + (10, 7), + (88, 11), + (25, 12), + (105, 12), + (118, 11), + (23, 12), + (82, 14), + (98, 16), + (110, 16), + (108, 15), + (93, 13), + (68, 10), + (72, 12), + (97, 12), + (81, 12), + (42, 12), + (64, 8), + (4, 4), + (1, 2), + (7, 6), + (14, 7), + (0, 9), + (55, 9), + (61, 9), + (117, 10), + (24, 12), + (44, 12), + (67, 12), + (70, 16), + (99, 18), + (96, 21), + (95, 21), + (2, 21), + (77, 21), + (52, 21), + (111, 21), + (102, 20), + (101, 17), + (46, 15), + (73, 15), + (109, 15), + (51, 14), + (92, 14), + (30, 7), + (11, 7), + (66, 7), + (15, 8), + (16, 8), + (116, 9), + (65, 9), + (57, 10), + (59, 10), + (115, 9), + (12, 7), + (35, 9), + (17, 9), + (41, 9), + (20, 11), + (91, 11), + (26, 12), + (75, 15), + (45, 15), + (107, 14), + (83, 14), + (100, 15), + (89, 15), + (43, 11), + (62, 9), + (37, 9), + (104, 8), + (6, 5), + (39, 8), + (40, 9), + (34, 9), + (79, 7), + (8, 6), + (63, 6), + (87, 12), + (94, 14), + (49, 14), + (50, 13), + (22, 11), + (119, 10), + (33, 9), + (36, 9), + (113, 11), + (106, 12), + (112, 13), + (71, 15), + (85, 15), + (74, 14), + (76, 10), + (114, 7), + (29, 5), + (54, 6), + (13, 6), + (3, 2), ]; pub(super) const SCALE_RL_RUN: [u8; 120] = [ - 0, 0, 0, 0, 1, 2, 3, 4, - 5, 6, 7, 8, 9, 10, 11, 12, - 13, 14, 15, 16, 17, 18, 19, 20, - 21, 22, 23, 24, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 10, 11, - 12, 13, 14, 15, 16, 17, 18, 19, - 20, 21, 22, 23, 24, 0, 1, 2, - 3, 4, 5, 6, 7, 8, 9, 10, - 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 0, 1, - 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 0, - 1, 2, 3, 4, 5, 6, 7, 8, - 9, 10, 0, 1, 0, 1, 0, 1, + 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, + 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 0, 1, 2, 3, + 4, 5, 6, 7, 8, 9, 10, 0, 1, 0, 1, 0, 1, ]; pub(super) const SCALE_RL_LEVEL: [u8; 120] = [ - 0, 0, 1, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 2, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, - 3, 3, 3, 3, 3, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 4, 4, - 4, 4, 4, 4, 4, 4, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5, 6, - 6, 6, 6, 6, 6, 6, 6, 6, - 6, 6, 7, 7, 8, 8, 9, 9, + 0, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, + 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, ]; pub(super) const COEF0_LENS: [u8; 272] = [ - 2, 9, 14, 14, 13, 12, 13, 14, - 15, 15, 12, 10, 10, 10, 13, 14, - 15, 15, 12, 11, 13, 14, 14, 13, - 15, 15, 14, 12, 12, 8, 10, 10, - 15, 15, 14, 13, 14, 14, 13, 15, - 20, 20, 19, 21, 21, 20, 19, 17, - 17, 18, 18, 15, 15, 13, 12, 14, - 15, 15, 14, 15, 15, 12, 11, 6, - 7, 8, 9, 13, 13, 13, 14, 14, - 11, 10, 7, 8, 14, 14, 14, 14, - 12, 13, 13, 12, 12, 12, 11, 9, - 13, 14, 14, 12, 11, 11, 11, 9, - 8, 7, 14, 15, 15, 14, 14, 12, - 13, 15, 16, 17, 17, 14, 12, 12, - 12, 15, 15, 14, 14, 14, 13, 13, - 9, 9, 11, 11, 10, 7, 6, 13, - 15, 15, 14, 14, 14, 13, 14, 15, - 15, 13, 14, 14, 14, 14, 10, 9, - 10, 10, 11, 11, 10, 8, 9, 13, - 14, 14, 12, 11, 14, 15, 15, 13, - 12, 14, 14, 14, 14, 13, 14, 14, - 3, 5, 8, 10, 10, 15, 15, 14, - 14, 16, 16, 15, 12, 11, 11, 11, - 7, 8, 8, 9, 12, 13, 13, 12, - 14, 15, 15, 13, 10, 11, 11, 13, - 14, 14, 13, 14, 14, 11, 10, 13, - 15, 15, 14, 12, 11, 4, 6, 6, - 8, 12, 12, 12, 13, 13, 12, 13, - 13, 14, 14, 13, 13, 13, 9, 7, - 9, 11, 14, 14, 13, 14, 14, 13, - 10, 8, 7, 5, 9, 12, 13, 14, - 15, 15, 12, 12, 10, 14, 14, 13, - 12, 13, 14, 14, 12, 13, 13, 12, - 12, 12, 9, 7, 6, 3, 4, 4, + 2, 9, 14, 14, 13, 12, 13, 14, 15, 15, 12, 10, 10, 10, 13, 14, 15, 15, 12, 11, 13, 14, 14, 13, + 15, 15, 14, 12, 12, 8, 10, 10, 15, 15, 14, 13, 14, 14, 13, 15, 20, 20, 19, 21, 21, 20, 19, 17, + 17, 18, 18, 15, 15, 13, 12, 14, 15, 15, 14, 15, 15, 12, 11, 6, 7, 8, 9, 13, 13, 13, 14, 14, 11, + 10, 7, 8, 14, 14, 14, 14, 12, 13, 13, 12, 12, 12, 11, 9, 13, 14, 14, 12, 11, 11, 11, 9, 8, 7, + 14, 15, 15, 14, 14, 12, 13, 15, 16, 17, 17, 14, 12, 12, 12, 15, 15, 14, 14, 14, 13, 13, 9, 9, + 11, 11, 10, 7, 6, 13, 15, 15, 14, 14, 14, 13, 14, 15, 15, 13, 14, 14, 14, 14, 10, 9, 10, 10, + 11, 11, 10, 8, 9, 13, 14, 14, 12, 11, 14, 15, 15, 13, 12, 14, 14, 14, 14, 13, 14, 14, 3, 5, 8, + 10, 10, 15, 15, 14, 14, 16, 16, 15, 12, 11, 11, 11, 7, 8, 8, 9, 12, 13, 13, 12, 14, 15, 15, 13, + 10, 11, 11, 13, 14, 14, 13, 14, 14, 11, 10, 13, 15, 15, 14, 12, 11, 4, 6, 6, 8, 12, 12, 12, 13, + 13, 12, 13, 13, 14, 14, 13, 13, 13, 9, 7, 9, 11, 14, 14, 13, 14, 14, 13, 10, 8, 7, 5, 9, 12, + 13, 14, 15, 15, 12, 12, 10, 14, 14, 13, 12, 13, 14, 14, 12, 13, 13, 12, 12, 12, 9, 7, 6, 3, 4, + 4, ]; pub(super) const COEF0_SYMS: [u16; 272] = [ - 2, 25, 111, 94, 69, 58, 87, 93, - 136, 135, 59, 37, 34, 36, 82, 182, - 120, 138, 195, 45, 168, 216, 178, 86, - 140, 219, 186, 162, 239, 18, 156, 35, - 127, 236, 109, 85, 180, 253, 88, 147, - 268, 264, 256, 266, 270, 262, 260, 248, - 246, 252, 258, 137, 189, 230, 64, 179, - 146, 208, 101, 118, 238, 163, 46, 9, - 153, 0, 26, 247, 169, 76, 202, 131, - 194, 38, 13, 19, 132, 106, 191, 97, - 65, 198, 77, 62, 66, 164, 48, 27, - 81, 183, 102, 60, 47, 49, 159, 227, - 20, 14, 112, 263, 144, 217, 104, 63, - 79, 209, 269, 250, 254, 203, 241, 196, - 61, 220, 148, 124, 185, 100, 80, 78, - 193, 28, 50, 235, 41, 1, 10, 171, - 226, 150, 103, 114, 115, 170, 105, 211, - 149, 249, 108, 188, 107, 255, 231, 155, - 42, 40, 55, 160, 39, 21, 29, 215, - 234, 184, 228, 51, 116, 142, 145, 172, - 165, 181, 130, 113, 117, 89, 128, 204, - 3, 7, 154, 157, 43, 141, 265, 133, - 225, 271, 244, 221, 74, 54, 56, 52, - 15, 222, 22, 30, 83, 199, 173, 73, - 123, 210, 143, 175, 44, 53, 237, 174, - 139, 134, 110, 218, 129, 161, 213, 177, - 267, 151, 125, 67, 223, 5, 11, 192, - 23, 214, 243, 166, 200, 176, 68, 224, - 187, 257, 261, 232, 96, 251, 31, 16, - 32, 57, 207, 121, 91, 126, 119, 99, - 158, 24, 212, 8, 33, 70, 92, 205, - 240, 242, 75, 197, 233, 259, 190, 98, - 71, 201, 122, 206, 72, 90, 95, 84, - 167, 245, 229, 17, 12, 4, 152, 6, + 2, 25, 111, 94, 69, 58, 87, 93, 136, 135, 59, 37, 34, 36, 82, 182, 120, 138, 195, 45, 168, 216, + 178, 86, 140, 219, 186, 162, 239, 18, 156, 35, 127, 236, 109, 85, 180, 253, 88, 147, 268, 264, + 256, 266, 270, 262, 260, 248, 246, 252, 258, 137, 189, 230, 64, 179, 146, 208, 101, 118, 238, + 163, 46, 9, 153, 0, 26, 247, 169, 76, 202, 131, 194, 38, 13, 19, 132, 106, 191, 97, 65, 198, + 77, 62, 66, 164, 48, 27, 81, 183, 102, 60, 47, 49, 159, 227, 20, 14, 112, 263, 144, 217, 104, + 63, 79, 209, 269, 250, 254, 203, 241, 196, 61, 220, 148, 124, 185, 100, 80, 78, 193, 28, 50, + 235, 41, 1, 10, 171, 226, 150, 103, 114, 115, 170, 105, 211, 149, 249, 108, 188, 107, 255, 231, + 155, 42, 40, 55, 160, 39, 21, 29, 215, 234, 184, 228, 51, 116, 142, 145, 172, 165, 181, 130, + 113, 117, 89, 128, 204, 3, 7, 154, 157, 43, 141, 265, 133, 225, 271, 244, 221, 74, 54, 56, 52, + 15, 222, 22, 30, 83, 199, 173, 73, 123, 210, 143, 175, 44, 53, 237, 174, 139, 134, 110, 218, + 129, 161, 213, 177, 267, 151, 125, 67, 223, 5, 11, 192, 23, 214, 243, 166, 200, 176, 68, 224, + 187, 257, 261, 232, 96, 251, 31, 16, 32, 57, 207, 121, 91, 126, 119, 99, 158, 24, 212, 8, 33, + 70, 92, 205, 240, 242, 75, 197, 233, 259, 190, 98, 71, 201, 122, 206, 72, 90, 95, 84, 167, 245, + 229, 17, 12, 4, 152, 6, ]; pub(super) const COEF1: [(u16, u8); 244] = [ - (2, 2), (3, 3), (102, 3), (4, 4), (148, 6), (134, 9), (171, 10), (18, 10), - (11, 8), (159, 8), (14, 9), (156, 14), (235, 15), (61, 15), (38, 13), (153, 13), - (48, 14), (49, 14), (23, 11), (203, 13), (208, 19), (204, 19), (129, 18), (94, 17), - (87, 16), (62, 15), (174, 15), (147, 15), (29, 12), (191, 12), (64, 15), (65, 15), - (146, 14), (164, 13), (142, 5), (132, 4), (103, 5), (154, 7), (165, 9), (181, 11), - (109, 12), (30, 12), (86, 16), (92, 16), (239, 15), (138, 14), (39, 13), (50, 14), - (115, 15), (238, 21), (228, 21), (236, 21), (222, 21), (216, 20), (226, 20), (196, 18), - (192, 17), (120, 16), (221, 14), (51, 14), (24, 11), (143, 8), (7, 6), (9, 7), - (152, 10), (136, 12), (160, 12), (241, 15), (66, 15), (168, 14), (219, 14), (113, 14), - (193, 12), (19, 10), (173, 10), (105, 8), (149, 9), (15, 9), (205, 13), (207, 13), - (125, 17), (190, 17), (182, 16), (68, 15), (70, 15), (67, 15), (137, 13), (31, 12), - (223, 14), (116, 15), (210, 19), (220, 19), (198, 18), (126, 17), (88, 16), (41, 13), - (25, 11), (40, 13), (73, 15), (243, 15), (53, 14), (195, 12), (183, 11), (225, 14), - (52, 14), (71, 15), (121, 16), (89, 16), (170, 14), (55, 14), (69, 15), (83, 15), - (209, 13), (108, 11), (32, 12), (54, 14), (122, 16), (184, 16), (176, 15), (42, 13), - (12, 8), (161, 8), (6, 5), (167, 9), (106, 9), (20, 10), (145, 12), (111, 13), - (43, 13), (26, 11), (175, 10), (107, 10), (34, 12), (33, 12), (197, 12), (74, 15), - (128, 17), (232, 20), (212, 20), (224, 19), (202, 18), (90, 16), (57, 14), (227, 14), - (97, 16), (93, 16), (140, 15), (185, 11), (27, 11), (16, 9), (158, 11), (211, 13), - (56, 14), (117, 15), (72, 15), (166, 13), (91, 16), (95, 16), (80, 15), (101, 16), - (194, 17), (127, 17), (82, 15), (21, 10), (144, 10), (177, 10), (151, 6), (10, 7), - (157, 7), (8, 6), (5, 4), (13, 8), (0, 9), (213, 13), (46, 13), (199, 12), - (35, 12), (162, 12), (135, 10), (169, 9), (45, 13), (59, 14), (114, 14), (44, 13), - (188, 16), (186, 16), (75, 15), (79, 15), (118, 15), (187, 11), (112, 13), (139, 14), - (178, 15), (81, 15), (110, 12), (28, 11), (163, 8), (133, 6), (104, 6), (17, 9), - (22, 10), (229, 14), (172, 14), (217, 13), (201, 12), (36, 12), (218, 20), (242, 22), - (240, 22), (234, 21), (230, 19), (206, 18), (200, 18), (214, 18), (130, 17), (131, 17), - (141, 15), (84, 15), (76, 15), (215, 13), (58, 14), (231, 14), (233, 14), (180, 15), - (77, 15), (37, 12), (189, 11), (179, 10), (155, 10), (47, 13), (96, 16), (99, 16), - (119, 15), (63, 14), (237, 14), (78, 15), (85, 15), (60, 14), (98, 16), (100, 16), - (124, 16), (123, 16), (150, 11), (1, 7), + (2, 2), + (3, 3), + (102, 3), + (4, 4), + (148, 6), + (134, 9), + (171, 10), + (18, 10), + (11, 8), + (159, 8), + (14, 9), + (156, 14), + (235, 15), + (61, 15), + (38, 13), + (153, 13), + (48, 14), + (49, 14), + (23, 11), + (203, 13), + (208, 19), + (204, 19), + (129, 18), + (94, 17), + (87, 16), + (62, 15), + (174, 15), + (147, 15), + (29, 12), + (191, 12), + (64, 15), + (65, 15), + (146, 14), + (164, 13), + (142, 5), + (132, 4), + (103, 5), + (154, 7), + (165, 9), + (181, 11), + (109, 12), + (30, 12), + (86, 16), + (92, 16), + (239, 15), + (138, 14), + (39, 13), + (50, 14), + (115, 15), + (238, 21), + (228, 21), + (236, 21), + (222, 21), + (216, 20), + (226, 20), + (196, 18), + (192, 17), + (120, 16), + (221, 14), + (51, 14), + (24, 11), + (143, 8), + (7, 6), + (9, 7), + (152, 10), + (136, 12), + (160, 12), + (241, 15), + (66, 15), + (168, 14), + (219, 14), + (113, 14), + (193, 12), + (19, 10), + (173, 10), + (105, 8), + (149, 9), + (15, 9), + (205, 13), + (207, 13), + (125, 17), + (190, 17), + (182, 16), + (68, 15), + (70, 15), + (67, 15), + (137, 13), + (31, 12), + (223, 14), + (116, 15), + (210, 19), + (220, 19), + (198, 18), + (126, 17), + (88, 16), + (41, 13), + (25, 11), + (40, 13), + (73, 15), + (243, 15), + (53, 14), + (195, 12), + (183, 11), + (225, 14), + (52, 14), + (71, 15), + (121, 16), + (89, 16), + (170, 14), + (55, 14), + (69, 15), + (83, 15), + (209, 13), + (108, 11), + (32, 12), + (54, 14), + (122, 16), + (184, 16), + (176, 15), + (42, 13), + (12, 8), + (161, 8), + (6, 5), + (167, 9), + (106, 9), + (20, 10), + (145, 12), + (111, 13), + (43, 13), + (26, 11), + (175, 10), + (107, 10), + (34, 12), + (33, 12), + (197, 12), + (74, 15), + (128, 17), + (232, 20), + (212, 20), + (224, 19), + (202, 18), + (90, 16), + (57, 14), + (227, 14), + (97, 16), + (93, 16), + (140, 15), + (185, 11), + (27, 11), + (16, 9), + (158, 11), + (211, 13), + (56, 14), + (117, 15), + (72, 15), + (166, 13), + (91, 16), + (95, 16), + (80, 15), + (101, 16), + (194, 17), + (127, 17), + (82, 15), + (21, 10), + (144, 10), + (177, 10), + (151, 6), + (10, 7), + (157, 7), + (8, 6), + (5, 4), + (13, 8), + (0, 9), + (213, 13), + (46, 13), + (199, 12), + (35, 12), + (162, 12), + (135, 10), + (169, 9), + (45, 13), + (59, 14), + (114, 14), + (44, 13), + (188, 16), + (186, 16), + (75, 15), + (79, 15), + (118, 15), + (187, 11), + (112, 13), + (139, 14), + (178, 15), + (81, 15), + (110, 12), + (28, 11), + (163, 8), + (133, 6), + (104, 6), + (17, 9), + (22, 10), + (229, 14), + (172, 14), + (217, 13), + (201, 12), + (36, 12), + (218, 20), + (242, 22), + (240, 22), + (234, 21), + (230, 19), + (206, 18), + (200, 18), + (214, 18), + (130, 17), + (131, 17), + (141, 15), + (84, 15), + (76, 15), + (215, 13), + (58, 14), + (231, 14), + (233, 14), + (180, 15), + (77, 15), + (37, 12), + (189, 11), + (179, 10), + (155, 10), + (47, 13), + (96, 16), + (99, 16), + (119, 15), + (63, 14), + (237, 14), + (78, 15), + (85, 15), + (60, 14), + (98, 16), + (100, 16), + (124, 16), + (123, 16), + (150, 11), + (1, 7), ]; pub(super) const COEF0_RUN: [u16; 272] = [ - 0, 0, 0, 1, 2, 3, 4, 5, - 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, - 62, 63, 64, 65, 66, 67, 68, 69, - 70, 71, 72, 73, 74, 75, 76, 77, - 78, 79, 80, 81, 82, 83, 84, 85, - 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 100, 101, - 102, 103, 104, 105, 106, 107, 108, 109, - 110, 111, 112, 113, 114, 115, 116, 117, - 118, 119, 120, 121, 122, 123, 124, 125, - 126, 127, 128, 129, 130, 131, 132, 133, - 134, 135, 136, 137, 138, 139, 140, 141, - 142, 143, 144, 145, 146, 147, 148, 149, - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 20, 21, 22, 23, - 24, 25, 26, 27, 28, 29, 30, 31, - 32, 33, 34, 35, 36, 37, 38, 39, - 0, 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, 17, 18, 19, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 0, 1, - 2, 3, 4, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, + 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 0, 1, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, ]; pub(super) const COEF0_LEVEL: [f32; 272] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, - 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, - 5.0, 5.0, 5.0, 6.0, 6.0, 7.0, 7.0, 8.0, - 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, - 12.0, 13.0, 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, - 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, - 20.0, 21.0, 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, - 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, + 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, 14.0, 14.0, + 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, 22.0, 22.0, + 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, ]; pub(super) const COEF1_RUN: [u16; 244] = [ - 0, 0, 0, 1, 2, 3, 4, 5, - 6, 7, 8, 9, 10, 11, 12, 13, - 14, 15, 16, 17, 18, 19, 20, 21, - 22, 23, 24, 25, 26, 27, 28, 29, - 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, - 54, 55, 56, 57, 58, 59, 60, 61, - 62, 63, 64, 65, 66, 67, 68, 69, - 70, 71, 72, 73, 74, 75, 76, 77, - 78, 79, 80, 81, 82, 83, 84, 85, - 86, 87, 88, 89, 90, 91, 92, 93, - 94, 95, 96, 97, 98, 99, 0, 1, - 2, 3, 4, 5, 6, 7, 8, 9, - 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, - 26, 27, 28, 29, 0, 1, 2, 3, - 4, 5, 6, 7, 8, 9, 0, 1, - 2, 3, 4, 5, 0, 1, 2, 0, - 1, 2, 0, 1, 2, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 1, 0, 1, 0, 1, 0, - 1, 0, 0, 0, + 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 98, 99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, 26, 27, 28, 29, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 0, 1, 2, 0, 1, 2, + 0, 1, 2, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, + 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, ]; pub(super) const COEF1_LEVEL: [f32; 244] = [ - 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, - 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, - 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, - 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, - 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, - 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, - 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, - 13.0, 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, - 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, - 21.0, 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, - 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, - 29.0, 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, - 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, - 37.0, 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, - 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, - 45.0, 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, - 49.0, 50.0, 51.0, 52.0, + 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, + 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 3.0, + 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 4.0, 4.0, 5.0, 5.0, 5.0, 6.0, + 6.0, 6.0, 7.0, 7.0, 7.0, 8.0, 8.0, 9.0, 9.0, 10.0, 10.0, 11.0, 11.0, 12.0, 12.0, 13.0, 13.0, + 14.0, 14.0, 15.0, 15.0, 16.0, 16.0, 17.0, 17.0, 18.0, 18.0, 19.0, 19.0, 20.0, 20.0, 21.0, 21.0, + 22.0, 22.0, 23.0, 23.0, 24.0, 24.0, 25.0, 25.0, 26.0, 26.0, 27.0, 27.0, 28.0, 28.0, 29.0, 29.0, + 30.0, 30.0, 31.0, 31.0, 32.0, 32.0, 33.0, 33.0, 34.0, 34.0, 35.0, 35.0, 36.0, 36.0, 37.0, 37.0, + 38.0, 38.0, 39.0, 39.0, 40.0, 40.0, 41.0, 41.0, 42.0, 42.0, 43.0, 43.0, 44.0, 44.0, 45.0, 45.0, + 46.0, 46.0, 47.0, 47.0, 48.0, 48.0, 49.0, 49.0, 50.0, 51.0, 52.0, ]; pub(super) const VEC4_LENS: [u8; 127] = [ - 1, 6, 8, 10, 10, 10, 10, 8, - 8, 10, 10, 9, 8, 8, 9, 12, - 12, 11, 12, 12, 11, 9, 9, 8, - 8, 9, 9, 8, 8, 9, 9, 12, - 12, 12, 14, 14, 13, 11, 11, 9, - 8, 9, 9, 11, 11, 10, 9, 8, - 6, 6, 6, 6, 6, 6, 11, 11, - 10, 11, 11, 10, 10, 11, 11, 9, - 7, 6, 7, 7, 6, 6, 6, 5, - 7, 11, 11, 10, 9, 8, 6, 9, - 9, 10, 10, 9, 8, 8, 6, 6, - 6, 8, 8, 9, 12, 12, 11, 10, - 8, 8, 8, 10, 10, 10, 10, 9, - 9, 8, 10, 11, 11, 9, 8, 8, - 8, 9, 9, 10, 11, 12, 12, 9, - 9, 9, 8, 8, 7, 7, 7, + 1, 6, 8, 10, 10, 10, 10, 8, 8, 10, 10, 9, 8, 8, 9, 12, 12, 11, 12, 12, 11, 9, 9, 8, 8, 9, 9, 8, + 8, 9, 9, 12, 12, 12, 14, 14, 13, 11, 11, 9, 8, 9, 9, 11, 11, 10, 9, 8, 6, 6, 6, 6, 6, 6, 11, + 11, 10, 11, 11, 10, 10, 11, 11, 9, 7, 6, 7, 7, 6, 6, 6, 5, 7, 11, 11, 10, 9, 8, 6, 9, 9, 10, + 10, 9, 8, 8, 6, 6, 6, 8, 8, 9, 12, 12, 11, 10, 8, 8, 8, 10, 10, 10, 10, 9, 9, 8, 10, 11, 11, 9, + 8, 8, 8, 9, 9, 10, 11, 12, 12, 9, 9, 9, 8, 8, 7, 7, 7, ]; pub(super) const VEC4_SYMS: [u16; 127] = [ - 0, 4370, 275, 8195, 4146, 12545, 8225, 290, - 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, - 5121, 8961, 321, 1041, 51, 4641, 546, 4610, - 530, 513, 8451, 4385, 4130, 33, 8211, 5, - 66, 4161, 1281, 81, 6, 801, 8196, 8481, - 8449, 4611, 531, 561, 769, 12290, 8226, 19, - 4097, 2, 4369, 274, 4354, 4114, 12291, 16641, - 12305, 49, 12321, 260, 4100, 516, 21, 12546, - 8466, 4353, 4371, 4626, 257, 18, 17, 1, - 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, - 276, 50, 785, 4116, 8209, 4099, 273, 4113, - 258, 259, 4609, 35, 1026, 1025, 16401, 305, - 34, 529, 289, 770, 12289, 4, 4145, 4356, - 12306, 8193, 12801, 261, 16386, 4881, 3, 514, - 4129, 545, 306, 36, 4101, 65, 20481, 786, - 4401, 4866, 8721, 291, 8450, 8465, 4115, + 0, 4370, 275, 8195, 4146, 12545, 8225, 290, 4625, 515, 20, 8706, 8210, 4355, 4131, 16385, 5121, + 8961, 321, 1041, 51, 4641, 546, 4610, 530, 513, 8451, 4385, 4130, 33, 8211, 5, 66, 4161, 1281, + 81, 6, 801, 8196, 8481, 8449, 4611, 531, 561, 769, 12290, 8226, 19, 4097, 2, 4369, 274, 4354, + 4114, 12291, 16641, 12305, 49, 12321, 260, 4100, 516, 21, 12546, 8466, 4353, 4371, 4626, 257, + 18, 17, 1, 4386, 8241, 771, 4865, 8705, 8194, 4098, 12561, 276, 50, 785, 4116, 8209, 4099, 273, + 4113, 258, 259, 4609, 35, 1026, 1025, 16401, 305, 34, 529, 289, 770, 12289, 4, 4145, 4356, + 12306, 8193, 12801, 261, 16386, 4881, 3, 514, 4129, 545, 306, 36, 4101, 65, 20481, 786, 4401, + 4866, 8721, 291, 8450, 8465, 4115, ]; pub(super) const VEC2: [(u16, u8); 137] = [ - (19, 5), (165, 10), (211, 11), (46, 11), (75, 10), (177, 11), (12, 11), (86, 8), - (83, 7), (38, 7), (133, 9), (178, 10), (28, 10), (104, 9), (73, 9), (35, 5), - (52, 6), (113, 9), (8, 9), (101, 8), (69, 7), (0, 3), (71, 8), (119, 9), - (91, 10), (179, 10), (114, 8), (166, 10), (10, 10), (44, 10), (145, 10), (66, 6), - (21, 6), (24, 8), (146, 9), (26, 9), (65, 7), (5, 7), (226, 11), (225, 12), - (15, 12), (180, 10), (147, 9), (115, 8), (40, 8), (89, 9), (134, 9), (84, 7), - (54, 7), (42, 9), (60, 10), (31, 11), (193, 11), (181, 10), (76, 10), (148, 9), - (37, 6), (67, 6), (33, 6), (3, 6), (17, 6), (2, 6), (102, 8), (87, 8), - (116, 8), (56, 8), (50, 5), (20, 5), (120, 9), (58, 9), (29, 10), (194, 10), - (135, 9), (97, 8), (7, 8), (105, 9), (13, 11), (241, 12), (16, 12), (45, 10), - (149, 9), (74, 9), (98, 7), (23, 7), (85, 7), (70, 7), (195, 10), (161, 10), - (129, 9), (72, 8), (51, 5), (36, 5), (117, 8), (61, 10), (11, 10), (162, 9), - (1, 7), (4, 6), (49, 6), (68, 6), (9, 9), (27, 9), (130, 8), (39, 7), - (53, 6), (99, 7), (25, 8), (150, 9), (90, 9), (103, 8), (163, 9), (196, 10), - (210, 10), (136, 9), (121, 9), (41, 8), (131, 8), (43, 9), (164, 9), (118, 8), - (88, 8), (81, 7), (6, 7), (55, 7), (59, 9), (30, 10), (209, 11), (14, 11), - (151, 9), (106, 9), (82, 6), (22, 6), (100, 7), (132, 8), (57, 8), (18, 4), + (19, 5), + (165, 10), + (211, 11), + (46, 11), + (75, 10), + (177, 11), + (12, 11), + (86, 8), + (83, 7), + (38, 7), + (133, 9), + (178, 10), + (28, 10), + (104, 9), + (73, 9), + (35, 5), + (52, 6), + (113, 9), + (8, 9), + (101, 8), + (69, 7), + (0, 3), + (71, 8), + (119, 9), + (91, 10), + (179, 10), + (114, 8), + (166, 10), + (10, 10), + (44, 10), + (145, 10), + (66, 6), + (21, 6), + (24, 8), + (146, 9), + (26, 9), + (65, 7), + (5, 7), + (226, 11), + (225, 12), + (15, 12), + (180, 10), + (147, 9), + (115, 8), + (40, 8), + (89, 9), + (134, 9), + (84, 7), + (54, 7), + (42, 9), + (60, 10), + (31, 11), + (193, 11), + (181, 10), + (76, 10), + (148, 9), + (37, 6), + (67, 6), + (33, 6), + (3, 6), + (17, 6), + (2, 6), + (102, 8), + (87, 8), + (116, 8), + (56, 8), + (50, 5), + (20, 5), + (120, 9), + (58, 9), + (29, 10), + (194, 10), + (135, 9), + (97, 8), + (7, 8), + (105, 9), + (13, 11), + (241, 12), + (16, 12), + (45, 10), + (149, 9), + (74, 9), + (98, 7), + (23, 7), + (85, 7), + (70, 7), + (195, 10), + (161, 10), + (129, 9), + (72, 8), + (51, 5), + (36, 5), + (117, 8), + (61, 10), + (11, 10), + (162, 9), + (1, 7), + (4, 6), + (49, 6), + (68, 6), + (9, 9), + (27, 9), + (130, 8), + (39, 7), + (53, 6), + (99, 7), + (25, 8), + (150, 9), + (90, 9), + (103, 8), + (163, 9), + (196, 10), + (210, 10), + (136, 9), + (121, 9), + (41, 8), + (131, 8), + (43, 9), + (164, 9), + (118, 8), + (88, 8), + (81, 7), + (6, 7), + (55, 7), + (59, 9), + (30, 10), + (209, 11), + (14, 11), + (151, 9), + (106, 9), + (82, 6), + (22, 6), + (100, 7), + (132, 8), + (57, 8), + (18, 4), (34, 4), ]; pub(super) const VEC1: [(u16, u8); 101] = [ - (7, 5), (32, 8), (59, 10), (60, 10), (83, 11), (82, 11), (62, 10), (33, 8), - (45, 9), (61, 10), (84, 11), (85, 11), (1, 6), (13, 5), (19, 6), (25, 7), - (34, 8), (46, 9), (47, 9), (14, 5), (6, 5), (64, 10), (87, 11), (86, 11), - (63, 10), (88, 11), (90, 11), (35, 8), (26, 7), (0, 7), (48, 9), (65, 10), - (66, 10), (36, 8), (15, 5), (20, 6), (91, 11), (89, 11), (67, 10), (49, 9), - (50, 9), (69, 10), (92, 11), (93, 11), (27, 7), (5, 5), (37, 8), (68, 10), - (71, 10), (51, 9), (52, 9), (70, 10), (94, 11), (96, 11), (38, 8), (21, 6), - (16, 5), (4, 5), (28, 7), (53, 9), (95, 11), (97, 11), (73, 10), (39, 8), - (29, 7), (72, 10), (98, 11), (99, 11), (54, 9), (40, 8), (22, 6), (30, 7), - (55, 9), (74, 10), (76, 10), (56, 9), (75, 10), (77, 10), (17, 5), (3, 5), - (23, 6), (41, 8), (57, 9), (78, 10), (79, 10), (31, 7), (10, 4), (9, 4), - (100, 5), (2, 5), (11, 4), (8, 4), (18, 5), (42, 8), (58, 9), (80, 10), - (81, 10), (43, 8), (44, 8), (24, 6), (12, 4), + (7, 5), + (32, 8), + (59, 10), + (60, 10), + (83, 11), + (82, 11), + (62, 10), + (33, 8), + (45, 9), + (61, 10), + (84, 11), + (85, 11), + (1, 6), + (13, 5), + (19, 6), + (25, 7), + (34, 8), + (46, 9), + (47, 9), + (14, 5), + (6, 5), + (64, 10), + (87, 11), + (86, 11), + (63, 10), + (88, 11), + (90, 11), + (35, 8), + (26, 7), + (0, 7), + (48, 9), + (65, 10), + (66, 10), + (36, 8), + (15, 5), + (20, 6), + (91, 11), + (89, 11), + (67, 10), + (49, 9), + (50, 9), + (69, 10), + (92, 11), + (93, 11), + (27, 7), + (5, 5), + (37, 8), + (68, 10), + (71, 10), + (51, 9), + (52, 9), + (70, 10), + (94, 11), + (96, 11), + (38, 8), + (21, 6), + (16, 5), + (4, 5), + (28, 7), + (53, 9), + (95, 11), + (97, 11), + (73, 10), + (39, 8), + (29, 7), + (72, 10), + (98, 11), + (99, 11), + (54, 9), + (40, 8), + (22, 6), + (30, 7), + (55, 9), + (74, 10), + (76, 10), + (56, 9), + (75, 10), + (77, 10), + (17, 5), + (3, 5), + (23, 6), + (41, 8), + (57, 9), + (78, 10), + (79, 10), + (31, 7), + (10, 4), + (9, 4), + (100, 5), + (2, 5), + (11, 4), + (8, 4), + (18, 5), + (42, 8), + (58, 9), + (80, 10), + (81, 10), + (43, 8), + (44, 8), + (24, 6), + (12, 4), ]; - diff --git a/crates/victory-gpu/Cargo.toml b/crates/victory-gpu/Cargo.toml index b369ec18..2e06531a 100644 --- a/crates/victory-gpu/Cargo.toml +++ b/crates/victory-gpu/Cargo.toml @@ -27,7 +27,7 @@ diagnostics = [] workspace = true [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_EventLog", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_Debug", "Win32_System_Diagnostics_ToolHelp", "Win32_System_EventLog", "Win32_System_Kernel", "Win32_System_LibraryLoader", "Win32_System_Memory", "Win32_System_Performance", "Win32_System_ProcessStatus", "Win32_System_SystemInformation", "Win32_System_Threading"] } windows = { workspace = true, features = [ "Win32_Graphics_Direct3D", "Win32_Graphics_Direct3D_Fxc", diff --git a/crates/victory-gpu/src/capture.rs b/crates/victory-gpu/src/capture.rs index b15aee6d..b67663ef 100644 --- a/crates/victory-gpu/src/capture.rs +++ b/crates/victory-gpu/src/capture.rs @@ -132,7 +132,11 @@ fn world_on() -> bool { fn world_every() -> u64 { static EVERY: std::sync::OnceLock = std::sync::OnceLock::new(); *EVERY.get_or_init(|| { - std::env::var("VICTORY_CAPTURE_WORLD_EVERY").ok().and_then(|v| v.trim().parse().ok()).filter(|&n| n > 0).unwrap_or(8) + std::env::var("VICTORY_CAPTURE_WORLD_EVERY") + .ok() + .and_then(|v| v.trim().parse().ok()) + .filter(|&n| n > 0) + .unwrap_or(8) }) } @@ -146,14 +150,27 @@ pub(crate) fn frame_drew(frame: u64, drawn: u64) { let before = LAST.swap(drawn, Relaxed); if world_on() && drawn.saturating_sub(before) >= 500 - && WORLD.compare_exchange(u64::MAX, frame, Relaxed, Relaxed).is_ok() + && WORLD + .compare_exchange(u64::MAX, frame, Relaxed, Relaxed) + .is_ok() { - tracing::info!(frame, "the first frame of 500 draws or more: frames {} and {} are captured", frame + 2, frame + 6); + tracing::info!( + frame, + "the first frame of 500 draws or more: frames {} and {} are captured", + frame + 2, + frame + 6 + ); #[cfg(feature = "diagnostics")] if let Some(folder) = folder() { - let lines: Vec = std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into(); - let _ = std::fs::write(folder.join("before-world-ops.txt"), lines.join(" -")); + let lines: Vec = + std::mem::take(&mut *RING.lock().unwrap_or_else(|e| e.into_inner())).into(); + let _ = std::fs::write( + folder.join("before-world-ops.txt"), + lines.join( + " +", + ), + ); } } } @@ -162,12 +179,15 @@ pub(crate) fn frame_drew(frame: u64, drawn: u64) { pub(crate) fn wanted(n: u64) -> bool { // Before the world, with `VICTORY_CAPTURE_WORLD`: every 16th frame too // (small pictures of menus, loading screens and title cards). - let before_world = world_on() && n.is_multiple_of(16) && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; + let before_world = world_on() + && n.is_multiple_of(16) + && WORLD.load(std::sync::atomic::Ordering::Relaxed) == u64::MAX; // In the world: every 8th frame's picture, a timeline of the opening // cutscene (its shots do not fall on the same frame numbers from run to // run, so single frames cannot be compared between runs). let first = WORLD.load(std::sync::atomic::Ordering::Relaxed); - let in_world = world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(world_every()); + let in_world = + world_on() && first != u64::MAX && n > first && (n - first).is_multiple_of(world_every()); folder().is_some() && (n.is_power_of_two() || listed(n) || before_world || in_world) } @@ -377,7 +397,9 @@ pub(crate) fn note_target(resource: crate::object::This) { pub(crate) fn dump_targets(frame: u64) { use std::sync::atomic::Ordering::Relaxed; let targets = std::mem::take(&mut *TARGETS.lock().unwrap_or_else(|e| e.into_inner())); - let Some(host) = crate::host::host() else { return }; + let Some(host) = crate::host::host() else { + return; + }; for (i, (resource, copy)) in targets.iter().enumerate() { let texture = ©.texture; // SAFETY: a live resource. @@ -387,7 +409,15 @@ pub(crate) fn dump_targets(frame: u64) { } // Every submission has run; the dump's list moves it there and back. let state = copy.state.load(Relaxed); - dump_one(host, texture, state, frame, i, *resource as crate::object::This, &d); + dump_one( + host, + texture, + state, + frame, + i, + *resource as crate::object::This, + &d, + ); } } @@ -431,7 +461,9 @@ fn dump_one( if let Some((buffer, footprint)) = stencil { stencil_values(&buffer, &footprint, frame, resource); } - let Some((buffer, footprint)) = read else { return }; + let Some((buffer, footprint)) = read else { + return; + }; let f = footprint.Footprint; let mut data = std::ptr::null_mut(); // SAFETY: the copy finished; the mapping spans the footprint's rows. @@ -461,7 +493,13 @@ fn dump_one( }; tracing::info!(?resource, depths = ?most(depths), top_bytes = ?most(tops), "24-bit depth plane values (value, texels)"); } - if let Some(rgba) = to_rgba(f.Format.0 as u32, f.Width as usize, f.Height as usize, pitch, rows) { + if let Some(rgba) = to_rgba( + f.Format.0 as u32, + f.Width as usize, + f.Height as usize, + pitch, + rows, + ) { let name = format!( "frame-{frame}-{i:02}-{resource:?}-{}x{}-f{}", d.Width, d.Height, d.Format.0 @@ -536,7 +574,11 @@ fn stencil_values( } fn half(h: u16) -> f32 { - let (sign, exp, man) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32); + let (sign, exp, man) = ( + (h >> 15) as u32, + ((h >> 10) & 0x1f) as i32, + (h & 0x3ff) as f32, + ); let v = match exp { 0 => man * 2f32.powi(-24), 31 => f32::INFINITY, @@ -564,7 +606,8 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let mut out = Vec::with_capacity(w * h * 4); let px = |x: usize, y: usize, n: usize| &rows[y * pitch + x * n..][..n]; let u16_at = |b: &[u8], i: usize| u16::from_le_bytes([b[2 * i], b[2 * i + 1]]); - let u32_at = |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); + let u32_at = + |b: &[u8], i: usize| u32::from_le_bytes(b[4 * i..4 * i + 4].try_into().unwrap_or([0; 4])); // Channel values as floats, then scaled. type Decode = Box [f32; 3]>; let (n, decode): (usize, Decode) = match format { @@ -587,23 +630,62 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } return Some(out); } - 23..=25 | 89 => (4, Box::new(move |b| { - let v = u32_at(b, 0); - [(v & 0x3ff) as f32, (v >> 10 & 0x3ff) as f32, (v >> 20 & 0x3ff) as f32] - })), - 26 => (4, Box::new(move |b| { - let v = u32_at(b, 0); - [small_float(v & 0x7ff, 6), small_float(v >> 11 & 0x7ff, 6), small_float(v >> 22, 5)] - })), - 9..=10 => (8, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))])), - 11..=14 => (8, Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i))))), - 33..=34 => (4, Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0])), - 1..=2 => (16, Box::new(move |b| { - [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i))) - })), - 15..=16 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)), f32::from_bits(u32_at(b, 1)), 0.0])), - 35..=38 => (4, Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0])), - 48..=52 => (2, Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0])), + 23..=25 | 89 => ( + 4, + Box::new(move |b| { + let v = u32_at(b, 0); + [ + (v & 0x3ff) as f32, + (v >> 10 & 0x3ff) as f32, + (v >> 20 & 0x3ff) as f32, + ] + }), + ), + 26 => ( + 4, + Box::new(move |b| { + let v = u32_at(b, 0); + [ + small_float(v & 0x7ff, 6), + small_float(v >> 11 & 0x7ff, 6), + small_float(v >> 22, 5), + ] + }), + ), + 9..=10 => ( + 8, + Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), half(u16_at(b, 2))]), + ), + 11..=14 => ( + 8, + Box::new(move |b| [0, 1, 2].map(|i| f32::from(u16_at(b, i)))), + ), + 33..=34 => ( + 4, + Box::new(move |b| [half(u16_at(b, 0)), half(u16_at(b, 1)), 0.0]), + ), + 1..=2 => ( + 16, + Box::new(move |b| [0, 1, 2].map(|i| f32::from_bits(u32_at(b, i)))), + ), + 15..=16 => ( + 8, + Box::new(move |b| { + [ + f32::from_bits(u32_at(b, 0)), + f32::from_bits(u32_at(b, 1)), + 0.0, + ] + }), + ), + 35..=38 => ( + 4, + Box::new(move |b| [f32::from(u16_at(b, 0)), f32::from(u16_at(b, 1)), 0.0]), + ), + 48..=52 => ( + 2, + Box::new(move |b| [f32::from(b[0]), f32::from(b[1]), 0.0]), + ), // Single channels (and depth planes): shown as grey. 39..=43 => (4, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), 19..=22 => (8, Box::new(move |b| [f32::from_bits(u32_at(b, 0)); 3])), @@ -627,7 +709,10 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option let range = (high - low).max(1e-20); // How much of the target holds anything: a lit scene and one bright // lamp on black have the same highest value. - let above = values.iter().filter(|v| v.iter().any(|c| c.is_finite() && *c > low)).count(); + let above = values + .iter() + .filter(|v| v.iter().any(|c| c.is_finite() && *c > low)) + .count(); let nonzero_percent = above as f32 * 100.0 / values.len().max(1) as f32; tracing::info!(format, low, high, nonzero_percent, "target values"); // Small float colour targets (the 1x1 luminance and exposure targets): @@ -663,7 +748,12 @@ fn to_rgba(format: u32, w: usize, h: usize, pitch: usize, rows: &[u8]) -> Option } } let nonzero_bits_percent = set as f32 * 100.0 / (w * h).max(1) as f32; - tracing::info!(format, nonzero_bits_percent, packed_high, "target values as packed light"); + tracing::info!( + format, + nonzero_bits_percent, + packed_high, + "target values as packed light" + ); // The same words as plain numbers, by class. Tables of indices and // masks say nothing as floats or as packed light: in the title's // shadow-mask table 0 is a block in full shadow, a word up to 255 @@ -853,11 +943,20 @@ mod tests { fn unorm16_and_xr_bias_targets_decode_as_their_formats() { // Red 0x8000 (a half-float -0), green 0x4000, blue 0. let unorm16 = [0x00, 0x80, 0x00, 0x40, 0, 0, 0xff, 0xff]; - assert_eq!(super::to_rgba(11, 1, 1, 8, &unorm16), Some(vec![255, 127, 0, 255])); + assert_eq!( + super::to_rgba(11, 1, 1, 8, &unorm16), + Some(vec![255, 127, 0, 255]) + ); // Red 0x3ff, green 0x1ff, blue 0, alpha 3. let xr = (0x3ffu32 | 0x1ff << 10 | 3 << 30).to_le_bytes(); - assert_eq!(super::to_rgba(89, 1, 1, 4, &xr), Some(vec![255, 127, 0, 255])); + assert_eq!( + super::to_rgba(89, 1, 1, 4, &xr), + Some(vec![255, 127, 0, 255]) + ); // B8G8R8A8 still swaps to RGBA. - assert_eq!(super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), Some(vec![3, 2, 1, 255])); + assert_eq!( + super::to_rgba(87, 1, 1, 4, &[1, 2, 3, 4]), + Some(vec![3, 2, 1, 255]) + ); } } diff --git a/crates/victory-gpu/src/cardmeter.rs b/crates/victory-gpu/src/cardmeter.rs index 9491f06f..3e23582c 100644 --- a/crates/victory-gpu/src/cardmeter.rs +++ b/crates/victory-gpu/src/cardmeter.rs @@ -38,12 +38,15 @@ pub(crate) enum Kind { Check, /// Every other host list: the title's own, our present copies. Lists, + /// Inside one of those: from where a pipeline is bound to where the + /// next one is, or the list ends ([`begin_named`]). + Pipeline, } /// Pairs of timestamps in the ring. -const PAIRS: u32 = 8192; +const PAIRS: u32 = 32768; /// A pair is read this long after it was recorded. -const AFTER: std::time::Duration = std::time::Duration::from_millis(1500); +const AFTER: std::time::Duration = std::time::Duration::from_millis(1000); /// A pair being recorded: its place in the ring, or none. #[derive(Clone, Copy)] @@ -70,6 +73,16 @@ struct Meter { next: u32, /// Pairs recorded and not read yet: place, kind, when recorded. pending: std::collections::VecDeque<(u32, Kind, std::time::Instant)>, + /// What the list of a pair mostly is ([`end_named`]), by place, until + /// the pair is read. + names: std::collections::HashMap, + /// Since the last table: by name, the lists and their microseconds. + by_name: std::collections::HashMap, + /// The same by pipeline ([`begin_named`]): the times it was bound and + /// the microseconds until the next one was. + by_pipeline: std::collections::HashMap, + /// Frames since the last table. + frames: u64, /// What each place held when it was last read: a place the card has /// not written since (its list never ran) still holds that, and is /// not counted again. @@ -95,14 +108,20 @@ fn make() -> Option { let device = host.device(); let mut heap: Option = None; let mut back: Option = None; - let readback = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_READBACK, ..Default::default() }; + let readback = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_READBACK, + ..Default::default() + }; let desc = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_BUFFER, Width: u64::from(PAIRS) * 16, Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; @@ -110,12 +129,23 @@ fn make() -> Option { unsafe { device .CreateQueryHeap( - &D3D12_QUERY_HEAP_DESC { Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, Count: PAIRS * 2, NodeMask: 0 }, + &D3D12_QUERY_HEAP_DESC { + Type: D3D12_QUERY_HEAP_TYPE_TIMESTAMP, + Count: PAIRS * 2, + NodeMask: 0, + }, &mut heap, ) .ok()?; device - .CreateCommittedResource(&readback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut back) + .CreateCommittedResource( + &readback, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut back, + ) .ok()?; let (heap, back) = (heap?, back?); let mut mapped = std::ptr::null_mut(); @@ -127,7 +157,19 @@ fn make() -> Option { tracing::info!( "the card's time is measured by kind of list, a timestamp where each list begins and ends (VICTORY_CARD_METER=0: not)" ); - Some(Meter { heap, back, mapped: mapped as usize, frequency, next: 0, pending: Default::default(), seen: vec![(0, 0); PAIRS as usize] }) + Some(Meter { + heap, + back, + mapped: mapped as usize, + frequency, + next: 0, + pending: Default::default(), + names: Default::default(), + by_name: Default::default(), + by_pipeline: Default::default(), + frames: 0, + seen: vec![(0, 0); PAIRS as usize], + }) } } @@ -166,7 +208,75 @@ pub(crate) fn end(list: &ID3D12GraphicsCommandList, span: Span) { // own sixteen bytes of it. unsafe { list.EndQuery(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2 + 1); - list.ResolveQueryData(&m.heap, D3D12_QUERY_TYPE_TIMESTAMP, span.0 * 2, 2, &m.back, u64::from(span.0) * 16); + list.ResolveQueryData( + &m.heap, + D3D12_QUERY_TYPE_TIMESTAMP, + span.0 * 2, + 2, + &m.back, + u64::from(span.0) * 16, + ); + } +} + +/// Whether the card's time is also measured pipeline by pipeline inside the +/// title's lists (`VICTORY_CARD_METER_PIPELINES=1`; off by default: two +/// more queries and a resolve at every change of pipeline). +pub(crate) fn pipelines() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| { + on() && std::env::var_os("VICTORY_CARD_METER_PIPELINES").is_some_and(|v| v == "1") + }) +} + +/// The pipeline `name` is bound on `list` here: the first timestamp of a +/// pair that [`end`] closes where the next pipeline is bound or the list +/// ends. What the card does between the two (the draws or dispatches of +/// that pipeline, and what the layer records around them) is that +/// pipeline's time in the table. +pub(crate) fn begin_named(list: &ID3D12GraphicsCommandList, name: &str) -> Span { + let span = begin(list, Kind::Pipeline); + if span.0 != u32::MAX { + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(m)) = meter.as_mut() { + m.names.insert(span.0, name.to_owned()); + } + } + span +} + +/// [`end`] for one of the title's lists, with what it mostly is: the +/// pipelines it binds (`names`, in order, as the list keeps them). Every +/// 256 frames the card's time is logged by that name: which of the title's +/// passes the card's time goes to, in a run like any other (the timing run +/// that names every command sends each list alone and needs the +/// device-removed notes). +pub(crate) fn end_named( + list: &ID3D12GraphicsCommandList, + span: Span, + names: &std::collections::BTreeSet, +) { + if span.0 == u32::MAX { + return; + } + end(list, span); + let name = name_of(names); + let mut meter = METER.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(Some(m)) = meter.as_mut() { + m.names.insert(span.0, name); + } +} + +/// A list's name in the table: how many pipelines it binds and the first +/// two of them (the set is in the order of the names, so a pass has the +/// same name every frame). +fn name_of(names: &std::collections::BTreeSet) -> String { + let short = |n: &String| n.chars().take(60).collect::(); + let mut first = names.iter(); + match (first.next(), first.next()) { + (None, _) => "no pipeline (copies, clears, barriers)".to_string(), + (Some(a), None) => format!("1 pipeline: {}", short(a)), + (Some(a), Some(b)) => format!("{} pipelines: {} / {}", names.len(), short(a), short(b)), } } @@ -219,8 +329,62 @@ pub(crate) fn collect() { Kind::Lists => { add(T::CardListsUs, us); add(T::CardLists, 1); + if let Some(name) = m.names.remove(&pair) { + let e = m.by_name.entry(name).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + } + Kind::Pipeline => { + if let Some(name) = m.names.remove(&pair) { + let e = m.by_pipeline.entry(name).or_insert((0, 0)); + e.0 += 1; + e.1 += us; + } + } + } + } + m.frames += 1; + if m.frames >= 256 { + let frames = m.frames as f64; + let mut table: Vec<(String, (u64, u64))> = m.by_name.drain().collect(); + table.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + let all: u64 = table.iter().map(|&(_, (_, us))| us).sum(); + tracing::info!( + "card time of the title's lists by what they bind, per frame over {} frames: {:.1} ms in {:.0} lists of {} kinds; the largest follow", + m.frames, + all as f64 / 1e3 / frames, + table.iter().map(|&(_, (n, _))| n).sum::() as f64 / frames, + table.len() + ); + for (name, (n, us)) in table.into_iter().take(24) { + tracing::info!( + " card {:6.2} ms a frame in {:5.1} lists: {name}", + us as f64 / 1e3 / frames, + n as f64 / frames + ); + } + if !m.by_pipeline.is_empty() { + let mut table: Vec<(String, (u64, u64))> = m.by_pipeline.drain().collect(); + table.sort_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); + let all: u64 = table.iter().map(|&(_, (_, us))| us).sum(); + tracing::info!( + "card time by pipeline (from where it is bound to where the next is), per frame over {} frames: {:.1} ms in {:.0} bindings of {} pipelines; the largest follow", + m.frames, + all as f64 / 1e3 / frames, + table.iter().map(|&(_, (n, _))| n).sum::() as f64 / frames, + table.len() + ); + for (name, (n, us)) in table.into_iter().take(48) { + tracing::info!( + " pipeline {:6.2} ms a frame in {:6.1} bindings ({:7.1} us each): {name}", + us as f64 / 1e3 / frames, + n as f64 / frames, + us as f64 / n.max(1) as f64 + ); } } + m.frames = 0; } } @@ -228,6 +392,20 @@ pub(crate) fn collect() { mod tests { use super::*; + #[test] + fn a_list_is_named_by_the_pipelines_it_binds() { + let mut names = std::collections::BTreeSet::new(); + assert_eq!(name_of(&names), "no pipeline (copies, clears, barriers)"); + names.insert("compute CS_Blur".to_string()); + assert_eq!(name_of(&names), "1 pipeline: compute CS_Blur"); + names.insert("mesh VS_A, pixel PS_B".to_string()); + names.insert("a".repeat(100)); + assert_eq!( + name_of(&names), + format!("3 pipelines: {} / compute CS_Blur", "a".repeat(60)) + ); + } + #[test] fn a_pairs_length_is_in_microseconds_of_the_queues_clock() { assert_eq!(micros(1_000, 11_000, 10_000_000), 1_000); diff --git a/crates/victory-gpu/src/copystat.rs b/crates/victory-gpu/src/copystat.rs index 6e0768ed..b3dc2d15 100644 --- a/crates/victory-gpu/src/copystat.rs +++ b/crates/victory-gpu/src/copystat.rs @@ -164,7 +164,10 @@ static WHOLE: Mutex>> = Mutex::new(No pub(crate) fn whole(src: usize, len: usize, us: u64) { add(C::WholeUs, us); let mut map = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); - let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + let e = map + .get_or_insert_with(HashMap::new) + .entry((src, len)) + .or_insert((0, 0)); e.0 += 1; e.1 += us; } @@ -187,7 +190,10 @@ static COMMANDS_BY_WORK: Mutex>> = Mutex pub(crate) fn command_took(op: &str, ms: f64) { let us = (ms * 1e3) as u64; let mut by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); - let e = by.get_or_insert_with(HashMap::new).entry(command_key(op)).or_insert((0, 0, 0)); + let e = by + .get_or_insert_with(HashMap::new) + .entry(command_key(op)) + .or_insert((0, 0, 0)); e.0 += 1; e.1 += us; e.2 = e.2.max(us); @@ -222,7 +228,10 @@ pub(crate) fn card_waited(us: u64, what: impl FnOnce() -> String) { let text = what(); { let mut by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()); - let e = by.get_or_insert_with(HashMap::new).entry(text.clone()).or_insert((0, 0)); + let e = by + .get_or_insert_with(HashMap::new) + .entry(text.clone()) + .or_insert((0, 0)); e.0 += 1; e.1 += us; } @@ -256,7 +265,10 @@ static COMPARED: Mutex>> = Mutex::new /// them put back into title memory. pub(crate) fn compared(src: usize, len: usize, written: usize) { let mut map = COMPARED.lock().unwrap_or_else(|e| e.into_inner()); - let e = map.get_or_insert_with(HashMap::new).entry((src, len)).or_insert((0, 0)); + let e = map + .get_or_insert_with(HashMap::new) + .entry((src, len)) + .or_insert((0, 0)); e.0 += 1; e.1 += written as u64; } @@ -309,7 +321,8 @@ fn own(size: usize, made: bool) { /// by size without saying whose they are (run 65: one of 544 MB, one of /// 401 MB, two of 174 MB, two of 115 MB); the sizes here say which of them /// are ours. -static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; +static BIG_AT: [std::sync::atomic::AtomicUsize; 64] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 64]; static BIG_BYTES: [AtomicU64; 64] = [const { AtomicU64::new(0) }; 64]; const BIG: usize = 32 << 20; @@ -320,7 +333,10 @@ fn big(at: *mut u8, size: usize, made: bool) { } for (place, bytes) in BIG_AT.iter().zip(&BIG_BYTES) { if made { - if place.compare_exchange(0, at as usize, Relaxed, Relaxed).is_ok() { + if place + .compare_exchange(0, at as usize, Relaxed, Relaxed) + .is_ok() + { bytes.store(size as u64, Relaxed); return; } @@ -334,10 +350,21 @@ fn big(at: *mut u8, size: usize, made: bool) { /// The sizes of our own big blocks alive, largest first, in MB. fn big_blocks() -> String { - let mut sizes: Vec = BIG_BYTES.iter().map(|b| b.load(Relaxed)).filter(|&b| b != 0).collect(); + let mut sizes: Vec = BIG_BYTES + .iter() + .map(|b| b.load(Relaxed)) + .filter(|&b| b != 0) + .collect(); sizes.sort_unstable_by(|a, b| b.cmp(a)); - let text: Vec = sizes.iter().map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)).collect(); - if text.is_empty() { "none".into() } else { text.join(", ") } + let text: Vec = sizes + .iter() + .map(|b| format!("{:.2}", *b as f64 / (1 << 20) as f64)) + .collect(); + if text.is_empty() { + "none".into() + } else { + text.join(", ") + } } /// The system's allocator with every block counted in [`OWN`] (two atomic @@ -398,15 +425,25 @@ mod command_tests { fn commands_are_named_by_their_pipeline() { use super::command_key; assert_eq!( - command_key("dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]"), + command_key( + "dispatch 182x1x1 [compute 24f989b98dcb03f0] | 24f989b98dcb03f0: u4=0xa6b080 [heap 341380: x]" + ), "dispatch [compute 24f989b98dcb03f0]" ); assert_eq!( - command_key("indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t"), + command_key( + "indirect kind 10 max 1 at 0xd9358fce0 [mesh 0750cb2d975c7563, pixel 085d374c5a795549] | t" + ), "indirect [mesh 0750cb2d975c7563, pixel 085d374c5a795549]" ); - assert_eq!(command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), "texture upload"); - assert_eq!(command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), "alias copy"); + assert_eq!( + command_key("texture upload 0x271b61c28b0 (2048x2048x1 f99 mips 10) sub 0"), + "texture upload" + ); + assert_eq!( + command_key("alias copy of 0x26f66aca780 into 0x26fbdc93890"), + "alias copy" + ); } } @@ -434,7 +471,9 @@ mod own_tests { super::BIG_AT .iter() .zip(&super::BIG_BYTES) - .any(|(place, bytes)| place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64) + .any(|(place, bytes)| { + place.load(Relaxed) == at && bytes.load(Relaxed) == size as u64 + }) }; let block = vec![0u8; size]; let at = block.as_ptr() as usize; @@ -501,7 +540,11 @@ fn in_memory(asked: &mut Vec<[usize; 2]>, stands: &mut Vec<(usize, u64)>, presen // SAFETY: our own process; `asked` holds that many entries of two // words each, as the call fills them in. let ok = unsafe { - K32QueryWorkingSetEx(GetCurrentProcess(), asked.as_mut_ptr().cast(), (asked.len() * 16) as u32) + K32QueryWorkingSetEx( + GetCurrentProcess(), + asked.as_mut_ptr().cast(), + (asked.len() * 16) as u32, + ) } != 0; if ok { for (a, &(kind, bytes)) in asked.iter().zip(stands.iter()) { @@ -630,7 +673,14 @@ fn log_memory_map() { } let text: Vec = (0..KINDS.len()) .filter(|&k| committed[k] > 0) - .map(|k| format!("{} {} MB ({} MB in memory)", KINDS[k], committed[k] >> 20, present[k] >> 20)) + .map(|k| { + format!( + "{} {} MB ({} MB in memory)", + KINDS[k], + committed[k] >> 20, + present[k] >> 20 + ) + }) .collect(); tracing::info!( "memory map ({} regions, {} ms): {}", @@ -652,7 +702,9 @@ fn log_memory_map() { } let mut groups: HashMap<(usize, usize), (u64, u64)> = HashMap::new(); for (base, &(k, bytes)) in &by_allocation { - let group = groups.entry((k, whole.get(base).copied().unwrap_or(0))).or_default(); + let group = groups + .entry((k, whole.get(base).copied().unwrap_or(0))) + .or_default(); group.0 += 1; group.1 += bytes; } @@ -692,7 +744,10 @@ fn log_memory() { let windows = crate::shadow::windows(); let stagings = crate::texture::let_go(); let census = crate::resource::census(); - let kinds: Vec = crate::resource::KINDS.iter().map(|k| k.load(Relaxed)).collect(); + let kinds: Vec = crate::resource::KINDS + .iter() + .map(|k| k.load(Relaxed)) + .collect(); let card = crate::host::host() .and_then(|h| h.video_memory()) .unwrap_or_default(); @@ -706,10 +761,12 @@ fn log_memory() { static LINES: AtomicU64 = AtomicU64::new(0); static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); if memory_map() && LINES.fetch_add(1, Relaxed) % 6 == 5 && !WALKING.swap(true, Relaxed) { - let walk = std::thread::Builder::new().name("victory-memory-map".into()).spawn(|| { - log_memory_map(); - WALKING.store(false, Relaxed); - }); + let walk = std::thread::Builder::new() + .name("victory-memory-map".into()) + .spawn(|| { + log_memory_map(); + WALKING.store(false, Relaxed); + }); if walk.is_err() { WALKING.store(false, Relaxed); } @@ -892,7 +949,10 @@ fn log_memory() { /// Microseconds since the first call. fn now_us() -> u64 { static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); - EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_micros() as u64 } /// When the last frame was presented and when the last submission returned @@ -950,10 +1010,21 @@ fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { fn thread_times() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); // SAFETY: our own thread and four valid out pointers. - unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; (micros(user), micros(kernel)) } @@ -961,10 +1032,21 @@ fn thread_times() -> (u64, u64) { fn process_times() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; - let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); // SAFETY: our own process and four valid out pointers. - unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + unsafe { + GetProcessTimes( + GetCurrentProcess(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; (micros(user), micros(kernel)) } @@ -989,7 +1071,10 @@ pub(crate) fn recorded(started: std::time::Instant) { crate::framelog::here(crate::framelog::H::RecordNs, ns); if !RECORDED_SINCE.load(Relaxed) && !RECORDED_SINCE.swap(true, Relaxed) { let began = now_us().saturating_sub(ns / 1000); - add(C::UntilRecordUs, began.saturating_sub(PRESENTED_AT.load(Relaxed))); + add( + C::UntilRecordUs, + began.saturating_sub(PRESENTED_AT.load(Relaxed)), + ); } OURS.with(|o| o.set(o.get() + ns)); let (unsent, calls) = UNSENT.with(|u| u.get()); @@ -1019,7 +1104,10 @@ pub(crate) fn recorded(started: std::time::Instant) { pub(crate) fn submission_begins() { let now = now_us(); if !SUBMITTED_SINCE.load(Relaxed) && !SUBMITTED_SINCE.swap(true, Relaxed) { - add(C::UntilSubmitUs, now.saturating_sub(PRESENTED_AT.load(Relaxed))); + add( + C::UntilSubmitUs, + now.saturating_sub(PRESENTED_AT.load(Relaxed)), + ); } let (user, kernel) = thread_times(); ENTERED.with(|e| e.set((user, kernel))); @@ -1053,7 +1141,10 @@ pub(crate) fn submission_ends(lock: u64) { /// The title calls its present (before our own copy to the window runs). pub(crate) fn present_begins() { - add(C::TailUs, now_us().saturating_sub(SUBMITTED_AT.load(Relaxed))); + add( + C::TailUs, + now_us().saturating_sub(SUBMITTED_AT.load(Relaxed)), + ); } /// A frame was presented. @@ -1233,7 +1324,10 @@ pub(crate) fn log(frames: f64) { longest.0 as f64 / 1e3, longest.1 ); - let by = WAITS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let by = WAITS_BY_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(); let mut by: Vec<_> = by.into_iter().flatten().collect(); by.sort_unstable_by_key(|&(_, (_, us))| std::cmp::Reverse(us)); for (what, (n, us)) in by.into_iter().take(12) { @@ -1244,7 +1338,10 @@ pub(crate) fn log(frames: f64) { what.chars().take(700).collect::() ); } - let by = COMMANDS_BY_WORK.lock().unwrap_or_else(|e| e.into_inner()).take(); + let by = COMMANDS_BY_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take(); let mut by: Vec<_> = by.into_iter().flatten().collect(); by.sort_unstable_by_key(|&(_, (_, us, _))| std::cmp::Reverse(us)); // All of them together, and by their first word: the forty lines below @@ -1262,8 +1359,16 @@ pub(crate) fn log(frames: f64) { } kinds.sort_unstable_by_key(|k| std::cmp::Reverse(k.2)); let all: u64 = kinds.iter().map(|k| k.2).sum(); - let text: Vec = - kinds.iter().map(|(word, n, us)| format!("{word} {:.1} ms in {:.0}", *us as f64 / 1e3 / frames, *n as f64 / frames)).collect(); + let text: Vec = kinds + .iter() + .map(|(word, n, us)| { + format!( + "{word} {:.1} ms in {:.0}", + *us as f64 / 1e3 / frames, + *n as f64 / frames + ) + }) + .collect(); tracing::info!( " the card's time by command (timing run), all {} kinds together: {:.1} ms a frame; by first word: {}", by.len(), @@ -1287,6 +1392,7 @@ pub(crate) fn log(frames: f64) { c[C::WatchKnownView as usize], crate::watch::AHEAD_VIEWS.swap(0, Relaxed) as f64 / frames, ); + crate::draw::window_line(frames); tracing::info!( " waits for every earlier shader write, per frame: {:.0} for the title's barrier groups, {:.0} \ for its barriers on buffers; {:.0} indirect commands bounded (a dispatch of ours between two \ @@ -1301,7 +1407,10 @@ pub(crate) fn log(frames: f64) { let compared = COMPARED.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut compared: Vec<_> = compared.into_iter().flatten().collect(); compared.sort_unstable_by_key(|&((_, len), (n, _))| std::cmp::Reverse(len as u64 * n)); - tracing::info!(" compared after submissions: {} ranges; the largest follow", compared.len()); + tracing::info!( + " compared after submissions: {} ranges; the largest follow", + compared.len() + ); for ((src, len), (n, written)) in compared.into_iter().take(8) { tracing::info!( " compared {src:#x}+{len:#x}: {:.1}x/frame, {:.2} MB/frame, {:.3} MB/frame of it written back", @@ -1333,9 +1442,20 @@ pub(crate) fn log(frames: f64) { let busiest: Vec = recorders .iter() .take(6) - .map(|r| format!("thread {} {:.0} ms in {:.0} calls", r.0, r.1 as f64 / 1e6 / frames, r.2 as f64 / frames)) + .map(|r| { + format!( + "thread {} {:.0} ms in {:.0} calls", + r.0, + r.1 as f64 / 1e6 / frames, + r.2 as f64 / frames + ) + }) .collect(); - tracing::info!(" list calls by thread: {} threads; {}", recorders.len(), busiest.join(", ")); + tracing::info!( + " list calls by thread: {} threads; {}", + recorders.len(), + busiest.join(", ") + ); log_memory(); let ranges = RANGES.lock().unwrap_or_else(|e| e.into_inner()).take(); let mut ranges: Vec<_> = ranges.into_iter().flatten().collect(); diff --git a/crates/victory-gpu/src/descriptor.rs b/crates/victory-gpu/src/descriptor.rs index c96ff17e..cc1df7a2 100644 --- a/crates/victory-gpu/src/descriptor.rs +++ b/crates/victory-gpu/src/descriptor.rs @@ -219,7 +219,8 @@ pub(crate) fn sync_heaps() { // (`HostHeap::mirror_copied_page`); one by one below // with `VICTORY_HEAP_SYNC_PAGE=0`. let slots = if page_at_once() { - let (seen, made) = host.mirror_copied_page(slots, (start, step), from, &page_bytes); + let (seen, made) = + host.mirror_copied_page(slots, (start, step), from, &page_bytes); looked += seen; mirrored += made; 0..0 @@ -249,7 +250,12 @@ pub(crate) fn sync_heaps() { } } drop(heaps); - for (count, n) in SYNCED.iter().zip([pages, looked, mirrored, started.elapsed().as_micros() as u64]) { + for (count, n) in SYNCED.iter().zip([ + pages, + looked, + mirrored, + started.elapsed().as_micros() as u64, + ]) { count.fetch_add(n, Relaxed); } } @@ -258,13 +264,15 @@ pub(crate) fn sync_heaps() { /// shader-visible heaps looked at, slots on them, slots whose record was /// not the one last seen (mirrored), and the microseconds it took. #[cfg(windows)] -pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +pub(crate) static SYNCED: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// With the frame line: what [`sync_heaps`] did per frame over `frames`. /// Nothing while no heap page changed. #[cfg(windows)] pub(crate) fn sync_line(frames: f64) { - let [pages, looked, mirrored, micros] = [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); + let [pages, looked, mirrored, micros] = + [0, 1, 2, 3].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed)); if pages == 0 { return; } @@ -551,7 +559,8 @@ fn inline() -> bool { /// Views named whole in their records since the start: constant buffer /// views, views of placed memory (for the memory line). -static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static NAMED_WHOLE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// The two record words of the 62 bits `payload` of kind `kind`. fn kind_words(kind: u32, payload: u64) -> [u32; 2] { @@ -579,14 +588,21 @@ fn constant_words(address: u64, size: u32) -> Option<[u32; 2]> { } else { return None; }; - Some(kind_words(CONSTANT, code << CONSTANT_ADDRESS_BITS | address)) + Some(kind_words( + CONSTANT, + code << CONSTANT_ADDRESS_BITS | address, + )) } /// The constant buffer view [`constant_words`] named. fn constant_of(i: u32, generation: u32) -> View { let payload = payload(i, generation); let code = (payload >> CONSTANT_ADDRESS_BITS) as u32; - let size = if code >> 14 == 0 { code } else { (code & 0x3fff) << 8 }; + let size = if code >> 14 == 0 { + code + } else { + (code & 0x3fff) << 8 + }; View::Constant(payload & ((1 << CONSTANT_ADDRESS_BITS) - 1), size) } @@ -627,7 +643,8 @@ impl Views { fn placed_of(&self, i: u32, generation: u32) -> Option { let payload = payload(i, generation); let address = payload & ((1 << PLACED_ADDRESS_BITS) - 1); - let &(unordered, resource, rest) = self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; + let &(unordered, resource, rest) = + self.shapes.get((payload >> PLACED_ADDRESS_BITS) as usize)?; let mut desc = [0u32; 16]; desc[..10].copy_from_slice(&rest[..10]); (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); @@ -1328,15 +1345,44 @@ mod tests { #[test] fn constant_views_fit_their_records() { let top = (1u64 << CONSTANT_ADDRESS_BITS) - 1; - for address in [0u64, 0x100, 0x2602_0000, 0xd_6b60_0000, 0x7ffd_a34f_0000, top] { - for size in [0u32, 1, 255, 256, 4000, (1 << 14) - 1, 1 << 14, 65536, (1 << 22) - 256] { + for address in [ + 0u64, + 0x100, + 0x2602_0000, + 0xd_6b60_0000, + 0x7ffd_a34f_0000, + top, + ] { + for size in [ + 0u32, + 1, + 255, + 256, + 4000, + (1 << 14) - 1, + 1 << 14, + 65536, + (1 << 22) - 256, + ] { let [i, generation] = constant_words(address, size).expect("fits"); assert_eq!(generation >> KIND_SHIFT, CONSTANT); - assert_eq!(view_at(i, generation), Some(View::Constant(address, size)), "{address:#x} {size}"); + assert_eq!( + view_at(i, generation), + Some(View::Constant(address, size)), + "{address:#x} {size}" + ); } } - assert_eq!(constant_words(top + 1, 256), None, "an address past 47 bits"); - assert_eq!(constant_words(0x1000, (1 << 14) + 1), None, "16 KiB or more, no multiple of 256"); + assert_eq!( + constant_words(top + 1, 256), + None, + "an address past 47 bits" + ); + assert_eq!( + constant_words(0x1000, (1 << 14) + 1), + None, + "16 KiB or more, no multiple of 256" + ); assert_eq!(constant_words(0x1000, 1 << 22), None, "4 MiB"); // Different views never share their words. assert_ne!(constant_words(0x1000, 256), constant_words(0x1000, 512)); @@ -1363,8 +1409,24 @@ mod tests { View::Placed(_, r, _) => *r == resource, _ => false, }; - let entries = || VIEWS.read().unwrap().list.iter().filter(|(v, _)| mine(v)).count(); - let shapes = || VIEWS.read().unwrap().shapes.iter().filter(|s| s.1 == resource).count(); + let entries = || { + VIEWS + .read() + .unwrap() + .list + .iter() + .filter(|(v, _)| mine(v)) + .count() + }; + let shapes = || { + VIEWS + .read() + .unwrap() + .shapes + .iter() + .filter(|s| s.1 == resource) + .count() + }; for n in 0..20_000u64 { let address = 0x6_0000_0000 + n * 0x100; create_cbv(null, &[address as u32, (address >> 32) as u32, 512, 0], at); diff --git a/crates/victory-gpu/src/descriptor/host.rs b/crates/victory-gpu/src/descriptor/host.rs index f9561996..82d625c2 100644 --- a/crates/victory-gpu/src/descriptor/host.rs +++ b/crates/victory-gpu/src/descriptor/host.rs @@ -106,7 +106,12 @@ pub(crate) fn next_start(start: u64, end: u64) -> Option { heaps .iter() .filter_map(std::sync::Weak::upgrade) - .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).next_start(start, end)) + .filter_map(|spans| { + spans + .lock() + .unwrap_or_else(|e| e.into_inner()) + .next_start(start, end) + }) .min() } @@ -118,7 +123,12 @@ pub(crate) fn first_viewed(start: u64) -> Option { heaps .iter() .filter_map(std::sync::Weak::upgrade) - .filter_map(|spans| spans.lock().unwrap_or_else(|e| e.into_inner()).first_viewed(start)) + .filter_map(|spans| { + spans + .lock() + .unwrap_or_else(|e| e.into_inner()) + .first_viewed(start) + }) .min() } @@ -130,7 +140,10 @@ static RESHOWN: Mutex> = Mutex::new(Vec::new()); /// The first level with memory of the placed texture at `start` changed: /// its slots are made again at the next texture pass. pub(crate) fn levels_changed(start: u64) { - RESHOWN.lock().unwrap_or_else(|e| e.into_inner()).push(start); + RESHOWN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(start); } /// Levels on demand (`crate::tiles`): where the placed textures start @@ -138,7 +151,8 @@ pub(crate) fn levels_changed(start: u64) { /// room, or no heap could be had), and when (`crate::host::moment`). A /// texture pass makes their slots due again once the card has room /// ([`HostHeap::texture_slots_waiting`]). -static WAITING: Mutex> = Mutex::new(std::collections::BTreeMap::new()); +static WAITING: Mutex> = + Mutex::new(std::collections::BTreeMap::new()); /// The last upload of the placed texture at `start` left a held level /// without tiles. A texture picked by index is uploaded once and then @@ -148,7 +162,10 @@ static WAITING: Mutex> = Mutex::new(std::co /// its memory alone, where a texture refused for want of room is tried /// again. pub(crate) fn levels_waiting(start: u64) { - WAITING.lock().unwrap_or_else(|e| e.into_inner()).insert(start, crate::host::moment()); + WAITING + .lock() + .unwrap_or_else(|e| e.into_inner()) + .insert(start, crate::host::moment()); } /// Title memory by the placed texture views that describe it: per span of @@ -230,7 +247,10 @@ impl Spans { .next_back() .filter(|(_, span)| span.0 > start) .map(|(at, _)| *at); - before.into_iter().chain(self.by_start.range(start..end).map(|(at, _)| *at)).collect() + before + .into_iter() + .chain(self.by_start.range(start..end).map(|(at, _)| *at)) + .collect() } /// Slot `index` holds a view of a texture in `[start, end)`. `newer`: @@ -239,7 +259,9 @@ impl Spans { /// Otherwise (a draw made the slot from what it held), and under /// [`Rule::Never`], a view that clashes with other spans is left out. fn note(&mut self, index: u32, start: u64, end: u64, newer: bool) -> Vec { - let same = |span: Option<&(u64, std::collections::BTreeSet)>| span.is_some_and(|s| s.0 == end); + let same = |span: Option<&(u64, std::collections::BTreeSet)>| { + span.is_some_and(|s| s.0 == end) + }; if self.by_slot.get(&index) == Some(&start) && same(self.by_start.get(&start)) { return Vec::new(); } @@ -287,7 +309,11 @@ impl Spans { } } } - self.by_start.entry(start).or_insert_with(|| (end, Default::default())).1.insert(index); + self.by_start + .entry(start) + .or_insert_with(|| (end, Default::default())) + .1 + .insert(index); self.by_slot.insert(index, start); stale } @@ -299,18 +325,30 @@ impl Spans { /// The lowest level a view of the texture at `start` starts at. fn first_viewed(&self, start: u64) -> Option { - self.by_start.get(&start)?.1.iter().filter_map(|slot| self.first.get(slot)).min().copied() + self.by_start + .get(&start)? + .1 + .iter() + .filter_map(|slot| self.first.get(slot)) + .min() + .copied() } /// The first span that starts inside `[start, end)` past the first /// [`HEAD`] bytes of it. fn next_start(&self, start: u64, end: u64) -> Option { - self.by_start.range(start.saturating_add(HEAD)..end).next().map(|(at, _)| *at) + self.by_start + .range(start.saturating_add(HEAD)..end) + .next() + .map(|(at, _)| *at) } /// The slots that hold a view of the texture at `start`. fn slots_at(&self, start: u64) -> Vec { - self.by_start.get(&start).map(|span| span.1.iter().copied().collect()).unwrap_or_default() + self.by_start + .get(&start) + .map(|span| span.1.iter().copied().collect()) + .unwrap_or_default() } /// Slot `index` holds no placed texture view any more. @@ -348,7 +386,11 @@ impl Spans { let before = if self.by_start.contains_key(&start) { None } else { - self.by_start.range(..start).next_back().filter(|(_, span)| span.0 > start).map(|(_, span)| span) + self.by_start + .range(..start) + .next_back() + .filter(|(_, span)| span.0 > start) + .map(|(_, span)| span) }; before .into_iter() @@ -433,11 +475,13 @@ pub(crate) static STALE: [std::sync::atomic::AtomicU64; 5] = /// until run 188. fn stale_rule() -> Rule { static RULE: std::sync::OnceLock = std::sync::OnceLock::new(); - *RULE.get_or_init(|| match std::env::var("VICTORY_STALE_TEXTURES").as_deref() { - Ok("0") => Rule::Never, - Ok("overlap") => Rule::Overlap, - _ => Rule::Start, - }) + *RULE.get_or_init( + || match std::env::var("VICTORY_STALE_TEXTURES").as_deref() { + Ok("0") => Rule::Never, + Ok("overlap") => Rule::Overlap, + _ => Rule::Start, + }, + ) } /// The runtime mapped or unmapped title memory `[at, at + len)`, or is @@ -547,7 +591,17 @@ impl TextureQueue { } self.writes += 1; let write = self.writes; - self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + self.slots.insert( + index, + Waiting { + due, + written: frame, + write, + looks: 0, + mapped: 0, + checked: (0, 0, 0, 0, 0), + }, + ); } fn remove(&mut self, index: u32) { @@ -568,14 +622,21 @@ impl TextureQueue { let mut again: Vec<(u64, u32, u64)> = Vec::new(); let mut fresh: Vec<(u64, u32, u64)> = Vec::new(); for (&index, w) in self.slots.iter().filter(|(_, w)| w.due <= frame) { - let class = if w.looks > 0 || w.mapped > 0 { &mut again } else { &mut fresh }; + let class = if w.looks > 0 || w.mapped > 0 { + &mut again + } else { + &mut fresh + }; class.push((w.written, index, w.write)); } // By the number of the write, counted over the run. let newest_first = |a: &(u64, u32, u64), b: &(u64, u32, u64)| b.2.cmp(&a.2); again.sort_unstable_by(newest_first); fresh.sort_unstable_by(newest_first); - let mut order: Vec<(u32, u64)> = again.iter().map(|&(_, index, write)| (index, write)).collect(); + let mut order: Vec<(u32, u64)> = again + .iter() + .map(|&(_, index, write)| (index, write)) + .collect(); let (mut new, mut old) = (0, fresh.len()); while new < old && order.len() < max { order.push((fresh[new].1, fresh[new].2)); @@ -654,7 +715,16 @@ impl TextureQueue { /// title that fills a texture's memory after it wrote the view (the /// `looks`-th such look; `uploaded` is the upload's frame). #[allow(clippy::too_many_arguments)] - fn recheck(&mut self, index: u32, write: u64, due: u64, at: (u64, u64), print: u64, looks: u8, uploaded: u64) { + fn recheck( + &mut self, + index: u32, + write: u64, + due: u64, + at: (u64, u64), + print: u64, + looks: u8, + uploaded: u64, + ) { if let Some(w) = self.same(index, write) { (w.due, w.looks, w.mapped) = (due, 1, 0); w.checked = (at.0, at.1, print, looks, uploaded); @@ -664,7 +734,10 @@ impl TextureQueue { /// What [`TextureQueue::recheck`] noted of slot `index`, if it is /// waiting for such a look. fn checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { - self.slots.get(&index).map(|w| w.checked).filter(|c| c.2 != 0) + self.slots + .get(&index) + .map(|w| w.checked) + .filter(|c| c.2 != 0) } /// The memory slot `index`'s texture lies in was mapped, unmapped or @@ -675,7 +748,17 @@ impl TextureQueue { self.writes += 1; let write = self.writes; let due = self.slots.get(&index).map_or(due, |w| w.due.min(due)); - self.slots.insert(index, Waiting { due, written: frame, write, looks: 0, mapped: 0, checked: (0, 0, 0, 0, 0) }); + self.slots.insert( + index, + Waiting { + due, + written: frame, + write, + looks: 0, + mapped: 0, + checked: (0, 0, 0, 0, 0), + }, + ); } /// Bytes of slot `index`'s memory that were mapped at its last upload @@ -716,7 +799,8 @@ pub(crate) fn is_texture_view(view: &View) -> bool { /// Buffer views left null because the host would refuse them /// ([`buffer_view_ok`]), since the start. -pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static REFUSED_VIEWS: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); /// Whether the host device is gone, and why (the first time it is asked /// after that): for passes that make many views, to name the one that did @@ -730,8 +814,10 @@ pub(crate) fn device_removed() -> Option { /// Writes of title view-heap slots with a placed texture view and with a /// view of a texture object, since the start (diagnostic counts). -pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); -pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static PLACED_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); +pub(crate) static OBJECT_TEXTURE_SLOTS: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); /// Bytes per element of a buffer view, as the console's descriptor holds /// them for indexed reads (structured: the stride; raw: 1, the index is the @@ -751,11 +837,19 @@ fn view_stride(view: &View) -> Option { if unordered { let d = uav_desc(words); let b = d.Anonymous.Buffer; - (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, d.Format) + ( + b.StructureByteStride, + b.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0, + d.Format, + ) } else { let d = srv_desc(words); let b = d.Anonymous.Buffer; - (b.StructureByteStride, b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, d.Format) + ( + b.StructureByteStride, + b.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0, + d.Format, + ) } }; Some(if stride > 0 { @@ -783,7 +877,11 @@ pub(crate) fn near_heaps(va: u64) -> String { } else if va < start + bytes { format!("inside, slot {}", (va - start) / step) } else { - format!("{:#x} past its end (slot {})", va - start - bytes, (va - start) / step) + format!( + "{:#x} past its end (slot {})", + va - start - bytes, + (va - start) / step + ) }; text.push_str(&format!("; {kind} heap {start:#x}+{bytes:#x}: {place}")); } @@ -903,7 +1001,10 @@ impl HostHeap { } else { // shortcut: descriptors past the host's limit are left out; a title that reaches // them needs remapping. They read the null slot instead. - tracing::warn!(count, "host view heap capped at {size}; views past it read a null slot"); + tracing::warn!( + count, + "host view heap capped at {size}; views past it read a null slot" + ); null - extra }; match make(size) { @@ -982,7 +1083,10 @@ impl HostHeap { if let Err(e) = h.fill_null(kind, size) { tracing::warn!(error = %e, "host descriptor heap not made null"); } - tracing::debug!(ms = started.elapsed().as_millis(), "host descriptor heap made null"); + tracing::debug!( + ms = started.elapsed().as_millis(), + "host descriptor heap made null" + ); Some(h) } @@ -994,11 +1098,12 @@ impl HostHeap { // SAFETY: plain heap creation and copies inside live heaps. unsafe { let block: ID3D12DescriptorHeap = - host.device.CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { - Type: kind, - NumDescriptors: BLOCK, - ..Default::default() - })?; + host.device + .CreateDescriptorHeap(&D3D12_DESCRIPTOR_HEAP_DESC { + Type: kind, + NumDescriptors: BLOCK, + ..Default::default() + })?; let start = block.GetCPUDescriptorHandleForHeapStart(); let at = |i: u32| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: start.ptr + (i * self.step) as usize, @@ -1011,13 +1116,15 @@ impl HostHeap { let mut filled = 1; while filled < BLOCK { let n = filled.min(BLOCK - filled); - host.device.CopyDescriptorsSimple(n, at(filled), start, kind); + host.device + .CopyDescriptorsSimple(n, at(filled), start, kind); filled += n; } let mut done = 0; while done < total { let n = BLOCK.min(total - done); - host.device.CopyDescriptorsSimple(n, self.cpu(done), start, kind); + host.device + .CopyDescriptorsSimple(n, self.cpu(done), start, kind); done += n; } } @@ -1082,10 +1189,13 @@ impl HostHeap { } let Some(first) = found else { if enough { - self.too_long.fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); + self.too_long + .fetch_min(n as u32, std::sync::atomic::Ordering::Relaxed); } static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(n, "no free dynamic descriptor slots: a table is not made")); + ONCE.call_once(|| { + tracing::warn!(n, "no free dynamic descriptor slots: a table is not made") + }); #[cfg(feature = "diagnostics")] { use crate::copystat::{C, add}; @@ -1095,9 +1205,13 @@ impl HostHeap { return None; }; #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::DynamicNs, started.elapsed().as_nanos() as u64); + crate::copystat::add( + crate::copystat::C::DynamicNs, + started.elapsed().as_nanos() as u64, + ); taken[first..first + n].fill(true); - self.free.fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); + self.free + .fetch_sub(n as u32, std::sync::atomic::Ordering::Relaxed); *next = ((first + n) % DYNAMIC as usize) as u32; Some(self.count + first as u32) } @@ -1125,7 +1239,14 @@ impl HostHeap { /// ([`TextureQueue::census`]). pub(crate) fn texture_slots_due(&self, frame: u64, max: usize) -> (Vec<(u32, u64)>, [u64; 5]) { let textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); - (if max == 0 { Vec::new() } else { textures.due(frame, max) }, textures.census(frame)) + ( + if max == 0 { + Vec::new() + } else { + textures.due(frame, max) + }, + textures.census(frame), + ) } /// Every title slot of the queue that is due at `frame`, and whether @@ -1172,7 +1293,10 @@ impl HostHeap { /// See [`TextureQueue::checked`]. pub(crate) fn texture_slot_checked(&self, index: u32) -> Option<(u64, u64, u64, u8, u64)> { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).checked(index) + self.textures + .lock() + .unwrap_or_else(|e| e.into_inner()) + .checked(index) } /// Nothing to upload at title slot `index` now (its memory is not @@ -1185,18 +1309,27 @@ impl HostHeap { /// See [`TextureQueue::hold`]. pub(crate) fn texture_slot_held(&self, index: u32, write: u64, due: u64) { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).hold(index, write, due); + self.textures + .lock() + .unwrap_or_else(|e| e.into_inner()) + .hold(index, write, due); } /// See [`TextureQueue::room`]. pub(crate) fn texture_slots_room(&self, frame: u64) -> usize { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).room(frame) + self.textures + .lock() + .unwrap_or_else(|e| e.into_inner()) + .room(frame) } /// Bytes of title slot `index`'s memory that were mapped when it was /// last uploaded in part (0: not uploaded, or whole). pub(crate) fn texture_slot_mapped(&self, index: u32) -> u64 { - self.textures.lock().unwrap_or_else(|e| e.into_inner()).mapped(index) + self.textures + .lock() + .unwrap_or_else(|e| e.into_inner()) + .mapped(index) } /// Takes the ranges of title memory the runtime mapped, unmapped or @@ -1218,7 +1351,10 @@ impl HostHeap { } let mut slots: Vec = { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - ranges.iter().flat_map(|&(start, end)| placed.slots_in(start, end)).collect() + ranges + .iter() + .flat_map(|&(start, end)| placed.slots_in(start, end)) + .collect() }; slots.sort_unstable(); slots.dedup(); @@ -1258,7 +1394,10 @@ impl HostHeap { use std::sync::atomic::Ordering::Relaxed; let mut slots: Vec = { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - ranges.iter().flat_map(|&(start, end)| placed.slots_holding(start, end)).collect() + ranges + .iter() + .flat_map(|&(start, end)| placed.slots_holding(start, end)) + .collect() }; slots.sort_unstable(); slots.dedup(); @@ -1267,7 +1406,12 @@ impl HostHeap { let mut textures = self.textures.lock().unwrap_or_else(|e| e.into_inner()); // Uploaded before: out of the queue, or in it after an upload (in // part, or whole and being looked at again). - slots.retain(|slot| textures.slots.get(slot).is_none_or(|w| w.mapped > 0 || w.checked.2 != 0)); + slots.retain(|slot| { + textures + .slots + .get(slot) + .is_none_or(|w| w.mapped > 0 || w.checked.2 != 0) + }); PAGE_WRITES[2].fetch_add(held as u64, Relaxed); PAGE_WRITES[3].fetch_add(slots.len() as u64, Relaxed); if !due { @@ -1300,7 +1444,8 @@ impl HostHeap { // made anew here, with the card full. `made` first, then `kept`, // as `mirror` takes them. let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); - made.get(index as usize).is_some_and(|&made| made != 0 && made == key) + made.get(index as usize) + .is_some_and(|&made| made != 0 && made == key) && self .kept .lock() @@ -1353,7 +1498,10 @@ impl HostHeap { } let mut slots: Vec = { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + starts + .iter() + .flat_map(|&start| placed.slots_at(start)) + .collect() }; slots.sort_unstable(); slots.dedup(); @@ -1382,7 +1530,10 @@ impl HostHeap { } let slots: Vec = { let placed = self.placed.lock().unwrap_or_else(|e| e.into_inner()); - starts.iter().flat_map(|&start| placed.slots_at(start)).collect() + starts + .iter() + .flat_map(|&start| placed.slots_at(start)) + .collect() }; let made = self.made.lock().unwrap_or_else(|e| e.into_inner()); let mut remade = 0; @@ -1489,11 +1640,16 @@ impl HostHeap { /// `texture`, whether it now holds a view of a texture the title may /// fill; `seen` as for [`HostHeap::note_buffer`]. fn queue_texture(&self, index: u32, texture: bool, seen: bool, frame: u64) { - let stamp = if tabled_out() { self.tabled_stamp(index) } else { 0 }; + let stamp = if tabled_out() { + self.tabled_stamp(index) + } else { + 0 + }; let now = (frame as u32).wrapping_add(1) & !TABLED_READ; // A table's slot lately: the draw that reads it uploads its // texture, so its write waits for that draw. - let lately = stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; + let lately = + stamp != 0 && u64::from(now.wrapping_sub(stamp & !TABLED_READ)) <= TABLED_FRAMES; // Made now by a draw of this frame that read it through a table: // up to date. let read_now = seen && stamp == now | TABLED_READ; @@ -1545,7 +1701,9 @@ impl HostHeap { PLACED_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } - Some(View::Shader(r, _)) if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => { + Some(View::Shader(r, _)) + if crate::resource::buffer_bytes(*r as crate::object::This).is_none() => + { OBJECT_TEXTURE_SLOTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); true } @@ -1563,7 +1721,11 @@ impl HostHeap { // (And the level the view starts at: word 4 of a texture // view's description, after format, dimension, mapping // and a pad.) - Some((resource, u64::from(desc[10]) | u64::from(desc[11]) << 32, desc[4])) + Some(( + resource, + u64::from(desc[10]) | u64::from(desc[11]) << 32, + desc[4], + )) } _ => None, }; @@ -1601,7 +1763,11 @@ impl HostHeap { { // SAFETY: inside the mapping; shaders read it while we write (a // dword, either value is one the slot had). - unsafe { (*data as *mut u32).add(index as usize).write_volatile(stride.unwrap_or(0)) }; + unsafe { + (*data as *mut u32) + .add(index as usize) + .write_volatile(stride.unwrap_or(0)) + }; } let mut buffers = self.buffers.lock().unwrap_or_else(|e| e.into_inner()); let was = if stride.is_some() { @@ -1631,8 +1797,10 @@ impl HostHeap { let end = (at + n).min(self.dynamic) as usize; if let Some(slots) = guard.1.get_mut(at as usize..end) { let given = slots.iter().filter(|taken| **taken).count() as u32; - self.free.fetch_add(given, std::sync::atomic::Ordering::Relaxed); - self.too_long.store(u32::MAX, std::sync::atomic::Ordering::Relaxed); + self.free + .fetch_add(given, std::sync::atomic::Ordering::Relaxed); + self.too_long + .store(u32::MAX, std::sync::atomic::Ordering::Relaxed); slots.fill(false); } } @@ -1969,7 +2137,11 @@ impl HostHeap { // for it, as buffer views wait for a draw: the slot is made // when the texture is first used (`super::make_waiting`), or // here when a draw reads the slot through a table. - let waiting = if for_draw { None } else { view.waiting_texture() }; + let waiting = if for_draw { + None + } else { + view.waiting_texture() + }; if let Some(texture) = waiting { super::wait_for(texture, handle); } @@ -1983,8 +2155,11 @@ impl HostHeap { // time it got sharper. if later && keep_views() - && view_at(made[index as usize] as u32, (made[index as usize] >> 32) as u32) - .is_some_and(|old| same_placed_texture(&old, &view)) + && view_at( + made[index as usize] as u32, + (made[index as usize] >> 32) as u32, + ) + .is_some_and(|old| same_placed_texture(&old, &view)) { KEPT_VIEWS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); return Some(view); @@ -2032,7 +2207,11 @@ impl HostHeap { None => "not queued".into(), Some(w) => format!( "queued due={} written@{} looks={} part_mapped={} recheck={}", - if w.due <= frame { "now".to_string() } else { format!("@{}", w.due) }, + if w.due <= frame { + "now".to_string() + } else { + format!("@{}", w.due) + }, w.written, w.looks, w.mapped, @@ -2046,7 +2225,11 @@ impl HostHeap { /// a slot never made or left null. #[cfg(feature = "diagnostics")] pub(crate) fn describe_slot(&self, index: u32) -> Option { - let key = *self.made.lock().unwrap_or_else(|e| e.into_inner()).get(index as usize)?; + let key = *self + .made + .lock() + .unwrap_or_else(|e| e.into_inner()) + .get(index as usize)?; if key == 0 { return Some("null".into()); } @@ -2175,7 +2358,9 @@ fn view_extent() -> bool { /// part's one), and for buffer objects, a part that also lies in a smaller /// buffer object. The slot then showed a copy nothing brought up to date, /// and what shaders wrote through it was looked for in the other copy. -pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc, u64, u64)> { +pub(crate) fn buffer_copy( + view: &View, +) -> Option<(std::sync::Arc, u64, u64)> { let (address, len) = buffer_range(view)?; if len == 0 { return None; @@ -2187,7 +2372,15 @@ pub(crate) fn buffer_copy(view: &View) -> Option<(std::sync::Arc bool { /// Since the last frame line: slots on changed heap pages that /// [`HostHeap::mirror_copied`] left to their draws (tables' slots). -pub(crate) static COPIED_TABLED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); +pub(crate) static COPIED_TABLED: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); /// A 64-bit fingerprint of a descriptor record's bytes (16 or 32 of them): /// equal records give equal prints, and two different records the same @@ -2274,8 +2468,25 @@ fn own_copy_on() -> bool { /// a view has no host view there; it is made on a copy of its own bytes /// (`crate::shadow::exact`), where it starts at element 0. `None`: the /// view is made on its buffer's copy, as every other. -fn own_bytes(offset: u64, base: u64, first: u64, count: u32, element: u64, stride: u32, unknown: bool) -> Option<(u64, u64)> { - own_bytes_if(own_copy_on(), offset, base, first, count, element, stride, unknown) +fn own_bytes( + offset: u64, + base: u64, + first: u64, + count: u32, + element: u64, + stride: u32, + unknown: bool, +) -> Option<(u64, u64)> { + own_bytes_if( + own_copy_on(), + offset, + base, + first, + count, + element, + stride, + unknown, + ) } #[allow(clippy::too_many_arguments)] @@ -2307,7 +2518,9 @@ fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> { let (words, unordered): (&[u32; 10], bool) = match view { View::Shader(_, Some(d)) if d[1] == BUFFER => (d, false), View::Unordered(_, _, Some(d)) if d[1] == BUFFER => (d, true), - View::Placed(unordered, resource, d) if resource[0] == BUFFER => (d[..10].try_into().ok()?, *unordered), + View::Placed(unordered, resource, d) if resource[0] == BUFFER => { + (d[..10].try_into().ok()?, *unordered) + } _ => return None, }; if unordered { @@ -2321,12 +2534,24 @@ fn buffer_fields(view: &View) -> Option<(u64, u32, u64, u32, bool)> { } else { crate::resource::element(d.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; - Some((b.FirstElement, b.NumElements, element, b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + Some(( + b.FirstElement, + b.NumElements, + element, + b.StructureByteStride, + d.Format == DXGI_FORMAT_UNKNOWN, + )) } else { let d = srv_desc(words); // SAFETY: a buffer view's union member. let b = unsafe { d.Anonymous.Buffer }; - Some((b.FirstElement, b.NumElements, element_size(&d), b.StructureByteStride, d.Format == DXGI_FORMAT_UNKNOWN)) + Some(( + b.FirstElement, + b.NumElements, + element_size(&d), + b.StructureByteStride, + d.Format == DXGI_FORMAT_UNKNOWN, + )) } } @@ -2347,7 +2572,11 @@ fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, let start = first.checked_mul(u64::from(stride))?.checked_add(offset)?; let bytes = u64::from(count) * u64::from(stride); (start % 16 == 0 && bytes % 4 == 0) - .then(|| u32::try_from(bytes / 4).ok().map(|dwords| (start / 4, dwords))) + .then(|| { + u32::try_from(bytes / 4) + .ok() + .map(|dwords| (start / 4, dwords)) + }) .flatten() } @@ -2358,7 +2587,14 @@ fn raw_window(offset: u64, first: u64, count: u32, stride: u32) -> Option<(u64, /// without the raw flag, with strides the host has no structured buffers /// for. Since every buffer view of the heap is made for shaders that pick /// them by index, one such view ended the run (2026-11-24, run 10). -fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bool, width: u64) -> bool { +fn buffer_view_ok( + format: DXGI_FORMAT, + first: u64, + count: u32, + stride: u32, + raw: bool, + width: u64, +) -> bool { use crate::resource::family; let f = format.0 as u32; let element = if raw { @@ -2402,8 +2638,16 @@ fn buffer_srv( // SAFETY: a buffer view's union member. let b = unsafe { desc.Anonymous.Buffer }; let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; - match own_bytes(offset, address, b.FirstElement, b.NumElements, element_size(&desc), b.StructureByteStride, unknown) - .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + match own_bytes( + offset, + address, + b.FirstElement, + b.NumElements, + element_size(&desc), + b.StructureByteStride, + unknown, + ) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) { Some(own) => { desc.Anonymous.Buffer.FirstElement = 0; @@ -2416,7 +2660,14 @@ fn buffer_srv( // SAFETY: a buffer view's union member. let structured = unsafe { desc.Anonymous.Buffer }; let window = (desc.Format == DXGI_FORMAT_UNKNOWN) - .then(|| raw_window(offset, structured.FirstElement, structured.NumElements, structured.StructureByteStride)) + .then(|| { + raw_window( + offset, + structured.FirstElement, + structured.NumElements, + structured.StructureByteStride, + ) + }) .flatten(); if let Some((first, count)) = window { desc.Format = DXGI_FORMAT_R32_TYPELESS; @@ -2441,7 +2692,11 @@ fn buffer_srv( } buffer.FirstElement += offset / element; } - let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let (first, count, stride) = ( + buffer.FirstElement, + buffer.NumElements, + buffer.StructureByteStride, + ); let raw = buffer.Flags.0 & D3D12_BUFFER_SRV_FLAG_RAW.0 != 0; // SAFETY: a live buffer. let width = unsafe { shadow.buffer.GetDesc() }.Width; @@ -2496,8 +2751,16 @@ fn buffer_uav( crate::resource::element(desc.Format.0 as u32).map_or(0, |(bytes, _)| bytes) }; let unknown = desc.Format == DXGI_FORMAT_UNKNOWN; - match own_bytes(shadow.offset(address), address, b.FirstElement, b.NumElements, element, b.StructureByteStride, unknown) - .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) + match own_bytes( + shadow.offset(address), + address, + b.FirstElement, + b.NumElements, + element, + b.StructureByteStride, + unknown, + ) + .and_then(|(start, bytes)| crate::shadow::exact(start, bytes)) { Some(own) => { desc.Anonymous.Buffer.FirstElement = 0; @@ -2524,7 +2787,14 @@ fn buffer_uav( let offset = if own { 0 } else { shadow.offset(address) }; // A structured view as a raw view of the same bytes (see `raw_window`). let window = (desc.Format == DXGI_FORMAT_UNKNOWN) - .then(|| raw_window(offset, buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride)) + .then(|| { + raw_window( + offset, + buffer.FirstElement, + buffer.NumElements, + buffer.StructureByteStride, + ) + }) .flatten(); if let Some((first, count)) = window { buffer.FirstElement = first; @@ -2533,13 +2803,21 @@ fn buffer_uav( buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW; } else { if element == 0 || offset % element != 0 { - once!(offset, element, "unordered buffer view not on an element of its host copy"); + once!( + offset, + element, + "unordered buffer view not on an element of its host copy" + ); return None; } buffer.FirstElement += offset / element; } buffer.CounterOffsetInBytes = 0; - let (first, count, stride) = (buffer.FirstElement, buffer.NumElements, buffer.StructureByteStride); + let (first, count, stride) = ( + buffer.FirstElement, + buffer.NumElements, + buffer.StructureByteStride, + ); let raw = buffer.Flags.0 & D3D12_BUFFER_UAV_FLAG_RAW.0 != 0; if window.is_some() { // (Left out at first: every structured unordered access view was then @@ -2564,8 +2842,12 @@ fn buffer_uav( let host = host()?; // SAFETY: a live buffer and a slot of our heap. unsafe { - host.device - .CreateUnorderedAccessView(&shadow.buffer, None::<&ID3D12Resource>, Some(&desc), at) + host.device.CreateUnorderedAccessView( + &shadow.buffer, + None::<&ID3D12Resource>, + Some(&desc), + at, + ) }; Some(Some(shadow.buffer.clone())) } @@ -2728,7 +3010,11 @@ fn rebase_mip_window( } else { // A view naming only dropped mips stays valid at the first surviving // mip; one past the chain uses the smallest survivor. - let start = if most_detailed < drop { 0 } else { host_mips - 1 }; + let start = if most_detailed < drop { + 0 + } else { + host_mips - 1 + }; (start, 1, min_lod) } } @@ -2850,7 +3136,11 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { }, }, }; - crate::tiles::show_from(desc.get_or_insert(whole), first, u32::from(own.MipLevels)); + crate::tiles::show_from( + desc.get_or_insert(whole), + first, + u32::from(own.MipLevels), + ); } // SAFETY: a live texture and a slot of our heap. unsafe { @@ -2950,7 +3240,10 @@ fn make(view: &View, at: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option { // shortcut: unordered access to a texture the title placed // itself is not mirrored; give it a resource as shader // views of such textures get when a dispatch writes one. - once!(dimension = resource[0], "placed unordered texture view not mirrored"); + once!( + dimension = resource[0], + "placed unordered texture view not mirrored" + ); return None; } // The resource description's width, after the alignment. @@ -3215,7 +3508,10 @@ mod tests { spans.note(2, 0x1_0000, 0x1_0000 + 0x5_6000, true); spans.shows(2, 1); spans.note(3, 0x1_6000, 0x1_6000 + 0x5_6000, true); - assert_eq!(spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), Some(0x1_6000)); + assert_eq!( + spans.next_start(0x1_0000, 0x1_0000 + 0x5_6000), + Some(0x1_6000) + ); assert_eq!(spans.next_start(0x1_6000, 0x1_6000 + 0x5_6000), None); assert_eq!(spans.first_viewed(0x1_0000), Some(1)); assert_eq!(spans.first_viewed(0x1_6000), None); @@ -3232,7 +3528,8 @@ mod tests { let texture = [3, 0, 0, 0, 512, 0, 512, 0x8_0001, 98, 1, 0, 0x105, 0, 0]; let view = |resource: [u32; 14], first_mip: u32, address: u32| { let mut desc = [0u32; 16]; - (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = (98, 4, first_mip, 8 - first_mip, address, 0xb); + (desc[0], desc[1], desc[4], desc[5], desc[10], desc[11]) = + (98, 4, first_mip, 8 - first_mip, address, 0xb); View::Placed(false, resource, desc) }; let low = view(texture, 3, 0x1000_0000); @@ -3245,9 +3542,17 @@ mod tests { assert!(!same_placed_texture(&low, &view(wider, 3, 0x1000_0000))); let mut buffer = texture; buffer[0] = 1; - assert!(!same_placed_texture(&view(buffer, 3, 0x1000_0000), &view(buffer, 3, 0x1000_0000))); - let View::Placed(_, resource, desc) = low.clone() else { unreachable!() }; - assert!(!same_placed_texture(&low, &View::Placed(true, resource, desc))); + assert!(!same_placed_texture( + &view(buffer, 3, 0x1000_0000), + &view(buffer, 3, 0x1000_0000) + )); + let View::Placed(_, resource, desc) = low.clone() else { + unreachable!() + }; + assert!(!same_placed_texture( + &low, + &View::Placed(true, resource, desc) + )); assert!(!same_placed_texture(&low, &View::Shader(0, None))); } @@ -3273,13 +3578,41 @@ mod tests { // bytes before the view's memory: bytes 192..2192. let (first, count) = raw_window(32, 8, 100, 20).unwrap(); assert_eq!((first, count), (48, 500)); - assert!(buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 4096)); + assert!(buffer_view_ok( + DXGI_FORMAT_R32_TYPELESS, + first, + count, + 0, + true, + 4096 + )); // the format a raw view must name; the structured one's is refused - assert!(!buffer_view_ok(DXGI_FORMAT_UNKNOWN, first, count, 0, true, 4096)); + assert!(!buffer_view_ok( + DXGI_FORMAT_UNKNOWN, + first, + count, + 0, + true, + 4096 + )); // past the buffer, not on 16 bytes, no elements - assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, first, count, 0, true, 2000)); + assert!(!buffer_view_ok( + DXGI_FORMAT_R32_TYPELESS, + first, + count, + 0, + true, + 2000 + )); assert!(raw_window(4, 0, 100, 20).is_none()); - assert!(!buffer_view_ok(DXGI_FORMAT_R32_TYPELESS, 0, 0, 0, true, 4096)); + assert!(!buffer_view_ok( + DXGI_FORMAT_R32_TYPELESS, + 0, + 0, + 0, + true, + 4096 + )); // a structured view the host takes as it is assert!(buffer_view_ok(DXGI_FORMAT_UNKNOWN, 1, 10, 12, false, 4096)); } @@ -3303,7 +3636,13 @@ mod tests { assert_eq!(q.due(9, 2).len(), 2); assert_eq!(q.census(9), [9, 9, 0, 0, 8]); // Slot 17's memory is not mapped: again next frame, then in 2, 4, 4. - let write = |q: &TextureQueue, index: u32| q.due(u64::MAX, 100).iter().find(|d| d.0 == index).unwrap().1; + let write = |q: &TextureQueue, index: u32| { + q.due(u64::MAX, 100) + .iter() + .find(|d| d.0 == index) + .unwrap() + .1 + }; let w17 = write(&q, 17); let mut frame = 9; for wait in [1, 2, 4, 4] { @@ -3486,8 +3825,14 @@ mod tests { assert_eq!(spans.slots_holding(at, at + 0x10000), [1, 2, 3]); // Past the last start, the last one; past all, or no bytes, none. assert_eq!(spans.slots_holding(at + 0x20000, at + 0x21000), [3]); - assert_eq!(spans.slots_holding(at + 0x32000, at + 0x33000), [] as [u32; 0]); - assert_eq!(spans.slots_holding(at + 0x2000, at + 0x2000), [] as [u32; 0]); + assert_eq!( + spans.slots_holding(at + 0x32000, at + 0x33000), + [] as [u32; 0] + ); + assert_eq!( + spans.slots_holding(at + 0x2000, at + 0x2000), + [] as [u32; 0] + ); } /// A write behind the guards' back under a placed texture: a slot @@ -3499,12 +3844,22 @@ mod tests { let Some(heap) = HostHeap::new(false, 8) else { return; // no host GPU }; - let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + let slots = |at: u64| -> Vec { + heap.texture_slots_due(at, 8) + .0 + .into_iter() + .map(|d| d.0) + .collect() + }; // 64x64 BC7, one mip, at an address no test and no title uses. let at = 0x7fed_0000_0000u64; let mut desc = [0u32; 16]; (desc[10], desc[11]) = (at as u32, (at >> 32) as u32); - let view = View::Placed(false, [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc); + let view = View::Placed( + false, + [3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], + desc, + ); assert!(heap.note_buffer(1, Some(&view), false).is_empty()); let written = [(at, at + 0x1000)]; // Waiting for its first upload: held, not uploaded, nothing done. @@ -3514,7 +3869,10 @@ mod tests { heap.texture_slot_done(1, write, None); assert_eq!(slots(u64::MAX), []); // Uploaded and out of the queue. Memory elsewhere: nothing. - assert_eq!(heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), [0, 0, 0]); + assert_eq!( + heap.slots_written_under(&[(at + 0x10_0000, at + 0x10_1000)], 60, true), + [0, 0, 0] + ); // Under it, counted only: it stays out of the queue. assert_eq!(heap.slots_written_under(&written, 60, false), [1, 1, 0]); assert_eq!(slots(u64::MAX), []); @@ -3528,7 +3886,10 @@ mod tests { /// overlaps others is left out of the spans, as before. #[test] fn never_stale_leaves_overlapping_views_out() { - let mut spans = Spans { rule: Rule::Never, ..Default::default() }; + let mut spans = Spans { + rule: Rule::Never, + ..Default::default() + }; assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); assert!(spans.note(2, 0x2000, 0x4000, true).is_empty()); assert!(spans.note(3, 0x1000, 0x2000, true).is_empty()); @@ -3540,7 +3901,10 @@ mod tests { /// those stale; views of the same span are one texture's. #[test] fn a_newer_view_of_other_memory_makes_the_older_stale() { - let mut spans = Spans { rule: Rule::Overlap, ..Default::default() }; + let mut spans = Spans { + rule: Rule::Overlap, + ..Default::default() + }; // Three textures side by side, the first in two slots. assert!(spans.note(1, 0x1000, 0x3000, true).is_empty()); assert!(spans.note(2, 0x1000, 0x3000, true).is_empty()); @@ -3579,15 +3943,28 @@ mod tests { let Some(heap) = HostHeap::new(false, 8) else { return; // no host GPU }; - let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; + let slots = |at: u64| -> Vec { + heap.texture_slots_due(at, 8) + .0 + .into_iter() + .map(|d| d.0) + .collect() + }; // 64x64 BC7, one mip, at an address no test and no title uses. let at = 0x7fee_0000_0000u64; let view = |address: u64, width: u32| { let mut desc = [0u32; 16]; (desc[10], desc[11]) = (address as u32, (address >> 32) as u32); - View::Placed(false, [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], desc) + View::Placed( + false, + [3, 0, 0, 0, width, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0], + desc, + ) }; - let len = crate::resource::placed_bytes(&[3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0]).unwrap(); + let len = crate::resource::placed_bytes(&[ + 3, 0, 0, 0, 64, 0, 64, 0x1_0001, 98, 1, 0, 0x105, 0, 0, + ]) + .unwrap(); assert!(heap.note_buffer(1, Some(&view(at, 64)), false).is_empty()); let (queued, write) = heap.texture_slots_due(u64::MAX, 8).0[0]; assert_eq!(queued, 1); @@ -3613,8 +3990,18 @@ mod tests { return; // no host GPU }; let frame = 100; - let slots = |at: u64| -> Vec { heap.texture_slots_due(at, 8).0.into_iter().map(|d| d.0).collect() }; - let texture = View::Placed(false, [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], [0; 16]); + let slots = |at: u64| -> Vec { + heap.texture_slots_due(at, 8) + .0 + .into_iter() + .map(|d| d.0) + .collect() + }; + let texture = View::Placed( + false, + [3, 0, 0, 0, 4, 0, 4, 0x1_0001, 28, 1, 0, 0x105, 0, 0], + [0; 16], + ); assert!(is_texture_view(&texture)); heap.queue_texture(2, true, false, frame); heap.queue_texture(3, true, false, frame); @@ -3661,7 +4048,10 @@ mod tests { fn srv_mip_window_rebasing_handles_partial_full_and_dropped_ranges() { assert_eq!(rebase_mip_window(1, 3, 3.5, 2, 5), (0, 2, 1.5)); assert_eq!(rebase_mip_window(3, 2, 1.0, 2, 5), (1, 2, 0.0)); - assert_eq!(rebase_mip_window(0, u32::MAX, 0.0, 2, 5), (0, u32::MAX, 0.0)); + assert_eq!( + rebase_mip_window(0, u32::MAX, 0.0, 2, 5), + (0, u32::MAX, 0.0) + ); assert_eq!(rebase_mip_window(0, 1, 0.0, 2, 5), (0, 1, 0.0)); assert_eq!(rebase_mip_window(1, 3, 1.5, 0, 7), (1, 3, 1.5)); } @@ -3675,7 +4065,9 @@ mod record_print_tests { /// or in its length, prints otherwise. #[test] fn a_record_that_changed_prints_otherwise() { - let record: Vec = (0..32u8).map(|i| i.wrapping_mul(37).wrapping_add(5)).collect(); + let record: Vec = (0..32u8) + .map(|i| i.wrapping_mul(37).wrapping_add(5)) + .collect(); let print = record_print(&record); assert_eq!(print, record_print(&record.clone())); for at in 0..32 { @@ -3708,10 +4100,16 @@ mod own_copy_tests { assert_eq!(own_bytes_if(true, 0, base, 0, 10, 12, 0, false), None); // A typed view of 12-byte elements, 5,222,240 bytes into its copy // (8 past an element): its own bytes, from its first element. - assert_eq!(own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), Some((base + 36, 120))); + assert_eq!( + own_bytes_if(true, 5_222_240, base, 3, 10, 12, 0, false), + Some((base + 36, 120)) + ); // A structured view of 32-byte elements 8 bytes in: not on 16, so // no raw view of the copy either. - assert_eq!(own_bytes_if(true, 8, base, 2, 4, 32, 32, true), Some((base + 64, 128))); + assert_eq!( + own_bytes_if(true, 8, base, 2, 4, 32, 32, true), + Some((base + 64, 128)) + ); // The same 16 bytes in: off its elements, but a raw view of the // copy's bytes does (as before). assert_eq!(own_bytes_if(true, 16, base, 2, 4, 32, 32, true), None); diff --git a/crates/victory-gpu/src/device.rs b/crates/victory-gpu/src/device.rs index dfbf2b22..ba97a1e3 100644 --- a/crates/victory-gpu/src/device.rs +++ b/crates/victory-gpu/src/device.rs @@ -377,7 +377,9 @@ extern "system" fn unknown_pipeline( let mut bytes = [0u8; 128]; (at != 0 && crate::host::read_into(at as *const u8, &mut bytes)).then(|| { bytes - .as_chunks::<8>().0.iter() + .as_chunks::<8>() + .0 + .iter() .map(|c| c.iter().rev().fold(0u64, |v, &b| v << 8 | u64::from(b))) .collect() }) @@ -385,9 +387,7 @@ extern "system" fn unknown_pipeline( #[cfg(not(windows))] let words = |_: usize| None::>; let description = words(desc as usize); - let first = description - .as_ref() - .and_then(|w| words(w[0] as usize)); + let first = description.as_ref().and_then(|w| words(w[0] as usize)); tracing::warn!( slot = format_args!("{:#x}", SLOT), calls, diff --git a/crates/victory-gpu/src/draw.rs b/crates/victory-gpu/src/draw.rs index e8efb2a3..52f080d7 100644 --- a/crates/victory-gpu/src/draw.rs +++ b/crates/victory-gpu/src/draw.rs @@ -15,7 +15,9 @@ use victory_shader::{ResourceType, RootType, UsedResource}; use crate::descriptor::View; use windows::Win32::Foundation::RECT; -use windows::Win32::Graphics::Direct3D::{D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST}; +use windows::Win32::Graphics::Direct3D::{ + D3D_PRIMITIVE_TOPOLOGY, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, +}; use windows::Win32::Graphics::Direct3D12::*; use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT; use windows::core::Interface; @@ -197,7 +199,125 @@ const WINDOW_MOST: u64 = 64; /// run with windows was announced that way seconds ahead. fn windows() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) && !crate::drvwatch::tripped() + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW").is_some_and(|v| v == "1")) + && !crate::drvwatch::tripped() +} + +/// Whether a record that is not on the window's walk opens a window of its +/// own at once, with the step the title was last seen to walk that +/// argument buffer by (`VICTORY_WINDOW_JUMP=1`; `alt`: twenty seconds +/// with, twenty without, in turn, each change said in the log). Off by +/// default. Needs [`windows()`]. +/// +/// Run 243 counted, per frame, 2,370 indirect commands read from a window +/// and 2,370 clamped by a pass of ours; 960 of those passes were for +/// records "off the window's walk": the title draws a few records one +/// after the other and then jumps to another place in the same argument +/// buffer, some 480 times a frame. The record after a jump was clamped +/// alone (its step is not known from one record), and the one after it +/// opened a window of sixteen: two passes a jump, each one a trip of the +/// card from drawing to compute and back (9 microseconds in the game). +/// +/// With the switch the step of the last window that draws did read from +/// is remembered with its argument buffer, kind and stride, and a record +/// that would be clamped alone on that buffer opens sixteen records at +/// that step instead: what the next record would have opened anyway, one +/// record earlier, so no more of the list's budget is spent than before. +/// If no draw reads from a window opened that way before the next pass, +/// the step is forgotten until a walk shows it again: a title that draws +/// lone records all over a buffer gets what it had. +fn jump_windows() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_WINDOW_JUMP").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_secs() + / 20) + % 2 + == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "a record off the window's walk opens a window at the remembered step from now (VICTORY_WINDOW_JUMP=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// The records of a window opened at a remembered step ([`jump_windows`]): +/// what the record after a lone one opens. +const WINDOW_JUMP: u32 = 16; + +/// What a record that would be clamped alone opens instead, if the step +/// its argument buffer is walked by is remembered: that step and how many +/// records (never past the buffer, of which `left` bytes are left from +/// the record on). None if nothing is remembered for this buffer, kind +/// and stride, or no second record fits. +fn jump_window( + remembered: Option<(u64, u32, u32, u32)>, + (copy, kind, stride): (u64, u32, u32), + left: u64, +) -> Option<(u32, u32)> { + let (c, k, s, step) = remembered?; + if (c, k, s) != (copy, kind, stride) || step == 0 { + return None; + } + let fit = (left / u64::from(step)).min(u64::from(WINDOW_JUMP)) as u32; + (fit > 1).then_some((step, fit)) +} + +/// Diagnostics of [`windows()`]: indirect commands since the last line, by +/// what became of their clamp. In order: read from a window (no pass of +/// ours); then clamped by a pass of ours because: it is a dispatch; it +/// asks for more than one record; it has a count buffer; its shaders can +/// store to buffers; it is the list's first; there was no window on its +/// argument buffer (another buffer, kind or stride, or the window was +/// ended); its record does not continue the window's walk; it is past the +/// window's end (the next window: as meant). And the records those passes +/// clamped in all; the passes that opened a window at a remembered step +/// ([`jump_windows`]), and those of them no draw read from. +#[cfg(feature = "diagnostics")] +pub(crate) static WINDOW_WHY: [std::sync::atomic::AtomicU64; 12] = + [const { std::sync::atomic::AtomicU64::new(0) }; 12]; + +/// The line of [`WINDOW_WHY`], per frame over `frames` frames. +#[cfg(feature = "diagnostics")] +pub(crate) fn window_line(frames: f64) { + let n: Vec = WINDOW_WHY + .iter() + .map(|n| n.swap(0, std::sync::atomic::Ordering::Relaxed) as f64 / frames.max(1.0)) + .collect(); + tracing::info!( + "indirect commands per frame by their clamp: {:.0} read from a window (no pass of ours); a pass of ours for {:.0}: {:.0} dispatches, {:.0} of more than one record, {:.0} with a count \ + buffer, {:.0} whose shaders can store to buffers, {:.0} first on their list, {:.0} with no window on their argument buffer, {:.0} off the window's walk, {:.0} past the window's end; \ + {:.0} records clamped by those passes; {:.0} of the passes opened a window at a remembered step (VICTORY_WINDOW_JUMP=1), {:.0} of those windows were read by no draw", + n[0], + n[1..9].iter().sum::(), + n[1], + n[2], + n[3], + n[4], + n[5], + n[6], + n[7], + n[8], + n[9], + n[10], + n[11], + ); } /// What one title list has set, and what its host list was last given. @@ -233,6 +353,18 @@ pub(crate) struct State { /// The indirect records clamped last, if later draws may still read /// them (`windows()`). window: Option, + /// With [`jump_windows`]: the argument buffer (its copy's number), kind + /// and stride of the last window of several records that a draw read + /// from, and that window's step. + walk_step: Option<(u64, u32, u32, u32)>, + /// Whether [`State::window`] was opened at the remembered step, and + /// whether a draw has read from it since. + window_jumped: bool, + window_read: bool, + /// Diagnostics: the argument buffer and the offset of the indirect + /// command before this one on the list. + #[cfg(feature = "diagnostics")] + last_indirect: (u64, u64), /// What the host list has: pipeline, root signature, heaps. host_pipeline: usize, /// Graphics, compute. @@ -343,7 +475,8 @@ fn mesh_kept(pipeline: usize) -> bool { if hash.len() < 16 { return true; } - last.as_bytes().contains(&hash[15]) && (before.is_empty() || before.as_bytes().contains(&hash[14])) + last.as_bytes().contains(&hash[15]) + && (before.is_empty() || before.as_bytes().contains(&hash[14])) } /// Draws recorded on the host GPU since the last frame line. @@ -489,9 +622,7 @@ fn root_view(list: &HostList, address: u64, srv: bool) -> Option { .map_or(u64::MAX, |mb| mb << 20) }); let shadow = crate::shadow::find(address, 1)?; - let len = shadow - .left(address) - .min(if srv { limit } else { 1 << 16 }); + let len = shadow.left(address).min(if srv { limit } else { 1 << 16 }); let gpu = shadow.gpu(address); if srv || gpu % 256 == 0 { shadow.refresh(list, address, len); @@ -597,7 +728,12 @@ impl State { } pub(crate) fn clear_vertex_buffers(&mut self, start: u32, count: u32) { - for slot in self.vertex.iter_mut().skip(start as usize).take(count as usize) { + for slot in self + .vertex + .iter_mut() + .skip(start as usize) + .take(count as usize) + { *slot = VertexView::default(); } } @@ -821,7 +957,11 @@ impl State { _ => 0, }; if address == 0 { - once!(slot, dword, "a shader takes the address of a buffer view that is not there: it reads 0"); + once!( + slot, + dword, + "a shader takes the address of a buffer view that is not there: it reads 0" + ); } if kind == USER_VIEW_ADDRESS { address as u32 @@ -879,7 +1019,10 @@ impl State { return false; }; if p.compute || p.mesh != mesh { - once!(mesh, "a draw or mesh dispatch with another kind of pipeline"); + once!( + mesh, + "a draw or mesh dispatch with another kind of pipeline" + ); return false; } if p.rects && self.topology != RECTANGLES { @@ -967,7 +1110,9 @@ impl State { /// False if the draw or dispatch must not run: a root SRV it reads /// could not be given a view. pub(crate) fn bind(&mut self, list: &HostList, p: &HostPipeline, compute: bool) -> bool { - self.bind_parts(list, p, &p.root, &p.pso, &p.name, &p.stages, compute, compute) + self.bind_parts( + list, p, &p.root, &p.pso, &p.name, &p.stages, compute, compute, + ) } #[allow(clippy::too_many_arguments)] @@ -1049,9 +1194,15 @@ impl State { let writes = (t.stores || !write_skip()) && !crate::pipeline::builder_quarantined(self.pipeline as This); // Title memory by address: what the shader finds it by. - let memory = if t.host.root_srvs.contains(&victory_shader::emit::SLOT_MEMORY) { + let memory = if t + .host + .root_srvs + .contains(&victory_shader::emit::SLOT_MEMORY) + { let Some(ready) = self.memory_ready(list, title_compute, writes) else { - once!("a shader that reads title memory by address without a view heap to hold its views: the draw is dropped"); + once!( + "a shader that reads title memory by address without a view heap to hold its views: the draw is dropped" + ); return false; }; Some(ready) @@ -1120,7 +1271,8 @@ impl State { continue; } let tabled = srv && crate::pipeline::host::bounded_root_srvs(); - let Some(&Root::View(address)) = self.roots_ref(title_compute).get(usize::from(slot)) + let Some(&Root::View(address)) = + self.roots_ref(title_compute).get(usize::from(slot)) else { once!(slot, "a shader reads a root view the title did not set"); // A table left unset is undefined: a null view. @@ -1450,7 +1602,8 @@ impl State { // at best); all of them every 16 passes, because a view of a // released resource goes stale without a write, and a slot written // before its memory had a host copy is only made then. - type Ranges = std::collections::HashMap, u64, u64)>; + type Ranges = + std::collections::HashMap, u64, u64)>; static RANGES: std::sync::Mutex>> = std::sync::Mutex::new(None); let mut kept = RANGES.lock().unwrap_or_else(|e| e.into_inner()); @@ -1469,7 +1622,8 @@ impl State { // Whether the device was there before the pass: a view that removes // it is named below. static GONE: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); - let mut alive = !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); + let mut alive = + !GONE.load(Ordering::Relaxed) && crate::descriptor::host::device_removed().is_none(); HEAP_PASS_PARTS[1].fetch_add(slots.len() as u64, Ordering::Relaxed); for (n, &index) in slots.iter().enumerate() { ranges.remove(&index); @@ -1534,7 +1688,8 @@ impl State { // the garbage ended runs (the card stopped answering 14-90 frames // into the opening cutscene; with every frame it ran on). The pass // costs some 30 ms a frame this way. - static WHOLE: std::sync::Mutex>> = std::sync::Mutex::new(None); + static WHOLE: std::sync::Mutex>> = + std::sync::Mutex::new(None); let mut whole = WHOLE.lock().unwrap_or_else(|e| e.into_inner()); let whole = whole.get_or_insert_with(Default::default); for (shadow, from, to) in spans.values() { @@ -1561,7 +1716,10 @@ impl State { } let textures_began = std::time::Instant::now(); self.heap_textures(list, heap, host); - HEAP_PASS_PARTS[0].fetch_add(textures_began.elapsed().as_micros() as u64, Ordering::Relaxed); + HEAP_PASS_PARTS[0].fetch_add( + textures_began.elapsed().as_micros() as u64, + Ordering::Relaxed, + ); HEAP_BUFFER_PASSES.fetch_add(1, Ordering::Relaxed); HEAP_BUFFER_MICROS.fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed); static LOGGED: AtomicU64 = AtomicU64::new(0); @@ -1594,7 +1752,9 @@ impl State { return; } let bake = bake_ms > 0 - && p.stages.iter().any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); + && p.stages + .iter() + .any(|s| BAKE_PIXEL_SHADERS.contains(&s.shader.hash.as_str())); static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); // The milliseconds this frame's bake draws have taken so far: a // frame has several, and together they get `bake_ms`. @@ -1628,7 +1788,9 @@ impl State { let bake = bake && left > 0; let n = EARLY_TEXTURE_PASSES[usize::from(bake)].fetch_add(1, Ordering::Relaxed) + 1; if bake && n.is_power_of_two() { - let [slots, due, ..] = HEAP_TEXTURES_QUEUE.each_ref().map(|c| c.load(Ordering::Relaxed)); + let [slots, due, ..] = HEAP_TEXTURES_QUEUE + .each_ref() + .map(|c| c.load(Ordering::Relaxed)); tracing::info!( frame, bakes = n, @@ -1662,7 +1824,9 @@ impl State { room: bool, ) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) { + if !*ON + .get_or_init(|| std::env::var_os("VICTORY_CARD_ACCOUNTING").is_some_and(|v| v == "1")) + { return; } // When the next line is due (0: none yet, the card has had room). @@ -1672,8 +1836,16 @@ impl State { // (With levels on demand the card may never be without room: the // lines then start with the first texture made that way.) let by_level = crate::tiles::STATS[4].load(Ordering::Relaxed) > 0; - let due_now = if next == 0 { !room || by_level } else { now >= next }; - if !due_now || NEXT.compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed).is_err() { + let due_now = if next == 0 { + !room || by_level + } else { + now >= next + }; + if !due_now + || NEXT + .compare_exchange(next, now + 5000, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { return; } // Due slots; of them uploaded before; of them viewing nothing the @@ -1755,7 +1927,10 @@ impl State { // textures (a scene's first minutes) then drains in fewer frames. static PER_FRAME_MB: std::sync::OnceLock = std::sync::OnceLock::new(); let per_frame: u64 = *PER_FRAME_MB.get_or_init(|| { - std::env::var("VICTORY_TEXTURE_STAGE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(192) + std::env::var("VICTORY_TEXTURE_STAGE_MB") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(192) }) << 20; static FRAME: AtomicU64 = AtomicU64::new(u64::MAX); static SPENT: AtomicU64 = AtomicU64::new(0); @@ -1814,7 +1989,9 @@ impl State { // the looks are now only for what that does not tell.) static PASSED: AtomicU64 = AtomicU64::new(0); let now = crate::host::now_ms(); - let took = now.saturating_sub(PASSED.swap(now, Ordering::Relaxed)).max(1); + let took = now + .saturating_sub(PASSED.swap(now, Ordering::Relaxed)) + .max(1); let most = (4000 / took).clamp(16, 256); // What a table entry of a texture a shader samples says. let sampled = UsedResource { @@ -1914,7 +2091,9 @@ impl State { } } let mut partly = None; - if let Some(View::Placed(false, resource, desc)) = heap.handle(index).and_then(crate::descriptor::view) { + if let Some(View::Placed(false, resource, desc)) = + heap.handle(index).and_then(crate::descriptor::view) + { let address = u64::from(desc[10]) | u64::from(desc[11]) << 32; let len = crate::resource::placed_bytes(&resource).unwrap_or(1); let mapped = crate::texture::mapped_bytes(address as *const u8, len as usize); @@ -1941,7 +2120,8 @@ impl State { // host's own contents: nothing to bring up to date, and this // pass is no use of it (its host copy is made when something // uses it, and its slots then: `descriptor::make_waiting`). - if let Some(View::Shader(object, _)) = heap.handle(index).and_then(crate::descriptor::view) + if let Some(View::Shader(object, _)) = + heap.handle(index).and_then(crate::descriptor::view) && crate::resource::buffer_bytes(object as This).is_none() && !crate::resource::title_fills(object as This) { @@ -1963,7 +2143,9 @@ impl State { // before. if !room { let has_its_texture = reupload_when_full() - && heap.handle(index).is_some_and(|handle| host.texture_slot_made_from(index, handle)); + && heap + .handle(index) + .is_some_and(|handle| host.texture_slot_made_from(index, handle)); if !has_its_texture { refused += 1; if full_card_pass() { @@ -1988,8 +2170,12 @@ impl State { ); } } - let view = heap.handle(index).and_then(|handle| host.mirror(index, handle, true)); - let placed = view.as_ref().and_then(crate::descriptor::host::placed_texture); + let view = heap + .handle(index) + .and_then(|handle| host.mirror(index, handle, true)); + let placed = view + .as_ref() + .and_then(crate::descriptor::host::placed_texture); let resource = match placed.as_ref().or(view.as_ref()) { Some(&View::Shader(resource, _)) => resource as This, _ => { @@ -1997,7 +2183,8 @@ impl State { continue; } }; - let title_fills = crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); + let title_fills = + crate::resource::host_resource(resource).is_some_and(crate::texture::title_written); if !title_fills { // a render target, a depth or unordered access texture: the host's own host.texture_slot_done(index, write, None); @@ -2017,7 +2204,11 @@ impl State { { GONE.store(true, Ordering::Relaxed); let text: String = format!("{view:?}").chars().take(300).collect(); - tracing::error!(why, slot = index, "the host device went while textures picked by index were made ready; last: {text}"); + tracing::error!( + why, + slot = index, + "the host device went while textures picked by index were made ready; last: {text}" + ); crate::host::log_removal_context(); return; } @@ -2207,7 +2398,10 @@ impl State { // A program that walks ray-tracing structures nothing has built. if crate::pipeline::walk_held(self.pipeline as This) { #[cfg(feature = "diagnostics")] - crate::pipeline::note_why("a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)".to_owned()); + crate::pipeline::note_why( + "a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)" + .to_owned(), + ); return; } // The ray-tracing structure builder's stages run all or none. @@ -2277,13 +2471,22 @@ impl State { }) }; let targets: Vec = self.targets.iter().filter_map(|&t| described(t)).collect(); - let _ = write!(text, " targets {targets:?} depth {:?} state [{}]", described(self.depth), p.state); + let _ = write!( + text, + " targets {targets:?} depth {:?} state [{}]", + described(self.depth), + p.state + ); // The title's scissor and viewport at this draw (the first of // each): the title draws what it sees through a // portal (a window, from inside a room) under the portal's // rectangle, and the listing did not say which draws those are. if let Some(r) = self.scissors.first() { - let _ = write!(text, " scissor [{} {} {} {}]", r.left, r.top, r.right, r.bottom); + let _ = write!( + text, + " scissor [{} {} {} {}]", + r.left, r.top, r.right, r.bottom + ); } if let Some(v) = self.viewports.first() { let _ = write!( @@ -2310,7 +2513,12 @@ impl State { let _ = write!(text, " [heap {index}: {slot}]"); } } - for &(slot, _) in stage.root_cbvs.iter().chain(&stage.root_srvs).chain(&stage.root_uavs) { + for &(slot, _) in stage + .root_cbvs + .iter() + .chain(&stage.root_srvs) + .chain(&stage.root_uavs) + { if let Some(Root::View(address)) = self.roots_ref(compute).get(usize::from(slot)) { let host = crate::shadow::find(*address, 1) .map(|s| (s.gpu(*address), s.left(*address))); @@ -2350,7 +2558,10 @@ impl State { let Some(p) = crate::pipeline::host_pipeline(self.pipeline as This) else { return String::new(); }; - let Some(stage) = p.stages.iter().find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) + let Some(stage) = p + .stages + .iter() + .find(|s| wanted.iter().any(|w| s.shader.hash.starts_with(w.as_str()))) else { return String::new(); }; @@ -2372,7 +2583,11 @@ impl State { crate::descriptor::view(table + u64::from(dwords) * 4) }; let mut material = None; - for u in t.used.iter().filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) { + for u in t + .used + .iter() + .filter(|u| u.root == RootType::Table && u.kind != ResourceType::Sampler) + { let label = format!("s{}+{}", u.slot, u.table_offset_dwords); let Some(view) = entry(u.slot, u.table_offset_dwords) else { let _ = write!(text, "\n ~table {label} no view"); @@ -2442,13 +2657,22 @@ impl State { } } if uses(0, GLOBAL) - && let Some(slot) = t.used.iter().find(|u| u.root == RootType::Constants).map(|u| u.slot) + && let Some(slot) = t + .used + .iter() + .find(|u| u.root == RootType::Constants) + .map(|u| u.slot) && let Some(Root::Constants(words)) = self.roots_ref(false).get(usize::from(slot)) && let Some(&at) = words.get(1) - && let Some((base, len)) = entry(0, GLOBAL).as_ref().and_then(crate::descriptor::host::buffer_range) + && let Some((base, len)) = entry(0, GLOBAL) + .as_ref() + .and_then(crate::descriptor::host::buffer_range) { let at = u64::from(at); - let _ = write!(text, "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}"); + let _ = write!( + text, + "\n ~root constants {words:08x?}: record at {at:#x} of the buffer at {base:#x} bytes {len}" + ); if at + 64 <= len { Self::slot_words(&mut text, heap, "G", base + at, 64); } @@ -2610,7 +2834,8 @@ impl State { if census.0 != frame { let draws: u32 = census.1.values().sum(); if draws > 0 { - let mut rects: Vec<([i32; 4], u32)> = census.1.iter().map(|(r, n)| (*r, *n)).collect(); + let mut rects: Vec<([i32; 4], u32)> = + census.1.iter().map(|(r, n)| (*r, *n)).collect(); rects.sort_unstable_by_key(|r| std::cmp::Reverse(r.1)); let scissors: Vec = rects .iter() @@ -2652,12 +2877,6 @@ impl State { } } - - - - - - fn dispatch_mesh_emulated(&mut self, list: &HostList, p: &HostPipeline, x: u32) -> bool { #[cfg(feature = "diagnostics")] if crate::pipeline::is_skipped(self.pipeline as This) { @@ -2796,8 +3015,7 @@ impl State { why("indirect mesh arguments are unaligned or exceed the shader address range"); return false; } - let refresh_len = - len.min(u64::from(stride) * u64::from(record_count.max(1))); + let refresh_len = len.min(u64::from(stride) * u64::from(record_count.max(1))); args.refresh(list, arguments, refresh_len); if let Some((s, at)) = counter { s.refresh(list, at, 4); @@ -3097,7 +3315,10 @@ impl State { Some(view) => { host.make_at(index, &view); let kind = used.map(|u| u.kind).or_else(|| { - selected.binary_search(&k).ok().and_then(|_| view_kind(&view)) + selected + .binary_search(&k) + .ok() + .and_then(|_| view_kind(&view)) }); if let Some(kind) = kind { readable(list, kind, &view); @@ -3365,7 +3586,10 @@ impl State { // dropped before the argument clamp, like a skipped one. if crate::pipeline::walk_held(self.pipeline as This) { #[cfg(feature = "diagnostics")] - crate::pipeline::note_why("a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)".to_owned()); + crate::pipeline::note_why( + "a walk of ray-tracing structures that are not built (VICTORY_BVH_HOLD=1)" + .to_owned(), + ); return false; } const DRAW: u32 = 0; @@ -3463,15 +3687,41 @@ impl State { && !p.stages.iter().any(|stage| stage.translated().stores); // Another host list (a new one after a cut, or this one after its // reset) has another scratch buffer, or this one's with old bytes. - if !windowed || list.first_use(WINDOW_USE) { + let first_on_list = list.first_use(WINDOW_USE); + if !windowed || first_on_list { self.window = None; } + // Diagnostics: why this command gets a pass of ours, if it does. + #[cfg(feature = "diagnostics")] + let why_not = if !windows() { + usize::MAX + } else if kind == DISPATCH { + 1 + } else if max != 1 { + 2 + } else if count.is_some() { + 3 + } else if !windowed { + 4 + } else if first_on_list { + 5 + } else { + match &self.window { + None => 6, + Some(w) if !(w.copy == args.id() && w.kind == kind && w.stride == stride) => 6, + Some(w) if offset >= w.base && (offset - w.base) % u64::from(w.step) == 0 => 8, + Some(_) => 7, + } + }; let same = |w: &Window| w.copy == args.id() && w.kind == kind && w.stride == stride; let hit = self .window .as_ref() .filter(|w| same(w) && offset >= w.base) - .filter(|w| (offset - w.base) % u64::from(w.step) == 0 && (offset - w.base) / u64::from(w.step) < u64::from(w.records)) + .filter(|w| { + (offset - w.base) % u64::from(w.step) == 0 + && (offset - w.base) / u64::from(w.step) < u64::from(w.records) + }) .map(|w| (w.scratch.clone(), offset - w.base, w.step)); let (bounded, at) = match hit { Some((scratch, at, step)) => { @@ -3489,9 +3739,25 @@ impl State { self.host_pipeline = 0; self.host_roots[1] = 0; } + #[cfg(feature = "diagnostics")] + WINDOW_WHY[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + if !self.window_read { + self.window_read = true; + if let Some(w) = self.window.as_ref().filter(|w| w.records > 1) { + self.walk_step = Some((w.copy, w.kind, w.stride, w.step)); + } + } (scratch, at) } None => { + // A window opened at the remembered step that no draw read + // from: the title does not walk here by that step. + if self.window_jumped && !self.window_read { + self.walk_step = None; + #[cfg(feature = "diagnostics")] + WINDOW_WHY[11].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + } + self.window_jumped = false; // A record a short step after the last window's last one // (the same step as that window's, if it had one): the // title walks the buffer, so the ones that step apart @@ -3518,6 +3784,28 @@ impl State { } _ => (stride, max), }; + // A record that would be clamped alone, on a buffer whose + // step is remembered: the window the next record would + // open, opened here ([`jump_windows`]). + let (step, records) = match (windowed && records == 1 && jump_windows()) + .then(|| { + jump_window( + self.walk_step, + (args.id(), kind, stride), + args.left(arguments), + ) + }) + .flatten() + { + Some(jumped) => { + self.window_jumped = true; + #[cfg(feature = "diagnostics")] + WINDOW_WHY[10].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + jumped + } + None => (step, records), + }; + self.window_read = false; args.refresh( list, arguments, @@ -3551,6 +3839,42 @@ impl State { why("not bounded (no clamp, or arguments not 4-byte aligned)"); return false; }; + #[cfg(feature = "diagnostics")] + if why_not < WINDOW_WHY.len() { + WINDOW_WHY[why_not].fetch_add(1, std::sync::atomic::Ordering::Relaxed); + WINDOW_WHY[9] + .fetch_add(u64::from(records), std::sync::atomic::Ordering::Relaxed); + // One in 256 of the draws that miss their window, said: + // where the record lies against the window and against + // the record drawn before it. + if (6..=8).contains(&why_not) { + static N: std::sync::atomic::AtomicU64 = + std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(256) { + let (last_copy, last_offset) = self.last_indirect; + tracing::info!( + "a window miss (one in 256): cause {why_not}, kind {kind}, stride {stride}, buffer {} offset {offset:#x} ({} left); the command before it on the list: buffer {last_copy} offset \ + {last_offset:#x} (this one is {} bytes on); the window it missed: {}; clamped now: {records} records at step {step}", + args.id(), + args.left(arguments), + offset as i64 - last_offset as i64, + match &self.window { + Some(w) => format!( + "buffer {} kind {} stride {} base {:#x} step {} records {} (this record is {} bytes from its base)", + w.copy, + w.kind, + w.stride, + w.base, + w.step, + w.records, + offset as i64 - w.base as i64 + ), + None => "none".to_string(), + } + ); + } + } + } self.host_pipeline = 0; self.host_roots[1] = 0; self.window = windowed.then(|| Window { @@ -3565,6 +3889,10 @@ impl State { (bounded, 0) } }; + #[cfg(feature = "diagnostics")] + { + self.last_indirect = (args.id(), offset); + } let ran = match kind { DRAW | INDEXED => self.prepare(list, kind == INDEXED), MESH => self.prepare_for(list, false, true), @@ -3611,7 +3939,6 @@ impl State { } true } - } /// The host command signature for one argument of `kind` with records @@ -3801,7 +4128,11 @@ fn print_4k(at: u64) -> String { fn memory_state(at: u64, bytes: u64) -> String { let mapped = crate::texture::mapped_bytes(at as *const u8, bytes as usize); let last = at + bytes.saturating_sub(4096); - format!("memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", print_4k(at), print_4k(last)) + format!( + "memory={at:#x} mapped={mapped}/{bytes} first4k={} last4k={}", + print_4k(at), + print_4k(last) + ) } /// Title texture `this` for the frame listing: its size, whether it has a @@ -3813,7 +4144,11 @@ fn texture_state(this: This) -> String { return "not a texture".into(); }; // SAFETY: 56 bytes in the description's layout. - let words = unsafe { std::ptr::from_ref(&desc).cast::<[u32; 14]>().read_unaligned() }; + let words = unsafe { + std::ptr::from_ref(&desc) + .cast::<[u32; 14]>() + .read_unaligned() + }; let bytes = crate::resource::placed_bytes(&words).unwrap_or(0); let staged = match crate::texture::staged_state(this) { Some((uploaded, dirty)) => format!("staged=yes uploaded={uploaded} dirty={dirty}"), @@ -3854,14 +4189,18 @@ fn view_state(view: Option<&View>) -> String { }; // (Last, so that readers of the older lines still find // theirs: the level the view starts at, and how many it shows.) - format!("placed texture view_format={} {state} view_levels={}+{}", d[0], d[4], d[5] as i32) + format!( + "placed texture view_format={} {state} view_levels={}+{}", + d[0], d[4], d[5] as i32 + ) } Some(View::Shader(r, d)) if crate::resource::texture_memory(*r as This).is_some() => { format!( "texture object {r:#x} view_format={} {} view_levels={}", d.as_ref().map_or(0, |d| d[0]), texture_state(*r as This), - d.as_ref().map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32)) + d.as_ref() + .map_or("all".to_owned(), |d| format!("{}+{}", d[4], d[5] as i32)) ) } Some(v) => format!("{v:?}").chars().take(80).collect(), @@ -3875,7 +4214,10 @@ fn describe(view: Option<&View>) -> String { crate::resource::host_made(r).map(|t| { // SAFETY: a live resource. let d = unsafe { t.GetDesc() }; - format!("{}x{} f{} flags {:#x} of {r:?}", d.Width, d.Height, d.Format.0, d.Flags.0) + format!( + "{}x{} f{} flags {:#x} of {r:?}", + d.Width, d.Height, d.Format.0, d.Flags.0 + ) }) }; match view { @@ -3954,3 +4296,28 @@ pub(crate) fn depth_bounds(list: &HostList, min: f32, max: f32) { unsafe { l1.OMSetDepthBounds(min, max) }; } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_lone_record_opens_a_window_at_the_remembered_step() { + // (a mesh dispatch is kind 10, a draw kind 0) + let remembered = Some((7u64, 10u32, 12u32, 32u32)); + // the same buffer, kind and stride: sixteen records at the title's step + assert_eq!( + jump_window(remembered, (7, 10, 12), 1 << 20), + Some((32, 16)) + ); + // never past the buffer: 100 bytes left hold three records 32 apart + assert_eq!(jump_window(remembered, (7, 10, 12), 100), Some((32, 3))); + // one record fits: nothing to open + assert_eq!(jump_window(remembered, (7, 10, 12), 40), None); + // another buffer, kind or stride, or nothing remembered: alone, as before + assert_eq!(jump_window(remembered, (8, 10, 12), 1 << 20), None); + assert_eq!(jump_window(remembered, (7, 0, 12), 1 << 20), None); + assert_eq!(jump_window(remembered, (7, 10, 16), 1 << 20), None); + assert_eq!(jump_window(None, (7, 10, 12), 1 << 20), None); + } +} diff --git a/crates/victory-gpu/src/drvwatch.rs b/crates/victory-gpu/src/drvwatch.rs index 6024346b..11de997d 100644 --- a/crates/victory-gpu/src/drvwatch.rs +++ b/crates/victory-gpu/src/drvwatch.rs @@ -20,7 +20,8 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; use windows_sys::Win32::System::EventLog::{ - EVT_HANDLE, EVT_SUBSCRIBE_NOTIFY_ACTION, EvtSubscribe, EvtSubscribeActionDeliver, EvtSubscribeToFutureEvents, + EVT_HANDLE, EVT_SUBSCRIBE_NOTIFY_ACTION, EvtSubscribe, EvtSubscribeActionDeliver, + EvtSubscribeToFutureEvents, }; /// Entries of a display driver seen since the start. @@ -54,7 +55,11 @@ fn seen() { ); } -unsafe extern "system" fn on_event(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _context: *const core::ffi::c_void, _event: EVT_HANDLE) -> u32 { +unsafe extern "system" fn on_event( + action: EVT_SUBSCRIBE_NOTIFY_ACTION, + _context: *const core::ffi::c_void, + _event: EVT_HANDLE, +) -> u32 { if action == EvtSubscribeActionDeliver { seen(); } @@ -130,30 +135,60 @@ mod tests { #[ignore = "writes one entry to the Application event log: run it by name with --ignored"] fn an_entry_written_reaches_a_subscription() { use windows_sys::Win32::System::EventLog::{ - DeregisterEventSource, EVENTLOG_INFORMATION_TYPE, EvtClose, RegisterEventSourceW, ReportEventW, + DeregisterEventSource, EVENTLOG_INFORMATION_TYPE, EvtClose, RegisterEventSourceW, + ReportEventW, }; static GOT: AtomicU64 = AtomicU64::new(0); - unsafe extern "system" fn got(action: EVT_SUBSCRIBE_NOTIFY_ACTION, _: *const core::ffi::c_void, _: EVT_HANDLE) -> u32 { + unsafe extern "system" fn got( + action: EVT_SUBSCRIBE_NOTIFY_ACTION, + _: *const core::ffi::c_void, + _: EVT_HANDLE, + ) -> u32 { if action == EvtSubscribeActionDeliver { GOT.fetch_add(1, Relaxed); } 0 } let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; - let (channel, query) = (wide("Application"), wide("*[System[Provider[@Name='victory-drvwatch-test']]]")); + let (channel, query) = ( + wide("Application"), + wide("*[System[Provider[@Name='victory-drvwatch-test']]]"), + ); // SAFETY: as in `start`. let subscription = unsafe { - EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(got), EvtSubscribeToFutureEvents) + EvtSubscribe( + 0, + std::ptr::null_mut(), + channel.as_ptr(), + query.as_ptr(), + 0, + std::ptr::null(), + Some(got), + EvtSubscribeToFutureEvents, + ) }; assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); - let (name, text) = (wide("victory-drvwatch-test"), wide("a test entry of the VIctory layer's driver watch")); + let (name, text) = ( + wide("victory-drvwatch-test"), + wide("a test entry of the VIctory layer's driver watch"), + ); // SAFETY: a source of our own name, one string, no data. unsafe { let source = RegisterEventSourceW(std::ptr::null(), name.as_ptr()); assert!(!source.is_null(), "{}", std::io::Error::last_os_error()); let strings = [text.as_ptr()]; assert_ne!( - ReportEventW(source, EVENTLOG_INFORMATION_TYPE, 0, 1, std::ptr::null_mut(), 1, 0, strings.as_ptr(), std::ptr::null()), + ReportEventW( + source, + EVENTLOG_INFORMATION_TYPE, + 0, + 1, + std::ptr::null_mut(), + 1, + 0, + strings.as_ptr(), + std::ptr::null() + ), 0, "{}", std::io::Error::last_os_error() @@ -176,10 +211,22 @@ mod tests { #[test] fn the_system_takes_the_subscription() { let wide = |s: &str| -> Vec { s.encode_utf16().chain(std::iter::once(0)).collect() }; - let (channel, query) = (wide("System"), wide("*[System[Provider[@Name='nvlddmkm' or @Name='Display']]]")); + let (channel, query) = ( + wide("System"), + wide("*[System[Provider[@Name='nvlddmkm' or @Name='Display']]]"), + ); // SAFETY: as in `start`. let subscription = unsafe { - EvtSubscribe(0, std::ptr::null_mut(), channel.as_ptr(), query.as_ptr(), 0, std::ptr::null(), Some(on_event), EvtSubscribeToFutureEvents) + EvtSubscribe( + 0, + std::ptr::null_mut(), + channel.as_ptr(), + query.as_ptr(), + 0, + std::ptr::null(), + Some(on_event), + EvtSubscribeToFutureEvents, + ) }; assert_ne!(subscription, 0, "{}", std::io::Error::last_os_error()); // SAFETY: our own subscription. diff --git a/crates/victory-gpu/src/dxgi.rs b/crates/victory-gpu/src/dxgi.rs index af102270..a8972182 100644 --- a/crates/victory-gpu/src/dxgi.rs +++ b/crates/victory-gpu/src/dxgi.rs @@ -235,7 +235,11 @@ fn display_size() -> (u32, u32) { Some((w, h)) if (640..=7680).contains(&w) && (360..=4320).contains(&h) => (w, h), _ => (3840, 2160), }; - tracing::info!(width = size.0, height = size.1, "display mode reported to the title"); + tracing::info!( + width = size.0, + height = size.1, + "display mode reported to the title" + ); size }) } diff --git a/crates/victory-gpu/src/fence.rs b/crates/victory-gpu/src/fence.rs index 98daa899..8bab0bb6 100644 --- a/crates/victory-gpu/src/fence.rs +++ b/crates/victory-gpu/src/fence.rs @@ -30,6 +30,9 @@ struct Fence { flags: u32, /// Events to set once the value reaches theirs (handles as integers). waiters: Mutex>, + /// For [`pace`]: when each wait above was asked for. + #[cfg(all(windows, feature = "diagnostics"))] + asked: Mutex>, } fn fence<'a>(this: This) -> &'a Fence { @@ -50,6 +53,8 @@ pub(crate) extern "system" fn create( value: AtomicU64::new(initial), flags, waiters: Mutex::new(Vec::new()), + #[cfg(all(windows, feature = "diagnostics"))] + asked: Mutex::new(Vec::new()), }); object::hand_out(FENCE, fence, iid, &FENCE_IIDS, out) } @@ -85,8 +90,17 @@ extern "system" fn set_event_on_completion(this: This, value: u64, event: *mut c if !event.is_null() { set_event(event as usize); } + #[cfg(all(windows, feature = "diagnostics"))] + pace::ready(); return S_OK; } + #[cfg(all(windows, feature = "diagnostics"))] + pace::waits( + this, + &fence.asked, + value, + fence.value.load(Ordering::Acquire), + ); if event.is_null() { // With submissions sent to the card and not waited for // (`crate::host::late`) the signal may be behind them: they are @@ -114,6 +128,8 @@ pub(crate) fn set(this: This, value: u64) { let fence = fence(this); let mut waiters = fence.waiters.lock().unwrap_or_else(|e| e.into_inner()); fence.value.store(value, Ordering::Release); + #[cfg(all(windows, feature = "diagnostics"))] + pace::reached(this, &fence.asked, value); waiters.retain(|&(wanted, event)| { let reached = wanted <= value; if reached { @@ -138,6 +154,174 @@ extern "system" fn gpu_address(this: This) -> u64 { (&raw const fence(this).value) as u64 } +/// How the title paces itself on its fences, measured (diagnostics +/// builds): which value it waits for, how long until our line gets the +/// fence there, and how many frames lie between the title's `Signal` on +/// its queue and the fence being set. Run 233 put presents behind the +/// line and the frame did not get shorter: the title waited somewhere +/// else, and this says for what. +#[cfg(all(windows, feature = "diagnostics"))] +pub(crate) mod pace { + use std::sync::Mutex; + use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; + use std::time::Instant; + + use crate::object::This; + + pub(crate) struct Asked { + value: u64, + at: Instant, + frame: u64, + thread: u32, + } + + /// The title's `Signal` calls on a queue not yet at the fence: + /// fence, value, when, frame. + static QUEUED: Mutex> = Mutex::new(Vec::new()); + /// The thread that presents. + static RENDER: AtomicU32 = AtomicU32::new(0); + /// Since the last line: waits already met; waits not met; of those, + /// the render thread's; reached waits, their microseconds, their + /// frames between; the render thread's reached waits and microseconds; + /// signals set, their microseconds since the title's call, their + /// frames between. + static N: [AtomicU64; 11] = [const { AtomicU64::new(0) }; 11]; + static SAID: AtomicU64 = AtomicU64::new(0); + static LINE_AT: AtomicU64 = AtomicU64::new(0); + + /// Whether events are said one by one now: four seconds of every two + /// minutes of the wall clock, the same seconds in which the loader says + /// the title's `mwaitx` waits (`console_insn`), to lay the two side by side. + fn detail_now() -> bool { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .is_ok_and(|d| d.as_secs() % 120 < 4) + } + + fn thread() -> u32 { + // SAFETY: a plain query. + unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() } + } + + pub(super) fn ready() { + N[0].fetch_add(1, Ordering::Relaxed); + } + + pub(super) fn waits(fence: This, asked: &Mutex>, value: u64, now: u64) { + let thread = thread(); + let render = thread == RENDER.load(Ordering::Relaxed); + N[1].fetch_add(1, Ordering::Relaxed); + if render { + N[2].fetch_add(1, Ordering::Relaxed); + } + let frame = crate::queue::presented(); + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: the title waits for fence {fence:?} value {value} (it is at {now}) in frame {frame}, on {}", + if render { + "the render thread".to_string() + } else { + format!("thread {thread}") + } + ); + } + let mut asked = asked.lock().unwrap_or_else(|e| e.into_inner()); + if asked.len() < 4096 { + asked.push(Asked { + value, + at: Instant::now(), + frame, + thread, + }); + } + } + + /// The title called `Signal` for `fence` on a queue. + pub(crate) fn signal_called(fence: usize, value: u64) { + let mut queued = QUEUED.lock().unwrap_or_else(|e| e.into_inner()); + if queued.len() < 4096 { + queued.push((fence, value, Instant::now(), crate::queue::presented())); + } + } + + pub(super) fn reached(fence: This, asked: &Mutex>, value: u64) { + let frame = crate::queue::presented(); + let render = RENDER.load(Ordering::Relaxed); + { + let mut queued = QUEUED.lock().unwrap_or_else(|e| e.into_inner()); + queued.retain(|&(f, v, at, called)| { + let done = f == fence as usize && v <= value; + if done { + N[8].fetch_add(1, Ordering::Relaxed); + N[9].fetch_add(at.elapsed().as_micros() as u64, Ordering::Relaxed); + N[10].fetch_add(frame.saturating_sub(called), Ordering::Relaxed); + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: fence {fence:?} is set to {v}, {:.1} ms after the title's Signal for it (called in frame {called}, set in frame {frame})", + at.elapsed().as_micros() as f64 / 1e3 + ); + } + } + !done + }); + } + let mut asked = asked.lock().unwrap_or_else(|e| e.into_inner()); + asked.retain(|a| { + let done = a.value <= value; + if done { + let us = a.at.elapsed().as_micros() as u64; + N[3].fetch_add(1, Ordering::Relaxed); + N[4].fetch_add(us, Ordering::Relaxed); + N[5].fetch_add(frame.saturating_sub(a.frame), Ordering::Relaxed); + if a.thread == render { + N[6].fetch_add(1, Ordering::Relaxed); + N[7].fetch_add(us, Ordering::Relaxed); + } + if detail_now() || SAID.fetch_add(1, Ordering::Relaxed) < 48 { + tracing::info!( + "pace: fence {fence:?} reached {} {:.1} ms after the wait for it (asked in frame {}, reached in frame {frame})", + a.value, + us as f64 / 1e3, + a.frame + ); + } + } + !done + }); + } + + /// Once a frame, on the thread that presents: a line every 256 frames. + pub(crate) fn frame() { + RENDER.store(thread(), Ordering::Relaxed); + let frame = crate::queue::presented(); + let last = LINE_AT.load(Ordering::Relaxed); + if frame < last + 256 { + return; + } + LINE_AT.store(frame, Ordering::Relaxed); + let n: Vec = N + .iter() + .map(|n| n.swap(0, Ordering::Relaxed) as f64) + .collect(); + let frames = (frame - last).max(1) as f64; + let per = |a: f64, b: f64| if b > 0.0 { a / b } else { 0.0 }; + tracing::info!( + "pace, per frame: fence waits already met {:.2}, not met {:.2} (the render thread's {:.2}); a wait is met {:.1} ms and {:.2} frames after it was asked \ + (the render thread's: {:.1} ms, {:.1} ms a frame); the title's queue signals: {:.2} a frame, a fence is set {:.1} ms and {:.2} frames after the title's Signal call", + n[0] / frames, + n[1] / frames, + n[2] / frames, + per(n[4], n[3]) / 1e3, + per(n[5], n[3]), + per(n[7], n[6]) / 1e3, + n[7] / frames / 1e3, + n[8] / frames, + per(n[9], n[8]) / 1e3, + per(n[10], n[8]), + ); + } +} + /// IUnknown 3, object 4, device child 1, fence 3, fence 1 (2, a console /// one among them). static FUNCTIONS: Table<24> = { diff --git a/crates/victory-gpu/src/framelog.rs b/crates/victory-gpu/src/framelog.rs index 0d90bae5..9a62c15b 100644 --- a/crates/victory-gpu/src/framelog.rs +++ b/crates/victory-gpu/src/framelog.rs @@ -178,19 +178,37 @@ pub fn on_slow_core() -> bool { /// The system's processor sets of group 0: each one's id, its logical /// processor and its efficiency class (higher is faster). fn cpu_sets() -> Vec<(u32, u8, u8)> { - use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION}; + use windows_sys::Win32::System::SystemInformation::{ + GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION, + }; use windows_sys::Win32::System::Threading::GetCurrentProcess; let mut bytes = 0u32; // SAFETY: a size query, then the call into a buffer of that size. - unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) }; + unsafe { + GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) + }; let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)]; // SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records. - let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) }; + let ok = unsafe { + GetSystemCpuSetInformation( + buffer.as_mut_ptr().cast(), + bytes, + &mut bytes, + GetCurrentProcess(), + 0, + ) + }; let mut sets = Vec::new(); let mut at = 0usize; while ok != 0 && at + size_of::() <= bytes as usize { // SAFETY: a record inside the buffer; each says its own size. - let info = unsafe { &*(buffer.as_ptr().cast::().add(at).cast::()) }; + let info = unsafe { + &*(buffer + .as_ptr() + .cast::() + .add(at) + .cast::()) + }; if info.Size == 0 { break; } @@ -204,6 +222,16 @@ fn cpu_sets() -> Vec<(u32, u8, u8)> { sets } +/// The slow logical processors of group 0 as a mask (a lower efficiency +/// class than the best): 0 where all cores are alike. +pub fn slow_processors() -> usize { + let sets = cpu_sets(); + let best = sets.iter().map(|c| c.2).max().unwrap_or(0); + sets.iter() + .filter(|c| c.2 < best && c.1 < usize::BITS as u8) + .fold(0, |mask, c| mask | 1usize << c.1) +} + /// Asks the system to run the calling thread on the fast cores only, where /// the processor has two kinds (`VICTORY_FAST_CORES=0`: not asked). /// @@ -227,11 +255,17 @@ pub fn keep_on_fast_cores(what: &str) { return; } // SAFETY: our own thread and a list of the system's own set ids. - let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; + let ok = + unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) }; if ok == 0 { tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores"); } else { - tracing::info!(what, fast = fast.len(), of = sets.len(), "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)"); + tracing::info!( + what, + fast = fast.len(), + of = sets.len(), + "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)" + ); } } @@ -255,10 +289,18 @@ pub fn keep_on_slow_cores(what: &str) -> bool { return false; } // SAFETY: our own thread and a list of the system's own set ids. - let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), slow.as_ptr(), slow.len() as u32) } != 0; + let ok = + unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), slow.as_ptr(), slow.len() as u32) } + != 0; static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { - tracing::info!(what, slow = slow.len(), of = sets.len(), ok, "helper threads are kept on the slow cores: the first one"); + tracing::info!( + what, + slow = slow.len(), + of = sets.len(), + ok, + "helper threads are kept on the slow cores: the first one" + ); }); ok } @@ -280,10 +322,21 @@ fn micros(t: windows_sys::Win32::Foundation::FILETIME) -> u64 { pub fn thread_times() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentThread, GetThreadTimes}; - let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); // SAFETY: our own thread and four valid out pointers. - unsafe { GetThreadTimes(GetCurrentThread(), &mut created, &mut exited, &mut kernel, &mut user) }; + unsafe { + GetThreadTimes( + GetCurrentThread(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; (micros(user), micros(kernel)) } @@ -291,16 +344,29 @@ pub fn thread_times() -> (u64, u64) { fn process_times() -> (u64, u64) { use windows_sys::Win32::Foundation::FILETIME; use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes}; - let zero = FILETIME { dwLowDateTime: 0, dwHighDateTime: 0 }; + let zero = FILETIME { + dwLowDateTime: 0, + dwHighDateTime: 0, + }; let (mut created, mut exited, mut kernel, mut user) = (zero, zero, zero, zero); // SAFETY: our own process and four valid out pointers. - unsafe { GetProcessTimes(GetCurrentProcess(), &mut created, &mut exited, &mut kernel, &mut user) }; + unsafe { + GetProcessTimes( + GetCurrentProcess(), + &mut created, + &mut exited, + &mut kernel, + &mut user, + ) + }; (micros(user), micros(kernel)) } /// The process's page faults so far (soft and hard). fn page_faults() -> u64 { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; use windows_sys::Win32::System::Threading::GetCurrentProcess; // SAFETY: plain data the call fills in. let mut c: PROCESS_MEMORY_COUNTERS = unsafe { std::mem::zeroed() }; @@ -471,7 +537,14 @@ fn text(f: &Frame) -> String { /// The mean of `frames` (not empty). fn mean(frames: &[&Frame]) -> Frame { let n = frames.len() as f64; - let mut out = Frame { number: 0, at: 0.0, us: 0.0, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + let mut out = Frame { + number: 0, + at: 0.0, + us: 0.0, + t: [0.0; N], + s: [0.0; S], + h: [0.0; HN], + }; for f in frames { out.us += f.us / n; for i in 0..N { @@ -497,7 +570,10 @@ fn long_over(usual: f64) -> f64 { fn lines(frames: &[Frame], usual: f64, seconds: f64) -> Vec { let over = long_over(usual); let (long, plain): (Vec<&Frame>, Vec<&Frame>) = frames.iter().partition(|f| f.us > over); - let each: Vec = frames.iter().map(|f| format!("{:.0}", f.us / 1e3)).collect(); + let each: Vec = frames + .iter() + .map(|f| format!("{:.0}", f.us / 1e3)) + .collect(); let shortest = frames.iter().map(|f| f.us).fold(f64::INFINITY, f64::min); let longest = frames.iter().map(|f| f.us).fold(0.0, f64::max); let mut out = vec![format!( @@ -513,13 +589,25 @@ fn lines(frames: &[Frame], usual: f64, seconds: f64) -> Vec { each.join(" ") )]; if !plain.is_empty() { - out.push(format!("usual frame (the mean of {} not long): {}", plain.len(), text(&mean(&plain)))); + out.push(format!( + "usual frame (the mean of {} not long): {}", + plain.len(), + text(&mean(&plain)) + )); } for f in long.iter().take(LONG_MOST) { - out.push(format!("long frame {} at {:.1} s: {}", f.number, f.at, text(f))); + out.push(format!( + "long frame {} at {:.1} s: {}", + f.number, + f.at, + text(f) + )); } if long.len() > LONG_MOST { - out.push(format!("long frames: {} more in this reading are not listed", long.len() - LONG_MOST)); + out.push(format!( + "long frames: {} more in this reading are not listed", + long.len() - LONG_MOST + )); } out } @@ -597,7 +685,14 @@ mod tests { use super::*; fn frame(number: u64, ms: f64) -> Frame { - let mut f = Frame { number, at: number as f64, us: ms * 1e3, t: [0.0; N], s: [0.0; S], h: [0.0; HN] }; + let mut f = Frame { + number, + at: number as f64, + us: ms * 1e3, + t: [0.0; N], + s: [0.0; S], + h: [0.0; HN], + }; f.t[T::PresentUs as usize] = ms * 100.0; f.t[T::Uploads as usize] = ms; f @@ -605,16 +700,28 @@ mod tests { #[test] fn a_long_frame_is_listed_beside_the_usual_one() { - let frames: Vec = [150.0, 160.0, 140.0, 400.0, 150.0].iter().enumerate().map(|(i, &ms)| frame(i as u64, ms)).collect(); + let frames: Vec = [150.0, 160.0, 140.0, 400.0, 150.0] + .iter() + .enumerate() + .map(|(i, &ms)| frame(i as u64, ms)) + .collect(); let out = lines(&frames, 150_000.0, 1.0); assert_eq!(out.len(), 3, "{out:#?}"); assert!(out[0].starts_with("frame times: 5 frames in 1.0 s: shortest 140 ms, median 150, longest 400; 1 long (over 225 ms"), "{}", out[0]); assert!(out[0].ends_with("each: 150 160 140 400 150"), "{}", out[0]); // The usual frame is the mean of the four that are not long. - assert!(out[1].starts_with("usual frame (the mean of 4 not long): 150 ms |"), "{}", out[1]); + assert!( + out[1].starts_with("usual frame (the mean of 4 not long): 150 ms |"), + "{}", + out[1] + ); assert!(out[1].contains("in the present call 15.0 "), "{}", out[1]); assert!(out[1].contains(" 150 uploads"), "{}", out[1]); - assert!(out[2].starts_with("long frame 3 at 3.0 s: 400 ms |"), "{}", out[2]); + assert!( + out[2].starts_with("long frame 3 at 3.0 s: 400 ms |"), + "{}", + out[2] + ); assert!(out[2].contains("in the present call 40.0 "), "{}", out[2]); assert!(out[2].contains(" 400 uploads"), "{}", out[2]); } @@ -630,8 +737,14 @@ mod tests { let mut frames: Vec = (0..12).map(|i| frame(i, 500.0)).collect(); frames.push(frame(12, 100.0)); let out = lines(&frames, 100_000.0, 5.0); - assert_eq!(out.iter().filter(|l| l.starts_with("long frame ")).count(), LONG_MOST); - assert!(out.last().unwrap().starts_with("long frames: 4 more"), "{out:#?}"); + assert_eq!( + out.iter().filter(|l| l.starts_with("long frame ")).count(), + LONG_MOST + ); + assert!( + out.last().unwrap().starts_with("long frames: 4 more"), + "{out:#?}" + ); } #[test] diff --git a/crates/victory-gpu/src/host.rs b/crates/victory-gpu/src/host.rs index 0264bbac..501985fd 100644 --- a/crates/victory-gpu/src/host.rs +++ b/crates/victory-gpu/src/host.rs @@ -85,7 +85,10 @@ unsafe impl Send for Retired {} /// Milliseconds since the first call. pub(crate) fn now_ms() -> u64 { static EPOCH: OnceLock = OnceLock::new(); - EPOCH.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_millis() as u64 } /// This moment, for telling later how long ago it was ([`long_ago`]): the @@ -238,7 +241,8 @@ fn bury(finished: u64) { /// Objects [`retire`] dropped at once (no submission was running) and /// kept until a running submission finished, since the start. -static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// What the layer did to the host's objects lately, newest last (sweeps /// that let host copies go, pipeline library calls, saves and trims): said @@ -249,7 +253,8 @@ static RETIREMENTS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atom /// the three such losses of runs 72, 73 and 82 each came within 5 ms of a /// pipeline library call that no line of the log tied to them. /// `VICTORY_TRAIL=0`: nothing is kept and nothing is said. -static TRAIL: Mutex> = Mutex::new(std::collections::VecDeque::new()); +static TRAIL: Mutex> = + Mutex::new(std::collections::VecDeque::new()); /// The entries kept. const TRAIL_MOST: usize = 96; @@ -261,7 +266,10 @@ fn trail_on() -> bool { /// Microseconds since the first call. pub(crate) fn now_us() -> u64 { static EPOCH: OnceLock = OnceLock::new(); - EPOCH.get_or_init(std::time::Instant::now).elapsed().as_micros() as u64 + EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_micros() as u64 } /// The calling thread, as the log's other lines name threads. @@ -294,7 +302,8 @@ pub(crate) fn trail(what: impl FnOnce() -> String) { /// What the submitting thread is doing (0 nothing: between submissions, /// 1 preparing one, 2 waiting for the card to run it, 3 copying back what /// it wrote), the lists of that submission, and since when ([`now_us`]). -static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +static SUBMITTING: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; fn submitting(phase: u64, lists: usize) { SUBMITTING[1].store(lists as u64, Ordering::Relaxed); @@ -328,7 +337,11 @@ pub(crate) fn removal_context() -> String { let trail = TRAIL.lock().unwrap_or_else(|e| e.into_inner()); let _ = write!(text, "; the last {} things done, newest last:", trail.len()); for (at, thread, what) in trail.iter() { - let _ = write!(text, "\n {:.1} ms before, thread {thread}: {what}", ms(*at)); + let _ = write!( + text, + "\n {:.1} ms before, thread {thread}: {what}", + ms(*at) + ); } text } @@ -354,7 +367,13 @@ static SUBMISSION_US: [std::sync::atomic::AtomicU64; 2] = [ /// Adds to [`SUBMISSION_US`] and to the frame log's totals. fn submission_us(i: usize, us: u64) { SUBMISSION_US[i].fetch_add(us, Ordering::Relaxed); - crate::framelog::add([crate::framelog::T::PrepareUs, crate::framelog::T::CardWaitUs][i], us); + crate::framelog::add( + [ + crate::framelog::T::PrepareUs, + crate::framelog::T::CardWaitUs, + ][i], + us, + ); if i == 0 { crate::framelog::add(crate::framelog::T::Submissions, 1); } @@ -363,13 +382,22 @@ fn submission_us(i: usize, us: u64) { /// Adds to [`PREPARING`]'s copies (time, bytes) and to the frame log's totals. fn preparing(i: usize, n: u64) { PREPARING[i].fetch_add(n, Ordering::Relaxed); - crate::framelog::add([crate::framelog::T::CopyUs, crate::framelog::T::CopyBytes][i], n); + crate::framelog::add( + [crate::framelog::T::CopyUs, crate::framelog::T::CopyBytes][i], + n, + ); } /// Adds to [`COPY_BACK`] and to the frame log's totals. fn copy_back(i: usize, n: u64) { COPY_BACK[i].fetch_add(n, Ordering::Relaxed); - crate::framelog::add([crate::framelog::T::CopyBackUs, crate::framelog::T::CopyBackBytes][i], n); + crate::framelog::add( + [ + crate::framelog::T::CopyBackUs, + crate::framelog::T::CopyBackBytes, + ][i], + n, + ); } /// Adds to [`CARD_CLOCK_US`] and, for the card's idle times, to the frame @@ -401,12 +429,14 @@ static COPY_BACK: [std::sync::atomic::AtomicU64; 2] = [ /// the clock's own ([`Host::card_sent`]). A thread of the clock waits for /// the newest signal and notes the moment the card reached it with nothing /// newer sent; the next send ends that idle stretch. -static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +static CARD_CLOCK_US: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; /// Of the thread that holds the submission lock: the microseconds it has /// worked so far (preparing, copying back; not its waits for the card), and /// since when it works now ([`now_us`] plus one; 0: it does not). -static WORKING: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static WORKING: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// The thread that holds the submission lock starts (`on`) or stops /// working; whether it worked until now. @@ -422,7 +452,11 @@ fn working(on: bool) -> bool { /// [`WORKING`] as of now: microseconds worked so far. fn worked() -> u64 { let since = WORKING[1].load(Ordering::Relaxed); - let now = if since != 0 { (now_us() + 1).saturating_sub(since) } else { 0 }; + let now = if since != 0 { + (now_us() + 1).saturating_sub(since) + } else { + 0 + }; WORKING[0].load(Ordering::Relaxed) + now } @@ -479,12 +513,17 @@ fn card_clock_watch(clock: &'static CardClock) { /// For the frame-rate line: [`CARD_CLOCK_US`] per frame, `ms` being the /// frame's time. fn card_clock_line(frames: f64, ms: f64) { - let [idle, behind, stood] = [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); + let [idle, behind, stood] = + [0, 1, 2].map(|i| CARD_CLOCK_US[i].swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames); tracing::info!( "the card's clock per frame: nothing of ours queued {idle:.1} ms (the card about {:.0}% busy by this count), \ {behind:.1} ms of that while the submitting thread was working (the card idle behind us), the rest while the title \ had not submitted; the submitting thread stood waiting for the card {stood:.1} ms", - if ms > 0.0 { (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) } else { 0.0 } + if ms > 0.0 { + (100.0 * (1.0 - idle / ms)).clamp(0.0, 100.0) + } else { + 0.0 + } ); } @@ -501,7 +540,8 @@ pub(crate) static PREPARING: [std::sync::atomic::AtomicU64; 4] = [ /// (staging, list scratch), shared with the processor (host copies of title /// memory) and the graphics card's own (indirect arguments, twins' copies). /// For the memory line: against what is alive, they show what was let go. -pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync::atomic::AtomicU64::new(0) }; 6]; +pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = + [const { std::sync::atomic::AtomicU64::new(0) }; 6]; /// What of that is alive now, for the memory line (`MADE` counts what was /// ever made: 42,607 upload buffers, 77.9 GB, in five minutes of run 60, @@ -511,7 +551,8 @@ pub(crate) static MADE: [std::sync::atomic::AtomicU64; 6] = [const { std::sync:: /// instead of made, since the start; and the lists' other upload buffers /// (texture data copied from buffers, scratch too big for a chunk) and /// their bytes. -pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = [const { std::sync::atomic::AtomicU64::new(0) }; 8]; +pub(crate) static ALIVE: [std::sync::atomic::AtomicU64; 8] = + [const { std::sync::atomic::AtomicU64::new(0) }; 8]; /// About host lists, for the memory line: lists made by the host since the /// start; preludes made (a list's second allocator and list, made when it @@ -597,6 +638,7 @@ pub(crate) fn host() -> Option<&'static Host> { fn create() -> windows::core::Result { crate::drvwatch::start(); + crate::spread::start(); // SAFETY: plain D3D12 object creation with valid descriptions. unsafe { // The debug layer only in builds with diagnostics. @@ -653,7 +695,10 @@ fn create() -> windows::core::Result { "host device on the largest-memory hardware adapter" ), Ok(()) => { - tracing::warn!(adapter = name, "hardware adapter lacks shader model 6.6; using the default adapter"); + tracing::warn!( + adapter = name, + "hardware adapter lacks shader model 6.6; using the default adapter" + ); device = None; D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device)?; } @@ -767,7 +812,7 @@ fn shader_model66(device: &ID3D12Device) -> bool { ) } .is_ok() - && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0 + && model.HighestShaderModel.0 >= D3D_SHADER_MODEL_6_6.0 } /// The hardware adapter with the most dedicated video memory, if DXGI knows @@ -845,17 +890,26 @@ mod tests { let mut expected = vec![0; N]; for (offset, value) in [(0, 9), (2 << 16, 37), (N - 4096, 85)] { let at = base.add(offset); - assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + assert_eq!( + VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), + at.cast() + ); at.write_bytes(value, 4096); expected[offset..offset + 4096].fill(value); } for remap in [false, true] { if remap { let mut old = 0; - assert_ne!(VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), 0); + assert_ne!( + VirtualProtect(base.cast(), 4096, PAGE_NOACCESS, &mut old), + 0 + ); expected[..4096].fill(0); let at = base.add(1 << 16); - assert_eq!(VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), at.cast()); + assert_eq!( + VirtualAlloc(at.cast(), 4096, MEM_COMMIT, PAGE_READWRITE), + at.cast() + ); at.write_bytes(0xc7, 4096); expected[1 << 16..(1 << 16) + 4096].fill(0xc7); } @@ -944,6 +998,9 @@ pub(crate) struct HostList { /// The pair of timestamps its run is timed with since its last reset /// (`crate::cardmeter`), or none. meter: AtomicU32, + /// With `crate::cardmeter::pipelines`: the pair of the pipeline bound + /// last, open until the next one is bound or the list closes. + pipeline_meter: AtomicU32, /// The texts of the markers `note_op` set, in order (for device-removed /// data without marker texts), with the host GPU range a copy reads. #[cfg(feature = "diagnostics")] @@ -1414,7 +1471,8 @@ pub(crate) fn dred_on() -> bool { /// Indirect mesh dispatches since the last frame line: the largest group /// count a record asked for, and the groups asked in all (from the lists' /// budget buffers, a run late). -static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static MESH_GROUPS: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// Whether a list's indirect-work budget lives in the card's own memory /// (`VICTORY_INDIRECT_CARD_BUDGET=0` keeps it in memory the CPU maps, as @@ -1752,7 +1810,9 @@ void main(uint3 id : SV_DispatchThreadID) { /// exact and when a landing falls back to the old fetch. fn inflight_fetch() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| relay() && std::env::var_os("VICTORY_CARD_FETCH_INFLIGHT").is_some_and(|v| v == "1")) + *ON.get_or_init(|| { + relay() && std::env::var_os("VICTORY_CARD_FETCH_INFLIGHT").is_some_and(|v| v == "1") + }) } /// The bytes of the PC's memory pieces fetched inside flights go to @@ -1762,7 +1822,12 @@ fn inflight_fetch() -> bool { fn inflight_fetch_bytes() -> u64 { static MOST: OnceLock = OnceLock::new(); *MOST.get_or_init(|| { - std::env::var("VICTORY_CARD_FETCH_INFLIGHT_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(64).max(1) << 20 + std::env::var("VICTORY_CARD_FETCH_INFLIGHT_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(64) + .max(1) + << 20 }) } @@ -1892,11 +1957,13 @@ void main(uint3 group : SV_GroupID, uint t : SV_GroupIndex) { fn rehash_runs() -> bool { /// 0 off, 1 on, 2 in turn. static MODE: OnceLock = OnceLock::new(); - match *MODE.get_or_init(|| match std::env::var("VICTORY_CARD_REHASH_RUNS").as_deref() { - Ok("1") => 1, - Ok("alt") => 2, - _ => 0, - }) { + match *MODE.get_or_init( + || match std::env::var("VICTORY_CARD_REHASH_RUNS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }, + ) { 0 => false, 1 => true, _ => { @@ -1905,7 +1972,11 @@ fn rehash_runs() -> bool { if LAST.swap(u8::from(joined), Ordering::Relaxed) != u8::from(joined) { tracing::info!( "card rehash passes from now (VICTORY_CARD_REHASH_RUNS=alt): {}", - if joined { "JOINED, one pass a run of touching pieces" } else { "one pass a range sent up, as usual" } + if joined { + "JOINED, one pass a run of touching pieces" + } else { + "one pass a range sent up, as usual" + } ); } joined @@ -1916,7 +1987,8 @@ fn rehash_runs() -> bool { /// Since the last frame-rate line, of our own passes over copies in the /// card's memory: hash passes after ranges were sent up, the pieces they /// hashed, and compare passes after the lists. -static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +static CARD_PASSES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; /// Whether what shaders wrote to copies in the card's memory is merged /// into title memory on several threads (`VICTORY_WIDE_MERGE=1`; off by @@ -2224,13 +2296,15 @@ static QUEUE_ORDER: Mutex = Mutex::new(0); /// ([`relay`]): landings, flights landed, microseconds it waited for the /// card with nothing to land, microseconds it waited for fetches of card /// copies' pieces, microseconds of landing in all. -static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; +static RELAY_STATS: [std::sync::atomic::AtomicU64; 5] = + [const { std::sync::atomic::AtomicU64::new(0) }; 5]; /// Since the last frame-rate line, with [`inflight_fetch`]: pieces merged /// from the slots their flights fetched them to, their bytes, landings that /// went the old way because a plan's pieces overflowed the slots, and /// landings that fetched the old way (for any reason, overflow too). -static INFLIGHT_STATS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +static INFLIGHT_STATS: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// After a fetch the old way taken with the queue's count at `after`, for /// plans whose highest send is `landed`: up to which send the notes of @@ -2263,7 +2337,11 @@ pub(crate) fn fallback_fetched_mark(inflight: bool, after: u64, landed: Option u32 { let next = k.wrapping_add(1); - if (next.wrapping_sub(landed) as i32) > 0 { next } else { landed } + if (next.wrapping_sub(landed) as i32) > 0 { + next + } else { + landed + } } /// With [`inflight_fetch`], after a landing merged (either way): the tickets @@ -2287,7 +2365,8 @@ fn inflight_tickets_landed(plans: &[&CardPlan]) { return; }; // SAFETY: the mapping of the tickets; these plans' fetches have run. - let table = unsafe { std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords) }; + let table = + unsafe { std::slice::from_raw_parts((inflight.table.1 as *const u32).add(1), dwords) }; for plan in plans.iter().filter(|p| p.inflight) { for r in plan.ranges.iter().filter(|r| r.compared) { for p in 0..r.span.pieces { @@ -2313,7 +2392,9 @@ fn inflight_tickets_landed(plans: &[&CardPlan]) { /// later flight never lands before an earlier one, and what follows a /// flight (its bottom-of-pipe writes, signals) never before the flight. fn landable(line: &[Option], completed: u64) -> usize { - line.iter().position(|f| f.is_some_and(|f| f > completed)).unwrap_or(line.len()) + line.iter() + .position(|f| f.is_some_and(|f| f > completed)) + .unwrap_or(line.len()) } /// For one plan of copies in the card's memory, with [`relay`]: `flags` @@ -2363,7 +2444,8 @@ static BESIDE: Mutex>> = Mut /// Since the last frame-rate line: pieces fetched because an earlier fetch /// of them ran beside their flight ([`BESIDE`]), and pieces noted there. -static BESIDE_STATS: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static BESIDE_STATS: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// [`BESIDE`]: whether the flight numbered `number` (among the submissions /// started) must fetch a piece that an earlier landing's fetch brought @@ -2380,7 +2462,12 @@ fn fetched_beside(started: Option, number: u64) -> bool { /// landed (each fetched the piece again if it declared it); the pieces /// just fetched are noted if anything later than the flights landed had /// started. -fn note_beside(noted: &mut std::collections::HashMap<(usize, u32), u64>, fetched: &[(usize, u32)], landed: u64, started: u64) -> u64 { +fn note_beside( + noted: &mut std::collections::HashMap<(usize, u32), u64>, + fetched: &[(usize, u32)], + landed: u64, + started: u64, +) -> u64 { noted.retain(|_, upto| *upto > landed); if started <= landed { return 0; @@ -2478,7 +2565,11 @@ mod relay_tests { fn late_most() -> usize { static MOST: OnceLock = OnceLock::new(); *MOST.get_or_init(|| { - std::env::var("VICTORY_LATE_WAIT_LISTS").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(256).max(1) + std::env::var("VICTORY_LATE_WAIT_LISTS") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(256) + .max(1) }) } @@ -2590,11 +2681,13 @@ const WHY_FENCE: usize = 10; /// bottom-of-pipe write; fence signals set behind flights. /// Then: the settles for title memory read, by what read it (a buffer /// copy, a fill of upload memory, a texture). -static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = [const { std::sync::atomic::AtomicU64::new(0) }; 18]; +static LATE_STATS: [std::sync::atomic::AtomicU64; 18] = + [const { std::sync::atomic::AtomicU64::new(0) }; 18]; /// Since the last frame-rate line: the microseconds settles waited for the /// card, by why they settled (the `WHY_` places). -static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = [const { std::sync::atomic::AtomicU64::new(0) }; 11]; +static LATE_WAITED: [std::sync::atomic::AtomicU64; 11] = + [const { std::sync::atomic::AtomicU64::new(0) }; 11]; /// Whether `[from, to)` touches one of `ranges` (in order, joined). fn touches(ranges: &[(usize, usize)], from: usize, to: usize) -> bool { @@ -2779,7 +2872,8 @@ mod fill_ahead { pub(super) fn on() -> bool { static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_WAIT").is_none_or(|v| v != "1")) && !WAIT.load(Relaxed) + *ON.get_or_init(|| std::env::var_os("VICTORY_FILL_WAIT").is_none_or(|v| v != "1")) + && !WAIT.load(Relaxed) } /// A fill reads `len` bytes at `src` ahead of flights that may write @@ -2798,7 +2892,8 @@ mod fill_ahead { p.pruned = frame; p.fills.retain(|f| f.2 + KEEP >= frame); } - p.fills.push((src, src + len, frame, super::STARTED.load(Relaxed))); + p.fills + .push((src, src + len, frame, super::STARTED.load(Relaxed))); } } @@ -2817,7 +2912,9 @@ mod fill_ahead { (at / PIECE..=(end - 1) / PIECE) .filter_map(|piece| map.get(&piece)) .flat_map(|p| p.fills.iter().copied()) - .filter(|f| f.0 < end && f.1 > at && f.2 + KEEP >= frame && (landing == 0 || landing <= f.3)) + .filter(|f| { + f.0 < end && f.1 > at && f.2 + KEEP >= frame && (landing == 0 || landing <= f.3) + }) .map(|f| (f.0, f.1, f.2)) .collect() }; @@ -2836,7 +2933,11 @@ mod fill_ahead { continue; } let n = COUNT[2].fetch_add(1, Relaxed) + 1; - let first = now.iter().zip(&new[a - at..b - at]).position(|(x, y)| x != y).unwrap_or(0); + let first = now + .iter() + .zip(&new[a - at..b - at]) + .position(|(x, y)| x != y) + .unwrap_or(0); if !WAIT.swap(true, Relaxed) { tracing::warn!( "a fill of upload memory read {} bytes at {from:#x} in frame {read_in} ahead of a flight whose shaders changed \ @@ -2874,7 +2975,11 @@ mod fill_ahead { ahead as f64 / frames, looked as f64 / frames, COUNT[2].load(Relaxed), - if WAIT.load(Relaxed) { " (fills wait again)" } else { "" } + if WAIT.load(Relaxed) { + " (fills wait again)" + } else { + "" + } ); } } @@ -2939,7 +3044,9 @@ mod fill_check { if !pending.as_ref().is_some_and(|p| (p.0, p.1) == (src, len)) { return; } - let Some((_, _, before)) = pending.take() else { return }; + let Some((_, _, before)) = pending.take() else { + return; + }; drop(pending); let mut now = vec![0u8; before.len()]; if !super::read_into(src as *const u8, &mut now) { @@ -2951,7 +3058,11 @@ mod fill_check { let bad = CHECKED[1].fetch_add(1, Relaxed) + 1; CHECKED[2].fetch_add(differ, Relaxed); if bad <= 12 { - let first = before.iter().zip(&now).position(|(a, b)| a != b).unwrap_or(0); + let first = before + .iter() + .zip(&now) + .position(|(a, b)| a != b) + .unwrap_or(0); tracing::info!( "a fill of upload memory that waited for flights read other bytes after the wait: {differ} of {len} bytes at {src:#x} changed, the first at +{first:#x} (check {n}, frame {})", crate::frame::current() @@ -3003,7 +3114,8 @@ mod fill_check { drop(seen); let n = len.min(1 << 20); let (mut a, mut b) = (vec![0u8; n], vec![0u8; n]); - if super::read_into(src as *const u8, &mut a) && super::read_into(dst as *const u8, &mut b) { + if super::read_into(src as *const u8, &mut a) && super::read_into(dst as *const u8, &mut b) + { *PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()) = Some((dst, src, len, a, b)); } } @@ -3011,13 +3123,20 @@ mod fill_check { /// The title buffer copy runs now. pub(super) fn copy_runs(dst: usize, src: usize, len: usize) { let mut pending = PENDING_COPY.lock().unwrap_or_else(|e| e.into_inner()); - if !pending.as_ref().is_some_and(|p| (p.0, p.1, p.2) == (dst, src, len)) { + if !pending + .as_ref() + .is_some_and(|p| (p.0, p.1, p.2) == (dst, src, len)) + { return; } - let Some((_, _, _, src_before, dst_before)) = pending.take() else { return }; + let Some((_, _, _, src_before, dst_before)) = pending.take() else { + return; + }; drop(pending); let (mut a, mut b) = (vec![0u8; src_before.len()], vec![0u8; dst_before.len()]); - if !super::read_into(src as *const u8, &mut a) || !super::read_into(dst as *const u8, &mut b) { + if !super::read_into(src as *const u8, &mut a) + || !super::read_into(dst as *const u8, &mut b) + { return; } let n = COPIES[0].fetch_add(1, Relaxed) + 1; @@ -3046,8 +3165,11 @@ mod fill_check { let seen = SEEN_COPIES.lock().unwrap_or_else(|e| e.into_inner()); let mut most: Vec<_> = seen.clone(); most.sort_unstable_by_key(|s| std::cmp::Reverse(s.3)); - let most: Vec = - most.iter().take(6).map(|s| format!("{:#x}->{:#x}+{:#x} {}x", s.0, s.1, s.2, s.3)).collect(); + let most: Vec = most + .iter() + .take(6) + .map(|s| format!("{:#x}->{:#x}+{:#x} {}x", s.0, s.1, s.2, s.3)) + .collect(); tracing::info!( "title buffer copies that waited for flights, since the start: {copies} checked after their wait; the source had other bytes after it {} times, the destination {} times; {} distinct copies, the most frequent: {}", COPIES[1].load(Relaxed), @@ -3063,7 +3185,11 @@ mod fill_check { let seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); let mut most: Vec<_> = seen.clone(); most.sort_unstable_by_key(|s| std::cmp::Reverse(s.2)); - let most: Vec = most.iter().take(6).map(|s| format!("{:#x}+{:#x} {}x", s.0, s.1, s.2)).collect(); + let most: Vec = most + .iter() + .take(6) + .map(|s| format!("{:#x}+{:#x} {}x", s.0, s.1, s.2)) + .collect(); tracing::info!( "fills of upload memory that waited for flights, since the start: {n} checked after their wait, {} of them read other bytes than before it ({} bytes in all); {} distinct fills (page, length), the most frequent: {}", CHECKED[1].load(Relaxed), @@ -3106,9 +3232,14 @@ fn stale_under_flights(runs: &[&HostList]) -> bool { // flights twice a frame, 50 ms of the submitting thread.) static RUNS: OnceLock = OnceLock::new(); let mut runs_left = *RUNS.get_or_init(|| { - std::env::var("VICTORY_MERGE_RUNS").ok().and_then(|v| v.trim().parse::().ok()).map_or(512, |n| n.clamp(1, 1 << 16)) + std::env::var("VICTORY_MERGE_RUNS") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(512, |n| n.clamp(1, 1 << 16)) + }); + return spans.iter().any(|(shadow, from, to)| { + shadow.merge_under_writes(*from, *to - *from, &mut runs_left) }); - return spans.iter().any(|(shadow, from, to)| shadow.merge_under_writes(*from, *to - *from, &mut runs_left)); } spans .iter() @@ -3152,10 +3283,14 @@ pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { } let mut unsure = touches(&line.written, address, address + bytes); // (With the relay: first the writes of flights being landed.) - let writes = line.in_hand.iter().map(|(at, what, n)| (at, what, n)).chain(line.line.iter().filter_map(|item| match item { - Late::Write(at, what, n) => Some((at, what, n)), - _ => None, - })); + let writes = line + .in_hand + .iter() + .map(|(at, what, n)| (at, what, n)) + .chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); for (at, what, n) in writes { if *at >= address + bytes || address >= *at + *n { continue; @@ -3178,6 +3313,33 @@ pub(crate) fn late_met(wait: &crate::list::ValueWait) -> bool { wait.met() } +/// [`late_met`] without its settle: whether a bottom-of-pipe write of a +/// flight in the air, or of one being landed, is known to meet `wait`. +/// False says nothing about what else the flights may write there. +pub(crate) fn late_met_known(wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + let line = line(); + let writes = line + .in_hand + .iter() + .map(|(at, what, n)| (at, what, n)) + .chain(line.line.iter().filter_map(|item| match item { + Late::Write(at, what, n) => Some((at, what, n)), + _ => None, + })); + for (at, what, n) in writes { + if let crate::queue::Written::Value(v) = what + && *at == address + && *n >= bytes + && wait.holds_for(*v) + { + LATE_STATS[13].fetch_add(1, Ordering::Relaxed); + return true; + } + } + false +} + /// Settles the flights in the air, if any ([`Host::settle`]), for reason /// `why` (one of the `WHY_` places). Not from inside a submission. pub(crate) fn settle_now(why: usize) { @@ -3343,7 +3505,9 @@ fn relay_worker() { crate::framelog::keep_on_fast_cores("victory-relay"); // SAFETY: a plain event of our own. let Ok(event) = (unsafe { CreateEventW(None, false, false, None) }) else { - fail(format_args!("no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)")); + fail(format_args!( + "no event for the thread that lands submissions sent ahead (VICTORY_RELAY=1)" + )); }; let mut fetch: Option = None; loop { @@ -3458,7 +3622,10 @@ fn late_line(frames: f64) { #[cfg(feature = "diagnostics")] fill_check::line(); fill_ahead::line(frames); - let s: Vec = LATE_STATS.iter().map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let s: Vec = LATE_STATS + .iter() + .map(|s| s.swap(0, Ordering::Relaxed) as f64 / frames) + .collect(); tracing::info!( "submissions sent ahead per frame: {:.1} in {:.1} settles ({:.1} flights each time), {:.1} ms waiting for the card in them; \ settled for: a synchronous submission or present {:.1}, the card had run them {:.1}, a wait for a memory value {:.1}, \ @@ -3487,7 +3654,10 @@ fn late_line(frames: f64) { s[14], ); { - let w: Vec = LATE_WAITED.iter().map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames).collect(); + let w: Vec = LATE_WAITED + .iter() + .map(|w| w.swap(0, Ordering::Relaxed) as f64 / 1000.0 / frames) + .collect(); tracing::info!( "of the waiting for the card in settles, per frame, by what settled: a synchronous submission or present {:.1} ms, \ the card had run them {:.1}, a wait for a memory value {:.1}, title memory changed under shader writes {:.1}, \ @@ -3504,8 +3674,12 @@ fn late_line(frames: f64) { ); } if relay() { - let r: Vec = RELAY_STATS.iter().map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames).collect(); - let [again, noted] = [0, 1].map(|i| BESIDE_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); + let r: Vec = RELAY_STATS + .iter() + .map(|r| r.swap(0, Ordering::Relaxed) as f64 / frames) + .collect(); + let [again, noted] = + [0, 1].map(|i| BESIDE_STATS[i].swap(0, Ordering::Relaxed) as f64 / frames); tracing::info!( "the relay per frame (VICTORY_RELAY={}): {:.1} flights landed in {:.1} landings by the thread that copies back, \ beside the submitting thread; that thread waited {:.1} ms for the card with nothing to land and {:.1} ms for \ @@ -3521,7 +3695,10 @@ fn late_line(frames: f64) { r[4] / 1000.0, ); if inflight_fetch() { - let i: Vec = INFLIGHT_STATS.iter().map(|i| i.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let i: Vec = INFLIGHT_STATS + .iter() + .map(|i| i.swap(0, Ordering::Relaxed) as f64 / frames) + .collect(); tracing::info!( "card copies' pieces fetched inside their flights per frame (VICTORY_CARD_FETCH_INFLIGHT=1): {:.1} pieces \ ({:.2} MB) merged with no fetch of their own; {:.1} landings fetched the old way (the wait above), {:.1} of \ @@ -3623,7 +3800,8 @@ fn join_copies() -> bool { /// Since the last frame-rate line: title buffer copies recorded, and those /// that continue the one before ([`join_copies`]). -static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static COPIES_JOINED: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; /// Whether the copy `next` (destination, source, bytes) goes on exactly /// where `last` ended, source and destination both, and the two as one do @@ -3636,7 +3814,8 @@ fn continues(last: (usize, usize, usize), next: (usize, usize, usize)) -> bool { }; d.checked_add(n) == Some(dst) && s.checked_add(n) == Some(src) - && (d.checked_add(all).is_some_and(|end| end <= s) || s.checked_add(all).is_some_and(|end| end <= d)) + && (d.checked_add(all).is_some_and(|end| end <= s) + || s.checked_add(all).is_some_and(|end| end <= d)) } /// The ranges the shaders of `runs` may write, per host copy, as declared. @@ -3647,7 +3826,10 @@ fn declared_writes(runs: &[&HostList]) -> Vec { for step in &list.deferred().copies { if let Step::GpuWrite(shadow, address, len) = step { let range = (*address, *address + *len); - match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + match back + .iter_mut() + .find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) + { Some((_, ranges)) => { if !ranges.contains(&range) { ranges.push(range); @@ -3973,6 +4155,7 @@ impl Host { window_check: OnceLock::new(), _alive: Counted::new(), meter: AtomicU32::new(u32::MAX), + pipeline_meter: AtomicU32::new(u32::MAX), #[cfg(feature = "diagnostics")] notes: Mutex::default(), #[cfg(feature = "diagnostics")] @@ -3988,7 +4171,11 @@ impl Host { let clock = CLOCK .get_or_init(|| { // SAFETY: a plain fence on our device. - let fence = unsafe { self.device.CreateFence::(0, D3D12_FENCE_FLAG_NONE) }.ok()?; + let fence = unsafe { + self.device + .CreateFence::(0, D3D12_FENCE_FLAG_NONE) + } + .ok()?; Some(CardClock { fence, state: Mutex::new((0, None)), @@ -4098,7 +4285,11 @@ impl Host { fetched: None, taken: 0, out: 0, - inflight: if inflight_fetch() { self.make_card_inflight(RESULTS) } else { None }, + inflight: if inflight_fetch() { + self.make_card_inflight(RESULTS) + } else { + None + }, }) } } @@ -4129,10 +4320,14 @@ impl Host { } let code = code.ok_or_else(windows::core::Error::empty)?; let slots = inflight_slots(inflight_fetch_bytes()); - let (table, table_data) = self.shared_buffer(4 + results).ok_or_else(windows::core::Error::empty)?; + let (table, table_data) = self + .shared_buffer(4 + results) + .ok_or_else(windows::core::Error::empty)?; name(&table, || "card fetch in flight: tickets".into()); let fetched_bytes = u64::from(slots) * INFLIGHT_SLOT; - let (fetched, fetched_data) = self.shared_buffer(fetched_bytes).ok_or_else(windows::core::Error::empty)?; + let (fetched, fetched_data) = self + .shared_buffer(fetched_bytes) + .ok_or_else(windows::core::Error::empty)?; name(&fetched, || "card fetch in flight: pieces".into()); // SAFETY: the mapping holds the counter; nothing of ours ran // on the card with it yet. @@ -4140,16 +4335,21 @@ impl Host { // SAFETY: the blob's own bytes; the root signature is inside // the shader. unsafe { - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; - let pso: ID3D12PipelineState = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { - pShaderBytecode: bytes.as_ptr().cast(), - BytecodeLength: bytes.len(), - }, - ..Default::default() - })?; + let pso: ID3D12PipelineState = + self.device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; Ok(CardInflight { root, pso, @@ -4297,7 +4497,13 @@ impl Host { continue; }; for &(a, b) in ranges { - copy.1.CopyBufferRegion(&landing, at, staging, a as u64, (b - a) as u64); + copy.1.CopyBufferRegion( + &landing, + at, + staging, + a as u64, + (b - a) as u64, + ); at += (b - a) as u64; } } @@ -4317,7 +4523,9 @@ impl Host { } if !dirty.is_empty() { let Some(sync) = work.sync.pop().or_else(|| self.make_prelude()) else { - fail(format_args!("no host list to bring host copies in the card's memory up to date")); + fail(format_args!( + "no host list to bring host copies in the card's memory up to date" + )); }; let (allocator, list) = &sync; // SAFETY: the list's last run finished (it ran ahead of a @@ -4336,11 +4544,24 @@ impl Host { }; for &(a, b) in ranges { match &landed { - Some(landing) => list.CopyBufferRegion(&shadow.buffer, a as u64, landing, at, (b - a) as u64), - None => list.CopyBufferRegion(&shadow.buffer, a as u64, staging, a as u64, (b - a) as u64), + Some(landing) => list.CopyBufferRegion( + &shadow.buffer, + a as u64, + landing, + at, + (b - a) as u64, + ), + None => list.CopyBufferRegion( + &shadow.buffer, + a as u64, + staging, + a as u64, + (b - a) as u64, + ), } at += (b - a) as u64; - crate::shadow::CARD_STATS[0].fetch_add((b - a) as u64, Ordering::Relaxed); + crate::shadow::CARD_STATS[0] + .fetch_add((b - a) as u64, Ordering::Relaxed); } crate::shadow::CARD_STATS[1] .fetch_add(ranges.len() as u64, Ordering::Relaxed); @@ -4401,7 +4622,9 @@ impl Host { })() }; if let Err(e) = recorded { - fail(format_args!("host copies in the card's memory could not be brought up to date ({e})")); + fail(format_args!( + "host copies in the card's memory could not be brought up to date ({e})" + )); } used.push((false, sync)); } @@ -4429,7 +4652,9 @@ impl Host { _ => spans.push((from, to)), } } - let twin = shadow.card_sides().is_some_and(|(_, before, _)| before.is_some()); + let twin = shadow + .card_sides() + .is_some_and(|(_, before, _)| before.is_some()); for (from, to) in spans { let Some(span) = shadow.card_span(from, to) else { continue; @@ -4450,7 +4675,9 @@ impl Host { work.taken = at; if plan.ranges.iter().any(|r| r.compared) { let Some(check) = work.check.pop().or_else(|| self.make_prelude()) else { - fail(format_args!("no host list for the compare of host copies in the card's memory")); + fail(format_args!( + "no host list for the compare of host copies in the card's memory" + )); }; let (allocator, list) = ✓ // SAFETY: the list's last run finished (its submission was @@ -4513,9 +4740,18 @@ impl Host { }]); list.SetComputeRootSignature(&inflight.root); list.SetPipelineState(&inflight.pso); - list.SetComputeRootUnorderedAccessView(2, work.differs.0.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(3, inflight.table.0.GetGPUVirtualAddress()); - list.SetComputeRootUnorderedAccessView(4, inflight.fetched.0.GetGPUVirtualAddress()); + list.SetComputeRootUnorderedAccessView( + 2, + work.differs.0.GetGPUVirtualAddress(), + ); + list.SetComputeRootUnorderedAccessView( + 3, + inflight.table.0.GetGPUVirtualAddress(), + ); + list.SetComputeRootUnorderedAccessView( + 4, + inflight.fetched.0.GetGPUVirtualAddress(), + ); let mut every = true; for r in plan.ranges.iter().filter(|r| r.compared) { let Some((_, Some(_), size)) = r.shadow.card_sides() else { @@ -4523,10 +4759,21 @@ impl Host { continue; }; let groups = r.span.pieces.clamp(1, 65535); - let constants = - [r.span.first, r.span.skew, size as u32, r.span.pieces, r.at * 4, inflight.landed, inflight.fetched.2, groups]; + let constants = [ + r.span.first, + r.span.skew, + size as u32, + r.span.pieces, + r.at * 4, + inflight.landed, + inflight.fetched.2, + groups, + ]; list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); - list.SetComputeRootShaderResourceView(1, r.shadow.buffer.GetGPUVirtualAddress()); + list.SetComputeRootShaderResourceView( + 1, + r.shadow.buffer.GetGPUVirtualAddress(), + ); list.Dispatch(groups, 1, 1); } plan.inflight = every; @@ -4539,7 +4786,9 @@ impl Host { }; match recorded { Ok(list) => plan.check = Some(list), - Err(e) => fail(format_args!("the compare of host copies in the card's memory could not be recorded ({e})")), + Err(e) => fail(format_args!( + "the compare of host copies in the card's memory could not be recorded ({e})" + )), } plan.lists.push((true, check)); } @@ -4568,7 +4817,11 @@ impl Host { return; }; for (check, list) in plan.lists { - if check { work.check.push(list) } else { work.sync.push(list) } + if check { + work.check.push(list) + } else { + work.sync.push(list) + } } work.out = work.out.saturating_sub(1); // With the relay other plans may be on the card, their results @@ -4622,7 +4875,13 @@ impl Host { /// of the last flight being landed: a piece an earlier fetch on the /// copy queue brought down beside one of these flights is fetched /// whatever the compare says ([`BESIDE`]). - fn relay_card_back(&self, plans: &[(u64, &CardPlan)], fetch: &mut Option, behind: u64, landed: u64) { + fn relay_card_back( + &self, + plans: &[(u64, &CardPlan)], + fetch: &mut Option, + behind: u64, + landed: u64, + ) { if inflight_fetch() { let only: Vec<&CardPlan> = plans.iter().map(|p| p.1).collect(); let taken = self.relay_card_inflight(&only); @@ -4636,7 +4895,11 @@ impl Host { // earlier landings: looked at for these plans, renewed below. let beside = lane.is_some() && refetch(); let noted: std::collections::HashMap<(usize, u32), u64> = if beside { - BESIDE.lock().unwrap_or_else(|e| e.into_inner()).clone().unwrap_or_default() + BESIDE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone() + .unwrap_or_default() } else { Default::default() }; @@ -4645,9 +4908,11 @@ impl Host { let mut numbers: Vec<(usize, u32)> = Vec::new(); let differs = { let work = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()); - work.as_ref().map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) + work.as_ref() + .map(|work| (work.differs.1, (work.differs.2 / 4) as usize)) }; - let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = Vec::new(); + let mut pieces: Vec<(std::sync::Arc, usize, usize, u64)> = + Vec::new(); let mut total = 0u64; if let Some((differs, dwords)) = differs { // SAFETY: the mapping of the results. The compares of these @@ -4693,7 +4958,8 @@ impl Host { total += (hi - lo) as u64; } } - crate::shadow::CARD_STATS[2].fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); + crate::shadow::CARD_STATS[2] + .fetch_add(u64::from(r.span.pieces), Ordering::Relaxed); } } } @@ -4711,7 +4977,12 @@ impl Host { if beside { // Notes whose flights have all landed are done with. let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); - note_beside(all.get_or_insert_with(Default::default), &[], landed, landed); + note_beside( + all.get_or_insert_with(Default::default), + &[], + landed, + landed, + ); } // Nothing to fetch: every send so far is older than the next // fetch (on a copy queue: every send the card has finished). @@ -4728,17 +4999,24 @@ impl Host { *fetch = self.make_relay_fetch(); } let Some(f) = fetch.as_mut() else { - fail(format_args!("no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)")); + fail(format_args!( + "no list, fence or event to fetch what shaders wrote to the card's memory (VICTORY_RELAY=1)" + )); }; if f.buffer.as_ref().is_none_or(|b| b.2 < total) { let size = total.next_multiple_of(16 << 20); - f.buffer = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + f.buffer = self + .shared_buffer(size) + .map(|(buffer, data)| (buffer, data as usize, size)); } let Some((buffer, data, _)) = f.buffer.clone() else { - fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)")); + fail(format_args!( + "no memory to fetch what shaders wrote to the card's memory ({total} bytes, VICTORY_RELAY=1)" + )); }; f.sent += 1; - let ((allocator, list), fence, event, sent) = (f.list.clone(), f.fence.clone(), f.event, f.sent); + let ((allocator, list), fence, event, sent) = + (f.list.clone(), f.fence.clone(), f.event, f.sent); let waiting = std::time::Instant::now(); // SAFETY: the list's last run was waited for by this thread; live // buffers (the copies are held by the plans); the fence and the @@ -4754,7 +5032,13 @@ impl Host { let after = second.order_done(); let copy = second.down.list()?; for (shadow, lo, hi, at) in &pieces { - copy.1.CopyBufferRegion(&buffer, *at, &shadow.buffer, *lo as u64, (*hi - *lo) as u64); + copy.1.CopyBufferRegion( + &buffer, + *at, + &shadow.buffer, + *lo as u64, + (*hi - *lo) as u64, + ); } let job = second.down.send(copy, &[(&self.fence, behind)], total)?; second.down.wait(job, event)?; @@ -4765,10 +5049,19 @@ impl Host { // queue, `Host::submit`: nothing later ran yet). let started = STARTED.load(Ordering::Acquire); let mut all = BESIDE.lock().unwrap_or_else(|e| e.into_inner()); - let noted = note_beside(all.get_or_insert_with(Default::default), &numbers, landed, started); + let noted = note_beside( + all.get_or_insert_with(Default::default), + &numbers, + landed, + started, + ); BESIDE_STATS[1].fetch_add(noted, Ordering::Relaxed); } - second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + second + .down + .stats + .waited_us + .fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); return Ok(after); } allocator.Reset()?; @@ -4799,7 +5092,9 @@ impl Host { }; let after = match ran { Ok(after) => after, - Err(e) => fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)")), + Err(e) => fail(format_args!( + "what shaders wrote to the card's memory could not be fetched ({e}, VICTORY_RELAY=1)" + )), }; // This fetch may bring bytes of flights in the air now: their own // slots are older than what it puts in the CPU's side there @@ -4808,9 +5103,17 @@ impl Host { // yet; every one before it has (the submission lock). if inflight_fetch() && after > 1 - && let Some(inflight) = CARD_WORK.lock().unwrap_or_else(|e| e.into_inner()).as_mut().and_then(|w| w.inflight.as_mut()) + && let Some(inflight) = CARD_WORK + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_mut() + .and_then(|w| w.inflight.as_mut()) { - inflight.brought.extend(pieces.iter().map(|(shadow, lo, hi, _)| (shadow.clone(), *lo, *hi, after - 1))); + inflight.brought.extend( + pieces + .iter() + .map(|(shadow, lo, hi, _)| (shadow.clone(), *lo, *hi, after - 1)), + ); } let us = waiting.elapsed().as_micros() as u64; RELAY_STATS[3].fetch_add(us, Ordering::Relaxed); @@ -4826,7 +5129,8 @@ impl Host { for (shadow, lo, hi, at) in &pieces { // SAFETY: the mapping of the fetched bytes, `total` of them; // the copy into it has run. - let gpu = unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; + let gpu = + unsafe { std::slice::from_raw_parts((data + *at as usize) as *const u8, hi - lo) }; let merged = shadow.card_merge_relay(*lo, gpu, after, &mut title); shadow.walls_merged(gpu.len(), merged); written += merged; @@ -4906,7 +5210,8 @@ impl Host { return false; } // Pieces (copy, number) the compare flagged, with their ticket. - let mut tickets: std::collections::HashMap<(usize, u32), u32> = std::collections::HashMap::new(); + let mut tickets: std::collections::HashMap<(usize, u32), u32> = + std::collections::HashMap::new(); let mut flags: Vec<(usize, u32, bool)> = Vec::new(); for r in &plan.ranges { let copy = Arc::as_ptr(&r.shadow) as usize; @@ -4948,12 +5253,18 @@ impl Host { if lo < from || (hi - from) as u64 > INFLIGHT_SLOT { return false; } - let slot = inflight.fetched.1 + (k % slots) as usize * INFLIGHT_SLOT as usize; + let slot = + inflight.fetched.1 + (k % slots) as usize * INFLIGHT_SLOT as usize; // Bytes a fetch the old way brought after this flight ran. let newer: Vec<(usize, usize)> = inflight .brought .iter() - .filter(|b| b.3 >= plan.sent_as && Arc::ptr_eq(&b.0, &r.shadow) && b.1 < hi && b.2 > lo) + .filter(|b| { + b.3 >= plan.sent_as + && Arc::ptr_eq(&b.0, &r.shadow) + && b.1 < hi + && b.2 > lo + }) .map(|b| (b.1, b.2)) .collect(); for (a, b) in crate::shadow::outside(lo, hi, newer) { @@ -5010,7 +5321,10 @@ impl Host { if !flights.is_empty() { // SAFETY: a plain query. if unsafe { self.device.GetDeviceRemovedReason() }.is_err() { - let runs: Vec<&HostList> = flights.iter().flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())).collect(); + let runs: Vec<&HostList> = flights + .iter() + .flat_map(|f| f.order.iter().map(|&i| f.lists[i].host())) + .collect(); fail(format_args!( "host GPU device removed after {} submissions sent ahead (VICTORY_RELAY=1) of {} lists{}{}", flights.len(), @@ -5020,14 +5334,20 @@ impl Host { )); } fill_ahead::landing(flights.iter().map(|f| f.number).min().unwrap_or(0)); - let plans: Vec<(u64, &CardPlan)> = flights.iter().filter_map(|f| f.card.as_ref().map(|card| (f.number, card))).collect(); + let plans: Vec<(u64, &CardPlan)> = flights + .iter() + .filter_map(|f| f.card.as_ref().map(|card| (f.number, card))) + .collect(); let behind = flights.iter().map(|f| f.fence).max().unwrap_or(0); let landed = flights.iter().map(|f| f.number).max().unwrap_or(0); self.relay_card_back(&plans, fetch, behind, landed); let mut back: Vec = Vec::new(); for flight in &flights { for (shadow, ranges) in &flight.back { - match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + match back + .iter_mut() + .find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) + { Some((_, all)) => { for range in ranges { if !all.contains(range) { @@ -5136,7 +5456,9 @@ impl Host { }; // SAFETY: the mapping of the results, which the compare (it has // run) wrote. - let differs = unsafe { std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) }; + let differs = unsafe { + std::slice::from_raw_parts(work.differs.1 as *const u32, (work.differs.2 / 4) as usize) + }; // The pieces to fetch: the range, the offsets in its copy, and // where the bytes come down. let mut pieces: Vec<(usize, usize, usize, u64)> = Vec::new(); @@ -5158,10 +5480,14 @@ impl Host { if !pieces.is_empty() { if work.fetched.as_ref().is_none_or(|f| f.2 < total) { let size = total.next_multiple_of(16 << 20); - work.fetched = self.shared_buffer(size).map(|(buffer, data)| (buffer, data as usize, size)); + work.fetched = self + .shared_buffer(size) + .map(|(buffer, data)| (buffer, data as usize, size)); } let Some((fetched, data, _)) = &work.fetched else { - fail(format_args!("no memory to fetch what shaders wrote to the card's memory ({total} bytes)")); + fail(format_args!( + "no memory to fetch what shaders wrote to the card's memory ({total} bytes)" + )); }; let waiting = std::time::Instant::now(); let (allocator, list) = &work.fetch; @@ -5177,14 +5503,26 @@ impl Host { if let Some(second) = crate::queue2::second().filter(|s| s.fetches()) { let copy = second.down.list()?; for &(i, lo, hi, at) in &pieces { - copy.1.CopyBufferRegion(fetched, at, &plan.ranges[i].shadow.buffer, lo as u64, (hi - lo) as u64); + copy.1.CopyBufferRegion( + fetched, + at, + &plan.ranges[i].shadow.buffer, + lo as u64, + (hi - lo) as u64, + ); } - let job = second.down.send(copy, &[(&self.fence, *submitted)], total)?; + let job = second + .down + .send(copy, &[(&self.fence, *submitted)], total)?; let was_working = working(false); second.down.wait(job, self.event)?; stood(waiting); working(was_working); - second.down.stats.waited_us.fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); + second + .down + .stats + .waited_us + .fetch_add(waiting.elapsed().as_micros() as u64, Ordering::Relaxed); return Ok(()); } allocator.Reset()?; @@ -5212,7 +5550,9 @@ impl Host { })() }; if let Err(e) = ran { - fail(format_args!("what shaders wrote to the card's memory could not be fetched ({e})")); + fail(format_args!( + "what shaders wrote to the card's memory could not be fetched ({e})" + )); } { use crate::shadow::CARD_STATS; @@ -5274,7 +5614,9 @@ impl Host { for &(i, lo, hi, at) in &pieces { // SAFETY: the mapping of the fetched bytes, `total` of // them; the copy into it has run. - let gpu = unsafe { std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) }; + let gpu = unsafe { + std::slice::from_raw_parts((*data + at as usize) as *const u8, hi - lo) + }; let merged = plan.ranges[i].shadow.card_merge(lo, gpu, &mut title); plan.ranges[i].shadow.walls_merged(gpu.len(), merged); written[i] += merged; @@ -5520,7 +5862,10 @@ impl Host { self.card_back(card, submitted, &mut seen); } for (shadow, ranges) in &flight.back { - match back.iter_mut().find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) { + match back + .iter_mut() + .find(|(s, _)| std::sync::Arc::ptr_eq(s, shadow)) + { Some((_, all)) => { for range in ranges { if !all.contains(range) { @@ -5651,7 +5996,8 @@ impl Host { // One write-watch asking for everything the submission refreshes // (`VICTORY_ASK_ONCE`): per copy, the span of its refreshed ranges. if crate::watch::once() { - let mut spans: std::collections::HashMap = std::collections::HashMap::new(); + let mut spans: std::collections::HashMap = + std::collections::HashMap::new(); for list in runs { for step in &list.deferred().copies { if let Step::Refresh(shadow, address, len) = step @@ -5732,8 +6078,14 @@ impl Host { )); } let back = declared_writes(runs); - let writes = runs.iter().flat_map(|l| l.deferred().writes.clone()).collect(); - submission_us(0, (prepared - started).saturating_sub(settled).as_micros() as u64); + let writes = runs + .iter() + .flat_map(|l| l.deferred().writes.clone()) + .collect(); + submission_us( + 0, + (prepared - started).saturating_sub(settled).as_micros() as u64, + ); submitting(0, 0); #[cfg(feature = "diagnostics")] crate::copystat::submission_ends(lock); @@ -5799,8 +6151,16 @@ impl Host { if timing() && started.elapsed() > std::time::Duration::from_millis(50) { // SAFETY: a plain query. let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1); - let commands = runs[i].notes.lock().unwrap_or_else(|e| e.into_inner()).len(); - tracing::warn!(ms = started.elapsed().as_millis(), commands, "slow host list"); + let commands = runs[i] + .notes + .lock() + .unwrap_or_else(|e| e.into_inner()) + .len(); + tracing::warn!( + ms = started.elapsed().as_millis(), + commands, + "slow host list" + ); for (ms, op) in runs[i].slowest(frequency, 6) { tracing::warn!("slow list command, {ms:.1} ms: {op}"); } @@ -6028,7 +6388,8 @@ impl Host { let Some(queue) = &self.messages else { return; }; - static SEEN: Mutex> = Mutex::new(std::collections::BTreeMap::new()); + static SEEN: Mutex> = + Mutex::new(std::collections::BTreeMap::new()); let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); // SAFETY: each message is read into a buffer of the size the queue // reports, then the queue is emptied. @@ -6046,10 +6407,16 @@ impl Host { let kind = seen.entry(m.ID.0).or_insert((0, m.Severity.0)); kind.0 += 1; if kind.0 <= 5 { - let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = + std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); let text = String::from_utf8_lossy(text); let text = text.trim_end_matches('\0'); - tracing::warn!(id = m.ID.0, severity = m.Severity.0, nth = kind.0, "D3D12 debug layer: {text}"); + tracing::warn!( + id = m.ID.0, + severity = m.Severity.0, + nth = kind.0, + "D3D12 debug layer: {text}" + ); } } } @@ -6057,7 +6424,10 @@ impl Host { stored }; if stored > 0 { - let counts: Vec = seen.iter().map(|(id, (n, severity))| format!("id {id} (severity {severity}) x{n}")).collect(); + let counts: Vec = seen + .iter() + .map(|(id, (n, severity))| format!("id {id} (severity {severity}) x{n}")) + .collect(); tracing::info!( "D3D12 debug layer messages so far by kind (severity 0 corruption, 1 error, 2 warning, 3 info, 4 message): {}", counts.join(", ") @@ -6248,19 +6618,33 @@ impl HostList { } self.flush_barriers(); self.twins_to_depth(); - let scratch = self.indirect_args.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let scratch = self + .indirect_args + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(); if let Some((scratch, _)) = scratch { self.indirect_common(&scratch); } self.card_budget_out(); - crate::cardmeter::end(&self.list, crate::cardmeter::Span::from_raw(self.meter.swap(u32::MAX, Ordering::Relaxed))); + crate::cardmeter::end( + &self.list, + crate::cardmeter::Span::from_raw(self.pipeline_meter.swap(u32::MAX, Ordering::Relaxed)), + ); + crate::cardmeter::end_named( + &self.list, + crate::cardmeter::Span::from_raw(self.meter.swap(u32::MAX, Ordering::Relaxed)), + &self.pipelines.lock().unwrap_or_else(|e| e.into_inner()), + ); #[cfg(feature = "diagnostics")] if let Some((heap, back)) = self.stamps() { - let count = (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); + let count = + (self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32).min(STAMPS - 1); // SAFETY: an open list, our heap and read-back buffer. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, count); - self.list.ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); + self.list + .ResolveQueryData(heap, D3D12_QUERY_TYPE_TIMESTAMP, 0, count + 1, back, 0); } } // SAFETY: our list. @@ -6274,18 +6658,25 @@ impl HostList { /// Only after the list's last submission finished (every one is waited /// for). pub(crate) fn reset(&self) { - self.closed.store(false, std::sync::atomic::Ordering::Release); + self.closed + .store(false, std::sync::atomic::Ordering::Release); #[cfg(feature = "diagnostics")] let started = std::time::Instant::now(); self._alive.used(); *self.deferred() = Deferred::default(); - self.states.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); self.twins.lock().unwrap_or_else(|e| e.into_inner()).clear(); self.pending_barriers .lock() .unwrap_or_else(|e| e.into_inner()) .clear(); - self.pipelines.lock().unwrap_or_else(|e| e.into_inner()).clear(); + self.pipelines + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clear(); #[cfg(feature = "diagnostics")] self.notes.lock().unwrap_or_else(|e| e.into_inner()).clear(); { @@ -6306,8 +6697,10 @@ impl HostList { if let Err(e) = reset { fail(format_args!("a host command list did not reset ({e})")); } - self.meter - .store(crate::cardmeter::begin(&self.list, crate::cardmeter::Kind::Lists).raw(), Ordering::Relaxed); + self.meter.store( + crate::cardmeter::begin(&self.list, crate::cardmeter::Kind::Lists).raw(), + Ordering::Relaxed, + ); #[cfg(feature = "diagnostics")] crate::copystat::add( crate::copystat::C::ResetNs, @@ -6685,7 +7078,9 @@ impl HostList { { let started = std::time::Instant::now(); let at = self.notes.lock().unwrap_or_else(|e| e.into_inner()).len() as u32; - if let Some((heap, _)) = self.stamps() && at < STAMPS - 1 { + if let Some((heap, _)) = self.stamps() + && at < STAMPS - 1 + { // SAFETY: an open list and our query heap. unsafe { self.list.EndQuery(heap, D3D12_QUERY_TYPE_TIMESTAMP, at) }; } @@ -6726,15 +7121,37 @@ impl HostList { return false; } } - self.states.lock().unwrap_or_else(|e| e.into_inner()).is_empty() - && self.twins.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + self.states + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() + && self + .twins + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() } - /// Notes a pipeline the list binds. + /// Notes a pipeline the list binds; called where it is bound. pub(crate) fn used_pipeline(&self, name: &str) { - let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); - if !pipelines.contains(name) { - pipelines.insert(name.to_owned()); + { + let mut pipelines = self.pipelines.lock().unwrap_or_else(|e| e.into_inner()); + if !pipelines.contains(name) { + pipelines.insert(name.to_owned()); + } + } + if crate::cardmeter::pipelines() { + // The pipeline before it ends here on the card's clock. + crate::cardmeter::end( + &self.list, + crate::cardmeter::Span::from_raw( + self.pipeline_meter.swap(u32::MAX, Ordering::Relaxed), + ), + ); + self.pipeline_meter.store( + crate::cardmeter::begin_named(&self.list, name).raw(), + Ordering::Relaxed, + ); } } @@ -6823,6 +7240,22 @@ impl HostList { self.deferred().writes.push((dst as usize, what, bytes)); } + /// Whether the list, once it has run, stores at `address` a value of + /// `bytes` bytes or more for which `holds` says yes (one of its + /// bottom-of-pipe writes, as [`late_met`] reads them of a flight). + pub(crate) fn will_write( + &self, + address: usize, + bytes: usize, + holds: impl Fn(u64) -> bool, + ) -> bool { + self.deferred().writes.iter().any(|(at, what, n)| { + *at == address + && *n >= bytes + && matches!(what, crate::queue::Written::Value(v) if holds(*v)) + }) + } + /// A mapped upload buffer of `size` bytes, alive until the list is /// reset. /// @@ -6886,7 +7319,10 @@ impl HostList { Some((b, d as usize)) }) .as_ref()?; - let card = self.card_budget.get_or_init(|| self.make_card_budget()).as_ref(); + let card = self + .card_budget + .get_or_init(|| self.make_card_budget()) + .as_ref(); let mut deferred = self.deferred(); if !deferred.budget_zeroed { deferred.budget_zeroed = true; @@ -7060,7 +7496,9 @@ impl HostList { /// The list's buffers for `crate::indirect::window_check`. pub(crate) fn window_check(&self) -> Option<&crate::indirect::WindowCheck> { - self.window_check.get_or_init(crate::indirect::WindowCheck::new).as_ref() + self.window_check + .get_or_init(crate::indirect::WindowCheck::new) + .as_ref() } /// Keeps `object` alive until the list is reset. @@ -7244,9 +7682,33 @@ fn wide_refresh() -> bool { /// before they were submitted. A title buffer copy of ours takes its /// bytes out of what counts as up to date ([`Batch::title_wrote`]); any /// other step that writes title memory takes everything out. +/// +/// `VICTORY_REFRESH_ONCE=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, so that one run measures both in +/// the same scene (two runs do not stand in the same scene at the same +/// second: runs 228 and 229). fn refresh_once() -> bool { - static ON: OnceLock = OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_ONCE").is_some_and(|v| v == "1")) + /// 0 off, 1 on, 2 in turn. + static MODE: OnceLock = OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_REFRESH_ONCE").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + let on = (now_us() / 20_000_000) % 2 == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "refreshes once a submission from now (VICTORY_REFRESH_ONCE=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } } /// A submission's refreshes not done yet, merged per buffer copy into the @@ -7269,7 +7731,8 @@ struct Batch { /// that the address names no other): the range of title addresses /// brought up to date in this submission that no step of ours has /// written since. - current: std::collections::HashMap, usize, usize)>, + current: + std::collections::HashMap, usize, usize)>, /// Staging buffers (by address) refreshed since the last title write. textures: std::collections::HashSet, } @@ -7306,13 +7769,17 @@ impl Batch { /// Before shaders are given a range of `shadow`'s copy: its pending /// refresh is done, the others stay pending. fn flush_one(&mut self, shadow: &std::sync::Arc) { - let Some(at) = self.index.remove(&(std::sync::Arc::as_ptr(shadow) as usize)) else { + let Some(at) = self + .index + .remove(&(std::sync::Arc::as_ptr(shadow) as usize)) + else { return; }; let (shadow, from, to) = self.refreshes.swap_remove(at); // The last entry took its place. if let Some(moved) = self.refreshes.get(at) { - self.index.insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); + self.index + .insert(std::sync::Arc::as_ptr(&moved.0) as usize, at); } Self::update(&shadow, from, to); Self::brought(&mut self.current, &shadow, from, to); @@ -7322,7 +7789,10 @@ impl Batch { /// up to date. Kept: its union with what was up to date if they touch, /// else the larger of the two. fn brought( - current: &mut std::collections::HashMap, usize, usize)>, + current: &mut std::collections::HashMap< + usize, + (std::sync::Arc, usize, usize), + >, shadow: &std::sync::Arc, from: usize, to: usize, @@ -7354,7 +7824,8 @@ impl Batch { /// Whether `staging` is still to be refreshed in this submission (and /// notes it refreshed). fn texture_due(&mut self, staging: &std::sync::Arc) -> bool { - self.textures.insert(std::sync::Arc::as_ptr(staging) as *const () as usize) + self.textures + .insert(std::sync::Arc::as_ptr(staging) as *const () as usize) } /// Before a step that writes title memory: pending refreshes are done @@ -7528,8 +7999,10 @@ fn read_sparse(src: *const u8, dst: *mut u8, len: usize) { // SAFETY: the query inspects an address and fills a local structure. let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; let size = unsafe { VirtualQuery(at.cast(), &mut info, size_of_val(&info)) }; - let n = (info.BaseAddress as usize).saturating_add(info.RegionSize) - .saturating_sub(at as usize).min(remaining); + let n = (info.BaseAddress as usize) + .saturating_add(info.RegionSize) + .saturating_sub(at as usize) + .min(remaining); if size != size_of_val(&info) || n == 0 { read_pieces(at, to, remaining); break; @@ -7571,7 +8044,8 @@ fn read_pieces(src: *const u8, dst: *mut u8, len: usize) { pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool { // In place first, if asked for (`crate::plaincopy`): the destination is // memory of ours, as in `copy_mapped`. - crate::plaincopy::copy(dst.as_mut_ptr(), src, dst.len()) || read(src, dst.as_mut_ptr(), dst.len()) + crate::plaincopy::copy(dst.as_mut_ptr(), src, dst.len()) + || read(src, dst.as_mut_ptr(), dst.len()) } /// Copies `len` bytes from `src` to `dst` unless a source page is not @@ -7937,7 +8411,8 @@ impl Meter { // dispatch runs; the counter went when the clamp's budget moved to // the card's memory.) { - let [texture_us, slots] = [0, 1].map(|i| crate::draw::HEAP_PASS_PARTS[i].swap(0, Ordering::Relaxed)); + let [texture_us, slots] = + [0, 1].map(|i| crate::draw::HEAP_PASS_PARTS[i].swap(0, Ordering::Relaxed)); tracing::info!( "the pass over the heap per frame (the frame line's \"heap buffers ... ms\" is both parts): {:.1} ms in its pass over textures picked by index; {:.0} buffer slots looked at by its pass over buffer views", texture_us as f64 / 1e3 / frames, @@ -7964,7 +8439,8 @@ impl Meter { } crate::shadow::back_line(frames); { - let [passes, pieces, compares] = [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); + let [passes, pieces, compares] = + [0, 1, 2].map(|i| CARD_PASSES[i].swap(0, Ordering::Relaxed) as f64 / frames); if passes + compares > 0.0 { tracing::info!( "our passes over copies in the card's memory per frame: {passes:.0} hash passes over {pieces:.0} pieces after \ @@ -7984,7 +8460,8 @@ impl Meter { hold still (the runtime remapping it); the rest is reading, hashing and detiling" ); } - let [through, left] = [0, 1].map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); + let [through, left] = [0, 1] + .map(|i| crate::texture::UNLOCKED[i].swap(0, Ordering::Relaxed) as f64 / frames); if through + left > 0.0 { tracing::info!( "texture refreshes that did not wait for title memory to hold still, per frame (VICTORY_TEXTURE_NO_WAIT=1): \ @@ -7993,7 +8470,8 @@ impl Meter { } } { - let [copies, joined] = [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); + let [copies, joined] = + [0, 1].map(|i| COPIES_JOINED[i].swap(0, Ordering::Relaxed) as f64 / frames); if copies > 0.0 { tracing::info!( "title buffer copies recorded per frame: {copies:.0}, of them {joined:.0} continue the one before \ @@ -8047,8 +8525,8 @@ impl Meter { } crate::tiles::status(); { - let [queued, due, away, partly, oldest] = - [0, 1, 2, 3, 4].map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); + let [queued, due, away, partly, oldest] = [0, 1, 2, 3, 4] + .map(|i| crate::draw::HEAP_TEXTURES_QUEUE[i].load(Ordering::Relaxed)); let [same, parts, tails] = [0, 1, 2].map(|i| crate::draw::HEAP_TEXTURES_PARTLY[i].load(Ordering::Relaxed)); tracing::info!( @@ -8071,15 +8549,28 @@ impl Meter { } { let mode = crate::watch::page_writes(); - let [writes, bytes, guarded, plain] = [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); - let [kept, dropped, slots, uploaded] = - [0, 1, 2, 3].map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); + let [writes, bytes, guarded, plain] = + [0, 1, 2, 3].map(|i| crate::watch::WRITTEN[i].load(Ordering::Relaxed)); + let [kept, dropped, slots, uploaded] = [0, 1, 2, 3] + .map(|i| crate::descriptor::host::PAGE_WRITES[i].load(Ordering::Relaxed)); tracing::info!( "writes behind the guards, since the start: {writes} DirectStorage writes into physical pages at addresses the title had mapped ({} MB); {guarded} guarded 64 KiB blocks of host copies lay under them ({}); {plain} reads to plain addresses finished ({}); {kept} ranges under texture views kept for the texture pass ({dropped} dropped); {slots} slots of placed textures held their bytes, {uploaded} of them uploaded before the write ({}) (VICTORY_PAGE_WRITES: unset or guards opens the guarded blocks, 0 counts only, 1, slots, all)", bytes >> 20, - if mode & 1 != 0 { "opened, taken again" } else { "left as they were" }, - if mode & 4 != 0 { "told as well" } else { "counted only" }, - if mode & 2 != 0 { "made due again" } else { "left as they were" } + if mode & 1 != 0 { + "opened, taken again" + } else { + "left as they were" + }, + if mode & 4 != 0 { + "told as well" + } else { + "counted only" + }, + if mode & 2 != 0 { + "made due again" + } else { + "left as they were" + } ); } #[cfg(feature = "diagnostics")] @@ -8225,7 +8716,10 @@ impl Host { pub(crate) fn present(&self, texture: &ID3D12Resource, state: u32, frame: u64) -> Option { let showing = std::time::Instant::now(); let shown = self.present_now(texture, state, frame); - crate::framelog::add(crate::framelog::T::PresentShowUs, showing.elapsed().as_micros() as u64); + crate::framelog::add( + crate::framelog::T::PresentShowUs, + showing.elapsed().as_micros() as u64, + ); shown } @@ -8290,12 +8784,15 @@ impl Host { let read_now = false; let slot = if late_free_present() && !read_now { let finished = FINISHED.load(Ordering::Acquire); - p.ahead.iter().position(|(_, flown)| *flown <= finished).or_else(|| { - let list = self.new_list().ok()?; - list.close(); - p.ahead.push((list, 0)); - Some(p.ahead.len() - 1) - }) + p.ahead + .iter() + .position(|(_, flown)| *flown <= finished) + .or_else(|| { + let list = self.new_list().ok()?; + list.close(); + p.ahead.push((list, 0)); + Some(p.ahead.len() - 1) + }) } else { None }; @@ -8319,7 +8816,11 @@ impl Host { .then(|| crate::capture::read_back(&self.device, list, texture)) .flatten(); #[cfg(feature = "diagnostics")] - let probe = if slot.is_some() { None } else { crate::capture::probe(&self.device, list, texture) }; + let probe = if slot.is_some() { + None + } else { + crate::capture::probe(&self.device, list, texture) + }; #[cfg(not(feature = "diagnostics"))] let _ = frame; list.ResourceBarrier(&[ @@ -8450,7 +8951,11 @@ impl Host { /// Dedicated video memory of the adapter the device is on, in bytes. pub(crate) fn dedicated_memory(&self) -> Option { // SAFETY: a live DXGI adapter. - Some(unsafe { self.adapter.as_ref()?.GetDesc1() }.ok()?.DedicatedVideoMemory as u64) + Some( + unsafe { self.adapter.as_ref()?.GetDesc1() } + .ok()? + .DedicatedVideoMemory as u64, + ) } /// The card's memory as the system accounts it to this process, in @@ -8476,7 +8981,8 @@ impl Host { // the first world frame in runs 179 to 185, and the memory line, // seconds later, was the first to show it. We reserve nothing // and make the swap chain once, at the start.) - static LAST: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; + static LAST: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; let now = [own.Budget, own.CurrentUsage, shared.CurrentUsage]; let last = [0, 1, 2].map(|i| LAST[i].swap(now[i], Ordering::Relaxed)); if last[0] != 0 && last[0].abs_diff(own.Budget) >= (256u64 << 20) { @@ -8654,7 +9160,11 @@ fn last_notes(runs: &[&HostList]) -> String { for (i, r) in runs.iter().enumerate() { let notes = r.notes.lock().unwrap_or_else(|e| e.into_inner()); for (n, _) in notes.iter().rev().take(6).rev() { - text.push_str(&format!("; list {i} of {}, of its {}: {n}", runs.len(), notes.len())); + text.push_str(&format!( + "; list {i} of {}, of its {}: {n}", + runs.len(), + notes.len() + )); } } text @@ -8889,7 +9399,10 @@ mod trail { assert!(text.contains("the submitting thread was")); assert!(text.contains("pipeline library: no call running")); assert!(text.contains(&format!("thing {} done", super::TRAIL_MOST + 4))); - assert!(!text.contains("thing 4 done"), "the oldest entries are dropped"); + assert!( + !text.contains("thing 4 done"), + "the oldest entries are dropped" + ); } } @@ -8921,7 +9434,8 @@ mod spare { } #[cfg(test)] -mod batch { // Batch::texture_due lives here; `mod tests` is already taken at the top of this file +mod batch { + // Batch::texture_due lives here; `mod tests` is already taken at the top of this file use super::Batch; use std::sync::Arc; @@ -9067,7 +9581,9 @@ void main() { #[test] fn warp_title_bytes_go_up_and_shader_writes_come_back_whatever_the_queues() { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + }; const MEM_WRITE_WATCH: u32 = 0x0020_0000; let Some(host) = host() else { return; @@ -9080,7 +9596,9 @@ void main() { .and_then(|a| unsafe { a.GetDesc1() }.ok()) .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); if !software { - eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + eprintln!( + "queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)" + ); return; } const PIECE: usize = 64 << 10; @@ -9088,7 +9606,14 @@ void main() { const ROUNDS: usize = 12; // "Title memory": write-watched, as the title's is. // SAFETY: a plain allocation of our own. - let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + let title = unsafe { + VirtualAlloc( + std::ptr::null(), + LEN, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as *mut u8; assert!(!title.is_null()); let dword = |at: usize| unsafe { title.add(at).cast::() }; for i in 0..LEN / 4 { @@ -9098,13 +9623,19 @@ void main() { crate::shadow::register(0x51_5151, title as u64, LEN as u64); let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); if !shadow.carded() { - eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + eprintln!( + "queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)" + ); return; } - let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + let code = compile(ADD, windows::core::s!("main"), windows::core::s!("cs_5_1")) + .expect("the test's shader"); // SAFETY: the shader's own root signature; plain creation. let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let root: ID3D12RootSignature = host + .device + .CreateRootSignature(0, &code) + .expect("a root signature"); let pso = host .device .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { @@ -9131,15 +9662,21 @@ void main() { unsafe { dword(from(k)).write_volatile(titles(k)) }; let list = host.new_list().expect("a host list"); shadow.refresh(&list, title as u64, LEN as u64); - shadow.gpu_writes(&list, (title as usize + (30 + k) * PIECE) as u64, PIECE as u64); + shadow.gpu_writes( + &list, + (title as usize + (30 + k) * PIECE) as u64, + PIECE as u64, + ); // SAFETY: an open list; the copy's buffer, with unordered // access; the shader's own root signature. unsafe { list.list.SetComputeRootSignature(&root); list.list.SetPipelineState(&pso); let constants = [to(k) as u32, from(k) as u32, k as u32, 30_000]; - list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list + .SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list + .SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); list.list.Dispatch(1, 1, 1); } list.close(); @@ -9153,7 +9690,8 @@ void main() { settle_now(WHY_SYNC); for k in 0..ROUNDS { // SAFETY: inside the allocation. - let (sum, kept) = unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; + let (sum, kept) = + unsafe { (dword(to(k)).read_volatile(), dword(from(k)).read_volatile()) }; assert_eq!(kept, titles(k), "round {k}: the title's own dword changed"); assert_eq!( sum, @@ -9164,15 +9702,23 @@ void main() { ); } // Nothing else moved. - let touched: std::collections::HashSet = (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); + let touched: std::collections::HashSet = + (0..ROUNDS).flat_map(|k| [from(k), to(k)]).collect(); for i in (0..LEN / 4).filter(|i| !touched.contains(&(i * 4))) { // SAFETY: inside the allocation. let got = unsafe { dword(i * 4).read_volatile() }; - assert_eq!(got, 0x5A00_0000 | i as u32, "dword {i} of title memory changed"); + assert_eq!( + got, + 0x5A00_0000 | i as u32, + "dword {i} of title memory changed" + ); } // The queues the switches name did the work. if let Some(second) = crate::queue2::second() { - let (down, up) = (second.down.stats.jobs.load(Ordering::Relaxed), second.up.stats.jobs.load(Ordering::Relaxed)); + let (down, up) = ( + second.down.stats.jobs.load(Ordering::Relaxed), + second.up.stats.jobs.load(Ordering::Relaxed), + ); // (Sends that found no landing buffer went the old way.) let no_room = second.landing[1].load(Ordering::Relaxed); eprintln!( @@ -9183,10 +9729,22 @@ void main() { second.held[0].load(Ordering::Relaxed) ); assert_eq!(down > 0, second.fetches(), "fetches through the copy queue"); - assert_eq!(up + no_room > 0, second.uploads(), "sends through the copy queue"); - assert_eq!(up, second.held[0].load(Ordering::Relaxed), "the direct queue waits for every send"); + assert_eq!( + up + no_room > 0, + second.uploads(), + "sends through the copy queue" + ); + assert_eq!( + up, + second.held[0].load(Ordering::Relaxed), + "the direct queue waits for every send" + ); } else { - eprintln!("queue2_tests: the direct queue alone (late {}, relay {})", late(), relay()); + eprintln!( + "queue2_tests: the direct queue alone (late {}, relay {})", + late(), + relay() + ); } drop(lists); } @@ -9227,7 +9785,9 @@ void main() { /// itself; `VICTORY_QUEUE2_REFETCH=0` shows the fault). #[test] fn warp_a_piece_fetched_while_a_later_flight_writes_it_is_fetched_again() { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, VirtualAlloc, + }; const MEM_WRITE_WATCH: u32 = 0x0020_0000; let Some(host) = host() else { return; @@ -9240,17 +9800,28 @@ void main() { .and_then(|a| unsafe { a.GetDesc1() }.ok()) .is_some_and(|d| d.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0); if !software { - eprintln!("queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)"); + eprintln!( + "queue2_tests: skipped, the host device is not the software adapter (VICTORY_D3D12_WARP=1, diagnostics)" + ); return; } if !relay() || !crate::queue2::second().is_some_and(|s| s.fetches()) { - eprintln!("queue2_tests: skipped, fetches do not go to a copy queue beside the relay (VICTORY_RELAY=1 VICTORY_QUEUE2=1)"); + eprintln!( + "queue2_tests: skipped, fetches do not go to a copy queue beside the relay (VICTORY_RELAY=1 VICTORY_QUEUE2=1)" + ); return; } const PIECE: usize = 64 << 10; const LEN: usize = 4 << 20; // SAFETY: a plain allocation of our own. - let title = unsafe { VirtualAlloc(std::ptr::null(), LEN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE) } as *mut u8; + let title = unsafe { + VirtualAlloc( + std::ptr::null(), + LEN, + MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, + PAGE_READWRITE, + ) + } as *mut u8; assert!(!title.is_null()); let dword = |at: usize| unsafe { title.add(at).cast::() }; for i in 0..LEN / 4 { @@ -9260,13 +9831,23 @@ void main() { crate::shadow::register(0x52_5252, title as u64, LEN as u64); let shadow = crate::shadow::find(title as u64, LEN as u64).expect("a host copy"); if !shadow.carded() { - eprintln!("queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)"); + eprintln!( + "queue2_tests: skipped, the copy is not in the card's memory (VICTORY_CARD_BUFFERS_MIN_MB=1)" + ); return; } - let code = compile(TWICE, windows::core::s!("main"), windows::core::s!("cs_5_1")).expect("the test's shader"); + let code = compile( + TWICE, + windows::core::s!("main"), + windows::core::s!("cs_5_1"), + ) + .expect("the test's shader"); // SAFETY: the shader's own root signature; plain creation. let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - let root: ID3D12RootSignature = host.device.CreateRootSignature(0, &code).expect("a root signature"); + let root: ID3D12RootSignature = host + .device + .CreateRootSignature(0, &code) + .expect("a root signature"); let pso = host .device .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { @@ -9291,8 +9872,10 @@ void main() { list.list.SetComputeRootSignature(&root); list.list.SetPipelineState(&pso); let constants = [(piece * PIECE + 256) as u32, first, last, spin]; - list.list.SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); - list.list.SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); + list.list + .SetComputeRoot32BitConstants(0, 4, constants.as_ptr().cast(), 0); + list.list + .SetComputeRootUnorderedAccessView(1, shadow.buffer.GetGPUVirtualAddress()); list.list.Dispatch(1, 1, 1); } list.close(); @@ -9314,7 +9897,11 @@ void main() { let took = timing.elapsed().as_secs_f64().max(1e-4); let spin = (f64::from(TRIAL) * 3.0 / took).clamp(f64::from(TRIAL), 2.0e9) as u32; // SAFETY: inside the allocation. - assert_eq!(unsafe { dword(40 * PIECE + 256).read_volatile() }, 2, "the trial's write did not come back"); + assert_eq!( + unsafe { dword(40 * PIECE + 256).read_volatile() }, + 2, + "the trial's write did not come back" + ); const AT: usize = 20 * PIECE + 256; const HALF_WAY: u32 = 0xDEAD_0001; const LEFT: u32 = 0x600D_0002; @@ -9337,7 +9924,10 @@ void main() { // A lands, as `Host::relay_land` lands it, while B is half way. let mut fetch = None; { - let plan = sent_a.card.as_ref().expect("flight A has a plan for the card's copies"); + let plan = sent_a + .card + .as_ref() + .expect("flight A has a plan for the card's copies"); host.relay_card_back(&[(sent_a.number, plan)], &mut fetch, fence_a, sent_a.number); } for (copy, ranges) in &sent_a.back { @@ -9357,7 +9947,10 @@ void main() { // nothing. Its landing must bring the piece down all the same. wait_for(fence_b); { - let plan = sent_b.card.as_ref().expect("flight B has a plan for the card's copies"); + let plan = sent_b + .card + .as_ref() + .expect("flight B has a plan for the card's copies"); host.relay_card_back(&[(sent_b.number, plan)], &mut fetch, fence_b, sent_b.number); } for (copy, ranges) in &sent_b.back { diff --git a/crates/victory-gpu/src/indirect.rs b/crates/victory-gpu/src/indirect.rs index ed784819..39cf704a 100644 --- a/crates/victory-gpu/src/indirect.rs +++ b/crates/victory-gpu/src/indirect.rs @@ -227,7 +227,11 @@ fn dxc_library() -> windows::core::Result { use windows::core::{HSTRING, w}; let mut paths: Vec = Vec::new(); if let Some(p) = std::env::var_os("VICTORY_DXC").map(std::path::PathBuf::from) { - let p = if p.is_dir() { p.join("dxcompiler.dll") } else { p }; + let p = if p.is_dir() { + p.join("dxcompiler.dll") + } else { + p + }; paths.push(std::fs::canonicalize(&p).unwrap_or(p)); } if let Some(dir) = victory_shader::emit::validator::Validator::default_path() @@ -512,7 +516,16 @@ fn clamp_into( ahead: bool, ) -> bool { let before = list.indirect_state(dst); - let recorded = record_clamp_as(c, &list.list, (dst, before), budget, src, count, spec, ahead); + let recorded = record_clamp_as( + c, + &list.list, + (dst, before), + budget, + src, + count, + spec, + ahead, + ); if recorded { list.indirect_readable(dst); } @@ -578,7 +591,14 @@ fn record_clamp_as( } None => (src_gpu, 0u32, 0u32), }; - let constants = [kind, stride, records, args_offset, has_count | (u32::from(ahead) << 1), count_offset]; + let constants = [ + kind, + stride, + records, + args_offset, + has_count | (u32::from(ahead) << 1), + count_offset, + ]; // SAFETY: an open list; our root signature and pipeline; live source, // count, scratch destination, and budget buffers. `src` and `count` stay // in `COMMON` / `GENERIC_READ` via implicit buffer promotion while `dst` @@ -637,9 +657,7 @@ fn record_clamp_as( /// per window draw. pub(crate) fn window_check() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - std::env::var_os("VICTORY_INDIRECT_WINDOW_CHECK").is_some_and(|v| v == "1") - }) + *ON.get_or_init(|| std::env::var_os("VICTORY_INDIRECT_WINDOW_CHECK").is_some_and(|v| v == "1")) } /// The compare of [`window_check`]: `words` dwords of the record a window @@ -810,7 +828,16 @@ pub(crate) fn check_hit( // (common before and after every check). let common = D3D12_RESOURCE_STATE_COMMON; let spec = (kind, step, 1); - if !record_clamp_as(c, &list.list, (&check.args, common), budget, src, None, spec, true) { + if !record_clamp_as( + c, + &list.list, + (&check.args, common), + budget, + src, + None, + spec, + true, + ) { return false; } let args = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT; @@ -826,7 +853,8 @@ pub(crate) fn check_hit( ]); list.list.SetComputeRootSignature(&cmp.root); list.list.SetPipelineState(&cmp.pso); - list.list.SetComputeRoot32BitConstants(0, 1, (&raw const words).cast(), 0); + list.list + .SetComputeRoot32BitConstants(0, 1, (&raw const words).cast(), 0); list.list.SetComputeRootShaderResourceView(1, window); list.list.SetComputeRootShaderResourceView(2, fresh); list.list.SetComputeRootUnorderedAccessView(3, results); @@ -1103,8 +1131,7 @@ void main() { const ATTEMPTS: u32 = 16; const GROUP_CAP: u32 = 16; const COUNTED_GROUPS: u32 = 5; - const EXPECTED_MESH_BUDGET: u32 = - COUNTED_GROUPS * 128 + ATTEMPTS * GROUP_CAP * 128; + const EXPECTED_MESH_BUDGET: u32 = COUNTED_GROUPS * 128 + ATTEMPTS * GROUP_CAP * 128; const DISPATCH_GROUPS: u32 = 64; let prep = compile_cs(&warp.device, crate::mesh_emu::PREP_SOURCE) @@ -1130,7 +1157,9 @@ void main() { words.add(3).write_volatile(65_535); words.add(4).write_volatile(1); words.add(5).write_volatile(1); - count_ptr.cast::().write_volatile(u32::from(!gpu_count)); + count_ptr + .cast::() + .write_volatile(u32::from(!gpu_count)); budget_ptr.cast::().write_volatile(0); next_args_ptr.cast::().write_volatile(DISPATCH_GROUPS); next_args_ptr.cast::().add(1).write_volatile(1); @@ -1186,7 +1215,8 @@ void main() { warp.list.SetComputeRootSignature(&prep.root); warp.list.SetPipelineState(&prep.pso); let constants = [STRIDE, RECORDS, 1, GROUP_CAP, 1, 1]; - warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list + .SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); warp.list.SetComputeRootUnorderedAccessView(1, args_gpu); warp.list.SetComputeRootUnorderedAccessView(2, count_gpu); warp.list.SetComputeRootUnorderedAccessView(3, prepared_gpu); @@ -1301,8 +1331,7 @@ void main() { assert_eq!( source, [ - 5, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0xff, 0xff, 0, 0, 1, 0, 0, 0, 1, 0, - 0, 0, + 5, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0xff, 0xff, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, ], "prep must leave the source arguments unchanged" ); @@ -1345,7 +1374,8 @@ void main() { let Some(mut warp) = WarpHarness::new() else { return; }; - let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE).expect("the card compare must compile on WARP"); + let compare = compile_cs(&warp.device, crate::host::CARD_COMPARE) + .expect("the card compare must compile on WARP"); const PIECE: usize = 64 << 10; const PIECES: u32 = 3; let size = PIECE * PIECES as usize; @@ -1367,7 +1397,8 @@ void main() { warp.list.SetComputeRootSignature(&compare.root); warp.list.SetPipelineState(&compare.pso); let constants = [0u32, 0, size as u32, PIECES, 0, mode]; - warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list + .SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); warp.list.SetComputeRootShaderResourceView(1, now_gpu); warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); @@ -1413,8 +1444,10 @@ void main() { let Some(mut warp) = WarpHarness::new() else { return; }; - let compare = compile_cs(&warp.device, CARD_COMPARE).expect("the card compare must compile on WARP"); - let fetch = compile_cs(&warp.device, CARD_FETCH).expect("the card fetch must compile on WARP"); + let compare = + compile_cs(&warp.device, CARD_COMPARE).expect("the card compare must compile on WARP"); + let fetch = + compile_cs(&warp.device, CARD_FETCH).expect("the card fetch must compile on WARP"); const PIECE: usize = 64 << 10; const PIECES: u32 = 3; // The copy starts 40 bytes into its piece 0: piece 0 is short, the @@ -1426,7 +1459,8 @@ void main() { let (_differs, _, differs_gpu) = warp.shared_buffer(64); let (_table, table_ptr, table_gpu) = warp.shared_buffer(4 + 64); let slots = 1u32; - let (_fetched, fetched_ptr, fetched_gpu) = warp.shared_buffer(INFLIGHT_SLOT * u64::from(slots)); + let (_fetched, fetched_ptr, fetched_gpu) = + warp.shared_buffer(INFLIGHT_SLOT * u64::from(slots)); let content: Vec = (0..size).map(|i| (i * 31 + i / 251) as u8).collect(); // SAFETY: the mappings hold what is written. unsafe { @@ -1441,7 +1475,8 @@ void main() { warp.list.SetComputeRootSignature(&compare.root); warp.list.SetPipelineState(&compare.pso); let constants = [0u32, SKEW, size as u32, pieces, 0, mode]; - warp.list.SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); + warp.list + .SetComputeRoot32BitConstants(0, 6, constants.as_ptr().cast(), 0); warp.list.SetComputeRootShaderResourceView(1, now_gpu); warp.list.SetComputeRootUnorderedAccessView(2, hashes_gpu); warp.list.SetComputeRootUnorderedAccessView(3, differs_gpu); @@ -1452,7 +1487,8 @@ void main() { warp.list.SetPipelineState(&fetch.pso); // Two groups for four pieces: the loop over pieces. let constants = [0u32, SKEW, size as u32, pieces, 0, landed, slots, 2]; - warp.list.SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); + warp.list + .SetComputeRoot32BitConstants(0, 8, constants.as_ptr().cast(), 0); warp.list.SetComputeRootShaderResourceView(1, now_gpu); warp.list.SetComputeRootUnorderedAccessView(2, differs_gpu); warp.list.SetComputeRootUnorderedAccessView(3, table_gpu); @@ -1462,7 +1498,9 @@ void main() { } warp.submit_and_wait(); // SAFETY: as above. - (0..=pieces as usize).map(|i| unsafe { table_ptr.cast::().add(i).read_volatile() }).collect() + (0..=pieces as usize) + .map(|i| unsafe { table_ptr.cast::().add(i).read_volatile() }) + .collect() }; // SAFETY (each): inside the mapping of the copy. let set = |at: usize, value: u8| unsafe { now_ptr.add(at).write_volatile(value) }; @@ -1797,7 +1835,8 @@ void main() { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); - warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); } warp.submit_and_wait(); // SAFETY: the work is done; mapped buffers. @@ -1805,24 +1844,46 @@ void main() { ( (budget_ptr as *const u32).read_volatile(), (budget_ptr as *const u32).add(1).read_volatile(), - std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4).to_vec(), + std::slice::from_raw_parts(readback_ptr.cast::().cast_const(), total / 4) + .to_vec(), ) }; for (i, groups) in filled.into_iter().enumerate() { let rec = &out[i * 8..i * 8 + 4]; - assert_eq!(rec, [groups, u32::from(groups > 0).max(1).min(1), 1, 0xAB00 + i as u32], "filled record {i}, ahead {ahead}"); + assert_eq!( + rec, + [ + groups, + u32::from(groups > 0).max(1).min(1), + 1, + 0xAB00 + i as u32 + ], + "filled record {i}, ahead {ahead}" + ); } let charged_filled = (5 + 519) * 128; if ahead { for i in filled.len()..RECORDS as usize { - assert_eq!(out[i * 8..i * 8 + 3], [0, 0, 0], "unfilled slot {i} must come out empty"); - assert_eq!(out[i * 8 + 3], u32::MAX, "the words after the record are copied as they are"); + assert_eq!( + out[i * 8..i * 8 + 3], + [0, 0, 0], + "unfilled slot {i} must come out empty" + ); + assert_eq!( + out[i * 8 + 3], + u32::MAX, + "the words after the record are copied as they are" + ); } assert_eq!(spent, charged_filled, "unfilled slots charge nothing"); assert_eq!(largest, 519, "and are not counted as asked for"); } else { // Thirteen slots at 65,535 groups: sixteen would be all of it. - assert_eq!(spent, charged_filled + 13 * 65535 * 128, "clamped one by one, each slot is charged the most"); + assert_eq!( + spent, + charged_filled + 13 * 65535 * 128, + "clamped one by one, each slot is charged the most" + ); assert_eq!(largest, u32::MAX); } } @@ -1851,10 +1912,10 @@ void main() { let words: [u32; 6] = [ if i == 0 { 1 << 24 } else { 1 << 22 }, // IndexCount if i == 0 { 1 } else { u32::MAX }, // InstanceCount -> clamps to 16 (cost = 1 << 26) - 1000 + i as u32, // StartIndexLocation - (-200i32 + i as i32) as u32, // BaseVertexLocation - 5000 + i as u32, // StartInstanceLocation - 0xCAFE_0000 | (i as u32), // Extra stride word + 1000 + i as u32, // StartIndexLocation + (-200i32 + i as i32) as u32, // BaseVertexLocation + 5000 + i as u32, // StartInstanceLocation + 0xCAFE_0000 | (i as u32), // Extra stride word ]; let base = i * (STRIDE as usize); for (w, val) in words.into_iter().enumerate() { @@ -2072,7 +2133,8 @@ void main() { D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT, D3D12_RESOURCE_STATE_COPY_SOURCE, )]); - warp.list.CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); + warp.list + .CopyBufferRegion(&readback_buf, 0, &dst_buf, 0, total as u64); } warp.submit_and_wait(); // SAFETY: the work is done; mapped buffers. @@ -2087,7 +2149,10 @@ void main() { for i in 1..counts.len() { assert_eq!(out[i * 4..i * 4 + 4], [0, 0, 7, 9], "record {i} runs empty"); } - assert_eq!(spent, BUDGET_CAP, "the record that did not fit took the rest"); + assert_eq!( + spent, BUDGET_CAP, + "the record that did not fit took the rest" + ); } /// The list's budget starts empty at each submission, wherever it @@ -2161,7 +2226,8 @@ void main() { list.list.SetComputeRootSignature(&worker.root); list.list.SetPipelineState(&worker.pso); list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); - list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + list.list + .ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); } list.close(); assert_eq!(host.log_messages(), None, "the debug layer found an error"); @@ -2171,7 +2237,10 @@ void main() { let hits = unsafe { (hits_ptr as *const u32).read_volatile() }; // The small record comes after the big ones spent the budget: // it runs empty, in every round alike (none carries over). - assert_eq!(hits, 0, "round {round}: the spent budget empties the record after it"); + assert_eq!( + hits, 0, + "round {round}: the spent budget empties the record after it" + ); } // A recording with only the small record: the budget is empty // again, so it runs. @@ -2181,7 +2250,8 @@ void main() { list.list.SetComputeRootSignature(&worker.root); list.list.SetPipelineState(&worker.pso); list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); - list.list.ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); + list.list + .ExecuteIndirect(&signature, 1, &scratch, 0, None, 0); } list.close(); assert_eq!(host.log_messages(), None, "the debug layer found an error"); @@ -2229,24 +2299,43 @@ void main() { let spec = (KIND_DISPATCH, STEP, records.len() as u32); let scratch = bound_ahead(&list, (&src, 0), spec).unwrap(); // Record 0: nothing wrote it. - assert!(check_hit(&list, (&src, 0), (KIND_DISPATCH, STEP), &scratch, 0)); + assert!(check_hit( + &list, + (&src, 0), + (KIND_DISPATCH, STEP), + &scratch, + 0 + )); // Record 1 is written on the card after the window's clamp. let read = D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE; // SAFETY: an open list; `src` was read by the clamp (promoted to a // shader read), `patch` is common; both live until the list has run. unsafe { - list.list.ResourceBarrier(&[transition(&src, read, D3D12_RESOURCE_STATE_COPY_DEST)]); - list.list.CopyBufferRegion(&src, u64::from(STEP), &patch, 0, 12); - list.list.ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, read)]); + list.list + .ResourceBarrier(&[transition(&src, read, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.list + .CopyBufferRegion(&src, u64::from(STEP), &patch, 0, 12); + list.list + .ResourceBarrier(&[transition(&src, D3D12_RESOURCE_STATE_COPY_DEST, read)]); } let at = u64::from(STEP); - assert!(check_hit(&list, (&src, at), (KIND_DISPATCH, STEP), &scratch, at)); + assert!(check_hit( + &list, + (&src, at), + (KIND_DISPATCH, STEP), + &scratch, + at + )); list.close(); assert_eq!(host.log_messages(), None, "the debug layer found an error"); host.execute(&[&list]); let (checked, differed, window, fresh) = list.window_check().unwrap().take(); list.reset(); - assert_eq!((checked, differed), (2, 1), "two checks, the written record differs"); + assert_eq!( + (checked, differed), + (2, 1), + "two checks, the written record differs" + ); assert_eq!(window[..3], [5, 1, 1], "as the window clamped it"); assert_eq!(fresh[..3], [11, 2, 1], "as it is now"); } @@ -2284,8 +2373,10 @@ void main() { const STRIDE: u32 = 12; const STEP: u32 = 32; let windows: [&[u32]; 2] = [&[1, 2, 3, 4], &[10, 11, 12, 13]]; - let sources: Vec = - windows.iter().map(|g| dispatch_records(&warp, g, STEP)).collect(); + let sources: Vec = windows + .iter() + .map(|g| dispatch_records(&warp, g, STEP)) + .collect(); let (_budget_buf, budget_ptr, budget_gpu) = warp.shared_buffer(256); let (_hits_buf, hits_ptr, hits_gpu) = warp.shared_buffer(256); let dst_buf = warp.default_uav(u64::from(STEP) * 4); @@ -2315,7 +2406,8 @@ void main() { warp.list.SetPipelineState(&warp.worker.pso); warp.list.SetComputeRootUnorderedAccessView(0, hits_gpu); for i in 0..groups.len() as u64 { - warp.list.ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0); + warp.list + .ExecuteIndirect(&sig, 1, &dst_buf, i * u64::from(STEP), None, 0); } } } @@ -2402,7 +2494,10 @@ void main() { for (groups, src) in windows.iter().zip(&sources) { let spec = (KIND_DISPATCH, STEP, groups.len() as u32); let scratch = bound_ahead(&list, (src, 0), spec).unwrap(); - assert_eq!(list.indirect_state(&scratch), D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + assert_eq!( + list.indirect_state(&scratch), + D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT + ); // SAFETY: an open list; the worker's root signature and // pipeline; buffers the test holds until the list has run. unsafe { @@ -2411,7 +2506,8 @@ void main() { list.list.SetComputeRootUnorderedAccessView(0, hits_gpu); for i in 0..groups.len() as u64 { let at = i * u64::from(STEP); - list.list.ExecuteIndirect(&signature, 1, &scratch, at, None, 0); + list.list + .ExecuteIndirect(&signature, 1, &scratch, at, None, 0); } } } @@ -2561,7 +2657,10 @@ void work() { DepthOrArraySize: 1, MipLevels: 1, Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Flags: flags, ..Default::default() }; @@ -2592,7 +2691,10 @@ void work() { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -2607,7 +2709,12 @@ void work() { out.unwrap() } - fn heap(device: &ID3D12Device, kind: D3D12_DESCRIPTOR_HEAP_TYPE, count: u32, visible: bool) -> ID3D12DescriptorHeap { + fn heap( + device: &ID3D12Device, + kind: D3D12_DESCRIPTOR_HEAP_TYPE, + count: u32, + visible: bool, + ) -> ID3D12DescriptorHeap { let flags = if visible { D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE } else { @@ -2626,7 +2733,12 @@ void work() { } } - fn pipeline(device: &ID3D12Device, root: &ID3D12RootSignature, vs: &[u8], ps: &[u8]) -> ID3D12PipelineState { + fn pipeline( + device: &ID3D12Device, + root: &ID3D12RootSignature, + vs: &[u8], + ps: &[u8], + ) -> ID3D12PipelineState { let code = |bytes: &[u8]| D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len(), @@ -2662,7 +2774,10 @@ void work() { NumRenderTargets: 1, RTVFormats: formats, DSVFormat: DXGI_FORMAT_D32_FLOAT, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, ..Default::default() }; device.CreateGraphicsPipelineState(&desc).unwrap() @@ -2686,7 +2801,9 @@ void work() { D3D12CreateDevice(None, D3D_FEATURE_LEVEL_12_0, &mut device).ok()?; let device = device?; let desc = CreateDXGIFactory2::(DXGI_CREATE_FACTORY_FLAGS(0)) - .and_then(|factory| factory.EnumAdapterByLuid::(device.GetAdapterLuid())) + .and_then(|factory| { + factory.EnumAdapterByLuid::(device.GetAdapterLuid()) + }) .ok()? .cast::() .ok()? @@ -2704,8 +2821,9 @@ void work() { ..Default::default() }) .ok()?; - let allocator: ID3D12CommandAllocator = - device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; let list: ID3D12GraphicsCommandList = device .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) .ok()?; @@ -2730,7 +2848,15 @@ void work() { .ok()?; let size = (WIDTH, HEIGHT); - let colour = |state| texture(&device, size, DXGI_FORMAT_R8G8B8A8_UNORM, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, state); + let colour = |state| { + texture( + &device, + size, + DXGI_FORMAT_R8G8B8A8_UNORM, + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET, + state, + ) + }; let target = [ colour(D3D12_RESOURCE_STATE_RENDER_TARGET), colour(D3D12_RESOURCE_STATE_RENDER_TARGET), @@ -2779,13 +2905,17 @@ void work() { // Target and depth views. let rtvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, false); - let rtv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) as usize; + let rtv_step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV) + as usize; let mut targets = [rtvs.GetCPUDescriptorHandleForHeapStart(); 2]; targets[1].ptr += rtv_step; device.CreateRenderTargetView(&target[0], None, targets[0]); device.CreateRenderTargetView(&target[1], None, targets[1]); let dsvs = heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, false); - let dsv_step = device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) as usize; + let dsv_step = device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV) + as usize; let depth_written = dsvs.GetCPUDescriptorHandleForHeapStart(); let mut depth_tested = depth_written; depth_tested.ptr += dsv_step; @@ -2809,7 +2939,11 @@ void work() { heap(&device, D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER, 1, true), ]; for views in &view_heaps { - device.CreateShaderResourceView(&image, None, views.GetCPUDescriptorHandleForHeapStart()); + device.CreateShaderResourceView( + &image, + None, + views.GetCPUDescriptorHandleForHeapStart(), + ); } let tables = [ view_heaps[0].GetGPUDescriptorHandleForHeapStart(), @@ -2866,7 +3000,9 @@ void work() { let run: ID3D12CommandList = self.list.cast().unwrap(); self.queue.ExecuteCommandLists(&[Some(run)]); self.queue.Signal(&self.fence, self.submitted).unwrap(); - self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .unwrap(); WaitForSingleObject(self.event, INFINITE); self.allocator.Reset().unwrap(); self.list.Reset(&self.allocator, None).unwrap(); @@ -2937,7 +3073,11 @@ void work() { l.ResourceBarrier(&[transition(&self.other, read, target)]); } Between::DepthMove => { - let (from, to) = if odd == 0 { (written, tested) } else { (tested, written) }; + let (from, to) = if odd == 0 { + (written, tested) + } else { + (tested, written) + }; l.ResourceBarrier(&[transition(&self.depth, from, to)]); } Between::Heaps => { @@ -2945,7 +3085,12 @@ void work() { l.SetGraphicsRootDescriptorTable(0, self.tables[odd]); } Between::Targets => { - l.OMSetRenderTargets(1, Some(&self.targets[odd]), false, Some(&self.depth_tested)); + l.OMSetRenderTargets( + 1, + Some(&self.targets[odd]), + false, + Some(&self.depth_tested), + ); } Between::Compute | Between::ComputeWithWaits => { let waits = between == Between::ComputeWithWaits; @@ -2954,7 +3099,10 @@ void work() { } l.SetComputeRootSignature(&self.work_root); l.SetPipelineState(&self.work); - l.SetComputeRootUnorderedAccessView(0, self.words.GetGPUVirtualAddress()); + l.SetComputeRootUnorderedAccessView( + 0, + self.words.GetGPUVirtualAddress(), + ); l.Dispatch(1, 1, 1); if waits { l.ResourceBarrier(&[super::uav_barrier()]); @@ -2976,7 +3124,14 @@ void work() { l.Reset(&self.allocator, None).unwrap(); } else { l.EndQuery(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 1); - l.ResolveQueryData(&self.stamps, D3D12_QUERY_TYPE_TIMESTAMP, 0, 2, &self.back, 0); + l.ResolveQueryData( + &self.stamps, + D3D12_QUERY_TYPE_TIMESTAMP, + 0, + 2, + &self.back, + 0, + ); } } } @@ -2993,8 +3148,13 @@ void work() { stamps[1].saturating_sub(stamps[0]) }; // SAFETY: a plain query of our queue. - let frequency = unsafe { self.queue.GetTimestampFrequency() }.unwrap_or(1).max(1); - (ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), recording) + let frequency = unsafe { self.queue.GetTimestampFrequency() } + .unwrap_or(1) + .max(1); + ( + ticks as f64 * 1e6 / frequency as f64 / f64::from(drawn.max(1)), + recording, + ) } } @@ -3005,19 +3165,46 @@ void work() { eprintln!("no hardware adapter, or our shaders did not compile; skipped"); return; }; - eprintln!("bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", rig.card); + eprintln!( + "bare command cost on {}: {DRAWS} one-triangle draws into {WIDTH}x{HEIGHT}, three batches each", + rig.card + ); // The first batch pays for whatever the driver does at first use. rig.batch(Between::Nothing, 1); let variants = [ ("(a) nothing changes between draws", Between::Nothing, 1), ("(b) another pipeline every draw", Between::Pipeline, 1), - ("(c) a barrier pair on a second texture every draw", Between::BarrierPair, 1), - ("(d) the tested depth texture moved between write and read every draw", Between::DepthMove, 1), - ("(e) another pair of descriptor heaps every draw", Between::Heaps, 1), + ( + "(c) a barrier pair on a second texture every draw", + Between::BarrierPair, + 1, + ), + ( + "(d) the tested depth texture moved between write and read every draw", + Between::DepthMove, + 1, + ), + ( + "(e) another pair of descriptor heaps every draw", + Between::Heaps, + 1, + ), ("(f) another colour target every draw", Between::Targets, 1), - ("(g) nothing changes, in 100 lists run one by one", Between::Nothing, 100), - ("(h) a compute pass of ours of one group before every draw", Between::Compute, 1), - ("(i) the same pass between two waits for earlier shader writes", Between::ComputeWithWaits, 1), + ( + "(g) nothing changes, in 100 lists run one by one", + Between::Nothing, + 100, + ), + ( + "(h) a compute pass of ours of one group before every draw", + Between::Compute, + 1, + ), + ( + "(i) the same pass between two waits for earlier shader writes", + Between::ComputeWithWaits, + 1, + ), ]; let mut least = Vec::new(); for (name, between, lists) in variants { @@ -3029,7 +3216,9 @@ void work() { ); least.push(runs[0].0); } - assert!(least.iter().all(|us| us.is_finite() && *us > 0.0), "the card gave no time for a batch"); + assert!( + least.iter().all(|us| us.is_finite() && *us > 0.0), + "the card gave no time for a batch" + ); } } - diff --git a/crates/victory-gpu/src/inplace.rs b/crates/victory-gpu/src/inplace.rs index 6ecf22e6..a1dea439 100644 --- a/crates/victory-gpu/src/inplace.rs +++ b/crates/victory-gpu/src/inplace.rs @@ -60,7 +60,12 @@ const MEM_WRITE_WATCH: u32 = 0x20_0000; /// first census. pub(crate) fn probe_level() -> u8 { static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); - *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE_PROBE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) + *LEVEL.get_or_init(|| { + std::env::var("VICTORY_INPLACE_PROBE") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0) + }) } /// `VICTORY_INPLACE`: 0 (unset) off. 1: a window of title memory outside @@ -87,7 +92,12 @@ pub(crate) fn probe_level() -> u8 { /// call before such a call once it takes them over. pub(crate) fn level() -> u8 { static LEVEL: std::sync::OnceLock = std::sync::OnceLock::new(); - *LEVEL.get_or_init(|| std::env::var("VICTORY_INPLACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)) + *LEVEL.get_or_init(|| { + std::env::var("VICTORY_INPLACE") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(0) + }) } /// The most title memory in place at once, in bytes @@ -95,7 +105,13 @@ pub(crate) fn level() -> u8 { /// memory, also those the title never touched. fn most() -> u64 { static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); - *MOST.get_or_init(|| std::env::var("VICTORY_INPLACE_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(4096) << 20) + *MOST.get_or_init(|| { + std::env::var("VICTORY_INPLACE_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(4096) + << 20 + }) } /// In place now: windows and their bytes, title buffers and their bytes; @@ -118,7 +134,11 @@ pub(crate) struct Placed { /// as a heap of their own and places one buffer over all of them. `Err` /// with nothing if the memory is not private memory committed whole /// (nothing was asked of the host), with the host's error if it refused. -pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result> { +pub(crate) fn place_part( + device: &ID3D12Device, + start: u64, + len: u64, +) -> Result> { let at = start & !(K64 as u64 - 1); let bytes = (start + len.max(1)).next_multiple_of(K64 as u64) - at; if !private_whole(at as usize, bytes as usize) { @@ -128,7 +148,12 @@ pub(crate) fn place_part(device: &ID3D12Device, start: u64, len: u64) -> Result< let buffer = place(device, &heap, 0, bytes).map_err(Some)?; // SAFETY: a live buffer. let gpu = unsafe { buffer.GetGPUVirtualAddress() } + (start - at); - Ok(Placed { buffer, heap, gpu, bias: start - at }) + Ok(Placed { + buffer, + heap, + gpu, + bias: start - at, + }) } /// Title memory `[start, start + len)` in place, for a window outside @@ -194,7 +219,11 @@ fn say() { static LAST: AtomicU64 = AtomicU64::new(0); let now = crate::host::now_ms(); let last = LAST.load(Ordering::Relaxed); - if now < last + 10_000 || LAST.compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed).is_err() { + if now < last + 10_000 + || LAST + .compare_exchange(last, now, Ordering::Relaxed, Ordering::Relaxed) + .is_err() + { return; } let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); @@ -228,9 +257,15 @@ pub(crate) fn open(device: &ID3D12Device, from: From) -> windows::core::Result device.cast::()?.OpenExistingHeapFromAddress(at as *const c_void), - From::Part(at, bytes) => device.cast::()?.OpenExistingHeapFromAddress1(at as *const c_void, bytes), - From::Section(handle) => device.cast::()?.OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), + From::Region(at) => device + .cast::()? + .OpenExistingHeapFromAddress(at as *const c_void), + From::Part(at, bytes) => device + .cast::()? + .OpenExistingHeapFromAddress1(at as *const c_void, bytes), + From::Section(handle) => device + .cast::()? + .OpenExistingHeapFromFileMapping(HANDLE(handle as *mut c_void)), } } } @@ -242,7 +277,10 @@ fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -251,12 +289,27 @@ fn buffer_desc(size: u64, flags: D3D12_RESOURCE_FLAGS) -> D3D12_RESOURCE_DESC { /// A buffer of `size` bytes at `offset` (a multiple of 64 KiB) of an /// opened heap, which shaders may read and write, in the common state. -pub(crate) fn place(device: &ID3D12Device, heap: &ID3D12Heap, offset: u64, size: u64) -> windows::core::Result { +pub(crate) fn place( + device: &ID3D12Device, + heap: &ID3D12Heap, + offset: u64, + size: u64, +) -> windows::core::Result { let mut placed: Option = None; // The heap is cross-adapter shared, so the buffer must say so too. - let flags = D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + let flags = + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; // SAFETY: plain creation in a live heap. - unsafe { device.CreatePlacedResource(heap, offset, &buffer_desc(size, flags), D3D12_RESOURCE_STATE_COMMON, None, &mut placed)? }; + unsafe { + device.CreatePlacedResource( + heap, + offset, + &buffer_desc(size, flags), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut placed, + )? + }; placed.ok_or_else(windows::core::Error::empty) } @@ -276,8 +329,11 @@ struct Views { sections: Vec<(usize, u64, bool)>, } -static VIEWS: Mutex = - Mutex::new(Views { views: BTreeMap::new(), pages: BTreeMap::new(), sections: Vec::new() }); +static VIEWS: Mutex = Mutex::new(Views { + views: BTreeMap::new(), + pages: BTreeMap::new(), + sections: Vec::new(), +}); fn views() -> std::sync::MutexGuard<'static, Views> { VIEWS.lock().unwrap_or_else(|e| e.into_inner()) @@ -286,9 +342,27 @@ fn views() -> std::sync::MutexGuard<'static, Views> { /// The runtime made a section of `bytes` for physical pages; `committed` /// if with `SEC_COMMIT` (only such a section can be opened as a heap). pub fn title_memory_section(section: usize, bytes: u64, committed: bool) { - let mut v = views(); - v.sections.retain(|s| s.0 != section); - v.sections.push((section, bytes, committed)); + { + let mut v = views(); + v.sections.retain(|s| s.0 != section); + v.sections.push((section, bytes, committed)); + } + // A view of our own made on an earlier section that had this handle's + // number shows that section's pages, not this one's: it is forgotten + // (left mapped: nothing reads it any more) and the next store through + // a view of ours maps this section. + let gone = OWN + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_mut() + .and_then(|own| own.remove(§ion)) + .flatten(); + if gone.is_some() { + tracing::info!( + section, + "a section handle's number came round again: our own view of the earlier section is forgotten" + ); + } } /// The runtime mapped `[at, at + len)` as a view of `section` from @@ -298,7 +372,10 @@ pub fn title_memory_view(at: usize, len: usize, section: usize, offset: u64) { let mut v = views(); v.views.insert(at, (len, section, offset)); for k in 0..len.div_ceil(K64) { - v.pages.entry((section, offset + (k * K64) as u64)).or_default().push(at + k * K64); + v.pages + .entry((section, offset + (k * K64) as u64)) + .or_default() + .push(at + k * K64); } } // This view is writable from now on: a guard over the same bytes at @@ -316,8 +393,20 @@ pub(crate) fn views_gone(at: usize, len: usize) { return; } let end = at.saturating_add(len); - let first = v.views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at).map(|(base, _)| *base); - let gone: Vec = first.into_iter().chain(v.views.range(at.saturating_add(1)..end).map(|(base, _)| *base)).collect(); + let first = v + .views + .range(..=at) + .next_back() + .filter(|(base, view)| *base + view.0 > at) + .map(|(base, _)| *base); + let gone: Vec = first + .into_iter() + .chain( + v.views + .range(at.saturating_add(1)..end) + .map(|(base, _)| *base), + ) + .collect(); for base in gone { let Some((bytes, section, offset)) = v.views.remove(&base) else { continue; @@ -364,7 +453,10 @@ pub(crate) fn pages_of(page: usize) -> Vec { if within >= bytes || !within.is_multiple_of(K64) { return Vec::new(); } - v.pages.get(&(section, offset + within as u64)).cloned().unwrap_or_default() + v.pages + .get(&(section, offset + within as u64)) + .cloned() + .unwrap_or_default() } /// The title views that show any of the physical bytes `[offset, offset + @@ -418,9 +510,38 @@ pub(crate) fn views_of_section(section: usize, offset: u64, len: usize) -> Vec<( /// told the page was written (`crate::watch::wrote_own`) so that every /// other copy of it takes it again, and the copy that wrote it notes the /// page current (`put_back_own` in `crate::shadow`). +/// +/// `VICTORY_BACK_OWN_VIEW=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, for measuring it in one scene. pub(crate) fn back_own() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_BACK_OWN_VIEW").is_some_and(|v| v == "1")) + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_BACK_OWN_VIEW").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_secs() + / 20) + % 2 + == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "copy-back through views of our own from now (VICTORY_BACK_OWN_VIEW=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } } /// A view of our own on a whole section of the title's physical pages: @@ -456,7 +577,10 @@ pub(crate) fn write_own(at: usize, bytes: &[u8]) -> Option> { return None; } let offset = offset + (at - base) as u64; - let shown = v.pages.get(&(section, offset - offset % K64 as u64))?.clone(); + let shown = v + .pages + .get(&(section, offset - offset % K64 as u64))? + .clone(); if shown.len() > crate::watch::MANY_VIEWS { return None; } @@ -503,7 +627,12 @@ pub(crate) fn write_own(at: usize, bytes: &[u8]) -> Option> { // once more through ours, which changes nothing if they are. // SAFETY: a block inside our own view. let there = unsafe { - mem::VirtualAlloc((view.base + block * K64) as *const c_void, K64, mem::MEM_COMMIT, mem::PAGE_READWRITE) + mem::VirtualAlloc( + (view.base + block * K64) as *const c_void, + K64, + mem::MEM_COMMIT, + mem::PAGE_READWRITE, + ) }; if there.is_null() { return None; @@ -512,7 +641,13 @@ pub(crate) fn write_own(at: usize, bytes: &[u8]) -> Option> { } // SAFETY: committed bytes inside our own view; the source is the // caller's slice. - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), (view.base + offset as usize) as *mut u8, bytes.len()) }; + unsafe { + std::ptr::copy_nonoverlapping( + bytes.as_ptr(), + (view.base + offset as usize) as *mut u8, + bytes.len(), + ) + }; Some(shown) } @@ -532,7 +667,11 @@ pub(crate) enum Cover { fn cover_in(views: &BTreeMap, at: usize, len: usize) -> Cover { let end = at + len.max(1); - let Some((&base, &(bytes, section, offset))) = views.range(..=at).next_back().filter(|(base, view)| *base + view.0 > at) else { + let Some((&base, &(bytes, section, offset))) = views + .range(..=at) + .next_back() + .filter(|(base, view)| *base + view.0 > at) + else { return Cover::None; }; let first = (section, offset + (at - base) as u64); @@ -544,7 +683,11 @@ fn cover_in(views: &BTreeMap, at: usize, len: usize) one &= s == first.0 && o == first.1 + (reached - at) as u64; reached += bytes; } - if one { Cover::Run(first.0, first.1) } else { Cover::Scattered } + if one { + Cover::Run(first.0, first.1) + } else { + Cover::Scattered + } } /// [`Cover`] of `[at, at + len)` by the title's views as they are now. @@ -602,18 +745,34 @@ impl Rig { // SAFETY: plain creation of objects of our own. unsafe { let queue: ID3D12CommandQueue = - device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE_DIRECT, ..Default::default() })?; - let allocator: ID3D12CommandAllocator = device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; - let list: ID3D12GraphicsCommandList = device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_DIRECT, + ..Default::default() + })?; + let allocator: ID3D12CommandAllocator = + device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT)?; + let list: ID3D12GraphicsCommandList = + device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None)?; list.Close()?; let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; let event = CreateEventW(None, false, false, None)?; - Ok(Rig { device: device.clone(), queue, allocator, list, fence, done: 0, event }) + Ok(Rig { + device: device.clone(), + queue, + allocator, + list, + fence, + done: 0, + event, + }) } } /// Records with `record`, runs it and waits (ten seconds at most). - fn run(&mut self, record: impl FnOnce(&ID3D12GraphicsCommandList)) -> windows::core::Result<()> { + fn run( + &mut self, + record: impl FnOnce(&ID3D12GraphicsCommandList), + ) -> windows::core::Result<()> { // SAFETY: our own list and queue, one run at a time. unsafe { self.allocator.Reset()?; @@ -625,26 +784,51 @@ impl Rig { self.queue.Signal(&self.fence, self.done)?; self.fence.SetEventOnCompletion(self.done, self.event)?; if WaitForSingleObject(self.event, 10_000).0 != 0 { - return Err(windows::core::Error::from_hresult(windows::Win32::Foundation::E_FAIL)); + return Err(windows::core::Error::from_hresult( + windows::Win32::Foundation::E_FAIL, + )); } self.device.GetDeviceRemovedReason() } } - fn committed(&self, kind: D3D12_HEAP_TYPE, size: u64, state: D3D12_RESOURCE_STATES) -> windows::core::Result { - let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() }; + fn committed( + &self, + kind: D3D12_HEAP_TYPE, + size: u64, + state: D3D12_RESOURCE_STATES, + ) -> windows::core::Result { + let heap = D3D12_HEAP_PROPERTIES { + Type: kind, + ..Default::default() + }; let mut buffer: Option = None; // SAFETY: plain creation. unsafe { - self.device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), state, None, &mut buffer)? + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(size, D3D12_RESOURCE_FLAG_NONE), + state, + None, + &mut buffer, + )? }; buffer.ok_or_else(windows::core::Error::empty) } /// What the GPU reads of `size` bytes of `resource` from `offset`. - fn fetch(&mut self, resource: &ID3D12Resource, offset: u64, size: usize) -> windows::core::Result> { - let back = self.committed(D3D12_HEAP_TYPE_READBACK, size as u64, D3D12_RESOURCE_STATE_COPY_DEST)?; + fn fetch( + &mut self, + resource: &ID3D12Resource, + offset: u64, + size: usize, + ) -> windows::core::Result> { + let back = self.committed( + D3D12_HEAP_TYPE_READBACK, + size as u64, + D3D12_RESOURCE_STATE_COPY_DEST, + )?; // SAFETY: two live buffers, the range inside both. self.run(|list| unsafe { list.CopyBufferRegion(&back, 0, resource, offset, size as u64) })?; let mut data = std::ptr::null_mut(); @@ -658,8 +842,17 @@ impl Rig { } /// The GPU writes `bytes` at `offset` of `resource` (a copy). - fn store(&mut self, resource: &ID3D12Resource, offset: u64, bytes: &[u8]) -> windows::core::Result<()> { - let up = self.committed(D3D12_HEAP_TYPE_UPLOAD, bytes.len() as u64, D3D12_RESOURCE_STATE_GENERIC_READ)?; + fn store( + &mut self, + resource: &ID3D12Resource, + offset: u64, + bytes: &[u8], + ) -> windows::core::Result<()> { + let up = self.committed( + D3D12_HEAP_TYPE_UPLOAD, + bytes.len() as u64, + D3D12_RESOURCE_STATE_GENERIC_READ, + )?; let mut data = std::ptr::null_mut(); // SAFETY: the mapping holds the buffer's bytes until unmapped. unsafe { @@ -668,7 +861,9 @@ impl Rig { up.Unmap(0, None); } // SAFETY: two live buffers, the range inside both. - self.run(|list| unsafe { list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) }) + self.run(|list| unsafe { + list.CopyBufferRegion(resource, offset, &up, 0, bytes.len() as u64) + }) } /// A compute shader stores, through a root unordered-access view at @@ -679,15 +874,35 @@ impl Rig { // SAFETY: the source and names live through the call; then the // blob's own bytes, which hold the root signature too. let (root, pso): (ID3D12RootSignature, ID3D12PipelineState) = unsafe { - D3DCompile(SOURCE.as_ptr().cast(), SOURCE.len(), s!("inplace"), None, None, s!("main"), s!("cs_5_1"), 0, 0, &mut code, None)?; + D3DCompile( + SOURCE.as_ptr().cast(), + SOURCE.len(), + s!("inplace"), + None, + None, + s!("main"), + s!("cs_5_1"), + 0, + 0, + &mut code, + None, + )?; let code = code.ok_or_else(windows::core::Error::empty)?; - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); let root: ID3D12RootSignature = self.device.CreateRootSignature(0, bytes)?; - let pso = self.device.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { - pRootSignature: std::mem::transmute_copy(&root), - CS: D3D12_SHADER_BYTECODE { pShaderBytecode: bytes.as_ptr().cast(), BytecodeLength: bytes.len() }, - ..Default::default() - })?; + let pso = + self.device + .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { + pRootSignature: std::mem::transmute_copy(&root), + CS: D3D12_SHADER_BYTECODE { + pShaderBytecode: bytes.as_ptr().cast(), + BytecodeLength: bytes.len(), + }, + ..Default::default() + })?; (root, pso) }; // SAFETY: an open list of ours; the view names a live buffer. @@ -702,11 +917,21 @@ impl Rig { /// Milliseconds the card takes to copy `bytes` of `from` into its own /// memory, the best of three. fn copy_ms(&mut self, from: &ID3D12Resource, bytes: u64) -> windows::core::Result { - let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() }; + let heap = D3D12_HEAP_PROPERTIES { + Type: D3D12_HEAP_TYPE_DEFAULT, + ..Default::default() + }; let mut to: Option = None; // SAFETY: plain creation. unsafe { - self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), D3D12_RESOURCE_STATE_COMMON, None, &mut to)? + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &buffer_desc(bytes, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COMMON, + None, + &mut to, + )? }; let to = to.ok_or_else(windows::core::Error::empty)?; let mut best = f64::MAX; @@ -723,7 +948,10 @@ impl Rig { fn fill(at: *mut u8, len: usize, seed: u8) { for i in 0..len { // SAFETY: the caller's own committed memory of `len` bytes. - unsafe { at.add(i).write((i as u8).wrapping_mul(31).wrapping_add(seed)) }; + unsafe { + at.add(i) + .write((i as u8).wrapping_mul(31).wrapping_add(seed)) + }; } } @@ -734,10 +962,21 @@ fn same(at: *const u8, bytes: &[u8]) -> bool { /// The process's working set in MB. fn working_set_mb() -> u64 { - use windows_sys::Win32::System::ProcessStatus::{K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS}; - let mut counters = PROCESS_MEMORY_COUNTERS { cb: size_of::() as u32, ..Default::default() }; + use windows_sys::Win32::System::ProcessStatus::{ + K32GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, + }; + let mut counters = PROCESS_MEMORY_COUNTERS { + cb: size_of::() as u32, + ..Default::default() + }; // SAFETY: our own process and a sized structure. - unsafe { K32GetProcessMemoryInfo(windows_sys::Win32::System::Threading::GetCurrentProcess(), &mut counters, counters.cb) }; + unsafe { + K32GetProcessMemoryInfo( + windows_sys::Win32::System::Threading::GetCurrentProcess(), + &mut counters, + counters.cb, + ) + }; counters.WorkingSetSize as u64 >> 20 } @@ -768,7 +1007,11 @@ pub(crate) struct Probe { /// gives the card's memory account (`Host::video_memory`) where there is /// one. Nothing of the title's is touched. `mb` is the size of the cost /// measurement (0 leaves it out). -pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]>, mb: usize) -> Probe { +pub(crate) fn probe( + device: &ID3D12Device, + memory: &dyn Fn() -> Option<[u64; 4]>, + mb: usize, +) -> Probe { let mut p = Probe::default(); let mut rig = match Rig::new(device) { Ok(rig) => rig, @@ -779,7 +1022,13 @@ pub(crate) fn probe(device: &ID3D12Device, memory: &dyn Fn() -> Option<[u64; 4]> }; let mut options = D3D12_FEATURE_DATA_D3D12_OPTIONS::default(); // SAFETY: a plain query that fills our structure. - let _ = unsafe { device.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS, (&raw mut options).cast(), size_of_val(&options) as u32) }; + let _ = unsafe { + device.CheckFeatureSupport( + D3D12_FEATURE_D3D12_OPTIONS, + (&raw mut options).cast(), + size_of_val(&options) as u32, + ) + }; p.lines.push(format!( "the device: ID3D12Device3 {}, ID3D12Device13 {} (parts of an allocation); cross-adapter row-major textures {}; heap tier {}", device.cast::().is_ok(), @@ -824,7 +1073,13 @@ unsafe fn private(p: &mut Probe, rig: &mut Rig) { const SIZE: usize = 64 * K64; // SAFETY (the whole function): the allocation below, `SIZE` bytes. unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + let base = mem::VirtualAlloc( + std::ptr::null(), + SIZE, + mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, + mem::PAGE_READWRITE, + ) + .cast::(); if base.is_null() { p.lines.push("private memory: none to try with".to_owned()); return; @@ -832,27 +1087,47 @@ unsafe fn private(p: &mut Probe, rig: &mut Rig) { // The part: 16 pages from the 16th on. let (at, bytes) = (base.add(16 * K64), 16 * K64); let whole = open(&rig.device, From::Region(base as usize)); - p.lines.push(format!("private memory, the whole allocation (OpenExistingHeapFromAddress): {}", hr(&whole))); + p.lines.push(format!( + "private memory, the whole allocation (OpenExistingHeapFromAddress): {}", + hr(&whole) + )); drop(whole); let opened = open(&rig.device, From::Part(at as usize, bytes)); - p.lines.push(format!("private memory, a part of it (OpenExistingHeapFromAddress1): {}", hr(&opened))); + p.lines.push(format!( + "private memory, a part of it (OpenExistingHeapFromAddress1): {}", + hr(&opened) + )); if let Ok(heap) = &opened { p.lines.push(format!(" {}", describe(heap))); let placed = place(&rig.device, heap, K64 as u64, 4 * K64 as u64); - p.lines.push(format!(" a buffer placed in it (cross-adapter, unordered access): {}", hr(&placed))); + p.lines.push(format!( + " a buffer placed in it (cross-adapter, unordered access): {}", + hr(&placed) + )); if let Ok(buffer) = &placed { let memory = at.add(K64); fill(memory, 4 * K64, 1); - let first = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + let first = rig + .fetch(buffer, 0, 4 * K64) + .is_ok_and(|got| same(memory, &got)); fill(memory, 4 * K64, 77); - let second = rig.fetch(buffer, 0, 4 * K64).is_ok_and(|got| same(memory, &got)); + let second = rig + .fetch(buffer, 0, 4 * K64) + .is_ok_and(|got| same(memory, &got)); p.part_reads = first && second; p.lines.push(format!(" the GPU reads the memory's bytes: {first}; and those the CPU wrote afterwards, with no call in between: {second}")); mem::ResetWriteWatch(base.cast(), SIZE); let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x5a).collect(); let copied = rig.store(buffer, 4096, &new).is_ok() && same(memory.add(4096), &new); let (mut found, mut count, mut granularity) = ([0usize; 64], 64usize, 0u32); - let watched = mem::GetWriteWatch(0, base.cast(), SIZE, found.as_mut_ptr().cast(), &mut count, &mut granularity) == 0; + let watched = mem::GetWriteWatch( + 0, + base.cast(), + SIZE, + found.as_mut_ptr().cast(), + &mut count, + &mut granularity, + ) == 0; memory.cast::<[u32; 3]>().write([40, 2, 0]); let shaded = rig.shade(buffer.GetGPUVirtualAddress()); let shader = shaded.is_ok() && memory.cast::<[u32; 3]>().read()[2] == 42; @@ -867,12 +1142,14 @@ unsafe fn private(p: &mut Probe, rig: &mut Rig) { } // What the title can still do with the pages while the heap stands. let mut old = 0; - let protect_in = mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let protect_in = + mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READONLY, &mut old) != 0; if protect_in { mem::VirtualProtect(at.add(8 * K64).cast(), K64, mem::PAGE_READWRITE, &mut old); } let decommit_in = mem::VirtualFree(at.add(9 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; - let decommit_out = mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; + let decommit_out = + mem::VirtualFree(base.add(40 * K64).cast(), K64, mem::MEM_DECOMMIT) != 0; p.lines.push(format!( " with the heap standing, the title's own calls: read-only inside the part {protect_in}, decommit inside {decommit_in}, decommit outside {decommit_out} \ (false inside means the heap must go before the title frees or guards those pages)" @@ -881,7 +1158,8 @@ unsafe fn private(p: &mut Probe, rig: &mut Rig) { } drop(opened); let freed = mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE) != 0; - p.lines.push(format!(" released after the heap went: {freed}")); + p.lines + .push(format!(" released after the heap went: {freed}")); } } @@ -894,7 +1172,14 @@ unsafe fn section(p: &mut Probe, rig: &mut Rig) { unsafe { let process = windows_sys::Win32::System::Threading::GetCurrentProcess(); let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; - let reserved = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_RESERVE, 0, SIZE as u32, std::ptr::null()); + let reserved = mem::CreateFileMappingW( + invalid, + std::ptr::null(), + mem::PAGE_READWRITE | mem::SEC_RESERVE, + 0, + SIZE as u32, + std::ptr::null(), + ); if !reserved.is_null() { let opened = open(&rig.device, From::Section(reserved as usize)); p.reserved_section_refused = opened.is_err(); @@ -902,40 +1187,82 @@ unsafe fn section(p: &mut Probe, rig: &mut Rig) { drop(opened); windows_sys::Win32::Foundation::CloseHandle(reserved); } - let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, 0, SIZE as u32, std::ptr::null()); - let hole = mem::VirtualAlloc2(process, std::ptr::null(), SIZE, mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, mem::PAGE_NOACCESS, std::ptr::null_mut(), 0).cast::(); + let handle = mem::CreateFileMappingW( + invalid, + std::ptr::null(), + mem::PAGE_READWRITE | mem::SEC_COMMIT, + 0, + SIZE as u32, + std::ptr::null(), + ); + let hole = mem::VirtualAlloc2( + process, + std::ptr::null(), + SIZE, + mem::MEM_RESERVE | mem::MEM_RESERVE_PLACEHOLDER, + mem::PAGE_NOACCESS, + std::ptr::null_mut(), + 0, + ) + .cast::(); if handle.is_null() || hole.is_null() { - p.lines.push("a committed section: none to try with".to_owned()); + p.lines + .push("a committed section: none to try with".to_owned()); return; } // Pages 4..12 of the section at the placeholder's start. - mem::VirtualFree(hole.cast(), 8 * K64, mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER); - let view = mem::MapViewOfFile3(handle, process, hole.cast(), (4 * K64) as u64, 8 * K64, mem::MEM_REPLACE_PLACEHOLDER, mem::PAGE_READWRITE, std::ptr::null_mut(), 0); + mem::VirtualFree( + hole.cast(), + 8 * K64, + mem::MEM_RELEASE | mem::MEM_PRESERVE_PLACEHOLDER, + ); + let view = mem::MapViewOfFile3( + handle, + process, + hole.cast(), + (4 * K64) as u64, + 8 * K64, + mem::MEM_REPLACE_PLACEHOLDER, + mem::PAGE_READWRITE, + std::ptr::null_mut(), + 0, + ); let opened = open(&rig.device, From::Section(handle as usize)); - p.lines.push(format!("a section made committed (OpenExistingHeapFromFileMapping): {}", hr(&opened))); + p.lines.push(format!( + "a section made committed (OpenExistingHeapFromFileMapping): {}", + hr(&opened) + )); let mut unmapped = false; if let (Ok(heap), false) = (&opened, view.Value.is_null()) { p.lines.push(format!(" {}", describe(heap))); // The section's page 5 is the view's second page. let placed = place(&rig.device, heap, 5 * K64 as u64, 2 * K64 as u64); - p.lines.push(format!(" a buffer placed at the section's offset of a view's pages: {}", hr(&placed))); + p.lines.push(format!( + " a buffer placed at the section's offset of a view's pages: {}", + hr(&placed) + )); if let Ok(buffer) = &placed { let memory = hole.add(K64); fill(memory, 2 * K64, 3); - p.section_reads = rig.fetch(buffer, 0, 2 * K64).is_ok_and(|got| same(memory, &got)); + p.section_reads = rig + .fetch(buffer, 0, 2 * K64) + .is_ok_and(|got| same(memory, &got)); let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x33).collect(); p.section_writes = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); // The guard of `watch.rs`: the view read-only. let mut old = 0; - let guarded = mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; + let guarded = + mem::VirtualProtect(memory.cast(), K64, mem::PAGE_READONLY, &mut old) != 0; let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x44).collect(); let through = rig.store(buffer, 0, &new).is_ok() && same(memory, &new); // The view goes; the GPU writes; another view shows it. unmapped = mem::UnmapViewOfFile2(process, view, mem::MEM_PRESERVE_PLACEHOLDER) != 0; let new: Vec = (0..K64).map(|i| (i as u8) ^ 0x55).collect(); let stored = rig.store(buffer, 0, &new).is_ok(); - let other = mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); - p.section_outlives_views = unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); + let other = + mem::MapViewOfFile(handle, mem::FILE_MAP_WRITE, 0, (5 * K64) as u32, K64); + p.section_outlives_views = + unmapped && stored && !other.Value.is_null() && same(other.Value.cast(), &new); p.lines.push(format!( " the GPU reads the view's bytes {}; the CPU reads through the view what the GPU wrote {}; the view made read-only under the heap {guarded}, \ and the GPU writes it all the same {through}; the view unmapped under the heap {unmapped}, the GPU's write then shows in a view mapped afterwards {}", @@ -967,13 +1294,24 @@ unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4 let ms = |speed: Option| speed.map_or("?".to_owned(), |ms| format!("{ms:.1}")); // SAFETY (the whole function): the allocation and the section below. unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), bytes, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + let base = mem::VirtualAlloc( + std::ptr::null(), + bytes, + mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, + mem::PAGE_READWRITE, + ) + .cast::(); if !base.is_null() { let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); let opened = open(&rig.device, From::Part(base as usize, bytes)); let took = started.elapsed().as_secs_f64() * 1000.0; - let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); - let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + let placed = opened + .as_ref() + .ok() + .and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed + .as_ref() + .and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); p.lines.push(format!( "cost, {mb} MB of private memory never touched: {}; opened in {took:.1} ms; working set {set} -> {} MB; shared with the card {account} -> {} MB; \ the card copies it out in {} ms", @@ -986,14 +1324,26 @@ unsafe fn cost(p: &mut Probe, rig: &mut Rig, memory: &dyn Fn() -> Option<[u64; 4 mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } let invalid = windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; - let handle = mem::CreateFileMappingW(invalid, std::ptr::null(), mem::PAGE_READWRITE | mem::SEC_COMMIT, (bytes as u64 >> 32) as u32, bytes as u32, std::ptr::null()); + let handle = mem::CreateFileMappingW( + invalid, + std::ptr::null(), + mem::PAGE_READWRITE | mem::SEC_COMMIT, + (bytes as u64 >> 32) as u32, + bytes as u32, + std::ptr::null(), + ); if !handle.is_null() { let (set, account, started) = (working_set_mb(), shared(), std::time::Instant::now()); let opened = open(&rig.device, From::Section(handle as usize)); let took = started.elapsed().as_secs_f64() * 1000.0; let (set_opened, account_opened) = (working_set_mb(), shared()); - let placed = opened.as_ref().ok().and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); - let speed = placed.as_ref().and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); + let placed = opened + .as_ref() + .ok() + .and_then(|heap| place(&rig.device, heap, 0, bytes as u64).ok()); + let speed = placed + .as_ref() + .and_then(|buffer| rig.copy_ms(buffer, bytes as u64).ok()); p.lines.push(format!( "cost, {mb} MB of a committed section never touched: {}; opened in {took:.1} ms; working set {set} -> {set_opened} -> after the card read all of it {} MB; \ shared with the card {account} -> {account_opened} -> {} MB; the card copies it out in {} ms", @@ -1063,7 +1413,10 @@ fn kind_of(at: usize, len: usize, known: &mut Vec<(usize, usize)>) -> usize { return 5; } let reach = (info.BaseAddress as usize).saturating_add(info.RegionSize); - if info.Type == mem::MEM_PRIVATE && info.State == mem::MEM_COMMIT && info.Protect == mem::PAGE_READWRITE { + if info.Type == mem::MEM_PRIVATE + && info.State == mem::MEM_COMMIT + && info.Protect == mem::PAGE_READWRITE + { known.push((info.BaseAddress as usize, reach)); return if reach >= end { 0 } else { 4 }; } @@ -1086,7 +1439,10 @@ fn census_of(spans: &[(u64, u64, bool)]) -> Vec { tally.0[kind].1 += len; } let mut lines = Vec::new(); - for (name, tally) in [("title buffers", buffers), ("windows outside buffers", windows)] { + for (name, tally) in [ + ("title buffers", buffers), + ("windows outside buffers", windows), + ] { let all = tally.0.iter().fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1)); lines.push(format!("census, {name}: {} of {} MB", all.0, all.1 >> 20)); for (kind, &(n, bytes)) in KINDS.iter().zip(&tally.0) { @@ -1096,7 +1452,10 @@ fn census_of(spans: &[(u64, u64, bool)]) -> Vec { } } let v = views(); - let (count, bytes) = (v.views.len(), v.views.values().map(|view| view.0 as u64).sum::()); + let (count, bytes) = ( + v.views.len(), + v.views.values().map(|view| view.0 as u64).sum::(), + ); let pages = v.views.values().filter(|view| view.0 == K64).count(); let big = v.views.values().map(|view| view.0).max().unwrap_or(0); lines.push(format!( @@ -1108,7 +1467,11 @@ fn census_of(spans: &[(u64, u64, bool)]) -> Vec { lines.push(format!( "census, a section of {} MB, {}", bytes >> 20, - if committed { "committed: it can be opened as one heap" } else { "reserved: refused as a heap until it is made with SEC_COMMIT" } + if committed { + "committed: it can be opened as one heap" + } else { + "reserved: refused as a heap until it is made with SEC_COMMIT" + } )); } lines @@ -1132,7 +1495,9 @@ fn real_part(spans: &[(u64, u64, bool)]) -> Vec { .filter(|s| kind_of(s.0 as usize, s.1 as usize, &mut known) == 0) .max_by_key(|s| s.1); let Some(&(start, len, _)) = found else { - return vec!["the title's memory: no title buffer in private, committed memory to try".to_owned()]; + return vec![ + "the title's memory: no title buffer in private, committed memory to try".to_owned(), + ]; }; let at = (start as usize).next_multiple_of(K64); let bytes = ((start + len) as usize).saturating_sub(at).min(4 << 20) & !(K64 - 1); @@ -1160,7 +1525,9 @@ fn real_part(spans: &[(u64, u64, bool)]) -> Vec { crate::host::copy_mapped(after.as_mut_ptr(), at as *const u8, K64, false); match got { Ok(got) => { - let equal = (0..K64).filter(|&i| got[i] == before[i] || got[i] == after[i]).count(); + let equal = (0..K64) + .filter(|&i| got[i] == before[i] || got[i] == after[i]) + .count(); let zeros = got.iter().filter(|&&b| b == 0).count(); lines.push(format!( " the GPU read 64 KiB of the title's own bytes: {equal} of {K64} equal to what the CPU read just before or just after ({zeros} of them zero)" @@ -1192,13 +1559,19 @@ pub(crate) fn tick() { let Some(host) = crate::host::host() else { return; }; - let mb = std::env::var("VICTORY_INPLACE_PROBE_MB").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(64usize); + let mb = std::env::var("VICTORY_INPLACE_PROBE_MB") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(64usize); let took = std::time::Instant::now(); let probe = probe(&host.device, &|| host.video_memory(), mb.min(1024)); for line in &probe.lines { tracing::info!("in place probe: {line}"); } - tracing::info!("in place probe: took {:.0} ms", took.elapsed().as_secs_f64() * 1000.0); + tracing::info!( + "in place probe: took {:.0} ms", + took.elapsed().as_secs_f64() * 1000.0 + ); now } Err(started) => started, @@ -1242,8 +1615,14 @@ mod tests { views.insert(at + 6 * K64, (K64, 9, 3 * K64 as u64)); // After a gap of one page. views.insert(at + 8 * K64, (K64, 9, 4 * K64 as u64)); - assert_eq!(cover_in(&views, at + K64, 2 * K64), Cover::Run(9, 17 * K64 as u64)); - assert_eq!(cover_in(&views, at + K64, 5 * K64), Cover::Run(9, 17 * K64 as u64)); + assert_eq!( + cover_in(&views, at + K64, 2 * K64), + Cover::Run(9, 17 * K64 as u64) + ); + assert_eq!( + cover_in(&views, at + K64, 5 * K64), + Cover::Run(9, 17 * K64 as u64) + ); assert_eq!(cover_in(&views, at, 7 * K64), Cover::Scattered); assert_eq!(cover_in(&views, at + 6 * K64, 3 * K64), Cover::Holes); assert_eq!(cover_in(&views, at + 7 * K64, K64), Cover::None); @@ -1271,13 +1650,22 @@ mod tests { fn only_private_memory_committed_whole_is_a_part() { // SAFETY: an allocation of the test's own. unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE, mem::PAGE_NOACCESS).cast::(); + let base = mem::VirtualAlloc( + std::ptr::null(), + 8 * K64, + mem::MEM_RESERVE, + mem::PAGE_NOACCESS, + ) + .cast::(); assert!(!base.is_null()); assert!(!private_whole(base as usize, K64), "reserved only"); mem::VirtualAlloc(base.cast(), 4 * K64, mem::MEM_COMMIT, mem::PAGE_READWRITE); assert!(private_whole(base as usize, 4 * K64)); assert!(private_whole(base as usize + K64, 2 * K64)); - assert!(!private_whole(base as usize, 5 * K64), "reaches into the reserved half"); + assert!( + !private_whole(base as usize, 5 * K64), + "reaches into the reserved half" + ); let mut old = 0; mem::VirtualProtect(base.cast(), K64, mem::PAGE_READONLY, &mut old); assert!(!private_whole(base as usize, 2 * K64), "a guarded page"); @@ -1319,9 +1707,18 @@ mod tests { } assert!(probe.part_reads, "the GPU reads private memory in place"); assert!(probe.part_writes, "GPU writes land in private memory"); - assert!(probe.section_reads && probe.section_writes, "a committed section in place"); - assert!(probe.section_outlives_views, "the section's heap does not depend on views"); - assert!(probe.reserved_section_refused, "a reserved section is refused"); + assert!( + probe.section_reads && probe.section_writes, + "a committed section in place" + ); + assert!( + probe.section_outlives_views, + "the section's heap does not depend on views" + ); + assert!( + probe.reserved_section_refused, + "a reserved section is refused" + ); } /// Stage 1's own call on the software adapter: a title buffer that @@ -1337,21 +1734,44 @@ mod tests { } // SAFETY: an allocation of the test's own. unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, mem::PAGE_READWRITE).cast::(); + let base = mem::VirtualAlloc( + std::ptr::null(), + 8 * K64, + mem::MEM_RESERVE | mem::MEM_COMMIT | MEM_WRITE_WATCH, + mem::PAGE_READWRITE, + ) + .cast::(); let (start, len) = (base as u64 + K64 as u64 + 0x1230, 2 * K64 as u64 + 5); - let placed = place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); + let placed = + place_part(&device, start, len).unwrap_or_else(|e| panic!("not placed: {e:?}")); assert_eq!(placed.bias, 0x1230); assert_eq!(placed.gpu, placed.buffer.GetGPUVirtualAddress() + 0x1230); - assert_eq!(placed.buffer.GetDesc().Width, 3 * K64 as u64, "the pages that hold the buffer"); + assert_eq!( + placed.buffer.GetDesc().Width, + 3 * K64 as u64, + "the pages that hold the buffer" + ); let mut rig = Rig::new(&device).unwrap(); fill(start as *mut u8, len as usize, 7); - let got = rig.fetch(&placed.buffer, placed.bias, len as usize).unwrap(); - assert!(same(start as *const u8, &got), "the GPU reads the title buffer's bytes"); - rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]).unwrap(); - assert!(same((start + 16) as *const u8, &[0xa5; 64]), "the GPU's write is at the title's address"); + let got = rig + .fetch(&placed.buffer, placed.bias, len as usize) + .unwrap(); + assert!( + same(start as *const u8, &got), + "the GPU reads the title buffer's bytes" + ); + rig.store(&placed.buffer, placed.bias + 16, &[0xa5; 64]) + .unwrap(); + assert!( + same((start + 16) as *const u8, &[0xa5; 64]), + "the GPU's write is at the title's address" + ); drop(placed); // Half of it decommitted: turned down, the host not asked. - assert_ne!(mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), 0); + assert_ne!( + mem::VirtualFree(base.add(2 * K64).cast(), K64, mem::MEM_DECOMMIT), + 0 + ); assert!(matches!(place_part(&device, start, len), Err(None))); mem::VirtualFree(base.cast(), 0, mem::MEM_RELEASE); } @@ -1362,16 +1782,37 @@ mod tests { fn census_tells_private_memory_from_views() { // SAFETY: an allocation of the test's own. unsafe { - let base = mem::VirtualAlloc(std::ptr::null(), 8 * K64, mem::MEM_RESERVE | mem::MEM_COMMIT, mem::PAGE_READWRITE) as u64; + let base = mem::VirtualAlloc( + std::ptr::null(), + 8 * K64, + mem::MEM_RESERVE | mem::MEM_COMMIT, + mem::PAGE_READWRITE, + ) as u64; let view = 0x7_8000_0000u64; title_memory_view(view as usize, 2 * K64, 5, 0); title_memory_view(view as usize + 2 * K64, K64, 5, 9 * K64 as u64); - let lines = census_of(&[(base, 2 * K64 as u64, false), (base + 4 * K64 as u64, K64 as u64, true), (view, K64 as u64, true), (view, 3 * K64 as u64, false)]); + let lines = census_of(&[ + (base, 2 * K64 as u64, false), + (base + 4 * K64 as u64, K64 as u64, true), + (view, K64 as u64, true), + (view, 3 * K64 as u64, false), + ]); let text = lines.join("\n"); assert!(text.contains("census, title buffers: 2 of"), "{text}"); - assert!(text.contains("census, private, committed whole (a part can be opened): 1 of"), "{text}"); - assert!(text.contains("census, view memory, scattered pages: 1 of"), "{text}"); - assert!(text.contains("census, view memory, one run of a section (one placed buffer): 1 of"), "{text}"); + assert!( + text.contains("census, private, committed whole (a part can be opened): 1 of"), + "{text}" + ); + assert!( + text.contains("census, view memory, scattered pages: 1 of"), + "{text}" + ); + assert!( + text.contains( + "census, view memory, one run of a section (one placed buffer): 1 of" + ), + "{text}" + ); views_gone(view as usize, 3 * K64); mem::VirtualFree(base as *mut c_void, 0, mem::MEM_RELEASE); } diff --git a/crates/victory-gpu/src/lib.rs b/crates/victory-gpu/src/lib.rs index ef5f0b1b..4ae75806 100644 --- a/crates/victory-gpu/src/lib.rs +++ b/crates/victory-gpu/src/lib.rs @@ -25,9 +25,9 @@ mod copystat; pub mod descriptor; pub mod device; #[cfg(windows)] -mod drvwatch; -#[cfg(windows)] mod draw; +#[cfg(windows)] +mod drvwatch; pub mod dxgi; pub mod fence; pub mod frame; @@ -41,6 +41,8 @@ mod indirect; mod inplace; pub mod list; #[cfg(windows)] +mod memory; +#[cfg(windows)] mod mesh_emu; pub mod object; pub mod pipeline; @@ -61,15 +63,15 @@ mod sampler; #[cfg(windows)] pub mod shader_cache; #[cfg(windows)] -mod memory; -#[cfg(windows)] mod shadow; -#[cfg(windows)] -mod tiles; pub mod signature; #[cfg(windows)] +mod spread; +#[cfg(windows)] mod texture; #[cfg(windows)] +mod tiles; +#[cfg(windows)] mod watch; #[cfg(windows)] diff --git a/crates/victory-gpu/src/list.rs b/crates/victory-gpu/src/list.rs index b0571b26..17a19e74 100644 --- a/crates/victory-gpu/src/list.rs +++ b/crates/victory-gpu/src/list.rs @@ -167,7 +167,10 @@ pub(crate) fn tables_done(lists: &[This]) { // SAFETY: the title passes our lists. let list = unsafe { &*this.cast::() }; if list.earlier.is_empty() { - list.state.lock().unwrap_or_else(|e| e.into_inner()).tables_done(); + list.state + .lock() + .unwrap_or_else(|e| e.into_inner()) + .tables_done(); } } } @@ -266,11 +269,21 @@ pub(crate) fn recycle(lists: Vec, ran: &[usize]) { if !pools() { return; } - for (i, Detached { host, _uploads, _state }) in lists.into_iter().enumerate() { + for ( + i, + Detached { + host, + _uploads, + _state, + }, + ) in lists.into_iter().enumerate() + { // The descriptor slots and the upload memory its commands named. drop(_state); drop(_uploads); - if !ran.contains(&i) || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 { + if !ran.contains(&i) + || IDLE.lock().unwrap_or_else(|e| e.into_inner()).0.len() >= IDLE_MOST.0 + { continue; } // As the title's reset does: what the list kept for its commands @@ -321,14 +334,21 @@ fn cut(this: This, wait: ValueWait) { // shortcut: without a new host list the wait stands before the part // it was recorded in. static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!("no host list for the part after a wait: the wait moves to the part's start")); + ONCE.call_once(|| { + tracing::warn!( + "no host list for the part after a wait: the wait moves to the part's start" + ) + }); list.gate.push(wait); return; }; current.close(); static CUTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); if CUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 { - tracing::info!(parts = list.earlier.len() + 2, "a list is cut at a wait for a memory value"); + tracing::info!( + parts = list.earlier.len() + 2, + "a list is cut at a wait for a memory value" + ); } if let Some(done) = list.host.replace(fresh) { let waits = std::mem::replace(&mut list.gate, vec![wait]); @@ -841,7 +861,11 @@ fn unlike(dst: This, src: This) -> bool { if unlike { static ONCE: std::sync::Once = std::sync::Once::new(); ONCE.call_once(|| { - tracing::warn!(?dst, ?src, "copy between a stand-in target and title-format texels skipped") + tracing::warn!( + ?dst, + ?src, + "copy between a stand-in target and title-format texels skipped" + ) }); } unlike @@ -876,7 +900,8 @@ extern "system" fn copy_resource(this: This, dst: This, src: This) { // Only the two state changes and the copy are left out: what // is noted of the textures stays as it was. After // triippywhale 6e502b3b. - let same = windows::core::Interface::as_raw(to) == windows::core::Interface::as_raw(from); + let same = + windows::core::Interface::as_raw(to) == windows::core::Interface::as_raw(from); // A source the title fills itself is uploaded first (upstream // PR #671): a copy read whatever the host texture held. if crate::texture::title_written(from) { @@ -1037,13 +1062,17 @@ extern "system" fn copy_texture_region( let made = read_back(list, dst, x, y, z, src, source_box); if n <= 16 || n.is_multiple_of(4096) || made.is_err() { static REFUSED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); - if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 { + if made.is_err() && REFUSED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) >= 16 + { return; } let source = crate::resource::host_resource(src.resource).map(|r| { // SAFETY: a live resource. let d = unsafe { r.GetDesc() }; - format!("{}x{} f{} mips {}", d.Width, d.Height, d.Format.0, d.MipLevels) + format!( + "{}x{} f{} mips {}", + d.Width, d.Height, d.Format.0, d.MipLevels + ) }); tracing::info!( copies = n, @@ -1209,10 +1238,12 @@ fn read_back( return Err("a destination corner other than the footprint's"); } let host = crate::host::host().ok_or("no host")?; - let (footprint, [size, row, rows, pitch]) = dst.footprint.host_rows().ok_or("an unknown format")?; + let (footprint, [size, row, rows, pitch]) = + dst.footprint.host_rows().ok_or("an unknown format")?; // The title's buffer holds every row at its own pitch. let bytes = pitch * (rows - 1) + row; - let data = buffer_range(dst.resource, dst.footprint.offset, bytes).ok_or("a destination outside its buffer")?; + let data = buffer_range(dst.resource, dst.footprint.offset, bytes) + .ok_or("a destination outside its buffer")?; let src_copy = crate::resource::host_copy(src.resource).ok_or("no host texture")?; let texture = &src_copy.texture; let console_sub = src.footprint.offset as u32; @@ -1246,8 +1277,14 @@ fn read_back( // in `copy_texture_region`), naming a live texture and our buffer, which // the list keeps until it is reset; the box is the title's. unsafe { - list.list - .CopyTextureRegion((&raw const to).cast(), 0, 0, 0, (&raw const from).cast(), host_box) + list.list.CopyTextureRegion( + (&raw const to).cast(), + 0, + 0, + 0, + (&raw const from).cast(), + host_box, + ) }; list.defer_read_back(buffer, data, [row as usize, rows as usize, pitch as usize]); Ok(()) @@ -1314,7 +1351,11 @@ extern "system" fn resolve( // SAFETY: an open list and live textures; the region is inside both. unsafe { let (a, b) = (to.GetDesc(), from.GetDesc()); - let format = if crate::resource::stands_in(dst) { a.Format } else { DXGI_FORMAT(format as i32) }; + let format = if crate::resource::stands_in(dst) { + a.Format + } else { + DXGI_FORMAT(format as i32) + }; let dst_mip = dst_sub % u32::from(a.MipLevels).max(1); let src_mip = src_sub % u32::from(b.MipLevels).max(1); let dst_w = (a.Width >> dst_mip).max(1); @@ -1437,8 +1478,13 @@ extern "system" fn clear_dsv( list.flush_barriers(); // SAFETY: an open list, a fresh view of a live texture. unsafe { - list.list - .ClearDepthStencilView(dsv, D3D12_CLEAR_FLAGS(flags as i32 & 3), depth, stencil, rects) + list.list.ClearDepthStencilView( + dsv, + D3D12_CLEAR_FLAGS(flags as i32 & 3), + depth, + stencil, + rects, + ) }; } #[cfg(not(windows))] @@ -1570,7 +1616,10 @@ extern "system" fn reset_x(this: This, allocator: This, pipeline: This, _flags: /// `E_NOTIMPL` as a pointer). extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mut u8 { let align = usize::try_from(alignment).unwrap_or(0).max(16); - let Some(len) = usize::try_from(size).ok().and_then(|s| s.checked_add(align)) else { + let Some(len) = usize::try_from(size) + .ok() + .and_then(|s| s.checked_add(align)) + else { return std::ptr::null_mut(); }; if this.is_null() || !align.is_power_of_two() { @@ -1583,7 +1632,10 @@ extern "system" fn allocate_upload(this: This, size: u64, alignment: u64) -> *mu // SAFETY: the title passes one of our lists. let uploads = unsafe { &(*this.cast::()).uploads }; // Moving the vector keeps its heap block where it is. - uploads.lock().unwrap_or_else(|e| e.into_inner()).push(block); + uploads + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(block); at } @@ -1620,7 +1672,9 @@ mod state { ) { // (Through the draw state, which keeps them for the host list // that continues this one after a cut: `State::replay`.) - with_state(this, |list, s| s.set_viewports(list, items(viewports, count))); + with_state(this, |list, s| { + s.set_viewports(list, items(viewports, count)) + }); } pub(super) extern "system" fn scissors(this: This, count: u32, rects: *const RECT) { with_state(this, |list, s| s.set_scissors(list, items(rects, count))); @@ -1854,7 +1908,11 @@ extern "system" fn execute_indirect( { const DISPATCH: u32 = 2; const DISPATCH_SINGLE: u32 = 105; - let kind = if *kind == DISPATCH_SINGLE { DISPATCH } else { *kind }; + let kind = if *kind == DISPATCH_SINGLE { + DISPATCH + } else { + *kind + }; with_state(this, |list, s| { ran = s.execute_indirect(list, (kind, stride, max), address, counter); }); @@ -2026,15 +2084,15 @@ pub(crate) fn unmet_waits(lists: &[This]) -> Vec { pub(crate) fn waits_by_list(lists: &[This]) -> Vec> { let mut waits = VALUE_WAITS.lock().unwrap_or_else(|e| e.into_inner()); let mut by = vec![Vec::new(); lists.len()]; - waits.retain(|&(list, wait)| { - match lists.iter().position(|&l| l as usize == list) { + waits.retain( + |&(list, wait)| match lists.iter().position(|&l| l as usize == list) { Some(i) => { by[i].push(wait); false } None => true, - } - }); + }, + ); by } @@ -2103,7 +2161,8 @@ extern "system" fn barrier_groups(this: This, count: u32, _groups: *const u8) { { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_BARRIER; // SAFETY: the same layout; no resource named. - let barrier = unsafe { std::mem::transmute::(UAV_BARRIER) }; + let barrier = + unsafe { std::mem::transmute::(UAV_BARRIER) }; // SAFETY: an open list. unsafe { list.list.ResourceBarrier(&[barrier]) }; } @@ -2360,10 +2419,18 @@ mod tests { assert!(!p.is_null() && (p as usize).is_multiple_of(0x100)); // SAFETY: 40 bytes were handed out. unsafe { p.write_bytes(0xab, 40) }; - assert!(allocate_upload(list, 8, 0x30).is_null(), "not a power of two"); + assert!( + allocate_upload(list, 8, 0x30).is_null(), + "not a power of two" + ); assert_eq!(reset(list, allocator, null), S_OK); // SAFETY: the list is ours. - assert!(unsafe { &(*list.cast::()).uploads }.lock().unwrap().is_empty()); + assert!( + unsafe { &(*list.cast::()).uploads } + .lock() + .unwrap() + .is_empty() + ); let release = |o: This| slot:: u32>(o, 0x10)(o); assert_eq!(release(list), 0); assert_eq!(release(allocator), 0); diff --git a/crates/victory-gpu/src/mesh_emu.rs b/crates/victory-gpu/src/mesh_emu.rs index 4f11af27..d7584993 100644 --- a/crates/victory-gpu/src/mesh_emu.rs +++ b/crates/victory-gpu/src/mesh_emu.rs @@ -220,7 +220,10 @@ fn make() -> Option { let prep = compile_prep(&host.device) .inspect_err(|e| tracing::warn!(error = %e, "mesh_indirect_prep pipeline failed")) .ok(); - let (prep_root, prep_pso) = (prep.as_ref().map(|p| p.0.clone()), prep.as_ref().map(|p| p.1.clone())); + let (prep_root, prep_pso) = ( + prep.as_ref().map(|p| p.0.clone()), + prep.as_ref().map(|p| p.1.clone()), + ); name(&output, || format!("mesh emu output {output_bytes:#x}")); name(&slot_map, || "mesh emu slot_map".into()); name(&indirect_args, || "mesh emu indirect_args".into()); diff --git a/crates/victory-gpu/src/pipeline.rs b/crates/victory-gpu/src/pipeline.rs index 5d183f2f..c80f89a9 100644 --- a/crates/victory-gpu/src/pipeline.rs +++ b/crates/victory-gpu/src/pipeline.rs @@ -80,7 +80,8 @@ static SHADERS: Mutex>>> = Mutex::new(None) /// For the memory lines: containers kept and their bytes, translations /// kept and the bytes of their host code. None of them is ever let go. -static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +static KEPT: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// What the shader table and the pipeline library keep in memory: /// containers and their bytes, translations and their bytes, the bytes of @@ -277,7 +278,8 @@ fn of_builder(shaders: &[Arc]) -> bool { #[cfg(windows)] pub(crate) fn builder_quarantined(this: This) -> bool { static ON: OnceLock = OnceLock::new(); - is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1")) + is_builder(this) + && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1")) } #[cfg(windows)] @@ -306,7 +308,10 @@ fn container_walks(container: &[u8]) -> bool { /// Whether native code has a ray-tracing node test. #[cfg(windows)] fn code_walks(code: &[u8]) -> bool { - victory_shader::gfx10::decode(code).is_ok_and(|code| code.iter().any(|i| i.name().is_some_and(|n| n.starts_with("image_bvh")))) + victory_shader::gfx10::decode(code).is_ok_and(|code| { + code.iter() + .any(|i| i.name().is_some_and(|n| n.starts_with("image_bvh"))) + }) } /// Dispatches held back by [`walk_held`] since the last frame line. @@ -338,7 +343,9 @@ pub(crate) static WALKS_HELD: std::sync::atomic::AtomicU64 = std::sync::atomic:: #[cfg(windows)] pub(crate) fn walk_held(this: This) -> bool { static ON: OnceLock = OnceLock::new(); - if this.is_null() || !*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_HOLD").is_some_and(|v| v == "1")) { + if this.is_null() + || !*ON.get_or_init(|| std::env::var_os("VICTORY_BVH_HOLD").is_some_and(|v| v == "1")) + { return false; } let p = pipeline(this); @@ -373,7 +380,10 @@ pub(crate) fn builder_off(why: &'static str) { let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner()); if !b.off { b.off = true; - tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none"); + tracing::warn!( + why, + "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none" + ); } } @@ -567,7 +577,10 @@ pub(crate) fn note_drop(this: This) { pub(crate) fn note_why(why: String) { crate::capture::op(0, || format!("DROPPED {why}")); let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()); - *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1; + *drops + .get_or_insert_with(HashMap::new) + .entry(why) + .or_default() += 1; } /// The drops counted since the last call, most first (diagnostics). diff --git a/crates/victory-gpu/src/pipeline/host.rs b/crates/victory-gpu/src/pipeline/host.rs index 927c399f..053479a8 100644 --- a/crates/victory-gpu/src/pipeline/host.rs +++ b/crates/victory-gpu/src/pipeline/host.rs @@ -185,7 +185,12 @@ impl GraphicsState { .map(|(e, name)| { format!( "{name:?} {} {} {} {} {} {}", - e.SemanticIndex, e.Format.0, e.InputSlot, e.AlignedByteOffset, e.InputSlotClass.0, e.InstanceDataStepRate + e.SemanticIndex, + e.Format.0, + e.InputSlot, + e.AlignedByteOffset, + e.InputSlotClass.0, + e.InstanceDataStepRate ) }) .collect(); @@ -750,7 +755,10 @@ impl HostPipeline { stages }; if mesh.is_some() && !(host()?.mesh_shaders() || host()?.emulate_mesh_shaders()) { - return refuse("the host GPU has no mesh shaders (or no shader model 6.6)", shaders); + return refuse( + "the host GPU has no mesh shaders (or no shader model 6.6)", + shaders, + ); } for (s, _) in &stages { s.translated()?; @@ -825,7 +833,10 @@ impl HostPipeline { slot == victory_shader::emit::SLOT_STRIDES || slot == victory_shader::emit::SLOT_MEMORY }; - if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) && !ours && bounded_root_srvs() { + if (uav || kind == D3D12_ROOT_PARAMETER_TYPE_SRV) + && !ours + && bounded_root_srvs() + { // A one-view table: the view's size bounds the // reads (and a root UAV's writes), which a root // descriptor leaves unbounded. @@ -890,13 +901,14 @@ impl HostPipeline { } bound.push(stage); } - let (root, root_blob) = match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { - Ok(root) => root, - Err(e) => { - tracing::warn!(error = %e, ?shaders, "host root signature refused"); - return None; - } - }; + let (root, root_blob) = + match root_signature(&host.device, ¶ms, &samplers, compute.is_some()) { + Ok(root) => root, + Err(e) => { + tracing::warn!(error = %e, ?shaders, "host root signature refused"); + return None; + } + }; let code = |i: usize| { stages.get(i).and_then(|(s, _)| s.translated()).map_or( D3D12_SHADER_BYTECODE::default(), @@ -1026,12 +1038,14 @@ impl HostPipeline { pRootSignature: unsafe { std::mem::transmute_copy(&root) }, VS: code(0), PS: code(1), - GS: rect_gs.as_ref().map_or(D3D12_SHADER_BYTECODE::default(), |gs| { - D3D12_SHADER_BYTECODE { - pShaderBytecode: gs.as_ptr().cast(), - BytecodeLength: gs.len(), - } - }), + GS: rect_gs + .as_ref() + .map_or(D3D12_SHADER_BYTECODE::default(), |gs| { + D3D12_SHADER_BYTECODE { + pShaderBytecode: gs.as_ptr().cast(), + BytecodeLength: gs.len(), + } + }), BlendState: g.blend, SampleMask: g.sample_mask, RasterizerState: g.rasterizer, @@ -1084,7 +1098,10 @@ impl HostPipeline { let mut made = make(&desc, &name(rect_gs.as_ref())); if made.is_err() && rect_gs.is_some() { // The host refused the geometry stage: once more without it. - tracing::warn!(?shaders, "host pipeline refused with the rectangle geometry stage"); + tracing::warn!( + ?shaders, + "host pipeline refused with the rectangle geometry stage" + ); host.log_messages(); desc.GS = D3D12_SHADER_BYTECODE::default(); rect_gs = None; @@ -1126,7 +1143,10 @@ impl HostPipeline { let face = |f: &D3D12_DEPTH_STENCILOP_DESC| { format!( "fail {} depth-fail {} pass {} func {}", - f.StencilFailOp.0, f.StencilDepthFailOp.0, f.StencilPassOp.0, f.StencilFunc.0 + f.StencilFailOp.0, + f.StencilDepthFailOp.0, + f.StencilPassOp.0, + f.StencilFunc.0 ) }; let bounds = if depth_bounds { " bounds true" } else { "" }; @@ -1384,7 +1404,8 @@ fn code_bytes(code: &D3D12_SHADER_BYTECODE) -> Vec { return Vec::new(); } // SAFETY: a translation's own bytes, alive while its shader is. - unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) }.to_vec() + unsafe { std::slice::from_raw_parts(code.pShaderBytecode.cast::(), code.BytecodeLength) } + .to_vec() } fn root_signature( @@ -1513,7 +1534,8 @@ mod tests { let name = super::super::library::name("mesh test", &root_blob, &[&ms, &ps], &g.describe()); mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made"); let loaded = super::super::library::LOADED.load(Ordering::Relaxed); - mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name).expect("made again"); + mesh_pipeline(&host.device, &root, code(&ms), code(&ps), &g, false, &name) + .expect("made again"); assert!( super::super::library::LOADED.load(Ordering::Relaxed) > loaded, "the mesh pipeline was compiled again instead of loaded from the library" @@ -1791,6 +1813,10 @@ mod tests { eprintln!("host does not enforce the depth bounds test; skipped"); return; } - assert_eq!(run_draw(0.4, 0.6), 255, "depth 0.5 inside [0.4, 0.6] must pass"); + assert_eq!( + run_draw(0.4, 0.6), + 255, + "depth 0.5 inside [0.4, 0.6] must pass" + ); } } diff --git a/crates/victory-gpu/src/pipeline/library.rs b/crates/victory-gpu/src/pipeline/library.rs index fac6f591..35443805 100644 --- a/crates/victory-gpu/src/pipeline/library.rs +++ b/crates/victory-gpu/src/pipeline/library.rs @@ -108,7 +108,8 @@ impl Mapped { use std::os::windows::io::AsRawHandle; use windows_sys::Win32::Foundation::CloseHandle; use windows_sys::Win32::System::Memory::{ - CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE, + CreateFileMappingW, FILE_MAP_READ, FILE_MAP_WRITE, MapViewOfFile, PAGE_READONLY, + PAGE_READWRITE, }; if len == 0 { return None; @@ -127,11 +128,21 @@ impl Mapped { if mapping.is_null() { return None; } - let at = MapViewOfFile(mapping, if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, 0, 0, 0); + let at = MapViewOfFile( + mapping, + if write { FILE_MAP_WRITE } else { FILE_MAP_READ }, + 0, + 0, + 0, + ); CloseHandle(mapping); at }; - (!at.Value.is_null()).then_some(Mapped { at, len, _file: None }) + (!at.Value.is_null()).then_some(Mapped { + at, + len, + _file: None, + }) } /// The file at `path`, mapped for reading; `None` if it is not there, @@ -207,7 +218,9 @@ impl Blob { let path = dir.join(LIBRARY_FILE); let next = dir.join(NEXT_FILE); if next.exists() && std::fs::rename(&next, &path).is_err() { - tracing::warn!("the host pipeline library saved last could not take the old one's place"); + tracing::warn!( + "the host pipeline library saved last could not take the old one's place" + ); } if mapped() && let Some(file) = Mapped::open(&path) @@ -232,7 +245,8 @@ impl Blob { /// The mapped library file's view (address, bytes; 0: not mapped), when a /// pipeline was last loaded from the library (`crate::host::now_ms`), and /// whether the view's pages were let go since ([`trim`]). -static VIEW: [std::sync::atomic::AtomicUsize; 2] = [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; +static VIEW: [std::sync::atomic::AtomicUsize; 2] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 2]; static LOADED_AT: AtomicU64 = AtomicU64::new(0); static TRIMMED: AtomicBool = AtomicBool::new(false); /// The bytes of the view let go so far, for the memory line. @@ -263,10 +277,12 @@ struct Call(u32, u64); fn call(what: &'static str, name: &str) -> Call { let (thread, since) = (crate::host::thread_id(), crate::host::now_us()); let label = LABEL.with(|l| l.borrow().clone()); - CALLS - .lock() - .unwrap_or_else(|e| e.into_inner()) - .push((thread, what, format!("{name} {label}"), since)); + CALLS.lock().unwrap_or_else(|e| e.into_inner()).push(( + thread, + what, + format!("{name} {label}"), + since, + )); Call(thread, since) } @@ -304,7 +320,10 @@ pub(crate) fn removal_note() -> String { ); } } - let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + let (at, len) = ( + VIEW[0].load(Ordering::Relaxed), + VIEW[1].load(Ordering::Relaxed), + ); if at == 0 { text.push_str("; its file is not mapped"); return text; @@ -313,7 +332,11 @@ pub(crate) fn removal_note() -> String { let _ = write!( text, "; its file is mapped ({len} bytes), the handle {}", - if holds() { "kept open" } else { "closed (VICTORY_LIBRARY_HANDLE=0)" } + if holds() { + "kept open" + } else { + "closed (VICTORY_LIBRARY_HANDLE=0)" + } ); match REPLACED[0].load(Ordering::Relaxed) { 0 => text.push_str("; this run has not replaced the file"), @@ -326,7 +349,11 @@ pub(crate) fn removal_note() -> String { } } if TRIMMED_BYTES.load(Ordering::Relaxed) > 0 { - let _ = write!(text, "; its pages were last let go {:.1} s ago", ago(TRIMMED_AT.load(Ordering::Relaxed))); + let _ = write!( + text, + "; its pages were last let go {:.1} s ago", + ago(TRIMMED_AT.load(Ordering::Relaxed)) + ); } // Within two seconds: pages not in memory come from the disk. let started = std::time::Instant::now(); @@ -345,9 +372,15 @@ pub(crate) fn removal_note() -> String { } } } - let _ = write!(text, "; {zero} of the {looked} pages looked at read as zeros now"); + let _ = write!( + text, + "; {zero} of the {looked} pages looked at read as zeros now" + ); if let Some(first) = first { - let _ = write!(text, " (the first is page {first}): the library's contents were lost there"); + let _ = write!( + text, + " (the first is page {first}): the library's contents were lost there" + ); } text } @@ -364,7 +397,10 @@ pub(crate) fn removal_note() -> String { /// `VICTORY_LIBRARY_TRIM=0`: the pages stay until Windows takes them. pub(crate) fn trim() { static ON: OnceLock = OnceLock::new(); - let (at, len) = (VIEW[0].load(Ordering::Relaxed), VIEW[1].load(Ordering::Relaxed)); + let (at, len) = ( + VIEW[0].load(Ordering::Relaxed), + VIEW[1].load(Ordering::Relaxed), + ); if at == 0 || TRIMMED.load(Ordering::Relaxed) || !*ON.get_or_init(|| std::env::var_os("VICTORY_LIBRARY_TRIM").is_none_or(|v| v != "0")) @@ -385,9 +421,15 @@ pub(crate) fn trim() { unsafe { windows_sys::Win32::System::Memory::VirtualUnlock(at as *const _, len) }; TRIMMED_BYTES.fetch_add(len as u64, Ordering::Relaxed); TRIMMED_AT.store(crate::host::now_ms(), Ordering::Relaxed); - crate::host::trail(|| format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)")); + crate::host::trail(|| { + format!("pipeline library: the mapped file's pages let go from memory ({len} bytes)") + }); }; - if std::thread::Builder::new().name("victory-library-trim".into()).spawn(work).is_err() { + if std::thread::Builder::new() + .name("victory-library-trim".into()) + .spawn(work) + .is_err() + { TRIMMED.store(false, Ordering::Relaxed); } } @@ -416,8 +458,12 @@ unsafe impl Sync for Library {} /// locks, so two different names seldom wait. fn same_name(name: &str) -> MutexGuard<'static, ()> { static LOADING: [Mutex<()>; 64] = [const { Mutex::new(()) }; 64]; - let at = name.bytes().fold(0usize, |h, b| h.wrapping_mul(31).wrapping_add(usize::from(b))); - LOADING[at % LOADING.len()].lock().unwrap_or_else(|e| e.into_inner()) + let at = name.bytes().fold(0usize, |h, b| { + h.wrapping_mul(31).wrapping_add(usize::from(b)) + }); + LOADING[at % LOADING.len()] + .lock() + .unwrap_or_else(|e| e.into_inner()) } /// With `VICTORY_LIBRARY_LOCK=1`: held by every library call, as before. @@ -458,7 +504,9 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { let make = |bytes: &[u8]| -> windows::core::Result { // SAFETY: the bytes outlive the library (kept beside it). unsafe { - device.CreatePipelineLibrary::(bytes)?.cast() + device + .CreatePipelineLibrary::(bytes)? + .cast() } }; if !blob.bytes().is_empty() { @@ -466,7 +514,11 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { Ok(library) => { let bytes = blob.bytes().len(); BLOB.store(bytes as u64, Ordering::Relaxed); - tracing::info!(bytes, mapped = matches!(blob, Blob::Mapped(_)), "host pipeline library loaded"); + tracing::info!( + bytes, + mapped = matches!(blob, Blob::Mapped(_)), + "host pipeline library loaded" + ); if let Blob::Mapped(file) = &blob { VIEW[1].store(file.len, Ordering::Relaxed); VIEW[0].store(file.at.Value as usize, Ordering::Relaxed); @@ -479,7 +531,9 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { saving: RwLock::new(()), }); } - Err(e) => tracing::info!(error = %e, "host pipeline library rejected; starting an empty one"), + Err(e) => { + tracing::info!(error = %e, "host pipeline library rejected; starting an empty one") + } } } else { tracing::info!("no host pipeline library yet; starting an empty one"); @@ -500,7 +554,11 @@ fn open(device: &ID3D12Device1, blob: Blob) -> Option { /// description holds. pub(crate) fn name(kind: &str, root: &[u8], code: &[&[u8]], state: &str) -> String { let mut h = blake3::Hasher::new(); - for part in [kind.as_bytes(), root].into_iter().chain(code.iter().copied()).chain([state.as_bytes()]) { + for part in [kind.as_bytes(), root] + .into_iter() + .chain(code.iter().copied()) + .chain([state.as_bytes()]) + { h.update(&(part.len() as u64).to_le_bytes()); h.update(part); } @@ -534,7 +592,10 @@ pub(crate) fn pipeline( LOADED.fetch_add(1, Ordering::Relaxed); crate::host::trail(|| { let label = LABEL.with(|l| l.borrow().clone()); - format!("pipeline library: loaded {label} in {:.1} ms", began.elapsed().as_secs_f64() * 1e3) + format!( + "pipeline library: loaded {label} in {:.1} ms", + began.elapsed().as_secs_f64() * 1e3 + ) }); return Ok(pso); } @@ -569,7 +630,9 @@ pub(crate) fn pipeline( pub(crate) fn save(now: bool) { static LAST: Mutex> = Mutex::new(None); const SAVE_EVERY: std::time::Duration = std::time::Duration::from_secs(20); - let (Some(dir), Some(library)) = (DIR.get(), library()) else { return }; + let (Some(dir), Some(library)) = (DIR.get(), library()) else { + return; + }; { let mut last = LAST.lock().unwrap_or_else(|e| e.into_inner()); if !now && last.is_some_and(|t| t.elapsed() < SAVE_EVERY) { @@ -610,8 +673,18 @@ pub(crate) fn save(now: bool) { size } }; - let used: Vec = USED.lock().unwrap_or_else(|e| e.into_inner()).iter().flatten().cloned().collect(); - let library_written = if bytes > 0 { replace_library(dir, &tmp) } else { Ok(()) }; + let used: Vec = USED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .flatten() + .cloned() + .collect(); + let library_written = if bytes > 0 { + replace_library(dir, &tmp) + } else { + Ok(()) + }; if bytes > 0 && library_written.is_ok() { // In place unless the system refused and the new one waits beside it. let in_place = !dir.join(NEXT_FILE).exists(); @@ -622,7 +695,11 @@ pub(crate) fn save(now: bool) { crate::host::trail(|| { format!( "pipeline library: saved {bytes} bytes, {}", - if in_place { "renamed over the library's file" } else { "left beside the library's file for the next start" } + if in_place { + "renamed over the library's file" + } else { + "left beside the library's file for the next start" + } ) }); } @@ -646,7 +723,11 @@ pub(crate) fn save(now: bool) { /// 1.3 GB more of the process's own memory for the seconds a save takes; /// through a buffer where the file cannot be mapped (and with /// `VICTORY_LIBRARY_MAP=0`). -fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usize) -> std::io::Result<()> { +fn serialise( + library: &ID3D12PipelineLibrary1, + tmp: &std::path::Path, + size: usize, +) -> std::io::Result<()> { let failed = |e: windows::core::Error| std::io::Error::other(e.to_string()); if mapped() && let Some(mut file) = Mapped::create(tmp, size) @@ -667,7 +748,8 @@ fn serialise(library: &ID3D12PipelineLibrary1, tmp: &std::path::Path, size: usiz /// stay: the rest read as zeros). Where a system refuses, the new library /// is left beside it as [`NEXT_FILE`] for the next start. fn replace_library(dir: &std::path::Path, tmp: &std::path::Path) -> std::io::Result<()> { - std::fs::rename(tmp, dir.join(LIBRARY_FILE)).or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) + std::fs::rename(tmp, dir.join(LIBRARY_FILE)) + .or_else(|_| std::fs::rename(tmp, dir.join(NEXT_FILE))) } /// Writes `bytes` to a temporary file beside `path`, then renames it over @@ -689,7 +771,11 @@ fn used() -> std::sync::MutexGuard<'static, Option>> { .get() .and_then(|d| std::fs::read_to_string(d.join(EARLY_FILE)).ok()) .unwrap_or_default(); - let set: HashSet = listed.lines().filter(|l| !l.is_empty()).map(str::to_owned).collect(); + let set: HashSet = listed + .lines() + .filter(|l| !l.is_empty()) + .map(str::to_owned) + .collect(); tracing::info!(pipelines = set.len(), "title pipelines to start early"); *used = Some(set); } @@ -728,10 +814,12 @@ mod tests { #[test] fn a_rejected_blob_gives_an_empty_library() { - let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) else { + let Some(device) = crate::host::host().and_then(|h| h.device.cast::().ok()) + else { return; // no host GPU here }; - let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))).expect("an empty library"); + let library = open(&device, Blob::Held(b"not a pipeline library".repeat(16))) + .expect("an empty library"); // SAFETY: a plain query on a live library. assert!(unsafe { library.library.GetSerializedSize() } > 0); assert!(matches!(library._blob, Blob::None)); @@ -773,7 +861,9 @@ mod tests { /// The bytes at `at` of the pattern the test below writes. fn pattern(at: usize, out: &mut [u8]) { for (i, word) in out.chunks_exact_mut(4).enumerate() { - let v = ((at / 4 + i) as u32).wrapping_mul(2_654_435_761).wrapping_add(1); + let v = ((at / 4 + i) as u32) + .wrapping_mul(2_654_435_761) + .wrapping_add(1); word.copy_from_slice(&v.to_le_bytes()); } } @@ -835,7 +925,10 @@ mod tests { let mut expected = vec![0u8; 4096]; for (page, bytes) in mapped.bytes().chunks(4096).enumerate() { pattern(page * 4096, &mut expected); - assert!(bytes == &expected[..], "page {page} of the replaced library no longer reads as the old file"); + assert!( + bytes == &expected[..], + "page {page} of the replaced library no longer reads as the old file" + ); } } } diff --git a/crates/victory-gpu/src/pipeline/make.rs b/crates/victory-gpu/src/pipeline/make.rs index 199c4953..6b9b4eee 100644 --- a/crates/victory-gpu/src/pipeline/make.rs +++ b/crates/victory-gpu/src/pipeline/make.rs @@ -48,7 +48,13 @@ impl Pending { key.update(s.stage.as_bytes()); key.update(s.hash.as_bytes()); } - key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes()); + key.update( + graphics + .as_ref() + .map(|g| g.describe()) + .unwrap_or_default() + .as_bytes(), + ); Pending { shaders, graphics, @@ -191,7 +197,10 @@ fn wait(p: &Pending, frame: u64) { if rest.is_zero() { break; } - held = done.wait_timeout(held, rest).unwrap_or_else(|e| e.into_inner()).0; + held = done + .wait_timeout(held, rest) + .unwrap_or_else(|e| e.into_inner()) + .0; } drop(held); let waited = started.elapsed().min(left); @@ -206,7 +215,10 @@ fn wait(p: &Pending, frame: u64) { } } } - crate::framelog::add(crate::framelog::T::PipelineWaitUs, started.elapsed().as_micros() as u64); + crate::framelog::add( + crate::framelog::T::PipelineWaitUs, + started.elapsed().as_micros() as u64, + ); #[cfg(feature = "diagnostics")] crate::copystat::add( crate::copystat::C::PipelineWaitUs, @@ -277,7 +289,10 @@ fn start(p: &Arc, priority: u8) { let mut queue = QUEUE.lock().unwrap_or_else(|e| e.into_inner()); if let Some(new) = queue.push(p, priority) { if new { - PEAK.fetch_max(WAITING.fetch_add(1, Ordering::Relaxed) + 1, Ordering::Relaxed); + PEAK.fetch_max( + WAITING.fetch_add(1, Ordering::Relaxed) + 1, + Ordering::Relaxed, + ); } AVAILABLE.notify_one(); } diff --git a/crates/victory-gpu/src/plaincopy.rs b/crates/victory-gpu/src/plaincopy.rs index 4f3e9a41..c649099c 100644 --- a/crates/victory-gpu/src/plaincopy.rs +++ b/crates/victory-gpu/src/plaincopy.rs @@ -90,26 +90,37 @@ const LEAST: usize = 256; /// By the block's number, in the place its low bits name (a later block /// with the same low bits takes the place). Forgotten every two seconds: /// the title maps the memory in the end. -static RECENT: [std::sync::atomic::AtomicUsize; 1024] = [const { std::sync::atomic::AtomicUsize::new(0) }; 1024]; +static RECENT: [std::sync::atomic::AtomicUsize; 1024] = + [const { std::sync::atomic::AtomicUsize::new(0) }; 1024]; /// When [`RECENT`] was last emptied (milliseconds of [`now_ms`]). static EMPTIED: AtomicU64 = AtomicU64::new(0); fn now_ms() -> u64 { static START: std::sync::OnceLock = std::sync::OnceLock::new(); - START.get_or_init(std::time::Instant::now).elapsed().as_millis() as u64 + START + .get_or_init(std::time::Instant::now) + .elapsed() + .as_millis() as u64 } /// The numbers of the first and last 64 KiB block of `[from, from + len)`, /// never 0 (0 is an empty place). fn blocks(from: usize, len: usize) -> (usize, usize) { - ((from >> 16) | 1 << 63, ((from + len.max(1) - 1) >> 16) | 1 << 63) + ( + (from >> 16) | 1 << 63, + ((from + len.max(1) - 1) >> 16) | 1 << 63, + ) } /// Whether a copy from there faulted lately. fn faulted_lately(from: usize, len: usize) -> bool { let now = now_ms(); let emptied = EMPTIED.load(Relaxed); - if now.saturating_sub(emptied) >= 2_000 && EMPTIED.compare_exchange(emptied, now, Relaxed, Relaxed).is_ok() { + if now.saturating_sub(emptied) >= 2_000 + && EMPTIED + .compare_exchange(emptied, now, Relaxed, Relaxed) + .is_ok() + { for place in &RECENT { place.store(0, Relaxed); } @@ -134,7 +145,8 @@ fn install() { EXCEPTION_ACCESS_VIOLATION, EXCEPTION_GUARD_PAGE, EXCEPTION_IN_PAGE_ERROR, }; use windows_sys::Win32::System::Diagnostics::Debug::{ - AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, EXCEPTION_POINTERS, + AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH, + EXCEPTION_POINTERS, }; unsafe extern "system" fn on_fault(info: *mut EXCEPTION_POINTERS) -> i32 { // SAFETY: the system passes the exception being dispatched and the @@ -146,7 +158,9 @@ fn install() { } const READ: usize = 0; let read = r.NumberParameters >= 1 && r.ExceptionInformation[0] == READ; - let gone = (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION || r.ExceptionCode == EXCEPTION_IN_PAGE_ERROR) && read; + let gone = (r.ExceptionCode == EXCEPTION_ACCESS_VIOLATION + || r.ExceptionCode == EXCEPTION_IN_PAGE_ERROR) + && read; if gone || r.ExceptionCode == EXCEPTION_GUARD_PAGE { context.Rip = (&raw const victory_copy_guarded_fault) as u64; return EXCEPTION_CONTINUE_EXECUTION; @@ -212,7 +226,8 @@ pub(crate) fn line(frames: f64) { if !on() { return; } - let [copies, bytes, gone, lately, small] = [0, 1, 2, 3, 4].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); + let [copies, bytes, gone, lately, small] = + [0, 1, 2, 3, 4].map(|i| COUNT[i].swap(0, Relaxed) as f64 / frames); tracing::info!( "copies of title memory made in place per frame (VICTORY_COPY_PLAIN=1): {copies:.0}, {:.1} MB; {gone:.1} met a page \ that was not there and went through the kernel's copy; left to the kernel's copy untried: {lately:.0} whose source \ @@ -225,7 +240,8 @@ pub(crate) fn line(frames: f64) { mod tests { use super::*; use windows_sys::Win32::System::Memory::{ - MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, VirtualFree, + MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READWRITE, VirtualAlloc, + VirtualFree, }; const PAGE: usize = 4096; @@ -246,7 +262,8 @@ mod tests { #[test] fn a_page_that_is_not_there_ends_the_copy_without_a_fault() { // SAFETY: memory of the test's own. - let base = unsafe { VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as *mut u8; + let base = unsafe { VirtualAlloc(std::ptr::null(), 3 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } + as *mut u8; assert!(!base.is_null()); // SAFETY: the first page of that reservation. assert!(!unsafe { VirtualAlloc(base.cast(), PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); @@ -257,13 +274,26 @@ mod tests { assert!(to[..PAGE].iter().all(|&b| b == 0xAB)); to.fill(0); assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE / 2), PAGE)); - assert!(to[..PAGE / 2].iter().all(|&b| b == 0xAB), "the bytes before the hole"); + assert!( + to[..PAGE / 2].iter().all(|&b| b == 0xAB), + "the bytes before the hole" + ); assert!(to[PAGE / 2..].iter().all(|&b| b == 0), "nothing after it"); // A source that is not there at all. assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(PAGE), PAGE)); // Committed but closed to reads. // SAFETY: the third page of the reservation. - assert!(!unsafe { VirtualAlloc(base.wrapping_add(2 * PAGE).cast(), PAGE, MEM_COMMIT, PAGE_NOACCESS) }.is_null()); + assert!( + !unsafe { + VirtualAlloc( + base.wrapping_add(2 * PAGE).cast(), + PAGE, + MEM_COMMIT, + PAGE_NOACCESS, + ) + } + .is_null() + ); assert!(!guarded(to.as_mut_ptr(), base.wrapping_add(2 * PAGE), 16)); // And the registers the caller owns came back: this still works. assert!(guarded(to.as_mut_ptr(), base, PAGE)); @@ -294,10 +324,13 @@ mod tests { #[test] fn threads_fault_and_copy_side_by_side() { // SAFETY: memory of the test's own. - let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } as usize; + let base = unsafe { VirtualAlloc(std::ptr::null(), 2 * PAGE, MEM_RESERVE, PAGE_NOACCESS) } + as usize; assert_ne!(base, 0); // SAFETY: the first page of that reservation. - assert!(!unsafe { VirtualAlloc(base as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null()); + assert!( + !unsafe { VirtualAlloc(base as *const _, PAGE, MEM_COMMIT, PAGE_READWRITE) }.is_null() + ); let threads: Vec<_> = (0..8) .map(|t| { std::thread::spawn(move || { diff --git a/crates/victory-gpu/src/queue.rs b/crates/victory-gpu/src/queue.rs index c6a760a3..ad7abd1e 100644 --- a/crates/victory-gpu/src/queue.rs +++ b/crates/victory-gpu/src/queue.rs @@ -61,7 +61,11 @@ enum Held { /// With [`present_behind`]: the title's present of a frame, due after /// what the queue holds before it: the host texture shown, the state /// the title's lists leave it in, and the frame's number. - Present(windows::Win32::Graphics::Direct3D12::ID3D12Resource, u32, u64), + Present( + windows::Win32::Graphics::Direct3D12::ID3D12Resource, + u32, + u64, + ), } /// Presents that are in a queue's line and have not run ([`Held::Present`]). @@ -95,18 +99,47 @@ static PRESENTS_HELD: AtomicU64 = AtomicU64::new(0); /// reads stays as it was until the submission's fence is signalled, also /// across the title's present. On the console the card reads that memory /// when it runs the list, after the present call has returned. +/// +/// `VICTORY_ASYNC_PRESENT=alt`: twenty seconds with, twenty without, in +/// turn, each change said in the log, for measuring it in one scene. #[cfg(windows)] fn present_behind() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| { - let on = std::env::var_os("VICTORY_ASYNC_PRESENT").is_some_and(|v| v == "1") - && behind() - && crate::host::late_free_present(); - if on { - tracing::info!("presents go behind the queue's line and return at once (VICTORY_ASYNC_PRESENT=1)"); + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let asked = match std::env::var("VICTORY_ASYNC_PRESENT").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + let mode = if asked != 0 && behind() && crate::host::late_free_present() { asked } else { 0 }; + if mode != 0 { + tracing::info!("presents go behind the queue's line and return at once (VICTORY_ASYNC_PRESENT=1; alt: in turn)"); } - on - }) + mode + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_secs() + / 20) + % 2 + == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "presents behind the line from now (VICTORY_ASYNC_PRESENT=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } } /// With [`present_behind`]: puts the present of the next frame behind what @@ -137,7 +170,8 @@ fn send_behind(this: This, planes: u32, plane_parameters: *const Plane) -> bool // The state the lists recorded so far leave the texture in: what our // copy finds it in when it runs behind them (looked at, not changed). const COPY_SOURCE: u32 = 0x800; - let state = crate::resource::host_transition(resource, COPY_SOURCE).map_or(COPY_SOURCE, |(_, before)| before); + let state = crate::resource::host_transition(resource, COPY_SOURCE) + .map_or(COPY_SOURCE, |(_, before)| before); crate::resource::host_transition(resource, state); let texture = texture.clone(); let sent = hold(this, || { @@ -208,7 +242,9 @@ fn split() -> bool { #[cfg(windows)] pub(crate) fn cuts() -> bool { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - waits() && split() && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0")) + waits() + && split() + && *ON.get_or_init(|| std::env::var_os("VICTORY_CUT_WAITS").is_none_or(|v| v != "0")) } /// Whether a present runs what queues still hold (on by default: a wait @@ -457,7 +493,8 @@ pub(crate) fn behind() -> bool { /// Whether there is something for [`worker`] to look at. #[cfg(windows)] -static WORK: (std::sync::Mutex, std::sync::Condvar) = (std::sync::Mutex::new(false), std::sync::Condvar::new()); +static WORK: (std::sync::Mutex, std::sync::Condvar) = + (std::sync::Mutex::new(false), std::sync::Condvar::new()); #[cfg(windows)] fn wake() { @@ -488,9 +525,18 @@ fn worker() { } release_held_now(false); let (user_now, kernel_now) = crate::framelog::thread_times(); - crate::framelog::add(crate::framelog::T::WorkerUs, started.elapsed().as_micros() as u64); - crate::framelog::add(crate::framelog::T::WorkerUserUs, user_now.saturating_sub(user)); - crate::framelog::add(crate::framelog::T::WorkerKernelUs, kernel_now.saturating_sub(kernel)); + crate::framelog::add( + crate::framelog::T::WorkerUs, + started.elapsed().as_micros() as u64, + ); + crate::framelog::add( + crate::framelog::T::WorkerUserUs, + user_now.saturating_sub(user), + ); + crate::framelog::add( + crate::framelog::T::WorkerKernelUs, + kernel_now.saturating_sub(kernel), + ); } } @@ -500,6 +546,231 @@ thread_local! { static RELEASING_HERE: std::cell::Cell = const { std::cell::Cell::new(false) }; } +/// Whether parts that follow one another in the queues' lines go to the +/// host as one submission (`VICTORY_JOIN_PARTS=1`; `alt`: twenty seconds +/// with, twenty without, in turn, each change said in the log). Off by +/// default. Needs [`behind`]. +/// +/// Why: the title's lists wait for memory values (19 to 20 waits a frame +/// in the first rooms, each met by the bottom-of-pipe write of the part +/// before it), and every wait cuts a submission into parts: 29 host +/// submissions a frame from about 15 of the title's (run 238). Each part +/// is prepared on its own: 82 askings of the write watch, 666 refresh +/// steps, a heap sync, a merge under the flights in the air, and on the +/// card one list of ours that sends changed bytes and one that compares. +/// The title hands a frame over in one burst at the end of its recording, +/// then stands still until the line has finished it (its fence wait of +/// the next frame: run 238), so the parts are all in the lines when our +/// thread gets to them. +/// +/// With the switch the thread that runs the lines takes parts off them +/// in the order they would have run and gives them to the host together: +/// the same host lists in the same order, prepared once. Between two +/// parts a wait passes if memory meets it, if a write of a flight in the +/// air is known to meet it, or if a bottom-of-pipe write of a part taken +/// before it meets it (that part is ahead of it in the joined +/// submission, which is the order the wait asks for). A signal met +/// behind parts not sent yet is delivered right behind the joined +/// submission: never before the part it followed has run. Anything else +/// (a wait not known to be met, a present, the end of what is free to +/// run) sends what was taken first. At most [`join_most`] parts or +/// [`join_lists`] lists are joined, so that the card has work while the +/// next ones are prepared. Each queue with a part taken keeps the mark +/// [`Held::Running`] at the head of its line until the part is sent: +/// what the title gives the queue meanwhile, signals too, stays behind. +#[cfg(windows)] +fn join_parts() -> bool { + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + let mode = *MODE.get_or_init(|| { + let mode = match std::env::var("VICTORY_JOIN_PARTS").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }; + if mode != 0 { + tracing::info!( + "parts that follow one another in the queues' lines go to the host as one submission, at most {} parts or {} lists (VICTORY_JOIN_PARTS=1; alt: in turn)", + join_most(), + join_lists() + ); + } + mode + }); + match mode { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_secs() + / 20) + % 2 + == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "parts joined into one host submission from now (VICTORY_JOIN_PARTS=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } +} + +/// The most parts joined into one host submission (`VICTORY_JOIN_MOST`, 4). +#[cfg(windows)] +fn join_most() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_JOIN_MOST") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|&n| n >= 1) + .unwrap_or(4) + }) +} + +/// The most host lists joined into one host submission (`VICTORY_JOIN_LISTS`, 48). +#[cfg(windows)] +fn join_lists() -> usize { + static N: std::sync::OnceLock = std::sync::OnceLock::new(); + *N.get_or_init(|| { + std::env::var("VICTORY_JOIN_LISTS") + .ok() + .and_then(|v| v.parse().ok()) + .filter(|&n| n >= 1) + .unwrap_or(48) + }) +} + +/// With [`join_parts`]: parts taken off the queues' lines and not yet +/// given to the host, in the order they run. +#[cfg(windows)] +#[derive(Default)] +struct Joined { + lists: Vec, + order: Vec, + parts: usize, + /// Signals met behind those parts: delivered when the parts are sent. + signals: Vec<(usize, u64)>, + /// The queues with a part here: each has [`Held::Running`] at the + /// head of its line. + marked: Vec, +} + +#[cfg(windows)] +impl Joined { + fn is_empty(&self) -> bool { + self.parts == 0 + } + + /// One more part behind those taken: its lists keep their order. + fn add(&mut self, lists: Vec, order: Vec) { + let (lists, order) = join( + std::mem::take(&mut self.lists), + std::mem::take(&mut self.order), + lists, + order, + ); + self.lists = lists; + self.order = order; + self.parts += 1; + } + + fn full(&self) -> bool { + self.parts >= join_most() || self.order.len() >= join_lists() + } + + /// Whether a bottom-of-pipe write of a part taken meets `wait`. + fn meets(&self, wait: &crate::list::ValueWait) -> bool { + let (address, bytes) = wait.place(); + self.order.iter().any(|&i| { + self.lists[i] + .host() + .will_write(address, bytes, |v| wait.holds_for(v)) + }) + } +} + +#[cfg(windows)] +/// The things of one part behind those of another: `order` names places in +/// `lists`, so the second part's places move up by the first's count. +fn join( + mut lists: Vec, + mut order: Vec, + more: Vec, + more_order: Vec, +) -> (Vec, Vec) { + let base = lists.len(); + lists.extend(more); + order.extend(more_order.into_iter().map(|i| i + base)); + (lists, order) +} + +/// Parts joined, host submissions they went in, their lists, signals +/// delivered behind them, and waits passed for a write of a part taken. +#[cfg(windows)] +static JOINED: [AtomicU64; 5] = [const { AtomicU64::new(0) }; 5]; + +/// Gives the host what [`Joined`] holds, as one submission, delivers the +/// signals met behind it, and takes the marks off the lines. Called with +/// no line locked. +#[cfg(windows)] +fn send_joined(joined: &mut Joined) { + if joined.parts > 0 { + let (lists, order) = ( + std::mem::take(&mut joined.lists), + std::mem::take(&mut joined.order), + ); + JOINED[0].fetch_add(joined.parts as u64, Ordering::Relaxed); + let sent = JOINED[1].fetch_add(1, Ordering::Relaxed) + 1; + JOINED[2].fetch_add(order.len() as u64, Ordering::Relaxed); + JOINED[3].fetch_add(joined.signals.len() as u64, Ordering::Relaxed); + if sent.is_multiple_of(2048) { + let n: Vec = JOINED + .iter() + .map(|n| n.swap(0, Ordering::Relaxed)) + .collect(); + tracing::info!( + "parts joined (VICTORY_JOIN_PARTS=1): {} parts went to the host in {} submissions ({:.1} parts, {:.1} lists each), {} signals delivered behind them, {} waits passed for a write of a part not sent yet", + n[0], + n[1], + n[0] as f64 / n[1].max(1) as f64, + n[2] as f64 / n[1].max(1) as f64, + n[3], + n[4] + ); + } + match crate::host::host() { + Some(host) => host.execute_late(lists, order), + // (Not reached: parts are only taken with a host.) + None => crate::list::recycle(lists, &order), + } + joined.parts = 0; + } + // Behind what was just sent, in the order they were met. + for (fence, value) in joined.signals.drain(..) { + if !crate::host::late_signal(fence, value) { + crate::fence::set(fence as This, value); + } + } + for q in joined.marked.drain(..) { + // SAFETY: a live queue, as in the loop that marked it. + let line = unsafe { &(*(q as *const Queue)).held }; + let mut held = lock(line); + if matches!(held.first(), Some(Held::Running)) { + held.remove(0); + } + if held.is_empty() { + lock(&WAITING).retain(|&w| w != q); + } + } +} + /// Before a submission of ours that is waited for, with [`behind`]: what /// the queues hold and is free to run runs first, on this thread, so the /// submission keeps its place behind them. @@ -526,6 +797,11 @@ fn release_held_now(all: bool) { } } let _leave = Leave(was_here); + // Parts taken and not sent yet ([`join_parts`]): none when the lines + // are forced, and none is left when this returns. + let joining = + !all && behind() && crate::host::late() && crate::host::host().is_some() && join_parts(); + let mut joined = Joined::default(); loop { let queues = lock(&WAITING).clone(); let mut moved = false; @@ -534,17 +810,34 @@ fn release_held_now(all: bool) { let line = unsafe { &(*(q as *const Queue)).held }; let mut held = lock(line); loop { - match held.first() { + // A queue with a part in `joined` has our mark at the head + // of its line: what is looked at is behind the mark. + let base = usize::from(joined.marked.contains(&q)); + match held.get(base) { None | Some(Held::Running) => break, Some(&Held::Wait(fence, value)) if !all && crate::fence::completed(fence as This) < value => { break; } + // With parts taken and not sent: only what is known + // without a wait for the card. A wait that stays is + // looked at again when the parts have been sent. + Some(Held::Value(wait)) if !all && !joined.is_empty() => { + if !wait.met() && !crate::host::late_met_known(wait) { + if !joined.meets(wait) { + break; + } + JOINED[4].fetch_add(1, Ordering::Relaxed); + } + } Some(Held::Value(wait)) if !all && !value_met(wait) => break, + // The frame is shown behind the parts taken: they are + // sent first. + Some(Held::Present(..)) if !joined.is_empty() => break, Some(_) => {} } - match held.remove(0) { + match held.remove(base) { Held::Wait(..) | Held::Running => {} Held::Value(wait) => { // Passed at a present without being met: what the @@ -574,14 +867,35 @@ fn release_held_now(all: bool) { // each range shaders write compared once). #[cfg(feature = "diagnostics")] { - let waits = held.iter().take_while(|h| matches!(h, Held::Value(_))).count(); + let waits = held + .iter() + .take_while(|h| matches!(h, Held::Value(_))) + .count(); if waits > 0 && matches!(held.get(waits), Some(Held::Run(..))) - && held[..waits].iter().all(|h| matches!(h, Held::Value(w) if w.met())) + && held[..waits] + .iter() + .all(|h| matches!(h, Held::Value(w) if w.met())) { crate::copystat::add(crate::copystat::C::PartsTogether, 1); } } + if joining { + // Taken, to go with the parts that follow it. + // The line stays open behind our mark. + if !joined.marked.contains(&q) { + held.insert(0, Held::Running); + joined.marked.push(q); + } + joined.add(lists, order); + if joined.full() { + drop(held); + send_joined(&mut joined); + held = lock(line); + } + moved = true; + continue; + } if crate::host::late() && let Some(host) = crate::host::host() { @@ -653,7 +967,10 @@ fn release_held_now(all: bool) { // Behind what was sent to the card and not waited // for, if anything was. Held::Signal(fence, value) => { - if !crate::host::late_signal(fence, value) { + if !joined.is_empty() { + // Behind parts not sent yet: with them. + joined.signals.push((fence, value)); + } else if !crate::host::late_signal(fence, value) { crate::fence::set(fence as This, value); } } @@ -665,7 +982,12 @@ fn release_held_now(all: bool) { } } if !moved { - break; + if joined.is_empty() { + break; + } + // Nothing more is free to run behind the parts taken: they go + // to the host, and what stood at a wait is looked at again. + send_joined(&mut joined); } } } @@ -795,7 +1117,11 @@ fn execute_now(this: This, count: u32, lists: *const This) { if !unmet.is_empty() { static SEEN: AtomicU64 = AtomicU64::new(0); if SEEN.fetch_add(1, Ordering::Relaxed) < 8 { - tracing::info!(kind = queue(this).kind, ?unmet, "a submission is held for a memory value"); + tracing::info!( + kind = queue(this).kind, + ?unmet, + "a submission is held for a memory value" + ); } lock(&queue(this).held).extend(unmet.into_iter().map(Held::Value)); let mut waiting = lock(&WAITING); @@ -873,6 +1199,8 @@ extern "system" fn signal(this: This, fence: This, value: u64) -> HRESULT { if fence.is_null() { return E_INVALIDARG; } + #[cfg(all(windows, feature = "diagnostics"))] + crate::fence::pace::signal_called(fence as usize, value); // A queue that waits signals after what it holds. #[cfg(windows)] if hold(this, || Held::Signal(fence as usize, value)) { @@ -905,11 +1233,21 @@ extern "system" fn wait(this: This, fence: This, value: u64) -> HRESULT { { static CALLS: AtomicU64 = AtomicU64::new(0); if CALLS.fetch_add(1, Ordering::Relaxed) < 8 { - tracing::info!(kind = queue(this).kind, now, value, "a queue is told to wait for a fence"); + tracing::info!( + kind = queue(this).kind, + now, + value, + "a queue is told to wait for a fence" + ); } } #[cfg(feature = "diagnostics")] - crate::capture::op(this as usize, || format!("WAIT queue kind {} for fence {fence:?} value {value} (now {now})", queue(this).kind)); + crate::capture::op(this as usize, || { + format!( + "WAIT queue kind {} for fence {fence:?} value {value} (now {now})", + queue(this).kind + ) + }); let behind = { let mut held = lock(&queue(this).held); let behind = !held.is_empty() || now < value; @@ -1024,8 +1362,13 @@ extern "system" fn present( let hr = present_now(this, planes, plane_parameters); #[cfg(windows)] { - crate::framelog::add(crate::framelog::T::PresentUs, presenting.elapsed().as_micros() as u64); + crate::framelog::add( + crate::framelog::T::PresentUs, + presenting.elapsed().as_micros() as u64, + ); crate::framelog::frame(); + #[cfg(feature = "diagnostics")] + crate::fence::pace::frame(); } hr } @@ -1068,7 +1411,10 @@ fn present_now(this: This, planes: u32, plane_parameters: *const Plane) -> HRESU release_held(forces()); } #[cfg(windows)] - crate::framelog::add(crate::framelog::T::PresentLineUs, presenting.elapsed().as_micros() as u64); + crate::framelog::add( + crate::framelog::T::PresentLineUs, + presenting.elapsed().as_micros() as u64, + ); let frame = FRAMES.fetch_add(1, Ordering::Relaxed) + 1; #[cfg(windows)] if sent_behind && PRESENTS_BEHIND.load(Ordering::Relaxed).is_multiple_of(512) { @@ -1242,7 +1588,9 @@ extern "system" fn copy_page_mappings( } if !ok { static ONCE: std::sync::Once = std::sync::Once::new(); - ONCE.call_once(|| tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed")); + ONCE.call_once(|| { + tracing::warn!(pool = format_args!("{pool:#x}"), "a page mapping failed") + }); } S_OK } @@ -1303,6 +1651,33 @@ static NEWER_FUNCTIONS: Table<36> = Table(queue_table(true)); #[cfg(test)] mod tests { use super::*; + + #[cfg(windows)] + #[test] + fn joined_parts_keep_their_lists_and_their_order() { + // a part of three lists run as 2, 0, 1; then one of two run as 1, 0; then one of one + let (lists, order) = join( + vec!["a0", "a1", "a2"], + vec![2, 0, 1], + vec!["b0", "b1"], + vec![1, 0], + ); + let (lists, order) = join(lists, order, vec!["c0"], vec![0]); + assert_eq!(lists, ["a0", "a1", "a2", "b0", "b1", "c0"]); + let run: Vec<&str> = order.iter().map(|&i| lists[i]).collect(); + assert_eq!( + run, + ["a2", "a0", "a1", "b1", "b0", "c0"], + "each part's lists in its own order, the parts one after the other" + ); + // a part with a list named twice, and an empty one + let (lists, order) = join(vec!["a0"], vec![0, 0], Vec::new(), Vec::new()); + let (lists, order) = join(lists, order, vec!["b0"], vec![0, 0]); + assert_eq!( + order.iter().map(|&i| lists[i]).collect::>(), + ["a0", "a0", "b0", "b0"] + ); + } use crate::object::slot; /// Where a queue's signal is: newer layouts have it two slots later. diff --git a/crates/victory-gpu/src/queue2.rs b/crates/victory-gpu/src/queue2.rs index 6d016d27..edc43a8c 100644 --- a/crates/victory-gpu/src/queue2.rs +++ b/crates/victory-gpu/src/queue2.rs @@ -75,7 +75,13 @@ use windows::core::Interface; /// Read once, when the first submission asks. pub(crate) fn bits() -> u32 { static BITS: OnceLock = OnceLock::new(); - *BITS.get_or_init(|| std::env::var("VICTORY_QUEUE2").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) & 3) + *BITS.get_or_init(|| { + std::env::var("VICTORY_QUEUE2") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + & 3 + }) } /// The most bytes of landing buffers in the card's memory, for title @@ -87,7 +93,11 @@ pub(crate) fn bits() -> u32 { fn landing_most() -> u64 { static MOST: OnceLock = OnceLock::new(); *MOST.get_or_init(|| { - std::env::var("VICTORY_QUEUE2_LANDING_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(96) << 20 + std::env::var("VICTORY_QUEUE2_LANDING_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(96) + << 20 }) } @@ -170,12 +180,16 @@ impl Lane { fn new(device: &ID3D12Device, name: &str) -> windows::core::Result { // SAFETY: plain object creation with valid descriptions. unsafe { - let queue: ID3D12CommandQueue = device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { - Type: D3D12_COMMAND_LIST_TYPE_COPY, - ..Default::default() - })?; + let queue: ID3D12CommandQueue = + device.CreateCommandQueue(&D3D12_COMMAND_QUEUE_DESC { + Type: D3D12_COMMAND_LIST_TYPE_COPY, + ..Default::default() + })?; let fence: ID3D12Fence = device.CreateFence(0, D3D12_FENCE_FLAG_NONE)?; - let wide: Vec = format!("victory copy queue ({name})").encode_utf16().chain([0]).collect(); + let wide: Vec = format!("victory copy queue ({name})") + .encode_utf16() + .chain([0]) + .collect(); let _ = queue.SetName(windows::core::PCWSTR(wide.as_ptr())); Ok(Lane { device: device.clone(), @@ -195,10 +209,14 @@ impl Lane { /// and adds up how long the lane had one ([`LaneStats::busy_us`]). fn clocked(&'static self, name: &str) { let (tx, rx) = channel(); - let started = std::thread::Builder::new().name(format!("victory-queue2-{name}")).spawn(move || self.watch(&rx)); + let started = std::thread::Builder::new() + .name(format!("victory-queue2-{name}")) + .spawn(move || self.watch(&rx)); match started { Ok(_) => lock(&self.state).clock = Some(tx), - Err(e) => tracing::warn!(error = %e, "no thread for a copy queue's clock: its milliseconds stay 0"), + Err(e) => { + tracing::warn!(error = %e, "no thread for a copy queue's clock: its milliseconds stay 0") + } } } @@ -213,7 +231,9 @@ impl Lane { return; } let done = Instant::now(); - self.stats.busy_us.fetch_add(busy_stretch(before, sent, done), Ordering::Relaxed); + self.stats + .busy_us + .fetch_add(busy_stretch(before, sent, done), Ordering::Relaxed); before = Some(done); } } @@ -227,16 +247,23 @@ impl Lane { let done = self.fence.GetCompletedValue(); let free = { let mut state = lock(&self.state); - state.spare.iter().position(|(job, _)| *job <= done).map(|at| state.spare.swap_remove(at).1) + state + .spare + .iter() + .position(|(job, _)| *job <= done) + .map(|at| state.spare.swap_remove(at).1) }; if let Some((allocator, list)) = free { allocator.Reset()?; list.Reset(&allocator, None)?; return Ok((allocator, list)); } - let allocator: ID3D12CommandAllocator = self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COPY)?; let list: ID3D12GraphicsCommandList = - self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; + self.device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COPY, &allocator, None)?; Ok((allocator, list)) } } @@ -247,7 +274,12 @@ impl Lane { /// of other queues) has reached its value: every value must have been /// signalled on its queue already. Returns the job's number, for /// [`Lane::wait`], [`Lane::done`] and [`Second::hold`]. - pub(crate) fn send(&self, list: CopyList, after: &[(&ID3D12Fence, u64)], bytes: u64) -> windows::core::Result { + pub(crate) fn send( + &self, + list: CopyList, + after: &[(&ID3D12Fence, u64)], + bytes: u64, + ) -> windows::core::Result { // SAFETY: an open list of ours; the lane's queue and fence; live // fences of the same device. unsafe { @@ -356,9 +388,14 @@ impl Second { self.down.clocked("down"); self.up.clocked("up"); let (tx, rx) = channel(); - match std::thread::Builder::new().name("victory-queue2-holds".into()).spawn(move || self.watch_holds(&rx)) { + match std::thread::Builder::new() + .name("victory-queue2-holds".into()) + .spawn(move || self.watch_holds(&rx)) + { Ok(_) => lock(&self.holds).1 = Some(tx), - Err(e) => tracing::warn!(error = %e, "no thread to time the direct queue's waits for the copy queue: they stay 0"), + Err(e) => { + tracing::warn!(error = %e, "no thread to time the direct queue's waits for the copy queue: they stay 0") + } } } @@ -408,18 +445,31 @@ impl Second { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; let mut buffer: Option = None; // SAFETY: plain creation of a buffer in the card's memory. let made = unsafe { - self.device.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + self.device.CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) }; match (made, buffer) { (Ok(()), Some(buffer)) => { - let wide: Vec = "victory landing buffer (title bytes on their way up)".encode_utf16().chain([0]).collect(); + let wide: Vec = "victory landing buffer (title bytes on their way up)" + .encode_utf16() + .chain([0]) + .collect(); // SAFETY: a live buffer and a terminated string. let _ = unsafe { buffer.SetName(windows::core::PCWSTR(wide.as_ptr())) }; landings.push(Landing { @@ -552,10 +602,18 @@ pub(crate) fn line(frames: f64) { let ms = |a: &AtomicU64| take(a) / 1000.0; let mb = |a: &AtomicU64| take(a) / (1 << 20) as f64; let (down, up) = (&second.down.stats, &second.up.stats); - let (down_jobs, down_mb, down_busy, down_waited) = (take(&down.jobs), mb(&down.bytes), ms(&down.busy_us), ms(&down.waited_us)); + let (down_jobs, down_mb, down_busy, down_waited) = ( + take(&down.jobs), + mb(&down.bytes), + ms(&down.busy_us), + ms(&down.waited_us), + ); let (up_jobs, up_mb, up_busy) = (take(&up.jobs), mb(&up.bytes), ms(&up.busy_us)); let [holds, stood, stood_us] = [0, 1, 2].map(|i| take(&second.held[i])); - let (landing_mb, no_room) = (second.landing[0].load(Ordering::Relaxed) >> 20, take(&second.landing[1])); + let (landing_mb, no_room) = ( + second.landing[0].load(Ordering::Relaxed) >> 20, + take(&second.landing[1]), + ); tracing::info!( "the copy queues per frame (VICTORY_QUEUE2={}): fetches of what shaders wrote: {down_jobs:.1} jobs, {down_mb:.1} MB, \ {down_busy:.1} ms on their queue, our threads stood {down_waited:.1} ms waiting for them; title bytes sent up: \ @@ -649,7 +707,8 @@ void main() { fn new(bits: u32) -> Option { // SAFETY: plain DXGI and D3D12 set-up on the software adapter. unsafe { - let factory: IDXGIFactory4 = CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; + let factory: IDXGIFactory4 = + CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0)).ok()?; let adapter: IDXGIAdapter = factory.EnumWarpAdapter().ok()?; let desc = adapter.cast::().ok()?.GetDesc1().ok()?; if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 == 0 { @@ -668,7 +727,9 @@ void main() { let event = CreateEventW(None, false, false, None).ok()?; // The clocks' threads live as long as the process: the // queues of a test are kept for them. - let second: &'static Second = Box::leak(Box::new(Second::new(&device, bits).expect("copy queues on WARP"))); + let second: &'static Second = Box::leak(Box::new( + Second::new(&device, bits).expect("copy queues on WARP"), + )); second.clocked(); let mut code: Option = None; D3DCompile( @@ -686,7 +747,10 @@ void main() { ) .expect("the test's shader compiles"); let code = code?; - let bytes = std::slice::from_raw_parts(code.GetBufferPointer().cast::(), code.GetBufferSize()); + let bytes = std::slice::from_raw_parts( + code.GetBufferPointer().cast::(), + code.GetBufferSize(), + ); let root: ID3D12RootSignature = device.CreateRootSignature(0, bytes).ok()?; let pso: ID3D12PipelineState = device .CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC { @@ -735,7 +799,10 @@ void main() { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, ..Default::default() @@ -745,7 +812,14 @@ void main() { // SAFETY: plain creation, and a mapping of CPU-visible memory. unsafe { self.device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) .expect("a test buffer"); let buffer = buffer.expect("a test buffer"); if mapped { @@ -761,15 +835,22 @@ void main() { // SAFETY: plain creation; an open list of ours; our queue and // fence. unsafe { - let allocator: ID3D12CommandAllocator = - self.device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).expect("an allocator"); - let list: ID3D12GraphicsCommandList = - self.device.CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None).expect("a list"); + let allocator: ID3D12CommandAllocator = self + .device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .expect("an allocator"); + let list: ID3D12GraphicsCommandList = self + .device + .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) + .expect("a list"); record(&list); list.Close().expect("the list closes"); - self.direct.ExecuteCommandLists(&[Some(list.cast().expect("a command list"))]); + self.direct + .ExecuteCommandLists(&[Some(list.cast().expect("a command list"))]); self.submitted += 1; - self.direct.Signal(&self.fence, self.submitted).expect("a signal"); + self.direct + .Signal(&self.fence, self.submitted) + .expect("a signal"); self.flown.push((allocator, list)); } self.submitted @@ -795,7 +876,9 @@ void main() { fn land(&mut self) { // SAFETY: our fence and event. unsafe { - self.fence.SetEventOnCompletion(self.submitted, self.event).expect("a wait"); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .expect("a wait"); WaitForSingleObject(self.event, INFINITE); } for lane in [&self.second.down, &self.second.up] { @@ -814,7 +897,9 @@ void main() { /// The dwords of a mapped buffer. fn dwords(data: *mut u8, at: usize, n: usize) -> Vec { // SAFETY: the caller's mapping holds them. - (0..n).map(|i| unsafe { data.cast::().add(at + i).read_volatile() }).collect() + (0..n) + .map(|i| unsafe { data.cast::().add(at + i).read_volatile() }) + .collect() } /// What shaders wrote, read back through the down lane, is what the @@ -835,24 +920,42 @@ void main() { // "Shader writes": a few dwords, each by a dispatch. let mut behind = 0; for i in 0..24u32 { - behind = warp.store(&card, (i * 163 % DWORDS as u32) * 4, round * 1000 + i, 20_000); + behind = warp.store( + &card, + (i * 163 % DWORDS as u32) * 4, + round * 1000 + i, + 20_000, + ); } // Through the lane, behind the writes' fence; no wait of ours. let second = warp.second; let list = second.down.list().expect("a copy list"); // SAFETY: an open copy list; live buffers. unsafe { list.1.CopyBufferRegion(&down_lane, 0, &card, 0, bytes) }; - let job = second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + let job = second + .down + .send(list, &[(&warp.fence, behind)], bytes) + .expect("the fetch is sent"); // And through the direct queue, as before. // SAFETY: an open list; live buffers. warp.fly(|list| unsafe { list.CopyBufferRegion(&down_direct, 0, &card, 0, bytes) }); - second.down.wait(job, warp.event).expect("the fetch is waited for"); + second + .down + .wait(job, warp.event) + .expect("the fetch is waited for"); assert!(second.down.done(job)); warp.land(); let (direct, lane) = (dwords(direct_data, 0, DWORDS), dwords(lane_data, 0, DWORDS)); - assert_eq!(direct, lane, "round {round}: the two ways brought different bytes"); + assert_eq!( + direct, lane, + "round {round}: the two ways brought different bytes" + ); for i in 0..24u32 { - assert_eq!(lane[(i * 163 % DWORDS as u32) as usize], round * 1000 + i, "round {round}, write {i}"); + assert_eq!( + lane[(i * 163 % DWORDS as u32) as usize], + round * 1000 + i, + "round {round}, write {i}" + ); } } assert_eq!(warp.second.down.stats.jobs.load(Ordering::Relaxed), 3); @@ -877,17 +980,30 @@ void main() { let behind = warp.store(&card, (k * 4) as u32, 0xA000 + k as u32, 60_000); let list = second.down.list().expect("a copy list"); // SAFETY: an open copy list; live buffers; the slot is inside. - unsafe { list.1.CopyBufferRegion(&down, k as u64 * bytes, &card, 0, bytes) }; - second.down.send(list, &[(&warp.fence, behind)], bytes).expect("the fetch is sent"); + unsafe { + list.1 + .CopyBufferRegion(&down, k as u64 * bytes, &card, 0, bytes) + }; + second + .down + .send(list, &[(&warp.fence, behind)], bytes) + .expect("the fetch is sent"); } warp.land(); for k in 0..N { let slot = dwords(data, k * N, N); for (i, &got) in slot.iter().enumerate().take(k + 1) { - assert_eq!(got, 0xA000 + i as u32, "fetch {k} ran before write {i}, which was sent before its fence"); + assert_eq!( + got, + 0xA000 + i as u32, + "fetch {k} ran before write {i}, which was sent before its fence" + ); } for (i, &got) in slot.iter().enumerate().skip(k + 1) { - assert!(got == 0 || got == 0xA000 + i as u32, "fetch {k} holds {got:#x} for write {i}"); + assert!( + got == 0 || got == 0xA000 + i as u32, + "fetch {k} holds {got:#x} for write {i}" + ); } } } @@ -919,14 +1035,27 @@ void main() { for i in 0..(PART as usize / 4) { // SAFETY: inside the mapping; nothing on the card reads // part k before the send below. - unsafe { staged.cast::().add(k * (PART as usize / 4) + i).write_volatile(0xB000 + k as u32) }; + unsafe { + staged + .cast::() + .add(k * (PART as usize / 4) + i) + .write_volatile(0xB000 + k as u32) + }; } let slow = warp.store(&other, 0, k as u32, 80_000); let list = second.up.list().expect("a copy list"); // SAFETY: an open copy list; live buffers. - unsafe { list.1.CopyBufferRegion(&cards[k], 0, &staging, k as u64 * PART, PART) }; - let job = second.up.send(list, &[(&warp.fence, slow)], PART).expect("the bytes are sent up"); - second.hold(&warp.direct, job).expect("the direct queue waits"); + unsafe { + list.1 + .CopyBufferRegion(&cards[k], 0, &staging, k as u64 * PART, PART) + }; + let job = second + .up + .send(list, &[(&warp.fence, slow)], PART) + .expect("the bytes are sent up"); + second + .hold(&warp.direct, job) + .expect("the direct queue waits"); second.sent_up(&warp.direct, k as u64 + 1); // SAFETY: an open list; live buffers; the slots are inside. warp.fly(|list| unsafe { @@ -940,11 +1069,18 @@ void main() { for k in 0..N { let read = dwords(data, k * N, N); for (part, &got) in read.iter().enumerate().take(k + 1) { - assert_eq!(got, 0xB000 + part as u32, "the direct queue's read {k} ran before send {part} was on the card"); + assert_eq!( + got, + 0xB000 + part as u32, + "the direct queue's read {k} ran before send {part} was on the card" + ); } } assert_eq!(second.held[0].load(Ordering::Relaxed), N as u64); - assert_eq!(second.up.stats.bytes.load(Ordering::Relaxed), PART * N as u64); + assert_eq!( + second.up.stats.bytes.load(Ordering::Relaxed), + PART * N as u64 + ); } /// The way title bytes go up with bit 2, as `Host::card_before` does @@ -972,17 +1108,26 @@ void main() { let at = (k * 256) as u64; // SAFETY: inside the mapping; read by the card only through // the job below. - unsafe { staged.add(at as usize).cast::().write_volatile(0xC000 + k as u32) }; + unsafe { + staged + .add(at as usize) + .cast::() + .write_volatile(0xC000 + k as u32) + }; // A shader's (slow) store to the same dword, sent first. warp.store(&card, at as u32, 0xDEAD_0000 + k as u32, 80_000); // SAFETY: a plain query. let completed = unsafe { warp.fence.GetCompletedValue() }; - let landing = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + let landing = second + .landing(4, completed, warp.submitted + 1) + .expect("a landing buffer"); let list = second.up.list().expect("a copy list"); // SAFETY: an open copy list; live buffers. unsafe { list.1.CopyBufferRegion(&landing, 0, &staging, at, 4) }; let job = second.up.send(list, &[], 4).expect("the bytes are sent up"); - second.hold(&warp.direct, job).expect("the direct queue waits"); + second + .hold(&warp.direct, job) + .expect("the direct queue waits"); // SAFETY: an open list; live buffers. let read = warp.fly(|list| unsafe { list.CopyBufferRegion(&card, at, &landing, 0, 4); @@ -990,14 +1135,28 @@ void main() { }); let list = second.down.list().expect("a copy list"); // SAFETY: an open copy list; live buffers. - unsafe { list.1.CopyBufferRegion(&down_lane, (k * 4) as u64, &card, at, 4) }; - second.down.send(list, &[(&warp.fence, read)], 4).expect("the fetch is sent"); + unsafe { + list.1 + .CopyBufferRegion(&down_lane, (k * 4) as u64, &card, at, 4) + }; + second + .down + .send(list, &[(&warp.fence, read)], 4) + .expect("the fetch is sent"); landings.push(landing.as_raw() as usize); } warp.land(); let want: Vec = (0..N).map(|k| 0xC000 + k as u32).collect(); - assert_eq!(dwords(data, 0, N), want, "the title's bytes did not reach the copy behind the shader's store"); - assert_eq!(dwords(lane_data, 0, N), want, "the copy queue's fetch differs from the direct queue's"); + assert_eq!( + dwords(data, 0, N), + want, + "the title's bytes did not reach the copy behind the shader's store" + ); + assert_eq!( + dwords(lane_data, 0, N), + want, + "the copy queue's fetch differs from the direct queue's" + ); // No buffer was given out while its last use was in the air: one // given to two rounds was free in between. landings.sort_unstable(); @@ -1007,7 +1166,9 @@ void main() { let alive = second.landing[0].load(Ordering::Relaxed); // SAFETY: a plain query. let completed = unsafe { warp.fence.GetCompletedValue() }; - let again = second.landing(4, completed, warp.submitted + 1).expect("a landing buffer"); + let again = second + .landing(4, completed, warp.submitted + 1) + .expect("a landing buffer"); assert!(landings.contains(&(again.as_raw() as usize))); assert_eq!(second.landing[0].load(Ordering::Relaxed), alive); } @@ -1029,18 +1190,28 @@ void main() { let first_list = first.1.as_raw(); // SAFETY: an open copy list; live buffers. unsafe { first.1.CopyBufferRegion(&down, 0, &card, 0, 64) }; - let job = second.down.send(first, &[(&warp.fence, behind)], 64).expect("sent"); + let job = second + .down + .send(first, &[(&warp.fence, behind)], 64) + .expect("sent"); if !second.down.done(job) { // Still in the air: the next list is another one. let next = second.down.list().expect("a copy list"); - assert_ne!(next.1.as_raw(), first_list, "a list was reset while its job had not run"); + assert_ne!( + next.1.as_raw(), + first_list, + "a list was reset while its job had not run" + ); second.down.send(next, &[], 0).expect("sent"); } warp.land(); // Everything has run: a list of before comes back. let again = second.down.list().expect("a copy list"); let spare_left = lock(&second.down.state).spare.len(); - assert!(spare_left <= 1, "lists that have run are taken before new ones are made"); + assert!( + spare_left <= 1, + "lists that have run are taken before new ones are made" + ); second.down.send(again, &[], 0).expect("sent"); warp.land(); } diff --git a/crates/victory-gpu/src/resource.rs b/crates/victory-gpu/src/resource.rs index 9dcb9ace..ba335bad 100644 --- a/crates/victory-gpu/src/resource.rs +++ b/crates/victory-gpu/src/resource.rs @@ -281,7 +281,11 @@ pub(crate) fn target_format(format: u32) -> u32 { | D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW.0; let refused = asked.is_err() || support.Support1.0 & both != both; if refused { - tracing::info!(format = f, stand_in = to, "the host does not render to this format: a stand-in is used"); + tracing::info!( + format = f, + stand_in = to, + "the host does not render to this format: a stand-in is used" + ); } refused }) @@ -1292,7 +1296,11 @@ pub(crate) fn host_waits(this: This) -> bool { let r = resource(this); r.desc.dimension != BUFFER && !r.host.refused.load(std::sync::atomic::Ordering::Relaxed) - && r.host.made.lock().unwrap_or_else(|e| e.into_inner()).is_none() + && r.host + .made + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_none() } /// The host side of title texture `this`: made now if it is not there and @@ -1334,17 +1342,25 @@ fn hosted(this: This, make: bool) -> Option { let start = r.data() as u64; // What the upload can read: a console layout, no XOR mode // (`crate::texture` `staging`). - let readable = texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()); + let readable = + texture_layout(&r.desc).is_some_and(|t| !t.planes[0].layout.desc.swizzle.xor()); let partly = readable && bytes >= crate::tiles::floor() && (!crate::texture::committed(r.data().cast_const(), bytes as usize) - || crate::descriptor::host::next_start(start, start.saturating_add(bytes)).is_some() + || crate::descriptor::host::next_start(start, start.saturating_add(bytes)) + .is_some() || crate::descriptor::host::first_viewed(start).is_some_and(|first| first > 0)); - let reserved = if partly { host_texture_as(&r.desc, r.host.state, clear, true) } else { None }; + let reserved = if partly { + host_texture_as(&r.desc, r.host.state, clear, true) + } else { + None + }; let cut = reserved .as_ref() .zip(crate::host::host()) - .and_then(|(t, host)| crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels))); + .and_then(|(t, host)| { + crate::tiles::Tiled::make(&host.device, t, u32::from(r.desc.mip_levels)) + }); // (Both or neither: a reserved texture the card will not cut // into tiles is dropped here, and the old kind is made below.) if cut.is_some() { @@ -1448,7 +1464,8 @@ pub(crate) fn room() -> bool { // world makes in its first frame ([`targets_room_kept`]) counts as // used. Some([budget, used, ..]) => { - used + crate::shadow::card_room_kept() + targets_room_kept() < budget / 100 * room_percent() + used + crate::shadow::card_room_kept() + targets_room_kept() + < budget / 100 * room_percent() } None => filled < WITHOUT_BUDGET, } @@ -1482,7 +1499,9 @@ pub(crate) fn targets_room_kept() -> u64 { .map_or(3072 << 20, |mb| mb.min(8192) << 20) }); // Every host texture's bytes less those of the copies the title fills. - let targets = HOST_TEXTURES[1].load(Relaxed).saturating_sub(KINDS[1].load(Relaxed)); + let targets = HOST_TEXTURES[1] + .load(Relaxed) + .saturating_sub(KINDS[1].load(Relaxed)); most.saturating_sub(targets) } @@ -1532,7 +1551,9 @@ pub(crate) fn placed_known(address: u64, desc: &[u32; 14]) -> Option { key[1] = 0; key[13] = 0; let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); - map.get(&(address, key)).or_else(|| map.get(&(address, *desc))).map(|&r| r as This) + map.get(&(address, key)) + .or_else(|| map.get(&(address, *desc))) + .map(|&r| r as This) } /// For the card accounting line: whether title texture `this` has a host @@ -1554,7 +1575,11 @@ pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { let made = r.host.made.lock().unwrap_or_else(|e| e.into_inner()); Some(match made.as_ref() { Some((host, _)) => (2, host.bytes, memory), - None => (u8::from(r.host.gone.load(Relaxed)), footprint(&r.desc).map_or(0, |f| f.size), memory), + None => ( + u8::from(r.host.gone.load(Relaxed)), + footprint(&r.desc).map_or(0, |f| f.size), + memory, + ), }) } @@ -1584,12 +1609,18 @@ pub(crate) fn copy_state(this: This) -> Option<(u8, u64, u64)> { /// one that is not. Not measured: a tenth to half a second is expected, /// and the line says what it took. No line is begun while one is walking. #[cfg(windows)] -pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, gone: Vec<(u64, u64)>) { +pub(crate) fn card_accounting( + room: bool, + due: [u64; 5], + never: Vec<(u64, u64)>, + gone: Vec<(u64, u64)>, +) { use std::sync::atomic::Ordering::Relaxed; static WALKING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); // Host copies let go and their bytes, made again and their bytes, and // made in all, at the line before. - static BEFORE: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5]; + static BEFORE: [std::sync::atomic::AtomicU64; 5] = + [const { std::sync::atomic::AtomicU64::new(0) }; 5]; if WALKING.swap(true, Relaxed) { return; } @@ -1618,7 +1649,11 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, } let kinds = KINDS.each_ref().map(|k| k.load(Relaxed)); let mut since = [0u64; 5]; - for ((slot, now), before) in since.iter_mut().zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]).zip(&BEFORE) { + for ((slot, now), before) in since + .iter_mut() + .zip([kinds[2], kinds[3], kinds[4], kinds[5], kinds[6]]) + .zip(&BEFORE) + { *slot = now.saturating_sub(before.swap(now, Relaxed)); } let video = crate::host::host().and_then(|h| h.video_memory()); @@ -1646,7 +1681,9 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, c[6] += 1; continue; }; - if layout.size == 0 || crate::texture::committed(memory as *const u8, layout.size as usize) { + if layout.size == 0 + || crate::texture::committed(memory as *const u8, layout.size as usize) + { continue; } c[3] += 1; @@ -1664,7 +1701,11 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, let all: u64 = mips.iter().map(texels).sum::().max(1); let (mut missing, mut any) = (0u64, false); for (level, m) in mips.iter().enumerate().take(tail) { - let end = if level == 0 { layout.slice_size } else { mips[level - 1].offset }; + let end = if level == 0 { + layout.slice_size + } else { + mips[level - 1].offset + }; if end <= m.offset { continue; } @@ -1708,15 +1749,54 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, }; let (never, gone) = (mapped(&never), mapped(&gone)); let [budget_mb, used_mb] = video.map_or([0, 0], |v| [v[0] >> 20, v[1] >> 20]); - let [copies_n, copies_mb, unmapped_mb, partly, largest, nothing, unknown] = - [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; + let [ + copies_n, + copies_mb, + unmapped_mb, + partly, + largest, + nothing, + unknown, + ] = [c[0], c[1] >> 20, c[2] >> 20, c[3], c[4], c[5], c[6]]; let [without_never, without_gone] = without; - let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = [due[0], due[1], due[2], due[3], due[4] >> 20]; - let [never_n, never_mb, never_whole, never_whole_mb, never_part, never_part_mb, never_none] = - [never[0], never[1] >> 20, never[2], never[3] >> 20, never[4], never[5] >> 20, never[6]]; - let [gone_n, gone_mb, gone_whole, gone_whole_mb, gone_part, gone_part_mb, gone_none] = - [gone[0], gone[1] >> 20, gone[2], gone[3] >> 20, gone[4], gone[5] >> 20, gone[6]]; - let [let_go, let_go_mb, again, again_mb, made] = [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; + let [due_slots, due_uploaded, due_other, alive_n, alive_mb] = + [due[0], due[1], due[2], due[3], due[4] >> 20]; + let [ + never_n, + never_mb, + never_whole, + never_whole_mb, + never_part, + never_part_mb, + never_none, + ] = [ + never[0], + never[1] >> 20, + never[2], + never[3] >> 20, + never[4], + never[5] >> 20, + never[6], + ]; + let [ + gone_n, + gone_mb, + gone_whole, + gone_whole_mb, + gone_part, + gone_part_mb, + gone_none, + ] = [ + gone[0], + gone[1] >> 20, + gone[2], + gone[3] >> 20, + gone[4], + gone[5] >> 20, + gone[6], + ]; + let [let_go, let_go_mb, again, again_mb, made] = + [since[0], since[1] >> 20, since[2], since[3] >> 20, since[4]]; let walk_ms = began.elapsed().as_millis() as u64; let [by_level_n, by_level_mb] = [on_demand[0], on_demand[1] >> 20]; tracing::info!( @@ -1734,7 +1814,11 @@ pub(crate) fn card_accounting(room: bool, due: [u64; 5], never: Vec<(u64, u64)>, ); WALKING.store(false, Relaxed); }; - if std::thread::Builder::new().name("card accounting".into()).spawn(walk).is_err() { + if std::thread::Builder::new() + .name("card accounting".into()) + .spawn(walk) + .is_err() + { WALKING.store(false, Relaxed); } } @@ -1918,7 +2002,9 @@ pub(crate) fn census() -> [u64; 10] { placed_filled += 1; // Its first page: a texture's smallest mips lie there, // and are mapped first and unmapped last. - if placed_filled.is_multiple_of(EVERY) && !crate::texture::committed(r.data().cast_const(), 1) { + if placed_filled.is_multiple_of(EVERY) + && !crate::texture::committed(r.data().cast_const(), 1) + { count[8] += host.bytes * EVERY; if crate::host::references(&host.texture) > 1 { count[9] += host.bytes * EVERY; @@ -1950,13 +2036,18 @@ fn host_bytes(texture: &windows::Win32::Graphics::Direct3D12::ID3D12Resource) -> // SAFETY: plain queries on a live resource and device. unsafe { let desc = texture.GetDesc(); - host.device.GetResourceAllocationInfo(0, &[desc]).SizeInBytes + host.device + .GetResourceAllocationInfo(0, &[desc]) + .SizeInBytes } } #[cfg(windows)] impl HostTexture { - fn new(texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, state: u32) -> HostTexture { + fn new( + texture: windows::Win32::Graphics::Direct3D12::ID3D12Resource, + state: u32, + ) -> HostTexture { use windows::Win32::Graphics::Direct3D12::D3D12_RESOURCE_DIMENSION_TEXTURE3D; // SAFETY: a live resource. let desc = unsafe { texture.GetDesc() }; @@ -2123,7 +2214,8 @@ pub(crate) fn compute_mip_drop(desc: &ResourceDesc, requested: u32) -> u32 { #[cfg(windows)] fn compute_mip_drop_with_floor(desc: &ResourceDesc, requested: u32, floor: u64) -> u32 { const TEXTURE_1D: u32 = 2; - if requested == 0 || desc.dimension == BUFFER || desc.flags & 0x7 != 0 || desc.sample_count > 1 { + if requested == 0 || desc.dimension == BUFFER || desc.flags & 0x7 != 0 || desc.sample_count > 1 + { return 0; } let height = u64::from(desc.height); @@ -2143,8 +2235,16 @@ fn compute_mip_drop_with_floor(desc: &ResourceDesc, requested: u32, floor: u64) let mut best = 0; for drop in 1..=cap { let width = (desc.width >> drop).max(1); - let height = if desc.dimension == TEXTURE_1D { 1 } else { (height >> drop).max(1) }; - let depth = if desc.dimension == TEXTURE_3D { (depth >> drop).max(1) } else { 1 }; + let height = if desc.dimension == TEXTURE_1D { + 1 + } else { + (height >> drop).max(1) + }; + let depth = if desc.dimension == TEXTURE_3D { + (depth >> drop).max(1) + } else { + 1 + }; let large_enough = width.max(height).max(depth) >= floor; let aligned = width.is_multiple_of(block) && height.is_multiple_of(block); if large_enough && aligned { @@ -2188,7 +2288,10 @@ impl Drop for HostTexture { /// (never released), for the memory line. #[cfg(all(windows, feature = "diagnostics"))] pub(crate) fn placed_textures() -> u64 { - PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()).len() as u64 + PLACED_TEXTURES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .len() as u64 } /// Moves the host texture to `wanted` (a host texture state); the host @@ -2313,7 +2416,11 @@ fn host_texture_impl( }); let title_mips = mip_count(desc); let base = d; - let mut drop = if reserved { 0 } else { compute_mip_drop(&base, requested_mip_drop()) }; + let mut drop = if reserved { + 0 + } else { + compute_mip_drop(&base, requested_mip_drop()) + }; apply_mip_drop(&mut d, title_mips, drop); let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, @@ -2328,9 +2435,10 @@ fn host_texture_impl( unsafe { host.device.CreateReservedResource( (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), + D3D12_RESOURCE_STATES(crate::host::legal_for( + d.flags, + crate::host::texture_state(state), + ) as i32), None, &mut texture, ) @@ -2345,9 +2453,10 @@ fn host_texture_impl( &heap, D3D12_HEAP_FLAG_NONE, (&raw const d).cast(), - D3D12_RESOURCE_STATES( - crate::host::legal_for(d.flags, crate::host::texture_state(state)) as i32, - ), + D3D12_RESOURCE_STATES(crate::host::legal_for( + d.flags, + crate::host::texture_state(state), + ) as i32), // The same layout: format, then color or depth and stencil. clear_value.as_ref().map(|v| std::ptr::from_ref(v).cast()), &mut attempt, @@ -2371,7 +2480,10 @@ fn host_texture_impl( drop = next; d = base; apply_mip_drop(&mut d, title_mips, drop); - tracing::warn!(drop, "host texture allocation out of memory; dropping another top mip"); + tracing::warn!( + drop, + "host texture allocation out of memory; dropping another top mip" + ); } }; if let Err(e) = made { @@ -2379,7 +2491,10 @@ fn host_texture_impl( } if let Some(t) = &texture { crate::host::name(t, || { - format!("texture {}x{} f{} flags {:#x}", d.width, d.height, d.format, d.flags) + format!( + "texture {}x{} f{} flags {:#x}", + d.width, d.height, d.format, d.flags + ) }); } texture.map(|texture| (texture, drop)) @@ -2392,7 +2507,10 @@ pub(crate) fn host_tiled(this: This) -> Option { if this.is_null() || !crate::tiles::wanted() { return None; } - hosted(this, false).map(|(host, _)| host).filter(|host| host.tiled.is_some()).map(OnDemand) + hosted(this, false) + .map(|(host, _)| host) + .filter(|host| host.tiled.is_some()) + .map(OnDemand) } /// The first level a view of title texture `this` may show, if its host @@ -2808,7 +2926,9 @@ pub(crate) fn texture_at_made(address: u64, desc: &[u32; 14]) -> Option { key[1] = 0; key[13] = 0; let map = PLACED_TEXTURES.lock().unwrap_or_else(|e| e.into_inner()); - let found = map.get(&(address, key)).or_else(|| map.get(&(address, *desc)))?; + let found = map + .get(&(address, key)) + .or_else(|| map.get(&(address, *desc)))?; Some(*found as This) } @@ -2836,12 +2956,14 @@ pub(crate) fn texture_at(address: u64, desc: &[u32; 14]) -> Option { if raw != key { let mut seen = PLACED_RAW.lock().unwrap_or_else(|e| e.into_inner()); if seen.insert((address, raw)) { - let others = seen.range((address, [0; 14])..=(address, [u32::MAX; 14])).filter(|(_, r)| { - let mut blank = *r; - blank[1] = 0; - blank[13] = 0; - blank == key - }); + let others = seen + .range((address, [0; 14])..=(address, [u32::MAX; 14])) + .filter(|(_, r)| { + let mut blank = *r; + blank[1] = 0; + blank[13] = 0; + blank == key + }); if others.count() > 1 { PLACED_TWINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed); } diff --git a/crates/victory-gpu/src/shader_cache.rs b/crates/victory-gpu/src/shader_cache.rs index 995b58f0..6a384eb2 100644 --- a/crates/victory-gpu/src/shader_cache.rs +++ b/crates/victory-gpu/src/shader_cache.rs @@ -55,7 +55,12 @@ fn build() -> [u8; 32] { static WARNED: std::sync::Once = std::sync::Once::new(); let limit = victory_shader::emit::loop_limit(); if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT { - WARNED.call_once(|| tracing::warn!(limit, "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner")); + WARNED.call_once(|| { + tracing::warn!( + limit, + "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner" + ) + }); } static EXE: OnceLock> = OnceLock::new(); let exe = EXE.get_or_init(|| { @@ -135,8 +140,6 @@ pub(crate) fn host_shader(container: &[u8], mesh: MeshMode) -> Result { @@ -844,6 +847,4 @@ mod tests { assert_eq!(runs.load(Ordering::Relaxed), 3); assert_eq!(walk(dir.path()).len(), 3); } - - } diff --git a/crates/victory-gpu/src/shadow.rs b/crates/victory-gpu/src/shadow.rs index 96c36e83..e14d338f 100644 --- a/crates/victory-gpu/src/shadow.rs +++ b/crates/victory-gpu/src/shadow.rs @@ -149,13 +149,20 @@ fn card_limits() -> (u64, u64) { static LIMITS: std::sync::OnceLock<(u64, u64)> = std::sync::OnceLock::new(); *LIMITS.get_or_init(|| { let mb = |name: &str, default: u64| { - std::env::var(name).ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(default) << 20 + std::env::var(name) + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(default) + << 20 }; // From 1 MiB up and 1,024 MB in all by default (it was 16 and 512): // the shader writes of the smaller buffers are then found by the // card's hashes too, and with that the first room's walls were // drawn in every run. - (mb("VICTORY_CARD_BUFFERS_MIN_MB", 1).max(1 << 20), mb("VICTORY_CARD_BUFFERS_MB", 1024)) + ( + mb("VICTORY_CARD_BUFFERS_MIN_MB", 1).max(1 << 20), + mb("VICTORY_CARD_BUFFERS_MB", 1024), + ) }) } @@ -209,7 +216,9 @@ pub(crate) fn card_room_kept() -> u64 { if !card_room_kept_on() || !cards() { return 0; } - card_limits().1.saturating_sub(CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed)) + card_limits().1.saturating_sub( + CARD_BYTES[0].load(Ordering::Relaxed) + CARD_REFUSED[1].load(Ordering::Relaxed), + ) } /// The copies in the card's memory. @@ -227,7 +236,12 @@ pub(crate) fn card_stats() -> [u64; 10] { for (i, stat) in CARD_STATS.iter().enumerate() { out[i] = stat.swap(0, Ordering::Relaxed); } - out[7] = CARDED.lock().unwrap_or_else(|e| e.into_inner()).iter().filter(|w| w.strong_count() > 0).count() as u64; + out[7] = CARDED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .iter() + .filter(|w| w.strong_count() > 0) + .count() as u64; out[8] = CARD_BYTES[0].load(Ordering::Relaxed) + WINDOW_CARD_BYTES.load(Ordering::Relaxed); out[9] = CARD_BYTES[1].load(Ordering::Relaxed); out @@ -322,7 +336,11 @@ fn card_for(size: u64) -> Option { fn window_card_most() -> u64 { static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); *MOST.get_or_init(|| { - std::env::var("VICTORY_CARD_WINDOWS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) << 20 + std::env::var("VICTORY_CARD_WINDOWS_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) + << 20 }) } @@ -478,14 +496,35 @@ mod card_tests { pieces, skew: 7, }; - let runs = vec![run(40, 1), run(3, 2), run(4, 1), run(5, 3), run(40, 1), run(9, 1), run(41, 2), run(100, 1)]; - let mut wanted: Vec = runs.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + let runs = vec![ + run(40, 1), + run(3, 2), + run(4, 1), + run(5, 3), + run(40, 1), + run(9, 1), + run(41, 2), + run(100, 1), + ]; + let mut wanted: Vec = runs + .iter() + .flat_map(|r| r.first..r.first + r.pieces) + .collect(); wanted.sort_unstable(); wanted.dedup(); let joined = joined_piece_runs(runs); - let got: Vec = joined.iter().flat_map(|r| r.first..r.first + r.pieces).collect(); + let got: Vec = joined + .iter() + .flat_map(|r| r.first..r.first + r.pieces) + .collect(); assert_eq!(got, wanted); - assert_eq!(joined.iter().map(|r| (r.first, r.pieces)).collect::>(), [(3, 5), (9, 1), (40, 3), (100, 1)]); + assert_eq!( + joined + .iter() + .map(|r| (r.first, r.pieces)) + .collect::>(), + [(3, 5), (9, 1), (40, 3), (100, 1)] + ); assert!(joined.iter().all(|r| r.skew == 7)); assert!(joined_piece_runs(Vec::new()).is_empty()); } @@ -504,16 +543,34 @@ mod card_tests { /// arithmetic names the same bytes as ours. #[test] fn the_shader_and_the_merge_cut_the_same_pieces() { - for start in [0usize, 4096, PIECE - 16, PIECE, 3 * PIECE + 0x1f00, 0xd_b790_df00] { + for start in [ + 0usize, + 4096, + PIECE - 16, + PIECE, + 3 * PIECE + 0x1f00, + 0xd_b790_df00, + ] { let len = 5 * PIECE + 4096; - for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + for (from, to) in [ + (0, len), + (0, 1), + (16, PIECE), + (PIECE - 4, PIECE + 4), + (2 * PIECE, len), + (12345, 4 * PIECE + 7), + ] { let span = card_span_of(start, from, to); let mut at = from; for i in 0..span.pieces { let (lo, hi) = card_piece_of(start, len, &span, i); assert_eq!(lo, at, "{start:#x} {from} {to} piece {i}"); assert!(hi > lo && hi - lo <= PIECE); - assert_eq!(shader_piece(&span, i), (lo as u32, hi as u32), "{start:#x} {from} {to} piece {i}"); + assert_eq!( + shader_piece(&span, i), + (lo as u32, hi as u32), + "{start:#x} {from} {to} piece {i}" + ); at = hi; } assert_eq!(at, to, "{start:#x} {from} {to}"); @@ -527,15 +584,33 @@ mod card_tests { #[test] fn a_piece_fetched_in_flight_fits_its_slot() { let slot = crate::host::INFLIGHT_SLOT as usize; - for start in [0usize, 4096, 7, PIECE - 16, PIECE - 3, 3 * PIECE + 0x1f09, 0xd_b790_df00] { + for start in [ + 0usize, + 4096, + 7, + PIECE - 16, + PIECE - 3, + 3 * PIECE + 0x1f09, + 0xd_b790_df00, + ] { let len = 5 * PIECE + 4096; - for (from, to) in [(0, len), (0, 1), (16, PIECE), (PIECE - 4, PIECE + 4), (2 * PIECE, len), (12345, 4 * PIECE + 7)] { + for (from, to) in [ + (0, len), + (0, 1), + (16, PIECE), + (PIECE - 4, PIECE + 4), + (2 * PIECE, len), + (12345, 4 * PIECE + 7), + ] { let span = card_span_of(start, from, to); for i in 0..span.pieces { let (lo, hi) = card_piece_of(start, len, &span, i); let at = crate::host::inflight_piece_from(&span, i); assert_eq!(at % 16, 0); - assert!(lo >= at && hi - at <= slot, "{start:#x} {from} {to} piece {i}: {lo}..{hi} from {at}"); + assert!( + lo >= at && hi - at <= slot, + "{start:#x} {from} {to} piece {i}: {lo}..{hi} from {at}" + ); } } } @@ -570,16 +645,30 @@ mod card_tests { let mut air: std::collections::VecDeque<(Vec, Vec)> = Default::default(); let mut after_wrap = 0; for flight in 0..40u32 { - let drawn: Vec = (0..1 + flight * 37 % 700).map(|i| next.wrapping_add(i)).collect(); + let drawn: Vec = (0..1 + flight * 37 % 700) + .map(|i| next.wrapping_add(i)) + .collect(); next = next.wrapping_add(drawn.len() as u32); - let slotted: Vec = drawn.iter().copied().filter(|&k| inflight_gets_slot(k, landed, slots)).collect(); + let slotted: Vec = drawn + .iter() + .copied() + .filter(|&k| inflight_gets_slot(k, landed, slots)) + .collect(); after_wrap += slotted.iter().filter(|&&k| k < 1 << 20).count(); air.push_back((drawn, slotted)); - let mut used: Vec = air.iter().flat_map(|a| a.1.iter()).map(|k| k % slots).collect(); + let mut used: Vec = air + .iter() + .flat_map(|a| a.1.iter()) + .map(|k| k % slots) + .collect(); let n = used.len(); used.sort_unstable(); used.dedup(); - assert_eq!(used.len(), n, "flight {flight}: two tickets in the air share a slot"); + assert_eq!( + used.len(), + n, + "flight {flight}: two tickets in the air share a slot" + ); if air.len() == 3 && let Some((drawn, _)) = air.pop_front() { @@ -615,7 +704,10 @@ mod card_tests { let notes = [5u64, 6, 7]; let mark = fallback_fetched_mark(true, 7, Some(5)); let kept: Vec = notes.iter().copied().filter(|&s| s > mark).collect(); - assert!(kept.iter().any(|&s| s > 6), "send 7's note was dropped before flight 6 merged"); + assert!( + kept.iter().any(|&s| s > 6), + "send 7's note was dropped before flight 6 merged" + ); assert_eq!(mark, 5); // Without the switch every later merge fetches after 7: as before. assert_eq!(fallback_fetched_mark(false, 7, Some(5)), 7); @@ -625,7 +717,10 @@ mod card_tests { /// Changed ranges are joined where they overlap or touch, and only there. #[test] fn ranges_join_where_they_touch() { - assert_eq!(joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), [(0, 6), (8, 20), (30, 31)]); + assert_eq!( + joined(vec![(8, 12), (0, 4), (4, 6), (10, 20), (30, 31)]), + [(0, 6), (8, 20), (30, 31)] + ); assert!(joined(Vec::new()).is_empty()); } } @@ -653,7 +748,9 @@ pub(crate) fn relay() -> bool { // The crate's own tests run without it unless they ask: several of // them look at title memory right after a submission, which the // relay's landing thread may still be writing. - *ON.get_or_init(|| std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps()) + *ON.get_or_init(|| { + std::env::var("VICTORY_RELAY").map_or(!cfg!(test), |v| v == "1" || v == "2") && !keeps() + }) } /// The submission being prepared (its number among those started): what @@ -750,7 +847,11 @@ fn merge_piece(now: &[u8], held: &mut [u8], title: &mut [u8]) -> bool { } /// `[from, to)` without the ranges of `skip`, in order. -pub(crate) fn outside(from: usize, to: usize, mut skip: Vec<(usize, usize)>) -> Vec<(usize, usize)> { +pub(crate) fn outside( + from: usize, + to: usize, + mut skip: Vec<(usize, usize)>, +) -> Vec<(usize, usize)> { skip.sort_unstable(); let mut out = Vec::new(); let mut at = from; @@ -826,8 +927,13 @@ struct MergeRace { quiet: u64, } -static MERGE_RACE: Mutex = - Mutex::new(MergeRace { frame: 0, now: [0; 7], said: Vec::new(), total: [0; 7], quiet: 0 }); +static MERGE_RACE: Mutex = Mutex::new(MergeRace { + frame: 0, + now: [0; 7], + said: Vec::new(), + total: [0; 7], + quiet: 0, +}); /// With [`merge_race_on`], right before a merge writes `merged` over title /// memory at `address` (a stretch of the copy of the title buffer `copy`: @@ -844,7 +950,13 @@ static MERGE_RACE: Mutex = /// write-back itself runs) is not seen, nor one that wrote a byte and then /// its old value again. Costs one more read and two compares of every /// stretch written back, on the thread that merges. -fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u8], which: &'static str) { +fn merge_race( + read: Option<&[u8]>, + copy: (u64, u64), + address: usize, + merged: &[u8], + which: &'static str, +) { if !merge_race_on() { return; } @@ -906,7 +1018,15 @@ fn merge_race(read: Option<&[u8]>, copy: (u64, u64), address: usize, merged: &[u } let hit = u64::from(put_back + both > 0); let run_bytes: u64 = runs.iter().map(|r| r.1 as u64).sum(); - let add = [1, n as u64, put_back, both, hit, runs.len() as u64, run_bytes]; + let add = [ + 1, + n as u64, + put_back, + both, + hit, + runs.len() as u64, + run_bytes, + ]; for (i, v) in add.iter().enumerate() { race.now[i] += v; race.total[i] += v; @@ -971,9 +1091,17 @@ mod relay_tests { assert!(merge_piece(&now, &mut held, &mut title)); for at in 0..200 { if now[at] != held0[at] { - assert_eq!((title[at], held[at]), (now[at], now[at]), "the card's byte at {at}"); + assert_eq!( + (title[at], held[at]), + (now[at], now[at]), + "the card's byte at {at}" + ); } else { - assert_eq!((title[at], held[at]), (title0[at], held0[at]), "untouched at {at}"); + assert_eq!( + (title[at], held[at]), + (title0[at], held0[at]), + "untouched at {at}" + ); } } // Again with nothing new: nothing changes and nothing is reported. @@ -986,7 +1114,10 @@ mod relay_tests { fn ranges_are_cut_out() { assert_eq!(outside(10, 50, vec![]), vec![(10, 50)]); assert_eq!(outside(10, 50, vec![(0, 10), (50, 60)]), vec![(10, 50)]); - assert_eq!(outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), vec![(12, 30), (40, 48)]); + assert_eq!( + outside(10, 50, vec![(30, 35), (0, 12), (34, 40), (48, 99)]), + vec![(12, 30), (40, 48)] + ); assert_eq!(outside(10, 50, vec![(0, 99)]), vec![]); } @@ -1038,7 +1169,10 @@ mod relay_tests { for at in (4..8).chain(10..12).chain(30..32) { assert_eq!(title[at], 0xa0, "A's byte at {at}"); } - assert_eq!((title[8], title[9], title[20], title[50]), (0x77, 0x77, 0x77, 0x77)); + assert_eq!( + (title[8], title[9], title[20], title[50]), + (0x77, 0x77, 0x77, 0x77) + ); for at in 32..36 { assert_eq!(title[at], 0xb0, "B's byte so far at {at}"); } @@ -1112,7 +1246,11 @@ mod relay_tests { card[a..b].copy_from_slice(&cpu[a..b]); } // The merge leaves out what went up after the fetch. - let skip: Vec<(usize, usize)> = noted.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1)).collect(); + let skip: Vec<(usize, usize)> = noted + .iter() + .filter(|s| s.2 > fetched_after) + .map(|s| (s.0, s.1)) + .collect(); let mut changed = false; for (a, b) in outside(0, N, skip) { let mut t = title[a..b].to_vec(); @@ -1193,7 +1331,10 @@ fn first_difference(a: &[u8], b: &[u8]) -> Option { Some(i) => (i * DIFF_CHUNK, &a_chunks[i][..], &b_chunks[i][..]), None => (len - a_tail.len(), a_tail, b_tail), }; - a.iter().zip(b).position(|(x, y)| x != y).map(|i| offset + i) + a.iter() + .zip(b) + .position(|(x, y)| x != y) + .map(|i| offset + i) } /// Where `a` and `b` last differ within their common length. @@ -1277,7 +1418,9 @@ unsafe fn copy_wide(src: *const u8, dst: *mut u8, len: usize) { let n = each.min(len - at); s.spawn(move || { // SAFETY: a part of the caller's ranges. - unsafe { std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) }; + unsafe { + std::ptr::copy_nonoverlapping((src + at) as *const u8, (dst + at) as *mut u8, n) + }; }); } }); @@ -1327,23 +1470,27 @@ fn workers() -> &'static Workers { more: std::sync::Condvar::new(), }); STARTED.call_once(|| { - let n = std::thread::available_parallelism().map_or(4, |n| n.get() / 4).clamp(2, 6); + let n = std::thread::available_parallelism() + .map_or(4, |n| n.get() / 4) + .clamp(2, 6); for i in 0..n { - let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || { - let workers = WORKERS.get().expect("made above"); - loop { - let job = { - let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); - loop { - if let Some(job) = jobs.pop_front() { - break job; + let _ = std::thread::Builder::new() + .name(format!("victory-wide-{i}")) + .spawn(move || { + let workers = WORKERS.get().expect("made above"); + loop { + let job = { + let mut jobs = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()); + loop { + if let Some(job) = jobs.pop_front() { + break job; + } + jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); } - jobs = workers.more.wait(jobs).unwrap_or_else(|e| e.into_inner()); - } - }; - job(); - } - }); + }; + job(); + } + }); } }); workers @@ -1376,7 +1523,11 @@ fn wide(jobs: Vec) { } workers.more.notify_all(); loop { - let job = workers.jobs.lock().unwrap_or_else(|e| e.into_inner()).pop_front(); + let job = workers + .jobs + .lock() + .unwrap_or_else(|e| e.into_inner()) + .pop_front(); match job { Some(job) => job(), None => break, @@ -1458,8 +1609,19 @@ pub(crate) fn find_all(work: &[(Arc, usize, usize)]) -> Vec (shadow.data as usize, before.as_ptr() as usize, shadow.start as usize, from, to), + match shadow + .before + .lock() + .unwrap_or_else(|e| e.into_inner()) + .as_ref() + { + Some(before) => ( + shadow.data as usize, + before.as_ptr() as usize, + shadow.start as usize, + from, + to, + ), None => (0, 0, 0, 0, 0), } }) @@ -1562,7 +1724,10 @@ static BACK_CLASS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; /// where the card does the search (`VICTORY_CARD_BUFFERS_MIN_MB`); a /// window outside buffers cannot as the code stands. pub(crate) fn back_line(frames: f64) { - let c: Vec = BACK_CLASS.iter().map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames).collect(); + let c: Vec = BACK_CLASS + .iter() + .map(|c| c.swap(0, Ordering::Relaxed) as f64 / frames) + .collect(); if c.iter().all(|&v| v == 0.0) { return; } @@ -1615,8 +1780,21 @@ mod wide_tests { let mut dst = vec![0u8; len]; let (s, d) = (src.as_ptr() as usize, dst.as_mut_ptr() as usize); // Ranges of the buffer, each to the same offsets of the other. - let cuts = [0, 1, 1, 4096, 70_000, WIDE_JOB + 3, 2 * WIDE_JOB + 3, 2 * WIDE_JOB + 9, len]; - let copies: Vec<(usize, usize, usize)> = cuts.windows(2).map(|w| (s + w[0], d + w[0], w[1] - w[0])).collect(); + let cuts = [ + 0, + 1, + 1, + 4096, + 70_000, + WIDE_JOB + 3, + 2 * WIDE_JOB + 3, + 2 * WIDE_JOB + 9, + len, + ]; + let copies: Vec<(usize, usize, usize)> = cuts + .windows(2) + .map(|w| (s + w[0], d + w[0], w[1] - w[0])) + .collect(); let jobs = copy_jobs(copies); assert!(jobs.len() >= 3); wide(jobs); @@ -1633,7 +1811,18 @@ mod wide_tests { let mut now = old.clone(); // Changes: single bytes at piece edges, a run across two pieces, // the last byte, and nothing in between. - for at in [0usize, 1, PIECE - 1, PIECE, 3 * PIECE + 5, WIDE_JOB - 1, WIDE_JOB, WIDE_JOB + PIECE / 2, 2 * WIDE_JOB + 9, len - 1] { + for at in [ + 0usize, + 1, + PIECE - 1, + PIECE, + 3 * PIECE + 5, + WIDE_JOB - 1, + WIDE_JOB, + WIDE_JOB + PIECE / 2, + 2 * WIDE_JOB + 9, + len - 1, + ] { now[at] ^= 0x5a; } for byte in &mut now[9 * PIECE - 40..9 * PIECE + 40] { @@ -1643,7 +1832,15 @@ mod wide_tests { let mut scans = Vec::new(); let mut wanted = Vec::new(); for start in [0usize, 4096, PIECE - 16, 0xd_b790_df00] { - for (from, to) in [(0, len), (0, 1), (1, 2), (PIECE - 1, PIECE + 1), (3 * PIECE, 3 * PIECE), (12345, len - 1), (WIDE_JOB - 3, 2 * WIDE_JOB + 10)] { + for (from, to) in [ + (0, len), + (0, 1), + (1, 2), + (PIECE - 1, PIECE + 1), + (3 * PIECE, 3 * PIECE), + (12345, len - 1), + (WIDE_JOB - 3, 2 * WIDE_JOB + 10), + ] { scans.push((data, before, start, from, to)); let mut pieces = Vec::new(); let mut at = from; @@ -1711,7 +1908,12 @@ fn back_piece( mask.clear(); mask.resize(n, 0); let mut differs = 0u8; - for (((t, h), o), m) in title.iter_mut().zip(host.iter_mut()).zip(old).zip(mask.iter_mut()) { + for (((t, h), o), m) in title + .iter_mut() + .zip(host.iter_mut()) + .zip(old) + .zip(mask.iter_mut()) + { let gpu = if (*h != *o) & (*t == *o) { 0xffu8 } else { 0 }; let merged = (*t & !gpu) | (*h & gpu); *m = merged ^ *t; @@ -1784,7 +1986,12 @@ fn joined_over(runs: Vec<(usize, usize)>, gap: usize) -> Vec<(usize, usize)> { /// the default for that reason. fn merge_gap() -> usize { static GAP: std::sync::OnceLock = std::sync::OnceLock::new(); - *GAP.get_or_init(|| std::env::var("VICTORY_MERGE_GAP").ok().and_then(|v| v.trim().parse::().ok()).map_or(0, |n| n.min(64))) + *GAP.get_or_init(|| { + std::env::var("VICTORY_MERGE_GAP") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .map_or(0, |n| n.min(64)) + }) } /// The runs of bytes where `now` differs from `was` (of one length), as @@ -1843,7 +2050,10 @@ mod merge_tests { into.copy_from_slice(&title_memory[first..first + into.len()]); true }; - assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((5, 5))); + assert_eq!( + back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), + Some((5, 5)) + ); assert_eq!(asked, Some((5, 5))); let mut wanted = title_memory[5..10].to_vec(); wanted[0] = gpu[5]; @@ -1854,14 +2064,38 @@ mod merge_tests { assert_eq!(runs, [(0, 1), (4, 1)]); // The copy outside the stretch is left as it was. assert!(host[..5] == gpu[..5] && host[10..] == gpu[10..]); - assert!(scratch.capacity() < PIECE / 2, "scratch of {} bytes for a stretch of 5", scratch.capacity()); + assert!( + scratch.capacity() < PIECE / 2, + "scratch of {} bytes for a stretch of 5", + scratch.capacity() + ); // Nothing differs: title memory is not read. let mut same = old.clone(); - assert_eq!(back_piece(&mut same, &old, &mut scratch, &mut mask, &mut runs, |_, _| unreachable!()), None); + assert_eq!( + back_piece( + &mut same, + &old, + &mut scratch, + &mut mask, + &mut runs, + |_, _| unreachable!() + ), + None + ); // Title memory not there: nothing to write, the copy unchanged. let mut host = gpu.clone(); - assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, _| false), None); + assert_eq!( + back_piece( + &mut host, + &old, + &mut scratch, + &mut mask, + &mut runs, + |_, _| false + ), + None + ); assert!(host == gpu); // The GPU wrote what the title holds already: nothing to write. let mut title_memory = old.clone(); @@ -1872,10 +2106,23 @@ mod merge_tests { into.copy_from_slice(&title_memory[first..first + into.len()]); true }; - assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), None); + assert_eq!( + back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), + None + ); // A whole piece changed: the scratch grows to it. let mut host: Vec = old.iter().map(|b| !b).collect(); - assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, |_, into| into.len() == PIECE), Some((0, PIECE))); + assert_eq!( + back_piece( + &mut host, + &old, + &mut scratch, + &mut mask, + &mut runs, + |_, into| into.len() == PIECE + ), + Some((0, PIECE)) + ); assert_eq!(scratch.len(), PIECE); } @@ -1898,8 +2145,15 @@ mod merge_tests { into.copy_from_slice(&title_memory[first..first + into.len()]); true }; - assert_eq!(back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), Some((1, 4))); - assert_eq!(scratch, [20, 3, 44, 50], "the title's byte where both changed"); + assert_eq!( + back_piece(&mut host, &old, &mut scratch, &mut mask, &mut runs, read), + Some((1, 4)) + ); + assert_eq!( + scratch, + [20, 3, 44, 50], + "the title's byte where both changed" + ); assert_eq!(host[1..5], [20, 3, 44, 50], "the copy takes the result"); assert_eq!(runs, [(0, 1), (3, 1)], "the GPU's bytes only"); } @@ -1909,7 +2163,16 @@ mod merge_tests { #[test] fn changed_runs_are_exactly_the_bytes_that_differ() { let was: Vec = (0..300u32).map(|i| (i * 13 + 5) as u8).collect(); - for changes in [vec![], vec![0], vec![299], vec![7, 8, 9], vec![7, 9], vec![15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299]] { + for changes in [ + vec![], + vec![0], + vec![299], + vec![7, 8, 9], + vec![7, 9], + vec![ + 15, 16, 17, 23, 24, 64, 65, 66, 67, 68, 69, 70, 71, 72, 298, 299, + ], + ] { let mut now = was.clone(); for &at in &changes { now[at] ^= 0x41; @@ -1925,7 +2188,10 @@ mod merge_tests { assert_eq!(put, now, "{changes:?}"); assert_eq!(held, changes, "{changes:?}"); // Runs do not touch: two that did would be one. - assert!(runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), "{changes:?}"); + assert!( + runs.windows(2).all(|w| w[0].0 + w[0].1 < w[1].0), + "{changes:?}" + ); } assert!(changed_runs(&[], &[]).is_empty()); } @@ -1933,7 +2199,8 @@ mod merge_tests { /// Host copies alive (also those only a list, a descriptor pass or a /// snapshot still holds) and the bytes of title memory they copy. -static LIVE: [std::sync::atomic::AtomicU64; 2] = [const { std::sync::atomic::AtomicU64::new(0) }; 2]; +static LIVE: [std::sync::atomic::AtomicU64; 2] = + [const { std::sync::atomic::AtomicU64::new(0) }; 2]; impl Drop for Shadow { fn drop(&mut self) { @@ -1954,7 +2221,12 @@ impl Drop for Shadow { } else { CARD_BYTES[0].fetch_sub(card.size, Ordering::Relaxed); } - if card.before.get_mut().unwrap_or_else(|e| e.into_inner()).is_some() { + if card + .before + .get_mut() + .unwrap_or_else(|e| e.into_inner()) + .is_some() + { CARD_BYTES[1].fetch_sub(card_hash_bytes(card.size), Ordering::Relaxed); } } @@ -1993,7 +2265,11 @@ static KEPT_BYTES: AtomicU64 = AtomicU64::new(0); fn kept_most() -> u64 { static MOST: std::sync::OnceLock = std::sync::OnceLock::new(); *MOST.get_or_init(|| { - std::env::var("VICTORY_KEEP_SNAPSHOTS_MB").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(256) << 20 + std::env::var("VICTORY_KEEP_SNAPSHOTS_MB") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(256) + << 20 }) } @@ -2022,7 +2298,15 @@ mod piece_tests { /// cuts (at multiples of 64 KiB of title memory). #[test] fn pieces_cover_the_copy_as_the_compare_cuts_it() { - for start in [0usize, 1, 4096, PIECE - 1, PIECE, PIECE + 77, 5 * PIECE + 12345] { + for start in [ + 0usize, + 1, + 4096, + PIECE - 1, + PIECE, + PIECE + 77, + 5 * PIECE + 12345, + ] { for len in [1usize, 100, PIECE - 1, PIECE, PIECE + 1, 3 * PIECE + 500] { let count = pieces_of(start, 0, len).end; let mut at = 0; @@ -2056,7 +2340,13 @@ mod piece_tests { /// merged nor a reason to settle; the refresh leaves such ranges alone, and /// shaders read zeros there (fxceless/victory-fork#206: missing geometry /// with `VICTORY_LATE_WAIT`/`VICTORY_RELAY`). -fn stale_pages_in(base: usize, copied: &[u64], a: usize, e: usize, written: &[(usize, u64)]) -> Vec { +fn stale_pages_in( + base: usize, + copied: &[u64], + a: usize, + e: usize, + written: &[(usize, u64)], +) -> Vec { (a / PAGE..e.div_ceil(PAGE)) .filter(|&page| page >= base) .filter(|&page| match copied.get(page - base) { @@ -2081,9 +2371,15 @@ mod stale_tests { // Page 0x101 was never taken; page 0x102 was written after it was // taken, page 0x103 before. let written = [(0x102, 6), (0x103, 4)]; - assert_eq!(stale_pages_in(base, &copied, at(0x100), at(0x104), &written), [0x101, 0x102]); + assert_eq!( + stale_pages_in(base, &copied, at(0x100), at(0x104), &written), + [0x101, 0x102] + ); // Part of a page counts as the page; pages outside the copy do not. - assert_eq!(stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), [0x101]); + assert_eq!( + stale_pages_in(base, &copied, at(0x101) + 8, at(0x101) + 16, &[]), + [0x101] + ); assert!(stale_pages_in(base, &copied, at(0x104), at(0x106), &[(0x104, 9)]).is_empty()); } } @@ -2108,7 +2404,11 @@ pub(crate) fn windows() -> [u64; 3] { }) .sum() }; - [LET_GO[0].load(Ordering::Relaxed), LET_GO[1].load(Ordering::Relaxed), asked] + [ + LET_GO[0].load(Ordering::Relaxed), + LET_GO[1].load(Ordering::Relaxed), + asked, + ] } /// For the memory line, of the windows alive: the bytes of their pages @@ -2177,12 +2477,17 @@ pub(crate) fn let_go_idle() { }) .map(|(key, _)| *key) .collect(); - idle.into_iter().filter_map(|key| map.remove(&key)).collect() + idle.into_iter() + .filter_map(|key| map.remove(&key)) + .collect() }; if !gone.is_empty() { let (went, bytes) = (gone.len(), gone.iter().map(|s| s.len).sum::()); crate::host::trail(|| { - format!("sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", bytes >> 10) + format!( + "sweep: {went} host copies of windows of title memory let go ({} KiB), held by no list and no slot", + bytes >> 10 + ) }); } for shadow in gone { @@ -2212,7 +2517,10 @@ pub(crate) fn memory() -> [u64; 6] { }; let (kept, kept_bytes) = { let pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - (pool.len() as u64, pool.iter().map(|v| v.capacity() as u64).sum::()) + ( + pool.len() as u64, + pool.iter().map(|v| v.capacity() as u64).sum::(), + ) }; [ LIVE[0].load(Ordering::Relaxed), @@ -2272,7 +2580,9 @@ impl Shadow { /// that binds, views or keeps a copy works on it unchanged; what /// copies does nothing ([`Shadow::update`], [`Shadow::gpu_writes`]). fn placed(placed: crate::inplace::Placed, start: u64, len: u64, window: bool) -> Shadow { - crate::host::name(&placed.buffer, || format!("title memory {start:#x}+{len:#x} in place")); + crate::host::name(&placed.buffer, || { + format!("title memory {start:#x}+{len:#x} in place") + }); let mut shadow = Shadow::new(placed.buffer, start as *mut u8, placed.gpu, start, len); // Not a copy: not counted with them, and nothing asks what the // title wrote there. @@ -2366,7 +2676,10 @@ impl Shadow { // With the copy-back on its own thread: counted for this submission // (once), whether or not an earlier one still holds the range. if relay() { - self.flights.lock().unwrap_or_else(|e| e.into_inner()).declare(range, PREPARED.load(Ordering::Relaxed)); + self.flights + .lock() + .unwrap_or_else(|e| e.into_inner()) + .declare(range, PREPARED.load(Ordering::Relaxed)); } // Dispatches declare the same ranges thousands of times. if pending.contains(&range) { @@ -2401,7 +2714,10 @@ impl Shadow { parts = rest; } pending.push(range); - let taken: usize = parts.iter().map(|&(from, to)| to.saturating_sub(from)).sum(); + let taken: usize = parts + .iter() + .map(|&(from, to)| to.saturating_sub(from)) + .sum(); BACK_CLASS[usize::from(!self.window)].fetch_add(taken as u64, Ordering::Relaxed); let total = self.len as usize; let mut before = self.before.lock().unwrap_or_else(|e| e.into_inner()); @@ -2430,7 +2746,11 @@ impl Shadow { let (lo, hi) = (lo.max(from), hi.min(to)); // SAFETY: as below; `hi <= total`. unsafe { - std::ptr::copy_nonoverlapping(self.data.add(lo), snapshot.as_mut_ptr().add(lo), hi - lo); + std::ptr::copy_nonoverlapping( + self.data.add(lo), + snapshot.as_mut_ptr().add(lo), + hi - lo, + ); } kept.0[piece] = whole; } @@ -2445,7 +2765,12 @@ impl Shadow { // range is done with (`copy_back_done`). let mut snaps = SNAPS.lock().unwrap_or_else(|e| e.into_inner()); let (data, snapshot) = (self.data as usize, snapshot.as_mut_ptr() as usize); - snaps.extend(parts.into_iter().filter(|&(from, to)| from < to).map(|(from, to)| (data + from, snapshot + from, to - from))); + snaps.extend( + parts + .into_iter() + .filter(|&(from, to)| from < to) + .map(|(from, to)| (data + from, snapshot + from, to - from)), + ); return; } for (from, to) in parts { @@ -2453,7 +2778,11 @@ impl Shadow { // SAFETY: the copy's mapping and the snapshot's allocation // (`pooled`) both hold `total` bytes, and `to <= total`. unsafe { - copy_wide(self.data.add(from), snapshot.as_mut_ptr().add(from), to - from); + copy_wide( + self.data.add(from), + snapshot.as_mut_ptr().add(from), + to - from, + ); } } } @@ -2475,7 +2804,12 @@ impl Shadow { /// [`Shadow::copy_back`]; `found`, if given, is the pieces of the range /// that differ from the snapshot, found beforehand ([`find_all`]). - pub(crate) fn copy_back_with(&self, address: usize, len: usize, found: Option>) -> usize { + pub(crate) fn copy_back_with( + &self, + address: usize, + len: usize, + found: Option>, + ) -> usize { if self.place.is_some() { return 0; } @@ -2489,7 +2823,8 @@ impl Shadow { { // SAFETY: `writing` set the snapshot's bytes of every declared // range, at the copy's offsets. - let before = unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; + let before = + unsafe { std::slice::from_raw_parts(before.as_ptr().add(from), to - from) }; // By 64 KiB piece: the copy compared with its bytes before the // submission (on several threads: gigabytes a frame, bound by // memory speed), title memory read only where the GPU wrote. @@ -2520,8 +2855,12 @@ impl Shadow { // writes it. let host = unsafe { std::slice::from_raw_parts_mut(self.data.add(at), n) }; let old = &before[at - from..at - from + n]; - let read = |first: usize, title: &mut [u8]| crate::host::read_into((start + at + first) as *const u8, title); - let Some((first, n)) = back_piece(host, old, &mut title, &mut mask, &mut runs, read) else { + let read = |first: usize, title: &mut [u8]| { + crate::host::read_into((start + at + first) as *const u8, title) + }; + let Some((first, n)) = + back_piece(host, old, &mut title, &mut mask, &mut runs, read) + else { continue; }; let at = at + first; @@ -2531,7 +2870,11 @@ impl Shadow { // stretch is the title's as read, and a title write landing // there since stays. for &(off, len) in &runs { - crate::host::write_mapped((start + at + off) as *mut u8, title[off..].as_ptr(), len); + crate::host::write_mapped( + (start + at + off) as *mut u8, + title[off..].as_ptr(), + len, + ); written += len; } } @@ -2541,7 +2884,10 @@ impl Shadow { // current, cost more: 19-31 askings a frame over 110-174 MB of // view memory, each a walk of its guards. #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::BackSyncUs, syncing.elapsed().as_micros() as u64); + crate::copystat::add( + crate::copystat::C::BackSyncUs, + syncing.elapsed().as_micros() as u64, + ); } written } @@ -2580,7 +2926,13 @@ impl Shadow { /// and puts the title's bytes into the copy and the snapshot: the two /// never see each other half done. `now` and `title` are scratch /// memory. Returns the bytes written to title memory. - pub(crate) fn relay_merge(&self, at: usize, n: usize, now: &mut Vec, title: &mut Vec) -> usize { + pub(crate) fn relay_merge( + &self, + at: usize, + n: usize, + now: &mut Vec, + title: &mut Vec, + ) -> usize { let start = self.start as usize; if self.card.is_some() || n == 0 || at + n > self.len as usize { return 0; @@ -2627,7 +2979,13 @@ impl Shadow { return n; } crate::watch::writing(start + at, n); - merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "pc relay"); + merge_race( + as_read.as_deref(), + (self.start, self.len), + start + at, + &title[..], + "pc relay", + ); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } @@ -2644,8 +3002,16 @@ impl Shadow { /// memory cannot be written that way (the caller writes as before). fn put_back_own(&self, at: usize, bytes: &[u8]) -> bool { /// Since the start: stretches and bytes stored this way, pages - /// noted current for their copy, stretches written the old way. - static OWN_WRITES: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4]; + /// noted current for their copy, stretches written the old way; + /// and with `VICTORY_BACK_OWN_CHECK=1`: stores the title's own + /// address did not show afterwards, pages noted current whose + /// CPU side in the copy differs from title memory, and those of + /// them whose guard was clean (a hole in the rule: a title write + /// on its way leaves the guard open). + static OWN_WRITES: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; + static CHECK: std::sync::OnceLock = std::sync::OnceLock::new(); + let check = *CHECK + .get_or_init(|| std::env::var_os("VICTORY_BACK_OWN_CHECK").is_some_and(|v| v == "1")); if !crate::inplace::back_own() { return false; } @@ -2653,8 +3019,19 @@ impl Shadow { OWN_WRITES[3].fetch_add(1, Ordering::Relaxed); return false; }; + if check { + // The title's own address must show what went in through ours. + let mut back = vec![0u8; bytes.len()]; + if crate::host::read_into(at as *const u8, &mut back) && back != bytes { + OWN_WRITES[4].fetch_add(1, Ordering::Relaxed); + } + } let page = at / PAGE; - let others: Vec = shown.iter().map(|&a| a / PAGE).filter(|&p| p != page).collect(); + let others: Vec = shown + .iter() + .map(|&a| a / PAGE) + .filter(|&p| p != page) + .collect(); let (before, now) = crate::watch::wrote_own(page, &others); // A placed texture there changed with no descriptor written (what // `crate::watch::writing` tells the texture table on the old way). @@ -2668,16 +3045,41 @@ impl Shadow { { *taken = (*taken).max(now); OWN_WRITES[2].fetch_add(1, Ordering::Relaxed); + // A copy in the card's memory only: its CPU side is never + // written by the card, so it must equal title memory now. + if check && self.card.is_some() { + let (start, end) = (self.start as usize, (self.start + self.len) as usize); + let (lo, hi) = ((page * PAGE).max(start), ((page + 1) * PAGE).min(end)); + if lo < hi { + let mut title = vec![0u8; hi - lo]; + // SAFETY: inside the copy's mapping; read only. + let held = unsafe { + std::slice::from_raw_parts( + self.data.add(lo - start).cast_const(), + hi - lo, + ) + }; + if crate::host::read_into(lo as *const u8, &mut title) && title != held { + OWN_WRITES[5].fetch_add(1, Ordering::Relaxed); + if crate::watch::clean(page) { + OWN_WRITES[6].fetch_add(1, Ordering::Relaxed); + } + } + } + } } } OWN_WRITES[1].fetch_add(bytes.len() as u64, Ordering::Relaxed); let n = OWN_WRITES[0].fetch_add(1, Ordering::Relaxed) + 1; if n.is_multiple_of(16384) { tracing::info!( - "what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way", + "what shaders wrote, stored through views of our own (VICTORY_BACK_OWN_VIEW=1), since the start: {n} stretches {} MB, {} pages noted current for the copy that wrote them (not copied in again), {} stretches written the old way; with VICTORY_BACK_OWN_CHECK=1: {} stores the title's address did not show, {} pages noted current whose CPU side differs from title memory, {} of those with the guard clean", OWN_WRITES[1].load(Ordering::Relaxed) >> 20, OWN_WRITES[2].load(Ordering::Relaxed), - OWN_WRITES[3].load(Ordering::Relaxed) + OWN_WRITES[3].load(Ordering::Relaxed), + OWN_WRITES[4].load(Ordering::Relaxed), + OWN_WRITES[5].load(Ordering::Relaxed), + OWN_WRITES[6].load(Ordering::Relaxed) ); } true @@ -2749,7 +3151,11 @@ impl Shadow { } let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner()); if relay() { - let free = self.flights.lock().unwrap_or_else(|e| e.into_inner()).done(ranges); + let free = self + .flights + .lock() + .unwrap_or_else(|e| e.into_inner()) + .done(ranges); pending.retain(|r| !free.contains(r)); } else { pending.retain(|r| !ranges.contains(r)); @@ -2811,7 +3217,11 @@ impl Shadow { /// Whether shaders of a submission not yet copied back may be writing /// the copy. pub(crate) fn writes_pending(&self) -> bool { - !self.pending.lock().unwrap_or_else(|e| e.into_inner()).is_empty() + !self + .pending + .lock() + .unwrap_or_else(|e| e.into_inner()) + .is_empty() } /// Whether [`Shadow::update`] of `[address, address + len)` would leave @@ -2847,10 +3257,11 @@ impl Shadow { } let base = start / PAGE; let copied = self.copied.lock().unwrap_or_else(|e| e.into_inner()); - busy.into_iter().any(|(a, e)| match crate::watch::asked(a, e) { - Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), - None => true, - }) + busy.into_iter() + .any(|(a, e)| match crate::watch::asked(a, e) { + Some((_, written)) => !stale_pages_in(base, &copied, a, e, &written).is_empty(), + None => true, + }) } /// Where [`Shadow::stale_under_writes`] says yes: puts the bytes the @@ -2869,7 +3280,12 @@ impl Shadow { /// Whether the caller must still settle the flights: the journal /// cannot say what was written, a snapshot is missing, or `runs_left` /// ran out. Pages done before that stay done. - pub(crate) fn merge_under_writes(&self, address: usize, len: usize, runs_left: &mut usize) -> bool { + pub(crate) fn merge_under_writes( + &self, + address: usize, + len: usize, + runs_left: &mut usize, + ) -> bool { let (start, end) = (self.start as usize, (self.start + self.len) as usize); let (from, to) = (address.max(start), (address + len).min(end)); if from >= to { @@ -2950,12 +3366,19 @@ impl Shadow { // SAFETY: the snapshot's allocation holds the copy's // bytes at the copy's offsets (`writing`), and these // are in a declared range. - let held = unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) }; + let held = + unsafe { std::slice::from_raw_parts_mut(snapshot.as_mut_ptr().add(at), n) }; for (r, m) in changed_runs(title, held) { // SAFETY: inside the copy's mapping. The card may be // writing the copy beside these bytes; they are // written here and nothing around them. - unsafe { std::ptr::copy_nonoverlapping(title.as_ptr().add(r), self.data.add(at + r), m) }; + unsafe { + std::ptr::copy_nonoverlapping( + title.as_ptr().add(r), + self.data.add(at + r), + m, + ) + }; held[r..r + m].copy_from_slice(&title[r..r + m]); MERGED[1].fetch_add(1, Ordering::Relaxed); MERGED[2].fetch_add(m as u64, Ordering::Relaxed); @@ -3056,7 +3479,8 @@ impl Shadow { /// title's that arrived between the refresh and the look. fn refresh_check(&self, from: usize, to: usize) { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) { + if !*ON.get_or_init(|| std::env::var_os("VICTORY_REFRESH_CHECK").is_some_and(|v| v == "1")) + { return; } const SAMPLE: usize = 256; @@ -3071,7 +3495,9 @@ impl Shadow { if crate::host::read_into(at as *const u8, &mut title[..n]) { // SAFETY: `[from, to)` lies inside the buffer (`update`), // so these bytes are inside the copy's mapping. - let copy = unsafe { std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) }; + let copy = unsafe { + std::slice::from_raw_parts(self.data.add(at - start).cast_const(), n) + }; let mut map = DIFFERING.lock().unwrap_or_else(|e| e.into_inner()); let map = map.get_or_insert_with(Default::default); if copy == &title[..n] { @@ -3169,7 +3595,9 @@ impl Shadow { } let mut dirty = card.dirty.lock().unwrap_or_else(|e| e.into_inner()); match dirty.last_mut() { - Some(last) if from <= last.1 && to >= last.0 => *last = (last.0.min(from), last.1.max(to)), + Some(last) if from <= last.1 && to >= last.0 => { + *last = (last.0.min(from), last.1.max(to)) + } _ => dirty.push((from, to)), } } @@ -3178,7 +3606,11 @@ impl Shadow { /// card side's bytes from before if made yet, and their size. pub(crate) fn card_sides(&self) -> Option<(&ID3D12Resource, Option, u64)> { let card = self.card.as_ref()?; - let before = card.before.lock().unwrap_or_else(|e| e.into_inner()).clone(); + let before = card + .before + .lock() + .unwrap_or_else(|e| e.into_inner()) + .clone(); Some((&card.staging, before, card.size)) } @@ -3187,7 +3619,10 @@ impl Shadow { /// Whether one was made now: the caller fills it, whole, from the /// card's side before the submission's lists run. Without one (no /// memory) every piece of a declared range is fetched. - pub(crate) fn card_make_before(&self, make: impl FnOnce(u64) -> Option) -> bool { + pub(crate) fn card_make_before( + &self, + make: impl FnOnce(u64) -> Option, + ) -> bool { let Some(card) = &self.card else { return false; }; @@ -3230,14 +3665,20 @@ impl Shadow { if !crate::host::walls_trace() { return; } - static SEEN: Mutex<(u64, BTreeMap)> = Mutex::new((0, BTreeMap::new())); + static SEEN: Mutex<(u64, BTreeMap)> = + Mutex::new((0, BTreeMap::new())); let frame = crate::frame::current(); let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner()); if seen.0 != frame { let buffers: Vec = seen .1 .iter() - .map(|(at, v)| format!("{at:#x}+{:#x}: {} pieces, {} fetched, {} written", v.0, v.1, v.2, v.3)) + .map(|(at, v)| { + format!( + "{at:#x}+{:#x}: {} pieces, {} fetched, {} written", + v.0, v.1, v.2, v.3 + ) + }) .take(32) .collect(); if !buffers.is_empty() { @@ -3299,7 +3740,13 @@ impl Shadow { if differs != 0 { crate::host::shaders_write(start + at, &title[..]); crate::watch::writing(start + at, n); - merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card"); + merge_race( + as_read.as_deref(), + (self.start, self.len), + start + at, + &title[..], + "card", + ); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); written = n; } @@ -3331,7 +3778,13 @@ impl Shadow { /// a copy has no other use for), as [`Shadow::merge_under_writes`]. /// `title` is scratch memory. Returns the bytes written to title /// memory. - pub(crate) fn card_merge_relay(&self, at: usize, gpu: &[u8], fetched_after: u64, title: &mut Vec) -> usize { + pub(crate) fn card_merge_relay( + &self, + at: usize, + gpu: &[u8], + fetched_after: u64, + title: &mut Vec, + ) -> usize { let start = self.start as usize; let Some(card) = &self.card else { return 0; @@ -3357,7 +3810,11 @@ impl Shadow { dirty .iter() .copied() - .chain(sent.iter().filter(|s| s.2 > fetched_after).map(|s| (s.0, s.1))) + .chain( + sent.iter() + .filter(|s| s.2 > fetched_after) + .map(|s| (s.0, s.1)), + ) .filter(|&(a, b)| a < at + n && b > at) .collect() }; @@ -3382,7 +3839,13 @@ impl Shadow { return n; } crate::watch::writing(start + at, n); - merge_race(as_read.as_deref(), (self.start, self.len), start + at, &title[..], "card relay"); + merge_race( + as_read.as_deref(), + (self.start, self.len), + start + at, + &title[..], + "card relay", + ); crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n); n } @@ -3469,7 +3932,10 @@ pub(crate) fn in_place_let_go(at: u64, len: u64) -> u64 { /// bytes, false) and the windows outside buffers that have a copy (start, /// bytes, true). pub(crate) fn spans() -> Vec<(u64, u64, bool)> { - let mut spans: Vec<(u64, u64, bool)> = buffers().iter().map(|(key, entry)| (key.0, entry.end - key.0, false)).collect(); + let mut spans: Vec<(u64, u64, bool)> = buffers() + .iter() + .map(|(key, entry)| (key.0, entry.end - key.0, false)) + .collect(); let loose = LOOSE.lock().unwrap_or_else(|e| e.into_inner()); spans.extend(loose.keys().map(|&(start, len)| (start, len, true))); spans @@ -3557,7 +4023,9 @@ fn lookup(address: u64, len: u64, any: bool) -> Option> { // memory, and the one just made is the CPU's side. let (buffer, card) = match card_for(size) { Some(on_card) => { - crate::host::name(&on_card, || format!("title buffer {:#x}+{len:#x} on the card", key.0)); + crate::host::name(&on_card, || { + format!("title buffer {:#x}+{len:#x} on the card", key.0) + }); tracing::info!( start = format_args!("{:#x}", key.0), len, @@ -3593,7 +4061,10 @@ fn lookup(address: u64, len: u64, any: bool) -> Option> { shadow.card = card; let shadow = Arc::new(shadow); if shadow.card.is_some() { - CARDED.lock().unwrap_or_else(|e| e.into_inner()).push(Arc::downgrade(&shadow)); + CARDED + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(Arc::downgrade(&shadow)); } entry.shadow = Some(shadow); } @@ -3623,7 +4094,9 @@ const WINDOW: u64 = 4 << 20; fn window() -> u64 { static GRID: std::sync::OnceLock = std::sync::OnceLock::new(); *GRID.get_or_init(|| { - let kb = std::env::var("VICTORY_WINDOW_KB").ok().and_then(|v| v.trim().parse::().ok()); + let kb = std::env::var("VICTORY_WINDOW_KB") + .ok() + .and_then(|v| v.trim().parse::().ok()); grid(kb) }) } @@ -3724,7 +4197,11 @@ fn cover(windows: impl Iterator) -> u64 { /// Of `windows` (start, bytes; in order), the longest tail a tail ask at /// `address` can take: the first that begins in the ask's cell at or below /// the ask's page and ends where the cell ends. -fn longest_tail(windows: impl Iterator, address: u64, end: u64) -> Option<(u64, u64)> { +fn longest_tail( + windows: impl Iterator, + address: u64, + end: u64, +) -> Option<(u64, u64)> { let (cell, len) = window_of(address, end, WINDOW); let step = address & !(TAIL_STEP - 1); windows @@ -3740,13 +4217,17 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option Option { - crate::host::name(&on_card, || format!("title memory {start:#x}+{len:#x} on the card")); + crate::host::name(&on_card, || { + format!("title memory {start:#x}+{len:#x} on the card") + }); let card = Card { staging: buffer, before: Mutex::default(), @@ -3802,7 +4285,10 @@ fn loose(address: u64, end: u64, unsized_ask: bool, any: bool) -> Option Option, u64)>)> = Mutex::new((0, BTreeMap::new())); +static EXACT: Mutex<(u64, BTreeMap<(u64, u64), (Arc, u64)>)> = + Mutex::new((0, BTreeMap::new())); /// Since the last frame line: askings for such copies, and copies made. static EXACT_STATS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2]; @@ -3855,7 +4342,9 @@ pub(crate) fn exact(address: u64, len: u64) -> Option> { // Held by the map alone (no list), its buffer by the copy alone (no // slot shows it), and not asked for lately. map.retain(|_, (shadow, used)| { - Arc::strong_count(shadow) > 1 || crate::host::references(&shadow.buffer) > 1 || *used + LATELY > now + Arc::strong_count(shadow) > 1 + || crate::host::references(&shadow.buffer) > 1 + || *used + LATELY > now }); } let (buffer, data) = host()?.shared_buffer(len.next_multiple_of(256))?; @@ -3887,8 +4376,8 @@ pub(crate) fn exact_line(frames: f64) { #[cfg(test)] mod window_tests { - use super::{WINDOW, cover, enclosing, grid, holder, longest_tail, tail_of, window_of}; use super::{BTreeMap, Entry}; + use super::{WINDOW, cover, enclosing, grid, holder, longest_tail, tail_of, window_of}; /// A big buffer is found below any number of smaller entries in it. #[test] @@ -3920,16 +4409,22 @@ mod window_tests { let (ask, end) = (cell + 0x9_0000, cell + 0xb_0000); assert_eq!(holder([].into_iter(), ask, end), None); let there = [ - (cell, 0x4_0000), // ends below the ask - (cell + 0x8_0000, 0x2_0000), // holds its first half only - (cell + 0x8_0000, 0x4_0000), // holds it + (cell, 0x4_0000), // ends below the ask + (cell + 0x8_0000, 0x2_0000), // holds its first half only + (cell + 0x8_0000, 0x4_0000), // holds it (cell + 0x4_0000, 0x10_0000), // holds it, longer (cell + 0xa_0000, 0x40_0000), // begins above it ]; - assert_eq!(holder(there.into_iter(), ask, end), Some((cell + 0x4_0000, 0x10_0000))); + assert_eq!( + holder(there.into_iter(), ask, end), + Some((cell + 0x4_0000, 0x10_0000)) + ); // Of two as long, the one that begins lower. let two = [(cell + 0x8_0000, 0x8_0000), (cell + 0x4_0000, 0x8_0000)]; - assert_eq!(holder(two.into_iter(), ask, end), Some((cell + 0x4_0000, 0x8_0000))); + assert_eq!( + holder(two.into_iter(), ask, end), + Some((cell + 0x4_0000, 0x8_0000)) + ); } /// What windows lie over counts each byte once. @@ -3954,14 +4449,20 @@ mod window_tests { fn tails_run_to_the_cells_end_and_the_longest_is_taken() { let cell = 0xd_1200_0000u64; let ask = cell + 0x12_3456; - assert_eq!(tail_of(ask, ask + 1), (cell + 0x10_0000, WINDOW - 0x10_0000)); + assert_eq!( + tail_of(ask, ask + 1), + (cell + 0x10_0000, WINDOW - 0x10_0000) + ); // The cell's first page: the whole cell, the window there always was. assert_eq!(tail_of(cell + 0xffff, cell + 0x1_0000), (cell, WINDOW)); let end = cell + WINDOW; let tail = |from: u64| (cell + from, WINDOW - from); // Nothing there, or only tails that begin above the ask. assert_eq!(longest_tail([].into_iter(), ask, ask + 1), None); - assert_eq!(longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), None); + assert_eq!( + longest_tail([tail(0x20_0000)].into_iter(), ask, ask + 1), + None + ); // The longest of those that hold the ask; windows that do not reach // the cell's end (cut on a finer grid for asks with a length) and // windows of other cells are not tails. @@ -3973,12 +4474,18 @@ mod window_tests { (cell + 0x10_0000, 0x4_0000), tail(0x20_0000), ]; - assert_eq!(longest_tail(there.into_iter(), ask, ask + 1), Some(tail(0x8_0000))); + assert_eq!( + longest_tail(there.into_iter(), ask, ask + 1), + Some(tail(0x8_0000)) + ); let (start, bytes) = tail(0x8_0000); assert!(start <= ask && start + bytes == end); // The whole cell's window is the longest tail of all. let with_whole = [(cell, WINDOW), tail(0x8_0000)]; - assert_eq!(longest_tail(with_whole.into_iter(), ask, ask + 1), Some((cell, WINDOW))); + assert_eq!( + longest_tail(with_whole.into_iter(), ask, ask + 1), + Some((cell, WINDOW)) + ); } /// The setting takes powers of two from 64 KiB to 4 MiB; anything else @@ -4002,10 +4509,16 @@ mod window_tests { let (address, end) = (0xd_1234_5678u64, 0xd_1234_5678u64 + 0x9000); assert_eq!(window_of(address, end, WINDOW), (0xd_1200_0000, 4 << 20)); assert_eq!(window_of(address, end, 1 << 20), (0xd_1230_0000, 1 << 20)); - assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 256 << 10)); + assert_eq!( + window_of(address, end, 256 << 10), + (0xd_1234_0000, 256 << 10) + ); // An ask across a grid line takes both cells. let end = address + 0x4_0000; - assert_eq!(window_of(address, end, 256 << 10), (0xd_1234_0000, 512 << 10)); + assert_eq!( + window_of(address, end, 256 << 10), + (0xd_1234_0000, 512 << 10) + ); for g in [64u64 << 10, 256 << 10, 1 << 20, WINDOW] { let (start, len) = window_of(address, end, g); assert!(start <= address && start + len >= end); @@ -4043,13 +4556,23 @@ mod card_merge_tests { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, ..Default::default() }; let mut buffer: Option = None; device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, None, &mut buffer) + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + D3D12_RESOURCE_STATE_COMMON, + None, + &mut buffer, + ) .ok()?; buffer } @@ -4080,7 +4603,13 @@ mod card_merge_tests { // The title's byte, refreshed into the CPU's side and sent up in send 7. title[title_byte] ^= 0x5a; side[title_byte] = title[title_byte]; - let mut shadow = Shadow::new(buffer.clone(), side.as_mut_ptr(), 0, title.as_ptr() as u64, LEN as u64); + let mut shadow = Shadow::new( + buffer.clone(), + side.as_mut_ptr(), + 0, + title.as_ptr() as u64, + LEN as u64, + ); shadow.card = Some(Card { staging: staging.clone(), before: Mutex::new(None), @@ -4102,8 +4631,16 @@ mod card_merge_tests { title }; let fixed = land(crate::host::fallback_fetched_mark(true, 7, Some(5))); - assert_eq!(fixed[title_byte], content[title_byte] ^ 0x5a, "the title's byte was lost"); - assert_eq!(fixed[shader_byte], content[shader_byte] ^ 0xc3, "the shader's write did not land"); + assert_eq!( + fixed[title_byte], + content[title_byte] ^ 0x5a, + "the title's byte was lost" + ); + assert_eq!( + fixed[shader_byte], + content[shader_byte] ^ 0xc3, + "the shader's write did not land" + ); // The mark at the fetch's count: the note of send 7 is gone and the // older card byte is taken for a shader's write. let before = land(7); diff --git a/crates/victory-gpu/src/spread.rs b/crates/victory-gpu/src/spread.rs new file mode 100644 index 00000000..0a27ff5e --- /dev/null +++ b/crates/victory-gpu/src/spread.rs @@ -0,0 +1,294 @@ +//! The title's crowded thread groups get more processors to run on. +//! +//! The title pins its threads as on the console: sixteen logical +//! processors of eight like cores. Measured on a 14700KF (eight fast cores +//! as logical processors 0-15, twelve efficiency cores as 16-27): eleven +//! of its threads, the ones that record lists and run its jobs, share +//! logical processors 8-12, which are two and a half fast cores; a +//! two-second sample found those five 70 to 107 % busy while fast core 7 +//! and the efficiency cores carried no pinned thread at all. The profile +//! of run 236 shows what that costs: code of the recording threads that +//! cannot wait for anything (a load of an atomic, a step in a tree) was +//! on a processor in only 58 to 72 of 100 looks, where the same kind of +//! code on the layer's unpinned submit thread was in 90 to 97. The frame +//! waits about 50 ms for those threads before the submit thread's 80. +//! +//! With `VICTORY_SPREAD=1` a group with more threads than processors may +//! also run on the processors no pinned thread of the title uses: the +//! slow cores by default (`VICTORY_SPREAD_SPARE=`: those +//! instead). The title cannot tell which processor a thread is on (it +//! imports neither `GetCurrentProcessorNumber` nor uses `rdpid`), and a +//! wider set is a place to run, not an order: the scheduler still prefers +//! the fast cores. `VICTORY_SPREAD=alt`: twenty seconds with, twenty +//! without, in turn, each change said in the log, to measure it in one +//! scene. Off by default. + +use std::collections::HashMap; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE, INVALID_HANDLE_VALUE}; +use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, +}; +use windows_sys::Win32::System::SystemInformation::GROUP_AFFINITY; +use windows_sys::Win32::System::Threading::{ + GetCurrentProcess, GetCurrentProcessId, GetProcessAffinityMask, GetThreadGroupAffinity, + OpenThread, SetThreadGroupAffinity, THREAD_QUERY_INFORMATION, THREAD_SET_INFORMATION, +}; + +/// 0 off, 1 on, 2 in turn. +fn mode() -> u8 { + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + *MODE.get_or_init(|| match std::env::var("VICTORY_SPREAD").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) +} + +/// A pinned thread of the title: the mask the title gave it and the one it +/// has from us. +struct Pinned { + original: usize, + wide: usize, +} + +/// The mask for a group of `threads` threads the title pinned to `mask`: +/// with `spare` added if they are more than its processors. +fn widened(mask: usize, threads: usize, spare: usize) -> usize { + if threads > mask.count_ones() as usize { + mask | spare + } else { + mask + } +} + +/// Whether `mask` is a pinning of the title's: some of the console's +/// sixteen logical processors, not all the processors there are. +fn console_pinning(mask: usize, all: usize) -> bool { + mask != 0 && mask != all && mask & !0xFFFF == 0 +} + +/// The ids of this process's threads. +fn threads() -> Vec { + let mut ids = Vec::new(); + // SAFETY: a snapshot handle, closed below; the entry says its own size. + unsafe { + let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if snapshot == INVALID_HANDLE_VALUE { + return ids; + } + let process = GetCurrentProcessId(); + let mut entry: THREADENTRY32 = std::mem::zeroed(); + entry.dwSize = size_of::() as u32; + let mut more = Thread32First(snapshot, &mut entry) != 0; + while more { + if entry.th32OwnerProcessID == process { + ids.push(entry.th32ThreadID); + } + more = Thread32Next(snapshot, &mut entry) != 0; + } + CloseHandle(snapshot); + } + ids +} + +/// A thread's mask in processor group 0, if it can be asked. +fn mask_of(thread: HANDLE) -> Option { + // SAFETY: plain data filled in by the query. + let mut affinity: GROUP_AFFINITY = unsafe { std::mem::zeroed() }; + // SAFETY: an open thread handle and a valid out pointer. + (unsafe { GetThreadGroupAffinity(thread, &mut affinity) } != 0 && affinity.Group == 0) + .then_some(affinity.Mask) +} + +/// One look at all threads: the title's pinned ones are noted, and each +/// gets its wide mask (`wide`) or the title's own back. +fn pass( + pinned: &mut HashMap, + all: usize, + spare: usize, + wide: bool, + said: &mut String, +) { + let ids = threads(); + pinned.retain(|id, _| ids.contains(id)); + let mut open: Vec<(u32, HANDLE, usize)> = Vec::new(); + for id in ids { + // SAFETY: a thread id of this process; the handle is closed below. + let handle = + unsafe { OpenThread(THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION, 0, id) }; + if handle.is_null() { + continue; + } + match mask_of(handle) { + Some(mask) => { + let ours = pinned + .get(&id) + .is_some_and(|p| mask == p.wide || mask == p.original); + if !ours { + if console_pinning(mask, all) { + // New, or the title pinned it again. + pinned.insert( + id, + Pinned { + original: mask, + wide: mask, + }, + ); + } else { + // Not pinned (an id used again by another thread). + pinned.remove(&id); + } + } + open.push((id, handle, mask)); + } + // SAFETY: the handle opened above. + None => unsafe { + CloseHandle(handle); + }, + } + } + let mut groups: HashMap = HashMap::new(); + for p in pinned.values() { + *groups.entry(p.original).or_default() += 1; + } + for p in pinned.values_mut() { + p.wide = widened(p.original, groups[&p.original], spare); + } + for (id, handle, mask) in open { + if let Some(p) = pinned.get(&id) { + let want = if wide { p.wide } else { p.original }; + if mask != want { + let affinity = GROUP_AFFINITY { + Mask: want, + Group: 0, + Reserved: [0; 3], + }; + // SAFETY: an open thread handle and a mask of this system's processors. + if unsafe { SetThreadGroupAffinity(handle, &affinity, std::ptr::null_mut()) } == 0 { + tracing::debug!(id, want, error = %std::io::Error::last_os_error(), "a thread's processors could not be set"); + } + } + } + // SAFETY: the handle opened above. + unsafe { CloseHandle(handle) }; + } + let mut table: Vec<(usize, usize)> = groups.into_iter().collect(); + table.sort(); + let text = table + .iter() + .map(|&(mask, threads)| { + let to = widened(mask, threads, spare); + if to == mask { + format!("{threads} on {mask:#x} ({} processors)", mask.count_ones()) + } else { + format!( + "{threads} on {mask:#x} ({} processors) -> {to:#x} ({})", + mask.count_ones(), + to.count_ones() + ) + } + }) + .collect::>() + .join("; "); + if text != *said { + tracing::info!("spread: the title's pinned threads by its mask: {text}"); + *said = text; + } +} + +/// Starts the thread that widens the title's crowded groups, if asked for. +pub(crate) fn start() { + static ONCE: std::sync::Once = std::sync::Once::new(); + if mode() == 0 { + return; + } + ONCE.call_once(|| { + let made = std::thread::Builder::new().name("victory-spread".into()).spawn(|| { + let (mut all, mut system) = (0usize, 0usize); + // SAFETY: our own process and valid out pointers. + if unsafe { GetProcessAffinityMask(GetCurrentProcess(), &mut all, &mut system) } == 0 || all == 0 { + tracing::warn!("spread: the process's processors could not be asked; nothing is widened"); + return; + } + let spare = match std::env::var("VICTORY_SPREAD_SPARE").ok().and_then(|v| usize::from_str_radix(v.trim_start_matches("0x"), 16).ok()) { + Some(mask) => mask & all, + None => crate::framelog::slow_processors() & all, + }; + if spare == 0 { + tracing::info!("spread: no spare processors (all cores are alike and VICTORY_SPREAD_SPARE names none); nothing is widened"); + return; + } + tracing::info!( + "spread: the title's thread groups with more threads than processors may also run on processors {spare:#x} (VICTORY_SPREAD=1; alt: in turn)" + ); + let epoch = std::time::Instant::now(); + let mut pinned = HashMap::new(); + let mut said = String::new(); + let mut last = None; + loop { + let wide = mode() == 1 || (epoch.elapsed().as_secs() / 20) % 2 == 1; + if mode() == 2 && last != Some(wide) { + tracing::info!( + "the title's crowded thread groups run on more processors from now (VICTORY_SPREAD=alt): {}", + if wide { "ON" } else { "off, as usual" } + ); + } + last = Some(wide); + pass(&mut pinned, all, spare, wide, &mut said); + // Often enough to catch threads the title starts and to turn with the + // twenty-second phases; a pass is a snapshot and a query a thread. + std::thread::sleep(std::time::Duration::from_millis(500)); + } + }); + if let Err(error) = made { + tracing::warn!(%error, "the spread thread could not be started"); + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn only_crowded_groups_are_widened() { + let spare = 0x0FFF_0000; + // eleven threads on five processors: crowded + assert_eq!(widened(0x1F00, 11, spare), 0x0FFF_1F00); + // eight on eight, three on six, one on one: left alone + assert_eq!(widened(0xFF, 8, spare), 0xFF); + assert_eq!(widened(0x3F00, 3, spare), 0x3F00); + assert_eq!(widened(0x2000, 1, spare), 0x2000); + assert_eq!(widened(0x3FFF, 11, spare), 0x3FFF); + assert_eq!(widened(0x3FFF, 15, spare), 0x0FFF_3FFF); + } + + #[test] + fn a_pinning_of_the_title_is_within_the_console_s_sixteen() { + let all = 0x0FFF_FFFF; + assert!(console_pinning(0x1F00, all)); + assert!(console_pinning(0xFFFF, all)); + assert!(!console_pinning(all, all), "not pinned"); + assert!( + !console_pinning(0x0FFF_1F00, all), + "already wide: not the title's" + ); + assert!(!console_pinning(0, all)); + // a PC with sixteen processors: all of them is not a pinning + assert!(!console_pinning(0xFFFF, 0xFFFF)); + } + + #[test] + fn this_process_has_threads_and_they_have_masks() { + let ids = threads(); + assert!(!ids.is_empty()); + // SAFETY: a thread id of this process. + let handle = + unsafe { OpenThread(THREAD_QUERY_INFORMATION | THREAD_SET_INFORMATION, 0, ids[0]) }; + assert!(!handle.is_null()); + assert!(mask_of(handle).is_some_and(|m| m != 0)); + // SAFETY: the handle opened above. + unsafe { CloseHandle(handle) }; + } +} diff --git a/crates/victory-gpu/src/tiles.rs b/crates/victory-gpu/src/tiles.rs index 6d3c3d8d..0f405004 100644 --- a/crates/victory-gpu/src/tiles.rs +++ b/crates/victory-gpu/src/tiles.rs @@ -156,7 +156,9 @@ fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u3 return None; } let mut pool = POOL.lock().unwrap_or_else(|e| e.into_inner()); - let found = pool.iter().position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count)); + let found = pool + .iter() + .position(|h| h.as_ref().is_some_and(|h| h.free_tiles() >= count)); let index = match found { Some(index) => index, None => { @@ -171,7 +173,9 @@ fn take(device: &ID3D12Device, count: u32) -> Option<(ID3D12Heap, usize, Vec<(u3 }; let mut made: Option = None; // SAFETY: plain creation; the out pointer is ours. - if let Err(e) = unsafe { device.CreateHeap::(&raw const desc, &raw mut made) } { + if let Err(e) = + unsafe { device.CreateHeap::(&raw const desc, &raw mut made) } + { tracing::warn!(error = %e, "no heap for texture levels given on demand: those levels stay empty"); return None; } @@ -278,7 +282,11 @@ impl Tiled { /// layer: how the card cuts it into tiles. `None` if the card will not /// say, or cuts it in a way this does not handle; the caller then makes /// the texture the old way. - pub(crate) fn make(device: &ID3D12Device, texture: &ID3D12Resource, levels: u32) -> Option { + pub(crate) fn make( + device: &ID3D12Device, + texture: &ID3D12Resource, + levels: u32, + ) -> Option { if levels == 0 || levels > 16 { return None; } @@ -300,7 +308,10 @@ impl Tiled { ); } let standard_levels = u32::from(packed.NumStandardMips); - if total == 0 || standard_levels + u32::from(packed.NumPackedMips) != levels || standard_levels > count { + if total == 0 + || standard_levels + u32::from(packed.NumPackedMips) != levels + || standard_levels > count + { return None; } let mut standard = Vec::with_capacity(standard_levels as usize); @@ -310,12 +321,19 @@ impl Tiled { .checked_mul(u32::from(tiling.HeightInTiles)) .and_then(|n| n.checked_mul(u32::from(tiling.DepthInTiles))) .unwrap_or(0); - if tiles == 0 || tiles > HEAP_TILES || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE { + if tiles == 0 + || tiles > HEAP_TILES + || tiling.StartTileIndexInOverallResource == D3D12_PACKED_TILE + { return None; } standard.push(tiles); } - let packed_tiles = if packed.NumPackedMips > 0 { packed.NumTilesForPackedMips } else { 0 }; + let packed_tiles = if packed.NumPackedMips > 0 { + packed.NumTilesForPackedMips + } else { + 0 + }; if (packed.NumPackedMips > 0 && packed_tiles == 0) || packed_tiles > HEAP_TILES { return None; } @@ -378,7 +396,14 @@ impl Tiled { let named = held | card; // The levels the card itself writes are few and are not kept // waiting: a write of the card's into no memory is lost. - let changed = self.give_locked(&mut given, queue, device, texture, named, if room { named } else { card }); + let changed = self.give_locked( + &mut given, + queue, + device, + texture, + named, + if room { named } else { card }, + ); let missing = self.without_locked(&given, named) != 0; (changed, missing) } @@ -474,7 +499,11 @@ impl Tiled { let first_packed = self.standard.len() as u32; let mut without = 0; for level in 0..self.levels.min(32) { - let has = if level < first_packed { given.levels[level as usize] } else { given.packed }; + let has = if level < first_packed { + given.levels[level as usize] + } else { + given.packed + }; if !has { without |= 1 << level; } @@ -586,7 +615,9 @@ impl Tiled { given.packed } }; - let shown = (0..self.levels).find(|&level| has(level) && with_tiles(level)).unwrap_or(u32::MAX); + let shown = (0..self.levels) + .find(|&level| has(level) && with_tiles(level)) + .unwrap_or(u32::MAX); self.shown.swap(shown, Ordering::Relaxed) != shown } @@ -617,7 +648,11 @@ impl Tiled { /// A bit for every level of the texture. pub(crate) fn every_level(&self) -> u32 { - if self.levels >= 32 { u32::MAX } else { (1 << self.levels) - 1 } + if self.levels >= 32 { + u32::MAX + } else { + (1 << self.levels) - 1 + } } /// The bytes of the tiles it has now. @@ -631,7 +666,8 @@ impl Drop for Tiled { fn drop(&mut self) { let given = self.given.get_mut().unwrap_or_else(|e| e.into_inner()); let mut bytes = 0; - let mut by_heap: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + let mut by_heap: std::collections::BTreeMap> = + std::collections::BTreeMap::new(); for &(index, start, tiles) in &given.runs { by_heap.entry(index).or_default().push((start, tiles)); bytes += u64::from(tiles) * TILE; @@ -671,12 +707,20 @@ pub(crate) fn show_from(desc: &mut D3D12_SHADER_RESOURCE_VIEW_DESC, first: u32, D3D12_SRV_DIMENSION_TEXTURE2D => { // SAFETY: `ViewDimension` selects `Texture2D`. let view = unsafe { &mut desc.Anonymous.Texture2D }; - clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + clamp( + &mut view.MostDetailedMip, + &mut view.MipLevels, + &mut view.ResourceMinLODClamp, + ); } D3D12_SRV_DIMENSION_TEXTURE2DARRAY => { // SAFETY: `ViewDimension` selects `Texture2DArray`. let view = unsafe { &mut desc.Anonymous.Texture2DArray }; - clamp(&mut view.MostDetailedMip, &mut view.MipLevels, &mut view.ResourceMinLODClamp); + clamp( + &mut view.MostDetailedMip, + &mut view.MipLevels, + &mut view.ResourceMinLODClamp, + ); } _ => {} } @@ -805,7 +849,9 @@ void look() { let layered = D3D12GetDebugInterface(&mut layer).is_ok() && layer.is_some(); layer.iter().for_each(|l| l.EnableDebugLayer()); if card && !layered { - eprintln!("no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it"); + eprintln!( + "no D3D12 debug layer (Windows optional feature \"Graphics Tools\"): not run on the card without it" + ); return None; } let mut device: Option = None; @@ -827,9 +873,17 @@ void look() { .ok()?; eprintln!( "levels on demand, {}: tiled resources tier {}, debug layer {}", - if card { "ON THE CARD" } else { "on the software adapter" }, + if card { + "ON THE CARD" + } else { + "on the software adapter" + }, options.TiledResourcesTier.0, - if messages.is_some() { "on" } else { "not installed" } + if messages.is_some() { + "on" + } else { + "not installed" + } ); if options.TiledResourcesTier.0 < 2 { return None; @@ -840,8 +894,9 @@ void look() { ..Default::default() }) .ok()?; - let allocator: ID3D12CommandAllocator = - device.CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT).ok()?; + let allocator: ID3D12CommandAllocator = device + .CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT) + .ok()?; let list: ID3D12GraphicsCommandList = device .CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, &allocator, None) .ok()?; @@ -879,10 +934,14 @@ void look() { let message = buffer.as_mut_ptr().cast::(); if queue.GetMessage(i, Some(message), &mut size).is_ok() { let m = &*message; - let text = std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); + let text = + std::slice::from_raw_parts(m.pDescription, m.DescriptionByteLength); let text = String::from_utf8_lossy(text); let text = text.trim_end_matches('\0'); - eprintln!("D3D12 says (severity {}, id {}): {text}", m.Severity.0, m.ID.0); + eprintln!( + "D3D12 says (severity {}, id {}): {text}", + m.Severity.0, m.ID.0 + ); if m.Severity.0 <= D3D12_MESSAGE_SEVERITY_ERROR.0 && first_error.is_none() { first_error = Some(text.to_owned()); } @@ -899,8 +958,17 @@ void look() { let error = self.said(); // SAFETY: a plain query. let removed = unsafe { self.device.GetDeviceRemovedReason() }; - assert!(removed.is_ok(), "{}, {what}: the device is lost: {removed:?}", self.step); - assert!(error.is_none(), "{}, {what}: the debug layer reports an error: {}", self.step, error.unwrap_or_default()); + assert!( + removed.is_ok(), + "{}, {what}: the device is lost: {removed:?}", + self.step + ); + assert!( + error.is_none(), + "{}, {what}: the debug layer reports an error: {}", + self.step, + error.unwrap_or_default() + ); } /// Gives tiles as a submission would, and stops if the mapping @@ -923,7 +991,9 @@ void look() { let run: ID3D12CommandList = self.list.cast().unwrap(); self.queue.ExecuteCommandLists(&[Some(run)]); self.queue.Signal(&self.fence, self.submitted).unwrap(); - self.fence.SetEventOnCompletion(self.submitted, self.event).unwrap(); + self.fence + .SetEventOnCompletion(self.submitted, self.event) + .unwrap(); // Never without end: a step is a few copies of a few // megabytes. On the card the limit stays under Windows' own // two seconds; the software adapter, which compiles its @@ -941,7 +1011,13 @@ void look() { } } - fn buffer(&self, kind: D3D12_HEAP_TYPE, flags: D3D12_RESOURCE_FLAGS, state: D3D12_RESOURCE_STATES, bytes: u64) -> ID3D12Resource { + fn buffer( + &self, + kind: D3D12_HEAP_TYPE, + flags: D3D12_RESOURCE_FLAGS, + state: D3D12_RESOURCE_STATES, + bytes: u64, + ) -> ID3D12Resource { let heap = D3D12_HEAP_PROPERTIES { Type: kind, ..Default::default() @@ -952,7 +1028,10 @@ void look() { Height: 1, DepthOrArraySize: 1, MipLevels: 1, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, Layout: D3D12_TEXTURE_LAYOUT_ROW_MAJOR, Flags: flags, ..Default::default() @@ -961,7 +1040,14 @@ void look() { // SAFETY: plain buffer creation. unsafe { self.device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, state, None, &mut out) + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &desc, + state, + None, + &mut out, + ) .unwrap(); } out.unwrap() @@ -970,7 +1056,12 @@ void look() { /// A square texture description of `side` texels and `levels` /// levels; `reserved`: in the layout a texture without memory of /// its own must have. - fn desc(format: DXGI_FORMAT, side: u32, levels: u16, reserved: bool) -> D3D12_RESOURCE_DESC { + fn desc( + format: DXGI_FORMAT, + side: u32, + levels: u16, + reserved: bool, + ) -> D3D12_RESOURCE_DESC { D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: u64::from(side), @@ -978,8 +1069,15 @@ void look() { DepthOrArraySize: 1, MipLevels: levels, Format: format, - SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 }, - Layout: if reserved { D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE } else { D3D12_TEXTURE_LAYOUT_UNKNOWN }, + SampleDesc: DXGI_SAMPLE_DESC { + Count: 1, + Quality: 0, + }, + Layout: if reserved { + D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE + } else { + D3D12_TEXTURE_LAYOUT_UNKNOWN + }, ..Default::default() } } @@ -990,14 +1088,19 @@ void look() { let mut made: Option = None; // SAFETY: plain creation; a texture that is no target has no clear value. let asked = unsafe { - self.device - .CreateReservedResource(desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + self.device.CreateReservedResource( + desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut made, + ) }; // The layer's reason first, if it refused. self.check("a texture without memory made"); asked.expect("a reserved texture"); let texture = made.expect("a reserved texture"); - let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)).expect("the card says how it cuts the texture"); + let tiled = Tiled::make(&self.device, &texture, u32::from(desc.MipLevels)) + .expect("the card says how it cuts the texture"); (texture, tiled) } @@ -1032,14 +1135,20 @@ void look() { /// level are `byte(level)`. fn filled(&self, layout: &Laid, byte: impl Fn(usize) -> u8) -> ID3D12Resource { let (footprints, rows) = (&layout.footprints, &layout.rows); - let upload = self.buffer(D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_GENERIC_READ, layout.total); + let upload = self.buffer( + D3D12_HEAP_TYPE_UPLOAD, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_GENERIC_READ, + layout.total, + ); // SAFETY: the buffer is `total` bytes; each level's rows lie inside it. unsafe { let mut data = std::ptr::null_mut(); upload.Map(0, None, Some(&mut data)).unwrap(); for (level, f) in footprints.iter().enumerate() { let len = rows[level] as usize * f.Footprint.RowPitch as usize; - std::slice::from_raw_parts_mut(data.cast::().add(f.Offset as usize), len).fill(byte(level)); + std::slice::from_raw_parts_mut(data.cast::().add(f.Offset as usize), len) + .fill(byte(level)); } upload.Unmap(0, None); } @@ -1057,20 +1166,47 @@ void look() { upload: Option<&ID3D12Resource>, ) -> Vec<[Vec; 2]> { let (footprints, rows) = (&layout.footprints, &layout.rows); - let back = self.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, layout.total); + let back = self.buffer( + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + layout.total, + ); self.run(|list| { // SAFETY: an open list; the texture and buffers outlive the run. unsafe { if let Some(upload) = upload { for (level, f) in footprints.iter().enumerate() { - list.CopyTextureRegion(&sub(texture, level as u32), 0, 0, 0, &placed(upload, *f), None); + list.CopyTextureRegion( + &sub(texture, level as u32), + 0, + 0, + 0, + &placed(upload, *f), + None, + ); } } - list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.ResourceBarrier(&[transition( + texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); for (level, f) in footprints.iter().enumerate() { - list.CopyTextureRegion(&placed(&back, *f), 0, 0, 0, &sub(texture, level as u32), None); + list.CopyTextureRegion( + &placed(&back, *f), + 0, + 0, + 0, + &sub(texture, level as u32), + None, + ); } - list.ResourceBarrier(&[transition(texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST)]); + list.ResourceBarrier(&[transition( + texture, + D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_COPY_DEST, + )]); } }); let mut read = Vec::new(); @@ -1081,7 +1217,10 @@ void look() { for (level, f) in footprints.iter().enumerate() { let pitch = f.Footprint.RowPitch as usize; let len = rows[level] as usize * pitch; - let bytes = std::slice::from_raw_parts(data.cast::().cast_const().add(f.Offset as usize), len); + let bytes = std::slice::from_raw_parts( + data.cast::().cast_const().add(f.Offset as usize), + len, + ); // The bytes of a row that are the level's own (its // blocks or texels; the rest of the pitch is padding). let own = layout.wide[level] as usize; @@ -1106,16 +1245,23 @@ void look() { // SAFETY: a borrowed pointer the location never releases. pResource: unsafe { std::mem::transmute_copy(texture) }, Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { SubresourceIndex: index }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + SubresourceIndex: index, + }, } } - fn placed(buffer: &ID3D12Resource, footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT) -> D3D12_TEXTURE_COPY_LOCATION { + fn placed( + buffer: &ID3D12Resource, + footprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT, + ) -> D3D12_TEXTURE_COPY_LOCATION { D3D12_TEXTURE_COPY_LOCATION { // SAFETY: as above. pResource: unsafe { std::mem::transmute_copy(buffer) }, Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, - Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { PlacedFootprint: footprint }, + Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 { + PlacedFootprint: footprint, + }, } } @@ -1131,7 +1277,11 @@ void look() { /// (i) Levels arrive one by one: after each step every level with /// tiles reads back its own bytes and every level without reads zeros. fn levels_arrive(rig: &mut Rig, format: DXGI_FORMAT) { - rig.step = if format == DXGI_FORMAT_BC7_UNORM { "step 1, levels arrive (BC7)" } else { "step 1, levels arrive (BC3)" }; + rig.step = if format == DXGI_FORMAT_BC7_UNORM { + "step 1, levels arrive (BC7)" + } else { + "step 1, levels arrive (BC3)" + }; let desc = Rig::desc(format, SIDE, LEVELS, true); let (texture, tiled) = rig.reserved(&desc); // (The card packs the levels smaller than a tile into shared @@ -1143,7 +1293,10 @@ void look() { tiled.standard, tiled.packed ); - assert!(!rig.card || tiled.packed > 0, "on the card a 1024 texture has levels smaller than a tile"); + assert!( + !rig.card || tiled.packed > 0, + "on the card a 1024 texture has levels smaller than a tile" + ); let layout = rig.footprints(&desc); let upload = rig.filled(&layout, |level| level as u8 + 1); for first in [3u32, 1, 0] { @@ -1151,8 +1304,16 @@ void look() { rig.give(&tiled, &texture, from_level(first)); let read = rig.round_trip(&texture, &layout, Some(&upload)); for (level, bytes) in read.iter().enumerate() { - let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; - assert!(all(bytes, want), "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", format.0); + let want = if tiled.has_tiles(level as u32) { + level as u8 + 1 + } else { + 0 + }; + assert!( + all(bytes, want), + "format {} from level {first}: level {level} reads {bytes:?}, wanted {want}", + format.0 + ); } } assert!(tiled.whole()); @@ -1181,31 +1342,59 @@ void look() { // SAFETY: plain texture creation. unsafe { rig.device - .CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &source_desc, D3D12_RESOURCE_STATE_COPY_DEST, None, &mut made) + .CreateCommittedResource( + &heap, + D3D12_HEAP_FLAG_NONE, + &source_desc, + D3D12_RESOURCE_STATE_COPY_DEST, + None, + &mut made, + ) .unwrap(); } let source = made.unwrap(); rig.run(|list| { // SAFETY: an open list and live resources. unsafe { - list.CopyTextureRegion(&sub(&source, 0), 0, 0, 0, &placed(&source_bytes, source_layout.footprints[0]), None); - list.ResourceBarrier(&[transition(&source, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.CopyTextureRegion( + &sub(&source, 0), + 0, + 0, + 0, + &placed(&source_bytes, source_layout.footprints[0]), + None, + ); + list.ResourceBarrier(&[transition( + &source, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); // No tiles yet: this copy goes nowhere. list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None); } }); let before = rig.round_trip(&texture, &layout, None); - assert!(all(&before[level as usize], 0), "a copy into a level without tiles left {:?}", before[level as usize]); + assert!( + all(&before[level as usize], 0), + "a copy into a level without tiles left {:?}", + before[level as usize] + ); // As `texture.rs` `card_writes` has it: the give at the list's // submission, the copy in the list. assert_ne!(tiled.claim(tiled.with_level(level)), 0, "the level is new"); rig.give(&tiled, &texture, tiled.with_level(level)); rig.run(|list| { // SAFETY: as above. - unsafe { list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) }; + unsafe { + list.CopyTextureRegion(&sub(&texture, level), 0, 0, 0, &sub(&source, 0), None) + }; }); let after = rig.round_trip(&texture, &layout, None); - assert!(all(&after[level as usize], 0x5a), "the copy after the give left {:?}", after[level as usize]); + assert!( + all(&after[level as usize], 0x5a), + "the copy after the give left {:?}", + after[level as usize] + ); assert_eq!(tiled.claim(tiled.with_level(level)), 0, "claimed once"); } @@ -1236,8 +1425,16 @@ void look() { ); let upload = rig.filled(&layout, |_| 0x3c); let read = rig.round_trip(&second, &layout, Some(&upload)); - assert!(all(&read[level as usize], 0x3c), "the reused level reads {:?}", read[level as usize]); - assert!(all(&read[0], 0), "level 0 has no tiles and reads {:?}", read[0]); + assert!( + all(&read[level as usize], 0x3c), + "the reused level reads {:?}", + read[level as usize] + ); + assert!( + all(&read[0], 0), + "level 0 has no tiles and reads {:?}", + read[0] + ); } /// (iv) A level whose tiles come from several runs of the heap (single @@ -1246,7 +1443,9 @@ void look() { rig.step = "step 4, a level on several ranges of the heap"; // Three single tiles; the first and the last go back, the middle // one stays taken. - let singles: Vec<_> = (0..3).map(|_| take(&rig.device, 1).expect("a tile")).collect(); + let singles: Vec<_> = (0..3) + .map(|_| take(&rig.device, 1).expect("a tile")) + .collect(); give_back(singles[0].1, &singles[0].2); give_back(singles[2].1, &singles[2].2); let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); @@ -1256,7 +1455,10 @@ void look() { assert!(tiled.standard.len() > 1 && tiled.standard[1] >= 2); rig.give(&tiled, &texture, 1 << 1); let runs = tiled.given.lock().unwrap().runs.len(); - eprintln!("level 1 ({} tiles) was mapped on {runs} ranges", tiled.standard[1]); + eprintln!( + "level 1 ({} tiles) was mapped on {runs} ranges", + tiled.standard[1] + ); assert!(runs >= 2, "the single free tiles were not used first"); let upload = rig.filled(&layout, |_| 0x77); let read = rig.round_trip(&texture, &layout, Some(&upload)); @@ -1320,18 +1522,28 @@ void look() { let mut shown = as_asked; show_from(&mut shown, tiled.first_shown()?, u32::from(LEVELS)); assert_eq!(shown.Anonymous.Texture2D.MostDetailedMip, 1); - let step = rig.device.GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) as usize; + let step = rig + .device + .GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) + as usize; let mut at = views.GetCPUDescriptorHandleForHeapStart(); - rig.device.CreateShaderResourceView(&texture, Some(&raw const shown), at); + rig.device + .CreateShaderResourceView(&texture, Some(&raw const shown), at); at.ptr += step; - rig.device.CreateShaderResourceView(&texture, Some(&raw const as_asked), at); + rig.device + .CreateShaderResourceView(&texture, Some(&raw const as_asked), at); let words = rig.buffer( D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, 256, ); - let back = rig.buffer(D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_FLAG_NONE, D3D12_RESOURCE_STATE_COPY_DEST, 256); + let back = rig.buffer( + D3D12_HEAP_TYPE_READBACK, + D3D12_RESOURCE_FLAG_NONE, + D3D12_RESOURCE_STATE_COPY_DEST, + 256, + ); (root, pipeline, views, words, back) }; // Before the one dispatch: the pipeline and both views are sound. @@ -1339,14 +1551,22 @@ void look() { rig.run(|list| { // SAFETY: an open list and live objects. unsafe { - list.ResourceBarrier(&[transition(&texture, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE)]); + list.ResourceBarrier(&[transition( + &texture, + D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE, + )]); list.SetDescriptorHeaps(&[Some(views.clone())]); list.SetComputeRootSignature(&root); list.SetPipelineState(&pipeline); list.SetComputeRootDescriptorTable(0, views.GetGPUDescriptorHandleForHeapStart()); list.SetComputeRootUnorderedAccessView(1, words.GetGPUVirtualAddress()); list.Dispatch(1, 1, 1); - list.ResourceBarrier(&[transition(&words, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE)]); + list.ResourceBarrier(&[transition( + &words, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, + D3D12_RESOURCE_STATE_COPY_SOURCE, + )]); list.CopyBufferRegion(&back, 0, &words, 0, 16); } }); @@ -1359,14 +1579,24 @@ void look() { back.Unmap(0, None); read }; - eprintln!("a sample at level 0: {} through the view from level 1, {} through the view as asked", read[0], read[1]); - assert_eq!(read[0], 32, "the view from the first level with tiles reads level 1"); - assert_eq!(read[1], 0, "the view from level 0 reads a level without tiles"); + eprintln!( + "a sample at level 0: {} through the view from level 1, {} through the view as asked", + read[0], read[1] + ); + assert_eq!( + read[0], 32, + "the view from the first level with tiles reads level 1" + ); + assert_eq!( + read[1], 0, + "the view from level 0 reads a level without tiles" + ); Some(()) } fn a_full_card_keeps_new_levels_waiting(rig: &mut Rig) { - rig.step = "step 6, no room on the card: held levels wait, and get their tiles when asked again"; + rig.step = + "step 6, no room on the card: held levels wait, and get their tiles when asked again"; let desc = Rig::desc(DXGI_FORMAT_BC7_UNORM, SIDE, LEVELS, true); let (texture, tiled) = rig.reserved(&desc); let layout = rig.footprints(&desc); @@ -1374,31 +1604,50 @@ void look() { let read_as_given = |rig: &mut Rig, what: &str| { let read = rig.round_trip(&texture, &layout, Some(&upload)); for (level, bytes) in read.iter().enumerate() { - let want = if tiled.has_tiles(level as u32) { level as u8 + 1 } else { 0 }; - assert!(all(bytes, want), "{what}: level {level} reads {bytes:?}, wanted {want}"); + let want = if tiled.has_tiles(level as u32) { + level as u8 + 1 + } else { + 0 + }; + assert!( + all(bytes, want), + "{what}: level {level} reads {bytes:?}, wanted {want}" + ); } }; // No room: nothing is given, the held levels are said to wait, // nothing is shown, every level reads zeros. - let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false); + let (changed, waiting) = + tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), false); rig.check("an upload without room"); - assert!(!changed && waiting, "without room: changed {changed}, waiting {waiting}"); + assert!( + !changed && waiting, + "without room: changed {changed}, waiting {waiting}" + ); assert_eq!(tiled.given_bytes(), 0, "without room no tile is given"); assert_eq!(tiled.first_shown(), None); read_as_given(rig, "without room"); // Asked again with room: the same levels get theirs. - let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true); + let (changed, waiting) = + tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(3), true); rig.check("the upload again, with room"); - assert!(changed && !waiting, "with room: changed {changed}, waiting {waiting}"); + assert!( + changed && !waiting, + "with room: changed {changed}, waiting {waiting}" + ); assert!(tiled.has_tiles(3) && !tiled.has_tiles(2)); assert_eq!(tiled.first_shown(), Some(3)); read_as_given(rig, "with room"); // More levels held and no room again: the ones that have tiles // are brought up to date, the new ones wait, the view stays. let before = tiled.given_bytes(); - let (changed, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false); + let (changed, waiting) = + tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), false); rig.check("more levels held, without room"); - assert!(!changed && waiting, "more levels without room: changed {changed}, waiting {waiting}"); + assert!( + !changed && waiting, + "more levels without room: changed {changed}, waiting {waiting}" + ); assert_eq!(tiled.given_bytes(), before); assert_eq!(tiled.first_shown(), Some(3)); read_as_given(rig, "more levels without room"); @@ -1409,9 +1658,14 @@ void look() { rig.check("the card's own write, without room"); assert!(changed && tiled.has_tiles(0) && !tiled.has_tiles(1) && !tiled.has_tiles(2)); assert_eq!(tiled.first_shown(), Some(0)); - assert_eq!(tiled.claim(1 << 0), 0, "a level with tiles is not claimed again"); + assert_eq!( + tiled.claim(1 << 0), + 0, + "a level with tiles is not claimed again" + ); // With room everything held gets its tiles. - let (_, waiting) = tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true); + let (_, waiting) = + tiled.uploaded_on(&rig.queue, &rig.device, &texture, from_level(1), true); rig.check("the last upload, with room"); assert!(!waiting && tiled.whole()); read_as_given(rig, "everything given"); @@ -1426,11 +1680,21 @@ void look() { assert_eq!(tiled.claim(level), 0, "claimed once"); // The list that claimed it was reset without being submitted. tiled.unclaim(level); - assert_eq!(tiled.claim(level), level, "claimed again after it was given up"); + assert_eq!( + tiled.claim(level), + level, + "claimed again after it was given up" + ); // The small levels the card packs together are claimed together. let small = tiled.with_level(u32::from(LEVELS) - 1); - assert!(!rig.card || small.count_ones() > 1, "on the card a 1024 texture has several levels in one tile"); - assert_eq!(tiled.claim(1 << (u32::from(LEVELS) - 1)), 1 << (u32::from(LEVELS) - 1)); + assert!( + !rig.card || small.count_ones() > 1, + "on the card a 1024 texture has several levels in one tile" + ); + assert_eq!( + tiled.claim(1 << (u32::from(LEVELS) - 1)), + 1 << (u32::from(LEVELS) - 1) + ); tiled.unclaim(small); assert_eq!(tiled.claim(small), small); } @@ -1440,7 +1704,9 @@ void look() { #[ignore = "on the card: run it by name with --ignored --nocapture"] fn levels_on_demand_on_the_card() { let Some(mut rig) = Rig::new() else { - eprintln!("no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped"); + eprintln!( + "no adapter with tiled resources of tier 2, or no debug layer for a run on the card; skipped" + ); return; }; rig.check("the device made"); @@ -1458,7 +1724,11 @@ void look() { rig.check("every step done"); eprintln!( "all steps passed {}", - if rig.card { "ON THE CARD" } else { "on the software adapter; VICTORY_TILES_TEST_CARD=1 is the run on the card" } + if rig.card { + "ON THE CARD" + } else { + "on the software adapter; VICTORY_TILES_TEST_CARD=1 is the run on the card" + } ); let s: Vec = STATS.iter().map(|s| s.load(Ordering::Relaxed)).collect(); eprintln!( @@ -1573,9 +1843,17 @@ void look() { assert_eq!(tiled.claim(1 << 0), 1 << 0); let changed = tiled.card_wrote_on(host.queue(), &host.device, &tex, 1 << 0); assert!(!changed); - assert_eq!(tiled.card.load(Ordering::Relaxed), 0, "failed tile allocation must not poison `card`"); + assert_eq!( + tiled.card.load(Ordering::Relaxed), + 0, + "failed tile allocation must not poison `card`" + ); assert_eq!(tiled.first_shown(), None); - assert_eq!(tiled.claim(1 << 0), 1 << 0, "failed level must be unclaimed"); + assert_eq!( + tiled.claim(1 << 0), + 1 << 0, + "failed level must be unclaimed" + ); // Even if level 0 later becomes allocatable, an upload with `room == false` // that does not hold level 0 must not treat level 0 as card-owned. tiled.standard[0] = 1; diff --git a/crates/victory-gpu/src/watch.rs b/crates/victory-gpu/src/watch.rs index 2442bc1a..78d4f9f0 100644 --- a/crates/victory-gpu/src/watch.rs +++ b/crates/victory-gpu/src/watch.rs @@ -192,7 +192,6 @@ fn allocation(at: usize) -> Option { Some(r) } - /// Ranges of one submission closer than this are asked about together: /// walking the pages between them costs less than another kernel call (a /// call that resets written pages costs 30-70 microseconds whatever the @@ -234,7 +233,10 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { let all = pieces.len(); pieces.retain(|&(first, _)| !known_view(first * PAGE)); #[cfg(feature = "diagnostics")] - AHEAD_VIEWS.fetch_add((all - pieces.len()) as u64, std::sync::atomic::Ordering::Relaxed); + AHEAD_VIEWS.fetch_add( + (all - pieces.len()) as u64, + std::sync::atomic::Ordering::Relaxed, + ); j.asked += 1; j.ahead_asked = j.asked; j.ahead.clear(); @@ -262,7 +264,8 @@ pub(crate) fn ask_ahead(ranges: &[(usize, usize)]) { /// heap's views ran long, 25-50 ms in the others. These numbers say /// whether a few askings wait for something or all of them are slow. #[cfg(feature = "diagnostics")] -static SLOW: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +static SLOW: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; #[cfg(feature = "diagnostics")] fn slow(us: u64) { @@ -488,7 +491,15 @@ pub(crate) fn asked(start: usize, end: usize) -> Option<(u64, Vec<(usize, u64)>) j.ahead .iter() .any(|&(a, b)| a <= first && last <= b) - .then(|| (j.ahead_asked, j.written.range(first..last).map(|(&p, &w)| (p, w)).collect())) + .then(|| { + ( + j.ahead_asked, + j.written + .range(first..last) + .map(|(&p, &w)| (p, w)) + .collect(), + ) + }) } /// The pages of `[start, end)` (whole pages) as last written, for pages @@ -575,6 +586,10 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve }, failed as u64, ); + #[cfg(feature = "diagnostics")] + if failed && !known_view && guarded { + failed_asking(first * PAGE, last * PAGE); + } let guarded = if failed { count = 0; if !guarded { @@ -584,7 +599,10 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve let guarding = std::time::Instant::now(); let written = guard(first * PAGE, last * PAGE, mapped); #[cfg(feature = "diagnostics")] - crate::copystat::add(crate::copystat::C::GuardUs, guarding.elapsed().as_micros() as u64); + crate::copystat::add( + crate::copystat::C::GuardUs, + guarding.elapsed().as_micros() as u64, + ); written? } else { Vec::new() @@ -621,6 +639,46 @@ pub(crate) fn writes(start: usize, end: usize, guarded: bool) -> Option<(u64, Ve )) } +/// Diagnostics: one in 2,048 of the askings the kernel's write watch +/// refused for memory the guards did not know (some 200 a frame in the +/// first rooms, each followed by a question to Windows about the memory): +/// what the memory is and what the guards hold of its first block. +#[cfg(feature = "diagnostics")] +fn failed_asking(start: usize, end: usize) { + use windows_sys::Win32::System::Memory::{MEMORY_BASIC_INFORMATION, VirtualQuery}; + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if !N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(2048) { + return; + } + // SAFETY: plain data filled in by the query. + let mut info: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: a valid out pointer of the right size. + let n = unsafe { VirtualQuery(start as *const _, &mut info, size_of_val(&info)) }; + let (protected, clean, absent, viewed, aliased) = { + let g = guards(); + let b = start / BLOCK; + ( + g.protected.contains(&b), + g.clean.contains(&b), + g.absent.contains(&b), + g.viewed.contains(&b), + g.aliased.contains(&b), + ) + }; + tracing::info!( + "a failed write-watch asking (one in 2048): {start:#x}+{:#x}; Windows says (answered {n}): base {:#x} region {:#x} state {:#x} type {:#x} protect {:#x} allocation protect {:#x}; \ + the guards of its first block: protected {protected} clean {clean} absent {absent} viewed {viewed} aliased {aliased}; is a view: {}", + end - start, + info.BaseAddress as usize, + info.RegionSize, + info.State, + info.Type, + info.Protect, + info.AllocationProtect, + is_view(start, end) + ); +} + impl Tracked { /// Takes changed pages of `[from, to)`, cut to the tracked range. A /// partial page stays changed so a later take can read its other bytes. @@ -643,9 +701,7 @@ impl Tracked { continue; } // Keep partial pages dirty: the caller has not taken the rest. - if (page * PAGE).max(self.start) >= from - && ((page + 1) * PAGE).min(self.end) <= to - { + if (page * PAGE).max(self.start) >= from && ((page + 1) * PAGE).min(self.end) <= to { seen.insert(page, write); } match ranges.last_mut() { @@ -660,7 +716,6 @@ impl Tracked { /// Guarded blocks of view memory. const BLOCK: usize = PAGE; - /// Whether the diagnostic switches ask the kernel even for memory known to /// be unwatchable (`VICTORY_VIEW_ASK=1` or `VICTORY_GUARD_ASK=1`). fn ask_anyway() -> bool { @@ -688,7 +743,9 @@ fn known_view(start: usize) -> bool { } let g = guards(); let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) + g.protected.contains(&first) + || g.absent.contains(&first) + || (view_known() && g.viewed.contains(&first)) } struct Guards { @@ -721,9 +778,39 @@ struct Guards { /// submitting thread in `VirtualQuery`. With the switch the block is /// remembered from the time it was first made read-only until the runtime /// maps or unmaps it ([`title_memory_remapped`]). +/// +/// `VICTORY_VIEW_KNOWN=alt`: twenty seconds with, twenty without, in turn, +/// each change said in the log, for measuring it in one scene. (Blocks +/// noted in one phase are forgotten at a remapping in either.) fn view_known() -> bool { - static ON: std::sync::OnceLock = std::sync::OnceLock::new(); - *ON.get_or_init(|| std::env::var_os("VICTORY_VIEW_KNOWN").is_some_and(|v| v == "1")) + /// 0 off, 1 on, 2 in turn. + static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); + match *MODE.get_or_init(|| match std::env::var("VICTORY_VIEW_KNOWN").as_deref() { + Ok("1") => 1, + Ok("alt") => 2, + _ => 0, + }) { + 0 => false, + 1 => true, + _ => { + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + let on = (EPOCH + .get_or_init(std::time::Instant::now) + .elapsed() + .as_secs() + / 20) + % 2 + == 1; + static LAST: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2); + if LAST.swap(u8::from(on), std::sync::atomic::Ordering::Relaxed) != u8::from(on) { + tracing::info!( + "view memory stays known while its guard is open from now (VICTORY_VIEW_KNOWN=alt): {}", + if on { "ON" } else { "off, as usual" } + ); + } + on + } + } } static GUARDS: Mutex = Mutex::new(Guards { @@ -738,6 +825,12 @@ fn guards() -> std::sync::MutexGuard<'static, Guards> { GUARDS.lock().unwrap_or_else(|e| e.into_inner()) } +/// Whether the block `page` is read-only by our hand and unwritten since a +/// copy took it (diagnostics of `VICTORY_BACK_OWN_CHECK`). +pub(crate) fn clean(page: usize) -> bool { + guards().clean.contains(&page) +} + /// For view memory: the pages of `[start, end)`'s blocks written since /// they were last guarded (all of a block's pages), guarding them again /// before the caller copies them. `None` if the memory is not a view. @@ -751,11 +844,14 @@ fn guard(start: usize, end: usize, known_mapped: bool) -> Option> { // `VICTORY_GUARD_ASK=1` asks every time, as before. static ASK: std::sync::OnceLock = std::sync::OnceLock::new(); let known = (known_mapped && !ask_anyway()) - || !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) && { - let g = guards(); - let first = start / BLOCK; - g.protected.contains(&first) || g.absent.contains(&first) || (view_known() && g.viewed.contains(&first)) - }; + || !*ASK.get_or_init(|| std::env::var_os("VICTORY_GUARD_ASK").is_some_and(|v| v == "1")) + && { + let g = guards(); + let first = start / BLOCK; + g.protected.contains(&first) + || g.absent.contains(&first) + || (view_known() && g.viewed.contains(&first)) + }; if !known && !is_view(start, end) { return None; } @@ -827,7 +923,8 @@ fn is_view(start: usize, end: usize) -> bool { MEM_COMMIT, MEM_MAPPED, MEMORY_BASIC_INFORMATION, VirtualQuery, }; static HOLES: std::sync::OnceLock = std::sync::OnceLock::new(); - let holes = *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0")); + let holes = + *HOLES.get_or_init(|| std::env::var_os("VICTORY_GUARD_HOLES").is_none_or(|v| v != "0")); let mut at = start; loop { // SAFETY: plain data filled in by the query. @@ -865,7 +962,9 @@ fn protect(g: &mut Guards, from: usize, to: usize) { if !view_guard() { return; } - for (base, bytes) in crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) { + for (base, bytes) in + crate::inplace::views_between(from.saturating_mul(BLOCK), to.saturating_mul(BLOCK)) + { let first = (base / BLOCK).max(from); let last = (base.saturating_add(bytes).div_ceil(BLOCK)).min(to); for block in first..last { @@ -903,7 +1002,8 @@ fn view_guard() -> bool { /// opened because another view of theirs was written, and blocks opened /// because a view of theirs was mapped; since the start. #[cfg(feature = "diagnostics")] -pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = [const { std::sync::atomic::AtomicU64::new(0) }; 3]; +pub(crate) static ALIASES: [std::sync::atomic::AtomicU64; 3] = + [const { std::sync::atomic::AtomicU64::new(0) }; 3]; /// Makes `block` read-only: another view of pages a copy has just taken /// through its own view, so that a write through this one faults too. It is @@ -957,8 +1057,26 @@ fn protect_here(g: &mut Guards, from: usize, to: usize) { for block in from..to { if set(block, block + 1) { note(g, block, block + 1); - } else if block < uncommitted_end(block) { - g.absent.insert(block); + } else { + #[cfg(feature = "diagnostics")] + let error = std::io::Error::last_os_error(); + if block < uncommitted_end(block) { + g.absent.insert(block); + } else { + // Diagnostics: a committed block that will not be made + // read-only is reported written at every asking and never + // known to the guards (one in 1,024 said). + #[cfg(feature = "diagnostics")] + { + static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed).is_multiple_of(1024) { + tracing::info!( + "a block of title memory could not be made read-only (one in 1024): {:#x}: {error}", + block * BLOCK + ); + } + } + } } } } @@ -989,7 +1107,11 @@ fn open(g: &mut Guards, start: usize, end: usize) -> bool { if start >= end || g.aliased.is_empty() { return any; } - let aliased: Vec = g.aliased.range(start / BLOCK..end.div_ceil(BLOCK)).copied().collect(); + let aliased: Vec = g + .aliased + .range(start / BLOCK..end.div_ceil(BLOCK)) + .copied() + .collect(); for block in aliased { g.aliased.remove(&block); for alias in crate::inplace::pages_of(block * BLOCK) { @@ -1049,12 +1171,17 @@ pub fn writing(at: usize, len: usize) { /// queue in an earlier form: still asked for by name.) pub(crate) fn page_writes() -> u8 { static MODE: std::sync::OnceLock = std::sync::OnceLock::new(); - *MODE.get_or_init(|| match std::env::var("VICTORY_PAGE_WRITES").as_deref().map(str::trim) { - Ok("0") => 0, - Ok("1") => 3, - Ok("slots") => 2, - Ok("all") => 7, - _ => 1, + *MODE.get_or_init(|| { + match std::env::var("VICTORY_PAGE_WRITES") + .as_deref() + .map(str::trim) + { + Ok("0") => 0, + Ok("1") => 3, + Ok("slots") => 2, + Ok("all") => 7, + _ => 1, + } }) } @@ -1063,7 +1190,8 @@ pub(crate) fn page_writes() -> u8 { /// of addresses); their bytes; guarded blocks that lay under them (host /// copies that would otherwise keep the bytes from before); reads to /// plain addresses that finished. -pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4]; +pub(crate) static WRITTEN: [std::sync::atomic::AtomicU64; 4] = + [const { std::sync::atomic::AtomicU64::new(0) }; 4]; /// The bytes of a write the guards do not see are there: title memory /// `[at, at + len)`. `pages`: DirectStorage wrote them into physical pages @@ -1148,12 +1276,18 @@ static MAPPING: std::sync::RwLock<()> = std::sync::RwLock::new(()); /// What the runtime holds while it changes what title memory shows /// ([`title_memory_remapping`]). -pub struct Remapping(#[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, std::time::Instant); +pub struct Remapping( + #[allow(dead_code)] std::sync::RwLockWriteGuard<'static, ()>, + std::time::Instant, +); impl Drop for Remapping { fn drop(&mut self) { // From asking for the lock until it is let go (the frame log). - crate::framelog::add(crate::framelog::T::RemapUs, self.1.elapsed().as_micros() as u64); + crate::framelog::add( + crate::framelog::T::RemapUs, + self.1.elapsed().as_micros() as u64, + ); } } @@ -1165,7 +1299,10 @@ pub fn title_memory_remapping() -> Remapping { let asked = std::time::Instant::now(); let held = MAPPING.write().unwrap_or_else(|e| e.into_inner()); crate::framelog::add(crate::framelog::T::Remaps, 1); - crate::framelog::add(crate::framelog::T::RemapWaitUs, asked.elapsed().as_micros() as u64); + crate::framelog::add( + crate::framelog::T::RemapWaitUs, + asked.elapsed().as_micros() as u64, + ); Remapping(held, asked) } @@ -1214,12 +1351,35 @@ pub fn title_memory_remapped(at: usize, len: usize) { g.protected.remove(&block); g.clean.remove(&block); } - let aliased: Vec = g.aliased.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + let aliased: Vec = g + .aliased + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) + .copied() + .collect(); for block in aliased { g.aliased.remove(&block); } + if view_known() { + // The runtime calls this for two things only (`xmem`: `map` and + // `unmap`): a range it has just mapped a section's pages into, + // and a view it is about to make a placeholder again. Either way + // what stands there is view memory or a hole in it, which is what + // `is_view` would answer for a range that begins there; and the + // write watch's asking can only fail there. The title remaps some + // 83 times a frame, and each time the blocks were forgotten, so + // that the next asking about each range went to the kernel twice + // (run 235: 266 to 565 failed askings a frame with the blocks + // remembered from their guards alone, no fewer than without). + g.viewed + .extend(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)); + return; + } // What the range shows is new: no longer known to be a view. - let viewed: Vec = g.viewed.range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)).copied().collect(); + let viewed: Vec = g + .viewed + .range(at / BLOCK..at.saturating_add(len).div_ceil(BLOCK)) + .copied() + .collect(); for block in viewed { g.viewed.remove(&block); } @@ -1505,7 +1665,11 @@ mod tests { // The range begins in the placeholder, its middle block is a view. assert!(is_view(p, p + 3 * BLOCK)); assert_eq!(guard(p, p + 3 * BLOCK, false), Some(all)); - assert_eq!(guard(p, p + 3 * BLOCK, false), Some(Vec::new()), "nothing written since"); + assert_eq!( + guard(p, p + 3 * BLOCK, false), + Some(Vec::new()), + "nothing written since" + ); // SAFETY: inside the mapped middle block. unsafe { ((p + BLOCK + 8) as *mut u8).write_volatile(1) }; assert_eq!(guard(p, p + 3 * BLOCK, false), Some(pages(1).collect())); @@ -1670,8 +1834,15 @@ mod tests { let (section, guarded, other) = two_views(SIZE); let pages = |block: usize| (guarded + block * BLOCK) / PAGE; // The first check takes it in (and every view of its pages). - assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new()), "nothing written yet"); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(vec![pages(0), pages(1)]) + ); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(Vec::new()), + "nothing written yet" + ); // Writing through the other view faults into the handler, which // opens that view and the guarded one: the next check sees it. // SAFETY: the second view, read-write once the handler has opened it. @@ -1688,11 +1859,21 @@ mod tests { const SIZE: usize = 2 * BLOCK; let (section, guarded, other) = two_views(SIZE); let pages = |block: usize| (guarded + block * BLOCK) / PAGE; - assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new()), "nothing written yet"); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(vec![pages(0), pages(1)]) + ); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(Vec::new()), + "nothing written yet" + ); title_memory_remapped(other, SIZE); crate::inplace::title_memory_view(other, SIZE, section, 0); - assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(vec![pages(0), pages(1)]) + ); assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new())); drop_views(section, &[guarded, other], SIZE); } @@ -1704,14 +1885,24 @@ mod tests { const SIZE: usize = 2 * BLOCK; let (section, guarded, other) = two_views(SIZE); let pages = |block: usize| (guarded + block * BLOCK) / PAGE; - assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); - assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new()), "nothing written yet"); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(vec![pages(0), pages(1)]) + ); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(Vec::new()), + "nothing written yet" + ); writing(other + BLOCK, BLOCK); assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(1)])); assert_eq!(guard(guarded, guarded + SIZE, false), Some(Vec::new())); // Half a page and the next: both blocks, not just the first's. writing(other + BLOCK / 2, BLOCK); - assert_eq!(guard(guarded, guarded + SIZE, false), Some(vec![pages(0), pages(1)])); + assert_eq!( + guard(guarded, guarded + SIZE, false), + Some(vec![pages(0), pages(1)]) + ); drop_views(section, &[guarded, other], SIZE); } @@ -1726,18 +1917,41 @@ mod tests { const SIZE: usize = 2 * BLOCK; let (section, one, two) = two_views(SIZE); let pages = |view: usize, block: usize| (view + block * BLOCK) / PAGE; - assert_eq!(guard(one, one + SIZE, false), Some(vec![pages(one, 0), pages(one, 1)])); - assert_eq!(guard(two, two + SIZE, false), Some(vec![pages(two, 0), pages(two, 1)]), "the second view's first check"); - assert_eq!(guard(one, one + SIZE, false), Some(Vec::new()), "nothing written yet"); - assert_eq!(guard(two, two + SIZE, false), Some(Vec::new()), "nothing written yet"); + assert_eq!( + guard(one, one + SIZE, false), + Some(vec![pages(one, 0), pages(one, 1)]) + ); + assert_eq!( + guard(two, two + SIZE, false), + Some(vec![pages(two, 0), pages(two, 1)]), + "the second view's first check" + ); + assert_eq!( + guard(one, one + SIZE, false), + Some(Vec::new()), + "nothing written yet" + ); + assert_eq!( + guard(two, two + SIZE, false), + Some(Vec::new()), + "nothing written yet" + ); // SAFETY: the second view, read-write once the handler has opened it. unsafe { ((two + BLOCK + 8) as *mut u8).write(1) }; assert_eq!(guard(one, one + SIZE, false), Some(vec![pages(one, 1)])); - assert_eq!(guard(two, two + SIZE, false), Some(vec![pages(two, 1)]), "written through this view, checked second"); + assert_eq!( + guard(two, two + SIZE, false), + Some(vec![pages(two, 1)]), + "written through this view, checked second" + ); // SAFETY: the first view, as above. unsafe { ((one + 8) as *mut u8).write(1) }; assert_eq!(guard(two, two + SIZE, false), Some(vec![pages(two, 0)])); - assert_eq!(guard(one, one + SIZE, false), Some(vec![pages(one, 0)]), "written through this view, checked second"); + assert_eq!( + guard(one, one + SIZE, false), + Some(vec![pages(one, 0)]), + "written through this view, checked second" + ); assert_eq!(guard(one, one + SIZE, false), Some(Vec::new())); assert_eq!(guard(two, two + SIZE, false), Some(Vec::new())); drop_views(section, &[one, two], SIZE); @@ -1797,7 +2011,10 @@ mod mapping_tests { }; wait.recv().unwrap(); std::thread::sleep(Duration::from_millis(100)); - assert!(!changed.load(Ordering::SeqCst), "the mapping changed under a read in place"); + assert!( + !changed.load(Ordering::SeqCst), + "the mapping changed under a read in place" + ); drop(reading); change.join().unwrap(); assert!(changed.load(Ordering::SeqCst)); @@ -1815,7 +2032,10 @@ mod mapping_tests { }; wait.recv().unwrap(); std::thread::sleep(Duration::from_millis(100)); - assert!(!read.load(Ordering::SeqCst), "a read in place began during a change of mapping"); + assert!( + !read.load(Ordering::SeqCst), + "a read in place began during a change of mapping" + ); drop(changing); reader.join().unwrap(); assert!(read.load(Ordering::SeqCst)); diff --git a/crates/victory-hle/src/modules/audio.rs b/crates/victory-hle/src/modules/audio.rs index 5ce75518..be9b2b38 100644 --- a/crates/victory-hle/src/modules/audio.rs +++ b/crates/victory-hle/src/modules/audio.rs @@ -497,9 +497,10 @@ impl Xma { let start = Instant::now(); let mut active = 0; for index in 0..self.voices.len() as u32 { - if let (Some(context), Some(voice)) = - (self.context(index), &mut *lock(&self.voices[index as usize])) - { + if let (Some(context), Some(voice)) = ( + self.context(index), + &mut *lock(&self.voices[index as usize]), + ) { pump(context, voice); active += 1; } @@ -648,7 +649,10 @@ fn dump_input(index: u32, context: Context) { ); let _ = std::fs::create_dir_all(&dir); let _ = std::fs::write(dir.join(format!("{n:02}-{index}.ctx")), words); - let _ = std::fs::write(dir.join(format!("{n:02}-{index}.xma")), input.unwrap_or_default()); + let _ = std::fs::write( + dir.join(format!("{n:02}-{index}.xma")), + input.unwrap_or_default(), + ); } /// Starts the decoding thread on the first enabled voice, and has it fill diff --git a/crates/victory-hle/src/modules/audio/capture.rs b/crates/victory-hle/src/modules/audio/capture.rs index f39bb3da..43922045 100644 --- a/crates/victory-hle/src/modules/audio/capture.rs +++ b/crates/victory-hle/src/modules/audio/capture.rs @@ -12,6 +12,7 @@ use std::io::{Seek, SeekFrom, Write}; use std::path::Path; use std::time::{Duration, Instant}; +use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::Media::Audio::{ AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY, AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM, AUDCLNT_STREAMFLAGS_LOOPBACK, @@ -23,7 +24,6 @@ use windows::Win32::Media::Audio::{ VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, WAVE_FORMAT_PCM, WAVEFORMATEX, }; use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx}; -use windows::Win32::Foundation::WAIT_OBJECT_0; use windows::Win32::System::Threading::{ OpenProcess, PROCESS_SYNCHRONIZE, Sleep, WaitForSingleObject, }; diff --git a/crates/victory-hle/src/modules/dstorage.rs b/crates/victory-hle/src/modules/dstorage.rs index ae859256..eb67c9f5 100644 --- a/crates/victory-hle/src/modules/dstorage.rs +++ b/crates/victory-hle/src/modules/dstorage.rs @@ -146,7 +146,10 @@ extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out // SAFETY: a handle we just opened and nobody else owns. let file = unsafe { std::fs::File::from_raw_handle(handle) }; let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file }); - WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept)); + WALLS_FILES + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push((file as usize, kept)); put(out, file) } @@ -449,7 +452,10 @@ impl Scheduler { fn walls_trace() -> u8 { static ON: OnceLock = OnceLock::new(); *ON.get_or_init(|| { - std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::().ok()).unwrap_or(0) + std::env::var("VICTORY_WALLS_TRACE") + .ok() + .and_then(|v| v.trim().parse::().ok()) + .unwrap_or(0) }) } @@ -468,7 +474,10 @@ fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std:: } else { let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()); let source = request.source as usize; - files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone()) + files + .iter() + .find(|f| f.0 == source) + .map_or_else(|| "?".to_string(), |f| f.1.clone()) }; let hr = match result { Ok(()) => 0, @@ -496,14 +505,18 @@ fn work(scheduler: &'static Scheduler) { #[cfg(windows)] { static SLOW: OnceLock = OnceLock::new(); - if *SLOW.get_or_init(|| std::env::var_os("VICTORY_DISK_CORES").is_some_and(|v| v == "slow")) { + if *SLOW.get_or_init(|| std::env::var_os("VICTORY_DISK_CORES").is_some_and(|v| v == "slow")) + { victory_gpu::framelog::keep_on_slow_cores("dstorage worker"); } } let mut lanes = scheduler.lock(); loop { let Some(job) = lanes.start() else { - lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner()); + lanes = scheduler + .work + .wait(lanes) + .unwrap_or_else(|e| e.into_inner()); continue; }; drop(lanes); @@ -550,7 +563,8 @@ impl Lanes { reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()), staging_waits = std::mem::take(&mut self.refused), bcpack_mb = self.bcpack.0 / 1_000_000, - bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), + bcpack_workers = + format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()), waiting, "dstorage: last {:.1} s", elapsed.as_secs_f64() @@ -662,7 +676,11 @@ impl Lane { fn flush(&mut self) { while let Some(&(seq, _)) = self.statuses.front() { let waiting = self.reads.front().map(|r| r.0); - if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) { + if waiting + .into_iter() + .chain(self.running.first().copied()) + .any(|s| s < seq) + { return; } let Some((_, status)) = self.statuses.pop_front() else { @@ -755,7 +773,6 @@ enum Command { Status(Status), } - /// A status entry to write, holding a reference on its array. struct Status { array: Array, @@ -900,7 +917,11 @@ fn execute(request: &Request) -> Result<(), HRESULT> { }) .map_err(|hr| fail(hr, "copying")); } - let tables = if bc != 0 { Some(bcpack_tables()?) } else { None }; + let tables = if bc != 0 { + Some(bcpack_tables()?) + } else { + None + }; let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?; // The console's order: zlib first, then BCPack. let source = if bc != 0 && options & ZLIB != 0 { @@ -1008,7 +1029,9 @@ fn use_bcpack_tables(dir: std::path::PathBuf) { #[cfg(test)] fn load_bcpack_tables() -> Result { - let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?; + let dir = BCPACK_DIR + .get() + .ok_or("no folder set for the test tables")?; let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?; Tables::parse(&bytes).map_err(|e| e.to_string()) } @@ -1034,7 +1057,9 @@ static READING: AtomicU64 = AtomicU64::new(0); fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> { if request.options & MEMORY_SOURCE != 0 { // SAFETY: the title's source holds `out.len()` bytes until completion. - out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) }); + out.copy_from_slice(unsafe { + std::slice::from_raw_parts(request.source.cast(), out.len()) + }); return Ok(()); } // SAFETY: a file object we created; the title keeps it open. @@ -1117,7 +1142,10 @@ fn into_destination( // that tried again (run 165) lost none of 13. static RETRIES: std::sync::OnceLock = std::sync::OnceLock::new(); let retries = *RETRIES.get_or_init(|| { - std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(12) + std::env::var("VICTORY_DSTORAGE_RETRIES") + .ok() + .and_then(|v| v.trim().parse().ok()) + .unwrap_or(12) }); // Since the start: writes that succeeded on a later try, and writes // given up. @@ -1125,7 +1153,9 @@ fn into_destination( let mut written = super::xmem::write_physical(pages, offset, &data[..n]); let mut tries = 0u32; while !written && tries < retries { - std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128))); + std::thread::sleep(std::time::Duration::from_millis( + (2u64 << tries.min(6)).min(128), + )); tries += 1; written = super::xmem::write_physical(pages, offset, &data[..n]); } @@ -1332,8 +1362,7 @@ mod tests { fn compress_zlib(plain: &[u8]) -> Vec { let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())]; - let (packed, rc) = - zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6)); + let (packed, rc) = zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6)); assert_eq!(rc, zlib_rs::ReturnCode::Ok); packed.to_vec() } @@ -1400,7 +1429,8 @@ mod tests { // Requests in flight together run in any order, so none of them // shares a destination (failed ones leave theirs undefined). let mut buffers = [[0u8; 16]; 5]; - let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast()); + let [failed, failed_too, out, other, bcpack] = + buffers.each_mut().map(|b| b.as_mut_ptr().cast()); // Segment 0: a read past the end, then a bad stream; the first wins. enqueue(queue, &request(0, failed, 16, file, 4090, 16)); @@ -1616,7 +1646,10 @@ mod tests { let (_dir, file) = file_with(&contents); let (queue, array) = (new_queue(0), status_array(1)); let mut out = [0u8; 16]; - enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88)); + enqueue( + queue, + &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88), + ); enqueue_status(queue, array, 0); void(queue, 0x30); assert_eq!(wait(array, 0), S_OK); diff --git a/crates/victory-hle/src/modules/files.rs b/crates/victory-hle/src/modules/files.rs index d13c3bc2..40013d5d 100644 --- a/crates/victory-hle/src/modules/files.rs +++ b/crates/victory-hle/src/modules/files.rs @@ -776,7 +776,10 @@ mod tests { let file = std::fs::File::open(&path).unwrap(); let (mut out, mut n) = ([0u8; 10], 0); let handle = file.as_raw_handle().cast(); - assert_ne!(ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), 0); + assert_ne!( + ReadFile(handle, out.as_mut_ptr(), 10, &mut n, std::ptr::null_mut()), + 0 + ); assert_eq!((&out, n), (b"0123456789", 10)); } @@ -785,7 +788,9 @@ mod tests { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("data.bin"); // Over two chunks, and not a whole number of 3-byte items. - let bytes: Vec = (0..(5 << 19) + 1).map(|i| (i * 7 + i / 251) as u8).collect(); + let bytes: Vec = (0..(5 << 19) + 1) + .map(|i| (i * 7 + i / 251) as u8) + .collect(); std::fs::write(&path, &bytes).unwrap(); let fclose = host!("ucrtbase.dll", "fclose": extern "C" fn(File) -> i32); let open = || { @@ -799,8 +804,15 @@ mod tests { let mut out = vec![0xaau8; bytes.len() + 64]; let items = fread(out.as_mut_ptr(), 3, out.len() / 3, f); assert_eq!(items, bytes.len() / 3); - assert_eq!(&out[..bytes.len()], &bytes[..], "the partial last item's bytes too"); - assert!(out[bytes.len()..].iter().all(|&b| b == 0xaa), "nothing past what was read"); + assert_eq!( + &out[..bytes.len()], + &bytes[..], + "the partial last item's bytes too" + ); + assert!( + out[bytes.len()..].iter().all(|&b| b == 0xaa), + "nothing past what was read" + ); fclose(f); // Exact reads continue where the last one stopped. diff --git a/crates/victory-hle/src/modules/gameinput.rs b/crates/victory-hle/src/modules/gameinput.rs index 501828ae..0392519c 100644 --- a/crates/victory-hle/src/modules/gameinput.rs +++ b/crates/victory-hle/src/modules/gameinput.rs @@ -886,7 +886,10 @@ extern "system" fn unregister_callback(this: This, token: u64, timeout: u64) -> return true; } state = match deadline { - None => hub.returned.wait(state).unwrap_or_else(PoisonError::into_inner), + None => hub + .returned + .wait(state) + .unwrap_or_else(PoisonError::into_inner), Some(deadline) => { let Some(left) = deadline.checked_duration_since(Instant::now()) else { return false; @@ -1154,7 +1157,8 @@ mod host { XInputSetState, }; use windows_sys::Win32::UI::WindowsAndMessaging::{ - GetCursorPos, GetForegroundWindow, GetWindowRect, GetWindowThreadProcessId, IsWindow, SetCursorPos, + GetCursorPos, GetForegroundWindow, GetWindowRect, GetWindowThreadProcessId, IsWindow, + SetCursorPos, }; use super::*; @@ -1260,7 +1264,9 @@ mod host { #[cfg(feature = "diagnostics")] if slot == 0 { for vk in scripted() { - if let Some(&(_, button)) = super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) { + if let Some(&(_, button)) = + super::FALLBACK_BUTTONS.iter().find(|(key, _)| *key == vk) + { pad.buttons |= button; } } @@ -1307,7 +1313,10 @@ mod host { } // SAFETY: plain queries. let window = unsafe { GetForegroundWindow() } as isize; - if self.game_window.is_none_or(|w| unsafe { IsWindow(w as _) } == 0) { + if self + .game_window + .is_none_or(|w| unsafe { IsWindow(w as _) } == 0) + { // Capture starts on the first in-process foreground window; // when that window closes (a startup dialog), capture moves // to whatever is in front then. @@ -1759,7 +1768,16 @@ mod tests { let mut token = 0; let context = (&raw const hub.object).cast_mut().cast(); assert_eq!( - register(&hub.object, std::ptr::null(), GAMEPAD_KIND, 1, 0, context, Some(slow), &mut token), + register( + &hub.object, + std::ptr::null(), + GAMEPAD_KIND, + 1, + 0, + context, + Some(slow), + &mut token + ), S_OK ); host.lock().unwrap().pads[1] = Some(PadState::default()); @@ -1768,7 +1786,10 @@ mod tests { std::thread::sleep(Duration::from_millis(1)); } let unregister = slot:: bool, _>(&hub.object, 0x68); - assert!(!unregister(&hub.object, token, 5000), "times out while it runs"); + assert!( + !unregister(&hub.object, token, 5000), + "times out while it runs" + ); let leave = std::thread::spawn(|| { std::thread::sleep(Duration::from_millis(50)); LEAVE.store(true, Ordering::SeqCst); diff --git a/crates/victory-hle/src/modules/xasync.rs b/crates/victory-hle/src/modules/xasync.rs index 068d75f2..f6b8921e 100644 --- a/crates/victory-hle/src/modules/xasync.rs +++ b/crates/victory-hle/src/modules/xasync.rs @@ -760,7 +760,10 @@ pub fn pending_with( identity: *const c_void, work: impl FnOnce() -> Result, HRESULT> + Send + 'static, ) -> HRESULT { - type Data = Mutex<(Option Result, HRESULT> + Send>>, Vec)>; + type Data = Mutex<( + Option Result, HRESULT> + Send>>, + Vec, + )>; extern "system" fn provider(op: u32, data: *const ProviderData) -> HRESULT { // SAFETY: the runtime passes valid provider data; the context is the // boxed state until cleanup frees it. @@ -771,7 +774,11 @@ pub fn pending_with( OP_CLEANUP => drop(unsafe { Box::from_raw(state) }), OP_BEGIN => { // SAFETY: as above; cleanup waits for completion. - let work = unsafe { &*state }.lock().unwrap_or_else(|e| e.into_inner()).0.take(); + let work = unsafe { &*state } + .lock() + .unwrap_or_else(|e| e.into_inner()) + .0 + .take(); let (block, state) = (data.block as usize, state as usize); std::thread::spawn(move || { let result = work.map_or(Err(E_ABORT), |work| work()); @@ -800,7 +807,13 @@ pub fn pending_with( } let state: Box = Box::new(Mutex::new((Some(Box::new(work)), Vec::new()))); let context = Box::into_raw(state); - let hr = XAsyncBegin(block, context.cast(), identity, std::ptr::null(), Some(provider)); + let hr = XAsyncBegin( + block, + context.cast(), + identity, + std::ptr::null(), + Some(provider), + ); if hr < 0 { // SAFETY: refused before the call existed; still ours. drop(unsafe { Box::from_raw(context) }); @@ -1164,7 +1177,13 @@ mod tests { }; let identity = 0x77 as *const c_void; assert_eq!( - XAsyncBegin(&mut block, std::ptr::null_mut(), identity, std::ptr::null(), Some(provider)), + XAsyncBegin( + &mut block, + std::ptr::null_mut(), + identity, + std::ptr::null(), + Some(provider) + ), S_OK ); assert!(XTaskQueueDispatch(q, WORK, 0)); @@ -1175,11 +1194,20 @@ mod tests { let mut value = 0u64; let mut used = 0; assert_eq!( - XAsyncGetResult(&mut block, identity, 8, (&mut value as *mut u64).cast(), &mut used), + XAsyncGetResult( + &mut block, + identity, + 8, + (&mut value as *mut u64).cast(), + &mut used + ), S_OK ); assert_eq!((value, used), (0x1234, 8)); - assert!(call(&raw mut block).is_none(), "the call ends with its result"); + assert!( + call(&raw mut block).is_none(), + "the call ends with its result" + ); XTaskQueueCloseHandle(q); } diff --git a/crates/victory-hle/src/modules/xg.rs b/crates/victory-hle/src/modules/xg.rs index 56011ec5..b283a435 100644 --- a/crates/victory-hle/src/modules/xg.rs +++ b/crates/victory-hle/src/modules/xg.rs @@ -582,19 +582,19 @@ struct Vtable([*const (); 13]); unsafe impl Sync for Vtable {} static VTABLE: Vtable = Vtable([ - add_ref as *const (), // 0x00 - release as *const (), // 0x08 - layout as *const (), // 0x10 - unused as *const (), // 0x18 size - unused as *const (), // 0x20 alignment - unused as *const (), // 0x28 mip offset + add_ref as *const (), // 0x00 + release as *const (), // 0x08 + layout as *const (), // 0x10 + unused as *const (), // 0x18 size + unused as *const (), // 0x20 alignment + unused as *const (), // 0x28 mip offset element_offset as *const (), // 0x30 - unused as *const (), // 0x38 element coordinate - copy_into as *const (), // 0x40 - copy_from as *const (), // 0x48 - tiling as *const (), // 0x50 - unused as *const (), // 0x58 view descriptor - unused as *const (), // 0x60 tiled resource? + unused as *const (), // 0x38 element coordinate + copy_into as *const (), // 0x40 + copy_from as *const (), // 0x48 + tiling as *const (), // 0x50 + unused as *const (), // 0x58 view descriptor + unused as *const (), // 0x60 tiled resource? ]); pub(crate) fn module() -> HleModule { diff --git a/crates/victory-hle/src/modules/xgame.rs b/crates/victory-hle/src/modules/xgame.rs index edcf2eaa..765e96ed 100644 --- a/crates/victory-hle/src/modules/xgame.rs +++ b/crates/victory-hle/src/modules/xgame.rs @@ -74,7 +74,10 @@ extern "system" fn launch_new_game( args: *const c_char, _user: *const c_void, ) { - let (exe, args) = (text(exe).unwrap_or_default(), text(args).unwrap_or_default()); + let (exe, args) = ( + text(exe).unwrap_or_default(), + text(args).unwrap_or_default(), + ); tracing::info!(exe, args, "XLaunchNewGame"); let current = runtime::main_image() .and_then(runtime::image_path) @@ -195,15 +198,32 @@ mod tests { #[test] fn a_relaunch_keeps_our_options() { - let ours: Vec = - ["run", "G:/game.exe", "--execute", "--console", "series-s", "--", "-old"] - .map(Into::into) - .into(); + let ours: Vec = [ + "run", + "G:/game.exe", + "--execute", + "--console", + "series-s", + "--", + "-old", + ] + .map(Into::into) + .into(); let current = std::ffi::OsStr::new("G:/game.exe"); let again = relaunch_args(ours.clone(), current, "G:/game.exe", " -config=x -y "); - let expected = ["run", "G:/game.exe", "--execute", "--console", "series-s", "--"]; + let expected = [ + "run", + "G:/game.exe", + "--execute", + "--console", + "series-s", + "--", + ]; assert_eq!(again[..6], expected.map(std::ffi::OsString::from)); - assert_eq!(again[6..], ["-config=x", "-y"].map(std::ffi::OsString::from)); + assert_eq!( + again[6..], + ["-config=x", "-y"].map(std::ffi::OsString::from) + ); let other = relaunch_args(ours, current, "G:/other.exe", ""); assert_eq!(other.len(), 5); assert_eq!(other[1], "G:/other.exe"); diff --git a/crates/victory-hle/src/modules/xgamesave.rs b/crates/victory-hle/src/modules/xgamesave.rs index 560b6a60..30954614 100644 --- a/crates/victory-hle/src/modules/xgamesave.rs +++ b/crates/victory-hle/src/modules/xgamesave.rs @@ -256,8 +256,9 @@ fn commit( match source { Source::Data(data) => write(path, data)?, // Files are never changed in place, so sharing one is safe. - Source::Kept(from) => std::fs::hard_link(from, &path) - .or_else(|_| std::fs::copy(from, &path).map(drop))?, + Source::Kept(from) => { + std::fs::hard_link(from, &path).or_else(|_| std::fs::copy(from, &path).map(drop))? + } } step(); } @@ -460,7 +461,9 @@ impl Update { } let replaced: u64 = current.as_ref().map_or(0, |v| { let sizes = v.sizes(); - let changed = sizes.iter().filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); + let changed = sizes + .iter() + .filter(|(n, _)| self.changes.iter().any(|(c, _)| c == n)); changed.map(|(_, size)| size).sum() }); let root = self.dir.parent().unwrap_or(&self.dir); @@ -513,7 +516,11 @@ fn read(c: &Container, names: Option>) -> Result bool, context: *mut c_void, callback: ContainerCallback) { +fn report( + root: &Path, + keep: impl Fn(&str) -> bool, + context: *mut c_void, + callback: ContainerCallback, +) { let infos: Vec<(CString, CString, u32, u64, i64)> = { let _saves = saves_lock(); containers(root) @@ -974,7 +986,10 @@ mod tests { fn a_full_disk_is_not_the_quota() { let mb = 1 << 20; assert_eq!(no_room(2 * mb, 0, 0, mb), Some(OUT_OF_LOCAL_STORAGE)); - assert_eq!(no_room(2 * mb, 0, QUOTA - mb, 100 * mb), Some(QUOTA_EXCEEDED)); + assert_eq!( + no_room(2 * mb, 0, QUOTA - mb, 100 * mb), + Some(QUOTA_EXCEEDED) + ); // Replacing a blob of the same size fits a full quota. assert_eq!(no_room(mb, mb, QUOTA, 100 * mb), None); assert_eq!(no_room(mb, 0, 0, mb), None); @@ -1003,18 +1018,28 @@ mod tests { } fn old_state() -> Option<(String, Vec<(String, String)>)> { - Some(("one".into(), vec![("a".into(), "old a".into()), ("b".into(), "old b".into())])) + Some(( + "one".into(), + vec![("a".into(), "old a".into()), ("b".into(), "old b".into())], + )) } /// Run by the crash test in a child process; does nothing otherwise. #[test] fn crash_child() { - let (Ok(root), Ok(op)) = (std::env::var("VICTORY_SAVE_CHILD"), std::env::var("VICTORY_SAVE_OP")) else { + let (Ok(root), Ok(op)) = ( + std::env::var("VICTORY_SAVE_CHILD"), + std::env::var("VICTORY_SAVE_OP"), + ) else { return; }; let root = PathBuf::from(root); let hr = if op == "update" { - update(&root, "two", &[("a", Some("new a")), ("b", None), ("c", Some("new c"))]) + update( + &root, + "two", + &[("a", Some("new a")), ("b", None), ("c", Some("new c"))], + ) } else { delete(&root, "Slot") }; @@ -1027,15 +1052,25 @@ mod tests { /// new one. #[test] fn a_kill_at_any_step_leaves_old_or_new() { - let new = Some(("two".into(), vec![("a".into(), "new a".into()), ("c".into(), "new c".into())])); + let new = Some(( + "two".into(), + vec![("a".into(), "new a".into()), ("c".into(), "new c".into())], + )); for (op, after) in [("update", new), ("delete", None)] { let mut seen = (0, 0); for stop in 1.. { let dir = tempfile::tempdir().unwrap(); let root = dir.path(); - assert_eq!(update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), S_OK); + assert_eq!( + update(root, "one", &[("a", Some("old a")), ("b", Some("old b"))]), + S_OK + ); let mut child = std::process::Command::new(std::env::current_exe().unwrap()) - .args(["--exact", "modules::xgamesave::tests::crash_child", "--nocapture"]) + .args([ + "--exact", + "modules::xgamesave::tests::crash_child", + "--nocapture", + ]) .args(["--test-threads=1"]) .env("VICTORY_SAVE_CHILD", root) .env("VICTORY_SAVE_OP", op) @@ -1080,16 +1115,35 @@ mod tests { for good in ["Profile/Slot_1", "a/b/Save-2.sav", "x", &"a".repeat(256)] { assert!(valid_container(good), "{good}"); } - for bad in ["a b", "", "a/", "a.", "a..b", "a.b/c", "a-b/c", &"a".repeat(257)] { + for bad in [ + "a b", + "", + "a/", + "a.", + "a..b", + "a.b/c", + "a-b/c", + &"a".repeat(257), + ] { assert!(!valid_container(bad), "{bad}"); } // Containers and blobs differing only in case, reserved device // names, characters the host forbids, long names: all distinct. let dir = tempfile::tempdir().unwrap(); - let p = Provider { root: dir.path().into() }; + let p = Provider { + root: dir.path().into(), + }; let long = "n".repeat(300); - let blobs = ["A", "a", "CON", "nul.txt", "x/y:z*?\"<>|", long.as_str(), "end. "]; + let blobs = [ + "A", + "a", + "CON", + "nul.txt", + "x/y:z*?\"<>|", + long.as_str(), + "end. ", + ]; for container in ["Save", "save", "SAVE/CON.x"] { let c = p.container(container); let u = Update { @@ -1121,7 +1175,10 @@ mod tests { #[test] fn the_old_layout_moves_over() { let saves = tempfile::tempdir().unwrap(); - let root = saves.path().join(format!("{:016X}", xuser::XUID)).join("scid"); + let root = saves + .path() + .join(format!("{:016X}", xuser::XUID)) + .join("scid"); let old = root.join("Player"); std::fs::create_dir_all(&old).unwrap(); std::fs::write(old.join("Save%20Game%20Data"), b"data").unwrap(); @@ -1214,7 +1271,10 @@ mod tests { S_OK ); type Delete = extern "system" fn(This, *mut Update, *const c_char) -> HRESULT; - assert_eq!(method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), S_OK); + assert_eq!( + method::(&OBJECT, 0xd0)(this, update, c"gone".as_ptr()), + S_OK + ); type Submit = extern "system" fn(This, *const Update, *mut AsyncBlock) -> HRESULT; let mut b = block(); assert_eq!(method::(&OBJECT, 0xe0)(this, update, &mut b), S_OK); diff --git a/crates/victory-hle/src/modules/xgameui.rs b/crates/victory-hle/src/modules/xgameui.rs index 9882b2ea..e19ba68b 100644 --- a/crates/victory-hle/src/modules/xgameui.rs +++ b/crates/victory-hle/src/modules/xgameui.rs @@ -60,7 +60,8 @@ extern "system" fn text_entry_async( _scope: u32, max_length: u32, ) -> HRESULT { - let [title, description, default] = [title, description, default].map(|t| text(t).unwrap_or_default()); + let [title, description, default] = + [title, description, default].map(|t| text(t).unwrap_or_default()); tracing::info!(title, description, max_length, "text entry"); xasync::pending_with(block, (&raw const TEXT).cast(), move || { match ask(&title, &description, &default, max_length) { @@ -178,7 +179,13 @@ mod dialog { let ok = wm::BS_DEFPUSHBUTTON as u32 | tab; item(ok, [129, 40, 50, 14], wm::IDOK as u16, button, "OK"); let cancel = wm::BS_PUSHBUTTON as u32 | tab; - item(cancel, [183, 40, 50, 14], wm::IDCANCEL as u16, button, "Cancel"); + item( + cancel, + [183, 40, 50, 14], + wm::IDCANCEL as u16, + button, + "Cancel", + ); // The template must start on a DWORD. let template: Vec = t .chunks(2) @@ -199,7 +206,12 @@ mod dialog { entry.typed } - extern "system" fn procedure(dialog: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> isize { + extern "system" fn procedure( + dialog: HWND, + message: u32, + wparam: WPARAM, + lparam: LPARAM, + ) -> isize { // SAFETY: our dialog; its user data is the `Entry` from `ask`, // stored at WM_INITDIALOG. unsafe { @@ -214,12 +226,16 @@ mod dialog { 0 // focus set here } wm::WM_COMMAND => { - let entry = &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); + let entry = + &mut *(wm::GetWindowLongPtrW(dialog, wm::GWLP_USERDATA) as *mut Entry); match (wparam & 0xffff) as i32 { wm::IDOK => { - let mut buffer = vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; - let n = wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); - entry.typed = Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); + let mut buffer = + vec![0u16; wm::GetWindowTextLengthW(edit) as usize + 1]; + let n = + wm::GetWindowTextW(edit, buffer.as_mut_ptr(), buffer.len() as i32); + entry.typed = + Some(String::from_utf16_lossy(&buffer[..n.max(0) as usize])); wm::EndDialog(dialog, 1); } wm::IDCANCEL => { @@ -295,19 +311,29 @@ mod tests { u32, ) -> HRESULT; type Size = extern "system" fn(This, *mut AsyncBlock, *mut u32) -> HRESULT; - type Result_ = extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; + type Result_ = + extern "system" fn(This, *mut AsyncBlock, u32, *mut c_char, *mut u32) -> HRESULT; let null = std::ptr::null(); let entry = method::(&OBJECT, 0x88); // Dismissed: cancelled. let mut b = block(); - assert_eq!(entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), S_OK); + assert_eq!( + entry(this, &mut b, c"Name".as_ptr(), null, null, 0, 16), + S_OK + ); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), E_ABORT); let mut size = 0; - assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), E_ABORT); + assert_eq!( + method::(&OBJECT, 0x90)(this, &mut b, &mut size), + E_ABORT + ); // Typed: the text, cut to the limit, with its NUL. let mut b = block(); let default = c"abc".as_ptr(); - assert_eq!(entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), S_OK); + assert_eq!( + entry(this, &mut b, c"Type".as_ptr(), null, default, 0, 6), + S_OK + ); assert_eq!(xasync::XAsyncGetStatus(&mut b, true), S_OK); assert_eq!(method::(&OBJECT, 0x90)(this, &mut b, &mut size), S_OK); assert_eq!(size, 7); diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs index e8984593..2fc6a692 100644 --- a/crates/victory-hle/src/modules/xmem.rs +++ b/crates/victory-hle/src/modules/xmem.rs @@ -629,7 +629,11 @@ pub(crate) fn shown_at(pages: &[usize], offset: usize, len: usize) -> Vec<(usize { let physical = physical(); for (i, page) in touched.iter().enumerate() { - let Some(addresses) = physical.pages.get(page).and_then(|slice| physical.shown.get(&slice.key(0))) else { + let Some(addresses) = physical + .pages + .get(page) + .and_then(|slice| physical.shown.get(&slice.key(0))) + else { continue; }; // The bytes of this page that the write covers. @@ -810,9 +814,18 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool { // New contents, read-write: the GPU side's copies no longer guard it. victory_gpu::title_memory_remapped(base, len); // What the range shows now, for the GPU side's in-place census. - victory_gpu::title_memory_view(base, len, slice.section.0 as usize, (slice.index * PAGE) as u64); + victory_gpu::title_memory_view( + base, + len, + slice.section.0 as usize, + (slice.index * PAGE) as u64, + ); for k in 0..len.div_ceil(PAGE) { - physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE); + physical + .shown + .entry(slice.key(k)) + .or_default() + .push(base + k * PAGE); } physical.views.insert(base, (len, slice)); true @@ -1389,7 +1402,13 @@ mod tests { fn pages_say_where_they_are_mapped() { let pages = allocate(3); let reserve = |n: usize| { - let at = XMemVirtualAlloc(std::ptr::null_mut(), n * PAGE, MEM_RESERVE | PAGES_64K, 0, PAGE_READWRITE); + let at = XMemVirtualAlloc( + std::ptr::null_mut(), + n * PAGE, + MEM_RESERVE | PAGES_64K, + 0, + PAGE_READWRITE, + ); assert!(!at.is_null()); at }; diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index e566bafa..f5a6a5f9 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -149,9 +149,15 @@ fn elements(text: &str) -> Vec<(String, String)> { .unwrap_or(""); path.push(name); let body = rest[..rest.find('<').unwrap_or(rest.len())].trim(); - let body = [("<", "<"), (">", ">"), (""", "\""), ("'", "'"), ("&", "&")] - .iter() - .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); + let body = [ + ("<", "<"), + (">", ">"), + (""", "\""), + ("'", "'"), + ("&", "&"), + ] + .iter() + .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c)); out.push((path.join("/"), body)); if closed { path.pop(); @@ -185,9 +191,9 @@ pub fn title() -> Title { pub fn use_console_timers() { use windows_sys::Win32::Media::timeBeginPeriod; use windows_sys::Win32::System::Threading::{ - GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED, - PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE, - ProcessPowerThrottling, SetProcessInformation, + GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, + PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, + PROCESS_POWER_THROTTLING_STATE, ProcessPowerThrottling, SetProcessInformation, }; // Also: the system does not run this process at reduced speed (its // "efficiency mode": lower clock, the slow cores of a hybrid processor) diff --git a/crates/victory-loader/src/console_insn.rs b/crates/victory-loader/src/console_insn.rs index ca1eb8cc..0572b8ce 100644 --- a/crates/victory-loader/src/console_insn.rs +++ b/crates/victory-loader/src/console_insn.rs @@ -46,14 +46,157 @@ static EMULATED: AtomicU64 = AtomicU64::new(0); static ASKED: AtomicU64 = AtomicU64::new(0); static ZEROED: AtomicU64 = AtomicU64::new(0); +/// Exceptions taken by kind since the last line: a lone `clzero`, the 12-byte loop, the +/// 15-byte loop taken whole, `monitorx`, `mwaitx`, everything else; and the 64-byte lines the +/// 15-byte loops zeroed (each was an exception of its own before they were taken whole). +static KINDS: [AtomicU64; 7] = [const { AtomicU64::new(0) }; 7]; +const K_CLZERO: usize = 0; +const K_LOOP12: usize = 1; +const K_LOOP15: usize = 2; +const K_MONITORX: usize = 3; +const K_MWAITX: usize = 4; +const K_OTHER: usize = 5; +const K_LOOP15_LINES: usize = 6; + +/// Waits the title made with `monitorx` / `mwaitx` (it waits for a fence that way, reading +/// the fence's value in memory: its +0x4fb0ad0) that have ended since the last line: how +/// many, their microseconds, and both again for those of 1 ms and more, 5 ms and more, +/// 20 ms and more. +static WAITS: [AtomicU64; 8] = [const { AtomicU64::new(0) }; 8]; +/// Waits said in the log one by one. +static WAITS_SAID: AtomicU64 = AtomicU64::new(0); +/// When the last line was written, in milliseconds of [`clock_us`]. +static LINE_AT: AtomicU64 = AtomicU64::new(0); + +thread_local! { + /// The address and the value this thread last armed a monitor for (`monitorx`: rax, and + /// the title's wanted value in rsi). + static MONITOR: Cell<(usize, u64)> = const { Cell::new((0, 0)) }; + /// This thread's wait under way: when it began and when its last `mwaitx` was, in + /// microseconds, what it waits for, and its `mwaitx` count. + static WAIT: Cell<(u64, u64, usize, u64, u32)> = const { Cell::new((0, 0, 0, 0, 0)) }; +} + +/// Microseconds on the performance counter. +fn clock_us() -> u64 { + static PER_SECOND: std::sync::OnceLock = std::sync::OnceLock::new(); + let per_second = *PER_SECOND.get_or_init(|| { + let mut f = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceFrequency(&mut f) }; + f.max(1) + }); + let mut now = 0i64; + // SAFETY: a valid out pointer. + unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut now) }; + (now as u128 * 1_000_000 / per_second as u128) as u64 +} + +/// Whether events are said one by one now: four seconds of every two minutes of the wall +/// clock, the same seconds in which the fence meter of the graphics side says its own +/// (`victory_gpu::fence::pace`), so that the two can be laid side by side. +fn detail_now() -> bool { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .is_ok_and(|d| d.as_secs() % 120 < 4) +} + +/// Whether the 15-byte `clzero` loop is taken whole (`VICTORY_CLZERO_LOOP15=0`: line by +/// line, as before). +fn loop15() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_LOOP15").is_none_or(|v| v != "0")) +} + +/// A wait of this thread has ended: counted, and said if it is one to say. +fn wait_ended(begin: u64, last: u64, address: usize, wanted: u64, spins: u32) { + let us = last.saturating_sub(begin); + for (i, least) in [0u64, 1_000, 5_000, 20_000].into_iter().enumerate() { + if us >= least { + WAITS[2 * i].fetch_add(1, Relaxed); + WAITS[2 * i + 1].fetch_add(us, Relaxed); + } + } + if us >= 500 && (detail_now() || WAITS_SAID.fetch_add(1, Relaxed) < 40) { + // SAFETY: no preconditions. + let thread = unsafe { windows_sys::Win32::System::Threading::GetCurrentThreadId() }; + tracing::info!( + "mwait: thread {thread} waited {:.1} ms for the value at {address:#x} to reach {wanted} ({spins} mwaitx)", + us as f64 / 1e3 + ); + } +} + +/// A `mwaitx` of this thread: part of the wait under way, or the first of a new one. +fn wait_step() { + let now = clock_us(); + let (address, wanted) = MONITOR.with(Cell::get); + let (begin, last, was_at, was_for, spins) = WAIT.with(Cell::get); + if begin != 0 && was_at == address && was_for == wanted && now.saturating_sub(last) < 2_000 { + WAIT.with(|w| w.set((begin, now, address, wanted, spins + 1))); + return; + } + if begin != 0 { + wait_ended(begin, last, was_at, was_for, spins); + } + WAIT.with(|w| w.set((now, now, address, wanted, 1))); +} + +/// A line every five seconds: exceptions a second by kind, and the waits that ended. +fn line() { + let now = clock_us() / 1000; + let last = LINE_AT.load(Relaxed); + if now < last + 5_000 + || LINE_AT + .compare_exchange(last, now, Relaxed, Relaxed) + .is_err() + { + return; + } + if last == 0 { + return; + } + let seconds = (now - last) as f64 / 1e3; + let k: Vec = KINDS + .iter() + .map(|k| k.swap(0, Relaxed) as f64 / seconds) + .collect(); + let w: Vec = WAITS.iter().map(|w| w.swap(0, Relaxed) as f64).collect(); + tracing::info!( + "console CPU instructions, exceptions a second: clzero alone {:.0}, its 12-byte loop {:.0}, its 15-byte loop taken whole {:.0} ({:.0} lines a second, each an exception \ + before; VICTORY_CLZERO_LOOP15=0: again), monitorx {:.0}, mwaitx {:.0}, others {:.0} | mwaitx waits ended a second: {:.0}, {:.1} ms of thread time a second; of 1 ms and \ + more {:.1} ({:.1} ms), of 5 ms and more {:.1} ({:.1} ms), of 20 ms and more {:.1} ({:.1} ms)", + k[K_CLZERO], + k[K_LOOP12], + k[K_LOOP15], + k[K_LOOP15_LINES], + k[K_MONITORX], + k[K_MWAITX], + k[K_OTHER], + w[0] / seconds, + w[1] / seconds / 1e3, + w[2] / seconds, + w[3] / seconds / 1e3, + w[4] / seconds, + w[5] / seconds / 1e3, + w[6] / seconds, + w[7] / seconds / 1e3, + ); +} + fn readable(va: usize, bytes: usize) -> bool { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery, + }; // SAFETY: plain data filled in by the query. let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; // SAFETY: a valid out pointer of the right size. let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; ASKED.fetch_add(1, Relaxed); - found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes + found + && m.State == MEM_COMMIT + && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 + && m.BaseAddress as usize + m.RegionSize >= va + bytes } fn writable(va: usize, bytes: usize) -> bool { @@ -67,12 +210,18 @@ fn writable(va: usize, bytes: usize) -> bool { /// on view memory opens as it does any write, and which is a crash otherwise (as the /// unchecked single-line emulation behind this one already is). fn writable_to(va: usize, end: usize) -> Option { - use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery}; + use windows_sys::Win32::System::Memory::{ + MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery, + }; let remember = remembers(); if remember { let (regions, answers) = WRITABLE.with(Cell::get); if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) { - let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) }; + let next = if answers >= ANSWERS { + ([(0, 0); 4], 0) + } else { + (regions, answers + 1) + }; WRITABLE.with(|w| w.set(next)); return Some(to.min(end)); } @@ -82,10 +231,14 @@ fn writable_to(va: usize, end: usize) -> Option { // SAFETY: a valid out pointer of the right size. let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0; ASKED.fetch_add(1, Relaxed); - if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 { + if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 + { return None; } - let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize); + let (from, to) = ( + m.BaseAddress as usize, + m.BaseAddress as usize + m.RegionSize, + ); if remember { WRITABLE.with(|w| { let (mut regions, answers) = w.get(); @@ -97,6 +250,99 @@ fn writable_to(va: usize, end: usize) -> Option { Some(to.min(end)) } +/// The register `r` of `ctx` (CONTEXT order: rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8..r15). +fn register(ctx: &mut CONTEXT, r: u8) -> &mut u64 { + match r & 15 { + 0 => &mut ctx.Rax, + 1 => &mut ctx.Rcx, + 2 => &mut ctx.Rdx, + 3 => &mut ctx.Rbx, + 4 => &mut ctx.Rsp, + 5 => &mut ctx.Rbp, + 6 => &mut ctx.Rsi, + 7 => &mut ctx.Rdi, + 8 => &mut ctx.R8, + 9 => &mut ctx.R9, + 10 => &mut ctx.R10, + 11 => &mut ctx.R11, + 12 => &mut ctx.R12, + 13 => &mut ctx.R13, + 14 => &mut ctx.R14, + _ => &mut ctx.R15, + } +} + +/// Where the lines of the loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb` end, +/// from the state the loop has at its `clzero`: the line at `rax` is zeroed now, and one +/// more at `ptr` for every pass the `cmp` sends back. None if this is not the plain case +/// the loop makes (the line at `rax` on a 64-byte boundary, `ptr` the next line, under +/// 2 GiB in all): then every line is taken alone, as the instruction itself does it. +fn loop15_end(rax: usize, ptr: usize, end: usize) -> Option { + if rax & 63 != 0 || ptr != rax.wrapping_add(64) || ptr < rax { + return None; + } + let more = if ptr < end { + (end - ptr).div_ceil(64) + } else { + 0 + }; + let last = ptr.checked_add(more.checked_mul(64)?)?; + (last - rax < 2 << 30).then_some(last) +} + +/// The `clzero` at `rip` in the loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb`, +/// with all the lines the loop would still zero: `Some(true)` when they are zeroed and the +/// registers stand as the loop leaves them at its last `clzero` (the caller steps over the +/// instruction; the title's own `cmp` and `jb` then leave the loop), `Some(false)` when the +/// first line is not writable (the real instruction faults there too), and when only a +/// first part was writable the registers stand at the line after it, where the instruction +/// runs again. None if it is not that loop: the lone instruction is emulated. +/// +/// # Safety +/// `rip` is the faulting instruction of `ctx`, whose bytes were read. +unsafe fn clzero_loop15(ctx: &mut CONTEXT, rip: usize, ptr_reg: u8, end_reg: u8) -> Option { + // The seven bytes in front of it: in the same page as the instruction, which ran. + if rip & 0xFFF < 7 && !readable(rip - 7, 7) { + return None; + } + // SAFETY: readable, as checked or as the instruction's own page. + let before = unsafe { std::slice::from_raw_parts((rip - 7) as *const u8, 7) }; + if !decode::loop15_head(before, ptr_reg) || end_reg == 0 || end_reg == ptr_reg { + return None; + } + let rax = ctx.Rax as usize; + let ptr = *register(ctx, ptr_reg) as usize; + let end = *register(ctx, end_reg) as usize; + let last = loop15_end(rax, ptr, end)?; + // Region by region, as the 12-byte loop: a block may lie across several views. + let mut at = rax; + while at < last { + let Some(to) = writable_to(at, last) else { + break; + }; + // A region ends on a page boundary, so `to` is on a line boundary as `at` is. + // SAFETY: committed and writable from `at` to `to`. + unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; + at = to; + } + if at == rax { + return Some(false); + } + ZEROED.fetch_add((at - rax) as u64, Relaxed); + KINDS[K_LOOP15_LINES].fetch_add(((at - rax) / 64) as u64, Relaxed); + if at < last { + // What follows is not writable: the loop stands at that line's `clzero` now, where + // the real one faults too. The instruction runs again (the caller must not step). + ctx.Rax = at as u64; + *register(ctx, ptr_reg) = (at + 64) as u64; + ctx.Rip = (rip as u64).wrapping_sub(3); + return Some(true); + } + ctx.Rax = (last - 64) as u64; + *register(ctx, ptr_reg) = last as u64; + Some(true) +} + /// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over /// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers /// see it). @@ -106,7 +352,11 @@ fn writable_to(va: usize, end: usize) -> Option { pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { let rip = ctx.Rip as usize; // The same few instructions fault again and again: their bytes are asked about once. - let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] }; + let known = if remembers() { + CODE.with(Cell::get) + } else { + [(0, 0); 8] + }; let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) { Some(&(_, n)) => n, None => { @@ -125,8 +375,11 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { }; // SAFETY: `n` bytes at `rip` are readable. let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) }; - let Some((what, len)) = decode::decode(code) else { return 0 }; - static SEEN: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + let Some((what, len)) = decode::decode(code) else { + return 0; + }; + static SEEN: std::sync::Mutex>> = + std::sync::Mutex::new(Vec::new()); if let Ok(mut seen) = SEEN.lock() && !seen.contains(&std::mem::discriminant(&what)) { @@ -149,9 +402,33 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } } } - ConsoleOnly::Monitorx => {} - ConsoleOnly::Mwaitx => std::hint::spin_loop(), - ConsoleOnly::Clzero => { + ConsoleOnly::Monitorx => { + KINDS[K_MONITORX].fetch_add(1, Relaxed); + MONITOR.with(|m| m.set((ctx.Rax as usize, ctx.Rsi))); + } + ConsoleOnly::Mwaitx => { + KINDS[K_MWAITX].fetch_add(1, Relaxed); + wait_step(); + std::hint::spin_loop() + } + ConsoleOnly::Clzero | ConsoleOnly::ClzeroStep { .. } => { + // The loop `mov rax, ptr; add ptr, 0x40; clzero; cmp ptr, end; jb` (the title's + // +0x4e8ab4c and three more like it zero 896 to 7,040 bytes each, a line an + // exception) is taken whole from the line it stands at. + if let ConsoleOnly::ClzeroStep { ptr_reg, end_reg } = what + && loop15() + && let Some(done) = unsafe { clzero_loop15(ctx, rip, ptr_reg, end_reg) } + { + if !done { + return 0; + } + ctx.Rip += len as u64; + EMULATED.fetch_add(1, Relaxed); + KINDS[K_LOOP15].fetch_add(1, Relaxed); + line(); + return CONTINUE_EXECUTION; + } + KINDS[K_CLZERO].fetch_add(1, Relaxed); // with an address-size prefix (0x67) the line is at EAX, zero-extended let a32 = code[..len - 3].contains(&0x67); let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63; @@ -162,9 +439,11 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) }; } ConsoleOnly::ClzeroLoop { end_reg } => { + KINDS[K_LOOP12].fetch_add(1, Relaxed); // the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once let regs: [u64; 16] = [ - ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, + ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, + ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15, ]; let end = regs[end_reg as usize & 15] as usize; let start = ctx.Rax as usize; @@ -174,7 +453,9 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { // which every 64-byte line took an exception of its own. let mut at = start; while at < end { - let Some(to) = writable_to(at, end) else { break }; + let Some(to) = writable_to(at, end) else { + break; + }; // SAFETY: committed and writable from `at` to `to`. unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) }; at = to; @@ -202,10 +483,25 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } ConsoleOnly::Rdpid(r) => { // SAFETY: no preconditions. - let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64; + let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } + as u64; let regs: [&mut u64; 16] = [ - &mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13, - &mut ctx.R14, &mut ctx.R15, + &mut ctx.Rax, + &mut ctx.Rcx, + &mut ctx.Rdx, + &mut ctx.Rbx, + &mut ctx.Rsp, + &mut ctx.Rbp, + &mut ctx.Rsi, + &mut ctx.Rdi, + &mut ctx.R8, + &mut ctx.R9, + &mut ctx.R10, + &mut ctx.R11, + &mut ctx.R12, + &mut ctx.R13, + &mut ctx.R14, + &mut ctx.R15, ]; *regs[r as usize & 15] = cpu; } @@ -224,16 +520,37 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { d.Low = decode::extrq(d.Low, len, idx); d.High = 0; } - ConsoleOnly::Insertq { dst, src, reg, len, idx } => { + ConsoleOnly::Insertq { + dst, + src, + reg, + len, + idx, + } => { // SAFETY: as above. let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters }; let s = x[src as usize & 15]; - let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) }; + let (len, idx) = if reg { + (s.High as u8, (s.High >> 8) as u8) + } else { + (len, idx) + }; let d = &mut x[dst as usize & 15]; d.Low = decode::insertq(d.Low, s.Low, len, idx); d.High = 0; } } + if !matches!( + what, + ConsoleOnly::Monitorx + | ConsoleOnly::Mwaitx + | ConsoleOnly::Clzero + | ConsoleOnly::ClzeroStep { .. } + | ConsoleOnly::ClzeroLoop { .. } + ) { + KINDS[K_OTHER].fetch_add(1, Relaxed); + } + line(); ctx.Rip += len as u64; // How often this runs at all (each one is an exception: a trip into Windows and back). let emulated = EMULATED.fetch_add(1, Relaxed) + 1; @@ -247,3 +564,151 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 { } CONTINUE_EXECUTION } + +#[cfg(test)] +mod tests { + use super::*; + + /// What the title's loop leaves, run line by line as the processor would: the lines it + /// zeroed and the registers (rax, ptr) at the end, from the state at its first `clzero`. + fn by_hand(mut rax: usize, mut ptr: usize, end: usize) -> (Vec, usize, usize) { + let mut lines = vec![rax & !63]; + while ptr < end { + rax = ptr; + ptr += 0x40; + lines.push(rax & !63); + } + (lines, rax, ptr) + } + + #[test] + fn the_15_byte_loop_ends_where_the_processor_would_end_it() { + for (rax, len) in [ + (0x1000usize, 7040usize), + (0x1000, 3264), + (0x1000, 3776), + (0x1000, 896), + (0x4000, 64), + (0x4000, 65), + (0x4000, 100), + (0x4000, 1), + (0x4000, 0), + (0x8000, 128), + ] { + let (ptr, end) = (rax + 64, rax + len); + let (lines, last_rax, last_ptr) = by_hand(rax, ptr, end); + let last = loop15_end(rax, ptr, end).expect("the plain case"); + assert_eq!(last, last_ptr, "rax {rax:#x} len {len}"); + assert_eq!(last - 64, last_rax, "rax {rax:#x} len {len}"); + assert_eq!((last - rax) / 64, lines.len(), "rax {rax:#x} len {len}"); + assert_eq!(*lines.last().unwrap(), last - 64); + } + // an end before the pointer: the line at rax alone + assert_eq!(loop15_end(0x1000, 0x1040, 0x800), Some(0x1040)); + // not the plain case: a line not on a boundary, a pointer that is not the next line + assert_eq!(loop15_end(0x1008, 0x1048, 0x2000), None); + assert_eq!(loop15_end(0x1000, 0x1080, 0x2000), None); + assert_eq!( + loop15_end(0x1000, 0x1040, 0x1000 + (3 << 30)), + None, + "over 2 GiB" + ); + } + + /// The loop as the title has it at +0x4e8ab4c, for the given registers. + fn code(ptr_reg: u8, end_reg: u8) -> Vec { + let (ph, pl, eh, el) = (ptr_reg >> 3, ptr_reg & 7, end_reg >> 3, end_reg & 7); + vec![ + 0x48 | ph << 2, + 0x89, + 0xC0 | pl << 3, // mov rax, ptr + 0x48 | ph, + 0x83, + 0xC0 | pl, + 0x40, // add ptr, 0x40 + 0x0F, + 0x01, + 0xFC, // clzero + 0x48 | eh << 2 | ph, + 0x39, + 0xC0 | el << 3 | pl, // cmp ptr, end + 0x72, + 0xF1, // jb -15 + 0x90, + ] + } + + #[test] + fn the_15_byte_loop_is_zeroed_whole_and_leaves_the_loop_s_registers() { + for (ptr_reg, end_reg, len) in [ + (10u8, 11u8, 7040usize), + (9, 10, 3264), + (8, 9, 3776), + (2, 8, 896), + (10, 11, 64), + (10, 11, 100), + ] { + let code = code(ptr_reg, end_reg); + // a block of 0xAA with room on both sides, its start on a line boundary + let mut block = vec![0xAAu8; 16384]; + let base = (block.as_mut_ptr() as usize + 4096 + 63) & !63; + // SAFETY: plain data. + let mut ctx: CONTEXT = unsafe { std::mem::zeroed() }; + ctx.Rip = code.as_ptr() as u64 + 7; + ctx.Rax = base as u64; + *register(&mut ctx, ptr_reg) = base as u64 + 64; + *register(&mut ctx, end_reg) = (base + len) as u64; + // SAFETY: the context points at the code above. + assert_eq!(unsafe { emulate(&mut ctx) }, CONTINUE_EXECUTION); + let (lines, last_rax, last_ptr) = by_hand(base, base + 64, base + len); + assert_eq!(ctx.Rip, code.as_ptr() as u64 + 10, "at the loop's own cmp"); + assert_eq!(ctx.Rax as usize, last_rax); + assert_eq!(*register(&mut ctx, ptr_reg) as usize, last_ptr); + assert_eq!( + *register(&mut ctx, end_reg) as usize, + base + len, + "the end is left alone" + ); + let zeroed = lines.len() * 64; + let at = base - block.as_ptr() as usize; + assert!( + block[at..at + zeroed].iter().all(|&b| b == 0), + "{zeroed} bytes zeroed" + ); + assert!( + block[..at].iter().all(|&b| b == 0xAA), + "nothing before the block" + ); + assert!( + block[at + zeroed..].iter().all(|&b| b == 0xAA), + "nothing after its last line" + ); + } + } + + #[test] + fn a_clzero_that_only_looks_like_the_loop_is_one_line() { + // the same bytes behind it, another head in front (add ptr, 0x80): one line, one step + let mut code = code(10, 11); + code[6] = 0x80; + let mut block = vec![0xAAu8; 8192]; + let base = (block.as_mut_ptr() as usize + 2048 + 63) & !63; + // SAFETY: plain data. + let mut ctx: CONTEXT = unsafe { std::mem::zeroed() }; + ctx.Rip = code.as_ptr() as u64 + 7; + ctx.Rax = base as u64; + ctx.R10 = base as u64 + 64; + ctx.R11 = base as u64 + 640; + // SAFETY: the context points at the code above. + assert_eq!(unsafe { emulate(&mut ctx) }, CONTINUE_EXECUTION); + assert_eq!(ctx.Rip, code.as_ptr() as u64 + 10); + assert_eq!( + (ctx.Rax, ctx.R10), + (base as u64, base as u64 + 64), + "registers untouched" + ); + let at = base - block.as_ptr() as usize; + assert!(block[at..at + 64].iter().all(|&b| b == 0)); + assert!(block[at + 64..].iter().all(|&b| b == 0xAA), "one line only"); + } +} diff --git a/crates/victory-loader/src/console_insn_decode.rs b/crates/victory-loader/src/console_insn_decode.rs index 08142f8b..234d971a 100644 --- a/crates/victory-loader/src/console_insn_decode.rs +++ b/crates/victory-loader/src/console_insn_decode.rs @@ -12,7 +12,16 @@ pub enum ConsoleOnly { /// `clzero`: zero the 64-byte cache line at rAX Clzero, /// `clzero` loop: `clzero; add rax, 0x40; cmp rax, ; jb -12` – zero `[rax..reg)` - ClzeroLoop { end_reg: u8 }, + ClzeroLoop { + end_reg: u8, + }, + /// `clzero` in the loop `mov rax, ; add , 0x40; clzero; cmp , ; jb -15` + /// (the seven bytes before it are the caller's to check, [`loop15_head`]): the length is + /// the `clzero`'s own + ClzeroStep { + ptr_reg: u8, + end_reg: u8, + }, /// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter) Rdpru, /// `monitorx` / `mwaitx`: a wait the emulation skips @@ -24,11 +33,22 @@ pub enum ConsoleOnly { /// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the /// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved /// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15. - Extrq { dst: u8, src: Option, len: u8, idx: u8 }, + Extrq { + dst: u8, + src: Option, + len: u8, + idx: u8, + }, /// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`: /// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a /// bit field of xmm1's low quadword. - Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 }, + Insertq { + dst: u8, + src: u8, + reg: bool, + len: u8, + idx: u8, + }, /// `ud2`: the title's own trap (not emulated) Ud2, } @@ -56,7 +76,11 @@ pub fn extrq(v: u64, len: u8, idx: u8) -> u64 { /// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`. pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 { let (len, idx) = (field_len(len), (idx & 63) as u32); - let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 }; + let ones = if len >= 64 { + u64::MAX + } else { + (1u64 << len) - 1 + }; let mask = ones.checked_shl(idx).unwrap_or(0); (dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask) } @@ -84,6 +108,24 @@ fn modrm_len(b: &[u8]) -> Option { (b.len() >= len).then_some(len) } +/// Whether `before`, the seven bytes in front of a [`ConsoleOnly::ClzeroStep`], are +/// `mov rax, ; add , 0x40` for that pointer register (neither rax nor rsp). +pub fn loop15_head(before: &[u8], ptr_reg: u8) -> bool { + let (hi, lo) = (ptr_reg >> 3 & 1, ptr_reg & 7); + ptr_reg != 0 + && ptr_reg != 4 + && before.len() == 7 + // mov rax, ptr: REX.W (+R for r8..r15) 89 /r with rm = rax + && before[0] == 0x48 | hi << 2 + && before[1] == 0x89 + && before[2] == 0xC0 | lo << 3 + // add ptr, 0x40: REX.W (+B) 83 /0 ib + && before[3] == 0x48 | hi + && before[4] == 0x83 + && before[5] == 0xC0 | lo + && before[6] == 0x40 +} + /// The console-only instruction at the start of `code` and its length. pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { let mut i = 0; @@ -128,6 +170,19 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { let modrm = code[i + 9]; let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 }; Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12)) + } else if i == 0 + && code.len() >= 8 + && code[3] & 0xF8 == 0x48 + && code[3] & 0x02 == 0 + && code[4] == 0x39 + && code[5] >> 6 == 3 + && code[6..8] == [0x72, 0xF1] + { + // clzero; cmp , (REX.W 39 /r, register form); jb -15 + let (rex, modrm) = (code[3], code[5]); + let end_reg = ((modrm >> 3) & 7) | (rex & 4) << 1; + let ptr_reg = (modrm & 7) | (rex & 1) << 3; + Some((ConsoleOnly::ClzeroStep { ptr_reg, end_reg }, 3)) } else { Some((ConsoleOnly::Clzero, i + 3)) } @@ -144,22 +199,59 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> { let imm = |k: usize| code.get(i + 3 + k).copied(); match (code[i + 1], rep == 0xF2) { // extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0 - (0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)), - (0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)), - (0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)), - (0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)), + (0x78, false) if (m >> 3) & 7 == 0 => Some(( + ConsoleOnly::Extrq { + dst: rm, + src: None, + len: imm(0)?, + idx: imm(1)?, + }, + i + 5, + )), + (0x79, false) => Some(( + ConsoleOnly::Extrq { + dst: reg, + src: Some(rm), + len: 0, + idx: 0, + }, + i + 3, + )), + (0x78, true) => Some(( + ConsoleOnly::Insertq { + dst: reg, + src: rm, + reg: false, + len: imm(0)?, + idx: imm(1)?, + }, + i + 5, + )), + (0x79, true) => Some(( + ConsoleOnly::Insertq { + dst: reg, + src: rm, + reg: true, + len: 0, + idx: 0, + }, + i + 3, + )), _ => None, } } // 66 0F AE /6 with a memory operand (without 66 it is xsaveopt) - (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)), + (0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => { + Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)) + } // F3 0F C7 /7 with a register operand - (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)), + (0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => { + Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)) + } _ => None, } } - #[cfg(test)] mod tests { use super::*; @@ -170,10 +262,20 @@ mod tests { assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC); assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0); assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1); - assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF); + assert_eq!( + insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), + 0xFFFF_FFFF_FFFF_ABFF + ); assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000); - assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000); - for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] { + assert_eq!( + insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), + 0xDEAD_BEEF_0000_0000 + ); + for (v, len, idx) in [ + (0x0123_4567_89AB_CDEFu64, 12u8, 20u8), + (u64::MAX, 63, 1), + (0x55, 3, 0), + ] { assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0)); } } @@ -183,47 +285,223 @@ mod tests { assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3))); // clzero loop against r10 (4C 39 D0 = cmp rax, r10) assert_eq!( - decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]), + decode(&[ + 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4 + ]), Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12)) ); // clzero loop against rdx (48 39 D0 = cmp rax, rdx) assert_eq!( - decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), + decode(&[ + 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4 + ]), Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12)) ); // the same loop after an address-size prefix: that one CLZERO alone - assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!( + decode(&[ + 0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4 + ]), + Some((ConsoleOnly::Clzero, 4)) + ); + // the title's other loop, as at its +0x4e8ab4c: mov rax, r10; add r10, 0x40; clzero; + // cmp r10, r11; jb -15 (and against r9/r10, r8/r9, rdx/r8) + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xDA, 0x72, 0xF1]), + Some(( + ConsoleOnly::ClzeroStep { + ptr_reg: 10, + end_reg: 11 + }, + 3 + )) + ); + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xD1, 0x72, 0xF1]), + Some(( + ConsoleOnly::ClzeroStep { + ptr_reg: 9, + end_reg: 10 + }, + 3 + )) + ); + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xC8, 0x72, 0xF1]), + Some(( + ConsoleOnly::ClzeroStep { + ptr_reg: 8, + end_reg: 9 + }, + 3 + )) + ); + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x4C, 0x39, 0xC2, 0x72, 0xF1]), + Some(( + ConsoleOnly::ClzeroStep { + ptr_reg: 2, + end_reg: 8 + }, + 3 + )) + ); + assert!(loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x40], 10)); + assert!(loop15_head(&[0x4C, 0x89, 0xC8, 0x49, 0x83, 0xC1, 0x40], 9)); + assert!(loop15_head(&[0x4C, 0x89, 0xC0, 0x49, 0x83, 0xC0, 0x40], 8)); + assert!(loop15_head(&[0x48, 0x89, 0xD0, 0x48, 0x83, 0xC2, 0x40], 2)); + assert!( + !loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x40], 9), + "another register" + ); + assert!( + !loop15_head(&[0x4C, 0x89, 0xD0, 0x49, 0x83, 0xC2, 0x80], 10), + "another step" + ); + // not that loop: another jump back, a memory operand, a 32-bit compare + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0xDA, 0x72, 0xF4]), + Some((ConsoleOnly::Clzero, 3)) + ); + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x4D, 0x39, 0x1A, 0x72, 0xF1]), + Some((ConsoleOnly::Clzero, 3)) + ); + assert_eq!( + decode(&[0x0F, 0x01, 0xFC, 0x45, 0x39, 0xDA, 0x72, 0xF1]), + Some((ConsoleOnly::Clzero, 3)) + ); assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3))); - assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3))); + assert_eq!( + decode(&[0x0F, 0x01, 0xFA]), + Some((ConsoleOnly::Monitorx, 3)) + ); assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3))); assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2))); // clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8] - assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4))); - assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5))); - assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6))); - assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8))); - assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5))); + assert_eq!( + decode(&[0x66, 0x0F, 0xAE, 0x30]), + Some((ConsoleOnly::Clwb, 4)) + ); + assert_eq!( + decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), + Some((ConsoleOnly::Clwb, 5)) + ); + assert_eq!( + decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), + Some((ConsoleOnly::Clwb, 6)) + ); + assert_eq!( + decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), + Some((ConsoleOnly::Clwb, 8)) + ); + assert_eq!( + decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), + Some((ConsoleOnly::Clwb, 5)) + ); // rdpid rax; rdpid r9 - assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4))); - assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5))); + assert_eq!( + decode(&[0xF3, 0x0F, 0xC7, 0xF8]), + Some((ConsoleOnly::Rdpid(0), 4)) + ); + assert_eq!( + decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), + Some((ConsoleOnly::Rdpid(9), 5)) + ); // not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes // SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes) - assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6))); - assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5))); - assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6))); - assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4))); - assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing"); - assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a"); + assert_eq!( + decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), + Some(( + ConsoleOnly::Insertq { + dst: 0, + src: 1, + reg: false, + len: 8, + idx: 16 + }, + 6 + )) + ); + assert_eq!( + decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), + Some(( + ConsoleOnly::Insertq { + dst: 8, + src: 9, + reg: true, + len: 0, + idx: 0 + }, + 5 + )) + ); + assert_eq!( + decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), + Some(( + ConsoleOnly::Extrq { + dst: 2, + src: None, + len: 4, + idx: 8 + }, + 6 + )) + ); + assert_eq!( + decode(&[0x66, 0x0F, 0x79, 0xCA]), + Some(( + ConsoleOnly::Extrq { + dst: 1, + src: Some(2), + len: 0, + idx: 0 + }, + 4 + )) + ); + assert_eq!( + decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), + None, + "an immediate missing" + ); + assert_eq!( + decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), + None, + "VMREAD without a prefix is not SSE4a" + ); // prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next // to them does not; 0x67 and a REX before a legacy prefix are ignored - let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7)); - for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] { + let insertq = Some(( + ConsoleOnly::Insertq { + dst: 0, + src: 1, + reg: false, + len: 16, + idx: 16, + }, + 7, + )); + for code in [ + [0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], + [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], + [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], + [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], + [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], + ] { assert_eq!(decode(&code), insertq, "{code:02x?}"); } - for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] { + for code in [ + [0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], + [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], + [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10], + ] { assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}"); } - assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4))); + assert_eq!( + decode(&[0x67, 0x0F, 0x01, 0xFC]), + Some((ConsoleOnly::Clzero, 4)) + ); assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None); assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None); assert_eq!(decode(&[0x48, 0x8B, 0x01]), None); diff --git a/crates/victory-loader/src/crash.rs b/crates/victory-loader/src/crash.rs index 3f77a884..6cb7e915 100644 --- a/crates/victory-loader/src/crash.rs +++ b/crates/victory-loader/src/crash.rs @@ -64,8 +64,11 @@ pub fn log_crashes_to(file: std::path::PathBuf) { /// Appends a failure that is not an exception (the host GPU's) to the crash /// log, with the title's last debug output, and prints it. pub fn log_crash(text: &str) { - let text = format!("{text} -{}", title_output()); + let text = format!( + "{text} +{}", + title_output() + ); eprint!("{text}"); append_to_log(&text); } @@ -76,9 +79,16 @@ fn append_to_log(text: &str) { let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs()); - let opened = std::fs::OpenOptions::new().create(true).append(true).open(file); + let opened = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(file); if let Ok(mut f) = opened { - let _ = write!(f, "unix time {now}, process {}\n{text}\n", std::process::id()); + let _ = write!( + f, + "unix time {now}, process {}\n{text}\n", + std::process::id() + ); } } @@ -105,7 +115,9 @@ fn title_output() -> String { let Ok(said) = SAID.try_lock() else { return String::new(); }; - said.iter().map(|l| format!(" title said: {l}\n")).collect() + said.iter() + .map(|l| format!(" title said: {l}\n")) + .collect() } /// Installs the handlers; call once before running title code. @@ -336,12 +348,20 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option { ((b(at + 3), b(at + 4)), at + 5) } else { // extrq reads its fields from src's low half, insertq from its high. - let f = if prefix == 0x66 { xmm[src].Low } else { xmm[src].High as u64 }; + let f = if prefix == 0x66 { + xmm[src].Low + } else { + xmm[src].High as u64 + }; ((f as u8, (f >> 8) as u8), at + 3) }; let (n, at_bit) = (u32::from(fields.0 & 63), u32::from(fields.1 & 63)); let bits = if n == 0 { 64 } else { n }; - let mask = if bits == 64 { u64::MAX } else { (1u64 << bits) - 1 }; + let mask = if bits == 64 { + u64::MAX + } else { + (1u64 << bits) - 1 + }; if prefix == 0x66 { // extrq: register form takes its fields from src, works on dst. if immediate && (modrm >> 3) & 7 != 0 { @@ -423,8 +443,7 @@ unsafe fn thrown(p: &[usize]) -> String { let types = p[3] + rva(p[2] + 12); let name = |i: usize| { let descriptor = p[3] + rva(p[3] + rva(types + 4 + 4 * i) + 4); - std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char) - .to_string_lossy() + std::ffi::CStr::from_ptr((descriptor + 16) as *const std::ffi::c_char).to_string_lossy() }; let first = name(0); let value = match &*first { diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index b87d6c03..6ee4d414 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -38,12 +38,12 @@ mod tls; #[cfg(windows)] mod windows; +#[cfg(all(windows, feature = "diagnostics"))] +pub use crash::save_on_crash; #[cfg(windows)] pub use crash::{ locate, log_crash, log_crashes_to, note_title_output, report_crashes, report_unhandled, }; -#[cfg(all(windows, feature = "diagnostics"))] -pub use crash::save_on_crash; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(all(windows, feature = "diagnostics"))] diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs index 903aebd4..a7a85d04 100644 --- a/crates/victory-loader/src/threads.rs +++ b/crates/victory-loader/src/threads.rs @@ -164,8 +164,8 @@ fn end_other_threads(keep: &[u32]) { CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; use windows_sys::Win32::System::Threading::{ - GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_TERMINATE, TerminateThread, - THREAD_QUERY_INFORMATION, + GetCurrentProcessId, GetCurrentThreadId, OpenThread, THREAD_QUERY_INFORMATION, + THREAD_TERMINATE, TerminateThread, }; // SAFETY: plain queries of the calling process and thread. let (process, me) = unsafe { (GetCurrentProcessId(), GetCurrentThreadId()) }; @@ -323,7 +323,10 @@ impl OwnTls { /// title callbacks. fn started_by_rust() -> bool { // SAFETY: the calling thread's pseudo handle. - starts_in(unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, c"") + starts_in( + unsafe { windows_sys::Win32::System::Threading::GetCurrentThread() }, + c"", + ) } /// Whether `thread`'s start routine lies in the module named `module` diff --git a/crates/victory-shader/build.rs b/crates/victory-shader/build.rs index b1021250..1ddca857 100644 --- a/crates/victory-shader/build.rs +++ b/crates/victory-shader/build.rs @@ -41,7 +41,11 @@ fn main() { let mut state = [0xcbf2_9ce4_8422_2325u64, 0x8422_2325_cbf2_9ce4u64]; let mut switches = std::collections::BTreeSet::new(); for p in &list { - let rel = p.strip_prefix(&src).unwrap_or(p).to_string_lossy().replace('\\', "/"); + let rel = p + .strip_prefix(&src) + .unwrap_or(p) + .to_string_lossy() + .replace('\\', "/"); let text = std::fs::read(p).unwrap_or_default(); fnv(&mut state, rel.as_bytes()); fnv(&mut state, &(text.len() as u64).to_le_bytes()); @@ -59,7 +63,13 @@ fn main() { rest = &tail[end..]; } } - println!("cargo:rustc-env=VICTORY_SHADER_SOURCE_HASH={:016x}{:016x}", state[0], state[1]); + println!( + "cargo:rustc-env=VICTORY_SHADER_SOURCE_HASH={:016x}{:016x}", + state[0], state[1] + ); let joined: Vec<_> = switches.into_iter().collect(); - println!("cargo:rustc-env=VICTORY_SHADER_SWITCHES={}", joined.join(",")); + println!( + "cargo:rustc-env=VICTORY_SHADER_SWITCHES={}", + joined.join(",") + ); } diff --git a/crates/victory-shader/src/emit/lower.rs b/crates/victory-shader/src/emit/lower.rs index 2e8b418c..4404651a 100644 --- a/crates/victory-shader/src/emit/lower.rs +++ b/crates/victory-shader/src/emit/lower.rs @@ -1665,7 +1665,9 @@ impl<'a> Lower<'a> { // first half only the second half reads is gone before lowering. // Only in the second translation of a program the first // one refused for it ([`with_first_half_pairs`]). - if FIRST_HALF_PAIRS.get() && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") { + if FIRST_HALF_PAIRS.get() + && std::env::var_os("VICTORY_FIRST_HALF").is_none_or(|v| v != "0") + { for (_, i) in &x.io.interps { if let Interp::Interpolated { first, .. } = i { for s in first { @@ -2330,9 +2332,16 @@ impl<'a> Lower<'a> { self.s.flags |= flags::WAVE_OPS; let four = self.s.m.named_struct("dx.types.fouri32", vec![i32t; 4]); let here = self.s.m.bool(true); - let ballot = self.s.op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); - let (blo, bhi) = (self.s.m.extract(c, ballot, 0), self.s.m.extract(c, ballot, 1)); - let lane = self.s.op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); + let ballot = self + .s + .op(c, "waveActiveBallot", Attr::NoUnwind, four, 116, &[here]); + let (blo, bhi) = ( + self.s.m.extract(c, ballot, 0), + self.s.m.extract(c, ballot, 1), + ); + let lane = self + .s + .op(c, "waveGetLaneIndex", Attr::ReadOnly, i32t, 111, &[]); let [zero, k31, k32] = [0, 31, 32].map(|k| self.s.m.i32(k)); // The lanes of the run of `size` lanes at `base` that are here, from bit 0. let present = |l: &mut Self, base: V, size: u32| -> V { @@ -2355,7 +2364,9 @@ impl<'a> Lower<'a> { let base = self.s.m.bin(c, Bin::And, other, run); let bits = present(self, base, size); // FirstbitLo (dx.op 32): the run's first lane that is here - let first = self.s.op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); + let first = self + .s + .op(c, "unaryBits.i32", Attr::ReadNone, i32t, 32, &[bits]); let any = self.s.m.cmp(c, pred::NE, bits, zero); let first = self.s.m.select(c, any, first, zero); let from = self.s.m.bin(c, Bin::Add, base, first); @@ -2363,7 +2374,11 @@ impl<'a> Lower<'a> { let theirs = self.s.m.select(c, any, theirs, zero); sum = self.add_halves(sum, theirs); } - let (high, low, one) = (self.s.m.i32(0xFFFF_0000), self.s.m.i32(0xFFFF), self.s.m.i32(1)); + let (high, low, one) = ( + self.s.m.i32(0xFFFF_0000), + self.s.m.i32(0xFFFF), + self.s.m.i32(1), + ); let lane0 = self.s.m.bin(c, Bin::And, blo, one); let lane0 = self.s.m.cmp(c, pred::NE, lane0, zero); let first = self.read_lane(x, zero); @@ -6092,117 +6107,118 @@ impl<'a> Lower<'a> { let (first, props, image, uav, used) = if let Some(kind) = unused { kind } else { - let Some((at, first)) = use_at else { - // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only - // copies its dwords and compares them, lane against first lane, and every load - // that reaches those lanes reads one address. Each dword stands in as its place - // in the table, so the lanes compare equal as they do on the console. - if self.x.res.lane_copied.contains(&site) - && let Some(a) = self.scalar.get(&site).copied() - { - for k in 0..count { - let x = self.s.m.i32(a.offset / 4 + k); - self.write(inst, Reg::S(code + k as u8), x, None); + let Some((at, first)) = use_at else { + // A descriptor kept per lane in VGPRs (`Resources::lane_copied`): the code only + // copies its dwords and compares them, lane against first lane, and every load + // that reaches those lanes reads one address. Each dword stands in as its place + // in the table, so the lanes compare equal as they do on the console. + if self.x.res.lane_copied.contains(&site) + && let Some(a) = self.scalar.get(&site).copied() + { + for k in 0..count { + let x = self.s.m.i32(a.offset / 4 + k); + self.write(inst, Reg::S(code + k as u8), x, None); + } + return Ok(()); } - return Ok(()); - } - // A sampler's descriptor: no program reads its dwords as numbers, so where one - // meets numbers at a join the register is dead on that path (`dead`), as a - // descriptor's address or format is. - let sampler = x.res.descriptors.iter().any(|d| { - d.role == Role::Sampler - && d.source - .leaves() - .into_iter() - .any(|l| matches!(*l, Source::Loaded { load, .. } if load == site)) - }); - if sampler { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a sampler's descriptor read as data"); - } - // A buffer view the code only takes the address of, to walk - // the memory behind it (a ray-tracing structure): the address - // from the host, the other dwords have no value. - if count <= 4 - && let Some((lo, hi)) = self.view_address(site) - { - for k in 0..count { - let reg = Reg::S(code + k as u8); - match k { - 0 => self.write(inst, reg, lo, None), - 1 => self.write(inst, reg, hi, None), - _ => { - if let Some(v) = inst.write(reg) { - self.vals.insert(v, Val::Missing(OTHER)); - self.stale.insert(v); + // A sampler's descriptor: no program reads its dwords as numbers, so where one + // meets numbers at a join the register is dead on that path (`dead`), as a + // descriptor's address or format is. + let sampler = x.res.descriptors.iter().any(|d| { + d.role == Role::Sampler + && d.source + .leaves() + .into_iter() + .any(|l| matches!(*l, Source::Loaded { load, .. } if load == site)) + }); + if sampler { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a sampler's descriptor read as data"); + } + // A buffer view the code only takes the address of, to walk + // the memory behind it (a ray-tracing structure): the address + // from the host, the other dwords have no value. + if count <= 4 + && let Some((lo, hi)) = self.view_address(site) + { + for k in 0..count { + let reg = Reg::S(code + k as u8); + match k { + 0 => self.write(inst, reg, lo, None), + 1 => self.write(inst, reg, hi, None), + _ => { + if let Some(v) = inst.write(reg) { + self.vals.insert(v, Val::Missing(OTHER)); + self.stale.insert(v); + } } } } + return Ok(()); } - return Ok(()); - } - if std::env::var_os("VICTORY_DESC_WHY").is_some() { - eprintln!( - "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", - inst.machine.offset, - inst.name(), - address, - self.x.res.lane_copied.contains(&site) - ); - } - return Err("a descriptor read only as data"); - }; - let src = Source::Loaded { load: site, first }; - let used = self.used_kind(&src); - let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; - let un = ui.name(); - let uav = un.contains("store") - || un.contains("atomic") - || used.is_some_and(|u| u.kind == ResourceType::Uav); - let u = if uav { 0x1000 } else { 0 }; - let (props, image) = match &ui.fields { - // A ray-tracing structure in a buffer of the host: read raw. - Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), - Fields::Image { dim, .. } => { - let kind = match dim { - 0 => 1, - 1 => 2, - 2 => 4, - 4 => 6, - 5 => 7, - _ => return Err("an image dimension (cube or MSAA)"), - }; - ((kind | u, 0x409), Some(kind)) - } - Fields::Buffer { idxen, format, .. } => { - let stride = used.map_or(0, |u| u.stride); - let props = if un.starts_with("buffer_load_format") - || un.starts_with("buffer_store_format") - { - (10 | u, 0x409) - } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) { - (12 | u, stride) - } else { - (11 | u, 0) - }; - if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + if std::env::var_os("VICTORY_DESC_WHY").is_some() { + eprintln!( + "DESC-WHY {:#x} {} scalar={:?} lane_copied={}", + inst.machine.offset, + inst.name(), + address, + self.x.res.lane_copied.contains(&site) + ); + } + return Err("a descriptor read only as data"); + }; + let src = Source::Loaded { load: site, first }; + let used = self.used_kind(&src); + let ui: &Inst = &self.x.p.blocks[at.0].insts[at.1]; + let un = ui.name(); + let uav = un.contains("store") + || un.contains("atomic") + || used.is_some_and(|u| u.kind == ResourceType::Uav); + let u = if uav { 0x1000 } else { 0 }; + let (props, image) = match &ui.fields { + // A ray-tracing structure in a buffer of the host: read raw. + Fields::Image { .. } if un.starts_with("image_bvh") => ((11, 0), None), + Fields::Image { dim, .. } => { + let kind = match dim { + 0 => 1, + 1 => 2, + 2 => 4, + 4 => 6, + 5 => 7, + _ => return Err("an image dimension (cube or MSAA)"), + }; + ((kind | u, 0x409), Some(kind)) + } + Fields::Buffer { idxen, format, .. } => { + let stride = used.map_or(0, |u| u.stride); + let props = if un.starts_with("buffer_load_format") + || un.starts_with("buffer_store_format") + { + (10 | u, 0x409) + } else if *idxen && format.is_none() && stride >= 4 && stride.is_multiple_of(4) + { + (12 | u, stride) + } else { + (11 | u, 0) + }; + if used.is_some_and(|u| u.kind == ResourceType::Cbv) { + self.stale.extend(inst.writes.iter().map(|w| w.1)); + return Err("a constant buffer's descriptor read as data"); + } + (props, None) + } + // Read by scalar buffer loads alone: the raw view `smem` reads it through. + Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { + ((11, 0), None) + } + // A constant buffer: nothing of its descriptor is a number. + Fields::Smem { .. } => { self.stale.extend(inst.writes.iter().map(|w| w.1)); return Err("a constant buffer's descriptor read as data"); } - (props, None) - } - // Read by scalar buffer loads alone: the raw view `smem` reads it through. - Fields::Smem { .. } if used.is_some_and(|u| u.kind == ResourceType::Srv) => { - ((11, 0), None) - } - // A constant buffer: nothing of its descriptor is a number. - Fields::Smem { .. } => { - self.stale.extend(inst.writes.iter().map(|w| w.1)); - return Err("a constant buffer's descriptor read as data"); - } - _ => return Err("a scalar memory read as data"), - }; - (first, props, image, uav, used) + _ => return Err("a scalar memory read as data"), + }; + (first, props, image, uav, used) }; let src = Source::Loaded { load: site, first }; let h = self.handle(site, &src, false, props)?; @@ -6320,9 +6336,10 @@ impl<'a> Lower<'a> { if self.x.res.lane_copied.contains(&site) || self.x.res.descriptors.iter().any(|d| { d.role == Role::Sampler - && d.source.leaves().into_iter().any( - |l| matches!(*l, Source::Loaded { load, .. } if load == site), - ) + && d.source + .leaves() + .into_iter() + .any(|l| matches!(*l, Source::Loaded { load, .. } if load == site)) }) { return None; @@ -11882,6 +11899,5 @@ include!("lower/mesh_emulation.rs"); #[cfg(test)] include!("lower/tests.rs"); - #[cfg(test)] include!("lower/code_table_tests.rs"); diff --git a/crates/victory-shader/src/emit/mod.rs b/crates/victory-shader/src/emit/mod.rs index e1db5764..630e2d14 100644 --- a/crates/victory-shader/src/emit/mod.rs +++ b/crates/victory-shader/src/emit/mod.rs @@ -207,7 +207,10 @@ pub fn translation_fingerprint() -> Vec { out.extend_from_slice(env!("VICTORY_SHADER_SOURCE_HASH").as_bytes()); out.push(u8::from(cfg!(feature = "diagnostics"))); out.push(u8::from(cfg!(debug_assertions))); - for name in env!("VICTORY_SHADER_SWITCHES").split(',').filter(|n| !n.is_empty()) { + for name in env!("VICTORY_SHADER_SWITCHES") + .split(',') + .filter(|n| !n.is_empty()) + { out.extend_from_slice(name.as_bytes()); out.push(b'='); if let Some(value) = std::env::var_os(name) { diff --git a/crates/victory-shader/src/emit/own_bits.rs b/crates/victory-shader/src/emit/own_bits.rs index 64aaba8f..f17efa56 100644 --- a/crates/victory-shader/src/emit/own_bits.rs +++ b/crates/victory-shader/src/emit/own_bits.rs @@ -173,7 +173,9 @@ fn effect(inst: &Inst) -> bool { || name.contains("store") || name.contains("atomic") || matches!(inst.fields, Fields::Ds { .. }) - && !(name.starts_with("ds_read") || name.starts_with("ds_swizzle") || name.contains("permute")) + && !(name.starts_with("ds_read") + || name.starts_with("ds_swizzle") + || name.contains("permute")) || matches!(name, "s_barrier" | "s_sendmsg" | "s_sendmsghalt") } @@ -276,7 +278,9 @@ impl Ctx<'_> { .into_iter() .flatten() .filter_map(|u| match *u { - User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => Some((b, k)), + User::Phi(b, k) if self.live.contains(&self.p.blocks[b].phis[k].value) => { + Some((b, k)) + } _ => None, }) .collect(); @@ -364,9 +368,11 @@ impl Ctx<'_> { // an unguarded copy let copy = |u: (usize, usize)| -> Option { let i = self.inst(u); - (matches!(i.name(), "v_mov_b32" | "s_mov_b32") && args(i).len() == 1 && st.guards[u.0][u.1].is_none()) - .then(|| result(i)) - .flatten() + (matches!(i.name(), "v_mov_b32" | "s_mov_b32") + && args(i).len() == 1 + && st.guards[u.0][u.1].is_none()) + .then(|| result(i)) + .flatten() }; let mut init = vec![t]; // (SCC, whether it is set when the OR is empty) @@ -374,8 +380,10 @@ impl Ctx<'_> { for u in self.readers(t) { let i = self.inst(u); let name = i.name(); - if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") - && other(i, t) == Some(Arg::K(0)) + if matches!( + name, + "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32" + ) && other(i, t) == Some(Arg::K(0)) && zero.is_none() && let Some(scc) = i.write(Reg::Scc) { @@ -450,7 +458,9 @@ impl Ctx<'_> { } match (name, &args(i)[..]) { ("s_ff1_i32_b32", [Arg::Val(_)]) if idx.is_none() => idx = result(i), - ("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) if next.is_none() => { + ("s_xor_b32", _) | ("s_andn2_b32", [Arg::Val(_), Arg::Val(_)]) + if next.is_none() => + { let bit = match (name, &args(i)[..]) { ("s_andn2_b32", [Arg::Val(c), Arg::Val(b)]) if *c == cur && *b != cur => *b, ("s_xor_b32", _) => match other(i, cur) { @@ -499,7 +509,9 @@ impl Ctx<'_> { }; let by_idx = shifted.is_some_and(|sh| { sh == idx - || made(sh).is_some_and(|(_, i)| i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31))) + || made(sh).is_some_and(|(_, i)| { + i.name() == "s_and_b32" && other(i, idx) == Some(Arg::K(31)) + }) }); if !by_idx { return Err((head, SHAPE)); @@ -510,8 +522,10 @@ impl Ctx<'_> { for u in self.readers(nx) { let i = self.inst(u); let name = i.name(); - if matches!(name, "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32") - && other(i, nx) == Some(Arg::K(0)) + if matches!( + name, + "s_cmp_eq_u32" | "s_cmp_lg_u32" | "s_cmp_eq_i32" | "s_cmp_lg_i32" + ) && other(i, nx) == Some(Arg::K(0)) && let Some(scc) = i.write(Reg::Scc) { more.push((scc, name.contains("_lg_"))); @@ -538,7 +552,11 @@ impl Ctx<'_> { } } for (q, a) in p.blocks[h].preds.iter().zip(&phi.args) { - let ok = if lp[*q] { nexts.contains(a) } else { init.contains(a) }; + let ok = if lp[*q] { + nexts.contains(a) + } else { + init.contains(a) + }; if !ok { return Err((head, SHAPE)); } @@ -553,7 +571,11 @@ impl Ctx<'_> { continue; } let (u, set, clear) = self.branch(scc).ok_or((head, USED))?; - let (on, out) = if set_while_more { (set, clear) } else { (clear, set) }; + let (on, out) = if set_while_more { + (set, clear) + } else { + (clear, set) + }; if !lp[u.0] || !lp[on] || lp[out] { return Err((self.at(u), SHAPE)); } @@ -572,7 +594,11 @@ impl Ctx<'_> { } if !self.readers(scc).is_empty() { let (u, set, clear) = self.branch(scc).ok_or((here, USED))?; - let (none, some) = if set_when_empty { (set, clear) } else { (clear, set) }; + let (none, some) = if set_when_empty { + (set, clear) + } else { + (clear, set) + }; if none == some || lp[u.0] { return Err((self.at(u), SHAPE)); } @@ -601,7 +627,10 @@ impl Ctx<'_> { let mut tests: Vec<(Atom, usize, usize)> = Vec::new(); for u in self.readers(bit) { let i = self.inst(u); - if i.name() != "v_and_b32" || other(i, bit) != Some(Arg::Val(x)) || st.guards[u.0][u.1].is_some() { + if i.name() != "v_and_b32" + || other(i, bit) != Some(Arg::Val(x)) + || st.guards[u.0][u.1].is_some() + { continue; } let Some(y) = result(i) else { continue }; @@ -609,8 +638,14 @@ impl Ctx<'_> { let ci = self.inst(c); if matches!( ci.name(), - "v_cmp_ne_u32" | "v_cmpx_ne_u32" | "v_cmp_lg_u32" | "v_cmpx_lg_u32" | "v_cmp_ne_i32" | "v_cmpx_ne_i32" - | "v_cmp_lg_i32" | "v_cmpx_lg_i32" + "v_cmp_ne_u32" + | "v_cmpx_ne_u32" + | "v_cmp_lg_u32" + | "v_cmpx_lg_u32" + | "v_cmp_ne_i32" + | "v_cmpx_ne_i32" + | "v_cmp_lg_i32" + | "v_cmpx_lg_i32" ) && other(ci, y) == Some(Arg::K(0)) && lp[c.0] { @@ -634,7 +669,8 @@ impl Ctx<'_> { || lp[b] && st.guards[b][i].is_some_and(|g| { tests.iter().enumerate().any(|(j, &(a, tb, ti))| { - (b == tb && i > ti || b != tb && self.dominates(tb, b)) && self.implied(g, a, &mut memo[j]) + (b == tb && i > ti || b != tb && self.dominates(tb, b)) + && self.implied(g, a, &mut memo[j]) }) }) }; @@ -646,7 +682,10 @@ impl Ctx<'_> { } let u = (b, i); for &(reg, w) in &inst.writes { - if rem.contains(&w) || is_mask(w) || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) { + if rem.contains(&w) + || is_mask(w) + || matches!(reg, Reg::S(c) if c == EXEC || c == EXEC + 1) + { continue; } for user in self.users.get(&w).into_iter().flatten() { @@ -674,7 +713,9 @@ impl Ctx<'_> { || name.contains("lane") || matches!(&inst.fields, Fields::Valu(v) if v.dpp.is_some()) || super::lower::reads_mask_as_data(st, inst) - || self.sections[b].iter().any(|(&s, sec)| i >= s && i <= sec.end); + || self.sections[b] + .iter() + .any(|(&s, sec)| i >= s && i <= sec.end); if cross { return Err((self.at(u), CROSS)); } @@ -700,7 +741,9 @@ impl Ctx<'_> { changed = false; for (&id, edges) in &st.phi_masks { if !dep.contains(&Atom::Phi(id)) - && edges.iter().any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a))) + && edges + .iter() + .any(|&e| st.bools.support(e).iter().any(|a| dep.contains(a))) { dep.insert(Atom::Phi(id)); changed = true; @@ -730,7 +773,9 @@ impl Ctx<'_> { for user in self.users.get(&v).into_iter().flatten() { let outside = match *user { User::Inst(b2, _) => !lp[b2], - User::Phi(b2, k2) => !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value), + User::Phi(b2, k2) => { + !lp[b2] && self.live.contains(&p.blocks[b2].phis[k2].value) + } }; if outside { return Err((head, STALE)); @@ -760,7 +805,8 @@ pub(super) fn find(p: &Program, st: &Structured, why: bool) -> OwnBits { }; let ctx = ctx.get_or_insert_with(|| Ctx::new(p, st)); // (values only the section itself reads are not results) - let inside = |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end); + let inside = + |u: &User| matches!(*u, User::Inst(b2, i) if b2 == b && i > s && i < sec.end); if ctx.users.get(&t).is_none_or(|us| us.iter().all(inside)) { continue; } @@ -827,8 +873,8 @@ mod tests { w.push(0xBEFE_040C); // s_mov_b64 exec, s[12:13] w.extend_from_slice(latch); w.extend_from_slice(&[ - 0x8909_080B, // s_xor_b32 s9, s11, s8 - 0xBF06_0B08, // s_cmp_eq_u32 s8, s11 + 0x8909_080B, // s_xor_b32 s9, s11, s8 + 0xBF06_0B08, // s_cmp_eq_u32 s8, s11 0xBF84_0000 | (0x1_0000 - head - 1) as u32, // s_cbranch_scc0 again ]); w.extend_from_slice(after); @@ -859,7 +905,13 @@ mod tests { assert!(names.contains(&n), "{n} in {names:?}"); } // a loop: its last branch goes back to the copy of the bits still to visit - assert!(p.blocks.iter().enumerate().any(|(b, blk)| blk.exit.successors().iter().any(|&s| s < b))); + assert!( + p.blocks.iter().enumerate().any(|(b, blk)| blk + .exit + .successors() + .iter() + .any(|&s| s < b)) + ); let own = found(&p); // the OR is the section's last lane read, and the bits still to visit (v3) are alike let total = insts() @@ -897,7 +949,12 @@ mod tests { // s_add_i32 s14, s14, 1 where every lane passes, read after the loop // (v_mov_b32 v6, s14): one round for each bit any lane has let p = light_loop(true, &[ADD_BIT_NUMBER], &[0x810E_810E], &[0x7E0C_020E]); - assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "s_add_i32")); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "s_add_i32") + ); assert!(found(&p).totals.is_empty()); // (reading s14 there without counting in it is nothing of the loop's) let p = light_loop(true, &[ADD_BIT_NUMBER], &[], &[0x7E0C_020E]); @@ -908,7 +965,12 @@ mod tests { fn an_effect_where_every_lane_passes_is_not_the_lanes_own() { // ds_write_b32 v5, v5 after the body: once for each bit any lane has let p = light_loop(true, &[ADD_BIT_NUMBER], &[0xD834_0000, 0x0000_0505], &[]); - assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "ds_write_b32")); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "ds_write_b32") + ); assert!(found(&p).totals.is_empty()); } } diff --git a/crates/victory-shader/src/emit/rect.rs b/crates/victory-shader/src/emit/rect.rs index ba6236af..82ab8707 100644 --- a/crates/victory-shader/src/emit/rect.rs +++ b/crates/victory-shader/src/emit/rect.rs @@ -74,7 +74,9 @@ fn build(mut outputs: Vec, ps_inputs: &[SigElement]) -> Result V { } else { ("loadInput.i32", s.t.i32) }; - let args = [ - s.m.i32(id as u32), - s.m.i32(0), - s.m.i8(col), - s.m.i32(vertex), - ]; + let args = [s.m.i32(id as u32), s.m.i32(0), s.m.i8(col), s.m.i32(vertex)]; let entry = s.entry; s.op(entry, name, Attr::ReadNone, ty, 4, &args) } @@ -479,7 +476,10 @@ mod tests { } let half = draw(None); let missing = half.iter().zip(&whole).filter(|(a, b)| a != b).count(); - assert!(missing >= 24, "{name}: only {missing} texels need the stage"); + assert!( + missing >= 24, + "{name}: only {missing} texels need the stage" + ); } } } diff --git a/crates/victory-shader/src/emit/valu_tests.rs b/crates/victory-shader/src/emit/valu_tests.rs index ca659c88..2c74bb29 100644 --- a/crates/victory-shader/src/emit/valu_tests.rs +++ b/crates/victory-shader/src/emit/valu_tests.rs @@ -361,11 +361,17 @@ fn v_cvt_f32_f64_rounds_to_nearest_even() { run_cases(&shader, &inputs, |backend, i, _, got| { let x = values[i]; if x.is_nan() { - assert!(f32::from_bits(got).is_nan(), "{backend}: cvt({x}) = {got:#010x}, want NaN"); + assert!( + f32::from_bits(got).is_nan(), + "{backend}: cvt({x}) = {got:#010x}, want NaN" + ); return; } let want = cvt_f32_f64_reference(x); - assert_eq!(got, want, "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}"); + assert_eq!( + got, want, + "{backend}: cvt({x:e}) = {got:#010x}, want {want:#010x}" + ); }); } @@ -402,14 +408,19 @@ fn v_permlane16_and_x16_read_the_lanes_their_selectors_pick() { let inputs: Vec<[u32; 4]> = selectors.iter().map(|&(a, b)| [a, b, 0, 0]).collect(); // Cross-lane code declares WaveSize(32), which WARP's pipeline // creation refuses: hardware only. - run_cases_on(&shader, &inputs, &[("hardware", false)], |backend, i, inp, got| { - let want = permlane_source(u32::from(read), inp[0], inp[1], cross); - assert_eq!( - got, want, - "{backend}: op {op:#x} selectors {:08x?}, lane {read}", - selectors[i] - ); - }); + run_cases_on( + &shader, + &inputs, + &[("hardware", false)], + |backend, i, inp, got| { + let want = permlane_source(u32::from(read), inp[0], inp[1], cross); + assert_eq!( + got, want, + "{backend}: op {op:#x} selectors {:08x?}, lane {read}", + selectors[i] + ); + }, + ); } } } @@ -1089,7 +1100,10 @@ fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { (0x7BFF, 65504), // 65504.0 (max finite f16) -> 65504 (0x7C00, 0xFFFF), // +inf -> 65535 (saturated) ]; - let u16_in: Vec<[u32; 4]> = u16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + let u16_in: Vec<[u32; 4]> = u16_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); run_cases(&cvt_u16, &u16_in, |backend, i, inp, got| { let want = u16_cases[i].1; assert_eq!( @@ -1107,15 +1121,18 @@ fn cvt_16bit_int_from_f16_saturates_and_honors_modifiers() { ); let i16_cases: &[(u16, u16)] = &[ - (0xFC00, 0x8000), // -inf -> -32768 - (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) + (0xFC00, 0x8000), // -inf -> -32768 + (0xF8E2, 0x8000), // -40000.0 -> -32768 (saturated, not wrapped) (0xD7BC, (-123i16) as u16), // -123.75 -> -123 - (0x7E00, 0), // NaN -> 0 - (0x57BC, 123), // 123.75 -> 123 - (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) - (0x7C00, 0x7FFF), // +inf -> 32767 + (0x7E00, 0), // NaN -> 0 + (0x57BC, 123), // 123.75 -> 123 + (0x78E2, 0x7FFF), // +40000.0 -> 32767 (saturated, not wrapped) + (0x7C00, 0x7FFF), // +inf -> 32767 ]; - let i16_in: Vec<[u32; 4]> = i16_cases.iter().map(|&(x, _)| [u32::from(x), 0, 0, 0]).collect(); + let i16_in: Vec<[u32; 4]> = i16_cases + .iter() + .map(|&(x, _)| [u32::from(x), 0, 0, 0]) + .collect(); run_cases(&cvt_i16, &i16_in, |backend, i, inp, got| { let want = i16_cases[i].1; assert_eq!( @@ -1434,7 +1451,8 @@ fn v_cvt_f32_f64_matches_ieee754() { ); } else { assert_eq!( - got, want, + got, + want, "{backend}: v_cvt_f32_f64({x} / {:#018x}) = {got:#010x}, want {want:#010x}", x.to_bits(), ); @@ -1464,7 +1482,8 @@ fn v_cvt_f32_f64_matches_ieee754() { fn whole_wave_f64_sum_and_cvt_f32_f64() { let s_or_saveexec_b32 = |sdst: u8, src0: u8| 0xBE80_0000 | (sdst as u32) << 16 | 0x3D << 8 | src0 as u32; - let v_mov_dpp8 = |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; + let v_mov_dpp8 = + |vdst: u8, vsrc: u8, sel: u32| [vop1(0x001, vdst, 0xE9), vsrc as u32 | (sel << 8)]; let v_mov_row_mirror = |vdst: u8, vsrc: u8| { [ vop1(0x001, vdst, 0xFA), diff --git a/crates/victory-shader/src/emit/wave.rs b/crates/victory-shader/src/emit/wave.rs index 1d7a91b7..69c09a1f 100644 --- a/crates/victory-shader/src/emit/wave.rs +++ b/crates/victory-shader/src/emit/wave.rs @@ -322,9 +322,11 @@ fn simulate(insts: &[Inst], wave: u32, saved: Value) -> HashMap { && let Some(w) = inst.write(Reg::S(*dc)) { let sym = match *s0 { - Operand::Scalar { code, .. } if code != NULL => inst - .read(Reg::S(code)) - .map_or(Sym::Unknown, |x| uni.get(&x).copied().unwrap_or(Sym::Uni(x))), + Operand::Scalar { code, .. } if code != NULL => { + inst.read(Reg::S(code)).map_or(Sym::Unknown, |x| { + uni.get(&x).copied().unwrap_or(Sym::Uni(x)) + }) + } Operand::Const(c) => crate::resource::inline(c).map_or(Sym::Unknown, Sym::K), Operand::Literal(x) => Sym::K(x), _ => Sym::Unknown, @@ -1109,10 +1111,17 @@ mod tests { let p = build(w, true); let insts = &p.blocks[0].insts; let saved = insts[0].write(Reg::S(4)).unwrap(); - let v7 = p.inputs.iter().find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)).unwrap(); + let v7 = p + .inputs + .iter() + .find_map(|&(r, v)| (r == Reg::V(7)).then_some(v)) + .unwrap(); // ..., v_readlane_b32 s7, v1, 0; s_mov_b64 exec, s[4:5]; s_endpgm let total = insts[insts.len() - 3].write(Reg::S(7)).unwrap(); - (sections(&p, 0)[&0].shapes.get(&total).copied(), Shape::Active(Op::AddH, v7, saved, 0)) + ( + sections(&p, 0)[&0].shapes.get(&total).copied(), + Shape::Active(Op::AddH, v7, saved, 0), + ) }; let (found, want) = shape(&words(pairs, quads)); assert_eq!(found, Some(want)); diff --git a/crates/victory-shader/src/emit/wave64_tests.rs b/crates/victory-shader/src/emit/wave64_tests.rs index 1501bd19..4ba44800 100644 --- a/crates/victory-shader/src/emit/wave64_tests.rs +++ b/crates/victory-shader/src/emit/wave64_tests.rs @@ -33,7 +33,7 @@ fn program(skip: u32) -> NativeProgram { 0x7E00_0207, // v_mov_b32 v0, s7 0x38 << 26 | 0x1C << 18, 0x80 << 24 | 2 << 16, // buffer_store_dword v0, off, s[8:11], 0 - 0xBEFE_040C, // s_mov_b64 exec, s[12:13] + 0xBEFE_040C, // s_mov_b64 exec, s[12:13] ]); native(&words) } @@ -94,7 +94,11 @@ fn native_of(body: &[u32], wave64: bool, threads: u32) -> NativeProgram { } /// `program()` for a host of 32-lane waves, with the branches closing `wide` taken wave-wide. -fn lowered(native: &NativeProgram, p: &ir::Program, wide: &HashSet) -> Result { +fn lowered( + native: &NativeProgram, + p: &ir::Program, + wide: &HashSet, +) -> Result { lowered_on(native, p, wide, 32) } @@ -150,7 +154,13 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 ]; // (the wave OR's words with v_add_f16 for v_or_b32: opcode 50 for 28) - words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| { + if w >> 25 == 28 { + w & 0x01FF_FFFF | 50 << 25 + } else { + w + } + })); words.extend_from_slice(&[ 0x7E00_0207, // v_mov_b32 v0, s7 0x38 << 26 | 0x1C << 18, @@ -158,7 +168,14 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { ]); let native = native(&words); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - assert_eq!(p.blocks.iter().flat_map(|b| &b.insts).filter(|i| i.name() == "v_add_f16").count(), 6); + assert_eq!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .filter(|i| i.name() == "v_add_f16") + .count(), + 6 + ); let shader = lowered(&native, &p, &HashSet::new()).expect("lower"); if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); @@ -166,7 +183,8 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { } // the console's sum: lanes 2k and 2k+1, then pairs, ... each addition rounded to 16 bits // (to nearest, ties to even); values here are normal numbers - let wide = |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); + let wide = + |h: u16| f32::from_bits((u32::from(h >> 10) + 112) << 23 | u32::from(h & 0x3FF) << 13); let narrow = |f: f32| { let b = f.to_bits(); let h = ((b >> 23) - 112) << 10 | (b >> 13 & 0x3FF); @@ -180,8 +198,13 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { tree = tree.chunks(2).map(|c| add(c[0], c[1])).collect(); } let in_a_row = terms.iter().copied().reduce(add).unwrap(); - assert_ne!(tree[0], in_a_row, "these terms tell the tree from another order"); - let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + assert_ne!( + tree[0], in_a_row, + "these terms tell the tree from another order" + ); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); let Ok(host) = Host::new(false) else { eprintln!("no SM 6.6 hardware device; not run"); return; @@ -189,7 +212,9 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { let (root, pso) = match host.compute_pipeline(&shader) { Ok(x) => x, Err(e) => { - eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); + eprintln!( + "the hardware device does not take this program (waves of 32?): {e}; not run" + ); return; } }; @@ -207,8 +232,16 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { ) .unwrap_or_else(|e| panic!("dispatch failed: {e}")); // (the high half is lane 0's term's: zero) - assert_eq!(out[0][0], u32::from(tree[0]), "tree {:#x}, in a row {in_a_row:#x}", tree[0]); - eprintln!("ran on the hardware device: the sum {:#x} of the console's tree", tree[0]); + assert_eq!( + out[0][0], + u32::from(tree[0]), + "tree {:#x}, in a row {in_a_row:#x}", + tree[0] + ); + eprintln!( + "ran on the hardware device: the sum {:#x} of the console's tree", + tree[0] + ); } /// The console's 16-bit wave sum where the lanes at or past s0 have left the program (a @@ -219,7 +252,7 @@ fn a_sum_of_halves_over_the_wave_is_the_consoles_tree_bit_for_bit() { fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { let mut words = vec![ 0x7DA8_0000, // v_cmpx_gt_u32 exec, s0, v0: the lanes below s0 stay - 0, // s_cbranch_execz to the end (filled in below) + 0, // s_cbranch_execz to the end (filled in below) 0x340C_0085, // v_lshlrev_b32 v6, 5, v0 0x340E_0082, // v_lshlrev_b32 v7, 2, v0 0x4A0E_0F06, // v_add_nc_u32 v7, v6, v7 @@ -227,7 +260,13 @@ fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { 0x4A0E_0EFF, 0x0000_3C00, // v_add_nc_u32 v7, 0x3c00, v7 ]; - words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| if w >> 25 == 28 { w & 0x01FF_FFFF | 50 << 25 } else { w })); + words.extend(super::wave::WAVE_OR_V7_TO_S7.iter().map(|&w| { + if w >> 25 == 28 { + w & 0x01FF_FFFF | 50 << 25 + } else { + w + } + })); words.extend_from_slice(&[ 0x7E00_0207, // v_mov_b32 v0, s7 0x38 << 26 | 0x1C << 18, @@ -259,11 +298,19 @@ fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { (h + u32::from(rest > 0x1000 || rest == 0x1000 && h & 1 == 1)) as u16 }; let add = |a: u16, b: u16| narrow(wide(a) + wide(b)); - let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); let mut ran = false; for stay in [64u32, 63, 40, 33, 32, 17, 5, 1] { let terms: Vec = (0..64u32) - .map(|t| if t < stay { (0x3C00 + 37 * t) as u16 } else { 0 }) + .map(|t| { + if t < stay { + (0x3C00 + 37 * t) as u16 + } else { + 0 + } + }) .collect(); let mut tree = terms.clone(); while tree.len() > 1 { @@ -274,7 +321,12 @@ fn a_sum_of_halves_where_lanes_have_left_is_the_consoles_tree_bit_for_bit() { }; ran = true; // (the high half is lane 0's term's: zero) - assert_eq!(got, u32::from(tree[0]), "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", tree[0]); + assert_eq!( + got, + u32::from(tree[0]), + "{stay} lanes stay: got {got:#x}, the console's tree {:#x}", + tree[0] + ); } if ran { eprintln!("ran on the hardware device: the console's tree with lanes gone, in every case"); @@ -298,14 +350,23 @@ fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { ]; let native = native(&words); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); - assert!(p.blocks.iter().flat_map(|b| &b.insts).any(|i| i.name() == "v_add_f16")); - let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + assert!( + p.blocks + .iter() + .flat_map(|b| &b.insts) + .any(|i| i.name() == "v_add_f16") + ); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); for nearest in [false, true] { let was = lower::TEST_F16_NEAREST.replace(Some(nearest)); let shader = lowered(&native, &p, &HashSet::new()); lower::TEST_F16_NEAREST.set(was); let shader = shader.expect("lower"); - if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { + if let Ok(mut v) = + validator::Validator::load(validator::Validator::default_path().as_deref()) + { let mut copy = shader.dxil.clone(); v.validate(&mut copy).expect("DXIL validation failed"); } @@ -342,7 +403,10 @@ fn a_16_bit_sum_rounds_to_nearest_when_asked_to() { #[test] fn a_wave_or_inside_a_lane_branch_needs_the_branch_wave_wide() { - for (skip, name) in [(0xBF88_0000, "s_cbranch_execz"), (0xBF84_0000, "s_cbranch_scc0")] { + for (skip, name) in [ + (0xBF88_0000, "s_cbranch_execz"), + (0xBF84_0000, "s_cbranch_scc0"), + ] { a_wave_or_inside(skip, name); } } @@ -382,7 +446,9 @@ fn a_wave_or_inside(skip: u32, name: &str) { } // On a GPU that takes waves of 32 (two host waves for the console's one): the OR is of // both halves, whichever half's lanes take the branch. - let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); let Ok(host) = Host::new(false) else { eprintln!("no SM 6.6 hardware device; not run"); return; @@ -390,12 +456,20 @@ fn a_wave_or_inside(skip: u32, name: &str) { let (root, pso) = match host.compute_pipeline(&shader) { Ok(x) => x, Err(e) => { - eprintln!("the hardware device does not take this program (waves of 32?): {e}; not run"); + eprintln!( + "the hardware device does not take this program (waves of 32?): {e}; not run" + ); return; } }; // (threads below s0 take the branch; thread t gives bit t >> 1) - for (below, expected) in [(64u32, u32::MAX), (40, 0x000F_FFFF), (33, 0x0001_FFFF), (10, 0x1F), (1, 1)] { + for (below, expected) in [ + (64u32, u32::MAX), + (40, 0x000F_FFFF), + (33, 0x0001_FFFF), + (10, 0x1F), + (1, 1), + ] { let mut ud = vec![0u32; shader.user_data_dwords().max(1) as usize]; for u in &shader.user_data { if let (RootType::Constants, 0, 0) = (u.root, u.slot, u.dword) { @@ -475,9 +549,18 @@ fn a_lane_mask_joined_with_a_number_is_read_as_the_number_it_is() { let mut copy = shader.dxil.clone(); v.validate(&mut copy).expect("DXIL validation failed"); } - let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); - for (below, other, expected) in [(32u32, 0u32, u32::MAX), (10, 0, 0x3FF), (0, 0, 0), (10, 1, 5)] { - let Some(got) = on_the_card(&shader, [below, other]) else { return }; + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); + for (below, other, expected) in [ + (32u32, 0u32, u32::MAX), + (10, 0, 0x3FF), + (0, 0, 0), + (10, 1, 5), + ] { + let Some(got) = on_the_card(&shader, [below, other]) else { + return; + }; assert_eq!(got, expected, "{below} lanes in the mask, s1 = {other}"); } eprintln!("ran on the hardware device: the mask's bits, or the number"); @@ -508,7 +591,12 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() let native = native_of(&words, false, 32); let p = ir::build(&native.code, native.wave64, native.vgprs).expect("ir::build"); let branch = (0..p.blocks.len()) - .find(|&b| p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .find(|&b| { + p.blocks[b] + .insts + .last() + .is_some_and(|i| i.name() == "s_cbranch_execz") + }) .expect("the skip"); lower::take_needs(); let per_lane = lowered(&native, &p, &HashSet::new()); @@ -518,17 +606,32 @@ fn scc_of_a_mask_operation_joined_with_a_scalar_test_needs_the_skip_wave_wide() per_lane.err() ); let st = structure::structure(&p).expect("structure"); - assert_eq!(lower::branches_around(&st, &lower::take_needs()), Some(vec![branch])); + assert_eq!( + lower::branches_around(&st, &lower::take_needs()), + Some(vec![branch]) + ); let shader = lowered(&native, &p, &HashSet::from([branch])).expect("lower"); if let Ok(mut v) = validator::Validator::load(validator::Validator::default_path().as_deref()) { let mut copy = shader.dxil.clone(); v.validate(&mut copy).expect("DXIL validation failed"); } - let _one = super::valu_tests::ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let _one = super::valu_tests::ONE_AT_A_TIME + .lock() + .unwrap_or_else(|e| e.into_inner()); // (lanes below s0 inside, s1) -> what lane 31 stores: 2 if SCC was set at the branch - for (below, s1, expected) in [(0u32, 7u32, 1u32), (10, 7, 2), (10, 3, 1), (32, 3, 1), (32, 7, 2)] { - let Some(got) = on_the_card(&shader, [below, s1]) else { return }; + for (below, s1, expected) in [ + (0u32, 7u32, 1u32), + (10, 7, 2), + (10, 3, 1), + (32, 3, 1), + (32, 7, 2), + ] { + let Some(got) = on_the_card(&shader, [below, s1]) else { + return; + }; assert_eq!(got, expected, "{below} lanes inside, s1 = {s1}"); } - eprintln!("ran on the hardware device: the inner test's SCC for every lane once some lane is inside"); + eprintln!( + "ran on the hardware device: the inner test's SCC for every lane once some lane is inside" + ); } diff --git a/crates/victory-shader/src/ir.rs b/crates/victory-shader/src/ir.rs index 0b8fd9c6..ca6c58aa 100644 --- a/crates/victory-shader/src/ir.rs +++ b/crates/victory-shader/src/ir.rs @@ -179,7 +179,11 @@ pub fn build(code: &[u8], wave64: bool, vgprs: u16) -> Result Option<(bool, u8, u8, u32)> { let Fields::Valu(v) = fields else { return None }; - if v.abs != 0 || v.neg != 0 || v.opsel != 0 || v.clamp || v.omod != 0 || v.sdwa.is_some() || v.dpp.is_some() { + if v.abs != 0 + || v.neg != 0 + || v.opsel != 0 + || v.clamp + || v.omod != 0 + || v.sdwa.is_some() + || v.dpp.is_some() + { return None; } let lane = |op: &Operand| match *op { @@ -264,10 +275,14 @@ fn unspill( _ => None, }; match (inst.name()?, v.dst?, v.src.as_slice()) { - ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) if *code < 105 => { + ("v_writelane_b32", Operand::Vector { reg, .. }, [Operand::Scalar { code, .. }, k]) + if *code < 105 => + { Some((true, reg, *code, lane(k)?)) } - ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) if code < 105 => { + ("v_readlane_b32", Operand::Scalar { code, .. }, [Operand::Vector { reg, .. }, k]) + if code < 105 => + { Some((false, *reg, code, lane(k)?)) } _ => None, @@ -282,7 +297,9 @@ fn unspill( let mut written: Vec> = Vec::with_capacity(list.len()); let mut read: Vec> = Vec::with_capacity(list.len()); for inst in list.iter() { - let Some(name) = inst.name() else { return Vec::new() }; + let Some(name) = inst.name() else { + return Vec::new(); + }; let fields = inst.fields(wave64); let park = parked(inst, &fields); let Ok(effects) = effects(inst, &fields, name, lanes, vgprs) else { @@ -387,16 +404,28 @@ fn unspill( }; let mut pairs: Vec<(u8, u32)> = Vec::new(); for &(reg, lane) in &slots { - if !wave64 || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) || !slots.contains(&(reg, lane + 1)) { + if !wave64 + || pairs.iter().any(|&(r, l)| r == reg && l + 1 == lane) + || !slots.contains(&(reg, lane + 1)) + { continue; } - let lower: Vec = (0..list.len()).filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))).collect(); - let upper = parks.iter().flatten().filter(|p| (p.1, p.3) == (reg, lane + 1)).count(); + let lower: Vec = (0..list.len()) + .filter(|&i| parks[i].is_some_and(|p| (p.1, p.3) == (reg, lane))) + .collect(); + let upper = parks + .iter() + .flatten() + .filter(|p| (p.1, p.3) == (reg, lane + 1)) + .count(); let partners: Vec> = lower.iter().map(|&i| partner(i)).collect(); let mut distinct: Vec = partners.iter().flatten().copied().collect(); distinct.sort_unstable(); distinct.dedup(); - if partners.iter().all(Option::is_some) && distinct.len() == lower.len() && upper == lower.len() { + if partners.iter().all(Option::is_some) + && distinct.len() == lower.len() + && upper == lower.len() + { pairs.push((reg, lane)); } } @@ -413,7 +442,10 @@ fn unspill( free[past..255].fill(true); let mut codes: Vec<((u8, u32), u8)> = Vec::new(); for &(reg, lane) in &pairs { - let at = (108..123).chain((0..104).rev()).chain(past..254).find(|&c| free[c] && free[c + 1]); + let at = (108..123) + .chain((0..104).rev()) + .chain(past..254) + .find(|&c| free[c] && free[c + 1]); // Not enough spare codes: leave the program as it is. let Some(c) = at else { return Vec::new() }; (free[c], free[c + 1]) = (false, false); @@ -424,7 +456,11 @@ fn unspill( if codes.iter().any(|c| c.0 == slot) { continue; } - let Some(c) = (108..=123).chain((0..105).rev()).chain(past..255).find(|&c| free[c]) else { + let Some(c) = (108..=123) + .chain((0..105).rev()) + .chain(past..255) + .find(|&c| free[c]) + else { return Vec::new(); }; free[c] = false; @@ -442,16 +478,22 @@ fn unspill( // `s_mov_b32` / `s_mov_b64 dst, src` (SOP1, opcodes 3 and 4); `s_nop`. A code // from `PARKED` up does not fit the word: s0 stands in for it there. let field = |code: u8| if code < PARKED { u32::from(code) } else { 0 }; - let mov = |wide: bool, dst: u8, src: u8| 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src); + let mov = |wide: bool, dst: u8, src: u8| { + 0xBE80_0000 | field(dst) << 16 | (3 + u32::from(wide)) << 8 | field(src) + }; const NOP: u32 = 0xBF80_0000; let mut edits: Vec<(usize, Option<(bool, u8, u8)>)> = Vec::new(); for i in 0..list.len() { let Some((save, reg, code, lane)) = parks[i] else { continue; }; - let Some(slot) = code_of(reg, lane) else { return Vec::new() }; + let Some(slot) = code_of(reg, lane) else { + return Vec::new(); + }; if pairs.contains(&(reg, lane)) { - let Some(j) = partner(i) else { return Vec::new() }; + let Some(j) = partner(i) else { + return Vec::new(); + }; // A save moves the pair where its second half is saved; a // restore where its first half is restored. let (at, gone) = if save { (j, i) } else { (i, j) }; @@ -469,7 +511,13 @@ fn unspill( for (i, edit) in edits { match edit { Some((wide, dst, src)) => { - put(list, i, gfx10::Encoding::Sop1, 3 + u16::from(wide), mov(wide, dst, src)); + put( + list, + i, + gfx10::Encoding::Sop1, + 3 + u16::from(wide), + mov(wide, dst, src), + ); moves.push((i, dst, src)); } None => put(list, i, gfx10::Encoding::Sopp, 0, NOP), @@ -592,7 +640,10 @@ pub(crate) fn thread_edges( pub(crate) fn without_early_outs(p: &Program) -> Option { let ends = |b: usize| { p.blocks[b].exit == Exit::End - && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + && p.blocks[b] + .insts + .iter() + .all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) }; let mut blocks = p.blocks.clone(); let mut any = false; @@ -600,7 +651,12 @@ pub(crate) fn without_early_outs(p: &Program) -> Option { let Exit::Branch { taken, not_taken } = block.exit else { continue; }; - if ends(taken) && block.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { + if ends(taken) + && block + .insts + .last() + .is_some_and(|i| i.name() == "s_cbranch_execz") + { block.insts.pop(); block.exit = Exit::Jump(not_taken); any = true; @@ -640,7 +696,10 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { let n = p.blocks.len(); let ends = |b: usize| { p.blocks[b].exit == Exit::End - && p.blocks[b].insts.iter().all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) + && p.blocks[b] + .insts + .iter() + .all(|i| matches!(i.fields, crate::gfx10::Fields::Sopp { .. })) }; // Scalars moved from register to register (a scalar the compiler parked in a VGPR lane // comes back by such a move, `unspill`) are the value they copy. @@ -664,7 +723,11 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { for inst in &block.insts { if matches!(inst.name(), "s_mov_b32" | "s_mov_b64") && inst.reads.len() == inst.writes.len() - && inst.reads.iter().chain(&inst.writes).all(|r| matches!(r.0, Reg::S(_))) + && inst + .reads + .iter() + .chain(&inst.writes) + .all(|r| matches!(r.0, Reg::S(_))) { copy.extend(inst.writes.iter().zip(&inst.reads).map(|(w, r)| (w.1, r.1))); } @@ -731,9 +794,19 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { if !scalar || deep && !live.contains(&phi.value) { continue; } - let before: Vec = - join.preds.iter().zip(&phi.args).filter(|(q, _)| **q == b).map(|(_, a)| root(*a)).collect(); - let within = join.preds.iter().zip(&phi.args).filter(|(q, _)| inside[**q]).map(|(_, a)| root(*a)); + let before: Vec = join + .preds + .iter() + .zip(&phi.args) + .filter(|(q, _)| **q == b) + .map(|(_, a)| root(*a)) + .collect(); + let within = join + .preds + .iter() + .zip(&phi.args) + .filter(|(q, _)| inside[**q]) + .map(|(_, a)| root(*a)); if within.into_iter().any(|a| !before.contains(&a)) { return None; } @@ -752,7 +825,11 @@ pub(crate) fn without_skips(p: &Program, deep: bool) -> Option { let Exit::Branch { taken, not_taken } = p.blocks[b].exit else { continue; }; - if !p.blocks[b].insts.last().is_some_and(|i| i.name() == "s_cbranch_execz") { + if !p.blocks[b] + .insts + .last() + .is_some_and(|i| i.name() == "s_cbranch_execz") + { continue; } if ends(taken) || skipped(b, taken, not_taken).is_some() { @@ -1576,7 +1653,11 @@ mod tests { fn skips(p: &Program) -> usize { p.blocks .iter() - .filter(|b| b.insts.last().is_some_and(|i| i.name() == "s_cbranch_execz")) + .filter(|b| { + b.insts + .last() + .is_some_and(|i| i.name() == "s_cbranch_execz") + }) .count() } diff --git a/crates/victory-shader/src/resource.rs b/crates/victory-shader/src/resource.rs index a27ae5e0..8708b4f7 100644 --- a/crates/victory-shader/src/resource.rs +++ b/crates/victory-shader/src/resource.rs @@ -343,12 +343,12 @@ pub fn track( for (block, (accesses, mut reads)) in first_lane_at { reads.sort_unstable(); reads.dedup(); - let proof = t - .waterfall(block, &accesses, &reads) - .map_err(|what| ShaderError::Unsupported { - offset: t.inst((block, accesses[0])).machine.offset, - what, - })?; + let proof = + t.waterfall(block, &accesses, &reads) + .map_err(|what| ShaderError::Unsupported { + offset: t.inst((block, accesses[0])).machine.offset, + what, + })?; out.waterfall.compares.extend(proof.compares); out.waterfall.reads.extend(proof.reads); } @@ -747,9 +747,10 @@ impl<'a> Tracer<'a> { /// [`Self::code_high`], at most `depth` additions deep. fn code_high_in(&self, t: Term, depth: u32) -> bool { let Term::Value(x) = t else { return false }; - if self.def(x).is_some_and(|i| { - i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x) - }) { + if self + .def(x) + .is_some_and(|i| i.name() == "s_getpc_b64" && i.writes.get(1).is_some_and(|w| w.1 == x)) + { return true; } depth > 0 @@ -958,7 +959,11 @@ impl<'a> Tracer<'a> { // A join of paths into tables in the code is the byte in the code // already: each path's `s_getpc_b64` counts as its own offset. let joined = s.dynamic.is_some_and(|d| self.code_join(d).is_some()); - let first = if joined { 0 } else { pc.machine.offset as u32 + 4 }; + let first = if joined { + 0 + } else { + pc.machine.offset as u32 + 4 + }; return Ok(Address { param: CODE, offset: first.wrapping_add(s.offset).wrapping_add(extra.offset), @@ -2030,7 +2035,8 @@ impl<'a> Tracer<'a> { } else { continue; }; - let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) else { + let Some(matched) = mask(inst.write(Reg::S(code)), inst.write(Reg::S(code + 1))) + else { continue; }; if meet(&[reach, (selected, true), (matched, false)]) { @@ -2624,7 +2630,10 @@ pub(crate) mod tests { assert_eq!(r.scalar.len(), 1); let a = r.scalar[0].1; assert_eq!((a.param, a.offset), (CODE, 0)); - assert!(a.dynamic.is_some(), "the join is the computed term, the byte in the code"); + assert!( + a.dynamic.is_some(), + "the join is the computed term, the byte in the code" + ); } /// An address into a table in the code computed per lane and taken from diff --git a/crates/victory-shader/src/spill.rs b/crates/victory-shader/src/spill.rs index a0feb6ae..534fddbc 100644 --- a/crates/victory-shader/src/spill.rs +++ b/crates/victory-shader/src/spill.rs @@ -170,11 +170,16 @@ pub fn user_data(p: &mut Program, native: &NativeProgram) -> usize { continue; }; if !inst.name().starts_with("s_load_dword") - || !matches!(soffset, Operand::Scalar { code: NULL, .. } | Operand::Const(128)) + || !matches!( + soffset, + Operand::Scalar { code: NULL, .. } | Operand::Const(128) + ) || offset < 0 || offset % 4 != 0 || !inst.read(Reg::S(base)).is_some_and(|v| lows.contains(&v)) - || !inst.read(Reg::S(base + 1)).is_some_and(|v| highs.contains(&v)) + || !inst + .read(Reg::S(base + 1)) + .is_some_and(|v| highs.contains(&v)) { continue; } @@ -339,7 +344,12 @@ mod tests { ); let mut p = ir::build(&n.code, false, 256).unwrap(); assert_eq!(user_data(&mut p, &n), 2); - let names: Vec<&str> = p.blocks.iter().flat_map(|b| &b.insts).map(|i| i.name()).collect(); + let names: Vec<&str> = p + .blocks + .iter() + .flat_map(|b| &b.insts) + .map(|i| i.name()) + .collect(); assert!(!names.iter().any(|n| n.starts_with("s_load_")), "{names:?}"); // The pointer is gone with the loads; byte 0x10 is index 20, the // first root constant, and bytes 0-7 are the first root view. diff --git a/crates/victory-shader/src/structure.rs b/crates/victory-shader/src/structure.rs index a913176c..b0f3a9bb 100644 --- a/crates/victory-shader/src/structure.rs +++ b/crates/victory-shader/src/structure.rs @@ -846,7 +846,11 @@ impl<'a> Lanes<'a> { .filter(|(lo, hi)| lo != hi) .map(|&(lo, hi)| (hi, lo)) .collect(), - paired_masks: if self.p.wave64 { self.masks } else { Map::default() }, + paired_masks: if self.p.wave64 { + self.masks + } else { + Map::default() + }, active: self.active, wide: self.wide, wave_any: self.wave_any, @@ -1247,7 +1251,11 @@ impl<'a> Lanes<'a> { let e = exec.unwrap_or(Bool::TRUE); let own = self.b.given(m, e); if self.b.implies(m, e) - && self.b.support(own).iter().all(|a| matches!(a, Atom::Uniform(_))) + && self + .b + .support(own) + .iter() + .all(|a| matches!(a, Atom::Uniform(_))) { self.scc_lane.insert(scc, own); }