Forráskód Böngészése

VIctory's 88 commits fitted in; clzero loops end as the console's do

The fork's emulation of a clzero loop zeroed from the start to the end and
left rax at the end: the instruction zeroes whole lines and the test comes
after it (VIctory's own test of it failed here). The title's descriptor
heaps are held shared while their slots are written (VIctory 628b95d held
them alone, for every thread that writes descriptors).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
local 2 napja
szülő
commit
daeeb28c1e

+ 18 - 8
crates/victory-gpu/src/descriptor.rs

@@ -126,14 +126,17 @@ const SHADER_VISIBLE: u32 = 1;
 /// Shader-visible heaps by address range, for mirroring descriptor writes:
 /// start, end, heap.
 #[cfg(windows)]
-static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new());
+///
+/// Held shared while a heap found here is used (by every thread that writes
+/// descriptors, and by [`sync_heaps`]), alone only where heaps come and go.
+static SHADER_HEAPS: std::sync::RwLock<Vec<(u64, u64, usize)>> = std::sync::RwLock::new(Vec::new());
 
 /// Makes the host descriptor for what the title wrote at `handle`, if it
 /// is in a shader-visible heap. Keeps `SHADER_HEAPS` locked for the duration
 /// so `Heap::drop` cannot free the heap concurrently.
 #[cfg(windows)]
 fn mirror(handle: u64) {
-    let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+    let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
     let Some(&(_, _, at)) = heaps
         .iter()
         .find(|&&(start, end, _)| (start..end).contains(&handle))
@@ -177,7 +180,7 @@ pub(crate) fn sync_heaps() {
     let started = std::time::Instant::now();
     let (mut pages, mut looked, mut mirrored) = (0u64, 0u64, 0u64);
     let mut page_bytes: Vec<u8> = Vec::new();
-    let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+    let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
     for &(start, end, at) in heaps.iter() {
         // SAFETY: registered heaps are live (removed when dropped).
         let heap = unsafe { &*(at as *const Heap) };
@@ -275,7 +278,7 @@ fn changed_slots(
 /// `heap`, if that heap still exists.
 #[cfg(windows)]
 pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
-    let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+    let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
     if heaps.iter().any(|&(_, _, h)| h == heap)
         // SAFETY: registered heaps are live (removed when dropped).
         && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
@@ -289,7 +292,7 @@ pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
 /// bytes at `gpu`.
 #[cfg(windows)]
 pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) {
-    let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+    let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
     if heaps.iter().any(|&(_, _, h)| h == heap)
         // SAFETY: registered heaps are live (removed when dropped).
         && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
@@ -302,7 +305,7 @@ pub(crate) fn constant_slot(heap: usize, index: u32, gpu: u64, size: u32) {
 impl Drop for Heap {
     fn drop(&mut self) {
         let at = std::ptr::from_ref::<Heap>(self) as usize;
-        let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+        let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner());
         heaps.retain(|&(_, _, h)| h != at);
     }
 }
@@ -819,7 +822,14 @@ pub(crate) fn make_waiting() {
             // texture without a host copy must go on waiting).
             // (Looked up first: the handle is read only while its heap is
             // there.)
-            let Some((heap, index)) = shader_slot(handle) else {
+            // (The heap stays while the lock is held: `mirror`.)
+            let heaps = SHADER_HEAPS.read().unwrap_or_else(|e| e.into_inner());
+            let Some(&(_, _, at)) = heaps.iter().find(|&&(start, end, _)| (start..end).contains(&handle)) else {
+                continue;
+            };
+            // SAFETY: a registered heap, live while the lock is held.
+            let heap = unsafe { &*(at as *const Heap) };
+            let Some(index) = heap.index(handle) else {
                 continue;
             };
             let same = match view(handle) {
@@ -1113,7 +1123,7 @@ pub(crate) extern "system" fn create_heap(
     #[cfg(windows)]
     if visible {
         let at = std::ptr::from_ref::<Heap>(&heap) as usize;
-        let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
+        let mut heaps = SHADER_HEAPS.write().unwrap_or_else(|e| e.into_inner());
         heaps.push((start, start + size, at));
     }
     #[cfg(not(windows))]

+ 30 - 22
crates/victory-loader/src/console_insn.rs

@@ -168,29 +168,37 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 {
             ];
             let end = regs[end_reg as usize & 15] as usize;
             let start = ctx.Rax as usize;
-            if end > start && end - start < 2 << 30 {
-                // Region by region: a block may lie across several (the title's pages are
-                // mapped one view each), and one answer for all of it was a refusal, after
-                // 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 };
-                    // SAFETY: committed and writable from `at` to `to`.
-                    unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) };
-                    at = to;
-                }
-                if at == start {
-                    return 0;
-                }
-                ZEROED.fetch_add((at - start) as u64, Relaxed);
-                if at < end {
-                    // What follows is not writable: the loop goes on there (the same
-                    // instruction again), where the real one faults too.
-                    ctx.Rax = at as u64;
-                    return CONTINUE_EXECUTION;
-                }
+            // A pass zeroes the whole line `rax` is in, wherever in it, and the test comes
+            // after it: lines are zeroed past an `end` inside one, and one is for an `end`
+            // not above the start. (The bytes from `start` to `end` were, `rax` came out as
+            // `end`, and the flags stayed what they were.)
+            const MOST: usize = (2 << 30) / 64;
+            let wanted = if end > start { (end - start).div_ceil(64) } else { 1 };
+            let passes = wanted.min(MOST);
+            let first = start & !63;
+            let Some(stop) = first.checked_add(passes * 64) else { return 0 };
+            // Region by region: a block may lie across several (the title's pages are
+            // mapped one view each), and one answer for all of it was a refusal, after
+            // which every 64-byte line took an exception of its own.
+            let mut at = first;
+            while at < stop {
+                let Some(to) = writable_to(at, stop) else { break };
+                // SAFETY: committed and writable from `at` to `to`.
+                unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) };
+                at = to;
+            }
+            let done = (at - first) / 64;
+            if done == 0 {
+                return 0;
+            }
+            ZEROED.fetch_add((done * 64) as u64, Relaxed);
+            ctx.Rax = ctx.Rax.wrapping_add((done * 64) as u64);
+            if done < wanted {
+                // What follows is not writable (or the block is huge): the loop goes on
+                // there (the same instruction again), where the real one faults too.
+                return CONTINUE_EXECUTION;
             }
-            ctx.Rax = end as u64;
+            ctx.EFlags = ctx.EFlags & !crate::crash::CMP_FLAGS | crate::crash::cmp_flags(ctx.Rax, end as u64);
         }
         ConsoleOnly::Rdpru => {
             let mut v = 0i64;

+ 2 - 2
crates/victory-loader/src/crash.rs

@@ -410,7 +410,7 @@ fn gpr(context: &mut CONTEXT, n: u8) -> &mut u64 {
 }
 
 /// The status flags `cmp a, b` leaves (CF, PF, AF, ZF, SF, OF) as `EFLAGS` bits.
-fn cmp_flags(a: u64, b: u64) -> u32 {
+pub(crate) fn cmp_flags(a: u64, b: u64) -> u32 {
     let r = a.wrapping_sub(b);
     u32::from(a < b)
         | u32::from((r as u8).count_ones().is_multiple_of(2)) << 2
@@ -419,7 +419,7 @@ fn cmp_flags(a: u64, b: u64) -> u32 {
         | ((r >> 63) as u32) << 7
         | ((((a ^ b) & (a ^ r)) >> 63) as u32) << 11
 }
-const CMP_FLAGS: u32 = 0x8d5;
+pub(crate) const CMP_FLAGS: u32 = 0x8d5;
 
 /// SSE4a's `extrq`/`insertq` (register forms, the only ones there are) on
 /// the saved XMM registers; returns the instruction's length.

+ 0 - 78
crates/victory-shader/src/emit/valu_tests.rs

@@ -295,39 +295,6 @@ fn scalar_quad_masks_pack_nibbles_and_set_scc() {
     });
 }
 
-#[test]
-fn scalar_quad_masks_pack_nibbles_and_set_scc() {
-    let pack_words = |opcode: u32| {
-        [
-            0xBE90_0000 | opcode << 8,   // s_quadmask s16, s0 (pairs for b64)
-            sop2(0x0a, 18, 129, 128),  // s_cselect_b32 s18, 1, 0
-            sop2(0x1e, 18, 18, 144),   // s_lshl_b32 s18, s18, 16
-            sop2(0x10, 16, 16, 18),    // s_or_b32 s16, s16, s18
-            vop1(1, 0, sgpr(16)),      // v_mov_b32 v0, s16
-        ]
-    };
-    let cases = [
-        ([0, 0, 0, 0], [0, 0]),
-        ([0x8000_0420, 0x0100_0001, 0, 0], [0x1_0086, 0x1_4186]),
-        ([0, 0x8000_0000, 0, 0], [0, 0x1_8000]),
-        ([u32::MAX, u32::MAX, 0, 0], [0x1_00ff, 0x1_ffff]),
-    ];
-    let inputs = cases.map(|(input, _)| input);
-    for (wide, opcode) in [0x2c, 0x2d].into_iter().enumerate() {
-        let shader = build_valu_cs(&pack_words(opcode));
-        run_cases(&shader, &inputs, |backend, i, _, got| {
-            assert_eq!(got, cases[i].1[wide], "{backend}, opcode {opcode:#x}");
-        });
-    }
-    let high = build_valu_cs(&[
-        0xBE90_2D00, // s_quadmask_b64 s[16:17], s[0:1]
-        vop1(1, 0, sgpr(17)),
-    ]);
-    run_cases(&high, &inputs, |backend, _, _, got| {
-        assert_eq!(got, 0, "{backend}: high dword");
-    });
-}
-
 fn is_f16_nan(bits: u16) -> bool {
     (bits & 0x7FFF) > 0x7C00
 }
@@ -718,51 +685,6 @@ fn v_min3_max3_med3_integer_forms_match_rdna2() {
     }
 }
 
-#[test]
-fn v_min3_max3_med3_integer_forms_match_rdna2() {
-    // v_{min3,max3,med3}_{i32,u32} v0, v1, v2, v3 (VOP3 0x152..0x159).
-    let ops: [(&str, u16, fn([u32; 3]) -> u32); 6] = [
-        ("v_min3_i32", 0x152, |t| {
-            t.into_iter().min_by_key(|&x| x as i32).unwrap()
-        }),
-        ("v_min3_u32", 0x153, |t| t.into_iter().min().unwrap()),
-        ("v_max3_i32", 0x155, |t| {
-            t.into_iter().max_by_key(|&x| x as i32).unwrap()
-        }),
-        ("v_max3_u32", 0x156, |t| t.into_iter().max().unwrap()),
-        ("v_med3_i32", 0x158, |mut t| {
-            t.sort_by_key(|&x| x as i32);
-            t[1]
-        }),
-        ("v_med3_u32", 0x159, |mut t| {
-            t.sort_unstable();
-            t[1]
-        }),
-    ];
-    // Every ordering of three values, with the sign bit set on some so that
-    // the signed and unsigned answers differ.
-    let values = [0u32, 1, 0x7FFF_FFFF, 0x8000_0000, 0xFFFF_FFFF];
-    let mut cases = Vec::new();
-    for a in values {
-        for b in values {
-            for c in values {
-                cases.push([a, b, c, 0]);
-            }
-        }
-    }
-    for (name, op, pick) in ops {
-        let shader = build_valu_cs(&vop3(op, 0, vgpr(1), vgpr(2), vgpr(3)));
-        run_cases(&shader, &cases, |backend, _, inp, got| {
-            let want = pick([inp[0], inp[1], inp[2]]);
-            assert_eq!(
-                got, want,
-                "{backend}: {name}({:#010x}, {:#010x}, {:#010x}) = {got:#010x}, want {want:#010x}",
-                inp[0], inp[1], inp[2],
-            );
-        });
-    }
-}
-
 #[test]
 fn v_med3_f16_matches_rdna2_with_nan() {
     // v_med3_f16 v0, v1, v2, v3 (VOP3 opcode 0x357)

+ 5 - 0
crates/victory-shader/src/gfx10/mod.rs

@@ -63,6 +63,11 @@ pub struct Instruction {
 }
 
 impl Instruction {
+    /// An instruction of these words, its name resolved.
+    pub fn new(offset: usize, encoding: Encoding, opcode: u16, words: Vec<u32>) -> Self {
+        Self { offset, encoding, opcode, words, name: name(encoding, opcode) }
+    }
+
     /// AMD's name for the opcode, if it is in our table.
     pub fn name(&self) -> Option<&'static str> {
         self.name

+ 1 - 6
crates/victory-shader/src/ir.rs

@@ -578,12 +578,7 @@ fn unspill(
     }
     let (store, pairs, codes) = chosen;
     let put = |list: &mut [gfx10::Instruction], i: usize, encoding, opcode: u16, word: u32| {
-        list[i] = gfx10::Instruction {
-            offset: list[i].offset,
-            encoding,
-            opcode,
-            words: vec![word],
-        };
+        list[i] = gfx10::Instruction::new(list[i].offset, encoding, opcode, vec![word]);
     };
     // `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.