Repository navigation
D3D12.X: XCL_CAST_LIST=1 shares one texture between R32_UINT and R9G9B9E5 #3340
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
42efa87
b383ccf
a07d740
4bb5c9a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -1984,3 +1984,6 @@ fn dispatch_with( | |
| Ok((out, ms)) | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod cast_tests; | ||
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,344 @@ | ||
| //! One memory, two formats, by relaxed format casting. | ||
| //! | ||
| //! A retail title packs light as R9G9B9E5 into R32_UINT textures (its compute programs cannot | ||
| //! store R9G9B9E5) and samples the same memory through an R9G9B9E5 texture it places at the same | ||
| //! address. On the console the two are one memory; here they are two PC textures, | ||
| //! and what is read through the sampled one is not what the GPU wrote. | ||
| //! | ||
| //! Where the device has relaxed format casting (OPTIONS12) and ID3D12Device10, a GPU-written | ||
| //! R32_UINT 2D texture is made with [R32_UINT, R9G9B9E5_SHAREDEXP] as its cast list (and a | ||
| //! texture the title gives a cast list of its own, console device #127, with that list too). | ||
| //! A view the title makes of a sampled texture at the same address, of the same shape, in a | ||
| //! format of that list, is made on the written texture: one PC texture under both descriptions. | ||
| //! | ||
| //! The title's legacy resource states are preserved. The title's views on the written resource | ||
| //! go with it (`console_heap::resource_gone`). | ||
| //! | ||
| //! Behind `XCL_CAST_LIST=1` (off by default); with it off nothing is kept and every hook stops | ||
| //! at one atomic load or a `OnceLock` read. | ||
|
|
||
| use std::cell::RefCell; | ||
| use std::collections::{HashMap, HashSet}; | ||
| use std::ffi::c_void; | ||
| use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; | ||
| use std::sync::{Mutex, OnceLock}; | ||
|
|
||
| use windows::core::Interface; | ||
| use windows::Win32::Graphics::Direct3D12::*; | ||
| use windows::Win32::Graphics::Dxgi::Common::*; | ||
|
|
||
| /// The pair the title packs light in: written as the first, read as the second. | ||
| const LIGHT: [DXGI_FORMAT; 2] = [DXGI_FORMAT_R32_UINT, DXGI_FORMAT_R9G9B9E5_SHAREDEXP]; | ||
|
|
||
| /// `XCL_CAST_LIST=1` (read once). | ||
| pub(super) fn on() -> bool { | ||
| static ON: OnceLock<bool> = OnceLock::new(); | ||
| *ON.get_or_init(|| std::env::var("XCL_CAST_LIST").is_ok_and(|v| v.trim() == "1")) | ||
| } | ||
|
|
||
| /// What a writer's views and barriers need. | ||
| #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] | ||
| struct Shape { | ||
| dimension: i32, | ||
| width: u64, | ||
| height: u32, | ||
| depth: u16, | ||
| mips: u16, | ||
| } | ||
|
|
||
| impl Shape { | ||
| fn of(d: &D3D12_RESOURCE_DESC) -> Self { | ||
| let extent = match d.Dimension { | ||
| D3D12_RESOURCE_DIMENSION_TEXTURE1D => d.Width, | ||
| D3D12_RESOURCE_DIMENSION_TEXTURE3D => d.Width.max(d.Height as u64).max(d.DepthOrArraySize as u64), | ||
| _ => d.Width.max(d.Height as u64), | ||
| }; | ||
| let full_mips = (u64::BITS - extent.max(1).leading_zeros()) as u16; | ||
| Shape { | ||
| dimension: d.Dimension.0, | ||
| width: d.Width, | ||
| height: d.Height, | ||
| depth: d.DepthOrArraySize.max(1), | ||
| mips: if d.MipLevels == 0 { full_mips } else { d.MipLevels }, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| struct Writer { | ||
| res: usize, | ||
| shape: Shape, | ||
| format: i32, | ||
| casts: Vec<i32>, | ||
| } | ||
|
|
||
| #[derive(Default)] | ||
| struct Table { | ||
| /// by (device, canonical address) | ||
| writers: HashMap<(usize, usize), Writer>, | ||
| /// the cast-made textures: their barriers are widened | ||
| made: HashSet<usize>, | ||
| /// the title's other textures, by resource: (device, canonical address, shape, format) | ||
| readers: HashMap<usize, (usize, usize, Shape, i32)>, | ||
| } | ||
|
|
||
| static TABLE: Mutex<Option<Table>> = Mutex::new(None); | ||
| /// Cast-made textures alive: the gate of every hook. | ||
| static MADE: AtomicUsize = AtomicUsize::new(0); | ||
| static VIEWS: AtomicU64 = AtomicU64::new(0); | ||
|
|
||
| thread_local! { | ||
| /// The cast list from #127, restricted to the resource at the title allocation's address. | ||
| static TITLE: RefCell<TitleCasts> = const { RefCell::new(TitleCasts { formats: Vec::new(), va: None }) }; | ||
| } | ||
|
|
||
| struct TitleCasts { formats: Vec<i32>, va: Option<usize> } | ||
|
|
||
| /// The title's create (#127) with `n` castable formats at `formats`: they are its texture's cast | ||
| /// list while the guard lives. | ||
| pub(super) struct TitleList; | ||
|
|
||
| impl Drop for TitleList { | ||
| fn drop(&mut self) { | ||
| TITLE.with(|t| *t.borrow_mut() = TitleCasts { formats: Vec::new(), va: None }); | ||
| } | ||
| } | ||
|
|
||
| pub(super) unsafe fn title_list(n: u32, formats: usize) -> Option<TitleList> { | ||
| if !on() || n == 0 || n > 16 || formats == 0 || !crate::gpu::shader::readable(formats, n as usize * 4) { | ||
| return None; | ||
| } | ||
| let list: Vec<i32> = (0..n as usize).map(|k| super::device_x::pc_view_format(((formats + 4 * k) as *const u32).read_unaligned()) as i32).filter(|&f| f != 0).collect(); | ||
| TITLE.with(|t| *t.borrow_mut() = TitleCasts { formats: list, va: None }); | ||
| Some(TitleList) | ||
| } | ||
|
|
||
| /// Bind #127's cast list to the allocation that its committed-resource hook is about to place. | ||
| pub(super) fn title_address(va: usize) { | ||
| TITLE.with(|t| { | ||
| let mut t = t.borrow_mut(); | ||
| if !t.formats.is_empty() && t.va.is_none() { t.va = Some(super::vram::canonical_va(va)); } | ||
| }); | ||
| } | ||
|
|
||
| fn take_title_formats(va: usize) -> Vec<i32> { | ||
| TITLE.with(|t| { | ||
| let mut t = t.borrow_mut(); | ||
| if t.va == Some(super::vram::canonical_va(va)) { | ||
| std::mem::take(&mut t.formats) | ||
| } else { Vec::new() } | ||
| }) | ||
| } | ||
|
|
||
| /// The barrier layout a writer is made in for the initial state `state` (None: made without a cast list). | ||
| fn layout_of(state: u32) -> Option<D3D12_BARRIER_LAYOUT> { | ||
| Some(match state { | ||
| 0 => D3D12_BARRIER_LAYOUT_COMMON, | ||
| 0x4 => D3D12_BARRIER_LAYOUT_RENDER_TARGET, | ||
| 0x8 => D3D12_BARRIER_LAYOUT_UNORDERED_ACCESS, | ||
| 0x400 => D3D12_BARRIER_LAYOUT_COPY_DEST, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The pushed head doesn't match the description. The body describes a later head (b25dbd8) that creates the written texture in COMMON, settles it with |
||
| _ => return None, | ||
| }) | ||
| } | ||
|
|
||
| /// Whether `dev` casts a texture's formats and samples R9G9B9E5 (asked once per device). | ||
| unsafe fn device_can(dev: &ID3D12Device) -> bool { | ||
| static CAN: Mutex<Option<HashMap<usize, bool>>> = Mutex::new(None); | ||
| let key = dev.as_raw() as usize; | ||
| if let Some(&c) = CAN.lock().unwrap().as_ref().and_then(|m| m.get(&key)) { | ||
| return c; | ||
| } | ||
| let mut o12 = D3D12_FEATURE_DATA_D3D12_OPTIONS12::default(); | ||
| let relaxed = dev.CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS12, &mut o12 as *mut _ as *mut c_void, std::mem::size_of_val(&o12) as u32).is_ok() && o12.RelaxedFormatCastingSupported.as_bool(); | ||
| let mut fs = D3D12_FEATURE_DATA_FORMAT_SUPPORT { Format: DXGI_FORMAT_R9G9B9E5_SHAREDEXP, ..Default::default() }; | ||
| let sample = dev.CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &mut fs as *mut _ as *mut c_void, std::mem::size_of_val(&fs) as u32).is_ok() | ||
| && (fs.Support1.0 & (D3D12_FORMAT_SUPPORT1_TEXTURE2D.0 | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE.0)) == (D3D12_FORMAT_SUPPORT1_TEXTURE2D.0 | D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE.0); | ||
| let device10 = dev.cast::<ID3D12Device10>().is_ok(); | ||
| let can = relaxed && sample && device10; | ||
| crate::xlog_info!( | ||
| "D3D12.X: cast lists {}: relaxed format casting {relaxed}, R9G9B9E5 sampled {sample}, ID3D12Device10 {device10}{}", | ||
| if can { "on" } else { "off" }, | ||
| if can { " (XCL_CAST_LIST=1: a GPU-written R32_UINT texture is made with R9G9B9E5 in its cast list)" } else { "" } | ||
| ); | ||
| CAN.lock().unwrap().get_or_insert_with(HashMap::new).insert(key, can); | ||
| can | ||
| } | ||
|
|
||
| /// The layout and cast list to make the GPU-owned texture `desc` with, in `state` (None: made | ||
| /// as before). The light pair's written texture, and the title's own list (#127). | ||
| pub(super) unsafe fn for_writer(dev: &ID3D12Device, desc: &D3D12_RESOURCE_DESC, state: u32, va: usize) -> Option<(D3D12_BARRIER_LAYOUT, Vec<i32>)> { | ||
| if !on() || desc.SampleDesc.Count > 1 { | ||
| return None; | ||
| } | ||
| let mut casts = take_title_formats(va); | ||
| let light = desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.Format == LIGHT[0] && desc.Flags.0 & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS.0 != 0; | ||
| if light { | ||
| casts.extend(LIGHT.iter().map(|f| f.0)); | ||
| } | ||
| if casts.is_empty() { | ||
| return None; | ||
| } | ||
| let layout = layout_of(state)?; | ||
| if !device_can(dev) { | ||
| return None; | ||
| } | ||
| if !casts.contains(&desc.Format.0) { | ||
| casts.push(desc.Format.0); | ||
| } | ||
| casts.sort_unstable(); | ||
| casts.dedup(); | ||
| // (one format is no cast list: the texture is made as before) | ||
| (casts.len() >= 2).then_some((layout, casts)) | ||
| } | ||
|
|
||
| /// `res` was made at the canonical address `va` with the cast list `casts` (`vram`). | ||
| pub(super) fn made(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC, casts: Vec<i32>) { | ||
| let mut g = TABLE.lock().unwrap(); | ||
| let t = g.get_or_insert_with(Table::default); | ||
| if t.made.insert(res) { | ||
| MADE.fetch_add(1, Ordering::Relaxed); | ||
| } | ||
| t.writers.insert((dev, va), Writer { res, shape: Shape::of(desc), format: desc.Format.0, casts }); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| } | ||
|
|
||
| /// The title placed `res` (PC description `desc`) at `va` (`device_x::create_placed_resource_x`). | ||
| pub(super) fn note_created(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC) { | ||
| if on() { | ||
| keep_reader(dev, res, super::vram::canonical_va(va), desc); | ||
| } | ||
| } | ||
|
|
||
| /// `note_created` without the switch (`va` canonical). Kept before any writer is made: a view is | ||
| /// put on its writer when it is made, in either order. | ||
| fn keep_reader(dev: usize, res: usize, va: usize, desc: &D3D12_RESOURCE_DESC) { | ||
| if res == 0 || va == 0 || desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count > 1 { | ||
| return; | ||
| } | ||
| let mut g = TABLE.lock().unwrap(); | ||
| let t = g.get_or_insert_with(Table::default); | ||
| if !t.made.contains(&res) { | ||
| t.readers.insert(res, (dev, va, Shape::of(desc), desc.Format.0)); | ||
| } | ||
| } | ||
|
|
||
| /// Whether `res` was made with a cast list. | ||
| #[cfg(test)] | ||
| fn is_writer(res: usize) -> bool { | ||
| MADE.load(Ordering::Relaxed) != 0 && TABLE.lock().unwrap().as_ref().is_some_and(|t| t.made.contains(&res)) | ||
| } | ||
|
|
||
| /// The written texture to make the title's view `view` of `res` on, and the view (None: `res`'s | ||
| /// own): `res` is at a writer's address with its shape, in another format of its cast list. | ||
| pub(super) fn view_on_writer(res: usize, view: Option<&D3D12_SHADER_RESOURCE_VIEW_DESC>) -> Option<(usize, D3D12_SHADER_RESOURCE_VIEW_DESC)> { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
|
||
| if MADE.load(Ordering::Relaxed) == 0 || res == 0 { | ||
| return None; | ||
| } | ||
| let (writer, v) = { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The redirect only happens when the SRV is created. If the title places the reader, creates its R9G9B9E5 SRV and only then places the writer, |
||
| let g = TABLE.lock().unwrap(); | ||
| let t = g.as_ref()?; | ||
| let &(dev, va, shape, format) = t.readers.get(&res)?; | ||
| let w = t.writers.get(&(dev, va)).filter(|w| w.res != res && w.shape == shape && w.format != format)?; | ||
| let v = match view { | ||
| Some(v) => D3D12_SHADER_RESOURCE_VIEW_DESC { Format: if v.Format == DXGI_FORMAT_UNKNOWN { DXGI_FORMAT(format) } else { v.Format }, ..*v }, | ||
| None => whole_view(shape, format), | ||
| }; | ||
| if !w.casts.contains(&v.Format.0) || v.Format.0 == w.format { | ||
| return None; | ||
| } | ||
| (w.res, v) | ||
| }; | ||
| let n = VIEWS.fetch_add(1, Ordering::Relaxed) + 1; | ||
| if n <= 4 || n.is_power_of_two() { | ||
| crate::xlog_info!("D3D12.X: cast lists: a format {} view of the texture {res:#x} is made on the written texture {writer:#x} at its address ({n} so far)", v.Format.0); | ||
| } | ||
| Some((writer, v)) | ||
| } | ||
|
|
||
| /// The view of all of a 2D texture of `shape` in `format` (a null description's). | ||
| fn whole_view(shape: Shape, format: i32) -> D3D12_SHADER_RESOURCE_VIEW_DESC { | ||
| let mut v = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT(format), Shader4ComponentMapping: D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING, ..Default::default() }; | ||
| if shape.depth > 1 { | ||
| v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2DARRAY; | ||
| v.Anonymous.Texture2DArray = D3D12_TEX2D_ARRAY_SRV { MipLevels: shape.mips as u32, ArraySize: shape.depth as u32, ..Default::default() }; | ||
| } else { | ||
| v.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; | ||
| v.Anonymous.Texture2D = D3D12_TEX2D_SRV { MipLevels: shape.mips as u32, ..Default::default() }; | ||
| } | ||
| v | ||
| } | ||
|
|
||
| /// The title's last reference to `res` went (before the object may be recycled: #2436). | ||
| pub(super) fn forget(res: usize) { | ||
| if on() { | ||
| drop_res(res); | ||
| } | ||
| } | ||
|
|
||
| /// `forget` without the switch. | ||
| fn drop_res(res: usize) { | ||
| let mut g = TABLE.lock().unwrap(); | ||
| let Some(t) = g.as_mut() else { return }; | ||
| t.readers.remove(&res); | ||
| if t.made.remove(&res) { | ||
| MADE.fetch_sub(1, Ordering::Relaxed); | ||
| t.writers.retain(|_, w| w.res != res); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn zero_mip_count_means_the_full_chain_for_the_texture_dimension() { | ||
| let mut d = D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: 128, Height: 32, DepthOrArraySize: 4, MipLevels: 0, ..Default::default() }; | ||
| assert_eq!(Shape::of(&d).mips, 8); | ||
| d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; | ||
| d.DepthOrArraySize = 16; | ||
| assert_eq!(Shape::of(&d).mips, 8); | ||
| d.MipLevels = 3; | ||
| assert_eq!(Shape::of(&d).mips, 3); | ||
| } | ||
|
|
||
| #[test] | ||
| fn title_cast_list_is_limited_to_its_bound_resource_address() { | ||
| let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); | ||
| TITLE.with(|t| *t.borrow_mut() = TitleCasts { formats: LIGHT.iter().map(|f| f.0).collect(), va: None }); | ||
| title_address(0x10000); | ||
| let other = take_title_formats(0x20000); | ||
| assert!(other.is_empty()); | ||
| let matching = take_title_formats(0x10000); | ||
| assert_eq!(matching.len(), 2); | ||
| drop(TitleList); | ||
| assert!(TITLE.with(|t| t.borrow().formats.is_empty())); | ||
| } | ||
|
|
||
| /// A sampled R9G9B9E5 texture at a writer's address and shape is viewed on the writer; one | ||
| /// at another address, of another shape, in a format not in the list, or gone, is not. | ||
| #[test] | ||
| fn a_reader_at_a_writers_address_is_viewed_on_it() { | ||
| let _g = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner()); | ||
| let tex = |w: u64, f: DXGI_FORMAT| D3D12_RESOURCE_DESC { Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, Width: w, Height: 720, DepthOrArraySize: 1, MipLevels: 1, Format: f, ..Default::default() }; | ||
| let (dev, va) = (0xD0, 0x12_3a00_0000usize); | ||
| let (writer, reader, other, wide) = (0x7E57_C000_0010usize, 0x7E57_C000_0020usize, 0x7E57_C000_0030usize, 0x7E57_C000_0040usize); | ||
| made(dev, writer, va, &tex(1280, DXGI_FORMAT_R32_UINT), LIGHT.iter().map(|f| f.0).collect()); | ||
| keep_reader(dev, reader, va, &tex(1280, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); | ||
| keep_reader(dev, other, va + 0x40_0000, &tex(1280, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); | ||
| keep_reader(dev, wide, va, &tex(1920, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); | ||
| assert!(is_writer(writer) && !is_writer(reader)); | ||
| let (w, v) = view_on_writer(reader, None).expect("on the writer"); | ||
| assert_eq!((w, v.Format, v.ViewDimension), (writer, DXGI_FORMAT_R9G9B9E5_SHAREDEXP, D3D12_SRV_DIMENSION_TEXTURE2D)); | ||
| assert_eq!(unsafe { v.Anonymous.Texture2D.MipLevels }, 1); | ||
| let r32 = D3D12_SHADER_RESOURCE_VIEW_DESC { Format: DXGI_FORMAT_R16G16_FLOAT, ViewDimension: D3D12_SRV_DIMENSION_TEXTURE2D, ..Default::default() }; | ||
| assert!(view_on_writer(reader, Some(&r32)).is_none(), "not in the cast list"); | ||
| assert!(view_on_writer(other, None).is_none() && view_on_writer(wide, None).is_none()); | ||
| drop_res(reader); | ||
| assert!(view_on_writer(reader, None).is_none(), "a recycled reader is resolved again"); | ||
| drop_res(writer); | ||
| keep_reader(dev, reader, va, &tex(1280, DXGI_FORMAT_R9G9B9E5_SHAREDEXP)); | ||
| assert!(!is_writer(writer) && view_on_writer(reader, None).is_none()); | ||
| drop_res(other); | ||
| drop_res(wide); | ||
| } | ||
|
|
||
| static TEST_LOCK: Mutex<()> = Mutex::new(()); | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Shape::oftreats MipLevels 0 ("full chain") as 1, andwhole_viewbuilds a null-desc view with that many mips. A reader or writer created with MipLevels=0 gets a 1-mip shape, so a rebuilt null-desc SRV has MipLevels=1 and every lower mip the title samples reads out of range. MipLevels=0 on one side and an explicit full count on the other also fail to match, so no redirect happens. The non-redirected path usesr.MipLevelsor u32::MAX.