cuda-driver: model-free stress of DMA out of a registered read-only file mapping under working-set trimming (STRA-235 hypothesis, Windows)

mapped_file_dma_under_working_set_trimming_is_exact maps a 2 GiB file read-only, page-locks the first GiB in place with
cuMemHostRegister(READ_ONLY) (what pin_resident does), copies random pieces out of the registered and the pageable halves to the device
while K32EmptyWorkingSet runs every 5 ms (the governor's relieve_working_set) and another thread churns the pages, and checks every byte
against the file's content function. 20 s on the laptop: 18,825 copies, 1,764 trims, 0 mismatches. #[ignore]d GPU test, no model.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-27 04:16:37 +01:00
co-authored by Claude Sonnet 5.5
parent d54f10161c
commit 2a7e80a390
2 changed files with 167 additions and 0 deletions
+4
View File
@@ -219,6 +219,10 @@ pub mod kar_decode_levels_gpu;
))]
#[path = "kar_decode_levels_gpu_smoke.rs"]
mod kar_decode_levels_gpu_smoke;
// Model-free stress of DMA out of a read-only file mapping that is page-locked in place, under working-set trimming (Windows only).
#[cfg(all(test, windows, feature = "cuda-driver", target_pointer_width = "64"))]
#[path = "mapped_file_dma_stress_gpu.rs"]
mod mapped_file_dma_stress_gpu;
/// Errors retain CUDA operation names/codes and any subsequent cleanup errors.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -0,0 +1,163 @@
//! Model-free stress of the host side of the expert copies on Windows (STRA-235 hypothesis): DMA out of a read-only FILE MAPPING whose
//! pages are page-locked in place by `cuMemHostRegister(READ_ONLY)` (what `MappedExpertBank::pin_resident` does with the hottest
//! experts of the mapped bank) and out of the same mapping left pageable, while the process working set is emptied over and over
//! (what the memory governor's `relieve_working_set` does on the workstation preset) and another thread churns the mapping's pages.
//!
//! Every copy is checked byte for byte against the file's content function (the expected bytes never come from the mapping), so a
//! page that was reclaimed under a registration, a stale physical page, or a trim that races a staged copy shows up as a mismatch
//! with its file offset. It is a check of the driver's and the OS's behaviour, not of Leleka code; it costs no model.
//!
//! Run (needs ~2.2 GiB of free disk in the temp directory and ~1 GiB of RAM; the file is removed at the end):
//! cargo test --release -p leleka-cuda-driver --features cuda-driver,sm86 --lib -- --ignored --nocapture mapped_file_dma
//! Knobs: `MFD_SECONDS` (default 60), `MFD_REGISTER_MIB` (default 1024), `MFD_TRIM=off` (no working-set trimming), `MFD_CHURN=off`.
#![allow(unsafe_code)]
use crate::{Driver, OriginalStreamKind, api::MappedApi};
use std::io::Write;
use std::os::windows::io::AsRawHandle;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
const FILE_BYTES: usize = 2 << 30;
const PIECE_MAX: usize = 640 << 10;
#[link(name = "kernel32")]
unsafe extern "system" {
fn K32EmptyWorkingSet(process: *mut std::ffi::c_void) -> i32;
fn GetCurrentProcess() -> *mut std::ffi::c_void;
}
/// The byte at `offset` of the test file: eight-byte words of a counter hash.
fn word(offset: usize) -> u64 {
let mut x = (offset as u64 / 8).wrapping_add(0x9E37_79B9_7F4A_7C15);
x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
x ^ (x >> 31)
}
fn expected(offset: usize, len: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(len + 16);
let mut at = offset & !7;
while out.len() < offset - (offset & !7) + len {
out.extend_from_slice(&word(at).to_le_bytes());
at += 8;
}
out[offset & 7..(offset & 7) + len].to_vec()
}
fn env_u64(name: &str, default: u64) -> u64 {
std::env::var(name).ok().and_then(|v| v.parse().ok()).unwrap_or(default)
}
struct Rng(u64);
impl Rng {
fn next(&mut self) -> u64 {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
self.0
}
}
#[test]
#[ignore = "needs a CUDA device, 2 GiB of temp disk and about a minute"]
fn mapped_file_dma_under_working_set_trimming_is_exact() {
let path = std::env::temp_dir().join(format!("leleka-mapped-dma-{}.bin", std::process::id()));
{
let mut file = std::io::BufWriter::with_capacity(8 << 20, std::fs::File::create(&path).unwrap());
for chunk in (0..FILE_BYTES).step_by(8) {
file.write_all(&word(chunk).to_le_bytes()).unwrap();
}
file.flush().unwrap();
}
let file = std::fs::File::open(&path).unwrap();
// SAFETY: a live read handle; the view is unmapped before the file is removed, after the registration was released.
let base = unsafe { libc::map_file_readonly(file.as_raw_handle().cast(), 0, 0) };
assert!(!base.is_null(), "mapping failed: {}", std::io::Error::last_os_error());
let base_address = base as usize;
let registered = (env_u64("MFD_REGISTER_MIB", 1024) as usize) << 20;
assert!(registered > 0 && registered < FILE_BYTES);
let driver = Driver::load().unwrap();
let ctx = driver.device(0).unwrap().create_context(64 << 20).unwrap();
let destination = ctx.allocate(PIECE_MAX).unwrap();
let device = destination.handle.expect("live buffer").qwen_address();
let mut stream = ctx.original_gpu_stream(OriginalStreamKind::NonBlocking).unwrap();
let api = {
let guard = ctx.enter().unwrap();
let api = MappedApi::load().unwrap();
api.register_read_only(base_address, registered).unwrap_or_else(|e| panic!("READ_ONLY registration of {registered} bytes failed: {e:?}"));
guard.finish().unwrap();
api
};
let stop = AtomicBool::new(false);
let trims = AtomicU64::new(0);
let mut seen_bad = 0u64;
let mut copies = [0u64; 2];
let seconds = env_u64("MFD_SECONDS", 60);
std::thread::scope(|scope| {
if std::env::var("MFD_TRIM").as_deref() != Ok("off") {
scope.spawn(|| {
while !stop.load(Ordering::Relaxed) {
// SAFETY: the pseudo handle of the current process, which has PROCESS_SET_QUOTA for itself.
unsafe { K32EmptyWorkingSet(GetCurrentProcess()) };
trims.fetch_add(1, Ordering::Relaxed);
std::thread::sleep(Duration::from_millis(5));
}
});
}
if std::env::var("MFD_CHURN").as_deref() != Ok("off") {
// read the unregistered half of the mapping in a loop: pages come in, get trimmed, come in again
scope.spawn(|| {
let mut rng = Rng(0x1234_5678_9ABC_DEF1);
let mut sink = 0u64;
while !stop.load(Ordering::Relaxed) {
let at = registered + (rng.next() as usize % (FILE_BYTES - registered - 4096));
// SAFETY: inside the live mapping.
sink = sink.wrapping_add(u64::from(unsafe { *(base_address as *const u8).add(at) }));
}
std::hint::black_box(sink);
});
}
let started = Instant::now();
let mut rng = Rng(0x0DDB_1A5E_5BAD_5EED);
while started.elapsed() < Duration::from_secs(seconds) && seen_bad < 5 {
// a piece inside the registered range, or entirely in the pageable rest: alternate
let locked = copies[0] <= copies[1];
let len = 16 * (1 + rng.next() as usize % (PIECE_MAX / 16));
let (lo, hi) = if locked { (0, registered) } else { (registered, FILE_BYTES) };
let at = lo + 16 * (rng.next() as usize % ((hi - lo - len) / 16));
// SAFETY: inside the live mapping, which stays mapped (and the first `registered` bytes registered) until after the loop.
let source = unsafe { std::slice::from_raw_parts((base_address + at) as *const u8, len) };
stream.enqueue_copy_h2d(device, source).unwrap_or_else(|e| panic!("copy failed at file offset {at} ({len} bytes, locked={locked}): {e:?}"));
stream.synchronize().unwrap_or_else(|e| panic!("stream failed after a copy of file offset {at} ({len} bytes, locked={locked}): {e:?}"));
let mut back = vec![0u8; PIECE_MAX];
destination.copy_to(&mut back).unwrap();
let want = expected(at, len);
if let Some(i) = (0..len).find(|&i| back[i] != want[i]) {
seen_bad += 1;
println!("MISMATCH locked={locked} file offset {at} + {i} (page {}): got {:#04x}, want {:#04x}, piece {len} bytes", (at + i) / 4096, back[i], want[i]);
}
copies[usize::from(!locked)] += 1;
}
stop.store(true, Ordering::Relaxed);
});
println!(
"mapped file DMA: {} copies from registered pages, {} from pageable pages, {} working-set trims, {seen_bad} mismatching pieces",
copies[0],
copies[1],
trims.load(Ordering::Relaxed)
);
{
let guard = ctx.enter().unwrap();
api.unregister_at(base_address).unwrap();
guard.finish().unwrap();
}
drop(stream);
drop(destination);
ctx.close().unwrap();
// SAFETY: the exact base returned by `map_file_readonly`, no reference into it is alive.
unsafe { libc::unmap_file(base) };
drop(file);
std::fs::remove_file(&path).unwrap();
assert_eq!(seen_bad, 0, "DMA out of the mapping returned wrong bytes");
}