diff --git a/crates/xcl/src/gpu/desc.rs b/crates/xcl/src/gpu/desc.rs index 157a18c..6814c39 100644 --- a/crates/xcl/src/gpu/desc.rs +++ b/crates/xcl/src/gpu/desc.rs @@ -159,20 +159,57 @@ pub fn component_mapping(dst_sel: [u32; 4], order: [u32; 4]) -> u32 { } /// Resource and SRV descriptions of a T# (None: format without a DXGI equivalent). +pub fn valid_cube_view(t: &Image) -> bool { + if t.ty != ImageType::Cube { + return true; + } + t.depth.checked_sub(t.base_array).is_some_and(|faces| faces != 0 && faces % 6 == 0) +} + +pub fn valid_image_shape(t: &Image) -> bool { + if t.width == 0 || (!matches!(t.ty, ImageType::D1 | ImageType::D1Array) && t.height == 0) { + return false; + } + if matches!(t.ty, ImageType::D1Array | ImageType::D2Array | ImageType::D2MsaaArray) && (t.depth == 0 || t.base_array >= t.depth) { + return false; + } + if t.ty == ImageType::D3 && t.depth == 0 { + return false; + } + if matches!(t.ty, ImageType::D1Array | ImageType::D2Array | ImageType::D2MsaaArray | ImageType::Cube | ImageType::D3) && t.depth > u16::MAX as u32 { + return false; + } + if matches!(t.ty, ImageType::D2Msaa | ImageType::D2MsaaArray) { + return true; + } + let largest = match t.ty { + ImageType::D1 | ImageType::D1Array => t.width, + ImageType::D3 => t.width.max(t.height).max(t.depth), + _ => t.width.max(t.height), + }; + let highest = 31 - largest.leading_zeros(); + t.base_level <= t.last_level && t.last_level <= t.max_mip && t.max_mip <= highest +} + pub fn image_d3d12(t: &Image) -> Option<(D3D12_RESOURCE_DESC, D3D12_SHADER_RESOURCE_VIEW_DESC)> { + if !valid_cube_view(t) || !valid_image_shape(t) { + return None; + } let (format, order) = dxgi_format(t.format)?; - let mips = t.max_mip.max(t.last_level) + 1; + let mips = t.max_mip + 1; let (dim, depth) = match t.ty { - ImageType::D1 | ImageType::D1Array => (D3D12_RESOURCE_DIMENSION_TEXTURE1D, t.depth), + ImageType::D1 => (D3D12_RESOURCE_DIMENSION_TEXTURE1D, 1), + ImageType::D1Array => (D3D12_RESOURCE_DIMENSION_TEXTURE1D, t.depth), ImageType::D3 => (D3D12_RESOURCE_DIMENSION_TEXTURE3D, t.depth), - _ => (D3D12_RESOURCE_DIMENSION_TEXTURE2D, t.depth), + ImageType::D2 | ImageType::D2Msaa => (D3D12_RESOURCE_DIMENSION_TEXTURE2D, 1), + ImageType::D2Array | ImageType::D2MsaaArray | ImageType::Cube => (D3D12_RESOURCE_DIMENSION_TEXTURE2D, t.depth), }; let samples = if matches!(t.ty, ImageType::D2Msaa | ImageType::D2MsaaArray) { 1u32 << t.last_level.min(4) } else { 1 }; let res = D3D12_RESOURCE_DESC { Dimension: dim, Width: t.width as u64, Height: if dim == D3D12_RESOURCE_DIMENSION_TEXTURE1D { 1 } else { t.height }, - DepthOrArraySize: depth.min(u16::MAX as u32) as u16, + DepthOrArraySize: depth as u16, MipLevels: if samples > 1 { 1 } else { mips as u16 }, Format: format, SampleDesc: DXGI_SAMPLE_DESC { Count: samples, Quality: 0 }, @@ -352,6 +389,97 @@ mod tests { assert!(dxgi_format(44).is_none()); // 2_10_10_10: no DXGI equivalent } + #[test] + fn non_array_resources_ignore_tsharp_depth() { + let mut t = image(&tsharp()).unwrap(); + t.depth = 19; + for (ty, depth, want) in [ + (ImageType::D1, 19, 1), + (ImageType::D2, 19, 1), + (ImageType::D2Msaa, 19, 1), + (ImageType::D1Array, 19, 19), + (ImageType::D2Array, 19, 19), + (ImageType::D2MsaaArray, 19, 19), + (ImageType::Cube, 18, 18), + (ImageType::D3, 19, 19), + ] { + t.ty = ty; + t.depth = depth; + assert_eq!(image_d3d12(&t).unwrap().0.DepthOrArraySize, want, "{ty:?}"); + } + } + + #[test] + fn cube_views_require_a_nonempty_whole_number_of_faces() { + let mut t = image(&tsharp()).unwrap(); + t.ty = ImageType::Cube; + t.depth = 12; + for (base, valid, cubes) in [(0, true, 2), (6, true, 1), (12, false, 0), (13, false, 0), (1, false, 0)] { + t.base_array = base; + assert_eq!(valid_cube_view(&t), valid, "base {base}"); + let d = image_d3d12(&t); + assert_eq!(d.is_some(), valid, "base {base}"); + if let Some((_, srv)) = d { + assert_eq!(unsafe { srv.Anonymous.TextureCubeArray.NumCubes }, cubes); + } + } + t.depth = 5; + t.base_array = 0; + assert!(!valid_cube_view(&t)); + assert!(image_d3d12(&t).is_none()); + } + + #[test] + fn image_mips_and_array_views_stay_within_resource_dimensions() { + let mut t = image(&tsharp()).unwrap(); + t.width = 8; + t.height = 4; + t.base_level = 0; + t.last_level = 3; + t.max_mip = 3; + assert!(valid_image_shape(&t)); + assert_eq!(image_d3d12(&t).unwrap().0.MipLevels, 4); + let changes: [fn(&mut Image); 6] = [ + |x: &mut Image| x.width = 0, + |x: &mut Image| x.height = 0, + |x: &mut Image| x.max_mip = 32, + |x: &mut Image| x.max_mip = 4, + |x: &mut Image| x.last_level = 4, + |x: &mut Image| x.base_level = 4, + ]; + for change in changes { + let mut bad = t; + change(&mut bad); + assert!(!valid_image_shape(&bad)); + assert!(image_d3d12(&bad).is_none()); + } + t.ty = ImageType::D2Array; + t.depth = 3; + t.base_array = 2; + assert!(valid_image_shape(&t)); + t.base_array = 3; + assert!(!valid_image_shape(&t)); + t.base_array = 0; + t.depth = 0; + assert!(!valid_image_shape(&t)); + } + + #[test] + fn resource_depth_is_rejected_instead_of_silently_clamped() { + let mut t = image(&tsharp()).unwrap(); + t.depth = u16::MAX as u32 + 1; + for ty in [ImageType::D1Array, ImageType::D2Array, ImageType::D2MsaaArray, ImageType::Cube, ImageType::D3] { + t.ty = ty; + assert!(!valid_image_shape(&t), "{ty:?}"); + assert!(image_d3d12(&t).is_none(), "{ty:?}"); + } + for ty in [ImageType::D1, ImageType::D2, ImageType::D2Msaa] { + t.ty = ty; + assert!(valid_image_shape(&t), "{ty:?}"); + assert_eq!(image_d3d12(&t).unwrap().0.DepthOrArraySize, 1, "{ty:?}"); + } + } + #[test] fn decodes_ssharp() { // clamp/wrap/border, aniso 8, compare LESS, bias -1.5, mag/min linear, mip linear, lod 0..13 diff --git a/crates/xcl/src/gpu/texture.rs b/crates/xcl/src/gpu/texture.rs index a3bff9c..390a100 100644 --- a/crates/xcl/src/gpu/texture.rs +++ b/crates/xcl/src/gpu/texture.rs @@ -2,7 +2,8 @@ //! memory a T# points at: the title writes it already tiled (GFX10 swizzle, mip chain and //! slices as addrlib lays them out – its archives store textures that way) and samples it //! directly. A PC texture has an opaque layout, so every mip level of every slice is detiled -//! (`tiling::Chain`) into a D3D12 subresource and copied in. +//! (`tiling::Chain`) into a D3D12 subresource and copied in. SW_LINEAR resources use +//! the GFX10 256-byte row, level and slice alignment directly. //! //! 2D textures, arrays and cubes, 3D textures (thick and thin modes) and linear ones. What is //! not here yet: MSAA, the console's pipe configuration for the _X modes (`CONSOLE_PIPES`), @@ -33,23 +34,78 @@ pub struct Placement { /// first byte (the T# address rounded down to a block; the rest is the base swizzle) pub start: u64, pub bytes: usize, - pub chain: Chain, - /// array slices (cube faces), or the slices of a 3D texture (`Chain::layers`) + pub chain: Option, + linear: Option, + /// array slices (cube faces), or the storage layers of a tiled 3D texture. pub slices: usize, } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct LinearLevel { offset: usize, width: usize, height: usize, depth: usize, pitch_bytes: usize } + +#[derive(Clone, Debug, PartialEq, Eq)] +struct LinearChain { elem_bytes: usize, slice_bytes: usize, levels: Vec } + +fn align_256(n: usize) -> Option { n.checked_add(255).map(|x| x & !255) } + +fn linear_element(format: u32) -> Option<(usize, u32)> { + tiling::element(format) + .map(|(log2, side)| (1usize << log2, side)) + .or_else(|| (72..=74).contains(&format).then_some((12, 1))) +} + +fn linear_chain(t: &Image) -> Result { + let (elem_bytes, side) = linear_element(t.format).ok_or_else(|| format!("format {} without a linear element layout", t.format))?; + let mut offset = 0usize; + let mut levels = Vec::with_capacity((t.max_mip + 1) as usize); + for mip in 0..=t.max_mip { + let width = (t.width >> mip).max(1).div_ceil(side) as usize; + let height = (t.height >> mip).max(1).div_ceil(side) as usize; + let depth = if t.ty == ImageType::D3 { (t.depth >> mip).max(1) as usize } else { 1 }; + let row_bytes = width.checked_mul(elem_bytes).ok_or("linear texture row size overflow")?; + let pitch_bytes = align_256(row_bytes).ok_or("linear texture row pitch overflow")?; + offset = align_256(offset).ok_or("linear texture mip offset overflow")?; + levels.push(LinearLevel { offset, width, height, depth, pitch_bytes }); + let plane_bytes = pitch_bytes.checked_mul(height).ok_or("linear texture plane size overflow")?; + offset = offset.checked_add(plane_bytes.checked_mul(depth).ok_or("linear texture level size overflow")?).ok_or("linear texture chain size overflow")?; + } + let slice_bytes = align_256(offset).ok_or("linear texture slice size overflow")?; + Ok(LinearChain { elem_bytes, slice_bytes, levels }) +} + pub fn placement(t: &Image, cfg: PipeConfig) -> Result { + if !desc::valid_image_shape(t) { + return Err(format!("invalid {:?} texture dimensions, mip range or array view", t.ty)); + } + if !desc::valid_cube_view(t) { + return Err(format!("cube view {}..{} is not a nonempty whole number of faces", t.base_array, t.depth)); + } if matches!(t.ty, ImageType::D2Msaa | ImageType::D2MsaaArray) { return Err(format!("texture {:?} – not yet (MSAA)", t.ty)); } - let chain = tiling::image_chain(t, cfg).ok_or_else(|| format!("SW_MODE {} / format {} / {:?} without a tiling pattern", t.swizzle_mode, t.format, t.ty))?; + let mut surface = *t; + if matches!(surface.ty, ImageType::D1 | ImageType::D1Array) { + // The T# height field is ignored for 1D resources, just as image_d3d12 ignores it. + surface.height = 1; + } + if t.swizzle_mode == 0 { + let slices = match t.ty { + ImageType::D1Array | ImageType::D2Array | ImageType::Cube => t.depth.max(1) as usize, + _ => 1, + }; + let linear = linear_chain(&surface)?; + let bytes = linear.slice_bytes.checked_mul(slices).ok_or("linear texture size overflow")?; + return Ok(Placement { start: t.address, bytes, chain: None, linear: Some(linear), slices }); + } + let chain = tiling::image_chain(&surface, cfg).ok_or_else(|| format!("SW_MODE {} / format {} without a tiling pattern", t.swizzle_mode, t.format))?; let slices = match t.ty { ImageType::D1Array | ImageType::D2Array | ImageType::Cube => t.depth.max(1) as usize, ImageType::D3 => chain.layers(), _ => 1, }; let start = t.address & !(chain.layout.block_bytes as u64 - 1); - Ok(Placement { start, bytes: chain.slice_bytes * slices, chain, slices }) + let bytes = chain.slice_bytes.checked_mul(slices).ok_or("tiled texture size overflow")?; + Ok(Placement { start, bytes, chain: Some(chain), linear: None, slices }) } /// The subresources of `t` in D3D12 order (mip + slice × mips) from `mem`, its bytes from @@ -59,31 +115,69 @@ pub fn subresources(t: &Image, mem: &[u8], cfg: PipeConfig) -> Result Result<(usize, usize), String> { + if bytes == 0 { + return Err("empty texture memory span".into()); + } + let start = usize::try_from(start).map_err(|_| "texture address does not fit the host address space")?; + let end = start.checked_add(bytes).ok_or("texture memory span overflows the host address space")?; + Ok((start, end)) +} + pub fn uma_bytes(t: &Image, cfg: PipeConfig) -> Result<&'static [u8], String> { let p = placement(t, cfg)?; let u = super::uma::get().ok_or("no UMA")?; - let (a, n) = (p.start as usize, p.bytes); - if !u.contains(a) || !u.contains(a + n - 1) { - return Err(format!("texture {a:#x}+{n:#x} outside UMA")); + let (a, end) = checked_span(p.start, p.bytes)?; + if !u.contains(a) || !u.contains(end - 1) { + return Err(format!("texture {a:#x}+{:#x} outside UMA", p.bytes)); } // SAFETY: inside the UMA reservation, which lives for the whole process - Ok(unsafe { std::slice::from_raw_parts(a as *const u8, n) }) + Ok(unsafe { std::slice::from_raw_parts(a as *const u8, p.bytes) }) } fn err(x: windows::core::Error) -> String { @@ -106,15 +200,63 @@ pub unsafe fn create(dev: &ID3D12Device, queue: &ID3D12CommandQueue, t: &Image, /// The states `create` leaves a texture in. pub const SHADER_READ: D3D12_RESOURCE_STATES = D3D12_RESOURCE_STATES(D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE.0 | D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE.0); +fn validate_subresources(subs: &[Subresource]) -> Result<(), String> { + if subs.is_empty() { + return Err("texture upload without subresources".into()); + } + for (i, s) in subs.iter().enumerate() { + if s.depth == 0 || s.rows == 0 || s.row_bytes == 0 { + return Err(format!("texture subresource {i} has a zero dimension")); + } + let bytes = s + .depth + .checked_mul(s.rows) + .and_then(|n| n.checked_mul(s.row_bytes)) + .ok_or_else(|| format!("texture subresource {i} size overflow"))?; + if s.data.len() < bytes { + return Err(format!("texture subresource {i} has {} B, needs {bytes} B", s.data.len())); + } + } + Ok(()) +} + +fn validate_subresource_count(rd: &D3D12_RESOURCE_DESC, count: usize) -> Result<(), String> { + let arrays = match rd.Dimension { + D3D12_RESOURCE_DIMENSION_TEXTURE1D | D3D12_RESOURCE_DIMENSION_TEXTURE2D => rd.DepthOrArraySize as usize, + D3D12_RESOURCE_DIMENSION_TEXTURE3D => 1, + _ => return Err("texture upload requires a texture resource".into()), + }; + // Every format accepted by desc::image_d3d12 is single-plane. Add the plane count here if + // planar formats are introduced later. + let expected = (rd.MipLevels as usize) + .checked_mul(arrays) + .ok_or("texture resource subresource count overflow")?; + if count != expected { + return Err(format!("texture upload has {count} subresources, resource requires {expected}")); + } + Ok(()) +} + /// Copy `subs` (all subresources, D3D12 order) into `res` on `queue` and wait; `res` is in /// `before` and ends in `after` (e.g. again after the title rewrote the memory). pub unsafe fn upload(dev: &ID3D12Device, queue: &ID3D12CommandQueue, res: &ID3D12Resource, subs: &[Subresource], before: D3D12_RESOURCE_STATES, after: D3D12_RESOURCE_STATES) -> Result<(), String> { + validate_subresources(subs)?; let rd = res.GetDesc(); let n = subs.len(); + validate_subresource_count(&rd, n)?; let mut fps = vec![D3D12_PLACED_SUBRESOURCE_FOOTPRINT::default(); n]; let mut rows = vec![0u32; n]; + let mut row_bytes = vec![0u64; n]; let mut total = 0u64; - dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), None, Some(&mut total)); + dev.GetCopyableFootprints(&rd, 0, n as u32, 0, Some(fps.as_mut_ptr()), Some(rows.as_mut_ptr()), Some(row_bytes.as_mut_ptr()), Some(&mut total)); + for (i, ((s, fp), (&nrows, &nbytes))) in subs.iter().zip(&fps).zip(rows.iter().zip(&row_bytes)).enumerate() { + if s.rows != nrows as usize || s.depth != fp.Footprint.Depth as usize || s.row_bytes != nbytes as usize { + return Err(format!( + "texture subresource {i} is {}x{}x{} B, resource expects {}x{}x{} B", + s.row_bytes, s.rows, s.depth, nbytes, nrows, fp.Footprint.Depth + )); + } + } let up = buffer(dev, total)?; let mut p = std::ptr::null_mut(); up.Map(0, None, Some(&mut p)).map_err(err)?; @@ -223,10 +365,49 @@ mod tests { } } + #[test] + fn texture_memory_spans_reject_empty_truncated_and_wrapping_addresses() { + assert_eq!(checked_span(0x1000, 0x200).unwrap(), (0x1000, 0x1200)); + assert!(checked_span(0x1000, 0).unwrap_err().contains("empty")); + assert!(checked_span(u64::MAX, 2).unwrap_err().contains("address")); + assert!(checked_span((usize::MAX - 1) as u64, 2).unwrap_err().contains("overflows")); + assert_eq!(checked_span((usize::MAX - 1) as u64, 1).unwrap(), (usize::MAX - 1, usize::MAX)); + } + + #[test] + fn upload_subresources_are_validated_before_unsafe_copying() { + assert!(validate_subresources(&[]).is_err()); + let zero = Subresource { depth: 1, rows: 0, row_bytes: 4, data: vec![] }; + assert!(validate_subresources(&[zero]).unwrap_err().contains("zero dimension")); + let short = Subresource { depth: 2, rows: 3, row_bytes: 4, data: vec![0; 23] }; + assert_eq!(validate_subresources(&[short]).unwrap_err(), "texture subresource 0 has 23 B, needs 24 B"); + let overflow = Subresource { depth: usize::MAX, rows: 2, row_bytes: 1, data: vec![] }; + assert!(validate_subresources(&[overflow]).unwrap_err().contains("size overflow")); + let complete = Subresource { depth: 2, rows: 3, row_bytes: 4, data: vec![0; 25] }; + assert!(validate_subresources(&[complete]).is_ok()); + } + + #[test] + fn upload_requires_every_resource_subresource_exactly_once() { + let mut rd = D3D12_RESOURCE_DESC { + Dimension: D3D12_RESOURCE_DIMENSION_TEXTURE2D, + DepthOrArraySize: 3, + MipLevels: 4, + ..Default::default() + }; + assert!(validate_subresource_count(&rd, 12).is_ok()); + assert_eq!(validate_subresource_count(&rd, 11).unwrap_err(), "texture upload has 11 subresources, resource requires 12"); + assert_eq!(validate_subresource_count(&rd, 13).unwrap_err(), "texture upload has 13 subresources, resource requires 12"); + rd.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE3D; + rd.DepthOrArraySize = 9; + assert!(validate_subresource_count(&rd, 4).is_ok()); + rd.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + assert!(validate_subresource_count(&rd, 4).unwrap_err().contains("requires a texture")); + } + /// Random linear subresources for `t`, and the console memory they are, tiled. fn console_texture(t: &Image) -> (Vec, Vec) { let p = placement(t, CONSOLE_PIPES).unwrap(); - let e = 1usize << p.chain.layout.elem_log2; let mut mem = vec![0u8; p.bytes]; let mut subs = Vec::new(); let mut n = 0x1234_5678u32; @@ -240,20 +421,40 @@ mod tests { }) .collect() }; + if let Some(linear) = &p.linear { + for s in 0..p.slices { + for l in &linear.levels { + let row_bytes = l.width * linear.elem_bytes; + let data = random(row_bytes * l.height * l.depth); + let plane_bytes = l.pitch_bytes * l.height; + for z in 0..l.depth { + for y in 0..l.height { + let src = (z * l.height + y) * row_bytes; + let dst = s * linear.slice_bytes + l.offset + z * plane_bytes + y * l.pitch_bytes; + mem[dst..dst + row_bytes].copy_from_slice(&data[src..src + row_bytes]); + } + } + subs.push(Subresource { rows: l.height, row_bytes, depth: l.depth, data }); + } + } + return (subs, mem); + } + let chain = p.chain.as_ref().unwrap(); + let e = 1usize << chain.layout.elem_log2; if matches!(t.ty, ImageType::D3) { - for (i, l) in p.chain.levels.iter().enumerate() { + for (i, l) in chain.levels.iter().enumerate() { let data = random(l.width * l.height * l.depth * e); - p.chain.tile_volume(&mut mem, i, &data); + chain.tile_volume(&mut mem, i, &data); subs.push(Subresource { rows: l.height, row_bytes: l.width * e, depth: l.depth, data }); } return (subs, mem); } for s in 0..p.slices { - let slice = &mut mem[s * p.chain.slice_bytes..(s + 1) * p.chain.slice_bytes]; - for (i, l) in p.chain.levels.iter().enumerate() { + let slice = &mut mem[s * chain.slice_bytes..(s + 1) * chain.slice_bytes]; + for (i, l) in chain.levels.iter().enumerate() { let data = random(l.width * l.height * e); - p.chain.tile_level(slice, i, &data); - subs.push(Subresource { rows: l.height, row_bytes: l.width * e, depth: 1, data }); + chain.tile_level(slice, i, &data); + subs.push(Subresource { depth: 1, rows: l.height, row_bytes: l.width * e, data }); } } (subs, mem) @@ -270,6 +471,232 @@ mod tests { assert!(subresources(&t, &mem[..mem.len() - 1], CONSOLE_PIPES).is_err()); } + #[test] + fn linear_mipped_array_uses_256_byte_rows_levels_and_slices() { + let rgba8 = desc::gfx10_format(DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let t = image(rgba8, ImageType::D2Array, 65, 3, 2, 3, 0, 0x20_0000); + let p = placement(&t, CONSOLE_PIPES).unwrap(); + let linear = p.linear.as_ref().unwrap(); + assert!(p.chain.is_none()); + assert_eq!(linear.levels, vec![ + LinearLevel { offset: 0, width: 65, height: 3, depth: 1, pitch_bytes: 512 }, + LinearLevel { offset: 1536, width: 32, height: 1, depth: 1, pitch_bytes: 256 }, + LinearLevel { offset: 1792, width: 16, height: 1, depth: 1, pitch_bytes: 256 }, + ]); + assert_eq!((linear.slice_bytes, p.bytes), (2048, 4096)); + let mut mem = vec![0xEE; p.bytes]; + let mut want = Vec::new(); + for slice in 0..p.slices { + for (mip, level) in linear.levels.iter().enumerate() { + let row_bytes = level.width * linear.elem_bytes; + let mut data = Vec::new(); + for y in 0..level.height { + let value = (slice * 32 + mip * 8 + y) as u8; + let start = slice * linear.slice_bytes + level.offset + y * level.pitch_bytes; + mem[start..start + row_bytes].fill(value); + data.extend(std::iter::repeat(value).take(row_bytes)); + } + want.push(Subresource { depth: 1, rows: level.height, row_bytes, data }); + } + } + assert_eq!(subresources(&t, &mem, CONSOLE_PIPES).unwrap(), want); + assert!(subresources(&t, &mem[..mem.len() - 1], CONSOLE_PIPES).is_err()); + } + + #[test] + fn linear_block_compressed_dimensions_are_in_blocks() { + let bc7 = desc::gfx10_format(DXGI_FORMAT_BC7_UNORM).unwrap(); + let t = image(bc7, ImageType::D2, 7, 5, 1, 3, 0, 0x30_0000); + let p = placement(&t, CONSOLE_PIPES).unwrap(); + let linear = p.linear.as_ref().unwrap(); + assert_eq!(linear.elem_bytes, 16); + assert_eq!(linear.levels.iter().map(|l| (l.width, l.height, l.depth, l.pitch_bytes)).collect::>(), vec![(2, 2, 1, 256), (1, 1, 1, 256), (1, 1, 1, 256)]); + assert_eq!(linear.slice_bytes, 1024); + } + + #[test] + fn linear_96_bit_texture_extracts_and_uploads_twelve_byte_elements() { + let rgb32 = desc::gfx10_format(DXGI_FORMAT_R32G32B32_FLOAT).unwrap(); + let t = image(rgb32, ImageType::D2, 21, 2, 1, 2, 0, 0x34_0000); + let p = placement(&t, CONSOLE_PIPES).unwrap(); + let linear = p.linear.as_ref().unwrap(); + assert_eq!(linear.elem_bytes, 12); + assert_eq!(linear.levels, vec![ + LinearLevel { offset: 0, width: 21, height: 2, depth: 1, pitch_bytes: 256 }, + LinearLevel { offset: 512, width: 10, height: 1, depth: 1, pitch_bytes: 256 }, + ]); + assert_eq!(p.bytes, 768); + let mut mem = vec![0xEE; p.bytes]; + let mut want = Vec::new(); + for (mip, level) in linear.levels.iter().enumerate() { + let row_bytes = level.width * 12; + let mut data = Vec::new(); + for y in 0..level.height { + let value = (mip * 16 + y) as u8; + let start = level.offset + y * level.pitch_bytes; + mem[start..start + row_bytes].fill(value); + data.extend(std::iter::repeat(value).take(row_bytes)); + } + want.push(Subresource { depth: 1, rows: level.height, row_bytes, data }); + } + assert_eq!(subresources(&t, &mem, CONSOLE_PIPES).unwrap(), want); + let Some((dev, queue)) = device() else { return }; + unsafe { + let res = create(&dev, &queue, &t, &mem, CONSOLE_PIPES).unwrap(); + assert_eq!(read_back(&dev, &queue, &res, &want), want); + } + } + + #[test] + fn one_dimensional_arrays_ignore_tsharp_height_for_linear_and_tiled_layouts() { + let rgba8 = desc::gfx10_format(DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let gpu = device(); + for mode in [0, 1] { + let t = image(rgba8, ImageType::D1Array, 33, 37, 2, 3, mode, 0x36_0000); + let mut normalized = t; + normalized.height = 1; + assert_eq!(placement(&t, CONSOLE_PIPES).unwrap().bytes, placement(&normalized, CONSOLE_PIPES).unwrap().bytes); + let (want, mem) = if mode == 1 { + console_texture(&t) + } else { + let p = placement(&t, CONSOLE_PIPES).unwrap(); + let linear = p.linear.as_ref().unwrap(); + assert!(linear.levels.iter().all(|l| l.height == 1)); + let mut mem = vec![0xEE; p.bytes]; + let mut want = Vec::new(); + for slice in 0..p.slices { + for (mip, level) in linear.levels.iter().enumerate() { + let row_bytes = level.width * linear.elem_bytes; + let value = (slice * 16 + mip) as u8; + let start = slice * linear.slice_bytes + level.offset; + mem[start..start + row_bytes].fill(value); + want.push(Subresource { depth: 1, rows: 1, row_bytes, data: vec![value; row_bytes] }); + } + } + (want, mem) + }; + assert!(want.iter().all(|s| s.rows == 1)); + assert_eq!(subresources(&t, &mem, CONSOLE_PIPES).unwrap(), want); + if let Some((dev, queue)) = &gpu { + unsafe { + let res = create(dev, queue, &t, &mem, CONSOLE_PIPES).unwrap(); + assert_eq!(read_back(dev, queue, &res, &want), want); + } + } + } + } + + #[test] + fn non_array_2d_ignores_tsharp_depth_for_linear_and_tiled_uploads() { + let rgba8 = desc::gfx10_format(DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let gpu = device(); + for mode in [0, 1] { + let t = image(rgba8, ImageType::D2, 17, 3, 9, 2, mode, 0x37_0000); + assert_eq!(desc::image_d3d12(&t).unwrap().0.DepthOrArraySize, 1); + let (want, mem) = if mode == 1 { + console_texture(&t) + } else { + let p = placement(&t, CONSOLE_PIPES).unwrap(); + assert_eq!(p.slices, 1); + let linear = p.linear.as_ref().unwrap(); + let mut mem = vec![0xEE; p.bytes]; + let mut want = Vec::new(); + for (mip, level) in linear.levels.iter().enumerate() { + let row_bytes = level.width * linear.elem_bytes; + let mut data = Vec::new(); + for y in 0..level.height { + let value = (mip * 8 + y) as u8; + let start = level.offset + y * level.pitch_bytes; + mem[start..start + row_bytes].fill(value); + data.extend(std::iter::repeat(value).take(row_bytes)); + } + want.push(Subresource { depth: 1, rows: level.height, row_bytes, data }); + } + (want, mem) + }; + assert_eq!(subresources(&t, &mem, CONSOLE_PIPES).unwrap(), want); + if let Some((dev, queue)) = &gpu { + unsafe { + let res = create(dev, queue, &t, &mem, CONSOLE_PIPES).unwrap(); + assert_eq!(read_back(dev, queue, &res, &want), want); + } + } + } + } + + #[test] + fn invalid_cube_face_ranges_are_rejected_before_placement() { + let rgba8 = desc::gfx10_format(DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let mut t = image(rgba8, ImageType::Cube, 16, 16, 5, 1, 1, 0x37_8000); + assert!(placement(&t, CONSOLE_PIPES).err().unwrap().contains("whole number of faces")); + t.depth = 12; + t.base_array = 12; + assert!(placement(&t, CONSOLE_PIPES).err().unwrap().contains("whole number of faces")); + t.base_array = 6; + assert!(placement(&t, CONSOLE_PIPES).is_ok()); + } + + #[test] + fn invalid_mip_counts_are_rejected_before_layout_shifts() { + let rgba8 = desc::gfx10_format(DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let mut t = image(rgba8, ImageType::D2, 8, 4, 1, 4, 0, 0x37_c000); + assert!(placement(&t, CONSOLE_PIPES).is_ok()); + t.max_mip = 32; + t.last_level = 32; + assert!(placement(&t, CONSOLE_PIPES).err().unwrap().contains("invalid")); + t.max_mip = 4; + t.last_level = 4; + assert!(placement(&t, CONSOLE_PIPES).is_err()); + t.max_mip = 3; + t.last_level = 2; + t.base_level = 3; + assert!(placement(&t, CONSOLE_PIPES).is_err()); + } + + #[test] + fn oversized_array_depth_is_rejected_before_placement_allocation() { + let rgba8 = desc::gfx10_format(DXGI_FORMAT_R8G8B8A8_UNORM).unwrap(); + let t = image(rgba8, ImageType::D2Array, 1, 1, u16::MAX as u32 + 1, 1, 1, 0x37_d000); + assert!(placement(&t, CONSOLE_PIPES).err().unwrap().contains("invalid")); + assert!(desc::image_d3d12(&t).is_none()); + } + + #[test] + fn linear_3d_mips_extract_and_upload_every_depth_plane() { + let r8 = desc::gfx10_format(DXGI_FORMAT_R8_UNORM).unwrap(); + let t = image(r8, ImageType::D3, 5, 3, 4, 3, 0, 0x38_0000); + let p = placement(&t, CONSOLE_PIPES).unwrap(); + let linear = p.linear.as_ref().unwrap(); + assert_eq!(linear.levels, vec![ + LinearLevel { offset: 0, width: 5, height: 3, depth: 4, pitch_bytes: 256 }, + LinearLevel { offset: 3072, width: 2, height: 1, depth: 2, pitch_bytes: 256 }, + LinearLevel { offset: 3584, width: 1, height: 1, depth: 1, pitch_bytes: 256 }, + ]); + assert_eq!(p.bytes, 3840); + let mut mem = vec![0xEE; p.bytes]; + let mut want = Vec::new(); + for (mip, level) in linear.levels.iter().enumerate() { + let row_bytes = level.width * linear.elem_bytes; + let plane_bytes = level.pitch_bytes * level.height; + let mut data = Vec::new(); + for z in 0..level.depth { + for y in 0..level.height { + let value = (mip * 40 + z * 8 + y) as u8; + let start = level.offset + z * plane_bytes + y * level.pitch_bytes; + mem[start..start + row_bytes].fill(value); + data.extend(std::iter::repeat(value).take(row_bytes)); + } + } + want.push(Subresource { depth: level.depth, rows: level.height, row_bytes, data }); + } + assert_eq!(subresources(&t, &mem, CONSOLE_PIPES).unwrap(), want); + let Some((dev, queue)) = device() else { return }; + unsafe { + let res = create(&dev, &queue, &t, &mem, CONSOLE_PIPES).unwrap(); + assert_eq!(read_back(&dev, &queue, &res, &want), want); + } + } + fn device() -> Option<(ID3D12Device, ID3D12CommandQueue)> { unsafe { let mut dev: Option = None; @@ -454,11 +881,12 @@ mod tests { let Some(err) = mip_error(&subs[k - 1], &subs[k], ch, cb) else { continue }; bad = bad.max(err); // control: a tail level read from the tail block's corner - let l = p.chain.levels[k]; + let chain = p.chain.as_ref().unwrap(); + let l = chain.levels[k]; if l.origin != (0, 0) && l.width >= 2 && l.height >= 2 { - let mut wrong = p.chain.clone(); + let mut wrong = chain.clone(); wrong.levels[k].origin = (0, 0); - let ws = Subresource { rows: l.height, row_bytes: subs[k].row_bytes, depth: 1, data: wrong.detile_level(&mem, k) }; + let ws = Subresource { depth: 1, rows: l.height, row_bytes: subs[k].row_bytes, data: wrong.detile_level(&mem, k) }; tail_levels += 1; tail_err += err; wrong_err += mip_error(&subs[k - 1], &ws, ch, cb).unwrap(); diff --git a/crates/xcl/src/hle/kernelx.rs b/crates/xcl/src/hle/kernelx.rs index 62dedd6..4f1e1fe 100644 --- a/crates/xcl/src/hle/kernelx.rs +++ b/crates/xcl/src/hle/kernelx.rs @@ -348,8 +348,8 @@ pub unsafe extern "system" fn ToolingMemoryStatus(buf: *mut u32) -> BOOL { /// Title physical pages (64 KiB) emulated in the unified memory region: an allocation is one /// contiguous UMA block, page numbers = offset / 64 KiB in UMA. Mapping consecutive pages -/// returns their UMA address (GPU-visible, no copy); mapping at an address of the title's -/// choice or scattered pages cannot alias memory this way – logged and refused. +/// returns their UMA address (GPU-visible, no copy); choosing that same address is supported. +/// A different address or scattered pages cannot alias memory this way – logged and refused. const PHYS_PAGE: usize = 0x1_0000; /// first page number → (pages in the block, pages still allocated) @@ -409,10 +409,25 @@ pub unsafe extern "system" fn MapTitlePhysicalPages(va: *mut c_void, n: usize, _ return std::ptr::null_mut(); } let first = *arr; - let consecutive = (1..n).all(|i| *arr.add(i) == first + i); - let at = (u.base() + first * PHYS_PAGE) as *mut c_void; - if consecutive && (va.is_null() || va == at) { - return at; + let consecutive = (1..n).all(|i| first.checked_add(i).is_some_and(|page| *arr.add(i) == page)); + let at = consecutive.then(|| { + let end_page = first.checked_add(n)?; + let blocks = PHYS_BLOCKS.lock().ok()?; + let (&block_first, &(block_pages, live_pages)) = blocks.range(..=first).next_back()?; + let block_end = block_first.checked_add(block_pages)?; + if live_pages == 0 || end_page > block_end { + return None; + } + let offset = first.checked_mul(PHYS_PAGE)?; + let bytes = n.checked_mul(PHYS_PAGE)?; + let address = u.base().checked_add(offset)?; + let end = address.checked_add(bytes)?; + (end <= u.base().checked_add(u.size())?).then_some(address as *mut c_void) + }).flatten(); + if let Some(at) = at { + if va.is_null() || va == at { + return at; + } } static WARNED: AtomicU32 = AtomicU32::new(0); if WARNED.fetch_add(1, Ordering::Relaxed) < 5 { @@ -898,6 +913,12 @@ mod tests { // scattered pages: refused let mut scattered = [pages[2], pages[0]]; assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, scattered.as_mut_ptr()).is_null()); + // Page numbers must refer to one registered allocation; arithmetic is checked before + // constructing an address inside the reserved UMA region. + let mut outside = [u.size() / PHYS_PAGE]; + assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 1, 0, 4, outside.as_mut_ptr()).is_null()); + let mut wrapping = [usize::MAX]; + assert!(MapTitlePhysicalPages(std::ptr::null_mut(), 2, 0, 4, wrapping.as_mut_ptr()).is_null()); let used = u.used(); assert_eq!(FreeTitlePhysicalPages(std::ptr::null_mut(), 3, pages.as_mut_ptr()), 1); assert_eq!(u.used(), used - 3 * PHYS_PAGE);