Only changed dwords go back into title memory; cheap safe copies; title's own arguments; more shader forms
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
d9a31188be
commit
7fa012814f
16 files changed
+973
-29
No files matched your search
@@ -179,8 +179,11 @@ fn main() -> Result<()> {
|
||||
strict,
|
||||
execute,
|
||||
console,
|
||||
title_args: _,
|
||||
} => run::run(&exe, unimplemented, strict, execute, console),
|
||||
title_args,
|
||||
} => {
|
||||
victory_hle::runtime::set_title_args(title_args);
|
||||
run::run(&exe, unimplemented, strict, execute, console)
|
||||
}
|
||||
Command::Config => show_config(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ pub fn run(paths: Vec<PathBuf>, verbose: bool, disasm: bool) -> Result<()> {
|
||||
};
|
||||
found_here += 1;
|
||||
t.containers += 1;
|
||||
let dxil = container.part(FourCC::DXIL);
|
||||
let dxil = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC));
|
||||
t.with_dxil_part += usize::from(dxil.is_some());
|
||||
let program = dxil.and_then(|p| DxilProgram::parse(p.data).ok());
|
||||
let mut listing = Vec::new();
|
||||
|
||||
@@ -400,7 +400,7 @@ fn translate(
|
||||
let Ok(container) = Container::parse(&bytes) else {
|
||||
return t.fail("no DXIL part (SM5 or older)".into(), example);
|
||||
};
|
||||
let Some(dxil) = container.part(FourCC::DXIL).map(|p| p.data) else {
|
||||
let Some(dxil) = container.part(FourCC::DXIL).or(container.part(FourCC::ACCC)).map(|p| p.data) else {
|
||||
return t.fail("no DXIL part (SM5 or older)".into(), example);
|
||||
};
|
||||
// `~`: the hash of the code alone; containers that differ only around
|
||||
|
||||
@@ -5824,6 +5824,11 @@ pub(crate) fn read_into(src: *const u8, dst: &mut [u8]) -> bool {
|
||||
fn read(src: *const u8, dst: *mut u8, len: usize) -> bool {
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
if crate::safecopy::on() {
|
||||
// SAFETY: the destination is mapped writable memory of `len` bytes;
|
||||
// a source page that is not there fails the copy.
|
||||
return unsafe { crate::safecopy::copy(dst, src, len) };
|
||||
}
|
||||
let mut done = 0;
|
||||
// SAFETY: the destination is mapped writable memory of `len` bytes; the
|
||||
// kernel checks the source.
|
||||
@@ -5863,6 +5868,11 @@ pub(crate) fn write_mapped(dst: *mut u8, src: *const u8, len: usize) {
|
||||
let direct = direct_writes();
|
||||
let write = |at: usize, n: usize| {
|
||||
let from = src.wrapping_add(at - dst as usize);
|
||||
if crate::safecopy::on() {
|
||||
// SAFETY: the source is ours; a destination page that is not
|
||||
// there, or not writable, fails the copy.
|
||||
return unsafe { crate::safecopy::copy(at as *mut u8, from, n) };
|
||||
}
|
||||
let mut done = 0;
|
||||
if direct {
|
||||
// SAFETY: as below; the kernel checks the destination and
|
||||
@@ -6227,6 +6237,14 @@ impl Meter {
|
||||
#[cfg(feature = "diagnostics")]
|
||||
{
|
||||
log_blame(frames);
|
||||
let put = [0, 1, 2, 3].map(|i| crate::shadow::PUT[i].swap(0, Ordering::Relaxed) as f64 / frames);
|
||||
tracing::info!(
|
||||
"what shaders wrote put into title memory per frame (VICTORY_EXACT_BACK): {:.0} pieces in {:.0} writes, {:.1} MB; {:.0} pieces joined over gaps",
|
||||
put[0],
|
||||
put[1],
|
||||
put[2] / 1e6,
|
||||
put[3]
|
||||
);
|
||||
crate::copystat::log(std::mem::take(&mut self.copy_stats_frames) as f64);
|
||||
for (why, n) in drops.iter().take(40) {
|
||||
tracing::info!(
|
||||
|
||||
@@ -45,6 +45,8 @@ pub mod queue;
|
||||
pub mod resource;
|
||||
pub mod root;
|
||||
#[cfg(windows)]
|
||||
mod safecopy;
|
||||
#[cfg(windows)]
|
||||
mod sampler;
|
||||
#[cfg(windows)]
|
||||
pub mod shader_cache;
|
||||
|
||||
@@ -178,7 +178,7 @@ fn translate(container: &[u8]) -> Result<Translated, String> {
|
||||
// The translation depends on it (a view index past a capped heap).
|
||||
crate::descriptor::host::probe_view_limit();
|
||||
let c = Container::parse(container).map_err(|e| e.to_string())?;
|
||||
let programs = match c.part(FourCC::DXIL) {
|
||||
let programs = match c.part(FourCC::DXIL).or(c.part(FourCC::ACCC)) {
|
||||
Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,359 @@
|
||||
//! Copies between our memory and the title's that fail instead of faulting.
|
||||
//!
|
||||
//! Title memory may be unmapped, remapped or made read-only by the title's
|
||||
//! other threads while we copy it, so copies went through the kernel
|
||||
//! (`ReadProcessMemory`, `NtWriteVirtualMemory`), which reports a missing
|
||||
//! page instead of faulting: some 35,000 calls a frame, each of which locks
|
||||
//! the pages it copies, 39 ms of kernel time on the submitting thread alone.
|
||||
//!
|
||||
//! [`copy`] is one `rep movsb`. A fault in it is taken by the handler of
|
||||
//! [`crate::watch`] (`on_write`, the first in the process), which opens a
|
||||
//! block we guard ourselves and lets the copy go on, and otherwise sends it
|
||||
//! to its failing exit. `VICTORY_SAFE_COPY=0`: through the kernel, as before.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
std::arch::global_asm!(
|
||||
".globl victory_safe_copy",
|
||||
".globl victory_safe_copy_at",
|
||||
".globl victory_safe_copy_after",
|
||||
".globl victory_safe_copy_failed",
|
||||
// rcx destination, rdx source, r8 bytes; eax: whether all were copied.
|
||||
// A leaf that leaves the stack alone (the two registers it must give
|
||||
// back are kept in volatile ones), so a stack walk through it works.
|
||||
"victory_safe_copy:",
|
||||
"mov r10, rsi",
|
||||
"mov r11, rdi",
|
||||
"mov rdi, rcx",
|
||||
"mov rsi, rdx",
|
||||
"mov rcx, r8",
|
||||
"victory_safe_copy_at:",
|
||||
"rep movsb",
|
||||
"victory_safe_copy_after:",
|
||||
"mov eax, 1",
|
||||
"mov rsi, r10",
|
||||
"mov rdi, r11",
|
||||
"ret",
|
||||
"victory_safe_copy_failed:",
|
||||
"xor eax, eax",
|
||||
"mov rsi, r10",
|
||||
"mov rdi, r11",
|
||||
"ret",
|
||||
".globl victory_safe_put",
|
||||
".globl victory_safe_put_at",
|
||||
".globl victory_safe_put_after",
|
||||
".globl victory_safe_put_failed",
|
||||
// rcx destination, rdx what was there, r8 what is to be there, r9 blocks
|
||||
// of eight dwords: stores the dwords in which the two differ, and no
|
||||
// other byte. eax: whether all could be stored.
|
||||
"victory_safe_put:",
|
||||
"test r9, r9",
|
||||
"jz 4f",
|
||||
"vpcmpeqd ymm3, ymm3, ymm3",
|
||||
"2:",
|
||||
"vmovdqu ymm1, ymmword ptr [r8]",
|
||||
"vpcmpeqd ymm2, ymm1, ymmword ptr [rdx]",
|
||||
"vmovmskps eax, ymm2",
|
||||
"cmp eax, 255",
|
||||
"je 3f",
|
||||
"vpxor ymm2, ymm2, ymm3",
|
||||
"victory_safe_put_at:",
|
||||
"vpmaskmovd ymmword ptr [rcx], ymm2, ymm1",
|
||||
"victory_safe_put_after:",
|
||||
"nop",
|
||||
"3:",
|
||||
"add rcx, 32",
|
||||
"add rdx, 32",
|
||||
"add r8, 32",
|
||||
"dec r9",
|
||||
"jnz 2b",
|
||||
"vzeroupper",
|
||||
"4:",
|
||||
"mov eax, 1",
|
||||
"ret",
|
||||
"victory_safe_put_failed:",
|
||||
"vzeroupper",
|
||||
"xor eax, eax",
|
||||
"ret",
|
||||
);
|
||||
|
||||
unsafe extern "system" {
|
||||
fn victory_safe_copy(dst: *mut u8, src: *const u8, len: usize) -> u32;
|
||||
fn victory_safe_copy_at();
|
||||
fn victory_safe_copy_after();
|
||||
fn victory_safe_copy_failed();
|
||||
fn victory_safe_put(dst: *mut u8, was: *const u8, now: *const u8, blocks: usize) -> u32;
|
||||
fn victory_safe_put_at();
|
||||
fn victory_safe_put_after();
|
||||
fn victory_safe_put_failed();
|
||||
}
|
||||
|
||||
/// Puts `now` at `dst` where it differs from `was`, whole dwords (as `dst`
|
||||
/// is aligned) and not a byte beside them: other threads may be writing
|
||||
/// those. At the ends, single bytes of a dword only partly in the stretch.
|
||||
/// False if a page could not be written; then some may have been.
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`copy`]'s.
|
||||
pub(crate) unsafe fn put_changed(dst: *mut u8, was: &[u8], now: &[u8]) -> bool {
|
||||
assert_eq!(was.len(), now.len());
|
||||
let n = now.len();
|
||||
let head = dst.addr().wrapping_neg() & 3;
|
||||
let head = head.min(n);
|
||||
let blocks = (n - head) / 32;
|
||||
let tail = head + blocks * 32;
|
||||
let mut all = true;
|
||||
if blocks > 0 {
|
||||
// SAFETY: the two slices hold the blocks; the destination's faults
|
||||
// leave through the failing exit.
|
||||
all &= unsafe { victory_safe_put(dst.add(head), was[head..].as_ptr(), now[head..].as_ptr(), blocks) != 0 };
|
||||
}
|
||||
let single = |from: usize, to: usize| {
|
||||
let mut all = true;
|
||||
let mut i = from;
|
||||
while i < to {
|
||||
// A whole aligned dword, or the bytes there are of one.
|
||||
let len = (4 - (dst.addr() + i) % 4).min(to - i);
|
||||
if was[i..i + len] != now[i..i + len] {
|
||||
// SAFETY: inside the stretch.
|
||||
all &= unsafe { copy(dst.add(i), now[i..].as_ptr(), len) };
|
||||
}
|
||||
i += len;
|
||||
}
|
||||
all
|
||||
};
|
||||
all &= single(0, head);
|
||||
all &= single(tail, n);
|
||||
all
|
||||
}
|
||||
|
||||
/// Whether copies are made here and not by the kernel.
|
||||
pub(crate) fn on() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| {
|
||||
let on = std::env::var_os("VICTORY_SAFE_COPY").is_none_or(|v| v != "0");
|
||||
if on {
|
||||
crate::watch::install();
|
||||
}
|
||||
on
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies `len` bytes. False if a page of the source cannot be read or one
|
||||
/// of the destination cannot be written; then some of the bytes may have
|
||||
/// been copied.
|
||||
///
|
||||
/// # Safety
|
||||
/// Of the two ranges, what is not title memory must be valid, and no Rust
|
||||
/// reference may cover the destination. [`on`] must have been asked.
|
||||
pub(crate) unsafe fn copy(dst: *mut u8, src: *const u8, len: usize) -> bool {
|
||||
// SAFETY: a fault on either side leaves through the failing exit
|
||||
// ([`failing_exit`]); the rest is the caller's.
|
||||
unsafe { victory_safe_copy(dst, src, len) != 0 }
|
||||
}
|
||||
|
||||
/// For the fault handler: where a fault at instruction `at` is to go on, if
|
||||
/// it is [`copy`]'s.
|
||||
pub(crate) fn failing_exit(at: usize) -> Option<usize> {
|
||||
let (from, to) = (victory_safe_copy_at as *const () as usize, victory_safe_copy_after as *const () as usize);
|
||||
if (from..to).contains(&at) {
|
||||
return Some(victory_safe_copy_failed as *const () as usize);
|
||||
}
|
||||
let (from, to) = (victory_safe_put_at as *const () as usize, victory_safe_put_after as *const () as usize);
|
||||
(from..to).contains(&at).then_some(victory_safe_put_failed as *const () as usize)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use windows_sys::Win32::System::Memory::{
|
||||
MEM_COMMIT, MEM_DECOMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE, VirtualAlloc,
|
||||
VirtualFree, VirtualProtect,
|
||||
};
|
||||
|
||||
struct Pages(*mut u8, usize);
|
||||
|
||||
impl Pages {
|
||||
fn new(len: usize) -> Pages {
|
||||
// SAFETY: plain allocation.
|
||||
let at = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) };
|
||||
assert!(!at.is_null());
|
||||
Pages(at.cast(), len)
|
||||
}
|
||||
fn fill(&self) {
|
||||
for i in 0..self.1 {
|
||||
// SAFETY: inside the allocation.
|
||||
unsafe { self.0.add(i).write((i * 31 + 7) as u8) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Pages {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: our allocation.
|
||||
unsafe { VirtualFree(self.0.cast(), 0, MEM_RELEASE) };
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn copies_every_length_and_alignment() {
|
||||
assert!(on());
|
||||
let (a, b) = (Pages::new(1 << 16), Pages::new(1 << 16));
|
||||
a.fill();
|
||||
for len in [0usize, 1, 3, 4, 8, 31, 64, 255, 4095, 4096, 4097, 60_000] {
|
||||
for (da, sa) in [(0usize, 0usize), (1, 0), (0, 3), (5, 2)] {
|
||||
// SAFETY: inside the two allocations.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(b.0, 0xEE, b.1);
|
||||
assert!(copy(b.0.add(da), a.0.add(sa), len));
|
||||
let (to, from) = (std::slice::from_raw_parts(b.0, b.1), std::slice::from_raw_parts(a.0, a.1));
|
||||
assert_eq!(to[da..da + len], from[sa..sa + len]);
|
||||
assert!(to[..da].iter().chain(&to[da + len..]).all(|&x| x == 0xEE));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The dwords that changed are stored, and no byte of any other, at
|
||||
/// every alignment and length; a page that is not there fails.
|
||||
#[test]
|
||||
fn only_changed_dwords_are_put() {
|
||||
assert!(on());
|
||||
let pages = Pages::new(3 << 12);
|
||||
for at in [0usize, 1, 2, 3, 4, 13, 4090] {
|
||||
for len in [0usize, 1, 3, 4, 5, 31, 32, 33, 64, 100, 1000, 4096] {
|
||||
let was: Vec<u8> = (0..len).map(|i| (i * 13 + 1) as u8).collect();
|
||||
for step in [1usize, 5, 17, 64, 10_000] {
|
||||
let mut now = was.clone();
|
||||
for i in (0..len).step_by(step) {
|
||||
now[i] ^= 0x5A;
|
||||
}
|
||||
// Other threads changed everything meanwhile.
|
||||
// SAFETY: inside the allocation.
|
||||
unsafe {
|
||||
std::ptr::write_bytes(pages.0, 0xC3, pages.1);
|
||||
assert!(put_changed(pages.0.add(at), &was, &now));
|
||||
let there = std::slice::from_raw_parts(pages.0, pages.1);
|
||||
let base = pages.0.addr();
|
||||
for (k, &byte) in there.iter().enumerate() {
|
||||
let expect = if (at..at + len).contains(&k) {
|
||||
let dword = (base + k) / 4;
|
||||
let changed = (0..len).any(|i| now[i] != was[i] && (base + at + i) / 4 == dword);
|
||||
if changed { now[k - at] } else { 0xC3 }
|
||||
} else {
|
||||
0xC3
|
||||
};
|
||||
if byte != expect {
|
||||
panic!("at {at} len {len} step {step} byte {k}: {byte:#x}, not {expect:#x}");
|
||||
}
|
||||
if k > at + len + 64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// SAFETY: pages of our allocation.
|
||||
unsafe {
|
||||
VirtualFree(pages.0.add(4096).cast(), 4096, MEM_DECOMMIT);
|
||||
let (was, now) = (vec![0u8; 8192], vec![1u8; 8192]);
|
||||
assert!(!put_changed(pages.0, &was, &now));
|
||||
// Nothing differs on the page that is not there: nothing fails.
|
||||
let mut now = was.clone();
|
||||
now[0] = 1;
|
||||
assert!(put_changed(pages.0, &was, &now));
|
||||
}
|
||||
}
|
||||
|
||||
/// What the copies cost (ignored: a measurement): 64 KiB pieces of
|
||||
/// scattered memory into a buffer the card reads, by the kernel and here.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn copy_costs() {
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
|
||||
use windows_sys::Win32::System::Threading::GetCurrentProcess;
|
||||
assert!(on());
|
||||
let Some(host) = crate::host::host() else { return };
|
||||
const N: usize = 128 << 20;
|
||||
let from = Pages::new(N);
|
||||
from.fill();
|
||||
let (_buffer, shared) = host.shared_buffer(N as u64).expect("a shared buffer");
|
||||
let plain = Pages::new(N);
|
||||
plain.fill();
|
||||
for (what, to) in [("a buffer the card reads", shared), ("plain memory", plain.0)] {
|
||||
for piece in [256usize, 4 << 10, 64 << 10] {
|
||||
let count = (N / piece).min(4096);
|
||||
// A different, scattered piece each time.
|
||||
let at = |i: usize| (i * 7919 % (N / piece)) * piece;
|
||||
let time = |f: &dyn Fn(usize) -> bool| {
|
||||
let mut best = f64::MAX;
|
||||
for _ in 0..5 {
|
||||
let t = std::time::Instant::now();
|
||||
for i in 0..count {
|
||||
assert!(f(at(i)));
|
||||
}
|
||||
best = best.min(t.elapsed().as_secs_f64());
|
||||
}
|
||||
(best * 1e6 / count as f64, count as f64 * piece as f64 / best / 1e9)
|
||||
};
|
||||
// SAFETY: inside the buffers.
|
||||
let kernel = time(&|o| unsafe {
|
||||
let mut done = 0;
|
||||
ReadProcessMemory(GetCurrentProcess(), from.0.add(o).cast(), to.add(o).cast(), piece, &mut done) != 0
|
||||
});
|
||||
// SAFETY: as above.
|
||||
let here = time(&|o| unsafe { copy(to.add(o), from.0.add(o), piece) });
|
||||
// SAFETY: as above.
|
||||
let std_copy = time(&|o| unsafe {
|
||||
std::ptr::copy_nonoverlapping(from.0.add(o), to.add(o), piece);
|
||||
true
|
||||
});
|
||||
println!(
|
||||
"{piece:>6} bytes into {what}: kernel {:.2} us ({:.1} GB/s), rep movsb {:.2} us ({:.1} GB/s), memcpy {:.2} us ({:.1} GB/s)",
|
||||
kernel.0, kernel.1, here.0, here.1, std_copy.0, std_copy.1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Missing, forbidden and read-only pages: the copy fails, at any byte,
|
||||
/// and the process goes on.
|
||||
#[test]
|
||||
fn faults_are_failures() {
|
||||
assert!(on());
|
||||
let (a, b) = (Pages::new(3 << 12), Pages::new(3 << 12));
|
||||
a.fill();
|
||||
let mut old = 0;
|
||||
// SAFETY: pages of our allocations.
|
||||
unsafe {
|
||||
assert!(copy(b.0, a.0, b.1));
|
||||
VirtualProtect(a.0.add(4096).cast(), 4096, PAGE_NOACCESS, &mut old);
|
||||
assert!(!copy(b.0, a.0, b.1));
|
||||
assert!(copy(b.0, a.0, 4096));
|
||||
assert!(!copy(b.0, a.0.add(8191), 1));
|
||||
assert!(copy(b.0, a.0.add(8192), 4096));
|
||||
VirtualProtect(a.0.add(4096).cast(), 4096, PAGE_READWRITE, &mut old);
|
||||
VirtualFree(a.0.add(8192).cast(), 4096, MEM_DECOMMIT);
|
||||
assert!(!copy(b.0, a.0, b.1));
|
||||
VirtualProtect(b.0.add(4096).cast(), 4096, PAGE_READONLY, &mut old);
|
||||
assert!(!copy(b.0, a.0, 8192));
|
||||
assert!(!copy(std::ptr::without_provenance_mut(0x10), a.0, 4));
|
||||
assert!(!copy(b.0, std::ptr::without_provenance(usize::MAX - 7), 4));
|
||||
VirtualProtect(b.0.add(4096).cast(), 4096, PAGE_READWRITE, &mut old);
|
||||
}
|
||||
// Many faults, on several threads at once.
|
||||
let at = a.0 as usize;
|
||||
std::thread::scope(|s| {
|
||||
for _ in 0..4 {
|
||||
s.spawn(move || {
|
||||
let mut to = [0u8; 64];
|
||||
for _ in 0..500 {
|
||||
// SAFETY: a decommitted page and our own buffer.
|
||||
assert!(!unsafe { copy(to.as_mut_ptr(), (at + 8192) as *const u8, 64) });
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1409,9 +1409,114 @@ fn changed_runs(now: &[u8], was: &[u8]) -> Vec<(usize, usize)> {
|
||||
runs
|
||||
}
|
||||
|
||||
/// Whether what shaders wrote goes into title memory run by run
|
||||
/// ([`put_changed`]; on by default, `VICTORY_EXACT_BACK=0` writes the whole
|
||||
/// stretch from the first changed byte to the last, as before).
|
||||
fn exact_back() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_EXACT_BACK").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// Since the last frame-rate line: pieces put back by [`put_changed`], the
|
||||
/// writes they took, the bytes written, and the pieces whose runs were
|
||||
/// joined over bytes that had not changed.
|
||||
pub(crate) static PUT: [AtomicU64; 4] = [const { AtomicU64::new(0) }; 4];
|
||||
|
||||
/// The dwords (of title memory from `at` on) where `merged` differs from
|
||||
/// `title`, as (offset, bytes) in order, joined where at most `gap` bytes
|
||||
/// lie between.
|
||||
fn dword_runs(at: usize, title: &[u8], merged: &[u8], gap: usize) -> Vec<(usize, usize)> {
|
||||
let mut runs: Vec<(usize, usize)> = Vec::new();
|
||||
for (from, n) in changed_runs(merged, title) {
|
||||
// Shaders write dwords: the whole of each.
|
||||
let lo = ((at + from) & !3).max(at) - at;
|
||||
let hi = ((at + from + n + 3) & !3).min(at + title.len()) - at;
|
||||
match runs.last_mut() {
|
||||
Some((a, len)) if lo <= *a + *len + gap => *len = (*len).max(hi - *a),
|
||||
_ => runs.push((lo, hi - lo)),
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// What shaders wrote goes into title memory from `at` on: `title` is what
|
||||
/// was read there, `merged` the same with their bytes put in. Only the
|
||||
/// dwords that differ are written. The whole stretch from the first changed
|
||||
/// byte to the last was: between the read and the write the title's own
|
||||
/// threads, or data streamed in, may have written the bytes between (a heap
|
||||
/// holds what shaders write beside what the CPU does), and those writes were
|
||||
/// undone. Beside running title threads (the relay) that is a piece of
|
||||
/// memory going back in time now and then: runs pool1, blame1 and seriess2
|
||||
/// ended in the title decoding garbage.
|
||||
///
|
||||
/// shortcut: a piece with very many runs has them joined over small gaps,
|
||||
/// where the old race is left.
|
||||
fn put_changed(at: usize, title: &[u8], merged: &[u8]) -> usize {
|
||||
crate::watch::landing(at, title.len());
|
||||
if !exact_back() {
|
||||
crate::host::write_mapped(at as *mut u8, merged.as_ptr(), merged.len());
|
||||
return merged.len();
|
||||
}
|
||||
if crate::safecopy::on() {
|
||||
PUT[0].fetch_add(1, Ordering::Relaxed);
|
||||
PUT[2].fetch_add(merged.len() as u64, Ordering::Relaxed);
|
||||
// SAFETY: title memory; a page of it that is not there fails the
|
||||
// put, and the rest is put page by page.
|
||||
if unsafe { crate::safecopy::put_changed(at as *mut u8, title, merged) } {
|
||||
return merged.len();
|
||||
}
|
||||
let mut from = 0;
|
||||
while from < merged.len() {
|
||||
let n = (4096 - (at + from) % 4096).min(merged.len() - from);
|
||||
// SAFETY: as above.
|
||||
unsafe { crate::safecopy::put_changed((at + from) as *mut u8, &title[from..from + n], &merged[from..from + n]) };
|
||||
from += n;
|
||||
}
|
||||
return merged.len();
|
||||
}
|
||||
let mut runs = dword_runs(at, title, merged, 0);
|
||||
if runs.len() > 64 {
|
||||
runs = dword_runs(at, title, merged, 32);
|
||||
PUT[3].fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let mut written = 0;
|
||||
for &(from, n) in &runs {
|
||||
crate::host::write_mapped((at + from) as *mut u8, merged[from..].as_ptr(), n);
|
||||
written += n;
|
||||
}
|
||||
PUT[0].fetch_add(1, Ordering::Relaxed);
|
||||
PUT[1].fetch_add(runs.len() as u64, Ordering::Relaxed);
|
||||
PUT[2].fetch_add(written as u64, Ordering::Relaxed);
|
||||
written
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod merge_tests {
|
||||
use super::changed_runs;
|
||||
use super::{changed_runs, dword_runs};
|
||||
|
||||
/// Whole dwords around every changed byte and no other, whatever the
|
||||
/// alignment; small gaps joined only when asked.
|
||||
#[test]
|
||||
fn dword_runs_hold_the_dwords_that_changed() {
|
||||
let title: Vec<u8> = (0..200u32).map(|i| (i * 7 + 3) as u8).collect();
|
||||
for at in [0x1000usize, 0x1001, 0x1002, 0x1003] {
|
||||
for changes in [vec![0], vec![199], vec![5, 6], vec![8, 12, 40, 41, 43, 120]] {
|
||||
let mut merged = title.clone();
|
||||
for &c in &changes {
|
||||
merged[c] ^= 0x55;
|
||||
}
|
||||
let runs = dword_runs(at, &title, &merged, 0);
|
||||
let held: Vec<usize> = runs.iter().flat_map(|&(a, n)| a..a + n).collect();
|
||||
let mut expect: Vec<usize> = (0..200).filter(|i| changes.iter().any(|c| (at + c) / 4 == (at + i) / 4)).collect();
|
||||
expect.dedup();
|
||||
assert_eq!(held, expect, "{at:#x} {changes:?}");
|
||||
let joined = dword_runs(at, &title, &merged, 32);
|
||||
assert!(joined.len() <= runs.len());
|
||||
assert!(runs.iter().all(|r| joined.iter().any(|j| j.0 <= r.0 && r.0 + r.1 <= j.0 + j.1)));
|
||||
}
|
||||
}
|
||||
assert!(dword_runs(0, &title, &title, 0).is_empty());
|
||||
}
|
||||
|
||||
/// The runs hold exactly the bytes that differ: putting them into the
|
||||
/// old bytes gives the new ones, and no run holds an equal byte.
|
||||
@@ -2002,6 +2107,7 @@ impl Shadow {
|
||||
// before the submission, else the title's. (With the two
|
||||
// searches above this was 44 ms a frame for 970 pieces.)
|
||||
let mut differs = 0u8;
|
||||
let was = title.to_vec();
|
||||
for ((t, h), o) in title.iter_mut().zip(host.iter_mut()).zip(old) {
|
||||
let gpu = if *h != *o { 0xffu8 } else { 0 };
|
||||
let merged = (*t & !gpu) | (*h & gpu);
|
||||
@@ -2010,9 +2116,7 @@ impl Shadow {
|
||||
*h = merged;
|
||||
}
|
||||
if differs != 0 {
|
||||
crate::watch::landing(start + at, n);
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
written += n;
|
||||
written += put_changed(start + at, &was, title);
|
||||
}
|
||||
}
|
||||
// Our write shows as a title write at the copy's next refresh,
|
||||
@@ -2096,12 +2200,11 @@ impl Shadow {
|
||||
if !crate::host::read_into((start + at) as *const u8, title) {
|
||||
return 0;
|
||||
}
|
||||
let was = title.clone();
|
||||
if !merge_piece(now, held, title) {
|
||||
return 0;
|
||||
}
|
||||
crate::watch::landing(start + at, n);
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
n
|
||||
put_changed(start + at, &was, title)
|
||||
}
|
||||
|
||||
/// The 64 KiB pieces (cut at multiples of 64 KiB of title memory) of
|
||||
@@ -2619,6 +2722,7 @@ impl Shadow {
|
||||
// As in `copy_back`: the card's byte where it is not what it
|
||||
// was before the submission, else the title's.
|
||||
let mut differs = 0u8;
|
||||
let was = title.clone();
|
||||
for ((t, g), o) in title.iter_mut().zip(gpu).zip(old.iter_mut()) {
|
||||
let wrote = if *g != *o { 0xffu8 } else { 0 };
|
||||
let merged = (*t & !wrote) | (*g & wrote);
|
||||
@@ -2627,9 +2731,7 @@ impl Shadow {
|
||||
*o = merged;
|
||||
}
|
||||
if differs != 0 {
|
||||
crate::watch::landing(start + at, n);
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
written = n;
|
||||
written = put_changed(start + at, &was, title);
|
||||
}
|
||||
} else {
|
||||
// Title memory is not mapped there: the copy keeps what the
|
||||
@@ -2692,6 +2794,7 @@ impl Shadow {
|
||||
title.clear();
|
||||
title.resize(n, 0);
|
||||
let mapped = crate::host::read_into((start + at) as *const u8, title);
|
||||
let was = title.clone();
|
||||
let mut changed = false;
|
||||
for (a, b) in outside(at, at + n, skip) {
|
||||
let (a, b) = (a - at, b - at);
|
||||
@@ -2702,9 +2805,7 @@ impl Shadow {
|
||||
if !mapped || !changed {
|
||||
return 0;
|
||||
}
|
||||
crate::watch::landing(start + at, n);
|
||||
crate::host::write_mapped((start + at) as *mut u8, title.as_ptr(), n);
|
||||
n
|
||||
put_changed(start + at, &was, title)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -758,7 +758,7 @@ pub fn title_memory_remapped(at: usize, len: usize) {
|
||||
|
||||
/// Registers the handler that takes writes to guarded blocks, once, ahead
|
||||
/// of the crash reporter's.
|
||||
fn install() {
|
||||
pub(crate) fn install() {
|
||||
use windows_sys::Win32::Foundation::{EXCEPTION_ACCESS_VIOLATION, NTSTATUS};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::{
|
||||
AddVectoredExceptionHandler, EXCEPTION_CONTINUE_EXECUTION, EXCEPTION_CONTINUE_SEARCH,
|
||||
@@ -768,11 +768,22 @@ fn install() {
|
||||
// SAFETY: the system passes the exception being dispatched.
|
||||
let r = unsafe { &*(*info).ExceptionRecord };
|
||||
const WRITE: usize = 1;
|
||||
// A fault of our own copies (`crate::safecopy`): whatever it is, if
|
||||
// it is not a block we guard, the copy fails and goes on from there.
|
||||
let ours = crate::safecopy::failing_exit(r.ExceptionAddress as usize);
|
||||
let fail = |exit: usize| {
|
||||
// SAFETY: the context the system passes, to go on from.
|
||||
unsafe { (*(*info).ContextRecord).Rip = exit as u64 };
|
||||
EXCEPTION_CONTINUE_EXECUTION
|
||||
};
|
||||
if r.ExceptionCode != EXCEPTION_ACCESS_VIOLATION as NTSTATUS
|
||||
|| r.NumberParameters < 2
|
||||
|| r.ExceptionInformation[0] != WRITE
|
||||
{
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
return match ours {
|
||||
Some(exit) => fail(exit),
|
||||
None => EXCEPTION_CONTINUE_SEARCH,
|
||||
};
|
||||
}
|
||||
let at = r.ExceptionInformation[1];
|
||||
// Held across both checks: another thread may have opened the block
|
||||
@@ -785,9 +796,11 @@ fn install() {
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
if writable(at) {
|
||||
EXCEPTION_CONTINUE_EXECUTION
|
||||
} else {
|
||||
EXCEPTION_CONTINUE_SEARCH
|
||||
return EXCEPTION_CONTINUE_EXECUTION;
|
||||
}
|
||||
match ours {
|
||||
Some(exit) => fail(exit),
|
||||
None => EXCEPTION_CONTINUE_SEARCH,
|
||||
}
|
||||
}
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
// API would trust.
|
||||
#![allow(clippy::not_unsafe_ptr_arg_deref)]
|
||||
|
||||
use std::ffi::{CStr, c_void};
|
||||
use std::ffi::{CStr, c_char, c_void};
|
||||
|
||||
use crate::{HleModule, HostPolicy, hle_export, registry, runtime};
|
||||
|
||||
@@ -350,6 +350,57 @@ fn refuse(file: &str) {
|
||||
|
||||
const ERROR_MOD_NOT_FOUND: u32 = 126;
|
||||
|
||||
/// The title's argument list: the program, then what was given after `--`.
|
||||
/// The host's own would be ours (`victory run <exe> ...`), and the title
|
||||
/// looks at fixed places in it (`-skipToIIS` only as the first argument).
|
||||
struct TitleArgv {
|
||||
count: std::cell::UnsafeCell<i32>,
|
||||
list: std::cell::UnsafeCell<*mut *mut c_char>,
|
||||
}
|
||||
|
||||
// SAFETY: never written here after it was made; the title's C runtime start
|
||||
// reads it once, on one thread.
|
||||
unsafe impl Send for TitleArgv {}
|
||||
// SAFETY: as above.
|
||||
unsafe impl Sync for TitleArgv {}
|
||||
|
||||
/// Kept for the whole run: the title holds on to the pointers.
|
||||
fn title_argv(program: &str, args: &[String]) -> TitleArgv {
|
||||
let list: Vec<*mut c_char> = std::iter::once(program)
|
||||
.chain(args.iter().map(String::as_str))
|
||||
.filter_map(|a| std::ffi::CString::new(a).ok())
|
||||
.map(std::ffi::CString::into_raw)
|
||||
.collect();
|
||||
let count = list.len() as i32;
|
||||
// `argv[argc]` is null.
|
||||
let list: Box<[*mut c_char]> = list.into_iter().chain(Some(std::ptr::null_mut())).collect();
|
||||
TitleArgv {
|
||||
count: count.into(),
|
||||
list: Box::leak(list).as_mut_ptr().into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn argv() -> &'static TitleArgv {
|
||||
static ARGV: std::sync::OnceLock<TitleArgv> = std::sync::OnceLock::new();
|
||||
ARGV.get_or_init(|| {
|
||||
// The program's name stays what the host says (as it was before).
|
||||
let program = std::env::args_os().next().unwrap_or_default();
|
||||
let args = runtime::title_args();
|
||||
tracing::info!(?args, "the title's arguments");
|
||||
title_argv(&program.to_string_lossy(), args)
|
||||
})
|
||||
}
|
||||
|
||||
/// See [`TitleArgv`].
|
||||
pub extern "C" fn __p___argc() -> *mut i32 {
|
||||
argv().count.get()
|
||||
}
|
||||
|
||||
/// See [`TitleArgv`].
|
||||
pub extern "C" fn __p___argv() -> *mut *mut *mut c_char {
|
||||
argv().list.get()
|
||||
}
|
||||
|
||||
pub(crate) fn module() -> HleModule {
|
||||
HleModule {
|
||||
name: "kernel",
|
||||
@@ -363,6 +414,8 @@ pub(crate) fn module() -> HleModule {
|
||||
"api-ms-win-crt-runtime-*",
|
||||
],
|
||||
exports: vec![
|
||||
hle_export!(__p___argc),
|
||||
hle_export!(__p___argv),
|
||||
hle_export!(GetModuleHandleW),
|
||||
hle_export!(GetModuleHandleA),
|
||||
hle_export!(GetModuleFileNameW),
|
||||
@@ -615,6 +668,29 @@ mod tests {
|
||||
assert_eq!(&small, &[b'C', b':', b'\\', 0]);
|
||||
}
|
||||
|
||||
/// The title's arguments come right after the program, and the list ends
|
||||
/// in a null pointer; without any there is only the program.
|
||||
#[test]
|
||||
fn the_title_gets_its_own_arguments() {
|
||||
let read = |made: &TitleArgv| {
|
||||
// SAFETY: made above, kept for the whole run.
|
||||
unsafe {
|
||||
let (count, list) = (*made.count.get() as usize, *made.list.get());
|
||||
assert!((*list.add(count)).is_null());
|
||||
(0..count)
|
||||
.map(|i| CStr::from_ptr(*list.add(i)).to_str().unwrap().to_owned())
|
||||
.collect::<Vec<_>>()
|
||||
}
|
||||
};
|
||||
let some = title_argv("victory.exe", &["-skipToIIS".into(), "-x=1".into()]);
|
||||
assert_eq!(read(&some), ["victory.exe", "-skipToIIS", "-x=1"]);
|
||||
assert_eq!(read(&title_argv("victory.exe", &[])), ["victory.exe"]);
|
||||
// What the title is given: the same list every time.
|
||||
assert_eq!(__p___argc(), __p___argc());
|
||||
// SAFETY: as above.
|
||||
unsafe { assert_eq!((*__p___argc(), (**__p___argv()).is_null()), (1, false)) };
|
||||
}
|
||||
|
||||
fn w(text: &str) -> Vec<u16> {
|
||||
text.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
@@ -55,6 +55,18 @@ pub fn image_named(file: &str) -> Option<usize> {
|
||||
.map(|(b, _)| *b)
|
||||
}
|
||||
|
||||
static TITLE_ARGS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
|
||||
|
||||
/// The arguments the title's `main` gets (those after `--`). Set once, before
|
||||
/// the title starts; later calls are ignored.
|
||||
pub fn set_title_args(args: Vec<String>) {
|
||||
let _ = TITLE_ARGS.set(args);
|
||||
}
|
||||
|
||||
pub fn title_args() -> &'static [String] {
|
||||
TITLE_ARGS.get().map_or(&[], Vec::as_slice)
|
||||
}
|
||||
|
||||
/// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its
|
||||
/// base; `Ok(None)` if `file` is not one of the title's DLLs.
|
||||
pub type TitleDllLoader = Box<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>;
|
||||
|
||||
@@ -17,6 +17,8 @@ pub struct FourCC(pub [u8; 4]);
|
||||
|
||||
impl FourCC {
|
||||
pub const DXIL: FourCC = FourCC(*b"DXIL");
|
||||
/// Native code another compiler made, in place of `DXIL` (VIctory upstream 0b35b7f).
|
||||
pub const ACCC: FourCC = FourCC(*b"ACCC");
|
||||
pub const STAT: FourCC = FourCC(*b"STAT");
|
||||
pub const RTS0: FourCC = FourCC(*b"RTS0");
|
||||
pub const PSV0: FourCC = FourCC(*b"PSV0");
|
||||
|
||||
@@ -3110,6 +3110,12 @@ impl<'a> Lower<'a> {
|
||||
let v = inst.read(Reg::V(reg)).ok_or("an unread operand")?;
|
||||
self.i32_of(v)
|
||||
}
|
||||
// src_scc: SCC as 0 or 1 (VIctory upstream 0b35b7f, as the dot
|
||||
// products and packed multiply-adds below).
|
||||
Operand::Const(253) => {
|
||||
let bit = self.scc_in(inst)?;
|
||||
Ok(self.s.m.cast(self.cur, Cast::ZExt, bit, self.s.t.i32))
|
||||
}
|
||||
Operand::Const(c) => crate::resource::inline(c)
|
||||
.map(|x| self.s.m.i32(x))
|
||||
.ok_or("a special operand (vccz, execz, scc, lds_direct)"),
|
||||
@@ -6955,6 +6961,61 @@ impl<'a> Lower<'a> {
|
||||
.op(c, "unaryBits.i32", Attr::ReadNone, self.s.t.i32, op, &[a]);
|
||||
int(self, r)
|
||||
}
|
||||
"v_dot4c_i32_i8" => {
|
||||
// D += the dot product of four signed bytes, wrapping: DXIL's
|
||||
// Dot4AddI8Packed.
|
||||
let (a, bb) = (s(self, 0)?, s(self, 1)?);
|
||||
let Some(Operand::Vector { reg, .. }) = v.dst else {
|
||||
return Err("an accumulator");
|
||||
};
|
||||
let acc = self.i32_of(inst.read(Reg::V(reg)).ok_or("an accumulator")?)?;
|
||||
let i32_ty = self.s.t.i32;
|
||||
let r = self.s.op(
|
||||
c,
|
||||
"dot4AddPacked.i32",
|
||||
Attr::ReadNone,
|
||||
i32_ty,
|
||||
163,
|
||||
&[acc, a, bb],
|
||||
);
|
||||
int(self, r)
|
||||
}
|
||||
"v_dot4_i32_i8" => {
|
||||
// VOP3P: op_sel picks the half each multiplicand's low half
|
||||
// reads, op_sel_hi its high half's; the accumulator is read
|
||||
// whole (as AMD's compilers fold constants into it).
|
||||
if v.clamp || v.neg_hi != 0 {
|
||||
return Err("a saturating or negated dot product");
|
||||
}
|
||||
let mut xs = Vec::new();
|
||||
for k in 0..2 {
|
||||
let x = s(self, k)?;
|
||||
let (lo, hi) = (v.opsel >> k & 1 != 0, v.opsel_hi >> k & 1 != 0);
|
||||
if (lo, hi) == (false, true) {
|
||||
xs.push(x);
|
||||
continue;
|
||||
}
|
||||
let (k16, low) = (self.s.m.i32(16), self.s.m.i32(0xFFFF));
|
||||
let top = self.s.m.bin(c, Bin::LShr, x, k16);
|
||||
let bottom = self.s.m.bin(c, Bin::And, x, low);
|
||||
let hi = self
|
||||
.s
|
||||
.m
|
||||
.bin(c, Bin::Shl, if hi { top } else { bottom }, k16);
|
||||
xs.push(self.s.m.bin(c, Bin::Or, if lo { top } else { bottom }, hi));
|
||||
}
|
||||
let acc = s(self, 2)?;
|
||||
let i32_ty = self.s.t.i32;
|
||||
let r = self.s.op(
|
||||
c,
|
||||
"dot4AddPacked.i32",
|
||||
Attr::ReadNone,
|
||||
i32_ty,
|
||||
163,
|
||||
&[acc, xs[0], xs[1]],
|
||||
);
|
||||
int(self, r)
|
||||
}
|
||||
"v_mov_b32" => {
|
||||
if v.abs != 0 || v.neg != 0 || v.clamp || v.omod != 0 {
|
||||
let a = f(self, 0)?;
|
||||
@@ -8411,6 +8472,30 @@ impl<'a> Lower<'a> {
|
||||
Ok(self.s.m.bin(c, Bin::And, x, m))
|
||||
}
|
||||
|
||||
/// Half `high` of source `k` of `v_pk_fmac_f16`, in the low 16 bits: a
|
||||
/// VOP2 operation (no op_sel) whose third source is its destination.
|
||||
fn fmac_half(&mut self, inst: &Inst, k: usize, high: bool) -> Result<V, Why> {
|
||||
let Fields::Valu(v) = &inst.fields else {
|
||||
unreachable!()
|
||||
};
|
||||
let op = if k == 2 { v.dst } else { v.src.get(k).copied() };
|
||||
let op = op.ok_or("a missing operand")?;
|
||||
if matches!(op, Operand::Const(_) | Operand::Literal(_)) {
|
||||
// shortcut: no constant operand seen; its high half is not known.
|
||||
return Err("a constant operand of v_pk_fmac_f16");
|
||||
}
|
||||
let x = self.operand(inst, &op)?;
|
||||
let c = self.cur;
|
||||
let x = if high {
|
||||
let k16 = self.s.m.i32(16);
|
||||
self.s.m.bin(c, Bin::LShr, x, k16)
|
||||
} else {
|
||||
x
|
||||
};
|
||||
let m = self.s.m.i32(0xFFFF);
|
||||
Ok(self.s.m.bin(c, Bin::And, x, m))
|
||||
}
|
||||
|
||||
/// Packed 16-bit operations (`v_pk_*`): each half computed as the
|
||||
/// 16-bit operation does, f16 through f32 as in [`Self::valu16`].
|
||||
fn packed16(&mut self, inst: &Inst, op: &str, guard: Option<V>) -> Result<(), Why> {
|
||||
@@ -8419,7 +8504,7 @@ impl<'a> Lower<'a> {
|
||||
};
|
||||
let float = op.ends_with("_f16");
|
||||
let n = match op {
|
||||
"fma_f16" | "mad_u16" | "mad_i16" => 3,
|
||||
"fma_f16" | "fmac_f16" | "mad_u16" | "mad_i16" => 3,
|
||||
"add_f16" | "mul_f16" | "min_f16" | "max_f16" | "add_u16" | "sub_u16" | "add_i16"
|
||||
| "sub_i16" | "mul_lo_u16" | "lshlrev_b16" | "lshrrev_b16" | "ashrrev_i16"
|
||||
| "max_u16" | "min_u16" | "max_i16" | "min_i16" => 2,
|
||||
@@ -8434,7 +8519,11 @@ impl<'a> Lower<'a> {
|
||||
for high in [false, true] {
|
||||
let mut xs = Vec::new();
|
||||
for k in 0..n {
|
||||
let h = self.packed_src(inst, k, high, float)?;
|
||||
let h = if op == "fmac_f16" {
|
||||
self.fmac_half(inst, k, high)?
|
||||
} else {
|
||||
self.packed_src(inst, k, high, float)?
|
||||
};
|
||||
if float {
|
||||
let mut f = self
|
||||
.s
|
||||
@@ -9480,7 +9569,8 @@ impl<'a> Lower<'a> {
|
||||
let Fields::Image { cache, .. } = &inst.fields else {
|
||||
unreachable!()
|
||||
};
|
||||
if *d16 || *a16 {
|
||||
// 16-bit coordinates (a16) are read as `addr_val` reads them.
|
||||
if *d16 {
|
||||
return Err("a 16-bit image atomic");
|
||||
}
|
||||
// Compare-exchange consumes a replacement followed by a comparand.
|
||||
|
||||
@@ -284,6 +284,7 @@ pub fn translate(container: &[u8]) -> Result<HostShader, ShaderError> {
|
||||
let c = Container::parse(container)?;
|
||||
let dxil = c
|
||||
.part(FourCC::DXIL)
|
||||
.or(c.part(FourCC::ACCC))
|
||||
.ok_or(ShaderError::Malformed("no DXIL part"))?;
|
||||
let native = crate::native_programs(dxil.data)?
|
||||
.into_iter()
|
||||
|
||||
@@ -120,6 +120,18 @@ const CS_THREADS: usize = 0x28;
|
||||
const RECORD_LDS: usize = 0x4c;
|
||||
const MS_CLIP_CNTL: usize = 0x194;
|
||||
const MS_INFO: usize = 0x448;
|
||||
const FSPX_VERSION: u32 = 1;
|
||||
const FSPX_HEADER: usize = 0x10;
|
||||
const FSPX_PACKET: u32 = 0;
|
||||
const FSPX_CODE: u32 = 6;
|
||||
const FSPX_METADATA: u32 = 7;
|
||||
const PACKET_THREADS: usize = 0x0c;
|
||||
const PACKET_FLAGS: usize = 0x12;
|
||||
const PACKET_WAVE32: u16 = 1 << 4;
|
||||
const PACKET_RSRC1: usize = 0x14;
|
||||
const PACKET_RSRC2: usize = 0x18;
|
||||
const FSPX_RECORDS: usize = 0x18;
|
||||
const FSPX_RECORD: usize = 32;
|
||||
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
|
||||
const MAX_UNPACKED: u64 = 16 << 20;
|
||||
|
||||
@@ -409,8 +421,12 @@ pub struct UsedResource {
|
||||
pub slot: u8,
|
||||
}
|
||||
|
||||
/// The native programs in a `DXIL` part's data; empty for the PC layout.
|
||||
/// The native programs in a `DXIL` part's data, or in an `ACCC` part's
|
||||
/// ([`fspx_program`]); empty for the PC layout.
|
||||
pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
|
||||
if part.starts_with(b"FSPX") {
|
||||
return Ok(vec![fspx_program(part)?]);
|
||||
}
|
||||
if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
@@ -432,6 +448,129 @@ pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The compute program of an `ACCC` part, which a container carries in place
|
||||
/// of `DXIL` when another compiler made the native code (the AMD
|
||||
/// FidelityFX upscaler's shaders). Layout as observed (offsets from "FSPX"):
|
||||
///
|
||||
/// ```text
|
||||
/// +0x00 "FSPX" u32 version (1), u32 entry count, u32 size; entries of 16 B
|
||||
/// from +0x10: u32 kind, u32 offset, u32 size, u32 0
|
||||
/// kind 0 pipeline registers, 0x1c B: +0x0c u16 x3 thread-group size,
|
||||
/// +0x12 u16 flags (bit 4 wave32), +0x14 COMPUTE_PGM_RSRC1,
|
||||
/// +0x18 COMPUTE_PGM_RSRC2
|
||||
/// kind 1 pipeline metadata (a hash); kind 6 the GFX10 code
|
||||
/// kind 7 program metadata: u32 0x403, u32 size - 0x14, u32 code dwords,
|
||||
/// u64 0, u8 0x40, u8 first user-data dword, u8 count of 0x41
|
||||
/// records, u8 0; then 32-byte records from +0x18, each a u32 tag:
|
||||
/// 0x41 a resource the code reads: u8 resource type (as FSSM's used
|
||||
/// entries), u8 root type, u16 0, u32 table offset (dwords), u32
|
||||
/// register, u32 view dimension (1 buffer, 4 2D, 0 root view),
|
||||
/// u8 descriptor dwords, u8 user-data dword, u8 root slot, u8 0,
|
||||
/// u32 -1, u32 0
|
||||
/// 0x42 a view declaration: u32 0, u8 1, u8 class (0 SRV, 1 UAV),
|
||||
/// u8 resource kind (DXIL's), u8 0, u32 register
|
||||
/// 0x43 the shader hash (16 B); the last record
|
||||
/// ```
|
||||
pub fn fspx_program(part: &[u8]) -> Result<NativeProgram, ShaderError> {
|
||||
if u32_at(part, 4)? != FSPX_VERSION {
|
||||
return Err(Malformed("unknown FSPX version"));
|
||||
}
|
||||
let count = u32_at(part, 8)? as usize;
|
||||
if count > MAX_XDAT_ENTRIES {
|
||||
return Err(Malformed("implausible FSPX entry count"));
|
||||
}
|
||||
let entry = |kind: u32| -> Result<&[u8], ShaderError> {
|
||||
for i in 0..count {
|
||||
let at = FSPX_HEADER + 16 * i;
|
||||
if u32_at(part, at)? == kind {
|
||||
let (offset, size) = (u32_at(part, at + 4)?, u32_at(part, at + 8)?);
|
||||
return bytes(part, offset.into(), size.into())
|
||||
.ok_or(Malformed("FSPX entry out of bounds"));
|
||||
}
|
||||
}
|
||||
Err(Malformed("FSPX entry missing"))
|
||||
};
|
||||
let packet = entry(FSPX_PACKET)?;
|
||||
let code = entry(FSPX_CODE)?;
|
||||
let meta = entry(FSPX_METADATA)?;
|
||||
if u32_at(meta, 8)? as usize * 4 != code.len() {
|
||||
return Err(Malformed("FSPX code size disagrees"));
|
||||
}
|
||||
let wave64 = u16_at(packet, PACKET_FLAGS)? & PACKET_WAVE32 == 0;
|
||||
// VGPRs in granules of 4 (wave64) or 8 (wave32).
|
||||
let granules = (u32_at(packet, PACKET_RSRC1)? & 0x3F) + 1;
|
||||
let vgprs = (granules * if wave64 { 4 } else { 8 }).min(256) as u16;
|
||||
let threads = |i: usize| u16_at(packet, PACKET_THREADS + 2 * i).map(u32::from);
|
||||
let mut layout: Vec<RootParam> = Vec::new();
|
||||
let mut used = Vec::new();
|
||||
for e in meta
|
||||
.get(FSPX_RECORDS..)
|
||||
.unwrap_or(&[])
|
||||
.as_chunks::<FSPX_RECORD>()
|
||||
.0
|
||||
{
|
||||
match e[0] {
|
||||
0x41 => {}
|
||||
0x42 => continue,
|
||||
0x43 => break,
|
||||
_ => return Err(Malformed("unknown FSPX metadata record")),
|
||||
}
|
||||
let root = RootType::from_raw(e[5].into());
|
||||
let u = UsedResource {
|
||||
kind: match e[4] {
|
||||
0 => ResourceType::Srv,
|
||||
1 => ResourceType::Sampler,
|
||||
2 => ResourceType::Cbv,
|
||||
3 => ResourceType::Uav,
|
||||
n => ResourceType::Other(n),
|
||||
},
|
||||
root,
|
||||
table_offset_dwords: le32(e, 8),
|
||||
lower_bound: le32(e, 12),
|
||||
stride: 0,
|
||||
dwords: e[20],
|
||||
user_data: e[21],
|
||||
slot: e[22],
|
||||
};
|
||||
let sgprs = match root {
|
||||
RootType::Table => 1,
|
||||
RootType::Descriptor => 2,
|
||||
// The code holds its words; no user data.
|
||||
RootType::ImmediateSampler => 0,
|
||||
_ => return Err(Malformed("an FSPX resource of an unknown root type")),
|
||||
};
|
||||
if sgprs > 0 && !layout.iter().any(|p| p.slot == u.slot) {
|
||||
layout.push(RootParam {
|
||||
root,
|
||||
table_offset_dwords: 0,
|
||||
sgprs,
|
||||
base_register: u.lower_bound,
|
||||
user_data: u.user_data,
|
||||
slot: u.slot,
|
||||
});
|
||||
}
|
||||
used.push(u);
|
||||
}
|
||||
Ok(NativeProgram {
|
||||
stage: HwStage::Cs,
|
||||
wave64,
|
||||
vgprs,
|
||||
layout,
|
||||
used,
|
||||
io: StageIo::Cs(ComputeIo {
|
||||
rsrc2: u32_at(packet, PACKET_RSRC2)?,
|
||||
threads: [threads(0)?, threads(1)?, threads(2)?],
|
||||
}),
|
||||
code: code.to_vec(),
|
||||
})
|
||||
}
|
||||
|
||||
fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
|
||||
data.get(at..at + 2)
|
||||
.map(|b| u16::from_le_bytes([b[0], b[1]]))
|
||||
.ok_or(Malformed("FSPX data out of bounds"))
|
||||
}
|
||||
|
||||
fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> {
|
||||
if blob.get(0..4) != Some(b"XBCH") {
|
||||
return Err(Malformed("native blob lacks XBCH magic"));
|
||||
|
||||
@@ -1118,10 +1118,17 @@ impl<'a> Tracer<'a> {
|
||||
let Operand::Scalar { code, dwords } = *op else {
|
||||
return Err("a descriptor not in SGPRs");
|
||||
};
|
||||
let words = (0..dwords)
|
||||
let mut words = (0..dwords)
|
||||
.map(|k| inst.read(Reg::S(code + k)).map(|v| self.origin(v)))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.ok_or("a descriptor not in SGPRs")?;
|
||||
// A byte access through a buffer descriptor made raw reads what the
|
||||
// descriptor's view does with a raw host view (VIctory upstream 0b35b7f).
|
||||
if !inst.name().contains("format")
|
||||
&& let Some(raw) = self.made_raw(&words)
|
||||
{
|
||||
words = raw.to_vec();
|
||||
}
|
||||
// Only the lanes that reach the access read the descriptor.
|
||||
let mut known = Vec::from_iter(self.lanes.map(|l| (l.reach[at], true)));
|
||||
self.classify(&words, &mut Vec::new(), &mut known)
|
||||
@@ -1462,6 +1469,46 @@ impl<'a> Tracer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The words of a buffer descriptor that `words` makes raw, as the
|
||||
/// FidelityFX upscaler's compiler does before byte accesses: the stride
|
||||
/// (dword 1 bits 16-29) cleared, the record count times max(stride, 1),
|
||||
/// out-of-bounds checking by bytes (dword 3 bits 28-29 set). The bounds
|
||||
/// are then the view's size in bytes either way.
|
||||
fn made_raw(&self, words: &[Term]) -> Option<[Term; 4]> {
|
||||
let [w0, Term::Value(w1), Term::Value(w2), Term::Value(w3)] = *words else {
|
||||
return None;
|
||||
};
|
||||
// `x op c` with `c` either side.
|
||||
let with = |v: Value, name: &str, c: u32| match self.sop2(v, &[name])?.1 {
|
||||
[x, Term::Const(k)] | [Term::Const(k), x] if k == c => Some(x),
|
||||
_ => None,
|
||||
};
|
||||
let d1 = with(w1, "s_and_b32", 0xC000_FFFF)?;
|
||||
let Term::Value(m3) = with(w3, "s_or_b32", 0x3000_0000)? else {
|
||||
return None;
|
||||
};
|
||||
let d3 = with(m3, "s_and_b32", 0xCFFF_FFFF)?;
|
||||
let [a, b] = self.sop2(w2, &["s_mul_i32"])?.1;
|
||||
let max = |t: Term| match t {
|
||||
Term::Value(s) => with(s, "s_max_u32", 1),
|
||||
Term::Const(_) => None,
|
||||
};
|
||||
let (d2, field) = match (max(a), max(b)) {
|
||||
(_, Some(f)) => (a, f),
|
||||
(Some(f), None) => (b, f),
|
||||
(None, None) => return None,
|
||||
};
|
||||
let Term::Value(field) = field else {
|
||||
return None;
|
||||
};
|
||||
// s_bfe_u32: offset 16, width 14.
|
||||
let (_, [x, Term::Const(0x000E_0010)]) = self.sop2(field, &["s_bfe_u32"])? else {
|
||||
return None;
|
||||
};
|
||||
(x == d1).then_some([w0, d1, d2, d3])
|
||||
}
|
||||
|
||||
|
||||
/// For a `v_readfirstlane_b32` result: the VGPR value it reads.
|
||||
fn first_lane_source(&self, v: Value) -> Option<Value> {
|
||||
let inst = self.def(v)?;
|
||||
@@ -2331,6 +2378,12 @@ fn copy_source(inst: &Inst, k: usize) -> Option<Moved> {
|
||||
if inst.name() == "s_movk_i32" {
|
||||
return Some(Moved::Const(i32::from((*imm)? as i16) as u32));
|
||||
}
|
||||
// A mask of S0 bits from bit S1, as the upscaler's compiler makes an
|
||||
// immediate sampler's word.
|
||||
if let ("s_bfm_b32", 0, [Operand::Const(w), Operand::Const(at)]) = (inst.name(), k, &src[..]) {
|
||||
let (w, at) = (inline(*w)? & 31, inline(*at)? & 31);
|
||||
return Some(Moved::Const(((1u32 << w) - 1) << at));
|
||||
}
|
||||
let src = src.first()?;
|
||||
match (inst.name(), *src) {
|
||||
("s_mov_b32" | "s_mov_b64", Operand::Scalar { code, .. }) if code != NULL => {
|
||||
@@ -2343,6 +2396,11 @@ fn copy_source(inst: &Inst, k: usize) -> Option<Moved> {
|
||||
// that has no inline form; fold more if descriptors need it.
|
||||
("s_brev_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(x.reverse_bits())),
|
||||
("s_not_b32", Operand::Const(c)) => inline(c).map(|x| Moved::Const(!x)),
|
||||
// shortcut: a literal below 2^31, whose high dword is 0 whether the
|
||||
// hardware extends it with zeros or with its sign.
|
||||
("s_mov_b64", Operand::Literal(x)) if x >> 31 == 0 => {
|
||||
Some(Moved::Const(if k == 0 { x } else { 0 }))
|
||||
}
|
||||
// 64-bit inline integers are sign-extended.
|
||||
("s_mov_b64", Operand::Const(c @ 128..=208)) => {
|
||||
let low = inline(c)?;
|
||||
@@ -2763,6 +2821,76 @@ pub(crate) mod tests {
|
||||
assert_eq!(r.scalar, [((0, 2), at(0, 0)), ((0, 3), at(0, 0x10))]);
|
||||
}
|
||||
|
||||
/// The FidelityFX upscaler's byte accesses make a loaded buffer
|
||||
/// descriptor raw first (stride cleared, records times stride, bounds
|
||||
/// in bytes): the access reads the loaded descriptor. Any other change
|
||||
/// still fails.
|
||||
#[test]
|
||||
fn a_descriptor_made_raw_is_the_loaded_one() {
|
||||
let words = |mask: u32| -> Vec<u8> {
|
||||
[
|
||||
0xBE88_0304, // s_mov_b32 s8, s4
|
||||
0xBE89_0380, // s_mov_b32 s9, 0
|
||||
0xF408_0204,
|
||||
0xFA00_0160, // s_load_dwordx4 s[8:11], s[8:9], 0x160
|
||||
0xBF8C_C07F, // s_waitcnt lgkmcnt(0)
|
||||
0x938C_FF09,
|
||||
0x000E_0010, // s_bfe_u32 s12, s9, 0x000e0010
|
||||
0x848C_810C, // s_max_u32 s12, s12, 1
|
||||
0x8709_FF09,
|
||||
mask, // s_and_b32 s9, s9, mask
|
||||
0x870B_FF0B,
|
||||
0xCFFF_FFFF, // s_and_b32 s11, s11, 0xcfffffff
|
||||
0x930A_0C0A, // s_mul_i32 s10, s10, s12
|
||||
0x880B_FF0B,
|
||||
0x3000_0000, // s_or_b32 s11, s11, 0x30000000
|
||||
0xE078_1000,
|
||||
0x8002_0007, // buffer_store_dwordx4 v[0:3], v7, s[8:11], 0 offen
|
||||
S_ENDPGM,
|
||||
]
|
||||
.iter()
|
||||
.flat_map(|w: &u32| w.to_le_bytes())
|
||||
.collect()
|
||||
};
|
||||
let run = |mask| {
|
||||
let p = crate::ir::build(&words(mask), false, 256).unwrap();
|
||||
track(&p, &[param(Table, 4, 1)], HwStage::Cs, lanes(&p).as_ref())
|
||||
};
|
||||
assert!(run(0xC000_FFFF).is_ok());
|
||||
assert_eq!(
|
||||
run(0xC000_FFFE).unwrap_err(),
|
||||
ShaderError::Unsupported {
|
||||
offset: 0x3c,
|
||||
what: "a descriptor changed after loading"
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/// Immediate sampler words the upscaler's compiler makes with a bit
|
||||
/// mask and a 64-bit move of a literal.
|
||||
#[test]
|
||||
fn sampler_words_from_bit_masks_and_wide_literals_are_constants() {
|
||||
let code: Vec<u8> = [
|
||||
0xB010_3092, // s_movk_i32 s16, 0x3092
|
||||
0x9211_8C8C, // s_bfm_b32 s17, 12, 12
|
||||
0xBE92_04FF,
|
||||
0x1850_0000, // s_mov_b64 s[18:19], 0x18500000
|
||||
S_ENDPGM,
|
||||
]
|
||||
.iter()
|
||||
.flat_map(|w: &u32| w.to_le_bytes())
|
||||
.collect();
|
||||
let p = crate::ir::build(&code, false, 256).unwrap();
|
||||
let layout = [param(Table, 4, 1)];
|
||||
let t = Tracer::new(&p, &layout, HwStage::Cs, None).unwrap();
|
||||
let block = &p.blocks[0];
|
||||
let value = |n: usize, k: usize| t.origin(block.insts[n].writes[k].1);
|
||||
assert_eq!(value(1, 0), Term::Const(0x00FF_F000));
|
||||
assert_eq!(value(2, 0), Term::Const(0x1850_0000));
|
||||
assert_eq!(value(2, 1), Term::Const(0));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn a_selection_that_mixes_two_descriptors_fails() {
|
||||
// The high half picked from the first load whatever SCC is: when
|
||||
|
||||
Reference in new issue
Block a user