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
202 changes: 185 additions & 17 deletions crates/xcl/src/hle/d3d12x/barrier_groups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
//! goes (`list_x::resource_barrier_x`). A layout says where a texture is; the access bits only
//! say which uses the title makes of it there, so the states come from the layouts. A barrier to
//! the undefined layout (the title is done with what the texture holds) moves nothing; one from
//! it starts at the state the texture was last moved to here. Buffer and global barriers have no
//! layout: the UAV barrier `list_x::uav_barrier_x` sends stands for them.
//! it starts at the state the texture was last moved to here, or else the state it was made in.
//! Buffer and global barriers have no layout: the UAV barrier `list_x::uav_barrier_x` sends stands for them.
//!
//! `XCL_BARRIER_GROUPS=0` turns the transitions off (the UAV barrier stays).

Expand Down Expand Up @@ -123,6 +123,8 @@ pub(super) struct Texture {
pub layout: (u32, u32),
pub res: usize,
pub range: [u32; 6],
/// D3D12_TEXTURE_BARRIER_FLAGS (only counted: `note_discards`)
pub flags: u32,
}

/// What a texture is like for `transitions_of`: (depth buffer, levels, slices, planes).
Expand Down Expand Up @@ -270,37 +272,59 @@ struct Tracked {
plane_stride: u32,
}

/// The per-plane state each texture was last moved to by a barrier group (the title's recording order).
/// The per-plane state each texture is in, in the title's recording order: seeded with the PC
/// state it was made in (`note_created`), then moved by barrier groups and legacy transitions.
/// A barrier from the undefined layout starts there.
static LAST: Sharded<Tracked> = Sharded::new();

/// The record a texture made in the PC state `state` starts with: both planes there.
fn created(state: u32, plane_stride: u32) -> Tracked {
Tracked { states: [Some(state), Some(state)], plane_stride }
}

/// `res` was made in the PC state `state` (`depth_uav::note_created`'s callers). Recorded whether
/// or not the title has used barrier groups yet: textures made at load (most render targets
/// and depth buffers) come before its first barrier group. A buffer is not recorded.
pub(super) fn note_created(res: usize, state: u32) {
if res == 0 || !enabled() {
return;
}
let r = res as *mut c_void;
let Some(d) = (unsafe { ID3D12Resource::from_raw_borrowed(&r) }).map(|r| unsafe { r.GetDesc() }) else { return };
if d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER {
return;
}
let array = if d.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D { 1 } else { d.DepthOrArraySize as u32 };
LAST.insert(res, created(state, (d.MipLevels as u32).max(1) * array.max(1)));
}

/// Texture barriers read, and transitions made of them.
static COUNTS: [AtomicU64; 2] = [const { AtomicU64::new(0) }; 2];

/// Keep `LAST` in sync when a legacy `ResourceBarrier` transitions a tracked texture (e.g. to
/// `COMMON` before returning to enhanced barriers). No-op if the resource is not tracked.
/// A legacy `ResourceBarrier` moves `res`'s subresource `sub` to `after`. A transition of all
/// subresources sets both planes; one of some sets the plane they are in (as a barrier group's
/// partial range does). No-op if the texture is not tracked.
pub(super) fn note_legacy_state(res: usize, sub: u32, after: u32) {
if COUNTS[0].load(Ordering::Relaxed) == 0 {
return;
if let Some(cur) = LAST.get(res) {
LAST.insert(res, legacy_moved(cur, sub, after));
}
let Some(mut cur) = LAST.get(res) else { return };
}

fn legacy_moved(mut cur: Tracked, sub: u32, after: u32) -> Tracked {
if sub == D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES {
cur.states[0] = Some(after);
if cur.states[1].is_some() {
cur.states[1] = Some(after);
}
cur.states = [Some(after), Some(after)];
} else if cur.plane_stride > 0 {
let p = (sub / cur.plane_stride) as usize;
if p < 2 {
cur.states[p] = Some(after);
}
}
LAST.insert(res, cur);
cur
}

/// The last reference of `res` goes (`real::res_release`).
pub(super) fn forget(res: usize) {
if COUNTS[0].load(Ordering::Relaxed) != 0 {
LAST.remove(res);
}
LAST.remove(res);
}

/// `state` as a texture with the PC resource flags `flags` (D3D12_RESOURCE_FLAGS) can be in it on
Expand Down Expand Up @@ -366,6 +390,7 @@ pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) ->
layout: (tb.LayoutBefore.0 as u32, tb.LayoutAfter.0 as u32),
res: std::mem::transmute_copy(&tb.pResource),
range: [r.IndexOrFirstMipLevel, r.NumMipLevels, r.FirstArraySlice, r.NumArraySlices, r.FirstPlane, r.NumPlanes],
flags: tb.Flags.0 as u32,
});
}
}
Expand Down Expand Up @@ -401,6 +426,7 @@ pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) ->
LAST.insert(res, cur);
},
);
note_discards(&textures, &asked);
out.retain_mut(|w| {
let res = (w[2] as u64 | (w[3] as u64) << 32) as usize;
let Some(a) = asked.iter().find(|a| a.0 == res).map(|a| a.1) else { return false };
Expand Down Expand Up @@ -447,6 +473,45 @@ pub(super) unsafe fn transitions(n: u32, groups: *const c_void, direct: bool) ->
out
}

/// D3D12_TEXTURE_BARRIER_FLAG_DISCARD
const FLAG_DISCARD: u32 = 0x1;
/// Barriers from the undefined layout by the kind of texture (render target, depth, unordered
/// access only, other): all of them, and those asking for a discard.
static FROM_UNDEFINED: [[AtomicU64; 2]; 4] = [const { [const { AtomicU64::new(0) }; 2] }; 4];

/// The kind of texture (`FROM_UNDEFINED`'s index) its PC resource flags make it.
fn kind(flags: u32) -> usize {
if flags & 0x2 != 0 { 1 } else if flags & 0x1 != 0 { 0 } else if flags & 0x4 != 0 { 2 } else { 3 }
}

/// Counts the barriers from the undefined layout that ask for a discard. XCL sends no discard
/// for them (a legacy transition has none); a texture placed on the PC that the title only
/// initialises this way keeps whatever its compression metadata held.
fn note_discards(textures: &[Texture], asked: &[(usize, Asked)]) {
let mut discards = 0u64;
for t in textures.iter().filter(|t| t.layout.0 == UNDEFINED && t.layout.1 != UNDEFINED) {
let Some(a) = asked.iter().find(|a| a.0 == t.res).map(|a| a.1) else { continue };
let k = kind(a.flags);
FROM_UNDEFINED[k][0].fetch_add(1, Ordering::Relaxed);
if t.flags & FLAG_DISCARD == 0 {
continue;
}
let n = FROM_UNDEFINED[k][1].fetch_add(1, Ordering::Relaxed) + 1;
discards += 1;
if n <= 4 {
crate::xlog_info!("D3D12.X: barrier groups: a barrier from the undefined layout asks for a discard (sent without one): texture {:#x} (flags {:#x}, format {}, {} subresources), layout {:#x}, range {:?}", t.res, a.flags, a.format, a.subresources, t.layout.1, t.range);
}
}
if discards == 0 {
return;
}
let all: u64 = FROM_UNDEFINED.iter().map(|k| k[1].load(Ordering::Relaxed)).sum();
if (all - discards).leading_zeros() != all.leading_zeros() {
let c = |k: usize, i: usize| FROM_UNDEFINED[k][i].load(Ordering::Relaxed);
crate::xlog_info!("D3D12.X: barrier groups: barriers from the undefined layout asking for a discard / all of them: render targets {}/{}, depth {}/{}, unordered access {}/{}, other {}/{}", c(0, 1), c(0, 0), c(1, 1), c(1, 0), c(2, 1), c(2, 0), c(3, 1), c(3, 0));
}
}

/// Transitions not made: the PC would refuse them.
static REFUSED: AtomicU64 = AtomicU64::new(0);

Expand Down Expand Up @@ -526,7 +591,7 @@ mod tests {
}

fn t(res: usize, layout: (u32, u32), access: (u32, u32)) -> Texture {
Texture { sync: (0, 0), access, layout, res, range: [u32::MAX, 0, 0, 0, 0, 0] }
Texture { sync: (0, 0), access, layout, res, range: [u32::MAX, 0, 0, 0, 0, 0], flags: 0 }
}

fn run(b: &[Texture], last: &mut std::collections::HashMap<usize, PlaneStates>) -> Vec<(usize, u32, u32, u32, u32)> {
Expand Down Expand Up @@ -575,6 +640,109 @@ mod tests {
assert_eq!(last.get(&0xC), Some(&[Some(SHADER_RESOURCE), None]));
}

#[test]
fn a_new_texture_leaves_the_undefined_layout_from_the_state_it_was_made_in() {
// (#3489) the record starts in the creation state on both planes
assert_eq!(created(0, 1).states, [Some(0), Some(0)]);
// a render target made in COMMON: drawn into after UNDEFINED -> RENDER_TARGET, so the PC
// texture must leave COMMON first
let mut last = std::collections::HashMap::from([(0xB, created(0, 1).states)]);
assert_eq!(run(&[t(0xB, (UNDEFINED, 2), (NO_ACCESS, 0x8))], &mut last), [(0xB, ALL, 0, RENDER_TARGET, 0)]);
// and the title's next barrier starts from where it now is
assert_eq!(run(&[t(0xB, (2, 6), (0x8, 0x80))], &mut last), [(0xB, ALL, RENDER_TARGET, SHADER_RESOURCE, 0)]);
// made where the barrier goes: nothing to send
let mut last = std::collections::HashMap::from([(0xB, created(RENDER_TARGET, 1).states)]);
assert_eq!(run(&[t(0xB, (UNDEFINED, 2), (NO_ACCESS, 0x8))], &mut last), []);
}

#[test]
fn a_legacy_move_of_some_subresources_then_of_all_leaves_a_known_state() {
let made = created(0, 2);
let partial = legacy_moved(made, 1, COPY_DEST);
assert_eq!(partial.states, [Some(COPY_DEST), Some(0)], "the plane the subresource is in");
let stencil = legacy_moved(made, 2, COPY_DEST);
assert_eq!(stencil.states, [Some(0), Some(COPY_DEST)]);
let whole = legacy_moved(partial, ALL, SHADER_RESOURCE);
assert_eq!(whole.states, [Some(SHADER_RESOURCE), Some(SHADER_RESOURCE)]);
}

/// The whole path on WARP textures: the creation hook (before any barrier group), legacy
/// transitions, barrier groups and the release hook, as the runtime calls them.
#[test]
fn a_texture_is_tracked_from_creation_through_legacy_and_group_barriers_to_release() {
use windows::Win32::Graphics::Dxgi::{Common::*, CreateDXGIFactory1, IDXGIAdapter, IDXGIFactory4};
let mut dev: Option<ID3D12Device> = None;
let made = unsafe {
CreateDXGIFactory1::<IDXGIFactory4>()
.and_then(|f| f.EnumWarpAdapter::<IDXGIAdapter>())
.and_then(|a| D3D12CreateDevice(&a, windows::Win32::Graphics::Direct3D::D3D_FEATURE_LEVEL_11_0, &mut dev))
};
let Some(dev) = dev.filter(|_| made.is_ok()) else { return crate::gpu::recomp::runner::skip_test("no WARP device") };
let texture = |format: DXGI_FORMAT, flags: D3D12_RESOURCE_FLAGS, state: u32| -> ID3D12Resource {
let desc = D3D12_RESOURCE_DESC {
Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 16, Height: 16, DepthOrArraySize: 1, MipLevels: 1,
Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
Flags: flags, ..Default::default()
};
let heap = D3D12_HEAP_PROPERTIES { Type: D3D12_HEAP_TYPE_DEFAULT, ..Default::default() };
let mut r: Option<ID3D12Resource> = None;
unsafe { dev.CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATES(state as i32), None, &mut r) }.unwrap();
let r = r.unwrap();
note_created(r.as_raw() as usize, state);
r
};
let barrier = |r: &ID3D12Resource, layout: (u32, u32), access: u32, plane: Option<u32>| D3D12_TEXTURE_BARRIER {
SyncBefore: D3D12_BARRIER_SYNC(0), SyncAfter: D3D12_BARRIER_SYNC(0),
AccessBefore: D3D12_BARRIER_ACCESS(NO_ACCESS as i32), AccessAfter: D3D12_BARRIER_ACCESS(access as i32),
LayoutBefore: D3D12_BARRIER_LAYOUT(layout.0 as i32), LayoutAfter: D3D12_BARRIER_LAYOUT(layout.1 as i32),
pResource: std::mem::ManuallyDrop::new(Some(r.clone())),
Subresources: match plane {
None => D3D12_BARRIER_SUBRESOURCE_RANGE { IndexOrFirstMipLevel: u32::MAX, ..Default::default() },
Some(p) => D3D12_BARRIER_SUBRESOURCE_RANGE { IndexOrFirstMipLevel: 0, NumMipLevels: 1, FirstArraySlice: 0, NumArraySlices: 1, FirstPlane: p, NumPlanes: 1 },
},
Flags: D3D12_TEXTURE_BARRIER_FLAGS(0),
};
let send = |mut b: D3D12_TEXTURE_BARRIER| -> Vec<(u32, u32, u32)> {
let group = D3D12_BARRIER_GROUP { Type: D3D12_BARRIER_TYPE_TEXTURE, NumBarriers: 1, Anonymous: D3D12_BARRIER_GROUP_0 { pTextureBarriers: &b } };
let out = unsafe { transitions(1, &group as *const _ as *const c_void, true) };
unsafe { std::mem::ManuallyDrop::drop(&mut b.pResource) };
out.iter().map(|w| (w[4], w[5], w[6])).collect()
};
let rt = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;

// made in COMMON, first moved by a barrier group from the undefined layout
let a = texture(DXGI_FORMAT_R8G8B8A8_UNORM, rt, 0);
assert_eq!(send(barrier(&a, (UNDEFINED, 2), 0x4, None)), [(ALL, 0, RENDER_TARGET)]);

// made in COMMON, moved by a legacy barrier before the title's first group on it
let b = texture(DXGI_FORMAT_R8G8B8A8_UNORM, rt, 0);
note_legacy_state(b.as_raw() as usize, ALL, COPY_DEST);
assert_eq!(send(barrier(&b, (UNDEFINED, 2), 0x4, None)), [(ALL, COPY_DEST, RENDER_TARGET)]);

// a legacy move of one subresource, then of all of them: the state is known again
let c = texture(DXGI_FORMAT_R8G8B8A8_UNORM, rt, 0);
note_legacy_state(c.as_raw() as usize, 0, COPY_DEST);
note_legacy_state(c.as_raw() as usize, ALL, SHADER_RESOURCE);
assert_eq!(send(barrier(&c, (UNDEFINED, 2), 0x4, None)), [(ALL, SHADER_RESOURCE, RENDER_TARGET)]);

// a depth-stencil buffer: the depth plane first, then the stencil plane, each from COMMON
let d = texture(DXGI_FORMAT_D24_UNORM_S8_UINT, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, 0);
assert_eq!(send(barrier(&d, (UNDEFINED, 4), 0x20, Some(0))), [(0, 0, DEPTH_WRITE)]);
assert_eq!(send(barrier(&d, (UNDEFINED, 4), 0x20, Some(1))), [(1, 0, DEPTH_WRITE)]);

// released: the record goes; a texture made at the same address starts from its own state
let e = texture(DXGI_FORMAT_R8G8B8A8_UNORM, rt, 0);
let at = e.as_raw() as usize;
forget(at);
assert_eq!(send(barrier(&e, (UNDEFINED, 2), 0x4, None)), [], "untracked: nothing is sent");
note_created(at, RENDER_TARGET);
assert_eq!(send(barrier(&e, (UNDEFINED, 2), 0x4, None)), [], "already there");
assert_eq!(send(barrier(&e, (UNDEFINED, 6), 0x80, None)), [(ALL, RENDER_TARGET, SHADER_RESOURCE)]);
for r in [&a, &b, &c, &d, &e] {
forget(r.as_raw() as usize);
}
}

#[test]
fn the_halves_of_a_split_barrier_are_the_pcs_begin_and_end() {
let mut last = Default::default();
Expand Down
3 changes: 3 additions & 0 deletions crates/xcl/src/hle/d3d12x/device_x.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1290,6 +1290,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
}
real::note_title_address(*ppv as usize, va as usize);
super::depth_uav::note_created(*ppv, &x, Some(va as usize), state);
super::barrier_groups::note_created(*ppv as usize, state);
super::lut3d::created("CreatePlacedResourceX (GPU-owned: on the title's pages / an arena)", *ppv, Some(&x), Some(va as usize), false, state);
}
return hr;
Expand All @@ -1313,6 +1314,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
Ok(()) => {
real::note_title_address(*ppv as usize, va as usize);
super::depth_uav::note_created(*ppv, &x, Some(va as usize), state);
super::barrier_groups::note_created(*ppv as usize, state);
super::lut3d::created(if placed_hr.is_some() { "CreatePlacedResourceX (sampled: on shared pages)" } else if small_hr.is_some() { "CreatePlacedResourceX (sampled: 4 KiB placement)" } else { "CreatePlacedResourceX (sampled: committed)" }, *ppv, Some(&x), Some(va as usize), true, state);
return hr;
}
Expand All @@ -1331,6 +1333,7 @@ pub(super) unsafe extern "system" fn create_placed_resource_x(this: *mut c_void,
real::note_title_address(*ppv as usize, va as usize);
if !buffer {
super::depth_uav::note_created(*ppv, &x, Some(va as usize), state);
super::barrier_groups::note_created(*ppv as usize, state);
super::lut3d::created("CreatePlacedResourceX (a resource of its own: not kept in step)", *ppv, Some(&x), Some(va as usize), false, state);
}
}
Expand Down
7 changes: 7 additions & 0 deletions crates/xcl/src/hle/d3d12x/real.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3927,6 +3927,7 @@ unsafe extern "system" fn dev_create_committed_resource_x(this: *mut c_void, pro
let hr = dev_create_committed_resource(this, props, flags, desc, st as usize, clear, riid, ppv);
if hr >= 0 && pc_full.is_some() && !ppv.is_null() && !(*ppv).is_null() {
super::depth_uav::note_created(*ppv, &(console_desc as *const [u8; 0x38]).read_unaligned(), None, st);
super::barrier_groups::note_created(*ppv as usize, st);
super::lut3d::created("CreateCommittedResource (a PC resource: not in the title's memory)", *ppv, Some(&(console_desc as *const [u8; 0x38]).read_unaligned()), None, false, st);
}
if hr < 0 {
Expand Down Expand Up @@ -4481,6 +4482,10 @@ unsafe fn placed_in_heap_x(this: *mut c_void, heap: usize, offset: usize, desc:
return hr;
}
let hr = dev_create_placed_resource(this, heap, offset, desc, state, clear, riid, ppv);
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
// (a buffer is not recorded)
super::barrier_groups::note_created(*ppv as usize, state as u32 & PC_RESOURCE_STATES);
}
if hr >= 0 || desc == 0 || !crate::gpu::shader::readable(desc, 0x38) {
return hr;
}
Expand Down Expand Up @@ -4519,6 +4524,7 @@ unsafe fn placed_in_heap_x(this: *mut c_void, heap: usize, offset: usize, desc:
let hr = hr3.unwrap_or(hr2);
if hr >= 0 && is_texture && !ppv.is_null() && !(*ppv).is_null() {
super::depth_uav::note_created(*ppv, &x, None, st);
super::barrier_groups::note_created(*ppv as usize, st);
}
hr
}
Expand Down Expand Up @@ -4559,6 +4565,7 @@ unsafe fn own_memory_if_larger_on_the_pc(this: *mut c_void, heap: usize, offset:
}
if hr >= 0 && !ppv.is_null() && !(*ppv).is_null() {
super::depth_uav::note_created(*ppv, &x, None, made_in);
super::barrier_groups::note_created(*ppv as usize, made_in);
}
static N: AtomicU64 = AtomicU64::new(0);
if N.fetch_add(1, Ordering::Relaxed) < 8 {
Expand Down
Loading