Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion crates/xcl/src/gpu/dxil/kernel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,14 @@ pub fn dispatch_piece_limit() -> usize {
std::env::var("XCL_DIRECT_SPLIT_INSTRUCTIONS").ok().and_then(|s| s.parse().ok()).unwrap_or(12_500)
}

/// `XCL_WINDOW_NO_CARRY=1`: memory accesses take their base's window (`lower_window::no_carry`).
pub fn window_no_carry() -> bool {
super::lower_window::no_carry()
}

#[cfg(test)]
pub use super::lower_window::with_no_carry;

/// `XCL_DIRECT_COMPACT`: `1` forces the compact form, `0` forbids it, unset uses automatic selection.
pub fn compact_mode() -> Option<bool> {
match std::env::var("XCL_DIRECT_COMPACT").as_deref() {
Expand Down Expand Up @@ -159,10 +167,12 @@ fn translate_entry(
// SSA construction recurses along the CFG (one level per guarded memory access between
// a register's definition and its use): a thread with a large stack for big programs
let code = code.to_vec();
// the caller's `no_carry` (a test may set it for its own thread)
let no_carry = super::lower_window::no_carry();
std::thread::Builder::new()
.name("xcl-dxil-translate".into())
.stack_size(256 << 20)
.spawn(move || translate_on_this_thread(&code, o, entry, compact, nest, tables))
.spawn(move || super::lower_window::with_no_carry(no_carry, || translate_on_this_thread(&code, o, entry, compact, nest, tables)))
.map_err(|e| format!("translator thread: {e}"))?
.join()
.map_err(|e| {
Expand Down
38 changes: 38 additions & 0 deletions crates/xcl/src/gpu/dxil/lower_window.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ impl Lw {
if !self.windowed() {
return;
}
// `XCL_WINDOW_NO_CARRY=1`: the window of the base address (`no_carry`). Heap windows only:
// their views are bounds-checked, so an access that leaves its allocation and wraps inside
// the base's window reads 0 past the window's end; a root UAV has no bounds and such an
// access could hang the GPU (a window test did on an RTX 3090, #2496)
if no_carry() && self.heap_mem.is_some() {
self.window_hi(hi, write);
return;
}
let non_zero = |t: &Ea| match *t {
Ea::K(0) => false,
Ea::U(v) | Ea::S(v) => self.s.m.const_u64(v) != Some(0),
Expand Down Expand Up @@ -206,3 +214,33 @@ impl Lw {
self.window_at(hi, lo, &[Ea::U(l4), off], write);
}
}

/// `XCL_WINDOW_NO_CARRY=1`: an access goes to the window of its base address. Allocations never
/// straddle windows (`gpu::uma`), so an access inside the allocation its base points into never
/// carries or borrows into the high dword, and the low dword is its offset in that window. Without
/// the 64-bit sum, accesses off the same base share their window, its range check and its heap
/// handle instead of computing them each, which makes the driver's code for big compute programs
/// smaller (on NVIDIA its shader code heap is limited, #2403). An access that leaves its base's
/// window (outside its allocation) stays in that window, wrapping its low dword. It applies with
/// heap windows only (`window_at`). A title reservation over 4 GiB still spans windows
/// (`Uma::sparse_reserve` logs it).
pub fn no_carry() -> bool {
if let Some(on) = NO_CARRY_TEST.with(|c| c.get()) {
return on;
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("XCL_WINDOW_NO_CARRY").is_ok_and(|v| v.trim() == "1"))
}

thread_local! {
/// `no_carry` for translations on this thread (`with_no_carry`; unset: `XCL_WINDOW_NO_CARRY`)
static NO_CARRY_TEST: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

/// `f` with `no_carry` set to `on` on this thread (the translator thread takes its caller's).
pub fn with_no_carry<R>(on: bool, f: impl FnOnce() -> R) -> R {
let old = NO_CARRY_TEST.with(|c| c.replace(Some(on)));
let r = f();
NO_CARRY_TEST.with(|c| c.set(old));
r
}
5 changes: 5 additions & 0 deletions crates/xcl/src/gpu/recomp/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,8 @@ mod translated {
Some(on) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), if on { "xcl-direct-compact-1" } else { "xcl-direct-compact-0" }),
_ => id,
};
// `XCL_WINDOW_NO_CARRY=1`: windows from the base address are another output
let id = if crate::gpu::dxil::kernel::window_no_carry() && Backend::current() != Backend::Hlsl { identity_for(&id.to_string(), "xcl-window-no-carry") } else { id };
// `XCL_DIRECT_COMPACT_NEST`: a non-default nesting policy changes the compact IR
let id = match crate::gpu::dxil::kernel::compact_nest_tag() {
Some(tag) if Backend::current() != Backend::Hlsl => identity_for(&id.to_string(), &tag),
Expand Down Expand Up @@ -512,6 +514,9 @@ mod translated {
None => id,
};
let id = identity_for(&id.to_string(), &format!("dispatch-split-{split_limit}"));
// `XCL_WINDOW_NO_CARRY=1`: windows from the base address are another output, also for
// the `enormous` programs that go direct without `XCL_DIRECT_DXIL`
let id = if crate::gpu::dxil::kernel::window_no_carry() { identity_for(&id.to_string(), "xcl-window-no-carry") } else { id };
if crate::gpu::recomp::lower_dxil::enabled() {
identity_for(&id.to_string(), concat!("xcl-per-lane-", env!("XCL_PER_LANE_SOURCE_ID")))
} else {
Expand Down
72 changes: 70 additions & 2 deletions crates/xcl/src/gpu/recomp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4153,6 +4153,72 @@ fn gpu_heap_windows_reject_out_of_uma_aliasing() {
memory_windows_reject_out_of_uma_aliasing(true);
}

/// `XCL_WINDOW_NO_CARRY` (direct DXIL): accesses inside an allocation read the same words when
/// the window comes from the base address as with the 64-bit sum (positive and negative offsets,
/// scalar and global loads), with the windows in root UAVs and in the descriptor heap; a 32-bit
/// (hi == 0) pointer still reads window 0 and a base outside the UMA still reads 0.
#[test]
fn gpu_window_no_carry_reads_inside_allocations_alike() {
if !gpu_ready() {
return;
}
let arena = crate::gpu::uma::Uma::with_windows(2, 1 << 20).unwrap();
let (w0, w1) = (arena.window(0).0 as u64, arena.window(1).0 as u64);
let base_hi = (w0 >> 32) as u32;
let word = |a: u64| unsafe { &mut *(a as *mut u32) };
*word(w1 + 0x0F0) = 0x1111_0F0F;
*word(w1 + 0x110) = 0x2222_1010;
*word(w1 + 0x120) = 0x3333_2020;
*word(w0 + 0x4000) = 0x4444_4000;
let glbl = |n: &'static str, f: &[(&'static str, u64)]| -> (&'static str, &'static str, Vec<(&'static str, u64)>, Option<u32>) { (n, "ENC_FLAT_GLBL", f.to_vec(), None) };
let list = vec![
// s[20:21] = w1 + 0x100: + v16 (0x10) -> w1 + 0x110 (v17)
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 17), ("ADDR", 16), ("SADDR", 20), ("OFFSET", 0)]),
// s[20:21] + v0 (0) + OFFSET -16 -> w1 + 0xF0 (v18)
glbl("GLOBAL_LOAD_DWORD", &[("VDST", 18), ("ADDR", 0), ("SADDR", 20), ("OFFSET", 0xFF0)]),
// s_load s[20:21] + 0x20 -> w1 + 0x120 (s30)
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 30), ("SBASE", 10), ("OFFSET", 0x20)], None),
// a 32-bit pointer (hi == 0) still reads window 0 (s31)
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 31), ("SBASE", 2), ("OFFSET", 0)], None),
// a base outside the UMA still reads 0 (s29)
("S_LOAD_DWORD", "ENC_SMEM", vec![("SDATA", 29), ("SBASE", 1), ("OFFSET", 0)], None),
];
let refs: Vec<(&str, &str, &[(&str, u64)], Option<u32>)> = list.iter().map(|(a, b, c, d)| (*a, *b, c.as_slice(), *d)).collect();
let p = prog(&refs);
let mut st = KernelState::default();
st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + 4]);
st.sgpr[4..6].copy_from_slice(&[0x4000, 0]);
st.sgpr[20..22].copy_from_slice(&[0x100, base_hi + 1]);
for r in st.vgpr.iter_mut() {
r[0] = 0;
r[16] = 0x10;
r[17] = 0x7777_7777;
r[18] = 0x7777_7777;
}
for heap in [false, true] {
let mem_windows = if heap { 2 | super::HEAP_WINDOWS } else { 2 };
let o = crate::gpu::dxil::kernel::KernelOptions { wave64: false, split: false, mem_windows, sampler_base: 0 };
let mut sizes = Vec::new();
for no_carry in [false, true] {
let dxil = crate::gpu::dxil::kernel::with_no_carry(no_carry, || crate::gpu::dxil::kernel::translate(&p, o)).unwrap_or_else(|e| panic!("direct DXIL: {e}"));
sizes.push(dxil.len());
let r = runner::run_in_arena(&dxil, &st, &arena).unwrap();
let what = format!("heap windows {heap}, no carry {no_carry}");
assert_eq!(r.vgpr[0][17], 0x2222_1010, "{what}: base + v16");
assert_eq!(r.vgpr[0][18], 0x1111_0F0F, "{what}: base - 16");
assert_eq!(r.sgpr[30], 0x3333_2020, "{what}: s_load base + 0x20");
assert_eq!(r.sgpr[31], 0x4444_4000, "{what}: hi == 0 reads window 0");
assert_eq!(r.sgpr[29], 0, "{what}: a base outside the UMA reads 0");
}
// root-UAV windows have no bounds: the switch leaves them as they are
if heap {
assert!(sizes[1] < sizes[0], "heap windows: no carry makes less DXIL ({sizes:?})");
} else {
assert_eq!(sizes[1], sizes[0], "root-UAV windows: no carry changes nothing ({sizes:?})");
}
}
}

fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
if !gpu_ready() {
return;
Expand Down Expand Up @@ -4210,7 +4276,8 @@ fn memory_windows_reject_out_of_uma_aliasing(heap: bool) {
let t = translate(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() })).unwrap();
assert_eq!(t.hlsl.contains("switch (xcl_w)"), !heap);
let hlsl_dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil);
// the 64-bit sum on purpose (crossings into another window): `XCL_WINDOW_NO_CARRY` off here
let dxil = crate::gpu::dxil::kernel::with_no_carry(false, || direct_or(&p, &on_gpu(Options { mem_windows: 2, heap_windows: heap, ..Default::default() }), hlsl_dxil));

let mut st = KernelState::default();
st.sgpr[2..4].copy_from_slice(&[0x1000, base_hi + 4]); // s[2:3]: out-of-UMA hi = base_hi + 4
Expand Down Expand Up @@ -4305,7 +4372,8 @@ fn gpu_window_at_32bit_carry_edge_cases() {
let p = prog(&refs);
let t = translate(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() })).unwrap();
let hlsl_dxil = super::dxc::compile(&t.hlsl, "main", "cs_6_6", &[]).map_err(|e| format!("{e}\n{}", t.hlsl)).unwrap();
let dxil = direct_or(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() }), hlsl_dxil);
// the 64-bit sum on purpose (carries and borrows across windows): `XCL_WINDOW_NO_CARRY` off here
let dxil = crate::gpu::dxil::kernel::with_no_carry(false, || direct_or(&p, &on_gpu(Options { mem_windows: 2, ..Default::default() }), hlsl_dxil));

let mut st = KernelState::default();
st.sgpr[2..4].copy_from_slice(&[0xFFFF_FFFC, base_hi]); // s[2:3] = w0 + 0xFFFF_FFFC
Expand Down
76 changes: 74 additions & 2 deletions crates/xcl/src/gpu/uma.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,18 +387,46 @@ impl Uma {
/// Address space for a title reservation of `size` bytes in the sparse windows (64 KiB
/// aligned, first fit; not committed). Prefers windows 1+ so window 0 stays uncluttered for
/// small allocations, falling back to all of the title's sparse space (never `desc_range`).
/// With `XCL_WINDOW_NO_CARRY=1` a reservation of 4 GiB or less stays inside one window where
/// one has room: shaders then take an access's window from its base address, so a buffer the
/// title places in a reservation should not cross into the next window. Where no window has
/// room it is placed as without the switch (across a boundary, logged) rather than not at
/// all: a reservation the sparse windows refuse goes to plain memory (`kernelx`), which the
/// switch must not make happen more often than without it.
pub fn sparse_reserve(&self, size: usize) -> Option<usize> {
if !self.has_sparse() {
return None;
}
let size = (size.max(1) + GRAIN - 1) & !(GRAIN - 1);
let one_window = crate::gpu::dxil::kernel::window_no_carry();
if one_window && size > WINDOW {
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 {
crate::xlog_warn!(
"memory: a title reservation of {} MB is larger than a 4 GiB window: with XCL_WINDOW_NO_CARRY a shader access from a base in it that crosses a window boundary stays in the base's window",
size >> 20
);
}
}
let mut g = self.sparse_free.lock().unwrap();
let end = self.base + self.kinds.len() * WINDOW;
let lo = self.title_sparse_start();
if let Some(at) = take_sparse_in(&mut g, (self.base + WINDOW).max(lo), end, size, GRAIN, false) {
let mut take = |single: bool| {
take_sparse_in(&mut g, (self.base + WINDOW).max(lo), end, size, GRAIN, single).or_else(|| take_sparse_in(&mut g, lo, end, size, GRAIN, single))
};
if one_window && size <= WINDOW {
if let Some(at) = take(true) {
return Some(at);
}
// no window has room for it in one piece: across a boundary, as without the switch
let at = take(false)?;
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
if N.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 {
crate::xlog_warn!("memory: a title reservation of {} MB crosses a window boundary (no window has room for it): with XCL_WINDOW_NO_CARRY a shader access across that boundary stays in its base's window", size >> 20);
}
return Some(at);
}
take_sparse_in(&mut g, lo, end, size, GRAIN, false)
take(false)
}

/// Reserve an aligned range strictly inside sparse window `k` (window 0: 32-bit descriptor
Expand Down Expand Up @@ -1051,6 +1079,50 @@ mod tests {
assert_eq!(take_sparse_in(&mut cross, lo, hi, 2 * GRAIN, GRAIN, false), Some(lo));
}

/// `XCL_WINDOW_NO_CARRY`: where the only room left for a reservation crosses a window
/// boundary, it is still placed there (as without the switch) instead of being refused, which
/// would send it to plain memory.
#[test]
fn a_reservation_crosses_a_boundary_when_no_window_has_room() {
let u = Uma::for_runtime(16 << 20).unwrap();
let gap = 6 * GRAIN;
// without the switch (whatever the environment): a gap of `gap` across the boundary after
// `first`, everything else full
let crossing = crate::gpu::dxil::kernel::with_no_carry(false, || {
let first = u.sparse_reserve(WINDOW - 3 * GRAIN).unwrap();
let crossing = u.sparse_reserve(gap).unwrap();
assert_ne!(crossing / WINDOW, (crossing + gap - 1) / WINDOW, "the second one crosses: {first:#x}, {crossing:#x}");
// fill all the rest, then free the crossing one: it is the only room left
for chunk in [256 * GRAIN, 16 * GRAIN, GRAIN] {
while u.sparse_reserve(chunk).is_some() {}
}
assert!(u.sparse_release(crossing).is_some());
assert!(u.sparse_reserve(gap + GRAIN).is_none(), "only the crossing gap is left");
crossing
});
// with the switch: no window has `gap` in one piece, so it goes across, not nowhere
let again = crate::gpu::dxil::kernel::with_no_carry(true, || u.sparse_reserve(gap));
assert_eq!(again, Some(crossing));
}

/// `XCL_WINDOW_NO_CARRY`: a title reservation that would cross a window boundary starts at
/// the next window instead (without it, first fit crosses as before).
#[test]
fn title_reservations_stay_in_one_window_without_the_carry() {
for no_carry in [false, true] {
let u = Uma::for_runtime(16 << 20).unwrap();
let (first, second) = crate::gpu::dxil::kernel::with_no_carry(no_carry, || {
let first = u.sparse_reserve(WINDOW - 3 * GRAIN).unwrap();
// what is left of `first`'s window is too small for the next one
let left = (first / WINDOW + 1) * WINDOW - (first + WINDOW - 3 * GRAIN);
assert!(left < 6 * GRAIN, "{left:#x}");
(first, u.sparse_reserve(6 * GRAIN).unwrap())
});
let crosses = second / WINDOW != (second + 6 * GRAIN - 1) / WINDOW;
assert_eq!(crosses, !no_carry, "no carry {no_carry}: first {first:#x}, second {second:#x}");
}
}

#[test]
fn runtime_layout_places_sparse_in_0_to_2_and_committed_in_3() {
let u = Uma::for_runtime(16 << 20).unwrap();
Expand Down
Loading