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
7 changes: 4 additions & 3 deletions d3d12/crates/leonida-gpu/src/descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -651,14 +651,15 @@ static SYNC_SPLIT: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomi
/// Nothing while no heap page changed.
#[cfg(windows)]
pub(crate) fn sync_line(frames: f64) {
let [twins, moved, lost, biased] = [0, 1, 2, 3].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed));
let [twins, moved, lost, biased, listed] = [0, 1, 2, 3, 4].map(|i| host::TWINS[i].swap(0, std::sync::atomic::Ordering::Relaxed));
if twins > 0 {
tracing::info!(
"raw twins of buffer views made per frame (LEONIDA_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null, {:.1} kept from 16 bytes before with a bias; LEONIDA_TWIN_BIAS=0: null)",
"raw twins of buffer views made per frame (LEONIDA_RAW_VIEWS=0: none): {:.0}, of them {:.1} that do not begin on 16 bytes ({:.1} null, {:.1} kept from 16 bytes before with a bias; LEONIDA_TWIN_BIAS=0: null; {:.1} of those a list keeps moved to their view with LEONIDA_LIST_TWIN_MOVE=1)",
twins as f64 / frames,
moved as f64 / frames,
lost as f64 / frames,
biased as f64 / frames
biased as f64 / frames,
listed as f64 / frames
);
}
let [pages, looked, mirrored, micros, tabled, later, waited] = [0, 1, 2, 3, 4, 5, 6].map(|i| SYNCED[i].swap(0, std::sync::atomic::Ordering::Relaxed));
Expand Down
70 changes: 66 additions & 4 deletions d3d12/crates/leonida-gpu/src/descriptor/host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4071,7 +4071,10 @@ impl HostHeap {
LIST_VIEWS.with(|views| {
let mut views = views.borrow_mut();
if views.is_none() {
*views = Some(ListViews::new()?);
let made = ListViews::new()?;
// (Its slots are this thread's own, as the one beside the heaps: `own_slot`.)
LIST_SLOTS.set((made.start, made.start + ListViews::SLOTS as usize * made.step));
*views = Some(made);
}
let views = views.as_mut()?;
if views.recording != recording {
Expand Down Expand Up @@ -5375,8 +5378,9 @@ fn buffer_view_ok(format: DXGI_FORMAT, first: u64, count: u32, stride: u32, raw:
/// Raw twins ([`raw_twins`]) made since the last frame line, and those of them that
/// do not begin on 16 bytes, as a raw view must ([`move_raw`]), and those of
/// these that could not be moved there (null), and those of these kept from
/// the 16 bytes before them with a bias instead ([`twin_bias`]).
pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
/// the 16 bytes before them with a bias instead ([`twin_bias`]), and those
/// moved in a slot a list keeps its views in ([`list_twin_move`]).
pub(crate) static TWINS: [std::sync::atomic::AtomicU64; 5] = [const { std::sync::atomic::AtomicU64::new(0) }; 5];

/// Whether the raw twin of a buffer view that does not begin on 16 bytes is
/// kept, made from the multiple of 16 before the view, with the bytes it
Expand Down Expand Up @@ -5412,13 +5416,71 @@ fn with_twin_bias(word: u32, bias: u32) -> u32 {
(word & !VIEW_BIAS_MASK) | ((bias << VIEW_BIAS_SHIFT) & VIEW_BIAS_MASK)
}

thread_local! {
/// Where the slots this thread keeps a recording's views in lie ([`ListViews`]: their
/// first byte and the one past their last; none before it has any), for [`own_slot`].
/// (Plain data: no destructor.)
static LIST_SLOTS: std::cell::Cell<(usize, usize)> = const { std::cell::Cell::new((0, 0)) };
}

#[cfg(test)]
thread_local! {
/// A test's choice for [`list_twin_move`], for its thread only.
pub(crate) static TEST_LIST_TWIN_MOVE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}

/// Whether the raw twin of a view a list keeps is moved to where its view begins, as the one
/// made beside the heaps is (`LEONIDA_LIST_TWIN_MOVE=1`; off by default: left where it was
/// made, with a bias or null). Only where the card's descriptors can be moved ([`move_raw`]);
/// a list's slot ([`ListViews`]) is this thread's own in a heap the card does not see, as
/// [`staged`]'s. By turns with `LEONIDA_AB`.
///
/// Such a twin is left where it was made, at the multiple of 16 before its view: with a bias
/// ([`twin_bias`]), or null where the view begins off its dwords (16-bit values at an odd
/// one). So a card whose descriptors [`move_raw`] moves has moved twins in the title's slots
/// and biased or null ones in the tables its lists make, and a card it does not move (an
/// RX 6800: [`twin_bias`]) biased ones everywhere. Which of the two an RX 7800 XT or an
/// RX 9070 XT is was not measured here (no such card). What cards have shown: on an
/// RX 7900 XT the picture broke when twins were first kept with a bias (#2702, where the
/// reporter asked for the bias only where `move_raw` cannot apply), and monte-alt/vesper
/// 7b7e556 (GPL-3.0, as this), which moves both kinds (its `TwinSlot::private`) and has no
/// bias, draws on an RX 9070 XT the ground this tree leaves black in patches (#2770).
/// Whether those patches come from here is not known until it is tried on such a card:
/// `listed_twins_moved_readback` (ignored: it needs one) reads through moved twins there.
fn list_twin_move() -> bool {
#[cfg(test)]
if let Some(on) = TEST_LIST_TWIN_MOVE.get() {
return on;
}
crate::asked!("LEONIDA_LIST_TWIN_MOVE")
}

/// Which slot of this thread's own, in a heap the card does not see, `twin` is, if it is one
/// [`move_raw`] may write: the one views are made in beside the heaps ([`staged`]; false), or
/// one of those it keeps a recording's views in ([`list_twin_move`]; true).
fn own_slot(twin: D3D12_CPU_DESCRIPTOR_HANDLE) -> Option<bool> {
if staged(false, 1).is_some_and(|s| s.ptr == twin.ptr) {
return Some(false);
}
let (from, to) = LIST_SLOTS.get();
((from..to).contains(&twin.ptr) && list_twin_move()).then_some(true)
}

/// 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 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)) {
if by == 0 {
return;
}
if let Some(listed) = own_slot(twin)
&& move_raw(twin, start, bytes, by)
{
if listed {
TWINS[4].fetch_add(1, Relaxed);
}
return;
}
if twin_bias() && by < 16 && by.is_multiple_of(4) && by < bytes {
Expand Down
173 changes: 168 additions & 5 deletions d3d12/crates/leonida-gpu/src/descriptor/host/listed_raw_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,47 @@ void main() {
}
"#;

/// Whether a list's own twins are moved ([`list_twin_move`]), on a test's thread until it is
/// dropped.
struct TwinMove(Option<bool>);

impl TwinMove {
fn set(on: bool) -> Self {
Self(TEST_LIST_TWIN_MOVE.replace(Some(on)))
}
}

impl Drop for TwinMove {
fn drop(&mut self) {
TEST_LIST_TWIN_MOVE.set(self.0);
}
}

/// A per-list view at 4, 8 and 12 bytes past a multiple of 16: its raw twin is made from the
/// multiple of 16 before it with the bias in its slot's stride word (`twin_bias`), and a program
/// that adds the bias reads the view's own dwords through it, and zeros past its end. Public
/// views at the same places and an explicit offset read the same.
#[test]
#[ignore = "offscreen descriptor probe requiring a host with raw view twins"]
fn listed_off_alignment_raw_twin_readback() {
listed_readback(false);
}

/// The same with the twins a list keeps moved to their views (`LEONIDA_LIST_TWIN_MOVE=1`), for
/// a card whose descriptors `move_raw` moves (not run on one: there was none here): the slots'
/// stride words then hold no bias, and a program reads the view's own dwords through the twin
/// with a bias of 0, and zeros past its end. On a card it does not move, the twins keep their
/// bias, as above.
#[test]
#[ignore = "offscreen descriptor probe requiring a host with raw view twins"]
fn listed_twins_moved_readback() {
listed_readback(true);
}

/// [`listed_off_alignment_raw_twin_readback`], with a list's own twins moved where they can be
/// if `move_twins`.
fn listed_readback(move_twins: bool) {
let _moved = TwinMove::set(move_twins);
const SIZE: u64 = 4096;
const POISON: u32 = 0xfeed_face;
let host = host().expect("an active D3D12 device");
Expand Down Expand Up @@ -181,11 +215,14 @@ fn listed_off_alignment_raw_twin_readback() {
heap.copy_from(slot + 1, cpu.slot(1));
}
let expected = [values[start as usize], values[start as usize + 1]];
// The words: R32_UINT (4 bytes, integer) and the twin's bias, made and copied alike.
// The words: R32_UINT (4 bytes, integer) and the twin's bias, made and copied alike; no
// bias where the twin was moved to its view.
let moved = word(first) & leonida_shader::emit::VIEW_BIAS_MASK == 0;
let kept = if moved { 0 } else { bias };
for slot in [first, first + 1] {
assert_eq!(
word(slot),
4 | leonida_shader::emit::VIEW_INTEGER | bias << leonida_shader::emit::VIEW_BIAS_SHIFT,
4 | leonida_shader::emit::VIEW_INTEGER | kept << leonida_shader::emit::VIEW_BIAS_SHIFT,
"stride word of slot {slot}"
);
}
Expand All @@ -195,8 +232,10 @@ fn listed_off_alignment_raw_twin_readback() {
// The view's own two dwords, then nothing past its end.
run(heap.raw + slot, first + 3, slot, [0, target_bias], expected);
run(heap.raw + slot, first + 3, slot, [8, target_bias], [0; 2]);
// Without the bias: the 16 bytes before the view's place, where the twin begins.
run(heap.raw + slot, first + 3, first + 2, [0, target_bias], [values[4], values[5]]);
// Without the bias: where the twin begins, at its view if it was moved, else the 16
// bytes before the view's place.
let begins = if moved { expected } else { [values[4], values[5]] };
run(heap.raw + slot, first + 3, first + 2, [0, target_bias], begins);
}
for slot in [first + 2, first + 4] {
run(slot, slot + 1, first + 2, [bias, target_bias], expected);
Expand All @@ -209,8 +248,10 @@ fn listed_off_alignment_raw_twin_readback() {
target_bias + 8,
target_bias,
);
// A list's twin is moved exactly where that is asked for and the card's descriptors can be.
assert_eq!(moved, move_twins && srv_guard, "bias {bias}: move asked {move_twins}, layout guard {srv_guard}");
println!(
"source bias {bias}, target bias {target_bias}: listed twins read right with their bias, public transfer correct, existing layout guard SRV={srv_guard} UAV={uav_guard}"
"source bias {bias}, target bias {target_bias}: listed twins read right (moved to their views: {moved}), public transfer correct, existing layout guard SRV={srv_guard} UAV={uav_guard}"
);
}
}
Expand Down Expand Up @@ -454,3 +495,125 @@ fn sub_dword_views_null_twins_and_recycled_raw_cbv_clears_bias() {
"constant_raw_at must clear stale twin bias when recycling a dynamic slot"
);
}

/// With `LEONIDA_LIST_TWIN_MOVE=1` a raw twin in a slot a list keeps its views in is moved to
/// where its view begins, as one in the slot beside the heaps is: the programs add no bias, and
/// one off its dwords is no null view. Without it, and in a slot that is not the thread's own,
/// it stays where it was made, with its bias.
#[test]
fn a_twin_in_a_lists_own_slot_is_moved_to_its_view() {
if !twin_bias() {
return;
}
// What a card whose descriptors can be moved holds for a raw buffer view (`move_raw`): its
// address, its bytes, then words that are not looked at. Made up, in memory that stands
// for the slots: no card is asked.
const START: u64 = 0x12_3456_7000;
const BYTES: u32 = 400;
let made = [START as u32, (START >> 32) as u32, BYTES, 0x1234_abcd, 5, 6, 7, 8];
let mut slots = [made; 2];
let first = slots.as_mut_ptr();
let at = |i: usize| D3D12_CPU_DESCRIPTOR_HANDLE { ptr: first.wrapping_add(i) as usize };
// SAFETY: a slot of `slots`, which lives to the end of the test and is read through `first` alone.
let read = |i: usize| unsafe { first.add(i).read() };
// SAFETY: as above.
let reset = |i: usize| unsafe { first.add(i).write(made) };
let moved = |by: u32| {
let to = START + u64::from(by);
[to as u32, (to >> 32) as u32, BYTES - by, 0x1234_abcd, 5, 6, 7, 8]
};
let _ = take_twin_bias();
// The first of the two is a list's; the second is no slot of the thread's.
let was = LIST_SLOTS.replace((at(0).ptr, at(1).ptr));
{
let _on = TwinMove::set(true);
for by in [8u32, 2, 15] {
reset(0);
settle_twin(at(0), START, BYTES, by);
assert_eq!(take_twin_bias(), 0, "moved by {by}: nothing for the programs to add");
assert_eq!(read(0), moved(by), "moved by {by}");
}
// Not the descriptor it is taken for (another size): not moved, kept with its bias.
reset(0);
settle_twin(at(0), START, BYTES + 4, 8);
assert_eq!((take_twin_bias(), read(0)), (8, made));
// No slot of the thread's own.
settle_twin(at(1), START, BYTES, 8);
assert_eq!((take_twin_bias(), read(1)), (8, made));
}
{
let _off = TwinMove::set(false);
settle_twin(at(0), START, BYTES, 8);
assert_eq!((take_twin_bias(), read(0)), (8, made), "without LEONIDA_LIST_TWIN_MOVE=1: as before");
}
LIST_SLOTS.set(was);
}

/// Calling [`HostHeap::make_listed`] on a fresh thread populates [`LIST_SLOTS`] with that
/// thread's real [`ListViews`] descriptor range, and [`own_slot`] recognizes every slot inside
/// that range (and rejects handles outside it) when `LEONIDA_LIST_TWIN_MOVE=1`.
#[test]
fn make_listed_populates_thread_list_slots_for_own_slot() {
let Some(host) = host() else {
return; // no host D3D12 device
};
std::thread::spawn(move || {
assert_eq!(LIST_SLOTS.get(), (0, 0), "fresh thread starts with empty LIST_SLOTS");
let heap = HostHeap::new(false, 4).expect("host view heap");
let first = heap.dynamic(2).expect("dynamic slots");
const SIZE: u64 = 4096;
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("registered buffer shadow");
let _ = &host.device;

let resource = [1, 0, 0, 0, SIZE as u32, 0, 1, 1 | 1 << 16, 0, 1, 0, 1, 0, 0];
let mut desc = [0u32; 16];
desc[..10].copy_from_slice(&[42, 1, 5768, 0, 6, 0, 2, 0, 0, 0]);
(desc[10], desc[11]) = (address as u32, (address >> 32) as u32);
let mut rec = [0u32; 8];
crate::descriptor::record(rec.as_mut_ptr() as u64, View::Placed(false, resource, desc));
assert!(
heap.make_listed(1, [rec[0], rec[1], rec[2]], first).is_some(),
"make_listed must succeed on a real placed buffer view"
);
flush_listed();

let (from, to) = LIST_SLOTS.get();
let expected = LIST_VIEWS.with(|views| {
let views = views.borrow();
let v = views.as_ref().expect("LIST_VIEWS initialized by make_listed");
(v.start, v.start + ListViews::SLOTS as usize * v.step, v.step)
});
assert_ne!(from, 0);
assert_eq!((from, to), (expected.0, expected.1));
let step = expected.2;

{
let _off = TwinMove::set(false);
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from }), None);
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to - step }), None);
}
{
let _on = TwinMove::set(true);
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from }), Some(true));
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from + step }), Some(true));
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to - step }), Some(true));
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: from.wrapping_sub(step) }), None);
assert_eq!(own_slot(D3D12_CPU_DESCRIPTOR_HANDLE { ptr: to }), None);
if let Some(staging) = staged(false, 1) {
assert_eq!(own_slot(staging), Some(false));
}
}
})
.join()
.expect("LIST_SLOTS worker thread");
}
Loading
Loading