Skip to content
Merged
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
44 changes: 27 additions & 17 deletions d3d12/crates/leonida-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3864,12 +3864,13 @@ impl HostHeap {
pub(crate) fn make_at(&self, index: u32, view: &View) {
let kept = make_twinned_info(view, self.at(index), self.twin(index)).0;
let bias = take_twin_bias();
if kept.is_none() {
let is_made = kept.is_some();
self.write_stride(index, if is_made { with_twin_bias(view_stride_word(view), bias) } else { 0 });
if !is_made {
null_for(view, self.at(index));
}
self.put(index);
self.twin_made(index, kept.is_some() && twinned(view));
self.write_stride(index, if kept.is_some() { with_twin_bias(view_stride_word(view), bias) } else { 0 });
self.twin_made(index, is_made && twinned(view));
self.keep(index, kept.flatten());
}

Expand Down Expand Up @@ -3909,18 +3910,21 @@ impl HostHeap {
flush_listed();
let (s0, s1) = (views.slot(at), views.slot(at + 1));
let (kept, cast_serial) = make_twinned_info(&view, s0, Some(s1));
let bias = take_twin_bias();
let Some(kept) = kept else {
null_for(&view, s0);
if let Some(existing) = views.made.get_mut(&words) {
existing.kept = None;
existing.twin = false;
existing.stride_word = 0;
existing.listed.ready = (0, 0, false);
}
views.cast_serials.insert(words, u64::MAX);
return None;
};
if let Some(existing) = views.made.get_mut(&words) {
existing.kept = kept;
existing.stride_word = with_twin_bias(view_stride_word(&view), bias);
existing.listed.ready = (0, 0, false);
match cast_serial {
Some(cs) => {
Expand Down Expand Up @@ -3959,9 +3963,9 @@ impl HostHeap {
let made = &views.made[&words];
self.copy_listed(index, views.slot(made.at));
if made.twin && twins {
self.write_stride(index, made.stride_word);
self.copy_listed(self.raw + index, views.slot(made.at + 1));
self.twins[index as usize].store(true, std::sync::atomic::Ordering::Relaxed);
self.write_stride(index, made.stride_word);
} else {
self.clear_twin(index);
self.write_stride(index, with_twin_bias(made.stride_word, 0));
Expand Down Expand Up @@ -4357,6 +4361,12 @@ impl HostHeap {
self.put(index);
host.device.CreateShaderResourceView(buffer, Some(&raw), twin);
}
let mark = if leonida_shader::emit::constant_marks() {
leonida_shader::emit::SLOT_STRIDE_CONSTANT
} else {
0
};
self.write_stride(index, mark);
self.twin_made(index, true);
self.keep_ref(index, Some(buffer));
true
Expand Down Expand Up @@ -4672,18 +4682,18 @@ impl HostHeap {
make_twinned_info(&view, self.at(index), self.twin(index))
};
let bias = take_twin_bias();
if kept.is_none() && !self.sampler {
null_for(&view, self.at(index));
}
if kept.is_some() || !self.sampler {
self.put(index);
}
self.twin_made(index, kept.is_some() && twinned(&view));
let is_made = kept.is_some();
if is_made && bias != 0 {
// (`note_buffer` wrote the word without it.)
// (`note_buffer` wrote the word without it: write before publishing `put`/`twin_made`.)
self.write_stride(index, with_twin_bias(view_stride_word(&view), bias));
}
if !is_made && !self.sampler {
null_for(&view, self.at(index));
}
if is_made || !self.sampler {
self.put(index);
}
self.twin_made(index, is_made && twinned(&view));
self.keep(index, kept.flatten());
self.note_cast_serial(index, cast_serial.filter(|&cs| is_made || cs != 0));
self.quick_is(index, if later || cast_serial.is_some() { 0 } else { key });
Expand Down Expand Up @@ -5219,14 +5229,14 @@ fn with_twin_bias(word: u32, bias: u32) -> u32 {

/// For a raw twin at `twin` showing from `start` (GPU address) `bytes`,
/// `by` bytes before its view ([`twin_window`]): moved to the view
/// ([`move_raw`]) where it can be, else kept with a bias ([`twin_bias`]),
/// else made null.
/// ([`move_raw`]) where it can be, else kept with a dword-aligned bias
/// ([`twin_bias`]), else made null.
fn settle_twin(twin: D3D12_CPU_DESCRIPTOR_HANDLE, start: u64, bytes: u32, by: u32) {
use std::sync::atomic::Ordering::Relaxed;
if by == 0 || (staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) && move_raw(twin, start, bytes, by)) {
return;
}
if twin_bias() && by < 16 && by < bytes {
if twin_bias() && by < 16 && by.is_multiple_of(4) && by < bytes {
TWINS[3].fetch_add(1, Relaxed);
TWIN_BIAS.with(|b| b.set(by));
} else {
Expand Down Expand Up @@ -5287,11 +5297,11 @@ fn twin_window(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw: bo
if end <= start {
return None;
}
let dwords = u32::try_from((end - from) / 4).ok()?;
let bytes = u32::try_from(end - from).ok()?;
if from != start {
TWINS[1].fetch_add(1, Relaxed);
}
Some((from / 4, dwords, (start - from) as u32))
Some((from / 4, bytes / 4, (start - from) as u32))
}

fn buffer_srv(
Expand Down
172 changes: 172 additions & 0 deletions d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -282,3 +282,175 @@ fn dump_buffer_view_descriptor_bytes() {
);
}
}

/// Sub-dword unaligned typed buffer views (`by % 4 != 0`, such as `R16_UINT` at an odd element or
/// `R8_UINT` off 4 bytes) must not keep a misaligned raw twin or record an unaligned bias in
/// `strides[slot]`; dword-aligned views (`by` in `[4, 8, 12]`) keep their biased twins; and
/// `constant_raw_at` clears any prior bias when recycling a dynamic slot.
#[test]
fn sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias() {
if !twin_bias() {
return;
}
const SIZE: u64 = 4096;
let Some(host) = host() else { return };
let mut heap = HostHeap::new(false, 4).expect("a host view heap");
if heap.raw == 0 {
// Portable hosts (1,000,000-descriptor cap) still have room inside this test's small heap
// to exercise the exact twin-slot and stride-word machinery.
heap.raw = 64;
heap.twins = (0..32)
.map(|_| std::sync::atomic::AtomicBool::new(false))
.collect();
}
let first = heap.dynamic(8).expect("dynamic descriptor slots");
assert!((first + 8) <= heap.twins.len() as u32);

let title = Box::new([0u32; SIZE as usize / 4]);
let address = title.as_ptr() as u64;
struct Registration(u64);
impl Drop for Registration {
fn drop(&mut self) {
crate::shadow::unregister(self.0 as usize, self.0);
}
}
crate::shadow::register(address as usize, address, SIZE);
let _registered = Registration(address);
let source = crate::shadow::find(address, SIZE).expect("the registered buffer's host copy");
let (target, result) = host.shared_buffer(SIZE).expect("a mapped write target");
let values: [u32; 16] = std::array::from_fn(|i| 0x4567_8000 + i as u32);
// SAFETY: live mapped buffer of SIZE bytes.
unsafe {
let mut data = std::ptr::null_mut();
source.buffer.Map(0, None, Some(&mut data)).expect("map source");
data.cast::<[u32; 16]>().write(values);
source.buffer.Unmap(0, None);
}

let word = |h: &HostHeap, slot: u32| {
let (_, _, data) = h.strides.as_ref().expect("stride table mapping");
// SAFETY: slot is within `SLOT_STRIDES_COUNT`.
unsafe { (*data as *const u32).add(slot as usize).read_volatile() }
};

let code = crate::host::compile(TRANSFER, s!("main"), s!("cs_5_1")).expect("transfer shader");
// SAFETY: shader blob contains matching root signature.
let (root, pipeline): (ID3D12RootSignature, ID3D12PipelineState) = unsafe {
let root = host.device.CreateRootSignature(0, &code).expect("root signature");
let pipeline = host
.device
.CreateComputePipelineState(&D3D12_COMPUTE_PIPELINE_STATE_DESC {
pRootSignature: std::mem::transmute_copy(&root),
CS: D3D12_SHADER_BYTECODE {
pShaderBytecode: code.as_ptr().cast(),
BytecodeLength: code.len(),
},
..Default::default()
})
.expect("compute pipeline");
(root, pipeline)
};
let strides_gpu = heap.strides_gpu().expect("strides GPU address");
let cpu = ListViews::new().expect("CPU descriptor staging");
let uav_desc = D3D12_UNORDERED_ACCESS_VIEW_DESC {
Format: DXGI_FORMAT_R32_TYPELESS,
ViewDimension: D3D12_UAV_DIMENSION_BUFFER,
Anonymous: D3D12_UNORDERED_ACCESS_VIEW_DESC_0 {
Buffer: D3D12_BUFFER_UAV {
FirstElement: 0,
NumElements: 16,
Flags: D3D12_BUFFER_UAV_FLAG_RAW,
..Default::default()
},
},
};
// SAFETY: private CPU slot and live target buffer.
unsafe {
host.device.CreateUnorderedAccessView(&target, None::<&ID3D12Resource>, Some(&uav_desc), cpu.slot(0));
}
let out_uav_slot = first + 7;
heap.copy_from(out_uav_slot, cpu.slot(0));

let read_twin = |h: &HostHeap, slot: u32| -> [u32; 2] {
let list = host.new_list().expect("command list");
// SAFETY: live heap, pipeline, and mapped result buffer.
unsafe {
result.cast::<[u32; 4]>().write([0xfeed_face; 4]);
list.list.SetDescriptorHeaps(&[Some(h.heap.clone())]);
list.list.SetComputeRootSignature(&root);
list.list.SetPipelineState(&pipeline);
list.list.SetComputeRootDescriptorTable(0, h.gpu_handle(h.raw + slot));
list.list.SetComputeRootDescriptorTable(1, h.gpu_handle(out_uav_slot));
let constants = [0u32, 0u32, slot];
list.list.SetComputeRoot32BitConstants(2, 3, constants.as_ptr().cast(), 0);
list.list.SetComputeRootShaderResourceView(3, strides_gpu);
list.list.Dispatch(1, 1, 1);
list.close();
host.execute(&[&list]);
result.cast::<[u32; 2]>().read_volatile()
}
};

let resource = [1, 0, 0, 0, SIZE as u32, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
let mut recording = 1000u64;
let make_via_listed = |recording: &mut u64, view: View| {
let mut rec = [0u32; 8];
crate::descriptor::record(rec.as_mut_ptr() as u64, view);
*recording += 1;
assert!(heap.make_listed(*recording, [rec[0], rec[1], rec[2]], first).is_some());
flush_listed();
};
// 1. Sub-dword unaligned R16_UINT (format 57, 2 bytes) at odd FirstElement (9 -> byte 18, by = 2;
// 11 -> byte 22, by = 6; 13 -> byte 26, by = 10; 15 -> byte 30, by = 14) and R8_UINT (format 62,
// 1 byte) at FirstElement 17 (by = 1) and 19 (by = 3), both SRV and UAV.
for (format, elem_idx, by) in [(57u32, 9u32, 2u32), (57, 11, 6), (57, 13, 10), (57, 15, 14), (62, 17, 1), (62, 19, 3)] {
for unordered in [false, true] {
let mut desc = [0u32; 16];
if unordered {
desc[..10].copy_from_slice(&[format, 1, elem_idx, 0, 8, 0, 0, 0, 0, 0]);
} else {
desc[..10].copy_from_slice(&[format, 1, 5768, 0, elem_idx, 0, 8, 0, 0, 0]);
}
(desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
make_via_listed(&mut recording, View::Placed(unordered, resource, desc));
let bias_bits = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK)
>> leonida_shader::emit::VIEW_BIAS_SHIFT;
assert_eq!(
bias_bits, 0,
"non-dword-aligned view (format {format}, by={by}, uav={unordered}) must not record an unaligned bias"
);
if !unordered {
assert_eq!(
read_twin(&heap, first),
[0, 0],
"non-dword-aligned SRV twin (by={by}) must be null, not reading misaligned pre-view bytes"
);
}
}
}

// 2. Dword-aligned unaligned R32_UINT (format 42, 4 bytes) at FirstElement = 6 (byte 24, by = 8)
// keeps its biased twin and reads [values[6], values[7]], then `constant_raw_at` on the same
// slot clears the bias bits to 0.
let mut aligned8 = [0u32; 16];
aligned8[..10].copy_from_slice(&[42, 1, 5768, 0, 6, 0, 2, 0, 0, 0]);
(aligned8[10], aligned8[11]) = (address as u32, (address >> 32) as u32);
make_via_listed(&mut recording, View::Placed(false, resource, aligned8));
let bias_bits = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK)
>> leonida_shader::emit::VIEW_BIAS_SHIFT;
assert_eq!(bias_bits, 8, "8-byte-offset R32_UINT view must record bias=8");
assert_eq!(read_twin(&heap, first), [values[6], values[7]]);

// Recycle `first` with `constant_raw_at` on a 256-byte-aligned address inside `source.buffer`.
let gpu_base = source.gpu(address);
assert!(
heap.constant_raw_at(first, &source.buffer, gpu_base + 256, 256),
"constant_raw_at should succeed on 16-byte-aligned GPU address"
);
let recycled_bias = (word(&heap, first) & leonida_shader::emit::VIEW_BIAS_MASK)
>> leonida_shader::emit::VIEW_BIAS_SHIFT;
assert_eq!(
recycled_bias, 0,
"constant_raw_at must clear stale twin bias when recycling a dynamic slot"
);
}
21 changes: 18 additions & 3 deletions d3d12/crates/leonida-shader/src/emit/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9659,11 +9659,23 @@ impl<'a> Lower<'a> {
h
}

/// `offset` plus `bias` in `block`, keeping 32-bit sentinel and negative
/// offsets (`u32::MAX * stride + field`, `x - 4` at `x = 0`) out of bounds
/// instead of wrapping modulo 2^32 into `[0, 16)`, the bytes before the
/// view (including across a 4-dword vector load or store).
fn add_bias(&mut self, block: usize, offset: V, bias: V) -> V {
let sum = self.s.m.bin(block, Bin::Add, offset, bias);
let ceiling = self.s.m.i32(0xFFFF_FFD0);
let oob = self.s.m.i32(0xFFFF_FFE0);
let wraps = self.s.m.cmp(block, pred::IUGT, offset, ceiling);
self.s.m.select(block, wraps, oob, sum)
}

/// `offset` plus the bias of the raw twin `h` is, if it is one
/// ([`Lower::twin_handle`]), in the current block.
fn biased(&mut self, h: V, offset: V) -> V {
match self.twin_bias.get(&h) {
Some(&bias) => self.s.m.bin(self.cur, Bin::Add, offset, bias),
match self.twin_bias.get(&h).copied() {
Some(bias) => self.add_bias(self.cur, offset, bias),
None => offset,
}
}
Expand All @@ -9685,7 +9697,7 @@ impl<'a> Lower<'a> {
match (args.first().and_then(|h| self.twin_bias.get(h)).copied(), args.get(at)) {
(Some(bias), Some(&offset)) => {
let mut moved = args.to_vec();
moved[at] = self.s.m.bin(block, Bin::Add, offset, bias);
moved[at] = self.add_bias(block, offset, bias);
self.s.op(block, name, attr, ret, opcode, &moved)
}
_ => self.s.op(block, name, attr, ret, opcode, args),
Expand Down Expand Up @@ -14206,7 +14218,10 @@ impl<'a> Lower<'a> {
let aligned = self.s.m.bin(c, Bin::Sub, byte, within);
let shift = self.s.m.bin(c, Bin::Shl, within, k3);
let four = self.s.m.i32(4);
let at_end = self.s.m.i32(0xFFFF_FFFC);
let wraps = self.s.m.cmp(c, pred::EQ, aligned, at_end);
let next = self.s.m.bin(c, Bin::Add, aligned, four);
let next = self.s.m.select(c, wraps, at_end, next);
let ones = self.s.m.i32(if bits == 8 { 0xff } else { 0xffff });
let zero = self.s.m.i32(0);
let k8 = self.s.m.i32(8);
Expand Down
Loading