mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-30 04:19:40 +00:00
Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9acd450445 | ||
|
|
9ab94bdd68 | ||
|
|
e99a0af3f3 | ||
|
|
d672271c6a | ||
|
|
aa41d275c6 | ||
|
|
0d1fcc3460 | ||
|
|
6ecd70bac5 | ||
|
|
83cdd49fab | ||
|
|
e667dfe435 | ||
|
|
f06dc97414 | ||
|
|
fc74ea53f8 | ||
|
|
7f689cb542 | ||
|
|
9bc65d7010 | ||
|
|
a35dc6e3a8 |
No files matched your search
@@ -31,6 +31,29 @@ remains unsupported.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- **`gfx10-translate`: compares, execution masks and branches** (#717). A shader with any of them is translated in structured mode.
|
||||
- Each lane's `exec`, `vcc` and every mask kept in SGPRs is a per-lane `bool`; `scc` is a wave-uniform `bool`.
|
||||
- Vector instructions act only where `exec` is set. Image instructions are computed for the whole quad, since their derivatives need it, and only their register writes are selected.
|
||||
- The program is split into blocks at branch targets and after branches, and a loop dispatches on the current block. Branch conditions are uniform: `scc`, or `WaveActiveAnyTrue` of a mask.
|
||||
- Translated:
|
||||
- `v_cmp`/`v_cmpx` on f32, u32 and i32, including `class`;
|
||||
- `v_cndmask`, `s_cmp`, `s_cselect`;
|
||||
- the scalar mask operations and their `saveexec` forms;
|
||||
- `s_wqm` (lanes of a set quad, via `QuadReadAcross*`);
|
||||
- `s_branch` and the `s_cbranch` forms on scc, vcc and exec.
|
||||
- The final export's `vm` bit discards lanes no longer in `exec`.
|
||||
- The decoder now reads past an `s_endpgm` that a branch jumps over (an early exit).
|
||||
- Tests: `divergent_if_runs_under_exec`, `cmpx_removes_lanes_before_the_final_export`, `early_exit_keeps_the_code_after_it` and `samples_run_for_the_whole_quad`, all from llvm-mc encodings.
|
||||
- Locally, 1,535 of the target build's 4,331 shaders translate, up from 900. The 632 that use structured mode all compile with dxc (`ps_6_0`/`vs_6_0`); compiling is not running them.
|
||||
- Blockers now: register-offset descriptor loads, `ds_swizzle_b32`, buffer stores, and vertex fetch through a constant buffer.
|
||||
- **`gfx10-translate`: `image_load` and `image_gather4_lz`** (#718). Loads at integer coordinates, mip 0, from 2D, 3D and 2D-array textures, each declared by the dimension it is read with. A texture read with two dimensions, and 16-bit addresses or data, are refused. Gathers of one component (`GatherRed` to `GatherAlpha`) on 2D textures. The test `image_loads_and_gathers` uses llvm-mc encodings. Locally 900 of the target build's 4,331 shaders translate; the shaders unblocked here next stop mostly on compares (#717).
|
||||
- **`gfx10-translate`: descriptor tables of every root parameter** (#715).
|
||||
- **Tables:** s8+k holds root parameter k's table pointer (s8 for 0, s9 for 1, ...), read zero-extended through `s_mov_b32`. Its constant buffers and textures are declared in register space 100+k, as `cb{k}_{entry}` and `tex{k}_{entry}`. The layout file gains `USE CB <k> <entry>`. Root parameter 0 keeps the prototype's names and lines.
|
||||
- **Computed offsets:** a constant-buffer load with a register offset is an indexed read. A 4-dword descriptor loaded with a computed index keeps the unknown-origin treatment; an 8-dword one (a texture array) stays refused.
|
||||
- **Two more rules** now reachable: `v_fmac_f32_e64` and `s_mul_hi_u32`.
|
||||
- **Measured locally:** 894 of the target build's 4,331 shaders translate (811 before); all 214 prototype pipeline pairs are still identical.
|
||||
- **Test:** `root_parameter_tables_and_register_offsets`.
|
||||
- **`gfx10-translate`: VOP3 modifiers on 32-bit float instructions** (#719). Input `abs` is applied before `neg` on each source, and `omod` (×2, ×4, ÷2) then `clamp` (`saturate`) on the result. `clamp` or `abs` on integer instructions and `op_sel` stay refused. The test `vop3_float_modifiers` uses llvm-mc encodings. Locally 811 of the target build's 4,331 shaders translate; the shaders that stopped on `clamp` now mostly stop on descriptor tables (#715).
|
||||
- **`gfx10-translate`: integer, conversion and lane instructions** (#716).
|
||||
- **Scalar:** `s_add_i32`, `s_sub_i32`, `s_min_i32`, `s_max_i32`.
|
||||
- **Conversions:** `v_cvt_u32_f32`, with the ISA's clamping of NaN, negative and too-large values; `v_cvt_f32_ubyte0`–`3`; `v_rcp_iflag_f32`.
|
||||
@@ -122,6 +145,12 @@ remains unsupported.
|
||||
- `d3d12_xs.dll!D3D12ConfigureVirtualMemoryX` now decodes the Xbox virtual-memory configuration (`D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION`) alongside the existing `BXVM` contract. Layout and behaviour follow the authorized GDK documentation of the function and structure: no flags, a GPU page-table size in 4 MB units clamped to 33, a frame-buffer preserve size (0, -1 for the legacy size, or bytes clamped to 64 MiB), and two output addresses, the minimum always 2 GiB and the maximum 159.375 GiB at the default 5 pages. The call fails with `E_FAIL` once a D3D12 device exists. Call-site observation of a project-authorized target build agrees with the documented layout. Inferred, and marked as such: the maximum for other page-table sizes scales linearly (`max_estimated=1` in the log), and a page-table size of 0, an unreadable configuration or unwritable outputs fail with `E_INVALIDARG`. The host sizes no GPU page tables and keeps no cross-process frame buffer, so the path records both (`vmem_config_recorded`, `applied=0 recorded_only=1`), leaves the `BXVM` record and cached backing heap untouched, and still emits `BX_STUB_LOG`. `tests/conformance/test_d3d12_vmem_xbox/` checks the documented outputs, clamps and post-device `E_FAIL`, the refused cases, and that a cached `BXVM` backing heap survives.
|
||||
|
||||
### Fixed
|
||||
- **Two causes of the target build's menu crashes are fixed** (#722). Before, most runs ended with exit status 5 within a few minutes.
|
||||
- **`d3d12_xs.dll`: `CopyTextureRegionX` is implemented**, as `CopyTextureRegion`; its `D3D12XBOX_COPY_FLAGS` steer console compression metadata the host does not have. As a stub it left a copy undone, the title's frame never completed, and its hang watchdog ended the process 30 s later (every watchdog crash followed its first call by 32–41 s). Test: `test_d3d12_copy_texture_region_x`, a box copy and a whole-texture copy through slot 85, read back. On the previous shim no pixel is copied.
|
||||
- **`bx_runtime_veh.dll`: a title fault on a page being remapped is retried.** xmem replaces part of a mapped run by unmapping the whole view and mapping the rest back, so other pages of the run briefly disappear; on the console that update is atomic. A fault in the title's own code on an inaccessible address now waits for any remap in progress (the remap guard) and retries if the address has become accessible. Each retry is logged (`remap_window_retry`). Genuine faults still reach the title. Test: `test_veh_remap_window`, four unguarded readers of one page while two pages of its run are remapped for four seconds. It crashes 4 of 4 times without the retry. A rarer silent case, a read that sees other data without faulting, remains (#729).
|
||||
- **Measured** on the target build (Apple Silicon, offline, scripted input, 210 s runs):
|
||||
- with `CopyTextureRegionX`, 1 of 9 runs still hit the watchdog (before, every crash did); that hang has another cause, still open in #722;
|
||||
- with the retry, a fault at the earlier recurring site was retried and the run completed.
|
||||
- **`XCRDAPI.dll`: physical-page destinations are mapped when the request runs, partial reads of compressed blocks are delivered, and BCPack requests can be decoded.**
|
||||
- **Page array timing:** a title can fill the `DestinationPageArray` of a `DestinationIsPhysicalPages` request after `EnqueueRequest` returns. #707 read the array at enqueue, so such requests failed (in the target build, about 290 per run named page 0). The array is now read, and its pages mapped, when the request runs; they are unmapped once it is fulfilled.
|
||||
- **Partial compressed reads:** a title may ask for only the first `DestinationSize` bytes of a zlib block (in the target build, 8 to 128 KiB blocks read 4 to 16 KiB at a time; 16 failures per run). The whole stream is decoded, its Adler-32 checked, and its first `DestinationSize` bytes delivered; a stream shorter than the destination is still an error. Logged as `dstorage_zlib_partial`.
|
||||
|
||||
@@ -312,14 +312,24 @@ fn count_of(name: &str) -> u8 {
|
||||
if is_64(name) { 2 } else { 1 }
|
||||
}
|
||||
|
||||
/// Decodes a shader until (and including) `s_endpgm`.
|
||||
/// Decodes a shader until (and including) its last `s_endpgm`: an `s_endpgm` ends the program
|
||||
/// unless a branch decoded so far goes past it (an early exit with more code after it).
|
||||
pub fn decode(words: &[u32]) -> Result<Vec<Inst>, DecodeError> {
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0;
|
||||
let mut furthest = 0usize;
|
||||
while at < words.len() {
|
||||
let inst = decode_one(words, at)?;
|
||||
at += inst.words.len();
|
||||
let end = inst.name == "s_endpgm";
|
||||
if inst.format == Format::Sopp
|
||||
&& (inst.name == "s_branch" || inst.name.starts_with("s_cbranch_"))
|
||||
{
|
||||
if let Some(Operand::Int(simm)) = inst.ops.first() {
|
||||
let target = at as i64 + i64::from(*simm);
|
||||
furthest = furthest.max(usize::try_from(target).unwrap_or(0));
|
||||
}
|
||||
}
|
||||
let end = inst.name == "s_endpgm" && furthest < at;
|
||||
out.push(inst);
|
||||
if end {
|
||||
return Ok(out);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -51,21 +51,10 @@ fn refusal(stage: Stage, hex: &str) -> Option<String> {
|
||||
// Encodings from llvm-mc (gfx1030); each program ends in s_endpgm (bf810000).
|
||||
#[test]
|
||||
fn refuses_what_it_does_not_model() {
|
||||
// v_cmp_lt_f32_e32 vcc_lo, v1, v2: no rule for compares yet.
|
||||
// v_add_nc_u32_e64 v0, v1, v2 clamp: saturating integer arithmetic is refused, not dropped
|
||||
// (float clamp and omod are translated; see vop3_float_modifiers).
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "7c020501 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("instruction 'v_cmp_lt_f32_e32")
|
||||
);
|
||||
// v_add_f32_e64 v0, v1, v2 clamp: output modifiers are refused, not dropped.
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "d5038000 02020501 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("modifier in")
|
||||
);
|
||||
// v_mul_f32_e64 v0, v1, v2 mul:2
|
||||
assert!(
|
||||
refusal(Stage::Pixel, "d5080000 0a020501 bf810000")
|
||||
refusal(Stage::Pixel, "d5258000 02020501 bf810000")
|
||||
.unwrap()
|
||||
.starts_with("modifier in")
|
||||
);
|
||||
@@ -186,6 +175,47 @@ fn wave32_mask_bookkeeping_and_half_compressed_exports() {
|
||||
);
|
||||
}
|
||||
|
||||
/// VOP3 modifiers (#719): input abs then neg on float sources, omod then clamp on a float
|
||||
/// result; clamp on an integer instruction (saturating arithmetic) stays refused. Encodings from
|
||||
/// llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn vop3_float_modifiers() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
let hlsl = |inst: &str| {
|
||||
let ps = decode(&words(&format!("{inst} f8000801 00000000 bf810000"))).unwrap();
|
||||
translate_pair(&vs, &ps).map(|t| t.ps_hlsl)
|
||||
};
|
||||
|
||||
// v_max_f32_e64 v0, v1, v2 clamp
|
||||
let t = hlsl("d5108000 02020501").unwrap();
|
||||
assert!(
|
||||
t.contains(" v0 = asuint(saturate(max(asfloat(v1), asfloat(v2))));\n"),
|
||||
"{t}"
|
||||
);
|
||||
// v_mul_f32_e64 v0, v1, v2 mul:2
|
||||
let t = hlsl("d5080000 0a020501").unwrap();
|
||||
assert!(
|
||||
t.contains(" v0 = asuint((asfloat(v1) * asfloat(v2)) * 2.0f);\n"),
|
||||
"{t}"
|
||||
);
|
||||
// v_add_f32_e64 v0, |v1|, -|v2|: abs first, then neg.
|
||||
let t = hlsl("d5030300 42020501").unwrap();
|
||||
assert!(t.contains("asfloat((asuint(abs(asfloat(v1)))))"), "{t}");
|
||||
assert!(
|
||||
t.contains("asfloat((asuint(-asfloat((asuint(abs(asfloat(v2))))))))"),
|
||||
"{t}"
|
||||
);
|
||||
// v_mul_legacy_f32_e64 v0, |v1|, |v2|
|
||||
let t = hlsl("d5070300 02020501").unwrap();
|
||||
assert!(
|
||||
t.contains("abs(asfloat(v1))") && t.contains("abs(asfloat(v2))"),
|
||||
"{t}"
|
||||
);
|
||||
// v_add_nc_u32_e64 v0, v1, v2 clamp: integer saturation is a different operation.
|
||||
let err = hlsl("d5258000 02020501").unwrap_err();
|
||||
assert!(err.0.starts_with("modifier in"), "{err}");
|
||||
}
|
||||
|
||||
/// Integer, conversion and lane instructions (#716). Encodings from llvm-mc (gfx1030); each
|
||||
/// expected line follows the instruction's ISA definition.
|
||||
#[test]
|
||||
@@ -228,3 +258,161 @@ fn integer_conversion_and_lane_instructions() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Descriptor tables of further root parameters (#715): s9 is root parameter 1's table pointer,
|
||||
/// read through `s_mov_b32 s10, s9; s_mov_b32 s11, 0`. Its entry 2 (byte 0x40, 32-byte entries)
|
||||
/// is a constant buffer in register space 101; a constant-buffer load with a register offset is
|
||||
/// an indexed read. Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn root_parameter_tables_and_register_offsets() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
// s_mov_b32 s10, s9; s_mov_b32 s11, 0; s_load_dwordx4 s[0:3], s[10:11], 0x40;
|
||||
// s_buffer_load_dword s4, s[0:3], 0x8; s_buffer_load_dword s5, s[0:3], s6;
|
||||
// v_mov_b32_e32 v0, s4; v_mov_b32_e32 v1, s5; exp mrt0, v0, v1, off, off done; s_endpgm
|
||||
let ps = decode(&words(
|
||||
"be8a0309 be8b0380 f4080005 fa000040 f4200100 fa000008 f4200140 0c000000 7e000204 7e020205 f8000803 00000100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
assert!(
|
||||
t.ps_hlsl
|
||||
.contains("cbuffer CB1_2 : register(b2, space101) { uint4 cb1_2[4096]; };"),
|
||||
"{}",
|
||||
t.ps_hlsl
|
||||
);
|
||||
assert!(
|
||||
t.ps_hlsl.contains(" s4 = cb1_2_word(2);\n"),
|
||||
"{}",
|
||||
t.ps_hlsl
|
||||
);
|
||||
assert!(
|
||||
t.ps_hlsl.contains(" s5 = cb1_2_word((s6 >> 2) + 0u);\n"),
|
||||
"{}",
|
||||
t.ps_hlsl
|
||||
);
|
||||
assert_eq!(t.layout, "FETCH 1\nUSE CB 1 2\n");
|
||||
}
|
||||
|
||||
/// image_load and image_gather4_lz (#718): integer-coordinate loads from 2D and 3D textures
|
||||
/// (declared by the dimension they are read with) and a green-channel gather. Textures come from
|
||||
/// root table 0 entries 1 and 2. Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn image_loads_and_gathers() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
// s_load_dwordx8 s[20:27], s[8:9], 0x20; s_load_dwordx8 s[28:35], s[8:9], 0x40;
|
||||
// image_load v[0:3], v[4:5], s[20:27] dmask:0xf dim:2D; image_load v6, v[4:6], s[28:35] dmask:0x1 dim:3D;
|
||||
// image_gather4_lz v[8:11], v[4:5], s[20:27], s[36:39] dmask:0x2 dim:2D;
|
||||
// exp mrt0, v0, v6, v8, v11 done; s_endpgm
|
||||
let ps = decode(&words(
|
||||
"f40c0504 fa000020 f40c0704 fa000040 f0000f08 00050004 f0000110 00070604 f11c0208 01250804 f800080f 0b080600 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.ps_hlsl;
|
||||
assert!(
|
||||
h.contains("Texture2D<float4> tex1 : register(t1, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("Texture3D<float4> tex2 : register(t2, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("{ float4 r = tex1.Load(int3(asint(v4), asint(v5), 0));"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("{ float4 r = tex2.Load(int4(asint(v4), asint(v5), asint(v6), 0));"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("{ float4 r = tex1.GatherGreen(smp0, float2(asfloat(v4), asfloat(v5)));"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(h.contains(" v11 = asuint(r.w);"), "{h}");
|
||||
assert_eq!(t.layout, "FETCH 1\nUSE TEX 1\nUSE TEX 2\n");
|
||||
}
|
||||
|
||||
/// A pixel shader's HLSL from instruction words (no interpolated inputs).
|
||||
fn pixel_hlsl(hex: &str) -> String {
|
||||
let insts = decode(&words(hex)).unwrap();
|
||||
let mut t = Translator::new(Stage::Pixel);
|
||||
t.run(&insts).unwrap();
|
||||
gfx10_translate::translate::build_ps(&t, &[]).unwrap()
|
||||
}
|
||||
|
||||
// Encodings from llvm-mc (gfx1030). Expected lines follow the ISA's definitions, not the
|
||||
// translator: a compare writes the condition for active lanes only; s_and_saveexec saves exec and
|
||||
// ANDs it with the source; s_cbranch_execz jumps when no lane is active; the export's vm bit
|
||||
// marks the lanes that survive.
|
||||
#[test]
|
||||
fn divergent_if_runs_under_exec() {
|
||||
// v_cmp_lt_f32_e32 vcc_lo, v0, v1 (word 0)
|
||||
// s_and_saveexec_b32 s0, vcc_lo (1)
|
||||
// s_cbranch_execz 1 (2: to word 4)
|
||||
// v_mov_b32_e32 v2, 1.0 (3)
|
||||
// s_or_b32 exec_lo, exec_lo, s0 (4)
|
||||
// exp mrt0 v2, v2, v2, v2 done vm (5-6)
|
||||
// s_endpgm (7)
|
||||
let ps = pixel_hlsl("7c020300 be803c6a bf880001 7e0402f2 887e007e f800180f 02020202 bf810000");
|
||||
let has = |line: &str| assert!(ps.contains(line), "missing `{line}` in\n{ps}");
|
||||
has("vcc = exec && (");
|
||||
has("bool old_exec = exec;");
|
||||
has("exec = exec && vcc;");
|
||||
has("m0 = old_exec;");
|
||||
has("blk = (!WaveActiveAnyTrue(exec)) ? 4u : 3u;");
|
||||
// The move runs only for active lanes; restoring exec reads the saved mask.
|
||||
has("if (exec) {");
|
||||
has("exec = exec || m0;");
|
||||
has("if (!exec) discard;");
|
||||
has("return float4(exp_mrt0.x, exp_mrt0.y, exp_mrt0.z, exp_mrt0.w);");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cmpx_removes_lanes_before_the_final_export() {
|
||||
// v_cmpx_gt_f32_e32 0.5, v0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
|
||||
let ps = pixel_hlsl("7c2800f0 f800180f 00000000 bf810000");
|
||||
assert!(
|
||||
ps.contains("exec = exec && (asfloat(asuint(0.5f)) > asfloat(v0));"),
|
||||
"{ps}"
|
||||
);
|
||||
assert!(ps.contains("if (!exec) discard;"), "{ps}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn early_exit_keeps_the_code_after_it() {
|
||||
// s_cmp_eq_u32 s0, 0 (word 0)
|
||||
// s_cbranch_scc1 3 (1: to word 5)
|
||||
// exp mrt0 v0, v0, v0, v0 done vm (2-3)
|
||||
// s_endpgm (4)
|
||||
// v_mov_b32_e32 v0, 0 (5)
|
||||
// exp mrt0 v0, v0, v0, v0 done vm (6-7)
|
||||
// s_endpgm (8)
|
||||
let hex = "bf068000 bf850003 f800180f 00000000 bf810000 7e000280 f800180f 00000000 bf810000";
|
||||
assert_eq!(decode(&words(hex)).unwrap().len(), 7);
|
||||
let ps = pixel_hlsl(hex);
|
||||
assert!(ps.contains("scc = s0 == 0u;"), "{ps}");
|
||||
assert!(ps.contains("blk = (scc) ? 5u : 2u;"), "{ps}");
|
||||
// Both exits export to the same variable, so the one that ran is returned.
|
||||
assert_eq!(
|
||||
ps.matches("exp_mrt0 = float4(asfloat(v0)").count(),
|
||||
2,
|
||||
"{ps}"
|
||||
);
|
||||
// Each s_endpgm ends the loop, as does the fallback for an unknown block.
|
||||
assert_eq!(ps.matches("blk = 0xffffffffu;").count(), 3, "{ps}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn samples_run_for_the_whole_quad() {
|
||||
// s_load_dwordx8 s[20:27], s[8:9], 0x20 ; v_cmpx_lt_f32_e32 0, v4 ;
|
||||
// image_sample v[0:3], v[4:5], s[20:27], s[36:39] dmask:0xf dim:2D ;
|
||||
// exp mrt0 v0, v1, v2, v3 done vm ; s_endpgm
|
||||
// A sample's derivatives come from its quad, whatever exec holds, so it is not placed under
|
||||
// control flow that depends on exec; only the register writes are.
|
||||
let ps = pixel_hlsl("f40c0504 fa000020 7c220880 f0800f08 01250004 f800180f 03020100 bf810000");
|
||||
assert!(ps.contains("v0 = exec ? (asuint(r.x)) : v0;"), "{ps}");
|
||||
assert!(ps.contains("v3 = exec ? (asuint(r.w)) : v3;"), "{ps}");
|
||||
let sample = ps.find(".Sample(").expect("a sample");
|
||||
assert!(!ps[..sample].contains("if (exec)"), "{ps}");
|
||||
}
|
||||
@@ -105,6 +105,7 @@ CUSTOM = {
|
||||
"GetGPUDescriptorHandleForHeapStart": "bx_xbox_heap_gpu_start"},
|
||||
"GraphicsCommandList": {"ResourceBarrier": "bx_xbox_list_resource_barrier",
|
||||
"CopyTextureRegion": "bx_xbox_list_copy_texture_region",
|
||||
"CopyTextureRegionX": "bx_xbox_list_copy_texture_region_x",
|
||||
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
|
||||
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
|
||||
"IASetPrimitiveTopology": "bx_xbox_list_ia_set_primitive_topology",
|
||||
|
||||
@@ -314,4 +314,16 @@ void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->CopyTextureRegion(dst ? &d : nullptr, x, y, z, src ? &s : nullptr, box);
|
||||
}
|
||||
|
||||
/* CopyTextureRegionX (GDK d3d12_xs.h): CopyTextureRegion plus D3D12XBOX_COPY_FLAGS, which only
|
||||
steer the console's compression metadata (HTILE resummarize, forced decompress, clear
|
||||
propagation). The host keeps no such metadata, so the copy is the PC one. Leaving the call a
|
||||
stub left the copy undone, and the target build then stalled its frame until its hang
|
||||
watchdog ended the process (#722). */
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region_x(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box, UINT /*flags*/) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyTextureRegionX");
|
||||
bx_xbox_list_copy_texture_region(self, dst, x, y, z, src, box);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -442,6 +442,9 @@ UINT STDMETHODCALLTYPE bx_xbox_list_resource_barrier(void* self, UINT count, con
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_copy_texture_region_x(void* self, const D3D12_TEXTURE_COPY_LOCATION* dst, UINT x,
|
||||
UINT y, UINT z, const D3D12_TEXTURE_COPY_LOCATION* src,
|
||||
const D3D12_BOX* box, UINT flags);
|
||||
}
|
||||
|
||||
#include "xbox_tables_generated.h"
|
||||
|
||||
@@ -1475,8 +1475,6 @@ static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_83(void*) { BX_VTABLE_STUB
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_84(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 84u, "NopX"); return 0; }
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_85(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 85u, "CopyTextureRegionX"); return 0; }
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_86(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 86u, "CopyResourceX"); return 0; }
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_87(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 87u, "Deprecated_SetPredicationBufferX"); return 0; }
|
||||
@@ -1727,7 +1725,7 @@ const void* const kGraphicsCommandListTable[] = {
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_82),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_83),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_84),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_85),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_copy_texture_region_x),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_86),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_87),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_88),
|
||||
@@ -1809,7 +1807,7 @@ const IID kGraphicsCommandListIids[] = {
|
||||
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
|
||||
};
|
||||
|
||||
/* ID3D12GraphicsCommandList8: 150 slots (65 forwarded, 25 shared, 60 stubs); hosted on ID3D12GraphicsCommandList7. */
|
||||
/* ID3D12GraphicsCommandList8: 150 slots (65 forwarded, 26 shared, 59 stubs); hosted on ID3D12GraphicsCommandList7. */
|
||||
const IID kHostGraphicsCommandList = __uuidof(ID3D12GraphicsCommandList7);
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#include <windows.h>
|
||||
#include <tlhelp32.h>
|
||||
#include <atomic>
|
||||
#include <utility>
|
||||
#include <cstdio>
|
||||
#include <cstdarg>
|
||||
#include <cstdlib>
|
||||
@@ -1380,6 +1381,75 @@ static bool continue_assert(PEXCEPTION_POINTERS ep) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A title thread can read or write a page of an XMEM_MAPPABLE reservation while another thread
|
||||
remaps part of the same run of pages. xmem replaces the whole run's view and maps the rest
|
||||
back (physical_pages.cpp), so for a moment every page of the run is unmapped; on the console
|
||||
the page-table update is atomic and other pages never disappear (#722). When a fault in the
|
||||
title's own code hits an address that is not accessible, wait for any remap in progress (the
|
||||
xmem remap guard: entering it waits for exclusive remaps to finish) and retry the instruction
|
||||
if the address is now accessible for that access. Genuine faults still reach the title: the
|
||||
address stays inaccessible, or the same instruction faults again more than three times in a
|
||||
row. Faults in BetterXen's own code are left alone, since they may already hold the guard. */
|
||||
static bool accessible(uintptr_t address, ULONG_PTR access) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) || region.State != MEM_COMMIT) return false;
|
||||
const DWORD p = region.Protect & 0xFF;
|
||||
if ((region.Protect & PAGE_GUARD) || p == PAGE_NOACCESS) return false;
|
||||
if (access == 1) {
|
||||
return p == PAGE_READWRITE || p == PAGE_WRITECOPY || p == PAGE_EXECUTE_READWRITE || p == PAGE_EXECUTE_WRITECOPY;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool retry_after_remap(PEXCEPTION_POINTERS ep) {
|
||||
using GuardFn = void (*)(void);
|
||||
static const std::pair<GuardFn, GuardFn> guard = [] {
|
||||
HMODULE xmem = GetModuleHandleW(L"xmem.dll");
|
||||
auto enter = xmem ? reinterpret_cast<GuardFn>(reinterpret_cast<void*>(GetProcAddress(xmem, "bx_xmem_remap_guard_enter"))) : nullptr;
|
||||
auto leave = xmem ? reinterpret_cast<GuardFn>(reinterpret_cast<void*>(GetProcAddress(xmem, "bx_xmem_remap_guard_leave"))) : nullptr;
|
||||
return (enter && leave) ? std::make_pair(enter, leave) : std::make_pair(GuardFn{}, GuardFn{});
|
||||
}();
|
||||
const EXCEPTION_RECORD& rec = *ep->ExceptionRecord;
|
||||
if (!guard.first || rec.NumberParameters < 2 || rec.ExceptionInformation[0] == 8) return false;
|
||||
const auto rip = static_cast<uintptr_t>(ep->ContextRecord->Rip);
|
||||
const auto exe = reinterpret_cast<uintptr_t>(GetModuleHandleW(nullptr));
|
||||
MEMORY_BASIC_INFORMATION code{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(rip), &code, sizeof(code)) || reinterpret_cast<uintptr_t>(code.AllocationBase) != exe) {
|
||||
return false;
|
||||
}
|
||||
thread_local uintptr_t last_rip = 0;
|
||||
thread_local int repeats = 0;
|
||||
repeats = (rip == last_rip) ? repeats + 1 : 0;
|
||||
last_rip = rip;
|
||||
if (repeats > 3) return false;
|
||||
const uintptr_t address = rec.ExceptionInformation[1];
|
||||
const ULONG_PTR access = rec.ExceptionInformation[0];
|
||||
const DWORD saved_error = GetLastError();
|
||||
guard.first(); // waits until no remap is in progress
|
||||
guard.second();
|
||||
const bool now = accessible(address, access);
|
||||
static std::atomic<uint64_t> retries{0}, refused{0};
|
||||
char detail[160];
|
||||
if (!now) {
|
||||
const uint64_t n = refused.fetch_add(1) + 1;
|
||||
if (n <= 8) {
|
||||
std::snprintf(detail, sizeof(detail), "title fault at rva 0x%llx on %s of an address still unmapped after waiting for remaps",
|
||||
static_cast<unsigned long long>(rip - exe), access == 1 ? "write" : "read");
|
||||
bx_log_emit(BX_LOG_INFO, "runtime_veh", "remap_window_checked", detail);
|
||||
}
|
||||
SetLastError(saved_error);
|
||||
return false;
|
||||
}
|
||||
const uint64_t n = retries.fetch_add(1) + 1;
|
||||
if (n <= 16 || (n & (n - 1)) == 0) {
|
||||
std::snprintf(detail, sizeof(detail), "title fault at rva 0x%llx on %s of a page being remapped: retried (%llu so far)",
|
||||
static_cast<unsigned long long>(rip - exe), access == 1 ? "write" : "read", static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_WARN, "runtime_veh", "remap_window_retry", detail);
|
||||
}
|
||||
SetLastError(saved_error);
|
||||
return true;
|
||||
}
|
||||
|
||||
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
if (!ep || !ep->ExceptionRecord || !ep->ContextRecord) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
@@ -1394,6 +1464,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
|
||||
return EXCEPTION_CONTINUE_SEARCH;
|
||||
}
|
||||
if (code == EXCEPTION_ACCESS_VIOLATION) {
|
||||
if (retry_after_remap(ep)) return EXCEPTION_CONTINUE_EXECUTION;
|
||||
if (!g_av_context_on) return EXCEPTION_CONTINUE_SEARCH; // diagnostics off: no work at all
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (g_av_all || (VirtualQuery(ep->ExceptionRecord->ExceptionAddress, ®ion, sizeof(region)) && region.Type == MEM_IMAGE)) {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_d3d12_copy_texture_region_x main.cpp)
|
||||
target_compile_definitions(test_d3d12_copy_texture_region_x PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_link_libraries(test_d3d12_copy_texture_region_x PRIVATE d3d12_xs kernel32 uuid)
|
||||
@@ -0,0 +1,226 @@
|
||||
/*
|
||||
* Conformance test: ID3D12GraphicsCommandList::CopyTextureRegionX (Xbox-layout slot 85).
|
||||
*
|
||||
* Contract (Xbox Series GDK d3d12_xs.h): CopyTextureRegionX(pDst, DstX, DstY, DstZ, pSrc, pSrcBox,
|
||||
* Flags) is CopyTextureRegion plus D3D12XBOX_COPY_FLAGS, which steer the console's compression
|
||||
* metadata (resummarize HTILE 0x10, force decompress 0x60, propagate color clear 0x400). The
|
||||
* host keeps no such metadata, so the copy is the PC one whatever the flags.
|
||||
*
|
||||
* A 64x64 target is cleared green with a red 16x16 square at (8, 8). Through slot 85 the test
|
||||
* copies the square's box into a 16x16 readback footprint (with flags 0x60), and the whole
|
||||
* texture into a second footprint at DstX = 0 (flags 0). Expected: the first readback is all red,
|
||||
* the second green with the red square at (8, 8). A stub that records nothing leaves both empty.
|
||||
*
|
||||
* Slots (Xbox-layout tables, ADR 0009): 2 Release; device 9 CreateCommandAllocator,
|
||||
* 14 CreateDescriptorHeap, 20 CreateRenderTargetView, 27 CreateCommittedResource, 36 CreateFence,
|
||||
* 48 CreateCommandQueueX, 73 CreateCommandListX; resource 8 Map; descriptor heap 9
|
||||
* GetCPUDescriptorHandleForHeapStart; command list 9 Close, 26 ResourceBarrier,
|
||||
* 52 ClearRenderTargetView, 85 CopyTextureRegionX; queue 10 ExecuteCommandLists, 16 Signal; fence 9
|
||||
* SetEventOnCompletion.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(PVOID adapter, const void* params, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kRelease = 2;
|
||||
constexpr int kDevCreateCommandAllocator = 9, kDevCreateDescriptorHeap = 14, kDevCreateRenderTargetView = 20;
|
||||
constexpr int kDevCreateCommittedResource = 27, kDevCreateFence = 36, kDevCreateCommandQueueX = 48, kDevCreateCommandListX = 73;
|
||||
constexpr int kResMap = 8, kHeapGetCpuStart = 9;
|
||||
constexpr int kListClose = 9, kListResourceBarrier = 26, kListClearRenderTargetView = 52, kListCopyTextureRegionX = 85;
|
||||
constexpr int kQueueExecuteCommandLists = 10, kQueueSignal = 16, kFenceSetEventOnCompletion = 9;
|
||||
constexpr UINT kForceDecompress = 0x60; // D3D12XBOX_COPY_FLAG_FORCE_DECOMPRESS
|
||||
constexpr UINT kSize = 64, kSquare = 16, kAt = 8;
|
||||
constexpr UINT kPitch = 256; // the texture data pitch alignment; 64 * 4 = 256
|
||||
|
||||
int g_checks = 0, g_failed = 0;
|
||||
#define CHECK(cond, ...) \
|
||||
do { \
|
||||
++g_checks; \
|
||||
if (!(cond)) { \
|
||||
++g_failed; \
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_copy_texture_region_x:%d: ", __LINE__); \
|
||||
std::fprintf(stderr, __VA_ARGS__); \
|
||||
std::fprintf(stderr, "\n"); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(void* object, int index) {
|
||||
return reinterpret_cast<Fn>((*static_cast<void* const* const*>(object))[index]);
|
||||
}
|
||||
|
||||
struct QueueDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, EngineOrPipeIndex, QueueIndex;
|
||||
};
|
||||
struct ListDescX {
|
||||
D3D12_COMMAND_LIST_TYPE Type;
|
||||
UINT Flags, NodeMask, ResourceBarrierBatchSize;
|
||||
};
|
||||
|
||||
using ReleaseFn = ULONG(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateQueueXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const QueueDescX*, REFIID, void**);
|
||||
using CreateAllocatorFn = HRESULT(STDMETHODCALLTYPE*)(void*, D3D12_COMMAND_LIST_TYPE, REFIID, void**);
|
||||
using CreateListXFn = HRESULT(STDMETHODCALLTYPE*)(void*, const ListDescX*, void*, void*, REFIID, void**);
|
||||
using CreateCommittedFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS,
|
||||
const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_STATES,
|
||||
const D3D12_CLEAR_VALUE*, REFIID, void**);
|
||||
using CreateFenceFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, D3D12_FENCE_FLAGS, REFIID, void**);
|
||||
using CreateHeapFn = HRESULT(STDMETHODCALLTYPE*)(void*, const D3D12_DESCRIPTOR_HEAP_DESC*, REFIID, void**);
|
||||
using HeapStartFn = D3D12_CPU_DESCRIPTOR_HANDLE(STDMETHODCALLTYPE*)(void*);
|
||||
using CreateRtvFn = void(STDMETHODCALLTYPE*)(void*, void*, const D3D12_RENDER_TARGET_VIEW_DESC*, D3D12_CPU_DESCRIPTOR_HANDLE);
|
||||
using MapFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RANGE*, void**);
|
||||
using CloseFn = HRESULT(STDMETHODCALLTYPE*)(void*);
|
||||
using BarrierFn = UINT(STDMETHODCALLTYPE*)(void*, UINT, const D3D12_RESOURCE_BARRIER*);
|
||||
using ClearFn = void(STDMETHODCALLTYPE*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT*, UINT, const D3D12_RECT*);
|
||||
using CopyRegionXFn = void(STDMETHODCALLTYPE*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT,
|
||||
const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*, UINT);
|
||||
using ExecuteFn = void(STDMETHODCALLTYPE*)(void*, UINT, void* const*);
|
||||
using QueueSignalFn = HRESULT(STDMETHODCALLTYPE*)(void*, void*, UINT64);
|
||||
using FenceEventFn = HRESULT(STDMETHODCALLTYPE*)(void*, UINT64, HANDLE);
|
||||
|
||||
bool red(const uint8_t* p) { return p[0] > 200 && p[1] < 40 && p[2] < 40 && p[3] > 200; }
|
||||
bool green(const uint8_t* p) { return p[0] < 40 && p[1] > 200 && p[2] < 40 && p[3] > 200; }
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
alignas(8) unsigned char title_params[80] = {};
|
||||
const UINT version = 0x20004; // a non-zero version selects the Xbox-layout device
|
||||
std::memcpy(title_params, &version, sizeof(version));
|
||||
void* dev = nullptr;
|
||||
HRESULT hr = D3D12XboxCreateDevice(nullptr, title_params, __uuidof(ID3D12Device), &dev);
|
||||
if (hr == E_NOINTERFACE) {
|
||||
std::printf("SKIP: test_d3d12_copy_texture_region_x: host lacks the Xbox-layout device interface (E_NOINTERFACE)\n");
|
||||
return 77;
|
||||
}
|
||||
CHECK(hr == S_OK && dev, "Xbox-layout device creation hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!dev) return 1;
|
||||
|
||||
const QueueDescX qdesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
const ListDescX ldesc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, 0};
|
||||
void *queue = nullptr, *allocator = nullptr, *list = nullptr, *fence = nullptr;
|
||||
slot<CreateQueueXFn>(dev, kDevCreateCommandQueueX)(dev, &qdesc, __uuidof(ID3D12CommandQueue), &queue);
|
||||
slot<CreateAllocatorFn>(dev, kDevCreateCommandAllocator)(dev, D3D12_COMMAND_LIST_TYPE_DIRECT, __uuidof(ID3D12CommandAllocator),
|
||||
&allocator);
|
||||
slot<CreateListXFn>(dev, kDevCreateCommandListX)(dev, &ldesc, allocator, nullptr, __uuidof(ID3D12GraphicsCommandList), &list);
|
||||
slot<CreateFenceFn>(dev, kDevCreateFence)(dev, 0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), &fence);
|
||||
|
||||
D3D12_HEAP_PROPERTIES default_heap{}, readback_heap{};
|
||||
default_heap.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
readback_heap.Type = D3D12_HEAP_TYPE_READBACK;
|
||||
D3D12_RESOURCE_DESC tex{};
|
||||
tex.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
tex.Width = kSize;
|
||||
tex.Height = kSize;
|
||||
tex.DepthOrArraySize = 1;
|
||||
tex.MipLevels = 1;
|
||||
tex.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
tex.SampleDesc.Count = 1;
|
||||
tex.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
D3D12_RESOURCE_DESC buf{};
|
||||
buf.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buf.Width = static_cast<UINT64>(kPitch) * kSize;
|
||||
buf.Height = 1;
|
||||
buf.DepthOrArraySize = 1;
|
||||
buf.MipLevels = 1;
|
||||
buf.SampleDesc.Count = 1;
|
||||
buf.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
auto committed = slot<CreateCommittedFn>(dev, kDevCreateCommittedResource);
|
||||
void *target = nullptr, *box_readback = nullptr, *full_readback = nullptr;
|
||||
hr = committed(dev, &default_heap, D3D12_HEAP_FLAG_NONE, &tex, D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr,
|
||||
__uuidof(ID3D12Resource), &target);
|
||||
CHECK(hr == S_OK && target, "render target hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &box_readback);
|
||||
CHECK(hr == S_OK && box_readback, "box readback hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
hr = committed(dev, &readback_heap, D3D12_HEAP_FLAG_NONE, &buf, D3D12_RESOURCE_STATE_COPY_DEST, nullptr,
|
||||
__uuidof(ID3D12Resource), &full_readback);
|
||||
CHECK(hr == S_OK && full_readback, "full readback hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap_desc{};
|
||||
heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap_desc.NumDescriptors = 1;
|
||||
void* rtv_heap = nullptr;
|
||||
hr = slot<CreateHeapFn>(dev, kDevCreateDescriptorHeap)(dev, &heap_desc, __uuidof(ID3D12DescriptorHeap), &rtv_heap);
|
||||
CHECK(hr == S_OK && rtv_heap, "RTV heap hr=0x%08lx", static_cast<unsigned long>(hr));
|
||||
if (!queue || !allocator || !list || !fence || !target || !box_readback || !full_readback || !rtv_heap) {
|
||||
std::fprintf(stderr, "FAIL: test_d3d12_copy_texture_region_x: setup\n");
|
||||
return 1;
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = slot<HeapStartFn>(rtv_heap, kHeapGetCpuStart)(rtv_heap);
|
||||
slot<CreateRtvFn>(dev, kDevCreateRenderTargetView)(dev, target, nullptr, rtv);
|
||||
|
||||
// Green everywhere, red in the 16x16 square at (8, 8).
|
||||
const FLOAT g[4] = {0, 1, 0, 1}, r[4] = {1, 0, 0, 1};
|
||||
const D3D12_RECT square{kAt, kAt, kAt + kSquare, kAt + kSquare};
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtv, g, 0, nullptr);
|
||||
slot<ClearFn>(list, kListClearRenderTargetView)(list, rtv, r, 1, &square);
|
||||
D3D12_RESOURCE_BARRIER to_copy{};
|
||||
to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
to_copy.Transition.pResource = static_cast<ID3D12Resource*>(target);
|
||||
to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_RENDER_TARGET;
|
||||
to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE;
|
||||
slot<BarrierFn>(list, kListResourceBarrier)(list, 1, &to_copy);
|
||||
|
||||
D3D12_TEXTURE_COPY_LOCATION src{};
|
||||
src.pResource = static_cast<ID3D12Resource*>(target);
|
||||
src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
|
||||
D3D12_TEXTURE_COPY_LOCATION box_dst{};
|
||||
box_dst.pResource = static_cast<ID3D12Resource*>(box_readback);
|
||||
box_dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
|
||||
box_dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSquare, kSquare, 1, kPitch};
|
||||
const D3D12_BOX box{kAt, kAt, 0, kAt + kSquare, kAt + kSquare, 1};
|
||||
auto copy_x = slot<CopyRegionXFn>(list, kListCopyTextureRegionX);
|
||||
copy_x(list, &box_dst, 0, 0, 0, &src, &box, kForceDecompress);
|
||||
D3D12_TEXTURE_COPY_LOCATION full_dst = box_dst;
|
||||
full_dst.pResource = static_cast<ID3D12Resource*>(full_readback);
|
||||
full_dst.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSize, kSize, 1, kPitch};
|
||||
copy_x(list, &full_dst, 0, 0, 0, &src, nullptr, 0);
|
||||
CHECK(slot<CloseFn>(list, kListClose)(list) == S_OK, "list Close");
|
||||
|
||||
void* lists[] = {list};
|
||||
slot<ExecuteFn>(queue, kQueueExecuteCommandLists)(queue, 1, lists);
|
||||
CHECK(slot<QueueSignalFn>(queue, kQueueSignal)(queue, fence, 1) == S_OK, "queue Signal");
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(slot<FenceEventFn>(fence, kFenceSetEventOnCompletion)(fence, 1, done) == S_OK, "fence event");
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0, "GPU work completes");
|
||||
CloseHandle(done);
|
||||
|
||||
void *box_pixels = nullptr, *full_pixels = nullptr;
|
||||
CHECK(slot<MapFn>(box_readback, kResMap)(box_readback, 0, nullptr, &box_pixels) == S_OK && box_pixels, "box readback Map");
|
||||
CHECK(slot<MapFn>(full_readback, kResMap)(full_readback, 0, nullptr, &full_pixels) == S_OK && full_pixels, "full readback Map");
|
||||
if (!box_pixels || !full_pixels) return 1;
|
||||
const auto* bp = static_cast<const uint8_t*>(box_pixels);
|
||||
const auto* fp = static_cast<const uint8_t*>(full_pixels);
|
||||
|
||||
unsigned box_red = 0;
|
||||
for (UINT y = 0; y < kSquare; ++y) {
|
||||
for (UINT x = 0; x < kSquare; ++x) box_red += red(bp + y * kPitch + x * 4) ? 1 : 0;
|
||||
}
|
||||
CHECK(box_red == kSquare * kSquare, "the box copy (flags 0x60) holds the red square: %u of %u pixels red", box_red,
|
||||
kSquare * kSquare);
|
||||
unsigned full_ok = 0;
|
||||
for (UINT y = 0; y < kSize; ++y) {
|
||||
for (UINT x = 0; x < kSize; ++x) {
|
||||
const bool in_square = x >= kAt && x < kAt + kSquare && y >= kAt && y < kAt + kSquare;
|
||||
const uint8_t* p = fp + y * kPitch + x * 4;
|
||||
full_ok += (in_square ? red(p) : green(p)) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
CHECK(full_ok == kSize * kSize, "the whole-texture copy (flags 0) matches the target: %u of %u pixels", full_ok, kSize * kSize);
|
||||
|
||||
void* const objects[] = {rtv_heap, full_readback, box_readback, target, fence, list, allocator, queue, dev};
|
||||
for (void* object : objects) slot<ReleaseFn>(object, kRelease)(object);
|
||||
std::printf("%s: test_d3d12_copy_texture_region_x (%d of %d checks passed)\n", g_failed ? "FAIL" : "PASS", g_checks - g_failed,
|
||||
g_checks);
|
||||
return g_failed ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
add_executable(test_veh_remap_window main.cpp)
|
||||
target_link_libraries(test_veh_remap_window PRIVATE bx_runtime_veh xmem kernel32)
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* A title thread reading a page of an XMEM_MAPPABLE reservation while another thread remaps a
|
||||
* different page of the same mapped run (#722).
|
||||
*
|
||||
* xmem replaces part of a mapped run by unmapping the run's whole view and mapping the remaining
|
||||
* pages back (physical_pages.cpp), so for a moment every page of the run is unmapped. On the
|
||||
* console the page-table update is atomic: pages that are not remapped never disappear. The title
|
||||
* reads such pages without BetterXen's remap guard, so bx_runtime_veh retries a fault in the
|
||||
* title's own code once the remap is over (retry_after_remap).
|
||||
*
|
||||
* The test maps four pages as one run, keeps reading page 0 from four threads of this executable
|
||||
* (the "title"), and remaps pages 1 and 2 again and again for four seconds. No read may fault;
|
||||
* without the retry a reader dies in an access violation (4 of 4 runs). The values read are
|
||||
* reported, not checked (see the note at the end).
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
uint64_t bx_veh_get_clwb_trap_count(void);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr SIZE_T kPage = 64 * 1024;
|
||||
constexpr DWORD kMem64KPages = 0x20400000;
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
constexpr uint64_t kXMemMappable = 0x20;
|
||||
constexpr uint32_t kMarker = 0x5eed1234;
|
||||
|
||||
struct Reader {
|
||||
volatile uint32_t* stable; // page 0 of the run: never remapped
|
||||
volatile LONG stop;
|
||||
volatile LONG reads;
|
||||
volatile LONG wrong;
|
||||
};
|
||||
|
||||
DWORD WINAPI read_without_guard(void* arg) {
|
||||
auto* reader = static_cast<Reader*>(arg);
|
||||
while (!reader->stop) {
|
||||
for (int i = 0; i < 256; ++i) {
|
||||
if (reader->stable[i * 64] != kMarker) InterlockedIncrement(&reader->wrong);
|
||||
}
|
||||
InterlockedIncrement(&reader->reads);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "FAIL: test_veh_remap_window:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
SetErrorMode(SEM_NOGPFAULTERRORBOX);
|
||||
// Keep a static import on bx_runtime_veh.dll so its handler is installed at load.
|
||||
volatile uint64_t attached = bx_veh_get_clwb_trap_count();
|
||||
(void)attached;
|
||||
|
||||
ULONG_PTR count = 6;
|
||||
ULONG_PTR pages[6]{};
|
||||
CHECK(XMemAllocatePhysicalPages(0, &count, pages) && count == 6);
|
||||
auto* base = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, 8 * kPage, MEM_RESERVE | kMem64KPages,
|
||||
kXMemMappable | kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(base);
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base); // one run of four pages
|
||||
auto* stable = reinterpret_cast<volatile uint32_t*>(base);
|
||||
for (int i = 0; i < 256; ++i) stable[i * 64] = kMarker;
|
||||
|
||||
// Four readers, so a remap's gap is hit within the run rather than by chance.
|
||||
Reader reader{stable, 0, 0, 0};
|
||||
HANDLE threads[4]{};
|
||||
for (HANDLE& t : threads) {
|
||||
t = CreateThread(nullptr, 0, read_without_guard, &reader, 0, nullptr);
|
||||
CHECK(t);
|
||||
}
|
||||
ULONG_PTR a[2] = {pages[4], pages[5]};
|
||||
ULONG_PTR b[2] = {pages[1], pages[2]};
|
||||
const DWORD start = GetTickCount();
|
||||
int remaps = 0;
|
||||
while (GetTickCount() - start < 4000) {
|
||||
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? b : a) == base + kPage);
|
||||
++remaps;
|
||||
Sleep(1);
|
||||
}
|
||||
InterlockedExchange(&reader.stop, 1);
|
||||
CHECK(WaitForMultipleObjects(4, threads, TRUE, 5000) == WAIT_OBJECT_0);
|
||||
for (HANDLE t : threads) CloseHandle(t);
|
||||
std::printf("remaps=%d unguarded read batches=%ld wrong=%ld\n", remaps, static_cast<long>(reader.reads), static_cast<long>(reader.wrong));
|
||||
CHECK(remaps > 10 && reader.reads > 10);
|
||||
// Not checked: in about one run in eight, one read in roughly 10^8 lands when the page is
|
||||
// readable but holds other data, with no fault to retry. Only views that never take
|
||||
// untouched pages out fix that (one view per page); tracked separately.
|
||||
if (reader.wrong) std::printf("note: %ld read(s) saw other data during a remap\n", static_cast<long>(reader.wrong));
|
||||
std::puts("PASS: test_veh_remap_window");
|
||||
return 0;
|
||||
}
|
||||
Reference in new issue
Block a user