mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-12-03 10:12:27 +00:00
Compare commits
184
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
34f97fd2d6 | ||
|
|
bc66413f29 | ||
|
|
f98bb2de50 | ||
|
|
11c8bf8209 | ||
|
|
3b8c67a4a7 | ||
|
|
aaa0171c0e | ||
|
|
180156806c | ||
|
|
98f4a16daa | ||
|
|
5fd69c0be2 | ||
|
|
c76957b7c7 | ||
|
|
358435595e | ||
|
|
6fd1438e67 | ||
|
|
875b326c57 | ||
|
|
6b0f62a62f | ||
|
|
1b53450da4 | ||
|
|
cabdcd63cb | ||
|
|
14c0abd930 | ||
|
|
fb69c0ef8e | ||
|
|
2216cd2c2a | ||
|
|
051accbba3 | ||
|
|
269a8d7d70 | ||
|
|
4a125c6ae9 | ||
|
|
8ed5430051 | ||
|
|
d6c4db93a0 | ||
|
|
5ca2dcc304 | ||
|
|
2aaef338b8 | ||
|
|
7bb28ad220 | ||
|
|
931390e9aa | ||
|
|
8f1c82fd42 | ||
|
|
2736f24ca2 | ||
|
|
2bd8766553 | ||
|
|
d01a7c004f | ||
|
|
f6bb3409e0 | ||
|
|
b420e89ba4 | ||
|
|
1c0ec5cc9a | ||
|
|
2370f97df5 | ||
|
|
0967b7413b | ||
|
|
9898f6b095 | ||
|
|
73c0815285 | ||
|
|
b8dfe5652c | ||
|
|
ebcfd27fce | ||
|
|
75d0f99b5c | ||
|
|
5398714f12 | ||
|
|
c465e03459 | ||
|
|
0b0c43173c | ||
|
|
ecd8a218f7 | ||
|
|
b0850c102d | ||
|
|
655102c06c | ||
|
|
b04b9ead4d | ||
|
|
5a64cc98ee | ||
|
|
fcc5b9c51c | ||
|
|
82b3dc28ff | ||
|
|
c4c90ef9ea | ||
|
|
03da5a03bb | ||
|
|
db6c361f47 | ||
|
|
d19ee55d25 | ||
|
|
f9500edd25 | ||
|
|
f9d2568009 | ||
|
|
f6315b09a8 | ||
|
|
ea956e0c91 | ||
|
|
9de78e0040 | ||
|
|
14be28e735 | ||
|
|
d922f87604 | ||
|
|
2236ee1c89 | ||
|
|
f6dedc95f3 | ||
|
|
a244f4172d | ||
|
|
9b25c50798 | ||
|
|
08a0dd562e | ||
|
|
d3000739d4 | ||
|
|
5d1b0ba8e4 | ||
|
|
b1319ca8d1 | ||
|
|
6e297c02a8 | ||
|
|
1b3a7d924e | ||
|
|
40eb3362be | ||
|
|
cc494f0222 | ||
|
|
f398dff965 | ||
|
|
3b51c3e562 | ||
|
|
29ebcdc192 | ||
|
|
b74b37b6af | ||
|
|
e70a72010d | ||
|
|
9c92845fae | ||
|
|
59bf82ac61 | ||
|
|
fe6240ecd6 | ||
|
|
58956469ef | ||
|
|
f76b60f162 | ||
|
|
c545d15530 | ||
|
|
714d90baf8 | ||
|
|
d18c2d514a | ||
|
|
f7858ca991 | ||
|
|
526d73b678 | ||
|
|
c1403b7bf9 | ||
|
|
17939f4acd | ||
|
|
924f2d1453 | ||
|
|
ea069a108a | ||
|
|
0ad5a18afc | ||
|
|
9ba9ff0ee1 | ||
|
|
ed3a0cb53d | ||
|
|
9bdd01f261 | ||
|
|
00c19f1d8c | ||
|
|
42c52415e1 | ||
|
|
3ead0599a2 | ||
|
|
87c5972e7c | ||
|
|
628c4ef89f | ||
|
|
5e5ce4318f | ||
|
|
a711d24946 | ||
|
|
952e9a315e | ||
|
|
ae4ce59ecf | ||
|
|
7433aa1487 | ||
|
|
6251953fbb | ||
|
|
711f977c7a | ||
|
|
6a22307db7 | ||
|
|
e5314efe67 | ||
|
|
8783454bb0 | ||
|
|
ce562bf99d | ||
|
|
aa4961b305 | ||
|
|
ddcfe6dfaa | ||
|
|
713e2d72db | ||
|
|
c6bb82a6a8 | ||
|
|
95b1b154fa | ||
|
|
3ac16471f1 | ||
|
|
bc2b0add5d | ||
|
|
28041c38a3 | ||
|
|
a328fb84a6 | ||
|
|
bb21c4da3c | ||
|
|
32f7bf2be1 | ||
|
|
21c729a6e5 | ||
|
|
19c9667b5a | ||
|
|
339ab9cb48 | ||
|
|
91455f43d5 | ||
|
|
ba81e8633d | ||
|
|
620eda1c62 | ||
|
|
af473fbfc2 | ||
|
|
60ce8fbd75 | ||
|
|
24dea84c7e | ||
|
|
e32e1349a9 | ||
|
|
160a200b56 | ||
|
|
dcb9e434c6 | ||
|
|
a94888d1c7 | ||
|
|
a5f6dadc6f | ||
|
|
2420c52ee5 | ||
|
|
ecee277cfa | ||
|
|
b92cfa8047 | ||
|
|
bf468e8c48 | ||
|
|
d08aaa0e33 | ||
|
|
1351925f40 | ||
|
|
a679c463dd | ||
|
|
55c31e71c6 | ||
|
|
3e456cf124 | ||
|
|
663c8597ad | ||
|
|
cb4683b688 | ||
|
|
837129f9d2 | ||
|
|
0fc212b907 | ||
|
|
4817914b50 | ||
|
|
29b8ec8ca2 | ||
|
|
09f66dcd77 | ||
|
|
75a958f655 | ||
|
|
3446c2a954 | ||
|
|
99d17af66e | ||
|
|
fd970820c7 | ||
|
|
406198fcf9 | ||
|
|
eb356c0342 | ||
|
|
ca3dfe72c6 | ||
|
|
9d829a5269 | ||
|
|
feb3197e2f | ||
|
|
b3c6b2e885 | ||
|
|
ba3f31418d | ||
|
|
64d2ab15a0 | ||
|
|
32fc81cc9c | ||
|
|
a6c922c480 | ||
|
|
3f01646e48 | ||
|
|
9acd450445 | ||
|
|
9ab94bdd68 | ||
|
|
e99a0af3f3 | ||
|
|
d672271c6a | ||
|
|
aa41d275c6 | ||
|
|
0d1fcc3460 | ||
|
|
6ecd70bac5 | ||
|
|
83cdd49fab | ||
|
|
e667dfe435 | ||
|
|
f06dc97414 | ||
|
|
fc74ea53f8 | ||
|
|
7f689cb542 | ||
|
|
9bc65d7010 | ||
|
|
a35dc6e3a8 |
No files matched your search
@@ -0,0 +1,81 @@
|
||||
name: Build open-source DXC (dxcompiler.dll)
|
||||
|
||||
# Builds x64 Release dxcompiler.dll from the pinned microsoft/DirectXShaderCompiler
|
||||
# tag on a Windows runner so BetterXen does not redistribute Microsoft's prebuilt
|
||||
# release zip or stage the GDK's dxcompiler.dll (#757).
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: DirectXShaderCompiler release tag to build
|
||||
required: true
|
||||
default: v1.9.2609
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: dxc-build-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build-dxcompiler:
|
||||
name: Build dxcompiler.dll (x64 Release)
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Checkout DirectXShaderCompiler
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
repository: microsoft/DirectXShaderCompiler
|
||||
ref: ${{ inputs.tag }}
|
||||
path: dxc
|
||||
submodules: recursive
|
||||
persist-credentials: false
|
||||
|
||||
- name: Configure CMake (x64)
|
||||
run: >
|
||||
cmake -B build -S dxc -A x64
|
||||
-C dxc/cmake/caches/PredefinedParams.cmake
|
||||
-DHLSL_INCLUDE_TESTS=OFF
|
||||
-DENABLE_SPIRV_CODEGEN=OFF
|
||||
|
||||
- name: Build dxcompiler (Release)
|
||||
run: cmake --build build --config Release --target dxcompiler --parallel
|
||||
|
||||
- name: Verify DxcCreateInstance export and collect artifact
|
||||
shell: pwsh
|
||||
run: |
|
||||
$dll = Get-ChildItem -Path build -Recurse -Filter dxcompiler.dll |
|
||||
Where-Object { $_.FullName -match '\\Release\\' } |
|
||||
Select-Object -First 1
|
||||
if (-not $dll) {
|
||||
throw "dxcompiler.dll not found under build/**/Release/"
|
||||
}
|
||||
$bytes = [System.IO.File]::ReadAllBytes($dll.FullName)
|
||||
$marker = [System.Text.Encoding]::ASCII.GetBytes("DxcCreateInstance`0")
|
||||
$found = $false
|
||||
for ($i = 0; $i -le $bytes.Length - $marker.Length; $i++) {
|
||||
$match = $true
|
||||
for ($j = 0; $j -lt $marker.Length; $j++) {
|
||||
if ($bytes[$i + $j] -ne $marker[$j]) { $match = $false; break }
|
||||
}
|
||||
if ($match) { $found = $true; break }
|
||||
}
|
||||
if (-not $found) {
|
||||
throw "DxcCreateInstance export string not found in $($dll.FullName)"
|
||||
}
|
||||
New-Item -ItemType Directory -Force -Path dist | Out-Null
|
||||
Copy-Item $dll.FullName dist/dxcompiler.dll
|
||||
$hash = (Get-FileHash dist/dxcompiler.dll -Algorithm SHA256).Hash
|
||||
Write-Host "Built $($dll.FullName)"
|
||||
Write-Host "SHA-256: $hash"
|
||||
|
||||
- name: Upload dxcompiler.dll artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dxcompiler-${{ inputs.tag }}-win64-release
|
||||
path: dist/dxcompiler.dll
|
||||
if-no-files-found: error
|
||||
@@ -92,7 +92,7 @@ gh issue list --repo MacosPorters/betterxen --state open --search "<event, symbo
|
||||
- **Nothing covers it:** carry on with step 1 below.
|
||||
|
||||
1. **Claim with a draft pull request, before writing the fix.** Branch `track-<a..f>/<slug>` from `origin/main`, push it with an empty commit or the first small change, and open a **draft** pull request titled `[<Stage>] <signature>`. Before opening it, list open pull requests once more; if one now covers the signature, take the next signature instead. A draft with no push for 3 days may be taken over; say so on it.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. Check the contract against the GDK where the GDK covers it.
|
||||
2. **Evidence before code:** find what the build asked for and what it got, from the run report and the diagnostics. **Before you instrument or run the build again, look the call up in the Ghidra results:** `bx-cli report` lists each unimplemented call's callers as `module+offset`, and `bx-cli ghidra <module+offset>` names the decompiled function; search the module's strings too (middleware often prints its own errors and asserts). Run the build only for what depends on run-time state. Check the contract against the GDK where the GDK covers it. ([Order of lookup](docs/process/working-method.md#order-of-lookup).)
|
||||
3. **Smallest fix:** only what removes this blocker. Stay inside the track directories it needs (Section 2); a new cross-DLL export goes through an `[ABI]` pull request first.
|
||||
4. **Test:** every contract the fix introduces gets a synthetic conformance test under `tests/conformance/test_<name>/` that fails without the fix and passes twice in a row. The test is what holds on every machine; your run is only why you looked.
|
||||
5. **Verify:** every command in Section 8.
|
||||
|
||||
+160
@@ -9,7 +9,68 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- **Ghidra first: unimplemented calls name their callers, and `bx-cli ghidra` finds the function.**
|
||||
- `runtime_veh` logs a `stub_caller` event once for each unimplemented call (signature, stub, direct caller): the stub, its caller and one more frame, as `module+offset`. The stub's own event is unchanged, so report signatures don't change.
|
||||
- `bx-cli report` lists those caller chains under each unimplemented call.
|
||||
- `bx-cli ghidra <module> <offset>` (or `<module+offset>`) names the function holding that offset in the configured Ghidra results (`exports/<program>/functions.csv`, image base from `sections.csv`) and its decompiled file.
|
||||
- AGENTS.md Step 3.2 and the working method's new "Order of lookup" say to look the call up in the Ghidra results before instrumenting or running the build again. Ghidra's rank as a source of truth is unchanged.
|
||||
- Tests: `test_stub_caller`, plus unit tests for the report and the lookup.
|
||||
|
||||
### Fixed
|
||||
- **GPU value waits recorded after a write no longer run before it.** Since #791 every `WaitOnBitValueX`-family wait of a command list ran before the list. A title that makes two queues hand over to each other (one list writes a value and then waits for the other's, the other waits and then writes) therefore waited in a cycle that only the 10 s timeout broke, on every frame. Waits recorded before the list's first write still run in front of it; a wait recorded after a write now runs after the list's GPU work and those writes, and later writes are stored once that wait holds. `test_d3d12_gpu_value_order` gains the two-queue case.
|
||||
- **`XCRDAPI`: the Xbox DirectStorage interfaces have the `dstorage_xs.h` slots, and a partial zlib read no longer allocates up to 2 GiB** (#769).
|
||||
- **Factory** (`IDStorageFactoryX`/`X1`/`X2`): slot 3 `CreateQueue(DSTORAGE_QUEUE_DESC*)` creates a queue with auto-submit on, where it used to return `E_NOTIMPL`. Slot 6 is `SetCpuAffinity` and returns an HRESULT; it used to be a `void` `SetDebugFlags`. Slot 7 is `SetDebugFlags`. Slot 9 `GetStats` writes a zeroed 256-byte `DSTORAGE_STATS`, logged as a stub. Slot 10 is `CreateQueue1`, which also checks `DSTORAGE_PRIORITY`. Slots 11 and 12, which don't exist, are gone. `DStorageGetFactory` and `QueryInterface` accept all three factory IIDs.
|
||||
- **File:** slot 4 is `GetHandle`, a new handle the caller closes. It used to be `GetFileInformation`, which returned 0 as the "handle".
|
||||
- **Queue** (`IDStorageQueueX`/`X1`/`X2`): slot 10 `RetrieveErrorRecord` fills the 656-byte `DSTORAGE_ERROR_RECORD`'s count, first HRESULT and command type. Slot 11 `Query` and slot 13 `Query1` report the queue. Slot 12 `EnqueueSetEvent` sets the event, so a waiter wakes; it used to be a stub. The queue answers all three queue IIDs.
|
||||
- **Requests** are read as the 0x48-byte `DSTORAGE_REQUEST`, including `IntermediateSize`, `CancellationTag` and `Name`. `CancelRequestsWithTag` logs its mask and value; requests still run, as the header allows.
|
||||
- **Partial zlib reads:** a read of the first part of a compressed block decodes the whole stream through a 32 KiB window, still checking Adler-32, and writes only `DestinationSize` bytes. It used to allocate `64 × DestinationSize + 256 KiB`, up to 2 GiB.
|
||||
- **Tests:** `test_xcrdapi_xbox_slots` covers the corrected slots and the bounded partial read.
|
||||
- **`xgameruntime`: a delayed task-queue callback no longer holds back the callbacks submitted after it** (#775, part 3). `XTaskQueueSubmitDelayedCallback` put the task in the port's FIFO, and the port waited for it to be due. So one multi-second retry timer blocked every later callback on that port, and on a pool lane a thread-pool thread slept meanwhile. In the GDK the delay elapses before the callback is submitted. Delayed tasks now wait outside the FIFO and a thread-pool timer moves them in when due, so a callback submitted later without a delay runs first. Delayed tasks still pending when the queue closes are drained or cancelled like the rest. `test_xgameruntime` checks both a manual and a serialized queue.
|
||||
- **`d3d12_xs`: `D3D12ConfigureVirtualMemoryX` accepts the DEFAULT page count and the legacy lower bound; `WaitFrameEventX` reports PRIMARY** (#772). These follow the authorized GDK header `d3d12_xs.h`.
|
||||
- `PageTableMemory4MBPageCount` = `D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT` (0) selects the default of 5 pages. It used to be refused with `E_INVALIDARG`.
|
||||
- `D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAG_ENABLE_LEGACY_LOWER_BOUND` (0x1) reports a 1 GiB minimum graphics address. A configuration with this flag used to be taken as an unrecognized block and returned `S_OK` without writing its outputs.
|
||||
- The outputs are now written even when the call returns `E_FAIL` because a device already exists, as the header documents.
|
||||
- `WaitFrameEventX` writes `D3D12XBOX_SIGNALED_OBJECT_INDEX_PRIMARY` (0xFFFFFFFE) when the frame event satisfied the wait, `NONE` only on a timeout, and otherwise the index of the first signalled ancillary object. A title testing for PRIMARY used to see every frame origin as a timeout.
|
||||
- **`xmem`: allocations follow their `XALLOC_ATTRIBUTES`, physical page numbers are reused, and `XMemVirtualQuery` / `XMemTransferMemory` have the GDK prototypes** (#768, #642).
|
||||
- `XMemAllocDefault` returned 64-byte-aligned memory whatever the attributes asked for. It now honours the alignment code (`1 << code`, up to 512 KB), aligns a block of at least one 64 KB or 2 MB page to that page, and keeps an `Address32BitMapping` block below 4 GB. `XMemFreeDefault` frees either kind.
|
||||
- `XMemAllocatePhysicalPages` gave every call new page numbers on the next 16 MB boundary and never reused freed ones, so after 8,192 calls every call failed. A call now takes the lowest free 16 MB-aligned numbers. The numbering rules are unchanged. `XMemFreePhysicalPages` no longer zeroes the caller's `PageArray`, which the GDK declares `_In_reads_`.
|
||||
- `XMemVirtualAlloc` with `MEM_2MB_PAGES` places the allocation on a 2 MB boundary, and `XMEM_GRAPHICS_32BIT_ADDRESS` keeps a system-placed plain allocation below 4 GB.
|
||||
- `XMemVirtualQuery(Process, Address, Buffer)` fills `XMEM_BASIC_INFORMATION`: the `VirtualQuery` fields, the `XMemFlags` the reservation was made with (0 for memory xmem did not reserve) and zero tags. It had the Win32 `VirtualQuery` shape, so a title passing `GetCurrentProcess()` always got FALSE.
|
||||
- `XMemTransferMemory(TransferType, TransferSize)`: a size of 0 succeeds. Title-to-system lowers the title cap by the size rounded up to 2 MB, if the free budget covers it. The tools transfers fail with a logged `ERROR_NOT_SUPPORTED`, since tools memory is not modelled. It used to be a `memmove(dst, src, bytes)`.
|
||||
- `test_xmem_gdk_forms` covers each of these with values from the GDK header.
|
||||
- **`d3d12_xs`: command-list and device forwards no longer pass wrapper objects or title addresses that sit inside structures** (#771). `Barrier`, `BeginRenderPass`, `DispatchRays`, `BuildRaytracingAccelerationStructure` (bottom-level; top-level builds are logged via `BX_VTABLE_STUB_LOG` until GPU-memory instance descriptors are translated), `EmitRaytracingAccelerationStructurePostbuildInfo`, `WriteBufferImmediate` and `SOSetTargets` are hand-written: embedded interface pointers are unwrapped, descriptor handles and GPU addresses are translated, and temporary allocation failures are logged instead of silently dropped. `CreateStateObject` and `AddToStateObject` are changed from plain forwarders to logged `BX_VTABLE_STUB_LOG` stubs because their subobject payloads are untyped and carry wrapper pointers. `GetRaytracingAccelerationStructurePrebuildInfo` stays forwarded because D3D12 only inspects counts, formats, flags, and nullness rather than dereferencing GPU addresses. The generator refuses a plain forward for any other method whose parameters are structures holding an interface pointer, a GPU address, or a descriptor handle. New test `test_d3d12_forwarder_struct`.
|
||||
- **`dxbc-accc` reads a 16-byte FSPX section table `{id, offset, size, 0}`, so a container whose first section begins at `16 + count * 16` classifies as ACCC** (#797). The 12-byte descriptor stays, because this repository's own synthetic fixtures use it (the `dxbc-accc` tests and `tests/conformance/test_shader_gate`). A table is 16-byte only when every entry's fourth word is 0 and the first section's offset equals `16 + count * 16`; every other table keeps the 12-byte parse. For 16-byte tables, section 1 is treated as opaque (its bounds are validated and recorded, while stage stays unknown unless supplied by another chunk) instead of requiring the 12-byte synthetic stage layout. A section that starts inside the header plus the table in use is still a layout mismatch.
|
||||
- **`xapu.dll` exports have the `xapu.h` prototypes** (#777). `XApuConnect`, `XApuEnqueueCommand`, `XApuDequeueResult` and `XApuGetResultCount` had BetterXen-defined shapes; called with the documented argument list, `XApuConnect` wrote the connection id through its first argument (the input block) and left the caller's handle and output parameters unset. The five exports now take the prototypes of the authorized GDK header `xapu.h`. Connecting succeeds and writes the handle and `XApuConnectOutputParameters`: `baseData`, and `resultReadyEvent` when the connect options request it. Each connection has its own command queue; a dequeued result echoes the submitted command id and carries no decoded audio. The APU device is not modelled and that is logged (`BX_STUB_LOG`). A dequeued result's `errorCode` is `S_OK` for a command that was not processed, and `BX_STUB_LOG` records it. `test_xapu_signatures` covers the argument lists, and `test_audio_input` and `test_integration_boot` call them the same way.
|
||||
- **`d3d12_xs`: a compute pipeline the host cannot make comes back as the logged null pipeline, so the target build no longer exits with status 5 on its next dispatch** (#722). Console compute shaders are not translated yet (#746), and `CreateComputePipelineStateX` returned `E_NOTIMPL` unless `BX_NULL_RENDER=1` was set. The target build keeps the shader program it was making even then, with no pipeline in it, and the next dispatch through that program read inside the missing pipeline (call-site observation). Refused compute pipelines now return the null pipeline whatever `BX_NULL_RENDER` says, logged as before (`pipeline_refused ... null pipeline returned`); dispatches with it are skipped and logged, as every untranslated dispatch is. Serialized and derived pipelines still fail. New test `test_d3d12_compute_placeholder`.
|
||||
- **`d3d12_xs.dll`: a placed texture has one host storage; host resources for title memory are released** (#782, #745).
|
||||
- **One storage per texture.** A texture placed in title memory now gets its contents uploaded into its host shadow itself, not into a side copy. On the console a placed texture has one storage, and now every view and copy command of it sees the texels; before, only views resolved for translated draws did, and copy commands read an empty texture. Read-only shadows are made with simultaneous access, so the upload promotes them from COMMON without barriers that contradict the title's own. A drawn texture no longer occupies a second host texture.
|
||||
- **Upload buffers.** A texture's upload buffer is released once the GPU has copied from it, and made again only if a later check finds the title memory changed.
|
||||
- **Implicit shadows.** `CreatePlacedRawShaderResourceViewX` and `CreatePlacedRawUnorderedAccessViewX` back each view with a host resource of the shim's own, which was made per (address, shape) and kept for the life of the process. A new view whose title memory overlaps an older implicit shadow of another address or shape now retires that shadow. The host resource is released 64 queue submissions later. Translated-draw markers of it then resolve to null views, and a constant view's fallback that lay in it is dropped.
|
||||
- **Effect on memory.** The target build's footprint on a 16 GB Mac (Series S profile) is about the same as before, 10 to 11 GB after about two minutes. Most of it is the title's own memory and one host texture per placed texture, which this design needs.
|
||||
- **Tests.** `test_d3d12_console_texture_contents` copies each placed texture out after a translated draw and checks every texel. `test_d3d12_placed_implicit_release` views four slots 256 times with new shapes and checks that at most one host resource per slot stays live.
|
||||
- **`d3d12_xs`: GPU value writes and waits in title memory take effect in list order, and Execute no longer blocks on them** (#773). `Wait32/64BitValueX` were all evaluated on the CPU before a submission went to the host (a busy loop of up to 10 s each), and every `Write*BitValue*X` was stored only after the host had finished the whole submission, so each Execute that carried a write waited for the GPU, and a wait on a write earlier in the same submission could only time out. A submission that carries them is now split at its lists: a list's waits hold the host queue on a fence before it (the fence slot itself, or a fence a per-queue worker signals once the value holds, checked with sleeps instead of a spin), and its writes are stored by that worker when the host GPU has finished the list. Inside one list, waits still count as being at its start and writes at its end. New test `test_d3d12_gpu_value_order` (a wait on a write earlier in the same submission, a wait on a value the CPU stores later, two writes to one address).
|
||||
- **`d3d12_xs`: `GetResourceAllocationInfo` answers textures with `Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN` in the console's default tiling** (#708). On the console `UNKNOWN` selects the default tiling mode (GDK documentation of `XG_RESOURCE_DESC::Layout`), but `d3d12_xs` passed such textures to the host, which has no console tiling. The target build sizes some of its loads that way (call-site observation): a 128x4 `R16G16B16A16_UNORM` texture came back as 4096 bytes where the GDK's XG gives 16384 (4 KB tiles, layout `0x105`), so it asked for a quarter of a 16 KB compressed chunk; its loader asserts on that, and `XCRDAPI.dll` refused the 47 such requests per run. With the GDK's XG loaded, these textures now get XG's size and alignment for the layout as given, as #710 does for explicit console layouts; buffers keep the host's answer. `test_d3d12_gdk_xg_sizes` checks an `UNKNOWN`-layout texture and uses a buffer as the host-answered case.
|
||||
- **`chad.dll`: `XDspConnectWithMaximumStreamLimit` connects again, so the target build no longer stops after 64 frames** (follow-up to #780). Since #780 connecting was refused with `E_NOTIMPL`, and the target build then hits its own assert a few seconds later and exits with status 3 (every default run; the same `main` with the earlier `chad.dll` runs on). Connecting now succeeds with a placeholder client handle and is logged as not modelled (`BX_STUB_LOG`); activating a stream on it is refused with `E_NOTIMPL`, and `XDspDisconnect` closes it. The prototypes from #780 stay, so nothing is written outside the documented outputs. `test_audio_input` and `test_integration_boot` check the new answers.
|
||||
- **`d3d12_xs.dll`: a texture the title rewrites every frame is copied as often as it changes** (#745). Texture contents from title memory were re-checked at most every 250 ms after a change. So a texture the title rewrites every frame (the intro movie's luma and chroma planes, decoded on the CPU) was re-copied at most 4 times a second, and the video stuttered: measured, about 10 re-copies a second of the luma planes during the movie. A texture found changed is now checked again at its next draw; one found unchanged waits 16 ms, doubling up to 4 s as before. Checks are a sampled hash, and only a change copies. Measured during the movie: 30 re-copies a second of the luma planes, the video's own rate, and 60 of the two chroma planes. `test_d3d12_console_texture_contents` gains a fourth round, in which the title rewrites a texture right after a copy and the next draw must show it.
|
||||
- **`chad.dll` exports have the `xdspaudio.h` prototypes** (#776). `XDspConnectWithMaximumStreamLimit`, `XDspActivate` and `XDspSubmitCommand` had BetterXen-defined shapes; called with the documented argument list, `XDspConnectWithMaximumStreamLimit` took `baseBufferLength` for its out pointer and wrote a NULL to that address. The five exports now take the prototypes of the authorized GDK header. XDSP is not modelled: connecting is refused with `E_NOTIMPL` and a NULL client handle (logged through `BX_STUB_LOG`), and the calls that take a client or stream handle answer `E_HANDLE` with their documented outputs cleared. `test_audio_input` and `test_integration_boot` call them with the documented argument lists; `test_integration_boot` reports the stage as pending, as for its other stubs. The DSP-only fields of the audio command ring are removed (`xapu.dll` still uses it; its signatures are #777).
|
||||
- **`xgameruntime`: the IXStore dispatch table covers every slot titles call** (#774). The table behind `QueryApiImpl` for the store interface (CLSID `0DD112AC-…`, IID `B09D803C-…`) had 40 entries, while the console runtime library calls it at slots up to 69 (call-site observation of a project-authorized target build); such a call read past the end of the table and jumped to whatever followed it. The table now has 80 entries, like the IXStoreDurables table under the same CLSID, and every slot without an implementation is the logged `E_NOTIMPL` stub. `test_xgameruntime` calls slots 40 to 79 through `QueryApiImpl`.
|
||||
- **`d3d12_xs`: a typed buffer view from `CreatePlacedRawShaderResourceViewX` is counted in its format's elements.** The constant-view marker counted every non-structured view at 4 bytes per element, so a typed view (for example `R32G32B32A32_FLOAT`, 16 bytes) with a non-zero first element pointed into the wrong part of the buffer. Typed views now use the format's size; a format of unknown size or a block-compressed one gets no marker. Follow-up of the review note on #767. New test `test_d3d12_console_typed_buffer_constants`.
|
||||
- **`d3d12_xs.dll`: translated draws find texture views made by `CreatePlacedRawShaderResourceViewX`** (#745). That function makes a view of memory placed at an address from a resource description, with no resource object behind it; "raw" does not mean a byte-address buffer. The target build makes the views of its menu textures this way, once per frame, and copies them into each draw's descriptor table. The handler made the host view but did not write the descriptor marker that `CreateShaderResourceView` and `CreatePlacedShaderResourceViewX` write, so with `BX_CONSOLE_SHADERS=1` every such entry was left unresolved and the menu drew without its artwork. A texture view now leaves that marker, and the texture's contents come from title memory like any other placed texture's. Buffer views are not changed here (#767 makes them constant views). `test_d3d12_console_texture_contents` draws a third texture, described but never created, through a view made this way, and checks every pixel in all three rounds.
|
||||
- **`d3d12_xs`: PresentX logs what its composition leaves out.** A plane given as two resources (a colour texture and a separate alpha texture, such as an RGBE + A8 pair) is composed from its first resource only, and with several views (`D3D12XBOX_PRESENT_PARAMETERS::ViewCount`) only the first view is composed. Both were dropped without a word; each is now logged once (`presentx_xbox`). Follow-up of the review notes on #758; `test_d3d12_presentx_planes` checks both lines and that the frame is unchanged.
|
||||
- **`gfx10-translate`: image instructions in the NSA encoding read their addresses from the registers it lists.** MIMG with NSA (non-sequential address) set lists the address VGPRs after the first one byte each in extra words. The decoder counted those words but read the addresses as a contiguous range from the first, so a 2D `image_sample` of `[v4, v7]` sampled at `(v4, v5)`. The list is now decoded, printed as LLVM prints it, and used by `image_sample`, `image_load` and `image_gather4`. Tests: NSA vectors from llvm-mc in `llvm_vectors.txt` (the vector test now compares up to runs of spaces: llvm-mc prints two after an NSA mnemonic), and `image_instructions_read_nsa_addresses`.
|
||||
- **`d3d12_xs`: translated pipelines bind input elements to the vertex shader by semantic.** The host input layout took the title's elements in their layout order as `ATTR0`, `ATTR1`, …, while the translated vertex shader reads input register r as `ATTR<r>` and the console shader's input signature (ISG1/ISGN) gives each register its semantic. Direct3D 12 links elements to shader inputs by semantic name and index, not by order, so a layout listing its elements in another order than the signature fed the wrong data to the shader (for example colour in place of texture coordinates). Each input register now gets the element whose semantic the signature names; a container without a signature keeps layout order, and a missing element is logged as the reason the pipeline is not drawn. New test `test_d3d12_console_input_semantics`.
|
||||
- **`d3d12_xs`: a buffer view made with `CreatePlacedRawShaderResourceViewX` reaches translated draws as a constant buffer.** The view wrote nothing into the title's 32-byte descriptor, so a title that copies it into a draw's table with plain stores copied zeros, and a console shader that reads it with scalar buffer loads (a constant buffer) read zeros. The view now leaves a marker of a constant view of its title memory, and translated draws get the buffer's current contents. New test `test_d3d12_console_raw_buffer_constants`.
|
||||
- **`gfx10-translate`: scan all `XBCH` candidates and support version 2/3 payloads** (#721). `container_code` previously stopped at the first `b"XBCH"` byte sequence in a container, so incidental `b"XBCH"` bytes earlier in the blob (for example in `STAT` or `DXIL` bitcode) caused it to read garbage sizes and fail with `XBCH record: compressed size past the end`. It now scans all `b"XBCH"` occurrences, validates the 24-byte header, bounds, version (`2` uncompressed `FSSM`, `1` and `3` zlib-compressed `FSSM`), and `FSSM` magic, and skips non-matching candidates. Covered by synthetic unit tests in `gfx10_translate::container::tests`.
|
||||
|
||||
### Changed
|
||||
- **Open-source DXC (`dxcompiler.dll`) replaces the GDK's shader compiler as the primary source** (#757, ADR 0010).
|
||||
- `.github/workflows/dxc-build.yml` builds x64 Release `dxcompiler.dll` from `microsoft/DirectXShaderCompiler` at pinned tag `v1.9.2609` on a Windows runner and uploads it as a workflow artifact.
|
||||
- `bx-cli setup --dxc-dir <dir>` (and `BX_DXC_DIR`) records the local open-source DXC folder in `local.conf` (`dxc_dir`).
|
||||
- `bx-cli run` (`gdk_libs::resolve`) stages `dxcompiler.dll` from `dxc_dir` first, falling back to the GDK's `dxcompiler.dll` only if no open-source build is configured. `dxcompiler.dll` is recognised by name and the `DxcCreateInstance` export, and `dxil.dll` is no longer staged.
|
||||
- ADR 0010, `docs/research/upstream-registry.md`, and `docs/research/component-reuse-matrix.md` record the source build and its `LICENSE.TXT` / per-file licence check.
|
||||
- **`docs/roadmap.md`, Picture stage, corrected to what was built.** The translator item said "GFX10-to-DXIL"; it produces HLSL, and `d3d12_xs` compiles that with the GDK's `dxcompiler.dll` at first draw. The item also said each rule is checked against the console compiler's output; it now says how rules are checked today (public assembler encodings and the instruction's definition) and where the console compiler has been used (the root-data layout). Dated state notes record that the capability checks were not done first, what is translated at run time, and what is open (#744, #745, #746). ADR 0010's title now names the shader compiler it has covered since #734; its file name is unchanged.
|
||||
- **`README.md` rewritten for the current state** (2026-11-30). It described the M0–M6 milestone plan with M2 active and listed as unimplemented several things that exist. It now gives the stage (Picture) and what the target build does today, the stages from `docs/roadmap.md`, an architecture diagram with the run-time shader translation and the GDK libraries, the current repository layout and `bx-cli` commands, the hard requirements for contributing, and a section that separates what the repository's tests verify from what was observed on the target build and from what is not claimed. `docs/architecture/parallel-tracks.md` is revised the same way: it listed the M0–M6 milestones and an issue-claiming protocol that `AGENTS.md` has replaced; it now gives the current directory table and points to `AGENTS.md` and the roadmap for the rules and the stages.
|
||||
- **Current stage: Picture** (`docs/roadmap.md`), by the repository owner's decision on 2026-11-30. Boot is marked as left without its ten-run gate having been run under the run protocol. The first frames and the menus are reached, and the open work is translation, textures and stability. The new pinned ladder issue carries the live status. The repository owner also accepted the LLVM-generated opcode table and test vectors of `gfx10-translate` (`docs/research/upstream-registry.md`).
|
||||
- **`CONTRIBUTING.md` is a short entry point for new members, consistent with AGENTS.md.** It covers the hard requirements (the target build, the GDK and the Ghidra results, distributed among members), setup (`setup --find`, `preflight`), the current way of working (pick order, checking for existing work, draft pull request claims with the 3-day rule, tests, Section 8), and running the target build with its diagnostic switches. The outdated workflow is removed: issue-comment claims, the 7-day rule and the Wave 1 backlog. The licensing, sign-off and merge sections are unchanged.
|
||||
- **Check for existing work before investigating any problem the game shows** (AGENTS.md Section 0 Step 3 and Section 7, `docs/process/working-method.md`). Every problem met while running the game, not only the picked blocker, is searched for in open and merged pull requests and open issues by its log event, stub symbol, error code and files. An open pull request that covers it is checked out and worked on, never duplicated. Prompted by a duplicate fix for physical-page DirectStorage requests made alongside #707.
|
||||
@@ -31,6 +92,84 @@ 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`: image sample/load/gather forms and `off`-address buffer loads** (#718).
|
||||
- **Image instructions:** `image_sample*` (`_l`, `_b`, `_d`, `_o`, `_cl`), `image_load_mip`, and `image_gather4*` (`image_gather4`, `_o`) across `1D`, `2D`, `3D`, `1D_ARRAY`, and `2D_ARRAY` textures (`Sample`, `SampleLevel`, `SampleBias`, `SampleGrad`, `Load`, `Gather*`). Fixed `decode::address_count` so `_cl` and `_cd` are not treated as comparison `_c`; comparison (`_c`) forms stay refused until a comparison sampler slot is added to the root-signature ABI (`d3d12_xs` `widen()`).
|
||||
- **Buffer loads:** `tbuffer_load_format_{x,xy,xyz}` and `off`-address (`!idxen && !offen`) loads on root buffers, table-bound constant/buffer descriptors, and vertex buffers.
|
||||
- **Refused with a reason:** `buffer_load_format_*` (its data format is in the buffer descriptor, not known at translation) and `v_interp_p2_f16` (the result's register half and the packed attribute layout aren't sourced). `decode` reads the 16-bit interpolation forms.
|
||||
- **Tests:** `address_count_matches_isa`, `decodes_f16_interpolation`, `image_sample_forms_and_dimensions`, `image_sample_grad_load_mip_and_gather`, `vconst_overwrite_clears_constant_offset`, `typed_buffer_loads_refused_off_loads_translated`, and `f16_interpolation_refused` from `llvm-mc` encodings.
|
||||
- **`xg_xs` computes requested swizzle modes with AMD addrlib** (#756). Mesa `src/amd/addrlib` at `mesa-25.2.0` (`0b97dcdd`) is vendored unmodified under `shims/xg_xs/third_party/addrlib`. A title that asks for a swizzle mode other than the one-tile `64KB_S` case (still the public D3D12 standard swizzle) gets that mode's gfx10 layout: size, alignment, mip offsets, texel offsets and copies. `XGSuggestSwizzleMode` suggests `64KB_S` for a 2D colour texture and `64KB_Z` when the format has a stencil plane. `XGComputeTexture2DLayout` and `XGEnableExclusiveLocking` are implemented in the same file and are not exported: `abi/defs/xg_xs.def` still lists the two functions titles import. Linear layouts are unchanged.
|
||||
- **`docs/research/console-shader-abi.md`: directly indexed descriptor heaps** (SM 6.6 `ResourceDescriptorHeap` / `SamplerDescriptorHeap`). Measured with probes of our own compiled by `xdxc`: the heap pointers follow the root data (resource heap, then sampler heap), as 32-bit pointers, with 32-byte resource and 16-byte sampler descriptors. The target build's pixel shaders with `SAMPLER_HEAP_DIRECTLY_INDEXED` take their sampler that way; the translator does not model it yet.
|
||||
- **Root signature layouts reach the translator at run time** (#715, #720; with `BX_CONSOLE_SHADERS=1`).
|
||||
- `bx_shader_bridge.dll` exports `bx_shader_translate_pair_rooted` (contract #741): the translation given the root parameter list and the signature's flags. `bx_shader_translate_pair` is the same call with no layout. The export list has 118 names across the 17 DLLs.
|
||||
- `d3d12_xs.dll` keeps each root signature's parameter list with its host object and passes it when a console pipeline is first drawn. With an older bridge it falls back to the table-only translation.
|
||||
- `SetGraphicsRootShaderResourceView` and `SetGraphicsRootConstantBufferView` give an address in plain title memory a host buffer, copied at submission. A root buffer has no size, so what is readable there is copied, up to 256 KiB for an SRV and 64 KiB for a CBV; a shader that reads further sees zeros.
|
||||
- Tests: `test_d3d12_console_pipeline_first_draw` gains a root SRV case, a vertex shader that pulls its positions by vertex index, drawn from an upload buffer and from plain process memory (46 checks); `tests/translate_pair.rs` covers the export, including inconsistent layouts.
|
||||
- On the target build every vertex/pixel pair it draws with in its first two minutes now translates; none is refused. The picture is unchanged (the menu's bars).
|
||||
- **`gfx10-translate`: root signature layouts** (#715; the rules are measured in `docs/research/console-shader-abi.md`). `translate_pair_rooted` and `translate_blobs_rooted` take the pipeline's root parameter list (`RootLayout`).
|
||||
- Each packed root value is mapped to its parameter: a table pointer is one value, a root CBV, SRV or UAV two, a constant one each. Both forms are read: registers from `s8`, and root data in memory through `s0` and the low byte of `s1` (`memory_based`).
|
||||
- A descriptor table is the parameter its pointer belongs to, no longer its register's position.
|
||||
- A root CBV, SRV or UAV, whose buffer descriptor the shader builds from the address, becomes a buffer at the title's own register and space. Indexed (`idxen`) and byte-offset (`offen`) loads and `s_buffer_load` read it.
|
||||
- A constants parameter becomes a constant buffer at its own register and space.
|
||||
- In a vertex shader translated with a layout, `v0` read before it is written is `SV_VertexID`, and `v_add_nc_u32` is a real addition (without a layout it is still dropped, as the prototype did).
|
||||
- Each root descriptor or constants parameter a stage reads adds a `USE ROOT <parameter>` layout line.
|
||||
- Without a layout nothing changes: the golden pairs still match.
|
||||
- `bx-cli shader translate` takes `--root <layout>`, e.g. `T,S:0:0,C2:1:0,B:2:0,mem`.
|
||||
- Tests: `root_layout_register_form`, `root_layout_memory_form`, `root_layout_decides_what_a_register_holds` and `root_buffer_byte_offsets_and_the_vertex_index`, from our own assembly through llvm-mc.
|
||||
- The last vertex/pixel pair the target build's menus draw with that was refused (a single root SRV, vertex pulling) now translates with its layout, and its HLSL compiles with dxc. Nothing passes a layout at run time yet: the bridge export (#741) and `d3d12_xs` follow.
|
||||
- **`docs/research/console-shader-abi.md`: root data of vertex and pixel shaders** (#715). Six probes of our own, compiled with the console `xdxc` (the ACO path that ACCC containers carry): root data starts at `s8` in root-parameter order; a table pointer takes one register, a root constant one per value, a root SRV or CBV two; no alignment padding; stage visibility does not renumber. This is the measurement behind passing the root-signature layout to the translator. With `XBOX_FORCE_MEMORY_BASED_ABI`, which the target build's root signatures set, the same packed data is read from memory at four bytes per root dword, through an address in `s0` and the low byte of `s1`.
|
||||
- **`d3d12_xs.dll`: descriptors the title copies itself reach translated draws** (#720; with `BX_CONSOLE_SHADERS=1`). On the console a descriptor is 32 bytes at its handle, and the target build fills per-draw tables with `memcpy`, so the host heap held nothing there.
|
||||
- Every `CreateConstantBufferView` and `CreateShaderResourceView` also writes a marker into the title's descriptor memory. `CopyDescriptors` and `CopyDescriptorsSimple` copy the title-side bytes too.
|
||||
- Each translated draw records the tables bound to its list. At submission, the entries its shaders read are found through their markers and written to the host heap at the same index.
|
||||
- A constant buffer's bytes are copied from title memory into an upload ring at submission.
|
||||
- An entry without a marker is left as the host heap has it and logged (`console_descriptor`).
|
||||
- Test: `test_d3d12_console_pipeline_first_draw` gains a case with a view copied by Direct3D and then by hand into the bound table (36 checks).
|
||||
- On the target build about 25,000 entries were resolved in a 110 s run. The frames are still black: the pipelines that would fill the presented buffer are refused by the translator (a 3D `image_sample_lz`, a buffer loaded from a root register) and compute is not translated.
|
||||
- **`d3d12_xs.dll`: console pipelines are translated when first drawn** (#720; opt-in with `BX_CONSOLE_SHADERS=1`).
|
||||
- A stream pipeline the shader gate refuses as console code, when it is a plain vertex/pixel pair, is kept with its stream instead of becoming a bare null pipeline.
|
||||
- At its first draw the pair is translated by `bx_shader_translate_pair`, the HLSL is compiled with the GDK's PC `dxcompiler.dll`, and a host pipeline is created from the title's own stream with the shaders, the input layout and the bound render-target formats substituted. One host pipeline is kept per bound format set.
|
||||
- Compiled shaders are kept on disk (`BX_SHADER_CACHE`, default `%LOCALAPPDATA%\BetterXen\shader-cache`), named by the hash of their HLSL source, so a translator change never reuses an old result.
|
||||
- Every root signature is widened with the register spaces translated shaders use (`CreateRootSignature` now goes through `pipelines.cpp`).
|
||||
- A pair that cannot be translated yet is not drawn, and its reason is logged (`console_pipeline`).
|
||||
- `bx-cli run` stages the GDK's `dxcompiler.dll` and `dxil.dll` with the other GDK libraries (ADR 0010) and passes `BX_CONSOLE_SHADERS` and `BX_SHADER_CACHE` to the guest.
|
||||
- Test: `test_d3d12_console_pipeline_first_draw` draws a red ramp with a console pair of our own into two target formats, checks the disk cache on a second pipeline and the logged reason of an untranslatable pair (25 checks; it skips without `--gdk-libraries`).
|
||||
- Not yet: the title's own descriptors and textures reach translated draws only in follow-up changes, so the target build still shows no picture.
|
||||
- **`bx_shader_bridge.dll`: `bx_shader_translate_pair`** (#720, contract in `abi/include/bx_shader_bridge.h`, #732). Translates a console vertex/pixel pair to HLSL with `gfx10-translate`.
|
||||
- Returns the two sources, the layout lines the host pipeline needs (`FETCH`, `ATTR`, `USE CB`, `USE TEX`) and the cache keys (64-bit FNV-1a of each input).
|
||||
- A stage the translator does not model returns `BX_SHADER_ERR_UNSUPPORTED` with a one-line reason and the keys, so a refusal can be cached.
|
||||
- `bx_shader_free_pair_translation` frees every buffer. The export list has both names (117 exports across the 17 DLLs).
|
||||
- Nothing calls it yet: `d3d12_xs` using it at first draw, with DXC and a disk cache, is the next step of #720.
|
||||
- Tests: `test_shader_bridge_translate` calls the built DLL (25 checks); `tests/translate_pair.rs` compares the output through the C entry point with the reference translator's golden files.
|
||||
- **`gfx10-translate`: `image_sample` and `image_sample_lz` on 3D textures** (#718). MIMG `dim` 2 (`SQ_RSRC_IMG_3D`) reads three address registers, the normalized coordinates s, t and r (RDNA 2 ISA); the sample becomes `Texture3D.Sample`/`SampleLevel(smp0, float3(...), 0)` and the texture is declared `Texture3D`. Samples now go through the same texture check as `image_load` and `image_gather4_lz`: a texture read with two dimensions, cube maps, other dimensions, and 16-bit addresses or data (`a16`, `d16`, `tfe`) are refused instead of being translated as 2D. In the target build this translates one more vertex/pixel pair that its menus draw with. Tests: `image_samples_on_3d_textures`, `refuses_cube_and_a16_samples`.
|
||||
- **`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 stays refused, and so does `op_sel` on a 32-bit source. 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`: SDWA, DPP, and `v_fma_mix` half select** (#719).
|
||||
- **SDWA** (VOP1/VOP2): a source byte or word is zero- or sign-extended, float `abs` then `neg` apply, then `omod` and `clamp` on an f32 result, then the result is written into the selected destination slice (`UNUSED_PAD`, `UNUSED_SEXT`, or `UNUSED_PRESERVE`). A scalar source is read from the extension word. Reserved selectors, and `clamp` or `abs` on an integer instruction, are refused.
|
||||
- **VOPC SDWA** uses the same source modifiers and writes the mask to `vcc` or the SGPR the word names. DPP compares are refused: gfx1030 does not encode them.
|
||||
- **DPP16**, on the translator's 32-lane waves: `quad_perm`, `row_shl` / `row_shr` / `row_ror`, `row_mirror`, `row_half_mirror`, `row_share`, and `row_xmask`, as `WaveReadLaneAt`. A shift that leaves the row of 16 reads 0 when bound control is set; when bound control is clear the write is disabled and the destination keeps its old value (the same for an inactive source lane when `fi` is clear in structured mode). A clear `row_mask` or `bank_mask` bit keeps the old destination. Bank `k` is lanes `4k..4k+3` of each row of 16, selected by `(lane >> 2) & 3`. `wave_*` and `row_bcast` are refused.
|
||||
- **DPP8**: the eight 3-bit selectors within each group of 8 lanes.
|
||||
- **`v_fma_mix*`**: `op_sel` takes the high half of an f16 source (`op_sel_hi` set), and `clamp` saturates the f32 product-sum before it is packed. `op_sel` on an f32 source is refused.
|
||||
- Tests `sdwa_and_dpp_forms` and `refuses_unmodeled_sdwa_and_dpp` use llvm-mc encodings. A selector or DPP control the assembler will not emit is the llvm-mc word of a legal neighbour with that field replaced.
|
||||
- **`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 +261,27 @@ 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
|
||||
- **`d3d12_xs.dll`: `PresentX` composes its planes** (authorized GDK documentation, *Hardware overlays*). It copied plane 0 alone to the window and logged that plane 1, rectangles and scaling were not applied. The target build presents its scene in plane 0 (1920×1080) and its UI in plane 1 (3840×2160), so its first menus, drawn correctly into plane 1, never showed. Planes are now drawn in order, plane 1 in front, as premultiplied alpha (`ONE`, `INV_SRC_ALPHA`) over transparent black, each scaled from its source rectangle (`pSrcViewRects`, texels) to its destination rectangle (`pDestPlacementBase`, normalized), into a texture the size of the swapchain that is copied to the back buffer and dumped by `BX_PRESENT_DUMP`. The shaders are compiled at the first such present with the GDK's PC `dxcompiler.dll`; without it plane 0 is copied as before (logged). Colour spaces other than RGB full G2.2 P709 are composed as SDR in plane order (logged once). One plane without rectangles is copied as before. `test_d3d12_presentx_planes` presents two planes of its own with and without rectangles and checks the composed frames.
|
||||
- **`d3d12_xs.dll`: texture contents are uploaded by the GPU** (follow-up of #747). The texels of a texture placed in title memory were written into its copy from the CPU (`WriteToSubresource`), on the submitting thread; for the target build's two continually rewritten 3840×2160 textures that cost about 30 % of the frame rate. They are now written into an upload buffer of the copy's own (rows copied, or untiled by XG straight into it) and copied by the GPU, on a list of the shim's own executed on the submitting queue ahead of the title's lists; the copy lives on a default heap in the shim's own states. An upload buffer is not rewritten until the GPU is past its last copy, and buffers of released textures are freed only then.
|
||||
- **`d3d12_xs.dll`: a texture placed in title memory shows its pixels in a translated draw** (#745). With `BX_CONSOLE_SHADERS=1`, when a translated draw reads a texture that `CreatePlacedResourceX` placed in title memory, its contents are copied from that memory into a CPU-writable copy of the host texture, which the view then reads: the linear console layout (`0x100`) row by row at its 256-byte pitch, other console layouts untiled through the GDK's XG library (`CopyFromSubresource`, ADR 0010). A view reads the copy only once a copy has succeeded; until then, and after a failure, it reads the host texture and the next draw tries again. So that textures still being streamed fill in, a later draw checks a hash over a sample of the title memory (64 bytes every 64 KiB), at an interval that starts at 250 ms and doubles up to 4 s while nothing changes; only a change copies the texture again (logged). The contents live in this side copy, not in the host texture: copy commands and other views read the empty host texture, and the first `CopyTextureRegion(X)` out of such a texture is logged. Render-target, depth and UAV textures are not copied over. `CreatePlacedShaderResourceViewX` now writes the descriptor marker that `CreateShaderResourceView` writes, so translated draws find views made that way. Before, every such texture was sampled empty. `test_d3d12_console_texture_contents` draws a linear and a tiled texture of its own (through a stand-in XG), with a view made each way, and checks every pixel over three rounds: a copy from unreadable memory, its retry at the next draw, and a copy again after the title rewrites one texture (and not of the unchanged one).
|
||||
- **`d3d12_xs.dll`: a translated pipeline that reads a root constants or root descriptor parameter is no longer refused or mistaken for a table read** (#744). The shim read the translator's `USE ROOT <parameter>` layout line as `USE CB <entry>`: as a constant-buffer read of entry `<parameter>` of root parameter 0's table. With a parameter index of 8 or more the pipeline was refused ("reads table entry 8, beyond the 8 widened ones") and drew nothing; below 8 each submission looked up a table entry the shader never reads and logged it as an unresolved descriptor, which was most of the `console_descriptor` warnings on the target build's first screens and hid the real ones. Only `USE CB` and `USE TEX` lines now name table entries; other kinds are ignored, as `abi/include/bx_shader_bridge.h` says. `test_d3d12_console_root_constants` draws with a vertex shader that reads root parameter 8.
|
||||
- **xmem: remapping some pages of a reservation no longer takes its other pages out** (#729). A run mapped with one call was one view, and remapping part of it unmapped the whole view and mapped the rest back, so a title thread reading an untouched page could fault (the #722 retry turned that into a wait) or, rarely, read other data. The console's page-table update is atomic.
|
||||
- Every 64 KB page of an `XMEM_MAPPABLE` reservation is now its own view, so a remap replaces only the views of the pages it names.
|
||||
- Mapped views are found by address instead of by walking all of them: with about 100,000 views, the per-page lookups of `CopyPageMappingsBatchX` stalled the target build's frames for over 30 s.
|
||||
- Mapping a page no longer queries its range first (`VirtualQuery`, about 7 s of the Series X boot): placeholders in a reservation begin and end on 64 KB boundaries.
|
||||
- Cost, measured on the target build: the first presented frame comes at about 18.6 s instead of 3.7 s with the Series X profile, and 10.9 s instead of 3.6 s with Series S, from mapping the page pool one view per page (`MapViewOfFile3`, a Wine server call per page). The `remap_window_retry` of #722 stays for now.
|
||||
- Tests: `test_xmem_remap_neighbours` (new) reads two untouched pages of a four-page run from four threads while the middle two are remapped, with no warm-up remap; `test_veh_remap_window` now checks its reads. Both count faults ahead of the #722 retry and require no fault and no wrong value. Without the change both fail (3 to 4 faults per run).
|
||||
- **xmem: pages of an `XMEM_MAPPABLE` reservation are mapped on first touch, which recovers the boot time and frame pacing that one view per page cost** (#754, #729). `XMemMapPhysicalPages` and `XMemMapPhysicalPagesScatter` now record each slot's page; the slot is mapped when an instruction first touches it, by a vectored exception handler in `xmem.dll`, and a remap of a slot that was never touched changes no host mapping. On the target build at least 16,384 of 135,040 mapped pages are touched in two minutes with Series X, and at least 12,288 of about 85,800 with Series S. Measured on the target build (Apple M5, 120 s, `BX_CONSOLE_SHADERS=1`, two runs each), against `main` dcb9e434 and one view per page mapped at once: first frame 3.9–4.1 s (3.8 s, 18.6 s) and frame 2,048 at 77.7–78.0 s (83.6 s, 110.9 s) with Series X; 3.9 s (3.7 s, 10.9 s) and 76.1–76.3 s (78.0 s, 90.6 s) with Series S.
|
||||
- **System calls that write into title memory map its untouched pages first**, since such a write fails (`ERROR_NOACCESS`) where an instruction would fault: `ReadFile` imports of the modules loaded at the first mapping go through a wrapper (the target build reads a file of about 270 MB straight into its page pool), and `XCRDAPI.dll` touches a destination before its own `ReadFile`. Writes by instructions, `XCRDAPI.dll`'s decompression and copies and `d3d12_xs.dll`'s copies included, fault and are mapped by the handler.
|
||||
- **Page sections are `SEC_RESERVE`, and a view is committed after it is mapped.** Over a placeholder, Wine first makes a committed section's view accessible as the placeholder's zeroed memory and only then maps the section, so a second thread touching the slot at that moment read zeros (or lost its write); a reserved section's view stays inaccessible until it is committed.
|
||||
- **`d3d12_xs.dll` checks title memory without mapping it:** a page xmem reports mapped counts as present (`title_memory.cpp`), so registering a page pool does not map its 100,000 pages and the copy that follows maps only what it reads.
|
||||
- Tests: `test_xmem_lazy_map` (an untouched slot stays a placeholder through 2,000 remaps, the query reports it, eight threads touch the same new slots at once, an unmapped slot still faults), `test_xmem_lazy_file_read` (a title's own `ReadFile`, synchronous and overlapped, into untouched pages) and `test_xcrdapi_lazy_destination` (uncompressed, zlib and memory requests into untouched pages). `test_xmem_physical` now expects an untouched slot to be reserved until its first touch.
|
||||
- **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`.
|
||||
|
||||
Generated
+3
@@ -31,6 +31,9 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "dxbc-accc"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"gfx10-translate",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gfx10-translate"
|
||||
|
||||
@@ -2,236 +2,250 @@
|
||||
|
||||
# BetterXen
|
||||
|
||||
**Modular Xbox Series (`Scarlett`) compatibility layer for Apple Silicon macOS — built on CrossOver, Rosetta 2, and D3DMetal 3.0.**
|
||||
**An Xbox Series (`Scarlett`) compatibility layer for Apple Silicon Macs, built on CrossOver, Rosetta 2 and D3DMetal 3.0.**
|
||||
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hybrid-ci.yml)
|
||||
[](https://github.com/MacosPorters/betterxen/actions/workflows/hygiene.yml)
|
||||
-1f6feb?logo=apple&logoColor=white)
|
||||

|
||||

|
||||
-0969da)
|
||||

|
||||

|
||||
|
||||
</div>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Experimental status.** BetterXen is an active, open-source compatibility engineering project with **Milestone M0 and Milestone M1 verified complete** on synthetic PE32+ workloads under CrossOver 26.3 + Rosetta 2, and **Milestone M2** (`First Rendered Frame & Shader Format Gate`) currently active. **Commercial Xbox game execution is not yet supported.** CrossOver, Rosetta 2, and D3DMetal are externally installed dependencies and are never bundled or redistributed.
|
||||
> **Experimental.** The goal is one project-authorized target build, fully playable on Apple Silicon Macs with 16 GB of memory. Today that build boots, reaches its frame loop and its first menus, and translates its own shaders at run time, but it shows almost no picture yet. CrossOver, Rosetta 2 and D3DMetal are installed separately and are never bundled or redistributed.
|
||||
|
||||
BetterXen builds the missing Xbox Game OS layer around **CrossOver 26.3+**, **Rosetta 2**, and **D3DMetal 3.0** on Apple Silicon:
|
||||
- **Native ARM64 macOS tooling** (`launcher/`, Rust) for host diagnostics, PE32+ static probing, CrossOver bottle orchestration, and structured trace aggregation.
|
||||
- **Cross-compiled x86-64 Windows PE32+ shim DLLs** (`shims/`, C++20 via `mingw-w64`) implementing Xbox runtime APIs (`xmem`, `XCRDAPI`, `d3d12_xs`, `xg_xs`, `xgameruntime`, `GameInput`, `AcpHal`/`xapu`/`chad`, Win32/PSM forwarders, and a `clwb` Vectored Exception Handler).
|
||||
- **Shader pipeline** (`shader-transpiler/`, Rust) for classifying `DXBC` containers (`DXIL` vs. `ACCC`/`FSPX` RDNA 2 machine code) and handling console shader translation where required.
|
||||
## Where it stands
|
||||
|
||||
> [!CAUTION]
|
||||
> **Provenance and anti-piracy policy.** BetterXen strictly opposes piracy and does not distribute copyrighted game files, firmware, decryption keys, or DRM circumvention tooling. Zero proprietary binaries, assets, or leaked materials are permitted in this repository or its Git history. All in-repo tests use independently authored synthetic PE32+ workloads.
|
||||
*As of 2026-11-30, on `main`. The live status is on the pinned issue labelled [`ladder`](https://github.com/MacosPorters/betterxen/issues?q=is%3Aissue+is%3Aopen+label%3Aladder).*
|
||||
|
||||
---
|
||||
The current stage is **Picture**: the target build should show its first non-black screen, correctly.
|
||||
|
||||
## Progress Tracker
|
||||
| | State |
|
||||
| --- | --- |
|
||||
| **Boot** | The target build starts, creates its Xbox-layout D3D12 device, loads through DirectStorage, and presents frames. |
|
||||
| **Menus reached** | With scripted input it goes through its first-run setup screens. A hang watchdog in the build still ends most runs after a few minutes ([#722](https://github.com/MacosPorters/betterxen/issues/722)). |
|
||||
| **Shaders** | The build ships console (RDNA 2) code only. BetterXen's own translator turns a vertex/pixel pair into HLSL when a pipeline is first drawn; the result is compiled and cached on disk. Every vertex/pixel pipeline the build draws with in its first two minutes translates and runs. Opt-in: `BX_CONSOLE_SHADERS=1`. |
|
||||
| **Picture** | Only the menu's background bars appear, in a few frames. The rest is open work: [#744](https://github.com/MacosPorters/betterxen/issues/744) (why only the bars), [#745](https://github.com/MacosPorters/betterxen/issues/745) (texture contents), [#746](https://github.com/MacosPorters/betterxen/issues/746) (compute shaders). |
|
||||
| **Translator coverage** | 1,538 of 4,331 vertex and pixel shaders in one member's dump of the build translate offline (35.5%). That means "produces HLSL that compiles", not "verified against the console". |
|
||||
| **Sound, saves, gameplay, performance** | Not started as stages. Audio and save shims answer the build's calls so that it runs; nothing is audible. |
|
||||
|
||||
> *Tracks engineering milestones and synthetic conformance progress only — not commercial game compatibility percentages.*
|
||||
Without `BX_CONSOLE_SHADERS=1` the window stays black: pipelines with console shaders are refused and their draws are skipped.
|
||||
|
||||
### Stages
|
||||
|
||||
From the Boot stage on, progress is measured by how far the target build gets in repeated, recorded runs, not by subsystems. Each stage has one exit gate: ten runs out of ten on a 16 GB Mac.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M0["M0: Foundation & Shims\n(Verified Complete)"]:::done
|
||||
M1["M1: Boot to D3D12\n(Verified Complete — 16/16)"]:::done
|
||||
M2["M2: First Frame &\nShader Gate\n(Active — Milestone #18)"]:::active
|
||||
M3["M3: Shaders &\nTexture Tiling"]:::planned
|
||||
M4["M4: 3D, DXR/BVH\n& Input"]:::planned
|
||||
M5["M5: Audio, Saves\n& Stability"]:::planned
|
||||
M6["M6: Cache & 16 GB\nOptimization"]:::planned
|
||||
F["Foundation\nM0–M2, synthetic"]:::done
|
||||
B["Boot"]:::done
|
||||
P["Picture\n(current)"]:::active
|
||||
M["Menus"]:::planned
|
||||
W["World"]:::planned
|
||||
Fi["Fidelity"]:::planned
|
||||
Pl["Playable"]:::planned
|
||||
|
||||
M0 --> M1 --> M2 --> M3 --> M4 --> M5 --> M6
|
||||
F --> B --> P --> M --> W --> Fi --> Pl
|
||||
|
||||
classDef done fill:#dafbe1,stroke:#1a7f37,color:#0f5323,stroke-width:2px
|
||||
classDef active fill:#ddf4ff,stroke:#0969da,color:#0a3069,stroke-width:2px
|
||||
classDef planned fill:#f6f8fa,stroke:#8c959f,color:#57606a
|
||||
```
|
||||
|
||||
Legend: 🟢 **Done / Merged** · 🔵 **Active Milestone** · ⚪ **Planned**
|
||||
|
||||
### Active Milestone — [M2: First Rendered Frame & Shader Format Gate](https://github.com/MacosPorters/betterxen/milestone/18)
|
||||
|
||||
| Track | Focus | Visual Status | Live Issues |
|
||||
| --- | --- | --- | --- |
|
||||
| **Track A** | `system32` shim staging (`#457` / PR `#458` merged), AMD-only VEH emulation (`#451`), Track A/F runner integration (`#407`) | `🟩🟨🟨` *(#458 merged; #451, #407 active)* | [View Track A](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+A%22) |
|
||||
| **Track B** | `XCRDAPI.dll` DirectStorage GPU-buffer & batch transfers (`#467`) | `⬜` *(1 ready)* | [View Track B](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+B%22) |
|
||||
| **Track C** | `d3d12_xs` `D3D12ConfigureVirtualMemoryX` + placed resources (`#464`), `PresentX` swapchain bridge (`#465`), D3D workload fixes (`#450`) | `⬜⬜⬜` *(3 ready)* | [View Track C](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+C%22) |
|
||||
| **Track D** | `dxbc-accc` Windows guest bridge (`#445`), M2 Shader Format Gate ADR & PSO hook (`#466`) | `⬜⬜` *(2 ready)* | [View Track D](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+D%22) |
|
||||
| **Track E** | Public GDK COM `QueryApiImpl` dispatch (`#456` / PR `#462` merged), offline `XGameSave` + `XPackage` COM dispatch (`#468`) | `🟩⬜` *(#462 merged, 1 ready)* | [View Track E](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+E%22) |
|
||||
| **Track F** | D3DMetal GPU limits fixture (`#453` / PR #455), M2 first-frame + shader-gate exit fixture (`#469`) | `🟨⬜` *(PR #455 approved, 1 ready)* | [View Track F](https://github.com/MacosPorters/betterxen/issues?q=is%3Aopen+label%3A%22track%3A+F%22) |
|
||||
|
||||
`🟩` Merged & verified · `🟨` PR open / in review · `⬜` Open & ready to claim
|
||||
|
||||
### Milestone Roadmap (M0 → M6)
|
||||
|
||||
| Milestone | Scope | Status |
|
||||
| Stage | The target build… | Status |
|
||||
| --- | --- | --- |
|
||||
| **M0 — Repo, ABI & Cross-Build** | 6-track layout, frozen `abi/`, ARM64 `bx-cli`, 16 mingw-w64 C++ PE32+ shims plus the Rust `bx_shader_bridge.dll` (17 verified DLLs), live CrossOver + Rosetta 2 smoke tests (`test_veh_clwb`, `test_shim_exports`) | 🟢 **Verified complete (`#406`)** |
|
||||
| **M1 — Boot to `D3D12XboxCreateDevice`** | Full startup shim coverage (`xmem` physical/scatter pages, `XCRDAPI` async file reads, `d3d12_xs` auto-logging COM proxy, offline `xgameruntime` + dynamic loader exports, audio queue stubs, supervised `bx-cli run`, ADR 0007, `test_integration_boot` 19 pass / 2 pending / 0 fail) | 🟢 **Verified complete ([Milestone #17](https://github.com/MacosPorters/betterxen/milestone/17))** |
|
||||
| **M2 — First Frame & Shader Gate** | Reversible `system32` staging, public GDK COM `QueryApiImpl` dispatch, `PresentX` → `IDXGISwapChain3::Present` via D3DMetal 3.0, `dxbc-accc` Windows bridge, D3DMetal GPU limits, and Shader Format Gate ADR | 🔵 **Active ([Milestone #18](https://github.com/MacosPorters/betterxen/milestone/18))** |
|
||||
| **M3 — Shaders, Streaming & Textures** | DirectStorage decompression, RDNA 2 `xg_xs` texture deswizzling, full shader pipeline | ⚪ Planned |
|
||||
| **M4 — 3D Rendering, DXR/BVH & Input** | BVH4 rehydration → live D3DMetal 3.0 DXR rebuild, PC FidelityFX/MetalFX upscaling shim, full `GameInput` | ⚪ Planned |
|
||||
| **M5 — Audio, Saves & Stability** | Software audio/DSP decoding (`AcpHal`/`xapu`/`chad`), `PersistentLocalStorage`, multi-hour soak stability | ⚪ Planned |
|
||||
| **M6 — Cache, 16 GB Tuning & Polish** | Persistent PSO/shader disk cache, Lockhart 16 GB unified memory optimization, Metal System Trace tuning | ⚪ Planned |
|
||||
| **Foundation** | (synthetic tests only) repository, frozen ABI, cross-built shims, a synthetic first frame, the shader format decision | Done |
|
||||
| **Boot** | starts, reaches its frame loop and stays there | Left on 2026-11-30 by the repository owner's decision; its ten-run gate was not run |
|
||||
| **Picture** | shows its first non-black screen, correctly | **Current** |
|
||||
| **Menus** | plays its opening sequence and menus with sound and input | Planned |
|
||||
| **World** | loads into gameplay and keeps running | Planned |
|
||||
| **Fidelity** | draws its 3D scenes as the console does | Planned |
|
||||
| **Playable** | is playable start to finish on every supported Mac | Planned |
|
||||
|
||||
See [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md) and [docs/roadmap.md](docs/roadmap.md) for full details.
|
||||
[docs/roadmap.md](docs/roadmap.md) is the single authoritative roadmap, with each gate's exact wording. [docs/process/working-method.md](docs/process/working-method.md) explains how runs are made and recorded.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
## How it works
|
||||
|
||||
Rosetta 2 executes x86-64 CPU code (including AVX/AVX2/FMA/F16C/BMI1/BMI2/128-bit VAES when launched with `ROSETTA_ADVERTISE_AVX=1`), CrossOver/Wine provides Win32/NT/CRT/XAudio2/WinHTTP, and D3DMetal 3.0 translates Direct3D 12 + DXR onto Metal. BetterXen supplies the modular Xbox Game OS shims, `clwb` exception handling, shader bridge, and ARM64 orchestration around that stack.
|
||||
Rosetta 2 executes the build's x86-64 code. CrossOver/Wine provides Win32. D3DMetal 3.0 translates Direct3D 12 to Metal. BetterXen supplies what is missing between an Xbox title and that stack:
|
||||
|
||||
- **Xbox Game OS shims** (`shims/`): x86-64 Windows DLLs, cross-compiled on macOS, that implement the Xbox runtime the title imports: memory, DirectStorage, the Xbox flavour of Direct3D 12, the GDK runtime, input and audio.
|
||||
- **A shader translator** (`shader-transpiler/`): console shaders are AMD RDNA 2 machine code. The translator turns them into HLSL, one rule per instruction, and the Direct3D shim compiles and caches the result.
|
||||
- **A native launcher** (`launcher/`): `bx-cli` checks the host, runs a program in an isolated CrossOver environment, and turns the shims' logs into a run report.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Guest["Scarlett x86-64 PE32+ Executable"]
|
||||
Guest["Xbox Series title (x86-64 PE32+)"]
|
||||
|
||||
subgraph Shims["BetterXen x86-64 Wine Shims (Cross-Compiled on macOS)"]
|
||||
VEH["bx_runtime_veh.dll (clwb VEH trap, JSONL trace, Lockhart cap)"]
|
||||
XMem["xmem.dll (Physical/Virtual/Scatter Allocator)"]
|
||||
DS["XCRDAPI.dll (DirectStorage Async I/O)"]
|
||||
D3DX["d3d12_xs.dll + xg_xs.dll (Xbox D3D12 COM Proxy & RDNA2 Tiling)"]
|
||||
XGR["xgameruntime.dll + GameInput.dll + Audio/DSP"]
|
||||
Bridge["PSM AppNotify & ntuser Win32 Forwarders"]
|
||||
subgraph Shims["BetterXen shims (x86-64 DLLs, built on macOS)"]
|
||||
VEH["bx_runtime_veh.dll\ninstruction traps, logging, fault diagnostics"]
|
||||
XMem["xmem.dll\nvirtual and physical page mapping"]
|
||||
DS["XCRDAPI.dll\nDirectStorage queues, zlib, BCPack"]
|
||||
D3DX["d3d12_xs.dll\nXbox-layout D3D12 over the host's D3D12"]
|
||||
XGR["xgameruntime.dll, GameInput.dll, audio DLLs"]
|
||||
Bridge["bx_shader_bridge.dll (Rust)\nshader classifier and translator"]
|
||||
end
|
||||
|
||||
subgraph Shaders["Shader & DXR Bridge"]
|
||||
DXIL["DXIL Fast Path (SM 6.5/6.6)"]
|
||||
ACCC["ACCC / FSPX RDNA2 Transpiler"]
|
||||
subgraph GDK["From the member's own GDK, staged at run time, never shipped"]
|
||||
XG["xg_xs.dll (texture layouts)\nBCPack.dll"]
|
||||
DXC["dxcompiler.dll (HLSL to DXIL)"]
|
||||
end
|
||||
|
||||
subgraph External["External Foundation (User-Installed)"]
|
||||
Wine["CrossOver 26.3 / Wine (Win32, CRT, XAudio2, WinHTTP)"]
|
||||
Rosetta["Rosetta 2 (ROSETTA_ADVERTISE_AVX=1)"]
|
||||
D3DM["D3DMetal 3.0 (D3D12 + DXR on Apple Silicon Metal)"]
|
||||
subgraph External["External foundation (installed by the user)"]
|
||||
Wine["CrossOver 26.3+ / Wine"]
|
||||
Rosetta["Rosetta 2"]
|
||||
D3DM["D3DMetal 3.0"]
|
||||
end
|
||||
|
||||
CLI["bx-cli (Native ARM64 macOS Launcher, Probe & Telemetry)"]
|
||||
CLI["bx-cli (native ARM64)\nsetup, preflight, run, report"]
|
||||
|
||||
Guest --> Shims
|
||||
D3DX --> DXIL --> D3DM
|
||||
D3DX --> ACCC --> D3DM
|
||||
D3DX -->|"console shaders, at first draw"| Bridge
|
||||
Bridge -->|"HLSL"| DXC
|
||||
DXC -->|"DXIL, cached on disk"| D3DX
|
||||
D3DX --> D3DM
|
||||
D3DX --> XG
|
||||
XMem --> Wine
|
||||
DS --> Wine
|
||||
XGR --> Wine
|
||||
Bridge --> Wine
|
||||
VEH --> Rosetta
|
||||
Wine --> Rosetta
|
||||
CLI -.->|"Launches, sets overrides, summarizes traces"| External
|
||||
CLI -.->|"launches, isolates, stages, reports"| External
|
||||
```
|
||||
|
||||
Design decisions are recorded as ADRs in [docs/adr/](docs/adr/): the CrossOver-based direction (0005), the shader format gate (0008), Xbox-layout Direct3D objects (0009), and using the GDK's own texture libraries and compiler at run time (0010).
|
||||
|
||||
---
|
||||
|
||||
## Repository Layout
|
||||
## Repository layout
|
||||
|
||||
The repository is organized into disjoint track directories around a single frozen `abi/` contract so **5–8+ contributors (and coding agents)** can work concurrently with minimal merge conflicts.
|
||||
Work is split into tracks with their own directories, around one frozen `abi/` contract, so several contributors and coding agents can work at once ([docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md)).
|
||||
|
||||
| Directory | Track | Stack | Contents |
|
||||
| --- | --- | --- | --- |
|
||||
| [`abi/`](abi/README.md) | Shared (frozen) | C headers + `.def` | Versioned cross-DLL headers (`bx_config.h`, `bx_log.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical export tables for all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) |
|
||||
| `launcher/` | Track A | Rust (`arm64`) | `bx-cli` (`doctor`, `probe`, `shader`, `trace`, `run`), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`x86_64` PE) | `bx_runtime_veh.dll`: `clwb` VEH trap, `adcx`/`adox` tripwire, Lockhart/Anaconda memory profile config, structured JSONL logging |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`x86_64` PE) | `api-ms-win-core-psm-appnotify-l1-1-0/1.dll` stubs and `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; CrossOver answers these API-set names itself for static imports, so the files are not loaded that way ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/`, `shims/xcrdapi/` | Track B | C++20 (`x86_64` PE) | `xmem.dll` (13 Xbox memory APIs + internal region stats) and `XCRDAPI.dll` (`DStorageGetFactory` async I/O) |
|
||||
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | Track C | C++20 (`x86_64` PE) | Xbox D3D12 COM proxy over D3DMetal 3.0, RDNA 2 texture tiling (`XG`), and future FidelityFX/BVH4 hooks |
|
||||
| `shader-transpiler/` | Track D | Rust (`arm64`) | `dxbc-accc` (`DXBC`/`DXIL`/`ACCC`/`FSPX` classifier), future RDNA 2 transpiler & `d3dmetal-native` isolation harness |
|
||||
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | Track E | C++20 (`x86_64` PE) | Offline GDK runtime (`xgameruntime.dll`), `GameInput.dll` (`@1`), and `AcpHal.dll`/`xapu.dll`/`chad.dll` |
|
||||
| [`tests/conformance/`](tests/conformance/README.md) | Track F | C++20 (`x86_64` PE) | Auto-discovered clean-room synthetic PE32+ test binaries (`test_*/CMakeLists.txt`) |
|
||||
| [`abi/`](abi/README.md) | ABI gate | C headers, `.def` | Cross-DLL headers and the canonical export table of every shim DLL (17 DLLs, 118 exports) |
|
||||
| `launcher/` | A | Rust (`arm64`) | `bx-cli`, `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/`, `shims/win32_bridge/` | A | C++20 (x86-64 PE) | `bx_runtime_veh.dll` (traps for instructions Rosetta 2 lacks, structured logging, fault diagnostics) and API-set forwarders ([ADR 0007](docs/adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/`, `shims/xcrdapi/` | B | C++20 (x86-64 PE) | `xmem.dll` (Xbox memory APIs, physical page mapping) and `XCRDAPI.dll` (DirectStorage) |
|
||||
| `shims/d3d12_xs/`, `shims/xg_xs/`, `shims/ffx_bvh_hooks/` | C | C++20 (x86-64 PE) | The Xbox-layout Direct3D 12 layer, `PresentX`, console pipelines translated at first draw, title-memory resources, and the texture-layout shim |
|
||||
| `shader-transpiler/` | D | Rust | `gfx10-translate` (RDNA 2 decoder and translator to HLSL), `dxbc-accc` (container classifier; built for Windows as `bx_shader_bridge.dll`), `d3dmetal-harness` |
|
||||
| `shims/xgameruntime/`, `shims/gameinput/`, `shims/audio/` | E | C++20 (x86-64 PE) | Offline GDK runtime, `GameInput.dll`, and `AcpHal.dll` / `xapu.dll` / `chad.dll` |
|
||||
| [`tests/conformance/`](tests/conformance/README.md), `docs/` | F | C++20 (x86-64 PE), Markdown | 54 synthetic test programs, auto-discovered from `test_*/CMakeLists.txt`, and the documentation |
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
## Quick start
|
||||
|
||||
### Requirements
|
||||
### Building and running the synthetic tests
|
||||
|
||||
- **Apple Silicon Mac** running native ARM64 macOS with **Rosetta 2** and **CrossOver 26.3+** (external install).
|
||||
- **Rust toolchain** (`aarch64-apple-darwin`, Rust 1.85+ / 1.100.0).
|
||||
- **`mingw-w64` & `cmake`** (`brew install mingw-w64 cmake`) for cross-compiling x86-64 Windows PE32+ shims on macOS.
|
||||
- **Python 3.11+** for export verification and repository hygiene checks.
|
||||
This needs no game and no GDK:
|
||||
|
||||
### Build & Verify
|
||||
- an **Apple Silicon Mac** with **Rosetta 2** and **CrossOver 26.3+** (licensed separately);
|
||||
- **Rust** 1.85 or later, **Python** 3.11 or later;
|
||||
- `brew install mingw-w64 cmake`.
|
||||
|
||||
```sh
|
||||
git clone https://github.com/MacosPorters/betterxen.git
|
||||
cd betterxen
|
||||
|
||||
# 1. Build & test the native ARM64 Rust workspace (launcher + shader-transpiler)
|
||||
# 1. The native ARM64 Rust workspace (launcher and shader translator)
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
cargo build -p bx-cli
|
||||
cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
cargo test --locked --workspace
|
||||
cargo build --locked -p bx-cli
|
||||
|
||||
# 2. Check host Apple Silicon, Rosetta 2, CrossOver, D3DMetal, and mingw-w64 readiness
|
||||
# 2. Host readiness: Apple Silicon, Rosetta 2, CrossOver, D3DMetal, mingw-w64
|
||||
target/debug/bx-cli doctor
|
||||
|
||||
# 3. Cross-compile the 16 x86-64 PE32+ mingw-w64 shim DLLs, build the Rust
|
||||
# bx_shader_bridge.dll with cargo, and build the conformance binaries
|
||||
# (automatically verifies every abi/defs/*.def export across all 17 DLLs and zero MinGW runtime DLL deps)
|
||||
# 3. Cross-compile the 16 C++ shim DLLs, build the Rust bx_shader_bridge.dll and the
|
||||
# conformance programs; verifies every export of all 17 DLLs against abi/defs/*.def
|
||||
scripts/build-shims.sh
|
||||
|
||||
# 4. Run live synthetic PE32+ conformance tests inside CrossOver + Rosetta 2
|
||||
# 4. Two synthetic tests inside CrossOver and Rosetta 2
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_veh_clwb.exe
|
||||
target/debug/bx-cli run --prefix /tmp/bx-test --shims build-shims/bin --log /tmp/bx-test.jsonl --exe build-shims/bin/test_shim_exports.exe
|
||||
target/debug/bx-cli trace /tmp/bx-test.jsonl
|
||||
|
||||
# 5. Check Markdown links & repository hygiene
|
||||
# 5. Markdown links and repository hygiene
|
||||
python3 scripts/audit/docs_hygiene.py
|
||||
```
|
||||
|
||||
### `bx-cli` Commands
|
||||
The graphics tests need a CrossOver bottle with D3DMetal (`--bottle <name> --backend d3dmetal`); in a plain prefix they skip.
|
||||
|
||||
### Working on the project
|
||||
|
||||
Contributing needs three more things, and they are a **hard requirement**: the **project-authorized target build**, the **GDK** under the project's authorization, and the **Ghidra results** of the target build. They are distributed among members only. Nothing from them (files, names, hashes, paths, bytes) is ever committed or posted.
|
||||
|
||||
```sh
|
||||
target/debug/bx-cli setup --find # finds the build, the GDK and the Ghidra results on this machine
|
||||
target/debug/bx-cli preflight # must print: Ready to work.
|
||||
```
|
||||
|
||||
Then point a coding agent at the repository and say **"work"**, or follow the same steps by hand. [CONTRIBUTING.md](CONTRIBUTING.md) explains what you need and how work is organised; [AGENTS.md](AGENTS.md) (also `CLAUDE.md`) holds the full rules, including how one item is picked, claimed with a draft pull request, tested and proven.
|
||||
|
||||
### `bx-cli` commands
|
||||
|
||||
| Command | Purpose |
|
||||
| --- | --- |
|
||||
| `bx-cli doctor` | Inspects Apple Silicon host, RAM (recommends `lockhart` on 16 GB Macs or `anaconda` on 32 GB+), Rosetta 2, CrossOver, D3DMetal, and `mingw-w64` |
|
||||
| `bx-cli probe <pe32+>` | Static PE32+ import scanner that classifies every imported DLL into Tracks A–E or Wine built-ins |
|
||||
| `bx-cli shader <blob>` | Classifies a `DXBC` shader container (`DXIL` vs. legacy `SHDR`/`SHEX` vs. `ACCC`/`FSPX`) |
|
||||
| `bx-cli run --exe <path> ...` | Launches a PE32+ binary under CrossOver/Wine with `env_clear()` host isolation (`--inherit-env` opt-in), `ROSETTA_ADVERTISE_AVX=1`, `WINEDLLOVERRIDES`, `BX_PROFILE`, and JSONL trace capture |
|
||||
| `bx-cli trace <log.jsonl>` | Aggregates `bx_runtime_veh.dll` logs (unimplemented API counts, COM vtable misses, `clwb` VEH traps, ADX tripwires) |
|
||||
| `bx-cli doctor` | Inspects the host: chip, memory, Rosetta 2, CrossOver, D3DMetal, `mingw-w64` |
|
||||
| `bx-cli setup [--find]` | Remembers where the target build, the GDK and the Ghidra results are on this machine, outside the repository |
|
||||
| `bx-cli preflight` | Checks everything work needs; fails if anything is missing |
|
||||
| `bx-cli run --exe <path> ...` | Runs a program under CrossOver with a cleared environment, the shim overrides and a JSONL log. For the target build it stages the GDK's libraries beside the shims |
|
||||
| `bx-cli report <log.jsonl>...` | One run report per log, then a summary with blocker signatures |
|
||||
| `bx-cli trace <log.jsonl>` | Summarises a log: unimplemented calls, trapped instructions, shader-gate decisions |
|
||||
| `bx-cli probe <pe32+>` | Classifies a program's imports by track |
|
||||
| `bx-cli shader <blob>` | Classifies a shader container (DXIL, legacy, or console code) |
|
||||
| `bx-cli shader translate <vs> <ps> --out <dir> [--root <layout>]` | Translates a console vertex/pixel pair to HLSL |
|
||||
| `bx-cli shader coverage <dir>` | Counts how many shaders in a folder translate and ranks what blocks the rest |
|
||||
|
||||
---
|
||||
|
||||
## Contributing with Humans & Coding Agents
|
||||
## What is verified, and what is not
|
||||
|
||||
BetterXen is built for **parallel work across 5–8+ contributors and coding agents** (`AGENTS.md` — symlinked as `CLAUDE.md` — holds the full ruleset):
|
||||
**Verified by tests in this repository** (synthetic programs of the project's own, on Apple Silicon with CrossOver 26.3 and Rosetta 2):
|
||||
|
||||
1. **Pick a track & claim an issue** from [docs/issues/wave-1-backlog.md](docs/issues/wave-1-backlog.md) (or GitHub Issues using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Reply `Claiming — branch: track-<a..f>/<issue>-<slug>` before coding.
|
||||
2. **Isolate your branch or worktree:** `git worktree add ../wt-<issue> -b track-<a..f>/<issue>-<slug> origin/main`.
|
||||
3. **Stay inside your issue's exclusive file scope:** Never edit another track's directory inside a feature PR. Need a new cross-DLL helper? Open a small `[ABI]` PR touching only `abi/` first.
|
||||
4. **Add a conflict-free conformance test:** Drop `tests/conformance/test_<name>/CMakeLists.txt` + `main.cpp` — CMake auto-discovers `test_*` directories with zero edits to shared files.
|
||||
5. **Run the verification commands above**, update [CHANGELOG.md](CHANGELOG.md) under `[Unreleased]`, sign off commits (DCO `Signed-off-by`), and open a PR with `Closes #<issue>`.
|
||||
- All 17 shim DLLs build, and their export tables match `abi/defs/*.def` exactly (118 exports, no extras, no MinGW runtime dependency).
|
||||
- 54 conformance programs cover the shims' contracts: memory mapping, DirectStorage, the Xbox-layout Direct3D objects, `PresentX`, rectangle lists, console formats, the shader gate, and console pipelines translated at first draw.
|
||||
- The translator's output matches a reference translator on its golden pairs, and its instruction decoder matches LLVM's on its test vectors.
|
||||
|
||||
See [AGENTS.md](AGENTS.md), [CONTRIBUTING.md](CONTRIBUTING.md), [docs/architecture/parallel-tracks.md](docs/architecture/parallel-tracks.md), and [docs/README.md](docs/README.md).
|
||||
A conformance test shows that a shim matches the contract the project recorded. It does not show that the recorded contract is what a console does.
|
||||
|
||||
**Observed on the target build, on members' machines** (recorded in pull requests and issues, not reproducible without the build): the states in "Where it stands" above.
|
||||
|
||||
**Not claimed:**
|
||||
|
||||
- Nothing is verified on Xbox hardware. The project has none.
|
||||
- No commercial game is supported or playable.
|
||||
- Translated shaders are not checked against console output yet; most have never been drawn.
|
||||
- Performance has not been measured.
|
||||
|
||||
Evidence classes are defined in [docs/claims.toml](docs/claims.toml).
|
||||
|
||||
---
|
||||
|
||||
## Current Verified Scope & Limitations
|
||||
## Provenance and legal boundaries
|
||||
|
||||
- **Verified (local Apple M5, macOS 27.2.1, CrossOver 26.3, Rosetta 2):**
|
||||
- Native ARM64 `bx-cli`, `bx-probe`, `bx-telemetry`, and `dxbc-accc` unit tests.
|
||||
- All 17 x86-64 PE32+ shim DLLs — the 16 mingw-w64 C++ shims plus the Rust-built `bx_shader_bridge.dll` — pass strict PE Export Directory verification (111 exact names, ordinals, forwarders, 0 extra exports) and carry zero dynamic MinGW runtime dependencies. `scripts/build-shims.sh` cross-compiles the 16 C++ shims with CMake/mingw-w64 and builds `bx_shader_bridge.dll` with `cargo` for `x86_64-pc-windows-gnu`.
|
||||
- `test_veh_clwb.exe` executes AVX2+FMA, traps and skips `clwb` via `bx_runtime_veh.dll`, and exercises starter `XMemAlloc`/`XMemTransferMemory` under CrossOver/Wine.
|
||||
- `test_shim_exports.exe` loads all 16 mingw-w64 C++ shim DLLs and resolves 25 runtime exports via `LoadLibraryA` / `GetProcAddress` inside CrossOver/Wine.
|
||||
- **Not yet verified at runtime (built and export-verified locally, not run under CrossOver):**
|
||||
- The build of `test_shim_exports.exe` on this revision also loads the Rust-built `bx_shader_bridge.dll` and resolves its three frozen exports (`bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, `bx_shader_free_buffer`), so the table covers 17 DLLs / 28 checks. The fixture compiles and links and `scripts/build-shims.sh` confirms the bridge's three exports statically, but the 28-check run across 17 DLLs under CrossOver/Wine has **not** been executed on this revision — the previous 16-DLL / 25-check pass was. Compiling, linking and export agreement do not establish that `LoadLibraryA` / `GetProcAddress` succeed for the bridge. This remains a load-and-resolve check in any case: it does not show the bridge *works*; `test_shader_gate.exe` exercises it functionally.
|
||||
- **Not yet implemented (M1–M6):**
|
||||
- `d3d12_xs.dll` COM device/command-list/PSO proxy and `PresentX` swapchain presentation.
|
||||
- `xmem.dll` physical/scatter page mapping and `XCRDAPI.dll` async DirectStorage queues.
|
||||
- `xg_xs.dll` RDNA 2 texture tiling/deswizzling and DXR/BVH4 rehydration interception.
|
||||
- Console `ACCC`/`FSPX` RDNA 2 → DXIL/MSL shader transpilation (gated on M2).
|
||||
- Real software audio/DSP decoding behind `AcpHal`/`xapu`/`chad` and full `GameInput` polling.
|
||||
- Commercial Xbox game execution.
|
||||
> [!CAUTION]
|
||||
> BetterXen opposes piracy. The repository contains no game files, firmware, keys, DRM circumvention, GDK files or compiler outputs, and none may be added to it or to its history.
|
||||
|
||||
- Contracts that have no public documentation are established from the authorized GDK, from the project-authorized target build (call sites and run-time diagnostics), and from compilers run on the project's own shaders. Each implemented contract gets a synthetic conformance test.
|
||||
- The GDK's own libraries (`xg_xs.dll`, `BCPack.dll`, `dxcompiler.dll`) are loaded at run time from each member's GDK. They are not reimplemented, committed or shipped ([ADR 0010](docs/adr/0010-gdk-texture-libraries.md)).
|
||||
- See [docs/legal.md](docs/legal.md), [docs/licenses.md](docs/licenses.md) and [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
||||
|
||||
---
|
||||
|
||||
## Historical Native-First Research
|
||||
## History
|
||||
|
||||
The earlier paused native-first implementation (independent x86-64 interpreter/ARM64 DBT, bounded `gfx1030` RDNA 2 → MSL translator, native Metal backend, and Swift app) was retired from `main` per [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md) and remains preserved permanently in Git history at tag `native-first-final`.
|
||||
The earlier native-first implementation (an x86-64 interpreter and ARM64 translator, a native Metal backend and a Swift app) was retired from `main` by [ADR 0006](docs/adr/0006-retire-in-tree-native-workspace.md). It is preserved at the Git tag `native-first-final`.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE). See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) and [docs/legal.md](docs/legal.md) for attribution and legal scope.
|
||||
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
|
||||
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, or any game publisher.
|
||||
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Apple, CodeWeavers, AMD or any game publisher.
|
||||
@@ -9,6 +9,7 @@ The active BetterXen Rust workspace (`Cargo.toml` / `Cargo.lock`) is original `G
|
||||
| Files | Origin | License |
|
||||
| --- | --- | --- |
|
||||
| `shims/xcrdapi/dstorage/dstorage.h`, `shims/xcrdapi/dstorage/dstorageerr.h` | Microsoft DirectStorage SDK headers, NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0, unmodified (#483). Provenance and hashes: [shims/xcrdapi/dstorage/README.md](shims/xcrdapi/dstorage/README.md). | MIT, per-file notice. The package's `LICENSE-CODE.txt` is kept next to the headers and reproduced under [DirectStorage headers MIT license text](#directstorage-headers-mit-license-text) below. |
|
||||
| `shims/xg_xs/third_party/addrlib/` | AMD addrlib from Mesa `src/amd/addrlib`, tag `mesa-25.2.0`, commit `0b97dcdd9424fce130054e1972a610b765644003`, unmodified (#756). Provenance: [shims/xg_xs/third_party/addrlib/README.md](shims/xg_xs/third_party/addrlib/README.md). | MIT. 42 of 44 files carry `SPDX-License-Identifier: MIT`. `src/core/addrswizzler.cpp` and `src/core/addrswizzler.h` have the AMD 2024 copyright block and no SPDX line; `meson.build`, which lists them, is SPDX MIT. |
|
||||
|
||||
## External Host Tools & Runtime Dependencies (Never Bundled)
|
||||
|
||||
|
||||
@@ -3,3 +3,6 @@ EXPORTS
|
||||
bx_shader_inspect
|
||||
bx_shader_prepare_for_d3dmetal
|
||||
bx_shader_free_buffer
|
||||
bx_shader_translate_pair
|
||||
bx_shader_free_pair_translation
|
||||
bx_shader_translate_pair_rooted
|
||||
@@ -76,6 +76,120 @@ bx_shader_status_t bx_shader_prepare_for_d3dmetal(
|
||||
|
||||
void bx_shader_free_buffer(uint8_t* ptr, size_t len);
|
||||
|
||||
/*
|
||||
* Translation of a console graphics pipeline's vertex and pixel shader to HLSL (#720).
|
||||
*
|
||||
* The inputs are the two stages as the title hands them to a pipeline: RDNA 2 code in the
|
||||
* console's shader container, or the bare code. d3d12_xs calls this when such a pipeline is
|
||||
* first drawn and compiles the HLSL with a DXC library (entry point `main`, profiles `vs_6_0`
|
||||
* and `ps_6_0`). The two keys identify the pair, in logs and wherever a caller wants a name for
|
||||
* it (`<vs_key>_<ps_key>`, 16 lower-case hex digits each). How compiled shaders are cached is the
|
||||
* caller's business: d3d12_xs names them by a hash of the HLSL, so that a change of the
|
||||
* translator can never reuse an old result.
|
||||
*
|
||||
* All text is UTF-8 without a terminator. A buffer that is not NULL belongs to the caller, who
|
||||
* frees it with bx_shader_free_buffer(ptr, len); bx_shader_free_pair_translation frees all of
|
||||
* them and clears the structure.
|
||||
*/
|
||||
typedef struct bx_shader_pair_translation {
|
||||
/* 64-bit FNV-1a (offset basis 0xcbf29ce484222325, prime 0x100000001b3) of each input, as
|
||||
passed. Set whenever both inputs are readable, also when translation is refused. */
|
||||
uint64_t vs_key;
|
||||
uint64_t ps_key;
|
||||
/* On BX_SHADER_OK: the two HLSL sources. */
|
||||
uint8_t* vs_hlsl;
|
||||
size_t vs_hlsl_len;
|
||||
uint8_t* ps_hlsl;
|
||||
size_t ps_hlsl_len;
|
||||
/*
|
||||
* On BX_SHADER_OK: what the host pipeline needs, one line each, '\n' after every line:
|
||||
* FETCH <n> the vertex shader reads its n attributes through the
|
||||
* console vertex-fetch call; the host input layout is
|
||||
* the pipeline's own, with semantics ATTR0..ATTR<n-1>
|
||||
* ATTR <semantic index> <DXGI_FORMAT> <slot> <byte offset>
|
||||
* an input element (semantic name ATTR) the vertex
|
||||
* shader loads itself from vertex buffer <slot>
|
||||
* USE CB <entry> a constant buffer: entry <entry> of root parameter
|
||||
* USE CB <root parameter> <entry> 0's descriptor table (two numbers: of that root
|
||||
* USE TEX <entry> parameter's), declared as register b<entry> or
|
||||
* USE TEX <root parameter> <entry> t<entry> in space 100 + <root parameter>
|
||||
* Unknown lines must be ignored by the caller, so lines can be added.
|
||||
*/
|
||||
uint8_t* layout;
|
||||
size_t layout_len;
|
||||
/* On BX_SHADER_ERR_UNSUPPORTED: one line saying what the translator does not model yet. */
|
||||
uint8_t* reason;
|
||||
size_t reason_len;
|
||||
} bx_shader_pair_translation_t;
|
||||
|
||||
/*
|
||||
* BX_SHADER_OK: translated. BX_SHADER_ERR_UNSUPPORTED: an input uses something not modelled
|
||||
* (`reason` says what); the pipeline then stays untranslated. BX_SHADER_ERR_INVALID_BLOB: a NULL
|
||||
* or empty input, a NULL `out`, or an input in a `DXBC` container that holds no console code.
|
||||
* Bare code has no magic to check: bytes that are not shader code are decoded as code and come
|
||||
* back BX_SHADER_ERR_UNSUPPORTED (an unknown or unmodelled instruction), not invalid.
|
||||
* BX_SHADER_ERR_TRANSLATE: an internal failure. `*out` is cleared first in every case.
|
||||
* Thread-safe; holds no state between calls.
|
||||
*/
|
||||
bx_shader_status_t bx_shader_translate_pair(
|
||||
const uint8_t* vs_bytes,
|
||||
size_t vs_len,
|
||||
const uint8_t* ps_bytes,
|
||||
size_t ps_len,
|
||||
bx_shader_pair_translation_t* out
|
||||
);
|
||||
|
||||
void bx_shader_free_pair_translation(bx_shader_pair_translation_t* translation);
|
||||
|
||||
/*
|
||||
* The same translation, given the layout of the pipeline's root signature (#715).
|
||||
*
|
||||
* A console shader receives its root arguments as packed 32-bit values in root-parameter order:
|
||||
* a descriptor-table parameter is one value (a 32-bit table pointer), a root CBV, SRV or UAV two
|
||||
* (a 64-bit address, low half first), a constants parameter one per constant. Value d is in
|
||||
* user-data register s(8 + d) of a vertex or pixel shader, or, when the root signature has
|
||||
* D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI, at byte 4 * d of root data the shader
|
||||
* reads from memory (docs/research/console-shader-abi.md). Which parameter a shader reads
|
||||
* therefore depends on the parameters before it, and bx_shader_translate_pair, which is not told
|
||||
* them, treats every parameter as a table.
|
||||
*
|
||||
* With a layout:
|
||||
* - a descriptor table is translated as before: entry k of root parameter i is register k of
|
||||
* space 100 + i, and is named in a `USE CB` / `USE TEX` layout line;
|
||||
* - a root CBV, SRV or UAV is declared at the title's own register and space, as given here
|
||||
* (b, t or u), so the root signature needs no change for it;
|
||||
* - a constants parameter is declared as a constant buffer at its own register and space;
|
||||
* - each root parameter of the last two kinds that a shader reads adds one layout line,
|
||||
* `USE ROOT <root parameter>`.
|
||||
*/
|
||||
typedef struct bx_shader_root_parameter {
|
||||
uint32_t type; /* D3D12_ROOT_PARAMETER_TYPE: 0 table, 1 constants, 2 CBV, 3 SRV, 4 UAV */
|
||||
uint32_t num_32bit_values; /* constants: how many; otherwise 0 */
|
||||
uint32_t shader_register; /* constants and root descriptors: the register; tables: 0 */
|
||||
uint32_t register_space; /* constants and root descriptors: the space; tables: 0 */
|
||||
} bx_shader_root_parameter_t;
|
||||
|
||||
typedef struct bx_shader_root_layout {
|
||||
const bx_shader_root_parameter_t* parameters; /* in root-parameter order */
|
||||
uint32_t parameter_count;
|
||||
uint32_t flags; /* the root signature's D3D12_ROOT_SIGNATURE_FLAGS, Xbox bits included */
|
||||
} bx_shader_root_layout_t;
|
||||
|
||||
/*
|
||||
* As bx_shader_translate_pair, with `layout` describing the pipeline's root signature. A NULL
|
||||
* `layout` gives exactly bx_shader_translate_pair. BX_SHADER_ERR_INVALID_BLOB also covers a
|
||||
* layout whose `parameters` is NULL with a non-zero count, or a parameter of an unknown type.
|
||||
* A shader that reads root data the layout does not account for is BX_SHADER_ERR_UNSUPPORTED.
|
||||
*/
|
||||
bx_shader_status_t bx_shader_translate_pair_rooted(
|
||||
const uint8_t* vs_bytes,
|
||||
size_t vs_len,
|
||||
const uint8_t* ps_bytes,
|
||||
size_t ps_len,
|
||||
const bx_shader_root_layout_t* layout,
|
||||
bx_shader_pair_translation_t* out
|
||||
);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@
|
||||
- [Project README](../README.md) — Overview, quick start, `bx-cli` commands, and verified scope.
|
||||
- [Roadmap](roadmap.md) — Single authoritative plan: the foundation milestones (M0–M2) and the stages the target build reaches (Boot, Picture, Menus, World, Fidelity, Playable), with exit gates and decision gates.
|
||||
- [Working Method](process/working-method.md) — What an agent does when told "work" — the blocker queue, run protocol, source ranks, pull-request shape and the starting queue.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — 6-track directory ownership, ABI freeze rule, and multi-agent Git workflow.
|
||||
- [Parallel Track Architecture](architecture/parallel-tracks.md) — Which track owns which directories, and how the tracks stay apart (one blocker per pull request, ABI first, self-contained tests). The rules themselves are in `AGENTS.md`.
|
||||
- [Wave 1 Parallel Backlog](issues/wave-1-backlog.md) — Non-overlapping starter issues across Tracks A–F.
|
||||
- [Frozen ABI Contracts](../abi/README.md) — Cross-DLL C headers (`abi/include/`) and canonical `.def` export tables (`abi/defs/`).
|
||||
- [Synthetic Conformance Suite](../tests/conformance/README.md) — Auto-discovered PE32+ conformance binaries.
|
||||
@@ -17,7 +17,7 @@
|
||||
- [ADR 0006: Retire in-tree native-first workspace](adr/0006-retire-in-tree-native-workspace.md) — Retirement of paused native code/scripts/docs from `main` (preserved at Git tag `native-first-final`).
|
||||
- [ADR 0007: API-set win32_bridge shims under CrossOver](adr/0007-api-set-shims-under-crossover.md) — Accepted: CrossOver answers the six API-set import names itself, so the shims are not loaded for static imports.
|
||||
- [ADR 0008: M2 Shader Format Gate](adr/0008-m2-shader-format-gate.md) — Proposed: Branch D1 (DXIL through D3DMetal, with the measured wave64 and 64-bit-atomic gaps as M3 work); ACCC-only containers refused with `E_NOTIMPL` until a lawful format source exists.
|
||||
- [ADR 0010: The GDK's texture libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), staged by `bx-cli run` for the target build from each machine's GDK; never reimplemented, committed or shipped.
|
||||
- [ADR 0010: The GDK's own libraries at run time](adr/0010-gdk-texture-libraries.md) — Accepted: console texture layouts and BCPack come from the GDK's own PC libraries (`xg_xs.dll`, `BCPack.dll`), and translated shaders are compiled with its PC `dxcompiler.dll`; all are staged by `bx-cli run` for the target build from each machine's GDK, and never reimplemented, committed or shipped.
|
||||
- [ADR 0009: Xbox-layout D3D12 objects](adr/0009-xbox-layout-d3d12-objects.md) — Proposed: `d3d12_xs` gives titles objects with the Xbox object layout and function-table order (generated from the Xbox header), hosting the PC proxies; Phase 1 covers the device chain and the objects it creates.
|
||||
|
||||
## Research, Testing & Licensing
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# ADR 0010: The GDK's texture libraries at run time
|
||||
# ADR 0010: The GDK's own libraries at run time (textures and the shader compiler)
|
||||
|
||||
Status: **Accepted** (2026-11-30, by the repository owner). The evidence is from local Apple Silicon runs by the implementer.
|
||||
|
||||
@@ -19,7 +19,8 @@ Reimplementing either would mean deriving the console's tiling rules and the BCP
|
||||
2. **From each machine's own GDK.** The libraries come from the GDK configured by `bx-cli setup`, which preflight already requires. They are found by their exports, not their place in the GDK.
|
||||
3. **Never committed or shipped**, unless the project records an authorization that covers redistributing them. Commits name only the documented interfaces (`XGCreateTextureComputer`, `BCPackDecompress`, ...), as with every other GDK contract.
|
||||
4. **Only for the target build.** Conformance tests check BetterXen's own shims, so the GDK's libraries are staged only when the executable is the configured target build, or with `--gdk-libraries`. `--no-gdk-libraries` turns them off.
|
||||
5. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
|
||||
5. **The shader compiler is open-source DXC, with the GDK as fallback** (added 2026-11-30, #720; revised #757). `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll`. Because Microsoft's prebuilt DXC release zip carries closed-source licence terms (`LICENSE-MS.txt`) and the GDK's `dxcompiler.dll` cannot be redistributed, BetterXen builds `dxcompiler.dll` (x64 Release) from the open-source `microsoft/DirectXShaderCompiler` repository (pinned tag `v1.9.2609`) via `.github/workflows/dxc-build.yml`. `bx-cli run` stages `dxcompiler.dll` from the configured open-source DXC folder (`bx-cli setup --dxc-dir <dir>` / `BX_DXC_DIR`) first, falling back to the GDK's PC `dxcompiler.dll` only when no open-source build is configured. `dxcompiler.dll` is recognised by name and export (`DxcCreateInstance`), never committed to the repository, and `dxil.dll` is not needed (`dxcompiler.dll` alone validates and signs DXIL).
|
||||
6. **BetterXen's `xg_xs` shim stays** as the fallback (and for CI, which has no GDK). Without the GDK's XG, console textures are sized linearly, and the run log says so (`gdk_xg`).
|
||||
|
||||
## Consequences
|
||||
|
||||
|
||||
@@ -1,46 +1,41 @@
|
||||
# Parallel Track Architecture & Contributor Handoff Guide
|
||||
# Parallel Track Architecture
|
||||
|
||||
BetterXen is organized so **5 to 8+ contributors** can develop the CrossOver-based Apple Silicon compatibility stack concurrently via Git and GitHub Issues without merge conflicts.
|
||||
BetterXen is organized so several contributors and coding agents can work at the same time without merge conflicts: the code is split into tracks, each with its own directories, around one frozen `abi/` contract.
|
||||
|
||||
## Repository Layout
|
||||
This page describes the layout. The rules themselves are in [AGENTS.md](../../AGENTS.md) (Sections 0, 2 and 7), and [docs/process/working-method.md](../process/working-method.md) explains the method behind them. Where this page and those disagree, they are right.
|
||||
|
||||
| Directory | Track | Language / Build | Purpose |
|
||||
## Tracks and directories
|
||||
|
||||
| Directory | Track | Language / build | Purpose |
|
||||
| --- | --- | --- | --- |
|
||||
| `abi/` | Shared (frozen) | C headers + `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and canonical DLL export lists |
|
||||
| `launcher/` | Track A | Rust (`aarch64-apple-darwin`) | Native ARM64 macOS CLI (`bx-cli`), PE32+ static probe (`bx-probe`), JSONL trace aggregator (`bx-telemetry`) |
|
||||
| `shims/runtime_veh/` | Track A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: `clwb` VEH handler, `adcx`/`adox` tripwire, Lockhart/Anaconda config, JSONL trace logger |
|
||||
| `shims/win32_bridge/` | Track A | C++20 (`mingw-w64`) | PSM AppNotify stubs + `ext-ms-win-rtcore-ntuser-*` → `user32.dll` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/` | Track B | C++20 (`mingw-w64`) | `xmem.dll`: physical/virtual/scatter memory allocator, `__XMemAllocationHooks__`, 16 GB Lockhart cap |
|
||||
| `shims/xcrdapi/` | Track B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage async I/O factory, queues, and decompression |
|
||||
| `shims/d3d12_xs/` | Track C1 | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox D3D12 COM proxy over Wine `d3d12.dll` (D3DMetal 3.0), `PresentX`, placed resources |
|
||||
| `shims/xg_xs/` | Track C2 | C++20 (`mingw-w64`) | `xg_xs.dll`: RDNA 2 texture tile addressing & swizzle layout computer |
|
||||
| `shims/ffx_bvh_hooks/` | Track C3 | C++20 (`mingw-w64`) | Optional PC FidelityFX/MetalFX upscaler shim & BVH4 rehydration → DXR live rebuild bridge |
|
||||
| `shader-transpiler/` | Track D | Rust (`aarch64` / C ABI) | `DXBC`/`DXIL`/`ACCC`/`FSPX` shader classifier, RDNA 2 → DXIL/MSL transpiler (M2 gate), shader cache, `d3dmetal-native` harness |
|
||||
| `shims/xgameruntime/` | Track E1 | C++20 (`mingw-w64`) | `xgameruntime.dll`: offline GDK runtime (`XTaskQueue`, `XAsync`, `XUser`, `XStore`, `XSystem`, `XPersistentLocalStorage`) |
|
||||
| `shims/gameinput/`, `shims/audio/` | Track E2 | C++20 (`mingw-w64`) | `GameInput.dll` ordinal 1 adapter + `AcpHal.dll`, `xapu.dll`, `chad.dll` audio/DSP shims |
|
||||
| `tests/conformance/` | Track F | C++20 (`mingw-w64`) | Clean-room synthetic PE32+ test executables verifying each shim under CrossOver/Wine |
|
||||
| `abi/` | ABI gate | C headers, `.def` | Cross-DLL contracts (`bx_log.h`, `bx_config.h`, `bx_xmem_internal.h`, `bx_shader_bridge.h`) and the canonical export list of every shim DLL |
|
||||
| `launcher/` | A | Rust (`aarch64-apple-darwin`) | `bx-cli` (setup, preflight, run, report), `bx-probe` (PE32+ import classifier), `bx-telemetry` (JSONL trace aggregator) |
|
||||
| `shims/runtime_veh/` | A | C++20 (`mingw-w64`) | `bx_runtime_veh.dll`: traps for instructions Rosetta 2 lacks, structured logging, fault diagnostics, the retry for faults on pages being remapped |
|
||||
| `shims/win32_bridge/` | A | C++20 (`mingw-w64`) | PSM AppNotify stubs and `ext-ms-win-rtcore-ntuser-*` forwarders; not loaded for static imports under CrossOver ([ADR 0007](../adr/0007-api-set-shims-under-crossover.md)) |
|
||||
| `shims/xmem/` | B | C++20 (`mingw-w64`) | `xmem.dll`: Xbox virtual and physical memory APIs, physical page mapping, the Lockhart memory budget |
|
||||
| `shims/xcrdapi/` | B | C++20 (`mingw-w64`) | `XCRDAPI.dll`: DirectStorage factory, queues, zlib and BCPack requests |
|
||||
| `shims/d3d12_xs/` | C | C++20 (`mingw-w64`) | `d3d12_xs.dll`: Xbox-layout Direct3D 12 objects over the host's Direct3D 12 ([ADR 0009](../adr/0009-xbox-layout-d3d12-objects.md)), `PresentX`, resources in title memory, console pipelines translated at first draw |
|
||||
| `shims/xg_xs/` | C | C++20 (`mingw-w64`) | `xg_xs.dll`: BetterXen's texture-layout shim. For the target build `bx-cli run` stages the GDK's own library in its place ([ADR 0010](../adr/0010-gdk-texture-libraries.md)) |
|
||||
| `shims/ffx_bvh_hooks/` | C | C++20 (`mingw-w64`) | Reserved for upscaler and BVH work |
|
||||
| `shader-transpiler/` | D | Rust | `gfx10-translate` (RDNA 2 decoder and translator to HLSL), `dxbc-accc` (container classifier and the C interface, built for Windows as `bx_shader_bridge.dll`), `d3dmetal-harness` |
|
||||
| `shims/xgameruntime/` | E | C++20 (`mingw-w64`) | `xgameruntime.dll`: offline GDK runtime (task queues, async, users, saves, packages) |
|
||||
| `shims/gameinput/`, `shims/audio/` | E | C++20 (`mingw-w64`) | `GameInput.dll`, and `AcpHal.dll`, `xapu.dll`, `chad.dll` |
|
||||
| `tests/conformance/`, `docs/` | F | C++20 (`mingw-w64`), Markdown | Synthetic test programs, one folder each (`test_<name>/`), discovered automatically; documentation |
|
||||
|
||||
*(The earlier native-first research workspace was retired from `main` per [ADR 0006](../adr/0006-retire-in-tree-native-workspace.md) and remains permanently accessible at Git tag `native-first-final`.)*
|
||||
The earlier native-first workspace was retired from `main` by [ADR 0006](../adr/0006-retire-in-tree-native-workspace.md) and is preserved at the Git tag `native-first-final`.
|
||||
|
||||
## Milestones (M0 → M6)
|
||||
## How the tracks stay apart
|
||||
|
||||
1. **M0 — Repo, ABI & Cross-Build:** One-command ARM64 + x86-64 PE32+ build, export verification, and `test_veh_clwb.exe` passing under CrossOver + Rosetta 2 (`ROSETTA_ADVERTISE_AVX=1`).
|
||||
2. **M1 — Boot to `D3D12XboxCreateDevice`:** Zero missing imports; all 17 shim DLLs (16 mingw-w64 C++ shims plus the Rust `bx_shader_bridge.dll`) load cleanly; auto-logging COM proxy captures startup call traces.
|
||||
3. **M2 — First Frame & Shader Format Gate:** Present real frames through D3DMetal 3.0 (`PresentX` → `IDXGISwapChain3::Present`) and classify runtime shaders (`DXIL` fast path vs. `ACCC`/`FSPX` RDNA 2 transpilation).
|
||||
4. **M3 — Full Shaders, Streaming & Texture Correctness:** Async DirectStorage decompression, accurate RDNA 2 `xg_xs` tiling/deswizzling, full shader pipeline.
|
||||
5. **M4 — 3D World, Ray Tracing & Input:** BVH4 rehydration → live D3DMetal 3.0 DXR build, FidelityFX/MetalFX upscaling shim, full `GameInput` controller/KB/M mapping.
|
||||
6. **M5 — Real Audio, Saves & Stability:** Software audio/DSP decoding behind `AcpHal`/`xapu`/`chad`, `PersistentLocalStorage` saves, multi-hour soak testing.
|
||||
7. **M6 — Shader Cache, 16 GB Optimization & Polish:** Persistent disk PSO/shader cache, Lockhart 16 GB unified memory tuning, Metal System Trace optimization, Swift launcher UI.
|
||||
- **One blocker, one pull request.** Work is found by running the target build and taking the first thing it stops on. A draft pull request titled with the blocker's signature is the claim; open pull requests are checked first, and a pull request that already covers the problem is worked on, not duplicated.
|
||||
- **Stay in the track's directories.** A fix touches only the directories its blocker needs. Maintainer-directed startup and compatibility work may cross tracks, without overlapping anyone's open claim.
|
||||
- **ABI first.** A new cross-DLL helper or export starts as a small `[ABI]` pull request that touches only `abi/`, so the provider and the consumer can be written in parallel. The header carries the contract; the `.def` line arrives with the implementation, because the build verifies every export.
|
||||
- **Tests never collide.** A conformance test is its own folder, `tests/conformance/test_<name>/` with a `CMakeLists.txt` and a `main.cpp`. Nothing shared is edited to add one.
|
||||
- **Branches.** `track-<a..f>/<slug>` from `origin/main`, in the contributor's own worktree and their own CrossOver bottle.
|
||||
|
||||
## Zero-Conflict Git & Issue Protocol
|
||||
## Stages, not milestones
|
||||
|
||||
- **ABI-first:** Any cross-track header or `.def` change lands first in a small `[ABI]` PR touching only `abi/`.
|
||||
- **Branch naming:** `track-<a..f>/<issue>-<slug>` off `main`, squash-merged daily.
|
||||
- **Exclusive file scope:** Every issue lists the exact directories it may edit (using `.github/ISSUE_TEMPLATE/track-handoff.yml`). Never edit another track's folder in a feature PR.
|
||||
- **Local verification:**
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
scripts/build-shims.sh
|
||||
```
|
||||
The first three milestones (M0 to M2) were defined by subsystems and synthetic tests, and are history. Since then progress is measured in stages of what the target build does: Boot, Picture, Menus, World, Fidelity, Playable. [docs/roadmap.md](../roadmap.md) is the single authoritative roadmap and names the current stage.
|
||||
|
||||
## Verification before a pull request
|
||||
|
||||
The commands are in [AGENTS.md](../../AGENTS.md) Section 8: the Rust checks, `scripts/build-shims.sh` (which also verifies every DLL's exports), the live conformance tests under CrossOver, and the documentation check.
|
||||
@@ -146,16 +146,27 @@ It ends with a ten-run summary and a list of **signatures**, the strings pull re
|
||||
|
||||
**What exists today** (#664): `bx-cli report <log.jsonl>...` produces the per-run report and the summary with signatures from run logs, and `bx-cli run` records how each run ended. Not yet in the launcher: the offline runner, per-session bottles, the machine-wide lock, thread stacks on a stall, and stall detection itself (frames are logged at powers of two, so a log cannot yet tell a stall from slow presentation).
|
||||
|
||||
## Order of lookup
|
||||
|
||||
The ranks below say how much a source can be trusted. They are not the order to look in. Look in the cheapest place that can answer first:
|
||||
|
||||
1. **The GDK** headers and documentation, for the contract itself.
|
||||
2. **The Ghidra results and the module's strings**, for how the build calls something, with what, and what it does with the answer: seconds, no GPU, no run. `bx-cli report` prints each unimplemented call's callers as `module+offset`; `bx-cli ghidra <module+offset>` names the function and its decompiled file.
|
||||
3. **A run**, only for what depends on run-time state: values, timing, which branch was taken. Prefer the cheapest run that answers, for example reading a module's own debug output, before writing new diagnostics.
|
||||
4. **New diagnostic code**, when nothing above can answer.
|
||||
|
||||
Runs take minutes each and share the machine's one GPU with every other session, so a question the Ghidra results answer is never a reason to run the build.
|
||||
|
||||
## Sources of truth
|
||||
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request.
|
||||
When a fix needs to know what the console does, use the strongest source available and name its rank in the pull request. A rank says how far a source can be trusted, not where to look first ([Order of lookup](#order-of-lookup)).
|
||||
|
||||
| Rank | Source | Notes |
|
||||
| --- | --- | --- |
|
||||
| 1 | Authorized GDK documentation and headers | Derived facts may be committed. The files never are. |
|
||||
| 2 | Our own compiler output for our own source | Built with the console compiler from the GDK. |
|
||||
| 3 | Run-time observation of the target build | What it calls, with what, and what it does with the answer. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | When observation cannot explain a wait or a branch. Local only. |
|
||||
| 4 | Call-site analysis of the target build (a disassembler such as Ghidra) | Consulted first for how the build calls something; ranked below observation because a run shows what actually happened. Local only. |
|
||||
| 5 | The authorized upstream emulator's source | A hint about what the build needs, not a reference for correctness. Confirm with ranks 1–4 or with runs. |
|
||||
|
||||
Collaborators may install the GDK and a disassembler for this. AGENTS.md §6 is unchanged: nothing from the build enters git, issues or pull requests — no bytes, file names, hashes, addresses or decompiled code.
|
||||
|
||||
@@ -11,6 +11,7 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| Direct3D 12 to Metal | D3DMetal | **Evaluate as external**, subject to license | Not in CodeWeavers' FOSS list; terms and availability to verify (#349, #354). Not redistributable until proven. |
|
||||
| D3D12 on D3DMetal outside Wine (fault isolation) | utmapp/d3dmetal-native | **Adopt as external, opt-in test dependency** (#417) | MIT; built and run at `af1ee17` (see the registry's M1-D2 section). The user builds it; BetterXen copies none of it, and only the x86_64 probe links it. It forces an x86_64 process under Rosetta 2 because D3DMetal is x86_64-only. BetterXen's arm64 tools drive that process instead of loading the framework. Never use its D3DMetal binary patcher. |
|
||||
| Shader compilation for BetterXen's own test kernels | DirectX Shader Compiler (official release) | **Use as external tool** (#417) | Run under CrossOver Wine because there is no macOS release. Only compiler output of BetterXen's own HLSL is committed, with version and hashes recorded. The package's Microsoft licence terms cover its closed-source parts, which are never redistributed. |
|
||||
| Run-time HLSL compilation for translated console shaders (`dxcompiler.dll`) | DirectX Shader Compiler (source build at `v1.9.2609`) | **Build from source in CI and stage as external binary** (#757) | University of Illinois/NCSA Open Source License (`LICENSE.TXT`, permissive and GPL-3.0-compatible; per-file check recorded in `upstream-registry.md`). Built x64 Release by `.github/workflows/dxc-build.yml` and staged by `bx-cli run` via `--dxc-dir` / `BX_DXC_DIR` ahead of any GDK fallback. No binary is committed to `main`. |
|
||||
| Direct3D 11/10 to Metal | DXMT | **Evaluate** as external binary or build | LGPL 2.1-or-later; usable as a separate process or library under LGPL terms; linking or copying needs legal review (#354). |
|
||||
| Direct3D to Vulkan | DXVK | **Evaluate** only together with MoltenVK | zlib/libpng is permissive and GPL-compatible. Value on macOS unknown. |
|
||||
| Direct3D 12 to Vulkan | VKD3D-Proton | **Evaluate**; blocked on a Vulkan 1.3 provider | Depends on MoltenVK feature coverage, unknown. |
|
||||
@@ -24,5 +25,6 @@ Companion to the [upstream registry](upstream-registry.md); same evidence limits
|
||||
| Public PC DirectStorage interface definitions (IIDs, structs, vtable order) | `dstorage.h` and `dstorageerr.h` from NuGet `Microsoft.Direct3D.DirectStorage` 1.4.0 (MIT per file) | **Vendor unmodified** (#483) | MIT notices kept in the files, with `LICENSE-CODE.txt` alongside and in `THIRD_PARTY_NOTICES.md`. Only the headers are used; the package's DLLs and other files fall under Microsoft's proprietary SDK terms and are never redistributed. |
|
||||
| Xbox console DirectStorage interfaces (`IDStorageFactoryX` and others) | `dstorage_xs.h` (GDK with Xbox Extensions) | **Rejected until a licence-compatible source exists** (#483) | Available only to licensed partners. Microsoft Learn and the MIT `Xbox-GDK-Samples` `dstorage_win32.h` document signatures and struct layouts but not the IIDs. |
|
||||
| GDK `QueryApiImpl` class and interface ids, inheritance and slot order for XGameSave and XPackage | xodus-gaming/xgameruntime-docs at `7090008` (GPL-3.0 text) | **Use as factual reference, pending maintainer provenance acceptance** (#468, #492) | Only interface facts are used, written as BetterXen's own code; no text or code is copied. The source describes its method as black-box reverse engineering under Wine's clean-room guidelines. `IXError` slot 3's `false` answer comes from the #492 review's interop observation instead; that source lists the slot as unknown. Revisit if the source's method or licence status changes. |
|
||||
| Console texture swizzle layouts (`xg_xs`) | Mesa `src/amd/addrlib` at `0b97dcdd` (MIT) | **Vendor unmodified** (#756) | gfx10 layouts for a swizzle mode a title requests. The copy lives at `shims/xg_xs/third_party/addrlib`. Two files lack an SPDX line; see the registry and `THIRD_PARTY_NOTICES.md`. The GDK `xg_xs.dll` stays a local comparison reference and is not redistributed. |
|
||||
|
||||
Open items: license text for every selected component must be read from the exact release used; DXMT, DXVK and Wine contributor and file-level notices are not reviewed.
|
||||
@@ -58,9 +58,62 @@ For each such load, the compiler also reported the instruction offset and the HL
|
||||
- **Wave64** is the default. The D1 path also needs to know whether a title's DXIL assumes 64 lanes.
|
||||
- **Bounds:** out-of-range accesses through root descriptors are not discarded on the console the way bounds-checked descriptors would discard them.
|
||||
|
||||
## Graphics stages: root data in registers (ACO path)
|
||||
|
||||
Recorded 2026-11-30, for the translator's root-signature layout (#715). Unlike the probes above, these six were compiled with `xdxc`, whose ACO back end produces the code that ACCC containers carry, and read with the project's own disassembler (`cargo run -p gfx10-translate --example listing`). Same host and GDK as above. Each probe is a `vs_6_6` vertex shader (one is `ps_6_6`) of the project's own with an explicit `[RootSignature]`; every declared parameter is used, so none is optimised away.
|
||||
|
||||
| Probe | Root signature | Where the shader reads each parameter |
|
||||
| --- | --- | --- |
|
||||
| g0 (VS) | `SRV(t0)` | address in `s8` (low), `s9` (high) |
|
||||
| g1 (VS) | `RootConstants(1, b0), SRV(t0)` | constant `s8`; address `s9`, `s10` |
|
||||
| g2 (VS) | `DescriptorTable(CBV(b0)), SRV(t0), RootConstants(2, b1), CBV(b2)` | table pointer `s8`; SRV address `s9`, `s10`; constants `s11`, `s12`; CBV address `s13`, `s14` |
|
||||
| g3 (PS) | the same as g2 | the same registers as g2 |
|
||||
| g4 (VS) | `SRV(t0, visibility = PIXEL), SRV(t1)` | `t1` address in `s10`, `s11` |
|
||||
| g5 (VS) | `DescriptorTable(CBV(b0)), DescriptorTable(CBV(b1)), SRV(t0)` | table pointers `s8`, `s9`; address `s10`, `s11` |
|
||||
|
||||
**Measured:**
|
||||
- **Start and order.** Root data starts at `s8` in a vertex and in a pixel shader, in root-parameter order (g2 and g3 agree register for register).
|
||||
- **Sizes.** A descriptor-table parameter takes one SGPR, a root constant one per 32-bit value, a root SRV or CBV two (low dword first).
|
||||
- **No alignment.** A 64-bit address directly follows an odd number of one-SGPR parameters (g1: `s9`, `s10`). This answers the "SGPR alignment" question below for this path.
|
||||
- **Visibility does not renumber.** A parameter the stage cannot see still occupies its registers (g4).
|
||||
- **Table pointers are 32-bit.** The shader copies the next register away if it needs it, writes 0 to it, and loads through the pair (g2: `s_mov_b32 s9, 0`, then `s_load_dwordx4 s[0:3], s[8:9]`). For a table that is not first, it builds the pair in other registers (g5: `s2 = s9`, `s3 = 0`).
|
||||
- **Root buffers.** For a root SRV or CBV the shader builds the buffer descriptor itself: word 0 the low address, word 1 the high address OR the stride in bits 16 and up (`0x100000` for a 16-byte element), word 2 `-1`, word 3 `0x11014fac`. A structured-buffer read is `buffer_load_dwordx4 ..., idxen` with the element index; a root CBV is read with `s_buffer_load_dwordx4` at a byte offset.
|
||||
|
||||
**The memory-based form.** Two more probes set root flags that the target build's root signatures also set (the compiler accepts them as `RootFlags(XBOX_FORCE_MEMORY_BASED_ABI)` and `XBOX_FORCE_COMPUTE_2_SPILL_AREA`):
|
||||
|
||||
| Probe | Root signature | Where the shader reads each parameter |
|
||||
| --- | --- | --- |
|
||||
| g6 (VS) | `RootFlags(XBOX_FORCE_MEMORY_BASED_ABI), SRV(t0)` | two dwords loaded from offset 0 of the root data in memory |
|
||||
| g7 (VS) | both flags, then the parameters of g2 | table pointer at offset 0; SRV address at 4; constants at 0xC and 0x10; CBV address at 0x14 |
|
||||
|
||||
- The shader forms the address of the root data from `s0` (low dword) and the low 8 bits of `s1` (`s_and_b32 s3, s1, 0xff`), and reads every parameter from there with `s_load_dword` / `s_load_dwordx2`. No root data is read from `s8` and up.
|
||||
- The offsets are four bytes per root dword, in the same packed parameter order as the registers: a parameter that would be in `s(8 + d)` is at byte `4 * d`.
|
||||
- `s0:s1` as the address of the root data matches the overflow case seen on the other compiler path (p10 above).
|
||||
|
||||
**Inferred:** the layout is a function of the root parameter list alone: each parameter has a root dword index, read from `s(8 + d)` or, in the memory-based form, from byte `4 * d` of the root data. A translator that is given the list (type and number of 32-bit values per parameter) can tell which parameter a shader reads. Not probed: root UAVs in graphics stages, more root data than fits in registers without the flag, what the upper bits of `s1` hold, and the other graphics stages.
|
||||
|
||||
## Directly indexed descriptor heaps (SM 6.6, ACO path)
|
||||
|
||||
Recorded 2026-11-30, from pixel shaders of the target build that index the sampler heap. Their root signature has the flag `0x800`, `D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED`, and their code reads a register past the root data. Probes of the project's own, compiled with `xdxc -T ps_6_6` and read with `cargo run -p gfx10-translate --example listing`:
|
||||
|
||||
| Probe | Root signature | What the code reads |
|
||||
| --- | --- | --- |
|
||||
| s0 | `DescriptorTable(SRV(t0)), RootConstants(2, b0), DescriptorTable(Sampler(s0, numDescriptors=8))` | texture descriptor from the SRV table `s8`; sampler `samplers[idx]` from the sampler table `s11`, at `idx << 4` (`idx` = constant `s9`) |
|
||||
| s2 | `RootFlags(SAMPLER_HEAP_DIRECTLY_INDEXED), DescriptorTable(SRV(t2, space=1)), RootConstants(2, b500)` | texture descriptor from the table `s8`; `SamplerDescriptorHeap[idx]` from `s11`, at `idx << 4` |
|
||||
| s3 | `RootFlags(CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED \| SAMPLER_HEAP_DIRECTLY_INDEXED), RootConstants(2, b500)` | `ResourceDescriptorHeap[other]` from `s10` at `other << 5`; `SamplerDescriptorHeap[idx]` from `s11` at `idx << 4`; `m0` from `s12` |
|
||||
|
||||
**Measured:**
|
||||
- **Heap pointers follow the root data**, one register each: the resource heap (`CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED`, `0x400`) first, then the sampler heap (`SAMPLER_HEAP_DIRECTLY_INDEXED`, `0x800`). With the root data of s2 (`s8`, `s9`, `s10`) the sampler heap is `s11`; with that of s3 (`s8`, `s9`) the resource heap is `s10` and the sampler heap `s11`. A pixel shader's `m0` value follows them (`s12` in s3).
|
||||
- They are **32-bit pointers**, like table pointers: the shader writes 0 to the next register and loads through the pair (`s_mov_b32 s11, 0` then `s_load_dwordx8 s[0:7], s[10:11], s0`), or copies the pointer away first (`s14 = s11`, `s15 = 0`).
|
||||
- **Strides:** a resource descriptor is 32 bytes (`s_lshl_b32 s0, s9, 5`, then `s_load_dwordx8`), a sampler descriptor 16 bytes (`s_lshl_b32 ..., 4`, then `s_load_dwordx4`), the same sizes as table entries.
|
||||
- The target build's shaders with this flag have exactly s2's code at their start (the sampler from `s11` at a root constant times 16), so this is the form ACCC containers carry for `SamplerDescriptorHeap[i]`.
|
||||
- With a sampler table instead of the flag (s0), the code is the same; only what `s11` points at differs.
|
||||
|
||||
**Not probed:** the memory-based form with these flags, vertex shaders, compute (where root data starts at `s4`), and whether a heap pointer can be absent from user data when a stage does not index that heap.
|
||||
|
||||
## Open
|
||||
|
||||
- **Graphics stages** (vertex and pixel inputs, exports) were not probed.
|
||||
- **Graphics stages:** root data is probed above; vertex and pixel inputs and exports are not.
|
||||
- **ACCC-only output:** `xdxc` emits containers that keep DXIL and add ACCC. Which compiler or option emits ACCC-only (DXIL-stripped) containers, like those in the target workload's upscaler component (see the [roadmap](../roadmap.md) scan entry), is open.
|
||||
- **ACO agreement:** which of these NewBE facts hold for the ACO code (see "Root buffer access").
|
||||
- **SGPR alignment:** every probe placed its 64-bit root addresses after an even number of SGPRs. Whether an odd count of one-SGPR parameters before a root descriptor inserts a padding SGPR is untested.
|
||||
|
||||
@@ -16,6 +16,7 @@ Reviewed 2026-11-25. Every entry is **evidence class D** (non-normative official
|
||||
| PortWatch VI | [portwatch-vi.xyz](https://portwatch-vi.xyz/), [4lwayz/portwatch-vi](https://github.com/4lwayz/portwatch-vi) | `ed00263cc0c9` | NOASSERTION | Project discovery reference | A tracker of community efforts; progress figures are editorial, with self-reported claims labelled. Not engineering evidence; flagged and ignored queues are not endorsed. |
|
||||
| LLVM (AMDGPU target) | [llvm/llvm-project](https://github.com/llvm/llvm-project) | Homebrew LLVM 23.1.6 (`llvm-mc`) | Apache-2.0 WITH LLVM-exception | Source of the generated GFX10.3 opcode table and decoder test vectors (`shader-transpiler/crates/gfx10-translate`) | Run locally by `scripts/console-shader/gen_opcodes.py` and `gen_llvm_vectors.py`. Only facts are committed (opcode number to mnemonic, instruction words to text); no LLVM code or tables are copied. Accepted by the repository owner on 2026-11-30 (AGENTS.md Section 4). |
|
||||
| libc | [rust-lang/libc](https://github.com/rust-lang/libc) | `0.2.191` (`ccc2ff4aaab9`) | MIT OR Apache-2.0 (used under MIT) | `bx-cli` process groups and signals (#408) | Unmodified crates.io dependency, locked checksum. |
|
||||
| Mesa addrlib | [mesa/mesa `src/amd/addrlib`](https://gitlab.freedesktop.org/mesa/mesa/-/tree/0b97dcdd9424fce130054e1972a610b765644003/src/amd/addrlib) | tag `mesa-25.2.0`, commit `0b97dcdd9424fce130054e1972a610b765644003` | MIT, per file, with the exception below | Vendored, unmodified, into `shims/xg_xs/third_party/addrlib` for console swizzle layouts (#756) | 42 of 44 files carry `SPDX-License-Identifier: MIT`. `src/core/addrswizzler.cpp` and `addrswizzler.h` carry an AMD 2024 copyright and "All rights reserved" and no SPDX line in this version; AMD added `SPDX-License-Identifier: MIT` to both upstream in Mesa commit `d778ede72` (2026-04-17, MR 40958). `meson.build` (SPDX MIT) compiles them, and gfx10 includes them, so they are kept unmodified. Accepted for this use by the task that vendors it; the two files without an SPDX line are called out in `THIRD_PARTY_NOTICES.md`. |
|
||||
|
||||
## Built and run for M1-D2 (#417)
|
||||
|
||||
@@ -25,7 +26,8 @@ Unlike the table above, these entries were cloned at the stated pin, built and r
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| d3dmetal-native | [utmapp/d3dmetal-native](https://github.com/utmapp/d3dmetal-native) | `af1ee1710711fadff41dead87960d0f1336c1047` (2026-10-26) | Repository `LICENSE`: MIT, © 2026 Turing Software LLC. 34 of 37 `src/` files and the public header carry `SPDX-License-Identifier: MIT`. `src/dmn_dxil_reflect.{cpp,h}`, `src/exports.symbols`, `scripts/` and about half of `tests/` have no per-file notice, so only the repository `LICENSE` covers them. `include/native/` holds WIDL-generated MinGW-w64/Wine headers under LGPL-2.1-or-later (`include/native/directx/README.md`, `COPYING.MinGW-w64.txt`). | External, opt-in, built by the user. It hosts a user-supplied `D3DMetal.framework` outside Wine for the M1-D2 harness. No source is copied into BetterXen. | It builds only as x86_64, because `meson.build` rejects other targets and D3DMetal is x86_64-only. Consumers must therefore be x86_64 processes under Rosetta 2. It loads the framework from an explicit path, `$D3DMETAL_FRAMEWORK_PATH`, or locations next to the dylib. Its optional `scripts/patch_d3dmetal_imports.py` rewrites the D3DMetal binary for App Store builds; BetterXen must not use it, and the harness works with an unpatched framework. Against CrossOver 26.3's D3DMetal 3.0, its `dmn-smoke` and `dmn-device-test` passed, while `d3d12-atomic64-test` read back zeros (not diagnosed). |
|
||||
| directx-native | [osy/directx-native](https://github.com/osy/directx-native) | `7258be1c56cdbf1e55c56b1bc4a866169c8ca0da` (pinned by d3dmetal-native's `subprojects/directx-native.wrap`) | Apache-2.0: repository `LICENSE`, plus `SPDX-License-Identifier: Apache-2.0` in 22 of its 25 files | Build dependency of d3dmetal-native, statically linked into the dylib; nothing is copied into BetterXen | Supplies the shared-resource and embedder headers that `d3dmetal_native.h` includes. Apache-2.0 is compatible with GPL-3.0, not GPL-2.0. |
|
||||
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The package ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
|
||||
| DirectX Shader Compiler | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.9.2609) | Release `v1.9.2609`, `dxc_2026_09_29.zip`, SHA-256 `ad31b1fc8443175d204f77a611fdb3ef2ec42759bdc2f1167368de24a4a7e7f1` | The prebuilt zip ships the LLVM Release License, an MIT licence and Microsoft Software License Terms (`LICENSE-MS.txt`, covering the closed-source parts of the package) | External tool, used once to compile BetterXen's own HLSL kernel. Only its output (`fill_cs66.h`) is committed. | There is no macOS release, so `bin/x64/dxc.exe` was run under CrossOver 26.3 Wine. It reported `dxcompiler.dll 1.9.2609.5 (01b62ad47)`. |
|
||||
| DirectX Shader Compiler (source build for `dxcompiler.dll`) | [microsoft/DirectXShaderCompiler](https://github.com/microsoft/DirectXShaderCompiler/tree/v1.9.2609) | Tag `v1.9.2609` | Repository `LICENSE.TXT` is the University of Illinois/NCSA Open Source License (LLVM Release License), with third-party notices in `LICENSE.TXT` for `lib/Miniz/*` (MIT / Unlicense), `lib/Support/*` (Henry Spencer), and `include/llvm/Support/ConvertUTF.h` (Unicode). Source files inspected (e.g. `tools/clang/tools/dxcompiler/DXCompiler.cpp`) carry the University of Illinois Open Source License header. No `LICENSE-MS.txt` is present in the source tree. | Run-time HLSL compiler (`dxcompiler.dll`, x64 Release) built from source by `.github/workflows/dxc-build.yml` and staged by `bx-cli run` (#757). | Built from source on Windows to avoid both the GDK's non-redistributable `dxcompiler.dll` and the prebuilt zip's `LICENSE-MS.txt`. `dxcompiler.dll` alone validates and signs DXIL (`dxil.dll` is not needed). |
|
||||
|
||||
## Interface facts for XGameSave and XPackage (#468, #492)
|
||||
|
||||
|
||||
+5
-1
@@ -82,10 +82,14 @@ Every gate below is measured the same way ([working method](process/working-meth
|
||||
This is where the shader translator becomes the critical path, and where the D3DMetal route is tested for real. The risk checks come **first**, before feature work depends on them.
|
||||
|
||||
1. **Capability checks on D3DMetal (first).** Synthetic tests, one each, for what translated shaders need: direct descriptor-heap indexing (SM 6.6), 64-lane compute behaviour through the translator's emulation, 64-bit atomics on typed resources, mesh and amplification shaders. Each ends in *runs correctly*, *can be worked around in the translator*, or *blocked*. A *blocked* result opens an ADR on the back end, marked `needs-human`, before anything else in this stage continues.
|
||||
2. **The translator.** BetterXen writes its own GFX10-to-DXIL translator in `shader-transpiler/` and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). The design is mechanical: one rule per instruction, registers as variables, and control flow as numbered blocks in a dispatch loop, so no structure has to be reconstructed. Each rule is checked against the console compiler's output for a shader of our own (source rank 2). A prototype on branch `experiment/visible-frame` translates the four pipelines of the build's first screen and is the reference for that screen.
|
||||
*State (2026-11-30): not done in this order.* The translator and its run-time path were built first, on the vertex and pixel shaders of the build's first screens, which need none of these capabilities. The checks still come before compute shaders (64-lane behaviour, 64-bit atomics) and before anything that indexes descriptor heaps directly.
|
||||
2. **The translator.** BetterXen writes its own translator in `shader-transpiler/` (`gfx10-translate`) and exposes it through `bx_shader_bridge.dll`; the upstream emulator's translator is not used (repository owner's decision, 2026-11-29). It turns GFX10 code into **HLSL**, not DXIL directly: `d3d12_xs` compiles the HLSL to DXIL with the GDK's PC `dxcompiler.dll` when a pipeline is first drawn, and keeps the result on disk ([ADR 0010](adr/0010-gdk-texture-libraries.md)). The design is mechanical: one rule per instruction, registers as variables, and control flow as numbered blocks in a dispatch loop, so no structure has to be reconstructed.
|
||||
*How rules are checked today:* each rule has a test whose instruction words come from the public LLVM assembler and whose expected HLSL is written from the instruction's definition. Checking against the console compiler's output for a shader of our own (source rank 2) is the standard this item set; so far it has been done for the root-data layout ([docs/research/console-shader-abi.md](research/console-shader-abi.md)) and not rule by rule. The Python prototype on branch `experiment/visible-frame` is kept as a reference; the Rust translator matched its output on the pairs both translate.
|
||||
3. **Translator verification.** Extend the known-source corpus (#650) so every instruction class the first screens use is checked against a reference result. A translator bug is found with a ten-line shader, not in a broken frame.
|
||||
4. **The first pipelines.** The clear pipeline, the display-mapping compute shader, and whatever the first reference screen draws with, created on the host on first use.
|
||||
*State (2026-11-30):* vertex/pixel pipelines are translated at first draw (opt-in, `BX_CONSOLE_SHADERS=1`), and every one the build draws with in its first two minutes translates. Compute pipelines are not translated; their dispatches are skipped (#746).
|
||||
5. **Descriptors and memory the shaders read.** The descriptor model the translated shaders expect; contents of textures placed in title memory (today a logged stub); title-written constant and vertex data reaching the GPU.
|
||||
*State (2026-11-30):* descriptors the title copies itself are followed, and root signature layouts are passed to the translator. Open: texture contents (#745), and why the first screen shows only its background bars (#744). Two known simplifications: every translated shader samples with one fixed sampler (#750), and a descriptor table is widened for its first 8 entries only (#751).
|
||||
|
||||
### Menus to Playable — known work and unknowns
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! The GDK's own texture libraries, staged for runs of the target build (ADR 0010).
|
||||
//! Runtime texture and shader-compiler libraries staged for runs of the target build (ADR 0010).
|
||||
//!
|
||||
//! Console textures use tiled layouts and BCPack compression. BetterXen does not reimplement
|
||||
//! either: a run of the target build loads Microsoft's PC builds of the GDK's XG library
|
||||
@@ -11,6 +11,12 @@
|
||||
//! import `xmem.dll` (the console build does), and one named `BCPack.dll` that exports
|
||||
//! `BCPackDecompress`. Conformance tests keep BetterXen's own shim: the GDK's are staged only
|
||||
//! for the configured target build, or with `--gdk-libraries`.
|
||||
//!
|
||||
//! `d3d12_xs` compiles the HLSL of translated console shaders with `dxcompiler.dll` (#720, #757).
|
||||
//! `dxcompiler.dll` is taken first from the configured BetterXen-built open-source DXC folder
|
||||
//! (`--dxc-dir` / `BX_DXC_DIR`), falling back to the GDK's PC `dxcompiler.dll` only if no
|
||||
//! open-source build is configured. It is recognised as an x86-64 PE32+ file named
|
||||
//! `dxcompiler.dll` that exports `DxcCreateInstance`; `dxil.dll` is not needed.
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
@@ -22,6 +28,8 @@ use bx_probe::probe_pe32_plus;
|
||||
pub struct GdkLibraries {
|
||||
pub xg: Option<PathBuf>,
|
||||
pub bcpack: Option<PathBuf>,
|
||||
/// The PC `dxcompiler.dll` (open-source DXC first, GDK fallback).
|
||||
pub dxc: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn contains(bytes: &[u8], needle: &[u8]) -> bool {
|
||||
@@ -46,11 +54,49 @@ pub fn is_bcpack(bytes: &[u8]) -> bool {
|
||||
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"BCPackDecompress\0")
|
||||
}
|
||||
|
||||
/// Finds the two libraries under `root` (bounded depth). When the GDK holds several builds,
|
||||
/// Whether `bytes` are a PC `dxcompiler.dll` (x86-64 PE32+ exporting `DxcCreateInstance`).
|
||||
pub fn is_dxc(bytes: &[u8]) -> bool {
|
||||
probe_pe32_plus(bytes).is_ok() && contains(bytes, b"DxcCreateInstance\0")
|
||||
}
|
||||
|
||||
/// Finds `dxcompiler.dll` under `dir` (bounded depth), recognised by name and `DxcCreateInstance`.
|
||||
pub fn find_dxc(dir: &Path) -> Option<PathBuf> {
|
||||
let mut dxc = Vec::new();
|
||||
let mut stack = vec![(dir.to_path_buf(), 0usize)];
|
||||
while let Some((cur, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&cur) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
if kind.is_dir() {
|
||||
if depth < 14 {
|
||||
stack.push((path, depth + 1));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if name != "dxcompiler.dll" {
|
||||
continue;
|
||||
}
|
||||
if fs::read(&path).is_ok_and(|bytes| is_dxc(&bytes)) {
|
||||
dxc.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
dxc.sort();
|
||||
dxc.into_iter().next()
|
||||
}
|
||||
|
||||
/// Finds the libraries under `root` (bounded depth). When the GDK holds several builds,
|
||||
/// the first by path order is used, so the choice is the same on every run.
|
||||
pub fn find(root: &Path) -> GdkLibraries {
|
||||
let mut xg = Vec::new();
|
||||
let mut bcpack = Vec::new();
|
||||
let mut dxc = Vec::new();
|
||||
let mut stack = vec![(root.to_path_buf(), 0usize)];
|
||||
while let Some((dir, depth)) = stack.pop() {
|
||||
let Ok(entries) = fs::read_dir(&dir) else {
|
||||
@@ -68,7 +114,7 @@ pub fn find(root: &Path) -> GdkLibraries {
|
||||
continue;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if name != "xg_xs.dll" && name != "bcpack.dll" {
|
||||
if !matches!(name.as_str(), "xg_xs.dll" | "bcpack.dll" | "dxcompiler.dll") {
|
||||
continue;
|
||||
}
|
||||
let Ok(bytes) = fs::read(&path) else {
|
||||
@@ -78,20 +124,34 @@ pub fn find(root: &Path) -> GdkLibraries {
|
||||
xg.push(path);
|
||||
} else if name == "bcpack.dll" && is_bcpack(&bytes) {
|
||||
bcpack.push(path);
|
||||
} else if name == "dxcompiler.dll" && is_dxc(&bytes) {
|
||||
dxc.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
xg.sort();
|
||||
bcpack.sort();
|
||||
dxc.sort();
|
||||
GdkLibraries {
|
||||
xg: xg.into_iter().next(),
|
||||
bcpack: bcpack.into_iter().next(),
|
||||
dxc: dxc.into_iter().next(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds `out` as a copy of the shim folder's files with the GDK's libraries added: its
|
||||
/// `xg_xs.dll` replaces BetterXen's shim, and `BCPack.dll` sits beside it. Returns the path of
|
||||
/// the staged `BCPack.dll`, when there is one.
|
||||
/// Resolves runtime libraries, preferring BetterXen-built open-source `dxcompiler.dll` under
|
||||
/// `dxc_dir` and falling back to the GDK's `dxcompiler.dll` under `gdk_root` only if needed.
|
||||
pub fn resolve(dxc_dir: Option<&Path>, gdk_root: Option<&Path>) -> GdkLibraries {
|
||||
let mut libs = gdk_root.map(find).unwrap_or_default();
|
||||
if let Some(dxc) = dxc_dir.and_then(find_dxc) {
|
||||
libs.dxc = Some(dxc);
|
||||
}
|
||||
libs
|
||||
}
|
||||
|
||||
/// Builds `out` as a copy of the shim folder's files with the runtime libraries added: the
|
||||
/// GDK's `xg_xs.dll` replaces BetterXen's shim, `dxcompiler.dll` is staged beside it, and
|
||||
/// `BCPack.dll` sits beside it. Returns the path of the staged `BCPack.dll`, when there is one.
|
||||
pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<Option<PathBuf>> {
|
||||
fs::create_dir_all(out)?;
|
||||
for entry in fs::read_dir(shims)? {
|
||||
@@ -103,6 +163,9 @@ pub fn merge_shims(shims: &Path, libs: &GdkLibraries, out: &Path) -> io::Result<
|
||||
if let Some(xg) = &libs.xg {
|
||||
fs::copy(xg, out.join("xg_xs.dll"))?;
|
||||
}
|
||||
if let Some(dxc) = &libs.dxc {
|
||||
fs::copy(dxc, out.join("dxcompiler.dll"))?;
|
||||
}
|
||||
match &libs.bcpack {
|
||||
Some(bcpack) => {
|
||||
let staged = out.join("BCPack.dll");
|
||||
@@ -146,6 +209,9 @@ mod tests {
|
||||
));
|
||||
assert!(is_bcpack(&pe(b"BCPackCompress\0BCPackDecompress\0")));
|
||||
assert!(!is_bcpack(&pe(b"BCPackCompress\0")));
|
||||
assert!(is_dxc(&pe(b"DxcCreateInstance\0DxcCreateInstance2\0")));
|
||||
assert!(!is_dxc(&pe(b"DxcCreateInstance2\0")));
|
||||
assert!(!is_dxc(b"DxcCreateInstance\0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -162,7 +228,12 @@ mod tests {
|
||||
.unwrap();
|
||||
fs::write(gdk.join("c/xg_xs.dll"), pe(b"XGCreateTextureComputer\0")).unwrap(); // not the PC library
|
||||
fs::write(gdk.join("c/BCPack.dll"), pe(b"BCPackDecompress\0")).unwrap();
|
||||
// The PC compiler; a console compiler has another name, and dxil.dll is not needed.
|
||||
fs::write(gdk.join("a/dxcompiler.dll"), pe(b"DxcCreateInstance\0")).unwrap();
|
||||
fs::write(gdk.join("a/dxil.dll"), pe(b"DxcCreateInstance\0dxil")).unwrap();
|
||||
fs::write(gdk.join("c/dxcompiler_xs.dll"), pe(b"DxcCreateInstance\0")).unwrap();
|
||||
let libs = find(&gdk);
|
||||
assert_eq!(libs.dxc, Some(gdk.join("a/dxcompiler.dll")));
|
||||
assert_eq!(libs.xg, Some(gdk.join("a/b/xg_xs.dll")));
|
||||
assert_eq!(libs.bcpack, Some(gdk.join("c/BCPack.dll")));
|
||||
|
||||
@@ -179,6 +250,57 @@ mod tests {
|
||||
fs::read(gdk.join("a/b/xg_xs.dll")).unwrap()
|
||||
);
|
||||
assert_eq!(fs::read(shims.join("xg_xs.dll")).unwrap(), b"shim");
|
||||
assert_eq!(
|
||||
fs::read(out.join("dxcompiler.dll")).unwrap(),
|
||||
fs::read(gdk.join("a/dxcompiler.dll")).unwrap()
|
||||
);
|
||||
assert!(!out.join("dxil.dll").exists());
|
||||
assert!(!out.join("dxcompiler_xs.dll").exists());
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_source_dxc_takes_precedence_over_gdk_fallback() {
|
||||
let root = std::env::temp_dir().join(format!("bx-dxc-prec-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let gdk = root.join("gdk");
|
||||
let dxc_dir = root.join("open-source-dxc");
|
||||
let empty_dir = root.join("empty");
|
||||
fs::create_dir_all(&gdk).unwrap();
|
||||
fs::create_dir_all(&dxc_dir).unwrap();
|
||||
fs::create_dir_all(&empty_dir).unwrap();
|
||||
|
||||
fs::write(
|
||||
gdk.join("xg_xs.dll"),
|
||||
pe(b"XGCreateTextureComputer\0XGComputeTexture2DLayout\0"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(gdk.join("dxcompiler.dll"), pe(b"DxcCreateInstance\0gdk")).unwrap();
|
||||
fs::write(
|
||||
dxc_dir.join("dxcompiler.dll"),
|
||||
pe(b"DxcCreateInstance\0oss"),
|
||||
)
|
||||
.unwrap();
|
||||
// A file without DxcCreateInstance is ignored.
|
||||
fs::write(empty_dir.join("dxcompiler.dll"), pe(b"NotDxc\0")).unwrap();
|
||||
|
||||
// Open-source DXC wins over GDK fallback.
|
||||
let libs = resolve(Some(&dxc_dir), Some(&gdk));
|
||||
assert_eq!(libs.dxc, Some(dxc_dir.join("dxcompiler.dll")));
|
||||
assert_eq!(libs.xg, Some(gdk.join("xg_xs.dll")));
|
||||
|
||||
// Without dxc_dir (or with an invalid one), GDK dxcompiler.dll is used as fallback.
|
||||
let fallback = resolve(None, Some(&gdk));
|
||||
assert_eq!(fallback.dxc, Some(gdk.join("dxcompiler.dll")));
|
||||
let invalid_dxc = resolve(Some(&empty_dir), Some(&gdk));
|
||||
assert_eq!(invalid_dxc.dxc, Some(gdk.join("dxcompiler.dll")));
|
||||
|
||||
// Open-source DXC works even without a GDK.
|
||||
let oss_only = resolve(Some(&dxc_dir), None);
|
||||
assert_eq!(oss_only.dxc, Some(dxc_dir.join("dxcompiler.dll")));
|
||||
assert_eq!(oss_only.xg, None);
|
||||
assert_eq!(oss_only.bcpack, None);
|
||||
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -47,10 +47,13 @@ const HOST_ENV_ALLOWLIST: &[&str] = &[
|
||||
"XPC_SERVICE_NAME",
|
||||
];
|
||||
|
||||
/// Opt-in `bx_runtime_veh.dll` diagnostic switches. They carry addresses and counts, never
|
||||
/// credentials, so the isolated guest environment lets them through by name; every other
|
||||
/// variable is still stripped.
|
||||
/// Opt-in shim switches: `bx_runtime_veh.dll` diagnostics, and `d3d12_xs.dll`'s translation of
|
||||
/// console pipelines (`BX_CONSOLE_SHADERS=1`, with `BX_SHADER_CACHE` naming the folder for
|
||||
/// compiled shaders, #720). They carry addresses, counts and a folder, never credentials, so the
|
||||
/// isolated guest environment lets them through by name; every other variable is still stripped.
|
||||
const DIAGNOSTIC_ENV_ALLOWLIST: &[&str] = &[
|
||||
"BX_CONSOLE_SHADERS",
|
||||
"BX_SHADER_CACHE",
|
||||
"BX_VEH_AV_CONTEXT",
|
||||
"BX_VEH_AV_ALL",
|
||||
"BX_VEH_WATCH",
|
||||
@@ -69,12 +72,13 @@ fn usage_text() -> &'static str {
|
||||
bx-cli doctor Inspect Apple Silicon host, Rosetta 2, CrossOver & mingw-w64\n\
|
||||
bx-cli probe <pe32+_path> Classify PE32+ imports by BetterXen track (A-E)\n\
|
||||
bx-cli shader <dxbc_blob_path> Classify a DXBC shader container (DXIL vs ACCC/FSPX)\n\
|
||||
bx-cli shader translate <vs> <ps> --out <dir> Translate a console VS/PS pair to HLSL (gfx10-translate)\n\
|
||||
bx-cli shader translate <vs> <ps> --out <dir> [--root <layout>] Translate a console VS/PS pair to HLSL (gfx10-translate); <layout> is the root signature's parameters, e.g. T,S:0:0,C2:1:0,B:2:0[,mem]\n\
|
||||
bx-cli shader coverage <dir> Rank what blocks translation across a folder of *_VS.* / *_PS.* shaders\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] Remember where the target build, the GDK and the target build's Ghidra results are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli setup [--find] [--target-exe <path>] [--gdk-root <dir>] [--ghidra-results <dir>] [--dxc-dir <dir>] Remember where the target build, the GDK, the target build's Ghidra results and open-source DXC are on this machine (saved outside the repository); --find searches the home folder for them\n\
|
||||
bx-cli preflight Check everything work needs: host, CrossOver, the target build, the GDK, the Ghidra results, disk space. Fails if anything is missing\n\
|
||||
bx-cli trace <log.jsonl> Summarize bx_runtime_veh JSONL diagnostics\n\
|
||||
bx-cli report <log.jsonl>... Run report per log (one log = one run), then a summary with blocker signatures\n\
|
||||
bx-cli ghidra <module> <offset>... | <module+offset>... Name the function in the configured Ghidra results that holds each module offset (as `bx-cli report` prints callers), with its decompiled file\n\
|
||||
bx-cli run --exe <path> [--shims <dir>] [--bottle <name> | --prefix <dir>] [--profile lockhart|anaconda] [--log <path>] [--inherit-env] [--timeout <secs>] [--backend d3dmetal|dxmt|dxvk|wined3d (needs --bottle)] [--gdk-libraries | --no-gdk-libraries]\n\
|
||||
(shims default to build-shims/bin; a timeout or signal stops the whole bottle or prefix; the GDK's XG and BCPack libraries are staged for the configured target build)\n"
|
||||
}
|
||||
@@ -242,6 +246,7 @@ fn local_setting(env_name: &str, key: &str, config: &BTreeMap<String, String>) -
|
||||
const TARGET_EXE_KEY: &str = "target_exe";
|
||||
const GDK_ROOT_KEY: &str = "gdk_root";
|
||||
const GHIDRA_RESULTS_KEY: &str = "ghidra_results";
|
||||
const DXC_DIR_KEY: &str = "dxc_dir";
|
||||
|
||||
/// The static-analysis results of the target build, recognised by structure: a folder with the
|
||||
/// run's `RUN_REPORT.md`, a `decompiled/` folder, and `exports/<program>/` folders each holding a
|
||||
@@ -577,6 +582,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
"--target-exe" => (TARGET_EXE_KEY, check_target_exe),
|
||||
"--gdk-root" => (GDK_ROOT_KEY, check_gdk_root),
|
||||
"--ghidra-results" => (GHIDRA_RESULTS_KEY, check_ghidra_results),
|
||||
"--dxc-dir" => (DXC_DIR_KEY, check_dxc_dir),
|
||||
other => {
|
||||
eprintln!("error: unknown argument: {other}");
|
||||
return ExitCode::FAILURE;
|
||||
@@ -621,6 +627,7 @@ fn cmd_setup(args: &[String]) -> ExitCode {
|
||||
" Ghidra results: {}",
|
||||
state(GHIDRA_RESULTS_KEY, check_ghidra_results)
|
||||
);
|
||||
println!(" DXC : {}", state(DXC_DIR_KEY, check_dxc_dir));
|
||||
println!("They are kept outside the repository. Run `bx-cli preflight` to check everything.");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -666,6 +673,22 @@ fn check_ghidra_for_target(results: Option<&str>, target: Option<&str>) -> Resul
|
||||
}
|
||||
}
|
||||
|
||||
/// Open-source DXC: the setting must be a folder that contains a PC `dxcompiler.dll`
|
||||
/// exporting `DxcCreateInstance`.
|
||||
fn check_dxc_dir(value: Option<&str>) -> Result<String, String> {
|
||||
let dir = value.filter(|v| !v.is_empty()).ok_or(
|
||||
"not set (optional; GDK dxcompiler.dll used as fallback, or run `bx-cli setup --dxc-dir <folder with dxcompiler.dll>`)",
|
||||
)?;
|
||||
let path = Path::new(dir);
|
||||
if !path.is_dir() {
|
||||
return Err("the saved path is not a folder".to_owned());
|
||||
}
|
||||
match gdk_libs::find_dxc(path) {
|
||||
Some(_) => Ok("present (dxcompiler.dll found)".to_owned()),
|
||||
None => Err("no PC dxcompiler.dll exporting DxcCreateInstance under it".to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The GDK: the setting must be a folder that contains the GDK's `d3d12_xs.h`.
|
||||
fn check_gdk_root(value: Option<&str>) -> Result<String, String> {
|
||||
let root = value
|
||||
@@ -1031,6 +1054,155 @@ fn cmd_trace(path: &str) -> ExitCode {
|
||||
|
||||
/// `bx-cli report <log>...`: each log is one run. Prints every run's report, then the summary
|
||||
/// whose signatures blocker issues are titled with (docs/process/working-method.md).
|
||||
/// One function of a Ghidra exports `functions.csv`: entry and end address (inclusive) and name.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct GhidraFunction {
|
||||
entry: u64,
|
||||
end: u64,
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// The exports folder of `module` in a Ghidra results folder (matched by its manifest's program
|
||||
/// name, ignoring case), or `None` when the results do not cover it.
|
||||
fn ghidra_program_dir(root: &Path, module: &str) -> Option<PathBuf> {
|
||||
fs::read_dir(root.join("exports"))
|
||||
.ok()?
|
||||
.flatten()
|
||||
.map(|e| e.path())
|
||||
.find(|dir| {
|
||||
fs::read_to_string(dir.join("manifest.json"))
|
||||
.ok()
|
||||
.and_then(|text| manifest_program(&text))
|
||||
.is_some_and(|program| program.eq_ignore_ascii_case(module))
|
||||
})
|
||||
}
|
||||
|
||||
/// The image base: the start of the `Headers` row of the program's `sections.csv`.
|
||||
fn ghidra_image_base(sections_csv: &str) -> Option<u64> {
|
||||
sections_csv.lines().find_map(|line| {
|
||||
let mut fields = line.split(',');
|
||||
(fields.next()? == "Headers").then(|| u64::from_str_radix(fields.next()?, 16).ok())?
|
||||
})
|
||||
}
|
||||
|
||||
/// The program's functions from `functions.csv` (`entry,end,size,name,...`, addresses in hex).
|
||||
fn ghidra_functions(functions_csv: &str) -> Vec<GhidraFunction> {
|
||||
functions_csv
|
||||
.lines()
|
||||
.skip(1)
|
||||
.filter_map(|line| {
|
||||
let mut fields = line.split(',');
|
||||
let entry = u64::from_str_radix(fields.next()?, 16).ok()?;
|
||||
let end = u64::from_str_radix(fields.next()?, 16).ok()?;
|
||||
let _size = fields.next()?;
|
||||
Some(GhidraFunction {
|
||||
entry,
|
||||
end,
|
||||
name: fields.next()?.to_owned(),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The function holding `address`: the one whose [entry, end] contains it, or `None`.
|
||||
fn ghidra_function_at(functions: &[GhidraFunction], address: u64) -> Option<&GhidraFunction> {
|
||||
functions
|
||||
.iter()
|
||||
.filter(|f| f.entry <= address && address <= f.end)
|
||||
.min_by_key(|f| f.end - f.entry)
|
||||
}
|
||||
|
||||
/// `module offset` or `module+offset` arguments, offsets in hex with or without `0x`.
|
||||
fn ghidra_queries(args: &[String]) -> Result<Vec<(String, u64)>, String> {
|
||||
let parse = |text: &str| {
|
||||
u64::from_str_radix(text.trim_start_matches("0x"), 16)
|
||||
.map_err(|_| format!("`{text}` is not a hex offset"))
|
||||
};
|
||||
let mut queries = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < args.len() {
|
||||
if let Some((module, offset)) = args[i].rsplit_once('+') {
|
||||
queries.push((module.to_owned(), parse(offset)?));
|
||||
i += 1;
|
||||
} else if i + 1 < args.len() {
|
||||
queries.push((args[i].clone(), parse(&args[i + 1])?));
|
||||
i += 2;
|
||||
} else {
|
||||
return Err(format!("`{}` needs an offset", args[i]));
|
||||
}
|
||||
}
|
||||
Ok(queries)
|
||||
}
|
||||
|
||||
/// One answer line for `module+offset` in the results at `root`.
|
||||
fn ghidra_lookup(root: &Path, module: &str, offset: u64) -> String {
|
||||
let Some(dir) = ghidra_program_dir(root, module) else {
|
||||
return format!(
|
||||
"{module}+{offset:x}: not in the Ghidra results (a BetterXen, Wine or system module, or not analysed)"
|
||||
);
|
||||
};
|
||||
let program = dir
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
let Some(base) = fs::read_to_string(dir.join("sections.csv"))
|
||||
.ok()
|
||||
.as_deref()
|
||||
.and_then(ghidra_image_base)
|
||||
else {
|
||||
return format!("{module}+{offset:x}: {program} has no Headers row in sections.csv");
|
||||
};
|
||||
let functions =
|
||||
ghidra_functions(&fs::read_to_string(dir.join("functions.csv")).unwrap_or_default());
|
||||
let address = base + offset;
|
||||
match ghidra_function_at(&functions, address) {
|
||||
Some(f) => {
|
||||
let file = root
|
||||
.join("decompiled")
|
||||
.join(&program)
|
||||
.join(format!("{:x}.c", f.entry));
|
||||
let shown = if file.is_file() {
|
||||
file.display().to_string()
|
||||
} else {
|
||||
"(no decompiled file)".to_owned()
|
||||
};
|
||||
format!(
|
||||
"{module}+{offset:x} = {address:#x} -> {} at {:#x} (+{:#x}); {shown}",
|
||||
f.name,
|
||||
f.entry,
|
||||
address - f.entry
|
||||
)
|
||||
}
|
||||
None => format!("{module}+{offset:x} = {address:#x}: inside no function Ghidra found"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `bx-cli ghidra`: look callers up statically before running the target build again.
|
||||
fn cmd_ghidra(args: &[String]) -> ExitCode {
|
||||
let queries = match ghidra_queries(args) {
|
||||
Ok(q) => q,
|
||||
Err(e) => {
|
||||
eprintln!("error: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let config = local_config_path()
|
||||
.map(|path| read_local_config(&path))
|
||||
.unwrap_or_default();
|
||||
let root = local_setting("BX_GHIDRA_RESULTS", GHIDRA_RESULTS_KEY, &config);
|
||||
let root = match check_ghidra_results(root.as_deref()) {
|
||||
Ok(_) => PathBuf::from(root.unwrap_or_default()),
|
||||
Err(e) => {
|
||||
eprintln!("Ghidra results: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
for (module, offset) in queries {
|
||||
println!("{}", ghidra_lookup(&root, &module, offset));
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
fn cmd_report(paths: &[String]) -> ExitCode {
|
||||
let mut runs = Vec::new();
|
||||
for path in paths {
|
||||
@@ -1620,8 +1792,9 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let mut abs_shims = fs::canonicalize(&shims_dir).unwrap_or(shims_dir);
|
||||
let abs_exe = fs::canonicalize(&exe).unwrap_or(exe);
|
||||
|
||||
// The GDK's texture libraries (gdk_libs.rs, ADR 0010): staged for the configured target
|
||||
// build, or with --gdk-libraries, from the GDK configured on this machine.
|
||||
// Runtime texture and shader-compiler libraries (gdk_libs.rs, ADR 0010): staged for the
|
||||
// configured target build, or with --gdk-libraries. Open-source DXC (`--dxc-dir` /
|
||||
// `BX_DXC_DIR`) takes precedence for `dxcompiler.dll`, with the GDK as fallback.
|
||||
let config = local_config_path()
|
||||
.map(|p| read_local_config(&p))
|
||||
.unwrap_or_default();
|
||||
@@ -1631,37 +1804,45 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
let mut staged_bcpack: Option<PathBuf> = None;
|
||||
let mut gdk_shims_dir: Option<PathBuf> = None;
|
||||
if gdk_libraries.unwrap_or(is_target) {
|
||||
match local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config) {
|
||||
Some(root) => {
|
||||
let libs = gdk_libs::find(Path::new(&root));
|
||||
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
|
||||
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
|
||||
Ok(bcpack) => {
|
||||
diag(format_args!(
|
||||
"bx-cli: GDK texture libraries: XG {}, BCPack {}",
|
||||
if libs.xg.is_some() {
|
||||
"staged"
|
||||
} else {
|
||||
"not found"
|
||||
},
|
||||
if bcpack.is_some() {
|
||||
"staged"
|
||||
} else {
|
||||
"not found"
|
||||
}
|
||||
));
|
||||
staged_bcpack = bcpack;
|
||||
abs_shims = out.clone();
|
||||
gdk_shims_dir = Some(out);
|
||||
}
|
||||
Err(e) => diag(format_args!(
|
||||
"warning: GDK texture libraries not staged: {e}"
|
||||
)),
|
||||
let dxc_dir = local_setting("BX_DXC_DIR", DXC_DIR_KEY, &config);
|
||||
let gdk_root = local_setting("BX_GDK_ROOT", GDK_ROOT_KEY, &config);
|
||||
if dxc_dir.is_none() && gdk_root.is_none() {
|
||||
diag(
|
||||
"warning: GDK texture libraries and DXC not staged: neither GDK nor DXC configured (bx-cli setup --find / --dxc-dir)",
|
||||
);
|
||||
} else {
|
||||
let libs = gdk_libs::resolve(
|
||||
dxc_dir.as_deref().map(Path::new),
|
||||
gdk_root.as_deref().map(Path::new),
|
||||
);
|
||||
let dxc_from_oss = dxc_dir
|
||||
.as_deref()
|
||||
.is_some_and(|dir| libs.dxc.as_ref().is_some_and(|p| p.starts_with(dir)));
|
||||
let out = env::temp_dir().join(format!("bx-gdk-shims-{}", std::process::id()));
|
||||
match gdk_libs::merge_shims(&abs_shims, &libs, &out) {
|
||||
Ok(bcpack) => {
|
||||
let state = |found: bool| if found { "staged" } else { "not found" };
|
||||
let dxc_state = if libs.dxc.is_none() {
|
||||
"not found"
|
||||
} else if dxc_from_oss {
|
||||
"staged (open-source)"
|
||||
} else {
|
||||
"staged (GDK fallback)"
|
||||
};
|
||||
diag(format_args!(
|
||||
"bx-cli: runtime libraries: XG {}, BCPack {}, DXC {}",
|
||||
state(libs.xg.is_some()),
|
||||
state(bcpack.is_some()),
|
||||
dxc_state
|
||||
));
|
||||
staged_bcpack = bcpack;
|
||||
abs_shims = out.clone();
|
||||
gdk_shims_dir = Some(out);
|
||||
}
|
||||
Err(e) => diag(format_args!(
|
||||
"warning: GDK texture libraries not staged: {e}"
|
||||
)),
|
||||
}
|
||||
None => diag(
|
||||
"warning: GDK texture libraries not staged: no GDK configured (bx-cli setup --find)",
|
||||
),
|
||||
}
|
||||
}
|
||||
struct RemoveOnDrop(Option<PathBuf>);
|
||||
@@ -1996,11 +2177,54 @@ fn cmd_run(args: &[String]) -> ExitCode {
|
||||
/// or raw code blobs) with the gfx10-translate crate. Writes `<vs key>_<ps key>.vs.hlsl`,
|
||||
/// `.ps.hlsl` and `.il` (the host pipeline's input layout and resources), keyed by FNV-1a of each
|
||||
/// blob as the shim's shader cache expects. Compile the HLSL with the public DXC (vs_6_0/ps_6_0).
|
||||
/// A root signature layout from its short form: comma-separated parameters in order, `T` (a
|
||||
/// descriptor table), `C<n>:<register>:<space>` (n constants), `B:`, `S:` or `U:` followed by
|
||||
/// `<register>:<space>` (a root CBV, SRV or UAV), and a final `mem` when the signature sets
|
||||
/// D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI.
|
||||
fn parse_root_layout(text: &str) -> Option<gfx10_translate::RootLayout> {
|
||||
use gfx10_translate::{RootKind, RootLayout, RootParameter};
|
||||
let mut layout = RootLayout::default();
|
||||
for item in text.split(',') {
|
||||
if item == "mem" {
|
||||
layout.memory_based = true;
|
||||
continue;
|
||||
}
|
||||
let mut fields = item.split(':');
|
||||
let head = fields.next()?;
|
||||
let (kind, values) = match head.split_at_checked(1)? {
|
||||
("T", "") => (RootKind::Table, 0),
|
||||
("C", n) => (RootKind::Constants, n.parse().ok()?),
|
||||
("B", "") => (RootKind::Cbv, 0),
|
||||
("S", "") => (RootKind::Srv, 0),
|
||||
("U", "") => (RootKind::Uav, 0),
|
||||
_ => return None,
|
||||
};
|
||||
let mut number = || fields.next().map_or(Some(0), |v| v.parse().ok());
|
||||
let (register, space) = (number()?, number()?);
|
||||
layout.parameters.push(RootParameter {
|
||||
kind,
|
||||
values,
|
||||
register,
|
||||
space,
|
||||
});
|
||||
}
|
||||
Some(layout)
|
||||
}
|
||||
|
||||
fn cmd_shader_translate(args: &[String]) -> ExitCode {
|
||||
let (vs_path, ps_path, out) = match args {
|
||||
[vs, ps, flag, out] if flag == "--out" => (vs, ps, out),
|
||||
const USAGE: &str = "usage: bx-cli shader translate <vs container> <ps container> --out <dir> [--root <layout>]\n \
|
||||
<layout>: the root parameters in order, e.g. T,S:0:0,C2:1:0,B:2:0[,mem]";
|
||||
let (vs_path, ps_path, out, root) = match args {
|
||||
[vs, ps, flag, out] if flag == "--out" => (vs, ps, out, None),
|
||||
[vs, ps, flag, out, root_flag, root] if flag == "--out" && root_flag == "--root" => {
|
||||
let Some(layout) = parse_root_layout(root) else {
|
||||
eprintln!("error: cannot read the root layout '{root}'\n{USAGE}");
|
||||
return ExitCode::FAILURE;
|
||||
};
|
||||
(vs, ps, out, Some(layout))
|
||||
}
|
||||
_ => {
|
||||
eprintln!("usage: bx-cli shader translate <vs container> <ps container> --out <dir>");
|
||||
eprintln!("{USAGE}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
@@ -2011,7 +2235,11 @@ fn cmd_shader_translate(args: &[String]) -> ExitCode {
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let t = match gfx10_translate::translate_blobs(&vs, &ps) {
|
||||
let translated = match &root {
|
||||
Some(layout) => gfx10_translate::translate_blobs_rooted(&vs, &ps, layout),
|
||||
None => gfx10_translate::translate_blobs(&vs, &ps),
|
||||
};
|
||||
let t = match translated {
|
||||
Ok(t) => t,
|
||||
Err(e) => {
|
||||
eprintln!("unsupported: {e}");
|
||||
@@ -2123,9 +2351,8 @@ impl<'a> Dispatch<'a> {
|
||||
};
|
||||
match sub.as_str() {
|
||||
"--help" | "-h" | "help" => Dispatch::Help,
|
||||
"doctor" | "setup" | "preflight" | "probe" | "shader" | "trace" | "report" | "run" => {
|
||||
Dispatch::Sub(sub.as_str())
|
||||
}
|
||||
"doctor" | "setup" | "preflight" | "probe" | "shader" | "trace" | "report"
|
||||
| "ghidra" | "run" => Dispatch::Sub(sub.as_str()),
|
||||
_ => Dispatch::Unknown(sub.as_str()),
|
||||
}
|
||||
}
|
||||
@@ -2164,6 +2391,7 @@ fn main() -> ExitCode {
|
||||
"shader" if args.len() >= 2 => cmd_shader(&args[1]),
|
||||
"trace" if args.len() >= 2 => cmd_trace(&args[1]),
|
||||
"report" if args.len() >= 2 => cmd_report(&args[1..]),
|
||||
"ghidra" if args.len() >= 2 => cmd_ghidra(&args[1..]),
|
||||
"run" => cmd_run(&args[1..]),
|
||||
// Only reachable when a subcommand that needs an argument got none.
|
||||
_ => {
|
||||
@@ -2174,6 +2402,113 @@ fn main() -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod ghidra_lookup_tests {
|
||||
use super::*;
|
||||
|
||||
fn results() -> PathBuf {
|
||||
let root = env::temp_dir().join(format!("bx-ghidra-lookup-{}", std::process::id()));
|
||||
let program = root.join("exports").join("sample.dll");
|
||||
fs::create_dir_all(&program).unwrap();
|
||||
fs::create_dir_all(root.join("decompiled").join("sample.dll")).unwrap();
|
||||
fs::write(root.join(GHIDRA_REPORT), "# RUN_REPORT\n").unwrap();
|
||||
fs::write(
|
||||
program.join("manifest.json"),
|
||||
"{\"program\":\"sample.dll\",\"rows\":{}}",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
program.join("sections.csv"),
|
||||
"section,start,end,size\nHeaders,180000000,1800003ff,1024\n.text,180001000,180001fff,4096\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
program.join("functions.csv"),
|
||||
"entry,end,size,name,namespace\n180001000,18000107f,128,FUN_180001000,Global\n180001080,1800010ff,128,Helper,Global\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
root.join("decompiled")
|
||||
.join("sample.dll")
|
||||
.join("180001080.c"),
|
||||
"void Helper(void) {}\n",
|
||||
)
|
||||
.unwrap();
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_the_function_holding_an_offset() {
|
||||
let root = results();
|
||||
let line = ghidra_lookup(&root, "SAMPLE.DLL", 0x10a4);
|
||||
assert!(
|
||||
line.contains("0x1800010a4 -> Helper at 0x180001080 (+0x24)"),
|
||||
"{line}"
|
||||
);
|
||||
assert!(line.contains("180001080.c"), "{line}");
|
||||
let missing = ghidra_lookup(&root, "sample.dll", 0x1000);
|
||||
assert!(
|
||||
missing.contains("FUN_180001000") && missing.contains("(no decompiled file)"),
|
||||
"{missing}"
|
||||
);
|
||||
assert!(ghidra_lookup(&root, "d3d12_xs.dll", 0x10).contains("not in the Ghidra results"));
|
||||
assert!(ghidra_lookup(&root, "sample.dll", 0x3000).contains("inside no function"));
|
||||
fs::remove_dir_all(root).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_both_argument_forms() {
|
||||
let args: Vec<String> = ["a.dll+1f", "b.exe", "0x20"]
|
||||
.iter()
|
||||
.map(|s| s.to_string())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
ghidra_queries(&args).unwrap(),
|
||||
vec![("a.dll".to_owned(), 0x1f), ("b.exe".to_owned(), 0x20)]
|
||||
);
|
||||
assert!(ghidra_queries(&["c.dll".to_owned()]).is_err());
|
||||
assert!(ghidra_queries(&["c.dll+zz".to_owned()]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod root_layout_tests {
|
||||
use super::parse_root_layout;
|
||||
use gfx10_translate::RootKind;
|
||||
|
||||
#[test]
|
||||
fn reads_the_short_form() {
|
||||
let layout = parse_root_layout("T,S:3:2,C2:1,B:2:1,mem").unwrap();
|
||||
assert!(layout.memory_based);
|
||||
let kinds: Vec<RootKind> = layout.parameters.iter().map(|p| p.kind).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[
|
||||
RootKind::Table,
|
||||
RootKind::Srv,
|
||||
RootKind::Constants,
|
||||
RootKind::Cbv
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
(layout.parameters[1].register, layout.parameters[1].space),
|
||||
(3, 2)
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
layout.parameters[2].values,
|
||||
layout.parameters[2].register,
|
||||
layout.parameters[2].space
|
||||
),
|
||||
(2, 1, 0)
|
||||
);
|
||||
assert!(!parse_root_layout("T,S:0:0").unwrap().memory_based);
|
||||
for bad in ["", "X", "C:0:0", "S:x", "T1"] {
|
||||
assert!(parse_root_layout(bad).is_none(), "{bad}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -3003,15 +3338,49 @@ sub setup_bottle_wineprefix {
|
||||
"free space is measurable for an existing folder"
|
||||
);
|
||||
|
||||
// Open-source DXC: unset, not a folder, folder without dxcompiler.dll, folder with valid PE32+ dxcompiler.dll.
|
||||
assert!(check_dxc_dir(None).unwrap_err().contains("not set"));
|
||||
assert!(
|
||||
check_dxc_dir(pe.to_str())
|
||||
.unwrap_err()
|
||||
.contains("not a folder")
|
||||
);
|
||||
let dxc_dir = dir.join("dxc");
|
||||
fs::create_dir_all(&dxc_dir).unwrap();
|
||||
assert!(
|
||||
check_dxc_dir(dxc_dir.to_str())
|
||||
.unwrap_err()
|
||||
.contains("no PC dxcompiler.dll")
|
||||
);
|
||||
let mut fake_dxc = vec![0u8; 0x200];
|
||||
fake_dxc[0..2].copy_from_slice(b"MZ");
|
||||
fake_dxc[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
fake_dxc[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
fake_dxc[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
fake_dxc[0x54..0x56].copy_from_slice(&240u16.to_le_bytes());
|
||||
fake_dxc[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
fake_dxc[0x58 + 108..0x58 + 112].copy_from_slice(&16u32.to_le_bytes());
|
||||
fake_dxc.extend_from_slice(b"DxcCreateInstance\0");
|
||||
fs::write(dxc_dir.join("dxcompiler.dll"), &fake_dxc).unwrap();
|
||||
assert!(check_dxc_dir(dxc_dir.to_str()).unwrap().contains("found"));
|
||||
|
||||
// Local settings: written, read back, unknown keys kept, comments ignored; the
|
||||
// environment variable wins over the saved value.
|
||||
let conf = dir.join("conf/local.conf");
|
||||
let mut values = BTreeMap::new();
|
||||
values.insert(TARGET_EXE_KEY.to_owned(), pe.to_string_lossy().into_owned());
|
||||
values.insert(
|
||||
DXC_DIR_KEY.to_owned(),
|
||||
dxc_dir.to_string_lossy().into_owned(),
|
||||
);
|
||||
values.insert("future_key".to_owned(), "kept".to_owned());
|
||||
write_local_config(&conf, &values).unwrap();
|
||||
let read = read_local_config(&conf);
|
||||
assert_eq!(read, values);
|
||||
assert_eq!(
|
||||
local_setting("BX_TEST_UNSET_VARIABLE_FOR_PREFLIGHT", DXC_DIR_KEY, &read).as_deref(),
|
||||
dxc_dir.to_str()
|
||||
);
|
||||
assert!(
|
||||
fs::read_to_string(&conf)
|
||||
.unwrap()
|
||||
|
||||
@@ -54,6 +54,10 @@ pub struct RunReport {
|
||||
pub frames_at_least: Option<u64>,
|
||||
/// Unimplemented calls reached, by signature, with how often.
|
||||
pub unimplemented: BTreeMap<String, u64>,
|
||||
/// For each unimplemented signature, the distinct caller chains runtime_veh logged for it
|
||||
/// (`stub_caller`: `module+offset < module+offset < module+offset`, the stub first), at most
|
||||
/// [`MAX_CALLERS_SHOWN`] each, in the order first seen.
|
||||
pub callers: BTreeMap<String, Vec<String>>,
|
||||
/// Faults whose innermost frame is in a BetterXen module, by module.
|
||||
pub faults: BTreeMap<String, u64>,
|
||||
/// Exceptions nothing handled.
|
||||
@@ -123,6 +127,18 @@ fn vtable_signature(detail: &str) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Caller chains kept per unimplemented signature.
|
||||
pub const MAX_CALLERS_SHOWN: usize = 4;
|
||||
|
||||
/// The report signature of a stub detail: `Iface[n]::Method` (a vtable slot) or `dll!Symbol`.
|
||||
fn stub_signature(detail: &str) -> String {
|
||||
if detail.contains("]::") {
|
||||
vtable_signature(detail)
|
||||
} else {
|
||||
format!("unimplemented {detail}")
|
||||
}
|
||||
}
|
||||
|
||||
/// The module of the innermost stack frame in an `av_context` detail (`... | stack: A.dll+12 B.dll+34`).
|
||||
fn fault_module(detail: &str) -> Option<&str> {
|
||||
let stack = detail.split("stack: ").nth(1)?;
|
||||
@@ -189,6 +205,14 @@ pub fn report_run(input: &str) -> RunReport {
|
||||
.entry(format!("unimplemented {detail}"))
|
||||
.or_default() += 1
|
||||
}
|
||||
"stub_caller" => {
|
||||
if let Some((stub, chain)) = detail.split_once(" <- ") {
|
||||
let chains = report.callers.entry(stub_signature(stub)).or_default();
|
||||
if chains.len() < MAX_CALLERS_SHOWN && !chains.iter().any(|c| c == chain) {
|
||||
chains.push(chain.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
"av_context" => {
|
||||
if let Some(module) = fault_module(detail).filter(|m| is_betterxen_module(m)) {
|
||||
*report.faults.entry(module.to_owned()).or_default() += 1;
|
||||
@@ -295,6 +319,15 @@ pub fn render_run(name: &str, report: &RunReport) -> String {
|
||||
let _ = writeln!(out, " unimplemented calls:");
|
||||
for (signature, count) in &report.unimplemented {
|
||||
let _ = writeln!(out, " {count:>7}x {signature}");
|
||||
for chain in report.callers.get(signature).into_iter().flatten() {
|
||||
let _ = writeln!(out, " from {chain}");
|
||||
}
|
||||
}
|
||||
if !report.callers.is_empty() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" (look a caller up with `bx-cli ghidra <module> <offset>` before running again)"
|
||||
);
|
||||
}
|
||||
}
|
||||
if !report.faults.is_empty() || report.unhandled_exceptions > 0 {
|
||||
@@ -406,6 +439,58 @@ mod tests {
|
||||
assert!(report.signatures().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stub_callers_are_listed_under_their_signature() {
|
||||
let log = line(
|
||||
1,
|
||||
"com_vtable",
|
||||
"unimpl_vtable",
|
||||
"XboxPipelineState[11]::GetInformationX",
|
||||
) + &line(
|
||||
2,
|
||||
"stub",
|
||||
"stub_caller",
|
||||
"XboxPipelineState[11]::GetInformationX <- d3d12_xs.dll+1f00 < upscaler.dll+5c10 < upscaler.dll+e93e",
|
||||
) + &line(3, "stub", "unimpl_api", "chad.dll!XDspActivate")
|
||||
+ &line(
|
||||
4,
|
||||
"stub",
|
||||
"stub_caller",
|
||||
"chad.dll!XDspActivate <- chad.dll+10 < game.exe+20 < game.exe+30",
|
||||
)
|
||||
+ &line(
|
||||
5,
|
||||
"stub",
|
||||
"stub_caller",
|
||||
"chad.dll!XDspActivate <- chad.dll+10 < game.exe+20 < game.exe+30",
|
||||
);
|
||||
let report = report_run(&log);
|
||||
assert_eq!(
|
||||
report
|
||||
.callers
|
||||
.get("unimplemented XboxPipelineState slot 11 (GetInformationX)"),
|
||||
Some(&vec![
|
||||
"d3d12_xs.dll+1f00 < upscaler.dll+5c10 < upscaler.dll+e93e".to_owned()
|
||||
])
|
||||
);
|
||||
assert_eq!(
|
||||
report
|
||||
.callers
|
||||
.get("unimplemented chad.dll!XDspActivate")
|
||||
.map(Vec::len),
|
||||
Some(1),
|
||||
"a repeated chain is kept once"
|
||||
);
|
||||
let text = render_run("run", &report);
|
||||
assert!(text.contains(" from chad.dll+10 < game.exe+20 < game.exe+30"));
|
||||
assert!(text.contains("bx-cli ghidra <module> <offset>"));
|
||||
assert_eq!(
|
||||
report.signatures().len(),
|
||||
2,
|
||||
"callers add no signatures of their own"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unimplemented_calls_become_stable_signatures() {
|
||||
let log = line(1, "com_vtable", "unimpl_vtable", "IXUser[3]::slot_3")
|
||||
|
||||
@@ -128,6 +128,8 @@ tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] idxe
|
||||
image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
|
||||
image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
|
||||
image_sample v3, [v4, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D
|
||||
image_sample_lz v[0:2], [v4, v9, v2], s[8:15], s[16:19] dmask:0x7 dim:SQ_RSRC_IMG_3D
|
||||
exp pos0, v0, v1, v2, v3 done
|
||||
exp mrt0, v0, v1, v2, v3 done vm
|
||||
exp mrt0, v0, off, off, off
|
||||
|
||||
@@ -8,5 +8,8 @@ rust-version.workspace = true
|
||||
[lib]
|
||||
crate-type = ["rlib", "cdylib"]
|
||||
|
||||
[dependencies]
|
||||
gfx10-translate = { path = "../gfx10-translate" }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -420,3 +420,260 @@ fn free_buffer(ptr: *mut u8, len: usize) {
|
||||
pub unsafe extern "C" fn bx_shader_free_buffer(ptr: *mut u8, len: usize) {
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| free_buffer(ptr, len)));
|
||||
}
|
||||
|
||||
/// Mirror of `bx_shader_pair_translation_t` (abi/include/bx_shader_bridge.h).
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BxShaderPairTranslation {
|
||||
pub vs_key: u64,
|
||||
pub ps_key: u64,
|
||||
pub vs_hlsl: *mut u8,
|
||||
pub vs_hlsl_len: usize,
|
||||
pub ps_hlsl: *mut u8,
|
||||
pub ps_hlsl_len: usize,
|
||||
pub layout: *mut u8,
|
||||
pub layout_len: usize,
|
||||
pub reason: *mut u8,
|
||||
pub reason_len: usize,
|
||||
}
|
||||
|
||||
impl BxShaderPairTranslation {
|
||||
const EMPTY: Self = Self {
|
||||
vs_key: 0,
|
||||
ps_key: 0,
|
||||
vs_hlsl: ptr::null_mut(),
|
||||
vs_hlsl_len: 0,
|
||||
ps_hlsl: ptr::null_mut(),
|
||||
ps_hlsl_len: 0,
|
||||
layout: ptr::null_mut(),
|
||||
layout_len: 0,
|
||||
reason: ptr::null_mut(),
|
||||
reason_len: 0,
|
||||
};
|
||||
|
||||
fn free_buffers(&mut self) {
|
||||
for (buffer, len) in [
|
||||
(&mut self.vs_hlsl, &mut self.vs_hlsl_len),
|
||||
(&mut self.ps_hlsl, &mut self.ps_hlsl_len),
|
||||
(&mut self.layout, &mut self.layout_len),
|
||||
(&mut self.reason, &mut self.reason_len),
|
||||
] {
|
||||
free_buffer(*buffer, *len);
|
||||
*buffer = ptr::null_mut();
|
||||
*len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 64-bit FNV-1a, the cache key of a shader as the title passes it.
|
||||
fn fnv1a64(data: &[u8]) -> u64 {
|
||||
data.iter().fold(0xcbf2_9ce4_8422_2325, |h, b| {
|
||||
(h ^ u64::from(*b)).wrapping_mul(0x0000_0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
/// Copies `text` into a caller-owned buffer; an empty text stays (NULL, 0).
|
||||
fn publish(text: &str, buffer: &mut *mut u8, len: &mut usize) -> Result<(), ()> {
|
||||
if text.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
*buffer = alloc_copy(text.as_bytes())?;
|
||||
*len = text.len();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Mirror of `bx_shader_root_parameter_t`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct BxShaderRootParameter {
|
||||
pub r#type: u32,
|
||||
pub num_32bit_values: u32,
|
||||
pub shader_register: u32,
|
||||
pub register_space: u32,
|
||||
}
|
||||
|
||||
/// Mirror of `bx_shader_root_layout_t`.
|
||||
#[repr(C)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct BxShaderRootLayout {
|
||||
pub parameters: *const BxShaderRootParameter,
|
||||
pub parameter_count: u32,
|
||||
pub flags: u32,
|
||||
}
|
||||
|
||||
/// D3D12XBOX_ROOT_SIGNATURE_FLAG_FORCE_MEMORY_BASED_ABI.
|
||||
const ROOT_FLAG_MEMORY_BASED: u32 = 0x0100_0000;
|
||||
/// More parameters than a root signature can have (its cost limit is 64 values).
|
||||
const MAX_ROOT_PARAMETERS: u32 = 64;
|
||||
|
||||
/// The translator's layout for a C layout; None when it is inconsistent.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `layout.parameters` must be readable for `parameter_count` entries when it is non-null.
|
||||
unsafe fn root_layout(layout: &BxShaderRootLayout) -> Option<gfx10_translate::RootLayout> {
|
||||
use gfx10_translate::{RootKind, RootParameter};
|
||||
if layout.parameter_count > MAX_ROOT_PARAMETERS
|
||||
|| (layout.parameters.is_null() && layout.parameter_count != 0)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let parameters: &[BxShaderRootParameter] = if layout.parameter_count == 0 {
|
||||
&[]
|
||||
} else {
|
||||
// SAFETY: non-null, and the caller guarantees `parameter_count` readable entries.
|
||||
unsafe { std::slice::from_raw_parts(layout.parameters, layout.parameter_count as usize) }
|
||||
};
|
||||
let mut out = gfx10_translate::RootLayout {
|
||||
parameters: Vec::with_capacity(parameters.len()),
|
||||
memory_based: layout.flags & ROOT_FLAG_MEMORY_BASED != 0,
|
||||
};
|
||||
for p in parameters {
|
||||
let kind = match p.r#type {
|
||||
0 => RootKind::Table,
|
||||
1 => RootKind::Constants,
|
||||
2 => RootKind::Cbv,
|
||||
3 => RootKind::Srv,
|
||||
4 => RootKind::Uav,
|
||||
_ => return None,
|
||||
};
|
||||
out.parameters.push(RootParameter {
|
||||
kind,
|
||||
values: p.num_32bit_values,
|
||||
register: p.shader_register,
|
||||
space: p.register_space,
|
||||
});
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn translate_pair_status(
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
root: Option<&gfx10_translate::RootLayout>,
|
||||
out: &mut BxShaderPairTranslation,
|
||||
) -> i32 {
|
||||
if vs.is_empty() || ps.is_empty() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
out.vs_key = fnv1a64(vs);
|
||||
out.ps_key = fnv1a64(ps);
|
||||
// An input that holds no console code is invalid; code the translator does not model is
|
||||
// unsupported and says why.
|
||||
if gfx10_translate::container::code_words(vs).is_err()
|
||||
|| gfx10_translate::container::code_words(ps).is_err()
|
||||
{
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
let translated = match root {
|
||||
Some(layout) => gfx10_translate::translate_blobs_rooted(vs, ps, layout),
|
||||
None => gfx10_translate::translate_blobs(vs, ps),
|
||||
};
|
||||
match translated {
|
||||
Ok(t) => {
|
||||
let published = publish(&t.vs_hlsl, &mut out.vs_hlsl, &mut out.vs_hlsl_len)
|
||||
.and_then(|()| publish(&t.ps_hlsl, &mut out.ps_hlsl, &mut out.ps_hlsl_len))
|
||||
.and_then(|()| publish(&t.layout, &mut out.layout, &mut out.layout_len));
|
||||
match published {
|
||||
Ok(()) => BX_SHADER_OK,
|
||||
Err(()) => BX_SHADER_ERR_OOM,
|
||||
}
|
||||
}
|
||||
Err(e) => match publish(&e.0, &mut out.reason, &mut out.reason_len) {
|
||||
Ok(()) => BX_SHADER_ERR_UNSUPPORTED,
|
||||
Err(()) => BX_SHADER_ERR_OOM,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate a console vertex/pixel shader pair to HLSL (see `bx_shader_translate_pair` in
|
||||
/// abi/include/bx_shader_bridge.h for the contract).
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `vs_bytes` and `ps_bytes` must be readable for their lengths when non-null. `out` must be
|
||||
/// null or point to a writable `bx_shader_pair_translation_t`; its previous contents are
|
||||
/// overwritten without being freed.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_translate_pair(
|
||||
vs_bytes: *const u8,
|
||||
vs_len: usize,
|
||||
ps_bytes: *const u8,
|
||||
ps_len: usize,
|
||||
out: *mut BxShaderPairTranslation,
|
||||
) -> i32 {
|
||||
// SAFETY: the caller's guarantees are those of the rooted form with no layout.
|
||||
unsafe { bx_shader_translate_pair_rooted(vs_bytes, vs_len, ps_bytes, ps_len, ptr::null(), out) }
|
||||
}
|
||||
|
||||
/// Translate a console vertex/pixel shader pair given the layout of the pipeline's root
|
||||
/// signature (see `bx_shader_translate_pair_rooted` in abi/include/bx_shader_bridge.h). A null
|
||||
/// `layout` gives `bx_shader_translate_pair`.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As [`bx_shader_translate_pair`]. `layout` must be null or point to a readable
|
||||
/// `bx_shader_root_layout_t` whose `parameters` is readable for `parameter_count` entries.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_translate_pair_rooted(
|
||||
vs_bytes: *const u8,
|
||||
vs_len: usize,
|
||||
ps_bytes: *const u8,
|
||||
ps_len: usize,
|
||||
layout: *const BxShaderRootLayout,
|
||||
out: *mut BxShaderPairTranslation,
|
||||
) -> i32 {
|
||||
if out.is_null() {
|
||||
return BX_SHADER_ERR_INVALID_BLOB;
|
||||
}
|
||||
// SAFETY: `out` is non-null and the caller guarantees it is writable.
|
||||
unsafe { out.write(BxShaderPairTranslation::EMPTY) };
|
||||
let mut result = BxShaderPairTranslation::EMPTY;
|
||||
let status = match catch_unwind(AssertUnwindSafe(|| {
|
||||
match (input_bytes(vs_bytes, vs_len), input_bytes(ps_bytes, ps_len)) {
|
||||
(Some(vs), Some(ps)) => {
|
||||
if layout.is_null() {
|
||||
translate_pair_status(vs, ps, None, &mut result)
|
||||
} else {
|
||||
// SAFETY: non-null, and the caller guarantees the layout is readable.
|
||||
match unsafe { root_layout(&*layout) } {
|
||||
Some(root) => translate_pair_status(vs, ps, Some(&root), &mut result),
|
||||
None => BX_SHADER_ERR_INVALID_BLOB,
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => BX_SHADER_ERR_INVALID_BLOB,
|
||||
}
|
||||
})) {
|
||||
Ok(status) => status,
|
||||
Err(_) => BX_SHADER_ERR_TRANSLATE,
|
||||
};
|
||||
// Buffers that do not belong to the returned status are not handed out.
|
||||
if status != BX_SHADER_OK && status != BX_SHADER_ERR_UNSUPPORTED {
|
||||
result.free_buffers();
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe { out.write(result) };
|
||||
status
|
||||
}
|
||||
|
||||
/// Free every buffer of a translation and clear it. A null pointer is a no-op.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `translation` must be null or point to a structure filled by [`bx_shader_translate_pair`]
|
||||
/// whose buffers have not been freed.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn bx_shader_free_pair_translation(
|
||||
translation: *mut BxShaderPairTranslation,
|
||||
) {
|
||||
if translation.is_null() {
|
||||
return;
|
||||
}
|
||||
let _ = catch_unwind(AssertUnwindSafe(|| {
|
||||
// SAFETY: non-null, and the caller guarantees it is a filled structure.
|
||||
let t = unsafe { &mut *translation };
|
||||
t.free_buffers();
|
||||
*t = BxShaderPairTranslation::EMPTY;
|
||||
}));
|
||||
}
|
||||
@@ -7,6 +7,19 @@
|
||||
//! verification. Section 6 is a byte range only; this module does not
|
||||
//! disassemble it.
|
||||
//!
|
||||
//! Version-1 entries are 12 or 16 bytes. The 12-byte form stays because this
|
||||
//! repository's own synthetic fixtures use it: the tests in this crate and
|
||||
//! `tests/conformance/test_shader_gate`. The 16-byte form `{id, offset, size, 0}`
|
||||
//! is used only when every entry's fourth word is 0 and the first section's
|
||||
//! offset equals `16 + count * 16`, so the first section begins where the
|
||||
//! header and the table end. Any other table keeps the 12-byte parse. For
|
||||
//! 16-byte tables, section 1 is treated as opaque (its bounds are validated and
|
||||
//! recorded in `sections`, while `stage_config` stays `None` and the stage
|
||||
//! remains unknown) rather than requiring the 12-byte synthetic stage layout.
|
||||
//! An offset inside the header plus the table of the stride in use is a layout
|
||||
//! mismatch, including a 16-byte table whose first section starts inside
|
||||
//! `16 + count * 16`.
|
||||
//!
|
||||
//! A version-1 table holds at most [`FSPX_MAX_SECTIONS`] descriptors. A larger
|
||||
//! count is rejected before any descriptor is compared with another, so
|
||||
//! inspection stays allocation-free and the pairwise check stays bounded.
|
||||
@@ -110,7 +123,14 @@ pub(crate) enum FspxError {
|
||||
}
|
||||
|
||||
const HEADER_LEN: usize = 16;
|
||||
/// 12-byte `{id, offset, size}`.
|
||||
///
|
||||
/// Kept because this repository's own synthetic fixtures use it: the tests
|
||||
/// in this crate and `tests/conformance/test_shader_gate`.
|
||||
const DESCRIPTOR_LEN: usize = 12;
|
||||
/// 16-byte `{id, offset, size, 0}`. Selected when every fourth word is 0 and
|
||||
/// the first section begins at `16 + count * 16`. Otherwise [`DESCRIPTOR_LEN`].
|
||||
const WIDE_DESCRIPTOR_LEN: usize = 16;
|
||||
const STAGE_CONFIG_LEN: usize = 12;
|
||||
|
||||
fn stage_from_abi(raw: u32) -> Option<ShaderStage> {
|
||||
@@ -160,13 +180,13 @@ fn stage_from_body(body: &[u8]) -> Result<(ShaderStage, u8, u8), FspxError> {
|
||||
Ok((stage, shader_model_major, shader_model_minor))
|
||||
}
|
||||
|
||||
fn descriptor_at(payload: &[u8], index: usize) -> Result<(u32, u32, u32), FspxError> {
|
||||
fn descriptor_at(
|
||||
payload: &[u8],
|
||||
index: usize,
|
||||
stride: usize,
|
||||
) -> Result<(u32, u32, u32), FspxError> {
|
||||
let at = HEADER_LEN
|
||||
.checked_add(
|
||||
index
|
||||
.checked_mul(DESCRIPTOR_LEN)
|
||||
.ok_or(FspxError::Truncated)?,
|
||||
)
|
||||
.checked_add(index.checked_mul(stride).ok_or(FspxError::Truncated)?)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
let id = read_u32_le(payload, at).ok_or(FspxError::Truncated)?;
|
||||
let offset = read_u32_le(payload, at + 4).ok_or(FspxError::Truncated)?;
|
||||
@@ -174,10 +194,49 @@ fn descriptor_at(payload: &[u8], index: usize) -> Result<(u32, u32, u32), FspxEr
|
||||
Ok((id, offset, size))
|
||||
}
|
||||
|
||||
/// 16-byte when the table itself says so; otherwise the 12-byte fixture stride.
|
||||
///
|
||||
/// Every entry's fourth `u32` must be 0, and the first section's offset must
|
||||
/// equal `16 + count * 16`. A table that fails either check keeps today's
|
||||
/// 12-byte parse, which still rejects an offset inside its own header and
|
||||
/// table. A 16-byte stride whose first section does start on that boundary
|
||||
/// still rejects a later entry that points inside it.
|
||||
fn descriptor_stride(payload: &[u8], count: usize) -> usize {
|
||||
let Some(wide_end) = count
|
||||
.checked_mul(WIDE_DESCRIPTOR_LEN)
|
||||
.and_then(|bytes| HEADER_LEN.checked_add(bytes))
|
||||
else {
|
||||
return DESCRIPTOR_LEN;
|
||||
};
|
||||
if count == 0 || wide_end > payload.len() {
|
||||
return DESCRIPTOR_LEN;
|
||||
}
|
||||
let Ok(wide_end_u32) = u32::try_from(wide_end) else {
|
||||
return DESCRIPTOR_LEN;
|
||||
};
|
||||
for index in 0..count {
|
||||
let Some(pad_at) = index
|
||||
.checked_mul(WIDE_DESCRIPTOR_LEN)
|
||||
.and_then(|bytes| HEADER_LEN.checked_add(bytes))
|
||||
.and_then(|start| start.checked_add(12))
|
||||
else {
|
||||
return DESCRIPTOR_LEN;
|
||||
};
|
||||
if read_u32_le(payload, pad_at) != Some(0) {
|
||||
return DESCRIPTOR_LEN;
|
||||
}
|
||||
}
|
||||
match read_u32_le(payload, HEADER_LEN + 4) {
|
||||
Some(offset) if offset == wide_end_u32 => WIDE_DESCRIPTOR_LEN,
|
||||
_ => DESCRIPTOR_LEN,
|
||||
}
|
||||
}
|
||||
|
||||
struct FspxHeader {
|
||||
version: u32,
|
||||
flags: u32,
|
||||
count: usize,
|
||||
stride: usize,
|
||||
table_end: usize,
|
||||
}
|
||||
|
||||
@@ -200,6 +259,7 @@ fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
version,
|
||||
flags,
|
||||
count: 0,
|
||||
stride: DESCRIPTOR_LEN,
|
||||
table_end: HEADER_LEN,
|
||||
}));
|
||||
}
|
||||
@@ -210,9 +270,8 @@ fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
if count > FSPX_MAX_SECTIONS {
|
||||
return Err(FspxError::TooManySections(section_count));
|
||||
}
|
||||
let table_bytes = count
|
||||
.checked_mul(DESCRIPTOR_LEN)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
let stride = descriptor_stride(payload, count);
|
||||
let table_bytes = count.checked_mul(stride).ok_or(FspxError::Truncated)?;
|
||||
let table_end = HEADER_LEN
|
||||
.checked_add(table_bytes)
|
||||
.ok_or(FspxError::Truncated)?;
|
||||
@@ -223,6 +282,7 @@ fn read_fspx_header(payload: &[u8]) -> Result<Option<FspxHeader>, FspxError> {
|
||||
version,
|
||||
flags,
|
||||
count,
|
||||
stride,
|
||||
table_end,
|
||||
}))
|
||||
}
|
||||
@@ -236,9 +296,9 @@ fn walk_sections(
|
||||
mut on_section: impl FnMut(FspxSection, &[u8]) -> Result<(), FspxError>,
|
||||
) -> Result<(), FspxError> {
|
||||
for index in 0..header.count {
|
||||
let (id, offset, size) = descriptor_at(payload, index)?;
|
||||
let (id, offset, size) = descriptor_at(payload, index, header.stride)?;
|
||||
if usize::try_from(offset).is_ok_and(|start| start < header.table_end) {
|
||||
// `table_end` is at most 16 + 64 * 12 bytes, so it fits in u32.
|
||||
// `table_end` is at most 16 + 64 * 16 bytes, so it fits in u32.
|
||||
let table_end = u32::try_from(header.table_end).unwrap_or(u32::MAX);
|
||||
return Err(FspxError::LayoutMismatch {
|
||||
section_id: id,
|
||||
@@ -249,7 +309,7 @@ fn walk_sections(
|
||||
let end = section_end(offset, size, header.table_end, payload.len())
|
||||
.ok_or(FspxError::SectionOutOfBounds { section_id: id })?;
|
||||
for prev in 0..index {
|
||||
let (prev_id, prev_off, prev_size) = descriptor_at(payload, prev)?;
|
||||
let (prev_id, prev_off, prev_size) = descriptor_at(payload, prev, header.stride)?;
|
||||
if prev_id == id {
|
||||
return Err(FspxError::DuplicateSection { section_id: id });
|
||||
}
|
||||
@@ -282,7 +342,7 @@ pub(crate) fn scan_fspx(payload: &[u8]) -> Result<Option<FspxStageScan>, FspxErr
|
||||
};
|
||||
let mut stage = None;
|
||||
walk_sections(payload, &header, |section, body| {
|
||||
if section.id == 1 {
|
||||
if section.id == 1 && header.stride == DESCRIPTOR_LEN {
|
||||
stage = Some(stage_from_body(body)?);
|
||||
}
|
||||
Ok(())
|
||||
@@ -307,7 +367,7 @@ pub(crate) fn parse_fspx(payload: &[u8]) -> Result<Option<FspxInfo>, FspxError>
|
||||
walk_sections(payload, &header, |section, body| {
|
||||
match section.id {
|
||||
0 => section0 = Some(section),
|
||||
1 => {
|
||||
1 if header.stride == DESCRIPTOR_LEN => {
|
||||
let (stage, shader_model_major, shader_model_minor) = stage_from_body(body)?;
|
||||
stage_config = Some(FspxStageConfig {
|
||||
offset: section.offset,
|
||||
|
||||
@@ -8,16 +8,20 @@
|
||||
//!
|
||||
//! An `ACCC` payload that begins with `FSPX` uses the layout documented on
|
||||
//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table of
|
||||
//! at most [`FSPX_MAX_SECTIONS`] descriptors. A larger count is
|
||||
//! at most [`FSPX_MAX_SECTIONS`] descriptors, 12 bytes each for this
|
||||
//! repository's synthetic fixtures, or 16 bytes `{id, offset, size, 0}` when
|
||||
//! the table itself selects that stride. A larger count is
|
||||
//! [`ParseError::FspxTooManySections`] before any pairwise comparison. A
|
||||
//! descriptor whose offset lands inside the header plus descriptor table is
|
||||
//! [`ParseError::FspxLayoutMismatch`], kept apart from
|
||||
//! [`ParseError::FspxSectionOutOfBounds`] (a section past the payload end).
|
||||
//! Section 0 and section 7 are opaque header ranges, section 1 is the stage
|
||||
//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2
|
||||
//! code byte range. The code bytes are not decoded. This layout is synthetic.
|
||||
//! Parsing it does not establish that a console compiler produced the blob
|
||||
//! and is not Xbox hardware verification.
|
||||
//! code byte range. The code bytes are not decoded. The 12-byte stride is
|
||||
//! this repository's synthetic fixture layout; the 16-byte stride is the
|
||||
//! additional `{id, offset, size, 0}` table. Parsing either one does not
|
||||
//! establish that a console compiler produced the blob and is not Xbox
|
||||
//! hardware verification.
|
||||
//!
|
||||
//! A `DXIL` chunk is a program only when its payload is a `DxilProgramHeader`
|
||||
//! from the public DirectXShaderCompiler layout
|
||||
@@ -37,8 +41,9 @@
|
||||
//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal`
|
||||
//! copies `container_size` bytes when an executable `DXIL` chunk is present,
|
||||
//! including when an accompanying `FSPX` table is malformed, and logs only an
|
||||
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation
|
||||
//! is not implemented.
|
||||
//! ACCC-only `BX_SHADER_ERR_UNSUPPORTED` result. `bx_shader_translate_pair`
|
||||
//! translates a console vertex/pixel pair to HLSL with the `gfx10-translate`
|
||||
//! crate (#720); compiling that HLSL to DXIL is the caller's step.
|
||||
|
||||
mod c_abi;
|
||||
mod fspx;
|
||||
@@ -47,8 +52,10 @@ use std::fmt;
|
||||
|
||||
pub use c_abi::{
|
||||
BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_OOM, BX_SHADER_ERR_TRANSLATE,
|
||||
BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderInspection, bx_shader_free_buffer,
|
||||
bx_shader_inspect, bx_shader_prepare_for_d3dmetal,
|
||||
BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderInspection, BxShaderPairTranslation,
|
||||
BxShaderRootLayout, BxShaderRootParameter, bx_shader_free_buffer,
|
||||
bx_shader_free_pair_translation, bx_shader_inspect, bx_shader_prepare_for_d3dmetal,
|
||||
bx_shader_translate_pair, bx_shader_translate_pair_rooted,
|
||||
};
|
||||
pub use fspx::{FSPX_MAX_SECTIONS, FspxCodeBounds, FspxInfo, FspxSection, FspxStageConfig};
|
||||
|
||||
@@ -171,9 +178,9 @@ pub enum ParseError {
|
||||
section_id: u32,
|
||||
},
|
||||
/// A descriptor's offset lands inside the `FSPX` header plus descriptor
|
||||
/// table (`table_end` bytes), which the synthetic layout reserves. The
|
||||
/// table does not follow BetterXen's clean-room layout; it is not reported
|
||||
/// as an out-of-bounds section. The container is still rejected.
|
||||
/// table (`table_end` bytes) reserved by the stride in use (12-byte
|
||||
/// synthetic fixtures, or 16-byte `{id, offset, size, 0}`). It is not
|
||||
/// reported as an out-of-bounds section. The container is still rejected.
|
||||
FspxLayoutMismatch {
|
||||
chunk: usize,
|
||||
section_id: u32,
|
||||
@@ -228,7 +235,7 @@ impl fmt::Display for ParseError {
|
||||
table_end,
|
||||
} => write!(
|
||||
f,
|
||||
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the synthetic FSPX layout"
|
||||
"FSPX section {section_id} starts at offset {offset}, inside the {table_end}-byte header and section table, in chunk {chunk}: the table does not follow the FSPX layout"
|
||||
),
|
||||
Self::FspxDuplicateSection { chunk, section_id } => {
|
||||
write!(f, "duplicate FSPX section {section_id} in chunk {chunk}")
|
||||
@@ -780,6 +787,23 @@ mod tests {
|
||||
payload
|
||||
}
|
||||
|
||||
/// Version-1 table of 16-byte `{id, offset, size, 0}` entries. The fourth
|
||||
/// word of each entry stays 0. Bytes past the table stay 0.
|
||||
fn fspx_wide_entries(entries: &[(u32, u32, u32)], len: usize) -> Vec<u8> {
|
||||
assert!(16 + entries.len() * 16 <= len);
|
||||
let mut payload = vec![0u8; len];
|
||||
payload[..4].copy_from_slice(b"FSPX");
|
||||
payload[4..8].copy_from_slice(&1u32.to_le_bytes());
|
||||
payload[8..12].copy_from_slice(&(entries.len() as u32).to_le_bytes());
|
||||
for (index, (id, offset, size)) in entries.iter().enumerate() {
|
||||
let at = 16 + index * 16;
|
||||
payload[at..at + 4].copy_from_slice(&id.to_le_bytes());
|
||||
payload[at + 4..at + 8].copy_from_slice(&offset.to_le_bytes());
|
||||
payload[at + 8..at + 12].copy_from_slice(&size.to_le_bytes());
|
||||
}
|
||||
payload
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn classifies_synthetic_dxil_cs_6_6() {
|
||||
let blob = synthetic_dxil_blob();
|
||||
@@ -1100,9 +1124,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn fspx_offset_inside_header_or_table_is_layout_mismatch() {
|
||||
// Inside the 16-byte header, inside the first descriptor, inside the
|
||||
// descriptor itself, and the last reserved byte.
|
||||
for offset in [0u32, 8, 16, 28, 39] {
|
||||
// Inside the 16-byte header, the offset-1 case, inside the first
|
||||
// descriptor, inside the descriptor itself, and the last reserved byte.
|
||||
for offset in [0u32, 1, 8, 16, 28, 39] {
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(offset))]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
@@ -1125,6 +1149,8 @@ mod tests {
|
||||
}
|
||||
|
||||
// The first byte after the table is outside the reserved region.
|
||||
// 12-byte fixtures stay on that stride: this table's entries are 12
|
||||
// bytes, so the 16-byte rule does not apply.
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &fspx_two_sections(56))]);
|
||||
let info = inspect_dxbc(&blob).expect("offset at the end of the stage section");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
@@ -1132,6 +1158,202 @@ mod tests {
|
||||
assert!(summarize_dxbc(&blob).is_ok());
|
||||
}
|
||||
|
||||
/// Four 16-byte entries `{0, 1, 6, 7}`. Section 0 begins at byte 80, which
|
||||
/// is `16 + 4 * 16`. Section 1 is an opaque 20-byte section whose first
|
||||
/// word is not a synthetic stage enum, section 6 is the code range, and
|
||||
/// section 7 follows the code.
|
||||
fn synthetic_wide_fspx() -> Vec<u8> {
|
||||
let mut payload =
|
||||
fspx_wide_entries(&[(0, 80, 8), (1, 88, 20), (6, 108, 16), (7, 124, 4)], 128);
|
||||
payload[80..88].copy_from_slice(&[0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00]);
|
||||
payload[88..108].copy_from_slice(&[
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xCA, 0xFE, 0xBA, 0xBE, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
]);
|
||||
payload[108..124].copy_from_slice(b"SYNTH_RDNA2_CODE");
|
||||
payload[124..128].copy_from_slice(&[0x01, 0x00, 0x00, 0x00]);
|
||||
payload
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_byte_fspx_classifies_as_accc_with_section_bounds() {
|
||||
let payload = synthetic_wide_fspx();
|
||||
assert_eq!(
|
||||
&payload[80..88],
|
||||
&[0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00]
|
||||
);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]);
|
||||
let info =
|
||||
inspect_dxbc(&blob).expect("16-byte section table with opaque 20-byte section 1");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
assert!(info.accc_is_fspx);
|
||||
assert_eq!(info.dxil_size, 0);
|
||||
assert!(!info.chunks.iter().any(|chunk| &chunk.fourcc == b"DXIL"));
|
||||
assert_eq!(info.stage, ShaderStage::Unknown);
|
||||
assert_eq!((info.shader_model_major, info.shader_model_minor), (0, 0));
|
||||
assert_eq!(info.accc_size, 128);
|
||||
|
||||
let fspx = info.fspx.expect("fspx table");
|
||||
assert_eq!(fspx.version, 1);
|
||||
assert_eq!(
|
||||
fspx.sections,
|
||||
vec![
|
||||
FspxSection {
|
||||
id: 0,
|
||||
offset: 80,
|
||||
size: 8
|
||||
},
|
||||
FspxSection {
|
||||
id: 1,
|
||||
offset: 88,
|
||||
size: 20
|
||||
},
|
||||
FspxSection {
|
||||
id: 6,
|
||||
offset: 108,
|
||||
size: 16
|
||||
},
|
||||
FspxSection {
|
||||
id: 7,
|
||||
offset: 124,
|
||||
size: 4
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
fspx.section0.map(|section| (section.offset, section.size)),
|
||||
Some((80, 8))
|
||||
);
|
||||
assert!(fspx.stage_config.is_none());
|
||||
let code = fspx.rdna_code.expect("section 6");
|
||||
assert_eq!((code.offset, code.size), (108, 16));
|
||||
assert_eq!(
|
||||
fspx.rdna_code_bytes(&payload),
|
||||
Some(b"SYNTH_RDNA2_CODE".as_slice())
|
||||
);
|
||||
assert_eq!(
|
||||
fspx.section7.map(|section| (section.offset, section.size)),
|
||||
Some((124, 4))
|
||||
);
|
||||
|
||||
let mut c_info = BxShaderInspection {
|
||||
kind: 99,
|
||||
..BxShaderInspection::default()
|
||||
};
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(c_info.kind, 3);
|
||||
assert_eq!(c_info.stage, 0);
|
||||
assert_eq!(c_info.shader_model_major, 0);
|
||||
assert_eq!(c_info.shader_model_minor, 0);
|
||||
assert_eq!(c_info.dxil_chunk_size, 0);
|
||||
assert_eq!(c_info.accc_chunk_size, 128);
|
||||
}
|
||||
|
||||
/// `bx-cli shader` prints this on `Ok` from `inspect_dxbc` and prints
|
||||
/// `error:` on `Err`. The 16-byte container must take the success path.
|
||||
#[test]
|
||||
fn bx_cli_shader_reports_accc_for_sixteen_byte_fspx() {
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &synthetic_wide_fspx())]);
|
||||
let info = inspect_dxbc(&blob).unwrap_or_else(|err| {
|
||||
panic!("bx-cli shader would fail with error: {err}");
|
||||
});
|
||||
let report = format!(
|
||||
"Kind : {:?}\nStage / SM : {:?} ({}.{})\nContainer size : {} bytes\nDXIL chunk : {} bytes\nACCC chunk : {} bytes (FSPX={})\nRoot signature : {}",
|
||||
info.kind,
|
||||
info.stage,
|
||||
info.shader_model_major,
|
||||
info.shader_model_minor,
|
||||
info.container_size,
|
||||
info.dxil_size,
|
||||
info.accc_size,
|
||||
info.accc_is_fspx,
|
||||
info.has_root_signature
|
||||
);
|
||||
assert!(
|
||||
report.starts_with("Kind : AcccOnly\n"),
|
||||
"{report}"
|
||||
);
|
||||
assert!(
|
||||
report.contains("ACCC chunk : 128 bytes (FSPX=true)"),
|
||||
"{report}"
|
||||
);
|
||||
assert!(!report.contains("error:"), "{report}");
|
||||
assert_eq!(info.kind, ShaderKind::AcccOnly);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_byte_fspx_offset_inside_table_is_layout_mismatch() {
|
||||
// Offset 1 on a 16-byte-shaped table. The first section does not begin
|
||||
// at 16 + 4 * 16, so today's 12-byte parse stays (table end 64) and
|
||||
// rejects it. The existing 12-byte offset-1 case is the loop in
|
||||
// `fspx_offset_inside_header_or_table_is_layout_mismatch`.
|
||||
let offset_one =
|
||||
fspx_wide_entries(&[(0, 1, 4), (1, 88, 12), (4, 100, 4), (6, 104, 16)], 120);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &offset_one)]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 0,
|
||||
offset: 1,
|
||||
table_end: 64,
|
||||
};
|
||||
assert_eq!(inspect_dxbc(&blob), Err(expected.clone()));
|
||||
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(expected));
|
||||
let mut c_info = BxShaderInspection {
|
||||
kind: 99,
|
||||
..BxShaderInspection::default()
|
||||
};
|
||||
let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut c_info) };
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert_eq!(c_info.kind, 0);
|
||||
|
||||
// Section 0's own offset is 70, inside 16 + 4 * 16 and past the
|
||||
// 12-byte table. The 12-byte reading then takes the next entry's id
|
||||
// as an offset and still reports offset 1.
|
||||
let inside_wide =
|
||||
fspx_wide_entries(&[(0, 70, 8), (1, 88, 12), (4, 100, 4), (6, 104, 16)], 120);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &inside_wide)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 0,
|
||||
offset: 1,
|
||||
table_end: 64,
|
||||
})
|
||||
);
|
||||
|
||||
// First section begins at 80, so the stride is 16 bytes, and a later
|
||||
// entry whose offset sits inside 16 + count * 16 is still rejected.
|
||||
let later_inside =
|
||||
fspx_wide_entries(&[(0, 80, 4), (1, 20, 12), (4, 100, 4), (6, 104, 4)], 120);
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &later_inside)]);
|
||||
let expected = ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 1,
|
||||
offset: 20,
|
||||
table_end: 80,
|
||||
};
|
||||
assert_eq!(inspect_dxbc(&blob), Err(expected.clone()));
|
||||
assert_eq!(summarize_dxbc(&blob).map(|_| ()), Err(expected));
|
||||
|
||||
// A non-zero fourth word is not the 16-byte table, even though the
|
||||
// first offset equals 16 + count * 16.
|
||||
let mut nonzero_pad =
|
||||
fspx_wide_entries(&[(0, 80, 8), (1, 88, 12), (4, 100, 4), (6, 104, 16)], 120);
|
||||
nonzero_pad[76..80].copy_from_slice(&1u32.to_le_bytes());
|
||||
let blob = build_synthetic_dxbc(&[(b"ACCC", &nonzero_pad)]);
|
||||
assert_eq!(
|
||||
inspect_dxbc(&blob),
|
||||
Err(ParseError::FspxLayoutMismatch {
|
||||
chunk: 0,
|
||||
section_id: 0,
|
||||
offset: 1,
|
||||
table_end: 64,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fspx_layout_mismatch_is_not_out_of_bounds() {
|
||||
// Past the payload end is still out of bounds, not a layout mismatch.
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
//! `bx_shader_translate_pair` through its C entry point.
|
||||
//!
|
||||
//! The expected HLSL and layout are the Python prototype's output for the same pair (the golden
|
||||
//! files of `gfx10-translate`); the expected keys are computed here from the FNV authors'
|
||||
//! published parameters, not by the bridge.
|
||||
|
||||
use dxbc_accc::{
|
||||
BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderPairTranslation,
|
||||
bx_shader_free_pair_translation, bx_shader_translate_pair,
|
||||
};
|
||||
use dxbc_accc::{BxShaderRootLayout, BxShaderRootParameter, bx_shader_translate_pair_rooted};
|
||||
|
||||
const VS_HEX: &str = include_str!("../../gfx10-translate/tests/goldens/textured.vs.hex");
|
||||
const PS_HEX: &str = include_str!("../../gfx10-translate/tests/goldens/textured.ps.hex");
|
||||
const VS_HLSL: &str = include_str!("../../gfx10-translate/tests/goldens/textured.vs.hlsl");
|
||||
const PS_HLSL: &str = include_str!("../../gfx10-translate/tests/goldens/textured.ps.hlsl");
|
||||
const LAYOUT: &str = include_str!("../../gfx10-translate/tests/goldens/textured.il");
|
||||
|
||||
/// Instruction words as the little-endian bytes of a raw code blob.
|
||||
fn code(hex: &str) -> Vec<u8> {
|
||||
hex.split_whitespace()
|
||||
.flat_map(|w| u32::from_str_radix(w, 16).unwrap().to_le_bytes())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fnv1a64(data: &[u8]) -> u64 {
|
||||
let mut h: u64 = 14_695_981_039_346_656_037;
|
||||
for b in data {
|
||||
h = (h ^ u64::from(*b)).wrapping_mul(1_099_511_628_211);
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
fn text(ptr: *const u8, len: usize) -> String {
|
||||
if ptr.is_null() {
|
||||
return String::new();
|
||||
}
|
||||
// SAFETY: the bridge returned `len` bytes at `ptr`.
|
||||
String::from_utf8(unsafe { std::slice::from_raw_parts(ptr, len) }.to_vec()).unwrap()
|
||||
}
|
||||
|
||||
fn translate(vs: &[u8], ps: &[u8]) -> (i32, BxShaderPairTranslation) {
|
||||
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
|
||||
// SAFETY: both inputs are readable slices and `out` is writable.
|
||||
let status = unsafe {
|
||||
bx_shader_translate_pair(
|
||||
vs.as_ptr(),
|
||||
vs.len(),
|
||||
ps.as_ptr(),
|
||||
ps.len(),
|
||||
out.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
// SAFETY: the bridge fills `out` in every case.
|
||||
(status, unsafe { out.assume_init() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pair_translates_to_the_prototypes_output() {
|
||||
let (vs, ps) = (code(VS_HEX), code(PS_HEX));
|
||||
let (status, mut t) = translate(&vs, &ps);
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
assert_eq!(text(t.vs_hlsl, t.vs_hlsl_len), VS_HLSL);
|
||||
assert_eq!(text(t.ps_hlsl, t.ps_hlsl_len), PS_HLSL);
|
||||
assert_eq!(text(t.layout, t.layout_len), LAYOUT);
|
||||
assert!(t.reason.is_null() && t.reason_len == 0);
|
||||
assert_eq!((t.vs_key, t.ps_key), (fnv1a64(&vs), fnv1a64(&ps)));
|
||||
// SAFETY: `t` was filled by the bridge and is freed once.
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
assert!(t.vs_hlsl.is_null() && t.ps_hlsl.is_null() && t.layout.is_null());
|
||||
assert_eq!(
|
||||
(t.vs_hlsl_len, t.ps_hlsl_len, t.layout_len, t.vs_key),
|
||||
(0, 0, 0, 0)
|
||||
);
|
||||
// Freeing a cleared structure, or none, does nothing.
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
unsafe { bx_shader_free_pair_translation(std::ptr::null_mut()) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refusal_carries_its_reason_and_the_keys() {
|
||||
// image_store v0, v[1:2], s[20:27] dmask:0x1 dim:2D ; s_endpgm (llvm-mc, gfx1030): the
|
||||
// translator has no rule for image stores.
|
||||
let (vs, ps) = (code(VS_HEX), code("f0200108 00050001 bf810000"));
|
||||
let (status, mut t) = translate(&vs, &ps);
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
let reason = text(t.reason, t.reason_len);
|
||||
assert!(reason.contains("image_store"), "{reason}");
|
||||
assert!(t.vs_hlsl.is_null() && t.ps_hlsl.is_null() && t.layout.is_null());
|
||||
assert_eq!((t.vs_key, t.ps_key), (fnv1a64(&vs), fnv1a64(&ps)));
|
||||
// SAFETY: as above.
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
assert!(t.reason.is_null());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_inputs_are_invalid() {
|
||||
let (vs, ps) = (code(VS_HEX), code(PS_HEX));
|
||||
// An empty stage.
|
||||
let (status, t) = translate(&vs, &[]);
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
|
||||
// A container (DXBC magic) that holds no console code.
|
||||
let mut not_code = b"DXBC".to_vec();
|
||||
not_code.extend([0u8; 60]);
|
||||
let (status, t) = translate(¬_code, &ps);
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
|
||||
// No output structure, and NULL inputs with a length.
|
||||
// SAFETY: a null `out` is not written; null inputs are not read.
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
bx_shader_translate_pair(
|
||||
vs.as_ptr(),
|
||||
vs.len(),
|
||||
ps.as_ptr(),
|
||||
ps.len(),
|
||||
std::ptr::null_mut()
|
||||
),
|
||||
BX_SHADER_ERR_INVALID_BLOB
|
||||
);
|
||||
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
|
||||
assert_eq!(
|
||||
bx_shader_translate_pair(
|
||||
std::ptr::null(),
|
||||
16,
|
||||
ps.as_ptr(),
|
||||
ps.len(),
|
||||
out.as_mut_ptr()
|
||||
),
|
||||
BX_SHADER_ERR_INVALID_BLOB
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// One root SRV at t5: s0 = s8 ; s1 = s9 | (1 << 16) ; s2 = -1 ; s3 = 0x11014fac ; v1 = v0 + v0 ;
|
||||
// buffer_load_dwordx3 v[1:3], v1, s[0:3], 8 offen offset:4 ; v4 = 1.0 ; exp pos0 ; s_endpgm
|
||||
// (our own assembly through llvm-mc; the same program as gfx10-translate's root-buffer test).
|
||||
const ROOT_SRV_VS: &str = "be800308 8801ff09 00010000 be8203c1 be8303ff 11014fac 4a020100 e03c1004 88000101 7e0802f2 f80008cf 04030201 bf810000";
|
||||
/// v_mov_b32 v0, 1.0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
|
||||
const FLAT_PS: &str = "7e0002f2 f800180f 00000000 bf810000";
|
||||
|
||||
fn translate_rooted(
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
layout: *const BxShaderRootLayout,
|
||||
) -> (i32, BxShaderPairTranslation) {
|
||||
let mut out = std::mem::MaybeUninit::<BxShaderPairTranslation>::uninit();
|
||||
// SAFETY: the inputs are readable slices, `layout` is null or valid, `out` is writable.
|
||||
let status = unsafe {
|
||||
bx_shader_translate_pair_rooted(
|
||||
vs.as_ptr(),
|
||||
vs.len(),
|
||||
ps.as_ptr(),
|
||||
ps.len(),
|
||||
layout,
|
||||
out.as_mut_ptr(),
|
||||
)
|
||||
};
|
||||
// SAFETY: the bridge fills `out` in every case.
|
||||
(status, unsafe { out.assume_init() })
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_root_layout_changes_what_the_registers_mean() {
|
||||
let (vs, ps) = (code(ROOT_SRV_VS), code(FLAT_PS));
|
||||
// Without a layout s8 is taken for a table pointer, and building a buffer from it is refused.
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, std::ptr::null());
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
// With the layout "one root SRV at t5, space 3" it is that parameter's buffer.
|
||||
let parameters = [BxShaderRootParameter {
|
||||
r#type: 3,
|
||||
num_32bit_values: 0,
|
||||
shader_register: 5,
|
||||
register_space: 3,
|
||||
}];
|
||||
let layout = BxShaderRootLayout {
|
||||
parameters: parameters.as_ptr(),
|
||||
parameter_count: 1,
|
||||
flags: 0,
|
||||
};
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, &layout);
|
||||
assert_eq!(status, BX_SHADER_OK);
|
||||
let hlsl = text(t.vs_hlsl, t.vs_hlsl_len);
|
||||
assert!(
|
||||
hlsl.contains("ByteAddressBuffer rootbuf0 : register(t5, space3);"),
|
||||
"{hlsl}"
|
||||
);
|
||||
assert!(hlsl.contains("uint vertex_id : SV_VertexID"), "{hlsl}");
|
||||
assert_eq!(text(t.layout, t.layout_len), "USE ROOT 0\n");
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
// The memory-based flag changes where root data is read: this register-form shader then
|
||||
// reads nothing the layout accounts for and is refused.
|
||||
let memory = BxShaderRootLayout {
|
||||
flags: 0x0100_0000,
|
||||
..layout
|
||||
};
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, &memory);
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inconsistent_layouts_are_invalid() {
|
||||
let (vs, ps) = (code(ROOT_SRV_VS), code(FLAT_PS));
|
||||
// A count without parameters.
|
||||
let missing = BxShaderRootLayout {
|
||||
parameters: std::ptr::null(),
|
||||
parameter_count: 2,
|
||||
flags: 0,
|
||||
};
|
||||
let (status, t) = translate_rooted(&vs, &ps, &missing);
|
||||
assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB);
|
||||
assert!(t.vs_hlsl.is_null() && t.reason.is_null());
|
||||
// A parameter type Direct3D 12 does not have.
|
||||
let parameters = [BxShaderRootParameter {
|
||||
r#type: 9,
|
||||
num_32bit_values: 0,
|
||||
shader_register: 0,
|
||||
register_space: 0,
|
||||
}];
|
||||
let unknown = BxShaderRootLayout {
|
||||
parameters: parameters.as_ptr(),
|
||||
parameter_count: 1,
|
||||
flags: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
translate_rooted(&vs, &ps, &unknown).0,
|
||||
BX_SHADER_ERR_INVALID_BLOB
|
||||
);
|
||||
// An empty signature is a layout like any other: the shader reads past it and is refused.
|
||||
let empty = BxShaderRootLayout {
|
||||
parameters: std::ptr::null(),
|
||||
parameter_count: 0,
|
||||
flags: 0,
|
||||
};
|
||||
let (status, mut t) = translate_rooted(&vs, &ps, &empty);
|
||||
assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED);
|
||||
unsafe { bx_shader_free_pair_translation(&mut t) };
|
||||
}
|
||||
@@ -39,7 +39,7 @@ Game shaders stay on your machine: never commit a shader, a listing, or anything
|
||||
## Differences from the prototype
|
||||
|
||||
- `s_movk_i32` sign-extends its 16-bit immediate. The prototype read it unsigned.
|
||||
- Output modifiers (`clamp`, `mul:`/`div:`, `op_sel`, `abs`) are refused on every VOP3 instruction, not only on `_e64` forms.
|
||||
- Output modifiers on a 32-bit float result (`clamp`, `mul:`/`div:`) and input `abs`/`neg` are translated. `op_sel` on a 32-bit source, and `clamp` or `abs` on an integer instruction, are refused. `op_sel` on `v_fma_mix*` selects the half of an f16 source. SDWA and DPP forms are translated for the selectors and lane controls in `src/translate.rs`; a reserved selector or any other DPP control is refused.
|
||||
- `v_fma_mix*` with `op_sel_hi` all zero (all 32-bit sources) is accepted. The prototype refused it.
|
||||
- **New rules:**
|
||||
- the multiply-add family (`v_mac_f32`, `v_mad_f32`, `v_madak/madmk_f32`, `v_fmaak/fmamk_f32`);
|
||||
|
||||
@@ -1,15 +1,28 @@
|
||||
//! The GPU code of one stage from a console shader container.
|
||||
//!
|
||||
//! A console container is a DXBC file whose DXIL part carries no bitcode. The console code is in
|
||||
//! an `XBCH` record: magic, version, compressed size (u64), uncompressed size (u64), then a zlib
|
||||
//! stream. It inflates to an `FSSM` block: a 16-byte header (magic, version, size), then offsets
|
||||
//! relative to the end of that header. One of the per-stage slots at 0x18..0x78 is not
|
||||
//! 0xDEADBEEF filler and locates the stage record, whose first two u64 fields are the code offset
|
||||
//! and size. The code starts with 12-byte header records (a VOP3 word whose top half is 0xD580,
|
||||
//! `v_nop` with a literal) before the first instruction.
|
||||
//! A console container is a DXBC file whose DXIL part carries no bitcode (or carries an `XDAT`
|
||||
//! section after the bitcode/`NOBC` placeholder). The console code is in an `XBCH` record:
|
||||
//! - `+0..+4`: magic `b"XBCH"`
|
||||
//! - `+4..+8`: version (`u32`, low byte checked: `2` = uncompressed `FSSM` payload of `csize`
|
||||
//! bytes at `+24`; `3` = zlib-compressed `FSSM` stream of `csize` bytes at `+24` inflating to
|
||||
//! `usize` bytes; synthetic conformance tests also use `1` for zlib-compressed)
|
||||
//! - `+8..+16`: `csize` (`u64`), payload/compressed stream size in bytes
|
||||
//! - `+16..+24`: `usize` (`u64`), uncompressed size in bytes (used for zlib-compressed records)
|
||||
//! - `+24..+24+csize`: payload (`FSSM` block or zlib stream)
|
||||
//!
|
||||
//! These are inferences from containers of the project-authorized target build (AGENTS.md
|
||||
//! section 6), checked by the synthetic container in the tests below.
|
||||
//! It inflates (or decodes directly for version 2) to an `FSSM` block: a 16-byte header (magic,
|
||||
//! version, size), then offsets relative to the end of that header. One of the per-stage slots
|
||||
//! at 0x18..0x78 is not 0xDEADBEEF filler and locates the stage record, whose first two u64 fields
|
||||
//! are the code offset and size. The code starts with 12-byte header records (a VOP3 word whose
|
||||
//! top half is 0xD580, `v_nop` with a literal) before the first instruction.
|
||||
//!
|
||||
//! Because the 4-byte sequence `b"XBCH"` can also appear incidentally in earlier chunks (such as
|
||||
//! `STAT` or `DXIL` bitcode) before the real `XBCH` record, [`container_code`] scans all `b"XBCH"`
|
||||
//! occurrences and validates each candidate's header, bounds, version, and `FSSM` magic rather than
|
||||
//! stopping at the first match.
|
||||
//!
|
||||
//! These are inferences from containers of the project-authorized target build and the GDK
|
||||
//! compiler (`AGENTS.md` section 6), checked by the synthetic containers in the tests below.
|
||||
|
||||
use crate::inflate::zlib_inflate;
|
||||
use std::fmt;
|
||||
@@ -47,31 +60,49 @@ fn u64_at(b: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_le_bytes(b.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
/// The stage code inside a console container, header records included.
|
||||
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
let at = blob
|
||||
.windows(4)
|
||||
.position(|w| w == b"XBCH")
|
||||
.ok_or(ContainerError::NoXbch)?;
|
||||
let csize = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
|
||||
let usize_ = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))? as usize;
|
||||
let stream = blob
|
||||
.get(at + 24..at.saturating_add(24).saturating_add(csize))
|
||||
fn try_xbch_at(blob: &[u8], at: usize) -> Result<Vec<u8>, ContainerError> {
|
||||
let ver = u32_at(blob, at + 4).ok_or(ContainerError::BadXbch("truncated header"))? & 0xff;
|
||||
let csize_u64 = u64_at(blob, at + 8).ok_or(ContainerError::BadXbch("truncated header"))?;
|
||||
let usize_u64 = u64_at(blob, at + 16).ok_or(ContainerError::BadXbch("truncated header"))?;
|
||||
let csize = usize::try_from(csize_u64)
|
||||
.map_err(|_| ContainerError::BadXbch("compressed size past the end"))?;
|
||||
let end = at
|
||||
.checked_add(24)
|
||||
.and_then(|start| start.checked_add(csize))
|
||||
.filter(|&end| end <= blob.len())
|
||||
.ok_or(ContainerError::BadXbch("compressed size past the end"))?;
|
||||
let fssm = zlib_inflate(stream, usize_.min(MAX_FSSM))
|
||||
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
|
||||
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
let payload = &blob[at + 24..end];
|
||||
match ver {
|
||||
2 => {
|
||||
if payload.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
}
|
||||
Ok(payload.to_vec())
|
||||
}
|
||||
1 | 3 => {
|
||||
let usize_ = usize::try_from(usize_u64)
|
||||
.map_err(|_| ContainerError::BadXbch("does not inflate to an FSSM block"))?;
|
||||
let fssm = zlib_inflate(payload, usize_.min(MAX_FSSM))
|
||||
.map_err(|_| ContainerError::BadXbch("zlib stream"))?;
|
||||
if fssm.len() != usize_ || fssm.get(..4) != Some(b"FSSM") {
|
||||
return Err(ContainerError::BadXbch("does not inflate to an FSSM block"));
|
||||
}
|
||||
Ok(fssm)
|
||||
}
|
||||
_ => Err(ContainerError::BadXbch("unsupported version")),
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_fssm_code(fssm: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
const BASE: usize = 16;
|
||||
let record = (0x18..0x78)
|
||||
.step_by(8)
|
||||
.filter_map(|slot| u64_at(&fssm, slot))
|
||||
.filter_map(|slot| u64_at(fssm, slot))
|
||||
.find(|&v| v != FILLER)
|
||||
.ok_or(ContainerError::NoStageRecord)? as usize
|
||||
+ BASE;
|
||||
let offset = u64_at(&fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let size = u64_at(&fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let offset = u64_at(fssm, record).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let size = u64_at(fssm, record + 8).ok_or(ContainerError::NoStageRecord)? as usize;
|
||||
let code = fssm
|
||||
.get(BASE + offset..BASE + offset + size)
|
||||
.ok_or(ContainerError::BadCode("outside the FSSM block"))?;
|
||||
@@ -83,6 +114,21 @@ pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
Ok(code.to_vec())
|
||||
}
|
||||
|
||||
/// The stage code inside a console container, header records included.
|
||||
pub fn container_code(blob: &[u8]) -> Result<Vec<u8>, ContainerError> {
|
||||
let mut last_err = None;
|
||||
for (at, w) in blob.windows(4).enumerate() {
|
||||
if w != b"XBCH" {
|
||||
continue;
|
||||
}
|
||||
match try_xbch_at(blob, at) {
|
||||
Ok(fssm) => return extract_fssm_code(&fssm),
|
||||
Err(e) => last_err = Some(e),
|
||||
}
|
||||
}
|
||||
Err(last_err.unwrap_or(ContainerError::NoXbch))
|
||||
}
|
||||
|
||||
/// The instruction words of a stage: from a console container (`DXBC` magic) or a raw code blob,
|
||||
/// with the leading 12-byte header records skipped.
|
||||
pub fn code_words(blob: &[u8]) -> Result<Vec<u32>, ContainerError> {
|
||||
@@ -125,9 +171,7 @@ mod tests {
|
||||
s
|
||||
}
|
||||
|
||||
/// A container laid out as the module comment describes: one header record, then two
|
||||
/// instruction words, the stage record in slot 0x30.
|
||||
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
fn build_fssm(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&0xD580_0000u32.to_le_bytes());
|
||||
code.extend_from_slice(&[0u8; 8]);
|
||||
@@ -146,17 +190,33 @@ mod tests {
|
||||
fssm[16 + record + 8..16 + record + 16].copy_from_slice(&(code.len() as u64).to_le_bytes());
|
||||
fssm.resize(16 + code_offset as usize, 0);
|
||||
fssm.extend_from_slice(&code);
|
||||
let stream = stored(&fssm);
|
||||
fssm
|
||||
}
|
||||
|
||||
fn container_with_version(code_words_after_header: &[u32], version: u32) -> Vec<u8> {
|
||||
let fssm = build_fssm(code_words_after_header);
|
||||
let (payload, usize_) = if (version & 0xff) == 2 {
|
||||
(fssm, 0u64)
|
||||
} else {
|
||||
let usize_ = fssm.len() as u64;
|
||||
(stored(&fssm), usize_)
|
||||
};
|
||||
let mut blob = b"DXBC".to_vec();
|
||||
blob.extend_from_slice(&[0u8; 28]);
|
||||
blob.extend_from_slice(b"XBCH");
|
||||
blob.extend_from_slice(&1u32.to_le_bytes());
|
||||
blob.extend_from_slice(&(stream.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&(fssm.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&stream);
|
||||
blob.extend_from_slice(&version.to_le_bytes());
|
||||
blob.extend_from_slice(&(payload.len() as u64).to_le_bytes());
|
||||
blob.extend_from_slice(&usize_.to_le_bytes());
|
||||
blob.extend_from_slice(&payload);
|
||||
blob
|
||||
}
|
||||
|
||||
/// A container laid out as the module comment describes: one header record, then two
|
||||
/// instruction words, the stage record in slot 0x30.
|
||||
fn container(code_words_after_header: &[u32]) -> Vec<u8> {
|
||||
container_with_version(code_words_after_header, 1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_the_stage_code_and_skips_header_records() {
|
||||
let blob = container(&[0xBF81_0000, 0x1234_5678]);
|
||||
@@ -171,6 +231,24 @@ mod tests {
|
||||
assert_eq!(code_words(&raw).unwrap(), vec![0xBF81_0000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_incidental_xbch_bytes_before_the_record() {
|
||||
let mut blob = container_with_version(&[0xBF81_0000, 0x1234_5678], 3);
|
||||
// Simulate an incidental "XBCH" sequence in an earlier chunk (e.g. STAT or DXIL bitcode)
|
||||
// whose +8 bytes look like a compressed size past the end of the container.
|
||||
blob[8..12].copy_from_slice(b"XBCH");
|
||||
blob[16..24].copy_from_slice(&u64::MAX.to_le_bytes());
|
||||
assert_eq!(code_words(&blob).unwrap(), vec![0xBF81_0000, 0x1234_5678]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supports_uncompressed_version_2_and_compressed_version_3() {
|
||||
let v2 = container_with_version(&[0xBF81_0000], 2);
|
||||
assert_eq!(code_words(&v2).unwrap(), vec![0xBF81_0000]);
|
||||
let v3 = container_with_version(&[0xBF81_0000], 3);
|
||||
assert_eq!(code_words(&v3).unwrap(), vec![0xBF81_0000]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_what_is_missing() {
|
||||
assert_eq!(
|
||||
@@ -181,5 +259,11 @@ mod tests {
|
||||
let at = blob.windows(4).position(|w| w == b"XBCH").unwrap();
|
||||
blob[at + 24] = 0; // break the zlib header
|
||||
assert!(matches!(code_words(&blob), Err(ContainerError::BadXbch(_))));
|
||||
|
||||
let v4 = container_with_version(&[0xBF81_0000], 4);
|
||||
assert_eq!(
|
||||
code_words(&v4),
|
||||
Err(ContainerError::BadXbch("unsupported version"))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,7 @@ pub struct Mods {
|
||||
pub neg_hi: u8,
|
||||
pub op_sel: u8,
|
||||
pub op_sel_hi: u8,
|
||||
pub high: bool,
|
||||
pub gds: bool,
|
||||
}
|
||||
|
||||
@@ -128,6 +129,111 @@ pub enum Extension {
|
||||
Dpp(u32),
|
||||
}
|
||||
|
||||
/// Selectors in an SDWA word (RDNA 2 VOP_SDWA). A selector is `BYTE_0`..`BYTE_3` (0..3),
|
||||
/// `WORD_0`..`WORD_1` (4..5) or `DWORD` (6); 7 is reserved. `dst_unused` is pad (0),
|
||||
/// sign-extend (1) or preserve (2); 3 is reserved.
|
||||
///
|
||||
/// On a VOPC SDWA word, bits 15:8 are the mask destination (`vcc` when bit 7 is clear, otherwise
|
||||
/// a scalar operand in the low 7 bits), not `dst_sel` / `clamp` / `omod`. The source fields are
|
||||
/// in the same place.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Sdwa {
|
||||
pub src0_scalar: bool,
|
||||
pub dst_sel: u8,
|
||||
pub dst_unused: u8,
|
||||
pub clamp: bool,
|
||||
pub omod: u8,
|
||||
pub src0_sel: u8,
|
||||
pub src0_sext: bool,
|
||||
pub src0_neg: bool,
|
||||
pub src0_abs: bool,
|
||||
pub src1_sel: u8,
|
||||
pub src1_sext: bool,
|
||||
pub src1_neg: bool,
|
||||
pub src1_abs: bool,
|
||||
pub src1_scalar: bool,
|
||||
}
|
||||
|
||||
impl Sdwa {
|
||||
pub fn parse(word: u32) -> Self {
|
||||
Self {
|
||||
src0_scalar: bits(word, 23, 1) != 0,
|
||||
dst_sel: bits(word, 8, 3) as u8,
|
||||
dst_unused: bits(word, 11, 2) as u8,
|
||||
clamp: bits(word, 13, 1) != 0,
|
||||
omod: bits(word, 14, 2) as u8,
|
||||
src0_sel: bits(word, 16, 3) as u8,
|
||||
src0_sext: bits(word, 19, 1) != 0,
|
||||
src0_neg: bits(word, 20, 1) != 0,
|
||||
src0_abs: bits(word, 21, 1) != 0,
|
||||
src1_sel: bits(word, 24, 3) as u8,
|
||||
src1_sext: bits(word, 27, 1) != 0,
|
||||
src1_neg: bits(word, 28, 1) != 0,
|
||||
src1_abs: bits(word, 29, 1) != 0,
|
||||
src1_scalar: bits(word, 31, 1) != 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// VOPC SDWA destination in bits 15:8. `None` is `vcc`; `Some` is the scalar operand code.
|
||||
pub fn vopc_dst(word: u32) -> Option<u32> {
|
||||
let d = bits(word, 8, 8);
|
||||
if d & 0x80 == 0 { None } else { Some(d & 0x7f) }
|
||||
}
|
||||
}
|
||||
|
||||
/// DPP16 word (src0 field 250). `ctrl` is the 9-bit lane control. `bound_zero` is the bit LLVM
|
||||
/// prints as `bound_ctrl:1` (the assembler also accepts `bound_ctrl:0` for it): an invalid source
|
||||
/// lane reads 0. When the bit is clear, that lane does not write the destination.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Dpp16 {
|
||||
pub src0: u8,
|
||||
pub ctrl: u16,
|
||||
pub fi: bool,
|
||||
pub bound_zero: bool,
|
||||
pub src0_neg: bool,
|
||||
pub src0_abs: bool,
|
||||
pub src1_neg: bool,
|
||||
pub src1_abs: bool,
|
||||
pub bank_mask: u8,
|
||||
pub row_mask: u8,
|
||||
}
|
||||
|
||||
impl Dpp16 {
|
||||
pub fn parse(word: u32) -> Self {
|
||||
Self {
|
||||
src0: bits(word, 0, 8) as u8,
|
||||
ctrl: bits(word, 8, 9) as u16,
|
||||
fi: bits(word, 18, 1) != 0,
|
||||
bound_zero: bits(word, 19, 1) != 0,
|
||||
src0_neg: bits(word, 20, 1) != 0,
|
||||
src0_abs: bits(word, 21, 1) != 0,
|
||||
src1_neg: bits(word, 22, 1) != 0,
|
||||
src1_abs: bits(word, 23, 1) != 0,
|
||||
bank_mask: bits(word, 24, 4) as u8,
|
||||
row_mask: bits(word, 28, 4) as u8,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// DPP8 word (src0 field 233, or 234 when `fi` is set). `sel` packs eight 3-bit lane numbers,
|
||||
/// lane 0 in the low bits: within each group of 8 lanes, lane `k` reads selector `k`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Dpp8 {
|
||||
pub src0: u8,
|
||||
pub sel: u32,
|
||||
pub fi: bool,
|
||||
}
|
||||
|
||||
impl Dpp8 {
|
||||
pub fn parse(word: u32, fi: bool) -> Self {
|
||||
Self {
|
||||
src0: bits(word, 0, 8) as u8,
|
||||
sel: word >> 8,
|
||||
fi,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Inst {
|
||||
pub name: &'static str,
|
||||
@@ -143,6 +249,24 @@ pub struct Inst {
|
||||
pub mods: Mods,
|
||||
/// SDWA or DPP extension word. Its real first source is in that word, not in `ops`.
|
||||
pub ext: Option<Extension>,
|
||||
/// MIMG in the NSA (non-sequential address) encoding: the address VGPRs after the first, one
|
||||
/// per byte of the extra words. Empty when the addresses are one contiguous range (`ops[1]`).
|
||||
pub nsa: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Inst {
|
||||
/// The VGPR holding address `k` of an image instruction: `ops[1]` and the ones after it, or,
|
||||
/// in the NSA encoding, the first address in `ops[1]` and the rest from the NSA words.
|
||||
pub fn address(&self, k: usize) -> Option<u16> {
|
||||
let (first, count) = self.ops.get(1)?.vgpr()?;
|
||||
if k == 0 {
|
||||
return Some(first);
|
||||
}
|
||||
if self.nsa.is_empty() {
|
||||
return (k < usize::from(count)).then(|| first + k as u16);
|
||||
}
|
||||
self.nsa.get(k - 1).copied()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -312,14 +436,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);
|
||||
@@ -339,6 +473,7 @@ pub fn decode_one(words: &[u32], at: usize) -> Result<Inst, DecodeError> {
|
||||
};
|
||||
let mut mods = Mods::default();
|
||||
let mut ops = Vec::new();
|
||||
let mut nsa_addresses: Vec<u16> = Vec::new();
|
||||
let mut first_src = 0;
|
||||
let named = |table: Table, format: Format, op: u32| {
|
||||
lookup(table, op as u16).ok_or(DecodeError::UnknownOpcode {
|
||||
@@ -524,47 +659,67 @@ pub fn decode_one(words: &[u32], at: usize) -> Result<Inst, DecodeError> {
|
||||
};
|
||||
let c = count_of(name);
|
||||
let srcs = [bits(w1, 0, 9), bits(w1, 9, 9), bits(w1, 18, 9)];
|
||||
literal_fields = srcs[..nsrc].to_vec();
|
||||
let vop3b = name.starts_with("v_add_co_u32")
|
||||
|| name.starts_with("v_sub_co_u32")
|
||||
|| name.starts_with("v_subrev_co_u32")
|
||||
|| name.starts_with("v_div_scale")
|
||||
|| name.starts_with("v_mad_u64")
|
||||
|| name.starts_with("v_mad_i64")
|
||||
|| name.starts_with("v_add_co_ci")
|
||||
|| name.starts_with("v_sub_co_ci")
|
||||
|| name.starts_with("v_subrev_co_ci");
|
||||
if op < 256 {
|
||||
if !name.starts_with("v_cmpx") {
|
||||
ops.push(sgpr(bits(w, 0, 8), 1));
|
||||
if name.starts_with("v_interp_") {
|
||||
let has_src2 = name != "v_interp_p1ll_f16";
|
||||
literal_fields = if has_src2 {
|
||||
vec![srcs[1], srcs[2]]
|
||||
} else {
|
||||
vec![srcs[1]]
|
||||
};
|
||||
ops.push(vgpr(bits(w, 0, 8), 1));
|
||||
first_src = ops.len();
|
||||
ops.push(source(srcs[1], 1, None));
|
||||
ops.push(Operand::Attr {
|
||||
n: (srcs[0] & 0x3f) as u8,
|
||||
chan: ((srcs[0] >> 6) & 3) as u8,
|
||||
});
|
||||
mods.high = (srcs[0] & 0x100) != 0;
|
||||
if has_src2 {
|
||||
ops.push(source(srcs[2], 1, None));
|
||||
}
|
||||
} else if name.starts_with("v_readlane") {
|
||||
ops.push(sgpr(bits(w, 0, 8), 1));
|
||||
} else {
|
||||
ops.push(vgpr(
|
||||
bits(w, 0, 8),
|
||||
if name.starts_with("v_mad_u64") || name.starts_with("v_mad_i64") {
|
||||
2
|
||||
literal_fields = srcs[..nsrc].to_vec();
|
||||
let vop3b = name.starts_with("v_add_co_u32")
|
||||
|| name.starts_with("v_sub_co_u32")
|
||||
|| name.starts_with("v_subrev_co_u32")
|
||||
|| name.starts_with("v_div_scale")
|
||||
|| name.starts_with("v_mad_u64")
|
||||
|| name.starts_with("v_mad_i64")
|
||||
|| name.starts_with("v_add_co_ci")
|
||||
|| name.starts_with("v_sub_co_ci")
|
||||
|| name.starts_with("v_subrev_co_ci");
|
||||
if op < 256 {
|
||||
if !name.starts_with("v_cmpx") {
|
||||
ops.push(sgpr(bits(w, 0, 8), 1));
|
||||
}
|
||||
} else if name.starts_with("v_readlane") {
|
||||
ops.push(sgpr(bits(w, 0, 8), 1));
|
||||
} else {
|
||||
ops.push(vgpr(
|
||||
bits(w, 0, 8),
|
||||
if name.starts_with("v_mad_u64") || name.starts_with("v_mad_i64") {
|
||||
2
|
||||
} else {
|
||||
c
|
||||
},
|
||||
));
|
||||
if vop3b {
|
||||
ops.push(sgpr(bits(w, 8, 7), 1));
|
||||
}
|
||||
}
|
||||
first_src = ops.len();
|
||||
for (i, &s) in srcs[..nsrc].iter().enumerate() {
|
||||
let cs = if name.starts_with("v_cndmask") && i == 2 {
|
||||
1
|
||||
} else {
|
||||
c
|
||||
},
|
||||
));
|
||||
};
|
||||
ops.push(source(s, cs, None));
|
||||
}
|
||||
if vop3b {
|
||||
ops.push(sgpr(bits(w, 8, 7), 1));
|
||||
mods.abs = 0; // the sdst field overlaps abs/op_sel
|
||||
mods.op_sel = 0;
|
||||
}
|
||||
}
|
||||
first_src = ops.len();
|
||||
for (i, &s) in srcs[..nsrc].iter().enumerate() {
|
||||
let cs = if name.starts_with("v_cndmask") && i == 2 {
|
||||
1
|
||||
} else {
|
||||
c
|
||||
};
|
||||
ops.push(source(s, cs, None));
|
||||
}
|
||||
if vop3b {
|
||||
mods.abs = 0; // the sdst field overlaps abs/op_sel
|
||||
mods.op_sel = 0;
|
||||
}
|
||||
}
|
||||
0x33 => {
|
||||
@@ -699,7 +854,17 @@ pub fn decode_one(words: &[u32], at: usize) -> Result<Inst, DecodeError> {
|
||||
mods.dmask.count_ones().max(1) as u8
|
||||
};
|
||||
ops.push(vgpr(bits(w1, 8, 8), data + u8::from(mods.tfe)));
|
||||
ops.push(vgpr(bits(w1, 0, 8), address_count(name, mods.dim)));
|
||||
let addresses = address_count(name, mods.dim);
|
||||
ops.push(vgpr(bits(w1, 0, 8), addresses));
|
||||
if nsa > 0 {
|
||||
// The addresses after the first are listed one per byte in the NSA words.
|
||||
for k in 0..usize::from(addresses).saturating_sub(1) {
|
||||
if k / 4 >= nsa {
|
||||
return Err(DecodeError::Truncated { at });
|
||||
}
|
||||
nsa_addresses.push(bits(word(2 + k / 4)?, 8 * (k % 4) as u32, 8) as u16);
|
||||
}
|
||||
}
|
||||
ops.push(Operand::Sgpr {
|
||||
n: (bits(w1, 16, 5) * 4) as u16,
|
||||
count: if mods.r128 { 4 } else { 8 },
|
||||
@@ -823,6 +988,11 @@ pub fn decode_one(words: &[u32], at: usize) -> Result<Inst, DecodeError> {
|
||||
len += 1;
|
||||
}
|
||||
}
|
||||
// The marker (249/250/233/234) was decoded as a reserved operand. The real src0, and an
|
||||
// SDWA scalar src1 or a VOPC mask destination, live in the extension word.
|
||||
if let Some(ext) = ext {
|
||||
bind_extension(name, format, ext, &mut ops);
|
||||
}
|
||||
// A source field holding 255 names the 32-bit literal after the instruction.
|
||||
if literal_fields.contains(&LITERAL) {
|
||||
let literal = word(len)?;
|
||||
@@ -847,11 +1017,58 @@ pub fn decode_one(words: &[u32], at: usize) -> Result<Inst, DecodeError> {
|
||||
first_src,
|
||||
mods,
|
||||
ext,
|
||||
nsa: nsa_addresses,
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces the SDWA/DPP marker operand with the source the extension word names.
|
||||
fn bind_extension(name: &str, format: Format, ext: Extension, ops: &mut [Operand]) {
|
||||
let Some(i) = ops
|
||||
.iter()
|
||||
.position(|o| matches!(o, Operand::Special("reserved")))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
match ext {
|
||||
Extension::Sdwa(w) => {
|
||||
if format == Format::Vopc && !name.starts_with("v_cmpx") {
|
||||
ops[0] = match Sdwa::vopc_dst(w) {
|
||||
None => Operand::Special("vcc_lo"),
|
||||
Some(code) => source(code, 1, None),
|
||||
};
|
||||
}
|
||||
let src1 = if bits(w, 31, 1) != 0 {
|
||||
match ops.get(i + 1) {
|
||||
Some(&Operand::Vgpr { n, count: 1 }) => Some(n),
|
||||
_ => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(n) = src1 {
|
||||
ops[i + 1] = source(u32::from(n), 1, None);
|
||||
}
|
||||
let n = w & 0xff;
|
||||
ops[i] = if bits(w, 23, 1) != 0 {
|
||||
source(n, 1, None)
|
||||
} else {
|
||||
Operand::Vgpr {
|
||||
n: n as u16,
|
||||
count: 1,
|
||||
}
|
||||
};
|
||||
}
|
||||
Extension::Dpp(w) => {
|
||||
ops[i] = Operand::Vgpr {
|
||||
n: (w & 0xff) as u16,
|
||||
count: 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Address registers an image instruction reads (non-NSA, 32-bit addresses).
|
||||
fn address_count(name: &str, dim: u8) -> u8 {
|
||||
pub fn address_count(name: &str, dim: u8) -> u8 {
|
||||
let coords: u8 = match dim {
|
||||
0 => 1,
|
||||
1 | 4 => 2,
|
||||
@@ -863,25 +1080,27 @@ fn address_count(name: &str, dim: u8) -> u8 {
|
||||
.trim_start_matches("image_sample")
|
||||
.trim_start_matches("image_gather4");
|
||||
if name.starts_with("image_sample") || name.starts_with("image_gather4") {
|
||||
if suffix.contains("_c") {
|
||||
let parts: Vec<&str> = suffix.split('_').filter(|s| !s.is_empty()).collect();
|
||||
if parts.contains(&"c") {
|
||||
n += 1;
|
||||
}
|
||||
if suffix.contains("_o") {
|
||||
if parts.contains(&"o") {
|
||||
n += 1;
|
||||
}
|
||||
if suffix.contains("_b") || suffix.contains("_l") && !suffix.contains("_lz") {
|
||||
if parts.contains(&"b") || parts.contains(&"l") {
|
||||
n += 1;
|
||||
}
|
||||
if suffix.contains("_cl") {
|
||||
if parts.contains(&"cl") {
|
||||
n += 1;
|
||||
}
|
||||
if suffix.contains("_d") {
|
||||
if parts.contains(&"d") || parts.contains(&"cd") {
|
||||
let grad = match dim {
|
||||
0 | 4 => 1,
|
||||
2 => 3,
|
||||
_ => 2,
|
||||
};
|
||||
n += 2 * grad;
|
||||
let mult = if parts.contains(&"g16") { 1 } else { 2 };
|
||||
n += mult * grad;
|
||||
}
|
||||
} else if name.contains("_mip") {
|
||||
n += 1;
|
||||
@@ -965,6 +1184,15 @@ impl fmt::Display for Inst {
|
||||
};
|
||||
let neg = matches!(self.format, Format::Vop3) && s < 3 && m.neg & (1 << s) != 0;
|
||||
let abs = matches!(self.format, Format::Vop3) && s < 3 && m.abs & (1 << s) != 0;
|
||||
if i == 1 && self.format == Format::Mimg && !self.nsa.is_empty() {
|
||||
// NSA addresses, as LLVM prints them: [v4, v7]
|
||||
write!(f, "[v{}", op.vgpr().map_or(0, |(n, _)| n))?;
|
||||
for v in &self.nsa {
|
||||
write!(f, ", v{v}")?;
|
||||
}
|
||||
f.write_str("]")?;
|
||||
continue;
|
||||
}
|
||||
match (neg, abs) {
|
||||
(true, true) => write!(f, "-|{op}|")?,
|
||||
(true, false) => write!(f, "-{op}")?,
|
||||
@@ -1026,6 +1254,9 @@ impl fmt::Display for Inst {
|
||||
}
|
||||
}
|
||||
Format::Vop3 => {
|
||||
if m.high {
|
||||
f.write_str(" high")?;
|
||||
}
|
||||
if m.clamp {
|
||||
f.write_str(" clamp")?;
|
||||
}
|
||||
@@ -1050,3 +1281,119 @@ impl fmt::Display for Inst {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{address_count, decode};
|
||||
|
||||
#[test]
|
||||
fn address_count_matches_isa() {
|
||||
// Dimensions: 0=1D, 1=2D, 2=3D, 3=CUBE, 4=1D_ARRAY, 5=2D_ARRAY.
|
||||
assert_eq!(address_count("image_sample", 0), 1);
|
||||
assert_eq!(address_count("image_sample", 1), 2);
|
||||
assert_eq!(address_count("image_sample", 2), 3);
|
||||
assert_eq!(address_count("image_sample", 4), 2);
|
||||
assert_eq!(address_count("image_sample", 5), 3);
|
||||
|
||||
// _cl must not double-count _c; _cd is coarse derivatives, not _c.
|
||||
assert_eq!(address_count("image_sample_cl", 1), 3);
|
||||
assert_eq!(address_count("image_sample_c", 1), 3);
|
||||
assert_eq!(address_count("image_sample_c_cl", 1), 4);
|
||||
assert_eq!(address_count("image_sample_l", 1), 3);
|
||||
assert_eq!(address_count("image_sample_lz", 1), 2);
|
||||
assert_eq!(address_count("image_sample_b", 1), 3);
|
||||
assert_eq!(address_count("image_sample_o", 1), 3);
|
||||
assert_eq!(address_count("image_sample_d", 1), 6);
|
||||
assert_eq!(address_count("image_sample_cd", 1), 6);
|
||||
assert_eq!(address_count("image_sample_d", 2), 9);
|
||||
assert_eq!(address_count("image_sample_d", 5), 7);
|
||||
assert_eq!(address_count("image_sample_c_l_o", 1), 5);
|
||||
|
||||
assert_eq!(address_count("image_gather4", 1), 2);
|
||||
assert_eq!(address_count("image_gather4_c", 1), 3);
|
||||
assert_eq!(address_count("image_gather4_c_lz_o", 1), 4);
|
||||
|
||||
assert_eq!(address_count("image_load", 1), 2);
|
||||
assert_eq!(address_count("image_load_mip", 1), 3);
|
||||
assert_eq!(address_count("image_get_lod", 1), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_f16_interpolation() {
|
||||
// Encodings from llvm-mc -arch=amdgcn -mcpu=gfx1030 -show-encoding.
|
||||
let insts = decode(&[
|
||||
0xd7420000, 0x02020400, // v_interp_p1ll_f16 v0, v2, attr0.x
|
||||
0xd7420000, 0x02020541, // v_interp_p1ll_f16 v0, v2, attr1.y high
|
||||
0xd7430000, 0x040e0400, // v_interp_p1lv_f16 v0, v2, attr0.x, v3
|
||||
0xd75a0000, 0x04160400, // v_interp_p2_f16 v0, v2, attr0.x, v5
|
||||
0xbf810000, // s_endpgm
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(insts[0].to_string(), "v_interp_p1ll_f16 v0, v2, attr0.x");
|
||||
assert_eq!(
|
||||
insts[1].to_string(),
|
||||
"v_interp_p1ll_f16 v0, v2, attr1.y high"
|
||||
);
|
||||
assert_eq!(
|
||||
insts[2].to_string(),
|
||||
"v_interp_p1lv_f16 v0, v2, attr0.x, v3"
|
||||
);
|
||||
assert_eq!(insts[3].to_string(), "v_interp_p2_f16 v0, v2, attr0.x, v5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sdwa_and_dpp_words_name_their_sources() {
|
||||
use super::{Dpp8, Dpp16, Extension, Operand, Sdwa};
|
||||
|
||||
// v_add_f32_sdwa v0, v1, v2 clamp mul:2 (llvm-mc, gfx1030).
|
||||
let s = Sdwa::parse(0x0606_7601);
|
||||
assert_eq!(s.dst_sel, 6);
|
||||
assert_eq!(s.dst_unused, 2);
|
||||
assert!(s.clamp);
|
||||
assert_eq!(s.omod, 1);
|
||||
assert!(!s.src0_abs && !s.src0_neg && !s.src0_sext);
|
||||
|
||||
// v_add_f32_sdwa v0, |v1|, -v2.
|
||||
let s = Sdwa::parse(0x1626_1601);
|
||||
assert!(s.src0_abs && !s.src0_neg);
|
||||
assert!(s.src1_neg && !s.src1_abs);
|
||||
|
||||
// v_add_f32_dpp v0, v1, v2 row_shr:1 bound_ctrl:1 (the bit that returns 0).
|
||||
let d = Dpp16::parse(0xff09_1101);
|
||||
assert_eq!(d.ctrl, 0x111);
|
||||
assert!(d.bound_zero);
|
||||
assert!(!d.fi);
|
||||
assert_eq!(d.row_mask, 0xf);
|
||||
assert_eq!(d.bank_mask, 0xf);
|
||||
assert_eq!(d.src0, 1);
|
||||
|
||||
// v_mov_b32_dpp v0, v1 dpp8:[0,1,2,3,4,5,6,7], fi clear (marker 233).
|
||||
let d8 = Dpp8::parse(0xfac6_8801, false);
|
||||
assert_eq!(d8.src0, 1);
|
||||
assert_eq!(d8.sel, 0xfac688);
|
||||
let lanes: Vec<u32> = (0..8).map(|i| (d8.sel >> (3 * i)) & 7).collect();
|
||||
assert_eq!(lanes, vec![0, 1, 2, 3, 4, 5, 6, 7]);
|
||||
|
||||
// The marker operand is replaced by the register the extension word names.
|
||||
let insts = decode(&[0x3600_04f9, 0x0000_1001, 0xbf81_0000]).unwrap();
|
||||
assert!(matches!(insts[0].ext, Some(Extension::Sdwa(_))));
|
||||
assert_eq!(
|
||||
insts[0].ops,
|
||||
vec![
|
||||
Operand::Vgpr { n: 0, count: 1 },
|
||||
Operand::Vgpr { n: 1, count: 1 },
|
||||
Operand::Vgpr { n: 2, count: 1 },
|
||||
]
|
||||
);
|
||||
assert_eq!(insts[0].to_string(), "v_and_b32_sdwa v0, v1, v2");
|
||||
|
||||
// v_add_f32_sdwa v0, s1, v2: src0 is scalar.
|
||||
let insts = decode(&[0x0600_04f9, 0x0686_1601, 0xbf81_0000]).unwrap();
|
||||
assert_eq!(insts[0].ops[1], Operand::Sgpr { n: 1, count: 1 });
|
||||
|
||||
// v_cmp_gt_u32_sdwa s4, sext(v1), v2: the mask destination is s4, not vcc.
|
||||
let insts = decode(&[0x7d88_04f9, 0x060a_8401, 0xbf81_0000]).unwrap();
|
||||
assert_eq!(insts[0].ops[0], Operand::Sgpr { n: 4, count: 1 });
|
||||
assert_eq!(Sdwa::vopc_dst(0x060a_8401), Some(4));
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,10 @@ pub mod opcodes;
|
||||
pub mod translate;
|
||||
|
||||
pub use decode::{Format, Inst, Operand, decode};
|
||||
pub use translate::{Stage, Translation, Unsupported, translate_pair};
|
||||
pub use translate::{
|
||||
RootKind, RootLayout, RootParameter, Stage, Translation, Unsupported, translate_pair,
|
||||
translate_pair_rooted,
|
||||
};
|
||||
|
||||
/// Decodes and translates a VS/PS pair given as console containers or raw code blobs.
|
||||
pub fn translate_blobs(vs: &[u8], ps: &[u8]) -> Result<Translation, Unsupported> {
|
||||
@@ -34,3 +37,17 @@ pub fn translate_blobs(vs: &[u8], ps: &[u8]) -> Result<Translation, Unsupported>
|
||||
let ps = decode(&words(ps, "PS")?).map_err(|e| Unsupported(format!("PS decode: {e}")))?;
|
||||
translate_pair(&vs, &ps)
|
||||
}
|
||||
|
||||
/// As `translate_blobs`, given the layout of the pipeline's root signature.
|
||||
pub fn translate_blobs_rooted(
|
||||
vs: &[u8],
|
||||
ps: &[u8],
|
||||
root: &RootLayout,
|
||||
) -> Result<Translation, Unsupported> {
|
||||
let words = |blob: &[u8], what: &str| {
|
||||
container::code_words(blob).map_err(|e| Unsupported(format!("{what}: {e}")))
|
||||
};
|
||||
let vs = decode(&words(vs, "VS")?).map_err(|e| Unsupported(format!("VS decode: {e}")))?;
|
||||
let ps = decode(&words(ps, "PS")?).map_err(|e| Unsupported(format!("PS decode: {e}")))?;
|
||||
translate_pair_rooted(&vs, &ps, Some(root))
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,15 @@
|
||||
//! The decoder against the public LLVM AMDGPU disassembler: every line of llvm_vectors.txt
|
||||
//! (generated by scripts/console-shader/gen_llvm_vectors.py) gives instruction words and the
|
||||
//! text llvm-mc prints for them. Decoding the words must give the same text and consume exactly
|
||||
//! those words.
|
||||
//! text llvm-mc prints for them. Decoding the words must give the same text (up to runs of
|
||||
//! spaces) and consume exactly those words.
|
||||
|
||||
use gfx10_translate::decode::decode_one;
|
||||
|
||||
/// The same text, up to runs of spaces.
|
||||
fn same_text(a: &str, b: &str) -> bool {
|
||||
a.split_whitespace().eq(b.split_whitespace())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_matches_llvm() {
|
||||
let mut failures = Vec::new();
|
||||
@@ -25,7 +30,8 @@ fn decoder_matches_llvm() {
|
||||
inst.words.len(),
|
||||
words.len()
|
||||
)),
|
||||
Ok(inst) if inst.to_string() != expected => {
|
||||
// llvm-mc prints two spaces after the mnemonic of an NSA image instruction.
|
||||
Ok(inst) if !same_text(&inst.to_string(), expected) => {
|
||||
failures.push(format!("{expected}\n got: {inst}"))
|
||||
}
|
||||
Ok(_) => {}
|
||||
|
||||
@@ -115,6 +115,8 @@ e8eb2008 80000004 | tbuffer_load_format_xyzw v[0:3], v4, s[0:3], 0 format:[BUF_F
|
||||
f0800f08 00820004 | image_sample v[0:3], v[4:5], s[8:15], s[16:19] dmask:0xf dim:SQ_RSRC_IMG_2D
|
||||
f0800808 00820004 | image_sample v0, v[4:5], s[8:15], s[16:19] dmask:0x8 dim:SQ_RSRC_IMG_2D
|
||||
f09c0308 00820002 | image_sample_lz v[0:1], v[2:3], s[8:15], s[16:19] dmask:0x3 dim:SQ_RSRC_IMG_2D
|
||||
f080010a 01250304 00000007 | image_sample v3, [v4, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D
|
||||
f09c0712 00820004 00000209 | image_sample_lz v[0:2], [v4, v9, v2], s[8:15], s[16:19] dmask:0x7 dim:SQ_RSRC_IMG_3D
|
||||
f80008cf 03020100 | exp pos0, v0, v1, v2, v3 done
|
||||
f800180f 03020100 | exp mrt0, v0, v1, v2, v3 done vm
|
||||
f8000001 00000000 | exp mrt0, v0, off, off, off
|
||||
|
||||
@@ -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,266 @@ 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 mul:4 and div:2. omod is applied to the result, before clamp.
|
||||
let t = hlsl("d5030000 12020501").unwrap();
|
||||
assert!(
|
||||
t.contains(" v0 = asuint((asfloat(v1) + asfloat(v2)) * 4.0f);\n"),
|
||||
"{t}"
|
||||
);
|
||||
let t = hlsl("d5030000 1a020501").unwrap();
|
||||
assert!(
|
||||
t.contains(" v0 = asuint((asfloat(v1) + asfloat(v2)) * 0.5f);\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}");
|
||||
}
|
||||
|
||||
/// SDWA and DPP (#719). Instruction words are `llvm-mc -arch=amdgcn -mcpu=gfx1030 -show-encoding`.
|
||||
/// The HLSL is the RDNA 2 definition: SDWA selects a byte or word, sign- or zero-extends it,
|
||||
/// then runs the operation, then writes that slice back (pad, sign-extend, or preserve). DPP16
|
||||
/// reads src0 from another lane in the quad or in the row of 16; an out-of-row shift reads 0
|
||||
/// when bound control is set, and leaves the destination unchanged when it is clear. DPP8 reads
|
||||
/// within a group of 8.
|
||||
#[test]
|
||||
fn sdwa_and_dpp_forms() {
|
||||
let line = |inst: &str, stmt: &str| {
|
||||
let h = pixel_hlsl(&format!("{inst} f8000801 00000000 bf810000"));
|
||||
assert!(h.contains(stmt), "missing `{stmt}` in\n{h}");
|
||||
};
|
||||
|
||||
// v_and_b32_sdwa v0, v1, v2 dst_sel:BYTE_0 dst_unused:UNUSED_PRESERVE src0_sel:BYTE_0 src1_sel:BYTE_0
|
||||
line(
|
||||
"360004f9 00001001",
|
||||
"v0 = ((v0 & 0xffffff00u) | (((v1 & 0xffu) & (v2 & 0xffu)) & 0xffu));",
|
||||
);
|
||||
// v_and_b32_sdwa v0, sext(v1), sext(v2) src0_sel:BYTE_0 src1_sel:BYTE_1 (dest is the whole dword)
|
||||
line(
|
||||
"360004f9 09081601",
|
||||
"v0 = ((uint)(((int)((v1 & 0xffu) << 24)) >> 24) & (uint)(((int)(((v2 >> 8) & 0xffu) << 24)) >> 24));",
|
||||
);
|
||||
// v_mov_b32_sdwa v0, v1 dst_sel:WORD_1 dst_unused:UNUSED_PAD src0_sel:WORD_0
|
||||
line(
|
||||
"7e0002f9 00040501",
|
||||
"v0 = (((v1 & 0xffffu) & 0xffffu) << 16);",
|
||||
);
|
||||
// v_mov_b32_sdwa v0, sext(v1) dst_sel:DWORD src0_sel:BYTE_3
|
||||
line(
|
||||
"7e0002f9 000b0601",
|
||||
"v0 = (uint)(((int)(((v1 >> 24) & 0xffu) << 24)) >> 24);",
|
||||
);
|
||||
// v_add_f32_sdwa v0, v1, v2 clamp mul:2
|
||||
line(
|
||||
"060004f9 06067601",
|
||||
"v0 = asuint(saturate((asfloat(v1) + asfloat(v2)) * 2.0f));",
|
||||
);
|
||||
// v_add_f32_sdwa v0, |v1|, -v2
|
||||
line(
|
||||
"060004f9 16261601",
|
||||
"v0 = asuint(asfloat((asuint(abs(asfloat(v1))))) + asfloat((asuint(-asfloat(v2)))));",
|
||||
);
|
||||
// v_add_f32_sdwa v0, s1, v2 and v0, v1, 2 and v0, 1.0, v2
|
||||
line(
|
||||
"060004f9 06861601",
|
||||
"v0 = asuint(asfloat(s1) + asfloat(v2));",
|
||||
);
|
||||
line(
|
||||
"060104f9 86061601",
|
||||
"v0 = asuint(asfloat(v1) + asfloat(2u));",
|
||||
);
|
||||
line(
|
||||
"060004f9 068616f2",
|
||||
"v0 = asuint(asfloat(asuint(1.0f)) + asfloat(v2));",
|
||||
);
|
||||
// v_add_f32_sdwa v0, v1, v2 dst_sel:BYTE_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:BYTE_0
|
||||
line(
|
||||
"060004f9 00000901",
|
||||
"v0 = ((uint)(((int)((asuint(asfloat((v1 & 0xffu)) + asfloat((v2 & 0xffu))) & 0xffu) << 24)) >> 24) << 8);",
|
||||
);
|
||||
|
||||
// v_add_f32_dpp v0, v1, v2 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf
|
||||
// Each pair of bits of 0xe4 is the source lane inside the group of 4.
|
||||
line(
|
||||
"060004fa ff00e401",
|
||||
"v0 = asuint(asfloat(WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~3u) + ((0xe4u >> ((WaveGetLaneIndex() & 3u) << 1)) & 3u))) + asfloat(v2));",
|
||||
);
|
||||
// quad_perm:[1,0,3,2] is 0xb1.
|
||||
line(
|
||||
"060004fa ff00b101",
|
||||
"((0xb1u >> ((WaveGetLaneIndex() & 3u) << 1)) & 3u)",
|
||||
);
|
||||
// |v1| is applied to the lane that was read.
|
||||
line(
|
||||
"060004fa ff20e401",
|
||||
"asfloat((asuint(abs(asfloat(WaveReadLaneAt(v1,",
|
||||
);
|
||||
// row_shr:1 with bound control set: a lane in the first column of its row of 16 reads 0.
|
||||
line(
|
||||
"060004fa ff091101",
|
||||
"v0 = asuint(asfloat((((WaveGetLaneIndex() & 15u) >= 1u) ? WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~15u) + ((WaveGetLaneIndex() & 15u) - (((WaveGetLaneIndex() & 15u) >= 1u) ? 1u : 0u))) : 0u)) + asfloat(v2));",
|
||||
);
|
||||
// The same shift with bound control clear disables the write. v0 keeps its old value,
|
||||
// which is not the lane's own source v1.
|
||||
line(
|
||||
"060004fa ff011101",
|
||||
"v0 = (((WaveGetLaneIndex() & 15u) >= 1u)) ? (asuint(asfloat(WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~15u) + ((WaveGetLaneIndex() & 15u) - (((WaveGetLaneIndex() & 15u) >= 1u) ? 1u : 0u)))) + asfloat(v2))) : v0;",
|
||||
);
|
||||
// v_mov_b32_dpp v1, v0 row_shr:1 row_mask:0xf bank_mask:0xf, bound control clear.
|
||||
// The destination is v1 and the source is v0, so keeping v1 is not a read of v0.
|
||||
line(
|
||||
"7e0202fa ff011100",
|
||||
"v1 = (((WaveGetLaneIndex() & 15u) >= 1u)) ? (WaveReadLaneAt(v0, (WaveGetLaneIndex() & ~15u) + ((WaveGetLaneIndex() & 15u) - (((WaveGetLaneIndex() & 15u) >= 1u) ? 1u : 0u)))) : v1;",
|
||||
);
|
||||
// row_shr:1 row_mask:0xf bank_mask:0x1, bound control clear. Bank 0 is lanes 0-3 of the
|
||||
// row and the same bank of the next row (16-19). Lanes 4, 8 and 12 are the old reading
|
||||
// of `lane & 3` and stay inactive. An out-of-row source keeps v0.
|
||||
line(
|
||||
"060004fa f1011101",
|
||||
"v0 = (((0xfu >> (WaveGetLaneIndex() >> 4)) & 1u) != 0u && ((0x1u >> ((WaveGetLaneIndex() >> 2) & 3u)) & 1u) != 0u && ((WaveGetLaneIndex() & 15u) >= 1u)) ? (asuint(asfloat(WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~15u) + ((WaveGetLaneIndex() & 15u) - (((WaveGetLaneIndex() & 15u) >= 1u) ? 1u : 0u)))) + asfloat(v2))) : v0;",
|
||||
);
|
||||
let bank0: Vec<u32> = (0..32u32)
|
||||
.filter(|&lane| (0x1u32 >> ((lane >> 2) & 3)) & 1 == 1)
|
||||
.collect();
|
||||
assert_eq!(bank0, [0, 1, 2, 3, 16, 17, 18, 19]);
|
||||
// row_shl:4 row_mask:0x3 bank_mask:0xf. A disabled row or bank keeps the old destination.
|
||||
// bank_mask 0xf is every bank under `(lane >> 2) & 3` as well. Bound control is clear, so
|
||||
// a shift that leaves the row also keeps v0.
|
||||
line(
|
||||
"060004fa 3f010401",
|
||||
"v0 = (((0x3u >> (WaveGetLaneIndex() >> 4)) & 1u) != 0u && ((0xfu >> ((WaveGetLaneIndex() >> 2) & 3u)) & 1u) != 0u && (((WaveGetLaneIndex() & 15u) + 4u) < 16u)) ? (asuint(asfloat(WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~15u) + ((WaveGetLaneIndex() & 15u) + ((((WaveGetLaneIndex() & 15u) + 4u) < 16u) ? 4u : 0u)))) + asfloat(v2))) : v0;",
|
||||
);
|
||||
// row_ror:2, row_mirror, row_half_mirror, row_share:3, row_xmask:5. None of these leaves the row.
|
||||
line(
|
||||
"060004fa ff012201",
|
||||
"WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~15u) + ((WaveGetLaneIndex() + 14u) & 15u))",
|
||||
);
|
||||
line(
|
||||
"060004fa ff014001",
|
||||
"WaveReadLaneAt(v1, WaveGetLaneIndex() ^ 15u)",
|
||||
);
|
||||
line(
|
||||
"060004fa ff014101",
|
||||
"WaveReadLaneAt(v1, WaveGetLaneIndex() ^ 7u)",
|
||||
);
|
||||
line(
|
||||
"060004fa ff015301",
|
||||
"WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~15u) + 3u)",
|
||||
);
|
||||
line(
|
||||
"060004fa ff016501",
|
||||
"WaveReadLaneAt(v1, WaveGetLaneIndex() ^ 5u)",
|
||||
);
|
||||
// v_mov_b32_dpp v0, v1 dpp8:[0,1,2,3,4,5,6,7]
|
||||
// Selectors are 3-bit fields, lane 0 in the low bits of 0xfac688.
|
||||
line(
|
||||
"7e0002e9 fac68801",
|
||||
"v0 = WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~7u) + ((0xfac688u >> ((WaveGetLaneIndex() & 7u) * 3u)) & 7u));",
|
||||
);
|
||||
// dpp8:[7,6,5,4,3,2,1,0] fi:1. In straight-line code every lane is active, so fi does not
|
||||
// change the read; the selectors are 0x53977.
|
||||
line(
|
||||
"7e0002ea 05397701",
|
||||
"v0 = WaveReadLaneAt(v1, (WaveGetLaneIndex() & ~7u) + ((0x53977u >> ((WaveGetLaneIndex() & 7u) * 3u)) & 7u));",
|
||||
);
|
||||
|
||||
// v_cmp_lt_f32_sdwa vcc_lo, v1, v2 src0_sel:BYTE_0 src1_sel:WORD_0
|
||||
let h = pixel_hlsl("7c0204f9 04000001 f8000801 00000000 bf810000");
|
||||
assert!(
|
||||
h.contains("vcc = exec && (asfloat((v1 & 0xffu)) < asfloat((v2 & 0xffffu)));"),
|
||||
"{h}"
|
||||
);
|
||||
// v_cmp_gt_u32_sdwa s4, sext(v1), v2 src0_sel:BYTE_2 src1_sel:DWORD
|
||||
let h = pixel_hlsl("7d8804f9 060a8401 f8000801 00000000 bf810000");
|
||||
assert!(
|
||||
h.contains("m4 = exec && ((uint)(((int)(((v1 >> 16) & 0xffu) << 24)) >> 24) > v2);"),
|
||||
"{h}"
|
||||
);
|
||||
|
||||
// v_fma_mixlo_f16 v0, v1, v2, v3 op_sel:[1,0,0] op_sel_hi:[1,0,0]
|
||||
// op_sel_hi says src0 is f16; op_sel says that f16 is the high half.
|
||||
line(
|
||||
"cc210800 0c0e0501",
|
||||
"v0 = (v0 & 0xffff0000u) | f32tof16(mad(f16tof32((v1 >> 16) & 0xffffu), asfloat(v2), asfloat(v3)));",
|
||||
);
|
||||
// clamp saturates the f32 mad, then the low half is packed.
|
||||
line(
|
||||
"cc218000 0c0e0501",
|
||||
"v0 = (v0 & 0xffff0000u) | f32tof16(saturate(mad(f16tof32(v1 & 0xffffu), asfloat(v2), asfloat(v3))));",
|
||||
);
|
||||
// v_fma_mixhi_f16 v0, v1, v2, v3 op_sel:[0,1,0] op_sel_hi:[0,1,0]
|
||||
line(
|
||||
"cc221000 140e0501",
|
||||
"v0 = (v0 & 0xffffu) | (f32tof16(mad(asfloat(v1), f16tof32((v2 >> 16) & 0xffffu), asfloat(v3))) << 16);",
|
||||
);
|
||||
}
|
||||
|
||||
/// Patterns the ISA leaves reserved, or that this translator does not model, are refused
|
||||
/// rather than translated as the unmodified operation. The SDWA/DPP words that llvm-mc will
|
||||
/// not assemble (selector 7, `row_bcast`, a VOPC DPP) are the llvm-mc encoding of a legal
|
||||
/// neighbour with that one field replaced.
|
||||
#[test]
|
||||
fn refuses_unmodeled_sdwa_and_dpp() {
|
||||
// v_and_b32_sdwa v0, v1, v2 clamp: integer clamp is saturating arithmetic.
|
||||
let err = refusal(Stage::Pixel, "360004f9 06063601 bf810000").unwrap();
|
||||
assert!(err.starts_with("modifier in"), "{err}");
|
||||
// The byte-preserve AND with src0_sel forced to the reserved value 7.
|
||||
let err = refusal(Stage::Pixel, "360004f9 00071001 bf810000").unwrap();
|
||||
assert!(err.starts_with("unmodeled SDWA selector"), "{err}");
|
||||
// abs on an integer SDWA source (src0_abs set on the same AND).
|
||||
let err = refusal(Stage::Pixel, "360004f9 00201001 bf810000").unwrap();
|
||||
assert!(err.starts_with("modifier in"), "{err}");
|
||||
// row_shr:1 with dpp_ctrl replaced by 0x142 (row_bcast:15), which gfx1030 will not assemble.
|
||||
let err = refusal(Stage::Pixel, "060004fa ff014201 bf810000").unwrap();
|
||||
assert!(err.starts_with("unmodeled DPP control"), "{err}");
|
||||
// The same word with dpp_ctrl 0x138 (wave_shr:1). Wave-wide DPP is already refused here,
|
||||
// with row_bcast: `dpp16_kind` leaves it unset. A 64-lane wave is not a second path.
|
||||
let err = refusal(Stage::Pixel, "060004fa ff013801 bf810000").unwrap();
|
||||
assert!(err.starts_with("unmodeled DPP control"), "{err}");
|
||||
// v_cmp_lt_f32_sdwa's encoding with the SDWA marker replaced by the DPP16 marker.
|
||||
let err = refusal(Stage::Pixel, "7c0204fa ff00e401 bf810000").unwrap();
|
||||
assert!(err.starts_with("DPP form of"), "{err}");
|
||||
// v_fma_mixlo_f16 v0, v1, v2, v3 op_sel:[1,0,0] and op_sel_hi all clear: src0 stays f32.
|
||||
let err = refusal(Stage::Pixel, "cc210800 040e0501 bf810000").unwrap();
|
||||
assert!(err.starts_with("op_sel on a 32-bit source"), "{err}");
|
||||
}
|
||||
|
||||
/// Integer, conversion and lane instructions (#716). Encodings from llvm-mc (gfx1030); each
|
||||
/// expected line follows the instruction's ISA definition.
|
||||
#[test]
|
||||
@@ -228,3 +477,578 @@ 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");
|
||||
}
|
||||
|
||||
/// image_sample_lz on a 3D texture (#718). MIMG `dim` 2 is SQ_RSRC_IMG_3D; a 3D sample reads
|
||||
/// three address registers, the normalized coordinates s, t and r, and `_lz` samples mip level 0
|
||||
/// (RDNA 2 ISA, MIMG). In HLSL that is `Texture3D.SampleLevel(sampler, float3, 0)`. A 2D sample of
|
||||
/// another texture in the same shader keeps its form. Textures come from root table 0 entries 1
|
||||
/// and 2. Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn image_samples_on_3d_textures() {
|
||||
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_sample_lz v[0:2], v[4:6], s[28:35], s[36:39] dmask:0x7 dim:SQ_RSRC_IMG_3D;
|
||||
// image_sample v3, v[4:5], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D;
|
||||
// exp mrt0, v0, v1, v2, v3 done; s_endpgm
|
||||
let ps = decode(&words(
|
||||
"f40c0504 fa000020 f40c0704 fa000040 f09c0710 01270004 f0800108 01250304 f800080f 03020100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.ps_hlsl;
|
||||
assert!(
|
||||
h.contains("Texture3D<float4> tex2 : register(t2, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("Texture2D<float4> tex1 : register(t1, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains(
|
||||
"{ float4 r = tex2.SampleLevel(smp0, float3(asfloat(v4), asfloat(v5), asfloat(v6)), 0);"
|
||||
),
|
||||
"{h}"
|
||||
);
|
||||
assert!(h.contains(" v0 = asuint(r.x);"), "{h}");
|
||||
assert!(h.contains(" v2 = asuint(r.z);"), "{h}");
|
||||
assert!(
|
||||
h.contains("{ float4 r = tex1.Sample(smp0, float2(asfloat(v4), asfloat(v5)));"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(h.contains(" v3 = asuint(r.x);"), "{h}");
|
||||
assert_eq!(t.layout, "FETCH 1\nUSE TEX 1\nUSE TEX 2\n");
|
||||
}
|
||||
|
||||
/// Image instructions in the NSA (non-sequential address) encoding. MIMG with NSA set lists the
|
||||
/// address VGPRs after the first one byte each in extra words, so the addresses need not be
|
||||
/// consecutive registers (RDNA 2 ISA, MIMG NSA). A 3D sample reads s, t, r from v4, v9, v6; a 2D
|
||||
/// sample and a gather read s, t from v4, v7 and v5, v7, not from v[4:5] or v[5:6]. Encodings from
|
||||
/// llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn image_instructions_read_nsa_addresses() {
|
||||
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_sample_lz v[0:2], [v4, v9, v6], s[28:35], s[36:39] dmask:0x7 dim:SQ_RSRC_IMG_3D;
|
||||
// image_sample v3, [v4, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D;
|
||||
// image_gather4_lz v[8:11], [v5, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D;
|
||||
// exp mrt0, v0, v1, v2, v3 done; s_endpgm
|
||||
let ps = decode(&words(
|
||||
"f40c0504 fa000020 f40c0704 fa000040 f09c0712 01270004 00000609 f080010a 01250304 00000007 \
|
||||
f11c010a 01250805 00000007 f800080f 03020100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ps[3].to_string(),
|
||||
"image_sample v3, [v4, v7], s[20:27], s[36:39] dmask:0x1 dim:SQ_RSRC_IMG_2D"
|
||||
);
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.ps_hlsl;
|
||||
assert!(
|
||||
h.contains(
|
||||
"{ float4 r = tex2.SampleLevel(smp0, float3(asfloat(v4), asfloat(v9), asfloat(v6)), 0);"
|
||||
),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("{ float4 r = tex1.Sample(smp0, float2(asfloat(v4), asfloat(v7)));"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("{ float4 r = tex1.GatherRed(smp0, float2(asfloat(v5), asfloat(v7)));"),
|
||||
"{h}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Sample forms still outside the model are refused, not translated as 2D: a cube map, and 16-bit
|
||||
/// (a16) addresses. Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn refuses_cube_and_a16_samples() {
|
||||
// s_load_dwordx8 s[20:27], s[8:9], 0x20;
|
||||
// image_sample_lz v[0:3], v[4:6], s[20:27], s[36:39] dmask:0xf dim:SQ_RSRC_IMG_CUBE; s_endpgm
|
||||
assert!(refusal(Stage::Pixel, "f40c0504 fa000020 f09c0f18 01250004 bf810000").is_some());
|
||||
// image_sample_lz v[0:2], v[4:5], s[20:27], s[36:39] dmask:0x7 dim:SQ_RSRC_IMG_3D a16
|
||||
assert!(refusal(Stage::Pixel, "f40c0504 fa000020 f09c0710 41250004 bf810000").is_some());
|
||||
}
|
||||
|
||||
/// 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}");
|
||||
}
|
||||
|
||||
// ---- Root signature layouts (#715) ---------------------------------------------------------
|
||||
// The layout rules are measured in docs/research/console-shader-abi.md ("Graphics stages"): root
|
||||
// arguments are packed 32-bit values in parameter order (table pointer 1, root CBV/SRV/UAV 2,
|
||||
// constants 1 each); value d is s(8 + d), or byte 4 * d of root data addressed through s0 and the
|
||||
// low byte of s1. The programs below are our own assembly (llvm-mc, gfx1030), not compiler
|
||||
// output; the expected lines follow from those rules and each program's comments.
|
||||
|
||||
use gfx10_translate::{RootKind, RootLayout, RootParameter, translate_pair_rooted};
|
||||
|
||||
/// A table, a root SRV at t3 space 2, two constants at b1 space 0, a root CBV at b2 space 1.
|
||||
fn mixed_layout(memory_based: bool) -> RootLayout {
|
||||
let p = |kind, values, register, space| RootParameter {
|
||||
kind,
|
||||
values,
|
||||
register,
|
||||
space,
|
||||
};
|
||||
RootLayout {
|
||||
parameters: vec![
|
||||
p(RootKind::Table, 0, 0, 0),
|
||||
p(RootKind::Srv, 0, 3, 2),
|
||||
p(RootKind::Constants, 2, 1, 0),
|
||||
p(RootKind::Cbv, 0, 2, 1),
|
||||
],
|
||||
memory_based,
|
||||
}
|
||||
}
|
||||
|
||||
/// v_mov_b32 v0, 1.0 ; exp mrt0 v0, v0, v0, v0 done vm ; s_endpgm
|
||||
const FLAT_PS: &str = "7e0002f2 f800180f 00000000 bf810000";
|
||||
|
||||
// Root values: 0 table pointer (s8); 1, 2 SRV address (s9, s10); 3, 4 constants (s11, s12);
|
||||
// 5, 6 CBV address (s13, s14).
|
||||
// s0 = s9 ; s1 = s10 | (16 << 16) ; s2 = -1 ; s3 = 0x11014fac the SRV's descriptor, stride 16
|
||||
// buffer_load_dwordx4 v[0:3], v0, s[0:3], 0 idxen element v0 (the vertex index)
|
||||
// s4 = s13 ; s5 = s14 | (16 << 16) ; s6 = -1 ; s7 = 0x11014fac the CBV's descriptor
|
||||
// s_buffer_load_dwordx4 s[4:7], s[4:7], 0x10 its bytes 16..31
|
||||
// s9 = 0 ; s_load_dwordx4 s[16:19], s[8:9], 0x20 entry 1 of the table
|
||||
// s_buffer_load_dwordx4 s[16:19], s[16:19], 0
|
||||
// v0 *= s11 ; v1 *= s12 ; v2 += s4 ; v3 += s16 ; exp pos0 ; s_endpgm
|
||||
const REGISTER_FORM_VS: &str = "be800309 8801ff0a 00100000 be8203c1 be8303ff 11014fac e0382000 80000000 be84030d 8805ff0e 00100000 \
|
||||
be8603c1 be8703ff 11014fac f4280102 fa000010 be890380 f4080404 fa000020 f4280408 fa000000 1000000b 1002020c 06040404 06060610 \
|
||||
f80008cf 03020100 bf810000";
|
||||
|
||||
#[test]
|
||||
fn root_layout_register_form() {
|
||||
let vs = decode(&words(REGISTER_FORM_VS)).unwrap();
|
||||
let ps = decode(&words(FLAT_PS)).unwrap();
|
||||
let t = translate_pair_rooted(&vs, &ps, Some(&mixed_layout(false)))
|
||||
.unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.vs_hlsl;
|
||||
let has = |line: &str| assert!(h.contains(line), "missing `{line}` in\n{h}");
|
||||
// Each root parameter at the title's own register and space; the table in space 100 + 0.
|
||||
has("ByteAddressBuffer rootbuf1 : register(t3, space2);");
|
||||
has("cbuffer ROOTC2 : register(b1, space0) { uint rootc2_0; uint rootc2_1; };");
|
||||
has("cbuffer ROOTCB3 : register(b2, space1) { uint4 rootcb3[4096]; };");
|
||||
has("cbuffer CB1 : register(b1, space100) { uint4 cb1[4096]; };");
|
||||
// The SRV read: element v0 of 16 bytes, and v0 on entry is the vertex index.
|
||||
has("uint vertex_id : SV_VertexID");
|
||||
has("uint v0 = vertex_id;");
|
||||
has("rootbuf1.Load((v0 * 16u + 0u) + 0u)");
|
||||
has("rootbuf1.Load((v0 * 16u + 0u) + 12u)");
|
||||
// The CBV read at byte 16, the constants in their registers, the table entry.
|
||||
has("s4 = rootcb3_word(((16u) >> 2) + 0u);");
|
||||
has("uint s11 = rootc2_0;");
|
||||
has("uint s12 = rootc2_1;");
|
||||
has("s16 = cb1_word(0);");
|
||||
assert_eq!(t.layout, "USE CB 1\nUSE ROOT 1\nUSE ROOT 2\nUSE ROOT 3\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_layout_decides_what_a_register_holds() {
|
||||
let vs = decode(&words(REGISTER_FORM_VS)).unwrap();
|
||||
let ps = decode(&words(FLAT_PS)).unwrap();
|
||||
// Without a layout every parameter is taken for a table, and this shader is refused.
|
||||
assert!(translate_pair(&vs, &ps).is_err());
|
||||
// With a layout in which s9 is a table pointer, building a buffer from it is refused too.
|
||||
let p = |kind| RootParameter {
|
||||
kind,
|
||||
values: 0,
|
||||
register: 0,
|
||||
space: 0,
|
||||
};
|
||||
let tables = RootLayout {
|
||||
parameters: vec![p(RootKind::Table); 7],
|
||||
memory_based: false,
|
||||
};
|
||||
assert!(translate_pair_rooted(&vs, &ps, Some(&tables)).is_err());
|
||||
// A shader that reads past the root signature is refused: here s9 and s10 are beyond a
|
||||
// signature of one table.
|
||||
let short = RootLayout {
|
||||
parameters: vec![p(RootKind::Table)],
|
||||
memory_based: false,
|
||||
};
|
||||
assert!(translate_pair_rooted(&vs, &ps, Some(&short)).is_err());
|
||||
}
|
||||
|
||||
// The same parameters with the root data in memory:
|
||||
// s3 = s1 & 0xff ; s2 = s0 the address of the root data
|
||||
// s_load_dwordx2 s[10:11], s[2:3], 0x4 values 1, 2: the SRV address
|
||||
// s_load_dwordx2 s[8:9], s[2:3], 0xc values 3, 4: the constants
|
||||
// s_load_dword s6, s[2:3], 0 ; s7 = 0 value 0: the table pointer
|
||||
// s0 = s10 ; s1 = s11 | (4 << 16) ; s2 = -1 ; s3 = 0x11014fac the SRV's descriptor, stride 4
|
||||
// buffer_load_dword v0, v0, s[0:3], 0 idxen
|
||||
// s_load_dwordx4 s[16:19], s[6:7], 0x40 entry 2 of the table
|
||||
// s_buffer_load_dword s16, s[16:19], 0
|
||||
// v1 = s8 * v0 ; v2 = s9 * v0 ; v3 = s16 ; exp pos0 ; s_endpgm
|
||||
const MEMORY_FORM_VS: &str = "8703ff01 000000ff be820300 f4040281 fa000004 f4040201 fa00000c f4000181 fa000000 be870380 be80030a \
|
||||
8801ff0b 00040000 be8203c1 be8303ff 11014fac e0302000 80000000 f4080403 fa000040 f4200408 fa000000 10020008 10040009 7e060210 \
|
||||
f80008cf 03020100 bf810000";
|
||||
|
||||
#[test]
|
||||
fn root_layout_memory_form() {
|
||||
let vs = decode(&words(MEMORY_FORM_VS)).unwrap();
|
||||
let ps = decode(&words(FLAT_PS)).unwrap();
|
||||
let t = translate_pair_rooted(&vs, &ps, Some(&mixed_layout(true)))
|
||||
.unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.vs_hlsl;
|
||||
let has = |line: &str| assert!(h.contains(line), "missing `{line}` in\n{h}");
|
||||
has("ByteAddressBuffer rootbuf1 : register(t3, space2);");
|
||||
has("cbuffer ROOTC2 : register(b1, space0) { uint rootc2_0; uint rootc2_1; };");
|
||||
has("cbuffer CB2 : register(b2, space100) { uint4 cb2[4096]; };");
|
||||
// The constants are assigned where they are loaded, not on entry: s8 and s9 are ordinary
|
||||
// registers in this form.
|
||||
has("s8 = rootc2_0;");
|
||||
has("s9 = rootc2_1;");
|
||||
assert!(!h.contains("uint s8 = rootc2_0;"), "{h}");
|
||||
has("rootbuf1.Load((v0 * 4u + 0u) + 0u)");
|
||||
has("s16 = cb2_word(0);");
|
||||
assert_eq!(t.layout, "USE CB 2\nUSE ROOT 1\nUSE ROOT 2\n");
|
||||
// Read as the register form, the same code loads from s0 as from the vertex-buffer table
|
||||
// and is refused.
|
||||
assert!(translate_pair_rooted(&vs, &ps, Some(&mixed_layout(false))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_buffer_byte_offsets_and_the_vertex_index() {
|
||||
// One root SRV at t5 (s8, s9), a byte-addressed buffer (stride 1):
|
||||
// s0 = s8 ; s1 = s9 | (1 << 16) ; s2 = -1 ; s3 = 0x11014fac
|
||||
// v1 = v0 + v0 v0 on entry: the vertex index
|
||||
// buffer_load_dwordx3 v[1:3], v1, s[0:3], 8 offen offset:4
|
||||
// three dwords at byte v1 + 8 + 4: the
|
||||
// scalar offset operand and the immediate
|
||||
// v4 = 1.0 ; exp pos0, v1, v2, v3, v4 done ; s_endpgm
|
||||
let vs = decode(&words(
|
||||
"be800308 8801ff09 00010000 be8203c1 be8303ff 11014fac 4a020100 e03c1004 88000101 7e0802f2 f80008cf 04030201 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let ps = decode(&words(FLAT_PS)).unwrap();
|
||||
let layout = RootLayout {
|
||||
parameters: vec![RootParameter {
|
||||
kind: RootKind::Srv,
|
||||
values: 0,
|
||||
register: 5,
|
||||
space: 0,
|
||||
}],
|
||||
memory_based: false,
|
||||
};
|
||||
let t = translate_pair_rooted(&vs, &ps, Some(&layout)).unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.vs_hlsl;
|
||||
assert!(
|
||||
h.contains("ByteAddressBuffer rootbuf0 : register(t5, space0);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("VSOut main(uint vertex_id : SV_VertexID)"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(h.contains("uint v0 = vertex_id;"), "{h}");
|
||||
assert!(h.contains("v1 = v0 + v0;"), "{h}");
|
||||
assert!(h.contains("rootbuf0.Load((v1 + 8u + 4u) + 0u)"), "{h}");
|
||||
assert!(h.contains("rootbuf0.Load((v1 + 8u + 4u) + 8u)"), "{h}");
|
||||
assert_eq!(t.layout, "USE ROOT 0\n");
|
||||
}
|
||||
|
||||
/// image_sample_l, image_sample_b, and image_sample_o on 1D and 1D_ARRAY textures (#718).
|
||||
/// Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn image_sample_forms_and_dimensions() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
let ps = decode(&words(
|
||||
"f40c0504 fa000020 f40c0704 fa000040 7e0602ff 00000201 f0900100 01250004 f0940120 01270104 f0c00100 01250203 f800080f 00020100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.ps_hlsl;
|
||||
assert!(
|
||||
h.contains("Texture1D<float4> tex1 : register(t1, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("Texture1DArray<float4> tex2 : register(t2, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("tex1.SampleLevel(smp0, asfloat(v4), asfloat(v5))"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("tex2.SampleBias(smp0, float2(asfloat(v5), asfloat(v6)), asfloat(v4))"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(h.contains("tex1.Sample(smp0, asfloat(v4), 1)"), "{h}");
|
||||
}
|
||||
|
||||
/// image_sample_d, image_load_mip, image_gather4_o, and refusal of comparison (_c) forms (#718).
|
||||
/// Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn image_sample_grad_load_mip_and_gather() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
let ps = decode(&words(
|
||||
"f40c0504 fa000020 f40c0704 fa000040 7e0402ff 00000102 f0880108 01250104 f0040108 00050a04 f1400128 01070c02 f800080f 0c0a0100 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("Texture2DArray<float4> tex2 : register(t2, space100);"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(!h.contains("smpc0"), "{h}");
|
||||
assert!(
|
||||
h.contains("tex1.SampleGrad(smp0, float2(asfloat(v8), asfloat(v9)), float2(asfloat(v4), asfloat(v5)), float2(asfloat(v6), asfloat(v7)))"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains("tex1.Load(int3(asint(v4), asint(v5), asint(v6)))"),
|
||||
"{h}"
|
||||
);
|
||||
assert!(
|
||||
h.contains(
|
||||
"tex2.GatherRed(smp0, float3(asfloat(v3), asfloat(v4), asfloat(v5)), int2(2, 1))"
|
||||
),
|
||||
"{h}"
|
||||
);
|
||||
|
||||
// Comparison (_c) forms stay refused until a comparison sampler is added to the root-signature ABI.
|
||||
let ps_cmp_sample = decode(&words(
|
||||
"f40c0504 fa000020 f0bc0108 01250004 f800080f 00000000 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let err = translate_pair(&vs, &ps_cmp_sample).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("comparison sampler"),
|
||||
"expected comparison sampler refusal, got: {err}"
|
||||
);
|
||||
let ps_cmp_gather = decode(&words(
|
||||
"f40c0704 fa000040 7e0402ff 00000102 f1600128 01270c02 f800080f 0c0a0100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let err = translate_pair(&vs, &ps_cmp_gather).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("comparison sampler"),
|
||||
"expected comparison sampler refusal, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Overwriting a VGPR inside a block clears its tracked `vconst` value (#718).
|
||||
/// Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn vconst_overwrite_clears_constant_offset() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
let ps = decode(&words(
|
||||
"f40c0504 fa000020 7e0402ff 00000102 7e040304 f0c00f08 01050c02 f800080f 0c0a0100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let err = translate_pair(&vs, &ps).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("non-constant"),
|
||||
"expected non-constant offset refusal after overwrite, got: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Off-address buffer loads (#718), and typed buffer loads (buffer_load_format_*), which are
|
||||
/// refused: their data format is in the buffer descriptor, not known at translation.
|
||||
/// Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn typed_buffer_loads_refused_off_loads_translated() {
|
||||
let vs = decode(&words("be842104 f80008cf 07060504 bf810000")).unwrap();
|
||||
// buffer_load_dword v1, off, s[4:7], 0 offset:8
|
||||
let ps = decode(&words(
|
||||
"f4080404 fa000020 e0300008 80040100 f800080f 03020100 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let t = translate_pair(&vs, &ps).unwrap_or_else(|e| panic!("{e}"));
|
||||
let h = &t.ps_hlsl;
|
||||
assert!(h.contains("cb1_word(((8u) >> 2))"), "{h}");
|
||||
// buffer_load_format_x and buffer_load_format_xy (idxen)
|
||||
for load in ["e0000010 80040000", "e0042000 80040204"] {
|
||||
let ps = decode(&words(&format!(
|
||||
"f4080404 fa000020 {load} f800080f 03020100 bf810000"
|
||||
)))
|
||||
.unwrap();
|
||||
let err = translate_pair(&vs, &ps).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("buffer descriptor"),
|
||||
"expected the typed-load refusal, got: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// 16-bit interpolation (v_interp_p2_f16) is refused until the result's register half and the
|
||||
/// packed attribute layout are sourced (#718 review). Encodings from llvm-mc (gfx1030).
|
||||
#[test]
|
||||
fn f16_interpolation_refused() {
|
||||
let vs = decode(&words(
|
||||
"7e080280 f80000cf 04040404 f8000e0f 00000504 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let ps = decode(&words(
|
||||
"d7420002 02020000 d75a0002 040a0200 d7430003 040a0100 d75a8003 040e0300 f8000c03 00000002 bf810000",
|
||||
))
|
||||
.unwrap();
|
||||
let err = translate_pair(&vs, &ps).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("16-bit interpolation"),
|
||||
"expected the 16-bit interpolation refusal, got: {err}"
|
||||
);
|
||||
}
|
||||
+85
-31
@@ -1,41 +1,95 @@
|
||||
#define BX_DSP_CONNECTIONS
|
||||
#include "command_ring.h"
|
||||
/*
|
||||
* chad.dll: the XDSP (convolution/DSP hardware) client API, with the prototypes of the authorized
|
||||
* GDK header xdspaudio.h (#776):
|
||||
*
|
||||
* XDspConnectWithMaximumStreamLimit(float* baseBuffer, uint32_t baseBufferLength,
|
||||
* uint32_t aggregateImpulseResponseInSeconds, uint32_t maximumStreamCount,
|
||||
* uint32_t maximumChannelCount, XDspClientHandle* handle)
|
||||
* XDspDisconnect(XDspClientHandle)
|
||||
* XDspActivate(XDspClientHandle, XDspActivationParameters*, XDspStatus** status,
|
||||
* XDspStreamHandle* streamHandle)
|
||||
* XDspDeactivate(XDspStreamHandle)
|
||||
* XDspSubmitCommand(XDspStreamHandle, XDspCommand*, uint32_t* commandSequence)
|
||||
*
|
||||
* BetterXen does not model the DSP. A title asserts when connecting fails (the target build stops
|
||||
* a few seconds after a refused connect), so connecting succeeds: the client handle is a
|
||||
* placeholder that stands for "connected, nothing modelled", and the call is logged with
|
||||
* BX_STUB_LOG so `bx-cli trace` still lists it. Activating a stream on it is refused with
|
||||
* E_NOTIMPL, the documented outputs set to NULL. No stream handle can exist, so Deactivate and
|
||||
* SubmitCommand answer E_HANDLE with their outputs cleared. XDspDisconnect accepts the placeholder
|
||||
* while a connection is open. Nothing else of the caller's memory is written. The earlier exports
|
||||
* had a BetterXen-defined shape ((max_streams, out) for connect); called with the documented
|
||||
* argument list, connect wrote its handle to the address given by baseBufferLength.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <atomic>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
struct XDspClient; // XDspClientHandle: opaque in the GDK header
|
||||
struct XDspStream; // XDspStreamHandle: opaque in the GDK header
|
||||
struct XDspStatus; // only ever handed out as NULL here
|
||||
|
||||
namespace {
|
||||
// The placeholder client handle: its address is all that is handed out.
|
||||
struct XDspClientPlaceholder {
|
||||
uint32_t unused;
|
||||
} g_client;
|
||||
std::atomic<long> g_connections{0};
|
||||
|
||||
XDspClient* placeholder_client() { return reinterpret_cast<XDspClient*>(&g_client); }
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
// Validate and record the caller's stream limit; the synthetic command ring
|
||||
// holds a fixed 32-packet backlog independent of stream count.
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t max_streams, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!max_streams) return E_INVALIDARG;
|
||||
return connect(out, max_streams);
|
||||
}
|
||||
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
|
||||
|
||||
HRESULT WINAPI XDspActivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = true;
|
||||
// chad has no result export. Active DSP commands complete synchronously.
|
||||
while (c->queue.count) c->queue.pop();
|
||||
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(float* base_buffer, uint32_t base_buffer_length,
|
||||
uint32_t aggregate_impulse_response_seconds,
|
||||
uint32_t maximum_stream_count, uint32_t maximum_channel_count,
|
||||
XDspClient** handle) {
|
||||
if (!handle) return E_POINTER;
|
||||
*handle = placeholder_client();
|
||||
const long open = ++g_connections;
|
||||
char detail[224];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"connected without a DSP model (streams are refused): base_buffer=%s length=%u "
|
||||
"impulse_response_s=%u max_streams=%u max_channels=%u open=%ld",
|
||||
base_buffer ? "set" : "null", base_buffer_length, aggregate_impulse_response_seconds,
|
||||
maximum_stream_count, maximum_channel_count, open);
|
||||
bx_log_emit(BX_LOG_WARN, "chad", "XDspConnectWithMaximumStreamLimit", detail);
|
||||
BX_STUB_LOG("chad.dll", "XDspConnectWithMaximumStreamLimit");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspDeactivate(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
c->active = false;
|
||||
return S_OK;
|
||||
HRESULT WINAPI XDspDisconnect(XDspClient* client) {
|
||||
BX_STUB_LOG("chad.dll", "XDspDisconnect");
|
||||
if (client != placeholder_client()) return E_HANDLE;
|
||||
long open = g_connections.load();
|
||||
while (open > 0 && !g_connections.compare_exchange_weak(open, open - 1)) {
|
||||
}
|
||||
return open > 0 ? S_OK : E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspSubmitCommand(void* handle, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
const HRESULT hr = c->queue.push(cmd, size);
|
||||
if (SUCCEEDED(hr) && c->active) c->queue.pop();
|
||||
return hr;
|
||||
HRESULT WINAPI XDspActivate(XDspClient* client, const void* /*XDspActivationParameters*/, XDspStatus** status,
|
||||
XDspStream** stream_handle) {
|
||||
if (status) *status = nullptr;
|
||||
if (stream_handle) *stream_handle = nullptr;
|
||||
BX_STUB_LOG("chad.dll", "XDspActivate");
|
||||
if (client != placeholder_client() || g_connections.load() <= 0) return E_HANDLE;
|
||||
return E_NOTIMPL; // streams are not modelled
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspDeactivate(XDspStream*) {
|
||||
BX_STUB_LOG("chad.dll", "XDspDeactivate");
|
||||
return E_HANDLE;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XDspSubmitCommand(XDspStream*, const void* /*XDspCommand*/, uint32_t* command_sequence) {
|
||||
if (command_sequence) *command_sequence = 0;
|
||||
BX_STUB_LOG("chad.dll", "XDspSubmitCommand");
|
||||
return E_HANDLE;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
+116
-70
@@ -1,96 +1,142 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include "xapu_layout.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
// A synthetic command completes by returning its opaque bytes unchanged.
|
||||
struct CommandRing {
|
||||
struct Packet {
|
||||
uint32_t size;
|
||||
unsigned char bytes[1024];
|
||||
};
|
||||
std::array<Packet, 32> packets;
|
||||
unsigned head = 0, count = 0;
|
||||
|
||||
HRESULT push(const void* data, uint32_t size) {
|
||||
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
|
||||
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
|
||||
auto& packet = packets[(head + count) % packets.size()];
|
||||
packet.size = size;
|
||||
std::memcpy(packet.bytes, data, size);
|
||||
++count;
|
||||
return S_OK;
|
||||
}
|
||||
void pop() {
|
||||
head = (head + 1) % packets.size();
|
||||
--count;
|
||||
}
|
||||
HRESULT read(void* data, uint32_t size) {
|
||||
if (!data) return E_POINTER;
|
||||
if (!count) return S_FALSE;
|
||||
const auto& packet = packets[head];
|
||||
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
|
||||
std::memcpy(data, packet.bytes, packet.size);
|
||||
pop();
|
||||
return S_OK;
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* One connection's command queue. A submitted XApuCommandId becomes an
|
||||
* XApuResult that carries the same id. A Process command is the 64-byte
|
||||
* XApuDecodeConvertCommand: its result also carries that command's
|
||||
* inputDataLength, inputData and outputData. outputFrameCount and
|
||||
* outputDataLength stay 0, and errorCode stays S_OK, because nothing was
|
||||
* decoded. The ring is FIFO, which is the default xapu.h ordering. Capacity is
|
||||
* maxStreamCount * maxQueuedCommandsPerStream,
|
||||
* and each stream accepts at most maxQueuedCommandsPerStream commands that
|
||||
* have not been dequeued yet (XAPU_E_QUEUE_FULL). An empty dequeue is
|
||||
* XAPU_E_PENDING_RESULTS. Identifiers are odd and are never reused, so a
|
||||
* disconnected handle stays invalid if the allocator reuses the address.
|
||||
*/
|
||||
struct Connection {
|
||||
uintptr_t id;
|
||||
Connection* next;
|
||||
CommandRing queue;
|
||||
uintptr_t id = 0;
|
||||
Connection* next = nullptr;
|
||||
void* base_data = nullptr;
|
||||
HANDLE result_event = nullptr;
|
||||
uint32_t max_streams = 0;
|
||||
bool active = false;
|
||||
uint32_t max_queued = 0;
|
||||
uint32_t total_commands = 0;
|
||||
uint32_t total_results = 0;
|
||||
uint32_t head = 0;
|
||||
uint32_t count = 0;
|
||||
uint32_t capacity = 0;
|
||||
uint32_t* pending = nullptr;
|
||||
XApuResult* slots = nullptr;
|
||||
};
|
||||
|
||||
// Each DLL owns its registry. An ID stays invalid after disconnect, including
|
||||
// when the allocator subsequently reuses the same Connection address.
|
||||
std::mutex connections_lock;
|
||||
Connection* connections;
|
||||
#ifdef BX_DSP_CONNECTIONS
|
||||
uintptr_t next_id = 2;
|
||||
#else
|
||||
Connection* connections = nullptr;
|
||||
uintptr_t next_id = 1;
|
||||
#endif
|
||||
|
||||
HRESULT connect(void** out, uint32_t max_streams = 0) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
std::lock_guard guard(connections_lock);
|
||||
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
|
||||
auto* c = new (std::nothrow) Connection;
|
||||
if (!c) return E_OUTOFMEMORY;
|
||||
c->id = next_id;
|
||||
c->max_streams = max_streams;
|
||||
next_id += 2;
|
||||
c->next = connections;
|
||||
connections = c;
|
||||
*out = reinterpret_cast<void*>(c->id);
|
||||
return S_OK;
|
||||
void release_connection(Connection* c) {
|
||||
if (!c) return;
|
||||
if (c->base_data) VirtualFree(c->base_data, 0, MEM_RELEASE);
|
||||
if (c->result_event) CloseHandle(c->result_event);
|
||||
delete[] c->pending;
|
||||
delete[] c->slots;
|
||||
delete c;
|
||||
}
|
||||
|
||||
// Caller holds connections_lock through the operation.
|
||||
Connection* lookup(void* handle) {
|
||||
for (auto* c = connections; c; c = c->next)
|
||||
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
|
||||
const auto id = reinterpret_cast<uintptr_t>(handle);
|
||||
for (Connection* c = connections; c; c = c->next)
|
||||
if (c->id == id) return c;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HRESULT disconnect(void* handle) {
|
||||
/* Caller has filled every field except id and next. On failure the caller frees c. */
|
||||
HRESULT publish_connection(Connection* c, uintptr_t* out_id) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
for (auto** link = &connections; *link; link = &(*link)->next) {
|
||||
auto* c = *link;
|
||||
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
|
||||
c->id = next_id;
|
||||
next_id += 2;
|
||||
c->next = connections;
|
||||
connections = c;
|
||||
*out_id = c->id;
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT enqueue_command(void* handle, const XApuCommandId* command, uint32_t* total) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
Connection* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
if (command->streamIndex >= c->max_streams) {
|
||||
if (total) *total = c->total_commands;
|
||||
return XAPU_E_INVALID_STREAM_INDEX;
|
||||
}
|
||||
if (c->pending[command->streamIndex] >= c->max_queued || c->count >= c->capacity) {
|
||||
if (total) *total = c->total_commands;
|
||||
return XAPU_E_QUEUE_FULL;
|
||||
}
|
||||
XApuResult result{};
|
||||
std::memcpy(&result.id, command, sizeof(result.id));
|
||||
result.errorCode = S_OK;
|
||||
if (command->type == kXApuCommandProcess) {
|
||||
XApuDecodeConvertCommand decode{};
|
||||
std::memcpy(&decode, command, sizeof(decode));
|
||||
result.inputDataLength = decode.inputDataLength;
|
||||
result.inputData = decode.inputData;
|
||||
result.outputData = decode.outputData;
|
||||
}
|
||||
const uint32_t slot = (c->head + c->count) % c->capacity;
|
||||
std::memcpy(&c->slots[slot], &result, sizeof(result));
|
||||
++c->count;
|
||||
++c->pending[command->streamIndex];
|
||||
++c->total_commands;
|
||||
++c->total_results;
|
||||
if (total) *total = c->total_commands;
|
||||
if (c->result_event && (command->options & kXApuSignalOnCompletion) != 0) SetEvent(c->result_event);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT dequeue_result(void* handle, XApuResult* command_result) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
Connection* c = lookup(handle);
|
||||
if (!c) return E_HANDLE;
|
||||
if (c->count == 0) return XAPU_E_PENDING_RESULTS;
|
||||
XApuResult result{};
|
||||
std::memcpy(&result, &c->slots[c->head], sizeof(result));
|
||||
c->head = (c->head + 1) % c->capacity;
|
||||
--c->count;
|
||||
if (result.id.streamIndex < c->max_streams && c->pending[result.id.streamIndex] > 0)
|
||||
--c->pending[result.id.streamIndex];
|
||||
std::memcpy(command_result, &result, sizeof(*command_result));
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
uint32_t result_count(void* handle, uint32_t* total) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
Connection* c = lookup(handle);
|
||||
if (!c) {
|
||||
if (total) *total = 0;
|
||||
return 0;
|
||||
}
|
||||
if (total) *total = c->total_results;
|
||||
return c->count;
|
||||
}
|
||||
|
||||
HRESULT disconnect_connection(void* handle) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
for (Connection** link = &connections; *link; link = &(*link)->next) {
|
||||
Connection* c = *link;
|
||||
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
|
||||
*link = c->next;
|
||||
delete c;
|
||||
return S_OK;
|
||||
const bool pending = c->count > 0;
|
||||
release_connection(c);
|
||||
return pending ? XAPU_E_PENDING_RESULTS : S_OK;
|
||||
}
|
||||
return E_HANDLE;
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
+135
-14
@@ -1,24 +1,145 @@
|
||||
/*
|
||||
* xapu.dll: the XAPU client API, with the prototypes of the authorized GDK header xapu.h (#777):
|
||||
*
|
||||
* XApuConnect(XApuConnectInputParameters* params, XApuConnectOutputParameters* data,
|
||||
* XApuHandle* handle)
|
||||
* XApuDisconnect(XApuHandle)
|
||||
* XApuEnqueueCommand(XApuHandle, XApuCommandId* command, uint32_t* totalCommandCount)
|
||||
* XApuDequeueResult(XApuHandle, XApuResult* commandResult)
|
||||
* XApuGetResultCount(XApuHandle, uint32_t* totalResultCount) -> uint32_t
|
||||
*
|
||||
* BetterXen does not model the APU device. Connecting still succeeds and is logged with
|
||||
* BX_STUB_LOG: a refused connect changes a title's audio init. On success the call writes
|
||||
* *handle and XApuConnectOutputParameters — baseData, and resultReadyEvent when
|
||||
* XApuConnectOptions::EnableResultReadyEvent is set — and nothing else. baseData is freed
|
||||
* and the event is closed on XApuDisconnect. Commands are queued per connection (see
|
||||
* command_ring.h) and come back as XApuResult records that carry the same XApuCommandId.
|
||||
* A Process command's result also carries that command's inputDataLength, inputData and
|
||||
* outputData. outputFrameCount and outputDataLength stay 0, and errorCode is S_OK, because
|
||||
* the command was not processed (BX_STUB_LOG). totalCommandCount and totalResultCount
|
||||
* advance when their pointers are non-null and do not reset. Hardware processing, the
|
||||
* result-ready timer, and pitch conversion are not modelled. The earlier exports took a
|
||||
* byte blob plus a size, and XApuConnect wrote its
|
||||
* handle through the first argument, which is the input parameter block.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "command_ring.h"
|
||||
|
||||
namespace {
|
||||
bool connect_params_ok(const XApuConnectInputParameters* params) {
|
||||
return params->maxStreamCount >= 1 && params->maxStreamCount <= kXApuMaxStreamCount &&
|
||||
params->maxQueuedCommandsPerStream >= 1 &&
|
||||
params->maxQueuedCommandsPerStream <= kXApuMaxQueuedPerStream && params->baseDataLength > 0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
|
||||
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
|
||||
|
||||
HRESULT WINAPI XApuEnqueueCommand(void* conn, const void* cmd, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.push(cmd, size) : E_HANDLE;
|
||||
HRESULT WINAPI XApuConnect(XApuConnectInputParameters* params, XApuConnectOutputParameters* data, XApu** handle) {
|
||||
if (!params || !data || !handle) return E_POINTER;
|
||||
if (!connect_params_ok(params)) {
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuConnect", "rejected parameters outside the xapu.h limits");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
void* base = VirtualAlloc(nullptr, params->baseDataLength, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
|
||||
if (!base) {
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "baseData allocation failed");
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
HANDLE event = nullptr;
|
||||
if ((params->options & kXApuEnableResultReadyEvent) != 0) {
|
||||
event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event) {
|
||||
const DWORD err = GetLastError();
|
||||
VirtualFree(base, 0, MEM_RELEASE);
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "resultReadyEvent creation failed");
|
||||
return err ? HRESULT_FROM_WIN32(err) : E_OUTOFMEMORY;
|
||||
}
|
||||
}
|
||||
|
||||
const uint32_t streams = params->maxStreamCount;
|
||||
const uint32_t queued = params->maxQueuedCommandsPerStream;
|
||||
const uint32_t capacity = streams * queued;
|
||||
auto* pending = new (std::nothrow) uint32_t[streams];
|
||||
auto* slots = new (std::nothrow) XApuResult[capacity];
|
||||
auto* connection = new (std::nothrow) Connection{};
|
||||
if (!pending || !slots || !connection) {
|
||||
delete[] pending;
|
||||
delete[] slots;
|
||||
delete connection;
|
||||
if (event) CloseHandle(event);
|
||||
VirtualFree(base, 0, MEM_RELEASE);
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "connection allocation failed");
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
std::memset(pending, 0, sizeof(uint32_t) * streams);
|
||||
connection->base_data = base;
|
||||
connection->result_event = event;
|
||||
connection->max_streams = streams;
|
||||
connection->max_queued = queued;
|
||||
connection->capacity = capacity;
|
||||
connection->pending = pending;
|
||||
connection->slots = slots;
|
||||
|
||||
uintptr_t id = 0;
|
||||
if (const HRESULT hr = publish_connection(connection, &id); FAILED(hr)) {
|
||||
release_connection(connection);
|
||||
bx_log_emit(BX_LOG_ERROR, "xapu", "XApuConnect", "connection id space exhausted");
|
||||
return hr;
|
||||
}
|
||||
|
||||
data->baseData = base;
|
||||
data->resultReadyEvent = event;
|
||||
*handle = reinterpret_cast<XApu*>(id);
|
||||
|
||||
char detail[288];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"connected without an APU device (commands are queued, not processed): "
|
||||
"process=%u streams=%u queued_per_stream=%u base_bytes=%u event=%s",
|
||||
params->processType, streams, queued, params->baseDataLength, event ? "set" : "null");
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuConnect", detail);
|
||||
BX_STUB_LOG("xapu.dll", "XApuConnect");
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDequeueResult(void* conn, void* result, uint32_t size) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.read(result, size) : E_HANDLE;
|
||||
HRESULT WINAPI XApuDisconnect(XApu* handle) {
|
||||
const HRESULT hr = disconnect_connection(handle);
|
||||
if (hr == XAPU_E_PENDING_RESULTS) {
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuDisconnect",
|
||||
"disconnected with results still queued; no APU device is modelled");
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
uint32_t WINAPI XApuGetResultCount(void* conn) {
|
||||
std::lock_guard guard(connections_lock);
|
||||
auto* c = lookup(conn);
|
||||
return c ? c->queue.count : 0;
|
||||
HRESULT WINAPI XApuEnqueueCommand(XApu* handle, XApuCommandId* command, uint32_t* total_command_count) {
|
||||
if (!command) return E_POINTER;
|
||||
const HRESULT hr = enqueue_command(handle, command, total_command_count);
|
||||
if (hr == S_OK) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.exchange(1) == 0) {
|
||||
BX_STUB_LOG("xapu.dll", "XApuEnqueueCommand");
|
||||
bx_log_emit(BX_LOG_WARN, "xapu", "XApuEnqueueCommand",
|
||||
"command queued and not processed; the result echoes the command id and Process buffers, with no decoded PCM");
|
||||
}
|
||||
}
|
||||
return hr;
|
||||
}
|
||||
|
||||
HRESULT WINAPI XApuDequeueResult(XApu* handle, XApuResult* command_result) {
|
||||
if (!command_result) return E_POINTER;
|
||||
return dequeue_result(handle, command_result);
|
||||
}
|
||||
|
||||
uint32_t WINAPI XApuGetResultCount(XApu* handle, uint32_t* total_result_count) {
|
||||
return result_count(handle, total_result_count);
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,115 @@
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* Field layout of the xapu.h structures the xapu.dll exports pass through.
|
||||
* The shim does not include the GDK header. Names match that header; the
|
||||
* pack is 1, as xapu.h packs these structures.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
struct XApuConnectInputParameters {
|
||||
uint32_t processType;
|
||||
uint32_t maxStreamCount;
|
||||
uint32_t maxQueuedCommandsPerStream;
|
||||
uint32_t baseDataLength;
|
||||
uint32_t maxFrameCountPerOutput;
|
||||
uint32_t options;
|
||||
};
|
||||
|
||||
struct XApuConnectOutputParameters {
|
||||
void* baseData;
|
||||
HANDLE resultReadyEvent;
|
||||
};
|
||||
|
||||
struct XApuCommandId {
|
||||
uint32_t type;
|
||||
uint32_t streamIndex;
|
||||
uint32_t sequence;
|
||||
uint32_t options;
|
||||
void* context;
|
||||
};
|
||||
|
||||
/* Process (XApuCommandType::Process) is this packed command, not the 24-byte id alone. */
|
||||
struct XApuDecodeConvertCommand {
|
||||
XApuCommandId id;
|
||||
float pitchRampRate;
|
||||
float targetPitch;
|
||||
uint32_t firstFrameIndex;
|
||||
uint32_t frameCount;
|
||||
uint32_t inputDataLength;
|
||||
void* inputData;
|
||||
uint32_t maxOutputDataLength;
|
||||
void* outputData;
|
||||
};
|
||||
|
||||
struct XApuResult {
|
||||
XApuCommandId id;
|
||||
uint32_t state;
|
||||
uint64_t stateData;
|
||||
uint64_t totalExecutionTime;
|
||||
HRESULT errorCode;
|
||||
uint32_t outputFrameCount;
|
||||
uint32_t outputDataLength;
|
||||
void* outputData;
|
||||
float currentPitch;
|
||||
uint32_t inputDataLength;
|
||||
void* inputData;
|
||||
};
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
struct XApu; /* XApuHandle in xapu.h: an opaque pointer */
|
||||
|
||||
/* XApuConnectOptions::EnableResultReadyEvent and XApuCommandOptions::SignalOnCompletion. */
|
||||
constexpr uint32_t kXApuEnableResultReadyEvent = 8u;
|
||||
constexpr uint32_t kXApuSignalOnCompletion = 1u;
|
||||
|
||||
/* XApuCommandType::Process. The submitted object is XApuDecodeConvertCommand. */
|
||||
constexpr uint32_t kXApuCommandProcess = 3u;
|
||||
|
||||
/* Limits xapu.h states for maxStreamCount and maxQueuedCommandsPerStream. */
|
||||
constexpr uint32_t kXApuMaxStreamCount = 500u;
|
||||
constexpr uint32_t kXApuMaxQueuedPerStream = 16u;
|
||||
|
||||
/*
|
||||
* Error codes named in xapu.h (XAPU_E_QUEUE_FULL, XAPU_E_PENDING_RESULTS,
|
||||
* XAPU_E_INVALID_STREAM_INDEX).
|
||||
*/
|
||||
#define XAPU_E_QUEUE_FULL MAKE_HRESULT(SEVERITY_ERROR, 0xAC8, 0x1000)
|
||||
#define XAPU_E_PENDING_RESULTS MAKE_HRESULT(SEVERITY_ERROR, 0xAC8, 0x1001)
|
||||
#define XAPU_E_INVALID_STREAM_INDEX MAKE_HRESULT(SEVERITY_ERROR, 0xAC8, 0x1003)
|
||||
|
||||
static_assert(sizeof(void*) == 8, "xapu handles and baseData are 8-byte pointers");
|
||||
static_assert(alignof(XApuConnectInputParameters) == 1 && sizeof(XApuConnectInputParameters) == 24,
|
||||
"XApuConnectInputParameters");
|
||||
static_assert(sizeof(XApuConnectOutputParameters) == 16, "XApuConnectOutputParameters");
|
||||
static_assert(offsetof(XApuCommandId, context) == 16 && sizeof(XApuCommandId) == 24, "XApuCommandId");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, id) == 0, "XApuDecodeConvertCommand.id");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, pitchRampRate) == 24, "XApuDecodeConvertCommand.pitchRampRate");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, targetPitch) == 28, "XApuDecodeConvertCommand.targetPitch");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, firstFrameIndex) == 32, "XApuDecodeConvertCommand.firstFrameIndex");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, frameCount) == 36, "XApuDecodeConvertCommand.frameCount");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, inputDataLength) == 40, "XApuDecodeConvertCommand.inputDataLength");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, inputData) == 44, "XApuDecodeConvertCommand.inputData");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, maxOutputDataLength) == 52, "XApuDecodeConvertCommand.maxOutputDataLength");
|
||||
static_assert(offsetof(XApuDecodeConvertCommand, outputData) == 56, "XApuDecodeConvertCommand.outputData");
|
||||
static_assert(sizeof(XApuDecodeConvertCommand) == 64, "XApuDecodeConvertCommand");
|
||||
static_assert(alignof(XApuResult) == 1 && sizeof(XApuResult) == 80, "XApuResult");
|
||||
static_assert(offsetof(XApuResult, state) == 24, "XApuResult.state");
|
||||
static_assert(offsetof(XApuResult, stateData) == 28, "XApuResult.stateData");
|
||||
static_assert(offsetof(XApuResult, totalExecutionTime) == 36, "XApuResult.totalExecutionTime");
|
||||
static_assert(offsetof(XApuResult, errorCode) == 44, "XApuResult.errorCode");
|
||||
static_assert(offsetof(XApuResult, outputFrameCount) == 48, "XApuResult.outputFrameCount");
|
||||
static_assert(offsetof(XApuResult, outputDataLength) == 52, "XApuResult.outputDataLength");
|
||||
static_assert(offsetof(XApuResult, outputData) == 56, "XApuResult.outputData");
|
||||
static_assert(offsetof(XApuResult, currentPitch) == 64, "XApuResult.currentPitch");
|
||||
static_assert(offsetof(XApuResult, inputDataLength) == 68, "XApuResult.inputDataLength");
|
||||
static_assert(offsetof(XApuResult, inputData) == 72, "XApuResult.inputData");
|
||||
static_assert(static_cast<uint32_t>(XAPU_E_QUEUE_FULL) == 0x8AC81000u, "XAPU_E_QUEUE_FULL");
|
||||
static_assert(static_cast<uint32_t>(XAPU_E_PENDING_RESULTS) == 0x8AC81001u, "XAPU_E_PENDING_RESULTS");
|
||||
static_assert(static_cast<uint32_t>(XAPU_E_INVALID_STREAM_INDEX) == 0x8AC81003u, "XAPU_E_INVALID_STREAM_INDEX");
|
||||
@@ -13,11 +13,14 @@ bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
|
||||
committed.cpp
|
||||
console_formats.cpp
|
||||
pipelines.cpp
|
||||
console_pipelines.cpp
|
||||
console_descriptors.cpp
|
||||
rect_list.cpp
|
||||
gpu_writes.cpp
|
||||
fences.cpp
|
||||
presentx_xbox.cpp
|
||||
page_mappings.cpp
|
||||
title_memory.cpp
|
||||
xbox_tables_generated.cpp
|
||||
)
|
||||
target_link_libraries(d3d12_xs PRIVATE bx_runtime_veh xmem kernel32 user32 dxguid)
|
||||
@@ -0,0 +1,393 @@
|
||||
/*
|
||||
* Descriptors of translated console draws (#720). Active with BX_CONSOLE_SHADERS=1.
|
||||
*
|
||||
* On the console a CBV/SRV/UAV descriptor is 32 bytes of memory at its handle, and a title may
|
||||
* copy those bytes itself: the target build fills per-draw descriptor tables with memcpy, never
|
||||
* telling Direct3D. The host heap behind such a table then holds nothing at those indices.
|
||||
*
|
||||
* So that the copies can be followed:
|
||||
* 1. every CreateConstantBufferView and CreateShaderResourceView also writes a marker into the
|
||||
* title's descriptor memory at the handle: a magic word, the id of a registry entry that
|
||||
* holds the view, and the id's complement. The title copies the marker with its bytes;
|
||||
* 2. SetGraphicsRootDescriptorTable is noted per command list, and each translated draw
|
||||
* records the tables bound at that moment;
|
||||
* 3. when the list is submitted, the entries the draw's shaders read (the translation's
|
||||
* `USE` lines) are looked up through their markers and written to the host heap at the same
|
||||
* index, before the host executes the list.
|
||||
* Direct3D's own copies (CopyDescriptors, CopyDescriptorsSimple) copy the title-side bytes as
|
||||
* well as the host descriptors, as they do on the console: the title goes on to copy from their
|
||||
* destinations by hand.
|
||||
* A constant buffer's bytes are copied from title memory into an upload ring at that moment, so
|
||||
* the host sees what the title had written by submission whatever backs the title's address.
|
||||
*
|
||||
* The marker is BetterXen's own format, not the console's descriptor encoding (which is not
|
||||
* known here): a title that reads its descriptors back, rather than only copying them, would
|
||||
* see it. Entries without a marker are left as the host heap has them and are logged.
|
||||
*
|
||||
* Limits, logged when met: a registered texture is kept referenced until the shim releases it
|
||||
* (placed_x.cpp releases implicit shadows the title has replaced; their markers then resolve to null
|
||||
* views); a table changed between a draw and the submission of its list is read at submission.
|
||||
*/
|
||||
#include "console_pipelines.h"
|
||||
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "title_memory.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t kMarkerMagic = 0x31445842u; // "BXD1"
|
||||
constexpr UINT kDescriptorSize = 32; // console CBV/SRV/UAV descriptor
|
||||
constexpr UINT kTables = 8; // root parameters followed per list
|
||||
|
||||
void log(bx_log_level_t level, const char* event, const char* fmt, ...) {
|
||||
char detail[400];
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
std::vsnprintf(detail, sizeof(detail), fmt, args);
|
||||
va_end(args);
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
bool sampled(std::atomic<uint64_t>& counter, uint64_t* total) {
|
||||
*total = ++counter;
|
||||
return (*total & (*total - 1)) == 0;
|
||||
}
|
||||
|
||||
struct View {
|
||||
bool texture = false;
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; // host description
|
||||
uint64_t title_va = 0; // the title's address of the constant data
|
||||
ID3D12Resource* resource = nullptr; // SRV: host resource, referenced
|
||||
bool has_srv_desc = false;
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC srv{};
|
||||
};
|
||||
|
||||
std::mutex g_view_lock;
|
||||
std::vector<View> g_views(1); // id 0 is never used
|
||||
std::vector<std::string> g_view_keys(1);
|
||||
std::unordered_map<std::string, uint32_t> g_view_ids;
|
||||
std::unordered_map<const ID3D12Resource*, std::vector<uint32_t>> g_views_of; // resource -> ids of its views
|
||||
|
||||
/* `owner`: the resource the view depends on, when the shim may release it early; an SRV's own
|
||||
resource otherwise. */
|
||||
uint32_t intern(const std::string& key, const View& view, ID3D12Resource* owner = nullptr) {
|
||||
std::lock_guard<std::mutex> guard(g_view_lock);
|
||||
auto it = g_view_ids.find(key);
|
||||
if (it != g_view_ids.end()) return it->second;
|
||||
const uint32_t id = static_cast<uint32_t>(g_views.size());
|
||||
g_views.push_back(view);
|
||||
g_view_keys.push_back(key);
|
||||
if (view.resource) view.resource->AddRef();
|
||||
if (const ID3D12Resource* index = owner ? owner : view.resource) g_views_of[index].push_back(id);
|
||||
g_view_ids.emplace(key, id);
|
||||
return id;
|
||||
}
|
||||
|
||||
void write_marker(uint64_t title_handle, uint32_t id) {
|
||||
if (!bx_xbox_title_descriptors(title_handle, 1)) return;
|
||||
const uint32_t words[8] = {kMarkerMagic, id, ~id, 0, 0, 0, 0, 0};
|
||||
std::memcpy(reinterpret_cast<void*>(title_handle), words, sizeof(words));
|
||||
}
|
||||
|
||||
bool readable(uint64_t address, uint64_t size) {
|
||||
return bx_title_memory_present(address, size);
|
||||
}
|
||||
|
||||
/* The constant data at `title_va`, copied to an upload ring at a 256-byte-aligned offset. The
|
||||
ring wraps: at 16 MiB it holds at least 256 buffers of the largest size, far more than the
|
||||
draws of the lists in flight. */
|
||||
bool constant_copy(ID3D12Device* device, uint64_t title_va, uint64_t size, D3D12_CONSTANT_BUFFER_VIEW_DESC* out) {
|
||||
constexpr uint64_t kRing = 16ull << 20;
|
||||
static ID3D12Resource* ring = nullptr;
|
||||
static uint8_t* mapped = nullptr;
|
||||
static uint64_t cursor = 0;
|
||||
static std::mutex lock;
|
||||
if (!size || size > 65536 || !readable(title_va, size)) return false;
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
if (!ring) {
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
D3D12_RESOURCE_DESC d{};
|
||||
d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
d.Width = kRing;
|
||||
d.Height = d.DepthOrArraySize = d.MipLevels = 1;
|
||||
d.SampleDesc.Count = 1;
|
||||
d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
if (FAILED(device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &d, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&ring))) ||
|
||||
FAILED(ring->Map(0, nullptr, reinterpret_cast<void**>(&mapped)))) {
|
||||
ring = nullptr;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const uint64_t aligned = (size + 255) & ~255ull;
|
||||
if (cursor + aligned > kRing) cursor = 0;
|
||||
std::memset(mapped + cursor, 0, aligned);
|
||||
std::memcpy(mapped + cursor, reinterpret_cast<const void*>(title_va), size);
|
||||
out->BufferLocation = ring->GetGPUVirtualAddress() + cursor;
|
||||
out->SizeInBytes = static_cast<UINT>(aligned);
|
||||
cursor += aligned;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct Draw {
|
||||
std::shared_ptr<BxConsolePipeline> pipeline;
|
||||
uint64_t tables[kTables];
|
||||
};
|
||||
|
||||
std::mutex g_list_lock;
|
||||
std::unordered_map<const void*, std::vector<Draw>> g_draws; // per list, since its reset
|
||||
std::unordered_map<const void*, std::array<uint64_t, kTables>> g_tables; // title table handles bound
|
||||
|
||||
std::atomic<uint64_t> g_resolved{0};
|
||||
std::atomic<uint64_t> g_unmarked{0};
|
||||
|
||||
/* Writes the host view for one table entry a translated draw reads. */
|
||||
void resolve(ID3D12Device* device, const char* key, const BxConsoleUse& use, uint64_t entry, BxTextureUploads* uploads) {
|
||||
uint32_t words[8] = {};
|
||||
std::memcpy(words, reinterpret_cast<const void*>(entry), sizeof(words));
|
||||
View view;
|
||||
bool ok = words[0] == kMarkerMagic && words[2] == ~words[1];
|
||||
if (ok) {
|
||||
std::lock_guard<std::mutex> guard(g_view_lock);
|
||||
ok = words[1] != 0 && words[1] < g_views.size();
|
||||
if (ok) view = g_views[words[1]];
|
||||
// Held for this resolve: bx_console_forget_resource may drop the registry's reference.
|
||||
if (ok && view.resource) view.resource->AddRef();
|
||||
}
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE host = bx_xbox_host_cpu_handle({static_cast<SIZE_T>(entry)});
|
||||
uint64_t total = 0;
|
||||
// A view whose resource the shim has released (an implicit shadow the title replaced) resolves
|
||||
// to a null view: never to memory that is gone.
|
||||
const bool released = ok && view.texture && !view.resource;
|
||||
if (ok && !use.texture && !view.texture) {
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC copy{};
|
||||
// Fresh bytes from title memory when it can be read; otherwise the view as created, or a
|
||||
// null view when the buffer behind it has been released.
|
||||
if (constant_copy(device, view.title_va, view.cbv.SizeInBytes, ©)) {
|
||||
device->CreateConstantBufferView(©, host);
|
||||
} else {
|
||||
device->CreateConstantBufferView(view.cbv.BufferLocation ? &view.cbv : nullptr, host);
|
||||
}
|
||||
++g_resolved;
|
||||
} else if (ok && use.texture && view.texture && !(released && !view.has_srv_desc)) {
|
||||
// A texture placed in title memory is read through a copy of its contents (#745).
|
||||
ID3D12Resource* contents = released ? nullptr : bx_xbox_texture_contents(view.resource, uploads);
|
||||
device->CreateShaderResourceView(contents, view.has_srv_desc ? &view.srv : nullptr, host);
|
||||
++g_resolved;
|
||||
} else if (sampled(g_unmarked, &total)) {
|
||||
log(BX_LOG_WARN, "console_descriptor",
|
||||
"pipeline %s reads %s entry %u of root parameter %u, which holds %s (%08x %08x %08x %08x); left as the host heap has it; "
|
||||
"total=%llu, resolved=%llu",
|
||||
key, use.texture ? "texture" : "constant buffer", use.entry, use.param,
|
||||
ok ? "a view of the other kind" : "no view this layer created", words[0], words[1], words[2], words[3],
|
||||
static_cast<unsigned long long>(total), static_cast<unsigned long long>(g_resolved.load()));
|
||||
}
|
||||
if (ok && view.resource) view.resource->Release();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
|
||||
ID3D12Resource* owner) {
|
||||
if (!bx_console_shaders_enabled() || !title_handle) return;
|
||||
View view;
|
||||
view.cbv = host_desc;
|
||||
view.title_va = title_va;
|
||||
char key[80];
|
||||
std::snprintf(key, sizeof(key), "c%llx:%llx:%u", static_cast<unsigned long long>(title_va),
|
||||
static_cast<unsigned long long>(host_desc.BufferLocation), host_desc.SizeInBytes);
|
||||
write_marker(title_handle, intern(key, view, owner));
|
||||
}
|
||||
|
||||
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc) {
|
||||
bx_console_mark_cbv_of(title_handle, title_va, host_desc, nullptr);
|
||||
}
|
||||
|
||||
void bx_console_forget_resource(ID3D12Resource* resource) {
|
||||
if (!resource) return;
|
||||
std::vector<ID3D12Resource*> references;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_view_lock);
|
||||
auto it = g_views_of.find(resource);
|
||||
if (it == g_views_of.end()) return;
|
||||
for (const uint32_t id : it->second) {
|
||||
View& v = g_views[id];
|
||||
if (v.resource == resource) {
|
||||
references.push_back(resource);
|
||||
v.resource = nullptr;
|
||||
}
|
||||
if (!v.texture) v.cbv.BufferLocation = 0; // the fallback lay in the released buffer
|
||||
// A new view made later with the same description gets a new id.
|
||||
auto key = g_view_ids.find(g_view_keys[id]);
|
||||
if (key != g_view_ids.end() && key->second == id) g_view_ids.erase(key);
|
||||
}
|
||||
g_views_of.erase(it);
|
||||
}
|
||||
for (ID3D12Resource* r : references) r->Release();
|
||||
}
|
||||
|
||||
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc) {
|
||||
if (!bx_console_shaders_enabled() || !title_handle || !host) return;
|
||||
View view;
|
||||
view.texture = true;
|
||||
view.resource = host;
|
||||
view.has_srv_desc = host_desc != nullptr;
|
||||
if (host_desc) view.srv = *host_desc;
|
||||
std::string key = "s" + std::to_string(reinterpret_cast<uintptr_t>(host)) + ":";
|
||||
if (host_desc) key.append(reinterpret_cast<const char*>(host_desc), sizeof(*host_desc));
|
||||
write_marker(title_handle, intern(key, view));
|
||||
}
|
||||
|
||||
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count) {
|
||||
if (!bx_console_shaders_enabled() || !count || dest == src) return;
|
||||
if (!bx_xbox_title_descriptors(dest, count) || !bx_xbox_title_descriptors(src, count)) return;
|
||||
std::memmove(reinterpret_cast<void*>(dest), reinterpret_cast<const void*>(src), static_cast<size_t>(kDescriptorSize) * count);
|
||||
}
|
||||
|
||||
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle) {
|
||||
if (!bx_console_shaders_enabled() || param >= kTables) return;
|
||||
std::lock_guard<std::mutex> guard(g_list_lock);
|
||||
g_tables[list][param] = title_handle;
|
||||
}
|
||||
|
||||
void bx_console_record_draw(ID3D12GraphicsCommandList* list, const std::shared_ptr<BxConsolePipeline>& pipeline) {
|
||||
std::lock_guard<std::mutex> guard(g_list_lock);
|
||||
Draw draw{pipeline, {}};
|
||||
auto bound = g_tables.find(list);
|
||||
if (bound != g_tables.end()) std::memcpy(draw.tables, bound->second.data(), sizeof(draw.tables));
|
||||
std::vector<Draw>& draws = g_draws[list];
|
||||
// Consecutive draws with the same pipeline and tables resolve the same entries.
|
||||
if (!draws.empty() && draws.back().pipeline == pipeline && std::memcmp(draws.back().tables, draw.tables, sizeof(draw.tables)) == 0) {
|
||||
return;
|
||||
}
|
||||
draws.push_back(std::move(draw));
|
||||
}
|
||||
|
||||
void bx_console_descriptors_reset(ID3D12GraphicsCommandList* list) {
|
||||
std::lock_guard<std::mutex> guard(g_list_lock);
|
||||
g_draws.erase(list);
|
||||
g_tables.erase(list);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* Per queue: a list of the shim's own that uploads texture contents (placed_x.cpp) ahead of the
|
||||
title's lists, its allocators in turn, and a fence for both (#745). */
|
||||
struct UploadContext {
|
||||
static constexpr UINT kTurns = 4;
|
||||
std::mutex lock;
|
||||
ID3D12CommandAllocator* allocators[kTurns] = {};
|
||||
UINT64 allocator_values[kTurns] = {};
|
||||
ID3D12GraphicsCommandList* list = nullptr;
|
||||
ID3D12Fence* fence = nullptr;
|
||||
HANDLE event = nullptr;
|
||||
UINT64 next = 1;
|
||||
UINT turn = 0;
|
||||
bool failed = false;
|
||||
};
|
||||
std::mutex g_upload_lock;
|
||||
std::unordered_map<const void*, std::unique_ptr<UploadContext>> g_uploads;
|
||||
|
||||
UploadContext* upload_context(ID3D12CommandQueue* queue) {
|
||||
UploadContext* ctx = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_upload_lock);
|
||||
auto& slot = g_uploads[queue];
|
||||
if (!slot) slot = std::make_unique<UploadContext>();
|
||||
ctx = slot.get();
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(ctx->lock);
|
||||
if (ctx->list || ctx->failed) return ctx->failed ? nullptr : ctx;
|
||||
ID3D12Device* device = nullptr;
|
||||
HRESULT hr = queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
const D3D12_COMMAND_LIST_TYPE type = queue->GetDesc().Type;
|
||||
for (UINT i = 0; SUCCEEDED(hr) && i < UploadContext::kTurns; ++i) {
|
||||
hr = device->CreateCommandAllocator(type, __uuidof(ID3D12CommandAllocator), reinterpret_cast<void**>(&ctx->allocators[i]));
|
||||
}
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommandList(0, type, ctx->allocators[0], nullptr, __uuidof(ID3D12GraphicsCommandList),
|
||||
reinterpret_cast<void**>(&ctx->list));
|
||||
}
|
||||
if (SUCCEEDED(hr)) hr = ctx->list->Close();
|
||||
if (SUCCEEDED(hr)) hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&ctx->fence));
|
||||
if (device) device->Release();
|
||||
ctx->event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (FAILED(hr) || !ctx->event) {
|
||||
ctx->failed = true;
|
||||
log(BX_LOG_WARN, "texture_upload", "no upload list for this queue (hr=0x%08lx); texture contents are not uploaded on it",
|
||||
static_cast<unsigned long>(FAILED(hr) ? hr : E_OUTOFMEMORY));
|
||||
return nullptr;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_console_submit(ID3D12CommandQueue* queue, ID3D12CommandList* const* host_lists, UINT count) {
|
||||
if (!bx_console_shaders_enabled()) return;
|
||||
std::vector<Draw> draws;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_list_lock);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
auto it = g_draws.find(host_lists[i]);
|
||||
if (it != g_draws.end()) draws.insert(draws.end(), it->second.begin(), it->second.end());
|
||||
}
|
||||
}
|
||||
if (draws.empty()) return;
|
||||
UploadContext* ctx = queue ? upload_context(queue) : nullptr;
|
||||
std::unique_lock<std::mutex> held;
|
||||
BxTextureUploads uploads{nullptr, nullptr, 0, false};
|
||||
UINT turn = 0;
|
||||
if (ctx) {
|
||||
held = std::unique_lock<std::mutex>(ctx->lock);
|
||||
turn = ctx->turn % UploadContext::kTurns;
|
||||
if (ctx->fence->GetCompletedValue() < ctx->allocator_values[turn]) {
|
||||
ctx->fence->SetEventOnCompletion(ctx->allocator_values[turn], ctx->event);
|
||||
WaitForSingleObject(ctx->event, 2000);
|
||||
}
|
||||
if (SUCCEEDED(ctx->allocators[turn]->Reset()) && SUCCEEDED(ctx->list->Reset(ctx->allocators[turn], nullptr))) {
|
||||
uploads = BxTextureUploads{ctx->list, ctx->fence, ctx->next, false};
|
||||
}
|
||||
}
|
||||
std::unordered_set<uint64_t> done; // entries written for this submission
|
||||
for (const Draw& draw : draws) {
|
||||
ID3D12Device* device = nullptr;
|
||||
const BxConsoleUse* uses = nullptr;
|
||||
size_t use_count = 0;
|
||||
const char* key = "";
|
||||
if (!bx_console_pipeline_info(draw.pipeline.get(), &device, &uses, &use_count, &key)) continue;
|
||||
for (size_t u = 0; u < use_count; ++u) {
|
||||
if (uses[u].param >= kTables || !draw.tables[uses[u].param]) continue;
|
||||
const uint64_t entry = draw.tables[uses[u].param] + static_cast<uint64_t>(kDescriptorSize) * uses[u].entry;
|
||||
if (!bx_xbox_title_descriptors(entry, 1)) continue;
|
||||
if (!done.insert(entry * 2 + (uses[u].texture ? 1 : 0)).second) continue;
|
||||
resolve(device, key, uses[u], entry, uploads.list ? &uploads : nullptr);
|
||||
}
|
||||
}
|
||||
if (uploads.list) {
|
||||
ctx->list->Close();
|
||||
if (uploads.recorded) {
|
||||
ID3D12CommandList* lists[] = {ctx->list};
|
||||
queue->ExecuteCommandLists(1, lists);
|
||||
queue->Signal(ctx->fence, uploads.value);
|
||||
ctx->allocator_values[turn] = uploads.value;
|
||||
++ctx->next;
|
||||
++ctx->turn;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,12 +11,21 @@
|
||||
#include "console_formats.h"
|
||||
|
||||
#include "xbox_facade.h"
|
||||
#include "console_pipelines.h"
|
||||
#include "gdk_xg.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
/* The format a view has: its own, or the resource's when the view names none. */
|
||||
DXGI_FORMAT view_format(ID3D12Resource* host_resource, DXGI_FORMAT format) {
|
||||
if (format != DXGI_FORMAT_UNKNOWN || !host_resource) return format;
|
||||
return host_resource->GetDesc().Format;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void bx_note_console_format(DXGI_FORMAT format, const char* where) {
|
||||
static std::atomic<uint32_t> noted{0}; // one bit per console-only format
|
||||
const int f = static_cast<int>(format);
|
||||
@@ -91,23 +100,32 @@ D3D12_RESOURCE_DESC as_desc(const D3D12_RESOURCE_DESC1& d) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* Allocation info for descriptions that include a console texture layout. The console sizes come
|
||||
from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
|
||||
/* Descriptions the GDK's XG answers: an explicit console layout, or a texture left at
|
||||
D3D12_TEXTURE_LAYOUT_UNKNOWN, which selects the console's default tiling. A title sizes its loads
|
||||
from these answers (#708: a 128x4 RGBA16 texture is 16 KB in 4 KB tiles; the host's 4 KB answer
|
||||
made it request a quarter of the compressed chunk). Buffers and the PC layouts (row major,
|
||||
64 KB swizzles) keep the host's answer. */
|
||||
bool xg_sized(const D3D12_RESOURCE_DESC& desc) {
|
||||
return bx_is_console_texture_layout(desc) || bx_is_console_default_texture(desc);
|
||||
}
|
||||
|
||||
/* Allocation info for descriptions that include a console texture (xg_sized). The console sizes
|
||||
come from the GDK's XG (gdk_xg.h); other descriptions keep the host's answer, one at a time. The
|
||||
total follows Direct3D 12: each resource at its alignment, in order; the total alignment is the
|
||||
largest. Returns false (the host answers everything) when no description has a console layout
|
||||
largest. Returns false (the host answers everything) when no description is a console texture
|
||||
or XG is not loaded. */
|
||||
template <typename Desc>
|
||||
bool console_allocation(ID3D12Device* device, UINT mask, UINT count, const Desc* descs, D3D12_RESOURCE_ALLOCATION_INFO* total,
|
||||
D3D12_RESOURCE_ALLOCATION_INFO1* each, const char* method) {
|
||||
if (!descs || !count || !bx_gdk_xg_available()) return false;
|
||||
bool any = false;
|
||||
for (UINT i = 0; i < count && !any; ++i) any = bx_is_console_texture_layout(as_desc(descs[i]));
|
||||
for (UINT i = 0; i < count && !any; ++i) any = xg_sized(as_desc(descs[i]));
|
||||
if (!any) return false;
|
||||
uint64_t offset = 0, max_alignment = 0;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
const D3D12_RESOURCE_DESC desc = as_desc(descs[i]);
|
||||
uint64_t size = 0, alignment = 0;
|
||||
if (!bx_is_console_texture_layout(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
|
||||
if (!xg_sized(desc) || !bx_gdk_xg_layout_size(desc, &size, &alignment)) {
|
||||
D3D12_RESOURCE_DESC host = desc;
|
||||
if (bx_is_console_only_format(host.Format)) host.Format = bx_host_resource_format(host.Format);
|
||||
if (bx_is_console_texture_layout(host)) host.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
@@ -207,9 +225,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_shader_resource_view(void* self, ID
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateShaderResourceView");
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
host.of(desc, "CreateShaderResourceView"),
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc = host.of(desc, "CreateShaderResourceView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
|
||||
bx_console_mark_srv(dest.ptr, host_resource, host_desc);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_unordered_access_view(void* self, ID3D12Resource* resource, ID3D12Resource* counter,
|
||||
@@ -226,9 +245,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_render_target_view(void* self, ID3D
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRenderTargetView");
|
||||
BxHostFormat<D3D12_RENDER_TARGET_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
host.of(desc, "CreateRenderTargetView"),
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
|
||||
const D3D12_RENDER_TARGET_VIEW_DESC* host_desc = host.of(desc, "CreateRenderTargetView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateRenderTargetView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
|
||||
bx_console_rtv_created(bx_xbox_host_cpu_handle(dest).ptr, view_format(host_resource, host_desc ? host_desc->Format : DXGI_FORMAT_UNKNOWN));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D12Resource* resource,
|
||||
@@ -236,9 +256,10 @@ void STDMETHODCALLTYPE bx_xbox_device_create_depth_stencil_view(void* self, ID3D
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateDepthStencilView");
|
||||
BxHostFormat<D3D12_DEPTH_STENCIL_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(bx_xbox_unwrap_as<ID3D12Resource>(resource),
|
||||
host.of(desc, "CreateDepthStencilView"),
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
ID3D12Resource* host_resource = bx_xbox_unwrap_as<ID3D12Resource>(resource);
|
||||
const D3D12_DEPTH_STENCIL_VIEW_DESC* host_desc = host.of(desc, "CreateDepthStencilView");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateDepthStencilView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
|
||||
bx_console_dsv_created(bx_xbox_host_cpu_handle(dest).ptr, view_format(host_resource, host_desc ? host_desc->Format : DXGI_FORMAT_UNKNOWN));
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -0,0 +1,839 @@
|
||||
/*
|
||||
* Console graphics pipelines translated at first draw (#720). Opt-in: BX_CONSOLE_SHADERS=1.
|
||||
*
|
||||
* A title's pipelines carry console shaders (RDNA 2 code), which the shader gate refuses. A
|
||||
* refused stream pipeline that is a plain vertex/pixel pair is kept here with its stream. When
|
||||
* it is first drawn:
|
||||
* 1. bx_shader_bridge.dll translates the pair to HLSL (bx_shader_translate_pair);
|
||||
* 2. the HLSL is compiled to DXIL with dxcompiler.dll, the GDK's PC compiler that `bx-cli run`
|
||||
* stages beside the shims. Compiled shaders are kept on disk, named by the FNV-1a hash of
|
||||
* their source, so a later run compiles nothing it has seen and a translator change can
|
||||
* never reuse an old result;
|
||||
* 3. a host pipeline is created from the title's own stream with three substitutions: the two
|
||||
* shaders, the input layout the translated vertex shader expects, and the formats of the
|
||||
* render targets bound at the draw (the title binds targets whose formats differ from the
|
||||
* ones a pipeline was created for, and a Metal pipeline must match its attachments). One
|
||||
* host pipeline is kept per bound format set.
|
||||
* Translation happens at the draw and not at creation because a title creates far more
|
||||
* pipelines than it draws.
|
||||
*
|
||||
* Translated shaders read entry k of root parameter i's descriptor table as register k of space
|
||||
* 100 + i (b for constant buffers, t for textures), and sample with s0 of space 100. Every root
|
||||
* signature is therefore widened with those ranges, overlapping the title's own, and with one
|
||||
* static sampler. That sampler is linear and wrapping whatever the title asked for: the console
|
||||
* sampler a shader names is not decoded yet.
|
||||
*
|
||||
* Root signature layouts (#715). A console shader's root arguments are packed values in
|
||||
* root-parameter order, so which register holds which parameter depends on the parameter list
|
||||
* (docs/research/console-shader-abi.md). Each root signature's list is kept with its host object
|
||||
* and handed to the translator (bx_shader_translate_pair_rooted). Root CBVs, SRVs, UAVs and
|
||||
* constants are then declared at the title's own registers, which the root signature already
|
||||
* has; only descriptor tables need the widening above.
|
||||
*
|
||||
* Not handled here, and logged when met: pipelines with other stages, stream output or view
|
||||
* instancing; table entries beyond the widened range.
|
||||
*/
|
||||
#include "console_pipelines.h"
|
||||
|
||||
#include "console_formats.h"
|
||||
#include "proxy.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_shader_bridge.h"
|
||||
|
||||
#include <dxcapi.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kWidenedEntries = 8; // registers 0..7 of each widened space
|
||||
constexpr UINT kFirstSpace = 100; // space of root parameter 0's table
|
||||
|
||||
bool env_is_one(const char* name) {
|
||||
char value[8] = {};
|
||||
const DWORD n = GetEnvironmentVariableA(name, value, sizeof(value));
|
||||
return n == 1 && value[0] == '1';
|
||||
}
|
||||
|
||||
void log(bx_log_level_t level, const char* event, const char* fmt, ...) {
|
||||
char detail[700];
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
std::vsnprintf(detail, sizeof(detail), fmt, args);
|
||||
va_end(args);
|
||||
bx_log_emit(level, "d3d12_xs", event, detail);
|
||||
}
|
||||
|
||||
/* Logs the 1st, 2nd, 4th, ... occurrence, with the running total. */
|
||||
bool sampled(std::atomic<uint64_t>& counter, uint64_t* total) {
|
||||
*total = ++counter;
|
||||
return (*total & (*total - 1)) == 0;
|
||||
}
|
||||
|
||||
uint64_t fnv1a64(const void* data, size_t size) {
|
||||
uint64_t h = 14695981039346656037ull;
|
||||
for (size_t i = 0; i < size; ++i) h = (h ^ static_cast<const uint8_t*>(data)[i]) * 1099511628211ull;
|
||||
return h;
|
||||
}
|
||||
|
||||
/* A library beside d3d12_xs.dll, where bx-cli stages the bridge and the compiler; otherwise by
|
||||
the process's search path (a shim loaded from the executable's own folder is not in the staged
|
||||
one). */
|
||||
HMODULE load_beside(const wchar_t* name) {
|
||||
HMODULE self = nullptr;
|
||||
wchar_t path[MAX_PATH];
|
||||
if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
|
||||
reinterpret_cast<LPCWSTR>(&load_beside), &self)) {
|
||||
const DWORD length = GetModuleFileNameW(self, path, MAX_PATH);
|
||||
wchar_t* slash = length && length < MAX_PATH ? std::wcsrchr(path, L'\\') : nullptr;
|
||||
if (slash && static_cast<size_t>(slash + 1 - path) + std::wcslen(name) + 1 <= MAX_PATH) {
|
||||
std::wcscpy(slash + 1, name);
|
||||
if (HMODULE module = LoadLibraryExW(path, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH)) return module;
|
||||
}
|
||||
}
|
||||
return LoadLibraryW(name);
|
||||
}
|
||||
|
||||
/* ---- Translation and compilation -------------------------------------------------------- */
|
||||
|
||||
using TranslateFn = bx_shader_status_t (*)(const uint8_t*, size_t, const uint8_t*, size_t, bx_shader_pair_translation_t*);
|
||||
using FreeTranslationFn = void (*)(bx_shader_pair_translation_t*);
|
||||
using TranslateRootedFn = bx_shader_status_t (*)(const uint8_t*, size_t, const uint8_t*, size_t, const bx_shader_root_layout_t*,
|
||||
bx_shader_pair_translation_t*);
|
||||
|
||||
struct Tools {
|
||||
TranslateFn translate = nullptr;
|
||||
TranslateRootedFn translate_rooted = nullptr; // absent in an older bridge: every parameter is then taken for a table
|
||||
FreeTranslationFn release = nullptr;
|
||||
DxcCreateInstanceProc dxc = nullptr;
|
||||
};
|
||||
|
||||
const Tools& tools() {
|
||||
static const Tools loaded = [] {
|
||||
Tools t;
|
||||
if (HMODULE bridge = load_beside(L"bx_shader_bridge.dll")) {
|
||||
t.translate = reinterpret_cast<TranslateFn>(reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_translate_pair")));
|
||||
t.release = reinterpret_cast<FreeTranslationFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_free_pair_translation")));
|
||||
t.translate_rooted = reinterpret_cast<TranslateRootedFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(bridge, "bx_shader_translate_pair_rooted")));
|
||||
}
|
||||
if (HMODULE dxc = load_beside(L"dxcompiler.dll")) {
|
||||
t.dxc = reinterpret_cast<DxcCreateInstanceProc>(reinterpret_cast<void*>(GetProcAddress(dxc, "DxcCreateInstance")));
|
||||
}
|
||||
if (!t.translate || !t.release) {
|
||||
log(BX_LOG_WARN, "console_shaders", "bx_shader_bridge.dll has no bx_shader_translate_pair; console pipelines stay undrawn");
|
||||
}
|
||||
if (!t.dxc) {
|
||||
log(BX_LOG_WARN, "console_shaders",
|
||||
"dxcompiler.dll not found (bx-cli run stages the GDK's for the target build, or with "
|
||||
"--gdk-libraries); console pipelines stay undrawn");
|
||||
}
|
||||
return t;
|
||||
}();
|
||||
return loaded;
|
||||
}
|
||||
|
||||
/* The folder compiled shaders are kept in: BX_SHADER_CACHE, or
|
||||
%LOCALAPPDATA%\BetterXen\shader-cache. Empty when neither can be made. */
|
||||
const std::string& cache_folder() {
|
||||
static const std::string folder = [] {
|
||||
char value[MAX_PATH] = {};
|
||||
DWORD n = GetEnvironmentVariableA("BX_SHADER_CACHE", value, sizeof(value));
|
||||
std::string path;
|
||||
if (n > 0 && n < sizeof(value)) {
|
||||
path = value;
|
||||
} else {
|
||||
n = GetEnvironmentVariableA("LOCALAPPDATA", value, sizeof(value));
|
||||
if (n == 0 || n >= sizeof(value)) return std::string();
|
||||
path = std::string(value) + "\\BetterXen";
|
||||
CreateDirectoryA(path.c_str(), nullptr);
|
||||
path += "\\shader-cache";
|
||||
}
|
||||
CreateDirectoryA(path.c_str(), nullptr);
|
||||
const DWORD attributes = GetFileAttributesA(path.c_str());
|
||||
if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
|
||||
log(BX_LOG_WARN, "console_shaders", "shader cache folder cannot be created; shaders are compiled every run");
|
||||
return std::string();
|
||||
}
|
||||
return path;
|
||||
}();
|
||||
return folder;
|
||||
}
|
||||
|
||||
bool read_file(const std::string& path, std::vector<uint8_t>& out) {
|
||||
HANDLE file = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file == INVALID_HANDLE_VALUE) return false;
|
||||
LARGE_INTEGER size{};
|
||||
bool ok = GetFileSizeEx(file, &size) && size.QuadPart > 0 && size.QuadPart < (64ll << 20);
|
||||
if (ok) {
|
||||
out.resize(static_cast<size_t>(size.QuadPart));
|
||||
DWORD got = 0;
|
||||
ok = ReadFile(file, out.data(), static_cast<DWORD>(out.size()), &got, nullptr) && got == out.size();
|
||||
}
|
||||
CloseHandle(file);
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* Writes through a temporary name, so a reader never sees half a file. */
|
||||
void write_file(const std::string& path, const void* data, size_t size) {
|
||||
char temporary[MAX_PATH + 32];
|
||||
std::snprintf(temporary, sizeof(temporary), "%s.%lu.tmp", path.c_str(), static_cast<unsigned long>(GetCurrentThreadId()));
|
||||
HANDLE file = CreateFileA(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (file == INVALID_HANDLE_VALUE) return;
|
||||
DWORD put = 0;
|
||||
const bool ok = WriteFile(file, data, static_cast<DWORD>(size), &put, nullptr) && put == size;
|
||||
CloseHandle(file);
|
||||
if (!ok || !MoveFileExA(temporary, path.c_str(), MOVEFILE_REPLACE_EXISTING)) DeleteFileA(temporary);
|
||||
}
|
||||
|
||||
std::atomic<uint64_t> g_compiled{0};
|
||||
std::atomic<uint64_t> g_from_cache{0};
|
||||
|
||||
/* HLSL to DXIL (entry `main`), from the disk cache when this source was compiled before. */
|
||||
bool compile(const uint8_t* source, size_t size, bool pixel, std::vector<uint8_t>& out, std::string& why) {
|
||||
char name[48];
|
||||
std::snprintf(name, sizeof(name), "\\%016llx.%s.dxil", static_cast<unsigned long long>(fnv1a64(source, size)), pixel ? "ps" : "vs");
|
||||
const std::string cached = cache_folder().empty() ? std::string() : cache_folder() + name;
|
||||
if (!cached.empty() && read_file(cached, out)) {
|
||||
++g_from_cache;
|
||||
return true;
|
||||
}
|
||||
const Tools& t = tools();
|
||||
if (!t.dxc) {
|
||||
why = "no dxcompiler.dll";
|
||||
return false;
|
||||
}
|
||||
IDxcCompiler3* compiler = nullptr;
|
||||
HRESULT hr = t.dxc(CLSID_DxcCompiler, __uuidof(IDxcCompiler3), reinterpret_cast<void**>(&compiler));
|
||||
if (FAILED(hr) || !compiler) {
|
||||
why = "DxcCreateInstance failed";
|
||||
return false;
|
||||
}
|
||||
const DxcBuffer buffer{source, size, DXC_CP_UTF8};
|
||||
LPCWSTR arguments[] = {L"-T", pixel ? L"ps_6_0" : L"vs_6_0", L"-E", L"main"};
|
||||
IDxcResult* result = nullptr;
|
||||
hr = compiler->Compile(&buffer, arguments, 4, nullptr, __uuidof(IDxcResult), reinterpret_cast<void**>(&result));
|
||||
HRESULT status = hr;
|
||||
if (SUCCEEDED(hr) && result) result->GetStatus(&status);
|
||||
bool ok = false;
|
||||
if (SUCCEEDED(status) && result) {
|
||||
IDxcBlob* code = nullptr;
|
||||
if (SUCCEEDED(result->GetResult(&code)) && code && code->GetBufferSize()) {
|
||||
const auto* bytes = static_cast<const uint8_t*>(code->GetBufferPointer());
|
||||
out.assign(bytes, bytes + code->GetBufferSize());
|
||||
ok = true;
|
||||
}
|
||||
if (code) code->Release();
|
||||
}
|
||||
if (!ok) {
|
||||
why = "the compiler refused the translated source";
|
||||
IDxcBlobEncoding* errors = nullptr;
|
||||
if (result && SUCCEEDED(result->GetErrorBuffer(&errors)) && errors && errors->GetBufferSize()) {
|
||||
why += ": ";
|
||||
why.append(static_cast<const char*>(errors->GetBufferPointer()), errors->GetBufferSize() < 300 ? errors->GetBufferSize() : 300);
|
||||
}
|
||||
if (errors) errors->Release();
|
||||
}
|
||||
if (result) result->Release();
|
||||
compiler->Release();
|
||||
if (ok) {
|
||||
++g_compiled;
|
||||
if (!cached.empty()) write_file(cached, out.data(), out.size());
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
/* ---- Render targets bound per list ------------------------------------------------------- */
|
||||
|
||||
struct Targets {
|
||||
bool known = false;
|
||||
UINT count = 0;
|
||||
DXGI_FORMAT rtv[8] = {};
|
||||
DXGI_FORMAT dsv = DXGI_FORMAT_UNKNOWN;
|
||||
};
|
||||
|
||||
std::mutex g_target_lock;
|
||||
std::unordered_map<SIZE_T, DXGI_FORMAT> g_rtv_formats;
|
||||
std::unordered_map<SIZE_T, DXGI_FORMAT> g_dsv_formats;
|
||||
std::unordered_map<const void*, Targets> g_list_targets;
|
||||
|
||||
/* ---- Root signatures ----------------------------------------------------------------------- */
|
||||
|
||||
using DeserializerFn = HRESULT(WINAPI*)(LPCVOID, SIZE_T, REFIID, void**);
|
||||
using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**);
|
||||
|
||||
template <typename Fn>
|
||||
Fn host_d3d12(const char* name) {
|
||||
HMODULE d3d12 = LoadLibraryA("d3d12.dll");
|
||||
return d3d12 ? reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(d3d12, name))) : nullptr;
|
||||
}
|
||||
|
||||
/* What the translator needs to know about a root signature: its parameters and flags. */
|
||||
struct RootLayout {
|
||||
std::vector<bx_shader_root_parameter_t> parameters;
|
||||
UINT flags = 0;
|
||||
};
|
||||
|
||||
std::mutex g_root_lock;
|
||||
std::unordered_map<const void*, std::shared_ptr<RootLayout>> g_root_layouts; // by host root signature
|
||||
|
||||
/* The layout of a serialized root signature, or nullptr when it cannot be read. */
|
||||
std::shared_ptr<RootLayout> read_layout(const void* blob, size_t size) {
|
||||
static const DeserializerFn deserialize = host_d3d12<DeserializerFn>("D3D12CreateVersionedRootSignatureDeserializer");
|
||||
if (!deserialize || !blob || !size) return nullptr;
|
||||
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
|
||||
if (FAILED(deserialize(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
|
||||
return nullptr;
|
||||
}
|
||||
std::shared_ptr<RootLayout> layout;
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
|
||||
if (SUCCEEDED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) && v) {
|
||||
layout = std::make_shared<RootLayout>();
|
||||
layout->flags = static_cast<UINT>(v->Desc_1_1.Flags);
|
||||
for (UINT i = 0; i < v->Desc_1_1.NumParameters; ++i) {
|
||||
const D3D12_ROOT_PARAMETER1& p = v->Desc_1_1.pParameters[i];
|
||||
bx_shader_root_parameter_t out{};
|
||||
out.type = static_cast<uint32_t>(p.ParameterType);
|
||||
if (p.ParameterType == D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS) {
|
||||
out.num_32bit_values = p.Constants.Num32BitValues;
|
||||
out.shader_register = p.Constants.ShaderRegister;
|
||||
out.register_space = p.Constants.RegisterSpace;
|
||||
} else if (p.ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) {
|
||||
out.shader_register = p.Descriptor.ShaderRegister;
|
||||
out.register_space = p.Descriptor.RegisterSpace;
|
||||
}
|
||||
layout->parameters.push_back(out);
|
||||
}
|
||||
}
|
||||
d->Release();
|
||||
return layout;
|
||||
}
|
||||
|
||||
/* The title's root signature with the translated shaders' ranges and sampler added, or nullptr. */
|
||||
ID3DBlob* widen(const void* blob, size_t size) {
|
||||
static const DeserializerFn deserialize = host_d3d12<DeserializerFn>("D3D12CreateVersionedRootSignatureDeserializer");
|
||||
static const SerializeFn serialize = host_d3d12<SerializeFn>("D3D12SerializeVersionedRootSignature");
|
||||
if (!deserialize || !serialize) return nullptr;
|
||||
ID3D12VersionedRootSignatureDeserializer* d = nullptr;
|
||||
if (FAILED(deserialize(blob, size, __uuidof(ID3D12VersionedRootSignatureDeserializer), reinterpret_cast<void**>(&d))) || !d) {
|
||||
return nullptr;
|
||||
}
|
||||
const D3D12_VERSIONED_ROOT_SIGNATURE_DESC* v = nullptr;
|
||||
ID3DBlob* out = nullptr;
|
||||
if (SUCCEEDED(d->GetRootSignatureDescAtVersion(D3D_ROOT_SIGNATURE_VERSION_1_1, &v)) && v) {
|
||||
const D3D12_ROOT_SIGNATURE_DESC1& src = v->Desc_1_1;
|
||||
std::vector<D3D12_ROOT_PARAMETER1> params(src.pParameters, src.pParameters + src.NumParameters);
|
||||
std::vector<std::vector<D3D12_DESCRIPTOR_RANGE1>> ranges(params.size());
|
||||
for (size_t i = 0; i < params.size(); ++i) {
|
||||
if (params[i].ParameterType != D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE) continue;
|
||||
const auto& table = params[i].DescriptorTable;
|
||||
if (table.NumDescriptorRanges && table.pDescriptorRanges[0].RangeType == D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) continue;
|
||||
ranges[i].assign(table.pDescriptorRanges, table.pDescriptorRanges + table.NumDescriptorRanges);
|
||||
for (D3D12_DESCRIPTOR_RANGE_TYPE type : {D3D12_DESCRIPTOR_RANGE_TYPE_CBV, D3D12_DESCRIPTOR_RANGE_TYPE_SRV}) {
|
||||
D3D12_DESCRIPTOR_RANGE1 r{};
|
||||
r.RangeType = type;
|
||||
r.NumDescriptors = kWidenedEntries;
|
||||
r.BaseShaderRegister = 0;
|
||||
r.RegisterSpace = kFirstSpace + static_cast<UINT>(i);
|
||||
r.Flags = D3D12_DESCRIPTOR_RANGE_FLAG_DESCRIPTORS_VOLATILE | D3D12_DESCRIPTOR_RANGE_FLAG_DATA_VOLATILE;
|
||||
r.OffsetInDescriptorsFromTableStart = 0;
|
||||
ranges[i].push_back(r);
|
||||
}
|
||||
params[i].DescriptorTable.NumDescriptorRanges = static_cast<UINT>(ranges[i].size());
|
||||
params[i].DescriptorTable.pDescriptorRanges = ranges[i].data();
|
||||
}
|
||||
std::vector<D3D12_STATIC_SAMPLER_DESC> samplers(src.pStaticSamplers, src.pStaticSamplers + src.NumStaticSamplers);
|
||||
D3D12_STATIC_SAMPLER_DESC s{};
|
||||
s.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR;
|
||||
s.AddressU = s.AddressV = s.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP;
|
||||
s.MaxLOD = D3D12_FLOAT32_MAX;
|
||||
s.ComparisonFunc = D3D12_COMPARISON_FUNC_NEVER;
|
||||
s.ShaderRegister = 0;
|
||||
s.RegisterSpace = kFirstSpace;
|
||||
s.ShaderVisibility = D3D12_SHADER_VISIBILITY_ALL;
|
||||
samplers.push_back(s);
|
||||
D3D12_VERSIONED_ROOT_SIGNATURE_DESC wide{};
|
||||
wide.Version = D3D_ROOT_SIGNATURE_VERSION_1_1;
|
||||
wide.Desc_1_1 = src;
|
||||
wide.Desc_1_1.NumParameters = static_cast<UINT>(params.size());
|
||||
wide.Desc_1_1.pParameters = params.data();
|
||||
wide.Desc_1_1.NumStaticSamplers = static_cast<UINT>(samplers.size());
|
||||
wide.Desc_1_1.pStaticSamplers = samplers.data();
|
||||
ID3DBlob* errors = nullptr;
|
||||
if (FAILED(serialize(&wide, &out, &errors))) out = nullptr;
|
||||
if (errors) errors->Release();
|
||||
}
|
||||
d->Release();
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_console_compile_hlsl(const char* source, bool pixel, std::vector<uint8_t>& out, std::string& why) {
|
||||
return compile(reinterpret_cast<const uint8_t*>(source), std::strlen(source), pixel, out, why);
|
||||
}
|
||||
|
||||
bool bx_console_shaders_enabled() {
|
||||
static const bool enabled = [] {
|
||||
const bool on = env_is_one("BX_CONSOLE_SHADERS");
|
||||
if (on) log(BX_LOG_INFO, "console_shaders", "enabled: refused vertex/pixel pipelines are translated when first drawn");
|
||||
return on;
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
namespace {
|
||||
/* Keeps the layout of the title's blob with the host root signature just created from it. */
|
||||
void remember_layout(void* host_root, const void* blob, size_t size) {
|
||||
std::shared_ptr<RootLayout> layout = read_layout(blob, size);
|
||||
std::lock_guard<std::mutex> guard(g_root_lock);
|
||||
if (layout) {
|
||||
g_root_layouts[host_root] = std::move(layout);
|
||||
} else {
|
||||
g_root_layouts.erase(host_root); // an address reused by a signature that cannot be read
|
||||
}
|
||||
}
|
||||
} // namespace
|
||||
|
||||
HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, const void* blob, SIZE_T size, REFIID riid,
|
||||
void** ppv) {
|
||||
if (bx_console_shaders_enabled() && blob && size) {
|
||||
static std::atomic<uint64_t> refused{0};
|
||||
ID3DBlob* wide = widen(blob, size);
|
||||
if (wide) {
|
||||
const HRESULT hr = device->CreateRootSignature(node_mask, wide->GetBufferPointer(), wide->GetBufferSize(), riid, ppv);
|
||||
wide->Release();
|
||||
if (SUCCEEDED(hr)) {
|
||||
remember_layout(*ppv, blob, size);
|
||||
return hr;
|
||||
}
|
||||
}
|
||||
uint64_t total = 0;
|
||||
if (sampled(refused, &total)) {
|
||||
log(BX_LOG_WARN, "console_root_signature",
|
||||
"a root signature could not be widened for translated shaders (%s); the title's own is used; total=%llu",
|
||||
wide ? "the host refused the widened form" : "it could not be read or serialized", static_cast<unsigned long long>(total));
|
||||
}
|
||||
const HRESULT hr = device->CreateRootSignature(node_mask, blob, size, riid, ppv);
|
||||
if (SUCCEEDED(hr)) remember_layout(*ppv, blob, size);
|
||||
return hr;
|
||||
}
|
||||
return device->CreateRootSignature(node_mask, blob, size, riid, ppv);
|
||||
}
|
||||
|
||||
/* ---- Pipelines --------------------------------------------------------------------------- */
|
||||
|
||||
struct BxConsolePipeline {
|
||||
ID3D12Device2* device = nullptr; // referenced
|
||||
ID3D12RootSignature* root = nullptr; // host object, referenced
|
||||
std::vector<uint8_t> stream; // host stream, shader slots patched per variant
|
||||
size_t vs_at = SIZE_MAX, ps_at = SIZE_MAX, layout_at = SIZE_MAX, rt_at = SIZE_MAX, ds_at = SIZE_MAX;
|
||||
std::vector<uint8_t> vs_code, ps_code; // the title's stages
|
||||
std::vector<D3D12_INPUT_ELEMENT_DESC> title_elements;
|
||||
std::vector<std::pair<std::string, UINT>> title_semantics; // each element's semantic name and index
|
||||
|
||||
std::mutex lock;
|
||||
enum class State { Untried, Ready, Failed } state = State::Untried;
|
||||
char key[40] = {};
|
||||
std::vector<uint8_t> vs_dxil, ps_dxil;
|
||||
std::vector<D3D12_INPUT_ELEMENT_DESC> elements; // the host input layout
|
||||
std::vector<BxConsoleUse> uses; // table entries the shaders read
|
||||
std::unordered_map<std::string, ID3D12PipelineState*> variants;
|
||||
|
||||
~BxConsolePipeline() {
|
||||
for (auto& v : variants) {
|
||||
if (v.second) v.second->Release();
|
||||
}
|
||||
if (root) root->Release();
|
||||
if (device) device->Release();
|
||||
}
|
||||
};
|
||||
|
||||
/* One element of a shader's input signature (DXBC ISGN or ISG1 chunk). */
|
||||
struct SignatureInput {
|
||||
std::string name;
|
||||
UINT index = 0;
|
||||
UINT system_value = 0;
|
||||
UINT reg = 0;
|
||||
};
|
||||
|
||||
/* The input signature of a shader container, or false if it has none (or it is malformed). */
|
||||
bool input_signature(const std::vector<uint8_t>& code, std::vector<SignatureInput>* out) {
|
||||
auto u32 = [&](size_t at, uint32_t* v) {
|
||||
if (at + 4 > code.size()) return false;
|
||||
std::memcpy(v, &code[at], 4);
|
||||
return true;
|
||||
};
|
||||
uint32_t chunks = 0;
|
||||
if (code.size() < 32 || std::memcmp(code.data(), "DXBC", 4) != 0 || !u32(28, &chunks)) return false;
|
||||
for (uint32_t c = 0; c < chunks; ++c) {
|
||||
uint32_t at = 0, size = 0;
|
||||
if (!u32(32 + 4 * c, &at) || !u32(at + 4, &size) || at + 8ull + size > code.size()) return false;
|
||||
const bool v1 = std::memcmp(&code[at], "ISG1", 4) == 0;
|
||||
if (!v1 && std::memcmp(&code[at], "ISGN", 4) != 0) continue;
|
||||
const size_t base = at + 8, stride = v1 ? 32 : 24;
|
||||
uint32_t count = 0;
|
||||
if (!u32(base, &count) || 8 + count * stride > size) return false;
|
||||
out->clear();
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
const size_t e = base + 8 + i * stride + (v1 ? 4 : 0); // ISG1 begins each element with its stream
|
||||
uint32_t name = 0, index = 0, sv = 0, reg = 0;
|
||||
if (!u32(e, &name) || !u32(e + 4, &index) || !u32(e + 8, &sv) || !u32(e + 16, ®) || name >= size) return false;
|
||||
const char* text = reinterpret_cast<const char*>(&code[base + name]);
|
||||
const size_t len = strnlen(text, size - name);
|
||||
if (len == size - name) return false;
|
||||
out->push_back({std::string(text, len), index, sv, reg});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/*
|
||||
* The host input layout of a translated pipeline. The translated vertex shader reads its fetched
|
||||
* attributes as ATTR<r>, r being the input register (attribute r is in v[4 + 4r] on the console).
|
||||
* Direct3D 12 links input elements to vertex-shader inputs by semantic name (case-insensitive) and
|
||||
* index, not by their order in the layout, so each register gets the title's element whose semantic
|
||||
* is the one the shader's input signature gives that register. A container without a signature
|
||||
* keeps the elements in layout order. Returns why the pipeline cannot be drawn, or "".
|
||||
*/
|
||||
std::string bind_inputs(BxConsolePipeline& p, unsigned fetch) {
|
||||
std::vector<SignatureInput> signature;
|
||||
if (!input_signature(p.vs_code, &signature)) {
|
||||
p.elements.assign(p.title_elements.begin(), p.title_elements.begin() + fetch);
|
||||
return {};
|
||||
}
|
||||
p.elements.clear();
|
||||
for (unsigned r = 0; r < fetch; ++r) {
|
||||
const SignatureInput* input = nullptr;
|
||||
for (const SignatureInput& s : signature) {
|
||||
if (s.reg == r && s.system_value == 0) input = &s;
|
||||
}
|
||||
if (!input) return "the vertex shader fetches input register " + std::to_string(r) + ", which its signature does not name";
|
||||
size_t k = 0;
|
||||
while (k < p.title_semantics.size() && !(p.title_semantics[k].second == input->index &&
|
||||
_stricmp(p.title_semantics[k].first.c_str(), input->name.c_str()) == 0)) {
|
||||
++k;
|
||||
}
|
||||
if (k == p.title_semantics.size()) {
|
||||
return "the input layout has no element for the vertex shader's " + input->name + std::to_string(input->index);
|
||||
}
|
||||
D3D12_INPUT_ELEMENT_DESC e = p.title_elements[k];
|
||||
e.SemanticIndex = r;
|
||||
p.elements.push_back(e);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
|
||||
std::shared_ptr<BxConsolePipeline> bx_console_pipeline_create(ID3D12Device* device, const std::vector<uint8_t>& stream,
|
||||
const std::vector<size_t>& stage_offsets,
|
||||
const std::vector<const char*>& stage_names, size_t root_offset) {
|
||||
if (!bx_console_shaders_enabled() || !device || root_offset == SIZE_MAX) return nullptr;
|
||||
auto p = std::make_shared<BxConsolePipeline>();
|
||||
const char* unsupported = nullptr;
|
||||
for (size_t i = 0; i < stage_offsets.size(); ++i) {
|
||||
D3D12_SHADER_BYTECODE code{};
|
||||
std::memcpy(&code, &stream[stage_offsets[i]], sizeof(code));
|
||||
if (!code.pShaderBytecode || !code.BytecodeLength) continue;
|
||||
const auto* bytes = static_cast<const uint8_t*>(code.pShaderBytecode);
|
||||
if (std::strcmp(stage_names[i], "VS") == 0) {
|
||||
p->vs_at = stage_offsets[i];
|
||||
p->vs_code.assign(bytes, bytes + code.BytecodeLength);
|
||||
} else if (std::strcmp(stage_names[i], "PS") == 0) {
|
||||
p->ps_at = stage_offsets[i];
|
||||
p->ps_code.assign(bytes, bytes + code.BytecodeLength);
|
||||
} else {
|
||||
unsupported = "a stage other than vertex and pixel";
|
||||
}
|
||||
}
|
||||
if (!unsupported && (p->vs_code.empty() || p->ps_code.empty())) unsupported = "no vertex/pixel pair";
|
||||
const size_t so_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_STREAM_OUTPUT);
|
||||
if (so_at != SIZE_MAX) {
|
||||
D3D12_STREAM_OUTPUT_DESC so{};
|
||||
std::memcpy(&so, &stream[so_at], sizeof(so));
|
||||
if (so.NumEntries || so.NumStrides) unsupported = "stream output";
|
||||
}
|
||||
const size_t vi_at = bx_stream_payload(stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_VIEW_INSTANCING);
|
||||
if (vi_at != SIZE_MAX) {
|
||||
D3D12_VIEW_INSTANCING_DESC vi{};
|
||||
std::memcpy(&vi, &stream[vi_at], sizeof(vi));
|
||||
if (vi.ViewInstanceCount) unsupported = "view instancing";
|
||||
}
|
||||
if (unsupported) {
|
||||
static std::atomic<uint64_t> skipped{0};
|
||||
uint64_t total = 0;
|
||||
if (sampled(skipped, &total)) {
|
||||
log(BX_LOG_WARN, "console_pipeline", "a refused pipeline is not translated: %s; total=%llu", unsupported,
|
||||
static_cast<unsigned long long>(total));
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
if (FAILED(device->QueryInterface(__uuidof(ID3D12Device2), reinterpret_cast<void**>(&p->device)))) return nullptr;
|
||||
p->stream = stream;
|
||||
// A cached blob belongs to the title's console pipeline, never to the host's.
|
||||
const size_t cached_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CACHED_PSO);
|
||||
if (cached_at != SIZE_MAX) std::memset(&p->stream[cached_at], 0, sizeof(D3D12_CACHED_PIPELINE_STATE));
|
||||
std::memcpy(&p->root, &p->stream[root_offset], sizeof(p->root));
|
||||
if (!p->root) return nullptr;
|
||||
p->root->AddRef();
|
||||
p->layout_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_INPUT_LAYOUT);
|
||||
if (p->layout_at != SIZE_MAX) {
|
||||
D3D12_INPUT_LAYOUT_DESC layout{};
|
||||
std::memcpy(&layout, &p->stream[p->layout_at], sizeof(layout));
|
||||
for (UINT k = 0; layout.pInputElementDescs && k < layout.NumElements; ++k) {
|
||||
// The translated vertex shader names its inputs ATTR<k> in element order. The title's
|
||||
// semantic names are not kept: their strings need not outlive the creation call.
|
||||
D3D12_INPUT_ELEMENT_DESC e = layout.pInputElementDescs[k];
|
||||
p->title_semantics.emplace_back(e.SemanticName ? e.SemanticName : "", e.SemanticIndex);
|
||||
e.SemanticName = "ATTR";
|
||||
e.SemanticIndex = k;
|
||||
e.Format = bx_host_format(e.Format);
|
||||
p->title_elements.push_back(e);
|
||||
}
|
||||
}
|
||||
p->rt_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_RENDER_TARGET_FORMATS);
|
||||
if (p->rt_at != SIZE_MAX) {
|
||||
D3D12_RT_FORMAT_ARRAY formats{};
|
||||
std::memcpy(&formats, &p->stream[p->rt_at], sizeof(formats));
|
||||
for (DXGI_FORMAT& f : formats.RTFormats) f = bx_host_format(f);
|
||||
std::memcpy(&p->stream[p->rt_at], &formats, sizeof(formats));
|
||||
}
|
||||
p->ds_at = bx_stream_payload(p->stream, D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_DEPTH_STENCIL_FORMAT);
|
||||
if (p->ds_at != SIZE_MAX) {
|
||||
DXGI_FORMAT depth{};
|
||||
std::memcpy(&depth, &p->stream[p->ds_at], sizeof(depth));
|
||||
depth = bx_host_format(depth);
|
||||
std::memcpy(&p->stream[p->ds_at], &depth, sizeof(depth));
|
||||
}
|
||||
std::snprintf(p->key, sizeof(p->key), "%016llx_%016llx", static_cast<unsigned long long>(fnv1a64(p->vs_code.data(), p->vs_code.size())),
|
||||
static_cast<unsigned long long>(fnv1a64(p->ps_code.data(), p->ps_code.size())));
|
||||
return p;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::atomic<uint64_t> g_translated{0};
|
||||
std::atomic<uint64_t> g_untranslated{0};
|
||||
|
||||
/* Translates and compiles the pair, and builds the host input layout. Called once, locked. */
|
||||
void prepare(BxConsolePipeline* p) {
|
||||
p->state = BxConsolePipeline::State::Failed;
|
||||
const Tools& t = tools();
|
||||
uint64_t total = 0;
|
||||
if (!t.translate || !t.release) return;
|
||||
const ULONGLONG started = GetTickCount64();
|
||||
bx_shader_pair_translation_t out{};
|
||||
// With the root signature's layout when both sides have it; otherwise as a signature of tables.
|
||||
std::shared_ptr<RootLayout> root;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_root_lock);
|
||||
auto it = g_root_layouts.find(p->root);
|
||||
if (it != g_root_layouts.end()) root = it->second;
|
||||
}
|
||||
bx_shader_status_t status;
|
||||
if (root && t.translate_rooted) {
|
||||
const bx_shader_root_layout_t layout{root->parameters.data(), static_cast<uint32_t>(root->parameters.size()), root->flags};
|
||||
status = t.translate_rooted(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &layout, &out);
|
||||
} else {
|
||||
status = t.translate(p->vs_code.data(), p->vs_code.size(), p->ps_code.data(), p->ps_code.size(), &out);
|
||||
}
|
||||
std::string why;
|
||||
if (status == BX_SHADER_OK) {
|
||||
const std::string layout(reinterpret_cast<const char*>(out.layout), out.layout_len);
|
||||
const uint64_t before = g_compiled.load();
|
||||
const bool compiled = compile(out.vs_hlsl, out.vs_hlsl_len, false, p->vs_dxil, why) &&
|
||||
compile(out.ps_hlsl, out.ps_hlsl_len, true, p->ps_dxil, why);
|
||||
unsigned fetch = 0;
|
||||
bool fetched = false;
|
||||
for (size_t at = 0; compiled && at < layout.size();) {
|
||||
const size_t end = layout.find('\n', at);
|
||||
const std::string line = layout.substr(at, end == std::string::npos ? std::string::npos : end - at);
|
||||
at = end == std::string::npos ? layout.size() : end + 1;
|
||||
unsigned a = 0, b = 0, c = 0, d = 0;
|
||||
char kind[8] = {};
|
||||
if (std::sscanf(line.c_str(), "FETCH %u", &fetch) == 1) {
|
||||
fetched = true;
|
||||
} else if (std::sscanf(line.c_str(), "ATTR %u %u %u %u", &a, &b, &c, &d) == 4) {
|
||||
D3D12_INPUT_ELEMENT_DESC e{};
|
||||
e.SemanticName = "ATTR";
|
||||
e.SemanticIndex = a;
|
||||
e.Format = static_cast<DXGI_FORMAT>(b);
|
||||
e.InputSlot = c;
|
||||
e.AlignedByteOffset = d;
|
||||
e.InputSlotClass = D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA;
|
||||
p->elements.push_back(e);
|
||||
} else if (std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) >= 2 &&
|
||||
(std::strcmp(kind, "CB") == 0 || std::strcmp(kind, "TEX") == 0)) {
|
||||
// Only CB and TEX lines name descriptor-table entries. `USE ROOT <parameter>` is a
|
||||
// root constants or root descriptor parameter, which the host root signature binds
|
||||
// as it is (abi/include/bx_shader_bridge.h); other kinds are ignored.
|
||||
const int numbers = std::sscanf(line.c_str(), "USE %7s %u %u", kind, &a, &b) - 1;
|
||||
const unsigned entry = numbers == 2 ? b : a;
|
||||
p->uses.push_back({std::strcmp(kind, "TEX") == 0, numbers == 2 ? a : 0, entry});
|
||||
if (entry >= kWidenedEntries) {
|
||||
char text[96];
|
||||
std::snprintf(text, sizeof(text), "it reads table entry %u, beyond the %u widened ones", entry, kWidenedEntries);
|
||||
why = text;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (compiled && why.empty() && fetched) {
|
||||
if (fetch > p->title_elements.size()) {
|
||||
char text[96];
|
||||
std::snprintf(text, sizeof(text), "the vertex shader fetches %u attributes, the pipeline has %zu", fetch,
|
||||
p->title_elements.size());
|
||||
why = text;
|
||||
} else {
|
||||
why = bind_inputs(*p, fetch);
|
||||
}
|
||||
}
|
||||
if (compiled && why.empty()) {
|
||||
p->state = BxConsolePipeline::State::Ready;
|
||||
if (sampled(g_translated, &total)) {
|
||||
log(BX_LOG_INFO, "console_pipeline", "pipeline %s translated in %llu ms (%s); total=%llu, compiled=%llu, from cache=%llu",
|
||||
p->key, static_cast<unsigned long long>(GetTickCount64() - started),
|
||||
g_compiled.load() == before ? "shaders from the disk cache" : "compiled", static_cast<unsigned long long>(total),
|
||||
static_cast<unsigned long long>(g_compiled.load()), static_cast<unsigned long long>(g_from_cache.load()));
|
||||
}
|
||||
}
|
||||
} else if (status == BX_SHADER_ERR_UNSUPPORTED) {
|
||||
why.assign(reinterpret_cast<const char*>(out.reason), out.reason_len);
|
||||
} else {
|
||||
why = "the stages are not console shader code";
|
||||
}
|
||||
t.release(&out);
|
||||
if (p->state != BxConsolePipeline::State::Ready && sampled(g_untranslated, &total)) {
|
||||
log(BX_LOG_WARN, "console_pipeline", "pipeline %s is not drawn: %.500s; total=%llu", p->key, why.c_str(),
|
||||
static_cast<unsigned long long>(total));
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ID3D12PipelineState* bx_console_pipeline_for_draw(BxConsolePipeline* p, ID3D12GraphicsCommandList* list) {
|
||||
if (!p) return nullptr;
|
||||
Targets bound;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_target_lock);
|
||||
auto it = g_list_targets.find(list);
|
||||
if (it != g_list_targets.end()) bound = it->second;
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(p->lock);
|
||||
if (p->state == BxConsolePipeline::State::Untried) prepare(p);
|
||||
if (p->state != BxConsolePipeline::State::Ready) return nullptr;
|
||||
char formats[96] = "declared";
|
||||
if (bound.known) {
|
||||
int n = std::snprintf(formats, sizeof(formats), "%u", static_cast<unsigned>(bound.dsv));
|
||||
for (UINT i = 0; i < bound.count; ++i) {
|
||||
n += std::snprintf(formats + n, sizeof(formats) - static_cast<size_t>(n), ",%u", static_cast<unsigned>(bound.rtv[i]));
|
||||
}
|
||||
}
|
||||
auto found = p->variants.find(formats);
|
||||
if (found != p->variants.end()) return found->second;
|
||||
std::vector<uint8_t> stream = p->stream;
|
||||
const D3D12_SHADER_BYTECODE vs{p->vs_dxil.data(), p->vs_dxil.size()};
|
||||
const D3D12_SHADER_BYTECODE ps{p->ps_dxil.data(), p->ps_dxil.size()};
|
||||
std::memcpy(&stream[p->vs_at], &vs, sizeof(vs));
|
||||
std::memcpy(&stream[p->ps_at], &ps, sizeof(ps));
|
||||
if (p->layout_at != SIZE_MAX) {
|
||||
const D3D12_INPUT_LAYOUT_DESC layout{p->elements.data(), static_cast<UINT>(p->elements.size())};
|
||||
std::memcpy(&stream[p->layout_at], &layout, sizeof(layout));
|
||||
}
|
||||
if (bound.known && p->rt_at != SIZE_MAX) {
|
||||
D3D12_RT_FORMAT_ARRAY actual{};
|
||||
actual.NumRenderTargets = bound.count;
|
||||
for (UINT i = 0; i < bound.count; ++i) actual.RTFormats[i] = bound.rtv[i];
|
||||
std::memcpy(&stream[p->rt_at], &actual, sizeof(actual));
|
||||
}
|
||||
if (bound.known && p->ds_at != SIZE_MAX) std::memcpy(&stream[p->ds_at], &bound.dsv, sizeof(bound.dsv));
|
||||
const D3D12_PIPELINE_STATE_STREAM_DESC desc{stream.size(), stream.data()};
|
||||
ID3D12PipelineState* host = nullptr;
|
||||
const HRESULT hr = p->device->CreatePipelineState(&desc, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&host));
|
||||
if (FAILED(hr)) {
|
||||
host = nullptr;
|
||||
log(BX_LOG_WARN, "console_pipeline", "pipeline %s for formats %s: the host refused the translated pipeline hr=0x%08lx", p->key,
|
||||
formats, static_cast<unsigned long>(hr));
|
||||
} else {
|
||||
bx_xbox_rect_pipeline_created(host, p->elements.data(), static_cast<UINT>(p->elements.size()));
|
||||
}
|
||||
p->variants[formats] = host; // a refusal is remembered too, so it is tried and logged once
|
||||
return host;
|
||||
}
|
||||
|
||||
bool bx_console_pipeline_info(BxConsolePipeline* p, ID3D12Device** device, const BxConsoleUse** uses, size_t* count,
|
||||
const char** key) {
|
||||
if (!p) return false;
|
||||
std::lock_guard<std::mutex> guard(p->lock);
|
||||
if (p->state != BxConsolePipeline::State::Ready) return false;
|
||||
*device = p->device;
|
||||
*uses = p->uses.data(); // not changed once the pipeline is ready
|
||||
*count = p->uses.size();
|
||||
*key = p->key;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ---- Render-target bookkeeping --------------------------------------------------------------- */
|
||||
|
||||
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format) {
|
||||
if (!bx_console_shaders_enabled()) return;
|
||||
std::lock_guard<std::mutex> guard(g_target_lock);
|
||||
g_rtv_formats[host_cpu] = format;
|
||||
}
|
||||
|
||||
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format) {
|
||||
if (!bx_console_shaders_enabled()) return;
|
||||
std::lock_guard<std::mutex> guard(g_target_lock);
|
||||
g_dsv_formats[host_cpu] = format;
|
||||
}
|
||||
|
||||
void bx_console_list_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* host_rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* host_dsv) {
|
||||
if (!bx_console_shaders_enabled()) return;
|
||||
UINT increment = 0;
|
||||
if (single_range && count > 1 && host_rtvs) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (SUCCEEDED(list->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) && device) {
|
||||
increment = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
|
||||
device->Release();
|
||||
}
|
||||
}
|
||||
std::lock_guard<std::mutex> guard(g_target_lock);
|
||||
Targets t;
|
||||
t.count = count > 8 ? 8 : count;
|
||||
t.known = true;
|
||||
for (UINT i = 0; i < t.count; ++i) {
|
||||
// A single range is `count` consecutive descriptors starting at the first handle.
|
||||
const SIZE_T handle = !host_rtvs ? 0 : single_range ? host_rtvs[0].ptr + static_cast<SIZE_T>(i) * increment : host_rtvs[i].ptr;
|
||||
auto it = g_rtv_formats.find(handle);
|
||||
if (it == g_rtv_formats.end() || it->second == DXGI_FORMAT_UNKNOWN) {
|
||||
t.known = false; // a view this layer did not see: keep the pipeline's declared formats
|
||||
break;
|
||||
}
|
||||
t.rtv[i] = it->second;
|
||||
}
|
||||
if (host_dsv) {
|
||||
auto it = g_dsv_formats.find(host_dsv->ptr);
|
||||
if (it == g_dsv_formats.end()) {
|
||||
t.known = false;
|
||||
} else {
|
||||
t.dsv = it->second;
|
||||
}
|
||||
}
|
||||
g_list_targets[list] = t;
|
||||
}
|
||||
|
||||
void bx_console_list_forget(ID3D12GraphicsCommandList* list) {
|
||||
std::lock_guard<std::mutex> guard(g_target_lock);
|
||||
g_list_targets.erase(list);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
/*
|
||||
* Console graphics pipelines translated at first draw (#720). See console_pipelines.cpp.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <d3d12.h>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
/* HLSL to DXIL with the GDK's PC dxcompiler.dll (entry `main`, vs_6_0 or ps_6_0), through the same
|
||||
disk cache as translated shaders. False with the reason in `why` when there is no compiler or it
|
||||
refuses the source. */
|
||||
bool bx_console_compile_hlsl(const char* source, bool pixel, std::vector<uint8_t>& out, std::string& why);
|
||||
|
||||
/* True when BX_CONSOLE_SHADERS=1 (opt-in while the draw path is being completed). */
|
||||
bool bx_console_shaders_enabled();
|
||||
|
||||
/* CreateRootSignature on the host device. With console shaders enabled the root signature is
|
||||
widened with the register spaces translated shaders use; if the host refuses the widened form,
|
||||
the title's own is created and that is logged. `*ppv` is the host object (not wrapped). */
|
||||
HRESULT bx_console_create_root_signature(ID3D12Device* device, UINT node_mask, const void* blob, SIZE_T size, REFIID riid,
|
||||
void** ppv);
|
||||
|
||||
/* A stream pipeline the shader gate refused, kept to be translated when it is first drawn. */
|
||||
struct BxConsolePipeline;
|
||||
|
||||
/* `stream` is the host form of the title's stream (root signature unwrapped, topology type
|
||||
converted) with the title's shader stages still in it. Returns nullptr when console shaders
|
||||
are disabled or the pipeline is not a plain vertex/pixel pair. */
|
||||
std::shared_ptr<BxConsolePipeline> bx_console_pipeline_create(ID3D12Device* device, const std::vector<uint8_t>& stream,
|
||||
const std::vector<size_t>& stage_offsets,
|
||||
const std::vector<const char*>& stage_names, size_t root_offset);
|
||||
|
||||
/* The host pipeline for a draw on `list` with its bound render targets: translated, compiled and
|
||||
created on first use. nullptr when the pipeline cannot be translated or created (logged); the
|
||||
draw is then skipped by the caller. */
|
||||
ID3D12PipelineState* bx_console_pipeline_for_draw(BxConsolePipeline* pipeline, ID3D12GraphicsCommandList* list);
|
||||
|
||||
/* Render-target bookkeeping (host handles), so a host pipeline matches the bound formats. */
|
||||
void bx_console_rtv_created(SIZE_T host_cpu, DXGI_FORMAT format);
|
||||
void bx_console_dsv_created(SIZE_T host_cpu, DXGI_FORMAT format);
|
||||
void bx_console_list_targets(ID3D12GraphicsCommandList* list, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* host_rtvs,
|
||||
BOOL single_range, const D3D12_CPU_DESCRIPTOR_HANDLE* host_dsv);
|
||||
void bx_console_list_forget(ID3D12GraphicsCommandList* list);
|
||||
|
||||
/* A descriptor-table entry a translated pipeline's shaders read (a `USE` line of its layout). */
|
||||
struct BxConsoleUse {
|
||||
bool texture; // false: constant buffer
|
||||
UINT param; // root parameter of the table
|
||||
UINT entry; // index in the table
|
||||
};
|
||||
/* What a translated pipeline reads, once it has been translated; false before that. */
|
||||
bool bx_console_pipeline_info(BxConsolePipeline* pipeline, ID3D12Device** device, const BxConsoleUse** uses, size_t* count,
|
||||
const char** key);
|
||||
|
||||
/* console_descriptors.cpp: descriptors the title copies itself. `title_handle` is the title's
|
||||
descriptor handle (an address in its descriptor memory). */
|
||||
void bx_console_mark_cbv(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc);
|
||||
/* As bx_console_mark_cbv, for a constant view whose host fallback lies in `owner`, a resource the
|
||||
shim may release early (bx_console_forget_resource). */
|
||||
void bx_console_mark_cbv_of(uint64_t title_handle, uint64_t title_va, const D3D12_CONSTANT_BUFFER_VIEW_DESC& host_desc,
|
||||
ID3D12Resource* owner);
|
||||
void bx_console_mark_srv(uint64_t title_handle, ID3D12Resource* host, const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc);
|
||||
/* The shim is releasing `resource` (placed_x.cpp, implicit shadows): views marked with it stop
|
||||
referencing it. A marker of such a view resolves to a null view from then on. */
|
||||
void bx_console_forget_resource(ID3D12Resource* resource);
|
||||
/* Direct3D copied `count` descriptors between title handles: the title-side bytes follow. */
|
||||
void bx_console_copy_title(uint64_t dest, uint64_t src, UINT count);
|
||||
void bx_console_note_table(ID3D12GraphicsCommandList* list, UINT param, uint64_t title_handle);
|
||||
void bx_console_record_draw(ID3D12GraphicsCommandList* list, const std::shared_ptr<BxConsolePipeline>& pipeline);
|
||||
void bx_console_descriptors_reset(ID3D12GraphicsCommandList* list);
|
||||
/* Before `queue` executes `host_lists`: writes the views their translated draws read. Texture
|
||||
contents copied for those views are uploaded by a list of the shim's own, executed on `queue`
|
||||
first. */
|
||||
void bx_console_submit(ID3D12CommandQueue* queue, ID3D12CommandList* const* host_lists, UINT count);
|
||||
@@ -14,6 +14,9 @@
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "console_pipelines.h"
|
||||
#include "title_memory.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
@@ -77,6 +80,12 @@ void log_untranslated(const char* what, uint64_t value) {
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_xbox_title_descriptors(uint64_t address, UINT count) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const Heap* h = find_locked(static_cast<uintptr_t>(address));
|
||||
return h && h->xbox_size == 32 && address + 32ull * count <= h->base + static_cast<uint64_t>(h->count) * h->xbox_size;
|
||||
}
|
||||
|
||||
UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
switch (type) {
|
||||
case D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV: return 32;
|
||||
@@ -187,6 +196,7 @@ void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, co
|
||||
host_desc.BufferLocation = bx_xbox_host_gpu_va(desc->BufferLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateConstantBufferView(desc ? &host_desc : nullptr, bx_xbox_host_cpu_handle(dest));
|
||||
if (desc) bx_console_mark_cbv(dest.ptr, desc->BufferLocation, host_desc);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ranges, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts,
|
||||
@@ -201,6 +211,28 @@ void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors(void* self, UINT dest_ran
|
||||
for (UINT i = 0; i < src_ranges; ++i) src[i] = bx_xbox_host_cpu_handle(src_starts[i]);
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptors(dest_ranges, dst, dest_sizes, src_ranges, src, src_sizes, type);
|
||||
delete[] dst;
|
||||
if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV && dest_starts && src_starts) {
|
||||
// Descriptor by descriptor across the two range lists; a missing size array means 1 each.
|
||||
UINT di = 0, dn = 0, si = 0, sn = 0;
|
||||
while (di < dest_ranges && si < src_ranges) {
|
||||
bx_console_copy_title(dest_starts[di].ptr + 32ull * dn, src_starts[si].ptr + 32ull * sn, 1);
|
||||
if (++dn >= (dest_sizes ? dest_sizes[di] : 1u)) {
|
||||
++di;
|
||||
dn = 0;
|
||||
}
|
||||
if (++sn >= (src_sizes ? src_sizes[si] : 1u)) {
|
||||
++si;
|
||||
sn = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors_simple(void* self, UINT count, D3D12_CPU_DESCRIPTOR_HANDLE dest,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE src, D3D12_DESCRIPTOR_HEAP_TYPE type) {
|
||||
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(count, bx_xbox_host_cpu_handle(dest), bx_xbox_host_cpu_handle(src), type);
|
||||
if (type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) bx_console_copy_title(dest.ptr, src.ptr, count);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count, const D3D12_CPU_DESCRIPTOR_HANDLE* rtvs,
|
||||
@@ -212,6 +244,8 @@ void STDMETHODCALLTYPE bx_xbox_list_om_set_render_targets(void* self, UINT count
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE host_dsv = dsv ? bx_xbox_host_cpu_handle(*dsv) : D3D12_CPU_DESCRIPTOR_HANDLE{};
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->OMSetRenderTargets(n, rtvs ? host_rtvs : nullptr, single_range,
|
||||
dsv ? &host_dsv : nullptr);
|
||||
bx_console_list_targets(bx_xbox_host<ID3D12GraphicsCommandList>(self), n, rtvs ? host_rtvs : nullptr, single_range,
|
||||
dsv ? &host_dsv : nullptr);
|
||||
}
|
||||
|
||||
namespace {
|
||||
@@ -237,6 +271,70 @@ void note_unbacked(const char* what, D3D12_GPU_VIRTUAL_ADDRESS address, UINT siz
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace {
|
||||
|
||||
/* How much of the title memory at `address` is readable, up to `limit` bytes. */
|
||||
UINT64 readable_extent(D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 limit) {
|
||||
return bx_title_memory_readable_extent(address, limit);
|
||||
}
|
||||
|
||||
/* A root CBV or SRV. A root buffer has no size (a console shader reads it unchecked), so plain
|
||||
* title memory behind one gets a host buffer of what is readable there, up to `limit`, copied
|
||||
* when the list is submitted: a shader that reads further sees zeros. Only with translated
|
||||
* console shaders enabled, the only ones that read such buffers; otherwise the address is
|
||||
* translated as before. Returns false when the binding must be left empty. */
|
||||
bool root_buffer_address(ID3D12GraphicsCommandList* list, D3D12_GPU_VIRTUAL_ADDRESS address, UINT64 limit, const char* what,
|
||||
const char* stub, D3D12_GPU_VIRTUAL_ADDRESS* host) {
|
||||
*host = address;
|
||||
if (!address || bx_xbox_try_host_gpu_va(address, host)) return true;
|
||||
if (!bx_console_shaders_enabled()) {
|
||||
*host = bx_xbox_host_gpu_va(address);
|
||||
return true;
|
||||
}
|
||||
const UINT64 size = readable_extent(address, limit);
|
||||
if (size && bx_xbox_bind_title_memory(list, address, size, host)) {
|
||||
static std::atomic<uint64_t> bound{0};
|
||||
const uint64_t n = ++bound;
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s at 0x%llx: %llu bytes of title memory get a host buffer; total=%llu", what,
|
||||
static_cast<unsigned long long>(address), static_cast<unsigned long long>(size),
|
||||
static_cast<unsigned long long>(n));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "root_buffer", detail);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
note_unbacked(what, address, static_cast<UINT>(size), stub);
|
||||
return false;
|
||||
}
|
||||
|
||||
constexpr UINT64 kRootSrvBytes = 256 * 1024; // copied per submission: a prefix of the buffer
|
||||
constexpr UINT64 kRootCbvBytes = 64 * 1024; // the largest constant buffer
|
||||
|
||||
} // namespace
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_shader_resource_view(void* self, UINT param,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS address) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
|
||||
if (root_buffer_address(list, address, kRootSrvBytes, "root SRV", "SetGraphicsRootShaderResourceView(title memory without a host buffer)",
|
||||
&host)) {
|
||||
list->SetGraphicsRootShaderResourceView(param, host);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_constant_buffer_view(void* self, UINT param,
|
||||
D3D12_GPU_VIRTUAL_ADDRESS address) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootConstantBufferView");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
D3D12_GPU_VIRTUAL_ADDRESS host = 0;
|
||||
if (root_buffer_address(list, address, kRootCbvBytes, "root CBV", "SetGraphicsRootConstantBufferView(title memory without a host buffer)",
|
||||
&host)) {
|
||||
list->SetGraphicsRootConstantBufferView(param, host);
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_ia_set_vertex_buffers(void* self, UINT start, UINT count,
|
||||
const D3D12_VERTEX_BUFFER_VIEW* views) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "IASetVertexBuffers");
|
||||
|
||||
@@ -31,7 +31,9 @@ constexpr UINT kScheduleDisableSignal = 0x1;
|
||||
constexpr UINT kWaitAll = 0x1;
|
||||
constexpr UINT kWaitProcessTokenOnTimeout = 0x2;
|
||||
constexpr UINT kIntervalFlag60FpsPlus = 0x1;
|
||||
// D3D12XBOX_SIGNALED_OBJECT_INDEX_NONE / _PRIMARY (authorized GDK header d3d12_xs.h).
|
||||
constexpr UINT kSignaledNone = 0xFFFFFFFF;
|
||||
constexpr UINT kSignaledPrimary = 0xFFFFFFFE;
|
||||
constexpr UINT kInfinite = 0xFFFFFFFF;
|
||||
|
||||
struct Scheduled {
|
||||
@@ -203,8 +205,11 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_wait_frame_event_x(void*, UINT type, UI
|
||||
timeout_ms == kInfinite ? INFINITE : timeout_ms);
|
||||
const bool satisfied = result < WAIT_OBJECT_0 + 1 + ancillary;
|
||||
if (waits && waits->pSignaledObjectIndex) {
|
||||
*waits->pSignaledObjectIndex = satisfied && !(flags & kWaitAll) && result > WAIT_OBJECT_0
|
||||
? result - WAIT_OBJECT_0 - 1 : kSignaledNone;
|
||||
// WaitFrameEventX reference: NONE when the wait timed out, PRIMARY when the frame event
|
||||
// itself was signalled (a satisfied WAIT_ALL included), otherwise the index of the first
|
||||
// signalled ancillary object (#772).
|
||||
*waits->pSignaledObjectIndex = !satisfied ? kSignaledNone
|
||||
: result == WAIT_OBJECT_0 ? kSignaledPrimary : result - WAIT_OBJECT_0 - 1;
|
||||
}
|
||||
if (type == kOrigin && token && (satisfied || (flags & kWaitProcessTokenOnTimeout))) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
|
||||
@@ -6,15 +6,20 @@
|
||||
* XG12_RESOURCE_MISC_FLAG in place of D3D12_RESOURCE_FLAGS; the title's console flags
|
||||
* (render target, depth, UAV, deny-compression) are those values.
|
||||
* XGTextureAddressComputer vtable: 0 AddRef, 1 Release, 2 GetResourceLayout,
|
||||
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, ...
|
||||
* 3 GetResourceSizeBytes, 4 GetResourceBaseAlignmentBytes, 5 GetMipLevelOffsetBytes,
|
||||
* 6 GetTexelElementOffsetBytes, 7 GetTexelCoordinate, 8 CopyIntoSubresource,
|
||||
* 9 CopyFromSubresource(linear destination, plane, subresource, sample, tiled base, row pitch,
|
||||
* slice pitch): the untiled copy of one subresource.
|
||||
* void XGEnableExclusiveLocking(BOOL), to be called before any computer is created.
|
||||
*/
|
||||
#include "gdk_xg.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -25,6 +30,12 @@ struct XgComputerVtbl {
|
||||
void* GetResourceLayout;
|
||||
UINT64 (*GetResourceSizeBytes)(XgComputer*);
|
||||
UINT64 (*GetResourceBaseAlignmentBytes)(XgComputer*);
|
||||
void* GetMipLevelOffsetBytes;
|
||||
void* GetTexelElementOffsetBytes;
|
||||
void* GetTexelCoordinate;
|
||||
void* CopyIntoSubresource;
|
||||
HRESULT(__cdecl* CopyFromSubresource)(XgComputer*, void* linear, UINT32 plane, UINT32 subresource, UINT32 sample,
|
||||
const void* tiled_base, UINT32 row_pitch, UINT32 slice_pitch);
|
||||
};
|
||||
struct XgComputer {
|
||||
const XgComputerVtbl* vtbl;
|
||||
@@ -64,9 +75,14 @@ bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc) {
|
||||
static_cast<UINT>(desc.Layout) >= 0x100;
|
||||
}
|
||||
|
||||
bool bx_is_console_default_texture(const D3D12_RESOURCE_DESC& desc) {
|
||||
return desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER && desc.Dimension != D3D12_RESOURCE_DIMENSION_UNKNOWN &&
|
||||
desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN;
|
||||
}
|
||||
|
||||
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment) {
|
||||
const CreateTextureComputerFn create = create_computer();
|
||||
if (!create || !bx_is_console_texture_layout(desc)) return false;
|
||||
if (!create || !(bx_is_console_texture_layout(desc) || bx_is_console_default_texture(desc))) return false;
|
||||
XgComputer* computer = nullptr;
|
||||
const HRESULT hr = create(&desc, &computer);
|
||||
if (FAILED(hr) || !computer) {
|
||||
@@ -86,6 +102,63 @@ bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint
|
||||
return true;
|
||||
}
|
||||
|
||||
UINT bx_texture_element_bytes(DXGI_FORMAT f, bool* block) {
|
||||
*block = false;
|
||||
switch (f) {
|
||||
case DXGI_FORMAT_BC1_TYPELESS: case DXGI_FORMAT_BC1_UNORM: case DXGI_FORMAT_BC1_UNORM_SRGB:
|
||||
case DXGI_FORMAT_BC4_TYPELESS: case DXGI_FORMAT_BC4_UNORM: case DXGI_FORMAT_BC4_SNORM:
|
||||
*block = true;
|
||||
return 8;
|
||||
case DXGI_FORMAT_BC2_TYPELESS: case DXGI_FORMAT_BC2_UNORM: case DXGI_FORMAT_BC2_UNORM_SRGB:
|
||||
case DXGI_FORMAT_BC3_TYPELESS: case DXGI_FORMAT_BC3_UNORM: case DXGI_FORMAT_BC3_UNORM_SRGB:
|
||||
case DXGI_FORMAT_BC5_TYPELESS: case DXGI_FORMAT_BC5_UNORM: case DXGI_FORMAT_BC5_SNORM:
|
||||
case DXGI_FORMAT_BC6H_TYPELESS: case DXGI_FORMAT_BC6H_UF16: case DXGI_FORMAT_BC6H_SF16:
|
||||
case DXGI_FORMAT_BC7_TYPELESS: case DXGI_FORMAT_BC7_UNORM: case DXGI_FORMAT_BC7_UNORM_SRGB:
|
||||
*block = true;
|
||||
return 16;
|
||||
case DXGI_FORMAT_A8_UNORM: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: case DXGI_FORMAT_R8_TYPELESS:
|
||||
return 1;
|
||||
case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM:
|
||||
case DXGI_FORMAT_R16_TYPELESS:
|
||||
return 2;
|
||||
case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
|
||||
case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
|
||||
case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: case DXGI_FORMAT_R32_TYPELESS:
|
||||
case DXGI_FORMAT_R10G10B10A2_UNORM: case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R11G11B10_FLOAT:
|
||||
case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: case DXGI_FORMAT_R16G16_TYPELESS:
|
||||
return 4;
|
||||
case DXGI_FORMAT_R16G16B16A16_FLOAT: case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_TYPELESS:
|
||||
case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_TYPELESS:
|
||||
return 8;
|
||||
case DXGI_FORMAT_R32G32B32A32_FLOAT: case DXGI_FORMAT_R32G32B32A32_TYPELESS:
|
||||
return 16;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT bx_gdk_xg_detile(const D3D12_RESOURCE_DESC& desc, const void* tiled, uint8_t* base,
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* footprints, const UINT* rows, UINT count, UINT* subresources) {
|
||||
*subresources = 0;
|
||||
const CreateTextureComputerFn create = create_computer();
|
||||
bool block = false;
|
||||
const UINT element = bx_texture_element_bytes(desc.Format, &block);
|
||||
if (!create || !tiled || !base || !footprints || !rows || !element || !bx_is_console_texture_layout(desc) ||
|
||||
desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count > 1) {
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
XgComputer* computer = nullptr;
|
||||
HRESULT hr = create(&desc, &computer);
|
||||
if (FAILED(hr) || !computer) return FAILED(hr) ? hr : E_FAIL;
|
||||
for (UINT sub = 0; sub < count && SUCCEEDED(hr); ++sub) {
|
||||
const UINT pitch = footprints[sub].Footprint.RowPitch;
|
||||
hr = computer->vtbl->CopyFromSubresource(computer, base + footprints[sub].Offset, 0, sub, 0, tiled, pitch, pitch * rows[sub]);
|
||||
if (SUCCEEDED(hr)) ++*subresources;
|
||||
}
|
||||
computer->vtbl->Release(computer);
|
||||
return hr;
|
||||
}
|
||||
|
||||
extern "C" void bx_gdk_xg_enable_locking() {
|
||||
HMODULE xg = microsoft_xg();
|
||||
if (!xg) return;
|
||||
|
||||
+20
-2
@@ -18,10 +18,28 @@ bool bx_gdk_xg_available();
|
||||
/* A console texture layout (Layout >= 0x100) that the GDK's XG can describe. */
|
||||
bool bx_is_console_texture_layout(const D3D12_RESOURCE_DESC& desc);
|
||||
|
||||
/* Size and base alignment of `desc` in the console layout. False when XG is not available or
|
||||
refuses the description; `size` and `alignment` are then untouched. */
|
||||
/* A texture whose Layout is D3D12_TEXTURE_LAYOUT_UNKNOWN. On the console that selects the default
|
||||
tiling mode (GDK documentation of XG_RESOURCE_DESC::Layout), which XG computes when given the
|
||||
same value, so its size is the tiled one, not the host's. */
|
||||
bool bx_is_console_default_texture(const D3D12_RESOURCE_DESC& desc);
|
||||
|
||||
/* Size and base alignment of `desc` in its console layout: an explicit one, or the default tiling
|
||||
for a texture with Layout UNKNOWN. False when XG is not available or refuses the description;
|
||||
`size` and `alignment` are then untouched. */
|
||||
bool bx_gdk_xg_layout_size(const D3D12_RESOURCE_DESC& desc, uint64_t* size, uint64_t* alignment);
|
||||
|
||||
/* Untiles every subresource of a texture laid out as `desc` (a console layout) from title memory at
|
||||
`tiled` into CPU memory at `base`, subresource i at footprints[i] (D3D12 placed-footprint form,
|
||||
as GetCopyableFootprints gives them for the host texture), through XG's CopyFromSubresource.
|
||||
*subresources is the number untiled. E_NOTIMPL when XG is not available or the format has no
|
||||
known element size; the caller checks that the XG size of `desc` is readable at `tiled`. */
|
||||
HRESULT bx_gdk_xg_detile(const D3D12_RESOURCE_DESC& desc, const void* tiled, uint8_t* base,
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT* footprints, const UINT* rows, UINT count, UINT* subresources);
|
||||
|
||||
/* Bytes per element (a texel, or a 4x4 block of a BC format) of the formats textures are copied
|
||||
for, or 0. *block is set for BC formats. */
|
||||
UINT bx_texture_element_bytes(DXGI_FORMAT format, bool* block);
|
||||
|
||||
/* Enables XG's internal lock (XGEnableExclusiveLocking) before any texture computer is created,
|
||||
so the title's threads and the shim can both create computers. Called at device creation. */
|
||||
extern "C" void bx_gdk_xg_enable_locking();
|
||||
+222
-98
@@ -1,17 +1,42 @@
|
||||
/*
|
||||
* GPU value writes into title memory (ADR 0009): Write32/64BitValueBottomOfPipeX and
|
||||
* ...TopOfPipeX record "when the GPU reaches this point, store this value at this address".
|
||||
* On the console the address is title memory that the CPU polls. The host GPU cannot write
|
||||
* title memory, so each command list keeps its writes in recording order, and when a queue
|
||||
* executes lists that carry writes, it waits for the host GPU (an internal fence) and stores the
|
||||
* values from the CPU, in submission order, before the Execute call returns. Executes with
|
||||
* writes are therefore synchronous (logged once); executes without writes are not changed.
|
||||
* GPU value writes and waits in title memory (ADR 0009, #773).
|
||||
*
|
||||
* Write32/64BitValueBottomOfPipeX and ...TopOfPipeX record "when the GPU reaches this point, store
|
||||
* this value at this address"; Wait32/64BitValueX "the GPU waits here until the value at this
|
||||
* address meets the comparison". On the console the address is title memory, and both take effect
|
||||
* at their position in the command list. The host GPU can neither write nor read title memory, so:
|
||||
*
|
||||
* - An Execute whose lists carry no writes or waits goes to the host unchanged.
|
||||
* - Otherwise the submission is split at list boundaries. A list's waits come before it: the
|
||||
* host queue waits on a fence (a fence slot itself when the address is one, or a fence this
|
||||
* file signals once the CPU sees the value in title memory). A list's writes come after it:
|
||||
* the queue signals a fence when it has finished the list, and the values are stored then.
|
||||
* - The stores and the memory checks are done by one worker thread per host queue, in
|
||||
* submission order, so the Execute call returns at once: CPU and GPU overlap as on the console.
|
||||
* A wait the worker cannot satisfy within 10 s is released anyway (logged), as is a GPU fence
|
||||
* that does not complete; a host queue never stays blocked for good.
|
||||
*
|
||||
* Accepted difference: a host command list cannot be split once recorded, so inside one list a
|
||||
* write is stored at the list's end, and a wait is placed at the list's start when no write was
|
||||
* recorded before it in that list, or at the list's end (after that list's writes are stored) when
|
||||
* one was. A write is never seen before the work in front of it. A wait recorded after a write
|
||||
* stays after it: a two-queue handshake, where one list writes then waits for the other queue
|
||||
* while the other waits then writes, completes instead of each queue holding the other for the
|
||||
* 10 s release (target build, #806 follow-up). Writes recorded after such a wait are stored only
|
||||
* once it holds. The price is that GPU work recorded after such a wait in the same list may run
|
||||
* before the wait holds.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "console_pipelines.h"
|
||||
#include "title_memory.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
@@ -41,10 +66,7 @@ ListWrites* find_locked(ID3D12GraphicsCommandList* list) {
|
||||
}
|
||||
|
||||
bool writable(uint64_t address, size_t size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(address), ®ion, sizeof(region)) || region.State != MEM_COMMIT) return false;
|
||||
constexpr DWORD kWritable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
return (region.Protect & kWritable) && address + size <= reinterpret_cast<uint64_t>(region.BaseAddress) + region.RegionSize;
|
||||
return bx_title_memory_present(address, size, true);
|
||||
}
|
||||
|
||||
void record(void* self, const Write& op) {
|
||||
@@ -76,125 +98,227 @@ bool satisfied(const Write& w) {
|
||||
}
|
||||
}
|
||||
|
||||
// A GPU wait on memory becomes a host queue Wait when the memory is a fence slot and the
|
||||
// comparison is >=; otherwise the CPU polls the memory before submitting (10 s limit, logged).
|
||||
void apply_wait(ID3D12CommandQueue* queue, const Write& w) {
|
||||
constexpr DWORD kLimitMs = 10000;
|
||||
|
||||
void store(const Write& w) {
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
static std::atomic<int> bad{0};
|
||||
if (bad.fetch_add(1) < 8) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "address 0x%llx is not writable title memory; value dropped",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (w.wide) {
|
||||
reinterpret_cast<std::atomic<uint64_t>*>(w.address)->store(w.value, std::memory_order_release);
|
||||
} else {
|
||||
reinterpret_cast<std::atomic<uint32_t>*>(w.address)->store(static_cast<uint32_t>(w.value), std::memory_order_release);
|
||||
}
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && bx_xbox_fence_slot(w.address, &fence)) fence->Signal(w.value);
|
||||
}
|
||||
|
||||
// Waits on the CPU for `w` to hold in title memory, without spinning a core: a few yields, then
|
||||
// 1 ms sleeps. False after kLimitMs.
|
||||
bool poll(const Write& w) {
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
for (unsigned n = 0; !satisfied(w); ++n) {
|
||||
if (GetTickCount64() - start > kLimitMs) return false;
|
||||
if (n < 64) {
|
||||
SwitchToThread();
|
||||
} else {
|
||||
Sleep(1);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// One per host queue that carried a write or a wait.
|
||||
struct QueueState {
|
||||
ID3D12CommandQueue* queue = nullptr;
|
||||
ID3D12Fence* gpu = nullptr; // signalled by the queue after a list that carries writes
|
||||
uint64_t gpu_value = 0;
|
||||
ID3D12Fence* cpu = nullptr; // signalled by the worker once a memory wait holds
|
||||
uint64_t cpu_value = 0;
|
||||
std::mutex submit; // keeps one Execute's splits, signals and items together
|
||||
|
||||
struct Item {
|
||||
bool is_wait = false;
|
||||
uint64_t value = 0; // gpu value to wait for (writes) or cpu value to signal (wait)
|
||||
std::vector<Write> writes; // in list order
|
||||
Write wait{};
|
||||
};
|
||||
std::mutex items_lock;
|
||||
std::condition_variable ready;
|
||||
std::deque<Item> items;
|
||||
|
||||
void push(Item item) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(items_lock);
|
||||
items.push_back(std::move(item));
|
||||
}
|
||||
ready.notify_one();
|
||||
}
|
||||
|
||||
void run() {
|
||||
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
for (;;) {
|
||||
Item item;
|
||||
{
|
||||
std::unique_lock<std::mutex> guard(items_lock);
|
||||
ready.wait(guard, [this] { return !items.empty(); });
|
||||
item = std::move(items.front());
|
||||
items.pop_front();
|
||||
}
|
||||
if (item.is_wait) {
|
||||
if (!poll(item.wait)) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "wait on 0x%llx not satisfied after 10 s; the queue goes on",
|
||||
static_cast<unsigned long long>(item.wait.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", detail);
|
||||
}
|
||||
cpu->Signal(item.value);
|
||||
continue;
|
||||
}
|
||||
bool done = gpu->GetCompletedValue() >= item.value;
|
||||
if (!done && event && SUCCEEDED(gpu->SetEventOnCompletion(item.value, event))) {
|
||||
done = WaitForSingleObject(event, kLimitMs) == WAIT_OBJECT_0;
|
||||
}
|
||||
if (!done) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes",
|
||||
"the host GPU did not finish a list carrying writes within 10 s; values stored anyway");
|
||||
}
|
||||
for (const Write& w : item.writes) store(w);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
std::mutex g_states_lock;
|
||||
std::vector<QueueState*> g_states; // never freed: a worker may still run for a queue being released
|
||||
|
||||
QueueState* state_for(ID3D12CommandQueue* queue) {
|
||||
std::lock_guard<std::mutex> guard(g_states_lock);
|
||||
for (QueueState* s : g_states) {
|
||||
if (s->queue == queue) return s;
|
||||
}
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return nullptr;
|
||||
auto* s = new QueueState;
|
||||
s->queue = queue;
|
||||
const bool ok =
|
||||
SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&s->gpu))) &&
|
||||
SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&s->cpu)));
|
||||
device->Release();
|
||||
if (!ok) {
|
||||
if (s->gpu) s->gpu->Release();
|
||||
if (s->cpu) s->cpu->Release();
|
||||
delete s;
|
||||
return nullptr;
|
||||
}
|
||||
std::thread([s] { s->run(); }).detach();
|
||||
g_states.push_back(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
// A list's wait, before the list: a host Wait on the fence slot itself when the address is one
|
||||
// and the comparison is >= on the whole value; otherwise on this queue's CPU fence, which the
|
||||
// worker signals once the value holds.
|
||||
void enqueue_wait(QueueState* s, const Write& w) {
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && w.compare == D3D12_COMPARISON_FUNC_GREATER_EQUAL && w.mask == ~0ull && bx_xbox_fence_slot(w.address, &fence)) {
|
||||
queue->Wait(fence, w.value);
|
||||
s->queue->Wait(fence, w.value);
|
||||
return;
|
||||
}
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", "wait address is not title memory; wait skipped");
|
||||
return;
|
||||
}
|
||||
const ULONGLONG start = GetTickCount64();
|
||||
while (!satisfied(w)) {
|
||||
if (GetTickCount64() - start > 10000) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "wait on 0x%llx not satisfied after 10 s; submitting anyway",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_wait", detail);
|
||||
return;
|
||||
}
|
||||
SwitchToThread();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
struct QueueFence {
|
||||
ID3D12CommandQueue* queue;
|
||||
ID3D12Fence* fence;
|
||||
uint64_t value;
|
||||
};
|
||||
std::vector<QueueFence> g_fences; // guarded by g_lock
|
||||
|
||||
HRESULT wait_for_queue(ID3D12CommandQueue* queue) {
|
||||
ID3D12Fence* fence = nullptr;
|
||||
uint64_t value = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (QueueFence& q : g_fences) {
|
||||
if (q.queue == queue) {
|
||||
fence = q.fence;
|
||||
value = ++q.value;
|
||||
}
|
||||
}
|
||||
if (!fence) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device)))) return E_FAIL;
|
||||
const HRESULT hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence));
|
||||
device->Release();
|
||||
if (FAILED(hr)) return hr;
|
||||
value = 1;
|
||||
g_fences.push_back({queue, fence, value});
|
||||
}
|
||||
}
|
||||
HRESULT hr = queue->Signal(fence, value);
|
||||
if (FAILED(hr)) return hr;
|
||||
if (fence->GetCompletedValue() >= value) return S_OK;
|
||||
HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
if (!event) return E_OUTOFMEMORY;
|
||||
hr = fence->SetEventOnCompletion(value, event);
|
||||
if (SUCCEEDED(hr) && WaitForSingleObject(event, 10000) != WAIT_OBJECT_0) hr = HRESULT_FROM_WIN32(WAIT_TIMEOUT);
|
||||
CloseHandle(event);
|
||||
return hr;
|
||||
QueueState::Item item;
|
||||
item.is_wait = true;
|
||||
item.value = ++s->cpu_value;
|
||||
item.wait = w;
|
||||
s->queue->Wait(s->cpu, item.value);
|
||||
s->push(std::move(item));
|
||||
}
|
||||
|
||||
void execute(void* self, UINT count, ID3D12CommandList* const* lists) {
|
||||
auto* queue = bx_xbox_host<ID3D12CommandQueue>(self);
|
||||
BxXboxUnwrapArray<ID3D12CommandList> host(lists, count);
|
||||
if (!host.ok()) return;
|
||||
std::vector<Write> pending;
|
||||
bx_xbox_placed_note_submission(); // releases implicit shadows replaced long enough ago (#782)
|
||||
std::vector<std::vector<Write>> ops(count);
|
||||
bool any = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
if (ListWrites* entry = find_locked(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host.data()[i])))) {
|
||||
pending.insert(pending.end(), entry->writes.begin(), entry->writes.end());
|
||||
ops[i] = entry->writes;
|
||||
any = any || !ops[i].empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
bx_xbox_sync_mapped_buffers();
|
||||
bx_xbox_refresh_bound_memory(host.data(), count);
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) apply_wait(queue, w);
|
||||
bx_console_submit(queue, host.data(), count);
|
||||
QueueState* s = any ? state_for(queue) : nullptr;
|
||||
if (!s) {
|
||||
if (any) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", "no fences for this queue; writes and waits dropped");
|
||||
queue->ExecuteCommandLists(count, host.data());
|
||||
return;
|
||||
}
|
||||
queue->ExecuteCommandLists(count, host.data());
|
||||
bool any_write = false;
|
||||
for (const Write& w : pending) any_write = any_write || !w.wait;
|
||||
if (!any_write) return;
|
||||
static std::atomic<bool> logged{false};
|
||||
if (!logged.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "gpu_value_writes",
|
||||
"executes carrying Write*BitValue*X wait for the host GPU, then store the values in title memory");
|
||||
"submissions with Write*/Wait*BitValue*X are split at their lists: waits hold the host queue, "
|
||||
"writes are stored when the host GPU has finished their list");
|
||||
}
|
||||
const HRESULT hr = wait_for_queue(queue);
|
||||
if (FAILED(hr)) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "waiting for the host GPU failed hr=0x%08lx; values still written",
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
}
|
||||
for (const Write& w : pending) {
|
||||
if (w.wait) continue;
|
||||
if (!writable(w.address, w.wide ? 8 : 4)) {
|
||||
static std::atomic<int> bad{0};
|
||||
if (bad.fetch_add(1) < 8) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "address 0x%llx is not writable title memory; value dropped",
|
||||
static_cast<unsigned long long>(w.address));
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "gpu_value_writes", detail);
|
||||
std::lock_guard<std::mutex> guard(s->submit);
|
||||
UINT start = 0;
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
// In recording order: waits before the list's first write go in front of the list; the
|
||||
// writes and any later waits go after it, the writes first.
|
||||
bool has_pre_wait = false, has_write = false, has_post_wait = false;
|
||||
for (const Write& w : ops[i]) {
|
||||
if (!w.wait) has_write = true;
|
||||
else if (has_write) has_post_wait = true;
|
||||
else has_pre_wait = true;
|
||||
}
|
||||
if (has_pre_wait) {
|
||||
if (i > start) queue->ExecuteCommandLists(i - start, host.data() + start);
|
||||
start = i;
|
||||
for (const Write& w : ops[i]) {
|
||||
if (!w.wait) break;
|
||||
enqueue_wait(s, w);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (w.wide) {
|
||||
reinterpret_cast<std::atomic<uint64_t>*>(w.address)->store(w.value, std::memory_order_release);
|
||||
} else {
|
||||
reinterpret_cast<std::atomic<uint32_t>*>(w.address)->store(static_cast<uint32_t>(w.value), std::memory_order_release);
|
||||
if (has_write) {
|
||||
queue->ExecuteCommandLists(i + 1 - start, host.data() + start);
|
||||
start = i + 1;
|
||||
// The writes up to the list's first later wait are stored when the GPU has finished
|
||||
// the list; each later wait follows, and the writes recorded after it are stored only
|
||||
// once it holds (same GPU fence value: the list is already done by then).
|
||||
const uint64_t done = ++s->gpu_value;
|
||||
queue->Signal(s->gpu, done);
|
||||
QueueState::Item item;
|
||||
item.value = done;
|
||||
bool seen_write = false;
|
||||
for (const Write& w : ops[i]) {
|
||||
if (!w.wait) {
|
||||
seen_write = true;
|
||||
item.writes.push_back(w);
|
||||
} else if (seen_write) {
|
||||
if (!item.writes.empty()) s->push(std::move(item));
|
||||
item = QueueState::Item{};
|
||||
item.value = done;
|
||||
enqueue_wait(s, w);
|
||||
}
|
||||
}
|
||||
if (!item.writes.empty()) s->push(std::move(item));
|
||||
}
|
||||
ID3D12Fence* fence = nullptr;
|
||||
if (w.wide && bx_xbox_fence_slot(w.address, &fence)) fence->Signal(w.value);
|
||||
}
|
||||
if (start < count) queue->ExecuteCommandLists(count - start, host.data() + start);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -13,15 +13,23 @@
|
||||
* are skipped. Everything else still runs, so fences complete and frames present, with the
|
||||
* skipped work missing from them. Each refusal and each skip is logged: the mode exists to see
|
||||
* how far a title gets, not to hide what it cannot run.
|
||||
*
|
||||
* Console pipelines (BX_CONSOLE_SHADERS=1, console_pipelines.cpp, #720): a refused stream
|
||||
* pipeline that is a vertex/pixel pair is returned as a null pipeline that carries the pair. A
|
||||
* draw with it bound asks for its translated host pipeline, binds that and draws; when there is
|
||||
* none (not translatable yet), the draw is skipped and logged like any null pipeline's.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include "console_pipelines.h"
|
||||
#include "proxy.h"
|
||||
#include "shader_gate.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
|
||||
@@ -43,6 +51,8 @@ class NullPipelineState final : public ID3D12PipelineState {
|
||||
public:
|
||||
explicit NullPipelineState(ID3D12Device* device) : device_(device) { device_->AddRef(); }
|
||||
|
||||
std::shared_ptr<BxConsolePipeline> console; // the console pair to translate at first draw, if any
|
||||
|
||||
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
if (riid == __uuidof(IUnknown) || riid == __uuidof(ID3D12Object) || riid == __uuidof(ID3D12DeviceChild) ||
|
||||
@@ -88,6 +98,7 @@ size_t g_null_capacity = 0;
|
||||
ID3D12GraphicsCommandList** g_lists = nullptr; // lists whose bound pipeline is a null pipeline
|
||||
size_t g_list_count = 0;
|
||||
size_t g_list_capacity = 0;
|
||||
std::unordered_map<const void*, std::shared_ptr<BxConsolePipeline>> g_list_console; // its console pair, if any
|
||||
|
||||
template <typename T>
|
||||
bool push(T**& items, size_t& count, size_t& capacity, T* item) {
|
||||
@@ -124,24 +135,55 @@ bool contains(T* const* items, size_t count, const T* item) {
|
||||
}
|
||||
|
||||
/* Returns the host pipeline for a title pipeline, or nullptr for a null pipeline. */
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null) {
|
||||
ID3D12PipelineState* host_pipeline(ID3D12PipelineState* title, bool* is_null,
|
||||
std::shared_ptr<BxConsolePipeline>* console = nullptr) {
|
||||
ID3D12PipelineState* host = bx_xbox_unwrap_as(title);
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
*is_null = host && contains(g_nulls, g_null_count, static_cast<NullPipelineState*>(static_cast<void*>(host)));
|
||||
auto* as_null = static_cast<NullPipelineState*>(static_cast<void*>(host));
|
||||
*is_null = host && contains(g_nulls, g_null_count, as_null);
|
||||
if (console && *is_null) *console = as_null->console;
|
||||
return *is_null ? nullptr : host;
|
||||
}
|
||||
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound) {
|
||||
void set_list_null(ID3D12GraphicsCommandList* list, bool null_bound, std::shared_ptr<BxConsolePipeline> console = nullptr) {
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
const bool present = contains(g_lists, g_list_count, list);
|
||||
if (null_bound && !present) push(g_lists, g_list_count, g_list_capacity, list);
|
||||
if (!null_bound && present) erase(g_lists, g_list_count, list);
|
||||
if (console) {
|
||||
g_list_console[list] = std::move(console);
|
||||
} else {
|
||||
g_list_console.erase(list);
|
||||
}
|
||||
}
|
||||
|
||||
bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
|
||||
/* True when the work must be skipped. A draw (`draw`) with a console pipeline bound binds its
|
||||
translated host pipeline instead, when there is one. */
|
||||
bool list_skips(ID3D12GraphicsCommandList* list, const char* what, bool draw = false) {
|
||||
std::shared_ptr<BxConsolePipeline> console;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!contains(g_lists, g_list_count, list)) return false;
|
||||
if (draw) {
|
||||
auto it = g_list_console.find(list);
|
||||
if (it != g_list_console.end()) console = it->second;
|
||||
}
|
||||
}
|
||||
if (console) {
|
||||
if (ID3D12PipelineState* host = bx_console_pipeline_for_draw(console.get(), list)) {
|
||||
bx_console_record_draw(list, console);
|
||||
list->SetPipelineState(host);
|
||||
bx_xbox_rect_note_pipeline(list, host);
|
||||
static std::atomic<uint64_t> drawn{0};
|
||||
const uint64_t k = ++drawn;
|
||||
if ((k & (k - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "%s with a translated console pipeline; total=%llu", what,
|
||||
static_cast<unsigned long long>(k));
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "console_draw", detail);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
static std::atomic<uint64_t> skipped{0};
|
||||
const uint64_t n = ++skipped;
|
||||
@@ -154,14 +196,19 @@ bool list_skips(ID3D12GraphicsCommandList* list, const char* what) {
|
||||
return true;
|
||||
}
|
||||
|
||||
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv) {
|
||||
/* `placeholder`: return the null pipeline whatever BX_NULL_RENDER says (refused compute pipelines,
|
||||
see create_compute). */
|
||||
HRESULT refused(ID3D12Device* device, HRESULT hr, const char* kind, REFIID riid, void** ppv,
|
||||
std::shared_ptr<BxConsolePipeline> console = nullptr, bool placeholder = false) {
|
||||
char detail[128];
|
||||
std::snprintf(detail, sizeof(detail), "%s pipeline refused hr=0x%08lx%s", kind, static_cast<unsigned long>(hr),
|
||||
null_render_enabled() ? "; null pipeline returned" : "");
|
||||
console ? "; kept for translation at first draw"
|
||||
: null_render_enabled() || placeholder ? "; null pipeline returned" : "");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_refused", detail);
|
||||
if (!null_render_enabled() || !ppv) return hr;
|
||||
if ((!null_render_enabled() && !console && !placeholder) || !ppv) return hr;
|
||||
auto* null_pso = new (std::nothrow) NullPipelineState(device);
|
||||
if (!null_pso) return E_OUTOFMEMORY;
|
||||
null_pso->console = std::move(console);
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
if (!push(g_nulls, g_null_count, g_null_capacity, null_pso)) {
|
||||
@@ -187,6 +234,15 @@ void log_extended(const char* kind, UINT count) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "pipeline_extended_desc", detail);
|
||||
}
|
||||
|
||||
/*
|
||||
* A compute pipeline the host cannot make (console compute shaders are not translated yet, #746)
|
||||
* comes back as the null pipeline, logged, not as a failure: on the console the call does not fail,
|
||||
* and the target build keeps the shader program it was making for the pipeline even when it does,
|
||||
* with no pipeline in it; its next dispatch through that program reads inside the missing pipeline
|
||||
* and the title exits (#722). Dispatches with the null pipeline are skipped and logged
|
||||
* (null_render_skip), as every dispatch of untranslated compute is today. Serialized and derived
|
||||
* pipelines still fail (refused_always_fail), so a title creates them from shaders instead.
|
||||
*/
|
||||
HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc, REFIID riid, void** ppv) {
|
||||
if (!desc || !ppv) return E_INVALIDARG;
|
||||
*ppv = nullptr;
|
||||
@@ -196,7 +252,7 @@ HRESULT create_compute(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc
|
||||
admitted.pRootSignature = bx_xbox_unwrap_as(desc->pRootSignature);
|
||||
HRESULT hr = gate.admit("compute", "CS", desc->CS, admitted.CS);
|
||||
if (SUCCEEDED(hr)) hr = device->CreateComputePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "compute", riid, ppv, nullptr, true);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
@@ -265,7 +321,9 @@ HRESULT create_stream(void* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc,
|
||||
}
|
||||
D3D12_PIPELINE_STATE_STREAM_DESC admitted = *desc;
|
||||
admitted.pPipelineStateSubobjectStream = stream.data();
|
||||
if (SUCCEEDED(hr)) hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
// The shader gate refused a stage: console code. The pair is kept for its first draw.
|
||||
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv, bx_console_pipeline_create(device, stream, offsets, names, root_offset));
|
||||
hr = device->CreatePipelineState(&admitted, riid, ppv);
|
||||
if (FAILED(hr)) return refused(device, hr, "stream", riid, ppv);
|
||||
{
|
||||
D3D12_INPUT_LAYOUT_DESC layout{};
|
||||
@@ -297,7 +355,10 @@ void bx_xbox_pipeline_forget(IUnknown* host) {
|
||||
|
||||
void bx_xbox_list_forget(IUnknown* host) {
|
||||
bx_xbox_rect_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
bx_console_list_forget(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
bx_console_descriptors_reset(static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
g_list_console.erase(host);
|
||||
erase(g_lists, g_list_count, static_cast<ID3D12GraphicsCommandList*>(static_cast<void*>(host)));
|
||||
}
|
||||
|
||||
@@ -309,6 +370,13 @@ void STDMETHODCALLTYPE bx_xbox_list_ia_set_primitive_topology(void* self, D3D12_
|
||||
list->IASetPrimitiveTopology(bx_xbox_rect_note_topology(list, topology));
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_descriptor_table(void* self, UINT param, D3D12_GPU_DESCRIPTOR_HANDLE base) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootDescriptorTable");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bx_console_note_table(list, param, base.ptr);
|
||||
list->SetGraphicsRootDescriptorTable(param, bx_xbox_host_gpu_handle(base));
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_compute_pipeline_state(void* self, const D3D12_COMPUTE_PIPELINE_STATE_DESC* desc,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateComputePipelineState");
|
||||
@@ -341,8 +409,9 @@ void STDMETHODCALLTYPE bx_xbox_list_set_pipeline_state(void* self, ID3D12Pipelin
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
std::shared_ptr<BxConsolePipeline> console;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &console);
|
||||
set_list_null(list, is_null, std::move(console));
|
||||
bx_xbox_rect_note_pipeline(list, host);
|
||||
if (!is_null) list->SetPipelineState(host);
|
||||
}
|
||||
@@ -351,9 +420,11 @@ HRESULT STDMETHODCALLTYPE bx_xbox_list_reset(void* self, ID3D12CommandAllocator*
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Reset");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
bool is_null = false;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null);
|
||||
set_list_null(list, is_null);
|
||||
std::shared_ptr<BxConsolePipeline> console;
|
||||
ID3D12PipelineState* host = host_pipeline(pso, &is_null, &console);
|
||||
set_list_null(list, is_null, std::move(console));
|
||||
bx_xbox_gpu_writes_reset(list);
|
||||
bx_console_descriptors_reset(list);
|
||||
bx_xbox_bound_memory_reset(list);
|
||||
bx_xbox_rect_list_reset(list, host);
|
||||
return list->Reset(bx_xbox_unwrap_as(allocator), host);
|
||||
@@ -363,7 +434,7 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_instanced(void* self, UINT vertices, UI
|
||||
UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (list_skips(list, "DrawInstanced")) return;
|
||||
if (list_skips(list, "DrawInstanced", true)) return;
|
||||
if (!bx_xbox_draw_rect_list(list, vertices, instances, first_vertex, first_instance)) {
|
||||
list->DrawInstanced(vertices, instances, first_vertex, first_instance);
|
||||
}
|
||||
@@ -373,7 +444,7 @@ void STDMETHODCALLTYPE bx_xbox_list_draw_indexed_instanced(void* self, UINT indi
|
||||
INT base_vertex, UINT first_instance) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DrawIndexedInstanced");
|
||||
auto* list = bx_xbox_host<ID3D12GraphicsCommandList>(self);
|
||||
if (list_skips(list, "DrawIndexedInstanced")) return;
|
||||
if (list_skips(list, "DrawIndexedInstanced", true)) return;
|
||||
if (bx_xbox_rect_list_bound(list)) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "DrawIndexedInstanced(rectangle list)");
|
||||
return;
|
||||
@@ -399,6 +470,16 @@ void STDMETHODCALLTYPE bx_xbox_list_execute_indirect(void* self, ID3D12CommandSi
|
||||
|
||||
} // extern "C"
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_root_signature(void* self, UINT node_mask, const void* blob, SIZE_T size,
|
||||
REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRootSignature");
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
const HRESULT hr = bx_console_create_root_signature(bx_xbox_host<ID3D12Device>(self), node_mask, blob, size, riid, ppv);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
|
||||
return bx_xbox_wrap_result(hr, riid, ppv);
|
||||
}
|
||||
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateCommandSignature");
|
||||
|
||||
+534
-34
@@ -8,15 +8,22 @@
|
||||
*
|
||||
* - a buffer gets a committed buffer in a CPU-visible write-back heap, filled from the title's
|
||||
* memory when it is created;
|
||||
* - a texture gets a committed texture whose contents are not filled (logged); texture
|
||||
* contents need the console tiling translation (xg_xs) first.
|
||||
* - a texture gets a committed texture on a default heap. Its contents reach the host when a
|
||||
* translated draw reads it (bx_xbox_texture_contents, below: a CPU-writable copy filled from
|
||||
* title memory, untiled through the GDK's XG); other views of it read the empty texture
|
||||
* (logged at creation when translation is off).
|
||||
*
|
||||
* The title's address and the shadow are recorded, and the resource reports the title's address
|
||||
* from GetGPUVirtualAddress. Keeping the shadow in step with later CPU writes, and translating
|
||||
* title addresses in GPU calls, are not done yet; both are logged when reached.
|
||||
*/
|
||||
#include "console_formats.h"
|
||||
#include "console_pipelines.h"
|
||||
#include "gdk_xg.h"
|
||||
#include "xbox_facade.h"
|
||||
#include "title_memory.h"
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
@@ -37,6 +44,9 @@ struct Shadow {
|
||||
D3D12_RESOURCE_DESC desc;
|
||||
ULONGLONG title_attributes; // non-zero: title_va came from XMemAlloc and is freed with the resource
|
||||
int mapped = 0; // outstanding Map calls on title memory (buffers)
|
||||
bool implicit = false; // made for a view of placed memory (implicit_shadow); owned by this table
|
||||
bool simultaneous = false; // texture made with D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS
|
||||
uint64_t span = 0; // implicit: the bytes of title memory the resource covers
|
||||
};
|
||||
|
||||
// Copies between a buffer's title memory and its host resource, when the host is CPU-mappable.
|
||||
@@ -75,17 +85,7 @@ bool remember(const Shadow& shadow) {
|
||||
}
|
||||
|
||||
bool readable(const void* p, uint64_t size) {
|
||||
auto cursor = reinterpret_cast<uintptr_t>(p);
|
||||
const uintptr_t end = cursor + size;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT
|
||||
|| (region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
return bx_title_memory_present(reinterpret_cast<uintptr_t>(p), size);
|
||||
}
|
||||
|
||||
HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc, const char* method,
|
||||
@@ -109,9 +109,26 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
|
||||
bx_note_console_format(desc.Format, "CreatePlacedResourceX");
|
||||
host_desc.Format = bx_host_resource_format(desc.Format);
|
||||
}
|
||||
// A texture the GPU never writes gets its contents from title memory, uploaded into it by the
|
||||
// shim (bx_xbox_texture_contents). Simultaneous access lets that copy promote the texture from
|
||||
// COMMON without barriers of the shim's own against the states the title's barriers name.
|
||||
constexpr UINT kGpuWrites = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
const bool simultaneous = !buffer && host_desc.SampleDesc.Count <= 1 && !(static_cast<UINT>(host_desc.Flags) & kGpuWrites);
|
||||
if (simultaneous) host_desc.Flags |= D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS;
|
||||
ID3D12Resource* resource = nullptr;
|
||||
HRESULT hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
bool made_simultaneous = simultaneous && SUCCEEDED(hr);
|
||||
if (simultaneous && FAILED(hr)) { // the host refuses the flag: without it, uploads use barriers from COMMON
|
||||
static std::atomic<bool> noted{false};
|
||||
if (!noted.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "placed_x_shadow", "the host refuses simultaneous access on a texture; made without it");
|
||||
}
|
||||
host_desc.Flags = static_cast<D3D12_RESOURCE_FLAGS>(host_desc.Flags & ~D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS);
|
||||
hr = device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &host_desc, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&resource));
|
||||
}
|
||||
char detail[224];
|
||||
std::snprintf(detail, sizeof(detail), "%s title_va=0x%llx dim=%d width=%llu height=%u format=%d hr=0x%08lx",
|
||||
method, static_cast<unsigned long long>(title_va), static_cast<int>(desc.Dimension),
|
||||
@@ -131,10 +148,13 @@ HRESULT make_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURC
|
||||
}
|
||||
resource->Unmap(0, nullptr);
|
||||
}
|
||||
} else {
|
||||
} else if (!bx_console_shaders_enabled()) {
|
||||
// Contents are copied only for views of translated draws (bx_xbox_texture_contents).
|
||||
BX_STUB_LOG("d3d12_xs.dll", "CreatePlacedResourceX(texture contents)");
|
||||
}
|
||||
if (!remember({resource, title_va, desc.Width, buffer, desc, 0})) {
|
||||
Shadow record{resource, title_va, desc.Width, buffer, desc, 0};
|
||||
record.simultaneous = made_simultaneous;
|
||||
if (!remember(record)) {
|
||||
resource->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
}
|
||||
@@ -158,17 +178,63 @@ bool same_shape(const D3D12_RESOURCE_DESC& a, const D3D12_RESOURCE_DESC& b) {
|
||||
a.DepthOrArraySize == b.DepthOrArraySize && a.MipLevels == b.MipLevels && a.Format == b.Format;
|
||||
}
|
||||
|
||||
// A view of placed memory with no resource object: reuse the shadow made for the same address
|
||||
// and shape, or make one. These shadows live for the rest of the process (logged).
|
||||
// The bytes of title memory a placed resource of `desc` covers: XG's size for console layouts,
|
||||
// 256-byte rows for the linear layout, packed elements otherwise. At least 1.
|
||||
uint64_t title_span(const D3D12_RESOURCE_DESC& desc) {
|
||||
if (desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return desc.Width ? desc.Width : 1;
|
||||
uint64_t size = 0, alignment = 0;
|
||||
if (static_cast<UINT>(desc.Layout) > 0x100 && bx_gdk_xg_layout_size(desc, &size, &alignment) && size) return size;
|
||||
bool block = false;
|
||||
const UINT element = bx_texture_element_bytes(desc.Format, &block);
|
||||
const uint64_t width = block ? (desc.Width + 3) / 4 : desc.Width;
|
||||
const uint64_t height = block ? (desc.Height + 3) / 4 : desc.Height;
|
||||
uint64_t row = width * (element ? element : 4);
|
||||
if (static_cast<UINT>(desc.Layout) == 0x100) row = (row + 255) / 256 * 256;
|
||||
size = row * (height ? height : 1) * (desc.DepthOrArraySize ? desc.DepthOrArraySize : 1);
|
||||
return size ? size : 1;
|
||||
}
|
||||
|
||||
// Implicit shadows the title has replaced, released once enough submissions have passed.
|
||||
void retire_implicit(const std::vector<ID3D12Resource*>& hosts);
|
||||
|
||||
/*
|
||||
* A view of placed memory with no resource object: reuse the shadow made for the same address
|
||||
* and shape, or make one (#782). A title streams textures and buffers through recycled memory, so
|
||||
* a new view whose title range overlaps an older implicit shadow of another address or shape means
|
||||
* the title has placed something else there and no longer uses the old one: that shadow is retired
|
||||
* and released later (retire_implicit). Without this, every (address, shape) a title ever viewed kept
|
||||
* a host resource for the life of the process.
|
||||
*/
|
||||
ID3D12Resource* implicit_shadow(ID3D12Device* device, uint64_t title_va, const D3D12_RESOURCE_DESC& desc) {
|
||||
const uint64_t span = title_span(desc);
|
||||
std::vector<ID3D12Resource*> replaced;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) {
|
||||
if (g_shadows[i].title_va == title_va && same_shape(g_shadows[i].desc, desc)) return g_shadows[i].host;
|
||||
}
|
||||
for (size_t i = 0; i < g_count;) {
|
||||
const Shadow& s = g_shadows[i];
|
||||
if (s.implicit && title_va < s.title_va + s.span && s.title_va < title_va + span) {
|
||||
replaced.push_back(s.host);
|
||||
g_shadows[i] = g_shadows[--g_count];
|
||||
} else {
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!replaced.empty()) retire_implicit(replaced);
|
||||
ID3D12Resource* resource = nullptr;
|
||||
return SUCCEEDED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource)) ? resource : nullptr;
|
||||
if (FAILED(make_shadow(device, title_va, desc, "implicit shadow for a placed view", &resource))) return nullptr;
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = g_count; i-- > 0;) {
|
||||
if (g_shadows[i].host == resource) {
|
||||
g_shadows[i].implicit = true;
|
||||
g_shadows[i].span = span;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
// The Xbox view descriptions start with the PC description's 40 bytes; ResourceLocation follows.
|
||||
@@ -182,6 +248,264 @@ uint64_t view_location(const void* xbox_desc) {
|
||||
return va;
|
||||
}
|
||||
|
||||
/*
|
||||
* Texture contents (#745, #782). On the console a placed texture has one storage, the title's
|
||||
* memory. Here its one host storage is the shadow texture itself: when a view of it is resolved for
|
||||
* a translated draw (console_descriptors.cpp), its pixels are uploaded from title memory into the
|
||||
* shadow, so every view and copy command of the texture sees them. The texels are written into an
|
||||
* upload buffer (persistently mapped while it exists) and copied by the GPU, on a list the shim
|
||||
* executes on the submitting queue ahead of the title's lists (BxTextureUploads). A read-only shadow
|
||||
* has simultaneous access (make_shadow), so that copy promotes it from COMMON and it decays back
|
||||
* after the list, without barriers that would contradict the states the title's own barriers name.
|
||||
* A linear layout (D3D12XBOX_TEXTURE_LAYOUT_SWIZZLE_MODE_LINEAR, 0x100) is copied
|
||||
* row by row: rows in title memory are 256-byte aligned, the layout XG reports for linear
|
||||
* textures. Other console layouts are untiled through the GDK's XG library (ADR 0010).
|
||||
*
|
||||
* The upload is made the first time a translated draw reads the texture (until then, and after a
|
||||
* failure, the shadow is empty and the next draw tries again). An upload buffer is not written
|
||||
* again until the GPU is past its last copy, and is released then (#782): made again only when a
|
||||
* check finds the title memory changed. Until then a check is put off. Because a title may still be filling a texture (streaming) when it is first drawn, a
|
||||
* later draw checks whether the title memory changed: a hash over a sample of it (64 bytes every
|
||||
* 64 KiB, and the last 64). A texture found changed is checked again at its next draw, so one the
|
||||
* title rewrites every frame (a video's planes) is copied as often as it changes; a check that finds
|
||||
* no change waits kTextureCheckMs before the next, doubling up to kTextureCheckMaxMs while nothing
|
||||
* changes. Only a change copies the texture again (logged). Render targets, depth and UAV textures are written by the GPU and are
|
||||
* never copied over.
|
||||
*
|
||||
* Accepted risk: a change that falls entirely between the sampled 64-byte lines is not seen, and
|
||||
* the texture keeps its earlier contents until a sampled line changes too.
|
||||
*
|
||||
* Limit: contents are uploaded when a translated draw first reads the texture. A copy command or
|
||||
* view of a texture no translated draw has read yet still sees an empty shadow.
|
||||
*/
|
||||
enum class TextureKind { None, Linear, Tiled };
|
||||
constexpr UINT kConsoleLayoutLinear = 0x100;
|
||||
constexpr uint64_t kTextureCheckMs = 16; // the first wait after a check found no change
|
||||
constexpr uint64_t kTextureCheckMaxMs = 4000;
|
||||
|
||||
struct TextureUpload {
|
||||
ID3D12Resource* upload = nullptr; // owned; upload heap, mapped at `mapped`; null while not needed
|
||||
uint8_t* mapped = nullptr;
|
||||
std::vector<D3D12_PLACED_SUBRESOURCE_FOOTPRINT> footprints;
|
||||
std::vector<UINT> rows;
|
||||
uint64_t title_va = 0;
|
||||
bool filled = false; // an upload has been recorded
|
||||
uint64_t checked_at = 0; // GetTickCount64 of the last copy or check
|
||||
uint64_t interval = kTextureCheckMs;
|
||||
uint64_t sample = 0; // the sample hash the copy was made from
|
||||
ID3D12Fence* fence = nullptr; // the upload list's fence and the value after the last copy
|
||||
uint64_t fence_value = 0;
|
||||
uint64_t upload_bytes = 0; // the upload buffer's size; the buffer exists only while needed
|
||||
};
|
||||
std::mutex g_texture_lock;
|
||||
std::unordered_map<const void*, TextureUpload> g_texture_uploads; // host texture -> its upload state
|
||||
|
||||
/* FNV-1a over 64 bytes every 64 KiB of [va, va + bytes), and the last 64 bytes. */
|
||||
uint64_t sample_hash(uint64_t va, uint64_t bytes) {
|
||||
uint64_t h = 0xcbf29ce484222325ull;
|
||||
auto mix = [&](uint64_t at) {
|
||||
const uint64_t n = at + 64 <= bytes ? 64 : bytes - at;
|
||||
const auto* p = reinterpret_cast<const uint8_t*>(va + at);
|
||||
for (uint64_t i = 0; i < n; ++i) h = (h ^ p[i]) * 0x100000001b3ull;
|
||||
};
|
||||
for (uint64_t at = 0; at < bytes; at += 64 * 1024) mix(at);
|
||||
if (bytes > 64) mix(bytes - 64);
|
||||
return h;
|
||||
}
|
||||
|
||||
TextureKind texture_kind(const D3D12_RESOURCE_DESC& desc) {
|
||||
constexpr UINT kGpuWritten = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL |
|
||||
D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS;
|
||||
if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count > 1 ||
|
||||
(static_cast<UINT>(desc.Flags) & kGpuWritten) || bx_is_console_only_format(desc.Format)) {
|
||||
return TextureKind::None;
|
||||
}
|
||||
bool block = false;
|
||||
if (!bx_texture_element_bytes(desc.Format, &block)) return TextureKind::None;
|
||||
const UINT layout = static_cast<UINT>(desc.Layout);
|
||||
if (layout == kConsoleLayoutLinear && !block && desc.MipLevels <= 1 && desc.DepthOrArraySize <= 1) return TextureKind::Linear;
|
||||
if (layout >= kConsoleLayoutLinear && bx_gdk_xg_available()) return TextureKind::Tiled;
|
||||
return TextureKind::None;
|
||||
}
|
||||
|
||||
void note_texture_skipped(const D3D12_RESOURCE_DESC& desc, const char* why) {
|
||||
static std::atomic<int> logged{0};
|
||||
if (logged.fetch_add(1) >= 16) return;
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail), "texture %llux%u layout=0x%x format=%d flags=0x%x: contents not copied (%s)",
|
||||
static_cast<unsigned long long>(desc.Width), desc.Height, static_cast<UINT>(desc.Layout),
|
||||
static_cast<int>(desc.Format), static_cast<UINT>(desc.Flags), why);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "texture_contents", detail);
|
||||
}
|
||||
|
||||
/* The upload buffer of `t` (t.upload_bytes, persistently mapped at t.mapped), made when a copy is
|
||||
about to be written. Released again once the GPU has copied from it (#782): a texture whose title
|
||||
memory never changes keeps only its copy. */
|
||||
HRESULT make_upload(ID3D12Device* device, TextureUpload& t) {
|
||||
D3D12_HEAP_PROPERTIES heap{};
|
||||
heap.Type = D3D12_HEAP_TYPE_UPLOAD;
|
||||
D3D12_RESOURCE_DESC buffer{};
|
||||
buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
|
||||
buffer.Width = t.upload_bytes;
|
||||
buffer.Height = 1;
|
||||
buffer.DepthOrArraySize = 1;
|
||||
buffer.MipLevels = 1;
|
||||
buffer.SampleDesc.Count = 1;
|
||||
buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
|
||||
HRESULT hr = t.upload_bytes ? device->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &buffer, D3D12_RESOURCE_STATE_GENERIC_READ,
|
||||
nullptr, __uuidof(ID3D12Resource), reinterpret_cast<void**>(&t.upload))
|
||||
: E_INVALIDARG;
|
||||
if (SUCCEEDED(hr) && t.upload) hr = t.upload->Map(0, nullptr, reinterpret_cast<void**>(&t.mapped));
|
||||
if (FAILED(hr) || !t.mapped) {
|
||||
if (t.upload) t.upload->Release();
|
||||
t.upload = nullptr;
|
||||
t.mapped = nullptr;
|
||||
return FAILED(hr) ? hr : E_FAIL;
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT make_upload(ID3D12Resource* owner, TextureUpload& t) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (!owner || FAILED(owner->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return E_FAIL;
|
||||
const HRESULT hr = make_upload(device, t);
|
||||
device->Release();
|
||||
return hr;
|
||||
}
|
||||
|
||||
/* The footprints of all of `host`'s subresources and an upload buffer for them. */
|
||||
bool prepare_upload(ID3D12Resource* host, TextureUpload& t) {
|
||||
ID3D12Device* device = nullptr;
|
||||
if (FAILED(host->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device))) || !device) return false;
|
||||
const D3D12_RESOURCE_DESC desc = host->GetDesc();
|
||||
const UINT subresources = (desc.MipLevels ? desc.MipLevels : 1) * (desc.DepthOrArraySize ? desc.DepthOrArraySize : 1);
|
||||
t.footprints.resize(subresources);
|
||||
t.rows.resize(subresources);
|
||||
std::vector<UINT64> row_bytes(subresources);
|
||||
UINT64 total = 0;
|
||||
device->GetCopyableFootprints(&desc, 0, subresources, 0, t.footprints.data(), t.rows.data(), row_bytes.data(), &total);
|
||||
t.upload_bytes = total;
|
||||
const HRESULT hr = total ? make_upload(device, t) : E_FAIL;
|
||||
device->Release();
|
||||
if (FAILED(hr) || !t.mapped) {
|
||||
bx_xbox_log_host_failure("XboxResource", "CreateCommittedResource(texture contents upload buffer)", FAILED(hr) ? hr : E_FAIL);
|
||||
t = TextureUpload{};
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Upload buffers the GPU may still be reading, released once their fence passes. */
|
||||
struct Retired {
|
||||
ID3D12Resource* resource;
|
||||
ID3D12Fence* fence;
|
||||
uint64_t value;
|
||||
};
|
||||
std::vector<Retired> g_retired; // under g_texture_lock
|
||||
|
||||
void retire_locked(TextureUpload& t) {
|
||||
if (t.upload) {
|
||||
if (t.fence && t.fence->GetCompletedValue() < t.fence_value) {
|
||||
g_retired.push_back({t.upload, t.fence, t.fence_value});
|
||||
} else {
|
||||
t.upload->Release();
|
||||
}
|
||||
}
|
||||
t.upload = nullptr;
|
||||
t.mapped = nullptr;
|
||||
}
|
||||
|
||||
void sweep_retired_locked() {
|
||||
for (size_t i = 0; i < g_retired.size();) {
|
||||
if (g_retired[i].fence->GetCompletedValue() >= g_retired[i].value) {
|
||||
g_retired[i].resource->Release();
|
||||
g_retired[i] = g_retired.back();
|
||||
g_retired.pop_back();
|
||||
} else {
|
||||
++i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Implicit shadows the title replaced (#782). The title reuses memory only once its own GPU work on
|
||||
* the old contents is done, so the host resource is no longer needed by the title; it is still
|
||||
* released only kReleaseAfter queue submissions later, as a margin for host work in flight. Its
|
||||
* texture-contents copy is retired through the copy's own fence (retire_locked), and translated-draw
|
||||
* markers of it stop referencing it (bx_console_forget_resource) and resolve to null views.
|
||||
*/
|
||||
constexpr uint64_t kReleaseAfter = 64; // queue submissions
|
||||
struct RetiredShadow {
|
||||
ID3D12Resource* host;
|
||||
uint64_t submission;
|
||||
};
|
||||
std::mutex g_implicit_lock;
|
||||
std::vector<RetiredShadow> g_implicit_retired; // under g_implicit_lock
|
||||
std::atomic<uint64_t> g_submissions{0};
|
||||
std::atomic<uint64_t> g_implicit_retired_total{0};
|
||||
std::atomic<uint64_t> g_implicit_released_total{0};
|
||||
|
||||
void retire_implicit(const std::vector<ID3D12Resource*>& hosts) {
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_texture_lock);
|
||||
for (ID3D12Resource* host : hosts) {
|
||||
auto upload = g_texture_uploads.find(host);
|
||||
if (upload != g_texture_uploads.end()) {
|
||||
retire_locked(upload->second);
|
||||
g_texture_uploads.erase(upload);
|
||||
}
|
||||
}
|
||||
}
|
||||
const uint64_t now = g_submissions.load();
|
||||
std::lock_guard<std::mutex> guard(g_implicit_lock);
|
||||
for (ID3D12Resource* host : hosts) g_implicit_retired.push_back({host, now});
|
||||
g_implicit_retired_total += hosts.size();
|
||||
}
|
||||
|
||||
void sweep_implicit() {
|
||||
const uint64_t now = g_submissions.load();
|
||||
std::vector<ID3D12Resource*> release;
|
||||
size_t pending = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_implicit_lock);
|
||||
for (size_t i = 0; i < g_implicit_retired.size();) {
|
||||
if (g_implicit_retired[i].submission + kReleaseAfter <= now) {
|
||||
release.push_back(g_implicit_retired[i].host);
|
||||
g_implicit_retired[i] = g_implicit_retired.back();
|
||||
g_implicit_retired.pop_back();
|
||||
} else {
|
||||
++i;
|
||||
}
|
||||
}
|
||||
pending = g_implicit_retired.size();
|
||||
}
|
||||
if (release.empty()) return;
|
||||
for (ID3D12Resource* host : release) {
|
||||
bx_console_forget_resource(host);
|
||||
host->Release();
|
||||
}
|
||||
const uint64_t before = g_implicit_released_total.fetch_add(release.size());
|
||||
const uint64_t after = before + release.size();
|
||||
// Logged at the first release and whenever the total passes a power of two.
|
||||
auto bits = [](uint64_t v) {
|
||||
int n = 0;
|
||||
for (; v; v >>= 1) ++n;
|
||||
return n;
|
||||
};
|
||||
if (before == 0 || bits(after) > bits(before)) {
|
||||
size_t live = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
for (size_t i = 0; i < g_count; ++i) live += g_shadows[i].implicit ? 1 : 0;
|
||||
}
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail), "live=%zu retired=%llu released=%llu pending=%zu", live,
|
||||
static_cast<unsigned long long>(g_implicit_retired_total.load()), static_cast<unsigned long long>(after),
|
||||
pending);
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "implicit_shadows", detail);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
@@ -215,7 +539,41 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_srv_x(void* self, const
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
device->CreateShaderResourceView(resource, host.of(&pc, "CreatePlacedRawShaderResourceViewX"), bx_xbox_host_cpu_handle(dest));
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc = host.of(&pc, "CreatePlacedRawShaderResourceViewX");
|
||||
device->CreateShaderResourceView(resource, host_desc, bx_xbox_host_cpu_handle(dest));
|
||||
// "Raw" is a view of placed memory without a resource object, a texture as often as a buffer:
|
||||
// the target build makes the views of its menu textures this way, once per frame, and copies
|
||||
// them into its draws' tables. A texture view leaves the marker CreatePlacedShaderResourceViewX
|
||||
// leaves, so translated draws find it and read the texture's contents from title memory.
|
||||
if (pc.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) {
|
||||
bx_console_mark_srv(dest.ptr, resource, host_desc);
|
||||
return;
|
||||
}
|
||||
// On the console this view is a buffer descriptor in the title's memory: titles copy it into
|
||||
// their draws' tables with plain stores, and scalar buffer loads read it like a constant buffer.
|
||||
// Leave a marker of a constant view of its title memory, so the copy carries it and translated
|
||||
// draws read the buffer's current contents (console_descriptors.cpp).
|
||||
// Bytes per element: 4 for a raw view, the stride for a structured one, the format's size for a
|
||||
// typed one (16 for R32G32B32A32_FLOAT). A typed view of a format without a known size, or of a
|
||||
// block-compressed one, gets no marker.
|
||||
uint64_t element = 4;
|
||||
if (!(pc.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW)) {
|
||||
if (pc.Buffer.StructureByteStride) {
|
||||
element = pc.Buffer.StructureByteStride;
|
||||
} else {
|
||||
bool block = false;
|
||||
element = bx_texture_element_bytes(pc.Format, &block);
|
||||
if (!element || block) return;
|
||||
}
|
||||
}
|
||||
const uint64_t offset = pc.Buffer.FirstElement * element;
|
||||
uint64_t bytes = static_cast<uint64_t>(pc.Buffer.NumElements) * element;
|
||||
if (bytes > D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * 16) bytes = D3D12_REQ_CONSTANT_BUFFER_ELEMENT_COUNT * 16;
|
||||
D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{};
|
||||
cbv.BufferLocation = resource->GetGPUVirtualAddress() + offset;
|
||||
cbv.SizeInBytes = static_cast<UINT>((bytes + 255) & ~255ull);
|
||||
// The fallback lies in the implicit shadow, which is released if the title replaces it.
|
||||
if (bytes) bx_console_mark_cbv_of(dest.ptr, view_location(xbox_desc) + offset, cbv, resource);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_raw_uav_x(void* self, const D3D12_RESOURCE_DESC* resource_desc,
|
||||
@@ -236,9 +594,11 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_srv_x(void* self, ID3D12Reso
|
||||
D3D12_SHADER_RESOURCE_VIEW_DESC pc{};
|
||||
if (xbox_desc) std::memcpy(&pc, xbox_desc, kPcViewDescBytes);
|
||||
BxHostFormat<D3D12_SHADER_RESOURCE_VIEW_DESC> host;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(
|
||||
bx_xbox_unwrap_as(resource), xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr,
|
||||
bx_xbox_host_cpu_handle(dest));
|
||||
ID3D12Resource* host_resource = bx_xbox_unwrap_as(resource);
|
||||
const D3D12_SHADER_RESOURCE_VIEW_DESC* host_desc = xbox_desc ? host.of(&pc, "CreatePlacedShaderResourceViewX") : nullptr;
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateShaderResourceView(host_resource, host_desc, bx_xbox_host_cpu_handle(dest));
|
||||
// Translated draws find the view through its marker, as for CreateShaderResourceView (#745).
|
||||
bx_console_mark_srv(dest.ptr, host_resource, host_desc);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Resource* resource, const void* xbox_desc,
|
||||
@@ -377,6 +737,145 @@ bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64
|
||||
attributes});
|
||||
}
|
||||
|
||||
ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads* uploads) {
|
||||
if (!uploads || !uploads->list) return host;
|
||||
Shadow shadow{};
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_lock);
|
||||
size_t i = 0;
|
||||
while (i < g_count && g_shadows[i].host != host) ++i;
|
||||
if (i == g_count || g_shadows[i].buffer) return host;
|
||||
shadow = g_shadows[i];
|
||||
}
|
||||
const TextureKind kind = texture_kind(shadow.desc);
|
||||
if (kind == TextureKind::None) {
|
||||
note_texture_skipped(shadow.desc, "no copy for this layout or format");
|
||||
return host;
|
||||
}
|
||||
// The texture's entry, made on first use. The lock is held for the whole check and upload:
|
||||
// the upload writes the entry's buffer and records onto the submission's list.
|
||||
std::lock_guard<std::mutex> guard(g_texture_lock);
|
||||
sweep_retired_locked();
|
||||
TextureUpload& known = g_texture_uploads[host];
|
||||
if (!known.upload_bytes || known.title_va != shadow.title_va) {
|
||||
retire_locked(known);
|
||||
known = TextureUpload{};
|
||||
if (!prepare_upload(host, known)) {
|
||||
g_texture_uploads.erase(host);
|
||||
note_texture_skipped(shadow.desc, "the host refused its upload buffer");
|
||||
return host;
|
||||
}
|
||||
known.title_va = shadow.title_va;
|
||||
}
|
||||
const uint64_t now = GetTickCount64();
|
||||
if (known.filled && now - known.checked_at < known.interval) return host;
|
||||
// The GPU is still copying from this buffer (from an earlier submission): check later.
|
||||
if (known.fence && known.fence->GetCompletedValue() < known.fence_value) return host;
|
||||
// The GPU is past the last copy: the upload buffer is not needed until the title memory
|
||||
// changes, and is made again then (#782).
|
||||
if (known.filled && known.upload) {
|
||||
known.upload->Release();
|
||||
known.upload = nullptr;
|
||||
known.mapped = nullptr;
|
||||
}
|
||||
known.checked_at = now;
|
||||
// The title memory the texture occupies.
|
||||
uint64_t bytes = 0;
|
||||
UINT title_pitch = 0;
|
||||
bool block = false;
|
||||
const UINT element = bx_texture_element_bytes(shadow.desc.Format, &block);
|
||||
if (kind == TextureKind::Linear) {
|
||||
title_pitch = static_cast<UINT>((shadow.desc.Width * element + 255) / 256 * 256);
|
||||
bytes = static_cast<uint64_t>(title_pitch) * shadow.desc.Height;
|
||||
} else {
|
||||
uint64_t alignment = 0;
|
||||
if (!bx_gdk_xg_layout_size(shadow.desc, &bytes, &alignment)) bytes = 0;
|
||||
}
|
||||
HRESULT hr = E_FAIL;
|
||||
UINT subresources = 0;
|
||||
uint64_t sample = 0;
|
||||
const bool filled = known.filled;
|
||||
if (!bytes) {
|
||||
hr = E_NOTIMPL;
|
||||
} else if (!readable(reinterpret_cast<const void*>(shadow.title_va), bytes)) {
|
||||
hr = E_ACCESSDENIED;
|
||||
} else {
|
||||
sample = sample_hash(shadow.title_va, bytes);
|
||||
if (filled && sample == known.sample) {
|
||||
hr = S_FALSE; // checked, unchanged
|
||||
} else if (!known.upload && FAILED(hr = make_upload(host, known))) {
|
||||
// no upload buffer: logged below, the next draw tries again
|
||||
} else if (kind == TextureKind::Linear) {
|
||||
const D3D12_PLACED_SUBRESOURCE_FOOTPRINT& fp = known.footprints[0];
|
||||
const size_t row = static_cast<size_t>(shadow.desc.Width) * element;
|
||||
for (UINT y = 0; y < shadow.desc.Height; ++y) {
|
||||
std::memcpy(known.mapped + fp.Offset + static_cast<size_t>(y) * fp.Footprint.RowPitch,
|
||||
reinterpret_cast<const uint8_t*>(shadow.title_va) + static_cast<size_t>(y) * title_pitch, row);
|
||||
}
|
||||
subresources = 1;
|
||||
hr = S_OK;
|
||||
} else {
|
||||
hr = bx_gdk_xg_detile(shadow.desc, reinterpret_cast<const void*>(shadow.title_va), known.mapped, known.footprints.data(),
|
||||
known.rows.data(), static_cast<UINT>(known.footprints.size()), &subresources);
|
||||
}
|
||||
}
|
||||
if (hr == S_OK) {
|
||||
ID3D12GraphicsCommandList* list = uploads->list;
|
||||
// A simultaneous-access shadow is promoted from COMMON by the copy and decays back after
|
||||
// the list; one without it (the host refused the flag) is moved explicitly from COMMON.
|
||||
D3D12_RESOURCE_BARRIER b{};
|
||||
b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
|
||||
b.Transition.pResource = host;
|
||||
b.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
|
||||
b.Transition.StateBefore = D3D12_RESOURCE_STATE_COMMON;
|
||||
b.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST;
|
||||
if (!shadow.simultaneous) list->ResourceBarrier(1, &b);
|
||||
for (UINT sub = 0; sub < subresources; ++sub) {
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{host, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
dst.SubresourceIndex = sub;
|
||||
D3D12_TEXTURE_COPY_LOCATION src{known.upload, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}};
|
||||
src.PlacedFootprint = known.footprints[sub];
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
}
|
||||
std::swap(b.Transition.StateBefore, b.Transition.StateAfter);
|
||||
if (!shadow.simultaneous) list->ResourceBarrier(1, &b);
|
||||
uploads->recorded = true;
|
||||
known.fence = uploads->fence;
|
||||
known.fence_value = uploads->value;
|
||||
known.filled = true;
|
||||
known.sample = sample;
|
||||
// Changed: checked again at its next draw. A video or other texture the title rewrites
|
||||
// every frame is then copied as often as it changes, not at most every few hundred ms.
|
||||
known.interval = 0;
|
||||
} else if (hr == S_FALSE) {
|
||||
const uint64_t next = known.interval < kTextureCheckMs ? kTextureCheckMs : known.interval * 2;
|
||||
known.interval = next > kTextureCheckMaxMs ? kTextureCheckMaxMs : next;
|
||||
} else if (!known.filled) {
|
||||
known.checked_at = 0; // the next draw tries again
|
||||
}
|
||||
if (hr != S_FALSE) {
|
||||
static std::atomic<int> logged{0};
|
||||
static std::atomic<int> failures{0};
|
||||
static std::atomic<int> recopied{0};
|
||||
const bool again = SUCCEEDED(hr) && filled;
|
||||
if (FAILED(hr) ? failures.fetch_add(1) < 16 : again ? recopied.fetch_add(1) < 8 : logged.fetch_add(1) < 8) {
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "%s texture %llux%u layout=0x%x format=%d mips=%u: %u subresource(s)%s, hr=0x%08lx",
|
||||
kind == TextureKind::Linear ? "linear" : "tiled", static_cast<unsigned long long>(shadow.desc.Width),
|
||||
shadow.desc.Height, static_cast<UINT>(shadow.desc.Layout), static_cast<int>(shadow.desc.Format),
|
||||
shadow.desc.MipLevels, subresources, again ? " copied again: its title memory changed" : "",
|
||||
static_cast<unsigned long>(hr));
|
||||
bx_log_emit(FAILED(hr) ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "texture_contents", detail);
|
||||
}
|
||||
}
|
||||
return host;
|
||||
}
|
||||
|
||||
void bx_xbox_placed_note_submission() {
|
||||
++g_submissions;
|
||||
sweep_implicit();
|
||||
}
|
||||
|
||||
void bx_xbox_placed_forget(IUnknown* host) {
|
||||
Shadow gone{};
|
||||
{
|
||||
@@ -389,6 +888,14 @@ void bx_xbox_placed_forget(IUnknown* host) {
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> guard(g_texture_lock);
|
||||
auto upload = g_texture_uploads.find(host);
|
||||
if (upload != g_texture_uploads.end()) {
|
||||
retire_locked(upload->second);
|
||||
g_texture_uploads.erase(upload);
|
||||
}
|
||||
}
|
||||
if (gone.title_attributes) XMemFree(reinterpret_cast<void*>(gone.title_va), gone.title_attributes);
|
||||
}
|
||||
|
||||
@@ -422,17 +929,10 @@ struct PagePool {
|
||||
|
||||
PagePool* g_pools = nullptr; // guarded by g_lock
|
||||
|
||||
// Every page is present: committed, or mapped by xmem and not touched yet (#754). Checking maps
|
||||
// nothing, so registering a pool of 100,000 pages does not map them.
|
||||
bool fully_mapped(uint64_t address, uint64_t size) {
|
||||
auto cursor = static_cast<uintptr_t>(address);
|
||||
const uintptr_t end = cursor + static_cast<uintptr_t>(size);
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
return bx_title_memory_present(address, size);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -480,8 +980,8 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_unregister_page_pool_x(void*, HANDLE ha
|
||||
* Map on a resource that has title-visible memory (placed at a title address, or committed with
|
||||
* XMemAlloc memory) returns that memory, as on the console, where CPU and GPU share it. Other
|
||||
* resources map their host resource. Writes through the title pointer reach the host resource
|
||||
* only where this layer copies them (buffers at creation; texture contents are not copied yet,
|
||||
* logged at creation).
|
||||
* only where this layer copies them (buffers at creation; texture contents when a translated draw
|
||||
* reads them, bx_xbox_texture_contents).
|
||||
*/
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_resource_map(void* self, UINT subresource, const D3D12_RANGE* read, void** data) {
|
||||
BX_D3D_TRACE("XboxResource", "Map");
|
||||
|
||||
@@ -8,9 +8,21 @@
|
||||
* window (the visible window owned by this process), sized to plane 0's first resource. Each
|
||||
* present copies that resource into the current back buffer when formats and sizes match, and
|
||||
* otherwise leaves the back buffer unchanged (logged once), then presents with sync interval 0: frame pacing
|
||||
* is the title's own, through the frame events (frame_pacing.cpp). Plane 1, source and
|
||||
* destination rectangles, colour spaces and scaling are not applied (logged once).
|
||||
* is the title's own, through the frame events (frame_pacing.cpp).
|
||||
*
|
||||
* Several planes, or source and destination rectangles, are composed the way the console's display
|
||||
* hardware composes them (authorized GDK documentation, "Hardware overlays"): plane 0 is the
|
||||
* background plane and plane 1 the HUD plane in front of it; content is premultiplied alpha; a
|
||||
* plane's source rectangle (pSrcViewRects) is in texels of its resource, its destination rectangle
|
||||
* (pDestPlacementBase, D3D12XBOX_VIEW_RECT) is normalized to the output; a plane left out is black
|
||||
* with alpha 0. Each plane is drawn, scaled with a bilinear filter, over transparent black in plane
|
||||
* order with the blend ONE, INV_SRC_ALPHA into a texture of the swapchain's size, which is copied
|
||||
* to the back buffer. The shaders are compiled at the first such present with the GDK's PC
|
||||
* dxcompiler.dll (bx_console_compile_hlsl); without it plane 0 is copied as before (logged). Colour
|
||||
* spaces other than RGB full G2.2 P709 (the SDR case) are composed as SDR, in plane order (logged
|
||||
* once); for HDR the documentation puts the scene in plane 1 and the UI in plane 0.
|
||||
*/
|
||||
#include "console_pipelines.h"
|
||||
#include "xbox_facade.h"
|
||||
|
||||
#include <dxgi1_4.h>
|
||||
@@ -21,6 +33,7 @@
|
||||
#include <cstdlib>
|
||||
#include <cwchar>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
@@ -58,6 +71,7 @@ struct Presenter {
|
||||
};
|
||||
Presenter g;
|
||||
|
||||
|
||||
struct FindWindow {
|
||||
DWORD pid;
|
||||
HWND found;
|
||||
@@ -167,6 +181,175 @@ void barrier(ID3D12GraphicsCommandList* list, ID3D12Resource* r, D3D12_RESOURCE_
|
||||
list->ResourceBarrier(1, &b);
|
||||
}
|
||||
|
||||
/* Plane composition (see the file comment). Created at the first present that needs it. */
|
||||
constexpr UINT kMaxPlanes = 4;
|
||||
|
||||
struct Composer {
|
||||
bool tried = false;
|
||||
bool ready = false;
|
||||
ID3D12RootSignature* root = nullptr;
|
||||
ID3D12PipelineState* pso = nullptr;
|
||||
ID3D12DescriptorHeap* srvs = nullptr; // shader-visible, kMaxPlanes per back buffer
|
||||
ID3D12DescriptorHeap* rtv = nullptr;
|
||||
ID3D12Resource* target = nullptr; // swapchain-sized, the composed frame
|
||||
UINT srv_size = 0;
|
||||
};
|
||||
Composer c;
|
||||
|
||||
const char kComposeRoot[] =
|
||||
"#define RS \"RootConstants(num32BitConstants=8, b0), DescriptorTable(SRV(t0)), "
|
||||
"StaticSampler(s0, filter=FILTER_MIN_MAG_MIP_LINEAR, addressU=TEXTURE_ADDRESS_CLAMP, addressV=TEXTURE_ADDRESS_CLAMP)\"\n"
|
||||
"cbuffer Place : register(b0) { float4 dst; float4 src; };\n";
|
||||
|
||||
// A quad over the destination rectangle (normalized, y down), sampling the source rectangle (uv).
|
||||
const char kComposeVs[] =
|
||||
"struct V { float4 pos : SV_Position; float2 uv : TEXCOORD0; };\n"
|
||||
"[RootSignature(RS)] V main(uint id : SV_VertexID) {\n"
|
||||
" float2 c = float2(id & 1, id >> 1);\n"
|
||||
" float2 p = lerp(dst.xy, dst.zw, c);\n"
|
||||
" V o; o.pos = float4(p.x * 2.0 - 1.0, 1.0 - p.y * 2.0, 0.0, 1.0); o.uv = lerp(src.xy, src.zw, c); return o;\n"
|
||||
"}\n";
|
||||
|
||||
const char kComposePs[] =
|
||||
"Texture2D<float4> plane : register(t0);\n"
|
||||
"SamplerState linear_clamp : register(s0);\n"
|
||||
"[RootSignature(RS)] float4 main(float4 pos : SV_Position, float2 uv : TEXCOORD0) : SV_Target0 {\n"
|
||||
" return plane.Sample(linear_clamp, uv);\n"
|
||||
"}\n";
|
||||
|
||||
bool composer_ready(ID3D12Device* device) {
|
||||
if (c.tried) return c.ready;
|
||||
c.tried = true;
|
||||
std::vector<uint8_t> vs, ps;
|
||||
std::string why;
|
||||
const std::string vs_src = std::string(kComposeRoot) + kComposeVs;
|
||||
const std::string ps_src = std::string(kComposeRoot) + kComposePs;
|
||||
if (!bx_console_compile_hlsl(vs_src.c_str(), false, vs, why) || !bx_console_compile_hlsl(ps_src.c_str(), true, ps, why)) {
|
||||
const std::string detail = "plane composition unavailable (" + why + "); plane 0 is copied as is";
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail.c_str());
|
||||
return false;
|
||||
}
|
||||
HRESULT hr = device->CreateRootSignature(0, vs.data(), vs.size(), __uuidof(ID3D12RootSignature), reinterpret_cast<void**>(&c.root));
|
||||
D3D12_GRAPHICS_PIPELINE_STATE_DESC d{};
|
||||
d.pRootSignature = c.root;
|
||||
d.VS = {vs.data(), vs.size()};
|
||||
d.PS = {ps.data(), ps.size()};
|
||||
D3D12_RENDER_TARGET_BLEND_DESC& b = d.BlendState.RenderTarget[0];
|
||||
b.BlendEnable = TRUE; // premultiplied alpha: out = src + dst * (1 - src.a)
|
||||
b.SrcBlend = D3D12_BLEND_ONE;
|
||||
b.DestBlend = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
b.BlendOp = D3D12_BLEND_OP_ADD;
|
||||
b.SrcBlendAlpha = D3D12_BLEND_ONE;
|
||||
b.DestBlendAlpha = D3D12_BLEND_INV_SRC_ALPHA;
|
||||
b.BlendOpAlpha = D3D12_BLEND_OP_ADD;
|
||||
b.RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
|
||||
d.SampleMask = UINT_MAX;
|
||||
d.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID;
|
||||
d.RasterizerState.CullMode = D3D12_CULL_MODE_NONE;
|
||||
d.RasterizerState.DepthClipEnable = TRUE;
|
||||
d.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
|
||||
d.NumRenderTargets = 1;
|
||||
d.RTVFormats[0] = g.format;
|
||||
d.SampleDesc.Count = 1;
|
||||
if (SUCCEEDED(hr)) hr = device->CreateGraphicsPipelineState(&d, __uuidof(ID3D12PipelineState), reinterpret_cast<void**>(&c.pso));
|
||||
D3D12_DESCRIPTOR_HEAP_DESC heap{};
|
||||
heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
|
||||
heap.NumDescriptors = kMaxPlanes * kBuffers;
|
||||
heap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
|
||||
if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&heap, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&c.srvs));
|
||||
heap.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
|
||||
heap.NumDescriptors = 1;
|
||||
heap.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
|
||||
if (SUCCEEDED(hr)) hr = device->CreateDescriptorHeap(&heap, __uuidof(ID3D12DescriptorHeap), reinterpret_cast<void**>(&c.rtv));
|
||||
D3D12_HEAP_PROPERTIES props{};
|
||||
props.Type = D3D12_HEAP_TYPE_DEFAULT;
|
||||
D3D12_RESOURCE_DESC t{};
|
||||
t.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
|
||||
t.Width = g.width;
|
||||
t.Height = g.height;
|
||||
t.DepthOrArraySize = 1;
|
||||
t.MipLevels = 1;
|
||||
t.Format = g.format;
|
||||
t.SampleDesc.Count = 1;
|
||||
t.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
|
||||
if (SUCCEEDED(hr)) {
|
||||
hr = device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &t, D3D12_RESOURCE_STATE_COMMON, nullptr,
|
||||
__uuidof(ID3D12Resource), reinterpret_cast<void**>(&c.target));
|
||||
}
|
||||
if (FAILED(hr)) {
|
||||
log_hr("plane composition resources (plane 0 is copied as is)", hr);
|
||||
return false;
|
||||
}
|
||||
device->CreateRenderTargetView(c.target, nullptr, c.rtv->GetCPUDescriptorHandleForHeapStart());
|
||||
c.srv_size = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
|
||||
c.ready = true;
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox", "plane composition ready: planes are composed in order, premultiplied alpha");
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Records the composition of `count` planes into c.target, then the copy to `back`. */
|
||||
void compose(ID3D12Device* device, const PlaneParameters* planes, UINT count, UINT index, ID3D12Resource* back) {
|
||||
ID3D12GraphicsCommandList* list = g.list;
|
||||
ID3D12Resource* sources[kMaxPlanes] = {};
|
||||
UINT n = 0;
|
||||
for (UINT i = 0; i < count && n < kMaxPlanes; ++i) {
|
||||
ID3D12Resource* r = planes[i].ResourceCount && planes[i].ppResources ? bx_xbox_unwrap_as(planes[i].ppResources[0]) : nullptr;
|
||||
bool repeated = false;
|
||||
for (UINT k = 0; k < n; ++k) repeated = repeated || sources[k] == r;
|
||||
sources[n++] = repeated ? nullptr : r; // a resource shown twice is transitioned once
|
||||
}
|
||||
for (UINT i = 0; i < n; ++i) {
|
||||
if (sources[i]) barrier(list, sources[i], D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE);
|
||||
}
|
||||
barrier(list, c.target, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET);
|
||||
const D3D12_CPU_DESCRIPTOR_HANDLE rtv = c.rtv->GetCPUDescriptorHandleForHeapStart();
|
||||
const FLOAT clear[4] = {0, 0, 0, 0}; // a plane left out is black with alpha 0
|
||||
list->ClearRenderTargetView(rtv, clear, 0, nullptr);
|
||||
list->OMSetRenderTargets(1, &rtv, FALSE, nullptr);
|
||||
const D3D12_VIEWPORT viewport{0, 0, static_cast<float>(g.width), static_cast<float>(g.height), 0, 1};
|
||||
const D3D12_RECT scissor{0, 0, static_cast<LONG>(g.width), static_cast<LONG>(g.height)};
|
||||
list->RSSetViewports(1, &viewport);
|
||||
list->RSSetScissorRects(1, &scissor);
|
||||
list->SetGraphicsRootSignature(c.root);
|
||||
list->SetPipelineState(c.pso);
|
||||
list->SetDescriptorHeaps(1, &c.srvs);
|
||||
list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
|
||||
for (UINT i = 0; i < count && i < kMaxPlanes; ++i) {
|
||||
const PlaneParameters& p = planes[i];
|
||||
ID3D12Resource* r = p.ResourceCount && p.ppResources ? bx_xbox_unwrap_as(p.ppResources[0]) : nullptr;
|
||||
if (!r) continue;
|
||||
const D3D12_RESOURCE_DESC rd = r->GetDesc();
|
||||
float place[8] = {0, 0, 1, 1, 0, 0, 1, 1};
|
||||
if (p.pDestPlacementBase) std::memcpy(place, p.pDestPlacementBase, 4 * sizeof(float)); // D3D12XBOX_VIEW_RECT
|
||||
if (p.pSrcViewRects && rd.Width && rd.Height) {
|
||||
const D3D12_RECT& s = p.pSrcViewRects[0];
|
||||
place[4] = static_cast<float>(s.left) / static_cast<float>(rd.Width);
|
||||
place[5] = static_cast<float>(s.top) / static_cast<float>(rd.Height);
|
||||
place[6] = static_cast<float>(s.right) / static_cast<float>(rd.Width);
|
||||
place[7] = static_cast<float>(s.bottom) / static_cast<float>(rd.Height);
|
||||
}
|
||||
const UINT slot = index * kMaxPlanes + i;
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE cpu = c.srvs->GetCPUDescriptorHandleForHeapStart();
|
||||
cpu.ptr += static_cast<SIZE_T>(slot) * c.srv_size;
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE gpu = c.srvs->GetGPUDescriptorHandleForHeapStart();
|
||||
gpu.ptr += static_cast<UINT64>(slot) * c.srv_size;
|
||||
device->CreateShaderResourceView(r, nullptr, cpu);
|
||||
list->SetGraphicsRoot32BitConstants(0, 8, place, 0);
|
||||
list->SetGraphicsRootDescriptorTable(1, gpu);
|
||||
list->DrawInstanced(4, 1, 0, 0);
|
||||
}
|
||||
barrier(list, c.target, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
D3D12_TEXTURE_COPY_LOCATION dst{back, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
D3D12_TEXTURE_COPY_LOCATION src{c.target, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}};
|
||||
list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr);
|
||||
barrier(list, back, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_PRESENT);
|
||||
barrier(list, c.target, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
for (UINT i = 0; i < n; ++i) {
|
||||
if (sources[i]) barrier(list, sources[i], D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_COMMON);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Diagnostics (off unless BX_PRESENT_DUMP=<folder>): every BX_PRESENT_DUMP_EVERY-th present (default
|
||||
// 64, at most 32 files) the presented buffer is copied to a readback buffer and written as a BMP,
|
||||
@@ -280,7 +463,6 @@ void dump_frame(ID3D12CommandQueue* queue, ID3D12Resource* source, const D3D12_R
|
||||
extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT plane_count, const void* planes_raw,
|
||||
const void* parameters) {
|
||||
BX_D3D_TRACE("XboxCommandQueue", "PresentX");
|
||||
(void)parameters;
|
||||
// Call and return times for GetFrameStatisticsX, kept for the first plane's pipeline token.
|
||||
struct PresentTimes {
|
||||
UINT64 token;
|
||||
@@ -308,10 +490,45 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
g.failed = true;
|
||||
return S_OK; // the title keeps running; frames are not shown (logged)
|
||||
}
|
||||
static std::atomic<bool> logged_extra{false};
|
||||
if ((plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase) && !logged_extra.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "presentx_xbox",
|
||||
"plane 1, view rectangles, placement and scaling are not applied; plane 0 is copied as is");
|
||||
// Limits of the composition, logged once each (GDK documentation, D3D12XBOX_PRESENT_PLANE_PARAMETERS
|
||||
// and "Hardware overlays and swap resources"): a plane's resources may be a colour texture and
|
||||
// a separate alpha texture (an RGBE + A8 pair, colour first), and with several views (split
|
||||
// screen) each view has its own source rectangle.
|
||||
static std::atomic<bool> logged_pair{false};
|
||||
for (UINT i = 0; i < plane_count; ++i) {
|
||||
if (planes[i].ResourceCount > 1 && !logged_pair.exchange(true)) {
|
||||
char detail[200];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"plane %u has %u resources (a colour/alpha pair such as RGBE + A8); only its first resource is "
|
||||
"composed, so a separate alpha is not applied",
|
||||
i, planes[i].ResourceCount);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
if (parameters) {
|
||||
UINT views = 0; // D3D12XBOX_PRESENT_PARAMETERS::ViewCount, after a FLOAT
|
||||
std::memcpy(&views, static_cast<const char*>(parameters) + 4, sizeof(views));
|
||||
static std::atomic<bool> logged_views{false};
|
||||
if (views > 1 && !logged_views.exchange(true)) {
|
||||
char detail[160];
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"PresentX with %u views; only the first view is composed (its source rectangle and placement)", views);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
const bool layered = plane_count > 1 || planes[0].pSrcViewRects || planes[0].pDestPlacementBase;
|
||||
if (layered) {
|
||||
static std::atomic<bool> logged_hdr{false};
|
||||
bool sdr = true;
|
||||
for (UINT i = 0; i < plane_count; ++i) sdr = sdr && planes[i].ColorSpace == 0; // DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709
|
||||
if (!sdr && !logged_hdr.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox",
|
||||
"a plane has a colour space other than RGB full G2.2 P709; planes are composed as SDR, in plane order");
|
||||
}
|
||||
if (plane_count > kMaxPlanes) {
|
||||
static std::atomic<bool> logged_many{false};
|
||||
if (!logged_many.exchange(true)) bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", "more than 4 planes; the rest are not shown");
|
||||
}
|
||||
}
|
||||
const UINT index = g.swapchain->GetCurrentBackBufferIndex();
|
||||
if (g.fence->GetCompletedValue() < g.fence_values[index]) {
|
||||
@@ -328,7 +545,12 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
g.list->Reset(g.allocators[index], nullptr);
|
||||
const bool copyable = desc.Width == g.width && desc.Height == g.height && swapchain_format(desc.Format) == g.format &&
|
||||
desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D && desc.SampleDesc.Count == 1;
|
||||
if (copyable) {
|
||||
ID3D12Device* device = nullptr;
|
||||
queue->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
|
||||
const bool composed = (layered || !copyable) && device && composer_ready(device);
|
||||
if (composed) {
|
||||
compose(device, planes, plane_count, index, back);
|
||||
} else if (copyable) {
|
||||
// The title's buffer is assumed to be presentable (PRESENT, i.e. COMMON) when PresentX is called.
|
||||
barrier(g.list, source, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE);
|
||||
barrier(g.list, back, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_COPY_DEST);
|
||||
@@ -346,6 +568,7 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "presentx_xbox", detail);
|
||||
}
|
||||
}
|
||||
if (device) device->Release();
|
||||
g.list->Close();
|
||||
ID3D12CommandList* lists[] = {g.list};
|
||||
g.queue->ExecuteCommandLists(1, lists);
|
||||
@@ -354,7 +577,13 @@ extern "C" HRESULT STDMETHODCALLTYPE bx_xbox_queue_present_x(void* self, UINT pl
|
||||
g.fence_values[index] = g.next_value++;
|
||||
g.queue->Signal(g.fence, g.fence_values[index]);
|
||||
const UINT64 n = ++g.presents;
|
||||
if (dump_folder() && copyable && n % dump_every() == 0) dump_frame(g.queue, source, desc, n);
|
||||
if (dump_folder() && n % dump_every() == 0) {
|
||||
if (composed) {
|
||||
dump_frame(g.queue, c.target, c.target->GetDesc(), n); // the composed frame
|
||||
} else if (copyable) {
|
||||
dump_frame(g.queue, source, desc, n);
|
||||
}
|
||||
}
|
||||
if ((n & (n - 1)) == 0) {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "frames presented=%llu last hr=0x%08lx", static_cast<unsigned long long>(n),
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
* loops are not emulated.
|
||||
*/
|
||||
#include "xbox_facade.h"
|
||||
#include "title_memory.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
@@ -52,17 +53,7 @@ std::unordered_map<const void*, ListState> g_lists;
|
||||
std::unordered_map<const void*, std::vector<Element>> g_layouts; // host pipeline -> input elements
|
||||
|
||||
bool readable(uint64_t address, uint64_t size) {
|
||||
uint64_t cursor = address;
|
||||
const uint64_t end = address + size;
|
||||
while (cursor < end) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(cursor), ®ion, sizeof(region)) || region.State != MEM_COMMIT ||
|
||||
(region.Protect & (PAGE_NOACCESS | PAGE_GUARD))) {
|
||||
return false;
|
||||
}
|
||||
cursor = reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
|
||||
}
|
||||
return true;
|
||||
return bx_title_memory_present(address, size);
|
||||
}
|
||||
|
||||
/* Space for generated vertices: one upload buffer used as a ring. A position is reused after the
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#include "title_memory.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
namespace {
|
||||
|
||||
bool allows(DWORD protect, bool write) {
|
||||
if (protect & (PAGE_NOACCESS | PAGE_GUARD)) return false;
|
||||
if (!write) return true;
|
||||
constexpr DWORD kWritable = PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY;
|
||||
return (protect & kWritable) != 0;
|
||||
}
|
||||
|
||||
// The end of the present stretch that starts at `address`, or `address` if none.
|
||||
uint64_t present_end(uint64_t address, bool write) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(reinterpret_cast<void*>(static_cast<uintptr_t>(address)), ®ion, sizeof(region))) return address;
|
||||
if (region.State == MEM_COMMIT) {
|
||||
return allows(region.Protect, write) ? reinterpret_cast<uint64_t>(region.BaseAddress) + region.RegionSize
|
||||
: address;
|
||||
}
|
||||
// Not committed: an xmem page that is mapped but not touched yet is present all the same.
|
||||
bx_xmem_region_info_t page{};
|
||||
if (region.State != MEM_RESERVE || !bx_xmem_query_region(address, &page) || !page.size_bytes ||
|
||||
!allows(page.protect_flags, write)) {
|
||||
return address;
|
||||
}
|
||||
return page.base_va + page.size_bytes;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool bx_title_memory_present(uint64_t address, uint64_t size, bool write) {
|
||||
if (!address) return false;
|
||||
const uint64_t end = address + size;
|
||||
for (uint64_t cursor = address; cursor < end;) {
|
||||
const uint64_t next = present_end(cursor, write);
|
||||
if (next <= cursor) return false;
|
||||
cursor = next;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
uint64_t bx_title_memory_readable_extent(uint64_t address, uint64_t limit) {
|
||||
// The stretch that holds `address` only, as with VirtualQuery's region before: one committed
|
||||
// region, or one xmem page.
|
||||
const uint64_t end = address ? present_end(address, false) : 0;
|
||||
if (end <= address) return 0;
|
||||
return end - address < limit ? end - address : limit;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Whether title memory can be read or written, for checks made before d3d12_xs copies from or
|
||||
// into it.
|
||||
//
|
||||
// xmem maps a page of an XMEM_MAPPABLE reservation when it is first touched (#754): until then
|
||||
// the page is still the reservation's placeholder, and VirtualQuery reports it reserved, not
|
||||
// committed. Any instruction that reads or writes it, d3d12_xs's own copies included, faults into
|
||||
// xmem's handler, which maps the page and resumes. So a page counts as present when it is
|
||||
// committed with a fitting protection, or when xmem reports it mapped (bx_xmem_query_region).
|
||||
// These checks map nothing: the copy that follows maps only what it touches.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
// Every byte of [address, address + size) is present and readable (or, with `write`, writable).
|
||||
bool bx_title_memory_present(uint64_t address, uint64_t size, bool write = false);
|
||||
|
||||
// How many bytes from `address` are present and readable, up to `limit`, within the one region
|
||||
// (or xmem page) that holds `address`.
|
||||
uint64_t bx_title_memory_readable_extent(uint64_t address, uint64_t limit);
|
||||
@@ -14,10 +14,15 @@ script reads two headers:
|
||||
For every slot of the chosen Xbox interfaces it emits one of:
|
||||
* a typed forwarder to the PC method of the same name, when the Xbox and PC signatures are
|
||||
equivalent (the PC types are used, so the compiler handles struct returns and the calling
|
||||
convention); interface-pointer parameters are unwrapped and (REFIID, void**) results wrapped;
|
||||
convention); interface-pointer parameters are unwrapped and (REFIID, void**) results wrapped.
|
||||
A forward is refused when a parameter is a structure, or a pointer or array of one, that
|
||||
contains an interface pointer, a GPU virtual address, or a CPU or GPU descriptor handle
|
||||
(nested structures included). State-object subobjects are included: their payload pointer is
|
||||
untyped and the payload structures hold interface pointers. Those slots are logged stubs
|
||||
unless CUSTOM names a hand-written function;
|
||||
* a shared IUnknown/GetDevice slot implemented in xbox_facade.cpp;
|
||||
* a stub that logs BX_VTABLE_STUB_LOG and returns a neutral value, for Xbox-only methods and for
|
||||
methods whose signatures differ.
|
||||
* a stub that logs BX_VTABLE_STUB_LOG and returns a neutral value, for Xbox-only methods, for
|
||||
methods whose signatures differ, and for the refused forwards above.
|
||||
|
||||
Usage: python3 shims/d3d12_xs/tools/gen_xbox_tables.py /path/to/d3d12_xs.h [path/to/pc/d3d12.h]
|
||||
"""
|
||||
@@ -59,8 +64,10 @@ CUSTOM = {
|
||||
"CreateDescriptorHeap": "bx_xbox_device_create_descriptor_heap",
|
||||
"GetDescriptorHandleIncrementSize": "bx_xbox_device_get_descriptor_handle_increment_size",
|
||||
"CreateConstantBufferView": "bx_xbox_device_create_constant_buffer_view",
|
||||
"CopyDescriptorsSimple": "bx_xbox_device_copy_descriptors_simple",
|
||||
"CopyDescriptors": "bx_xbox_device_copy_descriptors",
|
||||
"CreateCommandSignature": "bx_xbox_device_create_command_signature",
|
||||
"CreateRootSignature": "bx_xbox_device_create_root_signature",
|
||||
"CreatePipelineState": "bx_xbox_device_create_pipeline_state",
|
||||
"DeserializeGraphicsPipelineStateX": "bx_xbox_device_deserialize_graphics_pipeline_state_x",
|
||||
"CreateDerivedGraphicsPipelineStateX": "bx_xbox_device_create_derived_graphics_pipeline_state_x",
|
||||
@@ -105,9 +112,20 @@ 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",
|
||||
"Barrier": "bx_xbox_list_barrier",
|
||||
"BeginRenderPass": "bx_xbox_list_begin_render_pass",
|
||||
"DispatchRays": "bx_xbox_list_dispatch_rays",
|
||||
"BuildRaytracingAccelerationStructure": "bx_xbox_list_build_raytracing_acceleration_structure",
|
||||
"EmitRaytracingAccelerationStructurePostbuildInfo": "bx_xbox_list_emit_raytracing_postbuild_info",
|
||||
"WriteBufferImmediate": "bx_xbox_list_write_buffer_immediate",
|
||||
"SOSetTargets": "bx_xbox_list_so_set_targets",
|
||||
"OMSetRenderTargets": "bx_xbox_list_om_set_render_targets",
|
||||
"IASetVertexBuffers": "bx_xbox_list_ia_set_vertex_buffers",
|
||||
"IASetPrimitiveTopology": "bx_xbox_list_ia_set_primitive_topology",
|
||||
"SetGraphicsRootDescriptorTable": "bx_xbox_list_set_graphics_root_descriptor_table",
|
||||
"SetGraphicsRootShaderResourceView": "bx_xbox_list_set_graphics_root_shader_resource_view",
|
||||
"SetGraphicsRootConstantBufferView": "bx_xbox_list_set_graphics_root_constant_buffer_view",
|
||||
"IASetIndexBuffer": "bx_xbox_list_ia_set_index_buffer",
|
||||
"SetPipelineState": "bx_xbox_list_set_pipeline_state",
|
||||
"Reset": "bx_xbox_list_reset",
|
||||
@@ -299,6 +317,85 @@ def failure_value(ret):
|
||||
|
||||
STRUCT_TYPES = set() # filled from the Xbox header's `typedef struct` names
|
||||
|
||||
# A field of one of these shapes, anywhere inside a parameter structure, would be copied
|
||||
# unchanged by a plain forward: a wrapper object or a title GPU address would reach the host.
|
||||
_UNFORWARDABLE_FIELD = re.compile(
|
||||
r"\b(?:ID3D12\w+|IUnknown)\s*\*"
|
||||
r"|\bD3D12_GPU_VIRTUAL_ADDRESS\b"
|
||||
r"|\bD3D12_CPU_DESCRIPTOR_HANDLE\b"
|
||||
r"|\bD3D12_GPU_DESCRIPTOR_HANDLE\b"
|
||||
)
|
||||
# Subobject payloads (root signatures, collections) are not named by a field; pDesc is void*.
|
||||
_STATE_SUBOBJECT = "D3D12_STATE_SUBOBJECT"
|
||||
# Methods whose input structs contain D3D12_GPU_VIRTUAL_ADDRESS fields that D3D12 never
|
||||
# dereferences (it only inspects counts, formats, flags, and null vs. non-null).
|
||||
ALLOW_UNTRANSLATED_STRUCT_FORWARD = {
|
||||
("Device", "GetRaytracingAccelerationStructurePrebuildInfo"),
|
||||
}
|
||||
|
||||
|
||||
def _braced_body(text, open_at):
|
||||
"""text[open_at] is '{'. Returns the interior and the index just past the matching '}'."""
|
||||
depth = 0
|
||||
i = open_at
|
||||
while i < len(text):
|
||||
if text[i] == "{":
|
||||
depth += 1
|
||||
elif text[i] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return text[open_at + 1:i], i + 1
|
||||
i += 1
|
||||
return None, len(text)
|
||||
|
||||
|
||||
def struct_bodies(text):
|
||||
"""Struct name -> field text, from the Xbox header. Comments are dropped; SAL is not meaningful."""
|
||||
cleaned = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
|
||||
cleaned = re.sub(r"//[^\n]*", "", cleaned)
|
||||
found = {}
|
||||
for m in re.finditer(r"typedef\s+struct\s+(?:\w+\s*)?\{", cleaned):
|
||||
body, end = _braced_body(cleaned, m.end() - 1)
|
||||
tail = re.match(r"\s*(\w+)\s*;", cleaned[end:])
|
||||
if body is not None and tail:
|
||||
found[tail.group(1)] = strip_sal(body)
|
||||
for m in re.finditer(r"\bstruct\s+(\w+)\s*\{", cleaned):
|
||||
body, _end = _braced_body(cleaned, m.end() - 1)
|
||||
if body is not None:
|
||||
found.setdefault(m.group(1), strip_sal(body))
|
||||
return found
|
||||
|
||||
|
||||
def sensitive_structs(bodies):
|
||||
"""Structures that (directly or through nested structures) hold an unforwardable field."""
|
||||
if not bodies:
|
||||
return set()
|
||||
name_re = re.compile(r"\b(" + "|".join(re.escape(n) for n in sorted(bodies, key=len, reverse=True)) + r")\b")
|
||||
memo = {}
|
||||
|
||||
def holds(name, stack):
|
||||
if name in memo:
|
||||
return memo[name]
|
||||
if name in stack or name not in bodies:
|
||||
return False
|
||||
body = bodies[name]
|
||||
if _UNFORWARDABLE_FIELD.search(body) or (name == _STATE_SUBOBJECT and re.search(r"\bvoid\s*\*", body)):
|
||||
memo[name] = True
|
||||
return True
|
||||
stack.add(name)
|
||||
hit = any(other != name and holds(other, stack) for other in set(name_re.findall(body)))
|
||||
stack.discard(name)
|
||||
memo[name] = hit
|
||||
return hit
|
||||
|
||||
return {name for name in bodies if holds(name, set())}
|
||||
|
||||
|
||||
def unforwardable_param(sensitive):
|
||||
if not sensitive:
|
||||
return None
|
||||
return re.compile(r"\b(" + "|".join(re.escape(n) for n in sorted(sensitive, key=len, reverse=True)) + r")\b")
|
||||
|
||||
|
||||
def emit_stub(family, slot, name, xret, reason):
|
||||
stub = f'BX_VTABLE_STUB_LOG("Xbox{family}", {slot}u, "{name}");'
|
||||
@@ -339,6 +436,8 @@ def main():
|
||||
iids, bases, tables = parse_xbox(xtext)
|
||||
STRUCT_TYPES.update(re.findall(r"typedef\s+struct\s+(\w+)", xtext))
|
||||
STRUCT_TYPES.update(t for t in re.findall(r"^struct\s+(\w+)\s*$", xtext, re.M))
|
||||
blocked = unforwardable_param(sensitive_structs(struct_bodies(xtext)))
|
||||
blocked_reason = "parameter structure holds an interface pointer, GPU address, or descriptor handle"
|
||||
|
||||
note = ("// Generated by shims/d3d12_xs/tools/gen_xbox_tables.py from the Xbox Series D3D12 header (slot\n"
|
||||
"// order, names and types only) and the toolchain's <d3d12.h>. Do not edit by hand.")
|
||||
@@ -360,11 +459,22 @@ def main():
|
||||
counts["shared"] += 1
|
||||
continue
|
||||
kind = classify(xret, xparams, pc[name]) if name in pc else None
|
||||
if kind:
|
||||
# xparams[0] is the Xbox `this`. A structure after it that holds a wrapper or a title
|
||||
# address must not be forwarded; CUSTOM (already handled) is the hand-written path.
|
||||
holds = bool(
|
||||
kind
|
||||
and blocked
|
||||
and (family, name) not in ALLOW_UNTRANSLATED_STRUCT_FORWARD
|
||||
and any(blocked.search(t) for t in xparams[1:])
|
||||
)
|
||||
if kind and not holds:
|
||||
c += emit_forward(family, slot, name, pc[name], kind[1])
|
||||
counts["forward"] += 1
|
||||
else:
|
||||
reason = "signature differs from the PC method" if name in pc else "Xbox-only method"
|
||||
if holds:
|
||||
reason = blocked_reason
|
||||
else:
|
||||
reason = "signature differs from the PC method" if name in pc else "Xbox-only method"
|
||||
c += emit_stub(family, slot, name, xret, reason)
|
||||
counts["stub"] += 1
|
||||
names.append(f"reinterpret_cast<const void*>(&x_{family}_{slot})")
|
||||
|
||||
+25
-21
@@ -987,8 +987,25 @@ HRESULT decode_xbox_config(void* config) {
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
if (in.page_table_memory_4mb_page_count == 0u) {
|
||||
log_vmem_failed("xbox", "zero_page_table_pages", E_INVALIDARG);
|
||||
/* D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT (0) selects the default of 5 pages (#772). */
|
||||
const uint32_t requested = in.page_table_memory_4mb_page_count == BX_D3D12_XBOX_PAGE_TABLE_COUNT_DEFAULT
|
||||
? BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES : in.page_table_memory_4mb_page_count;
|
||||
const bool clamped = requested > BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES;
|
||||
const uint32_t pages = clamped ? BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES : requested;
|
||||
uint32_t preserve = in.frame_buffer_preserve_memory_size_bytes;
|
||||
if (preserve != BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY &&
|
||||
preserve > BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES) {
|
||||
preserve = BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES;
|
||||
}
|
||||
/* ENABLE_LEGACY_LOWER_BOUND lowers the minimum graphics address from 2 GB to 1 GB (#772). */
|
||||
const bool legacy_lower_bound = (in.flags & BX_D3D12_XBOX_VMEM_FLAG_LEGACY_LOWER_BOUND) != 0;
|
||||
const uint64_t outputs[2] = {legacy_lower_bound ? BX_D3D12_XBOX_LEGACY_MIN_GRAPHICS_ADDRESS
|
||||
: BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS,
|
||||
static_cast<uint64_t>(pages) * BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE};
|
||||
/* The header: the outputs are written even when the call returns E_FAIL. */
|
||||
if (!write_config_bytes(config, offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address), outputs,
|
||||
sizeof(outputs))) {
|
||||
log_vmem_failed("xbox", "unwritable_output", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
@@ -1001,22 +1018,6 @@ HRESULT decode_xbox_config(void* config) {
|
||||
}
|
||||
}
|
||||
|
||||
const bool clamped = in.page_table_memory_4mb_page_count > BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES;
|
||||
const uint32_t pages = clamped ? BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES : in.page_table_memory_4mb_page_count;
|
||||
uint32_t preserve = in.frame_buffer_preserve_memory_size_bytes;
|
||||
if (preserve != BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY &&
|
||||
preserve > BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES) {
|
||||
preserve = BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES;
|
||||
}
|
||||
const uint64_t outputs[2] = {BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS,
|
||||
static_cast<uint64_t>(pages) * BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE};
|
||||
if (!write_config_bytes(config, offsetof(BxXboxVirtualMemoryConfig, minimum_valid_graphics_address), outputs,
|
||||
sizeof(outputs))) {
|
||||
log_vmem_failed("xbox", "unwritable_output", E_INVALIDARG);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
|
||||
/*
|
||||
* The host sizes no GPU page tables and keeps no cross-process frame buffer, so both
|
||||
* values are only recorded. This path leaves the BXVM record and its cached backing heap
|
||||
@@ -1037,10 +1038,12 @@ HRESULT decode_xbox_config(void* config) {
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
"decoder=xbox applied=0 recorded_only=1 page_table_4mb_pages=%u clamped=%d "
|
||||
"frame_buffer_preserve_bytes=%u min_gpu_va=0x%llx max_gpu_va=0x%llx max_estimated=%d "
|
||||
"repeat=%d reason=host_ignores_page_table_size",
|
||||
"repeat=%d reason=host_ignores_page_table_size default_pages=%d legacy_lower_bound=%d",
|
||||
pages, clamped ? 1 : 0, preserve, static_cast<unsigned long long>(outputs[0]),
|
||||
static_cast<unsigned long long>(outputs[1]),
|
||||
pages == BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES ? 0 : 1, repeat ? 1 : 0);
|
||||
pages == BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES ? 0 : 1, repeat ? 1 : 0,
|
||||
in.page_table_memory_4mb_page_count == BX_D3D12_XBOX_PAGE_TABLE_COUNT_DEFAULT ? 1 : 0,
|
||||
legacy_lower_bound ? 1 : 0);
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "vmem_config_recorded", detail);
|
||||
BX_STUB_LOG("d3d12_xs.dll", "D3D12ConfigureVirtualMemoryX");
|
||||
return S_OK;
|
||||
@@ -1069,7 +1072,8 @@ extern "C" HRESULT bx_d3d12_configure_virtual_memory(void* config) {
|
||||
if (header.magic == BX_D3D12_VMEM_MAGIC && header.struct_size == sizeof(BxD3d12VirtualMemoryConfig)) {
|
||||
return decode_bxvm_config(config);
|
||||
}
|
||||
if (header.magic == 0u) {
|
||||
/* An Xbox configuration starts with its Flags: NONE or ENABLE_LEGACY_LOWER_BOUND. */
|
||||
if ((header.magic & ~BX_D3D12_XBOX_VMEM_FLAG_LEGACY_LOWER_BOUND) == 0u) {
|
||||
return decode_xbox_config(config);
|
||||
}
|
||||
|
||||
|
||||
@@ -106,8 +106,12 @@ static_assert(offsetof(BxD3d12VirtualMemoryConfig, cpu_pointer) == 40, "cpu_poin
|
||||
* The host does not size GPU page tables or keep a cross-process frame buffer, so the
|
||||
* decoder records both, writes the outputs and still logs BX_STUB_LOG. The maximum address
|
||||
* is documented only for the default size; for other sizes it is scaled linearly from that
|
||||
* value, an inference the log marks as max_estimated=1. A page count of 0 is refused: the
|
||||
* value of the header's DEFAULT constant is not documented.
|
||||
* value, an inference the log marks as max_estimated=1.
|
||||
*
|
||||
* Authorized GDK header (d3d12_xs.h): D3D12XBOX_PAGE_TABLE_MEMORY_4MB_PAGE_COUNT_DEFAULT is 0 and
|
||||
* selects the default of 5 pages; D3D12XBOX_VIRTUAL_MEMORY_CONFIGURATION_FLAG_ENABLE_LEGACY_LOWER_BOUND
|
||||
* (0x1) makes the lower bound 1 GB instead of 2 GB; and the outputs are written even when the
|
||||
* call returns E_FAIL (#772).
|
||||
*/
|
||||
struct BxXboxVirtualMemoryConfig {
|
||||
uint32_t flags;
|
||||
@@ -132,7 +136,10 @@ constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_DEFAULT_4MB_PAGES = 5u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_MAX_4MB_PAGES = 33u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_LEGACY = 0xFFFFFFFFu;
|
||||
constexpr uint32_t BX_D3D12_XBOX_FRAME_BUFFER_PRESERVE_MAX_BYTES = 64u * 1024u * 1024u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_PAGE_TABLE_COUNT_DEFAULT = 0u;
|
||||
constexpr uint32_t BX_D3D12_XBOX_VMEM_FLAG_LEGACY_LOWER_BOUND = 0x1u;
|
||||
constexpr uint64_t BX_D3D12_XBOX_MIN_GRAPHICS_ADDRESS = 2ull * 1024ull * 1024ull * 1024ull;
|
||||
constexpr uint64_t BX_D3D12_XBOX_LEGACY_MIN_GRAPHICS_ADDRESS = 1ull * 1024ull * 1024ull * 1024ull;
|
||||
/* 159.375 GiB at the default 5 pages (20 MB), so 31.875 GiB per 4 MB page. */
|
||||
constexpr uint64_t BX_D3D12_XBOX_GRAPHICS_BYTES_PER_4MB_PAGE = 0x7F8000000ull;
|
||||
|
||||
|
||||
@@ -24,6 +24,30 @@ Entry* g_entries = nullptr;
|
||||
size_t g_count = 0;
|
||||
size_t g_capacity = 0;
|
||||
|
||||
void translate_ending_access(D3D12_RENDER_PASS_ENDING_ACCESS* access) {
|
||||
if (!access) return;
|
||||
if (access->Type == D3D12_RENDER_PASS_ENDING_ACCESS_TYPE_RESOLVE) {
|
||||
access->Resolve.pSrcResource = bx_xbox_unwrap_as(access->Resolve.pSrcResource);
|
||||
access->Resolve.pDstResource = bx_xbox_unwrap_as(access->Resolve.pDstResource);
|
||||
return;
|
||||
}
|
||||
// The union only carries Resolve. Clearing its pointers keeps a wrapper out of the host
|
||||
// when the title left one in an access that does not resolve.
|
||||
access->Resolve.pSrcResource = nullptr;
|
||||
access->Resolve.pDstResource = nullptr;
|
||||
}
|
||||
|
||||
void translate_geometry(D3D12_RAYTRACING_GEOMETRY_DESC* geometry) {
|
||||
if (!geometry) return;
|
||||
if (geometry->Type == D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES) {
|
||||
geometry->Triangles.Transform3x4 = bx_xbox_host_gpu_va(geometry->Triangles.Transform3x4);
|
||||
geometry->Triangles.IndexBuffer = bx_xbox_host_gpu_va(geometry->Triangles.IndexBuffer);
|
||||
geometry->Triangles.VertexBuffer.StartAddress = bx_xbox_host_gpu_va(geometry->Triangles.VertexBuffer.StartAddress);
|
||||
} else if (geometry->Type == D3D12_RAYTRACING_GEOMETRY_TYPE_PROCEDURAL_PRIMITIVE_AABBS) {
|
||||
geometry->AABBs.AABBs.StartAddress = bx_xbox_host_gpu_va(geometry->AABBs.AABBs.StartAddress);
|
||||
}
|
||||
}
|
||||
|
||||
bool same_iid(REFIID a, REFIID b) {
|
||||
return std::memcmp(&a, &b, sizeof(IID)) == 0;
|
||||
}
|
||||
@@ -314,4 +338,251 @@ 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);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_barrier(void* self, UINT32 count, const D3D12_BARRIER_GROUP* groups) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Barrier");
|
||||
if (!count || !groups) {
|
||||
bx_xbox_host<ID3D12GraphicsCommandList7>(self)->Barrier(count, groups);
|
||||
return;
|
||||
}
|
||||
UINT ntex = 0, nbuf = 0;
|
||||
for (UINT32 i = 0; i < count; ++i) {
|
||||
if (!groups[i].NumBarriers) continue;
|
||||
if (groups[i].Type == D3D12_BARRIER_TYPE_TEXTURE && groups[i].pTextureBarriers) ntex += groups[i].NumBarriers;
|
||||
else if (groups[i].Type == D3D12_BARRIER_TYPE_BUFFER && groups[i].pBufferBarriers) nbuf += groups[i].NumBarriers;
|
||||
}
|
||||
auto* copy = new (std::nothrow) D3D12_BARRIER_GROUP[count];
|
||||
auto* tex = ntex ? new (std::nothrow) D3D12_TEXTURE_BARRIER[ntex] : nullptr;
|
||||
auto* buf = nbuf ? new (std::nothrow) D3D12_BUFFER_BARRIER[nbuf] : nullptr;
|
||||
if (!copy || (ntex && !tex) || (nbuf && !buf)) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "Barrier", "out of memory translating arguments; call dropped");
|
||||
delete[] copy;
|
||||
delete[] tex;
|
||||
delete[] buf;
|
||||
return;
|
||||
}
|
||||
UINT ti = 0, bi = 0;
|
||||
for (UINT32 i = 0; i < count; ++i) {
|
||||
copy[i] = groups[i];
|
||||
if (groups[i].Type == D3D12_BARRIER_TYPE_TEXTURE && groups[i].NumBarriers && groups[i].pTextureBarriers) {
|
||||
for (UINT j = 0; j < groups[i].NumBarriers; ++j) {
|
||||
tex[ti + j] = groups[i].pTextureBarriers[j];
|
||||
tex[ti + j].pResource = bx_xbox_unwrap_as(tex[ti + j].pResource);
|
||||
}
|
||||
copy[i].pTextureBarriers = tex + ti;
|
||||
ti += groups[i].NumBarriers;
|
||||
} else if (groups[i].Type == D3D12_BARRIER_TYPE_BUFFER && groups[i].NumBarriers && groups[i].pBufferBarriers) {
|
||||
for (UINT j = 0; j < groups[i].NumBarriers; ++j) {
|
||||
buf[bi + j] = groups[i].pBufferBarriers[j];
|
||||
buf[bi + j].pResource = bx_xbox_unwrap_as(buf[bi + j].pResource);
|
||||
}
|
||||
copy[i].pBufferBarriers = buf + bi;
|
||||
bi += groups[i].NumBarriers;
|
||||
}
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList7>(self)->Barrier(count, copy);
|
||||
delete[] copy;
|
||||
delete[] tex;
|
||||
delete[] buf;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_begin_render_pass(void* self, UINT count,
|
||||
const D3D12_RENDER_PASS_RENDER_TARGET_DESC* render_targets,
|
||||
const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* depth_stencil,
|
||||
D3D12_RENDER_PASS_FLAGS flags) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "BeginRenderPass");
|
||||
D3D12_RENDER_PASS_RENDER_TARGET_DESC* targets = nullptr;
|
||||
if (count && render_targets) {
|
||||
targets = new (std::nothrow) D3D12_RENDER_PASS_RENDER_TARGET_DESC[count];
|
||||
if (!targets) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "BeginRenderPass", "out of memory translating arguments; call dropped");
|
||||
return;
|
||||
}
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
targets[i] = render_targets[i];
|
||||
targets[i].cpuDescriptor = bx_xbox_host_cpu_handle(render_targets[i].cpuDescriptor);
|
||||
translate_ending_access(&targets[i].EndingAccess);
|
||||
}
|
||||
}
|
||||
D3D12_RENDER_PASS_DEPTH_STENCIL_DESC depth{};
|
||||
if (depth_stencil) {
|
||||
depth = *depth_stencil;
|
||||
depth.cpuDescriptor = bx_xbox_host_cpu_handle(depth_stencil->cpuDescriptor);
|
||||
translate_ending_access(&depth.DepthEndingAccess);
|
||||
translate_ending_access(&depth.StencilEndingAccess);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->BeginRenderPass(count, targets, depth_stencil ? &depth : nullptr, flags);
|
||||
delete[] targets;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch_rays(void* self, const D3D12_DISPATCH_RAYS_DESC* desc) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DispatchRays");
|
||||
if (!desc) {
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->DispatchRays(nullptr);
|
||||
return;
|
||||
}
|
||||
D3D12_DISPATCH_RAYS_DESC copy = *desc;
|
||||
copy.RayGenerationShaderRecord.StartAddress = bx_xbox_host_gpu_va(desc->RayGenerationShaderRecord.StartAddress);
|
||||
copy.MissShaderTable.StartAddress = bx_xbox_host_gpu_va(desc->MissShaderTable.StartAddress);
|
||||
copy.HitGroupTable.StartAddress = bx_xbox_host_gpu_va(desc->HitGroupTable.StartAddress);
|
||||
copy.CallableShaderTable.StartAddress = bx_xbox_host_gpu_va(desc->CallableShaderTable.StartAddress);
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->DispatchRays(©);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_build_raytracing_acceleration_structure(
|
||||
void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* desc, UINT post_count,
|
||||
const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* post) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "BuildRaytracingAccelerationStructure");
|
||||
D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC copy{};
|
||||
D3D12_RAYTRACING_GEOMETRY_DESC* geometries = nullptr;
|
||||
const D3D12_RAYTRACING_GEOMETRY_DESC** geometry_ptrs = nullptr;
|
||||
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* post_copy = nullptr;
|
||||
bool failed = false;
|
||||
if (desc) {
|
||||
copy = *desc;
|
||||
copy.DestAccelerationStructureData = bx_xbox_host_gpu_va(desc->DestAccelerationStructureData);
|
||||
copy.SourceAccelerationStructureData = bx_xbox_host_gpu_va(desc->SourceAccelerationStructureData);
|
||||
copy.ScratchAccelerationStructureData = bx_xbox_host_gpu_va(desc->ScratchAccelerationStructureData);
|
||||
const UINT n = desc->Inputs.NumDescs;
|
||||
if (desc->Inputs.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL) {
|
||||
/* Instance descriptors live in GPU memory and hold nested BLAS title GPU VAs;
|
||||
forwarding them untranslated would hand D3DMetal invalid GPU addresses. */
|
||||
BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 119u, "BuildRaytracingAccelerationStructure(TLAS)");
|
||||
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "BuildRaytracingAccelerationStructure",
|
||||
"TLAS instance descriptors contain nested title GPU VAs in GPU memory; build skipped");
|
||||
return;
|
||||
} else if (desc->Inputs.Type == D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL && n) {
|
||||
if (desc->Inputs.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY && desc->Inputs.pGeometryDescs) {
|
||||
geometries = new (std::nothrow) D3D12_RAYTRACING_GEOMETRY_DESC[n];
|
||||
if (!geometries) failed = true;
|
||||
else {
|
||||
for (UINT i = 0; i < n; ++i) {
|
||||
geometries[i] = desc->Inputs.pGeometryDescs[i];
|
||||
translate_geometry(&geometries[i]);
|
||||
}
|
||||
copy.Inputs.pGeometryDescs = geometries;
|
||||
}
|
||||
} else if (desc->Inputs.DescsLayout == D3D12_ELEMENTS_LAYOUT_ARRAY_OF_POINTERS && desc->Inputs.ppGeometryDescs) {
|
||||
geometries = new (std::nothrow) D3D12_RAYTRACING_GEOMETRY_DESC[n];
|
||||
geometry_ptrs = new (std::nothrow) const D3D12_RAYTRACING_GEOMETRY_DESC*[n];
|
||||
if (!geometries || !geometry_ptrs) failed = true;
|
||||
else {
|
||||
for (UINT i = 0; i < n; ++i) {
|
||||
if (!desc->Inputs.ppGeometryDescs[i]) {
|
||||
geometry_ptrs[i] = nullptr;
|
||||
continue;
|
||||
}
|
||||
geometries[i] = *desc->Inputs.ppGeometryDescs[i];
|
||||
translate_geometry(&geometries[i]);
|
||||
geometry_ptrs[i] = &geometries[i];
|
||||
}
|
||||
copy.Inputs.ppGeometryDescs = geometry_ptrs;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!failed && post && post_count) {
|
||||
post_copy = new (std::nothrow) D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC[post_count];
|
||||
if (!post_copy) failed = true;
|
||||
else {
|
||||
for (UINT i = 0; i < post_count; ++i) {
|
||||
post_copy[i] = post[i];
|
||||
post_copy[i].DestBuffer = bx_xbox_host_gpu_va(post[i].DestBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failed) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "BuildRaytracingAccelerationStructure",
|
||||
"out of memory translating arguments; call dropped");
|
||||
} else {
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->BuildRaytracingAccelerationStructure(
|
||||
desc ? © : nullptr, post_count, post_copy);
|
||||
}
|
||||
delete[] geometries;
|
||||
delete[] geometry_ptrs;
|
||||
delete[] post_copy;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_emit_raytracing_postbuild_info(
|
||||
void* self, const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* desc, UINT source_count,
|
||||
const D3D12_GPU_VIRTUAL_ADDRESS* sources) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "EmitRaytracingAccelerationStructurePostbuildInfo");
|
||||
D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC copy{};
|
||||
if (desc) {
|
||||
copy = *desc;
|
||||
copy.DestBuffer = bx_xbox_host_gpu_va(desc->DestBuffer);
|
||||
}
|
||||
D3D12_GPU_VIRTUAL_ADDRESS* translated = nullptr;
|
||||
if (sources && source_count) {
|
||||
translated = new (std::nothrow) D3D12_GPU_VIRTUAL_ADDRESS[source_count];
|
||||
if (!translated) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "EmitRaytracingAccelerationStructurePostbuildInfo",
|
||||
"out of memory translating arguments; call dropped");
|
||||
return;
|
||||
}
|
||||
for (UINT i = 0; i < source_count; ++i) translated[i] = bx_xbox_host_gpu_va(sources[i]);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->EmitRaytracingAccelerationStructurePostbuildInfo(
|
||||
desc ? © : nullptr, source_count, translated);
|
||||
delete[] translated;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write_buffer_immediate(void* self, UINT count,
|
||||
const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER* params,
|
||||
const D3D12_WRITEBUFFERIMMEDIATE_MODE* modes) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "WriteBufferImmediate");
|
||||
if (!count || !params) {
|
||||
bx_xbox_host<ID3D12GraphicsCommandList2>(self)->WriteBufferImmediate(count, params, modes);
|
||||
return;
|
||||
}
|
||||
constexpr UINT kInline = 16;
|
||||
D3D12_WRITEBUFFERIMMEDIATE_PARAMETER inline_copy[kInline];
|
||||
auto* copy = count <= kInline ? inline_copy : new (std::nothrow) D3D12_WRITEBUFFERIMMEDIATE_PARAMETER[count];
|
||||
if (!copy) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "WriteBufferImmediate",
|
||||
"out of memory translating arguments; call dropped");
|
||||
return;
|
||||
}
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
copy[i] = params[i];
|
||||
copy[i].Dest = bx_xbox_host_gpu_va(params[i].Dest);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList2>(self)->WriteBufferImmediate(count, copy, modes);
|
||||
if (copy != inline_copy) delete[] copy;
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE bx_xbox_list_so_set_targets(void* self, UINT start, UINT count,
|
||||
const D3D12_STREAM_OUTPUT_BUFFER_VIEW* views) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SOSetTargets");
|
||||
if (!count || !views) {
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SOSetTargets(start, count, views);
|
||||
return;
|
||||
}
|
||||
constexpr UINT kInline = 4;
|
||||
D3D12_STREAM_OUTPUT_BUFFER_VIEW inline_copy[kInline];
|
||||
auto* copy = count <= kInline ? inline_copy : new (std::nothrow) D3D12_STREAM_OUTPUT_BUFFER_VIEW[count];
|
||||
if (!copy) {
|
||||
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "SOSetTargets", "out of memory translating arguments; call dropped");
|
||||
return;
|
||||
}
|
||||
for (UINT i = 0; i < count; ++i) {
|
||||
copy[i] = views[i];
|
||||
copy[i].BufferLocation = bx_xbox_host_gpu_va(views[i].BufferLocation);
|
||||
copy[i].BufferFilledSizeLocation = bx_xbox_host_gpu_va(views[i].BufferFilledSizeLocation);
|
||||
}
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SOSetTargets(start, count, copy);
|
||||
if (copy != inline_copy) delete[] copy;
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -233,6 +233,21 @@ UINT bx_xbox_descriptor_size(D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void bx_xbox_descriptor_heap_forget(IUnknown* host);
|
||||
/* Records title-visible memory (from XMemAlloc) for a host resource; freed when it is released. */
|
||||
bool bx_xbox_title_memory_attach(ID3D12Resource* host, uint64_t title_va, uint64_t size, ULONGLONG attributes);
|
||||
/* Texture uploads of one submission (console_descriptors.cpp): an open list the shim executes on
|
||||
the queue ahead of the title's lists, and the fence value signaled after it. */
|
||||
struct BxTextureUploads {
|
||||
ID3D12GraphicsCommandList* list;
|
||||
ID3D12Fence* fence;
|
||||
UINT64 value;
|
||||
bool recorded; // set when a copy was recorded on `list`
|
||||
};
|
||||
/* The resource a view of `host` should read so that it sees the texture's contents in title memory
|
||||
(placed_x.cpp, #745): for a texture placed in title memory, a copy of its host texture filled
|
||||
from that memory (linear, or untiled through the GDK's XG) by a GPU copy recorded on
|
||||
`uploads->list`, and filled again when a sampled hash of that memory changes (checked at a
|
||||
backed-off interval); `host` itself for everything else, without `uploads`, and until a copy
|
||||
has been recorded (failures are logged). */
|
||||
ID3D12Resource* bx_xbox_texture_contents(ID3D12Resource* host, BxTextureUploads* uploads);
|
||||
|
||||
/* Logs a host call that failed (`host_call_failed`), so a refusal is never silent. */
|
||||
void bx_xbox_log_host_failure(const char* iface, const char* method, HRESULT hr);
|
||||
@@ -277,6 +292,18 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_pipeline_state(void* self, const
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_command_signature(void* self, const D3D12_COMMAND_SIGNATURE_DESC* desc,
|
||||
ID3D12RootSignature* root, REFIID riid, void** ppv);
|
||||
/* True when [address, address + 32 * count) lies in the title-visible storage of a
|
||||
CBV/SRV/UAV descriptor heap (descriptor_heaps.cpp). */
|
||||
bool bx_xbox_title_descriptors(uint64_t address, UINT count);
|
||||
/* descriptor_heaps.cpp: root buffers. An address in plain title memory gets a host buffer when
|
||||
translated console shaders are enabled; otherwise it is translated as before. */
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_shader_resource_view(void* self, UINT param, D3D12_GPU_VIRTUAL_ADDRESS address);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_constant_buffer_view(void* self, UINT param, D3D12_GPU_VIRTUAL_ADDRESS address);
|
||||
/* pipelines.cpp: the table handle is noted for translated console draws, then bound. */
|
||||
void STDMETHODCALLTYPE bx_xbox_list_set_graphics_root_descriptor_table(void* self, UINT param, D3D12_GPU_DESCRIPTOR_HANDLE base);
|
||||
/* pipelines.cpp: root signatures, widened for translated console shaders when those are enabled. */
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_create_root_signature(void* self, UINT node_mask, const void* blob, SIZE_T size,
|
||||
REFIID riid, void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_graphics_pipeline_state_x(void* self, const void* state, REFIID riid,
|
||||
void** ppv);
|
||||
HRESULT STDMETHODCALLTYPE bx_xbox_device_deserialize_compute_pipeline_state_x(void* self, const void* state, REFIID riid,
|
||||
@@ -402,6 +429,8 @@ HRESULT STDMETHODCALLTYPE bx_xbox_device_create_descriptor_heap(void* self, cons
|
||||
UINT STDMETHODCALLTYPE bx_xbox_device_get_descriptor_handle_increment_size(void* self, D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_cpu_start(void* self);
|
||||
D3D12_GPU_DESCRIPTOR_HANDLE STDMETHODCALLTYPE bx_xbox_heap_gpu_start(void* self);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_copy_descriptors_simple(void* self, UINT count, D3D12_CPU_DESCRIPTOR_HANDLE dest,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE src, D3D12_DESCRIPTOR_HEAP_TYPE type);
|
||||
void STDMETHODCALLTYPE bx_xbox_device_create_constant_buffer_view(void* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc,
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
/* `xbox_desc` is a D3D12XBOX_SAMPLER_DESC. */
|
||||
@@ -435,6 +464,9 @@ void STDMETHODCALLTYPE bx_xbox_device_create_placed_uav_x(void* self, ID3D12Reso
|
||||
D3D12_CPU_DESCRIPTOR_HANDLE dest);
|
||||
/* Drops the shadow record of a destroyed resource. */
|
||||
void bx_xbox_placed_forget(IUnknown* host);
|
||||
/* gpu_writes.cpp, at each ExecuteCommandLists: counts submissions and releases implicit shadows
|
||||
retired long enough ago (placed_x.cpp). */
|
||||
void bx_xbox_placed_note_submission();
|
||||
|
||||
/* Command-list slots whose structures carry interface pointers, unwrapped before the host call.
|
||||
The Xbox ResourceBarrier also returns the actions it took; 0 is returned. */
|
||||
@@ -442,6 +474,30 @@ 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);
|
||||
|
||||
/* The same unwrap as ResourceBarrier, for structures a plain forward would pass through.
|
||||
Interface pointers become the hosted object, descriptor handles and GPU addresses are
|
||||
translated. CreateStateObject is not here: its subobject payloads are untyped. */
|
||||
void STDMETHODCALLTYPE bx_xbox_list_barrier(void* self, UINT32 count, const D3D12_BARRIER_GROUP* groups);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_begin_render_pass(void* self, UINT count,
|
||||
const D3D12_RENDER_PASS_RENDER_TARGET_DESC* render_targets,
|
||||
const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC* depth_stencil,
|
||||
D3D12_RENDER_PASS_FLAGS flags);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_dispatch_rays(void* self, const D3D12_DISPATCH_RAYS_DESC* desc);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_build_raytracing_acceleration_structure(
|
||||
void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC* desc, UINT post_count,
|
||||
const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* post);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_emit_raytracing_postbuild_info(
|
||||
void* self, const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC* desc, UINT source_count,
|
||||
const D3D12_GPU_VIRTUAL_ADDRESS* sources);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_write_buffer_immediate(void* self, UINT count,
|
||||
const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER* params,
|
||||
const D3D12_WRITEBUFFERIMMEDIATE_MODE* modes);
|
||||
void STDMETHODCALLTYPE bx_xbox_list_so_set_targets(void* self, UINT start, UINT count,
|
||||
const D3D12_STREAM_OUTPUT_BUFFER_VIEW* views);
|
||||
}
|
||||
|
||||
#include "xbox_tables_generated.h"
|
||||
|
||||
@@ -56,20 +56,10 @@ static HRESULT STDMETHODCALLTYPE x_Device_13(void* self, D3D12_FEATURE a0, void
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CheckFeatureSupport", hr);
|
||||
return hr;
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_16(void* self, UINT a0, const void * a1, SIZE_T a2, REFIID a3, void ** a4) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateRootSignature");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device>(self)->CreateRootSignature(a0, a1, a2, a3, a4);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateRootSignature", hr);
|
||||
return bx_xbox_wrap_result(hr, a3, a4);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_22(void* self, const D3D12_SAMPLER_DESC * a0, D3D12_CPU_DESCRIPTOR_HANDLE a1) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateSampler");
|
||||
bx_xbox_host<ID3D12Device>(self)->CreateSampler(a0, bx_xbox_host_cpu_handle(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_Device_24(void* self, UINT a0, const D3D12_CPU_DESCRIPTOR_HANDLE a1, const D3D12_CPU_DESCRIPTOR_HANDLE a2, D3D12_DESCRIPTOR_HEAP_TYPE a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "CopyDescriptorsSimple");
|
||||
bx_xbox_host<ID3D12Device>(self)->CopyDescriptorsSimple(a0, bx_xbox_host_cpu_handle(a1), bx_xbox_host_cpu_handle(a2), a3);
|
||||
}
|
||||
static D3D12_HEAP_PROPERTIES STDMETHODCALLTYPE x_Device_26(void* self, UINT a0, D3D12_HEAP_TYPE a1) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetCustomHeapProperties");
|
||||
D3D12_HEAP_PROPERTIES result{};
|
||||
@@ -284,12 +274,8 @@ static HRESULT STDMETHODCALLTYPE x_Device_100(void* self, REFGUID a0, UINT a1, c
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateMetaCommand", hr);
|
||||
return bx_xbox_wrap_result(hr, a4, a5);
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_101(void* self, const D3D12_STATE_OBJECT_DESC * a0, REFIID a1, void ** a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateStateObject");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device5>(self)->CreateStateObject(a0, a1, a2);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "CreateStateObject", hr);
|
||||
return bx_xbox_wrap_result(hr, a1, a2);
|
||||
}
|
||||
/* parameter structure holds an interface pointer, GPU address, or descriptor handle */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_101(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 101u, "CreateStateObject"); return E_NOTIMPL; }
|
||||
static void STDMETHODCALLTYPE x_Device_102(void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS * a0, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO * a1) {
|
||||
BX_D3D_TRACE("XboxDevice", "GetRaytracingAccelerationStructurePrebuildInfo");
|
||||
bx_xbox_host<ID3D12Device5>(self)->GetRaytracingAccelerationStructurePrebuildInfo(a0, a1);
|
||||
@@ -306,12 +292,8 @@ static HRESULT STDMETHODCALLTYPE x_Device_105(void* self, D3D12_BACKGROUND_PROCE
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "SetBackgroundProcessingMode", hr);
|
||||
return hr;
|
||||
}
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_106(void* self, const D3D12_STATE_OBJECT_DESC * a0, ID3D12StateObject * a1, REFIID a2, void ** a3) {
|
||||
BX_D3D_TRACE("XboxDevice", "AddToStateObject");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device7>(self)->AddToStateObject(a0, bx_xbox_unwrap_as<ID3D12StateObject>(a1), a2, a3);
|
||||
if (FAILED(hr)) bx_xbox_log_host_failure("XboxDevice", "AddToStateObject", hr);
|
||||
return bx_xbox_wrap_result(hr, a2, a3);
|
||||
}
|
||||
/* parameter structure holds an interface pointer, GPU address, or descriptor handle */
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_106(void*) { BX_VTABLE_STUB_LOG("XboxDevice", 106u, "AddToStateObject"); return E_NOTIMPL; }
|
||||
static HRESULT STDMETHODCALLTYPE x_Device_107(void* self, const D3D12_PROTECTED_RESOURCE_SESSION_DESC1 * a0, REFIID a1, void ** a2) {
|
||||
BX_D3D_TRACE("XboxDevice", "CreateProtectedResourceSession1");
|
||||
HRESULT hr = bx_xbox_host<ID3D12Device7>(self)->CreateProtectedResourceSession1(a0, a1, a2);
|
||||
@@ -416,7 +398,7 @@ const void* const kDeviceTable[] = {
|
||||
reinterpret_cast<const void*>(&x_Device_13),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_descriptor_heap),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_descriptor_handle_increment_size),
|
||||
reinterpret_cast<const void*>(&x_Device_16),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_root_signature),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_constant_buffer_view),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_shader_resource_view),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_unordered_access_view),
|
||||
@@ -424,7 +406,7 @@ const void* const kDeviceTable[] = {
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_depth_stencil_view),
|
||||
reinterpret_cast<const void*>(&x_Device_22),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_copy_descriptors),
|
||||
reinterpret_cast<const void*>(&x_Device_24),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_copy_descriptors_simple),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_get_resource_allocation_info),
|
||||
reinterpret_cast<const void*>(&x_Device_26),
|
||||
reinterpret_cast<const void*>(&bx_xbox_device_create_committed_resource),
|
||||
@@ -557,7 +539,7 @@ const IID kDeviceIids[] = {
|
||||
{0xc4fec28f, 0x7966, 0x4e95, {0x9f, 0x94, 0xf4, 0x31, 0xcb, 0x56, 0xc3, 0xb8}}, /* ID3D12Object */
|
||||
};
|
||||
|
||||
/* ID3D12Device11: 139 slots (54 forwarded, 46 shared, 39 stubs); hosted on ID3D12Device10. */
|
||||
/* ID3D12Device11: 139 slots (50 forwarded, 48 shared, 41 stubs); hosted on ID3D12Device10. */
|
||||
const IID kHostDevice = __uuidof(ID3D12Device10);
|
||||
|
||||
static HRESULT STDMETHODCALLTYPE x_Resource_3(void* self, REFGUID a0, UINT * a1, void * a2) {
|
||||
@@ -1352,10 +1334,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_35(void* self, UINT a0, D3D1
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootDescriptorTable");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootDescriptorTable(a0, bx_xbox_host_gpu_handle(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_36(void* self, UINT a0, D3D12_GPU_DESCRIPTOR_HANDLE a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootDescriptorTable");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootDescriptorTable(a0, bx_xbox_host_gpu_handle(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_37(void* self, UINT a0, UINT a1, UINT a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRoot32BitConstant");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRoot32BitConstant(a0, a1, a2);
|
||||
@@ -1376,18 +1354,10 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_41(void* self, UINT a0, D3D1
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootConstantBufferView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootConstantBufferView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_42(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootConstantBufferView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootConstantBufferView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_43(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootShaderResourceView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_44(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootShaderResourceView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootShaderResourceView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_45(void* self, UINT a0, D3D12_GPU_VIRTUAL_ADDRESS a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetComputeRootUnorderedAccessView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetComputeRootUnorderedAccessView(a0, bx_xbox_host_gpu_va(a1));
|
||||
@@ -1396,10 +1366,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_46(void* self, UINT a0, D3D1
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetGraphicsRootUnorderedAccessView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SetGraphicsRootUnorderedAccessView(a0, bx_xbox_host_gpu_va(a1));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_49(void* self, UINT a0, UINT a1, const D3D12_STREAM_OUTPUT_BUFFER_VIEW * a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SOSetTargets");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->SOSetTargets(a0, a1, a2);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_51(void* self, D3D12_CPU_DESCRIPTOR_HANDLE a0, D3D12_CLEAR_FLAGS a1, FLOAT a2, UINT8 a3, UINT a4, const D3D12_RECT * a5) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ClearDepthStencilView");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList>(self)->ClearDepthStencilView(bx_xbox_host_cpu_handle(a0), a1, a2, a3, a4, a5);
|
||||
@@ -1475,8 +1441,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; }
|
||||
@@ -1542,18 +1506,10 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_112(void* self, UINT a0) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetViewInstanceMask");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList1>(self)->SetViewInstanceMask(a0);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_113(void* self, UINT a0, const D3D12_WRITEBUFFERIMMEDIATE_PARAMETER * a1, const D3D12_WRITEBUFFERIMMEDIATE_MODE * a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "WriteBufferImmediate");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList2>(self)->WriteBufferImmediate(a0, a1, a2);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_114(void* self, ID3D12ProtectedResourceSession * a0) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetProtectedResourceSession");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList3>(self)->SetProtectedResourceSession(bx_xbox_unwrap_as<ID3D12ProtectedResourceSession>(a0));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_115(void* self, UINT a0, const D3D12_RENDER_PASS_RENDER_TARGET_DESC * a1, const D3D12_RENDER_PASS_DEPTH_STENCIL_DESC * a2, D3D12_RENDER_PASS_FLAGS a3) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "BeginRenderPass");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->BeginRenderPass(a0, a1, a2, a3);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_116(void* self) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "EndRenderPass");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->EndRenderPass();
|
||||
@@ -1566,14 +1522,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_118(void* self, ID3D12MetaCo
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "ExecuteMetaCommand");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->ExecuteMetaCommand(bx_xbox_unwrap_as<ID3D12MetaCommand>(a0), a1, a2);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_119(void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC * a0, UINT a1, const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC * a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "BuildRaytracingAccelerationStructure");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->BuildRaytracingAccelerationStructure(a0, a1, a2);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_120(void* self, const D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC * a0, UINT a1, const D3D12_GPU_VIRTUAL_ADDRESS * a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "EmitRaytracingAccelerationStructurePostbuildInfo");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->EmitRaytracingAccelerationStructurePostbuildInfo(a0, a1, a2);
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_121(void* self, D3D12_GPU_VIRTUAL_ADDRESS a0, D3D12_GPU_VIRTUAL_ADDRESS a1, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE a2) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "CopyRaytracingAccelerationStructure");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->CopyRaytracingAccelerationStructure(bx_xbox_host_gpu_va(a0), bx_xbox_host_gpu_va(a1), a2);
|
||||
@@ -1582,10 +1530,6 @@ static void STDMETHODCALLTYPE x_GraphicsCommandList_122(void* self, ID3D12StateO
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "SetPipelineState1");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->SetPipelineState1(bx_xbox_unwrap_as<ID3D12StateObject>(a0));
|
||||
}
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_123(void* self, const D3D12_DISPATCH_RAYS_DESC * a0) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "DispatchRays");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList4>(self)->DispatchRays(a0);
|
||||
}
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_124(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 124u, "CpuValidateResultX"); return 0; }
|
||||
/* Xbox-only method */
|
||||
@@ -1630,10 +1574,6 @@ static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_143(void*) { BX_VTABLE_STU
|
||||
static HRESULT STDMETHODCALLTYPE x_GraphicsCommandList_144(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 144u, "EnableLiveDebuggingX"); return E_NOTIMPL; }
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_145(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 145u, "SetComputeShaderLaunchParametersX"); return 0; }
|
||||
static void STDMETHODCALLTYPE x_GraphicsCommandList_146(void* self, UINT32 a0, const D3D12_BARRIER_GROUP * a1) {
|
||||
BX_D3D_TRACE("XboxGraphicsCommandList", "Barrier");
|
||||
bx_xbox_host<ID3D12GraphicsCommandList7>(self)->Barrier(a0, a1);
|
||||
}
|
||||
/* Xbox-only method */
|
||||
static UINT64 STDMETHODCALLTYPE x_GraphicsCommandList_147(void*) { BX_VTABLE_STUB_LOG("XboxGraphicsCommandList", 147u, "OMSetFrontAndBackStencilRef"); return 0; }
|
||||
/* Xbox-only method */
|
||||
@@ -1678,20 +1618,20 @@ const void* const kGraphicsCommandListTable[] = {
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_33),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_34),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_35),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_36),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_descriptor_table),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_37),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_38),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_39),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_40),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_41),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_42),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_constant_buffer_view),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_43),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_44),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_set_graphics_root_shader_resource_view),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_45),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_46),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_index_buffer),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_ia_set_vertex_buffers),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_49),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_so_set_targets),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_om_set_render_targets),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_51),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_52),
|
||||
@@ -1727,7 +1667,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),
|
||||
@@ -1755,17 +1695,17 @@ const void* const kGraphicsCommandListTable[] = {
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_110),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_111),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_112),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_113),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_write_buffer_immediate),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_114),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_115),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_begin_render_pass),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_116),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_117),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_118),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_119),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_120),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_build_raytracing_acceleration_structure),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_emit_raytracing_postbuild_info),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_121),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_122),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_123),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_dispatch_rays),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_124),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_125),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_126),
|
||||
@@ -1788,7 +1728,7 @@ const void* const kGraphicsCommandListTable[] = {
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_143),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_144),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_145),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_146),
|
||||
reinterpret_cast<const void*>(&bx_xbox_list_barrier),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_147),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_148),
|
||||
reinterpret_cast<const void*>(&x_GraphicsCommandList_149),
|
||||
@@ -1809,7 +1749,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 (55 forwarded, 36 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)) {
|
||||
@@ -1503,12 +1574,73 @@ void bx_log_emit(bx_log_level_t level, const char* subsystem, const char* event,
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
// The callers of an unimplemented call, so a blocker can be looked up in the Ghidra results
|
||||
// (`bx-cli ghidra <module> <offset>`). The three return addresses above the logger: the stub, its
|
||||
// caller and the caller's caller. A stub that tail-calls the logger makes the title its first
|
||||
// entry. Each distinct (signature, stub, direct caller) is logged once, with the first-seen third
|
||||
// frame, as a `stub_caller` event whose detail is
|
||||
// `<stub signature> <- module+offset < module+offset < module+offset`; the stub's own event stays
|
||||
// unchanged, so report signatures do not change.
|
||||
constexpr size_t kCallerSlots = 4096;
|
||||
std::atomic<uint64_t> g_caller_seen[kCallerSlots];
|
||||
|
||||
uint64_t mix64(uint64_t x) {
|
||||
x ^= x >> 33;
|
||||
x *= 0xff51afd7ed558ccdull;
|
||||
x ^= x >> 33;
|
||||
x *= 0xc4ceb9fe1a85ec53ull;
|
||||
return x ^ (x >> 33);
|
||||
}
|
||||
|
||||
// True the first time `key` is seen. When the table is full, nothing more is logged.
|
||||
bool first_sighting(uint64_t key) {
|
||||
if (key == 0) key = 1;
|
||||
for (size_t probe = 0; probe < 16; ++probe) {
|
||||
std::atomic<uint64_t>& slot = g_caller_seen[(mix64(key) + probe) % kCallerSlots];
|
||||
uint64_t current = slot.load(std::memory_order_relaxed);
|
||||
if (current == key) return false;
|
||||
if (current == 0 && slot.compare_exchange_strong(current, key)) return true;
|
||||
if (current == key) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Not inlined: the frame count below assumes this function and the logger are frames 0 and 1.
|
||||
__attribute__((noinline)) void log_stub_callers(const char* signature) {
|
||||
void* frames[3] = {};
|
||||
const USHORT count = RtlCaptureStackBackTrace(2, 3, frames, nullptr);
|
||||
uint64_t key = 1469598103934665603ull; // FNV-1a over the signature text
|
||||
for (const char* c = signature; *c; ++c) key = (key ^ static_cast<unsigned char>(*c)) * 1099511628211ull;
|
||||
// One record per (signature, stub, direct caller); the third frame is a sample.
|
||||
for (USHORT i = 0; i < count && i < 2; ++i) key = mix64(key ^ reinterpret_cast<uintptr_t>(frames[i]));
|
||||
if (!first_sighting(key)) return;
|
||||
char line[512];
|
||||
int length = std::snprintf(line, sizeof(line), "%s <-", signature);
|
||||
for (USHORT i = 0; i < count && length > 0 && static_cast<size_t>(length) < sizeof(line) - 80; ++i) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
uintptr_t base = 0;
|
||||
if (VirtualQuery(frames[i], ®ion, sizeof(region)) && region.Type == MEM_IMAGE) {
|
||||
base = reinterpret_cast<uintptr_t>(region.AllocationBase);
|
||||
}
|
||||
char name[96] = "anon";
|
||||
if (base) module_name_utf8(base, name, sizeof(name));
|
||||
length += std::snprintf(line + length, sizeof(line) - length, "%s %s+%llx", i ? " <" : "", name,
|
||||
static_cast<unsigned long long>(reinterpret_cast<uintptr_t>(frames[i]) - base));
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "stub", "stub_caller", line);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void bx_log_unimpl_api(const char* dll_name, const char* symbol_name) {
|
||||
char detail[256];
|
||||
std::snprintf(detail, sizeof(detail), "%s!%s",
|
||||
dll_name ? dll_name : "?",
|
||||
symbol_name ? symbol_name : "?");
|
||||
bx_log_emit(BX_LOG_WARN, "stub", "unimpl_api", detail);
|
||||
log_stub_callers(detail);
|
||||
}
|
||||
|
||||
void bx_log_unimpl_vtable(const char* iface_name, uint32_t slot_index, const char* method_name) {
|
||||
@@ -1518,6 +1650,7 @@ void bx_log_unimpl_vtable(const char* iface_name, uint32_t slot_index, const cha
|
||||
slot_index,
|
||||
method_name ? method_name : "?");
|
||||
bx_log_emit(BX_LOG_WARN, "com_vtable", "unimpl_vtable", detail);
|
||||
log_stub_callers(detail);
|
||||
}
|
||||
|
||||
const bx_runtime_config_t* bx_get_runtime_config(void) {
|
||||
|
||||
@@ -13,3 +13,5 @@
|
||||
The package as a whole is under the proprietary *Microsoft DirectStorage SDK* licence terms (`LICENSE.txt`), whose distributable list (`distributable_files.txt`) names only `dstorage.dll` and `dstoragecore.dll`. BetterXen uses neither DLL and copies nothing else from the package.
|
||||
|
||||
The Xbox console interfaces (`IDStorageFactoryX` and others, `dstorage_xs.h`) are not included: their IIDs have no licence-compatible public source. See the discussion on #483.
|
||||
|
||||
`xcrdapi.cpp` declares its own copies of the Xbox console interfaces, which follow the authorized GDK header `dstorage_xs.h` (#769). That header itself is not vendored.
|
||||
+219
-114
@@ -13,6 +13,7 @@
|
||||
#include <atomic>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
namespace {
|
||||
using namespace bx::storage;
|
||||
@@ -247,6 +248,32 @@ private:
|
||||
Fn leave_ = nullptr;
|
||||
};
|
||||
|
||||
// xmem maps a page of an XMEM_MAPPABLE reservation on its first touch (#754): an instruction that
|
||||
// touches it faults into xmem's handler, which maps it. ReadFile writes from the host side and
|
||||
// does not fault, it fails. So before ReadFile writes into title memory, every 64 KB page of the
|
||||
// destination that xmem tracks but that is not committed yet is touched with a read here. Call
|
||||
// it with the remap guard held, so no page is remapped between the touch and the read.
|
||||
void touch_title_pages(void* destination, DWORD size) {
|
||||
using QueryFn = int (*)(uint64_t, bx_xmem_region_info_t*);
|
||||
static const QueryFn query = [] {
|
||||
const HMODULE xmem = GetModuleHandleW(L"xmem.dll");
|
||||
return xmem ? reinterpret_cast<QueryFn>(reinterpret_cast<void*>(GetProcAddress(xmem, "bx_xmem_query_region")))
|
||||
: nullptr;
|
||||
}();
|
||||
if (!query || !destination || !size) return;
|
||||
constexpr uintptr_t page = 64 * 1024;
|
||||
const auto begin = reinterpret_cast<uintptr_t>(destination);
|
||||
for (uintptr_t at = begin & ~(page - 1); at < begin + size; at += page) {
|
||||
const uintptr_t probe = at < begin ? begin : at;
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (VirtualQuery(reinterpret_cast<void*>(probe), ®ion, sizeof(region)) && region.State == MEM_COMMIT) {
|
||||
continue;
|
||||
}
|
||||
bx_xmem_region_info_t info{};
|
||||
if (query(probe, &info)) (void)*reinterpret_cast<volatile const uint8_t*>(probe);
|
||||
}
|
||||
}
|
||||
|
||||
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size,
|
||||
bool title_destination = false) {
|
||||
if (!size) return S_OK;
|
||||
@@ -267,6 +294,7 @@ HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* so
|
||||
DWORD bytes = 0;
|
||||
HRESULT result = S_OK;
|
||||
RemapGuard remap_guard(title_destination);
|
||||
if (title_destination) touch_title_pages(destination, size);
|
||||
if (!ReadFile(file, destination, size, &bytes, &operation)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (error != ERROR_IO_PENDING) {
|
||||
@@ -457,19 +485,15 @@ CopyResult copy_staged(HANDLE file, const Request& request) {
|
||||
}
|
||||
|
||||
/* A title may read only the first part of a compressed block: the stream then holds more than
|
||||
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and its first
|
||||
`output_size` bytes are delivered. A stream shorter than the destination stays an error. */
|
||||
DestinationSize bytes. The whole stream is decoded and checked (Adler-32), and only its first
|
||||
`output_size` bytes are written; the rest passes through a 32 KiB window, so a partial read
|
||||
needs no buffer for the whole stream (#769: it used to allocate output_size * 64 bytes, up to
|
||||
2 GiB for a 32 MiB destination). A stream shorter than the destination stays an error. */
|
||||
BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& request) {
|
||||
const size_t capacity = static_cast<size_t>(request.output_size) * 64 + 0x40000;
|
||||
auto* whole = static_cast<uint8_t*>(HeapAlloc(GetProcessHeap(), 0, capacity));
|
||||
if (!whole) return BxInflateResult::output_mismatch;
|
||||
size_t produced = 0;
|
||||
BxInflateResult r = bx_zlib_inflate_any(compressed, request.size, whole, capacity, &produced);
|
||||
if (r == BxInflateResult::ok && produced > request.output_size) {
|
||||
std::memcpy(request.destination, whole, request.output_size);
|
||||
} else if (r == BxInflateResult::ok) {
|
||||
r = BxInflateResult::output_mismatch;
|
||||
}
|
||||
BxInflateResult r = bx_zlib_inflate_prefix(compressed, request.size, static_cast<uint8_t*>(request.destination),
|
||||
request.output_size, &produced);
|
||||
if (r == BxInflateResult::ok && produced <= request.output_size) r = BxInflateResult::output_mismatch;
|
||||
static std::atomic<UINT> logged{0};
|
||||
if (logged.fetch_add(1) < 16) {
|
||||
char detail[160];
|
||||
@@ -478,7 +502,6 @@ BxInflateResult inflate_first_part(const uint8_t* compressed, const Request& req
|
||||
r == BxInflateResult::ok ? "first part delivered" : bx_inflate_result_name(r));
|
||||
bx_log_emit(r == BxInflateResult::ok ? BX_LOG_INFO : BX_LOG_WARN, "xcrdapi", "dstorage_zlib_partial", detail);
|
||||
}
|
||||
HeapFree(GetProcessHeap(), 0, whole);
|
||||
return r;
|
||||
}
|
||||
|
||||
@@ -1507,47 +1530,81 @@ private:
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Xbox Series DirectStorage COM interfaces (IDStorage*X), inferred from call-site
|
||||
// observation of a project-authorized target build (provenance pending maintainer
|
||||
// review; not a public contract), layered over the same WorkQueue / StorageFile /
|
||||
// StatusArray engine. Unimplemented vtable slots log through BX_VTABLE_STUB_LOG
|
||||
// so any newly reached slot surfaces immediately in bx-cli trace.
|
||||
// Xbox Series DirectStorage COM interfaces (IDStorage*X), as the authorized GDK header
|
||||
// dstorage_xs.h declares them (#769), layered over the same WorkQueue / StorageFile /
|
||||
// StatusArray engine. Methods the engine cannot honour log through BX_VTABLE_STUB_LOG so
|
||||
// they surface in bx-cli trace.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
constexpr IID kXboxFactoryIid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
|
||||
// IIDs from dstorage_xs.h. One object answers its interface and the interfaces it extends: a
|
||||
// factory implements IDStorageFactoryX2 (so X and X1 too), a queue IDStorageQueueX2.
|
||||
constexpr IID kXboxFactoryIid{0xfb3b54ac, 0xbf82, 0x463a, {0xb7, 0x77, 0x73, 0x19, 0x58, 0x37, 0x86, 0x4d}};
|
||||
constexpr IID kXboxFactory1Iid{0xc74c2a5b, 0x1e43, 0x46a5, {0xa2, 0x24, 0x91, 0x16, 0x35, 0x8e, 0x11, 0x18}};
|
||||
constexpr IID kXboxFactory2Iid{0x62959d11, 0xd45f, 0x4884, {0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae}};
|
||||
constexpr IID kXboxFileIid{0x43704f9f, 0x27c6, 0x4a9f, {0x88, 0x15, 0xd1, 0x65, 0x27, 0x89, 0x4d, 0xf4}};
|
||||
constexpr IID kXboxStatusArrayIid{0xcd66d752, 0x2786, 0x44f7, {0x90, 0x70, 0xe2, 0xa6, 0xfd, 0xad, 0x3f, 0x1b}};
|
||||
constexpr IID kXboxQueueIid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
|
||||
constexpr IID kXboxQueueIid{0xa3f6649a, 0x8c2c, 0x4b3a, {0x8b, 0x6e, 0x10, 0x18, 0x6a, 0x04, 0xb9, 0xbc}};
|
||||
constexpr IID kXboxQueue1Iid{0x3c02cb0c, 0xc050, 0x4195, {0x99, 0xa1, 0xa1, 0xce, 0x94, 0xba, 0x33, 0xc5}};
|
||||
constexpr IID kXboxQueue2Iid{0x3af5c948, 0x6297, 0x426c, {0xbf, 0xfc, 0x8f, 0x18, 0x95, 0x9f, 0xb8, 0x7b}};
|
||||
|
||||
bool is_xbox_factory_iid(REFIID riid) {
|
||||
return IsEqualIID(riid, kXboxFactoryIid) || IsEqualIID(riid, kXboxFactory1Iid) || IsEqualIID(riid, kXboxFactory2Iid);
|
||||
}
|
||||
|
||||
// DSTORAGE_QUEUE_DESC1; DSTORAGE_QUEUE_DESC is its first 24 bytes (no Options).
|
||||
struct XboxQueueDesc {
|
||||
UINT64 source_type;
|
||||
UINT16 capacity;
|
||||
INT8 priority;
|
||||
UINT8 reserved_pad[5];
|
||||
PCSTR name;
|
||||
UINT64 flags;
|
||||
UINT64 flags; // DSTORAGE_QUEUE_OPTIONS
|
||||
};
|
||||
static_assert(sizeof(XboxQueueDesc) == 32, "XboxQueueDesc must be 32 bytes");
|
||||
static_assert(sizeof(XboxQueueDesc) == 32, "DSTORAGE_QUEUE_DESC1 is 32 bytes");
|
||||
static_assert(offsetof(XboxQueueDesc, source_type) == 0x00, "source_type offset");
|
||||
static_assert(offsetof(XboxQueueDesc, capacity) == 0x08, "capacity offset");
|
||||
static_assert(offsetof(XboxQueueDesc, priority) == 0x0a, "priority offset");
|
||||
static_assert(offsetof(XboxQueueDesc, name) == 0x10, "name offset");
|
||||
static_assert(offsetof(XboxQueueDesc, flags) == 0x18, "flags offset");
|
||||
constexpr size_t kXboxQueueDescSize = 24; // DSTORAGE_QUEUE_DESC
|
||||
|
||||
// DSTORAGE_QUEUE_INFO (Desc is a DSTORAGE_QUEUE_DESC) and DSTORAGE_QUEUE_INFO1 (a DESC1).
|
||||
struct XboxQueueInfo {
|
||||
UINT64 source_type;
|
||||
UINT16 capacity;
|
||||
INT8 priority;
|
||||
UINT8 reserved_pad[5];
|
||||
PCSTR name;
|
||||
UINT16 empty_slot_count;
|
||||
UINT16 request_count_until_auto_submit;
|
||||
};
|
||||
static_assert(offsetof(XboxQueueInfo, empty_slot_count) == 24 && sizeof(XboxQueueInfo) == 32,
|
||||
"DSTORAGE_QUEUE_INFO layout");
|
||||
struct XboxQueueInfo1 {
|
||||
XboxQueueDesc desc;
|
||||
UINT16 empty_slot_count;
|
||||
UINT16 request_count_until_auto_submit;
|
||||
};
|
||||
static_assert(offsetof(XboxQueueInfo1, empty_slot_count) == 32 && sizeof(XboxQueueInfo1) == 40,
|
||||
"DSTORAGE_QUEUE_INFO1 layout");
|
||||
|
||||
// DSTORAGE_REQUEST, 0x48 bytes.
|
||||
struct XboxRequest {
|
||||
UINT64 options; // +0x00: bit 22 (0x400000) = memory source, bit 0 = compressed
|
||||
UINT64 options; // +0x00: DSTORAGE_REQUEST_OPTIONS
|
||||
void* destination; // +0x08: buffer, or the 64 KB page-number array (DestinationIsPhysicalPages)
|
||||
UINT16 destination_page_offset; // +0x10: offset into the first page (DestinationIsPhysicalPages)
|
||||
UINT16 reserved12;
|
||||
UINT32 reserved14;
|
||||
UINT32 destination_size; // +0x18
|
||||
UINT32 reserved1c; // +0x1c
|
||||
void* source_ptr; // +0x20: IXboxDStorageFile* (file) or const void* (memory)
|
||||
void* source_ptr; // +0x20: IDStorageFileX* (file) or const void* (memory)
|
||||
UINT64 file_offset; // +0x28
|
||||
UINT32 source_size; // +0x30
|
||||
UINT32 reserved34; // +0x34
|
||||
UINT32 intermediate_size; // +0x34: BCPack bytes when ZlibDecompress and BcpackMode are both set
|
||||
UINT64 cancellation_tag; // +0x38
|
||||
PCSTR name; // +0x40
|
||||
};
|
||||
static_assert(sizeof(XboxRequest) == 56, "XboxRequest must be 56 bytes");
|
||||
static_assert(sizeof(XboxRequest) == 0x48, "DSTORAGE_REQUEST must be 0x48 bytes");
|
||||
static_assert(offsetof(XboxRequest, options) == 0x00, "options offset");
|
||||
static_assert(offsetof(XboxRequest, destination) == 0x08, "destination offset");
|
||||
static_assert(offsetof(XboxRequest, destination_page_offset) == 0x10, "destination_page_offset offset");
|
||||
@@ -1555,6 +1612,26 @@ static_assert(offsetof(XboxRequest, destination_size) == 0x18, "destination_size
|
||||
static_assert(offsetof(XboxRequest, source_ptr) == 0x20, "source_ptr offset");
|
||||
static_assert(offsetof(XboxRequest, file_offset) == 0x28, "file_offset offset");
|
||||
static_assert(offsetof(XboxRequest, source_size) == 0x30, "source_size offset");
|
||||
static_assert(offsetof(XboxRequest, intermediate_size) == 0x34, "intermediate_size offset");
|
||||
static_assert(offsetof(XboxRequest, cancellation_tag) == 0x38, "cancellation_tag offset");
|
||||
static_assert(offsetof(XboxRequest, name) == 0x40, "name offset");
|
||||
|
||||
// DSTORAGE_ERROR_RECORD: FailureCount, then FirstFailure { HResult, CommandType, a union of
|
||||
// the failed command's parameters (Request is the largest: options through Name[64]) }.
|
||||
struct XboxErrorRecord {
|
||||
UINT32 failure_count;
|
||||
HRESULT hresult;
|
||||
INT32 command_type; // DSTORAGE_COMMAND_TYPE
|
||||
UINT32 pad;
|
||||
unsigned char parameters[640];
|
||||
};
|
||||
static_assert(offsetof(XboxErrorRecord, hresult) == 4 && offsetof(XboxErrorRecord, command_type) == 8,
|
||||
"DSTORAGE_ERROR_RECORD header");
|
||||
static_assert(offsetof(XboxErrorRecord, parameters) == 16 && sizeof(XboxErrorRecord) == 656,
|
||||
"DSTORAGE_ERROR_RECORD is 656 bytes");
|
||||
|
||||
// DSTORAGE_STATS: four 48-byte DSTORAGE_PRIORITY_STATS, two UINT8 and fifteen UINT32.
|
||||
constexpr size_t kXboxStatsSize = 256;
|
||||
|
||||
// DSTORAGE_REQUEST_OPTIONS (authorized GDK documentation): ZlibDecompress:1, BcpackMode:4,
|
||||
// SwizzleMode:16, DestinationIsPhysicalPages:1, SourceType:1, SourceIsPhysicalPages:1.
|
||||
@@ -1590,20 +1667,19 @@ void log_request_options(UINT64 options, UINT32 source_size, UINT32 destination_
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_request_options", detail);
|
||||
}
|
||||
|
||||
// IDStorageFileX: slot 3 Close, slot 4 GetHandle.
|
||||
struct IXboxDStorageFile : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
|
||||
virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0;
|
||||
};
|
||||
|
||||
// IDStorageStatusArrayX: slot 3 IsComplete, slot 4 GetHResult.
|
||||
struct IXboxDStorageStatusArray : IUnknown {
|
||||
virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot5() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot6() = 0;
|
||||
};
|
||||
|
||||
// IDStorageQueueX (slots 3-11), IDStorageQueueX1 (12), IDStorageQueueX2 (13).
|
||||
struct IXboxDStorageQueue : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueStatus(IXboxDStorageStatusArray* status_array, UINT32 index) = 0;
|
||||
@@ -1612,25 +1688,22 @@ struct IXboxDStorageQueue : IUnknown {
|
||||
virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0;
|
||||
virtual void STDMETHODCALLTYPE Close() = 0;
|
||||
virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0;
|
||||
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(void* record) = 0;
|
||||
virtual void STDMETHODCALLTYPE Query(void* info) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot13() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot14() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot15() = 0;
|
||||
virtual void STDMETHODCALLTYPE RetrieveErrorRecord(XboxErrorRecord* record) = 0;
|
||||
virtual void STDMETHODCALLTYPE Query(XboxQueueInfo* info) = 0;
|
||||
virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0;
|
||||
virtual void STDMETHODCALLTYPE Query1(XboxQueueInfo1* info) = 0;
|
||||
};
|
||||
|
||||
// IDStorageFactoryX (slots 3-8), IDStorageFactoryX1 (9), IDStorageFactoryX2 (10).
|
||||
struct IXboxDStorageFactory : IUnknown {
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0;
|
||||
virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot7() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot9() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot11() = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE StubSlot12() = 0;
|
||||
virtual void STDMETHODCALLTYPE GetStats(void* stats) = 0;
|
||||
virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const XboxQueueDesc* desc, REFIID riid, void** ppv) = 0;
|
||||
};
|
||||
|
||||
class XboxFile final : public PublicObject<IXboxDStorageFile> {
|
||||
@@ -1638,16 +1711,20 @@ public:
|
||||
explicit XboxFile(StorageFile* file) : file_(file) {}
|
||||
|
||||
void STDMETHODCALLTYPE Close() override { (void)file_->Close(); }
|
||||
HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) override {
|
||||
return file_->GetFileInformation(info);
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot5() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFileX", 5u, "Slot5");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot6() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFileX", 6u, "Slot6");
|
||||
return E_NOTIMPL;
|
||||
|
||||
// A new handle the caller closes, opened GENERIC_READ with FILE_SHARE_READ (dstorage_xs.h).
|
||||
// ReOpenFile gives one without the engine's FILE_FLAG_OVERLAPPED; a duplicate of the engine's
|
||||
// handle is the fallback. NULL if the file was closed.
|
||||
HANDLE STDMETHODCALLTYPE GetHandle() override {
|
||||
HANDLE engine = nullptr;
|
||||
if (FAILED(file_->GetHandle(&engine)) || !engine) return nullptr;
|
||||
using ReOpenFileFn = HANDLE(WINAPI*)(HANDLE, DWORD, DWORD, DWORD);
|
||||
static const auto reopen = reinterpret_cast<ReOpenFileFn>(
|
||||
reinterpret_cast<void*>(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "ReOpenFile")));
|
||||
const HANDLE fresh = reopen ? reopen(engine, GENERIC_READ, FILE_SHARE_READ, 0) : INVALID_HANDLE_VALUE;
|
||||
if (fresh == INVALID_HANDLE_VALUE) return engine;
|
||||
CloseHandle(engine);
|
||||
return fresh;
|
||||
}
|
||||
|
||||
File* inner() const { return file_; }
|
||||
@@ -1665,14 +1742,6 @@ public:
|
||||
|
||||
bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return array_->GetResult(index) != E_PENDING; }
|
||||
HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { return array_->GetResult(index); }
|
||||
HRESULT STDMETHODCALLTYPE StubSlot5() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 5u, "Slot5");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot6() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageStatusArrayX", 6u, "Slot6");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
StatusArray* inner() const { return array_; }
|
||||
|
||||
@@ -1685,7 +1754,12 @@ private:
|
||||
|
||||
class XboxQueue final : public PublicObject<IXboxDStorageQueue> {
|
||||
public:
|
||||
XboxQueue(WorkQueue* queue, UINT64 source_type) : queue_(queue), source_type_(source_type) {}
|
||||
XboxQueue(WorkQueue* queue, const XboxQueueDesc& desc) : queue_(queue), desc_(desc) {
|
||||
if (desc.name) {
|
||||
std::snprintf(name_, sizeof(name_), "%s", desc.name);
|
||||
desc_.name = name_;
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueRequest(const XboxRequest* request) override {
|
||||
if (!request) {
|
||||
@@ -1693,11 +1767,12 @@ public:
|
||||
return;
|
||||
}
|
||||
const bool is_memory = (request->options & kXboxRequestSourceMemoryBit) != 0;
|
||||
if ((is_memory && source_type_ == 0) || (!is_memory && source_type_ != 0)) {
|
||||
if ((is_memory && desc_.source_type == 0) || (!is_memory && desc_.source_type != 0)) {
|
||||
reject(E_DSTORAGE_INVALID_SOURCE_TYPE, Kind::request, "EnqueueRequest");
|
||||
return;
|
||||
}
|
||||
log_request_options(request->options, request->source_size, request->destination_size, request->reserved34);
|
||||
log_request_options(request->options, request->source_size, request->destination_size,
|
||||
request->intermediate_size);
|
||||
// BCPack (BcpackMode, DSTORAGE_BCPACK_MODE 1-7) is decoded by the GDK's BCPack.dll when
|
||||
// BX_BCPACK_DLL names it; combined with zlib, or without the codec, it stays refused.
|
||||
const UINT bcpack_mode = static_cast<UINT>((request->options & kXboxRequestBcpackMask) >> 1);
|
||||
@@ -1793,7 +1868,13 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64, UINT64) override {
|
||||
// The header allows cancelled requests to complete anyway, and the engine does not cancel:
|
||||
// every request still runs. Logged with its tag so the trace shows it.
|
||||
void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override {
|
||||
char detail[96];
|
||||
std::snprintf(detail, sizeof(detail), "mask=0x%llx value=0x%llx: requests still run",
|
||||
static_cast<unsigned long long>(mask), static_cast<unsigned long long>(value));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_cancel_requests", detail);
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 7u, "CancelRequestsWithTag");
|
||||
}
|
||||
|
||||
@@ -1801,33 +1882,55 @@ public:
|
||||
|
||||
HANDLE STDMETHODCALLTYPE GetErrorEvent() override { return queue_->error_event(); }
|
||||
|
||||
void STDMETHODCALLTYPE RetrieveErrorRecord(void*) override {
|
||||
// The size and layout of the Xbox caller's output are unverified.
|
||||
// Do not write the public PC record into it.
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 10u, "RetrieveErrorRecord");
|
||||
// FailureCount, FirstFailure.HResult and FirstFailure.CommandType are filled; the failed
|
||||
// command's parameters are left zeroed, as on the public queue.
|
||||
void STDMETHODCALLTYPE RetrieveErrorRecord(XboxErrorRecord* record) override {
|
||||
if (!record) return;
|
||||
std::memset(record, 0, sizeof(*record));
|
||||
ErrorRecord errors{};
|
||||
Kind first = Kind::request;
|
||||
queue_->take_errors(&errors, &first);
|
||||
record->failure_count = errors.failure_count > 0xffffffffull ? 0xffffffffu
|
||||
: static_cast<UINT32>(errors.failure_count);
|
||||
record->hresult = errors.failure_count ? errors.first_error : S_OK;
|
||||
record->command_type = errors.failure_count ? static_cast<INT32>(command_type(first))
|
||||
: static_cast<INT32>(DSTORAGE_COMMAND_TYPE_NONE);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE Query(void*) override { BX_VTABLE_STUB_LOG("IDStorageQueueX", 11u, "Query"); }
|
||||
HRESULT STDMETHODCALLTYPE StubSlot12() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 12u, "Slot12");
|
||||
return E_NOTIMPL;
|
||||
void STDMETHODCALLTYPE Query(XboxQueueInfo* info) override {
|
||||
if (!info) return;
|
||||
XboxQueueInfo1 full{};
|
||||
Query1(&full);
|
||||
std::memset(info, 0, sizeof(*info));
|
||||
std::memcpy(info, &full.desc, kXboxQueueDescSize);
|
||||
info->empty_slot_count = full.empty_slot_count;
|
||||
info->request_count_until_auto_submit = full.request_count_until_auto_submit;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot13() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 13u, "Slot13");
|
||||
return E_NOTIMPL;
|
||||
|
||||
void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override {
|
||||
if (!handle || handle == INVALID_HANDLE_VALUE) {
|
||||
reject(E_INVALIDARG, Kind::event, "EnqueueSetEvent");
|
||||
return;
|
||||
}
|
||||
accept(queue_->EnqueueSetEvent(handle), Kind::event, "EnqueueSetEvent");
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot14() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 14u, "Slot14");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
HRESULT STDMETHODCALLTYPE StubSlot15() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageQueueX", 15u, "Slot15");
|
||||
return E_NOTIMPL;
|
||||
|
||||
void STDMETHODCALLTYPE Query1(XboxQueueInfo1* info) override {
|
||||
if (!info) return;
|
||||
UINT empty = 0;
|
||||
UINT until_auto_submit = 0;
|
||||
queue_->counts(&empty, &until_auto_submit);
|
||||
std::memset(info, 0, sizeof(*info));
|
||||
info->desc = desc_;
|
||||
info->empty_slot_count = static_cast<UINT16>(empty);
|
||||
info->request_count_until_auto_submit = static_cast<UINT16>(until_auto_submit);
|
||||
}
|
||||
|
||||
private:
|
||||
~XboxQueue() override { queue_->Release(); }
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxQueueIid); }
|
||||
bool supports(REFIID riid) const override {
|
||||
return IsEqualIID(riid, kXboxQueueIid) || IsEqualIID(riid, kXboxQueue1Iid) || IsEqualIID(riid, kXboxQueue2Iid);
|
||||
}
|
||||
|
||||
void reject(HRESULT hr, Kind kind, const char* method) {
|
||||
char detail[96];
|
||||
@@ -1848,15 +1951,20 @@ private:
|
||||
}
|
||||
|
||||
WorkQueue* queue_;
|
||||
UINT64 source_type_;
|
||||
XboxQueueDesc desc_;
|
||||
char name_[64] = {};
|
||||
};
|
||||
|
||||
class XboxFactory final : public PublicObject<IXboxDStorageFactory> {
|
||||
public:
|
||||
HRESULT STDMETHODCALLTYPE CreateQueue(const void*, REFIID, void** ppv) override {
|
||||
if (ppv) *ppv = nullptr;
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 3u, "CreateQueue");
|
||||
return E_NOTIMPL;
|
||||
// A DSTORAGE_QUEUE_DESC is a DSTORAGE_QUEUE_DESC1 without Options: auto-submit stays on.
|
||||
HRESULT STDMETHODCALLTYPE CreateQueue(const void* desc, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!desc) return E_INVALIDARG;
|
||||
XboxQueueDesc full{};
|
||||
std::memcpy(&full, desc, kXboxQueueDescSize);
|
||||
return CreateQueue1(&full, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override {
|
||||
@@ -1898,13 +2006,16 @@ public:
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
|
||||
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 6u, "SetDebugFlags");
|
||||
// The engine's work runs on the Win32 thread pool, which has no affinity to set.
|
||||
HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override {
|
||||
char detail[64];
|
||||
std::snprintf(detail, sizeof(detail), "affinity=0x%llx has no effect", static_cast<unsigned long long>(affinity));
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_cpu_affinity", detail);
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot7() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "Slot7");
|
||||
return E_NOTIMPL;
|
||||
void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override {
|
||||
if (flags) BX_VTABLE_STUB_LOG("IDStorageFactoryX", 7u, "SetDebugFlags");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override {
|
||||
@@ -1915,12 +2026,15 @@ public:
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot9() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 9u, "Slot9");
|
||||
return E_NOTIMPL;
|
||||
// The engine keeps no DSTORAGE_STATS counters: the structure is written as zeros, and the
|
||||
// call logged so the trace shows that the values are not real.
|
||||
void STDMETHODCALLTYPE GetStats(void* stats) override {
|
||||
if (!stats) return;
|
||||
std::memset(stats, 0, kXboxStatsSize);
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX1", 9u, "GetStats");
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE CreateQueueX(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
|
||||
HRESULT STDMETHODCALLTYPE CreateQueue1(const XboxQueueDesc* desc, REFIID riid, void** ppv) override {
|
||||
if (!ppv) return E_POINTER;
|
||||
*ppv = nullptr;
|
||||
if (!desc) return E_INVALIDARG;
|
||||
@@ -1930,9 +2044,10 @@ public:
|
||||
if (desc->source_type > 1) {
|
||||
return E_DSTORAGE_INVALID_SOURCE_TYPE;
|
||||
}
|
||||
/* desc->priority is ignored on purpose: the Xbox priority range is not part of
|
||||
* the inferred contract, so no value is rejected (the public queue's
|
||||
* E_DSTORAGE_INVALID_QUEUE_PRIORITY range check is not assumed to apply). */
|
||||
// DSTORAGE_PRIORITY: LOW (-1) to REALTIME (2) (dstorage_xs.h). Queues are not prioritised.
|
||||
if (desc->priority < -1 || desc->priority > 2) {
|
||||
return E_DSTORAGE_INVALID_QUEUE_PRIORITY;
|
||||
}
|
||||
const UINT slots = desc->capacity - 1u;
|
||||
auto* entries = new (std::nothrow) Entry[slots];
|
||||
if (!entries) return E_OUTOFMEMORY;
|
||||
@@ -1957,7 +2072,7 @@ public:
|
||||
queue->Release();
|
||||
return error;
|
||||
}
|
||||
auto* wrapper = new (std::nothrow) XboxQueue(queue, desc->source_type);
|
||||
auto* wrapper = new (std::nothrow) XboxQueue(queue, *desc);
|
||||
if (!wrapper) {
|
||||
queue->Release();
|
||||
return E_OUTOFMEMORY;
|
||||
@@ -1965,24 +2080,14 @@ public:
|
||||
return publish(wrapper, riid, ppv);
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot11() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 11u, "Slot11");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
HRESULT STDMETHODCALLTYPE StubSlot12() override {
|
||||
BX_VTABLE_STUB_LOG("IDStorageFactoryX", 12u, "Slot12");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
private:
|
||||
bool supports(REFIID riid) const override { return IsEqualIID(riid, kXboxFactoryIid); }
|
||||
bool supports(REFIID riid) const override { return is_xbox_factory_iid(riid); }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
// Accepts BetterXen's synthetic factory IID and IUnknown (the synthetic factory),
|
||||
// the public PC IDStorageFactory / IDStorageFactory1, and the inferred Xbox
|
||||
// IDStorageFactoryX IID. Any other IID is logged with its value so `bx-cli trace`
|
||||
// the public PC IDStorageFactory / IDStorageFactory1, and the Xbox IDStorageFactoryX, X1 and X2
|
||||
// IIDs (dstorage_xs.h). Any other IID is logged with its value so `bx-cli trace`
|
||||
// names the interface a guest asked for.
|
||||
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
|
||||
if (!ppv) return E_POINTER;
|
||||
@@ -1991,7 +2096,7 @@ extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
|
||||
auto* factory = new (std::nothrow) PublicFactory;
|
||||
return factory ? publish(factory, riid, ppv) : E_OUTOFMEMORY;
|
||||
}
|
||||
if (IsEqualIID(riid, kXboxFactoryIid)) {
|
||||
if (is_xbox_factory_iid(riid)) {
|
||||
auto* factory = new (std::nothrow) XboxFactory;
|
||||
if (!factory) return E_OUTOFMEMORY;
|
||||
bx_log_emit(BX_LOG_INFO, "xcrdapi", "dstorage_get_factory", "dispatch xbox_com=IDStorageFactoryX");
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/* zlib (RFC 1950) / deflate (RFC 1951) decoder; see zlib_inflate.h. */
|
||||
#include "zlib_inflate.h"
|
||||
|
||||
#include <new>
|
||||
|
||||
namespace {
|
||||
|
||||
struct Bits {
|
||||
@@ -84,19 +86,68 @@ constexpr uint16_t kDistBase[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65,
|
||||
257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577};
|
||||
constexpr uint8_t kDistExtra[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13};
|
||||
|
||||
// Writes the whole output into one buffer of `size` bytes.
|
||||
struct Output {
|
||||
uint8_t* data;
|
||||
size_t size;
|
||||
size_t pos = 0;
|
||||
|
||||
bool put(uint8_t byte) {
|
||||
if (pos >= size) return false;
|
||||
data[pos++] = byte;
|
||||
return true;
|
||||
}
|
||||
BxInflateResult copy(size_t distance, size_t length) {
|
||||
if (distance > pos) return BxInflateResult::bad_data;
|
||||
if (length > size - pos) return BxInflateResult::output_mismatch;
|
||||
for (size_t i = 0; i < length; ++i, ++pos) data[pos] = data[pos - distance];
|
||||
return BxInflateResult::ok;
|
||||
}
|
||||
size_t produced() const { return pos; }
|
||||
uint32_t adler() const;
|
||||
};
|
||||
|
||||
BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman& dist) {
|
||||
// Decodes a stream of any length, keeps only its first `limit` bytes at `data`, and checks
|
||||
// Adler-32 over all of it. Back-references read a 32 KiB ring of the latest output (RFC 1951:
|
||||
// distances are at most 32768), so memory does not grow with the stream (#769).
|
||||
struct PrefixOutput {
|
||||
static constexpr size_t kWindow = 32768;
|
||||
uint8_t* data;
|
||||
size_t limit;
|
||||
uint64_t total = 0;
|
||||
uint32_t a = 1, b = 0;
|
||||
uint32_t pending = 0; // bytes summed since the last modulo
|
||||
uint8_t window[kWindow];
|
||||
|
||||
bool put(uint8_t byte) {
|
||||
if (total < limit) data[total] = byte;
|
||||
window[total & (kWindow - 1)] = byte;
|
||||
++total;
|
||||
a += byte;
|
||||
b += a;
|
||||
if (++pending == 5552) { // largest n with no 32-bit overflow before the modulo
|
||||
a %= 65521u;
|
||||
b %= 65521u;
|
||||
pending = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
BxInflateResult copy(size_t distance, size_t length) {
|
||||
if (distance > total || distance > kWindow) return BxInflateResult::bad_data;
|
||||
for (size_t i = 0; i < length; ++i) put(window[(total - distance) & (kWindow - 1)]);
|
||||
return BxInflateResult::ok;
|
||||
}
|
||||
size_t produced() const { return static_cast<size_t>(total); }
|
||||
uint32_t adler() const { return ((b % 65521u) << 16) | (a % 65521u); }
|
||||
};
|
||||
|
||||
template<class Out>
|
||||
BxInflateResult codes(Bits& in, Out& out, const Huffman& lit, const Huffman& dist) {
|
||||
for (;;) {
|
||||
const int symbol = lit.decode(in);
|
||||
if (symbol < 0) return in.overrun ? BxInflateResult::truncated : BxInflateResult::bad_data;
|
||||
if (symbol < 256) {
|
||||
if (out.pos >= out.size) return BxInflateResult::output_mismatch;
|
||||
out.data[out.pos++] = static_cast<uint8_t>(symbol);
|
||||
if (!out.put(static_cast<uint8_t>(symbol))) return BxInflateResult::output_mismatch;
|
||||
continue;
|
||||
}
|
||||
if (symbol == 256) return BxInflateResult::ok;
|
||||
@@ -108,13 +159,13 @@ BxInflateResult codes(Bits& in, Output& out, const Huffman& lit, const Huffman&
|
||||
if (ds >= 30) return BxInflateResult::bad_data;
|
||||
const size_t distance = kDistBase[ds] + in.get(kDistExtra[ds]);
|
||||
if (in.overrun) return BxInflateResult::truncated;
|
||||
if (distance > out.pos) return BxInflateResult::bad_data;
|
||||
if (length > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (size_t i = 0; i < length; ++i, ++out.pos) out.data[out.pos] = out.data[out.pos - distance];
|
||||
const BxInflateResult r = out.copy(distance, length);
|
||||
if (r != BxInflateResult::ok) return r;
|
||||
}
|
||||
}
|
||||
|
||||
BxInflateResult fixed_block(Bits& in, Output& out) {
|
||||
template<class Out>
|
||||
BxInflateResult fixed_block(Bits& in, Out& out) {
|
||||
static Huffman lit, dist;
|
||||
static bool built = [] {
|
||||
uint8_t lengths[288];
|
||||
@@ -133,7 +184,8 @@ BxInflateResult fixed_block(Bits& in, Output& out) {
|
||||
return codes(in, out, lit, dist);
|
||||
}
|
||||
|
||||
BxInflateResult dynamic_block(Bits& in, Output& out) {
|
||||
template<class Out>
|
||||
BxInflateResult dynamic_block(Bits& in, Out& out) {
|
||||
const int hlit = static_cast<int>(in.get(5)) + 257;
|
||||
const int hdist = static_cast<int>(in.get(5)) + 1;
|
||||
const int hclen = static_cast<int>(in.get(4)) + 4;
|
||||
@@ -189,17 +241,19 @@ uint32_t adler32(const uint8_t* data, size_t size) {
|
||||
return (b << 16) | a;
|
||||
}
|
||||
|
||||
uint32_t Output::adler() const { return adler32(data, pos); }
|
||||
|
||||
} // namespace
|
||||
|
||||
BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size, size_t* produced) {
|
||||
template<class Out>
|
||||
BxInflateResult inflate_stream(const uint8_t* input, size_t input_size, Out& out, size_t* produced) {
|
||||
// RFC 1950 2.2: CMF (method 8 = deflate, window <= 32 KiB), FLG (check bits, no FDICT).
|
||||
if (!input || input_size < 6 || (!output && output_size)) return BxInflateResult::bad_header;
|
||||
if (!input || input_size < 6) return BxInflateResult::bad_header;
|
||||
const uint8_t cmf = input[0], flg = input[1];
|
||||
if ((cmf & 0x0F) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) {
|
||||
return BxInflateResult::bad_header;
|
||||
}
|
||||
Bits in{input + 2, input_size - 2};
|
||||
Output out{output, output_size};
|
||||
for (;;) {
|
||||
const uint32_t final_block = in.get(1);
|
||||
const uint32_t type = in.get(2);
|
||||
@@ -212,8 +266,9 @@ BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* o
|
||||
if ((len ^ 0xFFFFu) != nlen) return BxInflateResult::bad_data;
|
||||
// After aligning, the bit buffer is empty: copy straight from the byte stream.
|
||||
if (len > in.size - in.pos) return BxInflateResult::truncated;
|
||||
if (len > out.size - out.pos) return BxInflateResult::output_mismatch;
|
||||
for (uint32_t i = 0; i < len; ++i) out.data[out.pos++] = in.data[in.pos++];
|
||||
for (uint32_t i = 0; i < len; ++i) {
|
||||
if (!out.put(in.data[in.pos++])) return BxInflateResult::output_mismatch;
|
||||
}
|
||||
r = BxInflateResult::ok;
|
||||
} else if (type == 1) {
|
||||
r = fixed_block(in, out);
|
||||
@@ -225,8 +280,7 @@ BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* o
|
||||
if (r != BxInflateResult::ok) return r;
|
||||
if (final_block) break;
|
||||
}
|
||||
if (produced) *produced = out.pos;
|
||||
else if (out.pos != out.size) return BxInflateResult::output_mismatch;
|
||||
if (produced) *produced = out.produced();
|
||||
// RFC 1950: the Adler-32 trailer follows the deflate data, byte-aligned, most significant first.
|
||||
in.align_to_byte();
|
||||
const size_t trailer = in.pos - static_cast<size_t>(in.count / 8);
|
||||
@@ -234,16 +288,34 @@ BxInflateResult inflate_impl(const uint8_t* input, size_t input_size, uint8_t* o
|
||||
const uint8_t* t = in.data + trailer;
|
||||
const uint32_t expected = (static_cast<uint32_t>(t[0]) << 24) | (static_cast<uint32_t>(t[1]) << 16) |
|
||||
(static_cast<uint32_t>(t[2]) << 8) | t[3];
|
||||
return adler32(output, out.pos) == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
|
||||
return out.adler() == expected ? BxInflateResult::ok : BxInflateResult::bad_checksum;
|
||||
}
|
||||
|
||||
BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t* output, size_t output_size) {
|
||||
return inflate_impl(input, input_size, output, output_size, nullptr);
|
||||
if (!output && output_size) return BxInflateResult::bad_header;
|
||||
Output out{output, output_size};
|
||||
size_t produced = 0;
|
||||
const BxInflateResult r = inflate_stream(input, input_size, out, &produced);
|
||||
if (r == BxInflateResult::ok && produced != output_size) return BxInflateResult::output_mismatch;
|
||||
return r;
|
||||
}
|
||||
|
||||
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced) {
|
||||
*produced = 0;
|
||||
return inflate_impl(input, input_size, output, capacity, produced);
|
||||
if (!output && capacity) return BxInflateResult::bad_header;
|
||||
Output out{output, capacity};
|
||||
return inflate_stream(input, input_size, out, produced);
|
||||
}
|
||||
|
||||
BxInflateResult bx_zlib_inflate_prefix(const uint8_t* input, size_t input_size, uint8_t* output, size_t prefix_size,
|
||||
size_t* produced) {
|
||||
*produced = 0;
|
||||
if (!output && prefix_size) return BxInflateResult::bad_header;
|
||||
auto* out = new (std::nothrow) PrefixOutput{output, prefix_size};
|
||||
if (!out) return BxInflateResult::output_mismatch;
|
||||
const BxInflateResult r = inflate_stream(input, input_size, *out, produced);
|
||||
delete out;
|
||||
return r;
|
||||
}
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result) {
|
||||
|
||||
@@ -29,4 +29,10 @@ BxInflateResult bx_zlib_inflate(const uint8_t* input, size_t input_size, uint8_t
|
||||
(checksum verified over those bytes). */
|
||||
BxInflateResult bx_zlib_inflate_any(const uint8_t* input, size_t input_size, uint8_t* output, size_t capacity, size_t* produced);
|
||||
|
||||
/* Decodes the whole of `input`, checks its Adler-32, writes only its first `prefix_size` bytes to
|
||||
`output` and reports how many bytes the stream produced. Memory use does not depend on the
|
||||
stream's length. */
|
||||
BxInflateResult bx_zlib_inflate_prefix(const uint8_t* input, size_t input_size, uint8_t* output, size_t prefix_size,
|
||||
size_t* produced);
|
||||
|
||||
const char* bx_inflate_result_name(BxInflateResult result);
|
||||
@@ -1,4 +1,53 @@
|
||||
# Vendored AMD addrlib, unmodified. Flags match Mesa's meson.build for this directory:
|
||||
# empty ADDR_FASTCALL (no regparm) and little-endian. DEBUG=0 keeps the assert path off.
|
||||
set(BX_ADDRLIB "${CMAKE_CURRENT_SOURCE_DIR}/third_party/addrlib")
|
||||
add_library(bx_addrlib STATIC
|
||||
"${BX_ADDRLIB}/src/addrinterface.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrelemlib.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrlib1.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrlib2.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrlib3.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrobject.cpp"
|
||||
"${BX_ADDRLIB}/src/core/addrswizzler.cpp"
|
||||
"${BX_ADDRLIB}/src/core/coord.cpp"
|
||||
"${BX_ADDRLIB}/src/gfx9/gfx9addrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/gfx10/gfx10addrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/gfx11/gfx11addrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/gfx12/gfx12addrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/r800/ciaddrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/r800/egbaddrlib.cpp"
|
||||
"${BX_ADDRLIB}/src/r800/siaddrlib.cpp"
|
||||
)
|
||||
target_include_directories(bx_addrlib PUBLIC
|
||||
"${BX_ADDRLIB}/inc"
|
||||
"${BX_ADDRLIB}/src"
|
||||
"${BX_ADDRLIB}/src/core"
|
||||
"${BX_ADDRLIB}/src/chip/gfx9"
|
||||
"${BX_ADDRLIB}/src/chip/gfx10"
|
||||
"${BX_ADDRLIB}/src/chip/gfx11"
|
||||
"${BX_ADDRLIB}/src/chip/gfx12"
|
||||
"${BX_ADDRLIB}/src/chip/r800"
|
||||
)
|
||||
target_compile_definitions(bx_addrlib PUBLIC ADDR_FASTCALL= LITTLEENDIAN_CPU DEBUG=0)
|
||||
target_compile_options(bx_addrlib PRIVATE
|
||||
-mbmi
|
||||
-Wno-unused-variable
|
||||
-Wno-ignored-qualifiers
|
||||
-Wno-unused-local-typedefs
|
||||
-Wno-maybe-uninitialized
|
||||
-Wno-unused-but-set-variable
|
||||
-Wno-unused-function
|
||||
-Wno-sign-compare
|
||||
-Wno-type-limits
|
||||
-Wno-implicit-fallthrough
|
||||
-Wno-missing-field-initializers
|
||||
-Wno-cast-function-type
|
||||
)
|
||||
|
||||
bx_add_shim_dll(xg_xs xg_xs xg_xs.def
|
||||
xg_xbox.cpp
|
||||
xg_addr.cpp
|
||||
)
|
||||
target_link_libraries(xg_xs PRIVATE bx_runtime_veh kernel32)
|
||||
target_link_libraries(xg_xs PRIVATE bx_runtime_veh bx_addrlib kernel32)
|
||||
target_compile_definitions(xg_xs PRIVATE ADDR_FASTCALL=)
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
# Vendored AMD addrlib
|
||||
|
||||
Unmodified copy of Mesa `src/amd/addrlib` at tag `mesa-25.2.0`, commit `0b97dcdd9424fce130054e1972a610b765644003` (`VERSION: bump for 25.2.0`).
|
||||
|
||||
Source: <https://gitlab.freedesktop.org/mesa/mesa/-/tree/0b97dcdd9424fce130054e1972a610b765644003/src/amd/addrlib>
|
||||
|
||||
42 of the 44 source files carry `SPDX-License-Identifier: MIT` (Advanced Micro Devices, or Intel on `meson.build`). `src/core/addrswizzler.cpp` and `src/core/addrswizzler.h` carry the same AMD copyright block dated 2024 and the words "All rights reserved", and they do not carry an SPDX line. They are compiled because gfx10, gfx11 and gfx12 include them. `meson.build`, which lists them, is SPDX MIT. No file in this directory was edited.
|
||||
|
||||
**Licence of `src/core/addrswizzler.cpp` and `src/core/addrswizzler.h`:** AMD added
|
||||
`SPDX-License-Identifier: MIT` to both files upstream in Mesa commit `d778ede72`
|
||||
("amd: import gfx11.7 addrlib", 2026-04-17, merge request 40958), the licence of the rest of addrlib.
|
||||
The copies here predate that line and are otherwise as vendored.
|
||||
+4715
File diff suppressed because it is too large.
Load diff
+781
@@ -0,0 +1,781 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrtypes.h
|
||||
* @brief Contains the helper function and constants
|
||||
****************************************************************************************************
|
||||
*/
|
||||
#ifndef __ADDR_TYPES_H__
|
||||
#define __ADDR_TYPES_H__
|
||||
|
||||
#if defined(__APPLE__) && !defined(HAVE_TSERVER)
|
||||
// External definitions header maintained by Apple driver team, but not for diag team under Mac.
|
||||
// Helps address compilation issues & reduces code covered by NDA
|
||||
#include "addrExtDef.h"
|
||||
|
||||
#else
|
||||
|
||||
// Windows and/or Linux
|
||||
#if !defined(VOID)
|
||||
typedef void VOID;
|
||||
#endif
|
||||
|
||||
#if !defined(FLOAT)
|
||||
typedef float FLOAT;
|
||||
#endif
|
||||
|
||||
#if !defined(DOUBLE)
|
||||
typedef double DOUBLE;
|
||||
#endif
|
||||
|
||||
#if !defined(CHAR)
|
||||
typedef char CHAR;
|
||||
#endif
|
||||
|
||||
#if !defined(INT)
|
||||
typedef int INT;
|
||||
#endif
|
||||
|
||||
#include <stdarg.h> // va_list...etc need this header
|
||||
|
||||
#endif // defined (__APPLE__) && !defined(HAVE_TSERVER)
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Calling conventions
|
||||
****************************************************************************************************
|
||||
*/
|
||||
#ifndef ADDR_CDECL
|
||||
#if defined(__GNUC__)
|
||||
#if defined(__i386__)
|
||||
#define ADDR_CDECL __attribute__((cdecl))
|
||||
#else
|
||||
#define ADDR_CDECL
|
||||
#endif
|
||||
#else
|
||||
#define ADDR_CDECL __cdecl
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef ADDR_STDCALL
|
||||
#if defined(__GNUC__)
|
||||
#if defined(__i386__)
|
||||
#define ADDR_STDCALL __attribute__((stdcall))
|
||||
#else
|
||||
#define ADDR_STDCALL
|
||||
#endif
|
||||
#else
|
||||
#define ADDR_STDCALL __stdcall
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef ADDR_FASTCALL
|
||||
#if defined(__GNUC__)
|
||||
#if defined(__i386__) || defined(__amd64__) || defined(__x86_64__)
|
||||
#define ADDR_FASTCALL __attribute__((regparm(0)))
|
||||
#else
|
||||
#define ADDR_FASTCALL
|
||||
#endif
|
||||
#else
|
||||
#define ADDR_FASTCALL __fastcall
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifndef GC_CDECL
|
||||
#define GC_CDECL ADDR_CDECL
|
||||
#endif
|
||||
|
||||
#ifndef GC_STDCALL
|
||||
#define GC_STDCALL ADDR_STDCALL
|
||||
#endif
|
||||
|
||||
#ifndef GC_FASTCALL
|
||||
#define GC_FASTCALL ADDR_FASTCALL
|
||||
#endif
|
||||
|
||||
|
||||
#if defined(__GNUC__)
|
||||
#define ADDR_INLINE static inline // inline needs to be static to link
|
||||
#else
|
||||
// win32, win64, other platforms
|
||||
#define ADDR_INLINE __inline
|
||||
#endif // #if defined(__GNUC__)
|
||||
|
||||
#define ADDR_API ADDR_FASTCALL //default call convention is fast call
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Global defines used by other modules
|
||||
****************************************************************************************************
|
||||
*/
|
||||
#if !defined(TILEINDEX_INVALID)
|
||||
#define TILEINDEX_INVALID -1
|
||||
#endif
|
||||
|
||||
#if !defined(TILEINDEX_LINEAR_GENERAL)
|
||||
#define TILEINDEX_LINEAR_GENERAL -2
|
||||
#endif
|
||||
|
||||
#if !defined(TILEINDEX_LINEAR_ALIGNED)
|
||||
#define TILEINDEX_LINEAR_ALIGNED 8
|
||||
#endif
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Return codes
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _ADDR_E_RETURNCODE
|
||||
{
|
||||
// General Return
|
||||
ADDR_OK = 0,
|
||||
ADDR_ERROR = 1,
|
||||
|
||||
// Specific Errors
|
||||
ADDR_OUTOFMEMORY,
|
||||
ADDR_INVALIDPARAMS,
|
||||
ADDR_NOTSUPPORTED,
|
||||
ADDR_NOTIMPLEMENTED,
|
||||
ADDR_PARAMSIZEMISMATCH,
|
||||
ADDR_INVALIDGBREGVALUES,
|
||||
|
||||
} ADDR_E_RETURNCODE;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define tile modes for all H/W
|
||||
* @note
|
||||
* R600/R800 tiling mode can be cast to hw enums directly but never cast into HW enum from
|
||||
* ADDR_TM_2D_TILED_XTHICK
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrTileMode
|
||||
{
|
||||
ADDR_TM_LINEAR_GENERAL = 0, ///< Least restrictions, pitch: multiple of 8 if not buffer
|
||||
ADDR_TM_LINEAR_ALIGNED = 1, ///< Requests pitch or slice to be multiple of 64 pixels
|
||||
ADDR_TM_1D_TILED_THIN1 = 2, ///< Linear array of 8x8 tiles
|
||||
ADDR_TM_1D_TILED_THICK = 3, ///< Linear array of 8x8x4 tiles
|
||||
ADDR_TM_2D_TILED_THIN1 = 4, ///< A set of macro tiles consist of 8x8 tiles
|
||||
ADDR_TM_2D_TILED_THIN2 = 5, ///< 600 HWL only, macro tile ratio is 1:4
|
||||
ADDR_TM_2D_TILED_THIN4 = 6, ///< 600 HWL only, macro tile ratio is 1:16
|
||||
ADDR_TM_2D_TILED_THICK = 7, ///< A set of macro tiles consist of 8x8x4 tiles
|
||||
ADDR_TM_2B_TILED_THIN1 = 8, ///< 600 HWL only, with bank swap
|
||||
ADDR_TM_2B_TILED_THIN2 = 9, ///< 600 HWL only, with bank swap and ratio is 1:4
|
||||
ADDR_TM_2B_TILED_THIN4 = 10, ///< 600 HWL only, with bank swap and ratio is 1:16
|
||||
ADDR_TM_2B_TILED_THICK = 11, ///< 600 HWL only, with bank swap, consists of 8x8x4 tiles
|
||||
ADDR_TM_3D_TILED_THIN1 = 12, ///< Macro tiling w/ pipe rotation between slices
|
||||
ADDR_TM_3D_TILED_THICK = 13, ///< Macro tiling w/ pipe rotation bwtween slices, thick
|
||||
ADDR_TM_3B_TILED_THIN1 = 14, ///< 600 HWL only, with bank swap
|
||||
ADDR_TM_3B_TILED_THICK = 15, ///< 600 HWL only, with bank swap, thick
|
||||
ADDR_TM_2D_TILED_XTHICK = 16, ///< Tile is 8x8x8, valid from NI
|
||||
ADDR_TM_3D_TILED_XTHICK = 17, ///< Tile is 8x8x8, valid from NI
|
||||
ADDR_TM_POWER_SAVE = 18, ///< Power save mode, only used by KMD on NI
|
||||
ADDR_TM_PRT_TILED_THIN1 = 19, ///< No bank/pipe rotation or hashing beyond macrotile size
|
||||
ADDR_TM_PRT_2D_TILED_THIN1 = 20, ///< Same as 2D_TILED_THIN1, PRT only
|
||||
ADDR_TM_PRT_3D_TILED_THIN1 = 21, ///< Same as 3D_TILED_THIN1, PRT only
|
||||
ADDR_TM_PRT_TILED_THICK = 22, ///< No bank/pipe rotation or hashing beyond macrotile size
|
||||
ADDR_TM_PRT_2D_TILED_THICK = 23, ///< Same as 2D_TILED_THICK, PRT only
|
||||
ADDR_TM_PRT_3D_TILED_THICK = 24, ///< Same as 3D_TILED_THICK, PRT only
|
||||
ADDR_TM_UNKNOWN = 25, ///< Unkown tile mode, should be decided by address lib
|
||||
ADDR_TM_COUNT = 26, ///< Must be the value of the last tile mode
|
||||
} AddrTileMode;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define swizzle modes for Gfx9+ ASIC
|
||||
* @note
|
||||
*
|
||||
* ADDR_SW_LINEAR linear aligned addressing mode, for 1D/2D/3D resource
|
||||
* ADDR_SW_256B_* addressing block aligned size is 256B, for 2D resource
|
||||
* ADDR_SW_4KB_* addressing block aligned size is 4KB, for 2D/3D resource
|
||||
* ADDR_SW_64KB_* addressing block aligned size is 64KB, for 1D/2D/3D resource
|
||||
* ADDR_SW_VAR_* addressing block aligned size is ASIC specific
|
||||
*
|
||||
* ADDR_SW_*_Z For GFX9:
|
||||
- for 2D resource, represents Z-order swizzle mode for depth/stencil/FMask
|
||||
- for 3D resource, represents a swizzle mode similar to legacy thick tile mode
|
||||
For GFX10:
|
||||
- represents Z-order swizzle mode for depth/stencil/FMask
|
||||
* ADDR_SW_*_S For GFX9+:
|
||||
- represents standard swizzle mode defined by MS
|
||||
* ADDR_SW_*_D For GFX9:
|
||||
- for 2D resource, represents a swizzle mode for displayable resource
|
||||
* - for 3D resource, represents a swizzle mode which places each slice in order & pixel
|
||||
For GFX10:
|
||||
- for 2D resource, represents a swizzle mode for displayable resource
|
||||
- for 3D resource, represents a swizzle mode similar to legacy thick tile mode
|
||||
within slice is placed as 2D ADDR_SW_*_S. Don't use this combination if possible!
|
||||
* ADDR_SW_*_R For GFX9:
|
||||
- 2D resource only, represents a swizzle mode for rotated displayable resource
|
||||
For GFX10:
|
||||
- represents a swizzle mode for render target resource
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrSwizzleMode
|
||||
{
|
||||
ADDR_SW_LINEAR = 0,
|
||||
ADDR_SW_256B_S = 1,
|
||||
ADDR_SW_256B_D = 2,
|
||||
ADDR_SW_256B_R = 3,
|
||||
ADDR_SW_4KB_Z = 4,
|
||||
ADDR_SW_4KB_S = 5,
|
||||
ADDR_SW_4KB_D = 6,
|
||||
ADDR_SW_4KB_R = 7,
|
||||
ADDR_SW_64KB_Z = 8,
|
||||
ADDR_SW_64KB_S = 9,
|
||||
ADDR_SW_64KB_D = 10,
|
||||
ADDR_SW_64KB_R = 11,
|
||||
ADDR_SW_MISCDEF12 = 12,
|
||||
ADDR_SW_MISCDEF13 = 13,
|
||||
ADDR_SW_MISCDEF14 = 14,
|
||||
ADDR_SW_MISCDEF15 = 15,
|
||||
ADDR_SW_64KB_Z_T = 16,
|
||||
ADDR_SW_64KB_S_T = 17,
|
||||
ADDR_SW_64KB_D_T = 18,
|
||||
ADDR_SW_64KB_R_T = 19,
|
||||
ADDR_SW_4KB_Z_X = 20,
|
||||
ADDR_SW_4KB_S_X = 21,
|
||||
ADDR_SW_4KB_D_X = 22,
|
||||
ADDR_SW_4KB_R_X = 23,
|
||||
ADDR_SW_64KB_Z_X = 24,
|
||||
ADDR_SW_64KB_S_X = 25,
|
||||
ADDR_SW_64KB_D_X = 26,
|
||||
ADDR_SW_64KB_R_X = 27,
|
||||
ADDR_SW_MISCDEF28 = 28,
|
||||
ADDR_SW_MISCDEF29 = 29,
|
||||
ADDR_SW_MISCDEF30 = 30,
|
||||
ADDR_SW_MISCDEF31 = 31,
|
||||
ADDR_SW_LINEAR_GENERAL = 32,
|
||||
ADDR_SW_MAX_TYPE = 33,
|
||||
|
||||
ADDR_SW_RESERVED0 = ADDR_SW_MISCDEF12,
|
||||
ADDR_SW_RESERVED1 = ADDR_SW_MISCDEF13,
|
||||
ADDR_SW_RESERVED2 = ADDR_SW_MISCDEF14,
|
||||
ADDR_SW_RESERVED3 = ADDR_SW_MISCDEF15,
|
||||
ADDR_SW_RESERVED4 = ADDR_SW_MISCDEF29,
|
||||
ADDR_SW_RESERVED5 = ADDR_SW_MISCDEF30,
|
||||
|
||||
ADDR_SW_VAR_Z_X = ADDR_SW_MISCDEF28,
|
||||
ADDR_SW_VAR_R_X = ADDR_SW_MISCDEF31,
|
||||
|
||||
ADDR_SW_256KB_Z_X = ADDR_SW_MISCDEF28,
|
||||
ADDR_SW_256KB_S_X = ADDR_SW_MISCDEF29,
|
||||
ADDR_SW_256KB_D_X = ADDR_SW_MISCDEF30,
|
||||
ADDR_SW_256KB_R_X = ADDR_SW_MISCDEF31,
|
||||
} AddrSwizzleMode;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define swizzle modes for Gfx12+ ASIC
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _Addr3SwizzleMode
|
||||
{
|
||||
ADDR3_LINEAR = 0,
|
||||
ADDR3_256B_2D = 1,
|
||||
ADDR3_4KB_2D = 2,
|
||||
ADDR3_64KB_2D = 3,
|
||||
ADDR3_256KB_2D = 4,
|
||||
ADDR3_4KB_3D = 5,
|
||||
ADDR3_64KB_3D = 6,
|
||||
ADDR3_256KB_3D = 7,
|
||||
ADDR3_MAX_TYPE,
|
||||
} Addr3SwizzleMode;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define image type
|
||||
* @note
|
||||
* this is new for address library interface version 2
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrResourceType
|
||||
{
|
||||
ADDR_RSRC_TEX_1D = 0,
|
||||
ADDR_RSRC_TEX_2D = 1,
|
||||
ADDR_RSRC_TEX_3D = 2,
|
||||
ADDR_RSRC_MAX_TYPE = 3,
|
||||
} AddrResourceType;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define resource heap location
|
||||
* @note
|
||||
* this is new for address library interface version 2
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrResrouceLocation
|
||||
{
|
||||
ADDR_RSRC_LOC_UNDEF = 0, // Resource heap is undefined/unknown
|
||||
ADDR_RSRC_LOC_LOCAL = 1, // CPU visable and CPU invisable local heap
|
||||
ADDR_RSRC_LOC_USWC = 2, // CPU write-combined non-cached nonlocal heap
|
||||
ADDR_RSRC_LOC_CACHED = 3, // CPU cached nonlocal heap
|
||||
ADDR_RSRC_LOC_INVIS = 4, // CPU invisable local heap only
|
||||
ADDR_RSRC_LOC_MAX_TYPE = 5,
|
||||
} AddrResrouceLocation;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define resource basic swizzle mode
|
||||
* @note
|
||||
* this is new for address library interface version 2
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrSwType
|
||||
{
|
||||
ADDR_SW_Z = 0, // Resource basic swizzle mode is ZOrder
|
||||
ADDR_SW_S = 1, // Resource basic swizzle mode is Standard
|
||||
ADDR_SW_D = 2, // Resource basic swizzle mode is Display
|
||||
ADDR_SW_R = 3, // Resource basic swizzle mode is Rotated/Render optimized
|
||||
ADDR_SW_L = 4, // Resource basic swizzle mode is Linear
|
||||
ADDR_SW_MAX_SWTYPE
|
||||
} AddrSwType;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief
|
||||
* Neutral enums that define mipmap major mode
|
||||
* @note
|
||||
* this is new for address library interface version 2
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrMajorMode
|
||||
{
|
||||
ADDR_MAJOR_X = 0,
|
||||
ADDR_MAJOR_Y = 1,
|
||||
ADDR_MAJOR_Z = 2,
|
||||
ADDR_MAJOR_MAX_TYPE = 3,
|
||||
} AddrMajorMode;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrFormat
|
||||
*
|
||||
* @brief
|
||||
* Neutral enum for SurfaceFormat
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrFormat {
|
||||
ADDR_FMT_INVALID = 0x00000000,
|
||||
ADDR_FMT_8 = 0x00000001,
|
||||
ADDR_FMT_4_4 = 0x00000002,
|
||||
ADDR_FMT_3_3_2 = 0x00000003,
|
||||
ADDR_FMT_RESERVED_4 = 0x00000004,
|
||||
ADDR_FMT_16 = 0x00000005,
|
||||
ADDR_FMT_16_FLOAT = ADDR_FMT_16,
|
||||
ADDR_FMT_8_8 = 0x00000007,
|
||||
ADDR_FMT_5_6_5 = 0x00000008,
|
||||
ADDR_FMT_6_5_5 = 0x00000009,
|
||||
ADDR_FMT_1_5_5_5 = 0x0000000a,
|
||||
ADDR_FMT_4_4_4_4 = 0x0000000b,
|
||||
ADDR_FMT_5_5_5_1 = 0x0000000c,
|
||||
ADDR_FMT_32 = 0x0000000d,
|
||||
ADDR_FMT_32_FLOAT = ADDR_FMT_32,
|
||||
ADDR_FMT_16_16 = 0x0000000f,
|
||||
ADDR_FMT_16_16_FLOAT = ADDR_FMT_16_16,
|
||||
ADDR_FMT_8_24 = 0x00000011,
|
||||
ADDR_FMT_8_24_FLOAT = ADDR_FMT_8_24,
|
||||
ADDR_FMT_24_8 = 0x00000013,
|
||||
ADDR_FMT_24_8_FLOAT = ADDR_FMT_24_8,
|
||||
ADDR_FMT_10_11_11 = 0x00000015,
|
||||
ADDR_FMT_10_11_11_FLOAT = ADDR_FMT_10_11_11,
|
||||
ADDR_FMT_11_11_10 = 0x00000017,
|
||||
ADDR_FMT_11_11_10_FLOAT = ADDR_FMT_11_11_10,
|
||||
ADDR_FMT_2_10_10_10 = 0x00000019,
|
||||
ADDR_FMT_8_8_8_8 = 0x0000001a,
|
||||
ADDR_FMT_10_10_10_2 = 0x0000001b,
|
||||
ADDR_FMT_X24_8_32_FLOAT = 0x0000001c,
|
||||
ADDR_FMT_32_32 = 0x0000001d,
|
||||
ADDR_FMT_32_32_FLOAT = ADDR_FMT_32_32,
|
||||
ADDR_FMT_16_16_16_16 = 0x0000001f,
|
||||
ADDR_FMT_16_16_16_16_FLOAT = ADDR_FMT_16_16_16_16,
|
||||
ADDR_FMT_RESERVED_33 = 0x00000021,
|
||||
ADDR_FMT_32_32_32_32 = 0x00000022,
|
||||
ADDR_FMT_32_32_32_32_FLOAT = ADDR_FMT_32_32_32_32,
|
||||
ADDR_FMT_RESERVED_36 = 0x00000024,
|
||||
ADDR_FMT_1 = 0x00000025,
|
||||
ADDR_FMT_1_REVERSED = 0x00000026,
|
||||
ADDR_FMT_GB_GR = 0x00000027,
|
||||
ADDR_FMT_BG_RG = 0x00000028,
|
||||
ADDR_FMT_32_AS_8 = 0x00000029,
|
||||
ADDR_FMT_32_AS_8_8 = 0x0000002a,
|
||||
ADDR_FMT_5_9_9_9_SHAREDEXP = 0x0000002b,
|
||||
ADDR_FMT_8_8_8 = 0x0000002c,
|
||||
ADDR_FMT_16_16_16 = 0x0000002d,
|
||||
ADDR_FMT_16_16_16_FLOAT = ADDR_FMT_16_16_16,
|
||||
ADDR_FMT_32_32_32 = 0x0000002f,
|
||||
ADDR_FMT_32_32_32_FLOAT = ADDR_FMT_32_32_32,
|
||||
ADDR_FMT_BC1 = 0x00000031,
|
||||
ADDR_FMT_BC2 = 0x00000032,
|
||||
ADDR_FMT_BC3 = 0x00000033,
|
||||
ADDR_FMT_BC4 = 0x00000034,
|
||||
ADDR_FMT_BC5 = 0x00000035,
|
||||
ADDR_FMT_BC6 = 0x00000036,
|
||||
ADDR_FMT_BC7 = 0x00000037,
|
||||
ADDR_FMT_32_AS_32_32_32_32 = 0x00000038,
|
||||
ADDR_FMT_APC3 = 0x00000039,
|
||||
ADDR_FMT_APC4 = 0x0000003a,
|
||||
ADDR_FMT_APC5 = 0x0000003b,
|
||||
ADDR_FMT_APC6 = 0x0000003c,
|
||||
ADDR_FMT_APC7 = 0x0000003d,
|
||||
ADDR_FMT_CTX1 = 0x0000003e,
|
||||
ADDR_FMT_RESERVED_63 = 0x0000003f,
|
||||
ADDR_FMT_ASTC_4x4 = 0x00000040,
|
||||
ADDR_FMT_ASTC_5x4 = 0x00000041,
|
||||
ADDR_FMT_ASTC_5x5 = 0x00000042,
|
||||
ADDR_FMT_ASTC_6x5 = 0x00000043,
|
||||
ADDR_FMT_ASTC_6x6 = 0x00000044,
|
||||
ADDR_FMT_ASTC_8x5 = 0x00000045,
|
||||
ADDR_FMT_ASTC_8x6 = 0x00000046,
|
||||
ADDR_FMT_ASTC_8x8 = 0x00000047,
|
||||
ADDR_FMT_ASTC_10x5 = 0x00000048,
|
||||
ADDR_FMT_ASTC_10x6 = 0x00000049,
|
||||
ADDR_FMT_ASTC_10x8 = 0x0000004a,
|
||||
ADDR_FMT_ASTC_10x10 = 0x0000004b,
|
||||
ADDR_FMT_ASTC_12x10 = 0x0000004c,
|
||||
ADDR_FMT_ASTC_12x12 = 0x0000004d,
|
||||
ADDR_FMT_ETC2_64BPP = 0x0000004e,
|
||||
ADDR_FMT_ETC2_128BPP = 0x0000004f,
|
||||
ADDR_FMT_BG_RG_16_16_16_16 = 0x00000050,
|
||||
} AddrFormat;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrDepthFormat
|
||||
*
|
||||
* @brief
|
||||
* Neutral enum for addrFlt32ToDepthPixel
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrDepthFormat
|
||||
{
|
||||
ADDR_DEPTH_INVALID = 0x00000000,
|
||||
ADDR_DEPTH_16 = 0x00000001,
|
||||
ADDR_DEPTH_X8_24 = 0x00000002,
|
||||
ADDR_DEPTH_8_24 = 0x00000003,
|
||||
ADDR_DEPTH_X8_24_FLOAT = 0x00000004,
|
||||
ADDR_DEPTH_8_24_FLOAT = 0x00000005,
|
||||
ADDR_DEPTH_32_FLOAT = 0x00000006,
|
||||
ADDR_DEPTH_X24_8_32_FLOAT = 0x00000007,
|
||||
|
||||
} AddrDepthFormat;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrColorFormat
|
||||
*
|
||||
* @brief
|
||||
* Neutral enum for ColorFormat
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrColorFormat
|
||||
{
|
||||
ADDR_COLOR_INVALID = 0x00000000,
|
||||
ADDR_COLOR_8 = 0x00000001,
|
||||
ADDR_COLOR_4_4 = 0x00000002,
|
||||
ADDR_COLOR_3_3_2 = 0x00000003,
|
||||
ADDR_COLOR_RESERVED_4 = 0x00000004,
|
||||
ADDR_COLOR_16 = 0x00000005,
|
||||
ADDR_COLOR_16_FLOAT = 0x00000006,
|
||||
ADDR_COLOR_8_8 = 0x00000007,
|
||||
ADDR_COLOR_5_6_5 = 0x00000008,
|
||||
ADDR_COLOR_6_5_5 = 0x00000009,
|
||||
ADDR_COLOR_1_5_5_5 = 0x0000000a,
|
||||
ADDR_COLOR_4_4_4_4 = 0x0000000b,
|
||||
ADDR_COLOR_5_5_5_1 = 0x0000000c,
|
||||
ADDR_COLOR_32 = 0x0000000d,
|
||||
ADDR_COLOR_32_FLOAT = 0x0000000e,
|
||||
ADDR_COLOR_16_16 = 0x0000000f,
|
||||
ADDR_COLOR_16_16_FLOAT = 0x00000010,
|
||||
ADDR_COLOR_8_24 = 0x00000011,
|
||||
ADDR_COLOR_8_24_FLOAT = 0x00000012,
|
||||
ADDR_COLOR_24_8 = 0x00000013,
|
||||
ADDR_COLOR_24_8_FLOAT = 0x00000014,
|
||||
ADDR_COLOR_10_11_11 = 0x00000015,
|
||||
ADDR_COLOR_10_11_11_FLOAT = 0x00000016,
|
||||
ADDR_COLOR_11_11_10 = 0x00000017,
|
||||
ADDR_COLOR_11_11_10_FLOAT = 0x00000018,
|
||||
ADDR_COLOR_2_10_10_10 = 0x00000019,
|
||||
ADDR_COLOR_8_8_8_8 = 0x0000001a,
|
||||
ADDR_COLOR_10_10_10_2 = 0x0000001b,
|
||||
ADDR_COLOR_X24_8_32_FLOAT = 0x0000001c,
|
||||
ADDR_COLOR_32_32 = 0x0000001d,
|
||||
ADDR_COLOR_32_32_FLOAT = 0x0000001e,
|
||||
ADDR_COLOR_16_16_16_16 = 0x0000001f,
|
||||
ADDR_COLOR_16_16_16_16_FLOAT = 0x00000020,
|
||||
ADDR_COLOR_RESERVED_33 = 0x00000021,
|
||||
ADDR_COLOR_32_32_32_32 = 0x00000022,
|
||||
ADDR_COLOR_32_32_32_32_FLOAT = 0x00000023,
|
||||
} AddrColorFormat;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrSurfaceNumber
|
||||
*
|
||||
* @brief
|
||||
* Neutral enum for SurfaceNumber
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrSurfaceNumber {
|
||||
ADDR_NUMBER_UNORM = 0x00000000,
|
||||
ADDR_NUMBER_SNORM = 0x00000001,
|
||||
ADDR_NUMBER_USCALED = 0x00000002,
|
||||
ADDR_NUMBER_SSCALED = 0x00000003,
|
||||
ADDR_NUMBER_UINT = 0x00000004,
|
||||
ADDR_NUMBER_SINT = 0x00000005,
|
||||
ADDR_NUMBER_SRGB = 0x00000006,
|
||||
ADDR_NUMBER_FLOAT = 0x00000007,
|
||||
} AddrSurfaceNumber;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrSurfaceSwap
|
||||
*
|
||||
* @brief
|
||||
* Neutral enum for SurfaceSwap
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrSurfaceSwap {
|
||||
ADDR_SWAP_STD = 0x00000000,
|
||||
ADDR_SWAP_ALT = 0x00000001,
|
||||
ADDR_SWAP_STD_REV = 0x00000002,
|
||||
ADDR_SWAP_ALT_REV = 0x00000003,
|
||||
} AddrSurfaceSwap;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrHtileBlockSize
|
||||
*
|
||||
* @brief
|
||||
* Size of HTILE blocks, valid values are 4 or 8 for now
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrHtileBlockSize
|
||||
{
|
||||
ADDR_HTILE_BLOCKSIZE_4 = 4,
|
||||
ADDR_HTILE_BLOCKSIZE_8 = 8,
|
||||
} AddrHtileBlockSize;
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrPipeCfg
|
||||
*
|
||||
* @brief
|
||||
* The pipe configuration field specifies both the number of pipes and
|
||||
* how pipes are interleaved on the surface.
|
||||
* The expression of number of pipes, the shader engine tile size, and packer tile size
|
||||
* is encoded in a PIPE_CONFIG register field.
|
||||
* In general the number of pipes usually matches the number of memory channels of the
|
||||
* hardware configuration.
|
||||
* For hw configurations w/ non-pow2 memory number of memory channels, it usually matches
|
||||
* the number of ROP units(? TODO: which registers??)
|
||||
* The enum value = hw enum + 1 which is to reserve 0 for requesting default.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrPipeCfg
|
||||
{
|
||||
ADDR_PIPECFG_INVALID = 0,
|
||||
ADDR_PIPECFG_P2 = 1, /// 2 pipes,
|
||||
ADDR_PIPECFG_P4_8x16 = 5, /// 4 pipes,
|
||||
ADDR_PIPECFG_P4_16x16 = 6,
|
||||
ADDR_PIPECFG_P4_16x32 = 7,
|
||||
ADDR_PIPECFG_P4_32x32 = 8,
|
||||
ADDR_PIPECFG_P8_16x16_8x16 = 9, /// 8 pipes
|
||||
ADDR_PIPECFG_P8_16x32_8x16 = 10,
|
||||
ADDR_PIPECFG_P8_32x32_8x16 = 11,
|
||||
ADDR_PIPECFG_P8_16x32_16x16 = 12,
|
||||
ADDR_PIPECFG_P8_32x32_16x16 = 13,
|
||||
ADDR_PIPECFG_P8_32x32_16x32 = 14,
|
||||
ADDR_PIPECFG_P8_32x64_32x32 = 15,
|
||||
ADDR_PIPECFG_P16_32x32_8x16 = 17, /// 16 pipes
|
||||
ADDR_PIPECFG_P16_32x32_16x16 = 18,
|
||||
ADDR_PIPECFG_UNUSED = 19,
|
||||
ADDR_PIPECFG_MAX = 20,
|
||||
} AddrPipeCfg;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* AddrTileType
|
||||
*
|
||||
* @brief
|
||||
* Neutral enums that specifies micro tile type (MICRO_TILE_MODE)
|
||||
****************************************************************************************************
|
||||
*/
|
||||
typedef enum _AddrTileType
|
||||
{
|
||||
ADDR_DISPLAYABLE = 0, ///< Displayable tiling
|
||||
ADDR_NON_DISPLAYABLE = 1, ///< Non-displayable tiling, a.k.a thin micro tiling
|
||||
ADDR_DEPTH_SAMPLE_ORDER = 2, ///< Same as non-displayable plus depth-sample-order
|
||||
ADDR_ROTATED = 3, ///< Rotated displayable tiling
|
||||
ADDR_THICK = 4, ///< Thick micro-tiling, only valid for THICK and XTHICK
|
||||
} AddrTileType;
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Type definitions: short system-independent names for address library types
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#if !defined(__APPLE__) || defined(HAVE_TSERVER)
|
||||
|
||||
#ifndef BOOL_32 // no bool type in C
|
||||
/// @brief Boolean type, since none is defined in C
|
||||
/// @ingroup type
|
||||
#define BOOL_32 int
|
||||
#endif
|
||||
|
||||
#ifndef INT_32
|
||||
#define INT_32 int
|
||||
#endif
|
||||
|
||||
#ifndef UINT_32
|
||||
#define UINT_32 unsigned int
|
||||
#endif
|
||||
|
||||
#ifndef INT_16
|
||||
#define INT_16 short
|
||||
#endif
|
||||
|
||||
#ifndef UINT_16
|
||||
#define UINT_16 unsigned short
|
||||
#endif
|
||||
|
||||
#ifndef INT_8
|
||||
#define INT_8 signed char // signed must be used because of aarch64
|
||||
#endif
|
||||
|
||||
#ifndef UINT_8
|
||||
#define UINT_8 unsigned char
|
||||
#endif
|
||||
|
||||
#ifndef NULL
|
||||
#define NULL 0
|
||||
#endif
|
||||
|
||||
#ifndef TRUE
|
||||
#define TRUE 1
|
||||
#endif
|
||||
|
||||
#ifndef FALSE
|
||||
#define FALSE 0
|
||||
#endif
|
||||
|
||||
//
|
||||
// 64-bit integer types depend on the compiler
|
||||
//
|
||||
#if defined( __GNUC__ ) || defined( __WATCOMC__ )
|
||||
#define INT_64 long long
|
||||
#define UINT_64 unsigned long long
|
||||
|
||||
#elif defined( _WIN32 )
|
||||
#define INT_64 __int64
|
||||
#define UINT_64 unsigned __int64
|
||||
|
||||
#else
|
||||
#error Unsupported compiler and/or operating system for 64-bit integers
|
||||
|
||||
/// @brief 64-bit signed integer type (compiler dependent)
|
||||
/// @ingroup type
|
||||
///
|
||||
/// The addrlib defines a 64-bit signed integer type for either
|
||||
/// Gnu/Watcom compilers (which use the first syntax) or for
|
||||
/// the Windows VCC compiler (which uses the second syntax).
|
||||
#define INT_64 long long OR __int64
|
||||
|
||||
/// @brief 64-bit unsigned integer type (compiler dependent)
|
||||
/// @ingroup type
|
||||
///
|
||||
/// The addrlib defines a 64-bit unsigned integer type for either
|
||||
/// Gnu/Watcom compilers (which use the first syntax) or for
|
||||
/// the Windows VCC compiler (which uses the second syntax).
|
||||
///
|
||||
#define UINT_64 unsigned long long OR unsigned __int64
|
||||
#endif
|
||||
|
||||
#endif // #if !defined(__APPLE__) || defined(HAVE_TSERVER)
|
||||
|
||||
// ADDR64X is used to print addresses in hex form on both Windows and Linux
|
||||
//
|
||||
#if defined( __GNUC__ ) || defined( __WATCOMC__ )
|
||||
#define ADDR64X "llx"
|
||||
#define ADDR64D "lld"
|
||||
|
||||
#elif defined( _WIN32 )
|
||||
#define ADDR64X "I64x"
|
||||
#define ADDR64D "I64d"
|
||||
|
||||
#else
|
||||
#error Unsupported compiler and/or operating system for 64-bit integers
|
||||
|
||||
/// @brief Addrlib device address 64-bit printf tag (compiler dependent)
|
||||
/// @ingroup type
|
||||
///
|
||||
/// This allows printf to display an ADDR_64 for either the Windows VCC compiler
|
||||
/// (which used this value) or the Gnu/Watcom compilers (which use "llx".
|
||||
/// An example of use is printf("addr 0x%"ADDR64X"\n", address);
|
||||
///
|
||||
#define ADDR64X "llx" OR "I64x"
|
||||
#define ADDR64D "lld" OR "I64d"
|
||||
#endif
|
||||
|
||||
|
||||
/// @brief Union for storing a 32-bit float or 32-bit integer
|
||||
/// @ingroup type
|
||||
///
|
||||
/// This union provides a simple way to convert between a 32-bit float
|
||||
/// and a 32-bit integer. It also prevents the compiler from producing
|
||||
/// code that alters NaN values when assiging or coying floats.
|
||||
/// Therefore, all address library routines that pass or return 32-bit
|
||||
/// floating point data do so by passing or returning a FLT_32.
|
||||
///
|
||||
typedef union {
|
||||
INT_32 i;
|
||||
UINT_32 u;
|
||||
float f;
|
||||
} ADDR_FLT_32;
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// Macros for controlling linking and building on multiple systems
|
||||
//
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
#if defined(_MSC_VER)
|
||||
#if defined(va_copy)
|
||||
#undef va_copy //redefine va_copy to support VC2013
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if !defined(va_copy)
|
||||
#define va_copy(dst, src) \
|
||||
((void) memcpy(&(dst), &(src), sizeof(va_list)))
|
||||
#endif
|
||||
|
||||
#endif // __ADDR_TYPES_H__
|
||||
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
# Copyright © 2017 Intel Corporation
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
files_addrlib = files(
|
||||
'inc/addrinterface.h',
|
||||
'inc/addrtypes.h',
|
||||
'src/addrinterface.cpp',
|
||||
'src/core/addrcommon.h',
|
||||
'src/core/addrelemlib.cpp',
|
||||
'src/core/addrelemlib.h',
|
||||
'src/core/addrlib.cpp',
|
||||
'src/core/addrlib.h',
|
||||
'src/core/addrlib1.cpp',
|
||||
'src/core/addrlib1.h',
|
||||
'src/core/addrlib2.cpp',
|
||||
'src/core/addrlib2.h',
|
||||
'src/core/addrlib3.cpp',
|
||||
'src/core/addrlib3.h',
|
||||
'src/core/addrobject.cpp',
|
||||
'src/core/addrobject.h',
|
||||
'src/core/addrswizzler.cpp',
|
||||
'src/core/addrswizzler.h',
|
||||
'src/core/coord.cpp',
|
||||
'src/core/coord.h',
|
||||
'src/gfx9/gfx9addrlib.cpp',
|
||||
'src/gfx9/gfx9addrlib.h',
|
||||
'src/gfx10/gfx10addrlib.cpp',
|
||||
'src/gfx10/gfx10addrlib.h',
|
||||
'src/gfx10/gfx10SwizzlePattern.h',
|
||||
'src/gfx11/gfx11addrlib.cpp',
|
||||
'src/gfx11/gfx11addrlib.h',
|
||||
'src/gfx11/gfx11SwizzlePattern.h',
|
||||
'src/gfx12/gfx12addrlib.cpp',
|
||||
'src/gfx12/gfx12addrlib.h',
|
||||
'src/gfx12/gfx12SwizzlePattern.h',
|
||||
'src/amdgpu_asic_addr.h',
|
||||
'src/chip/gfx10/gfx10_gb_reg.h',
|
||||
'src/chip/gfx11/gfx11_gb_reg.h',
|
||||
'src/chip/gfx12/gfx12_gb_reg.h',
|
||||
'src/chip/gfx9/gfx9_gb_reg.h',
|
||||
'src/chip/r800/si_gb_reg.h',
|
||||
'src/r800/ciaddrlib.cpp',
|
||||
'src/r800/ciaddrlib.h',
|
||||
'src/r800/egbaddrlib.cpp',
|
||||
'src/r800/egbaddrlib.h',
|
||||
'src/r800/siaddrlib.cpp',
|
||||
'src/r800/siaddrlib.h',
|
||||
)
|
||||
|
||||
# Skip the addrlib definition of ADDR_FASTCALL so as not to use regparm.
|
||||
cpp_args_addrlib = ['-DADDR_FASTCALL=']
|
||||
|
||||
if host_machine.endian() == 'little'
|
||||
cpp_args_addrlib += '-DLITTLEENDIAN_CPU'
|
||||
else
|
||||
cpp_args_addrlib += '-DBIGENDIAN_CPU'
|
||||
endif
|
||||
|
||||
if with_mesa_ndebug
|
||||
cpp_args_addrlib += '-DDEBUG=0'
|
||||
else
|
||||
cpp_args_addrlib += '-DDEBUG=1'
|
||||
endif
|
||||
|
||||
cpp_args_addrlib += cpp.get_supported_arguments(
|
||||
['-Wno-unused-variable', '-Wno-unused-local-typedefs',
|
||||
'-Wno-unused-but-set-variable', '-Wno-maybe-uninitialized',
|
||||
'-Wno-self-assign', '/wd4189', '-Wno-uninitialized']
|
||||
)
|
||||
|
||||
libamdgpu_addrlib = static_library(
|
||||
'addrlib',
|
||||
files_addrlib,
|
||||
include_directories : [
|
||||
include_directories(
|
||||
'inc', 'src', 'src/core', 'src/chip/gfx9', 'src/chip/r800',
|
||||
'src/chip/gfx10', 'src/chip/gfx11', 'src/chip/gfx12',
|
||||
),
|
||||
inc_amd_common, inc_include, inc_src
|
||||
],
|
||||
cpp_args : cpp_args_addrlib,
|
||||
gnu_symbol_visibility : 'hidden',
|
||||
)
|
||||
+2384
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,199 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2017-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
#ifndef _AMDGPU_ASIC_ADDR_H
|
||||
#define _AMDGPU_ASIC_ADDR_H
|
||||
|
||||
#define ATI_VENDOR_ID 0x1002
|
||||
#define AMD_VENDOR_ID 0x1022
|
||||
|
||||
// AMDGPU_VENDOR_IS_AMD(vendorId)
|
||||
#define AMDGPU_VENDOR_IS_AMD(v) ((v == ATI_VENDOR_ID) || (v == AMD_VENDOR_ID))
|
||||
|
||||
#define FAMILY_UNKNOWN 0x00
|
||||
#define FAMILY_TN 0x69 //# 105 / Trinity APUs
|
||||
#define FAMILY_SI 0x6E //# 110 / Southern Islands: Tahiti, Pitcairn, CapeVerde, Oland, Hainan
|
||||
#define FAMILY_CI 0x78 //# 120 / Sea Islands: Bonaire, Hawaii
|
||||
#define FAMILY_KV 0x7D //# 125 / Kaveri APUs: Spectre, Spooky, Kalindi, Godavari
|
||||
#define FAMILY_VI 0x82 //# 130 / Volcanic Islands: Iceland, Tonga, Fiji
|
||||
#define FAMILY_CZ 0x87 //# 135 / Carrizo APUs: Carrizo, Stoney
|
||||
#define FAMILY_AI 0x8D //# 141 / Vega: 10, 20
|
||||
#define FAMILY_RV 0x8E //# 142 / Raven
|
||||
#define FAMILY_NV 0x8F //# 143 / Navi: 10
|
||||
#define FAMILY_VGH 0x90 //# 144 / Van Gogh
|
||||
#define FAMILY_NV3 0x91 //# 145 / Navi: 3x
|
||||
#define FAMILY_GFX1150 0x96
|
||||
#define FAMILY_PHX 0x94 //# 148 / Phoenix
|
||||
#define FAMILY_RMB 0x92 //# 146 / Rembrandt
|
||||
#define FAMILY_RPL 0x95 //# 149 / Raphael
|
||||
#define FAMILY_MDN 0x97 //# 151 / Mendocino
|
||||
#define FAMILY_GFX12 0x98
|
||||
|
||||
// AMDGPU_FAMILY_IS(familyId, familyName)
|
||||
#define FAMILY_IS(f, fn) (f == FAMILY_##fn)
|
||||
#define FAMILY_IS_TN(f) FAMILY_IS(f, TN)
|
||||
#define FAMILY_IS_SI(f) FAMILY_IS(f, SI)
|
||||
#define FAMILY_IS_CI(f) FAMILY_IS(f, CI)
|
||||
#define FAMILY_IS_KV(f) FAMILY_IS(f, KV)
|
||||
#define FAMILY_IS_VI(f) FAMILY_IS(f, VI)
|
||||
#define FAMILY_IS_POLARIS(f) FAMILY_IS(f, POLARIS)
|
||||
#define FAMILY_IS_CZ(f) FAMILY_IS(f, CZ)
|
||||
#define FAMILY_IS_AI(f) FAMILY_IS(f, AI)
|
||||
#define FAMILY_IS_RV(f) FAMILY_IS(f, RV)
|
||||
#define FAMILY_IS_NV(f) FAMILY_IS(f, NV)
|
||||
#define FAMILY_IS_RMB(f) FAMILY_IS(f, RMB)
|
||||
#define FAMILY_IS_NV3(f) FAMILY_IS(f, NV3)
|
||||
#define FAMILY_IS_GFX12(f) FAMILY_IS(f, GFX12)
|
||||
|
||||
#define AMDGPU_UNKNOWN 0xFF
|
||||
|
||||
#define AMDGPU_TAHITI_RANGE 0x05, 0x14 //# 5 <= x < 20
|
||||
#define AMDGPU_PITCAIRN_RANGE 0x15, 0x28 //# 21 <= x < 40
|
||||
#define AMDGPU_CAPEVERDE_RANGE 0x29, 0x3C //# 41 <= x < 60
|
||||
#define AMDGPU_OLAND_RANGE 0x3C, 0x46 //# 60 <= x < 70
|
||||
#define AMDGPU_HAINAN_RANGE 0x46, 0xFF //# 70 <= x < max
|
||||
|
||||
#define AMDGPU_BONAIRE_RANGE 0x14, 0x28 //# 20 <= x < 40
|
||||
#define AMDGPU_HAWAII_RANGE 0x28, 0x3C //# 40 <= x < 60
|
||||
|
||||
#define AMDGPU_SPECTRE_RANGE 0x01, 0x41 //# 1 <= x < 65
|
||||
#define AMDGPU_SPOOKY_RANGE 0x41, 0x81 //# 65 <= x < 129
|
||||
#define AMDGPU_KALINDI_RANGE 0x81, 0xA1 //# 129 <= x < 161
|
||||
#define AMDGPU_GODAVARI_RANGE 0xA1, 0xFF //# 161 <= x < max
|
||||
|
||||
#define AMDGPU_ICELAND_RANGE 0x01, 0x14 //# 1 <= x < 20
|
||||
#define AMDGPU_TONGA_RANGE 0x14, 0x28 //# 20 <= x < 40
|
||||
#define AMDGPU_FIJI_RANGE 0x3C, 0x50 //# 60 <= x < 80
|
||||
|
||||
#define AMDGPU_POLARIS10_RANGE 0x50, 0x5A //# 80 <= x < 90
|
||||
#define AMDGPU_POLARIS11_RANGE 0x5A, 0x64 //# 90 <= x < 100
|
||||
#define AMDGPU_POLARIS12_RANGE 0x64, 0x6E //# 100 <= x < 110
|
||||
#define AMDGPU_VEGAM_RANGE 0x6E, 0xFF //# 110 <= x < max
|
||||
|
||||
#define AMDGPU_CARRIZO_RANGE 0x01, 0x21 //# 1 <= x < 33
|
||||
#define AMDGPU_BRISTOL_RANGE 0x10, 0x21 //# 16 <= x < 33
|
||||
#define AMDGPU_STONEY_RANGE 0x61, 0xFF //# 97 <= x < max
|
||||
|
||||
#define AMDGPU_VEGA10_RANGE 0x01, 0x14 //# 1 <= x < 20
|
||||
#define AMDGPU_VEGA12_RANGE 0x14, 0x28 //# 20 <= x < 40
|
||||
#define AMDGPU_VEGA20_RANGE 0x28, 0x31 //# 40 <= x < 49
|
||||
|
||||
#define AMDGPU_RAVEN_RANGE 0x01, 0x81 //# 1 <= x < 129
|
||||
#define AMDGPU_RAVEN2_RANGE 0x81, 0x90 //# 129 <= x < 144
|
||||
#define AMDGPU_RENOIR_RANGE 0x91, 0xFF //# 145 <= x < max
|
||||
|
||||
#define AMDGPU_NAVI10_RANGE 0x01, 0x0A //# 1 <= x < 10
|
||||
#define AMDGPU_NAVI12_RANGE 0x0A, 0x14 //# 10 <= x < 20
|
||||
#define AMDGPU_NAVI14_RANGE 0x14, 0x28 //# 20 <= x < 40
|
||||
#define AMDGPU_GFX1013_RANGE 0x84, 0x85 //# 132 <= x < 133
|
||||
#define AMDGPU_NAVI21_RANGE 0x28, 0x32 //# 40 <= x < 50
|
||||
#define AMDGPU_NAVI22_RANGE 0x32, 0x3C //# 50 <= x < 60
|
||||
#define AMDGPU_NAVI23_RANGE 0x3C, 0x46 //# 60 <= x < 70
|
||||
#define AMDGPU_NAVI24_RANGE 0x46, 0x50 //# 70 <= x < 80
|
||||
|
||||
#define AMDGPU_VANGOGH_RANGE 0x01, 0xFF //# 1 <= x < max
|
||||
|
||||
#define AMDGPU_NAVI31_RANGE 0x01, 0x10 //# 01 <= x < 16
|
||||
#define AMDGPU_NAVI32_RANGE 0x20, 0xFF //# 32 <= x < 255
|
||||
#define AMDGPU_NAVI33_RANGE 0x10, 0x20 //# 16 <= x < 32
|
||||
#define AMDGPU_GFX1150_RANGE 0x01, 0x40 //# 1 <= x < 64
|
||||
#define AMDGPU_GFX1151_RANGE 0xC0, 0xFF //# 192 <= x < 255
|
||||
#define AMDGPU_GFX1152_RANGE 0x40, 0x50 //# 64 <= x < 80
|
||||
#define AMDGPU_GFX1153_RANGE 0x50, 0xC0 //# 80 <= x < 192
|
||||
#define AMDGPU_PHOENIX1_RANGE 0x01, 0x80 //# 1 <= x < 128
|
||||
#define AMDGPU_PHOENIX2_RANGE 0x80, 0xC0 //# 128 <= x < 192
|
||||
#define AMDGPU_HAWK_POINT1_RANGE 0xC0, 0xF0 //# 192 <= x < 240
|
||||
#define AMDGPU_HAWK_POINT2_RANGE 0xF0, 0xFF //# 240 <= x < 255
|
||||
|
||||
#define AMDGPU_REMBRANDT_RANGE 0x01, 0xFF //# 01 <= x < 255
|
||||
#define AMDGPU_RAPHAEL_RANGE 0x01, 0xFF //# 1 <= x < max
|
||||
#define AMDGPU_MENDOCINO_RANGE 0x01, 0xFF //# 1 <= x < max
|
||||
|
||||
#define AMDGPU_GFX1200_RANGE 0x40, 0x50
|
||||
#define AMDGPU_GFX1201_RANGE 0x50, 0xFF
|
||||
|
||||
|
||||
#define AMDGPU_EXPAND_FIX(x) x
|
||||
#define AMDGPU_RANGE_HELPER(val, min, max) ((val >= min) && (val < max))
|
||||
#define AMDGPU_IN_RANGE(val, ...) AMDGPU_EXPAND_FIX(AMDGPU_RANGE_HELPER(val, __VA_ARGS__))
|
||||
|
||||
|
||||
// ASICREV_IS(eRevisionId, revisionName)
|
||||
#define ASICREV_IS(r, rn) AMDGPU_IN_RANGE(r, AMDGPU_##rn##_RANGE)
|
||||
#define ASICREV_IS_TAHITI_P(r) ASICREV_IS(r, TAHITI)
|
||||
#define ASICREV_IS_PITCAIRN_PM(r) ASICREV_IS(r, PITCAIRN)
|
||||
#define ASICREV_IS_CAPEVERDE_M(r) ASICREV_IS(r, CAPEVERDE)
|
||||
#define ASICREV_IS_OLAND_M(r) ASICREV_IS(r, OLAND)
|
||||
#define ASICREV_IS_HAINAN_V(r) ASICREV_IS(r, HAINAN)
|
||||
|
||||
#define ASICREV_IS_BONAIRE_M(r) ASICREV_IS(r, BONAIRE)
|
||||
#define ASICREV_IS_HAWAII_P(r) ASICREV_IS(r, HAWAII)
|
||||
|
||||
#define ASICREV_IS_SPECTRE(r) ASICREV_IS(r, SPECTRE)
|
||||
#define ASICREV_IS_SPOOKY(r) ASICREV_IS(r, SPOOKY)
|
||||
#define ASICREV_IS_KALINDI(r) ASICREV_IS(r, KALINDI)
|
||||
#define ASICREV_IS_KALINDI_GODAVARI(r) ASICREV_IS(r, GODAVARI)
|
||||
|
||||
#define ASICREV_IS_ICELAND_M(r) ASICREV_IS(r, ICELAND)
|
||||
#define ASICREV_IS_TONGA_P(r) ASICREV_IS(r, TONGA)
|
||||
#define ASICREV_IS_FIJI_P(r) ASICREV_IS(r, FIJI)
|
||||
|
||||
#define ASICREV_IS_POLARIS10_P(r) ASICREV_IS(r, POLARIS10)
|
||||
#define ASICREV_IS_POLARIS11_M(r) ASICREV_IS(r, POLARIS11)
|
||||
#define ASICREV_IS_POLARIS12_V(r) ASICREV_IS(r, POLARIS12)
|
||||
#define ASICREV_IS_VEGAM_P(r) ASICREV_IS(r, VEGAM)
|
||||
|
||||
#define ASICREV_IS_CARRIZO(r) ASICREV_IS(r, CARRIZO)
|
||||
#define ASICREV_IS_CARRIZO_BRISTOL(r) ASICREV_IS(r, BRISTOL)
|
||||
#define ASICREV_IS_STONEY(r) ASICREV_IS(r, STONEY)
|
||||
|
||||
#define ASICREV_IS_VEGA10_M(r) ASICREV_IS(r, VEGA10)
|
||||
#define ASICREV_IS_VEGA10_P(r) ASICREV_IS(r, VEGA10)
|
||||
#define ASICREV_IS_VEGA12_P(r) ASICREV_IS(r, VEGA12)
|
||||
#define ASICREV_IS_VEGA12_p(r) ASICREV_IS(r, VEGA12)
|
||||
#define ASICREV_IS_VEGA20_P(r) ASICREV_IS(r, VEGA20)
|
||||
|
||||
#define ASICREV_IS_RAVEN(r) ASICREV_IS(r, RAVEN)
|
||||
#define ASICREV_IS_RAVEN2(r) ASICREV_IS(r, RAVEN2)
|
||||
#define ASICREV_IS_RENOIR(r) ASICREV_IS(r, RENOIR)
|
||||
|
||||
#define ASICREV_IS_NAVI10_P(r) ASICREV_IS(r, NAVI10)
|
||||
|
||||
#define ASICREV_IS_NAVI12_P(r) ASICREV_IS(r, NAVI12)
|
||||
|
||||
#define ASICREV_IS_NAVI14_M(r) ASICREV_IS(r, NAVI14)
|
||||
|
||||
#define ASICREV_IS_NAVI21_M(r) ASICREV_IS(r, NAVI21)
|
||||
|
||||
#define ASICREV_IS_NAVI22_P(r) ASICREV_IS(r, NAVI22)
|
||||
|
||||
#define ASICREV_IS_NAVI23_P(r) ASICREV_IS(r, NAVI23)
|
||||
|
||||
#define ASICREV_IS_NAVI24_P(r) ASICREV_IS(r, NAVI24)
|
||||
|
||||
#define ASICREV_IS_VANGOGH(r) ASICREV_IS(r, VANGOGH)
|
||||
|
||||
#define ASICREV_IS_NAVI31_P(r) ASICREV_IS(r, NAVI31)
|
||||
#define ASICREV_IS_NAVI32_P(r) ASICREV_IS(r, NAVI32)
|
||||
#define ASICREV_IS_NAVI33_P(r) ASICREV_IS(r, NAVI33)
|
||||
#define ASICREV_IS_GFX1150(r) ASICREV_IS(r, GFX1150)
|
||||
#define ASICREV_IS_GFX1151(r) ASICREV_IS(r, GFX1151)
|
||||
#define ASICREV_IS_GFX1152(r) ASICREV_IS(r, GFX1152)
|
||||
#define ASICREV_IS_GFX1153(r) ASICREV_IS(r, GFX1153)
|
||||
#define ASICREV_IS_PHOENIX(r) ASICREV_IS(r, PHOENIX)
|
||||
#define ASICREV_IS_PHOENIX2(r) ASICREV_IS(r, PHOENIX2)
|
||||
#define ASICREV_IS_HAWK_POINT1(r) ASICREV_IS(r, HAWK_POINT1)
|
||||
#define ASICREV_IS_HAWK_POINT2(r) ASICREV_IS(r, HAWK_POINT2)
|
||||
|
||||
#define ASICREV_IS_REMBRANDT(r) ASICREV_IS(r, REMBRANDT)
|
||||
#define ASICREV_IS_RAPHAEL(r) ASICREV_IS(r, RAPHAEL)
|
||||
#define ASICREV_IS_MENDOCINO(r) ASICREV_IS(r, MENDOCINO)
|
||||
|
||||
#define ASICREV_IS_GFX1200(r) ASICREV_IS(r, GFX1200)
|
||||
|
||||
#endif // _AMDGPU_ASIC_ADDR_H
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2022 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
#if !defined (__GFX10_GB_REG_H__)
|
||||
#define __GFX10_GB_REG_H__
|
||||
|
||||
/*
|
||||
* gfx10_gb_reg.h
|
||||
*
|
||||
* Register Spec Release: 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
//
|
||||
// Make sure the necessary endian defines are there.
|
||||
//
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
#else
|
||||
#error "BIGENDIAN_CPU or LITTLEENDIAN_CPU must be defined"
|
||||
#endif
|
||||
|
||||
union GB_ADDR_CONFIG_GFX10
|
||||
{
|
||||
struct
|
||||
{
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
unsigned int NUM_PIPES : 3;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int NUM_PKRS : 3;
|
||||
unsigned int : 21;
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
unsigned int : 21;
|
||||
unsigned int NUM_PKRS : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int NUM_PIPES : 3;
|
||||
#endif
|
||||
} bitfields, bits;
|
||||
unsigned int u32All;
|
||||
int i32All;
|
||||
float f32All;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2022 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
#if !defined (__GFX11_GB_REG_H__)
|
||||
#define __GFX11_GB_REG_H__
|
||||
|
||||
/*
|
||||
* gfx11_gb_reg.h
|
||||
*
|
||||
* Register Spec Release: 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
//
|
||||
// Make sure the necessary endian defines are there.
|
||||
//
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
#else
|
||||
#error "BIGENDIAN_CPU or LITTLEENDIAN_CPU must be defined"
|
||||
#endif
|
||||
|
||||
union GB_ADDR_CONFIG_GFX11
|
||||
{
|
||||
struct
|
||||
{
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
unsigned int NUM_PIPES : 3;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int NUM_PKRS : 3;
|
||||
unsigned int : 8;
|
||||
unsigned int NUM_SHADER_ENGINES : 2;
|
||||
unsigned int : 5;
|
||||
unsigned int NUM_RB_PER_SE : 2;
|
||||
unsigned int : 4;
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
unsigned int : 4;
|
||||
unsigned int NUM_RB_PER_SE : 2;
|
||||
unsigned int : 5;
|
||||
unsigned int NUM_SHADER_ENGINES : 2;
|
||||
unsigned int : 8;
|
||||
unsigned int NUM_PKRS : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int NUM_PIPES : 3;
|
||||
#endif
|
||||
} bitfields, bits;
|
||||
unsigned int u32All;
|
||||
int i32All;
|
||||
float f32All;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2023 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
#if !defined (__GFX12_GB_REG_H__)
|
||||
#define __GFX12_GB_REG_H__
|
||||
|
||||
/*
|
||||
* gfx12_gb_reg.h
|
||||
*
|
||||
* Register Spec Release: 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
//
|
||||
// Make sure the necessary endian defines are there.
|
||||
//
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
#else
|
||||
#error "BIGENDIAN_CPU or LITTLEENDIAN_CPU must be defined"
|
||||
#endif
|
||||
|
||||
union GB_ADDR_CONFIG_GFX12 {
|
||||
struct {
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
unsigned int NUM_PIPES : 3;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int NUM_PKRS : 3;
|
||||
unsigned int : 8;
|
||||
unsigned int NUM_SHADER_ENGINES : 4;
|
||||
unsigned int : 3;
|
||||
unsigned int NUM_RB_PER_SE : 2;
|
||||
unsigned int : 4;
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
unsigned int : 4;
|
||||
unsigned int NUM_RB_PER_SE : 2;
|
||||
unsigned int : 3;
|
||||
unsigned int NUM_SHADER_ENGINES : 4;
|
||||
unsigned int : 8;
|
||||
unsigned int NUM_PKRS : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int NUM_PIPES : 3;
|
||||
#endif
|
||||
} bitfields, bits;
|
||||
unsigned int u32All;
|
||||
int i32All;
|
||||
float f32All;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2022 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
#if !defined (__GFX9_GB_REG_H__)
|
||||
#define __GFX9_GB_REG_H__
|
||||
|
||||
/*
|
||||
* gfx9_gb_reg.h
|
||||
*
|
||||
* Register Spec Release: 1.0
|
||||
*
|
||||
*/
|
||||
|
||||
//
|
||||
// Make sure the necessary endian defines are there.
|
||||
//
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
#else
|
||||
#error "BIGENDIAN_CPU or LITTLEENDIAN_CPU must be defined"
|
||||
#endif
|
||||
|
||||
union GB_ADDR_CONFIG_GFX9 {
|
||||
struct {
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
unsigned int NUM_PIPES : 3;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int BANK_INTERLEAVE_SIZE : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int NUM_BANKS : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int SHADER_ENGINE_TILE_SIZE : 3;
|
||||
unsigned int NUM_SHADER_ENGINES : 2;
|
||||
unsigned int NUM_GPUS : 3;
|
||||
unsigned int MULTI_GPU_TILE_SIZE : 2;
|
||||
unsigned int NUM_RB_PER_SE : 2;
|
||||
unsigned int ROW_SIZE : 2;
|
||||
unsigned int NUM_LOWER_PIPES : 1;
|
||||
unsigned int SE_ENABLE : 1;
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
unsigned int SE_ENABLE : 1;
|
||||
unsigned int NUM_LOWER_PIPES : 1;
|
||||
unsigned int ROW_SIZE : 2;
|
||||
unsigned int NUM_RB_PER_SE : 2;
|
||||
unsigned int MULTI_GPU_TILE_SIZE : 2;
|
||||
unsigned int NUM_GPUS : 3;
|
||||
unsigned int NUM_SHADER_ENGINES : 2;
|
||||
unsigned int SHADER_ENGINE_TILE_SIZE : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int NUM_BANKS : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int BANK_INTERLEAVE_SIZE : 3;
|
||||
unsigned int MAX_COMPRESSED_FRAGS : 2;
|
||||
unsigned int PIPE_INTERLEAVE_SIZE : 3;
|
||||
unsigned int NUM_PIPES : 3;
|
||||
#endif
|
||||
} bitfields, bits;
|
||||
unsigned int u32All;
|
||||
signed int i32All;
|
||||
float f32All;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
#if !defined (__SI_GB_REG_H__)
|
||||
#define __SI_GB_REG_H__
|
||||
|
||||
/*****************************************************************************************************************
|
||||
*
|
||||
* si_gb_reg.h
|
||||
*
|
||||
* Register Spec Release: Chip Spec 0.28
|
||||
*
|
||||
*****************************************************************************************************************/
|
||||
|
||||
//
|
||||
// Make sure the necessary endian defines are there.
|
||||
//
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
#else
|
||||
#error "BIGENDIAN_CPU or LITTLEENDIAN_CPU must be defined"
|
||||
#endif
|
||||
|
||||
/*
|
||||
* GB_ADDR_CONFIG struct
|
||||
*/
|
||||
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
|
||||
typedef struct _GB_ADDR_CONFIG_T {
|
||||
unsigned int num_pipes : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int pipe_interleave_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int bank_interleave_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int num_shader_engines : 2;
|
||||
unsigned int : 2;
|
||||
unsigned int shader_engine_tile_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int num_gpus : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int multi_gpu_tile_size : 2;
|
||||
unsigned int : 2;
|
||||
unsigned int row_size : 2;
|
||||
unsigned int num_lower_pipes : 1;
|
||||
unsigned int : 1;
|
||||
} GB_ADDR_CONFIG_T;
|
||||
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
|
||||
typedef struct _GB_ADDR_CONFIG_T {
|
||||
unsigned int : 1;
|
||||
unsigned int num_lower_pipes : 1;
|
||||
unsigned int row_size : 2;
|
||||
unsigned int : 2;
|
||||
unsigned int multi_gpu_tile_size : 2;
|
||||
unsigned int : 1;
|
||||
unsigned int num_gpus : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int shader_engine_tile_size : 3;
|
||||
unsigned int : 2;
|
||||
unsigned int num_shader_engines : 2;
|
||||
unsigned int : 1;
|
||||
unsigned int bank_interleave_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int pipe_interleave_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int num_pipes : 3;
|
||||
} GB_ADDR_CONFIG_T;
|
||||
|
||||
#endif
|
||||
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
|
||||
typedef struct _GB_ADDR_CONFIG_N {
|
||||
unsigned int num_pipes : 3;
|
||||
unsigned int pipe_interleave_size : 3;
|
||||
unsigned int max_compressed_frags : 2;
|
||||
unsigned int bank_interleave_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int num_banks : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int shader_engine_tile_size : 3;
|
||||
unsigned int num_shader_engines : 2;
|
||||
unsigned int num_gpus : 3;
|
||||
unsigned int multi_gpu_tile_size : 2;
|
||||
unsigned int num_rb_per_se : 2;
|
||||
unsigned int row_size : 2;
|
||||
unsigned int num_lower_pipes : 1;
|
||||
unsigned int se_enable : 1;
|
||||
} GB_ADDR_CONFIG_N;
|
||||
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
|
||||
typedef struct _GB_ADDR_CONFIG_N {
|
||||
unsigned int se_enable : 1;
|
||||
unsigned int num_lower_pipes : 1;
|
||||
unsigned int row_size : 2;
|
||||
unsigned int num_rb_per_se : 2;
|
||||
unsigned int multi_gpu_tile_size : 2;
|
||||
unsigned int num_gpus : 3;
|
||||
unsigned int num_shader_engines : 2;
|
||||
unsigned int shader_engine_tile_size : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int num_banks : 3;
|
||||
unsigned int : 1;
|
||||
unsigned int bank_interleave_size : 3;
|
||||
unsigned int max_compressed_frags : 2;
|
||||
unsigned int pipe_interleave_size : 3;
|
||||
unsigned int num_pipes : 3;
|
||||
} GB_ADDR_CONFIG_N;
|
||||
|
||||
#endif
|
||||
|
||||
typedef union {
|
||||
unsigned int val : 32;
|
||||
GB_ADDR_CONFIG_T f;
|
||||
GB_ADDR_CONFIG_N n;
|
||||
} GB_ADDR_CONFIG;
|
||||
|
||||
#if defined(LITTLEENDIAN_CPU)
|
||||
|
||||
typedef struct _GB_TILE_MODE_T {
|
||||
unsigned int micro_tile_mode : 2;
|
||||
unsigned int array_mode : 4;
|
||||
unsigned int pipe_config : 5;
|
||||
unsigned int tile_split : 3;
|
||||
unsigned int bank_width : 2;
|
||||
unsigned int bank_height : 2;
|
||||
unsigned int macro_tile_aspect : 2;
|
||||
unsigned int num_banks : 2;
|
||||
unsigned int micro_tile_mode_new : 3;
|
||||
unsigned int sample_split : 2;
|
||||
unsigned int alt_pipe_config : 5;
|
||||
} GB_TILE_MODE_T;
|
||||
|
||||
typedef struct _GB_MACROTILE_MODE_T {
|
||||
unsigned int bank_width : 2;
|
||||
unsigned int bank_height : 2;
|
||||
unsigned int macro_tile_aspect : 2;
|
||||
unsigned int num_banks : 2;
|
||||
unsigned int alt_bank_height : 2;
|
||||
unsigned int alt_macro_tile_aspect : 2;
|
||||
unsigned int alt_num_banks : 2;
|
||||
unsigned int : 18;
|
||||
} GB_MACROTILE_MODE_T;
|
||||
|
||||
#elif defined(BIGENDIAN_CPU)
|
||||
|
||||
typedef struct _GB_TILE_MODE_T {
|
||||
unsigned int alt_pipe_config : 5;
|
||||
unsigned int sample_split : 2;
|
||||
unsigned int micro_tile_mode_new : 3;
|
||||
unsigned int num_banks : 2;
|
||||
unsigned int macro_tile_aspect : 2;
|
||||
unsigned int bank_height : 2;
|
||||
unsigned int bank_width : 2;
|
||||
unsigned int tile_split : 3;
|
||||
unsigned int pipe_config : 5;
|
||||
unsigned int array_mode : 4;
|
||||
unsigned int micro_tile_mode : 2;
|
||||
} GB_TILE_MODE_T;
|
||||
|
||||
typedef struct _GB_MACROTILE_MODE_T {
|
||||
unsigned int : 18;
|
||||
unsigned int alt_num_banks : 2;
|
||||
unsigned int alt_macro_tile_aspect : 2;
|
||||
unsigned int alt_bank_height : 2;
|
||||
unsigned int num_banks : 2;
|
||||
unsigned int macro_tile_aspect : 2;
|
||||
unsigned int bank_height : 2;
|
||||
unsigned int bank_width : 2;
|
||||
} GB_MACROTILE_MODE_T;
|
||||
|
||||
#endif
|
||||
|
||||
typedef union {
|
||||
unsigned int val : 32;
|
||||
GB_TILE_MODE_T f;
|
||||
} GB_TILE_MODE;
|
||||
|
||||
typedef union {
|
||||
unsigned int val : 32;
|
||||
GB_MACROTILE_MODE_T f;
|
||||
} GB_MACROTILE_MODE;
|
||||
|
||||
#endif
|
||||
|
||||
+1187
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,262 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2022 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrelemlib.h
|
||||
* @brief Contains the class for element/pixel related functions.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __ELEM_LIB_H__
|
||||
#define __ELEM_LIB_H__
|
||||
|
||||
#include "addrinterface.h"
|
||||
#include "addrobject.h"
|
||||
#include "addrcommon.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
class Lib;
|
||||
|
||||
// The masks for property bits within the Properties INT_32
|
||||
union ComponentFlags
|
||||
{
|
||||
struct
|
||||
{
|
||||
UINT_32 byteAligned : 1; ///< all components are byte aligned
|
||||
UINT_32 exportNorm : 1; ///< components support R6xx NORM compression
|
||||
UINT_32 floatComp : 1; ///< there is at least one floating point component
|
||||
};
|
||||
|
||||
UINT_32 value;
|
||||
};
|
||||
|
||||
// Copy from legacy lib's NumberType
|
||||
enum NumberType
|
||||
{
|
||||
// The following number types have the range [-1..1]
|
||||
ADDR_NO_NUMBER, // This component doesn't exist and has no default value
|
||||
ADDR_EPSILON, // Force component value to integer 0x00000001
|
||||
ADDR_ZERO, // Force component value to integer 0x00000000
|
||||
ADDR_ONE, // Force component value to floating point 1.0
|
||||
// Above values don't have any bits per component (keep ADDR_ONE the last of these)
|
||||
|
||||
ADDR_UNORM, // Unsigned normalized (repeating fraction) full precision
|
||||
ADDR_SNORM, // Signed normalized (repeating fraction) full precision
|
||||
ADDR_GAMMA, // Gamma-corrected, full precision
|
||||
|
||||
ADDR_UNORM_R5XXRB, // Unsigned normalized (repeating fraction) for r5xx RB
|
||||
ADDR_SNORM_R5XXRB, // Signed normalized (repeating fraction) for r5xx RB
|
||||
ADDR_GAMMA_R5XXRB, // Gamma-corrected for r5xx RB (note: unnormalized value)
|
||||
ADDR_UNORM_R5XXBC, // Unsigned normalized (repeating fraction) for r5xx BC
|
||||
ADDR_SNORM_R5XXBC, // Signed normalized (repeating fraction) for r5xx BC
|
||||
ADDR_GAMMA_R5XXBC, // Gamma-corrected for r5xx BC (note: unnormalized value)
|
||||
|
||||
ADDR_UNORM_R6XX, // Unsigned normalized (repeating fraction) for R6xx
|
||||
ADDR_UNORM_R6XXDB, // Unorms for 24-bit depth: one value differs from ADDR_UNORM_R6XX
|
||||
ADDR_SNORM_R6XX, // Signed normalized (repeating fraction) for R6xx
|
||||
ADDR_GAMMA8_R6XX, // Gamma-corrected for r6xx
|
||||
ADDR_GAMMA8_R7XX_TP, // Gamma-corrected for r7xx TP 12bit unorm 8.4.
|
||||
|
||||
ADDR_U4FLOATC, // Unsigned float: 4-bit exponent, bias=15, no NaN, clamp [0..1]
|
||||
ADDR_GAMMA_4SEG, // Gamma-corrected, four segment approximation
|
||||
ADDR_U0FIXED, // Unsigned 0.N-bit fixed point
|
||||
|
||||
// The following number types have large ranges (LEAVE ADDR_USCALED first or fix Finish routine)
|
||||
ADDR_USCALED, // Unsigned integer converted to/from floating point
|
||||
ADDR_SSCALED, // Signed integer converted to/from floating point
|
||||
ADDR_USCALED_R5XXRB, // Unsigned integer to/from floating point for r5xx RB
|
||||
ADDR_SSCALED_R5XXRB, // Signed integer to/from floating point for r5xx RB
|
||||
ADDR_UINT_BITS, // Keep in unsigned integer form, clamped to specified range
|
||||
ADDR_SINT_BITS, // Keep in signed integer form, clamped to specified range
|
||||
ADDR_UINTBITS, // @@ remove Keep in unsigned integer form, use modulus to reduce bits
|
||||
ADDR_SINTBITS, // @@ remove Keep in signed integer form, use modulus to reduce bits
|
||||
|
||||
// The following number types and ADDR_U4FLOATC have exponents
|
||||
// (LEAVE ADDR_S8FLOAT first or fix Finish routine)
|
||||
ADDR_S8FLOAT, // Signed floating point with 8-bit exponent, bias=127
|
||||
ADDR_S8FLOAT32, // 32-bit IEEE float, passes through NaN values
|
||||
ADDR_S5FLOAT, // Signed floating point with 5-bit exponent, bias=15
|
||||
ADDR_S5FLOATM, // Signed floating point with 5-bit exponent, bias=15, no NaN/Inf
|
||||
ADDR_U5FLOAT, // Signed floating point with 5-bit exponent, bias=15
|
||||
ADDR_U3FLOATM, // Unsigned floating point with 3-bit exponent, bias=3
|
||||
|
||||
ADDR_S5FIXED, // Signed 5.N-bit fixed point, with rounding
|
||||
|
||||
ADDR_END_NUMBER // Used for range comparisons
|
||||
};
|
||||
|
||||
// Copy from legacy lib's AddrElement
|
||||
enum ElemMode
|
||||
{
|
||||
// These formats allow both packing an unpacking
|
||||
ADDR_ROUND_BY_HALF, // add 1/2 and truncate when packing this element
|
||||
ADDR_ROUND_TRUNCATE, // truncate toward 0 for sign/mag, else toward neg
|
||||
ADDR_ROUND_DITHER, // Pack by dithering -- requires (x,y) position
|
||||
|
||||
// These formats only allow unpacking, no packing
|
||||
ADDR_UNCOMPRESSED, // Elements are not compressed: one data element per pixel/texel
|
||||
ADDR_EXPANDED, // Elements are split up and stored in multiple data elements
|
||||
ADDR_PACKED_STD, // Elements are compressed into ExpandX by ExpandY data elements
|
||||
ADDR_PACKED_REV, // Like ADDR_PACKED, but X order of pixels is reverved
|
||||
ADDR_PACKED_GBGR, // Elements are compressed 4:2:2 in G1B_G0R order (high to low)
|
||||
ADDR_PACKED_BGRG, // Elements are compressed 4:2:2 in BG1_RG0 order (high to low)
|
||||
ADDR_PACKED_BC1, // Each data element is uncompressed to a 4x4 pixel/texel array
|
||||
ADDR_PACKED_BC2, // Each data element is uncompressed to a 4x4 pixel/texel array
|
||||
ADDR_PACKED_BC3, // Each data element is uncompressed to a 4x4 pixel/texel array
|
||||
ADDR_PACKED_BC4, // Each data element is uncompressed to a 4x4 pixel/texel array
|
||||
ADDR_PACKED_BC5, // Each data element is uncompressed to a 4x4 pixel/texel array
|
||||
ADDR_PACKED_ETC2_64BPP, // ETC2 formats that use 64bpp to represent each 4x4 block
|
||||
ADDR_PACKED_ETC2_128BPP, // ETC2 formats that use 128bpp to represent each 4x4 block
|
||||
ADDR_PACKED_ASTC, // Various ASTC formats, all are 128bpp with varying block sizes
|
||||
|
||||
// These formats provide various kinds of compression
|
||||
ADDR_ZPLANE_R5XX, // Compressed Zplane using r5xx architecture format
|
||||
ADDR_ZPLANE_R6XX, // Compressed Zplane using r6xx architecture format
|
||||
//@@ Fill in the compression modes
|
||||
|
||||
ADDR_END_ELEMENT // Used for range comparisons
|
||||
};
|
||||
|
||||
enum DepthPlanarType
|
||||
{
|
||||
ADDR_DEPTH_PLANAR_NONE = 0, // No plane z/stencl
|
||||
ADDR_DEPTH_PLANAR_R600 = 1, // R600 z and stencil planes are store within a tile
|
||||
ADDR_DEPTH_PLANAR_R800 = 2, // R800 has separate z and stencil planes
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* PixelFormatInfo
|
||||
*
|
||||
* @brief
|
||||
* Per component info
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
struct PixelFormatInfo
|
||||
{
|
||||
UINT_32 compBit[4];
|
||||
NumberType numType[4];
|
||||
UINT_32 compStart[4];
|
||||
ElemMode elemMode;
|
||||
UINT_32 comps; ///< Number of components
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief This class contains asic indepentent element related attributes and operations
|
||||
****************************************************************************************************
|
||||
*/
|
||||
class ElemLib : public Object
|
||||
{
|
||||
protected:
|
||||
ElemLib(Lib* pAddrLib);
|
||||
|
||||
public:
|
||||
|
||||
/// Makes this class virtual
|
||||
virtual ~ElemLib();
|
||||
|
||||
static ElemLib* Create(
|
||||
const Lib* pAddrLib);
|
||||
|
||||
/// The implementation is only for R6xx/R7xx, so make it virtual in case we need for R8xx
|
||||
BOOL_32 PixGetExportNorm(
|
||||
AddrColorFormat colorFmt,
|
||||
AddrSurfaceNumber numberFmt, AddrSurfaceSwap swap) const;
|
||||
|
||||
/// Below method are asic independent, so make them just static.
|
||||
/// Remove static if we need different operation in hwl.
|
||||
|
||||
VOID Flt32ToDepthPixel(
|
||||
AddrDepthFormat format, const ADDR_FLT_32 comps[2], UINT_8 *pPixel) const;
|
||||
|
||||
VOID Flt32ToColorPixel(
|
||||
AddrColorFormat format, AddrSurfaceNumber surfNum, AddrSurfaceSwap surfSwap,
|
||||
const ADDR_FLT_32 comps[4], UINT_8 *pPixel) const;
|
||||
|
||||
static VOID Flt32sToInt32s(
|
||||
ADDR_FLT_32 value, UINT_32 bits, NumberType numberType, UINT_32* pResult);
|
||||
|
||||
static VOID Int32sToPixel(
|
||||
UINT_32 numComps, UINT_32* pComps, UINT_32* pCompBits, UINT_32* pCompStart,
|
||||
ComponentFlags properties, UINT_32 resultBits, UINT_8* pPixel);
|
||||
|
||||
VOID PixGetColorCompInfo(
|
||||
AddrColorFormat format, AddrSurfaceNumber number, AddrSurfaceSwap swap,
|
||||
PixelFormatInfo* pInfo) const;
|
||||
|
||||
VOID PixGetDepthCompInfo(
|
||||
AddrDepthFormat format, PixelFormatInfo* pInfo) const;
|
||||
|
||||
UINT_32 GetBitsPerPixel(
|
||||
AddrFormat format, ElemMode* pElemMode = NULL,
|
||||
UINT_32* pExpandX = NULL, UINT_32* pExpandY = NULL, UINT_32* pBitsUnused = NULL);
|
||||
|
||||
static VOID SetClearComps(
|
||||
ADDR_FLT_32 comps[4], BOOL_32 clearColor, BOOL_32 float32);
|
||||
|
||||
VOID AdjustSurfaceInfo(
|
||||
ElemMode elemMode, UINT_32 expandX, UINT_32 expandY,
|
||||
UINT_32* pBpp, UINT_32* pBasePitch, UINT_32* pWidth, UINT_32* pHeight);
|
||||
|
||||
VOID RestoreSurfaceInfo(
|
||||
ElemMode elemMode, UINT_32 expandX, UINT_32 expandY,
|
||||
UINT_32* pBpp, UINT_32* pWidth, UINT_32* pHeight);
|
||||
|
||||
/// Checks if depth and stencil are planar inside a tile
|
||||
BOOL_32 IsDepthStencilTilePlanar()
|
||||
{
|
||||
return (m_depthPlanarType == ADDR_DEPTH_PLANAR_R600) ? TRUE : FALSE;
|
||||
}
|
||||
|
||||
/// Sets m_configFlags, copied from AddrLib
|
||||
VOID SetConfigFlags(ConfigFlags flags)
|
||||
{
|
||||
m_configFlags = flags;
|
||||
}
|
||||
|
||||
static BOOL_32 IsCompressed(AddrFormat format);
|
||||
static BOOL_32 IsBlockCompressed(AddrFormat format);
|
||||
static BOOL_32 IsExpand3x(AddrFormat format);
|
||||
static BOOL_32 IsMacroPixelPacked(AddrFormat format);
|
||||
|
||||
protected:
|
||||
|
||||
static VOID GetCompBits(
|
||||
UINT_32 c0, UINT_32 c1, UINT_32 c2, UINT_32 c3,
|
||||
PixelFormatInfo* pInfo,
|
||||
ElemMode elemMode = ADDR_ROUND_BY_HALF);
|
||||
|
||||
static VOID GetCompType(
|
||||
AddrColorFormat format, AddrSurfaceNumber numType,
|
||||
PixelFormatInfo* pInfo);
|
||||
|
||||
static VOID GetCompSwap(
|
||||
AddrSurfaceSwap swap, PixelFormatInfo* pInfo);
|
||||
|
||||
static VOID SwapComps(
|
||||
UINT_32 c0, UINT_32 c1, PixelFormatInfo* pInfo);
|
||||
|
||||
private:
|
||||
|
||||
UINT_32 m_fp16ExportNorm; ///< If allow FP16 to be reported as EXPORT_NORM
|
||||
DepthPlanarType m_depthPlanarType;
|
||||
|
||||
ConfigFlags m_configFlags; ///< Copy of AddrLib's configFlags
|
||||
Addr::Lib* const m_pAddrLib; ///< Pointer to parent addrlib instance
|
||||
};
|
||||
|
||||
} //Addr
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,772 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrlib.cpp
|
||||
* @brief Contains the implementation for the Addr::Lib class.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#include "addrinterface.h"
|
||||
#include "addrlib.h"
|
||||
#include "addrcommon.h"
|
||||
|
||||
#if defined(__APPLE__)
|
||||
|
||||
UINT_32 div64_32(UINT_64 n, UINT_32 base)
|
||||
{
|
||||
UINT_64 rem = n;
|
||||
UINT_64 b = base;
|
||||
UINT_64 res, d = 1;
|
||||
UINT_32 high = rem >> 32;
|
||||
|
||||
res = 0;
|
||||
if (high >= base)
|
||||
{
|
||||
high /= base;
|
||||
res = (UINT_64) high << 32;
|
||||
rem -= (UINT_64) (high * base) << 32;
|
||||
}
|
||||
|
||||
while (((INT_64)b > 0) && (b < rem))
|
||||
{
|
||||
b = b + b;
|
||||
d = d + d;
|
||||
}
|
||||
|
||||
do
|
||||
{
|
||||
if (rem >= b)
|
||||
{
|
||||
rem -= b;
|
||||
res += d;
|
||||
}
|
||||
b >>= 1;
|
||||
d >>= 1;
|
||||
} while (d);
|
||||
|
||||
n = res;
|
||||
return rem;
|
||||
}
|
||||
|
||||
extern "C"
|
||||
UINT_32 __umoddi3(UINT_64 n, UINT_32 base)
|
||||
{
|
||||
return div64_32(n, base);
|
||||
}
|
||||
|
||||
#endif // __APPLE__
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Constructor/Destructor
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::Lib
|
||||
*
|
||||
* @brief
|
||||
* Constructor for the AddrLib class
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Lib::Lib() :
|
||||
m_chipFamily(ADDR_CHIP_FAMILY_IVLD),
|
||||
m_chipRevision(0),
|
||||
m_version(ADDRLIB_VERSION),
|
||||
m_pipes(0),
|
||||
m_banks(0),
|
||||
m_pipeInterleaveBytes(0),
|
||||
m_rowSize(0),
|
||||
m_minPitchAlignPixels(1),
|
||||
m_maxSamples(8),
|
||||
m_maxBaseAlign(0),
|
||||
m_maxMetaBaseAlign(0),
|
||||
m_pElemLib(NULL)
|
||||
{
|
||||
m_configFlags.value = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::Lib
|
||||
*
|
||||
* @brief
|
||||
* Constructor for the AddrLib class with hClient as parameter
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Lib::Lib(const Client* pClient) :
|
||||
Object(pClient),
|
||||
m_chipFamily(ADDR_CHIP_FAMILY_IVLD),
|
||||
m_chipRevision(0),
|
||||
m_version(ADDRLIB_VERSION),
|
||||
m_pipes(0),
|
||||
m_banks(0),
|
||||
m_pipeInterleaveBytes(0),
|
||||
m_rowSize(0),
|
||||
m_minPitchAlignPixels(1),
|
||||
m_maxSamples(8),
|
||||
m_maxBaseAlign(0),
|
||||
m_maxMetaBaseAlign(0),
|
||||
m_pElemLib(NULL)
|
||||
{
|
||||
m_configFlags.value = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::~AddrLib
|
||||
*
|
||||
* @brief
|
||||
* Destructor for the AddrLib class
|
||||
*
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Lib::~Lib()
|
||||
{
|
||||
if (m_pElemLib)
|
||||
{
|
||||
delete m_pElemLib;
|
||||
m_pElemLib = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Initialization/Helper
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::Create
|
||||
*
|
||||
* @brief
|
||||
* Creates and initializes AddrLib object.
|
||||
*
|
||||
* @return
|
||||
* ADDR_E_RETURNCODE
|
||||
****************************************************************************************************
|
||||
*/
|
||||
ADDR_E_RETURNCODE Lib::Create(
|
||||
const ADDR_CREATE_INPUT* pCreateIn, ///< [in] pointer to ADDR_CREATE_INPUT
|
||||
ADDR_CREATE_OUTPUT* pCreateOut) ///< [out] pointer to ADDR_CREATE_OUTPUT
|
||||
{
|
||||
Lib* pLib = NULL;
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
if (pCreateIn->createFlags.fillSizeFields == TRUE)
|
||||
{
|
||||
if ((pCreateIn->size != sizeof(ADDR_CREATE_INPUT)) ||
|
||||
(pCreateOut->size != sizeof(ADDR_CREATE_OUTPUT)))
|
||||
{
|
||||
returnCode = ADDR_PARAMSIZEMISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
#if DEBUG
|
||||
ApplyDebugPrinters(pCreateIn->callbacks.debugPrint, pCreateIn->hClient);
|
||||
#endif
|
||||
|
||||
if ((returnCode == ADDR_OK) &&
|
||||
(pCreateIn->callbacks.allocSysMem != NULL) &&
|
||||
(pCreateIn->callbacks.freeSysMem != NULL))
|
||||
{
|
||||
Client client = {
|
||||
pCreateIn->hClient,
|
||||
pCreateIn->callbacks
|
||||
};
|
||||
|
||||
switch (pCreateIn->chipEngine)
|
||||
{
|
||||
case CIASICIDGFXENGINE_SOUTHERNISLAND:
|
||||
switch (pCreateIn->chipFamily)
|
||||
{
|
||||
case FAMILY_SI:
|
||||
pLib = SiHwlInit(&client);
|
||||
break;
|
||||
case FAMILY_CI:
|
||||
case FAMILY_KV: // CI based fusion
|
||||
case FAMILY_VI:
|
||||
case FAMILY_CZ: // VI based fusion
|
||||
pLib = CiHwlInit(&client);
|
||||
break;
|
||||
default:
|
||||
ADDR_ASSERT_ALWAYS();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case CIASICIDGFXENGINE_ARCTICISLAND:
|
||||
switch (pCreateIn->chipFamily)
|
||||
{
|
||||
case FAMILY_AI:
|
||||
case FAMILY_RV:
|
||||
pLib = Gfx9HwlInit(&client);
|
||||
break;
|
||||
case FAMILY_NV:
|
||||
case FAMILY_VGH:
|
||||
case FAMILY_RMB:
|
||||
case FAMILY_RPL:
|
||||
case FAMILY_MDN:
|
||||
pLib = Gfx10HwlInit(&client);
|
||||
break;
|
||||
case FAMILY_NV3:
|
||||
case FAMILY_GFX1150:
|
||||
case FAMILY_PHX:
|
||||
pLib = Gfx11HwlInit(&client);
|
||||
break;
|
||||
case FAMILY_GFX12:
|
||||
pLib = Gfx12HwlInit(&client);
|
||||
break;
|
||||
default:
|
||||
ADDR_ASSERT_ALWAYS();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
ADDR_ASSERT_ALWAYS();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if(pLib == NULL)
|
||||
{
|
||||
returnCode = ADDR_OUTOFMEMORY;
|
||||
}
|
||||
if (pLib != NULL)
|
||||
{
|
||||
BOOL_32 initValid;
|
||||
|
||||
// Pass createFlags to configFlags first since these flags may be overwritten
|
||||
pLib->m_configFlags.noCubeMipSlicesPad = pCreateIn->createFlags.noCubeMipSlicesPad;
|
||||
pLib->m_configFlags.fillSizeFields = pCreateIn->createFlags.fillSizeFields;
|
||||
pLib->m_configFlags.useTileIndex = pCreateIn->createFlags.useTileIndex;
|
||||
pLib->m_configFlags.useCombinedSwizzle = pCreateIn->createFlags.useCombinedSwizzle;
|
||||
pLib->m_configFlags.checkLast2DLevel = pCreateIn->createFlags.checkLast2DLevel;
|
||||
pLib->m_configFlags.useHtileSliceAlign = pCreateIn->createFlags.useHtileSliceAlign;
|
||||
pLib->m_configFlags.allowLargeThickTile = pCreateIn->createFlags.allowLargeThickTile;
|
||||
pLib->m_configFlags.forceDccAndTcCompat = pCreateIn->createFlags.forceDccAndTcCompat;
|
||||
pLib->m_configFlags.nonPower2MemConfig = pCreateIn->createFlags.nonPower2MemConfig;
|
||||
pLib->m_configFlags.enableAltTiling = pCreateIn->createFlags.enableAltTiling;
|
||||
pLib->m_configFlags.disableLinearOpt = FALSE;
|
||||
|
||||
pLib->SetChipFamily(pCreateIn->chipFamily, pCreateIn->chipRevision);
|
||||
|
||||
pLib->SetMinPitchAlignPixels(pCreateIn->minPitchAlignPixels);
|
||||
|
||||
// Global parameters initialized and remaining configFlags bits are set as well
|
||||
initValid = pLib->HwlInitGlobalParams(pCreateIn);
|
||||
|
||||
if (initValid)
|
||||
{
|
||||
pLib->m_pElemLib = ElemLib::Create(pLib);
|
||||
}
|
||||
else
|
||||
{
|
||||
pLib->m_pElemLib = NULL; // Don't go on allocating element lib
|
||||
returnCode = ADDR_INVALIDGBREGVALUES;
|
||||
}
|
||||
|
||||
if (pLib->m_pElemLib == NULL)
|
||||
{
|
||||
delete pLib;
|
||||
pLib = NULL;
|
||||
returnCode = ADDR_OUTOFMEMORY;
|
||||
ADDR_ASSERT_ALWAYS();
|
||||
}
|
||||
else
|
||||
{
|
||||
pLib->m_pElemLib->SetConfigFlags(pLib->m_configFlags);
|
||||
}
|
||||
}
|
||||
|
||||
pCreateOut->hLib = pLib;
|
||||
|
||||
if ((pLib != NULL) &&
|
||||
(returnCode == ADDR_OK))
|
||||
{
|
||||
pCreateOut->numEquations =
|
||||
pLib->HwlGetEquationTableInfo(&pCreateOut->pEquationTable);
|
||||
|
||||
pLib->SetMaxAlignments();
|
||||
|
||||
}
|
||||
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::SetChipFamily
|
||||
*
|
||||
* @brief
|
||||
* Convert familyID defined in atiid.h to ChipFamily and set m_chipFamily/m_chipRevision
|
||||
* @return
|
||||
* N/A
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID Lib::SetChipFamily(
|
||||
UINT_32 uChipFamily, ///< [in] chip family defined in atiih.h
|
||||
UINT_32 uChipRevision) ///< [in] chip revision defined in "asic_family"_id.h
|
||||
{
|
||||
ChipFamily family = HwlConvertChipFamily(uChipFamily, uChipRevision);
|
||||
|
||||
ADDR_ASSERT(family != ADDR_CHIP_FAMILY_IVLD);
|
||||
|
||||
m_chipFamily = family;
|
||||
m_chipRevision = uChipRevision;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::SetMinPitchAlignPixels
|
||||
*
|
||||
* @brief
|
||||
* Set m_minPitchAlignPixels with input param
|
||||
*
|
||||
* @return
|
||||
* N/A
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID Lib::SetMinPitchAlignPixels(
|
||||
UINT_32 minPitchAlignPixels) ///< [in] minmum pitch alignment in pixels
|
||||
{
|
||||
m_minPitchAlignPixels = (minPitchAlignPixels == 0) ? 1 : minPitchAlignPixels;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::SetMaxAlignments
|
||||
*
|
||||
* @brief
|
||||
* Set max alignments
|
||||
*
|
||||
* @return
|
||||
* N/A
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID Lib::SetMaxAlignments()
|
||||
{
|
||||
m_maxBaseAlign = HwlComputeMaxBaseAlignments();
|
||||
m_maxMetaBaseAlign = HwlComputeMaxMetaBaseAlignments();
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::GetLib
|
||||
*
|
||||
* @brief
|
||||
* Get AddrLib pointer
|
||||
*
|
||||
* @return
|
||||
* An AddrLib class pointer
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Lib* Lib::GetLib(
|
||||
ADDR_HANDLE hLib) ///< [in] handle of ADDR_HANDLE
|
||||
{
|
||||
Lib* pLib = static_cast<Addr::Lib*>(hLib);
|
||||
#if DEBUG
|
||||
if (pLib != NULL)
|
||||
{
|
||||
pLib->SetDebugPrinters();
|
||||
}
|
||||
#endif
|
||||
return pLib;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::GetMaxAlignments
|
||||
*
|
||||
* @brief
|
||||
* Gets maximum alignments for data surface (include FMask)
|
||||
*
|
||||
* @return
|
||||
* ADDR_E_RETURNCODE
|
||||
****************************************************************************************************
|
||||
*/
|
||||
ADDR_E_RETURNCODE Lib::GetMaxAlignments(
|
||||
ADDR_GET_MAX_ALIGNMENTS_OUTPUT* pOut ///< [out] output structure
|
||||
) const
|
||||
{
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
if (GetFillSizeFieldsFlags() == TRUE)
|
||||
{
|
||||
if (pOut->size != sizeof(ADDR_GET_MAX_ALIGNMENTS_OUTPUT))
|
||||
{
|
||||
returnCode = ADDR_PARAMSIZEMISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
if (returnCode == ADDR_OK)
|
||||
{
|
||||
if (m_maxBaseAlign != 0)
|
||||
{
|
||||
pOut->baseAlign = m_maxBaseAlign;
|
||||
}
|
||||
else
|
||||
{
|
||||
returnCode = ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
}
|
||||
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::GetMaxMetaAlignments
|
||||
*
|
||||
* @brief
|
||||
* Gets maximum alignments for metadata (CMask, DCC and HTile)
|
||||
*
|
||||
* @return
|
||||
* ADDR_E_RETURNCODE
|
||||
****************************************************************************************************
|
||||
*/
|
||||
ADDR_E_RETURNCODE Lib::GetMaxMetaAlignments(
|
||||
ADDR_GET_MAX_ALIGNMENTS_OUTPUT* pOut ///< [out] output structure
|
||||
) const
|
||||
{
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
if (GetFillSizeFieldsFlags() == TRUE)
|
||||
{
|
||||
if (pOut->size != sizeof(ADDR_GET_MAX_ALIGNMENTS_OUTPUT))
|
||||
{
|
||||
returnCode = ADDR_PARAMSIZEMISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
if (returnCode == ADDR_OK)
|
||||
{
|
||||
if (m_maxMetaBaseAlign != 0)
|
||||
{
|
||||
pOut->baseAlign = m_maxMetaBaseAlign;
|
||||
}
|
||||
else
|
||||
{
|
||||
returnCode = ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
}
|
||||
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::Bits2Number
|
||||
*
|
||||
* @brief
|
||||
* Cat a array of binary bit to a number
|
||||
*
|
||||
* @return
|
||||
* The number combined with the array of bits
|
||||
****************************************************************************************************
|
||||
*/
|
||||
UINT_32 Lib::Bits2Number(
|
||||
UINT_32 bitNum, ///< [in] how many bits
|
||||
...) ///< [in] varaible bits value starting from MSB
|
||||
{
|
||||
UINT_32 number = 0;
|
||||
UINT_32 i;
|
||||
va_list bits_ptr;
|
||||
|
||||
va_start(bits_ptr, bitNum);
|
||||
|
||||
for(i = 0; i < bitNum; i++)
|
||||
{
|
||||
number |= va_arg(bits_ptr, UINT_32);
|
||||
number <<= 1;
|
||||
}
|
||||
|
||||
number >>= 1;
|
||||
|
||||
va_end(bits_ptr);
|
||||
|
||||
return number;
|
||||
}
|
||||
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
// Element lib
|
||||
////////////////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::Flt32ToColorPixel
|
||||
*
|
||||
* @brief
|
||||
* Convert a FLT_32 value to a depth/stencil pixel value
|
||||
* @return
|
||||
* ADDR_E_RETURNCODE
|
||||
****************************************************************************************************
|
||||
*/
|
||||
ADDR_E_RETURNCODE Lib::Flt32ToDepthPixel(
|
||||
const ELEM_FLT32TODEPTHPIXEL_INPUT* pIn,
|
||||
ELEM_FLT32TODEPTHPIXEL_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
if (GetFillSizeFieldsFlags() == TRUE)
|
||||
{
|
||||
if ((pIn->size != sizeof(ELEM_FLT32TODEPTHPIXEL_INPUT)) ||
|
||||
(pOut->size != sizeof(ELEM_FLT32TODEPTHPIXEL_OUTPUT)))
|
||||
{
|
||||
returnCode = ADDR_PARAMSIZEMISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
if (returnCode == ADDR_OK)
|
||||
{
|
||||
GetElemLib()->Flt32ToDepthPixel(pIn->format, pIn->comps, pOut->pPixel);
|
||||
|
||||
UINT_32 depthBase = 0;
|
||||
UINT_32 stencilBase = 0;
|
||||
UINT_32 depthBits = 0;
|
||||
UINT_32 stencilBits = 0;
|
||||
|
||||
switch (pIn->format)
|
||||
{
|
||||
case ADDR_DEPTH_16:
|
||||
depthBits = 16;
|
||||
break;
|
||||
case ADDR_DEPTH_X8_24:
|
||||
case ADDR_DEPTH_8_24:
|
||||
case ADDR_DEPTH_X8_24_FLOAT:
|
||||
case ADDR_DEPTH_8_24_FLOAT:
|
||||
depthBase = 8;
|
||||
depthBits = 24;
|
||||
stencilBits = 8;
|
||||
break;
|
||||
case ADDR_DEPTH_32_FLOAT:
|
||||
depthBits = 32;
|
||||
break;
|
||||
case ADDR_DEPTH_X24_8_32_FLOAT:
|
||||
depthBase = 8;
|
||||
depthBits = 32;
|
||||
stencilBits = 8;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
// Overwrite base since R800 has no "tileBase"
|
||||
if (GetElemLib()->IsDepthStencilTilePlanar() == FALSE)
|
||||
{
|
||||
depthBase = 0;
|
||||
stencilBase = 0;
|
||||
}
|
||||
|
||||
depthBase *= 64;
|
||||
stencilBase *= 64;
|
||||
|
||||
pOut->stencilBase = stencilBase;
|
||||
pOut->depthBase = depthBase;
|
||||
pOut->depthBits = depthBits;
|
||||
pOut->stencilBits = stencilBits;
|
||||
}
|
||||
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::Flt32ToColorPixel
|
||||
*
|
||||
* @brief
|
||||
* Convert a FLT_32 value to a red/green/blue/alpha pixel value
|
||||
* @return
|
||||
* ADDR_E_RETURNCODE
|
||||
****************************************************************************************************
|
||||
*/
|
||||
ADDR_E_RETURNCODE Lib::Flt32ToColorPixel(
|
||||
const ELEM_FLT32TOCOLORPIXEL_INPUT* pIn,
|
||||
ELEM_FLT32TOCOLORPIXEL_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
if (GetFillSizeFieldsFlags() == TRUE)
|
||||
{
|
||||
if ((pIn->size != sizeof(ELEM_FLT32TOCOLORPIXEL_INPUT)) ||
|
||||
(pOut->size != sizeof(ELEM_FLT32TOCOLORPIXEL_OUTPUT)))
|
||||
{
|
||||
returnCode = ADDR_PARAMSIZEMISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
if (returnCode == ADDR_OK)
|
||||
{
|
||||
GetElemLib()->Flt32ToColorPixel(pIn->format,
|
||||
pIn->surfNum,
|
||||
pIn->surfSwap,
|
||||
pIn->comps,
|
||||
pOut->pPixel);
|
||||
}
|
||||
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::GetExportNorm
|
||||
*
|
||||
* @brief
|
||||
* Check one format can be EXPORT_NUM
|
||||
* @return
|
||||
* TRUE if EXPORT_NORM can be used
|
||||
****************************************************************************************************
|
||||
*/
|
||||
BOOL_32 Lib::GetExportNorm(
|
||||
const ELEM_GETEXPORTNORM_INPUT* pIn) const
|
||||
{
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
BOOL_32 enabled = FALSE;
|
||||
|
||||
if (GetFillSizeFieldsFlags() == TRUE)
|
||||
{
|
||||
if (pIn->size != sizeof(ELEM_GETEXPORTNORM_INPUT))
|
||||
{
|
||||
returnCode = ADDR_PARAMSIZEMISMATCH;
|
||||
}
|
||||
}
|
||||
|
||||
if (returnCode == ADDR_OK)
|
||||
{
|
||||
enabled = GetElemLib()->PixGetExportNorm(pIn->format, pIn->num, pIn->swap);
|
||||
}
|
||||
|
||||
return enabled;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Lib::GetBpe
|
||||
*
|
||||
* @brief
|
||||
* Get bits-per-element for specified format
|
||||
* @return
|
||||
* bits-per-element of specified format
|
||||
****************************************************************************************************
|
||||
*/
|
||||
UINT_32 Lib::GetBpe(AddrFormat format) const
|
||||
{
|
||||
return GetElemLib()->GetBitsPerPixel(format);
|
||||
}
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* Lib::ComputeOffsetFromSwizzlePattern
|
||||
*
|
||||
* @brief
|
||||
* Compute offset from swizzle pattern
|
||||
*
|
||||
* @return
|
||||
* Offset
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
UINT_32 Lib::ComputeOffsetFromSwizzlePattern(
|
||||
const UINT_64* pPattern, ///< Swizzle pattern
|
||||
UINT_32 numBits, ///< Number of bits in pattern
|
||||
UINT_32 x, ///< x coord in pixel
|
||||
UINT_32 y, ///< y coord in pixel
|
||||
UINT_32 z, ///< z coord in slice
|
||||
UINT_32 s ///< sample id
|
||||
)
|
||||
{
|
||||
UINT_32 offset = 0;
|
||||
const ADDR_BIT_SETTING* pSwizzlePattern = reinterpret_cast<const ADDR_BIT_SETTING*>(pPattern);
|
||||
|
||||
for (UINT_32 i = 0; i < numBits; i++)
|
||||
{
|
||||
UINT_32 v = 0;
|
||||
|
||||
if (pSwizzlePattern[i].x != 0)
|
||||
{
|
||||
UINT_16 mask = pSwizzlePattern[i].x;
|
||||
UINT_32 xBits = x;
|
||||
|
||||
while (mask != 0)
|
||||
{
|
||||
if (mask & 1)
|
||||
{
|
||||
v ^= xBits & 1;
|
||||
}
|
||||
|
||||
xBits >>= 1;
|
||||
mask >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (pSwizzlePattern[i].y != 0)
|
||||
{
|
||||
UINT_16 mask = pSwizzlePattern[i].y;
|
||||
UINT_32 yBits = y;
|
||||
|
||||
while (mask != 0)
|
||||
{
|
||||
if (mask & 1)
|
||||
{
|
||||
v ^= yBits & 1;
|
||||
}
|
||||
|
||||
yBits >>= 1;
|
||||
mask >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (pSwizzlePattern[i].z != 0)
|
||||
{
|
||||
UINT_16 mask = pSwizzlePattern[i].z;
|
||||
UINT_32 zBits = z;
|
||||
|
||||
while (mask != 0)
|
||||
{
|
||||
if (mask & 1)
|
||||
{
|
||||
v ^= zBits & 1;
|
||||
}
|
||||
|
||||
zBits >>= 1;
|
||||
mask >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (pSwizzlePattern[i].s != 0)
|
||||
{
|
||||
UINT_16 mask = pSwizzlePattern[i].s;
|
||||
UINT_32 sBits = s;
|
||||
|
||||
while (mask != 0)
|
||||
{
|
||||
if (mask & 1)
|
||||
{
|
||||
v ^= sBits & 1;
|
||||
}
|
||||
|
||||
sBits >>= 1;
|
||||
mask >>= 1;
|
||||
}
|
||||
}
|
||||
|
||||
offset |= (v << i);
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
} // Addr
|
||||
+484
@@ -0,0 +1,484 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrlib.h
|
||||
* @brief Contains the Addr::Lib base class definition.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __ADDR_LIB_H__
|
||||
#define __ADDR_LIB_H__
|
||||
|
||||
#include "addrinterface.h"
|
||||
#include "addrtypes.h"
|
||||
#include "addrobject.h"
|
||||
#include "addrelemlib.h"
|
||||
|
||||
#include "amdgpu_asic_addr.h"
|
||||
|
||||
#ifndef CIASICIDGFXENGINE_SOUTHERNISLAND
|
||||
#define CIASICIDGFXENGINE_SOUTHERNISLAND 0x0000000A
|
||||
#endif
|
||||
|
||||
#ifndef CIASICIDGFXENGINE_ARCTICISLAND
|
||||
#define CIASICIDGFXENGINE_ARCTICISLAND 0x0000000D
|
||||
#endif
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Neutral enums that define pipeinterleave
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum PipeInterleave
|
||||
{
|
||||
ADDR_PIPEINTERLEAVE_256B = 256,
|
||||
ADDR_PIPEINTERLEAVE_512B = 512,
|
||||
ADDR_PIPEINTERLEAVE_1KB = 1024,
|
||||
ADDR_PIPEINTERLEAVE_2KB = 2048,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Neutral enums that define DRAM row size
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum RowSize
|
||||
{
|
||||
ADDR_ROWSIZE_1KB = 1024,
|
||||
ADDR_ROWSIZE_2KB = 2048,
|
||||
ADDR_ROWSIZE_4KB = 4096,
|
||||
ADDR_ROWSIZE_8KB = 8192,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Neutral enums that define bank interleave
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum BankInterleave
|
||||
{
|
||||
ADDR_BANKINTERLEAVE_1 = 1,
|
||||
ADDR_BANKINTERLEAVE_2 = 2,
|
||||
ADDR_BANKINTERLEAVE_4 = 4,
|
||||
ADDR_BANKINTERLEAVE_8 = 8,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Neutral enums that define shader engine tile size
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum ShaderEngineTileSize
|
||||
{
|
||||
ADDR_SE_TILESIZE_16 = 16,
|
||||
ADDR_SE_TILESIZE_32 = 32,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Neutral enums that define bank swap size
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum BankSwapSize
|
||||
{
|
||||
ADDR_BANKSWAP_128B = 128,
|
||||
ADDR_BANKSWAP_256B = 256,
|
||||
ADDR_BANKSWAP_512B = 512,
|
||||
ADDR_BANKSWAP_1KB = 1024,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define max compressed fragments config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum NumMaxCompressedFragmentsConfig
|
||||
{
|
||||
ADDR_CONFIG_1_MAX_COMPRESSED_FRAGMENTS = 0x00000000,
|
||||
ADDR_CONFIG_2_MAX_COMPRESSED_FRAGMENTS = 0x00000001,
|
||||
ADDR_CONFIG_4_MAX_COMPRESSED_FRAGMENTS = 0x00000002,
|
||||
ADDR_CONFIG_8_MAX_COMPRESSED_FRAGMENTS = 0x00000003,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define num pipes config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum NumPipesConfig
|
||||
{
|
||||
ADDR_CONFIG_1_PIPE = 0x00000000,
|
||||
ADDR_CONFIG_2_PIPE = 0x00000001,
|
||||
ADDR_CONFIG_4_PIPE = 0x00000002,
|
||||
ADDR_CONFIG_8_PIPE = 0x00000003,
|
||||
ADDR_CONFIG_16_PIPE = 0x00000004,
|
||||
ADDR_CONFIG_32_PIPE = 0x00000005,
|
||||
ADDR_CONFIG_64_PIPE = 0x00000006,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define num banks config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum NumBanksConfig
|
||||
{
|
||||
ADDR_CONFIG_1_BANK = 0x00000000,
|
||||
ADDR_CONFIG_2_BANK = 0x00000001,
|
||||
ADDR_CONFIG_4_BANK = 0x00000002,
|
||||
ADDR_CONFIG_8_BANK = 0x00000003,
|
||||
ADDR_CONFIG_16_BANK = 0x00000004,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define num rb per shader engine config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum NumRbPerShaderEngineConfig
|
||||
{
|
||||
ADDR_CONFIG_1_RB_PER_SHADER_ENGINE = 0x00000000,
|
||||
ADDR_CONFIG_2_RB_PER_SHADER_ENGINE = 0x00000001,
|
||||
ADDR_CONFIG_4_RB_PER_SHADER_ENGINE = 0x00000002,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define num shader engines config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum NumShaderEnginesConfig
|
||||
{
|
||||
ADDR_CONFIG_1_SHADER_ENGINE = 0x00000000,
|
||||
ADDR_CONFIG_2_SHADER_ENGINE = 0x00000001,
|
||||
ADDR_CONFIG_4_SHADER_ENGINE = 0x00000002,
|
||||
ADDR_CONFIG_8_SHADER_ENGINE = 0x00000003,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define pipe interleave size config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum PipeInterleaveSizeConfig
|
||||
{
|
||||
ADDR_CONFIG_PIPE_INTERLEAVE_256B = 0x00000000,
|
||||
ADDR_CONFIG_PIPE_INTERLEAVE_512B = 0x00000001,
|
||||
ADDR_CONFIG_PIPE_INTERLEAVE_1KB = 0x00000002,
|
||||
ADDR_CONFIG_PIPE_INTERLEAVE_2KB = 0x00000003,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define row size config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum RowSizeConfig
|
||||
{
|
||||
ADDR_CONFIG_1KB_ROW = 0x00000000,
|
||||
ADDR_CONFIG_2KB_ROW = 0x00000001,
|
||||
ADDR_CONFIG_4KB_ROW = 0x00000002,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define bank interleave size config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum BankInterleaveSizeConfig
|
||||
{
|
||||
ADDR_CONFIG_BANK_INTERLEAVE_1 = 0x00000000,
|
||||
ADDR_CONFIG_BANK_INTERLEAVE_2 = 0x00000001,
|
||||
ADDR_CONFIG_BANK_INTERLEAVE_4 = 0x00000002,
|
||||
ADDR_CONFIG_BANK_INTERLEAVE_8 = 0x00000003,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Enums that define engine tile size config
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum ShaderEngineTileSizeConfig
|
||||
{
|
||||
ADDR_CONFIG_SE_TILE_16 = 0x00000000,
|
||||
ADDR_CONFIG_SE_TILE_32 = 0x00000001,
|
||||
};
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief Bit setting for swizzle pattern
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
union ADDR_BIT_SETTING
|
||||
{
|
||||
struct
|
||||
{
|
||||
UINT_16 x;
|
||||
UINT_16 y;
|
||||
UINT_16 z;
|
||||
UINT_16 s;
|
||||
};
|
||||
UINT_64 value;
|
||||
};
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* InitBit
|
||||
*
|
||||
* @brief
|
||||
* Initialize bit setting value via a return value
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
#define InitBit(c, index) (1ull << ((c << 4) + index))
|
||||
|
||||
const UINT_64 X0 = InitBit(0, 0);
|
||||
const UINT_64 X1 = InitBit(0, 1);
|
||||
const UINT_64 X2 = InitBit(0, 2);
|
||||
const UINT_64 X3 = InitBit(0, 3);
|
||||
const UINT_64 X4 = InitBit(0, 4);
|
||||
const UINT_64 X5 = InitBit(0, 5);
|
||||
const UINT_64 X6 = InitBit(0, 6);
|
||||
const UINT_64 X7 = InitBit(0, 7);
|
||||
const UINT_64 X8 = InitBit(0, 8);
|
||||
const UINT_64 X9 = InitBit(0, 9);
|
||||
const UINT_64 X10 = InitBit(0, 10);
|
||||
const UINT_64 X11 = InitBit(0, 11);
|
||||
|
||||
const UINT_64 Y0 = InitBit(1, 0);
|
||||
const UINT_64 Y1 = InitBit(1, 1);
|
||||
const UINT_64 Y2 = InitBit(1, 2);
|
||||
const UINT_64 Y3 = InitBit(1, 3);
|
||||
const UINT_64 Y4 = InitBit(1, 4);
|
||||
const UINT_64 Y5 = InitBit(1, 5);
|
||||
const UINT_64 Y6 = InitBit(1, 6);
|
||||
const UINT_64 Y7 = InitBit(1, 7);
|
||||
const UINT_64 Y8 = InitBit(1, 8);
|
||||
const UINT_64 Y9 = InitBit(1, 9);
|
||||
const UINT_64 Y10 = InitBit(1, 10);
|
||||
const UINT_64 Y11 = InitBit(1, 11);
|
||||
|
||||
const UINT_64 Z0 = InitBit(2, 0);
|
||||
const UINT_64 Z1 = InitBit(2, 1);
|
||||
const UINT_64 Z2 = InitBit(2, 2);
|
||||
const UINT_64 Z3 = InitBit(2, 3);
|
||||
const UINT_64 Z4 = InitBit(2, 4);
|
||||
const UINT_64 Z5 = InitBit(2, 5);
|
||||
const UINT_64 Z6 = InitBit(2, 6);
|
||||
const UINT_64 Z7 = InitBit(2, 7);
|
||||
const UINT_64 Z8 = InitBit(2, 8);
|
||||
|
||||
const UINT_64 S0 = InitBit(3, 0);
|
||||
const UINT_64 S1 = InitBit(3, 1);
|
||||
const UINT_64 S2 = InitBit(3, 2);
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief This class contains asic independent address lib functionalities
|
||||
****************************************************************************************************
|
||||
*/
|
||||
class Lib : public Object
|
||||
{
|
||||
public:
|
||||
virtual ~Lib();
|
||||
|
||||
static ADDR_E_RETURNCODE Create(
|
||||
const ADDR_CREATE_INPUT* pCreateInfo, ADDR_CREATE_OUTPUT* pCreateOut);
|
||||
|
||||
/// Pair of Create
|
||||
VOID Destroy()
|
||||
{
|
||||
delete this;
|
||||
}
|
||||
|
||||
static Lib* GetLib(ADDR_HANDLE hLib);
|
||||
|
||||
/// Returns which version of addrlib functions should be used.
|
||||
virtual UINT_32 GetInterfaceVersion() const = 0;
|
||||
|
||||
/// Returns AddrLib version (from compiled binary instead include file)
|
||||
UINT_32 GetVersion()
|
||||
{
|
||||
return m_version;
|
||||
}
|
||||
|
||||
/// Returns asic chip family name defined by AddrLib
|
||||
ChipFamily GetChipFamily() const
|
||||
{
|
||||
return m_chipFamily;
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE Flt32ToDepthPixel(
|
||||
const ELEM_FLT32TODEPTHPIXEL_INPUT* pIn,
|
||||
ELEM_FLT32TODEPTHPIXEL_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE Flt32ToColorPixel(
|
||||
const ELEM_FLT32TOCOLORPIXEL_INPUT* pIn,
|
||||
ELEM_FLT32TOCOLORPIXEL_OUTPUT* pOut) const;
|
||||
|
||||
BOOL_32 GetExportNorm(const ELEM_GETEXPORTNORM_INPUT* pIn) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetMaxAlignments(ADDR_GET_MAX_ALIGNMENTS_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetMaxMetaAlignments(ADDR_GET_MAX_ALIGNMENTS_OUTPUT* pOut) const;
|
||||
|
||||
UINT_32 GetBpe(AddrFormat format) const;
|
||||
|
||||
|
||||
static UINT_32 ComputeOffsetFromSwizzlePattern(
|
||||
const UINT_64* pPattern,
|
||||
UINT_32 numBits,
|
||||
UINT_32 x,
|
||||
UINT_32 y,
|
||||
UINT_32 z,
|
||||
UINT_32 s);
|
||||
|
||||
protected:
|
||||
Lib(); // Constructor is protected
|
||||
Lib(const Client* pClient);
|
||||
|
||||
/// Pure virtual function to get max base alignments
|
||||
virtual UINT_32 HwlComputeMaxBaseAlignments() const = 0;
|
||||
|
||||
/// Gets maximum alignements for metadata
|
||||
virtual UINT_32 HwlComputeMaxMetaBaseAlignments() const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
VOID ValidBaseAlignments(UINT_32 alignment) const
|
||||
{
|
||||
#if DEBUG
|
||||
ADDR_ASSERT(alignment <= m_maxBaseAlign);
|
||||
#endif
|
||||
}
|
||||
|
||||
VOID ValidMetaBaseAlignments(UINT_32 metaAlignment) const
|
||||
{
|
||||
#if DEBUG
|
||||
ADDR_ASSERT(metaAlignment <= m_maxMetaBaseAlign);
|
||||
#endif
|
||||
}
|
||||
|
||||
static BOOL_32 IsTex1d(AddrResourceType resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_TEX_1D);
|
||||
}
|
||||
|
||||
static BOOL_32 IsTex2d(AddrResourceType resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_TEX_2D);
|
||||
}
|
||||
|
||||
static BOOL_32 IsTex3d(AddrResourceType resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_TEX_3D);
|
||||
}
|
||||
|
||||
//
|
||||
// Initialization
|
||||
//
|
||||
/// Pure Virtual function for Hwl computing internal global parameters from h/w registers
|
||||
virtual BOOL_32 HwlInitGlobalParams(const ADDR_CREATE_INPUT* pCreateIn) = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl converting chip family
|
||||
virtual ChipFamily HwlConvertChipFamily(UINT_32 uChipFamily, UINT_32 uChipRevision) = 0;
|
||||
|
||||
/// Get equation table pointer and number of equations
|
||||
virtual UINT_32 HwlGetEquationTableInfo(const ADDR_EQUATION** ppEquationTable) const
|
||||
{
|
||||
*ppEquationTable = NULL;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
//
|
||||
// Misc helper
|
||||
//
|
||||
static UINT_32 Bits2Number(UINT_32 bitNum, ...);
|
||||
|
||||
static UINT_32 GetNumFragments(UINT_32 numSamples, UINT_32 numFrags)
|
||||
{
|
||||
return (numFrags != 0) ? numFrags : Max(1u, numSamples);
|
||||
}
|
||||
|
||||
/// Returns pointer of ElemLib
|
||||
ElemLib* GetElemLib() const
|
||||
{
|
||||
return m_pElemLib;
|
||||
}
|
||||
|
||||
/// Returns fillSizeFields flag
|
||||
UINT_32 GetFillSizeFieldsFlags() const
|
||||
{
|
||||
return m_configFlags.fillSizeFields;
|
||||
}
|
||||
|
||||
private:
|
||||
// Disallow the copy constructor
|
||||
Lib(const Lib& a);
|
||||
|
||||
// Disallow the assignment operator
|
||||
Lib& operator=(const Lib& a);
|
||||
|
||||
VOID SetChipFamily(UINT_32 uChipFamily, UINT_32 uChipRevision);
|
||||
|
||||
VOID SetMinPitchAlignPixels(UINT_32 minPitchAlignPixels);
|
||||
|
||||
VOID SetMaxAlignments();
|
||||
|
||||
protected:
|
||||
ChipFamily m_chipFamily; ///< Chip family translated from the one in atiid.h
|
||||
|
||||
UINT_32 m_chipRevision; ///< Revision id from xxx_id.h
|
||||
|
||||
UINT_32 m_version; ///< Current version
|
||||
|
||||
//
|
||||
// Global parameters
|
||||
//
|
||||
ConfigFlags m_configFlags; ///< Global configuration flags. Note this is setup by
|
||||
/// AddrLib instead of Client except forceLinearAligned
|
||||
|
||||
UINT_32 m_pipes; ///< Number of pipes
|
||||
UINT_32 m_banks; ///< Number of banks
|
||||
/// For r800 this is MC_ARB_RAMCFG.NOOFBANK
|
||||
/// Keep it here to do default parameter calculation
|
||||
|
||||
UINT_32 m_pipeInterleaveBytes;
|
||||
///< Specifies the size of contiguous address space
|
||||
/// within each tiling pipe when making linear
|
||||
/// accesses. (Formerly Group Size)
|
||||
|
||||
UINT_32 m_rowSize; ///< DRAM row size, in bytes
|
||||
|
||||
UINT_32 m_minPitchAlignPixels; ///< Minimum pitch alignment in pixels
|
||||
UINT_32 m_maxSamples; ///< Max numSamples
|
||||
|
||||
UINT_32 m_maxBaseAlign; ///< Max base alignment for data surface
|
||||
UINT_32 m_maxMetaBaseAlign; ///< Max base alignment for metadata
|
||||
|
||||
private:
|
||||
ElemLib* m_pElemLib; ///< Element Lib pointer
|
||||
};
|
||||
|
||||
Lib* SiHwlInit (const Client* pClient);
|
||||
Lib* CiHwlInit (const Client* pClient);
|
||||
Lib* Gfx9HwlInit (const Client* pClient);
|
||||
Lib* Gfx10HwlInit(const Client* pClient);
|
||||
Lib* Gfx11HwlInit(const Client* pClient);
|
||||
Lib* Gfx12HwlInit(const Client* pClient);
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
+4057
File diff suppressed because it is too large.
Load diff
+533
@@ -0,0 +1,533 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrlib1.h
|
||||
* @brief Contains the Addr::V1::Lib class definition.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __ADDR_LIB1_H__
|
||||
#define __ADDR_LIB1_H__
|
||||
|
||||
#include "addrlib.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V1
|
||||
{
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Neutral enums that define bank swap size
|
||||
****************************************************************************************************
|
||||
*/
|
||||
enum SampleSplitSize
|
||||
{
|
||||
ADDR_SAMPLESPLIT_1KB = 1024,
|
||||
ADDR_SAMPLESPLIT_2KB = 2048,
|
||||
ADDR_SAMPLESPLIT_4KB = 4096,
|
||||
ADDR_SAMPLESPLIT_8KB = 8192,
|
||||
};
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief Flags for AddrTileMode
|
||||
****************************************************************************************************
|
||||
*/
|
||||
struct TileModeFlags
|
||||
{
|
||||
UINT_32 thickness : 4;
|
||||
UINT_32 isLinear : 1;
|
||||
UINT_32 isMicro : 1;
|
||||
UINT_32 isMacro : 1;
|
||||
UINT_32 isMacro3d : 1;
|
||||
UINT_32 isPrt : 1;
|
||||
UINT_32 isPrtNoRotation : 1;
|
||||
UINT_32 isBankSwapped : 1;
|
||||
};
|
||||
|
||||
static const UINT_32 Block64K = 0x10000;
|
||||
static const UINT_32 PrtTileSize = Block64K;
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief This class contains asic independent address lib functionalities
|
||||
****************************************************************************************************
|
||||
*/
|
||||
class Lib : public Addr::Lib
|
||||
{
|
||||
public:
|
||||
virtual ~Lib();
|
||||
|
||||
static Lib* GetLib(
|
||||
ADDR_HANDLE hLib);
|
||||
|
||||
virtual UINT_32 GetInterfaceVersion() const override
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// Returns tileIndex support
|
||||
BOOL_32 UseTileIndex(INT_32 index) const
|
||||
{
|
||||
return m_configFlags.useTileIndex && (index != TileIndexInvalid);
|
||||
}
|
||||
|
||||
/// Returns combined swizzle support
|
||||
BOOL_32 UseCombinedSwizzle() const
|
||||
{
|
||||
return m_configFlags.useCombinedSwizzle;
|
||||
}
|
||||
|
||||
//
|
||||
// Interface stubs
|
||||
//
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfo(
|
||||
const ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoord(
|
||||
const ADDR_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceCoordFromAddr(
|
||||
const ADDR_COMPUTE_SURFACE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSliceTileSwizzle(
|
||||
const ADDR_COMPUTE_SLICESWIZZLE_INPUT* pIn,
|
||||
ADDR_COMPUTE_SLICESWIZZLE_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ExtractBankPipeSwizzle(
|
||||
const ADDR_EXTRACT_BANKPIPE_SWIZZLE_INPUT* pIn,
|
||||
ADDR_EXTRACT_BANKPIPE_SWIZZLE_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE CombineBankPipeSwizzle(
|
||||
const ADDR_COMBINE_BANKPIPE_SWIZZLE_INPUT* pIn,
|
||||
ADDR_COMBINE_BANKPIPE_SWIZZLE_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeBaseSwizzle(
|
||||
const ADDR_COMPUTE_BASE_SWIZZLE_INPUT* pIn,
|
||||
ADDR_COMPUTE_BASE_SWIZZLE_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeFmaskInfo(
|
||||
const ADDR_COMPUTE_FMASK_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_FMASK_INFO_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeFmaskAddrFromCoord(
|
||||
const ADDR_COMPUTE_FMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_FMASK_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeFmaskCoordFromAddr(
|
||||
const ADDR_COMPUTE_FMASK_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR_COMPUTE_FMASK_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ConvertTileInfoToHW(
|
||||
const ADDR_CONVERT_TILEINFOTOHW_INPUT* pIn,
|
||||
ADDR_CONVERT_TILEINFOTOHW_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ConvertTileIndex(
|
||||
const ADDR_CONVERT_TILEINDEX_INPUT* pIn,
|
||||
ADDR_CONVERT_TILEINDEX_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetMacroModeIndex(
|
||||
const ADDR_GET_MACROMODEINDEX_INPUT* pIn,
|
||||
ADDR_GET_MACROMODEINDEX_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ConvertTileIndex1(
|
||||
const ADDR_CONVERT_TILEINDEX1_INPUT* pIn,
|
||||
ADDR_CONVERT_TILEINDEX_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetTileIndex(
|
||||
const ADDR_GET_TILEINDEX_INPUT* pIn,
|
||||
ADDR_GET_TILEINDEX_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeHtileInfo(
|
||||
const ADDR_COMPUTE_HTILE_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_HTILE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeCmaskInfo(
|
||||
const ADDR_COMPUTE_CMASK_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_CMASK_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeDccInfo(
|
||||
const ADDR_COMPUTE_DCCINFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_DCCINFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeHtileAddrFromCoord(
|
||||
const ADDR_COMPUTE_HTILE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeCmaskAddrFromCoord(
|
||||
const ADDR_COMPUTE_CMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_CMASK_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeHtileCoordFromAddr(
|
||||
const ADDR_COMPUTE_HTILE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR_COMPUTE_HTILE_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeCmaskCoordFromAddr(
|
||||
const ADDR_COMPUTE_CMASK_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR_COMPUTE_CMASK_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputePrtInfo(
|
||||
const ADDR_PRT_INFO_INPUT* pIn,
|
||||
ADDR_PRT_INFO_OUTPUT* pOut) const;
|
||||
protected:
|
||||
Lib(); // Constructor is protected
|
||||
Lib(const Client* pClient);
|
||||
|
||||
/// Pure Virtual function for Hwl computing surface info
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceInfo(
|
||||
const ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing surface address from coord
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceAddrFromCoord(
|
||||
const ADDR_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing surface coord from address
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceCoordFromAddr(
|
||||
const ADDR_COMPUTE_SURFACE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_COORDFROMADDR_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing surface tile swizzle
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSliceTileSwizzle(
|
||||
const ADDR_COMPUTE_SLICESWIZZLE_INPUT* pIn,
|
||||
ADDR_COMPUTE_SLICESWIZZLE_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl extracting bank/pipe swizzle from base256b
|
||||
virtual ADDR_E_RETURNCODE HwlExtractBankPipeSwizzle(
|
||||
const ADDR_EXTRACT_BANKPIPE_SWIZZLE_INPUT* pIn,
|
||||
ADDR_EXTRACT_BANKPIPE_SWIZZLE_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl combining bank/pipe swizzle
|
||||
virtual ADDR_E_RETURNCODE HwlCombineBankPipeSwizzle(
|
||||
UINT_32 bankSwizzle, UINT_32 pipeSwizzle, ADDR_TILEINFO* pTileInfo,
|
||||
UINT_64 baseAddr, UINT_32* pTileSwizzle) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing base swizzle
|
||||
virtual ADDR_E_RETURNCODE HwlComputeBaseSwizzle(
|
||||
const ADDR_COMPUTE_BASE_SWIZZLE_INPUT* pIn,
|
||||
ADDR_COMPUTE_BASE_SWIZZLE_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing HTILE base align
|
||||
virtual UINT_32 HwlComputeHtileBaseAlign(
|
||||
BOOL_32 isTcCompatible, BOOL_32 isLinear, ADDR_TILEINFO* pTileInfo) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing HTILE bpp
|
||||
virtual UINT_32 HwlComputeHtileBpp(
|
||||
BOOL_32 isWidth8, BOOL_32 isHeight8) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing HTILE bytes
|
||||
virtual UINT_64 HwlComputeHtileBytes(
|
||||
UINT_32 pitch, UINT_32 height, UINT_32 bpp,
|
||||
BOOL_32 isLinear, UINT_32 numSlices, UINT_64* pSliceBytes, UINT_32 baseAlign) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing FMASK info
|
||||
virtual ADDR_E_RETURNCODE HwlComputeFmaskInfo(
|
||||
const ADDR_COMPUTE_FMASK_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_FMASK_INFO_OUTPUT* pOut) = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl FMASK address from coord
|
||||
virtual ADDR_E_RETURNCODE HwlComputeFmaskAddrFromCoord(
|
||||
const ADDR_COMPUTE_FMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_FMASK_ADDRFROMCOORD_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl FMASK coord from address
|
||||
virtual ADDR_E_RETURNCODE HwlComputeFmaskCoordFromAddr(
|
||||
const ADDR_COMPUTE_FMASK_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR_COMPUTE_FMASK_COORDFROMADDR_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl convert tile info from real value to HW value
|
||||
virtual ADDR_E_RETURNCODE HwlConvertTileInfoToHW(
|
||||
const ADDR_CONVERT_TILEINFOTOHW_INPUT* pIn,
|
||||
ADDR_CONVERT_TILEINFOTOHW_OUTPUT* pOut) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl compute mipmap info
|
||||
virtual BOOL_32 HwlComputeMipLevel(
|
||||
ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl compute max cmask blockMax value
|
||||
virtual BOOL_32 HwlGetMaxCmaskBlockMax() const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl compute fmask bits
|
||||
virtual UINT_32 HwlComputeFmaskBits(
|
||||
const ADDR_COMPUTE_FMASK_INFO_INPUT* pIn,
|
||||
UINT_32* pNumSamples) const = 0;
|
||||
|
||||
/// Virtual function to get index (not pure then no need to implement this in all hwls
|
||||
virtual ADDR_E_RETURNCODE HwlGetTileIndex(
|
||||
const ADDR_GET_TILEINDEX_INPUT* pIn,
|
||||
ADDR_GET_TILEINDEX_OUTPUT* pOut) const
|
||||
{
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
/// Virtual function for Hwl to compute Dcc info
|
||||
virtual ADDR_E_RETURNCODE HwlComputeDccInfo(
|
||||
const ADDR_COMPUTE_DCCINFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_DCCINFO_OUTPUT* pOut) const
|
||||
{
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
/// Virtual function to get cmask address for tc compatible cmask
|
||||
virtual ADDR_E_RETURNCODE HwlComputeCmaskAddrFromCoord(
|
||||
const ADDR_COMPUTE_CMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_CMASK_ADDRFROMCOORD_OUTPUT* pOut) const
|
||||
{
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
/// Virtual function to get htile address for tc compatible htile
|
||||
virtual ADDR_E_RETURNCODE HwlComputeHtileAddrFromCoord(
|
||||
const ADDR_COMPUTE_HTILE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT* pOut) const
|
||||
{
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
// Compute attributes
|
||||
|
||||
// HTILE
|
||||
UINT_32 ComputeHtileInfo(
|
||||
ADDR_HTILE_FLAGS flags,
|
||||
UINT_32 pitchIn, UINT_32 heightIn, UINT_32 numSlices,
|
||||
BOOL_32 isLinear, BOOL_32 isWidth8, BOOL_32 isHeight8,
|
||||
ADDR_TILEINFO* pTileInfo,
|
||||
UINT_32* pPitchOut, UINT_32* pHeightOut, UINT_64* pHtileBytes,
|
||||
UINT_32* pMacroWidth = NULL, UINT_32* pMacroHeight = NULL,
|
||||
UINT_64* pSliceSize = NULL, UINT_32* pBaseAlign = NULL) const;
|
||||
|
||||
// CMASK
|
||||
ADDR_E_RETURNCODE ComputeCmaskInfo(
|
||||
ADDR_CMASK_FLAGS flags,
|
||||
UINT_32 pitchIn, UINT_32 heightIn, UINT_32 numSlices, BOOL_32 isLinear,
|
||||
ADDR_TILEINFO* pTileInfo, UINT_32* pPitchOut, UINT_32* pHeightOut, UINT_64* pCmaskBytes,
|
||||
UINT_32* pMacroWidth, UINT_32* pMacroHeight, UINT_64* pSliceSize = NULL,
|
||||
UINT_32* pBaseAlign = NULL, UINT_32* pBlockMax = NULL) const;
|
||||
|
||||
virtual VOID HwlComputeTileDataWidthAndHeightLinear(
|
||||
UINT_32* pMacroWidth, UINT_32* pMacroHeight,
|
||||
UINT_32 bpp, ADDR_TILEINFO* pTileInfo) const;
|
||||
|
||||
// CMASK & HTILE addressing
|
||||
virtual UINT_64 HwlComputeXmaskAddrFromCoord(
|
||||
UINT_32 pitch, UINT_32 height, UINT_32 x, UINT_32 y, UINT_32 slice,
|
||||
UINT_32 numSlices, UINT_32 factor, BOOL_32 isLinear, BOOL_32 isWidth8,
|
||||
BOOL_32 isHeight8, ADDR_TILEINFO* pTileInfo,
|
||||
UINT_32* bitPosition) const;
|
||||
|
||||
virtual VOID HwlComputeXmaskCoordFromAddr(
|
||||
UINT_64 addr, UINT_32 bitPosition, UINT_32 pitch, UINT_32 height, UINT_32 numSlices,
|
||||
UINT_32 factor, BOOL_32 isLinear, BOOL_32 isWidth8, BOOL_32 isHeight8,
|
||||
ADDR_TILEINFO* pTileInfo, UINT_32* pX, UINT_32* pY, UINT_32* pSlice) const;
|
||||
|
||||
// Surface mipmap
|
||||
VOID ComputeMipLevel(
|
||||
ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
|
||||
/// Pure Virtual function for Hwl to get macro tiled alignment info
|
||||
virtual BOOL_32 HwlGetAlignmentInfoMacroTiled(
|
||||
const ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
UINT_32* pPitchAlign, UINT_32* pHeightAlign, UINT_32* pSizeAlign) const = 0;
|
||||
|
||||
|
||||
virtual VOID HwlOverrideTileMode(ADDR_COMPUTE_SURFACE_INFO_INPUT* pInOut) const
|
||||
{
|
||||
// not supported in hwl layer
|
||||
}
|
||||
|
||||
virtual VOID HwlOptimizeTileMode(ADDR_COMPUTE_SURFACE_INFO_INPUT* pInOut) const
|
||||
{
|
||||
// not supported in hwl layer
|
||||
}
|
||||
|
||||
virtual VOID HwlSelectTileMode(ADDR_COMPUTE_SURFACE_INFO_INPUT* pInOut) const
|
||||
{
|
||||
// not supported in hwl layer
|
||||
}
|
||||
|
||||
AddrTileMode DegradeLargeThickTile(AddrTileMode tileMode, UINT_32 bpp) const;
|
||||
|
||||
VOID PadDimensions(
|
||||
AddrTileMode tileMode, UINT_32 bpp, ADDR_SURFACE_FLAGS flags,
|
||||
UINT_32 numSamples, ADDR_TILEINFO* pTileInfo, UINT_32 padDims, UINT_32 mipLevel,
|
||||
UINT_32* pPitch, UINT_32* pPitchAlign, UINT_32* pHeight, UINT_32 heightAlign,
|
||||
UINT_32* pSlices, UINT_32 sliceAlign) const;
|
||||
|
||||
virtual VOID HwlPadDimensions(
|
||||
AddrTileMode tileMode, UINT_32 bpp, ADDR_SURFACE_FLAGS flags,
|
||||
UINT_32 numSamples, ADDR_TILEINFO* pTileInfo, UINT_32 mipLevel,
|
||||
UINT_32* pPitch, UINT_32* pPitchAlign, UINT_32 height, UINT_32 heightAlign) const
|
||||
{
|
||||
}
|
||||
|
||||
//
|
||||
// Addressing shared for linear/1D tiling
|
||||
//
|
||||
UINT_64 ComputeSurfaceAddrFromCoordLinear(
|
||||
UINT_32 x, UINT_32 y, UINT_32 slice, UINT_32 sample,
|
||||
UINT_32 bpp, UINT_32 pitch, UINT_32 height, UINT_32 numSlices,
|
||||
UINT_32* pBitPosition) const;
|
||||
|
||||
VOID ComputeSurfaceCoordFromAddrLinear(
|
||||
UINT_64 addr, UINT_32 bitPosition, UINT_32 bpp,
|
||||
UINT_32 pitch, UINT_32 height, UINT_32 numSlices,
|
||||
UINT_32* pX, UINT_32* pY, UINT_32* pSlice, UINT_32* pSample) const;
|
||||
|
||||
VOID ComputeSurfaceCoordFromAddrMicroTiled(
|
||||
UINT_64 addr, UINT_32 bitPosition,
|
||||
UINT_32 bpp, UINT_32 pitch, UINT_32 height, UINT_32 numSamples,
|
||||
AddrTileMode tileMode, UINT_32 tileBase, UINT_32 compBits,
|
||||
UINT_32* pX, UINT_32* pY, UINT_32* pSlice, UINT_32* pSample,
|
||||
AddrTileType microTileType, BOOL_32 isDepthSampleOrder) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeMicroTileEquation(
|
||||
UINT_32 bpp, AddrTileMode tileMode,
|
||||
AddrTileType microTileType, ADDR_EQUATION* pEquation) const;
|
||||
|
||||
UINT_32 ComputePixelIndexWithinMicroTile(
|
||||
UINT_32 x, UINT_32 y, UINT_32 z,
|
||||
UINT_32 bpp, AddrTileMode tileMode, AddrTileType microTileType) const;
|
||||
|
||||
/// Pure Virtual function for Hwl computing coord from offset inside micro tile
|
||||
virtual VOID HwlComputePixelCoordFromOffset(
|
||||
UINT_32 offset, UINT_32 bpp, UINT_32 numSamples,
|
||||
AddrTileMode tileMode, UINT_32 tileBase, UINT_32 compBits,
|
||||
UINT_32* pX, UINT_32* pY, UINT_32* pSlice, UINT_32* pSample,
|
||||
AddrTileType microTileType, BOOL_32 isDepthSampleOrder) const = 0;
|
||||
|
||||
//
|
||||
// Addressing shared by all
|
||||
//
|
||||
virtual UINT_32 HwlGetPipes(
|
||||
const ADDR_TILEINFO* pTileInfo) const;
|
||||
|
||||
UINT_32 ComputePipeFromAddr(
|
||||
UINT_64 addr, UINT_32 numPipes) const;
|
||||
|
||||
virtual ADDR_E_RETURNCODE ComputePipeEquation(
|
||||
UINT_32 log2BytesPP, UINT_32 threshX, UINT_32 threshY, ADDR_TILEINFO* pTileInfo, ADDR_EQUATION* pEquation) const
|
||||
{
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
/// Pure Virtual function for Hwl computing pipe from coord
|
||||
virtual UINT_32 ComputePipeFromCoord(
|
||||
UINT_32 x, UINT_32 y, UINT_32 slice, AddrTileMode tileMode,
|
||||
UINT_32 pipeSwizzle, BOOL_32 flags, ADDR_TILEINFO* pTileInfo) const = 0;
|
||||
|
||||
/// Pure Virtual function for Hwl computing coord Y for 8 pipe cmask/htile
|
||||
virtual UINT_32 HwlComputeXmaskCoordYFrom8Pipe(
|
||||
UINT_32 pipe, UINT_32 x) const = 0;
|
||||
|
||||
//
|
||||
// Misc helper
|
||||
//
|
||||
static const TileModeFlags ModeFlags[ADDR_TM_COUNT];
|
||||
|
||||
static UINT_32 Thickness(
|
||||
AddrTileMode tileMode);
|
||||
|
||||
// Checking tile mode
|
||||
static BOOL_32 IsMacroTiled(AddrTileMode tileMode);
|
||||
static BOOL_32 IsMacro3dTiled(AddrTileMode tileMode);
|
||||
static BOOL_32 IsLinear(AddrTileMode tileMode);
|
||||
static BOOL_32 IsMicroTiled(AddrTileMode tileMode);
|
||||
static BOOL_32 IsPrtTileMode(AddrTileMode tileMode);
|
||||
static BOOL_32 IsPrtNoRotationTileMode(AddrTileMode tileMode);
|
||||
|
||||
/// Return TRUE if tile info is needed
|
||||
BOOL_32 UseTileInfo() const
|
||||
{
|
||||
return !m_configFlags.ignoreTileInfo;
|
||||
}
|
||||
|
||||
/// Adjusts pitch alignment for flipping surface
|
||||
VOID AdjustPitchAlignment(
|
||||
ADDR_SURFACE_FLAGS flags, UINT_32* pPitchAlign) const;
|
||||
|
||||
/// Overwrite tile config according to tile index
|
||||
virtual ADDR_E_RETURNCODE HwlSetupTileCfg(
|
||||
UINT_32 bpp, INT_32 index, INT_32 macroModeIndex,
|
||||
ADDR_TILEINFO* pInfo, AddrTileMode* mode = NULL, AddrTileType* type = NULL) const;
|
||||
|
||||
/// Overwrite macro tile config according to tile index
|
||||
virtual INT_32 HwlComputeMacroModeIndex(
|
||||
INT_32 index, ADDR_SURFACE_FLAGS flags, UINT_32 bpp, UINT_32 numSamples,
|
||||
ADDR_TILEINFO* pTileInfo, AddrTileMode *pTileMode = NULL, AddrTileType *pTileType = NULL
|
||||
) const
|
||||
{
|
||||
return TileIndexNoMacroIndex;
|
||||
}
|
||||
|
||||
/// Pre-handler of 3x pitch (96 bit) adjustment
|
||||
virtual UINT_32 HwlPreHandleBaseLvl3xPitch(
|
||||
const ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn, UINT_32 expPitch) const;
|
||||
/// Post-handler of 3x pitch adjustment
|
||||
virtual UINT_32 HwlPostHandleBaseLvl3xPitch(
|
||||
const ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn, UINT_32 expPitch) const;
|
||||
/// Check miplevel after surface adjustment
|
||||
ADDR_E_RETURNCODE PostComputeMipLevel(
|
||||
ADDR_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
/// Quad buffer stereo support, has its implementation in ind. layer
|
||||
VOID ComputeQbStereoInfo(
|
||||
ADDR_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
/// Pure virutual function to compute stereo bank swizzle for right eye
|
||||
virtual UINT_32 HwlComputeQbStereoRightSwizzle(
|
||||
ADDR_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const = 0;
|
||||
|
||||
VOID OptimizeTileMode(ADDR_COMPUTE_SURFACE_INFO_INPUT* pInOut) const;
|
||||
|
||||
/// Overwrite tile setting to PRT
|
||||
virtual VOID HwlSetPrtTileMode(ADDR_COMPUTE_SURFACE_INFO_INPUT* pInOut) const
|
||||
{
|
||||
}
|
||||
|
||||
static BOOL_32 DegradeTo1D(
|
||||
UINT_32 width, UINT_32 height,
|
||||
UINT_32 macroTilePitchAlign, UINT_32 macroTileHeightAlign);
|
||||
|
||||
private:
|
||||
// Disallow the copy constructor
|
||||
Lib(const Lib& a);
|
||||
|
||||
// Disallow the assignment operator
|
||||
Lib& operator=(const Lib& a);
|
||||
|
||||
UINT_32 ComputeCmaskBaseAlign(
|
||||
ADDR_CMASK_FLAGS flags, ADDR_TILEINFO* pTileInfo) const;
|
||||
|
||||
UINT_64 ComputeCmaskBytes(
|
||||
UINT_32 pitch, UINT_32 height, UINT_32 numSlices) const;
|
||||
|
||||
//
|
||||
// CMASK/HTILE shared methods
|
||||
//
|
||||
VOID ComputeTileDataWidthAndHeight(
|
||||
UINT_32 bpp, UINT_32 cacheBits, ADDR_TILEINFO* pTileInfo,
|
||||
UINT_32* pMacroWidth, UINT_32* pMacroHeight) const;
|
||||
|
||||
UINT_32 ComputeXmaskCoordYFromPipe(
|
||||
UINT_32 pipe, UINT_32 x) const;
|
||||
};
|
||||
|
||||
} // V1
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
|
||||
+2397
File diff suppressed because it is too large.
Load diff
+956
@@ -0,0 +1,956 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @file addrlib2.h
|
||||
* @brief Contains the Addr::V2::Lib class definition.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __ADDR2_LIB2_H__
|
||||
#define __ADDR2_LIB2_H__
|
||||
|
||||
#include "addrlib.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V2
|
||||
{
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief Flags for SwizzleModeTable
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
union SwizzleModeFlags
|
||||
{
|
||||
struct
|
||||
{
|
||||
// Swizzle mode
|
||||
UINT_32 isLinear : 1; // Linear
|
||||
|
||||
// Block size
|
||||
UINT_32 is256b : 1; // Block size is 256B
|
||||
UINT_32 is4kb : 1; // Block size is 4KB
|
||||
UINT_32 is64kb : 1; // Block size is 64KB
|
||||
UINT_32 isVar : 1; // Block size is variable
|
||||
|
||||
UINT_32 isZ : 1; // Z order swizzle mode
|
||||
UINT_32 isStd : 1; // Standard swizzle mode
|
||||
UINT_32 isDisp : 1; // Display swizzle mode
|
||||
UINT_32 isRot : 1; // Rotate swizzle mode
|
||||
|
||||
// XOR mode
|
||||
UINT_32 isXor : 1; // XOR after swizzle if set
|
||||
|
||||
UINT_32 isT : 1; // T mode
|
||||
|
||||
// GFX10
|
||||
UINT_32 isRtOpt : 1; // mode opt for render target
|
||||
|
||||
UINT_32 reserved : 20; // Reserved bits
|
||||
};
|
||||
|
||||
UINT_32 u32All;
|
||||
};
|
||||
|
||||
struct Dim2d
|
||||
{
|
||||
UINT_32 w;
|
||||
UINT_32 h;
|
||||
};
|
||||
|
||||
struct Dim3d
|
||||
{
|
||||
UINT_32 w;
|
||||
UINT_32 h;
|
||||
UINT_32 d;
|
||||
};
|
||||
|
||||
enum AddrSwSet
|
||||
{
|
||||
AddrSwSetZ = 1 << ADDR_SW_Z,
|
||||
AddrSwSetS = 1 << ADDR_SW_S,
|
||||
AddrSwSetD = 1 << ADDR_SW_D,
|
||||
AddrSwSetR = 1 << ADDR_SW_R,
|
||||
|
||||
AddrSwSetAll = AddrSwSetZ | AddrSwSetS | AddrSwSetD | AddrSwSetR,
|
||||
};
|
||||
|
||||
const UINT_32 Size256 = 256u;
|
||||
const UINT_32 Size4K = 4096u;
|
||||
const UINT_32 Size64K = 65536u;
|
||||
|
||||
const UINT_32 Log2Size256 = 8u;
|
||||
const UINT_32 Log2Size4K = 12u;
|
||||
const UINT_32 Log2Size64K = 16u;
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief Swizzle pattern information
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
// Accessed by index representing the logbase2 of (8bpp/16bpp/32bpp/64bpp/128bpp)
|
||||
// contains the indices which map to 2D arrays SW_PATTERN_NIBBLE[0-9] which contain sections of an index equation. They are dependant on pipe# and bpe #
|
||||
struct ADDR_SW_PATINFO
|
||||
{
|
||||
UINT_8 maxItemCount;
|
||||
UINT_8 nibble01Idx;
|
||||
UINT_16 nibble2Idx;
|
||||
UINT_16 nibble3Idx;
|
||||
UINT_8 nibble4Idx;
|
||||
};
|
||||
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief This class contains asic independent address lib functionalities
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
class Lib : public Addr::Lib
|
||||
{
|
||||
public:
|
||||
virtual ~Lib();
|
||||
|
||||
static Lib* GetLib(
|
||||
ADDR_HANDLE hLib);
|
||||
|
||||
virtual UINT_32 GetInterfaceVersion() const override
|
||||
{
|
||||
return 2;
|
||||
}
|
||||
//
|
||||
// Interface stubs
|
||||
//
|
||||
|
||||
// For data surface
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfo(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoord(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceCoordFromAddr(
|
||||
const ADDR2_COMPUTE_SURFACE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE CopyMemToSurface(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const;
|
||||
|
||||
ADDR_E_RETURNCODE CopySurfaceToMem(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const;
|
||||
|
||||
// For HTile
|
||||
ADDR_E_RETURNCODE ComputeHtileInfo(
|
||||
const ADDR2_COMPUTE_HTILE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeHtileAddrFromCoord(
|
||||
const ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeHtileCoordFromAddr(
|
||||
const ADDR2_COMPUTE_HTILE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_COORDFROMADDR_OUTPUT* pOut);
|
||||
|
||||
// For CMask
|
||||
ADDR_E_RETURNCODE ComputeCmaskInfo(
|
||||
const ADDR2_COMPUTE_CMASK_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeCmaskAddrFromCoord(
|
||||
const ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeCmaskCoordFromAddr(
|
||||
const ADDR2_COMPUTE_CMASK_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
// For FMask
|
||||
ADDR_E_RETURNCODE ComputeFmaskInfo(
|
||||
const ADDR2_COMPUTE_FMASK_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_FMASK_INFO_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeFmaskAddrFromCoord(
|
||||
const ADDR2_COMPUTE_FMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_FMASK_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeFmaskCoordFromAddr(
|
||||
const ADDR2_COMPUTE_FMASK_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_FMASK_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
// For DCC key
|
||||
ADDR_E_RETURNCODE ComputeDccInfo(
|
||||
const ADDR2_COMPUTE_DCCINFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCCINFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCC_ADDRFROMCOORD_OUTPUT* pOut);
|
||||
|
||||
// Misc
|
||||
ADDR_E_RETURNCODE ComputePipeBankXor(
|
||||
const ADDR2_COMPUTE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSlicePipeBankXor(
|
||||
const ADDR2_COMPUTE_SLICE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SLICE_PIPEBANKXOR_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSubResourceOffsetForSwizzlePattern(
|
||||
const ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeNonBlockCompressedView(
|
||||
const ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_INPUT* pIn,
|
||||
ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE Addr2GetPreferredSurfaceSetting(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetPossibleSwizzleModes(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const;
|
||||
|
||||
virtual BOOL_32 IsValidDisplaySwizzleMode(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE GetAllowedBlockSet(
|
||||
ADDR2_SWMODE_SET allowedSwModeSet,
|
||||
AddrResourceType rsrcType,
|
||||
ADDR2_BLOCK_SET* pAllowedBlockSet) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetAllowedSwSet(
|
||||
ADDR2_SWMODE_SET allowedSwModeSet,
|
||||
ADDR2_SWTYPE_SET* pAllowedSwSet) const;
|
||||
|
||||
protected:
|
||||
Lib(); // Constructor is protected
|
||||
Lib(const Client* pClient);
|
||||
|
||||
static const UINT_32 MaxNumOfBpp = 5;
|
||||
static const UINT_32 MaxNumOfBppCMask = 4;
|
||||
static const UINT_32 MaxNumOfAA = 4;
|
||||
|
||||
static const Dim2d Block256_2d[MaxNumOfBpp];
|
||||
static const Dim3d Block1K_3d[MaxNumOfBpp];
|
||||
|
||||
static const UINT_32 PrtAlignment = 64 * 1024;
|
||||
static const UINT_32 MaxMacroBits = 20;
|
||||
|
||||
static const UINT_32 MaxMipLevels = 16;
|
||||
|
||||
BOOL_32 IsValidSwMode(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return (m_swizzleModeTable[swizzleMode].u32All != 0);
|
||||
}
|
||||
|
||||
// Checking block size
|
||||
BOOL_32 IsBlock256b(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is256b;
|
||||
}
|
||||
|
||||
BOOL_32 IsBlock4kb(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is4kb;
|
||||
}
|
||||
|
||||
BOOL_32 IsBlock64kb(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is64kb;
|
||||
}
|
||||
|
||||
BOOL_32 IsBlockVariable(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isVar;
|
||||
}
|
||||
|
||||
// Checking swizzle mode
|
||||
BOOL_32 IsLinear(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isLinear;
|
||||
}
|
||||
|
||||
BOOL_32 IsRtOptSwizzle(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isRtOpt;
|
||||
}
|
||||
|
||||
BOOL_32 IsZOrderSwizzle(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isZ;
|
||||
}
|
||||
|
||||
BOOL_32 IsStandardSwizzle(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isStd;
|
||||
}
|
||||
|
||||
BOOL_32 IsDisplaySwizzle(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isDisp;
|
||||
}
|
||||
|
||||
BOOL_32 IsRotateSwizzle(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isRot;
|
||||
}
|
||||
|
||||
BOOL_32 IsStandardSwizzle(AddrResourceType resourceType, AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return HwlIsStandardSwizzle(resourceType, swizzleMode);
|
||||
}
|
||||
|
||||
BOOL_32 IsDisplaySwizzle(AddrResourceType resourceType, AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return HwlIsDisplaySwizzle(resourceType, swizzleMode);
|
||||
}
|
||||
|
||||
BOOL_32 IsXor(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isXor;
|
||||
}
|
||||
|
||||
BOOL_32 IsPrt(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isT;
|
||||
}
|
||||
|
||||
BOOL_32 IsNonPrtXor(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return (IsXor(swizzleMode) && (IsPrt(swizzleMode) == FALSE));
|
||||
}
|
||||
|
||||
// Checking resource type
|
||||
static BOOL_32 IsTex1d(AddrResourceType resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_TEX_1D);
|
||||
}
|
||||
|
||||
static BOOL_32 IsTex2d(AddrResourceType resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_TEX_2D);
|
||||
}
|
||||
|
||||
static BOOL_32 IsTex3d(AddrResourceType resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_TEX_3D);
|
||||
}
|
||||
|
||||
BOOL_32 IsThick(AddrResourceType resourceType, AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return HwlIsThick(resourceType, swizzleMode);
|
||||
}
|
||||
|
||||
BOOL_32 IsThin(AddrResourceType resourceType, AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return HwlIsThin(resourceType, swizzleMode);
|
||||
}
|
||||
|
||||
UINT_32 GetBlockSizeLog2(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
UINT_32 blockSizeLog2 = 0;
|
||||
|
||||
if (IsBlock256b(swizzleMode) || IsLinear(swizzleMode))
|
||||
{
|
||||
blockSizeLog2 = 8;
|
||||
}
|
||||
else if (IsBlock4kb(swizzleMode))
|
||||
{
|
||||
blockSizeLog2 = 12;
|
||||
}
|
||||
else if (IsBlock64kb(swizzleMode))
|
||||
{
|
||||
blockSizeLog2 = 16;
|
||||
}
|
||||
else if (IsBlockVariable(swizzleMode) && (m_blockVarSizeLog2 != 0))
|
||||
{
|
||||
blockSizeLog2 = m_blockVarSizeLog2;
|
||||
}
|
||||
else
|
||||
{
|
||||
ADDR_ASSERT_ALWAYS();
|
||||
}
|
||||
|
||||
return blockSizeLog2;
|
||||
}
|
||||
|
||||
UINT_32 GetBlockSize(AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return (1 << GetBlockSizeLog2(swizzleMode));
|
||||
}
|
||||
|
||||
static UINT_32 GetFmaskBpp(UINT_32 sample, UINT_32 frag)
|
||||
{
|
||||
sample = (sample == 0) ? 1 : sample;
|
||||
frag = (frag == 0) ? sample : frag;
|
||||
|
||||
UINT_32 fmaskBpp = Log2(frag);
|
||||
|
||||
if (sample > frag)
|
||||
{
|
||||
fmaskBpp++;
|
||||
}
|
||||
|
||||
if (fmaskBpp == 3)
|
||||
{
|
||||
fmaskBpp = 4;
|
||||
}
|
||||
|
||||
fmaskBpp = Max(8u, fmaskBpp * sample);
|
||||
|
||||
return fmaskBpp;
|
||||
}
|
||||
|
||||
virtual BOOL_32 HwlIsStandardSwizzle(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
virtual BOOL_32 HwlIsDisplaySwizzle(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
virtual BOOL_32 HwlIsThin(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
virtual BOOL_32 HwlIsThick(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeHtileInfo(
|
||||
const ADDR2_COMPUTE_HTILE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeCmaskInfo(
|
||||
const ADDR2_COMPUTE_CMASK_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeDccInfo(
|
||||
const ADDR2_COMPUTE_DCCINFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCCINFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlSupportComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn)
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual VOID HwlComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCC_ADDRFROMCOORD_OUTPUT* pOut)
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeCmaskAddrFromCoord(
|
||||
const ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_OUTPUT* pOut)
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeHtileAddrFromCoord(
|
||||
const ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT* pOut)
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeHtileCoordFromAddr(
|
||||
const ADDR2_COMPUTE_HTILE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_COORDFROMADDR_OUTPUT* pOut)
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeBlock256Equation(
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
UINT_32 elementBytesLog2,
|
||||
ADDR_EQUATION* pEquation) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeThinEquation(
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
UINT_32 elementBytesLog2,
|
||||
ADDR_EQUATION* pEquation) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeThickEquation(
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
UINT_32 elementBytesLog2,
|
||||
ADDR_EQUATION* pEquation) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual UINT_32 HwlGetEquationIndex(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_INVALID_EQUATION_INDEX;
|
||||
}
|
||||
|
||||
UINT_32 GetEquationIndex(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
return HwlGetEquationIndex(pIn, pOut);
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputePipeBankXor(
|
||||
const ADDR2_COMPUTE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSlicePipeBankXor(
|
||||
const ADDR2_COMPUTE_SLICE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SLICE_PIPEBANKXOR_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSubResourceOffsetForSwizzlePattern(
|
||||
const ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeNonBlockCompressedView(
|
||||
const ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_INPUT* pIn,
|
||||
ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlGetPreferredSurfaceSetting(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlGetPossibleSwizzleModes(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlGetAllowedBlockSet(
|
||||
ADDR2_SWMODE_SET allowedSwModeSet,
|
||||
AddrResourceType rsrcType,
|
||||
ADDR2_BLOCK_SET* pAllowedBlockSet) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlGetAllowedSwSet(
|
||||
ADDR2_SWMODE_SET allowedSwModeSet,
|
||||
ADDR2_SWTYPE_SET* pAllowedSwSet) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceInfoSanityCheck(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceInfoTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceInfoLinear(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceAddrFromCoordTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlCopyMemToSurface(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlCopySurfaceToMem(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE ComputeBlock256Equation(
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
UINT_32 elementBytesLog2,
|
||||
ADDR_EQUATION* pEquation) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeThinEquation(
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
UINT_32 elementBytesLog2,
|
||||
ADDR_EQUATION* pEquation) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeThickEquation(
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
UINT_32 elementBytesLog2,
|
||||
ADDR_EQUATION* pEquation) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoSanityCheck(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoLinear(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE CopyLinearSurface(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount,
|
||||
bool surfaceIsDst) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordLinear(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceCoordFromAddrLinear(
|
||||
const ADDR2_COMPUTE_SURFACE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceCoordFromAddrTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_COORDFROMADDR_OUTPUT* pOut) const;
|
||||
|
||||
UINT_32 ComputeSurface2DMicroBlockOffset(
|
||||
const _ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn) const;
|
||||
|
||||
UINT_32 ComputeSurface3DMicroBlockOffset(
|
||||
const _ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn) const;
|
||||
|
||||
// Misc
|
||||
ADDR_E_RETURNCODE ComputeBlockDimensionForSurf(
|
||||
UINT_32* pWidth,
|
||||
UINT_32* pHeight,
|
||||
UINT_32* pDepth,
|
||||
UINT_32 bpp,
|
||||
UINT_32 numSamples,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeBlockDimension(
|
||||
UINT_32* pWidth,
|
||||
UINT_32* pHeight,
|
||||
UINT_32* pDepth,
|
||||
UINT_32 bpp,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const;
|
||||
|
||||
virtual VOID ComputeThinBlockDimension(
|
||||
UINT_32* pWidth,
|
||||
UINT_32* pHeight,
|
||||
UINT_32* pDepth,
|
||||
UINT_32 bpp,
|
||||
UINT_32 numSamples,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const;
|
||||
|
||||
VOID ComputeThickBlockDimension(
|
||||
UINT_32* pWidth,
|
||||
UINT_32* pHeight,
|
||||
UINT_32* pDepth,
|
||||
UINT_32 bpp,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const;
|
||||
|
||||
static UINT_64 ComputePadSize(
|
||||
const Dim3d* pBlkDim,
|
||||
UINT_32 width,
|
||||
UINT_32 height,
|
||||
UINT_32 numSlices,
|
||||
Dim3d* pPadDim)
|
||||
{
|
||||
pPadDim->w = PowTwoAlign(width ,pBlkDim->w);
|
||||
pPadDim->h = PowTwoAlign(height ,pBlkDim->h);
|
||||
pPadDim->d = PowTwoAlign(numSlices, pBlkDim->d);
|
||||
return static_cast<UINT_64>(pPadDim->w) * pPadDim->h * pPadDim->d;
|
||||
}
|
||||
|
||||
static ADDR_E_RETURNCODE ExtractPipeBankXor(
|
||||
UINT_32 pipeBankXor,
|
||||
UINT_32 bankBits,
|
||||
UINT_32 pipeBits,
|
||||
UINT_32* pBankX,
|
||||
UINT_32* pPipeX);
|
||||
|
||||
static BOOL_32 Valid3DMipSliceIdConstraint(
|
||||
UINT_32 numSlices,
|
||||
UINT_32 mipId,
|
||||
UINT_32 slice)
|
||||
{
|
||||
return (Max((numSlices >> mipId), 1u) > slice);
|
||||
}
|
||||
|
||||
Dim3d GetMipTailDim(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 blockWidth,
|
||||
UINT_32 blockHeight,
|
||||
UINT_32 blockDepth) const;
|
||||
|
||||
static BOOL_32 IsLocalHeap(AddrResrouceLocation resourceType)
|
||||
{
|
||||
return ((resourceType == ADDR_RSRC_LOC_LOCAL) ||
|
||||
(resourceType == ADDR_RSRC_LOC_INVIS));
|
||||
}
|
||||
|
||||
static BOOL_32 IsInvisibleHeap(AddrResrouceLocation resourceType)
|
||||
{
|
||||
return (resourceType == ADDR_RSRC_LOC_INVIS);
|
||||
}
|
||||
|
||||
static BOOL_32 IsNonlocalHeap(AddrResrouceLocation resourceType)
|
||||
{
|
||||
return ((resourceType == ADDR_RSRC_LOC_USWC) ||
|
||||
(resourceType == ADDR_RSRC_LOC_CACHED));
|
||||
}
|
||||
|
||||
UINT_32 GetPipeLog2ForMetaAddressing(BOOL_32 pipeAligned, AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
UINT_32 numPipeLog2 = pipeAligned ? Min(m_pipesLog2 + m_seLog2, 5u) : 0;
|
||||
|
||||
if (IsXor(swizzleMode))
|
||||
{
|
||||
UINT_32 maxPipeLog2 = GetBlockSizeLog2(swizzleMode) - m_pipeInterleaveLog2;
|
||||
|
||||
numPipeLog2 = Min(numPipeLog2, maxPipeLog2);
|
||||
}
|
||||
|
||||
return numPipeLog2;
|
||||
}
|
||||
|
||||
UINT_32 GetPipeNumForMetaAddressing(BOOL_32 pipeAligned, AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
return (1 << GetPipeLog2ForMetaAddressing(pipeAligned, swizzleMode));
|
||||
}
|
||||
|
||||
VOID VerifyMipLevelInfo(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const
|
||||
{
|
||||
#if DEBUG
|
||||
if (pIn->numMipLevels > 1)
|
||||
{
|
||||
UINT_32 actualMipLevels = 1;
|
||||
switch (pIn->resourceType)
|
||||
{
|
||||
case ADDR_RSRC_TEX_3D:
|
||||
// Fall through to share 2D case
|
||||
actualMipLevels = Max(actualMipLevels, Log2(pIn->numSlices) + 1);
|
||||
case ADDR_RSRC_TEX_2D:
|
||||
// Fall through to share 1D case
|
||||
actualMipLevels = Max(actualMipLevels, Log2(pIn->height) + 1);
|
||||
case ADDR_RSRC_TEX_1D:
|
||||
// Base 1D case
|
||||
actualMipLevels = Max(actualMipLevels, Log2(pIn->width) + 1);
|
||||
break;
|
||||
default:
|
||||
ADDR_ASSERT_ALWAYS();
|
||||
break;
|
||||
}
|
||||
// Client pass wrong number of MipLevels to addrlib and result will be bad.
|
||||
// Not sure if we should fail this calling instead of putting an assertion here.
|
||||
ADDR_ASSERT(actualMipLevels >= pIn->numMipLevels);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE ApplyCustomerPipeBankXor(
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 pipeBankXor,
|
||||
UINT_32 bankBits,
|
||||
UINT_32 pipeBits,
|
||||
UINT_32* pBlockOffset) const
|
||||
{
|
||||
ADDR_E_RETURNCODE returnCode = ADDR_OK;
|
||||
|
||||
if (IsXor(swizzleMode))
|
||||
{
|
||||
// Apply driver set bankPipeXor
|
||||
UINT_32 bankX = 0;
|
||||
UINT_32 pipeX = 0;
|
||||
returnCode = ExtractPipeBankXor(pipeBankXor, bankBits, pipeBits, &bankX, &pipeX);
|
||||
*pBlockOffset ^= (pipeX << m_pipeInterleaveLog2);
|
||||
*pBlockOffset ^= (bankX << (m_pipeInterleaveLog2 + pipeBits));
|
||||
}
|
||||
|
||||
return returnCode;
|
||||
}
|
||||
|
||||
UINT_32 GetPipeXorBits(UINT_32 macroBlockBits) const;
|
||||
|
||||
ADDR_E_RETURNCODE ApplyCustomizedPitchHeight(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
UINT_32 elementBytes,
|
||||
UINT_32 pitchAlignInElement,
|
||||
UINT_32* pPitch,
|
||||
UINT_32* pHeight) const;
|
||||
|
||||
VOID ComputeQbStereoInfo(ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
VOID FilterInvalidEqSwizzleMode(
|
||||
ADDR2_SWMODE_SET& allowedSwModeSet,
|
||||
AddrResourceType resourceType,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 maxComponents) const;
|
||||
|
||||
#if DEBUG
|
||||
VOID ValidateStereoInfo(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
#endif
|
||||
|
||||
UINT_32 m_se; ///< Number of shader engine
|
||||
UINT_32 m_rbPerSe; ///< Number of render backend per shader engine
|
||||
UINT_32 m_maxCompFrag; ///< Number of max compressed fragment
|
||||
|
||||
UINT_32 m_banksLog2; ///< Number of bank Log2
|
||||
UINT_32 m_pipesLog2; ///< Number of pipe per shader engine Log2
|
||||
UINT_32 m_seLog2; ///< Number of shader engine Log2
|
||||
UINT_32 m_rbPerSeLog2; ///< Number of render backend per shader engine Log2
|
||||
UINT_32 m_maxCompFragLog2; ///< Number of max compressed fragment Log2
|
||||
|
||||
UINT_32 m_pipeInterleaveLog2; ///< Log2 of pipe interleave bytes
|
||||
|
||||
UINT_32 m_blockVarSizeLog2; ///< Log2 of block var size
|
||||
|
||||
SwizzleModeFlags m_swizzleModeTable[ADDR_SW_MAX_TYPE]; ///< Swizzle mode table
|
||||
|
||||
// Max number of swizzle mode supported for equation
|
||||
static const UINT_32 MaxSwModeType = 32;
|
||||
// Max number of resource type (2D/3D) supported for equation
|
||||
static const UINT_32 MaxRsrcType = 2;
|
||||
// Almost all swizzle mode + resource type support equation
|
||||
static const UINT_32 EquationTableSize = MaxElementBytesLog2 * MaxSwModeType * MaxRsrcType;
|
||||
// Equation table
|
||||
ADDR_EQUATION m_equationTable[EquationTableSize];
|
||||
|
||||
// Number of equation entries in the table
|
||||
UINT_32 m_numEquations;
|
||||
// Equation lookup table according to bpp and tile index
|
||||
UINT_32 m_equationLookupTable[MaxRsrcType][MaxSwModeType][MaxElementBytesLog2];
|
||||
|
||||
private:
|
||||
// Disallow the copy constructor
|
||||
Lib(const Lib& a);
|
||||
|
||||
// Disallow the assignment operator
|
||||
Lib& operator=(const Lib& a);
|
||||
};
|
||||
|
||||
} // V2
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
|
||||
+1225
File diff suppressed because it is too large.
Load diff
+447
@@ -0,0 +1,447 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2022-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @file addrlib3.h
|
||||
* @brief Contains the Addr::V3::Lib class definition.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __ADDR3_LIB3_H__
|
||||
#define __ADDR3_LIB3_H__
|
||||
|
||||
#include "addrlib.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V3
|
||||
{
|
||||
|
||||
constexpr UINT_32 Size256 = 256u;
|
||||
constexpr UINT_32 Size4K = 4 * 1024;
|
||||
constexpr UINT_32 Size64K = 64 * 1024;
|
||||
constexpr UINT_32 Size256K = 256 * 1024;
|
||||
constexpr UINT_32 Addr3MaxMipLevels = 16; // Max Mip Levels across all addr3 chips
|
||||
|
||||
struct ADDR3_COORD
|
||||
{
|
||||
INT_32 x;
|
||||
INT_32 y;
|
||||
INT_32 z;
|
||||
};
|
||||
|
||||
// The HW address library utilizes an "addr_params" structure that is GPU-specific; therefore, we use a "void" pointer
|
||||
// here to allow the HWL's to interpret this pointer with the appropriate structure.
|
||||
// To reduce the frequency of conversion between the "ADDR3_COMPUTE_SURFACE_INFO_INPUT" structure and the "addr_params"
|
||||
// structure, we create this super-structure to tie the two structures together.
|
||||
struct ADDR3_COMPUTE_SURFACE_INFO_PARAMS_INPUT
|
||||
{
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pSurfInfo;
|
||||
void* pvAddrParams;
|
||||
};
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief Flags for SwizzleModeTable
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
union SwizzleModeFlags
|
||||
{
|
||||
struct
|
||||
{
|
||||
// Swizzle mode
|
||||
UINT_32 isLinear : 1; // Linear
|
||||
UINT_32 is2d : 1; // 2d mode
|
||||
UINT_32 is3d : 1; // 3d mode
|
||||
|
||||
// Block size
|
||||
UINT_32 is256b : 1; // Block size is 256B
|
||||
UINT_32 is4kb : 1; // Block size is 4KB
|
||||
UINT_32 is64kb : 1; // Block size is 64KB
|
||||
UINT_32 is256kb : 1; // Block size is 256KB
|
||||
|
||||
UINT_32 reserved : 25; // Reserved bits
|
||||
};
|
||||
|
||||
UINT_32 u32All;
|
||||
};
|
||||
|
||||
const UINT_32 Log2Size256 = 8u;
|
||||
|
||||
const UINT_32 Log2Size256K = 18u;
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief Swizzle pattern information
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
// Accessed by index representing the logbase2 of (8bpp/16bpp/32bpp/64bpp/128bpp)
|
||||
// contains the indices which map to 2D arrays SW_PATTERN_NIBBLE[1-4] which contain sections of an index equation.
|
||||
struct ADDR_SW_PATINFO
|
||||
{
|
||||
UINT_8 nibble1Idx;
|
||||
UINT_8 nibble2Idx;
|
||||
UINT_8 nibble3Idx;
|
||||
UINT_8 nibble4Idx;
|
||||
};
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief This class contains asic independent address lib functionalities
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
class Lib : public Addr::Lib
|
||||
{
|
||||
public:
|
||||
virtual ~Lib();
|
||||
|
||||
static Lib* GetLib(
|
||||
ADDR_HANDLE hLib);
|
||||
|
||||
UINT_32 GetInterfaceVersion() const override { return 3; }
|
||||
|
||||
//
|
||||
// Interface stubs
|
||||
//
|
||||
|
||||
// For data surface
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfo(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE GetPossibleSwizzleModes(
|
||||
const ADDR3_GET_POSSIBLE_SWIZZLE_MODE_INPUT* pIn,
|
||||
ADDR3_GET_POSSIBLE_SWIZZLE_MODE_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoord(
|
||||
const ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE CopyMemToSurface(
|
||||
const ADDR3_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR3_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const;
|
||||
|
||||
ADDR_E_RETURNCODE CopySurfaceToMem(
|
||||
const ADDR3_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR3_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const;
|
||||
|
||||
// Misc
|
||||
ADDR_E_RETURNCODE ComputePipeBankXor(
|
||||
const ADDR3_COMPUTE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR3_COMPUTE_PIPEBANKXOR_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeNonBlockCompressedView(
|
||||
const ADDR3_COMPUTE_NONBLOCKCOMPRESSEDVIEW_INPUT* pIn,
|
||||
ADDR3_COMPUTE_NONBLOCKCOMPRESSEDVIEW_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSubResourceOffsetForSwizzlePattern(
|
||||
const ADDR3_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_OUTPUT* pOut);
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSlicePipeBankXor(
|
||||
const ADDR3_COMPUTE_SLICE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SLICE_PIPEBANKXOR_OUTPUT* pOut);
|
||||
|
||||
protected:
|
||||
Lib(); // Constructor is protected
|
||||
Lib(const Client* pClient);
|
||||
|
||||
UINT_32 m_pipesLog2; ///< Number of pipe per shader engine Log2
|
||||
UINT_32 m_pipeInterleaveLog2; ///< Log2 of pipe interleave bytes
|
||||
|
||||
SwizzleModeFlags m_swizzleModeTable[ADDR3_MAX_TYPE]; ///< Swizzle mode table
|
||||
|
||||
// Number of unique MSAA sample rates (1/2/4/8)
|
||||
static const UINT_32 MaxNumMsaaRates = 4;
|
||||
|
||||
// Number of equation entries in the table
|
||||
UINT_32 m_numEquations;
|
||||
|
||||
// Swizzle equation lookup table according to swizzle mode, MSAA sample rate and bpp. This does not include linear.
|
||||
UINT_32 m_equationLookupTable[ADDR3_MAX_TYPE - 1][MaxNumMsaaRates][MaxElementBytesLog2];
|
||||
|
||||
// Block dimension lookup table according to swizzle mode, MSAA sample rate and bpp. This includes linear.
|
||||
ADDR_EXTENT3D m_blockDimensionTable[ADDR3_MAX_TYPE][MaxNumMsaaRates][MaxElementBytesLog2];
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeStereoInfo(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
UINT_32* pAlignY,
|
||||
UINT_32* pRightXor) const = 0;
|
||||
|
||||
void SetEquationTableEntry(
|
||||
Addr3SwizzleMode swMode,
|
||||
UINT_32 msaaLog2,
|
||||
UINT_32 elementBytesLog2,
|
||||
UINT_32 value)
|
||||
{
|
||||
// m_equationLookupTable doesn't include linear, so we must exclude linear when calling this function.
|
||||
ADDR_ASSERT(swMode != ADDR3_LINEAR);
|
||||
m_equationLookupTable[swMode - 1][msaaLog2][elementBytesLog2] = value;
|
||||
}
|
||||
|
||||
const UINT_32 GetEquationTableEntry(
|
||||
Addr3SwizzleMode swMode,
|
||||
UINT_32 msaaLog2,
|
||||
UINT_32 elementBytesLog2) const
|
||||
{
|
||||
UINT_32 res = ADDR_INVALID_EQUATION_INDEX;
|
||||
// m_equationLookupTable doesn't include linear
|
||||
if (swMode != ADDR3_LINEAR)
|
||||
{
|
||||
res = m_equationLookupTable[swMode - 1][msaaLog2][elementBytesLog2];
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
static UINT_32 ComputeOffsetFromEquation(
|
||||
const ADDR_EQUATION* pEq,
|
||||
UINT_32 x,
|
||||
UINT_32 y,
|
||||
UINT_32 z,
|
||||
UINT_32 s);
|
||||
|
||||
const ADDR_EXTENT3D GetBlockDimensionTableEntry(
|
||||
Addr3SwizzleMode swMode,
|
||||
UINT_32 msaaLog2,
|
||||
UINT_32 elementBytesLog2) const
|
||||
{
|
||||
return m_blockDimensionTable[swMode][msaaLog2][elementBytesLog2];
|
||||
}
|
||||
|
||||
static BOOL_32 Valid3DMipSliceIdConstraint(
|
||||
UINT_32 numSlices,
|
||||
UINT_32 mipId,
|
||||
UINT_32 slice)
|
||||
{
|
||||
return (Max((numSlices >> mipId), 1u) > slice);
|
||||
}
|
||||
|
||||
UINT_32 GetBlockSize(
|
||||
Addr3SwizzleMode swizzleMode,
|
||||
BOOL_32 forPitch = FALSE) const;
|
||||
|
||||
UINT_32 GetBlockSizeLog2(
|
||||
Addr3SwizzleMode swizzleMode,
|
||||
BOOL_32 forPitch = FALSE) const;
|
||||
|
||||
BOOL_32 IsValidSwMode(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return (m_swizzleModeTable[swizzleMode].u32All != 0);
|
||||
}
|
||||
|
||||
UINT_32 IsLinear(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isLinear;
|
||||
}
|
||||
|
||||
// Checking block size
|
||||
BOOL_32 IsBlock256b(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is256b;
|
||||
}
|
||||
|
||||
// Checking block size
|
||||
BOOL_32 IsBlock4kb(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is4kb;
|
||||
}
|
||||
|
||||
// Checking block size
|
||||
BOOL_32 IsBlock64kb(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is64kb;
|
||||
}
|
||||
|
||||
// Checking block size
|
||||
BOOL_32 IsBlock256kb(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is256kb;
|
||||
}
|
||||
|
||||
BOOL_32 Is2dSwizzle(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is2d;
|
||||
}
|
||||
|
||||
BOOL_32 Is3dSwizzle(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].is3d;
|
||||
}
|
||||
|
||||
// miptail is applied to only larger block size (4kb, 64kb, 256kb), so there is no miptail in linear and
|
||||
// 256b_2d addressing since they are both 256b block.
|
||||
BOOL_32 SupportsMipTail(Addr3SwizzleMode swizzleMode) const
|
||||
{
|
||||
return GetBlockSize(swizzleMode) > 256u;
|
||||
}
|
||||
|
||||
// The max alignment is tied to the swizzle mode and since the largest swizzle mode is 256kb, so the maximal
|
||||
// alignment is also 256kb.
|
||||
UINT_32 HwlComputeMaxBaseAlignments() const override { return Size256K; }
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlGetPossibleSwizzleModes(
|
||||
const ADDR3_GET_POSSIBLE_SWIZZLE_MODE_INPUT* pIn,
|
||||
ADDR3_GET_POSSIBLE_SWIZZLE_MODE_OUTPUT* pOut) const = 0;
|
||||
|
||||
UINT_32 HwlComputeMaxMetaBaseAlignments() const override { return 0; }
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceInfo(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlCopyMemToSurface(
|
||||
const ADDR3_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR3_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlCopySurfaceToMem(
|
||||
const ADDR3_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR3_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputePipeBankXor(
|
||||
const ADDR3_COMPUTE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR3_COMPUTE_PIPEBANKXOR_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
VOID ComputeBlockDimensionForSurf(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_PARAMS_INPUT* pIn,
|
||||
ADDR_EXTENT3D* pExtent) const;
|
||||
|
||||
ADDR_EXTENT3D GetMipTailDim(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_PARAMS_INPUT* pIn,
|
||||
const ADDR_EXTENT3D& blockDims) const;
|
||||
|
||||
ADDR_E_RETURNCODE CopyLinearSurface(
|
||||
const ADDR3_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR3_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount,
|
||||
bool surfaceIsDst) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordLinear(
|
||||
const ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceAddrFromCoordLinear(
|
||||
const ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pSurfInfoIn,
|
||||
ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const = 0;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordTiled(
|
||||
const ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSurfaceAddrFromCoordTiled(
|
||||
const ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTIMPLEMENTED;
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeNonBlockCompressedView(
|
||||
const ADDR3_COMPUTE_NONBLOCKCOMPRESSEDVIEW_INPUT* pIn,
|
||||
ADDR3_COMPUTE_NONBLOCKCOMPRESSEDVIEW_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual VOID HwlComputeSubResourceOffsetForSwizzlePattern(
|
||||
const ADDR3_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
}
|
||||
|
||||
virtual ADDR_E_RETURNCODE HwlComputeSlicePipeBankXor(
|
||||
const ADDR3_COMPUTE_SLICE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SLICE_PIPEBANKXOR_OUTPUT* pOut) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_NOTSUPPORTED;
|
||||
}
|
||||
|
||||
virtual UINT_32 HwlGetEquationIndex(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn) const
|
||||
{
|
||||
ADDR_NOT_IMPLEMENTED();
|
||||
return ADDR_INVALID_EQUATION_INDEX;
|
||||
}
|
||||
|
||||
void SetEquationIndex(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const
|
||||
{
|
||||
UINT_32 equationIdx = HwlGetEquationIndex(pIn);
|
||||
|
||||
if (pOut->pMipInfo != NULL)
|
||||
{
|
||||
for (UINT_32 i = 0; i < pIn->numMipLevels; i++)
|
||||
{
|
||||
pOut->pMipInfo[i].equationIndex = equationIdx;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE ApplyCustomizedPitchHeight(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR3_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
BOOL_32 UseCustomHeight(const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
BOOL_32 UseCustomPitch(const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
BOOL_32 CanTrimLinearPadding(const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
|
||||
virtual VOID HwlCalcBlockSize(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_PARAMS_INPUT* pIn,
|
||||
ADDR_EXTENT3D* pExtent) const = 0;
|
||||
|
||||
virtual ADDR_EXTENT3D HwlGetMipInTailMaxSize(
|
||||
const ADDR3_COMPUTE_SURFACE_INFO_PARAMS_INPUT* pIn,
|
||||
const ADDR_EXTENT3D& blockDims) const = 0;
|
||||
|
||||
virtual BOOL_32 HwlValidateNonSwModeParams(const ADDR3_GET_POSSIBLE_SWIZZLE_MODE_INPUT* pIn) const = 0;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoSanityCheck(const ADDR3_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
|
||||
private:
|
||||
// Disallow the copy constructor
|
||||
Lib(const Lib& a);
|
||||
|
||||
// Disallow the assignment operator
|
||||
Lib& operator=(const Lib& a);
|
||||
|
||||
void Init();
|
||||
|
||||
VOID ComputeQbStereoInfo(ADDR3_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
};
|
||||
|
||||
} // V3
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,261 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrobject.cpp
|
||||
* @brief Contains the Object base class implementation.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#include "addrinterface.h"
|
||||
#include "addrobject.h"
|
||||
|
||||
#if DEBUG
|
||||
#include <stdio.h>
|
||||
#endif
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
#if DEBUG && ADDR_ALLOW_TLS
|
||||
thread_local ADDR_CLIENT_HANDLE g_clientHandle = nullptr;
|
||||
thread_local ADDR_DEBUGPRINT g_pfnDebugPrint = nullptr;
|
||||
#endif
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::Object
|
||||
*
|
||||
* @brief
|
||||
* Constructor for the Object class.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Object::Object()
|
||||
{
|
||||
m_client.handle = NULL;
|
||||
m_client.callbacks.allocSysMem = NULL;
|
||||
m_client.callbacks.freeSysMem = NULL;
|
||||
m_client.callbacks.debugPrint = NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::Object
|
||||
*
|
||||
* @brief
|
||||
* Constructor for the Object class.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Object::Object(const Client* pClient)
|
||||
{
|
||||
m_client = *pClient;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::~Object
|
||||
*
|
||||
* @brief
|
||||
* Destructor for the Object class.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
Object::~Object()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::ClientAlloc
|
||||
*
|
||||
* @brief
|
||||
* Calls instanced allocSysMem inside Client
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID* Object::ClientAlloc(
|
||||
size_t objSize, ///< [in] Size to allocate
|
||||
const Client* pClient) ///< [in] Client pointer
|
||||
{
|
||||
VOID* pObjMem = NULL;
|
||||
|
||||
if (pClient->callbacks.allocSysMem != NULL)
|
||||
{
|
||||
ADDR_ALLOCSYSMEM_INPUT allocInput = {0};
|
||||
|
||||
allocInput.size = sizeof(ADDR_ALLOCSYSMEM_INPUT);
|
||||
allocInput.flags.value = 0;
|
||||
allocInput.sizeInBytes = static_cast<UINT_32>(objSize);
|
||||
allocInput.hClient = pClient->handle;
|
||||
|
||||
pObjMem = pClient->callbacks.allocSysMem(&allocInput);
|
||||
}
|
||||
|
||||
return pObjMem;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::Alloc
|
||||
*
|
||||
* @brief
|
||||
* A wrapper of ClientAlloc
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID* Object::Alloc(
|
||||
size_t objSize ///< [in] Size to allocate
|
||||
) const
|
||||
{
|
||||
return ClientAlloc(objSize, &m_client);;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::ClientFree
|
||||
*
|
||||
* @brief
|
||||
* Calls freeSysMem inside Client
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID Object::ClientFree(
|
||||
VOID* pObjMem, ///< [in] User virtual address to free.
|
||||
const Client* pClient) ///< [in] Client pointer
|
||||
{
|
||||
if (pClient->callbacks.freeSysMem != NULL)
|
||||
{
|
||||
if (pObjMem != NULL)
|
||||
{
|
||||
ADDR_FREESYSMEM_INPUT freeInput = {0};
|
||||
|
||||
freeInput.size = sizeof(ADDR_FREESYSMEM_INPUT);
|
||||
freeInput.hClient = pClient->handle;
|
||||
freeInput.pVirtAddr = pObjMem;
|
||||
|
||||
pClient->callbacks.freeSysMem(&freeInput);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::Free
|
||||
*
|
||||
* @brief
|
||||
* A wrapper of ClientFree
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID Object::Free(
|
||||
VOID* pObjMem ///< [in] User virtual address to free.
|
||||
) const
|
||||
{
|
||||
ClientFree(pObjMem, &m_client);
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::operator new
|
||||
*
|
||||
* @brief
|
||||
* Placement new operator. (with pre-allocated memory pointer)
|
||||
*
|
||||
* @return
|
||||
* Returns pre-allocated memory pointer.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID* Object::operator new(
|
||||
size_t objSize, ///< [in] Size to allocate
|
||||
VOID* pMem ///< [in] Pre-allocated pointer
|
||||
) noexcept
|
||||
{
|
||||
return pMem;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Object::operator delete
|
||||
*
|
||||
* @brief
|
||||
* Frees Object object memory.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID Object::operator delete(
|
||||
VOID* pObjMem) ///< [in] User virtual address to free.
|
||||
{
|
||||
Object* pObj = static_cast<Object*>(pObjMem);
|
||||
ClientFree(pObjMem, &pObj->m_client);
|
||||
}
|
||||
|
||||
|
||||
#if DEBUG
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* ApplyDebugPrinters
|
||||
*
|
||||
* @brief
|
||||
* Sets the debug printers via TLS
|
||||
*
|
||||
* @return
|
||||
* N/A
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID ApplyDebugPrinters(
|
||||
ADDR_DEBUGPRINT pfnDebugPrint,
|
||||
ADDR_CLIENT_HANDLE pClientHandle)
|
||||
{
|
||||
#if ADDR_ALLOW_TLS
|
||||
g_clientHandle = pClientHandle;
|
||||
g_pfnDebugPrint = pfnDebugPrint;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* DebugPrint
|
||||
*
|
||||
* @brief
|
||||
* Print debug message
|
||||
*
|
||||
* @return
|
||||
* N/A
|
||||
****************************************************************************************************
|
||||
*/
|
||||
VOID DebugPrint(
|
||||
const CHAR* pDebugString, ///< [in] Debug string
|
||||
...
|
||||
)
|
||||
{
|
||||
va_list ap;
|
||||
va_start(ap, pDebugString);
|
||||
|
||||
#if ADDR_ALLOW_TLS
|
||||
if (g_pfnDebugPrint != NULL)
|
||||
{
|
||||
ADDR_DEBUGPRINT_INPUT debugPrintInput = {0};
|
||||
|
||||
debugPrintInput.size = sizeof(ADDR_DEBUGPRINT_INPUT);
|
||||
debugPrintInput.pDebugString = const_cast<CHAR*>(pDebugString);
|
||||
debugPrintInput.hClient = g_clientHandle;
|
||||
va_copy(debugPrintInput.ap, ap);
|
||||
|
||||
g_pfnDebugPrint(&debugPrintInput);
|
||||
|
||||
va_end(debugPrintInput.ap);
|
||||
}
|
||||
else
|
||||
#endif
|
||||
{
|
||||
#if ADDR_ALLOW_STDIO
|
||||
fprintf(stderr, "Warning: Addrlib assert function called without corresponding 'ApplyDebugPrinters'\n");
|
||||
vfprintf(stderr, pDebugString, ap);
|
||||
#endif
|
||||
}
|
||||
va_end(ap);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // Addr
|
||||
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrobject.h
|
||||
* @brief Contains the Object base class definition.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __ADDR_OBJECT_H__
|
||||
#define __ADDR_OBJECT_H__
|
||||
|
||||
#include "addrtypes.h"
|
||||
#include "addrcommon.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief This structure contains client specific data
|
||||
****************************************************************************************************
|
||||
*/
|
||||
struct Client
|
||||
{
|
||||
ADDR_CLIENT_HANDLE handle;
|
||||
ADDR_CALLBACKS callbacks;
|
||||
};
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @brief This class is the base class for all ADDR class objects.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
class Object
|
||||
{
|
||||
public:
|
||||
Object();
|
||||
Object(const Client* pClient);
|
||||
virtual ~Object();
|
||||
|
||||
VOID* operator new(size_t size, VOID* pMem) noexcept;
|
||||
VOID operator delete(VOID* pObj);
|
||||
/// Microsoft compiler requires a matching delete implementation, which seems to be called when
|
||||
/// bad_alloc is thrown. But currently C++ exception isn't allowed so a dummy implementation is
|
||||
/// added to eliminate the warning.
|
||||
VOID operator delete(VOID* pObj, VOID* pMem) { ADDR_ASSERT_ALWAYS(); }
|
||||
|
||||
VOID* Alloc(size_t size) const;
|
||||
VOID Free(VOID* pObj) const;
|
||||
|
||||
#if DEBUG
|
||||
// This function should be called on every addrlib entrypoint (usually implicit by GetLib())
|
||||
VOID SetDebugPrinters() const { ApplyDebugPrinters(m_client.callbacks.debugPrint, m_client.handle); }
|
||||
#endif
|
||||
|
||||
const Client* GetClient() const {return &m_client;}
|
||||
|
||||
protected:
|
||||
Client m_client;
|
||||
|
||||
static VOID* ClientAlloc(size_t size, const Client* pClient);
|
||||
static VOID ClientFree(VOID* pObj, const Client* pClient);
|
||||
|
||||
private:
|
||||
// disallow the copy constructor
|
||||
Object(const Object& a);
|
||||
|
||||
// disallow the assignment operator
|
||||
Object& operator=(const Object& a);
|
||||
};
|
||||
|
||||
} // Addr
|
||||
#endif
|
||||
@@ -0,0 +1,441 @@
|
||||
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrswizzler.cpp
|
||||
* @brief Contains code for efficient CPU swizzling.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
|
||||
#include "addrswizzler.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::LutAddresser
|
||||
*
|
||||
* @brief
|
||||
* Constructor for the LutAddresser class.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
LutAddresser::LutAddresser()
|
||||
:
|
||||
m_pXLut(&m_lutData[0]),
|
||||
m_pYLut(&m_lutData[0]),
|
||||
m_pZLut(&m_lutData[0]),
|
||||
m_pSLut(&m_lutData[0]),
|
||||
m_xLutMask(0),
|
||||
m_yLutMask(0),
|
||||
m_zLutMask(0),
|
||||
m_sLutMask(0),
|
||||
m_blockBits(0),
|
||||
m_blockSize(),
|
||||
m_bpeLog2(0),
|
||||
m_bit(),
|
||||
m_lutData()
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::Init
|
||||
*
|
||||
* @brief
|
||||
* Calculates general properties about the swizzle
|
||||
****************************************************************************************************
|
||||
*/
|
||||
void LutAddresser::Init(
|
||||
const ADDR_BIT_SETTING* pEq,
|
||||
UINT_32 eqSize,
|
||||
ADDR_EXTENT3D blockSize,
|
||||
UINT_8 blockBits)
|
||||
{
|
||||
ADDR_ASSERT(eqSize <= ADDR_MAX_EQUATION_BIT);
|
||||
memcpy(&m_bit[0], pEq, sizeof(ADDR_BIT_SETTING) * eqSize);
|
||||
m_blockSize = blockSize;
|
||||
m_blockBits = blockBits;
|
||||
|
||||
InitSwizzleProps();
|
||||
InitLuts();
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::InitSwizzleProps
|
||||
*
|
||||
* @brief
|
||||
* Calculates general properties about the swizzle
|
||||
****************************************************************************************************
|
||||
*/
|
||||
void LutAddresser::InitSwizzleProps()
|
||||
{
|
||||
// Calculate BPE from the swizzle. This can be derived from the number of invalid low bits.
|
||||
m_bpeLog2 = 0;
|
||||
for (UINT_32 i = 0; i < MaxElementBytesLog2; i++)
|
||||
{
|
||||
if (m_bit[i].value != 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
m_bpeLog2++;
|
||||
}
|
||||
|
||||
// Generate a mask/size for each channel's LUT. This may be larger than the block size.
|
||||
// If a given 'source' bit (eg. 'x0') is used for any part of the equation, fill that in the mask.
|
||||
for (UINT_32 i = 0; i < ADDR_MAX_EQUATION_BIT; i++)
|
||||
{
|
||||
m_xLutMask |= m_bit[i].x;
|
||||
m_yLutMask |= m_bit[i].y;
|
||||
m_zLutMask |= m_bit[i].z;
|
||||
m_sLutMask |= m_bit[i].s;
|
||||
}
|
||||
|
||||
// An expandX of 1 is a no-op
|
||||
m_maxExpandX = 1;
|
||||
if (m_sLutMask == 0)
|
||||
{
|
||||
// Calculate expandX from the swizzle. This can be derived from the number of consecutive,
|
||||
// increasing low x bits
|
||||
for (UINT_32 i = 0; i < 3; i++)
|
||||
{
|
||||
const auto& curBit = m_bit[m_bpeLog2 + i];
|
||||
ADDR_ASSERT(curBit.value != 0);
|
||||
if ((IsPow2(curBit.value) == false) || // More than one bit contributes
|
||||
(curBit.x == 0) || // Bit is from Y/Z/S channel
|
||||
(curBit.x != m_maxExpandX)) // X bits are out of order
|
||||
{
|
||||
break;
|
||||
}
|
||||
m_maxExpandX *= 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::InitLuts
|
||||
*
|
||||
* @brief
|
||||
* Creates lookup tables for each channel.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
void LutAddresser::InitLuts()
|
||||
{
|
||||
UINT_32 curOffset = 0;
|
||||
m_pXLut = &m_lutData[0];
|
||||
for (UINT_32 x = 0; x < (m_xLutMask + 1); x++)
|
||||
{
|
||||
m_pXLut[x] = EvalEquation(x, 0, 0, 0);
|
||||
}
|
||||
curOffset += m_xLutMask + 1;
|
||||
ADDR_ASSERT(curOffset <= MaxLutSize);
|
||||
|
||||
if (m_yLutMask != 0)
|
||||
{
|
||||
m_pYLut = &m_lutData[curOffset];
|
||||
for (UINT_32 y = 0; y < (m_yLutMask + 1); y++)
|
||||
{
|
||||
m_pYLut[y] = EvalEquation(0, y, 0, 0);
|
||||
}
|
||||
curOffset += m_yLutMask + 1;
|
||||
ADDR_ASSERT(curOffset <= MaxLutSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_pYLut = &m_lutData[0];
|
||||
ADDR_ASSERT(m_pYLut[0] == 0);
|
||||
}
|
||||
|
||||
if (m_zLutMask != 0)
|
||||
{
|
||||
m_pZLut = &m_lutData[curOffset];
|
||||
for (UINT_32 z = 0; z < (m_zLutMask + 1); z++)
|
||||
{
|
||||
m_pZLut[z] = EvalEquation(0, 0, z, 0);
|
||||
}
|
||||
curOffset += m_zLutMask + 1;
|
||||
ADDR_ASSERT(curOffset <= MaxLutSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_pZLut = &m_lutData[0];
|
||||
ADDR_ASSERT(m_pZLut[0] == 0);
|
||||
}
|
||||
|
||||
if (m_sLutMask != 0)
|
||||
{
|
||||
m_pSLut = &m_lutData[curOffset];
|
||||
for (UINT_32 s = 0; s < (m_sLutMask + 1); s++)
|
||||
{
|
||||
m_pSLut[s] = EvalEquation(0, 0, 0, s);
|
||||
}
|
||||
curOffset += m_sLutMask + 1;
|
||||
ADDR_ASSERT(curOffset <= MaxLutSize);
|
||||
}
|
||||
else
|
||||
{
|
||||
m_pSLut = &m_lutData[0];
|
||||
ADDR_ASSERT(m_pSLut[0] == 0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::EvalEquation
|
||||
*
|
||||
* @brief
|
||||
* Evaluates the equation at a given coordinate manually.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
UINT_32 LutAddresser::EvalEquation(
|
||||
UINT_32 x,
|
||||
UINT_32 y,
|
||||
UINT_32 z,
|
||||
UINT_32 s)
|
||||
{
|
||||
UINT_32 out = 0;
|
||||
|
||||
for (UINT_32 i = 0; i < ADDR_MAX_EQUATION_BIT; i++)
|
||||
{
|
||||
if (m_bit[i].value == 0)
|
||||
{
|
||||
if (out != 0)
|
||||
{
|
||||
// Invalid bits at the top of the equation
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (x != 0)
|
||||
{
|
||||
UINT_32 xSrcs = m_bit[i].x;
|
||||
while (xSrcs != 0)
|
||||
{
|
||||
UINT_32 xIdx = BitMaskScanForward(xSrcs);
|
||||
out ^= (((x >> xIdx) & 1) << i);
|
||||
xSrcs = UnsetLeastBit(xSrcs);
|
||||
}
|
||||
}
|
||||
|
||||
if (y != 0)
|
||||
{
|
||||
UINT_32 ySrcs = m_bit[i].y;
|
||||
while (ySrcs != 0)
|
||||
{
|
||||
UINT_32 yIdx = BitMaskScanForward(ySrcs);
|
||||
out ^= (((y >> yIdx) & 1) << i);
|
||||
ySrcs = UnsetLeastBit(ySrcs);
|
||||
}
|
||||
}
|
||||
|
||||
if (z != 0)
|
||||
{
|
||||
UINT_32 zSrcs = m_bit[i].z;
|
||||
while (zSrcs != 0)
|
||||
{
|
||||
UINT_32 zIdx = BitMaskScanForward(zSrcs);
|
||||
out ^= (((z >> zIdx) & 1) << i);
|
||||
zSrcs = UnsetLeastBit(zSrcs);
|
||||
}
|
||||
}
|
||||
|
||||
if (s != 0)
|
||||
{
|
||||
UINT_32 sSrcs = m_bit[i].s;
|
||||
while (sSrcs != 0)
|
||||
{
|
||||
UINT_32 sIdx = BitMaskScanForward(sSrcs);
|
||||
out ^= (((s >> sIdx) & 1) << i);
|
||||
sSrcs = UnsetLeastBit(sSrcs);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* Copy2DSliceUnaligned
|
||||
*
|
||||
* @brief
|
||||
* Copies an arbitrary 2D pixel region to or from a surface.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
template <int BPELog2, int ExpandX, bool ImgIsDest>
|
||||
void Copy2DSliceUnaligned(
|
||||
void* pImgBlockSliceStart, // Block corresponding to beginning of slice
|
||||
void* pBuf, // Pointer to data starting from the copy origin.
|
||||
size_t bufStrideY, // Stride of each row in pBuf
|
||||
UINT_32 imageBlocksY, // Width of the image slice, in blocks.
|
||||
ADDR_COORD2D origin, // Absolute origin, in elements
|
||||
ADDR_EXTENT2D extent, // Size to copy, in elements
|
||||
UINT_32 sliceXor, // Includes pipeBankXor and z XOR
|
||||
const LutAddresser& addresser)
|
||||
{
|
||||
UINT_32 xStart = origin.x;
|
||||
UINT_32 xEnd = origin.x + extent.width;
|
||||
|
||||
constexpr UINT_32 PixBytes = (1 << BPELog2);
|
||||
|
||||
// Apply a negative offset now so later code can do eg. pBuf[x] instead of pBuf[x - origin.x]
|
||||
pBuf = VoidPtrDec(pBuf, xStart * PixBytes);
|
||||
|
||||
// Do things one row at a time for unaligned regions.
|
||||
for (UINT_32 y = origin.y; y < (origin.y + extent.height); y++)
|
||||
{
|
||||
UINT_32 yBlk = (y >> addresser.GetBlockYBits()) * imageBlocksY;
|
||||
UINT_32 rowXor = sliceXor ^ addresser.GetAddressY(y);
|
||||
|
||||
UINT_32 x = xStart;
|
||||
|
||||
// Most swizzles pack 2-4 pixels horizontally. Take advantage of this even in non-microblock-aligned
|
||||
// regions to commonly do 2-4x less work. This is still way less good than copying by whole microblocks though.
|
||||
if (ExpandX > 1)
|
||||
{
|
||||
// Unaligned left edge
|
||||
for (; x < Min(xEnd, PowTwoAlign(xStart, ExpandX)); x++)
|
||||
{
|
||||
UINT_32 blk = (yBlk + (x >> addresser.GetBlockXBits()));
|
||||
void* pImgBlock = VoidPtrInc(pImgBlockSliceStart, blk << addresser.GetBlockBits());
|
||||
void* pPix = VoidPtrInc(pImgBlock, rowXor ^ addresser.GetAddressX(x));
|
||||
if (ImgIsDest)
|
||||
{
|
||||
memcpy(pPix, VoidPtrInc(pBuf, x * PixBytes), PixBytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
memcpy(VoidPtrInc(pBuf, x * PixBytes), pPix, PixBytes);
|
||||
}
|
||||
}
|
||||
// Aligned middle
|
||||
for (; x < PowTwoAlignDown(xEnd, ExpandX); x += ExpandX)
|
||||
{
|
||||
UINT_32 blk = (yBlk + (x >> addresser.GetBlockXBits()));
|
||||
void* pImgBlock = VoidPtrInc(pImgBlockSliceStart, blk << addresser.GetBlockBits());
|
||||
void* pPix = VoidPtrInc(pImgBlock, rowXor ^ addresser.GetAddressX(x));
|
||||
if (ImgIsDest)
|
||||
{
|
||||
memcpy(pPix, VoidPtrInc(pBuf, x * PixBytes), PixBytes * ExpandX);
|
||||
}
|
||||
else
|
||||
{
|
||||
memcpy(VoidPtrInc(pBuf, x * PixBytes), pPix, PixBytes * ExpandX);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unaligned end (or the whole thing when ExpandX == 1)
|
||||
for (; x < xEnd; x++)
|
||||
{
|
||||
// Get the index of the block within the slice
|
||||
UINT_32 blk = (yBlk + (x >> addresser.GetBlockXBits()));
|
||||
// Apply that index to get the base address of the current block.
|
||||
void* pImgBlock = VoidPtrInc(pImgBlockSliceStart, blk << addresser.GetBlockBits());
|
||||
// Grab the x-xor and XOR it all together, adding to get the final address
|
||||
void* pPix = VoidPtrInc(pImgBlock, rowXor ^ addresser.GetAddressX(x));
|
||||
if (ImgIsDest)
|
||||
{
|
||||
memcpy(pPix, VoidPtrInc(pBuf, x * PixBytes), PixBytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
memcpy(VoidPtrInc(pBuf, x * PixBytes), pPix, PixBytes);
|
||||
}
|
||||
}
|
||||
|
||||
pBuf = VoidPtrInc(pBuf, bufStrideY);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::GetCopyMemImgFunc
|
||||
*
|
||||
* @brief
|
||||
* Determines and returns which copy function to use for copying to images
|
||||
****************************************************************************************************
|
||||
*/
|
||||
UnalignedCopyMemImgFunc LutAddresser::GetCopyMemImgFunc() const
|
||||
{
|
||||
// While these are all the same function, the codegen gets really bad if the size of each pixel
|
||||
// is not known at compile time. Hence, templates.
|
||||
const UnalignedCopyMemImgFunc Funcs[MaxElementBytesLog2][3] =
|
||||
{
|
||||
// ExpandX = 1, 2, 4
|
||||
{ Copy2DSliceUnaligned<0, 1, true>, Copy2DSliceUnaligned<0, 2, true>, Copy2DSliceUnaligned<0, 4, true> }, // 1BPE
|
||||
{ Copy2DSliceUnaligned<1, 1, true>, Copy2DSliceUnaligned<1, 2, true>, Copy2DSliceUnaligned<1, 4, true> }, // 2BPE
|
||||
{ Copy2DSliceUnaligned<2, 1, true>, Copy2DSliceUnaligned<2, 2, true>, Copy2DSliceUnaligned<2, 4, true> }, // 4BPE
|
||||
{ Copy2DSliceUnaligned<3, 1, true>, Copy2DSliceUnaligned<3, 2, true>, Copy2DSliceUnaligned<3, 4, true> }, // 8BPE
|
||||
{ Copy2DSliceUnaligned<4, 1, true>, Copy2DSliceUnaligned<4, 2, true>, Copy2DSliceUnaligned<4, 4, true> }, // 16BPE
|
||||
};
|
||||
|
||||
UnalignedCopyMemImgFunc pfnRet = nullptr;
|
||||
ADDR_ASSERT(m_bpeLog2 < MaxElementBytesLog2);
|
||||
if (m_maxExpandX >= 4)
|
||||
{
|
||||
pfnRet = Funcs[m_bpeLog2][2];
|
||||
}
|
||||
else if (m_maxExpandX >= 2)
|
||||
{
|
||||
pfnRet = Funcs[m_bpeLog2][1];
|
||||
}
|
||||
else
|
||||
{
|
||||
pfnRet = Funcs[m_bpeLog2][0];
|
||||
}
|
||||
return pfnRet;
|
||||
}
|
||||
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* LutAddresser::GetCopyImgMemFunc
|
||||
*
|
||||
* @brief
|
||||
* Determines and returns which copy function to use for copying from images
|
||||
****************************************************************************************************
|
||||
*/
|
||||
UnalignedCopyMemImgFunc LutAddresser::GetCopyImgMemFunc() const
|
||||
{
|
||||
// While these are all the same function, the codegen gets really bad if the size of each pixel
|
||||
// is not known at compile time. Hence, templates.
|
||||
const UnalignedCopyMemImgFunc Funcs[MaxElementBytesLog2][3] =
|
||||
{
|
||||
// ExpandX = 1, 2, 4
|
||||
{ Copy2DSliceUnaligned<0, 1, false>, Copy2DSliceUnaligned<0, 2, false>, Copy2DSliceUnaligned<0, 4, false> }, // 1BPE
|
||||
{ Copy2DSliceUnaligned<1, 1, false>, Copy2DSliceUnaligned<1, 2, false>, Copy2DSliceUnaligned<1, 4, false> }, // 2BPE
|
||||
{ Copy2DSliceUnaligned<2, 1, false>, Copy2DSliceUnaligned<2, 2, false>, Copy2DSliceUnaligned<2, 4, false> }, // 4BPE
|
||||
{ Copy2DSliceUnaligned<3, 1, false>, Copy2DSliceUnaligned<3, 2, false>, Copy2DSliceUnaligned<3, 4, false> }, // 8BPE
|
||||
{ Copy2DSliceUnaligned<4, 1, false>, Copy2DSliceUnaligned<4, 2, false>, Copy2DSliceUnaligned<4, 4, false> }, // 16BPE
|
||||
};
|
||||
|
||||
UnalignedCopyMemImgFunc pfnRet = nullptr;
|
||||
ADDR_ASSERT(m_bpeLog2 < MaxElementBytesLog2);
|
||||
if (m_maxExpandX >= 4)
|
||||
{
|
||||
pfnRet = Funcs[m_bpeLog2][2];
|
||||
}
|
||||
else if (m_maxExpandX >= 2)
|
||||
{
|
||||
pfnRet = Funcs[m_bpeLog2][1];
|
||||
}
|
||||
else
|
||||
{
|
||||
pfnRet = Funcs[m_bpeLog2][0];
|
||||
}
|
||||
return pfnRet;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
/**
|
||||
****************************************************************************************************
|
||||
* @file addrswizzler.cpp
|
||||
* @brief Contains code for efficient CPU swizzling.
|
||||
****************************************************************************************************
|
||||
*/
|
||||
#ifndef __ADDR_SWIZZLER_H__
|
||||
#define __ADDR_SWIZZLER_H__
|
||||
|
||||
#include "addrlib.h"
|
||||
#include "addrcommon.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
|
||||
// Forward decl
|
||||
class LutAddresser;
|
||||
|
||||
typedef void (*UnalignedCopyMemImgFunc)(
|
||||
void* pImgBlockSliceStart, // Block corresponding to beginning of slice
|
||||
void* pBuf, // Pointer to data starting from the copy origin.
|
||||
size_t bufStrideY, // Stride of each row in pBuf
|
||||
UINT_32 imageBlocksY, // Width of the image slice, in blocks.
|
||||
ADDR_COORD2D origin, // Absolute origin, in elements
|
||||
ADDR_EXTENT2D extent, // Size to copy, in elements
|
||||
UINT_32 sliceXor, // Includes pipeBankXor and z XOR
|
||||
const LutAddresser& addresser);
|
||||
|
||||
// This class calculates and holds up to four lookup tables (x/y/z/s) which can be used to cheaply calculate the
|
||||
// position of a pixel within a block at the cost of some precomputation and memory usage.
|
||||
//
|
||||
// This works for all equations and does something like this:
|
||||
// offset = blockAddr ^ XLut[x & xMask] ^ YLut[Y & ymask]...
|
||||
class LutAddresser
|
||||
{
|
||||
public:
|
||||
constexpr static UINT_32 MaxLutSize = 2100; // Sized to fit the largest non-VAR LUT size
|
||||
|
||||
LutAddresser();
|
||||
|
||||
void Init(const ADDR_BIT_SETTING* pEq, UINT_32 eqSize, ADDR_EXTENT3D blockSize, UINT_8 blkBits);
|
||||
|
||||
// Does a full calculation to get the offset within a block. Takes an *absolute* coordinate,
|
||||
// not the coordinate within the block.
|
||||
UINT_32 GetBlockOffset(
|
||||
UINT_32 x,
|
||||
UINT_32 y,
|
||||
UINT_32 z,
|
||||
UINT_32 s = 0,
|
||||
UINT_32 pipeBankXor = 0)
|
||||
{
|
||||
return GetAddressX(x) ^ GetAddressY(y) ^ GetAddressZ(z) ^ GetAddressS(s) ^ pipeBankXor;
|
||||
}
|
||||
|
||||
// Get the block size
|
||||
UINT_32 GetBlockBits() const { return m_blockBits; }
|
||||
UINT_32 GetBlockXBits() const { return Log2(m_blockSize.width); }
|
||||
UINT_32 GetBlockYBits() const { return Log2(m_blockSize.height); }
|
||||
UINT_32 GetBlockZBits() const { return Log2(m_blockSize.depth); }
|
||||
|
||||
// "Fast single channel" functions to get the part that each channel contributes to be XORd together.
|
||||
UINT_32 GetAddressX(UINT_32 x) const { return m_pXLut[x & m_xLutMask];}
|
||||
UINT_32 GetAddressY(UINT_32 y) const { return m_pYLut[y & m_yLutMask];}
|
||||
UINT_32 GetAddressZ(UINT_32 z) const { return m_pZLut[z & m_zLutMask];}
|
||||
UINT_32 GetAddressS(UINT_32 s) const { return m_pSLut[s & m_sLutMask];}
|
||||
|
||||
// Get a function that can copy a single 2D slice of an image with this swizzle.
|
||||
UnalignedCopyMemImgFunc GetCopyMemImgFunc() const;
|
||||
UnalignedCopyMemImgFunc GetCopyImgMemFunc() const;
|
||||
private:
|
||||
// Calculate general properties of the swizzle equations
|
||||
void InitSwizzleProps();
|
||||
// Fills a LUT for each channel.
|
||||
void InitLuts();
|
||||
// Evaluate coordinate without LUTs
|
||||
UINT_32 EvalEquation(UINT_32 x, UINT_32 y, UINT_32 z, UINT_32 s);
|
||||
|
||||
// Pointers within m_lutData corresponding to where each LUT starts
|
||||
// m_lutData[0] always has a value of 0 and thus can be considered an empty 1-entry LUT for "don't care" channels
|
||||
UINT_32* m_pXLut;
|
||||
UINT_32* m_pYLut;
|
||||
UINT_32* m_pZLut;
|
||||
UINT_32* m_pSLut;
|
||||
|
||||
// Size of each LUT, minus 1 to form a mask. A mask of 0 is valid for an empty LUT.
|
||||
UINT_32 m_xLutMask;
|
||||
UINT_32 m_yLutMask;
|
||||
UINT_32 m_zLutMask;
|
||||
UINT_32 m_sLutMask;
|
||||
|
||||
// Number of bits in the block (aka Log2(blkSize))
|
||||
UINT_32 m_blockBits;
|
||||
|
||||
// The block size
|
||||
ADDR_EXTENT3D m_blockSize;
|
||||
|
||||
// Number of 'x' bits at the bottom of the equation. Must be a pow2 and at least 1.
|
||||
// This will be used as a simple optimization to batch together operations on adjacent x pixels.
|
||||
UINT_32 m_maxExpandX;
|
||||
|
||||
// BPE for this equation.
|
||||
UINT_32 m_bpeLog2;
|
||||
|
||||
// The full equation
|
||||
ADDR_BIT_SETTING m_bit[ADDR_MAX_EQUATION_BIT];
|
||||
|
||||
// Backing store for the LUT tables.
|
||||
UINT_32 m_lutData[MaxLutSize];
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __ADDR_SWIZZLER_H__
|
||||
+586
@@ -0,0 +1,586 @@
|
||||
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2022 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
// Coordinate class implementation
|
||||
#include "addrcommon.h"
|
||||
#include "coord.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V2
|
||||
{
|
||||
|
||||
Coordinate::Coordinate()
|
||||
{
|
||||
dim = DIM_X;
|
||||
ord = 0;
|
||||
}
|
||||
|
||||
Coordinate::Coordinate(enum Dim dim, INT_32 n)
|
||||
{
|
||||
set(dim, n);
|
||||
}
|
||||
|
||||
VOID Coordinate::set(enum Dim d, INT_32 n)
|
||||
{
|
||||
dim = d;
|
||||
ord = static_cast<INT_8>(n);
|
||||
}
|
||||
|
||||
UINT_32 Coordinate::ison(const UINT_32 *coords) const
|
||||
{
|
||||
UINT_32 bit = static_cast<UINT_32>(1ull << static_cast<UINT_32>(ord));
|
||||
|
||||
return (coords[dim] & bit) ? 1 : 0;
|
||||
}
|
||||
|
||||
enum Dim Coordinate::getdim()
|
||||
{
|
||||
return dim;
|
||||
}
|
||||
|
||||
INT_8 Coordinate::getord()
|
||||
{
|
||||
return ord;
|
||||
}
|
||||
|
||||
BOOL_32 Coordinate::operator==(const Coordinate& b)
|
||||
{
|
||||
return (dim == b.dim) && (ord == b.ord);
|
||||
}
|
||||
|
||||
BOOL_32 Coordinate::operator<(const Coordinate& b)
|
||||
{
|
||||
BOOL_32 ret;
|
||||
|
||||
if (dim == b.dim)
|
||||
{
|
||||
ret = ord < b.ord;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (dim == DIM_S || b.dim == DIM_M)
|
||||
{
|
||||
ret = TRUE;
|
||||
}
|
||||
else if (b.dim == DIM_S || dim == DIM_M)
|
||||
{
|
||||
ret = FALSE;
|
||||
}
|
||||
else if (ord == b.ord)
|
||||
{
|
||||
ret = dim < b.dim;
|
||||
}
|
||||
else
|
||||
{
|
||||
ret = ord < b.ord;
|
||||
}
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
BOOL_32 Coordinate::operator>(const Coordinate& b)
|
||||
{
|
||||
BOOL_32 lt = *this < b;
|
||||
BOOL_32 eq = *this == b;
|
||||
return !lt && !eq;
|
||||
}
|
||||
|
||||
BOOL_32 Coordinate::operator<=(const Coordinate& b)
|
||||
{
|
||||
return (*this < b) || (*this == b);
|
||||
}
|
||||
|
||||
BOOL_32 Coordinate::operator>=(const Coordinate& b)
|
||||
{
|
||||
return !(*this < b);
|
||||
}
|
||||
|
||||
BOOL_32 Coordinate::operator!=(const Coordinate& b)
|
||||
{
|
||||
return !(*this == b);
|
||||
}
|
||||
|
||||
Coordinate& Coordinate::operator++(INT_32)
|
||||
{
|
||||
ord++;
|
||||
return *this;
|
||||
}
|
||||
|
||||
// CoordTerm
|
||||
|
||||
CoordTerm::CoordTerm()
|
||||
{
|
||||
num_coords = 0;
|
||||
}
|
||||
|
||||
VOID CoordTerm::Clear()
|
||||
{
|
||||
num_coords = 0;
|
||||
}
|
||||
|
||||
VOID CoordTerm::add(Coordinate& co)
|
||||
{
|
||||
// This function adds a coordinate INT_32o the list
|
||||
// It will prevent the same coordinate from appearing,
|
||||
// and will keep the list ordered from smallest to largest
|
||||
UINT_32 i;
|
||||
|
||||
for (i = 0; i < num_coords; i++)
|
||||
{
|
||||
if (m_coord[i] == co)
|
||||
{
|
||||
break;
|
||||
}
|
||||
if (m_coord[i] > co)
|
||||
{
|
||||
for (UINT_32 j = num_coords; j > i; j--)
|
||||
{
|
||||
m_coord[j] = m_coord[j - 1];
|
||||
}
|
||||
m_coord[i] = co;
|
||||
num_coords++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (i == num_coords)
|
||||
{
|
||||
m_coord[num_coords] = co;
|
||||
num_coords++;
|
||||
}
|
||||
}
|
||||
|
||||
VOID CoordTerm::add(CoordTerm& cl)
|
||||
{
|
||||
for (UINT_32 i = 0; i < cl.num_coords; i++)
|
||||
{
|
||||
add(cl.m_coord[i]);
|
||||
}
|
||||
}
|
||||
|
||||
BOOL_32 CoordTerm::remove(Coordinate& co)
|
||||
{
|
||||
BOOL_32 remove = FALSE;
|
||||
for (UINT_32 i = 0; i < num_coords; i++)
|
||||
{
|
||||
if (m_coord[i] == co)
|
||||
{
|
||||
remove = TRUE;
|
||||
num_coords--;
|
||||
}
|
||||
|
||||
if (remove)
|
||||
{
|
||||
m_coord[i] = m_coord[i + 1];
|
||||
}
|
||||
}
|
||||
return remove;
|
||||
}
|
||||
|
||||
BOOL_32 CoordTerm::Exists(Coordinate& co)
|
||||
{
|
||||
BOOL_32 exists = FALSE;
|
||||
for (UINT_32 i = 0; i < num_coords; i++)
|
||||
{
|
||||
if (m_coord[i] == co)
|
||||
{
|
||||
exists = TRUE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return exists;
|
||||
}
|
||||
|
||||
VOID CoordTerm::copyto(CoordTerm& cl)
|
||||
{
|
||||
cl.num_coords = num_coords;
|
||||
for (UINT_32 i = 0; i < num_coords; i++)
|
||||
{
|
||||
cl.m_coord[i] = m_coord[i];
|
||||
}
|
||||
}
|
||||
|
||||
UINT_32 CoordTerm::getsize()
|
||||
{
|
||||
return num_coords;
|
||||
}
|
||||
|
||||
UINT_32 CoordTerm::getxor(const UINT_32 *coords) const
|
||||
{
|
||||
UINT_32 out = 0;
|
||||
for (UINT_32 i = 0; i < num_coords; i++)
|
||||
{
|
||||
out = out ^ m_coord[i].ison(coords);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
VOID CoordTerm::getsmallest(Coordinate& co)
|
||||
{
|
||||
co = m_coord[0];
|
||||
}
|
||||
|
||||
UINT_32 CoordTerm::Filter(INT_8 f, Coordinate& co, UINT_32 start, enum Dim axis)
|
||||
{
|
||||
for (UINT_32 i = start; i < num_coords;)
|
||||
{
|
||||
if (((f == '<' && m_coord[i] < co) ||
|
||||
(f == '>' && m_coord[i] > co) ||
|
||||
(f == '=' && m_coord[i] == co)) &&
|
||||
(axis == NUM_DIMS || axis == m_coord[i].getdim()))
|
||||
{
|
||||
for (UINT_32 j = i; j < num_coords - 1; j++)
|
||||
{
|
||||
m_coord[j] = m_coord[j + 1];
|
||||
}
|
||||
num_coords--;
|
||||
}
|
||||
else
|
||||
{
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return num_coords;
|
||||
}
|
||||
|
||||
Coordinate& CoordTerm::operator[](UINT_32 i)
|
||||
{
|
||||
return m_coord[i];
|
||||
}
|
||||
|
||||
BOOL_32 CoordTerm::operator==(const CoordTerm& b)
|
||||
{
|
||||
BOOL_32 ret = TRUE;
|
||||
|
||||
if (num_coords != b.num_coords)
|
||||
{
|
||||
ret = FALSE;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (UINT_32 i = 0; i < num_coords; i++)
|
||||
{
|
||||
// Note: the lists will always be in order, so we can compare the two lists at time
|
||||
if (m_coord[i] != b.m_coord[i])
|
||||
{
|
||||
ret = FALSE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
BOOL_32 CoordTerm::operator!=(const CoordTerm& b)
|
||||
{
|
||||
return !(*this == b);
|
||||
}
|
||||
|
||||
BOOL_32 CoordTerm::exceedRange(const UINT_32 *ranges)
|
||||
{
|
||||
BOOL_32 exceed = FALSE;
|
||||
for (UINT_32 i = 0; (i < num_coords) && (exceed == FALSE); i++)
|
||||
{
|
||||
exceed = ((1u << m_coord[i].getord()) <= ranges[m_coord[i].getdim()]);
|
||||
}
|
||||
|
||||
return exceed;
|
||||
}
|
||||
|
||||
// coordeq
|
||||
CoordEq::CoordEq()
|
||||
{
|
||||
m_numBits = 0;
|
||||
}
|
||||
|
||||
VOID CoordEq::remove(Coordinate& co)
|
||||
{
|
||||
for (UINT_32 i = 0; i < m_numBits; i++)
|
||||
{
|
||||
m_eq[i].remove(co);
|
||||
}
|
||||
}
|
||||
|
||||
BOOL_32 CoordEq::Exists(Coordinate& co)
|
||||
{
|
||||
BOOL_32 exists = FALSE;
|
||||
|
||||
for (UINT_32 i = 0; i < m_numBits; i++)
|
||||
{
|
||||
if (m_eq[i].Exists(co))
|
||||
{
|
||||
exists = TRUE;
|
||||
}
|
||||
}
|
||||
return exists;
|
||||
}
|
||||
|
||||
VOID CoordEq::resize(UINT_32 n)
|
||||
{
|
||||
if (n > m_numBits)
|
||||
{
|
||||
for (UINT_32 i = m_numBits; i < n; i++)
|
||||
{
|
||||
m_eq[i].Clear();
|
||||
}
|
||||
}
|
||||
m_numBits = n;
|
||||
}
|
||||
|
||||
UINT_32 CoordEq::getsize()
|
||||
{
|
||||
return m_numBits;
|
||||
}
|
||||
|
||||
UINT_64 CoordEq::solve(const UINT_32 *coords) const
|
||||
{
|
||||
UINT_64 out = 0;
|
||||
for (UINT_32 i = 0; i < m_numBits; i++)
|
||||
{
|
||||
out |= static_cast<UINT_64>(m_eq[i].getxor(coords)) << i;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
VOID CoordEq::solveAddr(
|
||||
UINT_64 addr, UINT_32 sliceInM,
|
||||
UINT_32 *coords) const
|
||||
{
|
||||
UINT_32 BitsValid[NUM_DIMS] = {0};
|
||||
|
||||
CoordEq temp = *this;
|
||||
|
||||
memset(coords, 0, NUM_DIMS * sizeof(coords[0]));
|
||||
|
||||
UINT_32 bitsLeft = 0;
|
||||
|
||||
for (UINT_32 i = 0; i < temp.m_numBits; i++)
|
||||
{
|
||||
UINT_32 termSize = temp.m_eq[i].getsize();
|
||||
|
||||
if (termSize == 1)
|
||||
{
|
||||
INT_8 bit = (addr >> i) & 1;
|
||||
enum Dim dim = temp.m_eq[i][0].getdim();
|
||||
INT_8 ord = temp.m_eq[i][0].getord();
|
||||
|
||||
ADDR_ASSERT((ord < 32) || (bit == 0));
|
||||
|
||||
BitsValid[dim] |= 1u << ord;
|
||||
coords[dim] |= bit << ord;
|
||||
|
||||
temp.m_eq[i].Clear();
|
||||
}
|
||||
else if (termSize > 1)
|
||||
{
|
||||
bitsLeft++;
|
||||
}
|
||||
}
|
||||
|
||||
if (bitsLeft > 0)
|
||||
{
|
||||
if (sliceInM != 0)
|
||||
{
|
||||
coords[DIM_Z] = coords[DIM_M] / sliceInM;
|
||||
BitsValid[DIM_Z] = 0xffffffff;
|
||||
}
|
||||
|
||||
do
|
||||
{
|
||||
bitsLeft = 0;
|
||||
|
||||
for (UINT_32 i = 0; i < temp.m_numBits; i++)
|
||||
{
|
||||
UINT_32 termSize = temp.m_eq[i].getsize();
|
||||
|
||||
if (termSize == 1)
|
||||
{
|
||||
INT_8 bit = (addr >> i) & 1;
|
||||
enum Dim dim = temp.m_eq[i][0].getdim();
|
||||
INT_8 ord = temp.m_eq[i][0].getord();
|
||||
|
||||
ADDR_ASSERT((ord < 32) || (bit == 0));
|
||||
ADDR_ASSERT(dim < DIM_S);
|
||||
|
||||
BitsValid[dim] |= 1u << ord;
|
||||
coords[dim] |= bit << ord;
|
||||
|
||||
temp.m_eq[i].Clear();
|
||||
}
|
||||
else if (termSize > 1)
|
||||
{
|
||||
CoordTerm tmpTerm = temp.m_eq[i];
|
||||
|
||||
for (UINT_32 j = 0; j < termSize; j++)
|
||||
{
|
||||
enum Dim dim = temp.m_eq[i][j].getdim();
|
||||
INT_8 ord = temp.m_eq[i][j].getord();
|
||||
|
||||
ADDR_ASSERT(dim < DIM_S);
|
||||
|
||||
if (BitsValid[dim] & (1u << ord))
|
||||
{
|
||||
UINT_32 v = (((coords[dim] >> ord) & 1) << i);
|
||||
addr ^= static_cast<UINT_64>(v);
|
||||
tmpTerm.remove(temp.m_eq[i][j]);
|
||||
}
|
||||
}
|
||||
|
||||
temp.m_eq[i] = tmpTerm;
|
||||
|
||||
bitsLeft++;
|
||||
}
|
||||
}
|
||||
} while (bitsLeft > 0);
|
||||
}
|
||||
}
|
||||
|
||||
VOID CoordEq::copy(CoordEq& o, UINT_32 start, UINT_32 num)
|
||||
{
|
||||
o.m_numBits = (num == 0xFFFFFFFF) ? m_numBits : num;
|
||||
for (UINT_32 i = 0; i < o.m_numBits; i++)
|
||||
{
|
||||
m_eq[start + i].copyto(o.m_eq[i]);
|
||||
}
|
||||
}
|
||||
|
||||
VOID CoordEq::reverse(UINT_32 start, UINT_32 num)
|
||||
{
|
||||
UINT_32 n = (num == 0xFFFFFFFF) ? m_numBits : num;
|
||||
|
||||
for (UINT_32 i = 0; i < n / 2; i++)
|
||||
{
|
||||
CoordTerm temp;
|
||||
m_eq[start + i].copyto(temp);
|
||||
m_eq[start + n - 1 - i].copyto(m_eq[start + i]);
|
||||
temp.copyto(m_eq[start + n - 1 - i]);
|
||||
}
|
||||
}
|
||||
|
||||
VOID CoordEq::xorin(CoordEq& x, UINT_32 start)
|
||||
{
|
||||
UINT_32 n = ((m_numBits - start) < x.m_numBits) ? (m_numBits - start) : x.m_numBits;
|
||||
for (UINT_32 i = 0; i < n; i++)
|
||||
{
|
||||
m_eq[start + i].add(x.m_eq[i]);
|
||||
}
|
||||
}
|
||||
|
||||
UINT_32 CoordEq::Filter(INT_8 f, Coordinate& co, UINT_32 start, enum Dim axis)
|
||||
{
|
||||
for (UINT_32 i = start; i < m_numBits;)
|
||||
{
|
||||
UINT_32 m = m_eq[i].Filter(f, co, 0, axis);
|
||||
if (m == 0)
|
||||
{
|
||||
for (UINT_32 j = i; j < m_numBits - 1; j++)
|
||||
{
|
||||
m_eq[j] = m_eq[j + 1];
|
||||
}
|
||||
m_numBits--;
|
||||
}
|
||||
else
|
||||
{
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return m_numBits;
|
||||
}
|
||||
|
||||
VOID CoordEq::shift(INT_32 amount, INT_32 start)
|
||||
{
|
||||
if (amount != 0)
|
||||
{
|
||||
INT_32 numBits = static_cast<INT_32>(m_numBits);
|
||||
amount = -amount;
|
||||
INT_32 inc = (amount < 0) ? -1 : 1;
|
||||
INT_32 i = (amount < 0) ? numBits - 1 : start;
|
||||
INT_32 end = (amount < 0) ? start - 1 : numBits;
|
||||
for (; (inc > 0) ? i < end : i > end; i += inc)
|
||||
{
|
||||
if ((i + amount < start) || (i + amount >= numBits))
|
||||
{
|
||||
m_eq[i].Clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
m_eq[i + amount].copyto(m_eq[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CoordTerm& CoordEq::operator[](UINT_32 i)
|
||||
{
|
||||
return m_eq[i];
|
||||
}
|
||||
|
||||
VOID CoordEq::mort2d(Coordinate& c0, Coordinate& c1, UINT_32 start, UINT_32 end)
|
||||
{
|
||||
if (end == 0)
|
||||
{
|
||||
ADDR_ASSERT(m_numBits > 0);
|
||||
end = m_numBits - 1;
|
||||
}
|
||||
for (UINT_32 i = start; i <= end; i++)
|
||||
{
|
||||
UINT_32 select = (i - start) % 2;
|
||||
Coordinate& c = (select == 0) ? c0 : c1;
|
||||
m_eq[i].add(c);
|
||||
c++;
|
||||
}
|
||||
}
|
||||
|
||||
VOID CoordEq::mort3d(Coordinate& c0, Coordinate& c1, Coordinate& c2, UINT_32 start, UINT_32 end)
|
||||
{
|
||||
if (end == 0)
|
||||
{
|
||||
ADDR_ASSERT(m_numBits > 0);
|
||||
end = m_numBits - 1;
|
||||
}
|
||||
for (UINT_32 i = start; i <= end; i++)
|
||||
{
|
||||
UINT_32 select = (i - start) % 3;
|
||||
Coordinate& c = (select == 0) ? c0 : ((select == 1) ? c1 : c2);
|
||||
m_eq[i].add(c);
|
||||
c++;
|
||||
}
|
||||
}
|
||||
|
||||
BOOL_32 CoordEq::operator==(const CoordEq& b)
|
||||
{
|
||||
BOOL_32 ret = TRUE;
|
||||
|
||||
if (m_numBits != b.m_numBits)
|
||||
{
|
||||
ret = FALSE;
|
||||
}
|
||||
else
|
||||
{
|
||||
for (UINT_32 i = 0; i < m_numBits; i++)
|
||||
{
|
||||
if (m_eq[i] != b.m_eq[i])
|
||||
{
|
||||
ret = FALSE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
BOOL_32 CoordEq::operator!=(const CoordEq& b)
|
||||
{
|
||||
return !(*this == b);
|
||||
}
|
||||
|
||||
} // V2
|
||||
} // Addr
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2022 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
// Class used to define a coordinate bit
|
||||
|
||||
#ifndef __COORD_H
|
||||
#define __COORD_H
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V2
|
||||
{
|
||||
#if defined(__cplusplus)
|
||||
#if defined(_MSC_VER)
|
||||
#if _MSC_VER >= 1900
|
||||
#define ADDR_CPP11_COMPILER TRUE
|
||||
#endif
|
||||
#else
|
||||
#if __cplusplus >= 201103L
|
||||
#define ADDR_CPP11_COMPILER TRUE
|
||||
#endif
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(ADDR_CPP11_COMPILER)
|
||||
enum Dim : INT_8
|
||||
#else
|
||||
enum Dim
|
||||
#endif
|
||||
{
|
||||
DIM_X,
|
||||
DIM_Y,
|
||||
DIM_Z,
|
||||
DIM_S,
|
||||
DIM_M,
|
||||
NUM_DIMS
|
||||
};
|
||||
|
||||
class Coordinate
|
||||
{
|
||||
public:
|
||||
Coordinate();
|
||||
Coordinate(enum Dim dim, INT_32 n);
|
||||
|
||||
VOID set(enum Dim dim, INT_32 n);
|
||||
UINT_32 ison(const UINT_32 *coords) const;
|
||||
enum Dim getdim();
|
||||
INT_8 getord();
|
||||
|
||||
BOOL_32 operator==(const Coordinate& b);
|
||||
BOOL_32 operator<(const Coordinate& b);
|
||||
BOOL_32 operator>(const Coordinate& b);
|
||||
BOOL_32 operator<=(const Coordinate& b);
|
||||
BOOL_32 operator>=(const Coordinate& b);
|
||||
BOOL_32 operator!=(const Coordinate& b);
|
||||
Coordinate& operator++(INT_32);
|
||||
|
||||
private:
|
||||
enum Dim dim;
|
||||
INT_8 ord;
|
||||
};
|
||||
|
||||
class CoordTerm
|
||||
{
|
||||
public:
|
||||
CoordTerm();
|
||||
VOID Clear();
|
||||
VOID add(Coordinate& co);
|
||||
VOID add(CoordTerm& cl);
|
||||
BOOL_32 remove(Coordinate& co);
|
||||
BOOL_32 Exists(Coordinate& co);
|
||||
VOID copyto(CoordTerm& cl);
|
||||
UINT_32 getsize();
|
||||
UINT_32 getxor(const UINT_32 *coords) const;
|
||||
|
||||
VOID getsmallest(Coordinate& co);
|
||||
UINT_32 Filter(INT_8 f, Coordinate& co, UINT_32 start = 0, enum Dim axis = NUM_DIMS);
|
||||
Coordinate& operator[](UINT_32 i);
|
||||
BOOL_32 operator==(const CoordTerm& b);
|
||||
BOOL_32 operator!=(const CoordTerm& b);
|
||||
BOOL_32 exceedRange(const UINT_32 *ranges);
|
||||
|
||||
private:
|
||||
static const UINT_32 MaxCoords = 8;
|
||||
UINT_32 num_coords;
|
||||
Coordinate m_coord[MaxCoords];
|
||||
};
|
||||
|
||||
class CoordEq
|
||||
{
|
||||
public:
|
||||
CoordEq();
|
||||
VOID remove(Coordinate& co);
|
||||
BOOL_32 Exists(Coordinate& co);
|
||||
VOID resize(UINT_32 n);
|
||||
UINT_32 getsize();
|
||||
virtual UINT_64 solve(const UINT_32 *coords) const;
|
||||
virtual VOID solveAddr(UINT_64 addr, UINT_32 sliceInM,
|
||||
UINT_32 *coords) const;
|
||||
|
||||
VOID copy(CoordEq& o, UINT_32 start = 0, UINT_32 num = 0xFFFFFFFF);
|
||||
VOID reverse(UINT_32 start = 0, UINT_32 num = 0xFFFFFFFF);
|
||||
VOID xorin(CoordEq& x, UINT_32 start = 0);
|
||||
UINT_32 Filter(INT_8 f, Coordinate& co, UINT_32 start = 0, enum Dim axis = NUM_DIMS);
|
||||
VOID shift(INT_32 amount, INT_32 start = 0);
|
||||
virtual CoordTerm& operator[](UINT_32 i);
|
||||
VOID mort2d(Coordinate& c0, Coordinate& c1, UINT_32 start = 0, UINT_32 end = 0);
|
||||
VOID mort3d(Coordinate& c0, Coordinate& c1, Coordinate& c2, UINT_32 start = 0, UINT_32 end = 0);
|
||||
|
||||
BOOL_32 operator==(const CoordEq& b);
|
||||
BOOL_32 operator!=(const CoordEq& b);
|
||||
|
||||
private:
|
||||
static const UINT_32 MaxEqBits = 64;
|
||||
UINT_32 m_numBits;
|
||||
|
||||
CoordTerm m_eq[MaxEqBits];
|
||||
};
|
||||
|
||||
} // V2
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,579 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @file gfx10addrlib.h
|
||||
* @brief Contains the Gfx10Lib class definition.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __GFX10_ADDR_LIB_H__
|
||||
#define __GFX10_ADDR_LIB_H__
|
||||
|
||||
#include "addrlib2.h"
|
||||
#include "coord.h"
|
||||
#include "gfx10SwizzlePattern.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V2
|
||||
{
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief GFX10 specific settings structure.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
struct Gfx10ChipSettings
|
||||
{
|
||||
struct
|
||||
{
|
||||
UINT_32 reserved1 : 32;
|
||||
|
||||
// Misc configuration bits
|
||||
UINT_32 isDcn20 : 1; // If using DCN2.0
|
||||
UINT_32 supportRbPlus : 1;
|
||||
UINT_32 dsMipmapHtileFix : 1;
|
||||
UINT_32 dccUnsup3DSwDis : 1;
|
||||
UINT_32 reserved2 : 28;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief GFX10 data surface type.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
enum Gfx10DataType
|
||||
{
|
||||
Gfx10DataColor,
|
||||
Gfx10DataDepthStencil,
|
||||
Gfx10DataFmask
|
||||
};
|
||||
|
||||
const UINT_32 Gfx10LinearSwModeMask = (1u << ADDR_SW_LINEAR);
|
||||
|
||||
const UINT_32 Gfx10Blk256BSwModeMask = (1u << ADDR_SW_256B_S) |
|
||||
(1u << ADDR_SW_256B_D);
|
||||
|
||||
const UINT_32 Gfx10Blk4KBSwModeMask = (1u << ADDR_SW_4KB_S) |
|
||||
(1u << ADDR_SW_4KB_D) |
|
||||
(1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_4KB_D_X);
|
||||
|
||||
const UINT_32 Gfx10Blk64KBSwModeMask = (1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_R_X);
|
||||
|
||||
const UINT_32 Gfx10BlkVarSwModeMask = (1u << ADDR_SW_VAR_Z_X) |
|
||||
(1u << ADDR_SW_VAR_R_X);
|
||||
|
||||
const UINT_32 Gfx10ZSwModeMask = (1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_VAR_Z_X);
|
||||
|
||||
const UINT_32 Gfx10StandardSwModeMask = (1u << ADDR_SW_256B_S) |
|
||||
(1u << ADDR_SW_4KB_S) |
|
||||
(1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_S_X);
|
||||
|
||||
const UINT_32 Gfx10DisplaySwModeMask = (1u << ADDR_SW_256B_D) |
|
||||
(1u << ADDR_SW_4KB_D) |
|
||||
(1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_4KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_D_X);
|
||||
|
||||
const UINT_32 Gfx10RenderSwModeMask = (1u << ADDR_SW_64KB_R_X) |
|
||||
(1u << ADDR_SW_VAR_R_X);
|
||||
|
||||
const UINT_32 Gfx10XSwModeMask = (1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_4KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_R_X) |
|
||||
Gfx10BlkVarSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10TSwModeMask = (1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_64KB_D_T);
|
||||
|
||||
const UINT_32 Gfx10XorSwModeMask = Gfx10XSwModeMask |
|
||||
Gfx10TSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc1dSwModeMask = Gfx10LinearSwModeMask |
|
||||
Gfx10RenderSwModeMask |
|
||||
Gfx10ZSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc2dSwModeMask = Gfx10LinearSwModeMask |
|
||||
Gfx10Blk256BSwModeMask |
|
||||
Gfx10Blk4KBSwModeMask |
|
||||
Gfx10Blk64KBSwModeMask |
|
||||
Gfx10BlkVarSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dSwModeMask = (1u << ADDR_SW_LINEAR) |
|
||||
(1u << ADDR_SW_4KB_S) |
|
||||
(1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_R_X) |
|
||||
Gfx10BlkVarSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc2dPrtSwModeMask = (Gfx10Blk4KBSwModeMask | Gfx10Blk64KBSwModeMask) & ~Gfx10XSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dPrtSwModeMask = Gfx10Rsrc2dPrtSwModeMask & ~Gfx10DisplaySwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dThin64KBSwModeMask = (1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_R_X);
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dThinSwModeMask = Gfx10Rsrc3dThin64KBSwModeMask |
|
||||
Gfx10BlkVarSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dViewAs2dSwModeMask = Gfx10Rsrc3dThinSwModeMask | Gfx10LinearSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dThickSwModeMask = Gfx10Rsrc3dSwModeMask & ~(Gfx10Rsrc3dThinSwModeMask | Gfx10LinearSwModeMask);
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dThick4KBSwModeMask = Gfx10Rsrc3dThickSwModeMask & Gfx10Blk4KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10Rsrc3dThick64KBSwModeMask = Gfx10Rsrc3dThickSwModeMask & Gfx10Blk64KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx10MsaaSwModeMask = (Gfx10ZSwModeMask |
|
||||
Gfx10RenderSwModeMask);
|
||||
|
||||
const UINT_32 Dcn20NonBpp64SwModeMask = (1u << ADDR_SW_LINEAR) |
|
||||
(1u << ADDR_SW_4KB_S) |
|
||||
(1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_R_X);
|
||||
|
||||
const UINT_32 Dcn20Bpp64SwModeMask = (1u << ADDR_SW_4KB_D) |
|
||||
(1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_4KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
Dcn20NonBpp64SwModeMask;
|
||||
|
||||
const UINT_32 Dcn21NonBpp64SwModeMask = (1u << ADDR_SW_LINEAR) |
|
||||
(1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_R_X);
|
||||
|
||||
const UINT_32 Dcn21Bpp64SwModeMask = (1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
Dcn21NonBpp64SwModeMask;
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief This class is the GFX10 specific address library
|
||||
* function set.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
class Gfx10Lib : public Lib
|
||||
{
|
||||
public:
|
||||
/// Creates Gfx10Lib object
|
||||
static Addr::Lib* CreateObj(const Client* pClient)
|
||||
{
|
||||
VOID* pMem = Object::ClientAlloc(sizeof(Gfx10Lib), pClient);
|
||||
return (pMem != NULL) ? new (pMem) Gfx10Lib(pClient) : NULL;
|
||||
}
|
||||
|
||||
protected:
|
||||
Gfx10Lib(const Client* pClient);
|
||||
virtual ~Gfx10Lib();
|
||||
|
||||
BOOL_32 HwlIsStandardSwizzle(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isStd;
|
||||
}
|
||||
|
||||
BOOL_32 HwlIsDisplaySwizzle(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isDisp;
|
||||
}
|
||||
|
||||
BOOL_32 HwlIsThin(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return ((IsTex1d(resourceType) == TRUE) ||
|
||||
(IsTex2d(resourceType) == TRUE) ||
|
||||
((IsTex3d(resourceType) == TRUE) &&
|
||||
(m_swizzleModeTable[swizzleMode].isStd == FALSE) &&
|
||||
(m_swizzleModeTable[swizzleMode].isDisp == FALSE)));
|
||||
}
|
||||
|
||||
BOOL_32 HwlIsThick(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return ((IsTex3d(resourceType) == TRUE) &&
|
||||
(m_swizzleModeTable[swizzleMode].isStd || m_swizzleModeTable[swizzleMode].isDisp));
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeHtileInfo(
|
||||
const ADDR2_COMPUTE_HTILE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeCmaskInfo(
|
||||
const ADDR2_COMPUTE_CMASK_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeDccInfo(
|
||||
const ADDR2_COMPUTE_DCCINFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCCINFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeCmaskAddrFromCoord(
|
||||
const ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_CMASK_ADDRFROMCOORD_OUTPUT* pOut) override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeHtileAddrFromCoord(
|
||||
const ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT* pOut) override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeHtileCoordFromAddr(
|
||||
const ADDR2_COMPUTE_HTILE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_COORDFROMADDR_OUTPUT* pOut) override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlSupportComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn) override final;
|
||||
|
||||
VOID HwlComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCC_ADDRFROMCOORD_OUTPUT* pOut) override final;
|
||||
|
||||
UINT_32 HwlGetEquationIndex(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
UINT_32 HwlGetEquationTableInfo(const ADDR_EQUATION** ppEquationTable) const override final
|
||||
{
|
||||
*ppEquationTable = m_equationTable;
|
||||
|
||||
return m_numEquations;
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputePipeBankXor(
|
||||
const ADDR2_COMPUTE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSlicePipeBankXor(
|
||||
const ADDR2_COMPUTE_SLICE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SLICE_PIPEBANKXOR_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSubResourceOffsetForSwizzlePattern(
|
||||
const ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeNonBlockCompressedView(
|
||||
const ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_INPUT* pIn,
|
||||
ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlGetPreferredSurfaceSetting(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlGetPossibleSwizzleModes(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceInfoSanityCheck(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceInfoTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceInfoLinear(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceAddrFromCoordTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlCopyMemToSurface(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlCopySurfaceToMem(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const override final;
|
||||
|
||||
UINT_32 HwlComputeMaxBaseAlignments() const override final;
|
||||
|
||||
UINT_32 HwlComputeMaxMetaBaseAlignments() const override final;
|
||||
|
||||
BOOL_32 HwlInitGlobalParams(const ADDR_CREATE_INPUT* pCreateIn) override final;
|
||||
|
||||
ChipFamily HwlConvertChipFamily(UINT_32 uChipFamily, UINT_32 uChipRevision) override final;
|
||||
|
||||
private:
|
||||
// Initialize equation table
|
||||
VOID InitEquationTable();
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoMacroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoMicroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordMacroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordMicroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
UINT_32 ComputeOffsetFromEquation(
|
||||
const ADDR_EQUATION* pEq,
|
||||
UINT_32 x,
|
||||
UINT_32 y,
|
||||
UINT_32 z) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeStereoInfo(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
UINT_32* pAlignY,
|
||||
UINT_32* pRightXor) const;
|
||||
|
||||
static void GetMipSize(
|
||||
UINT_32 mip0Width,
|
||||
UINT_32 mip0Height,
|
||||
UINT_32 mip0Depth,
|
||||
UINT_32 mipId,
|
||||
UINT_32* pMipWidth,
|
||||
UINT_32* pMipHeight,
|
||||
UINT_32* pMipDepth = NULL)
|
||||
{
|
||||
*pMipWidth = ShiftCeil(Max(mip0Width, 1u), mipId);
|
||||
*pMipHeight = ShiftCeil(Max(mip0Height, 1u), mipId);
|
||||
|
||||
if (pMipDepth != NULL)
|
||||
{
|
||||
*pMipDepth = ShiftCeil(Max(mip0Depth, 1u), mipId);
|
||||
}
|
||||
}
|
||||
|
||||
const ADDR_SW_PATINFO* GetSwizzlePatternInfo(
|
||||
AddrSwizzleMode swizzleMode,
|
||||
AddrResourceType resourceType,
|
||||
UINT_32 log2Elem,
|
||||
UINT_32 numFrag) const;
|
||||
|
||||
/**
|
||||
* Will use the indices, "nibbles", to build an index equation inside pSwizzle
|
||||
*
|
||||
* @param pPatInfo Pointer to a patInfo. Contains indices mapping to the 2D nibble arrays which will be used to build an index equation.
|
||||
* @param pSwizzle Array to write the index equation to.
|
||||
*/
|
||||
VOID GetSwizzlePatternFromPatternInfo(
|
||||
const ADDR_SW_PATINFO* pPatInfo,
|
||||
ADDR_BIT_SETTING (&pSwizzle)[ADDR_MAX_EQUATION_BIT]) const
|
||||
{
|
||||
memcpy(pSwizzle,
|
||||
GFX10_SW_PATTERN_NIBBLE01[pPatInfo->nibble01Idx],
|
||||
sizeof(GFX10_SW_PATTERN_NIBBLE01[pPatInfo->nibble01Idx]));
|
||||
|
||||
memcpy(&pSwizzle[8],
|
||||
GFX10_SW_PATTERN_NIBBLE2[pPatInfo->nibble2Idx],
|
||||
sizeof(GFX10_SW_PATTERN_NIBBLE2[pPatInfo->nibble2Idx]));
|
||||
|
||||
memcpy(&pSwizzle[12],
|
||||
GFX10_SW_PATTERN_NIBBLE3[pPatInfo->nibble3Idx],
|
||||
sizeof(GFX10_SW_PATTERN_NIBBLE3[pPatInfo->nibble3Idx]));
|
||||
|
||||
memcpy(&pSwizzle[16],
|
||||
GFX10_SW_PATTERN_NIBBLE4[pPatInfo->nibble4Idx],
|
||||
sizeof(GFX10_SW_PATTERN_NIBBLE4[pPatInfo->nibble4Idx]));
|
||||
}
|
||||
|
||||
VOID ConvertSwizzlePatternToEquation(
|
||||
UINT_32 elemLog2,
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
const ADDR_SW_PATINFO* pPatInfo,
|
||||
ADDR_EQUATION* pEquation) const;
|
||||
|
||||
static INT_32 GetMetaElementSizeLog2(Gfx10DataType dataType);
|
||||
|
||||
static INT_32 GetMetaCacheSizeLog2(Gfx10DataType dataType);
|
||||
|
||||
void GetBlk256SizeLog2(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2,
|
||||
Dim3d* pBlock) const;
|
||||
|
||||
void GetCompressedBlockSizeLog2(
|
||||
Gfx10DataType dataType,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2,
|
||||
Dim3d* pBlock) const;
|
||||
|
||||
INT_32 GetMetaOverlapLog2(
|
||||
Gfx10DataType dataType,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2) const;
|
||||
|
||||
INT_32 Get3DMetaOverlapLog2(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2) const;
|
||||
|
||||
UINT_32 GetMetaBlkSize(
|
||||
Gfx10DataType dataType,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2,
|
||||
BOOL_32 pipeAlign,
|
||||
Dim3d* pBlock) const;
|
||||
|
||||
INT_32 GetPipeRotateAmount(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const;
|
||||
|
||||
INT_32 GetEffectiveNumPipes() const
|
||||
{
|
||||
return ((m_settings.supportRbPlus == FALSE) ||
|
||||
((m_numSaLog2 + 1) >= m_pipesLog2)) ? m_pipesLog2 : m_numSaLog2 + 1;
|
||||
}
|
||||
|
||||
BOOL_32 IsRbAligned(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
const BOOL_32 isRtopt = IsRtOptSwizzle(swizzleMode);
|
||||
const BOOL_32 isZ = IsZOrderSwizzle(swizzleMode);
|
||||
const BOOL_32 isDisplay = IsDisplaySwizzle(swizzleMode);
|
||||
|
||||
return (IsTex2d(resourceType) && (isRtopt || isZ)) ||
|
||||
(IsTex3d(resourceType) && isDisplay);
|
||||
|
||||
}
|
||||
|
||||
UINT_32 GetValidDisplaySwizzleModes(UINT_32 bpp) const;
|
||||
|
||||
BOOL_32 IsValidDisplaySwizzleMode(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const override final;
|
||||
|
||||
UINT_32 GetMaxNumMipsInTail(UINT_32 blockSizeLog2, BOOL_32 isThin) const;
|
||||
|
||||
static ADDR2_BLOCK_SET GetAllowedBlockSet(ADDR2_SWMODE_SET allowedSwModeSet, AddrResourceType rsrcType)
|
||||
{
|
||||
ADDR2_BLOCK_SET allowedBlockSet = {};
|
||||
|
||||
allowedBlockSet.micro = (allowedSwModeSet.value & Gfx10Blk256BSwModeMask) ? TRUE : FALSE;
|
||||
allowedBlockSet.linear = (allowedSwModeSet.value & Gfx10LinearSwModeMask) ? TRUE : FALSE;
|
||||
allowedBlockSet.var = (allowedSwModeSet.value & Gfx10BlkVarSwModeMask) ? TRUE : FALSE;
|
||||
|
||||
if (rsrcType == ADDR_RSRC_TEX_3D)
|
||||
{
|
||||
allowedBlockSet.macroThick4KB = (allowedSwModeSet.value & Gfx10Rsrc3dThick4KBSwModeMask) ? TRUE : FALSE;
|
||||
allowedBlockSet.macroThin64KB = (allowedSwModeSet.value & Gfx10Rsrc3dThin64KBSwModeMask) ? TRUE : FALSE;
|
||||
allowedBlockSet.macroThick64KB = (allowedSwModeSet.value & Gfx10Rsrc3dThick64KBSwModeMask) ? TRUE : FALSE;
|
||||
}
|
||||
else
|
||||
{
|
||||
allowedBlockSet.macroThin4KB = (allowedSwModeSet.value & Gfx10Blk4KBSwModeMask) ? TRUE : FALSE;
|
||||
allowedBlockSet.macroThin64KB = (allowedSwModeSet.value & Gfx10Blk64KBSwModeMask) ? TRUE : FALSE;
|
||||
}
|
||||
|
||||
return allowedBlockSet;
|
||||
}
|
||||
|
||||
static ADDR2_SWTYPE_SET GetAllowedSwSet(ADDR2_SWMODE_SET allowedSwModeSet)
|
||||
{
|
||||
ADDR2_SWTYPE_SET allowedSwSet = {};
|
||||
|
||||
allowedSwSet.sw_Z = (allowedSwModeSet.value & Gfx10ZSwModeMask) ? TRUE : FALSE;
|
||||
allowedSwSet.sw_S = (allowedSwModeSet.value & Gfx10StandardSwModeMask) ? TRUE : FALSE;
|
||||
allowedSwSet.sw_D = (allowedSwModeSet.value & Gfx10DisplaySwModeMask) ? TRUE : FALSE;
|
||||
allowedSwSet.sw_R = (allowedSwModeSet.value & Gfx10RenderSwModeMask) ? TRUE : FALSE;
|
||||
|
||||
return allowedSwSet;
|
||||
}
|
||||
|
||||
BOOL_32 IsInMipTail(
|
||||
Dim3d mipTailDim,
|
||||
UINT_32 maxNumMipsInTail,
|
||||
UINT_32 mipWidth,
|
||||
UINT_32 mipHeight,
|
||||
UINT_32 numMipsToTheEnd) const
|
||||
{
|
||||
BOOL_32 inTail = ((mipWidth <= mipTailDim.w) &&
|
||||
(mipHeight <= mipTailDim.h) &&
|
||||
(numMipsToTheEnd <= maxNumMipsInTail));
|
||||
|
||||
return inTail;
|
||||
}
|
||||
|
||||
UINT_32 GetBankXorBits(UINT_32 blockBits) const
|
||||
{
|
||||
return (blockBits > m_pipeInterleaveLog2 + m_pipesLog2 + ColumnBits) ?
|
||||
Min(blockBits - m_pipeInterleaveLog2 - m_pipesLog2 - ColumnBits, BankBits) : 0;
|
||||
}
|
||||
|
||||
BOOL_32 ValidateNonSwModeParams(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
BOOL_32 ValidateSwModeParams(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
|
||||
static const UINT_32 ColumnBits = 2;
|
||||
static const UINT_32 BankBits = 4;
|
||||
static const UINT_32 UnalignedDccType = 3;
|
||||
|
||||
static const Dim3d Block256_3d[MaxNumOfBpp];
|
||||
static const Dim3d Block64K_Log2_3d[MaxNumOfBpp];
|
||||
static const Dim3d Block4K_Log2_3d[MaxNumOfBpp];
|
||||
|
||||
static const SwizzleModeFlags SwizzleModeTable[ADDR_SW_MAX_TYPE];
|
||||
|
||||
// Number of packers log2
|
||||
UINT_32 m_numPkrLog2;
|
||||
// Number of shader array log2
|
||||
UINT_32 m_numSaLog2;
|
||||
|
||||
Gfx10ChipSettings m_settings;
|
||||
|
||||
UINT_32 m_colorBaseIndex;
|
||||
UINT_32 m_xmaskBaseIndex;
|
||||
UINT_32 m_htileBaseIndex;
|
||||
UINT_32 m_dccBaseIndex;
|
||||
};
|
||||
|
||||
} // V2
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,525 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2007-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @file gfx11addrlib.h
|
||||
* @brief Contains the Gfx11Lib class definition.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __GFX11_ADDR_LIB_H__
|
||||
#define __GFX11_ADDR_LIB_H__
|
||||
|
||||
#include "addrlib2.h"
|
||||
#include "coord.h"
|
||||
#include "gfx11SwizzlePattern.h"
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V2
|
||||
{
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief GFX11 specific settings structure.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
struct Gfx11ChipSettings
|
||||
{
|
||||
struct
|
||||
{
|
||||
UINT_32 isGfx1150 : 1;
|
||||
UINT_32 isPhoenix : 1;
|
||||
UINT_32 reserved1 : 30;
|
||||
|
||||
// Misc configuration bits
|
||||
UINT_32 reserved2 : 32;
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief GFX11 data surface type.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
enum Gfx11DataType
|
||||
{
|
||||
Gfx11DataColor,
|
||||
Gfx11DataDepthStencil,
|
||||
};
|
||||
|
||||
const UINT_32 Gfx11LinearSwModeMask = (1u << ADDR_SW_LINEAR);
|
||||
|
||||
const UINT_32 Gfx11Blk256BSwModeMask = (1u << ADDR_SW_256B_D);
|
||||
|
||||
const UINT_32 Gfx11Blk4KBSwModeMask = (1u << ADDR_SW_4KB_S) |
|
||||
(1u << ADDR_SW_4KB_D) |
|
||||
(1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_4KB_D_X);
|
||||
|
||||
const UINT_32 Gfx11Blk64KBSwModeMask = (1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_R_X);
|
||||
|
||||
const UINT_32 Gfx11Blk256KBSwModeMask = (1u << ADDR_SW_256KB_Z_X) |
|
||||
(1u << ADDR_SW_256KB_S_X) |
|
||||
(1u << ADDR_SW_256KB_D_X) |
|
||||
(1u << ADDR_SW_256KB_R_X);
|
||||
|
||||
const UINT_32 Gfx11ZSwModeMask = (1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_256KB_Z_X);
|
||||
|
||||
const UINT_32 Gfx11StandardSwModeMask = (1u << ADDR_SW_4KB_S) |
|
||||
(1u << ADDR_SW_64KB_S) |
|
||||
(1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_256KB_S_X);
|
||||
|
||||
const UINT_32 Gfx11DisplaySwModeMask = (1u << ADDR_SW_256B_D) |
|
||||
(1u << ADDR_SW_4KB_D) |
|
||||
(1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_4KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_256KB_D_X);
|
||||
|
||||
const UINT_32 Gfx11RenderSwModeMask = (1u << ADDR_SW_64KB_R_X) |
|
||||
(1u << ADDR_SW_256KB_R_X);
|
||||
|
||||
const UINT_32 Gfx11XSwModeMask = (1u << ADDR_SW_4KB_S_X) |
|
||||
(1u << ADDR_SW_4KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_S_X) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_R_X) |
|
||||
Gfx11Blk256KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11TSwModeMask = (1u << ADDR_SW_64KB_S_T) |
|
||||
(1u << ADDR_SW_64KB_D_T);
|
||||
|
||||
const UINT_32 Gfx11XorSwModeMask = Gfx11XSwModeMask |
|
||||
Gfx11TSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc1dSwModeMask = (1u << ADDR_SW_LINEAR) |
|
||||
(1u << ADDR_SW_64KB_R_X) |
|
||||
(1u << ADDR_SW_64KB_Z_X) ;
|
||||
|
||||
const UINT_32 Gfx11Rsrc2dSwModeMask = Gfx11LinearSwModeMask |
|
||||
Gfx11DisplaySwModeMask |
|
||||
Gfx11ZSwModeMask |
|
||||
Gfx11RenderSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dSwModeMask = Gfx11LinearSwModeMask |
|
||||
Gfx11StandardSwModeMask |
|
||||
Gfx11ZSwModeMask |
|
||||
Gfx11RenderSwModeMask |
|
||||
(1u << ADDR_SW_64KB_D_X);
|
||||
|
||||
const UINT_32 Gfx11Rsrc2dPrtSwModeMask =
|
||||
(Gfx11Blk4KBSwModeMask | Gfx11Blk64KBSwModeMask) & ~Gfx11XSwModeMask & Gfx11Rsrc2dSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dPrtSwModeMask =
|
||||
(Gfx11Blk4KBSwModeMask | Gfx11Blk64KBSwModeMask) & ~Gfx11XSwModeMask & Gfx11Rsrc3dSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThin64KBSwModeMask = (1u << ADDR_SW_64KB_Z_X) |
|
||||
(1u << ADDR_SW_64KB_R_X);
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThin256KBSwModeMask = (1u << ADDR_SW_256KB_Z_X) |
|
||||
(1u << ADDR_SW_256KB_R_X);
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThinSwModeMask = Gfx11Rsrc3dThin64KBSwModeMask | Gfx11Rsrc3dThin256KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dViewAs2dSwModeMask = Gfx11Rsrc3dThinSwModeMask | Gfx11LinearSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThickSwModeMask = Gfx11Rsrc3dSwModeMask & ~(Gfx11Rsrc3dThinSwModeMask | Gfx11LinearSwModeMask);
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThick4KBSwModeMask = Gfx11Rsrc3dThickSwModeMask & Gfx11Blk4KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThick64KBSwModeMask = Gfx11Rsrc3dThickSwModeMask & Gfx11Blk64KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11Rsrc3dThick256KBSwModeMask = Gfx11Rsrc3dThickSwModeMask & Gfx11Blk256KBSwModeMask;
|
||||
|
||||
const UINT_32 Gfx11MsaaSwModeMask = Gfx11ZSwModeMask |
|
||||
Gfx11RenderSwModeMask;
|
||||
|
||||
const UINT_32 Dcn32SwModeMask = (1u << ADDR_SW_LINEAR) |
|
||||
(1u << ADDR_SW_64KB_D) |
|
||||
(1u << ADDR_SW_64KB_D_T) |
|
||||
(1u << ADDR_SW_64KB_D_X) |
|
||||
(1u << ADDR_SW_64KB_R_X) |
|
||||
(1u << ADDR_SW_256KB_D_X) |
|
||||
(1u << ADDR_SW_256KB_R_X);
|
||||
|
||||
const UINT_32 Size256K = 262144u;
|
||||
const UINT_32 Log2Size256K = 18u;
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @brief This class is the GFX11 specific address library
|
||||
* function set.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
class Gfx11Lib : public Lib
|
||||
{
|
||||
public:
|
||||
/// Creates Gfx11Lib object
|
||||
static Addr::Lib* CreateObj(const Client* pClient)
|
||||
{
|
||||
VOID* pMem = Object::ClientAlloc(sizeof(Gfx11Lib), pClient);
|
||||
return (pMem != NULL) ? new (pMem) Gfx11Lib(pClient) : NULL;
|
||||
}
|
||||
|
||||
protected:
|
||||
Gfx11Lib(const Client* pClient);
|
||||
virtual ~Gfx11Lib();
|
||||
|
||||
BOOL_32 HwlIsStandardSwizzle(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isStd;
|
||||
}
|
||||
|
||||
BOOL_32 HwlIsDisplaySwizzle(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return m_swizzleModeTable[swizzleMode].isDisp;
|
||||
}
|
||||
|
||||
BOOL_32 HwlIsThin(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return ((IsTex1d(resourceType) == TRUE) ||
|
||||
(IsTex2d(resourceType) == TRUE) ||
|
||||
((IsTex3d(resourceType) == TRUE) &&
|
||||
(m_swizzleModeTable[swizzleMode].isStd == FALSE) &&
|
||||
(m_swizzleModeTable[swizzleMode].isDisp == FALSE)));
|
||||
}
|
||||
|
||||
BOOL_32 HwlIsThick(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const override final
|
||||
{
|
||||
return ((IsTex3d(resourceType) == TRUE) &&
|
||||
(m_swizzleModeTable[swizzleMode].isStd || m_swizzleModeTable[swizzleMode].isDisp));
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeHtileInfo(
|
||||
const ADDR2_COMPUTE_HTILE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeDccInfo(
|
||||
const ADDR2_COMPUTE_DCCINFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCCINFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeHtileAddrFromCoord(
|
||||
const ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_ADDRFROMCOORD_OUTPUT* pOut) override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeHtileCoordFromAddr(
|
||||
const ADDR2_COMPUTE_HTILE_COORDFROMADDR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_HTILE_COORDFROMADDR_OUTPUT* pOut) override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlSupportComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn) override final;
|
||||
|
||||
VOID HwlComputeDccAddrFromCoord(
|
||||
const ADDR2_COMPUTE_DCC_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_DCC_ADDRFROMCOORD_OUTPUT* pOut) override final;
|
||||
|
||||
UINT_32 HwlGetEquationIndex(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
UINT_32 HwlGetEquationTableInfo(const ADDR_EQUATION** ppEquationTable) const override final
|
||||
{
|
||||
*ppEquationTable = m_equationTable;
|
||||
|
||||
return m_numEquations;
|
||||
}
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputePipeBankXor(
|
||||
const ADDR2_COMPUTE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_PIPEBANKXOR_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSlicePipeBankXor(
|
||||
const ADDR2_COMPUTE_SLICE_PIPEBANKXOR_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SLICE_PIPEBANKXOR_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSubResourceOffsetForSwizzlePattern(
|
||||
const ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SUBRESOURCE_OFFSET_FORSWIZZLEPATTERN_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeNonBlockCompressedView(
|
||||
const ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_INPUT* pIn,
|
||||
ADDR2_COMPUTE_NONBLOCKCOMPRESSEDVIEW_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlGetPreferredSurfaceSetting(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlGetPossibleSwizzleModes(
|
||||
const ADDR2_GET_PREFERRED_SURF_SETTING_INPUT* pIn,
|
||||
ADDR2_GET_PREFERRED_SURF_SETTING_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlGetAllowedBlockSet(
|
||||
ADDR2_SWMODE_SET allowedSwModeSet,
|
||||
AddrResourceType rsrcType,
|
||||
ADDR2_BLOCK_SET* pAllowedBlockSet) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlGetAllowedSwSet(
|
||||
ADDR2_SWMODE_SET allowedSwModeSet,
|
||||
ADDR2_SWTYPE_SET* pAllowedSwSet) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceInfoSanityCheck(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceInfoTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceInfoLinear(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlComputeSurfaceAddrFromCoordTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlCopyMemToSurface(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const override final;
|
||||
|
||||
ADDR_E_RETURNCODE HwlCopySurfaceToMem(
|
||||
const ADDR2_COPY_MEMSURFACE_INPUT* pIn,
|
||||
const ADDR2_COPY_MEMSURFACE_REGION* pRegions,
|
||||
UINT_32 regionCount) const override final;
|
||||
|
||||
UINT_32 HwlComputeMaxBaseAlignments() const override final;
|
||||
|
||||
UINT_32 HwlComputeMaxMetaBaseAlignments() const override final;
|
||||
|
||||
BOOL_32 HwlInitGlobalParams(const ADDR_CREATE_INPUT* pCreateIn) override final;
|
||||
|
||||
ChipFamily HwlConvertChipFamily(UINT_32 uChipFamily, UINT_32 uChipRevision) override final;
|
||||
|
||||
private:
|
||||
// Initialize equation table
|
||||
VOID InitEquationTable();
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoMacroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceInfoMicroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_INFO_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordMacroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeSurfaceAddrFromCoordMicroTiled(
|
||||
const ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_INPUT* pIn,
|
||||
ADDR2_COMPUTE_SURFACE_ADDRFROMCOORD_OUTPUT* pOut) const;
|
||||
|
||||
UINT_32 ComputeOffsetFromEquation(
|
||||
const ADDR_EQUATION* pEq,
|
||||
UINT_32 x,
|
||||
UINT_32 y,
|
||||
UINT_32 z) const;
|
||||
|
||||
ADDR_E_RETURNCODE ComputeStereoInfo(
|
||||
const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn,
|
||||
UINT_32* pAlignY,
|
||||
UINT_32* pRightXor) const;
|
||||
|
||||
static void GetMipSize(
|
||||
UINT_32 mip0Width,
|
||||
UINT_32 mip0Height,
|
||||
UINT_32 mip0Depth,
|
||||
UINT_32 mipId,
|
||||
UINT_32* pMipWidth,
|
||||
UINT_32* pMipHeight,
|
||||
UINT_32* pMipDepth = NULL)
|
||||
{
|
||||
*pMipWidth = ShiftCeil(Max(mip0Width, 1u), mipId);
|
||||
*pMipHeight = ShiftCeil(Max(mip0Height, 1u), mipId);
|
||||
|
||||
if (pMipDepth != NULL)
|
||||
{
|
||||
*pMipDepth = ShiftCeil(Max(mip0Depth, 1u), mipId);
|
||||
}
|
||||
}
|
||||
|
||||
const ADDR_SW_PATINFO* GetSwizzlePatternInfo(
|
||||
AddrSwizzleMode swizzleMode,
|
||||
AddrResourceType resourceType,
|
||||
UINT_32 log2Elem,
|
||||
UINT_32 numFrag) const;
|
||||
|
||||
VOID GetSwizzlePatternFromPatternInfo(
|
||||
const ADDR_SW_PATINFO* pPatInfo,
|
||||
ADDR_BIT_SETTING (&pSwizzle)[ADDR_MAX_EQUATION_BIT]) const
|
||||
{
|
||||
memcpy(pSwizzle,
|
||||
GFX11_SW_PATTERN_NIBBLE01[pPatInfo->nibble01Idx],
|
||||
sizeof(GFX11_SW_PATTERN_NIBBLE01[pPatInfo->nibble01Idx]));
|
||||
|
||||
memcpy(&pSwizzle[8],
|
||||
GFX11_SW_PATTERN_NIBBLE2[pPatInfo->nibble2Idx],
|
||||
sizeof(GFX11_SW_PATTERN_NIBBLE2[pPatInfo->nibble2Idx]));
|
||||
|
||||
memcpy(&pSwizzle[12],
|
||||
GFX11_SW_PATTERN_NIBBLE3[pPatInfo->nibble3Idx],
|
||||
sizeof(GFX11_SW_PATTERN_NIBBLE3[pPatInfo->nibble3Idx]));
|
||||
|
||||
memcpy(&pSwizzle[16],
|
||||
GFX11_SW_PATTERN_NIBBLE4[pPatInfo->nibble4Idx],
|
||||
sizeof(GFX11_SW_PATTERN_NIBBLE4[pPatInfo->nibble4Idx]));
|
||||
}
|
||||
|
||||
VOID ConvertSwizzlePatternToEquation(
|
||||
UINT_32 elemLog2,
|
||||
AddrResourceType rsrcType,
|
||||
AddrSwizzleMode swMode,
|
||||
const ADDR_SW_PATINFO* pPatInfo,
|
||||
ADDR_EQUATION* pEquation) const;
|
||||
|
||||
static INT_32 GetMetaElementSizeLog2(Gfx11DataType dataType);
|
||||
|
||||
static INT_32 GetMetaCacheSizeLog2(Gfx11DataType dataType);
|
||||
|
||||
void GetBlk256SizeLog2(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2,
|
||||
Dim3d* pBlock) const;
|
||||
|
||||
void GetCompressedBlockSizeLog2(
|
||||
Gfx11DataType dataType,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2,
|
||||
Dim3d* pBlock) const;
|
||||
|
||||
INT_32 GetMetaOverlapLog2(
|
||||
Gfx11DataType dataType,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2) const;
|
||||
|
||||
INT_32 Get3DMetaOverlapLog2(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2) const;
|
||||
|
||||
UINT_32 GetMetaBlkSize(
|
||||
Gfx11DataType dataType,
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode,
|
||||
UINT_32 elemLog2,
|
||||
UINT_32 numSamplesLog2,
|
||||
BOOL_32 pipeAlign,
|
||||
Dim3d* pBlock) const;
|
||||
|
||||
INT_32 GetPipeRotateAmount(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const;
|
||||
|
||||
INT_32 GetEffectiveNumPipes() const
|
||||
{
|
||||
return ((m_numSaLog2 + 1) >= m_pipesLog2) ? m_pipesLog2 : m_numSaLog2 + 1;
|
||||
}
|
||||
|
||||
BOOL_32 IsRbAligned(
|
||||
AddrResourceType resourceType,
|
||||
AddrSwizzleMode swizzleMode) const
|
||||
{
|
||||
const BOOL_32 isRtopt = IsRtOptSwizzle(swizzleMode);
|
||||
const BOOL_32 isZ = IsZOrderSwizzle(swizzleMode);
|
||||
const BOOL_32 isDisplay = IsDisplaySwizzle(swizzleMode);
|
||||
|
||||
return (IsTex2d(resourceType) && (isRtopt || isZ)) ||
|
||||
(IsTex3d(resourceType) && isDisplay);
|
||||
|
||||
}
|
||||
|
||||
UINT_32 GetValidDisplaySwizzleModes(UINT_32 bpp) const;
|
||||
|
||||
BOOL_32 IsValidDisplaySwizzleMode(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const override final;
|
||||
|
||||
UINT_32 GetMaxNumMipsInTail(UINT_32 blockSizeLog2, BOOL_32 isThin) const;
|
||||
|
||||
BOOL_32 IsInMipTail(
|
||||
Dim3d mipTailDim,
|
||||
UINT_32 maxNumMipsInTail,
|
||||
UINT_32 mipWidth,
|
||||
UINT_32 mipHeight,
|
||||
UINT_32 numMipsToTheEnd) const
|
||||
{
|
||||
BOOL_32 inTail = ((mipWidth <= mipTailDim.w) &&
|
||||
(mipHeight <= mipTailDim.h) &&
|
||||
(numMipsToTheEnd <= maxNumMipsInTail));
|
||||
|
||||
return inTail;
|
||||
}
|
||||
|
||||
UINT_32 GetBankXorBits(UINT_32 blockBits) const
|
||||
{
|
||||
return (blockBits > m_pipeInterleaveLog2 + m_pipesLog2 + ColumnBits) ?
|
||||
Min(blockBits - m_pipeInterleaveLog2 - m_pipesLog2 - ColumnBits, BankBits) : 0;
|
||||
}
|
||||
|
||||
BOOL_32 ValidateNonSwModeParams(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
BOOL_32 ValidateSwModeParams(const ADDR2_COMPUTE_SURFACE_INFO_INPUT* pIn) const;
|
||||
|
||||
BOOL_32 IsBlock256kb(AddrSwizzleMode swizzleMode) const { return IsBlockVariable(swizzleMode); }
|
||||
|
||||
// TODO: figure out if there is any Column bits on GFX11...
|
||||
static const UINT_32 ColumnBits = 2;
|
||||
static const UINT_32 BankBits = 4;
|
||||
static const UINT_32 UnalignedDccType = 3;
|
||||
|
||||
static const Dim3d Block256_3d[MaxNumOfBpp];
|
||||
static const Dim3d Block256K_Log2_3d[MaxNumOfBpp];
|
||||
static const Dim3d Block64K_Log2_3d[MaxNumOfBpp];
|
||||
static const Dim3d Block4K_Log2_3d[MaxNumOfBpp];
|
||||
|
||||
static const SwizzleModeFlags SwizzleModeTable[ADDR_SW_MAX_TYPE];
|
||||
|
||||
// Number of packers log2
|
||||
UINT_32 m_numPkrLog2;
|
||||
// Number of shader array log2
|
||||
UINT_32 m_numSaLog2;
|
||||
|
||||
Gfx11ChipSettings m_settings;
|
||||
|
||||
UINT_32 m_colorBaseIndex;
|
||||
UINT_32 m_htileBaseIndex;
|
||||
UINT_32 m_dccBaseIndex;
|
||||
};
|
||||
|
||||
} // V2
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
/*
|
||||
************************************************************************************************************************
|
||||
*
|
||||
* Copyright (C) 2022-2024 Advanced Micro Devices, Inc. All rights reserved.
|
||||
* SPDX-License-Identifier: MIT
|
||||
*
|
||||
***********************************************************************************************************************/
|
||||
|
||||
/**
|
||||
************************************************************************************************************************
|
||||
* @file gfx12SwizzlePattern.h
|
||||
* @brief swizzle pattern for gfx12.
|
||||
************************************************************************************************************************
|
||||
*/
|
||||
|
||||
#ifndef __GFX12_SWIZZLE_PATTERN_H__
|
||||
#define __GFX12_SWIZZLE_PATTERN_H__
|
||||
|
||||
namespace Addr
|
||||
{
|
||||
namespace V3
|
||||
{
|
||||
const ADDR_SW_PATINFO GFX12_SW_256B_2D_1xAA_PATINFO[] =
|
||||
{
|
||||
{ 0, 0, 0, 0, } , // 1 BPE @ SW_256B_2D_1xAA
|
||||
{ 1, 0, 0, 0, } , // 2 BPE @ SW_256B_2D_1xAA
|
||||
{ 2, 0, 0, 0, } , // 4 BPE @ SW_256B_2D_1xAA
|
||||
{ 3, 0, 0, 0, } , // 8 BPE @ SW_256B_2D_1xAA
|
||||
{ 4, 0, 0, 0, } , // 16 BPE @ SW_256B_2D_1xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256B_2D_2xAA_PATINFO[] =
|
||||
{
|
||||
{ 5, 0, 0, 0, } , // 1 BPE @ SW_256B_2D_2xAA
|
||||
{ 6, 0, 0, 0, } , // 2 BPE @ SW_256B_2D_2xAA
|
||||
{ 7, 0, 0, 0, } , // 4 BPE @ SW_256B_2D_2xAA
|
||||
{ 8, 0, 0, 0, } , // 8 BPE @ SW_256B_2D_2xAA
|
||||
{ 9, 0, 0, 0, } , // 16 BPE @ SW_256B_2D_2xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256B_2D_4xAA_PATINFO[] =
|
||||
{
|
||||
{ 10, 0, 0, 0, } , // 1 BPE @ SW_256B_2D_4xAA
|
||||
{ 11, 0, 0, 0, } , // 2 BPE @ SW_256B_2D_4xAA
|
||||
{ 12, 0, 0, 0, } , // 4 BPE @ SW_256B_2D_4xAA
|
||||
{ 13, 0, 0, 0, } , // 8 BPE @ SW_256B_2D_4xAA
|
||||
{ 14, 0, 0, 0, } , // 16 BPE @ SW_256B_2D_4xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256B_2D_8xAA_PATINFO[] =
|
||||
{
|
||||
{ 15, 0, 0, 0, } , // 1 BPE @ SW_256B_2D_8xAA
|
||||
{ 16, 0, 0, 0, } , // 2 BPE @ SW_256B_2D_8xAA
|
||||
{ 17, 0, 0, 0, } , // 4 BPE @ SW_256B_2D_8xAA
|
||||
{ 18, 0, 0, 0, } , // 8 BPE @ SW_256B_2D_8xAA
|
||||
{ 19, 0, 0, 0, } , // 16 BPE @ SW_256B_2D_8xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_4KB_2D_1xAA_PATINFO[] =
|
||||
{
|
||||
{ 0, 1, 0, 0, } , // 1 BPE @ SW_4KB_2D_1xAA
|
||||
{ 1, 2, 0, 0, } , // 2 BPE @ SW_4KB_2D_1xAA
|
||||
{ 2, 3, 0, 0, } , // 4 BPE @ SW_4KB_2D_1xAA
|
||||
{ 3, 4, 0, 0, } , // 8 BPE @ SW_4KB_2D_1xAA
|
||||
{ 4, 5, 0, 0, } , // 16 BPE @ SW_4KB_2D_1xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_4KB_2D_2xAA_PATINFO[] =
|
||||
{
|
||||
{ 5, 2, 0, 0, } , // 1 BPE @ SW_4KB_2D_2xAA
|
||||
{ 6, 3, 0, 0, } , // 2 BPE @ SW_4KB_2D_2xAA
|
||||
{ 7, 4, 0, 0, } , // 4 BPE @ SW_4KB_2D_2xAA
|
||||
{ 8, 5, 0, 0, } , // 8 BPE @ SW_4KB_2D_2xAA
|
||||
{ 9, 6, 0, 0, } , // 16 BPE @ SW_4KB_2D_2xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_4KB_2D_4xAA_PATINFO[] =
|
||||
{
|
||||
{ 10, 3, 0, 0, } , // 1 BPE @ SW_4KB_2D_4xAA
|
||||
{ 11, 4, 0, 0, } , // 2 BPE @ SW_4KB_2D_4xAA
|
||||
{ 12, 5, 0, 0, } , // 4 BPE @ SW_4KB_2D_4xAA
|
||||
{ 13, 6, 0, 0, } , // 8 BPE @ SW_4KB_2D_4xAA
|
||||
{ 14, 7, 0, 0, } , // 16 BPE @ SW_4KB_2D_4xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_4KB_2D_8xAA_PATINFO[] =
|
||||
{
|
||||
{ 15, 4, 0, 0, } , // 1 BPE @ SW_4KB_2D_8xAA
|
||||
{ 16, 5, 0, 0, } , // 2 BPE @ SW_4KB_2D_8xAA
|
||||
{ 17, 6, 0, 0, } , // 4 BPE @ SW_4KB_2D_8xAA
|
||||
{ 18, 7, 0, 0, } , // 8 BPE @ SW_4KB_2D_8xAA
|
||||
{ 19, 8, 0, 0, } , // 16 BPE @ SW_4KB_2D_8xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_64KB_2D_1xAA_PATINFO[] =
|
||||
{
|
||||
{ 0, 1, 1, 0, } , // 1 BPE @ SW_64KB_2D_1xAA
|
||||
{ 1, 2, 2, 0, } , // 2 BPE @ SW_64KB_2D_1xAA
|
||||
{ 2, 3, 3, 0, } , // 4 BPE @ SW_64KB_2D_1xAA
|
||||
{ 3, 4, 4, 0, } , // 8 BPE @ SW_64KB_2D_1xAA
|
||||
{ 4, 5, 5, 0, } , // 16 BPE @ SW_64KB_2D_1xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_64KB_2D_2xAA_PATINFO[] =
|
||||
{
|
||||
{ 5, 2, 2, 0, } , // 1 BPE @ SW_64KB_2D_2xAA
|
||||
{ 6, 3, 3, 0, } , // 2 BPE @ SW_64KB_2D_2xAA
|
||||
{ 7, 4, 4, 0, } , // 4 BPE @ SW_64KB_2D_2xAA
|
||||
{ 8, 5, 5, 0, } , // 8 BPE @ SW_64KB_2D_2xAA
|
||||
{ 9, 6, 6, 0, } , // 16 BPE @ SW_64KB_2D_2xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_64KB_2D_4xAA_PATINFO[] =
|
||||
{
|
||||
{ 10, 3, 3, 0, } , // 1 BPE @ SW_64KB_2D_4xAA
|
||||
{ 11, 4, 4, 0, } , // 2 BPE @ SW_64KB_2D_4xAA
|
||||
{ 12, 5, 5, 0, } , // 4 BPE @ SW_64KB_2D_4xAA
|
||||
{ 13, 6, 6, 0, } , // 8 BPE @ SW_64KB_2D_4xAA
|
||||
{ 14, 7, 7, 0, } , // 16 BPE @ SW_64KB_2D_4xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_64KB_2D_8xAA_PATINFO[] =
|
||||
{
|
||||
{ 15, 4, 4, 0, } , // 1 BPE @ SW_64KB_2D_8xAA
|
||||
{ 16, 5, 5, 0, } , // 2 BPE @ SW_64KB_2D_8xAA
|
||||
{ 17, 6, 6, 0, } , // 4 BPE @ SW_64KB_2D_8xAA
|
||||
{ 18, 7, 7, 0, } , // 8 BPE @ SW_64KB_2D_8xAA
|
||||
{ 19, 8, 8, 0, } , // 16 BPE @ SW_64KB_2D_8xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256KB_2D_1xAA_PATINFO[] =
|
||||
{
|
||||
{ 0, 1, 1, 1, } , // 1 BPE @ SW_256KB_2D_1xAA
|
||||
{ 1, 2, 2, 2, } , // 2 BPE @ SW_256KB_2D_1xAA
|
||||
{ 2, 3, 3, 3, } , // 4 BPE @ SW_256KB_2D_1xAA
|
||||
{ 3, 4, 4, 4, } , // 8 BPE @ SW_256KB_2D_1xAA
|
||||
{ 4, 5, 5, 5, } , // 16 BPE @ SW_256KB_2D_1xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256KB_2D_2xAA_PATINFO[] =
|
||||
{
|
||||
{ 5, 2, 2, 2, } , // 1 BPE @ SW_256KB_2D_2xAA
|
||||
{ 6, 3, 3, 3, } , // 2 BPE @ SW_256KB_2D_2xAA
|
||||
{ 7, 4, 4, 4, } , // 4 BPE @ SW_256KB_2D_2xAA
|
||||
{ 8, 5, 5, 5, } , // 8 BPE @ SW_256KB_2D_2xAA
|
||||
{ 9, 6, 6, 6, } , // 16 BPE @ SW_256KB_2D_2xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256KB_2D_4xAA_PATINFO[] =
|
||||
{
|
||||
{ 10, 3, 3, 3, } , // 1 BPE @ SW_256KB_2D_4xAA
|
||||
{ 11, 4, 4, 4, } , // 2 BPE @ SW_256KB_2D_4xAA
|
||||
{ 12, 5, 5, 5, } , // 4 BPE @ SW_256KB_2D_4xAA
|
||||
{ 13, 6, 6, 6, } , // 8 BPE @ SW_256KB_2D_4xAA
|
||||
{ 14, 7, 7, 7, } , // 16 BPE @ SW_256KB_2D_4xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256KB_2D_8xAA_PATINFO[] =
|
||||
{
|
||||
{ 15, 4, 4, 4, } , // 1 BPE @ SW_256KB_2D_8xAA
|
||||
{ 16, 5, 5, 5, } , // 2 BPE @ SW_256KB_2D_8xAA
|
||||
{ 17, 6, 6, 6, } , // 4 BPE @ SW_256KB_2D_8xAA
|
||||
{ 18, 7, 7, 7, } , // 8 BPE @ SW_256KB_2D_8xAA
|
||||
{ 19, 8, 8, 8, } , // 16 BPE @ SW_256KB_2D_8xAA
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_4KB_3D_PATINFO[] =
|
||||
{
|
||||
{ 20, 9, 0, 0, } , // 1 BPE @ SW_4KB_3D
|
||||
{ 21, 10, 0, 0, } , // 2 BPE @ SW_4KB_3D
|
||||
{ 22, 11, 0, 0, } , // 4 BPE @ SW_4KB_3D
|
||||
{ 23, 12, 0, 0, } , // 8 BPE @ SW_4KB_3D
|
||||
{ 24, 13, 0, 0, } , // 16 BPE @ SW_4KB_3D
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_64KB_3D_PATINFO[] =
|
||||
{
|
||||
{ 20, 9, 9, 0, } , // 1 BPE @ SW_64KB_3D
|
||||
{ 21, 10, 10, 0, } , // 2 BPE @ SW_64KB_3D
|
||||
{ 22, 11, 11, 0, } , // 4 BPE @ SW_64KB_3D
|
||||
{ 23, 12, 12, 0, } , // 8 BPE @ SW_64KB_3D
|
||||
{ 24, 13, 13, 0, } , // 16 BPE @ SW_64KB_3D
|
||||
};
|
||||
|
||||
const ADDR_SW_PATINFO GFX12_SW_256KB_3D_PATINFO[] =
|
||||
{
|
||||
{ 20, 9, 9, 9, } , // 1 BPE @ SW_256KB_3D
|
||||
{ 21, 10, 10, 9, } , // 2 BPE @ SW_256KB_3D
|
||||
{ 22, 11, 11, 10, } , // 4 BPE @ SW_256KB_3D
|
||||
{ 23, 12, 12, 11, } , // 8 BPE @ SW_256KB_3D
|
||||
{ 24, 13, 13, 11, } , // 16 BPE @ SW_256KB_3D
|
||||
};
|
||||
|
||||
|
||||
const UINT_64 GFX12_SW_PATTERN_NIBBLE1[][8] =
|
||||
{
|
||||
{X0, X1, Y0, X2, Y1, Y2, X3, Y3, }, // 0
|
||||
{0, X0, Y0, X1, Y1, X2, Y2, X3, }, // 1
|
||||
{0, 0, X0, Y0, X1, Y1, X2, Y2, }, // 2
|
||||
{0, 0, 0, X0, Y0, X1, X2, Y1, }, // 3
|
||||
{0, 0, 0, 0, X0, Y0, X1, Y1, }, // 4
|
||||
{S0, X0, Y0, X1, Y1, X2, Y2, X3, }, // 5
|
||||
{0, S0, X0, Y0, X1, Y1, X2, Y2, }, // 6
|
||||
{0, 0, S0, X0, Y0, X1, Y1, X2, }, // 7
|
||||
{0, 0, 0, S0, X0, Y0, X1, Y1, }, // 8
|
||||
{0, 0, 0, 0, S0, X0, Y0, X1, }, // 9
|
||||
{S0, S1, X0, Y0, X1, Y1, X2, Y2, }, // 10
|
||||
{0, S0, S1, X0, Y0, X1, Y1, X2, }, // 11
|
||||
{0, 0, S0, S1, X0, Y0, X1, Y1, }, // 12
|
||||
{0, 0, 0, S0, S1, X0, Y0, X1, }, // 13
|
||||
{0, 0, 0, 0, S0, S1, X0, Y0, }, // 14
|
||||
{S0, S1, S2, X0, Y0, X1, Y1, X2, }, // 15
|
||||
{0, S0, S1, S2, X0, Y0, X1, Y1, }, // 16
|
||||
{0, 0, S0, S1, S2, X0, Y0, X1, }, // 17
|
||||
{0, 0, 0, S0, S1, S2, X0, Y0, }, // 18
|
||||
{0, 0, 0, 0, S0, S1, S2, X0, }, // 19
|
||||
{X0, X1, Z0, Y0, Y1, Z1, X2, Z2, }, // 20
|
||||
{0, X0, Z0, Y0, X1, Z1, Y1, Z2, }, // 21
|
||||
{0, 0, X0, Y0, X1, Z0, Y1, Z1, }, // 22
|
||||
{0, 0, 0, X0, Y0, Z0, X1, Z1, }, // 23
|
||||
{0, 0, 0, 0, X0, Z0, Y0, Z1, }, // 24
|
||||
};
|
||||
|
||||
const UINT_64 GFX12_SW_PATTERN_NIBBLE2[][4] =
|
||||
{
|
||||
{0, 0, 0, 0, }, // 0
|
||||
{Y4, X4, Y5, X5, }, // 1
|
||||
{Y3, X4, Y4, X5, }, // 2
|
||||
{Y3, X3, Y4, X4, }, // 3
|
||||
{Y2, X3, Y3, X4, }, // 4
|
||||
{Y2, X2, Y3, X3, }, // 5
|
||||
{Y1, X2, Y2, X3, }, // 6
|
||||
{Y1, X1, Y2, X2, }, // 7
|
||||
{Y0, X1, Y1, X2, }, // 8
|
||||
{Y2, X3, Z3, Y3, }, // 9
|
||||
{Y2, X2, Z3, Y3, }, // 10
|
||||
{Y2, X2, Z2, Y3, }, // 11
|
||||
{Y1, X2, Z2, Y2, }, // 12
|
||||
{Y1, X1, Z2, Y2, }, // 13
|
||||
};
|
||||
|
||||
const UINT_64 GFX12_SW_PATTERN_NIBBLE3[][4] =
|
||||
{
|
||||
{0, 0, 0, 0, }, // 0
|
||||
{Y6, X6, Y7, X7, }, // 1
|
||||
{Y5, X6, Y6, X7, }, // 2
|
||||
{Y5, X5, Y6, X6, }, // 3
|
||||
{Y4, X5, Y5, X6, }, // 4
|
||||
{Y4, X4, Y5, X5, }, // 5
|
||||
{Y3, X4, Y4, X5, }, // 6
|
||||
{Y3, X3, Y4, X4, }, // 7
|
||||
{Y2, X3, Y3, X4, }, // 8
|
||||
{X4, Z4, Y4, X5, }, // 9
|
||||
{X3, Z4, Y4, X4, }, // 10
|
||||
{X3, Z3, Y4, X4, }, // 11
|
||||
{X3, Z3, Y3, X4, }, // 12
|
||||
{X2, Z3, Y3, X3, }, // 13
|
||||
};
|
||||
|
||||
const UINT_64 GFX12_SW_PATTERN_NIBBLE4[][2] =
|
||||
{
|
||||
{0, 0, }, // 0
|
||||
{Y8, X8, }, // 1
|
||||
{Y7, X8, }, // 2
|
||||
{Y7, X7, }, // 3
|
||||
{Y6, X7, }, // 4
|
||||
{Y6, X6, }, // 5
|
||||
{Y5, X6, }, // 6
|
||||
{Y5, X5, }, // 7
|
||||
{Y4, X5, }, // 8
|
||||
{Z5, Y5, }, // 9
|
||||
{Z4, Y5, }, // 10
|
||||
{Z4, Y4, }, // 11
|
||||
};
|
||||
|
||||
} // V3
|
||||
} // Addr
|
||||
|
||||
#endif
|
||||
Loaded 100 of 181 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user